auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public StreamingOutput setSolr(@PathParam("command") final String command, @Context UriInfo uriInfo) throws JsonGenerationException, JsonMappingException, IOException { if (!"select".equals(command)) { throw new WebApplicationException(); } String query = uriInfo.getRequestUri().getRawQuery(); if (null == query) { throw new WebApplicationException(); } return new StringStreamingOutput(searchService.select(query)); }

Target:
public StreamingOutput setSolr(@PathParam("command") final String command, @Context UriInfo uriInfo) throws JsonGenerationException, JsonMappingException, IOException { if (!"select".equals(command)) { throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity("command not supported").build()); } String query = uriInfo.getRequestUri().getRawQuery(); if (null == query) { throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity("invalid query").build()); } ResultsWrapper results; try { results = searchService.select(query); } catch (Exception e) { throw new WebApplicationException(Response.serverError().entity("search not available").build()); } return new StringStreamingOutput(results); }
Source:
private String writeToString() { StringBuilder buf = new StringBuilder(); int index = 0; for (HashMap.Entry<String, ValidWriteIdList> entry : validTablesWriteIdList.entrySet()) { buf.append(entry.getValue().writeToString()); index++; if (index < validTablesWriteIdList.size()) { buf.append('$'); } } return buf.toString(); }

Target:
private String writeToString() { StringBuilder buf = new StringBuilder(txnId.toString()); int index = 0; for (HashMap.Entry<String, ValidWriteIdList> entry : tablesValidWriteIdList.entrySet()) { if (index < tablesValidWriteIdList.size()) { buf.append('$'); } buf.append(entry.getValue().writeToString()); index++; } return buf.toString(); }
Source:
public static List<String> getLocalesKeys(ConfigValues configValues) { if (!configValues.equals(ConfigValues.UnsupportedLocalesFilter) && !configValues.equals(ConfigValues.UnsupportedLocalesFilterOverrides)) { throw new IllegalArgumentException("Passed in config value not related to locales"); } List<String> locales = Config.<List<String>> getValue(configValues); List<String> result = new ArrayList<String>(); if (locales != null && !locales.isEmpty()) { for (String localeKey: locales) { try { String underScoredLocaleKey = localeKey.replaceAll("-", "_"); org.apache.commons.lang.LocaleUtils.toLocale(underScoredLocaleKey); result.add(underScoredLocaleKey); } catch (IllegalArgumentException iae) { log.info("Invalid locale found in configuration: " + localeKey); } } } return result; }

Target:
public static List<String> getLocalesKeys(ConfigValues configValues) { if (!configValues.equals(ConfigValues.UnsupportedLocalesFilter) && !configValues.equals(ConfigValues.UnsupportedLocalesFilterOverrides)) { throw new IllegalArgumentException("Passed in config value not related to locales"); } List<String> locales = Config.<List<String>> getValue(configValues); List<String> result = new ArrayList<String>(); if (locales != null && !locales.isEmpty()) { for (String localeKey: locales) { try { String underScoredLocaleKey = localeKey.replaceAll("-", "_"); LocaleUtils.toLocale(underScoredLocaleKey); result.add(underScoredLocaleKey); } catch (IllegalArgumentException iae) { log.info("Invalid locale found in configuration: " + localeKey); } } } return result; }
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { if (permissionCheckSubject == null) { permissionCheckSubject = new ArrayList<>(); if (getParameters().getTemplateType() != VmEntityType.INSTANCE_TYPE) { Guid storagePoolId = getCluster() == null ? null : getCluster().getStoragePoolId(); permissionCheckSubject.add(new PermissionSubject(storagePoolId, VdcObjectType.StoragePool, getActionType().getActionGroup())); VmStatic vmFromParams = getParameters().getMasterVm(); Set<Guid> dedicatedVmForVdsFromVm = new HashSet<>(getVm().getDedicatedVmForVdsList()); Set<Guid> dedicatedVmForVdsFromUser = new HashSet<>(vmFromParams.getDedicatedVmForVdsList()); if (!dedicatedVmForVdsFromVm.equals(dedicatedVmForVdsFromUser) || !StringUtils.isEmpty(vmFromParams.getCpuPinning())) { permissionCheckSubject.add( new PermissionSubject(storagePoolId, VdcObjectType.StoragePool, ActionGroup.EDIT_ADMIN_TEMPLATE_PROPERTIES)); } } else { permissionCheckSubject.add(new PermissionSubject(Guid.SYSTEM, VdcObjectType.System, getActionType().getActionGroup())); } } return permissionCheckSubject; }

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { if (permissionCheckSubject == null) { permissionCheckSubject = new ArrayList<>(); if (getParameters().getTemplateType() != VmEntityType.INSTANCE_TYPE) { Guid storagePoolId = getCluster() == null ? null : getCluster().getStoragePoolId(); permissionCheckSubject.add(new PermissionSubject(storagePoolId, VdcObjectType.StoragePool, getActionType().getActionGroup())); if (!new HashSet<>(getParameters().getMasterVm().getDedicatedVmForVdsList()) .equals(new HashSet<>(getVm().getDedicatedVmForVdsList())) || !StringUtils.isEmpty(getParameters().getMasterVm().getCpuPinning())) { permissionCheckSubject.add( new PermissionSubject(storagePoolId, VdcObjectType.StoragePool, ActionGroup.EDIT_ADMIN_TEMPLATE_PROPERTIES)); } } else { permissionCheckSubject.add(new PermissionSubject(Guid.SYSTEM, VdcObjectType.System, getActionType().getActionGroup())); } } return permissionCheckSubject; }
Source:
public byte[] loadContent(String id) { File file = getFileByPath(id); if (file.exists() && !file.isFile() && !ArrayUtils.isEmpty(file.listFiles())) { try { File destination = file.listFiles()[0]; return FileUtils.readFileToByteArray(destination); } catch (IOException e) { } } return null; }

