auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public LocalStackDaoImpl(LocalStorageFactory localStorageFactory) throws IOException, ServerException { HashMap<Class<?>, Object> adapters = new HashMap<>(); adapters.put(StackComponent.class, new StackComponentSerializer()); adapters.put(WorkspaceConfig.class, new WorkspaceConfigSerializer()); adapters.put(ProjectConfig.class, new ProjectConfigSerializer()); adapters.put(EnvironmentState.class, new EnvironmentStateSerializer()); adapters.put(Command.class, new CommandSerializer()); adapters.put(Recipe.class, new RecipeSerializer()); adapters.put(Limits.class, new LimitsSerializer()); adapters.put(MachineSource.class, new MachineSourceSerializer()); <START> adapters.put(MachineConfig.class, new MachineSourceSerializer()); <END> adapters.put(StackSource.class, new StackSourceSerializer()); adapters.put(Permissions.class, new PermissionsSerializer()); adapters.put(Group.class, new GroupSerializer()); this.stackStorage = localStorageFactory.create(STORAGE_FILE, Collections.unmodifiableMap(adapters), Collections.singletonMap(byte[].class, new ByteArrayToBase64Serializer())); this.stacks = new HashMap<>(); this.lock = new ReentrantReadWriteLock(); }</code><technical_language>MachineSourceSerializer for MachineConfig</technical_language>

Target:
public LocalStackDaoImpl(LocalStorageFactory localStorageFactory) throws IOException, ServerException { HashMap<Class<?>, Object> adapters = new HashMap<>(); adapters.put(StackComponent.class, new StackComponentSerializer()); adapters.put(WorkspaceConfig.class, new WorkspaceConfigSerializer()); adapters.put(ProjectConfig.class, new ProjectConfigSerializer()); adapters.put(EnvironmentState.class, new EnvironmentStateSerializer()); adapters.put(Command.class, new CommandSerializer()); adapters.put(Recipe.class, new RecipeSerializer()); adapters.put(Limits.class, new LimitsSerializer()); adapters.put(MachineSource.class, new MachineSourceSerializer()); adapters.put(MachineConfig.class, new MachineConfigSerializer()); adapters.put(StackSource.class, new StackSourceSerializer()); adapters.put(Permissions.class, new PermissionsSerializer()); adapters.put(Group.class, new GroupSerializer()); this.stackStorage = localStorageFactory.create(STORAGE_FILE, Collections.unmodifiableMap(adapters), Collections.singletonMap(byte[].class, new ByteArrayToBase64Serializer())); this.stacks = new HashMap<>(); this.lock = new ReentrantReadWriteLock(); }
Source:
<code>public void testCalculateRocksDBDefaultArenaBlockSize() { <START> long align = 4 * 1024; long writeBufferSize = 64 * 1024 * 1024; long expectArenaBlockSize = writeBufferSize / 8; long expectArenaBlockSize2 = expectArenaBlockSize + align; long expectArenaBlockSize3 = expectArenaBlockSize + 2 * align; assertThat(RocksDBMemoryControllerUtils.calculateRocksDBDefaultArenaBlockSize(writeBufferSize), is(expectArenaBlockSize)); assertThat(RocksDBMemoryControllerUtils.calculateRocksDBDefaultArenaBlockSize(writeBufferSize + 7), is(expectArenaBlockSize)); assertThat(RocksDBMemoryControllerUtils.calculateRocksDBDefaultArenaBlockSize(writeBufferSize + 8), is(expectArenaBlockSize2)); assertThat(RocksDBMemoryControllerUtils.calculateRocksDBDefaultArenaBlockSize(writeBufferSize + 8 * align + 7), is(expectArenaBlockSize2)); assertThat(RocksDBMemoryControllerUtils.calculateRocksDBDefaultArenaBlockSize(writeBufferSize + 8 * align + 8), is(expectArenaBlockSize3)); <END> }</code><technical_language>suggestion final long align = 4 * 1024; final long writeBufferSize = 64 * 1024 * 1024; final long expectArenaBlockSize = writeBufferSize / 8; // Normal case test assertThat("Arena block size calculation error for normal case", RocksDBMemoryControllerUtils.calculateRocksDBDefaultArenaBlockSize(writeBufferSize), is(expectArenaBlockSize)); // Alignment tests assertThat("Arena block size calculation error for alignment case", RocksDBMemoryControllerUtils.calculateRocksDBDefaultArenaBlockSize(writeBufferSize - 1), is(expectArenaBlockSize)); assertThat("Arena block size calculation error for alignment case2", RocksDBMemoryControllerUtils.calculateRocksDBDefaultArenaBlockSize(writeBufferSize + 8), is(expectArenaBlockSize + align));</technical_language>

Target:
public void testCalculateRocksDBDefaultArenaBlockSize() { final long align = 4 * 1024; final long writeBufferSize = 64 * 1024 * 1024; final long expectArenaBlockSize = writeBufferSize / 8; assertThat("Arena block size calculation error for normal case", RocksDBMemoryControllerUtils.calculateRocksDBDefaultArenaBlockSize(writeBufferSize), is(expectArenaBlockSize)); assertThat("Arena block size calculation error for alignment case", RocksDBMemoryControllerUtils.calculateRocksDBDefaultArenaBlockSize(writeBufferSize - 1), is(expectArenaBlockSize)); assertThat("Arena block size calculation error for alignment case2", RocksDBMemoryControllerUtils.calculateRocksDBDefaultArenaBlockSize(writeBufferSize + 8), is(expectArenaBlockSize + align)); }
Source:
<code>public Response getCatalogXml(@QueryParam(QUERY_REQUESTED_DT) final String requestedDate, @javax.ws.rs.core.Context final HttpServletRequest request) throws Exception { final TenantContext tenantContext = context.createTenantContextNoAccountId(request); final DateTime catalogDateVersion = requestedDate != null ? DATE_TIME_FORMATTER.parseDateTime(requestedDate).toDateTime(DateTimeZone.UTC) : null; final VersionedCatalog catalog = (VersionedCatalog) catalogUserApi.getCatalog(catalogName, tenantContext); String result = null; if (catalogDateVersion != null) { for (final StandaloneCatalog v : catalog.getVersions()) { <START> if (v.getEffectiveDate().compareTo(catalogDateVersion.toDate()) == 0) { <END> result = XMLWriter.writeXML(v, StandaloneCatalog.class); break; } } } else { result = XMLWriter.writeXML(catalog, VersionedCatalog.class); } return Response.status(Status.OK).entity(result).build(); }</code><technical_language>I wondering if v.getEffectiveDate().compareTo(catalogDateVersion.toDate()) >= 0, this forces user timestamp of catalog. 's assume versions: 2018-01-01T00:00:00+00:00 2018-03-01T00:00:00+00:00: * Providing date >= 2018-01-01T00:00:00+00:00 < 2018-03-01T00:00:00+00:00 return version * Providing date >= 2018-03-01T00:00:00+00:00 return version. parameter request date represents date range of date for this catalog version is effective. @pierre thoughts</technical_language>

