auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static void printHelp() { LOG.info("Usage: GoraCompiler <schema file> <output dir> [-license <id>]\n" + " <schema file> - individual avsc file to be compiled or a directory path containing avsc files\n" + " <output dir> - output directory for generated Java files\n" + " [-license <id>] - the preferred license header to add to the generated Java file.\n" + "Current License header options include;\n" + "\t\t ASLv2 (Apache Software License v2.0) \n" + "\t\t AGPLv3 (GNU Affero General Public License) \n" + "\t\t CDDLv1 (Common Development and Distribution License v1.0) \n" + "\t\t FDLv13 (GNU Free Documentation License v1.3) \n" + "\t\t GPLv1 (GNU General Public License v1.0) \n" + "\t\t GPLv2 (GNU General Public License v2.0) \n" + "\t\t GPLv3 (GNU General Public License v3.0) \n" + "\t\t LGPLv21 (GNU Lesser General Public License v2.1) \n" + "\t\t LGPLv3 (GNU Lesser General Public License v2.1)" ); }

Target:
private static void printHelp() { LOG.info("Usage: GoraCompiler <schema file> <output dir> [-license <id>]" + System.lineSeparator() + " <schema file> - individual avsc file to be compiled or a directory path containing avsc files" + System.lineSeparator() + " <output dir> - output directory for generated Java files" + System.lineSeparator() + " [-license <id>] - the preferred license header to add to the generated Java file." + System.lineSeparator() + "Current License header options include;" + System.lineSeparator() + "\t\t ASLv2 (Apache Software License v2.0)" + System.lineSeparator() + "\t\t AGPLv3 (GNU Affero General Public License)" + System.lineSeparator() + "\t\t CDDLv1 (Common Development and Distribution License v1.0)" + System.lineSeparator() + "\t\t FDLv13 (GNU Free Documentation License v1.3)" + System.lineSeparator() + "\t\t GPLv1 (GNU General Public License v1.0)" + System.lineSeparator() + "\t\t GPLv2 (GNU General Public License v2.0)" + System.lineSeparator() + "\t\t GPLv3 (GNU General Public License v3.0)" + System.lineSeparator() + "\t\t LGPLv21 (GNU Lesser General Public License v2.1)" + System.lineSeparator() + "\t\t LGPLv3 (GNU Lesser General Public License v2.1)" ); }
Source:
public MessageClass getMessageClass() { return this.entityStateClass; }

Target:
public EntityStateClass getMessageClass() { return this.entityStateClass; }
Source:
DOMINANCE_AMONG_RELATED_VALUES dominanceAmongRelatedValues(double[] allValuesSortedInIncreasingOrder, double value){ if(allValuesSortedInIncreasingOrder.length == 0 || value == 0) return DOMINANCE_AMONG_RELATED_VALUES.absent; if(allValuesSortedInIncreasingOrder.length == 1) return DOMINANCE_AMONG_RELATED_VALUES.dominant; double topValue = allValuesSortedInIncreasingOrder[allValuesSortedInIncreasingOrder.length - 1]; double valueFollowingTopValue = allValuesSortedInIncreasingOrder[allValuesSortedInIncreasingOrder.length - 2]; if(value == topValue && value > valueFollowingTopValue * 2 ) return DOMINANCE_AMONG_RELATED_VALUES.dominant; return DOMINANCE_AMONG_RELATED_VALUES.present; }

Target:
DOMINANCE_AMONG_RELATED_VALUES dominanceAmongRelatedValues(double[] allValuesSortedInIncreasingOrder, double value){ if(allValuesSortedInIncreasingOrder.length == 0 || value == 0) return DOMINANCE_AMONG_RELATED_VALUES.absent; if(allValuesSortedInIncreasingOrder.length == 1) return DOMINANCE_AMONG_RELATED_VALUES.dominant; double topValue = allValuesSortedInIncreasingOrder[allValuesSortedInIncreasingOrder.length - 1]; double valueFollowingTopValue = allValuesSortedInIncreasingOrder[allValuesSortedInIncreasingOrder.length - 2]; if(value == topValue && value >= valueFollowingTopValue * 2 ) return DOMINANCE_AMONG_RELATED_VALUES.dominant; return DOMINANCE_AMONG_RELATED_VALUES.present; }
Source:
private ICommand buildResizeCommand(ChangeBoundsRequest request) { ICommand result; Command cmd = super.getResizeCommand(request); if (cmd == null) { result = null; } else { result = new CommandProxy(cmd.chain(new ChildrenAdjustmentCommand((GraphicalEditPart) getHost(), request))); } return result; }

Target:
private ICommand buildResizeCommand(ChangeBoundsRequest request) { ICommand result; Command cmd = super.getResizeCommand(request); if (cmd == null) { result = null; } else { CompositeTransactionalCommand ctc = new CompositeTransactionalCommand(TransactionUtil.getEditingDomain(getHost().getModel()), cmd.getLabel()); ctc.add(new CommandProxy(cmd)); ctc.add(new ChildrenAdjustmentCommand((GraphicalEditPart) getHost(), request)); result = ctc; } return result; }
Source:
private OutputStream uploadAndTrigger(JobPreset preset, String filename) { try { BlobStorageSpace temporaryStorageSpace = blobStorage.getSpace(TmpRoot.TMP_SPACE); Blob buffer = temporaryStorageSpace.createTemporaryBlob(UserContext.getCurrentUser().getTenantId()); return buffer.createOutputStream(() -> { if (buffer.getSize() > 0) { temporaryStorageSpace.markAsUsed(buffer); trigger(preset, buffer, filename); } }, filename); } catch (Exception e) { throw Exceptions.handle(e); } }

Target:
private OutputStream uploadAndTrigger(JobPreset preset, String filename) { try { BlobStorageSpace temporaryStorageSpace = blobStorage.getSpace(TmpRoot.TMP_SPACE); Blob buffer = temporaryStorageSpace.createTemporaryBlob(UserContext.getCurrentUser().getTenantId()); return buffer.createOutputStream(() -> { if (buffer.getSize() > 0) { temporaryStorageSpace.markAsUsed(buffer); trigger(preset, buffer, filename); } else { buffer.delete(); } }, filename); } catch (Exception e) { throw Exceptions.handle(e); } }
Source:
private static ContentRetrieverResponse readPageContent(HttpEntity httpEntity, int maxPageContentLength, String url) throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), StandardCharsets.UTF_8))) { StringBuilder pageContent = new StringBuilder(); String inputLine; while ((inputLine = reader.readLine()) != null) { if (pageContent.length() < maxPageContentLength) { if (pageContent.length() > 0) { pageContent.append('\n'); } pageContent.append(inputLine); } else { log.warn(String.format( "page content from URL: '%s' exceeded page length limit: %d, returning truncated page content", url, maxPageContentLength)); return new ContentRetrieverResponse(pageContent.toString()); } } return new ContentRetrieverResponse(pageContent.toString()); } }

