auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testRecord003() throws CoreException { if (!isJRE14) { System.err.println("Test "+getName()+" requires a JRE 14"); return; } String source = "package pkg;\n" + "public record Point(int param1, int param2) {\n" + " public Point {\n" + " if (param1 > 5) {\n" + " System.out.println(\"error\");\n" + " }\n" + " }\n" + "\n" + " public Point(int a) {\n" + " this.param1 = 6;\n" + " this.param2 = 16;\n" + " a = 6;\n" + " }\n" + "}\n"; this.workingCopy = getWorkingCopy("/Converter14/src/X.java", true ); try { ASTNode node = buildAST(source, this.workingCopy); assertEquals("Not a compilation unit", ASTNode.COMPILATION_UNIT, node.getNodeType()); } catch(UnsupportedOperationException e) { fail("Should not throw UnsupportedOperationException"); } }

Target:
public void testRecord003() throws CoreException { if (!isJRE14) { System.err.println("Test "+getName()+" requires a JRE 14"); return; } String contents = "public record X(int param1, int param2) {\n" + " public X {\n" + " if (param1 > 5) {\n" + " System.out.println(\"error\");\n" + " }\n" + " }\n" + "\n" + " public X(int a) {\n" + " this.param1 = 6;\n" + " this.param2 = 16;\n" + " a = 6;\n" + " }\n" + "}\n"; this.workingCopy = getWorkingCopy("/Converter14/src/X.java", true ); IJavaProject javaProject = this.workingCopy.getJavaProject(); String old = javaProject.getOption(JavaCore.COMPILER_PB_ENABLE_PREVIEW_FEATURES, true); try { javaProject.setOption(JavaCore.COMPILER_PB_ENABLE_PREVIEW_FEATURES, JavaCore.ENABLED); javaProject.setOption(JavaCore.COMPILER_PB_REPORT_PREVIEW_FEATURES, JavaCore.IGNORE); ASTNode node = buildAST( contents, this.workingCopy); assertEquals("Not a compilation unit", ASTNode.COMPILATION_UNIT, node.getNodeType()); CompilationUnit compilationUnit = (CompilationUnit) node; assertProblemsSize(compilationUnit, 0); } finally { javaProject.setOption(JavaCore.COMPILER_PB_ENABLE_PREVIEW_FEATURES, old); } }
Source:
public static List<SessionData> from(Schedule schedule, OffsetTime now) { List<SessionData> sessionData = schedule.getSlots().stream() .filter(slot -> null != slot.getTalk()) .filter(slot -> slot.getTalk().getTalkType() != "BOF (Bird of a Feather)") .filter(slot -> OffsetTime.parse(slot.getToTime() + "Z").isAfter(now)) .filter(slot -> !OffsetTime.parse(slot.getFromTime() + "Z").isBefore(now.plusMinutes(120))) .collect(Collectors.groupingBy(slot -> slot.getRoomId())) .entrySet().stream() .map(entry -> entry.getValue().stream().findFirst()) .map(optional -> optional.orElse(null)) .map(slot -> new SessionData(slot.getRoomName(), slot.getTalk().getSpeakers().stream().map(ref -> ref.getName()).collect(Collectors.toList()), slot.getTalk().getTitle(), slot.getFromTime(), slot.isNotAllocated(), slot.getRoomSetup())) .sorted(SessionData.COMP) .collect(Collectors.toList()); System.out.println("Possible Next Sessions (" + sessionData.size() + "):\n " + sessionData); return sessionData; }

Target:
public static List<SessionData> from(Schedule schedule, OffsetTime now) { List<SessionData> sessionData = schedule.getSlots().stream() .filter(slot -> null != slot.getTalk()) .filter(slot -> slot.getTalk().getTalkType() != "BOF (Bird of a Feather)") .filter(slot -> OffsetTime.parse(slot.getToTime() + "Z").isAfter(now)) .filter(slot -> OffsetTime.parse(slot.getFromTime() + "Z").isBefore(now.plusMinutes(120))) .collect(Collectors.groupingBy(slot -> slot.getRoomId())) .entrySet().stream() .map(entry -> entry.getValue().stream().findFirst()) .map(optional -> optional.orElse(null)) .map(slot -> new SessionData(slot.getRoomName(), slot.getTalk().getSpeakers().stream().map(ref -> ref.getName()).collect(Collectors.toList()), slot.getTalk().getTitle(), slot.getFromTime(), slot.isNotAllocated(), slot.getRoomSetup())) .sorted(SessionData.COMP) .collect(Collectors.toList()); System.out.println("Possible Next Sessions (" + sessionData.size() + "):\n " + sessionData); return sessionData; }
Source:
private CreateSchema(Optional<NodeLocation> location, QualifiedName schemaName, boolean notExists, List<Property> properties) { super(location); this.schemaName = requireNonNull(schemaName, "schemaName is null"); this.notExists = notExists; this.properties = requireNonNull(properties, "properties is null"); }

Target:
private CreateSchema(Optional<NodeLocation> location, QualifiedName schemaName, boolean notExists, List<Property> properties) { super(location); this.schemaName = requireNonNull(schemaName, "schemaName is null"); this.notExists = notExists; this.properties = ImmutableList.copyOf(requireNonNull(properties, "properties is null")); }
Source:
public Object readSqlResultRecord(ResultSet result) { CitationCollectionOrder citationCollectionOrder = null; String collectionId = null; int location = 0; String sectionType = null; String value = null; try { collectionId = result.getString(1); location = result.getInt(2); sectionType = result.getString(3); value = result.getString(4); citationCollectionOrder = new CitationCollectionOrder(collectionId, location, CitationCollectionOrder.SectionType.HEADING1, value); } catch (SQLException e) { M_log.debug("TripleReader: problem reading CitationCollectionOrder from result: collectionId(" + collectionId + ") location(" + location + ") sectionType(" + sectionType + ") value(" + value + ")"); return null; } return citationCollectionOrder; }