Target:
public byte[] loadContent(String id) { File file = getFileByPath(id); if (file.exists() && !file.isFile() && !ArrayUtils.isEmpty(file.listFiles())) { try { File destination = file.listFiles()[0]; return FileUtils.readFileToByteArray(destination); } catch (IOException e) { log.error("Unable to laod content due to {}", e.getMessage(), e); } } return null; }
Source:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { super.configurePipeline(pipelineConfigurer); parseConfiguration(config.encode); Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { for (Schema.Field field : inputSchema.getFields()) { if (encodeMap.containsKey(field.getName())) { if (!field.getSchema().getType().equals(Schema.Type.BYTES) && !field.getSchema().getType().equals(Schema.Type.STRING)) { throw new IllegalArgumentException( String.format("Field %s is of type %s in Input Schema, currently only String and Bytes can be encoded", field.getName(), field.getSchema().getType())); } } } } try { Schema outputSchema = Schema.parseJson(config.schema); pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); } catch (IOException e) { throw new IllegalArgumentException("Format of schema specified is invalid. Please check the format."); } }

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { super.configurePipeline(pipelineConfigurer); parseConfiguration(config.encode); Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { for (Schema.Field field : inputSchema.getFields()) { if (encodeMap.containsKey(field.getName())) { if (!field.getSchema().getType().equals(Schema.Type.BYTES) && !field.getSchema().getType().equals(Schema.Type.STRING)) { throw new IllegalArgumentException( String.format("Input field %s should be of type bytes or string. It is currently of type %s", field.getName(), field.getSchema().getType().toString())); } } } } try { Schema outputSchema = Schema.parseJson(config.schema); pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); } catch (IOException e) { throw new IllegalArgumentException("Format of schema specified is invalid. Please check the format."); } }
Source:
private void validate() { Assert.isTrue(modules != null && modules.size() > 0, "at least one definition required"); ModuleType inferredType = null; if (modules.size() == 1) { inferredType = modules.get(0).getType(); } else { ModuleType firstType = modules.get(0).getType(); ModuleType lastType = modules.get(modules.size() - 1).getType(); boolean hasInput = (!firstType.equals(ModuleType.source)); boolean hasOutput = (!lastType.equals(ModuleType.sink)); if (hasInput && hasOutput) { inferredType = ModuleType.processor; } else if (hasInput) { inferredType = ModuleType.sink; } else if (hasOutput) { inferredType = ModuleType.source; } } Assert.isTrue(inferredType == this.getType(), "invalid composite module: inferred type=" + inferredType + ", stated type=" + this.getType()); }

Target:
private void validate() { Assert.isTrue(modules != null && modules.size() > 0, "at least one definition required"); ModuleType inferredType = null; if (modules.size() == 1) { inferredType = modules.get(0).getType(); } else { ModuleType firstType = modules.get(0).getType(); ModuleType lastType = modules.get(modules.size() - 1).getType(); boolean hasInput = firstType != ModuleType.source; boolean hasOutput = lastType != ModuleType.sink; if (hasInput && hasOutput) { inferredType = ModuleType.processor; } else if (hasInput) { inferredType = ModuleType.sink; } else if (hasOutput) { inferredType = ModuleType.source; } } Assert.isTrue(inferredType == this.getType(), "invalid composite module: inferred type=" + inferredType + ", stated type=" + this.getType()); }
Source:
public void onRequestUpdated(Request request) { if (pendingRequest == null) return; if (!request.getObjectId().equals(pendingRequest.getObjectId())) return; if (request.getState().equals(Request.State.PENDING)) ; if (request.getState().equals(Request.State.FULFILLED)) return; else onError(new IllegalStateException("Illegal Request State: " + request.getState().toString())); }

Target:
public void onRequestUpdated(Request request) { if (openRequest == null) return; if (!request.getObjectId().equals(openRequest.getObjectId())) return; if (request.getState().equals(Request.State.OPEN)) return; if (request.getState().equals(Request.State.ACTIVE)) startRequestActiveActivity(); onError(new IllegalStateException("Illegal Request State: " + request.getState().toString())); }
Source:
public DockerImageName apply(final DockerImageName original) { if (original.equals(DockerImageName.parse("registry.mycompany.com/mirror/mysql:8.0.22"))) { return defaultImageNameSubstitutor.apply(DockerImageName.parse("mysql")); } else { return defaultImageNameSubstitutor.apply(original); } }

Target:
public DockerImageName apply(final DockerImageName original) { if (original.equals(DockerImageName.parse("registry.mycompany.com/mirror/mysql:8.0.22"))) { return DockerImageName.parse("mysql"); } else { return original; } }
Source:
public Time getTime(int columnIndex, Calendar cal) throws SQLException { try { String value = getString(columnIndex); SimpleDateFormat dateFormat = new SimpleDateFormat(TIMESTAMP_FORMAT); java.util.Date date = dateFormat.parse(value); cal.setTime(date); Time sqlTime = new Time(cal.getTimeInMillis()); return sqlTime; } catch (Exception e) { throw new SQLException("Unable to fetch date", e); } }

Target:
public Time getTime(int columnIndex, Calendar cal) throws SQLException { try { String value = getString(columnIndex); return DateTimeUtils.getTimeFromString(value, cal); } catch (Exception e) { throw new SQLException("Unable to fetch date", e); } }
Source:
public void open() { iPythonInterpreter = getIPythonInterpreter(); if (getProperty().getProperty("zeppelin.python.useIPython", "true").equals("true") && iPythonInterpreter.checkIPythonPrerequisite()) { try { iPythonInterpreter.open(); if (InterpreterContext.get() != null) { InterpreterContext.get().out.write(("IPython is available, " + "use IPython for PythonInterpreter\n") .getBytes()); } return; } catch (Exception e) { iPythonInterpreter = null; } } iPythonInterpreter = null; try { if (InterpreterContext.get() != null) { InterpreterContext.get().out.write(("IPython is not available, " + "use the native PythonInterpreter\n") .getBytes()); } } catch (IOException e) { LOG.warn(e.getMessage()); } InterpreterGroup intpGroup = getInterpreterGroup(); if (intpGroup != null && intpGroup.getInterpreterHookRegistry() != null) { registerHook(HookType.POST_EXEC_DEV, "__zeppelin__._displayhook()"); } try { createGatewayServerAndStartScript(); } catch (UnknownHostException e) { throw new InterpreterException(e); } }