Target:
public Response getCatalogXml(@QueryParam(QUERY_REQUESTED_DT) final String requestedDate, @javax.ws.rs.core.Context final HttpServletRequest request) throws Exception { final TenantContext tenantContext = context.createTenantContextNoAccountId(request); final DateTime catalogDateVersion = requestedDate != null ? DATE_TIME_FORMATTER.parseDateTime(requestedDate).toDateTime(DateTimeZone.UTC) : null; final VersionedCatalog catalog = (VersionedCatalog) catalogUserApi.getCatalog(catalogName, tenantContext); final String result; if (catalogDateVersion != null) { final VersionedCatalog oneVersionCatalog = new VersionedCatalog(); for (final StandaloneCatalog v : catalog.getVersions()) { if (v.getEffectiveDate().compareTo(catalogDateVersion.toDate()) >= 0) { oneVersionCatalog.add(v); break; } } result = XMLWriter.writeXML(oneVersionCatalog, VersionedCatalog.class); } else { result = XMLWriter.writeXML(catalog, VersionedCatalog.class); } return Response.status(Status.OK).entity(result).build(); }
Source:
<code><START> public void testGetAllTicketsForTransport_Admin() { <END> ticketRepository.saveAndFlush(new Ticket(user, TicketType.REGULAR_FULL, true, false)); SessionData login = login("admin", adminCleartextPassword); given() .filter(sessionFilter) .header(login.getCsrfHeader()) .when() .get("/tickets/transport") .then() .statusCode(HttpStatus.SC_OK) .body("", hasSize(1)); }</code><technical_language>This test is sufficient itself. needs another test is a difference tickets transport tickets</technical_language>

Target:
public void testGetAllTicketsForTransport_Admin() { makeTicket(); ticketRepository.saveAndFlush(new Ticket(user, TicketType.REGULAR_FULL, true, false)); SessionData login = login(admin.getUsername(), adminCleartextPassword); given() .filter(sessionFilter) .header(login.getCsrfHeader()) .when() .get("/tickets/transport") .then() .statusCode(HttpStatus.SC_OK) .body("$", hasSize(1)) .body("pickupService", contains(true)); }
Source:
<code>public ResponseEntity<Resources<Resource<Project>>> getProjectsForUser(@RequestParam(value = "name", required = false) String name, @RequestParam(value = "type", required = false) String projectType, OAuth2Authentication oAuth2Authentication) { User sw360User = restControllerHelper.getSw360UserFromAuthentication(oAuth2Authentication); List<Project> sw360Projects = new ArrayList<>(); if (name != null && !name.isEmpty()) { sw360Projects.addAll(projectService.searchProjectByName(name, sw360User)); } else { sw360Projects.addAll(projectService.getProjectsForUser(sw360User)); } List<Resource<Project>> projectResources = new ArrayList<>(); sw360Projects.stream() <START> .filter(projectType == null ? p -> true : project -> projectType.equals(project.projectType.name())) <END> .forEach(p -> { p.setDescription(null); p.setType(null); p.setCreatedOn(null); p.setReleaseIdToUsage(null); p.setExternalIds(null); p.setBusinessUnit(null); projectResources.add(new Resource<>(p)); }); Resources<Resource<Project>> resources = new Resources<>(projectResources); return new ResponseEntity<>(resources, HttpStatus.OK); }</code><technical_language>project -> projectType == null || projectType.equals(project.projectType.name())</technical_language>

Target:
public ResponseEntity<Resources<Resource<Project>>> getProjectsForUser(@RequestParam(value = "name", required = false) String name, @RequestParam(value = "type", required = false) String projectType, OAuth2Authentication oAuth2Authentication) { User sw360User = restControllerHelper.getSw360UserFromAuthentication(oAuth2Authentication); List<Project> sw360Projects = new ArrayList<>(); if (name != null && !name.isEmpty()) { sw360Projects.addAll(projectService.searchProjectByName(name, sw360User)); } else { sw360Projects.addAll(projectService.getProjectsForUser(sw360User)); } List<Resource<Project>> projectResources = new ArrayList<>(); sw360Projects.stream() .filter(project -> projectType == null || projectType.equals(project.projectType.name())) .forEach(p -> { p.setDescription(null); p.setType(null); p.setCreatedOn(null); p.setReleaseIdToUsage(null); p.setExternalIds(null); p.setBusinessUnit(null); projectResources.add(new Resource<>(p)); }); Resources<Resource<Project>> resources = new Resources<>(projectResources); return new ResponseEntity<>(resources, HttpStatus.OK); }
Source:
<code><START> public void access(final Path path, final FsAction mode) <END> throws AzureBlobFileSystemException { LOG.debug("access for filesystem: {}, path: {}, mode: {}", this.client.getFileSystem(), path, mode); if (!this.abfsConfiguration.isCheckAccessEnabled() || !getIsNamespaceEnabled()) { LOG.debug("Returning; either check access is not enabled or the account" + " used is not namespace enabled"); return; } String relativePath = AbfsHttpConstants.FORWARD_SLASH + getRelativePath(path, true); this.client.checkAccess(relativePath, mode.SYMBOL); }</code><technical_language>update this method include "AbfsPerfInfo" introduced HADOOP-16612</technical_language>

