auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private URL loadXMLToFile(Document document) throws TransformerException, IOException { DOMSource source = new DOMSource(document); File tempFile = File.createTempFile("temp", ".txt"); tempFile.deleteOnExit(); FileWriter writer = new FileWriter(tempFile); StreamResult result = new StreamResult(writer); TransformerFactory transformerFactory; try { transformerFactory = TransformerFactory .newInstance("com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl", null); } catch (NoSuchMethodError e) { <START> logger.log(Level.INFO, "TransformerFactory.newInstance(String, ClassLoader) method not found. " + <END> "Using TransformerFactory.newInstance()"); transformerFactory = TransformerFactory.newInstance(); } transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(source, result); return tempFile.toURI().toURL(); }</code><technical_language>please change this log.info()</technical_language>

Target:
private URL loadXMLToFile(Document document) throws TransformerException, IOException { DOMSource source = new DOMSource(document); File tempFile = File.createTempFile("temp", ".txt"); tempFile.deleteOnExit(); FileWriter writer = new FileWriter(tempFile); StreamResult result = new StreamResult(writer); TransformerFactory transformerFactory; try { transformerFactory = TransformerFactory .newInstance("com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl", null); } catch (NoSuchMethodError e) { log.info("TransformerFactory.newInstance(String, ClassLoader) method not found. " + "Using TransformerFactory.newInstance()"); transformerFactory = TransformerFactory.newInstance(); } transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(source, result); return tempFile.toURI().toURL(); }
Source:
<code>public void onRewardedVideoStarted(@NonNull String adUnitId) { if (listener != null) { <START> listener.onAdOpened(MoPubMediationAdapter.this); <END> } }</code><technical_language>onVideoStarted() invoked calling onVideoCompleted()</technical_language>

Target:
public void onRewardedVideoStarted(@NonNull String adUnitId) { if (listener != null) { listener.onAdOpened(MoPubMediationAdapter.this); listener.onVideoStarted(MoPubMediationAdapter.this); } }
Source:
<code>public void deleteServerInstance(final ServerInstanceKey serverInstanceKey) { checkNotNull("serverInstanceKey", serverInstanceKey); <START> System.out.println("getKieServerInstanceManager().isAlive(serverInstanceKey) = " + getKieServerInstanceManager().isAlive(serverInstanceKey)); <END> if (getKieServerInstanceManager().isAlive(serverInstanceKey)) { throw new RuntimeException("Can't delete live instance."); } else { final String serverInstanceId = serverInstanceKey.getServerInstanceId(); final ServerTemplate serverTemplate = getServerTemplate(serverInstanceKey.getServerTemplateId()); if (serverTemplate != null) { serverTemplate.deleteServerInstance(serverInstanceId); getTemplateStorage().update(serverTemplate); getNotificationService().notify(new ServerInstanceDeleted(serverInstanceId)); } } }</code><technical_language>remove system out</technical_language>

Target:
public void deleteServerInstance(final ServerInstanceKey serverInstanceKey) { checkNotNull("serverInstanceKey", serverInstanceKey); if (getKieServerInstanceManager().isAlive(serverInstanceKey)) { throw new RuntimeException("Can't delete live instance."); } else { final String serverInstanceId = serverInstanceKey.getServerInstanceId(); final ServerTemplate serverTemplate = getServerTemplate(serverInstanceKey.getServerTemplateId()); if (serverTemplate != null) { serverTemplate.deleteServerInstance(serverInstanceId); getTemplateStorage().update(serverTemplate); getNotificationService().notify(new ServerInstanceDeleted(serverInstanceId)); } } }
Source:
<code>public void testGetAppointmentIdByGroupIdAndApplicantId() { List<String> userIdList = new ArrayList<>(); Collections.addAll(userIdList, "1", "2", "3"); Appointment appointment = new Appointment(userIdList, "TestApplicantId", 100L); appointment.setGroupId("TestGroupId"); Session session = sessionFactory.getCurrentSession(); String expectedId = (String) session.save(appointment); String actualId = appointmentDAO.getAppointmentIdByGroupIdAndApplicantId("TestGroupId", "TestApplicantId"); <START> System.out.println(expectedId + " " + actualId); <END> assertThat(expectedId, equalTo(actualId)); }</code><technical_language>why</technical_language>

Target:
public void testGetAppointmentIdByGroupIdAndApplicantId() { List<String> userIdList = new ArrayList<>(); Collections.addAll(userIdList, "1", "2", "3"); Appointment appointment = new Appointment(userIdList, "TestApplicantId", 100L); appointment.setGroupId("TestGroupId"); Session session = sessionFactory.getCurrentSession(); String expectedId = (String) session.save(appointment); String actualId = appointmentDAO.getAppointmentIdByGroupIdAndApplicantId("TestGroupId", "TestApplicantId"); assertThat(expectedId, equalTo(actualId)); }
Source:
<code>void unmonitor(IResource resource, IProgressMonitor progressMonitor) { if (resource == null || !isMonitoring(resource)) return; SubMonitor subMonitor = SubMonitor.convert(progressMonitor, 100); synchronized (registeredMonitors) { SubMonitor loopMonitor = subMonitor.split(90).setWorkRemaining(registeredMonitors.entrySet().size()); for (Iterator<Entry<IRefreshMonitor, List<IResource>>> i = registeredMonitors.entrySet().iterator(); i.hasNext();) { loopMonitor.worked(1); Entry<IRefreshMonitor, List<IResource>> current = i.next(); List<IResource> resources = current.getValue(); if ((resources != null) && !resources.isEmpty() && resources.contains(resource)) { current.getKey().unmonitor(resource); resources.remove(resource); } } } if (resource.getType() == IResource.PROJECT) unmonitorLinkedContents((IProject) resource, subMonitor.split(10)); <START> subMonitor.setWorkRemaining(0); <END> }</code><technical_language>This method advance monitor</technical_language>

