,code_before,comment,code_after
0,"public void initialize(IManagedForm form) { super.initialize(form); fwkContentProvider.onContentReady(new Success<List<OSGiFramework>,Void>() { @Override public Promise<Void> call(Promise<List<OSGiFramework>> resolved) throws Exception { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { refreshFromModel(); } }); <START> return Promises.resolved(null); <END> } }); frameworkViewer.setInput(model.getWorkspace()); }",return null here,"public void initialize(IManagedForm form) { super.initialize(form); fwkContentProvider.onContentReady(new Success<List<OSGiFramework>,Void>() { @Override public Promise<Void> call(Promise<List<OSGiFramework>> resolved) throws Exception { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { refreshFromModel(); } }); return null; } }); frameworkViewer.setInput(model.getWorkspace()); }"
1,"protected void handleError(final Exception e, final String correlationUid, final String organisationIdentification, final String deviceIdentification, final String messageType) { LOGGER.error(""Handling error for message type: "" + messageType, e); OsgpException osgpException = null; if (e instanceof OsgpException) { osgpException = (OsgpException) e; } else { osgpException = new TechnicalException(ComponentType.DOMAIN_CORE, ""An unknown error occurred"", e); } <START> this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() <END> .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(ResponseMessageResultType.NOT_OK) .withOsgpException(osgpException).withDataObject(e).build()); }","Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage","protected void handleError(final Exception e, final String correlationUid, final String organisationIdentification, final String deviceIdentification, final String messageType) { LOGGER.error(""Handling error for message type: "" + messageType, e); OsgpException osgpException = null; if (e instanceof OsgpException) { osgpException = (OsgpException) e; } else { osgpException = new TechnicalException(ComponentType.DOMAIN_CORE, ""An unknown error occurred"", e); } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(ResponseMessageResultType.NOT_OK) .withOsgpException(osgpException).withDataObject(e).build(); this.webServiceResponseMessageSender.send(responseMessage); }"
2,public EventBuilder setEventData(Eventful entity) { if (entity != null) { if (entity instanceof Named && ((Named) entity).getName() != null) { event.setTargetName(((Named) entity).getName()); } if (entity instanceof Owned) { Owner entityOwner = ((Owned) entity).getOwner(); if (entityOwner != null && entityOwner.getId() != null) { event.setOwnerId(entityOwner.getId()); } } if (entity instanceof Entitlement) { event.setReferenceType(Event.ReferenceType.POOL); Pool referencedPool = ((Entitlement) entity).getPool(); if (referencedPool != null && referencedPool.getId() != null) { event.setReferenceId(referencedPool.getId()); } } if ((String) entity.getId() != null) { event.setEntityId((String) entity.getId()); if (entity instanceof ConsumerProperty) { Consumer owningConsumer = ((ConsumerProperty) entity).getConsumer(); if (owningConsumer != null && owningConsumer.getId() != null) { event.setConsumerId(owningConsumer.getId()); } } } <START> factory.entityToJson(entity); <END> } return this; },"java protected String entityToJson(Object entity) { String newEntityJson = """"; // TODO: Throw auditing exception // Drop data consumer do want serialized, Jackson // care XmlTransient annotations here: try { newEntityJson = mapper.writeValueAsString(entity); } catch (Exception e) { log.warn(""Unable jsonify: "" + entity); log.error(""jsonification failed!"", e); } return newEntityJson; } is run entityToJson. I side effects happen in code",public EventBuilder setEventData(Eventful entity) { if (entity != null) { if (entity instanceof Named && ((Named) entity).getName() != null) { event.setTargetName(((Named) entity).getName()); } if (entity instanceof Owned) { Owner entityOwner = ((Owned) entity).getOwner(); if (entityOwner != null && entityOwner.getId() != null) { event.setOwnerId(entityOwner.getId()); } } if (entity instanceof Entitlement) { event.setReferenceType(Event.ReferenceType.POOL); Pool referencedPool = ((Entitlement) entity).getPool(); if (referencedPool != null && referencedPool.getId() != null) { event.setReferenceId(referencedPool.getId()); } } if ((String) entity.getId() != null) { event.setEntityId((String) entity.getId()); if (entity instanceof ConsumerProperty) { Consumer owningConsumer = ((ConsumerProperty) entity).getConsumer(); if (owningConsumer != null && owningConsumer.getId() != null) { event.setConsumerId(owningConsumer.getId()); } } } } return this; }
3,"<START> public void getSetBits(int batchSize, boolean[] vector) <END> throws IOException { for (int i = 0; i < batchSize; i++) { vector[i] = nextBit(); } }","@dain, this return int in aligning getUnsetBits? existing getSetBits (write bits a BlockBuilder) returns void tough","public int getSetBits(int batchSize, boolean[] vector) throws IOException { int count = 0; for (int i = 0; i < batchSize; i++) { vector[i] = nextBit(); count += vector[i] ? 1 : 0; } return count; }"
4,"public void testSetupInvalidChildFromBaseClass() throws Exception { final TestBean testBean = new TestBean(); final DefaultConfiguration conf = new DefaultConfiguration(""testConf""); final Field field = AutomaticBean.class.getDeclaredField(""configuration""); field.setAccessible(true); field.set(testBean, conf); try { testBean.setupChild(conf); fail(""expecting checkstyle exception""); } catch (CheckstyleException ex) { <START> assertEquals(""expected exception"", ""testConf is not allowed as a child in testConf"", <END> ex.getMessage()); } }",@rnveach I name for parent child confuse,"public void testSetupInvalidChildFromBaseClass() throws Exception { final TestBean testBean = new TestBean(); final DefaultConfiguration parentConf = new DefaultConfiguration(""parentConf""); final DefaultConfiguration childConf = new DefaultConfiguration(""childConf""); final Field field = AutomaticBean.class.getDeclaredField(""configuration""); field.setAccessible(true); field.set(testBean, parentConf); try { testBean.setupChild(childConf); fail(""expecting checkstyle exception""); } catch (CheckstyleException ex) { assertEquals(""expected exception"", ""childConf is not allowed as a child in parentConf"", ex.getMessage()); } }"
5,"public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) { <START> Assert.notNull(result, ""'result' must not be null""); <END> return (Mono<Void>) result.getReturnValue(); }","I this is reported issue; problem is result.getReturnValue() return null, is allowed handleResult contract","public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) { Object returnValue = result.getReturnValue(); return returnValue == null ? Mono.empty() : (Mono<Void>) returnValue; }"
6,"protected void moveOrCopyAllImageGroups(Guid containerID, Iterable<DiskImage> disks) { for (DiskImage disk : disks) { ActionReturnValue vdcRetValue = runInternalActionWithTasksContext( ActionType.CopyImageGroup, buildMoveOrCopyImageGroupParametersForDisk(disk, containerID)); if (!vdcRetValue.getSucceeded()) { throw new EngineException(vdcRetValue.getFault().getError(), ""Failed to copy disk!""); } <START> getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); <END> } }",I assume behavior ExportVmCommand. Do need this,"protected void moveOrCopyAllImageGroups(Guid containerID, Iterable<DiskImage> disks) { for (DiskImage disk : disks) { ActionReturnValue vdcRetValue = runInternalActionWithTasksContext( ActionType.CopyImageGroup, buildMoveOrCopyImageGroupParametersForDisk(disk, containerID)); if (!vdcRetValue.getSucceeded()) { throw new EngineException(vdcRetValue.getFault().getError(), ""Failed to copy disk!""); } getTaskIdList().addAll(vdcRetValue.getVdsmTaskIdList()); } }"
7,"private void onPreviewImage(DocDisplay docDisplay, String href, Position position, Range tokenRange) { String srcPath = href; if (!href.startsWith(""http"")) { srcPath = href.startsWith(""~/"") <START> ? ""files/"" + href.substring(2) <END> : ""file_show?path="" + StringUtil.encodeURIComponent(href); } String encoded = StringUtil.encodeURIComponent(srcPath); Element el = Document.get().getElementById(encoded); if (el != null) return; ImageElement imgEl = Document.get().createImageElement(); imgEl.setAttribute(""src"", srcPath); imgEl.getStyle().setProperty(""maxWidth"", ""100px""); ScreenCoordinates coordinates = docDisplay.documentPositionToScreenCoordinates(position); AnchoredPopupPanel panel = new AnchoredPopupPanel(docDisplay, tokenRange); panel.getElement().setId(encoded); panel.getElement().appendChild(imgEl); panel.setPopupPosition(coordinates.getPageX(), coordinates.getPageY() + 20); panel.show(); }",do need do special for Windows directory separators,"private void onPreviewImage(DocDisplay docDisplay, String href, Position position, Range tokenRange) { String srcPath = imgSrcPathFromHref(href); String encoded = StringUtil.encodeURIComponent(srcPath); Element el = Document.get().getElementById(encoded); if (el != null) return; AnchoredPopupPanel panel = new AnchoredPopupPanel(docDisplay, tokenRange, srcPath); panel.getElement().setId(encoded); ScreenCoordinates coordinates = docDisplay.documentPositionToScreenCoordinates(position); panel.setPopupPosition(coordinates.getPageX(), coordinates.getPageY() + 20); panel.show(); }"
8,"<START> public boolean isPeerReplicaLeaderForPartition(String partitionName, ReplicaId replicaId) { <END> rwLock.readLock().lock(); try { return peerLeaderReplicasByPartition.containsKey(partitionName) && peerLeaderReplicasByPartition.get( partitionName).contains(replicaId); } finally { rwLock.readLock().unlock(); } }",this method used,"public boolean isPeerReplicaLeaderForPartition(String partitionName, ReplicaId replicaId) { rwLock.readLock().lock(); try { return peerLeaderReplicasByPartition.getOrDefault(partitionName, Collections.emptySet()).contains(replicaId); } finally { rwLock.readLock().unlock(); } }"
9,"public boolean isDTS() { <START> return getCodecA() != null && (getCodecA().startsWith(""dts"") || ""dca"".equals(getCodecA()) || ""dca (dts)"".equals(getCodecA())); <END> }","return getCodecA() != null && (""dts"".contains(getCodecA()) || ""dca"".contains(getCodecA()));","public boolean isDTS() { return getCodecA() != null && (getCodecA().contains(""dts"") || getCodecA().contains(""dca"")); }"
10,"public IntervalList getLociToGenotype(final Collection<Fingerprint> fingerprints) { final IntervalList intervals = new IntervalList(this.haplotypes.getHeader()); for (final Fingerprint fp : fingerprints) { for (final HaplotypeProbabilities genotype : fp.values()) { final HaplotypeBlock h = genotype.getHaplotype(); for (final Snp snp : h.getSnps()) { intervals.add(new Interval(snp.getChrom(), snp.getPos(), snp.getPos(), false, snp.getName())); } } } <START> return intervals.sorted().uniqued(); <END> }",uniqued imply sorted,"public IntervalList getLociToGenotype(final Collection<Fingerprint> fingerprints) { final IntervalList intervals = new IntervalList(this.haplotypes.getHeader()); for (final Fingerprint fp : fingerprints) { for (final HaplotypeProbabilities genotype : fp.values()) { final HaplotypeBlock h = genotype.getHaplotype(); for (final Snp snp : h.getSnps()) { intervals.add(new Interval(snp.getChrom(), snp.getPos(), snp.getPos(), false, snp.getName())); } } } return intervals.uniqued(); }"
11,"protected String updateACHAccountIfNecessary(Person payee, PayeeACHAccountExtractDetail achDetail, PayeeACHAccount achAccount) { StringBuilder processingResults = new StringBuilder(); if (accountHasChanged(achDetail, achAccount)) { PayeeACHData achData = new PayeeACHData(payee, achDetail, achAccount.getPayeeIdentifierTypeCode(), achAccount); String accountUpdateErrors = createAndRoutePayeeACHAccountDocument(achData, this::setupDocumentForACHUpdate); processingResults.append(accountUpdateErrors); } else { <START> LOG.info(""Input file's account information for payee of type '"" + achAccount.getPayeeIdentifierTypeCode() <END> + ""' matches what is already in KFS; no updates will be made for this entry.""); } if (processingResults.length() > 0) { processingResults.append("" Update was NOT performed.""); LOG.warn(""updateACHAccountIfNecessary: "" + processingResults.toString()); } return processingResults.toString(); }",Missing method name,"protected String updateACHAccountIfNecessary(Person payee, PayeeACHAccountExtractDetail achDetail, PayeeACHAccount achAccount) { StringBuilder processingResults = new StringBuilder(); if (accountHasChanged(achDetail, achAccount)) { PayeeACHData achData = new PayeeACHData(payee, achDetail, achAccount.getPayeeIdentifierTypeCode(), achAccount); String accountUpdateErrors = createAndRoutePayeeACHAccountDocument(achData, this::setupDocumentForACHUpdate); processingResults.append(accountUpdateErrors); } else { LOG.info(""updateACHAccountIfNecessary: Input file's account information for payee of type '"" + achAccount.getPayeeIdentifierTypeCode() + ""' matches what is already in KFS; no updates will be made for this entry.""); } if (processingResults.length() > 0) { processingResults.append("" Update was NOT performed.""); LOG.warn(""updateACHAccountIfNecessary: "" + processingResults.toString()); } return processingResults.toString(); }"
12,"public void shouldSaveCondition() throws DotSecurityException, DotDataException { final Role role = new RoleDataGen().nextPersisted(); final User user = new UserDataGen().roles(role).nextPersisted(); final Host host = new SiteDataGen().nextPersisted(); final Rule rule = new RuleDataGen().host(host).nextPersisted(); final ConditionGroup conditionGroup = new ConditionGroupDataGen().rule(rule).next(); <START> this.addRulesPermission(role, host, true); <END> rulesAPI.saveConditionGroup(conditionGroup, user, false); List<Rule> allRules = rulesAPI.getAllRules(user, false); checkCondition(user, conditionGroup, allRules); }",create a variable for parameter understand boolean addPublishPermsForRules = true;,"public void shouldSaveCondition() throws DotSecurityException, DotDataException { final Role role = new RoleDataGen().nextPersisted(); final User user = new UserDataGen().roles(role).nextPersisted(); final Host host = new SiteDataGen().nextPersisted(); final Rule rule = new RuleDataGen().host(host).nextPersisted(); final ConditionGroup conditionGroup = new ConditionGroupDataGen().rule(rule).next(); addRulesPublishPermissions(role, host); rulesAPI.saveConditionGroup(conditionGroup, user, false); List<Rule> allRules = rulesAPI.getAllRules(user, false); createConditionAndCheck(user, conditionGroup, allRules); }"
13,"public synchronized void clearCache(HelixConstants.ChangeType changeType) { switch (changeType) { case LIVE_INSTANCE: case INSTANCE_CONFIG: <START> LOG.warn(""clearCache is deprecated for changeType: "" + changeType); <END> break; case EXTERNAL_VIEW: _externalViewCache.clear(); break; default: break; } }","nit: For new log, please do this """"clearCache is deprecated for changeType: {}"", changeType"". Minor performance improvement if config log level error","public synchronized void clearCache(HelixConstants.ChangeType changeType) { switch (changeType) { case LIVE_INSTANCE: case INSTANCE_CONFIG: LOG.warn(""clearCache is deprecated for changeType: {}."", changeType); break; case EXTERNAL_VIEW: _externalViewCache.clear(); break; default: break; } }"
14,"public List<RassXmlAgencyEntry> sortRassXmlAgencyEntriesForUpdate(List<RassXmlAgencyEntry> agencies) { AgenciesSortHelper agencySortHelper = new AgenciesSortHelper(); sortAgenciesWithNoReportsToAgency(agencies, agencySortHelper); sortAgenciesWithReportsToAgencyThatHasBeenSorted(agencySortHelper); <START> sortLeftOverAgencies(agencySortHelper); <END> return agencySortHelper.sortedAgencies; }",left agencies: agencies reports agency sorted? sense update method name more descriptive,"public List<RassXmlAgencyEntry> sortRassXmlAgencyEntriesForUpdate(List<RassXmlAgencyEntry> agencies) { AgenciesSortHelper agencySortHelper = new AgenciesSortHelper(); sortAgenciesWithNoReportsToAgency(agencies, agencySortHelper); sortAgenciesWithReportsToAgencyThatHasBeenSorted(agencySortHelper); sortAnyUnsortedAgencies(agencySortHelper); return agencySortHelper.sortedAgencies; }"
15,"private void handleCreateTableMutationCode(MetaDataMutationResult result, MutationCode code, CreateTableStatement statement, String schemaName, String tableName, PTable parent) throws SQLException { switch(code) { case NEWER_TABLE_FOUND: if (!statement.ifNotExists()) { throw new NewerTableAlreadyExistsException(schemaName, tableName, result.getTable()); } case UNALLOWED_TABLE_MUTATION: throw new SQLExceptionInfo.Builder(SQLExceptionCode.CANNOT_MUTATE_TABLE) .setSchemaName(schemaName).setTableName(tableName).build().buildException(); case CONCURRENT_TABLE_MUTATION: addTableToCache(result); throw new ConcurrentTableMutationException(schemaName, tableName); case AUTO_PARTITION_SEQUENCE_NOT_FOUND: case CANNOT_COERCE_AUTO_PARTITION_ID: case UNABLE_TO_CREATE_CHILD_LINK: case PARENT_TABLE_NOT_FOUND: case TABLE_NOT_IN_REGION: <START> throwsSQLExceptionUtil(String.valueOf(code), schemaName, tableName); <END> case TOO_MANY_INDEXES: case UNABLE_TO_UPDATE_PARENT_TABLE: throwsSQLExceptionUtil(String.valueOf(code), SchemaUtil.getSchemaNameFromFullName( parent.getPhysicalName().getString()),SchemaUtil.getTableNameFromFullName( parent.getPhysicalName().getString())); default: throw new SQLException(""Exception occurred while creating table Mutation code:"" + code.toString()); } }",nice simplification,"public boolean handleCreateTableMutationCode(MetaDataMutationResult result, MutationCode code, CreateTableStatement statement, String schemaName, String tableName, PTable parent) throws SQLException { switch(code) { case TABLE_ALREADY_EXISTS: if(result.getTable() != null) { addTableToCache(result); } if(!statement.ifNotExists()) { throw new TableAlreadyExistsException(schemaName, tableName, result.getTable()); } return true; case NEWER_TABLE_FOUND: if (!statement.ifNotExists()) { throw new NewerTableAlreadyExistsException(schemaName, tableName, result.getTable()); } return false; case UNALLOWED_TABLE_MUTATION: throwsSQLExceptionUtil(""CANNOT_MUTATE_TABLE"",schemaName,tableName); case CONCURRENT_TABLE_MUTATION: addTableToCache(result); throw new ConcurrentTableMutationException(schemaName, tableName); case AUTO_PARTITION_SEQUENCE_NOT_FOUND: throw new SQLExceptionInfo.Builder(SQLExceptionCode.AUTO_PARTITION_SEQUENCE_UNDEFINED) .setSchemaName(schemaName).setTableName(tableName).build().buildException(); case CANNOT_COERCE_AUTO_PARTITION_ID: case UNABLE_TO_CREATE_CHILD_LINK: case PARENT_TABLE_NOT_FOUND: case TABLE_NOT_IN_REGION: throwsSQLExceptionUtil(String.valueOf(code), schemaName, tableName); case TOO_MANY_INDEXES: case UNABLE_TO_UPDATE_PARENT_TABLE: throwsSQLExceptionUtil(String.valueOf(code), SchemaUtil.getSchemaNameFromFullName( parent.getPhysicalName().getString()),SchemaUtil.getTableNameFromFullName( parent.getPhysicalName().getString())); default: throw new SQLExceptionInfo.Builder(SQLExceptionCode.UNEXPECTED_MUTATION_CODE) .setSchemaName(schemaName).setTableName(tableName).setMessage(""mutation code: "" + code).build().buildException(); } }"
16,"public void process(JSONRequestContext jsonRequestContext) { StudentGroupContactLogEntryDAO logEntryDAO = DAOFactory.getInstance().getStudentGroupContactLogEntryDAO(); try { Long entryId = jsonRequestContext.getLong(""entryId""); <START> StudentGroupContactLogEntry entry = logEntryDAO.findById(entryId); <END> String entryText = jsonRequestContext.getRequest().getParameter(""entryText""); String entryCreator = jsonRequestContext.getRequest().getParameter(""entryCreatorName""); Date entryDate = new Date(NumberUtils.createLong(jsonRequestContext.getRequest().getParameter(""entryDate""))); StudentContactLogEntryType entryType = StudentContactLogEntryType.valueOf(jsonRequestContext.getString(""entryType"")); logEntryDAO.update(entry, entryType, entryText, entryDate, entryCreator); Map<String, Object> info = new HashMap<String, Object>(); info.put(""id"", entry.getId()); info.put(""creatorName"", entry.getCreatorName()); info.put(""timestamp"", entry.getEntryDate().getTime()); info.put(""text"", entry.getText()); info.put(""type"", entry.getType()); info.put(""studentGroupId"", entry.getStudentGroup().getId()); jsonRequestContext.addResponseParameter(""results"", info); } catch (Exception e) { throw new SmvcRuntimeException(e); } }",Null-check,"public void process(JSONRequestContext jsonRequestContext) { StudentGroupContactLogEntryDAO logEntryDAO = DAOFactory.getInstance().getStudentGroupContactLogEntryDAO(); Long entryId = jsonRequestContext.getLong(""entryId""); if (entryId == null) throw new SmvcRuntimeException(StatusCode.UNDEFINED, ""EntryId was not defined.""); try { StudentGroupContactLogEntry entry = logEntryDAO.findById(entryId); String entryText = jsonRequestContext.getString(""entryText""); String entryCreator = jsonRequestContext.getString(""entryCreatorName""); Date entryDate = jsonRequestContext.getDate(""entryDate""); StudentContactLogEntryType entryType = StudentContactLogEntryType.valueOf(jsonRequestContext.getString(""entryType"")); logEntryDAO.update(entry, entryType, entryText, entryDate, entryCreator); Map<String, Object> info = new HashMap<String, Object>(); info.put(""id"", entry.getId()); info.put(""creatorName"", entry.getCreatorName()); info.put(""timestamp"", entry.getEntryDate() != null ? entry.getEntryDate().getTime() : """"); info.put(""text"", entry.getText()); info.put(""type"", entry.getType()); info.put(""studentGroupId"", entry.getStudentGroup().getId()); jsonRequestContext.addResponseParameter(""results"", info); } catch (Exception e) { throw new SmvcRuntimeException(e); } }"
17,"private void execute() { if (fFinishedLatch.getCount() == 0) { return; } synchronized (syncObj) { if (fStarted) { return; } fStarted = true; } if (fTrace != null) { fTrace.notifyPendingRequest(true); } fJob = new Job(NLS.bind(Messages.TmfAbstractAnalysisModule_RunningAnalysis, getName())) { @Override protected IStatus run(final IProgressMonitor monitor) { try { monitor.beginTask("""", IProgressMonitor.UNKNOWN); broadcast(new TmfStartAnalysisSignal(TmfAbstractAnalysisModule.this, TmfAbstractAnalysisModule.this)); fAnalysisCancelled = !executeAnalysis(monitor); if (fTrace != null) { <START> fTrace.notifyPendingRequest(false); <END> } } catch (TmfAnalysisException e) { Activator.logError(""Error executing analysis with trace "" + getTrace().getName(), e); } finally { synchronized (syncObj) { monitor.done(); setAnalysisCompleted(); } } if (!fAnalysisCancelled) { return Status.OK_STATUS; } return Status.CANCEL_STATUS; } @Override protected void canceling() { TmfAbstractAnalysisModule.this.canceling(); } }; fJob.schedule(); }","I I this is this relies analysis module's developer forget decrement request flag else blocks forever. default behavior is block. add a function analysisHasRequest() { return false; } notifyPendingRequest(true) occur if analysisHasRequest is true. way, developer controls calls. if overwrites method decrement pending request flag. And, if ignores methods, a request, then, well... coalesced end of world. catch a review if code gerrit ;-)","private void execute() { if (fFinishedLatch.getCount() == 0) { return; } synchronized (syncObj) { if (fStarted) { return; } fStarted = true; } if (fTrace != null) { fTrace.notifyPendingRequest(true); setNotifyRequestNeeded(true); } fJob = new Job(NLS.bind(Messages.TmfAbstractAnalysisModule_RunningAnalysis, getName())) { @Override protected IStatus run(final IProgressMonitor monitor) { try { monitor.beginTask("""", IProgressMonitor.UNKNOWN); broadcast(new TmfStartAnalysisSignal(TmfAbstractAnalysisModule.this, TmfAbstractAnalysisModule.this)); fAnalysisCancelled = !executeAnalysis(monitor); if ((fTrace != null) && isNotifyRequestNeeded()) { fTrace.notifyPendingRequest(false); setNotifyRequestNeeded(false); } } catch (TmfAnalysisException e) { Activator.logError(""Error executing analysis with trace "" + getTrace().getName(), e); } finally { synchronized (syncObj) { monitor.done(); setAnalysisCompleted(); } } if (!fAnalysisCancelled) { return Status.OK_STATUS; } return Status.CANCEL_STATUS; } @Override protected void canceling() { TmfAbstractAnalysisModule.this.canceling(); } }; fJob.schedule(); }"
18,"public int execute() throws HiveException { DataOutputStream outStream = getOutputStream(ddlDesc.getResFile()); try { Database database = db.getDatabase(ddlDesc.getDatabaseName()); if (database == null) { throw new HiveException(ErrorMsg.DATABASE_NOT_EXISTS, ddlDesc.getDatabaseName()); } Map<String, String> params = null; if (ddlDesc.isExt()) { params = database.getParameters(); } if (HiveConf.getBoolVar(conf, HiveConf.ConfVars.HIVE_IN_TEST) && params != null) { params = new TreeMap<String, String>(params); } String location = database.getLocationUri(); if (HiveConf.getBoolVar(conf, HiveConf.ConfVars.HIVE_IN_TEST)) { location = ""location/in/test""; } <START> <END> PrincipalType ownerType = database.getOwnerType(); formatter.showDatabaseDescription(outStream, database.getName(), database.getDescription(), location, database.getOwnerName(), (null == ownerType) ? null : ownerType.name(), params); } catch (Exception e) { throw new HiveException(e, ErrorMsg.GENERIC_ERROR); } finally { IOUtils.closeStream(outStream); } return 0; }",do this alwregardless in test; this means is order in desc command outputs props is undefined running tests..,"public int execute() throws HiveException { try (DataOutputStream outStream = getOutputStream(new Path(desc.getResFile()))) { Database database = context.getDb().getDatabase(desc.getDatabaseName()); if (database == null) { throw new HiveException(ErrorMsg.DATABASE_NOT_EXISTS, desc.getDatabaseName()); } Map<String, String> params = null; if (desc.isExt()) { params = database.getParameters(); } if (HiveConf.getBoolVar(context.getConf(), HiveConf.ConfVars.HIVE_IN_TEST) && params != null) { params = new TreeMap<String, String>(params); } String location = database.getLocationUri(); if (HiveConf.getBoolVar(context.getConf(), HiveConf.ConfVars.HIVE_IN_TEST)) { location = ""location/in/test""; } PrincipalType ownerType = database.getOwnerType(); context.getFormatter().showDatabaseDescription(outStream, database.getName(), database.getDescription(), location, database.getOwnerName(), (null == ownerType) ? null : ownerType.name(), params); } catch (Exception e) { throw new HiveException(e, ErrorMsg.GENERIC_ERROR); } return 0; }"
19,"public boolean isMatch(String relativeTarget, boolean isDirectory) { if (relativeTarget == null) { return false; } relativeTarget = <START> stripTrailing(relativeTarget, <END> FastIgnoreRule.PATH_SEPARATOR); if (relativeTarget.length() == 0) { return false; } boolean match = matcher.matches(relativeTarget, isDirectory); return match; }","I decided strip trailing slashes here. caller care if is ""dir"" ""dir/"", get ""native git"" behavior. I decided do this in PathMatcher, is more generic this implications ignore rules, I overlook right now","public boolean isMatch(String relativeTarget, boolean isDirectory) { if (relativeTarget == null) return false; if (relativeTarget.length() == 0) return false; boolean match = matcher.matches(relativeTarget, isDirectory); return match; }"
20,"private void connector(IProject prj) { try { IRemoteConnection irc = Util.getRemoteConnection(prj); if(irc == null) return; <START> Activator.log(""Connection for project: '"" + prj.getName() + ""' is '"" + irc + ""'""); END> Activator.log(""Connection address is "" + irc.getAddress()); final ITerminalView tvr = (ITerminalView) PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage() .showView(""org.eclipse.tm.terminal.view.TerminalView""); ITerminalConnector[] itcarray = TerminalConnectorExtension .makeTerminalConnectors(); int remoteTools = -1; for (int i = 0; i < itcarray.length; i++) { if(""Remote Tools"".equals(itcarray[i].getName()) || ""Remote Services"".equals(itcarray[i].getName()) || ""org.eclipse.ptp.remote.internal.terminal.RemoteToolsConnector"".equals(itcarray[i].getId())) { remoteTools = i; break; } } if(itcarray.length==0) { Activator.log(""Could not find a terminal connection for ""+prj.getName()); return; } if(remoteTools >= 0) { final ITerminalConnector inner = itcarray[remoteTools]; Activator.log(""inner=""+inner.getId()+"",""+inner.getName()+"",""+inner.getSettingsSummary()); ITerminalConnector connector = inner; ISettingsStore store = new HashSettingsStore(); connector.save(store); store.put(RemoteSettings.PROJECT_NAME, prj.getName()); connector.load(store); tvr.newTerminal(connector); } } catch (CoreException e1) { Activator.log(e1); } }",Logging needs conditional a debug option removed,"private void connector(IProject prj) { try { IRemoteConnection irc = Util.getRemoteConnection(prj); if(irc == null) return; final ITerminalView tvr = (ITerminalView) PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage() .showView(""org.eclipse.tm.terminal.view.TerminalView""); final ITerminalConnector inner = TerminalConnectorExtension.makeTerminalConnector(""org.eclipse.ptp.remote.internal.terminal.RemoteToolsConnector""); ITerminalConnector connector = inner; ISettingsStore store = new HashSettingsStore(); connector.save(store); store.put(RemoteSettings.PROJECT_NAME, prj.getName()); connector.load(store); tvr.newTerminal(connector); } catch (CoreException e1) { Activator.log(e1); } }"
21,"private WaiterTimeoutCallback(final Callback<T> callback) { _timeout = new SingleTimeout<>(_timeoutExecutor, _waiterTimeout, TimeUnit.MILLISECONDS, callback, (callback1) -> { synchronized (_lock) { _waiters.remove(this); _statsTracker.incrementWaiterTimedOut(); } LOG.debug(""{}: failing waiter due to waiter timeout"", _poolName); <START> callback1.onError( <END> new WaiterTimeoutException( ""Exceeded waiter timeout of "" + _waiterTimeout + ""ms: in Pool: ""+ _poolName)); }); }","I put a number in callback variable, like: callbackIfTimeout","private WaiterTimeoutCallback(final Callback<T> callback) { _timeout = new SingleTimeout<>(_timeoutExecutor, _waiterTimeout, TimeUnit.MILLISECONDS, callback, (callbackIfTimeout) -> { synchronized (_lock) { _waiters.remove(this); _statsTracker.incrementWaiterTimedOut(); } LOG.debug(""{}: failing waiter due to waiter timeout"", _poolName); callbackIfTimeout.onError( new WaiterTimeoutException( ""Exceeded waiter timeout of "" + _waiterTimeout + ""ms: in Pool: ""+ _poolName)); }); }"
22,"public long sizeAsLong() { <START> if (!transaction.isReadCommitted() && !transaction.isReadUncommitted()) { <END> return sizeAsLongSlow(); } Snapshot<K,VersionedValue<V>> snapshot; RootReference<Long,Record<?,?>>[] undoLogRootReferences; do { snapshot = getSnapshot(); undoLogRootReferences = getTransaction().getUndoLogRootReferences(); } while (!snapshot.equals(getSnapshot())); RootReference<K,VersionedValue<V>> mapRootReference = snapshot.root; BitSet committingTransactions = snapshot.committingTransactions; long size = mapRootReference.getTotalCount(); long undoLogsTotalSize = undoLogRootReferences == null ? size : TransactionStore.calculateUndoLogsTotalSize(undoLogRootReferences); if (undoLogsTotalSize == 0) { return size; } if (transaction.isReadUncommitted()) { return size; } if (2 * undoLogsTotalSize > size) { Cursor<K, VersionedValue<V>> cursor = map.cursor(mapRootReference, null, null, false); while(cursor.hasNext()) { cursor.next(); VersionedValue<?> currentValue = cursor.getValue(); assert currentValue != null; long operationId = currentValue.getOperationId(); if (operationId != 0 && isIrrelevant(operationId, currentValue, committingTransactions)) { --size; } } } else { assert undoLogRootReferences != null; for (RootReference<Long,Record<?,?>> undoLogRootReference : undoLogRootReferences) { if (undoLogRootReference != null) { Cursor<Long, Record<?, ?>> cursor = undoLogRootReference.root.map.cursor(undoLogRootReference, null, null, false); while (cursor.hasNext()) { cursor.next(); Record<?,?> op = cursor.getValue(); if (op.mapId == map.getId()) { @SuppressWarnings(""unchecked"") VersionedValue<V> currentValue = map.get(mapRootReference.root, (K)op.key); if (currentValue != null) { long operationId = cursor.getKey(); assert operationId != 0; if (currentValue.getOperationId() == operationId && isIrrelevant(operationId, currentValue, committingTransactions)) { --size; } } } } } } } return size; }",if (!transaction.allowNonRepeatableRead()),"public long sizeAsLong() { if (!transaction.allowNonRepeatableRead()) { return sizeAsLongSlow(); } Snapshot<K,VersionedValue<V>> snapshot; RootReference<Long,Record<?,?>>[] undoLogRootReferences; do { snapshot = getSnapshot(); undoLogRootReferences = getTransaction().getUndoLogRootReferences(); } while (!snapshot.equals(getSnapshot())); RootReference<K,VersionedValue<V>> mapRootReference = snapshot.root; BitSet committingTransactions = snapshot.committingTransactions; long size = mapRootReference.getTotalCount(); if (!transaction.isReadCommitted()) { return size; } long undoLogsTotalSize = undoLogRootReferences == null ? size : TransactionStore.calculateUndoLogsTotalSize(undoLogRootReferences); if (undoLogsTotalSize == 0) { return size; } if (2 * undoLogsTotalSize > size) { Cursor<K, VersionedValue<V>> cursor = map.cursor(mapRootReference, null, null, false); while(cursor.hasNext()) { cursor.next(); VersionedValue<?> currentValue = cursor.getValue(); assert currentValue != null; long operationId = currentValue.getOperationId(); if (operationId != 0 && isIrrelevant(operationId, currentValue, committingTransactions)) { --size; } } } else { assert undoLogRootReferences != null; for (RootReference<Long,Record<?,?>> undoLogRootReference : undoLogRootReferences) { if (undoLogRootReference != null) { Cursor<Long, Record<?, ?>> cursor = undoLogRootReference.root.map.cursor(undoLogRootReference, null, null, false); while (cursor.hasNext()) { cursor.next(); Record<?,?> op = cursor.getValue(); if (op.mapId == map.getId()) { @SuppressWarnings(""unchecked"") VersionedValue<V> currentValue = map.get(mapRootReference.root, (K)op.key); if (currentValue != null) { long operationId = cursor.getKey(); assert operationId != 0; if (currentValue.getOperationId() == operationId && isIrrelevant(operationId, currentValue, committingTransactions)) { --size; } } } } } } } return size; }"
23,"private static Uri getFileUriFromMediaStoreUri(@NonNull Context context, @NonNull Uri photoUri) { final Cursor cursor = context.getContentResolver().query(photoUri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null); if (null == cursor) { return null; } try { <START> cursor.moveToFirst(); <END> if (cursor.getCount() <= 0 || cursor.getColumnCount() <= 0) { return null; } final String data = cursor.getString(0); if (TextUtils.isEmpty(data)) { return null; } return Uri.fromFile(new File(data)); } finally { cursor.close(); } }","more optimized function. @Nullable private static Uri getFileUriFromMediaStoreUri(@NonNull Context context, @NonNull Uri photoUri) { final Cursor cursor = context.getContentResolver().query(photoUri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null); if (null == cursor) { return null; } try { if (cursor.moveToFirst()) { final String data = cursor.getString(0); if (TextUtils.isEmpty(data)) { return null; } return Uri.fromFile(new File(data)); } } finally { cursor.close(); } return null; }","private static Uri getFileUriFromMediaStoreUri(@NonNull Context context, @NonNull Uri photoUri) { final Cursor cursor = context.getContentResolver().query(photoUri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null); if (null == cursor) { return null; } try { if (cursor.moveToFirst() && cursor.getColumnCount() > 0) { final String data = cursor.getString(0); if (TextUtils.isEmpty(data)) { return null; } return Uri.fromFile(new File(data)); } } finally { cursor.close(); } return null; }"
24,"void emitEscapedContent(int c) throws IOException { if (c == '\\') { super.emitContent(""&#92;""); } else { <START> if (c == '{' || c == '\\' <END> || c == '[' || c == ']') { super.emitContent('\\'); } super.emitContent(c); } }",I want remove this... character content (that's entity reference) properly,"void emitEscapedContent(int c) throws IOException { if (c == '\\') { super.emitContent(""&#92;""); } else { if ((c == '#' && getLastChar() == '&') || (c == '{' || c == '\\' || c == '[' || c == ']')) { super.emitContent('\\'); } super.emitContent(c); } }"
25,"public synchronized void start() { logger.debug(""start Thread""); if (shutdown) { shutdown = false; if (schedduler2 == null || getManagerState() == ManagerStates.stopped) { <START> this.pollingRunnable = new PollingRunnable(); <END> schedduler2 = new Thread(pollingRunnable); schedduler2.start(); } sceneMan.start(); } if (sceneJobExecuter != null) { this.sceneJobExecuter.startExecuter(); } if (sensorJobExecuter != null) { this.sensorJobExecuter.startExecuter(); } }","simply call scheduler.schedule(new PollingRunnable(), 0, POLLING_FREQUENCY)","public synchronized void start() { logger.debug(""start pollingScheduler""); if (pollingScheduler == null || pollingScheduler.isCancelled()) { pollingScheduler = scheduler.scheduleAtFixedRate(new PollingRunnable(), 0, config.getPollingFrequency(), TimeUnit.MILLISECONDS); sceneMan.start(); } if (sceneJobExecutor != null) { this.sceneJobExecutor.startExecutor(); } if (sensorJobExecutor != null) { this.sensorJobExecutor.startExecutor(); } }"
26,"public void spec203_blackbox_mustNotCallMethodsOnSubscriptionOrPublisherInOnComplete() throws Throwable { blackboxSubscriberWithoutSetupTest(new BlackboxTestStageTestRun() { @Override public void run(BlackboxTestStage stage) throws Throwable { final Subscription subs = new Subscription() { @Override public void request(long n) { final Throwable thr = new Throwable(); for (StackTraceElement stackElem : thr.getStackTrace()) { if (stackElem.getMethodName().equals(""onComplete"")) { <START> env.flop(String.format(""Subscription::request MUST NOT be called from Subscriber::onComplete! (Caller: %s::%s line %d)"", <END> stackElem.getClassName(), stackElem.getMethodName(), stackElem.getLineNumber())); } } } @Override public void cancel() { final Throwable thr = new Throwable(); for (StackTraceElement stackElem : thr.getStackTrace()) { if (stackElem.getMethodName().equals(""onComplete"")) { env.flop(String.format(""Subscription::cancel MUST NOT be called from Subscriber::onComplete! (Caller: %s::%s line %d)"", stackElem.getClassName(), stackElem.getMethodName(), stackElem.getLineNumber())); } } } }; final Subscriber<T> sub = createSubscriber(); sub.onSubscribe(subs); sub.onComplete(); env.verifyNoAsyncErrors(); } }); }",want give implementor rule prohibits this look,"public void spec203_blackbox_mustNotCallMethodsOnSubscriptionOrPublisherInOnComplete() throws Throwable { blackboxSubscriberWithoutSetupTest(new BlackboxTestStageTestRun() { @Override public void run(BlackboxTestStage stage) throws Throwable { final Subscription subs = new Subscription() { @Override public void request(long n) { final Optional<StackTraceElement> onCompleteStackTraceElement = env.findCallerMethodInStackTrace(""onComplete""); if (onCompleteStackTraceElement.isDefined()) { final StackTraceElement stackElem = onCompleteStackTraceElement.get(); env.flop(String.format(""Subscription::request MUST NOT be called from Subscriber::onComplete (Rule 2.3)! (Caller: %s::%s line %d)"", stackElem.getClassName(), stackElem.getMethodName(), stackElem.getLineNumber())); } } @Override public void cancel() { final Optional<StackTraceElement> onCompleteStackElement = env.findCallerMethodInStackTrace(""onComplete""); if (onCompleteStackElement.isDefined()) { final StackTraceElement stackElem = onCompleteStackElement.get(); env.flop(String.format(""Subscription::cancel MUST NOT be called from Subscriber::onComplete (Rule 2.3)! (Caller: %s::%s line %d)"", stackElem.getClassName(), stackElem.getMethodName(), stackElem.getLineNumber())); } } }; final Subscriber<T> sub = createSubscriber(); sub.onSubscribe(subs); sub.onComplete(); env.verifyNoAsyncErrors(); } }); }"
27,"private void onStart() { if (!mIsRunning) { return; } mAnimatedDrawableDiagnostics.onStartMethodBegin(); try { mStartTimeMs = mMonotonicClock.now(); mStartTimeMs -= resumable ? mAnimatedDrawableBackend.getTimestampMsForFrame(mPauseFrameNumber) : 0; mScheduledFrameNumber = resumable ? mPauseFrameNumber : 0; <START> mScheduledFrameMonotonicNumber = resumable ? mPauseFrameNumber : 0; <END> long nextFrameMs = mStartTimeMs + mAnimatedDrawableBackend.getDurationMsForFrame(0); scheduleSelf(mNextFrameTask, nextFrameMs); mNextFrameTaskMs = nextFrameMs; doInvalidateSelf(); } finally { mAnimatedDrawableDiagnostics.onStartMethodEnd(); } }",if/else block this readable,"private void onStart() { if (!mIsRunning) { return; } mAnimatedDrawableDiagnostics.onStartMethodBegin(); try { mStartTimeMs = mMonotonicClock.now(); if (mIsPaused) { mStartTimeMs -= mAnimatedDrawableBackend.getTimestampMsForFrame(mScheduledFrameNumber); } else { mScheduledFrameNumber = 0; mScheduledFrameMonotonicNumber = 0; } long nextFrameMs = mStartTimeMs + mAnimatedDrawableBackend.getDurationMsForFrame(0); scheduleSelf(mNextFrameTask, nextFrameMs); mNextFrameTaskMs = nextFrameMs; doInvalidateSelf(); } finally { mAnimatedDrawableDiagnostics.onStartMethodEnd(); } }"
28,"private MockHttpServletRequest requestToSave() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerPort(443); request.setSecure(true); request.setScheme(""https""); request.setServerName(""abc.com""); request.setRequestURI(""/destination""); <START> request.setServletPath(""/destination""); <END> request.setQueryString(""param1=a&param2=b&param3=1122""); return request; }",set servlet path for this test pass,"private MockHttpServletRequest requestToSave() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerPort(443); request.setSecure(true); request.setScheme(""https""); request.setServerName(""abc.com""); request.setRequestURI(""/destination""); request.setQueryString(""param1=a&param2=b&param3=1122""); return request; }"
29,"public ReadOnlyTableException(String message) { <START> super(SQLExceptionInfo.getNewInfoObject(code).setMessage(message).toString(), code.getSQLState()); <END> }",for message - remove if get it,"public ReadOnlyTableException(String message) { super(new SQLExceptionInfo.Builder(code).setMessage(message).toString(), code.getSQLState()); }"
30,"private Mac getMacInstance() { int masterKeyLatestHashCode = this.credential.getKey().hashCode(); if (masterKeyLatestHashCode != this.masterKeyHashCode) { <START> synchronized (this.credential) { <END> if (masterKeyLatestHashCode != this.masterKeyHashCode) { byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8); byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes); SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, ""HMACSHA256""); try { Mac macInstance = Mac.getInstance(""HMACSHA256""); macInstance.init(signingKey); this.masterKeyHashCode = masterKeyLatestHashCode; this.macInstance = macInstance; } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new IllegalStateException(e); } } } } try { return (Mac)this.macInstance.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } }","I concerned this synchronized code piece, this called request. concern is this slow things. Do need synchronized block credential is volatile",private Mac getMacInstance() { reInitializeIfPossible(); try { return (Mac)this.macInstance.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } }
31,<START> public final void close() throws Exception { <END> if (this.contextManager != null) { this.contextManager.close(); } operatorImplGraph.close(); },"again, I wondering, is thinking making close() final, process() non-final",public void close() throws Exception { if (this.contextManager != null) { this.contextManager.close(); } operatorImplGraph.close(); }
32,"public void compare() { setUpWithJson(SAMPLE_JSON); List<Element> elements = Arrays.stream(getFeatureByName(""Second feature"").getElements()) .filter(Element::isScenario) .collect(Collectors.toList()); assertThat(elements.get(0)).usingComparator(new ElementComparator()).isEqualTo(elements.get(0)); assertThat(elements.get(0)).usingComparator(new ElementComparator()).isNotEqualTo(elements.get(1)); <START> assertThat(elements.get(0)).usingComparator(new ElementComparator()).isNotEqualTo(null); <END> }",isNotNull(),"public void compare() { setUpWithJson(SAMPLE_JSON); List<Element> elements = Arrays.stream(getFeatureByName(""Second feature"").getElements()) .filter(Element::isScenario) .collect(Collectors.toList()); assertThat(elements.get(0)).usingComparator(new ElementComparator()).isEqualTo(elements.get(0)); assertThat(elements.get(0)).usingComparator(new ElementComparator()).isNotEqualTo(elements.get(1)); assertThat(elements.get(0)).usingComparator(new ElementComparator()).isNotNull(); }"
33,"public void start() { if (getBoolean(IGNITE_JVM_PAUSE_DETECTOR_DISABLED, DEFAULT_JVM_PAUSE_DETECTOR_DISABLED)) { if (log.isDebugEnabled()) log.debug(""JVM Pause Detector is disabled.""); return; } <START> lastWakeUpTime = System.currentTimeMillis(); <END> final Thread worker = new Thread(""jvm-pause-detector-worker"") { @Override public void run() { if (log.isDebugEnabled()) log.debug(getName() + "" has been started.""); while (true) { try { Thread.sleep(PRECISION); final long now = System.currentTimeMillis(); final long pause = now - PRECISION - lastWakeUpTime; if (pause >= THRESHOLD) { log.warning(""Possible too long JVM pause: "" + pause + "" milliseconds.""); synchronized (LongJVMPauseDetector.this) { final int next = (int)(longPausesCnt % EVT_CNT); longPausesCnt++; longPausesTotalDuration += pause; longPausesTimestamps[next] = now; longPausesDurations[next] = pause; lastWakeUpTime = now; } } else { synchronized (LongJVMPauseDetector.this) { lastWakeUpTime = now; } } } catch (InterruptedException e) { if (workerRef.compareAndSet(this, null)) log.error(getName() + "" has been interrupted."", e); else if (log.isDebugEnabled()) log.debug(getName() + "" has been stopped.""); break; } } } }; if (!workerRef.compareAndSet(null, worker)) { log.warning(LongJVMPauseDetector.class.getSimpleName() + "" already started!""); return; } worker.setDaemon(true); worker.start(); if (log.isDebugEnabled()) log.debug(""LongJVMPauseDetector was successfully started""); }","u initialize of new Thread(""jvm-pause-detector-worker"") scope","public void start() { if (DISABLED) { if (log.isDebugEnabled()) log.debug(""JVM Pause Detector is disabled.""); return; } final Thread worker = new Thread(""jvm-pause-detector-worker"") { @Override public void run() { synchronized (LongJVMPauseDetector.this) { lastWakeUpTime = System.currentTimeMillis(); } if (log.isDebugEnabled()) log.debug(getName() + "" has been started.""); while (true) { try { Thread.sleep(PRECISION); final long now = System.currentTimeMillis(); final long pause = now - PRECISION - lastWakeUpTime; if (pause >= THRESHOLD) { log.warning(""Possible too long JVM pause: "" + pause + "" milliseconds.""); synchronized (LongJVMPauseDetector.this) { final int next = (int)(longPausesCnt % EVT_CNT); longPausesCnt++; longPausesTotalDuration += pause; longPausesTimestamps[next] = now; longPausesDurations[next] = pause; lastWakeUpTime = now; } } else { synchronized (LongJVMPauseDetector.this) { lastWakeUpTime = now; } } } catch (InterruptedException e) { if (workerRef.compareAndSet(this, null)) log.error(getName() + "" has been interrupted."", e); else if (log.isDebugEnabled()) log.debug(getName() + "" has been stopped.""); break; } } } }; if (!workerRef.compareAndSet(null, worker)) { log.warning(LongJVMPauseDetector.class.getSimpleName() + "" already started!""); return; } worker.setDaemon(true); worker.start(); if (log.isDebugEnabled()) log.debug(""LongJVMPauseDetector was successfully started""); }"
34,"<START> public List<ACGroup> getGroups(SessionId sessionId, ACOrgUnitId orgUnitId) throws ESException { <END> checkForNulls(sessionId, orgUnitId); getAccessControl().getAuthorizationService().checkProjectAdminAccess( sessionId.toAPI(), null); final List<ACGroup> result = new ArrayList<ACGroup>(); final ACOrgUnit<?> orgUnit = getOrgUnit(orgUnitId); for (final ACGroup group : getGroups()) { if (group.getMembers().contains(orgUnit)) { final ACGroup copy = ModelUtil.clone(group); clearMembersFromGroup(copy); result.add(copy); } } return result; }",Do need call removeInvisibleOrgUnits well,"public List<ACGroup> getGroups(SessionId sessionId, ACOrgUnitId orgUnitId) throws ESException { checkForNulls(sessionId, orgUnitId); getAccessControl().getAuthorizationService().checkProjectAdminAccess( sessionId.toAPI(), null); final List<ACGroup> result = new ArrayList<ACGroup>(); final ACOrgUnit<?> orgUnit = getOrgUnit(orgUnitId); for (final ACGroup group : getGroups()) { if (group.getMembers().contains(orgUnit)) { final ACGroup copy = ModelUtil.clone(group); clearMembersFromGroup(copy); result.add(copy); } } return removeInvisibleOrgUnits(result, sessionId.toAPI()); }"
35,"public void transform(NodeType node) { for(Object om : node.getMetadata()){ <START> MetadataType metadata = (MetadataType) om; <END> for(Object oc : metadata.getColumn()){ ColumnType column = (ColumnType) oc; if(column.getType().equals(""id_Date"")) { if(""true"".equals(ComponentUtilities.getNodePropertyValue(node, name))){ column.setPattern(""\""yyyy-MM-dd HH:mm:ss\""""); } else if (""false"".equals(ComponentUtilities.getNodePropertyValue(node, name))) { column.setPattern(""\""dd-MM-yyyy\""""); } } } } }",type safe. objects _MetadataType_,"public void transform(NodeType node) { for(Object om : node.getMetadata()){ MetadataType metadata = (MetadataType) om; for(Object oc : metadata.getColumn()){ ColumnType column = (ColumnType) oc; if(column.getType().equals(""id_Date"")) { if(""true"".equals(ComponentUtilities.getNodePropertyValue(node, CHECK_BOX_NAME))){ column.setPattern(""\""yyyy-MM-dd HH:mm:ss\""""); } else if (""false"".equals(ComponentUtilities.getNodePropertyValue(node, CHECK_BOX_NAME))) { column.setPattern(""\""dd-MM-yyyy\""""); } } } } }"
36,"private void requestForbidden(HttpServerExchange exchange, String messageId, String qualifiedTopicName) { messageErrorProcessor.sendQuietly( exchange, <START> error(""Permission."", AUTH_ERROR), <END> messageId, qualifiedTopicName); }","""Permission."" -> ""Permission denied.""","private void requestForbidden(HttpServerExchange exchange, String messageId, String qualifiedTopicName) { messageErrorProcessor.sendQuietly( exchange, error(""Permission denied."", AUTH_ERROR), messageId, qualifiedTopicName); }"
37,"<START> Priority getPriority() { <END> Priority priority = Priority.LOW; boolean hasMultiple = actions != null && !actions.isEmpty(); if (actions != null && !hasMultiple) { return priority; } if (action != null) { priority = action.getPriority(); } if (hasMultiple) { for (int i = 0, n = actions.size(); i < n; i++) { Priority actionPriority = actions.get(i).getPriority(); if (actionPriority.ordinal() > priority.ordinal()) { priority = actionPriority; } } } return priority; }",This is expensive computationally. I track this in a field update requests attached/detached Action. This computation incremental access cheap (the of is essential priority queue is calling compateTo multiple times),Priority getPriority() { return priority; }
38,"private static String getPersistenceXml() { return ""<?xml version=\""1.0\"" encoding=\""UTF-8\"" standalone=\""yes\""?>\n"" + ""<persistence xmlns=\""<LINK_3>\"" xmlns:orm=\""<LINK_2>\"" xmlns:xsi=\""<LINK_1>\"" version=\""2.0\"" xsi:schemaLocation=\""<LINK_3> <LINK_0> <LINK_2> <LINK_2>_2_0.xsd\"">\n"" + "" <persistence-unit name=\""org.jbpm.test:test-module:1.0.0-SNAPSHOT\"" transaction-type=\""JTA\"">\n"" + "" <provider>org.hibernate.ejb.HibernatePersistence</provider>\n"" + "" <jta-data-source>java:jdbc/testDS1</jta-data-source>\n"" + "" <class>example.CaseDetail</class>\n"" + "" <class>org.drools.persistence.jpa.marshaller.MappedVariable</class>\n"" + "" <class>org.drools.persistence.jpa.marshaller.VariableEntity</class>\n"" + "" <exclude-unlisted-classes>true</exclude-unlisted-classes>\n"" + "" <properties>\n"" + <START> "" <property name=\""hibernate.dialect\"" value=\""org.hibernate.dialect.PostgreSQLDialect\""/>\n"" + <END> "" <property name=\""hibernate.max_fetch_depth\"" value=\""3\""/>\n"" + "" <property name=\""hibernate.hbm2ddl.auto\"" value=\""update\""/>\n"" + "" <property name=\""hibernate.show_sql\"" value=\""false\""/>\n"" + "" <property name=\""hibernate.id.new_generator_mappings\"" value=\""false\""/>\n"" + "" <property name=\""hibernate.transaction.jta.platform\"" value=\""org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform\""/>\n"" + "" </properties>\n"" + "" </persistence-unit>\n"" + ""</persistence>""; }","@tsurdilo I question. is this persistence.xml in String in a seperate resource file, moreover, is mentioned run PostgreSQL","private static String getPersistenceXml() { File entityTestPersistence = new File(""src/test/resources/entity/entity-test-persistence.xml""); assertTrue(entityTestPersistence.exists()); return IoUtils.readFileAsString(entityTestPersistence); }"
39,"private void addFootnoteRef(MacroMarkerBlock footnoteMacro, Block footnoteRef) { <START> for (ListIterator<Block> it = footnoteMacro.getChildren().listIterator(); it.hasNext();) { <END> it.next(); it.remove(); } footnoteMacro.addChild(footnoteRef); }",this for is equivalent footnoteMacro.getChildren().clear();,"private void addFootnoteRef(MacroMarkerBlock footnoteMacro, Block footnoteRef) { footnoteMacro.getChildren().clear(); footnoteMacro.addChild(footnoteRef); }"
40,"public void canHandleHoleInTail() { UUID streamID = UUID.randomUUID(); CorfuTable<String, String> corfuTable = getDefaultRuntime() .getObjectsView() .build() .setTypeToken(new TypeToken<CorfuTable<String, String>>() {}) .setStreamID(streamID) .open(); corfuTable.put(""k1"", ""dog fox cat""); corfuTable.put(""k2"", ""dog bat""); corfuTable.put(""k3"", ""fox""); TokenResponse tokenResponse = getDefaultRuntime() .getSequencerView() .next(streamID); Token token = tokenResponse.getToken(); <START> getDefaultRuntime().getAddressSpaceView() <END> .write(tokenResponse, LogData.getHole(token)); for (int i = 0; i < ITERATIONS; i++) { getDefaultRuntime().getObjectsView().TXBuild() .type(TransactionType.SNAPSHOT) .snapshot(token) .build() .begin(); corfuTable.scanAndFilter(item -> true); getDefaultRuntime().getObjectsView().TXEnd(); } assertThat(((CorfuCompileProxy) ((ICorfuSMR) corfuTable). getCorfuSMRProxy()).getUnderlyingObject().getSmrStream().pos()).isEqualTo(3); }",read address a hole,"public void canHandleHoleInTail() { UUID streamID = UUID.randomUUID(); CorfuTable<String, String> corfuTable = getDefaultRuntime() .getObjectsView() .build() .setTypeToken(new TypeToken<CorfuTable<String, String>>() {}) .setStreamID(streamID) .open(); corfuTable.put(""k1"", ""dog fox cat""); corfuTable.put(""k2"", ""dog bat""); corfuTable.put(""k3"", ""fox""); TokenResponse tokenResponse = getDefaultRuntime() .getSequencerView() .next(streamID); Token token = tokenResponse.getToken(); getDefaultRuntime().getAddressSpaceView() .write(tokenResponse, LogData.getHole(token)); assertThat(getDefaultRuntime().getAddressSpaceView() .read(token.getSequence()).isHole()).isTrue(); for (int i = 0; i < ITERATIONS; i++) { getDefaultRuntime().getObjectsView().TXBuild() .type(TransactionType.SNAPSHOT) .snapshot(token) .build() .begin(); corfuTable.scanAndFilter(item -> true); getDefaultRuntime().getObjectsView().TXEnd(); } assertThat(((CorfuCompileProxy) ((ICorfuSMR) corfuTable). getCorfuSMRProxy()).getUnderlyingObject().getSmrStream().pos()).isEqualTo(3); }"
41,"public void testGenerate() throws IOException{ final LabelsGeneratorInput input = new LabelsGeneratorInput(); input.setAllAvailablefields(this.mockAvailableFields()); input.setFileName(""filename""); input.setBarcodeRequired(false); input.setNumberOfRowsPerPageOfLabel(""7""); input.setSizeOfLabelSheet(""1""); final LabelsData data = new LabelsData(TermId.OBS_UNIT_ID.getId(), Arrays.asList(this.mockLabels())); final File file = this.pdfLabelsFileGenerator.generate(input, data); Assert.assertNotNull(file); <START> Assert.assertEquals(""filename.pdf"", file.getName()); <END> }",Delete file,"public void testGenerate() throws IOException{ final LabelsGeneratorInput input = new LabelsGeneratorInput(); input.setAllAvailablefields(this.mockAvailableFields()); input.setFileName(""filename""); input.setBarcodeRequired(false); input.setNumberOfRowsPerPageOfLabel(""7""); input.setSizeOfLabelSheet(""1""); final LabelsData data = new LabelsData(TermId.OBS_UNIT_ID.getId(), Arrays.asList(this.mockLabels())); final File file = this.pdfLabelsFileGenerator.generate(input, data); Assert.assertNotNull(file); Assert.assertEquals(""filename.pdf"", file.getName()); file.delete(); }"
42,"public void waitForCompletion(long timeoutMillis) { if(!(this.wrappedCommand instanceof BaseCommand)) { log.error(""waitForCompletion called on command which doesn't inherit from BaseCommand!"" + "" Unable to wait for command to complete.""); return; } ScriptedCommandCompletionLock lock = new ScriptedCommandCompletionLock((BaseCommand)wrappedCommand); parentCommand.addCompletionLock(lock); try { long startTime = System.currentTimeMillis(); synchronized (lock) { if(timeoutMillis <= 0) { log.debug(""Waiting indefinitely for lock notification""); lock.wait(); } else { log.debug(""Waiting with a timeout of "" + timeoutMillis + ""ms""); lock.wait(timeoutMillis); } } <START> log.debug(""Wait completed (waited "" + (System.currentTimeMillis() - startTime) + ""millis)""); <END> } catch (InterruptedException e) { log.error(""Scripted command wait unexpectedly interrupted!""); } }",I feel callers want if completed successfully timed out,"public void waitForCompletion(long timeoutMillis) { if(!(this.wrappedCommand instanceof BaseCommand)) { log.error(""waitForCompletion called on command which doesn't inherit from BaseCommand!"" + "" Unable to wait for command to complete.""); return; } ScriptedCommandCompletionLock lock = new ScriptedCommandCompletionLock((BaseCommand)wrappedCommand); parentCommand.addCompletionLock(lock); try { long startTime = System.currentTimeMillis(); synchronized (lock) { log.debug(""Waiting with a timeout of "" + timeoutMillis + ""ms""); lock.wait(timeoutMillis); } log.debug(""Wait completed (waited "" + (System.currentTimeMillis() - startTime) + ""millis)""); } catch (InterruptedException e) { log.error(""Scripted command wait unexpectedly interrupted!""); } }"
43,"public WebappDaoFactoryConfig() { preferredLocales = Arrays.asList(Locale.getDefault()); <START> preferredLanguages = Arrays.asList(""en-US"", ""en"", ""EN""); <END> defaultNamespace = ""<LINK_0>""; nonUserNamespaces = new HashSet<String>(); nonUserNamespaces.add(VitroVocabulary.vitroURI); }",@wwelling : Is guarantee default locale language included in list of languages,"public WebappDaoFactoryConfig() { preferredLanguages = Arrays.asList(""en-US"", ""en"", ""EN""); preferredLocales = LanguageFilteringUtils.languagesToLocales(preferredLanguages); defaultNamespace = ""<LINK_0>""; nonUserNamespaces = new HashSet<String>(); nonUserNamespaces.add(VitroVocabulary.vitroURI); }"
44,"public Iterator<Identity> enter(final Request request) throws IOException { return Collections.singleton( <START> PsLinkedin.parse(this.luserjson <END> .fetch(new Href(""<LINK_1>"") .with(""grant_type"", ""authorization_code"") .toString(), ""<LINK_0>,first-name,last-name,picture-url)"", new RqHref.Base(request).href() ) ) ).iterator(); }","@ikhvostenkov leave parameter in line ( if ) is there. this line more like: PsLinkedin.parse( this.luserjson.fetch( new Href( ""..","public Iterator<Identity> enter(final Request request) throws IOException { final Href href = new RqHref.Base(request).href(); final Iterator<String> code = href.param(""code"").iterator(); if (!code.hasNext()) { throw new IllegalArgumentException(""code is not provided""); } return Collections.singleton( this.fetch(this.token(href.toString(), code.next())) ).iterator(); }"
45,"public void saveDraftShouldDeleteDraftIfTitleAndBodyAreEmptyAndRecipientIsNotExists() throws Exception { mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); <START> saveDraft(EMPTY, EMPTY, null).andExpect(model() <END> .attributeHasErrors(""privateMessageDto"")) .andExpect(view().name(""redirect:/drafts"")) .andExpect(status().isMovedTemporarily()); verify(pmService).delete(anyList()); }","necessarily need constants for these.. Plain """" fine too","public void saveDraftShouldDeleteDraftIfTitleAndBodyAreEmptyAndRecipientIsNotExists() throws Exception { saveDraft("""", """", null) .andExpect(model() .attributeHasErrors(""privateMessageDto"")) .andExpect(view().name(""redirect:/drafts"")) .andExpect(status().isMovedTemporarily()); verify(pmService).delete(anyList()); }"
46,public SpecialAnonymizationUserPage submitAnonymization() { try { Thread.sleep(10000); } catch (Exception e) { } jsActions.scrollToElement(submitButton); <START> submitButton.click(); <END> return this; },"FYI, I a method scrollAndClick()",public SpecialAnonymizationUserPage submitAnonymization() { jsActions.scrollToElement(submitButton); submitButton.click(); return this; }
47,"protected boolean connect () { try { if (sysLibrary == null ) { logger.debug(""Loading native code library...""); sysLibrary = (LibK8055) Native.synchronizedLibrary((Library) Native.loadLibrary(""k8055"", LibK8055.class)); logger.debug(""Done loading native code library""); } } catch (Exception e) { logger.error(""Failed to load K8055 native library "" + e.getMessage(), e); } if (!connected) { if (sysLibrary.OpenDevice(boardNo) == boardNo) { connected = true; lastDigitalInputs = -1; try { Thread.sleep(100); } catch (InterruptedException e) { <START> e.printStackTrace(); <END> } logger.info(""K8055: Connect to board: "" + boardNo + "" succeeeded.""); } else { logger.error(""K8055: Connect to board: "" + boardNo + "" failed.""); } }; return connected; }",please remove TODO .printStackTrace() add proper logging instead,"protected boolean connect() { try { if (sysLibrary == null) { logger.debug(""Loading native code library...""); sysLibrary = (LibK8055) Native .synchronizedLibrary((Library) Native.loadLibrary( ""k8055"", LibK8055.class)); logger.debug(""Done loading native code library""); } if (!connected) { if (sysLibrary.OpenDevice(boardNo) == boardNo) { connected = true; lastDigitalInputs = -1; logger.info(""K8055: Connect to board: "" + boardNo + "" succeeeded.""); } else { logger.error(""K8055: Connect to board: "" + boardNo + "" failed.""); } } ; } catch (Exception e) { logger.error( ""Failed to load K8055 native library. Please check the libk8055 and jna native libraries are in the Java library path. "", e); } return connected; }"
48,"public String toPath(Class<?> classOfPackagingContainingFile, String filename) { String path = classOfPackagingContainingFile.getResource(filename).getPath(); <START> if (path.endsWith("".java.template"")) { <END> String javaPath = path.substring(0, path.length() - 9); File target = new File(javaPath); if (!target.exists()) { try { Files.copy(new File(path).toPath(), target.toPath()); } catch (IOException e) { throw new IllegalStateException(""unable to copy file"", e); } } return javaPath; } return path; }","Hmm, is this? is a java template","public String toPath(Class<?> classOfPackagingContainingFile, String filename) { return classOfPackagingContainingFile.getResource(filename).getPath(); }"
49,public boolean testNull() { <START> if (failNext > 0) { <END> filterIdx++; failNext--; return false; } Filter filter = nextFilter(); if (filter != null) { return processResult(filter.testNull()); } return true; },Consider extracting helper method tryConsumeFailedPosition: @Override public boolean testNull() { if (tryConsumeFailedPosition()) { return false; } ... } private boolean tryConsumeFailedPosition() { if (numNextPositionsToFail > 0) { filterIndex++; numNextPositionsToFail--; return true; } return false; },public boolean testNull() { if (numNextPositionsToFail > 0) { filterIndex++; numNextPositionsToFail--; return false; } Filter filter = nextFilter(); if (filter != null) { return processResult(filter.testNull()); } return true; }
50,"private void validateJsonSchemaConstraints(final Schema schema) throws InvalidEventTypeException { final List<SchemaIncompatibility> incompatibilities = schemaCompatibilityChecker.checkConstraints(schema); if (!incompatibilities.isEmpty()) { <START> final String erroMessage = incompatibilities.stream().map(Object::toString) <END> .collect(Collectors.joining("", "")); throw new InvalidEventTypeException(""Invalid schema: "" + erroMessage); } }",erroR,"private void validateJsonSchemaConstraints(final Schema schema) throws InvalidEventTypeException { final List<SchemaIncompatibility> incompatibilities = schemaCompatibilityChecker.checkConstraints(schema); if (!incompatibilities.isEmpty()) { final String errorMessage = incompatibilities.stream().map(Object::toString) .collect(Collectors.joining("", "")); throw new InvalidEventTypeException(""Invalid schema: "" + errorMessage); } }"
51,"private ScheduledExecutorService startKerberosLoginThread() { scheduledExecutorService = Executors.newScheduledThreadPool(1); scheduledExecutorService.submit(new Callable() { public Object call() throws Exception { if (runKerberosLogin()) { logger.info(""Ran runKerberosLogin command successfully.""); kinitFailCount = 0; <START> logger.info(""Scheduling Kerberos ticket refresh thread with interval "" + <END> getKerberosRefreshInterval() + "" ms""); scheduledExecutorService .schedule(this, getKerberosRefreshInterval(), TimeUnit.MILLISECONDS); } else { kinitFailCount++; logger.info(""runKerberosLogin failed for "" + kinitFailCount + "" time(s).""); if (kinitFailCount >= kinitFailThreshold()) { logger.error(""runKerberosLogin failed for max attempts, calling close interpreter.""); close(); } else { scheduledExecutorService.submit(this); } } return null; } }); return scheduledExecutorService; }",rename logger LOGGER ? is convention for naming static variables,"private ScheduledExecutorService startKerberosLoginThread() { scheduledExecutorService = Executors.newScheduledThreadPool(1); scheduledExecutorService.submit(new Callable() { public Object call() throws Exception { if (runKerberosLogin()) { LOGGER.info(""Ran runKerberosLogin command successfully.""); kinitFailCount = 0; LOGGER.info(""Scheduling Kerberos ticket refresh thread with interval "" + getKerberosRefreshInterval() + "" ms""); scheduledExecutorService .schedule(this, getKerberosRefreshInterval(), TimeUnit.MILLISECONDS); } else { kinitFailCount++; LOGGER.info(""runKerberosLogin failed for "" + kinitFailCount + "" time(s).""); if (kinitFailCount >= kinitFailThreshold()) { LOGGER.error(""runKerberosLogin failed for max attempts, calling close interpreter.""); close(); } else { scheduledExecutorService.schedule(this, 1, TimeUnit.SECONDS); } } return null; } }); return scheduledExecutorService; }"
52,"private ProcessBatchResult processBatch(int batchSize) { Block[] blocks = new Block[outputCount]; int pageSize = 0; SelectedPositions positionsBatch = selectedPositions.subRange(0, batchSize); for (PageProjectionWithOutputs projection : projections) { if (yieldSignal.isSet()) { return ProcessBatchResult.processBatchYield(); } if (positionsBatch.size() > 1 && pageSize > MAX_PAGE_SIZE_IN_BYTES) { return ProcessBatchResult.processBatchTooLarge(); } int[] outputChannels = projection.getOutputChannels(); if (previouslyComputedResults[outputChannels[0]] != null && previouslyComputedResults[outputChannels[0]].getPositionCount() >= batchSize) { <START> for (Integer channel : outputChannels) { <END> blocks[channel] = previouslyComputedResults[channel].getRegion(0, batchSize); pageSize += blocks[channel].getSizeInBytes(); } } else { if (pageProjectWork == null) { expressionProfiler.start(); pageProjectWork = projection.project(session, yieldSignal, projection.getPageProjection().getInputChannels().getInputChannels(page), positionsBatch); expressionProfiler.stop(positionsBatch.size()); } if (!pageProjectWork.process()) { return ProcessBatchResult.processBatchYield(); } List<Block> projectionOutputs = pageProjectWork.getResult(); for (int j = 0; j < outputChannels.length; j++) { int channel = outputChannels[j]; previouslyComputedResults[channel] = projectionOutputs.get(j); blocks[channel] = previouslyComputedResults[channel]; pageSize += blocks[channel].getSizeInBytes(); } pageProjectWork = null; } } return ProcessBatchResult.processBatchSuccess(new Page(positionsBatch.size(), blocks)); }",int channel,"private ProcessBatchResult processBatch(int batchSize) { Block[] blocks = new Block[outputCount]; int pageSize = 0; SelectedPositions positionsBatch = selectedPositions.subRange(0, batchSize); for (PageProjectionWithOutputs projection : projections) { if (yieldSignal.isSet()) { return ProcessBatchResult.processBatchYield(); } if (positionsBatch.size() > 1 && pageSize > MAX_PAGE_SIZE_IN_BYTES) { return ProcessBatchResult.processBatchTooLarge(); } int[] outputChannels = projection.getOutputChannels(); if (previouslyComputedResults[outputChannels[0]] != null && previouslyComputedResults[outputChannels[0]].getPositionCount() >= batchSize) { for (int channel : outputChannels) { blocks[channel] = previouslyComputedResults[channel].getRegion(0, batchSize); pageSize += blocks[channel].getSizeInBytes(); } } else { if (pageProjectWork == null) { expressionProfiler.start(); pageProjectWork = projection.project(properties, yieldSignal, projection.getPageProjection().getInputChannels().getInputChannels(page), positionsBatch); expressionProfiler.stop(positionsBatch.size()); } if (!pageProjectWork.process()) { return ProcessBatchResult.processBatchYield(); } List<Block> projectionOutputs = pageProjectWork.getResult(); for (int j = 0; j < outputChannels.length; j++) { int channel = outputChannels[j]; previouslyComputedResults[channel] = projectionOutputs.get(j); blocks[channel] = previouslyComputedResults[channel]; pageSize += blocks[channel].getSizeInBytes(); } pageProjectWork = null; } } return ProcessBatchResult.processBatchSuccess(new Page(positionsBatch.size(), blocks)); }"
53,"public void addPremisEventsTest() throws IOException { File premisEventsDir = job.getEventsDirectory(); premisEventsDir.mkdir(); PID folderObjPid = repository.mintContentPid(); <START> folderObjPid = repository.mintContentPid(); <END> File premisEventsFile = new File(premisEventsDir, folderObjPid.getUUID() + "".xml""); premisEventsFile.createNewFile(); String label = ""testfolder""; Model model = job.getWritableModel(); Bag depBag = model.createBag(depositPid.getRepositoryPath()); Bag folderBag = model.createBag(folderObjPid.getRepositoryPath()); folderBag.addProperty(RDF.type, Cdr.Folder); folderBag.addProperty(CdrDeposit.label, label); depBag.add(folderBag); FilePremisLogger premisLogger = new FilePremisLogger(folderObjPid, premisEventsFile, repository); Resource event1 = premisLogger.buildEvent(Premis.Normalization) .addEventDetail(""Event 1"") .addAuthorizingAgent(SoftwareAgent.depositService.getFullname()) .write(); Resource event2 = premisLogger.buildEvent(Premis.VirusCheck) .addEventDetail(""Event 2"") .addSoftwareAgent(SoftwareAgent.clamav.getFullname()) .write(); job.closeModel(); job.run(); FolderObject folder = repository.getFolderObject(folderObjPid); List<PremisEventObject> events = folder.getPremisLog().getEvents(); assertEquals(2, events.size()); assertTrue(events.contains(findPremisEventByType(events, Premis.Normalization))); assertTrue(events.contains(findPremisEventByType(events, Premis.VirusCheck))); }",Reducto this duplicate line,"public void addPremisEventsTest() throws IOException { File premisEventsDir = job.getEventsDirectory(); premisEventsDir.mkdir(); PID folderObjPid = repository.mintContentPid(); File premisEventsFile = new File(premisEventsDir, folderObjPid.getUUID() + "".xml""); premisEventsFile.createNewFile(); String label = ""testfolder""; Model model = job.getWritableModel(); Bag depBag = model.createBag(depositPid.getRepositoryPath()); Bag folderBag = model.createBag(folderObjPid.getRepositoryPath()); folderBag.addProperty(RDF.type, Cdr.Folder); folderBag.addProperty(CdrDeposit.label, label); depBag.add(folderBag); FilePremisLogger premisLogger = new FilePremisLogger(folderObjPid, premisEventsFile, repository); Resource event1 = premisLogger.buildEvent(Premis.Normalization) .addEventDetail(""Event 1"") .addAuthorizingAgent(SoftwareAgent.depositService.getFullname()) .write(); Resource event2 = premisLogger.buildEvent(Premis.VirusCheck) .addEventDetail(""Event 2"") .addSoftwareAgent(SoftwareAgent.clamav.getFullname()) .write(); job.closeModel(); job.run(); FolderObject folder = repository.getFolderObject(folderObjPid); List<PremisEventObject> events = folder.getPremisLog().getEvents(); assertEquals(2, events.size()); assertTrue(events.contains(findPremisEventByType(events, Premis.Normalization))); assertTrue(events.contains(findPremisEventByType(events, Premis.VirusCheck))); }"
54,"private Image getImageForDraw() { <START> if (sprite.look.getLookData() != null) { <END> if (sprite.look.getLookData().getCollisionInformation().getLeftBubblePos() == null || sprite.look.getLookData().getCollisionInformation().getRightBubblePos() == null) { sprite.look.getLookData().getCollisionInformation().loadOrCreateCollisionPolygon(); } CollisionInformation collisionInformation = sprite.look.getLookData().getCollisionInformation(); Pair<Integer, Integer> bubblePosRight = collisionInformation.getRightBubblePos(); Pair<Integer, Integer> bubblePosLeft = collisionInformation.getLeftBubblePos(); imageLeft.setX(calculateLeftImageX(bubblePosLeft.first)); imageLeft.setY(calculateImageY(bubblePosLeft.second)); imageRight.setX(calculateRightImageX(bubblePosRight.first)); imageRight.setY(calculateImageY(bubblePosRight.second)); } else { if (drawRight) { image.setX(sprite.look.getXInUserInterfaceDimensionUnit() + (sprite.look .getWidthInUserInterfaceDimensionUnit() / 2)); } else { image.setX(sprite.look.getXInUserInterfaceDimensionUnit() - sprite.look .getWidthInUserInterfaceDimensionUnit() / 2 - image.getWidth()); } image.setY(sprite.look.getYInUserInterfaceDimensionUnit() + (sprite.look .getHeightInUserInterfaceDimensionUnit() / 2)); } return image; }",I prefer of local variables resolve calls something.somethingelse.somefunction(),"private Image getImageForDraw() { LookData lookData = sprite.look.getLookData(); if (lookData != null) { CollisionInformation collisionInformation = lookData.getCollisionInformation(); if (collisionInformation.getLeftBubblePos() == null || collisionInformation.getRightBubblePos() == null) { collisionInformation.calculateBubblePositions(); } Pair<Integer, Integer> bubblePosRight = collisionInformation.getRightBubblePos(); Pair<Integer, Integer> bubblePosLeft = collisionInformation.getLeftBubblePos(); imageLeft.setX(calculateLeftImageX(bubblePosLeft.first)); imageLeft.setY(calculateImageY(bubblePosLeft.second)); imageRight.setX(calculateRightImageX(bubblePosRight.first)); imageRight.setY(calculateImageY(bubblePosRight.second)); } else { Look look = sprite.look; if (drawRight) { image.setX(look.getXInUserInterfaceDimensionUnit() + (look.getWidthInUserInterfaceDimensionUnit() / 2)); } else { image.setX(look.getXInUserInterfaceDimensionUnit() - look.getWidthInUserInterfaceDimensionUnit() / 2 - image.getWidth()); } image.setY(look.getYInUserInterfaceDimensionUnit() + (look.getHeightInUserInterfaceDimensionUnit() / 2)); } return image; }"
55,"<START> BundleContext getBundleContext() { <END> return Optional.ofNullable(FrameworkUtil.getBundle(getClass())) .map(Bundle::getBundleContext) .orElseThrow( () -> new IllegalStateException(""Could not get the bundle for "" + getClass().getName())); }",suggestion,"private BundleContext getBundleContext() { return Optional.ofNullable(bundleLookup.apply(getClass())) .map(Bundle::getBundleContext) .orElseThrow( () -> new IllegalStateException(""Could not get the bundle for "" + getClass().getName())); }"
56,"public Path(Class<?> entityClass, EntityDictionary dictionary, String dotSeparatedPath) { pathElements = new ArrayList<>(); String[] fieldNames = dotSeparatedPath.split(""\\.""); Class<?> currentClass = entityClass; String currentClassName = dictionary.getJsonAliasFor(currentClass); for (String fieldName : fieldNames) { if (dictionary.isRelation(currentClass, fieldName)) { Class<?> relationClass = dictionary.getParameterizedType(currentClass, fieldName); pathElements.add(new PathElement(currentClass, currentClassName, relationClass, fieldName)); currentClass = relationClass; currentClassName = fieldName; } else if (dictionary.isAttribute(currentClass, fieldName) || fieldName.equals(dictionary.getIdFieldName(entityClass))) { Class<?> attributeClass = dictionary.getType(currentClass, fieldName); pathElements.add(new PathElement(currentClass, currentClassName, attributeClass, fieldName)); } else { <START> throw new InvalidValueException(entityClass.getSimpleName() <END> + "" doesn't contain the field "" + fieldName); } } }",Is SimpleName want here? type name (which different),"public Path(Class<?> entityClass, EntityDictionary dictionary, String dotSeparatedPath) { pathElements = new ArrayList<>(); String[] fieldNames = dotSeparatedPath.split(""\\.""); Class<?> currentClass = entityClass; String currentClassName = dictionary.getJsonAliasFor(currentClass); for (String fieldName : fieldNames) { if (dictionary.isRelation(currentClass, fieldName)) { Class<?> relationClass = dictionary.getParameterizedType(currentClass, fieldName); pathElements.add(new PathElement(currentClass, currentClassName, relationClass, fieldName)); currentClass = relationClass; currentClassName = fieldName; } else if (dictionary.isAttribute(currentClass, fieldName) || fieldName.equals(dictionary.getIdFieldName(entityClass))) { Class<?> attributeClass = dictionary.getType(currentClass, fieldName); pathElements.add(new PathElement(currentClass, currentClassName, attributeClass, fieldName)); } else { throw new InvalidValueException(dictionary.getJsonAliasFor(currentClass) + "" doesn't contain the field "" + fieldName); } } }"
57,"void cleanUp() { Log.d(TAG, ""Vungle banner adapter try to cleanUp:"" + this); if (mVungleBannerAd != null) { Log.d(TAG, ""Vungle banner adapter cleanUp: destroyAd # "" + mVungleBannerAd.hashCode()); mVungleBannerAd.destroyAd(); if (mVungleBannerAd != null && mVungleBannerAd.getParent() != null) { <START> ((RelativeLayout) mVungleBannerAd.getParent()).removeView(mVungleBannerAd); <END> } mVungleBannerAd = null; } if (mVungleNativeAd != null) { Log.d(TAG, ""Vungle banner adapter cleanUp: finishDisplayingAd # "" + mVungleNativeAd.hashCode()); mVungleNativeAd.finishDisplayingAd(); if (mVungleNativeAd != null) { View adView = mVungleNativeAd.renderNativeView(); if (adView != null && adView.getParent() != null) { ((RelativeLayout) adView.getParent()).removeView(adView); } } mVungleNativeAd = null; } }",Safer cast ViewGroup here,"void cleanUp() { Log.d(TAG, ""Vungle banner adapter try to cleanUp:"" + this); if (mVungleBannerAd != null) { Log.d(TAG, ""Vungle banner adapter cleanUp: destroyAd # "" + mVungleBannerAd.hashCode()); mVungleBannerAd.destroyAd(); if (mVungleBannerAd != null && mVungleBannerAd.getParent() != null) { ((ViewGroup) mVungleBannerAd.getParent()).removeView(mVungleBannerAd); } mVungleBannerAd = null; } if (mVungleNativeAd != null) { Log.d(TAG, ""Vungle banner adapter cleanUp: finishDisplayingAd # "" + mVungleNativeAd.hashCode()); mVungleNativeAd.finishDisplayingAd(); if (mVungleNativeAd != null) { View adView = mVungleNativeAd.renderNativeView(); if (adView != null && adView.getParent() != null) { ((ViewGroup) adView.getParent()).removeView(adView); } } mVungleNativeAd = null; } }"
58,private void scheduleManagerUpdate(IContributionManager mgr) { if (this.mgrsToUpdate.isEmpty()) { Display display = context.get(Display.class); if (display == null || display.isDisposed()) { return; } <START> display.asyncExec(new Runnable() { <END> @Override public void run() { Collection<IContributionManager> toUpdate = new HashSet<>(mgrsToUpdate); mgrsToUpdate.clear(); for (IContributionManager mgr : toUpdate) { mgr.update(false); } } }); } this.mgrsToUpdate.add(mgr); },"If I undrestood right, want display.timerExec(X) here. X 50 - 100 ms. I prefer smaller values","private void scheduleManagerUpdate(IContributionManager mgr) { synchronized (mgrToUpdate) { if (this.mgrToUpdate.isEmpty()) { Display display = context.get(Display.class); if (display != null && !display.isDisposed()) { display.timerExec(100, new Runnable() { @Override public void run() { Collection<IContributionManager> toUpdate = new LinkedHashSet<>(); synchronized (mgrToUpdate) { toUpdate.addAll(mgrToUpdate); mgrToUpdate.clear(); } for (IContributionManager mgr : toUpdate) { mgr.update(false); } } }); } this.mgrToUpdate.add(mgr); } } }"
59,"public void testBigDecimalToLong() { Object r = ParameterConverter.tryToMakeCompatible(long.class, new BigDecimal(1000)); assertTrue(""expect long"", r.getClass() == Long.class); assertEquals(1000L, ((Long)r).longValue()); <START> boolean hasException = false; <END> try { r = ParameterConverter.tryToMakeCompatible(long.class, new BigDecimal(1000.01)); } catch (VoltTypeException e) { hasException = true; } assertEquals(true, hasException); hasException = false; try { r = ParameterConverter.tryToMakeCompatible(long.class, new BigDecimal(""10000000000000000000000000000000000"")); } catch (VoltTypeException e) { hasException = true; } assertEquals(true, hasException); }","Replace lossy conversion a static util function. failWithInvalidConversion(Class<?> class, BigDecimal bigDecimal);","public void testBigDecimalToLong() { Object r = ParameterConverter.tryToMakeCompatible(long.class, new BigDecimal(1000)); assertTrue(""expect long"", r.getClass() == Long.class); assertEquals(1000L, ((Long)r).longValue()); testBigDecimalFailWithInvalidConversion(long.class, new BigDecimal(1000.01)); testBigDecimalFailWithInvalidConversion(long.class, new BigDecimal(""10000000000000000000000000000000000"")); }"
60,"public void visitVariableIdentifier(VariableIdentifierTree tree) { if (!isBuiltInVariable(tree)) { if (classMemberUsageState == null) { createOrUseVariableIdentifierSymbol(tree); } else { if (classMemberUsageState.isSelfMember && classScope != null && classMemberUsageState.isStatic) { Symbol symbol = classScope.getSymbol(tree.text(), Symbol.Kind.FIELD); if (symbol != null) { symbol.addUsage(tree); <START> symbolTable.associateSymbol(tree, symbol); <END> } } Symbol symbol = currentScope.getSymbol(tree.text(), Symbol.Kind.VARIABLE, Symbol.Kind.PARAMETER); if (symbol != null) { symbol.addUsage(tree); symbolTable.associateSymbol(tree, symbol); } classMemberUsageState = null; } } }",call associateSymbol time call addUsage. factorizing that,"public void visitVariableIdentifier(VariableIdentifierTree tree) { if (!isBuiltInVariable(tree)) { if (classMemberUsageState == null) { createOrUseVariableIdentifierSymbol(tree); } else { if (classMemberUsageState.isSelfMember && classScope != null && classMemberUsageState.isStatic) { Symbol symbol = classScope.getSymbol(tree.text(), Symbol.Kind.FIELD); if (symbol != null) { associateSymbol(tree, symbol); } } Symbol symbol = currentScope.getSymbol(tree.text(), Symbol.Kind.VARIABLE, Symbol.Kind.PARAMETER); if (symbol != null) { associateSymbol(tree, symbol); } classMemberUsageState = null; } } }"
61,"public void sendCssText(String cssText) { waitForElementByElement(aceLayerTextArea); <START> executeScript(""ace.edit('cssEditorContainer').setValue('""+ cssText +""');""); <END> PageObjectLogging.log(""sendCssText"", ""the following text was send to ace editor: ""+cssText, true, driver); }","1. create method clearCSS() ace.edit('cssEditorContainer').setValue('') 2. add .ace_text-input element UI mapping - this is cursor, 3. in sendCssText sendKeys method type cursor","public void sendCssText(String cssText) { waitForElementByElement(aceLayerTextArea); waitForElementByElement(aceInputTextArea); aceInputTextArea.sendKeys(cssText); PageObjectLogging.log(""sendCssText"", ""the following text was send to ace editor: ""+cssText, true, driver); }"
62,"@Test public void clear() { LinkedHashTreeMap<String, String> map = new LinkedHashTreeMap<>(); map.put(""a"", ""android""); map.put(""c"", ""cola""); map.put(""b"", ""bbq""); map.clear(); assertIterationOrder(map.keySet()); <START> assertThat(map.size()).isEqualTo(0); <END> }",assertThat(map).isEmpty(),"@Test public void clear() { LinkedHashTreeMap<String, String> map = new LinkedHashTreeMap<>(); map.put(""a"", ""android""); map.put(""c"", ""cola""); map.put(""b"", ""bbq""); map.clear(); assertThat(map.keySet()).containsExactly(); assertThat(map).isEmpty(); }"
63,private void lookupCoordinatorAndRetry(TransactionManager.TxnRequestHandler nextRequestHandler) { if (!nextRequestHandler.needsCoordinator()) { time.sleep(retryBackoffMs); metadata.requestUpdate(); } <START> transactionManager.lookupCoordinator(nextRequestHandler); <END> transactionManager.retry(nextRequestHandler); },"reads a bit strange fall lookupCoordinator if request need coordinator. clearer a slight restructure: java transactionManager.retry(nextRequestHandler); if (nextRequestHandler.needsCoordinator()) { transactionManager.lookupCoordinator(nextRequestHandler); } else { // For non-coordinator requests, sleep prevent a tight loop node is time.sleep(retryBackoffMs); metadata.requestUpdate(); }",private void lookupCoordinatorAndRetry(TransactionManager.TxnRequestHandler nextRequestHandler) { if (nextRequestHandler.needsCoordinator()) { transactionManager.lookupCoordinator(nextRequestHandler); } else { time.sleep(retryBackoffMs); metadata.requestUpdate(); } transactionManager.retry(nextRequestHandler); }
64,"public void getMandatoryModules_shouldReturnMandatoryModuleIds() throws Exception { executeDataSet(""org/openmrs/module/include/mandatoryModulesGlobalProperties.xml""); Assert.assertEquals(1, ModuleUtil.getMandatoryModules().size()); <START> Assert.assertEquals(""firstmodule"", ModuleUtil.getMandatoryModules().get(0)); <END> }",Changes in 3 tests relevant either,"public void getMandatoryModules_shouldReturnMandatoryModuleIds() throws Exception { GlobalProperty gp1 = new GlobalProperty(""firstmodule.mandatory"", ""true""); GlobalProperty gp2 = new GlobalProperty(""secondmodule.mandatory"", ""false""); when(administrationService.getGlobalPropertiesBySuffix("".mandatory"")).thenReturn(Arrays.asList(gp1, gp2)); assertThat(ModuleUtil.getMandatoryModules(), contains(""firstmodule"")); }"
65,"protected void processAuthenticationResponse(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException { HttpSession session = request.getSession(false); <START> if (session.getAttribute(IWAConstants.SUBJECT_ATTRIBUTE) == null) { <END> if (log.isDebugEnabled()) { log.debug(""Attribute not set. Therefore authentication is failed.""); } throw new AuthenticationFailedException(""Authentication Failed""); } String username = session.getAttribute(IWAConstants.SUBJECT_ATTRIBUTE).toString(); if (username == null) { if (log.isDebugEnabled()) { log.debug(""User name is null. Therefore authentication is failed.""); } throw new AuthenticationFailedException(""Authentication Failed""); } StringTokenizer stringTokenizer = new StringTokenizer(username, ""@""); username = stringTokenizer.nextToken(); if (log.isDebugEnabled()) { log.debug(""Authenticate request received : AuthType - "" + request.getAuthType() + "", User - "" + username); } boolean isAuthenticated; UserStoreManager userStoreManager; try { userStoreManager = (UserStoreManager) CarbonContext.getThreadLocalCarbonContext().getUserRealm() .getUserStoreManager(); isAuthenticated = userStoreManager.isExistingUser(MultitenantUtils.getTenantAwareUsername(username)); } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new AuthenticationFailedException(""IWAAuthenticator failed while trying to find user existence"", e); } if (!isAuthenticated) { if (log.isDebugEnabled()) { log.debug(""user authentication failed, user:"" + username + "" is not in the user store""); } throw new AuthenticationFailedException(""Authentication Failed""); } username = FrameworkUtils.prependUserStoreDomainToName(username); context.setSubject(AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(username)); }",Formatting issue. Extra space ==,"protected void processAuthenticationResponse(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException { HttpSession session = request.getSession(false); if (session.getAttribute(IWAConstants.SUBJECT_ATTRIBUTE) == null) { if (log.isDebugEnabled()) { log.debug(""Subject attribute not set. Therefore authentication is failed.""); } throw new AuthenticationFailedException(""Authentication Failed""); } String username = (String)session.getAttribute(IWAConstants.SUBJECT_ATTRIBUTE); StringTokenizer stringTokenizer = new StringTokenizer(username, ""@""); username = stringTokenizer.nextToken(); if (log.isDebugEnabled()) { log.debug(""Authenticate request received : AuthType - "" + request.getAuthType() + "", User - "" + username); } boolean isAuthenticated; UserStoreManager userStoreManager; try { userStoreManager = (UserStoreManager) CarbonContext.getThreadLocalCarbonContext().getUserRealm() .getUserStoreManager(); isAuthenticated = userStoreManager.isExistingUser(MultitenantUtils.getTenantAwareUsername(username)); } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new AuthenticationFailedException(""IWAAuthenticator failed while trying to find user existence"", e); } if (!isAuthenticated) { if (log.isDebugEnabled()) { log.debug(""user authentication failed, user:"" + username + "" is not in the user store""); } throw new AuthenticationFailedException(""Authentication Failed""); } username = FrameworkUtils.prependUserStoreDomainToName(username); context.setSubject(AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(username)); }"
66,"public boolean isValidValue(final MeasurementVariable var, final String value, final String cValueId, final boolean validateDateForDB) { if (value == null || """".equals(value.trim())) { return true; } if (var.getMinRange() != null && var.getMaxRange() != null) { if (ValidationServiceImpl.MISSING_VAL.equals(value.trim())) { return true; } return NumberUtils.isNumber(value); } else if (validateDateForDB && var != null && var.getDataTypeId() != null && var.getDataTypeId() == TermId.DATE_VARIABLE.getId()) { return DateUtil.isValidDate(value); } else if (var.getDataType() != null && var.getDataType().equalsIgnoreCase(ValidationServiceImpl.DATA_TYPE_NUMERIC)) { <START> if (ValidationServiceImpl.MISSING_VAL.equals(value.trim())) { <END> return true; } return NumberUtils.isNumber(value.trim()); } return true; }",Potential null pointer exception remove != null check. check valid string values StringUtils.isNotBlank method,"public boolean isValidValue(final MeasurementVariable var, final String value, final String cValueId, final boolean validateDateForDB) { if (StringUtils.isBlank(value)) { return true; } if (var.getMinRange() != null && var.getMaxRange() != null) { return this.validateIfValueIsMissingOrNumber(value.trim()); } else if (validateDateForDB && var != null && var.getDataTypeId() != null && var.getDataTypeId() == TermId.DATE_VARIABLE.getId()) { return DateUtil.isValidDate(value); } else if (StringUtils.isNotBlank(var.getDataType()) && var.getDataType().equalsIgnoreCase(ValidationServiceImpl.DATA_TYPE_NUMERIC)) { return this.validateIfValueIsMissingOrNumber(value.trim()); } return true; }"
67,"public final void run(Configuration config, final Environment env) throws Exception { env.jersey().register(HttpRemotingJerseyFeature.INSTANCE); env.jersey().register(new TestResource()); <START> env.jersey().register(new EmptyOptionalTo204ExceptionMapper()); <END> env.getObjectMapper().registerModule(new Jdk8Module()); }",do need this,"public final void run(Configuration config, final Environment env) throws Exception { env.jersey().register(HttpRemotingJerseyFeature.INSTANCE); env.jersey().register(new JacksonMessageBodyProvider(ObjectMappers.newServerObjectMapper())); env.jersey().register(new EmptyOptionalTo204ExceptionMapper()); env.jersey().register(new TestResource()); }"
68,"public PlaintextAuthenticateRequest(final String username, final String password) { super(KEY); <START> this.username = username; <END> this.password = password; }",Null check,"public PlaintextAuthenticateRequest(final String username, final String password) { super(KEY); this.username = checkNotNull(username); this.password = checkNotNull(password); }"
69,"public Map.Entry<K, Collection<V>> next() { final Map.Entry<K, Collection<V>> entry = super.next(); final K key = entry.getKey(); final Collection<V> value = entry.getValue(); <START> return new UnmodifiableMapEntry<>(key, value); <END> }",inline key IMO,"public Map.Entry<K, Collection<V>> next() { final Map.Entry<K, Collection<V>> entry = super.next(); return new UnmodifiableMapEntry<>(entry.getKey(), entry.getValue()); }"
70,"public void restart(String uiCommand) { final UIConstants constants = ConstantsManager.getInstance().getConstants(); final UIMessages messages = ConstantsManager.getInstance().getMessages(); HostRestartConfirmationModel model = new HostRestartConfirmationModel(); setConfirmWindow(model); model.setTitle(constants.restartHostsTitle()); model.setHelpTag(HelpTag.restart_host); model.setHashName(""restart_host""); model.setMessage(constants.areYouSureYouWantToRestartTheFollowingHostsMsg()); ArrayList<String> items = new ArrayList<>(); for (Object item : getSelectedItems()) { VDS vds = (VDS) item; int runningVms = vds.getVmCount(); if (runningVms > 0) { items.add(messages.hostNumberOfRunningVms(vds.getName(), runningVms)); } else { items.add(vds.getName()); } } model.setItems(items); <START> model.setForceToMaintenanceLabel(ConstantsManager.getInstance().getConstants().forceToMaintenance()); <END> model.getForceToMaintenance().setEntity(false); model.getForceToMaintenance().setIsAvailable(true); model.getForceToMaintenance().setIsChangeable(true); UICommand tempVar = new UICommand(uiCommand, this); tempVar.setTitle(constants.ok()); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand(""Cancel"", this); tempVar2.setTitle(constants.cancel()); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); }","other places this confirmation called? If not, leave label setting defined in HostRestartConfirmationPopupView","public void restart(String uiCommand) { final UIConstants constants = ConstantsManager.getInstance().getConstants(); final UIMessages messages = ConstantsManager.getInstance().getMessages(); HostRestartConfirmationModel model = new HostRestartConfirmationModel(); setConfirmWindow(model); model.setTitle(constants.restartHostsTitle()); model.setHelpTag(HelpTag.restart_host); model.setHashName(""restart_host""); model.setMessage(constants.areYouSureYouWantToRestartTheFollowingHostsMsg()); ArrayList<String> items = new ArrayList<>(); for (Object item : getSelectedItems()) { VDS vds = (VDS) item; int runningVms = vds.getVmCount(); if (runningVms > 0) { items.add(messages.hostNumberOfRunningVms(vds.getName(), runningVms)); } else { items.add(vds.getName()); } } model.setItems(items); UICommand tempVar = new UICommand(uiCommand, this); tempVar.setTitle(constants.ok()); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand(""Cancel"", this); tempVar2.setTitle(constants.cancel()); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); }"
71,public String getSQL() { StringBuffer sb = new StringBuffer(); sb.append(m_def.getName()).append(Tokens.T_OPENBRACKET); switch (m_def.getId()) { case FunctionId.FUNC_VOLT_SINCE_EPOCH: case FunctionId.FUNC_VOLT_TO_TIMESTAMP: case FunctionId.FUNC_VOLT_TRUNCATE_TIMESTAMP: { int timeUnit = ((Number) nodes[0].valueData).intValue(); sb.append(Tokens.getKeyword(timeUnit)); break; } default: sb.append(nodes[0].getSQL()); break; } for (int ii = 1; ii < nodes.length; ii++) { if (nodes[ii] != null) { sb.append(Tokens.T_COMMA).append(nodes[ii].getSQL()); } else { assert (ii == 2); assert (m_def.getId() == FunctionId.FUNC_VOLT_REGEXP_POSITION); <START> } <END> } sb.append(Tokens.T_CLOSEBRACKET); return sb.toString(); },"clear exception is warranted -- is strange inconsistent for FUNC_VOLT_REGEXP_POSITION define extra nodes[] element set null vs. defining element? In other words, this fix works, is a cleaner fix",public String getSQL() { StringBuffer sb = new StringBuffer(); sb.append(m_def.getName()).append(Tokens.T_OPENBRACKET); switch (m_def.getId()) { case FunctionId.FUNC_VOLT_SINCE_EPOCH: case FunctionId.FUNC_VOLT_TO_TIMESTAMP: case FunctionId.FUNC_VOLT_TRUNCATE_TIMESTAMP: { int timeUnit = ((Number) nodes[0].valueData).intValue(); sb.append(Tokens.getKeyword(timeUnit)); break; } default: sb.append(nodes[0].getSQL()); break; } for (int ii = 1; ii < nodes.length; ii++) { if (nodes[ii] != null) { sb.append(Tokens.T_COMMA).append(nodes[ii].getSQL()); } else { } } sb.append(Tokens.T_CLOSEBRACKET); return sb.toString(); }
72,<START> public String getClientInfo() <END> { return clientInfo.orElse(null); },return Optional<String> implementation decide do if is present,public Optional<String> getClientInfo() { return clientInfo; }
73,public synchronized ITmfTimestamp readEnd() { try { Long pos = fFile.length() - 1; while (pos > 0) { while (pos > 0) { fFile.seek(pos - 1); <START> if (fFile.read() == '<') { <END> break; } pos--; } ITmfLocation location = new TmfLongLocation(pos); ITmfContext context = seekEvent(location); ITmfEvent event = parseEvent(context); context.dispose(); if (event != null) { return event.getTimestamp(); } pos--; } } catch (IOException e) { return null; } return null; },"If element for is ""<log>"", this code returns location of 'l'. location of '<', requires extra loop (or fail if event)","public synchronized ITmfTimestamp readEnd() { byte[] inputNameBytes = (""<"" + fRecordInputElement.getInputName()).getBytes(); try { Long pos = fFile.length() - inputNameBytes.length; while (pos >= 0) { searchloop: while (pos >= 0) { fFile.seek(pos); for (byte c : inputNameBytes) { if (c != fFile.read()) { break searchloop; } } pos--; } ITmfLocation location = new TmfLongLocation(pos); ITmfContext context = seekEvent(location); ITmfEvent event = parseEvent(context); context.dispose(); if (event != null) { return event.getTimestamp(); } pos -= inputNameBytes.length; } } catch (IOException e) { return null; } return null; }"
74,"<START> public List<ClusterNode> mapKeyToPrimaryAndBackupsList(K key) { <END> A.notNull(key, ""key""); return cctx.affinity().nodesByPartition(partition(key), topologyVersion()); }","Please, write in line: @Override public reason copy-paste implementation mapKeyToPrimaryAndBackupsList","@Override public List<ClusterNode> mapKeyToPrimaryAndBackupsList(K key) { A.notNull(key, ""key""); return cctx.affinity().nodesByPartition(partition(key), topologyVersion()); }"
75,"public void testListDList() { DList<Integer> d = listDList(List.range(0, 1000)); <START> assertThat(d.toJavaList(), is(d.run().toJavaList())); <END> }","instead of testing assertThat(d.toJavaList(), is(d.run().toJavaList())); (that check toJavaList() is alias of run().toJavaList()) I test assertThat(d.toJavaList(), is(List.range(0, 1000).toJavaList())); (same for methods)","public void testListDList() { DList<Integer> d = listDList(List.range(0, 1000)); assertThat(d.toJavaList(), is(List.range(0, 1000).toJavaList())); }"
76,"public void set(String name, String value) { String attribute = (name != null ? name.trim() : """") + "": "" + (value != null ? value.trim() : """"); lines.clear(); while (attribute.indexOf(',') > 0 || attribute.length() > 71) { int split = attribute.indexOf(',') + 1; if (split == 0) { split = 70; <START> } <END> lines.add(attribute.substring(0, split)); attribute = "" "" + attribute.substring(split); } lines.add(attribute); }","this split comma (or index 70), for commas e.g. in version ranges ? I thinking reuse ManifestElement.parseHeader() instead of this low-level (potentially error-prone) MANIFEST parsing. fill n elements total length > 70 render n-1 elements ManifestElement.toString() line. Wdyt","public void set(String name, String value) { lines.clear(); try { ManifestElement[] elements = ManifestElement.parseHeader(name, value); String firstLine = (name != null ? name.trim() : """") + "": "" + elements[0]; if (elements.length > 1) { firstLine = firstLine + "",""; } lines.add(firstLine); for (int i = 1; i < elements.length - 1; i++) { lines.add("" "" + elements[i] + "",""); } if (elements.length > 1) { lines.add("" "" + elements[elements.length - 1]); } } catch (BundleException e) { throw new RuntimeException(e); } }"
77,"protected void loadPersonFile() throws IOException { final String METHOD_NAME = ""loadPersonFile()""; File personnelFile = FileDialogs.openPersonnel(frame).orElse(null); if (personnelFile != null) { <START> InputStream is = new FileInputStream(personnelFile); <END> MekHQ.getLogger().log(getClass(), METHOD_NAME, LogLevel.INFO, ""Starting load of personnel file from XML...""); Document xmlDoc = null; try { DocumentBuilder db = MekHqXmlUtil.newSafeDocumentBuilder(); xmlDoc = db.parse(is); is.close(); } catch (Exception ex) { MekHQ.getLogger().error(getClass(), METHOD_NAME, ex); } Element personnelEle = xmlDoc.getDocumentElement(); NodeList nl = personnelEle.getChildNodes(); personnelEle.normalize(); Version version = new Version(personnelEle.getAttribute(""version"")); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeType() != Node.ELEMENT_NODE) { continue; } if (!wn2.getNodeName().equalsIgnoreCase(""person"")) { MekHQ.getLogger().log(getClass(), METHOD_NAME, LogLevel.ERROR, ""Unknown node type not loaded in Personnel nodes: "" + wn2.getNodeName()); continue; } Person p = Person.generateInstanceFromXML(wn2, getCampaign(), version); if (getCampaign().getPerson(p.getId()) != null && getCampaign().getPerson(p.getId()).getFullName() .equals(p.getFullName())) { MekHQ.getLogger().log(getClass(), METHOD_NAME, LogLevel.ERROR, ""ERROR: Cannot load person who exists, ignoring. (Name: "" + p.getFullName() + "")""); p = null; } if (p != null) { getCampaign().addPersonWithoutId(p, true); p.setUnitId(null); p.clearTechUnitIDs(); } } MekHQ.getLogger().log(getClass(), METHOD_NAME, LogLevel.INFO, ""Finished load of personnel file""); } }",try-with-resources? (the in this file),"protected void loadPersonFile() { final String METHOD_NAME = ""loadPersonFile()""; File personnelFile = FileDialogs.openPersonnel(frame).orElse(null); if (personnelFile != null) { MekHQ.getLogger().log(getClass(), METHOD_NAME, LogLevel.INFO, ""Starting load of personnel file from XML...""); Document xmlDoc = null; try (InputStream is = new FileInputStream(personnelFile)) { DocumentBuilder db = MekHqXmlUtil.newSafeDocumentBuilder(); xmlDoc = db.parse(is); } catch (Exception ex) { MekHQ.getLogger().error(getClass(), METHOD_NAME, ex); } Element personnelEle = xmlDoc.getDocumentElement(); NodeList nl = personnelEle.getChildNodes(); personnelEle.normalize(); Version version = new Version(personnelEle.getAttribute(""version"")); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeType() != Node.ELEMENT_NODE) { continue; } if (!wn2.getNodeName().equalsIgnoreCase(""person"")) { MekHQ.getLogger().log(getClass(), METHOD_NAME, LogLevel.ERROR, ""Unknown node type not loaded in Personnel nodes: "" + wn2.getNodeName()); continue; } Person p = Person.generateInstanceFromXML(wn2, getCampaign(), version); if (getCampaign().getPerson(p.getId()) != null && getCampaign().getPerson(p.getId()).getFullName() .equals(p.getFullName())) { MekHQ.getLogger().log(getClass(), METHOD_NAME, LogLevel.ERROR, ""ERROR: Cannot load person who exists, ignoring. (Name: "" + p.getFullName() + "")""); p = null; } if (p != null) { getCampaign().addPersonWithoutId(p, true); p.setUnitId(null); p.clearTechUnitIDs(); } } MekHQ.getLogger().log(getClass(), METHOD_NAME, LogLevel.INFO, ""Finished load of personnel file""); } }"
78,"private int calculateRunSize(int sizeIdx) { int maxElements = 1 << pageShifts - SizeClasses.LOG2_QUANTUM; <START> int runSize = 0, nElements; <END> final int elemSize = arena.sizeIdx2size(sizeIdx); do { runSize += pageSize; nElements = runSize / elemSize; if (nElements >= maxElements) { break; } } while (runSize != nElements * elemSize); while (nElements > maxElements) { runSize -= pageSize; nElements = runSize / elemSize; } assert nElements > 0; assert runSize <= chunkSize; assert runSize >= elemSize; return runSize; }",please line declaration do in netty,private int calculateRunSize(int sizeIdx) { int maxElements = 1 << pageShifts - SizeClasses.LOG2_QUANTUM; int runSize = 0; int nElements; final int elemSize = arena.sizeIdx2size(sizeIdx); do { runSize += pageSize; nElements = runSize / elemSize; } while (nElements < maxElements && runSize != nElements * elemSize); while (nElements > maxElements) { runSize -= pageSize; nElements = runSize / elemSize; } assert nElements > 0; assert runSize <= chunkSize; assert runSize >= elemSize; return runSize; }
79,"public void whenConsumerIsBlocked429() throws Exception { final FloodService.Flooder flooder = new FloodService.Flooder(eventType.getName(), FloodService.Type.CONSUMER_ET); NakadiControllerAT.blockFlooder(flooder); TestStreamingClient client = TestStreamingClient .create(URL, subscription.getId(), """") .start(); <START> Thread.sleep(2000); <END> Assert.assertEquals(MoreStatus.TOO_MANY_REQUESTS.getStatusCode(), client.getResponseCode()); Assert.assertEquals(""300"", client.getHeaderValue(""Retry-After"")); NakadiControllerAT.unblockFlooder(flooder); client = TestStreamingClient .create(URL, subscription.getId(), """") .start(); Thread.sleep(2000); Assert.assertEquals(HttpStatus.SC_OK, client.getResponseCode()); }","decided plain sleeps wait specific thing. Please a other tests in class. do waitFor(() -> assertThat(MoreStatus.TOO_MANY_REQUESTS.getStatusCode(), client.getResponseCode()));","public void whenConsumerIsBlocked429() throws Exception { final FloodService.Flooder flooder = new FloodService.Flooder(eventType.getName(), FloodService.Type.CONSUMER_ET); SettingsControllerAT.blockFlooder(flooder); final TestStreamingClient client1 = TestStreamingClient .create(URL, subscription.getId(), """") .start(); waitFor(() -> { Assert.assertEquals(MoreStatus.TOO_MANY_REQUESTS.getStatusCode(), client1.getResponseCode()); Assert.assertEquals(""300"", client1.getHeaderValue(""Retry-After"")); }); SettingsControllerAT.unblockFlooder(flooder); final TestStreamingClient client2 = TestStreamingClient .create(URL, subscription.getId(), """") .start(); waitFor(() -> Assert.assertEquals(HttpStatus.SC_OK, client2.getResponseCode())); }"
80,"public static VdsStatic map(Host model, VdsStatic template) { VdsStatic entity = template != null ? template : new VdsStatic(); if (model.isSetId()) { entity.setId(GuidUtils.asGuid(model.getId())); } if (model.isSetName()) { entity.setVdsName(model.getName()); } if (model.isSetCluster() && model.getCluster().isSetId()) { entity.setVdsGroupId(GuidUtils.asGuid(model.getCluster().getId())); } if (model.isSetAddress()) { entity.setHostName(model.getAddress()); } if (model.isSetPort() && model.getPort() > 0) { entity.setPort(model.getPort()); } else { entity.setPort(DEFAULT_VDSM_PORT); } if (model.isSetSsh() && model.getSsh().isSetUser() && model.getSsh().getUser().isSetUserName()) { entity.setSshUsername(model.getSsh().getUser().getUserName()); } else { entity.setSshUsername(DEFAULT_ROOT_USERNAME); <START> } <END> if (model.isSetSsh() && model.getSsh().isSetPort() && model.getSsh().getPort() > 0) { entity.setSshPort(model.getSsh().getPort()); } else { entity.setSshPort(DEFAULT_SSH_PORT); } if (model.isSetSsh() && model.getSsh().isSetFingerprint()) { entity.setSshKeyFingerprint(model.getSsh().getFingerprint()); } if (model.isSetPowerManagement()) { entity = map(model.getPowerManagement(), entity); } if (model.isSetStorageManager()) { if (model.getStorageManager().getPriority() != null) { entity.setVdsSpmPriority(model.getStorageManager().getPriority()); } } if (model.isSetDisplay() && model.getDisplay().isSetAddress()) { entity.setConsoleAddress("""".equals(model.getDisplay().getAddress()) ? null : model.getDisplay().getAddress()); } return entity; }",supported,"public static VdsStatic map(Host model, VdsStatic template) { VdsStatic entity = template != null ? template : new VdsStatic(); if (model.isSetId()) { entity.setId(GuidUtils.asGuid(model.getId())); } if (model.isSetName()) { entity.setVdsName(model.getName()); } if (model.isSetCluster() && model.getCluster().isSetId()) { entity.setVdsGroupId(GuidUtils.asGuid(model.getCluster().getId())); } if (model.isSetAddress()) { entity.setHostName(model.getAddress()); } if (model.isSetPort() && model.getPort() > 0) { entity.setPort(model.getPort()); } else { entity.setPort(DEFAULT_VDSM_PORT); } if (model.isSetSsh() && model.getSsh().isSetPort() && model.getSsh().getPort() > 0) { entity.setSshPort(model.getSsh().getPort()); } else { entity.setSshPort(DEFAULT_SSH_PORT); } if (model.isSetSsh() && model.getSsh().isSetFingerprint()) { entity.setSshKeyFingerprint(model.getSsh().getFingerprint()); } if (model.isSetPowerManagement()) { entity = map(model.getPowerManagement(), entity); } if (model.isSetStorageManager()) { if (model.getStorageManager().getPriority() != null) { entity.setVdsSpmPriority(model.getStorageManager().getPriority()); } } if (model.isSetDisplay() && model.getDisplay().isSetAddress()) { entity.setConsoleAddress("""".equals(model.getDisplay().getAddress()) ? null : model.getDisplay().getAddress()); } return entity; }"
81,"public ChecksumDTO extract(final Jar jar, final Locale locale) { Objects.requireNonNull(jar, ""jar""); Objects.requireNonNull(locale, ""locale""); ChecksumDTO checksumDTO = new ChecksumDTO(); checksumDTO.md5 = calcChecksum(jar, ""MD5""); <START> checksumDTO.sha1 = calcChecksum(jar, ""SHA-1""); <END> checksumDTO.sha256 = calcChecksum(jar, ""SHA-256""); if (checksumDTO.md5 == null && checksumDTO.sha1 == null && checksumDTO.sha256 == null) { return null; } return checksumDTO; }","aQute.libg.cryptography package for classes compute MD5, SHA1, SHA256. provide a nice asHex method return digest a hex string","public ChecksumDTO extract(final Jar jar, final Locale locale) { Objects.requireNonNull(jar, ""jar""); Objects.requireNonNull(locale, ""locale""); ChecksumDTO checksumDTO = new ChecksumDTO(); checksumDTO.md5 = calcChecksum(jar, MD5.ALGORITHM); checksumDTO.sha1 = calcChecksum(jar, SHA1.ALGORITHM); checksumDTO.sha256 = calcChecksum(jar, SHA256.ALGORITHM); checksumDTO.sha512 = calcChecksum(jar, SHA512.ALGORITHM); if (checksumDTO.md5 == null && checksumDTO.sha1 == null && checksumDTO.sha256 == null && checksumDTO.sha512 == null) { return null; } return checksumDTO; }"
82,"public void initializeDefaultPreferences() { IPreferenceStore store = Activator.getDefault().getPreferenceStore(); store.setDefault(PreferenceConstants.P_STANDARD, """"); store.setDefault(PreferenceConstants.P_CLASSIFICATION, """"); store.setDefault(PreferenceConstants.P_APPLICATION_DOMAIN, """"); store.setDefault(PreferenceConstants.P_FUNCTION, """"); store.setDefault(PreferenceConstants.P_TYPE, """"); store.setDefault(PreferenceConstants.P_DESCRIPTION, """"); <START> store.setDefault(PreferenceConstants.P_VERSION, """"); END> store.setDefault(PreferenceConstants.P_ORGANIZATION, """"); store.setDefault(PreferenceConstants.P_AUTHOR, """"); store.setDefault(PreferenceConstants.P_DATE, """"); store.setDefault(PreferenceConstants.P_REMARKS, """"); }",if this a preference,"public void initializeDefaultPreferences() { IPreferenceStore store = Activator.getDefault().getPreferenceStore(); store.setDefault(PreferenceConstants.P_STANDARD, """"); store.setDefault(PreferenceConstants.P_CLASSIFICATION, """"); store.setDefault(PreferenceConstants.P_APPLICATION_DOMAIN, """"); store.setDefault(PreferenceConstants.P_FUNCTION, """"); store.setDefault(PreferenceConstants.P_TYPE, """"); store.setDefault(PreferenceConstants.P_DESCRIPTION, """"); store.setDefault(PreferenceConstants.P_VERSION, ""1.0""); store.setDefault(PreferenceConstants.P_ORGANIZATION, """"); store.setDefault(PreferenceConstants.P_AUTHOR, System.getProperty(""user.name"")); store.setDefault(PreferenceConstants.P_REMARKS, """"); }"
83,"<START> public DruidQuerySignature(RowSignature rowSignature) <END> { this.isImmutable = false; this.rowSignature = rowSignature; this.virtualColumnPrefix = rowSignature == null ? ""v"" : Calcites.findUnusedPrefix( ""v"", new TreeSet<>(rowSignature.getRowOrder()) ); this.virtualColumnsByExpression = new HashMap<>(); this.virtualColumnsByName = new HashMap<>(); }",Please add @Nullable for param,"public DruidQuerySignature(RowSignature rowSignature) { this.isAggregateSignature = false; this.rowSignature = rowSignature; this.virtualColumnPrefix = rowSignature == null ? ""v"" : Calcites.findUnusedPrefix( ""v"", new TreeSet<>(rowSignature.getRowOrder()) ); this.virtualColumnsByExpression = new HashMap<>(); this.virtualColumnsByName = new HashMap<>(); }"
84,"public void clearDB() { try { dbOperator.update(""DELETE FROM projects""); dbOperator.update(""DELETE FROM project_versions""); dbOperator.update(""DELETE FROM project_properties""); dbOperator.update(""DELETE FROM project_permissions""); dbOperator.update(""DELETE FROM project_flows""); dbOperator.update(""DELETE FROM project_files""); dbOperator.update(""DELETE FROM project_events""); <START> dbOperator.update(""DELETE FROM project_flow_files""); <END> } catch (final SQLException e) { e.printStackTrace(); } }",nit: truncate faster delete <LINK_0>,"public void clearDB() { try { dbOperator.update(""TRUNCATE TABLE projects""); dbOperator.update(""TRUNCATE TABLE project_versions""); dbOperator.update(""TRUNCATE TABLE project_properties""); dbOperator.update(""TRUNCATE TABLE project_permissions""); dbOperator.update(""TRUNCATE TABLE project_flows""); dbOperator.update(""TRUNCATE TABLE project_files""); dbOperator.update(""TRUNCATE TABLE project_events""); dbOperator.update(""TRUNCATE TABLE project_flow_files""); } catch (final SQLException e) { e.printStackTrace(); } }"
85,"public void storeWorkerMetrics(final String workerId, final WorkerMetrics metrics) { if (metricCollectionEnabled) { final int numDataBlocksOnWorker = metrics.getNumDataBlocks(); if (numBlockByEvalIdForWorker != null && numBlockByEvalIdForWorker.containsKey(workerId)) { final int numDataBlocksOnDriver = numBlockByEvalIdForWorker.get(workerId); if (numDataBlocksOnWorker == numDataBlocksOnDriver) { final DataInfo dataInfo = new DataInfoImpl(numDataBlocksOnWorker); final EvaluatorParameters evaluatorParameters = new WorkerEvaluatorParameters(workerId, dataInfo, metrics); synchronized (workerEvalParams) { if (!workerEvalParams.containsKey(workerId)) { workerEvalParams.put(workerId, new ArrayList<>()); } workerEvalParams.get(workerId).add(evaluatorParameters); } } else { LOG.log(Level.FINE, ""{0} contains {1} blocks, driver says {2} blocks. Dropping metric."", new Object[]{workerId, numDataBlocksOnWorker, numDataBlocksOnDriver}); } } else { LOG.log(Level.FINE, ""No information about {0}. Dropping metric."", workerId); } } else { LOG.log(Level.FINE, ""Metric collection disabled. Dropping metric from {0}"", workerId); } if (this.dashboardEnabled) { try { metricsRequestQueue.put(String.format(""id=%s&metrics=%s&time=%d"", workerId, metrics, System.currentTimeMillis())); } catch (InterruptedException e) { <START> LOG.log(Level.WARNING, ""Dashboard: Interrupted while taking metrics to send from the queue - "", e); <END> } } }","separating dashboard MetricManager, need prepend 'Dashboard:' front of logging messages","public void storeWorkerMetrics(final String workerId, final WorkerMetrics metrics) { if (metricCollectionEnabled) { final int numDataBlocksOnWorker = metrics.getNumDataBlocks(); if (numBlockByEvalIdForWorker != null && numBlockByEvalIdForWorker.containsKey(workerId)) { final int numDataBlocksOnDriver = numBlockByEvalIdForWorker.get(workerId); if (numDataBlocksOnWorker == numDataBlocksOnDriver) { final DataInfo dataInfo = new DataInfoImpl(numDataBlocksOnWorker); final EvaluatorParameters evaluatorParameters = new WorkerEvaluatorParameters(workerId, dataInfo, metrics); synchronized (workerEvalParams) { if (!workerEvalParams.containsKey(workerId)) { workerEvalParams.put(workerId, new ArrayList<>()); } workerEvalParams.get(workerId).add(evaluatorParameters); } } else { LOG.log(Level.FINE, ""{0} contains {1} blocks, driver says {2} blocks. Dropping metric."", new Object[]{workerId, numDataBlocksOnWorker, numDataBlocksOnDriver}); } } else { LOG.log(Level.FINE, ""No information about {0}. Dropping metric."", workerId); } } else { LOG.log(Level.FINE, ""Metric collection disabled. Dropping metric from {0}"", workerId); } if (dashboardSetupStatus.dashboardEnabled) { try { metricsRequestQueue.put(String.format(""id=%s&metrics=%s&time=%d"", workerId, metrics, System.currentTimeMillis())); } catch (InterruptedException e) { LOG.log(Level.WARNING, ""Dashboard: Interrupted while taking metrics to send from the queue."", e); } } }"
86,public void handle(ExecutionContext context) { <START> NotFound reportMessage = new NotFound(System.currentTimeMillis()); <END> reportMessage.setRequestId(context.request().id()); reportMessage.setClientRequest(new io.gravitee.reporter.api.common.Request()); reportMessage.getClientRequest().setMethod(context.request().method()); reportMessage.getClientRequest().setUri(context.request().uri()); reportMessage.getClientRequest().setHeaders(new HttpHeaders(context.request().headers())); reporterService.report(reportMessage); next.handle(context); },I understand purpose of this. need create a dedicated Reportable for unmapped request ? I prefer of Metrics object for setting a dummy api-id (as for unknown application (id = 1)). WDYT,public void handle(ExecutionContext context) { Metrics metrics = context.request().metrics(); metrics.setApi(UNKNOWN_SERVICE); metrics.setApplication(UNKNOWN_SERVICE); if (logEnabled) { Buffer payload = Buffer.buffer(); context.request().bodyHandler(payload::appendBuffer).endHandler(aVoid -> { Log log = new Log(System.currentTimeMillis()); log.setRequestId(context.request().id()); log.setClientRequest(new io.gravitee.reporter.api.common.Request()); log.getClientRequest().setMethod(context.request().method()); log.getClientRequest().setUri(context.request().uri()); log.getClientRequest().setHeaders(new HttpHeaders(context.request().headers())); log.getClientRequest().setBody(payload.toString()); metrics.setLog(log); reporterService.report(metrics); next.handle(context); }); } else { reporterService.report(metrics); next.handle(context); } }
87,"public Map<String, String> devfileFileLocations() { <START> return singletonMap(null, devfileFileLocation); <END> }",please explain this null? strange put null key in map afraid bite later,public List<DevfileLocation> devfileFileLocations() { return singletonList( new DevfileLocation() { @Override public Optional<String> filename() { return Optional.empty(); } @Override public String location() { return devfileFileLocation; } }); }
88,"public void checkAttributeValue(PerunSessionImpl perunSession, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException { <START> List<String> value = (List<String>) attribute.getValue(); <END> for(String address : value) { if(!address.matches(IPv4_PATTERN) && !address.matches(IPv6_PATTERN) && !address.matches(IPv6_PATTERN_SHORT)) throw new WrongAttributeValueException(attribute, ""IP address is not in the correct format.""); } }","simple method ""valueAsList""","public void checkAttributeValue(PerunSessionImpl perunSession, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException { List<String> value = attribute.valueAsList(); for (String address : value) { if (!address.matches(IPv4_PATTERN) && !address.matches(IPv6_PATTERN) && !address.matches(IPv6_PATTERN_SHORT)) throw new WrongAttributeValueException(attribute, ""IP address is not in the correct format.""); } }"
89,"<START> public void setup(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) <END> throws InvalidKeyException, NoSuchAlgorithmException { if (interceptorManager.isPlaybackMode()) { connectionString = ""Endpoint=http://localhost:8080;Id=0000000000000;Secret=MDAwMDAw""; String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); client = new ConfigurationClientBuilder() .connectionString(connectionString) .endpoint(endpoint) .httpClient(interceptorManager.getPlaybackClient()) .buildClient(); } else { connectionString = Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); tokenCredential = new DefaultAzureCredentialBuilder().build(); String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); client = new ConfigurationClientBuilder() .httpClient(httpClient) .credential(tokenCredential) .endpoint(endpoint) .addPolicy(interceptorManager.getRecordPolicy()) .serviceVersion(serviceVersion) .buildClient(); } }",This method private,"private void setup(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) throws InvalidKeyException, NoSuchAlgorithmException { if (interceptorManager.isPlaybackMode()) { connectionString = ""Endpoint=http://localhost:8080;Id=0000000000000;Secret=MDAwMDAw""; String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); client = new ConfigurationClientBuilder() .connectionString(connectionString) .endpoint(endpoint) .httpClient(interceptorManager.getPlaybackClient()) .buildClient(); } else { connectionString = Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); tokenCredential = new DefaultAzureCredentialBuilder().build(); String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); client = new ConfigurationClientBuilder() .httpClient(httpClient) .credential(tokenCredential) .endpoint(endpoint) .addPolicy(interceptorManager.getRecordPolicy()) .serviceVersion(serviceVersion) .buildClient(); } }"
90,"public void testAllBlockComments() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(BlockCommentListenerCheck.class); final String path = getPath(""InputFullOfBlockComments.java""); if (new FileText(new File(path), StandardCharsets.UTF_8.name()) .getFullText().chars().anyMatch(character -> character == '\r')) { lineSeparator = ""\r\n""; } else { lineSeparator = ""\n""; <START> } <END> final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; verify(checkConfig, path, expected); Assert.assertTrue(""All comments should be empty"", ALL_COMMENTS.isEmpty()); }",sounds util method reused,"public void testAllBlockComments() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(BlockCommentListenerCheck.class); final String path = getPath(""InputFullOfBlockComments.java""); lineSeparator = CheckUtil.getLineSeparatorForFile(path, StandardCharsets.UTF_8); final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; verify(checkConfig, path, expected); Assert.assertTrue(""All comments should be empty"", ALL_COMMENTS.isEmpty()); }"
91,"static long applicationProc(long id, long sel, long arg0, long arg1) { Display display = getCurrent(); if (display == null && id != applicationDelegate.id) { objc_super super_struct = new objc_super (); super_struct.receiver = id; super_struct.super_class = OS.objc_msgSend (id, OS.sel_superclass); return OS.objc_msgSendSuper (super_struct, sel, arg0, arg1); } if (currAppDelegate != null) { if (currAppDelegate.respondsToSelector(sel)) OS.objc_msgSend(currAppDelegate.id, sel, arg0, arg1); } <START> if (sel == OS.sel_application_openFile_) { <END> String file = new NSString(arg1).getString(); Event event = new Event(); event.text = file; display.sendEvent(SWT.OpenDocument, event); return 1; } else if (sel == OS.sel_application_openFiles_) { NSArray files = new NSArray(arg1); long count = files.count(); for (int i=0; i<count; i++) { String file = new NSString(files.objectAtIndex(i)).getString(); Event event = new Event(); event.text = file; display.sendEvent(SWT.OpenDocument, event); } new NSApplication(arg0).replyToOpenOrPrint(OS.NSApplicationDelegateReplySuccess); } else if (sel == OS.sel_applicationShouldHandleReopen_hasVisibleWindows_) { final Event event = new Event(); display.sendEvent(SWT.Activate, event); return event.doit ? 1 : 0; } return 0; }",Convert switch for consistency,"static long applicationProc(long id, long sel, long arg0, long arg1) { Display display = getCurrent(); if (display == null && id != applicationDelegate.id) { objc_super super_struct = new objc_super (); super_struct.receiver = id; super_struct.super_class = OS.objc_msgSend (id, OS.sel_superclass); return OS.objc_msgSendSuper (super_struct, sel, arg0, arg1); } if (currAppDelegate != null) { if (currAppDelegate.respondsToSelector(sel)) OS.objc_msgSend(currAppDelegate.id, sel, arg0, arg1); } switch (Selector.valueOf(sel)) { case sel_application_openFile_: { String file = new NSString(arg1).getString(); Event event = new Event(); event.text = file; display.sendEvent(SWT.OpenDocument, event); return 1; } case sel_application_openFiles_: { NSArray files = new NSArray(arg1); long count = files.count(); for (int i=0; i<count; i++) { String file = new NSString(files.objectAtIndex(i)).getString(); Event event = new Event(); event.text = file; display.sendEvent(SWT.OpenDocument, event); } new NSApplication(arg0).replyToOpenOrPrint(OS.NSApplicationDelegateReplySuccess); return 0; } case sel_applicationShouldHandleReopen_hasVisibleWindows_: { final Event event = new Event(); display.sendEvent(SWT.Activate, event); return event.doit ? 1 : 0; } default: { return 0; } } }"
92,"void handleActionResult(final VdcActionType actionType, final VdcActionParametersBase parameters, final VdcReturnValueBase result, final IFrontendActionAsyncCallback callback, final Object state, final boolean showErrorDialog) { logger.log(Level.FINER, ""Retrieved action result from RunAction.""); FrontendActionAsyncResult f = new FrontendActionAsyncResult(actionType, parameters, result, state); boolean failedOnCanDoAction = !result.getCanDoAction(); if (failedOnCanDoAction) { result.setCanDoActionMessages((ArrayList<String>) translateError(result)); <START> } else if (showErrorDialog && result.getIsSyncronious() && !result.getSucceeded()) { <END> runActionExecutionFailed(actionType, result.getFault()); } callback.executed(f); if (showErrorDialog && failedOnCanDoAction && (getEventsHandler() != null) && (getEventsHandler().isRaiseErrorModalPanel(actionType, result.getFault()))) { ArrayList<String> messages = result.getCanDoActionMessages(); failureEventHandler(result.getDescription(), messages.isEmpty() ? Collections.singletonList(getConstants().noCanDoActionMessage()) : messages); } }","In case showErrorDialog=false messages aggregated, fault is localized (the localization of fault is part of runActionExecutionFailed(..)). Consider removing showErrorDialog 'if' pass runActionExecutionFailed(..). In runActionExecutionFailed(..) localize fault show dialog if !showErrorDialog","void handleActionResult(final VdcActionType actionType, final VdcActionParametersBase parameters, final VdcReturnValueBase result, final IFrontendActionAsyncCallback callback, final Object state, final boolean showErrorDialog) { logger.log(Level.FINER, ""Retrieved action result from RunAction.""); FrontendActionAsyncResult f = new FrontendActionAsyncResult(actionType, parameters, result, state); boolean failedOnCanDoAction = !result.getCanDoAction(); if (failedOnCanDoAction) { result.setCanDoActionMessages((ArrayList<String>) translateError(result)); } else if (!result.getSucceeded()) { VdcFault fault = result.getFault(); fault.setMessage(translateVdcFault(fault)); if (showErrorDialog && result.getIsSyncronious() && getEventsHandler() != null) { getEventsHandler().runActionExecutionFailed(actionType, fault); } } callback.executed(f); if (showErrorDialog && failedOnCanDoAction && (getEventsHandler() != null) && (getEventsHandler().isRaiseErrorModalPanel(actionType, result.getFault()))) { ArrayList<String> messages = result.getCanDoActionMessages(); failureEventHandler(result.getDescription(), messages.isEmpty() ? Collections.singletonList(getConstants().noCanDoActionMessage()) : messages); } }"
93,"private int computeNumberOfAvailableThreads() { Preconditions.checkState(getServerFactory() instanceof DefaultServerFactory, ""Unexpected serverFactory instance on TimeLockServerConfiguration.""); DefaultServerFactory serverFactory = (DefaultServerFactory) getServerFactory(); int maxServerThreads = serverFactory.getMaxThreads(); Preconditions.checkNotNull(serverFactory.getApplicationConnectors(), ""applicationConnectors of TimeLockServerConfiguration must not be null.""); Preconditions.checkState(serverFactory.getApplicationConnectors().get(0) instanceof HttpConnectorFactory, ""applicationConnectors of TimeLockServerConfiguration must have a HttpConnectorFactory instance.""); HttpConnectorFactory connectorFactory = (HttpConnectorFactory) serverFactory.getApplicationConnectors().get(0); <START> int selectorThreads = connectorFactory.getSelectorThreads().orElse(0); <END> int acceptorThreads = connectorFactory.getAcceptorThreads().orElse(0); return maxServerThreads - selectorThreads - acceptorThreads - 1; }","I minimum is 1 for of these, matters here, good consistent","private int computeNumberOfAvailableThreads() { Preconditions.checkState(getServerFactory() instanceof DefaultServerFactory, ""Unexpected serverFactory instance on TimeLockServerConfiguration.""); DefaultServerFactory serverFactory = (DefaultServerFactory) getServerFactory(); int maxServerThreads = serverFactory.getMaxThreads(); Preconditions.checkNotNull(serverFactory.getApplicationConnectors(), ""applicationConnectors of TimeLockServerConfiguration must not be null.""); Preconditions.checkState(serverFactory.getApplicationConnectors().get(0) instanceof HttpConnectorFactory, ""applicationConnectors of TimeLockServerConfiguration must have a HttpConnectorFactory instance.""); HttpConnectorFactory connectorFactory = (HttpConnectorFactory) serverFactory.getApplicationConnectors().get(0); int selectorThreads = connectorFactory.getSelectorThreads().orElse(1); int acceptorThreads = connectorFactory.getAcceptorThreads().orElse(1); return maxServerThreads - selectorThreads - acceptorThreads - 1; }"
94,"public OracleQuarterDiffFunction() { <START> super(""(select sign(i1) * floor(abs(i1)) from (values (trunc(-months_between(?1, ?2))/3)) as temp(i1))""); <END> }",a cast int enough,"public OracleQuarterDiffFunction() { super(""trunc(-months_between(?1, ?2)/3)""); }"
95,"private void captureScreenshot(String comment, WebDriver driver, WebElement element, boolean errorMessage) { if (getMessage(errorMessage) != null) { comment = getMessage(errorMessage); } LOGGER.debug(""DriverListener->captureScreenshot starting...""); try { if (errorMessage) { LOGGER.error(comment); Screenshot.captureFailure(driver, comment); } else { LOGGER.info(comment); if (MobileContextHelper.isInWebViewContext()) { MobileContextHelper.backUpContext(driver); Screenshot.capture(driver, comment); <START> MobileContextHelper.restoreContext(driver); <END> } else { Screenshot.capture(driver, comment); } } } catch (Exception e) { LOGGER.debug(""Unrecognized failure detected in DriverListener->captureScreenshot: "" + e.getMessage(), e); } finally { resetMessages(); } LOGGER.debug(""DriverListener->captureScreenshot finished...""); }",I sense this if (MobileContextHelper.isInWebViewContext()),"private void captureScreenshot(String comment, WebDriver driver, WebElement element, boolean errorMessage) { if (getMessage(errorMessage) != null) { comment = getMessage(errorMessage); } LOGGER.debug(""DriverListener->captureScreenshot starting...""); try { if (errorMessage) { LOGGER.error(comment); Screenshot.captureFailure(driver, comment); } else { LOGGER.info(comment); MobileContextHelper contextHelper = new MobileContextHelper(); if (contextHelper.isInWebViewContext(driver)) { String context = contextHelper.getContext(driver); contextHelper.changeToNativeAppContext(driver); Screenshot.capture(driver, comment); contextHelper.setContext(context, driver); } else { Screenshot.capture(driver, comment); } } } catch (Exception e) { LOGGER.debug(""Unrecognized failure detected in DriverListener->captureScreenshot: "" + e.getMessage(), e); } finally { resetMessages(); } LOGGER.debug(""DriverListener->captureScreenshot finished...""); }"
96,"void imageIncoming(ImageReaderProxy imageReader) { synchronized (mLock) { if (mClosed) { return; } ImageProxy image; do { image = null; try { image = imageReader.acquireNextImage(); } catch (IllegalStateException e) { <START> Log.e(TAG, ""Failed to acquire latest image."", e); <END> } finally { if (image != null) { mPendingImages.put(image.getTimestamp(), image); matchImages(); } } } while (image != null); } }","this logged time imageIncoming() is called? condition break out of do/while loop. If case, logging all","void imageIncoming(ImageReaderProxy imageReader) { synchronized (mLock) { if (mClosed) { return; } ImageProxy image; do { image = null; try { image = imageReader.acquireNextImage(); } catch (IllegalStateException e) { Log.e(TAG, ""Failed to acquire next image."", e); } finally { if (image != null) { mPendingImages.put(image.getTimestamp(), image); matchImages(); } } } while (image != null); } }"
97,"public void trackedMessagesReplicatedToPassive() throws Exception { clusterControl.terminateOnePassive(); storeProxy.getAndAppend(42L, createPayload(42L)); clusterControl.startOneServer(); clusterControl.waitForRunningPassivesInStandby(); passiveEntity = observableClusterTierServerEntityService.getServedPassiveEntities().get(1); passiveMessageHandler = passiveEntity.getMessageHandler(); <START> Assert.assertThat(passiveMessageHandler.getTrackedClients().count(), is(1L)); END> Map<Long, EhcacheEntityResponse> responses = passiveMessageHandler.getTrackedResponsesForSegment(11, passiveMessageHandler.getTrackedClients().findFirst().get()); assertThat(responses).hasSize(1); }","this assertion is pretty popular, I guess refactor in method. assertThat(passiveMessageHandler.getTrackerClients().count()).is(x)","public void trackedMessagesReplicatedToPassive() throws Exception { clusterControl.terminateOnePassive(); storeProxy.getAndAppend(42L, createPayload(42L)); clusterControl.startOneServer(); clusterControl.waitForRunningPassivesInStandby(); passiveEntity = observableClusterTierServerEntityService.getServedPassiveEntities().get(1); passiveMessageHandler = passiveEntity.getMessageHandler(); assertThat(passiveMessageHandler.getTrackedClients().count()).isEqualTo(1L); Map<Long, EhcacheEntityResponse> responses = passiveMessageHandler.getTrackedResponsesForSegment(KEY_ENDS_UP_IN_SEGMENT_11, passiveMessageHandler.getTrackedClients().findFirst().get()); assertThat(responses).hasSize(1); }"
98,"public void Start() { if (!havePermission) { final SoundRecorder me = this; form.runOnUiThread(new Runnable() { @Override public void run() { <START> form.askPermission(new BulkPermissionRequest(me, ""AudioRecord"", <END> Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE) { @Override public void onGranted() { me.havePermission = true; me.Start(); } }); } }); return; } if (controller != null) { Log.i(TAG, ""Start() called, but already recording to "" + controller.file); return; } Log.i(TAG, ""Start() called""); if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { form.dispatchErrorOccurredEvent( this, ""Start"", ErrorMessages.ERROR_MEDIA_EXTERNAL_STORAGE_NOT_AVAILABLE); return; } try { controller = new RecordingController(savedRecording); } catch (PermissionException e) { form.dispatchPermissionDeniedEvent(this, ""Start"", e); return; } catch (Throwable t) { form.dispatchErrorOccurredEvent( this, ""Start"", ErrorMessages.ERROR_SOUND_RECORDER_CANNOT_CREATE, t.getMessage()); return; } try { controller.start(); } catch (Throwable t) { controller = null; form.dispatchErrorOccurredEvent( this, ""Start"", ErrorMessages.ERROR_SOUND_RECORDER_CANNOT_CREATE, t.getMessage()); return; } StartedRecording(); }","argument is name of calling function, ""Start"", ""AudioRecord""","public void Start() { if (!havePermission) { final SoundRecorder me = this; form.runOnUiThread(new Runnable() { @Override public void run() { form.askPermission(new BulkPermissionRequest(me, ""Start"", Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE) { @Override public void onGranted() { me.havePermission = true; me.Start(); } }); } }); return; } if (controller != null) { Log.i(TAG, ""Start() called, but already recording to "" + controller.file); return; } Log.i(TAG, ""Start() called""); if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { form.dispatchErrorOccurredEvent( this, ""Start"", ErrorMessages.ERROR_MEDIA_EXTERNAL_STORAGE_NOT_AVAILABLE); return; } try { controller = new RecordingController(savedRecording); } catch (PermissionException e) { form.dispatchPermissionDeniedEvent(this, ""Start"", e); return; } catch (Throwable t) { form.dispatchErrorOccurredEvent( this, ""Start"", ErrorMessages.ERROR_SOUND_RECORDER_CANNOT_CREATE, t.getMessage()); return; } try { controller.start(); } catch (Throwable t) { controller = null; form.dispatchErrorOccurredEvent( this, ""Start"", ErrorMessages.ERROR_SOUND_RECORDER_CANNOT_CREATE, t.getMessage()); return; } StartedRecording(); }"
99,"private Class<?> loadClass(String className) { Class<?> clazz = null; try { clazz = classLoader.loadClass(className); <START> } catch (ClassNotFoundException ex) { <END> } if (clazz == null) { throw new ClassFileInfoException(""Unable to load class "" + className); } return clazz; }","Instead of suppressing exception checking for null, raise exception catch block instead","private Class<?> loadClass(String className) { log.trace(""Loading class with class loader: "" + className); Class<?> clazz = null; try { clazz = classLoader.loadClass(className); } catch (ClassNotFoundException ex) { throw new ClassFileInfoException(""Unable to load class "" + className); } return clazz; }"
100,void columnsTabToggle(final GuidedDecisionTableView.Presenter decisionTablePresenter) { <START> final boolean decisionTableIsEditable = !decisionTablePresenter.isReadOnly(); <END> final boolean decisionTableHasEditableColumns = decisionTablePresenter.hasEditableColumns(); if (!decisionTableIsEditable || !decisionTableHasEditableColumns) { disableColumnsPage(); } else { enableColumnsPage(); } },"I this method work properly, please follow steps below: - Log UserA - Open Pricing loans table, append row / change some data - table opened unsaved changes UserA - Simultaneously in new private window log UserB - Open Pricing loans table, is locked UserA, is read Columns tab is enabled",void columnsTabToggle(final GuidedDecisionTableView.Presenter decisionTablePresenter) { columnsTabToggle(isGuidedDecisionTableEditable(decisionTablePresenter)); }
101,"void next(ServiceBusReceivedMessageContext message) { try { <START> if (timeoutBeforeNextMessageOperation != null && !timeoutBeforeNextMessageOperation.isDisposed()) { <END> timeoutBeforeNextMessageOperation.dispose(); } emitter.next(message); remaining.decrementAndGet(); timeoutBeforeNextMessageOperation = getShortTimeoutBetweenMessages(); } catch (Exception e) { logger.warning(""Exception occurred while publishing downstream."", e); error(e); } }","This reactive create a new Mono operation everytime a message in. a combination of Flux.swithOnNext(publisher).takeUntil(notCancelled) a new item is emitted publisher if is a next message? for item emitted, delay interval. if item is emitted, cancel emitter","void next(ServiceBusReceivedMessageContext message) { try { emitter.next(message); messageReceivedSink.next(message); remaining.decrementAndGet(); } catch (Exception e) { logger.warning(""Exception occurred while publishing downstream."", e); error(e); } }"
102,"protected void handleCreateTarget() { final Map<String, String> commands = uiManager.getAddTargetCommands(); final Map<String, Image> images = uiManager.getTargetIcons(); if (!commands.isEmpty()) { <START> Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); <END> ListDialog ld = new ListDialog(shell); ld.setTitle(""New Target""); ld.setMessage(""Select target type to create""); ld.setContentProvider(new ArrayContentProvider()); ld.setLabelProvider(new LabelProvider() { @Override public String getText(Object element) { return (String)element; } @Override public Image getImage(Object element) { return images.get(element); } }); ld.setInput(commands.keySet().toArray()); switch(ld.open()) { case Window.CANCEL: return; case Window.OK: String command = commands.get((String) (ld.getResult()[0])); Activator.runCommand(command); return; default: } } }","get shell control of current element, i.e. getControl().getShell()","protected void handleCreateTarget() { final Map<String, String> commands = uiManager.getAddTargetCommands(); final Map<String, Image> images = uiManager.getTargetIcons(); if (!commands.isEmpty()) { ListDialog ld = new ListDialog(getShell()); ld.setTitle(""New Launch Target""); ld.setMessage(""Select target type to create""); ld.setContentProvider(new ArrayContentProvider()); ld.setLabelProvider(new LabelProvider() { @Override public String getText(Object element) { return (String)element; } @Override public Image getImage(Object element) { return images.get(element); } }); ld.setInput(commands.keySet().toArray()); switch(ld.open()) { case Window.CANCEL: return; case Window.OK: String command = commands.get((String) (ld.getResult()[0])); Activator.runCommand(command); return; default: } } }"
103,"public void addQueueNames(String... queueNames) { try { addQueues(Arrays.stream(queueNames)); } catch (AmqpIOException e) { <START> throw new AmqpIOException(""Failed to add "" + queueNames, e.getCause()); <END> } super.addQueueNames(queueNames); }",queueNames wrapped Arrays.asList(): ![array_in_sout](<LINK_0>,"public void addQueueNames(String... queueNames) { try { addQueues(Arrays.stream(queueNames)); } catch (AmqpIOException e) { throw new AmqpIOException(""Failed to add "" + Arrays.asList(queueNames), e.getCause()); } super.addQueueNames(queueNames); }"
104,<START> public void setRefSpecs(RefSpec... specs) { <END> this.refSpecs.clear(); for (RefSpec spec : specs) refSpecs.add(spec); },Missing checkCallable(). a variant takes Collection too,public FetchCommand setRefSpecs(RefSpec... specs) { checkCallable(); this.refSpecs.clear(); for (RefSpec spec : specs) refSpecs.add(spec); return this; }
105,"public <V> V get(final String key) throws IllegalArgumentException { if (!sideEffects.containsKey(key)) { if (!closed) { final RequestMessage msg = RequestMessage.build(Tokens.OPS_GATHER) .addArg(Tokens.ARGS_SIDE_EFFECT, serverSideEffect) .addArg(Tokens.ARGS_SIDE_EFFECT_KEY, key) .addArg(Tokens.ARGS_HOST, host) .processor(""traversal"").create(); try { <START> final Result result = client.submitAsync(msg).get().one(); <END> sideEffects.put(key, null == result ? null : result.getObject()); if (keys.isEmpty()) keys = new HashSet<>(); keys.add(key); } catch (Exception ex) { final Throwable root = ExceptionUtils.getRootCause(ex); final String exMsg = null == root ? """" : root.getMessage(); if (exMsg.equals(""Could not find side-effects for "" + serverSideEffect + ""."")) sideEffects.put(key, null); else throw new RuntimeException(""Could not get keys"", root); } } else { sideEffects.put(key, null); } } return (V) sideEffects.get(key); }",one() suffice. Side-effects aggregated internally returned ResultSet return Result object,"public <V> V get(final String key) throws IllegalArgumentException { if (!sideEffects.containsKey(key)) { if (!closed) { final RequestMessage msg = RequestMessage.build(Tokens.OPS_GATHER) .addArg(Tokens.ARGS_SIDE_EFFECT, serverSideEffect) .addArg(Tokens.ARGS_SIDE_EFFECT_KEY, key) .addArg(Tokens.ARGS_HOST, host) .processor(""traversal"").create(); try { final Result result = client.submitAsync(msg).get().one(); sideEffects.put(key, null == result ? null : result.getObject()); if (keys.equals(Collections.emptySet())) keys = new HashSet<>(); keys.add(key); } catch (Exception ex) { final Throwable root = ExceptionUtils.getRootCause(ex); final String exMsg = null == root ? """" : root.getMessage(); if (exMsg.equals(""Could not find side-effects for "" + serverSideEffect + ""."")) sideEffects.put(key, null); else throw new RuntimeException(""Could not get keys"", root); } } else { sideEffects.put(key, null); } } return (V) sideEffects.get(key); }"
106,"public Iec61850MockServerMarkerWadden(final String serverName, final String icdFilename, final int port) { <START> super(); <END> this.serverName = serverName; this.icdFilename = icdFilename; this.port = port; }",Is this super call needed here,"public Iec61850MockServerMarkerWadden(final String serverName, final String icdFilename, final int port) { this.serverName = serverName; this.icdFilename = icdFilename; this.port = port; }"
107,"public String edit() { try { savedId.clear(); ResourceInterface resource = this.loadResource(this.getResourceId()); this.setResourceTypeCode(resource.getType()); List fileDescr = new ArrayList<String>(); fileDescr.add(resource.getDescription()); setFileDescriptions(fileDescr); List<Category> resCategories = resource.getCategories(); <START> for (int i = 0; i < resCategories.size(); i++) { <END> Category resCat = resCategories.get(i); this.getCategoryCodes().add(resCat.getCode()); } this.setMainGroup(resource.getMainGroup()); this.setStrutsAction(ApsAdminSystemConstants.EDIT); } catch (Throwable t) { logger.error(""error in edit"", t); return FAILURE; } return SUCCESS; }",new loop strucutre: for(Category cat: resCategories) {..,"public String edit() { try { savedId.clear(); ResourceInterface resource = this.loadResource(this.getResourceId()); this.setResourceTypeCode(resource.getType()); List fileDescr = new ArrayList<String>(); fileDescr.add(resource.getDescription()); setFileDescriptions(fileDescr); List<Category> resCategories = resource.getCategories(); for (Category cat : resCategories) { this.getCategoryCodes().add(cat.getCode()); } this.setMainGroup(resource.getMainGroup()); this.setStrutsAction(ApsAdminSystemConstants.EDIT); } catch (Throwable t) { logger.error(""error in edit"", t); return FAILURE; } return SUCCESS; }"
108,"private CompletableFuture<Void> handleBatchRequest(TransferBatchRequest request, CompletableFuture<Void> allFutures, Semaphore semaphore) throws InterruptedException { if (request.getBatchType() == SEGMENT_INIT) { int numPermits = request.getDestinationNodes() .map(AbstractCollection::size).orElse(1) * NUM_REQUESTS_PER_NODE; if (numPermits == 0) { throw new IllegalStateException(""Number of permits should be equal to"" + "" at least one.""); } log.trace(""Starting a new segment transfer. Parallelism level: {}"", numPermits); semaphore.drainPermits(); semaphore.release(numPermits); } else if (request.getBatchType() == DATA) { semaphore.acquire(); CompletableFuture<Void> batchTransferResult = stateTransferBatchProcessor .transfer(request) .thenApply(response -> { semaphore.release(); if (response.getStatus() == SUCCEEDED) { return null; } else if (response.getStatus() == FAILED && response.getCauseOfFailure().isPresent()) { throw response.getCauseOfFailure().get(); } else { throw new StateTransferBatchProcessorException(); } }); <START> allFutures = CFUtils.allOfOrTerminateExceptionally(allFutures, batchTransferResult); <END> } else { throw new IllegalStateException(""Unrecognized batch type: "" + request.getBatchType()); } return allFutures; }","I this solve problem have. is impl of CFUtils.allOfOrTerminateExceptionally: java CompletableFuture<Void> result = CompletableFuture.allOf(futures); for (CompletableFuture<?> future : futures) { future.handle((res, ex) -> ex == null || result.completeExceptionally(ex)); } suppose this is current allFutures structure: a3<a2<a1<f0, f1>, f2>, f3> a_i means allFuture, f_i means individual transfer future. If f1 fails this moment, cancel a1, f2 f3 finished yet, a1 is exceptionally completedly, curerrnt allFuture, i.e. a3 waits f2 f3 finishes. if more futures, able jump out of loop, right","private CompletableFuture<Void> handleBatchRequest(TransferBatchRequest request, CompletableFuture<Void> allFutures, Semaphore semaphore) throws InterruptedException { semaphore.acquire(); CompletableFuture<Void> batchTransferResult = stateTransferBatchProcessor .transfer(request) .thenApply(response -> { semaphore.release(); if (response.getStatus() == SUCCEEDED) { return null; } else if (response.getStatus() == FAILED && response.getCauseOfFailure().isPresent()) { throw response.getCauseOfFailure().get(); } else { throw new StateTransferBatchProcessorException(); } }); allFutures = CFUtils.allOfOrTerminateExceptionally(allFutures, batchTransferResult); return allFutures; }"
109,"public RsWithoutHeader(final Response res, final CharSequence name) { super( <START> new RsOf( <END> () -> { final String prefix = String.format( ""%s:"", new EnglishLowerCase(name.toString()).string() ); return new Filtered<>( header -> { return !new EnglishLowerCase(header).string() .startsWith(prefix); }, res.head() ); }, res::body ) ); }",@fanifieiev above,"public RsWithoutHeader(final Response res, final CharSequence name) { super( new ResponseOf( () -> { final String prefix = String.format( ""%s:"", new EnglishLowerCase(name.toString()).string() ); return new Filtered<>( header -> { return !new EnglishLowerCase(header).string() .startsWith(prefix); }, res.head() ); }, res::body ) ); }"
110,"public void init(final ProcessorContext context) { internalProcessorContext = (InternalProcessorContext) context; <START> final String threadId = Thread.currentThread().getName(); <END> suppressionEmitSensor = ProcessorNodeMetrics.suppressionEmitSensor( threadId, context.taskId().toString(), internalProcessorContext.currentNode().name(), internalProcessorContext.metrics() ); buffer = requireNonNull((TimeOrderedKeyValueBuffer<K, V>) context.getStateStore(storeName)); buffer.setSerdesIfNull((Serde<K>) context.keySerde(), (Serde<V>) context.valueSerde()); }",nit: inline threadId in suppressionEmitSensor call,"public void init(final ProcessorContext context) { internalProcessorContext = (InternalProcessorContext) context; suppressionEmitSensor = ProcessorNodeMetrics.suppressionEmitSensor( Thread.currentThread().getName(), context.taskId().toString(), internalProcessorContext.currentNode().name(), internalProcessorContext.metrics() ); buffer = requireNonNull((TimeOrderedKeyValueBuffer<K, V>) context.getStateStore(storeName)); buffer.setSerdesIfNull((Serde<K>) context.keySerde(), (Serde<V>) context.valueSerde()); }"
111,"public URL addParameters(Map<String, String> parameters) { if (CollectionUtils.isEmptyMap(parameters)) { return this; } boolean hasAndEqual = true; for (Map.Entry<String, String> entry : parameters.entrySet()) { String value = getParameters().get(entry.getKey()); if (value == null) { if (entry.getValue() != null) { hasAndEqual = false; break; } } else { if (!value.equals(entry.getValue())) { hasAndEqual = false; break; } } } if (hasAndEqual) { return this; } if (frozen) { Map<String, String> map = new HashMap<>(getParameters()); <START> map.putAll(parameters); <END> return new URL(protocol, username, password, host, port, path, map); } else { getParameters().putAll(parameters); resetMethodParameters(); return this; } }","Create map expect size reduce memory, this: Map<String, String> srcParams = getParameters(); Map<String, String> newMap = new HashMap<>((int)((srcParams.size() + parameters.size) / 0.75 + 1)); newMap.putAll(srcParams); newMap.putAll(parameters);","public URL addParameters(Map<String, String> parameters) { if (CollectionUtils.isEmptyMap(parameters)) { return this; } boolean hasAndEqual = true; for (Map.Entry<String, String> entry : parameters.entrySet()) { String value = getParameters().get(entry.getKey()); if (value == null) { if (entry.getValue() != null) { hasAndEqual = false; break; } } else { if (!value.equals(entry.getValue())) { hasAndEqual = false; break; } } } if (hasAndEqual) { return this; } Map<String, String> srcParams = getParameters(); Map<String, String> newMap = new HashMap<>((int) ((srcParams.size() + parameters.size()) / 0.75 + 1)); newMap.putAll(srcParams); newMap.putAll(parameters); return new URL(protocol, username, password, host, port, path, newMap); }"
112,"public <START> static void <END> setReactorsMap(String vmId, ReactorClient client){ reactorsMap.put(vmId, client); }",Map static. single instance of JsonRpcServer pass call instance methods,"public void setReactorsMap(String vmId, ReactorClient client){ reactorsMap.put(vmId, client); }"
113,"private void removeDetachedServers(List<VDS> existingServers, List<GlusterServerInfo> fetchedServers) { for (final VDS server : existingServers) { if (isRemovableStatus(server.getStatus()) && serverDetached(server, fetchedServers)) { log.debugFormat(""Server {0} has been removed directly using the gluster CLI. Removing it from engine as well."", server.getName()); logUtil.logServerMessage(server, AuditLogType.GLUSTER_SERVER_REMOVED_FROM_CLI); <START> logUtil.logAuditMessage(server.getVdsGroupId(), null, server, <END> AuditLogType.GLUSTER_SERVER_REMOVED_FROM_CLI, new HashMap<String, String>() { { put(GlusterConstants.VDS_GROUP_NAME, server.getVdsGroupName()); } }); try { removeServerFromDb(server); runVdsCommand(VDSCommandType.RemoveVds, new RemoveVdsVDSCommandParameters(server.getId())); } catch (Exception e) { log.errorFormat(""Error while removing server {0} from database!"", server.getName(), e); } } } }","logServerMessage internally calls logAuditMessage. in effect, calling this twice. I fix in GlusterAuditLogUtil - in logAuditMessage, if server is passed, server.getVdsGroupId setVdsGroupId in AuditLogableBase","private void removeDetachedServers(List<VDS> existingServers, List<GlusterServerInfo> fetchedServers) { for (final VDS server : existingServers) { if (isRemovableStatus(server.getStatus()) && serverDetached(server, fetchedServers)) { log.debugFormat(""Server {0} has been removed directly using the gluster CLI. Removing it from engine as well."", server.getName()); logUtil.logServerMessage(server, AuditLogType.GLUSTER_SERVER_REMOVED_FROM_CLI); try { removeServerFromDb(server); runVdsCommand(VDSCommandType.RemoveVds, new RemoveVdsVDSCommandParameters(server.getId())); } catch (Exception e) { log.errorFormat(""Error while removing server {0} from database!"", server.getName(), e); } } } }"
114,"public static void main(String[] args) { final String key = ""your key""; final String secret = ""your secret""; Token token = new Token("""", """"); <START> OAuthService service = new ServiceBuilder().apiKey(key).apiSecret(secret).provider(ECHOApi.class).build(); <END> System.out.println(""Now we're going to access a protected resource...""); OAuthRequest request = new OAuthRequest(Verb.POST, PROTECTED_RESOURCE_URL); request.addBodyParameter(""content"", ""your valid activity streams xml""); service.signRequest(token, request); Response response = request.send(); System.out.println(); System.out.println(response.getCode()); System.out.println(response.getBody()); System.out.println(); System.out.println(""Thats it man! Go and build something awesome with Scribe! :)""); }",class is named EchoApi ECHOApi. This code compile,"public static void main(String[] args) { final String key = ""your key""; final String secret = ""your secret""; Token token = new Token("""", """"); OAuthService service = new ServiceBuilder().apiKey(key).apiSecret(secret).provider(EchoApi.class).build(); System.out.println(""Now we're going to access a protected resource...""); OAuthRequest request = new OAuthRequest(Verb.POST, PROTECTED_RESOURCE_URL); request.addBodyParameter(""content"", ""your valid activity streams xml""); service.signRequest(token, request); Response response = request.send(); System.out.println(); System.out.println(response.getCode()); System.out.println(response.getBody()); System.out.println(); System.out.println(""Thats it man! Go and build something awesome with Scribe! :)""); }"
115,"public void prepareTestProject() throws Exception { projectServiceClient.importProject( ws.getId(), Paths.get( getClass() .getResource(""/projects/plugins/JavaTestRunnerPlugin/"" + JUNIT4_PROJECT) .toURI()), JUNIT4_PROJECT, ProjectTemplates.CONSOLE_JAVA_SIMPLE); ide.open(ws); ide.waitOpenedWorkspaceIsReadyToUse(); projectExplorer.waitItem(JUNIT4_PROJECT); consoles.waitJDTLSProjectResolveFinishedMessage(JUNIT4_PROJECT); notifications.waitProgressPopupPanelClose(); projectExplorer.quickExpandWithJavaScript(); <START> runCompileCommand(); <END> }","you, please, explain, verification command palette removed","public void prepareTestProject() throws Exception { CompileCommand compileCommand = new CompileCommand(); testCommandServiceClient.createCommand(DtoConverter.asDto(compileCommand), ws.getId()); projectServiceClient.importProject( ws.getId(), Paths.get( getClass() .getResource(""/projects/plugins/JavaTestRunnerPlugin/"" + JUNIT4_PROJECT) .toURI()), JUNIT4_PROJECT, ProjectTemplates.CONSOLE_JAVA_SIMPLE); ide.open(ws); ide.waitOpenedWorkspaceIsReadyToUse(); projectExplorer.waitItem(JUNIT4_PROJECT); consoles.waitJDTLSProjectResolveFinishedMessage(JUNIT4_PROJECT); notifications.waitProgressPopupPanelClose(); projectExplorer.quickExpandWithJavaScript(); try { runCompileCommandByPallete(compileCommand); } catch (TimeoutException ex) { fail(""Known random failure <LINK_0>""); } }"
116,"<START> public Response handle(Request request) { <END> final CountDeviceTypeRequest req = (CountDeviceTypeRequest) request.getBody(); final long count = deviceTypeDao.count(req.getName(), req.getNamePattern(), req.getPrincipal()); final EntityCountResponse entityCountResponse = new EntityCountResponse(count); return Response.newBuilder() .withBody(new CountDeviceTypeResponse(entityCountResponse)) .buildSuccess(); }",Add empty new line (make consistent other count handlers),"public Response handle(Request request) { final CountDeviceTypeRequest req = (CountDeviceTypeRequest) request.getBody(); final long count = deviceTypeDao.count(req.getName(), req.getNamePattern(), req.getPrincipal()); final CountResponse countResponse = new CountResponse(count); return Response.newBuilder() .withBody(countResponse) .buildSuccess(); }"
117,"<START> public @ResponseBody List<Member> getPlayersForTeam( <END> HttpSession session, @PathVariable int id) { if (session.getAttribute(""member"") == null) { return null; } TeamDao teamDao = new TeamDao(); Team team = teamDao.getTeamById(id, false, true, false); return (List<Member>) team.getPlayers(); }",this return type changed avoid list cast,"public @ResponseBody Set<Member> getPlayersForTeam( HttpSession session, @PathVariable int id) { if (session.getAttribute(""member"") == null) { return null; } TeamDao teamDao = new TeamDao(); Team team = teamDao.getTeamById(id, false, true, false); return team.getPlayers(); }"
118,"protected String getBackupUrl() { String backupUrl = HttpSolrClientFactory.getDefaultHttpsAddress(); if (configurationAdmin != null) { try { Configuration solrConfig = configurationAdmin.getConfiguration( ""(service.pid=ddf.catalog.solr.external.SolrHttpCatalogProvider)""); <START> if (solrConfig != null) { <END> if (solrConfig.getProperties() != null && solrConfig.getProperties().get(""url"") != null) { LOGGER.debug(""Found url property in config, setting backup url""); backupUrl = (String) solrConfig.getProperties().get(""url""); } else { LOGGER.debug(""No Solr config found, checking System settings""); if (System.getProperty(""hostContext"") != null) { backupUrl = SystemBaseUrl.INTERNAL.constructUrl( SystemBaseUrl.INTERNAL.getProtocol(), System.getProperty(""hostContext"")); LOGGER.debug(""Trying system configured URL instead: {}"", backupUrl); } else { LOGGER.info( ""No Solr url configured, defaulting to: {}"", HttpSolrClientFactory.getDefaultHttpsAddress()); } } } } catch (IOException e) { LOGGER.debug(""Unable to get Solr url from bundle config, will check system properties.""); } } return backupUrl; }",pull this string a constant,protected String getBackupUrl() { return AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty(SOLR_URL_PROP)); }
119,"public void run() { for (BlobStore store : stores) { if (store.isStarted()) { try { store.maybeResumeCompaction(); } catch (Exception e) { <START> logger.error(""Compaction of store {} failed on resume. Continuing with the next store"", store, e); <END> storesToSkip.add(store); } } } while (enabled.get()) { try { long startTimeMs = time.milliseconds(); for (BlobStore store : stores) { try { if (!enabled.get()) { break; } if (store.isStarted() && !storesToSkip.contains(store)) { CompactionDetails details = getCompactionDetails(store); if (details != null) { store.compact(details); } } } catch (Exception e) { logger.error(""Compaction of store {} failed. Continuing with the next store"", store, e); storesToSkip.add(store); } } long timeElapsed = time.milliseconds() - startTimeMs; lock.lock(); try { time.await(waitCondition, waitTimeMs - timeElapsed); } finally { lock.unlock(); } } catch (Exception e) { logger.error(""Compaction execution encountered an error either during wait. Continuing"", e); } } }",Is this unstable state calls for manual investigation,"public void run() { for (BlobStore store : stores) { if (store.isStarted()) { try { store.maybeResumeCompaction(); } catch (Exception e) { logger.error(""Compaction of store {} failed on resume. Continuing with the next store"", store, e); storesToSkip.add(store); } } } while (enabled) { try { long startTimeMs = time.milliseconds(); for (BlobStore store : stores) { try { if (!enabled) { break; } if (store.isStarted() && !storesToSkip.contains(store)) { CompactionDetails details = getCompactionDetails(store); if (details != null) { store.compact(details); } } } catch (Exception e) { logger.error(""Compaction of store {} failed. Continuing with the next store"", store, e); storesToSkip.add(store); } } lock.lock(); try { if (enabled) { long timeElapsed = time.milliseconds() - startTimeMs; time.await(waitCondition, waitTimeMs - timeElapsed); } } finally { lock.unlock(); } } catch (Exception e) { logger.error(""Compaction execution encountered an error either during wait. Continuing"", e); } } }"
120,public static org.kie.dmn.model.api.InputClause dmnFromWB(final InputClause wb) { org.kie.dmn.model.api.InputClause result = new org.kie.dmn.model.v1_2.TInputClause(); result.setId(wb.getId().getValue()); result.setDescription(DescriptionPropertyConverter.dmnFromWB(wb.getDescription())); org.kie.dmn.model.api.LiteralExpression expression = LiteralExpressionPropertyConverter.dmnFromWB(wb.getInputExpression()); UnaryTests inputValues = UnaryTestsPropertyConverter.dmnFromWB(wb.getInputValues()); if (expression != null) { expression.setParent(result); } result.setInputExpression(expression); <START> if (inputValues != null && !inputValues.getText().isEmpty()) { <END> inputValues.setParent(result); result.setInputValues(inputValues); } return result; },org.kie.workbench.common.stunner.core.util.StringUtils.nonEmpty(..) (but know!?!),public static org.kie.dmn.model.api.InputClause dmnFromWB(final InputClause wb) { org.kie.dmn.model.api.InputClause result = new org.kie.dmn.model.v1_2.TInputClause(); result.setId(wb.getId().getValue()); result.setDescription(DescriptionPropertyConverter.dmnFromWB(wb.getDescription())); org.kie.dmn.model.api.LiteralExpression expression = LiteralExpressionPropertyConverter.dmnFromWB(wb.getInputExpression()); UnaryTests inputValues = UnaryTestsPropertyConverter.dmnFromWB(wb.getInputValues()); if (expression != null) { expression.setParent(result); } result.setInputExpression(expression); if (inputValues != null && StringUtils.nonEmpty(inputValues.getText())) { inputValues.setParent(result); result.setInputValues(inputValues); } return result; }
121,"public static long arrayPosition( @TypeParameter(""T"") Type type, @OperatorDependency(operator = EQUAL, argumentTypes = {""T"", ""T""}) MethodHandle equalMethodHandle, @SqlType(""array(T)"") Block array, @SqlType(""T"") Slice element) { int size = array.getPositionCount(); for (int i = 0; i < size; i++) { if (!array.isNull(i)) { Slice arrayValue = type.getSlice(array, i); try { Boolean result = (Boolean) equalMethodHandle.invokeExact(arrayValue, element); <START> checkArgument(result != null, ""Array element should not be nulll""); <END> if (result) { return i + 1; } } catch (Throwable t) { throw internalError(t); } } } return 0; }","nit: This check assertion. matter arguments passed this function equals function return null, null case is explicitly checked before. For assertions verify is preferred. (same for others)","public static long arrayPosition( @TypeParameter(""T"") Type type, @OperatorDependency(operator = EQUAL, argumentTypes = {""T"", ""T""}) MethodHandle equalMethodHandle, @SqlType(""array(T)"") Block array, @SqlType(""T"") Slice element) { int size = array.getPositionCount(); for (int i = 0; i < size; i++) { if (!array.isNull(i)) { Slice arrayValue = type.getSlice(array, i); try { Boolean result = (Boolean) equalMethodHandle.invokeExact(arrayValue, element); verify(result != null, ""Array element should not be nul""); if (result) { return i + 1; } } catch (Throwable t) { throw internalError(t); } } } return 0; }"
122,public void calculateDerivedFields() { OBSERVED_UNIQUE_UMIS = observedUmis.size(); INFERRED_UNIQUE_UMIS = inferredUmis.size(); PCT_UMI_WITH_N = (double) observedUmiWithN/ ((double) observedUmiWithN + (double) totalObservedUmis); OBSERVED_UMI_ENTROPY = effectiveNumberOfBases(observedUmis); INFERRED_UMI_ENTROPY = effectiveNumberOfBases(inferredUmis); UMI_BASE_QUALITIES = QualityUtil.getPhredScoreFromErrorProbability((double) OBSERVED_BASE_ERRORS / (double) observedUmiBases); <START> <END> },remove whitespace,public void calculateDerivedFields() { OBSERVED_UNIQUE_UMIS = observedUmis.size(); INFERRED_UNIQUE_UMIS = inferredUmis.size(); PCT_UMI_WITH_N = (double) observedUmiWithNs/ ((double) observedUmiWithNs + (double) totalObservedUmisWithoutNs); OBSERVED_UMI_ENTROPY = effectiveNumberOfBases(observedUmis); INFERRED_UMI_ENTROPY = effectiveNumberOfBases(inferredUmis); UMI_BASE_QUALITIES = QualityUtil.getPhredScoreFromErrorProbability((double) OBSERVED_BASE_ERRORS / (double) observedUmiBases); }
123,"public OkPacket(Buffer buffer, long clientCapabilities) { <START> buffer.skipByte(); END> affectedRows = buffer.getLengthEncodedNumeric(); insertId = buffer.getLengthEncodedNumeric(); if ((clientCapabilities & MariaDbServerCapabilities.CLIENT_PROTOCOL_41) !=0) { statusFlags = buffer.readShort(); warnings = buffer.readShort(); } else if ((clientCapabilities & MariaDbServerCapabilities.TRANSACTIONS) !=0) { statusFlags = buffer.readShort(); warnings = 0; } else { statusFlags = 0; warnings = 0; } String message = """"; String sessionStateMessage = """"; if (buffer.remaining() > 0) { if ((clientCapabilities & MariaDbServerCapabilities.CLIENT_SESSION_TRACK) !=0) { message = buffer.readStringLengthEncoded(StandardCharsets.UTF_8); if ((statusFlags & MariaDbServerCapabilities.SERVER_SESSION_STATE_CHANGED) !=0) { sessionStateMessage = buffer.readStringLengthEncoded(StandardCharsets.UTF_8); } } else { message = buffer.readStringNullEnd(StandardCharsets.UTF_8); } } info = message; sessionStateInfo = sessionStateMessage; }",suggestion buffer.skipByte(); // OkPacket Header this need checked ensure 0x00 (or 0xFE for EOF payload functioning OK payload?) assume correct,"public OkPacket(Buffer buffer, long clientCapabilities) { buffer.skipByte(); affectedRows = buffer.getLengthEncodedNumeric(); insertId = buffer.getLengthEncodedNumeric(); statusFlags = buffer.readShort(); warnings = buffer.readShort(); String message = """"; String sessionStateMessage = """"; if (buffer.remaining() > 0) { if ((clientCapabilities & MariaDbServerCapabilities.CLIENT_SESSION_TRACK) !=0) { message = buffer.readStringLengthEncoded(StandardCharsets.UTF_8); if ((statusFlags & ServerStatus.SERVER_SESSION_STATE_CHANGED) !=0 && buffer.remaining() > 0) { sessionStateMessage = buffer.readStringLengthEncoded(StandardCharsets.UTF_8); } } else { message = buffer.readStringNullEnd(StandardCharsets.UTF_8); } } info = message; sessionStateInfo = sessionStateMessage; }"
124,"public Response start(Action action) { return doAction(VdcActionType.StartGlusterVolume, new GlusterVolumeActionParameters(guid, <START> action.isForce() == null ? false : action.isForce()), action); <END> }",isSetX() jaxb generated properties (which is equal action.isForce() != null ),"public Response start(Action action) { return doAction(VdcActionType.StartGlusterVolume, new GlusterVolumeActionParameters(guid, action.isSetForce() ? action.isForce() : false), action); }"
125,"private String getDefaultOrigins() { List<VDS> allVds = vdsDao.getAll(getUserID(), <START> getParameters().isFiltered()); <END> StringBuilder sb = new StringBuilder(); for (VDS vds : allVds) { if (sb.length() > 0) { sb.append(','); } sb.append(HTTPS); sb.append(vds.getHostName()); } String result = sb.toString(); log.debug(""Default list of origins refreshed to: {}"" , result); return result; }","This filtered, in theory list of allowed origins depend permissions of user. I VdsDao.getAll(), parameters. suggest add a new method, a new stored procedure, get host names, attributes of host, is a waste of resources (joins, etc)","private Set<String> getDefaultOrigins() { log.debug(""getDefaultOrigins() called""); List<VDS> allVds = vdsDao.getAll(getUserID(), getParameters().isFiltered()); Set<String> result = new HashSet<>(); for (VDS vds : allVds) { if (getParameters().getSuffixes().size() > 0) { for (String suffix : getParameters().getSuffixes()) { result.add(HTTPS + vds.getHostName() + suffix); } } else { result.add(HTTPS + vds.getHostName()); } } log.debug(""Default list of origins refreshed to: {}"" , StringUtils.join(result, ',')); return result; }"
126,"public SerializedPage serialize(Page page) { SliceOutput serializationBuffer = new DynamicSliceOutput(toIntExact(page.getSizeInBytes() + Integer.BYTES)); writeRawPage(page, serializationBuffer, blockEncodingSerde); Slice slice = serializationBuffer.slice(); <START> return serialize(slice, page.getPositionCount()); <END> }","inline slice variable: return serialize(serializationBuffer.slice(), page.getPositionCount());","public SerializedPage serialize(Page page) { SliceOutput serializationBuffer = new DynamicSliceOutput(toIntExact(page.getSizeInBytes() + Integer.BYTES)); writeRawPage(page, serializationBuffer, blockEncodingSerde); Slice slice = serializationBuffer.slice(); int uncompressedSize = serializationBuffer.size(); byte markers = PageCodecMarker.none(); if (compressor.isPresent()) { ByteBuffer compressionBuffer = ByteBuffer.allocate(compressor.get().maxCompressedLength(uncompressedSize)); compressor.get().compress(slice.toByteBuffer(), compressionBuffer); compressionBuffer.flip(); if ((((double) compressionBuffer.remaining()) / uncompressedSize) <= MINIMUM_COMPRESSION_RATIO) { slice = Slices.wrappedBuffer(compressionBuffer); markers = COMPRESSED.set(markers); } } if (spillCipher.isPresent()) { slice = Slices.wrappedBuffer(spillCipher.get().encrypt(slice.toByteBuffer())); markers = ENCRYPTED.set(markers); } else { slice = Slices.copyOf(slice); } return new SerializedPage(slice, markers, page.getPositionCount(), uncompressedSize); }"
127,"public ListTabbedPage(WebDriver driver) { <START> super(driver); <END> PageFactory.initElements(driver, this); waitWithTimeout().until(ExpectedConditions.visibilityOf(selectedTab)); tablesElements.forEach(table -> { tables.add(new DataTable(table, table.getAttribute(""id""))); }); setSelectedTable(); }",static Strings enum for list targets helpful,"public ListTabbedPage(WebDriver driver) { super(driver); PageFactory.initElements(driver, this); tabs = driver.findElements(By.xpath("" waitWithTimeout().until(ExpectedConditions.visibilityOf(selectedTab)); tablesElements.forEach(table -> { tables.add(new DataTable(table)); }); setSelectedTable(getTabNumber()); }"
128,"public String getColumnText(Object element, int columnIndex) { switch (columnIndex) { case 0: return getText(element); case 1: try { if (element instanceof StagingFolderEntry) { return null; } StagingEntry stagingEntry = (StagingEntry) element; Date modified; if (isStaged) { IFileRevision fileRevision = GitFileRevision.inIndex( stagingEntry.getRepository(), stagingEntry.getPath()); modified = new Date(fileRevision.getTimestamp()); } else { File file = new File(stagingEntry.getRepository() .getWorkTree(), stagingEntry.getPath()); modified = new Date(file.lastModified()); } <START> if (showRelativeDate) <END> return RelativeDateFormatter.format(modified); else return absoluteFormatter.format(modified); } catch (Exception e) { Activator.handleError(e.getCause().getMessage(), e.getCause(), false); return null; } default: return null; } }",please {} brackets single line if/else too,"public String getColumnText(Object element, int columnIndex) { switch (columnIndex) { case 0: return getText(element); case 1: try { if (element instanceof StagingFolderEntry) { return null; } StagingEntry stagingEntry = (StagingEntry) element; Date modified; if (isStaged) { IFileRevision fileRevision = GitFileRevision.inIndex( stagingEntry.getRepository(), stagingEntry.getPath()); modified = new Date(fileRevision.getTimestamp()); } else { File file = new File(stagingEntry.getRepository() .getWorkTree(), stagingEntry.getPath()); modified = new Date(file.lastModified()); } if (showRelativeDate) { return RelativeDateFormatter.format(modified); } else { return absoluteFormatter.format(modified); } } catch (Exception e) { Activator.handleError(e.getCause().getMessage(), e.getCause(), false); return null; } default: return null; } }"
129,public synchronized int getType (Class<? extends AbstractRecord> c) { for (int i = 0; i < _map.size(); i++) { <START> RecordTypeMap typeMap = _map.get(i); <END> if (typeMap.getRecordClass() != null && typeMap.getRecordClass().equals(c)) return _map.get(i).getType(); } return RecordType.UNTYPED; },avoid call getRecordClass AbstractRecord rec = _map.get(i).getRecordClass() _map.get(i) return null in case need checking for too,public synchronized int getType (Class<? extends AbstractRecord> c) { for (int i = 0; i < _map.size(); i++) { Class<? extends AbstractRecord> recordClass = _map.get(i).getRecordClass(); if (recordClass != null && recordClass.equals(c)) return _map.get(i).getType(); } return RecordType.UNTYPED; }
130,"protected TmfXmlStateValue(ITmfXmlModelFactory modelFactory, Element node, IXmlStateSystemContainer container, List<ITmfXmlStateAttribute> attributes, @Nullable String eventField) { fPath = attributes; fContainer = container; fEventField = eventField; if (!node.getNodeName().equals(TmfXmlStrings.STATE_VALUE)) { throw new IllegalArgumentException(""TmfXmlStateValue constructor: Element is not a stateValue""); } String id = node.getAttribute(TmfXmlStrings.ID); <START> fID = id.isEmpty() ? null : id; <END> fIncrement = Boolean.parseBoolean(node.getAttribute(TmfXmlStrings.INCREMENT)); fUpdate = Boolean.parseBoolean(node.getAttribute(TmfXmlStrings.UPDATE)); fStateValue = initializeStateValue(modelFactory, node); String forcedTypeName = node.getAttribute(TmfXmlStrings.FORCED_TYPE); fForcedType = !forcedTypeName.isEmpty() ? TmfXmlUtils.getTmfStateValueByName(forcedTypeName): ITmfStateValue.Type.NULL; String stack = node.getAttribute(TmfXmlStrings.ATTRIBUTE_STACK); fStackType = ValueTypeStack.getTypeFromString(stack); fMappingGroup = node.getAttribute(TmfXmlStrings.MAPPING_GROUP); }",a positive test,"protected TmfXmlStateValue(ITmfXmlModelFactory modelFactory, Element node, IXmlStateSystemContainer container, List<ITmfXmlStateAttribute> attributes, @Nullable String eventField) { fPath = attributes; fContainer = container; fEventField = eventField; if (!node.getNodeName().equals(TmfXmlStrings.STATE_VALUE)) { throw new IllegalArgumentException(""TmfXmlStateValue constructor: Element is not a stateValue""); } String id = node.getAttribute(TmfXmlStrings.ID); fID = id.isEmpty() ? null : id; fIncrement = Boolean.parseBoolean(node.getAttribute(TmfXmlStrings.INCREMENT)); fUpdate = Boolean.parseBoolean(node.getAttribute(TmfXmlStrings.UPDATE)); fStateValue = initializeStateValue(modelFactory, node); String forcedTypeName = node.getAttribute(TmfXmlStrings.FORCED_TYPE); fForcedType = forcedTypeName.isEmpty() ? ITmfStateValue.Type.NULL : TmfXmlUtils.getTmfStateValueByName(forcedTypeName); String stack = node.getAttribute(TmfXmlStrings.ATTRIBUTE_STACK); fStackType = ValueTypeStack.getTypeFromString(stack); fMappingGroup = node.getAttribute(TmfXmlStrings.MAPPING_GROUP); }"
131,public int hashCode() { int result = _networkDomainName != null ? _networkDomainName.hashCode() : 0; result = 31 * result + (_networkDomainPath != null ? _networkDomainPath.hashCode() : 0); result = 31 * result + (_networkDomainUuid != null ? _networkDomainUuid.hashCode() : 0); result = 31 * result + (_networkAccountName != null ? _networkAccountName.hashCode() : 0); result = 31 * result + (_networkAccountUuid != null ? _networkAccountUuid.hashCode() : 0); result = 31 * result + (_networkName != null ? _networkName.hashCode() : 0); result = 31 * result + (_networkCidr != null ? _networkCidr.hashCode() : 0); result = 31 * result + (_networkGateway != null ? _networkGateway.hashCode() : 0); result = 31 * result + (_networkAclId != null ? _networkAclId.hashCode() : 0); result = 31 * result + (_dnsServers != null ? _dnsServers.hashCode() : 0); result = 31 * result + (_gatewaySystemIds != null ? _gatewaySystemIds.hashCode() : 0); result = 31 * result + (_networkUuid != null ? _networkUuid.hashCode() : 0); result = 31 * result + (_isL3Network ? 1 : 0); result = 31 * result + (_isVpc ? 1 : 0); result = 31 * result + (_isSharedNetwork ? 1 : 0); result = 31 * result + (_vpcName != null ? _vpcName.hashCode() : 0); result = 31 * result + (_vpcUuid != null ? _vpcUuid.hashCode() : 0); result = 31 * result + (_defaultEgressPolicy ? 1 : 0); result = 31 * result + (_ipAddressRange != null ? _ipAddressRange.hashCode() : 0); result = 31 * result + (_domainTemplateName != null ? _domainTemplateName.hashCode() : 0); return result; <START> } <END>,Please implement toString() provide debugging state information for debugging purposes,public int hashCode() { int result = super.hashCode(); result = 31 * result + (_networkDomainName != null ? _networkDomainName.hashCode() : 0); result = 31 * result + (_networkDomainPath != null ? _networkDomainPath.hashCode() : 0); result = 31 * result + (_networkDomainUuid != null ? _networkDomainUuid.hashCode() : 0); result = 31 * result + (_networkAccountName != null ? _networkAccountName.hashCode() : 0); result = 31 * result + (_networkAccountUuid != null ? _networkAccountUuid.hashCode() : 0); result = 31 * result + (_networkName != null ? _networkName.hashCode() : 0); result = 31 * result + (_networkCidr != null ? _networkCidr.hashCode() : 0); result = 31 * result + (_networkGateway != null ? _networkGateway.hashCode() : 0); result = 31 * result + (_networkAclId != null ? _networkAclId.hashCode() : 0); result = 31 * result + (_dnsServers != null ? _dnsServers.hashCode() : 0); result = 31 * result + (_gatewaySystemIds != null ? _gatewaySystemIds.hashCode() : 0); result = 31 * result + (_networkUuid != null ? _networkUuid.hashCode() : 0); result = 31 * result + (_isL3Network ? 1 : 0); result = 31 * result + (_isVpc ? 1 : 0); result = 31 * result + (_isSharedNetwork ? 1 : 0); result = 31 * result + (_vpcName != null ? _vpcName.hashCode() : 0); result = 31 * result + (_vpcUuid != null ? _vpcUuid.hashCode() : 0); result = 31 * result + (_defaultEgressPolicy ? 1 : 0); result = 31 * result + (_ipAddressRange != null ? _ipAddressRange.hashCode() : 0); result = 31 * result + (_domainTemplateName != null ? _domainTemplateName.hashCode() : 0); return result; }
132,"public PluginLoader(SitePaths sitePaths, PluginGuiceEnvironment pe, ServerInformationImpl sii, PluginUser.Factory puf, Provider<PluginCleanerTask> pct, @GerritServerConfig Config cfg, @CanonicalWebUrl Provider<String> provider) { pluginsDir = sitePaths.plugins_dir; dataDir = sitePaths.data_dir; tmpDir = sitePaths.tmp_dir; env = pe; srvInfoImpl = sii; pluginUserFactory = puf; running = Maps.newConcurrentMap(); disabled = Maps.newConcurrentMap(); broken = Maps.newHashMap(); toCleanup = Queues.newArrayDeque(); cleanupHandles = Maps.newConcurrentMap(); cleaner = pct; urlProvider = provider; <START> remoteInstall = <END> cfg.getBoolean(""plugins"", null, ""allowRemoteAdmin"", false); long checkFrequency = ConfigUtil.getTimeUnit(cfg, ""plugins"", null, ""checkFrequency"", TimeUnit.MINUTES.toMillis(1), TimeUnit.MILLISECONDS); if (checkFrequency > 0) { scanner = new PluginScannerThread(this, checkFrequency); } else { scanner = null; } }","Nit: name of variable longer matches name of config parameter, I this is a blocker","public PluginLoader(SitePaths sitePaths, PluginGuiceEnvironment pe, ServerInformationImpl sii, PluginUser.Factory puf, Provider<PluginCleanerTask> pct, @GerritServerConfig Config cfg, @CanonicalWebUrl Provider<String> provider) { pluginsDir = sitePaths.plugins_dir; dataDir = sitePaths.data_dir; tmpDir = sitePaths.tmp_dir; env = pe; srvInfoImpl = sii; pluginUserFactory = puf; running = Maps.newConcurrentMap(); disabled = Maps.newConcurrentMap(); broken = Maps.newHashMap(); toCleanup = Queues.newArrayDeque(); cleanupHandles = Maps.newConcurrentMap(); cleaner = pct; urlProvider = provider; remoteAdmin = cfg.getBoolean(""plugins"", null, ""allowRemoteAdmin"", false); long checkFrequency = ConfigUtil.getTimeUnit(cfg, ""plugins"", null, ""checkFrequency"", TimeUnit.MINUTES.toMillis(1), TimeUnit.MILLISECONDS); if (checkFrequency > 0) { scanner = new PluginScannerThread(this, checkFrequency); } else { scanner = null; } }"
133,"public void hasNoActiveMemberships_shouldReturnTrueIfNoneExists() throws Exception{ SimpleDateFormat dateFormat = new SimpleDateFormat(""yyyy-MM-dd HH:mm:ss""); Date endDateEarlier = dateFormat.parse(""2007-02-01 00:00:00""); Date endDateLater = dateFormat.parse(""2100-02-01 00:00:00""); <START> <END> Cohort cohort = new Cohort(3); CohortMembership temp = new CohortMembership(7); temp.setVoided(true); temp.setEndDate(endDateLater); cohort.addMembership(temp); temp = new CohortMembership(8); temp.setVoided(true); cohort.addMembership(temp); temp = new CohortMembership(9); temp.setEndDate(endDateEarlier); cohort.addMembership(temp); temp = new CohortMembership(10); temp.setVoided(true); cohort.addMembership(temp); assertTrue(cohort.hasNoActiveMemberships()); }",this test pass year 2100,"public void hasNoActiveMemberships_shouldReturnTrueIfNoneExists() throws Exception{ Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, 1); Date endDateLater = calendar.getTime(); calendar.add(Calendar.DAY_OF_YEAR, -2); Date endDateEarlier = calendar.getTime(); Cohort cohort = new Cohort(3); CohortMembership temp = new CohortMembership(7); temp.setVoided(true); temp.setEndDate(endDateLater); cohort.addMembership(temp); temp = new CohortMembership(8); temp.setVoided(true); cohort.addMembership(temp); temp = new CohortMembership(9); temp.setEndDate(endDateEarlier); cohort.addMembership(temp); temp = new CohortMembership(10); temp.setVoided(true); cohort.addMembership(temp); assertTrue(cohort.hasNoActiveMemberships()); }"
134,"private void initArticleHeaderView() { pageHeaderView.addOnLayoutChangeListener((View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) -> setWebViewPaddingTop()); pageHeaderView.setCallback(new PageHeaderView.Callback() { @Override public void onImageClicked() { if (getPage() != null && isLeadImageEnabled()) { String imageName = getPage().getPageProperties().getLeadImageName(); String imageUrl = getPage().getPageProperties().getLeadImageUrl(); if (imageName != null && imageUrl != null) { String filename = ""File:"" + imageName; WikiSite wiki = getTitle().getWikiSite(); getActivity().startActivityForResult(GalleryActivity.newIntent(getActivity(), parentFragment.getTitleOriginal(), filename, UriUtil.resolveProtocolRelativeUrl(imageUrl), wiki, GalleryFunnel.SOURCE_LEAD_IMAGE), Constants.ACTIVITY_REQUEST_GALLERY); } } } @Override public void onArticleCTAClicked() { <START> getActivity().startActivityForResult(DescriptionEditActivity.newIntent(getActivity(), isTranslation ? captionTargetPageTitle : captionSourcePageTitle, null, sourceSummary, targetSummary, isTranslation ? SUGGESTED_EDITS_TRANSLATE_CAPTION : SUGGESTED_EDITS_ADD_CAPTION), <END> ACTIVITY_REQUEST_IMAGE_CAPTION_EDIT); } }); }",sourceSummary.getPageTitle() targetSummary.getPageTitle() for PageTitle,"private void initArticleHeaderView() { pageHeaderView.addOnLayoutChangeListener((View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) -> setWebViewPaddingTop()); pageHeaderView.setCallback(new PageHeaderView.Callback() { @Override public void onImageClicked() { if (getPage() != null && isLeadImageEnabled()) { String imageName = getPage().getPageProperties().getLeadImageName(); String imageUrl = getPage().getPageProperties().getLeadImageUrl(); if (imageName != null && imageUrl != null) { String filename = ""File:"" + imageName; WikiSite wiki = getTitle().getWikiSite(); getActivity().startActivityForResult(GalleryActivity.newIntent(getActivity(), parentFragment.getTitleOriginal(), filename, UriUtil.resolveProtocolRelativeUrl(imageUrl), wiki, GalleryFunnel.SOURCE_LEAD_IMAGE), Constants.ACTIVITY_REQUEST_GALLERY); } } } @Override public void onCallToActionClicked() { if (isTranslation ? (targetSummary != null && sourceSummary != null) : sourceSummary != null) { getActivity().startActivityForResult(DescriptionEditActivity.newIntent(getActivity(), isTranslation ? targetSummary.getPageTitle() : sourceSummary.getPageTitle(), null, sourceSummary, targetSummary, isTranslation ? SUGGESTED_EDITS_TRANSLATE_CAPTION : SUGGESTED_EDITS_ADD_CAPTION), ACTIVITY_REQUEST_IMAGE_CAPTION_EDIT); } } }); }"
135,"private void writeProjectFile(File intoDir, String projectName, String sourcePath, String fileName) throws IOException { InputStream sourceInputStream = InitCommand.class.getClassLoader().getResourceAsStream(sourcePath); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(sourceInputStream, StandardCharsets.UTF_8)); File projectFile = new File(intoDir, fileName); PrintWriter writer = new PrintWriter(projectFile, ""UTF-8""); String line; try { while ((line = bufferedReader.readLine()) != null) { writer.println(line.replace(""{{projectName}}"", projectName)); } <START> } finally { <END> writer.close(); bufferedReader.close(); } }","sure, a ""try resources"" here","private void writeProjectFile(File intoDir, String projectName, String sourcePath, String fileName) throws IOException { InputStream sourceInputStream = InitCommand.class.getClassLoader().getResourceAsStream(sourcePath); File projectFile = new File(intoDir, fileName); String line; try ( BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(sourceInputStream, StandardCharsets.UTF_8)); PrintWriter writer = new PrintWriter(projectFile, ""UTF-8"")) { while ((line = bufferedReader.readLine()) != null) { writer.println(line.replace(""{{projectName}}"", projectName)); } } }"
136,"protected Object getInstanceToRun(Map paramsMap) { String instanceName = (String) paramsMap.get(SchedulerUtilQuartzImpl.RUNNABLE_INSTANCE); try { <START> Class<?> clazz = Class.forName(instanceName); <END> Constructor<?> constructor = clazz.getConstructor(); Object instance = constructor.newInstance(); return instance; } catch (ClassNotFoundException e) { log.error(""could not instantiate class '{}' due to error '{}'"", instanceName, e.getMessage()); log.debug(""Exception"", e); return null; } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { log.error(""could not instantiate class '{}' due to error '{}'"", instanceName, e.getMessage()); log.debug(""Exception"", e); return null; } }","for DB Scheduled scheduler existence of class examined ? able resolve correct class set map, this logic applied for simple scheduler for consistency","protected Object getInstanceToRun(Map paramsMap) { String instanceName = (String) paramsMap.get(SchedulerUtilBaseImpl.RUNNABLE_INSTANCE); try { Class<?> clazz = Class.forName(instanceName); Constructor<?> constructor = clazz.getConstructor(); Object instance = constructor.newInstance(); return instance; } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { log.error(""could not instantiate class '{}' due to error '{}'"", instanceName, e.getMessage()); log.debug(""Exception"", e); return null; } }"
137,"protected void exportAsContext() { if (EDatabaseConnTemplate.isSchemaNeeded(getConnection().getDatabaseType()) && schemaText != null <START> && StringUtils.isEmpty(schemaText.getText())) { <END> MessageDialog.openWarning(getShell(), Messages.getString(""AbstractForm.ExportAsContext""), Messages.getString(""DatabaseForm.checkSchema"")); } collectContextParams(); super.exportAsContext(); }",**isBlank**,"protected void exportAsContext() { if (EDatabaseConnTemplate.isSchemaNeeded(getConnection().getDatabaseType()) && schemaText != null && StringUtils.isBlank(schemaText.getText())) { boolean confirm = MessageDialog.openConfirm(getShell(), Messages.getString(""AbstractForm.ExportAsContext""), Messages.getString(""DatabaseForm.checkSchema"")); if(!confirm) { return; } } collectContextParams(); super.exportAsContext(); }"
138,public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { fieldName = getArguments().getString(NAME); listener.setActionBarTitle(fieldName); <START> sendCurrentDate(); <END> } },"a UI/UX consideration - worth noting today's date is highly user wants, stewardship events added carried out. I this initial thought ""If default accepting today's date, majority of users choose"". turns out ok",public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { fieldName = getArguments().getString(NAME); changeListener.setActionBarTitle(fieldName); sendCurrentDate(); } }
139,"public static void main(String[] args) { LOG.info(""Application started""); File configurationFile; if (args.length == 0) { configurationFile = new File(FileTailerMain.class.getClassLoader().getResource(""file-tailer.properties"").getPath()); } else if (args.length == 1) { configurationFile = new File(args[0]); } else { LOG.info(""Too many arguments: {}. Requirement: 0 or 1"", args.length); return; } PipeManager manager = new PipeManager(configurationFile); try { <START> manager.setupPipes(); <END> } catch (IOException e) { LOG.error(""Error during flows: {} setup"", e); return; } LOG.info(""Staring flows""); manager.startUp(); Runtime.getRuntime().addShutdownHook(new Thread(new PipeShutdownTask(manager))); }",need call setupPipes() explicitly. part of service start,"public static void main(String[] args) { LOG.info(""Application started""); File configurationFile; if (args.length == 0) { configurationFile = new File(FileTailerMain.class.getClassLoader().getResource(""file-tailer.properties"").getPath()); } else if (args.length == 1) { configurationFile = new File(args[0]); } else { LOG.info(""Too many arguments: {}. Requirement: 0 or 1"", args.length); return; } PipeManager manager = new PipeManager(configurationFile); LOG.info(""Staring pipes""); manager.startAsync(); Runtime.getRuntime().addShutdownHook(new Thread(new PipeShutdownTask(manager))); }"
140,"public void retrievesOrganizations() throws Exception { final Github github = new MkGithub(); final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_OK, Json.createArrayBuilder() .add(org(1, ""org1"")) .add(org(2, ""org2"")) .add(org(3, ""org3"")) .build().toString() ) ).start(); try { final Organizations orgs = new RtOrganizations( github, new ApacheRequest(container.home()) ); MatcherAssert.assertThat( orgs.iterate(), <START> Matchers.<Organization>iterableWithSize(3) <END> ); MatcherAssert.assertThat( container.take().uri().toString(), Matchers.endsWith(""/user/orgs"") ); } finally { container.stop(); } }",@cvrebert please leave Tv.THREE,"public void retrievesOrganizations() throws Exception { final Github github = new MkGithub(); final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_OK, Json.createArrayBuilder() .add(org(1, ""org1"")) .add(org(2, ""org2"")) .add(org(3, ""org3"")) .build().toString() ) ).start(); try { final Organizations orgs = new RtOrganizations( github, new ApacheRequest(container.home()) ); MatcherAssert.assertThat( orgs.iterate(), Matchers.<Organization>iterableWithSize(Tv.THREE) ); MatcherAssert.assertThat( container.take().uri().toString(), Matchers.endsWith(""/user/orgs"") ); } finally { container.stop(); } }"
141,"public void resolveArgumentSecurityContextErrorOnInvalidTypeTrue() throws Exception { String principal = ""invalid_type_true""; setAuthenticationPrincipal(principal); try { resolver.resolveArgument(showSecurityContextErrorOnInvalidTypeTrue(), null, null, null); fail(""should not reach here""); <START> } catch(ClassCastException ex) {} <END> }",AssertJ's assertThatCode instead of try-catch,"public void resolveArgumentSecurityContextErrorOnInvalidTypeTrue() throws Exception { String principal = ""invalid_type_true""; setAuthenticationPrincipal(principal); assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> resolver.resolveArgument(showSecurityContextErrorOnInvalidTypeTrue(), null, null, null)); }"
142,"public void printTime(String header, boolean fromStart) { long dur = logTime(fromStart); <START> System.out.println(String.format(""%s (%,6d sec; DB cache: %,6d; Docs: %,6d)"", header, dur / 1000, getCacheCounts(fromStart), docs.size())); <END> }",nice if log total elapsed time script started. easier estimate long conversion take,"public void printTime(String header, boolean fromStart) { long dur = logTime(fromStart); long totalDur = logTime(true); String stotalDur = duration(totalDur); System.out.println(String.format(""%s (%,6d sec; %s; DB cache: %,6d; Docs: %,6d)"", header, dur/1000, stotalDur, getCacheCounts(fromStart), docs.size())); }"
143,public void setup() { <START> provider = (ParanamerNameProvider) Factories.createParameterNameProvider(); <END> },casting,"public void setup() { CacheStore<AccessibleObject, Parameter[]> cache = new DefaultCacheStore<>(); provider = new ParanamerNameProvider(cache); }"
144,"public TransactionParser getParser(KXmlParser parser) { String namespace = parser.getNamespace(); String name = parser.getName(); TransactionParser superParser = super.getParser(parser); <START> if(superParser != null){ <END> return superParser; } if(""message"".equalsIgnoreCase(name)) { return new TransactionParser<String>(parser) { String nature = parser.getAttributeValue(null, ""nature""); public void commit(String parsed) throws IOException { } public String parse() throws InvalidStructureException,IOException, XmlPullParserException, UnfullfilledRequirementsException { message = parser.nextText(); if(nature != null) { if(message != null) { messages.put(nature, message); } } return message; } }; } return null; }",I if for future-proofing this check _after_ of internal ones? want default assumption override superclass's parsing behavior if supply parser for something,"public TransactionParser getParser(KXmlParser parser) { String namespace = parser.getNamespace(); String name = parser.getName(); if(""message"".equalsIgnoreCase(name)) { return new TransactionParser<String>(parser) { String nature = parser.getAttributeValue(null, ""nature""); public void commit(String parsed) throws IOException { } public String parse() throws InvalidStructureException,IOException, XmlPullParserException, UnfullfilledRequirementsException { message = parser.nextText(); if(nature != null) { if(message != null) { messages.put(nature, message); } } return message; } }; } TransactionParser superParser = super.getParser(parser); if(superParser != null){ return superParser; } return null; }"
145,"private boolean isWorkplaceJoined() { @SuppressWarnings(""unchecked"") Class<IDeviceCertificate> certClass = (Class<IDeviceCertificate>)AuthenticationSettings.INSTANCE.getDeviceCertificateProxy(); <START> return (certClass != null); <END> }",remove bracket,"private boolean isWorkplaceJoined() { @SuppressWarnings(""unchecked"") Class<IDeviceCertificate> certClass = (Class<IDeviceCertificate>)AuthenticationSettings.INSTANCE.getDeviceCertificateProxy(); return certClass != null; }"
146,"public Location resolveCurrentLocation() throws LocationDefinitionErrorException { int numberOfTries = 0; do { URL whatIsMyCity; try { whatIsMyCity = new URL(""<LINK_0>""); } catch (MalformedURLException e) { ++numberOfTries; continue; } try { <START> BufferedReader in = new BufferedReader(new InputStreamReader( <END> whatIsMyCity.openStream())); String currentInfo; StringBuilder responseStrBuilder = new StringBuilder(); while ((currentInfo = in.readLine()) != null) { responseStrBuilder.append(currentInfo); } JSONObject locationInfo = new JSONObject(responseStrBuilder.toString()); String[] coordinates = locationInfo .getString(""loc"").split("",""); Location result = new Location( Double.parseDouble(coordinates[0]), Double.parseDouble(coordinates[1])); result.setName(locationInfo.getString(""city"")); return result; } catch (IOException | JSONException e) { ++numberOfTries; } } while (numberOfTries < TwitterStream.MAX_NUMBER_OF_TRIES); throw new LocationDefinitionErrorException(LOCATION_DEFINITION_ERROR); }",try-with-resources,"public Location resolveCurrentLocation() throws LocationDefinitionErrorException, MalformedURLException { int numberOfTries = 0; do { URL whatIsMyCity; whatIsMyCity = new URL(""<LINK_0>""); try (BufferedReader in = new BufferedReader(new InputStreamReader( whatIsMyCity.openStream()))) { String currentInfo; StringBuilder responseStrBuilder = new StringBuilder(); while ((currentInfo = in.readLine()) != null) { responseStrBuilder.append(currentInfo); } JSONObject locationInfo = new JSONObject(responseStrBuilder.toString()); String[] coordinates = locationInfo .getString(""loc"").split("",""); Location result = new Location( Double.parseDouble(coordinates[0]), Double.parseDouble(coordinates[1]), locationInfo.getString(""city"")); return result; } catch (IOException | JSONException e) { ++numberOfTries; } } while (numberOfTries < TwitterStream.MAX_NUMBER_OF_TRIES); throw new LocationDefinitionErrorException(LOCATION_DEFINITION_ERROR); }"
147,"public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case Menu.FIRST: if (mLabel == mAddedLabel) { addIssue(); } else { editIssueLabel(); } break; case Menu.FIRST + 1: new AlertDialog.Builder(IssueLabelListActivity.this) .setMessage(getString(R.string.issue_dialog_delete_message, mLabel.getName())) .setPositiveButton(R.string.delete, (dialog, whichButton) -> { IssuesLabelService <START> .deleteIssueLabel(IssueLabelListActivity.this, getRootLayout(), mRepoOwner, mRepoName, mLabel.getName()) <END> .subscribe(result -> { forceLoaderReload(0); setResult(RESULT_OK); }, e -> {}); }) .setNegativeButton(R.string.cancel, null) .show(); break; default: break; } mode.finish(); return true; }",Code style: please line lengths <= 100 chars. Github's web UI show full text,"public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case Menu.FIRST: if (mLabel == mAddedLabel) { addIssue(); } else { editIssueLabel(); } break; case Menu.FIRST + 1: new AlertDialog.Builder(IssueLabelListActivity.this) .setMessage(getString(R.string.issue_dialog_delete_message, mLabel.getName())) .setPositiveButton(R.string.delete, (dialog, whichButton) -> { IssuesLabelService .deleteIssueLabel( IssueLabelListActivity.this, mRepoOwner, mRepoName, mLabel.getName() ).subscribe(result -> { forceLoaderReload(0); setResult(RESULT_OK); }, error -> {}); }) .setNegativeButton(R.string.cancel, null) .show(); break; default: break; } mode.finish(); return true; }"
148,"public void accept(ServiceLocator serviceLocator) { logger.info(""Loading topics metadata""); List<TopicName> topicsLeft = getTopics(); int initialTopicsCount = topicsLeft.size(); int retries = retryCount + 1; while (retries > 0) { retries--; <START> topicsLeft = topicsLeft.stream().filter(this::topicMetadataNotAvailable).collect(toList()); <END> if (!topicsLeft.isEmpty() && retries > 0) { waitBeforeNextRetry(); } } logResultInfo(topicsLeft, initialTopicsCount); }",@dankraw I remember wondered concurrency of this task. Imo try parallel this stream 500 topics metadata download takes 100ms (max is 500ms) wait 50 seconds is short amount of time in startup phase,"public void accept(ServiceLocator serviceLocator) { long start = System.currentTimeMillis(); logger.info(""Loading topics metadata""); List<CachedTopic> topics = topicsCache.getTopics(); List<MetadataLoadingResult> allResults = loadMetadataForTopics(topics); logResultInfo(allResults, System.currentTimeMillis() - start); }"
149,"static WeekActivityDTO createInstance(WeekActivity weekActivity, LevelOfDetail levelOfDetail) { boolean includeDetail = levelOfDetail == LevelOfDetail.WeekDetail; return new WeekActivityDTO(weekActivity.getGoal().getID(), weekActivity.getStartTime(), includeIf(() -> weekActivity.getSpread(), includeDetail), <START> includeIf(() -> weekActivity.getTotalActivityDurationMinutes(), includeDetail), <END> weekActivity.getDayActivities().stream() .map(dayActivity -> DayActivityDTO.createInstance(dayActivity, levelOfDetail)) .collect(Collectors.toList())); }",here: includeDetail ? weekActivity.getTotalActivitDurationMinutes() : Optional.empty(),"static WeekActivityDTO createInstance(WeekActivity weekActivity, LevelOfDetail levelOfDetail) { boolean includeDetail = levelOfDetail == LevelOfDetail.WeekDetail; return new WeekActivityDTO(weekActivity.getGoal().getID(), weekActivity.getStartTime(), includeDetail ? weekActivity.getSpread() : Collections.emptyList(), includeDetail ? Optional.of(weekActivity.getTotalActivityDurationMinutes()) : Optional.empty(), weekActivity.getDayActivities().stream() .map(dayActivity -> DayActivityDTO.createInstance(dayActivity, levelOfDetail)) .collect(Collectors.toList())); }"
150,"public CallbackResult<Collection<ValueType>> call() { final long start = System.currentTimeMillis(); if(!cache.acquireLock()) { log.debug(""{}: Unable to acquire refresh lock for"", cache.getCacheName()); cache.markLoadException(System.currentTimeMillis() - start); return new CallbackResult<>(new LockUnavailableException()); } <START> log.debug(""{}: Attempting to refresh data for"", cache.getCacheName()); <END> try { final Collection<ValueType> values = cache.loadAll(); if (values == null) { cache.markLoadException(System.currentTimeMillis() - start); return new CallbackResult<>(); } log.info(""{}: Async refresh for {}"", cache.getCacheName()); Map<KeyType, ValueType> valuesMap = new HashMap<>(); for (ValueType value : values) { valuesMap.put(cache.keyFromValue(value), value); } cache.putAll(valuesMap); cache.markLoadSuccess(System.currentTimeMillis() - start); cache.loadAllComplete(); return new CallbackResult<>(values); } catch (Exception ex) { cache.markLoadException(System.currentTimeMillis() - start); return new CallbackResult<>(ex); } finally { cache.releaseLock(); } }","small - drop "" for""","public CallbackResult<Collection<ValueType>> call() { final long start = System.currentTimeMillis(); if(!cache.acquireLock()) { log.debug(""{}: Unable to acquire refresh lock"", cache.getCacheName()); cache.markLoadException(System.currentTimeMillis() - start); return new CallbackResult<>(new LockUnavailableException()); } log.debug(""{}: Attempting to refresh data"", cache.getCacheName()); try { final Collection<ValueType> values = cache.loadAll(); if (values == null) { cache.markLoadException(System.currentTimeMillis() - start); return new CallbackResult<>(); } log.info(""{}: Async refresh"", cache.getCacheName()); Map<KeyType, ValueType> valuesMap = new HashMap<>(); for (ValueType value : values) { valuesMap.put(cache.keyFromValue(value), value); } cache.putAll(valuesMap); cache.markLoadSuccess(System.currentTimeMillis() - start); cache.loadAllComplete(); return new CallbackResult<>(values); } catch (Exception ex) { cache.markLoadException(System.currentTimeMillis() - start); return new CallbackResult<>(ex); } finally { cache.releaseLock(); } }"
151,"public String getExecutable(final Launcher launcher) throws IOException, InterruptedException { final File exe = launcher.getChannel().call(new MasterToSlaveCallable<File, IOException>() { <START> private static final long serialVersionUID = 5572701806697595613L; <END> @Override public File call() throws IOException { return getExeFile(); } }); final boolean existis = launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() { private static final long serialVersionUID = 5572701806697595613L; @Override public Boolean call() throws IOException { return exe.exists(); } }); if (!existis) { launcher.getListener().error(""Gradle executable does not exist: "" + exe.getPath()); return null; } else { return exe.getPath(); } }","is serialVersionUID for? IIUC, Jenkins XStream serialize/deserialize data, Java serialization. is this required","public String getExecutable(final Launcher launcher) throws IOException, InterruptedException { final File exe = launcher.getChannel().call(new MasterToSlaveCallable<File, IOException>() { @Override public File call() throws IOException { return getExeFile(); } }); final boolean existis = launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() { @Override public Boolean call() throws IOException { return exe.exists(); } }); if (!existis) { launcher.getListener().error(""Gradle executable does not exist: "" + exe.getPath()); return null; } else { return exe.getPath(); } }"
152,"private String transformToPluralForm(String singular) { StringBuilder plural = new StringBuilder(); plural.append(singular); if (singular.endsWith(LAST_CHAR_Y)) { int length = plural.length(); plural.replace(length - 1, length, PLURAL_SUFFIX_IES); } else if (singular.endsWith(LAST_CHAR_S) || singular.endsWith(LAST_CHAR_X) || singular.endsWith(LAST_CHAR_Z) || singular.endsWith(LAST_CHARS_CH) || singular.endsWith(LAST_CHARS_SH)) { <START> <END> plural.append(PLURAL_SUFFIX_ES); } else { plural.append(PLURAL_SUFFIX_S); } return plural.toString(); }",This benefit inilne examples (takle values tests),"private String transformToPluralForm(String singular) { StringBuilder plural = new StringBuilder(); plural.append(singular); if (singular.endsWith(String.valueOf(LAST_CHAR_Y))) { int length = plural.length(); plural.replace(length - 1, length, PLURAL_SUFFIX_IES); } else if (singular.endsWith(String.valueOf(LAST_CHAR_S)) || singular.endsWith(String.valueOf(LAST_CHAR_X)) || singular.endsWith(String.valueOf(LAST_CHAR_Z)) || singular.endsWith(LAST_CHARS_CH) || singular.endsWith(LAST_CHARS_SH)) { plural.append(PLURAL_SUFFIX_ES); } else { plural.append(PLURAL_SUFFIX_S); } return plural.toString(); }"
153,"public static void main(String[] args) throws Exception { MainDc mainInstance = new MainDc(); Properties nuroDCProp = new Properties(); mainInstance.loadDefaultValues(); mainInstance.loadFromEnrivonmentVariables(); try { <START> nuroDCProp.load(new FileInputStream(mainInstance.configFilePath)); <END> } catch (FileNotFoundException ex) { logger.error(""Properties file not found""); throw new RuntimeException(""Properties file not found""); } catch (IOException ex) { logger.error(""Error while parsing properties file""); throw new RuntimeException(""Error while parsing properties file""); } int port; try { port = Integer.parseInt(mainInstance.managerPort); } catch (NumberFormatException ex) { logger.error(""Error while converting manager port - must be an integer""); throw new RuntimeException(""Error while parsing properties file""); } Registry.initialize(mainInstance.managerIp, port, nuroDCProp); Registry.startMonitoring(); }",is semantic of config strategies? environment variables a config file. mechanism? I this simplify bootstrap of DC runtime management. Wdyt,"public static void main(String[] args) throws Exception { MainDc mainInstance = new MainDc(); if (args.length > 0) { mainInstance.configFilePath = args[0]; } else { mainInstance.configFilePath = CONFIG_FILE_PATH; } Properties nuroDCProp = new Properties(); try { nuroDCProp.load(new FileInputStream(mainInstance.configFilePath)); } catch (FileNotFoundException ex) { logger.error(""Properties file not found""); throw new RuntimeException(""Properties file not found""); } catch (IOException ex) { logger.error(""Error while parsing properties file""); throw new RuntimeException(""Error while parsing properties file""); } Registry.initialize(nuroDCProp); Registry.startMonitoring(); }"
154,"public void testUpdate() throws Exception { server.enqueue(jsonResponse(""/storageaccountupdate.json"")); final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup); StorageServiceUpdateParams.StorageServiceUpdateProperties props = StorageServiceUpdateParams.StorageServiceUpdateProperties.create(null, null, null, null, null, null, null, null, null); final StorageServiceUpdateParams params = storageAPI.update(""TESTSTORAGE"", props, ImmutableMap.of(""another_property_name"", ""another_property_value"")); assertTrue(params.tags().containsKey(""another_property_name"")); assertSent(server, ""PATCH"", ""/subscriptions/"" + subsriptionId + ""/resourcegroups/"" + resourceGroup + <START> ""/providers/Microsoft.Storage/storageAccounts/TESTSTORAGE?api-version=2015-06-15""); <END> }",Add body check,"public void testUpdate() throws Exception { server.enqueue(jsonResponse(""/storageaccountupdate.json"")); final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup); StorageServiceUpdateParams.StorageServiceUpdateProperties props = StorageServiceUpdateParams.StorageServiceUpdateProperties.create(StorageService.AccountType.Standard_LRS); final StorageServiceUpdateParams params = storageAPI.update(""TESTSTORAGE"", ImmutableMap.of(""another_property_name"", ""another_property_value""), props); assertTrue(params.tags().containsKey(""another_property_name"")); assertSent(server, ""PATCH"", ""/subscriptions/"" + subsriptionId + ""/resourcegroups/"" + resourceGroup + ""/providers/Microsoft.Storage/storageAccounts/TESTSTORAGE?api-version=2015-06-15"", String.format(""{\""properties\"":{ \""accountType\"": \""Standard_LRS\"" },\""tags\"":{\""another_property_name\"":\""another_property_value\""}}"")); }"
155,"public String getAlign() { <START> if (mAlign.startsWith(ATTR_ALIGN)) { <END> return mAlign.substring(ATTR_ALIGN.length(), mAlign.length()); } return mAlign; }",Do need null check mAlign here,"public String getAlign() { if (!TextUtils.isEmpty(mAlign) && mAlign.startsWith(ATTR_ALIGN)) { return mAlign.substring(ATTR_ALIGN.length(), mAlign.length()); } return mAlign; }"
156,"public synchronized List<List<Object>> addOrUpdate(DBObject object, DBObject oldObject) { if (oldObject != null) { this.remove(oldObject); } DBObject key = getKeyFor(object); if (unique) { if (mapValues.containsKey(key)) { <START> return extractFields(object, key.toMap().keySet()); <END> } mapValues.put(key, Collections.singletonList(object)); } else { List<DBObject> values = mapValues.get(key); if (values == null) { values = new ArrayList<DBObject>(); mapValues.put(key, values); } values.add(object); } return Collections.emptyList(); }",need .toMap() here. keySet() is a method DBObject,"public synchronized List<List<Object>> addOrUpdate(DBObject object, DBObject oldObject) { if (oldObject != null) { this.remove(oldObject); } DBObject key = getKeyFor(object); if (unique) { if (mapValues.containsKey(key)) { return extractFields(object, key.keySet()); } mapValues.put(key, Collections.singletonList(object)); } else { List<DBObject> values = mapValues.get(key); if (values == null) { values = new ArrayList<DBObject>(); mapValues.put(key, values); } values.add(object); } return Collections.emptyList(); }"
157,"public Market(String name) { <START> this.marketName = name; <END> stockList = new HashMap<String, Stock>(); marketHistory = new MarketHistory(this); orderBook = new OrderBook(this); }","Redundant variable name - ""name""","public Market(String name) { this.name = name; stockList = new HashMap<String, Stock>(); marketHistory = new MarketHistory(this); orderBook = new OrderBook(this); }"
158,"private List<DiscoverySelector> getSelectorsFromTestCasesHeader(BundleDescriptor bd) { Bundle bundle = bd.getBundle(); Bundle host = BundleUtils.getHost(bundle) .get(); return BundleUtils.testCases(bundle) .map(testcase -> { int index = testcase.indexOf('#'); String className = (index < 0) ? testcase : testcase.substring(0, index); try { Class<?> testClass = host.loadClass(className); testClass.getDeclaredMethods(); testClass.getDeclaredFields(); if (!resolvedClasses.contains(testClass)) { checkForMixedJUnit34(bd, testClass); if (index < 0) { resolvedClasses.add(testClass); return selectClass(testClass); } return selectMethod(testClass, DiscoverySelectors.selectMethod(testcase)); } <START> } catch (ClassNotFoundException | NoClassDefFoundError cnfe) { <END> info(() -> ""error: "" + cnfe); StaticFailureDescriptor unresolvedClassDescriptor = new StaticFailureDescriptor(bd.getUniqueId() .append(""test"", testcase), testcase, cnfe); bd.addChild(unresolvedClassDescriptor); } return null; }) .filter(Objects::nonNull) .collect(toList()); }",Putting NoClassDefFoundError hide stupidity in other parts of this code :-( narrow window for catching NoClassDefFoundError calls testClass.getDeclaredMethods() testClass.getDeclaredFields() I is source for need worry it,"private List<DiscoverySelector> getSelectorsFromTestCasesHeader(BundleDescriptor bd) { Bundle bundle = bd.getBundle(); Bundle host = BundleUtils.getHost(bundle) .get(); return BundleUtils.testCases(bundle) .map(testcase -> { int index = testcase.indexOf('#'); String className = (index < 0) ? testcase : testcase.substring(0, index); Class<?> testClass = tryToResolveTestClass(host, className, bd); if (testClass != null && !resolvedClasses.contains(testClass)) { checkForMixedJUnit34(bd, testClass); if (index < 0) { resolvedClasses.add(testClass); return selectClass(testClass); } return selectMethod(testClass, DiscoverySelectors.selectMethod(testcase)); } return null; }) .filter(Objects::nonNull) .collect(toList()); }"
159,"public void onFinish(SpanWrapper span, String operationName, long durationNanos) { final SpanContextInformation contextInfo = SpanContextInformation.forSpan(span); final MonitoredHttpRequest monitoredHttpRequest = contextInfo .getRequestAttribute(MONITORED_HTTP_REQUEST_ATTRIBUTE); if (monitoredHttpRequest == null) { return; } trackServletExceptions(span, monitoredHttpRequest.httpServletRequest); setParams(span, monitoredHttpRequest.httpServletRequest); setTrackingInformation(span, monitoredHttpRequest.httpServletRequest, monitoredHttpRequest.clientIp, monitoredHttpRequest.userAgentHeader); setStatus(span, monitoredHttpRequest.responseWrapper.getStatus()); span.setTag(""bytes_written"", monitoredHttpRequest.responseWrapper.getContentLength()); final Future<Void> userAgentParsedFuture = contextInfo.getRequestAttribute(USER_AGENT_PARSED_FUTURE_ATTRIBUTE); if (userAgentParsedFuture != null) { try { userAgentParsedFuture.get(); } catch (Exception e) { logger.warn(""Suppressed exception"", e); } } <START> final Long gcTime = contextInfo.getRequestAttribute(GC_TIME_ATTRIBUTE); <END> if (gcTime != null) { span.setTag(""gc_time_ms"", collectGcTimeMs() - gcTime); } }",Move this a SpanEventListener. works for other request types well,"public void onFinish(SpanWrapper span, String operationName, long durationNanos) { final SpanContextInformation contextInfo = SpanContextInformation.forSpan(span); final MonitoredHttpRequest monitoredHttpRequest = contextInfo .getRequestAttribute(MONITORED_HTTP_REQUEST_ATTRIBUTE); if (monitoredHttpRequest == null) { return; } trackServletExceptions(span, monitoredHttpRequest.httpServletRequest); setParams(span, monitoredHttpRequest.httpServletRequest); setTrackingInformation(span, monitoredHttpRequest.httpServletRequest, monitoredHttpRequest.clientIp, monitoredHttpRequest.userAgentHeader); setStatus(span, monitoredHttpRequest.responseWrapper.getStatus()); span.setTag(""bytes_written"", monitoredHttpRequest.responseWrapper.getContentLength()); final Future<Void> userAgentParsedFuture = contextInfo.getRequestAttribute(USER_AGENT_PARSED_FUTURE_ATTRIBUTE); if (userAgentParsedFuture != null) { try { userAgentParsedFuture.get(); } catch (Exception e) { logger.warn(""Suppressed exception"", e); } } }"
160,"private String createTopic(Datastream datastream) throws TransportException { Properties datastreamProperties = new Properties(); if (datastream.hasMetadata()) { datastreamProperties.putAll(datastream.getMetadata()); } Properties topicProperties = new VerifiableProperties(datastreamProperties).getDomainProperties(""topic""); int numberOfPartitions = DEFAULT_NUMBER_PARTITIONS; if (datastream.hasDestination() && datastream.getDestination().hasPartitions()) { numberOfPartitions = datastream.getDestination().getPartitions(); } else if (datastream.hasSource() && datastream.getSource().hasPartitions()) { numberOfPartitions = datastream.getSource().getPartitions(); } String connectionString = _transportProvider.createTopic(getTopicName(datastream), numberOfPartitions, topicProperties); DatastreamDestination destination = new DatastreamDestination(); destination.setConnectionString(connectionString); destination.setPartitions(numberOfPartitions); datastream.setDestination(destination); datastream.getMetadata().put(DatastreamMetadataConstants.DESTINATION_CREATION_MS, <START> String.valueOf(Instant.now().toEpochMilli())); <END> Duration retention = _transportProvider.getRetention(connectionString); if (retention != null) { datastream.getMetadata().put(DatastreamMetadataConstants.DESTINATION_RETENION_MS, String.valueOf(retention.toMillis())); } return connectionString; }",Is this System.currentTime in milliseconds,"private String createTopic(Datastream datastream) throws TransportException { Properties datastreamProperties = new Properties(); if (datastream.hasMetadata()) { datastreamProperties.putAll(datastream.getMetadata()); } Properties topicProperties = new VerifiableProperties(datastreamProperties).getDomainProperties(DESTINATION_DOMAIN); int numberOfPartitions = DEFAULT_NUMBER_PARTITIONS; if (datastream.hasDestination() && datastream.getDestination().hasPartitions()) { numberOfPartitions = datastream.getDestination().getPartitions(); } else if (datastream.hasSource() && datastream.getSource().hasPartitions()) { numberOfPartitions = datastream.getSource().getPartitions(); } String connectionString = _transportProvider.createTopic(getTopicName(datastream), numberOfPartitions, topicProperties); DatastreamDestination destination = new DatastreamDestination(); destination.setConnectionString(connectionString); destination.setPartitions(numberOfPartitions); datastream.setDestination(destination); datastream.getMetadata().put(DatastreamMetadataConstants.DESTINATION_CREATION_MS, String.valueOf(Instant.now().toEpochMilli())); Duration retention = _transportProvider.getRetention(connectionString); if (retention != null) { datastream.getMetadata().put(DatastreamMetadataConstants.DESTINATION_RETENION_MS, String.valueOf(retention.toMillis())); } return connectionString; }"
161,<START> public AtomicInteger getNumberOfConnections() { <END> return this.numberOfConnections; },return AtomicInteger,public int getNumberOfConnections() { return this.numberOfConnections.intValue(); }
162,"private Tags(Map<String, String> tags, boolean isObject) throws IllegalArgumentException { <START> if (tags == null) { return; } <END> if (isObject) { if (tags.size() > MAX_OBJECT_TAG_COUNT) { throw new IllegalArgumentException( ""too many object tags; allowed = "" + MAX_OBJECT_TAG_COUNT + "", found = "" + tags.size()); } } else if (tags.size() > MAX_TAG_COUNT) { throw new IllegalArgumentException( ""too many bucket tags; allowed = "" + MAX_TAG_COUNT + "", found = "" + tags.size()); } for (Map.Entry<String, String> entry : tags.entrySet()) { String key = entry.getKey(); if (key.length() == 0 || key.length() > MAX_KEY_LENGTH || key.contains(""&"")) { throw new IllegalArgumentException(""invalid tag key '"" + key + ""'""); } String value = entry.getValue(); if (value.length() > MAX_VALUE_LENGTH || value.contains(""&"")) { throw new IllegalArgumentException(""invalid tag value '"" + value + ""'""); } } this.tags = Collections.unmodifiableMap(tags); }",this condition throw exception,"private Tags(Map<String, String> tags, boolean isObject) throws IllegalArgumentException { if (tags == null) { return; } int limit = isObject ? MAX_OBJECT_TAG_COUNT : MAX_TAG_COUNT; if (tags.size() > limit) { throw new IllegalArgumentException( ""too many "" + (isObject ? ""object"" : ""bucket"") + "" tags; allowed = "" + limit + "", found = "" + tags.size()); } for (Map.Entry<String, String> entry : tags.entrySet()) { String key = entry.getKey(); if (key.length() == 0 || key.length() > MAX_KEY_LENGTH || key.contains(""&"")) { throw new IllegalArgumentException(""invalid tag key '"" + key + ""'""); } String value = entry.getValue(); if (value.length() > MAX_VALUE_LENGTH || value.contains(""&"")) { throw new IllegalArgumentException(""invalid tag value '"" + value + ""'""); } } this.tags = Collections.unmodifiableMap(tags); }"
163,"ImmutableMultimap<TypeName, TypeName> build() { for (Properties properties : propertiesSet) { put(properties); } <START> final ImmutableMultimap<TypeName, TypeName> result = builder.build(); <END> return result; }",return builder.build(). opportunity debug/inspect already,"ImmutableMultimap<TypeName, TypeName> build() { for (Properties props : this.properties) { put(props); } return builder.build(); }"
164,"private void assertValid(float num) { <START> if(num == Float.NaN) { <END> throw new RuntimeException(""Direction can not take a NaN float as an argument""); } else if (num == Float.NEGATIVE_INFINITY || num == Float.POSITIVE_INFINITY) { throw new RuntimeException(""Direction can not take +/- infinity as an argument""); } }","comparisons involving NaN (except !=) return false, Float.NaN == Float.NaN returns false. This Float.isNaN(num) instead. a Float.isInfinite(num) method for next check","private void assertValid(float num) { if(Float.isNaN(num)) { throw new RuntimeException(""Direction can not take a NaN float as an argument""); } else if (Float.isInfinite(num)) { throw new RuntimeException(""Direction can not take +/- infinity as an argument""); } }"
165,"public void buildAndDeployTest() { <START> ClassLoader currentCL = Thread.currentThread().getContextClassLoader(); <END> Thread.currentThread().setContextClassLoader(classLoader); PMMLRequestData request = new PMMLRequestData(""123"", ""SimpleScorecard""); request.addRequestParam(""param1"", 10.0); request.addRequestParam(""param2"", 15.0); ApplyPmmlModelCommand command = (ApplyPmmlModelCommand) ((CommandFactoryServiceImpl) commandsFactory).newApplyPmmlModel(request); command.setPackageName(""org.kie.scorecard""); ServiceResponse<ExecutionResults> results = ruleClient.executeCommandsWithResults(CONTAINER_ID, command); assertNotNull(results); PMML4Result resultHolder = (PMML4Result) results.getResult().getValue(""results""); assertNotNull(resultHolder); assertEquals(""OK"", resultHolder.getResultCode()); System.out.println(resultHolder.toString()); logger.info(resultHolder.toString()); }",saving existing classLoader? I remove,"public void buildAndDeployTest() { Thread.currentThread().setContextClassLoader(classLoader); PMMLRequestData request = new PMMLRequestData(""123"", ""SimpleScorecard""); request.addRequestParam(""param1"", 10.0); request.addRequestParam(""param2"", 15.0); ApplyPmmlModelCommand command = (ApplyPmmlModelCommand) ((CommandFactoryServiceImpl) commandsFactory).newApplyPmmlModel(request); command.setPackageName(""org.kie.scorecard""); ServiceResponse<ExecutionResults> results = ruleClient.executeCommandsWithResults(CONTAINER_ID, command); assertNotNull(results); PMML4Result resultHolder = (PMML4Result) results.getResult().getValue(""results""); assertNotNull(resultHolder); assertEquals(""OK"", resultHolder.getResultCode()); System.out.println(resultHolder.toString()); logger.info(resultHolder.toString()); }"
166,"<START> public PluginUploadResponse addPlugin(File uploadedPlugin, String filename) { <END> if (!validateJar(filename)) { Map<Integer, String> errors = new HashMap<Integer, String>(); errors.put(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE, ""Please upload a jar.""); return PluginUploadResponse.create(false, null, errors); } return uploadPlugin(uploadedPlugin, filename); }","DefaultPluginManager a ""runtime view of/access plugins"". plugin locations filesystem, now. want that","public PluginUploadResponse addPlugin(File uploadedPlugin, String filename) { if (!pluginValidator.namecheckForJar(filename)) { Map<Integer, String> errors = new HashMap<Integer, String>(); errors.put(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE, ""Please upload a jar.""); return PluginUploadResponse.create(false, null, errors); } return pluginWriter.addPlugin(uploadedPlugin, filename); }"
167,public void onDestroy() { super.onDestroy(); if (activity.isFinishing() && player != null && player.videoPlayerSelected()) stopService(); else unbind(); PreferenceManager.getDefaultSharedPreferences(activity) .unregisterOnSharedPreferenceChangeListener(this); activity.unregisterReceiver(broadcastReceiver); <START> activity.getContentResolver().unregisterContentObserver(settingsContentObserver); <END> if (positionSubscriber != null) positionSubscriber.dispose(); if (currentWorker != null) currentWorker.dispose(); if (disposables != null) disposables.clear(); positionSubscriber = null; currentWorker = null; disposables = null; bottomSheetBehavior.setBottomSheetCallback(null); },"set broadcastReceiver settingsContentObserver null, prevent memory leaks",public void onDestroy() { super.onDestroy(); if (activity.isFinishing() && player != null && player.videoPlayerSelected()) { stopService(requireContext()); } else { unbind(requireContext()); } PreferenceManager.getDefaultSharedPreferences(activity) .unregisterOnSharedPreferenceChangeListener(this); activity.unregisterReceiver(broadcastReceiver); activity.getContentResolver().unregisterContentObserver(settingsContentObserver); if (positionSubscriber != null) { positionSubscriber.dispose(); } if (currentWorker != null) { currentWorker.dispose(); } disposables.clear(); positionSubscriber = null; currentWorker = null; bottomSheetBehavior.setBottomSheetCallback(null); }
168,"<START> public static ValidationResult setAndValidateCpuProfile(VmBase vmBase, Guid userId) { <END> if (vmBase.getCpuProfileId() == null) { return assignFirstCpuProfile(vmBase, userId); } CpuProfileValidator validator = new CpuProfileValidator(vmBase.getCpuProfileId()); ValidationResult result = validator.isParentEntityValid(vmBase.getClusterId()); if (!result.isValid()) { return result; } if (!checkPermissions(vmBase.getCpuProfileId(), userId)) { return new ValidationResult(EngineMessage.ACTION_TYPE_NO_PERMISSION_TO_ASSIGN_CPU_PROFILE, String.format(""$cpuProfileId %s"", vmBase.getCpuProfileId()), String.format(""$cpuProfileName %s"", validator.getProfile().getName())); } return ValidationResult.VALID; }","move method purpose? public methods first, helpers, private","public static ValidationResult setAndValidateCpuProfile(VmBase vmBase, Guid userId) { if (vmBase.getCpuProfileId() == null) { return assignFirstCpuProfile(vmBase, userId); } CpuProfileValidator validator = new CpuProfileValidator(vmBase.getCpuProfileId()); ValidationResult result = validator.isParentEntityValid(vmBase.getClusterId()); if (!result.isValid()) { return result; } if (!isProfilePermitted(vmBase.getCpuProfileId(), userId)) { return new ValidationResult(EngineMessage.ACTION_TYPE_NO_PERMISSION_TO_ASSIGN_CPU_PROFILE, String.format(""$cpuProfileId %s"", vmBase.getCpuProfileId()), String.format(""$cpuProfileName %s"", validator.getProfile().getName())); } return ValidationResult.VALID; }"
169,"<START> public static <T> T createModel(Class<T> model, List<OpenEngSBModelEntry> entries) { <END> checkIfClassIsModel(model); try { T instance = model.newInstance(); for (OpenEngSBModelEntry entry : entries) { try { String setterName = getSetterName(entry.getKey()); Method method = model.getMethod(setterName, entry.getType()); method.invoke(instance, entry.getValue()); } catch (NoSuchMethodException e) { ((OpenEngSBModel) instance).addOpenEngSBModelEntry(entry); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return instance; } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } return null; }",simply a model instead of checking for one,"public static <T> T createModel(Class<T> model, List<OpenEngSBModelEntry> entries) { checkIfClassIsModel(model); try { T instance = model.newInstance(); for (OpenEngSBModelEntry entry : entries) { try { String setterName = getSetterName(entry.getKey()); Method method = model.getMethod(setterName, entry.getType()); method.invoke(instance, entry.getValue()); } catch (NoSuchMethodException e) { ((OpenEngSBModel) instance).addOpenEngSBModelEntry(entry); } catch (IllegalArgumentException e) { LOGGER.error(""IllegalArgumentException while trying to set values for the new model."", e); } catch (InvocationTargetException e) { LOGGER.error(""InvocationTargetException while trying to set values for the new model."", e); } } return instance; } catch (InstantiationException e) { LOGGER.error(""InstantiationException while creating a new model instance."", e); } catch (IllegalAccessException e) { LOGGER.error(""IllegalAccessException while creating a new model instance."", e); } catch (SecurityException e) { LOGGER.error(""SecurityException while creating a new model instance."", e); } return null; }"
170,"public QueryResponse getChromosomes(@RequestParam(name = ""species"") String species, HttpServletResponse response) throws IllegalOpenCGACredentialsException, IOException { <START> if (species == null || species.isEmpty()) { <END> response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return setQueryResponse(""Please specify a species""); } MultiMongoDbFactory.setDatabaseNameForCurrentThread(DBAdaptorConnector.getDBName(species)); List<String> chromosomeList = variantEntityRepository.findDistinctChromosomes(); QueryResult<String> queryResult = Utils.buildQueryResult(chromosomeList); return setQueryResponse(queryResult); }",null check unnecessary,"public QueryResponse getChromosomes(@RequestParam(name = ""species"") String species, HttpServletResponse response) throws IllegalOpenCGACredentialsException, IOException { if (species.isEmpty()) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return setQueryResponse(""Please specify a species""); } MultiMongoDbFactory.setDatabaseNameForCurrentThread(DBAdaptorConnector.getDBName(species)); List<String> chromosomeList = variantEntityRepository.findDistinctChromosomes(); QueryResult<String> queryResult = Utils.buildQueryResult(chromosomeList); return setQueryResponse(queryResult); }"
171,"protected Object applyEntryValueToMap(Entry value, Map target) { Object k = value.getKey(); if (acceptsSubkeyStronglyTyped(k)) { } else if (k instanceof ConfigKey<?>) { k = subKey( ((ConfigKey<?>)k).getName() ); } else if (k instanceof String) { k = subKey((String)k); } else { if (k instanceof Supplier) { Object mapAtRoot = target.get(this); if (mapAtRoot==null) { mapAtRoot = new LinkedHashMap(); target.put(this, mapAtRoot); } if (mapAtRoot instanceof Map) { <START> synchronized (mapAtRoot) { <END> return ((Map)mapAtRoot).put(k, value.getValue()); } } } log.warn(""Unexpected subkey ""+k+"" being inserted into ""+this+""; ignoring""); k = null; } if (k!=null) return target.put(k, value.getValue()); else return null; }","convinced synchronize this map, knowing it. feels dangerous ad hoc. rely map's put method synchronized if map needs synchronized. do expect this map (returned target.get(this)) be","protected Object applyEntryValueToMap(Entry value, Map target) { Object k = value.getKey(); if (acceptsSubkeyStronglyTyped(k)) { } else if (k instanceof ConfigKey<?>) { k = subKey( ((ConfigKey<?>)k).getName() ); } else if (k instanceof String) { k = subKey((String)k); } else { if (k instanceof Supplier) { Object mapAtRoot = target.get(this); if (mapAtRoot==null) { mapAtRoot = new LinkedHashMap(); target.put(this, mapAtRoot); } if (mapAtRoot instanceof Map) { if (mapAtRoot instanceof ConcurrentMap) { return ((Map)mapAtRoot).put(k, value.getValue()); } else { synchronized (mapAtRoot) { return ((Map)mapAtRoot).put(k, value.getValue()); } } } } log.warn(""Unexpected subkey ""+k+"" being inserted into ""+this+""; ignoring""); k = null; } if (k!=null) return target.put(k, value.getValue()); else return null; }"
172,"public void initialize(Text schemaObject) { text = gameLoop.getAssets().getI18N().m(schemaObject.getText()); style = null; String styleRefPath = schemaObject.getStyleref(); TextStyle embeddedTextStyle = schemaObject.getStyle(); if (embeddedTextStyle != null) { style = embeddedTextStyle; } else if (styleRefPath != null) { FileHandle fh = gameLoop.getAssets().resolve(styleRefPath); if (fh != null && fh.exists()) { TextStyle styleRef = gameLoop.getAssets().get(styleRefPath, TextStyle.class); if (styleRef != null) { style = styleRef; } else { Gdx.app.error( ""Text"", ""A style-ref file ("" + styleRefPath + "") was declared for this piece of text. However, this file could not be loaded. Text="" + schemaObject.getText()); } } } if (style == null) { FileHandle fh = gameLoop.getAssets().resolve( DEFAULT_TEXT_STYLE_PATH); if (fh != null && fh.exists()) { TextStyle defaultTextStyle = gameLoop.getAssets().get( DEFAULT_TEXT_STYLE_PATH, TextStyle.class); if (defaultTextStyle != null) { style = defaultTextStyle; } else { Gdx.app.error( ""Text"", ""This piece of text does not have style associated and the default text style ("" + DEFAULT_TEXT_STYLE_PATH + "") is missing. Text="" + schemaObject.getText()); } } } if (style == null) { style = new TextStyle(); scale = 1.0F; color = Color.WHITE; bitmapFont = gameLoop.getAssets().getDefaultFont(); } else { scale = style.getScale(); es.eucm.ead.schema.components.Color c = style.getColor(); color = c == null ? Color.WHITE : new Color(c.getR(), c.getG(), c.getB(), c.getA()); String fontFile = style.getFont(); if (fontFile == null <START> || !gameLoop.getAssets().resolve(fontFile).exists()) { <END> bitmapFont = gameLoop.getAssets().getDefaultFont(); } else { bitmapFont = gameLoop.getAssets().get(style.getFont(), BitmapFont.class); } } bounds = bitmapFont.getBounds(text); }",necessary check if font file exists,"public void initialize(Text schemaObject) { text = gameLoop.getAssets().getI18N().m(schemaObject.getText()); style = null; String styleRefPath = schemaObject.getStyleref(); TextStyle embeddedTextStyle = schemaObject.getStyle(); if (embeddedTextStyle != null) { style = embeddedTextStyle; } else if (styleRefPath != null) { try { style = gameLoop.getAssets().get(styleRefPath, TextStyle.class); } catch (GdxRuntimeException e) { Gdx.app.error( ""Text"", ""A style-ref file ("" + styleRefPath + "") was declared for this piece of text. However, this file could not be loaded. Text="" + schemaObject.getText()); } } if (style == null) { try { style = gameLoop.getAssets().get(DEFAULT_TEXT_STYLE_PATH, TextStyle.class); } catch (GdxRuntimeException e) { Gdx.app.error( ""Text"", ""This piece of text does not have style associated and the default text style ("" + DEFAULT_TEXT_STYLE_PATH + "") is missing. Text="" + schemaObject.getText(), e); } } if (style == null) { style = new TextStyle(); scale = 1.0F; color = Color.WHITE; bitmapFont = gameLoop.getAssets().getDefaultFont(); } else { scale = style.getScale(); es.eucm.ead.schema.components.Color c = style.getColor(); color = c == null ? Color.WHITE : new Color(c.getR(), c.getG(), c.getB(), c.getA()); String fontFile = style.getFont(); if (fontFile == null) { bitmapFont = gameLoop.getAssets().getDefaultFont(); } else { bitmapFont = gameLoop.getAssets().get(style.getFont(), BitmapFont.class); } } bounds = bitmapFont.getBounds(text); }"
173,"public ChangeStreamIterable<TResult> showMigrationEvents(final boolean showMigrationEvents) { <START> this.showMigrationEvents = notNull(""showMigrationEvents"", showMigrationEvents); <END> return this; }",Remove this line. sense for a primitive value. happening is primitive boolean is auto-boxed a Boolean,public ChangeStreamIterable<TResult> showMigrationEvents(final boolean showMigrationEvents) { this.showMigrationEvents = showMigrationEvents; return this; }
174,"protected void recoverFromException(final String curQueue, final Exception ex) { final RecoveryStrategy recoveryStrategy = this.exceptionHandlerRef.get().onException(this, ex, curQueue); switch (recoveryStrategy) { case RECONNECT: if (ex instanceof JedisNoScriptException) { <START> LOG.info(""got JedisNoScriptException while reconnecting, reloading redis scripts""); <END> loadRedisScripts(); } else { LOG.info(""waiting for pool to reconnect to redis"", ex); try { Thread.sleep(RECONNECT_SLEEP_TIME); } catch (InterruptedException e) { } } break; case TERMINATE: LOG.warn(""Terminating in response to exception"", ex); end(false); break; case PROCEED: this.listenerDelegate.fireEvent(WORKER_ERROR, this, curQueue, null, null, null, ex); break; default: LOG.error(""Unknown RecoveryStrategy: "" + recoveryStrategy + "" while attempting to recover from the following exception; worker proceeding..."", ex); break; } }","Nit: Capital 'G' for start of sentence. Also, Redis capitalized","protected void recoverFromException(final String curQueue, final Exception ex) { final RecoveryStrategy recoveryStrategy = this.exceptionHandlerRef.get().onException(this, ex, curQueue); switch (recoveryStrategy) { case RECONNECT: if (ex instanceof JedisNoScriptException) { LOG.info(""Got JedisNoScriptException while reconnecting, reloading Redis scripts""); loadRedisScripts(); } else { LOG.info(""Waiting "" + RECONNECT_SLEEP_TIME + ""ms for pool to reconnect to redis"", ex); try { Thread.sleep(RECONNECT_SLEEP_TIME); } catch (InterruptedException e) { } } break; case TERMINATE: LOG.warn(""Terminating in response to exception"", ex); end(false); break; case PROCEED: this.listenerDelegate.fireEvent(WORKER_ERROR, this, curQueue, null, null, null, ex); break; default: LOG.error(""Unknown RecoveryStrategy: "" + recoveryStrategy + "" while attempting to recover from the following exception; worker proceeding..."", ex); break; } }"
175,"void printUsageInfo() { StringBuilder usage = new StringBuilder(); usage.append("" System Properties: \n""); usage.append("" -DselionHome=<folderPath>: \n""); <START> usage.append("" Path of SeLion home directory. Defaults to <user.home>/.selion/ \n""); <END> usage.append("" -D[property]=[value]: \n""); usage.append("" Any other System Property you wish to pass to the JVM \n""); System.out.print(usage.toString()); }","consider defaulting ""<user.home>/.selion2"" For SeLion 2 ? allow SeLIon 1.x 2 host","void printUsageInfo() { StringBuilder usage = new StringBuilder(); usage.append("" System Properties: \n""); usage.append("" -DselionHome=<folderPath>: \n""); usage.append("" Path of SeLion home directory. Defaults to <user.home>/.selion2/ \n""); usage.append("" -D[property]=[value]: \n""); usage.append("" Any other System Property you wish to pass to the JVM \n""); System.out.print(usage.toString()); }"
176,<START> private boolean hasDeadlineExpired(final Date deadline) { <END> if (deadline != null) { return System.currentTimeMillis() > deadline.getTime(); } else { return false; } },deadline-related methods static,private static boolean hasDeadlineExpired(final Date deadline) { if (deadline != null) { return System.currentTimeMillis() > deadline.getTime(); } else { return false; } }
177,public void connectRemote() { this.serverConnection = ApiConnection.REMOTE; if (!isServerRouteLoaded()) { return; } this.serverAddress = serverRoute.getRemoteAddress(); this.serverApi = buildServerApi(); <START> BusProvider.getBus().post(new ServerConnectionDetectedEvent(serverRoute.getRemoteAddress())); <END> },Is this (ServerConnectionDetectedEvent) post required? This basically repeats lines finally calls finishServerConnectionDetection(). call finishServerConnectionDetection() method instead of this,public void connectRemote() { this.serverConnection = ApiConnection.REMOTE; if (!isServerRouteLoaded()) { return; } this.serverAddress = serverRoute.getRemoteAddress(); this.serverApi = buildServerApi(); finishServerConnectionDetection(); }
178,"public static void main(String[] args) { <START> MonitoringService obj = new MonitoringService(); CircuitBreaker circuitBreaker = new CircuitBreaker(3000, 1, 2000 * 1000 * 1000); long serverStartTime = System.nanoTime(); <END> while (true) { LOGGER.info(obj.localResourceResponse()); LOGGER.info(obj.remoteResourceResponse(circuitBreaker, serverStartTime)); LOGGER.info(circuitBreaker.getState()); try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { LOGGER.error(e.getMessage()); } } }",local-variable type inference (var),"public static void main(String[] args) { var obj = new MonitoringService(); var circuitBreaker = new CircuitBreaker(3000, 1, 2000 * 1000 * 1000); var serverStartTime = System.nanoTime(); while (true) { LOGGER.info(obj.localResourceResponse()); LOGGER.info(obj.remoteResourceResponse(circuitBreaker, serverStartTime)); LOGGER.info(circuitBreaker.getState()); try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { LOGGER.error(e.getMessage()); } } }"
179,"public boolean accepts(Class<?> extensionType) { if (GetHandle.class.isAssignableFrom(extensionType) || Transactional.class.isAssignableFrom(extensionType)) { return true; } MemberResolver mr = new MemberResolver(typeResolver); ResolvedType extension_type = typeResolver.resolve(extensionType); ResolvedTypeWithMembers d = mr.resolve(extension_type, null, null); for (ResolvedMethod method : d.getMemberMethods()) { Method rawMethod = method.getRawMember(); <START> if (rawMethod.isAnnotationPresent(SqlQuery.class) <END> || rawMethod.isAnnotationPresent(SqlUpdate.class) || rawMethod.isAnnotationPresent(SqlBatch.class) || rawMethod.isAnnotationPresent(SqlCall.class) || rawMethod.isAnnotationPresent(CreateSqlObject.class) || rawMethod.isAnnotationPresent(Transaction.class)) { return true; } } return false; }",This hardcoded list sucks. a meta-annotation? java @SqlObjectAnnotation public @interface SqlQuery { ... },"public boolean accepts(Class<?> extensionType) { if (GetHandle.class.isAssignableFrom(extensionType) || Transactional.class.isAssignableFrom(extensionType)) { return true; } MemberResolver mr = new MemberResolver(typeResolver); ResolvedType extension_type = typeResolver.resolve(extensionType); ResolvedTypeWithMembers d = mr.resolve(extension_type, null, null); return Stream.of(d.getMemberMethods()) .flatMap(m -> Stream.of(m.getRawMember().getAnnotations())) .anyMatch(a -> a.annotationType().isAnnotationPresent(SqlMethodAnnotation.class)); }"
180,"String getTenantId() throws IOException { if (tenantId == null) { log.debug( ""Requesting tenant id""); ProxyConfiguration proxyConfig = configuration.getProxyConfiguration(); String hostname = proxyConfig.getHostname(); int port = proxyConfig.getPort(); HttpContext context = new BasicHttpContext(); HttpHost host = new HttpHost(hostname, port, ""http""); HttpPost post = new HttpPost(AUTHENTICATE_URL); post.addHeader(ACCEPT, APPLICATION_JSON.toString()); String username = configuration.getZenossCredentials().getUsername(); String password = configuration.getZenossCredentials().getPassword(); if (!Strings.nullToEmpty(username).isEmpty()) { CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials( new AuthScope(host.getHostName(), host.getPort()), new UsernamePasswordCredentials(username, password) ); context.setAttribute(ClientContext.CREDS_PROVIDER, provider); AuthCache cache = new BasicAuthCache(); BasicScheme scheme = new BasicScheme(); cache.put( host, scheme); context.setAttribute( ClientContext.AUTH_CACHE, cache); } <START> HttpResponse response = httpClient.execute(host, post, context); <END> int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); try { log.debug( ""Tenant id request complete with status: {}"", statusCode); if (statusCode >= 200 && statusCode <= 299) { Header id = response.getFirstHeader(ZenossTenant.ID_HTTP_HEADER); if (id == null) { log.warn( ""Failed to get zauth tenant id after login""); throw new RuntimeException(""Failed to get zauth tenant id after successful login""); } tenantId = id.getValue(); log.info(""Got tenant id: {}"", tenantId); } else { log.warn( ""Unsuccessful response from server: {}"", response.getStatusLine()); throw new IOException( ""Login for tenantId failed""); } } finally { try { entity.getContent().close(); } catch( IOException ex) { log.warn( ""Failed to close entity: {}"", ex); } } } return tenantId; }","docs explicitly a method return null check it, in a try/catch handle NPE","String getTenantId() throws IOException { if (tenantId == null) { log.debug( ""Requesting tenant id""); ProxyConfiguration proxyConfig = configuration.getProxyConfiguration(); String hostname = proxyConfig.getHostname(); int port = proxyConfig.getPort(); HttpContext context = new BasicHttpContext(); HttpHost host = new HttpHost(hostname, port, ""http""); HttpPost post = new HttpPost(AUTHENTICATE_URL); post.addHeader(ACCEPT, APPLICATION_JSON.toString()); String username = configuration.getZenossCredentials().getUsername(); String password = configuration.getZenossCredentials().getPassword(); if (!Strings.nullToEmpty(username).isEmpty()) { CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials( new AuthScope(host.getHostName(), host.getPort()), new UsernamePasswordCredentials(username, password) ); context.setAttribute(ClientContext.CREDS_PROVIDER, provider); AuthCache cache = new BasicAuthCache(); BasicScheme scheme = new BasicScheme(); cache.put( host, scheme); context.setAttribute( ClientContext.AUTH_CACHE, cache); } HttpResponse response = null; try { response = httpClient.execute(host, post, context); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); log.debug( ""Tenant id request complete with status: {}"", statusCode); if (statusCode >= 200 && statusCode <= 299) { Header id = response.getFirstHeader(ZenossTenant.ID_HTTP_HEADER); if (id == null) { log.warn( ""Failed to get zauth tenant id after login""); throw new RuntimeException(""Failed to get zauth tenant id after successful login""); } tenantId = id.getValue(); log.info(""Got tenant id: {}"", tenantId); } else { log.warn( ""Unsuccessful response from server: {}"", response.getStatusLine()); throw new IOException( ""Login for tenantId failed""); } } catch (NullPointerException ex) { log.warn( ""npe retrieving tenantId: {}"", ex); } finally { try { if ( response != null) { response.getEntity().getContent().close(); } } catch( NullPointerException | IOException ex) { log.warn( ""Failed to close request: {}"", ex); } } } return tenantId; }"
181,public IdentifierSource newObject() { <START> return new SequentialIdentifierGenerator(); <END> },"For above, Context.getService(IdentifierSourceService.class).getProviderByUuid(getUuidProperty());",public IdentifierSource newObject() { return Context.getService(IdentifierSourceService.class).getIdentifierSourceByUuid(getUuidProperty()); }
182,"public void fireProgress(float progress, String task) { if (progress > status.progress || StringUtils.equals(task, status.task)) { if (status.getPhase() == ProcessState.QUEUED) { status.setPhase(ProcessState.RUNNING); } status.setProgress(progress); status.setTask(task); if (progress > 0) { <START> long timeEalpsedMillis = <END> (new Date().getTime() - status.getCreationTime().getTime()); int estimatedCompletionMillis = (int) ((timeEalpsedMillis / progress) * timeEalpsedMillis + timeEalpsedMillis); Calendar calendar = Calendar.getInstance(); calendar.setTime(status.getCreationTime()); calendar.add(Calendar.MILLISECOND, estimatedCompletionMillis); status.setEstimatedCompletion(calendar.getTime()); } ProcessEvent event = new ProcessEvent(status, inputs, outputs); for (ProcessListener listener : listeners) { listener.progress(event); } } }","typo, timeElapsedMillis","public void fireProgress(float progress, String task) { if (progress > status.progress || StringUtils.equals(task, status.task)) { if (status.getPhase() == ProcessState.QUEUED) { status.setPhase(ProcessState.RUNNING); } status.setProgress(progress); status.setTask(task); if (progress > 0) { long timeElapsedMillis = (new Date().getTime() - status.getCreationTime().getTime()); int estimatedCompletionMillis = (int) ((timeElapsedMillis / progress) * timeElapsedMillis + timeElapsedMillis); Calendar calendar = Calendar.getInstance(); calendar.setTime(status.getCreationTime()); calendar.add(Calendar.MILLISECOND, estimatedCompletionMillis); status.setEstimatedCompletion(calendar.getTime()); } ProcessEvent event = new ProcessEvent(status, inputs, outputs); for (ProcessListener listener : listeners) { listener.progress(event); } } }"
183,"public boolean supports(AuthenticationToken token) { if (!(token instanceof BaseAuthenticationToken)) { LOGGER.debug( ""The supplied authentication token is not an instance of BaseAuthenticationToken. Sending back not supported.""); return false; } BaseAuthenticationToken authToken = (BaseAuthenticationToken) token; Object credentials = authToken.getCredentials(); if (credentials == null || authToken.getType() != AuthenticationTokenType.USERNAME) { LOGGER.debug( <START> ""The supplied authentication token has null/empty credentials. Sending back no supported.""); <END> return false; } LOGGER.debug( ""Token {} is supported by {}."", token.getClass(), UsernamePasswordRealm.class.getName()); return true; }","S/b ""Sending supported.""","public boolean supports(AuthenticationToken token) { if (!(token instanceof BaseAuthenticationToken)) { LOGGER.debug( ""The supplied authentication token is not an instance of BaseAuthenticationToken. Sending back not supported.""); return false; } BaseAuthenticationToken authToken = (BaseAuthenticationToken) token; Object credentials = authToken.getCredentials(); if (credentials == null || authToken.getType() != AuthenticationTokenType.USERNAME) { LOGGER.debug( ""The supplied authentication token has null/empty credentials. Sending back not supported.""); return false; } if (credentials instanceof String) { LOGGER.debug( ""Token {} is supported by {}."", token.getClass(), UsernamePasswordRealm.class.getName()); return true; } return false; }"
184,"private String getAdditionalXmsHeaders(Map<String, String> headers) { final List<String> xmsHeaderNameArray = headers.entrySet().stream() .filter(entry -> entry.getKey().toLowerCase(Locale.ROOT).startsWith(""x-ms-"")) .filter(entry -> entry.getValue() != null) .map(Map.Entry::getKey) .collect(Collectors.toList()); if (xmsHeaderNameArray.isEmpty()) { return """"; } <START> Collections.sort(xmsHeaderNameArray, Collator.getInstance()); <END> final StringBuilder canonicalizedHeaders = new StringBuilder(); for (final String key : xmsHeaderNameArray) { if (canonicalizedHeaders.length() > 0) { canonicalizedHeaders.append('\n'); } canonicalizedHeaders.append(key.toLowerCase(Locale.ROOT)) .append(':') .append(headers.get(key)); } return canonicalizedHeaders.toString(); }",Collator.getInstance(Locale) ? this local machine JVM default expect. I guess en_US safe choice,"private String getAdditionalXmsHeaders(Map<String, String> headers) { final List<String> xmsHeaderNameArray = headers.entrySet().stream() .filter(entry -> entry.getKey().toLowerCase(Locale.ROOT).startsWith(""x-ms-"")) .filter(entry -> entry.getValue() != null) .map(Map.Entry::getKey) .collect(Collectors.toList()); if (xmsHeaderNameArray.isEmpty()) { return """"; } Collections.sort(xmsHeaderNameArray, Collator.getInstance(Locale.ROOT)); final StringBuilder canonicalizedHeaders = new StringBuilder(); for (final String key : xmsHeaderNameArray) { if (canonicalizedHeaders.length() > 0) { canonicalizedHeaders.append('\n'); } canonicalizedHeaders.append(key.toLowerCase(Locale.ROOT)) .append(':') .append(headers.get(key)); } return canonicalizedHeaders.toString(); }"
185,"private boolean selectDefaultSubpicLanguage() { String defaultAudioLang = uiMgr.get(""default_audio_language"", ""English""); MediaLangInfo mli = (MediaLangInfo) mediaLangMap.get(defaultAudioLang); SubpictureFormat [] subs = this.currFile.getFileFormat().getSubpictureFormats(); for(int i = 0; i < subs.length; i++) { if(subs[i].getForced()) { <START> if(subs[i].getLanguage().equalsIgnoreCase(mli.twoChar)) <END> { System.out.println(""Setting forced subtitle to index: "" + i); playbackControl(DVD_CONTROL_SUBTITLE_CHANGE, i, -1); return true; } for(int j = 0; j < mli.threeChar.length; j++) { if(subs[i].getLanguage().equalsIgnoreCase(mli.threeChar[j])) { System.out.println(""Setting forced subtitle to index: "" + i); playbackControl(DVD_CONTROL_SUBTITLE_CHANGE, i, -1); return true; } } } } String defaultLang = uiMgr.get(""default_subpic_language"", """"); if (defaultLang == null || defaultLang.length() == 0) return true; return performLanguageMatch(defaultLang, getDVDAvailableSubpictures(), DVD_CONTROL_SUBTITLE_CHANGE, getDVDSubpicture()); }",need handle case mli is null,"private boolean selectDefaultSubpicLanguage() { String defaultAudioLang = uiMgr.get(""default_audio_language"", ""English""); String defaultLang = uiMgr.get(""default_subpic_language"", """"); if(defaultLang == null || defaultLang.length() == 0) { String [] subs = getDVDAvailableSubpictures(); String [] forcedSubs = new String[subs.length]; boolean hasForcedSub = false; for(int i = 0; i < subs.length; i++) { if(subs[i].toLowerCase().indexOf(""["" + Sage.rez(""forced"") + ""]"") != -1) { forcedSubs[i] = subs[i]; hasForcedSub = true; } else { forcedSubs[i] = """"; } } if(hasForcedSub) { return performLanguageMatch(defaultAudioLang, forcedSubs, DVD_CONTROL_SUBTITLE_CHANGE, getDVDSubpicture()); } else { return true; } } return performLanguageMatch(defaultLang, getDVDAvailableSubpictures(), DVD_CONTROL_SUBTITLE_CHANGE, getDVDSubpicture()); }"
186,"public static void initConnectionSettings(Configuration conf, ClientConfiguration awsConf) throws IOException { awsConf.setMaxConnections(intOption(conf, MAXIMUM_CONNECTIONS, DEFAULT_MAXIMUM_CONNECTIONS, 1)); initProtocolSettings(conf, awsConf); awsConf.setMaxErrorRetry(intOption(conf, MAX_ERROR_RETRIES, DEFAULT_MAX_ERROR_RETRIES, 0)); awsConf.setConnectionTimeout(intOption(conf, ESTABLISH_TIMEOUT, DEFAULT_ESTABLISH_TIMEOUT, 0)); awsConf.setSocketTimeout(intOption(conf, SOCKET_TIMEOUT, DEFAULT_SOCKET_TIMEOUT, 0)); int sockSendBuffer = intOption(conf, SOCKET_SEND_BUFFER, DEFAULT_SOCKET_SEND_BUFFER, 2048); int sockRecvBuffer = intOption(conf, SOCKET_RECV_BUFFER, DEFAULT_SOCKET_RECV_BUFFER, 2048); <START> int requestTimeoutMillis = intOption(conf, REQUEST_TIMEOUT, <END> DEFAULT_REQUEST_TIMEOUT, 0); awsConf.setSocketBufferSizeHints(sockSendBuffer, sockRecvBuffer); awsConf.setRequestTimeout(requestTimeoutMillis); String signerOverride = conf.getTrimmed(SIGNING_ALGORITHM, """"); if (!signerOverride.isEmpty()) { LOG.debug(""Signer override = {}"", signerOverride); awsConf.setSignerOverride(signerOverride); } }",Configuration.getTimeDuration(),"public static void initConnectionSettings(Configuration conf, ClientConfiguration awsConf) throws IOException { awsConf.setMaxConnections(intOption(conf, MAXIMUM_CONNECTIONS, DEFAULT_MAXIMUM_CONNECTIONS, 1)); initProtocolSettings(conf, awsConf); awsConf.setMaxErrorRetry(intOption(conf, MAX_ERROR_RETRIES, DEFAULT_MAX_ERROR_RETRIES, 0)); awsConf.setConnectionTimeout(intOption(conf, ESTABLISH_TIMEOUT, DEFAULT_ESTABLISH_TIMEOUT, 0)); awsConf.setSocketTimeout(intOption(conf, SOCKET_TIMEOUT, DEFAULT_SOCKET_TIMEOUT, 0)); int sockSendBuffer = intOption(conf, SOCKET_SEND_BUFFER, DEFAULT_SOCKET_SEND_BUFFER, 2048); int sockRecvBuffer = intOption(conf, SOCKET_RECV_BUFFER, DEFAULT_SOCKET_RECV_BUFFER, 2048); long requestTimeoutMillis = conf.getTimeDuration(REQUEST_TIMEOUT, DEFAULT_REQUEST_TIMEOUT, TimeUnit.SECONDS, TimeUnit.MILLISECONDS); if (requestTimeoutMillis > Integer.MAX_VALUE) { LOG.debug(""Request timeout is too high({} ms). Setting to {} ms instead"", requestTimeoutMillis, Integer.MAX_VALUE); requestTimeoutMillis = Integer.MAX_VALUE; } awsConf.setRequestTimeout((int) requestTimeoutMillis); awsConf.setSocketBufferSizeHints(sockSendBuffer, sockRecvBuffer); String signerOverride = conf.getTrimmed(SIGNING_ALGORITHM, """"); if (!signerOverride.isEmpty()) { LOG.debug(""Signer override = {}"", signerOverride); awsConf.setSignerOverride(signerOverride); } }"
187,public void run() { try { Thread.sleep(timeout); this.timedout.setIsSatisfied(true); } catch (InterruptedException e) { <START> byte a = 0; <END> } },Hmmm if is a do this,public void run() { try { Thread.sleep(timeout); this.timedout.setIsSatisfied(true); } catch (InterruptedException e) { } }
188,"public JavaRDD<StructuredRecord> transform(SparkExecutionPluginContext context, JavaRDD<StructuredRecord> input) throws Exception { if (input.isEmpty()) { return context.getSparkContext().emptyRDD(); } outputSchema = outputSchema != null ? outputSchema : config.getOutputSchema(input.first().getSchema()); final Map<String, String> mapping = config.getFeatureListMapping(); final int vectorSize = loadedModel.wordVectors().length / loadedModel.wordIndex().size(); return input.map(new Function<StructuredRecord, StructuredRecord>() { @Override public StructuredRecord call(StructuredRecord input) throws Exception { StructuredRecord.Builder builder = StructuredRecord.builder(outputSchema); for (Schema.Field field : input.getSchema().getFields()) { String fieldName = field.getName(); builder.set(fieldName, input.get(fieldName)); } for (Map.Entry<String, String> mapEntry : mapping.entrySet()) { String inputField = mapEntry.getKey(); String outputField = mapEntry.getValue(); List<String> text = SparkUtils.getInputFieldValue(input, inputField, config.pattern); int numWords = 0; double[] vectorValues = new double[vectorSize]; for (String word : text) { double[] wordVector = loadedModel.transform(word).toArray(); for (int i = 0; i < vectorSize; i++) { vectorValues[i] += wordVector[i]; } numWords++; } for (int i = 0; i < vectorSize; i++) { vectorValues[i] /= (double) numWords; } <START> builder.set(outputField, new ArrayList<>(Arrays.asList(ArrayUtils.toObject(vectorValues)))); <END> } return builder.build(); } }); }","need this a List, set double[]","public JavaRDD<StructuredRecord> transform(SparkExecutionPluginContext context, JavaRDD<StructuredRecord> input) throws Exception { if (input.isEmpty()) { return context.getSparkContext().emptyRDD(); } outputSchema = outputSchema != null ? outputSchema : config.getOutputSchema(input.first().getSchema()); final Map<String, String> mapping = config.getFeatureListMapping(config.outputColumnMapping); final int vectorSize = loadedModel.wordVectors().length / loadedModel.wordIndex().size(); return input.map(new Function<StructuredRecord, StructuredRecord>() { @Override public StructuredRecord call(StructuredRecord input) throws Exception { splitter = splitter == null ? Splitter.on(pattern) : splitter; StructuredRecord.Builder builder = StructuredRecord.builder(outputSchema); for (Schema.Field field : input.getSchema().getFields()) { String fieldName = field.getName(); builder.set(fieldName, input.get(fieldName)); } for (Map.Entry<String, String> mapEntry : mapping.entrySet()) { String inputField = mapEntry.getKey(); String outputField = mapEntry.getValue(); List<String> text = SparkUtils.getInputFieldValue(input, inputField, splitter); int numWords = 0; double[] vectorValues = new double[vectorSize]; for (String word : text) { double[] wordVector = loadedModel.transform(word).toArray(); for (int i = 0; i < vectorSize; i++) { vectorValues[i] += wordVector[i]; } numWords++; } for (int i = 0; i < vectorSize; i++) { vectorValues[i] /= (double) numWords; } builder.set(outputField, vectorValues); } return builder.build(); } }); }"
189,"<START> public void testOneFail() throws IOException { <END> final List<Pass> list = new ArrayList<Pass>(1); list.add(new PsFake(false)); final Opt<Identity> identity = new PsAll(list, 0).enter(new RqFake()); MatcherAssert.assertThat( identity.has(), Matchers.is(false) ); }","@lautarobock too, declare throws Exception","public void testOneFail() throws Exception { final List<Pass> list = new ArrayList<Pass>(1); list.add(new PsFake(false)); final Opt<Identity> identity = new PsAll(list, 0).enter(new RqFake()); MatcherAssert.assertThat( identity.has(), Matchers.is(false) ); }"
190,"private boolean passCheck() { if (G.enableDeviceCheck()) { deviceCheck(); } else { switch (G.protectionLevel()) { case ""p0"": return true; case ""p1"": final String oldpwd = G.profile_pwd(); if (oldpwd.length() == 0) { return true; } else { requestPassword(); } break; case ""p2"": final String pwd = G.sPrefs.getString(""LockPassword"", """"); if (pwd.length() == 0) { return true; } else { requestPassword(); } <START> case ""p3"": <END> if(FingerprintUtil.isAndroidSupport() && G.isFingerprintEnabled()){ requestFingerprint(); } } } return false; }","I guess need break statement, existing ""p2"" option break;","private boolean passCheck() { if (G.enableDeviceCheck()) { deviceCheck(); } else { switch (G.protectionLevel()) { case ""p0"": return true; case ""p1"": final String oldpwd = G.profile_pwd(); if (oldpwd.length() == 0) { return true; } else { requestPassword(); } break; case ""p2"": final String pwd = G.sPrefs.getString(""LockPassword"", """"); if (pwd.length() == 0) { return true; } else { requestPassword(); } break; case ""p3"": if(FingerprintUtil.isAndroidSupport() && G.isFingerprintEnabled()){ requestFingerprint(); } } } return false; }"
191,"public TileFilteredBuffer() { invFilter = addInventory(""blueprint"", 9, ItemHandlerManager.EnumAccess.NONE);; <START> invMain = addInventory(""materials"", 9, ItemHandlerManager.EnumAccess.INSERT, EnumPipePart.VALUES); <END> }","idea filtered buffer is allows items ""main"" inventory if item matches is in blueprint inventory. extract filtered buffer's main inventory","public TileFilteredBuffer() { invFilter = addInventory(""filter"", 9, ItemHandlerManager.EnumAccess.NONE); invMain = addInventory(""main"", new ItemHandlerSimple(9, this::onSlotChange) { @Override public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) { if(invFilter.getStackInSlot(slot) != null && StackUtil.canMerge(invFilter.getStackInSlot(slot), stack)) { return super.insertItem(slot, stack, simulate); } return stack; } }, ItemHandlerManager.EnumAccess.INSERT, EnumPipePart.VALUES); }"
192,"private void doSaveElementState(TreePath parentPath, ModelDelta delta, VirtualItem item, Collection<VirtualItem> set, int flagsToSave) { Object element = item.getData(); if (element != null) { boolean expanded = item.getExpanded(); boolean selected = set.contains(item); int flags = IModelDelta.NO_CHANGE; if (expanded && (flagsToSave & IModelDelta.EXPAND) != 0) { flags = flags | IModelDelta.EXPAND; } if (!expanded && (flagsToSave & IModelDelta.COLLAPSE) != 0 && item.hasItems()){ flags = flags | IModelDelta.COLLAPSE; } if (selected && (flagsToSave & IModelDelta.SELECT) != 0) { flags = flags | IModelDelta.SELECT; } if (expanded || flags != IModelDelta.NO_CHANGE) { int modelIndex = ((TreeModelContentProvider)getContentProvider()).viewToModelIndex(parentPath, item.getIndex().intValue()); TreePath elementPath = parentPath.createChildPath(element); int numChildren = ((TreeModelContentProvider)getContentProvider()).viewToModelCount(elementPath, item.getItemCount()); ModelDelta childDelta = delta.addNode(element, modelIndex, flags, numChildren); if (expanded) { for (VirtualItem <START> item2 : <END> item.getItems()) { doSaveElementState(elementPath, childDelta, item2, set, flagsToSave); } } } } }",rename childItem,"private void doSaveElementState(TreePath parentPath, ModelDelta delta, VirtualItem item, Collection<VirtualItem> set, int flagsToSave) { Object element = item.getData(); if (element != null) { boolean expanded = item.getExpanded(); boolean selected = set.contains(item); int flags = IModelDelta.NO_CHANGE; if (expanded && (flagsToSave & IModelDelta.EXPAND) != 0) { flags = flags | IModelDelta.EXPAND; } if (!expanded && (flagsToSave & IModelDelta.COLLAPSE) != 0 && item.hasItems()){ flags = flags | IModelDelta.COLLAPSE; } if (selected && (flagsToSave & IModelDelta.SELECT) != 0) { flags = flags | IModelDelta.SELECT; } if (expanded || flags != IModelDelta.NO_CHANGE) { int modelIndex = ((TreeModelContentProvider)getContentProvider()).viewToModelIndex(parentPath, item.getIndex().intValue()); TreePath elementPath = parentPath.createChildPath(element); int numChildren = ((TreeModelContentProvider)getContentProvider()).viewToModelCount(elementPath, item.getItemCount()); ModelDelta childDelta = delta.addNode(element, modelIndex, flags, numChildren); if (expanded) { for (VirtualItem childItem : item.getItems()) { doSaveElementState(elementPath, childDelta, childItem, set, flagsToSave); } } } } }"
193,"private boolean evaluateDeterministicFilterFunctionWithConstantInputs(FilterFunction function) { int[] inputs = function.getInputChannels(); Block[] blocks = new Block[inputs.length]; for (int i = 0; i < inputs.length; i++) { int columnIndex = filterFunctionInputMapping.get(inputs[i]); Object constantValue = constantValues[columnIndex]; blocks[i] = RunLengthEncodedBlock.create(columnTypes.get(columnIndex), constantValue == NULL_MARKER ? null : constantValue, 1); } int[] positions = new int[] {0}; initializeTmpErrors(1); int positionCount = function.filter(new Page(blocks), positions, 1, tmpErrors); if (tmpErrors[0] != null) { <START> this.constantFilterError = tmpErrors[0]; <END> } return positionCount == 1; }","remove ""this.""","private boolean evaluateDeterministicFilterFunctionWithConstantInputs(FilterFunction function) { int[] inputs = function.getInputChannels(); Block[] blocks = new Block[inputs.length]; for (int i = 0; i < inputs.length; i++) { int columnIndex = filterFunctionInputMapping.get(inputs[i]); Object constantValue = constantValues[columnIndex]; blocks[i] = RunLengthEncodedBlock.create(columnTypes.get(columnIndex), constantValue == NULL_MARKER ? null : constantValue, 1); } initializeTmpErrors(1); int positionCount = function.filter(new Page(blocks), new int[] {0}, 1, tmpErrors); if (tmpErrors[0] != null) { constantFilterError = tmpErrors[0]; } return positionCount == 1; }"
194,"private Map<String, ProxyProfileConfig> getProxyProfiles(TransportOutDescription transportOut) throws AxisFault { Parameter proxyProfilesParam = transportOut.getParameter(""proxyProfiles""); if (proxyProfilesParam == null) { return null; } if (log.isDebugEnabled()) { log.debug(name + "" Loading proxy profiles for the HTTP/S sender""); } QName profileQName = new QName(""profile""); <START> QName targetHostsQName = new QName(""targetHosts""); <END> OMElement proxyProfilesParamEle = proxyProfilesParam.getParameterElement(); Iterator<?> profiles = proxyProfilesParamEle.getChildrenWithName(profileQName); Map<String, ProxyProfileConfig> proxyProfileMap = new HashMap<String, ProxyProfileConfig>(); while (profiles.hasNext()) { OMElement profile = (OMElement) profiles.next(); OMElement targetHostsEle = profile.getFirstChildWithName(targetHostsQName); if (targetHostsEle == null || targetHostsEle.getText() == null) { String msg = ""Each proxy profile must define at least one host "" + ""or a wildcard matcher under the targetHosts element""; log.error(name + "" "" + msg); throw new AxisFault(msg); } HttpHost proxy = getHttpProxy(profile, targetHostsEle.getText()); UsernamePasswordCredentials proxyCredentials = getUsernamePasswordCredentials(profile); Set<String> proxyBypass = getProxyBypass(profile); ProxyProfileConfig proxyProfileConfig = new ProxyProfileConfig(proxy, proxyCredentials, proxyBypass); String[] targetHosts = targetHostsEle.getText().split("",""); for (String endPoint : targetHosts) { endPoint = endPoint.trim(); if (!proxyProfileMap.containsKey(endPoint)) { proxyProfileMap.put(endPoint, proxyProfileConfig); } else { log.warn(name + "" Multiple proxy profiles were found for the endPoint : "" + endPoint + "". Ignoring the excessive profiles.""); } } } if (proxyProfileMap.size() > 0) { log.info(name + "" Proxy profiles initialized for "" + proxyProfileMap.size() + "" targetHosts""); return proxyProfileMap; } return null; }","profileQname, targetHostsQname constant fields.. other places do same","private Map<String, ProxyProfileConfig> getProxyProfiles(TransportOutDescription transportOut) throws AxisFault { Parameter proxyProfilesParam = transportOut.getParameter(""proxyProfiles""); if (proxyProfilesParam == null) { return null; } if (log.isDebugEnabled()) { log.debug(name + "" Loading proxy profiles for the HTTP/S sender""); } OMElement proxyProfilesParamEle = proxyProfilesParam.getParameterElement(); Iterator<?> profiles = proxyProfilesParamEle.getChildrenWithName(Q_PROFILE); Map<String, ProxyProfileConfig> proxyProfileMap = new HashMap<String, ProxyProfileConfig>(); while (profiles.hasNext()) { OMElement profile = (OMElement) profiles.next(); OMElement targetHostsEle = profile.getFirstChildWithName(Q_TARGET_HOSTS); if (targetHostsEle == null || targetHostsEle.getText().isEmpty()) { String msg = ""Each proxy profile must define at least one host "" + ""or a wildcard matcher under the targetHosts element""; log.error(name + "" "" + msg); throw new AxisFault(msg); } HttpHost proxy = getHttpProxy(profile, targetHostsEle.getText()); UsernamePasswordCredentials proxyCredentials = getUsernamePasswordCredentials(profile); Set<String> proxyBypass = getProxyBypass(profile); ProxyProfileConfig proxyProfileConfig = new ProxyProfileConfig(proxy, proxyCredentials, proxyBypass); String[] targetHosts = targetHostsEle.getText().split("",""); for (String endpoint : targetHosts) { endpoint = endpoint.trim(); if (!proxyProfileMap.containsKey(endpoint)) { proxyProfileMap.put(endpoint, proxyProfileConfig); } else { log.warn(name + "" Multiple proxy profiles were found for the endpoint: "" + endpoint + "". Ignoring the excessive profiles.""); } } } if (proxyProfileMap.size() > 0) { log.info(name + "" Proxy profiles initialized for "" + proxyProfileMap.size() + "" targetHosts""); return proxyProfileMap; } return null; }"
195,"public OracleReturning(RowMapper<ResultType> mapper) { this.mapper = mapper; try { <START> this.oraclePS = Class.forName(""oracle.jdbc.OraclePreparedStatement""); <END> this.registerReturnParameter = oraclePS.getMethod(""registerReturnParameter"", new Class[]{int.class, int.class}); this.getReturnResultSet = oraclePS.getMethod(""getReturnResultSet""); } catch (Exception e) { throw new RuntimeException(e); } }",Do need do this reflective bullshit in a separate artifact,public OracleReturning(RowMapper<ResultType> mapper) { this.mapper = mapper; }
196,"public IntegrationTestingConfig get() { return new IntegrationTestingConfig() { @Override public String getCoordinatorUrl() { return ""http://"" + dockerIp + "":8081""; } @Override public String getIndexerUrl() { return ""http://"" + dockerIp + "":8090""; } @Override public String getRouterUrl() { return ""http://"" + dockerIp + "":8888""; } @Override public String getBrokerUrl() { return ""http://"" + dockerIp + "":8082""; } @Override public String getHistoricalUrl() { return ""http://"" + dockerIp + "":8083""; } @Override public String getMiddleManagerHost() { return dockerIp; } @Override public String getZookeeperHosts() { return dockerIp + "":2181""; } @Override <START> public String getZookeeperIntenalHosts() <END> { return ""druid-zookeeper-kafka:2181""; } @Override public String getKafkaHost() { return dockerIp + "":9093""; } @Override public String getKafkaInternalHost() { return ""druid-zookeeper-kafka:9092""; } @Override public String getProperty(String prop) { if (prop.equals(""hadoopTestDir"")) { return hadoopDir; } throw new UnsupportedOperationException(""DockerConfigProvider does not support property "" + prop); } @Override public String getUsername() { return null; } @Override public String getPassword() { return null; } @Override public Map<String, String> getProperties() { return new HashMap<>(); } @Override public boolean manageKafkaTopic() { return true; } }; }",Intenal -> Internal,"public IntegrationTestingConfig get() { return new IntegrationTestingConfig() { @Override public String getCoordinatorUrl() { return ""http://"" + dockerIp + "":8081""; } @Override public String getIndexerUrl() { return ""http://"" + dockerIp + "":8090""; } @Override public String getRouterUrl() { return ""http://"" + dockerIp + "":8888""; } @Override public String getBrokerUrl() { return ""http://"" + dockerIp + "":8082""; } @Override public String getHistoricalUrl() { return ""http://"" + dockerIp + "":8083""; } @Override public String getMiddleManagerHost() { return dockerIp; } @Override public String getZookeeperHosts() { return dockerIp + "":2181""; } @Override public String getZookeeperInternalHosts() { return ""druid-zookeeper-kafka:2181""; } @Override public String getKafkaHost() { return dockerIp + "":9093""; } @Override public String getKafkaInternalHost() { return ""druid-zookeeper-kafka:9092""; } @Override public String getProperty(String prop) { if (prop.equals(""hadoopTestDir"")) { return hadoopDir; } throw new UnsupportedOperationException(""DockerConfigProvider does not support property "" + prop); } @Override public String getUsername() { return null; } @Override public String getPassword() { return null; } @Override public Map<String, String> getProperties() { return new HashMap<>(); } @Override public boolean manageKafkaTopic() { return true; } }; }"
197,"public String get(Properties properties) { <START> return new org.postgresql.util.ExpressionProperties(properties).getProperty(_name, _defaultValue); <END> }",This unexpected consequence if dfwe${...}asdfa pattern right a password property,"public String get(Properties properties) { return properties.getProperty(_name, _defaultValue); }"
198,"public SoulStrings(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, ""{X}{B}""); Effect effect = new DoUnlessAnyPlayerPaysEffect( new ReturnFromGraveyardToHandTargetEffect(), new VariableManaCost() ); this.getSpellAbility().addEffect(effect); <START> this.getSpellAbility().addTarget(new TargetCardInGraveyard(2, new FilterCreatureCard(""creature cards from your graveyard""))); <END> }",TargetCardInYourGraveyard,"public SoulStrings(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, ""{X}{B}""); Effect effect = new DoUnlessAnyPlayerPaysEffect( new ReturnFromGraveyardToHandTargetEffect(), new VariableManaCost() ); this.getSpellAbility().addEffect(effect); this.getSpellAbility().addTarget(new TargetCardInYourGraveyard(2, new FilterCreatureCard(""creature cards from your graveyard""))); }"
199,"public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_search, container, false); this.setHasOptionsMenu(true); ButterKnife.inject(this, view); apiClient = new MITAPIClient(getActivity()); recentSearches = new ArrayList<>(); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); Set<String> set = sharedPreferences.getStringSet(NEWS_SEARCH_HISTORY, null); <START> if (set != null) { <END> recentSearches.addAll(set); mitSearchAdapter = new MITSearchAdapter(getActivity().getApplicationContext(), recentSearches, this); recentSearchListView.setAdapter(mitSearchAdapter); } return view; }",mitSearchAdapter instantiated array of size 0 if set == null,"public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_search, container, false); this.setHasOptionsMenu(true); ButterKnife.inject(this, view); apiClient = new MITAPIClient(getActivity()); recentSearches = new ArrayList<>(); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); Set<String> set = sharedPreferences.getStringSet(NEWS_SEARCH_HISTORY, null); if (set != null) { recentSearches.addAll(set); } mitSearchAdapter = new MITSearchAdapter(getActivity().getApplicationContext(), recentSearches, this); recentSearchListView.setAdapter(mitSearchAdapter); return view; }"
200,"public void readWriteOffsets() throws Exception { KafkaConsumer<String, ChangeEvent> consumer = mock(KafkaConsumer.class); Uris uris = Uris.fromString(""<LINK_0>"").setEntityNamespaces(new long[]{0}); Instant startTime = Instant.ofEpochMilli(BEGIN_DATE); Collection<String> topics = ImmutableList.of(""topictest"", ""othertopic""); when(consumer.partitionsFor(any())).thenAnswer(inv -> { String pName = inv.getArgumentAt(0, String.class); PartitionInfo pi = new PartitionInfo(pName, 0, null, null, null); return ImmutableList.of(pi); }); HttpClient httpClient = buildHttpClient(getHttpProxyHost(), getHttpProxyPort()); RdfClient rdfClient = buildRdfClient( <START> url(""/namespace/"" + ""wdq"" + ""/sparql""), <END> httpClient ); try { rdfClient.update(""CLEAR ALL""); cleanupPoller(); KafkaOffsetsRepository kafkaOffsetsRepository = new KafkaOffsetsRepository(uris.builder().build(), rdfClient); poller = new KafkaPoller(consumer, uris, startTime, 5, topics, kafkaOffsetsRepository); when(consumer.position(any())).thenReturn(1L, 2L, 3L, 4L); kafkaOffsetsRepository.store(poller.currentOffsets()); Map<TopicPartition, OffsetAndTimestamp> offsets = kafkaOffsetsRepository.load(startTime); assertThat(offsets.get(new TopicPartition(""topictest"", 0)).offset(), is(1L)); assertThat(offsets.get(new TopicPartition(""othertopic"", 0)).offset(), is(2L)); kafkaOffsetsRepository.store(poller.currentOffsets()); offsets = kafkaOffsetsRepository.load(startTime); assertThat(offsets.get(new TopicPartition(""topictest"", 0)).offset(), is(3L)); assertThat(offsets.get(new TopicPartition(""othertopic"", 0)).offset(), is(4L)); } finally { rdfClient.update(""CLEAR ALL""); httpClient.stop(); if (poller != null) { poller.close(); } } }",components string,"public void readWriteOffsets() throws Exception { KafkaConsumer<String, ChangeEvent> consumer = mock(KafkaConsumer.class); Uris uris = Uris.fromString(""<LINK_0>"").setEntityNamespaces(new long[]{0}); Instant startTime = Instant.ofEpochMilli(BEGIN_DATE); Collection<String> topics = ImmutableList.of(""topictest"", ""othertopic""); when(consumer.partitionsFor(any())).thenAnswer(inv -> { String pName = inv.getArgumentAt(0, String.class); PartitionInfo pi = new PartitionInfo(pName, 0, null, null, null); return ImmutableList.of(pi); }); HttpClient httpClient = buildHttpClient(getHttpProxyHost(), getHttpProxyPort()); RdfClient rdfClient = buildRdfClient( url(""/namespace/wdq/sparql""), httpClient ); try { rdfClient.update(""CLEAR ALL""); cleanupPoller(); KafkaOffsetsRepository kafkaOffsetsRepository = new KafkaOffsetsRepository(uris.builder().build(), rdfClient); poller = new KafkaPoller(consumer, uris, startTime, 5, topics, kafkaOffsetsRepository); when(consumer.position(any())).thenReturn(1L, 2L, 3L, 4L); kafkaOffsetsRepository.store(poller.currentOffsets()); Map<TopicPartition, OffsetAndTimestamp> offsets = kafkaOffsetsRepository.load(startTime); assertThat(offsets.get(new TopicPartition(""topictest"", 0)).offset(), is(1L)); assertThat(offsets.get(new TopicPartition(""othertopic"", 0)).offset(), is(2L)); kafkaOffsetsRepository.store(poller.currentOffsets()); offsets = kafkaOffsetsRepository.load(startTime); assertThat(offsets.get(new TopicPartition(""topictest"", 0)).offset(), is(3L)); assertThat(offsets.get(new TopicPartition(""othertopic"", 0)).offset(), is(4L)); } finally { rdfClient.update(""CLEAR ALL""); httpClient.stop(); if (poller != null) { poller.close(); } } }"
201,"public List<T> listByKeys(List<Long> idsList, Class<T> clazz){ if (idsList == null || idsList.isEmpty()) { return Collections.emptyList(); } PersistenceManager pm = PersistenceFilter.getManager(); List<Object> datastoreKeysList = new ArrayList<>(); for (Long id : idsList) { Key key = KeyFactory.createKey(clazz.getSimpleName(), id); Object objectId = pm.newObjectIdInstance(clazz, key); datastoreKeysList.add(objectId); } final List<T> resultsList = new ArrayList<>(); try { <START> resultsList.addAll(pm.getObjectsById(datastoreKeysList)); <END> } catch (NucleusObjectNotFoundException nfe) { log.warning(""No "" + clazz.getCanonicalName() + "" found: "" + nfe.getMessage()); } return resultsList; }","happen if some of ids others not, work returns throw exception","public List<T> listByKeys(List<Long> idsList, Class<T> clazz){ if (idsList == null || idsList.isEmpty()) { return Collections.emptyList(); } PersistenceManager pm = PersistenceFilter.getManager(); List<Object> datastoreKeysList = new ArrayList<>(); for (Long id : idsList) { Key key = KeyFactory.createKey(clazz.getSimpleName(), id); Object objectId = pm.newObjectIdInstance(clazz, key); datastoreKeysList.add(objectId); } final List<T> resultsList = new ArrayList<>(); try { resultsList.addAll(pm.getObjectsById(datastoreKeysList)); } catch (NucleusObjectNotFoundException nfe) { log.warning(nfe.getMessage()); return listByKeysIndividually(idsList); } catch (ArrayIndexOutOfBoundsException exception) { log.warning(""Some entities were not found""); return listByKeysIndividually(idsList); } return resultsList; }"
202,protected void writeSpecificHeader(ByteBuffer buffer) { int size = getConfig().getMaxChildren(); buffer.putInt(extension); buffer.putInt(nbChildren); for (int i = 0; i < nbChildren; i++) { buffer.putInt(children[i]); } for (int i = nbChildren; i < size; i++) { buffer.putInt(0); } for (int i = 0; i < nbChildren; i++) { buffer.putLong(childStart[i]); } for (int i = 0; i < nbChildren; i++) { buffer.putLong(childEnd[i]); } <START> for (int i = nbChildren; i < size; i++) { <END> buffer.putLong(0); } },I this loop start time array puts. else a smaller header is calculated in getSpecificHeaderSize(),protected void writeSpecificHeader(ByteBuffer buffer) { int size = getConfig().getMaxChildren(); buffer.putInt(extension); buffer.putInt(nbChildren); for (int i = 0; i < nbChildren; i++) { buffer.putInt(children[i]); } for (int i = nbChildren; i < size; i++) { buffer.putInt(0); } for (int i = 0; i < nbChildren; i++) { buffer.putLong(childStart[i]); } for (int i = nbChildren; i < size; i++) { buffer.putLong(0); } for (int i = 0; i < nbChildren; i++) { buffer.putLong(childEnd[i]); } for (int i = nbChildren; i < size; i++) { buffer.putLong(Long.MAX_VALUE); } }
203,public long getLastModified() throws IOException { <START> File file = new File(super.getLocalePath()); <END> if (file.exists()) { return file.lastModified(); } return 0; },"I this call getExistedPath(url) (or equivalent if renamed). constructor call url.getPath() for parameter, this method to. constructor calls getExistedPath(url), _this method call too_ (for consistency)",public long getLastModified() throws IOException { if (file.exists()) { return file.lastModified(); } return 0; }
204,"protected void configureColumnSettings(Displayer displayer, CSVDataSetDef csvDataSetDef) { DataSet dataSet = displayer.getDataSetHandler().getLastDataSet(); <START> for (DataColumn column : dataSet.getColumns()) { <END> if (column.getColumnType().equals(ColumnType.DATE)) { String pattern = csvDataSetDef.getDatePattern(column.getId()); if (pattern != null) { displayer.getDisplayerSettings().setColumnValuePattern(column.getId(), pattern); } } else if (column.getColumnType().equals(ColumnType.NUMBER)) { String pattern = csvDataSetDef.getNumberPattern(column.getId()); if (pattern != null) { displayer.getDisplayerSettings().setColumnValuePattern(column.getId(), pattern); } } } }","@dgutierr - here, try avoid external iterations soon do incremental replacement internal iterators / of streams..","protected void configureColumnSettings(Displayer displayer, CSVDataSetDef csvDataSetDef) { DataSet dataSet = displayer.getDataSetHandler().getLastDataSet(); dataSet.getColumns().stream().forEach(column -> { if (column.getColumnType().equals(ColumnType.DATE)) { String pattern = csvDataSetDef.getDatePattern(column.getId()); if (pattern != null) { displayer.getDisplayerSettings().setColumnValuePattern(column.getId(), pattern); } } else if (column.getColumnType().equals(ColumnType.NUMBER)) { String pattern = csvDataSetDef.getNumberPattern(column.getId()); if (pattern != null) { displayer.getDisplayerSettings().setColumnValuePattern(column.getId(), pattern); } } }); }"
205,"public static Iterable<Object[]> getTracePaths() throws Exception { final List<Object[]> dirs = new LinkedList<>(); addDirsFrom(dirs, CTF_SUITE_BASE_PATH.resolve(Paths.get(""regression"", ""metadata"", ""pass"", ""literal-integers"")), IStatus.OK, 10, false); String tracePath; try { tracePath = FileLocator.toFileURL(CtfTestTrace.KERNEL.getTraceURL()).getPath(); } catch (IOException e) { <START> throw new IllegalStateException(); <END> } addDirsFrom(dirs, Paths.get(tracePath), IStatus.OK, 10, false); addDirsFrom(dirs, CTF_SUITE_BASE_PATH.resolve(Paths.get(""regression"", ""metadata"", ""fail"", ""enum-empty"")), IStatus.WARNING, 1, true); addDirsFrom(dirs, CTF_SUITE_BASE_PATH.resolve(Paths.get(""regression"", ""metadata"", ""fail"", ""lttng-modules-2.0-pre1"")), IStatus.WARNING, 1, true); addDirsFrom(dirs, BASE_PATH.resolve(Paths.get(""synctraces.tar.gz"")), IStatus.ERROR, 1, false); return dirs; }",propagate e please,"public static Iterable<Object[]> getTracePaths() throws Exception { final List<Object[]> dirs = new LinkedList<>(); addDirsFrom(dirs, CTF_SUITE_BASE_PATH.resolve(Paths.get(""regression"", ""metadata"", ""pass"", ""literal-integers"")), IStatus.OK, 10, false); String tracePath = FileLocator.toFileURL(CtfTestTrace.KERNEL.getTraceURL()).getPath(); addDirsFrom(dirs, Paths.get(tracePath), IStatus.OK, 10, false); addDirsFrom(dirs, CTF_SUITE_BASE_PATH.resolve(Paths.get(""regression"", ""metadata"", ""fail"", ""enum-empty"")), IStatus.WARNING, 1, true); addDirsFrom(dirs, CTF_SUITE_BASE_PATH.resolve(Paths.get(""regression"", ""metadata"", ""fail"", ""lttng-modules-2.0-pre1"")), IStatus.WARNING, 1, true); addDirsFrom(dirs, BASE_PATH.resolve(Paths.get(""synctraces.tar.gz"")), IStatus.ERROR, 1, false); return dirs; }"
206,"public void testInitialization() { SimpleIgnoreCache cache = new SimpleIgnoreCache(ignoreTestDir); File test = new File(ignoreTestDir.getAbsolutePath() + ""/new/a/b1/test.stp""); assertTrue(""Missing file "" + test.getAbsolutePath(), test.exists()); try { cache.partiallyInitialize(test); } catch (IOException e) { fail(""IOException when attempting to lazy initialize""); <START> e.printStackTrace(); <END> } boolean result = cache.isIgnored(test); assertFalse(""Unexpected match for "" + test.toString(), result); File folder = test.getParentFile(); IgnoreNode rules = null; while (!folder.getAbsolutePath().equals(ignoreTestDir.getAbsolutePath()) && folder.getAbsolutePath().length() > 0) { rules = cache.getRules(folder.getAbsolutePath()); assertNotNull(""Ignore file was not initialized for "" + folder.getAbsolutePath(), rules); assertEquals(1, rules.getRules().size()); folder = folder.getParentFile(); } if (rules != null) { assertEquals(1, rules.getRules().size()); } else { fail(""Ignore nodes not initialized""); } }","This stack trace, other in this file, get printed fail(String) method exception thrown. Personally, I tend declare exceptions in test method I JGit convention here","public void testInitialization() { SimpleIgnoreCache cache = new SimpleIgnoreCache(ignoreTestDir); File test = new File(ignoreTestDir.getAbsolutePath() + ""/new/a/b1/test.stp""); assertTrue(""Missing file "" + test.getAbsolutePath(), test.exists()); try { cache.partiallyInitialize(test); } catch (IOException e) { e.printStackTrace(); fail(""IOException when attempting to lazy initialize""); } boolean result = cache.isIgnored(test); assertFalse(""Unexpected match for "" + test.toString(), result); File folder = test.getParentFile(); IgnoreNode rules = null; while (!folder.getAbsolutePath().equals(ignoreTestDir.getAbsolutePath()) && folder.getAbsolutePath().length() > 0) { rules = cache.getRules(folder.getAbsolutePath()); assertNotNull(""Ignore file was not initialized for "" + folder.getAbsolutePath(), rules); assertEquals(1, rules.getRules().size()); folder = folder.getParentFile(); } if (rules != null) { assertEquals(1, rules.getRules().size()); } else { fail(""Ignore nodes not initialized""); } }"
207,"public String getQuestionResultStatisticsHtml(List<FeedbackResponseAttributes> responses, <START> FeedbackQuestionAttributes question, <END> String studentEmail, FeedbackSessionResultsBundle bundle, String view) { if (""student"".equals(view) || responses.isEmpty()) { return """"; } StringBuilder fragments = new StringBuilder(); Map<String, Integer> answerFrequency = new LinkedHashMap<>(); for (String option : mcqChoices) { answerFrequency.put(option, 0); } if (otherEnabled) { answerFrequency.put(""Other"", 0); } for (FeedbackResponseAttributes response : responses) { String answerString = response.getResponseDetails().getAnswerString(); boolean isOtherOptionAnswer = ((FeedbackMcqResponseDetails) response.getResponseDetails()).isOtherOptionAnswer(); if (isOtherOptionAnswer) { answerFrequency.putIfAbsent(""Other"", 0); answerFrequency.put(""Other"", answerFrequency.get(""Other"") + 1); } else { answerFrequency.putIfAbsent(answerString, 0); answerFrequency.put(answerString, answerFrequency.get(answerString) + 1); } } DecimalFormat df = new DecimalFormat(""#.##""); for (Entry<String, Integer> entry : answerFrequency.entrySet()) { fragments.append(Templates.populateTemplate(FormTemplates.MCQ_RESULT_STATS_OPTIONFRAGMENT, Slots.MCQ_CHOICE_VALUE, SanitizationHelper.sanitizeForHtml(entry.getKey()), Slots.COUNT, entry.getValue().toString(), Slots.PERCENTAGE, df.format(100 * (double) entry.getValue() / responses.size()))); } return Templates.populateTemplate(FormTemplates.MCQ_RESULT_STATS, Slots.FRAGMENTS, fragments.toString()); }",here. Pls refer <LINK_0>,"public String getQuestionResultStatisticsHtml(List<FeedbackResponseAttributes> responses, FeedbackQuestionAttributes question, String studentEmail, FeedbackSessionResultsBundle bundle, String view) { if (""student"".equals(view) || responses.isEmpty()) { return """"; } StringBuilder fragments = new StringBuilder(); Map<String, Integer> answerFrequency = collateAnswerFrequency(responses); DecimalFormat df = new DecimalFormat(""#.##""); answerFrequency.forEach((key, value) -> fragments.append(Templates.populateTemplate(FormTemplates.MCQ_RESULT_STATS_OPTIONFRAGMENT, Slots.MCQ_CHOICE_VALUE, SanitizationHelper.sanitizeForHtml(key), Slots.COUNT, value.toString(), Slots.PERCENTAGE, df.format(100 * (double) value / responses.size())))); return Templates.populateTemplate(FormTemplates.MCQ_RESULT_STATS, Slots.FRAGMENTS, fragments.toString()); }"
208,"private Map<String, List<Pair<VDS, Integer>>> getDeviceListAllVds(List<String> lunsToResize) { Map<String, List<Pair<VDS, Integer>>> lunToVds = new HashMap<>(); for (VDS vds : getAllRunningVdssInPool()) { GetDeviceListVDSCommandParameters parameters = new GetDeviceListVDSCommandParameters(vds.getId(), getStorageDomain().getStorageType(), lunsToResize); List<LUNs> luns = (List<LUNs>) runVdsCommand(VDSCommandType.GetDeviceList, parameters).getReturnValue(); for (LUNs lun : luns) { List<Pair<VDS, Integer>> vdsSizePairs = lunToVds.get(lun.getLUN_id()); if (vdsSizePairs == null) { vdsSizePairs = new ArrayList<>(); lunToVds.put(lun.getLUN_id(), vdsSizePairs); } <START> vdsSizePairs.add(new Pair<VDS, Integer>(vds, lun.getDeviceSize())); <END> } } return lunToVds; }",a MultiValueMapUtils - save this if statement,"private Map<String, List<Pair<VDS, Integer>>> getDeviceListAllVds(List<String> lunsToResize) { Map<String, List<Pair<VDS, Integer>>> lunToVds = new HashMap<>(); for (VDS vds : getAllRunningVdssInPool()) { GetDeviceListVDSCommandParameters parameters = new GetDeviceListVDSCommandParameters(vds.getId(), getStorageDomain().getStorageType(), lunsToResize); List<LUNs> luns = (List<LUNs>) runVdsCommand(VDSCommandType.GetDeviceList, parameters).getReturnValue(); for (LUNs lun : luns) { MultiValueMapUtils.addToMap(lun.getLUN_id(), new Pair<>(vds, lun.getDeviceSize()), lunToVds); } } return lunToVds; }"
209,"public void testFindLiveVersionFile() throws Exception{ String folderName = ""/testOldFile""+UUIDGenerator.generateUuid(); Folder ff = APILocator.getFolderAPI().createFolders(folderName, host, user, false); java.io.File tmp=new java.io.File(APILocator.getFileAPI().getRealAssetPathTmpBinary()+java.io.File.separator+""testOldFile""); if(!tmp.exists()) tmp.mkdirs(); java.io.File data=new java.io.File(tmp, ""test-""+UUIDGenerator.generateUuid()+"".txt""); FileWriter fw=new FileWriter(data,true); fw.write(""file content""); fw.close(); File file = new File(); file.setFileName(""legacy.txt""); file.setFriendlyName(""legacy.txt""); file.setMimeType(""text/plain""); file.setTitle(""legacy.txt""); file.setSize((int)data.length()); file.setModUser(user.getUserId()); file.setModDate(Calendar.getInstance().getTime()); <START> file = APILocator.getFileAPI().saveFile(file, data, ff, user, false); <END> APILocator.getFileAPI().publishFile(file, user, false); Versionable verAPI = APILocator.getVersionableAPI().findLiveVersion(file.getIdentifier(), user, false); assertEquals(verAPI.getTitle(),file.getTitle()); assertEquals(verAPI.getInode(),file.getInode()); APILocator.getFileAPI().delete(file, user, false); APILocator.getFolderAPI().delete(ff, user, false); }",extracted method createLegacyFile,"public void testFindLiveVersionFile() throws Exception{ File file = createLegacyFile(); APILocator.getFileAPI().publishFile(file, user, false); Versionable verAPI = APILocator.getVersionableAPI().findLiveVersion(file.getIdentifier(), user, false); assertEquals(verAPI.getTitle(),file.getTitle()); assertEquals(verAPI.getInode(),file.getInode()); Folder folder = APILocator.getFileAPI().getFileFolder(file, host, user, false); APILocator.getFileAPI().delete(file, user, false); APILocator.getFolderAPI().delete(folder, user, false); }"
210,"public void processEntry(MarshalledEntry<K, V> marshalledEntry, AdvancedCacheLoader.TaskContext taskContext) throws InterruptedException { if (!taskContext.isStopped()) { <START> InternalCacheEntry<K, V> ice = PersistenceUtil.convert(marshalledEntry, entryFactory); <END> if (!ice.isExpired(timeService.wallClockTime())) { action.apply(marshalledEntry.getKey(), ice); } if (Thread.interrupted()) { throw new InterruptedException(); } } }",curious if avoid converting MarshalledEntry InternalCacheEntry checking expiration. MarshalledEntry.getMetadata() here,"public void processEntry(MarshalledEntry<K, V> marshalledEntry, AdvancedCacheLoader.TaskContext taskContext) throws InterruptedException { if (!taskContext.isStopped()) { InternalMetadata metadata = marshalledEntry.getMetadata(); if (metadata == null || !metadata.isExpired(timeService.wallClockTime())) { InternalCacheEntry<K, V> ice = PersistenceUtil.convert(marshalledEntry, entryFactory); action.apply(marshalledEntry.getKey(), ice); } if (Thread.interrupted()) { throw new InterruptedException(); } } }"
211,"public <T> void set(PreparedStatement stmt, Path<?> path, int i, T value) throws SQLException { if (Null.class.isInstance(value)) { <START> Integer sqlType = path != null && !path.getMetadata().isRoot() ? ColumnMetadata.getColumnMetadata(path).getJdbcType() : null; <END> if (sqlType != null) { stmt.setNull(i, sqlType); } else { stmt.setNull(i, Types.NULL); } } else { getType(path, (Class) value.getClass()).setValue(stmt, i, value); } }","test case is ok, fix this differently, root path usage is case this breaks. Integer sqlType = null; if (path != null) { ColumnMetadata metadata = ColumnMetadata.getColumnMetadata(path); if (metadata.hasJdbcType()) { jdbcType = metadata.getJdbcType(); } }","public <T> void set(PreparedStatement stmt, Path<?> path, int i, T value) throws SQLException { if (Null.class.isInstance(value)) { Integer sqlType = null; if (path != null) { ColumnMetadata columnMetadata = ColumnMetadata.getColumnMetadata(path); if (columnMetadata.hasJdbcType()) { sqlType = columnMetadata.getJdbcType(); } } if (sqlType != null) { stmt.setNull(i, sqlType); } else { stmt.setNull(i, Types.NULL); } } else { getType(path, (Class) value.getClass()).setValue(stmt, i, value); } }"
212,"<START> @Override public <T> Supplier<CompletableFuture<T>> execute(RexNode node) { <END> return () -> { final CompletableFuture<T> f = new CompletableFuture<>(); Scalar s = scalar(node, null); final Row r = ctx.rowHandler().factory(typeFactory.getJavaClass(node.getType())).create(); ctx.execute(() -> { try { s.execute(ctx, null, r); f.complete((T)ctx.rowHandler().get(0, r)); } catch (Throwable t) { f.completeExceptionally(t); } }); return f; }; }",return a here? do need a) Supplier b) Future,"@Override public <T> Supplier<T> execute(RexNode node) { return () -> { Scalar s = scalar(node, null); final Row r = ctx.rowHandler().factory(typeFactory.getJavaClass(node.getType())).create(); s.execute(ctx, null, r); return (T)ctx.rowHandler().get(0, r); }; }"
213,<START> protected boolean hasChanges() { <END> return hasChanges; },this protected? override if is public,public boolean hasChanges() { return hasChanges; }
214,"private void createSampleBoard() { logger.info(""Creating "" + SAMPLE_BOARD); panelControl.closeAllPanels(); List<PanelInfo> panelData = new ArrayList<>(); panelData.add(new PanelInfo(FIRST_SAMPLE_PANEL_NAME, FIRST_SAMPLE_FILTER)); panelData.add(new PanelInfo(SECOND_SAMPLE_PANEL_NAME, SECOND_SAMPLE_FILTER)); panelData.add(new PanelInfo(THIRD_SAMPLE_PANEL_NAME, THIRD_SAMPLE_FILTER)); createBoard(panelData, SAMPLE_BOARD); panelControl.selectPanel(0); triggerBoardSaveEventSequence(SAMPLE_BOARD); DialogMessage.showInformationDialog(""Auto-create Board - "" + SAMPLE_BOARD, SAMPLE_BOARD + "" has been created and loaded.\n\n"" + <START> ""It is saved under the name \"""" + SAMPLE_BOARD + ""\"".""); <END> }","here, format strings","private void createSampleBoard() { logger.info(""Creating "" + SAMPLE_BOARD); panelControl.closeAllPanels(); List<PanelInfo> panelData = new ArrayList<>(); for (int i = 0; i < SAMPLE_PANEL_NAMES.size(); i++) { panelData.add(new PanelInfo(SAMPLE_PANEL_NAMES.get(i), SAMPLE_PANEL_FILTERS.get(i))); } createBoard(panelData, SAMPLE_BOARD); panelControl.selectPanel(0); triggerBoardSaveEventSequence(SAMPLE_BOARD); DialogMessage.showInformationDialog(""Auto-create Board - "" + SAMPLE_BOARD, SAMPLE_BOARD_DIALOG); }"
215,"<START> public SavedAttachment(String name, long revpos, long seq, byte[] key, String type, File file) { <END> this.name = name; this.revpos = revpos; this.seq = seq; this.key = key; this.type = type; this.file = file; }","long enough tempted a small Builder, pretty easy switch revpos seq accident in Java's world of unnamed arguments","protected SavedAttachment(String name, long revpos, long seq, byte[] key, String type, File file) { this.name = name; this.revpos = revpos; this.seq = seq; this.key = key; this.type = type; this.file = file; }"
216,@Override public void draw(Canvas canvas) { if (!animating) { image.draw(canvas); } else { if (placeholder != null) { placeholder.draw(canvas); } float normalized = (SystemClock.uptimeMillis() - startTimeMillis) / FADE_DURATION; int alpha = (int) (0xFF * normalized); if (normalized >= 1f) { animating = false; placeholder = null; image.setAlpha(0xFF); image.draw(canvas); } else { image.setAlpha(alpha); <START> image.draw(canvas); <END> invalidateSelf(); } } if (debugging) { drawDebugIndicator(canvas); } },need reset alpha here? Drawables share a global state,@Override public void draw(Canvas canvas) { if (!animating) { image.draw(canvas); } else { if (placeholder != null) { placeholder.draw(canvas); } float normalized = (SystemClock.uptimeMillis() - startTimeMillis) / FADE_DURATION; int alpha = (int) (0xFF * normalized); if (normalized >= 1f) { animating = false; placeholder = null; image.draw(canvas); } else { image.setAlpha(alpha); image.draw(canvas); image.setAlpha(0xFF); invalidateSelf(); } } if (debugging) { drawDebugIndicator(canvas); } }
217,"private boolean prereqSatisfied(String cdnURL) throws Exception { <START> for (String namenode: props.getList(""other_namenodes"")) { <END> if (removeTrailingSlash(namenode).equals(cdnURL)) { return true; } } return false; }",define this property name in 'VoldemortBuildAndPushJob' other cdn related properties? this is important execute distcp job,private boolean prereqSatisfied(String cdnURL) throws Exception { for (String namenode: props.getList(OTHER_NAMENODES)) { if (removeTrailingSlash(namenode).equals(cdnURL)) { return true; } } return false; }
218,"private static SliceHeader internalRead(int major, InputStream inputStream) throws IOException { final int sequenceId = ITF8.readUnsignedITF8(inputStream); final int alignmentStart = ITF8.readUnsignedITF8(inputStream); final int alignmentSpan = ITF8.readUnsignedITF8(inputStream); final int recordCount = ITF8.readUnsignedITF8(inputStream); final long globalRecordCounter = LTF8.readUnsignedLTF8(inputStream); final int blockCount = ITF8.readUnsignedITF8(inputStream); final int[] contentIDs = CramIntArray.array(inputStream); final int embeddedRefBlockContentID = ITF8.readUnsignedITF8(inputStream); <START> final byte[] referenceMD5s = new byte[MD5_LEN]; <END> InputStreamUtils.readFully(inputStream, referenceMD5s, 0, MD5_LEN); final byte[] tagBytes = InputStreamUtils.readFully(inputStream); final SAMBinaryTagAndValue tags = (major >= CramVersions.CRAM_v3.major) ? BinaryTagCodec.readTags(tagBytes, 0, tagBytes.length, ValidationStringency.DEFAULT_STRINGENCY) : null; return new SliceHeader(sequenceId, alignmentStart, alignmentSpan, recordCount, globalRecordCounter, blockCount, contentIDs, embeddedRefBlockContentID, referenceMD5s, tags); }",Nit: this is MD5 need plural,"private static SliceHeader internalRead(int major, InputStream inputStream) throws IOException { final int sequenceId = ITF8.readUnsignedITF8(inputStream); final int alignmentStart = ITF8.readUnsignedITF8(inputStream); final int alignmentSpan = ITF8.readUnsignedITF8(inputStream); final int recordCount = ITF8.readUnsignedITF8(inputStream); final long globalRecordCounter = LTF8.readUnsignedLTF8(inputStream); final int blockCount = ITF8.readUnsignedITF8(inputStream); final int[] contentIDs = CramIntArray.array(inputStream); final int embeddedRefBlockContentID = ITF8.readUnsignedITF8(inputStream); final byte[] referenceMD5 = new byte[MD5_LEN]; InputStreamUtils.readFully(inputStream, referenceMD5, 0, MD5_LEN); final byte[] tagBytes = InputStreamUtils.readFully(inputStream); final SAMBinaryTagAndValue sliceHeaderTags = (major >= CramVersions.CRAM_v3.major) ? BinaryTagCodec.readTags(tagBytes, 0, tagBytes.length, ValidationStringency.DEFAULT_STRINGENCY) : null; return new SliceHeader(sequenceId, alignmentStart, alignmentSpan, recordCount, globalRecordCounter, blockCount, contentIDs, embeddedRefBlockContentID, referenceMD5, sliceHeaderTags); }"
219,public void load(EngineLocalConfig config) throws ConfigurationException { File customExtensionsDir = config.getCustomExtensionsDir(); <START> File builtInExtensionsDir = config.getBuiltInExtensionsDir(); <END> load(customExtensionsDir); load(builtInExtensionsDir); activate(); },do need temp variables...,public void load(EngineLocalConfig config) throws ConfigurationException { for (File directory : config.getExtensionsDirectories()) { load(directory); } activate(); }
220,"public static List<String> normalize(List<URL> urls) throws IOException { HashMap<String, String> inoToFile = new HashMap<String, String>(); List<String> normalized = new ArrayList<String>(); for (URL url: urls) { Path path = Paths.get(url.toString()); BasicFileAttributes attr = null; <START> attr = Files.readAttributes(path, BasicFileAttributes.class); <END> Object fileKey = attr.fileKey(); String s = fileKey.toString(); String inode = s.substring(s.indexOf(""ino="") + 4, s.indexOf("")"")); inoToFile.put(inode, url.toString()); } for(String key : inoToFile.keySet()) { normalized.add(inoToFile.get(key)); } return normalized; }","understanding is API's java 7 APIs. Right supporting java 6 in project. This a hard stop, deprecate remove 6 7 support older hadoop versions removed, happen master API's used",public static Set<String> normalize(List<URL> urls) throws IOException { Set<String> normalized = new LinkedHashSet<String>(); for (URL url : urls) { File file = new File(url.toString()); paths.add(file.getCanonicalPath()); } return normalized; }
221,"protected StatsDMessage(String aspect, Message.Type type, T value, double sampleRate, String[] tags) { <START> super(aspect, type, value); <END> this.sampleRate = sampleRate; this.tags = tags; }","tags included in aspect, ? hash metrics in aggregator","protected StatsDMessage(String aspect, Message.Type type, T value, double sampleRate, String[] tags) { super(aspect, type, value, tags); this.sampleRate = sampleRate; }"
222,"public static Geometry unifyWindingOrder(Geometry geometry, boolean counterClockWise) { if (geometry == null) { return null; } if (geometry instanceof MultiPolygon) { return unifyWindingOrderForMultiPolygon((MultiPolygon) geometry, counterClockWise); } else if (geometry instanceof Polygon) { return unifyWindingOrderForPolyGon((Polygon) geometry, counterClockWise); } else if (geometry instanceof LinearRing) { return unifyWindingOrderForLinearRing((LinearRing) geometry, counterClockWise); } else if (geometry instanceof GeometryCollection <START> && geometry.getClass() == GeometryCollection.class) { <END> return unifyWindingOrderForGeometryCollection((GeometryCollection) geometry, counterClockWise); } else return geometry; }","If do class check omit instanceof check. I prefer if equals instead of ==, in OSGi class provided class loaders. this work in cases: GeometryCollection.class.equals(geometry.getClass())","public static Geometry unifyWindingOrder(Geometry geometry, boolean counterClockWise) { if (geometry == null) { return null; } if (geometry instanceof MultiPolygon) { return unifyWindingOrderForMultiPolygon((MultiPolygon) geometry, counterClockWise); } else if (geometry instanceof Polygon) { return unifyWindingOrderForPolyGon((Polygon) geometry, counterClockWise); } else if (geometry instanceof LinearRing) { return unifyWindingOrderForLinearRing((LinearRing) geometry, counterClockWise); } else if (GeometryCollection.class.equals(geometry.getClass())) { return unifyWindingOrderForGeometryCollection((GeometryCollection) geometry, counterClockWise); } else return geometry; }"
223,"public void validateRowGroupStatistics( OrcDataSourceId orcDataSourceId, long stripeOffset, int rowGroupIndex, List<ColumnStatistics> actual) throws OrcCorruptionException { List<RowGroupStatistics> rowGroups = rowGroupStatistics.get(stripeOffset); if (rowGroups == null) { throw new OrcCorruptionException(orcDataSourceId, ""Unexpected stripe at offset %s"", stripeOffset); } if (rowGroups.size() <= rowGroupIndex) { throw new OrcCorruptionException(orcDataSourceId, ""Unexpected row group %s in stripe at offset %s"", rowGroupIndex, stripeOffset); } RowGroupStatistics expectedRowGroup = rowGroups.get(rowGroupIndex); RowGroupStatistics actualRowGroup = new RowGroupStatistics(false, IntStream.range(1, actual.size()).boxed().collect(toImmutableMap(identity(), actual::get))); if (!expectedRowGroup.isLowMemoryMode()) { Map<Integer, ColumnStatistics> expectedByColumnIndex = expectedRowGroup.getColumnStatistics(); List<ColumnStatistics> expected = IntStream.range(1, actual.size()) .mapToObj(expectedByColumnIndex::get) .collect(toImmutableList()); actual = actual.subList(1, actual.size()); validateColumnStatisticsEquivalent(orcDataSourceId, ""Row group "" + rowGroupIndex + "" in stripe at offset "" + stripeOffset, actual, expected); } <START> if (expectedRowGroup.getHash() != actualRowGroup.getHash()) { <END> throw new OrcCorruptionException(orcDataSourceId, ""Checksum mismatch for row group %s in stripe at offset %s"", rowGroupIndex, stripeOffset); } }",if wanna put this check in isLowMemoryMode in case miss give false alert. For example (the metadata reader strips out string stats min/max = null causing hash result). affect production runs,"public void validateRowGroupStatistics( OrcDataSourceId orcDataSourceId, long stripeOffset, int rowGroupIndex, List<ColumnStatistics> actual) throws OrcCorruptionException { List<RowGroupStatistics> rowGroups = rowGroupStatistics.get(stripeOffset); if (rowGroups == null) { throw new OrcCorruptionException(orcDataSourceId, ""Unexpected stripe at offset %s"", stripeOffset); } if (rowGroups.size() <= rowGroupIndex) { throw new OrcCorruptionException(orcDataSourceId, ""Unexpected row group %s in stripe at offset %s"", rowGroupIndex, stripeOffset); } RowGroupStatistics expectedRowGroup = rowGroups.get(rowGroupIndex); RowGroupStatistics actualRowGroup = new RowGroupStatistics(BOTH, IntStream.range(1, actual.size()).boxed().collect(toImmutableMap(identity(), actual::get))); if (expectedRowGroup.getValidationMode() != HASHED) { Map<Integer, ColumnStatistics> expectedByColumnIndex = expectedRowGroup.getColumnStatistics(); List<ColumnStatistics> expected = IntStream.range(1, actual.size()) .mapToObj(expectedByColumnIndex::get) .collect(toImmutableList()); actual = actual.subList(1, actual.size()); validateColumnStatisticsEquivalent(orcDataSourceId, ""Row group "" + rowGroupIndex + "" in stripe at offset "" + stripeOffset, actual, expected); } if (expectedRowGroup.getValidationMode() != DETAILED) { if (expectedRowGroup.getHash() != actualRowGroup.getHash()) { throw new OrcCorruptionException(orcDataSourceId, ""Checksum mismatch for row group %s in stripe at offset %s"", rowGroupIndex, stripeOffset); } } }"
224,"public void setTopics(String topics) { <START> this.topics = topics.split("",""); <END> }",Figured this is new code.. fine semver check point,"public void setTopics(String topics) { this.topics = Iterables.toArray(Splitter.on(',').trimResults().omitEmptyStrings().split(topics), String.class); }"
225,"private TemporalUnitOffset getAllowableOffset() { if (SystemUtils.IS_OS_WINDOWS) { <START> return within(0, ChronoUnit.MICROS); <END> } else { return within(0, ChronoUnit.NANOS); } }","more lenient comparison window always, get rid of OS detection? intending test system clock all, OS-specific behavior avoided possible","private TemporalUnitOffset getAllowableOffset() { return within(0, ChronoUnit.MICROS); }"
226,"private void togglePostLike() { if (!isAdded() || !hasPost() || !NetworkUtils.checkConnection(getActivity())) { return; } boolean isAskingToLike = !mPost.isLikedByCurrentUser; ReaderIconCountView likeCount = (ReaderIconCountView) getView().findViewById(R.id.count_likes); likeCount.setSelected(isAskingToLike); ReaderAnim.animateLikeButton(likeCount.getImageView(), isAskingToLike); boolean success = ReaderPostActions.performLikeAction(mPost, isAskingToLike); if (!success) { likeCount.setSelected(!isAskingToLike); return; } <START> mPost = ReaderPostTable.getPost(mPost.blogId, mPost.postId, false); <END> refreshLikes(); refreshIconCounts(); if (isAskingToLike) { AnalyticsUtils.trackWithReaderPostDetails(AnalyticsTracker.Stat.READER_ARTICLE_LIKED, mPost); } else { AnalyticsUtils.trackWithReaderPostDetails(AnalyticsTracker.Stat.READER_ARTICLE_UNLIKED, mPost); } }","a big deal, curious this changed mPost.blogId mPost.postId","private void togglePostLike() { if (!isAdded() || !hasPost() || !NetworkUtils.checkConnection(getActivity())) { return; } boolean isAskingToLike = !mPost.isLikedByCurrentUser; ReaderIconCountView likeCount = (ReaderIconCountView) getView().findViewById(R.id.count_likes); likeCount.setSelected(isAskingToLike); ReaderAnim.animateLikeButton(likeCount.getImageView(), isAskingToLike); boolean success = ReaderPostActions.performLikeAction(mPost, isAskingToLike); if (!success) { likeCount.setSelected(!isAskingToLike); return; } mPost = ReaderPostTable.getBlogPost(mPost.blogId, mPost.postId, false); refreshLikes(); refreshIconCounts(); if (isAskingToLike) { AnalyticsUtils.trackWithReaderPostDetails(AnalyticsTracker.Stat.READER_ARTICLE_LIKED, mPost); } else { AnalyticsUtils.trackWithReaderPostDetails(AnalyticsTracker.Stat.READER_ARTICLE_UNLIKED, mPost); } }"
227,"public int write(ByteBuffer src) throws IOException { if (state == State.CLOSING) throw closingException(); if (state != State.READY) return 0; if (!flush(netWriteBuffer)) return 0; netWriteBuffer.clear(); SSLEngineResult wrapResult = sslEngine.wrap(src, netWriteBuffer); netWriteBuffer.flip(); if (wrapResult.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING && wrapResult.getStatus() == Status.OK) throw renegotiationException(); if (wrapResult.getStatus() == Status.OK) { <START> int written = wrapResult.bytesConsumed(); <END> flush(netWriteBuffer); return written; } else if (wrapResult.getStatus() == Status.BUFFER_OVERFLOW) { int currentNetWriteBufferSize = netWriteBufferSize(); netWriteBuffer.compact(); netWriteBuffer = Utils.ensureCapacity(netWriteBuffer, currentNetWriteBufferSize); netWriteBuffer.flip(); if (netWriteBuffer.limit() >= currentNetWriteBufferSize) throw new IllegalStateException(""SSL BUFFER_OVERFLOW when available data size ("" + netWriteBuffer.limit() + "") >= network buffer size ("" + currentNetWriteBufferSize + "")""); } else if (wrapResult.getStatus() == Status.BUFFER_UNDERFLOW) { throw new IllegalStateException(""SSL BUFFER_UNDERFLOW during write""); } else if (wrapResult.getStatus() == Status.CLOSED) { throw new EOFException(); } return 0; }","this point, clear if bytes src read. So, useful loop writes sslEngine flush() write bytes sockets return. This potentially avoid caller re-populating bytes fileChannel again","public int write(ByteBuffer src) throws IOException { if (state == State.CLOSING) throw closingException(); if (state != State.READY) return 0; int written = 0; while (flush(netWriteBuffer) && src.hasRemaining()) { netWriteBuffer.clear(); SSLEngineResult wrapResult = sslEngine.wrap(src, netWriteBuffer); netWriteBuffer.flip(); if (wrapResult.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING && wrapResult.getStatus() == Status.OK) throw renegotiationException(); if (wrapResult.getStatus() == Status.OK) { written += wrapResult.bytesConsumed(); } else if (wrapResult.getStatus() == Status.BUFFER_OVERFLOW) { netWriteBuffer = Utils.ensureCapacity(netWriteBuffer, netWriteBufferSize()); netWriteBuffer.position(netWriteBuffer.limit()); } else if (wrapResult.getStatus() == Status.BUFFER_UNDERFLOW) { throw new IllegalStateException(""SSL BUFFER_UNDERFLOW during write""); } else if (wrapResult.getStatus() == Status.CLOSED) { throw new EOFException(); } } return written; }"
228,"private JoinBridgeAndLifecycle<T> data(Lifespan lifespan) { checkArgument(!Lifespan.taskWide().equals(lifespan)); return map.computeIfAbsent(lifespan, span -> { T joinBridge = joinBridgeProvider.apply(span); return new JoinBridgeAndLifecycle<>(joinBridge, new JoinLifecycle(joinBridge, probeFactoryCount, outerFactoryCount)); }); <START> } <END>","nit: call method name data , instead of, say, joinBridgeAndLifecycle getJoinBridgeAndLifecycle ? :)","private JoinBridgeAndLifecycle<T> data(Lifespan lifespan) { checkArgument(!Lifespan.taskWide().equals(lifespan)); return joinBridgeMap.computeIfAbsent(lifespan, span -> { T joinBridge = joinBridgeProvider.apply(span); return new JoinBridgeAndLifecycle<>(joinBridge, new JoinLifecycle(joinBridge, probeFactoryCount, outerFactoryCount)); }); }"
229,public Optional<Relation> getModelClass() { final Relation relation = new Relation(); <START> return Optional.of(relation); <END> },return Optional.of(new Relation());,public Optional<Relation> getModelClass() { return Optional.of(new Relation()); }
230,"public boolean hasTemplatePath(TreeReference ref) { if (caseDbSpecTemplate != null) { return followsTemplateSpec(ref, caseDbSpecTemplate, 0); } else { Logger.log(""CaseDb Warning"", ""Using default hasTemplatePath implementation: reference resolution will break!""); <START> return super.hasTemplatePath(ref); <END> } }","Honestly thinking more sense literally inline template text static content here, permgen size of this file large. uncomfortable code path for loading this is static, introduces _huge_ unpredictable hits codebase for a complex parse (And will/can weird bad times), static init happen lazily instead? (Is fine for template parse static, I think), long is stateless threadsafe)","public boolean hasTemplatePath(TreeReference ref) { loadTemplateSpecLazily(); return followsTemplateSpec(ref, caseDbSpecTemplate, 0); }"
231,"public static void replaceIcons(Class iconsClass, String iconsRootPath) { for (Field field : iconsClass.getDeclaredFields()) { if (Modifier.isStatic(field.getModifiers())) { try { Object value = field.get(null); Class byClass = value.getClass(); if (byClass.getName().endsWith(""$ByClass"")) { setFieldValue(value, ""myCallerClass"", IconReplacer.class); setFieldValue(value, ""myWasComputed"", Boolean.FALSE); setFieldValue(value, ""myIcon"", null); } else if (byClass.getName().endsWith(""$CachedImageIcon"")) { String p = patchUrlIfNeeded(value, iconsRootPath); Icon newIcon = IconLoader.getIcon(p); <START> setFinalStatic(field, newIcon); <END> } } catch (IllegalAccessException e) { } catch (Exception e) { e.printStackTrace(); } } } for (Class subClass : iconsClass.getDeclaredClasses()) { replaceIcons(subClass, iconsRootPath); } }","A bit nit-picky, fix indentation give variable p a proper name","public static void replaceIcons(Class iconsClass, String iconsRootPath) { for (Field field : iconsClass.getDeclaredFields()) { if (Modifier.isStatic(field.getModifiers())) { try { Object value = field.get(null); Class byClass = value.getClass(); if (byClass.getName().endsWith(""$ByClass"")) { setFieldValue(value, ""myCallerClass"", IconReplacer.class); setFieldValue(value, ""myWasComputed"", Boolean.FALSE); setFieldValue(value, ""myIcon"", null); } else if (byClass.getName().endsWith(""$CachedImageIcon"")) { String newPath = patchUrlIfNeeded(value, iconsRootPath); if (newPath != null) { Icon newIcon = IconLoader.getIcon(newPath); setFinalStatic(field, newIcon); } } } catch (IllegalAccessException e) { } catch (Exception e) { } } } for (Class subClass : iconsClass.getDeclaredClasses()) { replaceIcons(subClass, iconsRootPath); } }"
232,"@Override protected void handleException(Throwable t) { super.handleException(t); server.abort(""Unrecoverable exception while closing "" + this.regionInfo.getRegionNameAsString(), t); <START> } <END>","new *Handler code, clear handle exceptions locally vs. handle this handleException method. I guess hooks for operating confines of a Runnable a thread pool somewhere","@Override protected void handleException(Throwable t) { server.abort(""Unrecoverable exception while closing "" + this.regionInfo.getRegionNameAsString(), t); }"
233,"public void handle(String input, Console console) { isInvincible = SolShip.isInvincible; if(hero.isDead()){ console.warn(""Cannot make invincible when dead""); return; } if(hero.isTranscendent()){ console.warn(""Cannot make invincible when transdencent""); return; } if(isInvincible == false){ console.warn(""Set player as invincible""); SolShip.setInvincible(); <START> }else if(isInvincible == true){ <END> console.warn(""Set player as non invincible""); SolShip.setNonInvincible(); } }",suggestion } else if (isInvincible == true) {,"public void handle(String input, Console console) { if (hero.isDead()) { console.warn(""Cannot make invincible when dead""); return; } if (hero.isTranscendent()) { console.warn(""Cannot make invincible when transdencent""); return; } if (!hero.isInvincible()) { console.info(""Set player as invincible""); hero.setInvincible(true); } else if (hero.isInvincible()) { console.info(""Set player as non invincible""); hero.setInvincible(false); } }"
234,"public void execute(DelegateExecution execution) throws Exception { final Pool pool = (Pool) execution.getVariable(CoreProcessVariables.POOL); @SuppressWarnings(""unchecked"") List<Machine> machines = (List<Machine>) execution.getVariable(CoreProcessVariables.MACHINES); checkNotNull(machines, ""expecting to find the list of machines as process variable""); <START> processEngine.getIdentityService().setAuthenticatedUserId(""kermit""); <END> List<String> processIds = Lists.newArrayList(); for (Machine machine : machines) { final String businessKey = String.format(""%s-%s-%s"", execution.getProcessBusinessKey(), type, machine.getExternalId()); ProcessInstance instance = processEngine.getRuntimeService().startProcessInstanceByKey( processKey, businessKey, ImmutableMap.<String, Object>of(CoreProcessVariables.POOL, pool, ""machine"", machine)); LOG.info(""Started background '"" + type + ""' process {} ({}) for machine {}"", new Object[]{businessKey, instance.getId(), machine.getExternalId()}); processIds.add(instance.getId()); } LOG.info(""Saving process IDs {} as {}"", processIds, resultVariable); execution.setVariable(resultVariable, processIds); }",I export this a constant - in places already. In future supply user name configuration,"public void execute(DelegateExecution execution) throws Exception { final Pool pool = (Pool) execution.getVariable(CoreProcessVariables.POOL); @SuppressWarnings(""unchecked"") List<Machine> machines = (List<Machine>) execution.getVariable(CoreProcessVariables.MACHINES); checkNotNull(machines, ""expecting to find the list of machines as process variable""); processEngine.getIdentityService().setAuthenticatedUserId(CoreConstants.ACTIVITI_EXPLORER_DEFAULT_USER); List<String> processIds = Lists.newArrayList(); for (Machine machine : machines) { final String businessKey = String.format(""%s-%s-%s"", execution.getProcessBusinessKey(), type, machine.getExternalId()); ProcessInstance instance = processEngine.getRuntimeService().startProcessInstanceByKey( processKey, businessKey, ImmutableMap.<String, Object>of(CoreProcessVariables.POOL, pool, ""machine"", machine)); LOG.info(""Started background '"" + type + ""' process {} ({}) for machine {}"", new Object[]{businessKey, instance.getId(), machine.getExternalId()}); processIds.add(instance.getId()); } LOG.info(""Saving process IDs {} as {}"", processIds, resultVariable); execution.setVariable(resultVariable, processIds); }"
235,"protected void label(Namespace namespace, Map<String, String> ensureLabels) throws InfrastructureException { if (ensureLabels.isEmpty()) { return; } Map<String, String> currentLabels = namespace.getMetadata().getLabels(); Map<String, String> newLabels = currentLabels != null ? new HashMap<>(currentLabels) : new HashMap<>(); if (newLabels.entrySet().containsAll(ensureLabels.entrySet())) { LOG.debug( ""Nothing to do, namespace [{}] already has all required labels."", namespace.getMetadata().getName()); return; } try { cheSAClientFactory .create() .namespaces() .createOrReplace( new NamespaceBuilder(namespace) .editMetadata() .addToLabels(ensureLabels) .endMetadata() .build()); } catch (KubernetesClientException kce) { if (kce.getCode() == 403) { LOG.warn( <START> ""Can't label the namespace due to lack of permissions. Grant to `che` ServiceAccount "" <END> + ""cluster-wide permissions to `get` and `update` the `namespaces` "" + ""(there might be `che-namespace-editor` ClusterRole prepared for this). "" + ""Or consider disabling the feature with setting "" + ""`che.infra.kubernetes.namespace.label=false`""); return; } throw new InfrastructureException(kce); } }","Grammar nazi suggests: > label namespace due lack of permissions. Grant cluster-wide permissions \get\ \update\ \namespaces\ \che\ service account (Che operator prepared a cluster role called \che-namespace-editor\ for this, depending configuration). Alternatively, consider disabling feature setting \che.infra.kubernetes.namepsace.label\ \false\","protected void label(Namespace namespace, Map<String, String> ensureLabels) throws InfrastructureException { if (ensureLabels.isEmpty()) { return; } Map<String, String> currentLabels = namespace.getMetadata().getLabels(); Map<String, String> newLabels = currentLabels != null ? new HashMap<>(currentLabels) : new HashMap<>(); if (newLabels.entrySet().containsAll(ensureLabels.entrySet())) { LOG.debug( ""Nothing to do, namespace [{}] already has all required labels."", namespace.getMetadata().getName()); return; } try { cheSAClientFactory .create() .namespaces() .createOrReplace( new NamespaceBuilder(namespace) .editMetadata() .addToLabels(ensureLabels) .endMetadata() .build()); } catch (KubernetesClientException kce) { if (kce.getCode() == 403) { LOG.warn( ""Can't label the namespace due to lack of permissions. Grant cluster-wide permissions "" + ""to `get` and `update` the `namespaces` to the `che` service account "" + ""(Che operator might have already prepared a cluster role called "" + ""`che-namespace-editor` for this, depending on its configuration). "" + ""Alternatively, consider disabling the feature by setting "" + ""`che.infra.kubernetes.namepsace.label` to `false`.""); return; } throw new InfrastructureException(kce); } }"
236,"private boolean updateGlusterHosts() { for (VDS vds : allForCluster) { HostStoragePoolParametersBase parameters = new HostStoragePoolParametersBase(vds); VdcReturnValueBase result = runInternalAction( VdcActionType.InitVdsOnUp, parameters, cloneContextAndDetachFromParent()); if (!result.getSucceeded()) { getReturnValue().setFault(result.getFault()); <START> return false; <END> } } return true; }",If host fails update stop updating other hosts well,"private void updateGlusterHosts() { for (VDS vds : allForCluster) { HostStoragePoolParametersBase parameters = new HostStoragePoolParametersBase(vds); runInternalAction( VdcActionType.InitVdsOnUp, parameters, cloneContextAndDetachFromParent()); } }"
237,public void afterJob(JobExecution jobExecution) { <START> if (!deleteFiles) { <END> return; } if (resources != null) { deleteResources(); } else { deleteFilePath(jobExecution); } },Do care if job completed successfully? assume want check status deleting..,"public void afterJob(JobExecution jobExecution) { if (!deleteFiles) { return; } if (jobExecution.getStatus().equals(BatchStatus.STOPPED) || jobExecution.getStatus().isUnsuccessful()) { logger.warn(""Job is stopped, or failed to complete successfully. File deletion will be skipped""); return; } if (resources != null) { deleteResources(); } else { deleteFilePath(jobExecution.getJobParameters().getString(ExpandedJobParametersConverter.ABSOLUTE_FILE_PATH)); } }"
238,"public static byte[] toByteArray(final HttpEntity entity) throws IOException { Args.notNull(entity, ""Entity""); try (final InputStream inStream = entity.getContent()) { if (inStream == null) { return null; } <START> final ByteArrayBuffer buffer = new ByteArrayBuffer(getCheckedContentLength(entity)); <END> final byte[] tmp = new byte[DEFAULT_BYTE_BUFFER_SIZE]; int l; while ((l = inStream.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toByteArray(); } }",if Content-Length is 500_000_000? create a buffer size,"public static byte[] toByteArray(final HttpEntity entity) throws IOException { Args.notNull(entity, ""Entity""); final int contentLength = toContentLength((int) Args.checkContentLength(entity)); try (final InputStream inStream = entity.getContent()) { if (inStream == null) { return null; } final ByteArrayBuffer buffer = new ByteArrayBuffer(contentLength); final byte[] tmp = new byte[DEFAULT_BYTE_BUFFER_SIZE]; int l; while ((l = inStream.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toByteArray(); } }"
239,"private String sendRequest(String url) throws IOException { BufferedReader in = null; StringBuilder b = new StringBuilder(); try{ URLConnection urlConnection = new URL(url).openConnection(); in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), Charset.forName(""utf-8""))); String inputLine = in.readLine(); while (inputLine != null) { b.append(inputLine).append(""\n""); inputLine = in.readLine(); } <START> }finally { <END> if(in != null){ try{ in.close(); }catch (IOException e){ log.error(""Error occurred while closing BufferedReader""); } } } return b.toString(); }",space betweeen } finally,"private String sendRequest(String url) throws IOException { BufferedReader in = null; StringBuilder b = new StringBuilder(); try{ URLConnection urlConnection = new URL(url).openConnection(); in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), Charset.forName(""utf-8""))); String inputLine = in.readLine(); while (inputLine != null) { b.append(inputLine).append(""\n""); inputLine = in.readLine(); } } finally { IdentityIOStreamUtils.closeReader(in); } return b.toString(); }"
240,"public void start() { <START> System.out.println(""ServerSideSession Start""); <END> instruments.startSession(getSessionId(), application, device, capabilities); final int sessionTimeoutMillis = options.getSessionTimeoutMillis(); stopSessionTimer.schedule(new TimerTask() { @Override public void run() { log.warning(""forcing stop session that has been running for "" + sessionTimeoutMillis / 1000 + "" seconds""); hardForceStop(); } }, sessionTimeoutMillis); URL url = null; try { url = new URL(""http://localhost:"" + driver.getHostInfo().getPort() + ""/wd/hub""); } catch (Exception e) { e.printStackTrace(); } nativeDriver = new ServerSideNativeDriver(url, new SessionId(instruments.getSessionId())); if (""Safari"".equals(capabilities.getBundleName())) { setMode(WorkingMode.Web); getRemoteWebDriver().get(""about:blank""); } }",Drop logging line,"public void start() { instruments.startSession(getSessionId(), application, device, capabilities); final int sessionTimeoutMillis = options.getSessionTimeoutMillis(); stopSessionTimer.schedule(new TimerTask() { @Override public void run() { log.warning(""forcing stop session that has been running for "" + sessionTimeoutMillis / 1000 + "" seconds""); hardForceStop(); } }, sessionTimeoutMillis); URL url = null; try { url = new URL(""http://localhost:"" + driver.getHostInfo().getPort() + ""/wd/hub""); } catch (Exception e) { e.printStackTrace(); } nativeDriver = new ServerSideNativeDriver(url, new SessionId(instruments.getSessionId())); if (""Safari"".equals(capabilities.getBundleName())) { setMode(WorkingMode.Web); getRemoteWebDriver().get(""about:blank""); } }"
241,public NodeMaskingFigure(IFigure decorated) { this.decorated = decorated; setLayoutManager(new XYLayout()); setOpaque(true); setFill(true); setOutline(false); IGraphicalEditPart backgroundPart = getDecoratedInterestingParent(getEditPart()); if (backgroundPart instanceof ShapeNodeEditPart) { <START> setBackgroundColor(((IFigure) backgroundPart.getFigure().getChildren().get(0)).getBackgroundColor()); <END> } else { setBackgroundColor(backgroundPart.getFigure().getBackgroundColor()); } setAlpha(255); },I this White for a reason..,public NodeMaskingFigure(IFigure decorated) { this.decorated = decorated; setLayoutManager(new XYLayout()); setOpaque(true); setFill(true); setOutline(false); IGraphicalEditPart backgroundPart = getDecoratedInterestingParent(getEditPart()); setBackgroundColor(getBackgroundColor(backgroundPart)); setAlpha(255); }
242,"public JavaLanguageModule() { super(NAME, null, TERSE_NAME, JavaRuleChainVisitor.class, ""java""); addVersion(""1.3"", new JavaLanguageHandler(3), false); addVersion(""1.4"", new JavaLanguageHandler(4), false); addVersion(""1.5"", new JavaLanguageHandler(5), false); addVersion(""1.6"", new JavaLanguageHandler(6), false); addVersion(""1.7"", new JavaLanguageHandler(7), false); addVersion(""1.8"", new JavaLanguageHandler(8), false); addVersion(""9"", new JavaLanguageHandler(9), false); addVersion(""10"", new JavaLanguageHandler(10), false); addVersion(""11"", new JavaLanguageHandler(11), false); <START> addVersion(""12"", new JavaLanguageHandler(12), false); <END> addVersion(""13"", new JavaLanguageHandler(13), true); }","anymore point of supporting preview features is, if drop support for minor version. 1. instability is expected, advertise preview feature support broken anytime (and display a warning) 2. support preview features 3. continue supporting preview version next major release. I I side option here. complex continue supporting Java 12 preview. Besides, advertised dropping Java 12 preview support this kind of sudden. If continue supporting preview features, sense separate language versions for preview versions, because: * Rules written for preview features apply non-preview version. For example, write a rule detect string concatenation replaced a text block - this irrelevant preview enabled. This is problem LanguageVersions supposed tackle. * a language version, determine running in preview mode *seeing* a preview feature used, making warning of option 1 unreliable","public JavaLanguageModule() { super(NAME, null, TERSE_NAME, JavaRuleChainVisitor.class, ""java""); addVersion(""1.3"", new JavaLanguageHandler(3), false); addVersion(""1.4"", new JavaLanguageHandler(4), false); addVersion(""1.5"", new JavaLanguageHandler(5), false); addVersion(""1.6"", new JavaLanguageHandler(6), false); addVersion(""1.7"", new JavaLanguageHandler(7), false); addVersion(""1.8"", new JavaLanguageHandler(8), false); addVersion(""9"", new JavaLanguageHandler(9), false); addVersion(""10"", new JavaLanguageHandler(10), false); addVersion(""11"", new JavaLanguageHandler(11), false); addVersion(""12"", new JavaLanguageHandler(12), false); addVersion(""12-preview"", new JavaLanguageHandler(12, true), false); addVersion(""13"", new JavaLanguageHandler(13), true); addVersion(""13-preview"", new JavaLanguageHandler(13, true), false); }"
243,public EventListWriter(AnnotationRegistry<Event> annotationRegistry) { <START> this.annotationRegistry = annotationRegistry; <END> },checkNotNull constructor params Ditto for other constructors,public EventListWriter(AnnotationRegistry<Event> annotationRegistry) { this.annotationRegistry = checkNotNull(annotationRegistry); }
244,"private void validateStopDatetime(Visit visit, Visit otherVisit, Errors errors) { if (visit.getStopDatetime() != null && otherVisit.getStartDatetime() != null && otherVisit.getStopDatetime() != null && visit.getStopDatetime().after(otherVisit.getStartDatetime()) && visit.getStopDatetime().before(otherVisit.getStopDatetime())) { errors.rejectValue(""stopDatetime"", ""Visit.stopDateCannotFallIntoAnotherVisitOfTheSamePatient"", ""This visit has a stop date that falls into another visit of the same patient.""); } if (visit.getStartDatetime() != null && visit.getStopDatetime() != null && otherVisit.getStartDatetime() != null && otherVisit.getStopDatetime() != null && visit.getStartDatetime().before(otherVisit.getStartDatetime()) && visit.getStopDatetime().after(otherVisit.getStopDatetime())) { <START> String messageBuilder = ""This visit contains another visit of the same patient, "" <END> + ""i.e. its start date is before the start date of the other visit "" + ""and its stop date is after the stop date of the other visit.""; errors.rejectValue(""stopDatetime"", ""Visit.visitCannotContainAnotherVisitOfTheSamePatient"", messageBuilder); } }",variable name remain messageBuilder,"private void validateStopDatetime(Visit visit, Visit otherVisit, Errors errors) { if (visit.getStopDatetime() != null && otherVisit.getStartDatetime() != null && otherVisit.getStopDatetime() != null && visit.getStopDatetime().after(otherVisit.getStartDatetime()) && visit.getStopDatetime().before(otherVisit.getStopDatetime())) { errors.rejectValue(""stopDatetime"", ""Visit.stopDateCannotFallIntoAnotherVisitOfTheSamePatient"", ""This visit has a stop date that falls into another visit of the same patient.""); } if (visit.getStartDatetime() != null && visit.getStopDatetime() != null && otherVisit.getStartDatetime() != null && otherVisit.getStopDatetime() != null && visit.getStartDatetime().before(otherVisit.getStartDatetime()) && visit.getStopDatetime().after(otherVisit.getStopDatetime())) { String message = ""This visit contains another visit of the same patient, "" + ""i.e. its start date is before the start date of the other visit "" + ""and its stop date is after the stop date of the other visit.""; errors.rejectValue(""stopDatetime"", ""Visit.visitCannotContainAnotherVisitOfTheSamePatient"", message); } }"
245,"public void createActions(IComparisonScope scope, Comparison comparison) { if (menuManager.isEmpty()) { IDifferenceFilter.Registry registry = EMFCompareRCPUIPlugin.getDefault() .getFilterActionRegistry(); Collection<IDifferenceFilter> filters = registry.getFilters(scope, comparison); for (IDifferenceFilter filter : filters) { FilterAction action = new FilterAction(filter.getLabel(), structureMergeViewerFilter, filter); if (filter.defaultSelected()) { action.setChecked(true); } menuManager.add(action); } <START> structureMergeViewerFilter.addFilters(filters); <END> } }",add filters defaultSelected? build a temporary list filters added..,"public void createActions(IComparisonScope scope, Comparison comparison) { if (menuManager.isEmpty()) { IDifferenceFilter.Registry registry = EMFCompareRCPUIPlugin.getDefault() .getFilterActionRegistry(); Collection<IDifferenceFilter> filters = registry.getFilters(scope, comparison); Collection<IDifferenceFilter> filtersSelected = Lists.newArrayList(); for (IDifferenceFilter filter : filters) { FilterAction action = new FilterAction(filter.getLabel(), structureMergeViewerFilter, filter); if (filter.defaultSelected()) { action.setChecked(true); filtersSelected.add(filter); } menuManager.add(action); } structureMergeViewerFilter.addFilters(filtersSelected); } }"
246,"public String generateNewMachineUniqueName() { Object context = setup.peek(CloudLocationConfig.CALLER_CONTEXT); Entity entity = null; if (context instanceof Entity) entity = (Entity) context; String template = this.setup.get(MACHINE_NAME_TEMPLATE); if (!template.startsWith(""#ftl\n"")) <START> template = ""#ftl\n"" + template; <END> String processed; if (entity == null) processed = TemplateProcessor.processTemplateContents(template, this.setup.get(EXTRA_SUBSTITUTIONS)); else processed = TemplateProcessor.processTemplateContents(template, (EntityInternal)entity, this.setup.get(EXTRA_SUBSTITUTIONS)); return sanitize(Strings.getFragmentBetween(processed, ""#ftl\n"", null)).toLowerCase(); }","So, I miss this bit out","public String generateNewMachineUniqueName() { Object context = setup.peek(CloudLocationConfig.CALLER_CONTEXT); Entity entity = null; if (context instanceof Entity) { entity = (Entity) context; } String template = this.setup.get(MACHINE_NAME_TEMPLATE); String processed; if (entity == null) { processed = TemplateProcessor.processTemplateContents(template, this.setup.get(EXTRA_SUBSTITUTIONS)); } else { processed = TemplateProcessor.processTemplateContents(template, (EntityInternal)entity, this.setup.get(EXTRA_SUBSTITUTIONS)); } processed = Strings.removeFromStart(processed, ""#ftl\n""); return sanitize(processed); }"
247,"<START> public void simplifyScopedStoragePathTest() { <END> assertThat(FileUtils.simplifyScopedStoragePath(null), is(nullValue())); assertThat(FileUtils.simplifyScopedStoragePath(""""), is("""")); assertThat(FileUtils.simplifyScopedStoragePath(""blahblahblah""), is(""blahblahblah"")); assertThat(FileUtils.simplifyScopedStoragePath(""/storage/emulated/0/Android/data/org.odk.collect.android/files/layers""), is(""/sdcard/Android/data/org.odk.collect.android/files/layers"")); }",I is equivelant == alias of is(equalTo()). in future,"public void simplifyScopedStoragePathTest() { assertThat(FileUtils.simplifyScopedStoragePath(null), is(nullValue())); assertThat(FileUtils.simplifyScopedStoragePath(""""), is("""")); assertThat(FileUtils.simplifyScopedStoragePath(""blahblahblah""), is(""blahblahblah"")); assertThat(FileUtils.simplifyScopedStoragePath(""/storage/emulated/0/Android/data/org.odk.collect.android/files/layers""), is(""/sdcard/Android/data/org.odk.collect.android/files/layers"")); assertThat(FileUtils.simplifyScopedStoragePath(""/storage/emulated/0/Android/data/org.odk.collect.android/files/layers/countries/countries-raster.mbtiles""), is(""/sdcard/Android/data/org.odk.collect.android/files/layers/countries/countries-raster.mbtiles"")); }"
248,"public void test_parallelPrefix$D() { Random rand = new Random(0); double[] list = new double[1000]; for(int i = 0; i < list.length; ++i) { list[i] = rand.nextDouble() <START> % 1000; END> } double[] seqResult = list.clone(); for(int i = 0; i < seqResult.length - 1; ++i) { seqResult[i + 1] += seqResult[i]; } Arrays.parallelPrefix(list, (x, y) -> x + y); int[] listInInt = Arrays.stream(list).mapToInt(x -> (int) x).toArray(); int[] seqResultInInt = Arrays.stream(seqResult).mapToInt(x -> (int) x).toArray(); assertTrue(Arrays.equals(seqResultInInt, listInInt)); try { Arrays.parallelPrefix(list, null); fail(); } catch (NullPointerException expected) { } try { Arrays.parallelPrefix((double[]) null, (x, y) -> x + y); fail(); } catch (NullPointerException expected) { } }","remove, nextDouble is in [0,1) range","public void test_setAll$D() { double[] list = new double[3]; list[0] = 0.0d; list[1] = 1.0d; list[2] = 2.0d; Arrays.setAll(list, x -> x + 0.5); assertEquals(0.5d, list[0]); assertEquals(1.5d, list[1]); assertEquals(2.5d, list[2]); try { Arrays.setAll(list, null); fail(); } catch (NullPointerException expected) { } try { Arrays.setAll((double[]) null, x -> x + 0.5); fail(); } catch (NullPointerException expected) { } }"
249,"private InputStream generateStream() { final Ds3ObjectList objects = new Ds3ObjectList(); objects.setObjects(this.ds3Objects); objects.setPriority(this.priority); objects.setWriteOptimization(this.writeOptimization); objects.setChunkClientProcessingOrderGuarantee(this.chunkOrdering); final StringBuilder xmlOutputBuilder = new StringBuilder(); <START> if (this.getCommand() == BulkCommand.GET) { <END> xmlOutputBuilder.append(XmlOutput.toXml(objects, true)); } else { xmlOutputBuilder.append(XmlOutput.toXml(objects, false)); } final byte[] stringBytes = xmlOutputBuilder.toString().getBytes(); this.size = stringBytes.length; return new ByteArrayInputStream(stringBytes); }",Is this right logic? care bulk PUT. want add filter for request besides bulk put. invert this logic,"private InputStream generateStream() { final Ds3ObjectList objects = new Ds3ObjectList(); objects.setObjects(this.ds3Objects); objects.setPriority(this.priority); objects.setWriteOptimization(this.writeOptimization); objects.setChunkClientProcessingOrderGuarantee(this.chunkOrdering); final StringBuilder xmlOutputBuilder = new StringBuilder(); if (this.getCommand() == BulkCommand.PUT) { xmlOutputBuilder.append(XmlOutput.toXml(objects, true)); } else { xmlOutputBuilder.append(XmlOutput.toXml(objects, false)); } final byte[] stringBytes = xmlOutputBuilder.toString().getBytes(); this.size = stringBytes.length; return new ByteArrayInputStream(stringBytes); }"
250,"public synchronized boolean doTerminate() { Collection<ImmutableWorkerInfo> workers = runner.getWorkers(); Collection<? extends TaskRunnerWorkItem> pendingTasks = runner.getPendingTasks(); final DefaultWorkerBehaviorConfig workerConfig = ProvisioningUtil.getDefaultWorkerBehaviorConfig( workerConfigRef, ""terminate"" ); if (workerConfig == null) { log.info(""No worker config found. Skip terminating.""); return false; } boolean didTerminate = false; WorkerCategorySpec workerCategorySpec = ProvisioningUtil.getWorkerCategorySpec(workerConfig); Map<String, List<TaskRunnerWorkItem>> pendingTasksByCategories = groupTasksByCategories( pendingTasks, runner, workerCategorySpec ); Map<String, List<ImmutableWorkerInfo>> workersByCategories = ProvisioningUtil.getWorkersByCategories(workers); Set<String> allCategories = workersByCategories.keySet(); log.debug( ""Workers of %d categories: %s"", workersByCategories.size(), allCategories ); Map<String, AutoScaler> autoscalersByCategory = ProvisioningUtil.mapAutoscalerByCategory(workerConfig.getAutoScalers()); for (String category : allCategories) { AutoScaler categoryAutoscaler = ProvisioningUtil.getAutoscalerByCategory(category, autoscalersByCategory); if (categoryAutoscaler == null) { log.error(""No autoScaler available, cannot execute doTerminate for workers of category %s"", category); continue; } category = ProvisioningUtil.getAutoscalerCategory(categoryAutoscaler); List<ImmutableWorkerInfo> categoryWorkers = workersByCategories.getOrDefault(category, Collections.emptyList()); <START> currentlyProvisioningMap.putIfAbsent(category, new HashSet<>()); Set<String> currentlyProvisioning = this.currentlyProvisioningMap.get(category); currentlyTerminatingMap.putIfAbsent(category, new HashSet<>()); Set<String> currentlyTerminating = this.currentlyTerminatingMap.get(category); <END> List<? extends TaskRunnerWorkItem> categoryPendingTasks = pendingTasksByCategories.getOrDefault( category, Collections.emptyList() ); didTerminate = doTerminate( category, categoryWorkers, currentlyProvisioning, currentlyTerminating, categoryAutoscaler, categoryPendingTasks ) || didTerminate; } return didTerminate; }",nit: HashSet instantiation,"public synchronized boolean doTerminate() { Collection<ImmutableWorkerInfo> workers = runner.getWorkers(); Collection<? extends TaskRunnerWorkItem> pendingTasks = runner.getPendingTasks(); final DefaultWorkerBehaviorConfig workerConfig = ProvisioningUtil.getDefaultWorkerBehaviorConfig( workerConfigRef, ""terminate"" ); if (workerConfig == null) { log.info(""No worker config found. Skip terminating.""); return false; } boolean didTerminate = false; WorkerCategorySpec workerCategorySpec = ProvisioningUtil.getWorkerCategorySpec(workerConfig); Map<String, List<TaskRunnerWorkItem>> pendingTasksByCategories = groupTasksByCategories( pendingTasks, runner, workerCategorySpec ); Map<String, List<ImmutableWorkerInfo>> workersByCategories = ProvisioningUtil.getWorkersByCategories(workers); Set<String> allCategories = workersByCategories.keySet(); log.debug( ""Workers of %d categories: %s"", workersByCategories.size(), allCategories ); Map<String, AutoScaler> autoscalersByCategory = ProvisioningUtil.mapAutoscalerByCategory(workerConfig.getAutoScalers()); for (String category : allCategories) { AutoScaler categoryAutoscaler = ProvisioningUtil.getAutoscalerByCategory(category, autoscalersByCategory); if (categoryAutoscaler == null) { log.error(""No autoScaler available, cannot execute doTerminate for workers of category %s"", category); continue; } category = ProvisioningUtil.getAutoscalerCategory(categoryAutoscaler); List<ImmutableWorkerInfo> categoryWorkers = workersByCategories.getOrDefault(category, Collections.emptyList()); Set<String> currentlyProvisioning = this.currentlyProvisioningMap.computeIfAbsent( category, ignored -> new HashSet<>() ); Set<String> currentlyTerminating = this.currentlyTerminatingMap.computeIfAbsent( category, ignored -> new HashSet<>() ); List<? extends TaskRunnerWorkItem> categoryPendingTasks = pendingTasksByCategories.getOrDefault( category, Collections.emptyList() ); didTerminate = doTerminate( category, categoryWorkers, currentlyProvisioning, currentlyTerminating, categoryAutoscaler, categoryPendingTasks ) || didTerminate; } return didTerminate; }"
251,"public QuotaViolationException(MetricName metricName, double value, double bound) { <START> super(metricName + "" violated quota.""); <END> this.metricName = metricName; this.value = value; this.bound = bound; }","I want string computation lazy, lose info. do overriding toString","public QuotaViolationException(MetricName metricName, double value, double bound) { this.metricName = metricName; this.value = value; this.bound = bound; }"
252,"private void processPropertiesXml(File file, AppInfo app) { DTConfiguration config = new DTConfiguration(); try { config.loadFile(file); for (Map.Entry<String, ValueEntry> entry : config.getMap().entrySet()) { String key = entry.getKey(); ValueEntry valueEntry = entry.getValue(); <START> LOG.info(""Properties: {} {} {}"", key, valueEntry.value, valueEntry.description); <END> if (valueEntry.value == null) { if (app == null) { requiredProperties.add(key); } else { app.requiredProperties.add(key); } } else { if (app == null) { defaultProperties.put(key, valueEntry); } else { app.requiredProperties.remove(key); app.defaultProperties.put(key, valueEntry); } } } } catch (Exception ex) { LOG.warn(""Ignoring META_INF/properties.xml because of error"", ex); } }",LOG.debug,"private void processPropertiesXml(File file, AppInfo app) { DTConfiguration config = new DTConfiguration(); try { config.loadFile(file); for (Map.Entry<String, String> entry : config) { String key = entry.getKey(); String value = entry.getValue(); if (value == null) { if (app == null) { requiredProperties.add(key); } else { app.requiredProperties.add(key); } } else { String description = key.contains("".attr."") ? null : config.getDescription(key); PropertyInfo propertyInfo = new PropertyInfo(value, description); if (app == null) { defaultProperties.put(key, propertyInfo); } else { app.requiredProperties.remove(key); app.defaultProperties.put(key, propertyInfo); } } } } catch (Exception ex) { LOG.warn(""Ignoring META_INF/properties.xml because of error"", ex); } }"
253,public String getQualifiedName() { return <START> StyleResolver.getQualifiedItemName(mySelectedValue.myValue); <END> },"do call getSelectedValue() in other places, code instead",public String getQualifiedName() { return StyleResolver.getQualifiedItemName(getSelectedValue()); }
254,"private Set<SignatureAlgorithm> fetchSignatureAlgorithms() { if (StringUtils.isEmpty(jwkSetUri)) { return Collections.emptySet(); } try { <START> return parseAlgorithms(JWKSet.load(toURL(jwkSetUri), 5000, 5000, 0)); <END> } catch (Exception ex) { log.error(""Failed to load Signature Algorithms from remote JWK source.""); return Collections.emptySet(); } }",please JWKSource retrieve JWKs. allow a JWKMatcher removes some of validation in parseAlgorithms,"private Set<SignatureAlgorithm> fetchSignatureAlgorithms() { try { return parseAlgorithms(JWKSet.load(toURL(jwkSetUri), 5000, 5000, 0)); } catch (Exception ex) { throw new IllegalArgumentException(""Failed to load Signature Algorithms from remote JWK source."", ex); } }"
255,"private static ClientRegistration.Builder getBuilder(String issuer, Supplier<ClientRegistration.Builder>... suppliers) { String errorMessage = ""Unable to resolve Configuration with the provided Issuer of \"""" + issuer + ""\""""; for (Supplier<ClientRegistration.Builder> supplier : suppliers) { try { <START> ClientRegistration.Builder builder = supplier.get(); <END> return builder; } catch (HttpClientErrorException e) { if (!e.getStatusCode().is4xxClientError()) { throw e; } } catch (IllegalArgumentException | IllegalStateException e) { throw e; } catch (RuntimeException e) { throw new IllegalArgumentException(errorMessage, e); } } throw new IllegalArgumentException(errorMessage); }",simplify this a bit: suggestion return supplier.get();,"private static ClientRegistration.Builder getBuilder(String issuer, Supplier<ClientRegistration.Builder>... suppliers) { String errorMessage = ""Unable to resolve Configuration with the provided Issuer of \"""" + issuer + ""\""""; for (Supplier<ClientRegistration.Builder> supplier : suppliers) { try { return supplier.get(); } catch (HttpClientErrorException e) { if (!e.getStatusCode().is4xxClientError()) { throw e; } } catch (IllegalArgumentException | IllegalStateException e) { throw e; } catch (RuntimeException e) { throw new IllegalArgumentException(errorMessage, e); } } throw new IllegalArgumentException(errorMessage); }"
256,"void maybeReadPayload(ChannelHandlerContext ctx) { if (pending.readableBytes() < nextFrameSize) { return; } ByteBuf payload = ctx.alloc().buffer(nextFrameSize); pending.readBytes(payload, nextFrameSize); state = ReadState.HEADER; HttpRequest request = HttpRequest.of( THRIFT_HEADERS.toMutable(), new ByteBufHttpData(payload, true)); ServiceRequestContext requestContext = ServiceRequestContextBuilder.of(request) .service(scribeService) .build(); final HttpResponse response; try { response = scribeService.serve(requestContext, request); } catch (Exception e) { logger.warn(""Unexpected exception servicing thrift request. "" + ""This usually indicates a bug in armeria's thrift implementation."", e); exceptionCaught(ctx, e); return; } response.aggregateWithPooledObjects(ctx.executor(), ctx.alloc()).handle((msg, t) -> { if (t != null) { logger.warn(""Unexpected exception reading thrift response. "" <START> + ""This usually indicates a bug in armeria's thrift implementation."", t); <END> exceptionCaught(ctx, t); return null; } HttpData content = msg.content(); final ByteBuf returned = ctx.alloc().buffer(msg.content().length() + 4); returned.writeInt(msg.content().length()); if (content instanceof ByteBufHolder) { ByteBuf buf = ((ByteBufHolder) content).content(); try { returned.writeBytes(((ByteBufHolder) content).content()); } finally { buf.release(); } } else { returned.writeBytes(content.array(), content.offset(), content.length()); } ctx.writeAndFlush(returned); return null; }); }","Hmm, really? I aggregation fail other cases OOME","void maybeReadPayload(ChannelHandlerContext ctx) { if (pending.readableBytes() < nextFrameSize) { return; } ByteBuf payload = ctx.alloc().buffer(nextFrameSize); pending.readBytes(payload, nextFrameSize); pending.discardSomeReadBytes(); state = ReadState.HEADER; HttpRequest request = HttpRequest.of( THRIFT_HEADERS.toMutable(), new ByteBufHttpData(payload, true)); ServiceRequestContextBuilder requestContextBuilder = ServiceRequestContextBuilder.of(request) .service(scribeService) .alloc(ctx.alloc()); if (ctx.executor() instanceof EventLoop) { requestContextBuilder.eventLoop((EventLoop) ctx.executor()); } ServiceRequestContext requestContext = requestContextBuilder.build(); final HttpResponse response; try (SafeCloseable unused = requestContext.push()){ response = scribeService.serve(requestContext, request); } catch (Exception e) { exceptionCaught(ctx, e); return; } int responseIndex = nextResponseIndex++; response.aggregateWithPooledObjects(ctx.executor(), ctx.alloc()).handle((msg, t) -> { if (t != null) { exceptionCaught(ctx, t); return null; } HttpData content = msg.content(); ByteBuf returned = ctx.alloc().buffer(content.length() + 4); returned.writeInt(content.length()); if (content instanceof ByteBufHolder) { ByteBuf buf = ((ByteBufHolder) content).content(); try { returned.writeBytes(((ByteBufHolder) content).content()); } finally { buf.release(); } } else { returned.writeBytes(content.array(), content.offset(), content.length()); } if (responseIndex == previouslySentResponseIndex + 1) { ctx.writeAndFlush(returned); previouslySentResponseIndex++; flushResponses(ctx); } else { pendingResponses.put(responseIndex, returned); } return null; }); }"
257,"public static PageViewAvroRecord buildPageViewRecord(PageView pageView) { PageViewAvroRecord record = new PageViewAvroRecord(); <START> record.put(0, pageView.userId); <END> record.put(1, pageView.country); record.put(2, pageView.pageId); return record; }",cleaner do record.userId = pageView.userId? for other fields below,public static PageViewAvroRecord buildPageViewRecord(PageView pageView) { PageViewAvroRecord record = new PageViewAvroRecord(); record.userId = pageView.userId; record.country = pageView.country; record.pageId = pageView.pageId; return record; }
258,"public <K, V> void send(final String topic, final K key, final V value, final Headers headers, final Long timestamp, final Serializer<K> keySerializer, final Serializer<V> valueSerializer, final StreamPartitioner<? super K, ? super V> partitioner) { <START> Integer partition = null; <END> if (partitioner != null) { final List<PartitionInfo> partitions = producer.partitionsFor(topic); if (partitions.size() > 0) { partition = partitioner.partition(topic, key, value, partitions.size()); } else { throw new StreamsException(""Could not get partition information for topic '"" + topic + ""' for task "" + taskId + "". This can happen if the topic does not exist.""); } } send(topic, key, value, headers, partition, timestamp, keySerializer, valueSerializer); }","nit: set final refactor as: final Integer partition; if (partitioner != null) { final List<PartitionInfo> partitions = producer.partitionsFor(topic); if (partitions.size() > 0) { partition = partitioner.partition(topic, key, value, partitions.size()); } else { throw new StreamsException(""Could get partition information for topic '"" + topic + ""' for task "" + taskId + "". This happen if topic exist.""); } } else { partition = null; }","public <K, V> void send(final String topic, final K key, final V value, final Headers headers, final Long timestamp, final Serializer<K> keySerializer, final Serializer<V> valueSerializer, final StreamPartitioner<? super K, ? super V> partitioner) { final Integer partition; if (partitioner != null) { final List<PartitionInfo> partitions = producer.partitionsFor(topic); if (partitions.size() > 0) { partition = partitioner.partition(topic, key, value, partitions.size()); } else { throw new StreamsException(""Could not get partition information for topic '"" + topic + ""' for task "" + taskId + "". This can happen if the topic does not exist.""); } } else { partition = null; } send(topic, key, value, headers, partition, timestamp, keySerializer, valueSerializer); }"
259,private boolean mkdir(Path path) throws IOException { String key = pathToKey(path); <START> adapter.createDirectory(key); <END> return true; },Lets return of apapter.createDirectory,private boolean mkdir(Path path) throws IOException { String key = pathToKey(path); return adapter.createDirectory(key); }
260,"<START> public static String getPreferredVideoUrlForDownloading(@NonNull VideoData video) { <END> String preferredVideoUrl = null; final VideoInfo preferredVideoInfo = video.encodedVideos.getPreferredVideoInfoForDownloading(); if (preferredVideoInfo == null || video.onlyOnWeb) { preferredVideoUrl = null; } else if (!videoHasFormat(preferredVideoInfo.url, VIDEO_FORMAT_M3U8)) { preferredVideoUrl = preferredVideoInfo.url; } if (TextUtils.isEmpty(preferredVideoUrl) && !new Config(MainApplication.instance()).isUsingVideoPipeline()) { for (String url : video.allSources) { if (VideoUtil.videoHasFormat(url, AppConstants.VIDEO_FORMAT_MP4)) { preferredVideoUrl = url; } } } return preferredVideoUrl; }","code more clean java /** * preferred video url for downloading a {@link VideoData} object. * * @param video Data of video preferred download url is needed. * @return download url of video, return null if unable find suitable url for downloading. */ @Nullable public static String getPreferredVideoUrlForDownloading(@NonNull VideoData video) { String preferredVideoUrl = null; final VideoInfo preferredVideoInfo = video.encodedVideos.getPreferredVideoInfoForDownloading(); if (preferredVideoInfo == null || TextUtils.isEmpty(preferredVideoInfo.url) || video.onlyOnWeb) { preferredVideoUrl = null; } else if (!videoHasFormat(preferredVideoInfo.url, VIDEO_FORMAT_M3U8)) { return preferredVideoInfo.url; } if (!new Config(MainApplication.instance()).isUsingVideoPipeline()) { /** * If preferred video url for downloading HLS format * {@link Config#USING_VIDEO_PIPELINE} feature flag is disabled, try find some .mp4 * format url {@link VideoData#allSources} urls consider for download. */ for (String url : video.allSources) { if (VideoUtil.videoHasFormat(url, AppConstants.VIDEO_FORMAT_MP4)) { preferredVideoUrl = url; } } } return preferredVideoUrl; }","public static String getPreferredVideoUrlForDownloading(@NonNull VideoData video) { String preferredVideoUrl = null; final VideoInfo preferredVideoInfo = video.encodedVideos.getPreferredVideoInfoForDownloading(); if (preferredVideoInfo != null && !TextUtils.isEmpty(preferredVideoInfo.url) && !video.onlyOnWeb && !videoHasFormat(preferredVideoInfo.url, VIDEO_FORMAT_M3U8)) { return preferredVideoInfo.url; } if (!new Config(MainApplication.instance()).isUsingVideoPipeline()) { for (String url : video.allSources) { if (VideoUtil.videoHasFormat(url, AppConstants.VIDEO_FORMAT_MP4)) { preferredVideoUrl = url; } } } return preferredVideoUrl; }"
261,"public void rewind() throws IOException { super.rewind(); for (int i=size-1;i>=0;i--) { File fi = getNumberedFileName(i); if (fi.exists()) { File next = getNumberedFileName(i+1); if (!next.delete()){ <START> throw new IOException(String.format(""Could not delete %s"", next.getAbsolutePath())); <END> } fi.renameTo(next); } } }",do this behaviour is right,public void rewind() throws IOException { super.rewind(); for (int i=size-1;i>=0;i--) { File fi = getNumberedFileName(i); if (fi.exists()) { File next = getNumberedFileName(i+1); next.delete(); fi.renameTo(next); } } }
262,"public FirebaseListAdapter(Activity activity, Class<T> modelClass, int modelLayout, Query ref) { mModelClass = modelClass; mLayout = modelLayout; mActivity = activity; mSnapshots = new FirebaseArray(ref); mSnapshots.setOnChangedListener(new FirebaseArray.OnChangedListener() { @Override public void onChanged(EventType type, int index, int oldIndex) { notifyDataSetChanged(); } @Override public void onCancelled(DatabaseError databaseError) { <START> FirebaseRecyclerAdapter.this.onCancelled(databaseError); <END> } }); }","I FirebaseListAdapter.this here, (rather FirebaseRecyclerAdapter.this)","public FirebaseListAdapter(Activity activity, Class<T> modelClass, int modelLayout, Query ref) { mModelClass = modelClass; mLayout = modelLayout; mActivity = activity; mSnapshots = new FirebaseArray(ref); mSnapshots.setOnChangedListener(new FirebaseArray.OnChangedListener() { @Override public void onChanged(EventType type, int index, int oldIndex) { notifyDataSetChanged(); } @Override public void onCancelled(DatabaseError databaseError) { FirebaseListAdapter.this.onCancelled(databaseError); } }); }"
263,"public boolean upload(FilePath workspace, String artifactIncludes, PrintStream log) { boolean result = true; if(workspace!=null) { for(String roomId : roomIds) { SlackFileRequest slackFileRequest = new SlackFileRequest( workspace, populatedToken, roomId, null, artifactIncludes); try { workspace.getChannel().callAsync(new SlackUploadFileRunner(log, Jenkins.get().proxy, slackFileRequest)).get(); } catch (IllegalStateException e) { logger.log(Level.WARNING, ""IllegalStateException"", e); result = false; } catch (InterruptedException e) { <START> logger.log(Level.WARNING, ""InterruptedException"", e); <END> result = false; } catch (ExecutionException e) { logger.log(Level.WARNING, ""ExecutionException"", e); result = false; } catch (IOException e) { logger.log(Level.WARNING, ""Error closing HttpClient"", e); result = false; } } } else { logger.log(Level.WARNING, ""Could not get workspace for current execution""); result = false; } return result; }","need log of separately, exception message / stacktrace is, collapse in catch block please","public boolean upload(FilePath workspace, String artifactIncludes, PrintStream log) { boolean result = true; if(workspace!=null) { for(String roomId : roomIds) { SlackFileRequest slackFileRequest = new SlackFileRequest( workspace, populatedToken, roomId, null, artifactIncludes); try { workspace.getChannel().callAsync(new SlackUploadFileRunner(log, Jenkins.get().proxy, slackFileRequest)).get(); } catch (IllegalStateException | InterruptedException e) { logger.log(Level.WARNING, ""Exception"", e); result = false; } catch (ExecutionException e) { logger.log(Level.WARNING, ""ExecutionException"", e); result = false; } catch (IOException e) { logger.log(Level.WARNING, ""Error closing HttpClient"", e); result = false; } } } else { logger.log(Level.WARNING, ""Could not get workspace for current execution""); result = false; } return result; }"
264,public static boolean isDemoUser() { try { User u = CommCareApplication._().getSession().getLoggedInUser(); return (User.TYPE_DEMO.equals(u.getUserType())); } catch (SessionUnavailableException e) { <START> return true; <END> } },session unavailable a demo user? if a SessionUnavailableException is thrown,public static boolean isDemoUser() { try { User u = CommCareApplication._().getSession().getLoggedInUser(); return (User.TYPE_DEMO.equals(u.getUserType())); } catch (SessionUnavailableException e) { return false; } }
265,"<START> @Test public void givenMultipleRequestsWhenResponseThenLog() throws InterruptedException { <END> AtomicInteger completedReqs = new AtomicInteger(0); OptionalInt optHttpsPort = testServer.getRunningHttpsPort(); String url; int port; if (optHttpsPort.isPresent()) { port = optHttpsPort.getAsInt(); url = ""https://localhost:"" + port; } else { port = testServer.getRunningHttpPort().getAsInt(); url = ""http://localhost:"" + port; } WSClient ws = play.test.WSTestClient.newClient(port); IntStream.range(0, 100).parallel().forEach(num -> ws.url(url) .setRequestFilter(new AhcCurlRequestLogger()) .addHeader(""key"", ""value"") .addQueryParameter(""num"", """" + num) .get() .thenAccept(r -> { log.debug(""Thread#"" + num + "" Request complete: Response code = "" + r.getStatus() + "" | Response: "" + r.getBody() + "" | Current Time:"" + System.currentTimeMillis()); completedReqs.incrementAndGet(); }) ); log.debug(""Waiting for requests to be completed. Current Time: "" + System.currentTimeMillis()); while (completedReqs.get() != 100) { Thread.sleep(100); } log.debug(""All requests have been completed. Exiting test.""); }",@Test annotation appears line test function,"public void givenMultipleRequestsWhenResponseThenLog() throws Exception { CountDownLatch latch = new CountDownLatch(100); WSClient ws = play.test.WSTestClient.newClient(port); IntStream.range(0, 100) .parallel() .forEach(num -> ws.url(url) .setRequestFilter(new AhcCurlRequestLogger()) .addHeader(""key"", ""value"") .addQueryParameter(""num"", """" + num) .get() .thenAccept(r -> { log.debug( ""Thread#"" + num + "" Request complete: Response code = "" + r.getStatus() + "" | Response: "" + r.getBody() + "" | Current Time:"" + System.currentTimeMillis()); latch.countDown(); }) ); log.debug( ""Waiting for requests to be completed. Current Time: "" + System.currentTimeMillis()); latch.await(5, TimeUnit.SECONDS ); assertEquals(0, latch.getCount()); log.debug(""All requests have been completed. Exiting test.""); }"
266,"public static boolean writeRecoveryJob(final RecoveryJob job) { try { final File file; if(job.getJobType() == BulkJobType.GET_BULK) { file = createGetFile(job.getId().toString()); } else { file = createPutFile(job.getId().toString()); } <START> try (BufferedWriter writer = com.google.common.io.Files.newWriter(file, Charset.forName(""utf-8""))) { <END> writer.write(JsonMapper.toJson(job)); } catch (final Exception inner) { throw inner; } return true; } catch (final IOException e) { LOG.error(""Could not create recovery file"", e); return false; } }",final,"public static boolean writeRecoveryJob(final RecoveryJob job) { try { final File file; if(job.getJobType() == BulkJobType.GET_BULK) { file = createGetFile(job.getId().toString()); } else { file = createPutFile(job.getId().toString()); } try (final BufferedWriter writer = com.google.common.io.Files.newWriter(file, Charset.forName(""utf-8""))) { writer.write(JsonMapper.toJson(job)); } catch (final Exception inner) { throw inner; } return true; } catch (final IOException e) { LOG.error(""Could not create recovery file"", e); return false; } }"
267,"public void setText (String string) { checkWidget(); if (string == null) error (SWT.ERROR_NULL_ARGUMENT); if ((style & SWT.SEPARATOR) != 0) return; if (text.equals (string)) return; super.setText (string); String accelString = """"; int index = string.indexOf ('\t'); if (index != -1) { boolean isRTL = (parent.style & SWT.RIGHT_TO_LEFT) != 0; accelString = (isRTL? """" : "" "") + string.substring (index+1, string.length()) + (isRTL? "" "" : """"); string = string.substring (0, index); } char [] chars = fixMnemonic (string); byte [] buffer = Converter.wcsToMbcs (null, chars, true); if (boxHandle == 0 && !OS.GTK3) { labelHandle = OS.gtk_bin_get_child (handle); } <START> if (labelHandle > 0 && OS.GTK_IS_LABEL (labelHandle)) { <END> OS.gtk_label_set_text_with_mnemonic (labelHandle, buffer); if (OS.GTK_IS_ACCEL_LABEL (labelHandle)) { if (OS.GTK3) { if (OS.GTK_VERSION >= OS.VERSION(3, 6, 0)) { MaskKeysym maskKeysym = getMaskKeysym(); if (maskKeysym != null) { OS.gtk_accel_label_set_accel_widget (labelHandle, handle); OS.gtk_accel_label_set_accel (labelHandle, maskKeysym.keysym, maskKeysym.mask); } } else { setAccelLabel (labelHandle, accelString); } } else { setAccelLabel (labelHandle, accelString); } OS.g_signal_emit_by_name(handle, OS.accel_closures_changed); } } }",Style: Y u change '!=' '>' :-/,"public void setText (String string) { checkWidget(); if (string == null) error (SWT.ERROR_NULL_ARGUMENT); if ((style & SWT.SEPARATOR) != 0) return; if (text.equals (string)) return; super.setText (string); String accelString = """"; int index = string.indexOf ('\t'); if (index != -1) { boolean isRTL = (parent.style & SWT.RIGHT_TO_LEFT) != 0; accelString = (isRTL? """" : "" "") + string.substring (index+1, string.length()) + (isRTL? "" "" : """"); string = string.substring (0, index); } char [] chars = fixMnemonic (string); byte [] buffer = Converter.wcsToMbcs (null, chars, true); if (boxHandle == 0 && !OS.GTK3) { labelHandle = OS.gtk_bin_get_child (handle); } if (labelHandle != 0 && OS.GTK_IS_LABEL (labelHandle)) { OS.gtk_label_set_text_with_mnemonic (labelHandle, buffer); if (OS.GTK_IS_ACCEL_LABEL (labelHandle)) { if (OS.GTK3) { if (OS.GTK_VERSION >= OS.VERSION(3, 6, 0)) { MaskKeysym maskKeysym = getMaskKeysym(); if (maskKeysym != null) { OS.gtk_accel_label_set_accel_widget (labelHandle, handle); OS.gtk_accel_label_set_accel (labelHandle, maskKeysym.keysym, maskKeysym.mask); } } else { setAccelLabel (labelHandle, accelString); } } else { setAccelLabel (labelHandle, accelString); } OS.g_signal_emit_by_name(handle, OS.accel_closures_changed); } } }"
268,"public void stop() { <START> executor.shutdown(); <END> super.stop(); setAttribute(Startable.SERVICE_UP, false); }","If calling shutdown() shutdownNow(), previously submitted tasks executed. Is wanted here? call executor.awaitTermination()? I suspect not; synchronization this call stop() blocking for other methods complete problems..","public void stop() { executor.shutdownNow(); super.stop(); setAttribute(Startable.SERVICE_UP, false); }"
269,<START> private boolean draftIsNotEmpty() { <END> if (mMessageContentView.getText().length() != 0) return true; if (!attachmentPresenter.createAttachmentList().isEmpty()) return true; if (mSubjectView.getText().length() != 0) return true; return false; },recipients signature fields checked,private boolean draftIsNotEmpty() { if (messageContentView.getText().length() != 0) { return true; } if (!attachmentPresenter.createAttachmentList().isEmpty()) { return true; } if (subjectView.getText().length() != 0) { return true; } if (!recipientPresenter.getToAddresses().isEmpty() || !recipientPresenter.getCcAddresses().isEmpty() || !recipientPresenter.getBccAddresses().isEmpty()) { return true; } return false; }
270,"public String getSearchTransformedNetwork(@ProjectIdentifier @PathVariable(""projectUnixName"") String projectUnixName, @RequestParam(""conceptId"") String conceptId, @CheckAccess @InjectProject IProject project, Model model) throws QuadrigaStorageException { String lemma = """"; String searchNodeLabel = """"; ConceptpowerReply reply = conceptpowerConnector.getById(conceptId); List<String> alternativeIdsForConcept = null; if (reply != null && reply.getConceptEntry().size() > 0) { searchNodeLabel = reply.getConceptEntry().get(0).getLemma(); lemma = reply.getConceptEntry().get(0).getDescription(); alternativeIdsForConcept = reply.getConceptEntry().get(0).getAlternativeIdList(); <START> } <END> if(alternativeIdsForConcept == null){ alternativeIdsForConcept = new ArrayList<String>(); } ITransformedNetwork transformedNetwork = transformationManager .getSearchTransformedNetwork(project.getProjectId(), conceptId, alternativeIdsForConcept, INetworkStatus.APPROVED); String json = null; if (transformedNetwork != null) { json = jsonCreator.getJson(transformedNetwork.getNodes(), transformedNetwork.getLinks()); } if (transformedNetwork == null || transformedNetwork.getNodes().size() == 0) { model.addAttribute(""isNetworkEmpty"", true); } model.addAttribute(""jsonstring"", json); model.addAttribute(""networkid"", ""\""\""""); model.addAttribute(""project"", project); model.addAttribute(""searchNodeLabel"", searchNodeLabel); model.addAttribute(""description"", lemma); model.addAttribute(""unixName"", projectUnixName); return ""sites/networks/searchednetwork""; }","concepts cached, a big deal if conceptconnector is called twice","public String getSearchTransformedNetwork(@ProjectIdentifier @PathVariable(""projectUnixName"") String projectUnixName, @RequestParam(""conceptId"") String conceptId, @CheckAccess @InjectProject IProject project, Model model) throws QuadrigaStorageException { String lemma = """"; String searchNodeLabel = """"; ConceptpowerReply reply = conceptpowerConnector.getById(conceptId); if (reply != null && reply.getConceptEntry().size() > 0) { searchNodeLabel = reply.getConceptEntry().get(0).getLemma(); lemma = reply.getConceptEntry().get(0).getDescription(); } ITransformedNetwork transformedNetwork = transformationManager .getSearchTransformedNetwork(project.getProjectId(), conceptId, INetworkStatus.APPROVED); String json = null; if (transformedNetwork != null) { json = jsonCreator.getJson(transformedNetwork.getNodes(), transformedNetwork.getLinks()); } if (transformedNetwork == null || transformedNetwork.getNodes().size() == 0) { model.addAttribute(""isNetworkEmpty"", true); } model.addAttribute(""jsonstring"", json); model.addAttribute(""networkid"", ""\""\""""); model.addAttribute(""project"", project); model.addAttribute(""searchNodeLabel"", searchNodeLabel); model.addAttribute(""description"", lemma); model.addAttribute(""unixName"", projectUnixName); return ""sites/networks/searchednetwork""; }"
271,"public @Nullable Integer getThreadOnCpuAtTime(int cpu, long time) { ITmfStateSystem stateSystem = getStateSystem(); if (stateSystem == null) { return null; } Integer tid = null; try { int cpuQuark = stateSystem.getQuarkAbsolute(Integer.toString(cpu)); ITmfStateValue value = stateSystem.querySingleState(time, cpuQuark).getStateValue(); if (value.getType().equals(Type.INTEGER)) { tid = value.unboxInt(); } } catch (AttributeNotFoundException | StateSystemDisposedException e) { Activator.getDefault().logError(NonNullUtils.nullToEmptyString(e.getMessage()), e); } <START> if (tid != null) { <END> return tid; } return null; }",simply return tid,"public @Nullable Integer getThreadOnCpuAtTime(int cpu, long time) { ITmfStateSystem stateSystem = getStateSystem(); if (stateSystem == null) { return null; } Integer tid = null; try { int cpuQuark = stateSystem.getQuarkAbsolute(Integer.toString(cpu)); ITmfStateValue value = stateSystem.querySingleState(time, cpuQuark).getStateValue(); if (value.getType().equals(Type.INTEGER)) { tid = value.unboxInt(); } } catch (AttributeNotFoundException | StateSystemDisposedException e) { Activator.getDefault().logError(NonNullUtils.nullToEmptyString(e.getMessage()), e); } return tid; }"
272,"Mono<Response<Void>> publishTelemetryWithResponse(String digitalTwinId, String payload, PublishTelemetryRequestOptions publishTelemetryRequestOptions, Context context) { return protocolLayer.getDigitalTwins().sendTelemetryWithResponseAsync( digitalTwinId, publishTelemetryRequestOptions.getMessageId(), <START> payload, <END> publishTelemetryRequestOptions.getTimestamp().toString(), context); }",need pre-emptively serialize this string PL deserializes string user provided,"Mono<Response<Void>> publishTelemetryWithResponse(String digitalTwinId, String payload, PublishTelemetryRequestOptions publishTelemetryRequestOptions, Context context) { Object payloadObject = null; try { payloadObject = mapper.readValue(payload, Object.class); } catch (JsonProcessingException e) { logger.error(""Could not parse the payload [%s]: %s"", payload, e); return Mono.error(e); } return protocolLayer.getDigitalTwins().sendTelemetryWithResponseAsync( digitalTwinId, publishTelemetryRequestOptions.getMessageId(), payloadObject, publishTelemetryRequestOptions.getTimestamp().toString(), context); }"
273,"public void testValidRequest() { try { HttpServletRequest req = EasyMock.createStrictMock(HttpServletRequest.class); HttpServletResponse resp = EasyMock.createStrictMock(HttpServletResponse.class); FilterChain filterChain = EasyMock.createNiceMock(FilterChain.class); ServletOutputStream outputStream = EasyMock.createNiceMock(ServletOutputStream.class); EasyMock.expect(resp.getOutputStream()).andReturn(outputStream).once(); EasyMock.expect(req.getAttribute(AuthConfig.DRUID_AUTH_TOKEN)).andReturn(""so-very-valid"").once(); EasyMock.expect(req.getAttribute(AuthConfig.DRUID_AUTH_TOKEN_CHECKED)).andReturn(true).once(); EasyMock.replay(req, resp, filterChain, outputStream); PreResponseAuthorizationCheckFilter filter = new PreResponseAuthorizationCheckFilter( authConfig, authenticators, new DefaultObjectMapper() ); filter.doFilter(req, resp, filterChain); EasyMock.verify(req, resp, filterChain, outputStream); } <START> catch (Exception ex) { <END> throw new RuntimeException(ex); } }",add exceptions method signature,"public void testValidRequest() throws Exception { AuthenticationResult authenticationResult = new AuthenticationResult(""so-very-valid"", ""so-very-valid""); HttpServletRequest req = EasyMock.createStrictMock(HttpServletRequest.class); HttpServletResponse resp = EasyMock.createStrictMock(HttpServletResponse.class); FilterChain filterChain = EasyMock.createNiceMock(FilterChain.class); ServletOutputStream outputStream = EasyMock.createNiceMock(ServletOutputStream.class); EasyMock.expect(req.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT)).andReturn(authenticationResult).once(); EasyMock.expect(req.getAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED)).andReturn(true).once(); EasyMock.replay(req, resp, filterChain, outputStream); PreResponseAuthorizationCheckFilter filter = new PreResponseAuthorizationCheckFilter( authenticators, new DefaultObjectMapper() ); filter.doFilter(req, resp, filterChain); EasyMock.verify(req, resp, filterChain, outputStream); }"
274,"public static BloomFilterReader getBloomFilterReader(PinotDataBuffer dataBuffer) { <START> int typeValue = dataBuffer.getInt(0); <END> int version = dataBuffer.getInt(4); Preconditions.checkState(typeValue == 1 && version == 1); return new OffHeapGuavaBloomFilterReader(dataBuffer.view(8, dataBuffer.size())); }","0, 4 static final variable? e.g. TYPE_VALUE_OFFSET, VERSION_OFFSET","public static BloomFilterReader getBloomFilterReader(PinotDataBuffer dataBuffer) { int typeValue = dataBuffer.getInt(TYPE_VALUE_OFFSET); int version = dataBuffer.getInt(VERSION_OFFSET); Preconditions.checkState( typeValue == OnHeapGuavaBloomFilterCreator.TYPE_VALUE && version == OnHeapGuavaBloomFilterCreator.VERSION, ""Unsupported bloom filter type value: %s and version: %s"", typeValue, version); return new OffHeapGuavaBloomFilterReader(dataBuffer.view(HEADER_SIZE, dataBuffer.size())); }"
275,"public void channelReleasedOnTimeout() throws Exception { final CachingConnectionFactory connectionFactory = new CachingConnectionFactory(""localhost""); RabbitTemplate template = createSendAndReceiveRabbitTemplate(connectionFactory); template.setReplyTimeout(1); AtomicReference<Throwable> exception = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); ErrorHandler replyErrorHandler = t -> { exception.set(t); latch.countDown(); }; template.setReplyErrorHandler(replyErrorHandler); Object reply = template.convertSendAndReceive(ROUTE, ""foo""); assertThat(reply).isNull(); Object container = TestUtils.getPropertyValue(template, ""directReplyToContainers"", Map.class) .get(template.isUsePublisherConnection() ? connectionFactory.getPublisherConnectionFactory() : connectionFactory); assertThat(TestUtils.getPropertyValue(container, ""inUseConsumerChannels"", Map.class)).hasSize(0); assertThat(TestUtils.getPropertyValue(container, ""errorHandler"")).isSameAs(replyErrorHandler); Message replyMessage = new Message(""foo"".getBytes(), new MessageProperties()); assertThatThrownBy(() -> template.onMessage(replyMessage)) .isInstanceOf(AmqpRejectAndDontRequeueException.class) .hasMessage(""No correlation header""); replyMessage.getMessageProperties().setCorrelationId(""foo""); assertThatThrownBy(() -> template.onMessage(replyMessage)) .isInstanceOf(AmqpRejectAndDontRequeueException.class) .hasMessage(""Reply received after timeout""); ExecutorService executor = Executors.newFixedThreadPool(1); executor.submit(() -> { Message message = template.receive(ROUTE, 10_000); assertNotNull(""No message received"", message); template.send(message.getMessageProperties().getReplyTo(), replyMessage); return message; }); while (template.receive(ROUTE, 100) != null) { } reply = template.convertSendAndReceive(ROUTE, ""foo""); assertThat(reply).isNull(); assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(exception.get()).isInstanceOf(ListenerExecutionFailedException.class); assertThat(exception.get().getCause().getMessage()).isEqualTo(""Reply received after timeout""); assertThat(((ListenerExecutionFailedException) exception.get()).getFailedMessage().getBody()) .isEqualTo(replyMessage.getBody()); assertThat(TestUtils.getPropertyValue(container, ""inUseConsumerChannels"", Map.class)).hasSize(0); <START> executor.shutdownNow(); <END> }",need destroy connectionFactory template in end of test well,"public void channelReleasedOnTimeout() throws Exception { final CachingConnectionFactory connectionFactory = new CachingConnectionFactory(""localhost""); RabbitTemplate template = createSendAndReceiveRabbitTemplate(connectionFactory); template.setReplyTimeout(1); AtomicReference<Throwable> exception = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); ErrorHandler replyErrorHandler = t -> { exception.set(t); latch.countDown(); }; template.setReplyErrorHandler(replyErrorHandler); Object reply = template.convertSendAndReceive(ROUTE, ""foo""); assertThat(reply).isNull(); Object container = TestUtils.getPropertyValue(template, ""directReplyToContainers"", Map.class) .get(template.isUsePublisherConnection() ? connectionFactory.getPublisherConnectionFactory() : connectionFactory); assertThat(TestUtils.getPropertyValue(container, ""inUseConsumerChannels"", Map.class)).hasSize(0); assertThat(TestUtils.getPropertyValue(container, ""errorHandler"")).isSameAs(replyErrorHandler); Message replyMessage = new Message(""foo"".getBytes(), new MessageProperties()); assertThatThrownBy(() -> template.onMessage(replyMessage)) .isInstanceOf(AmqpRejectAndDontRequeueException.class) .hasMessage(""No correlation header""); replyMessage.getMessageProperties().setCorrelationId(""foo""); assertThatThrownBy(() -> template.onMessage(replyMessage)) .isInstanceOf(AmqpRejectAndDontRequeueException.class) .hasMessage(""Reply received after timeout""); ExecutorService executor = Executors.newFixedThreadPool(1); executor.submit(() -> { Message message = template.receive(ROUTE, 10_000); assertNotNull(""No message received"", message); template.send(message.getMessageProperties().getReplyTo(), replyMessage); return message; }); while (template.receive(ROUTE, 100) != null) { } reply = template.convertSendAndReceive(ROUTE, ""foo""); assertThat(reply).isNull(); assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(exception.get()).isInstanceOf(ListenerExecutionFailedException.class); assertThat(exception.get().getCause().getMessage()).isEqualTo(""Reply received after timeout""); assertThat(((ListenerExecutionFailedException) exception.get()).getFailedMessage().getBody()) .isEqualTo(replyMessage.getBody()); assertThat(TestUtils.getPropertyValue(container, ""inUseConsumerChannels"", Map.class)).hasSize(0); executor.shutdownNow(); template.stop(); connectionFactory.destroy(); }"
276,"public Node createInterface_2004(EObject domainElement, View containerView, String semanticHint, int index, boolean persisted, PreferencesHint preferencesHint) { Shape node = NotationFactory.eINSTANCE.createShape(); node.setLayoutConstraint(NotationFactory.eINSTANCE.createBounds()); node.setType(semanticHint); ViewUtil.insertChildView(containerView, node, index, persisted); node.setElement(domainElement); ClassifierViewFactoryUtil.stampShortcut(containerView, node); final IPreferenceStore prefStore = (IPreferenceStore) preferencesHint.getPreferenceStore(); PreferenceInitializerForElementHelper.initFontStyleFromPrefs(node, prefStore, ""Interface""); ClassifierViewFactoryUtil.createLabel(node, UMLVisualIDRegistry.getType(InterfaceNameEditPart.VISUAL_ID)); Node label8507 = ClassifierViewFactoryUtil.createLabel(node, UMLVisualIDRegistry.getType(InterfaceFloatingNameEditPart.VISUAL_ID)); label8507.setLayoutConstraint(NotationFactory.eINSTANCE.createLocation()); Location location8507 = (Location) label8507.getLayoutConstraint(); location8507.setX(0); location8507.setY(5); <START> ClassifierViewFactoryUtil.createCompartment(node, UMLVisualIDRegistry.getType(InterfaceAttributeCompartmentEditPart.VISUAL_ID), true, true, true, true); ClassifierViewFactoryUtil.createCompartment(node, UMLVisualIDRegistry.getType(InterfaceAttributeCompartmentEditPart.VISUAL_ID), true, true, true, true); <END> ClassifierViewFactoryUtil.createCompartment(node, UMLVisualIDRegistry.getType(InterfaceOperationCompartmentEditPart.VISUAL_ID), true, true, true, true); ClassifierViewFactoryUtil.createCompartment(node, UMLVisualIDRegistry.getType(InterfaceNestedClassifierCompartmentEditPart.VISUAL_ID), true, true, true, true); PreferenceInitializerForElementHelper.initCompartmentsStatusFromPrefs(node, prefStore, ""Interface""); return node; }",Double attribute compartment visual id InterfaceAttributeCompartmentEditPart.VISUAL_ID,"public Node createInterface_2004(EObject domainElement, View containerView, String semanticHint, int index, boolean persisted, PreferencesHint preferencesHint) { Shape node = NotationFactory.eINSTANCE.createShape(); node.setLayoutConstraint(NotationFactory.eINSTANCE.createBounds()); node.setType(semanticHint); ViewUtil.insertChildView(containerView, node, index, persisted); node.setElement(domainElement); ClassifierViewFactoryUtil.stampShortcut(containerView, node); final IPreferenceStore prefStore = (IPreferenceStore) preferencesHint.getPreferenceStore(); PreferenceInitializerForElementHelper.initFontStyleFromPrefs(node, prefStore, ""Interface""); ClassifierViewFactoryUtil.createLabel(node, UMLVisualIDRegistry.getType(InterfaceNameEditPart.VISUAL_ID)); Node label8507 = ClassifierViewFactoryUtil.createLabel(node, UMLVisualIDRegistry.getType(InterfaceFloatingNameEditPart.VISUAL_ID)); label8507.setLayoutConstraint(NotationFactory.eINSTANCE.createLocation()); Location location8507 = (Location) label8507.getLayoutConstraint(); location8507.setX(0); location8507.setY(5); ClassifierViewFactoryUtil.createCompartment(node, UMLVisualIDRegistry.getType(InterfaceAttributeCompartmentEditPart.VISUAL_ID), true, true, true, true); ClassifierViewFactoryUtil.createCompartment(node, UMLVisualIDRegistry.getType(InterfaceOperationCompartmentEditPart.VISUAL_ID), true, true, true, true); ClassifierViewFactoryUtil.createCompartment(node, UMLVisualIDRegistry.getType(InterfaceNestedClassifierCompartmentEditPart.VISUAL_ID), true, true, true, true); PreferenceInitializerForElementHelper.initCompartmentsStatusFromPrefs(node, prefStore, ""Interface""); return node; }"
277,"protected boolean checkValidVersion(Set<SourceFile> sourceFiles, Tool entry) { boolean isValidCWL = false; String cwlPrimaryDescriptorPath = ""/Dockstore.cwl""; <START> Optional<SourceFile> cwlPrimaryDescriptor = sourceFiles.stream().filter(sf -> Objects.equals(sf.getPath(), cwlPrimaryDescriptorPath)).findFirst(); <END> if (cwlPrimaryDescriptor.isPresent()) { isValidCWL = true; } boolean isValidWDL = false; String wdlPrimaryDescriptorPath = ""/Dockstore.wdl""; Optional<SourceFile> wdlPrimaryDescriptor = sourceFiles.stream().filter(sf -> Objects.equals(sf.getPath(), wdlPrimaryDescriptorPath)).findFirst(); if (wdlPrimaryDescriptor.isPresent()) { isValidWDL = true; } boolean hasDockerfile = false; String dockerfilePath = ""/Dockerfile""; Optional<SourceFile> dockerfile = sourceFiles.stream().filter(sf -> Objects.equals(sf.getPath(), dockerfilePath)).findFirst(); if (dockerfile.isPresent()) { hasDockerfile = true; } return (isValidCWL || isValidWDL) && hasDockerfile; }",anyMatch more suitable filter+findFirst,"protected boolean checkValidVersion(Set<SourceFile> sourceFiles, Tool entry) { boolean isValidCWL = sourceFiles.stream().anyMatch(sf -> Objects.equals(sf.getPath(), ""/Dockstore.cwl"")); boolean isValidWDL = sourceFiles.stream().anyMatch(sf -> Objects.equals(sf.getPath(), ""/Dockstore.wdl"")); boolean hasDockerfile = sourceFiles.stream().anyMatch(sf -> Objects.equals(sf.getPath(), ""/Dockerfile"")); return (isValidCWL || isValidWDL) && hasDockerfile; }"
278,"public void setPermissionLevel(FolderPermissionLevel value) throws ServiceLocalException { if (this.permissionLevel != value) { if (value == FolderPermissionLevel.Custom) { throw new ServiceLocalException( <START> ""The PermissionLevel property can't be set to FolderPermissionLevel.Custom. To define a custom permission, set its individual properties to the values you want.""); <END> } this.AssignIndividualPermissions(defaultPermissions.getMember() .get(value)); if (this.canSetFieldValue(this.permissionLevel, value)) { this.permissionLevel = value; this.changed(); } } }",line-lenght ok,"public void setPermissionLevel(FolderPermissionLevel value) throws ServiceLocalException { if (this.permissionLevel != value) { if (value == FolderPermissionLevel.Custom) { throw new ServiceLocalException( ""The PermissionLevel property can't be set to FolderPermissionLevel.Custom. "" + ""To define a custom permission, set its individual properties to the values you want.""); } this.AssignIndividualPermissions(defaultPermissions.getMember() .get(value)); if (this.canSetFieldValue(this.permissionLevel, value)) { this.permissionLevel = value; this.changed(); } } }"
279,"public void shouldDeleteNetworkToPublicRouterNoDeleted() throws OpenStackException, InfrastructureException { String response = ""{\""ports\"": [ {\""status\"": \""ACTIVE\"",\""name\"": \""\"", \""admin_state_up\"": true, "" + ""\""network_id\"": \""ID\"", \""tenant_id\"": \""08bed031f6c54c9d9b35b42aa06b51c0\"","" + ""\""device_owner\"": \""compute:None\"", \""binding:capabilities\"": {\""port_filter\"": true}, "" + ""\""fixed_ips\"": [ {\""subnet_id\"": \""ID\"", \""ip_address\"": \""172.31.0.3\""}],"" + ""\""id\"": \""07fd27d2-9ce1-48f3-be83-c7d2b7041a1a\"", \""security_groups\"": [], \""device_id\"":"" + "" \""dhcpfa3e6aae-2140-5176-877a-2f67684a3165-6a609412-3f04-485c-b269-b1a9b9ecb6bf\"""" + ""}]}""; when(openStackUtil.listPorts(any(PaasManagerUser.class), anyString())).thenReturn(response); NetworkInstance net = new NetworkInstance(""router"", ""vdc"", ""region""); SubNetworkInstance subNet = new SubNetworkInstance(""dd"", ""vdc"", ""region"", ""ID""); subNet.setIdSubNet(""ID""); net.addSubNet(subNet); when(openStackUtil.deleteInterfaceToPublicRouter(any(PaasManagerUser.class), any(NetworkInstance.class), anyString())).thenReturn(response); openStackNetworkImpl.deleteNetworkToPublicRouter(claudiaData, net, REGION); <START> <END> }",add verify assert,"public void shouldDeleteNetworkToPublicRouterNoDeleted() throws OpenStackException, InfrastructureException { String response = ""{\""ports\"": [ {\""status\"": \""ACTIVE\"",\""name\"": \""\"", \""admin_state_up\"": true, "" + ""\""network_id\"": \""ID\"", \""tenant_id\"": \""08bed031f6c54c9d9b35b42aa06b51c0\"","" + ""\""device_owner\"": \""compute:None\"", \""binding:capabilities\"": {\""port_filter\"": true}, "" + ""\""fixed_ips\"": [ {\""subnet_id\"": \""ID\"", \""ip_address\"": \""172.31.0.3\""}],"" + ""\""id\"": \""07fd27d2-9ce1-48f3-be83-c7d2b7041a1a\"", \""security_groups\"": [], \""device_id\"":"" + "" \""dhcpfa3e6aae-2140-5176-877a-2f67684a3165-6a609412-3f04-485c-b269-b1a9b9ecb6bf\"""" + ""}]}""; when(openStackUtil.listPorts(any(PaasManagerUser.class), anyString())).thenReturn(response); NetworkInstance net = new NetworkInstance(""router"", ""vdc"", ""region""); SubNetworkInstance subNet = new SubNetworkInstance(""dd"", ""vdc"", ""region"", ""ID""); subNet.setIdSubNet(""ID""); net.addSubNet(subNet); when(openStackUtil.deleteInterfaceToPublicRouter(any(PaasManagerUser.class), any(NetworkInstance.class), anyString())).thenReturn(response); openStackNetworkImpl.deleteNetworkToPublicRouter(claudiaData, net, REGION); verify(openStackUtil, never()).deleteInterfaceToPublicRouter(any(PaasManagerUser.class), any(NetworkInstance.class), anyString()); }"
280,"static <T> Task<T> withSideEffect(final Callable<Task<T>> func) { <START> return Task.withSideEffect(""sideEffect"", func); <END> }","""withSideEffect"" description consistent current .withSideEffect","static <T> Task<Void> withSideEffect(final Callable<Task<T>> func) { return Task.withSideEffect(""withSideEffect"", func); }"
281,"private void connector(IProject prj) { try { IRemoteConnection irc = Util.getRemoteConnection(prj); if(irc == null) return; Activator.log(""Connection for project: '"" + prj.getName() + ""' is '"" + irc + ""'""); Activator.log(""Connection address is "" + irc.getAddress()); final ITerminalView tvr = (ITerminalView) PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage() .showView(""org.eclipse.tm.terminal.view.TerminalView""); ITerminalConnector[] itcarray = TerminalConnectorExtension .makeTerminalConnectors(); int remoteTools = 0; for (int i = 0; i < itcarray.length; i++) { <START> if(""Remote Tools"".equals(itcarray[i].getName())) { <END> remoteTools = i; break; } } if(itcarray.length==0) { Activator.log(""Could not find a terminal connection for ""+prj.getName()); return; } final ITerminalConnector inner = itcarray[remoteTools]; Activator.log(""inner=""+inner.getId()+"",""+inner.getName()+"",""+inner.getSettingsSummary()); ITerminalConnector connector = new ConnectorWrapper(inner,prj); tvr.newTerminal(connector); } catch (CoreException e1) { Activator.log(e1); } }","I change this ""Remote Services"" for terminal work. Note is for work coincidence if ""Remote Services"" is entry in array","private void connector(IProject prj) { try { IRemoteConnection irc = Util.getRemoteConnection(prj); if(irc == null) return; Activator.log(""Connection for project: '"" + prj.getName() + ""' is '"" + irc + ""'""); Activator.log(""Connection address is "" + irc.getAddress()); final ITerminalView tvr = (ITerminalView) PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage() .showView(""org.eclipse.tm.terminal.view.TerminalView""); ITerminalConnector[] itcarray = TerminalConnectorExtension .makeTerminalConnectors(); int remoteTools = -1; for (int i = 0; i < itcarray.length; i++) { if(""Remote Tools"".equals(itcarray[i].getName()) || ""Remote Services"".equals(itcarray[i].getName()) || ""org.eclipse.ptp.remote.internal.terminal.RemoteToolsConnector"".equals(itcarray[i].getId())) { remoteTools = i; break; } } if(itcarray.length==0) { Activator.log(""Could not find a terminal connection for ""+prj.getName()); return; } if(remoteTools >= 0) { final ITerminalConnector inner = itcarray[remoteTools]; Activator.log(""inner=""+inner.getId()+"",""+inner.getName()+"",""+inner.getSettingsSummary()); ITerminalConnector connector = inner; ISettingsStore store = new HashSettingsStore(); connector.save(store); store.put(RemoteSettings.PROJECT_NAME, prj.getName()); connector.load(store); tvr.newTerminal(connector); } } catch (CoreException e1) { Activator.log(e1); } }"
282,"private Action toAction() { try { <START> return new ActionImpl(getId(), title, description != null ? description : """", new URL(url)); <END> } catch (MalformedURLException e) { LOGGER.debug(""Unable to parse the action url: url={}"", url, e); return null; } }",description setter handle null-checking logic do here,"private Action toAction() { try { return new ActionImpl(getId(), title, description, new URL(url)); } catch (MalformedURLException e) { LOGGER.debug(""Unable to parse the action url: url={}"", url, e); return null; } }"
283,"public void setStepProperties(Map<String, Properties> properties) { Assert.notNull(properties, ""Step properties cannot be null""); for(Map.Entry<String, Properties> propertiesEntry : properties.entrySet()) { String stepName = propertiesEntry.getKey(); if (!propertiesEntry.getValue().isEmpty()) { if (this.stepProperties.containsKey(stepName)) { Properties existingStepProperties = this.stepProperties.get(stepName); <START> existingStepProperties.putAll(propertiesEntry.getValue()); <END> this.stepProperties.put(stepName, existingStepProperties); } else { this.stepProperties.put(stepName, propertiesEntry.getValue()); } } } }",This work. Map#addAll method a Properties object pull defaults defined in Properties object added,"public void setStepProperties(Map<String, Properties> properties) { Assert.notNull(properties, ""Step properties cannot be null""); for(Map.Entry<String, Properties> propertiesEntry : properties.entrySet()) { String stepName = propertiesEntry.getKey(); Properties stepProperties = propertiesEntry.getValue(); if (!stepProperties.isEmpty()) { if (this.stepProperties.containsKey(stepName)) { Properties existingStepProperties = this.stepProperties.get(stepName); Enumeration<?> stepPropertyNames = stepProperties.propertyNames(); while(stepPropertyNames.hasMoreElements()) { String propertyEntryName = (String) stepPropertyNames.nextElement(); existingStepProperties.put(propertyEntryName, stepProperties.getProperty(propertyEntryName)); } this.stepProperties.put(stepName, existingStepProperties); } else { this.stepProperties.put(stepName, propertiesEntry.getValue()); } } } }"
284,"public void testPatchRequestScope() { DataStoreTransaction tx = mock(DataStoreTransaction.class); <START> PatchRequestScope parentScope = <END> new PatchRequestScope(null, tx, new User(1), elideSettings); PatchRequestScope scope = new PatchRequestScope( parentScope.getPath(), parentScope.getJsonApiDocument(), parentScope); Parent parent = newParent(7); PersistentResource<Parent> parentResource = new PersistentResource<>(parent, null, ""1"", scope); parentResource.updateAttribute(""firstName"", ""foobar""); verify(tx, times(1)).setAttribute(parent, ""firstName"", ""foobar"", scope); }",code nest patch scopes this? I thought patch parent scope - child scopes normal request scopes,"public void testPatchRequestScope() { DataStoreTransaction tx = mock(DataStoreTransaction.class); PatchRequestScope parentScope = new PatchRequestScope(null, tx, new User(1), elideSettings); PatchRequestScope scope = new PatchRequestScope( parentScope.getPath(), parentScope.getJsonApiDocument(), parentScope); assertEquals(parentScope.isUseFilterExpressions(), scope.isUseFilterExpressions()); assertEquals(parentScope.getSorting(), scope.getSorting()); assertEquals(parentScope.getUpdateStatusCode(), scope.getUpdateStatusCode()); assertEquals(parentScope.getObjectEntityCache(), scope.getObjectEntityCache()); Parent parent = newParent(7); PersistentResource<Parent> parentResource = new PersistentResource<>(parent, null, ""1"", scope); parentResource.updateAttribute(""firstName"", ""foobar""); verify(tx, times(1)).setAttribute(parent, ""firstName"", ""foobar"", scope); }"
285,"public void shouldInvokeSignerIfRequested() throws IOException, NoSuchBuildTargetException, InterruptedException, DeploymentException { ProjectFilesystem filesystem = new ProjectFilesystem(temp.getRoot()); MavenPublishable publishable = (MavenPublishable) JavaLibraryBuilder.createBuilder(BuildTargetFactory.newInstance("" .setMavenCoords(""com.example:lib:1.0"") .addSrc(new FakeSourcePath(""Foo.java"")) .build(new BuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer())); filesystem.createParentDirs(publishable.getPathToOutput()); filesystem.touch(publishable.getPathToOutput()); Set<String> signatures = new HashSet<>(); ImmutableMap.Builder<ProcessExecutorParams, FakeProcess> commands = ImmutableMap.builder(); ImmutableSet<String> outputs = ImmutableSet.of( publishable.getPathToOutput().toString(), ""buck-out/gen/lib#maven.pom""); for (String out : outputs) { Path path = filesystem.getPathForRelativePath(out); Path signed = filesystem.getPathForRelativePath(out + "".asc""); commands.put( ProcessExecutorParams.builder().addCommand( ""gpg"", ""-ab"", ""--batch"", ""--passphrase"", ""passphrase"", path.toString()).build(), new FakeProcess(0, """", """")); signatures.add(signed.toString()); filesystem.touch(path); } FakeProcessExecutor executor = new FakeProcessExecutor(commands.build()); Publisher publisher = new Publisher( filesystem, Optional.of(temp.newFolder().toUri().toURL()), Optional.empty(), Optional.empty(), Optional.of(""passphrase""), false) { @Override protected ProcessExecutor createProcessExecutor(PrintStream stdout, PrintStream stderr) { try { for (String signature : signatures) { Path path = filesystem.getRootPath().getFileSystem().getPath(signature); filesystem.touch(path); } } catch (IOException e) { throw new RuntimeException(e); } return executor; } }; publisher.publish(ImmutableSet.of(publishable)); <START> } <END>",This is missing assert .asc file PUT,"public void shouldInvokeSignerIfRequested() throws IOException, NoSuchBuildTargetException, InterruptedException, DeploymentException { ProjectFilesystem filesystem = new ProjectFilesystem(temp.getRoot()); MavenPublishable publishable = (MavenPublishable) JavaLibraryBuilder.createBuilder(BuildTargetFactory.newInstance("" .setMavenCoords(""com.example:lib:1.0"") .addSrc(new FakeSourcePath(""Foo.java"")) .build(new BuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer())); filesystem.createParentDirs(publishable.getPathToOutput()); filesystem.touch(publishable.getPathToOutput()); Set<String> signatures = new HashSet<>(); ImmutableMap.Builder<ProcessExecutorParams, FakeProcess> commandBuilder = ImmutableMap.builder(); ImmutableSet<String> outputs = ImmutableSet.of( publishable.getPathToOutput().toString(), ""buck-out/gen/lib#maven.pom""); for (String out : outputs) { Path path = filesystem.getPathForRelativePath(out); Path signed = filesystem.getPathForRelativePath(out + "".asc""); ProcessExecutorParams signingCommand = ProcessExecutorParams.builder() .addCommand(""gpg"", ""-ab"", ""--batch"", ""--passphrase"", ""passphrase"", path.toString()) .build(); commandBuilder.put( signingCommand, new FakeProcess(0, """", """")); signatures.add(signed.toString()); filesystem.touch(path); } ImmutableMap<ProcessExecutorParams, FakeProcess> commands = commandBuilder.build(); FakeProcessExecutor executor = new FakeProcessExecutor(commands); Publisher publisher = new Publisher( filesystem, Optional.of(temp.newFolder().toUri().toURL()), Optional.empty(), Optional.empty(), Optional.of(""passphrase""), false) { @Override protected ProcessExecutor createProcessExecutor(PrintStream stdout, PrintStream stderr) { try { for (String signature : signatures) { Path path = filesystem.getRootPath().getFileSystem().getPath(signature); filesystem.touch(path); } } catch (IOException e) { throw new RuntimeException(e); } return executor; } }; publisher.publish(ImmutableSet.of(publishable)); for (ProcessExecutorParams params : commands.keySet()) { assertTrue(executor.isProcessLaunched(params)); } }"
286,"private void writeSavedConnectionResponse(HttpServletResponse response, DatabaseConfiguration savedConnection) throws IOException { Writer w = response.getWriter(); try { JsonGenerator writer = ParsingUtilities.mapper.getFactory().createGenerator(w); writer.writeStartObject(); writer.writeArrayFieldStart(DatabaseUtils.SAVED_CONNECTION_KEY); writer.writeStartObject(); <START> String sanitizedConnName = Encode.forHtml(savedConnection.getConnectionName()); <END> writer.writeStringField(""connectionName"", sanitizedConnName); writer.writeStringField(""databaseType"", savedConnection.getDatabaseType()); String sanitizedHost = Encode.forHtml(savedConnection.getDatabaseHost()); writer.writeStringField(""databaseHost"", sanitizedHost); writer.writeNumberField(""databasePort"", savedConnection.getDatabasePort()); String sanitizedDbName = Encode.forHtml(savedConnection.getDatabaseName()); writer.writeStringField(""databaseName"", sanitizedDbName); String dbPasswd = savedConnection.getDatabasePassword(); if(dbPasswd != null && !dbPasswd.isEmpty()) { dbPasswd = DatabaseUtils.decrypt(savedConnection.getDatabasePassword()); } writer.writeStringField(""databasePassword"", dbPasswd); writer.writeStringField(""databaseSchema"", savedConnection.getDatabaseSchema()); String sanitizedDbUser = Encode.forHtml(savedConnection.getDatabaseUser()); writer.writeStringField(""databaseUser"", sanitizedDbUser); logger.info(""Input DB User:{}, SanitizedDbUser:{}"", savedConnection.getDatabaseUser(), sanitizedDbUser); writer.writeEndObject(); writer.writeEndArray(); writer.writeEndObject(); writer.flush(); writer.close(); }finally { w.flush(); w.close(); } }","Intuitively I do HTML escaping in frontend. backend expose database credentials in true form, is frontend's job render user","private void writeSavedConnectionResponse(HttpServletResponse response, DatabaseConfiguration savedConnection) throws IOException { Writer w = response.getWriter(); try { JsonGenerator writer = ParsingUtilities.mapper.getFactory().createGenerator(w); writer.writeStartObject(); writer.writeArrayFieldStart(DatabaseUtils.SAVED_CONNECTION_KEY); writer.writeStartObject(); writer.writeStringField(""connectionName"", savedConnection.getConnectionName()); writer.writeStringField(""databaseType"", savedConnection.getDatabaseType()); writer.writeStringField(""databaseHost"", savedConnection.getDatabaseHost()); writer.writeNumberField(""databasePort"", savedConnection.getDatabasePort()); writer.writeStringField(""databaseName"", savedConnection.getDatabaseName()); String dbPasswd = savedConnection.getDatabasePassword(); if(dbPasswd != null && !dbPasswd.isEmpty()) { dbPasswd = DatabaseUtils.decrypt(savedConnection.getDatabasePassword()); } writer.writeStringField(""databasePassword"", dbPasswd); writer.writeStringField(""databaseSchema"", savedConnection.getDatabaseSchema()); writer.writeStringField(""databaseUser"", savedConnection.getDatabaseUser()); writer.writeEndObject(); writer.writeEndArray(); writer.writeEndObject(); writer.flush(); writer.close(); }finally { w.flush(); w.close(); } }"
287,public void dispose() { session.removeListener(this); SessionManager.INSTANCE.removeSessionsListener(this); session = null; treeViewer = null; manageSessionActionProvider = null; siriusCommonContentModelProvider = null; <START> menuManager = null; <END> },good set null toolkit,public void dispose() { session.removeListener(this); SessionManager.INSTANCE.removeSessionsListener(this); session = null; treeViewer = null; manageSessionActionProvider = null; siriusCommonContentModelProvider = null; menuManager = null; toolkit = null; }
288,private static FBNetwork getFBNetworkForSubApp(SubApp subApp) { if(null != subApp.getType()) { return subApp.getType().getFBNetwork(); } else <START> if(null != subApp.getOpposite()) { return ((SubApp)subApp.getOpposite()).getSubAppNetwork(); } else { <END> return subApp.getSubAppNetwork(); } },this break soon allow parts of subapps mapped. get wrong opposites here. reason I added orignal null check for subappnetwork,private static FBNetwork getFBNetworkForSubApp(SubApp subApp) { FBNetwork retVal = subApp.getSubAppNetwork(); if(null == retVal) { if(null != subApp.getType()) { retVal = subApp.getType().getFBNetwork(); } else if(null != subApp.getOpposite()) { retVal = ((SubApp)subApp.getOpposite()).getSubAppNetwork(); } } return retVal; }
289,"<START> private static LineEdit readEdit(final InputStream in) throws IOException { <END> final int beginA = readVarInt32(in); final int endA = readVarInt32(in); final int beginB = readVarInt32(in); final int endB = readVarInt32(in); return new LineEdit(beginA, endA, beginB, endB); }",BaseEdit,"private static BaseEdit readEdit(final InputStream in) throws IOException { final int beginA = readVarInt32(in); final int endA = readVarInt32(in); final int beginB = readVarInt32(in); final int endB = readVarInt32(in); return new BaseEdit(beginA, endA, beginB, endB); }"
290,"private void showOnboardingInstruction() { <START> InstructionDialogFragment.newInstance( <END> onboardingHelper.isDefaultBrowserFirefox() ? InstructionDialogFragment.EXTRA_INSTRUCTION_FIREFOX : InstructionDialogFragment.EXTRA_INSTRUCTION_CHROME, true).show(getSupportFragmentManager(), InstructionDialogFragment.TAG); }",pulling instructionType int a variable in line for readability. optional suggestion,"private void showOnboardingInstruction() { int instructionType = onboardingHelper.isDefaultBrowserFirefox() ? InstructionDialogFragment.EXTRA_INSTRUCTION_FIREFOX : InstructionDialogFragment.EXTRA_INSTRUCTION_CHROME; InstructionDialogFragment.newInstance(instructionType, true) .show(getSupportFragmentManager(), InstructionDialogFragment.TAG); }"
291,"public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) { final Player player = event.getPlayer(); final String cmd = event.getMessage().toLowerCase(Locale.ENGLISH).split("" "")[0].replace(""/"", """").toLowerCase(Locale.ENGLISH); if (ess.getUser(player).isMuted() && (ess.getSettings().getMuteCommands().contains(cmd) || ess.getSettings().getMuteCommands().contains(""*""))) { event.setCancelled(true); player.sendMessage(tl(""voiceSilenced"")); LOGGER.info(tl(""mutedUserSpeaks"", player.getName())); return; } if (ess.getSettings().getSocialSpyCommands().contains(cmd) || ess.getSettings().getSocialSpyCommands().contains(""*"")) { if (!player.hasPermission(""essentials.chat.spy.exempt"")) { for (User spyer : ess.getOnlineUsers()) { if (spyer.isSocialSpyEnabled() && !player.equals(spyer.getBase())) { spyer.sendMessage(player.getDisplayName() + "" : "" + event.getMessage()); } } } } boolean broadcast = true; boolean update = true; PluginCommand pluginCommand = ess.getServer().getPluginCommand(cmd); if (pluginCommand != null) { switch (pluginCommand.getName()) { case ""afk"": update = false; case ""vanish"": broadcast = false; } } if (update) { final User user = ess.getUser(player); user.updateActivity(broadcast); } <START> } <END>",changes in this class included in this PR? unrelated,"public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) { final Player player = event.getPlayer(); final String cmd = event.getMessage().toLowerCase(Locale.ENGLISH).split("" "")[0].replace(""/"", """").toLowerCase(Locale.ENGLISH); if (ess.getUser(player).isMuted() && (ess.getSettings().getMuteCommands().contains(cmd) || ess.getSettings().getMuteCommands().contains(""*""))) { event.setCancelled(true); player.sendMessage(tl(""voiceSilenced"")); LOGGER.info(tl(""mutedUserSpeaks"", player.getName())); return; } if (ess.getSettings().getSocialSpyCommands().contains(cmd) || ess.getSettings().getSocialSpyCommands().contains(""*"")) { if (!player.hasPermission(""essentials.chat.spy.exempt"")) { for (User spyer : ess.getOnlineUsers()) { if (spyer.isSocialSpyEnabled() && !player.equals(spyer.getBase())) { spyer.sendMessage(player.getDisplayName() + "" : "" + event.getMessage()); } } } } else { boolean broadcast = true; boolean update = true; PluginCommand pluginCommand = ess.getServer().getPluginCommand(cmd); if (pluginCommand != null) { switch (pluginCommand.getName()) { case ""afk"": update = false; case ""vanish"": broadcast = false; } } if (update) { final User user = ess.getUser(player); user.updateActivity(broadcast); } } }"
292,"protected @NonNull List<IMarkerEvent> getViewMarkerList(long startTime, long endTime, long resolution, @NonNull IProgressMonitor monitor) { ITimeGraphEntry[] expandedElements = getTimeGraphViewer().getExpandedElements(); List<IMarkerEvent> markers = new ArrayList<>(); for (ITimeGraphEntry element : expandedElements) { if (((TimeGraphEntry) element).getModel() instanceof SpanLifeEntryModel) { SpanLifeEntryModel model = (SpanLifeEntryModel) ((TimeGraphEntry) element).getModel(); for (LogEvent log : model.getLogs()) { markers.add(new SpanMarkerEvent(element, log.getTime(), MARKER_COLOR, log.getType())); } <START> if (model.getErrorTag()) { markers.add(new SpanMarkerEvent(element, model.getStartTime(), MARKER_COLOR, ""error.object"")); } <END> } } return markers; }",Remove this if postdraw for entries,"protected @NonNull List<IMarkerEvent> getViewMarkerList(long startTime, long endTime, long resolution, @NonNull IProgressMonitor monitor) { ITimeGraphEntry[] expandedElements = getTimeGraphViewer().getExpandedElements(); List<IMarkerEvent> markers = new ArrayList<>(); for (ITimeGraphEntry element : expandedElements) { if (((TimeGraphEntry) element).getModel() instanceof SpanLifeEntryModel) { SpanLifeEntryModel model = (SpanLifeEntryModel) ((TimeGraphEntry) element).getModel(); for (LogEvent log : model.getLogs()) { markers.add(new SpanMarkerEvent(element, log.getTime(), MARKER_COLOR, log.getType())); } } } return markers; }"
293,<START> public void doSetFilter(FileListFilter<F> filter) { <END> this.filter = filter; },intend this final,protected final void doSetFilter(FileListFilter<F> filter) { this.filter = filter; }
294,"public void updateDomain(UpdateDomain domain) throws CreateDomainException { try { directProxy.updateDomain(domain); } catch (Exception ex) { <START> throw new CreateDomainException(""Duplicate Domain: "" + domain.getDomain().getDomainName(), ex); <END> } }","Is this reason update fail? If run datasource issues, connection problems, constraint violations (excluding name uniqueness), ""Duplicate Domain"" reason in logs","public void updateDomain(UpdateDomain domain) throws DomainException { try { directProxy.updateDomain(domain); } catch (Exception ex) { throw new DomainException(""Unable to update Domain: "" + domain.getDomain().getDomainName(), ex); } }"
295,"public void testGetChangedAttributesWithComments() { TaskAttribute attributeComment = newData.getRoot().createAttribute(""custom""); attributeComment.setValue(""1""); attributeComment.getMetaData().setType(TaskAttribute.TYPE_COMMENT); TaskDataDiff diff = manager.createDiff(newData, oldData, new NullProgressMonitor()); <START> assertEquals(new ArrayList<>(diff.getNewComments()).get(0).getTaskAttribute(), attributeComment); <END> }",Collections.singleton for attachments,"public void testGetChangedAttributesWithComments() { TaskAttribute attributeComment = newData.getRoot().createAttribute(""custom""); attributeComment.setValue(""1""); attributeComment.getMetaData().setType(TaskAttribute.TYPE_COMMENT); TaskDataDiff diff = manager.createDiff(newData, oldData, new NullProgressMonitor()); assertEquals(1, diff.getNewComments().size()); assertEquals(attributeComment, diff.getNewComments().iterator().next().getTaskAttribute()); }"
296,"protected void setEnvironmentLabel(Map<String, Object> labels, Account account) { <START> labels.put(SystemLabels.LABEL_ENVIRONMENT_ID, account.getUuid()); <END> }","This ENVIRONMENT_UUID, ID. ID UUID values","protected void setEnvironmentLabel(Map<String, Object> labels, Account account) { labels.put(SystemLabels.LABEL_ENVIRONMENT_UUID, account.getUuid()); }"
297,"<START> private void putBlob(MessageInfo messageInfo, ByteBuffer messageBuf, long size) throws Exception { <END> boolean performUpload = messageInfo.getExpirationTimeInMs() == Utils.Infinite_Time && !messageInfo.isDeleted(); if (performUpload) { BlobId blobId = (BlobId) messageInfo.getStoreKey(); cloudDestination.uploadBlob(blobId, size, new ByteBufferInputStream(messageBuf)); } }",this is a bit weird. this function in class it,"private void putBlob(MessageInfo messageInfo, ByteBuffer messageBuf, long size) throws CloudStorageException { boolean performUpload = messageInfo.getExpirationTimeInMs() == Utils.Infinite_Time && !messageInfo.isDeleted(); if (performUpload) { BlobId blobId = (BlobId) messageInfo.getStoreKey(); cloudDestination.uploadBlob(blobId, size, new ByteBufferInputStream(messageBuf)); } }"
298,"private String generateRandomPassword() { <START> String acceptable = ""abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*(),.""; END> char[] chars = new char[8]; for (int i = 0; i < chars.length; i++) { char r = acceptable.charAt(rand.nextInt(acceptable.length())); chars[i] = r; } return new String(chars); }","include confusing characters 1 I, 0 O, . ,","private String generateRandomPassword() { String acceptable = ""abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*(),.""; char[] chars = new char[8]; char last = 'a'; for (int i = 0; i < chars.length; i++) { char r = acceptable.charAt(rand.nextInt(acceptable.length())); while (checkSimilar(last, r)) r = acceptable.charAt(rand.nextInt(acceptable.length())); last = r; chars[i] = r; } return new String(chars); }"
299,private static Optional<LiteralTree[]> getLiteralsFromFinalVariables(IdentifierTree identifier) { Symbol symbol = identifier.symbol(); if (!symbol.isVariableSymbol()) { return Optional.empty(); } Symbol.VariableSymbol variableSymbol = (Symbol.VariableSymbol) symbol; <START> if (!variableSymbol.isFinal()) { <END> return Optional.empty(); } VariableTree declaration = variableSymbol.declaration(); if (declaration == null) { return Optional.empty(); } ExpressionTree initializer = declaration.initializer(); if (initializer == null) { return Optional.empty(); } return getLiterals(initializer); },Is a check a variable is *effectively* final? this work locals locals rarely explicitly defined final,private static Optional<LiteralTree[]> getLiteralsFromFinalVariables(IdentifierTree identifier) { Symbol symbol = identifier.symbol(); if (!symbol.isVariableSymbol()) { return Optional.empty(); } Symbol.VariableSymbol variableSymbol = (Symbol.VariableSymbol) symbol; if (!(variableSymbol.isFinal() || JUtils.isEffectivelyFinal(variableSymbol))) { return Optional.empty(); } VariableTree declaration = variableSymbol.declaration(); if (declaration == null) { return Optional.empty(); } ExpressionTree initializer = declaration.initializer(); if (initializer == null) { return Optional.empty(); } return getLiterals(initializer); }
300,"private void loadMainActivity(){ settings = getSharedPreferences(""prefs"", 0); <START> SharedPreferences.Editor editor = settings.edit(); <END> editor.putBoolean(""firstRun"", false); editor.commit(); Intent intent = new Intent(this, StartActivity.class); startActivity(intent); finish(); }",Name this variable sharedPreferencesEditor for readability,"private void loadMainActivity() { sharedPreferences = getSharedPreferences(""prefs"", 0); SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit(); sharedPreferencesEditor.putBoolean(""firstRun"", false); sharedPreferencesEditor.commit(); startActivity(new Intent(this, StartActivity.class)); finish(); }"
301,"public String toString() { String flattenValue = values.stream().filter(value -> !CoreUtils.isNullOrEmpty(value)) .map(this::escapeValue).collect(Collectors.joining(COMMA)); if (CoreUtils.isNullOrEmpty(flattenValue)) { throw logger.logExceptionAsError( new IllegalArgumentException(""There must be at least one valid value for scoring parameter values."")); } <START> return name + SEPARATOR + values.stream().filter(value -> !CoreUtils.isNullOrEmpty(value)) .map(this::escapeValue).collect(Collectors.joining(COMMA)); <END> }",do need repeat creating flattenValue? This simplified following: java return name + SEPARATOR + flattenValue;,"public String toString() { String flattenValue = values.stream().filter(value -> !CoreUtils.isNullOrEmpty(value)) .map(ScoringParameter::escapeValue).collect(Collectors.joining(COMMA)); if (CoreUtils.isNullOrEmpty(flattenValue)) { throw logger.logExceptionAsError( new IllegalArgumentException(""There must be at least one valid value for scoring parameter values."")); } return name + DASH + flattenValue; }"
302,"protected void executeCommand() { lockImage(); CinderDisk cinderDisk = getDisk(); cinderDisk.setDiskAlias(getParameters().getDiskAlias()); String volumeId = getNewVolumeCinderDisk(cinderDisk); cinderDisk.setId(Guid.createGuidFromString(volumeId)); cinderDisk.setImageId(Guid.createGuidFromString(volumeId)); <START> cinderDisk.setActive(true); <END> cinderDisk.setParentId(Guid.Empty); cinderDisk.setVmSnapshotId(getParameters().getVmSnapshotId()); cinderDisk.setImageStatus(ImageStatus.LOCKED); cinderDisk.setVolumeType(VolumeType.Sparse); addCinderDiskTemplateToDB(cinderDisk); getReturnValue().setActionReturnValue(cinderDisk.getId()); getParameters().setDestinationImageId(Guid.createGuidFromString(volumeId)); getParameters().setContainerId(Guid.createGuidFromString(volumeId)); persistCommand(getParameters().getParentCommand(), true); setSucceeded(true); }",done disk is active,"protected void executeCommand() { lockImage(); CinderDisk cinderDisk = getDisk(); cinderDisk.setDiskAlias(getParameters().getDiskAlias()); String volumeId = getNewVolumeCinderDisk(cinderDisk); cinderDisk.setId(Guid.createGuidFromString(volumeId)); cinderDisk.setImageId(Guid.createGuidFromString(volumeId)); cinderDisk.setImageStatus(ImageStatus.LOCKED); cinderDisk.setVolumeType(VolumeType.Sparse); if (!cinderDisk.getActive()) { cinderDisk.setActive(true); cinderDisk.setParentId(Guid.Empty); cinderDisk.setVmSnapshotId(getParameters().getVmSnapshotId()); } addCinderDiskTemplateToDB(cinderDisk); getReturnValue().setActionReturnValue(cinderDisk.getId()); getParameters().setDestinationImageId(Guid.createGuidFromString(volumeId)); getParameters().setContainerId(Guid.createGuidFromString(volumeId)); persistCommand(getParameters().getParentCommand(), true); setSucceeded(true); }"
303,"private Object[] arraysOfDepth( int n ) { <START> return n == 0 ? new Object[]{""hej""} : arraysOfDepth( n-1 ); <END> }",This wrap nest arrays. returns array recursion base case,"private Object[] arraysOfDepth( int n ) { return n == 0 ? new Object[]{""hej""} : new Object[]{arraysOfDepth( n-1 )}; }"
304,protected void onResume() { if (PhoneFactory.getDefaultPhone().getPhoneType() != Phone.PHONE_TYPE_CDMA) { mButtonCdmaRoam.setEnabled(false); mButtonCdmaSubscription.setEnabled(false); } else { mButtonCdmaRoam.setEnabled(true); <START> mButtonCdmaSubscription.setEnabled(true); <END> } super.onResume(); },This needs conditional. This enabled devices NV RUIM. system default type,protected void onResume() { if (PhoneFactory.getDefaultPhone().getPhoneType() != Phone.PHONE_TYPE_CDMA) { mButtonCdmaRoam.setEnabled(false); mButtonCdmaSubscription.setEnabled(false); } else { mButtonCdmaRoam.setEnabled(true); if(deviceSupportsNvAndRuim()) { mButtonCdmaSubscription.setEnabled(true); } else { mButtonCdmaSubscription.setEnabled(false); } } super.onResume(); }
305,"private Folder getInboxFolder() throws MessagingException { final Folder inbox = store.getFolder(""inbox""); <START> inbox.open(Folder.READ_WRITE); <END> return inbox; }",Do need write permission,"private Folder getInboxFolder() throws MessagingException { Folder inbox = store.getFolder(""inbox""); inbox.open(Folder.READ_ONLY); return inbox; }"
306,"protected void setInitialState(ByteBuffer initialState) { if (m_shutdown.get()) { if (exportLog.isDebugEnabled()) { exportLog.debug(""Shutdown, ignore initial state proposed on "" + m_eds); } return; } try { m_eds.getExecutorService().execute(new Runnable() { @Override public void run() { try { if (exportLog.isDebugEnabled()) { exportLog.debug(""Set initial state on host: "" + m_hostId); } Integer newLeaderHostId = initialState.getInt(); m_leaderHostId = newLeaderHostId; StringBuilder sb = new StringBuilder(""Initialized export coordinator: host "") .append(m_leaderHostId) .append(isPartitionLeader() ? "" (localHost) "" : "" "") .append(""is the leader at initial state""); if (isPartitionLeader()) { exportLog.info(sb.toString()); } else if (exportLog.isDebugEnabled()) { <START> exportLog.debug(sb.toString()); <END> } setCoordinatorInitialized(); invokeNext(); } catch (Exception e) { exportLog.error(""Failed to change to initial state leader: "" + e); } } }); } catch (RejectedExecutionException rej) { if (exportLog.isDebugEnabled()) { exportLog.debug(""Initial state rejected by: "" + m_eds); } } catch (Exception e) { exportLog.error(""Failed to handle initial state: "" + e); } }",build log message needed,"protected void setInitialState(ByteBuffer initialState) { if (m_shutdown.get()) { if (exportLog.isDebugEnabled()) { exportLog.debug(""Shutdown, ignore initial state proposed on "" + m_eds); } return; } try { m_eds.getExecutorService().execute(new Runnable() { @Override public void run() { try { if (exportLog.isDebugEnabled()) { exportLog.debug(""Set initial state on host: "" + m_hostId); } Integer newLeaderHostId = initialState.getInt(); m_leaderHostId = newLeaderHostId; if (isPartitionLeader()) { exportLog.info(getLeaderMessageAtInitialState()); } else if (exportLog.isDebugEnabled()) { exportLog.debug(getLeaderMessageAtInitialState()); } setCoordinatorInitialized(); invokeNext(); } catch (Exception e) { exportLog.error(""Failed to change to initial state leader: "" + e); } } }); } catch (RejectedExecutionException rej) { if (exportLog.isDebugEnabled()) { exportLog.debug(""Initial state rejected by: "" + m_eds); } } catch (Exception e) { exportLog.error(""Failed to handle initial state: "" + e); } }"
307,"private InputStream downloadFile(final String fileId) { <START> final HttpResponse<InputStream> response = Unirest.delete(getDriveUrl() + ""/api/drive/file/"" + fileId + ""/download"") <END> .header(""Authorization"", ""Bearer "" + getAccessToken()) .asObject(raw -> raw.getContent()); final HttpResponse<InputStream> realResponse = response.getStatus() == 307 ? Unirest.get(response.getHeaders().getFirst(""Location"")).asObject(raw -> raw.getContent()) : response; return realResponse.getBody(); }",Is delete method want invoke here,"private InputStream downloadFile(final String fileId) { final HttpResponse<InputStream> response = Unirest.get(getDriveUrl() + ""/api/drive/file/"" + fileId + ""/download"") .header(""Authorization"", ""Bearer "" + getAccessToken()) .asObject(raw -> raw.getContent()); final HttpResponse<InputStream> realResponse = response.getStatus() == 307 ? Unirest.get(response.getHeaders().getFirst(""Location"")).asObject(raw -> raw.getContent()) : response; return realResponse.getBody(); }"
308,"protected void loadListeners(ServiceLoader<LifecycleListener> loader) { Iterator<LifecycleListener> iterator = loader.iterator(); <START> while (checkHasNextSafely(iterator)) { <END> try { LifecycleListener listener = iterator.next(); listeners.add(listener); } catch (ServiceConfigurationError e) { logger.error(""iterator.next() failed"", e); } } }","word ""check"" is overkill","protected void loadListeners(ServiceLoader<LifecycleListener> loader) { Iterator<LifecycleListener> iterator = loader.iterator(); while (hasNextSafely(iterator)) { try { LifecycleListener listener = iterator.next(); listeners.add(listener); logger.info(String.format(""Found %s: %s"", LifecycleListener.class, listener.getClass())); } catch (ServiceConfigurationError e) { logger.error(""iterator.next() failed"", e); } } }"
309,"private SessionId handleAcrChange(SessionId session, List<Prompt> prompts) { if (session != null) { if (session.getState() == SessionIdState.AUTHENTICATED) { String sessionPrompts; if (prompts.contains(Prompt.LOGIN)) { sessionPrompts = prompt; } else { prompts.add(Prompt.LOGIN); sessionPrompts = session.getSessionAttributes().get(""prompt""); sessionPrompts = StringUtils.isEmpty(sessionPrompts) ? """" : (sessionPrompts + "" ""); sessionPrompts = sessionPrompts + Prompt.LOGIN.getParamName(); } <START> session.getSessionAttributes().put(""prompt"", sessionPrompts); <END> session.setState(SessionIdState.UNAUTHENTICATED); String remoteIp = networkService.getRemoteIp(); session.getSessionAttributes().put(Constants.REMOTE_IP, remoteIp); sessionIdService.updateSessionId(session); sessionIdService.reinitLogin(session, false); } } return session; }","do work replace 11 lines 4 ? if (!prompts.contains(Prompt.LOGIN)) { prompts.add(Prompt.LOGIN); } session.getSessionAttributes().put(""prompt"", StringUtils.implode(prompts, "" "");","private SessionId handleAcrChange(SessionId session, List<Prompt> prompts) { if (session != null) { if (session.getState() == SessionIdState.AUTHENTICATED) { if (!prompts.contains(Prompt.LOGIN)) { prompts.add(Prompt.LOGIN); } session.getSessionAttributes().put(""prompt"", org.xdi.oxauth.model.util.StringUtils.implode(prompts, "" "")); session.setState(SessionIdState.UNAUTHENTICATED); String remoteIp = networkService.getRemoteIp(); session.getSessionAttributes().put(Constants.REMOTE_IP, remoteIp); sessionIdService.updateSessionId(session); sessionIdService.reinitLogin(session, false); } } return session; }"
310,public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); <START> searchView.setVisibility(isVisibleToUser ? View.VISIBLE : View.GONE); <END> onFragmentVisibilityChange(isVisibleToUser); },"SearchView's visibility dependent of discovery fragments, visibility controlled MainDiscoveryFragment'",public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); onFragmentVisibilityChange(isVisibleToUser); }
311,"public Optional<FieldSortExpectations<ZonedDateTime>> getFieldSortExpectations() { return Optional.of( new FieldSortExpectations<>( <START> LocalDateTime.of( 2018, 2, 1, 0, 0 ).atZone( ZoneId.of( ""America/Chicago"" ) ), <END> LocalDateTime.of( 2018, 3, 1, 0, 0 ).atZone( ZoneId.of( ""America/Chicago"" ) ), LocalDateTime.of( 2018, 4, 1, 0, 0 ).atZone( ZoneId.of( ""America/Chicago"" ) ), LocalDateTime.of( 2018, 1, 1, 0, 0 ).atZone( ZoneId.of( ""America/Chicago"" ) ), LocalDateTime.of( 2018, 2, 15, 0, 0 ).atZone( ZoneId.of( ""America/Chicago"" ) ), LocalDateTime.of( 2018, 3, 15, 0, 0 ).atZone( ZoneId.of( ""America/Chicago"" ) ), LocalDateTime.of( 2018, 5, 1, 0, 0 ).atZone( ZoneId.of( ""America/Chicago"" ) ) ) ); }","above, I mix timezones","public Optional<FieldSortExpectations<ZonedDateTime>> getFieldSortExpectations() { return Optional.of( new FieldSortExpectations<>( LocalDateTime.of( 2018, 2, 1, 0, 0 ).atZone( ZoneId.of( ""America/Chicago"" ) ), LocalDateTime.of( 2018, 3, 1, 0, 0 ).atZone( ZoneId.of( ""America/Chicago"" ) ), LocalDateTime.of( 2018, 4, 1, 0, 0 ).atZone( ZoneId.of( ""America/Chicago"" ) ), LocalDateTime.of( 2018, 1, 1, 0, 0 ).atZone( ZoneId.of( ""America/Chicago"" ) ), LocalDateTime.of( 2018, 2, 15, 0, 0 ).atZone( ZoneId.of( ""America/Chicago"" ) ), LocalDateTime.of( 2018, 3, 1, 0, 0 ).atZone( ZoneId.of( ""US/Alaska"" ) ), LocalDateTime.of( 2018, 5, 1, 0, 0 ).atZone( ZoneId.of( ""America/Chicago"" ) ) ) ); }"
312,"public void afterPropertiesSet() throws Exception { objectMapper = null; <START> if (applicationContext != null && applicationContext.containsBean(""objectMapper"")) { <END> objectMapper = (ObjectMapper) applicationContext.getBean(""objectMapper""); } if (objectMapper == null && applicationContext != null) { try { objectMapper = BeanFactoryUtils.beanOfTypeIncludingAncestors(applicationContext, ObjectMapper.class); } catch (Exception e) { logger.debug(e); } } if (objectMapper == null) { objectMapper = new ObjectMapper(); } jsonRpcServer = new JsonRpcServer( objectMapper, null == getServiceInterface() ? getService() : getProxyForService(), getServiceInterface()); jsonRpcServer.setErrorResolver(errorResolver); jsonRpcServer.setBackwardsCompatible(backwardsCompatible); jsonRpcServer.setRethrowExceptions(rethrowExceptions); jsonRpcServer.setAllowExtraParams(allowExtraParams); jsonRpcServer.setAllowLessParams(allowLessParams); jsonRpcServer.setInvocationListener(invocationListener); jsonRpcServer.setHttpStatusCodeProvider(httpStatusCodeProvider); jsonRpcServer.setConvertedParameterTransformer(convertedParameterTransformer); jsonRpcServer.setShouldLogInvocationErrors(shouldLogInvocationErrors); if (contentType != null) { jsonRpcServer.setContentType(contentType); } if (interceptorList != null) { jsonRpcServer.setInterceptorList(interceptorList); } ReflectionUtil.clearCache(); exportService(); }",purpose of removing objectMapper == null this if statement instead setting null line 41? is of objectMapper afterPropertiesSet() is called,"public void afterPropertiesSet() throws Exception { if (objectMapper == null && applicationContext != null && applicationContext.containsBean(""objectMapper"")) { objectMapper = (ObjectMapper) applicationContext.getBean(""objectMapper""); } if (objectMapper == null && applicationContext != null) { try { objectMapper = BeanFactoryUtils.beanOfTypeIncludingAncestors(applicationContext, ObjectMapper.class); } catch (Exception e) { logger.debug(e); } } if (objectMapper == null) { objectMapper = new ObjectMapper(); } jsonRpcServer = new JsonRpcServer( objectMapper, null == getServiceInterface() ? getService() : getProxyForService(), getServiceInterface()); jsonRpcServer.setErrorResolver(errorResolver); jsonRpcServer.setBackwardsCompatible(backwardsCompatible); jsonRpcServer.setRethrowExceptions(rethrowExceptions); jsonRpcServer.setAllowExtraParams(allowExtraParams); jsonRpcServer.setAllowLessParams(allowLessParams); jsonRpcServer.setInvocationListener(invocationListener); jsonRpcServer.setHttpStatusCodeProvider(httpStatusCodeProvider); jsonRpcServer.setConvertedParameterTransformer(convertedParameterTransformer); jsonRpcServer.setShouldLogInvocationErrors(shouldLogInvocationErrors); if (contentType != null) { jsonRpcServer.setContentType(contentType); } if (interceptorList != null) { jsonRpcServer.setInterceptorList(interceptorList); } ReflectionUtil.clearCache(); exportService(); }"
313,"public synchronized void onWorkerAdded(final boolean addedEval, final String workerId) { if (addedEval) { return; } <START> workerClockMap.put(workerId, globalMinimumClock); <END> minimumClockWorkers.add(workerId); }","globalMinimumClock of greater 0, parameter addedEval false. Handling this case throwing RuntimeException sense","public synchronized void onWorkerAdded(final boolean addedEval, final String workerId) { if (addedEval) { return; } if (!addedEval && globalMinimumClock != INITIAL_GLOBAL_MINIMUM_CLOCK) { throw new RuntimeException( String.format(""Initial worker %s is added after global minimum clock changes"", workerId)); } workerClockMap.put(workerId, globalMinimumClock); minimumClockWorkers.add(workerId); }"
314,"public void initialize() throws Exception { super.init(userMode); backendUrl = gatewayContextMgt.getContextUrls().getBackEndUrl(); loginClient = new AuthenticatorClient(backendUrl); String session = loginClient.login(user.getUserName(), user.getPassword(), ""localhost""); lifeCycleAdminClient = new LifeCycleAdminClient(backendUrl, session); originalLifeCycleContent = lifeCycleAdminClient.getLifecycleConfiguration(apiLifeCycleName); String customizedAPILifecycleContent = FileManager.readFile(customizedAPILifecyclePath); lifeCycleAdminClient.editLifeCycle(apiLifeCycleName, customizedAPILifecycleContent); String gatewayUrl; <START> if (gatewayContextWrk.getContextTenant().getDomain().equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { <END> gatewayUrl = gatewayUrlsWrk.getWebAppURLNhttp(); } else { gatewayUrl = gatewayUrlsWrk.getWebAppURLNhttp() + ""t/"" + gatewayContextWrk.getContextTenant().getDomain() + ""/""; } apiEndPointUrl = gatewayUrl + ""jaxrs_basic/services/customers/customerservice""; APIRequest apiRequest = new APIRequest(API_NAME, API_CONTEXT, new URL(apiEndPointUrl)); apiRequest.setVersion(API_VERSION_1_0_0); apiRequest.setSandbox(apiEndPointUrl); apiRequest.setProvider(user.getUserName()); HttpResponse serviceResponse = restAPIPublisher.addAPI(apiRequest); apiId = serviceResponse.getData(); }",Swap equals condition,"public void initialize() throws Exception { super.init(userMode); backendUrl = gatewayContextMgt.getContextUrls().getBackEndUrl(); loginClient = new AuthenticatorClient(backendUrl); String session = loginClient.login(user.getUserName(), user.getPassword(), ""localhost""); lifeCycleAdminClient = new LifeCycleAdminClient(backendUrl, session); originalLifeCycleContent = lifeCycleAdminClient.getLifecycleConfiguration(apiLifeCycleName); String customizedAPILifecycleContent = FileManager.readFile(customizedAPILifecyclePath); lifeCycleAdminClient.editLifeCycle(apiLifeCycleName, customizedAPILifecycleContent); String gatewayUrl; if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(gatewayContextWrk.getContextTenant().getDomain())) { gatewayUrl = gatewayUrlsWrk.getWebAppURLNhttp(); } else { gatewayUrl = gatewayUrlsWrk.getWebAppURLNhttp() + ""t/"" + gatewayContextWrk.getContextTenant().getDomain() + ""/""; } apiEndPointUrl = gatewayUrl + ""jaxrs_basic/services/customers/customerservice""; APIRequest apiRequest = new APIRequest(API_NAME, API_CONTEXT, new URL(apiEndPointUrl)); apiRequest.setVersion(API_VERSION_1_0_0); apiRequest.setSandbox(apiEndPointUrl); apiRequest.setProvider(user.getUserName()); HttpResponse serviceResponse = restAPIPublisher.addAPI(apiRequest); apiId = serviceResponse.getData(); }"
315,"private void onDeleteSnapshot() { if (getConfirmWindow() == null) { return; } ConfirmationModel model = (ConfirmationModel) getConfirmWindow(); if <START> (model.getProgress() != null) { <END> return; } List<VdcActionParametersBase> paramsList = new ArrayList<>(); for (GlusterVolumeSnapshotEntity snapshot : (List<GlusterVolumeSnapshotEntity>) getSelectedItems()) { GlusterVolumeSnapshotActionParameters param = new GlusterVolumeSnapshotActionParameters(getEntity().getId(), snapshot.getSnapshotName(), true); paramsList.add(param); } model.startProgress(null); Frontend.getInstance().runMultipleAction(VdcActionType.DeleteGlusterVolumeSnapshot, paramsList, new IFrontendMultipleActionAsyncCallback() { @Override public void executed(FrontendMultipleActionAsyncResult result) { ConfirmationModel localModel = (ConfirmationModel) getConfirmWindow(); localModel.stopProgress(); setConfirmWindow(null); } }, model); }",Is this required? this true,"private void onDeleteSnapshot() { if (getConfirmWindow() == null) { return; } ConfirmationModel model = (ConfirmationModel) getConfirmWindow(); List<VdcActionParametersBase> paramsList = new ArrayList<>(); for (GlusterVolumeSnapshotEntity snapshot : (List<GlusterVolumeSnapshotEntity>) getSelectedItems()) { GlusterVolumeSnapshotActionParameters param = new GlusterVolumeSnapshotActionParameters(getEntity().getId(), snapshot.getSnapshotName(), true); paramsList.add(param); } model.startProgress(null); Frontend.getInstance().runMultipleAction(VdcActionType.DeleteGlusterVolumeSnapshot, paramsList, new IFrontendMultipleActionAsyncCallback() { @Override public void executed(FrontendMultipleActionAsyncResult result) { ConfirmationModel localModel = (ConfirmationModel) getConfirmWindow(); localModel.stopProgress(); setConfirmWindow(null); } }, model); }"
316,"private boolean matchesExtensions(LanguageDescription language, String path) { if (language.getFileExtensions() != null) { for (String extension : language.getFileExtensions()) { if (path.endsWith(extension)) { return true; } } } <START> return false; <END> }",return Optional.ofNullable(language.getFileExtensions()).map(Collection::stream).orElse(Stream.empty()).anyMatch(extension -> path.endsWith(extension));,"private boolean matchesExtensions(LanguageDescription language, String path) { return language.getFileExtensions().stream().anyMatch(extension->path.endsWith(extension)); }"
317,private void closeScope() { if (openTracingService == null) { return; } Tracer tracer = openTracingService.getTracer(PAYARA_CORBA_RMI_TRACER_NAME); if (tracer == null) { return; } <START> try (Scope activeScope = tracer.scopeManager().active()) { <END> } },"activeScope, wrong..",private void closeScope() { if (!tracerAvailable()) { return; } try (Scope activeScope = tracer.scopeManager().active()) { } }
318,"private String buildUpdateScript(final String content) { Validate.notNull(content); final StringWriter raw = new StringWriter(); final PrintWriter script = new PrintWriter(raw); final StringBuilder sb = new StringBuilder(); final StringBuilder cb = new StringBuilder(); sb.append("":syntax => :scss""); for (final String require : requires) { script.println("" require '"" + require + ""' ""); } for (int i = 0; i < content.length(); i++) { <START> cb.append(String.format(""\\u%04x"", content.codePointAt(i))); <END> } final String scriptAsString = String.format(""result = Sass::Engine.new(\""%s\"", {%s}).render"", cb.toString(), sb.toString()); LOG.debug(""scriptAsString: {}"", scriptAsString); script.println(scriptAsString); script.flush(); return raw.toString(); }","Also, a test-case proves problem helpful","private String buildUpdateScript(final String content) { Validate.notNull(content); final StringWriter raw = new StringWriter(); final PrintWriter script = new PrintWriter(raw); final StringBuilder sb = new StringBuilder(); final StringBuilder cb = new StringBuilder(); sb.append("":syntax => :scss""); for (final String require : requires) { script.println("" require '"" + require + ""' ""); } final int BACKSLASH = 0x5c; for (int i = 0; i < content.length(); i++) { final int code = content.codePointAt(i); if (code < 0x80) { if (code == BACKSLASH) { cb.append(""\\""); } cb.append(content.charAt(i)); } else { cb.append(String.format(""\\u%04x"", code)); } } final String scriptAsString = String.format(""result = Sass::Engine.new(\""%s\"", {%s}).render"", cb.toString().replace(""\"""", ""\\\"""").replace(""#"", ""\\#""), sb.toString()); LOG.debug(""scriptAsString: {}"", scriptAsString); script.println(scriptAsString); script.flush(); return raw.toString(); }"
319,"public <T> void removeTask( ScheduledTask<T> task ) { synchronized ( applicationConfiguration ) { List<CScheduledTask> tasks = getCurrentConfiguration( true ); CScheduledTask foundTask = findTask( task.getId(), tasks ); if ( foundTask != null ) { tasks.remove( foundTask ); <START> } <END> if ( NXCM4979DEBUG ) { logger.info( ""Task with ID={} removed, config {} modified."", task.getId(), foundTask != null ? ""IS"" : ""is NOT"", new Exception( ""This is an exception only to provide caller backtrace"" ) ); } try { applicationConfiguration.saveConfiguration(); } catch ( IOException e ) { logger.warn( ""Could not save task changes!"", e ); } } }",relevant non-logging code change ^^^,"public <T> void removeTask( ScheduledTask<T> task ) { synchronized ( applicationConfiguration ) { List<CScheduledTask> tasks = getCurrentConfiguration( true ); CScheduledTask foundTask = findTask( task.getId(), tasks ); if ( foundTask != null ) { tasks.remove( foundTask ); } if ( logger.isTraceEnabled() ) { logger.trace( ""Task with ID={} removed, config {} modified."", task.getId(), foundTask != null ? ""IS"" : ""is NOT"", new Exception( ""This is an exception only to provide caller backtrace"" ) ); } try { applicationConfiguration.saveConfiguration(); } catch ( IOException e ) { logger.warn( ""Could not save task changes!"", e ); } } }"
320,public long writeTo(WritableByteChannel channel) throws IOException { <START> long written = 0; <END> if (!isSendComplete()) { written = channel.write(buffer); } return written; },java return isSendComplete() ? 0 : channel.write(buffer); if want more elegant,public long writeTo(WritableByteChannel channel) throws IOException { return isSendComplete() ? 0 : channel.write(buffer); }
321,"public void delete(final String evalId, @Nullable final EventHandler<AvroElasticMemoryMessage> callback) { final Set<String> dataTypeSet = partitionManager.getDataTypes(evalId); for (final String dataType : dataTypeSet) { final Set<LongRange> rangeSet = partitionManager.getRangeSet(evalId, dataType); if (!rangeSet.isEmpty()) { if (callback != null) { <START> LOG.log(Level.INFO, ""{0}"", rangeSet.size()); <END> final AvroElasticMemoryMessage msg = AvroElasticMemoryMessage.newBuilder() .setType(Type.ResultMsg) .setResultMsg(ResultMsg.newBuilder().setResult(Result.FAILURE).build()) .setSrcId(evalId) .setDestId("""") .build(); callback.onNext(msg); } return; } } if (callback == null) { deleteExecutor.get().execute(evalId, new EventHandler<AvroElasticMemoryMessage>() { @Override public void onNext(final AvroElasticMemoryMessage msg) { } }); } else { deleteExecutor.get().execute(evalId, callback); } }",This change is completely unrelated this PR. reason for adding it,"public void delete(final String evalId, @Nullable final EventHandler<AvroElasticMemoryMessage> callback) { final Set<String> dataTypeSet = partitionManager.getDataTypes(evalId); for (final String dataType : dataTypeSet) { final Set<LongRange> rangeSet = partitionManager.getRangeSet(evalId, dataType); if (!rangeSet.isEmpty()) { if (callback != null) { final AvroElasticMemoryMessage msg = AvroElasticMemoryMessage.newBuilder() .setType(Type.ResultMsg) .setResultMsg(ResultMsg.newBuilder().setResult(Result.FAILURE).build()) .setSrcId(evalId) .setDestId("""") .build(); callback.onNext(msg); } return; } } if (callback == null) { deleteExecutor.get().execute(evalId, new EventHandler<AvroElasticMemoryMessage>() { @Override public void onNext(final AvroElasticMemoryMessage msg) { } }); } else { deleteExecutor.get().execute(evalId, callback); } }"
322,static DownloadType fromString(final String type) { if (type.equalsIgnoreCase(MAP_SKIN.name())) { return MAP_SKIN; } else if (type.equalsIgnoreCase(MAP_TOOL.name())) { return MAP_TOOL; } else { return MAP; <START> } <END> },"of construct? java try { return DownloadType.valueOf(type); } catch (final IllegalArgumentException e) { return MAP; } current code (case-sensitive), a bit cleaner a lot of if-else cases chained",private static DownloadType fromString(final String type) { if (type.equalsIgnoreCase(MAP_SKIN.name())) { return MAP_SKIN; } else if (type.equalsIgnoreCase(MAP_TOOL.name())) { return MAP_TOOL; } else { return MAP; } }
323,"private void decreasePendingVms() { Guid vdsId = getCurrentVdsId(); VM vm = getVm(); if (vdsId == null || vdsId.equals(lastDecreasedVds)) { <START> log.debugFormat(""PendingVms for {0} was already released, not releasing again"", vm.getName()); <END> return; } lastDecreasedVds = vdsId; VmHandler.decreasePendingVms(vm, vdsId); getBlockingQueue(vdsId).offer(Boolean.TRUE); }",printing vdsId? useful in future,"private void decreasePendingVms() { Guid vdsId = getCurrentVdsId(); VM vm = getVm(); if (vdsId == null || vdsId.equals(lastDecreasedVds)) { log.debugFormat(""PendingVms for the guest {0} running on host {1} was already released, not releasing again"", vm.getName(), vdsId); return; } lastDecreasedVds = vdsId; VmHandler.decreasePendingVms(vm, vdsId); getBlockingQueue(vdsId).offer(Boolean.TRUE); }"
324,<START> public void tearDown() { <END> HotRodClientTestingUtil.killServers(hotRodServer); HotRodClientTestingUtil.killRemoteCacheManager(remoteCacheManager); },"Cache manager is leaked here. HR server stop cache manager... avoid leaks, extend existing classes, e.g. SingleHotRodServerTest",public void tearDown() { HotRodClientTestingUtil.killServers(hotRodServer); HotRodClientTestingUtil.killRemoteCacheManager(remoteCacheManager); TestingUtil.killCacheManagers(cacheManager); }
325,public Mono<PollResponse<T>> poll() { <START> return pollOperation.apply(pollResponse.get()) <END> .doOnEach(pollResponseSignal -> { if (pollResponseSignal.get() != null) { pollResponse.set(pollResponseSignal.get()); } }); },ok good for me,public Mono<PollResponse<T>> poll() { return pollOperation.apply(this.pollResponse) .doOnEach(pollResponseSignal -> { if (pollResponseSignal.get() != null) { this.pollResponse = pollResponseSignal.get(); } }); }
326,"private Connection acquireConnection() throws ClassNotFoundException, SQLException { <START> Class.forName(""org.apache.ignite.IgniteJdbcThinDriver""); <END> StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(""jdbc:ignite:thin://""); urlBuilder.append(igniteParameters.getHost()); if (igniteParameters.getPort() != null) { urlBuilder.append("":"" + igniteParameters.getPort()); } if (igniteParameters.getSchema() != null) { urlBuilder.append(""/"" + igniteParameters.getSchema()); } if (igniteParameters.getUser() != null) { urlBuilder.append("";"" + igniteParameters.getUser()); } if (igniteParameters.getPassword() != null) { urlBuilder.append("";"" + igniteParameters.getPassword()); } if (igniteParameters.getAdditionalConfigurations() != null) { urlBuilder.append(igniteParameters.getAdditionalConfigurations()); } return DriverManager.getConnection(urlBuilder.toString()); }","String constant here, move constant file refer there. Eg:- DRIVER_NAME = org.apache.ignite.IgniteJdbcThinDriver;","private Connection acquireConnection() throws ClassNotFoundException, SQLException { Class.forName(IgniteBackendConstants.DRIVER_NAME); StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(IgniteBackendConstants.JDBC_PREFIX); urlBuilder.append(igniteParameters.getHost()); if (igniteParameters.getPort() != null) { urlBuilder.append("":"" + igniteParameters.getPort()); } if (igniteParameters.getSchema() != null) { urlBuilder.append(""/"" + igniteParameters.getSchema()); } if (igniteParameters.getUser() != null) { urlBuilder.append("";"" + igniteParameters.getUser()); } if (igniteParameters.getPassword() != null) { urlBuilder.append("";"" + igniteParameters.getPassword()); } if (igniteParameters.getAdditionalConfigurations() != null) { urlBuilder.append(igniteParameters.getAdditionalConfigurations()); } return DriverManager.getConnection(urlBuilder.toString()); }"
327,"public void testConvertRegion() { DigitalOceanProviderMetadata metadata = new DigitalOceanProviderMetadata(); JustProvider locationsSupplier = new JustProvider(metadata.getId(), Suppliers.<URI> ofInstance(URI .create(metadata.getEndpoint())), ImmutableSet.<String> of()); <START> RegionToLocation function = new RegionToLocation(locationsSupplier); <END> Region region = new Region(1, ""Region 1"", ""reg1""); Location expected = new LocationBuilder().id(""reg1"").description(""1/Region 1"") .parent(getOnlyElement(locationsSupplier.get())).scope(LocationScope.REGION).build(); assertEquals(function.apply(region), expected); }",done in other tests...move function comparison,"public void testConvertRegion() { DigitalOceanProviderMetadata metadata = new DigitalOceanProviderMetadata(); JustProvider locationsSupplier = new JustProvider(metadata.getId(), Suppliers.<URI> ofInstance(URI .create(metadata.getEndpoint())), ImmutableSet.<String> of()); Region region = new Region(1, ""Region 1"", ""reg1""); Location expected = new LocationBuilder().id(""reg1"").description(""1/Region 1"") .parent(getOnlyElement(locationsSupplier.get())).scope(LocationScope.REGION).build(); RegionToLocation function = new RegionToLocation(locationsSupplier); assertEquals(function.apply(region), expected); }"
328,"public static String listUsers(final IEssentials ess, final List<User> users, final String seperator) { final StringBuilder groupString = new StringBuilder(); Collections.sort(users); boolean needComma = false; for (final User user : users) { if (needComma) { groupString.append(seperator); } needComma = true; if (user.isAfk()) { groupString.append(tl(""listAfkTag"")); } if (user.isHidden()) { groupString.append(tl(""listHiddenTag"")); } user.setDisplayNick(); groupString.append(user.getDisplayName()); <START> final String strippedNick = FormatUtil.stripEssentialsFormat(user.getNickname()); <END> if (ess.getSettings().realNamesOnList() && strippedNick != null && !strippedNick.equals(user.getName())) { groupString.append("" ("").append(user.getName()).append("")""); } groupString.append(ChatColor.WHITE.toString()); } return groupString.toString(); }",stripFormat stripEssentialsFormat untranslated color codes afaik? suggestion final String strippedNick = FormatUtil.stripFormat(user.getNickname());,"public static String listUsers(final IEssentials ess, final List<User> users, final String seperator) { final StringBuilder groupString = new StringBuilder(); Collections.sort(users); boolean needComma = false; for (final User user : users) { if (needComma) { groupString.append(seperator); } needComma = true; if (user.isAfk()) { groupString.append(tl(""listAfkTag"")); } if (user.isHidden()) { groupString.append(tl(""listHiddenTag"")); } user.setDisplayNick(); groupString.append(user.getDisplayName()); final String strippedNick = FormatUtil.stripFormat(user.getNickname()); if (ess.getSettings().realNamesOnList() && strippedNick != null && !strippedNick.equals(user.getName())) { groupString.append("" ("").append(user.getName()).append("")""); } groupString.append(ChatColor.WHITE.toString()); } return groupString.toString(); }"
329,"public RollConvention toRollConvention( LocalDate start, LocalDate end, Frequency frequency, boolean preferEndOfMonth) { ArgChecker.notNull(start, ""start""); ArgChecker.notNull(end, ""end""); ArgChecker.notNull(frequency, ""frequency""); if (this == NONE) { if (start.getDayOfMonth() != end.getDayOfMonth() && <START> start.getMonth() != end.getMonth() && <END> (start.getDayOfMonth() == start.lengthOfMonth() || end.getDayOfMonth() == end.lengthOfMonth())) { return RollConvention.ofDayOfMonth(Math.max(start.getDayOfMonth(), end.getDayOfMonth())); } } if (isCalculateBackwards()) { return impliedRollConvention(end, start, frequency, preferEndOfMonth); } else { return impliedRollConvention(start, end, frequency, preferEndOfMonth); } }","This odder test before. A schedule July July handled differently July August. existing code, block check preferEndOfMonth return EOM if true","public RollConvention toRollConvention( LocalDate start, LocalDate end, Frequency frequency, boolean preferEndOfMonth) { ArgChecker.notNull(start, ""start""); ArgChecker.notNull(end, ""end""); ArgChecker.notNull(frequency, ""frequency""); if (this == NONE) { if (start.getDayOfMonth() != end.getDayOfMonth() && start.getLong(PROLEPTIC_MONTH) != end.getLong(PROLEPTIC_MONTH) && (start.getDayOfMonth() == start.lengthOfMonth() || end.getDayOfMonth() == end.lengthOfMonth())) { return preferEndOfMonth ? RollConventions.EOM : RollConvention.ofDayOfMonth(Math.max(start.getDayOfMonth(), end.getDayOfMonth())); } } if (isCalculateBackwards()) { return impliedRollConvention(end, start, frequency, preferEndOfMonth); } else { return impliedRollConvention(start, end, frequency, preferEndOfMonth); } }"
330,"public void addDataFile(MockDataFile dataFileSource) { List<String> columnNames = dataFileSource.getColumnNames(); for (String column : columnNames) { MockChartData2D data = new MockChartData2D(editor); addComponent(data); <START> data.addToChart(MockChart.this); <END> data.changeProperty(""DataFileYColumn"", column); data.changeProperty(""Label"", column); data.changeProperty(""Source"", dataFileSource.getName()); } }",Is qualifying this necessary? context MockChart already,"public void addDataFile(MockDataFile dataFileSource) { List<String> columnNames = dataFileSource.getColumnNames(); for (String column : columnNames) { MockChartData2D data = new MockChartData2D(editor); addComponent(data); data.addToChart(this); data.changeProperty(""DataFileYColumn"", column); data.changeProperty(""Label"", column); data.changeProperty(""Source"", dataFileSource.getName()); } }"
331,"protected static boolean isRingTimeFromNextSmartAlarm(final DateTime currentTimeAlignedToStartOfMinute, final RingTime nextRingTimeFromWorker){ <START> final boolean alarmNotYetRing = currentTimeAlignedToStartOfMinute.isAfter(nextRingTimeFromWorker.actualRingTimeUTC) == false; <END> final boolean isProcessedSmartAlarm = nextRingTimeFromWorker.processed(); return alarmNotYetRing && isProcessedSmartAlarm; }",this variable english :wink:,"protected static boolean isRingTimeFromNextSmartAlarm(final DateTime currentTimeAlignedToStartOfMinute, final RingTime nextRingTimeFromWorker){ final boolean isNextSmartAlarm = currentTimeAlignedToStartOfMinute.isAfter(nextRingTimeFromWorker.actualRingTimeUTC) == false; final boolean isProcessedSmartAlarm = nextRingTimeFromWorker.processed(); return isNextSmartAlarm && isProcessedSmartAlarm; }"
332,"<START> public String getLocalPath(IJavaBreakpoint bp) throws CoreException { <END> if (bp.getMarker() != null && bp.getMarker().getResource() != null && bp.getMarker().getResource().getType() == IResource.FILE) { String type = bp.getTypeName(); if (type != null) { String pkg = (type.lastIndexOf('.') >= 0 ? (type.substring(0, type.lastIndexOf('.')) + ""/"") : """").replace('.', '/'); return pkg + bp.getMarker().getResource().getName(); } } return null; }","method need public. If so, please visibility 'private'","private String getLocalPath(IJavaBreakpoint bp) throws CoreException { if (bp.getMarker() != null && bp.getMarker().getResource() != null && bp.getMarker().getResource().getType() == IResource.FILE) { String type = bp.getTypeName(); if (type != null) { String pkg = (type.lastIndexOf('.') >= 0 ? (type.substring(0, type.lastIndexOf('.')) + ""/"") : """").replace('.', '/'); return pkg + bp.getMarker().getResource().getName(); } } return null; }"
333,"public void updateConfigSetLastUpdateDownloadStatus_getValueByReflection_correctValue() { UpdateConfig updateConfig = new UpdateConfig(); try { Class<?> updateConfigClass = updateConfig.getClass(); Field lastUpdateDownloadStatusField = updateConfigClass.getDeclaredField(""lastUpdateDownloadStatus""); lastUpdateDownloadStatusField.setAccessible(true); updateConfig.setLastUpdateDownloadStatus(true); assertTrue((boolean) lastUpdateDownloadStatusField.get(updateConfig)); updateConfig.setLastUpdateDownloadStatus(false); assertFalse((boolean) lastUpdateDownloadStatusField.get(updateConfig)); <START> } catch (NoSuchFieldException e) { <END> fail(""No field lastUpdateDownloadStatus.""); } catch (IllegalAccessException e) { fail(""Can't access field lastUpdateDownloadStatus""); } }",exceptions method signature I think. Removes some clutter,"public void updateConfigSetLastUpdateDownloadStatus_getValueByReflection_correctValue() throws NoSuchFieldException, IllegalAccessException { UpdateConfig updateConfig = new UpdateConfig(); Class<?> updateConfigClass = updateConfig.getClass(); Field isLastAppUpdateDownloadSuccessfulField = updateConfigClass.getDeclaredField(""isLastAppUpdateDownloadSuccessful""); isLastAppUpdateDownloadSuccessfulField.setAccessible(true); updateConfig.setLastAppUpdateDownloadSuccessful(true); assertTrue((boolean) isLastAppUpdateDownloadSuccessfulField.get(updateConfig)); updateConfig.setLastAppUpdateDownloadSuccessful(false); assertFalse((boolean) isLastAppUpdateDownloadSuccessfulField.get(updateConfig)); }"
334,"public FormValidation doCheckTargetLogIntakeURL(@QueryParameter(""targetLogIntakeURL"") final String targetLogIntakeURL) { <START> if (StringUtils.isNotBlank(targetApiURL) && !DatadogHttpClient.validateTargetURL(targetLogIntakeURL) && collectBuildLogs) { <END> return FormValidation.error(""The field must be configured in the form <http|https>://<url>/""); } return FormValidation.ok(""Valid URL""); }","Ditto here, need move validation DatadogHttpClient","public FormValidation doCheckTargetLogIntakeURL(@QueryParameter(""targetLogIntakeURL"") final String targetLogIntakeURL) { if (!validateURL(targetLogIntakeURL) && collectBuildLogs) { return FormValidation.error(""The field must be configured in the form <http|https>://<url>/""); } return FormValidation.ok(""Valid URL""); }"
335,"public void testNormalizedUrl() throws IOException { <START> int port = 8000 + new Random().nextInt(1000); <END> HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); server.createContext( ""/"", new HttpHandler() { @Override public void handle(HttpExchange httpExchange) throws IOException { byte[] response = httpExchange.getRequestURI().toString().getBytes(); httpExchange.sendResponseHeaders(200, response.length); OutputStream os = httpExchange.getResponseBody(); os.write(response); os.close(); } }); server.start(); ApacheHttpTransport transport = new ApacheHttpTransport(); com.google.api.client.http.HttpResponse response = transport .createRequestFactory() .buildGetRequest(new GenericUrl(""http://localhost:"" + port + ""/foo .execute(); assertEquals(200, response.getStatusCode()); assertEquals(""/foo }",find unused port? This hit 8080 is occupied,"public void testNormalizedUrl() throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(0), 0); server.createContext( ""/"", new HttpHandler() { @Override public void handle(HttpExchange httpExchange) throws IOException { byte[] response = httpExchange.getRequestURI().toString().getBytes(); httpExchange.sendResponseHeaders(200, response.length); try (OutputStream out = httpExchange.getResponseBody()) { out.write(response); } } }); server.start(); ApacheHttpTransport transport = new ApacheHttpTransport(); GenericUrl testUrl = new GenericUrl(""http://localhost/foo testUrl.setPort(server.getAddress().getPort()); com.google.api.client.http.HttpResponse response = transport .createRequestFactory() .buildGetRequest(testUrl) .execute(); assertEquals(200, response.getStatusCode()); assertEquals(""/foo }"
336,"public List<CloudResourceStatus> terminate(AuthenticatedContext ac, CloudStack stack, List<CloudResource> resources) { AzureClient client = ac.getParameter(AzureClient.class); String resourceGroupName = azureResourceGroupMetadataProvider.getResourceGroupName(ac.getCloudContext(), stack); Boolean singleResourceGroup = azureResourceGroupMetadataProvider.useSingleResourceGroup(stack); if (singleResourceGroup) { List<CloudResource> cloudResourceList = collectResourcesToRemove(ac, stack, resources, azureUtils.getInstanceList(stack)); resources.addAll(cloudResourceList); azureTerminationHelperService.terminate(ac, stack, resources); return check(ac, Collections.emptyList()); } else { try { try { <START> retryService.testWith2SecDelayMax5Times(() -> { if (!client.resourceGroupExists(resourceGroupName)) { throw new ActionFailedException(""Resource group not exists""); } return true; }); <END> client.deleteResourceGroup(resourceGroupName); } catch (ActionFailedException ignored) { LOGGER.debug(""Resource group not found with name: {}"", resourceGroupName); } } catch (CloudException e) { if (e.response().code() != AzureConstants.NOT_FOUND) { throw new CloudConnectorException(String.format(""Could not delete resource group: %s"", resourceGroupName), e); } else { return check(ac, Collections.emptyList()); } } return check(ac, resources); } }",This part AzureUtils,"public List<CloudResourceStatus> terminate(AuthenticatedContext ac, CloudStack stack, List<CloudResource> resources) { AzureClient client = ac.getParameter(AzureClient.class); String resourceGroupName = azureResourceGroupMetadataProvider.getResourceGroupName(ac.getCloudContext(), stack); Boolean singleResourceGroup = azureResourceGroupMetadataProvider.useSingleResourceGroup(stack); if (singleResourceGroup) { List<CloudResource> cloudResourceList = collectResourcesToRemove(ac, stack, resources, azureUtils.getInstanceList(stack)); resources.addAll(cloudResourceList); azureTerminationHelperService.terminate(ac, stack, resources); return check(ac, Collections.emptyList()); } else { try { try { azureUtils.checkResourceGroupExistence(client, resourceGroupName); client.deleteResourceGroup(resourceGroupName); } catch (ActionFailedException ignored) { LOGGER.debug(""Resource group not found with name: {}"", resourceGroupName); } } catch (CloudException e) { if (e.response().code() != AzureConstants.NOT_FOUND) { throw new CloudConnectorException(String.format(""Could not delete resource group: %s"", resourceGroupName), e); } else { return check(ac, Collections.emptyList()); } } return check(ac, resources); } }"
337,"protected List<SurveyGroupDto> parseSurveyGroups(String response) throws Exception { List<SurveyGroupDto> dtoList = new ArrayList<SurveyGroupDto>(); JSONArray jsonArray = getJsonArray(response); if (jsonArray == null) { return dtoList; } for (int i = 0; i < jsonArray.length(); i++) { JSONObject o = jsonArray.getJSONObject(i); if (o != null) { try { SurveyGroupDto dto = new SurveyGroupDto(); <START> if (o.has(""name"") && o.isNull(""name"")) { <END> dto.setName(o.getString(""name"")); } if (!o.has(""monitoringGroup"") || o.isNull(""monitoringGroup"")) { dto.setMonitoringGroup(false); } else { dto.setMonitoringGroup(o.getBoolean(""monitoringGroup"")); } dtoList.add(dto); } catch (Exception e) { System.out.println(""Error in json parsing: "" + e.getMessage()); e.printStackTrace(); } } } return dtoList; }","I guess !o.isNull(""name"")? enough. need for o.has(""name"")","protected List<SurveyGroupDto> parseSurveyGroups(String response) throws Exception { List<SurveyGroupDto> dtoList = new ArrayList<SurveyGroupDto>(); JSONArray jsonArray = getJsonArray(response); if (jsonArray == null) { return dtoList; } for (int i = 0; i < jsonArray.length(); i++) { JSONObject o = jsonArray.getJSONObject(i); if (o != null) { try { SurveyGroupDto dto = new SurveyGroupDto(); if (!o.isNull(""name"")) { dto.setName(o.getString(""name"")); } if (o.isNull(""monitoringGroup"")) { dto.setMonitoringGroup(false); } else { dto.setMonitoringGroup(o.getBoolean(""monitoringGroup"")); } dtoList.add(dto); } catch (Exception e) { System.out.println(""Error in json parsing: "" + e.getMessage()); e.printStackTrace(); } } } return dtoList; }"
338,"public Map<String, String> connectorConfig(String connName) { FutureCallback<Map<String, String>> connectorConfigCallback = new FutureCallback<>(); herder.connectorConfig(connName, connectorConfigCallback); try { <START> Map<String, String> result = connectorConfigCallback.get(herderRequestTimeoutMs, TimeUnit.MILLISECONDS); return new HashMap<>(result); <END> } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new ConnectException( String.format(""Failed to retrieve configuration for connector '%s'"", connName), e ); } }","suggestion return new HashMap<>(connectorConfigCallback.get(herderRequestTimeoutMs, TimeUnit.MILLISECONDS););","public Map<String, String> connectorConfig(String connName) { FutureCallback<Map<String, String>> connectorConfigCallback = new FutureCallback<>(); herder.connectorConfig(connName, connectorConfigCallback); try { return new HashMap<>(connectorConfigCallback.get(herderRequestTimeoutMs, TimeUnit.MILLISECONDS)); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new ConnectException( String.format(""Failed to retrieve configuration for connector '%s'"", connName), e ); } }"
339,protected void refreshASTSettingsActions() { boolean enabled; switch (getCurrentInputKind()) { case ASTInputKindAction.USE_CACHE: enabled= false; break; default: enabled= true; break; } fCreateBindingsAction.setEnabled(enabled && getCurrentInputKind() != ASTInputKindAction.USE_RECONCILE); fStatementsRecoveryAction.setEnabled(enabled); fBindingsRecoveryAction.setEnabled(enabled); fIgnoreMethodBodiesAction.setEnabled(enabled); for (ASTView.ASTLevelToggle <START> astVersionToggleAction : <END> fASTVersionToggleActions) { astVersionToggleAction.setEnabled(enabled); } },rename action,protected void refreshASTSettingsActions() { boolean enabled; switch (getCurrentInputKind()) { case ASTInputKindAction.USE_CACHE: enabled= false; break; default: enabled= true; break; } fCreateBindingsAction.setEnabled(enabled && getCurrentInputKind() != ASTInputKindAction.USE_RECONCILE); fStatementsRecoveryAction.setEnabled(enabled); fBindingsRecoveryAction.setEnabled(enabled); fIgnoreMethodBodiesAction.setEnabled(enabled); for (ASTView.ASTLevelToggle action : fASTVersionToggleActions) { action.setEnabled(enabled); } }
340,"protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { MultiMap<String, GoImportSpec> importMap = file.getImportMap(); for (PsiElement importIdentifier : GoImportOptimizer.findRedundantImportIdentifiers(importMap)) { problemsHolder.registerProblem(importIdentifier, ""Redundant alias"", ProblemHighlightType.LIKE_UNUSED_SYMBOL, OPTIMIZE_QUICK_FIX); } Set<GoImportSpec> duplicatedEntries = GoImportOptimizer.findDuplicatedEntries(importMap); for (GoImportSpec duplicatedImportSpec : duplicatedEntries) { problemsHolder.registerProblem(duplicatedImportSpec, ""Redeclared import"", ProblemHighlightType.GENERIC_ERROR, OPTIMIZE_QUICK_FIX); } for (Map.Entry<String, Collection<GoImportSpec>> specs : importMap.entrySet()) { <START> if (""."".equals(specs.getKey()) || ""_"".equals(specs.getKey())) { <END> continue; } Iterator<GoImportSpec> imports = specs.getValue().iterator(); imports.next(); while (imports.hasNext()) { GoImportSpec redeclaredImport = imports.next(); if (!duplicatedEntries.contains(redeclaredImport)) { problemsHolder.registerProblem(redeclaredImport, ""Redeclared import"", ProblemHighlightType.GENERIC_ERROR); } } } if (!problemsHolder.isOnTheFly()) { resolveAllReferences(file); } for (PsiElement importEntry : GoImportOptimizer.filterUnusedImports(file, importMap).values()) { GoImportSpec spec = GoImportOptimizer.getImportSpec(importEntry); if (spec != null) { if (spec.getImportString().resolve() != null) { problemsHolder.registerProblem(spec, ""Unused import"", ProblemHighlightType.GENERIC_ERROR, OPTIMIZE_QUICK_FIX); } } } }",Please reimplement invoking isDot isForSideEffects imports.next() object,"protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { MultiMap<String, GoImportSpec> importMap = file.getImportMap(); for (PsiElement importIdentifier : GoImportOptimizer.findRedundantImportIdentifiers(importMap)) { problemsHolder.registerProblem(importIdentifier, ""Redundant alias"", ProblemHighlightType.LIKE_UNUSED_SYMBOL, OPTIMIZE_QUICK_FIX); } Set<GoImportSpec> duplicatedEntries = GoImportOptimizer.findDuplicatedEntries(importMap); for (GoImportSpec duplicatedImportSpec : duplicatedEntries) { problemsHolder.registerProblem(duplicatedImportSpec, ""Redeclared import"", ProblemHighlightType.GENERIC_ERROR, OPTIMIZE_QUICK_FIX); } for (Map.Entry<String, Collection<GoImportSpec>> specs : importMap.entrySet()) { Iterator<GoImportSpec> imports = specs.getValue().iterator(); GoImportSpec originalImport = imports.next(); if (originalImport.isDot() || originalImport.isForSideEffects()) { continue; } while (imports.hasNext()) { GoImportSpec redeclaredImport = imports.next(); if (!duplicatedEntries.contains(redeclaredImport)) { problemsHolder.registerProblem(redeclaredImport, ""Redeclared import"", ProblemHighlightType.GENERIC_ERROR); } } } if (!problemsHolder.isOnTheFly()) { resolveAllReferences(file); } for (PsiElement importEntry : GoImportOptimizer.filterUnusedImports(file, importMap).values()) { GoImportSpec spec = GoImportOptimizer.getImportSpec(importEntry); if (spec != null) { if (spec.getImportString().resolve() != null) { problemsHolder.registerProblem(spec, ""Unused import"", ProblemHighlightType.GENERIC_ERROR, OPTIMIZE_QUICK_FIX); } } } }"
341,"public boolean validate() { boolean isNew = getModel().getIsNew(); int maxAllowedVms = getMaxVmsInPool(); int assignedVms = getModel().getAssignedVms().asConvertible().integer(); getModel().getNumOfDesktops().validateEntity( new IValidation[] { new NotEmptyValidation(), new LengthValidation(4), new IntegerValidation(isNew ? 1 : 0, isNew ? maxAllowedVms : maxAllowedVms - assignedVms) }); getModel().getPrestartedVms().validateEntity( new IValidation[] { new NotEmptyValidation(), new IntegerValidation(0, assignedVms) }); getModel().getMaxAssignedVmsPerUser().validateEntity( new IValidation[] { new NotEmptyValidation(), <START> new IntegerValidation(1, 1000000) <END> }); getModel().setIsGeneralTabValid(getModel().getIsGeneralTabValid() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid() && getModel().getMaxAssignedVmsPerUser().getIsValid()); getModel().setIsPoolTabValid(true); return super.validate() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid() && getModel().getMaxAssignedVmsPerUser().getIsValid(); }",please Short.MAX_VALUE,"public boolean validate() { boolean isNew = getModel().getIsNew(); int maxAllowedVms = getMaxVmsInPool(); int assignedVms = getModel().getAssignedVms().asConvertible().integer(); getModel().getNumOfDesktops().validateEntity( new IValidation[] { new NotEmptyValidation(), new LengthValidation(4), new IntegerValidation(isNew ? 1 : 0, isNew ? maxAllowedVms : maxAllowedVms - assignedVms) }); getModel().getPrestartedVms().validateEntity( new IValidation[] { new NotEmptyValidation(), new IntegerValidation(0, assignedVms) }); getModel().getMaxAssignedVmsPerUser().validateEntity( new IValidation[] { new NotEmptyValidation(), new IntegerValidation(1, Short.MAX_VALUE) }); getModel().setIsGeneralTabValid(getModel().getIsGeneralTabValid() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid() && getModel().getMaxAssignedVmsPerUser().getIsValid()); getModel().setIsPoolTabValid(true); return super.validate() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid() && getModel().getMaxAssignedVmsPerUser().getIsValid(); }"
342,"public void failed(final Exception ex) { <START> LOG.log(Level.WARNING, ""Dashboard: Post request failed - "", ex); <END> }",purpose of trailing - in logging msgs,"public void failed(final Exception ex) { LOG.log(Level.WARNING, ""Dashboard: Post request failed."", ex); }"
343,"public void the_user_clicks_on_the_button(String text) throws Throwable { List<WebElement> buttons = getDriver().findElements(By.tagName(""button"")); WebDriverWait webDriverWait = new WebDriverWait(getDriver(), TIMEOUT); WebElement elem = webDriverWait.until(elementToBeClickable( buttons.stream().filter(button -> button.getText().equals(text)).findFirst().get())); elem.click(); <START> waitForAjax(); <END> }",I Pagefactory AjaxElementLocatorFactory for this,"public void the_user_clicks_on_the_button(String text) { List<WebElement> buttons = getDriver().findElements(By.tagName(""button"")); WebElement element = DriverProvider.wait(getDriver()).until(elementToBeClickable( buttons.stream().filter(button -> button.getText().equals(text)).findFirst().get())); element.click(); waitForAjax(); }"
344,"public void testTimeoutViaSystemProperty() throws Exception { System.setProperty(""org.jbpm.cxf.client.connectionTimeout"", ""10""); System.setProperty(""org.jbpm.cxf.client.receiveTimeout"", ""10""); try { KieBase kbase = readKnowledgeBase(); KieSession ksession = createSession(kbase); ksession.getWorkItemManager().registerWorkItemHandler(""Service Task"", new WebServiceWorkItemHandler(ksession)); Map<String, Object> params = new HashMap<String, Object>(); params.put(""s"", ""john""); params.put(""mode"", ""sync""); WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession.startProcess(""org.jboss.qa.jbpm.CallWS"", params); fail(""should throw Read Timeout error""); } catch (Exception e) { <START> assertTrue(true); <END> } finally { System.clearProperty(""org.jbpm.cxf.client.connectionTimeout""); System.clearProperty(""org.jbpm.cxf.client.receiveTimeout""); } }","please assert exception, is timeout error message","public void testTimeoutViaSystemProperty() throws Exception { System.setProperty(""org.jbpm.cxf.client.connectionTimeout"", ""10""); System.setProperty(""org.jbpm.cxf.client.receiveTimeout"", ""10""); try { KieBase kbase = readKnowledgeBase(); KieSession ksession = createSession(kbase); ksession.getWorkItemManager().registerWorkItemHandler(""Service Task"", new WebServiceWorkItemHandler(ksession)); Map<String, Object> params = new HashMap<String, Object>(); params.put(""s"", ""john""); params.put(""mode"", ""sync""); WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession.startProcess(""org.jboss.qa.jbpm.CallWS"", params); fail(""should throw Read Timeout error""); } catch (Exception e) { assertTrue(isCausedBySocketTimeoutException(e)); } finally { System.clearProperty(""org.jbpm.cxf.client.connectionTimeout""); System.clearProperty(""org.jbpm.cxf.client.receiveTimeout""); } }"
345,"protected void handleGroupedCounterAspect(ITmfEvent event, ITmfStateSystemBuilder ss, CounterAspect aspect, int rootQuark) { int quark = rootQuark; for (Class<? extends ITmfEventAspect<?>> groupClass : aspect.getGroups()) { ITmfEventAspect<?> parentAspect = fAspectImpls.get(groupClass); if (parentAspect != null) { quark = ss.getQuarkRelativeAndAdd(quark, parentAspect.getName()); quark = ss.getQuarkRelativeAndAdd(quark, <START> String.valueOf(parentAspect.resolve(event))); <END> } } handleCounterAspect(event, ss, aspect, quark); }","this ""mutliAspect"" ? aspects resolve null String ""null"", is expected behavior","protected void handleGroupedCounterAspect(ITmfEvent event, ITmfStateSystemBuilder ss, CounterAspect aspect, int rootQuark) { int quark = rootQuark; for (Class<? extends ITmfEventAspect<?>> groupClass : aspect.getGroups()) { ITmfEventAspect<?> parentAspect = fAspectImpls.get(groupClass); if (parentAspect != null) { Object parentAspectContent = parentAspect.resolve(event); if (parentAspectContent != null) { quark = ss.getQuarkRelativeAndAdd(quark, parentAspect.getName()); quark = ss.getQuarkRelativeAndAdd(quark, String.valueOf(parentAspectContent)); } else { return; } } } handleCounterAspect(event, ss, aspect, quark); }"
346,"private io.fabric8.kubernetes.api.model.Container addContainer( Pod toolingPod, String image, List<EnvVar> env, ResourceRequirements resources) { io.fabric8.kubernetes.api.model.Container container = new ContainerBuilder() .withImage(image) <START> .withName(Names.generateName("""")) <END> .withEnv(toK8sEnv(env)) .withResources(toK8sResources(resources)) .build(); toolingPod.getSpec().getContainers().add(container); return container; }","sense add some meaningful prefix ""tooling""","private io.fabric8.kubernetes.api.model.Container addContainer( Pod toolingPod, String image, List<EnvVar> env, ResourceRequirements resources) { io.fabric8.kubernetes.api.model.Container container = new ContainerBuilder() .withImage(image) .withName(Names.generateName(""tooling"")) .withEnv(toK8sEnv(env)) .withResources(toK8sResources(resources)) .build(); toolingPod.getSpec().getContainers().add(container); return container; }"
347,"public TreeSet<T> addAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, ""elements is null""); <START> if (Collections.isEmpty(elements) || this.equals(elements)){ <END> return this; } RedBlackTree<T> that = tree; for (T element : elements) { if (!that.contains(element)) { that = that.insert(element); } } return new TreeSet<>(that); }",A TreeSet is a SortedSet. check for equality insertion depends underlying Comparator. Please restore previous version,"public TreeSet<T> addAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, ""elements is null""); RedBlackTree<T> that = tree; for (T element : elements) { if (!that.contains(element)) { that = that.insert(element); } } if (tree == that) { return this; } else { return new TreeSet<>(that); } }"
348,"public UniqueConstraintDetails(Label label, String property) { <START> super(); <END> this.label = label; this.property = property; }",remove useless super(),"public UniqueConstraintDetails(Label label, String property) { this.label = label; this.property = property; }"
349,@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); cfg.setIncludeEventTypes(EventType.EVTS_ALL); if (indexingDisabled) { GridQueryProcessor.idxCls = DummyQueryIndexing.class; <START> cfg.setSystemViewExporterSpi(new JmxSystemViewExporterSpi() { <END> @Override protected void register(SystemView<?> sysView) { } }); } return cfg; },fix SqlViewExporterSpi instead of excluding (looks a bug in implementation),@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); cfg.setIncludeEventTypes(EventType.EVTS_ALL); if (indexingDisabled) GridQueryProcessor.idxCls = DummyQueryIndexing.class; return cfg; }
350,"private void updateCounter(ISegment segment) { ITmfStateSystemBuilder ss = getStateSystemBuilder(); assertNotNull(ss); try { <START> int quark = ss.getQuarkAbsoluteAndAdd(TmfPatternSegmentManagerTest.COUNTER_STRING, ((TmfXmlPatternSegment) segment).getName().substring(4)); <END> ss.incrementAttribute(segment.getStart(), quark); } catch (StateValueTypeException | AttributeNotFoundException e) { e.printStackTrace(); } }","This class is this constant instead test class refer it. in state provider, in analysis","private void updateCounter(ISegment segment) { ITmfStateSystemBuilder ss = getStateSystemBuilder(); assertNotNull(ss); try { int quark = ss.getQuarkAbsoluteAndAdd(TmfXmlPatternSegmentBaseAnalysisForTest.COUNTER_STRING, ((TmfXmlPatternSegment) segment).getName().substring(4)); ss.incrementAttribute(segment.getStart(), quark); } catch (StateValueTypeException | AttributeNotFoundException e) { fail(""Failed to update the counter for segment "" + ((TmfXmlPatternSegment)segment).getName()); } }"
351,"static void handleHyperloglogLog2mOverride(BrokerRequest brokerRequest, int hllLog2mOverride) { if (brokerRequest.getAggregationsInfo() != null) { for (AggregationInfo aggregationInfo : brokerRequest.getAggregationsInfo()) { switch (AggregationFunctionType.valueOf(aggregationInfo.getAggregationType().toUpperCase())) { case DISTINCTCOUNTHLL: case DISTINCTCOUNTHLLMV: case DISTINCTCOUNTRAWHLL: case DISTINCTCOUNTRAWHLLMV: if (aggregationInfo.getExpressionsSize() == 1) { aggregationInfo.addToExpressions(Integer.toString(hllLog2mOverride)); } } } } <START> if (brokerRequest.getPinotQuery() != null && brokerRequest.getSelections() != null) { <END> for (Expression expr : brokerRequest.getPinotQuery().getSelectList()) { updateDistinctCountHllExpr(expr, hllLog2mOverride); } } }",do need brokerRequest.getSelections() != null here? true for aggregation right,"static void handleHyperloglogLog2mOverride(BrokerRequest brokerRequest, int hllLog2mOverride) { if (brokerRequest.getAggregationsInfo() != null) { for (AggregationInfo aggregationInfo : brokerRequest.getAggregationsInfo()) { switch (aggregationInfo.getAggregationType().toUpperCase()) { case ""DISTINCTCOUNTHLL"": case ""DISTINCTCOUNTHLLMV"": case ""DISTINCTCOUNTRAWHLL"": case ""DISTINCTCOUNTRAWHLLMV"": if (aggregationInfo.getExpressionsSize() == 1) { aggregationInfo.addToExpressions(Integer.toString(hllLog2mOverride)); } } } } if (brokerRequest.getPinotQuery() != null && brokerRequest.getPinotQuery().getSelectList() != null) { for (Expression expr : brokerRequest.getPinotQuery().getSelectList()) { updateDistinctCountHllExpr(expr, hllLog2mOverride); } } }"
352,<START> public static synchronized BrandingManager getInstance() { <END> if (instance == null) { instance = new BrandingManager(); } return instance; },"point in synchronizing entire getInstance() (read+write), synchronizing 'write' instance",public static BrandingManager getInstance() { return getInstance(EngineLocalConfig.getInstance().getEtcDir()); }
353,"public static void setParamsWithRegistrationConfigurationMappings(RegistrationConfiguration registrationConfiguration, ImportFromConfParameters params) { if (registrationConfiguration.getAffinityGroupMappings() != null && registrationConfiguration.isSetAffinityGroupMappings()) { Map<String, Object> affinityGroupMap = new HashMap<>(); affinityGroupMap.put(AFFINITY_GROUP_KEY, mapAffinityGroupMapping(registrationConfiguration.getAffinityGroupMappings())); <START> params.setAffinityGroupMap(affinityGroupMap); <END> } if (registrationConfiguration.getAffinityLabelMappings() != null && registrationConfiguration.isSetAffinityLabelMappings()) { Map<String, Object> affinityLabelMap = new HashMap<>(); affinityLabelMap.put(AFFINITY_LABEL_KEY, mapAffinityLabelMapping(registrationConfiguration.getAffinityLabelMappings())); params.setAffinityLabelMap(affinityLabelMap); } if (registrationConfiguration.getClusterMappings() != null && registrationConfiguration.isSetClusterMappings()) { Map<String, Object> clusterMap = new HashMap<>(); clusterMap.put(CLUSTER_KEY, mapClusterMapping(registrationConfiguration.getClusterMappings())); params.setClusterMap(clusterMap); } if (registrationConfiguration.getLunMapping() != null && registrationConfiguration.isSetLunMapping()) { Map<String, Object> lunMap = new HashMap<>(); lunMap.put(EXTERNAL_LUN_KEY, mapExternalLunMapping(registrationConfiguration.getLunMapping())); params.setExternalLunMap(lunMap); } if (registrationConfiguration.getRoleMappings() != null && registrationConfiguration.isSetRoleMappings()) { Map<String, Object> roleMap = new HashMap<>(); roleMap.put(ROLE_KEY, mapExternalRoleMapping(registrationConfiguration.getRoleMappings())); params.setRoleMap(roleMap); } if (registrationConfiguration.getDomainMappings() != null && registrationConfiguration.isSetDomainMappings()) { Map<String, Object> domainMap = new HashMap<>(); domainMap.put(DOMAIN_KEY, mapExternalDomainMapping(registrationConfiguration.getDomainMappings())); params.setDomainMap(domainMap); } }","If I understand correctly *_KEY strings needed now, want do is pass ""params.setAffinityGroupMap"" result of ""mapAffinityGroupMapping"": params.setAffinityGroupMap(mapAffinityGroupMapping(...)); I missing","public static void setParamsWithRegistrationConfigurationMappings(RegistrationConfiguration registrationConfiguration, ImportFromConfParameters params) { if (registrationConfiguration.getAffinityGroupMappings() != null && registrationConfiguration.isSetAffinityGroupMappings()) { params.setAffinityGroupMap(mapAffinityGroupMapping(registrationConfiguration.getAffinityGroupMappings())); } if (registrationConfiguration.getAffinityLabelMappings() != null && registrationConfiguration.isSetAffinityLabelMappings()) { params.setAffinityLabelMap(mapAffinityLabelMapping(registrationConfiguration.getAffinityLabelMappings())); } if (registrationConfiguration.getClusterMappings() != null && registrationConfiguration.isSetClusterMappings()) { params.setClusterMap(mapClusterMapping(registrationConfiguration.getClusterMappings())); } if (registrationConfiguration.getLunMappings() != null && registrationConfiguration.isSetLunMappings()) { params.setExternalLunMap(mapExternalLunMapping(registrationConfiguration.getLunMappings())); } if (registrationConfiguration.getRoleMappings() != null && registrationConfiguration.isSetRoleMappings()) { params.setRoleMap(mapExternalRoleMapping(registrationConfiguration.getRoleMappings())); } if (registrationConfiguration.getDomainMappings() != null && registrationConfiguration.isSetDomainMappings()) { params.setDomainMap(mapExternalDomainMapping(registrationConfiguration.getDomainMappings())); } }"
354,<START> private Object borrow(GenericObjectPool pool) { <END> try { return pool.borrowObject(); } catch (Exception e) { throw new ParquetCompressionCodecException(e); } },"generic do cast with: @SuppressWarning(""unchecked"") <T> T borrow(GenericObjectPool pool) { ... return (T) ... ... }",public <T> T borrow(GenericObjectPool pool) { try { return (T) pool.borrowObject(); } catch (Exception e) { throw new ParquetCompressionCodecException(e); } }
355,"public void onUpdateBalances(Coin availableBalance, Coin availableNonBsqBalance, Coin unverifiedBalance, Coin unconfirmedChangeBalance, Coin lockedForVotingBalance, Coin lockupBondsBalance, Coin unlockingBondsBalance) { boolean isNonBsqBalanceAvailable = availableNonBsqBalance.value > 0; availableBalanceTextField.setText(bsqFormatter.formatCoinWithCode(availableBalance)); Coin verified = availableBalance.subtract(unconfirmedChangeBalance); verifiedBalanceTextField.setText(bsqFormatter.formatCoinWithCode(verified)); unconfirmedChangTextField.setText(bsqFormatter.formatCoinWithCode(unconfirmedChangeBalance)); unverifiedBalanceTextField.setText(bsqFormatter.formatCoinWithCode(unverifiedBalance)); lockedForVoteBalanceTextField.setText(bsqFormatter.formatCoinWithCode(lockedForVotingBalance)); lockedInBondsBalanceTextField.setText(bsqFormatter.formatCoinWithCode( lockupBondsBalance.add(unlockingBondsBalance))); if (lockupAmountTextField != null && unlockingAmountTextField != null) { lockupAmountTextField.setText(bsqFormatter.formatCoinWithCode(lockupBondsBalance)); unlockingAmountTextField.setText(bsqFormatter.formatCoinWithCode(unlockingBondsBalance)); } availableNonBsqBalanceLabel.setVisible(isNonBsqBalanceAvailable); availableNonBsqBalanceLabel.setManaged(isNonBsqBalanceAvailable); availableNonBsqBalanceTextField.setVisible(isNonBsqBalanceAvailable); availableNonBsqBalanceTextField.setManaged(isNonBsqBalanceAvailable); availableNonBsqBalanceTextField.setText(bsqFormatter.formatBTCWithCode(availableNonBsqBalance.value)); <START> reputationBalanceTextField.setText(bsqFormatter.formatBSQSatoshisWithCode(myBlindVoteListService.getCurrentlyAvailableMerit())); <END> }",I more DaoFacade.getAvailableMerit() super important,"public void onUpdateBalances(Coin availableBalance, Coin availableNonBsqBalance, Coin unverifiedBalance, Coin unconfirmedChangeBalance, Coin lockedForVotingBalance, Coin lockupBondsBalance, Coin unlockingBondsBalance) { boolean isNonBsqBalanceAvailable = availableNonBsqBalance.value > 0; availableBalanceTextField.setText(bsqFormatter.formatCoinWithCode(availableBalance)); Coin verified = availableBalance.subtract(unconfirmedChangeBalance); verifiedBalanceTextField.setText(bsqFormatter.formatCoinWithCode(verified)); unconfirmedChangTextField.setText(bsqFormatter.formatCoinWithCode(unconfirmedChangeBalance)); unverifiedBalanceTextField.setText(bsqFormatter.formatCoinWithCode(unverifiedBalance)); lockedForVoteBalanceTextField.setText(bsqFormatter.formatCoinWithCode(lockedForVotingBalance)); lockedInBondsBalanceTextField.setText(bsqFormatter.formatCoinWithCode( lockupBondsBalance.add(unlockingBondsBalance))); if (lockupAmountTextField != null && unlockingAmountTextField != null) { lockupAmountTextField.setText(bsqFormatter.formatCoinWithCode(lockupBondsBalance)); unlockingAmountTextField.setText(bsqFormatter.formatCoinWithCode(unlockingBondsBalance)); } availableNonBsqBalanceLabel.setVisible(isNonBsqBalanceAvailable); availableNonBsqBalanceLabel.setManaged(isNonBsqBalanceAvailable); availableNonBsqBalanceTextField.setVisible(isNonBsqBalanceAvailable); availableNonBsqBalanceTextField.setManaged(isNonBsqBalanceAvailable); availableNonBsqBalanceTextField.setText(bsqFormatter.formatBTCWithCode(availableNonBsqBalance.value)); String bsqSatoshi = bsqFormatter.formatBSQSatoshisWithCode(daoFacade.getAvailableMerit()); reputationBalanceTextField.setText(bsqSatoshi); }"
356,"public TxnUnlockBackupOperation(String name, Data dataKey, String ownerUuid, long lockThreadId) { super(name, dataKey); this.ownerUuid = ownerUuid; <START> this.lockThreadId = lockThreadId; <END> }",reuse KeyBasedMapOperation#threadId there,"public TxnUnlockBackupOperation(String name, Data dataKey, String ownerUuid, long lockThreadId) { super(name, dataKey); this.ownerUuid = ownerUuid; this.threadId = lockThreadId; }"
357,"public void flush(boolean force) { if (useOptmizedPartitionedOutputOperator) { if (force) { for (int i = 0; i < partitionData.length; i++) { PartitionData target = partitionData[i]; <START> target.flush(outputBuffer); <END> } return; } } for (int partition = 0; partition < pageBuilders.length; partition++) { PageBuilder partitionPageBuilder = pageBuilders[partition]; if (!partitionPageBuilder.isEmpty() && (force || partitionPageBuilder.isFull())) { Page pagePartition = partitionPageBuilder.build(); partitionPageBuilder.reset(); List<SerializedPage> serializedPages = splitPage(pagePartition, DEFAULT_MAX_PAGE_SIZE_IN_BYTES).stream() .map(serde::serialize) .collect(toImmutableList()); outputBuffer.enqueue(lifespan, partition, serializedPages); pagesAdded.incrementAndGet(); rowsAdded.addAndGet(pagePartition.getPositionCount()); } } }",inline targe: partitionData[i].flush(outputBuffer);,"public void flush(boolean force) { for (int partition = 0; partition < pageBuilders.length; partition++) { PageBuilder partitionPageBuilder = pageBuilders[partition]; if (!partitionPageBuilder.isEmpty() && (force || partitionPageBuilder.isFull())) { Page pagePartition = partitionPageBuilder.build(); partitionPageBuilder.reset(); List<SerializedPage> serializedPages = splitPage(pagePartition, DEFAULT_MAX_PAGE_SIZE_IN_BYTES).stream() .map(serde::serialize) .collect(toImmutableList()); outputBuffer.enqueue(lifespan, partition, serializedPages); pagesAdded.incrementAndGet(); rowsAdded.addAndGet(pagePartition.getPositionCount()); } } }"
358,"public void testBuildBlobId() throws Exception { for (Short version : versions) { for (Boolean shouldUseSetter : setterChoice) { buildBlobIdAndAssert(version, referenceFlag, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId, shouldUseSetter); buildBlobIdAndAssert(version, null, referenceDatacenterId, referenceAccountId, referenceContainerId, <START> referencePartitionId, shouldUseSetter); <END> buildBlobIdAndAssert(version, referenceFlag, null, referenceAccountId, referenceContainerId, referencePartitionId, shouldUseSetter); buildBlobIdAndAssert(version, referenceFlag, referenceDatacenterId, null, referenceContainerId, referencePartitionId, shouldUseSetter); buildBlobIdAndAssert(version, referenceFlag, referenceDatacenterId, referenceAccountId, null, referencePartitionId, shouldUseSetter); buildBlobIdAndAssert(version, null, null, null, null, referencePartitionId, shouldUseSetter); } } }",null values for new fields in V2,"public void testBuildBlobId() throws Exception { buildBlobIdAndAssert(version, referenceFlag, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId); }"
359,"public BooleanWrapper removeNode(String nodeUrl, Client initiator) { Node node = null; if (this.nodes.containsKey(nodeUrl)) { <START> logger.info(""Remove node "" + nodeUrl + "" from node source "" + this.name); <END> node = this.nodes.remove(nodeUrl); } else if (this.downNodes.containsKey(nodeUrl)) { logger.info(""Remove down node "" + nodeUrl + "" from node source "" + this.name); node = this.downNodes.remove(nodeUrl); } if (node == null) { logger.error(""Node "" + nodeUrl + "" cannot be removed from node source "" + this.name + "" because it is not known""); return new BooleanWrapper(false); } else { RMCore.topologyManager.removeNode(node); try { this.infrastructureManager.internalRemoveNode(node); } catch (RMException e) { logger.error(e.getCause().getMessage(), e); } return new BooleanWrapper(true); } }",I is node source logging semantic [nodesourceName],"public BooleanWrapper removeNode(String nodeUrl, Client initiator) { Node node = null; if (this.nodes.containsKey(nodeUrl)) { logger.info(""["" + this.name + ""] removing node: "" + nodeUrl); node = this.nodes.remove(nodeUrl); } else if (this.downNodes.containsKey(nodeUrl)) { logger.info(""["" + this.name + ""] removing down node: "" + nodeUrl); node = this.downNodes.remove(nodeUrl); } if (node == null) { logger.error(""["" + this.name + ""] cannot remove node: "" + nodeUrl + "" because it is unknown""); return new BooleanWrapper(false); } else { RMCore.topologyManager.removeNode(node); try { this.infrastructureManager.internalRemoveNode(node); } catch (RMException e) { logger.error(e.getCause().getMessage(), e); } return new BooleanWrapper(true); } }"
360,"private QuorumServer(long id, InetSocketAddress addr, InetSocketAddress electionAddr, LearnerType type) { this.id = id; this.addr = addr; this.electionAddr = electionAddr; this.type = type; String checkIPReachableValue = System.getProperty(""zookeeper.checkIPTimeout""); <START> if(checkIPReachableValue != null){ <END> this.checkIPReachableTO = Integer.parseInt(checkIPReachableValue); } }",nit: space if (,"private QuorumServer(long id, InetSocketAddress addr, InetSocketAddress electionAddr, LearnerType type) { this.id = id; this.addr = addr; this.electionAddr = electionAddr; this.type = type; }"
361,"static ICPPFunction[] instantiateForFunctionCall(ICPPFunction[] fns, ICPPTemplateArgument[] tmplArgs, List<IType> fnArgs, List<ValueCategory> argCats, boolean withImpliedObjectArg, IASTNode point) { boolean requireTemplate= tmplArgs != null; boolean haveTemplate= false; for (final ICPPFunction func : fns) { if (func instanceof ICPPConstructor || (func instanceof ICPPMethod && ((ICPPMethod) func).isDestructor())) requireTemplate= false; if (func instanceof ICPPFunctionTemplate) { ICPPFunctionTemplate template= (ICPPFunctionTemplate) func; try { if (containsDependentType(fnArgs)) return new ICPPFunction[] {CPPDeferredFunction.createForCandidates(fns)}; if (requireTemplate) { <START> if (hasDependentArgument(tmplArgs)) <END> return new ICPPFunction[] {CPPDeferredFunction.createForCandidates(fns)}; } } catch (DOMException e) { return NO_FUNCTIONS; } haveTemplate= true; break; } } if (!haveTemplate && !requireTemplate) return fns; final List<ICPPFunction> result= new ArrayList<ICPPFunction>(fns.length); for (ICPPFunction fn : fns) { if (fn != null) { if (fn instanceof ICPPFunctionTemplate) { ICPPFunctionTemplate fnTmpl= (ICPPFunctionTemplate) fn; ICPPFunction inst = instantiateForFunctionCall(fnTmpl, tmplArgs, fnArgs, argCats, withImpliedObjectArg, point); if (inst != null) result.add(inst); } else if (!requireTemplate || fn instanceof ICPPUnknownBinding) { result.add(fn); } } } return result.toArray(new ICPPFunction[result.size()]); }",Please combine conditions,"static ICPPFunction[] instantiateForFunctionCall(ICPPFunction[] fns, ICPPTemplateArgument[] tmplArgs, List<IType> fnArgs, List<ValueCategory> argCats, boolean withImpliedObjectArg, IASTNode point) { boolean requireTemplate= tmplArgs != null; boolean haveTemplate= false; for (final ICPPFunction func : fns) { if (func instanceof ICPPConstructor || (func instanceof ICPPMethod && ((ICPPMethod) func).isDestructor())) requireTemplate= false; if (func instanceof ICPPFunctionTemplate) { ICPPFunctionTemplate template= (ICPPFunctionTemplate) func; if (containsDependentType(fnArgs)) return new ICPPFunction[] {CPPDeferredFunction.createForCandidates(fns)}; if (requireTemplate && hasDependentArgument(tmplArgs)) return new ICPPFunction[] {CPPDeferredFunction.createForCandidates(fns)}; haveTemplate= true; break; } } if (!haveTemplate && !requireTemplate) return fns; final List<ICPPFunction> result= new ArrayList<ICPPFunction>(fns.length); for (ICPPFunction fn : fns) { if (fn != null) { if (fn instanceof ICPPFunctionTemplate) { ICPPFunctionTemplate fnTmpl= (ICPPFunctionTemplate) fn; ICPPFunction inst = instantiateForFunctionCall(fnTmpl, tmplArgs, fnArgs, argCats, withImpliedObjectArg, point); if (inst != null) result.add(inst); } else if (!requireTemplate || fn instanceof ICPPUnknownBinding) { result.add(fn); } } } return result.toArray(new ICPPFunction[result.size()]); }"
362,"public void sample() throws IOException { BlobServiceClient serviceClient = new BlobServiceClientBuilder().endpoint(ACCOUNT_ENDPOINT) .credential(new SharedKeyCredential(ACCOUNT_NAME, ACCOUNT_KEY)) .httpClient(HttpClient.createDefault() ) <START> .buildClient(); <END> BlobContainerClient blobContainerClient = null; for (int i = 0; i < 5; i++) { String name = ""uxtesting"" + UUID.randomUUID(); blobContainerClient = serviceClient.getContainerClient(name); blobContainerClient.create(); System.out.println(""Created container: "" + name); } System.out.println(); System.out.println(""Listing containers in account:""); for (ContainerItem item : serviceClient.listContainers()) { System.out.println(item.getName()); } System.out.println(); for (int i = 0; i < 5; i++) { BlockBlobClient blobClient = blobContainerClient.getBlobClient(""testblob-"" + i).getBlockBlobClient(); ByteArrayInputStream testdata = new ByteArrayInputStream((""test data"" + i).getBytes(StandardCharsets.UTF_8)); blobClient.upload(testdata, testdata.available()); System.out.println(""Uploaded blob.""); } System.out.println(); System.out.println(""Listing/downloading blobs:""); for (BlobItem item : blobContainerClient.listBlobsFlat()) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); blobContainerClient.getBlobClient(item.getName()).download(stream); System.out.println(item.getName() + "": "" + new String(stream.toByteArray())); } System.out.println(); for (ContainerItem item : serviceClient.listContainers()) { blobContainerClient = serviceClient.getContainerClient(item.getName()); blobContainerClient.delete(); System.out.println(""Deleted container: "" + item.getName()); } }",Random aside.. this sample in.. samples? a bit confused,"public void sample() throws IOException { BlobServiceClient serviceClient = new BlobServiceClientBuilder().endpoint(ACCOUNT_ENDPOINT) .credential(new SharedKeyCredential(ACCOUNT_NAME, ACCOUNT_KEY)) .httpClient(HttpClient.createDefault() ) .buildClient(); BlobContainerClient blobContainerClient = null; for (int i = 0; i < 5; i++) { String name = ""uxtesting"" + UUID.randomUUID(); blobContainerClient = serviceClient.getBlobContainerClient(name); blobContainerClient.create(); System.out.println(""Created container: "" + name); } System.out.println(); System.out.println(""Listing containers in account:""); for (BlobContainerItem item : serviceClient.listBlobContainers()) { System.out.println(item.getName()); } System.out.println(); for (int i = 0; i < 5; i++) { BlockBlobClient blobClient = blobContainerClient.getBlobClient(""testblob-"" + i).getBlockBlobClient(); ByteArrayInputStream testdata = new ByteArrayInputStream((""test data"" + i).getBytes(StandardCharsets.UTF_8)); blobClient.upload(testdata, testdata.available()); System.out.println(""Uploaded blob.""); } System.out.println(); System.out.println(""Listing/downloading blobs:""); for (BlobItem item : blobContainerClient.listBlobsFlat()) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); blobContainerClient.getBlobClient(item.getName()).download(stream); System.out.println(item.getName() + "": "" + new String(stream.toByteArray())); } System.out.println(); for (BlobContainerItem item : serviceClient.listBlobContainers()) { blobContainerClient = serviceClient.getBlobContainerClient(item.getName()); blobContainerClient.delete(); System.out.println(""Deleted container: "" + item.getName()); } }"
363,private String getJobOrFlowName(SlaOption slaOption) { String jobName = (String) slaOption.getInfo().get(SlaOption.INFO_JOB_NAME); <START> if (org.apache.commons.lang.StringUtils.isNotBlank(jobName)) { <END> return jobName; } else { return (String) slaOption.getInfo().get(SlaOption.INFO_FLOW_NAME); } },isNotEmpty safer,"private String getJobOrFlowName(SlaOption slaOption) { String flowName = (String) slaOption.getInfo().get(SlaOption.INFO_FLOW_NAME); String jobName = (String) slaOption.getInfo().get(SlaOption.INFO_JOB_NAME); if (org.apache.commons.lang.StringUtils.isNotBlank(jobName)) { return flowName + "":"" + jobName; } else { return flowName; } }"
364,"ShardSyncTaskManager(final IKinesisProxy kinesisProxy, final ILeaseManager<KinesisClientLease> leaseManager, final InitialPositionInStreamExtended initialPositionInStream, final boolean cleanupLeasesUponShardCompletion, final boolean ignoreUnexpectedChildShards, final long shardSyncIdleTimeMillis, final IMetricsFactory metricsFactory, ExecutorService executorService, ShardSyncer shardSyncer) { this.kinesisProxy = kinesisProxy; this.leaseManager = leaseManager; this.metricsFactory = metricsFactory; this.cleanupLeasesUponShardCompletion = cleanupLeasesUponShardCompletion; this.ignoreUnexpectedChildShards = ignoreUnexpectedChildShards; this.shardSyncIdleTimeMillis = shardSyncIdleTimeMillis; this.executorService = executorService; this.initialPositionInStream = initialPositionInStream; this.shardSyncer = shardSyncer; this.shardSyncRequestPending = new AtomicBoolean(false); <START> this.lock = new ReentrantLock(Boolean.TRUE); <END> }",specific reason enforce fairness,"ShardSyncTaskManager(final IKinesisProxy kinesisProxy, final ILeaseManager<KinesisClientLease> leaseManager, final InitialPositionInStreamExtended initialPositionInStream, final boolean cleanupLeasesUponShardCompletion, final boolean ignoreUnexpectedChildShards, final long shardSyncIdleTimeMillis, final IMetricsFactory metricsFactory, ExecutorService executorService, ShardSyncer shardSyncer) { this.kinesisProxy = kinesisProxy; this.leaseManager = leaseManager; this.metricsFactory = metricsFactory; this.cleanupLeasesUponShardCompletion = cleanupLeasesUponShardCompletion; this.ignoreUnexpectedChildShards = ignoreUnexpectedChildShards; this.shardSyncIdleTimeMillis = shardSyncIdleTimeMillis; this.executorService = executorService; this.initialPositionInStream = initialPositionInStream; this.shardSyncer = shardSyncer; this.shardSyncRequestPending = new AtomicBoolean(false); this.lock = new ReentrantLock(); }"
365,"<START> public Optional<Repository> getRepository(Class<? extends Message> stateClass) { <END> final RepositoryAccess repositoryAccess = repositories.get(stateClass); if (repositoryAccess == null) { throw newIllegalArgumentException( ""A repository for the state class (%s) was not registered in VisibilityGuard"", stateClass.getName()); } return repositoryAccess.get(); }","long perform checkNotNull(...) in getEntityTypes(visibility) below, I do for stateClass well","public Optional<Repository> getRepository(Class<? extends Message> stateClass) { checkNotNull(stateClass); final RepositoryAccess repositoryAccess = repositories.get(stateClass); if (repositoryAccess == null) { throw newIllegalArgumentException( ""A repository for the state class (%s) was not registered in VisibilityGuard"", stateClass.getName()); } return repositoryAccess.get(); }"
366,"<START> void claimSlot( int slot, long[] key ) <END> { int offset = slot * width; System.arraycopy( key, 0, keys, offset, width ); numberOfEntries++; }","I contract for this method requires do overwrite slots, numberOfEntries broken. Add assert? Allow overwrite","void claimSlot( int slot, long[] key ) { int offset = slot * width; assert keys[offset] == NOT_IN_USE : ""Tried overwriting an already used slot""; System.arraycopy( key, 0, keys, offset, width ); numberOfEntries++; }"
367,"public void testTotalPriceColumn(User user) { HomePage homePage = new HomePage(driver); UserInfoPage userInfoPage = homePage.logIn(user.getLogin(), user.getPassword()); OrderingPage orderingPage = userInfoPage.clickOrderingTab(); List<Order> tableFromView = orderingPage.getTableFromView(); tableFromView.sort(Comparator.comparing(Order::getTotalPrice)); <START> orderingPage.clickOrdersTableColumn(OrdersTable.TOTAL_PRICE.toString()); <END> List<Order> sortedTableByTotalPriceAsc = orderingPage.getTableFromView(); orderingPage.clickOrdersTableColumn(OrdersTable.TOTAL_PRICE.toString()); List<Order> sortedTableByTotalPriceDesc = orderingPage.getTableFromView(); for (int i = 0; i < tableFromView.size(); i++) { Assert.assertTrue(sortedTableByTotalPriceAsc.get(i).getTotalPrice().equals(tableFromView.get(i).getTotalPrice()), ""Sorting by total price doesn't work.""); } for (int i = 0, j = tableFromView.size() - 1; i < tableFromView.size(); i++, j--) { Assert.assertTrue(sortedTableByTotalPriceDesc.get(i).getTotalPrice().equals(tableFromView.get(j).getTotalPrice()), ""Sorting by total price doesn't work.""); } }",move toString() clickOrdersTableColumn() method for OrdersTable.ELEM.toString() calls,"public void testTotalPriceColumn(User user) { HomePage homePage = new HomePage(driver); UserInfoPage userInfoPage = homePage.logIn(user.getLogin(), user.getPassword()); OrderingPage orderingPage = userInfoPage.clickOrderingTab(); List<Order> tableFromView = orderingPage.getTableFromView(); tableFromView.sort(Comparator.comparing(Order::getTotalPrice)); orderingPage.clickOrdersTableColumn(OrdersTable.TOTAL_PRICE); List<Order> sortedTableByTotalPriceAsc = orderingPage.getTableFromView(); orderingPage.clickOrdersTableColumn(OrdersTable.TOTAL_PRICE); List<Order> sortedTableByTotalPriceDesc = orderingPage.getTableFromView(); for (int i = 0; i < tableFromView.size(); i++) { Assert.assertTrue(sortedTableByTotalPriceAsc.get(i).getTotalPrice().equals(tableFromView.get(i).getTotalPrice()), ""Sorting by total price doesn't work.""); } for (int i = 0, j = tableFromView.size() - 1; i < tableFromView.size(); i++, j--) { Assert.assertTrue(sortedTableByTotalPriceDesc.get(i).getTotalPrice().equals(tableFromView.get(j).getTotalPrice()), ""Sorting by total price doesn't work.""); } }"
368,"public List<QuotaConsumptionParameter> getQuotaVdsConsumptionParameters() { List<QuotaConsumptionParameter> list = new ArrayList<QuotaConsumptionParameter>(); list.add(new QuotaVdsGroupConsumptionParameter( getParameters().getVmStaticData().getQuotaId(), null, QuotaConsumptionParameter.QuotaAction.CONSUME, getParameters().getVmStaticData().getvds_group_id(), 0, <START> 0)); <END> return list; }",zeros,"public List<QuotaConsumptionParameter> getQuotaVdsConsumptionParameters() { List<QuotaConsumptionParameter> list = new ArrayList<QuotaConsumptionParameter>(); list.add(new QuotaSanityParameter(getParameters().getVmStaticData().getQuotaId(), null)); return list; }"
369,"public void init() { executorService.schedule(this::setPublications, 1, TimeUnit.MILLISECONDS); <START> } <END>",waiting 1 millisecond call setPublications() help,public void init() { executorService.submit(this::setPublications); }
370,public void stop() { <START> running = false; <END> },executorService.shutdown() well,public void stop() { running = false; executorService.shutdown(); }
371,protected static MarkupParser createParserWithConfiguration(MarkupLanguageConfiguration configuration) { MarkupLanguage markupLanguage = new AsciiDocLanguage(); if (configuration != null) { markupLanguage.configure(configuration); } <START> MarkupParser parser = new <END> MarkupParser(markupLanguage); return parser; },inline return statement,protected static MarkupParser createParserWithConfiguration(MarkupLanguageConfiguration configuration) { MarkupLanguage markupLanguage = new AsciiDocLanguage(); if (configuration != null) { markupLanguage.configure(configuration); } return new MarkupParser(markupLanguage); }
372,"public void queueEvent(Event event) { <START> if (log.isDebugEnabled()) { <END> log.debug(""Queuing event: "" + event); } getEventQueue().add(event); }","Logback, need types of guards. java log.debug(""Queing event: {}"", event) do trick penalty in performance","public void queueEvent(Event event) { log.debug(""Queuing event: "" + event); getEventQueue().add(event); }"
373,"public void testFacetParams() { List<NameValuePair> actual = buildFacetParams(""journal"", ""foo"", true); SetMultimap<String, String> actualMap = convertToMap(actual); assertFacetParams(2, actualMap); assertSingle(""journal"", actualMap.get(""facet.field"")); assertSingle(""dismax"", actualMap.get(""defType"")); assertSingle(""foo"", actualMap.get(""q"")); actual = buildFacetParams(""journal"", ""*:*"", false); actualMap = convertToMap(actual); assertFacetParams(2, actualMap); assertSingle(""journal"", actualMap.get(""facet.field"")); assertEquals(actualMap.get(""defType"").size(), 0); assertSingle(""*:*"", actualMap.get(""q"")); ArticleSearchQuery.Facet facet = ArticleSearchQuery.Facet.builder() .setField(""foo"") .setExcludeKey(""bar"") .build(); ArticleSearchQuery asq = ArticleSearchQuery.builder() .addFacet(facet) .setQuery(""query"") .build(); actual = SolrQueryBuilder.buildParameters(asq); actualMap = convertToMap(actual); <START> System.out.println(actualMap.get(""facet.field"")); <END> assertSingle(""{!ex=bar}foo"", actualMap.get(""facet.field"")); assertSingle(""query"", actualMap.get(""q"")); }",logging,"public void testFacetParams() { List<NameValuePair> actual = buildFacetParams(""journal"", ""foo"", true); SetMultimap<String, String> actualMap = convertToMap(actual); assertFacetParams(2, actualMap); assertSingle(""journal"", actualMap.get(""facet.field"")); assertSingle(""dismax"", actualMap.get(""defType"")); assertSingle(""foo"", actualMap.get(""q"")); actual = buildFacetParams(""journal"", ""*:*"", false); actualMap = convertToMap(actual); assertFacetParams(2, actualMap); assertSingle(""journal"", actualMap.get(""facet.field"")); assertEquals(actualMap.get(""defType"").size(), 0); assertSingle(""*:*"", actualMap.get(""q"")); ArticleSearchQuery.Facet facet = ArticleSearchQuery.Facet.builder() .setField(""foo"") .setExcludeKey(""bar"") .build(); ArticleSearchQuery asq = ArticleSearchQuery.builder() .addFacet(facet) .setQuery(""query"") .build(); actual = SolrQueryBuilder.buildParameters(asq); actualMap = convertToMap(actual); assertSingle(""{!ex=bar}foo"", actualMap.get(""facet.field"")); assertSingle(""query"", actualMap.get(""q"")); }"
374,"public void addDefaultRoute() { if ((mInterfaceName != null) && (mDefaultGatewayAddr != 0) && mDefaultRouteSet == false) { if (DBG) { Log.d(TAG, ""addDefaultRoute for "" + mNetworkInfo.getTypeName() + "" ("" + mInterfaceName + ""), GatewayAddr="" + mDefaultGatewayAddr); } <START> InetAddress inetAddress = NetworkUtils.intToInetAddress(mDefaultGatewayAddr); <END> if (inetAddress == null) { if (DBG) Log.d(TAG, "" Unable to add default route. mDefaultGatewayAddr Error""); } else { if (NetworkUtils.addDefaultRoute(mInterfaceName, inetAddress, 0)) { mDefaultRouteSet = true; } else { if (DBG) Log.d(TAG, "" Unable to add default route.""); } } } }",If add mIPv6DefaultGateway member need add a IPv6 route well,"public void addDefaultRoute() { if ((mInterfaceName != null) && (mDefaultGatewayAddr != 0) && mDefaultRouteSet == false) { if (DBG) { Log.d(TAG, ""addDefaultRoute for "" + mNetworkInfo.getTypeName() + "" ("" + mInterfaceName + ""), GatewayAddr="" + mDefaultGatewayAddr); } InetAddress inetAddress = NetworkUtils.intToInetAddress(mDefaultGatewayAddr); if (inetAddress == null) { if (DBG) Log.d(TAG, "" Unable to add default route. mDefaultGatewayAddr Error""); } else { if (NetworkUtils.addDefaultRoute(mInterfaceName, inetAddress)) { mDefaultRouteSet = true; } else { if (DBG) Log.d(TAG, "" Unable to add default route.""); } } } }"
375,private List<Window> fetchWindowsInQueue() { List<Window> windows = Lists.newArrayList(getWindows()); <START> return ImmutableList.copyOf(Lists.reverse(windows)); <END> },"Remove reversal here, JDK 8 implementation return in reverse, JDK 9 implementation *not* reversed",private List<Window> fetchWindowsInQueue() { return ImmutableList.copyOf(getWindows()); }
376,"void update(ObservationPoint obsPoint, MapView mapView, boolean isMlsPointUpdate) { final Projection pj = mapView.getProjection(); GeoPoint geoPoint = (isMlsPointUpdate)? obsPoint.pointMLS : obsPoint.pointGPS; if (geoPoint == null) { <START> Log.i(LOG_TAG, ""Caller error: geoPoint is null""); <END> return; } final Point point = pj.toPixels(geoPoint, null); final int size = mSize3px * 2; final Rect dirty = new Rect(point.x - size, point.y - size, point.x + size, point.y + size); dirty.offset(mapView.getScrollX(), mapView.getScrollY()); mapView.postInvalidate(dirty.left, dirty.top, dirty.right, dirty.bottom); if (!isMlsPointUpdate) { addToGridHash(obsPoint, point); } }",this a warning info level message? happen,"void update(ObservationPoint obsPoint, MapView mapView, boolean isMlsPointUpdate) { final Projection pj = mapView.getProjection(); GeoPoint geoPoint = (isMlsPointUpdate)? obsPoint.pointMLS : obsPoint.pointGPS; if (geoPoint == null) { Log.w(LOG_TAG, ""Caller error: geoPoint is null""); return; } final Point point = pj.toPixels(geoPoint, null); final int size = mSize3px * 2; final Rect dirty = new Rect(point.x - size, point.y - size, point.x + size, point.y + size); dirty.offset(mapView.getScrollX(), mapView.getScrollY()); mapView.postInvalidate(dirty.left, dirty.top, dirty.right, dirty.bottom); if (!isMlsPointUpdate) { addToGridHash(obsPoint, point); } }"
377,"public static Date parseDate(String date, String format) { <START> return parseDate(date, new SimpleDateFormat(format, Locale.getDefault())); <END> }","Is a null check for passed in ""date"" required for safety","public static Date parseDate(String date, String format) { if (date == null) { return null; } return parseDate(date, new SimpleDateFormat(format, Locale.getDefault())); }"
378,"protected boolean isDeprecated() { if (isDeprecated == null) { <START> boolean isDeprecated = false; <END> if (parent instanceof AbstractProperty) { AbstractProperty absParent = (AbstractProperty) parent; isDeprecated = absParent.isDeprecated(); Property parentDeprecatedFallback = absParent.deprecatedFallback; if (isDeprecated && parentDeprecatedFallback != null) { deprecatedFallback = parentDeprecatedFallback.resolvePath(getName()); } } if (!isDeprecated) { String name = getXPath(); String schema = getSchema().getName(); SchemaManager schemaManager = Framework.getService(SchemaManager.class); isDeprecated = schemaManager.isPropertyDeprecated(schema, name); if (isDeprecated) { String fallback = schemaManager.getDeprecatedPropertyFallback(schema, name); if (fallback != null) { deprecatedFallback = resolvePath('/' + fallback); } } } this.isDeprecated = Boolean.valueOf(isDeprecated); } return isDeprecated.booleanValue(); }","Please name local variable differently field, for instance deprecated, reading code is a bit confusing. This avoid this.isDeprecated a bit down","protected boolean isDeprecated() { if (isDeprecated == null) { boolean deprecated = false; if (parent instanceof AbstractProperty) { AbstractProperty absParent = (AbstractProperty) parent; deprecated = absParent.isDeprecated(); Property parentDeprecatedFallback = absParent.deprecatedFallback; if (deprecated && parentDeprecatedFallback != null) { deprecatedFallback = parentDeprecatedFallback.resolvePath(getName()); } } if (!deprecated) { String name = getXPath(); String schema = getSchema().getName(); SchemaManager schemaManager = Framework.getService(SchemaManager.class); PropertyDeprecationHandler deprecatedProperties = schemaManager.getDeprecatedProperties(); deprecated = deprecatedProperties.isMarked(schema, name); if (deprecated) { String fallback = deprecatedProperties.getFallback(schema, name); if (fallback != null) { deprecatedFallback = resolvePath('/' + fallback); } } } isDeprecated = Boolean.valueOf(deprecated); } return isDeprecated.booleanValue(); }"
379,"private static Optional<Credential> getImpersonatedCredential( Configuration config, Credential credential) throws IOException { String serviceAccountToImpersonate = IMPERSONATION_SERVICE_ACCOUNT_SUFFIX .withPrefixes(CONFIG_KEY_PREFIXES) .get(config, config::get); if (isNullOrEmpty(serviceAccountToImpersonate)) { <START> Map<String, String> serviceAccountMapping = <END> IMPERSONATION_IDENTIFIER_PREFIX .withPrefixes(CONFIG_KEY_PREFIXES) .getPropsWithPrefix(config); for (Map.Entry<String, String> entry : serviceAccountMapping.entrySet()) { if (matchedUserOrGroup(entry.getKey())) { serviceAccountToImpersonate = entry.getValue(); break; } } } if (isNullOrEmpty(serviceAccountToImpersonate)) { return Optional.empty(); } GoogleCloudStorageOptions options = GoogleHadoopFileSystemConfiguration.getGcsFsOptionsBuilder(config) .build() .getCloudStorageOptions(); HttpTransport httpTransport = HttpTransportFactory.createHttpTransport( options.getTransportType(), options.getProxyAddress(), options.getProxyUsername(), options.getProxyPassword()); GoogleCredential impersonatedCredential = new GoogleCredentialWithIamAccessToken( httpTransport, new CredentialHttpRetryInitializer(credential), serviceAccountToImpersonate, CredentialFactory.GCS_SCOPES); return Optional.of(impersonatedCredential.createScoped(CredentialFactory.GCS_SCOPES)); }",get this map options object getImpersonationServiceAccounts() method instead,"private static Optional<Credential> getImpersonatedCredential( Configuration config, Credential credential) throws IOException { GoogleCloudStorageOptions options = GoogleHadoopFileSystemConfiguration.getGcsFsOptionsBuilder(config) .build() .getCloudStorageOptions(); String serviceAccountToImpersonate = IMPERSONATION_SERVICE_ACCOUNT_SUFFIX .withPrefixes(CONFIG_KEY_PREFIXES) .get(config, config::get); if (isNullOrEmpty(serviceAccountToImpersonate)) { Optional<String> serviceAccountToImpersonateFromUser = getMatchedServiceAccountToImpersonateFromGroup( options.getUserImpersonationServiceAccounts(), ImmutableList.of(UserGroupInformation.getCurrentUser().getShortUserName())); Optional<String> serviceAccountToImpersonateFromGroup = getMatchedServiceAccountToImpersonateFromGroup( options.getGroupImpersonationServiceAccounts(), ImmutableList.copyOf(UserGroupInformation.getCurrentUser().getGroupNames())); serviceAccountToImpersonate = serviceAccountToImpersonateFromUser.orElse( serviceAccountToImpersonateFromGroup.orElse(null)); } if (isNullOrEmpty(serviceAccountToImpersonate)) { return Optional.empty(); } HttpTransport httpTransport = HttpTransportFactory.createHttpTransport( options.getTransportType(), options.getProxyAddress(), options.getProxyUsername(), options.getProxyPassword()); GoogleCredential impersonatedCredential = new GoogleCredentialWithIamAccessToken( httpTransport, new CredentialHttpRetryInitializer(credential), serviceAccountToImpersonate, CredentialFactory.GCS_SCOPES); return Optional.of(impersonatedCredential.createScoped(CredentialFactory.GCS_SCOPES)); }"
380,public void shouldThrowExceptionOnNullTransformFunction() { <START> final Option<Integer> option = Option.some(1); <END> option.transform(null); },inline this,public void shouldThrowExceptionOnNullTransformFunction() { Option.some(1).transform(null); }
381,"public String listConnectionsAsJSON() throws Exception { checkStarted(); clearIO(); try { JsonArrayBuilder array = JsonLoader.createArrayBuilder(); Set<RemotingConnection> connections = server.getRemotingService().getConnections(); for (RemotingConnection connection : connections) { JsonObjectBuilder obj = JsonLoader.createObjectBuilder().add(""connectionID"", connection.getID().toString()) .add(""clientAddress"", connection.getRemoteAddress()) .add(""creationTime"", connection.getCreationTime()) <START> .add(""implementation"", connection.getClass().getSimpleName()) <END> .add(""sessionCount"", server.getSessions(connection.getID().toString()).size()); if (connection.getClientID() != null) { obj.add(""clientID"", connection.getClientID()); } else { obj.add(""clientID"", """"); } array.add(obj); } return array.build().toString(); } finally { blockOnIO(); } }","Please avoid reformatting this, code change","public String listConnectionsAsJSON() throws Exception { checkStarted(); clearIO(); try { JsonArrayBuilder array = JsonLoader.createArrayBuilder(); Set<RemotingConnection> connections = server.getRemotingService().getConnections(); for (RemotingConnection connection : connections) { JsonObjectBuilder obj = JsonLoader.createObjectBuilder().add(""connectionID"", connection.getID().toString()).add(""clientAddress"", connection.getRemoteAddress()).add(""creationTime"", connection.getCreationTime()).add(""implementation"", connection.getClass().getSimpleName()).add(""sessionCount"", server.getSessions(connection.getID().toString()).size()); List<ServerSession> sessions = server.getSessions(connection.getID().toString()); if (sessions.size() > 0) { if (sessions.get(0).getMetaData(ClientSession.JMS_SESSION_CLIENT_ID_PROPERTY) != null) { obj.add(""clientID"", sessions.get(0).getMetaData(ClientSession.JMS_SESSION_CLIENT_ID_PROPERTY)); } else { obj.add(""clientID"", """"); } } else { obj.add(""clientID"", """"); } array.add(obj); } return array.build().toString(); } finally { blockOnIO(); } }"
382,"private Optional<Set<String>> getFilteredStringObjectMap( final IndexEdge indexEdge ) { Id mapOwner = new SimpleId( indexEdge.getNodeId().getUuid(), TYPE_APPLICATION ); final MapScope ms = CpNamingUtils.getEntityTypeMapScope( mapOwner ); MapManager mm = mapManagerFactory.createMapManager( ms ); Set<String> defaultProperties; ArrayList fieldsToKeep; String collectionName = CpNamingUtils.getCollectionNameFromEdgeName( indexEdge.getEdgeName() ); String jsonSchemaMap = mm.getString( collectionName ); <START> if ( jsonSchemaMap != null ) { <END> Map jsonMapData = ( Map ) JsonUtils.parse( jsonSchemaMap ); Schema schema = Schema.getDefaultSchema(); defaultProperties = schema.getRequiredProperties( collectionName ); fieldsToKeep = ( ArrayList ) jsonMapData.get( ""fields"" ); defaultProperties.addAll( fieldsToKeep ); } else { return Optional.empty(); } return Optional.of(defaultProperties); }","this logic is duplicated in a couple classes, lets if a simplify","private Optional<Set<String>> getFilteredStringObjectMap( final IndexEdge indexEdge ) { Id mapOwner = new SimpleId( indexEdge.getNodeId().getUuid(), TYPE_APPLICATION ); final MapScope ms = CpNamingUtils.getEntityTypeMapScope( mapOwner ); MapManager mm = mapManagerFactory.createMapManager( ms ); Set<String> defaultProperties; ArrayList fieldsToKeep; String collectionName = CpNamingUtils.getCollectionNameFromEdgeName( indexEdge.getEdgeName() ); IndexSchemaCache indexSchemaCache = indexSchemaCacheFactory.getInstance( mm ); Optional<Map> collectionIndexingSchema = indexSchemaCache.getCollectionSchema( collectionName ); if ( collectionIndexingSchema.isPresent()) { Map jsonMapData = collectionIndexingSchema.get(); Schema schema = Schema.getDefaultSchema(); defaultProperties = schema.getRequiredProperties( collectionName ); fieldsToKeep = ( ArrayList ) jsonMapData.get( ""fields"" ); if(fieldsToKeep.contains( ""*"" )){ return Optional.absent(); } defaultProperties.addAll( fieldsToKeep ); } else { return Optional.absent(); } return Optional.of(defaultProperties); }"
383,"private static HaxeGenericResolver findGenericResolverFromVariable(HaxeCallExpression expr) { <START> PsiElement[] children = expr.getExpression().getChildren(); Optional<HaxeReference> first = Stream.of(children) .filter(c -> c instanceof HaxeReference) .map(c -> (HaxeReference)c) .findFirst(); <END> if(first.isPresent()) { HaxeReference expression = first.get(); HaxeClassResolveResult resolveResult = expression.resolveHaxeClass(); SpecificHaxeClassReference reference = resolveResult.getSpecificClassReference(expression.getElement(), null); SpecificHaxeClassReference finalReference = getUnderlyingClassIfAbstractNull(reference); return finalReference.getGenericResolver(); } return null; }","This is soooooo slower UsefulPsiTreeUtil.getChildOfType(expr, HaxeReference.class);. starting wish static extensions in Java. time Manifold (http://manifold.systems) in this project","private static HaxeGenericResolver findGenericResolverFromVariable(HaxeCallExpression expr) { HaxeReference[] type = UsefulPsiTreeUtil.getChildrenOfType(expr.getExpression(), HaxeReference.class, null); if(type!= null && type.length> 0) { HaxeReference expression = type[0]; HaxeClassResolveResult resolveResult = expression.resolveHaxeClass(); SpecificHaxeClassReference reference = resolveResult.getSpecificClassReference(expression.getElement(), null); SpecificHaxeClassReference finalReference = getUnderlyingClassIfAbstractNull(reference); return finalReference.getGenericResolver(); } return null; }"
384,"public Matrix bernoulli(final int rows, final int columns, final float prob) { final int length = rows * columns; final float[] data = new float[length]; for (int i = 0; i < length; ++i) { <START> if (randomGenerator.nextFloat() > prob) { <END> data[i] = 1; } else { data[i] = 0; } } return create(data, rows, columns); }","I thought prob = 1 generates a matrix filled ones, code generate a matrix zeros","public Matrix bernoulli(final int rows, final int columns, final float prob) { return bernoulli(rows, columns, prob, 1); }"
385,"public IDataChartDescriptor<?, ?> getX(int index) { <START> return checkNotNull(fSeries.get(index)).getX(); <END> }",do need checkNotNull() here? ChartSeries.getX() @NonNull due package annotation,"public IDataChartDescriptor<?, ?> getX(int index) { return fSeries.get(index).getX(); }"
386,"private Response copy(Action action) { GlusterHookManageParameters params = new GlusterHookManageParameters(guid); <START> if (action.getHost() != null) { <END> validateParameters(action.getHost(),""host.id|name""); Guid hostId = getHostId(action); if (hostId == null) { return handleError(new EntityNotFoundException(action.getHost().getId() != null ? id : action.getHost().getName()), false); } params.setSourceServerId(hostId); } return doAction(VdcActionType.UpdateGlusterHook, params, action); }",action.isSetHost(),"private Response copy(Action action) { GlusterHookManageParameters params = new GlusterHookManageParameters(guid); if (action.isSetHost()) { validateParameters(action.getHost(),""host.id|name""); Guid hostId = getHostId(action); params.setSourceServerId(hostId); } return doAction(VdcActionType.UpdateGlusterHook, params, action); }"
387,"protected void migrateSessionPropertyToSecured(CoreSession session, MigrationContext migrationContext) { List<String> comments = getUnsecuredCommentIds(session); CommentManager commentManager = Framework.getService(CommentManager.class); processBatched(migrationContext, BATCH_SIZE, comments, comment -> migrateCommentsFromPropertyToSecured(session, commentManager, new IdRef(comment)), ""Migrating comments from Property to Secured""); int totalOfComments = comments.size(); int nbeOfUnMigratedComments = getUnsecuredCommentIds(session).size(); if (nbeOfUnMigratedComments == 0) { session.query(GET_COMMENTS_FOLDERS_QUERY).forEach((folder -> session.removeDocument(folder.getRef()))); IdRef[] documentsToRemove = session.queryProjection(GET_COMMENTS_FOLDERS_QUERY, 0, 0) .stream() .map(m -> new IdRef((String) m.get(ECM_UUID))) .toArray(IdRef[]::new); session.removeDocuments(documentsToRemove); <START> reportProgress(""Done Migration from Property to Secured"", totalOfComments, totalOfComments); <END> } else { log.warn( ""Some comments have not been migrated, see logs for more information. The folder containing these comments will be renamed to {}"", UNMIGRATED_COMMENTS_FOLDER_NAME); session.query(GET_COMMENTS_FOLDERS_QUERY).forEach(docModel -> { session.move(docModel.getRef(), null, UNMIGRATED_COMMENTS_FOLDER_NAME); docModel.putContextData(DISABLE_NOTIFICATION_SERVICE, TRUE); session.saveDocument(docModel); }); session.save(); reportProgress(""Done Migration from Property to Secured"", totalOfComments - nbeOfUnMigratedComments, totalOfComments); } }",this change,"protected void migrateSessionPropertyToSecured(CoreSession session, MigrationContext migrationContext) { List<String> comments = getUnsecuredCommentIds(session); CommentManager commentManager = Framework.getService(CommentManager.class); processBatched(migrationContext, BATCH_SIZE, comments, comment -> migrateCommentsFromPropertyToSecured(session, commentManager, new IdRef(comment)), ""Migrating comments from Property to Secured""); int totalOfComments = comments.size(); int nbeOfUnMigratedComments = getUnsecuredCommentIds(session).size(); if (nbeOfUnMigratedComments == 0) { session.query(GET_COMMENTS_FOLDERS_QUERY).forEach((folder -> session.removeDocument(folder.getRef()))); IdRef[] documentsToRemove = session.queryProjection(GET_COMMENTS_FOLDERS_QUERY, 0, 0) .stream() .map(m -> new IdRef((String) m.get(ECM_UUID))) .toArray(IdRef[]::new); session.removeDocuments(documentsToRemove); reportProgress(""Done Migrating from Property to Secured"", totalOfComments, totalOfComments); } else { log.warn( ""Some comments have not been migrated, see logs for more information. The folder containing these comments will be renamed to {}"", UNMIGRATED_COMMENTS_FOLDER_NAME); session.query(GET_COMMENTS_FOLDERS_QUERY).forEach(docModel -> { session.move(docModel.getRef(), null, UNMIGRATED_COMMENTS_FOLDER_NAME); docModel.putContextData(DISABLE_NOTIFICATION_SERVICE, TRUE); session.saveDocument(docModel); }); session.save(); reportProgress(""Done Migrating from Property to Secured"", totalOfComments - nbeOfUnMigratedComments, totalOfComments); } }"
388,"<START> public void testAddNewRelationship_noIndex() throws Exception { <END> final Node diagram = createNode(CaseManagementDiagram.class); final Node start = createNode(StartNoneEvent.class); final Node end = createNode(EndNoneEvent.class); final Node stage = createNode(AdHocSubprocess.class); final Node candidate = createNode(AdHocSubprocess.class); createChildEdge(diagram, start); createChildEdge(diagram, stage); createChildEdge(diagram, end); createSequenceFlow(start, stage); final Edge edge = createSequenceFlow(stage, end); final CaseManagementSetChildNodeGraphCommand command = new CaseManagementSetChildNodeGraphCommand(diagram, candidate, OptionalInt.empty(), Optional.of(diagram), originalIndex); command.addNewRelationship(context); assertTrue(command.in.isPresent()); assertEquals(stage, command.in.get()); assertTrue(command.out.isPresent()); assertEquals(end, command.out.get()); assertTrue(command.edge.isPresent()); assertEquals(edge, command.edge.get()); assertEquals(candidate, ((Edge) diagram.getOutEdges().get(2)).getTargetNode()); assertEquals(candidate, ((Edge) stage.getOutEdges().get(0)).getTargetNode()); assertEquals(1, end.getInEdges().stream().filter(sequencePredicate()).count()); assertEquals(candidate, ((List) end.getInEdges().stream().filter(sequencePredicate()) .map(e -> ((Edge) e).getSourceNode()).collect(Collectors.toList())).get(0)); }",Exception is thrown,"public void testAddNewRelationship_noIndex() { final Node diagram = createNode(CaseManagementDiagram.class); final Node start = createNode(StartNoneEvent.class); final Node end = createNode(EndNoneEvent.class); final Node stage = createNode(AdHocSubprocess.class); final Node candidate = createNode(AdHocSubprocess.class); createChildEdge(diagram, start); createChildEdge(diagram, stage); createChildEdge(diagram, end); createSequenceFlow(start, stage); final Edge edge = createSequenceFlow(stage, end); final CaseManagementSetChildNodeGraphCommand command = new CaseManagementSetChildNodeGraphCommand(diagram, candidate, OptionalInt.empty(), Optional.of(diagram), originalIndex); command.addNewRelationship(context); assertTrue(command.in.isPresent()); assertEquals(stage, command.in.get()); assertTrue(command.out.isPresent()); assertEquals(end, command.out.get()); assertTrue(command.edge.isPresent()); assertEquals(edge, command.edge.get()); assertEquals(candidate, ((Edge) diagram.getOutEdges().get(2)).getTargetNode()); assertEquals(candidate, ((Edge) stage.getOutEdges().get(0)).getTargetNode()); assertEquals(1, end.getInEdges().stream().filter(sequencePredicate()).count()); assertEquals(candidate, ((List) end.getInEdges().stream().filter(sequencePredicate()) .map(e -> ((Edge) e).getSourceNode()).collect(Collectors.toList())).get(0)); }"
389,"<START> public void updateFeedbackQuestion(FeedbackQuestionAttributes newAttributes, boolean hasResponseRateUpdate) <END> throws InvalidParametersException, EntityDoesNotExistException { FeedbackQuestionAttributes oldQuestion = null; if (newAttributes.getId() == null) { oldQuestion = fqDb.getFeedbackQuestion(newAttributes.feedbackSessionName, newAttributes.courseId, newAttributes.questionNumber); } else { oldQuestion = fqDb.getFeedbackQuestion(newAttributes.getId()); } if (oldQuestion == null) { throw new EntityDoesNotExistException( ""Trying to update a feedback question that does not exist.""); } if(oldQuestion.isChangesRequiresResponseDeletion(newAttributes)) { frLogic.deleteFeedbackResponsesForQuestionAndCascade(oldQuestion.getId(), hasResponseRateUpdate); } oldQuestion.updateValues(newAttributes); newAttributes.removeIrrelevantVisibilityOptions(); fqDb.updateFeedbackQuestion(newAttributes); }","@unyoungwax, able this private too","private void updateFeedbackQuestion(FeedbackQuestionAttributes newAttributes, boolean hasResponseRateUpdate) throws InvalidParametersException, EntityDoesNotExistException { FeedbackQuestionAttributes oldQuestion = null; if (newAttributes.getId() == null) { oldQuestion = fqDb.getFeedbackQuestion(newAttributes.feedbackSessionName, newAttributes.courseId, newAttributes.questionNumber); } else { oldQuestion = fqDb.getFeedbackQuestion(newAttributes.getId()); } if (oldQuestion == null) { throw new EntityDoesNotExistException( ""Trying to update a feedback question that does not exist.""); } if(oldQuestion.isChangesRequiresResponseDeletion(newAttributes)) { frLogic.deleteFeedbackResponsesForQuestionAndCascade(oldQuestion.getId(), hasResponseRateUpdate); } oldQuestion.updateValues(newAttributes); newAttributes.removeIrrelevantVisibilityOptions(); fqDb.updateFeedbackQuestion(newAttributes); }"
390,"public ArrayList<LectureSlide> getLectureSlide(final List<String> slideId, final String userId) throws AuthenticationException, DatabaseAccessException { final long currentTime = System.currentTimeMillis(); final ArrayList<LectureSlide> allSlides = new ArrayList<LectureSlide>(); for (int slides = slideId.size() - 1; slides >= 0; slides--) { try { allSlides.add(SlideManager.mongoGetLectureSlide(getInstance().auth, getInstance().database, slideId.get(slides), userId, currentTime)); } catch (DatabaseAccessException e) { LOG.info(LoggingConstants.EXCEPTION_MESSAGE, e); if (!e.isRecoverable()) { throw e; } } catch (AuthenticationException e) { <START> LOG.error(""Error: {}"", e); <END> if (e.getType() != AuthenticationException.INVALID_DATE) { throw e; } } } return allSlides; }",constant,"public ArrayList<LectureSlide> getLectureSlide(final List<String> slideId, final String userId) throws AuthenticationException, DatabaseAccessException { final long currentTime = System.currentTimeMillis(); final ArrayList<LectureSlide> allSlides = new ArrayList<LectureSlide>(); for (int slides = slideId.size() - 1; slides >= 0; slides--) { try { allSlides.add(SlideManager.mongoGetLectureSlide(getInstance().auth, getInstance().database, slideId.get(slides), userId, currentTime)); } catch (DatabaseAccessException e) { LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); if (!e.isRecoverable()) { throw e; } } catch (AuthenticationException e) { LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); if (e.getType() != AuthenticationException.INVALID_DATE) { throw e; } } } return allSlides; }"
391,"protected void run() throws Exception { if (localName != null && gitdir != null) throw die(CLIText.get().conflictingUsageOf_git_dir_andArguments); final URIish uri = new URIish(sourceUri); if (localName == null) { try { localName = uri.getHumanishName(); } catch (IllegalArgumentException e) { throw die(MessageFormat.format(CLIText.get().cannotGuessLocalNameFrom, sourceUri)); } } if (branch == null) branch = Constants.HEAD; CloneCommand command = Git.cloneRepository(); command.setURI(sourceUri).setRemote(remoteName) .setNoCheckout(noCheckout).setBranch(branch); String dirPath = """"; if (localName != null && localName.length() > 0) dirPath = localName; if (gitdir != null && gitdir.length() > 0) dirPath = gitdir; <START> command.setDirectory(new File(dirPath)); <END> try { outw.println(MessageFormat.format(CLIText.get().cloningInto, dirPath)); Repository db = command.call().getRepository(); if (db.resolve(Constants.HEAD) == null) outw.println(CLIText.get().clonedEmptyRepository); } catch (InvalidRemoteException e) { throw die(MessageFormat.format(CLIText.get().doesNotExist, sourceUri)); } outw.println(); outw.flush(); }",if gitDir localName set (to clone a repo repo a non-standard layout)? I simply command.setDirectory(localname); command.setGitDir(gitDir); validation of localname (null not) gitdir done in CloneCommand,"protected void run() throws Exception { if (localName != null && gitdir != null) throw die(CLIText.get().conflictingUsageOf_git_dir_andArguments); final URIish uri = new URIish(sourceUri); if (localName == null) { try { localName = uri.getHumanishName(); } catch (IllegalArgumentException e) { throw die(MessageFormat.format(CLIText.get().cannotGuessLocalNameFrom, sourceUri)); } } if (branch == null) branch = Constants.HEAD; CloneCommand command = Git.cloneRepository(); command.setURI(sourceUri).setRemote(remoteName) .setNoCheckout(noCheckout).setBranch(branch); command.setGitDir(gitdir == null ? null : new File(gitdir)); command.setDirectory(localName == null ? null : new File(localName)); try { outw.println(MessageFormat.format(CLIText.get().cloningInto, command.getDirectory().getPath())); db = command.call().getRepository(); if (db.resolve(Constants.HEAD) == null) outw.println(CLIText.get().clonedEmptyRepository); } catch (InvalidRemoteException e) { throw die(MessageFormat.format(CLIText.get().doesNotExist, sourceUri)); } finally { if (db != null) db.close(); } outw.println(); outw.flush(); }"
392,"public PlatformResourceRequest getPlatformResourceRequest( String accountId, String credentialName, String credentialCrn, String region, String platformVariant, String availabilityZone, AccessConfigTypeQueryParam accessConfigType, CdpResourceType cdpResourceType) { PlatformResourceRequest platformResourceRequest = new PlatformResourceRequest(); if (!Strings.isNullOrEmpty(credentialName)) { <START> Credential credential = credentialService.getByNameForAccountId(credentialName, accountId, ENVIRONMENT); <END> if (credential == null) { credential = credentialService.getByNameForAccountId(credentialName, accountId, AUDIT); } platformResourceRequest.setCredential(credential); } else if (!Strings.isNullOrEmpty(credentialCrn)) { Credential credential = credentialService.getByCrnForAccountId(credentialCrn, accountId, ENVIRONMENT); if (credential == null) { credential = credentialService.getByCrnForAccountId(credentialCrn, accountId, AUDIT); } platformResourceRequest.setCredential(credential); } else { throw new BadRequestException(""The credentialCrn or the credentialName must be specified in the request""); } if (!Strings.isNullOrEmpty(platformVariant)) { platformResourceRequest.setCloudPlatform(platformResourceRequest.getCredential().getCloudPlatform()); } else { platformResourceRequest.setPlatformVariant( Strings.isNullOrEmpty(platformVariant) ? platformResourceRequest.getCredential().getCloudPlatform() : platformVariant); } platformResourceRequest.setCdpResourceType(Objects.requireNonNullElse(cdpResourceType, CdpResourceType.DEFAULT)); platformResourceRequest.setRegion(region); platformResourceRequest.setCloudPlatform(platformResourceRequest.getCredential().getCloudPlatform()); if (!Strings.isNullOrEmpty(availabilityZone)) { platformResourceRequest.setAvailabilityZone(availabilityZone); } String accessConfigTypeString = NullUtil.getIfNotNull(accessConfigType, Enum::name); if (accessConfigTypeString != null) { platformResourceRequest.setFilters(Map.of(ACCESS_CONFIG_TYPE, accessConfigTypeString)); } return platformResourceRequest; }",do in request? filter for type,"public PlatformResourceRequest getPlatformResourceRequest( String accountId, String credentialName, String credentialCrn, String region, String platformVariant, String availabilityZone, AccessConfigTypeQueryParam accessConfigType, CdpResourceType cdpResourceType) { PlatformResourceRequest platformResourceRequest = new PlatformResourceRequest(); if (!Strings.isNullOrEmpty(credentialName)) { Optional<Credential> credential = credentialService.getOptionalByNameForAccountId(credentialName, accountId, ENVIRONMENT); if (credential.isEmpty()) { credential = credentialService.getOptionalByNameForAccountId(credentialName, accountId, AUDIT); } platformResourceRequest.setCredential(credentialService.extractCredential(credential, credentialName)); } else if (!Strings.isNullOrEmpty(credentialCrn)) { Optional<Credential> credential = credentialService.getOptionalByCrnForAccountId(credentialCrn, accountId, ENVIRONMENT); if (credential.isEmpty()) { credential = credentialService.getOptionalByCrnForAccountId(credentialCrn, accountId, AUDIT); } platformResourceRequest.setCredential(credentialService.extractCredential(credential, credentialCrn)); } else { throw new BadRequestException(""The credentialCrn or the credentialName must be specified in the request""); } if (!Strings.isNullOrEmpty(platformVariant)) { platformResourceRequest.setCloudPlatform(platformResourceRequest.getCredential().getCloudPlatform()); } else { platformResourceRequest.setPlatformVariant( Strings.isNullOrEmpty(platformVariant) ? platformResourceRequest.getCredential().getCloudPlatform() : platformVariant); } platformResourceRequest.setCdpResourceType(Objects.requireNonNullElse(cdpResourceType, CdpResourceType.DEFAULT)); platformResourceRequest.setRegion(region); platformResourceRequest.setCloudPlatform(platformResourceRequest.getCredential().getCloudPlatform()); if (!Strings.isNullOrEmpty(availabilityZone)) { platformResourceRequest.setAvailabilityZone(availabilityZone); } String accessConfigTypeString = NullUtil.getIfNotNull(accessConfigType, Enum::name); if (accessConfigTypeString != null) { platformResourceRequest.setFilters(Map.of(ACCESS_CONFIG_TYPE, accessConfigTypeString)); } return platformResourceRequest; }"
393,"public boolean rename(ByteArrayWrapper oldKey, ByteArrayWrapper newKey) { <START> Object value = localRegion.get(oldKey); <END> localRegion.put(newKey, value); del(oldKey); return true; }",if get returns null? I in case rename immediately return false,"public boolean rename(ByteArrayWrapper oldKey, ByteArrayWrapper newKey) { RedisData value = getRedisData(oldKey); if (value == null) { return false; } region.put(newKey, value); region.remove(oldKey); return true; }"
394,<START> public Boolean getKeepNullColumns() <END> { return keepNullColumns; },boolean too,public boolean getKeepNullColumns() { return keepNullColumns; }
395,"public String getDefaultDunningCampaignCode() { String parameterDunningCampaignCode = """"; <START> if (getParameterService().parameterExists(DunningCampaign.class, ArConstants.DEFAULT_DUNNING_CAMPAIGN_PARAMETER)) { <END> parameterDunningCampaignCode = getParameterService().getParameterValueAsString(DunningCampaign.class, ArConstants.DEFAULT_DUNNING_CAMPAIGN_PARAMETER); } return parameterDunningCampaignCode; }",Do need this anymore? send empty string a default,"public String getDefaultDunningCampaignCode() { return getParameterService().getParameterValueAsString(DunningCampaign.class, ArConstants.DEFAULT_DUNNING_CAMPAIGN_PARAMETER,""""); }"
396,"public String getImageUrl(String imageName) { for (WebElement elem:imagesNewFiles) { String href = elem.findElement(parentBy).getAttribute(""href""); if (href.contains(imageName)){ return href; } } <START> return null; <END> }",exception handled that. Program inform wanted image found,"public String getImageUrl(String imageName) { for (WebElement elem:imagesNewFiles) { String href = elem.findElement(parentBy).getAttribute(""href""); if (href.contains(imageName)){ return href; } } throw new RuntimeException(""there is no "" + imageName + "" on Special:NewFiles page""); }"
397,"public void delete() throws IOException { File rootDir = getRootDir(); if (!rootDir.isDirectory()) { LOGGER.warning(String.format( ""%s: %s looks to have already been deleted, assuming build dir was already cleaned up"", this, rootDir )); RunListener.fireDeleted(this); synchronized (this) { removeRunFromParent(); } return; } RunListener.fireDeleted(this); if (artifactManager != null) { deleteArtifacts(); } synchronized (this) { File tmp = new File(rootDir.getParentFile(),'.'+rootDir.getName()); if (tmp.exists()) { Util.deleteRecursive(tmp); } boolean renamingSucceeded = true; try { <START> Path path = Files.move(rootDir.toPath(), tmp.toPath(), StandardCopyOption.ATOMIC_MOVE); <END> } catch (UnsupportedOperationException | IOException | SecurityException ex) { renamingSucceeded = rootDir.renameTo(tmp); } Util.deleteRecursive(tmp); if (tmp.exists()) { tmp.deleteOnExit(); } if (!renamingSucceeded) { throw new IOException(rootDir + "" is in use""); } LOGGER.log(FINE, ""{0}: {1} successfully deleted"", new Object[] {this, rootDir}); removeRunFromParent(); } }","InvalidPathException is handled here. I recommend Util#fileToPath() instead. <LINK_0> suggestion Path path = Files.move(rootDir.toPath(), Util.fileToPath(), StandardCopyOption.ATOMIC_MOVE);","public void delete() throws IOException { File rootDir = getRootDir(); if (!rootDir.isDirectory()) { LOGGER.warning(String.format( ""%s: %s looks to have already been deleted, assuming build dir was already cleaned up"", this, rootDir )); RunListener.fireDeleted(this); synchronized (this) { removeRunFromParent(); } return; } RunListener.fireDeleted(this); if (artifactManager != null) { deleteArtifacts(); } synchronized (this) { File tmp = new File(rootDir.getParentFile(),'.'+rootDir.getName()); if (tmp.exists()) { Util.deleteRecursive(tmp); } try { Files.move( Util.fileToPath(rootDir), Util.fileToPath(tmp), StandardCopyOption.ATOMIC_MOVE ); } catch (UnsupportedOperationException | SecurityException ex) { throw new IOException(rootDir + "" is in use""); } Util.deleteRecursive(tmp); if (tmp.exists()) { tmp.deleteOnExit(); } LOGGER.log(FINE, ""{0}: {1} successfully deleted"", new Object[] {this, rootDir}); removeRunFromParent(); } }"
398,"void addPreference(String userID, String productID, float score) { <START> reviewCount++; <END> if (!userIDs.containsKey(userID)) userIDs.put(userID, ++userCount); if (!productIDsBi.containsKey(productID)) productIDsBi.put(productID, ++productCount); Long longUserID = userIDs.get(userID); Long longProductID = productIDsBi.get(productID); addPreferenceToUser((GenericUserPreferenceArray) usersPreferences.get(longUserID),new GenericPreference(longUserID, longProductID, score)); }",This part relationship addPreference method. Try split methods,"private void addPreference(String userID, String productID, float score) { reviewCount++; if (!userIDs.containsKey(userID)) userIDs.put(userID, ++userCount); if (!productIDsBi.containsKey(productID)) productIDsBi.put(productID, ++productCount); Long longUserID = userIDs.get(userID); Long longProductID = productIDsBi.get(productID); addPreferenceToUser((GenericUserPreferenceArray) usersPreferences.get(longUserID),new GenericPreference(longUserID, longProductID, score)); }"
399,"public void becomeUser( final String principalName, final IParameterProvider paramProvider ) { UserSession session = null; tenantedUserNameUtils = getTenantedUserNameUtils(); if ( tenantedUserNameUtils != null ) { session = new UserSession( principalName, null, false, paramProvider ); ITenant tenant = tenantedUserNameUtils.getTenant( principalName ); session.setAttribute( IPentahoSession.TENANT_ID_KEY, tenant.getId() ); session.setAuthenticated( tenant.getId(), principalName ); } else { session = new UserSession( principalName, null, false, paramProvider ); session.setAuthenticated( principalName ); } PentahoSessionHolder.setSession( session ); Authentication auth = createAuthentication( principalName ); <START> PentahoSessionHolder.getSession().setAttribute( ""roles"", auth.getAuthorities() ); <END> SecurityContextHolder.clearContext(); SecurityContextHolder.getContext().setAuthentication( auth ); PentahoSystem.sessionStartup( PentahoSessionHolder.getSession(), paramProvider ); }","replace ""roles"" IPentahoSession.SESSION_ROLES","public void becomeUser( final String principalName, final IParameterProvider paramProvider ) { UserSession session = null; tenantedUserNameUtils = getTenantedUserNameUtils(); if ( tenantedUserNameUtils != null ) { session = new UserSession( principalName, null, false, paramProvider ); ITenant tenant = tenantedUserNameUtils.getTenant( principalName ); session.setAttribute( IPentahoSession.TENANT_ID_KEY, tenant.getId() ); session.setAuthenticated( tenant.getId(), principalName ); } else { session = new UserSession( principalName, null, false, paramProvider ); session.setAuthenticated( principalName ); } PentahoSessionHolder.setSession( session ); Authentication auth = createAuthentication( principalName ); PentahoSessionHolder.getSession().setAttribute( IPentahoSession.SESSION_ROLES, auth.getAuthorities() ); SecurityContextHolder.clearContext(); SecurityContextHolder.getContext().setAuthentication( auth ); PentahoSystem.sessionStartup( PentahoSessionHolder.getSession(), paramProvider ); }"
400,"private boolean bootstrapRealtimeTable(String tableName, File schemaFile, File realtimeTableConfigFile) throws Exception { <START> Quickstart.printStatus(Quickstart.Color.CYAN, String.format(""***** Adding %s realtime table *****"", tableName)); <END> if (!new AddTableCommand().setSchemaFile(schemaFile.getAbsolutePath()) .setTableConfigFile(realtimeTableConfigFile.getAbsolutePath()).setControllerHost(_controllerHost) .setControllerPort(String.valueOf(_controllerPort)).setExecute(true).execute()) { throw new RuntimeException(String .format(""Unable to create realtime table - %s from schema file [%s] and table conf file [%s]."", tableName, schemaFile, realtimeTableConfigFile)); } return true; }",logger in other places,"private boolean bootstrapRealtimeTable(String tableName, File schemaFile, File realtimeTableConfigFile) throws Exception { LOGGER.info(""Adding realtime table {}"", tableName); if (!createTable(schemaFile, realtimeTableConfigFile)) { throw new RuntimeException(String .format(""Unable to create realtime table - %s from schema file [%s] and table conf file [%s]."", tableName, schemaFile, realtimeTableConfigFile)); } return true; }"
401,"public void initTable() { <START> AbstractTextColumn<GuestContainer> idColumn = new AbstractTextColumn<GuestContainer>() { <END> @Override public String getValue(GuestContainer row) { if(row != null) { return row.getId(); } return constants.empty(); } }; AbstractTextColumn<GuestContainer> namesColumn = new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { if (row != null && row.getNames() != null) { return StringUtils.join(row.getNames(), "", ""); } return constants.empty(); } }; AbstractTextColumn<GuestContainer> imageColumn = new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { if (row != null) { return row.getImage(); } return constants.empty(); } }; AbstractTextColumn<GuestContainer> commandColumn = new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { if (row != null) { return row.getCommand(); } return constants.empty(); } }; AbstractTextColumn<GuestContainer> statusColumn = new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { if (row != null) { return row.getStatus(); } return constants.empty(); } }; getTable().addColumn(idColumn, constants.idContainer()); getTable().addColumn(namesColumn, constants.namesContainer()); getTable().addColumn(imageColumn, constants.imageContainer()); getTable().addColumn(commandColumn, constants.commandContainer()); getTable().addColumn(statusColumn, constants.statusContainer()); }","personally I prefer inline instantiation of columns in call table.addColumn (as in line 72) code more compact easier add/remove/move columns - especially need reference individual column instances for some additional tweaks. if strongly prefer this style, OK it","public void initTable() { getTable().addColumn(new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { if (row != null) { return row.getId(); } return constants.empty(); } }, constants.idContainer()); getTable().addColumn(new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return StringUtils.join(row.getNames(), "", ""); } }, constants.namesContainer()); getTable().addColumn(new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return row.getImage(); } }, constants.imageContainer()); getTable().addColumn(new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return row.getCommand(); } }, constants.commandContainer()); getTable().addColumn(new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return row.getStatus(); } }, constants.statusContainer()); }"
402,"public static <T> TupleDomain<T> columnWiseUnion(List<TupleDomain<T>> tupleDomains) { if (tupleDomains.isEmpty()) { throw new IllegalArgumentException(""tupleDomains must have at least one element""); } if (tupleDomains.size() == 1) { return tupleDomains.get(0); } <START> Set<T> commonColumns = new LinkedHashSet<>(); <END> boolean found = false; Iterator<TupleDomain<T>> domains = tupleDomains.iterator(); while (domains.hasNext()) { TupleDomain<T> domain = domains.next(); if (!domain.isNone()) { found = true; commonColumns.addAll(domain.getDomains().get().keySet()); break; } } if (!found) { return TupleDomain.none(); } while (domains.hasNext()) { TupleDomain<T> domain = domains.next(); if (!domain.isNone()) { commonColumns.retainAll(domain.getDomains().get().keySet()); } } Map<T, List<Domain>> domainsByColumn = new LinkedHashMap<>(tupleDomains.size()); for (TupleDomain<T> domain : tupleDomains) { if (!domain.isNone()) { for (Map.Entry<T, Domain> entry : domain.getDomains().get().entrySet()) { if (commonColumns.contains(entry.getKey())) { List<Domain> domainForColumn = domainsByColumn.get(entry.getKey()); if (domainForColumn == null) { domainForColumn = new ArrayList<>(); domainsByColumn.put(entry.getKey(), domainForColumn); } domainForColumn.add(entry.getValue()); } } } } Map<T, Domain> result = new LinkedHashMap<>(domainsByColumn.size()); for (Map.Entry<T, List<Domain>> entry : domainsByColumn.entrySet()) { result.put(entry.getKey(), Domain.union(entry.getValue())); } return withColumnDomains(result); }",Unneeded change,"public static <T> TupleDomain<T> columnWiseUnion(List<TupleDomain<T>> tupleDomains) { if (tupleDomains.isEmpty()) { throw new IllegalArgumentException(""tupleDomains must have at least one element""); } if (tupleDomains.size() == 1) { return tupleDomains.get(0); } Set<T> commonColumns = new HashSet<>(); boolean found = false; Iterator<TupleDomain<T>> domains = tupleDomains.iterator(); while (domains.hasNext()) { TupleDomain<T> domain = domains.next(); if (!domain.isNone()) { found = true; commonColumns.addAll(domain.getDomains().get().keySet()); break; } } if (!found) { return TupleDomain.none(); } while (domains.hasNext()) { TupleDomain<T> domain = domains.next(); if (!domain.isNone()) { commonColumns.retainAll(domain.getDomains().get().keySet()); } } Map<T, List<Domain>> domainsByColumn = new LinkedHashMap<>(tupleDomains.size()); for (TupleDomain<T> domain : tupleDomains) { if (!domain.isNone()) { for (Map.Entry<T, Domain> entry : domain.getDomains().get().entrySet()) { if (commonColumns.contains(entry.getKey())) { List<Domain> domainForColumn = domainsByColumn.get(entry.getKey()); if (domainForColumn == null) { domainForColumn = new ArrayList<>(); domainsByColumn.put(entry.getKey(), domainForColumn); } domainForColumn.add(entry.getValue()); } } } } Map<T, Domain> result = new LinkedHashMap<>(domainsByColumn.size()); for (Map.Entry<T, List<Domain>> entry : domainsByColumn.entrySet()) { result.put(entry.getKey(), Domain.union(entry.getValue())); } return withColumnDomains(result); }"
403,"public void testParsingCombined() { for (DependencyParser parser : parsers) { { DependencyParser.DependencyInfo info = parser.parseDependencies(""required:supermod3000@[1.2,)""); assertContainsSameToString(info.requirements, Sets.newHashSet(""supermod3000@[1.2,)"")); assertTrue(info.dependants.isEmpty()); assertTrue(info.dependencies.isEmpty()); assertTrue(info.softRequirements.isEmpty()); } { String dependencyString = ""after:supermod2000@[1.3,);required-before:yetanothermod;softDepMod@[1.0,2.0);required:modW""; DependencyParser.DependencyInfo info = parser.parseDependencies(dependencyString); assertContainsSameToString(info.requirements, Sets.newHashSet(""yetanothermod"", ""modW"")); <START> assertContainsSameToString(info.softRequirements, Sets.newHashSet(""softDepMod@[1.0,2.0)"")); <END> assertContainsSameToString(info.dependencies, Sets.newHashSet(""supermod2000@[1.3,)"")); assertContainsSameToString(info.dependants, Sets.newHashSet(""yetanothermod"")); } } }","lowercase, people reference this test for examples uppercase mod ids is isn't","public void testParsingCombined() { for (DependencyParser parser : parsers) { String dependencyString = ""after:supermod2000@[1.3,);required-before:yetanothermod;required:modw""; DependencyParser.DependencyInfo info = parser.parseDependencies(dependencyString); assertContainsSameToString(info.requirements, Sets.newHashSet(""yetanothermod"", ""modw"")); assertContainsSameToString(info.dependencies, Sets.newHashSet(""supermod2000@[1.3,)"")); assertContainsSameToString(info.dependants, Sets.newHashSet(""yetanothermod"")); } }"
404,"public static ServerScope parse(String scope) throws IllegalArgumentException { if (scope.startsWith(""unlimited"")) { return new Unlimited(); } String[] chunks = scope.trim().split("":"", 2); <START> if (chunks.length != 2) throw new IllegalArgumentException(""Invalid scope: "" + scope); <END> if (""node"".equals(chunks[0])) { return new Node(chunks[1]); } else if (""run"".equals(chunks[0])) { return new Build(chunks[1]); } else if (""time"".equals(chunks[0])) { return new Time(chunks[1]); } else { throw new IllegalArgumentException(""Invalid scope kind: "" + chunks[0]); } }",This a singleton,"public static ServerScope parse(String scope) throws IllegalArgumentException { if (scope.startsWith(""unlimited"")) { return Unlimited.getInstance(); } String[] chunks = scope.trim().split("":"", 2); if (chunks.length != 2) throw new IllegalArgumentException(""Invalid scope: "" + scope); if (""node"".equals(chunks[0])) { return new Node(chunks[1]); } else if (""run"".equals(chunks[0])) { return new Build(chunks[1]); } else if (""time"".equals(chunks[0])) { return new Time(chunks[1]); } else { throw new IllegalArgumentException(""Invalid scope kind: "" + chunks[0]); } }"
405,"public void should_not_change_other_organizations() throws Exception { OrganizationDto organization1 = OrganizationTesting.newOrganizationDto(); <START> db.organizations().insert(organization1); <END> OrganizationDto organization2 = OrganizationTesting.newOrganizationDto(); db.organizations().insert(organization2); userSessionRule .logIn() .addPermission(ADMINISTER_QUALITY_PROFILES, organization1.getUuid()); QualityProfileDto profileOrg1Old = QualityProfileTesting.newQualityProfileDto() .setOrganizationUuid(organization1.getUuid()) .setLanguage(xoo1Key) .setDefault(true); QualityProfileDto profileOrg1New = QualityProfileTesting.newQualityProfileDto() .setOrganizationUuid(organization1.getUuid()) .setLanguage(xoo1Key) .setDefault(false); QualityProfileDto profileOrg2 = QualityProfileTesting.newQualityProfileDto() .setOrganizationUuid(organization2.getUuid()) .setLanguage(xoo1Key) .setDefault(true); db.qualityProfiles().insertQualityProfiles(profileOrg1Old, profileOrg1New, profileOrg2); checkDefaultProfile(organization1, xoo1Key, profileOrg1Old.getKey()); checkDefaultProfile(organization2, xoo1Key, profileOrg2.getKey()); TestResponse response = tester.newRequest().setMethod(""POST"") .setParam(""language"", profileOrg1New.getLanguage()) .setParam(""profileName"", profileOrg1New.getName()) .setParam(""organization"", organization1.getKey()) .execute(); assertThat(response.getInput()).isEmpty(); assertThat(response.getStatus()).isEqualTo(204); checkDefaultProfile(organization1, xoo1Key, profileOrg1New.getKey()); checkDefaultProfile(organization2, xoo1Key, profileOrg2.getKee()); }",simply replaced by: OrganizationDto organization1 = db.organizations().insert();,"public void should_not_change_other_organizations() throws Exception { OrganizationDto organization1 = db.organizations().insert(); OrganizationDto organization2 = db.organizations().insert(); userSessionRule .logIn() .addPermission(ADMINISTER_QUALITY_PROFILES, organization1.getUuid()); QualityProfileDto profileOrg1Old = QualityProfileTesting.newQualityProfileDto() .setOrganizationUuid(organization1.getUuid()) .setLanguage(xoo1Key) .setDefault(true); QualityProfileDto profileOrg1New = QualityProfileTesting.newQualityProfileDto() .setOrganizationUuid(organization1.getUuid()) .setLanguage(xoo1Key) .setDefault(false); QualityProfileDto profileOrg2 = QualityProfileTesting.newQualityProfileDto() .setOrganizationUuid(organization2.getUuid()) .setLanguage(xoo1Key) .setDefault(true); db.qualityProfiles().insertQualityProfiles(profileOrg1Old, profileOrg1New, profileOrg2); checkDefaultProfile(organization1, xoo1Key, profileOrg1Old.getKey()); checkDefaultProfile(organization2, xoo1Key, profileOrg2.getKey()); TestResponse response = tester.newRequest().setMethod(""POST"") .setParam(""language"", profileOrg1New.getLanguage()) .setParam(""profileName"", profileOrg1New.getName()) .setParam(""organization"", organization1.getKey()) .execute(); assertThat(response.getInput()).isEmpty(); assertThat(response.getStatus()).isEqualTo(204); checkDefaultProfile(organization1, xoo1Key, profileOrg1New.getKey()); checkDefaultProfile(organization2, xoo1Key, profileOrg2.getKee()); }"
406,"public void selectionChanged(final SelectionChangedEvent event) { final ISelection selection = event.getSelection(); depopulateMenus(); Collection<?> newChildDescriptors = null; if (selection instanceof IStructuredSelection && ((IStructuredSelection) selection).size() == 1) { final Object object = ((IStructuredSelection) selection).getFirstElement(); final EditingDomain domain = ((IEditingDomainProvider) activeEditorPart).getEditingDomain(); newChildDescriptors = domain.getNewChildDescriptors(object, null); <START> } else if (((IStructuredSelection) selection).size() > 1) { <END> newChildDescriptors = Lists.newArrayList(); } if (newChildDescriptors != null) { updateChildDescriptorMenus(selection, newChildDescriptors); } populateMenus(); }","Joao, selection is a IStructuredSelection here, if test return false becauseof selection type. Please review entire if block: if (sel instanceof IStruc..ion) { if (size ==1) { ... } else if (size > 1) { ... } }","public void selectionChanged(final SelectionChangedEvent event) { final ISelection selection = event.getSelection(); depopulateMenus(); Collection<?> newChildDescriptors = null; if (selection instanceof IStructuredSelection) { IStructuredSelection stsel = (IStructuredSelection) selection; if (stsel.size() == 1) { final Object object = ((IStructuredSelection) selection).getFirstElement(); final EditingDomain domain = ((IEditingDomainProvider) activeEditorPart).getEditingDomain(); newChildDescriptors = domain.getNewChildDescriptors(object, null); } else if (stsel.size() > 1) { newChildDescriptors = Lists.newArrayList(); } } if (newChildDescriptors != null) { updateChildDescriptorMenus(selection, newChildDescriptors); } populateMenus(); }"
407,"private void createIndexToolTables(Connection connection) throws Exception { ConnectionQueryServices queryServices = connection.unwrap(PhoenixConnection.class).getQueryServices(); Admin admin = queryServices.getAdmin(); <START> if (!admin.tableExists(TableName.valueOf(OUTPUT_TABLE_NAME))) { <END> HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(OUTPUT_TABLE_NAME)); tableDescriptor.setValue(""DISABLE_TABLE_SOR"", ""true""); tableDescriptor.setValue(HColumnDescriptor.TTL, String.valueOf(MetaDataProtocol.DEFAULT_LOG_TTL)); HColumnDescriptor columnDescriptor = new HColumnDescriptor(OUTPUT_TABLE_COLUMN_FAMILY); tableDescriptor.addFamily(columnDescriptor); admin.createTable(tableDescriptor); } if (!admin.tableExists(TableName.valueOf(RESULT_TABLE_NAME))) { HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(RESULT_TABLE_NAME)); tableDescriptor.setValue(""DISABLE_TABLE_SOR"", ""true""); tableDescriptor.setValue(HColumnDescriptor.TTL, String.valueOf(MetaDataProtocol.DEFAULT_LOG_TTL)); HColumnDescriptor columnDescriptor = new HColumnDescriptor(RESULT_TABLE_COLUMN_FAMILY); tableDescriptor.addFamily(columnDescriptor); admin.createTable(tableDescriptor); } }",this work a cluster namespaces enabled,"private void createIndexToolTables(Connection connection) throws Exception { ConnectionQueryServices queryServices = connection.unwrap(PhoenixConnection.class).getQueryServices(); Admin admin = queryServices.getAdmin(); if (!admin.tableExists(TableName.valueOf(OUTPUT_TABLE_NAME))) { HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(OUTPUT_TABLE_NAME)); tableDescriptor.setValue(HColumnDescriptor.TTL, String.valueOf(MetaDataProtocol.DEFAULT_LOG_TTL)); HColumnDescriptor columnDescriptor = new HColumnDescriptor(OUTPUT_TABLE_COLUMN_FAMILY); tableDescriptor.addFamily(columnDescriptor); admin.createTable(tableDescriptor); } if (!admin.tableExists(TableName.valueOf(RESULT_TABLE_NAME))) { HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(RESULT_TABLE_NAME)); tableDescriptor.setValue(HColumnDescriptor.TTL, String.valueOf(MetaDataProtocol.DEFAULT_LOG_TTL)); HColumnDescriptor columnDescriptor = new HColumnDescriptor(RESULT_TABLE_COLUMN_FAMILY); tableDescriptor.addFamily(columnDescriptor); admin.createTable(tableDescriptor); } }"
408,public PreparedRead prepareRead(List<DriverRecord> driverRecords) { <START> requireNonNull(driverRecords); <END> OpcUaPreparedRead preparedRead = new OpcUaPreparedRead(); preparedRead.driverRecords = driverRecords; for (DriverRecord record : driverRecords) { OpcUaRequestInfo.extract(record).ifPresent(preparedRead.requestInfos::add); } return preparedRead; },I recommend a suitable localized message in precondition,"public PreparedRead prepareRead(List<DriverRecord> driverRecords) { requireNonNull(driverRecords, message.recordListNonNull()); OpcUaPreparedRead preparedRead = new OpcUaPreparedRead(); preparedRead.driverRecords = driverRecords; for (DriverRecord record : driverRecords) { OpcUaRequestInfo.extract(record).ifPresent(preparedRead.requestInfos::add); } return preparedRead; }"
409,"private boolean canLogAtLevel(int logLevel, int environmentLoggingLevel) { <START> if (logLevel < environmentLoggingLevel || logger == null) { <END> return false; } switch (logLevel) { case VERBOSE_LEVEL: return logger.isDebugEnabled(); case INFORMATIONAL_LEVEL: return logger.isInfoEnabled(); case WARNING_LEVEL: return logger.isWarnEnabled(); case ERROR_LEVEL: return logger.isErrorEnabled(); default: return false; } }",logger null. need null check here,"private boolean canLogAtLevel(int logLevel, int environmentLoggingLevel) { if (logLevel < environmentLoggingLevel) { return false; } switch (logLevel) { case VERBOSE_LEVEL: return logger.isDebugEnabled(); case INFORMATIONAL_LEVEL: return logger.isInfoEnabled(); case WARNING_LEVEL: return logger.isWarnEnabled(); case ERROR_LEVEL: return logger.isErrorEnabled(); default: return false; } }"
410,"<START> ParameterMap getQueryParams(MuleEvent event) <END> { return resolveParams(event, HttpParamType.QUERY_PARAM); }",This breaks compatibility,"public ParameterMap getQueryParams(MuleEvent event) { return resolveParams(event, HttpParamType.QUERY_PARAM); }"
411,"private void warnIfJavaVersionOutdated() { try { JavaVersion javaRuntimeVersion = JavaVersion.fromString(System.getProperty(""java.runtime.version"")); <START> JavaVersion javaRequiredVersion = JavaVersion.fromString(JavaVersion.REQUIRED_VERSION); <END> if (JavaVersion.isJavaVersionTooLow(javaRuntimeVersion, javaRequiredVersion)) { showJavaVersionOutdatedWarning(javaRuntimeVersion, javaRequiredVersion); } } catch (IllegalArgumentException e) { logger.error(""Java Version string failed to be parsed."", e); } }",required version a property of application (UI) instead. This is a bit verbose. drop some of prefixes for local variables (which ambiguous),"private void warnIfJavaVersionOutdated() { JavaVersion requiredVersion; try { requiredVersion = JavaVersion.fromString(REQUIRED_JAVA_VERSION); } catch (IllegalArgumentException e) { logger.error(""Required Java Version string cannot be parsed. This should have been covered by test.""); assert false; return; } JavaVersion runtimeVersion; String javaRuntimeVersionString = System.getProperty(""java.runtime.version""); try { runtimeVersion = JavaVersion.fromString(javaRuntimeVersionString); } catch (IllegalArgumentException e) { logger.error(""Runtime Java Version string cannot be parsed. Look at Java Doc about other version format.""); showJavaRuntimeVersionNotCompatible(System.getProperty(""java.runtime.version"")); return; } if (JavaVersion.isJavaVersionLower(runtimeVersion, requiredVersion)) { showJavaVersionOutdatedWarning(runtimeVersion, requiredVersion); } }"
412,<START> protected static String getMessageId(String rawMessageHref) { <END> return rawMessageHref.substring(rawMessageHref.lastIndexOf('/')+1); },"injectable ""hrefToMessageId"" function",private static String getMessageId(String rawMessageHref) { return rawMessageHref.substring(rawMessageHref.lastIndexOf('/')+1); }
413,"<START> public CrashGenCleaner( PagedFile pagedFile, TreeNode<?,?> treeNode, long lowTreeNodeId, long highTreeNodeId, <END> long stableGeneration, long unstableGeneration, Monitor monitor ) { this.pagedFile = pagedFile; this.treeNode = treeNode; this.lowTreeNodeId = lowTreeNodeId; this.highTreeNodeId = highTreeNodeId; this.stableGeneration = stableGeneration; this.unstableGeneration = unstableGeneration; this.monitor = monitor; this.maxKeyCount = treeNode.internalMaxKeyCount(); }",this constructor package local class is package local,"CrashGenCleaner( PagedFile pagedFile, TreeNode<?,?> treeNode, long lowTreeNodeId, long highTreeNodeId, long stableGeneration, long unstableGeneration, Monitor monitor ) { this.pagedFile = pagedFile; this.treeNode = treeNode; this.lowTreeNodeId = lowTreeNodeId; this.highTreeNodeId = highTreeNodeId; this.availableProcessors = Runtime.getRuntime().availableProcessors(); this.batchSize = min( 1000, max( 10, (highTreeNodeId - lowTreeNodeId) / (100 * availableProcessors) ) ); this.stableGeneration = stableGeneration; this.unstableGeneration = unstableGeneration; this.monitor = monitor; this.internalMaxKeyCount = treeNode.internalMaxKeyCount(); }"
414,"protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Mapbox.getInstance(this, getString(R.string.access_token)); setContentView(R.layout.activity_dds_text_field_formatting); mapView = findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(@NonNull MapboxMap mapboxMap) { mapboxMap.setStyle(Style.DARK, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull final Style style) { Toast.makeText(TextFieldFormattingActivity.this, getString(R.string.instruction_toast), Toast.LENGTH_SHORT).show(); FloatingActionButton textFontFab = findViewById(R.id.fab_toggle_font); textFontFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { adjustText(style, textFont(fontChanged ? new String[] {textFonts[1]} : new String[] {textFonts[0]})); fontChanged = !fontChanged; } }); FloatingActionButton textSizeFab = findViewById(R.id.fab_toggle_text_size); textSizeFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { adjustText(style, textSize(sizeChanged ? textSizes[1] : textSizes[0])); sizeChanged = !sizeChanged; } }); FloatingActionButton textColorFab = findViewById(R.id.fab_toggle_text_color); textColorFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { adjustText(style, textColor(colorChanged ? textColors[1] : textColors[0])); colorChanged = !colorChanged; } <START> }); <END> } }); } }); }","refactor statements, similar functionality. Additionally assigning setting click listener done in line instead","protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Mapbox.getInstance(this, getString(R.string.access_token)); setContentView(R.layout.activity_dds_text_field_formatting); mapView = findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(@NonNull final MapboxMap mapboxMap) { mapboxMap.setStyle(Style.DARK, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull final Style style) { TextFieldFormattingActivity.this.mapboxMap = mapboxMap; Toast.makeText(TextFieldFormattingActivity.this, getString(R.string.instruction_toast), Toast.LENGTH_SHORT).show(); findViewById(R.id.fab_toggle_font).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { adjustText(textFont(fontChanged ? new String[] {textFonts[1]} : new String[] {textFonts[0]})); fontChanged = !fontChanged; } }); findViewById(R.id.fab_toggle_text_size).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { adjustText(textSize(sizeChanged ? textSizes[1] : textSizes[0])); sizeChanged = !sizeChanged; } }); findViewById(R.id.fab_toggle_text_color).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { adjustText(textColor(colorChanged ? textColors[1] : textColors[0])); colorChanged = !colorChanged; } }); } }); } }); }"
415,public void setUp() throws Exception { <START> page = new WebPage(); <END> },I this full constructor WebPage.newBuilder().build();;,public void setUp() throws Exception { page = WebPage.newBuilder().build(); }
416,public Collection<Address> getLinkedAddresses() { <START> return linkedAddresses == null ? Collections.emptySet() : linkedAddresses; <END> },"a bunch of places getLinkedAddresses iterated over, collection is thread safe. need double check covered external sync get concurrent mod exceptions",public Collection<Address> getLinkedAddresses() { final Collection<Address> linkedAddresses = this.linkedAddresses; if (linkedAddresses == null) { return Collections.emptySet(); } return linkedAddresses; }
417,"protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(SIS_KEY_AUTH_STATE_NONCE, mAuthStateNonce); <START> outState.putSerializable(SIS_KEY_PKCE_MANAGER, mPKCEManager); <END> }","I forget - this automatically serialize deserialize fields of DbxPKCEManager class? IIRC this approach compat issues if change class update this code deserialize one. explicit serialize simple types, deserialize call a constructor","protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(SIS_KEY_AUTH_STATE_NONCE, mAuthStateNonce); outState.putString(SIS_KEY_PKCE_CODE_VERIFIER, mPKCEManager.getCodeVerifier()); }"
418,"void checkBlacklist(HttpRequest req, List<String> blacklist) { <START> if (blacklist.contains(req.headers().get(HttpHeaderNames.HOST).toLowerCase())) { <END> stripXFFHeaders(req); } }",a normalized() method call avoids lowercase string allocation,"void checkBlacklist(HttpRequest req, List<String> blacklist) { if (blacklist.stream().anyMatch(h -> h.equalsIgnoreCase(req.headers().get(HttpHeaderNames.HOST)))) { stripXFFHeaders(req); } }"
419,"<START> public FormValidation doCheckURIEncoding(StaplerRequest request) { <END> Jenkins.get().checkPermission(Jenkins.ADMINISTER); final String expected = ""\u57f7\u4e8b""; final String value = fixEmpty(request.getParameter(""value"")); if (!expected.equals(value)) return FormValidation.warningWithMarkup(hudson.model.Messages.Hudson_NotUsesUTF8ToDecodeURL()); return FormValidation.ok(); }",unrelated,"public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException { Jenkins.get().checkPermission(Jenkins.ADMINISTER); final String expected = ""\u57f7\u4e8b""; final String value = fixEmpty(request.getParameter(""value"")); if (!expected.equals(value)) return FormValidation.warningWithMarkup(hudson.model.Messages.Hudson_NotUsesUTF8ToDecodeURL()); return FormValidation.ok(); }"
420,"private void cleanConnection(StorageServerConnections connection, Guid hostId) { <START> if (connection.getid()!=null && !connection.getid().equalsIgnoreCase("""")) { <END> Frontend.RunAction(VdcActionType.RemoveStorageServerConnection, new StorageServerConnectionParametersBase(connection, hostId), null, this); } }","is point in case sensitive check for empty string. Also, StringUtils.isEmpty(connection.getId())","private void cleanConnection(StorageServerConnections connection, Guid hostId) { if (connection.getid() != null && !connection.getid().equals("""")) { Frontend.RunAction(VdcActionType.RemoveStorageServerConnection, new StorageServerConnectionParametersBase(connection, hostId), null, this); } }"
421,private Invocable lazyGetTemplateInvocable() { if (templateInvocable == null) { <START> synchronized(this) { <END> templateInvocable = newTemplateInvocable(params); } } return templateInvocable; },synchronized is unnecessary Context is (must be) instanciated for thread. purpose of Context class is making invokeTemplate single-threaded,private Invocable lazyGetTemplateInvocable() { if (templateInvocable == null) { templateInvocable = newTemplateInvocable(params); } return templateInvocable; }
422,"public void resourceChanged(IResourceChangeEvent event) { if (event.getType() == IResourceChangeEvent.PRE_DELETE || event.getType() == IResourceChangeEvent.PRE_CLOSE) { if (event.getResource() instanceof IProject) { IProject project = (IProject) event.getResource(); try { <START> if (project.hasNature(TmfProjectNature.ID)) { <END> TmfProjectElement tmfProjectElement = registry.get(project); if (tmfProjectElement == null) { return; } final List<TmfTraceElement> traces = tmfProjectElement.getTracesFolder().getTraces(); if (!traces.isEmpty()) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { for (TmfTraceElement traceElement : traces) { traceElement.closeEditors(); } } }); } } } catch (CoreException e) { Activator.getDefault().logError(""Error handling resource change event for "" + project.getName(), e); } } } else if (event.getType() == IResourceChangeEvent.POST_CHANGE) { for (IResourceDelta delta : event.getDelta().getAffectedChildren()) { if (delta.getResource() instanceof IProject) { IProject project = (IProject) delta.getResource(); try { if (delta.getKind() == IResourceDelta.CHANGED && project.isOpen() && project.hasNature(TmfProjectNature.ID)) { TmfProjectElement projectElement = getProject(project, true); projectElement.refresh(); } else if (delta.getKind() == IResourceDelta.REMOVED) { registry.remove(project); } } catch (CoreException e) { Activator.getDefault().logError(""Error handling resource change event for "" + project.getName(), e); } } } } }",I get this if closed. fix time org.eclipse.core.internal.resources.ResourceException: Resource '/delete-me' is open. org.eclipse.core.internal.resources.Project.checkAccessible(Project.java:150) org.eclipse.core.internal.resources.Project.hasNature(Project.java:584) org.eclipse.linuxtools.tmf.ui.project.model.TmfProjectRegistry.resourceChanged(TmfProjectRegistry.java:163),"public void resourceChanged(IResourceChangeEvent event) { if (event.getType() == IResourceChangeEvent.PRE_DELETE || event.getType() == IResourceChangeEvent.PRE_CLOSE) { if (event.getResource() instanceof IProject) { IProject project = (IProject) event.getResource(); try { if (project.isAccessible() && project.hasNature(TmfProjectNature.ID)) { TmfProjectElement tmfProjectElement = registry.get(project); if (tmfProjectElement == null) { return; } final List<TmfTraceElement> traces = tmfProjectElement.getTracesFolder().getTraces(); if (!traces.isEmpty()) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { for (TmfTraceElement traceElement : traces) { traceElement.closeEditors(); } } }); } } } catch (CoreException e) { Activator.getDefault().logError(""Error handling resource change event for "" + project.getName(), e); } } } else if (event.getType() == IResourceChangeEvent.POST_CHANGE) { for (IResourceDelta delta : event.getDelta().getAffectedChildren()) { if (delta.getResource() instanceof IProject) { IProject project = (IProject) delta.getResource(); try { if (delta.getKind() == IResourceDelta.CHANGED && project.isOpen() && project.hasNature(TmfProjectNature.ID)) { TmfProjectElement projectElement = getProject(project, true); projectElement.refresh(); } else if (delta.getKind() == IResourceDelta.REMOVED) { registry.remove(project); } } catch (CoreException e) { Activator.getDefault().logError(""Error handling resource change event for "" + project.getName(), e); } } } } }"
423,"private void retrieveDescriptor(String connectorType) { Filter filter; try { <START> filter = serviceUtils.makeFilter(ConnectorProvider.class, String.format(""(connector=%s)"", connectorType)); <END> } catch (InvalidSyntaxException e) { throw new IllegalArgumentException(e); } ConnectorProvider connectorProvider = serviceUtils.getOsgiServiceProxy(filter, ConnectorProvider.class); descriptor = connectorProvider.getDescriptor(); }",Constants.CONNECTOR,"private void retrieveDescriptor(String connectorType) { Filter filter = serviceUtils.makeFilter(ConnectorProvider.class, String.format(""(%s=%s)"", Constants.CONNECTOR_KEY, connectorType)); ConnectorProvider connectorProvider = serviceUtils.getOsgiServiceProxy(filter, ConnectorProvider.class); descriptor = connectorProvider.getDescriptor(); }"
424,"public FeatureFinderMetaboDetector(File mzMLFile) throws FeatureFinderMetaboException { this.mzMLFile = mzMLFile; <START> FEATURE_XML_FILE = new File(mzMLFile.getName() + ""featureXML""); <END> OPENMS_FEATURE_FINDER_METABO_LIBRARY_NAME = FeatureFinderMetaboLocator.findFeatureFinderMetabo(); }",File.createTempFile() here? combine File.deleteOnExit(),"public FeatureFinderMetaboDetector(File mzMLFile) throws MSDKException { this.mzMLFile = mzMLFile; FEATURE_XML_FILE = new File(System.getProperty(""java.io.tmpdir"") + UUID.randomUUID() + "".featureXML""); OPENMS_FEATURE_FINDER_METABO_LIBRARY_NAME = FeatureFinderMetaboLocator.findFeatureFinderMetabo(); mzMLFILE_PATH = mzMLFile.getAbsolutePath(); FEATURE_XML_FILE_PATH = FEATURE_XML_FILE.getAbsolutePath(); }"
425,"private void flushRaw(int limit) throws IOException { int expectedPacketSize = limit + HEADER_LENGTH * ((limit / maxPacketSize) + 1); int notCompressPosition = 0; while (notCompressPosition < expectedPacketSize) { int length = buffer.remaining(); if (length > maxPacketSize) { length = maxPacketSize; } byte[] header = new byte[HEADER_LENGTH]; header[0] = (byte) (length & 0xff); header[1] = (byte) (length >>> 8); header[2] = (byte) (length >>> 16); header[3] = (byte) seqNo++; outputStream.write(header, 0, HEADER_LENGTH); notCompressPosition += 4; if (length > 0) { <START> this.buffer.writeTo(this.outputStream); <END> this.outputStream.flush(); notCompressPosition += length; } } }","write ""length"" bytes, this.buffer.writeTo(this.outputStream, 0, length); Packet max size is set in variable maxPacketSize (server option max_allowed_packet). if sending more this size, database close socket","private void flushRaw(int limit) throws IOException { int expectedPacketSize = limit + HEADER_LENGTH * ((limit / maxPacketSize) + 1); if (limit < maxPacketSize) { byte[] header = this.header; header[0] = (byte) (limit & 0xff); header[1] = (byte) (limit >>> 8); header[2] = (byte) (limit >>> 16); header[3] = (byte) seqNo++; outputStream.write(header, 0, HEADER_LENGTH); this.buffer.writeTo(this.outputStream); } else { int notCompressPosition = 0; while (notCompressPosition < expectedPacketSize) { int length = buffer.remaining(); if (length > maxPacketSize) { length = maxPacketSize; } byte[] header = this.header; header[0] = (byte) (length & 0xff); header[1] = (byte) (length >>> 8); header[2] = (byte) (length >>> 16); header[3] = (byte) seqNo++; outputStream.write(header, 0, HEADER_LENGTH); notCompressPosition += 4; if (length > 0) { this.buffer.writePartTo(this.outputStream, length); notCompressPosition += length; } } } }"
426,"public static AndroidFxAccount unpickle(final Context context, final String filename) { final Account existingAccount = FirefoxAccounts.getFirefoxAccount(context); if (existingAccount != null) { Logger.debug(LOG_TAG, ""Firefox Account already exists: returning it.""); return new AndroidFxAccount(context, existingAccount); } final String jsonString = Utils.readFile(context, filename); if (jsonString == null) { Logger.info(LOG_TAG, ""Pickle file '"" + filename + ""' not found; aborting.""); return null; } ExtendedJSONObject json = null; try { json = ExtendedJSONObject.parseJSONObject(jsonString); } catch (Exception e) { Logger.warn(LOG_TAG, ""Got exception reading pickle file '"" + filename + ""'; aborting."", e); return null; } final UnpickleParams params; try { params = UnpickleParams.fromJSON(json); } catch (Exception e) { Logger.warn(LOG_TAG, ""Got exception extracting unpickle json; aborting."", e); return null; } final AndroidFxAccount account; try { account = AndroidFxAccount.addAndroidAccount(context, params.email, params.profile, params.idpServerURI, params.tokenServerURI, params.state, params.isSyncingEnabled, true); } catch (Exception e) { Logger.warn(LOG_TAG, ""Exception when adding Android Account; aborting."", e); return null; } if (account == null) { Logger.warn(LOG_TAG, ""Failed to add Android Account; aborting.""); return null; } <START> account.persistBundle(params.bundle); <END> Long timestamp = json.getLong(KEY_PICKLE_TIMESTAMP); if (timestamp == null) { Logger.warn(LOG_TAG, ""Did not find timestamp in pickle file; ignoring.""); timestamp = new Long(-1); } Logger.info(LOG_TAG, ""Un-pickled Android account named "" + params.email + "" (version "" + params.pickleVersion + "", pickled at "" + timestamp + "").""); return account; }",AndroidFxAccount adder takes a bundle,"public static AndroidFxAccount unpickle(final Context context, final String filename) { final String jsonString = Utils.readFile(context, filename); if (jsonString == null) { Logger.info(LOG_TAG, ""Pickle file '"" + filename + ""' not found; aborting.""); return null; } ExtendedJSONObject json = null; try { json = ExtendedJSONObject.parseJSONObject(jsonString); } catch (Exception e) { Logger.warn(LOG_TAG, ""Got exception reading pickle file '"" + filename + ""'; aborting."", e); return null; } final UnpickleParams params; try { params = UnpickleParams.fromJSON(json); } catch (Exception e) { Logger.warn(LOG_TAG, ""Got exception extracting unpickle json; aborting."", e); return null; } final AndroidFxAccount account; try { account = AndroidFxAccount.addAndroidAccount(context, params.email, params.profile, params.idpServerURI, params.tokenServerURI, params.state, params.accountVersion, params.isSyncingEnabled, true, params.bundle); } catch (Exception e) { Logger.warn(LOG_TAG, ""Exception when adding Android Account; aborting."", e); return null; } if (account == null) { Logger.warn(LOG_TAG, ""Failed to add Android Account; aborting.""); return null; } Long timestamp = json.getLong(KEY_PICKLE_TIMESTAMP); if (timestamp == null) { Logger.warn(LOG_TAG, ""Did not find timestamp in pickle file; ignoring.""); timestamp = Long.valueOf(-1); } Logger.info(LOG_TAG, ""Un-pickled Android account named "" + params.email + "" (version "" + params.pickleVersion + "", pickled at "" + timestamp + "").""); return account; }"
427,"public static void initTestCase() throws Exception { <START> EjbUtils.setStrategy(new DaoTestEjbUtilsStrategy()); <END> if(dataSource == null) { dataSource = createDataSource(); dataset = initDataSet(); dbFacade = DbFacadeLocator.getDbFacade(); dbFacade.setDbEngineDialect(DbFacadeLocator.loadDbEngineDialect()); DatabaseOperation.CLEAN_INSERT.execute(getConnection(), dataset); } }","@AfterClass method unsets this. @MockEJBStrategeyRule save trouble, IIRC","public static void initTestCase() throws Exception { if(dataSource == null) { dataSource = createDataSource(); ejbRule.mockResource(ContainerManagedResourceType.DATA_SOURCE, dataSource); dataset = initDataSet(); dbFacade = DbFacadeLocator.getDbFacade(); dbFacade.setDbEngineDialect(DbFacadeLocator.loadDbEngineDialect()); DatabaseOperation.CLEAN_INSERT.execute(getConnection(), dataset); } }"
428,"public void waitUntilAllTasksFinish() { drainExecutor.shutdown(); try { if (!drainExecutor.awaitTermination(TERMINATION_WAIT_TIME.getSeconds(), TimeUnit.SECONDS)) { <START> drainExecutor.shutdownNow(); <END> } } catch (InterruptedException ex) { drainExecutor.shutdownNow(); log.error(""Encounter interruption exception when {} is await termination"", drainExecutor, ex); throw new UnrecoverableCorfuInterruptedError(ex); } }",put ShutdownNow() finally block,"public void waitUntilAllTasksFinish() { while (getGarbageReceivingQueue().size() > 0) { gcUnsafe(); } drainExecutor.shutdown(); try { drainExecutor.awaitTermination(TERMINATION_WAIT_TIME.getSeconds(), TimeUnit.SECONDS); } catch (InterruptedException ex) { log.error(""Encounter interruption exception when {} is await termination"", drainExecutor, ex); throw new UnrecoverableCorfuInterruptedError(ex); } finally { drainExecutor.shutdownNow(); } }"
429,"public String getPropertyString() { <START> return entity.getBukkitEntity() instanceof Creeper ? ((Creeper) entity.getBukkitEntity()).getMaxFuseTicks() + """" : null; <END> }",Unneeded tern (it's a creeper if reading this line),public String getPropertyString() { return String.valueOf(((Creeper) entity.getBukkitEntity()).getMaxFuseTicks()); }
430,"public void onSkipInWrite(S item, Throwable t) { if(skipWriteDelegate != null && t instanceof Exception) { try { <START> skipWriteDelegate.onSkipWriteItem(Collections.<Object>singletonList(item), (Exception) t); <END> } catch (Exception e) { throw new BatchRuntimeException(e); } } }","This correct. ""item"" in this case is passed JSR-352 SkipListener is items in current chunk. Spring Batch, JSR provide facilities identify item a chunk caused error. section 9.2.7 of spec for more detail","public void onSkipInWrite(S item, Throwable t) { if(skipWriteDelegate != null && t instanceof Exception) { try { skipWriteDelegate.onSkipWriteItem((List<Object>) item, (Exception) t); } catch (Exception e) { throw new BatchRuntimeException(e); } } }"
431,"public void shouldCreateMultipleToolsAndAggregationResultWithWarningsAggregateFalseAndSameTool() { FreeStyleProject project = createJobWithWorkspaceFile(""checkstyle2.xml"", ""checkstyle3.xml""); enableWarningsAggregation(project, false, ""**/checkstyle2-issues.txt"", new CheckStyle(), ""**/checkstyle3-issues.txt"", new CheckStyle()); List<AnalysisResult> results = scheduleBuildAndAssertStatusForBothTools(project, Result.FAILURE); for (AnalysisResult elements : results) { assertThat(elements).hasErrorMessages(); } <START> } <END>","Im Console Log des Builds der Jenkins Instanz! j.assertLogContains(""ID checkstyle is another action: io.jenkins.plugins.analysis.core.views.ResultAction for CheckStyle"", build)","public void shouldCreateMultipleToolsAndAggregationResultWithWarningsAggregateFalseAndSameTool() { FreeStyleProject project = createJobWithWorkspaceFile(""checkstyle2.xml"", ""checkstyle3.xml""); enableWarningsAggregation(project, false, ""**/checkstyle2-issues.txt"", new CheckStyle(), ""**/checkstyle3-issues.txt"", new CheckStyle()); FreeStyleBuild build = scheduleBuildAndAssertLog(project, Result.FAILURE,""ID checkstyle is already used by another action: io.jenkins.plugins.analysis.core.views.ResultAction for CheckStyle""); List<AnalysisResult> results = getAssertStatusForBothTools(build); assertThat(results).hasSize(1); for (AnalysisResult element : results) { assertThat(element).hasId(""checkstyle""); } }"
432,"private void validateProjects(Devfile devfile) throws DevfileFormatException { Set<String> existingNames = new HashSet<>(); for (Project project : devfile.getProjects()) { if (!existingNames.add(project.getName())) { throw new DevfileFormatException( format(""Duplicate project name found:'%s'"", project.getName())); } if (!PROJECT_NAME_PATTERN.matcher(project.getName()).matches()) { throw new DevfileFormatException( format( <START> ""Invalid project name found:'%s'. Name must contain only Latin letters,\n"" <END> + ""digits or these following special characters ._-"", project.getName())); } } }",error message \n,"private void validateProjects(Devfile devfile) throws DevfileFormatException { Set<String> existingNames = new HashSet<>(); for (Project project : devfile.getProjects()) { if (!existingNames.add(project.getName())) { throw new DevfileFormatException( format(""Duplicate project name found:'%s'"", project.getName())); } if (!PROJECT_NAME_PATTERN.matcher(project.getName()).matches()) { throw new DevfileFormatException( format( ""Invalid project name found:'%s'. Name must contain only Latin letters,"" + ""digits or these following special characters ._-"", project.getName())); } } }"
433,"public Node visitDropCheckConstraint(SqlBaseParser.DropCheckConstraintContext context) { <START> Table table = (Table) visit(context.alterTableDefinition()); StringLiteral ident = (StringLiteral) visit(context.ident()); return new DropCheckConstraint<>(table, ident.getValue()); <END> }","suggestion Table<?> table = (Table<?>) visit(context.alterTableDefinition()); return new DropCheckConstraint<>(table, getIdentText(context.ident()));","public Node visitDropCheckConstraint(SqlBaseParser.DropCheckConstraintContext context) { Table<?> table = (Table<?>) visit(context.alterTableDefinition()); return new DropCheckConstraint<>(table, getIdentText(context.ident())); }"
434,"public TestProject(final boolean remove, String path, boolean insidews) throws CoreException { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); Path ppath = new Path(path); String projectName = ppath.lastSegment(); URI locationURI; URI top; if (insidews) { top = root.getRawLocationURI(); } else { File tempName; try { tempName = testUtils.createTempDir(""wssupplement""); } catch (IOException e) { throw new RuntimeException(e); } top = URIUtil.toURI(tempName.getAbsolutePath()); } <START> if (!ppath.lastSegment().equals(path)) { <END> locationURI = URIUtil.toURI(URIUtil.toPath(top).append(path)); } else locationURI = null; project = root.getProject(projectName); if (remove) project.delete(true, null); IProjectDescription description = ResourcesPlugin.getWorkspace() .newProjectDescription(projectName); description.setName(projectName); description.setLocationURI(locationURI); project.create(description, null); project.open(null); location = project.getLocation().toOSString(); javaProject = JavaCore.create(project); IFolder binFolder = createBinFolder(); setJavaNature(); javaProject.setRawClasspath(new IClasspathEntry[0], null); createOutputFolder(binFolder); addSystemLibraries(); }","If path is simple, i.e. project name, ppath.lastSegment().equals(path) is true a consequence locatioURI is set null (the default location). parameter insidews is account in this case. Please fix that. I (!ppath.lastSegment().equals(path) || !insidews) work","public TestProject(final boolean remove, String path, boolean insidews) throws CoreException { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProjectDescription description = createDescription(remove, path, insidews, root); project = root.getProject(description.getName()); if (remove) project.delete(true, null); IPath locationBefore = description.getLocation(); if (locationBefore == null) locationBefore = root.getRawLocation().append(path); location = locationBefore.toOSString(); project.create(description, null); project.open(null); javaProject = JavaCore.create(project); IFolder binFolder = createBinFolder(); setJavaNature(); javaProject.setRawClasspath(new IClasspathEntry[0], null); createOutputFolder(binFolder); addSystemLibraries(); }"
435,"public void doImport(VM vm) { if (!Config.<Boolean>getValue( ConfigValues.AutoImportHostedEngine, vdsGroupDAO.get(vm.getVdsGroupId()).getCompatibilityVersion().getValue())) { return; <START> } <END> VdcReturnValueBase heVmImported; StorageDomain sd = getHEStorageDomain(vm); if (sd != null && (sd.getStatus() == StorageDomainStatus.Active)) { log.info(""Try to import the Hosted Engine VM '{}'"", vm); if (vmStaticDAO.get(vm.getId()) == null || removedHEVM(vm)) { heVmImported = importHEVM(vm, sd); if (heVmImported.getSucceeded()) { log.info(""Successfully imported the Hosted Engine VM""); auditLogDirector.log(new AuditLogableBase(), AuditLogType.HOSTED_ENGINE_VM_IMPORT_SUCCEEDED); } else { log.error(""Failed importing the Hosted Engine VM""); auditLogDirector.log(new AuditLogableBase(), AuditLogType.HOSTED_ENGINE_VM_IMPORT_FAILED); } } } else { if (sd == null) { log.debug(""Skip trying to import the Hosted Engine VM. Storage Domain '{}' doesn't exist"", Config.<String>getValue(ConfigValues.HostedEngineStorageDomainName)); auditLogDirector.log(new AuditLogableBase(), AuditLogType.HOSTED_ENGINE_SD_NOT_EXIT); } else { log.debug(""Skip trying to import the Hosted Engine VM. Storage Domain '{}' isn't ACTIVE"", sd); auditLogDirector.log(new AuditLogableBase(), AuditLogType.HOSTED_ENGINE_SD_NOT_ACTIVE); } } }","data Center level, do for ImportStorageDomain","public void doImport(VM vm) { if (!Config.<Boolean>getValue( ConfigValues.AutoImportHostedEngine, storagePoolDao.getForVdsGroup(vm.getVdsGroupId()).getCompatibilityVersion().getValue())) { return; } VdcReturnValueBase heVmImported; StorageDomain sd = getHEStorageDomain(vm); if (sd != null && (sd.getStatus() == StorageDomainStatus.Active)) { log.info(""Try to import the Hosted Engine VM '{}'"", vm); if (vmStaticDAO.get(vm.getId()) == null || removedHEVM(vm)) { heVmImported = importHEVM(vm, sd); if (heVmImported.getSucceeded()) { log.info(""Successfully imported the Hosted Engine VM""); auditLogDirector.log(new AuditLogableBase(), AuditLogType.HOSTED_ENGINE_VM_IMPORT_SUCCEEDED); } else { log.error(""Failed importing the Hosted Engine VM""); auditLogDirector.log(new AuditLogableBase(), AuditLogType.HOSTED_ENGINE_VM_IMPORT_FAILED); } } } else { if (sd == null) { log.debug(""Skip trying to import the Hosted Engine VM. Storage Domain '{}' doesn't exist"", Config.<String>getValue(ConfigValues.HostedEngineStorageDomainName)); auditLogDirector.log(new AuditLogableBase(), AuditLogType.HOSTED_ENGINE_SD_NOT_EXIT); } else { log.debug(""Skip trying to import the Hosted Engine VM. Storage Domain '{}' isn't ACTIVE"", sd); auditLogDirector.log(new AuditLogableBase(), AuditLogType.HOSTED_ENGINE_SD_NOT_ACTIVE); } } }"
436,"public void load(final ReviewDb db, final PatchSet ps) throws OrmException { patchSet = ps; info = db.patchSetInfo().get(patchSet.getId()); patches = db.patches().byPatchSet(patchSet.getId()).toList(); final Account.Id me = Common.getAccountId(); if (me != null) { final List<PatchLineComment> comments = db.patchComments().draft(ps.getId(), me).toList(); if (!comments.isEmpty()) { final Map<Patch.Key, Patch> byKey = db.patches().toMap(patches); for (final PatchLineComment c : comments) { final Patch p = byKey.get(c.getKey().getParentKey()); if (p != null) { p.setDraftCount(p.getDraftCount() + 1); } } } for (Patch p : patches) { AccountPatchReview.Key key = new AccountPatchReview.Key(p.getKey(), me); <START> AccountPatchReview apr = db.accountPatchReviews().get(key); <END> if (apr != null) p.setReviewed(true); } } }","please do this a single query for patches this patch set this user reviewed, do a hash join in Java? patch set contains 1000+ files, this is 1000+ queries database, blows performance wise","public void load(final ReviewDb db, final PatchSet ps) throws OrmException { patchSet = ps; info = db.patchSetInfo().get(patchSet.getId()); patches = db.patches().byPatchSet(patchSet.getId()).toList(); final Account.Id me = Common.getAccountId(); if (me != null) { final List<PatchLineComment> comments = db.patchComments().draft(ps.getId(), me).toList(); if (!comments.isEmpty()) { final Map<Patch.Key, Patch> byKey = db.patches().toMap(patches); for (final PatchLineComment c : comments) { final Patch p = byKey.get(c.getKey().getParentKey()); if (p != null) { p.setDraftCount(p.getDraftCount() + 1); } } } ResultSet<AccountPatchReview> reviews = db.accountPatchReviews().byReviewer(me); HashSet<Patch.Key> reviewedPatches = new HashSet<Patch.Key>(); for (AccountPatchReview review : reviews) { reviewedPatches.add(review.getKey().getPatchKey()); } for (Patch p : patches) { if (reviewedPatches.contains(p.getKey())) p.setReviewedByCurrentUser(true); } } }"
437,"private void checkForIllegalStreamName(String streamName, String streamDef) { try { StreamNode sn = parse(streamName, streamDef); fail(""expected to fail but parsed "" + sn.stringify()); } catch (StreamDefinitionException e) { assertEquals(XDDSLMessages.ILLEGAL_STREAM_NAME, e.getMessageCode()); assertEquals(0, e.getPosition()); <START> e.printStackTrace(); <END> assertEquals(streamName, e.getInserts()[0]); } }",intend leave printStackTrace() here,"private void checkForIllegalStreamName(String streamName, String streamDef) { try { StreamNode sn = parse(streamName, streamDef); fail(""expected to fail but parsed "" + sn.stringify()); } catch (StreamDefinitionException e) { assertEquals(XDDSLMessages.ILLEGAL_STREAM_NAME, e.getMessageCode()); assertEquals(0, e.getPosition()); assertEquals(streamName, e.getInserts()[0]); } }"
438,"public void canLoadFeedWithErrors () { PersistenceExpectation[] expectations = PersistenceExpectation.list(); ErrorExpectation[] errorExpectations = ErrorExpectation.list( new ErrorExpectation(NewGTFSErrorType.FARE_TRANSFER_MISMATCH, ""fare-02""), new ErrorExpectation(NewGTFSErrorType.FREQUENCY_PERIOD_OVERLAP, ""freq-01_09:00:00_to_10:00:00_every_10m00s""), <START> new ErrorExpectation(NewGTFSErrorType.FREQUENCY_PERIOD_OVERLAP, ""freq-01_09:30:00_to_10:30:00_every_15m00s""), <END> new ErrorExpectation(NewGTFSErrorType.TRIP_OVERLAP_IN_BLOCK, ""1A00000"") ); assertThat( ""Integration test passes"", runIntegrationTestOnFolder(""fake-agency-overlapping-trips"", nullValue(), expectations, errorExpectations), equalTo(true) ); }","I good add 2 more error expectations cover overlaps: Key: |: start end of frequency -: active time of frequency _: frequency active A covers B: A: |---------| B: ___|--|____ B covers A A: ___|--|____ B: |---------| A starts B starts, A ends B starts A ends B ends: A: _|----|____ B: ____|-----| A starts B starts, A starts B ends A: ____|-----| B: _|----|____","public void canLoadFeedWithErrors () { PersistenceExpectation[] expectations = PersistenceExpectation.list(); ErrorExpectation[] errorExpectations = ErrorExpectation.list( new ErrorExpectation(NewGTFSErrorType.FARE_TRANSFER_MISMATCH, equalTo(""fare-02"")), new ErrorExpectation(NewGTFSErrorType.FREQUENCY_PERIOD_OVERLAP, equalTo(""freq-01_08:30:00_to_10:15:00_every_15m00s"")), new ErrorExpectation(NewGTFSErrorType.FREQUENCY_PERIOD_OVERLAP, equalTo(""freq-01_08:30:00_to_10:15:00_every_15m00s"")), new ErrorExpectation(NewGTFSErrorType.FREQUENCY_PERIOD_OVERLAP), new ErrorExpectation(NewGTFSErrorType.FREQUENCY_PERIOD_OVERLAP), new ErrorExpectation(NewGTFSErrorType.FREQUENCY_PERIOD_OVERLAP), new ErrorExpectation(NewGTFSErrorType.FREQUENCY_PERIOD_OVERLAP), new ErrorExpectation(NewGTFSErrorType.TRIP_OVERLAP_IN_BLOCK, equalTo(""1A00000"")) ); assertThat( ""Integration test passes"", runIntegrationTestOnFolder(""fake-agency-overlapping-trips"", nullValue(), expectations, errorExpectations), equalTo(true) ); }"
439,"public EnvironmentTestDto action(TestContext testContext, EnvironmentTestDto testDto, EnvironmentClient client) throws Exception { int retries = 0; while (retries <= testDto.getWaitUtil().getMaxRetry()) { try { return environmentAction(testContext, testDto, client); } catch (Exception e) { LOGGER.info(""Exception during executing Environment action: "", e); if (e.getMessage().contains(""flow under operation"")) { waitTillFlowInOperation(testDto.getWaitUtil()); retries++; } else { throw e; } } } <START> throw new Exception(""Exception during executing Environment action: exceeding maxrety during waiting for flow""); <END> }",typo in maxrety,"public EnvironmentTestDto action(TestContext testContext, EnvironmentTestDto testDto, EnvironmentClient client) throws Exception { int retries = 0; while (retries <= testDto.getWaitUtil().getMaxRetry()) { try { return environmentAction(testContext, testDto, client); } catch (Exception e) { LOGGER.info(""Exception during executing Environment action: "", e); if (e.getMessage().contains(""flow under operation"")) { waitTillFlowInOperation(testDto.getWaitUtil()); retries++; } else { throw e; } } } throw new Exception(""Exception during executing Environment action: exceeding maxretry during waiting for flow""); }"
440,"public MiniSet(T... entries) { if (entries.length == 0) { } else if (entries.length == 1) { holder = entries[0]; if (holder == null) throw new IllegalArgumentException(); type = Type.SINGLE; } else if (entries.length < ARRAY_SIZE) { Object[] array = new Object[ARRAY_SIZE]; for (int i = 0; i < ARRAY_SIZE; ++i) { if (i > entries.length) break; if (entries[i] == null) throw new IllegalArgumentException(); <START> array[i] = entries[i]; <END> } holder = array; type = Type.ARRAY; } else { Map<T, Object> map = new HashMap<>(); for (T entry : entries) { if (entry == null) throw new IllegalArgumentException(); map.put(entry, DUMMY); } holder = map; type = Type.MAP; } }",removing duplicated entries..,"public MiniSet(T... entries) { if (entries.length == 0) { type = Type.EMPTY; } else if (entries.length == 1) { holder = entries[0]; if (holder == null) throw new IllegalArgumentException(); type = Type.SINGLE; } else if (entries.length < ARRAY_SIZE) { holder = new Object[ARRAY_SIZE]; type = Type.ARRAY; for (T entry : entries) { add(entry); } } else { Map<T, Object> map = new HashMap<>(); for (T entry : entries) { if (entry == null) throw new IllegalArgumentException(); map.put(entry, DUMMY); } holder = map; type = Type.MAP; } }"
441,"public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_description_edit, container, false); unbinder = ButterKnife.bind(this, view); <START> source = getArguments().getInt(ARG_INVOKE_SOURCE, InvokeSource.PAGE_ACTIVITY.ordinal()); <END> editView.setTranslationEdit(source == InvokeSource.EDIT_FEED_TRANSLATE_TITLE_DESC.ordinal()); editView.setTranslationSourceLanguageDescription(getArguments().getCharSequence(ARG_TRANSLATION_SOURCE_LANG_DESC)); editView.setPageTitle(pageTitle); editView.setHighlightText(highlightText); editView.setCallback(new EditViewCallback()); if (reviewEnabled) { loadPageSummary(savedInstanceState); } if (funnel != null) { funnel.logReady(); } return view; }",type of source field InvokeSource instead of int,"public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_description_edit, container, false); unbinder = ButterKnife.bind(this, view); editView.setTranslationEdit(invokeSource == EDIT_FEED_TRANSLATE_TITLE_DESC); editView.setTranslationSources(getArguments().getCharSequence(ARG_TRANSLATION_SOURCE_DESCRIPTION), getArguments().getString(ARG_TRANSLATION_SOURCE_LANGUAGE_CODE)); editView.setPageTitle(pageTitle); editView.setHighlightText(highlightText); editView.setCallback(new EditViewCallback()); editView.editTaskEnabled(reviewEnabled); if (reviewEnabled) { editView.setVisibility(View.GONE); editView.showProgressBar(true); loadPageSummary(savedInstanceState); } if (funnel != null) { funnel.logReady(); } return view; }"
442,public JsonNode toJsonNode(Object json) throws Exception { if (json instanceof String) { return this.objectMapper.readTree((String) json); <START> } <END> else if (json instanceof byte[]) { return this.objectMapper.readTree((byte[]) json); } else if (json instanceof File) { return this.objectMapper.readTree((File) json); } else if (json instanceof URL) { return this.objectMapper.readTree((URL) json); } else if (json instanceof InputStream) { return this.objectMapper.readTree((InputStream) json); } else if (json instanceof Reader) { return this.objectMapper.readTree((Reader) json); } else { return this.objectMapper.valueToTree(json); } },this dropped review,public JsonNode toJsonNode(Object json) throws Exception { try { if (json instanceof String) { return this.objectMapper.readTree((String) json); } else if (json instanceof byte[]) { return this.objectMapper.readTree((byte[]) json); } else if (json instanceof File) { return this.objectMapper.readTree((File) json); } else if (json instanceof URL) { return this.objectMapper.readTree((URL) json); } else if (json instanceof InputStream) { return this.objectMapper.readTree((InputStream) json); } else if (json instanceof Reader) { return this.objectMapper.readTree((Reader) json); } } catch (JsonParseException e) { if (!(json instanceof String) && !(json instanceof byte[])) { throw e; } } return this.objectMapper.valueToTree(json); }
443,"public AbstractFindStoragePopupView(EventBus eventBus, boolean multiSelection) { super(eventBus); table = new EntityModelCellTable<>(multiSelection); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); table.addColumn(new AbstractEntityModelTextColumn<StorageDomain>() { @Override public String getText(StorageDomain storage) { return storage.getStorageName(); } }, constants.nameStorage()); table.addColumn(new AbstractEntityModelEnumColumn<StorageDomain, StorageDomainType>() { @Override protected StorageDomainType getEnum(StorageDomain storage) { return storage.getStorageDomainType(); } }, constants.typeStorage()); table.addColumn(new AbstractEntityModelTextColumn<StorageDomain>() { @Override public String getText(StorageDomain storage) { if (storage.getAvailableDiskSize() == null || storage.getAvailableDiskSize() < 1) { return messages.gigabytes(""< 1""); } return <START> messages.gigabytes(storage.getAvailableDiskSize().toString()); <END> } }, constants.freeSpaceStorage()); }",consider String.valueOf() circumvent NPE,"public AbstractFindStoragePopupView(EventBus eventBus, boolean multiSelection) { super(eventBus); table = new EntityModelCellTable<>(multiSelection); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); table.addColumn(new AbstractEntityModelTextColumn<StorageDomain>() { @Override public String getText(StorageDomain storage) { return storage.getStorageName(); } }, constants.nameStorage()); table.addColumn(new AbstractEntityModelEnumColumn<StorageDomain, StorageDomainType>() { @Override protected StorageDomainType getEnum(StorageDomain storage) { return storage.getStorageDomainType(); } }, constants.typeStorage()); table.addColumn(new AbstractEntityModelTextColumn<StorageDomain>() { @Override public String getText(StorageDomain storage) { if (storage.getAvailableDiskSize() == null || storage.getAvailableDiskSize() < 1) { return messages.gigabytes(""< 1""); } return messages.gigabytes(String.valueOf(storage.getAvailableDiskSize())); } }, constants.freeSpaceStorage()); }"
444,"private Map<Integer, List<InstanceId>> getRoundRobinAllocation( int numContainer, Map<String, Integer> parallelismMap) { Map<Integer, List<InstanceId>> allocation = new HashMap<>(); <START> int totalInstance = <END> parallelismMap.values().stream().collect(Collectors.summingInt(Integer::intValue)); if (numContainer > totalInstance) { throw new RuntimeException(""More containers allocated than instance.""); } for (int i = 1; i <= numContainer; ++i) { allocation.put(i, new ArrayList<InstanceId>()); } int index = 1; int globalTaskIndex = 1; for (String component : parallelismMap.keySet()) { int numInstance = parallelismMap.get(component); for (int i = 0; i < numInstance; ++i) { allocation.get(index).add(new InstanceId(component, globalTaskIndex, i)); index = (index == numContainer) ? 1 : index + 1; globalTaskIndex++; } } return allocation; }",TopologyUtils.getTotalInstance() work? worth adding this code TopologyUtils a util function,"private Map<Integer, List<InstanceId>> getRoundRobinAllocation( int numContainer, Map<String, Integer> parallelismMap) { Map<Integer, List<InstanceId>> allocation = new HashMap<>(); int totalInstance = TopologyUtils.getTotalInstance(parallelismMap); if (numContainer > totalInstance) { throw new RuntimeException(""More containers allocated than instance.""); } for (int i = 1; i <= numContainer; ++i) { allocation.put(i, new ArrayList<InstanceId>()); } int index = 1; int globalTaskIndex = 1; for (String component : parallelismMap.keySet()) { int numInstance = parallelismMap.get(component); for (int i = 0; i < numInstance; ++i) { allocation.get(index).add(new InstanceId(component, globalTaskIndex, i)); index = (index == numContainer) ? 1 : index + 1; globalTaskIndex++; } } return allocation; }"
445,"setChannelOptions(Configuration configuration, BigtableOptions.Builder builder) throws IOException { setCredentialOptions(builder, configuration); builder.setRetryOptions(createRetryOptions(configuration)); int channelCount = configuration.getInt( BIGTABLE_DATA_CHANNEL_COUNT_KEY, BigtableOptions.BIGTABLE_DATA_CHANNEL_COUNT_DEFAULT); builder.setDataChannelCount(channelCount); <START> StringBuilder agentBuidler = new StringBuilder(); <END> agentBuidler.append(""hbase-"").append(VersionInfo.getVersion()); String customUserAgent = configuration.get(CUSTOM_USER_AGENT_KEY); if (customUserAgent != null) { agentBuidler.append(',').append(customUserAgent); } builder.setUserAgent(agentBuidler.toString()); }",agentBuidler -> agentBuilder,"setChannelOptions(Configuration configuration, BigtableOptions.Builder builder) throws IOException { setCredentialOptions(builder, configuration); builder.setRetryOptions(createRetryOptions(configuration)); int channelCount = configuration.getInt( BIGTABLE_DATA_CHANNEL_COUNT_KEY, BigtableOptions.BIGTABLE_DATA_CHANNEL_COUNT_DEFAULT); builder.setDataChannelCount(channelCount); StringBuilder agentBuilder = new StringBuilder(); agentBuilder.append(""hbase-"").append(VersionInfo.getVersion()); String customUserAgent = configuration.get(CUSTOM_USER_AGENT_KEY); if (customUserAgent != null) { agentBuilder.append(',').append(customUserAgent); } builder.setUserAgent(agentBuilder.toString()); }"
446,"public TurtleRecordWriter(OutputStream out) throws IOException { <START> _ps = new BufferedWriter(new OutputStreamWriter(out, ""UTF-8"") , BUFFER_SIZE); <END> _decl.clear(); }","close method called in finally block of write method. is executed if is exception, finally block care of closing writer","public TurtleRecordWriter(OutputStream out) { bufferedWriter = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8), BUFFER_SIZE); }"
447,"public void changeQuestionAnswer(User u, String question, String answer) throws DAOException { log.info(""Updating secret question and answer for "" + u.getUsername()); LoginCredential credentials = getLoginCredential(u); credentials.setSecretQuestion(question); <START> String hashedAnswer = Security.encodeString(answer + credentials.getSalt()); <END> credentials.setSecretAnswer(hashedAnswer); credentials.setDateChanged(new Date()); credentials.setChangedBy(u); updateLoginCredential(credentials); }",I suggest answer.toLowerCase() secret answer validation case insensitive,"public void changeQuestionAnswer(User u, String question, String answer) throws DAOException { log.info(""Updating secret question and answer for "" + u.getUsername()); LoginCredential credentials = getLoginCredential(u); credentials.setSecretQuestion(question); String hashedAnswer = Security.encodeString(answer.toLowerCase() + credentials.getSalt()); credentials.setSecretAnswer(hashedAnswer); credentials.setDateChanged(new Date()); credentials.setChangedBy(u); updateLoginCredential(credentials); }"
448,"public CoapServer(final NetworkConfig config, final int... ports) { if (config != null) { this.config = config; } else { this.config = NetworkConfig.getStandard(); } <START> this.root = new RootResource(); <END> this.deliverer = new ServerMessageDeliverer(root); CoapResource wellKnown = new CoapResource("".well-known""); wellKnown.setVisible(false); wellKnown.add(new DiscoveryResource(root)); root.add(wellKnown); this.endpoints = new ArrayList<>(); if(null != config) { this.executor = Executors.newScheduledThreadPool( config.getInt(NetworkConfig.Keys.PROTOCOL_STAGE_THREAD_COUNT), new Utils.NamedThreadFactory(""CoapServer#"")); } if(null != this.config) { for (int port : ports) { addEndpoint(new CoapEndpoint(port, this.config)); } } }",This effectively removes possibility another root resource extending CoapServer,"public CoapServer(final NetworkConfig config, final int... ports) { if (config != null) { this.config = config; } else { this.config = NetworkConfig.getStandard(); } this.root = createRoot(); this.deliverer = new ServerMessageDeliverer(root); CoapResource wellKnown = new CoapResource("".well-known""); wellKnown.setVisible(false); wellKnown.add(new DiscoveryResource(root)); root.add(wellKnown); this.endpoints = new ArrayList<>(); this.executor = Executors.newScheduledThreadPool( this.config.getInt(NetworkConfig.Keys.PROTOCOL_STAGE_THREAD_COUNT), new Utils.NamedThreadFactory(""CoapServer#"")); for (int port : ports) { addEndpoint(new CoapEndpoint(port, this.config)); } }"
449,"public void checkIfRepoStarred() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_NO_CONTENT) ).next(new MkAnswer.Simple(HttpURLConnection.HTTP_NOT_FOUND)) .start(); <START> final Stars truestars = new RtStars( <END> new ApacheRequest(container.home()), RtStarsTest.repo(""someuser"", ""starredrepo"") ); MatcherAssert.assertThat( truestars.starred(), Matchers.is(true) ); final Stars falsestars = new RtStars( new ApacheRequest(container.home()), RtStarsTest.repo(""otheruser"", ""notstarredrepo"") ); MatcherAssert.assertThat( falsestars.starred(), Matchers.is(false) ); }",call this variable stars starred. avoid compound variable names: <LINK_0>,"public void checkIfRepoStarred() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_NO_CONTENT) ).next(new MkAnswer.Simple(HttpURLConnection.HTTP_NOT_FOUND)) .start(); final Stars starred = new RtStars( new ApacheRequest(container.home()), RtStarsTest.repo(""someuser"", ""starredrepo"") ); MatcherAssert.assertThat( starred.starred(), Matchers.is(true) ); final Stars unstarred = new RtStars( new ApacheRequest(container.home()), RtStarsTest.repo(""otheruser"", ""notstarredrepo"") ); MatcherAssert.assertThat( unstarred.starred(), Matchers.is(false) ); }"
450,"private Function<PollingContext<OperationResult>, Mono<OperationResult>> analyzeFormStreamActivationOperation( Flux<ByteBuffer> data, String modelId, long length, FormContentType formContentType, boolean includeTextDetails) { Objects.requireNonNull(data, ""'data' is required and cannot be null.""); Objects.requireNonNull(modelId, ""'modelId' is required and cannot be null.""); final long[] bufferedDataSize = {0}; final List<ByteBuffer> cachedBuffers = new LinkedList<>(); final AtomicBoolean[] isGuessed = {new AtomicBoolean(true)}; final ContentType[] contentType = new ContentType[1]; <START> return pollingContext -> data.filter(ByteBuffer::hasRemaining) <END> .windowUntil(buffer -> { if (bufferedDataSize[0] >= length) { return false; } bufferedDataSize[0] += buffer.remaining(); if (formContentType == null && isGuessed[0].get() && bufferedDataSize[0] >= 4) { byte[] bytes = buffer.array(); contentType[0] = getContentType(ByteBuffer.wrap(bytes)); isGuessed[0].compareAndSet(true, false); } ByteBuffer cachedBuffer = ByteBuffer.allocate(buffer.remaining()).put(buffer); cachedBuffer.flip(); cachedBuffers.add(cachedBuffer); if (bufferedDataSize[0] >= length) { return true; } return false; }, true, Integer.MAX_VALUE) .next() .flatMap(newData -> { final ContentType contentTypeFinal = formContentType == null ? contentType[0] : ContentType.fromString(formContentType.toString()); return service.analyzeWithCustomModelWithResponseAsync(UUID.fromString(modelId), contentTypeFinal, Flux.fromIterable(cachedBuffers), length, includeTextDetails) .map(response -> new OperationResult(parseModelId(response.getDeserializedHeaders().getOperationLocation()))); }); }","This logic appears duplicated times, chance this abstracted? Possibly a method takes Flux<ByteBuffer> returns Mono<Tuple2<ContentType, Flux<ByteBuffer>>","private Function<PollingContext<OperationResult>, Mono<OperationResult>> analyzeFormStreamActivationOperation( Flux<ByteBuffer> data, String modelId, long length, FormContentType formContentType, boolean includeTextDetails) { Objects.requireNonNull(data, ""'data' is required and cannot be null.""); Objects.requireNonNull(modelId, ""'modelId' is required and cannot be null.""); return pollingContext -> { if (formContentType != null) { try { return service.analyzeWithCustomModelWithResponseAsync(UUID.fromString(modelId), ContentType.fromString(formContentType.toString()), data, length, includeTextDetails) .map(response -> new OperationResult(parseModelId( response.getDeserializedHeaders().getOperationLocation()))); } catch (RuntimeException ex) { return monoError(logger, ex); } } else { return detectContentType(data) .flatMap(contentType -> service.analyzeWithCustomModelWithResponseAsync(UUID.fromString(modelId), contentType, data, length, includeTextDetails) .map(response -> new OperationResult( parseModelId(response.getDeserializedHeaders().getOperationLocation())))); } }; }"
451,"static Object[][] roleNameProvider() { return new Object[][] { new Object[] {""bbmri_eric"", ""Manager"", ""bbmri_eric_MANAGER""}, <START> new Object[] {""bbmri_eric"", ""Manager"", ""bbmri_eric_MANAGER""}, <END> new Object[] {""patientenfederatie-nederland"", ""Member"", ""patientenfederatie-nederland_MEMBER""} }; }",In new situation this line duplicated,"static Object[][] roleNameProvider() { return new Object[][] { new Object[] {""bbmri_eric"", ""Manager"", ""bbmri_eric_MANAGER""}, new Object[] {""patientenfederatie-nederland"", ""Member"", ""patientenfederatie-nederland_MEMBER""} }; }"
452,"public void setLastCancelAllTimeMillis(final long timeMillis) { <START> mWorkDatabase.beginTransaction(); <END> try { Preference preference = new Preference(KEY_LAST_CANCEL_ALL_TIME_MS, timeMillis); mWorkDatabase.preferenceDao().insertPreference(preference); mWorkDatabase.setTransactionSuccessful(); } finally { mWorkDatabase.endTransaction(); } }",Single statements need a transaction,"public void setLastCancelAllTimeMillis(final long timeMillis) { Preference preference = new Preference(KEY_LAST_CANCEL_ALL_TIME_MS, timeMillis); mWorkDatabase.preferenceDao().insertPreference(preference); }"
453,"<START> public Expression convert(String input) throws OptionsParsingException { <END> if (input.isEmpty()) { return null; } if (isLegacySyntax(input)) { input = convertLegacySyntaxToBooleanFormula(input); GoogleLogger.forEnclosingClass().at(Level.WARNING).log( ""Specifying a list of tags separated by comma is legacy syntax and will not be supported after"" + "" Jan 1, 2021. Consider changing to: "" + input); } try { Expression result = Expression.parse(ParserInput.fromLines(input)); validate(result); return result; } catch (SyntaxError.Exception e) { throw new OptionsParsingException(""Failed to parse expression: "" + e.getMessage() + "" input: "" + input, e); } }",@Nullable public,"@Nullable public Expression convert(String input) throws OptionsParsingException { if (input.isEmpty()) { return null; } if (isLegacySyntax(input)) { input = convertLegacySyntaxToBooleanFormula(input); } try { Expression result = Expression.parse(ParserInput.fromLines(input)); validate(result); return result; } catch (SyntaxError.Exception e) { throw new OptionsParsingException(""Failed to parse expression: "" + e.getMessage() + "" input: "" + input, e); } }"
454,"void updateThreadPoolSize(int numThreads) { <START> m_scheduler.setCorePoolSize(numThreads); LOG.info(""Updated PBD to use "" + numThreads + "" threads to enforce retention policy""); <END> }",Do want check if thread count changed right this log message logged catalog update affects kipling,"void updateThreadPoolSize(int numThreads) { if (numThreads != m_scheduler.getCorePoolSize()) { m_scheduler.setCorePoolSize(numThreads); LOG.info(""Updated PBD to use "" + numThreads + "" threads to enforce retention policy""); } }"
455,"<START> public IPath buildPath(IPath <END> sourcePath, IPath targetPath, int count) { sourcePath = sourcePath.removeFirstSegments(count); return targetPath.append(sourcePath); }",static,"public static IPath buildPath(IPath sourcePath, IPath targetPath, int count) { sourcePath = sourcePath.removeFirstSegments(count); return targetPath.append(sourcePath); }"
456,"@Override public IQuickAssistAssistant getQuickAssistAssistant(ISourceViewer sourceViewer) { QuickAssistAssistant quickAssistAssistant = new QuickAssistAssistant(); List<IQuickAssistProcessor> quickAssistProcessors = new ArrayList<IQuickAssistProcessor>(); quickAssistProcessors.add(new MarkerResoltionQuickAssistProcessor()); <START> quickAssistProcessors.addAll(GenericEditorPlugin.getDefault().getQuickAssistProcessorRegistry().getQuickAssistProcessors()); <END> CompositeQuickAssistProcessor compQuickAssistProcessor = new CompositeQuickAssistProcessor(quickAssistProcessors); quickAssistAssistant.setQuickAssistProcessor(compQuickAssistProcessor); quickAssistAssistant.setRestoreCompletionProposalSize(EditorsPlugin.getDefault().getDialogSettingsSection(""quick_assist_proposal_size"")); quickAssistAssistant.setInformationControlCreator(parent -> new DefaultInformationControl(parent, EditorsPlugin.getAdditionalInfoAffordanceString())); return quickAssistAssistant; }",This input content-types parameter sort out processors use,"@Override public IQuickAssistAssistant getQuickAssistAssistant(ISourceViewer sourceViewer) { QuickAssistAssistant quickAssistAssistant = new QuickAssistAssistant(); List<IQuickAssistProcessor> quickAssistProcessors = new ArrayList<IQuickAssistProcessor>(); quickAssistProcessors.add(new MarkerResoltionQuickAssistProcessor()); quickAssistProcessors.addAll(GenericEditorPlugin.getDefault().getQuickAssistProcessorRegistry().getQuickAssistProcessors(sourceViewer, editor, getContentTypes(sourceViewer))); CompositeQuickAssistProcessor compQuickAssistProcessor = new CompositeQuickAssistProcessor(quickAssistProcessors); quickAssistAssistant.setQuickAssistProcessor(compQuickAssistProcessor); quickAssistAssistant.setRestoreCompletionProposalSize(EditorsPlugin.getDefault().getDialogSettingsSection(""quick_assist_proposal_size"")); quickAssistAssistant.setInformationControlCreator(parent -> new DefaultInformationControl(parent, EditorsPlugin.getAdditionalInfoAffordanceString())); return quickAssistAssistant; }"
457,"private Response handleSaveRole(SecurityRole securityRole, boolean post) { ValidationResult validationResult = securityRole.validate(); if (post) { validationResult.merge(service.getSecurityService().validateSecurityRoleName(securityRole.getRoleName())); } if (validationResult.valid()) { SecurityRole savedRole = service.getSecurityService().saveSecurityRole(securityRole); if (post) { <START> return Response.created(URI.create(""v1/resource/securityroles"")).entity(savedRole).build(); <END> } else { return Response.ok(savedRole).build(); } } else { return Response.ok(validationResult.toRestError()).build(); } }",I this ok get encoded. point newly created role,"private Response handleSaveRole(SecurityRole securityRole, boolean post) { ValidationResult validationResult = securityRole.validate(); if (post) { validationResult.merge(service.getSecurityService().validateSecurityRoleName(securityRole.getRoleName())); } if (validationResult.valid()) { SecurityRole savedRole = service.getSecurityService().saveSecurityRole(securityRole); if (post) { return Response.created(URI.create(""v1/resource/securityroles/"" + URLEncoder.encode(savedRole.getRoleName()))).entity(savedRole).build(); } else { return Response.ok(savedRole).build(); } } else { return Response.ok(validationResult.toRestError()).build(); } }"
458,"public VSizeIndexedWriter( IOPeon ioPeon, String filenameBase, int maxId ) { this.ioPeon = ioPeon; <START> this.metaFileName = StringUtils.safeFormat(""%s.meta"", filenameBase); <END> this.headerFileName = StringUtils.safeFormat(""%s.header"", filenameBase); this.valuesFileName = StringUtils.safeFormat(""%s.values"", filenameBase); this.maxId = maxId; }",crash if bad format string,"public VSizeIndexedWriter( IOPeon ioPeon, String filenameBase, int maxId ) { this.ioPeon = ioPeon; this.metaFileName = StringUtils.format(""%s.meta"", filenameBase); this.headerFileName = StringUtils.format(""%s.header"", filenameBase); this.valuesFileName = StringUtils.format(""%s.values"", filenameBase); this.maxId = maxId; }"
459,"private void edit(ListModel model, final boolean topTableIsEdited) { EntityModelCellTable<ListModel> table = getTable(topTableIsEdited); IEventListener listener = topTableIsEdited ? topItemsChangedListener : bottomItemsChangedListener; if (listener != null) { table.asEditor().flush().getItemsChangedEvent().removeListener(listener); } listener = new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { getSelectionModel(topTableIsEdited).clear(); } }; <START> if (topTableIsEdited) { <END> topItemsChangedListener = listener; } else { bottomItemsChangedListener = listener; } model.getItemsChangedEvent().addListener(listener); table.asEditor().edit(model); }",simpler/nicer create static listeners in advance accordingly,"private void edit(ListModel model, final boolean topTableIsEdited) { EntityModelCellTable<ListModel> table = getTable(topTableIsEdited); IEventListener listener = topTableIsEdited ? topItemsChangedListener : bottomItemsChangedListener; if (listener != null) { table.asEditor().flush().getItemsChangedEvent().removeListener(listener); } model.getItemsChangedEvent().addListener(listener); table.asEditor().edit(model); }"
460,"void deleteProperty(AccumuloElement element, Property property, Authorizations authorizations) { <START> if (!element.getFetchHints().isIncludeAllProperties()) { <END> throw new VertexiumMissingFetchHintException(element.getFetchHints(), ""All Properties""); } if (!element.getFetchHints().isIncludeAllPropertyMetadata()) { throw new VertexiumMissingFetchHintException(element.getFetchHints(), ""All Property Metadata""); } Mutation m = new Mutation(element.getId()); elementMutationBuilder.addPropertyDeleteToMutation(m, property); addMutations(element, m); getSearchIndex().deleteProperty( this, element, PropertyDescriptor.fromProperty(property), authorizations ); if (hasEventListeners()) { queueEvent(new DeletePropertyEvent(this, element, property)); } }",Is reason isIncludeAllProperties of search index? need loaded,"void deleteProperty(AccumuloElement element, Property property, Authorizations authorizations) { if (!element.getFetchHints().isIncludePropertyAndMetadata(property.getName())) { throw new VertexiumMissingFetchHintException(element.getFetchHints(), ""Property "" + property.getName() + "" needs to be included with metadata""); } Mutation m = new Mutation(element.getId()); elementMutationBuilder.addPropertyDeleteToMutation(m, property); addMutations(element, m); getSearchIndex().deleteProperty( this, element, PropertyDescriptor.fromProperty(property), authorizations ); if (hasEventListeners()) { queueEvent(new DeletePropertyEvent(this, element, property)); } }"
461,"private InputRow getInputRowFromRow(final Row row, final List<String> dimensions) { return new InputRow() { @Override public List<String> getDimensions() { return dimensions; } @Override public long getTimestampFromEpoch() { return row.getTimestampFromEpoch(); } @Override public DateTime getTimestamp() { return row.getTimestamp(); } @Override public List<String> getDimension(String dimension) { return row.getDimension(dimension); } @Override public Object getRaw(String dimension) { return row.getRaw(dimension); } @Override <START> public Float getFloatMetric(String metric) <END> { return row.getFloatMetric(metric); } @Override public Long getLongMetric(String metric) { return row.getLongMetric(metric); } @Override public Double getDoubleMetric(String metric) { return row.getDoubleMetric(metric); } @Override public int compareTo(Row o) { return row.compareTo(o); } }; }",Please add @Nullable (same below),"private InputRow getInputRowFromRow(final Row row, final List<String> dimensions) { return new InputRow() { @Override public List<String> getDimensions() { return dimensions; } @Override public long getTimestampFromEpoch() { return row.getTimestampFromEpoch(); } @Override public DateTime getTimestamp() { return row.getTimestamp(); } @Override public List<String> getDimension(String dimension) { return row.getDimension(dimension); } @Override @Nullable public Object getRaw(String dimension) { return row.getRaw(dimension); } @Override public Number getMetric(String metric) { return row.getMetric(metric); } @Override public int compareTo(Row o) { return row.compareTo(o); } }; }"
462,"public void testGetStreamIds() { <START> assertEquals(ImmutableList.of(), ImmutableList.copyOf( <END> new StreamConfig(new MapConfig()).getStreamIds())); StreamConfig streamConfig = new StreamConfig(new MapConfig(ImmutableMap.of( String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + "".property"", ""value""))); assertEquals(ImmutableList.of(STREAM_ID), ImmutableList.copyOf(streamConfig.getStreamIds())); streamConfig = new StreamConfig(new MapConfig(ImmutableMap.of( String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + "".property.subProperty"", ""value""))); assertEquals(ImmutableList.of(STREAM_ID), ImmutableList.copyOf(streamConfig.getStreamIds())); streamConfig = new StreamConfig(new MapConfig(ImmutableMap.of( String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + "".property0"", ""value"", String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + "".property1"", ""value"", String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + "".property.subProperty0"", ""value"", String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + "".property.subProperty1"", ""value"", String.format(StreamConfig.STREAM_ID_PREFIX, OTHER_STREAM_ID) + "".property"", ""value""))); assertEquals(ImmutableList.of(STREAM_ID, OTHER_STREAM_ID), ImmutableList.copyOf(streamConfig.getStreamIds())); }","getStreamIds returns a Set, change expected values compare Set? I realize testGetStreamIds originally written compare a Set instead of List","public void testGetStreamIds() { assertEquals(ImmutableList.of(), ImmutableList.copyOf( new StreamConfig(new MapConfig()).getStreamIds())); StreamConfig streamConfig = new StreamConfig(new MapConfig(ImmutableMap.of( String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + "".property"", ""value""))); assertEquals(ImmutableSet.of(STREAM_ID), ImmutableSet.copyOf(streamConfig.getStreamIds())); streamConfig = new StreamConfig(new MapConfig(ImmutableMap.of( String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + "".property.subProperty"", ""value""))); assertEquals(ImmutableSet.of(STREAM_ID), ImmutableSet.copyOf(streamConfig.getStreamIds())); streamConfig = new StreamConfig(new MapConfig(ImmutableMap.of( String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + "".property0"", ""value"", String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + "".property1"", ""value"", String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + "".property.subProperty0"", ""value"", String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + "".property.subProperty1"", ""value"", String.format(StreamConfig.STREAM_ID_PREFIX, OTHER_STREAM_ID) + "".property"", ""value""))); assertEquals(ImmutableSet.of(STREAM_ID, OTHER_STREAM_ID), ImmutableSet.copyOf(streamConfig.getStreamIds())); }"
463,"private void prepareTest() { runner = spy(new LocalApplicationRunner(mockApp, config)); <START> localPlanner = spy((LocalJobConfigPlanner) Whitebox.getInternalState(runner, ""planner"")); <END> Whitebox.setInternalState(runner, ""planner"", localPlanner); }","Instead of Whitebox, a test constructor accepts a planner? Reflection harder find usages do refactoring","private void prepareTest() { ApplicationDescriptorImpl<? extends ApplicationDescriptor> appDesc = ApplicationDescriptorUtil.getAppDescriptor(mockApp, config); localPlanner = spy(new LocalJobPlanner(appDesc)); runner = spy(new LocalApplicationRunner(appDesc, localPlanner)); }"
464,"protected CacheConfiguration<?, ?> getCacheDefinitionFrom(String resourcePath, String cacheName) throws SAXException, JAXBException, ParserConfigurationException, IOException, ClassNotFoundException { final URL resource = this.getClass().getResource(resourcePath); ConfigurationParser rootParser = new ConfigurationParser(resource.toExternalForm()); <START> CacheDefinition cacheDefinition = StreamSupport.stream(rootParser.getCacheElements().spliterator(), true) <END> .filter(def -> def.id().equals(cacheName)).findAny().get(); return parser.parseServiceConfiguration(cacheDefinition, classLoader, cacheConfigurationBuilder).build(); }",parallel stream,"protected CacheConfiguration<?, ?> getCacheDefinitionFrom(String resourcePath, String cacheName) throws SAXException, JAXBException, ParserConfigurationException, IOException, ClassNotFoundException { final URL resource = this.getClass().getResource(resourcePath); ConfigurationParser rootParser = new ConfigurationParser(resource.toExternalForm()); CacheDefinition cacheDefinition = StreamSupport.stream(rootParser.getCacheElements().spliterator(), false) .filter(def -> def.id().equals(cacheName)).findAny().get(); return parser.parseServiceConfiguration(cacheDefinition, classLoader, cacheConfigurationBuilder).build(); }"
465,"public void onStartup(ServletContext servletContext) { LongTaskTimer longTaskTimer = LongTaskTimer <START> .builder(""spring.cloud.dataflow.server"").description(""DataFlow duration timer"") <END> .tags(Tags.empty()).register(Metrics.globalRegistry); this.longTaskSample = longTaskTimer.start(); if (StringUtils.hasText(dataSourceUrl) && dataSourceUrl.startsWith(""jdbc:h2:tcp://localhost:"")) { logger.info(""Start Embedded H2""); initH2TCPServer(); } }","if this description displayed anywhere. If displayed, please change name DataFlow Spring Cloud Data Flow","public void onStartup(ServletContext servletContext) { LongTaskTimer longTaskTimer = LongTaskTimer .builder(""spring.cloud.dataflow.server"").description(""Spring Cloud Data Flow duration timer"") .tags(Tags.empty()).register(Metrics.globalRegistry); this.longTaskSample = longTaskTimer.start(); if (StringUtils.hasText(dataSourceUrl) && dataSourceUrl.startsWith(""jdbc:h2:tcp://localhost:"")) { logger.info(""Start Embedded H2""); initH2TCPServer(); } }"
466,"private String key(final CreateContainerResponse container) throws IOException { final StringWriter writer = new StringWriter(); <START> IOUtil.copy( <END> this.client.copyFileFromContainerCmd( container.getId(), ""/root/.ssh/id_rsa"" ).exec(), writer ); final String key = writer.toString(); return key.substring(key.indexOf('-'), key.lastIndexOf('-') + 1); }",@original-brownbear need IOUtil plexus? some special property need,"private String key(final CreateContainerResponse container) throws IOException { final StringWriter writer = new StringWriter(); IOUtils.copy( this.client.copyFileFromContainerCmd( container.getId(), ""/root/.ssh/id_rsa"" ).exec(), writer ); final String key = writer.toString(); return key.substring(key.indexOf('-'), key.lastIndexOf('-') + 1); }"
467,"<START> public void setInSlot(Object slot, PresenterWidget<?> content) { <END> super.setInSlot(slot, content); if (slot == tabContentSlot) { try { Presenter<?, ?> presenter = (Presenter<?, ?>) content; Proxy<?> proxy = (Proxy<?>) presenter.getProxy(); if (proxy instanceof TabContentProxy) { getView().setActiveTab(((TabContentProxy<?>) proxy).getTab()); getView().setActiveTabHistoryToken(((TabContentProxy<?>) proxy).getTargetHistoryToken()); } } catch (Exception e) { logger.log(Level.SEVERE, ""Error while updating tab view"", e); } } }","This effectively overrides GWTP TabContainerPresenter#setInSlot(IsSlot<T>, T) method, this: ... try { Presenter<?, ?> presenter = (Presenter<?, ?>) child; TabContentProxy<?> proxy = (TabContentProxy<?>) presenter.getProxy(); getView().setActiveTab(proxy.getTab()); } catch (Exception e) { // cast, worry, highlight a tab } ... try/catch block catch java.lang.ClassCastException instanceof check is redundant here, recommend code before. typecast fail if a non-tab Presenter is revealed this (tab container) Presenter, a coding mistake","public void setInSlot(Object slot, PresenterWidget<?> content) { super.setInSlot(slot, content); if (slot == tabContentSlot) { try { Presenter<?, ?> presenter = (Presenter<?, ?>) content; TabContentProxy<?> proxy = (TabContentProxy<?>) presenter.getProxy(); getView().setActiveTab(proxy.getTab()); getView().setActiveTabHistoryToken(proxy.getTargetHistoryToken()); } catch (Exception e) { logger.log(Level.SEVERE, ""Error while updating tab view"", e); } } }"
468,"public void testConvertBedToTargetFile() { final String[] arguments = { ""-"" + ConvertBedToTargetFile.BED_INPUT_SHORT_NAME, TEST_BED_INPUT.getAbsolutePath(), ""-"" + ConvertBedToTargetFile.TARGET_OUTPUT_SHORT_NAME, TEST_TARGET_OUTPUT.getAbsolutePath(), }; runCommandLine(arguments); Assert.assertTrue(TEST_TARGET_OUTPUT.exists()); List<Target> outputTestTargets = TargetTableReader.readTargetFile(TEST_TARGET_OUTPUT); Assert.assertNotNull(outputTestTargets); List<Target> gtTargets = TargetTableReader.readTargetFile(TARGET_FILE_GT); Assert.assertEquals(outputTestTargets.size(), gtTargets.size()); <START> for(int i=0; i<gtTargets.size(); i++){ <END> Assert.assertEquals(outputTestTargets.get(i), gtTargets.get(i)); } }",Space for ... e.g. for ( ... ),"public void testConvertBedToTargetFile() { final String[] arguments = { ""-"" + ConvertBedToTargetFile.BED_INPUT_SHORT_NAME, TEST_BED_INPUT.getAbsolutePath(), ""-"" + ConvertBedToTargetFile.TARGET_OUTPUT_SHORT_NAME, TEST_TARGET_OUTPUT.getAbsolutePath(), }; runCommandLine(arguments); Assert.assertTrue(TEST_TARGET_OUTPUT.exists()); final List<Target> outputTestTargets = TargetTableReader.readTargetFile(TEST_TARGET_OUTPUT); Assert.assertNotNull(outputTestTargets); final List<Target> gtTargets = TargetTableReader.readTargetFile(TARGET_FILE_GT); Assert.assertEquals(outputTestTargets.size(), gtTargets.size()); for(int i=0; i<gtTargets.size(); i++){ Assert.assertEquals(outputTestTargets.get(i), gtTargets.get(i)); } }"
469,"public void encode(LuceneDocumentBuilder documentBuilder, String absoluteFieldPath, String value) { if ( value == null && indexNullAsValue != null ) { value = indexNullAsValue; } if ( value == null ) { return; } if ( searchable ) { documentBuilder.addField( new Field( absoluteFieldPath, value, fieldType ) ); } else if ( fieldType.stored() ) { documentBuilder.addField( new StoredField( absoluteFieldPath, normalize( absoluteFieldPath, value ) ) ); <START> } <END> if ( sortable ) { documentBuilder.addField( new SortedDocValuesField( absoluteFieldPath, normalize( absoluteFieldPath, value ) ) ); } if ( !sortable && fieldType.omitNorms() ) { documentBuilder.addFieldName( absoluteFieldPath ); } }","this is necessary? fieldType account. org.hibernate.search.backend.lucene.types.dsl.impl.LuceneStringIndexFieldTypeContext#getFieldType. In particular, if field is searchable, indexOptions forced IndexOptions.NONE. disable norms term vectors too, if explicitly set, matters if indexOptions is set NONE","public void encode(LuceneDocumentBuilder documentBuilder, String absoluteFieldPath, String value) { if ( value == null && indexNullAsValue != null ) { value = indexNullAsValue; } if ( value == null ) { return; } if ( searchable || fieldType.stored() ) { documentBuilder.addField( new Field( absoluteFieldPath, value, fieldType ) ); } if ( sortable ) { documentBuilder.addField( new SortedDocValuesField( absoluteFieldPath, normalize( absoluteFieldPath, value ) ) ); } if ( !sortable && fieldType.omitNorms() ) { documentBuilder.addFieldName( absoluteFieldPath ); } }"
470,"public void testValidMessageFlow() throws UnsupportedEncodingException, XMLStreamException { InputStream xmlStream = this.getClass().getClassLoader().getResourceAsStream(""org/activiti/engine/test/validation/validMessageProcess.bpmn20.xml""); XMLInputFactory xif = XMLInputFactory.newInstance(); InputStreamReader in = new InputStreamReader(xmlStream, ""UTF-8""); XMLStreamReader xtr = xif.createXMLStreamReader(in); <START> BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr); <END> Assert.assertNotNull(bpmnModel); Assert.assertNotNull(bpmnModel); List<ValidationError> allErrors = processValidator.validate(bpmnModel); Assert.assertEquals(0, allErrors.size()); }",block line 254 258 extracted in a method readModel(modelPath) reused in next test,"public void testValidMessageFlow() throws Exception { BpmnModel bpmnModel = readModel( ""org/activiti/engine/test/validation/validMessageProcess.bpmn20.xml""); Assert.assertNotNull(bpmnModel); assertThat(bpmnModel).isNotNull(); List<ValidationError> allErrors = processValidator.validate(bpmnModel); assertThat(allErrors).isEmpty(); }"
471,"protected BinaryData execute( ModelControllerClient mcc, EndpointService<DMRNodeLocation, DMRSession> endpointService, String modelNodePath, BasicMessageWithExtraData<UpdateCollectionIntervalsRequest> envelope, UpdateCollectionIntervalsResponse response, CommandContext context, DMRSession dmrContext) throws Exception { UpdateCollectionIntervalsRequest request = envelope.getBasicMessage(); Map<PathAddress, String> metricTypes = filterUpdates(mcc, request.getMetricTypes(), false); Map<PathAddress, String> availTypes = filterUpdates(mcc, request.getAvailTypes(), true); if (isEmpty(metricTypes) && isEmpty(availTypes)) { log.debug(""Skipping collection interval update, no valid type updates provided.""); return null; } CompositeOperationBuilder<?> composite = OperationBuilder.composite(); addUpdates(composite, metricTypes); addUpdates(composite, availTypes); composite.byNameOperation(""start"") <START> .address(PathAddress.parseCLIStyleAddress(""/subsystem=hawkular-wildfly-agent/"")) <END> .attribute(""restart"", ""true"") .attribute(""delay"", ""500"") .parentBuilder(); try { OperationResult<?> opResult = composite.execute(mcc).assertSuccess(); setServerRefreshIndicator(opResult, response); } catch (DmrApiException e) { log.errorf(""Failed to update collection intervals: %s"", e.getMessage()); throw e; } return null; }","This work EAP6, please this: [WildflyCompatibilityUtils.parseCLIStyleAddress](<LINK_0> WildflyCompatibilityUtils.parseCLIStyleAddress(""/subsystem=hawkular-wildfly-agent/"")","protected BinaryData execute( ModelControllerClient mcc, EndpointService<DMRNodeLocation, DMRSession> endpointService, String modelNodePath, BasicMessageWithExtraData<UpdateCollectionIntervalsRequest> envelope, UpdateCollectionIntervalsResponse response, CommandContext context, DMRSession dmrContext) throws Exception { PathAddress agentAddress = WildflyCompatibilityUtils.parseCLIStyleAddress(modelNodePath); UpdateCollectionIntervalsRequest request = envelope.getBasicMessage(); Map<PathAddress, String> metricTypes = filterUpdates(mcc, request.getMetricTypes(), false, agentAddress); Map<PathAddress, String> availTypes = filterUpdates(mcc, request.getAvailTypes(), true, agentAddress); if (isEmpty(metricTypes) && isEmpty(availTypes)) { log.debug(""Skipping collection interval update, no valid type updates provided.""); return null; } CompositeOperationBuilder<?> composite = OperationBuilder.composite(); addUpdates(composite, metricTypes); addUpdates(composite, availTypes); composite.allowResourceServiceRestart(false); composite.byNameOperation(""start"") .address(agentAddress) .attribute(""refresh"", ""true"") .attribute(""delay"", ""500"") .parentBuilder(); try { OperationResult<?> opResult = composite.execute(mcc).assertSuccess(); setServerRefreshIndicator(opResult, response); } catch (DmrApiException e) { log.errorf(""Failed to update collection intervals: %s"", e.getMessage()); throw e; } return null; }"
472,"public final void writeLabel(final LabelSegment labelSegment) throws IOException, NitfFormatException { writeFixedLengthString(LabelConstants.LA, LabelConstants.LA.length()); writeFixedLengthString(labelSegment.getIdentifier(), LabelConstants.LID_LENGTH); writeSecurityMetadata(labelSegment.getSecurityMetadata()); writeENCRYP(); writeFixedLengthString("" "", LabelConstants.LFS_LENGTH); writeFixedLengthNumber(labelSegment.getLabelCellWidth(), LabelConstants.LCW_LENGTH); writeFixedLengthNumber(labelSegment.getLabelCellHeight(), LabelConstants.LCH_LENGTH); writeFixedLengthNumber(labelSegment.getLabelDisplayLevel(), LabelConstants.LDLVL_LENGTH); writeFixedLengthNumber(labelSegment.getAttachmentLevel(), LabelConstants.LALVL_LENGTH); writeFixedLengthNumber(labelSegment.getLabelLocationRow(), LabelConstants.LLOC_HALF_LENGTH); writeFixedLengthNumber(labelSegment.getLabelLocationColumn(), LabelConstants.LLOC_HALF_LENGTH); writeBytes(labelSegment.getLabelTextColour().toByteArray(), RGBColourImpl.RGB_COLOUR_LENGTH); writeBytes(labelSegment.getLabelBackgroundColour().toByteArray(), RGBColourImpl.RGB_COLOUR_LENGTH); byte[] labelExtendedSubheaderData = mTreParser.getTREs(labelSegment, TreSource.LabelExtendedSubheaderData); int labelExtendedSubheaderDataLength = labelExtendedSubheaderData.length; if ((labelExtendedSubheaderDataLength > 0) || (labelSegment.getExtendedHeaderDataOverflow() != 0)) { labelExtendedSubheaderDataLength += LabelConstants.LXSOFL_LENGTH; } writeFixedLengthNumber(labelExtendedSubheaderDataLength, LabelConstants.LXSHDL_LENGTH); if (labelExtendedSubheaderDataLength > 0) { writeFixedLengthNumber(labelSegment.getExtendedHeaderDataOverflow(), LabelConstants.LXSOFL_LENGTH); writeBytes(labelExtendedSubheaderData, labelExtendedSubheaderDataLength - LabelConstants.LXSOFL_LENGTH); } mOutput.writeBytes(labelSegment.getData()); <START> } <END>",I static imports,"public final void writeLabel(final LabelSegment labelSegment) throws IOException, NitfFormatException { writeFixedLengthString(LA, LA.length()); writeFixedLengthString(labelSegment.getIdentifier(), LID_LENGTH); writeSecurityMetadata(labelSegment.getSecurityMetadata()); writeENCRYP(); writeFixedLengthString("" "", LFS_LENGTH); writeFixedLengthNumber(labelSegment.getLabelCellWidth(), LCW_LENGTH); writeFixedLengthNumber(labelSegment.getLabelCellHeight(), LCH_LENGTH); writeFixedLengthNumber(labelSegment.getLabelDisplayLevel(), LDLVL_LENGTH); writeFixedLengthNumber(labelSegment.getAttachmentLevel(), LALVL_LENGTH); writeFixedLengthNumber(labelSegment.getLabelLocationRow(), LLOC_HALF_LENGTH); writeFixedLengthNumber(labelSegment.getLabelLocationColumn(), LLOC_HALF_LENGTH); writeBytes(labelSegment.getLabelTextColour().toByteArray(), RGBColourImpl.RGB_COLOUR_LENGTH); writeBytes(labelSegment.getLabelBackgroundColour().toByteArray(), RGBColourImpl.RGB_COLOUR_LENGTH); byte[] labelExtendedSubheaderData = mTreParser.getTREs(labelSegment, TreSource.LabelExtendedSubheaderData); int labelExtendedSubheaderDataLength = labelExtendedSubheaderData.length; if ((labelExtendedSubheaderDataLength > 0) || (labelSegment.getExtendedHeaderDataOverflow() != 0)) { labelExtendedSubheaderDataLength += LXSOFL_LENGTH; } writeFixedLengthNumber(labelExtendedSubheaderDataLength, LXSHDL_LENGTH); if (labelExtendedSubheaderDataLength > 0) { writeFixedLengthNumber(labelSegment.getExtendedHeaderDataOverflow(), LXSOFL_LENGTH); writeBytes(labelExtendedSubheaderData, labelExtendedSubheaderDataLength - LXSOFL_LENGTH); } mOutput.writeBytes(labelSegment.getData()); }"
473,<START> public void setProperties(Set<Property> properties) { <END> this.properties = properties; },"Similarly, want create a new Set based set received, ensure contents changed some external object","public Node setProperties(Set<Property> properties) { if (details == null) { throw new IllegalArgumentException(""Null value not permitted""); } this.properties = properties; return this; }"
474,"public void removeAllPrivateWorkerKeys(String topologyId) { for (WorkerTokenServiceType type : WorkerTokenServiceType.values()) { String path = ClusterUtils.secretKeysPath(type, topologyId); try { <START> LOG.debug(""Removing worker keys under {}"", path); <END> stateStorage.delete_node(path); } catch (RuntimeException e) { if (!Utils.exceptionCauseIsInstanceOf(KeeperException.NoNodeException.class, e)) { throw e; } } } }","If this hit often, I vote for making this info","public void removeAllPrivateWorkerKeys(String topologyId) { for (WorkerTokenServiceType type : WorkerTokenServiceType.values()) { String path = ClusterUtils.secretKeysPath(type, topologyId); try { LOG.info(""Removing worker keys under {}"", path); stateStorage.delete_node(path); } catch (RuntimeException e) { if (!Utils.exceptionCauseIsInstanceOf(KeeperException.NoNodeException.class, e)) { throw e; } } } }"
475,"public static PartitionDesc buildPartitionDesc(String partitionName) { PartitionDesc partitionDesc = new PartitionDesc(); partitionDesc.setPartitionName(partitionName); String[] partitionNames = partitionName.split(""/""); List<PartitionKeyProto> partitionKeyList = new ArrayList<>(); <START> for (String partitionName1 : partitionNames) { <END> String[] splits = partitionName1.split(""=""); String columnName = """", partitionValue = """"; if (splits.length == 2) { columnName = splits[0]; partitionValue = splits[1]; } else if (splits.length == 1) { if (partitionName1.charAt(0) == '=') { partitionValue = splits[0]; } else { columnName = """"; } } PartitionKeyProto.Builder builder = PartitionKeyProto.newBuilder(); builder.setColumnName(columnName); builder.setPartitionValue(partitionValue); partitionKeyList.add(builder.build()); } partitionDesc.setPartitionKeys(partitionKeyList); partitionDesc.setPath(""hdfs://xxx.com/warehouse/"" + partitionName); return partitionDesc; }","This is valid, a good convention","public static PartitionDesc buildPartitionDesc(String partitionName) { PartitionDesc partitionDesc = new PartitionDesc(); partitionDesc.setPartitionName(partitionName); String[] partitionNames = partitionName.split(""/""); List<PartitionKeyProto> partitionKeyList = new ArrayList<>(); for (String partition : partitionNames) { String[] splits = partition.split(""=""); String columnName = """", partitionValue = """"; if (splits.length == 2) { columnName = splits[0]; partitionValue = splits[1]; } else if (splits.length == 1) { if (partition.charAt(0) == '=') { partitionValue = splits[0]; } else { columnName = """"; } } PartitionKeyProto.Builder builder = PartitionKeyProto.newBuilder(); builder.setColumnName(columnName); builder.setPartitionValue(partitionValue); partitionKeyList.add(builder.build()); } partitionDesc.setPartitionKeys(partitionKeyList); partitionDesc.setPath(""hdfs://xxx.com/warehouse/"" + partitionName); return partitionDesc; }"
476,"public boolean isSatisfied(Map<String, Object> inputs) { <START> String startTimeConfig = (String) module.getConfiguration().get(START_TIME); <END> String endTimeConfig = (String) module.getConfiguration().get(END_TIME); if (startTimeConfig == null || endTimeConfig == null) { logger.error(""Time condition with id {} is not well configured: startTime={} endTime = {}"", module.getId(), startTimeConfig, endTimeConfig); return false; } LocalTime currentTime = LocalTime.now().truncatedTo(ChronoUnit.MINUTES); LocalTime startTime = LocalTime.parse(startTimeConfig).truncatedTo(ChronoUnit.MINUTES); LocalTime endTime = LocalTime.parse(endTimeConfig).truncatedTo(ChronoUnit.MINUTES); if (currentTime.equals(startTime)) { logger.debug(""Time condition with id {} evaluated, that the current time {} equals the start time: {}"", module.getId(), currentTime, startTime); return true; } if (startTime.isBefore(endTime)) { if (currentTime.isAfter(startTime) && currentTime.isBefore(endTime)) { logger.debug(""Time condition with id {} evaluated, that {} is between {} and {}."", module.getId(), currentTime, startTime, endTime); return true; } } else if (currentTime.isAfter(LocalTime.MIDNIGHT) && currentTime.isBefore(endTime) || currentTime.isAfter(startTime) && currentTime.isBefore(LocalTime.MAX)) { logger.debug(""Time condition with id {} evaluated, that {} is between {} and {}, or between {} and {}."", module.getId(), currentTime, LocalTime.MIDNIGHT, endTime, startTime, LocalTime.MAX.truncatedTo(ChronoUnit.MINUTES)); return true; } return false; }",automation handler is recreated configuration change. Please extract configuration in contructor,"public boolean isSatisfied(Map<String, Object> inputs) { if (startTime == null || endTime == null) { logger.warn(""Time condition with id {} is not well configured: startTime={} endTime = {}"", module.getId(), startTime, endTime); return false; } LocalTime currentTime = LocalTime.now().truncatedTo(ChronoUnit.MINUTES); if (currentTime.equals(startTime)) { logger.debug(""Time condition with id {} evaluated, that the current time {} equals the start time: {}"", module.getId(), currentTime, startTime); return true; } if (startTime.isBefore(endTime)) { if (currentTime.isAfter(startTime) && currentTime.isBefore(endTime)) { logger.debug(""Time condition with id {} evaluated, that {} is between {} and {}."", module.getId(), currentTime, startTime, endTime); return true; } } else if (currentTime.isAfter(LocalTime.MIDNIGHT) && currentTime.isBefore(endTime) || currentTime.isAfter(startTime) && currentTime.isBefore(LocalTime.MAX)) { logger.debug(""Time condition with id {} evaluated, that {} is between {} and {}, or between {} and {}."", module.getId(), currentTime, LocalTime.MIDNIGHT, endTime, startTime, LocalTime.MAX.truncatedTo(ChronoUnit.MINUTES)); return true; } return false; }"
477,protected MutableBoundedValue<Short> constructValue(Short actualValue) { return SpongeValueFactory.boundedBuilder(Keys.SPAWNER_MINIMUM_DELAY) <START> .minimum((short) 0) <END> .maximum(Short.MAX_VALUE) .defaultValue((short) 200) .actualValue(actualValue) .build(); },Data Constants,protected MutableBoundedValue<Short> constructValue(Short actualValue) { return SpongeValueFactory.boundedBuilder(Keys.SPAWNER_MINIMUM_DELAY) .minimum((short) 0) .maximum(Short.MAX_VALUE) .defaultValue(DataConstants.DEFAULT_SPAWNER_MINIMUM_SPAWN_DELAY) .actualValue(actualValue) .build(); }
478,"public synchronized void reportProcessingUpdate( final ReportProgressEvent event ) { final int activity = event.getActivity(); if ( firstPageMode && ReportProgressEvent.GENERATING_CONTENT == activity && page > 0 ) { this.status = AsyncExecutionStatus.CONTENT_AVAILABLE; } <START> this.activity = getActivityCode( activity ); <END> this.progress = (int) ReportProgressEvent.computePercentageComplete( event, true ); this.page = event.getPage(); this.row = event.getRow(); }",4 lines identical in methods - refactor common method,"public synchronized void reportProcessingUpdate( final ReportProgressEvent event ) { final int activity = event.getActivity(); if ( firstPageMode && ReportProgressEvent.GENERATING_CONTENT == activity && page > 0 ) { this.status = AsyncExecutionStatus.CONTENT_AVAILABLE; } updateState( event, activity ); }"
479,"public ObjectInspector initialize(ObjectInspector[] arguments) <START> throws UDFArgumentException { <END> if (arguments.length != 1) { throw new UDFArgumentLengthException( ""Ex2 takes 1 mandatory argument""); } GenericUDFUtils.ReturnObjectInspectorResolver keyOIResolver = new GenericUDFUtils.ReturnObjectInspectorResolver( true); GenericUDFUtils.ReturnObjectInspectorResolver valueOIResolver = new GenericUDFUtils.ReturnObjectInspectorResolver( true); ObjectInspector keyOI = keyOIResolver.get(); ObjectInspector valueOI = valueOIResolver.get(); if (keyOI == null) { keyOI = PrimitiveObjectInspectorFactory .getPrimitiveJavaObjectInspector(PrimitiveObjectInspector.PrimitiveCategory.STRING); } if (valueOI == null) { valueOI = PrimitiveObjectInspectorFactory .getPrimitiveJavaObjectInspector(PrimitiveObjectInspector.PrimitiveCategory.STRING); } try { p = new CachingParser(); } catch (IOException e) { e.printStackTrace(); } argumentOIs = arguments; return ObjectInspectorFactory.getStandardMapObjectInspector(keyOI, valueOI); }",Arguments 1 element array. Type ObjectInspector for string abstract,"public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException{ if (arguments.length != 1) throw new UDFArgumentLengthException( ""Arguments array has more than 1 element""); for (int i = 0; i < arguments.length; i++) { if (arguments[i].getCategory() != Category.PRIMITIVE) { throw new UDFArgumentTypeException(i, ""A string argument was expected but an argument of type "" + arguments[i].getTypeName() + "" was given.""); } PrimitiveCategory primitiveCategory = ((PrimitiveObjectInspector) arguments[i]) .getPrimitiveCategory(); if (primitiveCategory != PrimitiveCategory.STRING && primitiveCategory != PrimitiveCategory.VOID) { throw new UDFArgumentTypeException(i, ""A string argument was expected but an argument of type "" + arguments[i].getTypeName() + "" was given.""); } } try { p = new CachingParser(); } catch (IOException e) { e.printStackTrace(); } argumentOIs = arguments; return ObjectInspectorFactory.getStandardMapObjectInspector( PrimitiveObjectInspectorFactory.javaStringObjectInspector, PrimitiveObjectInspectorFactory.javaStringObjectInspector); }"
480,"private StackV4Request getStackRequest(SdxClusterRequest sdxClusterRequest, StackV4Request internalStackV4Request, CloudPlatform cloudPlatform, String runtimeVersion) { if (internalStackV4Request == null) { StackV4Request stackRequest = cdpConfigService.getConfigForKey( new CDPConfigKey(cloudPlatform, sdxClusterRequest.getClusterShape(), runtimeVersion)); if (stackRequest == null) { LOGGER.error(""Can't find template for cloudplatform: {}, shape {}, cdp version: {}"", cloudPlatform, sdxClusterRequest.getClusterShape(), runtimeVersion); throw new BadRequestException(""Can't find template for cloudplatform: "" + cloudPlatform + "", shape: "" + sdxClusterRequest.getClusterShape() + "", runtime version: "" + runtimeVersion); } updateStackV4RequestWithIDBrokerVolume(stackRequest); stackRequest.getCluster().setRangerRazEnabled(sdxClusterRequest.isEnableRangerRaz()); return stackRequest; } else { <START> updateStackV4RequestWithIDBrokerVolume(internalStackV4Request); <END> internalStackV4Request.getCluster().setRangerRazEnabled(sdxClusterRequest.isEnableRangerRaz()); return internalStackV4Request; } }",I if relying custom DL templates pissed this change if expected volume present (for reason). I committing a change overwriting RAZ flag a lines below,"private StackV4Request getStackRequest(SdxClusterRequest sdxClusterRequest, StackV4Request internalStackV4Request, CloudPlatform cloudPlatform, String runtimeVersion) { if (internalStackV4Request == null) { StackV4Request stackRequest = cdpConfigService.getConfigForKey( new CDPConfigKey(cloudPlatform, sdxClusterRequest.getClusterShape(), runtimeVersion)); if (stackRequest == null) { LOGGER.error(""Can't find template for cloudplatform: {}, shape {}, cdp version: {}"", cloudPlatform, sdxClusterRequest.getClusterShape(), runtimeVersion); throw new BadRequestException(""Can't find template for cloudplatform: "" + cloudPlatform + "", shape: "" + sdxClusterRequest.getClusterShape() + "", runtime version: "" + runtimeVersion); } stackRequest.getCluster().setRangerRazEnabled(sdxClusterRequest.isEnableRangerRaz()); return stackRequest; } else { internalStackV4Request.getCluster().setRangerRazEnabled(sdxClusterRequest.isEnableRangerRaz()); return internalStackV4Request; } }"
481,"public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Optional<User> user = userFetcher.userFor(request); if (authenticationIsRequired(request) && !user.isPresent()) { ResponseWriter writer = writerResolver.writerFor(request, response); ErrorSummary summary = ErrorSummary.forException(new NotAuthorizedException()); new ErrorResultWriter().write(summary, writer, request, response); return false; } if (user.isPresent() && !user.get().isProfileComplete() && requiresCompleteProfile(request, user.get())) { ResponseWriter writer = writerResolver.writerFor(request, response); ErrorSummary summary = ErrorSummary.forException(new UserProfileIncompleteException()); <START> new ErrorResultWriter().write(summary, writer, request, response); <END> return false; } return true; }","refactor this avoid code duplication in two, similar, conditions","public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Optional<User> user = userFetcher.userFor(request); String uri = request.getRequestURI(); if (!authorized(user, uri)) { writeError(request, response, new NotAuthorizedException()); return false; } else if (user.isPresent() && !hasProfile(user.get()) && needsProfile(uri, user.get())) { writeError(request, response, new UserProfileIncompleteException()); return false; } return true; }"
482,"public void testCurrentSchemaPropertyNotVisibilityTableDuringFunctionCreation() throws SQLException { Properties properties = new Properties(); properties.setProperty(PGProperty.CURRENT_SCHEMA.getName(), ""public,schema2""); Connection connection = TestUtil.openDB(properties); TestUtil.execute(""create table schema1.check_table (test_col text)"", connection); TestUtil.execute(""insert into schema1.check_table (test_col) values ('test_value')"", connection); try { TestUtil.execute(""create or replace function schema2.check_fun (txt text) returns text as $$"" + "" select test_col from check_table"" + ""$$ language sql immutable"", connection); } catch (PSQLException e) { String sqlState = e.getSQLState(); String message = e.getMessage(); assertThat(""Incorrect sql error code"", sqlState, equalTo(PSQLState.RELATION_DOES_NOT_EXIST.getState())); <START> assertTrue(""Missing table name in error message"", message.contains(""\""check_table\"""")); <END> } catch (Exception e) { fail(""Incorrect exception is occurred""); } connection.close(); }","thing: Missing table name in error message. 1) is clear is missing 2) is clear is missing. Assert message ""\""check_table\"" contained in exception message ..."". Note: assertion **hides** original message, analysis hard. assertThat(..., message, contains(""..."")) add message message parameter","public void testCurrentSchemaPropertyNotVisibilityTableDuringFunctionCreation() throws SQLException { Properties properties = new Properties(); properties.setProperty(PGProperty.CURRENT_SCHEMA.getName(), ""public,schema2""); try (Connection connection = TestUtil.openDB(properties)) { TestUtil.execute(""create table schema1.check_table (test_col text)"", connection); TestUtil.execute(""insert into schema1.check_table (test_col) values ('test_value')"", connection); TestUtil.execute(""create or replace function schema2.check_fun (txt text) returns text as $$"" + "" select test_col from check_table"" + ""$$ language sql immutable"", connection); } catch (PSQLException e) { String sqlState = e.getSQLState(); String message = e.getMessage(); assertThat(""Test creates function in schema 'schema2' and this function try use table \""check_table\"" "" + ""from schema 'schema1'. We expect here sql error code - "" + PSQLState.UNDEFINED_TABLE + "", because search_path does not contains schema 'schema1' and "" + ""postgres does not see table \""check_table\"""", sqlState, equalTo(PSQLState.UNDEFINED_TABLE.getState()) ); assertThat( ""Test creates function in schema 'schema2' and this function try use table \""check_table\"" "" + ""from schema 'schema1'. We expect here that sql error message will be contains \""check_table\"", "" + ""because search_path does not contains schema 'schema1' and postgres does not see "" + ""table \""check_table\"""", message, containsString(""\""check_table\"""") ); } }"
483,public List<LogicalNode> getLogicalNodes() { <START> return logicalNodes; <END> },"add ""this"" qualifier",public List<LogicalNode> getLogicalNodes() { return this.logicalNodes; }
484,"private static void copyFile(File from, File to, Filter onlyCopy) throws IOException { if (!onlyCopy.isRequired(from)) { return; } try (OutputStream out = new FileOutputStream(to)) { final long copied = Files.copy(from.toPath(), out); final long length = from.length(); if (copied != length) { <START> throw new IOException(""Could not transfer all bytes of "" + from.toPath()); <END> } } }",reasonable want include 'to' location,"private static void copyFile(File from, File to, Filter onlyCopy) throws IOException { if (!onlyCopy.isRequired(from)) { return; } try (OutputStream out = new FileOutputStream(to)) { final long copied = Files.copy(from.toPath(), out); final long length = from.length(); if (copied != length) { throw new IOException(""Could not transfer all bytes from "" + from + "" to "" + to); } } }"
485,"public void run() { VanillaSelectionKeySet selectionKeys = null; try { socketChannel.configureBlocking(false); socketChannel.socket().setTcpNoDelay(true); socketChannel.socket().setSoTimeout(0); socketChannel.socket().setSoLinger(false, 0); if (builder.receiveBufferSize() > 0) { socketChannel.socket().setReceiveBufferSize(builder.receiveBufferSize()); } if (builder.sendBufferSize() > 0) { socketChannel.socket().setSendBufferSize(builder.sendBufferSize()); <START> } <END> final VanillaSelector selector = new VanillaSelector() .open() .register(socketChannel, SelectionKey.OP_READ, new Attached()); tailer = builder.chronicle().createTailer(); appender = builder.chronicle().createAppender(); sourceTcpHandler.setTailer(tailer); sourceTcpHandler.setAppender(appender); selectionKeys = selector.vanillaSelectionKeys(); if (selectionKeys != null) { vanillaNioLoop(selector, selectionKeys); } else { nioLoop(selector); } } catch (EOFException e) { if (running.get()) { logger.info(""Connection {} died"", socketChannel); } } catch (Exception e) { if (running.get()) { String msg = e.getMessage(); if (msg != null && (msg.contains(""reset by peer"") || msg.contains(""Broken pipe"") || msg.contains(""was aborted by""))) { logger.info(""Connection {} closed from the other end: "", socketChannel, e.getMessage()); } else { logger.info(""Connection {} died"", socketChannel, e); } } } finally { if (selectionKeys != null) { selectionKeys.clear(); } } try { close(); } catch (IOException e) { logger.warn("""", e); } }","SocketChannel is configured in SourceTcp/SinkTcp TcpEventHandler (i.e. send buffer size, etc) , a single a duplicated place socket is configured","public void run() { sessionActive = true; VanillaSelectionKeySet selectionKeys = null; try { final VanillaSelector selector = new VanillaSelector() .open() .register(socketChannel, SelectionKey.OP_READ, new Attached()); tailer = builder.chronicle().createTailer(); appender = builder.chronicle().createAppender(); sourceTcpHandler.setTailer(tailer); sourceTcpHandler.setAppender(appender); selectionKeys = selector.vanillaSelectionKeys(); if (selectionKeys != null) { vanillaNioLoop(selector, selectionKeys); } else { nioLoop(selector); } } catch (InvalidEventHandlerException e) { if (running.get()) { logger.info(""Connection {} died"", socketChannel); } } catch (Exception e) { if (running.get()) { logger.info(""Connection {} died"", socketChannel, e); } } finally { if (selectionKeys != null) { selectionKeys.clear(); } } try { close(); } catch (IOException e) { logger.warn("""", e); } }"
486,public List<Object> getJustificationList() { <START> return Collections.unmodifiableList(justificationList); <END> },"duplicating in constructor wrapping in unmodifiable List call? do in constructor too? if worth though. This costs performance wise. 2 proposals: Proposal A): in constructor: Collections.unmodifiableList(new ArrayList<>(justificationList)) Proposal B: in constructor: Collections.unmodifiableList(justificationList) I suspect for DRL CS-B, proposal B is bugfree, duplication cost of proposal A is a perf loss. For CS-D duplicate giving constructor",public List<Object> getJustificationList() { return justificationList; }
487,"<START> public <T> Object create(Class<T> cls) { <END> final AnnotatedType<T> annotatedType = beanManager.createAnnotatedType(cls); final InjectionTargetFactory<T> injectionTargetFactory = beanManager.getInjectionTargetFactory(annotatedType); final BeanAttributes<T> attributes = beanManager.createBeanAttributes(annotatedType); final Bean<T> bean = beanManager.createBean(attributes, cls, injectionTargetFactory); final CreationalContext<?> context = beanManager.createCreationalContext(bean); return beanManager.getReference(bean, cls, context); }",client close() - worse case - that. if beanManager.isNormalScope(bean.getScope()) is true need call context.release(),"public <T> Object create(Class<T> cls) { final AnnotatedType<T> annotatedType = beanManager.createAnnotatedType(cls); final InjectionTargetFactory<T> injectionTargetFactory = beanManager.getInjectionTargetFactory(annotatedType); final BeanAttributes<T> attributes = beanManager.createBeanAttributes(annotatedType); final Bean<T> bean = beanManager.createBean(attributes, cls, injectionTargetFactory); final CreationalContext<?> context = beanManager.createCreationalContext(bean); if (!beanManager.isNormalScope(bean.getScope())) { beanManager.fireEvent(new DisposableCreationalContext(context)); } return beanManager.getReference(bean, cls, context); }"
488,"public ConfigLocation getConfigLocation() { Iterable<ConfigLocation> locations; <START> locations = configLocationFileStore.getAll(); <END> StringBuilder sb = new StringBuilder(""""); for (ConfigLocation configLocation : locations) { sb.append(configLocation.getLocation()).append(' '); Resource configLocationResource = configLocation.toResource(); try { Resource motechSettings; motechSettings = configLocationResource.createRelative(ConfigurationConstants.SETTINGS_FILE_NAME); if (motechSettings.isReadable() && locations != null) { return configLocation; } LOGGER.warn(""Could not read motech-settings.properties from: "" + configLocationResource.toString()); } catch (IOException e) { LOGGER.warn(""Problem reading motech-settings.properties from location: "" + configLocationResource.toString(), e); } } throw new MotechConfigurationException(String.format(""Could not read settings from any of the config locations. Searched directories: %s."", sb)); }",done 1 line,"public ConfigLocation getConfigLocation() { Iterable<ConfigLocation> locations = configLocationFileStore.getAll(); StringBuilder sb = new StringBuilder(""""); for (ConfigLocation configLocation : locations) { sb.append(configLocation.getLocation()).append(' '); Resource configLocationResource = configLocation.toResource(); try { Resource motechSettings = configLocationResource.createRelative(ConfigurationConstants.SETTINGS_FILE_NAME); if (motechSettings.isReadable() && locations != null) { return configLocation; } LOGGER.warn(""Could not read motech-settings.properties from: "" + configLocationResource.toString()); } catch (IOException e) { LOGGER.warn(""Problem reading motech-settings.properties from location: "" + configLocationResource.toString(), e); } } throw new MotechConfigurationException(String.format(""Could not read settings from any of the config locations. Searched directories: %s."", sb)); }"
489,"AnalyzedInsertStatement(AnalyzedRelation subQueryRelation, DocTableInfo tableInfo, List<Reference> targetColumns, boolean ignoreDuplicateKeys, Map<Reference, Symbol> onDuplicateKeyAssignments, List<ColumnIdent> outputNames, List<Symbol> returnValues) { this.targetTable = tableInfo; this.subQueryRelation = subQueryRelation; this.ignoreDuplicateKeys = ignoreDuplicateKeys; this.onDuplicateKeyAssignments = onDuplicateKeyAssignments; this.targetColumns = targetColumns; Map<ColumnIdent, Integer> columnPositions = toPositionMap(targetColumns); int clusteredByIdx = MoreObjects.firstNonNull(columnPositions.get(tableInfo.clusteredBy()), -1); if (clusteredByIdx > -1) { clusteredBySymbol = new InputColumn(clusteredByIdx, targetColumns.get(clusteredByIdx).valueType()); } else { clusteredBySymbol = null; } ImmutableMap<ColumnIdent, GeneratedReference> generatedColumns = Maps.uniqueIndex(tableInfo.generatedColumns(), Reference::column); ImmutableMap<ColumnIdent, Reference> defaultExpressionColumns = Maps.uniqueIndex(tableInfo.defaultExpressionColumns(), Reference::column); if (tableInfo.hasAutoGeneratedPrimaryKey()) { this.primaryKeySymbols = Collections.emptyList(); } else { this.primaryKeySymbols = symbolsFromTargetColumnPositionOrGeneratedExpression( columnPositions, targetColumns, tableInfo.primaryKey(), generatedColumns, defaultExpressionColumns, true); } this.partitionedBySymbols = symbolsFromTargetColumnPositionOrGeneratedExpression( columnPositions, targetColumns, tableInfo.partitionedBy(), generatedColumns, defaultExpressionColumns, false); this.returnValues = returnValues; if (!outputNames.isEmpty() && !returnValues.isEmpty()) { this.fields = new ArrayList<>(outputNames.size()); Iterator<Symbol> outputsIterator = returnValues.iterator(); for (ColumnIdent path : outputNames) { <START> fields.add(new Field(new TableRelation(tableInfo), path, outputsIterator.next())); <END> } } else { fields = null; } }","suggestion fields.add(new Field(this, path, outputsIterator.next())); relation of a Field point relation owns field, in this case is AnalyzedInsertStatement","AnalyzedInsertStatement(AnalyzedRelation subQueryRelation, DocTableInfo tableInfo, List<Reference> targetColumns, boolean ignoreDuplicateKeys, Map<Reference, Symbol> onDuplicateKeyAssignments, List<ColumnIdent> outputNames, List<Symbol> returnValues) { this.targetTable = tableInfo; this.subQueryRelation = subQueryRelation; this.ignoreDuplicateKeys = ignoreDuplicateKeys; this.onDuplicateKeyAssignments = onDuplicateKeyAssignments; this.targetColumns = targetColumns; Map<ColumnIdent, Integer> columnPositions = toPositionMap(targetColumns); int clusteredByIdx = MoreObjects.firstNonNull(columnPositions.get(tableInfo.clusteredBy()), -1); if (clusteredByIdx > -1) { clusteredBySymbol = new InputColumn(clusteredByIdx, targetColumns.get(clusteredByIdx).valueType()); } else { clusteredBySymbol = null; } ImmutableMap<ColumnIdent, GeneratedReference> generatedColumns = Maps.uniqueIndex(tableInfo.generatedColumns(), Reference::column); ImmutableMap<ColumnIdent, Reference> defaultExpressionColumns = Maps.uniqueIndex(tableInfo.defaultExpressionColumns(), Reference::column); if (tableInfo.hasAutoGeneratedPrimaryKey()) { this.primaryKeySymbols = Collections.emptyList(); } else { this.primaryKeySymbols = symbolsFromTargetColumnPositionOrGeneratedExpression( columnPositions, targetColumns, tableInfo.primaryKey(), generatedColumns, defaultExpressionColumns, true); } this.partitionedBySymbols = symbolsFromTargetColumnPositionOrGeneratedExpression( columnPositions, targetColumns, tableInfo.partitionedBy(), generatedColumns, defaultExpressionColumns, false); this.returnValues = returnValues; if (!outputNames.isEmpty() && !returnValues.isEmpty()) { this.fields = new ArrayList<>(outputNames.size()); Iterator<Symbol> outputsIterator = returnValues.iterator(); for (ColumnIdent path : outputNames) { fields.add(new Field(this.subQueryRelation, path, outputsIterator.next())); } } else { fields = null; } }"
490,"public void normal() { <START> final TestObserver<Integer> ts = new TestObserver<Integer>(); <END> Observable.range(1, 5).mergeWith( Completable.fromAction(new Action() { @Override public void run() throws Exception { ts.onNext(100); } }) ) .subscribe(ts); ts.assertResult(1, 2, 3, 4, 5, 100); }",nit: ts,"public void normal() { final TestObserver<Integer> to = new TestObserver<Integer>(); Observable.range(1, 5).mergeWith( Completable.fromAction(new Action() { @Override public void run() throws Exception { to.onNext(100); } }) ) .subscribe(to); to.assertResult(1, 2, 3, 4, 5, 100); }"
491,"protected Void doInBackground(Void... params) { MimeMessage message; try { message = createMessage(); <START> } catch (Exception me) { <END> Log.e(K9.LOG_TAG, ""Failed to create new message for send or save."", me); throw new RuntimeException(""Failed to create a new message for send or save."", me); } try { mContacts.markAsContacted(message.getRecipients(RecipientType.TO)); mContacts.markAsContacted(message.getRecipients(RecipientType.CC)); mContacts.markAsContacted(message.getRecipients(RecipientType.BCC)); } catch (Exception e) { Log.e(K9.LOG_TAG, ""Failed to mark contact as contacted."", e); } MessagingController.getInstance(getApplication()).sendMessage(mAccount, message, null); long draftId = mDraftId; if (draftId != INVALID_DRAFT_ID) { mDraftId = INVALID_DRAFT_ID; MessagingController.getInstance(getApplication()).deleteDraft(mAccount, draftId); } return null; }",this a bad idea. list exceptions explicitly,"protected Void doInBackground(Void... params) { MimeMessage message; try { message = createMessage(); } catch (OpenPgpApiException e){ Log.e(K9.LOG_TAG, ""Failed to create new message for send or save."", e); throw new RuntimeException(""Failed to create a new message for send or save."", e); } catch (MessagingException me) { Log.e(K9.LOG_TAG, ""Failed to create new message for send or save."", me); throw new RuntimeException(""Failed to create a new message for send or save."", me); } try { mContacts.markAsContacted(message.getRecipients(RecipientType.TO)); mContacts.markAsContacted(message.getRecipients(RecipientType.CC)); mContacts.markAsContacted(message.getRecipients(RecipientType.BCC)); } catch (Exception e) { Log.e(K9.LOG_TAG, ""Failed to mark contact as contacted."", e); } MessagingController.getInstance(getApplication()).sendMessage(mAccount, message, null); long draftId = mDraftId; if (draftId != INVALID_DRAFT_ID) { mDraftId = INVALID_DRAFT_ID; MessagingController.getInstance(getApplication()).deleteDraft(mAccount, draftId); } return null; }"
492,"private void updateGameMode( CommandSender sender, Player who, GameMode gameMode, ResourceBundle bundle) { String gameModeName = GameModeUtils.prettyPrint(gameMode, bundle.getLocale()); who.setGameMode(gameMode); if (sender.equals(who)) { new LocalizedStringImpl(""gamemode.done.self"", bundle).send(sender, gameModeName); } else { <START> new LocalizedStringImpl(""gamemode.done"", bundle) <END> .send(sender, who.getDisplayName(), gameModeName); } }",This changes behavior longer notifying player gamemode set,"private void updateGameMode( CommandSender sender, Player who, GameMode gameMode, ResourceBundle bundle) { String gameModeName = GameModeUtils.prettyPrint(gameMode, bundle.getLocale()); who.setGameMode(gameMode); if (!sender.equals(who)) { new LocalizedStringImpl(""gamemode.done"", bundle) .send(sender, who.getDisplayName(), gameModeName); } new LocalizedStringImpl(""gamemode.done.to-you"", bundle).send(who, gameModeName); }"
493,"public Change perform(IProgressMonitor pm) throws CoreException { pm.beginTask("""", 1); try { ITestSuite suiteCopy = (ITestSuite) getTestSuite().getWorkingCopy( new NullProgressMonitor()); List<TestSuiteItem> references = getReferences(suiteCopy); Map<Integer, TestSuiteItem> deletedItems = new HashMap<Integer, TestSuiteItem>(); for (TestSuiteItem item : references) { int idx = suiteCopy.getTestSuite().getItems().indexOf(item); deletedItems.put(idx, item); } try { TestSuite suiteNamedElement = (TestSuite) suiteCopy .getModifiedNamedElement(); for (TestSuiteItem item : references) { suiteNamedElement.getItems().remove(item); } WriteAccessChecker writeAccessChecker = new WriteAccessChecker(); <START> if (writeAccessChecker.makeResourceWritable(suiteCopy)) { <END> suiteCopy.commitWorkingCopy(true, new NullProgressMonitor()); } } finally { suiteCopy.discardWorkingCopy(); } return new UndoDeleteTestReferenceChange(getTestSuite(), getQ7Element(), deletedItems); } finally { pm.done(); } }",questions refactoring progress,"public Change perform(IProgressMonitor pm) throws CoreException { pm.beginTask("""", 1); try { ITestSuite suiteCopy = (ITestSuite) getTestSuite().getWorkingCopy( new NullProgressMonitor()); List<TestSuiteItem> references = getReferences(suiteCopy); Map<Integer, TestSuiteItem> deletedItems = new HashMap<Integer, TestSuiteItem>(); for (TestSuiteItem item : references) { int idx = suiteCopy.getTestSuite().getItems().indexOf(item); deletedItems.put(idx, item); } try { TestSuite suiteNamedElement = (TestSuite) suiteCopy .getModifiedNamedElement(); for (TestSuiteItem item : references) { suiteNamedElement.getItems().remove(item); } suiteCopy.commitWorkingCopy(true, new NullProgressMonitor()); } finally { suiteCopy.discardWorkingCopy(); } return new UndoDeleteTestReferenceChange(getTestSuite(), getQ7Element(), deletedItems); } finally { pm.done(); } }"
494,"private void setDateRangeFilter(DateRangeFilter dateFilter) { ZonedDateTime zoneDate = ZonedDateTime.ofInstant(Instant.ofEpochSecond(dateFilter.getStartDate()), Utils.getUserPreferredZoneId()); startDatePicker.setEnabled(dateFilter.isStartDateEnabled()); <START> startCheckBox.setEnabled(dateFilter.isStartDateEnabled()); <END> startDatePicker.setDate(zoneDate.toLocalDate()); zoneDate = ZonedDateTime.ofInstant(Instant.ofEpochSecond(dateFilter.getEndDate()), Utils.getUserPreferredZoneId()); endDatePicker.setEnabled(dateFilter.isEndDateEnabled()); endCheckBox.setEnabled(dateFilter.isEndDateEnabled()); endDatePicker.setDate(zoneDate.toLocalDate()); }",I this setSelected setEnabled,"private void setDateRangeFilter(DateRangeFilter dateFilter) { ZonedDateTime zoneDate = ZonedDateTime.ofInstant(Instant.ofEpochSecond(dateFilter.getStartDate()), Utils.getUserPreferredZoneId()); startDatePicker.setEnabled(dateFilter.isStartDateEnabled()); startCheckBox.setSelected(dateFilter.isStartDateEnabled()); startDatePicker.setDate(zoneDate.toLocalDate()); zoneDate = ZonedDateTime.ofInstant(Instant.ofEpochSecond(dateFilter.getEndDate()), Utils.getUserPreferredZoneId()); endDatePicker.setEnabled(dateFilter.isEndDateEnabled()); endCheckBox.setSelected(dateFilter.isEndDateEnabled()); endDatePicker.setDate(zoneDate.toLocalDate()); }"
495,"protected boolean isAnyAppConfiguredInSourceServerXml() { boolean bConfigured = false; Set<String> locations = getAppConfigLocationsFromSourceServerXml(); if (locations.size() > 0) { log.debug(""Application configuration is found in server.xml.""); <START> bConfigured = true; <END> } return bConfigured; }","I return true. fall return false, instead of creating a variable","protected boolean isAnyAppConfiguredInSourceServerXml() { Set<String> locations = getAppConfigLocationsFromSourceServerXml(); if (locations.size() > 0) { log.debug(""Application configuration is found in server.xml.""); return true; } else { return false; } }"
496,"Bitmap decodeAsset(Uri uri, PicassoBitmapOptions bitmapOptions) throws IOException { <START> String path = Utils.cropScheme(uri.toString(), SCHEME_ASSETS); <END> AssetManager assets = context.getAssets(); if (bitmapOptions != null && bitmapOptions.inJustDecodeBounds) { BitmapFactory.decodeStream(assets.open(path), null, bitmapOptions); calculateInSampleSize(bitmapOptions); } return decodeStream(assets.open(path), bitmapOptions); }",Is uri.getPath() sufficient,"Bitmap decodeAsset(Uri uri, PicassoBitmapOptions bitmapOptions) throws IOException { String path = uri.getPath().substring(1); AssetManager assets = context.getAssets(); if (bitmapOptions != null && bitmapOptions.inJustDecodeBounds) { BitmapFactory.decodeStream(assets.open(path), null, bitmapOptions); calculateInSampleSize(bitmapOptions); } return decodeStream(assets.open(path), bitmapOptions); }"
497,"public void addRepresentation (String fileName, int zoom) { if (fileName == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); int imageSelectorIndex = DPIUtil.mapZoomToImageSelectorIndex(zoom); if (imageSelectorIndex == device.getImageSelector ()) { <START> initNative (fileName); <END> } dpiFilename [imageSelectorIndex] = fileName; addRepresentation (new ImageData(fileName), zoom); }",code required? care in next addRepresentation call,"public void addRepresentation (String fileName, int zoom) { if (fileName == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); int imageSelectorIndex = DPIUtil.mapZoomToImageSelectorIndex(zoom); if (imageSelectorIndex == getImageSelector ()) { initNative (fileName); } imageRepFileNames [imageSelectorIndex] = fileName; addRepresentation (new ImageData(fileName), zoom); }"
498,"public ClientHttpResponse execute() throws IOException { if (this.response == null) { <START> LOGGER.warn(""Attempting to load cached URI before actual caching: "" + this.originalRequest.getURI()); <END> } else { LOGGER.debug(""Loading cached URI resource "" + this.originalRequest.getURI()); } return this.response; }","If request failed, is this.reponse null? Is warning appropriate","public ClientHttpResponse execute() throws IOException { if (!HttpRequestCache.this.cached) { LOGGER.warn(""Attempting to load cached URI before actual caching: "" + this.originalRequest.getURI()); } else if (this.response == null) { LOGGER.warn(""Attempting to load cached URI from failed request: "" + this.originalRequest.getURI()); } else { LOGGER.debug(""Loading cached URI resource "" + this.originalRequest.getURI()); } return this.response; }"
499,"public void testPrioritizedJobsExecution() throws InterruptedException { CountDownAsyncJobListener countDownListener = configureListener(2); CommandContext ctxCMD = new CommandContext(); ctxCMD.setData(""businessKey"", ""low priority""); ctxCMD.setData(""priority"", 2); Date futureDate = new Date(System.currentTimeMillis() + EXTRA_TIME); executorService.scheduleRequest(""org.jbpm.executor.commands.PrintOutCommand"", futureDate, ctxCMD); CommandContext ctxCMD2 = new CommandContext(); ctxCMD2.setData(""businessKey"", ""high priority""); ctxCMD2.setData(""priority"", 8); executorService.scheduleRequest(""org.jbpm.executor.commands.PrintOutCommand"", futureDate, ctxCMD2); countDownListener.waitTillCompleted(); List<RequestInfo> inErrorRequests = executorService.getInErrorRequests(new QueryContext()); assertEquals(0, inErrorRequests.size()); List<RequestInfo> queuedRequests = executorService.getQueuedRequests(new QueryContext()); assertEquals(0, queuedRequests.size()); List<RequestInfo> executedRequests = executorService.getCompletedRequests(new QueryContext()); assertEquals(2, executedRequests.size()); RequestInfo executedHigh = executedRequests.get(1); assertNotNull(executedHigh); assertEquals(""high priority"", executedHigh.getKey()); RequestInfo executedLow = executedRequests.get(0); assertNotNull(executedLow); assertEquals(""low priority"", executedLow.getKey()); logger.info(""executedLow: {}"", executedLow.getTime().getTime()); logger.info(""executedHigh: {}"", executedHigh.getTime().getTime()); <START> logger.info(""exec difference: {}"", (executedLow.getTime().getTime() - executedHigh.getTime().getTime())); <END> assertTrue(executedLow.getTime().getTime() >= executedHigh.getTime().getTime()); }",please delete this logging? need this anymore verified theory issue,"public void testPrioritizedJobsExecution() throws InterruptedException { CountDownAsyncJobListener countDownListener = configureListener(2); CommandContext ctxCMD = new CommandContext(); ctxCMD.setData(""businessKey"", ""low priority""); ctxCMD.setData(""priority"", 2); Date futureDate = new Date(System.currentTimeMillis() + EXTRA_TIME); executorService.scheduleRequest(""org.jbpm.executor.commands.PrintOutCommand"", futureDate, ctxCMD); CommandContext ctxCMD2 = new CommandContext(); ctxCMD2.setData(""businessKey"", ""high priority""); ctxCMD2.setData(""priority"", 8); executorService.scheduleRequest(""org.jbpm.executor.commands.PrintOutCommand"", futureDate, ctxCMD2); countDownListener.waitTillCompleted(); List<RequestInfo> inErrorRequests = executorService.getInErrorRequests(new QueryContext()); assertEquals(0, inErrorRequests.size()); List<RequestInfo> queuedRequests = executorService.getQueuedRequests(new QueryContext()); assertEquals(0, queuedRequests.size()); List<RequestInfo> executedRequests = executorService.getCompletedRequests(new QueryContext()); assertEquals(2, executedRequests.size()); RequestInfo executedHigh = executedRequests.get(1); assertNotNull(executedHigh); assertEquals(""high priority"", executedHigh.getKey()); RequestInfo executedLow = executedRequests.get(0); assertNotNull(executedLow); assertEquals(""low priority"", executedLow.getKey()); assertTrue(executedLow.getTime().getTime() >= executedHigh.getTime().getTime()); }"
