auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean moveItemToSlotsFillClientTempEntities(EntityRef instigator, EntityRef fromInventory, int slotFrom, EntityRef toInventory, List<Integer> toSlots, Collection<EntityRef> clientTempEntities) { Set<Integer> emptySlotsBefore = toSlots.stream().filter(toSlot -> !InventoryUtils.getItemAt(toInventory, toSlot).exists()).collect(Collectors.toSet()); if (!InventoryUtils.moveItemToSlots(instigator, fromInventory, slotFrom, toInventory, toSlots)) { return true; } for (Integer slot : emptySlotsBefore) { EntityRef itemAt = InventoryUtils.getItemAt(toInventory, slot); if (itemAt.exists()) { clientTempEntities.add(itemAt); } } return false; }

Target:
private boolean moveItemToSlotsFillClientTempEntities(EntityRef instigator, EntityRef fromInventory, int slotFrom, EntityRef toInventory, List<Integer> toSlots, Collection<EntityRef> clientTempEntities) { Set<Integer> emptySlotsBefore = new HashSet<>(); for (Integer toSlot : toSlots) { if (!InventoryUtils.getItemAt(toInventory, toSlot).exists()) { emptySlotsBefore.add(toSlot); } } if (!InventoryUtils.moveItemToSlots(instigator, fromInventory, slotFrom, toInventory, toSlots)) { return true; } for (Integer slot : emptySlotsBefore) { EntityRef itemAt = InventoryUtils.getItemAt(toInventory, slot); if (itemAt.exists()) { clientTempEntities.add(itemAt); } } return false; }
Source:
protected void executeCommand() { if (getTagId() != null) { for (Guid templateGuid : getTemplatesList()) { VmTemplate template = DbFacade.getInstance().getVmTemplateDao().get(templateGuid); if (DbFacade.getInstance().getTagDao().getTagTemplateByTagIdAndByTemplateId(getTagId(), templateGuid) == null) { if (template != null) { appendCustomValue("TemplatesNames", template.getName(), ", "); } TagsTemplateMap map = new TagsTemplateMap(getTagId(), templateGuid); DbFacade.getInstance().getTagDao().attachTemplateToTag(map); noActionDone = false; } else { if (template != null) { appendCustomValue("TemplatesNamesExists", template.getName(), ", "); } } } } setSucceeded(true); }

Target:
protected void executeCommand() { for (Guid templateGuid : getTemplatesList()) { VmTemplate template = DbFacade.getInstance().getVmTemplateDao().get(templateGuid); if (DbFacade.getInstance().getTagDao().getTagTemplateByTagIdAndByTemplateId(getTagId(), templateGuid) == null) { if (template != null) { appendCustomValue("TemplatesNames", template.getName(), ", "); TagsTemplateMap map = new TagsTemplateMap(getTagId(), templateGuid); DbFacade.getInstance().getTagDao().attachTemplateToTag(map); noActionDone = false; } } else { if (template != null) { appendCustomValue("TemplatesNamesExists", template.getName(), ", "); } } } setSucceeded(true); }
Source:
public boolean post(String topic, Object data) { Event event = constructEvent(topic, data); EventAdmin eventAdmin = Activator.getDefault().getEventAdmin(); if (eventAdmin == null && logger != null) { logger.error(NLS.bind(ServiceMessages.NO_EVENT_ADMIN, event.toString())); return false; } eventAdmin.postEvent(event); return true; }

Target:
public boolean post(String topic, Object data) { Event event = constructEvent(topic, data); EventAdmin eventAdmin = Activator.getDefault().getEventAdmin(); if (eventAdmin == null) { if (logger != null) { logger.error(NLS.bind(ServiceMessages.NO_EVENT_ADMIN, event.toString())); } return false; } eventAdmin.postEvent(event); return true; }
Source:
public void resourceChanged(IResourceChangeEvent event) { try { event.getDelta().accept(new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) throws CoreException { if (!doAutoShare()) return false; if (delta.getKind() == IResourceDelta.CHANGED && (delta.getFlags() & INTERESTING_CHANGES) == 0) return true; final IResource resource = delta.getResource(); if (!resource.exists()) return false; if (resource.getType() != IResource.PROJECT) return true; if (Team.isIgnoredHint(resource)) return false; if (RepositoryMapping.getMapping(resource) != null) return false; final IProject project = (IProject) resource; RepositoryProvider provider = RepositoryProvider .getProvider(project); if (provider != null) return false; RepositoryFinder f = new RepositoryFinder(project); Collection<RepositoryMapping> mappings = f.find(new NullProgressMonitor()); try { if (mappings.size() == 1) { RepositoryMapping m = mappings.iterator() .next(); final File repositoryDir = m .getGitDirAbsolutePath().toFile(); final ConnectProviderOperation op = new ConnectProviderOperation( project, repositoryDir); JobUtil.scheduleUserJob(op, CoreText.Activator_AutoShareJobName, JobFamilies.AUTO_SHARE); Activator.getDefault().getRepositoryUtil() .addConfiguredRepository(repositoryDir); } } catch (Throwable e) { if (e instanceof InvocationTargetException) { e = e.getCause(); } if (e instanceof CoreException) { IStatus status = ((CoreException) e) .getStatus(); e = status.getException(); } logError(CoreText.Activator_AutoSharingFailed, e); } return false; } }); } catch (CoreException e) { Activator.logError(e.getMessage(), e); return; } }