Target:
private static ContentRetrieverResponse readPageContent(HttpEntity httpEntity, int maxPageContentLength, String url) throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), StandardCharsets.UTF_8))) { StringBuilder pageContent = new StringBuilder(); String inputLine; while ((inputLine = reader.readLine()) != null) { if (pageContent.length() < maxPageContentLength) { if (pageContent.length() > 0) { pageContent.append('\n'); } pageContent.append(inputLine); } else { log.warn("page content from URL: '{}' exceeded page length limit: {}, returning truncated page content", url, maxPageContentLength); return new ContentRetrieverResponse(pageContent.toString()); } } return new ContentRetrieverResponse(pageContent.toString()); } }
Source:
public Response updateInsertion(@PathParam("programUuid") long programUuid, JaxNewInsertion insertion) { ArtifactReadable insertionArt = atsServer.getQuery().andUuid(insertion.getUuid()).getResults().getExactlyOne(); if (!insertionArt.getArtifactType().equals(AtsArtifactTypes.Insertion)) { throw new OseeCoreException("Given insertion uuid not insertion type"); } Response response = null; if (!insertionArt.getName().equals(insertion.getName())) { IAtsConfigObject updated = atsServer.getConfigItemFactory().updateInsertion(insertion); response = getResponse(updated); } else { response = Response.notModified().build(); } return response; }

Target:
public Response updateInsertion(@PathParam("programUuid") long programUuid, JaxNewInsertion insertion) { ArtifactReadable insertionArt = atsServer.getArtifactByUuid(insertion.getUuid()); if (insertionArt == null) { throw new OseeCoreException("Given insertion uuid not found"); } if (!insertionArt.getArtifactType().equals(AtsArtifactTypes.Insertion)) { throw new OseeCoreException("Given insertion uuid not insertion type"); } Response response = null; if (!insertionArt.getName().equals(insertion.getName())) { IAtsConfigObject updated = atsServer.getConfigItemFactory().updateInsertion(insertion); response = Response.ok().entity(updated).build(); } else { response = Response.notModified().build(); } return response; }
Source:
public void onSendPack(UploadPack up, Collection<? extends ObjectId> wants, Collection<? extends ObjectId> haves) throws UploadPackMayNotContinueException { for (PreUploadHook hook : hooks) { hook.onSendPack(up, wants, haves); } }

Target:
public void onSendPack(UploadPack up, Collection<? extends ObjectId> wants, Collection<? extends ObjectId> haves) throws UploadPackMayNotContinueException { for (int i = 0; i < count; i++) hooks[i].onSendPack(up, wants, haves); }
Source:
public synchronized String toString() { List<String> stanzas = Lists.newArrayListWithCapacity(3); if (notBlank(appName) && notBlank(appVersion)) { stanzas.add(String.format("%s/%s", appName, appVersion)); } else if (notBlank(appName)) { stanzas.add(appName); } else if (notBlank(appVersion)) { stanzas.add(appVersion); } if (notBlank(device) && notBlank(osName)) { stanzas.add(String.format("(%s; %s/%s)", device, osName, osVersion)); } else if (notBlank(device)) { stanzas.add(String.format("(%s)", device)); } else if (notBlank(osName)){ stanzas.add(String.format("(%s/%s)", osName, osVersion)); } if (notBlank(sdkVersion)) { stanzas.add(String.format("BridgeJavaSDK/%s", sdkVersion)); } else { stanzas.add("BridgeJavaSDK"); } return Joiner.on(" ").join(stanzas); }

Target:
public synchronized String toString() { List<String> stanzas = Lists.newArrayListWithCapacity(3); if (isNotBlank(appName) && isNotBlank(appVersion)) { stanzas.add(String.format("%s/%s", appName, appVersion)); } else if (isNotBlank(appName)) { stanzas.add(appName); } else if (isNotBlank(appVersion)) { stanzas.add(appVersion); } if (isNotBlank(device) && isNotBlank(osName)) { stanzas.add(String.format("(%s; %s/%s)", device, osName, osVersion)); } else if (isNotBlank(device)) { stanzas.add(String.format("(%s)", device)); } else if (isNotBlank(osName)){ stanzas.add(String.format("(%s/%s)", osName, osVersion)); } if (isNotBlank(sdkVersion)) { stanzas.add(String.format("BridgeJavaSDK/%s", sdkVersion)); } else { stanzas.add("BridgeJavaSDK"); } return Joiner.on(" ").join(stanzas); }
Source:
public final Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { ParseTree tree; if(!CACHED_SCRIPTS.containsKey(this.getClass())) { try { String script = script(); tree = MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true), environment) .getChildAt(0); } catch (ConfigCompileException | ConfigCompileGroupException ex) { throw new Error(ex); } if(cacheCompile()) { CACHED_SCRIPTS.put(this.getClass(), tree); } } else { tree = CACHED_SCRIPTS.get(this.getClass()); } setTarget(tree, t); GlobalEnv env = environment.getEnv(GlobalEnv.class); IVariableList oldVariables = env.GetVarList(); IVariableList newVariables = new IVariableList(); newVariables.set(new IVariable(CArray.TYPE, "@arguments", new CArray(t, args.length, args), t)); env.SetVarList(newVariables); Mixed ret = CVoid.VOID; try { if(env.GetScript() != null) { env.GetScript().eval(tree, environment); } else { Script.GenerateScript(null, null).eval(tree, environment); } } catch (FunctionReturnException ex) { ret = ex.getReturn(); } env.SetVarList(oldVariables); return ret; }

