auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static String getHeader(Map<String, Object> args, String header, boolean required) throws RestServiceException { String value = null; if (args.containsKey(header)) { Object valueObj = args.get(header); value = valueObj != null ? valueObj.toString() : null; if (value == null && required) { <START> throw new RestServiceException("Request has unacceptable value for header: " + header, <END> RestServiceErrorCode.InvalidArgs); } } else if (required) { throw new RestServiceException("Request does not have required header: " + header, RestServiceErrorCode.MissingArgs); } return value; }</code><technical_language>change "unacceptable value"? specifically "Request a null for header"</technical_language>

Target:
private static String getHeader(Map<String, Object> args, String header, boolean required) throws RestServiceException { String value = null; if (args.containsKey(header)) { Object valueObj = args.get(header); value = valueObj != null ? valueObj.toString() : null; if (value == null && required) { throw new RestServiceException("Request has null value for header: " + header, RestServiceErrorCode.InvalidArgs); } } else if (required) { throw new RestServiceException("Request does not have required header: " + header, RestServiceErrorCode.MissingArgs); } return value; }
Source:
<code>public void testDefinitionHashCode() { DefinitionImpl<String> a = new DefinitionImpl<>("a"); DefinitionImpl<String> b = new DefinitionImpl<>("a"); assertEquals(a.hashCode(), b.hashCode()); b.setDefinition("b"); assertNotEquals(a.hashCode(), b.hashCode()); b.setDefinition("a"); assertEquals(a.hashCode(), b.hashCode()); <START> <END> }</code><technical_language>Also, null check cool there</technical_language>

Target:
public void testDefinitionHashCode() { DefinitionImpl<String> a = new DefinitionImpl<>("a"); DefinitionImpl<String> b = new DefinitionImpl<>("a"); assertEquals(a.hashCode(), b.hashCode()); b.setDefinition("b"); assertNotEquals(a.hashCode(), b.hashCode()); b.setDefinition(null); assertNotEquals(a, b); b.setDefinition("a"); assertEquals(a.hashCode(), b.hashCode()); }
Source:
<code>public boolean test() { try { String consoleText = getConsoleText(); return consoleText.contains(text); <START> } catch (WaitTimeoutExpiredException ex) { <END> return false; } }</code><technical_language>i do getConsoleText() throw WaitTimeoutExpiredException. I expect return text null if is none. WDYT</technical_language>

Target:
public boolean test() { String consoleText = consoleView.getConsoleText(); if (consoleText == null) { return false; } else { return consoleText.contains(text); } }
Source:
<code>private SsoLocalConfig() { String v; String defaultsPath = DEFAULTS_PATH; v = System.getProperty("ovirt-engine.config.defaults"); if (v != null) { defaultsPath = v; } v = System.getenv("ENGINE_DEFAULTS"); if (v != null) { defaultsPath = v; } String varsPath = VARS_PATH; <START> v = System.getProperty("ovirt-engine.config.vars"); <END> if (v != null) { varsPath = v; } v = System.getenv("ENGINE_VARS"); if (v != null) { varsPath = v; } loadConfig(defaultsPath, varsPath); }</code><technical_language>I getProperty method accepts default parameter, more here</technical_language>

Target:
private SsoLocalConfig() { String v; String defaultsPath = System.getProperty("ovirt-engine.config.defaults", DEFAULTS_PATH); v = System.getenv("ENGINE_DEFAULTS"); if (v != null) { defaultsPath = v; } String varsPath = System.getProperty("ovirt-engine.config.vars", VARS_PATH); v = System.getenv("ENGINE_VARS"); if (v != null) { varsPath = v; } loadConfig(defaultsPath, varsPath); }
Source:
<code>private static void checkNotIndeterminate(Boolean equalsResult) { if (equalsResult == null) { <START> throw new PrestoException(NOT_SUPPORTED, "map key cannot be indeterminate"); <END> } }</code><technical_language>ditto "indeterminate" in error messages</technical_language>

Target:
private static void checkNotIndeterminate(Boolean equalsResult) { if (equalsResult == null) { throw new PrestoException(NOT_SUPPORTED, "map key cannot be null or contain nulls"); } }
Source:
<code>public ScheduleContext(long currentTimeMillis, Collection<Integer> managedShards) { this.scheduleTime = currentTimeMillis; this.shardStateManager = new ShardStateManager(managedShards, asMillisecondsSinceEpochTicker()); this.lockManager = new NoOpShardLockManager(); <START> this.clock = new DefaultClockImpl(); <END> registerMBean(); }</code><technical_language>repeat this? calling this() correct do, call registerMBean() in subsequent constructor</technical_language>

Target:
public ScheduleContext(long currentTimeMillis, Collection<Integer> managedShards) { this(currentTimeMillis, managedShards, new DefaultClockImpl()); }
Source:
<code>public void onGracefulLeave(AvailabilityStrategyContext context, Address leaver) { CacheTopology currentTopology = context.getCurrentTopology(); List<Address> newMembers = new ArrayList<>(currentTopology.getMembers()); if (!newMembers.remove(leaver)) { log.debugf("Cache %s does not have member %s, ignoring leave request", context.getCacheName(), leaver); return; } if (context.getStableTopology() != null && isDataLost(context.getStableTopology().getCurrentCH(), newMembers)) { <START> log.errorf("Cache %s lost data because of graceful leaver %s", context.getCacheName(), leaver); <END> } context.updateCurrentTopology(newMembers); context.queueRebalance(newMembers); }</code><technical_language>Log method</technical_language>

Target:
public void onGracefulLeave(AvailabilityStrategyContext context, Address leaver) { CacheTopology currentTopology = context.getCurrentTopology(); List<Address> newMembers = new ArrayList<>(currentTopology.getMembers()); if (!newMembers.remove(leaver)) { log.debugf("Cache %s does not have member %s, ignoring leave request", context.getCacheName(), leaver); return; } if (context.getStableTopology() != null && isDataLost(context.getStableTopology().getCurrentCH(), newMembers)) { log.lostDataBecauseOfGracefulLeaver(context.getCacheName(), leaver); } context.updateCurrentTopology(newMembers); context.queueRebalance(newMembers); }
Source:
<code>public static void injectSystemProperties(Job job) { for (String propName : System.getProperties().stringPropertyNames()) { <START> Configuration conf = job.getConfiguration(); <END> if (propName.startsWith("hadoop.")) { conf.set(propName.substring("hadoop.".length()), System.getProperty(propName)); } } }</code><technical_language>kinda weird pull configuration out for property... code was, needless. fix get configuration once</technical_language>