Target:
public void resourceChanged(IResourceChangeEvent event) { try { event.getDelta().accept(new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) throws CoreException { if (!doAutoShare()) return false; if (delta.getKind() == IResourceDelta.CHANGED && (delta.getFlags() & INTERESTING_CHANGES) == 0) return true; final IResource resource = delta.getResource(); if (!resource.exists()) return false; if (resource.getType() != IResource.PROJECT) return true; if (Team.isIgnoredHint(resource)) return false; if (RepositoryMapping.getMapping(resource) != null) return false; final IProject project = (IProject) resource; RepositoryProvider provider = RepositoryProvider .getProvider(project); if (provider != null) return false; RepositoryFinder f = new RepositoryFinder(project); Collection<RepositoryMapping> mappings = f.find(new NullProgressMonitor()); try { if (mappings.size() == 1) { RepositoryMapping m = mappings.iterator() .next(); final File repositoryDir = m .getGitDirAbsolutePath().toFile(); final ConnectProviderOperation op = new ConnectProviderOperation( project, repositoryDir); JobUtil.scheduleUserJob(op, CoreText.Activator_AutoShareJobName, JobFamilies.AUTO_SHARE); Activator.getDefault().getRepositoryUtil() .addConfiguredRepository(repositoryDir); } } catch (IllegalArgumentException e) { logError(CoreText.Activator_AutoSharingFailed, e); } return false; } }); } catch (CoreException e) { Activator.logError(e.getMessage(), e); return; } }
Source:
public static <T extends Enum<?>> void parseEnumValueList(Class<T> c, List<T> list, String value, char... separators) { EwsUtilities.EwsAssert(c.isEnum(), "EwsUtilities.ParseEnumValueList", "T is not an enum type."); StringBuilder regexp = new StringBuilder(""); regexp.append("["); for (char s : separators) { regexp.append("["); regexp.append(Pattern.quote(s + "")); regexp.append("]"); } regexp.append("]"); String[] enumValues = value.split(regexp.toString()); for (String enumValue : enumValues) { for (T o : c.getEnumConstants()) { if (o.toString().equals(enumValue)) { list.add(o); } } } }

Target:
public static <T extends Enum<?>> void parseEnumValueList(Class<T> c, List<T> list, String value, char... separators) { EwsUtilities.EwsAssert(c.isEnum(), "EwsUtilities.ParseEnumValueList", "T is not an enum type."); StringBuilder regexp = new StringBuilder(); regexp.append("["); for (char s : separators) { regexp.append("["); regexp.append(Pattern.quote(s + "")); regexp.append("]"); } regexp.append("]"); String[] enumValues = value.split(regexp.toString()); for (String enumValue : enumValues) { for (T o : c.getEnumConstants()) { if (o.toString().equals(enumValue)) { list.add(o); } } } }
Source:
public String getForkNodeConnectionString() { return "tcp://" + localHost + ":" + localPort + ( sessionId == null ? "" : "?sessionId=" + sessionId ); }

Target:
public String getForkNodeConnectionString() { return "tcp://" + localHost + ":" + localPort + "?sessionId=" + sessionId; }
Source:
public List<String> getResourceFileList() { if (dirFileList == null) { String[] files = null; if (isDir() && getResourcePath().length() > 1) { files = getResourceFile().list(); } if (files == null) { dirFileList = Collections.emptyList(); } else { Arrays.sort(files, String.CASE_INSENSITIVE_ORDER); List<String> list = Arrays.asList(files); if (getPath().isEmpty()) { list = new ArrayList<>(list); list.removeIf((t) -> { return !getProjectHelper().getAllProjects().stream().anyMatch((p) -> { return p.getName().equalsIgnoreCase(t); }); }); } dirFileList = Collections.unmodifiableList(list); } } return dirFileList; }

Target:
public List<String> getResourceFileList() { if (dirFileList == null) { String[] files = null; if (isDir() && getResourcePath().length() > 1) { files = getResourceFile().list(); } if (files == null) { dirFileList = Collections.emptyList(); } else { Arrays.sort(files, String.CASE_INSENSITIVE_ORDER); List<String> listOfFiles = Arrays.asList(files); if (env.hasProjects() && getPath().isEmpty()) { List<String> modifiableListOfFiles = new ArrayList<>(listOfFiles); modifiableListOfFiles.removeIf((t) -> { return !getProjectHelper().getAllProjects().stream().anyMatch((p) -> { return p.getName().equalsIgnoreCase(t); }); }); return dirFileList = Collections.unmodifiableList(modifiableListOfFiles); } dirFileList = Collections.unmodifiableList(listOfFiles); } } return dirFileList; }
Source:
public void testUnmarshallTopLevelEventWithEdgesEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateMessageEventCatching emptyEvent = getCatchingIntermediateNodeById(diagram, EMPTY_WITH_OUTGOING_EDGE_TOP_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_OUTGOING_EDGE); assertGeneralSet(emptyEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertMessageEventExecutionSet(emptyEvent.getExecutionSet(), EMPTY_VALUE, NON_CANCELLING, ""); assertDataIOSet(emptyEvent.getDataIOSet(), EMPTY_VALUE); }

Target:
public void testUnmarshallTopLevelEventWithEdgesEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateMessageEventCatching emptyEvent = getCatchingIntermediateNodeById(diagram, EMPTY_WITH_OUTGOING_EDGE_TOP_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_OUTGOING_EDGE); assertGeneralSet(emptyEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertMessageEventExecutionSet(emptyEvent.getExecutionSet(), EMPTY_VALUE, NON_CANCELLING, EMPTY_VALUE); assertDataIOSet(emptyEvent.getDataIOSet(), EMPTY_VALUE); }
Source:
public void getExtension__OnUnknownType_ReturnsUnknown() { Embedding embedding = new Embedding("js", "", null); String extension = embedding.getExtension(); assertThat(extension).isEqualTo("unknown"); }

Target:
public void getExtension__OnUnknownType_ReturnsUnknown() { Embedding embedding = new Embedding("js", ""); String extension = embedding.getExtension(); assertThat(extension).isEqualTo("unknown"); }
Source:
public void testBadRequest() throws IOException { int port = server.getPort(); String msg = "GET /status HTTP/1.1\n\n"; InetSocketAddress sockAddr = new InetSocketAddress("127.0.0.1", port); Socket sock = new Socket(); sock.connect(sockAddr); OutputStream out = sock.getOutputStream(); out.write(msg.getBytes(StandardCharsets.UTF_8)); out.flush(); byte[] buf = new byte[2048]; int bytesRead = sock.getInputStream().read(buf); Assert.assertTrue("Connection should have been closed", bytesRead == -1); sock.close(); }