Target:
public void access(final Path path, final FsAction mode) throws AzureBlobFileSystemException { LOG.debug("access for filesystem: {}, path: {}, mode: {}", this.client.getFileSystem(), path, mode); if (!this.abfsConfiguration.isCheckAccessEnabled() || !getIsNamespaceEnabled()) { LOG.debug("Returning; either check access is not enabled or the account" + " used is not namespace enabled"); return; } try (AbfsPerfInfo perfInfo = startTracking("access", "checkAccess")) { String relativePath = AbfsHttpConstants.FORWARD_SLASH + getRelativePath(path, true); final AbfsRestOperation op = this.client .checkAccess(relativePath, mode.SYMBOL); perfInfo.registerResult(op.getResult()).registerSuccess(true); } }
Source:
<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_nearby, container, false); rootView.setPadding(0, getContentTopOffsetPx(getActivity()), 0, 0); mapView = (MapView) rootView.findViewById(R.id.mapview); mapView.setAccessToken(getString(R.string.mapbox_public_token)); markerIconPassive = mapView.getSpriteFactory().fromResource(R.drawable.ic_map_marker); <START> mapView.onCreate(savedInstanceState); <END> rootView.findViewById(R.id.user_location_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkLocationPermissionsToGoToUserLocation(); } }); return rootView; }</code><technical_language>docs[0], this called onCreate()... supposed get MapView onCreateView()? [0] "You call this method parent's Activity.onCreate(Bundle) Fragment.onCreate(Bundle)." <LINK_0></technical_language>

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_nearby, container, false); rootView.setPadding(0, getContentTopOffsetPx(getActivity()), 0, 0); mapView = (MapView) rootView.findViewById(R.id.mapview); mapView.setAccessToken(getString(R.string.mapbox_public_token)); markerIconPassive = mapView.getSpriteFactory().fromResource(R.drawable.ic_map_marker); mapView.onCreate(null); rootView.findViewById(R.id.user_location_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkLocationPermissionsToGoToUserLocation(); } }); return rootView; }
Source:
<code>public void ensureChannelCount(int capacity) throws IOException { if (this.shutdown) { throw new IOException("The channel is closed."); } if (channels.get().size() < capacity) { synchronized (this) { if (channels.get().size() < capacity) { Counter counter = getActiveChannelCounter(); List<ChannelAndMetrics> newChannelList = new ArrayList<>(channels.get()); while(newChannelList.size() < capacity) { newChannelList.add(createChannelAndMetrics()); <START> counter.inc(); <END> } setChannels(newChannelList); } } } }</code><technical_language>getActiveChannelCounter().inc()</technical_language>

Target:
public void ensureChannelCount(int capacity) throws IOException { if (this.shutdown) { throw new IOException("The channel is closed."); } if (channels.get().size() < capacity) { synchronized (this) { if (channels.get().size() < capacity) { List<InstrumentedChannel> newChannelList = new ArrayList<>(channels.get()); while(newChannelList.size() < capacity) { newChannelList.add(new InstrumentedChannel(factory.create())); } setChannels(newChannelList); } } } }
Source:
<code>protected Optional<AccessToken> tryJwt(String token, String type) { try { if (isJwt(token)) { final byte[] decoded = getDecoder().decode(splitToken(token)[1]); final JsonNode node = om.readTree(decoded); long expiration = node.get("exp").asLong(-1L); long initialValidSeconds = expiration - MILLISECONDS.toSeconds(currentTimeMillis()); return ofNullable(new AccessToken(token,type, initialValidSeconds, from(ofEpochSecond(expiration)))); } return empty(); } catch (Exception e) { <START> return empty(); <END> } }</code><technical_language>I suggest apply some warn logging here</technical_language>

Target:
protected Optional<AccessToken> tryJwt(String token, String type) { try { if (isJwt(token)) { final byte[] decoded = getDecoder().decode(splitToken(token)[1]); final JsonNode node = om.readTree(decoded); long expiration = node.get("exp").asLong(-1L); long initialValidSeconds = expiration - MILLISECONDS.toSeconds(currentTimeMillis()); return ofNullable(new AccessToken(token,type, initialValidSeconds, from(ofEpochSecond(expiration)))); } return empty(); } catch (Exception e) { logger.warn(e.getMessage()); return empty(); } }
Source:
<code>public void update(final GuidedDecisionTable52 model, final List<Coordinate> coordinates) { PortablePreconditions.checkNotNull("model", model); PortablePreconditions.checkNotNull("coordinates", coordinates); final Set<Integer> canBeUpdated = new HashSet<>(); for (final Coordinate coordinate : coordinates) { <START> if (coordinate.getCol() != GuidedDecisionTable52.RULE_NUMBER_INDEX && coordinate.getCol() != GuidedDecisionTable52.RULE_NAME_COLUMN_INDEX && coordinate.getCol() != GuidedDecisionTable52.RULE_DESCRIPTION_INDEX) { <END> if (getCellUpdateManager(coordinate, model).update()) { canBeUpdated.add(coordinate.getRow()); } } } boolean hadUpdates = !canBeUpdated.isEmpty(); if (hadUpdates) { analyzer.update(canBeUpdated); analyzer.analyze(); } }</code><technical_language>if compare index is greater GuidedDecisionTable52.RULE_DESCRIPTION_INDEX. thinking efficiency. Evaluting 1 condition 3 condition. is more safe. is opinion</technical_language>