Target:
public Object readSqlResultRecord(ResultSet result) { CitationCollectionOrder citationCollectionOrder = null; String collectionId = null; int location = 0; CitationCollectionOrder.SectionType sectionType = null; String value = null; try { collectionId = result.getString(1); location = result.getInt(2); sectionType = CitationCollectionOrder.SectionType.valueOf(result.getString(3)); value = result.getString(4); citationCollectionOrder = new CitationCollectionOrder(collectionId, location, CitationCollectionOrder.SectionType.HEADING1, value); } catch (SQLException e) { M_log.debug("TripleReader: problem reading CitationCollectionOrder from result: collectionId(" + collectionId + ") location(" + location + ") sectionType(" + sectionType + ") value(" + value + ")"); return null; } return citationCollectionOrder; }
Source:
public void shouldAcceptSv() throws Exception { Variant input = new Variant("1", 1000, 1061, "ATATATATATATATATATATATATATATATATATATATATATATATATATATATATATAT", "T"); Variant output = processor.process(input); assertEquals(Variant.VariantType.SV, input.getType()); assertNotNull(output); assertEquals(input, output); }

Target:
public void shouldAcceptSv() throws Exception { Variant input = new Variant("1", 1000, 1059, "ATATATATATATATATATATATATATATATATATATATATATATATATATATATATATAT", "T"); Variant output = processor.process(input); assertEquals(Variant.VariantType.SV, input.getType()); assertNotNull(output); assertEquals(input, output); }
Source:
public void ensureSubsequentRegistrationDoesNotFireActive() throws Throwable { final EventLoop eventLoop = mock(EventLoop.class); when(eventLoop.inEventLoop()).thenReturn(true); when(eventLoop.unsafe()).thenReturn(new EventLoop.Unsafe() { @Override public void register(Channel channel) { } @Override public void deregister(Channel channel) { } }); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { ((Runnable) invocationOnMock.getArgument(0)).run(); return null; } }).when(eventLoop).execute(any(Runnable.class)); final TestChannel channel = new TestChannel(eventLoop); ChannelInboundHandler handler = mock(ChannelInboundHandler.class); channel.pipeline().addLast(handler); registerChannel(channel); channel.unsafe().deregister(new DefaultChannelPromise(channel)); registerChannel(channel); verify(handler).handlerAdded(any(ChannelHandlerContext.class)); verify(handler, times(2)) .channelRegistered(any(ChannelHandlerContext.class)); verify(handler).channelActive(any(ChannelHandlerContext.class)); verify(handler).channelUnregistered(any(ChannelHandlerContext.class)); }

Target:
public void ensureSubsequentRegistrationDoesNotFireActive() throws Throwable { final EventLoop eventLoop = mock(EventLoop.class); when(eventLoop.inEventLoop()).thenReturn(true); when(eventLoop.unsafe()).thenReturn(mock(EventLoop.Unsafe.class)); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { ((Runnable) invocationOnMock.getArgument(0)).run(); return null; } }).when(eventLoop).execute(any(Runnable.class)); final TestChannel channel = new TestChannel(eventLoop); ChannelInboundHandler handler = mock(ChannelInboundHandler.class); channel.pipeline().addLast(handler); registerChannel(channel); channel.unsafe().deregister(new DefaultChannelPromise(channel)); registerChannel(channel); verify(handler).handlerAdded(any(ChannelHandlerContext.class)); verify(handler, times(2)) .channelRegistered(any(ChannelHandlerContext.class)); verify(handler).channelActive(any(ChannelHandlerContext.class)); verify(handler).channelUnregistered(any(ChannelHandlerContext.class)); }
Source:
public static void check(final HaxeVarDeclaration var, final AnnotationHolder holder) { HaxeFieldModel field = new HaxeFieldModel(var); if (field.isProperty()) { checkProperty(field, holder); } if (field.hasInitializer() && field.hasTypeTag()) { TypeTagChecker.check(field.getBasePsi(), field.getTypeTagPsi(), field.getInitializerPsi(), false, holder); } HashSet<HaxeClassModel> classSet = new HashSet<>(); HaxeClassModel fieldDeclaringClass = field.getDeclaringClass(); classSet.add(fieldDeclaringClass); while (fieldDeclaringClass != null) { fieldDeclaringClass = fieldDeclaringClass.getParentClass(); if (classSet.contains(fieldDeclaringClass)) { break; } else { classSet.add(fieldDeclaringClass); } if (fieldDeclaringClass != null) { for (HaxeFieldModel parentField : fieldDeclaringClass.getFields()) { if (parentField.getName().equals(field.getName())) { if (parentField.isStatic()) { holder.createWarningAnnotation(field.getNameOrBasePsi(), "Field '" + field.getName() + "' overrides a static field of a superclass."); } else { holder.createErrorAnnotation(field.getBasePsi(), "Redefinition of variable '" + field.getName() + "' in subclass is not allowed. Previously declared at '" + fieldDeclaringClass.getName() + "'."); } break; } } } } }

Target:
public static void check(final HaxeVarDeclaration var, final AnnotationHolder holder) { HaxeFieldModel field = new HaxeFieldModel(var); if (field.isProperty()) { checkProperty(field, holder); } if (field.hasInitializer() && field.hasTypeTag()) { TypeTagChecker.check(field.getBasePsi(), field.getTypeTagPsi(), field.getInitializerPsi(), false, holder); } HashSet<HaxeClassModel> classSet = new HashSet<>(); HaxeClassModel fieldDeclaringClass = field.getDeclaringClass(); classSet.add(fieldDeclaringClass); while (fieldDeclaringClass != null) { fieldDeclaringClass = fieldDeclaringClass.getParentClass(); if (classSet.contains(fieldDeclaringClass)) { break; } else { classSet.add(fieldDeclaringClass); } if (fieldDeclaringClass != null) { for (HaxeFieldModel parentField : fieldDeclaringClass.getFields()) { if (parentField.getName().equals(field.getName())) { String message; if (parentField.isStatic()) { message = HaxeBundle.message("haxe.semantic.static.field.override", field.getName()); holder.createWeakWarningAnnotation(field.getNameOrBasePsi(), message); } else { message = HaxeBundle.message("haxe.semantic.variable.redefinition", field.getName(), fieldDeclaringClass.getName()); holder.createErrorAnnotation(field.getBasePsi(), message); } break; } } } } }
Source:
protected void fileNameValidation( final String fileName ) throws PlatformImportException { if ( fileName != null && fileName.endsWith( ".xmi" ) ) { throw new PlatformImportException( Messages.getString( "AnalysisService.ERROR_001_ANALYSIS_DATASOURCE_ERROR" ), PlatformImportException.PUBLISH_GENERAL_ERROR ); } }