Target:
public void testBadRequest() throws IOException { int port = server.getPort(); String msg = "GET /status HTTP/1.1\n\n"; InetSocketAddress sockAddr = new InetSocketAddress("127.0.0.1", port); try (Socket sock = new Socket()) { sock.connect(sockAddr); OutputStream out = sock.getOutputStream(); out.write(msg.getBytes(StandardCharsets.UTF_8)); out.flush(); byte[] buf = new byte[2048]; int bytesRead = sock.getInputStream().read(buf); Assert.assertTrue("Connection should have been closed", bytesRead == -1); } }
Source:
private static int toPublic(int access) { return access & ~(Opcodes.ACC_PRIVATE + Opcodes.ACC_PROTECTED) | Opcodes.ACC_PUBLIC; }

Target:
private static int toPublic(int access) { return access & ~(Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED) | Opcodes.ACC_PUBLIC; }
Source:
public void beforeTestMethod(TestContext testContext) throws Exception { Authentication authentication = TestSecurityContextHolder.getContext().getAuthentication(); Hooks.onLastOperator(Operators.lift((s, sub) -> new SecuritySubContext<>(sub, authentication))); }

Target:
public void beforeTestMethod(TestContext testContext) throws Exception { SecurityContext securityContext = TestSecurityContextHolder.getContext(); Hooks.onLastOperator(Operators.lift((s, sub) -> new SecuritySubContext<>(sub, securityContext))); }
Source:
public ResponseEntity putDictionary(@PathVariable("tenant") final String tenant, @PathVariable("name") final String name, @RequestBody final DictionaryModel dictionaryModel) { final TenantContext context = _contextFactory.getContext(tenant); final FileResource resource = new FileResource(getResourceFile(context, name)); resource.write( stream -> stream.write((Joiner.on("\n").join(dictionaryModel.getEntries()) + "\n").getBytes("UTF-8"))); final TextFileDictionary dictionary = new TextFileDictionary(name, resource.getFile().getAbsolutePath(), "UTF-8", dictionaryModel.isCaseSensitive()); _referenceDataDao.removeDictionary(context, name); _referenceDataDao.addDictionary(context, dictionary); return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri()).build(); }

Target:
public ResponseEntity<Void> putDictionary(@PathVariable("tenant") final String tenant, @PathVariable("name") final String name, @RequestBody final DictionaryModel dictionaryModel) { final TenantContext context = _contextFactory.getContext(tenant); final FileResource resource = new FileResource(getResourceFile(context, name)); resource.write( stream -> stream.write((Joiner.on("\n").join(dictionaryModel.getEntries()) + "\n").getBytes("UTF-8"))); final TextFileDictionary dictionary = new TextFileDictionary(name, resource.getFile().getAbsolutePath(), "UTF-8", dictionaryModel.isCaseSensitive()); _referenceDataDao.removeDictionary(context, name); _referenceDataDao.addDictionary(context, dictionary); return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri()).build(); }
Source:
public MembershipExpirationInDays(Member member, int daysToExpiration, Vo vo) { this.member = member; this.daysToExpiration = daysToExpiration; this.vo = vo; this.message = formatMessage("%s will expire in %s days in %d.", member, vo, daysToExpiration); }

Target:
public MembershipExpirationInDays(Member member, int daysToExpiration, Vo vo) { this.member = member; this.daysToExpiration = daysToExpiration; this.vo = vo; this.message = formatMessage("%s will expire in %d days in %s.", member, daysToExpiration, vo); }
Source:
public void testIscsiLogin() throws Exception { setUriInfo(setUpActionExpectations(VdcActionType.ConnectStorageToVds, StorageServerConnectionParametersBase.class, new String[] { "VdsId", "StorageServerConnection.connection", "StorageServerConnection.portal", "StorageServerConnection.iqn", "StorageServerConnection.port", "StorageServerConnection.storage_type", "StorageServerConnection.user_name", "StorageServerConnection.password" }, new Object[] { GUIDS[0], ISCSI_SERVER_ADDRESS, "1", ISCSI_IQN, ISCSI_PORT_STRING, ISCSI_STORAGE_TYPE, ISCSI_USER_NAME, ISCSI_USER_PASS })); Action action = new Action(); IscsiDetails iscsiDetails = new IscsiDetails(); iscsiDetails.setAddress(ISCSI_SERVER_ADDRESS); iscsiDetails.setPort(ISCSI_PORT_INT); iscsiDetails.setTarget(ISCSI_IQN); iscsiDetails.setUsername(ISCSI_USER_NAME); iscsiDetails.setPassword(ISCSI_USER_PASS); action.setIscsi(iscsiDetails); verifyActionResponse(resource.iscsiLogin(action)); }

Target:
public void testIscsiLogin() throws Exception { setUriInfo(setUpActionExpectations(VdcActionType.ConnectStorageToVds, StorageServerConnectionParametersBase.class, new String[] { "VdsId", "StorageServerConnection.connection", "StorageServerConnection.portal", "StorageServerConnection.iqn", "StorageServerConnection.port", "StorageServerConnection.storage_type", "StorageServerConnection.user_name", "StorageServerConnection.password" }, new Object[] { GUIDS[0], ISCSI_SERVER_ADDRESS, StorageServerConnections.DEFAULT_TPGT, ISCSI_IQN, ISCSI_PORT_STRING, ISCSI_STORAGE_TYPE, ISCSI_USER_NAME, ISCSI_USER_PASS })); Action action = new Action(); IscsiDetails iscsiDetails = new IscsiDetails(); iscsiDetails.setAddress(ISCSI_SERVER_ADDRESS); iscsiDetails.setPort(ISCSI_PORT_INT); iscsiDetails.setTarget(ISCSI_IQN); iscsiDetails.setUsername(ISCSI_USER_NAME); iscsiDetails.setPassword(ISCSI_USER_PASS); action.setIscsi(iscsiDetails); verifyActionResponse(resource.iscsiLogin(action)); }
Source:
public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = View.inflate(getContext(), R.layout.list_contributor_item, null); ViewHolder viewHolder = new ViewHolder(convertView); convertView.setTag(viewHolder); } Contributor contributor = getItem(position); ViewHolder viewHolder = (ViewHolder) convertView.getTag(); viewHolder.contributorName.setText(contributor.getLogin()); if (!TextUtils.isEmpty(contributor.getAvatarUrl())) { App.getInstance().getPicasso() .load(contributor.getAvatarUrl()) .into(viewHolder.contributorAvatar); } return convertView; }