Target:
public void open() { iPythonInterpreter = getIPythonInterpreter(); if (getProperty().getProperty("zeppelin.python.useIPython", "true").equals("true") && iPythonInterpreter.checkIPythonPrerequisite()) { try { iPythonInterpreter.open(); if (InterpreterContext.get() != null) { InterpreterContext.get().out.write(("IPython is available, " + "use IPython for PythonInterpreter\n") .getBytes()); } LOG.info("Use IPythonInterpreter to replace PythonInterpreter"); return; } catch (Exception e) { iPythonInterpreter = null; } } iPythonInterpreter = null; try { if (InterpreterContext.get() != null) { InterpreterContext.get().out.write(("IPython is not available, " + "use the native PythonInterpreter\n") .getBytes()); } } catch (IOException e) { LOG.warn("Fail to write InterpreterOutput", e.getMessage()); } InterpreterGroup intpGroup = getInterpreterGroup(); if (intpGroup != null && intpGroup.getInterpreterHookRegistry() != null) { registerHook(HookType.POST_EXEC_DEV, "__zeppelin__._displayhook()"); } try { createGatewayServerAndStartScript(); } catch (UnknownHostException e) { throw new InterpreterException(e); } }
Source:
public void deleteOneTemplateTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, parentCommunity).withName("Collection 1").build(); Item templateItem = ItemBuilder.createTemplateItem(context, col1); String token = getAuthToken(admin.getEmail(), password); getClient().perform(get("/api/core/items/" + templateItem.getID())) .andExpect(status().isOk()); getClient(token).perform(delete("/api/core/items/" + templateItem.getID())) .andExpect(status().is(422)); }

Target:
public void deleteOneTemplateTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, parentCommunity).withName("Collection 1") .withTemplateItem() .build(); Item templateItem = col1.getTemplateItem(); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(delete("/api/core/items/" + templateItem.getID())) .andExpect(status().is(422)); getClient().perform(get("/api/core/items/" + templateItem.getID())) .andExpect(status().isOk()); }
Source:
public void stop() { Runnable r = new Runnable() { @Override public void run() { stopHawkularAgent(); } }; new Thread(r).start(); }

Target:
public void stop() { stopHawkularAgent(); }
Source:
protected void delete(Context context, UUID uuid) throws AuthorizeException { Group group = null; try { group = gs.find(context, uuid); if (group == null) { throw new ResourceNotFoundException( GroupRest.CATEGORY + "." + GroupRest.NAME + " with id: " + uuid + " not found" ); } if (isDeleteUnprocessable(context, group)) { throw new UnprocessableEntityException("This group cannot be deleted"); } gs.delete(context, group); } catch (SQLException | IOException e) { throw new RuntimeException(e.getMessage(), e); } }

Target:
protected void delete(Context context, UUID uuid) throws AuthorizeException { Group group = null; try { group = gs.find(context, uuid); if (group == null) { throw new ResourceNotFoundException( GroupRest.CATEGORY + "." + GroupRest.NAME + " with id: " + uuid + " not found" ); } try { if (group.isPermanent()) { throw new UnprocessableEntityException("A permanent group cannot be deleted"); } final DSpaceObject parentObject = gs.getParentObject(context, group); if (parentObject != null) { throw new UnprocessableEntityException( "This group cannot be deleted" + " as it has a parent " + parentObject.getType() + " with id " + parentObject.getID()); } } catch (SQLException e) { throw new RuntimeException(e); } gs.delete(context, group); } catch (SQLException | IOException e) { throw new RuntimeException(e.getMessage(), e); } }
Source:
void clearExpressionType() { final GridCellTuple gc = new GridCellTuple(0, 0, this); final FunctionDefinition function = expression.get(); sessionCommandManager.execute((AbstractCanvasHandler) sessionManager.getCurrentSession().getCanvasHandler(), new ClearExpressionTypeCommand(gc, function, uiModelMapper, () -> synchroniseViewWhenExpressionEditorChanged(Optional.empty()))); }

Target:
void clearExpressionType() { expression.ifPresent(function -> { final GridCellTuple gc = new GridCellTuple(0, 0, this); sessionCommandManager.execute((AbstractCanvasHandler) sessionManager.getCurrentSession().getCanvasHandler(), new ClearExpressionTypeCommand(gc, function, uiModelMapper, () -> synchroniseViewWhenExpressionEditorChanged(Optional.empty()))); }); }
Source:
private ExecuteResult(InputStream stream, InputStream errorStream, int responseCode, String responseMessage, Throwable cause, JSONHelper jsonHelper) { this.responseCode = responseCode; boolean needsCouchException = false; System.out.println("Response: "+responseMessage); switch(responseCode / 100) { case 1: case 2: this.fatal = false; this.exception = null; this.stream = stream; break; case 3: break; case 4: this.fatal = true; if (responseCode == 404) { this.exception = new NoResourceException(responseMessage, cause); } else if (responseCode == 409) { this.exception = new DocumentConflictException(responseMessage); } else { needsCouchException = true; } break; case 5: this.fatal = false; needsCouchException = true; break; default: this.fatal = false; needsCouchException = true; } if (needsCouchException) { try { Map<String, String> json = jsonHelper.fromJson(new InputStreamReader(errorStream), Map.class); CouchException ce = new CouchException(responseMessage, cause, responseCode); ce.setError(json.get("error")); ce.setReason(json.get("reason")); this.exception = ce; } catch (Exception e) { CouchException ce = new CouchException("Error deserializing server response", cause, responseCode); this.exception = ce; } } }