Target:
public static void injectSystemProperties(Job job) { final Configuration conf = job.getConfiguration(); for (String propName : System.getProperties().stringPropertyNames()) { if (propName.startsWith("hadoop.")) { conf.set(propName.substring("hadoop.".length()), System.getProperty(propName)); } } }
Source:
<code>protected void niceName(StringBuilder sb, int start) { if (mainGene != null && hiddenGene != null) { String niceName; <START> if (mainGene.equals("weak") && !hiddenGene.equals("weak")) { <END> niceName = "normal"; } else if (mainGene.equals("brown") && !hiddenGene.equals("brown")) { niceName = "normal"; } else { niceName = mainGene; } sb.insert(start, MiscUtils.niceName(niceName)).insert(start + niceName.length(), ' '); } }</code><technical_language>switch Sting compares put literal - stops NPE's</technical_language>

Target:
protected void niceName(StringBuilder sb, int start) { if (mainGene != null && hiddenGene != null) { String niceName; if ("weak".equals(mainGene) && !"weak".equals(hiddenGene)) { niceName = "normal"; } else if ("brown".equals(mainGene) && !"brown".equals(hiddenGene)) { niceName = "normal"; } else { niceName = mainGene; } sb.insert(start, MiscUtils.niceName(niceName)).insert(start + niceName.length(), ' '); } }
Source:
<code>public void detectAndSendChanges() { super.detectAndSendChanges(); if( Platform.isServer() ) { if( this.craftingMode != this.ct.isCraftingRecipe() ) { this.craftingMode = this.ct.isCraftingRecipe(); this.updateOrderOfOutputSlots(); } if( this.substitute != this.ct.isSubstitution() ) { this.substitute = this.ct.isSubstitution(); <START> } <END> } }</code><technical_language>this.substitute = this.ct.isSubstitution();? performance implications ifis used</technical_language>

Target:
public void detectAndSendChanges() { super.detectAndSendChanges(); if( Platform.isServer() ) { if( this.craftingMode != this.ct.isCraftingRecipe() ) { this.craftingMode = this.ct.isCraftingRecipe(); this.updateOrderOfOutputSlots(); } this.substitute = this.ct.isSubstitution(); } }
Source:
<code>public List<Future> rollback(NodeEngine nodeEngine) { List<Future> futures = new ArrayList<Future>(size()); <START> ListIterator<TransactionLogRecord> iterator = getRecordList().listIterator(size()); <END> while (iterator.hasPrevious()) { TransactionLogRecord record = iterator.previous(); Future future = invoke(nodeEngine, record, record.newRollbackOperation()); futures.add(future); } return futures; }</code><technical_language>iterated for recordMap.values() behaviour. iteration order later</technical_language>

Target:
public List<Future> rollback(NodeEngine nodeEngine) { List<Future> futures = new ArrayList<Future>(size()); for (TransactionLogRecord record : recordMap.values()) { Future future = invoke(nodeEngine, record, record.newRollbackOperation()); futures.add(future); } return futures; }
Source:
<code>public List<Record> apply(RevisionResource rsrc, Input input) throws AuthException, BadRequestException, OrmException { if (input == null) { input = new Input(); } if (input.rule != null && !rules.isProjectRulesEnabled()) { throw new AuthException("project rules are disabled"); } input.filters = MoreObjects.firstNonNull(input.filters, filters); SubmitRuleEvaluator evaluator = new SubmitRuleEvaluator( changeDataFactory.create(db.get(), rsrc.getChange()), rsrc.getPatchSet()); List<SubmitRecord> records = evaluator.setLogErrors(false) .setSkipSubmitFilters(input.filters == Filters.SKIP) .setRule(input.rule) <START> .canSubmit(); <END> List<Record> out = Lists.newArrayListWithCapacity(records.size()); AccountInfo.Loader accounts = accountInfoFactory.create(true); for (SubmitRecord r : records) { out.add(new Record(r, accounts)); } accounts.fill(); return out; }</code><technical_language>Confusing name? call this evaluate()</technical_language>

Target:
public List<Record> apply(RevisionResource rsrc, Input input) throws AuthException, BadRequestException, OrmException { if (input == null) { input = new Input(); } if (input.rule != null && !rules.isProjectRulesEnabled()) { throw new AuthException("project rules are disabled"); } input.filters = MoreObjects.firstNonNull(input.filters, filters); SubmitRuleEvaluator evaluator = new SubmitRuleEvaluator( changeDataFactory.create(db.get(), rsrc.getControl())); List<SubmitRecord> records = evaluator.setPatchSet(rsrc.getPatchSet()) .setLogErrors(false) .setSkipSubmitFilters(input.filters == Filters.SKIP) .setRule(input.rule) .canSubmit(); List<Record> out = Lists.newArrayListWithCapacity(records.size()); AccountInfo.Loader accounts = accountInfoFactory.create(true); for (SubmitRecord r : records) { out.add(new Record(r, accounts)); } accounts.fill(); return out; }
Source:
<code>public FileReadResponse readWithResponse(OutputStream stream, FileRange range, DownloadRetryOptions options, DataLakeRequestConditions requestConditions, boolean getRangeContentMd5, Duration timeout, Context context) { try { <START> BlobDownloadResponse response = blockBlobClient.downloadWithResponse(stream, Transforms.toBlobRange(range), <END> Transforms.toBlobDownloadRetryOptions(options), Transforms.toBlobRequestConditions(requestConditions), getRangeContentMd5, timeout, context); return Transforms.toFileReadResponse(response); } catch (BlobStorageException ex) { throw logger.logExceptionAsError(DataLakeImplUtils.transformBlobStorageException(ex)); } }</code><technical_language>chance sync readWithResponse call async readWithResponse in a similar fashion Blobs handles sync download calling async download? try/catch convert exception need written everywhere</technical_language>