Target:
public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mLayoutInflator.inflate(R.layout.list_contributor_item, parent, false); ViewHolder viewHolder = new ViewHolder(convertView); convertView.setTag(viewHolder); } Contributor contributor = getItem(position); ViewHolder viewHolder = (ViewHolder) convertView.getTag(); viewHolder.contributorName.setText(contributor.getLogin()); if (!TextUtils.isEmpty(contributor.getAvatarUrl())) { App.getInstance().getPicasso() .load(contributor.getAvatarUrl()) .into(viewHolder.contributorAvatar); } return convertView; }
Source:
protected void applyCenterInside(@NonNull TextureView view) { if(intrinsicVideoSize.y <= view.getWidth() && intrinsicVideoSize.x <= view.getHeight()) { applyCenter(view); } else { applyFitCenter(view); } }

Target:
protected void applyCenterInside(@NonNull TextureView view) { if(intrinsicVideoSize.x <= view.getWidth() && intrinsicVideoSize.y <= view.getHeight()) { applyCenter(view); } else { applyFitCenter(view); } }
Source:
public AuthEntry(Info info, Type... types) { Set<Type> typeSet = Sets.newHashSet(); for (Type type : types) { typeSet.add(type); } this.info = info; this.typeSet = ImmutableSet.copyOf(typeSet); }

Target:
public AuthEntry(Info info, Type... types) { List<String> temp = Lists.newArrayList(); for (Type type : types) { temp.add(type.name()); } this.info = info; this.types = ImmutableSet.copyOf(types); this.stringTypes = ImmutableSet.copyOf(temp); }
Source:
private ServerPing getPingInfo( String motd, int protocol ) { new ServerPing( new ServerPing.Protocol( bungee.getName() + " " + bungee.getGameVersion(), protocol ), new ServerPing.Players( listener.getMaxPlayers(), bungee.getOnlineCount(), null ), motd, BungeeCord.getInstance().config.getFaviconObject() ); }

Target:
private ServerPing getPingInfo(String motd, int protocol) { return new ServerPing( new ServerPing.Protocol( bungee.getName() + " " + bungee.getGameVersion(), protocol ), new ServerPing.Players( listener.getMaxPlayers(), bungee.getOnlineCount(), null ), motd, BungeeCord.getInstance().config.getFaviconObject() ); }
Source:
public DefaultThriftService(PrestoThriftService prestoThriftService, HostLocationHandle hostLocationHandle) { requireNonNull(hostLocationHandle, "hostLocationHandle is null"); requireNonNull(prestoThriftService, "prestoThriftService is null"); this.hostLocationHandle = hostLocationHandle; this.prestoThriftService = prestoThriftService; }

Target:
public DefaultThriftService(PrestoThriftService prestoThriftService, HostLocationHandle hostLocationHandle) { this.prestoThriftService = requireNonNull(prestoThriftService, "prestoThriftService is null"); this.hostLocationHandle = requireNonNull(hostLocationHandle, "hostLocationHandle is null"); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AdHocActivationCondition that = (AdHocActivationCondition) o; return Objects.equals(value, that.value); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o instanceof AdHocActivationCondition) { AdHocActivationCondition that = (AdHocActivationCondition) o; return Objects.equals(value, that.value); } return false; }
Source:
public int processLocator(int rollCount, RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter, Locator locator) { if (log.isTraceEnabled()) log.trace("Rolling up (check,metric,dimension) for (gran,slot,shard) {}", locator, parentSlotKey); try { executeRollupForLocator(executionContext, rollupBatchWriter, locator); rollCount += 1; } catch (Throwable any) { executionContext.markUnsuccessful(any); executionContext.decrementReadCounter(); log.error(any.getMessage(), any); log.error("BasicRollup failed for at {}", parentSlotKey, serverTime); } return rollCount; }

Target:
protected int processLocator(int rollCount, RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter, Locator locator) { if (log.isTraceEnabled()) log.trace("Rolling up (check,metric,dimension) for (gran,slot,shard) {}", locator, parentSlotKey); try { executeRollupForLocator(executionContext, rollupBatchWriter, locator); rollCount += 1; } catch (Throwable any) { executionContext.markUnsuccessful(any); executionContext.decrementReadCounter(); log.error(any.getMessage(), any); log.error("BasicRollup failed for at {}", parentSlotKey, serverTime); } return rollCount; }
Source:
public SpeechToTextManager(Context context, Listener listener) { this.listener = listener; speechRecognizer = SpeechRecognizer.createSpeechRecognizer(context); speechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH); speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en"); speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true); speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.getPackageName()); speechRecognizer.setRecognitionListener(this); dialog = new MaterialDialog.Builder(context) .customView(R.layout.voice_recognizble_layout, false) .build(); ButterKnife.bind(this, dialog); }

Target:
public SpeechToTextManager(Context context, Listener listener) { this.listener = listener; speechRecognizer = SpeechRecognizer.createSpeechRecognizer(context); speechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault().getLanguage()); speechRecognizer.setRecognitionListener(this); dialog = new MaterialDialog.Builder(context) .customView(R.layout.voice_recognizble_layout, false) .build(); dialog.getWindow().getAttributes().windowAnimations = R.style.speech_dialog_animation; ButterKnife.bind(this, dialog); }
Source:
public final ImageWorker ignoreColorMap() throws IOException { if (image == null) { throw new IOException("image is null"); } final ColorModel cm = image.getColorModel(); if (cm == null) { throw new IOException("image has null color model"); } SampleModel sm = image.getSampleModel(); if (sm == null) { throw new IOException("image has null sample model"); } if (cm instanceof IndexColorModel) { RenderingHints newHints = getRenderingHints(); ImageLayout layout = (ImageLayout) newHints.get(JAI.KEY_IMAGE_LAYOUT); if (layout == null) layout = new ImageLayout2(); final ColorModel newCm = new ComponentColorModel( ColorSpace.getInstance(ColorSpace.CS_GRAY), cm.hasAlpha(), cm.isAlphaPremultiplied(), cm.getTransparency(), cm.getTransferType()); layout.setColorModel(newCm); newHints.put(JAI.KEY_IMAGE_LAYOUT, layout); image = FormatDescriptor.create(image, sm.getDataType(), newHints); } return this; }