Target:
private ExecuteResult(InputStream stream, InputStream errorStream, int responseCode, String responseMessage, Throwable cause, JSONHelper jsonHelper) { this.responseCode = responseCode; boolean needsCouchException = false; switch(responseCode / 100) { case 1: case 2: this.fatal = false; this.exception = null; this.stream = stream; break; case 3: throw new CouchException("Unexpected redirection (3xx) code encountered", responseCode); case 4: this.fatal = true; if (responseCode == 404) { this.exception = new NoResourceException(responseMessage, cause); } else if (responseCode == 409) { this.exception = new DocumentConflictException(responseMessage); } else { needsCouchException = true; } break; case 5: this.fatal = false; needsCouchException = true; break; default: this.fatal = false; needsCouchException = true; } if (needsCouchException) { try { Map<String, String> json = jsonHelper.fromJson(new InputStreamReader(errorStream), Map.class); CouchException ce = new CouchException(responseMessage, cause, responseCode); ce.setError(json.get("error")); ce.setReason(json.get("reason")); this.exception = ce; } catch (Exception e) { CouchException ce = new CouchException("Error deserializing server response", cause, responseCode); this.exception = ce; } } }
Source:
private static IEclipseContext headlessContext() { if (HEADLESS_CONTEXT == null) { HEADLESS_CONTEXT = EclipseContextFactory.create("headlessContext"); } return HEADLESS_CONTEXT; }

Target:
private static synchronized IEclipseContext headlessContext() { if (HEADLESS_CONTEXT == null) { HEADLESS_CONTEXT = EclipseContextFactory.create("headlessContext"); } return HEADLESS_CONTEXT; }
Source:
public void testMaxAge() throws InterruptedException { Summary summary = Summary.build() .quantile(0.99, 0.001) .maxAgeMillis(200) .nBuckets(2) .name("short_attention_span").help("help").register(registry); summary.observe(8.0); double val = registry.getSampleValue("short_attention_span", new String[]{"quantile"}, new String[]{Collector.doubleToGoString(0.99)}).doubleValue(); assertEquals(8.0, val, 0.0); Thread.sleep(100); val = registry.getSampleValue("short_attention_span", new String[]{"quantile"}, new String[]{Collector.doubleToGoString(0.99)}).doubleValue(); assertEquals(8.0, val, 0.0); Thread.sleep(100); val = registry.getSampleValue("short_attention_span", new String[]{"quantile"}, new String[]{Collector.doubleToGoString(0.99)}).doubleValue(); assertEquals(Double.NaN, val, 0.0); }

Target:
public void testMaxAge() throws InterruptedException { Summary summary = Summary.build() .quantile(0.99, 0.001) .maxAgeSeconds(1) .ageBuckets(2) .name("short_attention_span").help("help").register(registry); summary.observe(8.0); double val = registry.getSampleValue("short_attention_span", new String[]{"quantile"}, new String[]{Collector.doubleToGoString(0.99)}).doubleValue(); assertEquals(8.0, val, 0.0); Thread.sleep(600); val = registry.getSampleValue("short_attention_span", new String[]{"quantile"}, new String[]{Collector.doubleToGoString(0.99)}).doubleValue(); assertEquals(8.0, val, 0.0); Thread.sleep(600); val = registry.getSampleValue("short_attention_span", new String[]{"quantile"}, new String[]{Collector.doubleToGoString(0.99)}).doubleValue(); assertEquals(Double.NaN, val, 0.0); }
Source:
public void run() { do { state.accept(this); setPosition(getPosition() + 1); setProgress(); if (supervisor != null && supervisor.isInterrupted()) { return; } } while (!(state.equals(ImageGeneratorStep.GENERATE_IMAGES) && getPosition() == getContentToBeGenerated().size())); logger.info("Completed"); }

Target:
public void run() { do { state.accept(this); setPosition(getPosition() + 1); setProgress(); if (Objects.nonNull(supervisor) && supervisor.isInterrupted()) { return; } } while (!(state.equals(ImageGeneratorStep.GENERATE_IMAGES) && getPosition() == getContentToBeGenerated().size())); logger.info("Completed"); }
Source:
public void execute(SchemaMigrationOption schemaMigrationOption) throws SQLException { switch (schemaMigrationOption) { case CREATE: create(); break; case MIGRATE: migrate(); break; case INFO: info(); break; case VALIDATE: validate(); break; case DROP: clean(); break; case CHECK_CONNECTION: if(!checkConnection()) { System.exit(1); } break; case REPAIR: repair(); break; default: throw new SchemaMigrationException("SchemaMigrationHelper unable to execute the option : " + schemaMigrationOption.toString()); } }

Target:
public void execute(SchemaMigrationOption schemaMigrationOption) throws SQLException { switch (schemaMigrationOption) { case CREATE: create(); break; case MIGRATE: migrate(); break; case INFO: info(); break; case VALIDATE: validate(); break; case DROP: clean(); break; case CHECK_CONNECTION: checkConnection(); break; case REPAIR: repair(); break; default: throw new SchemaMigrationException("SchemaMigrationHelper unable to execute the option : " + schemaMigrationOption.toString()); } }
Source:
public Key getKey(int pos) { return new Key(key.getRow(), timeStamps.get(pos)); }

Target:
public Key getKey(int pos) { Key tmpKey = new Key(key); tmpKey.setTimestamp(timeStamps.get(pos)); return tmpKey; }
Source:
public synchronized void close() throws IOException { try { keySerializer.close(); valSerializer.close(); if (out != null) { if (ownOutputStream) { out.close(); } else { out.flush(); } out = null; } } finally { if (fs != null) { try { fs.close(); } catch (Throwable t) { log.error("Could not close FileSystem", t); } } } }

Target:
public synchronized void close() throws IOException { try { keySerializer.close(); valSerializer.close(); if (out != null) { if (ownOutputStream) { out.close(); } else { out.flush(); } } } finally { if (fs != null) { try { fs.close(); } catch (Throwable t) { log.error("Could not close FileSystem", t); } } out = null; } }
Source:
protected void runOneIteration() throws Exception { log.trace("runOneIteration() - Enter"); lock.lock(); try { updateCache(); } finally { lock.unlock(); } log.trace("runOneIteration() - Exit"); }