Target:
public FileReadResponse readWithResponse(OutputStream stream, FileRange range, DownloadRetryOptions options, DataLakeRequestConditions requestConditions, boolean getRangeContentMd5, Duration timeout, Context context) { return DataLakeImplUtils.returnOrConvertException(() -> { BlobDownloadResponse response = blockBlobClient.downloadWithResponse(stream, Transforms.toBlobRange(range), Transforms.toBlobDownloadRetryOptions(options), Transforms.toBlobRequestConditions(requestConditions), getRangeContentMd5, timeout, context); return Transforms.toFileReadResponse(response); }, logger); }
Source:
<code>public void updateSelectionAfterTrashAction() { if (DisplayUtils.isLargeScreenLandscape(getActivity())) { List<Integer> deletedNotesPositions = getSelectedNotesPositions(); int firstDeletedNote = deletedNotesPositions.get(0); int positionToSelect = -1; for (int i = firstDeletedNote + 1; i < mNotesAdapter.getCount(); i++) { if (!deletedNotesPositions.contains(i)) { positionToSelect = i; break; } } if (positionToSelect == -1) { for (int i = firstDeletedNote - 1; i >= 0; i--) { if (!deletedNotesPositions.contains(i)) { positionToSelect = i; break; } } } if (positionToSelect != -1) { Note noteToSelect = mNotesAdapter.getItem(positionToSelect + mList.getHeaderViewsCount()); mCallbacks.onNoteSelected(noteToSelect.getSimperiumKey(), null, noteToSelect.isMarkdownEnabled(), noteToSelect.isPreviewEnabled()); mSelectedNoteId = noteToSelect.getSimperiumKey(); } else { <START> if (getActivity() != null) { ((NotesActivity) requireActivity()).showDetailPlaceholder(); } <END> } } }</code><technical_language>suggestion ((NotesActivity) requireActivity()).showDetailPlaceholder(); Do need if (getActivity() != null) check requireActivity() throws IllegalStateException if getActivity() == null? I guess question is do want do throw IllegalStateException if getActivity() == null? If getActivity() == null, is wrong NoteListFragment. If do nothing, leave note content in editor hide is wrong NoteListFragment. If throw IllegalStateException, crash show is wrong NoteListFragment</technical_language>

Target:
public void updateSelectionAfterTrashAction() { if (DisplayUtils.isLargeScreenLandscape(getActivity())) { List<Integer> deletedNotesPositions = getSelectedNotesPositions(); int firstDeletedNote = deletedNotesPositions.get(0); int positionToSelect = -1; for (int i = firstDeletedNote + 1; i < mNotesAdapter.getCount(); i++) { if (!deletedNotesPositions.contains(i)) { positionToSelect = i; break; } } if (positionToSelect == -1) { for (int i = firstDeletedNote - 1; i >= 0; i--) { if (!deletedNotesPositions.contains(i)) { positionToSelect = i; break; } } } if (positionToSelect != -1) { Note noteToSelect = mNotesAdapter.getItem(positionToSelect + mList.getHeaderViewsCount()); mCallbacks.onNoteSelected(noteToSelect.getSimperiumKey(), null, noteToSelect.isMarkdownEnabled(), noteToSelect.isPreviewEnabled()); mSelectedNoteId = noteToSelect.getSimperiumKey(); } else { ((NotesActivity) requireActivity()).showDetailPlaceholder(); } } }
Source:
<code><START> public ProcessEngineConfiguration setDefaultNumberOfRetries(int defaultNumberOfRetries) { <END> this.defaultNumberOfRetries = defaultNumberOfRetries; return this; }</code><technical_language>100% sure, this breaks binary compatibility, right</technical_language>

Target:
public void setDefaultNumberOfRetries(int defaultNumberOfRetries) { this.defaultNumberOfRetries = defaultNumberOfRetries; }
Source:
<code>public byte[] serializeObject(Object object) throws IOException { <START> ByteArrayOutputStream bos = new ByteArrayOutputStream(); <END> ObjectOutput out = null; try { out = new ObjectOutputStream(bos); out.writeObject(object); byte[] byteArray = bos.toByteArray(); return byteArray; } catch (IOException e) { logger.error("Exception while trying serialize java object", e); throw e; } finally { try { if (out != null) { out.close(); } } catch (IOException ex) { logger.error("Exception while trying to close object output stream", ex); throw ex; } try { bos.close(); } catch (IOException ex) { logger.error("Exception while trying to close bytes output stream", ex); throw ex; } } }</code><technical_language>try/catch in here. Check out try-with-resources (Java 1.7+) Google Guava's [Closer](<LINK_0> A cleaner approach is a try/catch try/finally (closing resources) block. try/catch wrap checked exception a RedisException</technical_language>

Target:
public byte[] serializeObject(Object object) { try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)){ out.writeObject(object); byte[] byteArray = bos.toByteArray(); return byteArray; } catch (Exception e){ logger.error("Exception occurred while Java Object Serialization", e); throw new RedisException("Java Serialization Failed", e); } }
Source:
<code>public String getMessage(IResource[] resources) { <START> throw new RuntimeException(); <END> }</code><technical_language>This exception is logged. avoid confusion build console log, _must_ a message stating this exception thrown purpose</technical_language>

Target:
public String getMessage(IResource[] resources) { throw new IllegalStateException( "CrashingCommitMessageProvider fails on purpose."); }
Source:
<code>public Session getSessionCookie() { <START> return wrapped.getSession(); <END> }</code><technical_language>please leave - intentionally referencing deprecated version</technical_language>

Target:
public Session getSessionCookie() { return wrapped.getSessionCookie(); }
Source:
<code>private void doUpdate(boolean optional, String workspaceId, Consumer<WorkspaceActivity> updater) throws ServerException { try { EntityManager em = managerProvider.get(); WorkspaceActivity activity = em.find(WorkspaceActivity.class, workspaceId); if (activity == null) { if (optional) { return; } activity = new WorkspaceActivity(); activity.setWorkspaceId(workspaceId); updater.accept(activity); <START> em.persist(activity); <END> } else { updater.accept(activity); em.merge(activity); em.flush(); } } catch (RuntimeException x) { throw new ServerException(x.getLocalizedMessage(), x); } }</code><technical_language>Please add em.flush persisted data is consistent error transaction commit</technical_language>