Target:
protected void fileNameValidation( final String fileName ) throws PlatformImportException { if ( fileName != null && !fileName.endsWith( ".xml" ) ) { throw new PlatformImportException( Messages.getString( "AnalysisService.ERROR_001_ANALYSIS_DATASOURCE_ERROR" ), PlatformImportException.PUBLISH_GENERAL_ERROR ); } }
Source:
public Observable<LeaderboardResponse> getLeaderboard(String userName, String duration, String category, String limit, String offset) { final String fetchLeaderboardUrlTemplate = wikiMediaTestToolforgeUrl + "/leaderboard.py"; String url = String.format(Locale.ENGLISH, fetchLeaderboardUrlTemplate, userName, duration, category, limit, offset); HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder(); urlBuilder.addQueryParameter("user", userName); urlBuilder.addQueryParameter("duration", duration); urlBuilder.addQueryParameter("category", category); urlBuilder.addQueryParameter("limit", limit); urlBuilder.addQueryParameter("offset", offset); Timber.i("Url %s", urlBuilder.toString()); Request request = new Request.Builder() .url(urlBuilder.toString()) .build(); return Observable.fromCallable(() -> { Response response = okHttpClient.newCall(request).execute(); if (response != null && response.body() != null && response.isSuccessful()) { String json = response.body().string(); if (json == null) { return new LeaderboardResponse(); } Timber.d("Response for leaderboard is %s", json); try { return gson.fromJson(json, LeaderboardResponse.class); } catch (Exception e) { return new LeaderboardResponse(); } } return new LeaderboardResponse(); }); }

Target:
public Observable<LeaderboardResponse> getLeaderboard(String userName, String duration, String category, String limit, String offset) { final String fetchLeaderboardUrlTemplate = wikiMediaTestToolforgeUrl + LEADERBOARD_END_POINT; String url = String.format(Locale.ENGLISH, fetchLeaderboardUrlTemplate, userName, duration, category, limit, offset); HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder(); urlBuilder.addQueryParameter("user", userName); urlBuilder.addQueryParameter("duration", duration); urlBuilder.addQueryParameter("category", category); urlBuilder.addQueryParameter("limit", limit); urlBuilder.addQueryParameter("offset", offset); Timber.i("Url %s", urlBuilder.toString()); Request request = new Request.Builder() .url(urlBuilder.toString()) .build(); return Observable.fromCallable(() -> { Response response = okHttpClient.newCall(request).execute(); if (response != null && response.body() != null && response.isSuccessful()) { String json = response.body().string(); if (json == null) { return new LeaderboardResponse(); } Timber.d("Response for leaderboard is %s", json); try { return gson.fromJson(json, LeaderboardResponse.class); } catch (Exception e) { return new LeaderboardResponse(); } } return new LeaderboardResponse(); }); }
Source:
public DataStoreTransaction beginTransaction() { if (queryEngine.getClass().equals(SQLQueryEngine.class)) { return new SQLAggregationDataStoreTransaction(queryEngine, cache, queryLogger); } throw new IllegalStateException("Unknown type of Query Engine"); }

Target:
public DataStoreTransaction beginTransaction() { return new AggregationDataStoreTransaction(queryEngine, cache, queryLogger); }
Source:
HashCode computeTemplateHash(String soyFile) { URL u = templates.get(soyFile); checkState(u != null, "Missing Soy template %s", soyFile); try (InputStream in = u.openStream()) { byte[] buf = new byte[4096]; Hasher h = Hashing.sha1().newHasher(); for (int n; (n = in.read(buf)) > 0;) { h.putBytes(buf, 0, n); } return h.hash(); } catch (IOException e) { throw new IllegalStateException("Missing Soy template " + soyFile, e); } }

Target:
HashCode computeTemplateHash(String soyFile) { URL u = templates.get(soyFile); checkState(u != null, "Missing Soy template %s", soyFile); Hasher h = Hashing.sha1().newHasher(); try (InputStream is = u.openStream(); OutputStream os = Funnels.asOutputStream(h)) { ByteStreams.copy(is, os); } catch (IOException e) { throw new IllegalStateException("Missing Soy template " + soyFile, e); } return h.hash(); }
Source:
private boolean propagate() { block.predecessors().stream() .map(programStateByBlock::get) .map(programStateAtBlock -> programStateAtBlock.out) .forEach(predecessorOuts -> in = join(in, predecessorOuts)); Map<Symbol, Set<Expression>> newOut = new HashMap<>(in); block.elements().forEach(element -> updateProgramState(element, newOut)); boolean outHasChanged = !newOut.equals(out); out = newOut; return outHasChanged; }

Target:
private boolean propagate() { block.predecessors().forEach(predecessor -> in = join(in, programStateByBlock.get(predecessor).out)); Map<Symbol, Set<Expression>> newOut = new HashMap<>(in); block.elements().forEach(element -> updateProgramState(element, newOut)); boolean outHasChanged = !newOut.equals(out); out = newOut; return outHasChanged; }
Source:
private static void transformMappedBy(Attribute attribute, Map<String, Attribute> newAttributes) { if (attribute.getMappedBy() != null) { String mappedByAttrId = attribute.getMappedBy().getIdentifier(); if (newAttributes.containsKey(mappedByAttrId)) { attribute.setMappedBy(newAttributes.get(mappedByAttrId)); } } }