Target:
public void update(final GuidedDecisionTable52 model, final List<Coordinate> coordinates) { PortablePreconditions.checkNotNull("model", model); PortablePreconditions.checkNotNull("coordinates", coordinates); final Set<Integer> canBeUpdated = new HashSet<>(); for (final Coordinate coordinate : coordinates) { if (coordinate.getCol() > GuidedDecisionTable52.RULE_DESCRIPTION_INDEX) { if (getCellUpdateManager(coordinate, model).update()) { canBeUpdated.add(coordinate.getRow()); } } } boolean hadUpdates = !canBeUpdated.isEmpty(); if (hadUpdates) { analyzer.update(canBeUpdated); analyzer.analyze(); } }
Source:
<code>public int getTiedJobCount() { SecurityContext context = ACL.impersonate(ACL.SYSTEM); try { int result = 0; for (TopLevelItem topLevelItem : Jenkins.getInstance().getItemMap().values()) { if (topLevelItem instanceof AbstractProject) { final AbstractProject project = (AbstractProject) topLevelItem; if (this.name.equals(project.getAssignedLabelString())) { result++; } } if (topLevelItem instanceof ItemGroup) { Stack<ItemGroup> q = new Stack<ItemGroup>(); q.push((ItemGroup) topLevelItem); while (!q.isEmpty()) { ItemGroup<?> parent = q.pop(); for (Item i : parent.getItems()) { if (i instanceof AbstractProject) { final AbstractProject project = (AbstractProject) i; <START> if (this.name.equals(project.getAssignedLabelString())) { <END> result++; } } if (i instanceof ItemGroup) { q.push((ItemGroup) i); } } } } } return result; } finally { SecurityContextHolder.setContext(context); } }</code><technical_language>I do this short-circuit work for derived Label classes. Derived Label classes entitled override equals assume a sub-class compares based name equality only</technical_language>

Target:
public int getTiedJobCount() { SecurityContext context = ACL.impersonate(ACL.SYSTEM); try { int result = 0; for (TopLevelItem topLevelItem : Jenkins.getInstance().getItemMap().values()) { if (topLevelItem instanceof AbstractProject) { final AbstractProject project = (AbstractProject) topLevelItem; if (matches(project.getAssignedLabelString())) { result++; } } if (topLevelItem instanceof ItemGroup) { Stack<ItemGroup> q = new Stack<ItemGroup>(); q.push((ItemGroup) topLevelItem); while (!q.isEmpty()) { ItemGroup<?> parent = q.pop(); for (Item i : parent.getItems()) { if (i instanceof AbstractProject) { final AbstractProject project = (AbstractProject) i; if (matches(project.getAssignedLabelString())) { result++; } } if (i instanceof ItemGroup) { q.push((ItemGroup) i); } } } } } return result; } finally { SecurityContextHolder.setContext(context); } }
Source:
<code>public Status mergeWith(Status that) { return this.compareTo(that) > 0 ? this : that; <START> } <END></code><technical_language>this... a re-implementation of natural ordering? I need this</technical_language>

Target:
public Status mergeWith(Status that) { return this.precedence >= that.precedence ? this : that; }
Source:
<code>public void shouldIterate() { for (byte depth = 1; depth <= 6; depth++) { for (int i = 0; i < getMaxSizeForDepth(depth); i++) { final Seq<Integer> expected = Array.range(0, i); final Vector<Integer> actual = Vector.ofAll(expected); assertAreEqual(actual, null, constant(actual), expected); } <START> System.out.println("Depth " + depth + " ok!"); <END> } }</code><technical_language>remove System.out calls (and assert if necessary)</technical_language>