Target:
private void doUpdate(boolean optional, String workspaceId, Consumer<WorkspaceActivity> updater) throws ServerException { try { EntityManager em = managerProvider.get(); WorkspaceActivity activity = em.find(WorkspaceActivity.class, workspaceId); if (activity == null) { if (optional) { return; } activity = new WorkspaceActivity(); activity.setWorkspaceId(workspaceId); updater.accept(activity); em.persist(activity); } else { updater.accept(activity); em.merge(activity); } em.flush(); } catch (RuntimeException x) { throw new ServerException(x.getLocalizedMessage(), x); } }
Source:
<code>protected String getDialogTitle() { <START> return Messages.getString("PasswordController.NewLicenseKey"); END> }</code><technical_language>"PasswordController.NewLicenseKey" ->"LicenseKeyController.NewLicenseKey" is</technical_language>

Target:
protected String getDialogTitle() { return Messages.getString("LicenseKeyController.NewLicenseKey"); }
Source:
<code>private static IFeaturesExtractor getExtractor(Node node) throws MalformedURLException, ClassNotFoundException, IllegalAccessException, InstantiationException { NodeList list = node.getChildNodes(); String classPath = null; String className = null; Map<String, String> parametrs = new HashMap<>(); for (int i = 0; i < list.getLength(); ++i) { Node child = list.item(i); if ("classPath".equals(child.getNodeName())) { classPath = child.getTextContent().trim(); } else if ("className".equals(child.getNodeName())) { className = child.getTextContent().trim(); } else if ("parameters".equals(child.getNodeName())) { getParametrs(parametrs, child); } } if (classPath == null || className == null) { return null; } File file = new File(classPath); URL url = file.toURI().toURL(); URL[] urls = new URL[]{url}; ClassLoader cl = new URLClassLoader(urls); Class cls = cl.loadClass(className); Object obj = cls.newInstance(); if (obj instanceof IFeaturesExtractor) { IFeaturesExtractor extractor = (IFeaturesExtractor) obj; <START> extractor.initialise(parametrs); <END> return extractor; } return null; }</code><technical_language>is initialize is verb initialise is noun</technical_language>

Target:
private static ExtractorStructure getExtractor(Node node) throws MalformedURLException, ClassNotFoundException, IllegalAccessException, InstantiationException { NodeList list = node.getChildNodes(); String classPath = null; String className = null; UUID id = null; Map<String, String> parametrs = new HashMap<>(); for (int i = 0; i < list.getLength(); ++i) { Node child = list.item(i); switch (child.getNodeName()) { case "classPath": classPath = child.getTextContent().trim(); break; case "className": className = child.getTextContent().trim(); break; case "parameters": getParametrs(parametrs, child); break; case "id": try { id = UUID.fromString(child.getTextContent().trim()); } catch (IllegalArgumentException e) { LOGGER.error("Attribute id of the plugin is not in UUID format", e); return null; } break; } } if (classPath == null || className == null || id == null) { LOGGER.error("Some of required nodes have not founded."); return null; } File file = new File(classPath); URL url = file.toURI().toURL(); URL[] urls = new URL[]{url}; ClassLoader cl = new URLClassLoader(urls); Class cls = cl.loadClass(className); Object obj = cls.newInstance(); if (obj instanceof IFeaturesExtractor) { IFeaturesExtractor extractor = (IFeaturesExtractor) obj; extractor.initialize(parametrs); return new ExtractorStructure(extractor, id); } return null; }
Source:
<code>public Resource decorate(final Resource resource) { try { if (!this.accepts(resource)) { return resource; } <START> } catch (final RepositoryException e) { <END> LOG.debug("Failed binary sync check for remote asset: {}", resource.getPath()); return resource; } boolean syncSuccessful = false; if (isAlreadySyncing(resource.getPath())) { syncSuccessful = waitForSyncInProgress(resource); } else { syncSuccessful = syncAssetBinaries(resource); } if (syncSuccessful) { LOG.trace("Refreshing resource after binary sync of {}", resource.getPath()); final ResourceResolver resourceResolver = resource.getResourceResolver(); resourceResolver.refresh(); return resourceResolver.getResource(resource.getPath()); } else { return resource; } }</code><technical_language>This purposely catching checked runtime exceptions, catch of Exception, if this a fundamental flaw causing a runtime exception conceivably kill sling resource fetches</technical_language>

Target:
public Resource decorate(final Resource resource) { try { if (!this.accepts(resource)) { return resource; } } catch (final Exception e) { LOG.debug("Failed binary sync check for remote asset: {}", resource.getPath()); return resource; } boolean syncSuccessful = false; if (isAlreadySyncing(resource.getPath())) { syncSuccessful = waitForSyncInProgress(resource); } else { syncSuccessful = syncAssetBinaries(resource); } if (syncSuccessful) { LOG.trace("Refreshing resource after binary sync of {}", resource.getPath()); final ResourceResolver resourceResolver = resource.getResourceResolver(); resourceResolver.refresh(); return resourceResolver.getResource(resource.getPath()); } else { return resource; } }
Source:
<code>static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) { Log.d(TAG, "updateAppWidget() appWidgetId=" + appWidgetId); long unreadCount = DbConnection.getSession().getArticleDao().queryBuilder(). <START> where(ArticleDao.Properties.Archive.eq(0)).count(); <END> Log.d(TAG, "updateAppWidget() read from database unreadCount=" + unreadCount); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.icon_unread); Log.d(TAG, "updateAppWidget() setting unread_count_text to " + unreadCount); if (unreadCount <= 0) { views.setViewVisibility(R.id.unread_count_text, View.GONE); } else { views.setViewVisibility(R.id.unread_count_text, View.VISIBLE); if (unreadCount > MAX_UNREAD_COUNT) { views.setTextViewText(R.id.unread_count_text, MAX_UNREAD_COUNT + "+"); } else { views.setTextViewText(R.id.unread_count_text, "" + unreadCount); } } Intent intent = new Intent(context, ArticlesListActivity.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, 0); views.setOnClickPendingIntent(R.id.icon_unread_layout, pendingIntent); appWidgetManager.updateAppWidget(appWidgetId, views); }</code><technical_language>false instead of 0 here</technical_language>