Target:
public final ImageWorker ignoreColorMap() throws IOException { if (image == null) { throw new IOException("image is null"); } final ColorModel cm = image.getColorModel(); if (cm == null) { throw new IOException("image has null color model"); } final SampleModel sm = image.getSampleModel(); if (sm == null) { throw new IOException("image has null sample model"); } if (cm instanceof IndexColorModel) { final RenderingHints newHints = getRenderingHints(); final ImageLayout layout = new ImageLayout2(); final ColorModel newCm = new ComponentColorModel( ColorSpace.getInstance(ColorSpace.CS_GRAY), false, false, Transparency.OPAQUE, cm.getTransferType()); layout.setColorModel(newCm); newHints.put(JAI.KEY_IMAGE_LAYOUT, layout); image = FormatDescriptor.create(image, sm.getDataType(), newHints); } return this; }
Source:
PermissionManager(final SyncUser user) { this.user = user; threadId = Thread.currentThread().getId(); managementRealmConfig = new SyncConfiguration.Builder( user, getRealmUrl(RealmType.MANAGEMENT_REALM, user.getAuthenticationUrl())) .errorHandler(new SyncSession.ErrorHandler() { @Override public void onError(SyncSession session, ObjectServerError error) { synchronized (errorLock) { managementRealmError = error; } } }) .modules(new ManagementModule()) .build(); permissionRealmConfig = new SyncConfiguration.Builder( user, getRealmUrl(RealmType.PERMISSION_REALM, user.getAuthenticationUrl())) .errorHandler(new SyncSession.ErrorHandler() { @Override public void onError(SyncSession session, ObjectServerError error) { synchronized (errorLock) { permissionRealmError = error; } } }) .modules(new PermissionModule()) .waitForInitialRemoteData() .readOnly() .build(); }

Target:
private PermissionManager(final SyncUser user) { this.user = user; threadId = Thread.currentThread().getId(); managementRealmConfig = new SyncConfiguration.Builder( user, getRealmUrl(RealmType.MANAGEMENT_REALM, user.getAuthenticationUrl())) .errorHandler(new SyncSession.ErrorHandler() { @Override public void onError(SyncSession session, ObjectServerError error) { synchronized (errorLock) { managementRealmError = error; } } }) .modules(new ManagementModule()) .build(); permissionRealmConfig = new SyncConfiguration.Builder( user, getRealmUrl(RealmType.PERMISSION_REALM, user.getAuthenticationUrl())) .errorHandler(new SyncSession.ErrorHandler() { @Override public void onError(SyncSession session, ObjectServerError error) { synchronized (errorLock) { permissionRealmError = error; } } }) .modules(new PermissionModule()) .waitForInitialRemoteData() .build(); }
Source:
public boolean setPreferredNetworkType(int subId, int networkType) { enforceModifyPermissionOrCarrierPrivilege(subId); if (DBG) log("setPreferredNetworkType: subId " + subId + " type " + networkType); Boolean success = (Boolean) sendRequest(CMD_SET_PREFERRED_NETWORK_TYPE, networkType, subId); if (DBG) log("setPreferredNetworkType: " + (success ? "ok" : "fail")); if (success) { Settings.Global.putInt(mPhone.getContext().getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE + subId, networkType); TelephonyManager.putIntAtIndex(mPhone.getContext().getContentResolver(), android.provider.Settings.Global.PREFERRED_NETWORK_MODE, mSubscriptionController.getPhoneId(subId), networkType); } return success; }

Target:
public boolean setPreferredNetworkType(int subId, int networkType) { TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege( mApp, subId, "setPreferredNetworkType"); if (DBG) log("setPreferredNetworkType: subId " + subId + " type " + networkType); Boolean success = (Boolean) sendRequest(CMD_SET_PREFERRED_NETWORK_TYPE, networkType, subId); if (DBG) log("setPreferredNetworkType: " + (success ? "ok" : "fail")); if (success) { Settings.Global.putInt(mPhone.getContext().getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE + subId, networkType); } return success; }
Source:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getSpec() != null) { sb.append("Specs: ").append(getSpec()).append(","); } if (mLayout.getData().getValuesList() != null) { sb.append("Values: ").append(mLayout.getData().getValuesList()).append(","); } if (mLayout.getData().getPartitionName() != null) { sb.append("PartitionName: ").append(mLayout.getData().getPartitionName()).append(","); } if (mLayout.getData().getDbName() != null) { sb.append("DatabaseName: ").append(mLayout.getData().getDbName()).append(","); } if (mLayout.getData().getTableName() != null) { sb.append("TableName: ").append(mLayout.getData().getTableName()).append(","); } if (mLayout.getData().getParametersMap() != null) { sb.append("Parameters: ").append(mLayout.getData().getParametersMap()); } sb.append("}"); return sb.toString(); }

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("Spec", getSpec()) .add("Values", mLayout.getData().getValuesList()) .add("PartitionName", mLayout.getData().getPartitionName()) .add("DatabaseName", mLayout.getData().getDbName()) .add("TableName", mLayout.getData().getTableName()) .add("Parameters", mLayout.getData().getParametersMap()) .toString(); }
Source:
void writeOffsetFiles() { storeToSSps.entrySet().stream() .filter(entry -> isPersistedStore(entry.getKey())) .forEach((entry) -> { String storeName = entry.getKey(); Map<SystemStreamPartition, String> offsets = entry.getValue().stream() .filter(lastProcessedOffsets::containsKey) .collect(Collectors.toMap(Function.identity(), lastProcessedOffsets::get)); try { String fileContents = OBJECT_MAPPER.writerWithType( TypeFactory.defaultInstance().constructMapType( HashMap.class, SystemStreamPartition.class, String.class)).writeValueAsString(offsets); File offsetFile = new File(getStoreLocation(storeName), OFFSET_FILE); FileUtil.writeWithChecksum(offsetFile, fileContents); } catch (Exception e) { throw new SamzaException("Failed to write offset file for side input store: " + storeName, e); } }); }