Target:
public void shouldIterate() { for (byte depth = 0; depth <= 4; depth++) { for (int i = 0; i < getMaxSizeForDepth(depth); i++) { final Seq<Integer> expected = Array.range(0, i); final Vector<Integer> actual = Vector.ofAll(expected); assertAreEqual(actual, expected); } } }
Source:
<code>public Iterable<Class<?>> allTypes() { final List<ClassLoader> classloaders = new LinkedList<ClassLoader>(); classloaders.add(ClasspathHelper.contextClassLoader()); classloaders.add(ClasspathHelper.staticClassLoader()); final Set<Class<?>> all = new Reflections( new ConfigurationBuilder() .setScanners(new SubTypesScanner(false), new ResourcesScanner()) .setUrls( ClasspathHelper.forClassLoader( <START> classloaders.toArray( <END> new ClassLoader[classloaders.size()] ) ) ).filterInputsBy( new FilterBuilder().include( FilterBuilder.prefix("com.jcabi.github") ) ) ).getSubTypesOf(Object.class); return Iterables.filter( all, new Predicate<Class<?>>() { @Override public boolean apply(final Class<?> input) { final String name = input.getName(); if (name.endsWith("Test") || name.endsWith("ITCase") || name.endsWith("ClasspathRule") || (input.getEnclosingClass() != null && !name.endsWith("Smart"))) { return false; } return true; } }); }</code><technical_language>a list of classloaders right here? writing more lines needed :) look: java return Iterables.filter( new Reflections( new ConfigurationBuilder() .setScanners(new SubTypesScanner(false), new ResourcesScanner()) .setUrls( ClasspathHelper.forClassLoader( Arrays.asList( ClasspathHelper.contextClassLoader(), ClasspathHelper.staticClassLoader() ) ) ).filterInputsBy( new FilterBuilder().include( FilterBuilder.prefix("com.jcabi.github") ) ) ).getSubTypesOf(Object.class), new Predicate<Class<?>>() { @Override public boolean apply(final Class<?> input) { final String name = input.getName(); // @checkstyle BooleanExpressionComplexityCheck (10 lines) return !name.endsWith("Test") && !name.endsWith("ITCase") && !name.endsWith("ClasspathRule") && (input.getEnclosingClass() == null || name.endsWith("Smart"))); } } ); more readable</technical_language>

Target:
public Iterable<Class<?>> allTypes() { return Iterables.filter( new Reflections( new ConfigurationBuilder() .setScanners( new SubTypesScanner(false), new ResourcesScanner() ) .setUrls( ClasspathHelper.forClassLoader( ClasspathHelper.contextClassLoader(), ClasspathHelper.staticClassLoader() ) ).filterInputsBy( new FilterBuilder().include( FilterBuilder.prefix("com.jcabi.github") ) ) ).getSubTypesOf(Object.class), new Predicate<Class<?>>() { @Override public boolean apply(final Class<?> input) { final String name = input.getName(); return !name.endsWith("Test") && !name.endsWith("ITCase") && !name.endsWith("ClasspathRule") && (input.getEnclosingClass() == null || name.endsWith("Smart")); } } ); }
Source:
<code>public static <T> T decodeValue(String str, Class<T> clazz, boolean failOnUnknownProperties) throws DecodeException { ObjectReader reader = mapper.readerFor(clazz); if (failOnUnknownProperties) { reader = reader.with(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); } else { reader = reader.without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); } <START> <END> T ret; try { ret = reader.readValue(str); } catch (Exception e) { throw new DecodeException("Failed to decode:" + e.getMessage()); } return ret; }</code><technical_language>a thought, create a new reader everytime ? try object mapper if failOnUnknownProperties is true (there is a risk mapper configured otherwise)</technical_language>

Target:
public static <T> T decodeValue(String str, Class<T> clazz, boolean failOnUnknownProperties) throws DecodeException { try { if (failOnUnknownProperties) { return mapper.readValue(str, clazz); } else { return mapper.readerFor(clazz) .without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .readValue(str); } } catch (Exception e) { throw new DecodeException("Failed to decode:" + e.getMessage()); } }
Source:
<code><START> @Override public void unparse(SqlWriter writer, SqlCall call, int leftPrec, <END> int rightPrec) { assert call.operandCount() == 1; final SqlWriter.Frame frame = writer.startFunCall(getName()); call.operand(0).unparse(writer, 0, 0); writer.endFunCall(frame); }</code><technical_language>super.unparse(...)</technical_language>

Target:
@Override public void unparse(SqlWriter writer, SqlCall call, int leftPrec, int rightPrec) { super.unparse(writer, call, 0, 0); }
Source:
<code>protected AbstractHttpOverXmpp.Data parseData(XmlPullParser parser) throws XmlPullParserException, IOException { NamedElement child = null; boolean done = false; AbstractHttpOverXmpp.Data data = null; if (parser.getEventType() == XmlPullParser.START_TAG) { while (!done) { int eventType = parser.next(); if (eventType == XmlPullParser.START_TAG) { <START> if (parser.getName().equals(ELEMENT_TEXT)) { <END> child = parseText(parser); } else if (parser.getName().equals(ELEMENT_BASE_64)) { child = parseBase64(parser); } else if (parser.getName().equals(ELEMENT_CHUNKED_BASE_64)) { child = parseChunkedBase64(parser); } else if (parser.getName().equals(ELEMENT_XML)) { child = parseXml(parser); } else if (parser.getName().equals(ELEMENT_IBB)) { child = parseIbb(parser); } else if (parser.getName().equals(ELEMENT_SIPUB)) { throw new UnsupportedOperationException("sipub is not supported yet"); } else if (parser.getName().equals(ELEMENT_JINGLE)) { throw new UnsupportedOperationException("jingle is not supported yet"); } else { throw new IllegalArgumentException("unsupported child tag: " + parser.getName()); } } else if (eventType == XmlPullParser.END_TAG) { if (parser.getName().equals(ELEMENT_DATA)) { done = true; } } } data = new AbstractHttpOverXmpp.Data(child); } return data; }</code><technical_language>ideal case for a string switch-case. (most) other providers for examples</technical_language>

Target:
protected AbstractHttpOverXmpp.Data parseData(XmlPullParser parser) throws XmlPullParserException, IOException { NamedElement child = null; boolean done = false; AbstractHttpOverXmpp.Data data = null; if (parser.getEventType() == XmlPullParser.START_TAG) { while (!done) { int eventType = parser.next(); if (eventType == XmlPullParser.START_TAG) { switch (parser.getName()) { case ELEMENT_TEXT: child = parseText(parser); break; case ELEMENT_BASE_64: child = parseBase64(parser); break; case ELEMENT_CHUNKED_BASE_64: child = parseChunkedBase64(parser); break; case ELEMENT_XML: child = parseXml(parser); break; case ELEMENT_IBB: child = parseIbb(parser); break; case ELEMENT_SIPUB: throw new UnsupportedOperationException("sipub is not supported yet"); case ELEMENT_JINGLE: throw new UnsupportedOperationException("jingle is not supported yet"); default: throw new IllegalArgumentException("unsupported child tag: " + parser.getName()); } } else if (eventType == XmlPullParser.END_TAG) { if (parser.getName().equals(ELEMENT_DATA)) { done = true; } } } data = new AbstractHttpOverXmpp.Data(child); } return data; }
Source:
<code>public static boolean getScalabilityCapabilitiesOfModule(Map<String, Object> modules, String elementName) { try{ Map<String,Object> moduleInfo = (Map<String,Object>) modules.get(elementName); Map<String,Object> moduleProperties= (Map<String,Object>) moduleInfo.get(TOSCAkeywords.MODULE_PROPERTIES_TAG); boolean moduleCanScale = (boolean) moduleProperties.get(TOSCAkeywords.MODULE_AUTOSCALE_PROPERTY); return moduleCanScale; <START> }catch(Exception e){ <END> } return true; }</code><technical_language>Avoiding Empty catch. For example, log</technical_language>

Target:
public static boolean getScalabilityCapabilitiesOfModule(Map<String, Object> modules, String elementName) { try { Map<String, Object> moduleInfo = (Map<String, Object>) modules.get(elementName); Map<String, Object> moduleProperties = (Map<String, Object>) moduleInfo .get(TOSCAkeywords.MODULE_PROPERTIES_TAG); boolean moduleCanScale = (boolean) moduleProperties.get(TOSCAkeywords.MODULE_AUTOSCALE_PROPERTY); return moduleCanScale; } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("For module " + elementName + " it was not found information in the AAM regarding its possibility to scale"); } } return true; }
Source:
<code><START> public TableDefinition(String id) { <END> super(id); }</code><technical_language>this public, instead. use. TableDefinition.id()</technical_language>