Target:
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) { Log.d(TAG, "updateAppWidget() appWidgetId=" + appWidgetId); long unreadCount = DbConnection.getSession().getArticleDao().queryBuilder(). where(ArticleDao.Properties.Archive.eq(false)).count(); Log.d(TAG, "updateAppWidget() read from database unreadCount=" + unreadCount); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.icon_unread); Log.d(TAG, "updateAppWidget() setting unread_count_text to " + unreadCount); if (unreadCount <= 0) { views.setViewVisibility(R.id.unread_count_text, View.GONE); } else { views.setViewVisibility(R.id.unread_count_text, View.VISIBLE); if (unreadCount > MAX_UNREAD_COUNT) { views.setTextViewText(R.id.unread_count_text, MAX_UNREAD_COUNT + "+"); } else { views.setTextViewText(R.id.unread_count_text, "" + unreadCount); } } Intent intent = new Intent(context, ArticlesListActivity.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, 0); views.setOnClickPendingIntent(R.id.icon_unread_layout, pendingIntent); appWidgetManager.updateAppWidget(appWidgetId, views); }
Source:
<code>public void setCreationDate(DocumentModel doc, Calendar creationDate) { <START> doc.setProperty(DUBLINCORE_SCHEMA_NAME, DUBLINCORE_CREATED_DATE, creationDate); <END> }</code><technical_language>2-arg doc.setPropertyValue instead of 3-arg doc.setProperty</technical_language>

Target:
public void setCreationDate(DocumentModel doc, Calendar creationDate) { doc.setPropertyValue(DUBLINCORE_CREATED_DATE_PROPERTY, creationDate); }
Source:
<code>private BytecodeBlock generateCheckYieldBlock(Variable thisVariable, Variable start, Variable index, FieldDefinition yieldSignal, FieldDefinition nextIndexOrPosition) { return new BytecodeBlock() .comment("if (System.nanoTime() - start > yieldCheckPeriodNanos)") .append(new IfStatement() <START> .condition(greaterThan(subtract(invokeStatic(System.class, "nanoTime", long.class), start), constantLong(yieldCheckPeriodNanos))) <END> .ifTrue(new BytecodeBlock() .comment("if (yieldSignal.isSet())") .append(new IfStatement() .condition(thisVariable.getField(yieldSignal).invoke("isSet", boolean.class)) .ifTrue(new BytecodeBlock() .comment("nextIndexOrPosition = index + 1;") .append(thisVariable.setField(nextIndexOrPosition, add(index, constantInt(1)))) .comment("return false;") .push(false) .retBoolean())))); }</code><technical_language>io.airlift.bytecode.expression.BytecodeExpressions#and</technical_language>

Target:
private BytecodeBlock generateCheckYieldBlock(Variable thisVariable, Variable start, Variable index, FieldDefinition yieldSignal, FieldDefinition nextIndexOrPosition) { BytecodeExpression shouldCheckYieldSignal = greaterThan(subtract(invokeStatic(System.class, "nanoTime", long.class), start), constantLong(yieldCheckPeriodNanos)); BytecodeExpression checkYieldSignal = thisVariable.getField(yieldSignal).invoke("isSet", boolean.class); return new BytecodeBlock() .comment("if (System.nanoTime() - start > yieldCheckPeriodNanos)") .append(new IfStatement() .condition(and(shouldCheckYieldSignal, checkYieldSignal)) .ifTrue(new BytecodeBlock() .comment("nextIndexOrPosition = index + 1;") .append(thisVariable.setField(nextIndexOrPosition, add(index, constantInt(1)))) .comment("return false;") .push(false) .retBoolean())); }
Source:
<code>private void generateActionHttpPost(Method method) { Name name = method.getName(); buffer.addLine("def %1$s(", pythonNames.getMemberStyleName(name)); buffer.startBlock(); buffer.addLine("self,"); method.parameters() .filter(Parameter::isIn) .sorted() .forEach(this::generateFormalParameter); buffer.endBlock(); buffer.addLine("):"); buffer.startBlock(); buffer.addLine("buf = io.BytesIO()"); buffer.addLine("writer = xml.XmlWriter(buf, indent=True)"); buffer.addLine("writer.write_start('action')"); method.parameters() .filter(Parameter::isIn) .sorted() .forEach(this::generateWriteActionParameter); buffer.addLine("writer.write_end()"); buffer.addLine("writer.flush()"); buffer.addLine("body = buf.getvalue()"); buffer.addLine("writer.close()"); buffer.addLine("buf.close()"); buffer.addLine("request = http.Request("); buffer.startBlock(); buffer.addLine("method='POST',"); buffer.addLine("path='%%s/%%s' %% (self._path, '%1$s'),", getPath(name)); buffer.addLine("body=body,"); buffer.endBlock(); buffer.addLine(")"); buffer.addLine("response = self._connection.send(request)"); buffer.addLine("if response.code in [200]:"); buffer.startBlock(); buffer.addLine("action = self._check_action(response)"); method.parameters() <START> .filter(x -> x.isOut()) <END> .findFirst() .ifPresent(this::generateActionResponse); buffer.endBlock(); buffer.addLine("else:"); buffer.startBlock(); buffer.addLine("self._check_fault(response)"); buffer.endBlock(); buffer.endBlock(); buffer.addLine(); }</code><technical_language>This kind of lambda expressions simplified a method reference: .filter(Parameter::isOut) I style in other parts of code, well</technical_language>