Target:
private static void transformMappedBy(Attribute attribute, Map<String, Attribute> newAttributes) { if (attribute.isMappedBy()) { @SuppressWarnings("ConstantConditions") String mappedByAttrId = attribute.getMappedBy().getIdentifier(); if (newAttributes.containsKey(mappedByAttrId)) { attribute.setMappedBy(newAttributes.get(mappedByAttrId)); } } }
Source:
void registerMetricsIfNecessary(TableReference tableRef) { SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(7, TimeUnit.DAYS); Histogram slidingWeek = new Histogram(reservoir); String deletesMetric = MetricRegistry.name(SweepMetrics.class, "deletes", tableRef.getQualifiedName()); registerMetricIfNotExists(deletesMetric, slidingWeek); }

Target:
void registerMetricsIfNecessary(TableReference tableRef) { forAllMetrics(metric -> metric.registerForTable(tableRef)); }
Source:
public static ApplicationRecord getInstalledAppRecord() { SqlStorage<ApplicationRecord> storage = CommCareApplication._().getGlobalStorage(ApplicationRecord.class); for (Persistable p : storage) { ApplicationRecord r = (ApplicationRecord) p; if (r.getStatus() == ApplicationRecord.STATUS_INSTALLED) { return r; } } return null; }

Target:
public static ApplicationRecord getInstalledAppRecord() { SqlStorage<ApplicationRecord> storage = CommCareApplication._().getGlobalStorage(ApplicationRecord.class); for (Persistable p : storage) { ApplicationRecord r = (ApplicationRecord) p; if (r.getStatus() == ApplicationRecord.STATUS_INSTALLED && r.resourcesValidated()) { return r; } } return null; }
Source:
public ModuleOptions interpolate(final Map<String, String> raw) throws BindException { MapBindingResult bindingResult = new MapBindingResult(new HashMap<String, String>(), "options"); for (String provided : raw.keySet()) { if (!options.containsKey(provided)) { bindingResult.addError(new FieldError("options", provided, String.format( "Module option '%s' does not exist", provided))); } } if (bindingResult.hasErrors()) { throw new BindException(bindingResult); } ModuleOptions moduleOptions = new ModuleOptions() { @Override public EnumerablePropertySource<?> asPropertySource() { return new EnumerablePropertySource<Object>(this.toString(), this) { @Override public Object getProperty(String name) { ModuleOption option = options.get(name); if (option != null) { String provided = raw.get(name); if (provided != null) { validateByType(option, provided); return provided; } else { if (option.getDefaultValue() != null) { validateByType(option, option.getDefaultValue().toString()); } return option.getDefaultValue(); } } else { return null; } } @Override public String[] getPropertyNames() { return options.keySet().toArray(new String[options.size()]); } }; } }; for (String name : options.keySet()) { moduleOptions.asPropertySource().getProperty(name); } return moduleOptions; }

Target:
public ModuleOptions interpolate(final Map<String, String> raw) throws BindException { MapBindingResult bindingResult = new MapBindingResult(new HashMap<String, String>(), "options"); for (String provided : raw.keySet()) { if (!options.containsKey(provided)) { bindingResult.addError(new FieldError("options", provided, String.format( "Module option '%s' does not exist", provided))); } } if (bindingResult.hasErrors()) { throw new BindException(bindingResult); } ModuleOptions moduleOptions = new ModuleOptions() { @Override public EnumerablePropertySource<?> asPropertySource() { return new EnumerablePropertySource<Object>(this.toString(), this) { @Override public Object getProperty(String name) { ModuleOption option = options.get(name); if (option != null) { String provided = raw.get(name); if (provided != null) { validateByType(option, provided); return provided; } else { return option.getDefaultValue(); } } else { return null; } } @Override public String[] getPropertyNames() { return options.keySet().toArray(new String[options.size()]); } }; } }; PropertySource<?> ps = moduleOptions.asPropertySource(); for (String name : options.keySet()) { ps.getProperty(name); } return moduleOptions; }
Source:
public void jwksRegenerationTask() { if (configurationService.get().getEnableJwksGeneration()) { LOG.trace("Delete jwks from object if not present in storage..."); if (keyGeneratorService.getKeysFromStorage() == null) { LOG.trace("Jwks not present in storage. Resetting jwks in object to null..."); keyGeneratorService.setKeys(null); } LOG.trace("Generating jwks if missing in storage or expired..."); keyGeneratorService.getKeys(); } }

Target:
public void jwksRegenerationTask() { ScheduledExecutorService scheduledExecutorService = CoreUtils.createExecutor(); scheduledExecutorService.scheduleWithFixedDelay(new Runnable() { public void run() { if (!configurationService.get().getEnableJwksGeneration()) { return; } LOG.trace("Delete jwks from object if not present in storage..."); if (keyGeneratorService.getKeysFromStorage() == null) { LOG.trace("Jwks not present in storage. Resetting jwks in object to null..."); keyGeneratorService.setKeys(null); } LOG.trace("Generating jwks if missing in storage or expired..."); keyGeneratorService.getKeys(); } }, configurationService.get().getJwksRegenerationIntervalInHours(), configurationService.get().getJwksRegenerationIntervalInHours(), TimeUnit.HOURS); }
Source:
public String sendRestoreFromDeletionOperation(String userid, Collection<PID> unmarked) { Element contentEl = createAtomEntry(userid, unmarked.iterator().next(), CDRActions.RESTORE_FROM_DELETION); Element mark = new Element("markForDeletion", CDR_MESSAGE_NS); contentEl.addContent(mark); Element subjects = new Element("subjects", CDR_MESSAGE_NS); mark.addContent(subjects); for (PID sub : unmarked) { subjects.addContent(new Element("pid", CDR_MESSAGE_NS).setText(sub.getRepositoryPath())); } Document msg = contentEl.getDocument(); sendMessage(msg); return getMessageId(msg); }