Target:
void unmonitor(IResource resource, IProgressMonitor progressMonitor) { if (resource == null || !isMonitoring(resource)) return; SubMonitor subMonitor = SubMonitor.convert(progressMonitor, 100); synchronized (registeredMonitors) { SubMonitor loopMonitor = subMonitor.split(90).setWorkRemaining(registeredMonitors.entrySet().size()); for (Iterator<Entry<IRefreshMonitor, List<IResource>>> i = registeredMonitors.entrySet().iterator(); i.hasNext();) { loopMonitor.worked(1); Entry<IRefreshMonitor, List<IResource>> current = i.next(); List<IResource> resources = current.getValue(); if ((resources != null) && !resources.isEmpty() && resources.contains(resource)) { current.getKey().unmonitor(resource); resources.remove(resource); } } } if (resource.getType() == IResource.PROJECT) unmonitorLinkedContents((IProject) resource, subMonitor.split(10)); }
Source:
<code>public static void startWith(boolean useNewRails, String jrubyPath) throws Exception { copyDbFiles(); copyScss(); File webApp = new File("webapp"); if (!webApp.exists()) { throw new RuntimeException("No webapp found in " + webApp.getAbsolutePath()); } copyActivatorJarToClassPath(); SystemEnvironment systemEnvironment = new SystemEnvironment(); systemEnvironment.setProperty(SystemEnvironment.PARENT_LOADER_PRIORITY, "true"); systemEnvironment.setProperty(SystemEnvironment.CRUISE_SERVER_WAR_PROPERTY, webApp.getAbsolutePath()); systemEnvironment.set(SystemEnvironment.USE_NEW_RAILS, useNewRails); systemEnvironment.set(useNewRails ? SystemEnvironment.JRUBY_NEW_PATH : SystemEnvironment.JRUBY_OLD_PATH, jrubyPath); systemEnvironment.set(SystemEnvironment.DEFAULT_PLUGINS_ZIP, "/plugins.zip"); systemEnvironment.setProperty(GoConstants.I18N_CACHE_LIFE, "0"); File pluginsDist = new File("../tw-go-plugins/dist/"); if (pluginsDist.exists()) { new ZipUtil().zipFolderContents(pluginsDist, new File(classpath(), "plugins.zip")); } GoServer server = new GoServer(); systemEnvironment.setProperty(GoConstants.USE_COMPRESSED_JAVASCRIPT, Boolean.toString(false)); try { server.startServer(); <START> System.out.println("Go server dashboard started on http://localhost:8153"); <END> System.out.println("* credentials: \"admin\" / \"badger\""); } catch (Exception e) { System.err.println("Failed to start Go server. Exception:"); e.printStackTrace(); } }</code><technical_language>+1 intention. this configuration.. instead of hardcoding</technical_language>

Target:
public static void startWith(boolean useNewRails, String jrubyPath) throws Exception { copyDbFiles(); copyScss(); File webApp = new File("webapp"); if (!webApp.exists()) { throw new RuntimeException("No webapp found in " + webApp.getAbsolutePath()); } copyActivatorJarToClassPath(); SystemEnvironment systemEnvironment = new SystemEnvironment(); systemEnvironment.setProperty(SystemEnvironment.PARENT_LOADER_PRIORITY, "true"); systemEnvironment.setProperty(SystemEnvironment.CRUISE_SERVER_WAR_PROPERTY, webApp.getAbsolutePath()); systemEnvironment.set(SystemEnvironment.USE_NEW_RAILS, useNewRails); systemEnvironment.set(useNewRails ? SystemEnvironment.JRUBY_NEW_PATH : SystemEnvironment.JRUBY_OLD_PATH, jrubyPath); systemEnvironment.set(SystemEnvironment.DEFAULT_PLUGINS_ZIP, "/plugins.zip"); systemEnvironment.setProperty(GoConstants.I18N_CACHE_LIFE, "0"); File pluginsDist = new File("../tw-go-plugins/dist/"); if (pluginsDist.exists()) { new ZipUtil().zipFolderContents(pluginsDist, new File(classpath(), "plugins.zip")); } GoServer server = new GoServer(); systemEnvironment.setProperty(GoConstants.USE_COMPRESSED_JAVASCRIPT, Boolean.toString(false)); try { server.startServer(); String hostName = systemEnvironment.getListenHost(); if(hostName == null){ hostName = "localhost"; } System.out.println("Go server dashboard started on http://" + hostName + ":" + systemEnvironment.getServerPort()); System.out.println("* credentials: \"admin\" / \"badger\""); } catch (Exception e) { System.err.println("Failed to start Go server. Exception:"); e.printStackTrace(); } }
Source:
<code><START> protected boolean useAsync(final Node node) { <END> if (node.getMetaData().containsKey(NodeInstance.METADATA_WRAP_ASYNC_NODE)) { return !((Boolean) node.getMetaData().get(NodeInstance.METADATA_WRAP_ASYNC_NODE)); } if (!(node instanceof EventSubProcessNode) && (node instanceof ActionNode || node instanceof StateBasedNode || node instanceof EndNode)) { boolean asyncMode = Boolean.parseBoolean((String)node.getMetaData().get("customAsync")); if (asyncMode) { return asyncMode; } return Boolean.parseBoolean((String)getProcessInstance().getKnowledgeRuntime().getEnvironment().get("AsyncMode")); } return false; }</code><technical_language>I pointed out - if this property is true - wrap async node - wrapping anything</technical_language>

Target:
protected boolean useAsync(final Node node) { if (node.getMetaData().containsKey(NodeInstance.METADATA_WRAP_ASYNC_NODE)) { return ((Boolean) node.getMetaData().get(NodeInstance.METADATA_WRAP_ASYNC_NODE)); } if (!(node instanceof EventSubProcessNode) && (node instanceof ActionNode || node instanceof StateBasedNode || node instanceof EndNode)) { boolean asyncMode = Boolean.parseBoolean((String)node.getMetaData().get("customAsync")); if (asyncMode) { return asyncMode; } return Boolean.parseBoolean((String)getProcessInstance().getKnowledgeRuntime().getEnvironment().get("AsyncMode")); } return false; }
Source:
<code>public void onEvent(NetworkConnectivityChangeEvent event){ <START> setFragmentState(!NetworkUtil.isConnected(getContext())); <END> }</code><technical_language>registerSticky() receive posted status initialization (and ensure initial state is posted app initialization), call this explicitly onViewCreated() some other callback for Fragment initialization</technical_language>