Target:
private void generateActionHttpPost(Method method) { Name name = method.getName(); buffer.addLine("def %1$s(", pythonNames.getMemberStyleName(name)); buffer.startBlock(); buffer.addLine("self,"); method.parameters() .filter(Parameter::isIn) .sorted() .forEach(this::generateFormalParameter); buffer.endBlock(); buffer.addLine("):"); buffer.startBlock(); buffer.addLine("buf = io.BytesIO()"); buffer.addLine("writer = xml.XmlWriter(buf, indent=True)"); buffer.addLine("writer.write_start('action')"); method.parameters() .filter(Parameter::isIn) .sorted() .forEach(this::generateWriteActionParameter); buffer.addLine("writer.write_end()"); buffer.addLine("writer.flush()"); buffer.addLine("body = buf.getvalue()"); buffer.addLine("writer.close()"); buffer.addLine("buf.close()"); buffer.addLine("request = http.Request("); buffer.startBlock(); buffer.addLine("method='POST',"); buffer.addLine("path='%%s/%%s' %% (self._path, '%1$s'),", getPath(name)); buffer.addLine("body=body,"); buffer.endBlock(); buffer.addLine(")"); buffer.addLine("response = self._connection.send(request)"); buffer.addLine("if response.code in [200]:"); buffer.startBlock(); buffer.addLine("action = self._check_action(response)"); method.parameters() .filter(Parameter::isOut) .findFirst() .ifPresent(this::generateActionResponse); buffer.endBlock(); buffer.addLine("else:"); buffer.startBlock(); buffer.addLine("self._check_fault(response)"); buffer.endBlock(); buffer.endBlock(); buffer.addLine(); }
Source:
<code>public void testOneDayDivide() { final Long accountId = 999L; final Long deviceId = 999L; final int light = 2; final int zeroLight = 0; final int offsetMillis = -28800000; final DateTime timestamp = DateTime.now(DateTimeZone.UTC).withHourOfDay(19).withMinuteOfHour(0); final int offMinuteThreshold = 45; final List<DeviceData> data = new ArrayList<>(); data.add(new DeviceData(accountId, deviceId, 0, 0, 0, 0, 0, 0, 0, light,light, 0, 0, timestamp, offsetMillis, 1, 1, 1, 0, 0, 0)); data.add(new DeviceData(accountId, deviceId, 0, 0, 0, 0, 0, 0, 0, zeroLight,zeroLight, 0, 0, timestamp.withMinuteOfHour(10), offsetMillis, 1, 1, 1, 0, 0, 0)); data.add(new DeviceData(accountId, deviceId, 0, 0, 0, 0, 0, 0, 0, zeroLight,zeroLight, 0, 0, timestamp.withMinuteOfHour(30), offsetMillis, 1, 1, 1, 0, 0, 0)); data.add(new DeviceData(accountId, deviceId, 0, 0, 0, 0, 0, 0, 0, zeroLight,zeroLight, 0, 0, timestamp.withMinuteOfHour(45), offsetMillis, 1, 1, 1, 0, 0, 0)); <START> data.add(new DeviceData(accountId, deviceId, 0, 0, 0, 0, 0, 0, 0, zeroLight,zeroLight, 0, 0, timestamp.withHourOfDay(21), offsetMillis, 1, 1, 1, 0, 0, 0)); <END> final Integer calculatedLightDurationList = BedLightDuration.findLightOnDurationForDay(data, offMinuteThreshold); final Integer expectedLightDurationList = light/4; assertThat(calculatedLightDurationList, is(expectedLightDurationList)); }</code><technical_language>suggest creating a private DeviceData withHourOfDay(int n) instead of copy pasting line</technical_language>

Target:
public void testOneDayDivide() { final int light = 2; final int zeroLight = 0; final DateTime timestamp = DateTime.now(DateTimeZone.UTC).withHourOfDay(19).withMinuteOfHour(0); final int offMinuteThreshold = 45; final List<DeviceData> data = Lists.newArrayList( createNewDeviceData(light, timestamp), createNewDeviceData(zeroLight, timestamp.withMinuteOfHour(10)), createNewDeviceData(zeroLight, timestamp.withMinuteOfHour(30)), createNewDeviceData(zeroLight, timestamp.withMinuteOfHour(45)), createNewDeviceData(zeroLight, timestamp.withHourOfDay(21)) ); final Integer calculatedLightDurationList = BedLightDuration.findLightOnDurationForDay(data, offMinuteThreshold); final Integer expectedLightDurationList = light/4; assertThat(calculatedLightDurationList, is(expectedLightDurationList)); }
Source:
<code>public void testFileSystemProperties() { String projectID = "projectID"; String jsonKey = "jsonKey"; String path = "path"; String schema = "schema"; String bucket = "bucket"; GCSAvroBatchSink.GCSAvroSinkConfig gcsAvroConfig = new GCSAvroBatchSink.GCSAvroSinkConfig("gcstest", bucket, schema, projectID, jsonKey, null, path); Map<String, String> fsProperties = GSON.fromJson(gcsAvroConfig.getFileSystemProperties(null, projectID, jsonKey), MAP_STRING_STRING_TYPE); Assert.assertNotNull(fsProperties); Assert.assertEquals(3, fsProperties.size()); Assert.assertEquals("gs://bucket/path", fsProperties.get(FileOutputFormat.OUTDIR) ); Assert.assertEquals(projectID, fsProperties.get("fs.gs.project.id")); <START> Assert.assertEquals(jsonKey, fsProperties.get("google.cloud.auth.service.account.json.keyfile")); <END> }</code><technical_language>Change all: jsonKey -> jsonKeyFile</technical_language>