Target:
public final Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { ParseTree tree; if(!CACHED_SCRIPTS.containsKey(this.getClass())) { try { String script = script(); tree = MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true), environment) .getChildAt(0); } catch (ConfigCompileException | ConfigCompileGroupException ex) { throw new Error(ex); } if(cacheCompile()) { CACHED_SCRIPTS.put(this.getClass(), tree); } } else { tree = CACHED_SCRIPTS.get(this.getClass()); } GlobalEnv env = environment.getEnv(GlobalEnv.class); IVariableList oldVariables = env.GetVarList(); IVariableList newVariables = new IVariableList(); newVariables.set(new IVariable(CArray.TYPE, "@arguments", new CArray(t, args.length, args), t)); env.SetVarList(newVariables); Mixed ret = CVoid.VOID; try { if(env.GetScript() != null) { env.GetScript().eval(tree, environment); } else { Script.GenerateScript(null, null).eval(tree, environment); } } catch (FunctionReturnException ex) { ret = ex.getReturn(); } catch (ConfigRuntimeException ex) { if(ex.getTarget().file() == null) { ex.setTarget(t); env.GetStackTraceManager().setCurrentTarget(t); } throw ex; } env.SetVarList(oldVariables); return ret; }
Source:
public static void assertExpectedModules(Configuration configuration, Class<? extends ModuleConfiguration>... moduleTypes) { stream(moduleTypes).forEach(moduleType -> { List<? extends ModuleConfiguration> matches = configuration.findModules(moduleType); if (matches.isEmpty()) { fail("No module of type '" + moduleType.getName() + "' was not found in the provided configuration"); } }); }

Target:
public static void assertExpectedModules(Configuration configuration, Class<? extends ModuleConfiguration>... moduleTypes) { stream(moduleTypes).forEach(moduleType -> { List<? extends ModuleConfiguration> matches = configuration.findModules(moduleType); if (matches.isEmpty()) { fail("No module of type '" + moduleType.getName() + "' was found in the provided configuration"); } }); }
Source:
private void updateLyrics() { if (updateLyricsAsyncTask != null) updateLyricsAsyncTask.cancel(false); final Song song = MusicPlayerRemote.getCurrentSong(); updateLyricsAsyncTask = new AsyncTask<Void, Void, String>() { @Override protected void onPreExecute() { super.onPreExecute(); lyricsInfo = null; playerAlbumCoverFragment.setSynchronizedLyrics(null); toolbar.getMenu().removeItem(R.id.action_show_lyrics); } @Override protected String doInBackground(Void... params) { return MusicUtil.getLyrics(song); } @Override protected void onPostExecute(String lyrics) { super.onPostExecute(lyrics); if (TextUtils.isEmpty(lyrics)) { lyricsInfo = null; if (toolbar != null) { toolbar.getMenu().removeItem(R.id.action_show_lyrics); } } else { lyricsInfo = new LyricsDialog.LyricInfo(song.title, lyrics); playerAlbumCoverFragment.setSynchronizedLyrics(AbsSynchronizedLyrics.parse(lyrics)); Activity activity = getActivity(); if (toolbar != null && activity != null) if (toolbar.getMenu().findItem(R.id.action_show_lyrics) == null) { int color = ToolbarContentTintHelper.toolbarContentColor(activity, Color.TRANSPARENT); Drawable drawable = Util.getTintedVectorDrawable(activity, R.drawable.ic_comment_text_outline_white_24dp, color); toolbar.getMenu() .add(Menu.NONE, R.id.action_show_lyrics, Menu.NONE, R.string.action_show_lyrics) .setIcon(drawable) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } } } @Override protected void onCancelled(String s) { onPostExecute(null); } }.execute(); }

Target:
private void updateLyrics() { if (updateLyricsAsyncTask != null) updateLyricsAsyncTask.cancel(false); final Song song = MusicPlayerRemote.getCurrentSong(); updateLyricsAsyncTask = new AsyncTask<Void, Void, Lyrics>() { @Override protected void onPreExecute() { super.onPreExecute(); lyrics = null; playerAlbumCoverFragment.setLyrics(null); toolbar.getMenu().removeItem(R.id.action_show_lyrics); } @Override protected Lyrics doInBackground(Void... params) { String data = MusicUtil.getLyrics(song); if (TextUtils.isEmpty(data)) { return null; } return Lyrics.parse(song, data); } @Override protected void onPostExecute(Lyrics l) { lyrics = l; playerAlbumCoverFragment.setLyrics(lyrics); if (lyrics == null) { if (toolbar != null) { toolbar.getMenu().removeItem(R.id.action_show_lyrics); } } else { Activity activity = getActivity(); if (toolbar != null && activity != null) if (toolbar.getMenu().findItem(R.id.action_show_lyrics) == null) { int color = ToolbarContentTintHelper.toolbarContentColor(activity, Color.TRANSPARENT); Drawable drawable = Util.getTintedVectorDrawable(activity, R.drawable.ic_comment_text_outline_white_24dp, color); toolbar.getMenu() .add(Menu.NONE, R.id.action_show_lyrics, Menu.NONE, R.string.action_show_lyrics) .setIcon(drawable) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } } } @Override protected void onCancelled(Lyrics s) { onPostExecute(null); } }.execute(); }
Source:
public void testMapSubscript() { assertQuery("SELECT map(array[1], array['aa'])[1]", "SELECT 'aa'"); assertQuery("SELECT map(array['a'], array['aa'])['a']", "SELECT 'aa'"); assertQuery("SELECT map(array[array[1,1]], array['a'])[array[1,1]]", "SELECT 'a'"); assertQuery("SELECT map(array[(1,2)], array['a'])[(1,2)]", "SELECT 'a'"); assertQuery("SELECT map(array['0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456', 'idv_fail'], array['aa', 'bb'])['request_fail']", "SELECT NULL"); assertQuery("SELECT map(array['0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456', 'idv_fail'], array['aa', 'bb'])['idv_fail']", "SELECT 'bb'"); }

Target:
public void testMapSubscript() { assertQuery("SELECT map(array[1], array['aa'])[1]", "SELECT 'aa'"); assertQuery("SELECT map(array['a'], array['aa'])['a']", "SELECT 'aa'"); assertQuery("SELECT map(array[array[1,1]], array['a'])[array[1,1]]", "SELECT 'a'"); assertQuery("SELECT map(array[(1,2)], array['a'])[(1,2)]", "SELECT 'a'"); }
Source:
public static void check() throws Exception { if (!CallManager.isHealthy()) { throw new Exception( "CallManager blocked to answer or hangup calls."); } if (sipChecker != null) { sipChecker.check(); } else { if (hasSipGw) { throw new Exception("GW not ready."); } if (JigasiBundleActivator.getAvailableGateways().isEmpty()) { throw new Exception("No gateways configured."); } } }