Target:
protected void runOneIteration() throws Exception { log.trace("runOneIteration() - Enter"); lock.lock(); try { updateCache(); } finally { lock.unlock(); log.trace("runOneIteration() - Exit"); } }
Source:
public Application createApplication(Application application) { ApplicationCredentials.Builder credentialsBuilder; if (application.getCredentials() != null) { credentialsBuilder = application.getCredentials().copy(); } else { credentialsBuilder = ApplicationCredentials.builder(); } credentialsBuilder = credentialsBuilder.withApiKey(generateApiKey()); ApplicationSources sources = application.getSources(); if (sources == null) { sources = ApplicationSources .builder() .withPrecedence(false) .withReads(ImmutableList.<SourceReadEntry>of()) .withWrites(ImmutableList.<Publisher>of()) .build(); } Id id = Id.valueOf(idGenerator.generateRaw()); Application created = application.copy() .withId(id) .withCreated(clock.now()) .withSlug(generateSlug(id)) .withCredentials(credentialsBuilder.build()) .withSources(sources) .build(); doCreateApplication(created); return created; }

Target:
public Application createApplication(Application application) { ApplicationCredentials.Builder credentialsBuilder; if (application.getCredentials() != null) { credentialsBuilder = application.getCredentials().copy(); } else { credentialsBuilder = ApplicationCredentials.builder(); } credentialsBuilder = credentialsBuilder.withApiKey(generateApiKey()); ApplicationSources sources = application.getSources(); if (sources == null) { sources = ApplicationSources.EMPTY_SOURCES; } Id id = Id.valueOf(idGenerator.generateRaw()); Application created = application.copy() .withId(id) .withCreated(clock.now()) .withSlug(generateSlug(id)) .withCredentials(credentialsBuilder.build()) .withSources(sources) .build(); doCreateApplication(created); return created; }
Source:
private byte getJpegQuality() { if (mCaptureMode == CAPTURE_MODE_MAXIMIZE_QUALITY) { return JPEG_QUALITY_MAXIMIZE_QUALITY_MODE; } else if (mCaptureMode == CAPTURE_MODE_MINIMIZE_LATENCY) { return JPEG_QUALITY_MINIMIZE_LATENCY_MODE; } else { throw new IllegalStateException("CaptureMode " + mCaptureMode + " is insvalid"); } }

Target:
private byte getJpegQuality() { switch (mCaptureMode) { case CAPTURE_MODE_MAXIMIZE_QUALITY: return JPEG_QUALITY_MAXIMIZE_QUALITY_MODE; case CAPTURE_MODE_MINIMIZE_LATENCY: return JPEG_QUALITY_MINIMIZE_LATENCY_MODE; default: throw new IllegalStateException("CaptureMode " + mCaptureMode + " is invalid"); } }
Source:
public int read(byte[] bytesEntry, int off, int len) throws IOException { try { if (off > 0) { byte[] data = new byte[(len < 10240) ? len : 10240]; int size = recv(fd, data, (len < 10240) ? len : 10240, 0); if (size > 0) { System.arraycopy(data, 0, bytesEntry, off, size); } return size; } else { return recv(fd, bytesEntry, len, 0); } } catch (LastErrorException lee) { throw new IOException("native read() failed : " + formatError(lee)); } }

Target:
public int read(byte[] bytesEntry, int off, int len) throws IOException { if (!isConnected()) { return -1; } try { if (off > 0) { byte[] data = new byte[(len < 10240) ? len : 10240]; int size = recv(fd, data, data.length, 0); if (size <= 0) { return -1; } System.arraycopy(data, 0, bytesEntry, off, size); return size; } else { int size = recv(fd, bytesEntry, len, 0); if (size <= 0) { return -1; } return size; } } catch (LastErrorException lee) { throw new IOException("native read() failed : " + formatError(lee)); } }
Source:
public static Point getTopLeftCornerOfFBNetwork(List<?> selection) { Assert.isNotNull(selection); Point pt = new Point(0, 0); Object fb = null; for (Object sel : selection) { fb = (sel instanceof EditPart) ? ((EditPart) sel).getModel() : sel; if (fb instanceof FBImpl) { pt.x = (pt.x == 0) ? ((FBNetworkElement) fb).getX() : Math.min(pt.x, ((FBNetworkElement) fb).getX()); pt.y = (pt.y == 0) ? ((FBNetworkElement) fb).getY() : Math.min(pt.y, ((FBNetworkElement) fb).getY()); } } return pt; }

Target:
public static Point getTopLeftCornerOfFBNetwork(List<?> selection) { Assert.isNotNull(selection); Point pt = new Point(0, 0); Object fb = null; for (Object sel : selection) { fb = (sel instanceof EditPart) ? ((EditPart) sel).getModel() : sel; if (fb instanceof FB) { pt.x = (pt.x == 0) ? ((FBNetworkElement) fb).getX() : Math.min(pt.x, ((FBNetworkElement) fb).getX()); pt.y = (pt.y == 0) ? ((FBNetworkElement) fb).getY() : Math.min(pt.y, ((FBNetworkElement) fb).getY()); } } return pt; }
Source:
public List<PictureView> computeViewsFor(Blob blob, List<PictureConversion> pictureConversions, ImageInfo imageInfo, boolean convert) { String mimeType = blob.getMimeType(); if (mimeType == null) { blob.setMimeType(getImageMimeType(blob)); } if (imageInfo == null) { imageInfo = getImageInfo(blob); } List<PictureView> views = new ArrayList<>(); for (PictureConversion pictureConversion : pictureConversions) { try { views.add(computeView(blob, pictureConversion, imageInfo, convert)); } catch (NuxeoException e) { log.warn("Unable to compute view: {}: {}", pictureConversion::getId, e::getMessage); log.debug(e, e); } } return views; }