Target:
public void testFileSystemProperties() { String projectId = "projectId"; String jsonKey = "jsonKey"; String path = "path"; String schema = "schema"; String bucket = "bucket"; GCSAvroBatchSink.GCSAvroSinkConfig gcsAvroConfig = new GCSAvroBatchSink.GCSAvroSinkConfig("gcstest", bucket, schema, projectId, jsonKey, null, path); Map<String, String> fsProperties = GSON.fromJson(gcsAvroConfig.getFileSystemProperties(null, projectId, jsonKey), MAP_STRING_STRING_TYPE); Assert.assertNotNull(fsProperties); Assert.assertEquals(5, fsProperties.size()); Assert.assertEquals("gs://bucket/path", fsProperties.get(FileOutputFormat.OUTDIR)); Assert.assertEquals(projectId, fsProperties.get("fs.gs.project.id")); Assert.assertEquals(jsonKey, fsProperties.get("google.cloud.auth.service.account.json.keyfile")); }
Source:
<code>public void testWithoutProxy() throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { keyStoreManager.createNew(f, KEYSTORE_PASSWORD.toCharArray()); final KeyStore ks = keyStoreManager.addCertificates(f, KEYSTORE_PASSWORD.toCharArray(), InetAddress.getLocalHost(), LDAPS_PORT); <START> assertThat(ks.size()).as("localhost should have three certificates in the chain").isEqualTo(1); <END> Map<String, Certificate> certs = keyStoreManager.listCertificates(f, KEYSTORE_PASSWORD.toCharArray()); for (final Map.Entry<String, Certificate> cert : certs.entrySet()) { System.out.println(cert.getKey() + " : " + ((X509Certificate)cert.getValue()).getSubjectDN()); } final String newPassword = "newpassword"; keyStoreManager.changePassword(f, KEYSTORE_PASSWORD.toCharArray(), newPassword.toCharArray()); keyStoreManager.removeCertificates(f, newPassword.toCharArray(), InetAddress.getLocalHost(), LDAPS_PORT); certs = keyStoreManager.listCertificates(f, newPassword.toCharArray()); assertThat(certs.size()).as("Expected empty certs.").isEqualTo(0); }</code><technical_language>assertThat(ks.size()).as("localhost certificates in chain").isEqualTo(1); => assertThat(ks).as("localhost certificates in chain").hasSize(1); please change .size() collections</technical_language>

Target:
public void testWithoutProxy() throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { keyStoreManager.createNew(f, KEYSTORE_PASSWORD.toCharArray()); final KeyStore ks = keyStoreManager.addCertificates(f, KEYSTORE_PASSWORD.toCharArray(), InetAddress.getLocalHost(), LDAPS_PORT); assertThat(ks.size()).as("localhost should have three certificates in the chain").isEqualTo(1); Map<String, Certificate> certs = keyStoreManager.listCertificates(f, KEYSTORE_PASSWORD.toCharArray()); for (final Map.Entry<String, Certificate> cert : certs.entrySet()) { System.out.println(cert.getKey() + " : " + ((X509Certificate)cert.getValue()).getSubjectDN()); } final String newPassword = "newpassword"; keyStoreManager.changePassword(f, KEYSTORE_PASSWORD.toCharArray(), newPassword.toCharArray()); keyStoreManager.removeCertificates(f, newPassword.toCharArray(), InetAddress.getLocalHost(), LDAPS_PORT); certs = keyStoreManager.listCertificates(f, newPassword.toCharArray()); assertThat(certs).as("Expected empty certs.").isEmpty(); }
Source:
<code>public static boolean isFormatCorrect(String blob) throws IOException { final Map<String, String> map = getEncryptionMap(blob); if (map.isEmpty()) { return false; <START> } <END> return ARTIFACT.equals(map.get(ARTIFACT_KEY)) && VERSION.equals(map.get(VERSION_KEY)); }</code><technical_language>needed test emptiness, contained in condition</technical_language>

Target:
public static boolean isFormatCorrect(String blob) throws IOException { final Map<String, String> map = getEncryptionMap(blob); return ARTIFACT.equals(map.get(ARTIFACT_KEY)) && VERSION.equals(map.get(VERSION_KEY)); }
Source:
<code>public Object get(String name) { <START> return getCurrentEntries().get( EvalHelper.normalizeVariableName( name ) ); <END> }</code><technical_language>If variable name is normalized set() method, is necessary normalize get() well</technical_language>

Target:
public Object get(String name) { return getCurrentEntries().get( name ); }
Source:
<code>public void runInControlledConcurrency(Runnable codeblock) { try { if (syncLock.isLocked()) <START> { <END> log.info("Waiting on other task to finish ({} additional threads are queued)", syncLock.getQueueLength()); } syncLock.lock(); codeblock.run(); } finally { syncLock.unlock(); } }</code><technical_language>if 'this' thread owns lock attempts acquire get wrong logging here. log is correct if lock is acquired other thread (use !isHeldByCurrentThread())</technical_language>

Target:
public void runInControlledConcurrency(Runnable codeblock) { try { if (!syncLock.isHeldByCurrentThread()) { log.info("Waiting on other task to finish ({} additional threads are queued)", syncLock.getQueueLength()); } syncLock.lock(); codeblock.run(); } finally { syncLock.unlock(); } }
Source:
<code>public int queryReplicationStatus() { <START> long maxTail = queryStreamTail(); if (maxTail > prepareSiteRoleChangeStreamTail) { prepareSiteRoleChange(); } long currentNumEntriesToSend = queryEntriesToSend(prepareSiteRoleChangeStreamTail); log.debug("maxTail totalNumEntriesToSend currentNumEntriesToSend {}", maxTail, totalNumEntriesToSend, currentNumEntriesToSend); <END> if (totalNumEntriesToSend == 0 || currentNumEntriesToSend == 0) return PERCENTAGE_BASE; int percent = (int)((totalNumEntriesToSend - currentNumEntriesToSend)*PERCENTAGE_BASE/totalNumEntriesToSend); if (percent == PERCENTAGE_BASE) { percent = PERCENTAGE_BASE - 1; } return percent; }</code><technical_language>if max stream tail moves, calls prepareSiteRoleChange(), call queryStreamTail() more time, update totalNumEntriesToSend. call queryEntriesToSend() again, get a pretty close result currentNumEntriesToSend. percent calculation return a 0</technical_language>