Target:
public void onEvent(NetworkConnectivityChangeEvent event) { if (NetworkUtil.isConnected(getContext())) { hideErrorMessage(); } else { showErrorMessage(R.string.reset_no_network_message, FontAwesomeIcons.fa_wifi); } }
Source:
<code>private void setProgressIndicatorsVisible(final boolean visible) { DISPLAY.asyncExec(new Runnable() { @Override public void run() { progressBar.setVisible(visible); } <START> }); <END> }</code><technical_language>condense this DISPLAY.asyncExec(() -> progressBar.setVisible(visible));</technical_language>

Target:
private void setProgressIndicatorsVisible(final boolean visible) { DISPLAY.asyncExec(() -> progressBar.setVisible(visible)); }
Source:
<code>public static Money getShareValue(Campaign campaign) { final String METHOD_NAME = "getShareValue(Campaign)"; if (!campaign.getCampaignOptions().getUseShareSystem()) { return Money.zero(); } String financialReport = campaign.getFinancialReport(); Money netWorth = Money.zero(); try { <START> Pattern p = Pattern.compile("Net Worth\\D*([\\d,.]+)"); <END> Matcher m = p.matcher(financialReport); m.find(); netWorth = Money.parse(m.group(1)); if (campaign.getCampaignOptions().getSharesExcludeLargeCraft()) { p = Pattern.compile("Large Craft\\D*([\\d,.]*)"); m = p.matcher(financialReport); if (m.find() && null != m.group(1)) { netWorth = netWorth.minus(Money.parse(m.group(1))); } } } catch (Exception e) { MekHQ.getLogger().log(RetirementDefectionTracker.class, METHOD_NAME, LogLevel.ERROR, "Error parsing net worth in financial report"); MekHQ.getLogger().error(RetirementDefectionTracker.class, METHOD_NAME, e); } int totalShares = 0; for (Person p : campaign.getActivePersonnel()) { totalShares += p.getNumShares(campaign.getCampaignOptions().getSharesForAll()); } if (totalShares <= 0) { return Money.zero(); } return netWorth.dividedBy(totalShares); }</code><technical_language>unescaped . matches anything, [\\d,.]+ is .+</technical_language>

Target:
public static Money getShareValue(Campaign campaign) { if (!campaign.getCampaignOptions().getUseShareSystem()) { return Money.zero(); } FinancialReport r = campaign.getFinancialReport(); Money netWorth = r.getNetWorth(); if (campaign.getCampaignOptions().getSharesExcludeLargeCraft()) { netWorth = netWorth.minus(r.getLargeCraftValue()); } int totalShares = 0; for (Person p : campaign.getActivePersonnel()) { totalShares += p.getNumShares(campaign.getCampaignOptions().getSharesForAll()); } if (totalShares <= 0) { return Money.zero(); } return netWorth.dividedBy(totalShares); }
Source:
<code><START> default <U> Validation<U,T> leftMap(Function<? super E,? extends U> f) { <END> if(isInvalid()) { E v = this.error(); return Validation.invalid(f.apply(v)); } else { return (Valid<U,T>) this; } }</code><technical_language>please null-check f</technical_language>

Target:
default <U> Validation<U,T> leftMap(Function<? super E,? extends U> f) { Objects.requireNonNull(f, "function f is null"); if(isInvalid()) { E error = this.getError(); return Validation.invalid(f.apply(error)); } else { return Validation.valid(this.get()); } }
Source:
<code>public void idle() { if (lastSendInterval++ >= sendIntervals) { lastSendInterval = 0; Iterator<DispatchAttempt> iterator = sendQueue.iterator(); while (iterator.hasNext()) { DispatchAttempt attempt = iterator.next(); try { EventMessageContent message = new EventMessageContent(); message.prepareMessage(hostName, attempt.event, isBodyHtml); log.info("Sending mail subject='{}' to='{}'", message.getMessageSubject(), attempt.address); log.debug("Send mail body='{}'", message.getMessageBody()); sendMail(attempt.address, message.getMessageSubject(), message.getMessageBody()); log.info( <START> "E-mail subject='{}' to='{} sent successfully", <END> message.getMessageSubject(), attempt.address ); notifyObservers(DispatchResult.success(attempt.event, attempt.address, EventNotificationMethod.SMTP)); iterator.remove(); } catch (Exception ex) { attempt.retries++; if (attempt.retries >= retries) { notifyObservers(DispatchResult.failure(attempt.event, attempt.address, EventNotificationMethod.SMTP, ex.getMessage())); iterator.remove(); } } } } }</code><technical_language>Please add missing apostrophe: "E-mail subject='{}' to='{}' successfully" ^</technical_language>

Target:
public void idle() { if (lastSendInterval++ >= sendIntervals) { lastSendInterval = 0; Iterator<DispatchAttempt> iterator = sendQueue.iterator(); while (iterator.hasNext()) { DispatchAttempt attempt = iterator.next(); try { EventMessageContent message = new EventMessageContent(); message.prepareMessage(hostName, attempt.event, isBodyHtml); log.info("Sending mail subject='{}' to='{}'", message.getMessageSubject(), attempt.address); log.debug("Send mail body='{}'", message.getMessageBody()); sendMail(attempt.address, message.getMessageSubject(), message.getMessageBody()); log.info( "E-mail subject='{}' to='{}' sent successfully", message.getMessageSubject(), attempt.address ); notifyObservers(DispatchResult.success(attempt.event, attempt.address, EventNotificationMethod.SMTP)); iterator.remove(); } catch (Exception ex) { attempt.retries++; if (attempt.retries >= retries) { notifyObservers(DispatchResult.failure(attempt.event, attempt.address, EventNotificationMethod.SMTP, ex.getMessage())); iterator.remove(); } } } } }
Source:
<code>protected RestResponse handleRequest(RestRequest req) throws Exception { DataPointRequest dpReq = (DataPointRequest) req; RestResponse res = new RestResponse(); if (dpReq.getSurveyId() != null) { DeviceDAO deviceDao = new DeviceDAO(); Device device = deviceDao.getDevice(dpReq.getAndroidId(), null, null); if (device != null) { log.info("Found device id: " + device.getKey().getId()); log.fine("Found device: " + device); List<SurveyedLocale> dpList = getDataPointList(device.getKey().getId(), dpReq.getSurveyId()); if (dpList == null) { <START> res.setCode(String.valueOf(HttpServletResponse.SC_BAD_REQUEST)); <END> res.setMessage("No assignment was found"); return res; } res = convertToResponse(dpList, dpReq.getSurveyId()); return res; } res.setCode(String.valueOf(HttpServletResponse.SC_NOT_FOUND)); res.setMessage("Unknown device"); } else { res.setCode(String.valueOf(HttpServletResponse.SC_FORBIDDEN)); res.setMessage("Invalid Survey"); } return res; }</code><technical_language>return a 404 instead? @valllllll2000 device behave return of error codes</technical_language>

