auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void setDisplayedTypeCall(QBRTCTypes.QBConferenceType conferenceType) { boolean isVideoCall = conferenceType == QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_VIDEO; callTypeTextView.setText(getString(isVideoCall ? R.string.incoming_video_call : R.string.incoming_audio_call)); takeButton.setImageResource(isVideoCall ? R.drawable.ic_video_white : R.drawable.ic_call); }

Target:
private void setDisplayedTypeCall(QBRTCTypes.QBConferenceType conferenceType) { boolean isVideoCall = conferenceType == QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_VIDEO; callTypeTextView.setText(isVideoCall ? R.string.incoming_video_call : R.string.incoming_audio_call); takeButton.setImageResource(isVideoCall ? R.drawable.ic_video_white : R.drawable.ic_call); }
Source:
public static URL getResourceRoot(String name) throws IOException { URL url = ResourceLoader.class.getResource("/" + name); if (url == null) { try { return getResourceForgeHack(name); } catch (Exception e) { throw new IOException("Could not find " + name); } } return url; }

Target:
public static URL getResourceRoot(String name) throws IOException { URL url = ResourceLoader.class.getResource("/" + name); if (url == null) { return getResourceForgeHack(name); } return url; }
Source:
public Mask parseFromInput(String input, ParserContext context) throws InputParseException { if (input.startsWith("##")) { Extent extent = Request.request().getEditSession(); // This means it's a tag mask. BlockCategory category = BlockCategories.get(input.substring(2).toLowerCase()); if (category == null) { throw new InputParseException("Unrecognised tag '" + input.substring(2) + '\''); } else { return new BlockCategoryMask(extent, category); } } return null; }

Target:
public Mask parseFromInput(String input, ParserContext context) throws InputParseException { if (!input.startsWith("##")) { return null; } Extent extent = Request.request().getEditSession(); // This means it's a tag mask. BlockCategory category = BlockCategories.get(input.substring(2).toLowerCase()); if (category == null) { throw new InputParseException("Unrecognised tag '" + input.substring(2) + '\''); } else { return new BlockCategoryMask(extent, category); } }
Source:
public void setWorkingSolution(Solution_ workingSolution) { Objects.requireNonNull(workingSolution); this.workingSolution = workingSolution; SolutionDescriptor<Solution_> solutionDescriptor = getSolutionDescriptor(); workingInitScore = - solutionDescriptor.countUninitializedVariables(workingSolution); if (lookUpEnabled) { lookUpManager.resetWorkingObjects(solutionDescriptor.getAllFacts(workingSolution)); } variableListenerSupport.resetWorkingSolution(); setWorkingEntityListDirty(); }

Target:
public void setWorkingSolution(Solution_ workingSolution) { this.workingSolution = Objects.requireNonNull(workingSolution); SolutionDescriptor<Solution_> solutionDescriptor = getSolutionDescriptor(); workingInitScore = - solutionDescriptor.countUninitializedVariables(workingSolution); if (lookUpEnabled) { lookUpManager.resetWorkingObjects(solutionDescriptor.getAllFacts(workingSolution)); } variableListenerSupport.resetWorkingSolution(); setWorkingEntityListDirty(); }
Source:
public static <Solution_> SolverFactory<Solution_> create(SolverConfig solverConfig) { return new DefaultSolverFactory<>(solverConfig); }

Target:
public static <Solution_> SolverFactory<Solution_> create(SolverConfig solverConfig) { // Does defensive copy of solverConfig, because the DefaultSolverFactory doesn't internalize it yet solverConfig = new SolverConfig(solverConfig); return new DefaultSolverFactory<>(solverConfig); }
Source:
public void fireSolvingStarted(DefaultSolverScope<Solution_> solverScope) { // Listeners can only be removed/added from the solver thread: no ConcurrentModificationException if (eventListenerSet.isEmpty()) { return; } final SolvingStartedEvent<Solution_> event = new SolvingStartedEvent<>(solver); for (SolverListener<Solution_> listener : eventListenerSet) { listener.solvingStarted(event); } }

Target:
public void fireSolvingStarted(DefaultSolverScope<Solution_> solverScope) { // Listeners can only be removed/added from the solver thread: no ConcurrentModificationException if (eventListenerSet.isEmpty()) { return; } final SolvingStartedEvent event = new SolvingStartedEvent(solver); for (SolverListener listener : eventListenerSet) { listener.solvingStarted(event); } }
Source:
public void testKJarNotAvailable() { boolean caughtException = false; ScoreKJarReleaseIdConfig config = new ScoreKJarReleaseIdConfig(); config.setGroupId(groupId); config.setArtifactId(artifactId); //Use a non-existing version. config.setVersion("1.0.1"); DroolsScoreDirectorFactory scoreDirectorFactory = config.build(); }

Target:
public void testKJarNotAvailable() { ScoreKJarReleaseIdConfig config = new ScoreKJarReleaseIdConfig(); config.setGroupId(groupId); config.setArtifactId(artifactId); //Use a non-existing version. config.setVersion("1.0.1"); DroolsScoreDirectorFactory scoreDirectorFactory = config.build(); }
Source:
private void verifyDistributedObjectEvent(final Message<?> msg, final DistributedObjectEvent.EventType eventType, final String distributedObjectName) { assertNotNull(msg); assertNotNull(msg.getPayload()); assertTrue(msg.getPayload() instanceof DistributedObjectEvent); assertEquals(((DistributedObjectEvent) msg.getPayload()).getEventType(), eventType); assertNotNull( (((DistributedObjectEvent) msg.getPayload()).getDistributedObject()) .getName(), distributedObjectName); }

Target:
private void verifyDistributedObjectEvent(final Message<?> msg, final DistributedObjectEvent.EventType eventType, final String distributedObjectName) { assertNotNull(msg); assertNotNull(msg.getPayload()); assertTrue(msg.getPayload() instanceof DistributedObjectEvent); assertEquals(eventType, ((DistributedObjectEvent) msg.getPayload()).getEventType()); assertNotNull( (((DistributedObjectEvent) msg.getPayload()).getDistributedObject()) .getName(), distributedObjectName); }
Source:
public void handleMessage(Message<?> message) throws MessagingException { try { // todo support a gateway and have that gateway also handle message delivery receipt notifications // that will correlate this smsMessageId with the ID that comes back asynchronously from the SMSC indicating that // the message has been delivered. // this could require that we keep a correlation map since its possible upstream SMSC // unused return value -- see gateway SmesMessageSpecification specification = applyDefaultsIfNecessary( SmesMessageSpecification.fromMessage(this.smppSession, message) .setTimeFormatter(this.timeFormatter)); String[] smsMessageId = specification.send(); logger.debug( "sent message : "+message.getPayload()); logger.debug("message ID(s) for the sent message: " + Arrays.toString(smsMessageId)); } catch (Exception e) { throw new RuntimeException("Exception in trying to process the inbound SMPP message", e); } }

Target:
public void handleMessage(Message<?> message) throws MessagingException { try { // todo support a gateway and have that gateway also handle message delivery receipt notifications // that will correlate this smsMessageId with the ID that comes back asynchronously from the SMSC indicating that // the message has been delivered. // this could require that we keep a correlation map since its possible upstream SMSC // unused return value -- see gateway SmesMessageSpecification specification = applyDefaultsIfNecessary( SmesMessageSpecification.fromMessage(this.smppSession, message) .setTimeFormatter(this.timeFormatter)); List<String> smsMessageId = specification.send(); logger.debug( "sent message : "+message.getPayload()); logger.debug("message ID(s) for the sent message: " + smsMessageId); } catch (Exception e) { throw new RuntimeException("Exception in trying to process the inbound SMPP message", e); } }
Source:
private char[] fileToCharArray(File file) throws IOException { FileInputStream is = new FileInputStream(file); try { return streamToCharArray(is); } finally { is.close(); } }

Target:
private static char[] fileToCharArray(File file) throws IOException { FileInputStream is = new FileInputStream(file); try { return streamToCharArray(is); } finally { is.close(); } }
Source:
boolean uploadFormDataToServer(List<FormData> allFormData, boolean result) throws IOException { for (FormData formData : allFormData) { String rawPayload = formData.getJsonPayload(); System.out.println(rawPayload); // inject consultation.sourceUuid formData = injectUuidToPayload(formData); // replace media paths with base64 string formData = replaceMediaPathWithBase64String(formData); if (formService.syncFormData(formData)) { formData.setStatus(STATUS_UPLOADED); //DO NOT save base64 string in DB formData.setJsonPayload(rawPayload); formService.saveFormData(formData); } else { result = false; } } return result; }

Target:
boolean uploadFormDataToServer(List<FormData> allFormData, boolean result) throws IOException { for (FormData formData : allFormData) { String rawPayload = formData.getJsonPayload(); // inject consultation.sourceUuid formData = injectUuidToPayload(formData); // replace media paths with base64 string formData = replaceMediaPathWithBase64String(formData); if (formService.syncFormData(formData)) { formData.setStatus(STATUS_UPLOADED); //DO NOT save base64 string in DB formData.setJsonPayload(rawPayload); formService.saveFormData(formData); } else { result = false; } } return result; }
Source:
public void onKeyboardClosed() { fabSearchButton.setVisibility(View.VISIBLE); // fabSearchButton.setFocusable(true); // boolean f=fabSearchButton.requestFocus(); listView.clearChoices(); if(getCurrentFocus() != null) { System.out.println("Current focus: " + getCurrentFocus().toString()); } else { System.out.println("Current focus: null"); } }

Target:
public void onKeyboardClosed() { fabSearchButton.setVisibility(View.VISIBLE); listView.clearChoices(); }
Source:
public void sendLastNEndpointsChangeEvent( Collection<String> forwardedEndpoints, Collection<String> endpointsEnteringLastN, Collection<String> conferenceEndpoints) { // We want endpointsEnteringLastN to always to reported. Consequently, // we will pretend that all lastNEndpoints are entering if no explicit // endpointsEnteringLastN is specified. // XXX do we really want that? if (endpointsEnteringLastN == null) { endpointsEnteringLastN = forwardedEndpoints; } String msg = createLastNEndpointsChangeEvent( forwardedEndpoints, endpointsEnteringLastN, conferenceEndpoints); sendMessage(msg); notifyForwardedEndpointsChanged(forwardedEndpoints, endpointsEnteringLastN, conferenceEndpoints); }

Target:
private void sendLastNEndpointsChangeEvent( Collection<String> forwardedEndpoints, Collection<String> endpointsEnteringLastN, Collection<String> conferenceEndpoints) { // We want endpointsEnteringLastN to always to reported. Consequently, // we will pretend that all lastNEndpoints are entering if no explicit // endpointsEnteringLastN is specified. // XXX do we really want that? if (endpointsEnteringLastN == null) { endpointsEnteringLastN = forwardedEndpoints; } String msg = createLastNEndpointsChangeEvent( forwardedEndpoints, endpointsEnteringLastN, conferenceEndpoints); sendMessage(msg); }
Source:
public Integer getInteger(String key, int defaultValue) { return parseValueOrDefault(key, Integer::parseInt, defaultValue); }

Target:
public int getInteger(String key, int defaultValue) { return parseValueOrDefault(key, Integer::parseInt, defaultValue); }
Source:
public Response toResponseInternal(Response.StatusType status, LoggingLevel loggingLevel, T exception) { logException(exception, loggingLevel); return serializeException(status, exception); }

Target:
protected Response toResponseInternal(Response.StatusType status, LoggingLevel loggingLevel, T exception) { logException(exception, loggingLevel); return serializeException(status, exception); }
Source:
private static boolean isMasterDataSource() { String dataSourceName = DataSourceContextUnsafe.getDataSourceType(); return dataSourceName == null || MASTER.equals(dataSourceName); }

Target:
private static boolean isMasterDataSource() { String dataSourceName = DataSourceContextUnsafe.getDataSourceType(); return MASTER.equals(dataSourceName); }
Source:
public String[] getPackagesToScan() { return packagesToScan.toArray(new String[packagesToScan.size()]); }

Target:
public String[] getPackagesToScan() { return packagesToScan.toArray(new String[0]); }
Source:
public static KFunction<?> findKotlinFunction(Method method) { KFunction<?> kotlinFunction = ReflectJvmMapping.getKotlinFunction(method); if (kotlinFunction == null) { // Fallback to own lookup because there's no public Kotlin API for that kind of lookup until // https://youtrack.jetbrains.com/issue/KT-20768 gets resolved. return findKFunction(method).orElse(null); } return kotlinFunction; }

Target:
public static KFunction<?> findKotlinFunction(Method method) { KFunction<?> kotlinFunction = ReflectJvmMapping.getKotlinFunction(method); // Fallback to own lookup because there's no public Kotlin API for that kind of lookup until // https://youtrack.jetbrains.com/issue/KT-20768 gets resolved. return kotlinFunction == null ? findKFunction(method).orElse(null) : kotlinFunction; }
Source:
Class<?> getRepositoryInterfaceFrom(BeanDefinition beanDefinition) { if (beanDefinition instanceof ScannedGenericBeanDefinition) { try { return ((ScannedGenericBeanDefinition) beanDefinition).resolveBeanClass(beanClassLoader); } catch (ClassNotFoundException e) { throw new IllegalStateException("Could not resolve bean class.", e); } } else { return getRepositoryInterfaceFromFactory(beanDefinition); } }

Target:
private Class<?> getRepositoryInterfaceFrom(BeanDefinition beanDefinition) { if (beanDefinition instanceof ScannedGenericBeanDefinition) { try { return ((ScannedGenericBeanDefinition) beanDefinition).resolveBeanClass(beanClassLoader); } catch (ClassNotFoundException e) { throw new IllegalStateException("Could not resolve bean class.", e); } } else { return getRepositoryInterfaceFromFactory(beanDefinition); } }
Source:
private boolean isSimpleSearch(String query) { return Arrays.stream(AdvancedSearchTerms.class.getEnumConstants()) .noneMatch(e -> query.contains(e.text)); }

Target:
private boolean isSimpleSearch(String query) { return Arrays.stream(AdvancedSearchTerms.values()).noneMatch(e -> query.contains(e.text)); }
Source:
public static String convertStreamToString(java.io.InputStream is) { java.util.Scanner scanner = null; String result=""; try { scanner = new java.util.Scanner(is).useDelimiter("\\A"); result = scanner.hasNext() ? scanner.next() : ""; scanner.close(); } finally { if(scanner!=null) scanner.close(); } return result; }

Target:
private static String convertStreamToString(java.io.InputStream is) { java.util.Scanner scanner = null; String result=""; try { // The delimiter is \A which means "beginning of input". That can't match anything later in the input. // So it will read everything in to the end of the stream. scanner = new java.util.Scanner(is).useDelimiter("\\A"); result = scanner.hasNext() ? scanner.next() : ""; scanner.close(); } finally { if(scanner!=null) { scanner.close(); } } return result; }
Source:
public String getFeedId() { if (code != null && code.length() > 0) { // The key stored in patternForId is the pattern code that is constructed as. // Agency:RouteId:DirectionId:PatternNumber, the first part is the feed id. return code.substring(0, code.indexOf(':')); } // If we cant obtain the feed id from the code, we can get it from the route. return route.getId().getAgencyId(); }

Target:
public String getFeedId() { // The feed id is the same as the agency id on the route, this allows us to obtain it from there. return route.getId().getAgencyId(); }
Source:
private static boolean isLowMemoryDevice(ActivityManager activityManager) { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && activityManager.isLowRamDevice(); }

Target:
private static boolean isLowMemoryDevice(ActivityManager activityManager) { // Explicitly check with an if statement, on some devices both parts of boolean expressions // can be evaluated even if we'd normally expect a short circuit. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { return activityManager.isLowRamDevice(); } else { return false; } }
Source:
public void testSetModulesEnabledFalse() throws Exception { // teaDown glide instance first so we have a clean slate and not the Glide.get() call in setUp Glide.tearDown(); Glide.setModulesEnabled(false); try { Glide glide = Glide.get(getContext()); List<ModelLoader<GlideUrl, ?>> modelLoaders = glide.getRegistry().getModelLoaders(mock(GlideUrl.class)); // With modules disabled, SetupModule below should not have been initialized, // so the default modelLoader should remain assertEquals(1, modelLoaders.size()); assertTrue(modelLoaders.get(0) instanceof HttpGlideUrlLoader); } finally { Glide.setModulesEnabled(true); } }

Target:
public void testSetModulesEnabledFalse() throws Exception { // tearDown glide instance first so we have a clean slate and not the Glide.get() call in setUp Glide.tearDown(); Glide.setModulesEnabled(false); Glide glide = Glide.get(getContext()); List<ModelLoader<GlideUrl, ?>> modelLoaders = glide.getRegistry().getModelLoaders(mock(GlideUrl.class)); // With modules disabled, SetupModule below should not have been initialized, // so the default modelLoader should remain assertEquals(1, modelLoaders.size()); assertTrue(modelLoaders.get(0) instanceof HttpGlideUrlLoader); }
Source:
public void bbCodesWithTextThatShouldFail(String postBody, String messageIfTestFails) throws Exception { info("Running a test case [" + messageIfTestFails + "]"); try { Topics.postAnswer(TEST_TOPIC, new Post(postBody)); //should throw exception if validation failed fail(messageIfTestFails); } catch (ValidationException e) { //if validation error happened, then the test passed } catch (CouldNotOpenPageException e) { fail("Something went wrong and user was thrown out of topic."); } }

Target:
public void bbCodesWithTextThatShouldFail(String postBody, String messageIfTestFails) throws Exception { info("Running a test case [" + messageIfTestFails + "]"); try { Topics.postAnswer(TEST_TOPIC, new Post(postBody)); //should throw exception if validation failed fail(messageIfTestFails); } catch (ValidationException e) { //if validation error happened, then the test passed } }
Source:
public void bbCodesWithTextThatShouldPass(String postBody, String messageIfTestFails) throws Exception { info("Running a test case [" + messageIfTestFails + "]"); try { Topics.postAnswer(TEST_TOPIC, new Post(postBody)); //should throw exception if validation failed } catch (ValidationException e) { fail(messageIfTestFails); //if validation error happened, then the test failed } catch (CouldNotOpenPageException e) { fail("Something went wrong and user was thrown out of topic."); } }

Target:
public void bbCodesWithTextThatShouldPass(String postBody, String messageIfTestFails) throws Exception { info("Running a test case [" + messageIfTestFails + "]"); try { Topics.postAnswer(TEST_TOPIC, new Post(postBody)); //should throw exception if validation failed } catch (ValidationException e) { fail(messageIfTestFails); //if validation error happened, then the test failed } }
Source:
public Qualifiers(Qualifiers other) { this.resolvers.addAll(other.resolvers); this.registry = null; }

Target:
private Qualifiers(Qualifiers other) { this.resolvers.addAll(other.resolvers); this.registry = null; }
Source:
private TemporalUnitOffset getAllowableOffset() { // PostgreSQL seems to not have as much precision on Windows as it does on Linux. if (SystemUtils.IS_OS_WINDOWS) { return within(0, ChronoUnit.MICROS); } else { return within(0, ChronoUnit.NANOS); } }

Target:
private TemporalUnitOffset getAllowableOffset() { // PostgreSQL seems to not have as much precision on Windows as it does on Linux. return within(0, ChronoUnit.MICROS); }
Source:
public E map(ResultSet rs, int columnNumber, StatementContext ctx) throws SQLException { String name = ctx.findColumnMapperFor(String.class) .orElseThrow(() -> new UnableToProduceResultException("a String column mapper is required to map Enums from names", ctx)) .map(rs, columnNumber, ctx); return name == null ? null : nameValueCache.computeIfAbsent(name.toLowerCase(), lowercased -> getValueByName(enumClass, name, ctx)); }

Target:
public E map(ResultSet rs, int columnNumber, StatementContext ctx) throws SQLException { String name = rs.getString(columnNumber); return name == null || name.isEmpty() // some vendors treat null and empty varchar as the same ? null : nameValueCache.computeIfAbsent(name, n -> getValueByName(enumClass, name, ctx)); }
Source:
public static Type resolveType(Type type, Type contextType) { return GenericTypeReflector.resolveType(GenericTypeReflector.annotate(type), GenericTypeReflector.annotate(contextType)).getType(); }

Target:
public static Type resolveType(Type type, Type contextType) { return GenericTypeReflector.resolveType(type, contextType); }
Source:
protected BeanMapper(Class<T> type, String prefix) { this(type, (PojoProperties<T>) BeanPropertiesFactory.propertiesFor(type), prefix); }

Target:
BeanMapper(Class<T> type, String prefix) { this(type, (PojoProperties<T>) BeanPropertiesFactory.propertiesFor(type), prefix); }
Source:
public void setUp() throws Exception { Jdbi jdbi = Jdbi.create("jdbc:sqlite::memory:"); jdbi.installPlugin(new SQLitePlugin()); handle = jdbi.open(); handle.useTransaction(handle -> { handle.execute("CREATE TABLE foo(url URL);"); }); }

Target:
public void setUp() throws Exception { Jdbi jdbi = Jdbi.create("jdbc:sqlite::memory:"); jdbi.installPlugin(new SQLitePlugin()); handle = jdbi.open(); handle.useTransaction(handle -> handle.execute("CREATE TABLE foo(url URL);")); }
Source:
public void testInvalidDuration() { handle.createQuery("select foo from intervals where id=?") .bind(0, 5) .mapTo(Duration.class) .findOnly(); }

Target:
public void testInvalidDuration() { handle.createQuery("select foo from intervals where id=?") .bind(0, 3) // The bad one. .mapTo(Duration.class) .findOnly(); }
Source:
private void restoreAutoCommitState(final Handle handle) { try { final LocalStuff stuff = localStuff.remove(handle); if (stuff != null) { handle.getConnection().setAutoCommit(stuff.getInitialAutocommit()); stuff.getCheckpoints().clear(); } } catch (SQLException e) { throw new UnableToRestoreAutoCommitStateException(e); } finally { // prevent memory leak if rollback throws an exception if (localStuff.containsKey(handle)) { localStuff.remove(handle); } } }

Target:
private void restoreAutoCommitState(final Handle handle) { try { final LocalStuff stuff = localStuff.remove(handle); if (stuff != null) { handle.getConnection().setAutoCommit(stuff.getInitialAutocommit()); stuff.getCheckpoints().clear(); } } catch (SQLException e) { throw new UnableToRestoreAutoCommitStateException(e); } finally { // prevent memory leak if rollback throws an exception localStuff.remove(handle); } }
Source:
public void stop() { logger.info("stopping SparkDriver"); try { // todo: when possible (spark 1.3.0), change to streamingContext.stop(false, true) without the cancel if (javaStreamingContext != null) { javaStreamingContext.ssc().sc().cancelAllJobs(); javaStreamingContext.close(); } if (streamingContext != null) { streamingContext.sc().cancelAllJobs(); streamingContext.stop(true, false); } super.stop(); } catch (Exception e) { logger.warn("Exception when stopping the spark module " + e); } }

Target:
public void stop() { logger.info("stopping SparkDriver"); try { // todo: when possible (spark 1.3.0), change to streamingContext.stop(true, true) without the cancel if (streamingContext != null) { streamingContext.sc().cancelAllJobs(); streamingContext.stop(true, false); } super.stop(); } catch (Exception e) { logger.warn("Exception when stopping the spark module " + e); } }
Source:
protected void deployModules(Container container) throws Exception { String containerName = container.getName(); logger.info("Container arrived: {}", containerName); // before attempting to deploy unallocated modules, // wait to see if any more containers show up; this // will mitigate "overloading" of the container that // just arrived Thread.sleep(1000); deployUnallocatedStreamModules(); deployUnallocatedJobModules(); }

Target:
protected void deployModules(Container container) throws Exception { String containerName = container.getName(); logger.info("Container arrived: {}", containerName); deployUnallocatedStreamModules(); deployUnallocatedJobModules(); }
Source:
public void initialize(ConfigurableApplicationContext applicationContext) { String adminPort = applicationContext.getEnvironment().resolvePlaceholders(ADMIN_PORT_PLACEHOLDER); ServerSocket socket = null; try { socket = new ServerSocket(Integer.parseInt(adminPort)); } catch (IOException e) { throw new AdminPortNotAvailableException(adminPort); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { // It is very unlikely to get an exception here. e.printStackTrace(); } } } }

Target:
public void initialize(ConfigurableApplicationContext applicationContext) { String adminPort = applicationContext.getEnvironment().resolvePlaceholders(ADMIN_PORT_PLACEHOLDER); ServerSocket socket = null; try { socket = new ServerSocket(Integer.parseInt(adminPort)); } catch (IOException e) { throw new AdminPortNotAvailableException(adminPort); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { // It is very unlikely to get an exception here. } } } }
Source:
private ModuleType verifyModuleOfTypeExists(ModuleDeploymentRequest request, String moduleName, ModuleType type) { ModuleDefinition def = moduleDefinitionRepository.findByNameAndType(moduleName, type); if (def == null || def.getResource() == null) { List<ModuleDefinition> definitions = moduleDefinitionRepository.findByName(moduleName); if (definitions == null || definitions.size() == 0) { throw new NoSuchModuleException(moduleName); } // TODO: revisit this method altogether; it shouldn't apply to composite modules but at this stage we don't // know whether the 'stream' is actually a composite module (and we do want to verify complete streams) // the following method was removed from MDR: (leaving here as a reminder for the TODO) // The module is known but this doesn't seem to be a standard stream, // assume it is a composite module stream that isn't deployable by itself // request.tagAsUndeployable(); return definitions.get(0).getType(); } return def.getType(); }

Target:
private ModuleType verifyModuleOfTypeExists(ModuleDeploymentRequest request, String moduleName, ModuleType type) { ModuleDefinition def = moduleDefinitionRepository.findByNameAndType(moduleName, type); if (def == null || def.getResource() == null) { List<ModuleDefinition> definitions = moduleDefinitionRepository.findByName(moduleName); if (definitions.isEmpty()) { throw new NoSuchModuleException(moduleName); } // TODO: revisit this method altogether; it shouldn't apply to composite modules but at this stage we don't // know whether the 'stream' is actually a composite module (and we do want to verify complete streams) // the following method was removed from MDR: (leaving here as a reminder for the TODO) // The module is known but this doesn't seem to be a standard stream, // assume it is a composite module stream that isn't deployable by itself // request.tagAsUndeployable(); return definitions.get(0).getType(); } return def.getType(); }
Source:
public void findImplementations() { ResolverUtil<VFS> resolverUtil = new ResolverUtil<>(); resolverUtil.findImplementations(VFS.class, "org.apache.ibatis.io"); Set<Class<? extends VFS>> classSets = resolverUtil.getClasses(); classSets.forEach(c -> Assert.assertTrue(VFS.class.isAssignableFrom(c))); }

Target:
void findImplementations() { ResolverUtil<VFS> resolverUtil = new ResolverUtil<>(); resolverUtil.findImplementations(VFS.class, "org.apache.ibatis.io"); Set<Class<? extends VFS>> classSets = resolverUtil.getClasses(); //org.apache.ibatis.io.VFS //org.apache.ibatis.io.DefaultVFS //org.apache.ibatis.io.JBoss6VFS assertEquals(classSets.size(), 3); //fail if add a new VFS implementation in this package!!! classSets.forEach(c -> assertTrue(VFS.class.isAssignableFrom(c))); }
Source:
public Object get(Object key) { String strKey = (String) key; if (super.containsKey(strKey)) { return super.get(strKey); } if (parameterMetaObject == null) { return null; } if (fallbackParameterObject) { return parameterMetaObject.hasGetter(strKey) ? parameterMetaObject.getValue(strKey) : parameterMetaObject.getOriginalObject(); } else { // issue #61 do not modify the context when reading return parameterMetaObject.getValue(strKey); } }

Target:
public Object get(Object key) { String strKey = (String) key; if (super.containsKey(strKey)) { return super.get(strKey); } if (parameterMetaObject == null) { return null; } if (fallbackParameterObject && !parameterMetaObject.hasGetter(strKey)) { return parameterMetaObject.getOriginalObject(); } else { // issue #61 do not modify the context when reading return parameterMetaObject.getValue(strKey); } }
Source:
public int update(String sql, Object... args) throws SQLException { try (PreparedStatement ps = connection.prepareStatement(sql)) { setParameters(ps, args); return ps.executeUpdate(); } }

Target:
public int update(String sql, Object... args) throws SQLException { PreparedStatement ps = connection.prepareStatement(sql); try { setParameters(ps, args); return ps.executeUpdate(); } finally { try { ps.close(); } catch (SQLException e) { //ignore } } }
Source:
private void populateWriterArray() { columnWriters = new ArrayList<>(); // Case for empty result set if (firstRow == null || firstRow.length == 0) { return; } int colPosition = 0; for (String value : firstRow) { columnWriters.add(new StringColumnWriter(value, rowWriter, colPosition)); colPosition++; } }

Target:
private void populateWriterArray() { // Case for empty result set if (firstRow == null || firstRow.length == 0) { return; } columnWriters = new ArrayList<>(); int colPosition = 0; for (String value : firstRow) { columnWriters.add(new StringColumnWriter(value, rowWriter, colPosition)); colPosition++; } }
Source:
private TupleMetadata buildSchema() { this.firstRow = csvReader.parseNext(); // Case for empty dataset if (firstRow == null) { return builder.buildSchema(); } // Parse the first row for (String value : firstRow) { builder.addNullable(value, TypeProtos.MinorType.VARCHAR); } return builder.buildSchema(); }

Target:
private TupleMetadata buildSchema() { firstRow = csvReader.parseNext(); if (firstRow != null) { for (String value : firstRow) { builder.addNullable(value, TypeProtos.MinorType.VARCHAR); } } return builder.buildSchema(); }
Source:
private IterOutcome handleRightIncoming() { outer: for (;;) { IterOutcome outcome = next(0, right); switch (outcome) { case NONE: state = State.LEFT; break outer; case NOT_YET: return outcome; case OK_NEW_SCHEMA: case OK: appendStatistics(statisticsCollector); break; default: throw new UnsupportedOperationException("Unsupported upstream state " + outcome); } } return null; }

Target:
private IterOutcome handleRightIncoming() { outer: while (true) { IterOutcome outcome = next(0, right); switch (outcome) { case NONE: state = State.LEFT; break outer; case NOT_YET: return outcome; case OK_NEW_SCHEMA: case OK: appendStatistics(statisticsCollector); break; default: throw new UnsupportedOperationException("Unsupported upstream state " + outcome); } } return null; }
Source:
protected ElementParser resolve(TokenIterator tokenizer) { tupleParser.loader().removeNullMarker(this); if (tokenizer.peek() == JsonToken.START_ARRAY) { // The value is [], [ foo, so resolve directly return tupleParser.resolveField(key, tokenizer); } else { } // The value is [], foo, so must artificially create the // surrounding array to get a repeated type, which will // then parse the item as one-item array. return tupleParser.resolveArray(key, tokenizer); }

Target:
protected ElementParser resolve(TokenIterator tokenizer) { tupleParser.loader().removeNullMarker(this); if (tokenizer.peek() == JsonToken.START_ARRAY) { // The value is [], [ foo, so resolve directly return tupleParser.resolveField(key, tokenizer); } else { // The value is [], foo, so must artificially create the // surrounding array to get a repeated type, which will // then parse the item as one-item array. return tupleParser.resolveArray(key, tokenizer); } }
Source:
private boolean processNextRow() { try { // Stop reading when you run out of data if (!spssReader.readNextCase()) { return false; } rowWriter.start(); for (SpssColumnWriter spssColumnWriter : writerList) { spssColumnWriter.load(spssReader); } rowWriter.save(); } catch (IOException e) { throw UserException .dataReadError(e) .message("Error reading SPSS File.") .addContext(e.getMessage()) .addContext(errorContext) .build(logger); } return true; }

Target:
private boolean processNextRow() { try { // Stop reading when you run out of data if (!spssReader.readNextCase()) { return false; } rowWriter.start(); for (SpssColumnWriter spssColumnWriter : writerList) { spssColumnWriter.load(spssReader); } rowWriter.save(); } catch (IOException e) { throw UserException .dataReadError(e) .message("Error reading SPSS File.") .addContext(errorContext) .build(logger); } return true; }
Source:
public void allocateNew() throws OutOfMemoryException { if (!allocateNewSafe()) { throw new OutOfMemoryException("" + "Failed to allocate memory for " + getClass().getSimpleName()); } }

Target:
public void allocateNew() throws OutOfMemoryException { if (!allocateNewSafe()) { throw new OutOfMemoryException( "Failed to allocate memory for " + getClass().getSimpleName()); } }
Source:
public static List<SchemaPath> expandMetadata(int dirCount) { List<String> selected = Lists.newArrayList( FULLY_QUALIFIED_NAME_COL, FILE_PATH_COL, FILE_NAME_COL, SUFFIX_COL); for (int i = 0; i < dirCount; i++) { selected.add(PARTITION_COL + Integer.toString(i)); } return RowSetTestUtils.projectList(selected); }

Target:
public static List<SchemaPath> expandMetadata(int dirCount) { List<String> selected = Arrays.asList( FULLY_QUALIFIED_NAME_COL, FILE_PATH_COL, FILE_NAME_COL, SUFFIX_COL); for (int i = 0; i < dirCount; i++) { selected.add(PARTITION_COL + Integer.toString(i)); } return RowSetTestUtils.projectList(selected); }
Source:
public void testNullUserAgent() throws Exception { String query = "SELECT parse_user_agent(CAST(null as VARCHAR)) AS agent FROM (values(1))"; Map<?, ?> emptyMap = new HashMap<>(); testBuilder() .sqlQuery(query) .ordered() .baselineColumns("agent") .baselineValues(emptyMap) .go(); }

Target:
public void testNullUserAgent() throws Exception { String query = "SELECT parse_user_agent(CAST(null as VARCHAR)) AS agent FROM (values(1))"; Map<?, ?> emptyMap = Collections.emptyMap(); testBuilder() .sqlQuery(query) .ordered() .baselineColumns("agent") .baselineValues(emptyMap) .go(); }
Source:
public void eval() { // Get the timestamp in milliseconds long timestamp = inputDate.value; // Get the interval in milliseconds long groupByInterval = interval.value; java.time.Instant instant = java.time.Instant.ofEpochMilli(timestamp - (timestamp % groupByInterval)); java.time.LocalDateTime localDate = instant.atZone(java.time.ZoneId.of("UTC")).toLocalDateTime(); out.value = localDate.atZone(java.time.ZoneId.of("UTC")).toInstant().toEpochMilli(); }

Target:
public void eval() { // Get the timestamp in milliseconds long timestamp = inputDate.value; // Get the interval in milliseconds long groupByInterval = interval.value; out.value = (timestamp - (timestamp % groupByInterval)); }
Source:
public void eval() { // Get the timestamp in milliseconds long timestamp = inputDate.value; // Get the interval in milliseconds long intervalToAdd = interval.value; out.value = (long) java.lang.Math.floor(timestamp / intervalToAdd) * intervalToAdd; }

Target:
public void eval() { // Get the timestamp in milliseconds long timestamp = inputDate.value; // Get the interval in milliseconds long intervalToAdd = interval.value; out.value = timestamp - (timestamp % intervalToAdd); }
Source:
public String toString() { String result = type.name(); for (int i = 0; i < arrayDims; i++) { result += "[]"; } return result; }

Target:
public String toString() { StringBuilder buf = new StringBuilder() .append(type.name()); for (int i = 0; i < arrayDims; i++) { buf.append("[]"); } return buf.toString(); }
Source:
public void sendOk(int credit) { everLargestAdviceCredit = credit > everLargestAdviceCredit ? credit : everLargestAdviceCredit; if (0 == count.decrementAndGet()) { BitData.AckWithCredit ackWithCredit = BitData.AckWithCredit.newBuilder().setAllowedCredit(everLargestAdviceCredit).build(); Response ackResponse = new Response(BitData.RpcType.DATA_ACK_WITH_CREDIT, ackWithCredit); sender.send(ackResponse); } }

Target:
public void sendOk(int credit) { everLargestAdviceCredit = Math.max(everLargestAdviceCredit, credit); if (0 == count.decrementAndGet()) { BitData.AckWithCredit ackWithCredit = BitData.AckWithCredit.newBuilder().setAllowedCredit(everLargestAdviceCredit).build(); Response ackResponse = new Response(BitData.RpcType.DATA_ACK_WITH_CREDIT, ackWithCredit); sender.send(ackResponse); } }
Source:
public boolean equals(final Object other) { if (other == this) { return true; } if (other == null || !(other instanceof Map.Entry)) { return false; } final Map.Entry<?, ?> entry = (Map.Entry<?, ?>) other; return Objects.equal(key, entry.getKey()) && Objects.equal(value, entry.getValue()); }

Target:
public boolean equals(final Object other) { if (other == this) { return true; } if (other == null || !(other instanceof Map.Entry)) { return false; } Map.Entry<?, ?> entry = (Map.Entry<?, ?>) other; return Objects.equal(key, entry.getKey()) && Objects.equal(value, entry.getValue()); }
Source:
public SystemPluginLocator(PluginRegistryContext context) { this.context = checkNotNull(context); }

Target:
public SystemPluginLocator(PluginRegistryContext context) { this.context = context; }
Source:
protected FileScanFramework.FileScanBuilder frameworkBuilder(OptionManager options, EasySubScan scan) { FileScanFramework.FileScanBuilder builder = new FileScanFramework.FileScanBuilder(); builder.setReaderFactory(new AvroReaderFactory(new AvroBatchReader.AvroReaderConfig(this))); initScanBuilder(builder, scan); builder.setNullType(Types.optional(TypeProtos.MinorType.VARCHAR)); return builder; }

Target:
protected FileScanFramework.FileScanBuilder frameworkBuilder(OptionManager options, EasySubScan scan) { FileScanFramework.FileScanBuilder builder = new FileScanFramework.FileScanBuilder(); builder.setReaderFactory(new AvroReaderFactory()); initScanBuilder(builder, scan); builder.setNullType(Types.optional(TypeProtos.MinorType.VARCHAR)); return builder; }
Source:
protected int processIpV6Packet() { try { return super.processIpV6Packet(); } catch (IllegalStateException ise) { return -1; } catch (ArrayIndexOutOfBoundsException e) { return -1; } }

Target:
protected int processIpV6Packet() { try { return super.processIpV6Packet(); } catch (IllegalStateException | ArrayIndexOutOfBoundsException e) { return -1; } }
Source:
public ConstantFilter(Set<LogicalExpression> constantBoundaries) { super(); this.constantBoundaries = constantBoundaries; }

Target:
public ConstantFilter(Set<LogicalExpression> constantBoundaries) { this.constantBoundaries = constantBoundaries; }
Source:
public FunctionHolderExpression(String nameUsed, ExpressionPosition pos, List<LogicalExpression> args) { super(pos); this.nameUsed = nameUsed; if (args == null) { this.args = ImmutableList.of(); } else if (args instanceof ImmutableList) { this.args = (ImmutableList<LogicalExpression>) args; } else { this.args = ImmutableList.copyOf(args); } }

Target:
public FunctionHolderExpression(String nameUsed, ExpressionPosition pos, List<LogicalExpression> args) { super(pos); this.nameUsed = nameUsed; if (args == null) { this.args = ImmutableList.of(); } else { this.args = ImmutableList.copyOf(args); } }
Source:
public ValueVector getOutgoingValueVector(TypedFieldId fieldId) { Class<?> clazz = fieldId.getIntermediateClass(); int[] fieldIds = fieldId.getFieldIds(); return outgoingBatch.getValueAccessorById(clazz, fieldIds).getValueVector(); }

Target:
private ValueVector getOutgoingValueVector(TypedFieldId fieldId) { Class<?> clazz = fieldId.getIntermediateClass(); int[] fieldIds = fieldId.getFieldIds(); return outgoingBatch.getValueAccessorById(clazz, fieldIds).getValueVector(); }
Source:
void addField(ValueVector vv, LogicalExpression logicalExpression, OutputColumnType outputColumnType, String inputColumnName, String outputColumnName) { if(isFixedWidth(vv)) { addFixedWidthField(vv); } else { addVariableWidthField(vv, logicalExpression, outputColumnType, inputColumnName, outputColumnName); } }

Target:
private void addField(ValueVector vv, LogicalExpression logicalExpression, OutputColumnType outputColumnType, String inputColumnName, String outputColumnName) { if(isFixedWidth(vv)) { addFixedWidthField(vv); } else { addVariableWidthField(vv, logicalExpression, outputColumnType, inputColumnName, outputColumnName); } }
Source:
private CapitalizingJdbcSchema determineDefaultSchema(String connectionSchemaName) { CapitalizingJdbcSchema connSchema; if (connectionSchemaName == null || (connSchema = schemaMap.get(connectionSchemaName.toLowerCase())) == null) { // todo: this selection of default schema isn't correct, users are getting implicit random schema as default connSchema = schemaMap.values().iterator().next(); } return (CapitalizingJdbcSchema) connSchema.getDefaultSchema(); }

Target:
private CapitalizingJdbcSchema determineDefaultSchema(String connectionSchemaName) { CapitalizingJdbcSchema connSchema; if (connectionSchemaName == null || (connSchema = schemaMap.get(connectionSchemaName.toLowerCase())) == null) { connSchema = schemaMap.values().iterator().next(); } return connSchema.getDefaultSchema(); }
Source:
public Table getTable(String name) { if (defaultSchema != null) { try { return defaultSchema.getTable(name); } catch (RuntimeException e) { JdbcStoragePlugin.logger.warn("Failure while attempting to read table '{}' from JDBC source.", name, e); } } // no table was found. return null; }

Target:
public Table getTable(String name) { if (defaultSchema != null) { try { return defaultSchema.getTable(name); } catch (RuntimeException e) { logger.warn("Failure while attempting to read table '{}' from JDBC source.", name, e); } } // no table was found. return null; }
Source:
JdbcIntermediatePrelConverterRule() { super(JdbcDrel.class, (Predicate<RelNode>) input -> true, DrillRel.DRILL_LOGICAL, Prel.DRILL_PHYSICAL, DrillRelFactories.LOGICAL_BUILDER, "JDBC_PREL_Converter"); }

Target:
private JdbcIntermediatePrelConverterRule() { super(JdbcDrel.class, (Predicate<RelNode>) input -> true, DrillRel.DRILL_LOGICAL, Prel.DRILL_PHYSICAL, DrillRelFactories.LOGICAL_BUILDER, "JDBC_PREL_Converter"); }
Source:
private static SqlNode expandAvg(final SqlNode arg) { final SqlParserPos pos = SqlParserPos.ZERO; final SqlNode sum = DrillCalciteSqlAggFunctionWrapper.SUM.createCall(pos, arg); final SqlNode count = SqlStdOperatorTable.COUNT.createCall(pos, arg); final SqlNode sumAsDouble = CastHighOp.createCall(pos, sum); return SqlStdOperatorTable.DIVIDE.createCall( pos, sumAsDouble, count); }

Target:
private static SqlNode expandAvg(final SqlNode arg) { SqlNode sum = DrillCalciteSqlAggFunctionWrapper.SUM.createCall(SqlParserPos.ZERO, arg); SqlNode count = SqlStdOperatorTable.COUNT.createCall(SqlParserPos.ZERO, arg); SqlNode sumAsDouble = CastHighOp.createCall(SqlParserPos.ZERO, sum); return SqlStdOperatorTable.DIVIDE.createCall(SqlParserPos.ZERO, sumAsDouble, count); }
Source:
private static String readAFileIntoString(String filePath) { String content = ""; try { content = new String ( Files.readAllBytes( Paths.get(filePath) ) ); } catch (IOException e) { e.printStackTrace(); } return content; }

Target:
private static String readAFileIntoString(String filePath) throws IOException { return new String(Files.readAllBytes(Paths.get(filePath))); }
Source:
public static String getPrincipalFromParts(final String primary, final String instance, final String realm) { checkNotNull(primary); checkNotNull(realm); return checkNotNull(primary) + ((instance != "")? "/" + instance: "") + "@" + checkNotNull(realm); }

Target:
public static String getPrincipalFromParts(final String primary, final String instance, final String realm) { checkNotNull(primary); checkNotNull(realm); return primary + ((instance != "") ? "/" + instance : "") + "@" + realm; }
Source:
public static RowSetReaderImpl build(BatchAccessor batch) { VectorContainer container = batch.container(); try { return build(container, new HyperSchemaInference().infer(container), batch.selectionVector4()); } catch (SchemaChangeException e) { throw new UnsupportedOperationException(e); } }

Target:
public static RowSetReaderImpl build(BatchAccessor batch) throws SchemaChangeException { VectorContainer container = batch.container(); return build(container, new HyperSchemaInference().infer(container), batch.selectionVector4()); }
Source:
public <T extends BaseSubScan> CloseableRecordBatch createScan(ExecutorFragmentContext context, BaseSubScan subScan) throws ExecutionSetupException { try { final ScanFrameworkBuilder builder = options.scanFactory.scanBuilderShim(this, context.getOptions(), subScan); return builder.buildScanOperator(context, subScan); } catch (final UserException e) { // Rethrow user exceptions directly throw e; } catch (final Throwable e) { // Wrap all others throw new ExecutionSetupException(e); } }

Target:
public CloseableRecordBatch createScan(ExecutorFragmentContext context, BaseSubScan subScan) throws ExecutionSetupException { try { ScanFrameworkBuilder builder = options.scanFactory.scanBuilderShim(this, context.getOptions(), subScan); return builder.buildScanOperator(context, subScan); } catch (UserException e) { // Rethrow user exceptions directly throw e; } catch (Throwable e) { // Wrap all others throw new ExecutionSetupException(e); } }
Source:
public BaseSubScan(BaseGroupScan groupScan) { super(groupScan.getUserName()); storagePlugin = groupScan.storagePlugin(); this.columns = groupScan.getColumns(); }

Target:
public BaseSubScan(BaseGroupScan groupScan) { super(groupScan.getUserName()); this.storagePlugin = groupScan.storagePlugin(); this.columns = groupScan.getColumns(); }
Source:
public void copy(ColumnReader from) { throw new UnsupportedOperationException("Cannot copy values through a type converter"); }

Target:
public final void copy(ColumnReader from) { throw new UnsupportedOperationException("Cannot copy values through a type converter"); }
Source:
public void setValueCount(int topLevelValueCount) { if (topLevelValueCount == 0) { return; } int childValueCount; if (topLevelValueCount == 0) { childValueCount = 0; offsets.getMutator().setValueCount(0); } else { emptyPopulator.populate(topLevelValueCount); childValueCount = offsets.getAccessor().get(topLevelValueCount); } for (ValueVector v : getChildren()) { v.getMutator().setValueCount(childValueCount); } }

Target:
public void setValueCount(int topLevelValueCount) { int childValueCount; if (topLevelValueCount == 0) { childValueCount = 0; offsets.getMutator().setValueCount(0); } else { emptyPopulator.populate(topLevelValueCount); childValueCount = offsets.getAccessor().get(topLevelValueCount); } for (ValueVector v : getChildren()) { v.getMutator().setValueCount(childValueCount); } }
Source:
public HttpGroupScan ( HttpStoragePluginConfig config, HttpScanSpec scanSpec, List<SchemaPath> columns ) { super("no-user"); this.httpStoragePluginConfig = config; this.httpScanSpec = scanSpec; this.columns = columns == null || columns.size() == 0 ? ALL_COLUMNS : columns; }

Target:
public HttpGroupScan ( HttpStoragePluginConfig config, HttpScanSpec scanSpec, List<SchemaPath> columns) { super("no-user"); this.config = config; this.httpScanSpec = scanSpec; this.columns = columns; }
Source:
public SubScan getSpecificScan(int minorFragmentId) { logger.debug("HttpGroupScan getSpecificScan"); return new HttpSubScan(httpStoragePluginConfig, httpScanSpec, columns); }

Target:
public SubScan getSpecificScan(int minorFragmentId) { return new HttpSubScan(config, httpScanSpec, columns); }