Target:
protected TableDefinition(String id) { super(id); }
Source:
<code>public void downloadInterpreter() throws IOException { String interpreterName = "test-interpreter"; String artifactName = "junit:junit:4.11"; Path specificInterpreterPath = Files.createDirectory(Paths.get(interpreterDir.toString(), interpreterName)); DependencyResolver dependencyResolver = new DependencyResolver(localRepoDir.toString()); <START> doNothing().when(mockInterpreterSettingManager).refreshInterpreterTemplates(); <END> ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class); doNothing().when(mockNotebookServer).broadcast(messageArgumentCaptor.capture()); interpreterService.downloadInterpreter( new InterpreterInstallationRequest(interpreterName, artifactName), dependencyResolver, specificInterpreterPath, null); Message message = messageArgumentCaptor.getValue(); assertNotNull(message.data); assertEquals("Success", message.data.get("result")); assertEquals(interpreterName + " downloaded", message.data.get("message")); }</code><technical_language>Need verify refreshInterpreterTemplates is called download is succeeded</technical_language>

Target:
public void downloadInterpreter() throws IOException { final String interpreterName = "test-interpreter"; String artifactName = "junit:junit:4.11"; Path specificInterpreterPath = Files.createDirectory(Paths.get(interpreterDir.toString(), interpreterName)); DependencyResolver dependencyResolver = new DependencyResolver(localRepoDir.toString()); doNothing().when(mockInterpreterSettingManager).refreshInterpreterTemplates(); interpreterService.downloadInterpreter( new InterpreterInstallationRequest(interpreterName, artifactName), dependencyResolver, specificInterpreterPath, new ServiceCallback() { @Override public void onStart(String message) { assertEquals("Starting to download " + interpreterName + " interpreter", message); } @Override public void onSuccess(String message) { assertEquals(interpreterName + " downloaded", message); } @Override public void onFailure(String message) { fail(); } }); verify(mockInterpreterSettingManager, times(1)).refreshInterpreterTemplates(); }
Source:
<code>public @Nullable String getThreadName(ITmfEvent event) { ITmfEventField content = event.getContent(); ITmfEventField field = content.getField(fLayout.contextProcname()); <START> String procName = field == null ? "" : (String) field.getValue() + '-'; END> long vtid = getThreadId(event); return (procName + Long.toString(vtid)); }</code><technical_language>StringUtils.EMPTY_STRING Also, add () parenthesis, is unclear if appending '-' "" field.getValue(); Also, String.valueOf(field.getValue());</technical_language>

Target:
public @Nullable String getThreadName(ITmfEvent event) { ITmfEventField content = event.getContent(); ITmfEventField field = content.getField(fLayout.contextProcname()); String procName = field == null ? StringUtils.EMPTY : (String) field.getValue() + '-'; long vtid = getThreadId(event); return (procName + Long.toString(vtid)); }
Source:
<code>public int hashCode() { <START> final int prime = 31; <END> int result = super.hashCode(); result = prime * result + ((ntlmDomain == null) ? 0 : ntlmDomain.hashCode()); return result; }</code><technical_language>Objects.hash()</technical_language>

Target:
public int hashCode() { return hash(super.hashCode(), ntlmDomain); }
Source:
<code>private boolean checkSupport(MatrixLib x) { double sum = 0.0; for (int i = 0; i < x.numRows(); i++) { sum += x.elementAt(i, 0); } <START> return (sum <= (1 + TOLERANCE)) && (sum >= (1 - TOLERANCE)); <END> }</code><technical_language>Is a reason Util.TOLERANCE</technical_language>

Target:
private boolean checkSupport(MatrixLib x) { double sum = 0.0; for (int i = 0; i < x.numRows(); i++) { sum += x.elementAt(i, 0); } return (sum <= (1 + Util.TOLERANCE)) && (sum >= (1 - Util.TOLERANCE)); }
Source:
<code>public boolean containsDeviceWithType(List<VmDevice> devices, VmDeviceGeneralType generalType, VmDeviceType deviceType) { VmDevice foundDevice = getFirstDeviceWithType(devices, generalType, deviceType); <START> return foundDevice == null ? false : true; <END> }</code><technical_language>Enough: return foundDevice != null</technical_language>

Target:
public boolean containsDeviceWithType(List<VmDevice> devices, VmDeviceGeneralType generalType, VmDeviceType deviceType) { VmDevice foundDevice = getFirstDeviceWithType(devices, generalType, deviceType); return foundDevice != null; }
Source:
<code>private static String createTempLobFileName(DataHandler handler) throws IOException { String path = handler.getDatabasePath(); if (path.isEmpty()) { path = SysProperties.PREFIX_TEMP_FILE; } <START> return FileUtils.createTempFile(path, Constants.SUFFIX_TEMP_FILE, false, true); <END> }</code><technical_language>I moment, if in embedded mode, hand this file client jdbc code, assume client close delete file. If client is badly written, this leak handles. Personally, I is client codes problem, client fixed, noting a reason this code is this way</technical_language>

Target:
private static String createTempLobFileName(DataHandler handler) throws IOException { String path = handler.getDatabasePath(); if (path.isEmpty()) { path = SysProperties.PREFIX_TEMP_FILE; } return FileUtils.createTempFile(path, Constants.SUFFIX_TEMP_FILE, true); }
Source:
<code><START> final public boolean isExtendedLifeTimeToken() { <END> return mIsExtendedLifeTimeToken; }</code><technical_language>If run checkstyle, complain access modifier order. do public final instead of final public</technical_language>

Target:
public boolean isExtendedLifeTimeToken() { return mIsExtendedLifeTimeToken; }
Source:
<code>protected void execute() { logger.debug("Checking if host is available"); boolean success = false; int timeout = 5000; try { success = Ping.checkVitality(ip, 0, timeout); if (success) { logger.debug("established connection [host '{}' port '{}' timeout '{}']", new Object[] {ip, 0, timeout}); } else { logger.debug("couldn't establish network connection [host '{}' port '{}' timeout '{}']", new Object[] {ip, 0, timeout}); } } catch (SocketTimeoutException se) { logger.debug("timed out while connecting to host '{}' port '{}' timeout '{}'", new Object[] {ip, 0, timeout}); } catch (IOException ioe) { logger.debug("couldn't establish network connection [host '{}' port '{}' timeout '{}']", new Object[] {ip, 0, timeout}); } if (!success) { <START> return; <END> } for (JointSpaceBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { String tvcommand = provider.getTVCommand(itemName, "POLL"); if (tvcommand != null) { updateItemState(itemName,tvcommand); } } } }</code><technical_language>return in line 129</technical_language>