Target:
public String sendRestoreFromDeletionOperation(String userid, Collection<PID> unmarked) { Element contentEl = createAtomEntry(userid, unmarked.iterator().next(), CDRActions.RESTORE_FROM_DELETION); Element mark = new Element("restoreFromDeletion", CDR_MESSAGE_NS); contentEl.addContent(mark); Element subjects = new Element("subjects", CDR_MESSAGE_NS); mark.addContent(subjects); for (PID sub : unmarked) { subjects.addContent(new Element("pid", CDR_MESSAGE_NS).setText(sub.getRepositoryPath())); } Document msg = contentEl.getDocument(); sendMessage(msg); return getMessageId(msg); }
Source:
public synchronized Location getLocation(Context context) { if (mLocation == null) { start(context, GOOGLE_API_CONNECT_TIMEOUT, false); if (isPlayServicesConnected()) { if (isLocationManagerConnected()) { stopLocationUpdatesWithoutPlayServices(); } try { mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); } catch (SecurityException e) { Log.e(TAG, "Appium Settings has no access to location permission", e); } } else if (isLocationManagerConnected() || mGoogleApiClient != null) { if (mGoogleApiClient != null && !isLocationManagerConnected()) { startLocationUpdatesWithoutPlayServices(); } if (mLocationManager != null) { try { mLocation = mLocationManager.getLastKnownLocation(mLocationProvider); } catch (SecurityException e) { Log.e(TAG, String.format("Appium Settings has no access to %s location permission", mLocationProvider), e); } } } } return mLocation; }

Target:
public synchronized Location getLocation(Context context) { if (mLocation != null) { return mLocation; } final boolean forceStart = hasAccessToLocationServices != null && !hasAccessToLocationServices; start(context, GOOGLE_API_CONNECT_TIMEOUT, forceStart); if (isPlayServicesConnected()) { if (isLocationManagerConnected()) { stopLocationUpdatesWithoutPlayServices(); } try { mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); hasAccessToLocationServices = true; } catch (SecurityException e) { hasAccessToLocationServices = false; Log.e(TAG, "Appium Settings has no access to location permission", e); } } else if (isLocationManagerConnected() || mGoogleApiClient != null) { if (mGoogleApiClient != null && !isLocationManagerConnected()) { mLocationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE); if (mLocationManager != null) { startLocationUpdatesWithoutPlayServices(); } } if (mLocationManager != null && mLocationProvider != null) { try { mLocation = mLocationManager.getLastKnownLocation(mLocationProvider); hasAccessToLocationServices = true; } catch (SecurityException e) { hasAccessToLocationServices = false; Log.e(TAG, String.format("Appium Settings has no access to %s location permission", mLocationProvider), e); } } } return mLocation; }
Source:
public Sequence<Cursor> makeCursors(Filter filter, Interval interval, QueryGranularity gran, boolean descending) { Interval actualInterval = interval; long minDataTimestamp = getMinTime().getMillis(); long maxDataTimestamp = getMaxTime().getMillis(); final Interval dataInterval = new Interval( minDataTimestamp, gran.next(gran.truncate(maxDataTimestamp)) ); if (!actualInterval.overlaps(dataInterval)) { return Sequences.empty(); } if (actualInterval.getStart().isBefore(dataInterval.getStart())) { actualInterval = actualInterval.withStart(dataInterval.getStart()); } if (actualInterval.getEnd().isAfter(dataInterval.getEnd())) { actualInterval = actualInterval.withEnd(dataInterval.getEnd()); } Filter[] filters = Filters.partitionWithBitmapSupport(filter); final Offset offset; if (filters[0] == null) { offset = new NoFilterOffset(0, index.getNumRows(), descending); } else { final ColumnSelectorBitmapIndexSelector selector = new ColumnSelectorBitmapIndexSelector( index.getBitmapFactoryForDimensions(), index ); offset = new BitmapOffset(selector.getBitmapFactory(), filters[0].getBitmapIndex(selector), descending); } return Sequences.filter( new CursorSequenceBuilder( index, actualInterval, gran, offset, filters[1], minDataTimestamp, maxDataTimestamp, descending ).build(), Predicates.<Cursor>notNull() ); }

Target:
public Sequence<Cursor> makeCursors(Filter filter, Interval interval, QueryGranularity gran, boolean descending) { Interval actualInterval = interval; long minDataTimestamp = getMinTime().getMillis(); long maxDataTimestamp = getMaxTime().getMillis(); final Interval dataInterval = new Interval( minDataTimestamp, gran.next(gran.truncate(maxDataTimestamp)) ); if (!actualInterval.overlaps(dataInterval)) { return Sequences.empty(); } if (actualInterval.getStart().isBefore(dataInterval.getStart())) { actualInterval = actualInterval.withStart(dataInterval.getStart()); } if (actualInterval.getEnd().isAfter(dataInterval.getEnd())) { actualInterval = actualInterval.withEnd(dataInterval.getEnd()); } final Filter[] filters = Filters.partitionWithBitmapSupport(filter); final Filter bitmapFilter = filters == null ? null : filters[0]; final Filter valuesFilter = filters == null ? null : filters[1]; final Offset offset; if (bitmapFilter == null) { offset = new NoFilterOffset(0, index.getNumRows(), descending); } else { final ColumnSelectorBitmapIndexSelector selector = new ColumnSelectorBitmapIndexSelector( index.getBitmapFactoryForDimensions(), index ); offset = new BitmapOffset(selector.getBitmapFactory(), bitmapFilter.getBitmapIndex(selector), descending); } return Sequences.filter( new CursorSequenceBuilder( index, actualInterval, gran, offset, valuesFilter, minDataTimestamp, maxDataTimestamp, descending ).build(), Predicates.<Cursor>notNull() ); }
Source:
public static LiveVariables analyze(CFG cfg, boolean includeFields) { LiveVariables liveVariables = new LiveVariables(cfg, includeFields); Map<CFG.Block, Set<Symbol>> kill = new HashMap<>(); Map<CFG.Block, Set<Symbol>> gen = new HashMap<>(); for (CFG.Block block : liveVariables.cfg.reversedBlocks()) { Set<Symbol> blockKill = new HashSet<>(); Set<Symbol> blockGen = new HashSet<>(); liveVariables.processBlockElements(block, blockKill, blockGen); kill.put(block, blockKill); gen.put(block, blockGen); } liveVariables.analyzeCFG(liveVariables.in, kill, gen); if (!liveVariables.out.get(liveVariables.cfg.reversedBlocks().get(0)).isEmpty()) { throw new IllegalStateException("Out of exit block should be empty"); } for (Map.Entry<CFG.Block, Set<Symbol>> blockSetEntry : liveVariables.out.entrySet()) { blockSetEntry.setValue(ImmutableSet.copyOf(blockSetEntry.getValue())); } return liveVariables; }