Target:
public static void check() throws Exception { if (!CallManager.isHealthy()) { throw new Exception("CallManager is not healthy."); } if (sipChecker != null) { sipChecker.check(); } else { if (hasSipGw) { throw new Exception("GW not ready."); } if (JigasiBundleActivator.getAvailableGateways().isEmpty()) { throw new Exception("No gateways configured."); } } }
Source:
public Node createNodeUnlessExists(Key key, NodeLabel label) { Map<String, Object> parameters = new HashMap<String, Object>(); StringBuilder query = new StringBuilder( "MERGE" ); appendNodePattern( key, parameters, query, label ); query.append( " RETURN n" ); ExecutionResult result = engine.execute( query.toString(), parameters ); ResourceIterator<Node> column = result.columnAs( "n" ); Node node = null; if ( column.hasNext() ) { node = column.next(); } column.close(); return node; }

Target:
public Node createNodeUnlessExists(Key key, NodeLabel label) { Map<String, Object> parameters = new HashMap<String, Object>( key.getColumnNames().length ); StringBuilder query = new StringBuilder( "MERGE" ); appendNodePattern( key, parameters, query, label ); query.append( " RETURN n" ); ExecutionResult result = engine.execute( query.toString(), parameters ); ResourceIterator<Node> column = result.columnAs( "n" ); Node node = null; if ( column.hasNext() ) { node = column.next(); } column.close(); return node; }
Source:
private static String[] getDependencies(ModelTestControllerVersion version) { switch (version) { case EAP_6_4_0: case EAP_6_4_7: return new String[] { formatEAP6SubsystemArtifact(version), }; case EAP_7_0_0: case EAP_7_1_0: case EAP_7_2_0_TEMP: return new String[] { formatEAP7SubsystemArtifact(version), formatArtifact("org.jboss.eap:wildfly-clustering-common:%s", version), formatArtifact("org.jboss.eap:wildfly-clustering-jgroups-spi:%s", version), formatArtifact("org.jboss.eap:wildfly-clustering-service:%s", version), formatArtifact("org.jboss.eap:wildfly-clustering-spi:%s", version), }; default: throw new IllegalArgumentException(); } }

Target:
private static String[] getDependencies(ModelTestControllerVersion version) { switch (version) { case EAP_6_4_0: case EAP_6_4_7: return new String[] { formatEAP6SubsystemArtifact(version), }; case EAP_7_0_0: case EAP_7_1_0: case EAP_7_2_0: return new String[] { formatEAP7SubsystemArtifact(version), formatArtifact("org.jboss.eap:wildfly-clustering-common:%s", version), formatArtifact("org.jboss.eap:wildfly-clustering-jgroups-spi:%s", version), formatArtifact("org.jboss.eap:wildfly-clustering-service:%s", version), formatArtifact("org.jboss.eap:wildfly-clustering-spi:%s", version), }; default: throw new IllegalArgumentException(); } }
Source:
public void testArrayShuffle() { List<Integer> expected = IntStream.rangeClosed(1, 500).boxed().collect(toList()); Set<List<Integer>> distinctResults = new HashSet<>(); distinctResults.add(expected); for (int i = 0; i < 3; i++) { MaterializedResult results = computeActual(format("SELECT shuffle(ARRAY %s) FROM orders LIMIT 10", expected)); List<MaterializedRow> rows = results.getMaterializedRows(); assertTrue(rows.size() == 10); for (MaterializedRow row : rows) { List<Integer> actual = (List<Integer>) row.getField(0); assertEqualsIgnoreOrder(actual, expected); distinctResults.add(actual); } } assertTrue(distinctResults.size() >= 24, "shuffle must produce at least 24 DISTINCT results"); }

Target:
public void testArrayShuffle() { List<Integer> expected = IntStream.rangeClosed(1, 500).boxed().collect(toList()); Set<List<Integer>> distinctResults = new HashSet<>(); distinctResults.add(expected); for (int i = 0; i < 3; i++) { MaterializedResult results = computeActual(format("SELECT shuffle(ARRAY %s) FROM orders LIMIT 10", expected)); List<MaterializedRow> rows = results.getMaterializedRows(); assertTrue(rows.size() == 10); for (MaterializedRow row : rows) { List<Integer> actual = (List<Integer>) row.getField(0); assertEqualsIgnoreOrder(actual, expected); distinctResults.add(actual); } } assertTrue(distinctResults.size() >= 24, "shuffle must produce at least 24 distinct results"); }
Source:
public static Map<String, String> parseAndGetProperties(String property, String propertyValue, String delimiter, String fieldDelimiter, Function<String, String> keyFunction) { Map<String, String> result = new HashMap<>(); List<String> fieldGroups = Arrays.asList(propertyValue.split(delimiter)); for (String group : fieldGroups) { String[] split = group.split(fieldDelimiter); if (split.length != 2) { throw new IllegalArgumentException( String.format("For Property %s Parameter {}, name or value is empty, please check config", property, group)); } if (Strings.isNullOrEmpty(split[0])) { throw new IllegalArgumentException( String.format("Empty key/value is not allowed in %s", property)); } if (Strings.isNullOrEmpty(split[1])) { throw new IllegalArgumentException( String.format("Empty key/value is not allowed in %s", property)); } result.put(keyFunction.apply(split[0]), split[1]); } return result; }

Target:
public static Map<String, String> parseAndGetProperties(String property, String propertyValue, String delimiter, String fieldDelimiter, Function<String, String> keyFunction) { Map<String, String> result = new HashMap<>(); List<String> fieldGroups = Arrays.asList(propertyValue.split(delimiter)); for (String group : fieldGroups) { String[] split = group.split(fieldDelimiter); if (split.length != 2) { throw new IllegalArgumentException( String.format("For Property %s Parameter %s, name or value is empty, please check config", property, group)); } if (Strings.isNullOrEmpty(split[0])) { throw new IllegalArgumentException( String.format("Empty key/value is not allowed in property %s, group %s", property, group)); } if (Strings.isNullOrEmpty(split[1])) { throw new IllegalArgumentException( String.format("Empty key/value is not allowed in property %s, group %s", property, group)); } result.put(keyFunction.apply(split[0]), split[1]); } return result; }
Source:
public void reset() { encodedValues = new IntList(); for (RunLengthBitPackingHybridEncoder encoder : encoders) { encoder.close(); } encoders.clear(); }

Target:
public void reset() { close(); encodedValues = new IntList(); }
Source:
public static int get(final String key) { if(!map.containsKey(key)) android.util.Log.e(GadgetStringMap.class.getSimpleName(), key); return map.containsKey(key)? map.get(key) : R.string.na; }

