method
stringlengths
13
441k
clean_method
stringlengths
7
313k
doc
stringlengths
17
17.3k
comment
stringlengths
3
1.42k
method_name
stringlengths
1
273
extra
dict
imports
list
imports_info
stringlengths
19
34.8k
cluster_imports_info
stringlengths
15
3.66k
libraries
list
libraries_info
stringlengths
6
661
id
int64
0
2.92M
@Test public void contains() { TestCase.assertTrue(tree.contains(9)); TestCase.assertFalse(tree.contains(14)); BinarySearchTree<Integer>.Node node = tree.get(-3); TestCase.assertTrue(tree.contains(node)); node = tree.new Node(-3); TestCase.assertFalse(tree.contains(node)); }
void function() { TestCase.assertTrue(tree.contains(9)); TestCase.assertFalse(tree.contains(14)); BinarySearchTree<Integer>.Node node = tree.get(-3); TestCase.assertTrue(tree.contains(node)); node = tree.new Node(-3); TestCase.assertFalse(tree.contains(node)); }
/** * Tests the contains method. */
Tests the contains method
contains
{ "repo_name": "satishbabusee/dyn4j", "path": "junit/org/dyn4j/BalancedBinarySearchTreeTest.java", "license": "bsd-3-clause", "size": 8526 }
[ "junit.framework.TestCase", "org.dyn4j.BinarySearchTree" ]
import junit.framework.TestCase; import org.dyn4j.BinarySearchTree;
import junit.framework.*; import org.dyn4j.*;
[ "junit.framework", "org.dyn4j" ]
junit.framework; org.dyn4j;
1,180,373
@Test @Feature({"NFCTest"}) public void testNFCNotSupported() { doReturn(null).when(mNfcManager).getDefaultAdapter(); TestNfcImpl nfc = new TestNfcImpl(mContext, mDelegate); mDelegate.invokeCallback(); WatchResponse mockCallback = mock(WatchResponse.class); nfc.watch(mNextWatchId, mockCallback); verify(mockCallback).call(mErrorCaptor.capture()); assertEquals(NdefErrorType.NOT_SUPPORTED, mErrorCaptor.getValue().errorType); }
@Feature({STR}) void function() { doReturn(null).when(mNfcManager).getDefaultAdapter(); TestNfcImpl nfc = new TestNfcImpl(mContext, mDelegate); mDelegate.invokeCallback(); WatchResponse mockCallback = mock(WatchResponse.class); nfc.watch(mNextWatchId, mockCallback); verify(mockCallback).call(mErrorCaptor.capture()); assertEquals(NdefErrorType.NOT_SUPPORTED, mErrorCaptor.getValue().errorType); }
/** * Test that error with type NOT_SUPPORTED is returned if NFC is not supported. */
Test that error with type NOT_SUPPORTED is returned if NFC is not supported
testNFCNotSupported
{ "repo_name": "nwjs/chromium.src", "path": "services/device/nfc/android/junit/src/org/chromium/device/nfc/NFCTest.java", "license": "bsd-3-clause", "size": 85297 }
[ "org.chromium.base.test.util.Feature", "org.chromium.device.mojom.NdefErrorType", "org.chromium.device.mojom.Nfc", "org.junit.Assert", "org.mockito.Mockito" ]
import org.chromium.base.test.util.Feature; import org.chromium.device.mojom.NdefErrorType; import org.chromium.device.mojom.Nfc; import org.junit.Assert; import org.mockito.Mockito;
import org.chromium.base.test.util.*; import org.chromium.device.mojom.*; import org.junit.*; import org.mockito.*;
[ "org.chromium.base", "org.chromium.device", "org.junit", "org.mockito" ]
org.chromium.base; org.chromium.device; org.junit; org.mockito;
2,011,000
protected boolean updateSelection(IStructuredSelection selection) { return true; }
boolean function(IStructuredSelection selection) { return true; }
/** * Updates this action in response to the given selection. * <p> * The <code>BaseSelectionListenerAction</code> implementation of this method * returns <code>true</code>. Subclasses may extend to react to selection * changes; however, if the super method returns <code>false</code>, the * overriding method must also return <code>false</code>. * </p> * * @param selection the new selection * @return <code>true</code> if the action should be enabled for this selection, * and <code>false</code> otherwise */
Updates this action in response to the given selection. The <code>BaseSelectionListenerAction</code> implementation of this method returns <code>true</code>. Subclasses may extend to react to selection changes; however, if the super method returns <code>false</code>, the overriding method must also return <code>false</code>.
updateSelection
{ "repo_name": "gama-platform/gama.cloud", "path": "cict.gama.web.wrapper/src/org/eclipse/ui/actions/BaseSelectionListenerAction.java", "license": "agpl-3.0", "size": 6572 }
[ "org.eclipse.jface.viewers.IStructuredSelection" ]
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.*;
[ "org.eclipse.jface" ]
org.eclipse.jface;
2,372,568
public double getDomainLowerBound(boolean includeInterval) { double result = Double.NaN; Range r = getDomainBounds(includeInterval); if (r != null) { result = r.getLowerBound(); } return result; }
double function(boolean includeInterval) { double result = Double.NaN; Range r = getDomainBounds(includeInterval); if (r != null) { result = r.getLowerBound(); } return result; }
/** * Returns the minimum x-value in the dataset. * * @param includeInterval a flag that determines whether or not the * x-interval is taken into account. * * @return The minimum value. */
Returns the minimum x-value in the dataset
getDomainLowerBound
{ "repo_name": "djun100/afreechart", "path": "src/org/afree/data/xy/IntervalXYDelegate.java", "license": "lgpl-3.0", "size": 15274 }
[ "org.afree.data.Range" ]
import org.afree.data.Range;
import org.afree.data.*;
[ "org.afree.data" ]
org.afree.data;
2,569,037
public void assertMappingOnMaster(final String index, final String type, final String... fieldNames) throws Exception { GetMappingsResponse response = client().admin().indices().prepareGetMappings(index).setTypes(type).get(); ImmutableOpenMap<String, MappingMetaData> mappings = response.getMappings().get(index); assertThat(mappings, notNullValue()); MappingMetaData mappingMetaData = mappings.get(type); assertThat(mappingMetaData, notNullValue()); Map<String, Object> mappingSource = mappingMetaData.getSourceAsMap(); assertFalse(mappingSource.isEmpty()); assertTrue(mappingSource.containsKey("properties")); for (String fieldName : fieldNames) { Map<String, Object> mappingProperties = (Map<String, Object>) mappingSource.get("properties"); if (fieldName.indexOf('.') != -1) { fieldName = fieldName.replace(".", ".properties."); } assertThat("field " + fieldName + " doesn't exists in mapping " + mappingMetaData.source().string(), XContentMapValues.extractValue(fieldName, mappingProperties), notNullValue()); } }
void function(final String index, final String type, final String... fieldNames) throws Exception { GetMappingsResponse response = client().admin().indices().prepareGetMappings(index).setTypes(type).get(); ImmutableOpenMap<String, MappingMetaData> mappings = response.getMappings().get(index); assertThat(mappings, notNullValue()); MappingMetaData mappingMetaData = mappings.get(type); assertThat(mappingMetaData, notNullValue()); Map<String, Object> mappingSource = mappingMetaData.getSourceAsMap(); assertFalse(mappingSource.isEmpty()); assertTrue(mappingSource.containsKey(STR)); for (String fieldName : fieldNames) { Map<String, Object> mappingProperties = (Map<String, Object>) mappingSource.get(STR); if (fieldName.indexOf('.') != -1) { fieldName = fieldName.replace(".", STR); } assertThat(STR + fieldName + STR + mappingMetaData.source().string(), XContentMapValues.extractValue(fieldName, mappingProperties), notNullValue()); } }
/** * Waits for the given mapping type to exists on the master node. */
Waits for the given mapping type to exists on the master node
assertMappingOnMaster
{ "repo_name": "strahanjen/strahanjen.github.io", "path": "elasticsearch-master/test/framework/src/main/java/org/elasticsearch/test/ESIntegTestCase.java", "license": "bsd-3-clause", "size": 100875 }
[ "java.util.Map", "org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse", "org.elasticsearch.cluster.metadata.MappingMetaData", "org.elasticsearch.common.collect.ImmutableOpenMap", "org.elasticsearch.common.xcontent.support.XContentMapValues", "org.hamcrest.Matchers" ]
import java.util.Map; import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse; import org.elasticsearch.cluster.metadata.MappingMetaData; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.hamcrest.Matchers;
import java.util.*; import org.elasticsearch.action.admin.indices.mapping.get.*; import org.elasticsearch.cluster.metadata.*; import org.elasticsearch.common.collect.*; import org.elasticsearch.common.xcontent.support.*; import org.hamcrest.*;
[ "java.util", "org.elasticsearch.action", "org.elasticsearch.cluster", "org.elasticsearch.common", "org.hamcrest" ]
java.util; org.elasticsearch.action; org.elasticsearch.cluster; org.elasticsearch.common; org.hamcrest;
1,692,461
private String invokeGitCommand(final String... args) throws Exception { final ArrayList<String> commandPlusArguments = new ArrayList<>(args.length + 1); final String osName = System.getProperty("os.name"); if ((osName != null) && osName.toLowerCase().contains("windows")) { commandPlusArguments.add("git.exe"); } else { if (new File("/usr/bin/git").exists()) { commandPlusArguments.add("/usr/bin/git"); } else if (new File("/bin/git").exists()) { commandPlusArguments.add("/bin/git"); } else if (new File("/usr/local/bin/git").exists()) { commandPlusArguments.add("/usr/local/bin/git"); } else { commandPlusArguments.add("git"); } } commandPlusArguments.addAll(Arrays.asList(args)); final ProcessBuilder processBuilder = new ProcessBuilder(commandPlusArguments); processBuilder.directory(baseDir); processBuilder.redirectOutput(ProcessBuilder.Redirect.PIPE); processBuilder.redirectErrorStream(true); System.out.println("Invoking command " + commandPlusArguments); final Process gitProcess = processBuilder.start(); try { final BufferedReader outputReader = new BufferedReader( new InputStreamReader(gitProcess.getInputStream())); final ArrayList<String> outputLines = new ArrayList<>(10); final long stopWaitingTime = System.currentTimeMillis() + 30_000L; while (true) { if (System.currentTimeMillis() > stopWaitingTime) { throw new BuildException("ERROR: Command " + commandPlusArguments + " did not complete after 30 seconds."); } while (outputReader.ready() && (System.currentTimeMillis() <= stopWaitingTime)) { final String line = outputReader.readLine(); if (line == null) { break; } outputLines.add(line); } final int exitCode; try { exitCode = gitProcess.exitValue(); } catch (final Exception e) { Thread.sleep(10L); continue; } if (exitCode == 0) { switch (outputLines.size()) { case 0: throw new BuildException("ERROR: Running command " + commandPlusArguments + " completed with exit code zero " + "but no output. Exactly one line of output was expected."); case 1: return outputLines.get(0); default: throw new BuildException("ERROR: Running command " + commandPlusArguments + " completed with exit code zero " + "but multiple lines of output when exactly one output " + "line was expected. The output lines were: " + outputLines); } } } } finally { gitProcess.destroy(); } }
String function(final String... args) throws Exception { final ArrayList<String> commandPlusArguments = new ArrayList<>(args.length + 1); final String osName = System.getProperty(STR); if ((osName != null) && osName.toLowerCase().contains(STR)) { commandPlusArguments.add(STR); } else { if (new File(STR).exists()) { commandPlusArguments.add(STR); } else if (new File(STR).exists()) { commandPlusArguments.add(STR); } else if (new File(STR).exists()) { commandPlusArguments.add(STR); } else { commandPlusArguments.add("git"); } } commandPlusArguments.addAll(Arrays.asList(args)); final ProcessBuilder processBuilder = new ProcessBuilder(commandPlusArguments); processBuilder.directory(baseDir); processBuilder.redirectOutput(ProcessBuilder.Redirect.PIPE); processBuilder.redirectErrorStream(true); System.out.println(STR + commandPlusArguments); final Process gitProcess = processBuilder.start(); try { final BufferedReader outputReader = new BufferedReader( new InputStreamReader(gitProcess.getInputStream())); final ArrayList<String> outputLines = new ArrayList<>(10); final long stopWaitingTime = System.currentTimeMillis() + 30_000L; while (true) { if (System.currentTimeMillis() > stopWaitingTime) { throw new BuildException(STR + commandPlusArguments + STR); } while (outputReader.ready() && (System.currentTimeMillis() <= stopWaitingTime)) { final String line = outputReader.readLine(); if (line == null) { break; } outputLines.add(line); } final int exitCode; try { exitCode = gitProcess.exitValue(); } catch (final Exception e) { Thread.sleep(10L); continue; } if (exitCode == 0) { switch (outputLines.size()) { case 0: throw new BuildException(STR + commandPlusArguments + STR + STR); case 1: return outputLines.get(0); default: throw new BuildException(STR + commandPlusArguments + STR + STR + STR + outputLines); } } } } finally { gitProcess.destroy(); } }
/** * Invokes the git command, if the command succeeds and produces a single line * of output, returns that line. * * @param args The command-line arguments to provide to the git command. * * @return The single line of output (without any line breaks) produced by * the git command. * * @throws Exception If a problem is encountered while trying to run the * git command, if the git command does not exit cleanly, * or if it does not produce exactly one line of output. */
Invokes the git command, if the command succeeds and produces a single line of output, returns that line
invokeGitCommand
{ "repo_name": "UnboundID/ldapsdk", "path": "build-src/repositoryinfo/com/unboundid/buildtools/repositoryinfo/RepositoryInfo.java", "license": "gpl-2.0", "size": 26071 }
[ "java.io.BufferedReader", "java.io.File", "java.io.InputStreamReader", "java.util.ArrayList", "java.util.Arrays", "org.apache.tools.ant.BuildException" ]
import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import org.apache.tools.ant.BuildException;
import java.io.*; import java.util.*; import org.apache.tools.ant.*;
[ "java.io", "java.util", "org.apache.tools" ]
java.io; java.util; org.apache.tools;
2,813,076
@Override protected final void closeNoLock(String reason) { if (isClosed.compareAndSet(false, true)) { assert rwl.isWriteLockedByCurrentThread() || failEngineLock.isHeldByCurrentThread() : "Either the write lock must be held or the engine must be currently be failing itself"; try { this.versionMap.clear(); try { IOUtils.close(searcherManager); } catch (Throwable t) { logger.warn("Failed to close SearcherManager", t); } try { IOUtils.close(translog); } catch (Throwable t) { logger.warn("Failed to close translog", t); } // no need to commit in this case!, we snapshot before we close the shard, so translog and all sync'ed logger.trace("rollback indexWriter"); try { indexWriter.rollback(); } catch (AlreadyClosedException e) { // ignore } logger.trace("rollback indexWriter done"); } catch (Throwable e) { logger.warn("failed to rollback writer on close", e); } finally { store.decRef(); logger.debug("engine closed [{}]", reason); } } }
final void function(String reason) { if (isClosed.compareAndSet(false, true)) { assert rwl.isWriteLockedByCurrentThread() failEngineLock.isHeldByCurrentThread() : STR; try { this.versionMap.clear(); try { IOUtils.close(searcherManager); } catch (Throwable t) { logger.warn(STR, t); } try { IOUtils.close(translog); } catch (Throwable t) { logger.warn(STR, t); } logger.trace(STR); try { indexWriter.rollback(); } catch (AlreadyClosedException e) { } logger.trace(STR); } catch (Throwable e) { logger.warn(STR, e); } finally { store.decRef(); logger.debug(STR, reason); } } }
/** * Closes the engine without acquiring the write lock. This should only be * called while the write lock is hold or in a disaster condition ie. if the engine * is failed. */
Closes the engine without acquiring the write lock. This should only be called while the write lock is hold or in a disaster condition ie. if the engine is failed
closeNoLock
{ "repo_name": "queirozfcom/elasticsearch", "path": "core/src/main/java/org/elasticsearch/index/engine/InternalEngine.java", "license": "apache-2.0", "size": 58809 }
[ "org.apache.lucene.store.AlreadyClosedException", "org.apache.lucene.util.IOUtils" ]
import org.apache.lucene.store.AlreadyClosedException; import org.apache.lucene.util.IOUtils;
import org.apache.lucene.store.*; import org.apache.lucene.util.*;
[ "org.apache.lucene" ]
org.apache.lucene;
2,530,934
public void enlargeSelectionOnDomain(double x, double y, MouseEvent selectionEvent) { Plot p = this.chart.getPlot(); if (p instanceof XYPlot) { XYPlot plot = (XYPlot) p; Selection selectionObject = new Selection(); for (int i = 0; i < plot.getDomainAxisCount(); i++) { ValueAxis domain = plot.getDomainAxis(i); double zoomFactor = getZoomOutFactor(); shrinkSelectionXAxis(x, y, selectionObject, domain, i, zoomFactor); } informSelectionListener(selectionObject, selectionEvent); } }
void function(double x, double y, MouseEvent selectionEvent) { Plot p = this.chart.getPlot(); if (p instanceof XYPlot) { XYPlot plot = (XYPlot) p; Selection selectionObject = new Selection(); for (int i = 0; i < plot.getDomainAxisCount(); i++) { ValueAxis domain = plot.getDomainAxis(i); double zoomFactor = getZoomOutFactor(); shrinkSelectionXAxis(x, y, selectionObject, domain, i, zoomFactor); } informSelectionListener(selectionObject, selectionEvent); } }
/** * Increases the length of the domain axis, centered about the given coordinate on the screen. The length of the * domain axis is increased by the value of {@link #getZoomOutFactor()}. * * @param x * the x coordinate (in screen coordinates). * @param y * the y-coordinate (in screen coordinates). */
Increases the length of the domain axis, centered about the given coordinate on the screen. The length of the domain axis is increased by the value of <code>#getZoomOutFactor()</code>
enlargeSelectionOnDomain
{ "repo_name": "aborg0/RapidMiner-Unuk", "path": "src/com/rapidminer/gui/plotter/charts/AbstractChartPanel.java", "license": "agpl-3.0", "size": 82675 }
[ "java.awt.event.MouseEvent", "org.jfree.chart.axis.ValueAxis", "org.jfree.chart.plot.Plot", "org.jfree.chart.plot.XYPlot" ]
import java.awt.event.MouseEvent; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.XYPlot;
import java.awt.event.*; import org.jfree.chart.axis.*; import org.jfree.chart.plot.*;
[ "java.awt", "org.jfree.chart" ]
java.awt; org.jfree.chart;
808,499
public static double pdf(double x, double k, double theta, double shift) { if(x == Double.POSITIVE_INFINITY || x == Double.NEGATIVE_INFINITY) { return 0.; } if(x != x) { return Double.NaN; } x = (x - shift) * theta; final double ex = FastMath.exp(x); return ex < Double.POSITIVE_INFINITY ? FastMath.exp(k * x - ex - GammaDistribution.logGamma(k)) * theta : 0.; }
static double function(double x, double k, double theta, double shift) { if(x == Double.POSITIVE_INFINITY x == Double.NEGATIVE_INFINITY) { return 0.; } if(x != x) { return Double.NaN; } x = (x - shift) * theta; final double ex = FastMath.exp(x); return ex < Double.POSITIVE_INFINITY ? FastMath.exp(k * x - ex - GammaDistribution.logGamma(k)) * theta : 0.; }
/** * ExpGamma distribution PDF (with 0.0 for x &lt; 0) * * @param x query value * @param k Alpha * @param theta Theta = 1 / Beta * @return probability density */
ExpGamma distribution PDF (with 0.0 for x &lt; 0)
pdf
{ "repo_name": "elki-project/elki", "path": "elki-core-math/src/main/java/elki/math/statistics/distribution/ExpGammaDistribution.java", "license": "agpl-3.0", "size": 7235 }
[ "net.jafama.FastMath" ]
import net.jafama.FastMath;
import net.jafama.*;
[ "net.jafama" ]
net.jafama;
1,447,296
public AzureFirewallApplicationRule withProtocols(List<AzureFirewallApplicationRuleProtocol> protocols) { this.protocols = protocols; return this; }
AzureFirewallApplicationRule function(List<AzureFirewallApplicationRuleProtocol> protocols) { this.protocols = protocols; return this; }
/** * Set array of ApplicationRuleProtocols. * * @param protocols the protocols value to set * @return the AzureFirewallApplicationRule object itself. */
Set array of ApplicationRuleProtocols
withProtocols
{ "repo_name": "selvasingh/azure-sdk-for-java", "path": "sdk/network/mgmt-v2020_06_01/src/main/java/com/microsoft/azure/management/network/v2020_06_01/AzureFirewallApplicationRule.java", "license": "mit", "size": 5070 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
719,832
public JobCreateParameters withSecrets(List<EnvironmentVariableWithSecretValue> secrets) { this.secrets = secrets; return this; }
JobCreateParameters function(List<EnvironmentVariableWithSecretValue> secrets) { this.secrets = secrets; return this; }
/** * Set the secrets value. * * @param secrets the secrets value to set * @return the JobCreateParameters object itself. */
Set the secrets value
withSecrets
{ "repo_name": "hovsepm/azure-sdk-for-java", "path": "batchai/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/batchai/v2018_03_01/JobCreateParameters.java", "license": "mit", "size": 16682 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
995,895
public void init(int chunkUid, boolean shouldSpliceIn) { upstreamChunkUid = chunkUid; for (SampleQueue sampleQueue : sampleQueues) { sampleQueue.sourceId(chunkUid); } if (shouldSpliceIn) { for (SampleQueue sampleQueue : sampleQueues) { sampleQueue.splice(); } } } // ExtractorOutput implementation. Called by the loading thread.
void function(int chunkUid, boolean shouldSpliceIn) { upstreamChunkUid = chunkUid; for (SampleQueue sampleQueue : sampleQueues) { sampleQueue.sourceId(chunkUid); } if (shouldSpliceIn) { for (SampleQueue sampleQueue : sampleQueues) { sampleQueue.splice(); } } }
/** * Initializes the wrapper for loading a chunk. * * @param chunkUid The chunk's uid. * @param shouldSpliceIn Whether the samples parsed from the chunk should be spliced into any * samples already queued to the wrapper. */
Initializes the wrapper for loading a chunk
init
{ "repo_name": "thermatk/Telegram-FOSS", "path": "TMessagesProj/src/main/java/org/telegram/messenger/exoplayer2/source/hls/HlsSampleStreamWrapper.java", "license": "gpl-2.0", "size": 31947 }
[ "org.telegram.messenger.exoplayer2.source.SampleQueue" ]
import org.telegram.messenger.exoplayer2.source.SampleQueue;
import org.telegram.messenger.exoplayer2.source.*;
[ "org.telegram.messenger" ]
org.telegram.messenger;
2,587,947
public static JFileChooser getXMLFileChooser() { if(chooser!=null) { FontSizer.setFonts(chooser, FontSizer.getLevel()); return chooser; }
static JFileChooser function() { if(chooser!=null) { FontSizer.setFonts(chooser, FontSizer.getLevel()); return chooser; }
/** * Gets a file chooser. * * @return the chooser */
Gets a file chooser
getXMLFileChooser
{ "repo_name": "OpenSourcePhysics/osp", "path": "src/org/opensourcephysics/controls/ControlUtils.java", "license": "gpl-3.0", "size": 10679 }
[ "javax.swing.JFileChooser", "org.opensourcephysics.tools.FontSizer" ]
import javax.swing.JFileChooser; import org.opensourcephysics.tools.FontSizer;
import javax.swing.*; import org.opensourcephysics.tools.*;
[ "javax.swing", "org.opensourcephysics.tools" ]
javax.swing; org.opensourcephysics.tools;
1,966,560
public void testApplicationScopeNameGreaterEqual() throws ServletException, JspException { GreaterEqualTag ge = new GreaterEqualTag(); String testKey = "testApplicationScopeNameGreaterEqual"; Integer itgr = new Integer(GREATER_VAL); pageContext.setAttribute(testKey, itgr, PageContext.APPLICATION_SCOPE); ge.setPageContext(pageContext); ge.setName(testKey); ge.setScope("application"); ge.setValue(LESSER_VAL); assertTrue( "Application scope value from name (" + GREATER_VAL + ") is greater than or equal to value (" + LESSER_VAL + ")", ge.condition()); }
void function() throws ServletException, JspException { GreaterEqualTag ge = new GreaterEqualTag(); String testKey = STR; Integer itgr = new Integer(GREATER_VAL); pageContext.setAttribute(testKey, itgr, PageContext.APPLICATION_SCOPE); ge.setPageContext(pageContext); ge.setName(testKey); ge.setScope(STR); ge.setValue(LESSER_VAL); assertTrue( STR + GREATER_VAL + STR + LESSER_VAL + ")", ge.condition()); }
/** * Testing <code>GreaterEqualTag</code> using name attribute in * the application scope. */
Testing <code>GreaterEqualTag</code> using name attribute in the application scope
testApplicationScopeNameGreaterEqual
{ "repo_name": "codelibs/cl-struts", "path": "src/test/org/apache/struts/taglib/logic/TestGreaterEqualTag.java", "license": "apache-2.0", "size": 9159 }
[ "javax.servlet.ServletException", "javax.servlet.jsp.JspException", "javax.servlet.jsp.PageContext" ]
import javax.servlet.ServletException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext;
import javax.servlet.*; import javax.servlet.jsp.*;
[ "javax.servlet" ]
javax.servlet;
2,343,172
testFailed=false; logger.info("\n\nExecuting test case "+rowDataWrapper+"\n"); currentTestcase=rowDataWrapper.getCurrentTestcase(); HashMap<String, String> rowData = rowDataWrapper.getRowData(); String runMode = rowData.get(Constants.COLUMN_RUN_MODE).trim(); tcid = rowData.get(Constants.COLUMN_TCID).trim(); // Execute when Run Mode is Yes if (runMode.equalsIgnoreCase("YES")) { // Initialize all the values from test data sheet initialize(rowData); //TODO define runBootstrapSQLQueries() // Replaces the URL with path parameters replaceURLParameters(urlParameters); Response response = getResponse(); if (response != null) { FileUtil.createFile(fileoutpath, tcid + "_Response.txt",response.asString()); validateResponse(response); // Updating the pass result only if there is no failure if (!testFailed) { testPassed(); } } } else if (runMode.equalsIgnoreCase("NO")) { testSkipped(tcid+" : Test Skipped as Run Mode was NO"); }else{ testFailed("Unable to read Run Mode"); } }
testFailed=false; logger.info(STR+rowDataWrapper+"\n"); currentTestcase=rowDataWrapper.getCurrentTestcase(); HashMap<String, String> rowData = rowDataWrapper.getRowData(); String runMode = rowData.get(Constants.COLUMN_RUN_MODE).trim(); tcid = rowData.get(Constants.COLUMN_TCID).trim(); if (runMode.equalsIgnoreCase("YES")) { initialize(rowData); replaceURLParameters(urlParameters); Response response = getResponse(); if (response != null) { FileUtil.createFile(fileoutpath, tcid + STR,response.asString()); validateResponse(response); if (!testFailed) { testPassed(); } } } else if (runMode.equalsIgnoreCase("NO")) { testSkipped(tcid+STR); }else{ testFailed(STR); } }
/** * This method is the main method that starts the execution. * * @throws IOException */
This method is the main method that starts the execution
test
{ "repo_name": "Infinite-Intelligence/Automation", "path": "src/test/java/com/prokarma/main/DriverScript.java", "license": "apache-2.0", "size": 2038 }
[ "com.jayway.restassured.response.Response", "com.prokarma.utils.Constants", "com.prokarma.utils.FileUtil", "java.util.HashMap" ]
import com.jayway.restassured.response.Response; import com.prokarma.utils.Constants; import com.prokarma.utils.FileUtil; import java.util.HashMap;
import com.jayway.restassured.response.*; import com.prokarma.utils.*; import java.util.*;
[ "com.jayway.restassured", "com.prokarma.utils", "java.util" ]
com.jayway.restassured; com.prokarma.utils; java.util;
611,909
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<Void>, Void> beginDelete( String resourceGroupName, String capacityReservationGroupName, String capacityReservationName);
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<Void>, Void> beginDelete( String resourceGroupName, String capacityReservationGroupName, String capacityReservationName);
/** * The operation to delete a capacity reservation. This operation is allowed only when all the associated resources * are disassociated from the capacity reservation. Please refer to https://aka.ms/CapacityReservation for more * details. * * @param resourceGroupName The name of the resource group. * @param capacityReservationGroupName The name of the capacity reservation group. * @param capacityReservationName The name of the capacity reservation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.compute.models.ApiErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link SyncPoller} for polling of long-running operation. */
The operation to delete a capacity reservation. This operation is allowed only when all the associated resources are disassociated from the capacity reservation. Please refer to HREF for more details
beginDelete
{ "repo_name": "Azure/azure-sdk-for-java", "path": "sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/fluent/CapacityReservationsClient.java", "license": "mit", "size": 34324 }
[ "com.azure.core.annotation.ReturnType", "com.azure.core.annotation.ServiceMethod", "com.azure.core.management.polling.PollResult", "com.azure.core.util.polling.SyncPoller" ]
import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.management.polling.PollResult; import com.azure.core.util.polling.SyncPoller;
import com.azure.core.annotation.*; import com.azure.core.management.polling.*; import com.azure.core.util.polling.*;
[ "com.azure.core" ]
com.azure.core;
946,342
private void saveKey(Key key) throws IOException { // TODO(DMS): change this to save: // The version of the save file, incremented everytime this method // changes. // the search request, // the set of bibles, // and any advanced search options. // perhaps by having and creating a book mark object. assert saved != null; Writer out = null; try { out = new FileWriter(saved); if (key instanceof Passage) { Passage ref = (Passage) key; ref.writeDescription(out); } else { out.write(key.getName()); out.write("\n"); } } finally { if (out != null) { out.close(); } } }
void function(Key key) throws IOException { assert saved != null; Writer out = null; try { out = new FileWriter(saved); if (key instanceof Passage) { Passage ref = (Passage) key; ref.writeDescription(out); } else { out.write(key.getName()); out.write("\n"); } } finally { if (out != null) { out.close(); } } }
/** * Do the real work of saving to a file * * @param key * The key to save * @throws IOException * If a write error happens */
Do the real work of saving to a file
saveKey
{ "repo_name": "truhanen/JSana", "path": "JSana/src_others/org/crosswire/bibledesktop/book/BibleViewPane.java", "license": "gpl-2.0", "size": 12958 }
[ "java.io.FileWriter", "java.io.IOException", "java.io.Writer", "org.crosswire.jsword.passage.Key", "org.crosswire.jsword.passage.Passage" ]
import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import org.crosswire.jsword.passage.Key; import org.crosswire.jsword.passage.Passage;
import java.io.*; import org.crosswire.jsword.passage.*;
[ "java.io", "org.crosswire.jsword" ]
java.io; org.crosswire.jsword;
2,090,252
public void testScanAcrossSnapshot2() throws IOException, CloneNotSupportedException { // we are going to the scanning across snapshot with two kvs // kv1 should always be returned before kv2 final byte[] one = Bytes.toBytes(1); final byte[] two = Bytes.toBytes(2); final byte[] f = Bytes.toBytes("f"); final byte[] q = Bytes.toBytes("q"); final byte[] v = Bytes.toBytes(3); final KeyValue kv1 = new KeyValue(one, f, q, v); final KeyValue kv2 = new KeyValue(two, f, q, v); // use case 1: both kvs in kvset this.memstore.add(kv1.clone()); this.memstore.add(kv2.clone()); verifyScanAcrossSnapshot2(kv1, kv2); // use case 2: both kvs in snapshot this.memstore.snapshot(); verifyScanAcrossSnapshot2(kv1, kv2); // use case 3: first in snapshot second in kvset this.memstore = new DefaultMemStore(); this.memstore.add(kv1.clone()); this.memstore.snapshot(); this.memstore.add(kv2.clone()); verifyScanAcrossSnapshot2(kv1, kv2); }
void function() throws IOException, CloneNotSupportedException { final byte[] one = Bytes.toBytes(1); final byte[] two = Bytes.toBytes(2); final byte[] f = Bytes.toBytes("f"); final byte[] q = Bytes.toBytes("q"); final byte[] v = Bytes.toBytes(3); final KeyValue kv1 = new KeyValue(one, f, q, v); final KeyValue kv2 = new KeyValue(two, f, q, v); this.memstore.add(kv1.clone()); this.memstore.add(kv2.clone()); verifyScanAcrossSnapshot2(kv1, kv2); this.memstore.snapshot(); verifyScanAcrossSnapshot2(kv1, kv2); this.memstore = new DefaultMemStore(); this.memstore.add(kv1.clone()); this.memstore.snapshot(); this.memstore.add(kv2.clone()); verifyScanAcrossSnapshot2(kv1, kv2); }
/** * A simple test which verifies the 3 possible states when scanning across snapshot. * @throws IOException * @throws CloneNotSupportedException */
A simple test which verifies the 3 possible states when scanning across snapshot
testScanAcrossSnapshot2
{ "repo_name": "toshimasa-nasu/hbase", "path": "hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestDefaultMemStore.java", "license": "apache-2.0", "size": 37226 }
[ "java.io.IOException", "org.apache.hadoop.hbase.KeyValue", "org.apache.hadoop.hbase.util.Bytes" ]
import java.io.IOException; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.util.Bytes;
import java.io.*; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.util.*;
[ "java.io", "org.apache.hadoop" ]
java.io; org.apache.hadoop;
108,998
Set<String> getMappableAttributes();
Set<String> getMappableAttributes();
/** * Implementations of this method should return a set of all string attributes which * can be mapped to <tt>GrantedAuthority</tt>s. * * @return set of all mappable roles */
Implementations of this method should return a set of all string attributes which can be mapped to GrantedAuthoritys
getMappableAttributes
{ "repo_name": "tekul/spring-security", "path": "core/src/main/java/org/springframework/security/core/authority/mapping/MappableAttributesRetriever.java", "license": "apache-2.0", "size": 620 }
[ "java.util.Set" ]
import java.util.Set;
import java.util.*;
[ "java.util" ]
java.util;
2,479,732
private void fetchValue() { // Do we determine a simple key? SimpleKey key = this.possibleSimpleKeys.remove(this.flowLevel); if (key != null) { // Add KEY. this.tokens.add(key.getTokenNumber() - this.tokensTaken, new KeyToken(key.getMark(), key.getMark())); // If this key starts a new block mapping, we need to add // BLOCK-MAPPING-START. if (this.flowLevel == 0) { if (addIndent(key.getColumn())) { this.tokens.add(key.getTokenNumber() - this.tokensTaken, new BlockMappingStartToken(key.getMark(), key.getMark())); } } // There cannot be two simple keys one after another. this.allowSimpleKey = false; } else { // It must be a part of a complex key. // Block context needs additional checks. Do we really need them? // They will be caught by the parser anyway. if (this.flowLevel == 0) { // We are allowed to start a complex value if and only if we can // start a simple key. if (!this.allowSimpleKey) { throw new ScannerException(null, null, "mapping values are not allowed here", reader.getMark()); } } // If this value starts a new block mapping, we need to add // BLOCK-MAPPING-START. It will be detected as an error later by // the parser. if (flowLevel == 0) { if (addIndent(reader.getColumn())) { Mark mark = reader.getMark(); this.tokens.add(new BlockMappingStartToken(mark, mark)); } } // Simple keys are allowed after ':' in the block context. allowSimpleKey = (flowLevel == 0); // Reset possible simple key on the current level. removePossibleSimpleKey(); } // Add VALUE. Mark startMark = reader.getMark(); reader.forward(); Mark endMark = reader.getMark(); Token token = new ValueToken(startMark, endMark); this.tokens.add(token); }
void function() { SimpleKey key = this.possibleSimpleKeys.remove(this.flowLevel); if (key != null) { this.tokens.add(key.getTokenNumber() - this.tokensTaken, new KeyToken(key.getMark(), key.getMark())); if (this.flowLevel == 0) { if (addIndent(key.getColumn())) { this.tokens.add(key.getTokenNumber() - this.tokensTaken, new BlockMappingStartToken(key.getMark(), key.getMark())); } } this.allowSimpleKey = false; } else { if (this.flowLevel == 0) { if (!this.allowSimpleKey) { throw new ScannerException(null, null, STR, reader.getMark()); } } if (flowLevel == 0) { if (addIndent(reader.getColumn())) { Mark mark = reader.getMark(); this.tokens.add(new BlockMappingStartToken(mark, mark)); } } allowSimpleKey = (flowLevel == 0); removePossibleSimpleKey(); } Mark startMark = reader.getMark(); reader.forward(); Mark endMark = reader.getMark(); Token token = new ValueToken(startMark, endMark); this.tokens.add(token); }
/** * Fetch a value in a block-style mapping. * * @see http://www.yaml.org/spec/1.1/#id863975 */
Fetch a value in a block-style mapping
fetchValue
{ "repo_name": "lsst-camera-dh/snakeyaml", "path": "src/main/java/org/yaml/snakeyaml/scanner/ScannerImpl.java", "license": "apache-2.0", "size": 82645 }
[ "org.yaml.snakeyaml.error.Mark", "org.yaml.snakeyaml.tokens.BlockMappingStartToken", "org.yaml.snakeyaml.tokens.KeyToken", "org.yaml.snakeyaml.tokens.Token", "org.yaml.snakeyaml.tokens.ValueToken" ]
import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.tokens.BlockMappingStartToken; import org.yaml.snakeyaml.tokens.KeyToken; import org.yaml.snakeyaml.tokens.Token; import org.yaml.snakeyaml.tokens.ValueToken;
import org.yaml.snakeyaml.error.*; import org.yaml.snakeyaml.tokens.*;
[ "org.yaml.snakeyaml" ]
org.yaml.snakeyaml;
2,084,236
//@Test public void thriftRespondTest() throws DSPException, IOException { OpenRTBAPIDummyTest bidder = new OpenRTBAPIDummyTest(); DemandSideDAODummyTest dao = new DemandSideDAODummyTest(); URL url = this.getClass().getResource("/properties.json"); dao.loadData(url.getPath()); DemandSideServer server = new DemandSideServer(bidder, dao); InputStream in = new ByteArrayInputStream(writeBidRequest(request, THRIFT_CONTENT_TYPE)); server.respond("BigAdExchange", in, THRIFT_CONTENT_TYPE); }
OpenRTBAPIDummyTest bidder = new OpenRTBAPIDummyTest(); DemandSideDAODummyTest dao = new DemandSideDAODummyTest(); URL url = this.getClass().getResource(STR); dao.loadData(url.getPath()); DemandSideServer server = new DemandSideServer(bidder, dao); InputStream in = new ByteArrayInputStream(writeBidRequest(request, THRIFT_CONTENT_TYPE)); server.respond(STR, in, THRIFT_CONTENT_TYPE); }
/** * This method is used to test the respond method with thrift content type */
This method is used to test the respond method with thrift content type
thriftRespondTest
{ "repo_name": "openrtb/openrtb2x", "path": "demand-side/dsp-core/src/test/java/org/openrtb/dsp/core/DemandSideServerTest.java", "license": "bsd-3-clause", "size": 11370 }
[ "java.io.ByteArrayInputStream", "java.io.InputStream" ]
import java.io.ByteArrayInputStream; import java.io.InputStream;
import java.io.*;
[ "java.io" ]
java.io;
1,276,868
public static void main(String[] args) throws IOException, InterruptedException { final HelloWorldServer server = new HelloWorldServer(); server.start(); server.blockUntilShutdown(); } static class GreeterImpl extends GreeterGrpc.GreeterImplBase {
static void function(String[] args) throws IOException, InterruptedException { final HelloWorldServer server = new HelloWorldServer(); server.start(); server.blockUntilShutdown(); } static class GreeterImpl extends GreeterGrpc.GreeterImplBase {
/** * Main launches the server from the command line. */
Main launches the server from the command line
main
{ "repo_name": "nmittler/grpc-java", "path": "examples/src/main/java/io/grpc/examples/helloworld/HelloWorldServer.java", "license": "bsd-3-clause", "size": 3592 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
2,111,871
public void testParseReference() { EntityReference er = null; er = entityBrokerManager.parseReference(TestData.REF1); assertNotNull(er); assertEquals(TestData.PREFIX1, er.getPrefix()); assertEquals(TestData.IDS1[0], er.getId()); er = entityBrokerManager.parseReference(TestData.REF2); assertNotNull(er); assertEquals(TestData.PREFIX2, er.getPrefix()); // test parsing a defined reference er = entityBrokerManager.parseReference(TestData.REF3A); assertNotNull(er); assertEquals(TestData.PREFIX3, er.getPrefix()); // parsing of unregistered entity references returns null er = entityBrokerManager.parseReference(TestData.REF9); assertNull(er); // parsing with nonexistent prefix returns null er = entityBrokerManager.parseReference("/totallyfake/notreal"); assertNull(er); // TODO test handling custom ref objects try { er = entityBrokerManager.parseReference(TestData.INVALID_REF); fail("Should have thrown exception"); } catch (IllegalArgumentException e) { assertNotNull(e.getMessage()); } } /** * Test method for {@link EntityHandlerImpl#parseEntityURL(String)}
void function() { EntityReference er = null; er = entityBrokerManager.parseReference(TestData.REF1); assertNotNull(er); assertEquals(TestData.PREFIX1, er.getPrefix()); assertEquals(TestData.IDS1[0], er.getId()); er = entityBrokerManager.parseReference(TestData.REF2); assertNotNull(er); assertEquals(TestData.PREFIX2, er.getPrefix()); er = entityBrokerManager.parseReference(TestData.REF3A); assertNotNull(er); assertEquals(TestData.PREFIX3, er.getPrefix()); er = entityBrokerManager.parseReference(TestData.REF9); assertNull(er); er = entityBrokerManager.parseReference(STR); assertNull(er); try { er = entityBrokerManager.parseReference(TestData.INVALID_REF); fail(STR); } catch (IllegalArgumentException e) { assertNotNull(e.getMessage()); } } /** * Test method for {@link EntityHandlerImpl#parseEntityURL(String)}
/** * Test method for * {@link org.sakaiproject.entitybroker.rest.EntityHandlerImpl#parseReference(java.lang.String)}. */
Test method for <code>org.sakaiproject.entitybroker.rest.EntityHandlerImpl#parseReference(java.lang.String)</code>
testParseReference
{ "repo_name": "eemirtekin/Sakai-10.6-TR", "path": "entitybroker/impl/src/test/org/sakaiproject/entitybroker/impl/EntityBrokerManagerTest.java", "license": "apache-2.0", "size": 16412 }
[ "org.sakaiproject.entitybroker.EntityReference", "org.sakaiproject.entitybroker.mocks.data.TestData" ]
import org.sakaiproject.entitybroker.EntityReference; import org.sakaiproject.entitybroker.mocks.data.TestData;
import org.sakaiproject.entitybroker.*; import org.sakaiproject.entitybroker.mocks.data.*;
[ "org.sakaiproject.entitybroker" ]
org.sakaiproject.entitybroker;
2,666,952
public static <R> R executeOnLocalOrRemoteJvm(Ignite ignite, final TestIgniteCallable<R> job) { if (!isMultiJvmObject(ignite)) try { return job.call(ignite); } catch (Exception e) { throw new IgniteException(e); } else return executeRemotely((IgniteProcessProxy)ignite, job); }
static <R> R function(Ignite ignite, final TestIgniteCallable<R> job) { if (!isMultiJvmObject(ignite)) try { return job.call(ignite); } catch (Exception e) { throw new IgniteException(e); } else return executeRemotely((IgniteProcessProxy)ignite, job); }
/** * Calls job on local JVM or on remote JVM in multi-JVM case. * * @param ignite Ignite. * @param job Job. */
Calls job on local JVM or on remote JVM in multi-JVM case
executeOnLocalOrRemoteJvm
{ "repo_name": "vladisav/ignite", "path": "modules/core/src/test/java/org/apache/ignite/testframework/junits/GridAbstractTest.java", "license": "apache-2.0", "size": 77511 }
[ "org.apache.ignite.Ignite", "org.apache.ignite.IgniteException", "org.apache.ignite.testframework.junits.multijvm.IgniteProcessProxy" ]
import org.apache.ignite.Ignite; import org.apache.ignite.IgniteException; import org.apache.ignite.testframework.junits.multijvm.IgniteProcessProxy;
import org.apache.ignite.*; import org.apache.ignite.testframework.junits.multijvm.*;
[ "org.apache.ignite" ]
org.apache.ignite;
2,136,770
public DeviceMap<VoltageSensor> voltageSensors() { return fullMap.checkedGet(VoltageSensor.class); } /** * Builds a new {@link Wire} to allow for a better usage of I2C Devices. This method only looks * at devices represented by {@link #i2cDevices()} * * @param name the name of the I2C to use, as known by {@link #i2cDevices()}
DeviceMap<VoltageSensor> function() { return fullMap.checkedGet(VoltageSensor.class); } /** * Builds a new {@link Wire} to allow for a better usage of I2C Devices. This method only looks * at devices represented by {@link #i2cDevices()} * * @param name the name of the I2C to use, as known by {@link #i2cDevices()}
/** * Returns a {@link DeviceMap<VoltageSensor>} for use to access VoltageSensor Sensor hardware * * @return a DeviceMap to use for access to representations of VoltageSensor Sensors * @see DeviceMap * @see VoltageSensor */
Returns a <code>DeviceMap</code> for use to access VoltageSensor Sensor hardware
voltageSensors
{ "repo_name": "MHS-FIRSTrobotics/TeamClutch-FTC2016", "path": "FtcXtensible/src/main/java/org/ftccommunity/ftcxtensible/robot/ExtensibleHardwareMap.java", "license": "mit", "size": 22071 }
[ "com.qualcomm.robotcore.hardware.VoltageSensor", "org.ftccommunity.ftcxtensible.collections.DeviceMap", "org.ftccommunity.i2clibrary.Wire" ]
import com.qualcomm.robotcore.hardware.VoltageSensor; import org.ftccommunity.ftcxtensible.collections.DeviceMap; import org.ftccommunity.i2clibrary.Wire;
import com.qualcomm.robotcore.hardware.*; import org.ftccommunity.ftcxtensible.collections.*; import org.ftccommunity.i2clibrary.*;
[ "com.qualcomm.robotcore", "org.ftccommunity.ftcxtensible", "org.ftccommunity.i2clibrary" ]
com.qualcomm.robotcore; org.ftccommunity.ftcxtensible; org.ftccommunity.i2clibrary;
142,939
public void setAddResponseOutcomeHeaderOnSeverity(ResultSeverityEnum theAddResponseOutcomeHeaderOnSeverity) { myAddResponseOutcomeHeaderOnSeverity = theAddResponseOutcomeHeaderOnSeverity != null ? theAddResponseOutcomeHeaderOnSeverity.ordinal() : null; }
void function(ResultSeverityEnum theAddResponseOutcomeHeaderOnSeverity) { myAddResponseOutcomeHeaderOnSeverity = theAddResponseOutcomeHeaderOnSeverity != null ? theAddResponseOutcomeHeaderOnSeverity.ordinal() : null; }
/** * If the validation produces a result with at least the given severity, a header with the name * specified by {@link #setResponseOutcomeHeaderName(String)} will be added containing a JSON encoded * OperationOutcome resource containing the validation results. */
If the validation produces a result with at least the given severity, a header with the name specified by <code>#setResponseOutcomeHeaderName(String)</code> will be added containing a JSON encoded OperationOutcome resource containing the validation results
setAddResponseOutcomeHeaderOnSeverity
{ "repo_name": "Gaduo/hapi-fhir", "path": "hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/BaseValidatingInterceptor.java", "license": "apache-2.0", "size": 13932 }
[ "ca.uhn.fhir.validation.ResultSeverityEnum" ]
import ca.uhn.fhir.validation.ResultSeverityEnum;
import ca.uhn.fhir.validation.*;
[ "ca.uhn.fhir" ]
ca.uhn.fhir;
286,816
@DisabledTest // Flaked on the try bot. http://crbug.com/543138 @SmallTest @Feature({"NewTabPage"}) public void testOpenMostVisitedItemInNewTab() throws InterruptedException { invokeContextMenuAndOpenInANewTab(mMostVisitedLayout.getChildAt(0), NewTabPage.ID_OPEN_IN_NEW_TAB, false, FAKE_MOST_VISITED_URLS[0]); }
@DisabledTest @Feature({STR}) void function() throws InterruptedException { invokeContextMenuAndOpenInANewTab(mMostVisitedLayout.getChildAt(0), NewTabPage.ID_OPEN_IN_NEW_TAB, false, FAKE_MOST_VISITED_URLS[0]); }
/** * Tests opening a most visited item in a new tab. */
Tests opening a most visited item in a new tab
testOpenMostVisitedItemInNewTab
{ "repo_name": "Workday/OpenFrame", "path": "chrome/android/javatests/src/org/chromium/chrome/browser/ntp/NewTabPageTest.java", "license": "bsd-3-clause", "size": 13789 }
[ "org.chromium.base.test.util.DisabledTest", "org.chromium.base.test.util.Feature" ]
import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature;
import org.chromium.base.test.util.*;
[ "org.chromium.base" ]
org.chromium.base;
137,002
private static List<FormatEntry> parseFormatString(String format) { List<FormatEntry> l = new ArrayList<>(); StringBuilder sb = new StringBuilder(); boolean escaped = false; for (int i = 0; i < format.length(); i++) { char c = format.charAt(i); if (escaped) { escaped = false; // we know we'll be out of escape mode after this // Check if this escape sequence is meaningful: if (c == '\\') { // Escaped backslash: means that we add a backslash: sb.append('\\'); } else if (WrapFileLinks.ESCAPE_SEQ.containsKey(c)) { // Ok, we have the code. Add the previous string (if any) and // the entry indicated by the escape sequence: if (sb.length() > 0) { l.add(new FormatEntry(sb.toString())); // Clear the buffer: sb = new StringBuilder(); } l.add(new FormatEntry(WrapFileLinks.ESCAPE_SEQ.get(c))); } else { // Unknown escape sequence. sb.append('\\'); sb.append(c); } } else { // Check if we are at the start of an escape sequence: if (c == '\\') { escaped = true; } else { sb.append(c); } } } // Finished scanning the string. If we collected text at the end, add an entry for it: if (sb.length() > 0) { l.add(new FormatEntry(sb.toString())); } return l; } static class FormatEntry { private final int type; private String string; public FormatEntry(int type) { this.type = type; } public FormatEntry(String value) { this.type = WrapFileLinks.STRING; this.string = value; }
static List<FormatEntry> function(String format) { List<FormatEntry> l = new ArrayList<>(); StringBuilder sb = new StringBuilder(); boolean escaped = false; for (int i = 0; i < format.length(); i++) { char c = format.charAt(i); if (escaped) { escaped = false; if (c == '\\') { sb.append('\\'); } else if (WrapFileLinks.ESCAPE_SEQ.containsKey(c)) { if (sb.length() > 0) { l.add(new FormatEntry(sb.toString())); sb = new StringBuilder(); } l.add(new FormatEntry(WrapFileLinks.ESCAPE_SEQ.get(c))); } else { sb.append('\\'); sb.append(c); } } else { if (c == '\\') { escaped = true; } else { sb.append(c); } } } if (sb.length() > 0) { l.add(new FormatEntry(sb.toString())); } return l; } static class FormatEntry { private final int type; private String string; public FormatEntry(int type) { this.type = type; } public FormatEntry(String value) { this.type = WrapFileLinks.STRING; this.string = value; }
/** * Parse a format string and return a list of FormatEntry objects. The format * string is basically marked up with "\i" marking that the iteration number should * be inserted, and with "\p" marking that the file path of the current iteration * should be inserted, plus additional markers. * * @param format The marked-up string. * @return the resulting format entries. */
Parse a format string and return a list of FormatEntry objects. The format string is basically marked up with "\i" marking that the iteration number should be inserted, and with "\p" marking that the file path of the current iteration should be inserted, plus additional markers
parseFormatString
{ "repo_name": "matheusvervloet/jabref", "path": "src/main/java/net/sf/jabref/logic/layout/format/WrapFileLinks.java", "license": "gpl-2.0", "size": 13309 }
[ "java.util.ArrayList", "java.util.List" ]
import java.util.ArrayList; import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
577,582
List<List<Feature>> features = new ArrayList<List<Feature>>(); features.add(createFeatures("0")); features.add(createFeatures("1")); features.add(createFeatures("2")); features.add(createFeatures("3")); features.add(createFeatures("4")); UimaContext uimaContext = UimaContextFactory.createUimaContext( DefaultOutcomeFeatureExtractor.PARAM_MOST_RECENT_OUTCOME, 1, DefaultOutcomeFeatureExtractor.PARAM_LEAST_RECENT_OUTCOME, 1, DefaultOutcomeFeatureExtractor.PARAM_USE_BIGRAM, false, DefaultOutcomeFeatureExtractor.PARAM_USE_TRIGRAM, false, DefaultOutcomeFeatureExtractor.PARAM_USE4GRAM, false); DefaultOutcomeFeatureExtractor dofe = new DefaultOutcomeFeatureExtractor(); dofe.initialize(uimaContext); TestViterbiClassifier tvc = new TestViterbiClassifier(); tvc.setOutcomeFeatureExctractors(new OutcomeFeatureExtractor[] { dofe }); tvc.setStackSize(4); tvc.setAddScores(true); tvc.setDelegatedClassifier(new TestClassifier()); List<String> bestSequence = tvc.viterbi(features); assertEquals("A", bestSequence.get(0)); assertEquals("E", bestSequence.get(1)); assertEquals("G", bestSequence.get(2)); assertEquals("K", bestSequence.get(3)); assertEquals("O", bestSequence.get(4)); }
List<List<Feature>> features = new ArrayList<List<Feature>>(); features.add(createFeatures("0")); features.add(createFeatures("1")); features.add(createFeatures("2")); features.add(createFeatures("3")); features.add(createFeatures("4")); UimaContext uimaContext = UimaContextFactory.createUimaContext( DefaultOutcomeFeatureExtractor.PARAM_MOST_RECENT_OUTCOME, 1, DefaultOutcomeFeatureExtractor.PARAM_LEAST_RECENT_OUTCOME, 1, DefaultOutcomeFeatureExtractor.PARAM_USE_BIGRAM, false, DefaultOutcomeFeatureExtractor.PARAM_USE_TRIGRAM, false, DefaultOutcomeFeatureExtractor.PARAM_USE4GRAM, false); DefaultOutcomeFeatureExtractor dofe = new DefaultOutcomeFeatureExtractor(); dofe.initialize(uimaContext); TestViterbiClassifier tvc = new TestViterbiClassifier(); tvc.setOutcomeFeatureExctractors(new OutcomeFeatureExtractor[] { dofe }); tvc.setStackSize(4); tvc.setAddScores(true); tvc.setDelegatedClassifier(new TestClassifier()); List<String> bestSequence = tvc.viterbi(features); assertEquals("A", bestSequence.get(0)); assertEquals("E", bestSequence.get(1)); assertEquals("G", bestSequence.get(2)); assertEquals("K", bestSequence.get(3)); assertEquals("O", bestSequence.get(4)); }
/** * This test was created from scratch using a small chart I wrote down on paper and solved by hand * before implementing here. */
This test was created from scratch using a small chart I wrote down on paper and solved by hand before implementing here
test1
{ "repo_name": "ClearTK/cleartk", "path": "cleartk-ml/src/test/java/org/cleartk/ml/viterbi/ViterbiTest.java", "license": "bsd-3-clause", "size": 12672 }
[ "java.util.ArrayList", "java.util.List", "org.apache.uima.UimaContext", "org.apache.uima.fit.factory.UimaContextFactory", "org.cleartk.ml.Feature", "org.cleartk.ml.viterbi.DefaultOutcomeFeatureExtractor", "org.cleartk.ml.viterbi.OutcomeFeatureExtractor", "org.junit.Assert" ]
import java.util.ArrayList; import java.util.List; import org.apache.uima.UimaContext; import org.apache.uima.fit.factory.UimaContextFactory; import org.cleartk.ml.Feature; import org.cleartk.ml.viterbi.DefaultOutcomeFeatureExtractor; import org.cleartk.ml.viterbi.OutcomeFeatureExtractor; import org.junit.Assert;
import java.util.*; import org.apache.uima.*; import org.apache.uima.fit.factory.*; import org.cleartk.ml.*; import org.cleartk.ml.viterbi.*; import org.junit.*;
[ "java.util", "org.apache.uima", "org.cleartk.ml", "org.junit" ]
java.util; org.apache.uima; org.cleartk.ml; org.junit;
2,471,856
private boolean indexRowChanged() throws StandardException { int numColumns = ourIndexRow.nColumns(); for (int index = 1; index <= numColumns; index++) { DataValueDescriptor oldOrderable = ourIndexRow.getColumn(index); DataValueDescriptor newOrderable = ourUpdatedIndexRow.getColumn(index); if (! (oldOrderable.compare(DataValueDescriptor.ORDER_OP_EQUALS, newOrderable, true, true))) { return true; } } return false; } /** Position our index scan to 'ourIndexRow'. <P>This creates the scan the first time it is called.
boolean function() throws StandardException { int numColumns = ourIndexRow.nColumns(); for (int index = 1; index <= numColumns; index++) { DataValueDescriptor oldOrderable = ourIndexRow.getColumn(index); DataValueDescriptor newOrderable = ourUpdatedIndexRow.getColumn(index); if (! (oldOrderable.compare(DataValueDescriptor.ORDER_OP_EQUALS, newOrderable, true, true))) { return true; } } return false; } /** Position our index scan to 'ourIndexRow'. <P>This creates the scan the first time it is called.
/** * Determine whether or not any columns in the current index * row are being changed by the update. No need to update the * index if no columns changed. * * @return Nothing. * * @exception StandardException Thrown on error */
Determine whether or not any columns in the current index row are being changed by the update. No need to update the index if no columns changed
indexRowChanged
{ "repo_name": "gemxd/gemfirexd-oss", "path": "gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/impl/sql/execute/IndexChanger.java", "license": "apache-2.0", "size": 22285 }
[ "com.pivotal.gemfirexd.internal.iapi.error.StandardException", "com.pivotal.gemfirexd.internal.iapi.types.DataValueDescriptor" ]
import com.pivotal.gemfirexd.internal.iapi.error.StandardException; import com.pivotal.gemfirexd.internal.iapi.types.DataValueDescriptor;
import com.pivotal.gemfirexd.internal.iapi.error.*; import com.pivotal.gemfirexd.internal.iapi.types.*;
[ "com.pivotal.gemfirexd" ]
com.pivotal.gemfirexd;
401,321
@Test public void testEnableAppContextsSameRetriever() { session.enableAppContext(CONTEXT_RETRIEVER_NAME_A, CONTEXT_NAME_A); session.enableAppContext(CONTEXT_RETRIEVER_NAME_A, CONTEXT_NAME_B); List<String> expectedCommands = Arrays.asList( CONTEXT_RETRIEVER_NAME_A + ':' + CONTEXT_NAME_A, CONTEXT_RETRIEVER_NAME_A + ':' + CONTEXT_NAME_B); List<String> actualCommands = clientListener.getEnabledAppContextCommands(); assertEquals(expectedCommands, actualCommands); }
void function() { session.enableAppContext(CONTEXT_RETRIEVER_NAME_A, CONTEXT_NAME_A); session.enableAppContext(CONTEXT_RETRIEVER_NAME_A, CONTEXT_NAME_B); List<String> expectedCommands = Arrays.asList( CONTEXT_RETRIEVER_NAME_A + ':' + CONTEXT_NAME_A, CONTEXT_RETRIEVER_NAME_A + ':' + CONTEXT_NAME_B); List<String> actualCommands = clientListener.getEnabledAppContextCommands(); assertEquals(expectedCommands, actualCommands); }
/** * Test enabling two application contexts sharing the same retriever name. */
Test enabling two application contexts sharing the same retriever name
testEnableAppContextsSameRetriever
{ "repo_name": "alexmonthy/ust-java-tests", "path": "lttng-ust-java-tests-common/src/test/java/org/lttng/ust/agent/integration/client/TcpClientIT.java", "license": "gpl-2.0", "size": 25122 }
[ "java.util.Arrays", "java.util.List", "org.junit.jupiter.api.Assertions" ]
import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Assertions;
import java.util.*; import org.junit.jupiter.api.*;
[ "java.util", "org.junit.jupiter" ]
java.util; org.junit.jupiter;
1,005,636
public void setApiName(GoogleMailApiName apiName) { this.apiName = apiName; }
void function(GoogleMailApiName apiName) { this.apiName = apiName; }
/** * What kind of operation to perform */
What kind of operation to perform
setApiName
{ "repo_name": "DariusX/camel", "path": "components/camel-google-mail/src/main/java/org/apache/camel/component/google/mail/GoogleMailConfiguration.java", "license": "apache-2.0", "size": 3708 }
[ "org.apache.camel.component.google.mail.internal.GoogleMailApiName" ]
import org.apache.camel.component.google.mail.internal.GoogleMailApiName;
import org.apache.camel.component.google.mail.internal.*;
[ "org.apache.camel" ]
org.apache.camel;
311,981
private static ArrayList<Row> createRows(TableSchema tableSchema, JsonNode rowsNode) { validateJsonNode(rowsNode, "rows"); ArrayList<Row> rows = Lists.newArrayList(); for (JsonNode rowNode : rowsNode.get("rows")) { rows.add(createRow(tableSchema, null, rowNode)); //FIXME null will throw exception } return rows; }
static ArrayList<Row> function(TableSchema tableSchema, JsonNode rowsNode) { validateJsonNode(rowsNode, "rows"); ArrayList<Row> rows = Lists.newArrayList(); for (JsonNode rowNode : rowsNode.get("rows")) { rows.add(createRow(tableSchema, null, rowNode)); } return rows; }
/** * Convert Operation JsonNode into Rows. * @param tableSchema TableSchema entity * @param rowsNode JsonNode * @return ArrayList<Row> the List of Row */
Convert Operation JsonNode into Rows
createRows
{ "repo_name": "sonu283304/onos", "path": "protocols/ovsdb/rfc/src/main/java/org/onosproject/ovsdb/rfc/utils/FromJsonUtil.java", "license": "apache-2.0", "size": 13697 }
[ "com.fasterxml.jackson.databind.JsonNode", "com.google.common.collect.Lists", "java.util.ArrayList", "org.onosproject.ovsdb.rfc.notation.Row", "org.onosproject.ovsdb.rfc.schema.TableSchema" ]
import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.Lists; import java.util.ArrayList; import org.onosproject.ovsdb.rfc.notation.Row; import org.onosproject.ovsdb.rfc.schema.TableSchema;
import com.fasterxml.jackson.databind.*; import com.google.common.collect.*; import java.util.*; import org.onosproject.ovsdb.rfc.notation.*; import org.onosproject.ovsdb.rfc.schema.*;
[ "com.fasterxml.jackson", "com.google.common", "java.util", "org.onosproject.ovsdb" ]
com.fasterxml.jackson; com.google.common; java.util; org.onosproject.ovsdb;
618,097
@Test public void testChangeState() { BuddyListModel model = new BuddyListModel(); model.addListDataListener(this); // add some buddies model.setOnline("dumdiduu", true); model.setOnline("daibaduu", true); model.setOnline("hubbaduu", true); model.setOnline("alibaba", false); assertEquals("Number of buddies", 4, model.getSize()); resetState(); // A dummy change doing nothing should not invoke anything model.setOnline("hubbaduu", true); assertFalse("intervalAdded() should not be called", intervalAddedFlag); assertFalse("intervalRemoved() should not be called", intervalRemovedFlag); assertFalse("contentsChanged() should not be called", contentsChangedFlag); // dumdiduu should become last if set offline model.setOnline("dumdiduu", false); assertEquals("Number of buddies should not change", 4, model.getSize()); assertTrue("contentsChanged() should be called", contentsChangedFlag); assertFalse("intervalAdded() should not be called", intervalAddedFlag); assertFalse("intervalRemoved() should not be called", intervalRemovedFlag); // interval; dumdiduu moved from second to the last assertEquals(1, Math.min(index0, index1)); assertEquals(3, Math.max(index0, index1)); resetState(); // alibaba should become first if set online model.setOnline("alibaba", true); assertEquals("Number of buddies should not change", 4, model.getSize()); assertTrue("contentsChanged() should be called", contentsChangedFlag); assertFalse("intervalAdded() should not be called", intervalAddedFlag); assertFalse("intervalRemoved() should not be called", intervalRemovedFlag); // interval; alibaba moved from second last to first assertEquals(0, Math.min(index0, index1)); assertEquals(2, Math.max(index0, index1)); // Check the final order assertEquals("alibaba", getBuddy(model, 0).getName()); assertEquals("daibaduu", getBuddy(model, 1).getName()); assertEquals("hubbaduu", getBuddy(model, 2).getName()); assertEquals("dumdiduu", getBuddy(model, 3).getName()); }
void function() { BuddyListModel model = new BuddyListModel(); model.addListDataListener(this); model.setOnline(STR, true); model.setOnline(STR, true); model.setOnline(STR, true); model.setOnline(STR, false); assertEquals(STR, 4, model.getSize()); resetState(); model.setOnline(STR, true); assertFalse(STR, intervalAddedFlag); assertFalse(STR, intervalRemovedFlag); assertFalse(STR, contentsChangedFlag); model.setOnline(STR, false); assertEquals(STR, 4, model.getSize()); assertTrue(STR, contentsChangedFlag); assertFalse(STR, intervalAddedFlag); assertFalse(STR, intervalRemovedFlag); assertEquals(1, Math.min(index0, index1)); assertEquals(3, Math.max(index0, index1)); resetState(); model.setOnline(STR, true); assertEquals(STR, 4, model.getSize()); assertTrue(STR, contentsChangedFlag); assertFalse(STR, intervalAddedFlag); assertFalse(STR, intervalRemovedFlag); assertEquals(0, Math.min(index0, index1)); assertEquals(2, Math.max(index0, index1)); assertEquals(STR, getBuddy(model, 0).getName()); assertEquals(STR, getBuddy(model, 1).getName()); assertEquals(STR, getBuddy(model, 2).getName()); assertEquals(STR, getBuddy(model, 3).getName()); }
/** * Test changing status of already added buddies. */
Test changing status of already added buddies
testChangeState
{ "repo_name": "AntumDeluge/arianne-stendhal", "path": "tests/games/stendhal/client/gui/buddies/BuddyListModelTest.java", "license": "gpl-2.0", "size": 9681 }
[ "org.junit.Assert" ]
import org.junit.Assert;
import org.junit.*;
[ "org.junit" ]
org.junit;
269,684
public void setExecutorService(final ExecutorService executorService) { Assert.notNull(executorService); EXECUTOR_SERVICE = executorService; }
void function(final ExecutorService executorService) { Assert.notNull(executorService); EXECUTOR_SERVICE = executorService; }
/** * Note that changing this executor will affect all httpClients. While not ideal, this change was made because certain ticket registries * were persisting the HttpClient and thus getting serializable exceptions. * @param executorService */
Note that changing this executor will affect all httpClients. While not ideal, this change was made because certain ticket registries were persisting the HttpClient and thus getting serializable exceptions
setExecutorService
{ "repo_name": "ConnCollege/cas", "path": "cas-server-core/src/main/java/org/jasig/cas/util/HttpClient.java", "license": "bsd-3-clause", "size": 10144 }
[ "java.util.concurrent.ExecutorService", "org.springframework.util.Assert" ]
import java.util.concurrent.ExecutorService; import org.springframework.util.Assert;
import java.util.concurrent.*; import org.springframework.util.*;
[ "java.util", "org.springframework.util" ]
java.util; org.springframework.util;
2,833,083
static FeedImage getFeedImage(PodDBAdapter adapter, final long id) { Cursor cursor = adapter.getImageCursor(id); try { if ((cursor.getCount() == 0) || !cursor.moveToFirst()) { return null; } FeedImage image = FeedImage.fromCursor(cursor); image.setId(id); return image; } finally { cursor.close(); } }
static FeedImage getFeedImage(PodDBAdapter adapter, final long id) { Cursor cursor = adapter.getImageCursor(id); try { if ((cursor.getCount() == 0) !cursor.moveToFirst()) { return null; } FeedImage image = FeedImage.fromCursor(cursor); image.setId(id); return image; } finally { cursor.close(); } }
/** * Searches the DB for a FeedImage of the given id. * * @param id The id of the object * @return The found object */
Searches the DB for a FeedImage of the given id
getFeedImage
{ "repo_name": "TomHennen/AntennaPod", "path": "core/src/main/java/de/danoeh/antennapod/core/storage/DBReader.java", "license": "mit", "size": 37122 }
[ "android.database.Cursor", "de.danoeh.antennapod.core.feed.FeedImage" ]
import android.database.Cursor; import de.danoeh.antennapod.core.feed.FeedImage;
import android.database.*; import de.danoeh.antennapod.core.feed.*;
[ "android.database", "de.danoeh.antennapod" ]
android.database; de.danoeh.antennapod;
1,237,854
public Item getItem(World p_149694_1_, int p_149694_2_, int p_149694_3_, int p_149694_4_) { return Item.getItemById(0); }
Item function(World p_149694_1_, int p_149694_2_, int p_149694_3_, int p_149694_4_) { return Item.getItemById(0); }
/** * Gets an item for the block being called on. Args: world, x, y, z */
Gets an item for the block being called on. Args: world, x, y, z
getItem
{ "repo_name": "mviitanen/marsmod", "path": "mcp/src/minecraft/net/minecraft/block/BlockEndPortal.java", "license": "gpl-2.0", "size": 3925 }
[ "net.minecraft.item.Item", "net.minecraft.world.World" ]
import net.minecraft.item.Item; import net.minecraft.world.World;
import net.minecraft.item.*; import net.minecraft.world.*;
[ "net.minecraft.item", "net.minecraft.world" ]
net.minecraft.item; net.minecraft.world;
478,107
private void registerObjective(final ILPObjective objective) { for (int variableId : objective.getLinearExpression().getVariables()) { double coefficient = objective.getLinearExpression().getCoefficient(variableId); while (Math.abs(coefficient - ((long) coefficient)) >= 0.00000000001) { objective.getLinearExpression().multiplyBy(10); coefficient = objective.getLinearExpression().getCoefficient(variableId); } } ILPLinearExpression expr = objective.getLinearExpression(); switch (objective.getObjectiveOperation()) { case maximize: ILPLinearExpression invertedExpression = this.ilpProblem.createLinearExpression(); for (int variableId : objective.getLinearExpression().getVariables()) { double coefficient = objective.getLinearExpression().getCoefficient(variableId); invertedExpression.addTerm(variableId, -coefficient); } expr = invertedExpression; break; case minimize: break; default: throw new IllegalArgumentException( "Unsupported comparator: " + objective.getObjectiveOperation().toString()); } IVecInt literals = this.getLiterals(expr); IVec<BigInteger> coeffs = this.getCoefs(expr); this.solver.setObjectiveFunction(new ObjectiveFunction(literals, coeffs)); }
void function(final ILPObjective objective) { for (int variableId : objective.getLinearExpression().getVariables()) { double coefficient = objective.getLinearExpression().getCoefficient(variableId); while (Math.abs(coefficient - ((long) coefficient)) >= 0.00000000001) { objective.getLinearExpression().multiplyBy(10); coefficient = objective.getLinearExpression().getCoefficient(variableId); } } ILPLinearExpression expr = objective.getLinearExpression(); switch (objective.getObjectiveOperation()) { case maximize: ILPLinearExpression invertedExpression = this.ilpProblem.createLinearExpression(); for (int variableId : objective.getLinearExpression().getVariables()) { double coefficient = objective.getLinearExpression().getCoefficient(variableId); invertedExpression.addTerm(variableId, -coefficient); } expr = invertedExpression; break; case minimize: break; default: throw new IllegalArgumentException( STR + objective.getObjectiveOperation().toString()); } IVecInt literals = this.getLiterals(expr); IVec<BigInteger> coeffs = this.getCoefs(expr); this.solver.setObjectiveFunction(new ObjectiveFunction(literals, coeffs)); }
/** * Register the objective for SAT4J */
Register the objective for SAT4J
registerObjective
{ "repo_name": "eMoflon/emoflon-ibex", "path": "org.emoflon.ibex.tgg.core.runtime/src/org/emoflon/ibex/tgg/util/ilp/Sat4JWrapper.java", "license": "gpl-3.0", "size": 8988 }
[ "java.math.BigInteger", "org.emoflon.ibex.tgg.util.ilp.ILPProblem", "org.sat4j.pb.ObjectiveFunction", "org.sat4j.specs.IVec", "org.sat4j.specs.IVecInt" ]
import java.math.BigInteger; import org.emoflon.ibex.tgg.util.ilp.ILPProblem; import org.sat4j.pb.ObjectiveFunction; import org.sat4j.specs.IVec; import org.sat4j.specs.IVecInt;
import java.math.*; import org.emoflon.ibex.tgg.util.ilp.*; import org.sat4j.pb.*; import org.sat4j.specs.*;
[ "java.math", "org.emoflon.ibex", "org.sat4j.pb", "org.sat4j.specs" ]
java.math; org.emoflon.ibex; org.sat4j.pb; org.sat4j.specs;
2,061,614
Model getModel() throws SolverException;
Model getModel() throws SolverException;
/** * Get a satisfying assignment. * This should be called only immediately after an {@link #isUnsat()} call that returned <code>false</code>. */
Get a satisfying assignment. This should be called only immediately after an <code>#isUnsat()</code> call that returned <code>false</code>
getModel
{ "repo_name": "TommesDee/cpachecker", "path": "src/org/sosy_lab/cpachecker/util/predicates/interfaces/InterpolatingProverEnvironment.java", "license": "apache-2.0", "size": 2775 }
[ "org.sosy_lab.cpachecker.core.Model", "org.sosy_lab.cpachecker.exceptions.SolverException" ]
import org.sosy_lab.cpachecker.core.Model; import org.sosy_lab.cpachecker.exceptions.SolverException;
import org.sosy_lab.cpachecker.core.*; import org.sosy_lab.cpachecker.exceptions.*;
[ "org.sosy_lab.cpachecker" ]
org.sosy_lab.cpachecker;
1,614,805
public void killTask(TaskAttemptID taskId) throws IOException { ensureState(JobState.RUNNING); info.killTask(org.apache.hadoop.mapred.TaskAttemptID.downgrade(taskId), false); }
void function(TaskAttemptID taskId) throws IOException { ensureState(JobState.RUNNING); info.killTask(org.apache.hadoop.mapred.TaskAttemptID.downgrade(taskId), false); }
/** * Kill indicated task attempt. * * @param taskId the id of the task to be terminated. * @throws IOException */
Kill indicated task attempt
killTask
{ "repo_name": "zincumyx/Mammoth", "path": "mammoth-src/src/mapred/org/apache/hadoop/mapreduce/Job.java", "license": "apache-2.0", "size": 16404 }
[ "java.io.IOException", "org.apache.hadoop.mapreduce.TaskAttemptID" ]
import java.io.IOException; import org.apache.hadoop.mapreduce.TaskAttemptID;
import java.io.*; import org.apache.hadoop.mapreduce.*;
[ "java.io", "org.apache.hadoop" ]
java.io; org.apache.hadoop;
2,775,022
public int countBooks(String bookshelf) { int result = 0; try { if (bookshelf.equals("")) { return countBooks(); } String sql = "SELECT count(DISTINCT b._id) as count " + " FROM " + DB_TB_BOOKSHELF + " bs " + " Join " + DB_TB_BOOK_BOOKSHELF_WEAK + " bbs " + " On bbs." + KEY_BOOKSHELF + " = bs." + KEY_ROWID + " Join " + DB_TB_BOOKS + " b " + " On bbs." + KEY_BOOK + " = b." + KEY_ROWID + " WHERE " + makeTextTerm("bs." + KEY_BOOKSHELF, "=", bookshelf); Cursor count = mDb.rawQuery(sql, new String[]{}); count.moveToNext(); result = count.getInt(0); count.close(); } catch (IllegalStateException e) { Logger.logError(e); } return result; }
int function(String bookshelf) { int result = 0; try { if (bookshelf.equals(STRSELECT count(DISTINCT b._id) as count STR FROM STR bs STR Join STR bbs STR On bbs.STR = bs.STR Join STR b STR On bbs.STR = b.STR WHERE STRbs.STR=", bookshelf); Cursor count = mDb.rawQuery(sql, new String[]{}); count.moveToNext(); result = count.getInt(0); count.close(); } catch (IllegalStateException e) { Logger.logError(e); } return result; }
/** * Return the number of books * * @param string bookshelf the bookshelf the search within * @return int The number of books */
Return the number of books
countBooks
{ "repo_name": "gvmelle/Book-Catalogue", "path": "src/com/eleybourn/bookcatalogue/CatalogueDBAdapter.java", "license": "gpl-3.0", "size": 238306 }
[ "android.database.Cursor", "com.eleybourn.bookcatalogue.utils.Logger" ]
import android.database.Cursor; import com.eleybourn.bookcatalogue.utils.Logger;
import android.database.*; import com.eleybourn.bookcatalogue.utils.*;
[ "android.database", "com.eleybourn.bookcatalogue" ]
android.database; com.eleybourn.bookcatalogue;
2,429,859
@Schema(description = "Total amount of existing files uploaded with this share.") public Integer getCntFiles() { return cntFiles; }
@Schema(description = STR) Integer function() { return cntFiles; }
/** * Total amount of existing files uploaded with this share. * @return cntFiles **/
Total amount of existing files uploaded with this share
getCntFiles
{ "repo_name": "iterate-ch/cyberduck", "path": "dracoon/src/main/java/ch/cyberduck/core/sds/io/swagger/client/model/UploadShare.java", "license": "gpl-3.0", "size": 19372 }
[ "io.swagger.v3.oas.annotations.media.Schema" ]
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.media.*;
[ "io.swagger.v3" ]
io.swagger.v3;
254,829
public static DocumentContent fromDocument(Project project, Document document) { return new DocumentContent(project, document); }
static DocumentContent function(Project project, Document document) { return new DocumentContent(project, document); }
/** * Creates DiffContent associated with given document * * @param project * @param document * @return content associated with document */
Creates DiffContent associated with given document
fromDocument
{ "repo_name": "consulo/consulo", "path": "modules/base/diff-api/src/main/java/com/intellij/openapi/diff/DiffContent.java", "license": "apache-2.0", "size": 4734 }
[ "com.intellij.openapi.editor.Document", "com.intellij.openapi.project.Project" ]
import com.intellij.openapi.editor.Document; import com.intellij.openapi.project.Project;
import com.intellij.openapi.editor.*; import com.intellij.openapi.project.*;
[ "com.intellij.openapi" ]
com.intellij.openapi;
2,181,156
@Generated @Selector("setRequiresPhoneNumber:") public native void setRequiresPhoneNumber(boolean value);
@Selector(STR) native void function(boolean value);
/** * YES means a phone number required to book. Defaults to NO. */
YES means a phone number required to book. Defaults to NO
setRequiresPhoneNumber
{ "repo_name": "multi-os-engine/moe-core", "path": "moe.apple/moe.platform.ios/src/main/java/apple/intents/INRestaurantReservationBooking.java", "license": "apache-2.0", "size": 9731 }
[ "org.moe.natj.objc.ann.Selector" ]
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.ann.*;
[ "org.moe.natj" ]
org.moe.natj;
2,095,643
public static XPath newXPath() { XPath xpath = sFactory.newXPath(); xpath.setNamespaceContext(AndroidNamespaceContext.getDefault()); return xpath; }
static XPath function() { XPath xpath = sFactory.newXPath(); xpath.setNamespaceContext(AndroidNamespaceContext.getDefault()); return xpath; }
/** * Creates a new XPath object using the default prefix for the android * namespace. * * @see #DEFAULT_NS_PREFIX */
Creates a new XPath object using the default prefix for the android namespace
newXPath
{ "repo_name": "titze/axmlparser", "path": "src/axmlprinter/AndroidXPathFactory.java", "license": "apache-2.0", "size": 2564 }
[ "javax.xml.xpath.XPath" ]
import javax.xml.xpath.XPath;
import javax.xml.xpath.*;
[ "javax.xml" ]
javax.xml;
2,417,721
public Intent putExtra(String name, byte[] value) { if (mExtras == null) { mExtras = new Bundle(); } mExtras.putByteArray(name, value); return this; }
Intent function(String name, byte[] value) { if (mExtras == null) { mExtras = new Bundle(); } mExtras.putByteArray(name, value); return this; }
/** * Add extended data to the intent. The name must include a package * prefix, for example the app com.android.contacts would use names * like "com.android.contacts.ShowAll". * * @param name The name of the extra data, with package prefix. * @param value The byte array data value. * * @return Returns the same Intent object, for chaining multiple calls * into a single statement. * * @see #putExtras * @see #removeExtra * @see #getByteArrayExtra(String) */
Add extended data to the intent. The name must include a package prefix, for example the app com.android.contacts would use names like "com.android.contacts.ShowAll"
putExtra
{ "repo_name": "indashnet/InDashNet.Open.UN2000", "path": "android/frameworks/base/core/java/android/content/Intent.java", "license": "apache-2.0", "size": 299722 }
[ "android.os.Bundle" ]
import android.os.Bundle;
import android.os.*;
[ "android.os" ]
android.os;
981,348
public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) { }
void function(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) { }
/** * Sets the raw JSON object * * @param serializer the serializer * @param json the JSON object to set this object to */
Sets the raw JSON object
setRawObject
{ "repo_name": "microsoftgraph/msgraph-sdk-java", "path": "src/main/java/com/microsoft/graph/models/WorkbookRangeReference.java", "license": "mit", "size": 1815 }
[ "com.google.gson.JsonObject", "com.microsoft.graph.serializer.ISerializer", "javax.annotation.Nonnull" ]
import com.google.gson.JsonObject; import com.microsoft.graph.serializer.ISerializer; import javax.annotation.Nonnull;
import com.google.gson.*; import com.microsoft.graph.serializer.*; import javax.annotation.*;
[ "com.google.gson", "com.microsoft.graph", "javax.annotation" ]
com.google.gson; com.microsoft.graph; javax.annotation;
1,055,254
@Override public void markAsAlive(Node node, boolean isMaster, String restTransportAddress) { node.getFields().put("last_seen", Tools.getUTCTimestamp()); node.getFields().put("is_master", isMaster); node.getFields().put("transport_address", restTransportAddress); try { save(node); } catch (ValidationException e) { throw new RuntimeException("Validation failed.", e); } }
void function(Node node, boolean isMaster, String restTransportAddress) { node.getFields().put(STR, Tools.getUTCTimestamp()); node.getFields().put(STR, isMaster); node.getFields().put(STR, restTransportAddress); try { save(node); } catch (ValidationException e) { throw new RuntimeException(STR, e); } }
/** * Mark this node as alive and probably update some settings that may have changed since last server boot. * * @param isMaster * @param restTransportAddress */
Mark this node as alive and probably update some settings that may have changed since last server boot
markAsAlive
{ "repo_name": "berkeleydave/graylog2-server", "path": "graylog2-server/src/main/java/org/graylog2/cluster/NodeServiceImpl.java", "license": "gpl-3.0", "size": 6006 }
[ "org.graylog2.plugin.Tools", "org.graylog2.plugin.database.ValidationException" ]
import org.graylog2.plugin.Tools; import org.graylog2.plugin.database.ValidationException;
import org.graylog2.plugin.*; import org.graylog2.plugin.database.*;
[ "org.graylog2.plugin" ]
org.graylog2.plugin;
109,177
private static int getLength(byte [] bytes, int offset) { return (2 * Bytes.SIZEOF_INT) + Bytes.toInt(bytes, offset) + Bytes.toInt(bytes, offset + Bytes.SIZEOF_INT); }
static int function(byte [] bytes, int offset) { return (2 * Bytes.SIZEOF_INT) + Bytes.toInt(bytes, offset) + Bytes.toInt(bytes, offset + Bytes.SIZEOF_INT); }
/** * Determines the total length of the KeyValue stored in the specified * byte array and offset. Includes all headers. * @param bytes byte array * @param offset offset to start of the KeyValue * @return length of entire KeyValue, in bytes */
Determines the total length of the KeyValue stored in the specified byte array and offset. Includes all headers
getLength
{ "repo_name": "lifeng5042/RStore", "path": "src/org/apache/hadoop/hbase/KeyValue.java", "license": "gpl-2.0", "size": 67894 }
[ "org.apache.hadoop.hbase.util.Bytes" ]
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.*;
[ "org.apache.hadoop" ]
org.apache.hadoop;
2,128,084
@Test public void testDeleteNonExistentEntity() { Object a = createTopLevelObject(); assignPK(a); Object id = getIdForLookup(a); assertNull(provider.find((Class<Object>)a.getClass(), id)); provider.delete(a); assertNull(provider.find((Class<Object>)a.getClass(), id)); }
void function() { Object a = createTopLevelObject(); assignPK(a); Object id = getIdForLookup(a); assertNull(provider.find((Class<Object>)a.getClass(), id)); provider.delete(a); assertNull(provider.find((Class<Object>)a.getClass(), id)); }
/** * Tests that deletion of a non-existent detached object does not result in a save of the object * via merge. */
Tests that deletion of a non-existent detached object does not result in a save of the object via merge
testDeleteNonExistentEntity
{ "repo_name": "jruchcolo/rice-cd", "path": "rice-framework/krad-it/src/test/java/org/kuali/rice/krad/data/jpa/JpaPersistenceProviderTest.java", "license": "apache-2.0", "size": 27776 }
[ "org.junit.Assert" ]
import org.junit.Assert;
import org.junit.*;
[ "org.junit" ]
org.junit;
2,049,701
private static boolean canBeSerialized(Serializable o) { ByteArrayOutputStream baos = null; ObjectOutputStream out = null; try { baos = new ByteArrayOutputStream(512); out = new ObjectOutputStream(baos); out.writeObject((Serializable) o); return true; } catch (IOException e) { LOG.warn("error serializing object" , e); } finally { try { if (baos != null) { try { baos.close(); } catch (IOException e) { LOG.warn("error closing stream" , e); } } } finally { if (out != null) { try { out.close(); } catch (IOException e) { LOG.warn("error closing stream" , e); } } } } return false; }
static boolean function(Serializable o) { ByteArrayOutputStream baos = null; ObjectOutputStream out = null; try { baos = new ByteArrayOutputStream(512); out = new ObjectOutputStream(baos); out.writeObject((Serializable) o); return true; } catch (IOException e) { LOG.warn(STR , e); } finally { try { if (baos != null) { try { baos.close(); } catch (IOException e) { LOG.warn(STR , e); } } } finally { if (out != null) { try { out.close(); } catch (IOException e) { LOG.warn(STR , e); } } } } return false; }
/** * Performs an expensive test of serializability by attempting to serialize the object graph */
Performs an expensive test of serializability by attempting to serialize the object graph
canBeSerialized
{ "repo_name": "ua-eas/ua-rice-2.1.9", "path": "krad/krad-web-framework/src/main/java/org/kuali/rice/krad/web/session/NonSerializableSessionListener.java", "license": "apache-2.0", "size": 5678 }
[ "java.io.ByteArrayOutputStream", "java.io.IOException", "java.io.ObjectOutputStream", "java.io.Serializable" ]
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable;
import java.io.*;
[ "java.io" ]
java.io;
654,600
private Chapter fromFile() { assert file != null; // Ensure File is actually a file. if (!file.isFile()) { Util.logf(C.MISSING_CHAP_FILE, story.getTitle(), number); return null; } // Read the contents of the file into a String. Util.loudf(C.READING_CHAP_FILE, file.getName()); String contents; try { contents = Files.toString(file, StandardCharsets.UTF_8); } catch (IOException e) { // Issues while reading the file. Util.logf(C.MALFORMED_CHAP_FILE, story.getTitle(), number); return null; } if (runThroughParser) { // Run the contents through Jsoup to ensure it's valid HTML. try { contents = Jsoup.parseBodyFragment(contents).body().html().trim(); } catch (Exception e) { // Issue while parsing the HTML string. Util.logf(C.MALFORMED_CHAP_FILE, story.getTitle(), number); return null; } } // Create a Chapter object using the contents of the file. return new Chapter(story, contents, number); }
Chapter function() { assert file != null; if (!file.isFile()) { Util.logf(C.MISSING_CHAP_FILE, story.getTitle(), number); return null; } Util.loudf(C.READING_CHAP_FILE, file.getName()); String contents; try { contents = Files.toString(file, StandardCharsets.UTF_8); } catch (IOException e) { Util.logf(C.MALFORMED_CHAP_FILE, story.getTitle(), number); return null; } if (runThroughParser) { try { contents = Jsoup.parseBodyFragment(contents).body().html().trim(); } catch (Exception e) { Util.logf(C.MALFORMED_CHAP_FILE, story.getTitle(), number); return null; } } return new Chapter(story, contents, number); }
/** * Get a {@link Chapter} from a File. * @return New {@link Chapter}, or null if we had issues. */
Get a <code>Chapter</code> from a File
fromFile
{ "repo_name": "bkromhout/FictionDL", "path": "FictionDL/src/main/java/bkromhout/fdl/chapter/ChapterSource.java", "license": "mit", "size": 5998 }
[ "com.google.common.io.Files", "java.io.IOException", "java.nio.charset.StandardCharsets", "org.jsoup.Jsoup" ]
import com.google.common.io.Files; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.jsoup.Jsoup;
import com.google.common.io.*; import java.io.*; import java.nio.charset.*; import org.jsoup.*;
[ "com.google.common", "java.io", "java.nio", "org.jsoup" ]
com.google.common; java.io; java.nio; org.jsoup;
840,324
private ParseEvent.Started postParseStartEvent( Iterable<BuildTarget> buildTargets, BuckEventBus eventBus) { ParseEvent.Started started = ParseEvent.started(buildTargets); if (parseStartEvent.isPresent()) { eventBus.post(started, parseStartEvent.get()); } else { eventBus.post(started); } return started; }
ParseEvent.Started function( Iterable<BuildTarget> buildTargets, BuckEventBus eventBus) { ParseEvent.Started started = ParseEvent.started(buildTargets); if (parseStartEvent.isPresent()) { eventBus.post(started, parseStartEvent.get()); } else { eventBus.post(started); } return started; }
/** * Post a ParseStart event to eventBus, using the start of WatchEvent processing as the start * time if applicable. */
Post a ParseStart event to eventBus, using the start of WatchEvent processing as the start time if applicable
postParseStartEvent
{ "repo_name": "mnuessler/buck", "path": "src/com/facebook/buck/parser/Parser.java", "license": "apache-2.0", "size": 52742 }
[ "com.facebook.buck.event.BuckEventBus", "com.facebook.buck.model.BuildTarget" ]
import com.facebook.buck.event.BuckEventBus; import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.event.*; import com.facebook.buck.model.*;
[ "com.facebook.buck" ]
com.facebook.buck;
2,481,464
public void sendEmail(final String theTo, final String theFrom, final String theSubject, final String theContent) { if (null == smtpServerSetup) { throw new IllegalStateException("Can not send mail, no SMTP or SMTPS setup found"); } GreenMailUtil.sendTextEmail(theTo, theFrom, theSubject, theContent, smtpServerSetup); }
void function(final String theTo, final String theFrom, final String theSubject, final String theContent) { if (null == smtpServerSetup) { throw new IllegalStateException(STR); } GreenMailUtil.sendTextEmail(theTo, theFrom, theSubject, theContent, smtpServerSetup); }
/** * Sends a mail message to the GreenMail server. * <p/> * Note: SMTP or SMTPS must be configured. * * @param theTo the <em>TO</em> field. * @param theFrom the <em>FROM</em>field. * @param theSubject the subject. * @param theContent the message content. */
Sends a mail message to the GreenMail server. Note: SMTP or SMTPS must be configured
sendEmail
{ "repo_name": "buildscientist/greenmail", "path": "greenmail-spring/src/main/java/com/icegreen/greenmail/spring/GreenMailBean.java", "license": "apache-2.0", "size": 11858 }
[ "com.icegreen.greenmail.util.GreenMailUtil" ]
import com.icegreen.greenmail.util.GreenMailUtil;
import com.icegreen.greenmail.util.*;
[ "com.icegreen.greenmail" ]
com.icegreen.greenmail;
2,381,949
ReadDB getDb();
ReadDB getDb();
/** * Get the database handle. * * @return {@link ReadDB} reference */
Get the database handle
getDb
{ "repo_name": "sirixdb/sirix", "path": "bundles/sirix-gui/src/main/java/org/sirix/gui/view/model/interfaces/Model.java", "license": "bsd-3-clause", "size": 5803 }
[ "org.sirix.gui.ReadDB" ]
import org.sirix.gui.ReadDB;
import org.sirix.gui.*;
[ "org.sirix.gui" ]
org.sirix.gui;
1,496,233
private boolean doNextWithExceptionHandler(K key, V value) throws IOException { try { return curReader.next(key, value); } catch (Exception e) { return HiveIOExceptionHandlerUtil .handleRecordReaderNextException(e, jc); } }
boolean function(K key, V value) throws IOException { try { return curReader.next(key, value); } catch (Exception e) { return HiveIOExceptionHandlerUtil .handleRecordReaderNextException(e, jc); } }
/** * do next and handle exception inside it. * @param key * @param value * @return * @throws IOException */
do next and handle exception inside it
doNextWithExceptionHandler
{ "repo_name": "alanfgates/hive", "path": "shims/common/src/main/java/org/apache/hadoop/hive/shims/HadoopShimsSecure.java", "license": "apache-2.0", "size": 12520 }
[ "java.io.IOException", "org.apache.hadoop.hive.io.HiveIOExceptionHandlerUtil" ]
import java.io.IOException; import org.apache.hadoop.hive.io.HiveIOExceptionHandlerUtil;
import java.io.*; import org.apache.hadoop.hive.io.*;
[ "java.io", "org.apache.hadoop" ]
java.io; org.apache.hadoop;
303,088
public static Map<String, String> serializeProperties(Properties props) { Map<String, String> infoAsString = new HashMap<>(); for (Map.Entry<Object, Object> entry : props.entrySet()) { // Determine if this is a property we want to forward to the server boolean localProperty = false; for (BuiltInConnectionProperty prop : BuiltInConnectionProperty.values()) { if (prop.camelName().equals(entry.getKey())) { localProperty = true; break; } } if (!localProperty) { infoAsString.put(entry.getKey().toString(), entry.getValue().toString()); } } return infoAsString; }
static Map<String, String> function(Properties props) { Map<String, String> infoAsString = new HashMap<>(); for (Map.Entry<Object, Object> entry : props.entrySet()) { boolean localProperty = false; for (BuiltInConnectionProperty prop : BuiltInConnectionProperty.values()) { if (prop.camelName().equals(entry.getKey())) { localProperty = true; break; } } if (!localProperty) { infoAsString.put(entry.getKey().toString(), entry.getValue().toString()); } } return infoAsString; }
/** * Serializes the necessary properties into a Map. * * @param props The properties to serialize. * @return A representation of the Properties as a Map. */
Serializes the necessary properties into a Map
serializeProperties
{ "repo_name": "joshelser/incubator-calcite", "path": "avatica/src/main/java/org/apache/calcite/avatica/remote/Service.java", "license": "apache-2.0", "size": 90257 }
[ "java.util.HashMap", "java.util.Map", "java.util.Properties", "org.apache.calcite.avatica.BuiltInConnectionProperty" ]
import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.apache.calcite.avatica.BuiltInConnectionProperty;
import java.util.*; import org.apache.calcite.avatica.*;
[ "java.util", "org.apache.calcite" ]
java.util; org.apache.calcite;
1,472,896
private static void validatePage(Document page) { Elements errorDivs = page.select("div[class*=error_message]"); String errorMessage = null; if (!errorDivs.isEmpty()) { errorMessage = errorDivs.first().text().replaceAll("\\s+", " ") .replaceAll(" Show Error Details", ":").trim(); } else { errorDivs = page.select("div[class*=message]"); if (!errorDivs.isEmpty()) { errorMessage = errorDivs.first().text(); } } if (!errorDivs.isEmpty()) { throw new IllegalArgumentException("Error authorizing application: " + errorMessage); } }
static void function(Document page) { Elements errorDivs = page.select(STR); String errorMessage = null; if (!errorDivs.isEmpty()) { errorMessage = errorDivs.first().text().replaceAll("\\s+", " ") .replaceAll(STR, ":").trim(); } else { errorDivs = page.select(STR); if (!errorDivs.isEmpty()) { errorMessage = errorDivs.first().text(); } } if (!errorDivs.isEmpty()) { throw new IllegalArgumentException(STR + errorMessage); } }
/** * Validation of page: * - detects invalid credentials error * - detects wrong clientId error */
Validation of page: - detects invalid credentials error - detects wrong clientId error
validatePage
{ "repo_name": "punkhorn/camel-upstream", "path": "components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/internal/BoxConnectionHelper.java", "license": "apache-2.0", "size": 12358 }
[ "org.jsoup.nodes.Document", "org.jsoup.select.Elements" ]
import org.jsoup.nodes.Document; import org.jsoup.select.Elements;
import org.jsoup.nodes.*; import org.jsoup.select.*;
[ "org.jsoup.nodes", "org.jsoup.select" ]
org.jsoup.nodes; org.jsoup.select;
723,057
static SecretKey getSharedKey(NetLoginHandler par0NetLoginHandler) { return par0NetLoginHandler.sharedKey; }
static SecretKey getSharedKey(NetLoginHandler par0NetLoginHandler) { return par0NetLoginHandler.sharedKey; }
/** * Return the secret AES sharedKey */
Return the secret AES sharedKey
getSharedKey
{ "repo_name": "LolololTrololol/InsertNameHere", "path": "minecraft/net/minecraft/src/NetLoginHandler.java", "license": "gpl-2.0", "size": 9906 }
[ "javax.crypto.SecretKey" ]
import javax.crypto.SecretKey;
import javax.crypto.*;
[ "javax.crypto" ]
javax.crypto;
2,467,952
private void doFinish(String containerName, String fileName, IProgressMonitor monitor) { // create a sample file monitor.beginTask("Creating " + fileName, 2); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(new Path(containerName)); if (!resource.exists() || !(resource instanceof IContainer)) { throwCoreException( "Container \"" + containerName + "\" does not exist."); } IContainer container = (IContainer) resource; final IFile file = container.getFile(new Path(fileName)); try { InputStream stream = openContentStream(); if (file.exists()) { try { file.setContents(stream, true, true, monitor); } catch (CoreException e) { throw new RuntimeException(e); } } else { try { file.create(stream, true, monitor); } catch (CoreException e) { throw new RuntimeException(e); } } stream.close(); } catch (IOException e) { throw new RuntimeException(e); }
void function(String containerName, String fileName, IProgressMonitor monitor) { monitor.beginTask(STR + fileName, 2); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(new Path(containerName)); if (!resource.exists() !(resource instanceof IContainer)) { throwCoreException( STRSTR\STR); } IContainer container = (IContainer) resource; final IFile file = container.getFile(new Path(fileName)); try { InputStream stream = openContentStream(); if (file.exists()) { try { file.setContents(stream, true, true, monitor); } catch (CoreException e) { throw new RuntimeException(e); } } else { try { file.create(stream, true, monitor); } catch (CoreException e) { throw new RuntimeException(e); } } stream.close(); } catch (IOException e) { throw new RuntimeException(e); }
/** * The worker method. It will find the container, create the file if missing * or just replace its contents, and open the editor on the newly created * file. */
The worker method. It will find the container, create the file if missing or just replace its contents, and open the editor on the newly created file
doFinish
{ "repo_name": "veltzer/demos-java", "path": "projects/RcpView/src/com/example/addressbook/view/wizards/AddressBookWizard.java", "license": "gpl-3.0", "size": 5269 }
[ "java.io.IOException", "java.io.InputStream", "org.eclipse.core.resources.IContainer", "org.eclipse.core.resources.IFile", "org.eclipse.core.resources.IResource", "org.eclipse.core.resources.IWorkspaceRoot", "org.eclipse.core.resources.ResourcesPlugin", "org.eclipse.core.runtime.CoreException", "org.eclipse.core.runtime.IProgressMonitor", "org.eclipse.core.runtime.Path" ]
import java.io.IOException; import java.io.InputStream; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path;
import java.io.*; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*;
[ "java.io", "org.eclipse.core" ]
java.io; org.eclipse.core;
1,992,163
private String getIdFromSTR(OMElement refElem) { //ASSUMPTION:SecurityTokenReference/KeyIdentifier OMElement child = refElem.getFirstElement(); if(child == null) { return null; } if (child.getQName().equals(new QName(WSConstants.SIG_NS, "KeyInfo")) || child.getQName().equals(new QName(WSConstants.WSSE_NS, "KeyIdentifier"))) { return child.getText(); } else if(child.getQName().equals(Reference.TOKEN)) { return child.getAttributeValue(new QName("URI")); } else { return null; } }
String function(OMElement refElem) { OMElement child = refElem.getFirstElement(); if(child == null) { return null; } if (child.getQName().equals(new QName(WSConstants.SIG_NS, STR)) child.getQName().equals(new QName(WSConstants.WSSE_NS, STR))) { return child.getText(); } else if(child.getQName().equals(Reference.TOKEN)) { return child.getAttributeValue(new QName("URI")); } else { return null; } }
/** * Process the given STR to find the id it refers to * * @param refElem * @return id */
Process the given STR to find the id it refers to
getIdFromSTR
{ "repo_name": "maheshika/wso2-rampart", "path": "modules/rampart-trust/src/main/java/org/apache/rahas/client/STSClient.java", "license": "apache-2.0", "size": 36754 }
[ "javax.xml.namespace.QName", "org.apache.axiom.om.OMElement", "org.apache.ws.security.WSConstants", "org.apache.ws.security.message.token.Reference" ]
import javax.xml.namespace.QName; import org.apache.axiom.om.OMElement; import org.apache.ws.security.WSConstants; import org.apache.ws.security.message.token.Reference;
import javax.xml.namespace.*; import org.apache.axiom.om.*; import org.apache.ws.security.*; import org.apache.ws.security.message.token.*;
[ "javax.xml", "org.apache.axiom", "org.apache.ws" ]
javax.xml; org.apache.axiom; org.apache.ws;
2,174,130
//----------------------------------------------------------------------- public MetaProperty<Double> expiry() { return expiry; }
MetaProperty<Double> function() { return expiry; }
/** * The meta-property for the {@code expiry} property. * @return the meta-property, not null */
The meta-property for the expiry property
expiry
{ "repo_name": "OpenGamma/Strata", "path": "modules/pricer/src/main/java/com/opengamma/strata/pricer/fxopt/SmileDeltaParameters.java", "license": "apache-2.0", "size": 27328 }
[ "org.joda.beans.MetaProperty" ]
import org.joda.beans.MetaProperty;
import org.joda.beans.*;
[ "org.joda.beans" ]
org.joda.beans;
270,955
public static Map<String, Object> queueTTL( Map<String, Object> properties, long delay ) { Objects.requireNonNull( properties ); properties.put( "x-message-ttl", delay ); return properties; }
static Map<String, Object> function( Map<String, Object> properties, long delay ) { Objects.requireNonNull( properties ); properties.put( STR, delay ); return properties; }
/** * Set the queue Time To Live value. * <p> * By default if this is not set the queue will default to 5 minutes (set in our code, RabbitMQ's default is no timeout). * <p> * @param properties Properties * @param delay time to live in milliseconds * <p> * @return */
Set the queue Time To Live value. By default if this is not set the queue will default to 5 minutes (set in our code, RabbitMQ's default is no timeout).
queueTTL
{ "repo_name": "peter-mount/opendata-common", "path": "brokers/rabbitmq/src/main/java/uk/trainwatch/rabbitmq/RabbitMQ.java", "license": "apache-2.0", "size": 29777 }
[ "java.util.Map", "java.util.Objects" ]
import java.util.Map; import java.util.Objects;
import java.util.*;
[ "java.util" ]
java.util;
1,264,963
public static boolean hasTextAhead(XMLEventReader xmlEventReader) throws ParsingException { XMLEvent event = peek(xmlEventReader); return event.getEventType() == XMLEvent.CHARACTERS; }
static boolean function(XMLEventReader xmlEventReader) throws ParsingException { XMLEvent event = peek(xmlEventReader); return event.getEventType() == XMLEvent.CHARACTERS; }
/** * Return whether the next event is going to be text * * @param xmlEventReader * * @return * * @throws ParsingException */
Return whether the next event is going to be text
hasTextAhead
{ "repo_name": "iperdomo/keycloak", "path": "saml-core/src/main/java/org/keycloak/saml/common/util/StaxParserUtil.java", "license": "apache-2.0", "size": 16588 }
[ "javax.xml.stream.XMLEventReader", "javax.xml.stream.events.XMLEvent", "org.keycloak.saml.common.exceptions.ParsingException" ]
import javax.xml.stream.XMLEventReader; import javax.xml.stream.events.XMLEvent; import org.keycloak.saml.common.exceptions.ParsingException;
import javax.xml.stream.*; import javax.xml.stream.events.*; import org.keycloak.saml.common.exceptions.*;
[ "javax.xml", "org.keycloak.saml" ]
javax.xml; org.keycloak.saml;
1,596,549
private Action handleAddUpdateActionStatus(final JpaActionStatus actionStatus, final JpaAction action) { LOG.debug("addUpdateActionStatus for action {}", action.getId()); switch (actionStatus.getStatus()) { case ERROR: final JpaTarget target = DeploymentHelper.updateTargetInfo((JpaTarget) action.getTarget(), TargetUpdateStatus.ERROR, false); handleErrorOnAction(action, target); break; case FINISHED: handleFinishedAndStoreInTargetStatus(action); break; default: // information status entry - check for a potential DOS attack checkForTooManyStatusEntries(action); checkForTooManyStatusMessages(actionStatus); break; } actionStatus.setAction(action); actionStatusRepository.save(actionStatus); LOG.debug("addUpdateActionStatus for action {} isfinished.", action.getId()); return actionRepository.save(action); }
Action function(final JpaActionStatus actionStatus, final JpaAction action) { LOG.debug(STR, action.getId()); switch (actionStatus.getStatus()) { case ERROR: final JpaTarget target = DeploymentHelper.updateTargetInfo((JpaTarget) action.getTarget(), TargetUpdateStatus.ERROR, false); handleErrorOnAction(action, target); break; case FINISHED: handleFinishedAndStoreInTargetStatus(action); break; default: checkForTooManyStatusEntries(action); checkForTooManyStatusMessages(actionStatus); break; } actionStatus.setAction(action); actionStatusRepository.save(actionStatus); LOG.debug(STR, action.getId()); return actionRepository.save(action); }
/** * Sets {@link TargetUpdateStatus} based on given {@link ActionStatus}. */
Sets <code>TargetUpdateStatus</code> based on given <code>ActionStatus</code>
handleAddUpdateActionStatus
{ "repo_name": "stormc/hawkbit", "path": "hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaControllerManagement.java", "license": "epl-1.0", "size": 31273 }
[ "org.eclipse.hawkbit.repository.jpa.model.JpaAction", "org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus", "org.eclipse.hawkbit.repository.jpa.model.JpaTarget", "org.eclipse.hawkbit.repository.model.Action", "org.eclipse.hawkbit.repository.model.TargetUpdateStatus" ]
import org.eclipse.hawkbit.repository.jpa.model.JpaAction; import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus; import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.jpa.model.*; import org.eclipse.hawkbit.repository.model.*;
[ "org.eclipse.hawkbit" ]
org.eclipse.hawkbit;
1,117,271
List<? extends IJointDerivation<MR, ERESULT>> getDerivations();
List<? extends IJointDerivation<MR, ERESULT>> getDerivations();
/** * All joint derivations. Including evaluations that terminate in * <code>null</code>. */
All joint derivations. Including evaluations that terminate in <code>null</code>
getDerivations
{ "repo_name": "PriyankaKhante/nlp_spf", "path": "parser.ccg.joint/src/edu/uw/cs/lil/tiny/parser/joint/IJointOutput.java", "license": "gpl-2.0", "size": 3124 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
861,573
private void createErrorBubbleWindow(JComponent component, String i18n, Object... arguments) { killCurrentErrorBubbleWindow(); JButton okayButton = new JButton(I18N.getGUILabel("io.dataimport.step.excel.sheet_selection.got_it")); final ComponentBubbleWindow errorWindow = new ComponentBubbleWindow(component, BubbleStyle.ERROR, SwingUtilities.getWindowAncestor(this), AlignedSide.BOTTOM, i18n, null, null, false, true, new JButton[] { okayButton }, arguments); okayButton.addActionListener(new ActionListener() {
void function(JComponent component, String i18n, Object... arguments) { killCurrentErrorBubbleWindow(); JButton okayButton = new JButton(I18N.getGUILabel(STR)); final ComponentBubbleWindow errorWindow = new ComponentBubbleWindow(component, BubbleStyle.ERROR, SwingUtilities.getWindowAncestor(this), AlignedSide.BOTTOM, i18n, null, null, false, true, new JButton[] { okayButton }, arguments); okayButton.addActionListener(new ActionListener() {
/** * Creates an error bubble for the component and kills other error bubbles. * * @param component * the component for which to show the bubble * @param i18n * the i18n key * @param arguments * arguments for the i18n */
Creates an error bubble for the component and kills other error bubbles
createErrorBubbleWindow
{ "repo_name": "transwarpio/rapidminer", "path": "rapidMiner/rapidminer-studio-core/src/main/java/com/rapidminer/studio/io/data/internal/file/csv/CSVFormatSpecificationPanel.java", "license": "gpl-3.0", "size": 29383 }
[ "com.rapidminer.gui.tools.bubble.BubbleWindow", "com.rapidminer.gui.tools.bubble.ComponentBubbleWindow", "java.awt.event.ActionListener", "javax.swing.JButton", "javax.swing.JComponent", "javax.swing.SwingUtilities" ]
import com.rapidminer.gui.tools.bubble.BubbleWindow; import com.rapidminer.gui.tools.bubble.ComponentBubbleWindow; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.SwingUtilities;
import com.rapidminer.gui.tools.bubble.*; import java.awt.event.*; import javax.swing.*;
[ "com.rapidminer.gui", "java.awt", "javax.swing" ]
com.rapidminer.gui; java.awt; javax.swing;
2,840,624
public com.atinternet.tracker.avinsights.Media Media(SparseIntArray heartbeat, SparseIntArray bufferHeartbeat, String sessionId) { return new com.atinternet.tracker.avinsights.Media(events, heartbeat, bufferHeartbeat, sessionId); }
com.atinternet.tracker.avinsights.Media function(SparseIntArray heartbeat, SparseIntArray bufferHeartbeat, String sessionId) { return new com.atinternet.tracker.avinsights.Media(events, heartbeat, bufferHeartbeat, sessionId); }
/*** * Create new Media * @param heartbeat heartbeat periods * @param bufferHeartbeat buffer heartbeat periods * @param sessionId custom sessionId * @return Media instance */
Create new Media
Media
{ "repo_name": "at-internet/atinternet-android-sdk", "path": "ATMobileAnalytics/Tracker/src/main/java/com/atinternet/tracker/AVInsights.java", "license": "mit", "size": 3351 }
[ "android.util.SparseIntArray" ]
import android.util.SparseIntArray;
import android.util.*;
[ "android.util" ]
android.util;
1,647,262
public void testCrashRecover() throws Throwable { List<CopycatServer> servers = createServers(3); CopycatClient client = createClient(); submit(client, 0, 1000); await(30000); servers.get(0).shutdown().get(10, TimeUnit.SECONDS); CopycatServer server = createServer(members.get(0)); server.join(members.stream().map(Member::serverAddress).collect(Collectors.toList())).thenRun(this::resume); await(30000); submit(client, 0, 1000); await(30000); }
void function() throws Throwable { List<CopycatServer> servers = createServers(3); CopycatClient client = createClient(); submit(client, 0, 1000); await(30000); servers.get(0).shutdown().get(10, TimeUnit.SECONDS); CopycatServer server = createServer(members.get(0)); server.join(members.stream().map(Member::serverAddress).collect(Collectors.toList())).thenRun(this::resume); await(30000); submit(client, 0, 1000); await(30000); }
/** * Tests joining a server to an existing cluster. */
Tests joining a server to an existing cluster
testCrashRecover
{ "repo_name": "atomix/copycat", "path": "test/src/test/java/io/atomix/copycat/test/ClusterTest.java", "license": "apache-2.0", "size": 39445 }
[ "io.atomix.copycat.client.CopycatClient", "io.atomix.copycat.server.CopycatServer", "io.atomix.copycat.server.cluster.Member", "java.util.List", "java.util.concurrent.TimeUnit", "java.util.stream.Collectors" ]
import io.atomix.copycat.client.CopycatClient; import io.atomix.copycat.server.CopycatServer; import io.atomix.copycat.server.cluster.Member; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
import io.atomix.copycat.client.*; import io.atomix.copycat.server.*; import io.atomix.copycat.server.cluster.*; import java.util.*; import java.util.concurrent.*; import java.util.stream.*;
[ "io.atomix.copycat", "java.util" ]
io.atomix.copycat; java.util;
611,396
void onStartDrag(RecyclerView.ViewHolder viewHolder);
void onStartDrag(RecyclerView.ViewHolder viewHolder);
/** * Called when a view is requesting a start of a drag. * * @param viewHolder The holder of the view to drag. */
Called when a view is requesting a start of a drag
onStartDrag
{ "repo_name": "dan-silver/cast-dashboard-android-app", "path": "app/src/main/java/com/silver/dan/castdemo/widgetList/OnDragListener.java", "license": "mit", "size": 328 }
[ "android.support.v7.widget.RecyclerView" ]
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.*;
[ "android.support" ]
android.support;
760,879
ProcessInstance startProcessInstanceByKeyAndTenantId(String processDefinitionKey, String tenantId);
ProcessInstance startProcessInstanceByKeyAndTenantId(String processDefinitionKey, String tenantId);
/** * Similar to {@link #startProcessInstanceByKey(String)}, but using a specific tenant identifier. */
Similar to <code>#startProcessInstanceByKey(String)</code>, but using a specific tenant identifier
startProcessInstanceByKeyAndTenantId
{ "repo_name": "ahwxl/deep", "path": "src/main/java/org/activiti/engine/RuntimeService.java", "license": "apache-2.0", "size": 40262 }
[ "org.activiti.engine.runtime.ProcessInstance" ]
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.*;
[ "org.activiti.engine" ]
org.activiti.engine;
1,092,049
public static Map read_supervisor_topology_conf(Map conf, String topologyId) throws IOException { String topologyRoot = StormConfig.supervisor_stormdist_root(conf, topologyId); String confPath = StormConfig.stormconf_path(topologyRoot); return (Map) readLocalObject(topologyId, confPath); }
static Map function(Map conf, String topologyId) throws IOException { String topologyRoot = StormConfig.supervisor_stormdist_root(conf, topologyId); String confPath = StormConfig.stormconf_path(topologyRoot); return (Map) readLocalObject(topologyId, confPath); }
/** * stormconf is mergered into clusterconf * * @param conf * @param topologyId * @return * @throws IOException */
stormconf is mergered into clusterconf
read_supervisor_topology_conf
{ "repo_name": "kenchen1101/jstorm", "path": "jstorm-core/src/main/java/com/alibaba/jstorm/cluster/StormConfig.java", "license": "apache-2.0", "size": 19690 }
[ "java.io.IOException", "java.util.Map" ]
import java.io.IOException; import java.util.Map;
import java.io.*; import java.util.*;
[ "java.io", "java.util" ]
java.io; java.util;
1,553,483
public static double[] values(final double[] v, final int t) { ArgumentChecker.notNull(v, "v"); ArgumentChecker.isTrue(t > -1, "Invalid number of differences requested, t must be positive or 0. The given t was: " + t); ArgumentChecker.isTrue(t < v.length, "Invalid number of differences requested, 't' is greater than the number of elements in 'v'. The given 't' was: " + t + " and 'v' contains " + v.length + " elements."); double[] tmp; if (t == 0) { // no differencing done tmp = new double[v.length]; System.arraycopy(v, 0, tmp, 0, v.length); } else { tmp = values(v); for (int i = 0; i < t - 1; i++) { tmp = values(tmp); } } return tmp; }
static double[] function(final double[] v, final int t) { ArgumentChecker.notNull(v, "v"); ArgumentChecker.isTrue(t > -1, STR + t); ArgumentChecker.isTrue(t < v.length, STR + t + STR + v.length + STR); double[] tmp; if (t == 0) { tmp = new double[v.length]; System.arraycopy(v, 0, tmp, 0, v.length); } else { tmp = values(v); for (int i = 0; i < t - 1; i++) { tmp = values(tmp); } } return tmp; }
/** * Finds the t^{th} numerical difference between value at position (i+1) and (i) (effectively recurses #values "t" times). * * @param v * the vector * @param t * the number of differences to be taken (t positive). * @return the numerical difference between adjacent elements in v */
Finds the t^{th} numerical difference between value at position (i+1) and (i) (effectively recurses #values "t" times)
values
{ "repo_name": "McLeodMoores/starling", "path": "projects/analytics/src/main/java/com/opengamma/analytics/math/utilities/Diff.java", "license": "apache-2.0", "size": 6940 }
[ "com.opengamma.util.ArgumentChecker" ]
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.*;
[ "com.opengamma.util" ]
com.opengamma.util;
1,913,061
protected void writeParagraphEnd() throws IOException { if (!inParagraph) { writeParagraphStart(); } output.write(getParagraphEnd()); inParagraph = false; }
void function() throws IOException { if (!inParagraph) { writeParagraphStart(); } output.write(getParagraphEnd()); inParagraph = false; }
/** * Write something (if defined) at the end of a paragraph. * * @throws IOException if something went wrong */
Write something (if defined) at the end of a paragraph
writeParagraphEnd
{ "repo_name": "apache/pdfbox", "path": "pdfbox/src/main/java/org/apache/pdfbox/text/PDFTextStripper.java", "license": "apache-2.0", "size": 75973 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
941,277
public void setCharset(Charset c) { inputCharset = c; }
void function(Charset c) { inputCharset = c; }
/** * Store the Charset specification as the string version of the name, * rather than the Charset itself. This allows us to serialize the * SourceFile class. * @param c charset to use when reading the input. */
Store the Charset specification as the string version of the name, rather than the Charset itself. This allows us to serialize the SourceFile class
setCharset
{ "repo_name": "shantanusharma/closure-compiler", "path": "src/com/google/javascript/jscomp/SourceFile.java", "license": "apache-2.0", "size": 24992 }
[ "java.nio.charset.Charset" ]
import java.nio.charset.Charset;
import java.nio.charset.*;
[ "java.nio" ]
java.nio;
2,400,560
boolean toggle(String key, Player player, long ttl);
boolean toggle(String key, Player player, long ttl);
/** * Toggles a state * * @param key state key * @param player state player * @param ttl TimeToLive * @return the new state (<code>true</code>/<code>false</code>) */
Toggles a state
toggle
{ "repo_name": "InventivetalentDev/MapMenus", "path": "src/main/java/org/inventivetalent/mapmenus/menu/data/IStates.java", "license": "bsd-3-clause", "size": 3087 }
[ "org.bukkit.entity.Player" ]
import org.bukkit.entity.Player;
import org.bukkit.entity.*;
[ "org.bukkit.entity" ]
org.bukkit.entity;
155,913
public static String getOutputRootDirectory(final ContentSpecConfiguration cspConfig, final ContentSpec contentSpec) { return getOutputRootDirectory(cspConfig, contentSpec.getTitle()); }
static String function(final ContentSpecConfiguration cspConfig, final ContentSpec contentSpec) { return getOutputRootDirectory(cspConfig, contentSpec.getTitle()); }
/** * Gets the output root directory based on the configuration files and ContentSpec object. * * @param cspConfig The content spec configuration settings. * @param contentSpec The content spec object to get details from for the output directory. * @return A string that represents where the root folder is for content to be saved. */
Gets the output root directory based on the configuration files and ContentSpec object
getOutputRootDirectory
{ "repo_name": "pressgang-ccms/PressGangCCMSCSPClient", "path": "src/main/java/org/jboss/pressgang/ccms/contentspec/client/utils/ClientUtilities.java", "license": "gpl-3.0", "size": 60301 }
[ "org.jboss.pressgang.ccms.contentspec.ContentSpec", "org.jboss.pressgang.ccms.contentspec.client.config.ContentSpecConfiguration" ]
import org.jboss.pressgang.ccms.contentspec.ContentSpec; import org.jboss.pressgang.ccms.contentspec.client.config.ContentSpecConfiguration;
import org.jboss.pressgang.ccms.contentspec.*; import org.jboss.pressgang.ccms.contentspec.client.config.*;
[ "org.jboss.pressgang" ]
org.jboss.pressgang;
1,824,910
public static WildcardType wildcardSuper(Type lowerBound) { if (lowerBound == null) { throw new NullPointerException(); } return new WildcardTypeImpl(new Type[] {Object.class}, new Type[] {lowerBound}); }
static WildcardType function(Type lowerBound) { if (lowerBound == null) { throw new NullPointerException(); } return new WildcardTypeImpl(new Type[] {Object.class}, new Type[] {lowerBound}); }
/** * Creates a wildcard type with a lower bound. * * <p>For example <tt>wildcardSuper(String.class)</tt> returns the type <tt>? super String</tt>. * * @param lowerBound Lower bound of the wildcard * @return A wildcard type */
Creates a wildcard type with a lower bound. For example wildcardSuper(String.class) returns the type ? super String
wildcardSuper
{ "repo_name": "coekie/gentyref", "path": "src/main/java/com/coekie/gentyref/TypeFactory.java", "license": "apache-2.0", "size": 12717 }
[ "java.lang.reflect.Type", "java.lang.reflect.WildcardType" ]
import java.lang.reflect.Type; import java.lang.reflect.WildcardType;
import java.lang.reflect.*;
[ "java.lang" ]
java.lang;
1,581,529
public boolean equalsIgnoreCase(Vertex vertex) { if (this.equals(vertex)) { return true; } if ((this.data instanceof String) && (vertex.getData() instanceof String)) { return ((String)this.data).equalsIgnoreCase((String)vertex.getData()); } return false; }
boolean function(Vertex vertex) { if (this.equals(vertex)) { return true; } if ((this.data instanceof String) && (vertex.getData() instanceof String)) { return ((String)this.data).equalsIgnoreCase((String)vertex.getData()); } return false; }
/** * Compare the vertices ignoring case. */
Compare the vertices ignoring case
equalsIgnoreCase
{ "repo_name": "BOTlibre/BOTlibre", "path": "micro-ai-engine/android/source/org/botlibre/knowledge/BasicVertex.java", "license": "epl-1.0", "size": 152940 }
[ "org.botlibre.api.knowledge.Vertex" ]
import org.botlibre.api.knowledge.Vertex;
import org.botlibre.api.knowledge.*;
[ "org.botlibre.api" ]
org.botlibre.api;
909,983
List<String> getTransitiveMemberRepositoryIds();
List<String> getTransitiveMemberRepositoryIds();
/** * Returns the unmodifiable ID list of the transitive members of this group. This method differs from * {@link #getMemberRepositoryIds()} by resolving all inner groups member as well. <b>The resulting list won't * contain any GroupRepository.</b> * * @return a List<Repository> */
Returns the unmodifiable ID list of the transitive members of this group. This method differs from <code>#getMemberRepositoryIds()</code> by resolving all inner groups member as well. The resulting list won't contain any GroupRepository
getTransitiveMemberRepositoryIds
{ "repo_name": "scmod/nexus-public", "path": "components/nexus-core/src/main/java/org/sonatype/nexus/proxy/repository/GroupRepository.java", "license": "epl-1.0", "size": 3678 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
2,075,814
public boolean clear(GridCacheVersion ver, boolean readers) throws IgniteCheckedException;
boolean function(GridCacheVersion ver, boolean readers) throws IgniteCheckedException;
/** * Marks entry as obsolete and, if possible or required, removes it * from swap storage. * * @param ver Obsolete version. * @param readers Flag to clear readers as well. * @throws IgniteCheckedException If failed to remove from swap. * @return {@code True} if entry was not being used, passed the filter and could be removed. */
Marks entry as obsolete and, if possible or required, removes it from swap storage
clear
{ "repo_name": "vldpyatkov/ignite", "path": "modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheEntryEx.java", "license": "apache-2.0", "size": 38956 }
[ "org.apache.ignite.IgniteCheckedException", "org.apache.ignite.internal.processors.cache.version.GridCacheVersion" ]
import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
import org.apache.ignite.*; import org.apache.ignite.internal.processors.cache.version.*;
[ "org.apache.ignite" ]
org.apache.ignite;
2,843,455
public BigDecimal getPayrollTotalHours();
BigDecimal function();
/** * Gets the payrollTotalHours * * @return Returns the payrollTotalHours. */
Gets the payrollTotalHours
getPayrollTotalHours
{ "repo_name": "Ariah-Group/Finance", "path": "af_webapp/src/main/java/org/kuali/kfs/integration/ld/LaborLedgerExpenseTransferAccountingLine.java", "license": "apache-2.0", "size": 3081 }
[ "java.math.BigDecimal" ]
import java.math.BigDecimal;
import java.math.*;
[ "java.math" ]
java.math;
805,261
@Test(expected = ConstraintViolationException.class) public void testValidateNoUser() { this.c = new Command(NAME, " ", VERSION, CommandStatus.ACTIVE, EXECUTABLE); this.validate(this.c); }
@Test(expected = ConstraintViolationException.class) void function() { this.c = new Command(NAME, " ", VERSION, CommandStatus.ACTIVE, EXECUTABLE); this.validate(this.c); }
/** * Make sure validation works on with failure from super class. */
Make sure validation works on with failure from super class
testValidateNoUser
{ "repo_name": "ZhangboFrank/genie", "path": "genie-common/src/test/java/com/netflix/genie/common/model/TestCommand.java", "license": "apache-2.0", "size": 8186 }
[ "javax.validation.ConstraintViolationException", "org.junit.Test" ]
import javax.validation.ConstraintViolationException; import org.junit.Test;
import javax.validation.*; import org.junit.*;
[ "javax.validation", "org.junit" ]
javax.validation; org.junit;
2,337,219
private Element chooseFoundingFather(Element element) { final List<FoundingFather> possibleFoundingFathers = new ArrayList<FoundingFather>(); for (FoundingFatherType type : FoundingFatherType.values()) { String id = element.getAttribute(type.toString()); if (id != null && !id.equals("")) { possibleFoundingFathers.add(Reformation.getSpecification().getFoundingFather(id)); } } FoundingFather foundingFather = new ShowSelectFoundingFatherSwingTask(possibleFoundingFathers).select(); Element reply = Message.createNewRootElement("chosenFoundingFather"); reply.setAttribute("foundingFather", foundingFather.getId()); getFreeColClient().getMyPlayer().setCurrentFather(foundingFather); return reply; }
Element function(Element element) { final List<FoundingFather> possibleFoundingFathers = new ArrayList<FoundingFather>(); for (FoundingFatherType type : FoundingFatherType.values()) { String id = element.getAttribute(type.toString()); if (id != null && !id.equals(STRchosenFoundingFatherSTRfoundingFather", foundingFather.getId()); getFreeColClient().getMyPlayer().setCurrentFather(foundingFather); return reply; }
/** * Handles an "chooseFoundingFather"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */
Handles an "chooseFoundingFather"-request
chooseFoundingFather
{ "repo_name": "tectronics/reformationofeurope", "path": "src/net/sf/freecol/client/control/InGameInputHandler.java", "license": "gpl-2.0", "size": 80987 }
[ "java.util.ArrayList", "java.util.List", "net.sf.freecol.common.model.FoundingFather", "org.w3c.dom.Element" ]
import java.util.ArrayList; import java.util.List; import net.sf.freecol.common.model.FoundingFather; import org.w3c.dom.Element;
import java.util.*; import net.sf.freecol.common.model.*; import org.w3c.dom.*;
[ "java.util", "net.sf.freecol", "org.w3c.dom" ]
java.util; net.sf.freecol; org.w3c.dom;
1,785,107
protected Object createEnum(String symbol, Schema schema) { return data.createEnum(symbol, schema); }
Object function(String symbol, Schema schema) { return data.createEnum(symbol, schema); }
/** Called to create an enum value. May be overridden for alternate enum * representations. By default, returns a GenericEnumSymbol. */
Called to create an enum value. May be overridden for alternate enum
createEnum
{ "repo_name": "Asana/mypipe", "path": "avro/lang/java/avro/src/main/java/org/apache/avro/generic/GenericDatumReader.java", "license": "apache-2.0", "size": 17712 }
[ "org.apache.avro.Schema" ]
import org.apache.avro.Schema;
import org.apache.avro.*;
[ "org.apache.avro" ]
org.apache.avro;
926,125
void registerOnActivityStopListener(OnActivityStopListener listener) { synchronized (this) { if (mActivityStopListeners == null) { mActivityStopListeners = new ArrayList<OnActivityStopListener>(); } if (!mActivityStopListeners.contains(listener)) { mActivityStopListeners.add(listener); } } }
void registerOnActivityStopListener(OnActivityStopListener listener) { synchronized (this) { if (mActivityStopListeners == null) { mActivityStopListeners = new ArrayList<OnActivityStopListener>(); } if (!mActivityStopListeners.contains(listener)) { mActivityStopListeners.add(listener); } } }
/** * Registers a listener. * * @see OnActivityStopListener */
Registers a listener
registerOnActivityStopListener
{ "repo_name": "mateor/PDroidHistory", "path": "frameworks/base/core/java/android/preference/PreferenceManager.java", "license": "gpl-3.0", "size": 26854 }
[ "java.util.ArrayList" ]
import java.util.ArrayList;
import java.util.*;
[ "java.util" ]
java.util;
73,656
protected void updateBounds() { if (!checkSize) { return; } Rectangle bbox = getBounds(); Dimension minSize = getMinimumSize(); bbox.width = Math.max(bbox.width, minSize.width); bbox.height = Math.max(bbox.height, minSize.height); setBounds(bbox.x, bbox.y, bbox.width, bbox.height); }
void function() { if (!checkSize) { return; } Rectangle bbox = getBounds(); Dimension minSize = getMinimumSize(); bbox.width = Math.max(bbox.width, minSize.width); bbox.height = Math.max(bbox.height, minSize.height); setBounds(bbox.x, bbox.y, bbox.width, bbox.height); }
/** * Determine new bounds. <p> * * This algorithm makes the box grow * (if the calculated minimum size grows), * but then it can never shrink again * (not even if the calculated minimum size is smaller). */
Determine new bounds. This algorithm makes the box grow (if the calculated minimum size grows), but then it can never shrink again (not even if the calculated minimum size is smaller)
updateBounds
{ "repo_name": "ckaestne/LEADT", "path": "workspace/argouml_diagrams/argouml-app/src/org/argouml/uml/diagram/ui/FigNodeModelElement.java", "license": "gpl-3.0", "size": 92897 }
[ "java.awt.Dimension", "java.awt.Rectangle" ]
import java.awt.Dimension; import java.awt.Rectangle;
import java.awt.*;
[ "java.awt" ]
java.awt;
2,059,423
@Provides @Singleton Map<String, SoyLibraryAssistedJsSrcPrintDirective> provideSoyLibraryAssistedJsSrcDirectivesMap( Set<SoyPrintDirective> soyDirectivesSet) { return ModuleUtils.buildSpecificSoyDirectivesMap( soyDirectivesSet, SoyLibraryAssistedJsSrcPrintDirective.class); }
Map<String, SoyLibraryAssistedJsSrcPrintDirective> provideSoyLibraryAssistedJsSrcDirectivesMap( Set<SoyPrintDirective> soyDirectivesSet) { return ModuleUtils.buildSpecificSoyDirectivesMap( soyDirectivesSet, SoyLibraryAssistedJsSrcPrintDirective.class); }
/** * Builds and provides the map of SoyLibraryAssistedJsSrcDirectives (name to directive). * @param soyDirectivesSet The installed set of SoyPrintDirectives (from Guice Multibinder). Each * SoyDirective may or may not implement SoyLibraryAssistedJsSrcDirectives. */
Builds and provides the map of SoyLibraryAssistedJsSrcDirectives (name to directive)
provideSoyLibraryAssistedJsSrcDirectivesMap
{ "repo_name": "oujesky/closure-templates", "path": "java/src/com/google/template/soy/jssrc/internal/JsSrcModule.java", "license": "apache-2.0", "size": 5218 }
[ "com.google.template.soy.jssrc.restricted.SoyLibraryAssistedJsSrcPrintDirective", "com.google.template.soy.shared.internal.ModuleUtils", "com.google.template.soy.shared.restricted.SoyPrintDirective", "java.util.Map", "java.util.Set" ]
import com.google.template.soy.jssrc.restricted.SoyLibraryAssistedJsSrcPrintDirective; import com.google.template.soy.shared.internal.ModuleUtils; import com.google.template.soy.shared.restricted.SoyPrintDirective; import java.util.Map; import java.util.Set;
import com.google.template.soy.jssrc.restricted.*; import com.google.template.soy.shared.internal.*; import com.google.template.soy.shared.restricted.*; import java.util.*;
[ "com.google.template", "java.util" ]
com.google.template; java.util;
2,463,413
void setAttribute(PerunSession sess, Host host, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
void setAttribute(PerunSession sess, Host host, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/** * Store the attribute associated with the host. Core attributes can't be set this way. * @param sess perun session * @param host host to set attributes for * @param attribute attribute to be set * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongAttributeAssignmentException if attribute is not host attribute * @throws WrongAttributeValueException if the attribute value is illegal */
Store the attribute associated with the host. Core attributes can't be set this way
setAttribute
{ "repo_name": "jirmauritz/perun", "path": "perun-core/src/main/java/cz/metacentrum/perun/core/bl/AttributesManagerBl.java", "license": "bsd-2-clause", "size": 193360 }
[ "cz.metacentrum.perun.core.api.Attribute", "cz.metacentrum.perun.core.api.Host", "cz.metacentrum.perun.core.api.PerunSession", "cz.metacentrum.perun.core.api.exceptions.InternalErrorException", "cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException", "cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException", "cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException" ]
import cz.metacentrum.perun.core.api.Attribute; import cz.metacentrum.perun.core.api.Host; import cz.metacentrum.perun.core.api.PerunSession; import cz.metacentrum.perun.core.api.exceptions.InternalErrorException; import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException; import cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException; import cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException;
import cz.metacentrum.perun.core.api.*; import cz.metacentrum.perun.core.api.exceptions.*;
[ "cz.metacentrum.perun" ]
cz.metacentrum.perun;
1,296,530
private boolean readDataInfo(String aFile, String errorStr) throws FileNotFoundException, IOException { this.setFileName(aFile); BufferedReader sr = new BufferedReader(new FileReader(new File(aFile))); String aLine = ""; String[] dataArray; int i; boolean isEnd = false; //Set dufault value DESCRIPTOR = aFile; boolean isReadLine = true; Dimension zDim; Dimension eDim = null; this.addAttribute(new Attribute("data_format", "GrADS binary")); do { if (isReadLine) { aLine = sr.readLine().trim(); if (aLine.isEmpty()) { continue; } } isReadLine = true; dataArray = aLine.split("\\s+"); String hStr = dataArray[0].toUpperCase(); switch (hStr) { case "DSET": DSET = dataArray[1]; boolean isNotPath = false; if (!DSET.contains("/") && !DSET.contains("\\")) { isNotPath = true; } File theFile = new File(aFile); String aDir = theFile.getParent(); if (isNotPath) { if (DSET.substring(0, 1).equals("^")) { DSET = aDir + File.separator + DSET.substring(1); } else { DSET = aDir + File.separator + DSET; } if (!new File(DSET).isFile()) { DSET = dataArray[1]; DSET = theFile.getParent() + "/" + DSET.substring(1, DSET.length()); } } if (!new File(DSET).isFile()) { if (DSET.substring(0, 2).equals("./") || DSET.substring(0, 2).equals(".\\")) { DSET = aDir + File.separator + DSET.substring(2); } else { errorStr = "The data file is not exist!" + System.getProperty("line.separator") + DSET; } //goto ERROR; } break; case "DTYPE": DTYPE = dataArray[1]; if (!DTYPE.toUpperCase().equals("GRIDDED") && !DTYPE.toUpperCase().equals("STATION")) { errorStr = "The data type is not supported at present!" + System.getProperty("line.separator") + DTYPE; //goto ERROR; } if (DTYPE.toUpperCase().equals("STATION")) { this.setDataType(MeteoDataType.GrADS_Station); } Attribute attr = new Attribute("data_type", this.DTYPE); this.addAttribute(attr); break; case "OPTIONS": for (i = 1; i < dataArray.length; i++) { String oStr = dataArray[i].toLowerCase(); switch (oStr) { case "big_endian": OPTIONS.big_endian = true; break; case "byteswapped": OPTIONS.byteswapped = true; break; case "365_day_calendar": OPTIONS.calendar_365_day = true; break; case "cray_32bit_ieee": OPTIONS.cray_32bit_ieee = true; break; case "little_endian": OPTIONS.little_endian = true; break; case "pascals": OPTIONS.pascals = true; break; case "sequential": OPTIONS.sequential = true; break; case "template": OPTIONS.template = true; break; case "yrev": OPTIONS.yrev = true; break; case "zrev": OPTIONS.zrev = true; break; default: break; } } break; case "UNDEF": this.setMissingValue(Double.parseDouble(dataArray[1])); attr = new Attribute("fill_value", this.getMissingValue()); this.addAttribute(attr); break; case "TITLE": TITLE = aLine.substring(5, aLine.length()).trim(); attr = new Attribute("title", this.TITLE); this.addAttribute(attr); break; case "FILEHEADER": FILEHEADER = Integer.parseInt(dataArray[1]); break; case "THEADER": THEADER = Integer.parseInt(dataArray[1]); break; case "XYHEADER": XYHEADER = Integer.parseInt(dataArray[1]); break; case "PDEF": PDEF.PDEF_Type = dataArray[3].toUpperCase(); String ProjStr; ProjectionInfo theProj; String pStr = PDEF.PDEF_Type; switch (pStr) { case "LCC": case "LCCR": { PDEF_LCC aPLCC = new PDEF_LCC(); aPLCC.isize = Integer.parseInt(dataArray[1]); aPLCC.jsize = Integer.parseInt(dataArray[2]); aPLCC.latref = Float.parseFloat(dataArray[4]); aPLCC.lonref = Float.parseFloat(dataArray[5]); aPLCC.iref = Float.parseFloat(dataArray[6]); aPLCC.jref = Float.parseFloat(dataArray[7]); aPLCC.Struelat = Float.parseFloat(dataArray[8]); aPLCC.Ntruelat = Float.parseFloat(dataArray[9]); aPLCC.slon = Float.parseFloat(dataArray[10]); aPLCC.dx = Float.parseFloat(dataArray[11]); aPLCC.dy = Float.parseFloat(dataArray[12]); PDEF.PDEF_Content = aPLCC; isLatLon = false; ProjStr = "+proj=lcc" + " +lat_1=" + String.valueOf(aPLCC.Struelat) + " +lat_2=" + String.valueOf(aPLCC.Ntruelat) + " +lat_0=" + String.valueOf(aPLCC.latref) + " +lon_0=" + String.valueOf(aPLCC.slon); theProj = ProjectionInfo.factory(ProjStr); this.setProjectionInfo(theProj); if (PDEF.PDEF_Type.equals("LCCR")) { EarthWind = false; } //Set X Y XNum = aPLCC.isize; YNum = aPLCC.jsize; X = new double[aPLCC.isize]; Y = new double[aPLCC.jsize]; getProjectedXY(theProj, aPLCC.dx, aPLCC.dy, aPLCC.iref, aPLCC.jref, aPLCC.lonref, aPLCC.latref, X, Y); Dimension xdim = new Dimension(DimensionType.X); xdim.setShortName("X"); xdim.setValues(X); this.setXDimension(xdim); this.addDimension(xdim); Dimension ydim = new Dimension(DimensionType.Y); ydim.setShortName("Y"); ydim.setValues(Y); this.setYDimension(ydim); this.addDimension(ydim); break; } case "NPS": case "SPS": { int iSize = Integer.parseInt(dataArray[1]); int jSize = Integer.parseInt(dataArray[2]); float iPole = Float.parseFloat(dataArray[3]); float jPole = Float.parseFloat(dataArray[4]); float lonRef = Float.parseFloat(dataArray[5]); float dx = Float.parseFloat(dataArray[6]) * 1000; float dy = dx; String lat0 = "90"; if (PDEF.PDEF_Type.equals("SPS")) { lat0 = "-90"; } isLatLon = false; ProjStr = "+proj=stere +lon_0=" + String.valueOf(lonRef) + " +lat_0=" + lat0; this.setProjectionInfo(ProjectionInfo.factory(ProjStr)); //Set X Y XNum = iSize; YNum = jSize; X = new double[iSize]; Y = new double[jSize]; getProjectedXY_NPS(dx, dy, iPole, jPole, X, Y); Dimension xdim = new Dimension(DimensionType.X); xdim.setShortName("X"); xdim.setValues(X); this.setXDimension(xdim); this.addDimension(xdim); Dimension ydim = new Dimension(DimensionType.Y); ydim.setShortName("Y"); ydim.setValues(Y); this.setYDimension(ydim); this.addDimension(ydim); break; } default: errorStr = "The PDEF type is not supported at present!" + System.getProperty("line.separator") + "Please send your data to the author to improve MeteoInfo!"; //goto ERROR; break; } break; case "XDEF": if (this.getProjectionInfo().isLonLat()) { XDEF.XNum = Integer.parseInt(dataArray[1]); XDEF.X = new double[XDEF.XNum]; XDEF.Type = dataArray[2]; List<Double> values = new ArrayList<>(); if (XDEF.Type.toUpperCase().equals("LINEAR")) { XDEF.XMin = Float.parseFloat(dataArray[3]); XDEF.XDelt = Float.parseFloat(dataArray[4]); } else { if (dataArray.length < XDEF.XNum + 3) { while (true) { aLine = aLine + " " + sr.readLine().trim(); if (aLine.isEmpty()) { continue; } dataArray = aLine.split("\\s+"); if (dataArray.length >= XDEF.XNum + 3) { break; } } } if (dataArray.length > XDEF.XNum + 3) { errorStr = "XDEF is wrong! Please check the ctl file!"; //goto ERROR; } XDEF.XMin = Float.parseFloat(dataArray[3]); float xmax = Float.parseFloat(dataArray[dataArray.length - 1]); XDEF.XDelt = (xmax - XDEF.XMin) / (XDEF.XNum - 1); } double delta = BigDecimalUtil.toDouble(XDEF.XDelt); double min = BigDecimalUtil.toDouble(XDEF.XMin); for (i = 0; i < XDEF.XNum; i++) { XDEF.X[i] = BigDecimalUtil.add(min, BigDecimalUtil.mul(i, delta)); values.add(XDEF.X[i]); } if (XDEF.XMin == 0 && XDEF.X[XDEF.XNum - 1] + XDEF.XDelt == 360) { isGlobal = true; } Dimension xDim = new Dimension(DimensionType.X); xDim.setShortName("X"); xDim.setValues(values); this.setXDimension(xDim); this.addDimension(xDim); } break; case "YDEF": if (this.getProjectionInfo().isLonLat()) { YDEF.YNum = Integer.parseInt(dataArray[1]); YDEF.Y = new double[YDEF.YNum]; YDEF.Type = dataArray[2]; List<Double> values = new ArrayList<>(); if (YDEF.Type.toUpperCase().equals("LINEAR")) { YDEF.YMin = Float.parseFloat(dataArray[3]); YDEF.YDelt = Float.parseFloat(dataArray[4]); } else { if (dataArray.length < YDEF.YNum + 3) { while (true) { aLine = aLine + " " + sr.readLine().trim(); if (aLine.isEmpty()) { continue; } dataArray = aLine.split("\\s+"); if (dataArray.length >= YDEF.YNum + 3) { break; } } } if (dataArray.length > YDEF.YNum + 3) { errorStr = "YDEF is wrong! Please check the ctl file!"; //goto ERROR; } YDEF.YMin = Float.parseFloat(dataArray[3]); float ymax = Float.parseFloat(dataArray[dataArray.length - 1]); YDEF.YDelt = (ymax - YDEF.YMin) / (YDEF.YNum - 1); } double delta = BigDecimalUtil.toDouble(YDEF.YDelt); double min = BigDecimalUtil.toDouble(YDEF.YMin); for (i = 0; i < YDEF.YNum; i++) { YDEF.Y[i] = BigDecimalUtil.add(min, BigDecimalUtil.mul(i, delta)); values.add(YDEF.Y[i]); } Dimension yDim = new Dimension(DimensionType.Y); yDim.setShortName("Y"); yDim.setValues(values); this.setYDimension(yDim); this.addDimension(yDim); } break; case "ZDEF": ZDEF.ZNum = Integer.parseInt(dataArray[1]); ZDEF.Type = dataArray[2]; ZDEF.ZLevels = new float[ZDEF.ZNum]; List<Double> values = new ArrayList<>(); if (ZDEF.Type.toUpperCase().equals("LINEAR")) { ZDEF.SLevel = Float.parseFloat(dataArray[3]); ZDEF.ZDelt = Float.parseFloat(dataArray[4]); for (i = 0; i < ZDEF.ZNum; i++) { ZDEF.ZLevels[i] = ZDEF.SLevel + i * ZDEF.ZDelt; values.add(Double.valueOf(ZDEF.ZLevels[i])); } } else if (dataArray.length < ZDEF.ZNum + 3) { while (true) { String line = sr.readLine().trim(); if (line.isEmpty()) { continue; } dataArray = line.split("\\s+"); if (this.isKeyWord(dataArray[0])) { dataArray = aLine.split("\\s+"); // if (dataArray.length > ZDEF.ZNum + 3) { // errorStr = "ZDEF is wrong! Please check the ctl file!"; // //goto ERROR; // } // for (i = 0; i < ZDEF.ZNum; i++) { // ZDEF.ZLevels[i] = Float.parseFloat(dataArray[3 + i]); // values.add(Double.parseDouble(dataArray[3 + i])); // } ZDEF.ZNum = dataArray.length - 3; ZDEF.ZLevels = new float[ZDEF.ZNum]; for (i = 0; i < ZDEF.ZNum; i++) { ZDEF.ZLevels[i] = Float.parseFloat(dataArray[3 + i]); values.add(Double.parseDouble(dataArray[3 + i])); } aLine = line; isReadLine = false; break; } aLine = aLine + " " + line; // dataArray = aLine.split("\\s+"); // if (dataArray.length >= ZDEF.ZNum + 3) { // break; // } } } else { ZDEF.ZNum = dataArray.length - 3; ZDEF.ZLevels = new float[ZDEF.ZNum]; for (i = 0; i < ZDEF.ZNum; i++) { ZDEF.ZLevels[i] = Float.parseFloat(dataArray[3 + i]); values.add(Double.parseDouble(dataArray[3 + i])); } } zDim = new Dimension(DimensionType.Z); zDim.setShortName("Z"); zDim.setValues(values); this.setZDimension(zDim); this.addDimension(zDim); break; case "TDEF": int tnum = Integer.parseInt(dataArray[1]); TDEF.Type = dataArray[2]; if (TDEF.Type.toUpperCase().equals("LINEAR")) { String dStr = dataArray[3]; dStr = dStr.toUpperCase(); i = dStr.indexOf("Z"); switch (i) { case -1: if (Character.isDigit(dStr.charAt(0))) { dStr = "00:00Z" + dStr; } else { dStr = "00:00Z01" + dStr; } break; case 1: dStr = "0" + dStr.substring(0, 1) + ":00" + dStr.substring(1); break; case 2: dStr = dStr.substring(0, 2) + ":00" + dStr.substring(2); break; default: break; } if (!(Character.isDigit(dStr.charAt(dStr.length() - 3)))) { int aY = Integer.parseInt(dStr.substring(dStr.length() - 2)); if (aY > 50) { aY = 1900 + aY; } else { aY = 2000 + aY; } dStr = dStr.substring(0, dStr.length() - 2) + String.valueOf(aY); } if (dStr.length() == 14) { StringBuilder strb = new StringBuilder(dStr); strb.insert(6, "0"); dStr = strb.toString(); } String mn = dStr.substring(8, 11); String Nmn = mn.substring(0, 1).toUpperCase() + mn.substring(1, 3).toLowerCase(); dStr = dStr.replace(mn, Nmn); dStr = dStr.replace("Z", " "); SimpleDateFormat formatter = new SimpleDateFormat("HH:mm ddMMMyyyy", Locale.ENGLISH); try { TDEF.STime = formatter.parse(dStr); } catch (ParseException ex) { Logger.getLogger(GrADSDataInfo.class.getName()).log(Level.SEVERE, null, ex); } //Read time interval TDEF.TDelt = dataArray[4]; char[] tChar = dataArray[4].toCharArray(); int aPos = 0; //Position between number and string for (i = 0; i < tChar.length; i++) { if (!Character.isDigit(tChar[i])) { aPos = i; break; } } if (aPos == 0) { errorStr = "TDEF is wrong! Please check the ctl file!"; //goto ERROR; } int iNum = Integer.parseInt(TDEF.TDelt.substring(0, aPos)); TDEF.DeltaValue = iNum; Calendar cal = Calendar.getInstance(); cal.setTime(TDEF.STime); String tStr = TDEF.TDelt.substring(aPos).toLowerCase(); TDEF.unit = tStr; switch (tStr) { case "mn": for (i = 0; i < tnum; i++) { TDEF.times.add(cal.getTime()); cal.add(Calendar.MINUTE, iNum); } break; case "hr": for (i = 0; i < tnum; i++) { TDEF.times.add(cal.getTime()); cal.add(Calendar.HOUR, iNum); } break; case "dy": for (i = 0; i < tnum; i++) { TDEF.times.add(cal.getTime()); cal.add(Calendar.DAY_OF_YEAR, iNum); } break; case "mo": case "mon": for (i = 0; i < tnum; i++) { TDEF.times.add(cal.getTime()); cal.add(Calendar.MONTH, iNum); } break; case "yr": for (i = 0; i < tnum; i++) { TDEF.times.add(cal.getTime()); cal.add(Calendar.YEAR, iNum); } break; default: break; } values = new ArrayList<>(); for (Date t : TDEF.times) { values.add(DateUtil.toOADate(t)); } Dimension tDim = new Dimension(DimensionType.T); tDim.setShortName("T"); tDim.setValues(values); this.setTimeDimension(tDim); this.addDimension(tDim); } else { if (dataArray.length < tnum + 3) { while (true) { aLine = aLine + " " + sr.readLine().trim(); if (aLine.isEmpty()) { continue; } dataArray = aLine.split("\\s+"); if (dataArray.length >= tnum + 3) { break; } } } if (dataArray.length > tnum + 3) { errorStr = "TDEF is wrong! Please check the ctl file!"; //goto ERROR; } SimpleDateFormat formatter = new SimpleDateFormat("HH:mm ddMMMyyyy", Locale.ENGLISH); values = new ArrayList<>(); for (i = 0; i < tnum; i++) { try { String dStr = dataArray[3 + i]; dStr = dStr.replace("Z", " "); Date t = formatter.parse(dStr); TDEF.times.add(t); values.add(DateUtil.toOADate(t)); } catch (ParseException ex) { Logger.getLogger(GrADSDataInfo.class.getName()).log(Level.SEVERE, null, ex); } } Dimension tDim = new Dimension(DimensionType.T); tDim.setShortName("T"); tDim.setValues(values); this.setTimeDimension(tDim); this.addDimension(tDim); } break; case "EDEF": int eNum = Integer.parseInt(dataArray[1]); if (dataArray.length < eNum + 3) { while (true) { aLine = aLine + " " + sr.readLine().trim(); if (aLine.isEmpty()) { continue; } dataArray = aLine.split("\\s+"); if (dataArray.length >= eNum + 3) { break; } } } if (dataArray.length > eNum + 3) { errorStr = "EDEF is wrong! Please check the ctl file!"; } for (i = 0; i < eNum; i++){ this.ensNames.add(dataArray[3 + i]); } eDim = new Dimension(DimensionType.E); eDim.setLength(eNum); this.addDimension(eDim); Variable evar = new Variable(); evar.setName("ensemble"); evar.setDataType(DataType.STRING); evar.addAttribute("standard_name", "ensemble"); evar.addDimension(eDim); this.addVariable(evar); break; case "VARS": int vNum = Integer.parseInt(dataArray[1]); for (i = 0; i < vNum; i++) { aLine = sr.readLine().trim(); if (aLine.isEmpty()) { i -= 1; continue; } dataArray = aLine.split("\\s+"); Variable aVar = new Variable(); aVar.setName(dataArray[0]); aVar.setDataType(DataType.FLOAT); int lNum = Integer.parseInt(dataArray[1]); //aVar.setLevelNum(Integer.parseInt(dataArray[1])); aVar.setUnits(dataArray[2]); //attr = new Attribute("units", dataArray[2]); //aVar.addAttribute(attr); if (dataArray.length > 3) { aVar.setDescription(dataArray[3]); attr = new Attribute("description", dataArray[3]); aVar.addAttribute(attr); } if (eDim != null){ aVar.addDimension(eDim); } aVar.setDimension(this.getTimeDimension()); if (lNum > 1) { boolean isNew = true; for (Dimension dim : this.getDimensions()) { if (dim.getDimType() == DimensionType.Z) { if (lNum == dim.getLength()) { aVar.setDimension(dim); isNew = false; break; } } } if (isNew) { List<Double> levs = new ArrayList<>(); for (int j = 0; j < lNum; j++) { if (ZDEF.ZNum > j) { aVar.addLevel(ZDEF.ZLevels[j]); levs.add((double) ZDEF.ZLevels[j]); } } Dimension dim = new Dimension(DimensionType.Z); dim.setShortName("Z_" + String.valueOf(lNum)); dim.setValues(levs); aVar.setDimension(dim); this.addDimension(dim); } } aVar.setDimension(this.getYDimension()); aVar.setDimension(this.getXDimension()); if (this.getDataType() == MeteoDataType.GrADS_Station) { aVar.setStation(true); } aVar.setFillValue(this.getMissingValue()); VARDEF.addVar(aVar); this.addVariable(aVar); } break; case "ENDVARS": isEnd = true; break; default: break; } if (isEnd) { break; } } while (aLine != null); sr.close(); //Set X/Y coordinate if (isLatLon) { X = XDEF.X; Y = YDEF.Y; XNum = XDEF.XNum; YNum = YDEF.YNum; } //Calculate record length RecordLen = XNum * YNum * 4; if (OPTIONS.sequential) { RecordLen += 8; } //Calculate data length of each time RecLenPerTime = 0; int lNum; for (i = 0; i < VARDEF.getVNum(); i++) { lNum = VARDEF.getVars().get(i).getLevelNum(); if (lNum == 0) { lNum = 1; } RecLenPerTime += lNum * RecordLen; } return true; }
boolean function(String aFile, String errorStr) throws FileNotFoundException, IOException { this.setFileName(aFile); BufferedReader sr = new BufferedReader(new FileReader(new File(aFile))); String aLine = STRdata_formatSTRGrADS binarySTR\\s+STRDSETSTR/STR\\STR^STR/STR./STR.\\STRThe data file is not exist!STRline.separatorSTRDTYPESTRGRIDDEDSTRSTATIONSTRThe data type is not supported at present!STRline.separatorSTRSTATIONSTRdata_typeSTROPTIONSSTRbig_endianSTRbyteswappedSTR365_day_calendarSTRcray_32bit_ieeeSTRlittle_endianSTRpascalsSTRsequentialSTRtemplateSTRyrevSTRzrevSTRUNDEFSTRfill_valueSTRTITLESTRtitleSTRFILEHEADERSTRTHEADERSTRXYHEADERSTRPDEFSTRLCCSTRLCCRSTR+proj=lccSTR +lat_1=STR +lat_2=STR +lat_0=STR +lon_0=STRLCCRSTRXSTRYSTRNPSSTRSPSSTR90STRSPSSTR-90STR+proj=stere +lon_0=STR +lat_0=STRXSTRYSTRThe PDEF type is not supported at present!STRline.separatorSTRPlease send your data to the author to improve MeteoInfo!STRXDEFSTRLINEARSTR STR\\s+STRXDEF is wrong! Please check the ctl file!STRXSTRYDEFSTRLINEARSTR STR\\s+STRYDEF is wrong! Please check the ctl file!STRYSTRZDEFSTRLINEARSTR\\s+STR\\s+STR STRZSTRTDEFSTRLINEARSTRZSTR00:00ZSTR00:00Z01STR0STR:00STR:00STR0STRZSTR STRHH:mm ddMMMyyyySTRTDEF is wrong! Please check the ctl file!STRmnSTRhrSTRdySTRmoSTRmonSTRyrSTRTSTR STR\\s+STRTDEF is wrong! Please check the ctl file!STRHH:mm ddMMMyyyySTRZSTR STRTSTREDEFSTR STR\\s+STREDEF is wrong! Please check the ctl file!STRensembleSTRstandard_nameSTRensembleSTRVARSSTR\\s+STRdescriptionSTRZ_STRENDVARS": isEnd = true; break; default: break; } if (isEnd) { break; } } while (aLine != null); sr.close(); if (isLatLon) { X = XDEF.X; Y = YDEF.Y; XNum = XDEF.XNum; YNum = YDEF.YNum; } RecordLen = XNum * YNum * 4; if (OPTIONS.sequential) { RecordLen += 8; } RecLenPerTime = 0; int lNum; for (i = 0; i < VARDEF.getVNum(); i++) { lNum = VARDEF.getVars().get(i).getLevelNum(); if (lNum == 0) { lNum = 1; } RecLenPerTime += lNum * RecordLen; } return true; }
/** * Read GrADS control file * * @param aFile The control file * @param errorStr Error string * @return If read corrected */
Read GrADS control file
readDataInfo
{ "repo_name": "meteoinfo/meteoinfolib", "path": "src/org/meteoinfo/data/meteodata/grads/GrADSDataInfo.java", "license": "lgpl-3.0", "size": 115651 }
[ "java.io.BufferedReader", "java.io.File", "java.io.FileNotFoundException", "java.io.FileReader", "java.io.IOException" ]
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
561,800
public synchronized void setConfiguration(Set<String> atomicStateIds) throws ModelException { exctx.initialize(); Set<EnterableState> states = new HashSet<EnterableState>(); for (String stateId : atomicStateIds) { TransitionTarget tt = getStateMachine().getTargets().get(stateId); if (tt instanceof EnterableState && ((EnterableState)tt).isAtomicState()) { EnterableState es = (EnterableState)tt; while (es != null && !states.add(es)) { es = es.getParent(); } } else { throw new ModelException("Illegal atomic stateId "+stateId+": state unknown or not an atomic state"); } } if (semantics.isLegalConfiguration(states, getErrorReporter())) { for (EnterableState es : states) { exctx.getScInstance().getStateConfiguration().enterState(es); } logState(); } else { throw new ModelException("Illegal state machine configuration!"); } }
synchronized void function(Set<String> atomicStateIds) throws ModelException { exctx.initialize(); Set<EnterableState> states = new HashSet<EnterableState>(); for (String stateId : atomicStateIds) { TransitionTarget tt = getStateMachine().getTargets().get(stateId); if (tt instanceof EnterableState && ((EnterableState)tt).isAtomicState()) { EnterableState es = (EnterableState)tt; while (es != null && !states.add(es)) { es = es.getParent(); } } else { throw new ModelException(STR+stateId+STR); } } if (semantics.isLegalConfiguration(states, getErrorReporter())) { for (EnterableState es : states) { exctx.getScInstance().getStateConfiguration().enterState(es); } logState(); } else { throw new ModelException(STR); } }
/** * Initializes the state machine with a specific active configuration * <p> * This will first (re)initialize the current state machine: clearing all variable contexts, histories and current * status, and clones the SCXML root datamodel into the root context. * </p> * @param atomicStateIds The set of atomic state ids for the state machine * @throws ModelException when the state machine hasn't been properly configured yet, when an unknown or illegal * stateId is specified, or when the specified active configuration does not represent a legal configuration. * @see SCInstance#initialize() * @see SCXMLSemantics#isLegalConfiguration(java.util.Set, ErrorReporter) */
Initializes the state machine with a specific active configuration This will first (re)initialize the current state machine: clearing all variable contexts, histories and current status, and clones the SCXML root datamodel into the root context.
setConfiguration
{ "repo_name": "mohanaraosv/commons-scxml", "path": "src/main/java/org/apache/commons/scxml2/SCXMLExecutor.java", "license": "apache-2.0", "size": 17923 }
[ "java.util.HashSet", "java.util.Set", "org.apache.commons.scxml2.model.EnterableState", "org.apache.commons.scxml2.model.ModelException", "org.apache.commons.scxml2.model.TransitionTarget" ]
import java.util.HashSet; import java.util.Set; import org.apache.commons.scxml2.model.EnterableState; import org.apache.commons.scxml2.model.ModelException; import org.apache.commons.scxml2.model.TransitionTarget;
import java.util.*; import org.apache.commons.scxml2.model.*;
[ "java.util", "org.apache.commons" ]
java.util; org.apache.commons;
1,596,306
@Test public void testReverseIntensity() throws Exception { //First import an image File f = File.createTempFile("testReverseIntensity", "." + OME_FORMAT); XMLMockObjects xml = new XMLMockObjects(); XMLWriter writer = new XMLWriter(); writer.writeFile(f, xml.createImage(), true); List<Pixels> pixels = null; try { pixels = importFile(f, OME_FORMAT); } catch (Throwable e) { throw new Exception("cannot import image", e); } Pixels p = pixels.get(0); long id = p.getId().getValue(); factory.getRenderingSettingsService().setOriginalSettingsInSet( Pixels.class.getName(), Arrays.asList(id)); RenderingEnginePrx re = factory.createRenderingEngine(); re.lookupPixels(id); if (!(re.lookupRenderingDef(id))) { re.resetDefaultSettings(true); re.lookupRenderingDef(id); } re.load(); PlaneDef pDef = new PlaneDef(); pDef.t = re.getDefaultT(); pDef.z = re.getDefaultZ(); pDef.slice = omero.romio.XY.value; RenderingDef def = factory.getPixelsService().retrieveRndSettings(id); List<ChannelBinding> channels = def.copyWaveRendering(); int end = re.getQuantumDef().getCdEnd().getValue(); //color model: greyscale for (int k = 0; k < channels.size(); k++) { int[] before = re.renderAsPackedInt(pDef); re.addCodomainMapToChannel(new omero.romio.ReverseIntensityMapContext(), k); int[] after = re.renderAsPackedInt(pDef); for (int i = 0; i < before.length; i++) { //get the discrete value w/o codomain map int bp = before[i] & 0x0ff; //get the discrete value with codomain map int ap = after[i] & 0x0ff; //check that the reverse intensity was applied Assert.assertEquals(ap, (end-bp)); } } }
void function() throws Exception { File f = File.createTempFile(STR, "." + OME_FORMAT); XMLMockObjects xml = new XMLMockObjects(); XMLWriter writer = new XMLWriter(); writer.writeFile(f, xml.createImage(), true); List<Pixels> pixels = null; try { pixels = importFile(f, OME_FORMAT); } catch (Throwable e) { throw new Exception(STR, e); } Pixels p = pixels.get(0); long id = p.getId().getValue(); factory.getRenderingSettingsService().setOriginalSettingsInSet( Pixels.class.getName(), Arrays.asList(id)); RenderingEnginePrx re = factory.createRenderingEngine(); re.lookupPixels(id); if (!(re.lookupRenderingDef(id))) { re.resetDefaultSettings(true); re.lookupRenderingDef(id); } re.load(); PlaneDef pDef = new PlaneDef(); pDef.t = re.getDefaultT(); pDef.z = re.getDefaultZ(); pDef.slice = omero.romio.XY.value; RenderingDef def = factory.getPixelsService().retrieveRndSettings(id); List<ChannelBinding> channels = def.copyWaveRendering(); int end = re.getQuantumDef().getCdEnd().getValue(); for (int k = 0; k < channels.size(); k++) { int[] before = re.renderAsPackedInt(pDef); re.addCodomainMapToChannel(new omero.romio.ReverseIntensityMapContext(), k); int[] after = re.renderAsPackedInt(pDef); for (int i = 0; i < before.length; i++) { int bp = before[i] & 0x0ff; int ap = after[i] & 0x0ff; Assert.assertEquals(ap, (end-bp)); } } }
/** * Tests reverse intensity * @throws Exception */
Tests reverse intensity
testReverseIntensity
{ "repo_name": "simleo/openmicroscopy", "path": "components/tools/OmeroJava/test/integration/RenderingEngineTest.java", "license": "gpl-2.0", "size": 131741 }
[ "java.io.File", "java.util.Arrays", "java.util.List", "org.testng.Assert" ]
import java.io.File; import java.util.Arrays; import java.util.List; import org.testng.Assert;
import java.io.*; import java.util.*; import org.testng.*;
[ "java.io", "java.util", "org.testng" ]
java.io; java.util; org.testng;
2,844,760
@SuppressWarnings("unchecked") private static EventTrigger buildEventTrigger(EmfEvent event) { String targetClass = null; Serializable targetId = null; String serverOperation = ""; String userOperation = ""; Object instance = null; if (event instanceof AbstractInstanceEvent) { instance = ((AbstractInstanceEvent<?>) event).getInstance(); } else if (event instanceof AbstractInstanceTwoPhaseEvent) { instance = ((AbstractInstanceTwoPhaseEvent<?, ?>) event).getInstance(); } if (instance instanceof Instance) { targetClass = ((Instance) instance).type().getId().toString(); targetId = ((Instance) instance).getId(); } else if (instance instanceof InstanceReference) { targetClass = ((InstanceReference) instance).getType().getId().toString(); targetId = ((InstanceReference) instance).getId(); } if (event instanceof OperationEvent) { serverOperation = ((OperationEvent) event).getOperationId(); Operation operationObj = ((OperationEvent) event).getOperation(); if (operationObj != null) { userOperation = operationObj.getUserOperationId(); } } Class<? extends EmfEvent> eventClass = (Class<? extends EmfEvent>) ReflectionUtils.getWeldBeanClass(event); return new EventTrigger(eventClass, targetClass, targetId, serverOperation, userOperation); }
@SuppressWarnings(STR) static EventTrigger function(EmfEvent event) { String targetClass = null; Serializable targetId = null; String serverOperation = STR"; Object instance = null; if (event instanceof AbstractInstanceEvent) { instance = ((AbstractInstanceEvent<?>) event).getInstance(); } else if (event instanceof AbstractInstanceTwoPhaseEvent) { instance = ((AbstractInstanceTwoPhaseEvent<?, ?>) event).getInstance(); } if (instance instanceof Instance) { targetClass = ((Instance) instance).type().getId().toString(); targetId = ((Instance) instance).getId(); } else if (instance instanceof InstanceReference) { targetClass = ((InstanceReference) instance).getType().getId().toString(); targetId = ((InstanceReference) instance).getId(); } if (event instanceof OperationEvent) { serverOperation = ((OperationEvent) event).getOperationId(); Operation operationObj = ((OperationEvent) event).getOperation(); if (operationObj != null) { userOperation = operationObj.getUserOperationId(); } } Class<? extends EmfEvent> eventClass = (Class<? extends EmfEvent>) ReflectionUtils.getWeldBeanClass(event); return new EventTrigger(eventClass, targetClass, targetId, serverOperation, userOperation); }
/** * Builds the event trigger from the given event instance. * * @param event * the event * @return the event trigger that matches the given event */
Builds the event trigger from the given event instance
buildEventTrigger
{ "repo_name": "SirmaITT/conservation-space-1.7.0", "path": "docker/sirma-platform/platform/seip-parent/extensions/task-schedule/task-schedule-core/src/main/java/com/sirma/itt/seip/tasks/SchedulerServiceImpl.java", "license": "lgpl-3.0", "size": 26066 }
[ "com.sirma.itt.seip.domain.event.AbstractInstanceTwoPhaseEvent", "com.sirma.itt.seip.domain.event.OperationEvent", "com.sirma.itt.seip.domain.instance.Instance", "com.sirma.itt.seip.domain.instance.InstanceReference", "com.sirma.itt.seip.event.AbstractInstanceEvent", "com.sirma.itt.seip.event.EmfEvent", "com.sirma.itt.seip.instance.state.Operation", "com.sirma.itt.seip.util.ReflectionUtils", "java.io.Serializable" ]
import com.sirma.itt.seip.domain.event.AbstractInstanceTwoPhaseEvent; import com.sirma.itt.seip.domain.event.OperationEvent; import com.sirma.itt.seip.domain.instance.Instance; import com.sirma.itt.seip.domain.instance.InstanceReference; import com.sirma.itt.seip.event.AbstractInstanceEvent; import com.sirma.itt.seip.event.EmfEvent; import com.sirma.itt.seip.instance.state.Operation; import com.sirma.itt.seip.util.ReflectionUtils; import java.io.Serializable;
import com.sirma.itt.seip.domain.event.*; import com.sirma.itt.seip.domain.instance.*; import com.sirma.itt.seip.event.*; import com.sirma.itt.seip.instance.state.*; import com.sirma.itt.seip.util.*; import java.io.*;
[ "com.sirma.itt", "java.io" ]
com.sirma.itt; java.io;
747,074
public void writeDataArrayToSheet(XSSFSheet sheet, Object[] data, int ic, int ir, boolean inColumn) { // write to wb for (int r = 0; r < data.length; r++) { if (data[r] != null) { if (inColumn) writeToCell(sheet, ic, r + ir, data[r]); else writeToCell(sheet, ic + r, ir, data[r]); } } }
void function(XSSFSheet sheet, Object[] data, int ic, int ir, boolean inColumn) { for (int r = 0; r < data.length; r++) { if (data[r] != null) { if (inColumn) writeToCell(sheet, ic, r + ir, data[r]); else writeToCell(sheet, ic + r, ir, data[r]); } } }
/** * writes a data array to one column * * @param data * @param inColumn in column or inRow? */
writes a data array to one column
writeDataArrayToSheet
{ "repo_name": "mzmine/mzmine3", "path": "src/main/java/io/github/mzmine/util/io/XSSFExcelWriterReader.java", "license": "gpl-2.0", "size": 11253 }
[ "org.apache.poi.xssf.usermodel.XSSFSheet" ]
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.*;
[ "org.apache.poi" ]
org.apache.poi;
1,277,682
public static Color getRepresentingColor(final int id, final int value){ if (colorlist[id][value] == null){ //if not in list, add it to the list colorlist[id][value] = new Color(); int colorInt; if (Block.getInstance(id,value, new Coordinate(0,0,0,false)).hasSides){ AtlasRegion texture = getBlockSprite(id, value, 1); if (texture == null) return new Color(); colorInt = getPixmap().getPixel( texture.getRegionX()+SCREEN_DEPTH2, texture.getRegionY()-SCREEN_DEPTH4); } else { AtlasRegion texture = getSprite('b', id, value); if (texture == null) return new Color(); colorInt = getPixmap().getPixel( texture.getRegionX()+SCREEN_DEPTH2, texture.getRegionY()-SCREEN_DEPTH2); } Color.rgba8888ToColor(colorlist[id][value], colorInt); return colorlist[id][value]; } else return colorlist[id][value]; //return value when in list }
static Color function(final int id, final int value){ if (colorlist[id][value] == null){ colorlist[id][value] = new Color(); int colorInt; if (Block.getInstance(id,value, new Coordinate(0,0,0,false)).hasSides){ AtlasRegion texture = getBlockSprite(id, value, 1); if (texture == null) return new Color(); colorInt = getPixmap().getPixel( texture.getRegionX()+SCREEN_DEPTH2, texture.getRegionY()-SCREEN_DEPTH4); } else { AtlasRegion texture = getSprite('b', id, value); if (texture == null) return new Color(); colorInt = getPixmap().getPixel( texture.getRegionX()+SCREEN_DEPTH2, texture.getRegionY()-SCREEN_DEPTH2); } Color.rgba8888ToColor(colorlist[id][value], colorInt); return colorlist[id][value]; } else return colorlist[id][value]; }
/** * Returns a color representing the block. Picks from the sprite sprite. * @param id id of the Block * @param value the value of the block. * @return a color representing the block */
Returns a color representing the block. Picks from the sprite sprite
getRepresentingColor
{ "repo_name": "thtomate/W-E-f-a", "path": "src/com/BombingGames/WurfelEngine/Core/Gameobjects/Block.java", "license": "bsd-3-clause", "size": 22907 }
[ "com.badlogic.gdx.graphics.Color", "com.badlogic.gdx.graphics.g2d.TextureAtlas" ]
import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.*; import com.badlogic.gdx.graphics.g2d.*;
[ "com.badlogic.gdx" ]
com.badlogic.gdx;
2,323,985
public AstRoot parse(String sourceString, String sourceURI, int lineno) { if (parseFinished) throw new IllegalStateException("parser reused"); this.sourceURI = sourceURI; if (compilerEnv.isIdeMode()) { this.sourceChars = sourceString.toCharArray(); } this.ts = new TokenStream(this, null, sourceString, lineno); try { return parse(); } catch (IOException iox) { // Should never happen throw new IllegalStateException(); } finally { parseFinished = true; } }
AstRoot function(String sourceString, String sourceURI, int lineno) { if (parseFinished) throw new IllegalStateException(STR); this.sourceURI = sourceURI; if (compilerEnv.isIdeMode()) { this.sourceChars = sourceString.toCharArray(); } this.ts = new TokenStream(this, null, sourceString, lineno); try { return parse(); } catch (IOException iox) { throw new IllegalStateException(); } finally { parseFinished = true; } }
/** * Builds a parse tree from the given source string. * * @return an {@link AstRoot} object representing the parsed program. If * the parse fails, {@code null} will be returned. (The parse failure will * result in a call to the {@link ErrorReporter} from * {@link CompilerEnvirons}.) */
Builds a parse tree from the given source string
parse
{ "repo_name": "Pilarbrist/rhino", "path": "src/org/mozilla/javascript/Parser.java", "license": "mpl-2.0", "size": 146072 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
615,416
public static String mainDirectory(String directory) { String dirname = directory + File.separator + Properties.PROJECT_PREFIX.replace('.', File.separatorChar); // +"/GeneratedTests"; File dir = new File(dirname); logger.debug("Target directory: " + dirname); dir.mkdirs(); return dirname; }
static String function(String directory) { String dirname = directory + File.separator + Properties.PROJECT_PREFIX.replace('.', File.separatorChar); File dir = new File(dirname); logger.debug(STR + dirname); dir.mkdirs(); return dirname; }
/** * Create subdirectory for package in test directory * * @param directory * a {@link java.lang.String} object. * @return a {@link java.lang.String} object. */
Create subdirectory for package in test directory
mainDirectory
{ "repo_name": "claudejin/evosuite", "path": "client/src/main/java/org/evosuite/junit/writer/TestSuiteWriterUtils.java", "license": "lgpl-3.0", "size": 5818 }
[ "java.io.File", "org.evosuite.Properties" ]
import java.io.File; import org.evosuite.Properties;
import java.io.*; import org.evosuite.*;
[ "java.io", "org.evosuite" ]
java.io; org.evosuite;
69,817
public static void setLink(String path, String title, String target) { nativeSetLink(path, CmsStringUtil.escapeHtml(title), target); }
static void function(String path, String title, String target) { nativeSetLink(path, CmsStringUtil.escapeHtml(title), target); }
/** * Sets the resource link within the rich text editor (FCKEditor, CKEditor, ...).<p> * * @param path the link path * @param title the link title * @param target the link target attribute */
Sets the resource link within the rich text editor (FCKEditor, CKEditor, ...)
setLink
{ "repo_name": "serrapos/opencms-core", "path": "src-gwt/org/opencms/ade/galleries/client/preview/CmsPreviewUtil.java", "license": "lgpl-2.1", "size": 15765 }
[ "org.opencms.util.CmsStringUtil" ]
import org.opencms.util.CmsStringUtil;
import org.opencms.util.*;
[ "org.opencms.util" ]
org.opencms.util;
2,511,116
public int tickRate(World worldIn) { return 4; }
int function(World worldIn) { return 4; }
/** * How many world ticks before ticking */
How many world ticks before ticking
tickRate
{ "repo_name": "Hexeption/Youtube-Hacked-Client-1.8", "path": "minecraft/net/minecraft/block/BlockDispenser.java", "license": "mit", "size": 9682 }
[ "net.minecraft.world.World" ]
import net.minecraft.world.World;
import net.minecraft.world.*;
[ "net.minecraft.world" ]
net.minecraft.world;
2,585,994
@NotNull SCMNode parseNode(@NotNull SCMCompositeNode container, @NotNull IToken token, @NotNull SCMSourceScanner scanner);
SCMNode parseNode(@NotNull SCMCompositeNode container, @NotNull IToken token, @NotNull SCMSourceScanner scanner);
/** * Returns parsed node. Null on end of file */
Returns parsed node. Null on end of file
parseNode
{ "repo_name": "dbeaver/dbeaver", "path": "plugins/org.jkiss.dbeaver.lang/src/org/jkiss/dbeaver/lang/SCMSourceParser.java", "license": "apache-2.0", "size": 1123 }
[ "org.eclipse.jface.text.rules.IToken", "org.jkiss.code.NotNull" ]
import org.eclipse.jface.text.rules.IToken; import org.jkiss.code.NotNull;
import org.eclipse.jface.text.rules.*; import org.jkiss.code.*;
[ "org.eclipse.jface", "org.jkiss.code" ]
org.eclipse.jface; org.jkiss.code;
2,278,710