Target:
private static LiveVariables analyze(CFG cfg, boolean includeFields) { LiveVariables liveVariables = new LiveVariables(cfg, includeFields); Map<CFG.Block, Set<Symbol>> kill = new HashMap<>(); Map<CFG.Block, Set<Symbol>> gen = new HashMap<>(); for (CFG.Block block : liveVariables.cfg.reversedBlocks()) { Set<Symbol> blockKill = new HashSet<>(); Set<Symbol> blockGen = new HashSet<>(); liveVariables.processBlockElements(block, blockKill, blockGen); kill.put(block, blockKill); gen.put(block, blockGen); } liveVariables.analyzeCFG(liveVariables.in, kill, gen); if (!liveVariables.out.get(liveVariables.cfg.reversedBlocks().get(0)).isEmpty()) { throw new IllegalStateException("Out of exit block should be empty"); } for (Map.Entry<CFG.Block, Set<Symbol>> blockSetEntry : liveVariables.out.entrySet()) { blockSetEntry.setValue(ImmutableSet.copyOf(blockSetEntry.getValue())); } return liveVariables; }
Source:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_path_tracker); ButterKnife.bind(this); if (!CheckSelfPermissionAndRequest .checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) || !CheckSelfPermissionAndRequest .checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)) { CheckSelfPermissionAndRequest .requestPermission(this, Manifest.permission.ACCESS_FINE_LOCATION, 100, "Location Permission is necessary for this feature", "Location Permission is necessary for this feature", "Permission Denied"); } else { start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (buildLocationEnableDialog()) { service.startLogging(); } } }); stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { service.stopLogging(); } }); } showBackButton(); }

Target:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_path_tracker); ButterKnife.bind(this); start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (checkPermissionAndRequest()) { service.startLogging(); } } }); stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { service.stopLogging(); } }); showBackButton(); }
Source:
public ValidationResult checkObjectCode(String chartOfAccountsCode, String objectCodeParm) { ValidationResult validationResult = new ValidationResult(true, new ArrayList<String>()); ObjectCode objectCode = objectCodeService.getByPrimaryIdForCurrentYear(chartOfAccountsCode, objectCodeParm); if (objectCode == null || objectCode.toString().isEmpty()) { validationResult.setValid(false); validationResult.addMessage(ConcurConstants.AccountingStringValidationErrorMessages.ERROR_OBJ_CD_DOES_NOT_EXIST); } else if (!objectCode.isActive()) { validationResult.setValid(false); validationResult.addMessage(ConcurConstants.AccountingStringValidationErrorMessages.ERROR_OBJ_CD_INACTIVE); } return validationResult; }

Target:
public ValidationResult checkObjectCode(String chartOfAccountsCode, String objectCodeParm) { ObjectCode objectCode = objectCodeService.getByPrimaryIdForCurrentYear(chartOfAccountsCode, objectCodeParm); return checkMissingOrInactive(objectCode, MessageFormat.format(configurationService.getPropertyValueAsString(KFSKeyConstants.ERROR_EXISTENCE), ConcurConstants.AccountingStringFieldNames.OBJECT_CODE), MessageFormat.format(configurationService.getPropertyValueAsString(KFSKeyConstants.ERROR_INACTIVE), ConcurConstants.AccountingStringFieldNames.OBJECT_CODE)); }
Source:
public void testCaasUrl() { Supplier<String> orgIdSupplier = new OrganisationIdForAccount(api); String expectedPath = "/caas/2.4/6ac1e746-b1ea-4da5-a24e-caf1a978789d/server/0896551e-4fe3-4450-a627-ad5548e7e83a?clone=trevor-test2&desc=trevor-description2"; String updatedPath = new OrganisationIdFilter(orgIdSupplier).injectOrganisationId( "/caas/2.4/server/0896551e-4fe3-4450-a627-ad5548e7e83a?clone=trevor-test2&desc=trevor-description2"); assertEquals(updatedPath, expectedPath); }

Target:
public void testCaasUrl() { String expectedPath = "/caas/2.4/6ac1e746-b1ea-4da5-a24e-caf1a978789d/server/0896551e-4fe3-4450-a627-ad5548e7e83a?clone=trevor-test2&desc=trevor-description2"; String updatedPath = new OrganisationIdFilter(orgIdSupplier).injectOrganisationId( "/caas/2.4/server/0896551e-4fe3-4450-a627-ad5548e7e83a?clone=trevor-test2&desc=trevor-description2"); assertEquals(updatedPath, expectedPath); }
Source:
public AmbryCapacityUnitQuotaEnforcer(QuotaSource quotaSource) { this.quotaSource = quotaSource; allowRecommendation = new AmbryEnforcementRecommendation(false, 0, AmbryCapacityUnitQuotaEnforcer.class.getSimpleName(), 200); }

Target:
public AmbryCapacityUnitQuotaEnforcer(QuotaSource quotaSource) { this.quotaSource = quotaSource; allowRecommendation = new AmbryEnforcementRecommendation(false, 0, AmbryCapacityUnitQuotaEnforcer.class.getSimpleName(), 200, new RequestCost(null, null)); }
Source:
public void close() { File dir = new File("."); for (int i = 0; i < dir.list().length; i++) { File f = dir.listFiles()[i]; if (f.getAbsolutePath().endsWith(".class")) { f.delete(); } } }

