before
stringlengths
33
3.21M
after
stringlengths
63
3.21M
repo
stringlengths
1
56
type
stringclasses
1 value
__index_level_0__
int64
0
442k
private TrieNode buildTrie(BinaryComparable[] splits, int lower, int upper, byte[] prefix, int maxDepth) { final int depth = prefix.length; if (depth >= maxDepth || lower >= upper - 1) { if (lower == upper && new CarriedTrieNodeRef().content != null) { return new CarriedTrieNodeRef().content; } TrieNode result = LeafTrieNodeFactory(depth, splits, lower, upper); new CarriedTrieNodeRef().content = lower == upper ? result : null; return result; } InnerTrieNode result = new InnerTrieNode(depth); byte[] trial = Arrays.copyOf(prefix, prefix.length + 1); int currentBound = lower; for (int ch = 0; ch < 0xFF; ++ch) { trial[depth] = (byte) (ch + 1); lower = currentBound; while (currentBound < upper) { if (splits[currentBound].compareTo(trial, 0, trial.length) >= 0) { break; } currentBound += 1; } trial[depth] = (byte) ch; result.child[0xFF & ch] = buildTrieRec(splits, lower, currentBound, trial, maxDepth, new CarriedTrieNodeRef()); } trial[depth] = (byte) 0xFF; result.child[0xFF] = buildTrieRec(splits, lower, currentBound, trial, maxDepth, new CarriedTrieNodeRef()); return result; }
private TrieNode buildTrie(BinaryComparable[] splits, int lower, int upper, byte[] prefix, int maxDepth) { <DeepExtract> final int depth = prefix.length; if (depth >= maxDepth || lower >= upper - 1) { if (lower == upper && new CarriedTrieNodeRef().content != null) { return new CarriedTrieNodeRef().content; } TrieNode result = LeafTrieNodeFactory(depth, splits, lower, upper); new CarriedTrieNodeRef().content = lower == upper ? result : null; return result; } InnerTrieNode result = new InnerTrieNode(depth); byte[] trial = Arrays.copyOf(prefix, prefix.length + 1); int currentBound = lower; for (int ch = 0; ch < 0xFF; ++ch) { trial[depth] = (byte) (ch + 1); lower = currentBound; while (currentBound < upper) { if (splits[currentBound].compareTo(trial, 0, trial.length) >= 0) { break; } currentBound += 1; } trial[depth] = (byte) ch; result.child[0xFF & ch] = buildTrieRec(splits, lower, currentBound, trial, maxDepth, new CarriedTrieNodeRef()); } trial[depth] = (byte) 0xFF; result.child[0xFF] = buildTrieRec(splits, lower, currentBound, trial, maxDepth, new CarriedTrieNodeRef()); return result; </DeepExtract> }
webarchive-discovery
positive
115
public BankAccount find(int id) throws PagarMeException { final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s", getClassName(), id)); final BankAccount other = JSONUtils.getAsObject((JsonObject) request.execute(), BankAccount.class); super.copy(other); this.chargeTransferFees = other.chargeTransferFees; this.bankCode = other.bankCode; this.agencia = other.agencia; this.agenciaDv = other.agenciaDv; this.conta = other.conta; this.contaDv = other.contaDv; this.documentNumber = other.documentNumber; this.legalName = other.legalName; this.documentType = other.documentType; this.type = other.type; flush(); return other; }
public BankAccount find(int id) throws PagarMeException { final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s", getClassName(), id)); final BankAccount other = JSONUtils.getAsObject((JsonObject) request.execute(), BankAccount.class); <DeepExtract> super.copy(other); this.chargeTransferFees = other.chargeTransferFees; this.bankCode = other.bankCode; this.agencia = other.agencia; this.agenciaDv = other.agenciaDv; this.conta = other.conta; this.contaDv = other.contaDv; this.documentNumber = other.documentNumber; this.legalName = other.legalName; this.documentType = other.documentType; this.type = other.type; </DeepExtract> flush(); return other; }
pagarme-java
positive
116
@Override protected void setUpView() { mToolbar.setTitle("相册"); setSupportActionBar(mToolbar); mToolbar.setNavigationOnClickListener(mArrowListener); if ((Boolean) SPUtil.get(GalleryActivity.this, Constant.NIGHT_MODE, true)) { mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.gray)); mToolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); mToolbar.setTitleTextColor(getResources().getColor(android.R.color.white)); mToolbar.setNavigationIcon(R.mipmap.arrow_back); StatusBarUtil.setStatusBarColor(GalleryActivity.this, getResources().getColor(R.color.colorPrimaryDark)); } else { mRelativeLayout.setBackgroundColor(getResources().getColor(android.R.color.black)); mToolbar.setBackgroundColor(getResources().getColor(android.R.color.black)); mToolbar.setTitleTextColor(getResources().getColor(android.R.color.darker_gray)); mToolbar.setNavigationIcon(R.mipmap.arrow_back_night); StatusBarUtil.setStatusBarColor(GalleryActivity.this, getResources().getColor(android.R.color.black)); } }
@Override protected void setUpView() { mToolbar.setTitle("相册"); setSupportActionBar(mToolbar); mToolbar.setNavigationOnClickListener(mArrowListener); <DeepExtract> if ((Boolean) SPUtil.get(GalleryActivity.this, Constant.NIGHT_MODE, true)) { mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.gray)); mToolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); mToolbar.setTitleTextColor(getResources().getColor(android.R.color.white)); mToolbar.setNavigationIcon(R.mipmap.arrow_back); StatusBarUtil.setStatusBarColor(GalleryActivity.this, getResources().getColor(R.color.colorPrimaryDark)); } else { mRelativeLayout.setBackgroundColor(getResources().getColor(android.R.color.black)); mToolbar.setBackgroundColor(getResources().getColor(android.R.color.black)); mToolbar.setTitleTextColor(getResources().getColor(android.R.color.darker_gray)); mToolbar.setNavigationIcon(R.mipmap.arrow_back_night); StatusBarUtil.setStatusBarColor(GalleryActivity.this, getResources().getColor(android.R.color.black)); } </DeepExtract> }
EasyMvp
positive
117
private int jjMoveStringLiteralDfa5_1(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_1(3, old0); try { curChar = input_stream.readChar(); } catch (java.io.IOException e) { jjStopStringLiteralDfa_1(4, active0); return 5; } switch(curChar) { case 110: return jjMoveStringLiteralDfa6_1(active0, 0x400000000000L); default: break; } return jjMoveNfa_1(jjStopStringLiteralDfa_1(4, active0), 4 + 1); }
private int jjMoveStringLiteralDfa5_1(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_1(3, old0); try { curChar = input_stream.readChar(); } catch (java.io.IOException e) { jjStopStringLiteralDfa_1(4, active0); return 5; } switch(curChar) { case 110: return jjMoveStringLiteralDfa6_1(active0, 0x400000000000L); default: break; } <DeepExtract> return jjMoveNfa_1(jjStopStringLiteralDfa_1(4, active0), 4 + 1); </DeepExtract> }
el-spec
positive
118
@Test public void shouldReportCorrectCoverageForSpecialisation4() { final SideEffect2<Integer, boolean[]> se = new SideEffect2<Integer, boolean[]>() { @Override public void apply(final Integer classId, final boolean[] probes) { CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], probes[2], probes[3]); } }; ascendingPermuation(4, se); CodeCoverageStore.resetAllStaticState(); descendingPermutation(4, se); }
@Test public void shouldReportCorrectCoverageForSpecialisation4() { final SideEffect2<Integer, boolean[]> se = new SideEffect2<Integer, boolean[]>() { @Override public void apply(final Integer classId, final boolean[] probes) { CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], probes[2], probes[3]); } }; <DeepExtract> ascendingPermuation(4, se); CodeCoverageStore.resetAllStaticState(); descendingPermutation(4, se); </DeepExtract> }
QuickTheories
positive
119
@Test public void createGraphTiming() throws Exception { factory = new SimpleRDF(); graph = factory.createGraph(); final IRI subject = factory.createIRI("subj"); final IRI predicate = factory.createIRI("pred"); final List<IRI> types = new ArrayList<>(Types.values()); types.remove(Types.RDF_LANGSTRING); Collections.shuffle(types); for (int i = 0; i < TRIPLES; i++) { if (i % 11 == 0) { graph.add(subject, predicate, factory.createBlankNode("Example " + i)); } else if (i % 5 == 0) { graph.add(subject, predicate, factory.createLiteral("Example " + i, "en")); } else if (i % 3 == 0) { graph.add(subject, predicate, factory.createLiteral("Example " + i, types.get(i % types.size()))); } else { graph.add(subject, predicate, factory.createLiteral("Example " + i)); } } }
@Test public void createGraphTiming() throws Exception { <DeepExtract> factory = new SimpleRDF(); graph = factory.createGraph(); final IRI subject = factory.createIRI("subj"); final IRI predicate = factory.createIRI("pred"); final List<IRI> types = new ArrayList<>(Types.values()); types.remove(Types.RDF_LANGSTRING); Collections.shuffle(types); for (int i = 0; i < TRIPLES; i++) { if (i % 11 == 0) { graph.add(subject, predicate, factory.createBlankNode("Example " + i)); } else if (i % 5 == 0) { graph.add(subject, predicate, factory.createLiteral("Example " + i, "en")); } else if (i % 3 == 0) { graph.add(subject, predicate, factory.createLiteral("Example " + i, types.get(i % types.size()))); } else { graph.add(subject, predicate, factory.createLiteral("Example " + i)); } } </DeepExtract> }
commons-rdf
positive
120
@Override protected Void run() throws Exception { TaskListener listener = this.getContext().get(TaskListener.class); AWSElasticBeanstalk client = AWSClientFactory.create(AWSElasticBeanstalkClientBuilder.standard(), this.getContext(), this.getContext().get(EnvVars.class)); listener.getLogger().format("Creating application version (%s) for application (%s) %n", step.versionLabel, step.applicationName); CreateApplicationVersionRequest request = new CreateApplicationVersionRequest(); request.setApplicationName(step.applicationName); request.setVersionLabel(step.versionLabel); request.setSourceBundle(new S3Location(step.s3Bucket, step.s3Key)); this.description = step.description; CreateApplicationVersionResult result = client.createApplicationVersion(request); listener.getLogger().format("Created a new version (%s) for the application (%s) with arn (%s) %n", step.versionLabel, step.applicationName, result.getApplicationVersion().getApplicationVersionArn()); return null; }
@Override protected Void run() throws Exception { TaskListener listener = this.getContext().get(TaskListener.class); AWSElasticBeanstalk client = AWSClientFactory.create(AWSElasticBeanstalkClientBuilder.standard(), this.getContext(), this.getContext().get(EnvVars.class)); listener.getLogger().format("Creating application version (%s) for application (%s) %n", step.versionLabel, step.applicationName); CreateApplicationVersionRequest request = new CreateApplicationVersionRequest(); request.setApplicationName(step.applicationName); request.setVersionLabel(step.versionLabel); request.setSourceBundle(new S3Location(step.s3Bucket, step.s3Key)); <DeepExtract> this.description = step.description; </DeepExtract> CreateApplicationVersionResult result = client.createApplicationVersion(request); listener.getLogger().format("Created a new version (%s) for the application (%s) with arn (%s) %n", step.versionLabel, step.applicationName, result.getApplicationVersion().getApplicationVersionArn()); return null; }
pipeline-aws-plugin
positive
121
@Test public void testOpenWithInactiveVisibleConsoleView() { partHelper.showView(CONSOLE_VIEW_ID); partHelper.showView(PartHelper.PROBLEM_VIEW_ID); new ConsoleViewOpener(activePage).open(); IViewPart consoleView = getConsoleView(); assertThat(consoleView).isNotNull(); assertThat(consoleView.getSite().getPage().getActivePart()).isEqualTo(consoleView); }
@Test public void testOpenWithInactiveVisibleConsoleView() { partHelper.showView(CONSOLE_VIEW_ID); partHelper.showView(PartHelper.PROBLEM_VIEW_ID); new ConsoleViewOpener(activePage).open(); <DeepExtract> IViewPart consoleView = getConsoleView(); assertThat(consoleView).isNotNull(); assertThat(consoleView.getSite().getPage().getActivePart()).isEqualTo(consoleView); </DeepExtract> }
gonsole
positive
122
private void setNewPatientId(Element root, Integer patientId) { try { NodeList elemList = root.getElementsByTagName(XformBuilder.NODE_PATIENT_PATIENT_ID); if (!(elemList != null && elemList.getLength() > 0)) return; elemList.item(0).setTextContent(patientId.toString()); } catch (Exception e) { log.error(e.getMessage(), e); } }
private void setNewPatientId(Element root, Integer patientId) { <DeepExtract> try { NodeList elemList = root.getElementsByTagName(XformBuilder.NODE_PATIENT_PATIENT_ID); if (!(elemList != null && elemList.getLength() > 0)) return; elemList.item(0).setTextContent(patientId.toString()); } catch (Exception e) { log.error(e.getMessage(), e); } </DeepExtract> }
buendia
positive
123
public DynamicByteBuffer put(byte v) { if (autoExpand) { expand(1); } _buf.put(v); return this; }
public DynamicByteBuffer put(byte v) { <DeepExtract> if (autoExpand) { expand(1); } </DeepExtract> _buf.put(v); return this; }
netx
positive
125
static void dataSetAssertion(CallInfo callInfo, DataSet expected, DataSet actual) { if (expected == null) { throw new InvalidOperationException("Null argument for 'old' data set."); } if (actual == null) { throw new InvalidOperationException("Null argument for 'new' data set."); } if (expected.getSource() != actual.getSource()) { throw new InvalidOperationException("Data source mismatch between data sets."); } DataSource source = expected.getSource(); Delta delta = new Delta(expected, actual); DataSetAssertion assertion = new DataSetAssertion(expected, delta); source.getDB().log(callInfo, assertion); if (!assertion.passed()) { throw new DBAssertionError(callInfo.getMessage()); } }
static void dataSetAssertion(CallInfo callInfo, DataSet expected, DataSet actual) { <DeepExtract> if (expected == null) { throw new InvalidOperationException("Null argument for 'old' data set."); } if (actual == null) { throw new InvalidOperationException("Null argument for 'new' data set."); } if (expected.getSource() != actual.getSource()) { throw new InvalidOperationException("Data source mismatch between data sets."); } </DeepExtract> DataSource source = expected.getSource(); Delta delta = new Delta(expected, actual); DataSetAssertion assertion = new DataSetAssertion(expected, delta); source.getDB().log(callInfo, assertion); if (!assertion.passed()) { throw new DBAssertionError(callInfo.getMessage()); } }
jdbdt
positive
126
@Test void shouldNotTriggerNotificationOnTaintVulnerabilityRaisedEventWhenConnectionDoesNotExist() { mockFileInAFolder(); var projectBindingWrapperMock = mock(ProjectBindingWrapper.class); var projectBinding = mock(ProjectBinding.class); when(projectBinding.projectKey()).thenReturn(PROJECT_KEY); when(projectBindingWrapperMock.getBinding()).thenReturn(projectBinding); folderBindingCache.put(workspaceFolderPath.toUri(), Optional.of(projectBindingWrapperMock)); when(projectBindingWrapperMock.getEngine()).thenReturn(fakeEngine); when(projectBinding.serverPathToIdePath(fileInAWorkspaceFolderPath.toUri().toString())).thenReturn(Optional.of(fileInAWorkspaceFolderPath.toString())); when(projectBindingWrapperMock.getConnectionId()).thenReturn(CONNECTION_ID); List<ServerTaintIssue> issuesList = new ArrayList<>(); ServerTaintIssue newIssue = new ServerTaintIssue(ISSUE_KEY2, false, RULE_KEY, MAIN_LOCATION.getMessage(), fileInAWorkspaceFolderPath.toUri().toString(), CREATION_DATE, ISSUE_SEVERITY, RULE_TYPE, textRangeWithHashFromTextRange(MAIN_LOCATION.getTextRange()), null); issuesList.add(newIssue); when(fakeEngine.getServerTaintIssues(any(ProjectBinding.class), eq(CURRENT_BRANCH_NAME), eq(FILE_PHP))).thenReturn(issuesList); when(settingsManager.getCurrentSettings()).thenReturn(newWorkspaceSettingsWithServers(Collections.emptyMap())); when(workspaceFoldersManager.findFolderForFile(any(URI.class))).thenReturn(Optional.of(new WorkspaceFolderWrapper(workspaceFolderPath.toUri(), new WorkspaceFolder(workspaceFolderPath.toString())))); TaintVulnerabilityRaisedEvent fakeEvent = new TaintVulnerabilityRaisedEvent(ISSUE_KEY2, PROJECT_KEY, CURRENT_BRANCH_NAME, CREATION_DATE, RULE_KEY, ISSUE_SEVERITY, RULE_TYPE, MAIN_LOCATION, FLOWS, null); underTest.handleEvents(fakeEvent); verify(taintVulnerabilityRaisedNotification, never()).showTaintVulnerabilityNotification(fakeEvent, CONNECTION_ID, false); }
@Test void shouldNotTriggerNotificationOnTaintVulnerabilityRaisedEventWhenConnectionDoesNotExist() { <DeepExtract> mockFileInAFolder(); var projectBindingWrapperMock = mock(ProjectBindingWrapper.class); var projectBinding = mock(ProjectBinding.class); when(projectBinding.projectKey()).thenReturn(PROJECT_KEY); when(projectBindingWrapperMock.getBinding()).thenReturn(projectBinding); folderBindingCache.put(workspaceFolderPath.toUri(), Optional.of(projectBindingWrapperMock)); when(projectBindingWrapperMock.getEngine()).thenReturn(fakeEngine); when(projectBinding.serverPathToIdePath(fileInAWorkspaceFolderPath.toUri().toString())).thenReturn(Optional.of(fileInAWorkspaceFolderPath.toString())); when(projectBindingWrapperMock.getConnectionId()).thenReturn(CONNECTION_ID); </DeepExtract> List<ServerTaintIssue> issuesList = new ArrayList<>(); ServerTaintIssue newIssue = new ServerTaintIssue(ISSUE_KEY2, false, RULE_KEY, MAIN_LOCATION.getMessage(), fileInAWorkspaceFolderPath.toUri().toString(), CREATION_DATE, ISSUE_SEVERITY, RULE_TYPE, textRangeWithHashFromTextRange(MAIN_LOCATION.getTextRange()), null); issuesList.add(newIssue); when(fakeEngine.getServerTaintIssues(any(ProjectBinding.class), eq(CURRENT_BRANCH_NAME), eq(FILE_PHP))).thenReturn(issuesList); when(settingsManager.getCurrentSettings()).thenReturn(newWorkspaceSettingsWithServers(Collections.emptyMap())); when(workspaceFoldersManager.findFolderForFile(any(URI.class))).thenReturn(Optional.of(new WorkspaceFolderWrapper(workspaceFolderPath.toUri(), new WorkspaceFolder(workspaceFolderPath.toString())))); TaintVulnerabilityRaisedEvent fakeEvent = new TaintVulnerabilityRaisedEvent(ISSUE_KEY2, PROJECT_KEY, CURRENT_BRANCH_NAME, CREATION_DATE, RULE_KEY, ISSUE_SEVERITY, RULE_TYPE, MAIN_LOCATION, FLOWS, null); underTest.handleEvents(fakeEvent); verify(taintVulnerabilityRaisedNotification, never()).showTaintVulnerabilityNotification(fakeEvent, CONNECTION_ID, false); }
sonarlint-language-server
positive
129
public void setImageBitmap(Bitmap bitmap, ExifInterface exif) { int degreesRotated = 0; if (bitmap != null && exif != null) { BitmapUtils.RotateBitmapResult result = BitmapUtils.rotateBitmapByExif(bitmap, exif); setBitmap = result.bitmap; degreesRotated = result.degrees; mInitialDegreesRotated = result.degrees; } else { setBitmap = bitmap; } mCropOverlayView.setInitialCropWindowRect(null); if (mBitmap == null || !mBitmap.equals(setBitmap)) { mImageView.clearAnimation(); clearImageInt(); mBitmap = setBitmap; mImageView.setImageBitmap(mBitmap); mLoadedImageUri = null; mImageResource = 0; mLoadedSampleSize = 1; mDegreesRotated = degreesRotated; applyImageMatrix(getWidth(), getHeight(), true, false); if (mCropOverlayView != null) { mCropOverlayView.resetCropOverlayView(); setCropOverlayVisibility(); } } }
public void setImageBitmap(Bitmap bitmap, ExifInterface exif) { int degreesRotated = 0; if (bitmap != null && exif != null) { BitmapUtils.RotateBitmapResult result = BitmapUtils.rotateBitmapByExif(bitmap, exif); setBitmap = result.bitmap; degreesRotated = result.degrees; mInitialDegreesRotated = result.degrees; } else { setBitmap = bitmap; } mCropOverlayView.setInitialCropWindowRect(null); <DeepExtract> if (mBitmap == null || !mBitmap.equals(setBitmap)) { mImageView.clearAnimation(); clearImageInt(); mBitmap = setBitmap; mImageView.setImageBitmap(mBitmap); mLoadedImageUri = null; mImageResource = 0; mLoadedSampleSize = 1; mDegreesRotated = degreesRotated; applyImageMatrix(getWidth(), getHeight(), true, false); if (mCropOverlayView != null) { mCropOverlayView.resetCropOverlayView(); setCropOverlayVisibility(); } } </DeepExtract> }
Whatsapp-Like-PhotoEditor
positive
130
@Override public int getLength() { if (length == UNDEFINED_LENGTH_OR_OFFSET_OR_ADDRESS) { this.length = HEADER.getDataLength(getMetadataAddress()) + OFF_HEAP_HEADER_SIZE; } return length - OFF_HEAP_HEADER_SIZE; }
@Override public int getLength() { <DeepExtract> if (length == UNDEFINED_LENGTH_OR_OFFSET_OR_ADDRESS) { this.length = HEADER.getDataLength(getMetadataAddress()) + OFF_HEAP_HEADER_SIZE; } </DeepExtract> return length - OFF_HEAP_HEADER_SIZE; }
Oak
positive
131
protected Object convert(Settings settings, Object value) throws SettingException { int ln = (List) super.convert(settings, value).size(); List res = new ArrayList(ln); for (int i = 0; i < ln; i++) { Object o = (List) super.convert(settings, value).get(i); if (o instanceof String) { File f = new File((String) o); if (f.isAbsolute()) { res.add(new FileWithSettingValue((String) o, (String) o)); } else { res.add(new FileWithSettingValue(settings.baseDir, (String) o, (String) o)); } } else if (o instanceof FileWithSettingValue) { res.add(o); } else { throw new SettingException("All list items must be strings (paths), " + "but the item at index " + i + " is a " + typeName(o) + "."); } } return res; }
protected Object convert(Settings settings, Object value) throws SettingException { <DeepExtract> int ln = (List) super.convert(settings, value).size(); List res = new ArrayList(ln); for (int i = 0; i < ln; i++) { Object o = (List) super.convert(settings, value).get(i); if (o instanceof String) { File f = new File((String) o); if (f.isAbsolute()) { res.add(new FileWithSettingValue((String) o, (String) o)); } else { res.add(new FileWithSettingValue(settings.baseDir, (String) o, (String) o)); } } else if (o instanceof FileWithSettingValue) { res.add(o); } else { throw new SettingException("All list items must be strings (paths), " + "but the item at index " + i + " is a " + typeName(o) + "."); } } return res; </DeepExtract> }
fmpp
positive
132
@Test public void testGetRevisions_XmlFile() { SortedMap<String, HistoryDescr> result = sutWithUserAndNoDuplicateHistory.getRevisions(test1Config); assertEquals(5, result.size()); assertEquals("2012-11-21_11-29-12", result.firstKey()); assertEquals("2012-11-21_11-42-05", result.lastKey()); final HistoryDescr firstValue = result.get(result.firstKey()); final HistoryDescr lastValue = result.get(result.lastKey()); assertEquals("Created", firstValue.getOperation()); assertEquals("anonymous", firstValue.getUserID()); assertEquals("Changed", lastValue.getOperation()); }
@Test public void testGetRevisions_XmlFile() { SortedMap<String, HistoryDescr> result = sutWithUserAndNoDuplicateHistory.getRevisions(test1Config); <DeepExtract> assertEquals(5, result.size()); assertEquals("2012-11-21_11-29-12", result.firstKey()); assertEquals("2012-11-21_11-42-05", result.lastKey()); final HistoryDescr firstValue = result.get(result.firstKey()); final HistoryDescr lastValue = result.get(result.lastKey()); assertEquals("Created", firstValue.getOperation()); assertEquals("anonymous", firstValue.getUserID()); assertEquals("Changed", lastValue.getOperation()); </DeepExtract> }
jobConfigHistory-plugin
positive
136
public Criteria andProductIdGreaterThanOrEqualTo(String value) { if (value == null) { throw new RuntimeException("Value for " + "productId" + " cannot be null"); } criteria.add(new Criterion("product_id >=", value)); return (Criteria) this; }
public Criteria andProductIdGreaterThanOrEqualTo(String value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "productId" + " cannot be null"); } criteria.add(new Criterion("product_id >=", value)); </DeepExtract> return (Criteria) this; }
sihai-maven-ssm-alipay
positive
137
public static void decorateDialog(Window dialog) { try { dialog.setAlwaysOnTop(true); } catch (SecurityException e) { } dialog.pack(); if (dialog instanceof JDialog) { ((JDialog) dialog).setModalityType(Dialog.ModalityType.APPLICATION_MODAL); } dialog.toFront(); List<Image> icons = getApplicationIcons(); if (icons.size() != 0) { dialog.setIconImages(icons); } }
public static void decorateDialog(Window dialog) { try { dialog.setAlwaysOnTop(true); } catch (SecurityException e) { } dialog.pack(); if (dialog instanceof JDialog) { ((JDialog) dialog).setModalityType(Dialog.ModalityType.APPLICATION_MODAL); } dialog.toFront(); <DeepExtract> List<Image> icons = getApplicationIcons(); if (icons.size() != 0) { dialog.setIconImages(icons); } </DeepExtract> }
TightVNC
positive
138
public Object getDao(Class<?> clazz, String dataSourceName, RSConnection conn) { try { Constructor<?> cons = clazz.getDeclaredConstructor((Class[]) null); obj = cons.newInstance(); Method init = clazz.getMethod("init", new Class[] { RSConnection.class, PageHelper.class, String.class }); init.invoke(obj, new Object[] { conn, conn.getPageHelper(), dataSourceName }); } catch (Exception e) { throw new RuntimeException(e); } return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this); }
public Object getDao(Class<?> clazz, String dataSourceName, RSConnection conn) { try { Constructor<?> cons = clazz.getDeclaredConstructor((Class[]) null); obj = cons.newInstance(); Method init = clazz.getMethod("init", new Class[] { RSConnection.class, PageHelper.class, String.class }); init.invoke(obj, new Object[] { conn, conn.getPageHelper(), dataSourceName }); } catch (Exception e) { throw new RuntimeException(e); } <DeepExtract> return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this); </DeepExtract> }
roubsite
positive
139
private void matchStartAndEnd(@NonNull TransitionValuesMaps startValues, @NonNull TransitionValuesMaps endValues) { ArrayMap<View, TransitionValues> unmatchedStart = new ArrayMap<View, TransitionValues>(startValues.viewValues); ArrayMap<View, TransitionValues> unmatchedEnd = new ArrayMap<View, TransitionValues>(endValues.viewValues); for (int i = 0; i < mMatchOrder.length; i++) { switch(mMatchOrder[i]) { case MATCH_INSTANCE: matchInstances(unmatchedStart, unmatchedEnd); break; case MATCH_NAME: matchNames(unmatchedStart, unmatchedEnd, startValues.nameValues, endValues.nameValues); break; case MATCH_ID: matchIds(unmatchedStart, unmatchedEnd, startValues.idValues, endValues.idValues); break; case MATCH_ITEM_ID: matchItemIds(unmatchedStart, unmatchedEnd, startValues.itemIdValues, endValues.itemIdValues); break; } } for (int i = 0; i < unmatchedStart.size(); i++) { mStartValuesList.add(unmatchedStart.valueAt(i)); mEndValuesList.add(null); } for (int i = 0; i < unmatchedEnd.size(); i++) { mEndValuesList.add(unmatchedEnd.valueAt(i)); mStartValuesList.add(null); } }
private void matchStartAndEnd(@NonNull TransitionValuesMaps startValues, @NonNull TransitionValuesMaps endValues) { ArrayMap<View, TransitionValues> unmatchedStart = new ArrayMap<View, TransitionValues>(startValues.viewValues); ArrayMap<View, TransitionValues> unmatchedEnd = new ArrayMap<View, TransitionValues>(endValues.viewValues); for (int i = 0; i < mMatchOrder.length; i++) { switch(mMatchOrder[i]) { case MATCH_INSTANCE: matchInstances(unmatchedStart, unmatchedEnd); break; case MATCH_NAME: matchNames(unmatchedStart, unmatchedEnd, startValues.nameValues, endValues.nameValues); break; case MATCH_ID: matchIds(unmatchedStart, unmatchedEnd, startValues.idValues, endValues.idValues); break; case MATCH_ITEM_ID: matchItemIds(unmatchedStart, unmatchedEnd, startValues.itemIdValues, endValues.itemIdValues); break; } } <DeepExtract> for (int i = 0; i < unmatchedStart.size(); i++) { mStartValuesList.add(unmatchedStart.valueAt(i)); mEndValuesList.add(null); } for (int i = 0; i < unmatchedEnd.size(); i++) { mEndValuesList.add(unmatchedEnd.valueAt(i)); mStartValuesList.add(null); } </DeepExtract> }
Transitions-Everywhere
positive
140
public boolean pmFastequals(Object other) { if (this == other) return true; if (other == null) return false; if (this.getClass() != other.getClass()) return false; final Bean other = (Bean) other; if (this.i != other.i) return false; if (this.integer == null) { if (other.integer != null) return false; } else if (!this.integer.equals(other.integer)) return false; if (!Arrays.equals(this.ints, other.ints)) return false; if (this.string == null) { if (other.string != null) return false; } else if (!this.string.equals(other.string)) return false; if (this.strings == null) { if (other.strings != null) return false; } else if (!this.strings.equals(other.strings)) return false; return true; }
public boolean pmFastequals(Object other) { <DeepExtract> if (this == other) return true; if (other == null) return false; if (this.getClass() != other.getClass()) return false; final Bean other = (Bean) other; if (this.i != other.i) return false; if (this.integer == null) { if (other.integer != null) return false; } else if (!this.integer.equals(other.integer)) return false; if (!Arrays.equals(this.ints, other.ints)) return false; if (this.string == null) { if (other.string != null) return false; } else if (!this.string.equals(other.string)) return false; if (this.strings == null) { if (other.strings != null) return false; } else if (!this.strings.equals(other.strings)) return false; return true; </DeepExtract> }
pojomatic
positive
141
@java.lang.Override public Builder newBuilderForType() { return DEFAULT_INSTANCE.toBuilder(); }
@java.lang.Override public Builder newBuilderForType() { <DeepExtract> return DEFAULT_INSTANCE.toBuilder(); </DeepExtract> }
FightingICE
positive
142
@Test void svgWithDottedLines() { Bill bill = SampleData.getExample1(); bill.getFormat().setOutputSize(OutputSize.A4_PORTRAIT_SHEET); bill.getFormat().setSeparatorType(SeparatorType.DOTTED_LINE_WITH_SCISSORS); bill.getFormat().setGraphicsFormat(GraphicsFormat.SVG); byte[] imageData = QRBill.generate(bill); if (GraphicsFormat.SVG == GraphicsFormat.PNG) FileComparison.assertGrayscaleImageContentsEqual(imageData, "linestyle_2.svg", 35000); else FileComparison.assertFileContentsEqual(imageData, "linestyle_2.svg"); }
@Test void svgWithDottedLines() { Bill bill = SampleData.getExample1(); <DeepExtract> bill.getFormat().setOutputSize(OutputSize.A4_PORTRAIT_SHEET); bill.getFormat().setSeparatorType(SeparatorType.DOTTED_LINE_WITH_SCISSORS); bill.getFormat().setGraphicsFormat(GraphicsFormat.SVG); byte[] imageData = QRBill.generate(bill); if (GraphicsFormat.SVG == GraphicsFormat.PNG) FileComparison.assertGrayscaleImageContentsEqual(imageData, "linestyle_2.svg", 35000); else FileComparison.assertFileContentsEqual(imageData, "linestyle_2.svg"); </DeepExtract> }
SwissQRBill
positive
143
PerformanceReport parse(File reportFile) throws Exception { boolean isXml; try (FileReader fr = new FileReader(reportFile); BufferedReader reader = new BufferedReader(fr)) { String line; boolean isXml = false; while ((line = reader.readLine()) != null) { if (line.trim().length() == 0) { continue; } if (line.toLowerCase().trim().startsWith("<?xml ")) { isXml = true; } break; } isXml = isXml; } if (isXml) { return parseXml(reportFile); } else { return parseCsv(reportFile); } }
PerformanceReport parse(File reportFile) throws Exception { <DeepExtract> boolean isXml; try (FileReader fr = new FileReader(reportFile); BufferedReader reader = new BufferedReader(fr)) { String line; boolean isXml = false; while ((line = reader.readLine()) != null) { if (line.trim().length() == 0) { continue; } if (line.toLowerCase().trim().startsWith("<?xml ")) { isXml = true; } break; } isXml = isXml; } </DeepExtract> if (isXml) { return parseXml(reportFile); } else { return parseCsv(reportFile); } }
performance-plugin
positive
144
public final void close() { if (!open) return; open = false; if (true && !inventory.getViewers().isEmpty()) player.closeInventory(); HandlerList.unregisterAll(listener); }
public final void close() { <DeepExtract> if (!open) return; open = false; if (true && !inventory.getViewers().isEmpty()) player.closeInventory(); HandlerList.unregisterAll(listener); </DeepExtract> }
tree-feller
positive
145
public boolean add(final K k) { if (wrapped) a = ObjectArrays.grow(a, size + 1, size); else { if (size + 1 > a.length) { final int newLength = (int) Math.max(Math.min(2L * a.length, Arrays.MAX_ARRAY_SIZE), size + 1); final Object[] t = new Object[newLength]; System.arraycopy(a, 0, t, 0, size); a = (K[]) t; } } if (ASSERTS) assert size <= a.length; a[size++] = k; if (ASSERTS) assert size <= a.length; return true; }
public boolean add(final K k) { <DeepExtract> if (wrapped) a = ObjectArrays.grow(a, size + 1, size); else { if (size + 1 > a.length) { final int newLength = (int) Math.max(Math.min(2L * a.length, Arrays.MAX_ARRAY_SIZE), size + 1); final Object[] t = new Object[newLength]; System.arraycopy(a, 0, t, 0, size); a = (K[]) t; } } if (ASSERTS) assert size <= a.length; </DeepExtract> a[size++] = k; if (ASSERTS) assert size <= a.length; return true; }
jhighlight
positive
146
public Criteria andOrderNoBetween(String value1, String value2) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "orderNo" + " cannot be null"); } criteria.add(new Criterion("order_no between", value1, value2)); return (Criteria) this; }
public Criteria andOrderNoBetween(String value1, String value2) { <DeepExtract> if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "orderNo" + " cannot be null"); } criteria.add(new Criterion("order_no between", value1, value2)); </DeepExtract> return (Criteria) this; }
hotel_ssm
positive
147
public static PImage blur(PImage img, int radius, int iterations) { PImage out = new PImage(img.width, img.height); out.loadPixels(); out.pixels = blur(img.pixels, img.width, img.height, radius, iterations); out.updatePixels(); return out; }
public static PImage blur(PImage img, int radius, int iterations) { <DeepExtract> PImage out = new PImage(img.width, img.height); out.loadPixels(); out.pixels = blur(img.pixels, img.width, img.height, radius, iterations); out.updatePixels(); return out; </DeepExtract> }
Project-16x16
positive
148
public void commit() throws SQLException { if (isClosed()) throw new SQLNonTransientConnectionException(WAS_CLOSED_CON); throw new SQLFeatureNotSupportedException(ALWAYS_AUTOCOMMIT); }
public void commit() throws SQLException { <DeepExtract> if (isClosed()) throw new SQLNonTransientConnectionException(WAS_CLOSED_CON); </DeepExtract> throw new SQLFeatureNotSupportedException(ALWAYS_AUTOCOMMIT); }
twig
positive
149
@Override public void onReceive(Context context, Intent intent) { if (DEBUG) { Log.d(TAG, "testBroadcast(): onReceive(Context context, Intent intent): context=" + context.toString() + "; intent=" + intent.toString()); } Toast.makeText(this, "testBroadcast(): onReceive(Context context, Intent intent): context=" + context.toString() + "; intent=" + intent.toString(), Toast.LENGTH_SHORT).show(); unregisterReceiver(this); }
@Override public void onReceive(Context context, Intent intent) { if (DEBUG) { Log.d(TAG, "testBroadcast(): onReceive(Context context, Intent intent): context=" + context.toString() + "; intent=" + intent.toString()); } <DeepExtract> Toast.makeText(this, "testBroadcast(): onReceive(Context context, Intent intent): context=" + context.toString() + "; intent=" + intent.toString(), Toast.LENGTH_SHORT).show(); </DeepExtract> unregisterReceiver(this); }
GPT
positive
150
public void increaseMana(int mana) { this.mana = this.getMana() + mana; if (this.getMana() + mana > getMaxMana()) this.mana = getMaxMana(); else if (this.getMana() + mana < 0) this.mana = 0; if (this.mana > this.maxMana) this.mana = this.maxMana; }
public void increaseMana(int mana) { <DeepExtract> this.mana = this.getMana() + mana; if (this.getMana() + mana > getMaxMana()) this.mana = getMaxMana(); else if (this.getMana() + mana < 0) this.mana = 0; </DeepExtract> if (this.mana > this.maxMana) this.mana = this.maxMana; }
Loot-Slash-Conquer-Pre1.14
positive
151
@Test(groups = "fast") public void testSendValidPayload() { Mockito.when(filterRequestHandler.processEvent(Mockito.<Event>any(), Mockito.<ParsedRequest>any())).thenReturn(true); eventDeserializer.setEvent(Mockito.mock(Event.class)); try { Mockito.when(deserializerFactory.getEventDeserializer(Mockito.<ParsedRequest>any())).thenReturn(eventDeserializer); } catch (IOException e) { Assert.fail(); } final EventDeserializerRequestHandler enabledRequestHandler = new EventDeserializerRequestHandler(true, filterRequestHandler, deserializerFactory); resource = setupResource(enabledRequestHandler); Assert.assertEquals(enabledRequestHandler.getRejectedMeter().count(), 0); Assert.assertEquals(enabledRequestHandler.getBadRequestMeter().count(), 0); verifyNoEventWentThroughTheFilterRequestHandler(enabledRequestHandler); final Response response = callEndpoint(); Assert.assertEquals(enabledRequestHandler.getRejectedMeter().count(), 0); Assert.assertEquals(enabledRequestHandler.getBadRequestMeter().count(), 0); final MetricName successMetricName = enabledRequestHandler.getSuccessMetricsKey(deserializationType); for (final MetricName name : enabledRequestHandler.getMetrics().keySet()) { if (name.equals(successMetricName)) { Assert.assertEquals(enabledRequestHandler.getMetrics().get(name).count(), 1); } else { Assert.assertEquals(enabledRequestHandler.getMetrics().get(name).count(), 0); } } Assert.assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode()); if (false) { Assert.assertEquals(response.getMetadata().get("Warning").size(), 1); Assert.assertTrue(StringUtils.contains(((String) response.getMetadata().get("Warning").get(0)), "199")); } else { Assert.assertNull(response.getMetadata().get("Warning")); } verifyCacheControl(response); Mockito.verify(httpHeaders, Mockito.times(5)).getRequestHeader(Mockito.<String>any()); Mockito.verify(request, Mockito.times(1)).getRemoteAddr(); try { Mockito.verify(deserializerFactory, Mockito.times(1)).getEventDeserializer(Mockito.<ParsedRequest>any()); } catch (IOException e) { Assert.fail(); } Mockito.verify(filterRequestHandler, Mockito.times(1)).processEvent(Mockito.<Event>any(), Mockito.<ParsedRequest>any()); Mockito.verifyNoMoreInteractions(httpHeaders, request, deserializerFactory, filterRequestHandler); }
@Test(groups = "fast") public void testSendValidPayload() { Mockito.when(filterRequestHandler.processEvent(Mockito.<Event>any(), Mockito.<ParsedRequest>any())).thenReturn(true); eventDeserializer.setEvent(Mockito.mock(Event.class)); try { Mockito.when(deserializerFactory.getEventDeserializer(Mockito.<ParsedRequest>any())).thenReturn(eventDeserializer); } catch (IOException e) { Assert.fail(); } final EventDeserializerRequestHandler enabledRequestHandler = new EventDeserializerRequestHandler(true, filterRequestHandler, deserializerFactory); resource = setupResource(enabledRequestHandler); Assert.assertEquals(enabledRequestHandler.getRejectedMeter().count(), 0); Assert.assertEquals(enabledRequestHandler.getBadRequestMeter().count(), 0); verifyNoEventWentThroughTheFilterRequestHandler(enabledRequestHandler); final Response response = callEndpoint(); Assert.assertEquals(enabledRequestHandler.getRejectedMeter().count(), 0); Assert.assertEquals(enabledRequestHandler.getBadRequestMeter().count(), 0); final MetricName successMetricName = enabledRequestHandler.getSuccessMetricsKey(deserializationType); for (final MetricName name : enabledRequestHandler.getMetrics().keySet()) { if (name.equals(successMetricName)) { Assert.assertEquals(enabledRequestHandler.getMetrics().get(name).count(), 1); } else { Assert.assertEquals(enabledRequestHandler.getMetrics().get(name).count(), 0); } } <DeepExtract> Assert.assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode()); if (false) { Assert.assertEquals(response.getMetadata().get("Warning").size(), 1); Assert.assertTrue(StringUtils.contains(((String) response.getMetadata().get("Warning").get(0)), "199")); } else { Assert.assertNull(response.getMetadata().get("Warning")); } verifyCacheControl(response); </DeepExtract> Mockito.verify(httpHeaders, Mockito.times(5)).getRequestHeader(Mockito.<String>any()); Mockito.verify(request, Mockito.times(1)).getRemoteAddr(); try { Mockito.verify(deserializerFactory, Mockito.times(1)).getEventDeserializer(Mockito.<ParsedRequest>any()); } catch (IOException e) { Assert.fail(); } Mockito.verify(filterRequestHandler, Mockito.times(1)).processEvent(Mockito.<Event>any(), Mockito.<ParsedRequest>any()); Mockito.verifyNoMoreInteractions(httpHeaders, request, deserializerFactory, filterRequestHandler); }
collector
positive
153
@Override public void onErrorResponse(VolleyError volleyError) { if (ingreso == 0) { cargarWebService(getString(R.string.ip2)); ingreso = 1; } else { if (ingreso == 1) { cargarWebService(getString(R.string.ip3)); ingreso = 2; } else { txtInfo.setText("No se pudo establecer conexión con el servidor, Intente mas tarde"); obtenerListaProyectos(); } } }
@Override public void onErrorResponse(VolleyError volleyError) { <DeepExtract> if (ingreso == 0) { cargarWebService(getString(R.string.ip2)); ingreso = 1; } else { if (ingreso == 1) { cargarWebService(getString(R.string.ip3)); ingreso = 2; } else { txtInfo.setText("No se pudo establecer conexión con el servidor, Intente mas tarde"); obtenerListaProyectos(); } } </DeepExtract> }
curso-android-codejavu
positive
155
@Test @Ignore public void testRequestWhen() { Double in = new Double(36); ACLMessageFactory factory = new ACLMessageFactory(Encodings.XML); Map<String, Object> args = new LinkedHashMap<String, Object>(); args.put("x", in); Rule condition = new Rule(); condition.setDrl("String( this == \"actionTrigger\" || this == \"actionTrigger2\")"); Action action = MessageContentFactory.newActionContent("squareRoot", args); ACLMessage req = factory.newRequestWhenMessage("me", "you", action, condition); mainAgent.tell(req); ACLMessage info = factory.newInformMessage("me", "you", new String("actionTrigger")); mainAgent.tell(info); ACLMessage info2 = factory.newInformMessage("me", "you", new String("actionTrigger2")); mainAgent.tell(info2); int counter = 0; do { System.out.println("Answer for " + req.getId() + " is not ready, wait... "); try { Thread.sleep(1000); counter++; } catch (InterruptedException e) { e.printStackTrace(); } } while (mainAgent.peekAgentAnswers(req.getId()).size() < 2 && counter < 50); if (counter == 50) { fail("Timeout waiting for an answer to msg " + req.getId()); } StatefulKnowledgeSession s2 = mainAgent.getInnerSession("session2"); QueryResults ans = s2.getQueryResults("squareRoot", in, Variable.v); assertEquals(1, ans.size()); assertEquals(6.0, (Double) ans.iterator().next().get("$return"), 1e-6); }
@Test @Ignore public void testRequestWhen() { Double in = new Double(36); ACLMessageFactory factory = new ACLMessageFactory(Encodings.XML); Map<String, Object> args = new LinkedHashMap<String, Object>(); args.put("x", in); Rule condition = new Rule(); condition.setDrl("String( this == \"actionTrigger\" || this == \"actionTrigger2\")"); Action action = MessageContentFactory.newActionContent("squareRoot", args); ACLMessage req = factory.newRequestWhenMessage("me", "you", action, condition); mainAgent.tell(req); ACLMessage info = factory.newInformMessage("me", "you", new String("actionTrigger")); mainAgent.tell(info); ACLMessage info2 = factory.newInformMessage("me", "you", new String("actionTrigger2")); mainAgent.tell(info2); <DeepExtract> int counter = 0; do { System.out.println("Answer for " + req.getId() + " is not ready, wait... "); try { Thread.sleep(1000); counter++; } catch (InterruptedException e) { e.printStackTrace(); } } while (mainAgent.peekAgentAnswers(req.getId()).size() < 2 && counter < 50); if (counter == 50) { fail("Timeout waiting for an answer to msg " + req.getId()); } </DeepExtract> StatefulKnowledgeSession s2 = mainAgent.getInnerSession("session2"); QueryResults ans = s2.getQueryResults("squareRoot", in, Variable.v); assertEquals(1, ans.size()); assertEquals(6.0, (Double) ans.iterator().next().get("$return"), 1e-6); }
drools-mas
positive
156
private void createDot(float rx, float ry) { Snapshot dot = new Snapshot(false); mBitmapToLoad = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_picsphere_marker); Quaternion quat = new Quaternion(); quat.fromEuler(rx, 0, ry); float[] matrix = quat.getMatrix(); Matrix.translateM(matrix, 0, 0, 0, 100); return matrix; Matrix.scaleM(dot.mModelMatrix, 0, 0.1f, 0.1f, 0.1f); mAutoAlphaX = rx; mAutoAlphaY = ry; mDots.add(dot); }
private void createDot(float rx, float ry) { Snapshot dot = new Snapshot(false); mBitmapToLoad = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_picsphere_marker); Quaternion quat = new Quaternion(); quat.fromEuler(rx, 0, ry); float[] matrix = quat.getMatrix(); Matrix.translateM(matrix, 0, 0, 0, 100); return matrix; Matrix.scaleM(dot.mModelMatrix, 0, 0.1f, 0.1f, 0.1f); <DeepExtract> mAutoAlphaX = rx; mAutoAlphaY = ry; </DeepExtract> mDots.add(dot); }
android_packages_apps_Focal
positive
157
public Criteria andOrderIdGreaterThanOrEqualTo(Integer value) { if (value == null) { throw new RuntimeException("Value for " + "orderId" + " cannot be null"); } criteria.add(new Criterion("order_id >=", value)); return (Criteria) this; }
public Criteria andOrderIdGreaterThanOrEqualTo(Integer value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "orderId" + " cannot be null"); } criteria.add(new Criterion("order_id >=", value)); </DeepExtract> return (Criteria) this; }
Ordering
positive
158
@Override public void caseAIfromexprExprFunction(AIfromexprExprFunction node) { if (new UnaryOperatorCompiler(this, node.getExprFunction()) != ExpressionCompiler.this) throw new RuntimeException("unexpected switch"); invokeOperator(UnaryOperator.TIME, exprString); }
@Override public void caseAIfromexprExprFunction(AIfromexprExprFunction node) { <DeepExtract> if (new UnaryOperatorCompiler(this, node.getExprFunction()) != ExpressionCompiler.this) throw new RuntimeException("unexpected switch"); invokeOperator(UnaryOperator.TIME, exprString); </DeepExtract> }
arden2bytecode
positive
159
public void simulateProgress() { if (this.state == STATE_PROGRESS_STARTED) { return; } tempBitmap.recycle(); resetTempCanvas(); this.state = STATE_PROGRESS_STARTED; if (STATE_PROGRESS_STARTED == STATE_PROGRESS_STARTED) { setCurrentProgress(0); simulateProgressAnimator.start(); } else if (STATE_PROGRESS_STARTED == STATE_DONE_STARTED) { setCurrentDoneBgOffset(MAX_DONE_BG_OFFSET); setCurrentCheckmarkOffset(MAX_DONE_IMG_OFFSET); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playSequentially(doneBgAnimator, checkmarkAnimator); animatorSet.start(); } else if (STATE_PROGRESS_STARTED == STATE_FINISHED) { if (onLoadingFinishedListener != null) { onLoadingFinishedListener.onLoadingFinished(); } } }
public void simulateProgress() { <DeepExtract> if (this.state == STATE_PROGRESS_STARTED) { return; } tempBitmap.recycle(); resetTempCanvas(); this.state = STATE_PROGRESS_STARTED; if (STATE_PROGRESS_STARTED == STATE_PROGRESS_STARTED) { setCurrentProgress(0); simulateProgressAnimator.start(); } else if (STATE_PROGRESS_STARTED == STATE_DONE_STARTED) { setCurrentDoneBgOffset(MAX_DONE_BG_OFFSET); setCurrentCheckmarkOffset(MAX_DONE_IMG_OFFSET); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playSequentially(doneBgAnimator, checkmarkAnimator); animatorSet.start(); } else if (STATE_PROGRESS_STARTED == STATE_FINISHED) { if (onLoadingFinishedListener != null) { onLoadingFinishedListener.onLoadingFinished(); } } </DeepExtract> }
UPES-SPE-Fest
positive
160
public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; if (domainBaseClass != null && dataSource != null) { DataSourceConnectionProvider cp = new DataSourceConnectionProvider(dataSource); ActiveRecordBase.putConnectionProvider(domainBaseClass, cp); } if (domainBaseClass != null && adapterClass != null) { try { Adapter adapter = (Adapter) Class.forName(adapterClass).newInstance(); ActiveRecordBase.putConnectionAdapter(domainBaseClass, adapter); } catch (Exception e) { } } }
public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; <DeepExtract> if (domainBaseClass != null && dataSource != null) { DataSourceConnectionProvider cp = new DataSourceConnectionProvider(dataSource); ActiveRecordBase.putConnectionProvider(domainBaseClass, cp); } if (domainBaseClass != null && adapterClass != null) { try { Adapter adapter = (Adapter) Class.forName(adapterClass).newInstance(); ActiveRecordBase.putConnectionAdapter(domainBaseClass, adapter); } catch (Exception e) { } } </DeepExtract> }
etmvc
positive
161
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_surface_camera); mCloseIv = findViewById(R.id.toolbar_close_iv); mCloseIv.setOnClickListener(this); mSwitchCameraIv = findViewById(R.id.toolbar_switch_iv); mSwitchCameraIv.setOnClickListener(this); mTakePictureIv = findViewById(R.id.take_picture_iv); mTakePictureIv.setOnClickListener(this); mPictureIv = findViewById(R.id.picture_iv); mPictureIv.setOnClickListener(this); mPictureIv.setImageBitmap(ImageUtils.getLatestThumbBitmap()); mCameraView = findViewById(R.id.camera_view); mCameraProxy = mCameraView.getCameraProxy(); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_surface_camera); <DeepExtract> mCloseIv = findViewById(R.id.toolbar_close_iv); mCloseIv.setOnClickListener(this); mSwitchCameraIv = findViewById(R.id.toolbar_switch_iv); mSwitchCameraIv.setOnClickListener(this); mTakePictureIv = findViewById(R.id.take_picture_iv); mTakePictureIv.setOnClickListener(this); mPictureIv = findViewById(R.id.picture_iv); mPictureIv.setOnClickListener(this); mPictureIv.setImageBitmap(ImageUtils.getLatestThumbBitmap()); mCameraView = findViewById(R.id.camera_view); mCameraProxy = mCameraView.getCameraProxy(); </DeepExtract> }
EasyOpengl
positive
162
@Override public Status update(String table, String key, HashMap<String, ByteIterator> values) { if (debug) { System.out.println("Setting up put for key: " + key); } try { long mutator = connection.mutator_open(ns, table, 0, 0); SerializedCellsWriter writer = new SerializedCellsWriter(BUFFER_SIZE * values.size(), true); for (Map.Entry<String, ByteIterator> entry : values.entrySet()) { writer.add(key, columnFamily, entry.getKey(), SerializedCellsFlag.AUTO_ASSIGN, ByteBuffer.wrap(entry.getValue().toArray())); } connection.mutator_set_cells_serialized(mutator, writer.buffer(), true); connection.mutator_close(mutator); } catch (ClientException e) { if (debug) { System.err.println("Error doing set: " + e.message); } return Status.ERROR; } catch (TException e) { if (debug) { System.err.println("Error doing set"); } return Status.ERROR; } return Status.OK; }
@Override public Status update(String table, String key, HashMap<String, ByteIterator> values) { <DeepExtract> if (debug) { System.out.println("Setting up put for key: " + key); } try { long mutator = connection.mutator_open(ns, table, 0, 0); SerializedCellsWriter writer = new SerializedCellsWriter(BUFFER_SIZE * values.size(), true); for (Map.Entry<String, ByteIterator> entry : values.entrySet()) { writer.add(key, columnFamily, entry.getKey(), SerializedCellsFlag.AUTO_ASSIGN, ByteBuffer.wrap(entry.getValue().toArray())); } connection.mutator_set_cells_serialized(mutator, writer.buffer(), true); connection.mutator_close(mutator); } catch (ClientException e) { if (debug) { System.err.println("Error doing set: " + e.message); } return Status.ERROR; } catch (TException e) { if (debug) { System.err.println("Error doing set"); } return Status.ERROR; } return Status.OK; </DeepExtract> }
anna
positive
163
@Override public JobrunrMigrationsRecord value3(String value) { set(2, value); return this; }
@Override public JobrunrMigrationsRecord value3(String value) { <DeepExtract> set(2, value); </DeepExtract> return this; }
openvsx
positive
165
@Override public void writeRawUTF8String(final byte[] text, final int offset, final int length) throws IOException { writer.writeString(new String(text, offset, length, StandardCharsets.UTF_8)); }
@Override public void writeRawUTF8String(final byte[] text, final int offset, final int length) throws IOException { <DeepExtract> writer.writeString(new String(text, offset, length, StandardCharsets.UTF_8)); </DeepExtract> }
mongojack
positive
167
@Override Exception onConferenceCallStarted(Call jvbConferenceCall) { this.jvbCall = jvbConferenceCall; this.chatRoom = super.jvbConference.getJvbRoom(); if (!service.isConfiguredProperly()) { logger.warn("TranscriptionService is not properly configured"); sendMessageToRoom("Transcriber is not properly " + "configured. Contact the service administrators and let them " + "know! I will now leave."); jvbConference.stop(); return null; } for (TranscriptionResultPublisher pub : handler.getTranscriptResultPublishers()) { if (pub instanceof TranscriptionEventListener) transcriber.addTranscriptionEventListener((TranscriptionEventListener) pub); } transcriber.addTranscriptionEventListener(this); transcriber.start(); List<ConferenceMember> confMembers = getCurrentConferenceMembers(); if (confMembers == null) { logger.warn("Cannot add initial ConferenceMembers to " + "transcription"); } else { for (ConferenceMember confMember : confMembers) { if ("jvb".equals(confMember.getAddress())) { continue; } String identifier = getParticipantIdentifier(confMember); this.transcriber.updateParticipant(identifier, confMember); } } List<ChatRoomMember> chatRoomMembers = getCurrentChatRoomMembers(); if (chatRoomMembers == null) { logger.warn("Cannot add initial ChatRoomMembers to transcription"); return; } for (ChatRoomMember chatRoomMember : chatRoomMembers) { ChatRoomMemberJabberImpl chatRoomMemberJabber; if (chatRoomMember instanceof ChatRoomMemberJabberImpl) { chatRoomMemberJabber = (ChatRoomMemberJabberImpl) chatRoomMember; } else { logger.warn("Could not cast a ChatRoomMember to " + "ChatRoomMemberJabberImpl"); continue; } String identifier = getParticipantIdentifier(chatRoomMemberJabber); if ("focus".equals(identifier)) { continue; } if (chatRoomMemberJabber.getJabberID().getResourceOrNull() == null) { continue; } this.transcriber.updateParticipant(identifier, chatRoomMember); this.transcriber.participantJoined(identifier); } StringBuilder welcomeMessage = new StringBuilder(); finalTranscriptPromises.addAll(handler.getTranscriptPublishPromises()); for (TranscriptPublisher.Promise promise : finalTranscriptPromises) { if (promise.hasDescription()) { welcomeMessage.append(promise.getDescription()); } promise.maybeStartRecording(transcriber.getMediaDevice()); } if (welcomeMessage.length() > 0) { sendMessageToRoom(welcomeMessage.toString()); } try { CallManager.acceptCall(jvbConferenceCall); } catch (OperationFailedException e) { return e; } logger.debug("TranscriptionGatewaySession started transcribing"); return null; }
@Override Exception onConferenceCallStarted(Call jvbConferenceCall) { this.jvbCall = jvbConferenceCall; this.chatRoom = super.jvbConference.getJvbRoom(); if (!service.isConfiguredProperly()) { logger.warn("TranscriptionService is not properly configured"); sendMessageToRoom("Transcriber is not properly " + "configured. Contact the service administrators and let them " + "know! I will now leave."); jvbConference.stop(); return null; } for (TranscriptionResultPublisher pub : handler.getTranscriptResultPublishers()) { if (pub instanceof TranscriptionEventListener) transcriber.addTranscriptionEventListener((TranscriptionEventListener) pub); } transcriber.addTranscriptionEventListener(this); transcriber.start(); <DeepExtract> List<ConferenceMember> confMembers = getCurrentConferenceMembers(); if (confMembers == null) { logger.warn("Cannot add initial ConferenceMembers to " + "transcription"); } else { for (ConferenceMember confMember : confMembers) { if ("jvb".equals(confMember.getAddress())) { continue; } String identifier = getParticipantIdentifier(confMember); this.transcriber.updateParticipant(identifier, confMember); } } List<ChatRoomMember> chatRoomMembers = getCurrentChatRoomMembers(); if (chatRoomMembers == null) { logger.warn("Cannot add initial ChatRoomMembers to transcription"); return; } for (ChatRoomMember chatRoomMember : chatRoomMembers) { ChatRoomMemberJabberImpl chatRoomMemberJabber; if (chatRoomMember instanceof ChatRoomMemberJabberImpl) { chatRoomMemberJabber = (ChatRoomMemberJabberImpl) chatRoomMember; } else { logger.warn("Could not cast a ChatRoomMember to " + "ChatRoomMemberJabberImpl"); continue; } String identifier = getParticipantIdentifier(chatRoomMemberJabber); if ("focus".equals(identifier)) { continue; } if (chatRoomMemberJabber.getJabberID().getResourceOrNull() == null) { continue; } this.transcriber.updateParticipant(identifier, chatRoomMember); this.transcriber.participantJoined(identifier); } </DeepExtract> StringBuilder welcomeMessage = new StringBuilder(); finalTranscriptPromises.addAll(handler.getTranscriptPublishPromises()); for (TranscriptPublisher.Promise promise : finalTranscriptPromises) { if (promise.hasDescription()) { welcomeMessage.append(promise.getDescription()); } promise.maybeStartRecording(transcriber.getMediaDevice()); } if (welcomeMessage.length() > 0) { sendMessageToRoom(welcomeMessage.toString()); } try { CallManager.acceptCall(jvbConferenceCall); } catch (OperationFailedException e) { return e; } logger.debug("TranscriptionGatewaySession started transcribing"); return null; }
jigasi
positive
168
void setPagerAdapter(@Nullable final PagerAdapter adapter, final boolean addObserver) { if (pagerAdapter != null && pagerAdapterObserver != null) { pagerAdapter.unregisterDataSetObserver(pagerAdapterObserver); } pagerAdapter = adapter; if (addObserver && adapter != null) { if (pagerAdapterObserver == null) { pagerAdapterObserver = new PagerAdapterObserver(); } adapter.registerDataSetObserver(pagerAdapterObserver); } removeAllTabs(); if (pagerAdapter != null) { final int adapterCount = pagerAdapter.getCount(); for (int i = 0; i < adapterCount; i++) { addTab(newTab().setText(pagerAdapter.getPageTitle(i)), false); } if (viewPager != null && adapterCount > 0) { final int curItem = viewPager.getCurrentItem(); if (curItem != getSelectedTabPosition() && curItem < getTabCount()) { selectTab(getTabAt(curItem), true, true); } } } }
void setPagerAdapter(@Nullable final PagerAdapter adapter, final boolean addObserver) { if (pagerAdapter != null && pagerAdapterObserver != null) { pagerAdapter.unregisterDataSetObserver(pagerAdapterObserver); } pagerAdapter = adapter; if (addObserver && adapter != null) { if (pagerAdapterObserver == null) { pagerAdapterObserver = new PagerAdapterObserver(); } adapter.registerDataSetObserver(pagerAdapterObserver); } <DeepExtract> removeAllTabs(); if (pagerAdapter != null) { final int adapterCount = pagerAdapter.getCount(); for (int i = 0; i < adapterCount; i++) { addTab(newTab().setText(pagerAdapter.getPageTitle(i)), false); } if (viewPager != null && adapterCount > 0) { final int curItem = viewPager.getCurrentItem(); if (curItem != getSelectedTabPosition() && curItem < getTabCount()) { selectTab(getTabAt(curItem), true, true); } } } </DeepExtract> }
SamsungOneUi
positive
169
public File getChild(File arg0, String arg1) { File tmp = null; try { tmp = view.getChild(arg0, arg1); if (tmp != null) return tmp; } catch (Exception e) { } try { tmp = super.getChild(arg0, arg1); if (tmp != null) return tmp; } catch (Exception e) { } File tmp = null; try { tmp = view.createFileObject(arg0, arg1); if (tmp != null) return tmp; } catch (Exception e) { } try { tmp = super.createFileObject(arg0, arg1); if (tmp != null) return tmp; } catch (Exception e) { } return fileit(arg0, arg1); }
public File getChild(File arg0, String arg1) { File tmp = null; try { tmp = view.getChild(arg0, arg1); if (tmp != null) return tmp; } catch (Exception e) { } try { tmp = super.getChild(arg0, arg1); if (tmp != null) return tmp; } catch (Exception e) { } <DeepExtract> File tmp = null; try { tmp = view.createFileObject(arg0, arg1); if (tmp != null) return tmp; } catch (Exception e) { } try { tmp = super.createFileObject(arg0, arg1); if (tmp != null) return tmp; } catch (Exception e) { } return fileit(arg0, arg1); </DeepExtract> }
CrococryptFile
positive
170
@Override public void buildInterrupted(SRunningBuild sRunningBuild) { Loggers.SERVER.debug("About to process MsTeams notifications for " + sRunningBuild.getProjectId() + " at buildState " + BuildStateEnum.BUILD_INTERRUPTED.getShortName()); for (MsTeamsNotificationConfigWrapper msteamsNotificationConfigWrapper : getListOfEnabledMsTeamsNotifications(sRunningBuild.getProjectId())) { if (BuildStateEnum.BUILD_INTERRUPTED.equals(BuildStateEnum.BUILD_STARTED)) { msteamsNotificationConfigWrapper.msteamsNotification.setPayload(myManager.buildStarted(sRunningBuild, getPreviousNonPersonalBuild(sRunningBuild))); msteamsNotificationConfigWrapper.msteamsNotification.setEnabled(msteamsNotificationConfigWrapper.whc.isEnabledForBuildType(sRunningBuild.getBuildType()) && msteamsNotificationConfigWrapper.msteamsNotification.getBuildStates().enabled(BuildStateEnum.BUILD_STARTED)); } else if (BuildStateEnum.BUILD_INTERRUPTED.equals(BuildStateEnum.BUILD_INTERRUPTED)) { msteamsNotificationConfigWrapper.msteamsNotification.setPayload(myManager.buildInterrupted(sRunningBuild, getPreviousNonPersonalBuild(sRunningBuild))); msteamsNotificationConfigWrapper.msteamsNotification.setEnabled(msteamsNotificationConfigWrapper.whc.isEnabledForBuildType(sRunningBuild.getBuildType()) && msteamsNotificationConfigWrapper.msteamsNotification.getBuildStates().enabled(BuildStateEnum.BUILD_INTERRUPTED)); } else if (BuildStateEnum.BUILD_INTERRUPTED.equals(BuildStateEnum.BEFORE_BUILD_FINISHED)) { msteamsNotificationConfigWrapper.msteamsNotification.setPayload(myManager.beforeBuildFinish(sRunningBuild, getPreviousNonPersonalBuild(sRunningBuild))); msteamsNotificationConfigWrapper.msteamsNotification.setEnabled(msteamsNotificationConfigWrapper.whc.isEnabledForBuildType(sRunningBuild.getBuildType()) && msteamsNotificationConfigWrapper.msteamsNotification.getBuildStates().enabled(BuildStateEnum.BEFORE_BUILD_FINISHED)); } else if (BuildStateEnum.BUILD_INTERRUPTED.equals(BuildStateEnum.BUILD_FINISHED)) { msteamsNotificationConfigWrapper.msteamsNotification.setEnabled(msteamsNotificationConfigWrapper.whc.isEnabledForBuildType(sRunningBuild.getBuildType()) && msteamsNotificationConfigWrapper.msteamsNotification.getBuildStates().enabled(BuildStateEnum.BUILD_FINISHED, sRunningBuild.getStatusDescriptor().isSuccessful(), this.hasBuildChangedHistoricalState(sRunningBuild))); msteamsNotificationConfigWrapper.msteamsNotification.setPayload(myManager.buildFinished(sRunningBuild, getPreviousNonPersonalBuild(sRunningBuild))); ; } doPost(msteamsNotificationConfigWrapper.msteamsNotification); } }
@Override public void buildInterrupted(SRunningBuild sRunningBuild) { <DeepExtract> Loggers.SERVER.debug("About to process MsTeams notifications for " + sRunningBuild.getProjectId() + " at buildState " + BuildStateEnum.BUILD_INTERRUPTED.getShortName()); for (MsTeamsNotificationConfigWrapper msteamsNotificationConfigWrapper : getListOfEnabledMsTeamsNotifications(sRunningBuild.getProjectId())) { if (BuildStateEnum.BUILD_INTERRUPTED.equals(BuildStateEnum.BUILD_STARTED)) { msteamsNotificationConfigWrapper.msteamsNotification.setPayload(myManager.buildStarted(sRunningBuild, getPreviousNonPersonalBuild(sRunningBuild))); msteamsNotificationConfigWrapper.msteamsNotification.setEnabled(msteamsNotificationConfigWrapper.whc.isEnabledForBuildType(sRunningBuild.getBuildType()) && msteamsNotificationConfigWrapper.msteamsNotification.getBuildStates().enabled(BuildStateEnum.BUILD_STARTED)); } else if (BuildStateEnum.BUILD_INTERRUPTED.equals(BuildStateEnum.BUILD_INTERRUPTED)) { msteamsNotificationConfigWrapper.msteamsNotification.setPayload(myManager.buildInterrupted(sRunningBuild, getPreviousNonPersonalBuild(sRunningBuild))); msteamsNotificationConfigWrapper.msteamsNotification.setEnabled(msteamsNotificationConfigWrapper.whc.isEnabledForBuildType(sRunningBuild.getBuildType()) && msteamsNotificationConfigWrapper.msteamsNotification.getBuildStates().enabled(BuildStateEnum.BUILD_INTERRUPTED)); } else if (BuildStateEnum.BUILD_INTERRUPTED.equals(BuildStateEnum.BEFORE_BUILD_FINISHED)) { msteamsNotificationConfigWrapper.msteamsNotification.setPayload(myManager.beforeBuildFinish(sRunningBuild, getPreviousNonPersonalBuild(sRunningBuild))); msteamsNotificationConfigWrapper.msteamsNotification.setEnabled(msteamsNotificationConfigWrapper.whc.isEnabledForBuildType(sRunningBuild.getBuildType()) && msteamsNotificationConfigWrapper.msteamsNotification.getBuildStates().enabled(BuildStateEnum.BEFORE_BUILD_FINISHED)); } else if (BuildStateEnum.BUILD_INTERRUPTED.equals(BuildStateEnum.BUILD_FINISHED)) { msteamsNotificationConfigWrapper.msteamsNotification.setEnabled(msteamsNotificationConfigWrapper.whc.isEnabledForBuildType(sRunningBuild.getBuildType()) && msteamsNotificationConfigWrapper.msteamsNotification.getBuildStates().enabled(BuildStateEnum.BUILD_FINISHED, sRunningBuild.getStatusDescriptor().isSuccessful(), this.hasBuildChangedHistoricalState(sRunningBuild))); msteamsNotificationConfigWrapper.msteamsNotification.setPayload(myManager.buildFinished(sRunningBuild, getPreviousNonPersonalBuild(sRunningBuild))); ; } doPost(msteamsNotificationConfigWrapper.msteamsNotification); } </DeepExtract> }
teamcity-msteams-notifier
positive
171
@Override public void onViewDetachedFromWindow(final View v) { dismiss(); if (SDK_INT >= LOLLIPOP) { context.getWindow().getDecorView().setOnApplyWindowInsetsListener(null); } popupWindow.setOnDismissListener(null); if (SDK_INT < LOLLIPOP) { rootView.getViewTreeObserver().removeGlobalOnLayoutListener(onGlobalLayoutListener); } rootView.removeOnAttachStateChangeListener(this); }
@Override public void onViewDetachedFromWindow(final View v) { <DeepExtract> dismiss(); if (SDK_INT >= LOLLIPOP) { context.getWindow().getDecorView().setOnApplyWindowInsetsListener(null); } </DeepExtract> popupWindow.setOnDismissListener(null); if (SDK_INT < LOLLIPOP) { rootView.getViewTreeObserver().removeGlobalOnLayoutListener(onGlobalLayoutListener); } rootView.removeOnAttachStateChangeListener(this); }
AXEmojiView
positive
172
@Override public Selection cop(final String column, final String op, final Object arg2) { if (currentSelection != null) { moveToColumns(currentSelection); } currentSelection = new SimpleClause(column, op, arg2); return this; }
@Override public Selection cop(final String column, final String op, final Object arg2) { <DeepExtract> if (currentSelection != null) { moveToColumns(currentSelection); } currentSelection = new SimpleClause(column, op, arg2); return this; </DeepExtract> }
influxdb-java
positive
173
private void apply(final Paint paint, final Typeface tf) { Typeface old = paint.getTypeface(); if (old == null) { oldStyle = 0; } else { oldStyle = old.getStyle(); } int fake = oldStyle & ~tf.getStyle(); if ((fake & Typeface.BOLD) != 0) { paint.setFakeBoldText(true); } if ((fake & Typeface.ITALIC) != 0) { paint.setTextSkewX(-0.25f); } paint.getShader(); this.typeface = tf; return this; }
private void apply(final Paint paint, final Typeface tf) { Typeface old = paint.getTypeface(); if (old == null) { oldStyle = 0; } else { oldStyle = old.getStyle(); } int fake = oldStyle & ~tf.getStyle(); if ((fake & Typeface.BOLD) != 0) { paint.setFakeBoldText(true); } if ((fake & Typeface.ITALIC) != 0) { paint.setTextSkewX(-0.25f); } paint.getShader(); <DeepExtract> this.typeface = tf; return this; </DeepExtract> }
BaseDemo
positive
174
void init(Context m) { master = m; masterHandler = new Handler(m.getMainLooper()); notificationManager = (NotificationManager) master.getSystemService(Context.NOTIFICATION_SERVICE); if (m instanceof Application) { app = (Application) m; } else if (m instanceof Service) { app = ((Service) m).getApplication(); } else if (m instanceof Activity) { app = ((Activity) m).getApplication(); } else throw new ClassCastException("MemorizingTrustManager context must be either Activity or Service!"); File dir = app.getDir(KEYSTORE_DIR, Context.MODE_PRIVATE); keyStoreFile = new File(dir + File.separator + KEYSTORE_FILE); KeyStore ks; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e) { LOGGER.log(Level.SEVERE, "getAppKeyStore()", e); appKeyStore = null; } try { ks.load(null, null); ks.load(new java.io.FileInputStream(keyStoreFile), "MTM".toCharArray()); } catch (java.io.FileNotFoundException e) { LOGGER.log(Level.INFO, "getAppKeyStore(" + keyStoreFile + ") - file does not exist"); } catch (Exception e) { LOGGER.log(Level.SEVERE, "getAppKeyStore(" + keyStoreFile + ")", e); } return ks; }
void init(Context m) { master = m; masterHandler = new Handler(m.getMainLooper()); notificationManager = (NotificationManager) master.getSystemService(Context.NOTIFICATION_SERVICE); if (m instanceof Application) { app = (Application) m; } else if (m instanceof Service) { app = ((Service) m).getApplication(); } else if (m instanceof Activity) { app = ((Activity) m).getApplication(); } else throw new ClassCastException("MemorizingTrustManager context must be either Activity or Service!"); File dir = app.getDir(KEYSTORE_DIR, Context.MODE_PRIVATE); keyStoreFile = new File(dir + File.separator + KEYSTORE_FILE); <DeepExtract> KeyStore ks; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e) { LOGGER.log(Level.SEVERE, "getAppKeyStore()", e); appKeyStore = null; } try { ks.load(null, null); ks.load(new java.io.FileInputStream(keyStoreFile), "MTM".toCharArray()); } catch (java.io.FileNotFoundException e) { LOGGER.log(Level.INFO, "getAppKeyStore(" + keyStoreFile + ") - file does not exist"); } catch (Exception e) { LOGGER.log(Level.SEVERE, "getAppKeyStore(" + keyStoreFile + ")", e); } return ks; </DeepExtract> }
simpleirc
positive
175
public static String toString(Reader in) throws IOException { StringWriter out = new StringWriter(); byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int n = 0; while (-1 != (n = in.read(buffer))) { out.write(buffer, 0, n); } return out.toString(); }
public static String toString(Reader in) throws IOException { StringWriter out = new StringWriter(); <DeepExtract> byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int n = 0; while (-1 != (n = in.read(buffer))) { out.write(buffer, 0, n); } </DeepExtract> return out.toString(); }
eclim
positive
176
private ConfigData doLoad() { if (!Files.exists(Paths.get(CONFIG_PATH)) && Files.exists(Paths.get(OLD_CONFIG_PATH))) { var config = JsonUtils.from(OLD_CONFIG_PATH, ConfigData.class); save(config); } final ConfigData config = JsonUtils.from(CONFIG_PATH, ConfigData.class); final List<ServerConfigData> sortedServers = config.getServers().stream().filter(serverConfigData -> serverConfigData.getConnectTimes() > 0).sorted(Comparator.comparingInt(ServerConfigData::getConnectTimes)).collect(Collectors.toList()); Collections.reverse(sortedServers); List<ServerConfigData> unConnectServers = config.getServers().stream().filter(serverConfigData -> serverConfigData.getConnectTimes() == 0).collect(Collectors.toList()); List<ServerConfigData> servers = new ArrayList<>(); servers.addAll(sortedServers); servers.addAll(unConnectServers); servers.forEach(s -> { if (s.getId() == null) { s.setId(UUID.randomUUID().toString()); } }); config.setServers(servers); return config; }
private ConfigData doLoad() { <DeepExtract> if (!Files.exists(Paths.get(CONFIG_PATH)) && Files.exists(Paths.get(OLD_CONFIG_PATH))) { var config = JsonUtils.from(OLD_CONFIG_PATH, ConfigData.class); save(config); } </DeepExtract> final ConfigData config = JsonUtils.from(CONFIG_PATH, ConfigData.class); final List<ServerConfigData> sortedServers = config.getServers().stream().filter(serverConfigData -> serverConfigData.getConnectTimes() > 0).sorted(Comparator.comparingInt(ServerConfigData::getConnectTimes)).collect(Collectors.toList()); Collections.reverse(sortedServers); List<ServerConfigData> unConnectServers = config.getServers().stream().filter(serverConfigData -> serverConfigData.getConnectTimes() == 0).collect(Collectors.toList()); List<ServerConfigData> servers = new ArrayList<>(); servers.addAll(sortedServers); servers.addAll(unConnectServers); servers.forEach(s -> { if (s.getId() == null) { s.setId(UUID.randomUUID().toString()); } }); config.setServers(servers); return config; }
PrettyZoo
positive
177
@Override public void render(Node node) { textContent.write('/'); Node node = node.getFirstChild(); while (node != null) { Node next = node.getNext(); context.render(node); node = next; } textContent.write('/'); }
@Override public void render(Node node) { textContent.write('/'); <DeepExtract> Node node = node.getFirstChild(); while (node != null) { Node next = node.getNext(); context.render(node); node = next; } </DeepExtract> textContent.write('/'); }
NBlog
positive
178
@Test public void testIllegalInstantDueToTimeZoneOffsetTransition() { final DateTimeZone dateTimeZone = DateTimeZone.forID("CET"); LocalDateTime localDateTime = new LocalDateTime(dateTimeZone).withYear(2011).withMonthOfYear(3).withDayOfMonth(27).withHourOfDay(2); try { DateTime myDateBroken = localDateTime.toDateTime(dateTimeZone); fail("No exception for " + localDateTime + " -> " + myDateBroken); } catch (IllegalArgumentException iae) { Log.v(TAG, "Sure enough, invalid instant due to time zone offset transition: " + localDateTime); } if (dateTimeZone.isLocalDateTimeGap(localDateTime)) { localDateTime = localDateTime.withHourOfDay(3); } DateTime myDate = localDateTime.toDateTime(dateTimeZone); Log.v(TAG, "No problem with this date: " + myDate); long millis = toMillis("2014-09-07T00:00:00+00:00"); String title = "DST"; for (int ind = -25; ind < 26; ind++) { provider.addRow(new QueryRow().setEventId(++eventId).setTitle(title + " " + ind).setBegin(millis + TimeUnit.HOURS.toMillis(ind)).setAllDay(1)); } long millis = toMillis("2015-03-29T00:00:00+00:00"); String title = "DST"; for (int ind = -25; ind < 26; ind++) { provider.addRow(new QueryRow().setEventId(++eventId).setTitle(title + " " + ind).setBegin(millis + TimeUnit.HOURS.toMillis(ind)).setAllDay(1)); } long millis = toMillis("2015-10-25T00:00:00+00:00"); String title = "DST"; for (int ind = -25; ind < 26; ind++) { provider.addRow(new QueryRow().setEventId(++eventId).setTitle(title + " " + ind).setBegin(millis + TimeUnit.HOURS.toMillis(ind)).setAllDay(1)); } long millis = toMillis("2011-03-27T00:00:00+00:00"); String title = "DST"; for (int ind = -25; ind < 26; ind++) { provider.addRow(new QueryRow().setEventId(++eventId).setTitle(title + " " + ind).setBegin(millis + TimeUnit.HOURS.toMillis(ind)).setAllDay(1)); } long millis = toMillis("1980-04-06T00:00:00+00:00"); String title = "DST"; for (int ind = -25; ind < 26; ind++) { provider.addRow(new QueryRow().setEventId(++eventId).setTitle(title + " " + ind).setBegin(millis + TimeUnit.HOURS.toMillis(ind)).setAllDay(1)); } provider.addRow(new CalendarEvent(getSettings(), provider.getContext(), provider.getWidgetId(), false).setStartDate(getSettings().clock().startOfTomorrow()).setEventSource(provider.getFirstActiveEventSource()).setTitle("This will be the only event that will be shown")); playResults(TAG); assertEquals(3, getFactory().getWidgetEntries().size()); }
@Test public void testIllegalInstantDueToTimeZoneOffsetTransition() { final DateTimeZone dateTimeZone = DateTimeZone.forID("CET"); LocalDateTime localDateTime = new LocalDateTime(dateTimeZone).withYear(2011).withMonthOfYear(3).withDayOfMonth(27).withHourOfDay(2); try { DateTime myDateBroken = localDateTime.toDateTime(dateTimeZone); fail("No exception for " + localDateTime + " -> " + myDateBroken); } catch (IllegalArgumentException iae) { Log.v(TAG, "Sure enough, invalid instant due to time zone offset transition: " + localDateTime); } if (dateTimeZone.isLocalDateTimeGap(localDateTime)) { localDateTime = localDateTime.withHourOfDay(3); } DateTime myDate = localDateTime.toDateTime(dateTimeZone); Log.v(TAG, "No problem with this date: " + myDate); long millis = toMillis("2014-09-07T00:00:00+00:00"); String title = "DST"; for (int ind = -25; ind < 26; ind++) { provider.addRow(new QueryRow().setEventId(++eventId).setTitle(title + " " + ind).setBegin(millis + TimeUnit.HOURS.toMillis(ind)).setAllDay(1)); } long millis = toMillis("2015-03-29T00:00:00+00:00"); String title = "DST"; for (int ind = -25; ind < 26; ind++) { provider.addRow(new QueryRow().setEventId(++eventId).setTitle(title + " " + ind).setBegin(millis + TimeUnit.HOURS.toMillis(ind)).setAllDay(1)); } long millis = toMillis("2015-10-25T00:00:00+00:00"); String title = "DST"; for (int ind = -25; ind < 26; ind++) { provider.addRow(new QueryRow().setEventId(++eventId).setTitle(title + " " + ind).setBegin(millis + TimeUnit.HOURS.toMillis(ind)).setAllDay(1)); } long millis = toMillis("2011-03-27T00:00:00+00:00"); String title = "DST"; for (int ind = -25; ind < 26; ind++) { provider.addRow(new QueryRow().setEventId(++eventId).setTitle(title + " " + ind).setBegin(millis + TimeUnit.HOURS.toMillis(ind)).setAllDay(1)); } <DeepExtract> long millis = toMillis("1980-04-06T00:00:00+00:00"); String title = "DST"; for (int ind = -25; ind < 26; ind++) { provider.addRow(new QueryRow().setEventId(++eventId).setTitle(title + " " + ind).setBegin(millis + TimeUnit.HOURS.toMillis(ind)).setAllDay(1)); } </DeepExtract> provider.addRow(new CalendarEvent(getSettings(), provider.getContext(), provider.getWidgetId(), false).setStartDate(getSettings().clock().startOfTomorrow()).setEventSource(provider.getFirstActiveEventSource()).setTitle("This will be the only event that will be shown")); playResults(TAG); assertEquals(3, getFactory().getWidgetEntries().size()); }
calendar-widget
positive
180
public static void main(String[] args) { Kalman2Filter filter = new Kalman2Filter(); history.add(new Sample(1[0])); float[] result = new float[] { doKalman2() }; trimSamples(); return result; history.add(new Sample(3[0])); float[] result = new float[] { doKalman2() }; trimSamples(); return result; history.add(new Sample(5[0])); float[] result = new float[] { doKalman2() }; trimSamples(); return result; history.add(new Sample(1[0])); float[] result = new float[] { doKalman2() }; trimSamples(); return result; history.add(new Sample(1[0])); float[] result = new float[] { doKalman2() }; trimSamples(); return result; history.add(new Sample(1[0])); float[] result = new float[] { doKalman2() }; trimSamples(); return result; }
public static void main(String[] args) { Kalman2Filter filter = new Kalman2Filter(); <DeepExtract> history.add(new Sample(1[0])); float[] result = new float[] { doKalman2() }; trimSamples(); return result; </DeepExtract> history.add(new Sample(3[0])); float[] result = new float[] { doKalman2() }; trimSamples(); return result; history.add(new Sample(5[0])); float[] result = new float[] { doKalman2() }; trimSamples(); return result; <DeepExtract> history.add(new Sample(1[0])); float[] result = new float[] { doKalman2() }; trimSamples(); return result; </DeepExtract> history.add(new Sample(1[0])); float[] result = new float[] { doKalman2() }; trimSamples(); return result; <DeepExtract> history.add(new Sample(1[0])); float[] result = new float[] { doKalman2() }; trimSamples(); return result; </DeepExtract> }
AVario
positive
181
public static PersonList fromQuery(Query<Person> query, int pageNum, int pageSize) { PersonList results = new PersonList(pageNum, pageSize, query.list()); this.list = query.list(); if (results.getList().size() == 0) { results.setTotalCount(0); } else { results.setTotalCount((Integer) query.getContext().getAttribute("totalCount")); } return results; }
public static PersonList fromQuery(Query<Person> query, int pageNum, int pageSize) { PersonList results = new PersonList(pageNum, pageSize, query.list()); <DeepExtract> this.list = query.list(); </DeepExtract> if (results.getList().size() == 0) { results.setTotalCount(0); } else { results.setTotalCount((Integer) query.getContext().getAttribute("totalCount")); } return results; }
anet
positive
182
@SuppressWarnings("unchecked") @Override public boolean equals(Object other) { if (!(other instanceof Map)) { return false; } Map<K, V> that = (Map<K, V>) other; if (that.size() != this.size()) { return false; } Object[] keys = _set; V[] values = _values; for (int i = keys.length; i-- > 0; ) { if (keys[i] != FREE && keys[i] != REMOVED && !new EqProcedure<K, V>(that).execute((K) keys[i], values[i])) { return false; } } return true; }
@SuppressWarnings("unchecked") @Override public boolean equals(Object other) { if (!(other instanceof Map)) { return false; } Map<K, V> that = (Map<K, V>) other; if (that.size() != this.size()) { return false; } <DeepExtract> Object[] keys = _set; V[] values = _values; for (int i = keys.length; i-- > 0; ) { if (keys[i] != FREE && keys[i] != REMOVED && !new EqProcedure<K, V>(that).execute((K) keys[i], values[i])) { return false; } } return true; </DeepExtract> }
trove
positive
183
public String getKanCan() { int offset = 9 - Solar.fromJulianDay(getMonth(1).getFirstJulianDay()).getLunar().getDayZhiIndex(); if (offset < 0) { offset += 12; } return "几姑看蚕".replaceFirst("几", LunarUtil.NUMBER[offset + 1]); }
public String getKanCan() { <DeepExtract> int offset = 9 - Solar.fromJulianDay(getMonth(1).getFirstJulianDay()).getLunar().getDayZhiIndex(); if (offset < 0) { offset += 12; } return "几姑看蚕".replaceFirst("几", LunarUtil.NUMBER[offset + 1]); </DeepExtract> }
lunar-java
positive
184
@Override public void onClick(DialogInterface dialog, int which) { int deleted = deleteSelected(); mIngredientView.drawList(); mActionMode.finish(); updateStats(); toastDeleted(deleted); }
@Override public void onClick(DialogInterface dialog, int which) { <DeepExtract> int deleted = deleteSelected(); mIngredientView.drawList(); mActionMode.finish(); updateStats(); toastDeleted(deleted); </DeepExtract> }
BrewShopApp
positive
185
public static void main16() { int[] first = { 0, -1, 2, -3, 1 }; for (int i = 0; i < (first.length - 2); i++) { for (int j = i + 1; j < (first.length - 1); j++) { for (int k = j + 1; k < first.length; k++) { if (first[i] + first[j] + first[k] == 0) System.out.println("Triplet:: " + first[i] + " " + first[j] + " " + first[k]); } } } int start, stop; Arrays.sort(first); for (int i = 0; i < (first.length - 2); i++) { start = i + 1; stop = first.length - 1; while (start < stop) { if (first[i] + first[start] + first[stop] == 0) { System.out.println("Triplet :: " + first[i] + " " + first[start] + " " + first[stop]); start += 1; stop -= 1; } else if (first[i] + first[start] + first[stop] > 0) stop -= 1; else start += 1; } } }
public static void main16() { int[] first = { 0, -1, 2, -3, 1 }; for (int i = 0; i < (first.length - 2); i++) { for (int j = i + 1; j < (first.length - 1); j++) { for (int k = j + 1; k < first.length; k++) { if (first[i] + first[j] + first[k] == 0) System.out.println("Triplet:: " + first[i] + " " + first[j] + " " + first[k]); } } } <DeepExtract> int start, stop; Arrays.sort(first); for (int i = 0; i < (first.length - 2); i++) { start = i + 1; stop = first.length - 1; while (start < stop) { if (first[i] + first[start] + first[stop] == 0) { System.out.println("Triplet :: " + first[i] + " " + first[start] + " " + first[stop]); start += 1; stop -= 1; } else if (first[i] + first[start] + first[stop] > 0) stop -= 1; else start += 1; } } </DeepExtract> }
Problem-Solving-in-Data-Structures-Algorithms-using-Java
positive
188
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { iprot.readStructBegin(); while (true) { field = iprot.readFieldBegin(); if (field.type == org.apache.thrift.protocol.TType.STOP) { break; } switch(field.id) { case 0: if (field.type == org.apache.thrift.protocol.TType.STRUCT) { this.success = new QueueResponse(); this.success.read(iprot); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); }
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { <DeepExtract> </DeepExtract> iprot.readStructBegin(); <DeepExtract> </DeepExtract> while (true) { <DeepExtract> </DeepExtract> field = iprot.readFieldBegin(); <DeepExtract> </DeepExtract> if (field.type == org.apache.thrift.protocol.TType.STOP) { <DeepExtract> </DeepExtract> break; <DeepExtract> </DeepExtract> } <DeepExtract> </DeepExtract> switch(field.id) { <DeepExtract> </DeepExtract> case 0: <DeepExtract> </DeepExtract> if (field.type == org.apache.thrift.protocol.TType.STRUCT) { <DeepExtract> </DeepExtract> this.success = new QueueResponse(); <DeepExtract> </DeepExtract> this.success.read(iprot); <DeepExtract> </DeepExtract> } else { <DeepExtract> </DeepExtract> org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); <DeepExtract> </DeepExtract> } <DeepExtract> </DeepExtract> break; <DeepExtract> </DeepExtract> default: <DeepExtract> </DeepExtract> org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); <DeepExtract> </DeepExtract> } <DeepExtract> </DeepExtract> iprot.readFieldEnd(); <DeepExtract> </DeepExtract> } <DeepExtract> </DeepExtract> iprot.readStructEnd(); <DeepExtract> </DeepExtract> }
bigqueue
positive
190
public View getView(int position, ViewGroup parent) { view = this.inflater.inflate(resource, parent, false); if (this.data.size() <= position) return view; String vault = this.data.get(position); View viewElement = view.findViewById(R.id.name); TextView tv = (TextView) viewElement; tv.setText(vault); return view; }
public View getView(int position, ViewGroup parent) { view = this.inflater.inflate(resource, parent, false); <DeepExtract> if (this.data.size() <= position) return view; String vault = this.data.get(position); View viewElement = view.findViewById(R.id.name); TextView tv = (TextView) viewElement; tv.setText(vault); return view; </DeepExtract> }
secrecy
positive
191
public static void clearJsonDB() { if (DirectoryStructureNetSNMP.fNetSNMPJSON().exists()) { PrintWriter pw = null; try { pw = new PrintWriter(DirectoryStructureNetSNMP.fNetSNMPJSON()); } catch (FileNotFoundException e) { e.printStackTrace(); } pw.print(""); pw.close(); } if (!DirectoryStructureNetSNMP.fNetSNMPJSON().exists()) { Disk.writeToDisk("{\"1.3.6\":\"dod\"}", DirectoryStructureNetSNMP.fNetSNMPJSON()); } else if (HexString.fileToByteArray(DirectoryStructureNetSNMP.fNetSNMPJSON()).length == 0) { Disk.writeToDisk("{\"1.3.6\":\"dod\"}", DirectoryStructureNetSNMP.fNetSNMPJSON()); } }
public static void clearJsonDB() { if (DirectoryStructureNetSNMP.fNetSNMPJSON().exists()) { PrintWriter pw = null; try { pw = new PrintWriter(DirectoryStructureNetSNMP.fNetSNMPJSON()); } catch (FileNotFoundException e) { e.printStackTrace(); } pw.print(""); pw.close(); } <DeepExtract> if (!DirectoryStructureNetSNMP.fNetSNMPJSON().exists()) { Disk.writeToDisk("{\"1.3.6\":\"dod\"}", DirectoryStructureNetSNMP.fNetSNMPJSON()); } else if (HexString.fileToByteArray(DirectoryStructureNetSNMP.fNetSNMPJSON()).length == 0) { Disk.writeToDisk("{\"1.3.6\":\"dod\"}", DirectoryStructureNetSNMP.fNetSNMPJSON()); } </DeepExtract> }
Oscar
positive
192
@Override public void update(float time) throws Exception { if (null != m_pCallFunc) { m_pCallFunc.method(); } }
@Override public void update(float time) throws Exception { <DeepExtract> if (null != m_pCallFunc) { m_pCallFunc.method(); } </DeepExtract> }
cocos2d-java
positive
194
public void setxBegin(float xBegin) { this.xBegin = xBegin; xCurrent = xBegin; isFirstList = true; points1.clear(); points2.clear(); }
public void setxBegin(float xBegin) { this.xBegin = xBegin; <DeepExtract> xCurrent = xBegin; isFirstList = true; points1.clear(); points2.clear(); </DeepExtract> }
university
positive
195
protected MockMvc getMockMvc(String entityClass, HttpMethod method) throws MockNotFoundException { if (customControllersMockMvc == null) return getDefaultMockMvc(); Map<HttpMethod, MockMvc> map = customControllersMockMvc.get(entityClass); if (map != null && map.containsKey(method)) { MockMvc mockMvc2 = map.get(method); if (mockMvc2 == null) { throw new MockNotFoundException(String.format("Mock Not Found for entity %s and method %s", entityClass, method.toString())); } return mockMvc2; } return this.mockMvc; }
protected MockMvc getMockMvc(String entityClass, HttpMethod method) throws MockNotFoundException { if (customControllersMockMvc == null) return getDefaultMockMvc(); Map<HttpMethod, MockMvc> map = customControllersMockMvc.get(entityClass); if (map != null && map.containsKey(method)) { MockMvc mockMvc2 = map.get(method); if (mockMvc2 == null) { throw new MockNotFoundException(String.format("Mock Not Found for entity %s and method %s", entityClass, method.toString())); } return mockMvc2; } <DeepExtract> return this.mockMvc; </DeepExtract> }
crud-rest-gen
positive
196
private static void copyHtmlResources(File parent) throws IOException { File file = new File(parent, "Benchmarks.html"); if (!file.exists()) { writeToFile(readResource("charts/" + "Benchmarks.html"), file); } File file = new File(parent, "benchmarks.js"); if (!file.exists()) { writeToFile(readResource("charts/" + "benchmarks.js"), file); } File file = new File(parent, "benchmarks.css"); if (!file.exists()) { writeToFile(readResource("charts/" + "benchmarks.css"), file); } File file = new File(parent, "parser.css"); if (!file.exists()) { writeToFile(readResource("charts/" + "parser.css"), file); } }
private static void copyHtmlResources(File parent) throws IOException { File file = new File(parent, "Benchmarks.html"); if (!file.exists()) { writeToFile(readResource("charts/" + "Benchmarks.html"), file); } File file = new File(parent, "benchmarks.js"); if (!file.exists()) { writeToFile(readResource("charts/" + "benchmarks.js"), file); } File file = new File(parent, "benchmarks.css"); if (!file.exists()) { writeToFile(readResource("charts/" + "benchmarks.css"), file); } <DeepExtract> File file = new File(parent, "parser.css"); if (!file.exists()) { writeToFile(readResource("charts/" + "parser.css"), file); } </DeepExtract> }
minimal-json
positive
197
public TextBuilder font(String family) { mSpans.put(new TypefaceSpan(family).getClass(), new TypefaceSpan(family)); return this; }
public TextBuilder font(String family) { <DeepExtract> mSpans.put(new TypefaceSpan(family).getClass(), new TypefaceSpan(family)); </DeepExtract> return this; }
rich-text-android
positive
198
public E remove() { E x = pollFirst(); if (x == null) throw new NoSuchElementException(); return x; }
public E remove() { <DeepExtract> E x = pollFirst(); if (x == null) throw new NoSuchElementException(); return x; </DeepExtract> }
Android-Universal-Image-Loader-Modify
positive
199
public static List<Float> getFloatValues(Collection<?> values, String property) { if (values == null || values.isEmpty()) { return Collections.<T>emptyList(); } List<T> result = new ArrayList<T>(values.size()); for (Object value : values) { try { String propertyValue = value.toString(); if (property != null) { propertyValue = BeanUtils.getProperty(value, property); } Object key = MethodUtils.invokeExactMethod(new Float(0f), "valueOf", propertyValue); result.add((T) key); } catch (Exception e) { logger.error(e.getMessage(), e); continue; } } return result; }
public static List<Float> getFloatValues(Collection<?> values, String property) { <DeepExtract> if (values == null || values.isEmpty()) { return Collections.<T>emptyList(); } List<T> result = new ArrayList<T>(values.size()); for (Object value : values) { try { String propertyValue = value.toString(); if (property != null) { propertyValue = BeanUtils.getProperty(value, property); } Object key = MethodUtils.invokeExactMethod(new Float(0f), "valueOf", propertyValue); result.add((T) key); } catch (Exception e) { logger.error(e.getMessage(), e); continue; } } return result; </DeepExtract> }
jweb
positive
200
@Override public void visit(CompilationUnit cu, T context) { for (String defaultType : CachedClassLoader.PRIMITIVES.keySet()) { SymbolType st = new SymbolType(CachedClassLoader.PRIMITIVES.get(defaultType)); symbolTable.pushSymbol(defaultType, ReferenceType.TYPE, st, null, actions); } for (String sdkFile : SDKFiles) { if (isClassFile(sdkFile) && !isAnonymousClass(sdkFile)) { String asClass = sdkFile.replaceAll(File.separator, "\\."); String fullName = asClass.substring(0, asClass.length() - 6); symbolTable.pushSymbol(resolveSymbolName(fullName, false, false), ReferenceType.TYPE, new SymbolType(fullName), null, actions); } } if (cu.getPackage() != null) { contextName = cu.getPackage().getName().toString(); } else { contextName = ""; } packageName = contextName; addTypes(classLoader.getPackageContents(packageName), actions, null); if (cu.getImports() != null) { for (ImportDeclaration i : cu.getImports()) { i.accept(this, context); } } if (cu.getTypes() != null) { for (TypeDeclaration typeDeclaration : cu.getTypes()) { typeDeclaration.accept(this, context); } } startingNode = null; }
@Override public void visit(CompilationUnit cu, T context) { for (String defaultType : CachedClassLoader.PRIMITIVES.keySet()) { SymbolType st = new SymbolType(CachedClassLoader.PRIMITIVES.get(defaultType)); symbolTable.pushSymbol(defaultType, ReferenceType.TYPE, st, null, actions); } for (String sdkFile : SDKFiles) { if (isClassFile(sdkFile) && !isAnonymousClass(sdkFile)) { String asClass = sdkFile.replaceAll(File.separator, "\\."); String fullName = asClass.substring(0, asClass.length() - 6); symbolTable.pushSymbol(resolveSymbolName(fullName, false, false), ReferenceType.TYPE, new SymbolType(fullName), null, actions); } } if (cu.getPackage() != null) { contextName = cu.getPackage().getName().toString(); } else { contextName = ""; } packageName = contextName; <DeepExtract> addTypes(classLoader.getPackageContents(packageName), actions, null); </DeepExtract> if (cu.getImports() != null) { for (ImportDeclaration i : cu.getImports()) { i.accept(this, context); } } if (cu.getTypes() != null) { for (TypeDeclaration typeDeclaration : cu.getTypes()) { typeDeclaration.accept(this, context); } } startingNode = null; }
javalang-compiler
positive
201
public int read(byte[] buf, int off, int len) throws TTransportException { if (readBuffer_ != null) { int got = readBuffer_.read(buf, off, len); if (got > 0) { return got; } } transport_.readAll(i32buf, 0, 4); int size = decodeFrameSize(i32buf); if (size < 0) { throw new TTransportException("Read a negative frame size (" + size + ")!"); } if (size > maxLength_) { throw new TTransportException("Frame size (" + size + ") larger than max length (" + maxLength_ + ")!"); } byte[] buff = new byte[size]; transport_.readAll(buff, 0, size); readBuffer_.reset(buff); return readBuffer_.read(buf, off, len); }
public int read(byte[] buf, int off, int len) throws TTransportException { if (readBuffer_ != null) { int got = readBuffer_.read(buf, off, len); if (got > 0) { return got; } } <DeepExtract> transport_.readAll(i32buf, 0, 4); int size = decodeFrameSize(i32buf); if (size < 0) { throw new TTransportException("Read a negative frame size (" + size + ")!"); } if (size > maxLength_) { throw new TTransportException("Frame size (" + size + ") larger than max length (" + maxLength_ + ")!"); } byte[] buff = new byte[size]; transport_.readAll(buff, 0, size); readBuffer_.reset(buff); </DeepExtract> return readBuffer_.read(buf, off, len); }
Thrift-Client-Server-Example--PHP-
positive
202
protected void scrollIntoView(WebElement element) { JavascriptExecutor jsrunner = (JavascriptExecutor) driver; logger.finer("executing script '" + "arguments[0].scrollIntoView()" + "' with params " + Arrays.asList(element)); Object result = jsrunner.executeScript("arguments[0].scrollIntoView()".toString(), element); logger.finer("executed script returned: " + result + (result == null ? "" : String.format(" (%s)", result.getClass()))); return result; }
protected void scrollIntoView(WebElement element) { <DeepExtract> JavascriptExecutor jsrunner = (JavascriptExecutor) driver; logger.finer("executing script '" + "arguments[0].scrollIntoView()" + "' with params " + Arrays.asList(element)); Object result = jsrunner.executeScript("arguments[0].scrollIntoView()".toString(), element); logger.finer("executed script returned: " + result + (result == null ? "" : String.format(" (%s)", result.getClass()))); return result; </DeepExtract> }
adf-selenium
positive
203
@Test public void configurationValidationHandling() throws Exception { Configuration configuration = getBasicConf(); configuration.setHost(null); mockMvc.perform(post("/v1/admin/config").content(json(mapping, configuration)).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest()).andExpect(jsonPath("$.code").value("400")).andExpect(jsonPath("$.reasonPhrase").value("Configuration validation error")).andExpect(jsonPath("$.details").exists()); configuration = getBasicConf(); configuration.setEventTypeIns(null); mockMvc.perform(post("/v1/admin/config").content(json(mapping, configuration)).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest()).andExpect(jsonPath("$.code").value("400")).andExpect(jsonPath("$.reasonPhrase").value("Configuration validation error")).andExpect(jsonPath("$.details").exists()); configuration = getBasicConf(); configuration.setEventTypeOuts(null); mockMvc.perform(post("/v1/admin/config").content(json(mapping, configuration)).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest()).andExpect(jsonPath("$.code").value("400")).andExpect(jsonPath("$.reasonPhrase").value("Configuration validation error")).andExpect(jsonPath("$.details").exists()); }
@Test public void configurationValidationHandling() throws Exception { Configuration configuration = getBasicConf(); configuration.setHost(null); <DeepExtract> mockMvc.perform(post("/v1/admin/config").content(json(mapping, configuration)).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest()).andExpect(jsonPath("$.code").value("400")).andExpect(jsonPath("$.reasonPhrase").value("Configuration validation error")).andExpect(jsonPath("$.details").exists()); </DeepExtract> configuration = getBasicConf(); configuration.setEventTypeIns(null); <DeepExtract> mockMvc.perform(post("/v1/admin/config").content(json(mapping, configuration)).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest()).andExpect(jsonPath("$.code").value("400")).andExpect(jsonPath("$.reasonPhrase").value("Configuration validation error")).andExpect(jsonPath("$.details").exists()); </DeepExtract> configuration = getBasicConf(); configuration.setEventTypeOuts(null); <DeepExtract> mockMvc.perform(post("/v1/admin/config").content(json(mapping, configuration)).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest()).andExpect(jsonPath("$.code").value("400")).andExpect(jsonPath("$.reasonPhrase").value("Configuration validation error")).andExpect(jsonPath("$.details").exists()); </DeepExtract> }
fiware-cepheus
positive
204
public Map[] campaignPublisherStatistics(Integer id, Date startDate) throws XmlRpcException { if (!isValidSessionId()) throw new IllegalArgumentException("Not logined to server"); return campaignService.campaignPublisherStatistics(id, startDate); }
public Map[] campaignPublisherStatistics(Integer id, Date startDate) throws XmlRpcException { <DeepExtract> if (!isValidSessionId()) throw new IllegalArgumentException("Not logined to server"); </DeepExtract> return campaignService.campaignPublisherStatistics(id, startDate); }
openx-2.8.8
positive
205
void setSelectedIndicatorColors(int... colors) { mCustomTabColorizer = null; mIndicatorColors = colors; invalidate(); }
void setSelectedIndicatorColors(int... colors) { mCustomTabColorizer = null; <DeepExtract> mIndicatorColors = colors; </DeepExtract> invalidate(); }
Akit-Reader
positive
207
@Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); mContentRect.set(mOffsetLeft, mOffsetTop, getWidth() - mOffsetRight, getHeight() - mOffsetBottom); }
@Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); <DeepExtract> mContentRect.set(mOffsetLeft, mOffsetTop, getWidth() - mOffsetRight, getHeight() - mOffsetBottom); </DeepExtract> }
MPChartLib
positive
210
public static void INIT(int role) { setRole(role); MessageCenter.getInstance().registerListener(this, MessageTable.MSG_SERVER_START); if (role == SERVER) { launchServer(); } else { launchClient(); } }
public static void INIT(int role) { <DeepExtract> setRole(role); MessageCenter.getInstance().registerListener(this, MessageTable.MSG_SERVER_START); if (role == SERVER) { launchServer(); } else { launchClient(); } </DeepExtract> }
LinkChat
positive
211
@Override public void onGfxReinit(GL10 gl, float w, float h) { LoadFromBitmap(mBitmap); }
@Override public void onGfxReinit(GL10 gl, float w, float h) { <DeepExtract> LoadFromBitmap(mBitmap); </DeepExtract> }
love-android
positive
212
public void initialize(IPreferenceStore store) { if (store == null) { store = Activator.getDefault().getPreferenceStore(); } directoryPathOfProductSourceCode = store.getString(Preference.Common.srcMainPath); directoryPathOfTestSourceCode = store.getString(Preference.Common.srcTestPath); outputFileEncoding = store.getString(Preference.Common.outputFileEncoding); lineBreakPolicy = store.getString(Preference.Common.lineBreakPolicy); useSoftTabs = store.getBoolean(Preference.Common.useSoftTabs); softTabSize = store.getInt(Preference.Common.softTabSize); isTestMethodNameArgsRequired = store.getBoolean(Preference.TestMethodGen.enabledArgs); isTestMethodNameReturnRequired = store.getBoolean(Preference.TestMethodGen.enabledReturn); isExceptionPatternRequired = store.getBoolean(Preference.TestMethodGen.enabledException); isTemplateImplementationRequired = store.getBoolean(Preference.TestMethodGen.enabledTestMethodSampleImpl); isPublicRequired = store.getBoolean(Preference.TestMethodGen.includePublic); isProtectedRequired = store.getBoolean(Preference.TestMethodGen.includeProtected); isPackageLocalRequired = store.getBoolean(Preference.TestMethodGen.includePackageLocal); isAccessorExcluded = store.getBoolean(Preference.TestMethodGen.excludesAccessors); String setting = store.getString(Preference.TestMethodGen.usingMock); return Preference.TestMethodGen.usingMockJMock2.equals(setting); String setting = store.getString(Preference.TestMethodGen.usingMock); return Preference.TestMethodGen.usingMockEasyMock.equals(setting); String setting = store.getString(Preference.TestMethodGen.usingMock); return Preference.TestMethodGen.usingMockMockito.equals(setting); String setting = store.getString(Preference.TestMethodGen.usingMock); return Preference.TestMethodGen.usingMockJMockit.equals(setting); String setting = store.getString(Preference.TestMethodGen.usingTestingPatternComments); return Preference.TestMethodGen.commentsArrangeActAssert.equals(setting); String setting = store.getString(Preference.TestMethodGen.usingTestingPatternComments); return Preference.TestMethodGen.commentsGivenWhenThen.equals(setting); String version = store.getString(Preference.TestClassGen.junitVersion); isJUnitVersion3 = version.equals(Preference.TestClassGen.junitVersion3); isJUnitVersion4 = version.equals(Preference.TestClassGen.junitVersion4); testMethodDelimiter = store.getString(Preference.TestMethodGen.delimiter); testMethodArgsPrefix = store.getString(Preference.TestMethodGen.argsPrefix); testMethodArgsDelimiter = store.getString(Preference.TestMethodGen.argsDelimiter); testMethodReturnPrefix = store.getString(Preference.TestMethodGen.returnPrefix); testMethodReturnDelimiter = store.getString(Preference.TestMethodGen.returnDelimiter); testMethodExceptionPrefix = store.getString(Preference.TestMethodGen.exceptionPrefix); testMethodExceptionDelimiter = store.getString(Preference.TestMethodGen.exceptionDelimiter); classToExtend = store.getString(Preference.TestClassGen.classToExtend); }
public void initialize(IPreferenceStore store) { if (store == null) { store = Activator.getDefault().getPreferenceStore(); } directoryPathOfProductSourceCode = store.getString(Preference.Common.srcMainPath); directoryPathOfTestSourceCode = store.getString(Preference.Common.srcTestPath); outputFileEncoding = store.getString(Preference.Common.outputFileEncoding); lineBreakPolicy = store.getString(Preference.Common.lineBreakPolicy); useSoftTabs = store.getBoolean(Preference.Common.useSoftTabs); softTabSize = store.getInt(Preference.Common.softTabSize); isTestMethodNameArgsRequired = store.getBoolean(Preference.TestMethodGen.enabledArgs); isTestMethodNameReturnRequired = store.getBoolean(Preference.TestMethodGen.enabledReturn); isExceptionPatternRequired = store.getBoolean(Preference.TestMethodGen.enabledException); isTemplateImplementationRequired = store.getBoolean(Preference.TestMethodGen.enabledTestMethodSampleImpl); isPublicRequired = store.getBoolean(Preference.TestMethodGen.includePublic); isProtectedRequired = store.getBoolean(Preference.TestMethodGen.includeProtected); isPackageLocalRequired = store.getBoolean(Preference.TestMethodGen.includePackageLocal); isAccessorExcluded = store.getBoolean(Preference.TestMethodGen.excludesAccessors); String setting = store.getString(Preference.TestMethodGen.usingMock); return Preference.TestMethodGen.usingMockJMock2.equals(setting); String setting = store.getString(Preference.TestMethodGen.usingMock); return Preference.TestMethodGen.usingMockEasyMock.equals(setting); String setting = store.getString(Preference.TestMethodGen.usingMock); return Preference.TestMethodGen.usingMockMockito.equals(setting); String setting = store.getString(Preference.TestMethodGen.usingMock); return Preference.TestMethodGen.usingMockJMockit.equals(setting); String setting = store.getString(Preference.TestMethodGen.usingTestingPatternComments); return Preference.TestMethodGen.commentsArrangeActAssert.equals(setting); <DeepExtract> String setting = store.getString(Preference.TestMethodGen.usingTestingPatternComments); return Preference.TestMethodGen.commentsGivenWhenThen.equals(setting); </DeepExtract> String version = store.getString(Preference.TestClassGen.junitVersion); isJUnitVersion3 = version.equals(Preference.TestClassGen.junitVersion3); isJUnitVersion4 = version.equals(Preference.TestClassGen.junitVersion4); testMethodDelimiter = store.getString(Preference.TestMethodGen.delimiter); testMethodArgsPrefix = store.getString(Preference.TestMethodGen.argsPrefix); testMethodArgsDelimiter = store.getString(Preference.TestMethodGen.argsDelimiter); testMethodReturnPrefix = store.getString(Preference.TestMethodGen.returnPrefix); testMethodReturnDelimiter = store.getString(Preference.TestMethodGen.returnDelimiter); testMethodExceptionPrefix = store.getString(Preference.TestMethodGen.exceptionPrefix); testMethodExceptionDelimiter = store.getString(Preference.TestMethodGen.exceptionDelimiter); classToExtend = store.getString(Preference.TestClassGen.classToExtend); }
junithelper
positive
213
public void windowOpened(java.awt.event.WindowEvent evt) { DAL d = new DAL(); d.setCentr(this); jComboBoxDateOfBirth.addItem("1990"); jComboBoxDateOfBirth.addItem("1991"); jComboBoxDateOfBirth.addItem("1992"); jComboBoxDateOfBirth.addItem("1993"); jComboBoxDateOfBirth.addItem("1994"); jComboBoxDateOfBirth.addItem("1995"); jComboBoxDateOfBirth.addItem("1996"); jComboBoxDateOfBirth.addItem("1997"); jComboBoxDateOfBirth.addItem("1998"); }
public void windowOpened(java.awt.event.WindowEvent evt) { <DeepExtract> DAL d = new DAL(); d.setCentr(this); jComboBoxDateOfBirth.addItem("1990"); jComboBoxDateOfBirth.addItem("1991"); jComboBoxDateOfBirth.addItem("1992"); jComboBoxDateOfBirth.addItem("1993"); jComboBoxDateOfBirth.addItem("1994"); jComboBoxDateOfBirth.addItem("1995"); jComboBoxDateOfBirth.addItem("1996"); jComboBoxDateOfBirth.addItem("1997"); jComboBoxDateOfBirth.addItem("1998"); </DeepExtract> }
SS17_AdvancedProgramming
positive
214
public static <T> SearchBaseResult<T> rpcFaild(int errorCode, String errMsg) { SearchBaseResult<T> searchResult = new SearchBaseResult<T>(); this.status = new Status(errorCode, errMsg, false); return searchResult; }
public static <T> SearchBaseResult<T> rpcFaild(int errorCode, String errMsg) { SearchBaseResult<T> searchResult = new SearchBaseResult<T>(); <DeepExtract> this.status = new Status(errorCode, errMsg, false); </DeepExtract> return searchResult; }
search-spring-boot-starter
positive
215
public void regenerateHeightMap() { double[][] map = HeightMapFactory.heightMap(width, height, rng.nextInt()); for (int x = 0; x < width / 8; x++) { for (int y = 0; y < height; y++) { map[x][y] = map[x][y] - 1.0 + x / ((width - 1) * 0.125); if (map[x][y] > maxPeak) { maxPeak = map[x][y]; } } } for (int x = width / 8; x < 7 * width / 8; x++) { for (int y = 0; y < height; y++) { map[x][y] = map[x][y]; if (map[x][y] > maxPeak) { maxPeak = map[x][y]; } } } for (int x = 7 * width / 8; x < width; x++) { for (int y = 0; y < height; y++) { map[x][y] = map[x][y] - 1.0 + (width - 1 - x) / ((width - 1) * 0.125); if (map[x][y] > maxPeak) { maxPeak = map[x][y]; } } } return map; }
public void regenerateHeightMap() { <DeepExtract> double[][] map = HeightMapFactory.heightMap(width, height, rng.nextInt()); for (int x = 0; x < width / 8; x++) { for (int y = 0; y < height; y++) { map[x][y] = map[x][y] - 1.0 + x / ((width - 1) * 0.125); if (map[x][y] > maxPeak) { maxPeak = map[x][y]; } } } for (int x = width / 8; x < 7 * width / 8; x++) { for (int y = 0; y < height; y++) { map[x][y] = map[x][y]; if (map[x][y] > maxPeak) { maxPeak = map[x][y]; } } } for (int x = 7 * width / 8; x < width; x++) { for (int y = 0; y < height; y++) { map[x][y] = map[x][y] - 1.0 + (width - 1 - x) / ((width - 1) * 0.125); if (map[x][y] > maxPeak) { maxPeak = map[x][y]; } } } return map; </DeepExtract> }
mapgen
positive
216
@Override public void onClick(View v) { Map currentMap = mapView.getCurrentMap(); if (currentMap == null) { new AlertDialog.Builder(this).setPositiveButton(android.R.string.ok, null).setTitle(R.string.map_view_title).setMessage(R.string.map_view_no_map_selected).create().show(); Log.w(TAG, "addNewLocation: no current map shown"); return; } progressDialog.show(); Location location = new Location(); location.setMap(currentMap); firstMeasurement = true; mLocation = location; mWifiService.forceMeasurement(); }
@Override public void onClick(View v) { <DeepExtract> Map currentMap = mapView.getCurrentMap(); if (currentMap == null) { new AlertDialog.Builder(this).setPositiveButton(android.R.string.ok, null).setTitle(R.string.map_view_title).setMessage(R.string.map_view_no_map_selected).create().show(); Log.w(TAG, "addNewLocation: no current map shown"); return; } progressDialog.show(); Location location = new Location(); location.setMap(currentMap); firstMeasurement = true; mLocation = location; mWifiService.forceMeasurement(); </DeepExtract> }
redpin
positive
217
public void offlineHbck() throws IOException, InterruptedException { if (shouldCheckHdfs() || (shouldFixHdfsOrphans() || shouldFixHdfsHoles() || shouldFixHdfsOverlaps() || shouldFixTableOrphans())) { LOG.info("Loading regioninfos HDFS"); int maxIterations = getConf().getInt("hbase.hbck.integrityrepair.iterations.max", 3); int curIter = 0; do { clearState(); restoreHdfsIntegrity(); curIter++; } while (fixes > 0 && curIter <= maxIterations); if (curIter > 2) { if (curIter == maxIterations) { LOG.warn("Exiting integrity repairs after max " + curIter + " iterations. " + "Tables integrity may not be fully repaired!"); } else { LOG.info("Successfully exiting integrity repairs after " + curIter + " iterations"); } } } clearState(); Configuration conf = getConf(); Path hbaseRoot = CommonFSUtils.getRootDir(conf); FileSystem fs = hbaseRoot.getFileSystem(conf); Map<String, Path> allFiles = getTableStoreFilePathMap(fs, hbaseRoot, new FSUtils.ReferenceFileFilter(fs), executor); for (Path path : allFiles.values()) { Path referredToFile = StoreFileInfo.getReferredToFile(path); if (fs.exists(referredToFile)) { continue; } errors.reportError(ErrorReporter.ERROR_CODE.LINGERING_REFERENCE_HFILE, "Found lingering reference file " + path); if (!shouldFixReferenceFiles()) { continue; } boolean success = false; String pathStr = path.toString(); int index = pathStr.lastIndexOf(Path.SEPARATOR_CHAR); for (int i = 0; index > 0 && i < 5; i++) { index = pathStr.lastIndexOf(Path.SEPARATOR_CHAR, index - 1); } if (index > 0) { Path rootDir = getSidelineDir(); Path dst = new Path(rootDir, pathStr.substring(index + 1)); fs.mkdirs(dst.getParent()); LOG.info("Trying to sideline reference file " + path + " to " + dst); setShouldRerun(); success = fs.rename(path, dst); debugLsr(dst); } if (!success) { LOG.error("Failed to sideline reference file " + path); } } Configuration conf = getConf(); Path hbaseRoot = CommonFSUtils.getRootDir(conf); FileSystem fs = hbaseRoot.getFileSystem(conf); Map<String, Path> allFiles = getTableStoreFilePathMap(fs, hbaseRoot, new FSUtils.HFileLinkFilter(), executor); for (Path path : allFiles.values()) { HFileLink actualLink = HFileLink.buildFromHFileLinkPattern(conf, path); if (actualLink.exists(fs)) { continue; } errors.reportError(ErrorReporter.ERROR_CODE.LINGERING_HFILELINK, "Found lingering HFileLink " + path); if (!shouldFixHFileLinks()) { continue; } setShouldRerun(); boolean success = sidelineFile(fs, hbaseRoot, path); if (!success) { LOG.error("Failed to sideline HFileLink file " + path); } Path backRefPath = FileLink.getBackReferencesDir(HFileArchiveUtil.getStoreArchivePath(conf, HFileLink.getReferencedTableName(path.getName().toString()), HFileLink.getReferencedRegionName(path.getName().toString()), path.getParent().getName()), HFileLink.getReferencedHFileName(path.getName().toString())); success = sidelineFile(fs, hbaseRoot, backRefPath); if (!success) { LOG.error("Failed to sideline HFileLink backreference file " + path); } } }
public void offlineHbck() throws IOException, InterruptedException { if (shouldCheckHdfs() || (shouldFixHdfsOrphans() || shouldFixHdfsHoles() || shouldFixHdfsOverlaps() || shouldFixTableOrphans())) { LOG.info("Loading regioninfos HDFS"); int maxIterations = getConf().getInt("hbase.hbck.integrityrepair.iterations.max", 3); int curIter = 0; do { clearState(); restoreHdfsIntegrity(); curIter++; } while (fixes > 0 && curIter <= maxIterations); if (curIter > 2) { if (curIter == maxIterations) { LOG.warn("Exiting integrity repairs after max " + curIter + " iterations. " + "Tables integrity may not be fully repaired!"); } else { LOG.info("Successfully exiting integrity repairs after " + curIter + " iterations"); } } } clearState(); Configuration conf = getConf(); Path hbaseRoot = CommonFSUtils.getRootDir(conf); FileSystem fs = hbaseRoot.getFileSystem(conf); Map<String, Path> allFiles = getTableStoreFilePathMap(fs, hbaseRoot, new FSUtils.ReferenceFileFilter(fs), executor); for (Path path : allFiles.values()) { Path referredToFile = StoreFileInfo.getReferredToFile(path); if (fs.exists(referredToFile)) { continue; } errors.reportError(ErrorReporter.ERROR_CODE.LINGERING_REFERENCE_HFILE, "Found lingering reference file " + path); if (!shouldFixReferenceFiles()) { continue; } boolean success = false; String pathStr = path.toString(); int index = pathStr.lastIndexOf(Path.SEPARATOR_CHAR); for (int i = 0; index > 0 && i < 5; i++) { index = pathStr.lastIndexOf(Path.SEPARATOR_CHAR, index - 1); } if (index > 0) { Path rootDir = getSidelineDir(); Path dst = new Path(rootDir, pathStr.substring(index + 1)); fs.mkdirs(dst.getParent()); LOG.info("Trying to sideline reference file " + path + " to " + dst); setShouldRerun(); success = fs.rename(path, dst); debugLsr(dst); } if (!success) { LOG.error("Failed to sideline reference file " + path); } } <DeepExtract> Configuration conf = getConf(); Path hbaseRoot = CommonFSUtils.getRootDir(conf); FileSystem fs = hbaseRoot.getFileSystem(conf); Map<String, Path> allFiles = getTableStoreFilePathMap(fs, hbaseRoot, new FSUtils.HFileLinkFilter(), executor); for (Path path : allFiles.values()) { HFileLink actualLink = HFileLink.buildFromHFileLinkPattern(conf, path); if (actualLink.exists(fs)) { continue; } errors.reportError(ErrorReporter.ERROR_CODE.LINGERING_HFILELINK, "Found lingering HFileLink " + path); if (!shouldFixHFileLinks()) { continue; } setShouldRerun(); boolean success = sidelineFile(fs, hbaseRoot, path); if (!success) { LOG.error("Failed to sideline HFileLink file " + path); } Path backRefPath = FileLink.getBackReferencesDir(HFileArchiveUtil.getStoreArchivePath(conf, HFileLink.getReferencedTableName(path.getName().toString()), HFileLink.getReferencedRegionName(path.getName().toString()), path.getParent().getName()), HFileLink.getReferencedHFileName(path.getName().toString())); success = sidelineFile(fs, hbaseRoot, backRefPath); if (!success) { LOG.error("Failed to sideline HFileLink backreference file " + path); } } </DeepExtract> }
hbase-operator-tools
positive
218
private void ensureCanStoreNewEdgeLabel(int newMaxEdgeLabelId) { int targetSize = newMaxEdgeLabelId + 1; T[] returnArray; if (edgeProperties == null) { returnArray = (T[]) new Object[Math.max(targetSize, INITIAL_ARRAY_SIZE)]; } else if (edgeProperties.length < targetSize) { returnArray = Arrays.copyOf(edgeProperties, getSizeWithPaddingWithoutOverflow(targetSize, edgeProperties.length)); } else { returnArray = edgeProperties; } return returnArray; }
private void ensureCanStoreNewEdgeLabel(int newMaxEdgeLabelId) { <DeepExtract> int targetSize = newMaxEdgeLabelId + 1; T[] returnArray; if (edgeProperties == null) { returnArray = (T[]) new Object[Math.max(targetSize, INITIAL_ARRAY_SIZE)]; } else if (edgeProperties.length < targetSize) { returnArray = Arrays.copyOf(edgeProperties, getSizeWithPaddingWithoutOverflow(targetSize, edgeProperties.length)); } else { returnArray = edgeProperties; } return returnArray; </DeepExtract> }
fractal
positive
219
private void updateRaw(String sql) throws SQLException { try { con.commit(); } catch (SQLException e) { ExceptionMan.handle(e); } try { con.setAutoCommit(true); } catch (SQLException e) { System.err.println("Failed to set AutoCommit to " + true); System.err.println(e.getMessage()); } Statement stmt = con.createStatement(); currentlyRunningQuery = stmt; stmt.executeUpdate(sql); try { if (con != null) { UIMan.verbose(1000, "------------------- Close a DB " + this); con.close(); con = null; } } catch (SQLException e) { ExceptionMan.handle(e); } currentlyRunningQuery = null; }
private void updateRaw(String sql) throws SQLException { try { con.commit(); } catch (SQLException e) { ExceptionMan.handle(e); } try { con.setAutoCommit(true); } catch (SQLException e) { System.err.println("Failed to set AutoCommit to " + true); System.err.println(e.getMessage()); } Statement stmt = con.createStatement(); currentlyRunningQuery = stmt; stmt.executeUpdate(sql); <DeepExtract> try { if (con != null) { UIMan.verbose(1000, "------------------- Close a DB " + this); con.close(); con = null; } } catch (SQLException e) { ExceptionMan.handle(e); } </DeepExtract> currentlyRunningQuery = null; }
tuffy
positive
220
@Override protected TEntity toElement(final FieldValueLookup<TEntity> row) { TKey id = row.getValue(keyField); return entityCache.get(id, () -> entityType.newInstance(row)); }
@Override protected TEntity toElement(final FieldValueLookup<TEntity> row) { <DeepExtract> TKey id = row.getValue(keyField); return entityCache.get(id, () -> entityType.newInstance(row)); </DeepExtract> }
slimrepo
positive
221
public Criteria andIdLessThan(Integer value) { if (value == null) { throw new RuntimeException("Value for " + "id" + " cannot be null"); } criteria.add(new Criterion("id <", value)); return (Criteria) this; }
public Criteria andIdLessThan(Integer value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "id" + " cannot be null"); } criteria.add(new Criterion("id <", value)); </DeepExtract> return (Criteria) this; }
yurencloud-public
positive
222
public Query createNativeQuery(String queryString, Class resultClass) { if (closed) { throw new IllegalStateException(Localiser.msg("EM.IsClosed")); } try { String nativeQueryLanguage = ec.getStoreManager().getNativeQueryLanguage(); if (nativeQueryLanguage == null) { throw new IllegalArgumentException("This datastore does not support 'native' queries"); } org.datanucleus.store.query.Query internalQuery = ec.getStoreManager().newQuery(nativeQueryLanguage, ec, queryString); if (resultClass != null) { if (ec.getApiAdapter().isPersistable(resultClass)) { internalQuery.setCandidateClass(resultClass); } else { internalQuery.setResultClass(resultClass); } } return new JPAQuery(this, internalQuery, nativeQueryLanguage); } catch (NucleusException ne) { throw new IllegalArgumentException(ne.getMessage(), ne); } }
public Query createNativeQuery(String queryString, Class resultClass) { <DeepExtract> if (closed) { throw new IllegalStateException(Localiser.msg("EM.IsClosed")); } </DeepExtract> try { String nativeQueryLanguage = ec.getStoreManager().getNativeQueryLanguage(); if (nativeQueryLanguage == null) { throw new IllegalArgumentException("This datastore does not support 'native' queries"); } org.datanucleus.store.query.Query internalQuery = ec.getStoreManager().newQuery(nativeQueryLanguage, ec, queryString); if (resultClass != null) { if (ec.getApiAdapter().isPersistable(resultClass)) { internalQuery.setCandidateClass(resultClass); } else { internalQuery.setResultClass(resultClass); } } return new JPAQuery(this, internalQuery, nativeQueryLanguage); } catch (NucleusException ne) { throw new IllegalArgumentException(ne.getMessage(), ne); } }
datanucleus-api-jpa
positive
223
protected final void setHeaderScroll(int value) { if (DEBUG) { Log.d(LOG_TAG, "setHeaderScroll: " + value); } int maximumPullScroll; switch(getPullToRefreshScrollDirection()) { case HORIZONTAL: maximumPullScroll = Math.round(getWidth() / FRICTION); case VERTICAL: default: maximumPullScroll = Math.round(getHeight() / FRICTION); } value = Math.min(maximumPullScroll, Math.max(-maximumPullScroll, value)); if (mLayoutVisibilityChangesEnabled) { if (value < 0) { mHeaderLayout.setVisibility(View.VISIBLE); } else if (value > 0) { mFooterLayout.setVisibility(View.VISIBLE); } else { mHeaderLayout.setVisibility(View.INVISIBLE); mFooterLayout.setVisibility(View.INVISIBLE); } } if (USE_HW_LAYERS) { ViewCompat.setLayerType(mRefreshableViewWrapper, value != 0 ? View.LAYER_TYPE_HARDWARE : View.LAYER_TYPE_NONE); } switch(getPullToRefreshScrollDirection()) { case VERTICAL: scrollTo(0, value); break; case HORIZONTAL: scrollTo(value, 0); break; } }
protected final void setHeaderScroll(int value) { if (DEBUG) { Log.d(LOG_TAG, "setHeaderScroll: " + value); } <DeepExtract> int maximumPullScroll; switch(getPullToRefreshScrollDirection()) { case HORIZONTAL: maximumPullScroll = Math.round(getWidth() / FRICTION); case VERTICAL: default: maximumPullScroll = Math.round(getHeight() / FRICTION); } </DeepExtract> value = Math.min(maximumPullScroll, Math.max(-maximumPullScroll, value)); if (mLayoutVisibilityChangesEnabled) { if (value < 0) { mHeaderLayout.setVisibility(View.VISIBLE); } else if (value > 0) { mFooterLayout.setVisibility(View.VISIBLE); } else { mHeaderLayout.setVisibility(View.INVISIBLE); mFooterLayout.setVisibility(View.INVISIBLE); } } if (USE_HW_LAYERS) { ViewCompat.setLayerType(mRefreshableViewWrapper, value != 0 ? View.LAYER_TYPE_HARDWARE : View.LAYER_TYPE_NONE); } switch(getPullToRefreshScrollDirection()) { case VERTICAL: scrollTo(0, value); break; case HORIZONTAL: scrollTo(value, 0); break; } }
GotyeSDK-Android
positive
224
void RandomRead() { int N = 500; Random write_rnd = new Random(0); for (int i = 0; i < N; i++) { Write(RandomSkewedString(i, write_rnd)); } Random read_rnd = new Random(0); for (int i = 0; i < N; i++) { ASSERT_EQ(RandomSkewedString(i, read_rnd), Read()); } if ("EOF".compareTo(Read()) != 0) { System.out.println("EOF" + ", " + Read()); } else { } }
void RandomRead() { int N = 500; Random write_rnd = new Random(0); for (int i = 0; i < N; i++) { Write(RandomSkewedString(i, write_rnd)); } Random read_rnd = new Random(0); for (int i = 0; i < N; i++) { ASSERT_EQ(RandomSkewedString(i, read_rnd), Read()); } <DeepExtract> if ("EOF".compareTo(Read()) != 0) { System.out.println("EOF" + ", " + Read()); } else { } </DeepExtract> }
leveldb-java
positive
225
@Override public void threadStarted() { try { JMeterContext context = this.getThreadContext(); if (context != null && context.getVariables() != null) { JMeterVariables jMeterVariables = context.getVariables(); Class<JMeterVariables> cls = JMeterVariables.class; Field variablesField = cls.getDeclaredField("variables"); variablesField.setAccessible(true); Object obj = variablesField.get(jMeterVariables); synchronized (obj) { if (obj instanceof Map) { Map variables = (Map) obj; if (!(variables instanceof ConcurrentHashMap)) { variablesField.set(jMeterVariables, new ConcurrentHashMap(variables)); } } else { log.warn("Unexpected variables map type " + obj.getClass().getName()); } } } } catch (Throwable ex) { log.warn("Cannot change variables map ", ex); } if (getLimitMaxThreadNumber()) { log.info("Starting up to {} threads", getMaxThreadNumber()); executorService = Executors.newFixedThreadPool(getMaxThreadNumber(), new ParallelThreadFactory(this.getName())); } else { executorService = Executors.newCachedThreadPool(new ParallelThreadFactory(this.getName())); } threadGroup = new DummyThreadGroup(); try { StandardJMeterEngine engine = JMeterContextService.getContext().getEngine(); Field groupsField = StandardJMeterEngine.class.getDeclaredField("groups"); groupsField.setAccessible(true); List<AbstractThreadGroup> groups = (List<AbstractThreadGroup>) groupsField.get(engine); groups.add(threadGroup); } catch (ReflectiveOperationException ex) { log.warn("Can not add DummyThreadGroup to engine", ex); } }
@Override public void threadStarted() { try { JMeterContext context = this.getThreadContext(); if (context != null && context.getVariables() != null) { JMeterVariables jMeterVariables = context.getVariables(); Class<JMeterVariables> cls = JMeterVariables.class; Field variablesField = cls.getDeclaredField("variables"); variablesField.setAccessible(true); Object obj = variablesField.get(jMeterVariables); synchronized (obj) { if (obj instanceof Map) { Map variables = (Map) obj; if (!(variables instanceof ConcurrentHashMap)) { variablesField.set(jMeterVariables, new ConcurrentHashMap(variables)); } } else { log.warn("Unexpected variables map type " + obj.getClass().getName()); } } } } catch (Throwable ex) { log.warn("Cannot change variables map ", ex); } if (getLimitMaxThreadNumber()) { log.info("Starting up to {} threads", getMaxThreadNumber()); executorService = Executors.newFixedThreadPool(getMaxThreadNumber(), new ParallelThreadFactory(this.getName())); } else { executorService = Executors.newCachedThreadPool(new ParallelThreadFactory(this.getName())); } threadGroup = new DummyThreadGroup(); <DeepExtract> try { StandardJMeterEngine engine = JMeterContextService.getContext().getEngine(); Field groupsField = StandardJMeterEngine.class.getDeclaredField("groups"); groupsField.setAccessible(true); List<AbstractThreadGroup> groups = (List<AbstractThreadGroup>) groupsField.get(engine); groups.add(threadGroup); } catch (ReflectiveOperationException ex) { log.warn("Can not add DummyThreadGroup to engine", ex); } </DeepExtract> }
jmeter-bzm-plugins
positive
226
public int getOneTransfer(int usersId, int money) { Integer percent = findUsers(usersId).getOneTransfer(); if (percent == null || Math.abs(percent) > 10000) { percent = findSys().getOneTransfer(); } if (percent == null || Math.abs(percent) >= 10000 || percent == 0) { return 0; } int value = (int) (money * percent * 0.0001); if (value == 0) { return 0; } return value; }
public int getOneTransfer(int usersId, int money) { Integer percent = findUsers(usersId).getOneTransfer(); if (percent == null || Math.abs(percent) > 10000) { percent = findSys().getOneTransfer(); } <DeepExtract> if (percent == null || Math.abs(percent) >= 10000 || percent == 0) { return 0; } int value = (int) (money * percent * 0.0001); if (value == 0) { return 0; } return value; </DeepExtract> }
ccshop
positive
227
@Override public U64 readFrom(ByteBuf bb) throws OFParseError { if (bb.readLong() == ZERO_VAL) return ZERO; return new U64(bb.readLong()); }
@Override public U64 readFrom(ByteBuf bb) throws OFParseError { <DeepExtract> if (bb.readLong() == ZERO_VAL) return ZERO; return new U64(bb.readLong()); </DeepExtract> }
loxigen
positive
228
@Override public void visit(ListItemNode lin) { for (Node child : lin.getChildren()) { child.accept(this); } }
@Override public void visit(ListItemNode lin) { <DeepExtract> for (Node child : lin.getChildren()) { child.accept(this); } </DeepExtract> }
maven-confluence-plugin
positive
229
public String createConstants(final String typeName, ExprNodeConstantDesc[] constantDesc) { if (constantDesc == null) { return StringUtil.EMPTY_STRING; } List<String> constants = new ArrayList<>(); for (ExprNodeConstantDesc s : constantDesc) { constants.add(createConstantString(typeName, String.valueOf(s.getValue()))); } return String.join(this.delimiter, constants); }
public String createConstants(final String typeName, ExprNodeConstantDesc[] constantDesc) { if (constantDesc == null) { return StringUtil.EMPTY_STRING; } List<String> constants = new ArrayList<>(); for (ExprNodeConstantDesc s : constantDesc) { constants.add(createConstantString(typeName, String.valueOf(s.getValue()))); } <DeepExtract> return String.join(this.delimiter, constants); </DeepExtract> }
phoenix-connectors
positive
230
public static double hypot(double x, double y) { if (USE_JDK_MATH) { return STRICT_MATH ? StrictMath.hypot(x, y) : Math.hypot(x, y); } if (USE_JDK_MATH) { x = Math.abs(x); } return NumbersUtils.abs(x); if (USE_JDK_MATH) { y = Math.abs(y); } return NumbersUtils.abs(y); if (y < x) { double a = x; x = y; y = a; } else if (!(y >= x)) { if ((x == Double.POSITIVE_INFINITY) || (y == Double.POSITIVE_INFINITY)) { return Double.POSITIVE_INFINITY; } else { return Double.NaN; } } if (y - x == y) { return y; } else { double factor; if (x > TWO_POW_450) { x *= TWO_POW_N750; y *= TWO_POW_N750; factor = TWO_POW_750; } else if (y < TWO_POW_N450) { x *= TWO_POW_750; y *= TWO_POW_750; factor = TWO_POW_N750; } else { factor = 1.0; } return factor * FastMath.sqrt(x * x + y * y); } }
public static double hypot(double x, double y) { if (USE_JDK_MATH) { return STRICT_MATH ? StrictMath.hypot(x, y) : Math.hypot(x, y); } if (USE_JDK_MATH) { x = Math.abs(x); } return NumbersUtils.abs(x); <DeepExtract> if (USE_JDK_MATH) { y = Math.abs(y); } return NumbersUtils.abs(y); </DeepExtract> if (y < x) { double a = x; x = y; y = a; } else if (!(y >= x)) { if ((x == Double.POSITIVE_INFINITY) || (y == Double.POSITIVE_INFINITY)) { return Double.POSITIVE_INFINITY; } else { return Double.NaN; } } if (y - x == y) { return y; } else { double factor; if (x > TWO_POW_450) { x *= TWO_POW_N750; y *= TWO_POW_N750; factor = TWO_POW_750; } else if (y < TWO_POW_N450) { x *= TWO_POW_750; y *= TWO_POW_750; factor = TWO_POW_N750; } else { factor = 1.0; } return factor * FastMath.sqrt(x * x + y * y); } }
jmathplot
positive
232
@Override public SpringSessionAttributesRecord value2(String value) { set(1, value); return this; }
@Override public SpringSessionAttributesRecord value2(String value) { <DeepExtract> set(1, value); </DeepExtract> return this; }
openvsx
positive
233