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
public void plnI(Object o) throws IOException { p(o.toString()); pln(); pI(); }
void function(Object o) throws IOException { p(o.toString()); pln(); pI(); }
/** * Writes object; ends current line; indents in. **/
Writes object; ends current line; indents in
plnI
{ "repo_name": "rokn/Count_Words_2015", "path": "testing/openjdk2/jdk/src/share/classes/sun/rmi/rmic/newrmic/IndentingWriter.java", "license": "mit", "size": 7592 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
575,833
@Test public void testInverseOrder() { final List<FDate> ents = new ArrayList<FDate>(entities); Collections.reverse(ents); for (final FDate entity : ents) { Assertions.assertThat(cache.query().getValue(entity)).isNotNull(); } Assertions.assertThat(countReadAllValuesAscendingFrom).isEqualTo(6); Assertions.assertThat(countReadNewestValueTo).isEqualTo(2); }
void function() { final List<FDate> ents = new ArrayList<FDate>(entities); Collections.reverse(ents); for (final FDate entity : ents) { Assertions.assertThat(cache.query().getValue(entity)).isNotNull(); } Assertions.assertThat(countReadAllValuesAscendingFrom).isEqualTo(6); Assertions.assertThat(countReadNewestValueTo).isEqualTo(2); }
/** * for reverse sorting this is less efficient, this costs O(n) for queries. */
for reverse sorting this is less efficient, this costs O(n) for queries
testInverseOrder
{ "repo_name": "subes/invesdwin-util", "path": "invesdwin-util-parent/invesdwin-util/src/test/java/de/invesdwin/util/collections/loadingcache/historical/AGapHistoricalCacheWithNoCacheTest.java", "license": "lgpl-3.0", "size": 82413 }
[ "de.invesdwin.util.assertions.Assertions", "de.invesdwin.util.time.date.FDate", "java.util.ArrayList", "java.util.Collections", "java.util.List" ]
import de.invesdwin.util.assertions.Assertions; import de.invesdwin.util.time.date.FDate; import java.util.ArrayList; import java.util.Collections; import java.util.List;
import de.invesdwin.util.assertions.*; import de.invesdwin.util.time.date.*; import java.util.*;
[ "de.invesdwin.util", "java.util" ]
de.invesdwin.util; java.util;
1,668,577
public Dao<PersistentLocation, Integer> getCommentsDao() throws SQLException { if (locationsDao == null) { locationsDao = getDao(PersistentLocation.class); } return locationsDao; }
Dao<PersistentLocation, Integer> function() throws SQLException { if (locationsDao == null) { locationsDao = getDao(PersistentLocation.class); } return locationsDao; }
/** * Returns the Database Access Object (DAO) for our SimpleData class. It will create it or just give the cached * value. */
Returns the Database Access Object (DAO) for our SimpleData class. It will create it or just give the cached value
getCommentsDao
{ "repo_name": "tgnourse/android-dive-guide", "path": "app/src/main/java/com/int8/diveguide/OrmDatabaseHelper.java", "license": "mit", "size": 4222 }
[ "com.j256.ormlite.dao.Dao", "java.sql.SQLException" ]
import com.j256.ormlite.dao.Dao; import java.sql.SQLException;
import com.j256.ormlite.dao.*; import java.sql.*;
[ "com.j256.ormlite", "java.sql" ]
com.j256.ormlite; java.sql;
2,766,339
return new JUnit4TestAdapter(IntegrationTest.class); }
return new JUnit4TestAdapter(IntegrationTest.class); }
/** * <p> * Creates a test suite for the tests in this test case. * </p> * * @return a Test suite for this test case. */
Creates a test suite for the tests in this test case.
suite
{ "repo_name": "NASA-Tournament-Lab/CoECI-OPM-Service-Credit-Redeposit-Deposit-Application", "path": "Code/SCRD_BRE/src/java/tests/gov/opm/scrd/IntegrationTest.java", "license": "apache-2.0", "size": 39833 }
[ "junit.framework.JUnit4TestAdapter" ]
import junit.framework.JUnit4TestAdapter;
import junit.framework.*;
[ "junit.framework" ]
junit.framework;
1,065,959
protected Knob<Double> createKnobDouble(Composite parent, double min, double max) { Knob<Double> knob = new Knob<Double>(parent, SWT.NULL, new KnobRange.Double(min, max)); knob.setLayoutData(GridDataFactory.swtDefaults().grab(false, false).align(SWT.CENTER, SWT.CENTER).hint(30, 30).create()); knob.setDefaultColorProfile(defaultColorProfile); knob.setFocusedColorProfile(focusedColorProfile); return knob; }
Knob<Double> function(Composite parent, double min, double max) { Knob<Double> knob = new Knob<Double>(parent, SWT.NULL, new KnobRange.Double(min, max)); knob.setLayoutData(GridDataFactory.swtDefaults().grab(false, false).align(SWT.CENTER, SWT.CENTER).hint(30, 30).create()); knob.setDefaultColorProfile(defaultColorProfile); knob.setFocusedColorProfile(focusedColorProfile); return knob; }
/** * Creates a double knob * @param parent * @param min * @param max * @return */
Creates a double knob
createKnobDouble
{ "repo_name": "RaffaelBild/arx", "path": "src/gui/org/deidentifier/arx/gui/view/impl/menu/EditorCriterion.java", "license": "apache-2.0", "size": 6115 }
[ "de.linearbits.swt.widgets.Knob", "de.linearbits.swt.widgets.KnobRange", "org.eclipse.jface.layout.GridDataFactory", "org.eclipse.swt.widgets.Composite" ]
import de.linearbits.swt.widgets.Knob; import de.linearbits.swt.widgets.KnobRange; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.swt.widgets.Composite;
import de.linearbits.swt.widgets.*; import org.eclipse.jface.layout.*; import org.eclipse.swt.widgets.*;
[ "de.linearbits.swt", "org.eclipse.jface", "org.eclipse.swt" ]
de.linearbits.swt; org.eclipse.jface; org.eclipse.swt;
2,428,578
private boolean fillBuffer(int minimum) throws IOException { char[] buffer = this.buffer; lineStart -= pos; if (limit != pos) { limit -= pos; System.arraycopy(buffer, pos, buffer, 0, limit); } else { limit = 0; } pos = 0; int total; while ((total = in.read(buffer, limit, buffer.length - limit)) != -1) { limit += total; // if this is the first read, consume an optional byte order mark (BOM) if it exists if (lineNumber == 0 && lineStart == 0 && limit > 0 && buffer[0] == '\ufeff') { pos++; lineStart++; minimum++; } if (limit >= minimum) { return true; } } return false; }
boolean function(int minimum) throws IOException { char[] buffer = this.buffer; lineStart -= pos; if (limit != pos) { limit -= pos; System.arraycopy(buffer, pos, buffer, 0, limit); } else { limit = 0; } pos = 0; int total; while ((total = in.read(buffer, limit, buffer.length - limit)) != -1) { limit += total; if (lineNumber == 0 && lineStart == 0 && limit > 0 && buffer[0] == '\ufeff') { pos++; lineStart++; minimum++; } if (limit >= minimum) { return true; } } return false; }
/** * Returns true once {@code limit - pos >= minimum}. If the data is * exhausted before that many characters are available, this returns * false. */
Returns true once limit - pos >= minimum. If the data is exhausted before that many characters are available, this returns false
fillBuffer
{ "repo_name": "Nasso/urmusic-desktop", "path": "src/com/google/gson/stream/JsonReader.java", "license": "gpl-2.0", "size": 49920 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
1,131,987
public Object getAttribute( final String attrName ) throws FileSystemException { if ( LAST_REFRESH_TIME_ATTRIBUTE.equals( attrName ) ) { return Long.valueOf( solutionFileModel.getRefreshTime() ); } if ( MAJOR_VERSION.equals( attrName ) ) { return ( solutionFileModel.getMajorVersion() ); } if ( MINOR_VERSION.equals( attrName ) ) { return ( solutionFileModel.getMinorVersion() ); } if ( BUILD_VERSION.equals( attrName ) ) { return ( solutionFileModel.getBuildVersion() ); } if ( RELEASE_VERSION.equals( attrName ) ) { return ( solutionFileModel.getReleaseVersion() ); } if ( MILESTONE_VERSION.equals( attrName ) ) { return ( solutionFileModel.getMilestoneVersion() ); } return null; }
Object function( final String attrName ) throws FileSystemException { if ( LAST_REFRESH_TIME_ATTRIBUTE.equals( attrName ) ) { return Long.valueOf( solutionFileModel.getRefreshTime() ); } if ( MAJOR_VERSION.equals( attrName ) ) { return ( solutionFileModel.getMajorVersion() ); } if ( MINOR_VERSION.equals( attrName ) ) { return ( solutionFileModel.getMinorVersion() ); } if ( BUILD_VERSION.equals( attrName ) ) { return ( solutionFileModel.getBuildVersion() ); } if ( RELEASE_VERSION.equals( attrName ) ) { return ( solutionFileModel.getReleaseVersion() ); } if ( MILESTONE_VERSION.equals( attrName ) ) { return ( solutionFileModel.getMilestoneVersion() ); } return null; }
/** * Retrieves the attribute with the specified name. The default implementation simply throws an exception. */
Retrieves the attribute with the specified name. The default implementation simply throws an exception
getAttribute
{ "repo_name": "mbatchelor/pentaho-reporting", "path": "libraries/libpensol/src/main/java/org/pentaho/reporting/libraries/pensol/vfs/WebSolutionFileSystem.java", "license": "lgpl-2.1", "size": 3678 }
[ "org.apache.commons.vfs2.FileSystemException" ]
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.*;
[ "org.apache.commons" ]
org.apache.commons;
1,202,394
public void setFullscreen() { requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); }
void function() { requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); }
/** * Maximize the application. */
Maximize the application
setFullscreen
{ "repo_name": "Turupawn/LuxxorAR", "path": "src/edu/dhbw/andar/AndARActivity.java", "license": "gpl-3.0", "size": 10295 }
[ "android.view.Window", "android.view.WindowManager" ]
import android.view.Window; import android.view.WindowManager;
import android.view.*;
[ "android.view" ]
android.view;
1,026,172
private void validateOIDCProviderMetadata() { // ensure the authorization endpoint is present if (oidcProviderMetadata.getAuthorizationEndpointURI() == null) { throw new RuntimeException("OpenId Connect Provider metadata does not contain an Authorization Endpoint."); } // ensure the token endpoint is present if (oidcProviderMetadata.getTokenEndpointURI() == null) { throw new RuntimeException("OpenId Connect Provider metadata does not contain a Token Endpoint."); } // ensure the oidc provider supports basic or post client auth List<ClientAuthenticationMethod> clientAuthenticationMethods = oidcProviderMetadata.getTokenEndpointAuthMethods(); logger.info("OpenId Connect: Available clientAuthenticationMethods {} ", clientAuthenticationMethods); if (clientAuthenticationMethods == null || clientAuthenticationMethods.isEmpty()) { clientAuthenticationMethods = new ArrayList<>(); clientAuthenticationMethods.add(ClientAuthenticationMethod.CLIENT_SECRET_BASIC); oidcProviderMetadata.setTokenEndpointAuthMethods(clientAuthenticationMethods); logger.warn("OpenId Connect: ClientAuthenticationMethods is null, Setting clientAuthenticationMethods as CLIENT_SECRET_BASIC"); } else if (!clientAuthenticationMethods.contains(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) && !clientAuthenticationMethods.contains(ClientAuthenticationMethod.CLIENT_SECRET_POST)) { throw new RuntimeException(String.format("OpenId Connect Provider does not support %s or %s", ClientAuthenticationMethod.CLIENT_SECRET_BASIC.getValue(), ClientAuthenticationMethod.CLIENT_SECRET_POST.getValue())); } // extract the supported json web signature algorithms final List<JWSAlgorithm> allowedAlgorithms = oidcProviderMetadata.getIDTokenJWSAlgs(); if (allowedAlgorithms == null || allowedAlgorithms.isEmpty()) { throw new RuntimeException("The OpenId Connect Provider does not support any JWS algorithms."); } try { // get the preferred json web signature algorithm final JWSAlgorithm preferredJwsAlgorithm = extractJwsAlgorithm(); if (preferredJwsAlgorithm == null) { tokenValidator = new IDTokenValidator(oidcProviderMetadata.getIssuer(), clientId); } else if (JWSAlgorithm.HS256.equals(preferredJwsAlgorithm) || JWSAlgorithm.HS384.equals(preferredJwsAlgorithm) || JWSAlgorithm.HS512.equals(preferredJwsAlgorithm)) { tokenValidator = new IDTokenValidator(oidcProviderMetadata.getIssuer(), clientId, preferredJwsAlgorithm, clientSecret); } else { final ResourceRetriever retriever = new DefaultResourceRetriever(oidcConnectTimeout, oidcReadTimeout); tokenValidator = new IDTokenValidator(oidcProviderMetadata.getIssuer(), clientId, preferredJwsAlgorithm, oidcProviderMetadata.getJWKSetURI().toURL(), retriever); } } catch (final Exception e) { throw new RuntimeException("Unable to create the ID token validator for the configured OpenId Connect Provider: " + e.getMessage(), e); } }
void function() { if (oidcProviderMetadata.getAuthorizationEndpointURI() == null) { throw new RuntimeException(STR); } if (oidcProviderMetadata.getTokenEndpointURI() == null) { throw new RuntimeException(STR); } List<ClientAuthenticationMethod> clientAuthenticationMethods = oidcProviderMetadata.getTokenEndpointAuthMethods(); logger.info(STR, clientAuthenticationMethods); if (clientAuthenticationMethods == null clientAuthenticationMethods.isEmpty()) { clientAuthenticationMethods = new ArrayList<>(); clientAuthenticationMethods.add(ClientAuthenticationMethod.CLIENT_SECRET_BASIC); oidcProviderMetadata.setTokenEndpointAuthMethods(clientAuthenticationMethods); logger.warn(STR); } else if (!clientAuthenticationMethods.contains(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) && !clientAuthenticationMethods.contains(ClientAuthenticationMethod.CLIENT_SECRET_POST)) { throw new RuntimeException(String.format(STR, ClientAuthenticationMethod.CLIENT_SECRET_BASIC.getValue(), ClientAuthenticationMethod.CLIENT_SECRET_POST.getValue())); } final List<JWSAlgorithm> allowedAlgorithms = oidcProviderMetadata.getIDTokenJWSAlgs(); if (allowedAlgorithms == null allowedAlgorithms.isEmpty()) { throw new RuntimeException(STR); } try { final JWSAlgorithm preferredJwsAlgorithm = extractJwsAlgorithm(); if (preferredJwsAlgorithm == null) { tokenValidator = new IDTokenValidator(oidcProviderMetadata.getIssuer(), clientId); } else if (JWSAlgorithm.HS256.equals(preferredJwsAlgorithm) JWSAlgorithm.HS384.equals(preferredJwsAlgorithm) JWSAlgorithm.HS512.equals(preferredJwsAlgorithm)) { tokenValidator = new IDTokenValidator(oidcProviderMetadata.getIssuer(), clientId, preferredJwsAlgorithm, clientSecret); } else { final ResourceRetriever retriever = new DefaultResourceRetriever(oidcConnectTimeout, oidcReadTimeout); tokenValidator = new IDTokenValidator(oidcProviderMetadata.getIssuer(), clientId, preferredJwsAlgorithm, oidcProviderMetadata.getJWKSetURI().toURL(), retriever); } } catch (final Exception e) { throw new RuntimeException(STR + e.getMessage(), e); } }
/** * Validates the retrieved OIDC provider metadata. */
Validates the retrieved OIDC provider metadata
validateOIDCProviderMetadata
{ "repo_name": "mattyb149/nifi", "path": "nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/oidc/StandardOidcIdentityProvider.java", "license": "apache-2.0", "size": 27102 }
[ "com.nimbusds.jose.JWSAlgorithm", "com.nimbusds.jose.util.DefaultResourceRetriever", "com.nimbusds.jose.util.ResourceRetriever", "com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod", "com.nimbusds.openid.connect.sdk.validators.IDTokenValidator", "java.util.ArrayList", "java.util.List" ]
import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.util.DefaultResourceRetriever; import com.nimbusds.jose.util.ResourceRetriever; import com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod; import com.nimbusds.openid.connect.sdk.validators.IDTokenValidator; import java.util.ArrayList; import java.util.List;
import com.nimbusds.jose.*; import com.nimbusds.jose.util.*; import com.nimbusds.oauth2.sdk.auth.*; import com.nimbusds.openid.connect.sdk.validators.*; import java.util.*;
[ "com.nimbusds.jose", "com.nimbusds.oauth2", "com.nimbusds.openid", "java.util" ]
com.nimbusds.jose; com.nimbusds.oauth2; com.nimbusds.openid; java.util;
2,481,021
public String getData() { if (data instanceof JsonPrimitive) { return ((JsonPrimitive) data).getAsString(); } else if (data != null) { return data.toString(); } else { return null; } }
String function() { if (data instanceof JsonPrimitive) { return ((JsonPrimitive) data).getAsString(); } else if (data != null) { return data.toString(); } else { return null; } }
/** * Error data accessor (getter). * * @return Error data */
Error data accessor (getter)
getData
{ "repo_name": "EugenioFidel/kurento-java", "path": "kurento-jsonrpc/kurento-jsonrpc-client/src/main/java/org/kurento/jsonrpc/message/ResponseError.java", "license": "lgpl-2.1", "size": 5168 }
[ "com.google.gson.JsonPrimitive" ]
import com.google.gson.JsonPrimitive;
import com.google.gson.*;
[ "com.google.gson" ]
com.google.gson;
1,749,993
@Override public Adapter createSourceAspectAdapter() { if (sourceAspectItemProvider == null) { sourceAspectItemProvider = new SourceAspectItemProvider(this); } return sourceAspectItemProvider; } protected SpectrumItemProvider spectrumItemProvider;
Adapter function() { if (sourceAspectItemProvider == null) { sourceAspectItemProvider = new SourceAspectItemProvider(this); } return sourceAspectItemProvider; } protected SpectrumItemProvider spectrumItemProvider;
/** * This creates an adapter for a {@link net.mlanoe.language.vhdl.ams.SourceAspect}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */
This creates an adapter for a <code>net.mlanoe.language.vhdl.ams.SourceAspect</code>.
createSourceAspectAdapter
{ "repo_name": "mlanoe/x-vhdl", "path": "plugins/net.mlanoe.language.vhdl.edit/src-gen/net/mlanoe/language/vhdl/ams/provider/AmsItemProviderAdapterFactory.java", "license": "gpl-3.0", "size": 8007 }
[ "org.eclipse.emf.common.notify.Adapter" ]
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
388,355
public final int getMaxCumulationBufferCapacity() { return copyThreshold; } /** * Set the maximal capacity of the internal cumulation ChannelBuffer to use * before the {@link FrameDecoder} tries to minimize the memory usage by * "byte copy". * * * What you use here really depends on your application and need. Using * {@link Integer#MAX_VALUE} will disable all byte copies but give you the * cost of a higher memory usage if big {@link ChannelBuffer}'s will be * received. * * By default a threshold of {@code 0} is used, which means it will * always copy to try to reduce memory usage * * * @param copyThreshold * the threshold (in bytes) or {@link Integer#MAX_VALUE} to * disable it. The value must be at least 0 * @throws IllegalStateException * get thrown if someone tries to change this setting after the * Decoder was added to the {@link ChannelPipeline}
final int function() { return copyThreshold; } /** * Set the maximal capacity of the internal cumulation ChannelBuffer to use * before the {@link FrameDecoder} tries to minimize the memory usage by * STR. * * * What you use here really depends on your application and need. Using * {@link Integer#MAX_VALUE} will disable all byte copies but give you the * cost of a higher memory usage if big {@link ChannelBuffer}'s will be * received. * * By default a threshold of {@code 0} is used, which means it will * always copy to try to reduce memory usage * * * @param copyThreshold * the threshold (in bytes) or {@link Integer#MAX_VALUE} to * disable it. The value must be at least 0 * @throws IllegalStateException * get thrown if someone tries to change this setting after the * Decoder was added to the {@link ChannelPipeline}
/** * See {@link #setMaxCumulationBufferCapacity(int)} for explaintation of this setting * */
See <code>#setMaxCumulationBufferCapacity(int)</code> for explaintation of this setting
getMaxCumulationBufferCapacity
{ "repo_name": "CliffYuan/netty", "path": "src/main/java/org/jboss/netty/handler/codec/frame/FrameDecoder.java", "license": "apache-2.0", "size": 22670 }
[ "org.jboss.netty.buffer.ChannelBuffer", "org.jboss.netty.channel.ChannelPipeline" ]
import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.buffer.*; import org.jboss.netty.channel.*;
[ "org.jboss.netty" ]
org.jboss.netty;
1,033,411
public void testListings() throws Exception { JSONObject result; JSONObject item; // Check all of the listings, none should have anything yet result = getPosts(null, Status.STATUS_OK); assertEquals(0, result.getInt("total")); assertEquals(0, result.getInt("itemCount")); assertEquals(0, result.getJSONArray("items").length()); result = getPosts("hot", Status.STATUS_OK); assertEquals(0, result.getInt("total")); assertEquals(0, result.getInt("itemCount")); assertEquals(0, result.getJSONArray("items").length()); result = getPosts("mine", Status.STATUS_OK); assertEquals(0, result.getInt("total")); assertEquals(0, result.getInt("itemCount")); assertEquals(0, result.getJSONArray("items").length()); result = getPosts("new?numdays=100", Status.STATUS_OK); assertEquals(0, result.getInt("total")); assertEquals(0, result.getInt("itemCount")); assertEquals(0, result.getJSONArray("items").length()); // Check with a noderef too result = getPosts(FORUM_NODE, null, Status.STATUS_OK); assertEquals(0, result.getInt("total")); assertEquals(0, result.getInt("itemCount")); assertEquals(0, result.getJSONArray("items").length()); result = getPosts(FORUM_NODE, "hot", Status.STATUS_OK); assertEquals(0, result.getInt("total")); assertEquals(0, result.getInt("itemCount")); assertEquals(0, result.getJSONArray("items").length()); result = getPosts(FORUM_NODE, "mine", Status.STATUS_OK); assertEquals(0, result.getInt("total")); assertEquals(0, result.getInt("itemCount")); assertEquals(0, result.getJSONArray("items").length()); result = getPosts(FORUM_NODE, "new?numdays=100", Status.STATUS_OK); assertEquals(0, result.getInt("total")); assertEquals(0, result.getInt("itemCount")); assertEquals(0, result.getJSONArray("items").length()); // Now add a few topics with replies // Some of these will be created as different users item = createSitePost("SiteTitle1", "Content", Status.STATUS_OK); NodeRef siteTopic1 = new NodeRef(item.getString("nodeRef")); this.authenticationComponent.setCurrentUser(USER_TWO); item = createSitePost("SiteTitle2", "Content", Status.STATUS_OK); NodeRef siteTopic2 = new NodeRef(item.getString("nodeRef")); item = createNodePost(FORUM_NODE, "NodeTitle1", "Content", Status.STATUS_OK); NodeRef nodeTopic1 = new NodeRef(item.getString("nodeRef")); this.authenticationComponent.setCurrentUser(USER_ONE); item = createNodePost(FORUM_NODE, "NodeTitle2", "Content", Status.STATUS_OK); NodeRef nodeTopic2 = new NodeRef(item.getString("nodeRef")); item = createNodePost(FORUM_NODE, "NodeTitle3", "Content", Status.STATUS_OK); NodeRef nodeTopic3 = new NodeRef(item.getString("nodeRef")); item = createReply(siteTopic1, "Reply1a", "Content", Status.STATUS_OK); NodeRef siteReply1A = new NodeRef(item.getString("nodeRef")); item = createReply(siteTopic1, "Reply1b", "Content", Status.STATUS_OK); NodeRef siteReply1B = new NodeRef(item.getString("nodeRef")); this.authenticationComponent.setCurrentUser(USER_TWO); item = createReply(siteTopic2, "Reply2a", "Content", Status.STATUS_OK); NodeRef siteReply2A = new NodeRef(item.getString("nodeRef")); item = createReply(siteTopic2, "Reply2b", "Content", Status.STATUS_OK); NodeRef siteReply2B = new NodeRef(item.getString("nodeRef")); item = createReply(siteTopic2, "Reply2c", "Content", Status.STATUS_OK); NodeRef siteReply2C = new NodeRef(item.getString("nodeRef")); item = createReply(siteReply2A, "Reply2aa", "Content", Status.STATUS_OK); NodeRef siteReply2AA = new NodeRef(item.getString("nodeRef")); item = createReply(siteReply2A, "Reply2ab", "Content", Status.STATUS_OK); NodeRef siteReply2AB = new NodeRef(item.getString("nodeRef")); this.authenticationComponent.setCurrentUser(USER_ONE); item = createReply(siteReply2AA, "Reply2aaa", "Content", Status.STATUS_OK); NodeRef siteReply2AAA = new NodeRef(item.getString("nodeRef")); item = createReply(nodeTopic1, "ReplyN1a", "Content", Status.STATUS_OK); NodeRef nodeReply1A = new NodeRef(item.getString("nodeRef")); item = createReply(nodeReply1A, "ReplyN1aa", "Content", Status.STATUS_OK); NodeRef nodeReply1AA = new NodeRef(item.getString("nodeRef")); item = createReply(nodeReply1AA, "ReplyN1aaa", "Content", Status.STATUS_OK); NodeRef nodeReply1AAA = new NodeRef(item.getString("nodeRef")); // Check for totals // We should get all the topics result = getPosts(null, Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(2, result.getInt("itemCount")); assertEquals(2, result.getJSONArray("items").length()); assertEquals("SiteTitle1", result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals("SiteTitle2", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(2, result.getJSONArray("items").getJSONObject(1).getInt("replyCount")); assertEquals(3, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); result = getPosts(FORUM_NODE, null, Status.STATUS_OK); assertEquals(3, result.getInt("total")); assertEquals(3, result.getInt("itemCount")); assertEquals(3, result.getJSONArray("items").length()); assertEquals("NodeTitle1", result.getJSONArray("items").getJSONObject(2).getString("title")); assertEquals("NodeTitle2", result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals("NodeTitle3", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(1, result.getJSONArray("items").getJSONObject(2).getInt("replyCount")); assertEquals(0, result.getJSONArray("items").getJSONObject(1).getInt("replyCount")); assertEquals(0, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); // Check for "mine" // User 1 has Site 1, and Nodes 2 + 3 result = getPosts("mine", Status.STATUS_OK); assertEquals(1, result.getInt("total")); assertEquals(1, result.getInt("itemCount")); assertEquals(1, result.getJSONArray("items").length()); assertEquals("SiteTitle1", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(2, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); result = getPosts(FORUM_NODE, "mine", Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(2, result.getInt("itemCount")); assertEquals(2, result.getJSONArray("items").length()); assertEquals("NodeTitle2", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals("NodeTitle3", result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals(0, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); assertEquals(0, result.getJSONArray("items").getJSONObject(1).getInt("replyCount")); // Check for recent (new) // We should get all the topics, with the newest one first (rather than last as with others) result = getPosts("new?numdays=2", Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(2, result.getInt("itemCount")); assertEquals(2, result.getJSONArray("items").length()); assertEquals("SiteTitle2", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals("SiteTitle1", result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals(3, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); assertEquals(2, result.getJSONArray("items").getJSONObject(1).getInt("replyCount")); result = getPosts(FORUM_NODE, "new?numdays=2", Status.STATUS_OK); assertEquals(3, result.getInt("total")); assertEquals(3, result.getInt("itemCount")); assertEquals(3, result.getJSONArray("items").length()); assertEquals("NodeTitle3", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals("NodeTitle2", result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals("NodeTitle1", result.getJSONArray("items").getJSONObject(2).getString("title")); assertEquals(0, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); assertEquals(0, result.getJSONArray("items").getJSONObject(1).getInt("replyCount")); assertEquals(1, result.getJSONArray("items").getJSONObject(2).getInt("replyCount")); // Check for hot // Will only show topics with replies. Sorting is by replies, not date result = getPosts("hot", Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(2, result.getInt("itemCount")); assertEquals(2, result.getJSONArray("items").length()); assertEquals("SiteTitle2", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals("SiteTitle1", result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals(3, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); assertEquals(2, result.getJSONArray("items").getJSONObject(1).getInt("replyCount")); result = getPosts(FORUM_NODE, "hot", Status.STATUS_OK); assertEquals(1, result.getInt("total")); assertEquals(1, result.getInt("itemCount")); assertEquals(1, result.getJSONArray("items").length()); assertEquals("NodeTitle1", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(1, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); // Shift some of the posts into the past // (Update the created and published dates) pushCreatedDateBack(siteTopic1, 10); pushCreatedDateBack(siteReply1B, -2); // Make it newer pushCreatedDateBack(nodeTopic2, 10); pushCreatedDateBack(nodeTopic3, 4); pushCreatedDateBack(nodeReply1AAA, -1); // Make it newer // Re-check totals, only ordering changes result = getPosts(null, Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(2, result.getInt("itemCount")); assertEquals(2, result.getJSONArray("items").length()); assertEquals("SiteTitle1", result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals("SiteTitle2", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(2, result.getJSONArray("items").getJSONObject(1).getInt("replyCount")); assertEquals(3, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); result = getPosts(FORUM_NODE, null, Status.STATUS_OK); assertEquals(3, result.getInt("total")); assertEquals(3, result.getInt("itemCount")); assertEquals(3, result.getJSONArray("items").length()); assertEquals("NodeTitle2", result.getJSONArray("items").getJSONObject(2).getString("title")); assertEquals("NodeTitle3", result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals("NodeTitle1", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(0, result.getJSONArray("items").getJSONObject(2).getInt("replyCount")); assertEquals(0, result.getJSONArray("items").getJSONObject(1).getInt("replyCount")); assertEquals(1, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); // Re-check recent, old ones vanish result = getPosts("new?numdays=2", Status.STATUS_OK); assertEquals(1, result.getInt("total")); assertEquals(1, result.getInt("itemCount")); assertEquals(1, result.getJSONArray("items").length()); assertEquals("SiteTitle2", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(3, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); result = getPosts(FORUM_NODE, "new?numdays=6", Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(2, result.getInt("itemCount")); assertEquals(2, result.getJSONArray("items").length()); assertEquals("NodeTitle1", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals("NodeTitle3", result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals(1, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); assertEquals(0, result.getJSONArray("items").getJSONObject(1).getInt("replyCount")); result = getPosts(FORUM_NODE, "new?numdays=2", Status.STATUS_OK); assertEquals(1, result.getInt("total")); assertEquals(1, result.getInt("itemCount")); assertEquals(1, result.getJSONArray("items").length()); assertEquals("NodeTitle1", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(1, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); // Re-check "mine", no change except ordering result = getPosts("mine", Status.STATUS_OK); assertEquals(1, result.getInt("total")); assertEquals(1, result.getInt("itemCount")); assertEquals(1, result.getJSONArray("items").length()); assertEquals("SiteTitle1", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(2, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); result = getPosts(FORUM_NODE, "mine", Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(2, result.getInt("itemCount")); assertEquals(2, result.getJSONArray("items").length()); assertEquals("NodeTitle2", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals("NodeTitle3", result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals(0, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); assertEquals(0, result.getJSONArray("items").getJSONObject(1).getInt("replyCount")); // Re-check hot, some old ones vanish result = getPosts("hot", Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(2, result.getInt("itemCount")); assertEquals(2, result.getJSONArray("items").length()); assertEquals("SiteTitle2", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals("SiteTitle1", result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals(3, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); assertEquals(2, result.getJSONArray("items").getJSONObject(1).getInt("replyCount")); result = getPosts(FORUM_NODE, "hot", Status.STATUS_OK); assertEquals(1, result.getInt("total")); assertEquals(1, result.getInt("itemCount")); assertEquals(1, result.getJSONArray("items").length()); assertEquals("NodeTitle1", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(1, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); // Check paging result = getPosts("limit", Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(1, result.getInt("itemCount")); assertEquals(1, result.getJSONArray("items").length()); assertEquals("SiteTitle2", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(3, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); result = getPosts(FORUM_NODE, "limit", Status.STATUS_OK); assertEquals(3, result.getInt("total")); assertEquals(1, result.getInt("itemCount")); assertEquals(1, result.getJSONArray("items").length()); assertEquals("NodeTitle1", result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(1, result.getJSONArray("items").getJSONObject(0).getInt("replyCount")); }
void function() throws Exception { JSONObject result; JSONObject item; result = getPosts(null, Status.STATUS_OK); assertEquals(0, result.getInt("total")); assertEquals(0, result.getInt(STR)); assertEquals(0, result.getJSONArray("items").length()); result = getPosts("hot", Status.STATUS_OK); assertEquals(0, result.getInt("total")); assertEquals(0, result.getInt(STR)); assertEquals(0, result.getJSONArray("items").length()); result = getPosts("mine", Status.STATUS_OK); assertEquals(0, result.getInt("total")); assertEquals(0, result.getInt(STR)); assertEquals(0, result.getJSONArray("items").length()); result = getPosts(STR, Status.STATUS_OK); assertEquals(0, result.getInt("total")); assertEquals(0, result.getInt(STR)); assertEquals(0, result.getJSONArray("items").length()); result = getPosts(FORUM_NODE, null, Status.STATUS_OK); assertEquals(0, result.getInt("total")); assertEquals(0, result.getInt(STR)); assertEquals(0, result.getJSONArray("items").length()); result = getPosts(FORUM_NODE, "hot", Status.STATUS_OK); assertEquals(0, result.getInt("total")); assertEquals(0, result.getInt(STR)); assertEquals(0, result.getJSONArray("items").length()); result = getPosts(FORUM_NODE, "mine", Status.STATUS_OK); assertEquals(0, result.getInt("total")); assertEquals(0, result.getInt(STR)); assertEquals(0, result.getJSONArray("items").length()); result = getPosts(FORUM_NODE, STR, Status.STATUS_OK); assertEquals(0, result.getInt("total")); assertEquals(0, result.getInt(STR)); assertEquals(0, result.getJSONArray("items").length()); item = createSitePost(STR, STR, Status.STATUS_OK); NodeRef siteTopic1 = new NodeRef(item.getString(STR)); this.authenticationComponent.setCurrentUser(USER_TWO); item = createSitePost(STR, STR, Status.STATUS_OK); NodeRef siteTopic2 = new NodeRef(item.getString(STR)); item = createNodePost(FORUM_NODE, STR, STR, Status.STATUS_OK); NodeRef nodeTopic1 = new NodeRef(item.getString(STR)); this.authenticationComponent.setCurrentUser(USER_ONE); item = createNodePost(FORUM_NODE, STR, STR, Status.STATUS_OK); NodeRef nodeTopic2 = new NodeRef(item.getString(STR)); item = createNodePost(FORUM_NODE, STR, STR, Status.STATUS_OK); NodeRef nodeTopic3 = new NodeRef(item.getString(STR)); item = createReply(siteTopic1, STR, STR, Status.STATUS_OK); NodeRef siteReply1A = new NodeRef(item.getString(STR)); item = createReply(siteTopic1, STR, STR, Status.STATUS_OK); NodeRef siteReply1B = new NodeRef(item.getString(STR)); this.authenticationComponent.setCurrentUser(USER_TWO); item = createReply(siteTopic2, STR, STR, Status.STATUS_OK); NodeRef siteReply2A = new NodeRef(item.getString(STR)); item = createReply(siteTopic2, STR, STR, Status.STATUS_OK); NodeRef siteReply2B = new NodeRef(item.getString(STR)); item = createReply(siteTopic2, STR, STR, Status.STATUS_OK); NodeRef siteReply2C = new NodeRef(item.getString(STR)); item = createReply(siteReply2A, STR, STR, Status.STATUS_OK); NodeRef siteReply2AA = new NodeRef(item.getString(STR)); item = createReply(siteReply2A, STR, STR, Status.STATUS_OK); NodeRef siteReply2AB = new NodeRef(item.getString(STR)); this.authenticationComponent.setCurrentUser(USER_ONE); item = createReply(siteReply2AA, STR, STR, Status.STATUS_OK); NodeRef siteReply2AAA = new NodeRef(item.getString(STR)); item = createReply(nodeTopic1, STR, STR, Status.STATUS_OK); NodeRef nodeReply1A = new NodeRef(item.getString(STR)); item = createReply(nodeReply1A, STR, STR, Status.STATUS_OK); NodeRef nodeReply1AA = new NodeRef(item.getString(STR)); item = createReply(nodeReply1AA, STR, STR, Status.STATUS_OK); NodeRef nodeReply1AAA = new NodeRef(item.getString(STR)); result = getPosts(null, Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(2, result.getInt(STR)); assertEquals(2, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(2, result.getJSONArray("items").getJSONObject(1).getInt(STR)); assertEquals(3, result.getJSONArray("items").getJSONObject(0).getInt(STR)); result = getPosts(FORUM_NODE, null, Status.STATUS_OK); assertEquals(3, result.getInt("total")); assertEquals(3, result.getInt(STR)); assertEquals(3, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(2).getString("title")); assertEquals(STR, result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(1, result.getJSONArray("items").getJSONObject(2).getInt(STR)); assertEquals(0, result.getJSONArray("items").getJSONObject(1).getInt(STR)); assertEquals(0, result.getJSONArray("items").getJSONObject(0).getInt(STR)); result = getPosts("mine", Status.STATUS_OK); assertEquals(1, result.getInt("total")); assertEquals(1, result.getInt(STR)); assertEquals(1, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(2, result.getJSONArray("items").getJSONObject(0).getInt(STR)); result = getPosts(FORUM_NODE, "mine", Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(2, result.getInt(STR)); assertEquals(2, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(STR, result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals(0, result.getJSONArray("items").getJSONObject(0).getInt(STR)); assertEquals(0, result.getJSONArray("items").getJSONObject(1).getInt(STR)); result = getPosts(STR, Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(2, result.getInt(STR)); assertEquals(2, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(STR, result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals(3, result.getJSONArray("items").getJSONObject(0).getInt(STR)); assertEquals(2, result.getJSONArray("items").getJSONObject(1).getInt(STR)); result = getPosts(FORUM_NODE, STR, Status.STATUS_OK); assertEquals(3, result.getInt("total")); assertEquals(3, result.getInt(STR)); assertEquals(3, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(STR, result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals(STR, result.getJSONArray("items").getJSONObject(2).getString("title")); assertEquals(0, result.getJSONArray("items").getJSONObject(0).getInt(STR)); assertEquals(0, result.getJSONArray("items").getJSONObject(1).getInt(STR)); assertEquals(1, result.getJSONArray("items").getJSONObject(2).getInt(STR)); result = getPosts("hot", Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(2, result.getInt(STR)); assertEquals(2, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(STR, result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals(3, result.getJSONArray("items").getJSONObject(0).getInt(STR)); assertEquals(2, result.getJSONArray("items").getJSONObject(1).getInt(STR)); result = getPosts(FORUM_NODE, "hot", Status.STATUS_OK); assertEquals(1, result.getInt("total")); assertEquals(1, result.getInt(STR)); assertEquals(1, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(1, result.getJSONArray("items").getJSONObject(0).getInt(STR)); pushCreatedDateBack(siteTopic1, 10); pushCreatedDateBack(siteReply1B, -2); pushCreatedDateBack(nodeTopic2, 10); pushCreatedDateBack(nodeTopic3, 4); pushCreatedDateBack(nodeReply1AAA, -1); result = getPosts(null, Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(2, result.getInt(STR)); assertEquals(2, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(2, result.getJSONArray("items").getJSONObject(1).getInt(STR)); assertEquals(3, result.getJSONArray("items").getJSONObject(0).getInt(STR)); result = getPosts(FORUM_NODE, null, Status.STATUS_OK); assertEquals(3, result.getInt("total")); assertEquals(3, result.getInt(STR)); assertEquals(3, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(2).getString("title")); assertEquals(STR, result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(0, result.getJSONArray("items").getJSONObject(2).getInt(STR)); assertEquals(0, result.getJSONArray("items").getJSONObject(1).getInt(STR)); assertEquals(1, result.getJSONArray("items").getJSONObject(0).getInt(STR)); result = getPosts(STR, Status.STATUS_OK); assertEquals(1, result.getInt("total")); assertEquals(1, result.getInt(STR)); assertEquals(1, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(3, result.getJSONArray("items").getJSONObject(0).getInt(STR)); result = getPosts(FORUM_NODE, STR, Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(2, result.getInt(STR)); assertEquals(2, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(STR, result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals(1, result.getJSONArray("items").getJSONObject(0).getInt(STR)); assertEquals(0, result.getJSONArray("items").getJSONObject(1).getInt(STR)); result = getPosts(FORUM_NODE, STR, Status.STATUS_OK); assertEquals(1, result.getInt("total")); assertEquals(1, result.getInt(STR)); assertEquals(1, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(1, result.getJSONArray("items").getJSONObject(0).getInt(STR)); result = getPosts("mine", Status.STATUS_OK); assertEquals(1, result.getInt("total")); assertEquals(1, result.getInt(STR)); assertEquals(1, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(2, result.getJSONArray("items").getJSONObject(0).getInt(STR)); result = getPosts(FORUM_NODE, "mine", Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(2, result.getInt(STR)); assertEquals(2, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(STR, result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals(0, result.getJSONArray("items").getJSONObject(0).getInt(STR)); assertEquals(0, result.getJSONArray("items").getJSONObject(1).getInt(STR)); result = getPosts("hot", Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(2, result.getInt(STR)); assertEquals(2, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(STR, result.getJSONArray("items").getJSONObject(1).getString("title")); assertEquals(3, result.getJSONArray("items").getJSONObject(0).getInt(STR)); assertEquals(2, result.getJSONArray("items").getJSONObject(1).getInt(STR)); result = getPosts(FORUM_NODE, "hot", Status.STATUS_OK); assertEquals(1, result.getInt("total")); assertEquals(1, result.getInt(STR)); assertEquals(1, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(1, result.getJSONArray("items").getJSONObject(0).getInt(STR)); result = getPosts("limit", Status.STATUS_OK); assertEquals(2, result.getInt("total")); assertEquals(1, result.getInt(STR)); assertEquals(1, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(3, result.getJSONArray("items").getJSONObject(0).getInt(STR)); result = getPosts(FORUM_NODE, "limit", Status.STATUS_OK); assertEquals(3, result.getInt("total")); assertEquals(1, result.getInt(STR)); assertEquals(1, result.getJSONArray("items").length()); assertEquals(STR, result.getJSONArray("items").getJSONObject(0).getString("title")); assertEquals(1, result.getJSONArray("items").getJSONObject(0).getInt(STR)); }
/** * Test for the various listings: * All, New, Hot (Most Active), Mine */
Test for the various listings: All, New, Hot (Most Active), Mine
testListings
{ "repo_name": "nguyentienlong/community-edition", "path": "projects/remote-api/source/test-java/org/alfresco/repo/web/scripts/discussion/DiscussionRestApiTest.java", "license": "lgpl-3.0", "size": 59331 }
[ "org.alfresco.service.cmr.repository.NodeRef", "org.json.JSONObject", "org.springframework.extensions.webscripts.Status" ]
import org.alfresco.service.cmr.repository.NodeRef; import org.json.JSONObject; import org.springframework.extensions.webscripts.Status;
import org.alfresco.service.cmr.repository.*; import org.json.*; import org.springframework.extensions.webscripts.*;
[ "org.alfresco.service", "org.json", "org.springframework.extensions" ]
org.alfresco.service; org.json; org.springframework.extensions;
2,667,638
public static String getLogin(final Context context) { final Account account = getAccount(context); return account != null ? account.name : null; }
static String function(final Context context) { final Account account = getAccount(context); return account != null ? account.name : null; }
/** * Get login name of configured account * * @param context * @return login name or null if none configure */
Get login name of configured account
getLogin
{ "repo_name": "DeLaSalleUniversity-Manila/forkhub-JeraldLimqueco", "path": "app/src/main/java/com/github/mobile/accounts/AccountUtils.java", "license": "apache-2.0", "size": 12236 }
[ "android.accounts.Account", "android.content.Context" ]
import android.accounts.Account; import android.content.Context;
import android.accounts.*; import android.content.*;
[ "android.accounts", "android.content" ]
android.accounts; android.content;
1,782,465
public void removeFrdParameterRule24(FrdParameterRule24 frdParameterRule24);
void function(FrdParameterRule24 frdParameterRule24);
/** * removeFrdParameterRule24 - removes a FrdParameterRule24 * * @param frdParameterRule24 */
removeFrdParameterRule24 - removes a FrdParameterRule24
removeFrdParameterRule24
{ "repo_name": "yauritux/venice-legacy", "path": "Venice/Venice-Interface-Model/src/main/java/com/gdn/venice/facade/FrdParameterRule24SessionEJBRemote.java", "license": "apache-2.0", "size": 2780 }
[ "com.gdn.venice.persistence.FrdParameterRule24" ]
import com.gdn.venice.persistence.FrdParameterRule24;
import com.gdn.venice.persistence.*;
[ "com.gdn.venice" ]
com.gdn.venice;
226,188
public ObjectContainer getObjectItem(int i) { Element objElem = XMLUtils.selectDsNode( this.constructionElement.getFirstChild(), Constants._TAG_OBJECT, i ); try { return new ObjectContainer(objElem, this.baseURI); } catch (XMLSecurityException ex) { return null; } }
ObjectContainer function(int i) { Element objElem = XMLUtils.selectDsNode( this.constructionElement.getFirstChild(), Constants._TAG_OBJECT, i ); try { return new ObjectContainer(objElem, this.baseURI); } catch (XMLSecurityException ex) { return null; } }
/** * Returns the <code>i<code>th <code>ds:Object</code> child of the signature * or null if no such <code>ds:Object</code> element exists. * * @param i * @return the <code>i<code>th <code>ds:Object</code> child of the signature * or null if no such <code>ds:Object</code> element exists. */
Returns the <code>i<code>th <code>ds:Object</code> child of the signature or null if no such <code>ds:Object</code> element exists
getObjectItem
{ "repo_name": "isaacl/openjdk-jdk", "path": "src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java", "license": "gpl-2.0", "size": 33947 }
[ "com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException", "com.sun.org.apache.xml.internal.security.utils.Constants", "com.sun.org.apache.xml.internal.security.utils.XMLUtils", "org.w3c.dom.Element" ]
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element;
import com.sun.org.apache.xml.internal.security.exceptions.*; import com.sun.org.apache.xml.internal.security.utils.*; import org.w3c.dom.*;
[ "com.sun.org", "org.w3c.dom" ]
com.sun.org; org.w3c.dom;
214,914
@Override public void registerManager(IPluginManager manager, String apiVersion) throws RemoteException { String packageName = null; String[] packages = getPackageManager().getPackagesForUid(Binder.getCallingUid()); if (packages != null && packages.length > 0) { packageName = packages[0]; } Log.e(TAG, "registering manager " + packageName + " with API version " + apiVersion); mManager = manager; mManagerVersion = apiVersion; //plugins.put(packageName, listener); //mListenerList.register(listener); }
void function(IPluginManager manager, String apiVersion) throws RemoteException { String packageName = null; String[] packages = getPackageManager().getPackagesForUid(Binder.getCallingUid()); if (packages != null && packages.length > 0) { packageName = packages[0]; } Log.e(TAG, STR + packageName + STR + apiVersion); mManager = manager; mManagerVersion = apiVersion; }
/** * This is called when the plugin manager asks to register itself. * @param manager the PluginManager * @throws RemoteException when AJKIDL goes wrong */
This is called when the plugin manager asks to register itself
registerManager
{ "repo_name": "MessageOnTap/MessageOnTap_API", "path": "api/src/main/java/edu/cmu/chimps/messageontap_api/MessageOnTapPlugin.java", "license": "apache-2.0", "size": 16185 }
[ "android.os.Binder", "android.os.RemoteException", "android.util.Log" ]
import android.os.Binder; import android.os.RemoteException; import android.util.Log;
import android.os.*; import android.util.*;
[ "android.os", "android.util" ]
android.os; android.util;
943,005
@Override public Object call(Class<?> controllerClass) { if (null == controllerClass) { throw new IllegalArgumentException("The controller class cannot be null."); } if (controllerClass.isAssignableFrom(AbstractController.class)) { throw new IllegalArgumentException( String.format( Locale.US, "%s have to implement %s", controllerClass.getName(), AbstractController.class.getName())); } // Initialize both list representing the constructor parameters List<Class<?>> classes = new ArrayList<Class<?>>(); List<Object> parameters = new ArrayList<Object>(); // Add default constructor parameters types classes.add(UIApplication.class); classes.add(RemoteDriveBootstrap.class); classes.add(ResourceBundle.class); // Add default constructor parameters values parameters.add(uiApplication); parameters.add(remoteDriveApplication); parameters.add(resourceBundle); // Apply extra parameters for(Object extraParameter : extraParameters) { classes.add(extraParameter.getClass()); parameters.add(extraParameter); } try { // Try to find a matching constructor and call it Constructor constructor = controllerClass.getConstructor(classes.toArray(new Class[classes.size()])); Object newInstance = constructor.newInstance(parameters.toArray(new Object[parameters.size()])); log.info(String.format(Locale.US, "GUI Controller created: %s", controllerClass)); return newInstance; } catch (Exception exception) { // Build parameter signature StringBuilder parametersSignatureBuilder = new StringBuilder(); for(Class clazz : classes) { // Add separator if(0 < parametersSignatureBuilder.length()) parametersSignatureBuilder.append(", "); // Add the class name parametersSignatureBuilder.append(clazz.getName()); } // Build the error message String message = String.format( Locale.US, "Constructor %s(%s) not found", controllerClass.getName(), parametersSignatureBuilder.toString()); // Create the exception BootstrapException bootstrapException = new BootstrapException(message, exception); // Log and throw log.error(bootstrapException.getMessage(), bootstrapException); throw bootstrapException; } }
Object function(Class<?> controllerClass) { if (null == controllerClass) { throw new IllegalArgumentException(STR); } if (controllerClass.isAssignableFrom(AbstractController.class)) { throw new IllegalArgumentException( String.format( Locale.US, STR, controllerClass.getName(), AbstractController.class.getName())); } List<Class<?>> classes = new ArrayList<Class<?>>(); List<Object> parameters = new ArrayList<Object>(); classes.add(UIApplication.class); classes.add(RemoteDriveBootstrap.class); classes.add(ResourceBundle.class); parameters.add(uiApplication); parameters.add(remoteDriveApplication); parameters.add(resourceBundle); for(Object extraParameter : extraParameters) { classes.add(extraParameter.getClass()); parameters.add(extraParameter); } try { Constructor constructor = controllerClass.getConstructor(classes.toArray(new Class[classes.size()])); Object newInstance = constructor.newInstance(parameters.toArray(new Object[parameters.size()])); log.info(String.format(Locale.US, STR, controllerClass)); return newInstance; } catch (Exception exception) { StringBuilder parametersSignatureBuilder = new StringBuilder(); for(Class clazz : classes) { if(0 < parametersSignatureBuilder.length()) parametersSignatureBuilder.append(STR); parametersSignatureBuilder.append(clazz.getName()); } String message = String.format( Locale.US, STR, controllerClass.getName(), parametersSignatureBuilder.toString()); BootstrapException bootstrapException = new BootstrapException(message, exception); log.error(bootstrapException.getMessage(), bootstrapException); throw bootstrapException; } }
/** * Implements the callback. * * @param controllerClass The controller class. * @return The created controller. */
Implements the callback
call
{ "repo_name": "defrancea/remote-drive", "path": "gui/src/main/java/remotedrive/gui/ControllerFactory.java", "license": "lgpl-2.1", "size": 6446 }
[ "java.lang.reflect.Constructor", "java.util.ArrayList", "java.util.List", "java.util.Locale", "java.util.ResourceBundle" ]
import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.ResourceBundle;
import java.lang.reflect.*; import java.util.*;
[ "java.lang", "java.util" ]
java.lang; java.util;
917,381
public static String shaHex(InputStream data) throws IOException { return Hex.encodeHexString(sha(data)); }
static String function(InputStream data) throws IOException { return Hex.encodeHexString(sha(data)); }
/** * Calculates the SHA-1 digest and returns the value as a hex string. * * @param data * Data to digest * @return SHA-1 digest as a hex string * @throws IOException * On error reading from the stream * @since 1.4 */
Calculates the SHA-1 digest and returns the value as a hex string
shaHex
{ "repo_name": "renepreuss/P2P-Client", "path": "src/org/apache/commons/codec/digest/DigestUtils.java", "license": "mit", "size": 17848 }
[ "java.io.IOException", "java.io.InputStream", "org.apache.commons.codec.binary.Hex" ]
import java.io.IOException; import java.io.InputStream; import org.apache.commons.codec.binary.Hex;
import java.io.*; import org.apache.commons.codec.binary.*;
[ "java.io", "org.apache.commons" ]
java.io; org.apache.commons;
1,823,625
private String getStatus(String filename, String command) throws Exception { long oldOpsStat = metricsGetter.getOrDefault(command, defaultEntryMetricGetter).call(); String user = HadoopUsersConfTestHelper.getHadoopUsers()[0]; // Remove leading / from filename if (filename.charAt(0) == '/') { filename = filename.substring(1); } String pathOps = MessageFormat.format( "/webhdfs/v1/{0}?user.name={1}&op={2}", filename, user, command); URL url = new URL(TestJettyHelper.getJettyURL(), pathOps); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); long opsStat = metricsGetter.getOrDefault(command, defaultExitMetricGetter).call(); Assert.assertEquals(oldOpsStat + 1L, opsStat); return reader.readLine(); }
String function(String filename, String command) throws Exception { long oldOpsStat = metricsGetter.getOrDefault(command, defaultEntryMetricGetter).call(); String user = HadoopUsersConfTestHelper.getHadoopUsers()[0]; if (filename.charAt(0) == '/') { filename = filename.substring(1); } String pathOps = MessageFormat.format( STR, filename, user, command); URL url = new URL(TestJettyHelper.getJettyURL(), pathOps); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); long opsStat = metricsGetter.getOrDefault(command, defaultExitMetricGetter).call(); Assert.assertEquals(oldOpsStat + 1L, opsStat); return reader.readLine(); }
/** * Talks to the http interface to get the json output of a *STATUS command * on the given file. * * @param filename The file to query. * @param command Either GETFILESTATUS, LISTSTATUS, or ACLSTATUS * @return A string containing the JSON output describing the file. * @throws Exception */
Talks to the http interface to get the json output of a *STATUS command on the given file
getStatus
{ "repo_name": "apurtell/hadoop", "path": "hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/fs/http/server/TestHttpFSServer.java", "license": "apache-2.0", "size": 77473 }
[ "java.io.BufferedReader", "java.io.InputStreamReader", "java.net.HttpURLConnection", "java.text.MessageFormat", "org.apache.hadoop.test.HadoopUsersConfTestHelper", "org.apache.hadoop.test.TestJettyHelper", "org.junit.Assert" ]
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.text.MessageFormat; import org.apache.hadoop.test.HadoopUsersConfTestHelper; import org.apache.hadoop.test.TestJettyHelper; import org.junit.Assert;
import java.io.*; import java.net.*; import java.text.*; import org.apache.hadoop.test.*; import org.junit.*;
[ "java.io", "java.net", "java.text", "org.apache.hadoop", "org.junit" ]
java.io; java.net; java.text; org.apache.hadoop; org.junit;
2,377,254
@Override public String getCatalogName(int column) throws SQLException { throw new SQLException("tinySQL does not support catalogues."); }
String function(int column) throws SQLException { throw new SQLException(STR); }
/** * * Return the column's table catalog name. Not supported by tinySQL * */
Return the column's table catalog name. Not supported by tinySQL
getCatalogName
{ "repo_name": "ryangoodrich/GT_CS4420_Spring_2013_TinySQL", "path": "com/sqlmagic/tinysql/tinySQLResultSetMetaData.java", "license": "lgpl-2.1", "size": 9810 }
[ "java.sql.SQLException" ]
import java.sql.SQLException;
import java.sql.*;
[ "java.sql" ]
java.sql;
933,595
protected ISelection getSelection() { return treeViewer.getSelection(); }
ISelection function() { return treeViewer.getSelection(); }
/** * Gets the selection. * * @return The selection */
Gets the selection
getSelection
{ "repo_name": "TANGO-Project/code-optimiser-plugin", "path": "bundles/org.jvmmonitor.ui/src/org/jvmmonitor/internal/ui/views/JvmExplorer.java", "license": "apache-2.0", "size": 3563 }
[ "org.eclipse.jface.viewers.ISelection" ]
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.*;
[ "org.eclipse.jface" ]
org.eclipse.jface;
523,562
public void setTotalGrossReqAmount(KualiInteger totalGrossReqAmount) { this.totalGrossReqAmount = totalGrossReqAmount; }
void function(KualiInteger totalGrossReqAmount) { this.totalGrossReqAmount = totalGrossReqAmount; }
/** * Sets the totalGrossReqAmount * * @param totalGrossReqAmount The totalGrossReqAmount to set. */
Sets the totalGrossReqAmount
setTotalGrossReqAmount
{ "repo_name": "ua-eas/ua-kfs-5.3", "path": "work/src/org/kuali/kfs/module/bc/businessobject/BudgetConstructionOrgSubFundSummaryReport.java", "license": "agpl-3.0", "size": 27198 }
[ "org.kuali.rice.core.api.util.type.KualiInteger" ]
import org.kuali.rice.core.api.util.type.KualiInteger;
import org.kuali.rice.core.api.util.type.*;
[ "org.kuali.rice" ]
org.kuali.rice;
2,151,904
private static String filterErrorString(String xmlString) { String errorString; StringBuilder builder = new StringBuilder(); Pattern pattern = Pattern.compile("<error>(.*?)</error>"); Matcher matcher = pattern.matcher(xmlString); while (matcher.find()) { builder.append(matcher.group(1) + "\r\n"); } errorString = builder.toString(); if (errorString.contains("\r\n")) { errorString = errorString.substring(0, builder.lastIndexOf("\r\n")); } return errorString; }
static String function(String xmlString) { String errorString; StringBuilder builder = new StringBuilder(); Pattern pattern = Pattern.compile(STR); Matcher matcher = pattern.matcher(xmlString); while (matcher.find()) { builder.append(matcher.group(1) + "\r\n"); } errorString = builder.toString(); if (errorString.contains("\r\n")) { errorString = errorString.substring(0, builder.lastIndexOf("\r\n")); } return errorString; }
/** * filter error string from the Veracode response. * * @param xmlString * @return the error string */
filter error string from the Veracode response
filterErrorString
{ "repo_name": "wso2/security-tools", "path": "internal/scan-manager/scanners/veracode/src/main/java/org/wso2/security/tools/scanmanager/scanners/veracode/handler/VeracodeResultProcessor.java", "license": "apache-2.0", "size": 10428 }
[ "java.util.regex.Matcher", "java.util.regex.Pattern" ]
import java.util.regex.Matcher; import java.util.regex.Pattern;
import java.util.regex.*;
[ "java.util" ]
java.util;
998,707
private double getLengthAllTfDim(final Object gemNr, final String gu, final GerinneGeschlFlaechenReportDialog.Art art, final Integer tfFrom, final Integer tfTill, final Integer dimFrom, final Integer dimTill) { final List<GmdPartObjGeschl> gemList = gemPartMap.get(gemNr); double length = 0; for (final GmdPartObjGeschl tmp : gemList) { if (tmp.getOwner().equals(gu) && tmp.getArt().equals(art.name()) && valueBetween(tmp.getTf(), tfFrom, tfTill) && valueBetween(tmp.getDim(), dimFrom, dimTill)) { length += tmp.getLength(); } } return length; }
double function(final Object gemNr, final String gu, final GerinneGeschlFlaechenReportDialog.Art art, final Integer tfFrom, final Integer tfTill, final Integer dimFrom, final Integer dimTill) { final List<GmdPartObjGeschl> gemList = gemPartMap.get(gemNr); double length = 0; for (final GmdPartObjGeschl tmp : gemList) { if (tmp.getOwner().equals(gu) && tmp.getArt().equals(art.name()) && valueBetween(tmp.getTf(), tfFrom, tfTill) && valueBetween(tmp.getDim(), dimFrom, dimTill)) { length += tmp.getLength(); } } return length; }
/** * DOCUMENT ME! * * @param gemNr DOCUMENT ME! * @param gu gew DOCUMENT ME! * @param art DOCUMENT ME! * @param tfFrom DOCUMENT ME! * @param tfTill DOCUMENT ME! * @param dimFrom DOCUMENT ME! * @param dimTill DOCUMENT ME! * * @return DOCUMENT ME! */
DOCUMENT ME
getLengthAllTfDim
{ "repo_name": "cismet/watergis-client", "path": "src/main/java/de/cismet/watergis/reports/GerinneGFlReport.java", "license": "lgpl-3.0", "size": 159735 }
[ "de.cismet.watergis.gui.dialog.GerinneGeschlFlaechenReportDialog", "de.cismet.watergis.reports.types.GmdPartObjGeschl", "java.util.List" ]
import de.cismet.watergis.gui.dialog.GerinneGeschlFlaechenReportDialog; import de.cismet.watergis.reports.types.GmdPartObjGeschl; import java.util.List;
import de.cismet.watergis.gui.dialog.*; import de.cismet.watergis.reports.types.*; import java.util.*;
[ "de.cismet.watergis", "java.util" ]
de.cismet.watergis; java.util;
489,848
public DateTime getMaxDate4Procedure(final String procedure, final Session session) throws OwsExceptionReport { Object maxStart = null; Object maxEnd = null; if (HibernateHelper.isNamedQuerySupported(SQL_QUERY_GET_MAX_DATE_FOR_PROCEDURE, session)) { Query namedQuery = session.getNamedQuery(SQL_QUERY_GET_MAX_DATE_FOR_PROCEDURE); namedQuery.setParameter(PROCEDURE, procedure); LOGGER.trace("QUERY getMaxDate4Procedure(procedure) with NamedQuery: {}", SQL_QUERY_GET_MAX_DATE_FOR_PROCEDURE); maxStart = namedQuery.uniqueResult(); maxEnd = maxStart; } else { AbstractObservationDAO observationDAO = getDaoFactory().getObservationDAO(); Criteria cstart = observationDAO.getDefaultObservationInfoCriteria(session); Criteria cend = observationDAO.getDefaultObservationInfoCriteria(session); if (observationDAO instanceof SeriesObservationDAO) { addProcedureRestrictionForSeries(cstart, procedure); addProcedureRestrictionForSeries(cend, procedure); } else { addProcedureRestrictionForObservation(cstart, procedure); addProcedureRestrictionForObservation(cend, procedure); } addMinMaxProjection(cstart, MinMax.MAX, DataEntity.PROPERTY_SAMPLING_TIME_START); addMinMaxProjection(cend, MinMax.MAX, DataEntity.PROPERTY_SAMPLING_TIME_END); LOGGER.trace("QUERY getMaxDate4Procedure(procedure) start: {}", HibernateHelper.getSqlString(cstart)); LOGGER.trace("QUERY getMaxDate4Procedure(procedure) end: {}", HibernateHelper.getSqlString(cend)); if (HibernateHelper.getSqlString(cstart).endsWith(HibernateHelper.getSqlString(cend))) { maxStart = cstart.uniqueResult(); maxEnd = maxStart; LOGGER.trace("Max time start and end query are identically, only one query is executed!"); } else { maxStart = cstart.uniqueResult(); maxEnd = cend.uniqueResult(); } } if (maxStart == null && maxEnd == null) { return null; } else { final DateTime start = new DateTime(maxStart, DateTimeZone.UTC); if (maxEnd != null) { final DateTime end = new DateTime(maxEnd, DateTimeZone.UTC); if (end.isAfter(start)) { return end; } } return start; } }
DateTime function(final String procedure, final Session session) throws OwsExceptionReport { Object maxStart = null; Object maxEnd = null; if (HibernateHelper.isNamedQuerySupported(SQL_QUERY_GET_MAX_DATE_FOR_PROCEDURE, session)) { Query namedQuery = session.getNamedQuery(SQL_QUERY_GET_MAX_DATE_FOR_PROCEDURE); namedQuery.setParameter(PROCEDURE, procedure); LOGGER.trace(STR, SQL_QUERY_GET_MAX_DATE_FOR_PROCEDURE); maxStart = namedQuery.uniqueResult(); maxEnd = maxStart; } else { AbstractObservationDAO observationDAO = getDaoFactory().getObservationDAO(); Criteria cstart = observationDAO.getDefaultObservationInfoCriteria(session); Criteria cend = observationDAO.getDefaultObservationInfoCriteria(session); if (observationDAO instanceof SeriesObservationDAO) { addProcedureRestrictionForSeries(cstart, procedure); addProcedureRestrictionForSeries(cend, procedure); } else { addProcedureRestrictionForObservation(cstart, procedure); addProcedureRestrictionForObservation(cend, procedure); } addMinMaxProjection(cstart, MinMax.MAX, DataEntity.PROPERTY_SAMPLING_TIME_START); addMinMaxProjection(cend, MinMax.MAX, DataEntity.PROPERTY_SAMPLING_TIME_END); LOGGER.trace(STR, HibernateHelper.getSqlString(cstart)); LOGGER.trace(STR, HibernateHelper.getSqlString(cend)); if (HibernateHelper.getSqlString(cstart).endsWith(HibernateHelper.getSqlString(cend))) { maxStart = cstart.uniqueResult(); maxEnd = maxStart; LOGGER.trace(STR); } else { maxStart = cstart.uniqueResult(); maxEnd = cend.uniqueResult(); } } if (maxStart == null && maxEnd == null) { return null; } else { final DateTime start = new DateTime(maxStart, DateTimeZone.UTC); if (maxEnd != null) { final DateTime end = new DateTime(maxEnd, DateTimeZone.UTC); if (end.isAfter(start)) { return end; } } return start; } }
/** * Get max time from observations for procedure * * @param procedure * ProcedureEntity identifier * @param session * Hibernate session * @return max time for procedure * @throws CodedException * If an error occurs */
Get max time from observations for procedure
getMaxDate4Procedure
{ "repo_name": "52North/SOS", "path": "hibernate/common/src/main/java/org/n52/sos/ds/hibernate/dao/ProcedureDAO.java", "license": "gpl-2.0", "size": 49589 }
[ "org.hibernate.Criteria", "org.hibernate.Session", "org.hibernate.query.Query", "org.joda.time.DateTime", "org.joda.time.DateTimeZone", "org.n52.series.db.beans.DataEntity", "org.n52.shetland.ogc.ows.exception.OwsExceptionReport", "org.n52.sos.ds.hibernate.dao.observation.AbstractObservationDAO", "org.n52.sos.ds.hibernate.dao.observation.series.SeriesObservationDAO", "org.n52.sos.ds.hibernate.util.HibernateHelper" ]
import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.query.Query; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.n52.series.db.beans.DataEntity; import org.n52.shetland.ogc.ows.exception.OwsExceptionReport; import org.n52.sos.ds.hibernate.dao.observation.AbstractObservationDAO; import org.n52.sos.ds.hibernate.dao.observation.series.SeriesObservationDAO; import org.n52.sos.ds.hibernate.util.HibernateHelper;
import org.hibernate.*; import org.hibernate.query.*; import org.joda.time.*; import org.n52.series.db.beans.*; import org.n52.shetland.ogc.ows.exception.*; import org.n52.sos.ds.hibernate.dao.observation.*; import org.n52.sos.ds.hibernate.dao.observation.series.*; import org.n52.sos.ds.hibernate.util.*;
[ "org.hibernate", "org.hibernate.query", "org.joda.time", "org.n52.series", "org.n52.shetland", "org.n52.sos" ]
org.hibernate; org.hibernate.query; org.joda.time; org.n52.series; org.n52.shetland; org.n52.sos;
2,182,553
public Node getRoot();
Node function();
/** * The <code>root</code> node of the <code>TreeWalker</code>, as specified * when it was created. */
The <code>root</code> node of the <code>TreeWalker</code>, as specified when it was created
getRoot
{ "repo_name": "shun634501730/java_source_cn", "path": "src_en/org/w3c/dom/traversal/TreeWalker.java", "license": "apache-2.0", "size": 8857 }
[ "org.w3c.dom.Node" ]
import org.w3c.dom.Node;
import org.w3c.dom.*;
[ "org.w3c.dom" ]
org.w3c.dom;
2,186,799
IPageMapEvictionStrategy getPageMapEvictionStrategy();
IPageMapEvictionStrategy getPageMapEvictionStrategy();
/** * Gets the strategy for evicting pages from the page map. * * @return the strategy for evicting pages from the page map */
Gets the strategy for evicting pages from the page map
getPageMapEvictionStrategy
{ "repo_name": "Servoy/wicket", "path": "wicket/src/main/java/org/apache/wicket/settings/ISessionSettings.java", "license": "apache-2.0", "size": 2980 }
[ "org.apache.wicket.session.pagemap.IPageMapEvictionStrategy" ]
import org.apache.wicket.session.pagemap.IPageMapEvictionStrategy;
import org.apache.wicket.session.pagemap.*;
[ "org.apache.wicket" ]
org.apache.wicket;
29,061
public void testEmbeddedCollection() throws Exception { addClassesToSchema(new Class[] {EmbeddedCollectionOwner.class, EmbeddedCollElement.class}); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); RDBMSStoreManager databaseMgr = (RDBMSStoreManager)storeMgr; Connection conn = null; ManagedConnection mconn = null; try { tx.begin(); mconn = databaseMgr.getConnectionManager().getConnection(0); conn = (Connection) mconn.getConnection(); DatabaseMetaData dmd = conn.getMetaData(); // Map with embedded value taking default value column names Set<String> columnNames = new HashSet<String>(); columnNames.add("JPA_COLL_EMB_OWNER_ID"); // FK to owner columnNames.add("NAME"); // Element "name" columnNames.add("VALUE"); // Element "value" RDBMSTestHelper.checkColumnsForTable(storeMgr, dmd, "JPA_COLL_EMB", columnNames); // Map with embedded value overriding the value column names Set<String> columnNames2 = new HashSet<String>(); columnNames2.add("JPA_COLL_EMB_OWNER_ID"); // FK to owner columnNames2.add("COLL_ELEM_NAME"); // Element "name" columnNames2.add("COLL_ELEM_VALUE"); // Element "value" RDBMSTestHelper.checkColumnsForTable(storeMgr, dmd, "JPA_COLL_EMB_OVERRIDE", columnNames2); } catch (Exception e) { LOG.error("Exception thrown", e); fail("Exception thrown : " + e.getMessage()); } finally { if (conn != null) { mconn.close(); } if (tx.isActive()) { tx.rollback(); } em.close(); } }
void function() throws Exception { addClassesToSchema(new Class[] {EmbeddedCollectionOwner.class, EmbeddedCollElement.class}); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); RDBMSStoreManager databaseMgr = (RDBMSStoreManager)storeMgr; Connection conn = null; ManagedConnection mconn = null; try { tx.begin(); mconn = databaseMgr.getConnectionManager().getConnection(0); conn = (Connection) mconn.getConnection(); DatabaseMetaData dmd = conn.getMetaData(); Set<String> columnNames = new HashSet<String>(); columnNames.add(STR); columnNames.add("NAME"); columnNames.add("VALUE"); RDBMSTestHelper.checkColumnsForTable(storeMgr, dmd, STR, columnNames); Set<String> columnNames2 = new HashSet<String>(); columnNames2.add(STR); columnNames2.add(STR); columnNames2.add(STR); RDBMSTestHelper.checkColumnsForTable(storeMgr, dmd, STR, columnNames2); } catch (Exception e) { LOG.error(STR, e); fail(STR + e.getMessage()); } finally { if (conn != null) { mconn.close(); } if (tx.isActive()) { tx.rollback(); } em.close(); } }
/** * Test for JPA embedded collection elements. */
Test for JPA embedded collection elements
testEmbeddedCollection
{ "repo_name": "datanucleus/tests", "path": "jakarta/rdbms/src/test/org/datanucleus/tests/SchemaTest.java", "license": "apache-2.0", "size": 30960 }
[ "jakarta.persistence.EntityManager", "jakarta.persistence.EntityTransaction", "java.sql.Connection", "java.sql.DatabaseMetaData", "java.util.HashSet", "java.util.Set", "org.datanucleus.samples.annotations.embedded.collection.EmbeddedCollElement", "org.datanucleus.samples.annotations.embedded.collection.EmbeddedCollectionOwner", "org.datanucleus.store.connection.ManagedConnection", "org.datanucleus.store.rdbms.RDBMSStoreManager" ]
import jakarta.persistence.EntityManager; import jakarta.persistence.EntityTransaction; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.util.HashSet; import java.util.Set; import org.datanucleus.samples.annotations.embedded.collection.EmbeddedCollElement; import org.datanucleus.samples.annotations.embedded.collection.EmbeddedCollectionOwner; import org.datanucleus.store.connection.ManagedConnection; import org.datanucleus.store.rdbms.RDBMSStoreManager;
import jakarta.persistence.*; import java.sql.*; import java.util.*; import org.datanucleus.samples.annotations.embedded.collection.*; import org.datanucleus.store.connection.*; import org.datanucleus.store.rdbms.*;
[ "jakarta.persistence", "java.sql", "java.util", "org.datanucleus.samples", "org.datanucleus.store" ]
jakarta.persistence; java.sql; java.util; org.datanucleus.samples; org.datanucleus.store;
1,744,436
public void fill(Composite parent);
void function(Composite parent);
/** * Fills the given composite control with controls representing this widget. * * @param parent * the parent control */
Fills the given composite control with controls representing this widget
fill
{ "repo_name": "AntoineDelacroix/NewSuperProject-", "path": "org.eclipse.jface/src/org/eclipse/jface/menus/IWidget.java", "license": "gpl-2.0", "size": 2494 }
[ "org.eclipse.swt.widgets.Composite" ]
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.*;
[ "org.eclipse.swt" ]
org.eclipse.swt;
828,856
public static StarGraph readStarGraphVertex(final Map<String, Object> vertexData) throws IOException { final StarGraph starGraph = StarGraph.open(); starGraph.addVertex(T.id, vertexData.get(GraphSONTokens.ID), T.label, vertexData.get(GraphSONTokens.LABEL)); if (vertexData.containsKey(GraphSONTokens.PROPERTIES)) { final Map<String, List<Map<String, Object>>> properties = (Map<String, List<Map<String, Object>>>) vertexData.get(GraphSONTokens.PROPERTIES); for (Map.Entry<String, List<Map<String, Object>>> property : properties.entrySet()) { for (Map<String, Object> p : property.getValue()) { final StarGraph.StarVertexProperty vp = (StarGraph.StarVertexProperty) starGraph.getStarVertex().property(VertexProperty.Cardinality.list, property.getKey(), p.get(GraphSONTokens.VALUE), T.id, p.get(GraphSONTokens.ID)); if (p.containsKey(GraphSONTokens.PROPERTIES)) { final Map<String, Object> edgePropertyData = (Map<String, Object>) p.get(GraphSONTokens.PROPERTIES); for (Map.Entry<String, Object> epd : edgePropertyData.entrySet()) { vp.property(epd.getKey(), epd.getValue()); } } } } } return starGraph; }
static StarGraph function(final Map<String, Object> vertexData) throws IOException { final StarGraph starGraph = StarGraph.open(); starGraph.addVertex(T.id, vertexData.get(GraphSONTokens.ID), T.label, vertexData.get(GraphSONTokens.LABEL)); if (vertexData.containsKey(GraphSONTokens.PROPERTIES)) { final Map<String, List<Map<String, Object>>> properties = (Map<String, List<Map<String, Object>>>) vertexData.get(GraphSONTokens.PROPERTIES); for (Map.Entry<String, List<Map<String, Object>>> property : properties.entrySet()) { for (Map<String, Object> p : property.getValue()) { final StarGraph.StarVertexProperty vp = (StarGraph.StarVertexProperty) starGraph.getStarVertex().property(VertexProperty.Cardinality.list, property.getKey(), p.get(GraphSONTokens.VALUE), T.id, p.get(GraphSONTokens.ID)); if (p.containsKey(GraphSONTokens.PROPERTIES)) { final Map<String, Object> edgePropertyData = (Map<String, Object>) p.get(GraphSONTokens.PROPERTIES); for (Map.Entry<String, Object> epd : edgePropertyData.entrySet()) { vp.property(epd.getKey(), epd.getValue()); } } } } } return starGraph; }
/** * A helper function for reading a serialized {@link StarGraph} from a {@link Map} generated by * {@link StarGraphGraphSONSerializer}. */
A helper function for reading a serialized <code>StarGraph</code> from a <code>Map</code> generated by <code>StarGraphGraphSONSerializer</code>
readStarGraphVertex
{ "repo_name": "gdelafosse/incubator-tinkerpop", "path": "gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/star/StarGraphGraphSONSerializer.java", "license": "apache-2.0", "size": 14719 }
[ "java.io.IOException", "java.util.List", "java.util.Map", "org.apache.tinkerpop.gremlin.structure.VertexProperty", "org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONTokens" ]
import java.io.IOException; import java.util.List; import java.util.Map; import org.apache.tinkerpop.gremlin.structure.VertexProperty; import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONTokens;
import java.io.*; import java.util.*; import org.apache.tinkerpop.gremlin.structure.*; import org.apache.tinkerpop.gremlin.structure.io.graphson.*;
[ "java.io", "java.util", "org.apache.tinkerpop" ]
java.io; java.util; org.apache.tinkerpop;
2,214,381
public List<TaskState> getTaskStates() { return ImmutableList.<TaskState>builder().addAll(this.taskStates.values()).build(); }
List<TaskState> function() { return ImmutableList.<TaskState>builder().addAll(this.taskStates.values()).build(); }
/** * Get {@link TaskState}s of {@link Task}s of this job. * * @return {@link TaskState}s of {@link Task}s of this job */
Get <code>TaskState</code>s of <code>Task</code>s of this job
getTaskStates
{ "repo_name": "chavdar/gobblin", "path": "gobblin-runtime/src/main/java/gobblin/runtime/JobState.java", "license": "apache-2.0", "size": 12203 }
[ "com.google.common.collect.ImmutableList", "java.util.List" ]
import com.google.common.collect.ImmutableList; import java.util.List;
import com.google.common.collect.*; import java.util.*;
[ "com.google.common", "java.util" ]
com.google.common; java.util;
2,024,382
protected void configureContext(ServletContext context) { ObjectGraph injector = getInjector(context); // create the runtime settings object IStoredSettings runtimeSettings = injector.get(IStoredSettings.class); final File baseFolder; if (goSettings != null) { // Gitblit GO baseFolder = configureGO(context, goSettings, goBaseFolder, runtimeSettings); } else { // servlet container WebXmlSettings webxmlSettings = new WebXmlSettings(context); String contextRealPath = context.getRealPath("/"); File contextFolder = (contextRealPath != null) ? new File(contextRealPath) : null; // if the base folder dosen't match the default assume they don't want to use express, // this allows for other containers to customise the basefolder per context. String defaultBase = Constants.contextFolder$ + "/WEB-INF/data"; String base = getBaseFolderPath(defaultBase); if (!StringUtils.isEmpty(System.getenv("OPENSHIFT_DATA_DIR")) && defaultBase.equals(base)) { // RedHat OpenShift baseFolder = configureExpress(context, webxmlSettings, contextFolder, runtimeSettings); } else { // standard WAR baseFolder = configureWAR(context, webxmlSettings, contextFolder, runtimeSettings); } // Test for Tomcat forward-slash/%2F issue and auto-adjust settings ContainerUtils.CVE_2007_0450.test(runtimeSettings); } // Manually configure IRuntimeManager logManager(IRuntimeManager.class); IRuntimeManager runtime = injector.get(IRuntimeManager.class); runtime.setBaseFolder(baseFolder); runtime.getStatus().isGO = goSettings != null; runtime.getStatus().servletContainer = context.getServerInfo(); runtime.start(); managers.add(runtime); // create the plugin manager instance but do not start it loadManager(injector, IPluginManager.class); // start all other managers startManager(injector, INotificationManager.class); startManager(injector, IUserManager.class); startManager(injector, IAuthenticationManager.class); startManager(injector, IPublicKeyManager.class); startManager(injector, IRepositoryManager.class); startManager(injector, IProjectManager.class); startManager(injector, IFederationManager.class); startManager(injector, IGitblit.class); // start the plugin manager last so that plugins can depend on // deterministic access to all other managers in their start() methods startManager(injector, IPluginManager.class); logger.info(""); logger.info("All managers started."); logger.info(""); IPluginManager pluginManager = injector.get(IPluginManager.class); for (LifeCycleListener listener : pluginManager.getExtensions(LifeCycleListener.class)) { try { listener.onStartup(); } catch (Throwable t) { logger.error(null, t); } } }
void function(ServletContext context) { ObjectGraph injector = getInjector(context); IStoredSettings runtimeSettings = injector.get(IStoredSettings.class); final File baseFolder; if (goSettings != null) { baseFolder = configureGO(context, goSettings, goBaseFolder, runtimeSettings); } else { WebXmlSettings webxmlSettings = new WebXmlSettings(context); String contextRealPath = context.getRealPath("/"); File contextFolder = (contextRealPath != null) ? new File(contextRealPath) : null; String defaultBase = Constants.contextFolder$ + STR; String base = getBaseFolderPath(defaultBase); if (!StringUtils.isEmpty(System.getenv(STR)) && defaultBase.equals(base)) { baseFolder = configureExpress(context, webxmlSettings, contextFolder, runtimeSettings); } else { baseFolder = configureWAR(context, webxmlSettings, contextFolder, runtimeSettings); } ContainerUtils.CVE_2007_0450.test(runtimeSettings); } logManager(IRuntimeManager.class); IRuntimeManager runtime = injector.get(IRuntimeManager.class); runtime.setBaseFolder(baseFolder); runtime.getStatus().isGO = goSettings != null; runtime.getStatus().servletContainer = context.getServerInfo(); runtime.start(); managers.add(runtime); loadManager(injector, IPluginManager.class); startManager(injector, INotificationManager.class); startManager(injector, IUserManager.class); startManager(injector, IAuthenticationManager.class); startManager(injector, IPublicKeyManager.class); startManager(injector, IRepositoryManager.class); startManager(injector, IProjectManager.class); startManager(injector, IFederationManager.class); startManager(injector, IGitblit.class); startManager(injector, IPluginManager.class); logger.info(STRAll managers started.STR"); IPluginManager pluginManager = injector.get(IPluginManager.class); for (LifeCycleListener listener : pluginManager.getExtensions(LifeCycleListener.class)) { try { listener.onStartup(); } catch (Throwable t) { logger.error(null, t); } } }
/** * Prepare runtime settings and start all manager instances. */
Prepare runtime settings and start all manager instances
configureContext
{ "repo_name": "cesarmarinhorj/gitblit", "path": "src/main/java/com/gitblit/servlet/GitblitContext.java", "license": "apache-2.0", "size": 15521 }
[ "com.gitblit.Constants", "com.gitblit.IStoredSettings", "com.gitblit.WebXmlSettings", "com.gitblit.extensions.LifeCycleListener", "com.gitblit.manager.IAuthenticationManager", "com.gitblit.manager.IFederationManager", "com.gitblit.manager.IGitblit", "com.gitblit.manager.INotificationManager", "com.gitblit.manager.IPluginManager", "com.gitblit.manager.IProjectManager", "com.gitblit.manager.IRepositoryManager", "com.gitblit.manager.IRuntimeManager", "com.gitblit.manager.IUserManager", "com.gitblit.transport.ssh.IPublicKeyManager", "com.gitblit.utils.ContainerUtils", "com.gitblit.utils.StringUtils", "java.io.File", "javax.servlet.ServletContext" ]
import com.gitblit.Constants; import com.gitblit.IStoredSettings; import com.gitblit.WebXmlSettings; import com.gitblit.extensions.LifeCycleListener; import com.gitblit.manager.IAuthenticationManager; import com.gitblit.manager.IFederationManager; import com.gitblit.manager.IGitblit; import com.gitblit.manager.INotificationManager; import com.gitblit.manager.IPluginManager; import com.gitblit.manager.IProjectManager; import com.gitblit.manager.IRepositoryManager; import com.gitblit.manager.IRuntimeManager; import com.gitblit.manager.IUserManager; import com.gitblit.transport.ssh.IPublicKeyManager; import com.gitblit.utils.ContainerUtils; import com.gitblit.utils.StringUtils; import java.io.File; import javax.servlet.ServletContext;
import com.gitblit.*; import com.gitblit.extensions.*; import com.gitblit.manager.*; import com.gitblit.transport.ssh.*; import com.gitblit.utils.*; import java.io.*; import javax.servlet.*;
[ "com.gitblit", "com.gitblit.extensions", "com.gitblit.manager", "com.gitblit.transport", "com.gitblit.utils", "java.io", "javax.servlet" ]
com.gitblit; com.gitblit.extensions; com.gitblit.manager; com.gitblit.transport; com.gitblit.utils; java.io; javax.servlet;
151,877
public UniversalBody getBody() { return (UniversalBody) getSource(); }
UniversalBody function() { return (UniversalBody) getSource(); }
/** * Returns the body associated to this event * @return the body associated to this event */
Returns the body associated to this event
getBody
{ "repo_name": "jrochas/scale-proactive", "path": "src/Core/org/objectweb/proactive/core/event/BodyEvent.java", "license": "agpl-3.0", "size": 2578 }
[ "org.objectweb.proactive.core.body.UniversalBody" ]
import org.objectweb.proactive.core.body.UniversalBody;
import org.objectweb.proactive.core.body.*;
[ "org.objectweb.proactive" ]
org.objectweb.proactive;
1,690,732
public int doAfterBody() throws JspException { String label = bodyContent.getString(); if (label != null) { label = label.trim(); if (label.length() > 0) this.label = label; } return (SKIP_BODY); }
int function() throws JspException { String label = bodyContent.getString(); if (label != null) { label = label.trim(); if (label.length() > 0) this.label = label; } return (SKIP_BODY); }
/** * Process the body text of this tag (if any). * * @exception JspException if a JSP exception has occurred */
Process the body text of this tag (if any)
doAfterBody
{ "repo_name": "devjin24/howtomcatworks", "path": "bookrefer/jakarta-tomcat-5.0.18-src/jakarta-tomcat-catalina/webapps/admin/WEB-INF/classes/org/apache/webapp/admin/ActionTag.java", "license": "apache-2.0", "size": 7599 }
[ "javax.servlet.jsp.JspException" ]
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.*;
[ "javax.servlet" ]
javax.servlet;
433,678
public int getSelectedTabIndex() { return selectedTabIndex; } @SideOnly(Side.CLIENT) static class ContainerCreative extends Container { public List<ItemStack> itemList = Lists.<ItemStack>newArrayList(); public ContainerCreative(EntityPlayer p_i1086_1_) { InventoryPlayer inventoryplayer = p_i1086_1_.inventory; for (int i = 0; i < 5; ++i) { for (int j = 0; j < 9; ++j) { this.addSlotToContainer(new Slot(GuiContainerCreative.field_147060_v, i * 9 + j, 9 + j * 18, 18 + i * 18)); } } for (int k = 0; k < 9; ++k) { this.addSlotToContainer(new Slot(inventoryplayer, k, 9 + k * 18, 112)); } this.scrollTo(0.0F); }
int function() { return selectedTabIndex; } @SideOnly(Side.CLIENT) static class ContainerCreative extends Container { public List<ItemStack> itemList = Lists.<ItemStack>newArrayList(); public ContainerCreative(EntityPlayer p_i1086_1_) { InventoryPlayer inventoryplayer = p_i1086_1_.inventory; for (int i = 0; i < 5; ++i) { for (int j = 0; j < 9; ++j) { this.addSlotToContainer(new Slot(GuiContainerCreative.field_147060_v, i * 9 + j, 9 + j * 18, 18 + i * 18)); } } for (int k = 0; k < 9; ++k) { this.addSlotToContainer(new Slot(inventoryplayer, k, 9 + k * 18, 112)); } this.scrollTo(0.0F); }
/** * Returns the index of the currently selected tab. */
Returns the index of the currently selected tab
getSelectedTabIndex
{ "repo_name": "aebert1/BigTransport", "path": "build/tmp/recompileMc/sources/net/minecraft/client/gui/inventory/GuiContainerCreative.java", "license": "gpl-3.0", "size": 43085 }
[ "com.google.common.collect.Lists", "java.util.List", "net.minecraft.entity.player.EntityPlayer", "net.minecraft.entity.player.InventoryPlayer", "net.minecraft.inventory.Container", "net.minecraft.inventory.Slot", "net.minecraft.item.ItemStack", "net.minecraftforge.fml.relauncher.Side", "net.minecraftforge.fml.relauncher.SideOnly" ]
import com.google.common.collect.Lists; import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly;
import com.google.common.collect.*; import java.util.*; import net.minecraft.entity.player.*; import net.minecraft.inventory.*; import net.minecraft.item.*; import net.minecraftforge.fml.relauncher.*;
[ "com.google.common", "java.util", "net.minecraft.entity", "net.minecraft.inventory", "net.minecraft.item", "net.minecraftforge.fml" ]
com.google.common; java.util; net.minecraft.entity; net.minecraft.inventory; net.minecraft.item; net.minecraftforge.fml;
383,093
protected boolean setTableLine(String table, int state, Hashtable line, RuleStateItem item, Integer action, String terminal) { // set one action into a table row and detect conflicts Object o = line.get(terminal); if (o == null) { // no conflict line.put(terminal, action); } else { // conflict? if (o.equals(action) == false) { // conflict! System.err .println("========================================================"); System.err.println("WARNING: " + table + " state " + state + ", terminal " + terminal + " is " + displayAction(o) + " and was overwritten by action " + displayAction(action)); System.err.println("... from rule state: " + item); System.err.println("... current state:\n" + this); System.err .println("========================================================"); return false; } } return true; }
boolean function(String table, int state, Hashtable line, RuleStateItem item, Integer action, String terminal) { Object o = line.get(terminal); if (o == null) { line.put(terminal, action); } else { if (o.equals(action) == false) { System.err .println(STR); System.err.println(STR + table + STR + state + STR + terminal + STR + displayAction(o) + STR + displayAction(action)); System.err.println(STR + item); System.err.println(STR + this); System.err .println(STR); return false; } } return true; }
/** * Set a position in one of the tables. Here SHIFT/SHIFT, SHIFT/REDUCE and * REDUCE/REDUCE conflicts are detected. * * @return true when no conflict was detected */
Set a position in one of the tables. Here SHIFT/SHIFT, SHIFT/REDUCE and REDUCE/REDUCE conflicts are detected
setTableLine
{ "repo_name": "dashorst/runcc", "path": "src/main/java/com/martijndashorst/runcc/patterns/interpreter/parsergenerator/parsertables/SLRSyntaxNode.java", "license": "lgpl-3.0", "size": 18725 }
[ "java.util.Hashtable" ]
import java.util.Hashtable;
import java.util.*;
[ "java.util" ]
java.util;
610,964
public final void testGeneralizedEncoderDecoder02() throws ParseException, IOException { runTest(true); }
final void function() throws ParseException, IOException { runTest(true); }
/** * GENERALIZED TIME DER Encoder/Decoder test * (InputStream case) * @throws ParseException * @throws IOException */
GENERALIZED TIME DER Encoder/Decoder test (InputStream case)
testGeneralizedEncoderDecoder02
{ "repo_name": "rex-xxx/mt6572_x201", "path": "external/apache-harmony/security/src/test/impl/java/org/apache/harmony/security/tests/asn1/der/DerGeneralizedTimeEDTest.java", "license": "gpl-2.0", "size": 6375 }
[ "java.io.IOException", "java.text.ParseException" ]
import java.io.IOException; import java.text.ParseException;
import java.io.*; import java.text.*;
[ "java.io", "java.text" ]
java.io; java.text;
610,045
public CopyOrMoveRowResult setRowMappings(List<RowMapping> rowMappings) { this.rowMappings = rowMappings; return this; }
CopyOrMoveRowResult function(List<RowMapping> rowMappings) { this.rowMappings = rowMappings; return this; }
/** * Sets the Array of RowMapping objects. * * @param rowMappings the Array of RowMapping objects */
Sets the Array of RowMapping objects
setRowMappings
{ "repo_name": "smartsheet-platform/smartsheet-java-sdk", "path": "src/main/java/com/smartsheet/api/models/CopyOrMoveRowResult.java", "license": "apache-2.0", "size": 1906 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
2,174,449
public int clampViewPositionHorizontal(View child, int left, int dx) { return 0; }
int function(View child, int left, int dx) { return 0; }
/** * Restrict the motion of the dragged child view along the horizontal * axis. The default implementation does not allow horizontal motion; * the extending class must override this method and provide the desired * clamping. * * @param child Child view being dragged * @param left Attempted motion along the X axis * @param dx Proposed change in position for left * @return The new clamped position for left */
Restrict the motion of the dragged child view along the horizontal axis. The default implementation does not allow horizontal motion; the extending class must override this method and provide the desired clamping
clampViewPositionHorizontal
{ "repo_name": "ccrama/Slide", "path": "app/src/main/java/me/ccrama/redditslide/SwipeLayout/ViewDragHelper.java", "license": "gpl-3.0", "size": 62368 }
[ "android.view.View" ]
import android.view.View;
import android.view.*;
[ "android.view" ]
android.view;
2,054,707
@SimpleProperty public YailList Extras() { return extras; }
YailList function() { return extras; }
/** * Returns the list of key-value pairs that will be passed as extra data to the activity. */
Returns the list of key-value pairs that will be passed as extra data to the activity
Extras
{ "repo_name": "josmas/app-inventor", "path": "appinventor/components/src/com/google/appinventor/components/runtime/ActivityStarter.java", "license": "apache-2.0", "size": 22558 }
[ "com.google.appinventor.components.runtime.util.YailList" ]
import com.google.appinventor.components.runtime.util.YailList;
import com.google.appinventor.components.runtime.util.*;
[ "com.google.appinventor" ]
com.google.appinventor;
2,802,689
@Override public void setFilters( List filters ) { throw new UnsupportedOperationException( "not supported for memory stream" ); }
void function( List filters ) { throw new UnsupportedOperationException( STR ); }
/** * This will set the filters that are part of this stream. * * @param filters The filters that are part of this stream. */
This will set the filters that are part of this stream
setFilters
{ "repo_name": "mdamt/pdfbox", "path": "pdfbox/src/main/java/org/apache/pdfbox/pdmodel/common/PDMemoryStream.java", "license": "apache-2.0", "size": 7502 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
181,769
void configure(@NonNull Registry registry);
void configure(@NonNull Registry registry);
/** * This method will be called before any other during {@link Markwon} instance construction. * * @since 4.0.0 */
This method will be called before any other during <code>Markwon</code> instance construction
configure
{ "repo_name": "noties/Markwon", "path": "markwon-core/src/main/java/io/noties/markwon/MarkwonPlugin.java", "license": "apache-2.0", "size": 5077 }
[ "androidx.annotation.NonNull" ]
import androidx.annotation.NonNull;
import androidx.annotation.*;
[ "androidx.annotation" ]
androidx.annotation;
2,753,117
ComponentSelector project(String path); /** * DSL-friendly mechanism to construct a dependency substitution for dependencies matching the provided selector. * <p> * Examples: * <pre class='autoTested'> * configurations { main } * configurations.main.resolutionStrategy.dependencySubstitution { * // Substitute project and module dependencies * substitute module('org.gradle:api') with project(':api') * substitute project(':util') with module('org.gradle:util:3.0') * * // Substitute one module dependency for another * substitute module('org.gradle:api:2.0') with module('org.gradle:api:2.1') * }
ComponentSelector project(String path); /** * DSL-friendly mechanism to construct a dependency substitution for dependencies matching the provided selector. * <p> * Examples: * <pre class='autoTested'> * configurations { main } * configurations.main.resolutionStrategy.dependencySubstitution { * * substitute module('org.gradle:api') with project(':api') * substitute project(':util') with module('org.gradle:util:3.0') * * * substitute module('org.gradle:api:2.0') with module('org.gradle:api:2.1') * }
/** * Create a ProjectComponentSelector from the provided input string. Strings must be in the format ":path". */
Create a ProjectComponentSelector from the provided input string. Strings must be in the format ":path"
project
{ "repo_name": "robinverduijn/gradle", "path": "subprojects/core-api/src/main/java/org/gradle/api/artifacts/DependencySubstitutions.java", "license": "apache-2.0", "size": 4265 }
[ "org.gradle.api.artifacts.component.ComponentSelector" ]
import org.gradle.api.artifacts.component.ComponentSelector;
import org.gradle.api.artifacts.component.*;
[ "org.gradle.api" ]
org.gradle.api;
2,600,820
@Test public void shouldExcludeModuleAndItsChildren() { MavenBuild build = MavenBuild.create(ItUtils.projectPom("shared/multi-modules-sample")) .setGoals("clean verify", "sonar:sonar") .setProperty("sonar.dynamicAnalysis", "false") .setProperty("sonar.skippedModules", "module_b"); orchestrator.executeBuild(build); assertNotNull(getResource("com.sonarsource.it.samples:multi-modules-sample")); assertNotNull(getResource("com.sonarsource.it.samples:module_a")); assertNotNull(getResource("com.sonarsource.it.samples:module_a1")); assertNotNull(getResource("com.sonarsource.it.samples:module_a2")); // excluded project and its children assertNull(getResource("com.sonarsource.it.samples:module_b")); assertNull(getResource("com.sonarsource.it.samples:module_b1")); assertNull(getResource("com.sonarsource.it.samples:module_b2")); }
void function() { MavenBuild build = MavenBuild.create(ItUtils.projectPom(STR)) .setGoals(STR, STR) .setProperty(STR, "false") .setProperty(STR, STR); orchestrator.executeBuild(build); assertNotNull(getResource(STR)); assertNotNull(getResource(STR)); assertNotNull(getResource(STR)); assertNotNull(getResource(STR)); assertNull(getResource(STR)); assertNull(getResource(STR)); assertNull(getResource(STR)); }
/** * Black list */
Black list
shouldExcludeModuleAndItsChildren
{ "repo_name": "joansmith/sonarqube", "path": "it/it-tests/src/test/java/it/analysis/ProjectExclusionsTest.java", "license": "lgpl-3.0", "size": 5550 }
[ "com.sonar.orchestrator.build.MavenBuild", "org.junit.Assert" ]
import com.sonar.orchestrator.build.MavenBuild; import org.junit.Assert;
import com.sonar.orchestrator.build.*; import org.junit.*;
[ "com.sonar.orchestrator", "org.junit" ]
com.sonar.orchestrator; org.junit;
1,616,148
public IConnectionDescription getRegistryClientConnection() { return registryClientConnection; }
IConnectionDescription function() { return registryClientConnection; }
/** * Gets the client side Registry <code>IConnectionDescription</code> of this actor. * * @return the client side Registry connection */
Gets the client side Registry <code>IConnectionDescription</code> of this actor
getRegistryClientConnection
{ "repo_name": "jembi/openxds", "path": "openxds-core/src/main/java/org/openhealthtools/openxds/xca/XcaRGImpl.java", "license": "apache-2.0", "size": 6196 }
[ "org.openhealthtools.openexchange.actorconfig.net.IConnectionDescription" ]
import org.openhealthtools.openexchange.actorconfig.net.IConnectionDescription;
import org.openhealthtools.openexchange.actorconfig.net.*;
[ "org.openhealthtools.openexchange" ]
org.openhealthtools.openexchange;
533,220
@PostMapping(value = "/deleteTaskList", produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody JsonObject deleteWorkflowtask(@RequestParam int taskId) { log.debug("TASK ID : {}", taskId); try { boolean status = workflowService.deleteTaskDetail(taskId); if (!status) return PlatformServiceUtil.buildFailureResponse("The workflow task in use"); else return PlatformServiceUtil.buildSuccessResponseWithData(status); } catch (InsightsCustomException e) { log.error(e); return PlatformServiceUtil.buildFailureResponse(e.getMessage()); } }
@PostMapping(value = STR, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody JsonObject function(@RequestParam int taskId) { log.debug(STR, taskId); try { boolean status = workflowService.deleteTaskDetail(taskId); if (!status) return PlatformServiceUtil.buildFailureResponse(STR); else return PlatformServiceUtil.buildSuccessResponseWithData(status); } catch (InsightsCustomException e) { log.error(e); return PlatformServiceUtil.buildFailureResponse(e.getMessage()); } }
/** * Deleting a task * @param taskId * @return JsonObject */
Deleting a task
deleteWorkflowtask
{ "repo_name": "CognizantOneDevOps/Insights", "path": "PlatformService/src/main/java/com/cognizant/devops/platformservice/workflow/controller/InsightsWorkflowController.java", "license": "apache-2.0", "size": 12009 }
[ "com.cognizant.devops.platformcommons.exception.InsightsCustomException", "com.cognizant.devops.platformservice.rest.util.PlatformServiceUtil", "com.google.gson.JsonObject", "org.springframework.http.MediaType", "org.springframework.web.bind.annotation.PostMapping", "org.springframework.web.bind.annotation.RequestParam", "org.springframework.web.bind.annotation.ResponseBody" ]
import com.cognizant.devops.platformcommons.exception.InsightsCustomException; import com.cognizant.devops.platformservice.rest.util.PlatformServiceUtil; import com.google.gson.JsonObject; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody;
import com.cognizant.devops.platformcommons.exception.*; import com.cognizant.devops.platformservice.rest.util.*; import com.google.gson.*; import org.springframework.http.*; import org.springframework.web.bind.annotation.*;
[ "com.cognizant.devops", "com.google.gson", "org.springframework.http", "org.springframework.web" ]
com.cognizant.devops; com.google.gson; org.springframework.http; org.springframework.web;
1,736,995
public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, double range) throws ParticleVersionException, ParticleDataException { if (!isSupported()) { throw new ParticleVersionException("This particle effect is not supported by your server version"); } if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { throw new ParticleDataException("This particle effect does not require additional data"); } if (!isDataCorrect(this, data)) { throw new ParticleDataException("The particle data type is incorrect"); } new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, range > 256, data).sendTo(center, range); }
void function(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, double range) throws ParticleVersionException, ParticleDataException { if (!isSupported()) { throw new ParticleVersionException(STR); } if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { throw new ParticleDataException(STR); } if (!isDataCorrect(this, data)) { throw new ParticleDataException(STR); } new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, range > 256, data).sendTo(center, range); }
/** * Displays a particle effect which requires additional data and is only visible for all players within a certain range in the world of @param center * * @param data Data of the effect * @param offsetX Maximum distance particles can fly away from the center on the x-axis * @param offsetY Maximum distance particles can fly away from the center on the y-axis * @param offsetZ Maximum distance particles can fly away from the center on the z-axis * @param speed Display speed of the particles * @param amount Amount of particles * @param center Center location of the effect * @param range Range of the visibility * @throws ParticleVersionException If the particle effect is not supported by the server version * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect * @see ParticlePacket * @see ParticlePacket#sendTo(Location, double) */
Displays a particle effect which requires additional data and is only visible for all players within a certain range in the world of @param center
display
{ "repo_name": "NavidK0/PSCiv", "path": "src/main/java/com/lastabyss/psciv/util/ParticleEffect.java", "license": "mit", "size": 96450 }
[ "org.bukkit.Location" ]
import org.bukkit.Location;
import org.bukkit.*;
[ "org.bukkit" ]
org.bukkit;
2,105,508
@WebMethod @WebResult(name = "rval", targetNamespace = "https://www.google.com/apis/ads/publisher/v202111") @RequestWrapper(localName = "updateOrders", targetNamespace = "https://www.google.com/apis/ads/publisher/v202111", className = "com.google.api.ads.admanager.jaxws.v202111.OrderServiceInterfaceupdateOrders") @ResponseWrapper(localName = "updateOrdersResponse", targetNamespace = "https://www.google.com/apis/ads/publisher/v202111", className = "com.google.api.ads.admanager.jaxws.v202111.OrderServiceInterfaceupdateOrdersResponse") public List<Order> updateOrders( @WebParam(name = "orders", targetNamespace = "https://www.google.com/apis/ads/publisher/v202111") List<Order> orders) throws ApiException_Exception ;
@WebResult(name = "rval", targetNamespace = STRupdateOrdersSTRhttps: @ResponseWrapper(localName = "updateOrdersResponseSTRhttps: List<Order> function( @WebParam(name = "ordersSTRhttps: List<Order> orders) throws ApiException_Exception ;
/** * * Updates the specified {@link Order} objects. * * @param orders the orders to update * @return the updated orders * * * @param orders * @return * returns java.util.List<com.google.api.ads.admanager.jaxws.v202111.Order> * @throws ApiException_Exception */
Updates the specified <code>Order</code> objects
updateOrders
{ "repo_name": "googleads/googleads-java-lib", "path": "modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202111/OrderServiceInterface.java", "license": "apache-2.0", "size": 8303 }
[ "java.util.List", "javax.jws.WebParam", "javax.jws.WebResult", "javax.xml.ws.ResponseWrapper" ]
import java.util.List; import javax.jws.WebParam; import javax.jws.WebResult; import javax.xml.ws.ResponseWrapper;
import java.util.*; import javax.jws.*; import javax.xml.ws.*;
[ "java.util", "javax.jws", "javax.xml" ]
java.util; javax.jws; javax.xml;
1,452,425
private ImmutableList<LibraryToLink> convertLibrariesToStaticLibraries( Iterable<LibraryToLink> librariesToLink) { ImmutableList.Builder<LibraryToLink> libraries = ImmutableList.builder(); for (LibraryToLink libraryToLink : librariesToLink) { LibraryToLink.Builder staticLibraryToLink = libraryToLink.toBuilder(); if (libraryToLink.getPicStaticLibrary() != null || libraryToLink.getStaticLibrary() != null) { staticLibraryToLink.setDynamicLibrary(null); staticLibraryToLink.setResolvedSymlinkDynamicLibrary(null); staticLibraryToLink.setInterfaceLibrary(null); staticLibraryToLink.setResolvedSymlinkInterfaceLibrary(null); } libraries.add(staticLibraryToLink.build()); } return libraries.build(); }
ImmutableList<LibraryToLink> function( Iterable<LibraryToLink> librariesToLink) { ImmutableList.Builder<LibraryToLink> libraries = ImmutableList.builder(); for (LibraryToLink libraryToLink : librariesToLink) { LibraryToLink.Builder staticLibraryToLink = libraryToLink.toBuilder(); if (libraryToLink.getPicStaticLibrary() != null libraryToLink.getStaticLibrary() != null) { staticLibraryToLink.setDynamicLibrary(null); staticLibraryToLink.setResolvedSymlinkDynamicLibrary(null); staticLibraryToLink.setInterfaceLibrary(null); staticLibraryToLink.setResolvedSymlinkInterfaceLibrary(null); } libraries.add(staticLibraryToLink.build()); } return libraries.build(); }
/** * This method removes dynamic libraries from LibraryToLink objects coming from C++ dependencies. * The reason for this is that objective-C rules do not support linking the dynamic version of the * libraries. */
This method removes dynamic libraries from LibraryToLink objects coming from C++ dependencies. The reason for this is that objective-C rules do not support linking the dynamic version of the libraries
convertLibrariesToStaticLibraries
{ "repo_name": "ulfjack/bazel", "path": "src/main/java/com/google/devtools/build/lib/rules/objc/ObjcLibrary.java", "license": "apache-2.0", "size": 8674 }
[ "com.google.common.collect.ImmutableList", "com.google.devtools.build.lib.rules.cpp.LibraryToLink" ]
import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.rules.cpp.LibraryToLink;
import com.google.common.collect.*; import com.google.devtools.build.lib.rules.cpp.*;
[ "com.google.common", "com.google.devtools" ]
com.google.common; com.google.devtools;
196,074
protected Schema getFieldSchema(GenericRecord record, String schemaIdLocation) throws Exception { Optional<Object> schemaIdValue = AvroUtils.getFieldValue(record, schemaIdLocation); if (!schemaIdValue.isPresent()) { throw new Exception("Schema id with key " + schemaIdLocation + " not found in the record"); } String schemaKey = String.valueOf(schemaIdValue.get()); return (Schema) registry.getSchemaByKey(schemaKey); } /** * Get payload field and convert to byte array * * @param inputRecord the input record which has the payload * @return the byte array of the payload in the input record * @deprecated use {@link #getFieldAsBytes(GenericRecord, String)}
Schema function(GenericRecord record, String schemaIdLocation) throws Exception { Optional<Object> schemaIdValue = AvroUtils.getFieldValue(record, schemaIdLocation); if (!schemaIdValue.isPresent()) { throw new Exception(STR + schemaIdLocation + STR); } String schemaKey = String.valueOf(schemaIdValue.get()); return (Schema) registry.getSchemaByKey(schemaKey); } /** * Get payload field and convert to byte array * * @param inputRecord the input record which has the payload * @return the byte array of the payload in the input record * @deprecated use {@link #getFieldAsBytes(GenericRecord, String)}
/** * Get the schema of a field * * @param record the input record which has the schema id * @param schemaIdLocation a dot separated location string the schema id * @return a schema referenced by the schema id */
Get the schema of a field
getFieldSchema
{ "repo_name": "jack-moseley/gobblin", "path": "gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/converter/BaseEnvelopeSchemaConverter.java", "license": "apache-2.0", "size": 6969 }
[ "com.google.common.base.Optional", "org.apache.avro.Schema", "org.apache.avro.generic.GenericRecord", "org.apache.gobblin.util.AvroUtils" ]
import com.google.common.base.Optional; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; import org.apache.gobblin.util.AvroUtils;
import com.google.common.base.*; import org.apache.avro.*; import org.apache.avro.generic.*; import org.apache.gobblin.util.*;
[ "com.google.common", "org.apache.avro", "org.apache.gobblin" ]
com.google.common; org.apache.avro; org.apache.gobblin;
1,834,012
@EventHandler public void onBucketFill(PlayerBucketFillEvent event) { CuboidRegion region = regionHandler.getApplicableRegion(event.getBlockClicked().getLocation()); if (!event.isCancelled() && region != null && !region.allows("destroy")) { event.setCancelled(true); warnPlayer(event.getPlayer()); } }
void function(PlayerBucketFillEvent event) { CuboidRegion region = regionHandler.getApplicableRegion(event.getBlockClicked().getLocation()); if (!event.isCancelled() && region != null && !region.allows(STR)) { event.setCancelled(true); warnPlayer(event.getPlayer()); } }
/** * Prevents buckets from being filled */
Prevents buckets from being filled
onBucketFill
{ "repo_name": "redwallhp/AthenaGM", "path": "src/main/java/io/github/redwallhp/athenagm/regions/listeners/BlockBreakListener.java", "license": "lgpl-3.0", "size": 4470 }
[ "io.github.redwallhp.athenagm.regions.CuboidRegion", "org.bukkit.event.player.PlayerBucketFillEvent" ]
import io.github.redwallhp.athenagm.regions.CuboidRegion; import org.bukkit.event.player.PlayerBucketFillEvent;
import io.github.redwallhp.athenagm.regions.*; import org.bukkit.event.player.*;
[ "io.github.redwallhp", "org.bukkit.event" ]
io.github.redwallhp; org.bukkit.event;
37,681
@Override public void setDividerDrawable(Drawable drawable) { super.setDividerDrawable(drawable); }
void function(Drawable drawable) { super.setDividerDrawable(drawable); }
/** * Sets the drawable to use as a divider between the tab indicators. * @param drawable the divider drawable */
Sets the drawable to use as a divider between the tab indicators
setDividerDrawable
{ "repo_name": "mateor/pdroid", "path": "android-4.0.3_r1/trunk/frameworks/base/core/java/android/widget/TabWidget.java", "license": "gpl-3.0", "size": 20231 }
[ "android.graphics.drawable.Drawable" ]
import android.graphics.drawable.Drawable;
import android.graphics.drawable.*;
[ "android.graphics" ]
android.graphics;
1,736,416
void createImpl(boolean stream) throws SocketException { if (impl == null) setImpl(); try { impl.create(stream); created = true; } catch (IOException e) { throw new SocketException(e.getMessage()); } }
void createImpl(boolean stream) throws SocketException { if (impl == null) setImpl(); try { impl.create(stream); created = true; } catch (IOException e) { throw new SocketException(e.getMessage()); } }
/** * Creates the socket implementation. * * @param stream a <code>boolean</code> value : <code>true</code> for a TCP socket, * <code>false</code> for UDP. * @throws IOException if creation fails * @since 1.4 */
Creates the socket implementation
createImpl
{ "repo_name": "ZhaoX/jdk-1.7-annotated", "path": "src/java/net/Socket.java", "license": "apache-2.0", "size": 64511 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
1,527,416
private void openParents(CmsTreeItem item) { if (item != null) { item.setOpen(true); openParents(item.getParentItem()); } }
void function(CmsTreeItem item) { if (item != null) { item.setOpen(true); openParents(item.getParentItem()); } }
/** * Goes up the tree and opens the parents of the item.<p> * * @param item the child item to start from */
Goes up the tree and opens the parents of the item
openParents
{ "repo_name": "victos/opencms-core", "path": "src-gwt/org/opencms/ade/galleries/client/ui/CmsCategoriesTab.java", "license": "lgpl-2.1", "size": 14303 }
[ "org.opencms.gwt.client.ui.tree.CmsTreeItem" ]
import org.opencms.gwt.client.ui.tree.CmsTreeItem;
import org.opencms.gwt.client.ui.tree.*;
[ "org.opencms.gwt" ]
org.opencms.gwt;
2,220,283
public void setUpMouldingProcessTable() throws DAOException { setUpMaterialTable(); DAO<Material> materialDAO = new DAO<Material>(Material.class); materialDAO.setEntityManager(entityManager); Material material = materialDAO.findEntities().get(0); DAO<MouldingProcess> mpDAO = new DAO<MouldingProcess>(MouldingProcess.class); mpDAO.setEntityManager(entityManager); String[] partId = { "1", "2", "3", "4" }; int[] machineSize = { 150, 100, 125, 75 }; String[] machineNo = { "Fanuc 1", "Fanuc 7", "Fanuc 5", "Boy 2" }; Material[] materials = { material, material, material, material }; String[] masterbatchNo = { "20303", "030030", "303002", "30302123" }; Date[] dateOfIssue = { Date.valueOf("2014-06-12"), Date.valueOf("2013-05-11"), Date.valueOf("2010-02-12"), Date.valueOf("2004-01-02") }; String signOffBy = "John Malone"; for (int i = 0; i < partId.length; i++) { MouldingProcess mp = new MouldingProcess(); mp.getBasicInfo().setPartId(parts.get(i)); mp.getBasicInfo().setMachineSize(machineSize[i]); mp.getBasicInfo().setMachineNo(machineNo[i]); mp.getBasicInfo().setMaterial(materials[i]); mp.getBasicInfo().setMasterbatchNo(masterbatchNo[i]); mp.getBasicInfo().setDateOfIssue(dateOfIssue[i]); mp.getBasicInfo().setSignOffBy(signOffBy); mpDAO.addEntity(mp); } mpDAO = null; }
void function() throws DAOException { setUpMaterialTable(); DAO<Material> materialDAO = new DAO<Material>(Material.class); materialDAO.setEntityManager(entityManager); Material material = materialDAO.findEntities().get(0); DAO<MouldingProcess> mpDAO = new DAO<MouldingProcess>(MouldingProcess.class); mpDAO.setEntityManager(entityManager); String[] partId = { "1", "2", "3", "4" }; int[] machineSize = { 150, 100, 125, 75 }; String[] machineNo = { STR, STR, STR, STR }; Material[] materials = { material, material, material, material }; String[] masterbatchNo = { "20303", STR, STR, STR }; Date[] dateOfIssue = { Date.valueOf(STR), Date.valueOf(STR), Date.valueOf(STR), Date.valueOf(STR) }; String signOffBy = STR; for (int i = 0; i < partId.length; i++) { MouldingProcess mp = new MouldingProcess(); mp.getBasicInfo().setPartId(parts.get(i)); mp.getBasicInfo().setMachineSize(machineSize[i]); mp.getBasicInfo().setMachineNo(machineNo[i]); mp.getBasicInfo().setMaterial(materials[i]); mp.getBasicInfo().setMasterbatchNo(masterbatchNo[i]); mp.getBasicInfo().setDateOfIssue(dateOfIssue[i]); mp.getBasicInfo().setSignOffBy(signOffBy); mpDAO.addEntity(mp); } mpDAO = null; }
/** * A Material table is set up when calling this method * * @throws DAOException */
A Material table is set up when calling this method
setUpMouldingProcessTable
{ "repo_name": "subwoofer359/aplsystem", "path": "src/test/java/org/amc/myservlet/test/spc/TestSPCFixture.java", "license": "mit", "size": 6633 }
[ "java.sql.Date", "org.amc.DAOException", "org.amc.model.Material", "org.amc.model.MouldingProcess" ]
import java.sql.Date; import org.amc.DAOException; import org.amc.model.Material; import org.amc.model.MouldingProcess;
import java.sql.*; import org.amc.*; import org.amc.model.*;
[ "java.sql", "org.amc", "org.amc.model" ]
java.sql; org.amc; org.amc.model;
2,750,173
public TemporalConverter.Conversion<ZonedDateTime, Date> zonedDateTimeConversion() { return TemporalConverter.Conversion.of(ZonedDateTime.class, this::encode); }
TemporalConverter.Conversion<ZonedDateTime, Date> function() { return TemporalConverter.Conversion.of(ZonedDateTime.class, this::encode); }
/** * Gets the conversion function of a {@link ZonedDateTime} instance to an iCal4J date object. The * function will throw a {@link SilverpeasRuntimeException} if the conversion fails. * @return a conversion of a {@link ZonedDateTime} to an iCal4J {@link DateTime} value. */
Gets the conversion function of a <code>ZonedDateTime</code> instance to an iCal4J date object. The function will throw a <code>SilverpeasRuntimeException</code> if the conversion fails
zonedDateTimeConversion
{ "repo_name": "SilverDav/Silverpeas-Core", "path": "core-library/src/main/java/org/silverpeas/core/calendar/ical4j/ICal4JDateCodec.java", "license": "agpl-3.0", "size": 9722 }
[ "java.time.ZonedDateTime", "net.fortuna.ical4j.model.Date", "org.silverpeas.core.date.TemporalConverter" ]
import java.time.ZonedDateTime; import net.fortuna.ical4j.model.Date; import org.silverpeas.core.date.TemporalConverter;
import java.time.*; import net.fortuna.ical4j.model.*; import org.silverpeas.core.date.*;
[ "java.time", "net.fortuna.ical4j", "org.silverpeas.core" ]
java.time; net.fortuna.ical4j; org.silverpeas.core;
159,700
void addScrapView(View scrap) { TwoWayAbsListView.LayoutParams lp = (TwoWayAbsListView.LayoutParams) scrap.getLayoutParams(); if (lp == null) { return; } // Don't put header or footer views or views that should be ignored // into the scrap heap int viewType = lp.viewType; if (!shouldRecycleViewType(viewType)) { if (viewType != ITEM_VIEW_TYPE_HEADER_OR_FOOTER) { removeDetachedView(scrap, false); } return; } if (mViewTypeCount == 1) { scrap.onStartTemporaryDetach(); mCurrentScrap.add(scrap); } else { scrap.onStartTemporaryDetach(); mScrapViews[viewType].add(scrap); } if (mRecyclerListener != null) { mRecyclerListener.onMovedToScrapHeap(scrap); } }
void addScrapView(View scrap) { TwoWayAbsListView.LayoutParams lp = (TwoWayAbsListView.LayoutParams) scrap.getLayoutParams(); if (lp == null) { return; } int viewType = lp.viewType; if (!shouldRecycleViewType(viewType)) { if (viewType != ITEM_VIEW_TYPE_HEADER_OR_FOOTER) { removeDetachedView(scrap, false); } return; } if (mViewTypeCount == 1) { scrap.onStartTemporaryDetach(); mCurrentScrap.add(scrap); } else { scrap.onStartTemporaryDetach(); mScrapViews[viewType].add(scrap); } if (mRecyclerListener != null) { mRecyclerListener.onMovedToScrapHeap(scrap); } }
/** * Put a view into the ScapViews list. These views are unordered. * * @param scrap The view to add */
Put a view into the ScapViews list. These views are unordered
addScrapView
{ "repo_name": "NhamPhanDinh/customlistview", "path": "src/com/example/reminder_demo/scrollview/TwoWayAbsListView.java", "license": "gpl-2.0", "size": 165054 }
[ "android.view.View" ]
import android.view.View;
import android.view.*;
[ "android.view" ]
android.view;
1,700,953
protected DestinationConfiguration getDestinationConfiguration() throws IOException { String name = getDestinationName(); DestinationConfiguration destination = geConnectivityConfiguration().getConfiguration(name); if (destination == null) { throw new IOException( "Unable to establish a connectivity to the destination [" + name + "]"); } return destination; }
DestinationConfiguration function() throws IOException { String name = getDestinationName(); DestinationConfiguration destination = geConnectivityConfiguration().getConfiguration(name); if (destination == null) { throw new IOException( STR + name + "]"); } return destination; }
/** * Returns a concrete destination configuration object from JNDI connectivity configuration */
Returns a concrete destination configuration object from JNDI connectivity configuration
getDestinationConfiguration
{ "repo_name": "mahnazhaj/iot-starterkit", "path": "src/apps/java/consumption/com.sap.iot.starterkit.ui/src/main/java/com/sap/iot/starterkit/ui/AbstractDispatcherServlet.java", "license": "apache-2.0", "size": 9016 }
[ "com.sap.core.connectivity.api.configuration.DestinationConfiguration", "java.io.IOException" ]
import com.sap.core.connectivity.api.configuration.DestinationConfiguration; import java.io.IOException;
import com.sap.core.connectivity.api.configuration.*; import java.io.*;
[ "com.sap.core", "java.io" ]
com.sap.core; java.io;
1,742,842
@Nonnull public static <T> NumberBinding mapToNumberThenReduce(@Nonnull final ObservableList<T> items, @Nonnull final Supplier<Number> supplier, @Nonnull final ObservableValue<Function<? super T, Number>> mapper, @Nonnull final ObservableValue<BinaryOperator<Number>> reducer) { requireNonNull(supplier, ERROR_SUPPLIER_NULL); requireNonNull(reducer, ERROR_REDUCER_NULL); requireNonNull(mapper, ERROR_MAPPER_NULL); return createDoubleBinding(() -> { BinaryOperator<Number> reducerValue = reducer.getValue(); requireNonNull(reducerValue, ERROR_REDUCER_NULL); final Function<? super T, Number> mapperValue = mapper.getValue(); requireNonNull(mapperValue, ERROR_MAPPER_NULL); return items.stream().map(mapperValue).reduce(reducerValue).orElseGet(supplier).doubleValue(); }, items, reducer, mapper); }
static <T> NumberBinding function(@Nonnull final ObservableList<T> items, @Nonnull final Supplier<Number> supplier, @Nonnull final ObservableValue<Function<? super T, Number>> mapper, @Nonnull final ObservableValue<BinaryOperator<Number>> reducer) { requireNonNull(supplier, ERROR_SUPPLIER_NULL); requireNonNull(reducer, ERROR_REDUCER_NULL); requireNonNull(mapper, ERROR_MAPPER_NULL); return createDoubleBinding(() -> { BinaryOperator<Number> reducerValue = reducer.getValue(); requireNonNull(reducerValue, ERROR_REDUCER_NULL); final Function<? super T, Number> mapperValue = mapper.getValue(); requireNonNull(mapperValue, ERROR_MAPPER_NULL); return items.stream().map(mapperValue).reduce(reducerValue).orElseGet(supplier).doubleValue(); }, items, reducer, mapper); }
/** * Returns a number binding whose value is the reduction of all elements in the list. The mapper function is applied to each element before reduction. * * @param items the observable list of elements. * @param supplier a {@code Supplier} whose result is returned if no value is present. * @param mapper a non-interfering, stateless function to apply to each element. * @param reducer an associative, non-interfering, stateless function for combining two values. * * @return a number binding */
Returns a number binding whose value is the reduction of all elements in the list. The mapper function is applied to each element before reduction
mapToNumberThenReduce
{ "repo_name": "griffon/griffon", "path": "subprojects/griffon-javafx/src/main/java/griffon/javafx/beans/binding/ReducingBindings.java", "license": "apache-2.0", "size": 249342 }
[ "java.util.Objects", "java.util.function.BinaryOperator", "java.util.function.Function", "java.util.function.Supplier" ]
import java.util.Objects; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Supplier;
import java.util.*; import java.util.function.*;
[ "java.util" ]
java.util;
509,790
public BlockWriteStreams writeToBlock(Block b, boolean isRecovery, boolean replicationRequest) throws IOException { // // Make sure the block isn't a valid one - we're still creating it! // if (isValidBlock(b)) { if (!isRecovery) { throw new BlockAlreadyExistsException("Block " + b + " is valid, and cannot be written to."); } // If the block was successfully finalized because all packets // were successfully processed at the Datanode but the ack for // some of the packets were not received by the client. The client // re-opens the connection and retries sending those packets. // The other reason is that an "append" is occurring to this block. detachBlock(b, 1); } long blockSize = b.getNumBytes(); // // Serialize access to /tmp, and check if file already there. // File f = null; List<Thread> threads = null; synchronized (this) { // // Is it already in the create process? // ActiveFile activeFile = ongoingCreates.get(b); if (activeFile != null) { f = activeFile.file; threads = activeFile.threads; if (!isRecovery) { throw new BlockAlreadyExistsException("Block " + b + " has already been started (though not completed), and thus cannot be created."); } else { for (Thread thread:threads) { thread.interrupt(); } } ongoingCreates.remove(b); } FSVolume v = null; if (!isRecovery) { v = volumes.getNextVolume(blockSize); // create temporary file to hold block in the designated volume f = createTmpFile(v, b, replicationRequest); } else if (f != null) { DataNode.LOG.info("Reopen already-open Block for append " + b); // create or reuse temporary file to hold block in the designated volume v = volumeMap.get(b).getVolume(); volumeMap.put(b, new DatanodeBlockInfo(v, f)); } else { // reopening block for appending to it. DataNode.LOG.info("Reopen Block for append " + b); v = volumeMap.get(b).getVolume(); f = createTmpFile(v, b, replicationRequest); File blkfile = getBlockFile(b); File oldmeta = getMetaFile(b); File newmeta = getMetaFile(f, b); // rename meta file to tmp directory DataNode.LOG.debug("Renaming " + oldmeta + " to " + newmeta); if (!oldmeta.renameTo(newmeta)) { throw new IOException("Block " + b + " reopen failed. " + " Unable to move meta file " + oldmeta + " to tmp dir " + newmeta); } // rename block file to tmp directory DataNode.LOG.debug("Renaming " + blkfile + " to " + f); if (!blkfile.renameTo(f)) { if (!f.delete()) { throw new IOException("Block " + b + " reopen failed. " + " Unable to remove file " + f); } if (!blkfile.renameTo(f)) { throw new IOException("Block " + b + " reopen failed. " + " Unable to move block file " + blkfile + " to tmp dir " + f); } } } if (f == null) { DataNode.LOG.warn("Block " + b + " reopen failed " + " Unable to locate tmp file."); throw new IOException("Block " + b + " reopen failed " + " Unable to locate tmp file."); } // If this is a replication request, then this is not a permanent // block yet, it could get removed if the datanode restarts. If this // is a write or append request, then it is a valid block. if (replicationRequest) { volumeMap.put(b, new DatanodeBlockInfo(v)); } else { volumeMap.put(b, new DatanodeBlockInfo(v, f)); } ongoingCreates.put(b, new ActiveFile(f, threads)); } try { if (threads != null) { for (Thread thread:threads) { thread.join(); } } } catch (InterruptedException e) { throw new IOException("Recovery waiting for thread interrupted."); } // // Finally, allow a writer to the block file // REMIND - mjc - make this a filter stream that enforces a max // block size, so clients can't go crazy // File metafile = getMetaFile(f, b); DataNode.LOG.debug("writeTo blockfile is " + f + " of size " + f.length()); DataNode.LOG.debug("writeTo metafile is " + metafile + " of size " + metafile.length()); return createBlockWriteStreams( f , metafile); }
BlockWriteStreams function(Block b, boolean isRecovery, boolean replicationRequest) throws IOException { if (!isRecovery) { throw new BlockAlreadyExistsException(STR + b + STR); } detachBlock(b, 1); } long blockSize = b.getNumBytes(); List<Thread> threads = null; synchronized (this) { if (activeFile != null) { f = activeFile.file; threads = activeFile.threads; if (!isRecovery) { throw new BlockAlreadyExistsException(STR + b + STR); } else { for (Thread thread:threads) { thread.interrupt(); } } ongoingCreates.remove(b); } FSVolume v = null; if (!isRecovery) { v = volumes.getNextVolume(blockSize); f = createTmpFile(v, b, replicationRequest); } else if (f != null) { DataNode.LOG.info(STR + b); v = volumeMap.get(b).getVolume(); volumeMap.put(b, new DatanodeBlockInfo(v, f)); } else { DataNode.LOG.info(STR + b); v = volumeMap.get(b).getVolume(); f = createTmpFile(v, b, replicationRequest); File blkfile = getBlockFile(b); File oldmeta = getMetaFile(b); File newmeta = getMetaFile(f, b); DataNode.LOG.debug(STR + oldmeta + STR + newmeta); if (!oldmeta.renameTo(newmeta)) { throw new IOException(STR + b + STR + STR + oldmeta + STR + newmeta); } DataNode.LOG.debug(STR + blkfile + STR + f); if (!blkfile.renameTo(f)) { if (!f.delete()) { throw new IOException(STR + b + STR + STR + f); } if (!blkfile.renameTo(f)) { throw new IOException(STR + b + STR + STR + blkfile + STR + f); } } } if (f == null) { DataNode.LOG.warn(STR + b + STR + STR); throw new IOException(STR + b + STR + STR); } if (replicationRequest) { volumeMap.put(b, new DatanodeBlockInfo(v)); } else { volumeMap.put(b, new DatanodeBlockInfo(v, f)); } ongoingCreates.put(b, new ActiveFile(f, threads)); } try { if (threads != null) { for (Thread thread:threads) { thread.join(); } } } catch (InterruptedException e) { throw new IOException(STR); } DataNode.LOG.debug(STR + f + STR + f.length()); DataNode.LOG.debug(STR + metafile + STR + metafile.length()); return createBlockWriteStreams( f , metafile); }
/** * Start writing to a block file * If isRecovery is true and the block pre-exists, then we kill all volumeMap.put(b, v); volumeMap.put(b, v); * other threads that might be writing to this block, and then reopen the file. * If replicationRequest is true, then this operation is part of a block * replication request. */
Start writing to a block file If isRecovery is true and the block pre-exists, then we kill all other threads that might be writing to this block, and then reopen the file. If replicationRequest is true, then this operation is part of a block replication request
writeToBlock
{ "repo_name": "ryanobjc/hadoop-cloudera", "path": "src/hdfs/org/apache/hadoop/hdfs/server/datanode/FSDataset.java", "license": "apache-2.0", "size": 63084 }
[ "java.io.File", "java.io.IOException", "java.util.List", "org.apache.hadoop.hdfs.protocol.Block" ]
import java.io.File; import java.io.IOException; import java.util.List; import org.apache.hadoop.hdfs.protocol.Block;
import java.io.*; import java.util.*; import org.apache.hadoop.hdfs.protocol.*;
[ "java.io", "java.util", "org.apache.hadoop" ]
java.io; java.util; org.apache.hadoop;
538,405
public static <K, V> HashMap<K, V> newHashMap(int expSize) { return new HashMap<>(capacity(expSize)); }
static <K, V> HashMap<K, V> function(int expSize) { return new HashMap<>(capacity(expSize)); }
/** * Creates new {@link HashMap} with expected size. * * @param expSize Expected size of created map. * @param <K> Type of map keys. * @param <V> Type of map values. * @return New map. */
Creates new <code>HashMap</code> with expected size
newHashMap
{ "repo_name": "ascherbakoff/ignite", "path": "modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java", "license": "apache-2.0", "size": 385578 }
[ "java.util.HashMap" ]
import java.util.HashMap;
import java.util.*;
[ "java.util" ]
java.util;
2,273,711
public static void writeFloat(float num, ByteBuffer buf) { writeInt(Float.floatToIntBits(num), buf); }
static void function(float num, ByteBuffer buf) { writeInt(Float.floatToIntBits(num), buf); }
/** * Writes a float to a ByteBuffer * @param num the float to be written * @param buf the buffer */
Writes a float to a ByteBuffer
writeFloat
{ "repo_name": "dimbleby/JGroups", "path": "src/org/jgroups/util/Bits.java", "license": "apache-2.0", "size": 26132 }
[ "java.nio.ByteBuffer" ]
import java.nio.ByteBuffer;
import java.nio.*;
[ "java.nio" ]
java.nio;
2,013,909
// find all channels in the workspace ChannelsListResponse channelsResponse = slack.methods().channelsList(ChannelsListRequest.builder().token(token).build()); // find channelName Channel chann = channelsResponse.getChannels().stream() .filter(c -> c.getName().equals(channelName)).findFirst().get(); // https://slack.com/api/chat.postMessage ChatPostMessageResponse postResponse = slack.methods().chatPostMessage(ChatPostMessageRequest.builder() .token(token) .channel(chann.getId()) .username("syndesis-bot") .text(message) .build()); return postResponse; }
ChannelsListResponse channelsResponse = slack.methods().channelsList(ChannelsListRequest.builder().token(token).build()); Channel chann = channelsResponse.getChannels().stream() .filter(c -> c.getName().equals(channelName)).findFirst().get(); ChatPostMessageResponse postResponse = slack.methods().chatPostMessage(ChatPostMessageRequest.builder() .token(token) .channel(chann.getId()) .username(STR) .text(message) .build()); return postResponse; }
/** * Send message to specified channel. * * Note that Slack QE credentials must have "Token" property correctly set up for desired workspace. * * @param message * @param channelName * @return * @throws IOException * @throws SlackApiException * @throws InterruptedException */
Send message to specified channel. Note that Slack QE credentials must have "Token" property correctly set up for desired workspace
sendMessage
{ "repo_name": "mcada/syndesis-qe", "path": "utilities/src/main/java/io/syndesis/qe/utils/SlackConnector.java", "license": "apache-2.0", "size": 4845 }
[ "com.github.seratch.jslack.api.methods.request.channels.ChannelsListRequest", "com.github.seratch.jslack.api.methods.request.chat.ChatPostMessageRequest", "com.github.seratch.jslack.api.methods.response.channels.ChannelsListResponse", "com.github.seratch.jslack.api.methods.response.chat.ChatPostMessageResponse", "com.github.seratch.jslack.api.model.Channel" ]
import com.github.seratch.jslack.api.methods.request.channels.ChannelsListRequest; import com.github.seratch.jslack.api.methods.request.chat.ChatPostMessageRequest; import com.github.seratch.jslack.api.methods.response.channels.ChannelsListResponse; import com.github.seratch.jslack.api.methods.response.chat.ChatPostMessageResponse; import com.github.seratch.jslack.api.model.Channel;
import com.github.seratch.jslack.api.methods.request.channels.*; import com.github.seratch.jslack.api.methods.request.chat.*; import com.github.seratch.jslack.api.methods.response.channels.*; import com.github.seratch.jslack.api.methods.response.chat.*; import com.github.seratch.jslack.api.model.*;
[ "com.github.seratch" ]
com.github.seratch;
2,678,136
private void copyIntersection(MDLSection section, String subSectionName, StateflowTransition transition) { MDLSection subSection = section.getFirstSubSection(subSectionName); transition.setParameter(subSectionName + "_" + PARAM_intersection, subSection.getParameter(PARAM_intersection)); }
void function(MDLSection section, String subSectionName, StateflowTransition transition) { MDLSection subSection = section.getFirstSubSection(subSectionName); transition.setParameter(subSectionName + "_" + PARAM_intersection, subSection.getParameter(PARAM_intersection)); }
/** * Copies the intersection parameter from the src/dst section to the * transition (using src/dst prefix). */
Copies the intersection parameter from the src/dst section to the transition (using src/dst prefix)
copyIntersection
{ "repo_name": "vimaier/conqat", "path": "org.conqat.engine.simulink/external/simulink-src/org/conqat/lib/simulink/builder/StateflowBuilder.java", "license": "apache-2.0", "size": 15574 }
[ "org.conqat.lib.simulink.model.stateflow.StateflowTransition" ]
import org.conqat.lib.simulink.model.stateflow.StateflowTransition;
import org.conqat.lib.simulink.model.stateflow.*;
[ "org.conqat.lib" ]
org.conqat.lib;
2,867,541
public static void addChannelPerm(User user, Long cid, String role) { //first figure out if this channel is visible by the user's org boolean permittedAction = false; Iterator<Channel> channels = user.getOrg().getAccessibleChannels().iterator(); while (!permittedAction && channels.hasNext()) { if ((channels.next()).getId().equals(cid)) { permittedAction = true; } } //now perform the action if (permittedAction) { user.getOrg().resetChannelPermissions(user.getId(), cid, role); } }
static void function(User user, Long cid, String role) { boolean permittedAction = false; Iterator<Channel> channels = user.getOrg().getAccessibleChannels().iterator(); while (!permittedAction && channels.hasNext()) { if ((channels.next()).getId().equals(cid)) { permittedAction = true; } } if (permittedAction) { user.getOrg().resetChannelPermissions(user.getId(), cid, role); } }
/** * Adds channel permissions from a user. * Does nothing if the channel cannot be viewed by this user's org * @param user The user for which the perm is changing * @param cid The channel identifier * @param role The role the user is gaining for this channel. */
Adds channel permissions from a user. Does nothing if the channel cannot be viewed by this user's org
addChannelPerm
{ "repo_name": "xkollar/spacewalk", "path": "java/code/src/com/redhat/rhn/manager/user/UserManager.java", "license": "gpl-2.0", "size": 42980 }
[ "com.redhat.rhn.domain.channel.Channel", "com.redhat.rhn.domain.user.User", "java.util.Iterator" ]
import com.redhat.rhn.domain.channel.Channel; import com.redhat.rhn.domain.user.User; import java.util.Iterator;
import com.redhat.rhn.domain.channel.*; import com.redhat.rhn.domain.user.*; import java.util.*;
[ "com.redhat.rhn", "java.util" ]
com.redhat.rhn; java.util;
287,018
@Override public Header authenticate( final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException { Args.notNull(credentials, "Credentials"); Args.notNull(request, "HTTP request"); final StringBuilder tmp = new StringBuilder(); tmp.append(credentials.getUserPrincipal().getName()); tmp.append(":"); tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword()); final byte[] base64password = Base64.decode( EncodingUtils.getBytes(tmp.toString(), getCredentialsCharset(request)), Base64.NO_WRAP); final CharArrayBuffer buffer = new CharArrayBuffer(32); if (isProxy()) { buffer.append(AUTH.PROXY_AUTH_RESP); } else { buffer.append(AUTH.WWW_AUTH_RESP); } buffer.append(": Basic "); buffer.append(base64password, 0, base64password.length); return new BufferedHeader(buffer); }
Header function( final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException { Args.notNull(credentials, STR); Args.notNull(request, STR); final StringBuilder tmp = new StringBuilder(); tmp.append(credentials.getUserPrincipal().getName()); tmp.append(":"); tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword()); final byte[] base64password = Base64.decode( EncodingUtils.getBytes(tmp.toString(), getCredentialsCharset(request)), Base64.NO_WRAP); final CharArrayBuffer buffer = new CharArrayBuffer(32); if (isProxy()) { buffer.append(AUTH.PROXY_AUTH_RESP); } else { buffer.append(AUTH.WWW_AUTH_RESP); } buffer.append(STR); buffer.append(base64password, 0, base64password.length); return new BufferedHeader(buffer); }
/** * Produces basic authorization header for the given set of {@link Credentials}. * * @param credentials The set of credentials to be used for authentication * @param request The request being authenticated * @throws org.apache.http.auth.InvalidCredentialsException if authentication * credentials are not valid or not applicable for this authentication scheme * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return a basic authorization string */
Produces basic authorization header for the given set of <code>Credentials</code>
authenticate
{ "repo_name": "SxdsF/Visit", "path": "src/org/apache/http/impl/auth/BasicSchemeHC4.java", "license": "apache-2.0", "size": 7270 }
[ "android.util.Base64", "org.apache.http.Header", "org.apache.http.HttpRequest", "org.apache.http.auth.AuthenticationException", "org.apache.http.auth.Credentials", "org.apache.http.message.BufferedHeader", "org.apache.http.protocol.HttpContext", "org.apache.http.util.Args", "org.apache.http.util.CharArrayBuffer", "org.apache.http.util.EncodingUtils" ]
import android.util.Base64; import org.apache.http.Header; import org.apache.http.HttpRequest; import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.Credentials; import org.apache.http.message.BufferedHeader; import org.apache.http.protocol.HttpContext; import org.apache.http.util.Args; import org.apache.http.util.CharArrayBuffer; import org.apache.http.util.EncodingUtils;
import android.util.*; import org.apache.http.*; import org.apache.http.auth.*; import org.apache.http.message.*; import org.apache.http.protocol.*; import org.apache.http.util.*;
[ "android.util", "org.apache.http" ]
android.util; org.apache.http;
605,447
public static java.util.List extractPatientICPActionList(ims.domain.ILightweightDomainFactory domainFactory, ims.icp.vo.PatientICPActionLiteVoCollection voCollection) { return extractPatientICPActionList(domainFactory, voCollection, null, new HashMap()); }
static java.util.List function(ims.domain.ILightweightDomainFactory domainFactory, ims.icp.vo.PatientICPActionLiteVoCollection voCollection) { return extractPatientICPActionList(domainFactory, voCollection, null, new HashMap()); }
/** * Create the ims.icps.instantiation.domain.objects.PatientICPAction list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */
Create the ims.icps.instantiation.domain.objects.PatientICPAction list from the value object collection
extractPatientICPActionList
{ "repo_name": "open-health-hub/openmaxims-linux", "path": "openmaxims_workspace/ValueObjects/src/ims/icp/vo/domain/PatientICPActionLiteVoAssembler.java", "license": "agpl-3.0", "size": 18097 }
[ "java.util.HashMap" ]
import java.util.HashMap;
import java.util.*;
[ "java.util" ]
java.util;
1,845,397
@VisibleForTesting Predicate get(String name) { return constraints.get(name); }
Predicate get(String name) { return constraints.get(name); }
/** * Returns the predicate for a named field. * * For testing. * * @param name a String field name * @return a Predicate for the given field, or null if none is set */
Returns the predicate for a named field. For testing
get
{ "repo_name": "EdwardSkoviak/kite", "path": "kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/Constraints.java", "license": "apache-2.0", "size": 28300 }
[ "com.google.common.base.Predicate" ]
import com.google.common.base.Predicate;
import com.google.common.base.*;
[ "com.google.common" ]
com.google.common;
1,487,235
public void setCurrentDir(File dir) { mCurrentDir = dir; refresh(); }
void function(File dir) { mCurrentDir = dir; refresh(); }
/** * Changes the currently active directory */
Changes the currently active directory
setCurrentDir
{ "repo_name": "xbao/vanilla", "path": "src/ch/blinkenlights/android/vanilla/FolderPickerAdapter.java", "license": "gpl-3.0", "size": 5347 }
[ "java.io.File" ]
import java.io.File;
import java.io.*;
[ "java.io" ]
java.io;
502,620
public MetaProperty<RiskLevel> riskLevel() { return riskLevel; }
MetaProperty<RiskLevel> function() { return riskLevel; }
/** * The meta-property for the {@code riskLevel} property. * @return the meta-property, not null */
The meta-property for the riskLevel property
riskLevel
{ "repo_name": "fengshao0907/joda-beans", "path": "src/test/java/org/joda/beans/gen/ImmAddress.java", "license": "apache-2.0", "size": 61491 }
[ "org.joda.beans.MetaProperty" ]
import org.joda.beans.MetaProperty;
import org.joda.beans.*;
[ "org.joda.beans" ]
org.joda.beans;
949,528
@Test public void checkCastShouldReturnCorrectlyWhenTargetObjectIsNotNullAndCanBeTypeCasted() { Object stringCastTarget = "SomeCharacters"; Object stringCastResult = TypeUtils.checkCast(stringCastTarget, String.class); assertThat(stringCastResult).isNotNull(); assertThat(stringCastResult).isInstanceOf(String.class); assertThat(stringCastResult).isSameAs(stringCastTarget); Object integerCastTarget = 20; Object integerCastResult = TypeUtils.checkCast(integerCastTarget, Integer.class); assertThat(integerCastResult).isNotNull(); assertThat(integerCastResult).isInstanceOf(Integer.class); assertThat(integerCastResult).isSameAs(integerCastResult); Object numberCastResult = TypeUtils.checkCast(integerCastTarget, Number.class); assertThat(numberCastResult).isNotNull(); assertThat(numberCastResult).isInstanceOf(Integer.class); assertThat(numberCastResult).isSameAs(numberCastResult); }
void function() { Object stringCastTarget = STR; Object stringCastResult = TypeUtils.checkCast(stringCastTarget, String.class); assertThat(stringCastResult).isNotNull(); assertThat(stringCastResult).isInstanceOf(String.class); assertThat(stringCastResult).isSameAs(stringCastTarget); Object integerCastTarget = 20; Object integerCastResult = TypeUtils.checkCast(integerCastTarget, Integer.class); assertThat(integerCastResult).isNotNull(); assertThat(integerCastResult).isInstanceOf(Integer.class); assertThat(integerCastResult).isSameAs(integerCastResult); Object numberCastResult = TypeUtils.checkCast(integerCastTarget, Number.class); assertThat(numberCastResult).isNotNull(); assertThat(numberCastResult).isInstanceOf(Integer.class); assertThat(numberCastResult).isSameAs(numberCastResult); }
/** * Can't test every possible combination, so try a few ones. */
Can't test every possible combination, so try a few ones
checkCastShouldReturnCorrectlyWhenTargetObjectIsNotNullAndCanBeTypeCasted
{ "repo_name": "jdeppe-pivotal/geode", "path": "geode-core/src/test/java/org/apache/geode/cache/query/internal/types/TypeUtilsJUnitTest.java", "license": "apache-2.0", "size": 49398 }
[ "org.assertj.core.api.Assertions" ]
import org.assertj.core.api.Assertions;
import org.assertj.core.api.*;
[ "org.assertj.core" ]
org.assertj.core;
745,816
public void start() { if (state == State.READY) { if (rUncompressed) { payloadSize = 0; audioRecorder.startRecording(); audioRecorder.read(buffer, 0, buffer.length); } else { mediaRecorder.start(); } state = State.RECORDING; } else { Log.e(Recorder.class.getName(), "start() called on illegal state"); state = State.ERROR; } }
void function() { if (state == State.READY) { if (rUncompressed) { payloadSize = 0; audioRecorder.startRecording(); audioRecorder.read(buffer, 0, buffer.length); } else { mediaRecorder.start(); } state = State.RECORDING; } else { Log.e(Recorder.class.getName(), STR); state = State.ERROR; } }
/** * * * Starts the recording, and sets the state to RECORDING. * Call after prepare(). * */
Starts the recording, and sets the state to RECORDING. Call after prepare()
start
{ "repo_name": "yoowonyoung/IoD", "path": "App/DoggyWare/app/src/main/java/iod/app/mobile/tools/Recorder.java", "license": "apache-2.0", "size": 17852 }
[ "android.util.Log" ]
import android.util.Log;
import android.util.*;
[ "android.util" ]
android.util;
576,790
protected void resetLoginTimeCountdown() throws SocketException { if (this.loginTimeoutCountdown > 0) { long now = System.currentTimeMillis(); this.loginTimeoutCountdown -= now - this.loginTimeoutCheckTimestamp; if (this.loginTimeoutCountdown <= 0) { throw new SocketException(Messages.getString("Connection.LoginTimeout")); } this.loginTimeoutCheckTimestamp = now; } }
void function() throws SocketException { if (this.loginTimeoutCountdown > 0) { long now = System.currentTimeMillis(); this.loginTimeoutCountdown -= now - this.loginTimeoutCheckTimestamp; if (this.loginTimeoutCountdown <= 0) { throw new SocketException(Messages.getString(STR)); } this.loginTimeoutCheckTimestamp = now; } }
/** * Decrements elapsed time since last reset from login timeout count down. * * @throws SocketException * If the login timeout is reached or exceeded. */
Decrements elapsed time since last reset from login timeout count down
resetLoginTimeCountdown
{ "repo_name": "hansmeets/bio2rdf-scripts", "path": "linkedSPLs/LinkedSPLs-update/lib/mysql-connector-java-5.1.33/src/com/mysql/jdbc/StandardSocketFactory.java", "license": "mit", "size": 18378 }
[ "java.net.SocketException" ]
import java.net.SocketException;
import java.net.*;
[ "java.net" ]
java.net;
627,836
public void wipeGraph() { graph = new JGraph(); model = new DefaultGraphModel(); graphElements = new Hashtable(); lastY = SEQ_START_DISTANCE_Y; lastX = SEQ_START_DISTANCE_X; graphPath = new Vector(); nodes = new Vector(); nodesInvisible = new Hashtable(); graph.setModel(model); graph.setGraphLayoutCache(new GraphLayoutCache(model, new DefaultCellViewFactory(), true)); }
void function() { graph = new JGraph(); model = new DefaultGraphModel(); graphElements = new Hashtable(); lastY = SEQ_START_DISTANCE_Y; lastX = SEQ_START_DISTANCE_X; graphPath = new Vector(); nodes = new Vector(); nodesInvisible = new Hashtable(); graph.setModel(model); graph.setGraphLayoutCache(new GraphLayoutCache(model, new DefaultCellViewFactory(), true)); }
/** * Cleans the graph by creating a new graph object and by resetting * status information like graphPath and graphElements. */
Cleans the graph by creating a new graph object and by resetting status information like graphPath and graphElements
wipeGraph
{ "repo_name": "elitak/peertrust", "path": "sandbox/TomcatPeerTrust/src/org/peertrust/demo/client/applet/TestSequenceDiagramm.java", "license": "gpl-2.0", "size": 27233 }
[ "java.util.Hashtable", "java.util.Vector", "org.jgraph.JGraph", "org.jgraph.graph.DefaultCellViewFactory", "org.jgraph.graph.DefaultGraphModel", "org.jgraph.graph.GraphLayoutCache" ]
import java.util.Hashtable; import java.util.Vector; import org.jgraph.JGraph; import org.jgraph.graph.DefaultCellViewFactory; import org.jgraph.graph.DefaultGraphModel; import org.jgraph.graph.GraphLayoutCache;
import java.util.*; import org.jgraph.*; import org.jgraph.graph.*;
[ "java.util", "org.jgraph", "org.jgraph.graph" ]
java.util; org.jgraph; org.jgraph.graph;
2,284,675
@Test public void testpathComputationCase15() { Link link1 = addLink(DEVICE1, 10, DEVICE2, 20, false, 50); Link link2 = addLink(DEVICE2, 30, DEVICE4, 40, false, 20); Link link3 = addLink(DEVICE1, 80, DEVICE3, 70, false, 100); Link link4 = addLink(DEVICE3, 60, DEVICE4, 50, false, 80); List<Constraint> constraints = null; Set<Path> paths = computePath(link1, link2, link3, link4, constraints); assertThat(paths.iterator().next().cost(), is((double) 2)); }
void function() { Link link1 = addLink(DEVICE1, 10, DEVICE2, 20, false, 50); Link link2 = addLink(DEVICE2, 30, DEVICE4, 40, false, 20); Link link3 = addLink(DEVICE1, 80, DEVICE3, 70, false, 100); Link link4 = addLink(DEVICE3, 60, DEVICE4, 50, false, 80); List<Constraint> constraints = null; Set<Path> paths = computePath(link1, link2, link3, link4, constraints); assertThat(paths.iterator().next().cost(), is((double) 2)); }
/** * Test case with constraints as null. */
Test case with constraints as null
testpathComputationCase15
{ "repo_name": "sdnwiselab/onos", "path": "apps/pce/app/src/test/java/org/onosproject/pce/pceservice/PathComputationTest.java", "license": "apache-2.0", "size": 57603 }
[ "java.util.List", "java.util.Set", "org.hamcrest.MatcherAssert", "org.hamcrest.core.Is", "org.onosproject.net.Link", "org.onosproject.net.Path", "org.onosproject.net.intent.Constraint" ]
import java.util.List; import java.util.Set; import org.hamcrest.MatcherAssert; import org.hamcrest.core.Is; import org.onosproject.net.Link; import org.onosproject.net.Path; import org.onosproject.net.intent.Constraint;
import java.util.*; import org.hamcrest.*; import org.hamcrest.core.*; import org.onosproject.net.*; import org.onosproject.net.intent.*;
[ "java.util", "org.hamcrest", "org.hamcrest.core", "org.onosproject.net" ]
java.util; org.hamcrest; org.hamcrest.core; org.onosproject.net;
889,530
private static Collection getImport(String fullClassName) { Collection result; boolean generic; int openAngleIndex; String unwrappedClassName; String[] multiValueGeneric; result = new ArrayList(); if (StringUtil.isSet(fullClassName)) { openAngleIndex = fullClassName.indexOf('<'); if(openAngleIndex > -1) { //get front result.add(fullClassName.substring(0, openAngleIndex)); //unwrap unwrappedClassName = fullClassName.substring(openAngleIndex+1, fullClassName.lastIndexOf('>')); // split multivalue generic e.g. Map<X,Y> multiValueGeneric = unwrappedClassName.split(","); for (String className : multiValueGeneric) { result.addAll(getImport(className.trim())); } } // if fully qualified else if (fullClassName.contains(".")) { result.add(fullClassName); } } return result; }
static Collection function(String fullClassName) { Collection result; boolean generic; int openAngleIndex; String unwrappedClassName; String[] multiValueGeneric; result = new ArrayList(); if (StringUtil.isSet(fullClassName)) { openAngleIndex = fullClassName.indexOf('<'); if(openAngleIndex > -1) { result.add(fullClassName.substring(0, openAngleIndex)); unwrappedClassName = fullClassName.substring(openAngleIndex+1, fullClassName.lastIndexOf('>')); multiValueGeneric = unwrappedClassName.split(","); for (String className : multiValueGeneric) { result.addAll(getImport(className.trim())); } } else if (fullClassName.contains(".")) { result.add(fullClassName); } } return result; }
/** * Filters the supplied type into a class import. * <p> * If no import is needed for the class i.e. no package is specified or the * specified package is java.lang null is returned. * * @param fullClassName * an objects fully qualified class name. * @return the import statement portion of the class name or null. */
Filters the supplied type into a class import. If no import is needed for the class i.e. no package is specified or the specified package is java.lang null is returned
getImport
{ "repo_name": "justinrknowles/toshookan", "path": "src/main/java/toshookan/domainmodel/VelocityDomainModelCodeGenerator.java", "license": "apache-2.0", "size": 16799 }
[ "java.util.ArrayList", "java.util.Collection" ]
import java.util.ArrayList; import java.util.Collection;
import java.util.*;
[ "java.util" ]
java.util;
1,000,774
public Bitmap getFavicon() { throw new MustOverrideException(); }
Bitmap function() { throw new MustOverrideException(); }
/** * Return the favicon of this history item or null if no favicon was found. * @return A Bitmap containing the favicon for this history item or null. * Note: The VM ensures 32-bit atomic read/write operations so we don't have * to synchronize this method. */
Return the favicon of this history item or null if no favicon was found
getFavicon
{ "repo_name": "yuzaipiaofei/chromium_webview", "path": "java/src/com/mogoweb/chrome/WebHistoryItem.java", "license": "bsd-3-clause", "size": 3372 }
[ "android.graphics.Bitmap" ]
import android.graphics.Bitmap;
import android.graphics.*;
[ "android.graphics" ]
android.graphics;
2,792,358
private static <T, F> FieldAugment<T, F> tryCreateReflectionAugment(Class<T> type, Class<? super F> fieldType, String name, F defaultValue) { Field f = findField(type, fieldType, name); if (f != null && typeIsAssignmentCompatible(f.getType(), fieldType)) return new ReflectionFieldAugment<T, F>(f, fieldType, defaultValue); return null; }
static <T, F> FieldAugment<T, F> function(Class<T> type, Class<? super F> fieldType, String name, F defaultValue) { Field f = findField(type, fieldType, name); if (f != null && typeIsAssignmentCompatible(f.getType(), fieldType)) return new ReflectionFieldAugment<T, F>(f, fieldType, defaultValue); return null; }
/** * Creates a reflection-based augment which will directly access the listed field name. If this field does not exist or the field * is not capable of storing the requested type, {@code null} is returned instead. */
Creates a reflection-based augment which will directly access the listed field name. If this field does not exist or the field is not capable of storing the requested type, null is returned instead
tryCreateReflectionAugment
{ "repo_name": "riccardobl/lombok", "path": "src/utils/lombok/core/FieldAugment.java", "license": "mit", "size": 13467 }
[ "java.lang.reflect.Field" ]
import java.lang.reflect.Field;
import java.lang.reflect.*;
[ "java.lang" ]
java.lang;
135,012
public static Integer getMnemonicPosition(String key) { String value = null; try { value = msg.getString(key); } catch (MissingResourceException e) { return null; } int amp = value.indexOf('&'); if (amp == -1 || amp == value.length() - 1) return null; return amp; } // the resource bundle to use private final static ResourceBundle msg; static { ResourceBundle bundle; try { // Grab overriding language prefs if available String country = App.prefs.getPref(PrefKey.LOCALE_COUNTRY_CODE, "xxx"); String language = App.prefs.getPref(PrefKey.LOCALE_LANGUAGE_CODE, "xxx"); if (country.equals("xxx") || language.equals("xxx")) { // No prefs specified so just go with the default from the system bundle = ResourceBundle.getBundle("Translations/TextBundle"); } else { // Prefs specified so use these instead bundle = ResourceBundle.getBundle("Translations/TextBundle", new Locale(language, country)); } } catch (MissingResourceException mre) { try { bundle = ResourceBundle.getBundle("Translations/TextBundle"); } catch (MissingResourceException mre2) { log.error("Could not find locale file."); mre2.printStackTrace(); bundle = new ResourceBundle() { @Override protected Object handleGetObject(String key) { return key; } @Override public Enumeration<String> getKeys() { return EMPTY_ENUMERATION; } private final Enumeration<String> EMPTY_ENUMERATION = new Enumeration<String>() { @Override public boolean hasMoreElements() { return false; } @Override public String nextElement() { throw new NoSuchElementException(); } }; }; } } msg = bundle; }
static Integer function(String key) { String value = null; try { value = msg.getString(key); } catch (MissingResourceException e) { return null; } int amp = value.indexOf('&'); if (amp == -1 amp == value.length() - 1) return null; return amp; } private final static ResourceBundle msg; static { ResourceBundle bundle; try { String country = App.prefs.getPref(PrefKey.LOCALE_COUNTRY_CODE, "xxx"); String language = App.prefs.getPref(PrefKey.LOCALE_LANGUAGE_CODE, "xxx"); if (country.equals("xxx") language.equals("xxx")) { bundle = ResourceBundle.getBundle(STR); } else { bundle = ResourceBundle.getBundle(STR, new Locale(language, country)); } } catch (MissingResourceException mre) { try { bundle = ResourceBundle.getBundle(STR); } catch (MissingResourceException mre2) { log.error(STR); mre2.printStackTrace(); bundle = new ResourceBundle() { protected Object handleGetObject(String key) { return key; } public Enumeration<String> getKeys() { return EMPTY_ENUMERATION; } private final Enumeration<String> EMPTY_ENUMERATION = new Enumeration<String>() { public boolean hasMoreElements() { return false; } public String nextElement() { throw new NoSuchElementException(); } }; }; } } msg = bundle; }
/** * Get the position of the mnemonic character in the string Used for setDisplayedMnemonicIndex * * @param key * @return an Integer, or null */
Get the position of the mnemonic character in the string Used for setDisplayedMnemonicIndex
getMnemonicPosition
{ "repo_name": "petebrew/fhaes", "path": "FHUtil/src/main/java/org/fhaes/util/I18n.java", "license": "gpl-3.0", "size": 15156 }
[ "java.util.Enumeration", "java.util.Locale", "java.util.MissingResourceException", "java.util.NoSuchElementException", "java.util.ResourceBundle", "org.fhaes.preferences.App", "org.fhaes.preferences.FHAESPreferences" ]
import java.util.Enumeration; import java.util.Locale; import java.util.MissingResourceException; import java.util.NoSuchElementException; import java.util.ResourceBundle; import org.fhaes.preferences.App; import org.fhaes.preferences.FHAESPreferences;
import java.util.*; import org.fhaes.preferences.*;
[ "java.util", "org.fhaes.preferences" ]
java.util; org.fhaes.preferences;
1,822,494
@SuppressWarnings("WeakerAccess") @Nullable public List<Migration> findMigrationPath(int start, int end) { if (start == end) { return Collections.emptyList(); } boolean migrateUp = end > start; List<Migration> result = new ArrayList<>(); return findUpMigrationPath(result, migrateUp, start, end); }
@SuppressWarnings(STR) List<Migration> function(int start, int end) { if (start == end) { return Collections.emptyList(); } boolean migrateUp = end > start; List<Migration> result = new ArrayList<>(); return findUpMigrationPath(result, migrateUp, start, end); }
/** * Finds the list of migrations that should be run to move from {@code start} version to * {@code end} version. * * @param start The current database version * @param end The target database version * @return An ordered list of {@link Migration} objects that should be run to migrate * between the given versions. If a migration path cannot be found, returns {@code null}. */
Finds the list of migrations that should be run to move from start version to end version
findMigrationPath
{ "repo_name": "aosp-mirror/platform_frameworks_support", "path": "room/runtime/src/main/java/androidx/room/RoomDatabase.java", "license": "apache-2.0", "size": 28028 }
[ "androidx.room.migration.Migration", "java.util.ArrayList", "java.util.Collections", "java.util.List" ]
import androidx.room.migration.Migration; import java.util.ArrayList; import java.util.Collections; import java.util.List;
import androidx.room.migration.*; import java.util.*;
[ "androidx.room", "java.util" ]
androidx.room; java.util;
831,901
public void pauseWork() { mExitTasksEarly = false; setPause(true); if (DEBUG) { CLog.d(LOG_TAG, "work_status: pauseWork %s", this); } }
void function() { mExitTasksEarly = false; setPause(true); if (DEBUG) { CLog.d(LOG_TAG, STR, this); } }
/** * Temporarily hand up work, you can call this when the view is scrolling. */
Temporarily hand up work, you can call this when the view is scrolling
pauseWork
{ "repo_name": "muxiaolin/cube-sdk-dev", "path": "core/src/in/srain/cube/image/ImageLoader.java", "license": "apache-2.0", "size": 17447 }
[ "in.srain.cube.util.CLog" ]
import in.srain.cube.util.CLog;
import in.srain.cube.util.*;
[ "in.srain.cube" ]
in.srain.cube;
1,748,828
public Model<?> getModel() { return this.model; }
Model<?> function() { return this.model; }
/** * Gets the value for the model field. * * @return The value for the model field. */
Gets the value for the model field
getModel
{ "repo_name": "lunarray-org/model-ext-guice", "path": "src/main/java/org/lunarray/model/descriptor/registry/guice/ModelProvider.java", "license": "lgpl-3.0", "size": 2360 }
[ "org.lunarray.model.descriptor.model.Model" ]
import org.lunarray.model.descriptor.model.Model;
import org.lunarray.model.descriptor.model.*;
[ "org.lunarray.model" ]
org.lunarray.model;
2,118,082
public AdvancedKVExtractionView getAdvancedKVExtractionView() { return advancedKVExtractionView; }
AdvancedKVExtractionView function() { return advancedKVExtractionView; }
/** * To get Advanced KV Extraction View. * * @return AdvancedKVExtractionView */
To get Advanced KV Extraction View
getAdvancedKVExtractionView
{ "repo_name": "kuzavas/ephesoft", "path": "dcma-gwt/dcma-gwt-admin/src/main/java/com/ephesoft/dcma/gwt/admin/bm/client/view/BatchClassManagementView.java", "license": "agpl-3.0", "size": 33774 }
[ "com.ephesoft.dcma.gwt.admin.bm.client.view.kvextraction.advancedkvextraction.AdvancedKVExtractionView" ]
import com.ephesoft.dcma.gwt.admin.bm.client.view.kvextraction.advancedkvextraction.AdvancedKVExtractionView;
import com.ephesoft.dcma.gwt.admin.bm.client.view.kvextraction.advancedkvextraction.*;
[ "com.ephesoft.dcma" ]
com.ephesoft.dcma;
624,099
public void addExtraPropertyAnnotations(PrismPropertyDefinition definition, Element appinfo, SchemaToDomProcessor schemaToDomProcessor) { // Nothing to do by default }
void function(PrismPropertyDefinition definition, Element appinfo, SchemaToDomProcessor schemaToDomProcessor) { }
/** * Add extra annotations to a property DOM model. Used when serializing schema to DOM. */
Add extra annotations to a property DOM model. Used when serializing schema to DOM
addExtraPropertyAnnotations
{ "repo_name": "rpudil/midpoint", "path": "infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaDefinitionFactory.java", "license": "apache-2.0", "size": 5375 }
[ "com.evolveum.midpoint.prism.PrismPropertyDefinition", "org.w3c.dom.Element" ]
import com.evolveum.midpoint.prism.PrismPropertyDefinition; import org.w3c.dom.Element;
import com.evolveum.midpoint.prism.*; import org.w3c.dom.*;
[ "com.evolveum.midpoint", "org.w3c.dom" ]
com.evolveum.midpoint; org.w3c.dom;
1,471,317
public int getTokenCount(String targetString) { // The \w represents a "word" charactor String expression = "(\\$\\{\\w+\\})"; Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(targetString); log().debug("getTokenCount: processing string: "+targetString); int count = 0; while (matcher.find()) { count++; log().debug("getTokenCount: Token "+count+": "+matcher.group(1)); } return count; }
int function(String targetString) { String expression = STR; Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(targetString); log().debug(STR+targetString); int count = 0; while (matcher.find()) { count++; log().debug(STR+count+STR+matcher.group(1)); } return count; }
/** * Counts the number of tokens in an Action Statement. * @param targetString * @return */
Counts the number of tokens in an Action Statement
getTokenCount
{ "repo_name": "vishwaAbhinav/OpenNMS", "path": "opennms-services/src/main/java/org/opennms/netmgt/vacuumd/AutomationProcessor.java", "license": "gpl-2.0", "size": 29684 }
[ "java.util.regex.Matcher", "java.util.regex.Pattern" ]
import java.util.regex.Matcher; import java.util.regex.Pattern;
import java.util.regex.*;
[ "java.util" ]
java.util;
785,860
private void setThrowable(Throwable throwable) { if ( throwable instanceof SqlException ) { setNextException((SqlException) throwable); } else if ( throwable instanceof SQLException ) { setNextException((SQLException) throwable ); } if (throwable != null) { initCause(throwable); } } public SqlException(SQLException wrapme) { wrappedException_ = wrapme; }
void function(Throwable throwable) { if ( throwable instanceof SqlException ) { setNextException((SqlException) throwable); } else if ( throwable instanceof SQLException ) { setNextException((SQLException) throwable ); } if (throwable != null) { initCause(throwable); } } public SqlException(SQLException wrapme) { wrappedException_ = wrapme; }
/** * Set the cause of this exception based on its type. * <code>SQLException</code>s and <code>SqlException</code>s are * linked with <code>setNextException()</code> and <code>initCause()</code>. * All other exception types are linked with <code>initCause()</code>. */
Set the cause of this exception based on its type. <code>SQLException</code>s and <code>SqlException</code>s are linked with <code>setNextException()</code> and <code>initCause()</code>. All other exception types are linked with <code>initCause()</code>
setThrowable
{ "repo_name": "splicemachine/spliceengine", "path": "db-client/src/main/java/com/splicemachine/db/client/am/SqlException.java", "license": "agpl-3.0", "size": 21086 }
[ "java.sql.SQLException" ]
import java.sql.SQLException;
import java.sql.*;
[ "java.sql" ]
java.sql;
1,713,292
@Override public boolean visit(AnonymousClassDeclaration node) { return isNodeEnclosingMethod(node); }
boolean function(AnonymousClassDeclaration node) { return isNodeEnclosingMethod(node); }
/** * When an anonymous class declaration is reached, the traversal should not go further since it's not * supposed to consider calls inside the anonymous inner class as calls from the outer method. * * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.AnonymousClassDeclaration) */
When an anonymous class declaration is reached, the traversal should not go further since it's not supposed to consider calls inside the anonymous inner class as calls from the outer method
visit
{ "repo_name": "kumattau/JDTPatch", "path": "org.eclipse.jdt.ui/src/org/eclipse/jdt/internal/corext/callhierarchy/CalleeAnalyzerVisitor.java", "license": "epl-1.0", "size": 12792 }
[ "org.eclipse.jdt.core.dom.AnonymousClassDeclaration" ]
import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
import org.eclipse.jdt.core.dom.*;
[ "org.eclipse.jdt" ]
org.eclipse.jdt;
2,378,107
public Entity addIndicies(final int index) { if (indicies == null) { indicies = new TreeSet<>(); } indicies.add(index); return this; }
Entity function(final int index) { if (indicies == null) { indicies = new TreeSet<>(); } indicies.add(index); return this; }
/** * Adds start indices * * @param index * @return self */
Adds start indices
addIndicies
{ "repo_name": "renespeck/fox-java", "path": "src/main/java/org/aksw/fox/data/Entity.java", "license": "gpl-2.0", "size": 3397 }
[ "java.util.TreeSet" ]
import java.util.TreeSet;
import java.util.*;
[ "java.util" ]
java.util;
2,856,363
@JsonSetter(value = "references") protected void setReferences(final List<Reference> references) { // Protected since only Jackson should use it this.references = references; }
@JsonSetter(value = STR) void function(final List<Reference> references) { this.references = references; }
/** * Set the list of references where information about this item is published. * * @param references List of {@link Reference} objects with the references for this item. */
Set the list of references where information about this item is published
setReferences
{ "repo_name": "kjaym/jpif", "path": "src/main/java/io/citrine/jpif/obj/common/Rcl.java", "license": "apache-2.0", "size": 11519 }
[ "com.fasterxml.jackson.annotation.JsonSetter", "java.util.List" ]
import com.fasterxml.jackson.annotation.JsonSetter; import java.util.List;
import com.fasterxml.jackson.annotation.*; import java.util.*;
[ "com.fasterxml.jackson", "java.util" ]
com.fasterxml.jackson; java.util;
405,801
@GwtIncompatible("java.lang.Math.getExponent, io.trivium.dep.com.google.common.math.DoubleUtils") @SuppressWarnings("fallthrough") public static int log2(double x, RoundingMode mode) { checkArgument(x > 0.0 && isFinite(x), "x must be positive and finite"); int exponent = getExponent(x); if (!isNormal(x)) { return log2(x * IMPLICIT_BIT, mode) - SIGNIFICAND_BITS; // Do the calculation on a normal value. } // x is positive, finite, and normal boolean increment; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through case FLOOR: increment = false; break; case CEILING: increment = !isPowerOfTwo(x); break; case DOWN: increment = exponent < 0 & !isPowerOfTwo(x); break; case UP: increment = exponent >= 0 & !isPowerOfTwo(x); break; case HALF_DOWN: case HALF_EVEN: case HALF_UP: double xScaled = scaleNormalize(x); // sqrt(2) is irrational, and the spec is relative to the "exact numerical result," // so log2(x) is never exactly exponent + 0.5. increment = (xScaled * xScaled) > 2.0; break; default: throw new AssertionError(); } return increment ? exponent + 1 : exponent; }
@GwtIncompatible(STR) @SuppressWarnings(STR) static int function(double x, RoundingMode mode) { checkArgument(x > 0.0 && isFinite(x), STR); int exponent = getExponent(x); if (!isNormal(x)) { return log2(x * IMPLICIT_BIT, mode) - SIGNIFICAND_BITS; } boolean increment; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(isPowerOfTwo(x)); case FLOOR: increment = false; break; case CEILING: increment = !isPowerOfTwo(x); break; case DOWN: increment = exponent < 0 & !isPowerOfTwo(x); break; case UP: increment = exponent >= 0 & !isPowerOfTwo(x); break; case HALF_DOWN: case HALF_EVEN: case HALF_UP: double xScaled = scaleNormalize(x); increment = (xScaled * xScaled) > 2.0; break; default: throw new AssertionError(); } return increment ? exponent + 1 : exponent; }
/** * Returns the base 2 logarithm of a double value, rounded with the specified rounding mode to an * {@code int}. * * <p>Regardless of the rounding mode, this is faster than {@code (int) log2(x)}. * * @throws IllegalArgumentException if {@code x <= 0.0}, {@code x} is NaN, or {@code x} is * infinite */
Returns the base 2 logarithm of a double value, rounded with the specified rounding mode to an int. Regardless of the rounding mode, this is faster than (int) log2(x)
log2
{ "repo_name": "trivium-io/trivium-core", "path": "src/io/trivium/dep/com/google/common/math/DoubleMath.java", "license": "apache-2.0", "size": 18747 }
[ "io.trivium.dep.com.google.common.annotations.GwtIncompatible", "io.trivium.dep.com.google.common.base.Preconditions", "io.trivium.dep.com.google.common.math.DoubleUtils", "io.trivium.dep.com.google.common.math.MathPreconditions", "java.lang.Math", "java.math.RoundingMode" ]
import io.trivium.dep.com.google.common.annotations.GwtIncompatible; import io.trivium.dep.com.google.common.base.Preconditions; import io.trivium.dep.com.google.common.math.DoubleUtils; import io.trivium.dep.com.google.common.math.MathPreconditions; import java.lang.Math; import java.math.RoundingMode;
import io.trivium.dep.com.google.common.annotations.*; import io.trivium.dep.com.google.common.base.*; import io.trivium.dep.com.google.common.math.*; import java.lang.*; import java.math.*;
[ "io.trivium.dep", "java.lang", "java.math" ]
io.trivium.dep; java.lang; java.math;
499,274
String getExtendedRunState() throws IOException;
String getExtendedRunState() throws IOException;
/** * The extended run state of the service - this embeds more information but * is not designed for progamatic interpretation. */
The extended run state of the service - this embeds more information but is not designed for progamatic interpretation
getExtendedRunState
{ "repo_name": "rac021/blazegraph_1_5_3_cluster_2_nodes", "path": "bigdata/src/java/com/bigdata/ha/HAGlue.java", "license": "gpl-2.0", "size": 13598 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
278,459
public synchronized void curveTo(float x1, float y1, float x2, float y2, float x3, float y3) { checkMoveTo(); // check if prev command was moveto path.curveTo(x1, y1, x2, y2, x3, y3); makeRoom(6); types[numSeg++] = PathIterator.SEG_CUBICTO; values[numVals++] = x1; values[numVals++] = y1; values[numVals++] = x2; values[numVals++] = y2; cx = values[numVals++] = x3; cy = values[numVals++] = y3; }
synchronized void function(float x1, float y1, float x2, float y2, float x3, float y3) { checkMoveTo(); path.curveTo(x1, y1, x2, y2, x3, y3); makeRoom(6); types[numSeg++] = PathIterator.SEG_CUBICTO; values[numVals++] = x1; values[numVals++] = y1; values[numVals++] = x2; values[numVals++] = y2; cx = values[numVals++] = x3; cy = values[numVals++] = y3; }
/** * Delegates to the enclosed <code>GeneralPath</code>. */
Delegates to the enclosed <code>GeneralPath</code>
curveTo
{ "repo_name": "JanaWengenroth/GKA1", "path": "libraries/jgraphx/src/com/mxgraph/util/svg/ExtendedGeneralPath.java", "license": "gpl-2.0", "size": 19981 }
[ "java.awt.geom.PathIterator" ]
import java.awt.geom.PathIterator;
import java.awt.geom.*;
[ "java.awt" ]
java.awt;
662,515
public static MozuClient publishDocumentsClient(List<String> documentIds, String documentLists) throws Exception { MozuUrl url = com.mozu.api.urls.content.DocumentDraftSummaryUrl.publishDocumentsUrl(documentLists); String verb = "PUT"; MozuClient mozuClient = new MozuClient(); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.setBody(documentIds); return mozuClient; }
static MozuClient function(List<String> documentIds, String documentLists) throws Exception { MozuUrl url = com.mozu.api.urls.content.DocumentDraftSummaryUrl.publishDocumentsUrl(documentLists); String verb = "PUT"; MozuClient mozuClient = new MozuClient(); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.setBody(documentIds); return mozuClient; }
/** * Publish one or more document drafts to live content on the site. * <p><pre><code> * MozuClient mozuClient=PublishDocumentsClient( documentIds, documentLists); * client.setBaseAddress(url); * client.executeRequest(); * </code></pre></p> * @param documentLists List of document lists that contain documents to publish. * @param documentIds List of unique identifiers of the document drafts to publish. * @return Mozu.Api.MozuClient * @see string */
Publish one or more document drafts to live content on the site. <code><code> MozuClient mozuClient=PublishDocumentsClient( documentIds, documentLists); client.setBaseAddress(url); client.executeRequest(); </code></code>
publishDocumentsClient
{ "repo_name": "eileenzhuang1/mozu-java", "path": "mozu-java-core/src/main/java/com/mozu/api/clients/content/DocumentDraftSummaryClient.java", "license": "mit", "size": 6300 }
[ "com.mozu.api.MozuClient", "com.mozu.api.MozuUrl", "java.util.List" ]
import com.mozu.api.MozuClient; import com.mozu.api.MozuUrl; import java.util.List;
import com.mozu.api.*; import java.util.*;
[ "com.mozu.api", "java.util" ]
com.mozu.api; java.util;
2,616,422
// A small graph String[] graph = new String[] { "12 34 56", "34 78", "56 34 78", "78 34" }; GiraphConfiguration conf = new GiraphConfiguration(); conf.setInt(RandomWalkWithRestartVertex.SOURCE_VERTEX, 12); conf.setInt(RandomWalkWithRestartVertex.MAX_SUPERSTEPS, 30); conf.setFloat(RandomWalkWithRestartVertex.TELEPORTATION_PROBABILITY, 0.25f); conf.setVertexClass(RandomWalkWithRestartVertex.class); conf.setOutEdgesClass(ByteArrayEdges.class); conf.setVertexInputFormatClass(LongDoubleDoubleTextInputFormat.class); conf.setVertexOutputFormatClass( VertexWithDoubleValueDoubleEdgeTextOutputFormat.class); conf.setWorkerContextClass(RandomWalkWorkerContext.class); conf.setMasterComputeClass(RandomWalkVertexMasterCompute.class); // Run internally Iterable<String> results = InternalVertexRunner.run(conf, graph); Map<Long, Double> steadyStateProbabilities = RandomWalkTestUtils.parseSteadyStateProbabilities(results); // values computed with external software // 0.25, 0.354872, 0.09375, 0.301377 assertEquals(0.25, steadyStateProbabilities.get(12L), RandomWalkTestUtils.EPSILON); assertEquals(0.354872, steadyStateProbabilities.get(34L), RandomWalkTestUtils.EPSILON); assertEquals(0.09375, steadyStateProbabilities.get(56L), RandomWalkTestUtils.EPSILON); assertEquals(0.301377, steadyStateProbabilities.get(78L), RandomWalkTestUtils.EPSILON); }
String[] graph = new String[] { STR, STR, STR, STR }; GiraphConfiguration conf = new GiraphConfiguration(); conf.setInt(RandomWalkWithRestartVertex.SOURCE_VERTEX, 12); conf.setInt(RandomWalkWithRestartVertex.MAX_SUPERSTEPS, 30); conf.setFloat(RandomWalkWithRestartVertex.TELEPORTATION_PROBABILITY, 0.25f); conf.setVertexClass(RandomWalkWithRestartVertex.class); conf.setOutEdgesClass(ByteArrayEdges.class); conf.setVertexInputFormatClass(LongDoubleDoubleTextInputFormat.class); conf.setVertexOutputFormatClass( VertexWithDoubleValueDoubleEdgeTextOutputFormat.class); conf.setWorkerContextClass(RandomWalkWorkerContext.class); conf.setMasterComputeClass(RandomWalkVertexMasterCompute.class); Iterable<String> results = InternalVertexRunner.run(conf, graph); Map<Long, Double> steadyStateProbabilities = RandomWalkTestUtils.parseSteadyStateProbabilities(results); assertEquals(0.25, steadyStateProbabilities.get(12L), RandomWalkTestUtils.EPSILON); assertEquals(0.354872, steadyStateProbabilities.get(34L), RandomWalkTestUtils.EPSILON); assertEquals(0.09375, steadyStateProbabilities.get(56L), RandomWalkTestUtils.EPSILON); assertEquals(0.301377, steadyStateProbabilities.get(78L), RandomWalkTestUtils.EPSILON); }
/** * A local integration test on toy data */
A local integration test on toy data
testToyData
{ "repo_name": "zfighter/giraph-research", "path": "giraph-examples/target/munged/test/org/apache/giraph/examples/RandomWalkWithRestartVertexTest.java", "license": "apache-2.0", "size": 4457 }
[ "java.util.Map", "org.apache.giraph.conf.GiraphConfiguration", "org.apache.giraph.edge.ByteArrayEdges", "org.apache.giraph.utils.InternalVertexRunner", "org.junit.Assert" ]
import java.util.Map; import org.apache.giraph.conf.GiraphConfiguration; import org.apache.giraph.edge.ByteArrayEdges; import org.apache.giraph.utils.InternalVertexRunner; import org.junit.Assert;
import java.util.*; import org.apache.giraph.conf.*; import org.apache.giraph.edge.*; import org.apache.giraph.utils.*; import org.junit.*;
[ "java.util", "org.apache.giraph", "org.junit" ]
java.util; org.apache.giraph; org.junit;
1,015,333
public int readByte() throws IOException { return bitSource.readByte(); }
int function() throws IOException { return bitSource.readByte(); }
/** * Reads an entire byte from the underlying input stream. * * @return The byte read from the underlying input stream. * @throws java.io.IOException If reading the byte caused an IOException */
Reads an entire byte from the underlying input stream
readByte
{ "repo_name": "jfim/bitio", "path": "src/main/java/im/jeanfrancois/bitio/BitInputStream.java", "license": "lgpl-3.0", "size": 3660 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
2,865,202
ArrayList<Task> tasks = job.getTasks(); for (Task task : tasks) { Map<String, String> variables = task.getVariablesOverriden(job); List<SelectionScript> selectionScripts = task.getSelectionScripts(); if (selectionScripts != null) { for (SelectionScript sscript : selectionScripts) { resolveScript(sscript, variables); } } resolveScript(task.getFlowScript(), variables); resolveScript(task.getPreScript(), variables); resolveScript(task.getPostScript(), variables); resolveScript(task.getCleaningScript(), variables); } return job; }
ArrayList<Task> tasks = job.getTasks(); for (Task task : tasks) { Map<String, String> variables = task.getVariablesOverriden(job); List<SelectionScript> selectionScripts = task.getSelectionScripts(); if (selectionScripts != null) { for (SelectionScript sscript : selectionScripts) { resolveScript(sscript, variables); } } resolveScript(task.getFlowScript(), variables); resolveScript(task.getPreScript(), variables); resolveScript(task.getPostScript(), variables); resolveScript(task.getCleaningScript(), variables); } return job; }
/** * Filters the scripts in the specified job. */
Filters the scripts in the specified job
resolveScripts
{ "repo_name": "marcocast/scheduling", "path": "scheduler/scheduler-api/src/test/java/org/ow2/proactive/scheduler/common/job/factories/ScriptUpdateUtil.java", "license": "agpl-3.0", "size": 2996 }
[ "java.util.ArrayList", "java.util.List", "java.util.Map", "org.ow2.proactive.scheduler.common.task.Task", "org.ow2.proactive.scripting.SelectionScript" ]
import java.util.ArrayList; import java.util.List; import java.util.Map; import org.ow2.proactive.scheduler.common.task.Task; import org.ow2.proactive.scripting.SelectionScript;
import java.util.*; import org.ow2.proactive.scheduler.common.task.*; import org.ow2.proactive.scripting.*;
[ "java.util", "org.ow2.proactive" ]
java.util; org.ow2.proactive;
1,934,646
public boolean isOpaqueCube(IBlockState state) { return false; }
boolean function(IBlockState state) { return false; }
/** * Used to determine ambient occlusion and culling when rebuilding chunks for render */
Used to determine ambient occlusion and culling when rebuilding chunks for render
isOpaqueCube
{ "repo_name": "Severed-Infinity/technium", "path": "build/tmp/recompileMc/sources/net/minecraft/block/BlockDoor.java", "license": "gpl-3.0", "size": 19142 }
[ "net.minecraft.block.state.IBlockState" ]
import net.minecraft.block.state.IBlockState;
import net.minecraft.block.state.*;
[ "net.minecraft.block" ]
net.minecraft.block;
2,694,690
public void setDeploymentInfoCustomizers( Collection<? extends UndertowDeploymentInfoCustomizer> customizers) { Assert.notNull(customizers, "Customizers must not be null"); this.deploymentInfoCustomizers = new ArrayList<UndertowDeploymentInfoCustomizer>( customizers); }
void function( Collection<? extends UndertowDeploymentInfoCustomizer> customizers) { Assert.notNull(customizers, STR); this.deploymentInfoCustomizers = new ArrayList<UndertowDeploymentInfoCustomizer>( customizers); }
/** * Set {@link UndertowDeploymentInfoCustomizer}s that should be applied to the * Undertow {@link DeploymentInfo}. Calling this method will replace any existing * customizers. * @param customizers the customizers to set */
Set <code>UndertowDeploymentInfoCustomizer</code>s that should be applied to the Undertow <code>DeploymentInfo</code>. Calling this method will replace any existing customizers
setDeploymentInfoCustomizers
{ "repo_name": "end-user/spring-boot", "path": "spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainerFactory.java", "license": "apache-2.0", "size": 19960 }
[ "java.util.ArrayList", "java.util.Collection", "org.springframework.util.Assert" ]
import java.util.ArrayList; import java.util.Collection; import org.springframework.util.Assert;
import java.util.*; import org.springframework.util.*;
[ "java.util", "org.springframework.util" ]
java.util; org.springframework.util;
897,143
@Override public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] valuesArray) { int match = uriMatcher.match(uri); String table; switch (match) { case ALL_ROWS: table = uri.getLastPathSegment(); break; case ROW_BY_ID: throw new UnsupportedOperationException("Unable to insert by id for uri: " + uri); default: throw new UnsupportedOperationException("Unknown uri: " + uri); } int count = 0; SQLiteDatabase db = getWritableDatabaseWithReference(); if (db == null) return count; try { startTransaction(db); try { final String nullColumnHack = getNullColumnHack(table); final int conflictAlgorithm = translateConflictAlgorithm(getInsertConflictAlgorithm(table)); for (ContentValues values : valuesArray) { long id; try { id = db.insertWithOnConflict(table, nullColumnHack, values, conflictAlgorithm); } catch (SQLiteConstraintException e) { if (LOGGING_ENABLED) { Log.e(TAG, "Error inserting " + table + " with " + values, e); } throw e; } if (id != -1) { ++count; } } db.setTransactionSuccessful(); } catch (SQLiteException e) { if (LOGGING_ENABLED && !(e instanceof SQLiteConstraintException)) { Log.e(TAG, "Unexpected error bulk inserting " + table, e); } count = 0; } finally { db.endTransaction(); } } finally { db.releaseReference(); } // notify change essentially indicates to any users with active cursors // that they need to "reload" the data if (count > 0) { notifyChange(getContext(), uri); } return count; }
int function(@NonNull Uri uri, @NonNull ContentValues[] valuesArray) { int match = uriMatcher.match(uri); String table; switch (match) { case ALL_ROWS: table = uri.getLastPathSegment(); break; case ROW_BY_ID: throw new UnsupportedOperationException(STR + uri); default: throw new UnsupportedOperationException(STR + uri); } int count = 0; SQLiteDatabase db = getWritableDatabaseWithReference(); if (db == null) return count; try { startTransaction(db); try { final String nullColumnHack = getNullColumnHack(table); final int conflictAlgorithm = translateConflictAlgorithm(getInsertConflictAlgorithm(table)); for (ContentValues values : valuesArray) { long id; try { id = db.insertWithOnConflict(table, nullColumnHack, values, conflictAlgorithm); } catch (SQLiteConstraintException e) { if (LOGGING_ENABLED) { Log.e(TAG, STR + table + STR + values, e); } throw e; } if (id != -1) { ++count; } } db.setTransactionSuccessful(); } catch (SQLiteException e) { if (LOGGING_ENABLED && !(e instanceof SQLiteConstraintException)) { Log.e(TAG, STR + table, e); } count = 0; } finally { db.endTransaction(); } } finally { db.releaseReference(); } if (count > 0) { notifyChange(getContext(), uri); } return count; }
/** * Implements a bulk insertion operation under a single transaction for all rows. * If the uri references a single record, the insertion will fail. * * @param uri The content:// URI of the insertion request. * @param valuesArray An array of sets of column_name/value pairs to add to the database. * This must not be {@code null}. * @return The number of values that were inserted. * @throws UnsupportedOperationException If the URI refers to a single item, or is not in * the expected format */
Implements a bulk insertion operation under a single transaction for all rows. If the uri references a single record, the insertion will fail
bulkInsert
{ "repo_name": "joerogers/CrudContent", "path": "crudcontent/src/main/java/com/forkingcode/crudcontent/provider/BasicCRUDProvider.java", "license": "apache-2.0", "size": 29910 }
[ "android.content.ContentValues", "android.database.sqlite.SQLiteConstraintException", "android.database.sqlite.SQLiteDatabase", "android.database.sqlite.SQLiteException", "android.net.Uri", "android.support.annotation.NonNull", "android.util.Log" ]
import android.content.ContentValues; import android.database.sqlite.SQLiteConstraintException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.net.Uri; import android.support.annotation.NonNull; import android.util.Log;
import android.content.*; import android.database.sqlite.*; import android.net.*; import android.support.annotation.*; import android.util.*;
[ "android.content", "android.database", "android.net", "android.support", "android.util" ]
android.content; android.database; android.net; android.support; android.util;
1,680,264