Target:
void writeOffsetFiles() { storeToSSps.entrySet().stream() .filter(entry -> isPersistedStore(entry.getKey())) .forEach((entry) -> { String storeName = entry.getKey(); Map<SystemStreamPartition, String> offsets = entry.getValue().stream() .filter(lastProcessedOffsets::containsKey) .collect(Collectors.toMap(Function.identity(), lastProcessedOffsets::get)); try { String fileContents = OBJECT_WRITER.writeValueAsString(offsets); File offsetFile = new File(getStoreLocation(storeName), OFFSET_FILE); FileUtil.writeWithChecksum(offsetFile, fileContents); } catch (Exception e) { throw new SamzaException("Failed to write offset file for side input store: " + storeName, e); } }); }
Source:
private void logReturnedToken(final AuthenticationResult result) { if (result != null && result.getAccessToken() != null) { String accessTokenHash = getTokenHash(result.getAccessToken()); String refreshTokenHash = getTokenHash(result.getRefreshToken()); Logger.i(TAG, "Access tokenID and refresh tokenID returned. ", String.format( "Access TokenID: %s and Refresh TokenID: %s .", accessTokenHash, refreshTokenHash)); } }

Target:
private void logReturnedToken(final AuthenticationResult result) { if (result != null && result.getAccessToken() != null) { Logger.i(TAG, "Access tokenID and refresh tokenID returned. ", null); } }
Source:
private Map<String, String> getFormattingProperties(String rawFormat, List<String> positionalParameters) { Map<String, String> properties = new HashMap<String, String>(); String[] valpairs = rawFormat.split(","); for (String pair : valpairs) { Matcher matcher = keyValuePattern.matcher(pair.trim()); String key, value; if (matcher.find()) { key = matcher.group(1); value = matcher.group(2); properties.put(key, value); } else { if (positionalParameters.isEmpty()) { } else { properties.put(positionalParameters.remove(0), pair.trim()); } } } return properties; }

Target:
private Map<String, String> getFormattingProperties(String rawFormat, List<String> positionalParameters) { Map<String, String> properties = new HashMap<>(); String[] valpairs = rawFormat.split(","); for (String pair : valpairs) { Matcher matcher = keyValuePattern.matcher(pair.trim()); String key, value; if (matcher.find()) { key = matcher.group(1); value = matcher.group(2); properties.put(key, value); } else { if (positionalParameters.isEmpty()) { } else { properties.put(positionalParameters.remove(0), pair.trim()); } } } return properties; }
Source:
private static Expression.FieldAccess buildFieldAccess(IdentifierTree identifierTree) { if (!identifierTree.symbol().isVariableSymbol() || identifierTree.symbol().owner().isMethodSymbol() || identifierTree.name().equals("this")) { return null; } Expression.Variable rightSide = variableWithId(identifierTree.name()); Expression.FieldAccess fieldAccess; if (identifierTree.symbol().isStatic()) { fieldAccess = new Expression.FieldAccess( new Expression.ClassName(identifierTree.symbol().owner().type().fullyQualifiedName()), rightSide); } else { fieldAccess = new Expression.FieldAccess(rightSide); } return fieldAccess; }

Target:
private static Optional<Expression.FieldAccess> buildFieldAccess(IdentifierTree identifierTree) { Symbol identifierTreeSymbol = identifierTree.symbol(); if (!identifierTreeSymbol.isVariableSymbol() || identifierTreeSymbol.owner().isMethodSymbol() || identifierTree.name().equals("this") || identifierTree.name().equals("super")) { return Optional.empty(); } Expression.Variable rightSide = variableWithId(identifierTree.name()); if (identifierTreeSymbol.isStatic()) { return Optional.of(new Expression.FieldAccess( new Expression.ClassName(identifierTreeSymbol.owner().type().fullyQualifiedName()), rightSide)); } return Optional.of(new Expression.FieldAccess(rightSide)); }
Source:
public static void assertNeverCalled() { throw new AssertException("Should never been called"); }

Target:
public static <T> T assertNeverCalled() { throw new AssertException("Should never been called"); }
Source:
public PremisEventObject getPremisEventObject(PID pid) { return new PremisEventObject(pid, this, dataLoader, repoObjFactory).validateType(); }

Target:
public PremisEventObject getPremisEventObject(PID pid) { RepositoryObject repoObj = getRepositoryObject(pid); if (!(repoObj instanceof PremisEventObject)) { throw new FedoraException("Object with pid " + pid + " is not a premis event"); } return (PremisEventObject) repoObj; }
Source:
private void addRootProjection(SelectionSet selectionSet) { List<Selection> selections = selectionSet.getSelections(); Map<String, Field> rootSelectionField = new HashMap<>(); selections.stream().forEach(rootSelection -> { if (!(rootSelection instanceof Field)) { throw new InvalidEntityBodyException("Entity selection must be a graphQL field."); } String entityName = ((Field) rootSelection).getName(); if (SCHEMA.equals(entityName) || TYPE.equals(entityName)) { return; } if (rootSelectionField.containsKey(entityName)) { Field fields = rootSelectionField.get(entityName); fields.getSelectionSet().getSelections().addAll( ((Field) rootSelection).getSelectionSet().getSelections()); } else { rootSelectionField.put(entityName, (Field) rootSelection); } }); rootSelectionField.entrySet() .stream() .forEach(selectionField -> { String entityName = selectionField.getKey(); Class<?> entityType = entityDictionary.getEntityClass(selectionField.getKey()); if (entityType == null) { throw new InvalidEntityBodyException(String.format("Unknown entity {%s}.", selectionField.getKey())); } rootProjections.put(entityName, createProjection(entityType, selectionField.getValue())); }); }

Target:
private void addRootProjection(SelectionSet selectionSet) { List<Selection> selections = selectionSet.getSelections(); Map<String, Field> rootSelectionFields = new HashMap<>(); selections.stream().forEach(rootSelection -> { if (!(rootSelection instanceof Field)) { throw new InvalidEntityBodyException("Entity selection must be a graphQL field."); } String entityName = ((Field) rootSelection).getName(); if (SCHEMA.equals(entityName) || TYPE.equals(entityName)) { return; } if (rootSelectionFields.containsKey(entityName)) { Field fields = rootSelectionFields.get(entityName); fields.getSelectionSet().getSelections().addAll( ((Field) rootSelection).getSelectionSet().getSelections()); } else { rootSelectionFields.put(entityName, (Field) rootSelection); } }); rootSelectionFields.entrySet() .stream() .forEach(selectionField -> { String entityName = selectionField.getKey(); Class<?> entityType = entityDictionary.getEntityClass(selectionField.getKey()); if (entityType == null) { throw new InvalidEntityBodyException(String.format("Unknown entity {%s}.", selectionField.getKey())); } rootProjections.put(entityName, createProjection(entityType, selectionField.getValue())); }); }
Source:
public void executeMojo() throws MojoExecutionException, MojoExecutionException { if (!canCheckCoverage()) { return; } executeCheck(); }