Target:
protected RestResponse handleRequest(RestRequest req) throws Exception { DataPointRequest dpReq = (DataPointRequest) req; RestResponse res = new RestResponse(); if (dpReq.getSurveyId() != null) { DeviceDAO deviceDao = new DeviceDAO(); Device device = deviceDao.getDevice(dpReq.getAndroidId(), null, null); if (device != null) { log.info("Found device id: " + device.getKey().getId()); log.fine("Found device: " + device); List<SurveyedLocale> dpList = getDataPointList(device.getKey().getId(), dpReq.getSurveyId()); if (dpList == null) { res.setCode(String.valueOf(HttpServletResponse.SC_NOT_FOUND)); res.setMessage("No assignment was found"); return res; } res = convertToResponse(dpList, dpReq.getSurveyId()); return res; } res.setCode(String.valueOf(HttpServletResponse.SC_NOT_FOUND)); res.setMessage("Unknown device"); } else { res.setCode(String.valueOf(HttpServletResponse.SC_FORBIDDEN)); res.setMessage("Invalid Survey"); } return res; }
Source:
<code>public void testMixedDistinctWithFilter() { assertions.assertQuery( "SELECT " + " count(DISTINCT x) FILTER (WHERE x > 0), " + " sum(x) " + "FROM (VALUES 0, 1, 1, 2) t(x)", "VALUES (BIGINT '2', BIGINT '4')"); assertions.assertQuery( <START> "SELECT" + <END> " count(DISTINCT x) FILTER (where y = 1)" + "FROM (VALUES (2, 1), (1, 2), (1,1)) t(x, y)", "VALUES (BIGINT '2')"); assertions.assertQuery( "SELECT " + " count(DISTINCT x), " + " sum(x) FILTER (WHERE x > 0) " + "FROM (VALUES 0, 1, 1, 2) t(x)", "VALUES (BIGINT '3', BIGINT '4')"); assertions.assertQuery( "SELECT" + " sum(DISTINCT x) FILTER (WHERE y > 3)," + " sum(DISTINCT y) FILTER (WHERE x > 1)" + "FROM (VALUES (1, 3), (2, 4), (2, 4), (4, 5)) t (x, y)", "VALUES (BIGINT '6', BIGINT '9')"); assertions.assertQuery( "SELECT" + " sum(x) FILTER (WHERE x > 1) AS x," + " sum(DISTINCT x)" + "FROM (VALUES (1), (2), (2), (4)) t (x)", "VALUES (BIGINT '6', BIGINT '7')"); }</code><technical_language>This strange. I breaking line improves readability</technical_language>