Target:
public List<PictureView> computeViewsFor(Blob blob, List<PictureConversion> pictureConversions, ImageInfo imageInfo, boolean convert) { String mimeType = blob.getMimeType(); if (mimeType == null) { blob.setMimeType(getImageMimeType(blob)); } if (imageInfo == null) { imageInfo = getImageInfo(blob); } List<PictureView> views = new ArrayList<>(); for (PictureConversion pictureConversion : pictureConversions) { try { views.add(computeView(blob, pictureConversion, imageInfo, convert)); } catch (NuxeoException e) { log.warn("Unable to compute view: exception message: {}", pictureConversion::getId, e::getMessage); log.debug(e, e); } } return views; }
Source:
public Response createPoly(byte[] inputToAutodetectType) { log.debug("Creating app from autodetecting input"); boolean looksLikeLegacy = false; Exception legacyFormatException = null; try { ApplicationSpec appSpec = mapper().readValue(inputToAutodetectType, ApplicationSpec.class); return createFromAppSpec(appSpec); } catch (Exception e) { legacyFormatException = e; log.debug("Input is not legacy ApplicationSpec JSON (will try others): "+e, e); } AssemblyTemplate template = null; boolean looksLikeYaml = false; try { template = camp().pdp().registerDeploymentPlan(new StringReader(new String(inputToAutodetectType))); if (!template.getPlatformComponentTemplates().isEmpty() || !template.getApplicationComponentTemplates().isEmpty()) { looksLikeYaml = true; } else { if (template.getCustomAttributes().containsKey("type")) { looksLikeLegacy = true; } } } catch (Exception e) { log.debug("Input is not valid YAML: "+e); } if (template!=null) { try { return launch(template); } catch (Exception e) { if (looksLikeYaml) throw Throwables.propagate(e); } } if (looksLikeLegacy && legacyFormatException!=null) throw Throwables.propagate(legacyFormatException); return Response.serverError().entity("Unsupported format; not able to autodetect.").build(); }

Target:
public Response createPoly(byte[] inputToAutodetectType) { log.debug("Creating app from autodetecting input"); boolean looksLikeLegacy = false; Exception legacyFormatException = null; try { ApplicationSpec appSpec = mapper().readValue(inputToAutodetectType, ApplicationSpec.class); return createFromAppSpec(appSpec); } catch (Exception e) { Exceptions.propagateIfFatal(e); legacyFormatException = e; log.debug("Input is not legacy ApplicationSpec JSON (will try others): "+e, e); } AssemblyTemplate template = null; boolean looksLikeYaml = false; try { template = camp().pdp().registerDeploymentPlan(new StringReader(new String(inputToAutodetectType))); if (!template.getPlatformComponentTemplates().isEmpty() || !template.getApplicationComponentTemplates().isEmpty()) { looksLikeYaml = true; } else { if (template.getCustomAttributes().containsKey("type")) { looksLikeLegacy = true; } } } catch (Exception e) { Exceptions.propagateIfFatal(e); log.debug("Input is not valid YAML: "+e); } if (template!=null) { try { return launch(template); } catch (Exception e) { Exceptions.propagateIfFatal(e); if (looksLikeYaml) throw Exceptions.propagate(e); } } if (looksLikeLegacy && legacyFormatException!=null) throw Throwables.propagate(legacyFormatException); return Response.serverError().entity("Unsupported format; not able to autodetect.").build(); }
Source:
public boolean equalsSignature(Object obj) { if (obj instanceof FunctionDesc) { return this.getSignature().equalsWithoutType(obj); } return false; }

Target:
public boolean equalsSignature(Object obj) { if (obj instanceof FunctionDesc) { return this.getSignature().equalsWithoutType(((FunctionDesc) obj).getSignature()); } return false; }
Source:
public boolean isClosed() { return ehCacheManager.getStatus() != Status.AVAILABLE; }

Target:
public boolean isClosed() { return ehCacheManager.getStatus() == Status.UNINITIALIZED; }
Source:
public ListenableFuture<?> processFor(Duration duration) { checkLockNotHeld("Can not process for a duration while holding the driver lock"); requireNonNull(duration, "duration is null"); long maxRuntime = duration.roundTo(TimeUnit.NANOSECONDS); Optional<ListenableFuture<?>> result = tryWithLock(100, TimeUnit.MILLISECONDS, () -> { driverContext.getYieldSignal().yieldAfter(maxRuntime, driverContext.getExecutor()); driverContext.startProcessTimer(); try { long start = System.nanoTime(); do { ListenableFuture<?> future = processInternal(); if (!future.isDone()) { return future; } } while (System.nanoTime() - start < maxRuntime && !isFinishedInternal()); } finally { driverContext.getYieldSignal().reset(); driverContext.recordProcessed(); } return NOT_BLOCKED; }); return result.orElse(NOT_BLOCKED); }

Target:
public ListenableFuture<?> processFor(Duration duration) { checkLockNotHeld("Can not process for a duration while holding the driver lock"); requireNonNull(duration, "duration is null"); long maxRuntime = duration.roundTo(TimeUnit.NANOSECONDS); Optional<ListenableFuture<?>> result = tryWithLock(100, TimeUnit.MILLISECONDS, () -> { driverContext.startProcessTimer(); driverContext.getYieldSignal().setWithDelay(maxRuntime, driverContext.getYieldExecutor()); try { long start = System.nanoTime(); do { ListenableFuture<?> future = processInternal(); if (!future.isDone()) { return wakeUpOnRevokeRequest(future); } } while (System.nanoTime() - start < maxRuntime && !isFinishedInternal()); } finally { driverContext.getYieldSignal().reset(); driverContext.recordProcessed(); } return NOT_BLOCKED; }); return result.orElse(NOT_BLOCKED); }
Source:
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeMessage("msg", msg)) return false; writer.incrementState(); case 1: if (!writer.writeBoolean("ordered", ordered)) return false; writer.incrementState(); case 2: if (!writer.writeByte("plc", plc)) return false; writer.incrementState(); case 3: if (!writer.writeUuid("secSubjId", secSubjId)) return false; writer.incrementState(); case 4: if (!writer.writeBoolean("skipOnTimeout", skipOnTimeout)) return false; writer.incrementState(); case 5: if (!writer.writeLong("timeout", timeout)) return false; writer.incrementState(); case 6: if (!writer.writeByteArray("topicBytes", topicBytes)) return false; writer.incrementState(); case 7: if (!writer.writeInt("topicOrd", topicOrd)) return false; writer.incrementState(); } return true; }