Target:
public static int get(final String key) { return map.containsKey(key)? map.get(key) : R.string.na; }
Source:
public void testDropColumn() { featuresToTest(TestedFeature.DROP_COLUMN); assertUpdate("CREATE TABLE test_drop_column AS SELECT 123 x, 111 a", 1); assertUpdate("ALTER TABLE test_drop_column DROP COLUMN x"); assertQueryFails("SELECT x FROM test_drop_column", ".* Column 'x' cannot be resolved"); assertQueryFails("ALTER TABLE test_drop_column DROP COLUMN a", ".* Cannot drop the only column in a table"); }

Target:
public void testDropColumn() { requiredFeatures(TestedFeature.DROP_COLUMN); assertUpdate("CREATE TABLE test_drop_column AS SELECT 123 x, 111 a", 1); assertUpdate("ALTER TABLE test_drop_column DROP COLUMN x"); assertQueryFails("SELECT x FROM test_drop_column", ".* Column 'x' cannot be resolved"); assertQueryFails("ALTER TABLE test_drop_column DROP COLUMN a", ".* Cannot drop the only column in a table"); }
Source:
public void setData(@Nullable ISegmentStoreProvider provider) { fSegmentProvider = provider; if (provider == null) { updateModel(null); return; } createProviderColumns(); ISegmentStore<ISegment> segStore = provider.getSegmentStore(); Map<@NonNull Integer, @NonNull Predicate<@NonNull Map<@NonNull String, @NonNull String>>> predicates = computeRegexPredicate(); Predicate<ISegment> predicate = (segment) -> { if (!predicates.isEmpty()) { Map<@NonNull String, @NonNull String> input = getFilterInput(segment, provider); boolean r = false; for (Map.Entry<Integer, Predicate<Map<String, String>>> mapEntry : predicates.entrySet()) { Integer property = Objects.requireNonNull(mapEntry.getKey()); Predicate<Map<String, String>> value = Objects.requireNonNull(mapEntry.getValue()); if (property == IFilterProperty.DIMMED) { boolean status = value.test(input); r |= status; } } return r; } return true; }; if (segStore != null) { Collection<ISegment> filtered = Collections2.filter(segStore, seg -> predicate.test(seg)); ISegmentStore<ISegment> segStore2 = new ArrayListStore<>(filtered.toArray(new ISegment[filtered.size()])); updateModel(segStore2); return; } updateModel(null); SegmentStoreProviderProgressListener listener = fListener; if (listener != null) { provider.addListener(listener); } if (provider instanceof IAnalysisModule) { ((IAnalysisModule) provider).schedule(); } }

Target:
public void setData(@Nullable ISegmentStoreProvider provider) { fSegmentProvider = provider; if (provider == null) { updateModel(null); return; } createProviderColumns(); ISegmentStore<ISegment> segStore = provider.getSegmentStore(); Map<@NonNull Integer, @NonNull Predicate<@NonNull Map<@NonNull String, @NonNull String>>> predicates = computeRegexPredicate(); Predicate<ISegment> predicate = (segment) -> { if (!predicates.isEmpty()) { Map<@NonNull String, @NonNull String> input = getFilterInput(segment, provider); boolean activateProperty = false; for (Map.Entry<Integer, Predicate<Map<String, String>>> mapEntry : predicates.entrySet()) { Integer property = Objects.requireNonNull(mapEntry.getKey()); Predicate<Map<String, String>> value = Objects.requireNonNull(mapEntry.getValue()); if (property == IFilterProperty.DIMMED) { boolean status = value.test(input); activateProperty |= status; } } return activateProperty; } return true; }; if (segStore != null) { if (!predicates.isEmpty()) { updateModel(segStore); } else { Collection<ISegment> filtered = Collections2.filter(segStore, seg -> predicate.test(seg)); ISegmentStore<ISegment> filteredStore = new ArrayListStore<>(filtered.toArray(new ISegment[filtered.size()])); updateModel(filteredStore); return; } } updateModel(null); SegmentStoreProviderProgressListener listener = fListener; if (listener != null) { provider.addListener(listener); } if (provider instanceof IAnalysisModule) { ((IAnalysisModule) provider).schedule(); } }
Source:
static TerminationPolicy alwaysTerminate() { return new AlwaysTerminate(); }

Target:
static TerminationPolicy alwaysTerminate() { return (attempts, nextAttemptAt) -> true; }
Source:
public IBeaconAdvertiserOptions(Map<String, Object> properties) { requireNonNull(properties, "Required not null"); this.enable = getProperty(properties, PROPERTY_ENABLE, PROPERTY_ENABLE_DEFAULT); this.minInterval = (int) (getProperty(properties, PROPERTY_MIN_INTERVAL, PROPERTY_MIN_INTERVAL_DEFAULT) / 0.625); this.maxInterval = (int) (getProperty(properties, PROPERTY_MAX_INTERVAL, PROPERTY_MAX_INTERVAL_DEFAULT) / 0.625); this.major = checkRange(getProperty(properties, PROPERTY_MAJOR, PROPERTY_MAJOR_DEFAULT), PROPERTY_MAJOR_MAX, PROPERTY_MAJOR_MIN); this.minor = checkRange(getProperty(properties, PROPERTY_MINOR, PROPERTY_MINOR_DEFAULT), PROPERTY_MINOR_MAX, PROPERTY_MINOR_MIN); this.txPower = checkRange(getProperty(properties, PROPERTY_TX_POWER, PROPERTY_TX_POWER_DEFAULT), PROPERTY_TX_POWER_MAX, PROPERTY_TX_POWER_MIN); this.iname = getProperty(properties, PROPERTY_INAME, PROPERTY_INAME_DEFAULT); String uuidString = getProperty(properties, PROPERTY_UUID, PROPERTY_UUID_DEFAULT); if (uuidString.trim().replace("-", "").length() != 32) { logger.warn("UUID is too short or too long!"); this.uuid = UUID.fromString(PROPERTY_UUID_DEFAULT); } else { this.uuid = UUID.fromString(uuidString); } }

