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
sequence
imports_info
stringlengths
19
34.8k
cluster_imports_info
stringlengths
15
3.66k
libraries
sequence
libraries_info
stringlengths
6
661
id
int64
0
2.92M
public synchronized void fetchAndUpdateRemoteStore(int nodeId, List<StoreDefinition> updatedStores) { // Check for backwards compatibility StoreDefinitionUtils.validateSchemasAsNeeded(updatedStores); Map<String, StoreDefinition> updatedStoresMap = new HashMap<String, StoreDefinition>(); // Fetch the original store definition list Versioned<List<StoreDefinition>> originalStoreDefinitions = getRemoteStoreDefList(nodeId); if(originalStoreDefinitions == null) { throw new VoldemortException("No stores found at this node ID : " + nodeId); } List<StoreDefinition> originalstoreDefList = originalStoreDefinitions.getValue(); List<StoreDefinition> finalStoreDefList = new ArrayList<StoreDefinition>(); VectorClock oldClock = (VectorClock) originalStoreDefinitions.getVersion(); // Build a map of store name to the new store definitions for(StoreDefinition def: updatedStores) { updatedStoresMap.put(def.getName(), def); } // Iterate through the original store definitions. Replace the old // ones with the ones specified in 'updatedStores' for(StoreDefinition def: originalstoreDefList) { StoreDefinition updatedDef = updatedStoresMap.get(def.getName()); if(updatedDef == null) { finalStoreDefList.add(def); } else { finalStoreDefList.add(updatedDef); } } // Set the new store definition on the given nodeId updateRemoteMetadata(nodeId, MetadataStore.STORES_KEY, new Versioned<String>(storeMapper.writeStoreList(finalStoreDefList), oldClock.incremented(nodeId, 1))); }
synchronized void function(int nodeId, List<StoreDefinition> updatedStores) { StoreDefinitionUtils.validateSchemasAsNeeded(updatedStores); Map<String, StoreDefinition> updatedStoresMap = new HashMap<String, StoreDefinition>(); Versioned<List<StoreDefinition>> originalStoreDefinitions = getRemoteStoreDefList(nodeId); if(originalStoreDefinitions == null) { throw new VoldemortException(STR + nodeId); } List<StoreDefinition> originalstoreDefList = originalStoreDefinitions.getValue(); List<StoreDefinition> finalStoreDefList = new ArrayList<StoreDefinition>(); VectorClock oldClock = (VectorClock) originalStoreDefinitions.getVersion(); for(StoreDefinition def: updatedStores) { updatedStoresMap.put(def.getName(), def); } for(StoreDefinition def: originalstoreDefList) { StoreDefinition updatedDef = updatedStoresMap.get(def.getName()); if(updatedDef == null) { finalStoreDefList.add(def); } else { finalStoreDefList.add(updatedDef); } } updateRemoteMetadata(nodeId, MetadataStore.STORES_KEY, new Versioned<String>(storeMapper.writeStoreList(finalStoreDefList), oldClock.incremented(nodeId, 1))); }
/** * Helper method to fetch the current stores xml list and update the * specified stores * * @param nodeId ID of the node for which the stores list has to be * updated * @param updatedStores New version of the stores to be updated */
Helper method to fetch the current stores xml list and update the specified stores
fetchAndUpdateRemoteStore
{ "repo_name": "null-exception/voldemort", "path": "src/java/voldemort/client/protocol/admin/AdminClient.java", "license": "apache-2.0", "size": 240012 }
[ "java.util.ArrayList", "java.util.HashMap", "java.util.List", "java.util.Map" ]
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
2,499,524
public static String formatSessionSubtitle(long blockStart, long blockEnd, String roomName, Context context) { TimeZone.setDefault(CONFERENCE_TIME_ZONE); // NOTE: There is an efficient version of formatDateRange in Eclair and // beyond that allows you to recycle a StringBuilder. final CharSequence timeString = DateUtils.formatDateRange(context, blockStart, blockEnd, TIME_FLAGS); return context.getString(R.string.session_subtitle, timeString, roomName); }
static String function(long blockStart, long blockEnd, String roomName, Context context) { TimeZone.setDefault(CONFERENCE_TIME_ZONE); final CharSequence timeString = DateUtils.formatDateRange(context, blockStart, blockEnd, TIME_FLAGS); return context.getString(R.string.session_subtitle, timeString, roomName); }
/** * Format and return the given {@link Blocks} and {@link Rooms} values using * {@link #CONFERENCE_TIME_ZONE}. */
Format and return the given <code>Blocks</code> and <code>Rooms</code> values using <code>#CONFERENCE_TIME_ZONE</code>
formatSessionSubtitle
{ "repo_name": "underhilllabs/iosched", "path": "src/com/google/android/apps/iosched/util/UIUtils.java", "license": "apache-2.0", "size": 7986 }
[ "android.content.Context", "android.text.format.DateUtils", "java.util.TimeZone" ]
import android.content.Context; import android.text.format.DateUtils; import java.util.TimeZone;
import android.content.*; import android.text.format.*; import java.util.*;
[ "android.content", "android.text", "java.util" ]
android.content; android.text; java.util;
2,572,016
Collection<T> getNextWork();
Collection<T> getNextWork();
/** * Get the next lot of work for the batch processor. Implementations should return * the largest number of entries possible; the {@link BatchProcessor} will keep calling * this method until it has enough work for the individual worker threads to process * or until the work load is empty. * * @return the next set of work object to process or an empty collection * if there is no more work remaining. */
Get the next lot of work for the batch processor. Implementations should return the largest number of entries possible; the <code>BatchProcessor</code> will keep calling this method until it has enough work for the individual worker threads to process or until the work load is empty
getNextWork
{ "repo_name": "Alfresco/alfresco-repository", "path": "src/main/java/org/alfresco/repo/batch/BatchProcessWorkProvider.java", "license": "lgpl-3.0", "size": 2354 }
[ "java.util.Collection" ]
import java.util.Collection;
import java.util.*;
[ "java.util" ]
java.util;
2,746,361
public int corruptBlockOnDataNodes(ExtendedBlock block) throws IOException{ return corruptBlockOnDataNodesHelper(block, false); }
int function(ExtendedBlock block) throws IOException{ return corruptBlockOnDataNodesHelper(block, false); }
/** * Return the number of corrupted replicas of the given block. * * @param block block to be corrupted * @throws IOException on error accessing the file for the given block */
Return the number of corrupted replicas of the given block
corruptBlockOnDataNodes
{ "repo_name": "vlajos/hadoop", "path": "hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/MiniDFSCluster.java", "license": "apache-2.0", "size": 105726 }
[ "java.io.IOException", "org.apache.hadoop.hdfs.protocol.ExtendedBlock" ]
import java.io.IOException; import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import java.io.*; import org.apache.hadoop.hdfs.protocol.*;
[ "java.io", "org.apache.hadoop" ]
java.io; org.apache.hadoop;
952,925
public static IMouseStateChange enterEdgeLabel(final CStateFactory<?, ?> m_factory, final MouseEvent event, final HitInfo hitInfo) { final EdgeLabel l = hitInfo.getHitEdgeLabel(); return new CStateChange(m_factory.createEdgeLabelEnterState(l, event), true); }
static IMouseStateChange function(final CStateFactory<?, ?> m_factory, final MouseEvent event, final HitInfo hitInfo) { final EdgeLabel l = hitInfo.getHitEdgeLabel(); return new CStateChange(m_factory.createEdgeLabelEnterState(l, event), true); }
/** * Changes the state to edge label enter state. * * @param m_factory The state factory for all states. * @param event The mouse event that caused the state change. * @param hitInfo The information about what was hit. * * @return The state object that describes the mouse state. */
Changes the state to edge label enter state
enterEdgeLabel
{ "repo_name": "AmesianX/binnavi", "path": "src/main/java/com/google/security/zynamics/zylib/yfileswrap/gui/zygraph/editmode/transformations/CHitEdgeLabelsTransformer.java", "license": "apache-2.0", "size": 2616 }
[ "com.google.security.zynamics.zylib.gui.zygraph.editmode.CStateChange", "com.google.security.zynamics.zylib.gui.zygraph.editmode.IMouseStateChange", "com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.editmode.CStateFactory", "java.awt.event.MouseEvent" ]
import com.google.security.zynamics.zylib.gui.zygraph.editmode.CStateChange; import com.google.security.zynamics.zylib.gui.zygraph.editmode.IMouseStateChange; import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.editmode.CStateFactory; import java.awt.event.MouseEvent;
import com.google.security.zynamics.zylib.gui.zygraph.editmode.*; import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.editmode.*; import java.awt.event.*;
[ "com.google.security", "java.awt" ]
com.google.security; java.awt;
2,816,952
public static void repairRoster(UserRepository repo) throws Exception { if (user != null) { repairUserRoster(user, repo); } else { List<BareJID> users = repo.getUsers(); if (users != null) { for (BareJID usr : users) { // System.out.println(usr); repairUserRoster(usr, repo); } // end of for (String user: users) } else { System.out.println("There are no user accounts in repository."); } // end of else } }
static void function(UserRepository repo) throws Exception { if (user != null) { repairUserRoster(user, repo); } else { List<BareJID> users = repo.getUsers(); if (users != null) { for (BareJID usr : users) { repairUserRoster(usr, repo); } } else { System.out.println(STR); } } }
/** * Method description * * * @param repo * * @throws Exception */
Method description
repairRoster
{ "repo_name": "DanielYao/tigase-server", "path": "src/main/java/tigase/util/RepositoryUtils.java", "license": "agpl-3.0", "size": 27889 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
2,545,812
@Test public void testFsckMissingReplicas() throws IOException { // Desired replication factor // Set this higher than NUM_REPLICAS so it's under-replicated final short REPL_FACTOR = 2; // Number of replicas to actually start final short NUM_REPLICAS = 1; // Number of blocks to write final short NUM_BLOCKS = 3; // Set a small-ish blocksize final long blockSize = 512; Configuration conf = new Configuration(); conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize); MiniDFSCluster cluster = null; DistributedFileSystem dfs = null; try { // Startup a minicluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(NUM_REPLICAS).build(); assertNotNull("Failed Cluster Creation", cluster); cluster.waitClusterUp(); dfs = cluster.getFileSystem(); assertNotNull("Failed to get FileSystem", dfs); // Create a file that will be intentionally under-replicated final String pathString = new String("/testfile"); final Path path = new Path(pathString); long fileLen = blockSize * NUM_BLOCKS; DFSTestUtil.createFile(dfs, path, fileLen, REPL_FACTOR, 1); // Create an under-replicated file NameNode namenode = cluster.getNameNode(); NetworkTopology nettop = cluster.getNamesystem().getBlockManager() .getDatanodeManager().getNetworkTopology(); Map<String,String[]> pmap = new HashMap<String, String[]>(); Writer result = new StringWriter(); PrintWriter out = new PrintWriter(result, true); InetAddress remoteAddress = InetAddress.getLocalHost(); NamenodeFsck fsck = new NamenodeFsck(conf, namenode, nettop, pmap, out, NUM_REPLICAS, remoteAddress); // Run the fsck and check the Result final HdfsFileStatus file = namenode.getRpcServer().getFileInfo(pathString); assertNotNull(file); Result res = new Result(conf); fsck.check(pathString, file, res); // Also print the output from the fsck, for ex post facto sanity checks System.out.println(result.toString()); assertEquals(res.missingReplicas, (NUM_BLOCKS*REPL_FACTOR) - (NUM_BLOCKS*NUM_REPLICAS)); assertEquals(res.numExpectedReplicas, NUM_BLOCKS*REPL_FACTOR); } finally { if(dfs != null) { dfs.close(); } if(cluster != null) { cluster.shutdown(); } } }
void function() throws IOException { final short REPL_FACTOR = 2; final short NUM_REPLICAS = 1; final short NUM_BLOCKS = 3; final long blockSize = 512; Configuration conf = new Configuration(); conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize); MiniDFSCluster cluster = null; DistributedFileSystem dfs = null; try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(NUM_REPLICAS).build(); assertNotNull(STR, cluster); cluster.waitClusterUp(); dfs = cluster.getFileSystem(); assertNotNull(STR, dfs); final String pathString = new String(STR); final Path path = new Path(pathString); long fileLen = blockSize * NUM_BLOCKS; DFSTestUtil.createFile(dfs, path, fileLen, REPL_FACTOR, 1); NameNode namenode = cluster.getNameNode(); NetworkTopology nettop = cluster.getNamesystem().getBlockManager() .getDatanodeManager().getNetworkTopology(); Map<String,String[]> pmap = new HashMap<String, String[]>(); Writer result = new StringWriter(); PrintWriter out = new PrintWriter(result, true); InetAddress remoteAddress = InetAddress.getLocalHost(); NamenodeFsck fsck = new NamenodeFsck(conf, namenode, nettop, pmap, out, NUM_REPLICAS, remoteAddress); final HdfsFileStatus file = namenode.getRpcServer().getFileInfo(pathString); assertNotNull(file); Result res = new Result(conf); fsck.check(pathString, file, res); System.out.println(result.toString()); assertEquals(res.missingReplicas, (NUM_BLOCKS*REPL_FACTOR) - (NUM_BLOCKS*NUM_REPLICAS)); assertEquals(res.numExpectedReplicas, NUM_BLOCKS*REPL_FACTOR); } finally { if(dfs != null) { dfs.close(); } if(cluster != null) { cluster.shutdown(); } } }
/** * Tests that the # of missing block replicas and expected replicas is correct * @throws IOException */
Tests that the # of missing block replicas and expected replicas is correct
testFsckMissingReplicas
{ "repo_name": "gilv/hadoop", "path": "hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFsck.java", "license": "apache-2.0", "size": 62445 }
[ "java.io.IOException", "java.io.PrintWriter", "java.io.StringWriter", "java.io.Writer", "java.net.InetAddress", "java.util.HashMap", "java.util.Map", "org.apache.hadoop.conf.Configuration", "org.apache.hadoop.fs.Path", "org.apache.hadoop.hdfs.DFSConfigKeys", "org.apache.hadoop.hdfs.DFSTestUtil", "org.apache.hadoop.hdfs.DistributedFileSystem", "org.apache.hadoop.hdfs.MiniDFSCluster", "org.apache.hadoop.hdfs.protocol.HdfsFileStatus", "org.apache.hadoop.hdfs.server.namenode.NamenodeFsck", "org.apache.hadoop.net.NetworkTopology", "org.junit.Assert" ]
import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.net.InetAddress; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.DFSTestUtil; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.protocol.HdfsFileStatus; import org.apache.hadoop.hdfs.server.namenode.NamenodeFsck; import org.apache.hadoop.net.NetworkTopology; import org.junit.Assert;
import java.io.*; import java.net.*; import java.util.*; import org.apache.hadoop.conf.*; import org.apache.hadoop.fs.*; import org.apache.hadoop.hdfs.*; import org.apache.hadoop.hdfs.protocol.*; import org.apache.hadoop.hdfs.server.namenode.*; import org.apache.hadoop.net.*; import org.junit.*;
[ "java.io", "java.net", "java.util", "org.apache.hadoop", "org.junit" ]
java.io; java.net; java.util; org.apache.hadoop; org.junit;
1,922,737
public void resolveActualValues() { TreeMap<String, String> replaced = new TreeMap<String, String>(); trace("Before:"); trace(toString()); for (Entry<String, String> e : m_actualHashMap.entrySet()) { replaced.put(e.getKey(), StringUtil.substitute(e.getValue(), m_actualHashMap)); } m_actualHashMap = replaced; trace("After:"); trace(toString()); }
void function() { TreeMap<String, String> replaced = new TreeMap<String, String>(); trace(STR); trace(toString()); for (Entry<String, String> e : m_actualHashMap.entrySet()) { replaced.put(e.getKey(), StringUtil.substitute(e.getValue(), m_actualHashMap)); } m_actualHashMap = replaced; trace(STR); trace(toString()); }
/** * This method can be called to resolve all actual values. Resolving actual values means that if an actual value contains a * reference to a parameter it will resolve that variable. It supports unlimited nesting. */
This method can be called to resolve all actual values. Resolving actual values means that if an actual value contains a reference to a parameter it will resolve that variable. It supports unlimited nesting
resolveActualValues
{ "repo_name": "MarkHooijkaas/caas-cordys-svn", "path": "src/java/org/kisst/cordys/caas/support/LoadedPropertyMap.java", "license": "gpl-3.0", "size": 12397 }
[ "java.util.TreeMap", "org.kisst.cordys.caas.main.Environment", "org.kisst.cordys.caas.util.StringUtil" ]
import java.util.TreeMap; import org.kisst.cordys.caas.main.Environment; import org.kisst.cordys.caas.util.StringUtil;
import java.util.*; import org.kisst.cordys.caas.main.*; import org.kisst.cordys.caas.util.*;
[ "java.util", "org.kisst.cordys" ]
java.util; org.kisst.cordys;
637,943
public void subtitle(Player... players) { ReflectionHelper.sendPacket(ReflectionHelper.createSubtitlePacket(toString()), players); }
void function(Player... players) { ReflectionHelper.sendPacket(ReflectionHelper.createSubtitlePacket(toString()), players); }
/** * Sends this as a subtitle to all the players specified * * @param players the players to send it to */
Sends this as a subtitle to all the players specified
subtitle
{ "repo_name": "YoungOG/CarbyneCore", "path": "src/com/medievallords/carbyne/utils/JSONMessage.java", "license": "apache-2.0", "size": 23143 }
[ "org.bukkit.entity.Player" ]
import org.bukkit.entity.Player;
import org.bukkit.entity.*;
[ "org.bukkit.entity" ]
org.bukkit.entity;
807,881
public Array getArray() { return new ArrayImpl(this.retrofitBuilder.build(), this); } public AutoRestSwaggerBATArrayServiceImpl() { this("http://localhost"); } public AutoRestSwaggerBATArrayServiceImpl(String baseUri) { super(); this.baseUri = baseUri; initialize(); } public AutoRestSwaggerBATArrayServiceImpl(String baseUri, OkHttpClient client, Retrofit.Builder retrofitBuilder) { super(client, retrofitBuilder); this.baseUri = baseUri; initialize(); }
Array function() { return new ArrayImpl(this.retrofitBuilder.build(), this); } public AutoRestSwaggerBATArrayServiceImpl() { this("http: } public AutoRestSwaggerBATArrayServiceImpl(String baseUri) { super(); this.baseUri = baseUri; initialize(); } public AutoRestSwaggerBATArrayServiceImpl(String baseUri, OkHttpClient client, Retrofit.Builder retrofitBuilder) { super(client, retrofitBuilder); this.baseUri = baseUri; initialize(); }
/** * Gets the Array object to access its operations. * @return the array value. */
Gets the Array object to access its operations
getArray
{ "repo_name": "matt-gibbs/AutoRest", "path": "AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/AutoRestSwaggerBATArrayServiceImpl.java", "license": "mit", "size": 2245 }
[ "com.squareup.okhttp.OkHttpClient" ]
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.*;
[ "com.squareup.okhttp" ]
com.squareup.okhttp;
705,847
public T addCategory(String name, Iterable<? extends CharSequence> categories) { return addContextQuery(CategoryContextMapping.query(name, categories)); }
T function(String name, Iterable<? extends CharSequence> categories) { return addContextQuery(CategoryContextMapping.query(name, categories)); }
/** * Setup a Category for suggestions. See {@link CategoryContextMapping}. * @param categories name of the category * @return this */
Setup a Category for suggestions. See <code>CategoryContextMapping</code>
addCategory
{ "repo_name": "strapdata/elassandra-test", "path": "core/src/main/java/org/elasticsearch/search/suggest/SuggestBuilder.java", "license": "apache-2.0", "size": 10572 }
[ "org.elasticsearch.search.suggest.context.CategoryContextMapping" ]
import org.elasticsearch.search.suggest.context.CategoryContextMapping;
import org.elasticsearch.search.suggest.context.*;
[ "org.elasticsearch.search" ]
org.elasticsearch.search;
1,524,082
public void deleteInstance(com.google.bigtable.admin.v2.DeleteInstanceRequest request, io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) { asyncUnimplementedUnaryCall(getDeleteInstanceMethodHelper(), responseObserver); }
void function(com.google.bigtable.admin.v2.DeleteInstanceRequest request, io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) { asyncUnimplementedUnaryCall(getDeleteInstanceMethodHelper(), responseObserver); }
/** * <pre> * Delete an instance from a project. * </pre> */
<code> Delete an instance from a project. </code>
deleteInstance
{ "repo_name": "pongad/api-client-staging", "path": "generated/java/grpc-google-cloud-bigtable-admin-v2/src/main/java/com/google/bigtable/admin/v2/BigtableInstanceAdminGrpc.java", "license": "bsd-3-clause", "size": 106367 }
[ "io.grpc.stub.ServerCalls" ]
import io.grpc.stub.ServerCalls;
import io.grpc.stub.*;
[ "io.grpc.stub" ]
io.grpc.stub;
278,318
public void assignAdditionalGroupsToUser(String userId, String[] groupIds) throws SMException { checkForSufficientParams(userId, groupIds); try { UserProvisioningManager upManager = ProvisionManager.getInstance() .getUserProvisioningManager(); Set conGrpIds = addAllGroups(userId, groupIds, upManager); String[] finalUserGroupIds = new String[conGrpIds.size()]; Iterator iter = conGrpIds.iterator(); for (int i = 0; iter.hasNext(); i++) { finalUserGroupIds[i] = (String) iter.next(); } //Setting groups for user and updating it upManager.assignGroupsToUser(userId, finalUserGroupIds); } catch (CSException exception) { String mesg = "The Security Service encountered a fatal exception."; Utility.getInstance().throwSMException(exception, mesg, "sm.operation.error"); } }
void function(String userId, String[] groupIds) throws SMException { checkForSufficientParams(userId, groupIds); try { UserProvisioningManager upManager = ProvisionManager.getInstance() .getUserProvisioningManager(); Set conGrpIds = addAllGroups(userId, groupIds, upManager); String[] finalUserGroupIds = new String[conGrpIds.size()]; Iterator iter = conGrpIds.iterator(); for (int i = 0; iter.hasNext(); i++) { finalUserGroupIds[i] = (String) iter.next(); } upManager.assignGroupsToUser(userId, finalUserGroupIds); } catch (CSException exception) { String mesg = STR; Utility.getInstance().throwSMException(exception, mesg, STR); } }
/** * Assigns additional groups to user. * @param userId string userId * @param groupIds string[] * @throws SMException exception */
Assigns additional groups to user
assignAdditionalGroupsToUser
{ "repo_name": "NCIP/catissue-security-manager", "path": "software/SecurityManager/src/main/java/edu/wustl/security/manager/SecurityManager.java", "license": "bsd-3-clause", "size": 22807 }
[ "edu.wustl.security.exception.SMException", "edu.wustl.security.global.ProvisionManager", "edu.wustl.security.global.Utility", "gov.nih.nci.security.UserProvisioningManager", "gov.nih.nci.security.exceptions.CSException", "java.util.Iterator", "java.util.Set" ]
import edu.wustl.security.exception.SMException; import edu.wustl.security.global.ProvisionManager; import edu.wustl.security.global.Utility; import gov.nih.nci.security.UserProvisioningManager; import gov.nih.nci.security.exceptions.CSException; import java.util.Iterator; import java.util.Set;
import edu.wustl.security.exception.*; import edu.wustl.security.global.*; import gov.nih.nci.security.*; import gov.nih.nci.security.exceptions.*; import java.util.*;
[ "edu.wustl.security", "gov.nih.nci", "java.util" ]
edu.wustl.security; gov.nih.nci; java.util;
535,840
@Test(expected=ApplicationException.class) public void test09_saveLocation() throws ApplicationException{ LocationTypeDto countryLocationTypeDto = createAndSaveLocationType(locationService, "Country", null, true); LocationDto location = createLocation("India", countryLocationTypeDto, null); location.setParentLocationId(randomLong(100000)); locationService.saveLocation(location); }
@Test(expected=ApplicationException.class) void function() throws ApplicationException{ LocationTypeDto countryLocationTypeDto = createAndSaveLocationType(locationService, STR, null, true); LocationDto location = createLocation("India", countryLocationTypeDto, null); location.setParentLocationId(randomLong(100000)); locationService.saveLocation(location); }
/** * Simple Test to save Location where parent do not exists * @throws ApplicationException */
Simple Test to save Location where parent do not exists
test09_saveLocation
{ "repo_name": "eswaraj/platform", "path": "core/src/test/java/com/eswaraj/core/service/impl/TestLocationServiceImpl.java", "license": "gpl-3.0", "size": 16835 }
[ "com.eswaraj.core.exceptions.ApplicationException", "com.eswaraj.web.dto.LocationDto", "com.eswaraj.web.dto.LocationTypeDto", "org.junit.Test" ]
import com.eswaraj.core.exceptions.ApplicationException; import com.eswaraj.web.dto.LocationDto; import com.eswaraj.web.dto.LocationTypeDto; import org.junit.Test;
import com.eswaraj.core.exceptions.*; import com.eswaraj.web.dto.*; import org.junit.*;
[ "com.eswaraj.core", "com.eswaraj.web", "org.junit" ]
com.eswaraj.core; com.eswaraj.web; org.junit;
2,904,993
public static Set<String> scanClassNames(final String packageName) throws IOException { return scanClassNames(packageName, false, true); }
static Set<String> function(final String packageName) throws IOException { return scanClassNames(packageName, false, true); }
/** * Scan class names from the given package name. * * @param packageName * the package name * @return the list * @throws IOException * Signals that an I/O exception has occurred. */
Scan class names from the given package name
scanClassNames
{ "repo_name": "lightblueseas/jcommons-lang", "path": "src/main/java/de/alpharogroup/lang/ScanPackageExtensions.java", "license": "mit", "size": 5804 }
[ "java.io.IOException", "java.util.Set" ]
import java.io.IOException; import java.util.Set;
import java.io.*; import java.util.*;
[ "java.io", "java.util" ]
java.io; java.util;
1,389,650
protected Method getAccessor(Object obj, Field field, boolean isGetter) { String name = field.getName(); name = name.substring(0, 1).toUpperCase() + name.substring(1); if (!isGetter) { name = "set" + name; } else if (boolean.class.isAssignableFrom(field.getType())) { name = "is" + name; } else { name = "get" + name; } Method method = (accessors != null) ? accessors.get(name) : null; if (method == null) { try { if (isGetter) { method = getMethod(obj, name, null); } else { method = getMethod(obj, name, new Class[] { field.getType() }); } } catch (Exception e1) { // ignore } // Adds accessor to cache if (method != null) { if (accessors == null) { accessors = new Hashtable<String, Method>(); } accessors.put(name, method); } } return method; }
Method function(Object obj, Field field, boolean isGetter) { String name = field.getName(); name = name.substring(0, 1).toUpperCase() + name.substring(1); if (!isGetter) { name = "set" + name; } else if (boolean.class.isAssignableFrom(field.getType())) { name = "is" + name; } else { name = "get" + name; } Method method = (accessors != null) ? accessors.get(name) : null; if (method == null) { try { if (isGetter) { method = getMethod(obj, name, null); } else { method = getMethod(obj, name, new Class[] { field.getType() }); } } catch (Exception e1) { } if (method != null) { if (accessors == null) { accessors = new Hashtable<String, Method>(); } accessors.put(name, method); } } return method; }
/** * Returns the accessor (getter, setter) for the specified field. */
Returns the accessor (getter, setter) for the specified field
getAccessor
{ "repo_name": "JanaWengenroth/GKA1", "path": "libraries/jgraphx/src/com/mxgraph/io/mxObjectCodec.java", "license": "gpl-2.0", "size": 32261 }
[ "java.lang.reflect.Field", "java.lang.reflect.Method", "java.util.Hashtable" ]
import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Hashtable;
import java.lang.reflect.*; import java.util.*;
[ "java.lang", "java.util" ]
java.lang; java.util;
1,930,118
private void renameKeyClassNames(Collection<PojoDescriptor> selPojos, String regex, String replace) { for (PojoDescriptor pojo : selPojos) pojo.keyClassName(pojo.keyClassName().replaceAll(regex, replace)); }
void function(Collection<PojoDescriptor> selPojos, String regex, String replace) { for (PojoDescriptor pojo : selPojos) pojo.keyClassName(pojo.keyClassName().replaceAll(regex, replace)); }
/** * Rename key class name for selected POJOs. * * @param selPojos Selected POJOs to rename. * @param regex Regex to search. * @param replace Text for replacement. */
Rename key class name for selected POJOs
renameKeyClassNames
{ "repo_name": "agura/incubator-ignite", "path": "modules/schema-import/src/main/java/org/apache/ignite/schema/ui/SchemaImportApp.java", "license": "apache-2.0", "size": 67649 }
[ "java.util.Collection", "org.apache.ignite.schema.model.PojoDescriptor" ]
import java.util.Collection; import org.apache.ignite.schema.model.PojoDescriptor;
import java.util.*; import org.apache.ignite.schema.model.*;
[ "java.util", "org.apache.ignite" ]
java.util; org.apache.ignite;
363,410
public static ExtensionList<PeriodicWork> all() { return Jenkins.getInstance().getExtensionList(PeriodicWork.class); } // time constants protected static final long MIN = 1000*60; protected static final long HOUR =60*MIN; protected static final long DAY = 24*HOUR; private static final Random RANDOM = new Random();
static ExtensionList<PeriodicWork> function() { return Jenkins.getInstance().getExtensionList(PeriodicWork.class); } protected static final long MIN = 1000*60; protected static final long HOUR =60*MIN; protected static final long DAY = 24*HOUR; private static final Random RANDOM = new Random();
/** * Returns all the registered {@link PeriodicWork}s. */
Returns all the registered <code>PeriodicWork</code>s
all
{ "repo_name": "rwaldron/jenkins", "path": "core/src/main/java/hudson/model/PeriodicWork.java", "license": "mit", "size": 3484 }
[ "java.util.Random" ]
import java.util.Random;
import java.util.*;
[ "java.util" ]
java.util;
995,055
EClass getReplaceType();
EClass getReplaceType();
/** * Returns the meta object for class '{@link net.opengis.wfs20.ReplaceType <em>Replace Type</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for class '<em>Replace Type</em>'. * @see net.opengis.wfs20.ReplaceType * @generated */
Returns the meta object for class '<code>net.opengis.wfs20.ReplaceType Replace Type</code>'.
getReplaceType
{ "repo_name": "geotools/geotools", "path": "modules/ogc/net.opengis.wfs/src/net/opengis/wfs20/Wfs20Package.java", "license": "lgpl-2.1", "size": 404067 }
[ "org.eclipse.emf.ecore.EClass" ]
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
1,181,597
public static List<Node> searchPath(final Entity sourceEntity, StendhalRPZone zone, final int x, final int y, final Rectangle2D destination, final double maxDistance, final boolean withEntities) { if (zone == null) { zone = sourceEntity.getZone(); } // // long startTimeNano = System.nanoTime(); final long startTime = System.currentTimeMillis(); final EntityPathfinder pathfinder = new EntityPathfinder(sourceEntity, zone, x, y, destination, maxDistance, withEntities); final List<Node> resultPath = pathfinder.getPath(); if (logger.isDebugEnabled() && (pathfinder.getStatus() == EntityPathfinder.PATH_NOT_FOUND)) { logger.debug("Pathfinding aborted: " + zone.getID() + " " + sourceEntity.getTitle() + " (" + x + ", " + y + ") " + destination + " Pathfinding time: " + (System.currentTimeMillis() - startTime)); } return resultPath; }
static List<Node> function(final Entity sourceEntity, StendhalRPZone zone, final int x, final int y, final Rectangle2D destination, final double maxDistance, final boolean withEntities) { if (zone == null) { zone = sourceEntity.getZone(); } final long startTime = System.currentTimeMillis(); final EntityPathfinder pathfinder = new EntityPathfinder(sourceEntity, zone, x, y, destination, maxDistance, withEntities); final List<Node> resultPath = pathfinder.getPath(); if (logger.isDebugEnabled() && (pathfinder.getStatus() == EntityPathfinder.PATH_NOT_FOUND)) { logger.debug(STR + zone.getID() + " " + sourceEntity.getTitle() + STR + x + STR + y + STR + destination + STR + (System.currentTimeMillis() - startTime)); } return resultPath; }
/** * Finds a path for the Entity <code>entity</code>. * * @param sourceEntity * the Entity * @param zone * the zone, if null the current zone of entity is used. * @param x * start x * @param y * start y * @param destination * the destination area * @param maxDistance * the maximum distance (air line) a possible path may be * @param withEntities * @return a list with the path nodes or an empty list if no path is found */
Finds a path for the Entity <code>entity</code>
searchPath
{ "repo_name": "sourceress-project/archestica", "path": "src/games/stendhal/server/core/pathfinder/Path.java", "license": "gpl-2.0", "size": 7815 }
[ "games.stendhal.server.core.engine.StendhalRPZone", "games.stendhal.server.entity.Entity", "java.awt.geom.Rectangle2D", "java.util.List" ]
import games.stendhal.server.core.engine.StendhalRPZone; import games.stendhal.server.entity.Entity; import java.awt.geom.Rectangle2D; import java.util.List;
import games.stendhal.server.core.engine.*; import games.stendhal.server.entity.*; import java.awt.geom.*; import java.util.*;
[ "games.stendhal.server", "java.awt", "java.util" ]
games.stendhal.server; java.awt; java.util;
2,574,930
private void shutdown() { if (execSvc != null) execSvc.shutdown(5000); if (msgExecSvc != null) msgExecSvc.shutdownNow(); try { job.dispose(true); } catch (IgniteCheckedException e) { U.error(log, "Failed to dispose job.", e); } }
void function() { if (execSvc != null) execSvc.shutdown(5000); if (msgExecSvc != null) msgExecSvc.shutdownNow(); try { job.dispose(true); } catch (IgniteCheckedException e) { U.error(log, STR, e); } }
/** * Stops all executors and running tasks. */
Stops all executors and running tasks
shutdown
{ "repo_name": "f7753/ignite", "path": "modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/taskexecutor/external/child/HadoopChildProcessRunner.java", "license": "apache-2.0", "size": 18314 }
[ "org.apache.ignite.IgniteCheckedException", "org.apache.ignite.internal.util.typedef.internal.U" ]
import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.*; import org.apache.ignite.internal.util.typedef.internal.*;
[ "org.apache.ignite" ]
org.apache.ignite;
113,552
protected int createDestination(String name, boolean isTopic) throws SQLException { Connection conn = _jdbcManager.getDataSource().getConnection(); String destinationTable = _jdbcManager.getDestinationTable(); String destinationSequence = _jdbcManager.getDestinationSequence(); try { String sql = ("SELECT id FROM " + destinationTable + " WHERE name=? AND is_topic=?"); PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, name); pstmt.setInt(2, isTopic ? 1 : 0); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { return rs.getInt(1); } rs.close(); if (destinationSequence != null) { JdbcMetaData metaData = _jdbcManager.getMetaData(); sql = metaData.selectSequenceSQL(destinationSequence); int id = 0; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); if (rs.next()) id = rs.getInt(1); else throw new RuntimeException("can't create sequence"); sql = "INSERT INTO " + destinationTable + " (id,name,is_topic) VALUES(?,?,?)"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, id); pstmt.setString(2, name); pstmt.setInt(3, isTopic ? 1 : 0); pstmt.executeUpdate(); if (isTopic) log.fine("JMSTopic[" + name + "," + id + "] created"); else log.fine("JMSQueue[" + name + "," + id + "] created"); return id; } else { sql = "INSERT INTO " + destinationTable + " (name,is_topic) VALUES(?,?)"; pstmt = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS); pstmt.setString(1, name); pstmt.setInt(2, isTopic ? 1 : 0); pstmt.executeUpdate(); rs = pstmt.getGeneratedKeys(); if (rs.next()) { int id = rs.getInt(1); if (isTopic) log.fine("JMSTopic[" + name + "," + id + "] created"); else log.fine("JMSQueue[" + name + "," + id + "] created"); return id; } else throw new SQLException(L.l("can't generate destination for {0}", name)); } } finally { conn.close(); } }
int function(String name, boolean isTopic) throws SQLException { Connection conn = _jdbcManager.getDataSource().getConnection(); String destinationTable = _jdbcManager.getDestinationTable(); String destinationSequence = _jdbcManager.getDestinationSequence(); try { String sql = (STR + destinationTable + STR); PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, name); pstmt.setInt(2, isTopic ? 1 : 0); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { return rs.getInt(1); } rs.close(); if (destinationSequence != null) { JdbcMetaData metaData = _jdbcManager.getMetaData(); sql = metaData.selectSequenceSQL(destinationSequence); int id = 0; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); if (rs.next()) id = rs.getInt(1); else throw new RuntimeException(STR); sql = STR + destinationTable + STR; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, id); pstmt.setString(2, name); pstmt.setInt(3, isTopic ? 1 : 0); pstmt.executeUpdate(); if (isTopic) log.fine(STR + name + "," + id + STR); else log.fine(STR + name + "," + id + STR); return id; } else { sql = STR + destinationTable + STR; pstmt = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS); pstmt.setString(1, name); pstmt.setInt(2, isTopic ? 1 : 0); pstmt.executeUpdate(); rs = pstmt.getGeneratedKeys(); if (rs.next()) { int id = rs.getInt(1); if (isTopic) log.fine(STR + name + "," + id + STR); else log.fine(STR + name + "," + id + STR); return id; } else throw new SQLException(L.l(STR, name)); } } finally { conn.close(); } }
/** * Creates a queue. */
Creates a queue
createDestination
{ "repo_name": "WelcomeHUME/svn-caucho-com-resin", "path": "modules/resin/src/com/caucho/jms/jdbc/JdbcDestination.java", "license": "gpl-2.0", "size": 6445 }
[ "com.caucho.jdbc.JdbcMetaData", "java.sql.Connection", "java.sql.PreparedStatement", "java.sql.ResultSet", "java.sql.SQLException" ]
import com.caucho.jdbc.JdbcMetaData; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;
import com.caucho.jdbc.*; import java.sql.*;
[ "com.caucho.jdbc", "java.sql" ]
com.caucho.jdbc; java.sql;
2,503,348
@Override public BlobRequestConditions setIfModifiedSince(OffsetDateTime ifModifiedSince) { super.setIfModifiedSince(ifModifiedSince); return this; }
BlobRequestConditions function(OffsetDateTime ifModifiedSince) { super.setIfModifiedSince(ifModifiedSince); return this; }
/** * Optionally limit requests to resources that have only been modified since the passed * {@link OffsetDateTime datetime}. * * @param ifModifiedSince The datetime that resources must have been modified since. * @return The updated BlobRequestConditions object. */
Optionally limit requests to resources that have only been modified since the passed <code>OffsetDateTime datetime</code>
setIfModifiedSince
{ "repo_name": "navalev/azure-sdk-for-java", "path": "sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/models/BlobRequestConditions.java", "license": "mit", "size": 3052 }
[ "java.time.OffsetDateTime" ]
import java.time.OffsetDateTime;
import java.time.*;
[ "java.time" ]
java.time;
2,014,374
TextPosition getCursorPosition();
TextPosition getCursorPosition();
/** * Returns the cursor position as a {@link TextPosition} object (a line char position). * @return the cursor position */
Returns the cursor position as a <code>TextPosition</code> object (a line char position)
getCursorPosition
{ "repo_name": "dhuebner/che", "path": "core/ide/che-core-ide-jseditor/src/main/java/org/eclipse/che/ide/jseditor/client/texteditor/TextEditor.java", "license": "epl-1.0", "size": 3101 }
[ "org.eclipse.che.ide.jseditor.client.text.TextPosition" ]
import org.eclipse.che.ide.jseditor.client.text.TextPosition;
import org.eclipse.che.ide.jseditor.client.text.*;
[ "org.eclipse.che" ]
org.eclipse.che;
23,134
AuthenticationBuilder addCredentials(List<CredentialMetaData> credentials);
AuthenticationBuilder addCredentials(List<CredentialMetaData> credentials);
/** * Add credentials authentication builder. * * @param credentials the credentials * @return the authentication builder * @since 4.2.0 */
Add credentials authentication builder
addCredentials
{ "repo_name": "rrenomeron/cas", "path": "api/cas-server-core-api-authentication/src/main/java/org/apereo/cas/authentication/AuthenticationBuilder.java", "license": "apache-2.0", "size": 6202 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
1,370,594
public Title setTitleColor(ChatColor color) { this.titleColor = color; return this; }
Title function(ChatColor color) { this.titleColor = color; return this; }
/** * Set the title color * * @param color * Chat color */
Set the title color
setTitleColor
{ "repo_name": "Vanillacraft/vanillacraft", "path": "CoreFunctions/src/net/vanillacraft/CoreFunctions/fanciful/Title.java", "license": "agpl-3.0", "size": 10182 }
[ "org.bukkit.ChatColor" ]
import org.bukkit.ChatColor;
import org.bukkit.*;
[ "org.bukkit" ]
org.bukkit;
234,349
void addDevicePropertiesTo(DiscoveryResultBuilder discoveryResultBuilder) throws RFXComException;
void addDevicePropertiesTo(DiscoveryResultBuilder discoveryResultBuilder) throws RFXComException;
/** * Given a DiscoveryResultBuilder add any new properties to the builder for the given message * * @param discoveryResultBuilder existing builder containing some early details * @throws RFXComException */
Given a DiscoveryResultBuilder add any new properties to the builder for the given message
addDevicePropertiesTo
{ "repo_name": "Snickermicker/openhab2", "path": "bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/messages/RFXComDeviceMessage.java", "license": "epl-1.0", "size": 3250 }
[ "org.eclipse.smarthome.config.discovery.DiscoveryResultBuilder", "org.openhab.binding.rfxcom.internal.exceptions.RFXComException" ]
import org.eclipse.smarthome.config.discovery.DiscoveryResultBuilder; import org.openhab.binding.rfxcom.internal.exceptions.RFXComException;
import org.eclipse.smarthome.config.discovery.*; import org.openhab.binding.rfxcom.internal.exceptions.*;
[ "org.eclipse.smarthome", "org.openhab.binding" ]
org.eclipse.smarthome; org.openhab.binding;
2,768,790
AuthenticationSessionModel getAuthenticationSession();
AuthenticationSessionModel getAuthenticationSession();
/** * AuthenticationSessionModel attached to this flow * * @return */
AuthenticationSessionModel attached to this flow
getAuthenticationSession
{ "repo_name": "thomasdarimont/keycloak", "path": "server-spi-private/src/main/java/org/keycloak/authentication/AuthenticationFlowContext.java", "license": "apache-2.0", "size": 5826 }
[ "org.keycloak.sessions.AuthenticationSessionModel" ]
import org.keycloak.sessions.AuthenticationSessionModel;
import org.keycloak.sessions.*;
[ "org.keycloak.sessions" ]
org.keycloak.sessions;
2,080,223
EClass getHasTurnedCmd();
EClass getHasTurnedCmd();
/** * Returns the meta object for class '{@link robot.robot.HasTurnedCmd <em>Has Turned Cmd</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Has Turned Cmd</em>'. * @see robot.robot.HasTurnedCmd * @generated */
Returns the meta object for class '<code>robot.robot.HasTurnedCmd Has Turned Cmd</code>'.
getHasTurnedCmd
{ "repo_name": "diverse-project/k3", "path": "k3-sample/lego/lego/src/robot/robot/RobotPackage.java", "license": "epl-1.0", "size": 28235 }
[ "org.eclipse.emf.ecore.EClass" ]
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
350,933
public final void addSpinnerChangeListener(final ChangeListener listener) { spinner.addChangeListener(listener); }
final void function(final ChangeListener listener) { spinner.addChangeListener(listener); }
/** * Add a spinner change listener. */
Add a spinner change listener
addSpinnerChangeListener
{ "repo_name": "supranove/clockwork-old", "path": "src/clockwork/gui/component/slider/GUIUnboundedSlider.java", "license": "mit", "size": 4075 }
[ "javax.swing.event.ChangeListener" ]
import javax.swing.event.ChangeListener;
import javax.swing.event.*;
[ "javax.swing" ]
javax.swing;
80,875
public List<EventElement> getEvents(String owningType, String eventName) { ArrayList<EventElement> events = new ArrayList<EventElement>(); for (Index index : indices) { events.addAll(_reader.getEvents(index, owningType, eventName)); } events.trimToSize(); return events; }
List<EventElement> function(String owningType, String eventName) { ArrayList<EventElement> events = new ArrayList<EventElement>(); for (Index index : indices) { events.addAll(_reader.getEvents(index, owningType, eventName)); } events.trimToSize(); return events; }
/** * Gets all events defined for the given type name in the given index. * * @param index * @param owningType * @param eventName * @return */
Gets all events defined for the given type name in the given index
getEvents
{ "repo_name": "HossainKhademian/Studio3", "path": "plugins/com.aptana.js.core/src/com/aptana/js/core/index/JSIndexQueryHelper.java", "license": "gpl-3.0", "size": 14802 }
[ "com.aptana.index.core.Index", "com.aptana.js.core.model.EventElement", "java.util.ArrayList", "java.util.List" ]
import com.aptana.index.core.Index; import com.aptana.js.core.model.EventElement; import java.util.ArrayList; import java.util.List;
import com.aptana.index.core.*; import com.aptana.js.core.model.*; import java.util.*;
[ "com.aptana.index", "com.aptana.js", "java.util" ]
com.aptana.index; com.aptana.js; java.util;
882,808
@Test public void testSelectNestedAndWhereScript() { SelectStatement stmt = new SelectStatement().from(new TableReference(TEST_TABLE)) .where(Criterion.and( Criterion.eq(new FieldReference(STRING_FIELD), "A0001"), Criterion.greaterThan(new FieldReference(INT_FIELD), new Integer(20080101)))); String value = varCharCast("'A0001'"); String expectedSql = "SELECT * FROM " + tableName(TEST_TABLE) + " WHERE ((stringField = " + stringLiteralPrefix() +value+") AND (intField > 20080101))"; assertEquals("Select with multiple where clauses", expectedSql, testDialect.convertStatementToSQL(stmt)); }
void function() { SelectStatement stmt = new SelectStatement().from(new TableReference(TEST_TABLE)) .where(Criterion.and( Criterion.eq(new FieldReference(STRING_FIELD), "A0001"), Criterion.greaterThan(new FieldReference(INT_FIELD), new Integer(20080101)))); String value = varCharCast(STR); String expectedSql = STR + tableName(TEST_TABLE) + STR + stringLiteralPrefix() +value+STR; assertEquals(STR, expectedSql, testDialect.convertStatementToSQL(stmt)); }
/** * Tests a select with a nested "and where" clause. */
Tests a select with a nested "and where" clause
testSelectNestedAndWhereScript
{ "repo_name": "badgerwithagun/morf", "path": "morf-testsupport/src/main/java/org/alfasoftware/morf/jdbc/AbstractSqlDialectTest.java", "license": "apache-2.0", "size": 201465 }
[ "org.alfasoftware.morf.sql.SelectStatement", "org.alfasoftware.morf.sql.element.Criterion", "org.alfasoftware.morf.sql.element.FieldReference", "org.alfasoftware.morf.sql.element.TableReference", "org.junit.Assert", "org.mockito.Matchers" ]
import org.alfasoftware.morf.sql.SelectStatement; import org.alfasoftware.morf.sql.element.Criterion; import org.alfasoftware.morf.sql.element.FieldReference; import org.alfasoftware.morf.sql.element.TableReference; import org.junit.Assert; import org.mockito.Matchers;
import org.alfasoftware.morf.sql.*; import org.alfasoftware.morf.sql.element.*; import org.junit.*; import org.mockito.*;
[ "org.alfasoftware.morf", "org.junit", "org.mockito" ]
org.alfasoftware.morf; org.junit; org.mockito;
2,713,242
public void extractMetadata(ContentItem item) { MediaContent mediaContent = item.getMediaContent(); if (mediaContent != null) { String mime_type = mediaContent.getMimeType(); if (mime_type == null || mime_type.equals("")) { throw new InvalidArgumentException( "the mime type of the content item was not set correctly"); } String iw_type = "MultimediaObject"; if (mime_type.startsWith("image")) { iw_type = "Image"; } else if (mime_type.startsWith("video/flash")) { iw_type = "FlashVideo"; } else if (mime_type.startsWith("video")) { iw_type = "Video"; } else if (mime_type.startsWith("application/pdf")) { iw_type = "PDFDocument"; } else if (mime_type.startsWith("application/msword")) { iw_type = "MSWordDocument"; } else if (mime_type .startsWith("application/vnd.oasis.opendocument") || mime_type.startsWith("application/postscript") || mime_type.startsWith("application/vnd.ms-")) { iw_type = "Document"; } else if (mime_type.startsWith("audio/mpeg") || mime_type.startsWith("audio/mp3")) { iw_type = "MP3Audio"; } else if (mime_type.startsWith("audio")) { iw_type = "Audio"; } KiWiResource subject = item.getResource(); KiWiResource t_image = tripleStore.createUriResource(Constants.NS_KIWI_CORE + iw_type); // set type to image so that the renderer can determine the type // correctly try { subject.addOutgoingNode("<" + Constants.NS_RDF + "type" + ">", t_image); // set the mime type properly subject.setProperty( "<" + Constants.NS_KIWI_CORE + "mimeType" + ">", mime_type); } catch (NamespaceResolvingException e1) { e1.printStackTrace(); } // ontology.begin(); if (mime_type.startsWith("image")) { // Store EXIF metadata, if the exif ontology is loaded try { Metadata metadata = JpegMetadataReader .readMetadata(mediaContent.getDataInputStream()); // iterate through metadata directories Iterator directories = metadata.getDirectoryIterator(); while (directories.hasNext()) { Directory directory = (Directory) directories.next(); // iterate through tags and print to System.out Iterator tags = directory.getTagIterator(); while (tags.hasNext()) { Tag tag = (Tag) tags.next(); // use Tag.toString() KiWiResource prop = getEXIFProperty(tag.getTagType(),tag.getTagName().toLowerCase()); if (prop != null) { try { try { subject.setProperty(prop.getSeRQLID(), tag.getDescription()); } catch (NamespaceResolvingException e) { e.printStackTrace(); } } catch (MetadataException e) { log.warn("error extracting metadata for tag #0 (id: #1)", tag.getTagName(), tag.getTagType()); } } } } } catch (JpegProcessingException ex) { log.error(ex); } } else if (mime_type.startsWith("application/pdf")) { // for PDF documents, we extract the metadata using PDFBox and // store it in appropriate // Dublin Core elements try { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); PDDocument doc = PDDocument.load(mediaContent.getDataInputStream()); PDDocumentInformation info = doc.getDocumentInformation(); if (info.getAuthor() != null && !info.getAuthor().equals("")) try { subject.setProperty("<" + Constants.NS_DC + "creator" + ">", info.getAuthor()); } catch (NamespaceResolvingException e) { e.printStackTrace(); } if (info.getSubject() != null && !info.getSubject().equals("")) try { subject.setProperty("<" + Constants.NS_DC + "subject" + ">", info.getSubject()); } catch (NamespaceResolvingException e) { e.printStackTrace(); } if (info.getTitle() != null && !info.getTitle().equals("")) try { subject.setProperty("<" + Constants.NS_DC + "title" + ">", info.getTitle()); } catch (NamespaceResolvingException e) { e.printStackTrace(); } if (info.getModificationDate() != null) { try { subject.setProperty("<" + Constants.NS_DC + "date" + ">", df.format(info.getModificationDate().getTime())); } catch (NamespaceResolvingException e) { e.printStackTrace(); } } doc.close(); } catch (IOException ex) { log.error("I/O error while extracting PDF metadata (should never happen): ",ex); } } else if (mime_type.startsWith("application/msword") || mime_type.startsWith("application/vnd.ms-")) { // for MS Office documents, we extract the metadata using POI // and store it in appropriate // Dublin Core elements try { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); HWPFDocument doc = new HWPFDocument(mediaContent.getDataInputStream()); SummaryInformation info = doc.getSummaryInformation(); DocumentSummaryInformation info2 = doc .getDocumentSummaryInformation(); if (info.getAuthor() != null && !info.getAuthor().equals("")) try { subject.setProperty("<" + Constants.NS_DC + "creator" + ">", info.getAuthor()); } catch (NamespaceResolvingException e) { e.printStackTrace(); } if (info.getSubject() != null && !info.getSubject().equals("")) try { subject.setProperty("<" + Constants.NS_DC + "subject" + ">", info.getSubject()); } catch (NamespaceResolvingException e) { e.printStackTrace(); } if (info.getTitle() != null && !info.getTitle().equals("")) try { subject.setProperty("<" + Constants.NS_DC + "title" + ">", info.getTitle()); } catch (NamespaceResolvingException e) { e.printStackTrace(); } if (info.getLastSaveDateTime() != null) try { subject.setProperty("<" + Constants.NS_DC + "date" + ">", df.format(info.getLastSaveDateTime().getTime())); } catch (NamespaceResolvingException e) { e.printStackTrace(); } if (info.getKeywords() != null && !info.getKeywords().equals("")) try { subject.setProperty("<" + Constants.NS_DC + "subject" + ">", info.getTitle()); } catch (NamespaceResolvingException e) { e.printStackTrace(); } if (info2.getCompany() != null && !info2.getCompany().equals("")) try { subject.setProperty("<" + Constants.NS_DC + "publisher" + ">", info.getTitle()); } catch (NamespaceResolvingException e) { e.printStackTrace(); } } catch (IOException ex) { log.error("I/O error while extracting MS Office metadata (should never happen): ", ex); } } } else { log.error("the content item #0 does not contain media content", item.getResource().getKiwiIdentifier()); } }
void function(ContentItem item) { MediaContent mediaContent = item.getMediaContent(); if (mediaContent != null) { String mime_type = mediaContent.getMimeType(); if (mime_type == null mime_type.equals(STRthe mime type of the content item was not set correctlySTRMultimediaObjectSTRimageSTRImageSTRvideo/flashSTRFlashVideoSTRvideoSTRVideoSTRapplication/pdfSTRPDFDocumentSTRapplication/mswordSTRMSWordDocumentSTRapplication/vnd.oasis.opendocumentSTRapplication/postscriptSTRapplication/vnd.ms-STRDocumentSTRaudio/mpegSTRaudio/mp3STRMP3AudioSTRaudioSTRAudioSTR<STRtypeSTR>STR<STRmimeTypeSTR>STRimageSTRerror extracting metadata for tag #0 (id: #1)STRapplication/pdfSTRyyyy-MM-dd HH:mmSTRSTR<STRcreatorSTR>STRSTR<STRsubjectSTR>STRSTR<STRtitleSTR>STR<STRdateSTR>STRI/O error while extracting PDF metadata (should never happen): STRapplication/mswordSTRapplication/vnd.ms-STRyyyy-MM-dd HH:mmSTRSTR<STRcreatorSTR>STRSTR<STRsubjectSTR>STRSTR<STRtitleSTR>STR<STRdateSTR>STRSTR<STRsubjectSTR>STRSTR<STRpublisherSTR>STRI/O error while extracting MS Office metadata (should never happen): STRthe content item #0 does not contain media content", item.getResource().getKiwiIdentifier()); } }
/** * Extract RDF metadata from the media content object passed as argument. * Currently works for images, for PDF documents, and for MS Word documents. * The method expects a fully specified media content with correct mime * type. */
Extract RDF metadata from the media content object passed as argument. Currently works for images, for PDF documents, and for MS Word documents. The method expects a fully specified media content with correct mime type
extractMetadata
{ "repo_name": "StexX/KiWi-OSE", "path": "src/action/kiwi/service/multimedia/MultimediaServiceImpl.java", "license": "bsd-3-clause", "size": 14993 }
[ "kiwi.model.content.ContentItem", "kiwi.model.content.MediaContent" ]
import kiwi.model.content.ContentItem; import kiwi.model.content.MediaContent;
import kiwi.model.content.*;
[ "kiwi.model.content" ]
kiwi.model.content;
2,844,093
@Override public void close() { List<Closeable> closeables = new ArrayList<>(); closeables.add(nodesService); closeables.add(injector.getInstance(TransportService.class)); for (LifecycleComponent plugin : pluginLifecycleComponents) { closeables.add(plugin); } closeables.add(() -> ThreadPool.terminate(injector.getInstance(ThreadPool.class), 10, TimeUnit.SECONDS)); closeables.add(injector.getInstance(BigArrays.class)); IOUtils.closeWhileHandlingException(closeables); }
void function() { List<Closeable> closeables = new ArrayList<>(); closeables.add(nodesService); closeables.add(injector.getInstance(TransportService.class)); for (LifecycleComponent plugin : pluginLifecycleComponents) { closeables.add(plugin); } closeables.add(() -> ThreadPool.terminate(injector.getInstance(ThreadPool.class), 10, TimeUnit.SECONDS)); closeables.add(injector.getInstance(BigArrays.class)); IOUtils.closeWhileHandlingException(closeables); }
/** * Closes the client. */
Closes the client
close
{ "repo_name": "nezirus/elasticsearch", "path": "core/src/main/java/org/elasticsearch/client/transport/TransportClient.java", "license": "apache-2.0", "size": 18756 }
[ "java.io.Closeable", "java.util.ArrayList", "java.util.List", "java.util.concurrent.TimeUnit", "org.apache.lucene.util.IOUtils", "org.elasticsearch.common.component.LifecycleComponent", "org.elasticsearch.common.util.BigArrays", "org.elasticsearch.threadpool.ThreadPool", "org.elasticsearch.transport.TransportService" ]
import java.io.Closeable; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.lucene.util.IOUtils; import org.elasticsearch.common.component.LifecycleComponent; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService;
import java.io.*; import java.util.*; import java.util.concurrent.*; import org.apache.lucene.util.*; import org.elasticsearch.common.component.*; import org.elasticsearch.common.util.*; import org.elasticsearch.threadpool.*; import org.elasticsearch.transport.*;
[ "java.io", "java.util", "org.apache.lucene", "org.elasticsearch.common", "org.elasticsearch.threadpool", "org.elasticsearch.transport" ]
java.io; java.util; org.apache.lucene; org.elasticsearch.common; org.elasticsearch.threadpool; org.elasticsearch.transport;
798,663
protected boolean isInfrastructureClass(Class<?> beanClass) { boolean retVal = Advice.class.isAssignableFrom(beanClass) || Advisor.class.isAssignableFrom(beanClass) || AopInfrastructureBean.class.isAssignableFrom(beanClass); if (retVal && logger.isTraceEnabled()) { logger.trace("Did not attempt to auto-proxy infrastructure class [" + beanClass.getName() + "]"); } return retVal; }
boolean function(Class<?> beanClass) { boolean retVal = Advice.class.isAssignableFrom(beanClass) Advisor.class.isAssignableFrom(beanClass) AopInfrastructureBean.class.isAssignableFrom(beanClass); if (retVal && logger.isTraceEnabled()) { logger.trace(STR + beanClass.getName() + "]"); } return retVal; }
/** * Return whether the given bean class represents an infrastructure class * that should never be proxied. * <p>The default implementation considers Advices, Advisors and * AopInfrastructureBeans as infrastructure classes. * @param beanClass the class of the bean * @return whether the bean represents an infrastructure class * @see org.aopalliance.aop.Advice * @see org.springframework.aop.Advisor * @see org.springframework.aop.framework.AopInfrastructureBean * @see #shouldSkip */
Return whether the given bean class represents an infrastructure class that should never be proxied. The default implementation considers Advices, Advisors and AopInfrastructureBeans as infrastructure classes
isInfrastructureClass
{ "repo_name": "kingtang/spring-learn", "path": "spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java", "license": "gpl-3.0", "size": 24104 }
[ "org.aopalliance.aop.Advice", "org.springframework.aop.Advisor", "org.springframework.aop.framework.AopInfrastructureBean" ]
import org.aopalliance.aop.Advice; import org.springframework.aop.Advisor; import org.springframework.aop.framework.AopInfrastructureBean;
import org.aopalliance.aop.*; import org.springframework.aop.*; import org.springframework.aop.framework.*;
[ "org.aopalliance.aop", "org.springframework.aop" ]
org.aopalliance.aop; org.springframework.aop;
530,227
public SplitTransition<?> getSplitTransition(Rule rule) { Preconditions.checkState(hasSplitConfigurationTransition()); return splitTransitionProvider.apply(rule); }
SplitTransition<?> function(Rule rule) { Preconditions.checkState(hasSplitConfigurationTransition()); return splitTransitionProvider.apply(rule); }
/** * Returns the split configuration transition for this attribute. * * @param rule the originating {@link Rule} which owns this attribute * @return a SplitTransition<BuildOptions> object * @throws IllegalStateException if {@link #hasSplitConfigurationTransition} is not true */
Returns the split configuration transition for this attribute
getSplitTransition
{ "repo_name": "UrbanCompass/bazel", "path": "src/main/java/com/google/devtools/build/lib/packages/Attribute.java", "license": "apache-2.0", "size": 64772 }
[ "com.google.devtools.build.lib.util.Preconditions" ]
import com.google.devtools.build.lib.util.Preconditions;
import com.google.devtools.build.lib.util.*;
[ "com.google.devtools" ]
com.google.devtools;
1,176,784
private void createTimeNarrativeShapes(final Element spTreeobj, final TrackData trackData, final Element time_tag, final Element time_anim_tag_first, final Element anim_insertion_tag_upper, final Element time_anim_tag_big, final Element time_anim_tag_big_insertion, final Element narrative_tag) { // Create parent animation object for all time box animations final ArrayList<Element> time_shape_objs = new ArrayList<>(); int coord_num = 0; final int intervalDuration = trackData.getIntervals(); int time_delay = intervalDuration; int current_time_id = Integer.parseInt(time_tag.selectFirst("p|cNvPr").attr( "id")); Application.logError2(Application.INFO, "Last Time Id::::: " + current_time_id, null); // we will get the timestamps from the first track final Track firstItem = trackData.getTracks().get(0); final ArrayList<TrackPoint> coordinates = firstItem.getPoints(); for (final TrackPoint coordinate : coordinates) { final String timestampString = coordinate.getFormattedTime(); final Element temp_time_tag = time_tag.clone(); temp_time_tag.selectFirst("p|cNvPr").attr("id", current_time_id + ""); temp_time_tag.selectFirst("p|txBody").selectFirst("a|p").selectFirst( "a|r").selectFirst("a|t").text(timestampString); time_shape_objs.add(temp_time_tag); // handle animation objs for time if (coord_num == 0) { final Element temp_time_anim = time_anim_tag_first.clone(); temp_time_anim.selectFirst("p|spTgt").attr("spid", current_time_id + ""); temp_time_anim.selectFirst("p|cond").attr("delay", "0"); temp_time_anim.selectFirst("p|cTn").attr("nodeType", "withEffect"); anim_insertion_tag_upper.insertChildren(anim_insertion_tag_upper .childNodeSize(), temp_time_anim); } else { final Element temp_time_anim = time_anim_tag_big.clone(); temp_time_anim.selectFirst("p|spTgt").attr("spid", current_time_id + ""); temp_time_anim.selectFirst("p|cond").attr("delay", time_delay + ""); time_delay += intervalDuration; temp_time_anim.selectFirst("p|cTn").attr("nodeType", "afterEffect"); temp_time_anim.selectFirst("p|par").child(0).selectFirst("p|par") .selectFirst("p|cond").attr("delay", intervalDuration + ""); time_anim_tag_big_insertion.insertChildren(time_anim_tag_big_insertion .childNodeSize(), temp_time_anim); } if (coord_num == 0) { current_time_id = 300; } current_time_id++; coord_num++; } for (final Element timeshape : time_shape_objs) { spTreeobj.insertChildren(spTreeobj.childNodeSize(), timeshape); } // Adding narratives - final ArrayList<Element> narrative_objects = new ArrayList<>(); time_delay = 0; int current_narrative_id = Integer.parseInt(narrative_tag.selectFirst( "p|cNvPr").attr("id")); Application.logError2(Application.INFO, "Last Narrative Id::::: " + current_narrative_id, null); // Blank narrative box final Element blank_narrative = narrative_tag.clone(); blank_narrative.selectFirst("p|cNvPr").attr("id", current_narrative_id + ""); blank_narrative.selectFirst("p|txBody").selectFirst("a|p").selectFirst( "a|r").selectFirst("a|t").text(""); narrative_objects.add(blank_narrative); current_narrative_id = 400; int num_narrative = 0; for (final ExportNarrativeEntry narrative : trackData.getNarrativeEntries()) { time_delay += Integer.parseInt(narrative.getElapsed()) - time_delay; final String time_str = narrative.getDateString(); final Element temp_narrative_tag = narrative_tag.clone(); temp_narrative_tag.selectFirst("p|cNvPr").attr("id", current_narrative_id + ""); temp_narrative_tag.selectFirst("p|txBody").selectFirst("a|p").selectFirst( "a|r").selectFirst("a|t").text(time_str + " " + narrative.getText()); narrative_objects.add(temp_narrative_tag); if (num_narrative == 0) { final Element temp_narrative_anim = time_anim_tag_first.clone(); temp_narrative_anim.selectFirst("p|spTgt").attr("spid", current_narrative_id + ""); temp_narrative_anim.selectFirst("p|cond").attr("delay", time_delay + ""); temp_narrative_anim.selectFirst("p|cTn").attr("nodeType", "withEffect"); anim_insertion_tag_upper.insertChildren(anim_insertion_tag_upper .childNodeSize(), temp_narrative_anim); } else { final Element temp_narrative_anim = time_anim_tag_big.clone(); temp_narrative_anim.selectFirst("p|spTgt").attr("spid", current_narrative_id + ""); temp_narrative_anim.selectFirst("p|cond").attr("delay", time_delay + ""); temp_narrative_anim.selectFirst("p|cTn").attr("nodeType", "afterEffect"); temp_narrative_anim.selectFirst("p|par").child(0).selectFirst("p|par") .selectFirst("p|cond").attr("delay", intervalDuration + ""); time_anim_tag_big_insertion.insertChildren(time_anim_tag_big_insertion .childNodeSize(), temp_narrative_anim); } current_narrative_id++; num_narrative++; } for (final Element narrative : narrative_objects) { spTreeobj.insertChildren(spTreeobj.childNodeSize(), narrative); } }
void function(final Element spTreeobj, final TrackData trackData, final Element time_tag, final Element time_anim_tag_first, final Element anim_insertion_tag_upper, final Element time_anim_tag_big, final Element time_anim_tag_big_insertion, final Element narrative_tag) { final ArrayList<Element> time_shape_objs = new ArrayList<>(); int coord_num = 0; final int intervalDuration = trackData.getIntervals(); int time_delay = intervalDuration; int current_time_id = Integer.parseInt(time_tag.selectFirst(STR).attr( "id")); Application.logError2(Application.INFO, STR + current_time_id, null); final Track firstItem = trackData.getTracks().get(0); final ArrayList<TrackPoint> coordinates = firstItem.getPoints(); for (final TrackPoint coordinate : coordinates) { final String timestampString = coordinate.getFormattedTime(); final Element temp_time_tag = time_tag.clone(); temp_time_tag.selectFirst(STR).attr("id", current_time_id + STRp txBodySTRa pSTRa rSTRa tSTRp spTgtSTRspidSTRSTRp condSTRdelaySTR0STRp cTnSTRnodeTypeSTRwithEffectSTRp spTgtSTRspidSTRSTRp condSTRdelaySTRSTRp cTnSTRnodeTypeSTRafterEffectSTRp parSTRp parSTRp condSTRdelaySTR"); time_anim_tag_big_insertion.insertChildren(time_anim_tag_big_insertion .childNodeSize(), temp_time_anim); } if (coord_num == 0) { current_time_id = 300; } current_time_id++; coord_num++; } for (final Element timeshape : time_shape_objs) { spTreeobj.insertChildren(spTreeobj.childNodeSize(), timeshape); } final ArrayList<Element> narrative_objects = new ArrayList<>(); time_delay = 0; int current_narrative_id = Integer.parseInt(narrative_tag.selectFirst( STR).attr("idSTRLast Narrative Id::::: " + current_narrative_id, null); final Element blank_narrative = narrative_tag.clone(); blank_narrative.selectFirst(STR).attr("idSTRSTRp txBodySTRa pSTRa rSTRa tSTR"); narrative_objects.add(blank_narrative); current_narrative_id = 400; int num_narrative = 0; for (final ExportNarrativeEntry narrative : trackData.getNarrativeEntries()) { time_delay += Integer.parseInt(narrative.getElapsed()) - time_delay; final String time_str = narrative.getDateString(); final Element temp_narrative_tag = narrative_tag.clone(); temp_narrative_tag.selectFirst(STR).attr("idSTRSTRp txBodySTRa pSTRa rSTRa tSTR STRp spTgtSTRspidSTRSTRp condSTRdelaySTRSTRp cTnSTRnodeTypeSTRwithEffectSTRp spTgtSTRspidSTRSTRp condSTRdelaySTRSTRp cTnSTRnodeTypeSTRafterEffectSTRp parSTRp parSTRp condSTRdelaySTR"); time_anim_tag_big_insertion.insertChildren(time_anim_tag_big_insertion .childNodeSize(), temp_narrative_anim); } current_narrative_id++; num_narrative++; } for (final Element narrative : narrative_objects) { spTreeobj.insertChildren(spTreeobj.childNodeSize(), narrative); } }
/** * Insert the narratives in the track file to the soup document * * @param spTreeobj * @param trackData * @param time_tag * @param time_anim_tag_first * @param anim_insertion_tag_upper * @param time_anim_tag_big * @param time_anim_tag_big_insertion * @param narrative_tag */
Insert the narratives in the track file to the soup document
createTimeNarrativeShapes
{ "repo_name": "theanuradha/debrief", "path": "org.mwc.debrief.legacy/src/Debrief/ReaderWriter/powerPoint/PlotTracks.java", "license": "epl-1.0", "size": 37055 }
[ "java.util.ArrayList", "org.jsoup.nodes.Element" ]
import java.util.ArrayList; import org.jsoup.nodes.Element;
import java.util.*; import org.jsoup.nodes.*;
[ "java.util", "org.jsoup.nodes" ]
java.util; org.jsoup.nodes;
2,154,129
public static void addGrassSeed(ItemStack seed, int weight) { ForgeHooks.seedList.add(new SeedEntry(seed, weight)); }
static void function(ItemStack seed, int weight) { ForgeHooks.seedList.add(new SeedEntry(seed, weight)); }
/** * Register a new seed to be dropped when breaking tall grass. * * @param seed The item to drop as a seed. * @param weight The relative probability of the seeds, * where wheat seeds are 10. */
Register a new seed to be dropped when breaking tall grass
addGrassSeed
{ "repo_name": "dogjaw2233/tiu-s-mod", "path": "build/tmp/recompileMc/sources/net/minecraftforge/common/MinecraftForge.java", "license": "lgpl-2.1", "size": 7823 }
[ "net.minecraft.item.ItemStack", "net.minecraftforge.common.ForgeHooks" ]
import net.minecraft.item.ItemStack; import net.minecraftforge.common.ForgeHooks;
import net.minecraft.item.*; import net.minecraftforge.common.*;
[ "net.minecraft.item", "net.minecraftforge.common" ]
net.minecraft.item; net.minecraftforge.common;
359,924
public Collection<DOSNAContent> loadContent(Collection<ContentMetadata> contentMD) { Collection<DOSNAContent> content = new ArrayList<>(); if (contentMD.isEmpty()) { return content; } for (ContentMetadata cmd : contentMD) { try { long startTime = System.nanoTime(); JSocialKademliaStorageEntry e = dataManager.getAndCache(cmd.getKey(), cmd.getType(), cmd.getOwnerId()); Status s = (Status) new Status().fromSerializedForm(e.getContent()); content.add(s); long endTime = System.nanoTime(); this.totalLoadingTimeTaken += (endTime - startTime); } catch (IOException | ContentNotFoundException ex) { } } return content; }
Collection<DOSNAContent> function(Collection<ContentMetadata> contentMD) { Collection<DOSNAContent> content = new ArrayList<>(); if (contentMD.isEmpty()) { return content; } for (ContentMetadata cmd : contentMD) { try { long startTime = System.nanoTime(); JSocialKademliaStorageEntry e = dataManager.getAndCache(cmd.getKey(), cmd.getType(), cmd.getOwnerId()); Status s = (Status) new Status().fromSerializedForm(e.getContent()); content.add(s); long endTime = System.nanoTime(); this.totalLoadingTimeTaken += (endTime - startTime); } catch (IOException ContentNotFoundException ex) { } } return content; }
/** * Loads the given set of content from the DHT. * * @param contentMD The metadata of the content to be loaded * * @return A collection of the content loaded from the DHT */
Loads the given set of content from the DHT
loadContent
{ "repo_name": "JoshuaKissoon/SuperDosna", "path": "src/dosna/osn/activitystream/ActivityStreamDataManager.java", "license": "mit", "size": 2383 }
[ "java.io.IOException", "java.util.ArrayList", "java.util.Collection" ]
import java.io.IOException; import java.util.ArrayList; import java.util.Collection;
import java.io.*; import java.util.*;
[ "java.io", "java.util" ]
java.io; java.util;
1,776,003
public void setDestinationMetaDataConstraints(Map destinationMetaDataConstraints) { this.destinationMetaDataConstraints = destinationMetaDataConstraints; }
void function(Map destinationMetaDataConstraints) { this.destinationMetaDataConstraints = destinationMetaDataConstraints; }
/** * Sets the destination meta data constraints setting. */
Sets the destination meta data constraints setting
setDestinationMetaDataConstraints
{ "repo_name": "tolo/JServer", "path": "src/java/com/teletalk/jserver/tcp/messaging/MessageDispatcherProperties.java", "license": "apache-2.0", "size": 7809 }
[ "java.util.Map" ]
import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
2,079,213
void setVariablesLocal(String executionId, Map<String, ? extends Object> variables);
void setVariablesLocal(String executionId, Map<String, ? extends Object> variables);
/** * Update or create given variables for an execution (not considering parent scopes). If the variables are not already existing, it will be created in the given execution. * * @param executionId * id of the execution, cannot be null. * @param variables * map containing name (key) and value of variables, can be null. * @throws FlowableObjectNotFoundException * when no execution is found for the given executionId. */
Update or create given variables for an execution (not considering parent scopes). If the variables are not already existing, it will be created in the given execution
setVariablesLocal
{ "repo_name": "marcus-nl/flowable-engine", "path": "modules/flowable-engine/src/main/java/org/flowable/engine/RuntimeService.java", "license": "apache-2.0", "size": 61256 }
[ "java.util.Map" ]
import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
367,890
public static void collectVocabularyDebates(String corpusPath, String vocabularyFile) throws Exception { SimplePipeline.runPipeline( // reader CollectionReaderFactory.createReaderDescription(FullDebateContentReader.class, FullDebateContentReader.PARAM_SOURCE_LOCATION, corpusPath), // tokenize web-texts AnalysisEngineFactory.createEngineDescription(ArktweetTokenizerFixed.class), // find sentences AnalysisEngineFactory.createEngineDescription(StanfordSegmenter.class, StanfordSegmenter.PARAM_WRITE_TOKEN, false), // lemma AnalysisEngineFactory.createEngineDescription(StanfordLemmatizer.class), AnalysisEngineFactory.createEngineDescription(VocabularyCollector.class, VocabularyCollector.PARAM_MINIMAL_OCCURRENCE, 5, VocabularyCollector.PARAM_IGNORE_STOPWORDS, true, VocabularyCollector.PARAM_MODEL_LOCATION, vocabularyFile)); }
static void function(String corpusPath, String vocabularyFile) throws Exception { SimplePipeline.runPipeline( CollectionReaderFactory.createReaderDescription(FullDebateContentReader.class, FullDebateContentReader.PARAM_SOURCE_LOCATION, corpusPath), AnalysisEngineFactory.createEngineDescription(ArktweetTokenizerFixed.class), AnalysisEngineFactory.createEngineDescription(StanfordSegmenter.class, StanfordSegmenter.PARAM_WRITE_TOKEN, false), AnalysisEngineFactory.createEngineDescription(StanfordLemmatizer.class), AnalysisEngineFactory.createEngineDescription(VocabularyCollector.class, VocabularyCollector.PARAM_MINIMAL_OCCURRENCE, 5, VocabularyCollector.PARAM_IGNORE_STOPWORDS, true, VocabularyCollector.PARAM_MODEL_LOCATION, vocabularyFile)); }
/** * Collects and stores vocabulary * * @param corpusPath corpus * @param vocabularyFile vocabulary * @throws Exception */
Collects and stores vocabulary
collectVocabularyDebates
{ "repo_name": "habernal/emnlp2015", "path": "code/experiments/src/main/java/de/tudarmstadt/ukp/experiments/argumentation/comments/pipeline/TopicModelGenerator.java", "license": "apache-2.0", "size": 6432 }
[ "de.tudarmstadt.ukp.dkpro.core.stanfordnlp.StanfordLemmatizer", "de.tudarmstadt.ukp.dkpro.core.stanfordnlp.StanfordSegmenter", "org.apache.uima.fit.factory.AnalysisEngineFactory", "org.apache.uima.fit.factory.CollectionReaderFactory", "org.apache.uima.fit.pipeline.SimplePipeline" ]
import de.tudarmstadt.ukp.dkpro.core.stanfordnlp.StanfordLemmatizer; import de.tudarmstadt.ukp.dkpro.core.stanfordnlp.StanfordSegmenter; import org.apache.uima.fit.factory.AnalysisEngineFactory; import org.apache.uima.fit.factory.CollectionReaderFactory; import org.apache.uima.fit.pipeline.SimplePipeline;
import de.tudarmstadt.ukp.dkpro.core.stanfordnlp.*; import org.apache.uima.fit.factory.*; import org.apache.uima.fit.pipeline.*;
[ "de.tudarmstadt.ukp", "org.apache.uima" ]
de.tudarmstadt.ukp; org.apache.uima;
327,001
@Test public void testJmxDoesNotExposePassword() throws Exception { final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try (Connection c = ds.getConnection()) { // nothing } final ObjectName objectName = new ObjectName(ds.getJmxName()); final MBeanAttributeInfo[] attributes = mbs.getMBeanInfo(objectName).getAttributes(); assertTrue(attributes != null && attributes.length > 0); Arrays.asList(attributes).forEach(attrInfo -> { assertFalse("password".equalsIgnoreCase(attrInfo.getName())); }); assertThrows(AttributeNotFoundException.class, () -> { mbs.getAttribute(objectName, "Password"); }); }
void function() throws Exception { final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try (Connection c = ds.getConnection()) { } final ObjectName objectName = new ObjectName(ds.getJmxName()); final MBeanAttributeInfo[] attributes = mbs.getMBeanInfo(objectName).getAttributes(); assertTrue(attributes != null && attributes.length > 0); Arrays.asList(attributes).forEach(attrInfo -> { assertFalse(STR.equalsIgnoreCase(attrInfo.getName())); }); assertThrows(AttributeNotFoundException.class, () -> { mbs.getAttribute(objectName, STR); }); }
/** * Tests JIRA <a href="https://issues.apache.org/jira/browse/DBCP-562">DBCP-562</a>. * <p> * Make sure Password Attribute is not exported via JMXBean. * </p> */
Tests JIRA DBCP-562. Make sure Password Attribute is not exported via JMXBean.
testJmxDoesNotExposePassword
{ "repo_name": "apache/commons-dbcp", "path": "src/test/java/org/apache/commons/dbcp2/TestBasicDataSource.java", "license": "apache-2.0", "size": 43003 }
[ "java.lang.management.ManagementFactory", "java.sql.Connection", "java.util.Arrays", "javax.management.AttributeNotFoundException", "javax.management.MBeanAttributeInfo", "javax.management.MBeanServer", "javax.management.ObjectName", "org.junit.jupiter.api.Assertions" ]
import java.lang.management.ManagementFactory; import java.sql.Connection; import java.util.Arrays; import javax.management.AttributeNotFoundException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanServer; import javax.management.ObjectName; import org.junit.jupiter.api.Assertions;
import java.lang.management.*; import java.sql.*; import java.util.*; import javax.management.*; import org.junit.jupiter.api.*;
[ "java.lang", "java.sql", "java.util", "javax.management", "org.junit.jupiter" ]
java.lang; java.sql; java.util; javax.management; org.junit.jupiter;
472,489
@Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); } return itemPropertyDescriptors; }
List<IItemPropertyDescriptor> function(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); } return itemPropertyDescriptors; }
/** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */
This returns the property descriptors for the adapted class.
getPropertyDescriptors
{ "repo_name": "KAMP-Research/KAMP", "path": "bundles/Toometa/toometa.options.edit/src/options/provider/OptionRepositoryItemProvider.java", "license": "apache-2.0", "size": 4795 }
[ "java.util.List", "org.eclipse.emf.edit.provider.IItemPropertyDescriptor" ]
import java.util.List; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import java.util.*; import org.eclipse.emf.edit.provider.*;
[ "java.util", "org.eclipse.emf" ]
java.util; org.eclipse.emf;
197,819
public File getWorkingDir() { return workingDir; } /** * @see {@link #getWorkingDir()}
File function() { return workingDir; } /** * @see {@link #getWorkingDir()}
/** * Gets working directory where commands are executed. By default it is project root directory. * @since 2.2.0 */
Gets working directory where commands are executed. By default it is project root directory
getWorkingDir
{ "repo_name": "mockito/mockito-release-tools", "path": "subprojects/shipkit/src/main/groovy/org/shipkit/gradle/git/GitCommitTask.java", "license": "mit", "size": 3537 }
[ "java.io.File" ]
import java.io.File;
import java.io.*;
[ "java.io" ]
java.io;
2,143,991
public void check_store_card_visibility() { CreditCardVisibilityTesterCommon.check_store_card_visibility("check_store_card_visibility" + shopperCheckoutRequirements, true); }
void function() { CreditCardVisibilityTesterCommon.check_store_card_visibility(STR + shopperCheckoutRequirements, true); }
/** * This test verifies the visibility of store card switch. * It covers visibility and switch state */
This test verifies the visibility of store card switch. It covers visibility and switch state
check_store_card_visibility
{ "repo_name": "bluesnap/bluesnap-android-int", "path": "DemoApp/src/androidTest/java/com/bluesnap/android/demoapp/BlueSnapCheckoutUITests/CheckoutNewShopperTests/MinimalBillingTests.java", "license": "mit", "size": 8425 }
[ "com.bluesnap.android.demoapp.BlueSnapCheckoutUITests" ]
import com.bluesnap.android.demoapp.BlueSnapCheckoutUITests;
import com.bluesnap.android.demoapp.*;
[ "com.bluesnap.android" ]
com.bluesnap.android;
1,923,926
static LocatedBlock prepareFileForAppend(final FSNamesystem fsn, final INodesInPath iip, final String leaseHolder, final String clientMachine, final boolean newBlock, final boolean writeToEditLog, final boolean logRetryCache) throws IOException { assert fsn.hasWriteLock(); final INodeFile file = iip.getLastINode().asFile(); final QuotaCounts delta = verifyQuotaForUCBlock(fsn, file, iip); file.recordModification(iip.getLatestSnapshotId()); file.toUnderConstruction(leaseHolder, clientMachine); fsn.getLeaseManager().addLease( file.getFileUnderConstructionFeature().getClientName(), file.getId()); LocatedBlock ret = null; if (!newBlock) { FSDirectory fsd = fsn.getFSDirectory(); ret = fsd.getBlockManager().convertLastBlockToUnderConstruction(file, 0); if (ret != null && delta != null) { Preconditions.checkState(delta.getStorageSpace() >= 0, "appending to" + " a block with size larger than the preferred block size"); fsd.writeLock(); try { fsd.updateCountNoQuotaCheck(iip, iip.length() - 1, delta); } finally { fsd.writeUnlock(); } } } else { BlockInfo lastBlock = file.getLastBlock(); if (lastBlock != null) { ExtendedBlock blk = new ExtendedBlock(fsn.getBlockPoolId(), lastBlock); ret = new LocatedBlock(blk, DatanodeInfo.EMPTY_ARRAY); } } if (writeToEditLog) { final String path = iip.getPath(); if (NameNodeLayoutVersion.supports(Feature.APPEND_NEW_BLOCK, fsn.getEffectiveLayoutVersion())) { fsn.getEditLog().logAppendFile(path, file, newBlock, logRetryCache); } else { fsn.getEditLog().logOpenFile(path, file, false, logRetryCache); } } return ret; }
static LocatedBlock prepareFileForAppend(final FSNamesystem fsn, final INodesInPath iip, final String leaseHolder, final String clientMachine, final boolean newBlock, final boolean writeToEditLog, final boolean logRetryCache) throws IOException { assert fsn.hasWriteLock(); final INodeFile file = iip.getLastINode().asFile(); final QuotaCounts delta = verifyQuotaForUCBlock(fsn, file, iip); file.recordModification(iip.getLatestSnapshotId()); file.toUnderConstruction(leaseHolder, clientMachine); fsn.getLeaseManager().addLease( file.getFileUnderConstructionFeature().getClientName(), file.getId()); LocatedBlock ret = null; if (!newBlock) { FSDirectory fsd = fsn.getFSDirectory(); ret = fsd.getBlockManager().convertLastBlockToUnderConstruction(file, 0); if (ret != null && delta != null) { Preconditions.checkState(delta.getStorageSpace() >= 0, STR + STR); fsd.writeLock(); try { fsd.updateCountNoQuotaCheck(iip, iip.length() - 1, delta); } finally { fsd.writeUnlock(); } } } else { BlockInfo lastBlock = file.getLastBlock(); if (lastBlock != null) { ExtendedBlock blk = new ExtendedBlock(fsn.getBlockPoolId(), lastBlock); ret = new LocatedBlock(blk, DatanodeInfo.EMPTY_ARRAY); } } if (writeToEditLog) { final String path = iip.getPath(); if (NameNodeLayoutVersion.supports(Feature.APPEND_NEW_BLOCK, fsn.getEffectiveLayoutVersion())) { fsn.getEditLog().logAppendFile(path, file, newBlock, logRetryCache); } else { fsn.getEditLog().logOpenFile(path, file, false, logRetryCache); } } return ret; }
/** * Convert current node to under construction. * Recreate in-memory lease record. * * @param fsn namespace * @param iip inodes in the path containing the file * @param leaseHolder identifier of the lease holder on this file * @param clientMachine identifier of the client machine * @param newBlock if the data is appended to a new block * @param writeToEditLog whether to persist this change to the edit log * @param logRetryCache whether to record RPC ids in editlog for retry cache * rebuilding * @return the last block locations if the block is partial or null otherwise * @throws IOException */
Convert current node to under construction. Recreate in-memory lease record
prepareFileForAppend
{ "repo_name": "JingchengDu/hadoop", "path": "hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSDirAppendOp.java", "license": "apache-2.0", "size": 11035 }
[ "java.io.IOException", "org.apache.hadoop.hdfs.protocol.DatanodeInfo", "org.apache.hadoop.hdfs.protocol.ExtendedBlock", "org.apache.hadoop.hdfs.protocol.LocatedBlock", "org.apache.hadoop.hdfs.server.blockmanagement.BlockInfo", "org.apache.hadoop.hdfs.server.namenode.NameNodeLayoutVersion", "org.apache.hadoop.util.Preconditions" ]
import java.io.IOException; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.protocol.ExtendedBlock; import org.apache.hadoop.hdfs.protocol.LocatedBlock; import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfo; import org.apache.hadoop.hdfs.server.namenode.NameNodeLayoutVersion; import org.apache.hadoop.util.Preconditions;
import java.io.*; import org.apache.hadoop.hdfs.protocol.*; import org.apache.hadoop.hdfs.server.blockmanagement.*; import org.apache.hadoop.hdfs.server.namenode.*; import org.apache.hadoop.util.*;
[ "java.io", "org.apache.hadoop" ]
java.io; org.apache.hadoop;
111,459
public DiGraph<Function, Callsite> getBackwardDirectedGraph() { return constructDirectedGraph(false); }
DiGraph<Function, Callsite> function() { return constructDirectedGraph(false); }
/** * Constructs and returns a directed graph where the nodes are functions and * the edges are callsites connecting callees to callers. * * It is safe to call this method on both forward and backwardly constructed * CallGraphs. */
Constructs and returns a directed graph where the nodes are functions and the edges are callsites connecting callees to callers. It is safe to call this method on both forward and backwardly constructed CallGraphs
getBackwardDirectedGraph
{ "repo_name": "110035/kissy", "path": "tools/module-compiler/src/com/google/javascript/jscomp/CallGraph.java", "license": "mit", "size": 26034 }
[ "com.google.javascript.jscomp.graph.DiGraph" ]
import com.google.javascript.jscomp.graph.DiGraph;
import com.google.javascript.jscomp.graph.*;
[ "com.google.javascript" ]
com.google.javascript;
1,125,444
void notifyAlert(final Alert alert);
void notifyAlert(final Alert alert);
/** * Notifies both system and member alerts */
Notifies both system and member alerts
notifyAlert
{ "repo_name": "robertoandrade/cyclos", "path": "src/nl/strohalm/cyclos/utils/notifications/AdminNotificationHandler.java", "license": "gpl-2.0", "size": 2275 }
[ "nl.strohalm.cyclos.entities.alerts.Alert" ]
import nl.strohalm.cyclos.entities.alerts.Alert;
import nl.strohalm.cyclos.entities.alerts.*;
[ "nl.strohalm.cyclos" ]
nl.strohalm.cyclos;
1,725,986
@Test(groups = "unit") public void minValue() { String json = "[]"; PartitionKeyInternal partitionKey = PartitionKeyInternal.fromJsonString(json); assertThat(partitionKey).isEqualTo(PartitionKeyInternal.InclusiveMinimum); }
@Test(groups = "unit") void function() { String json = "[]"; PartitionKeyInternal partitionKey = PartitionKeyInternal.fromJsonString(json); assertThat(partitionKey).isEqualTo(PartitionKeyInternal.InclusiveMinimum); }
/** * Tests serialization of minimum value. */
Tests serialization of minimum value
minValue
{ "repo_name": "selvasingh/azure-sdk-for-java", "path": "sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/PartitionKeyInternalTest.java", "license": "mit", "size": 25910 }
[ "com.azure.cosmos.implementation.routing.PartitionKeyInternal", "org.assertj.core.api.AssertionsForClassTypes", "org.testng.annotations.Test" ]
import com.azure.cosmos.implementation.routing.PartitionKeyInternal; import org.assertj.core.api.AssertionsForClassTypes; import org.testng.annotations.Test;
import com.azure.cosmos.implementation.routing.*; import org.assertj.core.api.*; import org.testng.annotations.*;
[ "com.azure.cosmos", "org.assertj.core", "org.testng.annotations" ]
com.azure.cosmos; org.assertj.core; org.testng.annotations;
2,015,841
public String toString(Verbosity verbosity) { switch (verbosity) { case Id: return Integer.toString(id); case Name: return getNodeClass().shortName(); case Short: return toString(Verbosity.Id) + "|" + toString(Verbosity.Name); case Long: return toString(Verbosity.Short); case Debugger: case All: { StringBuilder str = new StringBuilder(); str.append(toString(Verbosity.Short)).append(" { "); for (Map.Entry<Object, Object> entry : getDebugProperties().entrySet()) { str.append(entry.getKey()).append("=").append(entry.getValue()).append(", "); } str.append(" }"); return str.toString(); } default: throw new RuntimeException("unknown verbosity: " + verbosity); } }
String function(Verbosity verbosity) { switch (verbosity) { case Id: return Integer.toString(id); case Name: return getNodeClass().shortName(); case Short: return toString(Verbosity.Id) + " " + toString(Verbosity.Name); case Long: return toString(Verbosity.Short); case Debugger: case All: { StringBuilder str = new StringBuilder(); str.append(toString(Verbosity.Short)).append(STR); for (Map.Entry<Object, Object> entry : getDebugProperties().entrySet()) { str.append(entry.getKey()).append("=").append(entry.getValue()).append(STR); } str.append(STR); return str.toString(); } default: throw new RuntimeException(STR + verbosity); } }
/** * Creates a String representation for this node with a given {@link Verbosity}. */
Creates a String representation for this node with a given <code>Verbosity</code>
toString
{ "repo_name": "mcberg2016/graal-core", "path": "graal/com.oracle.graal.graph/src/com/oracle/graal/graph/Node.java", "license": "gpl-2.0", "size": 43715 }
[ "com.oracle.graal.nodeinfo.Verbosity", "java.util.Map" ]
import com.oracle.graal.nodeinfo.Verbosity; import java.util.Map;
import com.oracle.graal.nodeinfo.*; import java.util.*;
[ "com.oracle.graal", "java.util" ]
com.oracle.graal; java.util;
2,489,303
@Path("/node/{node-id}/rights") @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Consumes(MediaType.APPLICATION_XML) public String getNodeRights(@CookieParam("user") String user, @CookieParam("credential") String token, @QueryParam("group") long groupId, @PathParam("node-id") String nodeUuid, @Context ServletConfig sc, @Context HttpServletRequest httpServletRequest, @HeaderParam("Accept") String accept, @QueryParam("user") Integer userId) { if (!isUUID(nodeUuid)) { throw new RestWebApplicationException(Status.BAD_REQUEST, "Not UUID"); } UserInfo ui = checkCredential(httpServletRequest, user, token, null); try { GroupRights gr = nodeManager.getRights(ui.userId, groupId, nodeUuid); String returnValue = null; if (gr != null) { if (accept.equals(MediaType.APPLICATION_JSON)) returnValue = XML.toJSONObject(returnValue).toString(); } else { throw new RestWebApplicationException(Status.FORBIDDEN, "Vous n'avez pas les droits necessaires"); } return returnValue; } catch (RestWebApplicationException ex) { throw new RestWebApplicationException(Status.FORBIDDEN, ex.getResponse().getEntity().toString()); } catch (NullPointerException ex) { throw new RestWebApplicationException(Status.NOT_FOUND, "Node " + nodeUuid + " not found"); } catch (Exception ex) { ex.printStackTrace(); logger.error(ex.getMessage() + "\n\n" + javaUtils.getCompleteStackTrace(ex)); throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage()); } }
@Path(STR) @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Consumes(MediaType.APPLICATION_XML) String function(@CookieParam("user") String user, @CookieParam(STR) String token, @QueryParam("group") long groupId, @PathParam(STR) String nodeUuid, @Context ServletConfig sc, @Context HttpServletRequest httpServletRequest, @HeaderParam(STR) String accept, @QueryParam("user") Integer userId) { if (!isUUID(nodeUuid)) { throw new RestWebApplicationException(Status.BAD_REQUEST, STR); } UserInfo ui = checkCredential(httpServletRequest, user, token, null); try { GroupRights gr = nodeManager.getRights(ui.userId, groupId, nodeUuid); String returnValue = null; if (gr != null) { if (accept.equals(MediaType.APPLICATION_JSON)) returnValue = XML.toJSONObject(returnValue).toString(); } else { throw new RestWebApplicationException(Status.FORBIDDEN, STR); } return returnValue; } catch (RestWebApplicationException ex) { throw new RestWebApplicationException(Status.FORBIDDEN, ex.getResponse().getEntity().toString()); } catch (NullPointerException ex) { throw new RestWebApplicationException(Status.NOT_FOUND, STR + nodeUuid + STR); } catch (Exception ex) { ex.printStackTrace(); logger.error(ex.getMessage() + "\n\n" + javaUtils.getCompleteStackTrace(ex)); throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage()); } }
/** * Fetch rights per role for a node. <br> * GET /rest/api/nodes/node/{node-id}/rights * * @param user * @param token * @param groupId * @param nodeUuid * @param sc * @param httpServletRequest * @param accept * @param userId * @return <node uuid=""> <role name=""> <right RD="" WR="" DL="" /> </role> * </node> */
Fetch rights per role for a node. GET /rest/api/nodes/node/{node-id}/rights
getNodeRights
{ "repo_name": "nobry/karuta-backend", "path": "karuta-webapp/src/main/java/eportfolium/com/karuta/webapp/rest/resource/NodeResource.java", "license": "apache-2.0", "size": 45285 }
[ "javax.servlet.ServletConfig", "javax.servlet.http.HttpServletRequest", "javax.ws.rs.Consumes", "javax.ws.rs.CookieParam", "javax.ws.rs.HeaderParam", "javax.ws.rs.Path", "javax.ws.rs.PathParam", "javax.ws.rs.Produces", "javax.ws.rs.QueryParam", "javax.ws.rs.core.Context", "javax.ws.rs.core.MediaType", "javax.ws.rs.core.Response", "org.json.XML" ]
import javax.servlet.ServletConfig; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.CookieParam; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.json.XML;
import javax.servlet.*; import javax.servlet.http.*; import javax.ws.rs.*; import javax.ws.rs.core.*; import org.json.*;
[ "javax.servlet", "javax.ws", "org.json" ]
javax.servlet; javax.ws; org.json;
1,666,606
public Observable<ServiceResponse<List<ServiceTierAdvisorInner>>> listServiceTierAdvisorsWithServiceResponseAsync(String resourceGroupName, String serverName, String databaseName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (serverName == null) { throw new IllegalArgumentException("Parameter serverName is required and cannot be null."); } if (databaseName == null) { throw new IllegalArgumentException("Parameter databaseName is required and cannot be null."); }
Observable<ServiceResponse<List<ServiceTierAdvisorInner>>> function(String resourceGroupName, String serverName, String databaseName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException(STR); } if (resourceGroupName == null) { throw new IllegalArgumentException(STR); } if (serverName == null) { throw new IllegalArgumentException(STR); } if (databaseName == null) { throw new IllegalArgumentException(STR); }
/** * Returns information about service tier advisors for specified database. * * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. * @param serverName The name of the Azure SQL server. * @param databaseName The name of database. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the List&lt;ServiceTierAdvisorInner&gt; object */
Returns information about service tier advisors for specified database
listServiceTierAdvisorsWithServiceResponseAsync
{ "repo_name": "anudeepsharma/azure-sdk-for-java", "path": "azure-mgmt-sql/src/main/java/com/microsoft/azure/management/sql/implementation/DatabasesInner.java", "license": "mit", "size": 166183 }
[ "com.microsoft.rest.ServiceResponse", "java.util.List" ]
import com.microsoft.rest.ServiceResponse; import java.util.List;
import com.microsoft.rest.*; import java.util.*;
[ "com.microsoft.rest", "java.util" ]
com.microsoft.rest; java.util;
2,326,686
public static void voidInstance(VoidInstance voidInstance) { voidInstance(voidInstance, OmakaseRuntimeException::new); }
static void function(VoidInstance voidInstance) { voidInstance(voidInstance, OmakaseRuntimeException::new); }
/** * Executes a {@link Throwables.VoidInstance} wrapping any exceptions in a OmakaseRuntimeException. * * @param voidInstance * a function that does not return a result * @throws OmakaseRuntimeException * if the function throws an exception. */
Executes a <code>Throwables.VoidInstance</code> wrapping any exceptions in a OmakaseRuntimeException
voidInstance
{ "repo_name": "projectomakase/omakase", "path": "omakase-commons/src/main/java/org/projectomakase/omakase/commons/functions/Throwables.java", "license": "apache-2.0", "size": 4956 }
[ "org.projectomakase.omakase.commons.exceptions.OmakaseRuntimeException" ]
import org.projectomakase.omakase.commons.exceptions.OmakaseRuntimeException;
import org.projectomakase.omakase.commons.exceptions.*;
[ "org.projectomakase.omakase" ]
org.projectomakase.omakase;
1,365,766
@Test public void getTopology() { WebTarget wt = target(); String response = wt.path("topology").request().get(String.class); JsonObject result = Json.parse(response).asObject(); assertThat(result, notNullValue()); assertThat(result.names(), hasSize(4)); assertThat(result.get("time").asLong(), is(11111L)); assertThat(result.get("clusters").asLong(), is(2L)); assertThat(result.get("devices").asLong(), is(6L)); assertThat(result.get("links").asLong(), is(4L)); }
void function() { WebTarget wt = target(); String response = wt.path(STR).request().get(String.class); JsonObject result = Json.parse(response).asObject(); assertThat(result, notNullValue()); assertThat(result.names(), hasSize(4)); assertThat(result.get("time").asLong(), is(11111L)); assertThat(result.get(STR).asLong(), is(2L)); assertThat(result.get(STR).asLong(), is(6L)); assertThat(result.get("links").asLong(), is(4L)); }
/** * Tests the topology overview. */
Tests the topology overview
getTopology
{ "repo_name": "sdnwiselab/onos", "path": "web/api/src/test/java/org/onosproject/rest/resources/TopologyResourceTest.java", "license": "apache-2.0", "size": 10347 }
[ "com.eclipsesource.json.Json", "com.eclipsesource.json.JsonObject", "javax.ws.rs.client.WebTarget", "org.hamcrest.Matchers", "org.junit.Assert" ]
import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonObject; import javax.ws.rs.client.WebTarget; import org.hamcrest.Matchers; import org.junit.Assert;
import com.eclipsesource.json.*; import javax.ws.rs.client.*; import org.hamcrest.*; import org.junit.*;
[ "com.eclipsesource.json", "javax.ws", "org.hamcrest", "org.junit" ]
com.eclipsesource.json; javax.ws; org.hamcrest; org.junit;
702,940
public static void setBitmaps(Map<Integer, ImageView> views, Map<String, Bitmap> bitmaps, Map<Integer, String> convert) { for(Entry<Integer, ImageView>entry: views.entrySet()){ Bitmap bm = bitmaps.get(convert.get(entry.getKey())); entry.getValue().setImageBitmap(bm); } }
static void function(Map<Integer, ImageView> views, Map<String, Bitmap> bitmaps, Map<Integer, String> convert) { for(Entry<Integer, ImageView>entry: views.entrySet()){ Bitmap bm = bitmaps.get(convert.get(entry.getKey())); entry.getValue().setImageBitmap(bm); } }
/** * Set bitmaps for map of imageViews. * @param views * @param bitmaps * @param convert */
Set bitmaps for map of imageViews
setBitmaps
{ "repo_name": "moriline/AMocaccino", "path": "src/and/mocaccino/AUtils.java", "license": "apache-2.0", "size": 12074 }
[ "android.graphics.Bitmap", "android.widget.ImageView", "java.util.Map" ]
import android.graphics.Bitmap; import android.widget.ImageView; import java.util.Map;
import android.graphics.*; import android.widget.*; import java.util.*;
[ "android.graphics", "android.widget", "java.util" ]
android.graphics; android.widget; java.util;
1,498,380
@Override public boolean execute(String action, JSONArray inputs, CallbackContext callbackContext) throws JSONException { if (bannerExecutor == null) { bannerExecutor = new BannerExecutor(this); } if (interstitialExecutor == null) { interstitialExecutor = new InterstitialExecutor(this); } if (rewardVideoExecutor == null) { rewardVideoExecutor = new RewardVideoExecutor(this); } PluginResult result = null; if (Actions.SET_OPTIONS.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = executeSetOptions(options, callbackContext); } else if (Actions.CREATE_BANNER.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = bannerExecutor.prepareAd(options, callbackContext); } else if (Actions.DESTROY_BANNER.equals(action)) { result = bannerExecutor.removeAd(callbackContext); } else if (Actions.REQUEST_AD.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = bannerExecutor.requestAd(options, callbackContext); } else if (Actions.SHOW_AD.equals(action)) { boolean show = inputs.optBoolean(0); result = bannerExecutor.showAd(show, callbackContext); } else if (Actions.PREPARE_INTERSTITIAL.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = interstitialExecutor.prepareAd(options, callbackContext); } else if (Actions.CREATE_INTERSTITIAL.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = interstitialExecutor.createAd(options, callbackContext); } else if (Actions.REQUEST_INTERSTITIAL.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = interstitialExecutor.requestAd(options, callbackContext); } else if (Actions.SHOW_INTERSTITIAL.equals(action)) { boolean show = inputs.optBoolean(0); result = interstitialExecutor.showAd(show, callbackContext); } else if(Actions.IS_INTERSTITIAL_READY.equals(action)) { result = interstitialExecutor.isReady(callbackContext); } else if (Actions.CREATE_REWARD_VIDEO.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = rewardVideoExecutor.prepareAd(options, callbackContext); } else if (Actions.SHOW_REWARD_VIDEO.equals(action)) { boolean show = inputs.optBoolean(0); result = rewardVideoExecutor.showAd(show, callbackContext); } else if(Actions.IS_REWARD_VIDEO_READY.equals(action)) { result = rewardVideoExecutor.isReady(callbackContext); } else { Log.d(TAG, String.format("Invalid action passed: %s", action)); result = new PluginResult(Status.INVALID_ACTION); } if (result != null) { callbackContext.sendPluginResult(result); } return true; }
boolean function(String action, JSONArray inputs, CallbackContext callbackContext) throws JSONException { if (bannerExecutor == null) { bannerExecutor = new BannerExecutor(this); } if (interstitialExecutor == null) { interstitialExecutor = new InterstitialExecutor(this); } if (rewardVideoExecutor == null) { rewardVideoExecutor = new RewardVideoExecutor(this); } PluginResult result = null; if (Actions.SET_OPTIONS.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = executeSetOptions(options, callbackContext); } else if (Actions.CREATE_BANNER.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = bannerExecutor.prepareAd(options, callbackContext); } else if (Actions.DESTROY_BANNER.equals(action)) { result = bannerExecutor.removeAd(callbackContext); } else if (Actions.REQUEST_AD.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = bannerExecutor.requestAd(options, callbackContext); } else if (Actions.SHOW_AD.equals(action)) { boolean show = inputs.optBoolean(0); result = bannerExecutor.showAd(show, callbackContext); } else if (Actions.PREPARE_INTERSTITIAL.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = interstitialExecutor.prepareAd(options, callbackContext); } else if (Actions.CREATE_INTERSTITIAL.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = interstitialExecutor.createAd(options, callbackContext); } else if (Actions.REQUEST_INTERSTITIAL.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = interstitialExecutor.requestAd(options, callbackContext); } else if (Actions.SHOW_INTERSTITIAL.equals(action)) { boolean show = inputs.optBoolean(0); result = interstitialExecutor.showAd(show, callbackContext); } else if(Actions.IS_INTERSTITIAL_READY.equals(action)) { result = interstitialExecutor.isReady(callbackContext); } else if (Actions.CREATE_REWARD_VIDEO.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = rewardVideoExecutor.prepareAd(options, callbackContext); } else if (Actions.SHOW_REWARD_VIDEO.equals(action)) { boolean show = inputs.optBoolean(0); result = rewardVideoExecutor.showAd(show, callbackContext); } else if(Actions.IS_REWARD_VIDEO_READY.equals(action)) { result = rewardVideoExecutor.isReady(callbackContext); } else { Log.d(TAG, String.format(STR, action)); result = new PluginResult(Status.INVALID_ACTION); } if (result != null) { callbackContext.sendPluginResult(result); } return true; }
/** * This is the main method for the AdMob plugin. All API calls go through here. * This method determines the action, and executes the appropriate call. * * @param action The action that the plugin should execute. * @param inputs The input parameters for the action. * @param callbackContext The callback context. * @return A PluginResult representing the result of the provided action. A * status of INVALID_ACTION is returned if the action is not recognized. */
This is the main method for the AdMob plugin. All API calls go through here. This method determines the action, and executes the appropriate call
execute
{ "repo_name": "ratson/cordova-plugin-admob-free", "path": "src/android/AdMob.java", "license": "mit", "size": 10407 }
[ "android.util.Log", "name.ratson.cordova.admob.banner.BannerExecutor", "name.ratson.cordova.admob.interstitial.InterstitialExecutor", "name.ratson.cordova.admob.rewardvideo.RewardVideoExecutor", "org.apache.cordova.CallbackContext", "org.apache.cordova.PluginResult", "org.json.JSONArray", "org.json.JSONException", "org.json.JSONObject" ]
import android.util.Log; import name.ratson.cordova.admob.banner.BannerExecutor; import name.ratson.cordova.admob.interstitial.InterstitialExecutor; import name.ratson.cordova.admob.rewardvideo.RewardVideoExecutor; import org.apache.cordova.CallbackContext; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;
import android.util.*; import name.ratson.cordova.admob.banner.*; import name.ratson.cordova.admob.interstitial.*; import name.ratson.cordova.admob.rewardvideo.*; import org.apache.cordova.*; import org.json.*;
[ "android.util", "name.ratson.cordova", "org.apache.cordova", "org.json" ]
android.util; name.ratson.cordova; org.apache.cordova; org.json;
1,416,287
public static void setPingInterval(Configuration conf, int pingInterval) { conf.setInt(PING_INTERVAL_NAME, pingInterval); }
static void function(Configuration conf, int pingInterval) { conf.setInt(PING_INTERVAL_NAME, pingInterval); }
/** * set the ping interval value in configuration * * @param conf Configuration * @param pingInterval the ping interval */
set the ping interval value in configuration
setPingInterval
{ "repo_name": "infospace/hbase", "path": "src/main/java/org/apache/hadoop/hbase/ipc/HBaseClient.java", "license": "apache-2.0", "size": 42794 }
[ "org.apache.hadoop.conf.Configuration" ]
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.*;
[ "org.apache.hadoop" ]
org.apache.hadoop;
592,458
public Map<Object, Object> getMapExpColors() { return mapExpColors; }
Map<Object, Object> function() { return mapExpColors; }
/** * Get intraExperiment colors. * * @return */
Get intraExperiment colors
getMapExpColors
{ "repo_name": "sing-group/BEW", "path": "plugins_src/bew/es/uvigo/ei/sing/bew/view/dialogs/CompareExperimentsDialog.java", "license": "gpl-3.0", "size": 12872 }
[ "java.util.Map" ]
import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
2,538,805
public void paramDuration(String scenario, Period value) { paramDurationWithServiceResponseAsync(scenario, value).toBlocking().single().getBody(); }
void function(String scenario, Period value) { paramDurationWithServiceResponseAsync(scenario, value).toBlocking().single().getBody(); }
/** * Send a post request with header values "scenario": "valid", "value": "P123DT22H14M12.011S". * * @param scenario Send a post request with header values "scenario": "valid" * @param value Send a post request with header values "P123DT22H14M12.011S" */
Send a post request with header values "scenario": "valid", "value": "P123DT22H14M12.011S"
paramDuration
{ "repo_name": "yugangw-msft/autorest", "path": "src/generator/AutoRest.Java.Tests/src/main/java/fixtures/header/implementation/HeadersImpl.java", "license": "mit", "size": 118072 }
[ "org.joda.time.Period" ]
import org.joda.time.Period;
import org.joda.time.*;
[ "org.joda.time" ]
org.joda.time;
397,241
static ThreadPool defaultIo() { return new FixedThreadPool(DEFAULT_IO_POOL_SIZE, DEFAULT_IO_THREAD_FACTORY); }
static ThreadPool defaultIo() { return new FixedThreadPool(DEFAULT_IO_POOL_SIZE, DEFAULT_IO_THREAD_FACTORY); }
/** * Factory method for creating thread pool configured for blocking I/O operations. * * @return created thread pool */
Factory method for creating thread pool configured for blocking I/O operations
defaultIo
{ "repo_name": "siy/booter-flow", "path": "src/main/java/org/rxbooter/flow/reactor/ThreadPool.java", "license": "apache-2.0", "size": 2887 }
[ "org.rxbooter.flow.reactor.impl.FixedThreadPool" ]
import org.rxbooter.flow.reactor.impl.FixedThreadPool;
import org.rxbooter.flow.reactor.impl.*;
[ "org.rxbooter.flow" ]
org.rxbooter.flow;
2,223,710
@Override public boolean supportsMinimumSQLGrammar() throws SQLException { return false; }
boolean function() throws SQLException { return false; }
/** * <p> * <h1>Implementation Details:</h1><br> * Returns false * </p> */
Implementation Details: Returns false
supportsMinimumSQLGrammar
{ "repo_name": "jonathanswenson/starschema-bigquery-jdbc", "path": "src/main/java/net/starschema/clouddb/jdbc/BQDatabaseMetadata.java", "license": "bsd-2-clause", "size": 92438 }
[ "java.sql.SQLException" ]
import java.sql.SQLException;
import java.sql.*;
[ "java.sql" ]
java.sql;
1,012,255
public void execute() throws MojoExecutionException, MojoFailureException { String skip = System.getProperties().getProperty("maven.test.skip"); if (skip == null || "false".equals(skip)) { // lets log a INFO about how to skip tests if you want to so you can run faster getLog().info("You can skip tests from the command line using: mvn camel:run -Dmaven.test.skip=true"); } boolean usingSpringJavaConfigureMain = false; boolean useCdiMain; if (useCDI != null) { // use configured value useCdiMain = useCDI; } else { // auto detect if we have cdi useCdiMain = detectCDIOnClassPath(); } boolean usingBlueprintMain; if (useBlueprint != null) { // use configured value usingBlueprintMain = useBlueprint; } else { // auto detect if we have blueprint usingBlueprintMain = detectBlueprintOnClassPathOrBlueprintXMLFiles(); } if (killAfter != -1) { getLog().warn("Warning: killAfter is now deprecated. Do you need it ? Please comment on MEXEC-6."); } // lets create the command line arguments to pass in... List<String> args = new ArrayList<>(); if (trace) { args.add("-t"); } if (fileWatcherDirectory != null) { args.add("-watch"); args.add(fileWatcherDirectory); } if (applicationContextUri != null) { args.add("-ac"); args.add(applicationContextUri); } else if (fileApplicationContextUri != null) { args.add("-fa"); args.add(fileApplicationContextUri); } if (configClasses != null) { args.add("-cc"); args.add(configClasses); usingSpringJavaConfigureMain = true; } if (basedPackages != null) { args.add("-bp"); args.add(basedPackages); usingSpringJavaConfigureMain = true; } if (!duration.equals("-1")) { args.add("-d"); args.add(duration); } if (!durationIdle.equals("-1")) { args.add("-di"); args.add(durationIdle); } if (!durationMaxMessages.equals("-1")) { args.add("-dm"); args.add(durationMaxMessages); } if (arguments != null) { args.addAll(Arrays.asList(arguments)); } if (usingSpringJavaConfigureMain) { mainClass = "org.apache.camel.spring.javaconfig.Main"; getLog().info("Using org.apache.camel.spring.javaconfig.Main to initiate a CamelContext"); } else if (useCdiMain) { mainClass = "org.apache.camel.cdi.Main"; // must include plugin dependencies for cdi extraPluginDependencyArtifactId = "camel-cdi"; getLog().info("Using " + mainClass + " to initiate a CamelContext"); } else if (usingBlueprintMain) { mainClass = "org.apache.camel.test.blueprint.Main"; // must include plugin dependencies for blueprint extraPluginDependencyArtifactId = "camel-test-blueprint"; // set the configAdmin pid if (configAdminPid != null) { args.add("-pid"); args.add(configAdminPid); } // set the configAdmin pFile if (configAdminFileName != null) { args.add("-pf"); args.add(configAdminFileName); } getLog().info("Using org.apache.camel.test.blueprint.Main to initiate a CamelContext"); } else if (mainClass != null) { getLog().info("Using custom " + mainClass + " to initiate a CamelContext"); } else { // use spring by default getLog().info("Using org.apache.camel.spring.Main to initiate a CamelContext"); mainClass = "org.apache.camel.spring.Main"; } arguments = new String[args.size()]; args.toArray(arguments); if (getLog().isDebugEnabled()) { StringBuilder msg = new StringBuilder("Invoking: "); msg.append(mainClass); msg.append(".main("); for (int i = 0; i < arguments.length; i++) { if (i > 0) { msg.append(", "); } msg.append(arguments[i]); } msg.append(")"); getLog().debug(msg); }
void function() throws MojoExecutionException, MojoFailureException { String skip = System.getProperties().getProperty(STR); if (skip == null "false".equals(skip)) { getLog().info(STR); } boolean usingSpringJavaConfigureMain = false; boolean useCdiMain; if (useCDI != null) { useCdiMain = useCDI; } else { useCdiMain = detectCDIOnClassPath(); } boolean usingBlueprintMain; if (useBlueprint != null) { usingBlueprintMain = useBlueprint; } else { usingBlueprintMain = detectBlueprintOnClassPathOrBlueprintXMLFiles(); } if (killAfter != -1) { getLog().warn(STR); } List<String> args = new ArrayList<>(); if (trace) { args.add("-t"); } if (fileWatcherDirectory != null) { args.add(STR); args.add(fileWatcherDirectory); } if (applicationContextUri != null) { args.add("-ac"); args.add(applicationContextUri); } else if (fileApplicationContextUri != null) { args.add("-fa"); args.add(fileApplicationContextUri); } if (configClasses != null) { args.add("-cc"); args.add(configClasses); usingSpringJavaConfigureMain = true; } if (basedPackages != null) { args.add("-bp"); args.add(basedPackages); usingSpringJavaConfigureMain = true; } if (!duration.equals("-1")) { args.add("-d"); args.add(duration); } if (!durationIdle.equals("-1")) { args.add("-di"); args.add(durationIdle); } if (!durationMaxMessages.equals("-1")) { args.add("-dm"); args.add(durationMaxMessages); } if (arguments != null) { args.addAll(Arrays.asList(arguments)); } if (usingSpringJavaConfigureMain) { mainClass = STR; getLog().info(STR); } else if (useCdiMain) { mainClass = STR; extraPluginDependencyArtifactId = STR; getLog().info(STR + mainClass + STR); } else if (usingBlueprintMain) { mainClass = STR; extraPluginDependencyArtifactId = STR; if (configAdminPid != null) { args.add("-pid"); args.add(configAdminPid); } if (configAdminFileName != null) { args.add("-pf"); args.add(configAdminFileName); } getLog().info(STR); } else if (mainClass != null) { getLog().info(STR + mainClass + STR); } else { getLog().info(STR); mainClass = STR; } arguments = new String[args.size()]; args.toArray(arguments); if (getLog().isDebugEnabled()) { StringBuilder msg = new StringBuilder(STR); msg.append(mainClass); msg.append(STR); for (int i = 0; i < arguments.length; i++) { if (i > 0) { msg.append(STR); } msg.append(arguments[i]); } msg.append(")"); getLog().debug(msg); }
/** * Execute goal. * * @throws MojoExecutionException execution of the main class or one of the * threads it generated failed. * @throws MojoFailureException something bad happened... */
Execute goal
execute
{ "repo_name": "kevinearls/camel", "path": "tooling/maven/camel-maven-plugin/src/main/java/org/apache/camel/maven/RunMojo.java", "license": "apache-2.0", "size": 43590 }
[ "java.util.ArrayList", "java.util.Arrays", "java.util.List", "org.apache.maven.plugin.MojoExecutionException", "org.apache.maven.plugin.MojoFailureException" ]
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException;
import java.util.*; import org.apache.maven.plugin.*;
[ "java.util", "org.apache.maven" ]
java.util; org.apache.maven;
1,172,919
private int slotIndex(final long dateQuantum) { int iInf = 0; final long qInf = slots.get(iInf).getEarliestQuantum(); int iSup = slots.size() - 1; final long qSup = slots.get(iSup).getLatestQuantum(); while (iSup - iInf > 0) { final int iInterp = (int) ((iInf * (qSup - dateQuantum) + iSup * (dateQuantum - qInf)) / (qSup - qInf)); final int iMed = FastMath.max(iInf, FastMath.min(iInterp, iSup)); final Slot slot = slots.get(iMed); if (dateQuantum < slot.getEarliestQuantum()) { iSup = iMed - 1; } else if (dateQuantum > slot.getLatestQuantum()) { iInf = FastMath.min(iSup, iMed + 1); } else { return iMed; } } return iInf; } private final class Slot { private final List<Entry> cache; private AtomicLong earliestQuantum; private AtomicLong latestQuantum; private AtomicInteger guessedIndex; private AtomicLong lastAccess; Slot(final AbsoluteDate date) throws TimeStampedCacheException { // allocate cache this.cache = new ArrayList<Entry>(); // set up first entries AbsoluteDate generationDate = date; generateCalls.incrementAndGet(); for (final T entry : generateAndCheck(null, generationDate)) { cache.add(new Entry(entry, quantum(entry.getDate()))); } earliestQuantum = new AtomicLong(cache.get(0).getQuantum()); latestQuantum = new AtomicLong(cache.get(cache.size() - 1).getQuantum()); while (cache.size() < neighborsSize) { // we need to generate more entries final T entry0 = cache.get(0).getData(); final T entryN = cache.get(cache.size() - 1).getData(); generateCalls.incrementAndGet(); final T existing; if (entryN.getDate().durationFrom(date) <= date.durationFrom(entry0.getDate())) { // generate additional point at the end of the slot existing = entryN; generationDate = entryN.getDate().shiftedBy(getMeanStep() * (neighborsSize - cache.size())); appendAtEnd(generateAndCheck(existing, generationDate)); } else { // generate additional point at the start of the slot existing = entry0; generationDate = entry0.getDate().shiftedBy(-getMeanStep() * (neighborsSize - cache.size())); insertAtStart(generateAndCheck(existing, generationDate)); } } guessedIndex = new AtomicInteger(cache.size() / 2); lastAccess = new AtomicLong(System.currentTimeMillis()); }
int function(final long dateQuantum) { int iInf = 0; final long qInf = slots.get(iInf).getEarliestQuantum(); int iSup = slots.size() - 1; final long qSup = slots.get(iSup).getLatestQuantum(); while (iSup - iInf > 0) { final int iInterp = (int) ((iInf * (qSup - dateQuantum) + iSup * (dateQuantum - qInf)) / (qSup - qInf)); final int iMed = FastMath.max(iInf, FastMath.min(iInterp, iSup)); final Slot slot = slots.get(iMed); if (dateQuantum < slot.getEarliestQuantum()) { iSup = iMed - 1; } else if (dateQuantum > slot.getLatestQuantum()) { iInf = FastMath.min(iSup, iMed + 1); } else { return iMed; } } return iInf; } private final class Slot { private final List<Entry> cache; private AtomicLong earliestQuantum; private AtomicLong latestQuantum; private AtomicInteger guessedIndex; private AtomicLong lastAccess; Slot(final AbsoluteDate date) throws TimeStampedCacheException { this.cache = new ArrayList<Entry>(); AbsoluteDate generationDate = date; generateCalls.incrementAndGet(); for (final T entry : generateAndCheck(null, generationDate)) { cache.add(new Entry(entry, quantum(entry.getDate()))); } earliestQuantum = new AtomicLong(cache.get(0).getQuantum()); latestQuantum = new AtomicLong(cache.get(cache.size() - 1).getQuantum()); while (cache.size() < neighborsSize) { final T entry0 = cache.get(0).getData(); final T entryN = cache.get(cache.size() - 1).getData(); generateCalls.incrementAndGet(); final T existing; if (entryN.getDate().durationFrom(date) <= date.durationFrom(entry0.getDate())) { existing = entryN; generationDate = entryN.getDate().shiftedBy(getMeanStep() * (neighborsSize - cache.size())); appendAtEnd(generateAndCheck(existing, generationDate)); } else { existing = entry0; generationDate = entry0.getDate().shiftedBy(-getMeanStep() * (neighborsSize - cache.size())); insertAtStart(generateAndCheck(existing, generationDate)); } } guessedIndex = new AtomicInteger(cache.size() / 2); lastAccess = new AtomicLong(System.currentTimeMillis()); }
/** Get the index of the slot in which a date could be cached. * <p> * We own a global read lock while calling this method. * </p> * @param dateQuantum quantum of the date to search for * @return the slot in which the date could be cached */
Get the index of the slot in which a date could be cached. We own a global read lock while calling this method.
slotIndex
{ "repo_name": "ProjectPersephone/Orekit", "path": "src/main/java/org/orekit/utils/GenericTimeStampedCache.java", "license": "apache-2.0", "size": 34014 }
[ "java.util.ArrayList", "java.util.List", "java.util.concurrent.atomic.AtomicInteger", "java.util.concurrent.atomic.AtomicLong", "org.apache.commons.math3.util.FastMath", "org.orekit.errors.TimeStampedCacheException", "org.orekit.time.AbsoluteDate" ]
import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.math3.util.FastMath; import org.orekit.errors.TimeStampedCacheException; import org.orekit.time.AbsoluteDate;
import java.util.*; import java.util.concurrent.atomic.*; import org.apache.commons.math3.util.*; import org.orekit.errors.*; import org.orekit.time.*;
[ "java.util", "org.apache.commons", "org.orekit.errors", "org.orekit.time" ]
java.util; org.apache.commons; org.orekit.errors; org.orekit.time;
1,802,081
private void showPopupMenu(View view, Not2DoModel not2DoModel, boolean owner) { // inflate menu PopupMenu popup = new PopupMenu(mContext, view); MenuInflater inflater = popup.getMenuInflater(); if(owner) inflater.inflate(R.menu.menu_not2do_creator, popup.getMenu()); else inflater.inflate(R.menu.menu_not2do, popup.getMenu()); popup.setOnMenuItemClickListener(new MyMenuItemClickListener(not2DoModel)); popup.show(); }
void function(View view, Not2DoModel not2DoModel, boolean owner) { PopupMenu popup = new PopupMenu(mContext, view); MenuInflater inflater = popup.getMenuInflater(); if(owner) inflater.inflate(R.menu.menu_not2do_creator, popup.getMenu()); else inflater.inflate(R.menu.menu_not2do, popup.getMenu()); popup.setOnMenuItemClickListener(new MyMenuItemClickListener(not2DoModel)); popup.show(); }
/** * Showing popup menu when tapping on 3 dots */
Showing popup menu when tapping on 3 dots
showPopupMenu
{ "repo_name": "uyarburak/Not2DoAndroidClient", "path": "app/src/main/java/bil495/not2do/fragment/MyNotDoRecyclerViewAdapter.java", "license": "gpl-3.0", "size": 6633 }
[ "android.support.v7.widget.PopupMenu", "android.view.MenuInflater", "android.view.View" ]
import android.support.v7.widget.PopupMenu; import android.view.MenuInflater; import android.view.View;
import android.support.v7.widget.*; import android.view.*;
[ "android.support", "android.view" ]
android.support; android.view;
381,845
public String getCssText(); public void setCssText(String cssText) throws DOMException;
String getCssText(); public void function(String cssText) throws DOMException;
/** * A string representation of the current value. * @exception DOMException * SYNTAX_ERR: Raised if the specified CSS string value has a syntax * error (according to the attached property) or is unparsable. * <br>INVALID_MODIFICATION_ERR: Raised if the specified CSS string * value represents a different type of values than the values allowed * by the CSS property. * <br> NO_MODIFICATION_ALLOWED_ERR: Raised if this value is readonly. */
A string representation of the current value
setCssText
{ "repo_name": "shaotuanchen/sunflower_exp", "path": "tools/source/gcc-4.2.4/libjava/classpath/external/w3c_dom/org/w3c/dom/css/CSSValue.java", "license": "bsd-3-clause", "size": 2740 }
[ "org.w3c.dom.DOMException" ]
import org.w3c.dom.DOMException;
import org.w3c.dom.*;
[ "org.w3c.dom" ]
org.w3c.dom;
2,687,736
AbstractScoreHolder<Score_> buildScoreHolder(boolean constraintMatchEnabled); /** * Builds a {@link Score} which is equal or better than any other {@link Score} with more variables initialized * (while the already variables don't change). * * @param initializingScoreTrend never null, with {@link InitializingScoreTrend#getLevelsSize()}
AbstractScoreHolder<Score_> buildScoreHolder(boolean constraintMatchEnabled); /** * Builds a {@link Score} which is equal or better than any other {@link Score} with more variables initialized * (while the already variables don't change). * * @param initializingScoreTrend never null, with {@link InitializingScoreTrend#getLevelsSize()}
/** * Used by {@link DroolsScoreDirector}. * * @param constraintMatchEnabled true if{@link InnerScoreDirector#isConstraintMatchEnabled()} should be true * @return never null */
Used by <code>DroolsScoreDirector</code>
buildScoreHolder
{ "repo_name": "droolsjbpm/optaplanner", "path": "optaplanner-core/src/main/java/org/optaplanner/core/impl/score/definition/ScoreDefinition.java", "license": "apache-2.0", "size": 7107 }
[ "org.optaplanner.core.api.score.Score", "org.optaplanner.core.impl.score.holder.AbstractScoreHolder", "org.optaplanner.core.impl.score.trend.InitializingScoreTrend" ]
import org.optaplanner.core.api.score.Score; import org.optaplanner.core.impl.score.holder.AbstractScoreHolder; import org.optaplanner.core.impl.score.trend.InitializingScoreTrend;
import org.optaplanner.core.api.score.*; import org.optaplanner.core.impl.score.holder.*; import org.optaplanner.core.impl.score.trend.*;
[ "org.optaplanner.core" ]
org.optaplanner.core;
676,260
private void updateContextMenu(Cursor cursor) { if (contextMenuUniqueId == 0) { return; } for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { long uniqueId = cursor.getLong(uniqueIdColumn); if (uniqueId == contextMenuUniqueId) { return; } } contextMenuUniqueId = 0; Activity activity = getActivity(); if (activity != null) { activity.closeContextMenu(); } }
void function(Cursor cursor) { if (contextMenuUniqueId == 0) { return; } for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { long uniqueId = cursor.getLong(uniqueIdColumn); if (uniqueId == contextMenuUniqueId) { return; } } contextMenuUniqueId = 0; Activity activity = getActivity(); if (activity != null) { activity.closeContextMenu(); } }
/** * Close the context menu when the message it was opened for is no longer in the message list. */
Close the context menu when the message it was opened for is no longer in the message list
updateContextMenu
{ "repo_name": "philipwhiuk/q-mail", "path": "qmail/src/main/java/com/fsck/k9/fragment/MessageListFragment.java", "license": "apache-2.0", "size": 101650 }
[ "android.app.Activity", "android.database.Cursor" ]
import android.app.Activity; import android.database.Cursor;
import android.app.*; import android.database.*;
[ "android.app", "android.database" ]
android.app; android.database;
2,311,840
boolean handle(ConsumeResponse consumeResponse, Quantum quantum);
boolean handle(ConsumeResponse consumeResponse, Quantum quantum);
/** * Called after a Quantum is fed to an Organism * * @param consumeResponse * @param quantum Post-feeding data Quantum. * @return If handle() returns false then all processing is stopped. */
Called after a Quantum is fed to an Organism
handle
{ "repo_name": "intermancer/predictor2-core", "path": "src/main/java/com/intermancer/predictor/feeder/FeedCycleListener.java", "license": "lgpl-3.0", "size": 662 }
[ "com.intermancer.predictor.data.ConsumeResponse", "com.intermancer.predictor.data.Quantum" ]
import com.intermancer.predictor.data.ConsumeResponse; import com.intermancer.predictor.data.Quantum;
import com.intermancer.predictor.data.*;
[ "com.intermancer.predictor" ]
com.intermancer.predictor;
2,165,382
@SuppressWarnings("unchecked") public static <I> I[] insert(Class<I> clazz, I[] array, int index, I... valuesToInsert) { I[] result = null; int k = 0; if (array == null || array.length == 0) { result = (I[]) Array.newInstance(clazz, valuesToInsert.length); for (I element : valuesToInsert) { result[k] = element; k++; } return result; } if (index < 0 || index > array.length) return null; result = (I[]) Array.newInstance(clazz, array.length + valuesToInsert.length); k = index; System.arraycopy(array, 0, result, 0, index); for (I element : valuesToInsert) { result[k] = element; k++; } System.arraycopy(array, index, result, index + valuesToInsert.length, array.length - index); return result; }
@SuppressWarnings(STR) static <I> I[] function(Class<I> clazz, I[] array, int index, I... valuesToInsert) { I[] result = null; int k = 0; if (array == null array.length == 0) { result = (I[]) Array.newInstance(clazz, valuesToInsert.length); for (I element : valuesToInsert) { result[k] = element; k++; } return result; } if (index < 0 index > array.length) return null; result = (I[]) Array.newInstance(clazz, array.length + valuesToInsert.length); k = index; System.arraycopy(array, 0, result, 0, index); for (I element : valuesToInsert) { result[k] = element; k++; } System.arraycopy(array, index, result, index + valuesToInsert.length, array.length - index); return result; }
/** * Inserts the element(s) at the specified position in the array. Shifts the * element currently at that position (if any) and any subsequent elements to * the right. Example: ArrayUtil.insert(null, 3, -12) = [-12] * ArrayUtil.insert([1], 0, 2) = [2, 1] ArrayUtil.insert([1], 1, 2, -12, 3) = * [1, 2, -12, 3] * * @param clazz - Type of Array * @param array - the array to insert the element * @param index - the position of the new object * @param valuesToInsert - the object to add * @param <I> - type of element * @return A new array containing the existing elements and the new element */
Inserts the element(s) at the specified position in the array. Shifts the element currently at that position (if any) and any subsequent elements to the right. Example: ArrayUtil.insert(null, 3, -12) = [-12] ArrayUtil.insert([1], 0, 2) = [2, 1] ArrayUtil.insert([1], 1, 2, -12, 3) = [1, 2, -12, 3]
insert
{ "repo_name": "Sriee/epi", "path": "Interview/src/util/ArrayUtil.java", "license": "gpl-3.0", "size": 92016 }
[ "java.lang.reflect.Array" ]
import java.lang.reflect.Array;
import java.lang.reflect.*;
[ "java.lang" ]
java.lang;
1,578,498
public void logMessage(Date date, String componentId, TokenContent token, Level level, String message, String exception);
void function(Date date, String componentId, TokenContent token, Level level, String message, String exception);
/** * Token reports a message * @param date time stamp of the event * @param componentId component id where the message is reported * @param token reported token * @param level logging level * @param message reported message * @param exception reported exception */
Token reports a message
logMessage
{ "repo_name": "CloverETL/CloverETL-Engine", "path": "cloveretl.engine/src/org/jetel/graph/runtime/tracker/TokenEventListener.java", "license": "lgpl-2.1", "size": 4313 }
[ "java.util.Date", "org.apache.log4j.Level" ]
import java.util.Date; import org.apache.log4j.Level;
import java.util.*; import org.apache.log4j.*;
[ "java.util", "org.apache.log4j" ]
java.util; org.apache.log4j;
454,396
@Override public void addChild(Container child) { // Global JspServlet Wrapper oldJspServlet = null; if (!(child instanceof Wrapper)) { throw new IllegalArgumentException (sm.getString("standardContext.notWrapper")); } boolean isJspServlet = "jsp".equals(child.getName()); // Allow webapp to override JspServlet inherited from global web.xml. if (isJspServlet) { oldJspServlet = (Wrapper) findChild("jsp"); if (oldJspServlet != null) { removeChild(oldJspServlet); } } super.addChild(child); if (isJspServlet && oldJspServlet != null) { String[] jspMappings = oldJspServlet.findMappings(); for (int i=0; jspMappings!=null && i<jspMappings.length; i++) { addServletMapping(jspMappings[i], child.getName()); } } }
void function(Container child) { Wrapper oldJspServlet = null; if (!(child instanceof Wrapper)) { throw new IllegalArgumentException (sm.getString(STR)); } boolean isJspServlet = "jsp".equals(child.getName()); if (isJspServlet) { oldJspServlet = (Wrapper) findChild("jsp"); if (oldJspServlet != null) { removeChild(oldJspServlet); } } super.addChild(child); if (isJspServlet && oldJspServlet != null) { String[] jspMappings = oldJspServlet.findMappings(); for (int i=0; jspMappings!=null && i<jspMappings.length; i++) { addServletMapping(jspMappings[i], child.getName()); } } }
/** * Add a child Container, only if the proposed child is an implementation * of Wrapper. * * @param child Child container to be added * * @exception IllegalArgumentException if the proposed container is * not an implementation of Wrapper */
Add a child Container, only if the proposed child is an implementation of Wrapper
addChild
{ "repo_name": "sdw2330976/apache-tomcat-7.0.57", "path": "target/classes/org/apache/catalina/core/StandardContext.java", "license": "apache-2.0", "size": 213785 }
[ "org.apache.catalina.Container", "org.apache.catalina.Wrapper" ]
import org.apache.catalina.Container; import org.apache.catalina.Wrapper;
import org.apache.catalina.*;
[ "org.apache.catalina" ]
org.apache.catalina;
2,161,649
protected File resolveFile(final String s) { if(getProject() == null) { // Note FileUtils.getFileUtils replaces FileUtils.newFileUtils in Ant 1.6.3 return FileUtils.getFileUtils().resolveFile(null, s); } else { return FileUtils.getFileUtils().resolveFile(getProject().getBaseDir(), s); } }
File function(final String s) { if(getProject() == null) { return FileUtils.getFileUtils().resolveFile(null, s); } else { return FileUtils.getFileUtils().resolveFile(getProject().getBaseDir(), s); } }
/** * Resolves the relative or absolute pathname correctly * in both Ant and command-line situations. If Ant launched * us, we should use the basedir of the current project * to resolve relative paths. * * See Bugzilla 35571. * * @param s The file * @return The file resolved */
Resolves the relative or absolute pathname correctly in both Ant and command-line situations. If Ant launched us, we should use the basedir of the current project to resolve relative paths. See Bugzilla 35571
resolveFile
{ "repo_name": "plumer/codana", "path": "tomcat_files/7.0.61/JspC.java", "license": "mit", "size": 51918 }
[ "java.io.File", "org.apache.tools.ant.util.FileUtils" ]
import java.io.File; import org.apache.tools.ant.util.FileUtils;
import java.io.*; import org.apache.tools.ant.util.*;
[ "java.io", "org.apache.tools" ]
java.io; org.apache.tools;
1,494,154
private static List<ManagedAnswer> readAnswerInput(String content) { List<ManagedAnswer> store = null; // read the CVS of label to canonical question first try ( StringReader reader = new StringReader(content); CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL); ){ // read in the csv file and get the records List<CSVRecord> records = parser.getRecords(); // now we can create the answer store because we have read the records store = new ArrayList<ManagedAnswer>(); for( CSVRecord r : records ) { // order is: LabelId, CanonicalQuestion // create the answer pojo ManagedAnswer answer = new ManagedAnswer(); answer.setClassName(r.get(0)); answer.setCanonicalQuestion(r.get(1)); answer.setType(TypeEnum.TEXT); // add to the managed answers list store.add(answer); } } catch(Exception e) { e.printStackTrace(); } return store; } private static class AnswerStoreRestClient extends SimpleRestClient { public AnswerStoreRestClient(String url, String user, String password) { super(url, user, password); }
static List<ManagedAnswer> function(String content) { List<ManagedAnswer> store = null; try ( StringReader reader = new StringReader(content); CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL); ){ List<CSVRecord> records = parser.getRecords(); store = new ArrayList<ManagedAnswer>(); for( CSVRecord r : records ) { ManagedAnswer answer = new ManagedAnswer(); answer.setClassName(r.get(0)); answer.setCanonicalQuestion(r.get(1)); answer.setType(TypeEnum.TEXT); store.add(answer); } } catch(Exception e) { e.printStackTrace(); } return store; } private static class AnswerStoreRestClient extends SimpleRestClient { public AnswerStoreRestClient(String url, String user, String password) { super(url, user, password); }
/** * Reads in the answer input file and creates a POJO for each answer it finds. If the answer has no value * it is skipped. * * @return AnswerStore - full POJO of the answer store read from the file */
Reads in the answer input file and creates a POJO for each answer it finds. If the answer has no value it is skipped
readAnswerInput
{ "repo_name": "Rygbee/questions-with-classifier-ega", "path": "questions-with-classifier-ega-war/src/main/java/com/ibm/watson/app/qaclassifier/tools/PopulateAnswerStore.java", "license": "apache-2.0", "size": 10713 }
[ "com.ibm.watson.app.common.util.rest.SimpleRestClient", "com.ibm.watson.app.qaclassifier.rest.model.ManagedAnswer", "java.io.StringReader", "java.util.ArrayList", "java.util.List", "org.apache.commons.csv.CSVFormat", "org.apache.commons.csv.CSVParser", "org.apache.commons.csv.CSVRecord" ]
import com.ibm.watson.app.common.util.rest.SimpleRestClient; import com.ibm.watson.app.qaclassifier.rest.model.ManagedAnswer; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord;
import com.ibm.watson.app.common.util.rest.*; import com.ibm.watson.app.qaclassifier.rest.model.*; import java.io.*; import java.util.*; import org.apache.commons.csv.*;
[ "com.ibm.watson", "java.io", "java.util", "org.apache.commons" ]
com.ibm.watson; java.io; java.util; org.apache.commons;
613,675
void updateServicesTopologies(@NotNull final Map<IgniteUuid, Map<UUID, Integer>> fullTops) { if (!enterBusy()) return; try { updateServicesMap(deployedServices, fullTops); } finally { leaveBusy(); } }
void updateServicesTopologies(@NotNull final Map<IgniteUuid, Map<UUID, Integer>> fullTops) { if (!enterBusy()) return; try { updateServicesMap(deployedServices, fullTops); } finally { leaveBusy(); } }
/** * Processes deployment result. * * @param fullTops Deployment topologies. */
Processes deployment result
updateServicesTopologies
{ "repo_name": "andrey-kuznetsov/ignite", "path": "modules/core/src/main/java/org/apache/ignite/internal/processors/service/IgniteServiceProcessor.java", "license": "apache-2.0", "size": 63821 }
[ "java.util.Map", "org.apache.ignite.lang.IgniteUuid", "org.jetbrains.annotations.NotNull" ]
import java.util.Map; import org.apache.ignite.lang.IgniteUuid; import org.jetbrains.annotations.NotNull;
import java.util.*; import org.apache.ignite.lang.*; import org.jetbrains.annotations.*;
[ "java.util", "org.apache.ignite", "org.jetbrains.annotations" ]
java.util; org.apache.ignite; org.jetbrains.annotations;
190,896
public void close() throws IOException { parkCursorAtEnd(); }
void function() throws IOException { parkCursorAtEnd(); }
/** * Close the scanner. Release all resources. The behavior of using the * scanner after calling close is not defined. The entry returned by the * previous entry() call will be invalid. */
Close the scanner. Release all resources. The behavior of using the scanner after calling close is not defined. The entry returned by the previous entry() call will be invalid
close
{ "repo_name": "koichi626/hadoop-gpu", "path": "hadoop-gpu-0.20.1/src/core/org/apache/hadoop/io/file/tfile/TFile.java", "license": "apache-2.0", "size": 74043 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
179,436
public List<DataSource> getDataSources() { return getRepeatingExtension(DataSource.class); }
List<DataSource> function() { return getRepeatingExtension(DataSource.class); }
/** * Returns the data sources. * * @return data sources */
Returns the data sources
getDataSources
{ "repo_name": "elhoim/gdata-client-java", "path": "java/src/com/google/gdata/data/analytics/DataFeed.java", "license": "apache-2.0", "size": 5048 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
498,508
public ResultInterface getCurrentResult(Session session) { return expressionQuery.query(0); }
ResultInterface function(Session session) { return expressionQuery.query(0); }
/** * Get the current result of the expression. The rows may not be of the same * type, therefore the rows may not be unique. * * @param session the session * @return the result */
Get the current result of the expression. The rows may not be of the same type, therefore the rows may not be unique
getCurrentResult
{ "repo_name": "titus08/frostwire-desktop", "path": "lib/jars-src/h2-1.3.164/org/h2/index/IndexCondition.java", "license": "gpl-3.0", "size": 9780 }
[ "org.h2.engine.Session", "org.h2.result.ResultInterface" ]
import org.h2.engine.Session; import org.h2.result.ResultInterface;
import org.h2.engine.*; import org.h2.result.*;
[ "org.h2.engine", "org.h2.result" ]
org.h2.engine; org.h2.result;
680,014
private List<Embedding<GradoopId>> executeStep(Embedding<GradoopId> embedding, int step) { // map containing the found matches for all pattern edges // this is necessary to be able to construct all valid permutations of edges Map<Long, Set<GradoopId>> edgeMatches = new HashMap<>(); List<Embedding<GradoopId>> results = new ArrayList<>(); // get the possible vertex matches for (GradoopId id : getCandidates(step)) { // flag to recognize failed vertex matchings boolean failed = false; // if the vertex is already in the embedding, skip it if (Arrays.asList(embedding.getVertexMapping()).contains(id)) { continue; } // get all outgoing edges of the next step vertex Collection<Edge> edges = handler.getEdgesBySourceVertexId((long) step); List<Edge> patternEdges = edges != null ? new ArrayList<>(edges) : new ArrayList<>(); // only keep those edges that have at least one vertex already in the // embedding, or are direct loops filterPatternEdges(patternEdges, embedding); // find the matches for each pattern edge for (Edge patternEdge : patternEdges) { edgeMatches.put(patternEdge.getId(), new HashSet<>()); // find all edge candidates Set<GradoopId> edgeCandidateIds = sourceDict.get(id) != null ? sourceDict.get(id) : new HashSet<>(); // for each candidate, check if it matches the pattern edge for (GradoopId edgeCandidateId : edgeCandidateIds) { Tuple3<GradoopId, GradoopId, boolean[]> edgeCandidate = edgeDict.get(edgeCandidateId); // get the target vertex of the edge GradoopId target = embedding.getVertexMapping()[ Math.toIntExact(patternEdge.getTargetVertexId())]; // if the pattern edge and the edge candidate are both loops // and the candidate matches, add it to the embedding if (isLoop(patternEdge, edgeCandidate)) { edgeMatches.get(patternEdge.getId()).add(edgeCandidateId); // else, if the candidate matches the pattern edge, // add it to the embedding } else if (matchOutgoingEdge(patternEdge, edgeCandidateId, target)) { edgeMatches.get(patternEdge.getId()).add(edgeCandidateId); } } // if there was no matching edge for a pattern edge, the candidate can be discarded if (edgeMatches.get(patternEdge.getId()).isEmpty()) { failed = true; break; } } if (failed) { continue; } // get all incoming edges of the next step vertex edges = handler.getEdgesByTargetVertexId((long) step); patternEdges = edges != null ? new ArrayList<>(edges) : new ArrayList<>(); // only keep those edges that have at least one vertex already in the // embedding, or are direct loops filterPatternEdges(patternEdges, embedding); // find the matches for each pattern edge for (Edge patternEdge : patternEdges) { edgeMatches.put(patternEdge.getId(), new HashSet<>()); // find all edge candidates Set<GradoopId> edgeCandidateIds = targetDict.get(id) != null ? targetDict.get(id) : new HashSet<>(); // for each candidate, check if it matches the pattern edge for (GradoopId edgeCandidateId : edgeCandidateIds) { Tuple3<GradoopId, GradoopId, boolean[]> edgeCandidate = edgeDict.get(edgeCandidateId); // get the target vertex of the edge GradoopId source = embedding.getVertexMapping()[ Math.toIntExact(patternEdge.getSourceVertexId())]; // if the pattern edge and the edge candidate are both loops // and the candidate matches, add it to the embedding if (isLoop(patternEdge, edgeCandidate)) { edgeMatches.get(patternEdge.getId()).add(edgeCandidateId); // else, if the candidate matches the pattern edge, // add it to the embedding } else if (matchIncomingEdge(patternEdge, edgeCandidateId, source)) { edgeMatches.get(patternEdge.getId()).add(edgeCandidateId); } } // if there was no matching edge for a pattern edge, the candidate // can be discarded if (edgeMatches.get(patternEdge.getId()).isEmpty()) { failed = true; break; } } if (failed) { continue; } // add all grown embeddings to the results results.addAll(buildNewEmbeddings(embedding, step, id, edgeMatches)); } return results; }
List<Embedding<GradoopId>> function(Embedding<GradoopId> embedding, int step) { Map<Long, Set<GradoopId>> edgeMatches = new HashMap<>(); List<Embedding<GradoopId>> results = new ArrayList<>(); for (GradoopId id : getCandidates(step)) { boolean failed = false; if (Arrays.asList(embedding.getVertexMapping()).contains(id)) { continue; } Collection<Edge> edges = handler.getEdgesBySourceVertexId((long) step); List<Edge> patternEdges = edges != null ? new ArrayList<>(edges) : new ArrayList<>(); filterPatternEdges(patternEdges, embedding); for (Edge patternEdge : patternEdges) { edgeMatches.put(patternEdge.getId(), new HashSet<>()); Set<GradoopId> edgeCandidateIds = sourceDict.get(id) != null ? sourceDict.get(id) : new HashSet<>(); for (GradoopId edgeCandidateId : edgeCandidateIds) { Tuple3<GradoopId, GradoopId, boolean[]> edgeCandidate = edgeDict.get(edgeCandidateId); GradoopId target = embedding.getVertexMapping()[ Math.toIntExact(patternEdge.getTargetVertexId())]; if (isLoop(patternEdge, edgeCandidate)) { edgeMatches.get(patternEdge.getId()).add(edgeCandidateId); } else if (matchOutgoingEdge(patternEdge, edgeCandidateId, target)) { edgeMatches.get(patternEdge.getId()).add(edgeCandidateId); } } if (edgeMatches.get(patternEdge.getId()).isEmpty()) { failed = true; break; } } if (failed) { continue; } edges = handler.getEdgesByTargetVertexId((long) step); patternEdges = edges != null ? new ArrayList<>(edges) : new ArrayList<>(); filterPatternEdges(patternEdges, embedding); for (Edge patternEdge : patternEdges) { edgeMatches.put(patternEdge.getId(), new HashSet<>()); Set<GradoopId> edgeCandidateIds = targetDict.get(id) != null ? targetDict.get(id) : new HashSet<>(); for (GradoopId edgeCandidateId : edgeCandidateIds) { Tuple3<GradoopId, GradoopId, boolean[]> edgeCandidate = edgeDict.get(edgeCandidateId); GradoopId source = embedding.getVertexMapping()[ Math.toIntExact(patternEdge.getSourceVertexId())]; if (isLoop(patternEdge, edgeCandidate)) { edgeMatches.get(patternEdge.getId()).add(edgeCandidateId); } else if (matchIncomingEdge(patternEdge, edgeCandidateId, source)) { edgeMatches.get(patternEdge.getId()).add(edgeCandidateId); } } if (edgeMatches.get(patternEdge.getId()).isEmpty()) { failed = true; break; } } if (failed) { continue; } results.addAll(buildNewEmbeddings(embedding, step, id, edgeMatches)); } return results; }
/** * Execute a step. A step corresponds to the position of the next vertex in * the vertex mappings of the embedding that shall be matched. * * @param embedding the embedding that has been constructed so far * @param step number of the next vertex to be matched * @return list of newly constructed embeddings */
Execute a step. A step corresponds to the position of the next vertex in the vertex mappings of the embedding that shall be matched
executeStep
{ "repo_name": "Venom590/gradoop", "path": "gradoop-flink/src/main/java/org/gradoop/flink/model/impl/operators/matching/transactional/algorithm/DepthSearchMatching.java", "license": "gpl-3.0", "size": 20182 }
[ "java.util.ArrayList", "java.util.Arrays", "java.util.Collection", "java.util.HashMap", "java.util.HashSet", "java.util.List", "java.util.Map", "java.util.Set", "org.apache.flink.api.java.tuple.Tuple3", "org.gradoop.common.model.impl.id.GradoopId", "org.gradoop.flink.model.impl.operators.matching.common.tuples.Embedding", "org.s1ck.gdl.model.Edge" ]
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.flink.api.java.tuple.Tuple3; import org.gradoop.common.model.impl.id.GradoopId; import org.gradoop.flink.model.impl.operators.matching.common.tuples.Embedding; import org.s1ck.gdl.model.Edge;
import java.util.*; import org.apache.flink.api.java.tuple.*; import org.gradoop.common.model.impl.id.*; import org.gradoop.flink.model.impl.operators.matching.common.tuples.*; import org.s1ck.gdl.model.*;
[ "java.util", "org.apache.flink", "org.gradoop.common", "org.gradoop.flink", "org.s1ck.gdl" ]
java.util; org.apache.flink; org.gradoop.common; org.gradoop.flink; org.s1ck.gdl;
2,187,589
public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state) { context.put("tlang", rb); context.put("contentTypeImageService", ContentTypeImageService.getInstance()); // if the synoptic options have just been imported, we need to update // the state if (state.getAttribute(STATE_UPDATE) != null) { updateState(state, portlet); state.removeAttribute(STATE_UPDATE); } // // TODO: TIMING // if (CurrentService.getInThread("DEBUG") == null) // CurrentService.setInThread("DEBUG", new StringBuilder()); // long startTime = System.currentTimeMillis(); // different title of Option link for different tools. Tool tool = ToolManager.getCurrentTool(); context.put("toolId", tool.getId()); // handle options mode if (MODE_OPTIONS.equals(state.getAttribute(STATE_MODE))) { return buildOptionsPanelContext(portlet, context, rundata, state); } // build the menu Menu bar = new MenuImpl(portlet, rundata, (String) state.getAttribute(STATE_ACTION)); // add options if allowed if (!(Boolean)state.getAttribute(STATE_HIDE_OPTIONS)) { addOptionsMenu(bar, (JetspeedRunData) rundata); } if (!bar.getItems().isEmpty()) { context.put(Menu.CONTEXT_MENU, bar); } context.put(Menu.CONTEXT_ACTION, state.getAttribute(STATE_ACTION)); // set the message length (leave as an Integer) context.put("length", state.getAttribute(STATE_LENGTH)); // set useSubject - true to display the message subject (else use the body) context.put("showSubject", state.getAttribute(STATE_SHOW_SUBJECT)); // set showBody - true to display the message body // message subject is always displayed for recent discussion tool - handled by vm context.put("showBody", state.getAttribute(STATE_SHOW_BODY)); // whether to show newlines in the message body, or not if (state.getAttribute(STATE_SHOW_NEWLINES) == null) { initStateShowNewlines(state, portlet.getPortletConfig()); } context.put("show_newlines", ((Boolean) state.getAttribute(STATE_SHOW_NEWLINES)).toString()); try { MessageService service = (MessageService) state.getAttribute(STATE_SERVICE); String channelRef = (String) state.getAttribute(STATE_CHANNEL_REF); Time afterDate = (Time) state.getAttribute(STATE_AFTER_DATE); int items = 3; // read the items parameter if (state.getAttribute(STATE_ITEMS) != null) { items = ((Integer) state.getAttribute(STATE_ITEMS)).intValue(); } String serviceName = (String) state.getAttribute(STATE_SERVICE_NAME); List messages = retrieveMessages(service, serviceName, channelRef,afterDate, items); context.put("messages", messages); } catch (PermissionException e) { addAlert(state, rb.getString("youdonot")); } // inform the observing courier that we just updated the page... // if there are pending requests to do so they can be cleared justDelivered(state); String rv = (String) getContext(rundata).get("template") + "-List"; // // TODO: TIMING // long endTime = System.currentTimeMillis(); // if (endTime-startTime > 000) // { // StringBuilder buf = (StringBuilder) CurrentService.getInThread("DEBUG"); // if (buf != null) // { // buf.insert(0,"synopticMessageAction: " // + state.getAttribute(STATE_CHANNEL_REF) // + " time: " + (endTime - startTime)); // } // } //SAK-19700 put name of tool into context so it can be rendered with the option link, for screenreaders context.put("toolTitle", ToolManager.getCurrentPlacement().getTitle()); return rv; } // buildMainPanelContext
String function(VelocityPortlet portlet, Context context, RunData rundata, SessionState state) { context.put("tlang", rb); context.put(STR, ContentTypeImageService.getInstance()); if (state.getAttribute(STATE_UPDATE) != null) { updateState(state, portlet); state.removeAttribute(STATE_UPDATE); } Tool tool = ToolManager.getCurrentTool(); context.put(STR, tool.getId()); if (MODE_OPTIONS.equals(state.getAttribute(STATE_MODE))) { return buildOptionsPanelContext(portlet, context, rundata, state); } Menu bar = new MenuImpl(portlet, rundata, (String) state.getAttribute(STATE_ACTION)); if (!(Boolean)state.getAttribute(STATE_HIDE_OPTIONS)) { addOptionsMenu(bar, (JetspeedRunData) rundata); } if (!bar.getItems().isEmpty()) { context.put(Menu.CONTEXT_MENU, bar); } context.put(Menu.CONTEXT_ACTION, state.getAttribute(STATE_ACTION)); context.put(STR, state.getAttribute(STATE_LENGTH)); context.put(STR, state.getAttribute(STATE_SHOW_SUBJECT)); context.put(STR, state.getAttribute(STATE_SHOW_BODY)); if (state.getAttribute(STATE_SHOW_NEWLINES) == null) { initStateShowNewlines(state, portlet.getPortletConfig()); } context.put(STR, ((Boolean) state.getAttribute(STATE_SHOW_NEWLINES)).toString()); try { MessageService service = (MessageService) state.getAttribute(STATE_SERVICE); String channelRef = (String) state.getAttribute(STATE_CHANNEL_REF); Time afterDate = (Time) state.getAttribute(STATE_AFTER_DATE); int items = 3; if (state.getAttribute(STATE_ITEMS) != null) { items = ((Integer) state.getAttribute(STATE_ITEMS)).intValue(); } String serviceName = (String) state.getAttribute(STATE_SERVICE_NAME); List messages = retrieveMessages(service, serviceName, channelRef,afterDate, items); context.put(STR, messages); } catch (PermissionException e) { addAlert(state, rb.getString(STR)); } justDelivered(state); String rv = (String) getContext(rundata).get(STR) + "-List"; context.put(STR, ToolManager.getCurrentPlacement().getTitle()); return rv; }
/** * build the context for the Main panel * * @return (optional) template name for this panel */
build the context for the Main panel
buildMainPanelContext
{ "repo_name": "eemirtekin/Sakai-10.6-TR", "path": "message/message-tool/tool/src/java/org/sakaiproject/message/tool/SynopticMessageAction.java", "license": "apache-2.0", "size": 28729 }
[ "java.util.List", "org.sakaiproject.cheftool.Context", "org.sakaiproject.cheftool.JetspeedRunData", "org.sakaiproject.cheftool.RunData", "org.sakaiproject.cheftool.VelocityPortlet", "org.sakaiproject.cheftool.api.Menu", "org.sakaiproject.cheftool.menu.MenuImpl", "org.sakaiproject.content.cover.ContentTypeImageService", "org.sakaiproject.event.api.SessionState", "org.sakaiproject.exception.PermissionException", "org.sakaiproject.message.api.MessageService", "org.sakaiproject.time.api.Time", "org.sakaiproject.tool.api.Tool", "org.sakaiproject.tool.cover.ToolManager" ]
import java.util.List; import org.sakaiproject.cheftool.Context; import org.sakaiproject.cheftool.JetspeedRunData; import org.sakaiproject.cheftool.RunData; import org.sakaiproject.cheftool.VelocityPortlet; import org.sakaiproject.cheftool.api.Menu; import org.sakaiproject.cheftool.menu.MenuImpl; import org.sakaiproject.content.cover.ContentTypeImageService; import org.sakaiproject.event.api.SessionState; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.message.api.MessageService; import org.sakaiproject.time.api.Time; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.tool.cover.ToolManager;
import java.util.*; import org.sakaiproject.cheftool.*; import org.sakaiproject.cheftool.api.*; import org.sakaiproject.cheftool.menu.*; import org.sakaiproject.content.cover.*; import org.sakaiproject.event.api.*; import org.sakaiproject.exception.*; import org.sakaiproject.message.api.*; import org.sakaiproject.time.api.*; import org.sakaiproject.tool.api.*; import org.sakaiproject.tool.cover.*;
[ "java.util", "org.sakaiproject.cheftool", "org.sakaiproject.content", "org.sakaiproject.event", "org.sakaiproject.exception", "org.sakaiproject.message", "org.sakaiproject.time", "org.sakaiproject.tool" ]
java.util; org.sakaiproject.cheftool; org.sakaiproject.content; org.sakaiproject.event; org.sakaiproject.exception; org.sakaiproject.message; org.sakaiproject.time; org.sakaiproject.tool;
1,549,918
public void disable() throws IOException { // This has to be synchronized or it can collide with the check in the task. synchronized (optOutLock) { // Check if the server owner has already set opt-out, if not, set it. if (!isOptOut()) { configuration.set("opt-out", true); configuration.save(configurationFile); } // Disable Task, if it is running if (task != null) { task.cancel(); task = null; } } }
void function() throws IOException { synchronized (optOutLock) { if (!isOptOut()) { configuration.set(STR, true); configuration.save(configurationFile); } if (task != null) { task.cancel(); task = null; } } }
/** * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. * * @throws java.io.IOException */
Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task
disable
{ "repo_name": "BMatteusz/bEssentials", "path": "src/org/mcstats/Metrics.java", "license": "epl-1.0", "size": 24854 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
876,394
Object processNCNAME( StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws org.xml.sax.SAXException { if (getSupportsAVT()) { AVT avt = null; try { avt = new AVT(handler, uri, name, rawName, value, owner); // If an AVT wasn't used, validate the value if ((avt.isSimple()) && (!XML11Char.isXML11ValidNCName(value))) { handleError(handler,XSLTErrorResources.INVALID_NCNAME,new Object[] {name,value},null); return null; } return avt; } catch (TransformerException te) { // thrown by AVT constructor throw new org.xml.sax.SAXException(te); } } else { if (!XML11Char.isXML11ValidNCName(value)) { handleError(handler,XSLTErrorResources.INVALID_NCNAME,new Object[] {name,value},null); return null; } return value; } }
Object processNCNAME( StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws org.xml.sax.SAXException { if (getSupportsAVT()) { AVT avt = null; try { avt = new AVT(handler, uri, name, rawName, value, owner); if ((avt.isSimple()) && (!XML11Char.isXML11ValidNCName(value))) { handleError(handler,XSLTErrorResources.INVALID_NCNAME,new Object[] {name,value},null); return null; } return avt; } catch (TransformerException te) { throw new org.xml.sax.SAXException(te); } } else { if (!XML11Char.isXML11ValidNCName(value)) { handleError(handler,XSLTErrorResources.INVALID_NCNAME,new Object[] {name,value},null); return null; } return value; } }
/** * Process an attribute string of type NCName into a String * * @param handler non-null reference to current StylesheetHandler that is constructing the Templates. * @param uri The Namespace URI, or an empty string. * @param name The local name (without prefix), or empty string if not namespace processing. * @param rawName The qualified name (with prefix). * @param value A string that represents a potentially prefix qualified name. * @param owner * * @return A String object if this attribute does not support AVT's. Otherwise, an AVT * is returned. * * @throws org.xml.sax.SAXException if the string contains a prefix that can not be * resolved, or the string contains syntax that is invalid for a NCName. */
Process an attribute string of type NCName into a String
processNCNAME
{ "repo_name": "life-beam/j2objc", "path": "xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/processor/XSLTAttributeDef.java", "license": "apache-2.0", "size": 55623 }
[ "javax.xml.transform.TransformerException", "org.apache.xalan.res.XSLTErrorResources", "org.apache.xalan.templates.ElemTemplateElement", "org.apache.xml.utils.XML11Char" ]
import javax.xml.transform.TransformerException; import org.apache.xalan.res.XSLTErrorResources; import org.apache.xalan.templates.ElemTemplateElement; import org.apache.xml.utils.XML11Char;
import javax.xml.transform.*; import org.apache.xalan.res.*; import org.apache.xalan.templates.*; import org.apache.xml.utils.*;
[ "javax.xml", "org.apache.xalan", "org.apache.xml" ]
javax.xml; org.apache.xalan; org.apache.xml;
2,707,453
interface WithUserWhitelistedIpRanges { WithCreate withUserWhitelistedIpRanges(List<String> userWhitelistedIpRanges); }
interface WithUserWhitelistedIpRanges { WithCreate withUserWhitelistedIpRanges(List<String> userWhitelistedIpRanges); }
/** * Specifies userWhitelistedIpRanges. */
Specifies userWhitelistedIpRanges
withUserWhitelistedIpRanges
{ "repo_name": "hovsepm/azure-sdk-for-java", "path": "appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/AppServiceEnvironmentResource.java", "license": "mit", "size": 20701 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
2,030,078
@Transactional public List<Release> list(String releaseNameLike) { return this.releaseRepository.findLatestDeployedOrFailed(releaseNameLike); }
List<Release> function(String releaseNameLike) { return this.releaseRepository.findLatestDeployedOrFailed(releaseNameLike); }
/** * List the latest version of releases with status of deployed or failed. * * @param releaseNameLike the wildcard name of releases to search for * @return the list of all matching releases */
List the latest version of releases with status of deployed or failed
list
{ "repo_name": "markpollack/spring-cloud-skipper", "path": "spring-cloud-skipper-server-core/src/main/java/org/springframework/cloud/skipper/server/service/ReleaseService.java", "license": "apache-2.0", "size": 14641 }
[ "java.util.List", "org.springframework.cloud.skipper.domain.Release" ]
import java.util.List; import org.springframework.cloud.skipper.domain.Release;
import java.util.*; import org.springframework.cloud.skipper.domain.*;
[ "java.util", "org.springframework.cloud" ]
java.util; org.springframework.cloud;
1,706,721
public static <C extends Collection<Literal>> C negateLiterals(final Collection<? extends Literal> literals, final Supplier<C> collectionFactory) { final C result = collectionFactory.get(); for (final Literal lit : literals) { result.add(lit.negate()); } return result; }
static <C extends Collection<Literal>> C function(final Collection<? extends Literal> literals, final Supplier<C> collectionFactory) { final C result = collectionFactory.get(); for (final Literal lit : literals) { result.add(lit.negate()); } return result; }
/** * Returns the negation of the given literals * @param literals the literals * @param collectionFactory the supplier for the collection * @param <C> the type parameters of the collection * @return the negated literals */
Returns the negation of the given literals
negateLiterals
{ "repo_name": "logic-ng/LogicNG", "path": "src/main/java/org/logicng/util/FormulaHelper.java", "license": "apache-2.0", "size": 10939 }
[ "java.util.Collection", "java.util.function.Supplier", "org.logicng.formulas.Literal" ]
import java.util.Collection; import java.util.function.Supplier; import org.logicng.formulas.Literal;
import java.util.*; import java.util.function.*; import org.logicng.formulas.*;
[ "java.util", "org.logicng.formulas" ]
java.util; org.logicng.formulas;
2,887,898
private static OrderFormatDelegate getDelegate(String name) { if (name != null && name.length() > 0) { // Check the cached array of names to see if the delegate has been configured for (int idx = 0; idx < delegates.length; idx++) { if (delegates[idx].equals(name)) { return (OrderFormatDelegate)PluginManager.getNamedPlugin(OrderFormatDelegate.class, name); } } } return null; }
static OrderFormatDelegate function(String name) { if (name != null && name.length() > 0) { for (int idx = 0; idx < delegates.length; idx++) { if (delegates[idx].equals(name)) { return (OrderFormatDelegate)PluginManager.getNamedPlugin(OrderFormatDelegate.class, name); } } } return null; }
/** * Retrieve the named delegate */
Retrieve the named delegate
getDelegate
{ "repo_name": "mdiggory/dryad-repo", "path": "dspace-api/src/main/java/org/dspace/sort/OrderFormat.java", "license": "bsd-3-clause", "size": 4282 }
[ "org.dspace.core.PluginManager" ]
import org.dspace.core.PluginManager;
import org.dspace.core.*;
[ "org.dspace.core" ]
org.dspace.core;
560,967
protected Date getMonth(int row, int column) { Calendar calendar = getCalendar(); calendar.add(Calendar.MONTH, row * calendarColumnCount + column); return calendar.getTime(); }
Date function(int row, int column) { Calendar calendar = getCalendar(); calendar.add(Calendar.MONTH, row * calendarColumnCount + column); return calendar.getTime(); }
/** * Returns the Date representing the start of the month at the given * logical position in the grid of months. <p> * * Mapping logical grid coordinates to Calendar. * * @param row the rowIndex in the grid of months. * @param column the columnIndex in the grid months. * @return a Date representing the start of the month at the given * logical coordinates. * * @see #getMonthGridPosition(Date) */
Returns the Date representing the start of the month at the given logical position in the grid of months. Mapping logical grid coordinates to Calendar
getMonth
{ "repo_name": "Mindtoeye/Hoop", "path": "src/org/jdesktop/swingx/plaf/basic/BasicMonthViewUI.java", "license": "lgpl-3.0", "size": 88932 }
[ "java.util.Calendar", "java.util.Date" ]
import java.util.Calendar; import java.util.Date;
import java.util.*;
[ "java.util" ]
java.util;
170,551
void write(boolean errorStream, int b) throws IOException { setError(errorStream); switch (b) { case '\n': super.write(BR); convertSpace = true; break; case '\t': super.write(NBSP); super.write(NBSP); break; case ' ': if (convertSpace) { super.write(NBSP); } else { super.write(b); } break; case '<': super.write(LT); break; case '>': super.write(GT); break; case '&': super.write(AMP); break; default: if (b >= 128) { super.write(("&#" + b + ";").getBytes()); } else { super.write(b); } convertSpace = false; } } }
void write(boolean errorStream, int b) throws IOException { setError(errorStream); switch (b) { case '\n': super.write(BR); convertSpace = true; break; case '\t': super.write(NBSP); super.write(NBSP); break; case ' ': if (convertSpace) { super.write(NBSP); } else { super.write(b); } break; case '<': super.write(LT); break; case '>': super.write(GT); break; case '&': super.write(AMP); break; default: if (b >= 128) { super.write(("&#" + b + ";").getBytes()); } else { super.write(b); } convertSpace = false; } } }
/** * Write a character. * * @param errorStream if the character comes from the error stream * @param b the character */
Write a character
write
{ "repo_name": "ferquies/2dam", "path": "AD/Tema 2/h2/src/test/org/h2/test/utils/OutputCatcher.java", "license": "gpl-3.0", "size": 6482 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
504,765
protected void writeSubclassFields(final JsonGenerator jgen, final T component) throws IOException { }
void function(final JsonGenerator jgen, final T component) throws IOException { }
/** * Override to serialize fields from subclasses * * @param jgen * @param component */
Override to serialize fields from subclasses
writeSubclassFields
{ "repo_name": "codeaudit/beaker-notebook", "path": "plugin/jvm/src/main/java/com/twosigma/beaker/easyform/serializer/AbstractEasyFormComponentSerializer.java", "license": "apache-2.0", "size": 1930 }
[ "java.io.IOException", "org.codehaus.jackson.JsonGenerator" ]
import java.io.IOException; import org.codehaus.jackson.JsonGenerator;
import java.io.*; import org.codehaus.jackson.*;
[ "java.io", "org.codehaus.jackson" ]
java.io; org.codehaus.jackson;
1,041,482
protected void addEmptyColumnsIfNeeded(Simulation simulation, ScenarioWithIndex scenarioWithIndex) { boolean hasGiven = false; boolean hasExpect = false; ScesimModelDescriptor simulationDescriptor = simulation.getScesimModelDescriptor(); for (FactMapping factMapping : simulationDescriptor.getFactMappings()) { FactMappingType factMappingType = factMapping.getExpressionIdentifier().getType(); if (!hasGiven && GIVEN.equals(factMappingType)) { hasGiven = true; } else if (!hasExpect && EXPECT.equals(factMappingType)) { hasExpect = true; } } if (!hasGiven) { createEmptyColumn(simulationDescriptor, scenarioWithIndex, 1, GIVEN, findNewIndexOfGroup(simulationDescriptor, GIVEN)); } if (!hasExpect) { createEmptyColumn(simulationDescriptor, scenarioWithIndex, 2, EXPECT, findNewIndexOfGroup(simulationDescriptor, EXPECT)); } }
void function(Simulation simulation, ScenarioWithIndex scenarioWithIndex) { boolean hasGiven = false; boolean hasExpect = false; ScesimModelDescriptor simulationDescriptor = simulation.getScesimModelDescriptor(); for (FactMapping factMapping : simulationDescriptor.getFactMappings()) { FactMappingType factMappingType = factMapping.getExpressionIdentifier().getType(); if (!hasGiven && GIVEN.equals(factMappingType)) { hasGiven = true; } else if (!hasExpect && EXPECT.equals(factMappingType)) { hasExpect = true; } } if (!hasGiven) { createEmptyColumn(simulationDescriptor, scenarioWithIndex, 1, GIVEN, findNewIndexOfGroup(simulationDescriptor, GIVEN)); } if (!hasExpect) { createEmptyColumn(simulationDescriptor, scenarioWithIndex, 2, EXPECT, findNewIndexOfGroup(simulationDescriptor, EXPECT)); } }
/** * If DMN model is empty, contains only inputs or only outputs this method add one GIVEN and/or EXPECT empty column * @param simulation * @param scenarioWithIndex */
If DMN model is empty, contains only inputs or only outputs this method add one GIVEN and/or EXPECT empty column
addEmptyColumnsIfNeeded
{ "repo_name": "mbiarnes/drools-wb", "path": "drools-wb-screens/drools-wb-scenario-simulation-editor/drools-wb-scenario-simulation-editor-backend/src/main/java/org/drools/workbench/screens/scenariosimulation/backend/server/util/DMNSimulationSettingsCreationStrategy.java", "license": "apache-2.0", "size": 12616 }
[ "org.drools.scenariosimulation.api.model.FactMapping", "org.drools.scenariosimulation.api.model.FactMappingType", "org.drools.scenariosimulation.api.model.ScenarioWithIndex", "org.drools.scenariosimulation.api.model.ScesimModelDescriptor", "org.drools.scenariosimulation.api.model.Simulation" ]
import org.drools.scenariosimulation.api.model.FactMapping; import org.drools.scenariosimulation.api.model.FactMappingType; import org.drools.scenariosimulation.api.model.ScenarioWithIndex; import org.drools.scenariosimulation.api.model.ScesimModelDescriptor; import org.drools.scenariosimulation.api.model.Simulation;
import org.drools.scenariosimulation.api.model.*;
[ "org.drools.scenariosimulation" ]
org.drools.scenariosimulation;
256,181
public Matrix3f set(ByteBuffer buffer) { MemUtil.INSTANCE.get(this, buffer.position(), buffer); return this; }
Matrix3f function(ByteBuffer buffer) { MemUtil.INSTANCE.get(this, buffer.position(), buffer); return this; }
/** * Set the values of this matrix by reading 9 float values from the given {@link ByteBuffer} in column-major order, * starting at its current position. * <p> * The ByteBuffer is expected to contain the values in column-major order. * <p> * The position of the ByteBuffer will not be changed by this method. * * @param buffer * the ByteBuffer to read the matrix values from in column-major order * @return this */
Set the values of this matrix by reading 9 float values from the given <code>ByteBuffer</code> in column-major order, starting at its current position. The ByteBuffer is expected to contain the values in column-major order. The position of the ByteBuffer will not be changed by this method
set
{ "repo_name": "RogueLogic/Big-Fusion", "path": "src/main/java/org/joml/Matrix3f.java", "license": "mit", "size": 132310 }
[ "java.nio.ByteBuffer" ]
import java.nio.ByteBuffer;
import java.nio.*;
[ "java.nio" ]
java.nio;
2,856,033
public static void load(Matrix matrix, ByteBuffer buffer) { int rows = matrix.getRows(); int columns = matrix.getColumns(); int index = 0; for(int column=0; column<columns; column++) { for(int row=0; row<rows; row++) { matrix.values[row][column] = buffer.getFloat(index); index += 4; } } }
static void function(Matrix matrix, ByteBuffer buffer) { int rows = matrix.getRows(); int columns = matrix.getColumns(); int index = 0; for(int column=0; column<columns; column++) { for(int row=0; row<rows; row++) { matrix.values[row][column] = buffer.getFloat(index); index += 4; } } }
/** * Loads matrix from {@code ByteBuffer} object. * @param matrix matrix to be loaded with values * @param buffer {@code ByteBuffer} to load matrix from */
Loads matrix from ByteBuffer object
load
{ "repo_name": "tomaszkax86/Legacy-OpenGL-Shadow-Mapping", "path": "src/program/geometry/Matrix.java", "license": "bsd-2-clause", "size": 20292 }
[ "java.nio.ByteBuffer" ]
import java.nio.ByteBuffer;
import java.nio.*;
[ "java.nio" ]
java.nio;
977,402
public NodeProperty getProperty(String propertyName, String resourcePath, String slideContextPath) throws SlideException, JDOMException { UriHandler uriHandler = UriHandler.getUriHandler(resourcePath); String uri = null; NodeRevisionDescriptors revisionDescriptors = null; NodeRevisionDescriptor revisionDescriptor = null; Content contentHelper = nsaToken.getContentHelper(); if (uriHandler.isVersionUri()) { uri = uriHandler.getAssociatedHistoryUri(); NodeRevisionNumber revisionNumber = new NodeRevisionNumber(uriHandler.getVersionName()); revisionDescriptors = contentHelper.retrieve(sToken, uri); revisionDescriptor = contentHelper.retrieve(sToken, revisionDescriptors, revisionNumber); } else if (uriHandler.isHistoryUri()) { uri = uriHandler.getAssociatedHistoryUri(); NodeRevisionNumber revisionNumber = new NodeRevisionNumber("0.0"); revisionDescriptors = contentHelper.retrieve(sToken, uri); revisionDescriptor = contentHelper.retrieve(sToken, revisionDescriptors, revisionNumber); } else { uri = resourcePath; revisionDescriptors = contentHelper.retrieve(sToken, uri); revisionDescriptor = contentHelper.retrieve(sToken, revisionDescriptors); } return getProperty(propertyName, revisionDescriptors, revisionDescriptor, slideContextPath); } /** * Returns the property of the resource described by * the resourcePath. * * @param propertyName the name of the property. * @param revisionDescriptors the NodeRevisionDescriptors of the resource. * @param revisionDescriptor the NodeRevisionDescriptor of the resource. * * @return the property. * * @throws SlideException * @throws JDOMException * @deprecated use {@link #getProperty(String, NodeRevisionDescriptors, NodeRevisionDescriptor, String)}
NodeProperty function(String propertyName, String resourcePath, String slideContextPath) throws SlideException, JDOMException { UriHandler uriHandler = UriHandler.getUriHandler(resourcePath); String uri = null; NodeRevisionDescriptors revisionDescriptors = null; NodeRevisionDescriptor revisionDescriptor = null; Content contentHelper = nsaToken.getContentHelper(); if (uriHandler.isVersionUri()) { uri = uriHandler.getAssociatedHistoryUri(); NodeRevisionNumber revisionNumber = new NodeRevisionNumber(uriHandler.getVersionName()); revisionDescriptors = contentHelper.retrieve(sToken, uri); revisionDescriptor = contentHelper.retrieve(sToken, revisionDescriptors, revisionNumber); } else if (uriHandler.isHistoryUri()) { uri = uriHandler.getAssociatedHistoryUri(); NodeRevisionNumber revisionNumber = new NodeRevisionNumber("0.0"); revisionDescriptors = contentHelper.retrieve(sToken, uri); revisionDescriptor = contentHelper.retrieve(sToken, revisionDescriptors, revisionNumber); } else { uri = resourcePath; revisionDescriptors = contentHelper.retrieve(sToken, uri); revisionDescriptor = contentHelper.retrieve(sToken, revisionDescriptors); } return getProperty(propertyName, revisionDescriptors, revisionDescriptor, slideContextPath); } /** * Returns the property of the resource described by * the resourcePath. * * @param propertyName the name of the property. * @param revisionDescriptors the NodeRevisionDescriptors of the resource. * @param revisionDescriptor the NodeRevisionDescriptor of the resource. * * @return the property. * * @throws SlideException * @throws JDOMException * @deprecated use {@link #getProperty(String, NodeRevisionDescriptors, NodeRevisionDescriptor, String)}
/** * Returns the property of the resource described by * the resourcePath. * * @param propertyName the name of the property. * @param resourcePath the path that identifies the resource. * @param contextPath a String , the result of HttpRequest.getContextPath() * @param servletPath a String, the result of HttpRequest.getServletPath() * * @return the property. * * @throws SlideException * @throws JDOMException */
Returns the property of the resource described by the resourcePath
getProperty
{ "repo_name": "integrated/jakarta-slide-server", "path": "maven/jakarta-slide-webdavservlet/src/main/java/org/apache/slide/webdav/util/PropertyHelper.java", "license": "apache-2.0", "size": 102956 }
[ "org.apache.slide.common.SlideException", "org.apache.slide.content.Content", "org.apache.slide.content.NodeProperty", "org.apache.slide.content.NodeRevisionDescriptor", "org.apache.slide.content.NodeRevisionDescriptors", "org.apache.slide.content.NodeRevisionNumber", "org.jdom.JDOMException" ]
import org.apache.slide.common.SlideException; import org.apache.slide.content.Content; import org.apache.slide.content.NodeProperty; import org.apache.slide.content.NodeRevisionDescriptor; import org.apache.slide.content.NodeRevisionDescriptors; import org.apache.slide.content.NodeRevisionNumber; import org.jdom.JDOMException;
import org.apache.slide.common.*; import org.apache.slide.content.*; import org.jdom.*;
[ "org.apache.slide", "org.jdom" ]
org.apache.slide; org.jdom;
417,339
public void addView(View child) { if (mRecyclerView.mAnimatingViewIndex >= 0) { addView(child, mRecyclerView.mAnimatingViewIndex); } else { addView(child, -1); } }
void function(View child) { if (mRecyclerView.mAnimatingViewIndex >= 0) { addView(child, mRecyclerView.mAnimatingViewIndex); } else { addView(child, -1); } }
/** * Add a view to the currently attached RecyclerView if needed. LayoutManagers should * use this method to add views obtained from a {@link Recycler} using * {@link Recycler#getViewForPosition(int)}. * * @param child View to add */
Add a view to the currently attached RecyclerView if needed. LayoutManagers should use this method to add views obtained from a <code>Recycler</code> using <code>Recycler#getViewForPosition(int)</code>
addView
{ "repo_name": "tasrs/XDA-One-master", "path": "libraries/recyclerview-v7/src/main/java/android/support/v7/widget/RecyclerView.java", "license": "gpl-3.0", "size": 245154 }
[ "android.view.View" ]
import android.view.View;
import android.view.*;
[ "android.view" ]
android.view;
2,335,575
public void commit() throws IOException { if (hasErrors) { completeEdit(this, false); remove(entry.key); // the previous entry is stale } else { completeEdit(this, true); } }
void function() throws IOException { if (hasErrors) { completeEdit(this, false); remove(entry.key); } else { completeEdit(this, true); } }
/** * Commits this edit so it is visible to readers. This releases the * edit lock so another edit may be started on the same key. */
Commits this edit so it is visible to readers. This releases the edit lock so another edit may be started on the same key
commit
{ "repo_name": "jlsarmientoh/AndroidHandsOn", "path": "src/com/globant/mobile/handson/util/DiskLruCache.java", "license": "apache-2.0", "size": 33911 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
649,675
static <T> TStream<T> invokeSource(Topology topology, String kind, JsonObject invokeInfo, Supplier<Iterable<T>> logic, Type tupleType, TupleSerializer outputSerializer, Map<String, Object> parameters) { parameters = copyParameters(parameters); if (outputSerializer != null) { parameters.put("outputSerializer", serializeLogic(outputSerializer)); } BOperatorInvocation source = JavaFunctional.addFunctionalOperator(topology, jstring(invokeInfo, "name"), kind, logic, parameters); // Extract any source location information from the config. SourceInfo.setInvocationInfo(source, invokeInfo); return JavaFunctional.addJavaOutput(topology, source, tupleType, ofNullable(outputSerializer), true); }
static <T> TStream<T> invokeSource(Topology topology, String kind, JsonObject invokeInfo, Supplier<Iterable<T>> logic, Type tupleType, TupleSerializer outputSerializer, Map<String, Object> parameters) { parameters = copyParameters(parameters); if (outputSerializer != null) { parameters.put(STR, serializeLogic(outputSerializer)); } BOperatorInvocation source = JavaFunctional.addFunctionalOperator(topology, jstring(invokeInfo, "name"), kind, logic, parameters); SourceInfo.setInvocationInfo(source, invokeInfo); return JavaFunctional.addJavaOutput(topology, source, tupleType, ofNullable(outputSerializer), true); }
/** * Invoke a functional source operator that generates a single stream. * * @param topology Topology the operator will be invoked in. * @param kind Java functional operator kind. * @param invokeInfo Operator invocation information. * @param logic Functional logic. * @param tupleType Type of tuples for the returned stream. * @param outputSerializer How output tuples are serialized. * @param parameters Additional SPL operator parameters. * * @return Stream produced by the source operator invocation. */
Invoke a functional source operator that generates a single stream
invokeSource
{ "repo_name": "IBMStreams/streamsx.topology", "path": "java/src/com/ibm/streamsx/topology/spi/builder/Invoker.java", "license": "apache-2.0", "size": 11995 }
[ "com.google.gson.JsonObject", "com.ibm.streamsx.topology.TStream", "com.ibm.streamsx.topology.Topology", "com.ibm.streamsx.topology.builder.BOperatorInvocation", "com.ibm.streamsx.topology.function.Supplier", "com.ibm.streamsx.topology.internal.core.JavaFunctional", "com.ibm.streamsx.topology.internal.core.SourceInfo", "com.ibm.streamsx.topology.internal.gson.GsonUtilities", "com.ibm.streamsx.topology.internal.logic.ObjectUtils", "com.ibm.streamsx.topology.spi.builder.Utils", "com.ibm.streamsx.topology.spi.runtime.TupleSerializer", "java.lang.reflect.Type", "java.util.Map", "java.util.Optional" ]
import com.google.gson.JsonObject; import com.ibm.streamsx.topology.TStream; import com.ibm.streamsx.topology.Topology; import com.ibm.streamsx.topology.builder.BOperatorInvocation; import com.ibm.streamsx.topology.function.Supplier; import com.ibm.streamsx.topology.internal.core.JavaFunctional; import com.ibm.streamsx.topology.internal.core.SourceInfo; import com.ibm.streamsx.topology.internal.gson.GsonUtilities; import com.ibm.streamsx.topology.internal.logic.ObjectUtils; import com.ibm.streamsx.topology.spi.builder.Utils; import com.ibm.streamsx.topology.spi.runtime.TupleSerializer; import java.lang.reflect.Type; import java.util.Map; import java.util.Optional;
import com.google.gson.*; import com.ibm.streamsx.topology.*; import com.ibm.streamsx.topology.builder.*; import com.ibm.streamsx.topology.function.*; import com.ibm.streamsx.topology.internal.core.*; import com.ibm.streamsx.topology.internal.gson.*; import com.ibm.streamsx.topology.internal.logic.*; import com.ibm.streamsx.topology.spi.builder.*; import com.ibm.streamsx.topology.spi.runtime.*; import java.lang.reflect.*; import java.util.*;
[ "com.google.gson", "com.ibm.streamsx", "java.lang", "java.util" ]
com.google.gson; com.ibm.streamsx; java.lang; java.util;
47,474
public static List channelsForUser(User user) { //subscribableChannels is the list we'll be returning List subscribableChannels = new ArrayList(); //Setup items for the query SelectMode m = ModeFactory.getMode("Channel_queries", "user_subscribe_perms"); Map params = new HashMap(); params.put("user_id", user.getId()); params.put("org_id", user.getOrg().getId()); //Execute the query DataResult subscribable = m.execute(params); Iterator i = subscribable.iterator(); while (i.hasNext()) { ChannelPerms perms = (ChannelPerms) i.next(); //if the user has permissions for this channel if (perms.isHasPerm()) { //add the name to the list subscribableChannels.add(perms.getName()); } } return subscribableChannels; }
static List function(User user) { List subscribableChannels = new ArrayList(); SelectMode m = ModeFactory.getMode(STR, STR); Map params = new HashMap(); params.put(STR, user.getId()); params.put(STR, user.getOrg().getId()); DataResult subscribable = m.execute(params); Iterator i = subscribable.iterator(); while (i.hasNext()) { ChannelPerms perms = (ChannelPerms) i.next(); if (perms.isHasPerm()) { subscribableChannels.add(perms.getName()); } } return subscribableChannels; }
/** * channelsForUser returns a list containing the names of the channels * that this user has permissions to. If the user doesn't have permissions * to any channels, this method returns an empty list. * @param user The user in question * @return Returns the list of names of channels this user has permission to, * an empty list otherwise. */
channelsForUser returns a list containing the names of the channels that this user has permissions to. If the user doesn't have permissions to any channels, this method returns an empty list
channelsForUser
{ "repo_name": "dmacvicar/spacewalk", "path": "java/code/src/com/redhat/rhn/manager/channel/ChannelManager.java", "license": "gpl-2.0", "size": 105505 }
[ "com.redhat.rhn.common.db.datasource.DataResult", "com.redhat.rhn.common.db.datasource.ModeFactory", "com.redhat.rhn.common.db.datasource.SelectMode", "com.redhat.rhn.domain.user.User", "com.redhat.rhn.frontend.dto.ChannelPerms", "java.util.ArrayList", "java.util.HashMap", "java.util.Iterator", "java.util.List", "java.util.Map" ]
import com.redhat.rhn.common.db.datasource.DataResult; import com.redhat.rhn.common.db.datasource.ModeFactory; import com.redhat.rhn.common.db.datasource.SelectMode; import com.redhat.rhn.domain.user.User; import com.redhat.rhn.frontend.dto.ChannelPerms; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map;
import com.redhat.rhn.common.db.datasource.*; import com.redhat.rhn.domain.user.*; import com.redhat.rhn.frontend.dto.*; import java.util.*;
[ "com.redhat.rhn", "java.util" ]
com.redhat.rhn; java.util;
1,311,975
Document createDocument(String ns, String root, String uri, Reader r) throws IOException;
Document createDocument(String ns, String root, String uri, Reader r) throws IOException;
/** * Creates a Document instance. * @param ns The namespace URI of the root element of the document. * @param root The name of the root element of the document. * @param uri The document URI. * @param r The document reader. * @exception IOException if an error occured while reading the document. */
Creates a Document instance
createDocument
{ "repo_name": "sflyphotobooks/crp-batik", "path": "sources/org/apache/batik/dom/util/DocumentFactory.java", "license": "apache-2.0", "size": 3570 }
[ "java.io.IOException", "java.io.Reader", "org.w3c.dom.Document" ]
import java.io.IOException; import java.io.Reader; import org.w3c.dom.Document;
import java.io.*; import org.w3c.dom.*;
[ "java.io", "org.w3c.dom" ]
java.io; org.w3c.dom;
1,405,764
public static Class<? extends TupleRawComparator> getComparatorClass() { return BinInterSedesTupleRawComparator.class; }
static Class<? extends TupleRawComparator> function() { return BinInterSedesTupleRawComparator.class; }
/** * Since our serialization matches BinInterSedes, we can use the same comparator. * @return */
Since our serialization matches BinInterSedes, we can use the same comparator
getComparatorClass
{ "repo_name": "kaituo/sedge", "path": "trunk/src/org/apache/pig/data/PrimitiveFieldTuple.java", "license": "mit", "size": 9775 }
[ "org.apache.pig.data.BinInterSedes" ]
import org.apache.pig.data.BinInterSedes;
import org.apache.pig.data.*;
[ "org.apache.pig" ]
org.apache.pig;
457,360
@Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { Set<String> sets = new HashSet<>(); boolean silent = false; for(String arg : args) { if (!arg.startsWith("-")) { sets.add(arg); } if(arg.equals("-s") || arg.equals("--silent")) silent = true; } if(sets.size() <= 0) { if(!silent) sender.addChatMessage(new TextComponentString("A set name must be specified.")); return; } for(String set : sets) { if (!CraftingHarmonicsMod.isValidSet(set)) { if(!silent) { sender.addChatMessage(new TextComponentString(args[0] + " is not a valid set.")); sender.addChatMessage(new TextComponentString("Valid sets: " + Joiner.on(", ").join(CraftingHarmonicsMod.getAllSets()))); } return; } } boolean finalSilent = silent; server.addScheduledTask(() -> { if(!CraftingHarmonicsMod.applySets(sets.toArray(new String[sets.size()]))) { if(!finalSilent) sender.addChatMessage(new TextComponentString("One or more of the sets: " + Joiner.on(", ").join(sets) + " could not be applied.")); return; } if(!finalSilent) sender.addChatMessage(new TextComponentString(Joiner.on(", ").join(sets) + " applied.")); CraftingHarmonicsMod.syncAllConfigs(); }); }
void function(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { Set<String> sets = new HashSet<>(); boolean silent = false; for(String arg : args) { if (!arg.startsWith("-")) { sets.add(arg); } if(arg.equals("-s") arg.equals(STR)) silent = true; } if(sets.size() <= 0) { if(!silent) sender.addChatMessage(new TextComponentString(STR)); return; } for(String set : sets) { if (!CraftingHarmonicsMod.isValidSet(set)) { if(!silent) { sender.addChatMessage(new TextComponentString(args[0] + STR)); sender.addChatMessage(new TextComponentString(STR + Joiner.on(STR).join(CraftingHarmonicsMod.getAllSets()))); } return; } } boolean finalSilent = silent; server.addScheduledTask(() -> { if(!CraftingHarmonicsMod.applySets(sets.toArray(new String[sets.size()]))) { if(!finalSilent) sender.addChatMessage(new TextComponentString(STR + Joiner.on(STR).join(sets) + STR)); return; } if(!finalSilent) sender.addChatMessage(new TextComponentString(Joiner.on(STR).join(sets) + STR)); CraftingHarmonicsMod.syncAllConfigs(); }); }
/** * Callback for when the command is executed * * @param server The Minecraft server instance * @param sender The source of the command invocation * @param args The arguments that were passed */
Callback for when the command is executed
execute
{ "repo_name": "legendblade/CraftingHarmonics", "path": "src/main/java/org/winterblade/minecraft/harmony/commands/ApplySetCommand.java", "license": "mit", "size": 3317 }
[ "com.google.common.base.Joiner", "java.util.HashSet", "java.util.Set", "net.minecraft.command.CommandException", "net.minecraft.command.ICommandSender", "net.minecraft.server.MinecraftServer", "net.minecraft.util.text.TextComponentString", "org.winterblade.minecraft.harmony.CraftingHarmonicsMod" ]
import com.google.common.base.Joiner; import java.util.HashSet; import java.util.Set; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; import net.minecraft.util.text.TextComponentString; import org.winterblade.minecraft.harmony.CraftingHarmonicsMod;
import com.google.common.base.*; import java.util.*; import net.minecraft.command.*; import net.minecraft.server.*; import net.minecraft.util.text.*; import org.winterblade.minecraft.harmony.*;
[ "com.google.common", "java.util", "net.minecraft.command", "net.minecraft.server", "net.minecraft.util", "org.winterblade.minecraft" ]
com.google.common; java.util; net.minecraft.command; net.minecraft.server; net.minecraft.util; org.winterblade.minecraft;
2,408,720