Target:
public void executeMojo() throws MojoExecutionException { if (!canCheckCoverage()) { return; } executeCheck(); }
Source:
String getName(GuidedDecisionTable52 dt, List<DTCellValue52> row, Number num) { final DTCellValue52 dtCellValue52 = row.get(RULE_NAME_COLUMN_INDEX); if (hasStringValue(dtCellValue52)) { return dtCellValue52.getStringValue(); } else { return String.format("Row %d %s", num.longValue(), dt.getTableName()); } }

Target:
String getName(GuidedDecisionTable52 dt, List<DTCellValue52> row, Number num) { final DTCellValue52 ruleNameValue = row.get(RULE_NAME_COLUMN_INDEX); if (hasStringValue(ruleNameValue)) { return ruleNameValue.getStringValue(); } else { return String.format("Row %d %s", num.longValue(), dt.getTableName()); } }
Source:
static Supplier<Object> supplierFromObjectSelector(final BaseObjectColumnValueSelector<?> selector) { if (selector == null) { return null; } final Class<?> clazz = selector.classOfObject(); if (Number.class.isAssignableFrom(clazz) || String.class.isAssignableFrom(clazz)) { return selector::getObject; } else if (clazz.isAssignableFrom(Number.class) || clazz.isAssignableFrom(String.class)) { return () -> { final Object val = selector.getObject(); if (val instanceof Number || val instanceof String) { return val; } else { return null; } }; } else { return null; } }

Target:
static Supplier<Object> supplierFromObjectSelector(final BaseObjectColumnValueSelector<?> selector) { if (selector instanceof NilColumnValueSelector) { return null; } final Class<?> clazz = selector.classOfObject(); if (Number.class.isAssignableFrom(clazz) || String.class.isAssignableFrom(clazz)) { return selector::getObject; } else if (clazz.isAssignableFrom(Number.class) || clazz.isAssignableFrom(String.class)) { return () -> { final Object val = selector.getObject(); if (val instanceof Number || val instanceof String) { return val; } else { return null; } }; } else { return null; } }
Source:
public Set<RelColumnOrigin> getColumnOrigins( Aggregate rel, int iOutputColumn) { if (iOutputColumn < rel.getGroupCount()) { return invokeGetColumnOrigins( rel.getInput(), iOutputColumn); } if (rel.indicator) { if (iOutputColumn < rel.getGroupCount() + rel.getIndicatorCount()) { return new HashSet<RelColumnOrigin>(); } } AggregateCall call = rel.getAggCallList().get(iOutputColumn - rel.getGroupCount() - rel.getIndicatorCount()); Set<RelColumnOrigin> set = new HashSet<RelColumnOrigin>(); for (Integer iInput : call.getArgList()) { Set<RelColumnOrigin> inputSet = invokeGetColumnOrigins( rel.getInput(), iInput); inputSet = createDerivedColumnOrigins(inputSet); if (inputSet != null) { set.addAll(inputSet); } } return set; }

Target:
public Set<RelColumnOrigin> getColumnOrigins( Aggregate rel, int iOutputColumn) { if (iOutputColumn < rel.getGroupCount()) { return invokeGetColumnOrigins( rel.getInput(), iOutputColumn); } if (rel.indicator) { if (iOutputColumn < rel.getGroupCount() + rel.getIndicatorCount()) { return ImmutableSet.of(); } } AggregateCall call = rel.getAggCallList().get(iOutputColumn - rel.getGroupCount() - rel.getIndicatorCount()); Set<RelColumnOrigin> set = new HashSet<RelColumnOrigin>(); for (Integer iInput : call.getArgList()) { Set<RelColumnOrigin> inputSet = invokeGetColumnOrigins( rel.getInput(), iInput); inputSet = createDerivedColumnOrigins(inputSet); if (inputSet != null) { set.addAll(inputSet); } } return set; }
Source:
public static File getRevisionFile(AbstractBuild build) { return new File(build.getRootDir(),"revision.txt"); }

Target:
public static File getRevisionFile(AbstractBuild build) { return getRevisionFile((Run) build); }
Source:
int getSize() { return events.size(); }

Target:
public int getSize() { return events.size(); }
Source:
PackageBinding combineWithSiblings(PackageBinding childPackage, char[] name, ModuleBinding module) { ModuleBinding primaryModule = childPackage != null ? childPackage.enclosingModule : this.enclosingModule; boolean activeSave = primaryModule.isPackageLookupActive; primaryModule.isPackageLookupActive = true; try { char[] flatName = CharOperation.concatWith(childPackage.compoundName, '.'); for (PackageBinding incarnation : this.incarnations) { ModuleBinding moduleBinding = incarnation.enclosingModule; if (moduleBinding == module) continue; if (childPackage.isDeclaredIn(moduleBinding)) continue; PackageBinding next = moduleBinding.getDeclaredPackage(flatName); childPackage = combine(next, childPackage, primaryModule); } return childPackage; } finally { primaryModule.isPackageLookupActive = activeSave; } }

Target:
PackageBinding combineWithSiblings(PackageBinding childPackage, char[] name, ModuleBinding module) { ModuleBinding primaryModule = childPackage.enclosingModule; boolean activeSave = primaryModule.isPackageLookupActive; primaryModule.isPackageLookupActive = true; try { char[] flatName = CharOperation.concatWith(childPackage.compoundName, '.'); for (PackageBinding incarnation : this.incarnations) { ModuleBinding moduleBinding = incarnation.enclosingModule; if (moduleBinding == module) continue; if (childPackage.isDeclaredIn(moduleBinding)) continue; PackageBinding next = moduleBinding.getDeclaredPackage(flatName); childPackage = combine(next, childPackage, primaryModule); } return childPackage; } finally { primaryModule.isPackageLookupActive = activeSave; } }
Source:
private Jedis getJedisResource() { if (jedisSentinelPool != null) { return jedisSentinelPool.getResource(); } return jedisPool.getResource(); }