Target:
public IBeaconAdvertiserOptions(Map<String, Object> properties) { requireNonNull(properties, "Required not null"); this.enable = getProperty(properties, PROPERTY_ENABLE, PROPERTY_ENABLE_DEFAULT); this.minInterval = (int) (getProperty(properties, PROPERTY_MIN_INTERVAL, PROPERTY_MIN_INTERVAL_DEFAULT) / 0.625); this.maxInterval = (int) (getProperty(properties, PROPERTY_MAX_INTERVAL, PROPERTY_MAX_INTERVAL_DEFAULT) / 0.625); this.major = setInRange(getProperty(properties, PROPERTY_MAJOR, PROPERTY_MAJOR_DEFAULT), PROPERTY_MAJOR_MAX, PROPERTY_MAJOR_MIN); this.minor = setInRange(getProperty(properties, PROPERTY_MINOR, PROPERTY_MINOR_DEFAULT), PROPERTY_MINOR_MAX, PROPERTY_MINOR_MIN); this.txPower = setInRange(getProperty(properties, PROPERTY_TX_POWER, PROPERTY_TX_POWER_DEFAULT), PROPERTY_TX_POWER_MAX, PROPERTY_TX_POWER_MIN); this.iname = getProperty(properties, PROPERTY_INAME, PROPERTY_INAME_DEFAULT); String uuidString = getProperty(properties, PROPERTY_UUID, PROPERTY_UUID_DEFAULT); if (uuidString.trim().replace("-", "").length() != 32) { logger.warn("UUID is too short or too long!"); this.uuid = UUID.fromString(PROPERTY_UUID_DEFAULT); } else { this.uuid = UUID.fromString(setInHex(uuidString, PROPERTY_UUID_DEFAULT)); } }
Source:
protected void addPages() { try { if (getCommit().isStash()) { commitPage = new StashEditorPage(this); } else { commitPage = new CommitEditorPage(this); } addPage(commitPage); if (getCommit().getRevCommit().getParentCount() <= 1) { diffPage = new DiffEditorPage(this); addPage(diffPage); } if (getCommit().getNotes().length > 0) { notePage = new NotesEditorPage(this); addPage(notePage); } } catch (PartInitException e) { Activator.error("Error adding page", e); } refListenerHandle = Repository.getGlobalListenerList() .addRefsChangedListener(this); }

Target:
protected void addPages() { try { if (getCommit().isStash()) { commitPage = new StashEditorPage(this); } else { commitPage = new CommitEditorPage(this); } addPage(commitPage); diffPage = new DiffEditorPage(this); addPage(diffPage); if (getCommit().getNotes().length > 0) { notePage = new NotesEditorPage(this); addPage(notePage); } } catch (PartInitException e) { Activator.error("Error adding page", e); } refListenerHandle = Repository.getGlobalListenerList() .addRefsChangedListener(this); }
Source:
public StreamConsumersInfo(Map<String,Object> map) { if (map!= null && map.size()>0) { consumerInfo = map; name = (String) map.get(NAME); idle = (long) map.get(IDLE); pending = (long) map.get(PENDING); } else throw new IllegalArgumentException(); }

Target:
public StreamConsumersInfo(Map<String,Object> map) { consumerInfo = map; name = (String) map.get(NAME); idle = (long) map.get(IDLE); pending = (long) map.get(PENDING); }
Source:
void executeTask(final KeyFilter<? super K> filter, BiConsumer<? super K, InternalCacheEntry<K, V>> action) throws InterruptedException; void executeTask(KeyValueFilter<? super K, ? super V> filter, BiConsumer<? super K, InternalCacheEntry<K, V>> action) throws InterruptedException; @Override Iterator<InternalCacheEntry<K, V>> iterator(); Iterator<InternalCacheEntry<K, V>> expiredIterator(); interface ComputeAction<K, V> { InternalCacheEntry<K, V> compute(K key, InternalCacheEntry<K, V> oldEntry, InternalEntryFactory factory); }

Target:
void executeTask(final KeyFilter<? super K> filter, BiConsumer<? super K, InternalCacheEntry<K, V>> action) throws InterruptedException; void executeTask(KeyValueFilter<? super K, ? super V> filter, BiConsumer<? super K, InternalCacheEntry<K, V>> action) throws InterruptedException; @Override Iterator<InternalCacheEntry<K, V>> iterator(); Iterator<InternalCacheEntry<K, V>> iteratorIncludingExpired(); interface ComputeAction<K, V> { InternalCacheEntry<K, V> compute(K key, InternalCacheEntry<K, V> oldEntry, InternalEntryFactory factory); }
Source:
public void prependLog(String contentId, String contentDisplayName, byte[] logBytes) throws VirusFoundException, OverQuotaException, ServerOverloadException, PermissionException, TypeException, InUseException { switchUser(); ContentResourceEdit cre = getContentResourceEdit(contentId, contentDisplayName); File tempFile = null; try { tempFile = File.createTempFile(uniqid(), ".tmp"); tempFile.deleteOnExit(); OutputStream out = new FileOutputStream(tempFile); out.write(logBytes); InputStream inputStream = cre.streamContent(); int read = 0; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } inputStream.close(); out.flush(); out.close(); cre.setContent(new FileInputStream(tempFile)); } catch (IOException e) { } finally { if (null != tempFile) { tempFile.delete(); } } contentHostingService.commitResource(cre, NotificationService.NOTI_NONE); }

Target:
public void prependLog(String contentId, String contentDisplayName, byte[] logBytes) { switchUser(); File tempFile = null; OutputStream out = null; ContentResourceEdit cre = null; try { cre = getContentResourceEdit(contentId, contentDisplayName); tempFile = File.createTempFile("ses", ".tmp"); tempFile.deleteOnExit(); out = new FileOutputStream(tempFile); out.write(logBytes); IOUtils.copy(cre.streamContent(), out); out.flush(); cre.setContent(new FileInputStream(tempFile)); contentHostingService.commitResource(cre, NotificationService.NOTI_NONE); } catch (IOException e) { log.error("IOException ["+e.getMessage()+"]", e); } catch (ServerOverloadException e) { log.error("ServerOverloadException ["+e.getMessage()+"]", e); } catch (PermissionException e) { log.error("PermissionException ["+e.getMessage()+"]", e); } catch (TypeException e) { log.error("TypeException ["+e.getMessage()+"]", e); } catch (InUseException e) { log.error("InUseException ["+e.getMessage()+"]", e); } catch (VirusFoundException e) { log.error("VirusFoundException ["+e.getMessage()+"]", e); } catch (OverQuotaException e) { log.error("OverQuotaException ["+e.getMessage()+"]", e); } finally { try { if (null != out) { out.close(); } if (null != tempFile) { tempFile.delete(); } } catch (IOException e) { log.error("IOException ["+e.getMessage()+"]", e); } } }
Source:
private static int defaultCalculator(String productAttribute, Consumer consumer) { return consumer.getFact(ATTRIBUTES_TO_FACTS.get(productAttribute)) != null ? Integer.parseInt(consumer.getFact(ATTRIBUTES_TO_FACTS.get(productAttribute))) : 1; }