Target:
protected void execute() { logger.debug("Checking if host is available"); boolean success = false; int timeout = 5000; try { success = Ping.checkVitality(ip, 0, timeout); if (success) { logger.debug("established connection [host '{}' port '{}' timeout '{}']", new Object[] {ip, 0, timeout}); for (JointSpaceBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { String tvcommand = provider.getTVCommand(itemName, "POLL"); if (tvcommand != null) { updateItemState(itemName,tvcommand); } } } } else { logger.debug("couldn't establish network connection [host '{}' port '{}' timeout '{}']", new Object[] {ip, 0, timeout}); } } catch (SocketTimeoutException se) { logger.debug("timed out while connecting to host '{}' port '{}' timeout '{}'", new Object[] {ip, 0, timeout}); } catch (IOException ioe) { logger.debug("couldn't establish network connection [host '{}' port '{}' timeout '{}']", new Object[] {ip, 0, timeout}); } }
Source:
<code><START> private String findIntermediateTable() { <END> if (DbConnectionFactory.isMySql()) { return MYSQL_FIND_INTERMEDIATE_TABLE; } else if (DbConnectionFactory.isPostgres()) { return POSTGRES_FIND_INTERMEDIATE_TABLE; } else if (DbConnectionFactory.isMsSql()) { return MSSQL_FIND_INTERMEDIATE_TABLE; } else if (DbConnectionFactory.isOracle()) { return ORACLE_FIND_INTERMEDIATE_TABLE; } else { return null; } }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Reduce number of returns of this method 5, maximum allowed 3. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
private String findIntermediateTable() { String sql = null; if (DbConnectionFactory.isMySql()) { sql = MYSQL_FIND_INTERMEDIATE_TABLE; } else if (DbConnectionFactory.isPostgres()) { sql = POSTGRES_FIND_INTERMEDIATE_TABLE; } else if (DbConnectionFactory.isMsSql()) { sql = MSSQL_FIND_INTERMEDIATE_TABLE; } else if (DbConnectionFactory.isOracle()) { sql = ORACLE_FIND_INTERMEDIATE_TABLE; } return sql; }
Source:
<code>protected void processTuple(T tuple) { long time = getTime(tuple); Future<Slice> valFuture = managedState.getAsync(time, getKey(tuple)); if (valFuture.isDone()) { try { processEvent(tuple, valFuture.get()); } catch (InterruptedException | ExecutionException e) { <START> throw new RuntimeException("process", e); <END> } } else { processWaitingEvent(tuple, valFuture); } }</code><technical_language>describe exception</technical_language>