Target:
private Jedis getJedisResource() { return jedisPool.getResource(); }
Source:
public ColumnBuilderFactory(@NonNull ColumnDefinitions<T> columnDefinitions) { this.columnDefinitions = columnDefinitions; id = Syncable.MISSING_ID; uuid = Syncable.Companion.getMISSING_UUID(); columnType = 0; syncState = new DefaultSyncState(); customOrderId = 0; }

Target:
public ColumnBuilderFactory(@NonNull ColumnDefinitions<T> columnDefinitions) { this.columnDefinitions = columnDefinitions; id = Keyed.MISSING_ID; uuid = Keyed.Companion.getMISSING_UUID(); columnType = 0; syncState = new DefaultSyncState(); customOrderId = 0; }
Source:
protected Object getEntity() { try { Method m = resolveGet(); if (m == null) { return null; } Object entity = m.invoke(this); return getEntityWithIdAndHref(entity); } catch (Exception e) { log.error("Getting resource after action failed: {}", e.getMessage()); log.debug("Exception", e); return null; } }

Target:
protected Object getEntity() { try { Method m = resolveGet(); if (m == null) { return null; } Object entity = m.invoke(this); return getEntityWithIdAndHref(entity); } catch (Exception e) { log.error("Getting resource after action failed.", e); return null; } }
Source:
public void canAddToEmptyWallet() { final SDBClient client = Mockito.mock(SDBClient.class); final AmazonSimpleDB aws = Mockito.mock(AmazonSimpleDB.class); Mockito.doReturn(aws).when(client).get(); final GetAttributesResult gar = Mockito.mock(GetAttributesResult.class); Mockito.doReturn(gar).when(aws) .getAttributes( Mockito.any(GetAttributesRequest.class) ); Mockito.doReturn(new ArrayList<Attribute>()).when(gar).getAttributes(); Mockito.doNothing().when(aws).putAttributes( Mockito.any( PutAttributesRequest.class ) ); final Wallet wlt = new Wallet.Empty(); final ItemSpinbox box = new ItemSpinbox(wlt, "test", client); final long deposit = Tv.EIGHT; final long balance = box.add(deposit); Mockito.verify(aws).getAttributes( Mockito.any( GetAttributesRequest.class ) ); Mockito.verify(aws).putAttributes( Mockito.any( PutAttributesRequest.class ) ); MatcherAssert.assertThat(balance, Matchers.equalTo(deposit)); }

Target:
public void canAddToEmptyWallet() { final SDBClient client = Mockito.mock(SDBClient.class); final AmazonSimpleDB aws = Mockito.mock(AmazonSimpleDB.class); Mockito.doReturn(aws).when(client).get(); final GetAttributesResult gar = Mockito.mock(GetAttributesResult.class); Mockito.doReturn(gar).when(aws).getAttributes( Mockito.any(GetAttributesRequest.class) ); Mockito.doReturn(new ArrayList<Attribute>(0)).when(gar).getAttributes(); Mockito.doNothing().when(aws).putAttributes( Mockito.any( PutAttributesRequest.class ) ); final Wallet wlt = new Wallet.Empty(); final ItemSpinbox box = new ItemSpinbox(wlt, "test", client); final long deposit = Tv.EIGHT; final long balance = box.add(deposit); Mockito.verify(aws).getAttributes( Mockito.any( GetAttributesRequest.class ) ); Mockito.verify(aws).putAttributes( Mockito.any( PutAttributesRequest.class ) ); MatcherAssert.assertThat(balance, Matchers.equalTo(deposit)); }
Source:
public static int defaultMaxConnections() { return AsyncPropertiesHelper.getAysncHttpClientConfig().getInt(ASYNC_CLIENT + "maxConnections"); }

Target:
public static int defaultMaxConnections() { return AsyncPropertiesHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT + "maxConnections"); }
Source:
public Collection<Measurement> executeSensors() { LOG.info("----------------------------------"); try { for (TopologyAPI.Config.KeyValue kv : physicalPlanProvider.get().getTopology().getTopologyConfig().getKvsList()) { if (kv.getKey().endsWith(":runtime")) { LOG.fine("kv:runtime " + kv.getKey() + " -> " + kv.getValue()); if (kv.getKey().equals(policyIdRuntime)) { try { PolicyMode val = PolicyMode.valueOf(kv.getValue()); if (!policyMode.equals(val)) { policyMode = val; LOG.info("policy " + policyId + " status changed to " + policyMode); } else { LOG.fine("policy " + policyId + " status remains same " + policyMode); } break; } catch (IllegalArgumentException e) { LOG.warning("policy " + policyId + " status does not change " + policyMode + "; unknown input " + kv.getValue()); } } } } } catch (Exception e) { LOG.warning( "failed to fetch the latest physical plan and skip policy toggle update: " + e.toString()); } if (policyMode.equals(PolicyMode.activated)) { return super.executeSensors(); } else { return Collections.EMPTY_LIST; } }

Target:
public Collection<Measurement> executeSensors() { LOG.fine("--------- policy: " + policyId + " ---------"); try { for (TopologyAPI.Config.KeyValue kv : physicalPlanProvider.get().getTopology().getTopologyConfig().getKvsList()) { if (kv.getKey().endsWith(":runtime")) { LOG.fine("kv:runtime " + kv.getKey() + " -> " + kv.getValue()); if (kv.getKey().equals(policyIdRuntime)) { try { PolicyMode val = PolicyMode.valueOf(kv.getValue()); if (!policyMode.equals(val)) { policyMode = val; LOG.info("policy " + policyId + " status changed to " + policyMode); } else { LOG.fine("policy " + policyId + " status remains same " + policyMode); } break; } catch (IllegalArgumentException e) { LOG.warning("policy " + policyId + " status does not change " + policyMode + "; unknown input " + kv.getValue()); } } } } } catch (Exception e) { LOG.warning( "failed to fetch the latest physical plan and skip policy toggle update: " + e.toString()); } if (policyMode.equals(PolicyMode.activated)) { return super.executeSensors(); } else { return Collections.EMPTY_LIST; } }