Target:
private static int defaultCalculator(String productAttribute, Consumer consumer) { String fact = consumer.getFact(ATTRIBUTES_TO_FACTS.get(productAttribute)); return fact != null ? Integer.parseInt(fact) : 1; }
Source:
private Map<Cell, Value> getRowsSomeColumns(final TableReference tableRef, final Iterable<byte[]> rows, final ColumnSelection columnSelection, final long timestamp) { if (Iterables.isEmpty(rows)) { return ImmutableMap.of(); } Map<Cell, Value> toReturn = new HashMap<>(); for (List<byte[]> part : Iterables.partition(rows, PARTITION_SIZE)) { toReturn.putAll(run(ctx -> { Select<? extends Record> query = getLatestTimestampQuerySomeColumns( ctx, tableRef, ImmutableList.copyOf(part), columnSelection.getSelectedColumns(), timestamp); Result<? extends Record> records = fetchValues(ctx, tableRef, query); Map<Cell, Value> results = Maps.newHashMapWithExpectedSize(records.size()); for (Record record : records) { results.put( Cell.create(record.getValue(A_ROW_NAME), record.getValue(A_COL_NAME)), Value.create(record.getValue(A_VALUE), record.getValue(A_TIMESTAMP))); } return results; })); } return toReturn; }

Target:
private Map<Cell, Value> getRowsSomeColumns(final TableReference tableRef, final Iterable<byte[]> rows, final ColumnSelection columnSelection, final long timestamp) { if (Iterables.isEmpty(rows)) { return ImmutableMap.of(); } return run(ctx -> { Select<? extends Record> query = getLatestTimestampQuerySomeColumns( ctx, tableRef, ImmutableList.copyOf(rows), columnSelection.getSelectedColumns(), timestamp); Result<? extends Record> records = fetchValues(ctx, tableRef, query); Map<Cell, Value> results = Maps.newHashMapWithExpectedSize(records.size()); for (Record record : records) { results.put( Cell.create(record.getValue(A_ROW_NAME), record.getValue(A_COL_NAME)), Value.create(record.getValue(A_VALUE), record.getValue(A_TIMESTAMP))); } return results; }); }
Source:
public void testCreateSymlink() throws IOException { FS fs = FS.DETECTED; if (!fs.supportsSymlinks()) return; fs.createSymLink(new File(trash, "x"), "y"); String target = fs.readSymLink(new File(trash, "x")); assertEquals("y", target); }

Target:
public void testCreateSymlink() throws IOException { FS fs = FS.DETECTED; try { fs.createSymLink(new File(trash, "x"), "y"); } catch (IOException e) { if (fs.supportsSymlinks()) fail("FS claims to support symlinks but attempt to create symlink failed"); return; } assertTrue(fs.supportsSymlinks()); String target = fs.readSymLink(new File(trash, "x")); assertEquals("y", target); }
Source:
private boolean compareAt(Object o, int i, int j, int jLen) { for (; i < iLen; i++) { if ((j >= jLen) || (cLike[i] != getChar(o, j++))) { return false; } } if (j != jLen) { return false; } return true; }

Target:
private boolean compareAt(Object o, int i, int j, int jLen) { for (; i < iLen; i++) { if ((j >= jLen) || (cStartsWith[i] != getChar(o, j++))) { return false; } } return true; }
Source:
static public boolean isVariantFile(final File file){ final String name = file.getName(); if (name.endsWith(UNCOMPRESSED_VCF_ENDING)) return true; if (name.endsWith(COMPRESSED_VCF_ENDING)) return true; if (name.endsWith(BCF_ENDING)) return true; return false; }

Target:
static public boolean isVariantFile(final File file){ final String name = file.getName(); return name.endsWith(UNCOMPRESSED_VCF_ENDING) || name.endsWith(COMPRESSED_VCF_ENDING) || name.endsWith(BCF_ENDING); }
Source:
public final void registerResourceWebscript() throws IOException { if (resourcePatternResolver == null) { return; } final Resource[] resources = resourcePatternResolver.getResources("osgibundle:" + WEB_PATH + "**"); if (resources.length == 0) { return; } if (bundleContext == null) { Intrinsics.throwNpe(); } if (webscriptRegistry == null) { Intrinsics.throwNpe(); } currentWebscript = new ResourceWebscript(bundleContext); webscriptRegistry.registerWebScript(currentWebscript); }

Target:
public final void registerResourceWebscript() throws IOException { if (resourcePatternResolver == null) { return; } final Resource[] resources = resourcePatternResolver.getResources("osgibundle:" + WEB_PATH + "**"); if (resources.length == 0) { return; } if (bundleContext == null) { throw new IllegalStateException("bundleContext"); } if (webscriptRegistry == null) { throw new IllegalStateException("webscriptRegistry"); } currentWebscript = new ResourceWebscript(bundleContext); webscriptRegistry.registerWebScript(currentWebscript); }
Source:
private ImmutableSortedMap<String, ImmutableList<String>> readMap(final String mapPath) { String fileContent; String actualPath = mapPath; try { if (Strings.isNullOrEmpty(mapPath)) { actualPath = this.getClass().getClassLoader().getResource("defaultWhiteListMap.json").getFile(); LOGGER.info("using default whiteList map located at [%s]", actualPath); InputStream byteContent = this.getClass().getClassLoader().getResourceAsStream("defaultWhiteListMap.json"); try (final InputStreamReader in = new InputStreamReader(byteContent, StandardCharsets.UTF_8)) { fileContent = CharStreams.toString(in); } } else { fileContent = Files.asCharSource(new File(mapPath), StandardCharsets.UTF_8).read(); } return mapper.readerFor(new TypeReference<ImmutableSortedMap<String, ImmutableList<String>>>() { }).readValue(fileContent); } catch (IOException e) { throw new ISE(e, "Got an exception while parsing file [%s]", actualPath); } }

Target:
private ImmutableSortedMap<String, ImmutableList<String>> readMap(final String mapPath) { String fileContent; String actualPath = mapPath; try { if (Strings.isNullOrEmpty(mapPath)) { URL defaultWhiteListMapUrl = this.getClass().getClassLoader().getResource("defaultWhiteListMap.json"); actualPath = defaultWhiteListMapUrl.getFile(); LOGGER.info("using default whiteList map located at [%s]", actualPath); fileContent = Resources.toString(defaultWhiteListMapUrl, StandardCharsets.UTF_8); } else { fileContent = Files.asCharSource(new File(mapPath), StandardCharsets.UTF_8).read(); } return mapper.readerFor(new TypeReference<ImmutableSortedMap<String, ImmutableList<String>>>() { }).readValue(fileContent); } catch (IOException e) { throw new ISE(e, "Got an exception while parsing file [%s]", actualPath); } }
Source:
private synchronized BridgeHandler getDssBridgeHandler() { if (this.dssBridgeHandler == null) { Bridge bridge = getBridge(); if (bridge == null) { logger.debug("Bride cannot be found"); return null; } ThingHandler handler = bridge.getHandler(); if (handler instanceof BridgeHandler) { dssBridgeHandler = (BridgeHandler) handler; } else { return null; } } if (temperatureSensorTransmitter == null && zoneID != null) { dssBridgeHandler.registerTemperatureControlStatusListener(this); } return dssBridgeHandler; }