Target:
public void close() { File dir = new File("."); File[] dirFiles = dir.listFiles(); for (int i = 0; i < dir.list().length; i++) { File f = dirFiles[i]; if (f.getAbsolutePath().endsWith(".class")) { f.delete(); } } }
Source:
private static String updateFileSystemProperties(@Nullable String fileSystemProperties, String accessID, String accessKey, String authenticationMethod, String enableEncryption) { Map<String, String> providedProperties; if (fileSystemProperties == null) { providedProperties = new HashMap<>(); } else { providedProperties = GSON.fromJson(fileSystemProperties, MAP_STRING_STRING_TYPE); } boolean encryptionEnabled = enableEncryption != null && enableEncryption.equalsIgnoreCase("True"); if (authenticationMethod != null && authenticationMethod.equalsIgnoreCase("Access Credentials")) { providedProperties.put("fs.s3n.awsAccessKeyId", accessID); providedProperties.put("fs.s3n.awsSecretAccessKey", accessKey); if (encryptionEnabled) { providedProperties.put("fs.s3n.server-side-encryption-algorithm", ENCRYPTION_VALUE); } } else if (authenticationMethod != null && authenticationMethod.equalsIgnoreCase("IAM")) { if (encryptionEnabled) { providedProperties.put("fs.s3a.server-side-encryption-algorithm", ENCRYPTION_VALUE); } } return GSON.toJson(providedProperties); }