Target:
public void testMixedDistinctWithFilter() { assertions.assertQuery( "SELECT " + " count(DISTINCT x) FILTER (WHERE x > 0), " + " sum(x) " + "FROM (VALUES 0, 1, 1, 2) t(x)", "VALUES (BIGINT '2', BIGINT '4')"); assertions.assertQuery( "SELECT count(DISTINCT x) FILTER (where y = 1)" + "FROM (VALUES (2, 1), (1, 2), (1,1)) t(x, y)", "VALUES (BIGINT '2')"); assertions.assertQuery( "SELECT " + " count(DISTINCT x), " + " sum(x) FILTER (WHERE x > 0) " + "FROM (VALUES 0, 1, 1, 2) t(x)", "VALUES (BIGINT '3', BIGINT '4')"); assertions.assertQuery( "SELECT" + " sum(DISTINCT x) FILTER (WHERE y > 3)," + " sum(DISTINCT y) FILTER (WHERE x > 1)" + "FROM (VALUES (1, 3), (2, 4), (2, 4), (4, 5)) t (x, y)", "VALUES (BIGINT '6', BIGINT '9')"); assertions.assertQuery( "SELECT" + " sum(x) FILTER (WHERE x > 1) AS x," + " sum(DISTINCT x)" + "FROM (VALUES (1), (2), (2), (4)) t (x)", "VALUES (BIGINT '8', BIGINT '7')"); assertions.assertQuery( "SELECT sum(DISTINCT x) FILTER (WHERE y > 5)" + "FROM (VALUES (1, 3), (2, 4), (2, 4), (4, 5)) t (x, y)", "VALUES (CAST(NULL AS BIGINT))"); assertions.assertQuery( "SELECT" + " count(DISTINCT y) FILTER (WHERE x > 4)," + " sum(DISTINCT x) FILTER (WHERE y > 5)" + "FROM (VALUES (1, 3), (2, 4), (2, 4), (4, 5)) t (x, y)", "VALUES (BIGINT '0', CAST(NULL AS BIGINT))"); }
Source:
<code>private void processAsVideo() throws FileNotFoundException { Log.d(Config.LOGTAG,"processing file as video"); mXmppConnectionService.startForcingForegroundNotification(); message.setRelativeFilePath(message.getUuid() + ".mp4"); final DownloadableFile file = mXmppConnectionService.getFileBackend().getFile(message); final MediaFormatStrategy formatStrategy; <START> final String compressVideo = mXmppConnectionService.getResources().getString(R.string.video_compression); <END> switch (compressVideo) { case "720": formatStrategy = new Android720pFormatStrategy(); Log.d(Config.LOGTAG,"WOOOMP 720 dar " + compressVideo); break; case "1080": formatStrategy = new Android1080pFormatStrategy(); Log.d(Config.LOGTAG,"WOOOMP 1080 dar " + compressVideo); break; default: formatStrategy = new Android360pFormatStrategy(); Log.d(Config.LOGTAG,"WOOOMP 360 dar" + compressVideo); break; } file.getParentFile().mkdirs(); final ParcelFileDescriptor parcelFileDescriptor = mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r"); if (parcelFileDescriptor == null) { throw new FileNotFoundException("Parcel File Descriptor was null"); } FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Future<Void> future = MediaTranscoder.getInstance().transcodeVideo(fileDescriptor, file.getAbsolutePath(), formatStrategy, this); try { future.get(); } catch (InterruptedException e) { throw new AssertionError(e); } catch (ExecutionException e) { Log.d(Config.LOGTAG,"ignoring execution exception. Should get handled by onTranscodeFiled() instead",e); } }</code><technical_language>This read preference a translated string. content of compressVideo 'Video compression</technical_language>

Target:
private void processAsVideo() throws FileNotFoundException { Log.d(Config.LOGTAG,"processing file as video"); mXmppConnectionService.startForcingForegroundNotification(); message.setRelativeFilePath(message.getUuid() + ".mp4"); final DownloadableFile file = mXmppConnectionService.getFileBackend().getFile(message); final MediaFormatStrategy formatStrategy = "720".equals(getVideoCompression()) ? new Android720pFormatStrategy() : new Android360pFormatStrategy(); file.getParentFile().mkdirs(); final ParcelFileDescriptor parcelFileDescriptor = mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r"); if (parcelFileDescriptor == null) { throw new FileNotFoundException("Parcel File Descriptor was null"); } FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Future<Void> future = MediaTranscoder.getInstance().transcodeVideo(fileDescriptor, file.getAbsolutePath(), formatStrategy, this); try { future.get(); } catch (InterruptedException e) { throw new AssertionError(e); } catch (ExecutionException e) { Log.d(Config.LOGTAG,"ignoring execution exception. Should get handled by onTranscodeFiled() instead",e); } }
Source:
<code>public String getText(Object object) { GenClass genClass = (GenClass)object; EClass eClass = genClass.getEcoreClass(); if(eClass == null) { <START> return "null"; <END> } StringBuffer result = new StringBuffer(); if (eClass.getName() != null) { result.append(eClass.getName()); } if (!eClass.getESuperTypes().isEmpty()) { result.append(" -> "); for (Iterator<EClass> i = eClass.getESuperTypes().iterator(); i.hasNext(); ) { EClass eSuperType = i.next(); result.append(eSuperType.getName()); if (i.hasNext()) { result.append(", "); } } } if (eClass.getInstanceClassName() != null) { result.append(" ["); result.append(eClass.getInstanceClassName()); result.append("]"); } return result.toString(); }</code><technical_language>I return ""</technical_language>

Target:
public String getText(Object object) { GenClass genClass = (GenClass)object; EClass eClass = genClass.getEcoreClass(); if(eClass == null) { return ""; } StringBuffer result = new StringBuffer(); if (eClass.getName() != null) { result.append(eClass.getName()); } if (!eClass.getESuperTypes().isEmpty()) { result.append(" -> "); for (Iterator<EClass> i = eClass.getESuperTypes().iterator(); i.hasNext(); ) { EClass eSuperType = i.next(); result.append(eSuperType.getName()); if (i.hasNext()) { result.append(", "); } } } if (eClass.getInstanceClassName() != null) { result.append(" ["); result.append(eClass.getInstanceClassName()); result.append("]"); } return result.toString(); }
Source:
<code>private EventEntity convertEvent(Event event) { EventEntity eventEntity = new EventEntity(); eventEntity.setId(UUID.randomUUID().toString()); eventEntity.setTime(event.getTime()); eventEntity.setType(event.getType().toString()); eventEntity.setRealmId(event.getRealmId()); eventEntity.setClientId(event.getClientId()); eventEntity.setUserId(event.getUserId()); eventEntity.setSessionId(event.getSessionId()); eventEntity.setIpAddress(event.getIpAddress()); eventEntity.setError(event.getError()); try { <START> if (maxDetailLength > 0) { <END> Map<String, String> result = new HashMap<>(event.getDetails()); result.values().forEach(this::trimToMaxLength); eventEntity.setDetailsJson(mapper.writeValueAsString(result)); } else { eventEntity.setDetailsJson(mapper.writeValueAsString(event.getDetails())); } } catch (IOException ex) { logger.error("Failed to write log details", ex); } return eventEntity; }</code><technical_language>suggestion if (maxDetailLength > 0 && event.getDetails() != null) {</technical_language>

Target:
private EventEntity convertEvent(Event event) { EventEntity eventEntity = new EventEntity(); eventEntity.setId(UUID.randomUUID().toString()); eventEntity.setTime(event.getTime()); eventEntity.setType(event.getType().toString()); eventEntity.setRealmId(event.getRealmId()); eventEntity.setClientId(event.getClientId()); eventEntity.setUserId(event.getUserId()); eventEntity.setSessionId(event.getSessionId()); eventEntity.setIpAddress(event.getIpAddress()); eventEntity.setError(event.getError()); try { if (maxDetailLength > 0 && event.getDetails() != null) { Map<String, String> result = new HashMap<>(event.getDetails()); result.entrySet().forEach(t -> t.setValue(trimToMaxLength(t.getValue()))); eventEntity.setDetailsJson(mapper.writeValueAsString(result)); } else { eventEntity.setDetailsJson(mapper.writeValueAsString(event.getDetails())); } } catch (IOException ex) { logger.error("Failed to write log details", ex); } return eventEntity; }
Source:
<code>void partitionTasks() { ArrayList<TopPath> topPaths = computeTopPaths(); Iterator<TopPath> topPathItr = topPaths.iterator(); int nextTop = 0; long weightPerThread = totalWeight / threads; for (int i = beginIndex; i < endIndex;) { DeltaTask task = new DeltaTask(this); long w = 0; if (topPathItr.hasNext()) { TopPath p = topPathItr.next(); w += p.weight; task.add(p.slice); } int s = i; for (; w < weightPerThread && i < endIndex;) { if (nextTop < topPaths.size() <START> && i == topPaths.get(nextTop).slice.beginIndex) { <END> if (s < i) task.add(new Slice(s, i)); s = i = topPaths.get(nextTop++).slice.endIndex; } else w += list[i++].getWeight(); } if (s < i) { int h = list[i - 1].getPathHash(); while (i < endIndex) { if (h == list[i].getPathHash()) i++; else break; } task.add(new Slice(s, i)); } if (!task.slices.isEmpty()) tasks.add(task); } while (topPathItr.hasNext()) { TopPath p = topPathItr.next(); DeltaTask task = new DeltaTask(this); task.add(p.slice); tasks.add(task); } topPaths = null; }</code><technical_language>making this more complicated needs be. If returned arrays, for top paths for other paths, this logic. other array threads + 1 length this overlap logic. but, logic ok</technical_language>

Target:
void partitionTasks() { ArrayList<WeightedPath> topPaths = computeTopPaths(); Iterator<WeightedPath> topPathItr = topPaths.iterator(); int nextTop = 0; long weightPerThread = totalWeight / threads; for (int i = beginIndex; i < endIndex;) { DeltaTask task = new DeltaTask(this); long w = 0; if (topPathItr.hasNext()) { WeightedPath p = topPathItr.next(); w += p.weight; task.add(p.slice); } int s = i; for (; w < weightPerThread && i < endIndex;) { if (nextTop < topPaths.size() && i == topPaths.get(nextTop).slice.beginIndex) { if (s < i) task.add(new Slice(s, i)); s = i = topPaths.get(nextTop++).slice.endIndex; } else w += list[i++].getWeight(); } if (s < i) { int h = list[i - 1].getPathHash(); while (i < endIndex) { if (h == list[i].getPathHash()) i++; else break; } task.add(new Slice(s, i)); } if (!task.slices.isEmpty()) tasks.add(task); } while (topPathItr.hasNext()) { WeightedPath p = topPathItr.next(); DeltaTask task = new DeltaTask(this); task.add(p.slice); tasks.add(task); } topPaths = null; }
Source:
<code>static boolean isValidMining(ICodeMining mining) { <START> return Objects.nonNull(mining) && mining.getLabel() != null && !mining.getLabel().isEmpty(); <END> }</code><technical_language>Objects.nonNull instead of != null</technical_language>

Target:
static boolean isValidMining(ICodeMining mining) { return mining != null && mining.getLabel() != null && !mining.getLabel().isEmpty(); }
Source:
<code>public static boolean isExecute(ModelControllerClient client, String[] parent, OperationRequestAddress address, String operation) { final ModelNode accessControl = getAccessControl(client, parent, address, true); if(accessControl == null) { return false; } if(!accessControl.has(Util.DEFAULT)) { log.warn("access-control is missing defaults: " + accessControl); return false; } final ModelNode defaults = accessControl.get(Util.DEFAULT); if(!defaults.has(Util.OPERATIONS)) { log.warn("access-control/default is missing operations: " + defaults); return false; } final ModelNode operations = defaults.get(Util.OPERATIONS); if(!operations.has(operation)) { <START> log.trace("The operation is missing in the description: " + operation); <END> return false; } final ModelNode opAC = operations.get(operation); if(!opAC.has(Util.EXECUTE)) { log.warnf("'execute' is missing for %s in %s", operation, accessControl); return false; } return opAC.get(Util.EXECUTE).asBoolean(); }</code><technical_language>tracef</technical_language>

Target:
public static boolean isExecute(ModelControllerClient client, String[] parent, OperationRequestAddress address, String operation) { final ModelNode accessControl = getAccessControl(client, parent, address, true); if(accessControl == null) { return false; } if(!accessControl.has(Util.DEFAULT)) { log.warnf("access-control is missing defaults: %s", accessControl); return false; } final ModelNode defaults = accessControl.get(Util.DEFAULT); if(!defaults.has(Util.OPERATIONS)) { log.warnf("access-control/default is missing operations: %s", defaults); return false; } final ModelNode operations = defaults.get(Util.OPERATIONS); if(!operations.has(operation)) { log.tracef("The operation is missing in the description: %s", operation); return false; } final ModelNode opAC = operations.get(operation); if(!opAC.has(Util.EXECUTE)) { log.warnf("'execute' is missing for %s in %s", operation, accessControl); return false; } return opAC.get(Util.EXECUTE).asBoolean(); }
Source:
<code>public boolean processLine(String line) { String lineTrimmed = line.trim(); lineCounter++; ProblemMarkerInfo marker=null; outer: for (IErrorParser[] parsers : fErrorParsers.values()) { for (IErrorParser parser : parsers) { IErrorParser curr = parser; if (parser instanceof ErrorParserNamedWrapper) { curr = ((ErrorParserNamedWrapper)parser).getErrorParser(); } int types = IErrorParser2.NONE; if (curr instanceof IErrorParser2) { types = ((IErrorParser2) curr).getProcessLineBehaviour(); } if ((types & IErrorParser2.KEEP_LONGLINES) == 0) { <START> if (lineTrimmed.length() > 1000) <END> continue; } String lineToParse = lineTrimmed; if ((types & IErrorParser2.KEEP_UNTRIMMED) !=0 ) { lineToParse = line; } boolean consume = false; try { consume = curr.processLine(lineToParse, this); } catch (Exception e){ String id = ""; if (parser instanceof IErrorParserNamed) id = ((IErrorParserNamed)parser).getId(); @SuppressWarnings("nls") String message = "Errorparser " + id + " failed parsing line [" + lineToParse + "]"; CCorePlugin.log(message, e); } finally { if (fErrors.size() > 0) { if (marker==null) marker = fErrors.get(0); fErrors.clear(); } } if (consume) break outer; } } outputLine(line, marker); return false; }</code><technical_language>Please bring braces back</technical_language>

Target:
public boolean processLine(String line) { String lineTrimmed = line.trim(); lineCounter++; ProblemMarkerInfo marker=null; outer: for (IErrorParser[] parsers : fErrorParsers.values()) { for (IErrorParser parser : parsers) { IErrorParser curr = parser; if (parser instanceof ErrorParserNamedWrapper) { curr = ((ErrorParserNamedWrapper)parser).getErrorParser(); } int types = IErrorParser2.NONE; if (curr instanceof IErrorParser2) { types = ((IErrorParser2) curr).getProcessLineBehaviour(); } if ((types & IErrorParser2.KEEP_LONGLINES) == 0) { if (lineTrimmed.length() > 1000) { continue; } } String lineToParse = lineTrimmed; if ((types & IErrorParser2.KEEP_UNTRIMMED) !=0 ) { lineToParse = line; } boolean consume = false; try { consume = curr.processLine(lineToParse, this); } catch (Exception e){ String id = ""; if (parser instanceof IErrorParserNamed) { id = ((IErrorParserNamed) parser).getId(); } @SuppressWarnings("nls") String message = "Errorparser " + id + " failed parsing line [" + lineToParse + "]"; CCorePlugin.log(message, e); } finally { if (fErrors.size() > 0) { if (marker==null) { marker = fErrors.get(0); } fErrors.clear(); } } if (consume) { break outer; } } } outputLine(line, marker); return false; }
Source:
<code>public void garbageCollect() throws Exception { if (!systemEnvironment.get(SystemEnvironment.GO_CONFIG_REPO_PERIODIC_GC)) { return; } doLocked(new VoidThrowingFn<Exception>() { public void run() throws Exception { try { LOGGER.info("Before GC: {}", git.gc().getStatistics()); long date = systemEnvironment.getConfigGitGCExpireTime(); git.gc().setAggressive(systemEnvironment.get(SystemEnvironment.GO_CONFIG_REPO_GC_AGGRESSIVE)) <START> .setExpire(new Date(System.currentTimeMillis() - date)) <END> .call(); LOGGER.info("After GC: {}", git.gc().getStatistics()); } catch (GitAPIException e) { LOGGER.error("Could not perform GC", e); throw e; } } }); }</code><technical_language>Rename date variable more meaningful, expireAge better</technical_language>

Target:
public void garbageCollect() throws Exception { if (!systemEnvironment.get(SystemEnvironment.GO_CONFIG_REPO_PERIODIC_GC)) { return; } doLocked(new VoidThrowingFn<Exception>() { public void run() throws Exception { try { LOGGER.info("Before GC: {}", git.gc().getStatistics()); long expireTimeInMs = systemEnvironment.getConfigGitGCExpireTime(); git.gc().setAggressive(systemEnvironment.get(SystemEnvironment.GO_CONFIG_REPO_GC_AGGRESSIVE)) .setExpire(new Date(System.currentTimeMillis() - expireTimeInMs)) .call(); LOGGER.info("After GC: {}", git.gc().getStatistics()); } catch (GitAPIException e) { LOGGER.error("Could not perform GC", e); throw e; } } }); }
Source:
<code>public String nextLotteryInvestAmount(){ long totalAmount = investMapper.sumInvestAmountRanking(activityIphone7StartTime, activityIphone7EndTime); int currentLotteryInvestAmount = iPhone7LotteryConfigMapper.getCurrentLotteryInvestAmount(); <START> long nextLotteryInvestAmount = (totalAmount - currentLotteryInvestAmount * 1000000) <= 0 ? 50000000 : (totalAmount - currentLotteryInvestAmount * 1000000); <END> return AmountConverter.convertCentToString(nextLotteryInvestAmount); }</code><technical_language>50 - .</technical_language>

Target:
public String nextLotteryInvestAmount(){ long totalAmount = investMapper.sumInvestAmountIphone7(activityIphone7StartTime, activityIphone7EndTime); int currentLotteryInvestAmount = iPhone7LotteryConfigMapper.getCurrentLotteryInvestAmount(); long nextLotteryInvestAmount = (totalAmount - currentLotteryInvestAmount * 1000000) <= 0 ? 50000000 : (50000000 - (totalAmount - currentLotteryInvestAmount * 1000000)); return AmountConverter.convertCentToString(nextLotteryInvestAmount); }
Source:
<code>private void removeChildren(Guid snapshot) { List<DiskImage> children = new ArrayList<>(); getImageChildren(snapshot, children); <START> children.stream().sorted(Collections.reverseOrder()).forEach(this::removeSnapshot); <END> }</code><technical_language>reason reverse order do DiskImage instead of Guid order changed. If is reason add this order I suggest remove completely</technical_language>

Target:
private void removeChildren(Guid snapshot) { List<DiskImage> children = new ArrayList<>(); getImageChildren(snapshot, children); Collections.reverse(children); children.stream().forEach(this::removeSnapshot); }
Source:
<code>StreamSession deriveSession(StreamMessage message) { StreamSession streamSession = null; if (message instanceof StreamInitMessage) { assert session == null : "initiator of stream session received a StreamInitMessage"; StreamInitMessage init = (StreamInitMessage) message; StreamResultFuture.createFollower(init.sessionIndex, init.planId, init.streamOperation, init.from, channel, init.pendingRepair, init.previewKind); streamSession = sessionProvider.apply(new SessionIdentifier(init.from, init.planId, init.sessionIndex)); } else if (message instanceof IncomingStreamMessage) { StreamMessageHeader header = ((IncomingStreamMessage) message).header; streamSession = sessionProvider.apply(new SessionIdentifier(header.sender, header.planId, header.sessionIndex)); } if (streamSession == null) throw new IllegalStateException(createLogTag(null, channel) + " no session found for message " + message); <START> streamSession.attachInbound(channel); <END> return streamSession; }</code><technical_language>attach inbound control channel receiving a StreamInitMessage</technical_language>

Target:
StreamSession deriveSession(StreamMessage message) { StreamSession streamSession = null; if (message instanceof StreamInitMessage) { assert session == null : "initiator of stream session received a StreamInitMessage"; StreamInitMessage init = (StreamInitMessage) message; StreamResultFuture.createFollower(init.sessionIndex, init.planId, init.streamOperation, init.from, channel, init.pendingRepair, init.previewKind); streamSession = sessionProvider.apply(new SessionIdentifier(init.from, init.planId, init.sessionIndex)); } else if (message instanceof IncomingStreamMessage) { StreamMessageHeader header = ((IncomingStreamMessage) message).header; streamSession = sessionProvider.apply(new SessionIdentifier(header.sender, header.planId, header.sessionIndex)); } if (streamSession == null) throw new IllegalStateException(createLogTag(null, channel) + " no session found for message " + message); streamSession.attachInbound(channel, message instanceof StreamInitMessage); return streamSession; }
Source:
<code><START> public void canGetJson() throws Exception { <END> final File file = File.createTempFile("jcabi-github", ".xml"); final MkStorage storage = new MkStorage.InFile(file); final StringBuffer contentBuffer = new StringBuffer(); contentBuffer.append("<github><repos>"); contentBuffer.append("<repo coords='test_login/test_repo'>"); contentBuffer.append("<commits><commit sha='"); contentBuffer.append(SHA1); contentBuffer.append("'>"); contentBuffer.append("Hello world</commit></commits></repo>"); contentBuffer.append("</repos></github>"); Files.write(contentBuffer.toString().getBytes(), file); final MkRepoCommit repoCommit = new MkRepoCommit( storage, this.repo(storage), SHA1); MatcherAssert.assertThat( repoCommit.json(), Matchers.notNullValue() ); }</code><technical_language>create some structure storage MkStorage.apply( ... ) method. MkIssues.create() for example. Try avoid creation of github, repos, repo nodes manually. there, if create new MkRepo storage</technical_language>

Target:
public void canGetJson() throws Exception { final MkStorage storage = new MkStorage.InFile(); storage.apply( new Directives().xpath("/github").add("repos") .add("repo").attr("coords", "test_login/test_repo") .add("commits").add("commit").attr("sha", SHA1) .set("Hello world") ); final MkRepoCommit repoCommit = new MkRepoCommit( storage, this.repo(storage), SHA1 ); MatcherAssert.assertThat( repoCommit.json(), Matchers.notNullValue() ); }
Source:
<code><START> public boolean isRelativeMissingFileSuffix(String href) { <END> String[] names = href.split("/"); String name = names[names.length - 1]; return (name.indexOf('.') == -1 && !ABSOLUTE_URL_PATTERN.matcher(href).matches()); }</code><technical_language>please this method private API</technical_language>

Target:
private boolean isRelativeMissingFileSuffix(String href) { String name = href; if (name.indexOf('/') > -1) { name = name.substring(name.lastIndexOf('/')); } return (name.indexOf('.') == -1 && !ABSOLUTE_URL_PATTERN.matcher(href).matches()); }
Source:
<code>private Function<List<Stream<Double>>, Long> reduceBricksToSize(GlusterVolumeEntity volume) { return (List<Stream<Double>> data) -> { switch (volume.getVolumeType()) { case REPLICATE: return data.stream().flatMap(Function.identity()).map(v -> v * SizeConverter.BYTES_IN_MB).map(Double::longValue).min(Long::compare).orElse(null); <START> case DISTRIBUTED_REPLICATE: <END> return data.stream() .map(b -> b.map(v -> v * SizeConverter.BYTES_IN_MB).map(Double::longValue).min(Long::compare).orElse(null)) .filter(Objects::nonNull) .min(Long::compare) .orElse(null); case DISTRIBUTE: case STRIPE: case DISTRIBUTED_STRIPE: case STRIPED_REPLICATE: case DISTRIBUTED_STRIPED_REPLICATE: case DISPERSE: default: return data.stream().flatMap(Function.identity()).map(v -> v * SizeConverter.BYTES_IN_MB).mapToLong(Double::longValue).sum(); } }; }</code><technical_language>map function for replica/distribute-replica</technical_language>

Target:
private Function<List<Stream<Double>>, Long> reduceBricksToSize(GlusterVolumeEntity volume) { return (List<Stream<Double>> data) -> { switch (volume.getVolumeType()) { case REPLICATE: return data.stream().flatMap(Function.identity()).map(v -> v * SizeConverter.BYTES_IN_MB).map(Double::longValue).min(Long::compare).orElse(null); case DISTRIBUTED_REPLICATE: return data.stream() .map(b -> b.map(v -> v * SizeConverter.BYTES_IN_MB).map(Double::longValue).min(Long::compare).orElse(null)) .filter(Objects::nonNull) .mapToLong(s-> s) .sum(); case DISTRIBUTE: case STRIPE: case DISTRIBUTED_STRIPE: case STRIPED_REPLICATE: case DISTRIBUTED_STRIPED_REPLICATE: case DISPERSE: default: return data.stream().flatMap(Function.identity()).map(v -> v * SizeConverter.BYTES_IN_MB).mapToLong(Double::longValue).sum(); } }; }
Source:
<code>public Object create(NewOperator operator) { <START> Long count = datastore.entityCount(OperatorEntity.class, Filter.where("name").is(operator.name)); <END> if (count != 0) { throw new OperatorException("Operator with name: " + operator.name + " already exists."); } return datastore.save(adapt(operator)); }</code><technical_language>NewOperatorEntity.class</technical_language>

Target:
public Object create(NewOperator operator) { Long count = datastore.entityCount(NewOperatorEntity.class, Filter.where("name").is(operator.name)); if (count != 0) { throw new OperatorException("Operator with name: " + operator.name + " already exists."); } return datastore.save(adapt(operator)); }
Source:
<code>private void addExpectedMessage(int line, int column, String construct) { this.expectedMessages.add( Printer.genOutputStringForTest( Rules.REDUNDANT_OPTIONAL_BINDING, inputFile.getName(), line, column, Severity.WARNING, <START> Messages.CONSECUTIVE + "'" + construct + "' " + Messages.AT_COLUMN + column <END> + Messages.REDUNDANT_OPTIONAL_BINDING ) ); }</code><technical_language>Hmm, 'var' column 26 is redundant removed? I usual style, more sense 'consecutive' misleading point out actual problem</technical_language>

Target:
private void addExpectedMessage(int line, int column, String construct) { this.expectedMessages.add( Printer.genOutputStringForTest( Rules.REDUNDANT_OPTIONAL_BINDING, inputFile.getName(), line, column, Severity.WARNING, Messages.REDUNDANT + "'" + construct + "' " + Messages.AT_COLUMN + column + Messages.REDUNDANT_OPTIONAL_BINDING ) ); }
Source:
<code><START> public String getCAConfPath(CAType caType) { <END> switch (caType) { case ROOT: return Paths.get(settings.getCaDir(), "openssl-ca.cnf").toString(); case INTERMEDIATE: return Paths.get(settings.getIntermediateCaDir(), "openssl-intermediate.cnf").toString(); default: throw new IllegalArgumentException("CA type not recognized"); } }</code><technical_language>for type safety return type Path</technical_language>

Target:
public Path getCAConfPath(CAType caType) { switch (caType) { case ROOT: return Paths.get(settings.getCaDir(), "openssl-ca.cnf"); case INTERMEDIATE: return Paths.get(settings.getIntermediateCaDir(), "openssl-intermediate.cnf"); default: throw new IllegalArgumentException("CA type not recognized"); } }