Target:
private synchronized BridgeHandler getDssBridgeHandler() { if (this.dssBridgeHandler == null) { Bridge bridge = getBridge(); if (bridge == null) { logger.debug("Bride cannot be found"); return null; } ThingHandler handler = bridge.getHandler(); if (handler instanceof BridgeHandler) { dssBridgeHandler = (BridgeHandler) handler; } else { return null; } } return dssBridgeHandler; }
Source:
public static void main(String[] args) throws Exception { if (args.length > 1) { throw new IllegalArgumentException("wrong number of arguments"); } else if (args.length != 1) { throw new IllegalArgumentException("port parameter not supplied"); } URL log4jProperties = SarosLauncher.class.getResource(LOGGING_CONFIG_FILE); PropertyConfigurator.configure(log4jProperties); LogOutputStream los = new LogOutputStream(LOG, Level.DEBUG); PrintStream ps = new PrintStream(los); System.setOut(ps); int port = Integer.parseInt(args[0]); Socket socket = new Socket("localhost", port); LOG.info("listening on port " + port); Runtime.getRuntime() .addShutdownHook( new Thread() { public void run() { try { socket.close(); } catch (IOException e) { } } }); SarosLanguageServer langSvr = new SarosLanguageServer(); Launcher<ISarosLanguageClient> l = Launcher.createLauncher( langSvr, ISarosLanguageClient.class, socket.getInputStream(), socket.getOutputStream()); ISarosLanguageClient langClt = l.getRemoteProxy(); LOG.addAppender(new LanguageClientAppender(langClt)); langSvr.connect(langClt); l.startListening(); }

Target:
public static void main(String[] args) throws Exception { if (args.length > 1) { throw new IllegalArgumentException("wrong number of arguments"); } else if (args.length != 1) { throw new IllegalArgumentException("port parameter not supplied"); } else if (!args[0].matches("\\d+")) { throw new IllegalArgumentException("port is not a number"); } URL log4jProperties = SarosLauncher.class.getResource(LOGGING_CONFIG_FILE); PropertyConfigurator.configure(log4jProperties); LOG.addAppender(new ConsoleAppender()); int port = Integer.parseInt(args[0]); Socket socket = new Socket("localhost", port); LOG.info("listening on port " + port); Runtime.getRuntime() .addShutdownHook( new Thread() { public void run() { try { socket.close(); } catch (IOException e) { } } }); SarosLanguageServer langSvr = new SarosLanguageServer(); Launcher<ISarosLanguageClient> l = Launcher.createLauncher( langSvr, ISarosLanguageClient.class, socket.getInputStream(), socket.getOutputStream()); ISarosLanguageClient langClt = l.getRemoteProxy(); LOG.addAppender(new LanguageClientAppender(langClt)); langSvr.connect(langClt); l.startListening(); }
Source:
public void throttlerTest() throws InterruptedException { MockTime time = new MockTime(); time.currentMilliseconds = 0; time.currentNanoSeconds = 0; time.sleepTimeExpected = 0; Throttler throttler = new Throttler(100, 10, true, time); throttler.maybeThrottle(50); Assert.assertEquals(time.currentMilliseconds, 0); time.currentNanoSeconds = 11 * Time.NsPerMs; time.currentMilliseconds = 11; time.sleepTimeExpected = 1489; throttler.maybeThrottle(100); time.currentNanoSeconds = 22 * Time.NsPerMs; time.currentMilliseconds = 22; time.sleepTimeExpected = 4989; throttler.maybeThrottle(500); System.out.println(time.currentMilliseconds); }

Target:
public void throttlerTest() throws InterruptedException { MockTime time = new MockTime(); time.currentMilliseconds = 0; time.currentNanoSeconds = 0; time.sleepTimeExpected = 0; Throttler throttler = new Throttler(100, 10, true, time); throttler.maybeThrottle(50); Assert.assertEquals(time.currentMilliseconds, 0); time.currentNanoSeconds = 11 * Time.NsPerMs; time.currentMilliseconds = 11; time.sleepTimeExpected = 1489; throttler.maybeThrottle(100); time.currentNanoSeconds = 22 * Time.NsPerMs; time.currentMilliseconds = 22; time.sleepTimeExpected = 4989; throttler.maybeThrottle(500); Assert.assertEquals(time.currentMilliseconds, 5011); }
Source:
public Application approveApplication(PerunSession session, Application app) throws PerunException { User user = app.getUser(); Group group = app.getGroup(); AttributesManager am = session.getPerun().getAttributesManager(); Attribute attestation = am.getAttribute(session, group, A_G_D_groupAttestation); String newValue = attestation.valueAsString(); Attribute bonaFideStatus = am.getAttribute(session, user, A_U_D_userBonaFideStatus); List<String> value = new ArrayList<>(); if (bonaFideStatus.getValue() == null) { value = bonaFideStatus.valueAsList(); } value.add(newValue); bonaFideStatus.setValue(value); am.setAttribute(session, user, bonaFideStatus); return app; }

Target:
public Application approveApplication(PerunSession session, Application app) throws PerunException { User user = app.getUser(); Group group = app.getGroup(); AttributesManager am = session.getPerun().getAttributesManager(); Attribute attestation = am.getAttribute(session, group, A_G_D_groupAttestation); String newValue = attestation.valueAsString(); Attribute bonaFideStatus = am.getAttribute(session, user, A_U_D_userBonaFideStatus); List<String> value = new ArrayList<>(); if (bonaFideStatus.getValue() != null && bonaFideStatus.valueAsList() != null) { value = bonaFideStatus.valueAsList(); } value.add(newValue); bonaFideStatus.setValue(value); am.setAttribute(session, user, bonaFideStatus); return app; }
Source:
public boolean equals(Object object) { if (!(object instanceof Person)) { return false; } else { return getId().equals(((Person) object).getId()); } }

Target:
public boolean equals(Object object) { if (this == object) { return true; } else if (!(object instanceof Person)) { return false; } else { return getId().equals(((Person) object).getId()); } }