Target:
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeMessage("msg", msg)) return false; writer.incrementState(); case 1: if (!writer.writeBoolean("ordered", ordered)) return false; writer.incrementState(); case 2: if (!writer.writeByte("plc", plc)) return false; writer.incrementState(); case 3: if (!writer.writeBoolean("skipOnTimeout", skipOnTimeout)) return false; writer.incrementState(); case 4: if (!writer.writeLong("timeout", timeout)) return false; writer.incrementState(); case 5: if (!writer.writeByteArray("topicBytes", topicBytes)) return false; writer.incrementState(); case 6: if (!writer.writeInt("topicOrd", topicOrd)) return false; writer.incrementState(); } return true; }
Source:
public SqlUserDefinedAggFunction(SqlIdentifier opName, SqlReturnTypeInference returnTypeInference, SqlOperandTypeInference operandTypeInference, SqlOperandTypeChecker operandTypeChecker, AggregateFunction function, boolean requiresOrder, boolean requiresOver, RelDataTypeFactory typeFactory) { super(Util.last(opName.names), opName, SqlKind.getSqlKindByName(opName.names.get(0)) != null ? SqlKind.valueOf(opName.names.get(0)) : SqlKind.OTHER_FUNCTION, returnTypeInference, operandTypeInference, operandTypeChecker, SqlFunctionCategory.USER_DEFINED_FUNCTION, requiresOrder, requiresOver); this.function = function; this.typeFactory = typeFactory; }

Target:
public SqlUserDefinedAggFunction(SqlIdentifier opName, SqlReturnTypeInference returnTypeInference, SqlOperandTypeInference operandTypeInference, SqlOperandTypeChecker operandTypeChecker, AggregateFunction function, boolean requiresOrder, boolean requiresOver, RelDataTypeFactory typeFactory) { super(Util.last(opName.names), opName, SqlKind.OTHER_FUNCTION, returnTypeInference, operandTypeInference, operandTypeChecker, SqlFunctionCategory.USER_DEFINED_FUNCTION, requiresOrder, requiresOver); this.function = function; this.typeFactory = typeFactory; }
Source:
private boolean hasOpenableDRepresentations() { boolean hasOpenableDRepresentations = false; Collection<DRepresentation> representations = DialectManager.INSTANCE.getRepresentations(semanticElement, session); for (DRepresentation representation : representations) { if (session.getSelectedViews().contains(representation.eContainer())) { hasOpenableDRepresentations = true; break; } } return hasOpenableDRepresentations; }

Target:
private boolean hasOpenableDRepresentations() { boolean hasOpenableDRepresentations = false; Collection<DRepresentation> representations = DialectManager.INSTANCE.getRepresentations(semanticElement, session); Collection<DView> selectedViews = session.getSelectedViews(); for (DRepresentation representation : representations) { if (selectedViews.contains(representation.eContainer())) { hasOpenableDRepresentations = true; break; } } return hasOpenableDRepresentations; }
Source:
public void canReleaseLock() { LockEntry entry = lockStore.acquireBackupLock(TEST_REASON); PersistentLockId entryId = ImmutablePersistentLockId.of(entry.instanceId()); service.releaseLock(entryId); verify(lockStore, times(1)).releaseLock(entry); }

Target:
public void canReleaseLock() { PersistentLockId lockId = service.acquireBackupLock(TEST_REASON); LockEntry lockEntry = Iterables.getOnlyElement(lockStore.allLockEntries()); service.releaseLock(lockId); verify(lockStore, times(1)).releaseLock(eq(lockEntry)); }
Source:
public S3TO(final Long id, final String uuid, final String accessKey, final String secretKey, final String endPoint, final String bucketName, final String signer, final Boolean httpsFlag, final Integer connectionTimeout, final Integer maxErrorRetry, final Integer socketTimeout, final Date created, final boolean enableRRS, final long maxUploadSize, final Integer connectionTtl, final Boolean useTCPKeepAlive) { super(); this.id = id; this.uuid = uuid; this.accessKey = accessKey; this.secretKey = secretKey; this.endPoint = endPoint; this.bucketName = bucketName; this.signer = signer; this.httpsFlag = httpsFlag; this.connectionTimeout = connectionTimeout; this.maxErrorRetry = maxErrorRetry; this.socketTimeout = socketTimeout; this.created = created; this.enableRRS = enableRRS; this.maxSingleUploadSizeInBytes = maxUploadSize; this.connectionTtl = connectionTtl; this.useTCPKeepAlive = useTCPKeepAlive; }

Target:
public S3TO(final Long id, final String uuid, final String accessKey, final String secretKey, final String endPoint, final String bucketName, final String signer, final Boolean httpsFlag, final Integer connectionTimeout, final Integer maxErrorRetry, final Integer socketTimeout, final Date created, final boolean enableRRS, final long maxUploadSize, final Integer connectionTtl, final Boolean useTCPKeepAlive) { this.id = id; this.uuid = uuid; this.accessKey = accessKey; this.secretKey = secretKey; this.endPoint = endPoint; this.bucketName = bucketName; this.signer = signer; this.httpsFlag = httpsFlag; this.connectionTimeout = connectionTimeout; this.maxErrorRetry = maxErrorRetry; this.socketTimeout = socketTimeout; this.created = created; this.enableRRS = enableRRS; this.maxSingleUploadSizeInBytes = maxUploadSize; this.connectionTtl = connectionTtl; this.useTCPKeepAlive = useTCPKeepAlive; }
Source:
public void flushCounters() { ConcurrentMap<CounterMetric, Integer> counters = ConcurrentMetricCounters.Counters.get(); ConcurrentMetricCounters.Counters.set(new ConcurrentHashMap<CounterMetric, Integer>()); for (CounterMetric counterMetric: counters.keySet()) { int count = counters.get(counterMetric); this.postMetric(counterMetric.getMetricName(), count, counterMetric.getHostname(), counterMetric.getTags(), "rate"); } }