Target:
public int queryReplicationStatus() { long maxTail = queryStreamTail(); if (maxTail > prepareClusterRoleChangeLogTail) { prepareSiteRoleChange(); } long currentNumEntriesToSend = queryEntriesToSend(prepareClusterRoleChangeLogTail); log.debug("maxTail totalNumEntriesToSend currentNumEntriesToSend {}", maxTail, totalNumEntriesToSend, currentNumEntriesToSend); if (totalNumEntriesToSend == 0 || currentNumEntriesToSend == 0) return PERCENTAGE_BASE; int percent = (int)((totalNumEntriesToSend - currentNumEntriesToSend)*PERCENTAGE_BASE/totalNumEntriesToSend); if (percent == PERCENTAGE_BASE) { percent = PERCENTAGE_BASE - 1; } return percent; }
Source:
<code>public RouterConfig(JsonNode node, String source, boolean logUnusedParams) { NodeAdapter adapter = new NodeAdapter(node, source); this.rawJson = node; this.requestLogFile = adapter.asText("requestLogFile", null); this.streetRoutingTimeoutSeconds = adapter.asDouble( "streetRoutingTimeout", DEFAULT_STREET_ROUTING_TIMEOUT ); <START> this.bikeShareUpdaterEndpoint = adapter.asText( "bikeShareUpdaterEndpoint", null ); <END> this.transitConfig = new TransitRoutingConfig(adapter.path("transit")); this.routingRequestDefaults = mapRoutingRequest(adapter.path("routingDefaults")); this.updaterConfig = new UpdaterConfig(adapter.path("updaters")); if(logUnusedParams) { adapter.logAllUnusedParameters(LOG); } }</code><technical_language>asURI(...)</technical_language>

Target:
public RouterConfig(JsonNode node, String source, boolean logUnusedParams) { NodeAdapter adapter = new NodeAdapter(node, source); this.rawJson = node; this.requestLogFile = adapter.asText("requestLogFile", null); this.streetRoutingTimeoutSeconds = adapter.asDouble( "streetRoutingTimeout", DEFAULT_STREET_ROUTING_TIMEOUT ); this.bikeRentalServiceDirectoryUrl = adapter.asUri( "bikeRentalServiceDirectoryUrl", null ); this.transitConfig = new TransitRoutingConfig(adapter.path("transit")); this.routingRequestDefaults = mapRoutingRequest(adapter.path("routingDefaults")); this.updaterConfig = new UpdaterConfig(adapter.path("updaters")); if(logUnusedParams) { adapter.logAllUnusedParameters(LOG); } }
Source:
<code><START> private void apply( Iterable<IndexEntryUpdate<LabelSchemaDescriptor>> updates, IndexUpdateMode updateMode ) <END> throws IOException, IndexEntryConflictException { Map<LabelSchemaDescriptor,List<IndexEntryUpdate<LabelSchemaDescriptor>>> bySchema = new HashMap<>(); for ( IndexEntryUpdate<LabelSchemaDescriptor> indexUpdate : updates ) { List<IndexEntryUpdate<LabelSchemaDescriptor>> forSchema = bySchema.get( indexUpdate.indexKey() ); if ( forSchema == null ) { forSchema = new ArrayList<>(); bySchema.put( indexUpdate.indexKey(), forSchema ); } forSchema.add( indexUpdate ); } for ( Map.Entry<LabelSchemaDescriptor, List<IndexEntryUpdate<LabelSchemaDescriptor>>> entry : bySchema.entrySet() ) { LabelSchemaDescriptor schema = entry.getKey(); try ( IndexUpdater updater = indexMapRef.getIndexProxy( schema ).newUpdater( updateMode ) ) { for ( IndexEntryUpdate<LabelSchemaDescriptor> indexUpdate : entry.getValue() ) { updater.process( indexUpdate ); } } catch ( IndexNotFoundKernelException e ) { } } }</code><technical_language>WDYT apply that: private void apply( Iterable<IndexEntryUpdate<LabelSchemaDescriptor>> updates, IndexUpdateMode updateMode ) throws IOException, IndexEntryConflictException { Map<LabelSchemaDescriptor, IndexUpdater> indexUpdaters = new HashMap<>(); for ( IndexEntryUpdate<LabelSchemaDescriptor> indexUpdate : updates ) { IndexUpdater indexUpdater = indexUpdaters.computeIfAbsent( indexUpdate.indexKey(), getMappingFunction( updateMode ) ); indexUpdater.process( indexUpdate ); } IOUtils.closeAll( indexUpdaters.values() ); } private Function<LabelSchemaDescriptor,IndexUpdater> getMappingFunction( IndexUpdateMode updateMode ) { return labelSchemaDescriptor -> { try { return indexMapRef.getIndexProxy( labelSchemaDescriptor ).newUpdater( updateMode ); } catch ( IndexNotFoundKernelException infe ) { throw new RuntimeException( infe ); } }; } saves a bit of cycles iteration updates</technical_language>

Target:
private void apply( Iterable<IndexEntryUpdate<LabelSchemaDescriptor>> updates, IndexUpdateMode updateMode ) throws IOException, IndexEntryConflictException { try ( IndexUpdaterMap updaterMap = indexMapRef.createIndexUpdaterMap( updateMode ) ) { for ( IndexEntryUpdate<LabelSchemaDescriptor> indexUpdate : updates ) { IndexUpdater updater = updaterMap.getUpdater( indexUpdate.indexKey().schema() ); if ( updater != null ) { updater.process( indexUpdate ); } } } }
Source:
<code>private CallNotPermittedException(CircuitBreaker circuitBreaker, String message, boolean writableStackTrace) { super(message, null, false, writableStackTrace); <START> this.circuitBreaker = circuitBreaker; <END> }</code><technical_language>if a reference in exception CircuitBreaker instance. I prefer if add name CallNotPermittedException a field</technical_language>

Target:
private CallNotPermittedException(CircuitBreaker circuitBreaker, String message, boolean writableStackTrace) { super(message, null, false, writableStackTrace); this.causingCircuitBreakerName = circuitBreaker.getName(); }
Source:
<code>public void cleanUp(boolean ok, Exception e) { super.cleanUp(ok, e); if (ok) { return; } List<Blob> blobs = new ArrayList<Blob>(); Blob emptyBlob = new AsyncBlob(key); <START> blobs.add(emptyBlob); <END> TransientStore ts = getTransientStore(); ts.putParameter(key, DownloadService.ERROR, e); updateAndCompleteStoreEntry(blobs); }</code><technical_language>List<Blob> blobs = Collections.singletonList(new AsyncBlob(key))</technical_language>

Target:
public void cleanUp(boolean ok, Exception e) { super.cleanUp(ok, e); if (ok) { return; } List<Blob> blobs = Collections.singletonList(new AsyncBlob(key)); TransientStore ts = getTransientStore(); ts.putParameter(key, DownloadService.TRANSIENT_STORE_PARAM_ERROR, e.getMessage()); updateAndCompleteStoreEntry(blobs); }