Target:
protected void processTuple(T tuple) { long time = getTime(tuple); Future<Slice> valFuture = managedState.getAsync(time, getKey(tuple)); if (valFuture.isDone()) { try { processEvent(tuple, valFuture.get()); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } else { processWaitingEvent(tuple, valFuture); } }
Source:
<code>public void consolesAdded(final IConsole[] consoles) { if (isAvailable()) { Runnable r = () -> { for (IConsole c : consoles) { if (isAvailable()) { <START> IConsole console = c; <END> IConsole[] allConsoles = getConsoleManager().getConsoles(); for (IConsole registered : allConsoles) { if (registered.equals(console)) { ConsoleWorkbenchPart part = new ConsoleWorkbenchPart(console, getSite()); fConsoleToPart.put(console, part); fPartToConsole.put(part, console); partActivated(part); break; } } } } }; asyncExec(r); } }</code><technical_language>obsolete naming loopvar 'console'</technical_language>

Target:
public void consolesAdded(final IConsole[] consoles) { if (isAvailable()) { Runnable r = () -> { for (IConsole console : consoles) { if (isAvailable()) { IConsole[] allConsoles = getConsoleManager().getConsoles(); for (IConsole registered : allConsoles) { if (registered.equals(console)) { ConsoleWorkbenchPart part = new ConsoleWorkbenchPart(console, getSite()); fConsoleToPart.put(console, part); fPartToConsole.put(part, console); partActivated(part); break; } } } } }; asyncExec(r); } }
Source:
<code>private void sendTicket() { final DbUser user = getCurrentUser(); final boolean sent = runVdsCommand(VDSCommandType.SetVmTicket, new SetVmTicketVDSCommandParameters(getVdsId(), getVmId(), ticket, getParameters().getValidTime(), <START> user.getLoginName(), user.getId(), getParameters().getGraphicsType(), getVm().getConsoleDisconnectAction(), <END> getVm().getClusterCompatibilityVersion())).getSucceeded(); if (sent) { setActionReturnValue(ticket); } setSucceeded(sent); }</code><technical_language>Please, format line</technical_language>

Target:
private void sendTicket() { final DbUser user = getCurrentUser(); final boolean sent = runVdsCommand(VDSCommandType.SetVmTicket, new SetVmTicketVDSCommandParameters(getVdsId(), getVmId(), ticket, getParameters().getValidTime(), user.getLoginName(), user.getId(), getParameters().getGraphicsType(), getVm().getConsoleDisconnectAction(), getVm().getCompatibilityVersion())).getSucceeded(); if (sent) { setActionReturnValue(ticket); } setSucceeded(sent); }
Source:
<code><START> public TerminationRequest(String message) { <END> super(message); }</code><technical_language>helpful record date/time well</technical_language>

Target:
public TerminationRequest(String message) { super(message); this.when = System.currentTimeMillis(); }
Source:
<code>public void letTheSupervisorDo(Consumer<EmptyTask> action) { <START> if (supervisor != null) { <END> action.accept(supervisor); } }</code><technical_language>Objects.nonNull</technical_language>

Target:
public void letTheSupervisorDo(Consumer<EmptyTask> action) { if (Objects.nonNull(supervisor)) { action.accept(supervisor); } }
Source:
<code>public String addPromo(HttpServletRequest request, HttpServletResponse response, Model model, String customerOffer) throws IOException, PricingException, ItemNotFoundException, OfferMaxUseExceededException { Order cart = CartState.getCart(request); Boolean promoAdded = false; OfferCode offerCode = offerService.lookupOfferCodeByCode(customerOffer); <START> if(offerCode!=null&&offerService.verifyMaxCustomerUsageThreshold(cart.getCustomer(), offerCode.getOffer())) { <END> cartService.addOfferCode(cart, offerCode, false); promoAdded = true; } cartService.save(cart, true); CartState.setCart(request, cart); if (isAjaxRequest(request)) { Map<String, Object> extraData = new HashMap<String, Object>(); extraData.put("promoAdded", promoAdded); model.addAttribute("blcextradata", new ObjectMapper().writeValueAsString(extraData)); return "ajax/cart"; } else { return "redirect:/cart"; } }</code><technical_language>clean spacing need verifyMaxCustomerUsageThreshold; this check is done in cartService, need catch exception</technical_language>

Target:
public String addPromo(HttpServletRequest request, HttpServletResponse response, Model model, String customerOffer) throws IOException, PricingException { Order cart = CartState.getCart(request); Boolean promoAdded = false; String exception = ""; OfferCode offerCode = offerService.lookupOfferCodeByCode(customerOffer); if(offerCode!=null) { try { cartService.addOfferCode(cart, offerCode, false); promoAdded = true; cart = cartService.save(cart, true); } catch(OfferMaxUseExceededException e) { exception = "Use Limit Exceeded"; } } else { exception = "Invalid Code"; } CartState.setCart(request, cart); if (isAjaxRequest(request)) { Map<String, Object> extraData = new HashMap<String, Object>(); extraData.put("promoAdded", promoAdded); extraData.put("exception" , exception); model.addAttribute("blcextradata", new ObjectMapper().writeValueAsString(extraData)); return "ajax/cart"; } else { return "redirect:/cart"; } }
Source:
<code><START> public static double greatCircleDistance(double latitude1, double longitude1, double latitude2, double longitude2) { <END> checkLatitude(latitude1); checkLongitude(longitude1); checkLatitude(latitude2); checkLongitude(longitude2); double radianLatitude1 = toRadians(latitude1); double radianLatitude2 = toRadians(latitude2); double sin1 = sin(radianLatitude1); double cos1 = cos(radianLatitude1); double sin2 = sin(radianLatitude2); double cos2 = cos(radianLatitude2); double deltaLongitude = toRadians(longitude1) - toRadians(longitude2); double cosDeltaLongitude = cos(deltaLongitude); double t1 = cos2 * sin(deltaLongitude); double t2 = cos1 * sin2 - sin1 * cos2 * cosDeltaLongitude; double t3 = sin1 * sin2 + cos1 * cos2 * cosDeltaLongitude; return atan2(sqrt(t1 * t1 + t2 * t2), t3) * GeometryUtils.EARTH_RADIUS_KM; }</code><technical_language>work line dateline</technical_language>

Target:
private static double greatCircleDistance(double latitude1, double longitude1, double latitude2, double longitude2) { checkLatitude(latitude1); checkLongitude(longitude1); checkLatitude(latitude2); checkLongitude(longitude2); double radianLatitude1 = toRadians(latitude1); double radianLatitude2 = toRadians(latitude2); double sin1 = sin(radianLatitude1); double cos1 = cos(radianLatitude1); double sin2 = sin(radianLatitude2); double cos2 = cos(radianLatitude2); double deltaLongitude = toRadians(longitude1) - toRadians(longitude2); double cosDeltaLongitude = cos(deltaLongitude); double t1 = cos2 * sin(deltaLongitude); double t2 = cos1 * sin2 - sin1 * cos2 * cosDeltaLongitude; double t3 = sin1 * sin2 + cos1 * cos2 * cosDeltaLongitude; return atan2(sqrt(t1 * t1 + t2 * t2), t3) * GeometryUtils.EARTH_RADIUS_M; }
Source:
<code>public String toString() { StringBuffer buff = new StringBuffer(getParentString()); buff.append(", queueName=" + queueName); buff.append(", filterString=" + filterString); <START> buff.append(", priority=" + priority); <END> buff.append(", id=" + id); buff.append(", browseOnly=" + browseOnly); buff.append(", requiresResponse=" + requiresResponse); buff.append("]"); return buff.toString(); }</code><technical_language>Nitpicking, other details emitted 'in order' relative buffer content, sense put this end consistent location</technical_language>

Target:
public String toString() { StringBuffer buff = new StringBuffer(getParentString()); buff.append(", queueName=" + queueName); buff.append(", filterString=" + filterString); buff.append(", id=" + id); buff.append(", browseOnly=" + browseOnly); buff.append(", requiresResponse=" + requiresResponse); buff.append(", priority=" + priority); buff.append("]"); return buff.toString(); }
Source:
<code>public void tesIsModifiedBySameLastModifiedAndDifferentSize() throws Exception { File f1 = createFile("foo", "lorem".getBytes()); File f2 = createFile("bar", "lorem ipsum".getBytes()); <START> long now = System.currentTimeMillis(); <END> f1.setLastModified(f2.lastModified()); FileSnapshot save = FileSnapshot.save(f1); Thread.sleep(3000L); assertEquals(save.lastModified(), f2.lastModified()); assertTrue(save.isModified(f2)); }</code><technical_language>is unused</technical_language>

Target:
public void tesIsModifiedBySameLastModifiedAndDifferentSize() throws Exception { File f1 = createFile("foo", "lorem".getBytes()); File f2 = createFile("bar", "lorem ipsum".getBytes()); f1.setLastModified(f2.lastModified()); FileSnapshot save = FileSnapshot.save(f1); Thread.sleep(3000L); assertEquals(save.lastModified(), f2.lastModified()); assertTrue(save.isModified(f2)); }