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 java.util.List<fr.lip6.move.pnml.hlpn.cyclicEnumerations.hlapi.PredecessorHLAPI> getSubterm_cyclicEnumerations_PredecessorHLAPI(){
java.util.List<fr.lip6.move.pnml.hlpn.cyclicEnumerations.hlapi.PredecessorHLAPI> retour = new ArrayList<fr.lip6.move.pnml.hlpn.cyclicEnumerations.hlapi.PredecessorHLAPI>();
for (Term elemnt : getSubterm()) {
if(elemnt.getClass().equals(fr.lip6.move.pnml.hlpn.cyclicEnumerations.impl.PredecessorImpl.class)){
retour.add(new fr.lip6.move.pnml.hlpn.cyclicEnumerations.hlapi.PredecessorHLAPI(
(fr.lip6.move.pnml.hlpn.cyclicEnumerations.Predecessor)elemnt
));
}
}
return retour;
}
| java.util.List<fr.lip6.move.pnml.hlpn.cyclicEnumerations.hlapi.PredecessorHLAPI> function(){ java.util.List<fr.lip6.move.pnml.hlpn.cyclicEnumerations.hlapi.PredecessorHLAPI> retour = new ArrayList<fr.lip6.move.pnml.hlpn.cyclicEnumerations.hlapi.PredecessorHLAPI>(); for (Term elemnt : getSubterm()) { if(elemnt.getClass().equals(fr.lip6.move.pnml.hlpn.cyclicEnumerations.impl.PredecessorImpl.class)){ retour.add(new fr.lip6.move.pnml.hlpn.cyclicEnumerations.hlapi.PredecessorHLAPI( (fr.lip6.move.pnml.hlpn.cyclicEnumerations.Predecessor)elemnt )); } } return retour; } | /**
* This accessor return a list of encapsulated subelement, only of PredecessorHLAPI kind.
* WARNING : this method can creates a lot of new object in memory.
*/ | This accessor return a list of encapsulated subelement, only of PredecessorHLAPI kind. WARNING : this method can creates a lot of new object in memory | getSubterm_cyclicEnumerations_PredecessorHLAPI | {
"repo_name": "lhillah/pnmlframework",
"path": "pnmlFw-HLPN/src/fr/lip6/move/pnml/hlpn/lists/hlapi/EmptyListHLAPI.java",
"license": "epl-1.0",
"size": 113924
} | [
"fr.lip6.move.pnml.hlpn.terms.Term",
"java.util.ArrayList",
"java.util.List"
] | import fr.lip6.move.pnml.hlpn.terms.Term; import java.util.ArrayList; import java.util.List; | import fr.lip6.move.pnml.hlpn.terms.*; import java.util.*; | [
"fr.lip6.move",
"java.util"
] | fr.lip6.move; java.util; | 5,439 |
@Test (timeout=60000)
public void testAssignRacingWithSSH() throws Exception {
TableName table = TableName.valueOf("testAssignRacingWithSSH");
MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
MyMaster master = null;
try {
HTableDescriptor desc = new HTableDescriptor(table);
desc.addFamily(new HColumnDescriptor(FAMILY));
admin.createTable(desc);
Table meta = TEST_UTIL.getConnection().getTable(TableName.META_TABLE_NAME);
HRegionInfo hri = new HRegionInfo(
desc.getTableName(), Bytes.toBytes("A"), Bytes.toBytes("Z"));
MetaTableAccessor.addRegionToMeta(meta, hri);
// Assign the region
master = (MyMaster)cluster.getMaster();
master.assignRegion(hri);
// Hold SSH before killing the hosting server
master.enableSSH(false);
AssignmentManager am = master.getAssignmentManager();
RegionStates regionStates = am.getRegionStates();
ServerName metaServer = regionStates.getRegionServerOfRegion(
HRegionInfo.FIRST_META_REGIONINFO);
while (true) {
assertTrue(am.waitForAssignment(hri));
RegionState state = regionStates.getRegionState(hri);
ServerName oldServerName = state.getServerName();
if (!ServerName.isSameHostnameAndPort(oldServerName, metaServer)) {
// Kill the hosting server, which doesn't have meta on it.
cluster.killRegionServer(oldServerName);
cluster.waitForRegionServerToStop(oldServerName, -1);
break;
}
int i = cluster.getServerWithMeta();
HRegionServer rs = cluster.getRegionServer(i == 0 ? 1 : 0);
oldServerName = rs.getServerName();
master.move(hri.getEncodedNameAsBytes(),
Bytes.toBytes(oldServerName.getServerName()));
}
// You can't assign a dead region before SSH
am.assign(hri, true);
RegionState state = regionStates.getRegionState(hri);
assertTrue(state.isFailedClose());
// You can't unassign a dead region before SSH either
am.unassign(hri);
state = regionStates.getRegionState(hri);
assertTrue(state.isFailedClose());
// Enable SSH so that log can be split
master.enableSSH(true);
// let's check if it's assigned after it's out of transition.
// no need to assign it manually, SSH should do it
am.waitOnRegionToClearRegionsInTransition(hri);
assertTrue(am.waitForAssignment(hri));
ServerName serverName = master.getAssignmentManager().
getRegionStates().getRegionServerOfRegion(hri);
TEST_UTIL.assertRegionOnlyOnServer(hri, serverName, 6000);
} finally {
if (master != null) {
master.enableSSH(true);
}
TEST_UTIL.deleteTable(table);
cluster.startRegionServer();
}
} | @Test (timeout=60000) void function() throws Exception { TableName table = TableName.valueOf(STR); MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster(); MyMaster master = null; try { HTableDescriptor desc = new HTableDescriptor(table); desc.addFamily(new HColumnDescriptor(FAMILY)); admin.createTable(desc); Table meta = TEST_UTIL.getConnection().getTable(TableName.META_TABLE_NAME); HRegionInfo hri = new HRegionInfo( desc.getTableName(), Bytes.toBytes("A"), Bytes.toBytes("Z")); MetaTableAccessor.addRegionToMeta(meta, hri); master = (MyMaster)cluster.getMaster(); master.assignRegion(hri); master.enableSSH(false); AssignmentManager am = master.getAssignmentManager(); RegionStates regionStates = am.getRegionStates(); ServerName metaServer = regionStates.getRegionServerOfRegion( HRegionInfo.FIRST_META_REGIONINFO); while (true) { assertTrue(am.waitForAssignment(hri)); RegionState state = regionStates.getRegionState(hri); ServerName oldServerName = state.getServerName(); if (!ServerName.isSameHostnameAndPort(oldServerName, metaServer)) { cluster.killRegionServer(oldServerName); cluster.waitForRegionServerToStop(oldServerName, -1); break; } int i = cluster.getServerWithMeta(); HRegionServer rs = cluster.getRegionServer(i == 0 ? 1 : 0); oldServerName = rs.getServerName(); master.move(hri.getEncodedNameAsBytes(), Bytes.toBytes(oldServerName.getServerName())); } am.assign(hri, true); RegionState state = regionStates.getRegionState(hri); assertTrue(state.isFailedClose()); am.unassign(hri); state = regionStates.getRegionState(hri); assertTrue(state.isFailedClose()); master.enableSSH(true); am.waitOnRegionToClearRegionsInTransition(hri); assertTrue(am.waitForAssignment(hri)); ServerName serverName = master.getAssignmentManager(). getRegionStates().getRegionServerOfRegion(hri); TEST_UTIL.assertRegionOnlyOnServer(hri, serverName, 6000); } finally { if (master != null) { master.enableSSH(true); } TEST_UTIL.deleteTable(table); cluster.startRegionServer(); } } | /**
* Test force unassign/assign a region hosted on a dead server
*/ | Test force unassign/assign a region hosted on a dead server | testAssignRacingWithSSH | {
"repo_name": "juwi/hbase",
"path": "hbase-server/src/test/java/org/apache/hadoop/hbase/master/TestAssignmentManagerOnCluster.java",
"license": "apache-2.0",
"size": 50331
} | [
"org.apache.hadoop.hbase.HColumnDescriptor",
"org.apache.hadoop.hbase.HRegionInfo",
"org.apache.hadoop.hbase.HTableDescriptor",
"org.apache.hadoop.hbase.MetaTableAccessor",
"org.apache.hadoop.hbase.MiniHBaseCluster",
"org.apache.hadoop.hbase.ServerName",
"org.apache.hadoop.hbase.TableName",
"org.apache.hadoop.hbase.client.Table",
"org.apache.hadoop.hbase.regionserver.HRegionServer",
"org.apache.hadoop.hbase.util.Bytes",
"org.junit.Assert",
"org.junit.Test"
] | import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.MetaTableAccessor; import org.apache.hadoop.hbase.MiniHBaseCluster; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.regionserver.HRegionServer; import org.apache.hadoop.hbase.util.Bytes; import org.junit.Assert; import org.junit.Test; | import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.regionserver.*; import org.apache.hadoop.hbase.util.*; import org.junit.*; | [
"org.apache.hadoop",
"org.junit"
] | org.apache.hadoop; org.junit; | 741,363 |
public void setImageType(final String imageType) {
this.imageType = BufferedImageType.lookupValue(imageType);
}
public static class Input {
public MfClientHttpRequestFactory clientHttpRequestFactory;
public MapAttribute.MapAttributeValues map;
public File tempTaskDirectory;
}
public static final class Output {
@InternalValue
public final List<URI> layerGraphics;
public final String mapSubReport;
public final MapfishMapContext mapContext;
private Output(final List<URI> layerGraphics,
final String mapSubReport,
final MapfishMapContext mapContext) {
this.layerGraphics = layerGraphics;
this.mapSubReport = mapSubReport;
this.mapContext = mapContext;
}
} | void function(final String imageType) { this.imageType = BufferedImageType.lookupValue(imageType); } public static class Input { public MfClientHttpRequestFactory clientHttpRequestFactory; public MapAttribute.MapAttributeValues map; public File tempTaskDirectory; } public static final class Output { public final List<URI> layerGraphics; public final String mapSubReport; public final MapfishMapContext mapContext; private Output(final List<URI> layerGraphics, final String mapSubReport, final MapfishMapContext mapContext) { this.layerGraphics = layerGraphics; this.mapSubReport = mapSubReport; this.mapContext = mapContext; } } | /**
* Set the type of buffered image rendered to. See {@link org.mapfish.print.processor.map.CreateMapProcessor.BufferedImageType}.
* <p/>
* Default is {@link org.mapfish.print.processor.map.CreateMapProcessor.BufferedImageType#TYPE_4BYTE_ABGR}.
*
* @param imageType one of the {@link org.mapfish.print.processor.map.CreateMapProcessor.BufferedImageType} values.
*/ | Set the type of buffered image rendered to. See <code>org.mapfish.print.processor.map.CreateMapProcessor.BufferedImageType</code>. Default is <code>org.mapfish.print.processor.map.CreateMapProcessor.BufferedImageType#TYPE_4BYTE_ABGR</code> | setImageType | {
"repo_name": "jesseeichar/mapfish-printV3",
"path": "core/src/main/java/org/mapfish/print/processor/map/CreateMapProcessor.java",
"license": "mit",
"size": 18736
} | [
"java.io.File",
"java.util.List",
"org.mapfish.print.attribute.map.MapAttribute",
"org.mapfish.print.attribute.map.MapfishMapContext",
"org.mapfish.print.http.MfClientHttpRequestFactory"
] | import java.io.File; import java.util.List; import org.mapfish.print.attribute.map.MapAttribute; import org.mapfish.print.attribute.map.MapfishMapContext; import org.mapfish.print.http.MfClientHttpRequestFactory; | import java.io.*; import java.util.*; import org.mapfish.print.attribute.map.*; import org.mapfish.print.http.*; | [
"java.io",
"java.util",
"org.mapfish.print"
] | java.io; java.util; org.mapfish.print; | 1,410,518 |
AdaptrisMessage buildForRetry(String msgId, Map<String, String> metadata,
AdaptrisMessageFactory factory) throws InterlokException; | AdaptrisMessage buildForRetry(String msgId, Map<String, String> metadata, AdaptrisMessageFactory factory) throws InterlokException; | /**
* Build the message for retrying from the store.
*
* @param msgId the message id.
* @param metadata the metadata you want to apply to the message
* @param factory the message factory to use
* @return a message.
* @throws CoreException
*/ | Build the message for retrying from the store | buildForRetry | {
"repo_name": "adaptris/interlok",
"path": "interlok-core/src/main/java/com/adaptris/core/http/jetty/retry/RetryStore.java",
"license": "apache-2.0",
"size": 2946
} | [
"com.adaptris.core.AdaptrisMessage",
"com.adaptris.core.AdaptrisMessageFactory",
"com.adaptris.interlok.InterlokException",
"java.util.Map"
] | import com.adaptris.core.AdaptrisMessage; import com.adaptris.core.AdaptrisMessageFactory; import com.adaptris.interlok.InterlokException; import java.util.Map; | import com.adaptris.core.*; import com.adaptris.interlok.*; import java.util.*; | [
"com.adaptris.core",
"com.adaptris.interlok",
"java.util"
] | com.adaptris.core; com.adaptris.interlok; java.util; | 2,706,114 |
@Test
public void testBlockOnEmptyQueue() throws InterruptedException {
int queueSize = randomIntBetween(1, 3000);
ExecutorService executor = Executors.newSingleThreadExecutor();
CountDownLatch empty = new CountDownLatch(1);
CountDownLatch finished = new CountDownLatch(1);
ThroughputQueue queue = new ThroughputQueue();
BlocksOnEmptyQueue testThread = new BlocksOnEmptyQueue(empty, finished, queueSize, queue);
for(int i=0; i < queueSize; ++i) {
queue.put(i);
}
executor.submit(testThread);
empty.await();
Assert.assertEquals(0, queue.size());
Assert.assertEquals(0, queue.getCurrentSize());
Assert.assertFalse(testThread.isComplete());
safeSleep(1000);
Assert.assertFalse(testThread.isComplete());
queue.put(1);
finished.await();
Assert.assertEquals(0, queue.size());
Assert.assertEquals(0, queue.getCurrentSize());
Assert.assertTrue(testThread.isComplete());
executor.shutdownNow();
executor.awaitTermination(500, TimeUnit.MILLISECONDS);
} | void function() throws InterruptedException { int queueSize = randomIntBetween(1, 3000); ExecutorService executor = Executors.newSingleThreadExecutor(); CountDownLatch empty = new CountDownLatch(1); CountDownLatch finished = new CountDownLatch(1); ThroughputQueue queue = new ThroughputQueue(); BlocksOnEmptyQueue testThread = new BlocksOnEmptyQueue(empty, finished, queueSize, queue); for(int i=0; i < queueSize; ++i) { queue.put(i); } executor.submit(testThread); empty.await(); Assert.assertEquals(0, queue.size()); Assert.assertEquals(0, queue.getCurrentSize()); Assert.assertFalse(testThread.isComplete()); safeSleep(1000); Assert.assertFalse(testThread.isComplete()); queue.put(1); finished.await(); Assert.assertEquals(0, queue.size()); Assert.assertEquals(0, queue.getCurrentSize()); Assert.assertTrue(testThread.isComplete()); executor.shutdownNow(); executor.awaitTermination(500, TimeUnit.MILLISECONDS); } | /**
* Test that queue will block on Take when queue is empty
* @throws InterruptedException
*/ | Test that queue will block on Take when queue is empty | testBlockOnEmptyQueue | {
"repo_name": "jfrazee/incubator-streams",
"path": "streams-runtimes/streams-runtime-local/src/test/java/org/apache/streams/local/queues/ThroughputQueueMultiThreadTest.java",
"license": "apache-2.0",
"size": 9938
} | [
"java.util.concurrent.CountDownLatch",
"java.util.concurrent.ExecutorService",
"java.util.concurrent.Executors",
"java.util.concurrent.TimeUnit",
"org.junit.Assert"
] | import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.Assert; | import java.util.concurrent.*; import org.junit.*; | [
"java.util",
"org.junit"
] | java.util; org.junit; | 688,441 |
protected void submitInitialSeeds() {
for(Entry<N, Set<D>> seed: initialSeeds.entrySet()) {
N startPoint = seed.getKey();
for(D val: seed.getValue())
propagate(zeroValue, startPoint, val, null, false);
jumpFn.addFunction(new PathEdge<N, D>(zeroValue, startPoint, zeroValue));
}
} | void function() { for(Entry<N, Set<D>> seed: initialSeeds.entrySet()) { N startPoint = seed.getKey(); for(D val: seed.getValue()) propagate(zeroValue, startPoint, val, null, false); jumpFn.addFunction(new PathEdge<N, D>(zeroValue, startPoint, zeroValue)); } } | /**
* Schedules the processing of initial seeds, initiating the analysis.
* Clients should only call this methods if performing synchronization on
* their own. Normally, {@link #solve()} should be called instead.
*/ | Schedules the processing of initial seeds, initiating the analysis. Clients should only call this methods if performing synchronization on their own. Normally, <code>#solve()</code> should be called instead | submitInitialSeeds | {
"repo_name": "wangxiayang/soot-infoflow",
"path": "src/soot/jimple/infoflow/solver/fastSolver/IFDSSolver.java",
"license": "lgpl-2.1",
"size": 24417
} | [
"java.util.Map",
"java.util.Set"
] | import java.util.Map; import java.util.Set; | import java.util.*; | [
"java.util"
] | java.util; | 2,777,034 |
CompletableFuture<Optional<JobManagerMessages.ClassloadingProps>> requestClassloadingProps(JobID jobId, Time timeout);
/**
* Requests the TaskManager instance registered under the given instanceId from the JobManager.
* If there is no Instance registered, then {@link Optional#empty()} is returned.
*
* @param instanceId for which to retrieve the Instance
* @param timeout for the asynchronous operation
* @return Future containing the TaskManager instance registered under instanceId, otherwise {@link Optional#empty()} | CompletableFuture<Optional<JobManagerMessages.ClassloadingProps>> requestClassloadingProps(JobID jobId, Time timeout); /** * Requests the TaskManager instance registered under the given instanceId from the JobManager. * If there is no Instance registered, then {@link Optional#empty()} is returned. * * @param instanceId for which to retrieve the Instance * @param timeout for the asynchronous operation * @return Future containing the TaskManager instance registered under instanceId, otherwise {@link Optional#empty()} | /**
* Requests the class loading properties for the given JobID.
*
* @param jobId for which the class loading properties are requested
* @param timeout for this operation
* @return Future containing the optional class loading properties if they could be retrieved from the JobManager.
*/ | Requests the class loading properties for the given JobID | requestClassloadingProps | {
"repo_name": "zohar-mizrahi/flink",
"path": "flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobManagerGateway.java",
"license": "apache-2.0",
"size": 6835
} | [
"java.util.Optional",
"java.util.concurrent.CompletableFuture",
"org.apache.flink.api.common.JobID",
"org.apache.flink.api.common.time.Time",
"org.apache.flink.runtime.instance.Instance",
"org.apache.flink.runtime.messages.JobManagerMessages"
] | import java.util.Optional; import java.util.concurrent.CompletableFuture; import org.apache.flink.api.common.JobID; import org.apache.flink.api.common.time.Time; import org.apache.flink.runtime.instance.Instance; import org.apache.flink.runtime.messages.JobManagerMessages; | import java.util.*; import java.util.concurrent.*; import org.apache.flink.api.common.*; import org.apache.flink.api.common.time.*; import org.apache.flink.runtime.instance.*; import org.apache.flink.runtime.messages.*; | [
"java.util",
"org.apache.flink"
] | java.util; org.apache.flink; | 1,184,803 |
public static ProjectListOption pageSize(int pageSize) {
return new ProjectListOption(ResourceManagerRpc.Option.PAGE_SIZE, pageSize);
} | static ProjectListOption function(int pageSize) { return new ProjectListOption(ResourceManagerRpc.Option.PAGE_SIZE, pageSize); } | /**
* The maximum number of projects to return per RPC.
*
* <p>The server can return fewer projects than requested. When there are more results than the
* page size, the server will return a page token that can be used to fetch other results.
*/ | The maximum number of projects to return per RPC. The server can return fewer projects than requested. When there are more results than the page size, the server will return a page token that can be used to fetch other results | pageSize | {
"repo_name": "googleapis/java-resourcemanager",
"path": "google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManager.java",
"license": "apache-2.0",
"size": 21104
} | [
"com.google.cloud.resourcemanager.spi.v1beta1.ResourceManagerRpc"
] | import com.google.cloud.resourcemanager.spi.v1beta1.ResourceManagerRpc; | import com.google.cloud.resourcemanager.spi.v1beta1.*; | [
"com.google.cloud"
] | com.google.cloud; | 469,377 |
public JceAsymmetricKeyUnwrapper setAlgorithmMapping(ASN1ObjectIdentifier algorithm, String algorithmName)
{
extraMappings.put(algorithm, algorithmName);
return this;
} | JceAsymmetricKeyUnwrapper function(ASN1ObjectIdentifier algorithm, String algorithmName) { extraMappings.put(algorithm, algorithmName); return this; } | /**
* Internally algorithm ids are converted into cipher names using a lookup table. For some providers
* the standard lookup table won't work. Use this method to establish a specific mapping from an
* algorithm identifier to a specific algorithm.
* <p>
* For example:
* <pre>
* unwrapper.setAlgorithmMapping(PKCSObjectIdentifiers.rsaEncryption, "RSA");
* </pre>
* </p>
* @param algorithm OID of algorithm in recipient.
* @param algorithmName JCE algorithm name to use.
* @return the current Unwrapper.
*/ | Internally algorithm ids are converted into cipher names using a lookup table. For some providers the standard lookup table won't work. Use this method to establish a specific mapping from an algorithm identifier to a specific algorithm. For example: <code> unwrapper.setAlgorithmMapping(PKCSObjectIdentifiers.rsaEncryption, "RSA"); </code> | setAlgorithmMapping | {
"repo_name": "sake/bouncycastle-java",
"path": "src/org/bouncycastle/operator/jcajce/JceAsymmetricKeyUnwrapper.java",
"license": "mit",
"size": 4167
} | [
"org.bouncycastle.asn1.ASN1ObjectIdentifier"
] | import org.bouncycastle.asn1.ASN1ObjectIdentifier; | import org.bouncycastle.asn1.*; | [
"org.bouncycastle.asn1"
] | org.bouncycastle.asn1; | 2,542,913 |
public void testGetUmlClassModelElements() {
setUpTestsOfTagDefinitionContainedInStereotype();
Collection col = Model.getModelManagementHelper()
.getAllModelElementsOfKind(theGoodPackage,
Model.getMetaTypes().getUMLClass());
assertTrue("Failed to get UmlClass ModelElement", col
.contains(theClass));
}
| void function() { setUpTestsOfTagDefinitionContainedInStereotype(); Collection col = Model.getModelManagementHelper() .getAllModelElementsOfKind(theGoodPackage, Model.getMetaTypes().getUMLClass()); assertTrue(STR, col .contains(theClass)); } | /**
* Test to make sure that we can get UmlClass since its name is different
*/ | Test to make sure that we can get UmlClass since its name is different | testGetUmlClassModelElements | {
"repo_name": "ckaestne/LEADT",
"path": "workspace/argouml_critics/argouml-app/tests/org/argouml/model/TestModelManagementHelper.java",
"license": "gpl-3.0",
"size": 7467
} | [
"java.util.Collection"
] | import java.util.Collection; | import java.util.*; | [
"java.util"
] | java.util; | 680,036 |
public ServerInner withMinimalTlsVersion(MinimalTlsVersionEnum minimalTlsVersion) {
if (this.innerProperties() == null) {
this.innerProperties = new ServerProperties();
}
this.innerProperties().withMinimalTlsVersion(minimalTlsVersion);
return this;
} | ServerInner function(MinimalTlsVersionEnum minimalTlsVersion) { if (this.innerProperties() == null) { this.innerProperties = new ServerProperties(); } this.innerProperties().withMinimalTlsVersion(minimalTlsVersion); return this; } | /**
* Set the minimalTlsVersion property: Enforce a minimal Tls version for the server.
*
* @param minimalTlsVersion the minimalTlsVersion value to set.
* @return the ServerInner object itself.
*/ | Set the minimalTlsVersion property: Enforce a minimal Tls version for the server | withMinimalTlsVersion | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/postgresql/azure-resourcemanager-postgresql/src/main/java/com/azure/resourcemanager/postgresql/fluent/models/ServerInner.java",
"license": "mit",
"size": 15590
} | [
"com.azure.resourcemanager.postgresql.models.MinimalTlsVersionEnum"
] | import com.azure.resourcemanager.postgresql.models.MinimalTlsVersionEnum; | import com.azure.resourcemanager.postgresql.models.*; | [
"com.azure.resourcemanager"
] | com.azure.resourcemanager; | 1,301,455 |
public static List<String> getClassNames(URL jarFile) throws IOException {
List<String> classNames = new ArrayList<String>();
ZipInputStream zip = new ZipInputStream(new FileInputStream(
jarFile.getPath()));
for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip
.getNextEntry()) {
if (entry.getName().endsWith(".class") && !entry.isDirectory()) {
// This ZipEntry represents a class. Now, what class does it
// represent?
StringBuilder className = new StringBuilder();
for (String part : entry.getName().split("/")) {
if (className.length() != 0) {
className.append(".");
}
className.append(part);
if (part.endsWith(".class")) {
className.setLength(className.length()
- ".class".length());
}
}
classNames.add(className.toString());
}
}
zip.close();
return classNames;
} | static List<String> function(URL jarFile) throws IOException { List<String> classNames = new ArrayList<String>(); ZipInputStream zip = new ZipInputStream(new FileInputStream( jarFile.getPath())); for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip .getNextEntry()) { if (entry.getName().endsWith(STR) && !entry.isDirectory()) { StringBuilder className = new StringBuilder(); for (String part : entry.getName().split("/")) { if (className.length() != 0) { className.append("."); } className.append(part); if (part.endsWith(STR)) { className.setLength(className.length() - STR.length()); } } classNames.add(className.toString()); } } zip.close(); return classNames; } | /**
* Creates a {@link List} of all classes within a given JAR file.
*
* From:
* http://stackoverflow.com/questions/15720822/how-to-get-names-of-classes
* -inside-a-jar-file
*
* @param jarFile
* the JAR file to search for Classes
* @return a {@link List} with all found classes
* @throws IOException
*/ | Creates a <code>List</code> of all classes within a given JAR file. From: HREF -inside-a-jar-file | getClassNames | {
"repo_name": "MReichenbach/visitmeta",
"path": "common/src/main/java/de/hshannover/f4/trust/visitmeta/util/ReflectionUtils.java",
"license": "apache-2.0",
"size": 5197
} | [
"java.io.FileInputStream",
"java.io.IOException",
"java.util.ArrayList",
"java.util.List",
"java.util.zip.ZipEntry",
"java.util.zip.ZipInputStream"
] | import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; | import java.io.*; import java.util.*; import java.util.zip.*; | [
"java.io",
"java.util"
] | java.io; java.util; | 868,785 |
public void processClickWindow(C0EPacketClickWindow packetIn)
{
PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.playerEntity.getServerForPlayer());
this.playerEntity.markPlayerActive();
if (this.playerEntity.openContainer.windowId == packetIn.getWindowId() && this.playerEntity.openContainer.isPlayerNotUsingContainer(this.playerEntity))
{
if (this.playerEntity.isSpectator())
{
ArrayList arraylist = Lists.newArrayList();
for (int i = 0; i < this.playerEntity.openContainer.inventorySlots.size(); ++i)
{
arraylist.add(((Slot)this.playerEntity.openContainer.inventorySlots.get(i)).getStack());
}
this.playerEntity.sendContainerAndContentsToPlayer(this.playerEntity.openContainer, arraylist);
}
else
{
ItemStack itemstack = this.playerEntity.openContainer.slotClick(packetIn.getSlotId(), packetIn.getUsedButton(), packetIn.getMode(), this.playerEntity);
if (ItemStack.areItemStacksEqual(packetIn.getClickedItem(), itemstack))
{
this.playerEntity.playerNetServerHandler.sendPacket(new S32PacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), true));
this.playerEntity.isChangingQuantityOnly = true;
this.playerEntity.openContainer.detectAndSendChanges();
this.playerEntity.updateHeldItem();
this.playerEntity.isChangingQuantityOnly = false;
}
else
{
this.field_147372_n.addKey(this.playerEntity.openContainer.windowId, Short.valueOf(packetIn.getActionNumber()));
this.playerEntity.playerNetServerHandler.sendPacket(new S32PacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), false));
this.playerEntity.openContainer.setPlayerIsPresent(this.playerEntity, false);
ArrayList arraylist1 = Lists.newArrayList();
for (int j = 0; j < this.playerEntity.openContainer.inventorySlots.size(); ++j)
{
arraylist1.add(((Slot)this.playerEntity.openContainer.inventorySlots.get(j)).getStack());
}
this.playerEntity.sendContainerAndContentsToPlayer(this.playerEntity.openContainer, arraylist1);
}
}
}
} | void function(C0EPacketClickWindow packetIn) { PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.playerEntity.getServerForPlayer()); this.playerEntity.markPlayerActive(); if (this.playerEntity.openContainer.windowId == packetIn.getWindowId() && this.playerEntity.openContainer.isPlayerNotUsingContainer(this.playerEntity)) { if (this.playerEntity.isSpectator()) { ArrayList arraylist = Lists.newArrayList(); for (int i = 0; i < this.playerEntity.openContainer.inventorySlots.size(); ++i) { arraylist.add(((Slot)this.playerEntity.openContainer.inventorySlots.get(i)).getStack()); } this.playerEntity.sendContainerAndContentsToPlayer(this.playerEntity.openContainer, arraylist); } else { ItemStack itemstack = this.playerEntity.openContainer.slotClick(packetIn.getSlotId(), packetIn.getUsedButton(), packetIn.getMode(), this.playerEntity); if (ItemStack.areItemStacksEqual(packetIn.getClickedItem(), itemstack)) { this.playerEntity.playerNetServerHandler.sendPacket(new S32PacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), true)); this.playerEntity.isChangingQuantityOnly = true; this.playerEntity.openContainer.detectAndSendChanges(); this.playerEntity.updateHeldItem(); this.playerEntity.isChangingQuantityOnly = false; } else { this.field_147372_n.addKey(this.playerEntity.openContainer.windowId, Short.valueOf(packetIn.getActionNumber())); this.playerEntity.playerNetServerHandler.sendPacket(new S32PacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), false)); this.playerEntity.openContainer.setPlayerIsPresent(this.playerEntity, false); ArrayList arraylist1 = Lists.newArrayList(); for (int j = 0; j < this.playerEntity.openContainer.inventorySlots.size(); ++j) { arraylist1.add(((Slot)this.playerEntity.openContainer.inventorySlots.get(j)).getStack()); } this.playerEntity.sendContainerAndContentsToPlayer(this.playerEntity.openContainer, arraylist1); } } } } | /**
* Executes a container/inventory slot manipulation as indicated by the packet. Sends the serverside result if they
* didn't match the indicated result and prevents further manipulation by the player until he confirms that it has
* the same open container/inventory
*/ | Executes a container/inventory slot manipulation as indicated by the packet. Sends the serverside result if they didn't match the indicated result and prevents further manipulation by the player until he confirms that it has the same open container/inventory | processClickWindow | {
"repo_name": "kelthalorn/ConquestCraft",
"path": "build/tmp/recompSrc/net/minecraft/network/NetHandlerPlayServer.java",
"license": "lgpl-2.1",
"size": 68065
} | [
"com.google.common.collect.Lists",
"java.util.ArrayList",
"net.minecraft.inventory.Slot",
"net.minecraft.item.ItemStack",
"net.minecraft.network.play.client.C0EPacketClickWindow",
"net.minecraft.network.play.server.S32PacketConfirmTransaction"
] | import com.google.common.collect.Lists; import java.util.ArrayList; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.network.play.client.C0EPacketClickWindow; import net.minecraft.network.play.server.S32PacketConfirmTransaction; | import com.google.common.collect.*; import java.util.*; import net.minecraft.inventory.*; import net.minecraft.item.*; import net.minecraft.network.play.client.*; import net.minecraft.network.play.server.*; | [
"com.google.common",
"java.util",
"net.minecraft.inventory",
"net.minecraft.item",
"net.minecraft.network"
] | com.google.common; java.util; net.minecraft.inventory; net.minecraft.item; net.minecraft.network; | 2,345,296 |
public Hashtable getParameters()
{
return parameters;
} | Hashtable function() { return parameters; } | /**
* Obtains a map of type (Integer) to value (byte[]) for the parameters tracked in this object.
*/ | Obtains a map of type (Integer) to value (byte[]) for the parameters tracked in this object | getParameters | {
"repo_name": "iseki-masaya/spongycastle",
"path": "core/src/main/java/org/spongycastle/crypto/params/SkeinParameters.java",
"license": "mit",
"size": 11633
} | [
"java.util.Hashtable"
] | import java.util.Hashtable; | import java.util.*; | [
"java.util"
] | java.util; | 869,719 |
public boolean isUploading(Account account, OCFile file) {
if (account == null || file == null)
return false;
String targetKey = buildRemoteName(account, file);
synchronized (mPendingUploads) {
if (file.isFolder()) {
// this can be slow if there are many uploads :(
Iterator<String> it = mPendingUploads.keySet().iterator();
boolean found = false;
while (it.hasNext() && !found) {
found = it.next().startsWith(targetKey);
}
return found;
} else {
return (mPendingUploads.containsKey(targetKey));
}
}
} | boolean function(Account account, OCFile file) { if (account == null file == null) return false; String targetKey = buildRemoteName(account, file); synchronized (mPendingUploads) { if (file.isFolder()) { Iterator<String> it = mPendingUploads.keySet().iterator(); boolean found = false; while (it.hasNext() && !found) { found = it.next().startsWith(targetKey); } return found; } else { return (mPendingUploads.containsKey(targetKey)); } } } | /**
* Returns True when the file described by 'file' is being uploaded to
* the ownCloud account 'account' or waiting for it
*
* If 'file' is a directory, returns 'true' if some of its descendant files
* is uploading or waiting to upload.
*
* @param account ownCloud account where the remote file will be stored.
* @param file A file that could be in the queue of pending uploads
*/ | Returns True when the file described by 'file' is being uploaded to the ownCloud account 'account' or waiting for it If 'file' is a directory, returns 'true' if some of its descendant files is uploading or waiting to upload | isUploading | {
"repo_name": "asifdahir/nscloud",
"path": "src/com/nscloud/android/files/services/FileUploader.java",
"license": "gpl-2.0",
"size": 41699
} | [
"android.accounts.Account",
"com.nscloud.android.datamodel.OCFile",
"java.util.Iterator"
] | import android.accounts.Account; import com.nscloud.android.datamodel.OCFile; import java.util.Iterator; | import android.accounts.*; import com.nscloud.android.datamodel.*; import java.util.*; | [
"android.accounts",
"com.nscloud.android",
"java.util"
] | android.accounts; com.nscloud.android; java.util; | 2,643,402 |
synchronized Point3i transformPoint(Point3f pointAngstroms) {
matrixTransform.transform2(pointAngstroms, point3fScreenTemp);
return adjustedTemporaryScreenPoint();
} | synchronized Point3i transformPoint(Point3f pointAngstroms) { matrixTransform.transform2(pointAngstroms, point3fScreenTemp); return adjustedTemporaryScreenPoint(); } | /**
* CAUTION! returns a POINTER TO A TEMPORARY VARIABLE
* @param pointAngstroms
* @return POINTER TO point3iScreenTemp
*/ | CAUTION! returns a POINTER TO A TEMPORARY VARIABLE | transformPoint | {
"repo_name": "ajschult/etomica",
"path": "etomica-graphics3D/src/main/java/g3dsys/control/TransformManager.java",
"license": "mpl-2.0",
"size": 27238
} | [
"org.jmol.util.Point3f",
"org.jmol.util.Point3i"
] | import org.jmol.util.Point3f; import org.jmol.util.Point3i; | import org.jmol.util.*; | [
"org.jmol.util"
] | org.jmol.util; | 378,127 |
public UserProfile registerUser(String loginName, String clearPassword,
UserProfileDetails userProfileDetails)
throws DuplicateInstanceException; | UserProfile function(String loginName, String clearPassword, UserProfileDetails userProfileDetails) throws DuplicateInstanceException; | /**
* Register user.
*
* @param loginName
* the login name
* @param clearPassword
* the clear password
* @param userProfileDetails
* the user profile details
* @return the user profile
* @throws DuplicateInstanceException
* the duplicate instance exception
*/ | Register user | registerUser | {
"repo_name": "iago-suarez/pojo-cinema-app",
"path": "src/main/java/es/udc/pojo/model/userservice/UserService.java",
"license": "gpl-2.0",
"size": 2956
} | [
"es.udc.pojo.model.userprofile.UserProfile",
"es.udc.pojo.modelutil.exceptions.DuplicateInstanceException"
] | import es.udc.pojo.model.userprofile.UserProfile; import es.udc.pojo.modelutil.exceptions.DuplicateInstanceException; | import es.udc.pojo.model.userprofile.*; import es.udc.pojo.modelutil.exceptions.*; | [
"es.udc.pojo"
] | es.udc.pojo; | 2,826,846 |
@Test
public void setupPathTest3() {
build4RouterTopo(false, false, false, false, 0); // TE cost is set here.
List<Constraint> constraints = new LinkedList<Constraint>();
CostConstraint costConstraint = new CostConstraint(TE_COST);
constraints.add(costConstraint);
boolean result = pceManager.setupPath(D1.deviceId(), D2.deviceId(), "T123", constraints, WITH_SIGNALLING);
assertThat(result, is(true));
} | void function() { build4RouterTopo(false, false, false, false, 0); List<Constraint> constraints = new LinkedList<Constraint>(); CostConstraint costConstraint = new CostConstraint(TE_COST); constraints.add(costConstraint); boolean result = pceManager.setupPath(D1.deviceId(), D2.deviceId(), "T123", constraints, WITH_SIGNALLING); assertThat(result, is(true)); } | /**
* Tests path success with TE-cost constraint for signalled LSP.
*/ | Tests path success with TE-cost constraint for signalled LSP | setupPathTest3 | {
"repo_name": "Shashikanth-Huawei/bmp",
"path": "apps/pce/app/src/test/java/org/onosproject/pce/pceservice/PceManagerTest.java",
"license": "apache-2.0",
"size": 65722
} | [
"java.util.LinkedList",
"java.util.List",
"org.hamcrest.MatcherAssert",
"org.hamcrest.core.Is",
"org.onosproject.net.intent.Constraint",
"org.onosproject.pce.pceservice.constraint.CostConstraint"
] | import java.util.LinkedList; import java.util.List; import org.hamcrest.MatcherAssert; import org.hamcrest.core.Is; import org.onosproject.net.intent.Constraint; import org.onosproject.pce.pceservice.constraint.CostConstraint; | import java.util.*; import org.hamcrest.*; import org.hamcrest.core.*; import org.onosproject.net.intent.*; import org.onosproject.pce.pceservice.constraint.*; | [
"java.util",
"org.hamcrest",
"org.hamcrest.core",
"org.onosproject.net",
"org.onosproject.pce"
] | java.util; org.hamcrest; org.hamcrest.core; org.onosproject.net; org.onosproject.pce; | 1,179,395 |
@Nonnull
public java.util.concurrent.CompletableFuture<WindowsAutopilotDeviceIdentity> putAsync(@Nonnull final WindowsAutopilotDeviceIdentity newWindowsAutopilotDeviceIdentity) {
return sendAsync(HttpMethod.PUT, newWindowsAutopilotDeviceIdentity);
} | java.util.concurrent.CompletableFuture<WindowsAutopilotDeviceIdentity> function(@Nonnull final WindowsAutopilotDeviceIdentity newWindowsAutopilotDeviceIdentity) { return sendAsync(HttpMethod.PUT, newWindowsAutopilotDeviceIdentity); } | /**
* Creates a WindowsAutopilotDeviceIdentity with a new object
*
* @param newWindowsAutopilotDeviceIdentity the object to create/update
* @return a future with the result
*/ | Creates a WindowsAutopilotDeviceIdentity with a new object | putAsync | {
"repo_name": "microsoftgraph/msgraph-sdk-java",
"path": "src/main/java/com/microsoft/graph/requests/WindowsAutopilotDeviceIdentityRequest.java",
"license": "mit",
"size": 6764
} | [
"com.microsoft.graph.http.HttpMethod",
"com.microsoft.graph.models.WindowsAutopilotDeviceIdentity",
"javax.annotation.Nonnull"
] | import com.microsoft.graph.http.HttpMethod; import com.microsoft.graph.models.WindowsAutopilotDeviceIdentity; import javax.annotation.Nonnull; | import com.microsoft.graph.http.*; import com.microsoft.graph.models.*; import javax.annotation.*; | [
"com.microsoft.graph",
"javax.annotation"
] | com.microsoft.graph; javax.annotation; | 506,526 |
private List<Object> getPreOrder() {
if (preOrder == null) {
preOrder = new ArrayList<Object>();
Collection<?> rootItemIds = getContainerDataSource()
.rootItemIds();
for (Object id : rootItemIds) {
preOrder.add(id);
addVisibleChildTree(id);
}
}
return preOrder;
} | List<Object> function() { if (preOrder == null) { preOrder = new ArrayList<Object>(); Collection<?> rootItemIds = getContainerDataSource() .rootItemIds(); for (Object id : rootItemIds) { preOrder.add(id); addVisibleChildTree(id); } } return preOrder; } | /**
* Preorder of ids currently visible
*
* @return
*/ | Preorder of ids currently visible | getPreOrder | {
"repo_name": "peterl1084/framework",
"path": "compatibility-server/src/main/java/com/vaadin/v7/ui/TreeTable.java",
"license": "apache-2.0",
"size": 31087
} | [
"java.util.ArrayList",
"java.util.Collection",
"java.util.List"
] | import java.util.ArrayList; import java.util.Collection; import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 2,665,310 |
public void setByteOrder(ByteOrder byteOrder) {
this.byteOrder = byteOrder;
} | void function(ByteOrder byteOrder) { this.byteOrder = byteOrder; } | /**
* Sets the byte order.
*
* @param byteOrder the new byte order
*/ | Sets the byte order | setByteOrder | {
"repo_name": "EasyinnovaSL/Tiff-Library-4J",
"path": "src/main/java/com/easyinnova/tiff/writer/TiffWriter.java",
"license": "gpl-3.0",
"size": 14610
} | [
"com.easyinnova.tiff.model.ByteOrder"
] | import com.easyinnova.tiff.model.ByteOrder; | import com.easyinnova.tiff.model.*; | [
"com.easyinnova.tiff"
] | com.easyinnova.tiff; | 1,857,584 |
@Test(expected = IllegalStateException.class)
public void dualstackInClientAndConfiguration_ThrowsIllegalStateException() {
buildClient(withDualstackEnabled(), b -> b.dualstackEnabled(true));
} | @Test(expected = IllegalStateException.class) void function() { buildClient(withDualstackEnabled(), b -> b.dualstackEnabled(true)); } | /**
* Only configure dualstack enabled in one place.
*/ | Only configure dualstack enabled in one place | dualstackInClientAndConfiguration_ThrowsIllegalStateException | {
"repo_name": "aws/aws-sdk-java-v2",
"path": "services/s3/src/test/java/software/amazon/awssdk/services/s3/S3EndpointResolutionTest.java",
"license": "apache-2.0",
"size": 40014
} | [
"org.junit.Test"
] | import org.junit.Test; | import org.junit.*; | [
"org.junit"
] | org.junit; | 1,381,962 |
public void setClasspathRef(final Reference ref) {
createClasspath().setRefid(ref);
} | void function(final Reference ref) { createClasspath().setRefid(ref); } | /**
* Set the classpath for loading
* using the classpath reference.
*
* @param ref the refid to use
*/ | Set the classpath for loading using the classpath reference | setClasspathRef | {
"repo_name": "PascalSchumacher/incubator-groovy",
"path": "subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovy.java",
"license": "apache-2.0",
"size": 23072
} | [
"org.apache.tools.ant.types.Reference"
] | import org.apache.tools.ant.types.Reference; | import org.apache.tools.ant.types.*; | [
"org.apache.tools"
] | org.apache.tools; | 1,313,895 |
protected void syncMembership(@NotNull ExternalIdentity external, @NotNull Authorizable auth, long depth)
throws RepositoryException {
if (depth <= 0) {
return;
}
log.debug("Syncing membership '{}' -> '{}'", external.getExternalId().getString(), auth.getID());
final DebugTimer timer = new DebugTimer();
Iterable<ExternalIdentityRef> externalGroups;
try {
externalGroups = external.getDeclaredGroups();
} catch (ExternalIdentityException e) {
log.error("Error while retrieving external declared groups for '{}'", external.getId(), e);
return;
}
timer.mark("fetching");
// first get the set of the existing groups that are synced ones
Map<String, Group> declaredExternalGroups = new HashMap<>();
Iterator<Group> grpIter = auth.declaredMemberOf();
while (grpIter.hasNext()) {
Group grp = grpIter.next();
if (isSameIDP(grp)) {
declaredExternalGroups.put(grp.getID(), grp);
}
}
timer.mark("reading");
for (ExternalIdentityRef ref : externalGroups) {
log.debug("- processing membership {}", ref.getId());
// get group
ExternalGroup extGroup;
try {
ExternalIdentity extId = idp.getIdentity(ref);
if (extId instanceof ExternalGroup) {
extGroup = (ExternalGroup) extId;
} else {
log.warn("No external group found for ref '{}'.", ref.getString());
continue;
}
} catch (ExternalIdentityException e) {
log.warn("Unable to retrieve external group '{}' from provider.", ref.getString(), e);
continue;
}
log.debug("- idp returned '{}'", extGroup.getId());
// mark group as processed
Group grp = declaredExternalGroups.remove(extGroup.getId());
boolean exists = grp != null;
if (!exists) {
Authorizable a = userManager.getAuthorizable(extGroup.getId());
if (a == null) {
grp = createGroup(extGroup);
log.debug("- created new group");
} else if (a.isGroup() && isSameIDP(a)) {
grp = (Group) a;
} else {
log.warn("Existing authorizable '{}' is not a group from this IDP '{}'.", extGroup.getId(), idp.getName());
continue;
}
log.debug("- user manager returned '{}'", grp);
}
syncGroup(extGroup, grp);
if (!exists) {
// ensure membership
grp.addMember(auth);
log.debug("- added '{}' as member to '{}'", auth, grp);
}
// recursively apply further membership
if (depth > 1) {
log.debug("- recursively sync group membership of '{}' (depth = {}).", grp.getID(), depth);
syncMembership(extGroup, grp, depth - 1);
} else {
log.debug("- group nesting level for '{}' reached", grp.getID());
}
}
timer.mark("adding");
// remove us from the lost membership groups
for (Group grp : declaredExternalGroups.values()) {
grp.removeMember(auth);
log.debug("- removing member '{}' for group '{}'", auth.getID(), grp.getID());
}
timer.mark("removing");
log.debug("syncMembership({}) {}", external.getId(), timer);
} | void function(@NotNull ExternalIdentity external, @NotNull Authorizable auth, long depth) throws RepositoryException { if (depth <= 0) { return; } log.debug(STR, external.getExternalId().getString(), auth.getID()); final DebugTimer timer = new DebugTimer(); Iterable<ExternalIdentityRef> externalGroups; try { externalGroups = external.getDeclaredGroups(); } catch (ExternalIdentityException e) { log.error(STR, external.getId(), e); return; } timer.mark(STR); Map<String, Group> declaredExternalGroups = new HashMap<>(); Iterator<Group> grpIter = auth.declaredMemberOf(); while (grpIter.hasNext()) { Group grp = grpIter.next(); if (isSameIDP(grp)) { declaredExternalGroups.put(grp.getID(), grp); } } timer.mark(STR); for (ExternalIdentityRef ref : externalGroups) { log.debug(STR, ref.getId()); ExternalGroup extGroup; try { ExternalIdentity extId = idp.getIdentity(ref); if (extId instanceof ExternalGroup) { extGroup = (ExternalGroup) extId; } else { log.warn(STR, ref.getString()); continue; } } catch (ExternalIdentityException e) { log.warn(STR, ref.getString(), e); continue; } log.debug(STR, extGroup.getId()); Group grp = declaredExternalGroups.remove(extGroup.getId()); boolean exists = grp != null; if (!exists) { Authorizable a = userManager.getAuthorizable(extGroup.getId()); if (a == null) { grp = createGroup(extGroup); log.debug(STR); } else if (a.isGroup() && isSameIDP(a)) { grp = (Group) a; } else { log.warn(STR, extGroup.getId(), idp.getName()); continue; } log.debug(STR, grp); } syncGroup(extGroup, grp); if (!exists) { grp.addMember(auth); log.debug(STR, auth, grp); } if (depth > 1) { log.debug(STR, grp.getID(), depth); syncMembership(extGroup, grp, depth - 1); } else { log.debug(STR, grp.getID()); } } timer.mark(STR); for (Group grp : declaredExternalGroups.values()) { grp.removeMember(auth); log.debug(STR, auth.getID(), grp.getID()); } timer.mark(STR); log.debug(STR, external.getId(), timer); } | /**
* Recursively sync the memberships of an authorizable up-to the specified depth. If the given depth
* is equal or less than 0, no syncing is performed.
*
* @param external the external identity
* @param auth the authorizable
* @param depth recursion depth.
* @throws RepositoryException If a user management specific error occurs upon synchronizing membership
*/ | Recursively sync the memberships of an authorizable up-to the specified depth. If the given depth is equal or less than 0, no syncing is performed | syncMembership | {
"repo_name": "apache/jackrabbit-oak",
"path": "oak-auth-external/src/main/java/org/apache/jackrabbit/oak/spi/security/authentication/external/basic/DefaultSyncContext.java",
"license": "apache-2.0",
"size": 31583
} | [
"java.util.HashMap",
"java.util.Iterator",
"java.util.Map",
"javax.jcr.RepositoryException",
"org.apache.jackrabbit.api.security.user.Authorizable",
"org.apache.jackrabbit.api.security.user.Group",
"org.apache.jackrabbit.oak.commons.DebugTimer",
"org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalGroup",
"org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentity",
"org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityException",
"org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityRef",
"org.jetbrains.annotations.NotNull"
] | import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.jcr.RepositoryException; import org.apache.jackrabbit.api.security.user.Authorizable; import org.apache.jackrabbit.api.security.user.Group; import org.apache.jackrabbit.oak.commons.DebugTimer; import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalGroup; import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentity; import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityException; import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityRef; import org.jetbrains.annotations.NotNull; | import java.util.*; import javax.jcr.*; import org.apache.jackrabbit.api.security.user.*; import org.apache.jackrabbit.oak.commons.*; import org.apache.jackrabbit.oak.spi.security.authentication.external.*; import org.jetbrains.annotations.*; | [
"java.util",
"javax.jcr",
"org.apache.jackrabbit",
"org.jetbrains.annotations"
] | java.util; javax.jcr; org.apache.jackrabbit; org.jetbrains.annotations; | 200,619 |
public ManagedClusterIdentity identity() {
return this.identity;
} | ManagedClusterIdentity function() { return this.identity; } | /**
* Get the identity of the managed cluster, if configured.
*
* @return the identity value
*/ | Get the identity of the managed cluster, if configured | identity | {
"repo_name": "selvasingh/azure-sdk-for-java",
"path": "sdk/containerservice/mgmt-v2020_07_01/src/main/java/com/microsoft/azure/management/containerservice/v2020_07_01/implementation/ManagedClusterInner.java",
"license": "mit",
"size": 17856
} | [
"com.microsoft.azure.management.containerservice.v2020_07_01.ManagedClusterIdentity"
] | import com.microsoft.azure.management.containerservice.v2020_07_01.ManagedClusterIdentity; | import com.microsoft.azure.management.containerservice.v2020_07_01.*; | [
"com.microsoft.azure"
] | com.microsoft.azure; | 1,513,465 |
private Node tryFoldHook(Node n) {
Preconditions.checkState(n.isHook());
Node parent = n.getParent();
Preconditions.checkNotNull(parent);
Node cond = n.getFirstChild();
Node thenBody = cond.getNext();
Node elseBody = thenBody.getNext();
TernaryValue condValue = NodeUtil.getImpureBooleanValue(cond);
if (condValue == TernaryValue.UNKNOWN) {
// If the result nodes are equivalent, then one of the nodes can be
// removed and it doesn't matter which.
if (!areNodesEqualForInlining(thenBody, elseBody)) {
return n; // We can't remove branches otherwise!
}
}
// Transform "(a = 2) ? x =2 : y" into "a=2,x=2"
Node branchToKeep = condValue.toBoolean(true) ? thenBody : elseBody;
Node replacement;
boolean condHasSideEffects = mayHaveSideEffects(cond);
// Must detach after checking for side effects, to ensure that the parents
// of nodes are set correctly.
n.detachChildren();
if (condHasSideEffects) {
replacement = IR.comma(cond, branchToKeep).srcref(n);
} else {
replacement = branchToKeep;
}
parent.replaceChild(n, replacement);
reportCodeChange();
return replacement;
} | Node function(Node n) { Preconditions.checkState(n.isHook()); Node parent = n.getParent(); Preconditions.checkNotNull(parent); Node cond = n.getFirstChild(); Node thenBody = cond.getNext(); Node elseBody = thenBody.getNext(); TernaryValue condValue = NodeUtil.getImpureBooleanValue(cond); if (condValue == TernaryValue.UNKNOWN) { if (!areNodesEqualForInlining(thenBody, elseBody)) { return n; } } Node branchToKeep = condValue.toBoolean(true) ? thenBody : elseBody; Node replacement; boolean condHasSideEffects = mayHaveSideEffects(cond); n.detachChildren(); if (condHasSideEffects) { replacement = IR.comma(cond, branchToKeep).srcref(n); } else { replacement = branchToKeep; } parent.replaceChild(n, replacement); reportCodeChange(); return replacement; } | /**
* Try folding HOOK (?:) if the condition results of the condition is known.
* @return the replacement node, if changed, or the original if not
*/ | Try folding HOOK (?:) if the condition results of the condition is known | tryFoldHook | {
"repo_name": "zombiezen/cardcpx",
"path": "third_party/closure-compiler/src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java",
"license": "apache-2.0",
"size": 31811
} | [
"com.google.common.base.Preconditions",
"com.google.javascript.rhino.IR",
"com.google.javascript.rhino.Node",
"com.google.javascript.rhino.jstype.TernaryValue"
] | import com.google.common.base.Preconditions; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.jstype.TernaryValue; | import com.google.common.base.*; import com.google.javascript.rhino.*; import com.google.javascript.rhino.jstype.*; | [
"com.google.common",
"com.google.javascript"
] | com.google.common; com.google.javascript; | 902,324 |
public static char checkUnicodeEscapeChar(String s) {
if (s.length() != 1) {
throw RESOURCE.unicodeEscapeCharLength(s).ex();
}
char c = s.charAt(0);
if (Character.isDigit(c)
|| Character.isWhitespace(c)
|| (c == '+')
|| (c == '"')
|| ((c >= 'a') && (c <= 'f'))
|| ((c >= 'A') && (c <= 'F'))) {
throw RESOURCE.unicodeEscapeCharIllegal(s).ex();
}
return c;
}
//~ Inner Classes ----------------------------------------------------------
public static class ParsedCollation {
private final Charset charset;
private final Locale locale;
private final String strength;
public ParsedCollation(
Charset charset,
Locale locale,
String strength) {
this.charset = charset;
this.locale = locale;
this.strength = strength;
} | static char function(String s) { if (s.length() != 1) { throw RESOURCE.unicodeEscapeCharLength(s).ex(); } char c = s.charAt(0); if (Character.isDigit(c) Character.isWhitespace(c) (c == '+') (c == '"') ((c >= 'a') && (c <= 'f')) ((c >= 'A') && (c <= 'F'))) { throw RESOURCE.unicodeEscapeCharIllegal(s).ex(); } return c; } public static class ParsedCollation { private final Charset charset; private final Locale locale; private final String strength; public ParsedCollation( Charset charset, Locale locale, String strength) { this.charset = charset; this.locale = locale; this.strength = strength; } | /**
* Checks a UESCAPE string for validity, and returns the escape character if
* no exception is thrown.
*
* @param s UESCAPE string to check
* @return validated escape character
*/ | Checks a UESCAPE string for validity, and returns the escape character if no exception is thrown | checkUnicodeEscapeChar | {
"repo_name": "sreev/incubator-calcite",
"path": "core/src/main/java/org/apache/calcite/sql/parser/SqlParserUtil.java",
"license": "apache-2.0",
"size": 26930
} | [
"java.nio.charset.Charset",
"java.util.Locale",
"org.apache.calcite.util.Static"
] | import java.nio.charset.Charset; import java.util.Locale; import org.apache.calcite.util.Static; | import java.nio.charset.*; import java.util.*; import org.apache.calcite.util.*; | [
"java.nio",
"java.util",
"org.apache.calcite"
] | java.nio; java.util; org.apache.calcite; | 1,801,702 |
protected void startActivityForResult(Intent intent, int code) {
activity.startActivityForResult(intent, code);
} | void function(Intent intent, int code) { activity.startActivityForResult(intent, code); } | /**
* Start an activity. This method is defined to allow different methods of
* activity starting for newer versions of Android and for compatibility
* library.
*
* @param intent
* Intent to start.
* @param code
* Request code for the activity
* @see android.app.Activity#startActivityForResult(Intent, int)
* @see android.app.Fragment#startActivityForResult(Intent, int)
*/ | Start an activity. This method is defined to allow different methods of activity starting for newer versions of Android and for compatibility library | startActivityForResult | {
"repo_name": "alberapps/tiempobus",
"path": "TiempoBus/src/alberapps/android/tiempobus/barcode/IntentIntegrator.java",
"license": "gpl-3.0",
"size": 15408
} | [
"android.content.Intent"
] | import android.content.Intent; | import android.content.*; | [
"android.content"
] | android.content; | 2,849,391 |
public static SeqOfGANSSTimeModel_R10_Ext fromPerAligned(byte[] encodedBytes) {
SeqOfGANSSTimeModel_R10_Ext result = new SeqOfGANSSTimeModel_R10_Ext();
result.decodePerAligned(new BitStreamReader(encodedBytes));
return result;
} | static SeqOfGANSSTimeModel_R10_Ext function(byte[] encodedBytes) { SeqOfGANSSTimeModel_R10_Ext result = new SeqOfGANSSTimeModel_R10_Ext(); result.decodePerAligned(new BitStreamReader(encodedBytes)); return result; } | /**
* Creates a new SeqOfGANSSTimeModel_R10_Ext from encoded stream.
*/ | Creates a new SeqOfGANSSTimeModel_R10_Ext from encoded stream | fromPerAligned | {
"repo_name": "google/supl-client",
"path": "src/main/java/com/google/location/suplclient/asn1/supl2/rrlp_components/SeqOfGANSSTimeModel_R10_Ext.java",
"license": "apache-2.0",
"size": 3692
} | [
"com.google.location.suplclient.asn1.base.BitStreamReader"
] | import com.google.location.suplclient.asn1.base.BitStreamReader; | import com.google.location.suplclient.asn1.base.*; | [
"com.google.location"
] | com.google.location; | 917,629 |
public void addAnnotation(XYAnnotation annotation) {
// defer argument checking
addAnnotation(annotation, Layer.FOREGROUND);
}
| void function(XYAnnotation annotation) { addAnnotation(annotation, Layer.FOREGROUND); } | /**
* Adds an annotation and sends a {@link RendererChangeEvent} to all
* registered listeners. The annotation is added to the foreground
* layer.
*
* @param annotation the annotation (<code>null</code> not permitted).
*/ | Adds an annotation and sends a <code>RendererChangeEvent</code> to all registered listeners. The annotation is added to the foreground layer | addAnnotation | {
"repo_name": "lulab/PI",
"path": "MISC_scripts/java/Kevin_scripts/org/jfree/chart/renderer/xy/AbstractXYItemRenderer.java",
"license": "gpl-2.0",
"size": 72893
} | [
"org.jfree.chart.annotations.XYAnnotation",
"org.jfree.ui.Layer"
] | import org.jfree.chart.annotations.XYAnnotation; import org.jfree.ui.Layer; | import org.jfree.chart.annotations.*; import org.jfree.ui.*; | [
"org.jfree.chart",
"org.jfree.ui"
] | org.jfree.chart; org.jfree.ui; | 2,586,370 |
@Override
protected void validateComponent(final List<Diagnostic> diags) {
if (isParseable()) {
super.validateComponent(diags);
validateDate(diags);
} else {
diags.add(createErrorDiagnostic(getComponentModel().errorMessage, this));
}
} | void function(final List<Diagnostic> diags) { if (isParseable()) { super.validateComponent(diags); validateDate(diags); } else { diags.add(createErrorDiagnostic(getComponentModel().errorMessage, this)); } } | /**
* Override WInput's validateComponent to perform further validation on the date.
*
* @param diags the list into which any validation diagnostics are added.
*/ | Override WInput's validateComponent to perform further validation on the date | validateComponent | {
"repo_name": "ricksbrown/wcomponents",
"path": "wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WDateField.java",
"license": "gpl-3.0",
"size": 12177
} | [
"com.github.bordertech.wcomponents.validation.Diagnostic",
"java.util.List"
] | import com.github.bordertech.wcomponents.validation.Diagnostic; import java.util.List; | import com.github.bordertech.wcomponents.validation.*; import java.util.*; | [
"com.github.bordertech",
"java.util"
] | com.github.bordertech; java.util; | 2,517,692 |
@NonNull public static Logger getLogger() {
return logger;
} | @NonNull static Logger function() { return logger; } | /**
* Returns the logger used by this logging class.
*
* @return Either default or custom logger.
*
* @see #setLogger(Logger)
*/ | Returns the logger used by this logging class | getLogger | {
"repo_name": "universum-studios/android_fragments",
"path": "library-core/src/main/java/universum/studios/android/fragment/FragmentsLogging.java",
"license": "apache-2.0",
"size": 5548
} | [
"androidx.annotation.NonNull"
] | import androidx.annotation.NonNull; | import androidx.annotation.*; | [
"androidx.annotation"
] | androidx.annotation; | 2,364,377 |
@Override
public Path globVersionPattern() {
return this.globPattern;
} | Path function() { return this.globPattern; } | /**
* Obtained by replacing all non-slash characters in datetime pattern by *.
* E.g. yyyy/MM/dd/hh/mm -> *\/*\/*\/*\/*
*/ | Obtained by replacing all non-slash characters in datetime pattern by *. E.g. yyyy/MM/dd/hh/mm -> *\/*\/*\/*\ | globVersionPattern | {
"repo_name": "sahooamit/bigdata",
"path": "gobblin-data-management/src/main/java/gobblin/data/management/retention/version/finder/DateTimeDatasetVersionFinder.java",
"license": "apache-2.0",
"size": 3514
} | [
"org.apache.hadoop.fs.Path"
] | import org.apache.hadoop.fs.Path; | import org.apache.hadoop.fs.*; | [
"org.apache.hadoop"
] | org.apache.hadoop; | 949,905 |
try (InputStream in = resource.getInputStream()) {
return CertUtil.readCertificate(in);
} catch (final Exception e) {
throw new IllegalArgumentException("Error reading certificate " + resource, e);
}
} | try (InputStream in = resource.getInputStream()) { return CertUtil.readCertificate(in); } catch (final Exception e) { throw new IllegalArgumentException(STR + resource, e); } } | /**
* Read certificate x 509 certificate.
*
* @param resource the resource
* @return the x 509 certificate
*/ | Read certificate x 509 certificate | readCertificate | {
"repo_name": "prigaux/cas",
"path": "support/cas-server-support-saml-core/src/main/java/org/apereo/cas/support/saml/SamlUtils.java",
"license": "apache-2.0",
"size": 11144
} | [
"java.io.InputStream",
"org.cryptacular.util.CertUtil"
] | import java.io.InputStream; import org.cryptacular.util.CertUtil; | import java.io.*; import org.cryptacular.util.*; | [
"java.io",
"org.cryptacular.util"
] | java.io; org.cryptacular.util; | 2,903,976 |
@Operation(desc = "Closes the session with the id", impact = MBeanOperationInfo.INFO)
boolean closeSessionWithID(@Parameter(desc = "The connection ID", name = "connectionID") String connectionID,
@Parameter(desc = "The session ID", name = "ID") String ID) throws Exception; | @Operation(desc = STR, impact = MBeanOperationInfo.INFO) boolean closeSessionWithID(@Parameter(desc = STR, name = STR) String connectionID, @Parameter(desc = STR, name = "ID") String ID) throws Exception; | /**
* Closes the session with the given id.
*/ | Closes the session with the given id | closeSessionWithID | {
"repo_name": "gaohoward/activemq-artemis",
"path": "artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ActiveMQServerControl.java",
"license": "apache-2.0",
"size": 83324
} | [
"javax.management.MBeanOperationInfo"
] | import javax.management.MBeanOperationInfo; | import javax.management.*; | [
"javax.management"
] | javax.management; | 1,925,371 |
public static BigInteger[] string2BigIntegers(String plaintext) {
String base64 = base64Encode(plaintext);
int length = (int) Math.ceil(base64.length() * 1.0d / BLOCK_SIZE);
BigInteger[] bigIntegers = new BigInteger[length];
String text = null;
for (int i = 0; i < length - 1; i++) {
int start = i * BLOCK_SIZE;
text = base64.substring(start, start + BLOCK_SIZE);
bigIntegers[i] = toBigInteger(text);
}
if (length == 1) {
bigIntegers[0] = toBigInteger(base64);
}
if (length > 1) {
int start = (length - 1) * BLOCK_SIZE;
text = base64.substring(start, base64.length());
bigIntegers[length - 1] = toBigInteger(text);
}
return bigIntegers;
} | static BigInteger[] function(String plaintext) { String base64 = base64Encode(plaintext); int length = (int) Math.ceil(base64.length() * 1.0d / BLOCK_SIZE); BigInteger[] bigIntegers = new BigInteger[length]; String text = null; for (int i = 0; i < length - 1; i++) { int start = i * BLOCK_SIZE; text = base64.substring(start, start + BLOCK_SIZE); bigIntegers[i] = toBigInteger(text); } if (length == 1) { bigIntegers[0] = toBigInteger(base64); } if (length > 1) { int start = (length - 1) * BLOCK_SIZE; text = base64.substring(start, base64.length()); bigIntegers[length - 1] = toBigInteger(text); } return bigIntegers; } | /**
* String 2 big integers big integer [ ].
*
* @param plaintext the plaintext
* @return the big integer [ ]
*/ | String 2 big integers big integer [ ] | string2BigIntegers | {
"repo_name": "forsrc/MyStudy",
"path": "src/main/java/com/forsrc/utils/MyRsaUtils.java",
"license": "apache-2.0",
"size": 16784
} | [
"java.math.BigInteger"
] | import java.math.BigInteger; | import java.math.*; | [
"java.math"
] | java.math; | 103,002 |
public static char[] bArr2HexEdChars(byte[] data, int len)
{
// {OFFSET} {HEXADECIMAL} {ASCII}{NEWLINE}
final int lineLength = 9 + (_HEX_ED_BPL * _HEX_ED_CPB) + 1 + _HEX_ED_BPL + _NEW_LINE_CHARS.length;
final int lenBplMod = len % _HEX_ED_BPL;
// create text buffer
// 1. don't allocate a full last line if not _HEX_ED_BPL bytes are shown in last line
// 2. no new line at end of buffer
// BUG: when the length is multiple of _HEX_ED_BPL we erase the whole ascii space with this
// char[] textData = new char[lineLength * numLines - (_HEX_ED_BPL - (len % _HEX_ED_BPL)) - _NEW_LINE_CHARS.length];
// FIXED HERE
int numLines;
char[] textData;
if (lenBplMod == 0)
{
numLines = len / _HEX_ED_BPL;
textData = new char[(lineLength * numLines) - _NEW_LINE_CHARS.length];
}
else
{
numLines = (len / _HEX_ED_BPL) + 1;
textData = new char[(lineLength * numLines) - (_HEX_ED_BPL - (lenBplMod)) - _NEW_LINE_CHARS.length];
}
// performance penalty, only doing space filling in the loop is faster
// Arrays.fill(textData, ' ');
int dataOffset;
int dataLen;
int lineStart;
int lineHexDataStart;
int lineAsciiDataStart;
for (int i = 0; i < numLines; ++i)
{
dataOffset = i * _HEX_ED_BPL;
dataLen = Math.min(len - dataOffset, _HEX_ED_BPL);
lineStart = i * lineLength;
lineHexDataStart = lineStart + 9;
lineAsciiDataStart = lineHexDataStart + (_HEX_ED_BPL * _HEX_ED_CPB) + 1;
int2HexChars(dataOffset, textData, lineStart); // the offset of this line
textData[lineHexDataStart - 1] = ' '; // separate
bArr2HexChars(data, dataOffset, dataLen, textData, lineHexDataStart); // the data in hex
bArr2AsciiChars(data, dataOffset, dataLen, textData, lineAsciiDataStart); // the data in ascii
if (i < (numLines - 1))
{
textData[lineAsciiDataStart - 1] = ' '; // separate
System.arraycopy(_NEW_LINE_CHARS, 0, textData, lineAsciiDataStart + _HEX_ED_BPL, _NEW_LINE_CHARS.length); // the new line
}
else if (dataLen < _HEX_ED_BPL)
{
// last line which shows less than _HEX_ED_BPL bytes
final int lineHexDataEnd = lineHexDataStart + (dataLen * _HEX_ED_CPB);
Arrays.fill(textData, lineHexDataEnd, lineHexDataEnd + ((_HEX_ED_BPL - dataLen) * _HEX_ED_CPB) + 1, ' '); // spaces, for the last line if there are not _HEX_ED_BPL bytes
}
else
{
// last line which shows _HEX_ED_BPL bytes
textData[lineAsciiDataStart - 1] = ' '; // separate
}
}
return textData;
} | static char[] function(byte[] data, int len) { final int lineLength = 9 + (_HEX_ED_BPL * _HEX_ED_CPB) + 1 + _HEX_ED_BPL + _NEW_LINE_CHARS.length; final int lenBplMod = len % _HEX_ED_BPL; int numLines; char[] textData; if (lenBplMod == 0) { numLines = len / _HEX_ED_BPL; textData = new char[(lineLength * numLines) - _NEW_LINE_CHARS.length]; } else { numLines = (len / _HEX_ED_BPL) + 1; textData = new char[(lineLength * numLines) - (_HEX_ED_BPL - (lenBplMod)) - _NEW_LINE_CHARS.length]; } int dataOffset; int dataLen; int lineStart; int lineHexDataStart; int lineAsciiDataStart; for (int i = 0; i < numLines; ++i) { dataOffset = i * _HEX_ED_BPL; dataLen = Math.min(len - dataOffset, _HEX_ED_BPL); lineStart = i * lineLength; lineHexDataStart = lineStart + 9; lineAsciiDataStart = lineHexDataStart + (_HEX_ED_BPL * _HEX_ED_CPB) + 1; int2HexChars(dataOffset, textData, lineStart); textData[lineHexDataStart - 1] = ' '; bArr2HexChars(data, dataOffset, dataLen, textData, lineHexDataStart); bArr2AsciiChars(data, dataOffset, dataLen, textData, lineAsciiDataStart); if (i < (numLines - 1)) { textData[lineAsciiDataStart - 1] = ' '; System.arraycopy(_NEW_LINE_CHARS, 0, textData, lineAsciiDataStart + _HEX_ED_BPL, _NEW_LINE_CHARS.length); } else if (dataLen < _HEX_ED_BPL) { final int lineHexDataEnd = lineHexDataStart + (dataLen * _HEX_ED_CPB); Arrays.fill(textData, lineHexDataEnd, lineHexDataEnd + ((_HEX_ED_BPL - dataLen) * _HEX_ED_CPB) + 1, ' '); } else { textData[lineAsciiDataStart - 1] = ' '; } } return textData; } | /**
* Method to generate the hexadecimal character representation of a byte array like in a hex editor<br>
* Line Format: {OFFSET} {HEXADECIMAL} {ASCII}({NEWLINE})<br>
* {OFFSET} = offset of the first byte in line(8 chars)<br>
* {HEXADECIMAL} = hexadecimal character representation({@link #_HEX_ED_BPL}*2 chars)<br>
* {ASCII} = ascii character presentation({@link #_HEX_ED_BPL} chars)
* @param data byte array to generate the hexadecimal character representation
* @param len the number of bytes to generate the hexadecimal character representation from
* @return byte array which contains the hexadecimal character representation of the given byte array
*/ | Method to generate the hexadecimal character representation of a byte array like in a hex editor Line Format: {OFFSET} {HEXADECIMAL} {ASCII}({NEWLINE}) {OFFSET} = offset of the first byte in line(8 chars) {HEXADECIMAL} = hexadecimal character representation(<code>#_HEX_ED_BPL</code>*2 chars) {ASCII} = ascii character presentation(<code>#_HEX_ED_BPL</code> chars) | bArr2HexEdChars | {
"repo_name": "rubenswagner/L2J-Global",
"path": "java/com/l2jglobal/commons/util/HexUtils.java",
"license": "gpl-3.0",
"size": 9763
} | [
"java.util.Arrays"
] | import java.util.Arrays; | import java.util.*; | [
"java.util"
] | java.util; | 1,651,986 |
public static Domain createPseudoDomain(Provisioning prov) throws ServiceException {
return (Domain)createPseudoTarget(prov, TargetType.domain, null, null, false, null, null);
} | static Domain function(Provisioning prov) throws ServiceException { return (Domain)createPseudoTarget(prov, TargetType.domain, null, null, false, null, null); } | /**
* short hand for PseudoTarget.createPseudoTarget(prov, TargetType.domain, null, null, false, null, null);
* @param prov
* @return
* @throws ServiceException
*/ | short hand for PseudoTarget.createPseudoTarget(prov, TargetType.domain, null, null, false, null, null) | createPseudoDomain | {
"repo_name": "nico01f/z-pec",
"path": "ZimbraServer/src/java/com/zimbra/cs/account/accesscontrol/PseudoTarget.java",
"license": "mit",
"size": 13556
} | [
"com.zimbra.common.service.ServiceException",
"com.zimbra.cs.account.Domain",
"com.zimbra.cs.account.Provisioning"
] | import com.zimbra.common.service.ServiceException; import com.zimbra.cs.account.Domain; import com.zimbra.cs.account.Provisioning; | import com.zimbra.common.service.*; import com.zimbra.cs.account.*; | [
"com.zimbra.common",
"com.zimbra.cs"
] | com.zimbra.common; com.zimbra.cs; | 1,006,470 |
public Set<Conflict> conflicts(Enrollment e1, Enrollment e2) {
Set<Conflict> ret = new HashSet<Conflict>();
for (Type type: iContext.getTypes()) {
if (!e1.getStudent().equals(e2.getStudent()) || !type.isApplicable(iContext, e1.getStudent(), e1.getRequest(), e2.getRequest())) continue;
for (SctAssignment s1 : e1.getAssignments()) {
for (SctAssignment s2 : e2.getAssignments()) {
int penalty = type.penalty(iContext, s1, s2);
if (penalty > 0)
ret.add(new Conflict(e1.getStudent(), type, penalty, e1, s1, e2, s2));
}
}
}
return ret;
} | Set<Conflict> function(Enrollment e1, Enrollment e2) { Set<Conflict> ret = new HashSet<Conflict>(); for (Type type: iContext.getTypes()) { if (!e1.getStudent().equals(e2.getStudent()) !type.isApplicable(iContext, e1.getStudent(), e1.getRequest(), e2.getRequest())) continue; for (SctAssignment s1 : e1.getAssignments()) { for (SctAssignment s2 : e2.getAssignments()) { int penalty = type.penalty(iContext, s1, s2); if (penalty > 0) ret.add(new Conflict(e1.getStudent(), type, penalty, e1, s1, e2, s2)); } } } return ret; } | /**
* Conflicts of any type between two enrollments of a student.
*/ | Conflicts of any type between two enrollments of a student | conflicts | {
"repo_name": "UniTime/cpsolver",
"path": "src/org/cpsolver/studentsct/extension/StudentQuality.java",
"license": "lgpl-3.0",
"size": 76743
} | [
"java.util.HashSet",
"java.util.Set",
"org.cpsolver.studentsct.model.Enrollment",
"org.cpsolver.studentsct.model.SctAssignment"
] | import java.util.HashSet; import java.util.Set; import org.cpsolver.studentsct.model.Enrollment; import org.cpsolver.studentsct.model.SctAssignment; | import java.util.*; import org.cpsolver.studentsct.model.*; | [
"java.util",
"org.cpsolver.studentsct"
] | java.util; org.cpsolver.studentsct; | 2,048,245 |
private void clearClientDeadChannels() {
ArrayList<Messenger> deadClients = new ArrayList<Messenger>();
for (ClientInfo c : mClientInfoList.values()) {
Message msg = Message.obtain();
msg.what = WifiP2pManager.PING;
msg.arg1 = 0;
msg.arg2 = 0;
msg.obj = null;
try {
c.mMessenger.send(msg);
} catch (RemoteException e) {
if (DBG) logd("detect dead channel");
deadClients.add(c.mMessenger);
}
}
for (Messenger m : deadClients) {
clearClientInfo(m);
}
} | void function() { ArrayList<Messenger> deadClients = new ArrayList<Messenger>(); for (ClientInfo c : mClientInfoList.values()) { Message msg = Message.obtain(); msg.what = WifiP2pManager.PING; msg.arg1 = 0; msg.arg2 = 0; msg.obj = null; try { c.mMessenger.send(msg); } catch (RemoteException e) { if (DBG) logd(STR); deadClients.add(c.mMessenger); } } for (Messenger m : deadClients) { clearClientInfo(m); } } | /**
* We dont get notifications of clients that have gone away.
* We detect this actively when services are added and throw
* them away.
*
* TODO: This can be done better with full async channels.
*/ | We dont get notifications of clients that have gone away. We detect this actively when services are added and throw them away | clearClientDeadChannels | {
"repo_name": "rex-xxx/mt6572_x201",
"path": "frameworks/base/wifi/java/android/net/wifi/p2p/WifiP2pService.java",
"license": "gpl-2.0",
"size": 143712
} | [
"android.os.Message",
"android.os.Messenger",
"android.os.RemoteException",
"java.util.ArrayList"
] | import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import java.util.ArrayList; | import android.os.*; import java.util.*; | [
"android.os",
"java.util"
] | android.os; java.util; | 2,900,137 |
public String hmset(final byte[] key, final Map<byte[], byte[]> hash) {
checkIsInMultiOrPipeline();
client.hmset(key, hash);
return client.getStatusCodeReply();
} | String function(final byte[] key, final Map<byte[], byte[]> hash) { checkIsInMultiOrPipeline(); client.hmset(key, hash); return client.getStatusCodeReply(); } | /**
* Set the respective fields to the respective values. HMSET replaces old values with new values.
* <p>
* If key does not exist, a new key holding a hash is created.
* <p>
* <b>Time complexity:</b> O(N) (with N being the number of fields)
* @param key
* @param hash
* @return Always OK because HMSET can't fail
*/ | Set the respective fields to the respective values. HMSET replaces old values with new values. If key does not exist, a new key holding a hash is created. Time complexity: O(N) (with N being the number of fields) | hmset | {
"repo_name": "corydolphin/jedis",
"path": "src/main/java/redis/clients/jedis/BinaryJedis.java",
"license": "mit",
"size": 122575
} | [
"java.util.Map"
] | import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 2,179,604 |
@Test
public void testGetRabat2() {
assertEquals((Integer) 11, products.getRabat2());
} | void function() { assertEquals((Integer) 11, products.getRabat2()); } | /**
* Test getter of product's second salary piece.
*/ | Test getter of product's second salary piece | testGetRabat2 | {
"repo_name": "firstvan/OrderTaker",
"path": "model/src/test/java/hu/firstvan/model/ProductsTest.java",
"license": "gpl-3.0",
"size": 5768
} | [
"org.junit.Assert"
] | import org.junit.Assert; | import org.junit.*; | [
"org.junit"
] | org.junit; | 2,071,479 |
public com.mozu.api.contracts.customer.CustomerNote getAccountNote(Integer accountId, Integer noteId, String responseFields) throws Exception
{
MozuClient<com.mozu.api.contracts.customer.CustomerNote> client = com.mozu.api.clients.commerce.customer.accounts.CustomerNoteClient.getAccountNoteClient( accountId, noteId, responseFields);
client.setContext(_apiContext);
client.executeRequest();
return client.getResult();
} | com.mozu.api.contracts.customer.CustomerNote function(Integer accountId, Integer noteId, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.customer.CustomerNote> client = com.mozu.api.clients.commerce.customer.accounts.CustomerNoteClient.getAccountNoteClient( accountId, noteId, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } | /**
* Retrieves the contents of a particular note attached to a specified customer account.
* <p><pre><code>
* CustomerNote customernote = new CustomerNote();
* CustomerNote customerNote = customernote.getAccountNote( accountId, noteId, responseFields);
* </code></pre></p>
* @param accountId Unique identifier of the customer account that contains the note being retrieved.
* @param noteId Unique identifier of a particular note to retrieve.
* @param responseFields Use this field to include those fields which are not included by default.
* @return com.mozu.api.contracts.customer.CustomerNote
* @see com.mozu.api.contracts.customer.CustomerNote
*/ | Retrieves the contents of a particular note attached to a specified customer account. <code><code> CustomerNote customernote = new CustomerNote(); CustomerNote customerNote = customernote.getAccountNote( accountId, noteId, responseFields); </code></code> | getAccountNote | {
"repo_name": "eileenzhuang1/mozu-java",
"path": "mozu-java-core/src/main/java/com/mozu/api/resources/commerce/customer/accounts/CustomerNoteResource.java",
"license": "mit",
"size": 10561
} | [
"com.mozu.api.MozuClient"
] | import com.mozu.api.MozuClient; | import com.mozu.api.*; | [
"com.mozu.api"
] | com.mozu.api; | 568,713 |
public List<HandlerType<HandlerChainType<T>>> getAllHandler(); | List<HandlerType<HandlerChainType<T>>> function(); | /**
* Returns all <code>handler</code> elements
* @return list of <code>handler</code>
*/ | Returns all <code>handler</code> elements | getAllHandler | {
"repo_name": "forge/javaee-descriptors",
"path": "api/src/main/java/org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient14/HandlerChainType.java",
"license": "epl-1.0",
"size": 6046
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 1,367,481 |
EReference getTrans_Priority();
| EReference getTrans_Priority(); | /**
* Returns the meta object for the containment reference '{@link io.github.abelgomez.cpntools.Trans#getPriority <em>Priority</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Priority</em>'.
* @see io.github.abelgomez.cpntools.Trans#getPriority()
* @see #getTrans()
* @generated
*/ | Returns the meta object for the containment reference '<code>io.github.abelgomez.cpntools.Trans#getPriority Priority</code>'. | getTrans_Priority | {
"repo_name": "abelgomez/cpntools.toolkit",
"path": "plugins/io.github.abelgomez.cpntools/src/io/github/abelgomez/cpntools/CpntoolsPackage.java",
"license": "epl-1.0",
"size": 204644
} | [
"org.eclipse.emf.ecore.EReference"
] | import org.eclipse.emf.ecore.EReference; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 188,105 |
public MacAddress getPublicFacingMac() {
return publicFacingMac;
} | MacAddress function() { return publicFacingMac; } | /**
* Gets the MAC address configured for all the public IP addresses.
*
* @return the MAC address
*/ | Gets the MAC address configured for all the public IP addresses | getPublicFacingMac | {
"repo_name": "jmiserez/onos",
"path": "apps/virtualbng/src/main/java/org/onosproject/virtualbng/VbngConfiguration.java",
"license": "apache-2.0",
"size": 2937
} | [
"org.onlab.packet.MacAddress"
] | import org.onlab.packet.MacAddress; | import org.onlab.packet.*; | [
"org.onlab.packet"
] | org.onlab.packet; | 1,952,315 |
default AdvancedSqs2EndpointConsumerBuilder pollStrategy(
PollingConsumerPollStrategy pollStrategy) {
doSetProperty("pollStrategy", pollStrategy);
return this;
} | default AdvancedSqs2EndpointConsumerBuilder pollStrategy( PollingConsumerPollStrategy pollStrategy) { doSetProperty(STR, pollStrategy); return this; } | /**
* A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing
* you to provide your custom implementation to control error handling
* usually occurred during the poll operation before an Exchange have
* been created and being routed in Camel.
*
* The option is a:
* <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type.
*
* Group: consumer (advanced)
*/ | A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel. The option is a: <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type. Group: consumer (advanced) | pollStrategy | {
"repo_name": "ullgren/camel",
"path": "core/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/Sqs2EndpointBuilderFactory.java",
"license": "apache-2.0",
"size": 88450
} | [
"org.apache.camel.spi.PollingConsumerPollStrategy"
] | import org.apache.camel.spi.PollingConsumerPollStrategy; | import org.apache.camel.spi.*; | [
"org.apache.camel"
] | org.apache.camel; | 2,532,685 |
public void setCondition(Expression condition) {
this.condition = condition;
}
DoStmt() {
super();
}
DoStmt(Statement body, Expression condition, NodeList<AnnotationExpr> annotations, int posBegin, int posEnd) {
super(annotations, posBegin, posEnd);
this.body = body;
this.condition = condition;
} | void function(Expression condition) { this.condition = condition; } DoStmt() { super(); } DoStmt(Statement body, Expression condition, NodeList<AnnotationExpr> annotations, int posBegin, int posEnd) { super(annotations, posBegin, posEnd); this.body = body; this.condition = condition; } | /**
* Sets the condition.
*
* @param condition the new condition
*/ | Sets the condition | setCondition | {
"repo_name": "DigiArea/jse-model",
"path": "com.digiarea.jse/src/com/digiarea/jse/DoStmt.java",
"license": "epl-1.0",
"size": 2707
} | [
"com.digiarea.jse.AnnotationExpr",
"com.digiarea.jse.Expression",
"com.digiarea.jse.NodeList",
"com.digiarea.jse.Statement"
] | import com.digiarea.jse.AnnotationExpr; import com.digiarea.jse.Expression; import com.digiarea.jse.NodeList; import com.digiarea.jse.Statement; | import com.digiarea.jse.*; | [
"com.digiarea.jse"
] | com.digiarea.jse; | 1,110,396 |
public Observable<ServiceResponse<ExpressRouteConnectionListInner>> listWithServiceResponseAsync(String resourceGroupName, String expressRouteGatewayName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (expressRouteGatewayName == null) {
throw new IllegalArgumentException("Parameter expressRouteGatewayName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
} | Observable<ServiceResponse<ExpressRouteConnectionListInner>> function(String resourceGroupName, String expressRouteGatewayName) { if (resourceGroupName == null) { throw new IllegalArgumentException(STR); } if (expressRouteGatewayName == null) { throw new IllegalArgumentException(STR); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException(STR); } | /**
* Lists ExpressRouteConnections.
*
* @param resourceGroupName The name of the resource group.
* @param expressRouteGatewayName The name of the ExpressRoute gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ExpressRouteConnectionListInner object
*/ | Lists ExpressRouteConnections | listWithServiceResponseAsync | {
"repo_name": "selvasingh/azure-sdk-for-java",
"path": "sdk/network/mgmt-v2019_04_01/src/main/java/com/microsoft/azure/management/network/v2019_04_01/implementation/ExpressRouteConnectionsInner.java",
"license": "mit",
"size": 39006
} | [
"com.microsoft.rest.ServiceResponse"
] | import com.microsoft.rest.ServiceResponse; | import com.microsoft.rest.*; | [
"com.microsoft.rest"
] | com.microsoft.rest; | 2,163,649 |
@RequestMapping(value = "/startServiceSOS", method = RequestMethod.POST)
public ModelAndView startServiceHandler(@ModelAttribute("startEditorBeanSML") StartEditorBeanSML pEditorBean,
BindingResult pResult) {
//Error handling
ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceUrl", "errors.service.url.empty");
ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceType", "errors.service.type.empty");
if (pEditorBean.getServiceType().equalsIgnoreCase("ARCIMS")) {
ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceName", "errors.service.name.empty");
}
if (pEditorBean.getServiceType().equalsIgnoreCase(SOS_SERVICE_TYPE)) {
ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceTokenForSOS", "errors.service.tokenForSOS.empty");
ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceProcedureIDForSOS", "errors.service.procedureIDForSOS.empty");
ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceOperationForSOS", "errors.service.operationForSOS.empty");
}
if (pResult.hasErrors()) {
LOG.debug("Form validation errors: " + pResult);
// return form view
return new ModelAndView(getFormView(), getModelMap());
}
//Set service URL
String serviceUrl=pEditorBean.getServiceUrl();
LOG.debug("ServiceUrl set to '" + serviceUrl + "'");
//Create webservice
if(pEditorBean.getServiceType().equalsIgnoreCase(SOS_SERVICE_TYPE)){//serviceTypes are defined in codelist_enumeration.xml in identifier: CT_ServiceTypeExt.
LOG.debug("Put SOS values into webserviceDescriptionDAO");
StartEditorBeanSML editorBeanSML = (StartEditorBeanSML) pEditorBean;
//Set procedureID
String procId = editorBeanSML.getServiceProcedureIDForSOS();
LOG.debug("Procedure ID set to '" + procId + "'");
//Set token
String token = editorBeanSML.getServiceTokenForSOS();
LOG.debug("Token is set to '" + token + "'");
//Set the token and the serviceUrl within the BackendBeanSml to insert them in the selectStates.jsp file.
BackendBean backendBean=getBackendService().getBackend();
if(backendBean instanceof BackendBeanSML){
BackendBeanSML backendBeanSML=((BackendBeanSML)backendBean);
backendBeanSML.setServiceURL(serviceUrl);
LOG.debug("ServiceUrl is set in the BeackendBean '" + serviceUrl + "'");
backendBeanSML.setServiceTokenSOS(token);
LOG.debug("Token is set in the BackendBean '" + token + "'");
}
//For request
Document catalogRequest = null;
Document catalogResponse=null;
Map parameterMap = new HashMap();
parameterMap.put("procedureId", procId);
SOSCatalogService sosService = getSOSCatalogServiceDAO();
sosService.init(serviceUrl);
sosService.addRequestHeader("Authorization", token);
sosService.addRequestHeader("Content-Type", "application/soap+xml");
//When a sensor should be edited
if (editorBeanSML.getServiceOperationForSOS().equalsIgnoreCase(SOS_Operation_DESCRIBE)) {
//Create Request and do transaction
catalogRequest = getRequestFactory().createRequest("get" , parameterMap);
catalogResponse = sosService.transaction(catalogRequest);//does it really throw an exception??
if(catalogResponse==null){
Map<String, Object> lModel=getModelMap();
lModel.put("response", new TransactionResponseSOS());
lModel.put("serverError","errors.service.connect.request");
lModel.put("sourcePage","startService");
return new ModelAndView(getFinishView(), lModel);
}
//For Transformation
Document sensorML = DOMUtil.newDocument(true);
Source source = new DOMSource(catalogResponse);
Result result = new DOMResult(sensorML);
String transformerFilePath=getTransformerFiles().get(SOS_SERVICE_TYPE.toLowerCase());
getXsltTransformer().setRulesetSystemID(transformerFilePath);
// transform
getXsltTransformer().transform(source, result);
getBackendService().initBackend(sensorML);
getBackendService().setUpdate(true);
return new ModelAndView(getSuccessView());
}
//When a sensor should be deleted
if (editorBeanSML.getServiceOperationForSOS().equalsIgnoreCase(SOS_Operation_DELETE)) {
catalogRequest = getRequestFactory().createRequest("delete" , parameterMap);
catalogResponse = sosService.transaction(catalogRequest);
Map<String, Object> lModel = new HashMap<String, Object>();
lModel.put("sourcePage","startService");
if(catalogResponse==null){
lModel.put("response", new TransactionResponseSOS());
lModel.put("serverError","errors.service.connect.request");
return new ModelAndView(getFinishView(), lModel);
}
lModel.put("response", new TransactionResponseSOS(catalogResponse));
return new ModelAndView(getFinishView(), lModel);
}
}else{
WebServiceDescriptionDAO dao = getServiceFactory().getDescriptionDAO(pEditorBean.getServiceType().toLowerCase());
dao.setUrl(serviceUrl);
LOG.trace("Current dao: " + dao);
if (!"".equals(pEditorBean.getServiceName())) {
dao.setServiceName(pEditorBean.getServiceName());
}
try {
Document lDoc = dao.getDescription();
if (LOG.isTraceEnabled()) {
String docString = DOMUtil.convertToString(lDoc, true);
LOG.trace("Retrieved document from DAO: " + docString);
}
if (lDoc != null) {
getBackendService().setUpdate(true);
getBackendService().initBackend(lDoc);
return new ModelAndView(getSuccessView());
}
} catch (WebServiceDescriptionException e) {
pResult.rejectValue("serviceUrl", "errors.service.connect", new Object[]{e.getMessage()}, "Capabilities error");
return new ModelAndView(getFormView(), getModelMap());
}
}
return new ModelAndView(getFormView());
} | @RequestMapping(value = STR, method = RequestMethod.POST) ModelAndView function(@ModelAttribute(STR) StartEditorBeanSML pEditorBean, BindingResult pResult) { ValidationUtils.rejectIfEmptyOrWhitespace(pResult, STR, STR); ValidationUtils.rejectIfEmptyOrWhitespace(pResult, STR, STR); if (pEditorBean.getServiceType().equalsIgnoreCase(STR)) { ValidationUtils.rejectIfEmptyOrWhitespace(pResult, STR, STR); } if (pEditorBean.getServiceType().equalsIgnoreCase(SOS_SERVICE_TYPE)) { ValidationUtils.rejectIfEmptyOrWhitespace(pResult, STR, STR); ValidationUtils.rejectIfEmptyOrWhitespace(pResult, STR, STR); ValidationUtils.rejectIfEmptyOrWhitespace(pResult, STR, STR); } if (pResult.hasErrors()) { LOG.debug(STR + pResult); return new ModelAndView(getFormView(), getModelMap()); } String serviceUrl=pEditorBean.getServiceUrl(); LOG.debug(STR + serviceUrl + "'"); if(pEditorBean.getServiceType().equalsIgnoreCase(SOS_SERVICE_TYPE)){ LOG.debug(STR); StartEditorBeanSML editorBeanSML = (StartEditorBeanSML) pEditorBean; String procId = editorBeanSML.getServiceProcedureIDForSOS(); LOG.debug(STR + procId + "'"); String token = editorBeanSML.getServiceTokenForSOS(); LOG.debug(STR + token + "'"); BackendBean backendBean=getBackendService().getBackend(); if(backendBean instanceof BackendBeanSML){ BackendBeanSML backendBeanSML=((BackendBeanSML)backendBean); backendBeanSML.setServiceURL(serviceUrl); LOG.debug(STR + serviceUrl + "'"); backendBeanSML.setServiceTokenSOS(token); LOG.debug(STR + token + "'"); } Document catalogRequest = null; Document catalogResponse=null; Map parameterMap = new HashMap(); parameterMap.put(STR, procId); SOSCatalogService sosService = getSOSCatalogServiceDAO(); sosService.init(serviceUrl); sosService.addRequestHeader(STR, token); sosService.addRequestHeader(STR, STR); if (editorBeanSML.getServiceOperationForSOS().equalsIgnoreCase(SOS_Operation_DESCRIBE)) { catalogRequest = getRequestFactory().createRequest("get" , parameterMap); catalogResponse = sosService.transaction(catalogRequest); if(catalogResponse==null){ Map<String, Object> lModel=getModelMap(); lModel.put(STR, new TransactionResponseSOS()); lModel.put(STR,STR); lModel.put(STR,STR); return new ModelAndView(getFinishView(), lModel); } Document sensorML = DOMUtil.newDocument(true); Source source = new DOMSource(catalogResponse); Result result = new DOMResult(sensorML); String transformerFilePath=getTransformerFiles().get(SOS_SERVICE_TYPE.toLowerCase()); getXsltTransformer().setRulesetSystemID(transformerFilePath); getXsltTransformer().transform(source, result); getBackendService().initBackend(sensorML); getBackendService().setUpdate(true); return new ModelAndView(getSuccessView()); } if (editorBeanSML.getServiceOperationForSOS().equalsIgnoreCase(SOS_Operation_DELETE)) { catalogRequest = getRequestFactory().createRequest(STR , parameterMap); catalogResponse = sosService.transaction(catalogRequest); Map<String, Object> lModel = new HashMap<String, Object>(); lModel.put(STR,STR); if(catalogResponse==null){ lModel.put(STR, new TransactionResponseSOS()); lModel.put(STR,STR); return new ModelAndView(getFinishView(), lModel); } lModel.put(STR, new TransactionResponseSOS(catalogResponse)); return new ModelAndView(getFinishView(), lModel); } }else{ WebServiceDescriptionDAO dao = getServiceFactory().getDescriptionDAO(pEditorBean.getServiceType().toLowerCase()); dao.setUrl(serviceUrl); LOG.trace(STR + dao); if (!STRRetrieved document from DAO: " + docString); } if (lDoc != null) { getBackendService().setUpdate(true); getBackendService().initBackend(lDoc); return new ModelAndView(getSuccessView()); } } catch (WebServiceDescriptionException e) { pResult.rejectValue(STR, "errors.service.connectSTRCapabilities error"); return new ModelAndView(getFormView(), getModelMap()); } } return new ModelAndView(getFormView()); } | /**
* Starts editor with a service description
*
* @param pEditorBean
* @param pResult
* @return
*/ | Starts editor with a service description | startServiceHandler | {
"repo_name": "nuest/Sensor_SmartEditor",
"path": "smartsensoreditor-api/src/main/java/org/n52/smartsensoreditor/controller/StartEditorControllerSML.java",
"license": "apache-2.0",
"size": 11863
} | [
"de.conterra.smarteditor.beans.BackendBean",
"de.conterra.smarteditor.dao.WebServiceDescriptionDAO",
"de.conterra.smarteditor.dao.WebServiceDescriptionException",
"de.conterra.smarteditor.util.DOMUtil",
"java.util.HashMap",
"java.util.Map",
"javax.xml.transform.Result",
"javax.xml.transform.Source",
"javax.xml.transform.dom.DOMResult",
"javax.xml.transform.dom.DOMSource",
"org.n52.smartsensoreditor.beans.BackendBeanSML",
"org.n52.smartsensoreditor.beans.StartEditorBeanSML",
"org.n52.smartsensoreditor.cswclient.facades.TransactionResponseSOS",
"org.n52.smartsensoreditor.dao.SOSCatalogService",
"org.springframework.validation.BindingResult",
"org.springframework.validation.ValidationUtils",
"org.springframework.web.bind.annotation.ModelAttribute",
"org.springframework.web.bind.annotation.RequestMapping",
"org.springframework.web.bind.annotation.RequestMethod",
"org.springframework.web.servlet.ModelAndView",
"org.w3c.dom.Document"
] | import de.conterra.smarteditor.beans.BackendBean; import de.conterra.smarteditor.dao.WebServiceDescriptionDAO; import de.conterra.smarteditor.dao.WebServiceDescriptionException; import de.conterra.smarteditor.util.DOMUtil; import java.util.HashMap; import java.util.Map; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import org.n52.smartsensoreditor.beans.BackendBeanSML; import org.n52.smartsensoreditor.beans.StartEditorBeanSML; import org.n52.smartsensoreditor.cswclient.facades.TransactionResponseSOS; import org.n52.smartsensoreditor.dao.SOSCatalogService; import org.springframework.validation.BindingResult; import org.springframework.validation.ValidationUtils; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.w3c.dom.Document; | import de.conterra.smarteditor.beans.*; import de.conterra.smarteditor.dao.*; import de.conterra.smarteditor.util.*; import java.util.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import org.n52.smartsensoreditor.beans.*; import org.n52.smartsensoreditor.cswclient.facades.*; import org.n52.smartsensoreditor.dao.*; import org.springframework.validation.*; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.*; import org.w3c.dom.*; | [
"de.conterra.smarteditor",
"java.util",
"javax.xml",
"org.n52.smartsensoreditor",
"org.springframework.validation",
"org.springframework.web",
"org.w3c.dom"
] | de.conterra.smarteditor; java.util; javax.xml; org.n52.smartsensoreditor; org.springframework.validation; org.springframework.web; org.w3c.dom; | 1,046,076 |
@Override
public int addUsedAxis(UsedAxis usedAxis, String treeId) throws PdcException {
try (final Connection con = DBUtil.openConnection()) {
if (utilizationDAO
.isAlreadyAdded(con, usedAxis.getInstanceId(), Integer.parseInt(usedAxis.getPK().getId()),
usedAxis.getAxisId(), usedAxis.getBaseValue(), treeId)) {
return 1;
} else {
dao.add(usedAxis);
}
} catch (Exception e) {
throw new PdcException(e);
}
return 0;
} | int function(UsedAxis usedAxis, String treeId) throws PdcException { try (final Connection con = DBUtil.openConnection()) { if (utilizationDAO .isAlreadyAdded(con, usedAxis.getInstanceId(), Integer.parseInt(usedAxis.getPK().getId()), usedAxis.getAxisId(), usedAxis.getBaseValue(), treeId)) { return 1; } else { dao.add(usedAxis); } } catch (Exception e) { throw new PdcException(e); } return 0; } | /**
* Create an used axis into the data base.
* @param usedAxis - the object which contains all data about utilization of an axis
* @param treeId
* @return usedAxisId
*/ | Create an used axis into the data base | addUsedAxis | {
"repo_name": "SilverDav/Silverpeas-Core",
"path": "core-services/pdc/src/main/java/org/silverpeas/core/pdc/pdc/service/DefaultPdcUtilizationService.java",
"license": "agpl-3.0",
"size": 12092
} | [
"java.sql.Connection",
"org.silverpeas.core.pdc.pdc.model.PdcException",
"org.silverpeas.core.pdc.pdc.model.UsedAxis",
"org.silverpeas.core.persistence.jdbc.DBUtil"
] | import java.sql.Connection; import org.silverpeas.core.pdc.pdc.model.PdcException; import org.silverpeas.core.pdc.pdc.model.UsedAxis; import org.silverpeas.core.persistence.jdbc.DBUtil; | import java.sql.*; import org.silverpeas.core.pdc.pdc.model.*; import org.silverpeas.core.persistence.jdbc.*; | [
"java.sql",
"org.silverpeas.core"
] | java.sql; org.silverpeas.core; | 2,640,715 |
public static void startAllServers() throws Exception {
assertNotNull("KdcServer is null and cannot be started", kdcServer);
assertNotNull("LdapServer is null and cannot be started", ldapServer);
assertNotNull("DirectoryService is null and cannot be started", directoryService);
Log.info(c, "startAllServers", "Starting all ApacheDS servers");
directoryService.startup();
ldapServer.start();
kdcServer.start();
Log.info(c, "startAllServers", "Started all ApacheDS servers");
} | static void function() throws Exception { assertNotNull(STR, kdcServer); assertNotNull(STR, ldapServer); assertNotNull(STR, directoryService); Log.info(c, STR, STR); directoryService.startup(); ldapServer.start(); kdcServer.start(); Log.info(c, STR, STR); } | /**
* Start all the servers related to ApacheDS
*
* @throws Exception
*/ | Start all the servers related to ApacheDS | startAllServers | {
"repo_name": "kgibm/open-liberty",
"path": "dev/com.ibm.ws.security.wim.adapter.ldap_fat.krb5/fat/src/com/ibm/ws/security/wim/adapter/ldap/fat/krb5/ApacheDSandKDC.java",
"license": "epl-1.0",
"size": 29051
} | [
"com.ibm.websphere.simplicity.log.Log",
"org.junit.Assert"
] | import com.ibm.websphere.simplicity.log.Log; import org.junit.Assert; | import com.ibm.websphere.simplicity.log.*; import org.junit.*; | [
"com.ibm.websphere",
"org.junit"
] | com.ibm.websphere; org.junit; | 695,749 |
public Bed[] getBeds() {
Bed[] beds = bedDAO.getBedsByRoom(null, null);
for (Bed bed : beds) {
setAttributes(bed);
}
return beds;
} | Bed[] function() { Bed[] beds = bedDAO.getBedsByRoom(null, null); for (Bed bed : beds) { setAttributes(bed); } return beds; } | /**
* Get beds
*
* @return array of beds
*/ | Get beds | getBeds | {
"repo_name": "oscarservice/oscar-old",
"path": "src/main/java/org/oscarehr/PMmodule/service/BedManager.java",
"license": "gpl-2.0",
"size": 19185
} | [
"org.oscarehr.PMmodule"
] | import org.oscarehr.PMmodule; | import org.oscarehr.*; | [
"org.oscarehr"
] | org.oscarehr; | 2,478,992 |
private boolean updateData(DatabaseModifyType modifyType, String data, DatabaseType type) {
if(type == DatabaseType.GROUP) {
if(modifyType == DatabaseModifyType.DELETE) {
MooCache.getInstance().getGroupMap().remove(data);
// GROUP HAS BEEN DELETED
return true;
}
else if(modifyType == DatabaseModifyType.CREATE || modifyType == DatabaseModifyType.MODIFY) {
Group group = ReflectionUtil.deserialize(data, Group.class);
MooCache.getInstance().getGroupMap().fastPut(group.getName(), new MooGroup(group));
// GROUP HAS BEEN UPDATED
if(modifyType == DatabaseModifyType.CREATE) {
return true;
}
}
else if(modifyType == DatabaseModifyType.MODIFY_PRIMARY) {
List<String> l = StringUtil.split(data);
Object id = ReflectionUtil.safeCast(l.get(0));
Group group = ReflectionUtil.deserialize(l.get(1), Group.class);
MooCache.getInstance().getGroupMap().remove((String)id);
MooCache.getInstance().getGroupMap().fastPut(group.getName(), new MooGroup(group));
return true;
}
}
else if(type == DatabaseType.PLAYER) {
if(modifyType == DatabaseModifyType.DELETE) {
MooCache.getInstance().getPlayerMap().remove(UUID.fromString(data));
// PLAYERDATA HAS BEEN DELETED ? WHAT THE FLACK? (Shouldnt happen)
}
else if(modifyType == DatabaseModifyType.CREATE || modifyType == DatabaseModifyType.MODIFY) {
PlayerData playerData = ReflectionUtil.deserialize(data, PlayerData.class);
MooCache.getInstance().getPlayerMap().fastPut(playerData.getUuid(), new MooPlayer(playerData));
// UPDATE PERMISSIONS IF EDITED
if(modifyType == DatabaseModifyType.MODIFY) {
return true;
}
}
}
return false;
} | boolean function(DatabaseModifyType modifyType, String data, DatabaseType type) { if(type == DatabaseType.GROUP) { if(modifyType == DatabaseModifyType.DELETE) { MooCache.getInstance().getGroupMap().remove(data); return true; } else if(modifyType == DatabaseModifyType.CREATE modifyType == DatabaseModifyType.MODIFY) { Group group = ReflectionUtil.deserialize(data, Group.class); MooCache.getInstance().getGroupMap().fastPut(group.getName(), new MooGroup(group)); if(modifyType == DatabaseModifyType.CREATE) { return true; } } else if(modifyType == DatabaseModifyType.MODIFY_PRIMARY) { List<String> l = StringUtil.split(data); Object id = ReflectionUtil.safeCast(l.get(0)); Group group = ReflectionUtil.deserialize(l.get(1), Group.class); MooCache.getInstance().getGroupMap().remove((String)id); MooCache.getInstance().getGroupMap().fastPut(group.getName(), new MooGroup(group)); return true; } } else if(type == DatabaseType.PLAYER) { if(modifyType == DatabaseModifyType.DELETE) { MooCache.getInstance().getPlayerMap().remove(UUID.fromString(data)); } else if(modifyType == DatabaseModifyType.CREATE modifyType == DatabaseModifyType.MODIFY) { PlayerData playerData = ReflectionUtil.deserialize(data, PlayerData.class); MooCache.getInstance().getPlayerMap().fastPut(playerData.getUuid(), new MooPlayer(playerData)); if(modifyType == DatabaseModifyType.MODIFY) { return true; } } } return false; } | /**
* Similar to {@link #updateData(AbstractPacket, Object, MultiMap, DatabaseType, boolean)} but with only subdata not a whole set
* of updates.
*
* @param modifyType The modify type
* @param data The data
* @param type The database type
* @return The result (true=updatePerm; false=do not)
*/ | Similar to <code>#updateData(AbstractPacket, Object, MultiMap, DatabaseType, boolean)</code> but with only subdata not a whole set of updates | updateData | {
"repo_name": "Superioz/MooProject",
"path": "master/src/main/java/de/superioz/moo/cloud/listeners/packet/PacketDatabaseModifyListener.java",
"license": "gpl-2.0",
"size": 10374
} | [
"de.superioz.moo.api.database.DatabaseModifyType",
"de.superioz.moo.api.database.DatabaseType",
"de.superioz.moo.api.database.objects.Group",
"de.superioz.moo.api.database.objects.PlayerData",
"de.superioz.moo.api.utils.ReflectionUtil",
"de.superioz.moo.api.utils.StringUtil",
"de.superioz.moo.network.common.MooCache",
"de.superioz.moo.network.common.MooGroup",
"de.superioz.moo.network.common.MooPlayer",
"java.util.List",
"java.util.UUID"
] | import de.superioz.moo.api.database.DatabaseModifyType; import de.superioz.moo.api.database.DatabaseType; import de.superioz.moo.api.database.objects.Group; import de.superioz.moo.api.database.objects.PlayerData; import de.superioz.moo.api.utils.ReflectionUtil; import de.superioz.moo.api.utils.StringUtil; import de.superioz.moo.network.common.MooCache; import de.superioz.moo.network.common.MooGroup; import de.superioz.moo.network.common.MooPlayer; import java.util.List; import java.util.UUID; | import de.superioz.moo.api.database.*; import de.superioz.moo.api.database.objects.*; import de.superioz.moo.api.utils.*; import de.superioz.moo.network.common.*; import java.util.*; | [
"de.superioz.moo",
"java.util"
] | de.superioz.moo; java.util; | 2,628,983 |
public static Host getByUuid(Connection c, String uuid) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "host.get_by_uuid";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toHost(result);
} | static Host function(Connection c, String uuid) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = STR; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toHost(result); } | /**
* Get a reference to the host instance with the specified UUID.
*
* @param uuid UUID of object to return
* @return reference to the object
*/ | Get a reference to the host instance with the specified UUID | getByUuid | {
"repo_name": "cinderella/incubator-cloudstack",
"path": "deps/XenServerJava/com/xensource/xenapi/Host.java",
"license": "apache-2.0",
"size": 105838
} | [
"com.xensource.xenapi.Types",
"java.util.Map",
"org.apache.xmlrpc.XmlRpcException"
] | import com.xensource.xenapi.Types; import java.util.Map; import org.apache.xmlrpc.XmlRpcException; | import com.xensource.xenapi.*; import java.util.*; import org.apache.xmlrpc.*; | [
"com.xensource.xenapi",
"java.util",
"org.apache.xmlrpc"
] | com.xensource.xenapi; java.util; org.apache.xmlrpc; | 625,168 |
public static HashMap merge(Map map1, Map map2)
{
HashMap retval = new HashMap(calcCapacity(map1.size() + map2.size()));
retval.putAll(map1);
retval.putAll(map2);
return retval;
}
| static HashMap function(Map map1, Map map2) { HashMap retval = new HashMap(calcCapacity(map1.size() + map2.size())); retval.putAll(map1); retval.putAll(map2); return retval; } | /**
* Creates a new <code>HashMap</code> that has all of the elements
* of <code>map1</code> and <code>map2</code> (on key collision, the latter
* override the former).
*
* @param map1 the fist hashmap to merge
* @param map2 the second hashmap to merge
* @return new hashmap
*/ | Creates a new <code>HashMap</code> that has all of the elements of <code>map1</code> and <code>map2</code> (on key collision, the latter override the former) | merge | {
"repo_name": "GIP-RECIA/esco-grouper-ui",
"path": "ext/bundles/myfaces-impl/src/main/java/org/apache/myfaces/shared_impl/util/HashMapUtils.java",
"license": "apache-2.0",
"size": 3867
} | [
"java.util.HashMap",
"java.util.Map"
] | import java.util.HashMap; import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 358,168 |
protected void addServiceFactory(final ServiceFactory<? extends Service> factory, final int index) {
logger.debug("Adding [{}] application context", factory);
final List<ServiceFactory<? extends Service>> list =
applicationContext.getBean("serviceFactoryList", List.class);
list.add(index, factory);
} | void function(final ServiceFactory<? extends Service> factory, final int index) { logger.debug(STR, factory); final List<ServiceFactory<? extends Service>> list = applicationContext.getBean(STR, List.class); list.add(index, factory); } | /**
* Add service factory.
*
* @param factory the factory
* @param index the index
*/ | Add service factory | addServiceFactory | {
"repo_name": "joansmith/cas",
"path": "cas-server-core-web/src/main/java/org/jasig/cas/web/AbstractServletContextInitializer.java",
"license": "apache-2.0",
"size": 12370
} | [
"java.util.List",
"org.jasig.cas.authentication.principal.Service",
"org.jasig.cas.authentication.principal.ServiceFactory"
] | import java.util.List; import org.jasig.cas.authentication.principal.Service; import org.jasig.cas.authentication.principal.ServiceFactory; | import java.util.*; import org.jasig.cas.authentication.principal.*; | [
"java.util",
"org.jasig.cas"
] | java.util; org.jasig.cas; | 1,942,651 |
private static void checkAudioFormat(final AudioFormat audioFormat,
final int bits) {
final int channels = audioFormat.getChannels();
if (channels != 2) {
throw new RuntimeException("Wrong channels: " + channels);
}
final int sizeInBits = audioFormat.getSampleSizeInBits();
if (sizeInBits != bits) {
throw new RuntimeException("Wrong sizeInBits: " + sizeInBits);
}
final int frameSize = audioFormat.getFrameSize();
if (frameSize != sizeInBits * channels / 8) {
throw new RuntimeException("Wrong frameSize: " + frameSize);
}
final AudioFormat.Encoding encoding = audioFormat.getEncoding();
if (!encoding.equals(AudioFormat.Encoding.PCM_FLOAT)) {
throw new RuntimeException("Wrong encoding: " + encoding);
}
final float frameRate = audioFormat.getFrameRate();
if (frameRate != 32000) {
throw new RuntimeException("Wrong frameRate: " + frameRate);
}
final float sampleRate = audioFormat.getSampleRate();
if (sampleRate != 32000) {
throw new RuntimeException("Wrong sampleRate: " + sampleRate);
}
} | static void function(final AudioFormat audioFormat, final int bits) { final int channels = audioFormat.getChannels(); if (channels != 2) { throw new RuntimeException(STR + channels); } final int sizeInBits = audioFormat.getSampleSizeInBits(); if (sizeInBits != bits) { throw new RuntimeException(STR + sizeInBits); } final int frameSize = audioFormat.getFrameSize(); if (frameSize != sizeInBits * channels / 8) { throw new RuntimeException(STR + frameSize); } final AudioFormat.Encoding encoding = audioFormat.getEncoding(); if (!encoding.equals(AudioFormat.Encoding.PCM_FLOAT)) { throw new RuntimeException(STR + encoding); } final float frameRate = audioFormat.getFrameRate(); if (frameRate != 32000) { throw new RuntimeException(STR + frameRate); } final float sampleRate = audioFormat.getSampleRate(); if (sampleRate != 32000) { throw new RuntimeException(STR + sampleRate); } } | /**
* Tests that audio data is the same format as a command lines above.
*/ | Tests that audio data is the same format as a command lines above | checkAudioFormat | {
"repo_name": "md-5/jdk10",
"path": "test/jdk/javax/sound/sampled/spi/AudioFileReader/RecognizeAuFloat.java",
"license": "gpl-2.0",
"size": 50422
} | [
"javax.sound.sampled.AudioFormat"
] | import javax.sound.sampled.AudioFormat; | import javax.sound.sampled.*; | [
"javax.sound"
] | javax.sound; | 1,520,009 |
public void zoomRangeAxes(double factor, PlotRenderingInfo state,
Point2D source, boolean useAnchor); | void function(double factor, PlotRenderingInfo state, Point2D source, boolean useAnchor); | /**
* Multiplies the range on the range axis/axes by the specified factor.
* The <code>source</code> point can be used in some cases to identify a
* subplot, or to determine the center of zooming (refer to the
* documentation of the implementing class for details).
*
* @param factor the zoom factor.
* @param state the plot state.
* @param source the source point (in Java2D coordinates).
* @param useAnchor use source point as zoom anchor?
*
* @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D)
*
* @since 1.0.7
*/ | Multiplies the range on the range axis/axes by the specified factor. The <code>source</code> point can be used in some cases to identify a subplot, or to determine the center of zooming (refer to the documentation of the implementing class for details) | zoomRangeAxes | {
"repo_name": "JSansalone/JFreeChart",
"path": "source/org/jfree/chart/plot/Zoomable.java",
"license": "lgpl-2.1",
"size": 6642
} | [
"java.awt.geom.Point2D"
] | import java.awt.geom.Point2D; | import java.awt.geom.*; | [
"java.awt"
] | java.awt; | 318,689 |
public static Integer cubeDim(Configuration configuration, Object __1) {
CubeDim f = new CubeDim();
f.set__1(__1);
f.execute(configuration);
return f.getReturnValue();
} | static Integer function(Configuration configuration, Object __1) { CubeDim f = new CubeDim(); f.set__1(__1); f.execute(configuration); return f.getReturnValue(); } | /**
* Call <code>public.cube_dim</code>
*/ | Call <code>public.cube_dim</code> | cubeDim | {
"repo_name": "Remper/sociallink",
"path": "alignments/src/main/java/eu/fbk/fm/alignments/index/db/Routines.java",
"license": "apache-2.0",
"size": 37686
} | [
"eu.fbk.fm.alignments.index.db.routines.CubeDim",
"org.jooq.Configuration"
] | import eu.fbk.fm.alignments.index.db.routines.CubeDim; import org.jooq.Configuration; | import eu.fbk.fm.alignments.index.db.routines.*; import org.jooq.*; | [
"eu.fbk.fm",
"org.jooq"
] | eu.fbk.fm; org.jooq; | 2,219,482 |
public void restartProxies() {
for (IgniteCacheProxyImpl<?, ?> proxy : jCacheProxies.values()) {
if (proxy == null)
continue;
GridCacheContext<?, ?> cacheCtx = sharedCtx.cacheContext(CU.cacheId(proxy.getName()));
if (cacheCtx == null)
continue;
if (proxy.isRestarting()) {
caches.get(proxy.getName()).active(true);
proxy.onRestarted(cacheCtx, cacheCtx.cache());
if (cacheCtx.dataStructuresCache())
ctx.dataStructures().restart(proxy.internalProxy());
}
}
} | void function() { for (IgniteCacheProxyImpl<?, ?> proxy : jCacheProxies.values()) { if (proxy == null) continue; GridCacheContext<?, ?> cacheCtx = sharedCtx.cacheContext(CU.cacheId(proxy.getName())); if (cacheCtx == null) continue; if (proxy.isRestarting()) { caches.get(proxy.getName()).active(true); proxy.onRestarted(cacheCtx, cacheCtx.cache()); if (cacheCtx.dataStructuresCache()) ctx.dataStructures().restart(proxy.internalProxy()); } } } | /**
* Restarts proxies of caches if they was marked as restarting.
* Requires external synchronization - shouldn't be called concurrently with another caches restart.
*/ | Restarts proxies of caches if they was marked as restarting. Requires external synchronization - shouldn't be called concurrently with another caches restart | restartProxies | {
"repo_name": "irudyak/ignite",
"path": "modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java",
"license": "apache-2.0",
"size": 174729
} | [
"org.apache.ignite.internal.util.typedef.internal.CU"
] | import org.apache.ignite.internal.util.typedef.internal.CU; | import org.apache.ignite.internal.util.typedef.internal.*; | [
"org.apache.ignite"
] | org.apache.ignite; | 2,865,514 |
public Map<TObject, Set<Long>> browse(String key); | Map<TObject, Set<Long>> function(String key); | /**
* Browse {@code key}.
* <p>
* This method returns a mapping from each of the values that is currently
* indexed to {@code key} to a Set the records that contain {@code key} as
* the associated value. If there are no such values, an empty Map is
* returned.
* </p>
*
* @param key
* @return a possibly empty Map of data
*/ | Browse key. This method returns a mapping from each of the values that is currently indexed to key to a Set the records that contain key as the associated value. If there are no such values, an empty Map is returned. | browse | {
"repo_name": "JerJohn15/concourse",
"path": "concourse-server/src/main/java/com/cinchapi/concourse/server/storage/Store.java",
"license": "apache-2.0",
"size": 10638
} | [
"com.cinchapi.concourse.thrift.TObject",
"java.util.Map",
"java.util.Set"
] | import com.cinchapi.concourse.thrift.TObject; import java.util.Map; import java.util.Set; | import com.cinchapi.concourse.thrift.*; import java.util.*; | [
"com.cinchapi.concourse",
"java.util"
] | com.cinchapi.concourse; java.util; | 488,699 |
public void purge() {
this.listOfSigns.clear();
}
/**
* Composes a path to this storage's file
*
* @return the path as {@code File} | void function() { this.listOfSigns.clear(); } /** * Composes a path to this storage's file * * @return the path as {@code File} | /**
* Removes all items from this storage. The internal {@link HashMap} will be
* empty after this call returns.
*/ | Removes all items from this storage. The internal <code>HashMap</code> will be empty after this call returns | purge | {
"repo_name": "Amunak/MineAuction",
"path": "src/net/amunak/bukkit/mineauction/sign/SignStorage.java",
"license": "gpl-3.0",
"size": 7228
} | [
"java.io.File"
] | import java.io.File; | import java.io.*; | [
"java.io"
] | java.io; | 183,782 |
@CheckResult
public PlaybackInfo copyWithPlayWhenReady(
boolean playWhenReady, @PlaybackSuppressionReason int playbackSuppressionReason) {
return new PlaybackInfo(
timeline,
periodId,
requestedContentPositionUs,
discontinuityStartPositionUs,
playbackState,
playbackError,
isLoading,
trackGroups,
trackSelectorResult,
staticMetadata,
loadingMediaPeriodId,
playWhenReady,
playbackSuppressionReason,
playbackParameters,
bufferedPositionUs,
totalBufferedDurationUs,
positionUs,
offloadSchedulingEnabled,
sleepingForOffload);
} | PlaybackInfo function( boolean playWhenReady, @PlaybackSuppressionReason int playbackSuppressionReason) { return new PlaybackInfo( timeline, periodId, requestedContentPositionUs, discontinuityStartPositionUs, playbackState, playbackError, isLoading, trackGroups, trackSelectorResult, staticMetadata, loadingMediaPeriodId, playWhenReady, playbackSuppressionReason, playbackParameters, bufferedPositionUs, totalBufferedDurationUs, positionUs, offloadSchedulingEnabled, sleepingForOffload); } | /**
* Copies playback info with new information about whether playback should proceed when ready.
*
* @param playWhenReady Whether playback should proceed when {@link #playbackState} == {@link
* Player#STATE_READY}.
* @param playbackSuppressionReason Reason why playback is suppressed even though {@link
* #playWhenReady} is {@code true}.
* @return Copied playback info with new information.
*/ | Copies playback info with new information about whether playback should proceed when ready | copyWithPlayWhenReady | {
"repo_name": "ened/ExoPlayer",
"path": "library/core/src/main/java/com/google/android/exoplayer2/PlaybackInfo.java",
"license": "apache-2.0",
"size": 18102
} | [
"com.google.android.exoplayer2.Player"
] | import com.google.android.exoplayer2.Player; | import com.google.android.exoplayer2.*; | [
"com.google.android"
] | com.google.android; | 2,008,526 |
public static WsDiscoveryS11SOAPMessage<ProbeType> createWsdSOAPMessageProbe() throws SOAPOverUDPException {
return new WsDiscoveryS11SOAPMessage<ProbeType>(WsDiscoveryActionTypes.PROBE,
wsDiscoveryObjectFactory.createProbe(wsDiscoveryObjectFactory.createProbeType()));
} | static WsDiscoveryS11SOAPMessage<ProbeType> function() throws SOAPOverUDPException { return new WsDiscoveryS11SOAPMessage<ProbeType>(WsDiscoveryActionTypes.PROBE, wsDiscoveryObjectFactory.createProbe(wsDiscoveryObjectFactory.createProbeType())); } | /**
* Create blank WS-Discovery Probe-message.
* @return Probe-message.
*/ | Create blank WS-Discovery Probe-message | createWsdSOAPMessageProbe | {
"repo_name": "thchu168/java-ws-discovery",
"path": "wsdiscovery-lib/src/main/java/com/ms/wsdiscovery/standard11/WsDiscoveryS11Utilities.java",
"license": "lgpl-3.0",
"size": 20884
} | [
"com.ms.wsdiscovery.datatypes.WsDiscoveryActionTypes",
"com.ms.wsdiscovery.jaxb.standard11.wsdiscovery.ProbeType",
"com.skjegstad.soapoverudp.exceptions.SOAPOverUDPException"
] | import com.ms.wsdiscovery.datatypes.WsDiscoveryActionTypes; import com.ms.wsdiscovery.jaxb.standard11.wsdiscovery.ProbeType; import com.skjegstad.soapoverudp.exceptions.SOAPOverUDPException; | import com.ms.wsdiscovery.datatypes.*; import com.ms.wsdiscovery.jaxb.standard11.wsdiscovery.*; import com.skjegstad.soapoverudp.exceptions.*; | [
"com.ms.wsdiscovery",
"com.skjegstad.soapoverudp"
] | com.ms.wsdiscovery; com.skjegstad.soapoverudp; | 2,393,845 |
List<FileType> getRegisteredFileTypes(); | List<FileType> getRegisteredFileTypes(); | /**
* Returns the {@link List} of all registered file types.
*
* @return {@link List} of all registered file types
*/ | Returns the <code>List</code> of all registered file types | getRegisteredFileTypes | {
"repo_name": "codenvy/che-core",
"path": "ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/filetypes/FileTypeRegistry.java",
"license": "epl-1.0",
"size": 2302
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 1,921,870 |
int deleteByExample(PassresetExample example); | int deleteByExample(PassresetExample example); | /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table public.passreset
*
* @mbggenerated Sat Apr 09 16:44:25 CST 2016
*/ | This method was generated by MyBatis Generator. This method corresponds to the database table public.passreset | deleteByExample | {
"repo_name": "zjlywjh001/PhrackCTF-Platform-Personal",
"path": "src/main/java/top/phrack/ctf/models/dao/PassresetMapper.java",
"license": "apache-2.0",
"size": 3098
} | [
"top.phrack.ctf.pojo.PassresetExample"
] | import top.phrack.ctf.pojo.PassresetExample; | import top.phrack.ctf.pojo.*; | [
"top.phrack.ctf"
] | top.phrack.ctf; | 288,649 |
public void testExhaustContentSource() throws Exception {
// 1. alg definition (required in every "logic" test)
String algLines[] = {
"# ----- properties ",
"content.source=org.apache.lucene.benchmark.byTask.feeds.SingleDocSource",
"content.source.log.step=1",
"doc.term.vector=false",
"content.source.forever=false",
"directory=RAMDirectory",
"doc.stored=false",
"doc.tokenized=false",
"# ----- alg ",
"CreateIndex",
"{ AddDoc } : * ",
"ForceMerge(1)",
"CloseIndex",
"OpenReader",
"{ CountingSearchTest } : 100",
"CloseReader",
"[ CountingSearchTest > : 30",
"[ CountingSearchTest > : 9",
};
// 2. we test this value later
CountingSearchTestTask.numSearches = 0;
// 3. execute the algorithm (required in every "logic" test)
Benchmark benchmark = execBenchmark(algLines);
// 4. test specific checks after the benchmark run completed.
assertEquals("TestSearchTask was supposed to be called!",139,CountingSearchTestTask.numSearches);
assertTrue("Index does not exist?...!", DirectoryReader.indexExists(benchmark.getRunData().getDirectory()));
// now we should be able to open the index for write.
IndexWriter iw = new IndexWriter(benchmark.getRunData().getDirectory(), new IndexWriterConfig(new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND));
iw.close();
IndexReader ir = DirectoryReader.open(benchmark.getRunData().getDirectory());
assertEquals("1 docs were added to the index, this is what we expect to find!",1,ir.numDocs());
ir.close();
} | void function() throws Exception { String algLines[] = { STR, STR, STR, STR, STR, STR, STR, STR, STR, STR, STR, STR, STR, STR, STR, STR, STR, STR, }; CountingSearchTestTask.numSearches = 0; Benchmark benchmark = execBenchmark(algLines); assertEquals(STR,139,CountingSearchTestTask.numSearches); assertTrue(STR, DirectoryReader.indexExists(benchmark.getRunData().getDirectory())); IndexWriter iw = new IndexWriter(benchmark.getRunData().getDirectory(), new IndexWriterConfig(new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND)); iw.close(); IndexReader ir = DirectoryReader.open(benchmark.getRunData().getDirectory()); assertEquals(STR,1,ir.numDocs()); ir.close(); } | /**
* Test Exhasting Doc Maker logic
*/ | Test Exhasting Doc Maker logic | testExhaustContentSource | {
"repo_name": "PATRIC3/p3_solr",
"path": "lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/TestPerfTasksLogic.java",
"license": "apache-2.0",
"size": 42375
} | [
"org.apache.lucene.analysis.MockAnalyzer",
"org.apache.lucene.benchmark.byTask.tasks.CountingSearchTestTask",
"org.apache.lucene.index.DirectoryReader",
"org.apache.lucene.index.IndexReader",
"org.apache.lucene.index.IndexWriter",
"org.apache.lucene.index.IndexWriterConfig"
] | import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.benchmark.byTask.tasks.CountingSearchTestTask; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; | import org.apache.lucene.analysis.*; import org.apache.lucene.benchmark.*; import org.apache.lucene.index.*; | [
"org.apache.lucene"
] | org.apache.lucene; | 488,599 |
@Override
public void deletedProject(final IDatabase database, final INaviProject project) {
// Remove the node that represents the deleted project.
for (int i = 0; i < getChildCount(); i++) {
final CProjectNode node = (CProjectNode) getChildAt(i);
if (node.getObject() == project) {
node.dispose();
remove(node);
break;
}
}
getTreeModel().nodeStructureChanged(CProjectContainerNode.this);
}
} | void function(final IDatabase database, final INaviProject project) { for (int i = 0; i < getChildCount(); i++) { final CProjectNode node = (CProjectNode) getChildAt(i); if (node.getObject() == project) { node.dispose(); remove(node); break; } } getTreeModel().nodeStructureChanged(CProjectContainerNode.this); } } | /**
* When a project was removed from the database, the corresponding node must be removed from the
* tree.
*/ | When a project was removed from the database, the corresponding node must be removed from the tree | deletedProject | {
"repo_name": "dgrif/binnavi",
"path": "src/main/java/com/google/security/zynamics/binnavi/Gui/MainWindow/ProjectTree/Nodes/ProjectContainer/CProjectContainerNode.java",
"license": "apache-2.0",
"size": 5535
} | [
"com.google.security.zynamics.binnavi.Database",
"com.google.security.zynamics.binnavi.Gui",
"com.google.security.zynamics.binnavi.disassembly.INaviProject"
] | import com.google.security.zynamics.binnavi.Database; import com.google.security.zynamics.binnavi.Gui; import com.google.security.zynamics.binnavi.disassembly.INaviProject; | import com.google.security.zynamics.binnavi.*; import com.google.security.zynamics.binnavi.disassembly.*; | [
"com.google.security"
] | com.google.security; | 2,065,865 |
public static int createPreSplitLoadTestTable(Configuration conf,
TableName tableName, byte[] columnFamily, Algorithm compression,
DataBlockEncoding dataBlockEncoding, int numRegionsPerServer, int regionReplication,
Durability durability)
throws IOException {
HTableDescriptor desc = new HTableDescriptor(tableName);
desc.setDurability(durability);
desc.setRegionReplication(regionReplication);
HColumnDescriptor hcd = new HColumnDescriptor(columnFamily);
hcd.setDataBlockEncoding(dataBlockEncoding);
hcd.setCompressionType(compression);
return createPreSplitLoadTestTable(conf, desc, hcd, numRegionsPerServer);
} | static int function(Configuration conf, TableName tableName, byte[] columnFamily, Algorithm compression, DataBlockEncoding dataBlockEncoding, int numRegionsPerServer, int regionReplication, Durability durability) throws IOException { HTableDescriptor desc = new HTableDescriptor(tableName); desc.setDurability(durability); desc.setRegionReplication(regionReplication); HColumnDescriptor hcd = new HColumnDescriptor(columnFamily); hcd.setDataBlockEncoding(dataBlockEncoding); hcd.setCompressionType(compression); return createPreSplitLoadTestTable(conf, desc, hcd, numRegionsPerServer); } | /**
* Creates a pre-split table for load testing. If the table already exists,
* logs a warning and continues.
* @return the number of regions the table was split into
*/ | Creates a pre-split table for load testing. If the table already exists, logs a warning and continues | createPreSplitLoadTestTable | {
"repo_name": "grokcoder/pbase",
"path": "hbase-server/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java",
"license": "apache-2.0",
"size": 132664
} | [
"java.io.IOException",
"org.apache.hadoop.conf.Configuration",
"org.apache.hadoop.hbase.client.Durability",
"org.apache.hadoop.hbase.io.compress.Compression",
"org.apache.hadoop.hbase.io.encoding.DataBlockEncoding"
] | import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.Durability; import org.apache.hadoop.hbase.io.compress.Compression; import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding; | import java.io.*; import org.apache.hadoop.conf.*; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.io.compress.*; import org.apache.hadoop.hbase.io.encoding.*; | [
"java.io",
"org.apache.hadoop"
] | java.io; org.apache.hadoop; | 559,724 |
if (!cachedResources.containsKey(name)) {
File file = super.loadResource(name);
if (file != null && file.exists()) {
cachedResources.put(name, YamlConfiguration.loadConfiguration(file));
}
}
return cachedResources.get(name);
} | if (!cachedResources.containsKey(name)) { File file = super.loadResource(name); if (file != null && file.exists()) { cachedResources.put(name, YamlConfiguration.loadConfiguration(file)); } } return cachedResources.get(name); } | /**
* Retrieves a resource from its name,
* unlike {{@link #loadResource(String)}} configurations
* are cached/stored once loaded.
*
* @param name the name of the resource.
* @return the loaded resource, cached or not. Null if
* it does not exist.
*/ | Retrieves a resource from its name, unlike {<code>#loadResource(String)</code>} configurations are cached/stored once loaded | getResource | {
"repo_name": "ImABradley/Peach",
"path": "src/main/java/imabradley/common/examples/ExampleResourceHandler.java",
"license": "apache-2.0",
"size": 2196
} | [
"java.io.File",
"org.bukkit.configuration.file.YamlConfiguration"
] | import java.io.File; import org.bukkit.configuration.file.YamlConfiguration; | import java.io.*; import org.bukkit.configuration.file.*; | [
"java.io",
"org.bukkit.configuration"
] | java.io; org.bukkit.configuration; | 1,282,791 |
@SimpleProperty(
category = PropertyCategory.BEHAVIOR)
public boolean TimerAlwaysFires() {
return timerAlwaysFires;
} | @SimpleProperty( category = PropertyCategory.BEHAVIOR) boolean function() { return timerAlwaysFires; } | /**
* TimerAlwaysFires property getter method.
*
* return {@code true} if the timer event will fire even if the application
* is not on the screen
*/ | TimerAlwaysFires property getter method. return true if the timer event will fire even if the application is not on the screen | TimerAlwaysFires | {
"repo_name": "wanddy/ai4cn",
"path": "appinventor/components/src/com/google/appinventor/components/runtime/Clock.java",
"license": "mit",
"size": 13519
} | [
"com.google.appinventor.components.annotations.PropertyCategory",
"com.google.appinventor.components.annotations.SimpleProperty"
] | import com.google.appinventor.components.annotations.PropertyCategory; import com.google.appinventor.components.annotations.SimpleProperty; | import com.google.appinventor.components.annotations.*; | [
"com.google.appinventor"
] | com.google.appinventor; | 2,652,339 |
public Campeonato_model carregarCampeonatoInteiro( Campeonato_model campeonatoModel ){
Connection conn = null;
conn = BDConexao_dao.conectar();
//Filtro da minha query
String filtro = "";
if( campeonatoModel.getIdcampeonato() != 0 ){
String valor = " ce.idcampeonato=";
valor += Integer.toString(campeonatoModel.getIdcampeonato());
filtro = BDConexao_dao.adicionaFiltro(filtro, valor, "");
}
//preparando a query
Statement query = null;
String sql = "SELECT " +
"* " +
"FROM " +
"`bodyboardsys`.`campeonato` c" +
"INNER JOIN " +
"`bodyboardsys`.`campeonatoetapa` ce ON ce.idcampeonato = c.idcampeonato " +
"INNER JOIN " +
"`bodyboardsys`.`bateria` b ON b.idcampeonatoetapa = ce.idcampeonatoetapa " +
"" + filtro;
ResultSet res = null;
try{
query = (Statement) conn.createStatement();
res = query.executeQuery(sql);
} catch(SQLException e){
System.out.println("Erro ao conectar com o banco: " + e.getMessage());
System.err.println("SQLException: " + e.getMessage());
System.err.println("SQLState: " + e.getSQLState());
System.err.println("VendorError: " + e.getErrorCode());
return null;
}
try{
campeonatoModel = Campeonato_control.carregarCampeonatoInteiroResultSet(res);
conn.close();
return campeonatoModel;
} catch (Exception e) {
return null;
}
}
| Campeonato_model function( Campeonato_model campeonatoModel ){ Connection conn = null; conn = BDConexao_dao.conectar(); String filtro = STR ce.idcampeonato=STRSTRSELECT STR* STRFROM STR`bodyboardsys`.`campeonato` cSTRINNER JOIN STR`bodyboardsys`.`campeonatoetapa` ce ON ce.idcampeonato = c.idcampeonato STRINNER JOIN STR`bodyboardsys`.`bateria` b ON b.idcampeonatoetapa = ce.idcampeonatoetapa STRSTRErro ao conectar com o banco: STRSQLException: STRSQLState: STRVendorError: " + e.getErrorCode()); return null; } try{ campeonatoModel = Campeonato_control.carregarCampeonatoInteiroResultSet(res); conn.close(); return campeonatoModel; } catch (Exception e) { return null; } } | /**
* Funcao que carrega um campeonato inteiro com todas as etapas e baterias
* @param Campeonato_model
* return Campeonato_model
* */ | Funcao que carrega um campeonato inteiro com todas as etapas e baterias | carregarCampeonatoInteiro | {
"repo_name": "rtancman/bbsys",
"path": "src/br/com/bbsys/dao/campeonato/Campeonato_dao.java",
"license": "apache-2.0",
"size": 11159
} | [
"java.sql.Connection"
] | import java.sql.Connection; | import java.sql.*; | [
"java.sql"
] | java.sql; | 1,913,222 |
public Set<Object> getAdded() {
return setDifference(newSelection, oldSelection);
} | Set<Object> function() { return setDifference(newSelection, oldSelection); } | /**
* A {@link Collection} of all the itemIds that became selected.
* <p>
* <em>Note:</em> this excludes all itemIds that might have been previously
* selected.
*
* @return a Collection of the itemIds that became selected
*/ | A <code>Collection</code> of all the itemIds that became selected. Note: this excludes all itemIds that might have been previously selected | getAdded | {
"repo_name": "peterl1084/framework",
"path": "compatibility-server/src/main/java/com/vaadin/v7/event/SelectionEvent.java",
"license": "apache-2.0",
"size": 4034
} | [
"java.util.Set"
] | import java.util.Set; | import java.util.*; | [
"java.util"
] | java.util; | 844,398 |
private void unregisterAllAccounts(boolean cancelNotification) throws SameThreadException {
releaseResources();
Log.d(THIS_FILE, "Remove all accounts");
Cursor c = getContentResolver().query(SipProfile.ACCOUNT_URI, DBProvider.ACCOUNT_FULL_PROJECTION, null, null, null);
if (c != null) {
try {
c.moveToFirst();
do {
SipProfile account = new SipProfile(c);
setAccountRegistration(account, 0, false);
} while (c.moveToNext() );
} catch (Exception e) {
Log.e(THIS_FILE, "Error on looping over sip profiles", e);
} finally {
c.close();
}
}
if (notificationManager != null && cancelNotification) {
notificationManager.cancelRegisters();
}
} | void function(boolean cancelNotification) throws SameThreadException { releaseResources(); Log.d(THIS_FILE, STR); Cursor c = getContentResolver().query(SipProfile.ACCOUNT_URI, DBProvider.ACCOUNT_FULL_PROJECTION, null, null, null); if (c != null) { try { c.moveToFirst(); do { SipProfile account = new SipProfile(c); setAccountRegistration(account, 0, false); } while (c.moveToNext() ); } catch (Exception e) { Log.e(THIS_FILE, STR, e); } finally { c.close(); } } if (notificationManager != null && cancelNotification) { notificationManager.cancelRegisters(); } } | /**
* Remove accounts from database
*/ | Remove accounts from database | unregisterAllAccounts | {
"repo_name": "hongbinz/csipsimple",
"path": "src/com/csipsimple/service/SipService.java",
"license": "lgpl-3.0",
"size": 59911
} | [
"android.database.Cursor",
"com.csipsimple.api.SipProfile",
"com.csipsimple.db.DBProvider",
"com.csipsimple.utils.Log"
] | import android.database.Cursor; import com.csipsimple.api.SipProfile; import com.csipsimple.db.DBProvider; import com.csipsimple.utils.Log; | import android.database.*; import com.csipsimple.api.*; import com.csipsimple.db.*; import com.csipsimple.utils.*; | [
"android.database",
"com.csipsimple.api",
"com.csipsimple.db",
"com.csipsimple.utils"
] | android.database; com.csipsimple.api; com.csipsimple.db; com.csipsimple.utils; | 973,126 |
public void addUnmatchedIds(Collection<String> ids) {
unmatchedIds.addAll(ids);
} | void function(Collection<String> ids) { unmatchedIds.addAll(ids); } | /**
* Add some new unmatched ids to the set of unmatched identifiers.
*
* This is meant for use by the service modules.
* @param ids the ids to add.
*/ | Add some new unmatched ids to the set of unmatched identifiers. This is meant for use by the service modules | addUnmatchedIds | {
"repo_name": "elsiklab/intermine",
"path": "intermine/webservice/client/main/src/org/intermine/webservice/client/lists/ItemList.java",
"license": "lgpl-2.1",
"size": 18291
} | [
"java.util.Collection"
] | import java.util.Collection; | import java.util.*; | [
"java.util"
] | java.util; | 1,624,129 |
private JMenu createDisplayOptions()
{
JMenu displayOptions;
JCheckBoxMenuItem setDisplayScale;
displayOptions = new JMenu(DISPLAY_UNITS);
ButtonGroup displayUnits = new ButtonGroup();
int i;
for (i = 0 ; i < DisplayAction.MAX ; i++)
{
setDisplayScale = new JCheckBoxMenuItem(new DisplayAction
(lensComponent, i));
displayUnits.add(setDisplayScale);
displayOptions.add(setDisplayScale);
setDisplayScale.setSelected(i == 1);
}
return displayOptions;
}
| JMenu function() { JMenu displayOptions; JCheckBoxMenuItem setDisplayScale; displayOptions = new JMenu(DISPLAY_UNITS); ButtonGroup displayUnits = new ButtonGroup(); int i; for (i = 0 ; i < DisplayAction.MAX ; i++) { setDisplayScale = new JCheckBoxMenuItem(new DisplayAction (lensComponent, i)); displayUnits.add(setDisplayScale); displayOptions.add(setDisplayScale); setDisplayScale.setSelected(i == 1); } return displayOptions; } | /**
* Create the menu which will allow the user to change the units the lens
* will be measured and positioned in. (Micron or pixels);
*
* @return The lens select units menu.
*/ | Create the menu which will allow the user to change the units the lens will be measured and positioned in. (Micron or pixels) | createDisplayOptions | {
"repo_name": "tp81/openmicroscopy",
"path": "components/insight/SRC/org/openmicroscopy/shoola/util/ui/lens/LensMenu.java",
"license": "gpl-2.0",
"size": 8447
} | [
"javax.swing.ButtonGroup",
"javax.swing.JCheckBoxMenuItem",
"javax.swing.JMenu"
] | import javax.swing.ButtonGroup; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenu; | import javax.swing.*; | [
"javax.swing"
] | javax.swing; | 2,892,900 |
public InetSocketAddress getConnectorAddress(int index) {
Preconditions.checkArgument(index >= 0);
if (index > webServer.getConnectors().length)
return null;
Connector c = webServer.getConnectors()[index];
if (c.getLocalPort() == -1) {
// The connector is not bounded
return null;
}
return new InetSocketAddress(c.getHost(), c.getLocalPort());
} | InetSocketAddress function(int index) { Preconditions.checkArgument(index >= 0); if (index > webServer.getConnectors().length) return null; Connector c = webServer.getConnectors()[index]; if (c.getLocalPort() == -1) { return null; } return new InetSocketAddress(c.getHost(), c.getLocalPort()); } | /**
* Get the address that corresponds to a particular connector.
*
* @return the corresponding address for the connector, or null if there's no
* such connector or the connector is not bounded.
*/ | Get the address that corresponds to a particular connector | getConnectorAddress | {
"repo_name": "NJUJYB/disYarn",
"path": "hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/http/HttpServer2.java",
"license": "apache-2.0",
"size": 45208
} | [
"com.google.common.base.Preconditions",
"java.net.InetSocketAddress",
"org.mortbay.jetty.Connector"
] | import com.google.common.base.Preconditions; import java.net.InetSocketAddress; import org.mortbay.jetty.Connector; | import com.google.common.base.*; import java.net.*; import org.mortbay.jetty.*; | [
"com.google.common",
"java.net",
"org.mortbay.jetty"
] | com.google.common; java.net; org.mortbay.jetty; | 1,947,760 |
public void unregister(Object subscriber) {
ArrayList<EventHandlerInfo> kill = new ArrayList<EventHandlerInfo>();
for (EventHandlerInfo handler : handlers) {
Object existingSubscriber = handler.getSubscriber();
if (existingSubscriber == null // Remove dead subscribers while we're here....
|| existingSubscriber == subscriber) {
kill.add(handler);
}
}
handlers.removeAll(kill);
} | void function(Object subscriber) { ArrayList<EventHandlerInfo> kill = new ArrayList<EventHandlerInfo>(); for (EventHandlerInfo handler : handlers) { Object existingSubscriber = handler.getSubscriber(); if (existingSubscriber == null existingSubscriber == subscriber) { kill.add(handler); } } handlers.removeAll(kill); } | /**
* Unregisters the given object from the event bus.
*/ | Unregisters the given object from the event bus | unregister | {
"repo_name": "codeka/steptastic",
"path": "mobile/src/main/java/au/com/codeka/steptastic/eventbus/EventBus.java",
"license": "mit",
"size": 3829
} | [
"java.util.ArrayList"
] | import java.util.ArrayList; | import java.util.*; | [
"java.util"
] | java.util; | 2,244,734 |
private boolean isLocked(HttpServletRequest req) {
String path = getRelativePath(req);
String ifHeader = req.getHeader("If");
if (ifHeader == null)
ifHeader = "";
String lockTokenHeader = req.getHeader("Lock-Token");
if (lockTokenHeader == null)
lockTokenHeader = "";
return isLocked(path, ifHeader + lockTokenHeader);
} | boolean function(HttpServletRequest req) { String path = getRelativePath(req); String ifHeader = req.getHeader("If"); if (ifHeader == null) ifHeader = STRLock-TokenSTR"; return isLocked(path, ifHeader + lockTokenHeader); } | /**
* Check to see if a resource is currently write locked. The method
* will look at the "If" header to make sure the client
* has give the appropriate lock tokens.
*
* @param req Servlet request
* @return boolean true if the resource is locked (and no appropriate
* lock token has been found for at least one of the non-shared locks which
* are present on the resource).
*/ | Check to see if a resource is currently write locked. The method will look at the "If" header to make sure the client has give the appropriate lock tokens | isLocked | {
"repo_name": "Netprophets/JBOSSWEB_7_0_13_FINAL",
"path": "java/org/apache/catalina/servlets/WebdavServlet.java",
"license": "lgpl-3.0",
"size": 110965
} | [
"javax.servlet.http.HttpServletRequest"
] | import javax.servlet.http.HttpServletRequest; | import javax.servlet.http.*; | [
"javax.servlet"
] | javax.servlet; | 742,700 |
@FactoryParameter(obligation = OPTIONAL)
@Deprecated
List<ReplacementSet> getFindReplace(); | @FactoryParameter(obligation = OPTIONAL) List<ReplacementSet> getFindReplace(); | /**
* Allow to use text replacement in project files after clone
*/ | Allow to use text replacement in project files after clone | getFindReplace | {
"repo_name": "codenvy/che-core",
"path": "platform-api/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/dto/Actions.java",
"license": "epl-1.0",
"size": 2160
} | [
"java.util.List",
"org.eclipse.che.api.core.factory.FactoryParameter",
"org.eclipse.che.api.vfs.shared.dto.ReplacementSet"
] | import java.util.List; import org.eclipse.che.api.core.factory.FactoryParameter; import org.eclipse.che.api.vfs.shared.dto.ReplacementSet; | import java.util.*; import org.eclipse.che.api.core.factory.*; import org.eclipse.che.api.vfs.shared.dto.*; | [
"java.util",
"org.eclipse.che"
] | java.util; org.eclipse.che; | 2,140,503 |
@Override
public void ZWaveIncomingEvent(ZWaveEvent event) {
// if we are not yet initialized, don't waste time and return
if (!this.isProperlyConfigured())
return;
if (!isZwaveNetworkReady) {
if (event instanceof ZWaveInitializationCompletedEvent) {
logger.debug("ZWaveIncomingEvent Called, Network Event, Init Done. Setting ZWave Network Ready.");
isZwaveNetworkReady = true;
// Initialise the polling table
rebuildPollingTable();
return;
}
}
logger.debug("ZwaveIncomingEvent");
// ignore transaction completed events.
if (event instanceof ZWaveTransactionCompletedEvent)
return;
// handle command class value events.
if (event instanceof ZWaveCommandClassValueEvent) {
handleZWaveCommandClassValueEvent((ZWaveCommandClassValueEvent)event);
return;
}
} | void function(ZWaveEvent event) { if (!this.isProperlyConfigured()) return; if (!isZwaveNetworkReady) { if (event instanceof ZWaveInitializationCompletedEvent) { logger.debug(STR); isZwaveNetworkReady = true; rebuildPollingTable(); return; } } logger.debug(STR); if (event instanceof ZWaveTransactionCompletedEvent) return; if (event instanceof ZWaveCommandClassValueEvent) { handleZWaveCommandClassValueEvent((ZWaveCommandClassValueEvent)event); return; } } | /**
* Event handler method for incoming Z-Wave events.
* @param event the incoming Z-Wave event.
*/ | Event handler method for incoming Z-Wave events | ZWaveIncomingEvent | {
"repo_name": "gregfinley/openhab",
"path": "bundles/binding/org.openhab.binding.zwave/src/main/java/org/openhab/binding/zwave/internal/ZWaveActiveBinding.java",
"license": "epl-1.0",
"size": 14045
} | [
"org.openhab.binding.zwave.internal.protocol.event.ZWaveCommandClassValueEvent",
"org.openhab.binding.zwave.internal.protocol.event.ZWaveEvent",
"org.openhab.binding.zwave.internal.protocol.event.ZWaveInitializationCompletedEvent",
"org.openhab.binding.zwave.internal.protocol.event.ZWaveTransactionCompletedEvent"
] | import org.openhab.binding.zwave.internal.protocol.event.ZWaveCommandClassValueEvent; import org.openhab.binding.zwave.internal.protocol.event.ZWaveEvent; import org.openhab.binding.zwave.internal.protocol.event.ZWaveInitializationCompletedEvent; import org.openhab.binding.zwave.internal.protocol.event.ZWaveTransactionCompletedEvent; | import org.openhab.binding.zwave.internal.protocol.event.*; | [
"org.openhab.binding"
] | org.openhab.binding; | 2,036,491 |
public N getPartitionSuperNode(N node) {
Preconditions.checkNotNull(colorToNodeMap,
"No coloring founded. color() should be called first.");
Color color = graph.getNode(node).getAnnotation();
N headNode = colorToNodeMap[color.value];
if (headNode == null) {
colorToNodeMap[color.value] = node;
return node;
} else {
return headNode;
}
} | N function(N node) { Preconditions.checkNotNull(colorToNodeMap, STR); Color color = graph.getNode(node).getAnnotation(); N headNode = colorToNodeMap[color.value]; if (headNode == null) { colorToNodeMap[color.value] = node; return node; } else { return headNode; } } | /**
* Using the coloring as partitions, finds the node that represents that
* partition as the super node. The first to retrieve its partition will
* become the super node.
*/ | Using the coloring as partitions, finds the node that represents that partition as the super node. The first to retrieve its partition will become the super node | getPartitionSuperNode | {
"repo_name": "antz29/closure-compiler",
"path": "src/com/google/javascript/jscomp/graph/GraphColoring.java",
"license": "apache-2.0",
"size": 5512
} | [
"com.google.common.base.Preconditions"
] | import com.google.common.base.Preconditions; | import com.google.common.base.*; | [
"com.google.common"
] | com.google.common; | 2,163,873 |
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testEventListeners");
assertNotNull(testListenerBean);
org.flowable.task.api.Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
taskService.complete(task.getId());
// Check if the listener (defined as bean) received events (only creation, not other events)
assertFalse(testListenerBean.getEventsReceived().isEmpty());
for (FlowableEvent event : testListenerBean.getEventsReceived()) {
assertEquals(FlowableEngineEventType.ENTITY_CREATED, event.getType());
}
// Second event received should be creation of Process instance (first is process definition create event)
assertTrue(testListenerBean.getEventsReceived().get(1) instanceof FlowableEntityEvent);
FlowableEntityEvent event = (FlowableEntityEvent) testListenerBean.getEventsReceived().get(1);
assertTrue(event.getEntity() instanceof ProcessInstance);
assertEquals(processInstance.getId(), ((ProcessInstance) event.getEntity()).getId());
// Check if listener, defined by classname, received all events
List<FlowableEvent> events = StaticTestFlowableEventListener.getEventsReceived();
assertFalse(events.isEmpty());
boolean insertFound = false;
boolean deleteFound = false;
for (FlowableEvent e : events) {
if (FlowableEngineEventType.ENTITY_CREATED == e.getType()) {
insertFound = true;
} else if (FlowableEngineEventType.ENTITY_DELETED == e.getType()) {
deleteFound = true;
}
}
assertTrue(insertFound);
assertTrue(deleteFound);
} | ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(STR); assertNotNull(testListenerBean); org.flowable.task.api.Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); taskService.complete(task.getId()); assertFalse(testListenerBean.getEventsReceived().isEmpty()); for (FlowableEvent event : testListenerBean.getEventsReceived()) { assertEquals(FlowableEngineEventType.ENTITY_CREATED, event.getType()); } assertTrue(testListenerBean.getEventsReceived().get(1) instanceof FlowableEntityEvent); FlowableEntityEvent event = (FlowableEntityEvent) testListenerBean.getEventsReceived().get(1); assertTrue(event.getEntity() instanceof ProcessInstance); assertEquals(processInstance.getId(), ((ProcessInstance) event.getEntity()).getId()); List<FlowableEvent> events = StaticTestFlowableEventListener.getEventsReceived(); assertFalse(events.isEmpty()); boolean insertFound = false; boolean deleteFound = false; for (FlowableEvent e : events) { if (FlowableEngineEventType.ENTITY_CREATED == e.getType()) { insertFound = true; } else if (FlowableEngineEventType.ENTITY_DELETED == e.getType()) { deleteFound = true; } } assertTrue(insertFound); assertTrue(deleteFound); } | /**
* Test to verify listeners defined in the BPMN xml are added to the process definition and are active.
*/ | Test to verify listeners defined in the BPMN xml are added to the process definition and are active | testProcessDefinitionListenerDefinition | {
"repo_name": "lsmall/flowable-engine",
"path": "modules/flowable-engine/src/test/java/org/flowable/standalone/event/ProcessDefinitionScopedEventListenerDefinitionTest.java",
"license": "apache-2.0",
"size": 7507
} | [
"java.util.List",
"org.flowable.common.engine.api.delegate.event.FlowableEngineEventType",
"org.flowable.common.engine.api.delegate.event.FlowableEntityEvent",
"org.flowable.common.engine.api.delegate.event.FlowableEvent",
"org.flowable.engine.runtime.ProcessInstance",
"org.flowable.engine.test.api.event.StaticTestFlowableEventListener"
] | import java.util.List; import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType; import org.flowable.common.engine.api.delegate.event.FlowableEntityEvent; import org.flowable.common.engine.api.delegate.event.FlowableEvent; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.engine.test.api.event.StaticTestFlowableEventListener; | import java.util.*; import org.flowable.common.engine.api.delegate.event.*; import org.flowable.engine.runtime.*; import org.flowable.engine.test.api.event.*; | [
"java.util",
"org.flowable.common",
"org.flowable.engine"
] | java.util; org.flowable.common; org.flowable.engine; | 2,216,314 |
private int diff_cleanupSemanticScore(String one, String two) {
if (one.length() == 0 || two.length() == 0) {
// Edges are the best.
return 6;
}
// Each port of this function behaves slightly differently due to
// subtle differences in each language's definition of things like
// 'whitespace'. Since this function's purpose is largely cosmetic,
// the choice has been made to use each language's native features
// rather than force total conformity.
char char1 = one.charAt(one.length() - 1);
char char2 = two.charAt(0);
boolean nonAlphaNumeric1 = !Character.isLetterOrDigit(char1);
boolean nonAlphaNumeric2 = !Character.isLetterOrDigit(char2);
boolean whitespace1 = nonAlphaNumeric1 && Character.isWhitespace(char1);
boolean whitespace2 = nonAlphaNumeric2 && Character.isWhitespace(char2);
boolean lineBreak1 = whitespace1
&& Character.getType(char1) == Character.CONTROL;
boolean lineBreak2 = whitespace2
&& Character.getType(char2) == Character.CONTROL;
boolean blankLine1 = lineBreak1 && BLANKLINEEND.matcher(one).find();
boolean blankLine2 = lineBreak2 && BLANKLINESTART.matcher(two).find();
if (blankLine1 || blankLine2) {
// Five points for blank lines.
return 5;
} else if (lineBreak1 || lineBreak2) {
// Four points for line breaks.
return 4;
} else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) {
// Three points for end of sentences.
return 3;
} else if (whitespace1 || whitespace2) {
// Two points for whitespace.
return 2;
} else if (nonAlphaNumeric1 || nonAlphaNumeric2) {
// One point for non-alphanumeric.
return 1;
}
return 0;
}
// Define some regex patterns for matching boundaries.
private Pattern BLANKLINEEND
= Pattern.compile("\\n\\r?\\n\\Z", Pattern.DOTALL);
private Pattern BLANKLINESTART
= Pattern.compile("\\A\\r?\\n\\r?\\n", Pattern.DOTALL); | int function(String one, String two) { if (one.length() == 0 two.length() == 0) { return 6; } char char1 = one.charAt(one.length() - 1); char char2 = two.charAt(0); boolean nonAlphaNumeric1 = !Character.isLetterOrDigit(char1); boolean nonAlphaNumeric2 = !Character.isLetterOrDigit(char2); boolean whitespace1 = nonAlphaNumeric1 && Character.isWhitespace(char1); boolean whitespace2 = nonAlphaNumeric2 && Character.isWhitespace(char2); boolean lineBreak1 = whitespace1 && Character.getType(char1) == Character.CONTROL; boolean lineBreak2 = whitespace2 && Character.getType(char2) == Character.CONTROL; boolean blankLine1 = lineBreak1 && BLANKLINEEND.matcher(one).find(); boolean blankLine2 = lineBreak2 && BLANKLINESTART.matcher(two).find(); if (blankLine1 blankLine2) { return 5; } else if (lineBreak1 lineBreak2) { return 4; } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { return 3; } else if (whitespace1 whitespace2) { return 2; } else if (nonAlphaNumeric1 nonAlphaNumeric2) { return 1; } return 0; } private Pattern BLANKLINEEND = Pattern.compile(STR, Pattern.DOTALL); private Pattern BLANKLINESTART = Pattern.compile(STR, Pattern.DOTALL); | /**
* Given two strings, compute a score representing whether the internal
* boundary falls on logical boundaries.
* Scores range from 6 (best) to 0 (worst).
*
* @param one First string.
* @param two Second string.
* @return The score.
*/ | Given two strings, compute a score representing whether the internal boundary falls on logical boundaries. Scores range from 6 (best) to 0 (worst) | diff_cleanupSemanticScore | {
"repo_name": "Cognifide/AET",
"path": "core/jobs/src/main/java/com/cognifide/aet/job/common/comparators/source/diff/DiffMatchPatch.java",
"license": "apache-2.0",
"size": 91233
} | [
"java.util.regex.Pattern"
] | import java.util.regex.Pattern; | import java.util.regex.*; | [
"java.util"
] | java.util; | 1,144,184 |
public final int getAuthenticationLength() {
return DataPacker.getIntelShort(getBuffer(), m_offset + AUTHLEN);
} | final int function() { return DataPacker.getIntelShort(getBuffer(), m_offset + AUTHLEN); } | /**
* Return the authentication length
*
* @return int
*/ | Return the authentication length | getAuthenticationLength | {
"repo_name": "loftuxab/community-edition-old",
"path": "projects/alfresco-jlan/source/java/org/alfresco/jlan/smb/dcerpc/client/DCEPacket.java",
"license": "lgpl-3.0",
"size": 16648
} | [
"org.alfresco.jlan.util.DataPacker"
] | import org.alfresco.jlan.util.DataPacker; | import org.alfresco.jlan.util.*; | [
"org.alfresco.jlan"
] | org.alfresco.jlan; | 1,079,799 |
private static String makeThreadName(String suffix) {
String name = Thread.currentThread().getName().
replaceAll("-EventThread", "");
return name + suffix;
}
class EventThread extends ZooKeeperThread {
private final LinkedBlockingQueue<Object> waitingEvents =
new LinkedBlockingQueue<Object>();
private volatile KeeperState sessionState = KeeperState.Disconnected;
private volatile boolean wasKilled = false;
private volatile boolean isRunning = false;
EventThread() {
super(makeThreadName("-EventThread"));
setDaemon(true);
} | static String function(String suffix) { String name = Thread.currentThread().getName(). replaceAll(STR, ""); return name + suffix; } class EventThread extends ZooKeeperThread { private final LinkedBlockingQueue<Object> waitingEvents = new LinkedBlockingQueue<Object>(); private volatile KeeperState sessionState = KeeperState.Disconnected; private volatile boolean wasKilled = false; private volatile boolean isRunning = false; EventThread() { super(makeThreadName(STR)); setDaemon(true); } | /**
* Guard against creating "-EventThread-EventThread-EventThread-..." thread
* names when ZooKeeper object is being created from within a watcher.
* See ZOOKEEPER-795 for details.
*/ | Guard against creating "-EventThread-EventThread-EventThread-..." thread names when ZooKeeper object is being created from within a watcher. See ZOOKEEPER-795 for details | makeThreadName | {
"repo_name": "shayhatsor/zookeeper",
"path": "src/java/main/org/apache/zookeeper/ClientCnxn.java",
"license": "apache-2.0",
"size": 61199
} | [
"java.util.concurrent.LinkedBlockingQueue",
"org.apache.zookeeper.Watcher",
"org.apache.zookeeper.server.ZooKeeperThread"
] | import java.util.concurrent.LinkedBlockingQueue; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.server.ZooKeeperThread; | import java.util.concurrent.*; import org.apache.zookeeper.*; import org.apache.zookeeper.server.*; | [
"java.util",
"org.apache.zookeeper"
] | java.util; org.apache.zookeeper; | 1,291,436 |
private static <T> T[] findServices( Class<T> clazz, ClassLoader classLoader ) {
// if true, print debug output
final boolean debug = com.sun.tools.internal.xjc.util.Util.getSystemProperty(Options.class,"findServices")!=null;
// if we are running on Mustang or Dolphin, use ServiceLoader
// so that we can take advantage of JSR-277 module system.
try {
Class<?> serviceLoader = Class.forName("java.util.ServiceLoader");
if(debug)
System.out.println("Using java.util.ServiceLoader");
Iterable<T> itr = (Iterable<T>)serviceLoader.getMethod("load",Class.class,ClassLoader.class).invoke(null,clazz,classLoader);
List<T> r = new ArrayList<T>();
for (T t : itr)
r.add(t);
return r.toArray((T[])Array.newInstance(clazz,r.size()));
} catch (ClassNotFoundException e) {
// fall through
} catch (IllegalAccessException e) {
Error x = new IllegalAccessError();
x.initCause(e);
throw x;
} catch (InvocationTargetException e) {
Throwable x = e.getTargetException();
if (x instanceof RuntimeException)
throw (RuntimeException) x;
if (x instanceof Error)
throw (Error) x;
throw new Error(x);
} catch (NoSuchMethodException e) {
Error x = new NoSuchMethodError();
x.initCause(e);
throw x;
}
String serviceId = "META-INF/services/" + clazz.getName();
// used to avoid creating the same instance twice
Set<String> classNames = new HashSet<String>();
if(debug) {
System.out.println("Looking for "+serviceId+" for add-ons");
}
// try to find services in CLASSPATH
try {
Enumeration<URL> e = classLoader.getResources(serviceId);
if(e==null) return (T[])Array.newInstance(clazz,0);
ArrayList<T> a = new ArrayList<T>();
while(e.hasMoreElements()) {
URL url = e.nextElement();
BufferedReader reader=null;
if(debug) {
System.out.println("Checking "+url+" for an add-on");
}
try {
reader = new BufferedReader(new InputStreamReader(url.openStream()));
String impl;
while((impl = reader.readLine())!=null ) {
// try to instanciate the object
impl = impl.trim();
if(classNames.add(impl)) {
Class implClass = classLoader.loadClass(impl);
if(!clazz.isAssignableFrom(implClass)) {
pluginLoadFailure = impl+" is not a subclass of "+clazz+". Skipping";
if(debug)
System.out.println(pluginLoadFailure);
continue;
}
if(debug) {
System.out.println("Attempting to instanciate "+impl);
}
a.add(clazz.cast(implClass.newInstance()));
}
}
reader.close();
} catch( Exception ex ) {
// let it go.
StringWriter w = new StringWriter();
ex.printStackTrace(new PrintWriter(w));
pluginLoadFailure = w.toString();
if(debug) {
System.out.println(pluginLoadFailure);
}
if( reader!=null ) {
try {
reader.close();
} catch( IOException ex2 ) {
// ignore
}
}
}
}
return a.toArray((T[])Array.newInstance(clazz,a.size()));
} catch( Throwable e ) {
// ignore any error
StringWriter w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
pluginLoadFailure = w.toString();
if(debug) {
System.out.println(pluginLoadFailure);
}
return (T[])Array.newInstance(clazz,0);
}
} | static <T> T[] function( Class<T> clazz, ClassLoader classLoader ) { final boolean debug = com.sun.tools.internal.xjc.util.Util.getSystemProperty(Options.class,STR)!=null; try { Class<?> serviceLoader = Class.forName(STR); if(debug) System.out.println(STR); Iterable<T> itr = (Iterable<T>)serviceLoader.getMethod("load",Class.class,ClassLoader.class).invoke(null,clazz,classLoader); List<T> r = new ArrayList<T>(); for (T t : itr) r.add(t); return r.toArray((T[])Array.newInstance(clazz,r.size())); } catch (ClassNotFoundException e) { } catch (IllegalAccessException e) { Error x = new IllegalAccessError(); x.initCause(e); throw x; } catch (InvocationTargetException e) { Throwable x = e.getTargetException(); if (x instanceof RuntimeException) throw (RuntimeException) x; if (x instanceof Error) throw (Error) x; throw new Error(x); } catch (NoSuchMethodException e) { Error x = new NoSuchMethodError(); x.initCause(e); throw x; } String serviceId = STR + clazz.getName(); Set<String> classNames = new HashSet<String>(); if(debug) { System.out.println(STR+serviceId+STR); } try { Enumeration<URL> e = classLoader.getResources(serviceId); if(e==null) return (T[])Array.newInstance(clazz,0); ArrayList<T> a = new ArrayList<T>(); while(e.hasMoreElements()) { URL url = e.nextElement(); BufferedReader reader=null; if(debug) { System.out.println(STR+url+STR); } try { reader = new BufferedReader(new InputStreamReader(url.openStream())); String impl; while((impl = reader.readLine())!=null ) { impl = impl.trim(); if(classNames.add(impl)) { Class implClass = classLoader.loadClass(impl); if(!clazz.isAssignableFrom(implClass)) { pluginLoadFailure = impl+STR+clazz+STR; if(debug) System.out.println(pluginLoadFailure); continue; } if(debug) { System.out.println(STR+impl); } a.add(clazz.cast(implClass.newInstance())); } } reader.close(); } catch( Exception ex ) { StringWriter w = new StringWriter(); ex.printStackTrace(new PrintWriter(w)); pluginLoadFailure = w.toString(); if(debug) { System.out.println(pluginLoadFailure); } if( reader!=null ) { try { reader.close(); } catch( IOException ex2 ) { } } } } return a.toArray((T[])Array.newInstance(clazz,a.size())); } catch( Throwable e ) { StringWriter w = new StringWriter(); e.printStackTrace(new PrintWriter(w)); pluginLoadFailure = w.toString(); if(debug) { System.out.println(pluginLoadFailure); } return (T[])Array.newInstance(clazz,0); } } | /**
* Looks for all "META-INF/services/[className]" files and
* create one instance for each class name found inside this file.
*/ | Looks for all "META-INF/services/[className]" files and create one instance for each class name found inside this file | findServices | {
"repo_name": "PrincetonUniversity/NVJVM",
"path": "build/linux-amd64/jaxws/drop/jaxws_src/src/com/sun/tools/internal/xjc/Options.java",
"license": "gpl-2.0",
"size": 36349
} | [
"com.sun.tools.internal.xjc.reader.Util",
"java.io.BufferedReader",
"java.io.IOException",
"java.io.InputStreamReader",
"java.io.PrintWriter",
"java.io.StringWriter",
"java.lang.reflect.Array",
"java.lang.reflect.InvocationTargetException",
"java.util.ArrayList",
"java.util.Enumeration",
"java.util.HashSet",
"java.util.List",
"java.util.Set"
] | import com.sun.tools.internal.xjc.reader.Util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Set; | import com.sun.tools.internal.xjc.reader.*; import java.io.*; import java.lang.reflect.*; import java.util.*; | [
"com.sun.tools",
"java.io",
"java.lang",
"java.util"
] | com.sun.tools; java.io; java.lang; java.util; | 679,844 |
@Test
public void testRedoRenameFolderInFolderListing() throws IOException {
// create original folder
String parent = "parent";
Path parentFolder = new Path(parent);
assertTrue(fs.mkdirs(parentFolder));
Path inner = new Path(parentFolder, "innerFolder");
assertTrue(fs.mkdirs(inner));
Path inner2 = new Path(parentFolder, "innerFolder2");
assertTrue(fs.mkdirs(inner2));
Path innerFile = new Path(inner2, "file");
assertTrue(fs.createNewFile(innerFile));
Path inner2renamed = new Path(parentFolder, "innerFolder2Renamed");
// propose (but don't do) the rename of innerFolder2
Path home = fs.getHomeDirectory();
String relativeHomeDir = getRelativePath(home.toString());
NativeAzureFileSystem.FolderRenamePending pending =
new NativeAzureFileSystem.FolderRenamePending(
relativeHomeDir + "/" + inner2,
relativeHomeDir + "/" + inner2renamed, null,
(NativeAzureFileSystem) fs);
// Create a rename-pending file and write rename information to it.
final String renamePendingStr = inner2 + FolderRenamePending.SUFFIX;
Path renamePendingFile = new Path(renamePendingStr);
FSDataOutputStream out = fs.create(renamePendingFile, true);
assertTrue(out != null);
writeString(out, pending.makeRenamePendingFileContents());
// Redo the rename operation based on the contents of the
// -RenamePending.json file. Trigger the redo by checking for existence of
// the original folder. It must appear to not exist.
FileStatus[] listed = fs.listStatus(parentFolder);
assertEquals(2, listed.length);
assertTrue(listed[0].isDirectory());
assertTrue(listed[1].isDirectory());
// The rename pending file is not a directory, so at this point we know the
// redo has been done.
assertFalse(fs.exists(inner2)); // verify original folder is gone
assertTrue(fs.exists(inner2renamed)); // verify the target is there
assertTrue(fs.exists(new Path(inner2renamed, "file")));
} | void function() throws IOException { String parent = STR; Path parentFolder = new Path(parent); assertTrue(fs.mkdirs(parentFolder)); Path inner = new Path(parentFolder, STR); assertTrue(fs.mkdirs(inner)); Path inner2 = new Path(parentFolder, STR); assertTrue(fs.mkdirs(inner2)); Path innerFile = new Path(inner2, "file"); assertTrue(fs.createNewFile(innerFile)); Path inner2renamed = new Path(parentFolder, STR); Path home = fs.getHomeDirectory(); String relativeHomeDir = getRelativePath(home.toString()); NativeAzureFileSystem.FolderRenamePending pending = new NativeAzureFileSystem.FolderRenamePending( relativeHomeDir + "/" + inner2, relativeHomeDir + "/" + inner2renamed, null, (NativeAzureFileSystem) fs); final String renamePendingStr = inner2 + FolderRenamePending.SUFFIX; Path renamePendingFile = new Path(renamePendingStr); FSDataOutputStream out = fs.create(renamePendingFile, true); assertTrue(out != null); writeString(out, pending.makeRenamePendingFileContents()); FileStatus[] listed = fs.listStatus(parentFolder); assertEquals(2, listed.length); assertTrue(listed[0].isDirectory()); assertTrue(listed[1].isDirectory()); assertFalse(fs.exists(inner2)); assertTrue(fs.exists(inner2renamed)); assertTrue(fs.exists(new Path(inner2renamed, "file"))); } | /**
* If there is a folder to be renamed inside a parent folder,
* then when you list the parent folder, you should only see
* the final result, after the rename.
*/ | If there is a folder to be renamed inside a parent folder, then when you list the parent folder, you should only see the final result, after the rename | testRedoRenameFolderInFolderListing | {
"repo_name": "Microsoft-CISL/hadoop-prototype",
"path": "hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azure/NativeAzureFileSystemBaseTest.java",
"license": "apache-2.0",
"size": 57447
} | [
"java.io.IOException",
"org.apache.hadoop.fs.FSDataOutputStream",
"org.apache.hadoop.fs.FileStatus",
"org.apache.hadoop.fs.Path",
"org.apache.hadoop.fs.azure.NativeAzureFileSystem",
"org.junit.Assert"
] | import java.io.IOException; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.azure.NativeAzureFileSystem; import org.junit.Assert; | import java.io.*; import org.apache.hadoop.fs.*; import org.apache.hadoop.fs.azure.*; import org.junit.*; | [
"java.io",
"org.apache.hadoop",
"org.junit"
] | java.io; org.apache.hadoop; org.junit; | 233,534 |
void moveAllowedValues(RelationType<? extends Collection<T>> rSource,
RelationType<? extends Collection<T>> rTarget,
boolean bAllValues)
{
Collection<T> rSourceValues;
List<T> rTargetValues = new ArrayList<>(getAllowedElements(rTarget));
if (bAllValues)
{
rSourceValues = getAllowedElements(rSource);
getParameter(rSource).clear();
}
else
{
rSourceValues = getParameter(rSource);
getAllowedElements(rSource).removeAll(rSourceValues);
}
rTargetValues.addAll(rSourceValues);
setAllowedElements(rTarget, sortValues(rTargetValues));
rSourceValues.clear();
if (rSelectionListener != null)
{
rSelectionListener.selectionChanged(this);
}
} | void moveAllowedValues(RelationType<? extends Collection<T>> rSource, RelationType<? extends Collection<T>> rTarget, boolean bAllValues) { Collection<T> rSourceValues; List<T> rTargetValues = new ArrayList<>(getAllowedElements(rTarget)); if (bAllValues) { rSourceValues = getAllowedElements(rSource); getParameter(rSource).clear(); } else { rSourceValues = getParameter(rSource); getAllowedElements(rSource).removeAll(rSourceValues); } rTargetValues.addAll(rSourceValues); setAllowedElements(rTarget, sortValues(rTargetValues)); rSourceValues.clear(); if (rSelectionListener != null) { rSelectionListener.selectionChanged(this); } } | /***************************************
* Moves certain allowed values from one parameter to another.
*
* @param rSource The source parameter
* @param rTarget The target parameter
* @param bAllValues TRUE for all allowed values, FALSE for only the
* selected values in the source parameter
*/ | Moves certain allowed values from one parameter to another | moveAllowedValues | {
"repo_name": "esoco/esoco-business",
"path": "src/main/java/de/esoco/process/step/SelectValues.java",
"license": "apache-2.0",
"size": 13929
} | [
"java.util.ArrayList",
"java.util.Collection",
"java.util.List",
"org.obrel.core.RelationType"
] | import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.obrel.core.RelationType; | import java.util.*; import org.obrel.core.*; | [
"java.util",
"org.obrel.core"
] | java.util; org.obrel.core; | 1,677,676 |
protected CertPathParameters getParameters(String algorithm,
String crlf,
KeyStore trustStore)
throws Exception {
CertPathParameters params = null;
if("PKIX".equalsIgnoreCase(algorithm)) {
PKIXBuilderParameters xparams =
new PKIXBuilderParameters(trustStore, new X509CertSelector());
Collection<? extends CRL> crls = getCRLs(crlf);
CertStoreParameters csp = new CollectionCertStoreParameters(crls);
CertStore store = CertStore.getInstance("Collection", csp);
xparams.addCertStore(store);
xparams.setRevocationEnabled(true);
String trustLength = endpoint.getTrustMaxCertLength();
if(trustLength != null) {
try {
xparams.setMaxPathLength(Integer.parseInt(trustLength));
} catch(Exception ex) {
log.warn("Bad maxCertLength: "+trustLength);
}
}
params = xparams;
} else {
throw new CRLException("CRLs not supported for type: "+algorithm);
}
return params;
} | CertPathParameters function(String algorithm, String crlf, KeyStore trustStore) throws Exception { CertPathParameters params = null; if("PKIX".equalsIgnoreCase(algorithm)) { PKIXBuilderParameters xparams = new PKIXBuilderParameters(trustStore, new X509CertSelector()); Collection<? extends CRL> crls = getCRLs(crlf); CertStoreParameters csp = new CollectionCertStoreParameters(crls); CertStore store = CertStore.getInstance(STR, csp); xparams.addCertStore(store); xparams.setRevocationEnabled(true); String trustLength = endpoint.getTrustMaxCertLength(); if(trustLength != null) { try { xparams.setMaxPathLength(Integer.parseInt(trustLength)); } catch(Exception ex) { log.warn(STR+trustLength); } } params = xparams; } else { throw new CRLException(STR+algorithm); } return params; } | /**
* Return the initialization parameters for the TrustManager.
* Currently, only the default <code>PKIX</code> is supported.
*
* @param algorithm The algorithm to get parameters for.
* @param crlf The path to the CRL file.
* @param trustStore The configured TrustStore.
* @return The parameters including the CRLs and TrustStore.
*/ | Return the initialization parameters for the TrustManager. Currently, only the default <code>PKIX</code> is supported | getParameters | {
"repo_name": "codefollower/Open-Source-Research",
"path": "Douyu-0.7.1/douyu-http/src/main/java/com/codefollower/douyu/http/ssl/jsse/JSSESocketFactory.java",
"license": "apache-2.0",
"size": 30384
} | [
"java.security.KeyStore",
"java.security.cert.CRLException",
"java.security.cert.CertPathParameters",
"java.security.cert.CertStore",
"java.security.cert.CertStoreParameters",
"java.security.cert.CollectionCertStoreParameters",
"java.security.cert.PKIXBuilderParameters",
"java.security.cert.X509CertSelector",
"java.util.Collection"
] | import java.security.KeyStore; import java.security.cert.CRLException; import java.security.cert.CertPathParameters; import java.security.cert.CertStore; import java.security.cert.CertStoreParameters; import java.security.cert.CollectionCertStoreParameters; import java.security.cert.PKIXBuilderParameters; import java.security.cert.X509CertSelector; import java.util.Collection; | import java.security.*; import java.security.cert.*; import java.util.*; | [
"java.security",
"java.util"
] | java.security; java.util; | 478,510 |
default Function11<T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, R> curry(Tuple3<T1, T2, T3> args) {
return (v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) -> apply(args.v1, args.v2, args.v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14);
} | default Function11<T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, R> curry(Tuple3<T1, T2, T3> args) { return (v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) -> apply(args.v1, args.v2, args.v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14); } | /**
* Partially apply this function to the arguments.
*/ | Partially apply this function to the arguments | curry | {
"repo_name": "colinger/jOOL",
"path": "src/main/java/org/jooq/lambda/function/Function14.java",
"license": "apache-2.0",
"size": 11076
} | [
"org.jooq.lambda.tuple.Tuple3"
] | import org.jooq.lambda.tuple.Tuple3; | import org.jooq.lambda.tuple.*; | [
"org.jooq.lambda"
] | org.jooq.lambda; | 1,826,459 |
public int getWarp(ItemStack itemstack, EntityPlayer player);
| int function(ItemStack itemstack, EntityPlayer player); | /**
* returns how much warp this item adds while worn or held.
*/ | returns how much warp this item adds while worn or held | getWarp | {
"repo_name": "jaquadro/StorageDrawers",
"path": "api/thaumcraft/api/items/IWarpingGear.java",
"license": "mit",
"size": 434
} | [
"net.minecraft.entity.player.EntityPlayer",
"net.minecraft.item.ItemStack"
] | import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; | import net.minecraft.entity.player.*; import net.minecraft.item.*; | [
"net.minecraft.entity",
"net.minecraft.item"
] | net.minecraft.entity; net.minecraft.item; | 2,502,626 |
boolean isMethod(HttpMethod method); | boolean isMethod(HttpMethod method); | /**
* Checks if the request HTTP method matched the specified as parameter
*
* @param method Specified method
* @return true if the HTTP method matches the specified, false otherwise
*/ | Checks if the request HTTP method matched the specified as parameter | isMethod | {
"repo_name": "ogrebgr/forge-server",
"path": "src/main/java/com/bolyartech/forge/server/route/RequestContext.java",
"license": "apache-2.0",
"size": 7611
} | [
"com.bolyartech.forge.server.HttpMethod"
] | import com.bolyartech.forge.server.HttpMethod; | import com.bolyartech.forge.server.*; | [
"com.bolyartech.forge"
] | com.bolyartech.forge; | 979,222 |
private File allocate(String filename, long size) throws StoreException {
File segmentFile = new File(dataDir, filename);
if (!segmentFile.exists()) {
try {
diskSpaceAllocator.allocate(segmentFile, size);
} catch (IOException e) {
StoreErrorCodes errorCode =
Objects.equals(e.getMessage(), StoreException.IO_ERROR_STR) ? StoreErrorCodes.IOError
: StoreErrorCodes.Unknown_Error;
throw new StoreException(errorCode.toString() + " while allocating the file", e, errorCode);
}
}
return segmentFile;
} | File function(String filename, long size) throws StoreException { File segmentFile = new File(dataDir, filename); if (!segmentFile.exists()) { try { diskSpaceAllocator.allocate(segmentFile, size); } catch (IOException e) { StoreErrorCodes errorCode = Objects.equals(e.getMessage(), StoreException.IO_ERROR_STR) ? StoreErrorCodes.IOError : StoreErrorCodes.Unknown_Error; throw new StoreException(errorCode.toString() + STR, e, errorCode); } } return segmentFile; } | /**
* Allocates a file named {@code filename} and of capacity {@code size}.
* @param filename the intended filename of the file.
* @param size the intended size of the file.
* @return a {@link File} instance that points to the created file named {@code filename} and capacity {@code size}.
* @throws StoreException if the there is any store exception while allocating the file.
*/ | Allocates a file named filename and of capacity size | allocate | {
"repo_name": "pnarayanan/ambry",
"path": "ambry-store/src/main/java/com.github.ambry.store/Log.java",
"license": "apache-2.0",
"size": 27046
} | [
"java.io.File",
"java.io.IOException",
"java.util.Objects"
] | import java.io.File; import java.io.IOException; import java.util.Objects; | import java.io.*; import java.util.*; | [
"java.io",
"java.util"
] | java.io; java.util; | 1,245,402 |
public void write(byte[] theBytes, int off, int len) throws java.io.IOException {
// Encoding suspended?
if (suspendEncoding) {
super.out.write(theBytes, off, len);
return;
} // end if: supsended
for (int i = 0; i < len; i++) {
write(theBytes[off + i]);
} // end for: each byte written
} // end write | void function(byte[] theBytes, int off, int len) throws java.io.IOException { if (suspendEncoding) { super.out.write(theBytes, off, len); return; } for (int i = 0; i < len; i++) { write(theBytes[off + i]); } } | /**
* Calls {@link #write(int)} repeatedly until <var>len</var> bytes are written.
*
* @param theBytes array from which to read bytes
* @param off offset for array
* @param len max number of bytes to read into array
* @since 1.3
*/ | Calls <code>#write(int)</code> repeatedly until len bytes are written | write | {
"repo_name": "picketlink/picketlink-certmgmt",
"path": "server/src/main/java/org/picketlink/certmgmt/Base64.java",
"license": "apache-2.0",
"size": 50520
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 1,963,973 |
private void setActivityTitle(String title) {
if (null != ((AppCompatActivity) getActivity()).getSupportActionBar()) {
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(title);
}
} | void function(String title) { if (null != ((AppCompatActivity) getActivity()).getSupportActionBar()) { ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(title); } } | /**
* Update the activity title
*
* @param title the new title
*/ | Update the activity title | setActivityTitle | {
"repo_name": "riot-spanish/riot-android",
"path": "vector/src/main/java/im/vector/fragments/VectorRoomDetailsMembersFragment.java",
"license": "apache-2.0",
"size": 39169
} | [
"android.support.v7.app.AppCompatActivity"
] | import android.support.v7.app.AppCompatActivity; | import android.support.v7.app.*; | [
"android.support"
] | android.support; | 562,194 |
ImmutableList<String> getCopts() {
return copts;
} | ImmutableList<String> getCopts() { return copts; } | /**
* The compiler flags used for the compile that should also be used when finishing compilation
* during the LTO backend.
*/ | The compiler flags used for the compile that should also be used when finishing compilation during the LTO backend | getCopts | {
"repo_name": "dslomov/bazel",
"path": "src/main/java/com/google/devtools/build/lib/rules/cpp/LtoCompilationContext.java",
"license": "apache-2.0",
"size": 5572
} | [
"com.google.common.collect.ImmutableList"
] | import com.google.common.collect.ImmutableList; | import com.google.common.collect.*; | [
"com.google.common"
] | com.google.common; | 189,972 |
public long getQuota(ContentCollection collection) {
long quota = m_siteQuota;
String default_quota = DEFAULT_RESOURCE_QUOTA;
ContentCollection parentCollection = null;
// parse a string like /user/344454534543534535353543535
String[] parts = StringUtil.split(collection.getId(), Entity.SEPARATOR);
if (parts.length >= 3) {
String siteId = null;
// SITE_ID come in 2 forms (~siteid||siteid)
if (parts[1].equals("user")) {
siteId = "~" + parts[2];
} else {
siteId = parts[2];
}
if (collection.getId().startsWith(COLLECTION_DROPBOX)) {
default_quota = DEFAULT_DROPBOX_QUOTA;
quota = m_dropBoxQuota;
try {
parentCollection = findCollection(Entity.SEPARATOR + parts[1] + Entity.SEPARATOR + parts[2] + Entity.SEPARATOR);
} catch (TypeException tex) {
}
}
String siteType = null;
// get the site type
try {
siteType = m_siteService.getSite(siteId).getType();
} catch (IdUnusedException e) {
M_log.warn("Quota calculation could not find the site '"+ siteId + "' to determine the type.", M_log.isDebugEnabled()?e:null);
}
// use this quota unless we have one more specific
if (siteType != null) {
quota = Long.parseLong(m_serverConfigurationService.getString(default_quota + siteType, Long.toString(collection.getId().startsWith(COLLECTION_DROPBOX)?m_dropBoxQuota:m_siteQuota)));
}
}
// see if this collection has a quota property
try
{
long siteSpecific = collection.getProperties().getLongProperty(
ResourceProperties.PROP_COLLECTION_BODY_QUOTA);
quota = siteSpecific;
}
catch (EntityPropertyNotDefinedException ignore)
{
// don't log or anything, this just means that this site doesn't have this quota property.
// Look for dropBox quota in parent collection
try {
if (parentCollection!=null) {
long siteSpecific = parentCollection.getProperties().getLongProperty(
ResourceProperties.PROP_COLLECTION_BODY_QUOTA);
quota = siteSpecific;
}
} catch (EntityPropertyTypeException ignoretex) {
// don't log or anything, this just means that this site doesn't have this quota property.
} catch (EntityPropertyNotDefinedException ignoreex) {
// don't log or anything, this just means that this site doesn't have this quota property.
}
}
catch (Exception ignore)
{
M_log.warn("getQuota: reading quota property of : " + collection.getId() + " : " + ignore);
}
return quota;
} | long function(ContentCollection collection) { long quota = m_siteQuota; String default_quota = DEFAULT_RESOURCE_QUOTA; ContentCollection parentCollection = null; String[] parts = StringUtil.split(collection.getId(), Entity.SEPARATOR); if (parts.length >= 3) { String siteId = null; if (parts[1].equals("user")) { siteId = "~" + parts[2]; } else { siteId = parts[2]; } if (collection.getId().startsWith(COLLECTION_DROPBOX)) { default_quota = DEFAULT_DROPBOX_QUOTA; quota = m_dropBoxQuota; try { parentCollection = findCollection(Entity.SEPARATOR + parts[1] + Entity.SEPARATOR + parts[2] + Entity.SEPARATOR); } catch (TypeException tex) { } } String siteType = null; try { siteType = m_siteService.getSite(siteId).getType(); } catch (IdUnusedException e) { M_log.warn(STR+ siteId + STR, M_log.isDebugEnabled()?e:null); } if (siteType != null) { quota = Long.parseLong(m_serverConfigurationService.getString(default_quota + siteType, Long.toString(collection.getId().startsWith(COLLECTION_DROPBOX)?m_dropBoxQuota:m_siteQuota))); } } try { long siteSpecific = collection.getProperties().getLongProperty( ResourceProperties.PROP_COLLECTION_BODY_QUOTA); quota = siteSpecific; } catch (EntityPropertyNotDefinedException ignore) { try { if (parentCollection!=null) { long siteSpecific = parentCollection.getProperties().getLongProperty( ResourceProperties.PROP_COLLECTION_BODY_QUOTA); quota = siteSpecific; } } catch (EntityPropertyTypeException ignoretex) { } catch (EntityPropertyNotDefinedException ignoreex) { } } catch (Exception ignore) { M_log.warn(STR + collection.getId() + STR + ignore); } return quota; } | /**
* gets the quota for a site collection or for a user's my workspace collection
*
* @param collection the collection on which to test for a quota. this can be the collection for a site
* or a user's workspace collection
* @return the quota in kb
*/ | gets the quota for a site collection or for a user's my workspace collection | getQuota | {
"repo_name": "marktriggs/nyu-sakai-10.4",
"path": "kernel/kernel-impl/src/main/java/org/sakaiproject/content/impl/BaseContentService.java",
"license": "apache-2.0",
"size": 426240
} | [
"org.sakaiproject.content.api.ContentCollection",
"org.sakaiproject.entity.api.Entity",
"org.sakaiproject.entity.api.EntityPropertyNotDefinedException",
"org.sakaiproject.entity.api.EntityPropertyTypeException",
"org.sakaiproject.entity.api.ResourceProperties",
"org.sakaiproject.exception.IdUnusedException",
"org.sakaiproject.exception.TypeException",
"org.sakaiproject.util.StringUtil"
] | import org.sakaiproject.content.api.ContentCollection; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.entity.api.EntityPropertyNotDefinedException; import org.sakaiproject.entity.api.EntityPropertyTypeException; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.TypeException; import org.sakaiproject.util.StringUtil; | import org.sakaiproject.content.api.*; import org.sakaiproject.entity.api.*; import org.sakaiproject.exception.*; import org.sakaiproject.util.*; | [
"org.sakaiproject.content",
"org.sakaiproject.entity",
"org.sakaiproject.exception",
"org.sakaiproject.util"
] | org.sakaiproject.content; org.sakaiproject.entity; org.sakaiproject.exception; org.sakaiproject.util; | 2,109,311 |
public static Object create(int dsfid, DataInput in)
throws IOException, ClassNotFoundException {
switch (dsfid) {
case REGION:
return (DataSerializableFixedID)DataSerializer.readRegion(in);
case END_OF_STREAM_TOKEN:
return Token.END_OF_STREAM;
case DLOCK_REMOTE_TOKEN:
return DLockRemoteToken.createFromDataInput(in);
case TRANSACTION_ID:
return TXId.createFromData(in);
case INTEREST_RESULT_POLICY:
return readInterestResultPolicy(in);
case UNDEFINED:
return readUndefined(in);
case RESULTS_BAG:
return readResultsBag(in);
case SQLF_TYPE:
return readSqlfMessage(in);
case SQLF_DVD_OBJECT:
return readDVD(in);
case SQLF_GLOBAL_ROWLOC:
return readGlobalRowLocation(in);
case SQLF_GEMFIRE_KEY:
return readGemFireKey(in);
case SQLF_FORMATIBLEBITSET:
return readSqlFormatibleBitSet(in);
case TOKEN_INVALID:
return Token.INVALID;
case TOKEN_LOCAL_INVALID:
return Token.LOCAL_INVALID;
case TOKEN_DESTROYED:
return Token.DESTROYED;
case TOKEN_REMOVED:
return Token.REMOVED_PHASE1;
case TOKEN_REMOVED2:
return Token.REMOVED_PHASE2;
case TOKEN_TOMBSTONE:
return Token.TOMBSTONE;
case NULL_TOKEN:
return readNullToken(in);
case CONFIGURATION_REQUEST :
return readConfigurationRequest(in);
case CONFIGURATION_RESPONSE:
return readConfigurationResponse(in);
case PR_DESTROY_ON_DATA_STORE_MESSAGE:
return readDestroyOnDataStore(in);
default:
final Constructor<?> cons;
if (dsfid >= Byte.MIN_VALUE && dsfid <= Byte.MAX_VALUE) {
cons = dsfidMap[dsfid + Byte.MAX_VALUE + 1];
} else {
cons = (Constructor<?>) dsfidMap2.get(dsfid);
}
if (cons != null) {
try {
Object ds = cons
.newInstance((Object[]) null);
InternalDataSerializer.invokeFromData(ds, in);
return ds;
} catch (InstantiationException ie) {
throw new IOException(ie.getMessage(), ie);
} catch (IllegalAccessException iae) {
throw new IOException(iae.getMessage(), iae);
} catch (InvocationTargetException ite) {
Throwable targetEx = ite.getTargetException();
if (targetEx instanceof IOException) {
throw (IOException) targetEx;
} else if (targetEx instanceof ClassNotFoundException) {
throw (ClassNotFoundException) targetEx;
} else {
throw new IOException(ite.getMessage(), targetEx);
}
}
}
throw new DSFIDNotFoundException("Unknown DataSerializableFixedID: "
+ dsfid, dsfid);
}
} | static Object function(int dsfid, DataInput in) throws IOException, ClassNotFoundException { switch (dsfid) { case REGION: return (DataSerializableFixedID)DataSerializer.readRegion(in); case END_OF_STREAM_TOKEN: return Token.END_OF_STREAM; case DLOCK_REMOTE_TOKEN: return DLockRemoteToken.createFromDataInput(in); case TRANSACTION_ID: return TXId.createFromData(in); case INTEREST_RESULT_POLICY: return readInterestResultPolicy(in); case UNDEFINED: return readUndefined(in); case RESULTS_BAG: return readResultsBag(in); case SQLF_TYPE: return readSqlfMessage(in); case SQLF_DVD_OBJECT: return readDVD(in); case SQLF_GLOBAL_ROWLOC: return readGlobalRowLocation(in); case SQLF_GEMFIRE_KEY: return readGemFireKey(in); case SQLF_FORMATIBLEBITSET: return readSqlFormatibleBitSet(in); case TOKEN_INVALID: return Token.INVALID; case TOKEN_LOCAL_INVALID: return Token.LOCAL_INVALID; case TOKEN_DESTROYED: return Token.DESTROYED; case TOKEN_REMOVED: return Token.REMOVED_PHASE1; case TOKEN_REMOVED2: return Token.REMOVED_PHASE2; case TOKEN_TOMBSTONE: return Token.TOMBSTONE; case NULL_TOKEN: return readNullToken(in); case CONFIGURATION_REQUEST : return readConfigurationRequest(in); case CONFIGURATION_RESPONSE: return readConfigurationResponse(in); case PR_DESTROY_ON_DATA_STORE_MESSAGE: return readDestroyOnDataStore(in); default: final Constructor<?> cons; if (dsfid >= Byte.MIN_VALUE && dsfid <= Byte.MAX_VALUE) { cons = dsfidMap[dsfid + Byte.MAX_VALUE + 1]; } else { cons = (Constructor<?>) dsfidMap2.get(dsfid); } if (cons != null) { try { Object ds = cons .newInstance((Object[]) null); InternalDataSerializer.invokeFromData(ds, in); return ds; } catch (InstantiationException ie) { throw new IOException(ie.getMessage(), ie); } catch (IllegalAccessException iae) { throw new IOException(iae.getMessage(), iae); } catch (InvocationTargetException ite) { Throwable targetEx = ite.getTargetException(); if (targetEx instanceof IOException) { throw (IOException) targetEx; } else if (targetEx instanceof ClassNotFoundException) { throw (ClassNotFoundException) targetEx; } else { throw new IOException(ite.getMessage(), targetEx); } } } throw new DSFIDNotFoundException(STR + dsfid, dsfid); } } | /**
* Creates a DataSerializableFixedID or StreamableFixedID instance by deserializing it from
* the data input.
*/ | Creates a DataSerializableFixedID or StreamableFixedID instance by deserializing it from the data input | create | {
"repo_name": "ysung-pivotal/incubator-geode",
"path": "gemfire-core/src/main/java/com/gemstone/gemfire/internal/DSFIDFactory.java",
"license": "apache-2.0",
"size": 77947
} | [
"com.gemstone.gemfire.DataSerializer",
"com.gemstone.gemfire.distributed.internal.locks.DLockRemoteToken",
"com.gemstone.gemfire.internal.cache.TXId",
"com.gemstone.gemfire.internal.cache.Token",
"java.io.DataInput",
"java.io.IOException",
"java.lang.reflect.Constructor",
"java.lang.reflect.InvocationTargetException"
] | import com.gemstone.gemfire.DataSerializer; import com.gemstone.gemfire.distributed.internal.locks.DLockRemoteToken; import com.gemstone.gemfire.internal.cache.TXId; import com.gemstone.gemfire.internal.cache.Token; import java.io.DataInput; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; | import com.gemstone.gemfire.*; import com.gemstone.gemfire.distributed.internal.locks.*; import com.gemstone.gemfire.internal.cache.*; import java.io.*; import java.lang.reflect.*; | [
"com.gemstone.gemfire",
"java.io",
"java.lang"
] | com.gemstone.gemfire; java.io; java.lang; | 1,725,969 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.