Target:
public void flushCounters() { ConcurrentMap<CounterMetric, Integer> counters = ConcurrentMetricCounters.getInstance().getAndReset(); logger.fine("Run flushCounters method"); for (CounterMetric counterMetric: counters.keySet()) { int count = counters.get(counterMetric); logger.fine("Flushing: " + counterMetric.getMetricName() + " - " + count); this.postMetric(counterMetric.getMetricName(), count / 10, counterMetric.getHostname(), counterMetric.getTags(), "rate"); } }
Source:
private void checkSubtree(Object element, boolean state) { TreeItem item = (TreeItem) fCheckboxTreeViewer.testFindItem(element); if (!state || (item != null)) { fObjects.put(element, state); for (Object o : ((ITreeContentProvider) fCheckboxTreeViewer.getContentProvider()).getChildren(element)) { checkSubtree(o, state); } } }

Target:
private void checkSubtree(Object element, boolean state) { if (!state || (fCheckboxTreeViewer.testFindItem(element) != null)) { if (state) { fObjects.add(element); } else { fObjects.remove(element); } for (Object o : ((ITreeContentProvider) fCheckboxTreeViewer.getContentProvider()).getChildren(element)) { checkSubtree(o, state); } } }
Source:
public Plan getLogicalPlan(Session session, Statement statement, List<Expression> parameters, PlanNodeIdAllocator idAllocator, WarningCollector warningCollector) { Analysis analysis = analyze(session, statement, parameters, warningCollector); LogicalPlanner logicalPlanner = new LogicalPlanner(session, planOptimizers, idAllocator, metadata, sqlParser, statsCalculator, costCalculator, warningCollector); return logicalPlanner.plan(analysis); }

Target:
public Plan getLogicalPlan(Session session, Statement statement, List<Expression> parameters, PlanNodeIdAllocator idAllocator, WarningCollector warningCollector) { Analysis analysis = analyze(session, statement, parameters, warningCollector); LogicalPlanner logicalPlanner = new LogicalPlanner(true, session, planOptimizers, idAllocator, metadata, sqlParser, statsCalculator, costCalculator, warningCollector); return logicalPlanner.plan(analysis); }
Source:
public static long dateValueFromDate(long ms) { ms += getTimeZone().getOffset(ms); long absoluteDay = ms / 86_400_000; if (ms < 0 && (absoluteDay * 86_400_000 != ms)) { absoluteDay--; } return dateValueFromAbsoluteDay(absoluteDay); }

Target:
public static long dateValueFromDate(long ms) { ms += getTimeZone().getOffset(ms); long absoluteDay = ms / MILLIS_PER_DAY; if (ms < 0 && (absoluteDay * MILLIS_PER_DAY != ms)) { absoluteDay--; } return dateValueFromAbsoluteDay(absoluteDay); }
Source:
public <TM> MessageStream<TM> map(MapFunction<? super M, ? extends TM> mapFn) { String opId = this.graph.getNextOpId(OpCode.MAP, null); OperatorSpec<M, TM> op = OperatorSpecs.createMapOperatorSpec(mapFn, opId); this.operatorSpec.registerNextOperatorSpec(op); return new MessageStreamImpl<>(this.graph, op); }

Target:
public <TM> MessageStream<TM> map(MapFunction<? super M, ? extends TM> mapFn) { String opId = this.graph.getNextOpId(OpCode.MAP); OperatorSpec<M, TM> op = OperatorSpecs.createMapOperatorSpec(mapFn, opId); this.operatorSpec.registerNextOperatorSpec(op); return new MessageStreamImpl<>(this.graph, op); }
Source:
public OrcZstdDecompressor(OrcDataSourceId orcDataSourceId, int maxBufferSize, boolean zstdJniDecompressionEnabled) { this.orcDataSourceId = requireNonNull(orcDataSourceId, "orcDataSourceId is null"); this.maxBufferSize = maxBufferSize; if (zstdJniDecompressionEnabled) { this.decompressor = (input, inputOffset, inputLength, output, outputOffset, maxOutputLength) -> (int) Zstd.decompressByteArray(output, 0, maxOutputLength, input, inputOffset, inputLength); } else { ZstdDecompressor zstdDecompressor = new ZstdDecompressor(); this.decompressor = zstdDecompressor::decompress; } }

Target:
public OrcZstdDecompressor(OrcDataSourceId orcDataSourceId, int maxBufferSize, boolean zstdJniDecompressionEnabled) { this.orcDataSourceId = requireNonNull(orcDataSourceId, "orcDataSourceId is null"); this.maxBufferSize = maxBufferSize; if (zstdJniDecompressionEnabled) { this.decompressor = (input, inputOffset, inputLength, output, outputOffset, maxOutputLength) -> { long size = Zstd.decompressByteArray(output, 0, maxOutputLength, input, inputOffset, inputLength); if (Zstd.isError(size)) { String errorName = Zstd.getErrorName(size); throw new MalformedInputException(inputOffset, "Zstd JNI decompressor failed with " + errorName); } return toIntExact(size); }; } else { ZstdDecompressor zstdDecompressor = new ZstdDecompressor(); this.decompressor = zstdDecompressor::decompress; } }
Source:
public HttpResponse doConfirmRename(@QueryParameter String newName) throws IOException { if (!isNameEditable()) { throw new IllegalArgumentException("Trying to rename an item that has not editable name."); } newName = newName == null ? null : newName.trim(); FormValidation validationError = doCheckNewName(newName); if (validationError.kind != FormValidation.Kind.OK) { throw new Failure(validationError.getMessage()); } renameTo(newName); return HttpResponses.redirectTo("../" + newName); }

Target:
public HttpResponse doConfirmRename(@QueryParameter String newName) throws IOException { newName = newName == null ? null : newName.trim(); FormValidation validationError = doCheckNewName(newName); if (validationError.kind != FormValidation.Kind.OK) { throw new Failure(validationError.getMessage()); } renameTo(newName); return HttpResponses.redirectTo("../" + newName); }
Source:
public static void setUp() { System.setProperty("XD_HOME", "../.."); RandomConfigurationSupport randomConfigSupport = new RandomConfigurationSupport(); application = new SingleNodeApplication().run(); SingleNodeIntegrationTestSupport singleNodeIntegrationTestSupport = new SingleNodeIntegrationTestSupport( application); }

Target:
public static void setUp() { System.setProperty("XD_HOME", "../.."); new RandomConfigurationSupport(); application = new SingleNodeApplication().run(); }