Target:
private static String updateFileSystemProperties(@Nullable String fileSystemProperties, String accessID, String accessKey, String authenticationMethod, String enableEncryption) { Map<String, String> providedProperties; if (fileSystemProperties == null) { providedProperties = new HashMap<>(); } else { providedProperties = GSON.fromJson(fileSystemProperties, MAP_STRING_STRING_TYPE); } boolean encryptionEnabled = enableEncryption != null && enableEncryption.equalsIgnoreCase("True"); if (authenticationMethod != null && authenticationMethod.equalsIgnoreCase(ACCESS_CREDENTIALS)) { providedProperties.put(ACCESS_KEY, accessID); providedProperties.put(SECRET_KEY, accessKey); if (encryptionEnabled) { providedProperties.put(S3N_ENCRYPTION, ENCRYPTION_VALUE); } } else if (authenticationMethod != null && authenticationMethod.equalsIgnoreCase(IAM) && encryptionEnabled) { providedProperties.put(S3A_ENCRYPTION, ENCRYPTION_VALUE); } return GSON.toJson(providedProperties); }
Source:
public void handleDefaultDeviceResponse(final String deviceIdentification, final String organisationIdentification, final String correlationUid, final String messageType, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleDefaultDeviceResponse for MessageType: {}", messageType); ResponseMessageResultType result = deviceResult; OsgpException osgpException = exception; if (deviceResult == ResponseMessageResultType.NOT_OK && exception == null) { LOGGER.error("Incorrect response received, exception should not be null when result is not ok"); osgpException = new TechnicalException(ComponentType.DOMAIN_TARIFF_SWITCHING, "An unknown error occurred"); } if (deviceResult == ResponseMessageResultType.OK && exception != null) { LOGGER.error("Incorrect response received, result should be set to not ok when exception is not null"); result = ResponseMessageResultType.NOT_OK; } this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(result).withOsgpException(osgpException) .build()); }

Target:
public void handleDefaultDeviceResponse(final String deviceIdentification, final String organisationIdentification, final String correlationUid, final String messageType, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleDefaultDeviceResponse for MessageType: {}", messageType); ResponseMessageResultType result = deviceResult; OsgpException osgpException = exception; if (deviceResult == ResponseMessageResultType.NOT_OK && exception == null) { LOGGER.error("Incorrect response received, exception should not be null when result is not ok"); osgpException = new TechnicalException(ComponentType.DOMAIN_TARIFF_SWITCHING, "An unknown error occurred"); } if (deviceResult == ResponseMessageResultType.OK && exception != null) { LOGGER.error("Incorrect response received, result should be set to not ok when exception is not null"); result = ResponseMessageResultType.NOT_OK; } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(result).withOsgpException(osgpException) .build(); this.webServiceResponseMessageSender.send(responseMessage); }
Source:
public Host findDefaultHost(User user, boolean respectFrontendRoles) throws DotSecurityException, DotDataException { Host host; try{ host = (hostCache.getDefaultHost()!=null) ? hostCache.getDefaultHost() : getOrCreateDefaultHost(); APILocator.getPermissionAPI().checkPermission(host, PermissionLevel.READ, user); return host; } catch (DotSecurityException | DotDataException e) { throw e; } catch (Exception e) { throw new DotRuntimeException(e.getMessage(), e); } }

Target:
public Host findDefaultHost(User user, boolean respectFrontendRoles) throws DotSecurityException, DotDataException { Host host; try{ host = (hostCache.getDefaultHost()!=null) ? hostCache.getDefaultHost() : getOrCreateDefaultHost(); APILocator.getPermissionAPI().checkPermission(host, PermissionLevel.READ, user); return host; } catch (DotSecurityException | DotDataException e) { Logger.warn(HostAPIImpl.class, "Error trying to het default host:" + e.getMessage()); throw e; } catch (Exception e) { throw new DotRuntimeException(e.getMessage(), e); } }
Source:
RevCommit next() throws MissingObjectException, IncorrectObjectTypeException, IOException { final RevCommit c = source.next(); if (c == null) { return null; } boolean rewrote = false; final RevCommit[] pList = c.parents; final int nParents = pList.length; for (int i = 0; i < nParents; i++) { final RevCommit oldp = pList[i]; RevCommit newp; if (firstParent && i > 0) { newp = null; } else { newp = rewrite(oldp); } if (oldp != newp) { pList[i] = newp; rewrote = true; } } if (rewrote) { c.parents = cleanup(pList); } return c; }

Target:
RevCommit next() throws MissingObjectException, IncorrectObjectTypeException, IOException { final RevCommit c = source.next(); if (c == null) { return null; } boolean rewrote = false; final RevCommit[] pList = c.parents; final int nParents = pList.length; for (int i = 0; i < nParents; i++) { final RevCommit oldp = pList[i]; if (firstParent && i > 0) { c.parents = new RevCommit[] { rewrite(oldp) }; return c; } final RevCommit newp = rewrite(oldp); if (oldp != newp) { pList[i] = newp; rewrote = true; } } if (rewrote) { c.parents = cleanup(pList); } return c; }
Source:
private void executeAction() { LOG.trace("response processing for {}", requestTicket); for (ResponseListener listener : responseListeners) { if (listener != null) { if (hasException) { LOG.debug("invoke response listener for requestTicket throws exception", requestTicket, exception); listener.onError(endpoint, requestTicket, exception); } else { LOG.trace("invoke response listener for requestTicket with response {}", requestTicket, response); listener.onResponse(endpoint, requestTicket, response); } } } }

Target:
private void executeAction() { LOG.trace("response processing for {}", requestTicket); for (ResponseListener listener : responseListeners) { if (listener != null) { if (hasException) { LOG.debug("invoke response listener for requestTicket with exception", requestTicket, exception); listener.onError(client, requestTicket, exception); } else { LOG.trace("invoke response listener for requestTicket with response {}", requestTicket, response); listener.onResponse(client, requestTicket, response); } } } }
Source:
private void clearProfileCache() { server_.clearProfile(htmlLocalPath_, new ServerRequestCallback<JavaScriptObject>() { @Override public void onError(ServerError error) { } }); }

Target:
private void clearProfileCache() { try { server_.clearProfile(htmlLocalPath_, new ServerRequestCallback<JavaScriptObject>() { @Override public void onError(ServerError error) { Debug.logError(error); } }); } catch(Exception e) { Debug.logException(e); } }
Source:
public Configuration generate(JTestSuite jTestConfiguration) { Configuration configuration = new Configuration(); List<Task> tasks = jTestConfiguration.getTestGroups().stream(). map(TestGroupGenerator::generateFromTestGroup) .collect(Collectors.toList()); configuration.setTasks(tasks); ManagedList<SessionExecutionListener> seListeners = new ManagedList<>(); seListeners.add(basicSessionCollector); seListeners.add(basicAggregator); ManagedList<DistributionListener> teListeners = new ManagedList<>(); teListeners.add(basicSessionCollector); teListeners.add(basicAggregator); teListeners.add(e1MasterCollector); teListeners.add(e1ScenarioAggregator); teListeners.add(metricLogProcessor); teListeners.add(profilerLogProcessor); configuration.setSessionExecutionListeners(seListeners); configuration.setTaskExecutionListeners(teListeners); return configuration; }

Target:
public Configuration generate(JTestSuite jTestConfiguration) { Configuration configuration = new Configuration(); List<Task> tasks = jTestConfiguration.getTestGroups() .stream() .map(TestGroupGenerator::generateFromTestGroup) .collect(Collectors.toList()); configuration.setTasks(tasks); ManagedList<SessionExecutionListener> seListeners = new ManagedList<>(); seListeners.add(basicSessionCollector); seListeners.add(basicAggregator); ManagedList<DistributionListener> teListeners = new ManagedList<>(); teListeners.add(basicSessionCollector); teListeners.add(basicAggregator); teListeners.add(e1MasterCollector); teListeners.add(e1ScenarioAggregator); teListeners.add(metricLogProcessor); teListeners.add(profilerLogProcessor); teListeners.add(durationLogProcessor); configuration.setSessionExecutionListeners(seListeners); configuration.setTaskExecutionListeners(teListeners); return configuration; }
Source:
public void testPRGatherCancellationWhileGatheringResults() { final VM server1 = VM.getVM(0); final VM server2 = VM.getVM(1); final VM client = VM.getVM(2); final int numObjects = 200; try { final int[] port = AvailablePortHelper.getRandomAvailableTCPPorts(2); startCacheServer(server1, port[0], false, -1, true); startCacheServer(server2, port[1], true, -1, true); startClient(client, port[0]); populateData(server2); createCancelDuringGatherTestHook(server1, VM.getController()); client.invoke("executing query to be canceled by gather", () -> { QueryService qs; try { qs = getCache().getQueryService(); Query query = qs.newQuery("Select * From /" + "portfolios"); query.execute(); } catch (ServerOperationException soe) { if (soe.getRootCause() instanceof QueryException) { QueryException e = (QueryException) soe.getRootCause(); if (!isExceptionDueToLowMemory(e)) { throw new CacheException(soe) {}; } else { return 0; } } } catch (Exception e) { throw new CacheException(e) {}; } throw new CacheException("should have hit low memory") {}; }); verifyRejectedObjects(server1); vmRecoversFromCriticalHeap(server1); client.invoke("Executing query when system is 'Normal'", () -> { try { QueryService qs = getCache().getQueryService(); Query query = qs.newQuery("Select * From /" + "portfolios"); SelectResults results = (SelectResults) query.execute(); assertThat(results.size()).isEqualTo(numObjects); } catch (QueryInvocationTargetException | FunctionDomainException | TypeMismatchException | NameResolutionException e) { fail(""); } }); vmRecoversFromCriticalHeap(server1); } finally { stopServer(server1); stopServer(server2); } }

Target:
public void testPRGatherCancellationWhileGatheringResults() { final VM server1 = VM.getVM(0); final VM server2 = VM.getVM(1); final VM client = VM.getVM(2); final int numObjects = 200; try { final int[] port = AvailablePortHelper.getRandomAvailableTCPPorts(2); startCacheServer(server1, port[0], false, -1, true); startCacheServer(server2, port[1], true, -1, true); startClient(client, port[0]); populateData(server2); createCancelDuringGatherTestHook(server1, VM.getController()); client.invoke("executing query to be canceled by gather", () -> { QueryService qs; try { qs = getCache().getQueryService(); Query query = qs.newQuery("Select * From /" + "portfolios"); query.execute(); } catch (ServerOperationException soe) { if (soe.getRootCause() instanceof QueryException) { QueryException e = (QueryException) soe.getRootCause(); if (!isExceptionDueToLowMemory(e)) { throw new CacheException(soe) {}; } else { return 0; } } } catch (Exception e) { throw new CacheException(e) {}; } throw new CacheException("should have hit low memory") {}; }); verifyRejectedObjects(server1); vmRecoversFromCriticalHeap(server1); client.invoke("Executing query when system is 'Normal'", () -> { QueryService qs = getCache().getQueryService(); Query query = qs.newQuery("Select * From /" + "portfolios"); SelectResults results = (SelectResults) query.execute(); assertThat(results.size()).isEqualTo(numObjects); }); vmRecoversFromCriticalHeap(server1); } finally { stopServer(server1); stopServer(server2); } }