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 static DetailAST parseFile(FileText text)
throws ANTLRException {
final FileContents contents = new FileContents(text);
return TreeWalker.parse(contents);
} | static DetailAST function(FileText text) throws ANTLRException { final FileContents contents = new FileContents(text); return TreeWalker.parse(contents); } | /**
* Parses a file and returns the parse tree.
* @param text the file to parse
* @return the root node of the parse tree
* @throws ANTLRException if the file is not a Java source
*/ | Parses a file and returns the parse tree | parseFile | {
"repo_name": "another-dave/checkstyle",
"path": "src/main/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeInfoPanel.java",
"license": "lgpl-2.1",
"size": 10756
} | [
"com.puppycrawl.tools.checkstyle.TreeWalker",
"com.puppycrawl.tools.checkstyle.api.DetailAST",
"com.puppycrawl.tools.checkstyle.api.FileContents",
"com.puppycrawl.tools.checkstyle.api.FileText"
] | import com.puppycrawl.tools.checkstyle.TreeWalker; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FileContents; import com.puppycrawl.tools.checkstyle.api.FileText; | import com.puppycrawl.tools.checkstyle.*; import com.puppycrawl.tools.checkstyle.api.*; | [
"com.puppycrawl.tools"
] | com.puppycrawl.tools; | 2,091,388 |
DeleteIndexTemplateRequestBuilder prepareDeleteTemplate(String name); | DeleteIndexTemplateRequestBuilder prepareDeleteTemplate(String name); | /**
* Deletes an index template.
*
* @param name The name of the template.
*/ | Deletes an index template | prepareDeleteTemplate | {
"repo_name": "strapdata/elassandra-test",
"path": "core/src/main/java/org/elasticsearch/client/IndicesAdminClient.java",
"license": "apache-2.0",
"size": 34405
} | [
"org.elasticsearch.action.admin.indices.template.delete.DeleteIndexTemplateRequestBuilder"
] | import org.elasticsearch.action.admin.indices.template.delete.DeleteIndexTemplateRequestBuilder; | import org.elasticsearch.action.admin.indices.template.delete.*; | [
"org.elasticsearch.action"
] | org.elasticsearch.action; | 2,741,534 |
public void addSymbolToScope(Identifier ident) {
addSymbolToScope(ident, null);
} | void function(Identifier ident) { addSymbolToScope(ident, null); } | /**
* Add a symbol into scope
*
* @param ident
*/ | Add a symbol into scope | addSymbolToScope | {
"repo_name": "apache/incubator-asterixdb",
"path": "asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/context/Scope.java",
"license": "apache-2.0",
"size": 9438
} | [
"org.apache.asterix.lang.common.struct.Identifier"
] | import org.apache.asterix.lang.common.struct.Identifier; | import org.apache.asterix.lang.common.struct.*; | [
"org.apache.asterix"
] | org.apache.asterix; | 2,004,819 |
public static List<Action> schedulePackageInstalls(User user,
Collection<Long> serverIds, List<Map<String, Long>> packages, Date earliest,
ActionChain actionChain) {
return schedulePackageActionsByOs(user, serverIds, packages, earliest, actionChain,
ActionFactory.TYPE_PACKAGES_UPDATE);
} | static List<Action> function(User user, Collection<Long> serverIds, List<Map<String, Long>> packages, Date earliest, ActionChain actionChain) { return schedulePackageActionsByOs(user, serverIds, packages, earliest, actionChain, ActionFactory.TYPE_PACKAGES_UPDATE); } | /**
* Schedules one or more package installation actions on one or more servers.
* @param user the user scheduling actions
* @param serverIds the affected servers' IDs
* @param packages a list of "package maps"
* @param earliest the earliest execution date
* @param actionChain the action chain or null
* @return scheduled actions
* @see ActionManager#addPackageActionDetails(Action, List) for "package map"
*/ | Schedules one or more package installation actions on one or more servers | schedulePackageInstalls | {
"repo_name": "mcalmer/spacewalk",
"path": "java/code/src/com/redhat/rhn/manager/action/ActionChainManager.java",
"license": "gpl-2.0",
"size": 23405
} | [
"com.redhat.rhn.domain.action.Action",
"com.redhat.rhn.domain.action.ActionChain",
"com.redhat.rhn.domain.action.ActionFactory",
"com.redhat.rhn.domain.user.User",
"java.util.Collection",
"java.util.Date",
"java.util.List",
"java.util.Map"
] | import com.redhat.rhn.domain.action.Action; import com.redhat.rhn.domain.action.ActionChain; import com.redhat.rhn.domain.action.ActionFactory; import com.redhat.rhn.domain.user.User; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; | import com.redhat.rhn.domain.action.*; import com.redhat.rhn.domain.user.*; import java.util.*; | [
"com.redhat.rhn",
"java.util"
] | com.redhat.rhn; java.util; | 1,617,514 |
protected void keyTyped(char typedChar, int keyCode) throws IOException
{
if (keyCode == 1)
{
this.wakeFromSleep();
}
else if (keyCode != 28 && keyCode != 156)
{
super.keyTyped(typedChar, keyCode);
}
else
{
String s = this.inputField.getText().trim();
if (!s.isEmpty())
{
this.sendChatMessage(s); // Forge: fix vanilla not adding messages to the sent list while sleeping
}
this.inputField.setText("");
this.mc.ingameGUI.getChatGUI().resetScroll();
}
} | void function(char typedChar, int keyCode) throws IOException { if (keyCode == 1) { this.wakeFromSleep(); } else if (keyCode != 28 && keyCode != 156) { super.keyTyped(typedChar, keyCode); } else { String s = this.inputField.getText().trim(); if (!s.isEmpty()) { this.sendChatMessage(s); } this.inputField.setText(""); this.mc.ingameGUI.getChatGUI().resetScroll(); } } | /**
* Fired when a key is typed (except F11 which toggles full screen). This is the equivalent of
* KeyListener.keyTyped(KeyEvent e). Args : character (character on the key), keyCode (lwjgl Keyboard key code)
*/ | Fired when a key is typed (except F11 which toggles full screen). This is the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character (character on the key), keyCode (lwjgl Keyboard key code) | keyTyped | {
"repo_name": "TheGreatAndPowerfulWeegee/wipunknown",
"path": "build/tmp/recompileMc/sources/net/minecraft/client/gui/GuiSleepMP.java",
"license": "gpl-3.0",
"size": 2262
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 2,389,604 |
@Override
public ComparableObjectItem getDataItem(int index) {
return super.getDataItem(index);
}
| ComparableObjectItem function(int index) { return super.getDataItem(index); } | /**
* Returns the data item at the specified index.
*
* @param index the item index.
*
* @return The data item.
*/ | Returns the data item at the specified index | getDataItem | {
"repo_name": "jfree/jfreechart",
"path": "src/main/java/org/jfree/data/time/ohlc/OHLCSeries.java",
"license": "lgpl-2.1",
"size": 4362
} | [
"org.jfree.data.ComparableObjectItem"
] | import org.jfree.data.ComparableObjectItem; | import org.jfree.data.*; | [
"org.jfree.data"
] | org.jfree.data; | 1,892,287 |
EReference getDataOutput_OutputSetWithWhileExecuting(); | EReference getDataOutput_OutputSetWithWhileExecuting(); | /**
* Returns the meta object for the reference list '{@link org.eclipse.bpmn2.DataOutput#getOutputSetWithWhileExecuting <em>Output Set With While Executing</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference list '<em>Output Set With While Executing</em>'.
* @see org.eclipse.bpmn2.DataOutput#getOutputSetWithWhileExecuting()
* @see #getDataOutput()
* @generated
*/ | Returns the meta object for the reference list '<code>org.eclipse.bpmn2.DataOutput#getOutputSetWithWhileExecuting Output Set With While Executing</code>'. | getDataOutput_OutputSetWithWhileExecuting | {
"repo_name": "Rikkola/kie-wb-common",
"path": "kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-emf/src/main/java/org/eclipse/bpmn2/Bpmn2Package.java",
"license": "apache-2.0",
"size": 929298
} | [
"org.eclipse.emf.ecore.EReference"
] | import org.eclipse.emf.ecore.EReference; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 2,124,206 |
private void updateAllAsyncInternal0(
UUID nodeId,
GridNearAtomicAbstractUpdateRequest req,
UpdateReplyClosure completionCb
) {
ClusterNode node = ctx.discovery().node(nodeId);
if (node == null) {
U.warn(msgLog, "Skip near update request, node originated update request left [" +
"futId=" + req.futureId() + ", node=" + nodeId + ']');
return;
}
GridNearAtomicUpdateResponse res = new GridNearAtomicUpdateResponse(ctx.cacheId(),
nodeId,
req.futureId(),
req.partition(),
false,
ctx.deploymentEnabled());
assert !req.returnValue() || (req.operation() == TRANSFORM || req.size() == 1);
GridDhtAtomicAbstractUpdateFuture dhtFut = null;
boolean remap = false;
String taskName = ctx.kernalContext().task().resolveTaskName(req.taskNameHash());
IgniteCacheExpiryPolicy expiry = null;
try {
// If batch store update is enabled, we need to lock all entries.
// First, need to acquire locks on cache entries, then check filter.
List<GridDhtCacheEntry> locked = null;
Collection<IgniteBiTuple<GridDhtCacheEntry, GridCacheVersion>> deleted = null;
try {
GridDhtPartitionTopology top = topology();
top.readLock();
try {
if (top.stopping()) {
res.addFailedKeys(req.keys(), new IgniteCheckedException("Failed to perform cache operation " +
"(cache is stopped): " + name()));
completionCb.apply(req, res);
return;
}
// Do not check topology version if topology was locked on near node by
// external transaction or explicit lock.
if (req.topologyLocked() || !needRemap(req.topologyVersion(), top.topologyVersion())) {
locked = lockEntries(req, req.topologyVersion());
boolean hasNear = ctx.discovery().cacheNearNode(node, name());
// Assign next version for update inside entries lock.
GridCacheVersion ver = ctx.versions().next(top.topologyVersion());
if (hasNear)
res.nearVersion(ver);
if (msgLog.isDebugEnabled()) {
msgLog.debug("Assigned update version [futId=" + req.futureId() +
", writeVer=" + ver + ']');
}
assert ver != null : "Got null version for update request: " + req;
boolean sndPrevVal = !top.rebalanceFinished(req.topologyVersion());
dhtFut = createDhtFuture(ver, req);
expiry = expiryPolicy(req.expiry());
GridCacheReturn retVal = null;
if (req.size() > 1 && // Several keys ...
writeThrough() && !req.skipStore() && // and store is enabled ...
!ctx.store().isLocal() && // and this is not local store ...
// (conflict resolver should be used for local store)
!ctx.dr().receiveEnabled() // and no DR.
) {
// This method can only be used when there are no replicated entries in the batch.
UpdateBatchResult updRes = updateWithBatch(node,
hasNear,
req,
res,
locked,
ver,
dhtFut,
ctx.isDrEnabled(),
taskName,
expiry,
sndPrevVal);
deleted = updRes.deleted();
dhtFut = updRes.dhtFuture();
if (req.operation() == TRANSFORM)
retVal = updRes.invokeResults();
}
else {
UpdateSingleResult updRes = updateSingle(node,
hasNear,
req,
res,
locked,
ver,
dhtFut,
ctx.isDrEnabled(),
taskName,
expiry,
sndPrevVal);
retVal = updRes.returnValue();
deleted = updRes.deleted();
dhtFut = updRes.dhtFuture();
}
if (retVal == null)
retVal = new GridCacheReturn(ctx, node.isLocal(), true, null, true);
res.returnValue(retVal);
if (dhtFut != null)
ctx.mvcc().addAtomicFuture(dhtFut.id(), dhtFut);
}
else {
// Should remap all keys.
remap = true;
res.remapTopologyVersion(top.topologyVersion());
}
}
finally {
top.readUnlock();
}
}
catch (GridCacheEntryRemovedException e) {
assert false : "Entry should not become obsolete while holding lock.";
e.printStackTrace();
}
finally {
if (locked != null)
unlockEntries(locked, req.topologyVersion());
// Enqueue if necessary after locks release.
if (deleted != null) {
assert !deleted.isEmpty();
assert ctx.deferredDelete() : this;
for (IgniteBiTuple<GridDhtCacheEntry, GridCacheVersion> e : deleted)
ctx.onDeferredDelete(e.get1(), e.get2());
}
}
}
catch (GridDhtInvalidPartitionException ignore) {
if (log.isDebugEnabled())
log.debug("Caught invalid partition exception for cache entry (will remap update request): " + req);
remap = true;
res.remapTopologyVersion(ctx.topology().topologyVersion());
}
catch (Throwable e) {
// At least RuntimeException can be thrown by the code above when GridCacheContext is cleaned and there is
// an attempt to use cleaned resources.
U.error(log, "Unexpected exception during cache update", e);
res.addFailedKeys(req.keys(), e);
completionCb.apply(req, res);
if (e instanceof Error)
throw e;
return;
}
if (remap) {
assert dhtFut == null;
completionCb.apply(req, res);
}
else
if (dhtFut != null)
dhtFut.map(node, res.returnValue(), res, completionCb);
if (req.writeSynchronizationMode() != FULL_ASYNC)
req.cleanup(!node.isLocal());
sendTtlUpdateRequest(expiry);
} | void function( UUID nodeId, GridNearAtomicAbstractUpdateRequest req, UpdateReplyClosure completionCb ) { ClusterNode node = ctx.discovery().node(nodeId); if (node == null) { U.warn(msgLog, STR + STR + req.futureId() + STR + nodeId + ']'); return; } GridNearAtomicUpdateResponse res = new GridNearAtomicUpdateResponse(ctx.cacheId(), nodeId, req.futureId(), req.partition(), false, ctx.deploymentEnabled()); assert !req.returnValue() (req.operation() == TRANSFORM req.size() == 1); GridDhtAtomicAbstractUpdateFuture dhtFut = null; boolean remap = false; String taskName = ctx.kernalContext().task().resolveTaskName(req.taskNameHash()); IgniteCacheExpiryPolicy expiry = null; try { List<GridDhtCacheEntry> locked = null; Collection<IgniteBiTuple<GridDhtCacheEntry, GridCacheVersion>> deleted = null; try { GridDhtPartitionTopology top = topology(); top.readLock(); try { if (top.stopping()) { res.addFailedKeys(req.keys(), new IgniteCheckedException(STR + STR + name())); completionCb.apply(req, res); return; } if (req.topologyLocked() !needRemap(req.topologyVersion(), top.topologyVersion())) { locked = lockEntries(req, req.topologyVersion()); boolean hasNear = ctx.discovery().cacheNearNode(node, name()); GridCacheVersion ver = ctx.versions().next(top.topologyVersion()); if (hasNear) res.nearVersion(ver); if (msgLog.isDebugEnabled()) { msgLog.debug(STR + req.futureId() + STR + ver + ']'); } assert ver != null : STR + req; boolean sndPrevVal = !top.rebalanceFinished(req.topologyVersion()); dhtFut = createDhtFuture(ver, req); expiry = expiryPolicy(req.expiry()); GridCacheReturn retVal = null; if (req.size() > 1 && writeThrough() && !req.skipStore() && !ctx.store().isLocal() && !ctx.dr().receiveEnabled() ) { UpdateBatchResult updRes = updateWithBatch(node, hasNear, req, res, locked, ver, dhtFut, ctx.isDrEnabled(), taskName, expiry, sndPrevVal); deleted = updRes.deleted(); dhtFut = updRes.dhtFuture(); if (req.operation() == TRANSFORM) retVal = updRes.invokeResults(); } else { UpdateSingleResult updRes = updateSingle(node, hasNear, req, res, locked, ver, dhtFut, ctx.isDrEnabled(), taskName, expiry, sndPrevVal); retVal = updRes.returnValue(); deleted = updRes.deleted(); dhtFut = updRes.dhtFuture(); } if (retVal == null) retVal = new GridCacheReturn(ctx, node.isLocal(), true, null, true); res.returnValue(retVal); if (dhtFut != null) ctx.mvcc().addAtomicFuture(dhtFut.id(), dhtFut); } else { remap = true; res.remapTopologyVersion(top.topologyVersion()); } } finally { top.readUnlock(); } } catch (GridCacheEntryRemovedException e) { assert false : STR; e.printStackTrace(); } finally { if (locked != null) unlockEntries(locked, req.topologyVersion()); if (deleted != null) { assert !deleted.isEmpty(); assert ctx.deferredDelete() : this; for (IgniteBiTuple<GridDhtCacheEntry, GridCacheVersion> e : deleted) ctx.onDeferredDelete(e.get1(), e.get2()); } } } catch (GridDhtInvalidPartitionException ignore) { if (log.isDebugEnabled()) log.debug(STR + req); remap = true; res.remapTopologyVersion(ctx.topology().topologyVersion()); } catch (Throwable e) { U.error(log, STR, e); res.addFailedKeys(req.keys(), e); completionCb.apply(req, res); if (e instanceof Error) throw e; return; } if (remap) { assert dhtFut == null; completionCb.apply(req, res); } else if (dhtFut != null) dhtFut.map(node, res.returnValue(), res, completionCb); if (req.writeSynchronizationMode() != FULL_ASYNC) req.cleanup(!node.isLocal()); sendTtlUpdateRequest(expiry); } | /**
* Executes local update after preloader fetched values.
*
* @param nodeId Node ID.
* @param req Update request.
* @param completionCb Completion callback.
*/ | Executes local update after preloader fetched values | updateAllAsyncInternal0 | {
"repo_name": "nivanov/ignite",
"path": "modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicCache.java",
"license": "apache-2.0",
"size": 130370
} | [
"java.util.Collection",
"java.util.List",
"org.apache.ignite.IgniteCheckedException",
"org.apache.ignite.cluster.ClusterNode",
"org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException",
"org.apache.ignite.internal.processors.cache.GridCacheReturn",
"org.apache.ignite.internal.processors.cache.IgniteCacheExpiryPolicy",
"org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtCacheEntry",
"org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtInvalidPartitionException",
"org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionTopology",
"org.apache.ignite.internal.processors.cache.version.GridCacheVersion",
"org.apache.ignite.internal.util.typedef.internal.U",
"org.apache.ignite.lang.IgniteBiTuple"
] | import java.util.Collection; import java.util.List; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException; import org.apache.ignite.internal.processors.cache.GridCacheReturn; import org.apache.ignite.internal.processors.cache.IgniteCacheExpiryPolicy; import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtCacheEntry; import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtInvalidPartitionException; import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionTopology; import org.apache.ignite.internal.processors.cache.version.GridCacheVersion; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteBiTuple; | import java.util.*; import org.apache.ignite.*; import org.apache.ignite.cluster.*; import org.apache.ignite.internal.processors.cache.*; import org.apache.ignite.internal.processors.cache.distributed.dht.*; import org.apache.ignite.internal.processors.cache.version.*; import org.apache.ignite.internal.util.typedef.internal.*; import org.apache.ignite.lang.*; | [
"java.util",
"org.apache.ignite"
] | java.util; org.apache.ignite; | 2,778,972 |
@CanIgnoreReturnValue
default InterruptibleSupplier<Map<SkyKey, ? extends NodeEntry>> createIfAbsentBatchAsync(
@Nullable SkyKey requestor, Reason reason, Iterable<SkyKey> keys) {
return InterruptibleSupplier.Memoize.of(() -> createIfAbsentBatch(requestor, reason, keys));
} | default InterruptibleSupplier<Map<SkyKey, ? extends NodeEntry>> createIfAbsentBatchAsync( @Nullable SkyKey requestor, Reason reason, Iterable<SkyKey> keys) { return InterruptibleSupplier.Memoize.of(() -> createIfAbsentBatch(requestor, reason, keys)); } | /**
* Like {@link QueryableGraph#getBatchAsync}, except it creates a new node for each key not
* already present in the graph. Thus, the returned map will have an entry for each key in {@code
* keys}.
*
* @param requestor if non-{@code null}, the node on behalf of which the given {@code keys} are
* being requested.
* @param reason the reason the nodes are being requested.
*/ | Like <code>QueryableGraph#getBatchAsync</code>, except it creates a new node for each key not already present in the graph. Thus, the returned map will have an entry for each key in keys | createIfAbsentBatchAsync | {
"repo_name": "dropbox/bazel",
"path": "src/main/java/com/google/devtools/build/skyframe/EvaluableGraph.java",
"license": "apache-2.0",
"size": 3165
} | [
"java.util.Map",
"javax.annotation.Nullable"
] | import java.util.Map; import javax.annotation.Nullable; | import java.util.*; import javax.annotation.*; | [
"java.util",
"javax.annotation"
] | java.util; javax.annotation; | 1,428,619 |
@Override
public void setConfiguration(Settings configuration)
{
this.configuration.setValue(configuration);
}
| void function(Settings configuration) { this.configuration.setValue(configuration); } | /**
* Sets the configuration property
*/ | Sets the configuration property | setConfiguration | {
"repo_name": "sensiasoft/lib-sensorml",
"path": "sensorml-core/src/main/java/net/opengis/sensorml/v20/impl/ModeImpl.java",
"license": "mpl-2.0",
"size": 1926
} | [
"net.opengis.sensorml.v20.Settings"
] | import net.opengis.sensorml.v20.Settings; | import net.opengis.sensorml.v20.*; | [
"net.opengis.sensorml"
] | net.opengis.sensorml; | 2,797,906 |
public void addMarker(String tag) {
if (mRequestBirthTime == 0) {
mRequestBirthTime = SystemClock.elapsedRealtime();
}
} | void function(String tag) { if (mRequestBirthTime == 0) { mRequestBirthTime = SystemClock.elapsedRealtime(); } } | /**
* Adds an event to this request's event log; for debugging.
*/ | Adds an event to this request's event log; for debugging | addMarker | {
"repo_name": "jun0813/Telegram-plusplus",
"path": "TMessagesProj/src/main/java/org/telegramsecureplus/android/volley/Request.java",
"license": "gpl-2.0",
"size": 18403
} | [
"android.os.SystemClock"
] | import android.os.SystemClock; | import android.os.*; | [
"android.os"
] | android.os; | 480,316 |
@PUT
@Path("/instances/{vnfId}/grant")
public String grantVnfRes(@Context HttpServletRequest context, @PathParam("vnfId") String vnfId) {
LOG.info("function=grantVnfRes, msg=enter to grant vnf resource");
JSONObject restJson = new JSONObject();
restJson.put(EntityUtils.RESULT_CODE_KEY, Constant.REST_FAIL);
JSONObject compute = StringUtil.getJsonFromContexts(context);
if(null == compute) {
LOG.error("function=grantVnfRes, msg=param request content can't be null!");
restJson.put("data", "param request content can't be null!");
return restJson.toString();
}
JSONObject resultObj = vnfResourceMgr.grantVnfResource(compute, vnfId);
handleResult(resultObj, restJson);
return restJson.toString();
} | @Path(STR) String function(@Context HttpServletRequest context, @PathParam("vnfId") String vnfId) { LOG.info(STR); JSONObject restJson = new JSONObject(); restJson.put(EntityUtils.RESULT_CODE_KEY, Constant.REST_FAIL); JSONObject compute = StringUtil.getJsonFromContexts(context); if(null == compute) { LOG.error(STR); restJson.put("data", STR); return restJson.toString(); } JSONObject resultObj = vnfResourceMgr.grantVnfResource(compute, vnfId); handleResult(resultObj, restJson); return restJson.toString(); } | /**
* Provide function of grant resource.
* <br/>
*JSONObject compute :
* field:(cpu,mem,disk,action(addResource/removeResource))
* @param context
* @param vnfId
* @return
* @since NFVO 0.5
*/ | Provide function of grant resource. JSONObject compute : field:(cpu,mem,disk,action(addResource/removeResource)) | grantVnfRes | {
"repo_name": "open-o/nfvo",
"path": "drivers/vnfm/gvnfm/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/VnfResourceRoa.java",
"license": "apache-2.0",
"size": 3539
} | [
"javax.servlet.http.HttpServletRequest",
"javax.ws.rs.Path",
"javax.ws.rs.PathParam",
"javax.ws.rs.core.Context",
"net.sf.json.JSONObject",
"org.openo.nfvo.jujuvnfmadapter.common.EntityUtils",
"org.openo.nfvo.jujuvnfmadapter.common.StringUtil",
"org.openo.nfvo.jujuvnfmadapter.service.constant.Constant"
] | import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Context; import net.sf.json.JSONObject; import org.openo.nfvo.jujuvnfmadapter.common.EntityUtils; import org.openo.nfvo.jujuvnfmadapter.common.StringUtil; import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; | import javax.servlet.http.*; import javax.ws.rs.*; import javax.ws.rs.core.*; import net.sf.json.*; import org.openo.nfvo.jujuvnfmadapter.common.*; import org.openo.nfvo.jujuvnfmadapter.service.constant.*; | [
"javax.servlet",
"javax.ws",
"net.sf.json",
"org.openo.nfvo"
] | javax.servlet; javax.ws; net.sf.json; org.openo.nfvo; | 181,957 |
private TryPolicyPortTypeProxy createPortProxy() {
final URL WSDL_LOCATION = this.getClass().getClassLoader()
.getResource("TryPolicy.wsdl");
final QName SERVICE = new QName(
"http://acs.samhsa.gov/pep/ws/contract", "TryPolicyService");
final TryPolicyPortTypeProxy port = new TryPolicyService(WSDL_LOCATION,
SERVICE).getTryPolicyServicePort();
return port;
} | TryPolicyPortTypeProxy function() { final URL WSDL_LOCATION = this.getClass().getClassLoader() .getResource(STR); final QName SERVICE = new QName( "http: final TryPolicyPortTypeProxy port = new TryPolicyService(WSDL_LOCATION, SERVICE).getTryPolicyServicePort(); return port; } | /**
* Creates the port.
*
* @return the try policy port type
*/ | Creates the port | createPortProxy | {
"repo_name": "OBHITA/Consent2Share",
"path": "DS4P/access-control-service/pep-try-policy-client/src/main/java/gov/samhsa/acs/trypolicy/wsclient/TryPolicyWebServiceClient.java",
"license": "bsd-3-clause",
"size": 5439
} | [
"gov.samhsa.acs.pep.ws.contract.TryPolicyService",
"javax.xml.namespace.QName"
] | import gov.samhsa.acs.pep.ws.contract.TryPolicyService; import javax.xml.namespace.QName; | import gov.samhsa.acs.pep.ws.contract.*; import javax.xml.namespace.*; | [
"gov.samhsa.acs",
"javax.xml"
] | gov.samhsa.acs; javax.xml; | 2,323,980 |
private static <UK, UV, K, N> Map<UK, UV> getSerializedMap(
InternalKvState<N> kvState,
K key,
TypeSerializer<K> keySerializer,
N namespace,
TypeSerializer<N> namespaceSerializer,
TypeSerializer<UK> userKeySerializer,
TypeSerializer<UV> userValueSerializer
) throws Exception {
byte[] serializedKeyAndNamespace = KvStateRequestSerializer.serializeKeyAndNamespace(
key, keySerializer, namespace, namespaceSerializer);
byte[] serializedValue = kvState.getSerializedValue(serializedKeyAndNamespace);
if (serializedValue == null) {
return null;
} else {
return KvStateRequestSerializer.deserializeMap(serializedValue, userKeySerializer, userValueSerializer);
}
} | static <UK, UV, K, N> Map<UK, UV> function( InternalKvState<N> kvState, K key, TypeSerializer<K> keySerializer, N namespace, TypeSerializer<N> namespaceSerializer, TypeSerializer<UK> userKeySerializer, TypeSerializer<UV> userValueSerializer ) throws Exception { byte[] serializedKeyAndNamespace = KvStateRequestSerializer.serializeKeyAndNamespace( key, keySerializer, namespace, namespaceSerializer); byte[] serializedValue = kvState.getSerializedValue(serializedKeyAndNamespace); if (serializedValue == null) { return null; } else { return KvStateRequestSerializer.deserializeMap(serializedValue, userKeySerializer, userValueSerializer); } } | /**
* Returns the value by getting the serialized value and deserializing it
* if it is not null.
*/ | Returns the value by getting the serialized value and deserializing it if it is not null | getSerializedMap | {
"repo_name": "zohar-mizrahi/flink",
"path": "flink-runtime/src/test/java/org/apache/flink/runtime/state/StateBackendTestBase.java",
"license": "apache-2.0",
"size": 101791
} | [
"java.util.Map",
"org.apache.flink.api.common.typeutils.TypeSerializer",
"org.apache.flink.runtime.query.netty.message.KvStateRequestSerializer",
"org.apache.flink.runtime.state.internal.InternalKvState"
] | import java.util.Map; import org.apache.flink.api.common.typeutils.TypeSerializer; import org.apache.flink.runtime.query.netty.message.KvStateRequestSerializer; import org.apache.flink.runtime.state.internal.InternalKvState; | import java.util.*; import org.apache.flink.api.common.typeutils.*; import org.apache.flink.runtime.query.netty.message.*; import org.apache.flink.runtime.state.internal.*; | [
"java.util",
"org.apache.flink"
] | java.util; org.apache.flink; | 2,887,739 |
public static final String constructFilenameForTable(Table table,
String fileNonce,
SnapshotFormat format,
int hostId)
{
String extension = ".vpt";
if (format == SnapshotFormat.CSV) {
extension = ".csv";
}
StringBuilder filename_builder = new StringBuilder(fileNonce);
filename_builder.append("-");
filename_builder.append(table.getTypeName());
if (!table.getIsreplicated())
{
filename_builder.append("-host_");
filename_builder.append(hostId);
}
filename_builder.append(extension);//Volt partitioned table
return filename_builder.toString();
} | static final String function(Table table, String fileNonce, SnapshotFormat format, int hostId) { String extension = ".vpt"; if (format == SnapshotFormat.CSV) { extension = ".csv"; } StringBuilder filename_builder = new StringBuilder(fileNonce); filename_builder.append("-"); filename_builder.append(table.getTypeName()); if (!table.getIsreplicated()) { filename_builder.append(STR); filename_builder.append(hostId); } filename_builder.append(extension); return filename_builder.toString(); } | /**
* Generates a Filename to the snapshot file for the given table.
* @param table
* @param fileNonce
* @param hostId
*/ | Generates a Filename to the snapshot file for the given table | constructFilenameForTable | {
"repo_name": "eoneil1942/voltdb-4.7fix",
"path": "src/frontend/org/voltdb/sysprocs/saverestore/SnapshotUtil.java",
"license": "agpl-3.0",
"size": 63510
} | [
"org.voltdb.SnapshotFormat",
"org.voltdb.catalog.Table"
] | import org.voltdb.SnapshotFormat; import org.voltdb.catalog.Table; | import org.voltdb.*; import org.voltdb.catalog.*; | [
"org.voltdb",
"org.voltdb.catalog"
] | org.voltdb; org.voltdb.catalog; | 989,173 |
protected Document loadSoapMessage(String messageFile) throws Exception { // NOPMD
final URL messageFileURL = getClass().getClassLoader().getResource(messageFile);
return TestUtils.getXMLDoc(messageFileURL);
} | Document function(String messageFile) throws Exception { final URL messageFileURL = getClass().getClassLoader().getResource(messageFile); return TestUtils.getXMLDoc(messageFileURL); } | /**
* Loads the soap message for the given file as DOM document.
*
* @param messageFile message file located on the classpath
* @return Document response w3c Document
* @throws Exception exception message
*/ | Loads the soap message for the given file as DOM document | loadSoapMessage | {
"repo_name": "NCIP/cacis",
"path": "esd-commons/src/main/java/gov/nih/nci/cacis/common/systest/AbstractJaxWsTest.java",
"license": "bsd-3-clause",
"size": 5520
} | [
"gov.nih.nci.cacis.common.test.TestUtils",
"org.w3c.dom.Document"
] | import gov.nih.nci.cacis.common.test.TestUtils; import org.w3c.dom.Document; | import gov.nih.nci.cacis.common.test.*; import org.w3c.dom.*; | [
"gov.nih.nci",
"org.w3c.dom"
] | gov.nih.nci; org.w3c.dom; | 1,988,725 |
protected void loadChildren()
{
try
{
Database database=getDatabase();
DatabaseSchema defaultSchema=database.getDefaultSchema(project);
if (defaultSchema!=null)
{
insertNode(new SchemasNode(project, database, treeModel));
insertNode(new FunctionsNode(project, database, treeModel));
insertNode(new DataTypesNode(project, database, treeModel));
for (Iterator it=database.getTableTypes(project).iterator(); it.hasNext();)
{
String type=(String)it.next();
insertNode(new TablesNode(project, defaultSchema, type, treeModel));
}
insertNode(new ProceduresNode(project, defaultSchema, treeModel));
}
else insertNode(new InfoNode("No connection established.", InfoNode.ERROR, treeModel));
}
catch (Exception e)
{
e.printStackTrace();
insertNode(new InfoNode(e.getMessage(), InfoNode.ERROR, treeModel));
}
super.loadChildren();
} | void function() { try { Database database=getDatabase(); DatabaseSchema defaultSchema=database.getDefaultSchema(project); if (defaultSchema!=null) { insertNode(new SchemasNode(project, database, treeModel)); insertNode(new FunctionsNode(project, database, treeModel)); insertNode(new DataTypesNode(project, database, treeModel)); for (Iterator it=database.getTableTypes(project).iterator(); it.hasNext();) { String type=(String)it.next(); insertNode(new TablesNode(project, defaultSchema, type, treeModel)); } insertNode(new ProceduresNode(project, defaultSchema, treeModel)); } else insertNode(new InfoNode(STR, InfoNode.ERROR, treeModel)); } catch (Exception e) { e.printStackTrace(); insertNode(new InfoNode(e.getMessage(), InfoNode.ERROR, treeModel)); } super.loadChildren(); } | /**
* Method called to load all child nodes.
*/ | Method called to load all child nodes | loadChildren | {
"repo_name": "xylo/idea-sql-query-plugin",
"path": "src/com/kiwisoft/sqlPlugin/browser/DatabaseNode.java",
"license": "gpl-2.0",
"size": 3032
} | [
"com.kiwisoft.db.Database",
"com.kiwisoft.db.DatabaseSchema",
"com.kiwisoft.utils.gui.inspect.InfoNode",
"java.util.Iterator"
] | import com.kiwisoft.db.Database; import com.kiwisoft.db.DatabaseSchema; import com.kiwisoft.utils.gui.inspect.InfoNode; import java.util.Iterator; | import com.kiwisoft.db.*; import com.kiwisoft.utils.gui.inspect.*; import java.util.*; | [
"com.kiwisoft.db",
"com.kiwisoft.utils",
"java.util"
] | com.kiwisoft.db; com.kiwisoft.utils; java.util; | 1,582,846 |
public String getHtmlUrlSha1() {
if (this.htmlUrlSha1 == null && this.htmlUrl != null) {
this.htmlUrlSha1 = HashUtils.sha1Hex(this.htmlUrl);
}
return this.htmlUrlSha1;
} | String function() { if (this.htmlUrlSha1 == null && this.htmlUrl != null) { this.htmlUrlSha1 = HashUtils.sha1Hex(this.htmlUrl); } return this.htmlUrlSha1; } | /**
* Returns the SHA-1 of the htmlUrl field, if it is available.
*
* @return The SHA-1 of the htmlUrl field, or null if htmlUrl is null.
*/ | Returns the SHA-1 of the htmlUrl field, if it is available | getHtmlUrlSha1 | {
"repo_name": "efsavage/ajah",
"path": "ajah-syndicate/src/main/java/com/ajah/syndicate/FeedEntry.java",
"license": "apache-2.0",
"size": 2258
} | [
"com.ajah.util.data.HashUtils"
] | import com.ajah.util.data.HashUtils; | import com.ajah.util.data.*; | [
"com.ajah.util"
] | com.ajah.util; | 1,772,407 |
public void setLivingAnimations(EntityLivingBase entitylivingbaseIn, float p_78086_2_, float p_78086_3_, float partialTickTime)
{
EntityWolf entitywolf = (EntityWolf)entitylivingbaseIn;
if (entitywolf.isAngry())
{
this.wolfTail.rotateAngleY = 0.0F;
}
else
{
this.wolfTail.rotateAngleY = MathHelper.cos(p_78086_2_ * 0.6662F) * 1.4F * p_78086_3_;
}
if (entitywolf.isSitting())
{
this.wolfMane.setRotationPoint(-1.0F, 16.0F, -3.0F);
this.wolfMane.rotateAngleX = ((float)Math.PI * 2F / 5F);
this.wolfMane.rotateAngleY = 0.0F;
this.wolfBody.setRotationPoint(0.0F, 18.0F, 0.0F);
this.wolfBody.rotateAngleX = ((float)Math.PI / 4F);
this.wolfTail.setRotationPoint(-1.0F, 21.0F, 6.0F);
this.wolfLeg1.setRotationPoint(-2.5F, 22.0F, 2.0F);
this.wolfLeg1.rotateAngleX = ((float)Math.PI * 3F / 2F);
this.wolfLeg2.setRotationPoint(0.5F, 22.0F, 2.0F);
this.wolfLeg2.rotateAngleX = ((float)Math.PI * 3F / 2F);
this.wolfLeg3.rotateAngleX = 5.811947F;
this.wolfLeg3.setRotationPoint(-2.49F, 17.0F, -4.0F);
this.wolfLeg4.rotateAngleX = 5.811947F;
this.wolfLeg4.setRotationPoint(0.51F, 17.0F, -4.0F);
}
else
{
this.wolfBody.setRotationPoint(0.0F, 14.0F, 2.0F);
this.wolfBody.rotateAngleX = ((float)Math.PI / 2F);
this.wolfMane.setRotationPoint(-1.0F, 14.0F, -3.0F);
this.wolfMane.rotateAngleX = this.wolfBody.rotateAngleX;
this.wolfTail.setRotationPoint(-1.0F, 12.0F, 8.0F);
this.wolfLeg1.setRotationPoint(-2.5F, 16.0F, 7.0F);
this.wolfLeg2.setRotationPoint(0.5F, 16.0F, 7.0F);
this.wolfLeg3.setRotationPoint(-2.5F, 16.0F, -4.0F);
this.wolfLeg4.setRotationPoint(0.5F, 16.0F, -4.0F);
this.wolfLeg1.rotateAngleX = MathHelper.cos(p_78086_2_ * 0.6662F) * 1.4F * p_78086_3_;
this.wolfLeg2.rotateAngleX = MathHelper.cos(p_78086_2_ * 0.6662F + (float)Math.PI) * 1.4F * p_78086_3_;
this.wolfLeg3.rotateAngleX = MathHelper.cos(p_78086_2_ * 0.6662F + (float)Math.PI) * 1.4F * p_78086_3_;
this.wolfLeg4.rotateAngleX = MathHelper.cos(p_78086_2_ * 0.6662F) * 1.4F * p_78086_3_;
}
this.wolfHeadMain.rotateAngleZ = entitywolf.getInterestedAngle(partialTickTime) + entitywolf.getShakeAngle(partialTickTime, 0.0F);
this.wolfMane.rotateAngleZ = entitywolf.getShakeAngle(partialTickTime, -0.08F);
this.wolfBody.rotateAngleZ = entitywolf.getShakeAngle(partialTickTime, -0.16F);
this.wolfTail.rotateAngleZ = entitywolf.getShakeAngle(partialTickTime, -0.2F);
} | void function(EntityLivingBase entitylivingbaseIn, float p_78086_2_, float p_78086_3_, float partialTickTime) { EntityWolf entitywolf = (EntityWolf)entitylivingbaseIn; if (entitywolf.isAngry()) { this.wolfTail.rotateAngleY = 0.0F; } else { this.wolfTail.rotateAngleY = MathHelper.cos(p_78086_2_ * 0.6662F) * 1.4F * p_78086_3_; } if (entitywolf.isSitting()) { this.wolfMane.setRotationPoint(-1.0F, 16.0F, -3.0F); this.wolfMane.rotateAngleX = ((float)Math.PI * 2F / 5F); this.wolfMane.rotateAngleY = 0.0F; this.wolfBody.setRotationPoint(0.0F, 18.0F, 0.0F); this.wolfBody.rotateAngleX = ((float)Math.PI / 4F); this.wolfTail.setRotationPoint(-1.0F, 21.0F, 6.0F); this.wolfLeg1.setRotationPoint(-2.5F, 22.0F, 2.0F); this.wolfLeg1.rotateAngleX = ((float)Math.PI * 3F / 2F); this.wolfLeg2.setRotationPoint(0.5F, 22.0F, 2.0F); this.wolfLeg2.rotateAngleX = ((float)Math.PI * 3F / 2F); this.wolfLeg3.rotateAngleX = 5.811947F; this.wolfLeg3.setRotationPoint(-2.49F, 17.0F, -4.0F); this.wolfLeg4.rotateAngleX = 5.811947F; this.wolfLeg4.setRotationPoint(0.51F, 17.0F, -4.0F); } else { this.wolfBody.setRotationPoint(0.0F, 14.0F, 2.0F); this.wolfBody.rotateAngleX = ((float)Math.PI / 2F); this.wolfMane.setRotationPoint(-1.0F, 14.0F, -3.0F); this.wolfMane.rotateAngleX = this.wolfBody.rotateAngleX; this.wolfTail.setRotationPoint(-1.0F, 12.0F, 8.0F); this.wolfLeg1.setRotationPoint(-2.5F, 16.0F, 7.0F); this.wolfLeg2.setRotationPoint(0.5F, 16.0F, 7.0F); this.wolfLeg3.setRotationPoint(-2.5F, 16.0F, -4.0F); this.wolfLeg4.setRotationPoint(0.5F, 16.0F, -4.0F); this.wolfLeg1.rotateAngleX = MathHelper.cos(p_78086_2_ * 0.6662F) * 1.4F * p_78086_3_; this.wolfLeg2.rotateAngleX = MathHelper.cos(p_78086_2_ * 0.6662F + (float)Math.PI) * 1.4F * p_78086_3_; this.wolfLeg3.rotateAngleX = MathHelper.cos(p_78086_2_ * 0.6662F + (float)Math.PI) * 1.4F * p_78086_3_; this.wolfLeg4.rotateAngleX = MathHelper.cos(p_78086_2_ * 0.6662F) * 1.4F * p_78086_3_; } this.wolfHeadMain.rotateAngleZ = entitywolf.getInterestedAngle(partialTickTime) + entitywolf.getShakeAngle(partialTickTime, 0.0F); this.wolfMane.rotateAngleZ = entitywolf.getShakeAngle(partialTickTime, -0.08F); this.wolfBody.rotateAngleZ = entitywolf.getShakeAngle(partialTickTime, -0.16F); this.wolfTail.rotateAngleZ = entitywolf.getShakeAngle(partialTickTime, -0.2F); } | /**
* Used for easily adding entity-dependent animations. The second and third float params here are the same second
* and third as in the setRotationAngles method.
*/ | Used for easily adding entity-dependent animations. The second and third float params here are the same second and third as in the setRotationAngles method | setLivingAnimations | {
"repo_name": "MartyParty21/AwakenDreamsClient",
"path": "mcp/src/minecraft/net/minecraft/client/model/ModelWolf.java",
"license": "gpl-3.0",
"size": 8057
} | [
"net.minecraft.entity.EntityLivingBase",
"net.minecraft.entity.passive.EntityWolf",
"net.minecraft.util.math.MathHelper"
] | import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityWolf; import net.minecraft.util.math.MathHelper; | import net.minecraft.entity.*; import net.minecraft.entity.passive.*; import net.minecraft.util.math.*; | [
"net.minecraft.entity",
"net.minecraft.util"
] | net.minecraft.entity; net.minecraft.util; | 2,269,500 |
protected void performReaction(String selectedReactionID, final boolean noAssignmentRulesFlag, final boolean noConstraintsFlag)
{
// these are sets of things that need to be re-evaluated or tested due
// to the reaction firing
HashSet<AssignmentRule> affectedAssignmentRuleSet = new HashSet<AssignmentRule>();
HashSet<ASTNode> affectedConstraintSet = new HashSet<ASTNode>();
// loop through the reaction's reactants and products and update their
// amounts
for (StringDoublePair speciesAndStoichiometry : reactionToSpeciesAndStoichiometrySetMap.get(selectedReactionID))
{
double stoichiometry = speciesAndStoichiometry.doub;
String speciesID = speciesAndStoichiometry.string;
// this means the stoichiometry isn't constant, so look to the
// variableToValue map
if (reactionToNonconstantStoichiometriesSetMap.containsKey(selectedReactionID))
{
for (StringStringPair doubleID : reactionToNonconstantStoichiometriesSetMap.get(selectedReactionID))
{
// string1 is the species ID; string2 is the
// speciesReference ID
if (doubleID.string1.equals(speciesID))
{
stoichiometry = variableToValueMap.get(doubleID.string2);
// this is to get the plus/minus correct, as the
// variableToValueMap has
// a stoichiometry without the reactant/product
// plus/minus data
stoichiometry *= (int) (speciesAndStoichiometry.doub / Math.abs(speciesAndStoichiometry.doub));
break;
}
}
}
// update the species count if the species isn't a boundary
// condition or constant
// note that the stoichiometries are earlier modified with the
// correct +/- sign
if (speciesToIsBoundaryConditionMap.get(speciesID) == false && variableToIsConstantMap.get(speciesID) == false)
{
if (speciesToConversionFactorMap.containsKey(speciesID))
{
variableToValueMap.adjustValue(speciesID, stoichiometry * variableToValueMap.get(speciesToConversionFactorMap.get(speciesID)));
}
else
{
variableToValueMap.adjustValue(speciesID, stoichiometry);
}
}
// if this variable that was just updated is part of an assignment
// rule (RHS)
// then re-evaluate that assignment rule
if (noAssignmentRulesFlag == false && variableToIsInAssignmentRuleMap.get(speciesID) == true)
{
affectedAssignmentRuleSet.addAll(variableToAffectedAssignmentRuleSetMap.get(speciesID));
}
if (noConstraintsFlag == false && variableToIsInConstraintMap.get(speciesID) == true)
{
affectedConstraintSet.addAll(variableToAffectedConstraintSetMap.get(speciesID));
}
}
if (affectedAssignmentRuleSet.size() > 0)
{
performAssignmentRules(affectedAssignmentRuleSet);
}
if (affectedConstraintSet.size() > 0)
{
if (testConstraints(affectedConstraintSet) == false)
{
constraintFailureFlag = true;
}
}
} | void function(String selectedReactionID, final boolean noAssignmentRulesFlag, final boolean noConstraintsFlag) { HashSet<AssignmentRule> affectedAssignmentRuleSet = new HashSet<AssignmentRule>(); HashSet<ASTNode> affectedConstraintSet = new HashSet<ASTNode>(); for (StringDoublePair speciesAndStoichiometry : reactionToSpeciesAndStoichiometrySetMap.get(selectedReactionID)) { double stoichiometry = speciesAndStoichiometry.doub; String speciesID = speciesAndStoichiometry.string; if (reactionToNonconstantStoichiometriesSetMap.containsKey(selectedReactionID)) { for (StringStringPair doubleID : reactionToNonconstantStoichiometriesSetMap.get(selectedReactionID)) { if (doubleID.string1.equals(speciesID)) { stoichiometry = variableToValueMap.get(doubleID.string2); stoichiometry *= (int) (speciesAndStoichiometry.doub / Math.abs(speciesAndStoichiometry.doub)); break; } } } if (speciesToIsBoundaryConditionMap.get(speciesID) == false && variableToIsConstantMap.get(speciesID) == false) { if (speciesToConversionFactorMap.containsKey(speciesID)) { variableToValueMap.adjustValue(speciesID, stoichiometry * variableToValueMap.get(speciesToConversionFactorMap.get(speciesID))); } else { variableToValueMap.adjustValue(speciesID, stoichiometry); } } if (noAssignmentRulesFlag == false && variableToIsInAssignmentRuleMap.get(speciesID) == true) { affectedAssignmentRuleSet.addAll(variableToAffectedAssignmentRuleSetMap.get(speciesID)); } if (noConstraintsFlag == false && variableToIsInConstraintMap.get(speciesID) == true) { affectedConstraintSet.addAll(variableToAffectedConstraintSetMap.get(speciesID)); } } if (affectedAssignmentRuleSet.size() > 0) { performAssignmentRules(affectedAssignmentRuleSet); } if (affectedConstraintSet.size() > 0) { if (testConstraints(affectedConstraintSet) == false) { constraintFailureFlag = true; } } } | /**
* updates reactant/product species counts based on their stoichiometries
*
* @param selectedReactionID
* the reaction to perform
*/ | updates reactant/product species counts based on their stoichiometries | performReaction | {
"repo_name": "MyersResearchGroup/iBioSim",
"path": "analysis/src/main/java/edu/utah/ece/async/ibiosim/analysis/simulation/flattened/Simulator.java",
"license": "apache-2.0",
"size": 210548
} | [
"java.util.HashSet",
"org.sbml.jsbml.ASTNode",
"org.sbml.jsbml.AssignmentRule"
] | import java.util.HashSet; import org.sbml.jsbml.ASTNode; import org.sbml.jsbml.AssignmentRule; | import java.util.*; import org.sbml.jsbml.*; | [
"java.util",
"org.sbml.jsbml"
] | java.util; org.sbml.jsbml; | 1,940,898 |
public final int numberOfActionButtons() {
int number = 0;
if (mBuilder.positiveText != null && positiveButton.getVisibility() == View.VISIBLE)
number++;
if (mBuilder.neutralText != null && neutralButton.getVisibility() == View.VISIBLE)
number++;
if (mBuilder.negativeText != null && negativeButton.getVisibility() == View.VISIBLE)
number++;
return number;
} | final int function() { int number = 0; if (mBuilder.positiveText != null && positiveButton.getVisibility() == View.VISIBLE) number++; if (mBuilder.neutralText != null && neutralButton.getVisibility() == View.VISIBLE) number++; if (mBuilder.negativeText != null && negativeButton.getVisibility() == View.VISIBLE) number++; return number; } | /**
* Gets the number of visible action buttons.
*
* @return 0 through 3, depending on how many should be or are visible.
*/ | Gets the number of visible action buttons | numberOfActionButtons | {
"repo_name": "huhu/material-dialogs",
"path": "library/src/main/java/com/afollestad/materialdialogs/MaterialDialog.java",
"license": "mit",
"size": 68144
} | [
"android.view.View"
] | import android.view.View; | import android.view.*; | [
"android.view"
] | android.view; | 1,317,339 |
public static java.util.Set extractSch_ProfileSet(ims.domain.ILightweightDomainFactory domainFactory, ims.scheduling.vo.ProfileLiteForBookingRightsVoCollection voCollection)
{
return extractSch_ProfileSet(domainFactory, voCollection, null, new HashMap());
}
| static java.util.Set function(ims.domain.ILightweightDomainFactory domainFactory, ims.scheduling.vo.ProfileLiteForBookingRightsVoCollection voCollection) { return extractSch_ProfileSet(domainFactory, voCollection, null, new HashMap()); } | /**
* Create the ims.scheduling.domain.objects.Sch_Profile set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/ | Create the ims.scheduling.domain.objects.Sch_Profile set from the value object collection | extractSch_ProfileSet | {
"repo_name": "FreudianNM/openMAXIMS",
"path": "Source Library/openmaxims_workspace/ValueObjects/src/ims/scheduling/vo/domain/ProfileLiteForBookingRightsVoAssembler.java",
"license": "agpl-3.0",
"size": 16902
} | [
"java.util.HashMap"
] | import java.util.HashMap; | import java.util.*; | [
"java.util"
] | java.util; | 1,877,010 |
@Test
public void testFindEveryTask(PrintWriter out) throws Exception {
TaskStatus<?> status = scheduler.schedule((Runnable) new DBIncrementTask("testFindEveryTaskId"), 68, TimeUnit.HOURS);
List<Long> taskIds = scheduler.findTaskIds(null, null, TaskState.ANY, true, null, null);
if (!taskIds.contains(status.getTaskId()))
throw new Exception("Task id for " + status + " not found in list of all: " + taskIds);
// remove every task, but then roll back
tran.begin();
try {
int numRemoved = scheduler.remove(null, null, TaskState.ANY, true);
if (numRemoved < 1)
throw new Exception("At least one task " + status + " should have been removed. " + numRemoved);
} finally {
tran.rollback();
}
List<TaskStatus<?>> statusList = scheduler.findTaskStatus(null, null, TaskState.ANY, true, null, null);
if (!statusList.contains(status))
throw new Exception(status + " not found in list of all: " + statusList);
List<TimerStatus<?>> timerStatusList = ((TimersPersistentExecutor) scheduler).findTimerStatus("schedtest", null, null, TaskState.ANY, true, null, null);
if (!timerStatusList.contains(status))
throw new Exception(status + " not found in list of all timer status: " + statusList);
} | void function(PrintWriter out) throws Exception { TaskStatus<?> status = scheduler.schedule((Runnable) new DBIncrementTask(STR), 68, TimeUnit.HOURS); List<Long> taskIds = scheduler.findTaskIds(null, null, TaskState.ANY, true, null, null); if (!taskIds.contains(status.getTaskId())) throw new Exception(STR + status + STR + taskIds); tran.begin(); try { int numRemoved = scheduler.remove(null, null, TaskState.ANY, true); if (numRemoved < 1) throw new Exception(STR + status + STR + numRemoved); } finally { tran.rollback(); } List<TaskStatus<?>> statusList = scheduler.findTaskStatus(null, null, TaskState.ANY, true, null, null); if (!statusList.contains(status)) throw new Exception(status + STR + statusList); List<TimerStatus<?>> timerStatusList = ((TimersPersistentExecutor) scheduler).findTimerStatus(STR, null, null, TaskState.ANY, true, null, null); if (!timerStatusList.contains(status)) throw new Exception(status + STR + statusList); } | /**
* Find every task for this application that is in the persistent store.
*/ | Find every task for this application that is in the persistent store | testFindEveryTask | {
"repo_name": "kgibm/open-liberty",
"path": "dev/com.ibm.ws.concurrent.persistent_fat/test-applications/schedtest/src/web/SchedulerFATServlet.java",
"license": "epl-1.0",
"size": 196518
} | [
"com.ibm.websphere.concurrent.persistent.TaskState",
"com.ibm.websphere.concurrent.persistent.TaskStatus",
"com.ibm.ws.concurrent.persistent.ejb.TimerStatus",
"com.ibm.ws.concurrent.persistent.ejb.TimersPersistentExecutor",
"java.io.PrintWriter",
"java.util.List",
"java.util.concurrent.TimeUnit"
] | import com.ibm.websphere.concurrent.persistent.TaskState; import com.ibm.websphere.concurrent.persistent.TaskStatus; import com.ibm.ws.concurrent.persistent.ejb.TimerStatus; import com.ibm.ws.concurrent.persistent.ejb.TimersPersistentExecutor; import java.io.PrintWriter; import java.util.List; import java.util.concurrent.TimeUnit; | import com.ibm.websphere.concurrent.persistent.*; import com.ibm.ws.concurrent.persistent.ejb.*; import java.io.*; import java.util.*; import java.util.concurrent.*; | [
"com.ibm.websphere",
"com.ibm.ws",
"java.io",
"java.util"
] | com.ibm.websphere; com.ibm.ws; java.io; java.util; | 2,398,505 |
private class InternalMouseListener extends MouseAdapter {
private void maybeShowPopup(final MouseEvent event) {
if (event.isPopupTrigger()) {
final JPopupMenu menu = new JPopupMenu();
menu.add(new CopyLogAction(m_textArea));
menu.show(event.getComponent(), event.getX(), event.getY());
}
} | class InternalMouseListener extends MouseAdapter { private void function(final MouseEvent event) { if (event.isPopupTrigger()) { final JPopupMenu menu = new JPopupMenu(); menu.add(new CopyLogAction(m_textArea)); menu.show(event.getComponent(), event.getX(), event.getY()); } } | /**
* Shows a popup menu depending on the mouse event.
*
* @param event The mouse event.
*/ | Shows a popup menu depending on the mouse event | maybeShowPopup | {
"repo_name": "mayl8822/binnavi",
"path": "src/main/java/com/google/security/zynamics/binnavi/Gui/plugins/output/CPluginOutputDialog.java",
"license": "apache-2.0",
"size": 6056
} | [
"java.awt.event.MouseAdapter",
"java.awt.event.MouseEvent",
"javax.swing.JPopupMenu"
] | import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JPopupMenu; | import java.awt.event.*; import javax.swing.*; | [
"java.awt",
"javax.swing"
] | java.awt; javax.swing; | 203,035 |
public List<? extends CalendarDayContract> getDays();
| List<? extends CalendarDayContract> function(); | /**
* The list of CalendarDay object the CalendarWeek is associated with
*
* <p>
* days of a CalendarWeek
* </p>
*
* @return days of CalendarWeek
*/ | The list of CalendarDay object the CalendarWeek is associated with days of a CalendarWeek | getDays | {
"repo_name": "kuali/kpme",
"path": "core/api/src/main/java/org/kuali/kpme/core/api/calendar/web/CalendarWeekContract.java",
"license": "apache-2.0",
"size": 1050
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 2,439,556 |
public long advanceTime( long amount, TimeUnit unit ); | long function( long amount, TimeUnit unit ); | /**
* Advances the clock time in the specified unit amount.
*
* @param amount the amount of units to advance in the clock
* @param unit the used time unit
* @return the current absolute timestamp
*/ | Advances the clock time in the specified unit amount | advanceTime | {
"repo_name": "amckee23/drools",
"path": "drools-core/src/main/java/org/drools/core/time/SessionPseudoClock.java",
"license": "apache-2.0",
"size": 1320
} | [
"java.util.concurrent.TimeUnit"
] | import java.util.concurrent.TimeUnit; | import java.util.concurrent.*; | [
"java.util"
] | java.util; | 2,866,589 |
public boolean contains(Item item) {
return stream().filter(Objects::nonNull)
.anyMatch(i -> i.getId() == item.getId() && i.getAmount() >= item.getAmount());
} | boolean function(Item item) { return stream().filter(Objects::nonNull) .anyMatch(i -> i.getId() == item.getId() && i.getAmount() >= item.getAmount()); } | /**
* Determines if this container contains {@code item}.
*
* @param item the item to check this container for.
* @return {@code true} if this container contains the item, {@code false} otherwise.
*/ | Determines if this container contains item | contains | {
"repo_name": "Vult-R/Astraeus-Java-Framework",
"path": "src/main/java/com/astraeus/game/world/entity/item/ItemContainer.java",
"license": "gpl-3.0",
"size": 23104
} | [
"java.util.Objects"
] | import java.util.Objects; | import java.util.*; | [
"java.util"
] | java.util; | 290,627 |
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof AbstractCategoryItemRenderer)) {
return false;
}
AbstractCategoryItemRenderer that = (AbstractCategoryItemRenderer) obj;
if (!ObjectUtilities.equal(this.itemLabelGeneratorList,
that.itemLabelGeneratorList)) {
return false;
}
if (!ObjectUtilities.equal(this.defaultItemLabelGenerator,
that.defaultItemLabelGenerator)) {
return false;
}
if (!ObjectUtilities.equal(this.toolTipGeneratorList,
that.toolTipGeneratorList)) {
return false;
}
if (!ObjectUtilities.equal(this.defaultToolTipGenerator,
that.defaultToolTipGenerator)) {
return false;
}
if (!ObjectUtilities.equal(this.itemURLGeneratorList,
that.itemURLGeneratorList)) {
return false;
}
if (!ObjectUtilities.equal(this.defaultItemURLGenerator,
that.defaultItemURLGenerator)) {
return false;
}
if (!ObjectUtilities.equal(this.legendItemLabelGenerator,
that.legendItemLabelGenerator)) {
return false;
}
if (!ObjectUtilities.equal(this.legendItemToolTipGenerator,
that.legendItemToolTipGenerator)) {
return false;
}
if (!ObjectUtilities.equal(this.legendItemURLGenerator,
that.legendItemURLGenerator)) {
return false;
}
return super.equals(obj);
} | boolean function(Object obj) { if (obj == this) { return true; } if (!(obj instanceof AbstractCategoryItemRenderer)) { return false; } AbstractCategoryItemRenderer that = (AbstractCategoryItemRenderer) obj; if (!ObjectUtilities.equal(this.itemLabelGeneratorList, that.itemLabelGeneratorList)) { return false; } if (!ObjectUtilities.equal(this.defaultItemLabelGenerator, that.defaultItemLabelGenerator)) { return false; } if (!ObjectUtilities.equal(this.toolTipGeneratorList, that.toolTipGeneratorList)) { return false; } if (!ObjectUtilities.equal(this.defaultToolTipGenerator, that.defaultToolTipGenerator)) { return false; } if (!ObjectUtilities.equal(this.itemURLGeneratorList, that.itemURLGeneratorList)) { return false; } if (!ObjectUtilities.equal(this.defaultItemURLGenerator, that.defaultItemURLGenerator)) { return false; } if (!ObjectUtilities.equal(this.legendItemLabelGenerator, that.legendItemLabelGenerator)) { return false; } if (!ObjectUtilities.equal(this.legendItemToolTipGenerator, that.legendItemToolTipGenerator)) { return false; } if (!ObjectUtilities.equal(this.legendItemURLGenerator, that.legendItemURLGenerator)) { return false; } return super.equals(obj); } | /**
* Tests this renderer for equality with another object.
*
* @param obj the object.
*
* @return <code>true</code> or <code>false</code>.
*/ | Tests this renderer for equality with another object | equals | {
"repo_name": "akardapolov/ASH-Viewer",
"path": "jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/AbstractCategoryItemRenderer.java",
"license": "gpl-3.0",
"size": 66756
} | [
"org.jfree.chart.util.ObjectUtilities"
] | import org.jfree.chart.util.ObjectUtilities; | import org.jfree.chart.util.*; | [
"org.jfree.chart"
] | org.jfree.chart; | 2,446,332 |
private JPanel createHeader() {
JPanel header = new JPanel(new BorderLayout());
header.setBorder(new EmptyBorder(0, 0, 0, 0));
JLabel headerIcon = new JLabel();
headerIcon.setIcon(new ImageIcon(new ImageIcon(Dropzone.class.getResource("/images/settings.png")).getImage()
.getScaledInstance(400, 210, Image.SCALE_SMOOTH)));
header.add(headerIcon, BorderLayout.NORTH);
JLabel area = new JLabel();
area.setForeground(Color.DARK_GRAY);
final String s = "<html>" + (I18n.get("settings.infotext")) + "</html>";
area.setText(s);
JPanel infoWrapperPanel = new JPanel();
infoWrapperPanel.setLayout(new BoxLayout(infoWrapperPanel, BoxLayout.Y_AXIS));
JPanel topSpacerPanel = new JPanel();
JPanel bottomSpacerPanel = new JPanel();
JPanel infoTextPanel = new JPanel(new BorderLayout());
infoTextPanel.setBorder(new EmptyBorder(0, 10, 10, 0));
infoTextPanel.setPreferredSize(getPreferredSize(s, true, 400));
infoTextPanel.add(area, BorderLayout.NORTH);
infoWrapperPanel.add(topSpacerPanel);
infoWrapperPanel.add(infoTextPanel);
infoWrapperPanel.add(bottomSpacerPanel);
header.add(infoWrapperPanel, BorderLayout.SOUTH);
return header;
} | JPanel function() { JPanel header = new JPanel(new BorderLayout()); header.setBorder(new EmptyBorder(0, 0, 0, 0)); JLabel headerIcon = new JLabel(); headerIcon.setIcon(new ImageIcon(new ImageIcon(Dropzone.class.getResource(STR)).getImage() .getScaledInstance(400, 210, Image.SCALE_SMOOTH))); header.add(headerIcon, BorderLayout.NORTH); JLabel area = new JLabel(); area.setForeground(Color.DARK_GRAY); final String s = STR + (I18n.get(STR)) + STR; area.setText(s); JPanel infoWrapperPanel = new JPanel(); infoWrapperPanel.setLayout(new BoxLayout(infoWrapperPanel, BoxLayout.Y_AXIS)); JPanel topSpacerPanel = new JPanel(); JPanel bottomSpacerPanel = new JPanel(); JPanel infoTextPanel = new JPanel(new BorderLayout()); infoTextPanel.setBorder(new EmptyBorder(0, 10, 10, 0)); infoTextPanel.setPreferredSize(getPreferredSize(s, true, 400)); infoTextPanel.add(area, BorderLayout.NORTH); infoWrapperPanel.add(topSpacerPanel); infoWrapperPanel.add(infoTextPanel); infoWrapperPanel.add(bottomSpacerPanel); header.add(infoWrapperPanel, BorderLayout.SOUTH); return header; } | /**
* Creates the header of the settings dialog
*
* @return
*/ | Creates the header of the settings dialog | createHeader | {
"repo_name": "michaelnetter/sds-dropzone",
"path": "src/main/java/org/mn/dropzone/SettingsDialog.java",
"license": "mit",
"size": 11197
} | [
"java.awt.BorderLayout",
"java.awt.Color",
"java.awt.Image",
"javax.swing.BoxLayout",
"javax.swing.ImageIcon",
"javax.swing.JLabel",
"javax.swing.JPanel",
"javax.swing.border.EmptyBorder",
"org.mn.dropzone.i18n.I18n"
] | import java.awt.BorderLayout; import java.awt.Color; import java.awt.Image; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import org.mn.dropzone.i18n.I18n; | import java.awt.*; import javax.swing.*; import javax.swing.border.*; import org.mn.dropzone.i18n.*; | [
"java.awt",
"javax.swing",
"org.mn.dropzone"
] | java.awt; javax.swing; org.mn.dropzone; | 799,987 |
public static List<DataFile> getDataFiles(Connection conn,
Properties appConfig, List<Long> ids)
throws DatabaseException, MissingParamException, RecordNotFoundException {
MissingParam.checkMissing(conn, "conn");
MissingParam.checkMissing(appConfig, "appConfig");
MissingParam.checkMissing(ids, "ids");
List<DataFile> files = new ArrayList<DataFile>(ids.size());
PreparedStatement stmt = null;
ResultSet records = null;
try {
stmt = conn.prepareStatement(
DatabaseUtils.makeInStatementSql(GET_FILENAME_QUERY, ids.size()));
for (int i = 0; i < ids.size(); i++) {
stmt.setLong(i + 1, ids.get(i));
}
records = stmt.executeQuery();
while (records.next()) {
files
.add(makeDataFile(records, appConfig.getProperty("filestore"), conn));
}
} catch (SQLException e) {
throw new DatabaseException("Error while getting files", e);
} finally {
DatabaseUtils.closeResultSets(records);
DatabaseUtils.closeStatements(stmt);
}
if (files.size() != ids.size()) {
throw new RecordNotFoundException("Could not locate all files");
}
return files;
} | static List<DataFile> function(Connection conn, Properties appConfig, List<Long> ids) throws DatabaseException, MissingParamException, RecordNotFoundException { MissingParam.checkMissing(conn, "conn"); MissingParam.checkMissing(appConfig, STR); MissingParam.checkMissing(ids, "ids"); List<DataFile> files = new ArrayList<DataFile>(ids.size()); PreparedStatement stmt = null; ResultSet records = null; try { stmt = conn.prepareStatement( DatabaseUtils.makeInStatementSql(GET_FILENAME_QUERY, ids.size())); for (int i = 0; i < ids.size(); i++) { stmt.setLong(i + 1, ids.get(i)); } records = stmt.executeQuery(); while (records.next()) { files .add(makeDataFile(records, appConfig.getProperty(STR), conn)); } } catch (SQLException e) { throw new DatabaseException(STR, e); } finally { DatabaseUtils.closeResultSets(records); DatabaseUtils.closeStatements(stmt); } if (files.size() != ids.size()) { throw new RecordNotFoundException(STR); } return files; } | /**
* Get the {@link DataFile} objects for a set of files
*
* @param conn
* A datbase connection
* @param appConfig
* The application configuration
* @param ids
* The file ids
* @return The DataFile objects
* @throws MissingParamException
* If any of the parameters are missing
* @throws DatabaseException
* If an error occurs during the search
* @throws RecordNotFoundException
* If any files are not in the database
*/ | Get the <code>DataFile</code> objects for a set of files | getDataFiles | {
"repo_name": "squaregoldfish/QuinCe",
"path": "WebApp/src/uk/ac/exeter/QuinCe/data/Files/DataFileDB.java",
"license": "gpl-3.0",
"size": 38666
} | [
"java.sql.Connection",
"java.sql.PreparedStatement",
"java.sql.ResultSet",
"java.sql.SQLException",
"java.util.ArrayList",
"java.util.List",
"java.util.Properties",
"uk.ac.exeter.QuinCe"
] | import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import uk.ac.exeter.QuinCe; | import java.sql.*; import java.util.*; import uk.ac.exeter.*; | [
"java.sql",
"java.util",
"uk.ac.exeter"
] | java.sql; java.util; uk.ac.exeter; | 1,612,338 |
public AbstractThrowableAssert<?, ? extends Throwable> getFailure() {
hasFailed();
return assertThat(this.startupFailure);
} | AbstractThrowableAssert<?, ? extends Throwable> function() { hasFailed(); return assertThat(this.startupFailure); } | /**
* Obtain the failure that stopped the application context from running, the failure
* becoming the object under test.
* <p>
* Example: <pre class="code">
* assertThat(context).getFailure().containsMessage("missing bean");
* </pre>
* @return assertions on the cause of the failure
* @throws AssertionError if the application context started without a failure
*/ | Obtain the failure that stopped the application context from running, the failure becoming the object under test. Example: assertThat(context).getFailure().containsMessage("missing bean"); </code> | getFailure | {
"repo_name": "shakuzen/spring-boot",
"path": "spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssert.java",
"license": "apache-2.0",
"size": 21274
} | [
"org.assertj.core.api.AbstractThrowableAssert",
"org.assertj.core.api.Assertions"
] | import org.assertj.core.api.AbstractThrowableAssert; import org.assertj.core.api.Assertions; | import org.assertj.core.api.*; | [
"org.assertj.core"
] | org.assertj.core; | 591,658 |
@Test
public void testStreamingPipelineFailsIfException() throws Exception {
options.setStreaming(true);
Pipeline pipeline = TestPipeline.create(options);
PCollection<Integer> pc = pipeline.apply(Create.of(1, 2, 3));
PAssert.that(pc).containsInAnyOrder(1, 2, 3);
DataflowPipelineJob mockJob = Mockito.mock(DataflowPipelineJob.class);
when(mockJob.getState()).thenReturn(State.RUNNING);
when(mockJob.getProjectId()).thenReturn("test-project");
when(mockJob.getJobId()).thenReturn("test-job");
when(mockJob.waitUntilFinish(any(Duration.class), any(JobMessagesHandler.class)))
.thenAnswer(
invocation -> {
JobMessage message = new JobMessage();
message.setMessageText("FooException");
message.setTime(TimeUtil.toCloudTime(Instant.now()));
message.setMessageImportance("JOB_MESSAGE_ERROR");
((JobMessagesHandler) invocation.getArguments()[1]).process(Arrays.asList(message));
return State.CANCELLED;
});
DataflowRunner mockRunner = Mockito.mock(DataflowRunner.class);
when(mockRunner.run(any(Pipeline.class))).thenReturn(mockJob);
when(mockClient.getJobMetrics(anyString()))
.thenReturn(generateMockMetricResponse(false , true ));
TestDataflowRunner runner = TestDataflowRunner.fromOptionsAndClient(options, mockClient);
expectedException.expect(RuntimeException.class);
runner.run(pipeline, mockRunner);
} | void function() throws Exception { options.setStreaming(true); Pipeline pipeline = TestPipeline.create(options); PCollection<Integer> pc = pipeline.apply(Create.of(1, 2, 3)); PAssert.that(pc).containsInAnyOrder(1, 2, 3); DataflowPipelineJob mockJob = Mockito.mock(DataflowPipelineJob.class); when(mockJob.getState()).thenReturn(State.RUNNING); when(mockJob.getProjectId()).thenReturn(STR); when(mockJob.getJobId()).thenReturn(STR); when(mockJob.waitUntilFinish(any(Duration.class), any(JobMessagesHandler.class))) .thenAnswer( invocation -> { JobMessage message = new JobMessage(); message.setMessageText(STR); message.setTime(TimeUtil.toCloudTime(Instant.now())); message.setMessageImportance(STR); ((JobMessagesHandler) invocation.getArguments()[1]).process(Arrays.asList(message)); return State.CANCELLED; }); DataflowRunner mockRunner = Mockito.mock(DataflowRunner.class); when(mockRunner.run(any(Pipeline.class))).thenReturn(mockJob); when(mockClient.getJobMetrics(anyString())) .thenReturn(generateMockMetricResponse(false , true )); TestDataflowRunner runner = TestDataflowRunner.fromOptionsAndClient(options, mockClient); expectedException.expect(RuntimeException.class); runner.run(pipeline, mockRunner); } | /**
* Tests that if a streaming pipeline crash loops for a non-assertion reason that the test run
* throws an {@link AssertionError}.
*
* <p>This is a known limitation/bug of the runner that it does not distinguish the two modes of
* failure.
*/ | Tests that if a streaming pipeline crash loops for a non-assertion reason that the test run throws an <code>AssertionError</code>. This is a known limitation/bug of the runner that it does not distinguish the two modes of failure | testStreamingPipelineFailsIfException | {
"repo_name": "mxm/incubator-beam",
"path": "runners/google-cloud-dataflow-java/src/test/java/org/apache/beam/runners/dataflow/TestDataflowRunnerTest.java",
"license": "apache-2.0",
"size": 27594
} | [
"com.google.api.services.dataflow.model.JobMessage",
"java.util.Arrays",
"org.apache.beam.runners.dataflow.util.MonitoringUtil",
"org.apache.beam.runners.dataflow.util.TimeUtil",
"org.apache.beam.sdk.Pipeline",
"org.apache.beam.sdk.PipelineResult",
"org.apache.beam.sdk.testing.PAssert",
"org.apache.beam.sdk.testing.TestPipeline",
"org.apache.beam.sdk.transforms.Create",
"org.apache.beam.sdk.values.PCollection",
"org.joda.time.Duration",
"org.joda.time.Instant",
"org.mockito.Matchers",
"org.mockito.Mockito"
] | import com.google.api.services.dataflow.model.JobMessage; import java.util.Arrays; import org.apache.beam.runners.dataflow.util.MonitoringUtil; import org.apache.beam.runners.dataflow.util.TimeUtil; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.PipelineResult; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.values.PCollection; import org.joda.time.Duration; import org.joda.time.Instant; import org.mockito.Matchers; import org.mockito.Mockito; | import com.google.api.services.dataflow.model.*; import java.util.*; import org.apache.beam.runners.dataflow.util.*; import org.apache.beam.sdk.*; import org.apache.beam.sdk.testing.*; import org.apache.beam.sdk.transforms.*; import org.apache.beam.sdk.values.*; import org.joda.time.*; import org.mockito.*; | [
"com.google.api",
"java.util",
"org.apache.beam",
"org.joda.time",
"org.mockito"
] | com.google.api; java.util; org.apache.beam; org.joda.time; org.mockito; | 1,185,821 |
public void loadPage( long pageNumber, int paginationType,
IContentEmitter emitter ) throws BirtException; | void function( long pageNumber, int paginationType, IContentEmitter emitter ) throws BirtException; | /**
* load the page from the content stream and output it to the emitter
*
* @param pageNumber
* @param paginationType
* @param emitter
*/ | load the page from the content stream and output it to the emitter | loadPage | {
"repo_name": "sguan-actuate/birt",
"path": "engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/internal/document/IReportContentLoader.java",
"license": "epl-1.0",
"size": 1997
} | [
"org.eclipse.birt.core.exception.BirtException",
"org.eclipse.birt.report.engine.emitter.IContentEmitter"
] | import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.report.engine.emitter.IContentEmitter; | import org.eclipse.birt.core.exception.*; import org.eclipse.birt.report.engine.emitter.*; | [
"org.eclipse.birt"
] | org.eclipse.birt; | 2,192,482 |
EAttribute getField_InputBehaviour(); | EAttribute getField_InputBehaviour(); | /**
* Returns the meta object for the attribute '{@link com.odcgroup.t24.version.versionDSL.Field#getInputBehaviour <em>Input Behaviour</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Input Behaviour</em>'.
* @see com.odcgroup.t24.version.versionDSL.Field#getInputBehaviour()
* @see #getField()
* @generated
*/ | Returns the meta object for the attribute '<code>com.odcgroup.t24.version.versionDSL.Field#getInputBehaviour Input Behaviour</code>'. | getField_InputBehaviour | {
"repo_name": "debabratahazra/DS",
"path": "designstudio/components/t24/core/com.odcgroup.t24.version.model/src-gen/com/odcgroup/t24/version/versionDSL/VersionDSLPackage.java",
"license": "epl-1.0",
"size": 110395
} | [
"org.eclipse.emf.ecore.EAttribute"
] | import org.eclipse.emf.ecore.EAttribute; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 1,968,040 |
@Test
public void testCustomManifestNoFeature() throws IOException {
String currentValue = null;
try {
String dir = VALUE_PROP_INSTALL_DIR;
currentValue = System.setProperty(KEY_PROP_INSTALL_DIR, dir);
new CustomManifest(new File(VALUE_EXTENSION_JAR_LOCATION + JAR_NO_FEATURE));
fail("IllegalArgumentException should be thrown when the feature manifest file is not found.");
} catch (IllegalArgumentException iae) {
// this is expected.
} finally {
if (currentValue != null) {
System.setProperty(KEY_PROP_INSTALL_DIR, currentValue);
}
}
} | void function() throws IOException { String currentValue = null; try { String dir = VALUE_PROP_INSTALL_DIR; currentValue = System.setProperty(KEY_PROP_INSTALL_DIR, dir); new CustomManifest(new File(VALUE_EXTENSION_JAR_LOCATION + JAR_NO_FEATURE)); fail(STR); } catch (IllegalArgumentException iae) { } finally { if (currentValue != null) { System.setProperty(KEY_PROP_INSTALL_DIR, currentValue); } } } | /**
* Test CustomManifest constructor with the invalid data.
*
* @throws IOException
*/ | Test CustomManifest constructor with the invalid data | testCustomManifestNoFeature | {
"repo_name": "OpenLiberty/open-liberty",
"path": "dev/com.ibm.ws.crypto.passwordutil/test/com/ibm/ws/crypto/util/custom/CustomManifestTest.java",
"license": "epl-1.0",
"size": 9818
} | [
"java.io.File",
"java.io.IOException",
"org.junit.Assert"
] | import java.io.File; import java.io.IOException; import org.junit.Assert; | import java.io.*; import org.junit.*; | [
"java.io",
"org.junit"
] | java.io; org.junit; | 915,973 |
public X3DNode getFontStyle() {
if ( fontStyle == null ) {
fontStyle = (SFNode)getField( "fontStyle" );
}
return( fontStyle.getValue( ) );
} | X3DNode function() { if ( fontStyle == null ) { fontStyle = (SFNode)getField( STR ); } return( fontStyle.getValue( ) ); } | /** Return the fontStyle X3DNode value.
* @return The fontStyle X3DNode value. */ | Return the fontStyle X3DNode value | getFontStyle | {
"repo_name": "Norkart/NK-VirtualGlobe",
"path": "Xj3D/src/java/org/xj3d/sai/external/node/text/SAIText.java",
"license": "gpl-2.0",
"size": 4992
} | [
"org.web3d.x3d.sai.SFNode",
"org.web3d.x3d.sai.X3DNode"
] | import org.web3d.x3d.sai.SFNode; import org.web3d.x3d.sai.X3DNode; | import org.web3d.x3d.sai.*; | [
"org.web3d.x3d"
] | org.web3d.x3d; | 78,777 |
public RemoteProcessGroupStatus getRemoteProcessGroupStatus(final String remoteProcessGroupId) {
final ProcessGroup root = getRootGroup();
final RemoteProcessGroup remoteProcessGroup = root.findRemoteProcessGroup(remoteProcessGroupId);
// ensure the output port was found
if (remoteProcessGroup == null) {
throw new ResourceNotFoundException(String.format("Unable to locate remote process group with id '%s'.", remoteProcessGroupId));
}
final String groupId = remoteProcessGroup.getProcessGroup().getIdentifier();
final ProcessGroupStatus groupStatus = flowController.getEventAccess().getGroupStatus(groupId, NiFiUserUtils.getNiFiUser(), 1);
if (groupStatus == null) {
throw new ResourceNotFoundException(String.format("Unable to locate group with id '%s'.", groupId));
}
final RemoteProcessGroupStatus status = groupStatus.getRemoteProcessGroupStatus().stream().filter(rpgStatus -> remoteProcessGroupId.equals(rpgStatus.getId())).findFirst().orElse(null);
if (status == null) {
throw new ResourceNotFoundException(String.format("Unable to locate remote process group with id '%s'.", remoteProcessGroupId));
}
return status;
} | RemoteProcessGroupStatus function(final String remoteProcessGroupId) { final ProcessGroup root = getRootGroup(); final RemoteProcessGroup remoteProcessGroup = root.findRemoteProcessGroup(remoteProcessGroupId); if (remoteProcessGroup == null) { throw new ResourceNotFoundException(String.format(STR, remoteProcessGroupId)); } final String groupId = remoteProcessGroup.getProcessGroup().getIdentifier(); final ProcessGroupStatus groupStatus = flowController.getEventAccess().getGroupStatus(groupId, NiFiUserUtils.getNiFiUser(), 1); if (groupStatus == null) { throw new ResourceNotFoundException(String.format(STR, groupId)); } final RemoteProcessGroupStatus status = groupStatus.getRemoteProcessGroupStatus().stream().filter(rpgStatus -> remoteProcessGroupId.equals(rpgStatus.getId())).findFirst().orElse(null); if (status == null) { throw new ResourceNotFoundException(String.format(STR, remoteProcessGroupId)); } return status; } | /**
* Gets the status for the specified remote process group.
*
* @param remoteProcessGroupId remote process group id
* @return the status for the specified remote process group
*/ | Gets the status for the specified remote process group | getRemoteProcessGroupStatus | {
"repo_name": "jtstorck/nifi",
"path": "nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/controller/ControllerFacade.java",
"license": "apache-2.0",
"size": 74706
} | [
"org.apache.nifi.authorization.user.NiFiUserUtils",
"org.apache.nifi.controller.status.ProcessGroupStatus",
"org.apache.nifi.controller.status.RemoteProcessGroupStatus",
"org.apache.nifi.groups.ProcessGroup",
"org.apache.nifi.groups.RemoteProcessGroup",
"org.apache.nifi.web.ResourceNotFoundException"
] | import org.apache.nifi.authorization.user.NiFiUserUtils; import org.apache.nifi.controller.status.ProcessGroupStatus; import org.apache.nifi.controller.status.RemoteProcessGroupStatus; import org.apache.nifi.groups.ProcessGroup; import org.apache.nifi.groups.RemoteProcessGroup; import org.apache.nifi.web.ResourceNotFoundException; | import org.apache.nifi.authorization.user.*; import org.apache.nifi.controller.status.*; import org.apache.nifi.groups.*; import org.apache.nifi.web.*; | [
"org.apache.nifi"
] | org.apache.nifi; | 1,628,312 |
Boolean isUnique();
class DataType<D> {
public static final DataType<String> STRING = new DataType<>(String.class.getName(), Schema.ConceptProperty.VALUE_STRING);
public static final DataType<Boolean> BOOLEAN = new DataType<>(Boolean.class.getName(), Schema.ConceptProperty.VALUE_BOOLEAN);
public static final DataType<Long> LONG = new DataType<>(Long.class.getName(), Schema.ConceptProperty.VALUE_LONG);
public static final DataType<Double> DOUBLE = new DataType<>(Double.class.getName(), Schema.ConceptProperty.VALUE_DOUBLE);
public static final ImmutableMap<String, DataType<?>> SUPPORTED_TYPES = ImmutableMap.of(
STRING.getName(), STRING,
BOOLEAN.getName(), BOOLEAN,
LONG.getName(), LONG,
DOUBLE.getName(), DOUBLE,
Integer.class.getName(), LONG
);
private final String dataType;
private final Schema.ConceptProperty conceptProperty;
private DataType(String dataType, Schema.ConceptProperty conceptProperty){
this.dataType = dataType;
this.conceptProperty = conceptProperty;
} | Boolean isUnique(); class DataType<D> { public static final DataType<String> STRING = new DataType<>(String.class.getName(), Schema.ConceptProperty.VALUE_STRING); public static final DataType<Boolean> BOOLEAN = new DataType<>(Boolean.class.getName(), Schema.ConceptProperty.VALUE_BOOLEAN); public static final DataType<Long> LONG = new DataType<>(Long.class.getName(), Schema.ConceptProperty.VALUE_LONG); public static final DataType<Double> DOUBLE = new DataType<>(Double.class.getName(), Schema.ConceptProperty.VALUE_DOUBLE); public static final ImmutableMap<String, DataType<?>> SUPPORTED_TYPES = ImmutableMap.of( STRING.getName(), STRING, BOOLEAN.getName(), BOOLEAN, LONG.getName(), LONG, DOUBLE.getName(), DOUBLE, Integer.class.getName(), LONG ); private final String dataType; private final Schema.ConceptProperty conceptProperty; private DataType(String dataType, Schema.ConceptProperty conceptProperty){ this.dataType = dataType; this.conceptProperty = conceptProperty; } | /**
* Returns whether the ResourceType is unique.
*
* @return True if the ResourceType is unique and its instances are limited to one connection to an entity
*/ | Returns whether the ResourceType is unique | isUnique | {
"repo_name": "mikonapoli/grakn",
"path": "grakn-core/src/main/java/ai/grakn/concept/ResourceType.java",
"license": "gpl-3.0",
"size": 7241
} | [
"ai.grakn.util.Schema",
"com.google.common.collect.ImmutableMap"
] | import ai.grakn.util.Schema; import com.google.common.collect.ImmutableMap; | import ai.grakn.util.*; import com.google.common.collect.*; | [
"ai.grakn.util",
"com.google.common"
] | ai.grakn.util; com.google.common; | 680,095 |
private static int getNumDocs(LeafReader reader, Query roleQuery, BitSet roleQueryBits) throws IOException, ExecutionException {
IndexReader.CacheHelper cacheHelper = reader.getReaderCacheHelper(); // this one takes deletes into account
if (cacheHelper == null) {
return computeNumDocs(reader, roleQueryBits);
}
final boolean[] added = new boolean[] { false };
Cache<Query, Integer> perReaderCache = NUM_DOCS_CACHE.computeIfAbsent(cacheHelper.getKey(),
key -> {
added[0] = true;
return CacheBuilder.<Query, Integer>builder()
// Not configurable, this limit only exists so that if a role query is updated
// then we won't risk OOME because of old role queries that are not used anymore
.setMaximumWeight(1000)
.weigher((k, v) -> 1) // just count
.build();
});
if (added[0]) {
IndexReader.ClosedListener closedListener = NUM_DOCS_CACHE::remove;
try {
cacheHelper.addClosedListener(closedListener);
} catch (AlreadyClosedException e) {
closedListener.onClose(cacheHelper.getKey());
throw e;
}
}
return perReaderCache.computeIfAbsent(roleQuery, q -> computeNumDocs(reader, roleQueryBits));
}
public static final class DocumentSubsetDirectoryReader extends FilterDirectoryReader {
private final Query roleQuery;
private final DocumentSubsetBitsetCache bitsetCache; | static int function(LeafReader reader, Query roleQuery, BitSet roleQueryBits) throws IOException, ExecutionException { IndexReader.CacheHelper cacheHelper = reader.getReaderCacheHelper(); if (cacheHelper == null) { return computeNumDocs(reader, roleQueryBits); } final boolean[] added = new boolean[] { false }; Cache<Query, Integer> perReaderCache = NUM_DOCS_CACHE.computeIfAbsent(cacheHelper.getKey(), key -> { added[0] = true; return CacheBuilder.<Query, Integer>builder() .setMaximumWeight(1000) .weigher((k, v) -> 1) .build(); }); if (added[0]) { IndexReader.ClosedListener closedListener = NUM_DOCS_CACHE::remove; try { cacheHelper.addClosedListener(closedListener); } catch (AlreadyClosedException e) { closedListener.onClose(cacheHelper.getKey()); throw e; } } return perReaderCache.computeIfAbsent(roleQuery, q -> computeNumDocs(reader, roleQueryBits)); } public static final class DocumentSubsetDirectoryReader extends FilterDirectoryReader { private final Query roleQuery; private final DocumentSubsetBitsetCache bitsetCache; | /**
* Like {@link #computeNumDocs} but caches results.
*/ | Like <code>#computeNumDocs</code> but caches results | getNumDocs | {
"repo_name": "ern/elasticsearch",
"path": "x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/accesscontrol/DocumentSubsetReader.java",
"license": "apache-2.0",
"size": 9719
} | [
"java.io.IOException",
"java.util.concurrent.ExecutionException",
"org.apache.lucene.index.FilterDirectoryReader",
"org.apache.lucene.index.IndexReader",
"org.apache.lucene.index.LeafReader",
"org.apache.lucene.search.Query",
"org.apache.lucene.store.AlreadyClosedException",
"org.apache.lucene.util.BitSet",
"org.elasticsearch.common.cache.Cache",
"org.elasticsearch.common.cache.CacheBuilder"
] | import java.io.IOException; import java.util.concurrent.ExecutionException; import org.apache.lucene.index.FilterDirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.LeafReader; import org.apache.lucene.search.Query; import org.apache.lucene.store.AlreadyClosedException; import org.apache.lucene.util.BitSet; import org.elasticsearch.common.cache.Cache; import org.elasticsearch.common.cache.CacheBuilder; | import java.io.*; import java.util.concurrent.*; import org.apache.lucene.index.*; import org.apache.lucene.search.*; import org.apache.lucene.store.*; import org.apache.lucene.util.*; import org.elasticsearch.common.cache.*; | [
"java.io",
"java.util",
"org.apache.lucene",
"org.elasticsearch.common"
] | java.io; java.util; org.apache.lucene; org.elasticsearch.common; | 2,186,675 |
public final void setFirstRowRef(final Cell pfirstRowRef) {
this.getSerialFirstRowRef().setCell(pfirstRowRef);
}
| final void function(final Cell pfirstRowRef) { this.getSerialFirstRowRef().setCell(pfirstRowRef); } | /**
* Sets the first row ref.
*
* @param pfirstRowRef
* the new first row ref
*/ | Sets the first row ref | setFirstRowRef | {
"repo_name": "tiefaces/TieFaces",
"path": "src/org/tiefaces/components/websheet/configuration/ConfigRangeAttrs.java",
"license": "mit",
"size": 6029
} | [
"org.apache.poi.ss.usermodel.Cell"
] | import org.apache.poi.ss.usermodel.Cell; | import org.apache.poi.ss.usermodel.*; | [
"org.apache.poi"
] | org.apache.poi; | 2,828,718 |
private void markLoginSiteNode(SiteNode sn) {
// No need for resetting everything up if it's already the right node
if (this.markedLoginSiteNode == sn) {
return;
}
if (this.markedLoginSiteNode != null) {
this.markedLoginSiteNode.removeCustomIcon(LOGIN_ICON_RESOURCE);
}
this.markedLoginSiteNode = sn;
if (sn == null) {
return;
}
sn.addCustomIcon(LOGIN_ICON_RESOURCE, false);
} | void function(SiteNode sn) { if (this.markedLoginSiteNode == sn) { return; } if (this.markedLoginSiteNode != null) { this.markedLoginSiteNode.removeCustomIcon(LOGIN_ICON_RESOURCE); } this.markedLoginSiteNode = sn; if (sn == null) { return; } sn.addCustomIcon(LOGIN_ICON_RESOURCE, false); } | /**
* Marks the provided Site Login as being a Login request. If {@code null} is provided, no
* site node will be marked as login request (for the {@link Context} corresponding to this
* AuthenticationMethod).
*
* @param sn the new login site node
*/ | Marks the provided Site Login as being a Login request. If null is provided, no site node will be marked as login request (for the <code>Context</code> corresponding to this AuthenticationMethod) | markLoginSiteNode | {
"repo_name": "gmaran23/zaproxy",
"path": "zap/src/main/java/org/zaproxy/zap/authentication/PostBasedAuthenticationMethodType.java",
"license": "apache-2.0",
"size": 68833
} | [
"org.parosproxy.paros.model.SiteNode"
] | import org.parosproxy.paros.model.SiteNode; | import org.parosproxy.paros.model.*; | [
"org.parosproxy.paros"
] | org.parosproxy.paros; | 514,879 |
@Override
public void createMacronutrients(MacrosEntity macronutrientsDto)
{
this.save(macronutrientsDto);
} | void function(MacrosEntity macronutrientsDto) { this.save(macronutrientsDto); } | /**
* <h1>createMacronutrients</h1>
* <p>Elemto que agrega un elemto a la base detos</p>
*
* @param macronutrientsDto Objeto que agrega un nuevo elemento a la base de datos
*/ | createMacronutrients Elemto que agrega un elemto a la base detos | createMacronutrients | {
"repo_name": "tomas-93/My-Macros",
"path": "Repository/src/main/java/com/mymacros/repository/dao/implement/database/MacronutrientsDataBaseImplementDao.java",
"license": "apache-2.0",
"size": 2659
} | [
"com.mymacros.database.entity.MacrosEntity"
] | import com.mymacros.database.entity.MacrosEntity; | import com.mymacros.database.entity.*; | [
"com.mymacros.database"
] | com.mymacros.database; | 803,136 |
protected Arrow createArrow(float pos, float spanSize, float displayScale) {
Arrow arrow = new Arrow();
//attachChild(arrow);
Matrix3f matrix = new Matrix3f();
matrix.fromStartEndVectors(Vector3f.UNIT_Z, Vector3f.UNIT_Y.negate());
arrow.setLocalRotation(matrix);
float arrowScale = DisplayConstants.getInstance().getDistributedArrowSize();
arrow.setSize(.2f * arrowScale, 0.5f, .075f * arrowScale);
//arrow.setSize(.1f, 0.5f, .05f);
float height = displayScale * getTarget().getDistributedForce().getCurveValue(pos);
arrow.setLength(height);
arrow.setLocalTranslation(spanSize * (pos - .5f), height, 0);
return arrow;
} | Arrow function(float pos, float spanSize, float displayScale) { Arrow arrow = new Arrow(); Matrix3f matrix = new Matrix3f(); matrix.fromStartEndVectors(Vector3f.UNIT_Z, Vector3f.UNIT_Y.negate()); arrow.setLocalRotation(matrix); float arrowScale = DisplayConstants.getInstance().getDistributedArrowSize(); arrow.setSize(.2f * arrowScale, 0.5f, .075f * arrowScale); float height = displayScale * getTarget().getDistributedForce().getCurveValue(pos); arrow.setLength(height); arrow.setLocalTranslation(spanSize * (pos - .5f), height, 0); return arrow; } | /**
* This method should create the arrow in the correct position and scale.
* @param pos a number ranging from 0 to 1, denoting the percentage along the span to create the arrow.
*/ | This method should create the arrow in the correct position and scale | createArrow | {
"repo_name": "jogjayr/InTEL-Project",
"path": "Statics/src/edu/gatech/statics/modes/distributed/objects/DistributedForceRepresentation.java",
"license": "gpl-3.0",
"size": 8703
} | [
"com.jme.math.Matrix3f",
"com.jme.math.Vector3f",
"edu.gatech.statics.exercise.DisplayConstants",
"edu.gatech.statics.objects.representations.Arrow"
] | import com.jme.math.Matrix3f; import com.jme.math.Vector3f; import edu.gatech.statics.exercise.DisplayConstants; import edu.gatech.statics.objects.representations.Arrow; | import com.jme.math.*; import edu.gatech.statics.exercise.*; import edu.gatech.statics.objects.representations.*; | [
"com.jme.math",
"edu.gatech.statics"
] | com.jme.math; edu.gatech.statics; | 186,012 |
@DataProvider(name = "malformedDurationDataProvider")
public Object[][] malformedDurationDataProvider() {
return new Object[][]{
{"10us"},
{"MicroSeconds"},
{"5"},
{"ten seconds"}
};
} | @DataProvider(name = STR) Object[][] function() { return new Object[][]{ {"10us"}, {STR}, {"5"}, {STR} }; } | /**
* Data provider.
*
* @return Test data.
*/ | Data provider | malformedDurationDataProvider | {
"repo_name": "elasticlib/elasticlib",
"path": "elasticlib-common/src/test/java/org/elasticlib/common/config/ConfigUtilTest.java",
"license": "apache-2.0",
"size": 7816
} | [
"org.testng.annotations.DataProvider"
] | import org.testng.annotations.DataProvider; | import org.testng.annotations.*; | [
"org.testng.annotations"
] | org.testng.annotations; | 1,654,972 |
public static void unregisterMBean(ManagementObject aMBean, Object aMBeanServerO) {
MBeanServer aMBeanServer = (MBeanServer) aMBeanServerO;
if (!jmxAvailable) // means we couldn't find the required classes and methods
{
return;
}
if (aMBeanServer == null) {
if (platformMBeanServer != null) {
aMBeanServer = platformMBeanServer;
} else {
UIMAFramework.getLogger().logrb(Level.CONFIG, JmxMBeanAgent.class.getName(),
"unregisterMBean", LOG_RESOURCE_BUNDLE,
"UIMA_JMX_platform_mbean_server_not_available__CONFIG");
return;
}
}
try {
// Now unregister the MBean.
String mbeanName = aMBean.getUniqueMBeanName();
if (mbeanName != null) // guards against uninitialized AE instances
{
ObjectName objName = new ObjectName(mbeanName);
if (aMBeanServer.isRegistered(objName)) {
aMBeanServer.unregisterMBean(objName);
}
// Object objName = objectNameConstructor.newInstance(new Object[] { mbeanName });
// if (((Boolean) isRegistered.invoke(aMBeanServer, new Object[] { objName
// })).booleanValue()) {
// unregisterMBean.invoke(aMBeanServer, new Object[] { objName });
// }
}
} catch (Exception e) {
// don't fail catastrophically if we can't unregister. Just log a warning and continue.
UIMAFramework.getLogger().logrb(Level.WARNING, JmxMBeanAgent.class.getName(),
"unregisterMBean", LOG_RESOURCE_BUNDLE,
"UIMA_JMX_failed_to_unregister_mbean__WARNING", e);
return;
}
}
// private static Class mbeanServerClass;
//
// private static Class objectNameClass;
// private static Constructor objectNameConstructor;
//
// private static Method isRegistered;
//
// private static Method registerMBean;
//
// private static Method unregisterMBean;
private static boolean jmxAvailable = true;
private static MBeanServer platformMBeanServer;
static {
// try {
// mbeanServerClass = Class.forName("javax.management.MBeanServer");
// objectNameClass = Class.forName("javax.management.ObjectName");
// objectNameConstructor = objectNameClass.getConstructor(new Class[] { String.class });
// isRegistered = mbeanServerClass.getMethod("isRegistered", new Class[] { objectNameClass });
// registerMBean = mbeanServerClass.getMethod("registerMBean", new Class[] { Object.class,
// objectNameClass });
// unregisterMBean = mbeanServerClass.getMethod("unregisterMBean",
// new Class[] { objectNameClass });
// jmxAvailable = true;
// } catch (Exception e) {
// // JMX not available
// jmxAvailable = false;
// }
// try to get platform MBean Server (Java 1.5 only)
// try {
// Class managementFactory = Class.forName("java.lang.management.ManagementFactory");
// Method getPlatformMBeanServer = managementFactory.getMethod("getPlatformMBeanServer",
// new Class[0]);
// platformMBeanServer = getPlatformMBeanServer.invoke(null, null);
// } catch (Exception e) {
// platformMBeanServer = null;
// }
platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
}
private static final String LOG_RESOURCE_BUNDLE = "org.apache.uima.impl.log_messages"; | static void function(ManagementObject aMBean, Object aMBeanServerO) { MBeanServer aMBeanServer = (MBeanServer) aMBeanServerO; if (!jmxAvailable) { return; } if (aMBeanServer == null) { if (platformMBeanServer != null) { aMBeanServer = platformMBeanServer; } else { UIMAFramework.getLogger().logrb(Level.CONFIG, JmxMBeanAgent.class.getName(), STR, LOG_RESOURCE_BUNDLE, STR); return; } } try { String mbeanName = aMBean.getUniqueMBeanName(); if (mbeanName != null) { ObjectName objName = new ObjectName(mbeanName); if (aMBeanServer.isRegistered(objName)) { aMBeanServer.unregisterMBean(objName); } } } catch (Exception e) { UIMAFramework.getLogger().logrb(Level.WARNING, JmxMBeanAgent.class.getName(), STR, LOG_RESOURCE_BUNDLE, STR, e); return; } } private static boolean jmxAvailable = true; private static MBeanServer platformMBeanServer; static { platformMBeanServer = ManagementFactory.getPlatformMBeanServer(); } private static final String LOG_RESOURCE_BUNDLE = STR; | /**
* Unregister an MBean from the MBeanServer.
*
* @param aMBean
* the MBean to register
* @param aMBeanServerO
* server to unregister from. If null, the platform MBeanServer will be used if we are
* running under Java 1.5. Earlier versions of Java did not have a platform MBeanServer;
* in that case, this method will do nothing.
*/ | Unregister an MBean from the MBeanServer | unregisterMBean | {
"repo_name": "apache/uima-uimaj",
"path": "uimaj-core/src/main/java/org/apache/uima/internal/util/JmxMBeanAgent.java",
"license": "apache-2.0",
"size": 7692
} | [
"java.lang.management.ManagementFactory",
"javax.management.MBeanServer",
"javax.management.ObjectName",
"org.apache.uima.UIMAFramework",
"org.apache.uima.resource.ManagementObject",
"org.apache.uima.util.Level"
] | import java.lang.management.ManagementFactory; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.uima.UIMAFramework; import org.apache.uima.resource.ManagementObject; import org.apache.uima.util.Level; | import java.lang.management.*; import javax.management.*; import org.apache.uima.*; import org.apache.uima.resource.*; import org.apache.uima.util.*; | [
"java.lang",
"javax.management",
"org.apache.uima"
] | java.lang; javax.management; org.apache.uima; | 1,570,484 |
@Nonnull
public DeviceConfigurationUserStatusRequestBuilder userStatuses(@Nonnull final String id) {
return new DeviceConfigurationUserStatusRequestBuilder(getRequestUrlWithAdditionalSegment("userStatuses") + "/" + id, getClient(), null);
} | DeviceConfigurationUserStatusRequestBuilder function(@Nonnull final String id) { return new DeviceConfigurationUserStatusRequestBuilder(getRequestUrlWithAdditionalSegment(STR) + "/" + id, getClient(), null); } | /**
* Gets a request builder for the DeviceConfigurationUserStatus item
*
* @return the request builder
* @param id the item identifier
*/ | Gets a request builder for the DeviceConfigurationUserStatus item | userStatuses | {
"repo_name": "microsoftgraph/msgraph-sdk-java",
"path": "src/main/java/com/microsoft/graph/requests/AndroidGeneralDeviceConfigurationRequestBuilder.java",
"license": "mit",
"size": 8027
} | [
"javax.annotation.Nonnull"
] | import javax.annotation.Nonnull; | import javax.annotation.*; | [
"javax.annotation"
] | javax.annotation; | 2,826,572 |
public void readNoUpdate( String path, long fileStartFrame, int numFrames, int bufStartFrame, boolean leaveOpen )
throws IOException
{
readNoUpdate( path, fileStartFrame, numFrames, bufStartFrame, leaveOpen, null );
} | void function( String path, long fileStartFrame, int numFrames, int bufStartFrame, boolean leaveOpen ) throws IOException { readNoUpdate( path, fileStartFrame, numFrames, bufStartFrame, leaveOpen, null ); } | /**
* Reads in frames from a sound file into the buffer, beginning a
* given offset in the buffer. Just like <code>read( String, long, int, int, boolean )</code>
* but without sending
* a <code>/b_query</code>. Hence, the internal fields are not updated
* unless you explicitly call <code>query()</code>.
*
* @param path the path to the sound file
* @param fileStartFrame the frame index in the sound file to start reading from
* @param numFrames the number of frames to read
* a value of <code>-1</code> indicates that as many frames as fit into the buffer
* should be read
* @param bufStartFrame the offset (in frames) in the buffer at which the filling begins
* @param leaveOpen <code>false</code> to close the sound file after reading, <code>true</code> to
* leave it open (as required for a <code>DiskIn</code> UGen). If you leave the file
* open, don't forget to call <code>close</code> on the buffer eventually.
*
* @throws IOException if an error occurs while sending the OSC message
*
* @warning <code>long fileStartFrame</code> is truncated to 32bit by <code>OSCMessage</code> for now
*/ | Reads in frames from a sound file into the buffer, beginning a given offset in the buffer. Just like <code>read( String, long, int, int, boolean )</code> but without sending a <code>/b_query</code>. Hence, the internal fields are not updated unless you explicitly call <code>query()</code> | readNoUpdate | {
"repo_name": "acm-uiuc/Tacchi",
"path": "libs/JCollider/src/de/sciss/jcollider/Buffer.java",
"license": "gpl-2.0",
"size": 89231
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 1,190,367 |
@Override
public RequestDispatcher getNamedDispatcher(String name) {
ServletContext delegatee = getServletContext();
if (delegatee != null) {
return delegatee.getNamedDispatcher(name);
}
return null;
}
// ---------- Resource Access ---------------------------------------------- | RequestDispatcher function(String name) { ServletContext delegatee = getServletContext(); if (delegatee != null) { return delegatee.getNamedDispatcher(name); } return null; } | /**
* Returns a servlet container request dispatcher for the named servlet.
* This method calls on the <code>ServletContext</code> in which the
* {@link SlingMainServlet} is running.
*/ | Returns a servlet container request dispatcher for the named servlet. This method calls on the <code>ServletContext</code> in which the <code>SlingMainServlet</code> is running | getNamedDispatcher | {
"repo_name": "plutext/sling",
"path": "bundles/engine/src/main/java/org/apache/sling/engine/impl/helper/SlingServletContext.java",
"license": "apache-2.0",
"size": 22558
} | [
"javax.servlet.RequestDispatcher",
"javax.servlet.ServletContext"
] | import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; | import javax.servlet.*; | [
"javax.servlet"
] | javax.servlet; | 2,868,805 |
public void allocate ( int length, int errorCode )
{
totalLength = length + 6;
dataLength = length;
position = 5;
packet = new byte[this.totalLength];
Arrays.fill( packet, (byte) PKT_EMPTY );
packet[0] = (byte) PKT_START;
byte[] bLength = ByteConverter.shortTobyte( (short) length );
packet[2] = (byte) errorCode;
packet[3] = bLength[0];
packet[4] = bLength[1];
packet[totalLength - 1] = (byte) PKT_END;
} | void function ( int length, int errorCode ) { totalLength = length + 6; dataLength = length; position = 5; packet = new byte[this.totalLength]; Arrays.fill( packet, (byte) PKT_EMPTY ); packet[0] = (byte) PKT_START; byte[] bLength = ByteConverter.shortTobyte( (short) length ); packet[2] = (byte) errorCode; packet[3] = bLength[0]; packet[4] = bLength[1]; packet[totalLength - 1] = (byte) PKT_END; } | /**
* buffer allocation and set packet frame
*
* @param length the length
* @param errorCode the error code
*/ | buffer allocation and set packet frame | allocate | {
"repo_name": "NeoSmartpen/AndroidSDK2.0",
"path": "NASDK2.0_Studio/app/src/main/java/kr/neolab/sdk/pen/bluetooth/lib/ProtocolParser20.java",
"license": "gpl-3.0",
"size": 53433
} | [
"java.util.Arrays"
] | import java.util.Arrays; | import java.util.*; | [
"java.util"
] | java.util; | 2,900,306 |
static String toStringHeader(ByteBuff buf) throws IOException {
byte[] magicBuf = new byte[Math.min(buf.limit() - buf.position(), BlockType.MAGIC_LENGTH)];
buf.get(magicBuf);
BlockType bt = BlockType.parse(magicBuf, 0, BlockType.MAGIC_LENGTH);
int compressedBlockSizeNoHeader = buf.getInt();
int uncompressedBlockSizeNoHeader = buf.getInt();
long prevBlockOffset = buf.getLong();
byte cksumtype = buf.get();
long bytesPerChecksum = buf.getInt();
long onDiskDataSizeWithHeader = buf.getInt();
return " Header dump: magic: " + Bytes.toString(magicBuf) +
" blockType " + bt +
" compressedBlockSizeNoHeader " +
compressedBlockSizeNoHeader +
" uncompressedBlockSizeNoHeader " +
uncompressedBlockSizeNoHeader +
" prevBlockOffset " + prevBlockOffset +
" checksumType " + ChecksumType.codeToType(cksumtype) +
" bytesPerChecksum " + bytesPerChecksum +
" onDiskDataSizeWithHeader " + onDiskDataSizeWithHeader;
} | static String toStringHeader(ByteBuff buf) throws IOException { byte[] magicBuf = new byte[Math.min(buf.limit() - buf.position(), BlockType.MAGIC_LENGTH)]; buf.get(magicBuf); BlockType bt = BlockType.parse(magicBuf, 0, BlockType.MAGIC_LENGTH); int compressedBlockSizeNoHeader = buf.getInt(); int uncompressedBlockSizeNoHeader = buf.getInt(); long prevBlockOffset = buf.getLong(); byte cksumtype = buf.get(); long bytesPerChecksum = buf.getInt(); long onDiskDataSizeWithHeader = buf.getInt(); return STR + Bytes.toString(magicBuf) + STR + bt + STR + compressedBlockSizeNoHeader + STR + uncompressedBlockSizeNoHeader + STR + prevBlockOffset + STR + ChecksumType.codeToType(cksumtype) + STR + bytesPerChecksum + STR + onDiskDataSizeWithHeader; } | /**
* Convert the contents of the block header into a human readable string.
* This is mostly helpful for debugging. This assumes that the block
* has minor version > 0.
*/ | Convert the contents of the block header into a human readable string. This is mostly helpful for debugging. This assumes that the block has minor version > 0 | toStringHeader | {
"repo_name": "juwi/hbase",
"path": "hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/HFileBlock.java",
"license": "apache-2.0",
"size": 76522
} | [
"java.io.IOException",
"org.apache.hadoop.hbase.nio.ByteBuff",
"org.apache.hadoop.hbase.util.Bytes",
"org.apache.hadoop.hbase.util.ChecksumType"
] | import java.io.IOException; import org.apache.hadoop.hbase.nio.ByteBuff; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.ChecksumType; | import java.io.*; import org.apache.hadoop.hbase.nio.*; import org.apache.hadoop.hbase.util.*; | [
"java.io",
"org.apache.hadoop"
] | java.io; org.apache.hadoop; | 2,078,783 |
public void setInitialReplayIdMap(Map<String, Integer> initialReplayIdMap) {
this.initialReplayIdMap = initialReplayIdMap;
} | void function(Map<String, Integer> initialReplayIdMap) { this.initialReplayIdMap = initialReplayIdMap; } | /**
* Replay IDs to start from per channel name.
*/ | Replay IDs to start from per channel name | setInitialReplayIdMap | {
"repo_name": "ssharma/camel",
"path": "components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/SalesforceEndpointConfig.java",
"license": "apache-2.0",
"size": 23040
} | [
"java.util.Map"
] | import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 795,307 |
public FutureResult<Void> exportCsv(final Report report, final OutputStream output) {
notNull(report, "report");
return exportCsv(report, new ExecuteReport(report), output);
} | FutureResult<Void> function(final Report report, final OutputStream output) { notNull(report, STR); return exportCsv(report, new ExecuteReport(report), output); } | /**
* Export the given Report using the raw export (without columns/rows limitations)
* @param report report
* @param output output
* @return polling result
* @throws ExportException in case export fails
*/ | Export the given Report using the raw export (without columns/rows limitations) | exportCsv | {
"repo_name": "standevgd/gooddata-java",
"path": "src/main/java/com/gooddata/export/ExportService.java",
"license": "bsd-3-clause",
"size": 12740
} | [
"com.gooddata.FutureResult",
"com.gooddata.md.report.Report",
"com.gooddata.util.Validate",
"java.io.OutputStream"
] | import com.gooddata.FutureResult; import com.gooddata.md.report.Report; import com.gooddata.util.Validate; import java.io.OutputStream; | import com.gooddata.*; import com.gooddata.md.report.*; import com.gooddata.util.*; import java.io.*; | [
"com.gooddata",
"com.gooddata.md",
"com.gooddata.util",
"java.io"
] | com.gooddata; com.gooddata.md; com.gooddata.util; java.io; | 564,927 |
public static <T> T configure(Closure configureClosure, T delegate, int resolveStrategy) {
return configure(configureClosure, delegate, resolveStrategy, false);
} | static <T> T function(Closure configureClosure, T delegate, int resolveStrategy) { return configure(configureClosure, delegate, resolveStrategy, false); } | /**
* <p>Configures {@code delegate} with {@code configureClosure}, ignoring the {@link Configurable} interface.</p>
*
* <p>{@code delegate} is set as the delegate of a clone of {@code configureClosure} with a resolve strategy
* of the {@code resolveStrategy} param.</p>
*
* @param configureClosure The configuration closure
* @param delegate The object to be configured
* @param resolveStrategy The resolution strategy to use for the configuration closure
* @return The delegate param
*/ | Configures delegate with configureClosure, ignoring the <code>Configurable</code> interface. delegate is set as the delegate of a clone of configureClosure with a resolve strategy of the resolveStrategy param | configure | {
"repo_name": "cams7/gradle-samples",
"path": "plugin/core/src/main/groovy/org/gradle/util/ConfigureUtil.java",
"license": "gpl-2.0",
"size": 5803
} | [
"groovy.lang.Closure"
] | import groovy.lang.Closure; | import groovy.lang.*; | [
"groovy.lang"
] | groovy.lang; | 2,526,895 |
@NotAuditable
SiteInfo getSite(NodeRef nodeRef);
| SiteInfo getSite(NodeRef nodeRef); | /**
* This method gets the {@link SiteInfo} for the Share Site which contains the given NodeRef.
* If the given NodeRef is not contained within a Share Site, then <code>null</code> is returned.
*
* @param nodeRef the node whose containing site's info is to be found.
* @return SiteInfo site information for the containing site or <code>null</code> if node is not in a site.
*/ | This method gets the <code>SiteInfo</code> for the Share Site which contains the given NodeRef. If the given NodeRef is not contained within a Share Site, then <code>null</code> is returned | getSite | {
"repo_name": "Kast0rTr0y/community-edition",
"path": "projects/repository/source/java/org/alfresco/service/cmr/site/SiteService.java",
"license": "lgpl-3.0",
"size": 23601
} | [
"org.alfresco.service.cmr.repository.NodeRef"
] | import org.alfresco.service.cmr.repository.NodeRef; | import org.alfresco.service.cmr.repository.*; | [
"org.alfresco.service"
] | org.alfresco.service; | 2,235,878 |
protected final ArrayList<MCRMetaClassification> getClassificationsAsMCRMetaClassification(String type) {
return classifications.stream()
.filter(metaLangText -> type.equals(metaLangText.getType()))
.collect(Collectors.toCollection(ArrayList::new));
} | final ArrayList<MCRMetaClassification> function(String type) { return classifications.stream() .filter(metaLangText -> type.equals(metaLangText.getType())) .collect(Collectors.toCollection(ArrayList::new)); } | /**
* This method returns all classification values of the specified type.
*
* @param type
* a type as string.
* @return a list of classification values
*/ | This method returns all classification values of the specified type | getClassificationsAsMCRMetaClassification | {
"repo_name": "MyCoRe-Org/mycore",
"path": "mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectService.java",
"license": "gpl-3.0",
"size": 43222
} | [
"java.util.ArrayList",
"java.util.stream.Collectors"
] | import java.util.ArrayList; import java.util.stream.Collectors; | import java.util.*; import java.util.stream.*; | [
"java.util"
] | java.util; | 1,074,354 |
void setAnalysisResults(Map analysisResults)
{
if (this.analysisResults != null) {
this.analysisResults.clear();
} else {
this.analysisResults = new LinkedHashMap();
}
//this.analysisResults = analysisResults;
//sort the map.
if (analysisResults != null) {
List newList = sorter.sort(analysisResults.keySet());
Iterator i = newList.iterator();
ROIShape shape;
while (i.hasNext()) {
shape = (ROIShape) i.next();
this.analysisResults.put(shape, analysisResults.get(shape));
}
analysisResults.clear();
}
state = MeasurementViewer.READY;
}
Map getAnalysisResults() { return analysisResults; } | void setAnalysisResults(Map analysisResults) { if (this.analysisResults != null) { this.analysisResults.clear(); } else { this.analysisResults = new LinkedHashMap(); } if (analysisResults != null) { List newList = sorter.sort(analysisResults.keySet()); Iterator i = newList.iterator(); ROIShape shape; while (i.hasNext()) { shape = (ROIShape) i.next(); this.analysisResults.put(shape, analysisResults.get(shape)); } analysisResults.clear(); } state = MeasurementViewer.READY; } Map getAnalysisResults() { return analysisResults; } | /**
* Sets the results of an analysis.
*
* @param analysisResults The value to set.
*/ | Sets the results of an analysis | setAnalysisResults | {
"repo_name": "bramalingam/openmicroscopy",
"path": "components/insight/SRC/org/openmicroscopy/shoola/agents/measurement/view/MeasurementViewerModel.java",
"license": "gpl-2.0",
"size": 50321
} | [
"java.util.Iterator",
"java.util.LinkedHashMap",
"java.util.List",
"java.util.Map",
"org.openmicroscopy.shoola.util.roi.model.ROIShape"
] | import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.openmicroscopy.shoola.util.roi.model.ROIShape; | import java.util.*; import org.openmicroscopy.shoola.util.roi.model.*; | [
"java.util",
"org.openmicroscopy.shoola"
] | java.util; org.openmicroscopy.shoola; | 1,753,871 |
public void addCoalescingGroup(List<CoalesceConfig> objects) {
for (CoalesceConfig config : objects) {
mCoalesceObjects.add(config);
mThetaRanges.add(config.spiral.calculateThetaForRadius(config.endProximity));
}
} | void function(List<CoalesceConfig> objects) { for (CoalesceConfig config : objects) { mCoalesceObjects.add(config); mThetaRanges.add(config.spiral.calculateThetaForRadius(config.endProximity)); } } | /**
* Adds a {@link List} of object configurations to the animation at the end of the list.
*
* @param objects {@link List} of {@link CoalesceConfig} The new configurations to add to the animation list.
*/ | Adds a <code>List</code> of object configurations to the animation at the end of the list | addCoalescingGroup | {
"repo_name": "drdaemos/LifeLiveWP",
"path": "rajawali/src/main/java/rajawali/animation/CoalesceAnimation3D.java",
"license": "mit",
"size": 5050
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 962,047 |
private int classifyTestInstance(int index, double example[]) {
double minDist[];
int nearestN[];
double dist;
boolean stop;
double alpha;
int out;
double KNorm;
int result;
nearestN = new int[K];
minDist = new double[K];
for (int i=0; i<K; i++) {
nearestN[i] = 0;
minDist[i] = Double.MAX_VALUE;
}
//KNN Method starts here
for (int i=0; i<trainData.length; i++) {
dist = Util.euclideanDistance(trainData[i],example);
//see if it's nearer than our previous selected neighbors
stop=false;
for(int j=0;j<K && !stop;j++){
if (dist < minDist[j]) {
for (int l = K - 1; l >= j+1; l--) {
minDist[l] = minDist[l - 1];
nearestN[l] = nearestN[l - 1];
}
minDist[j] = dist;
nearestN[j] = i;
stop=true;
}
}
}
//compute inner m_s^q({Cq}) and outter m_s^q(C) arrays
Arrays.fill(inner, 1.0);
Arrays.fill(outter, 1.0);
Arrays.fill(exists, false);
for(int i=0;i<nearestN.length;i++){
out=trainOutput[nearestN[i]];
dist=minDist[i];
exists[out]=true;
alpha=1.0-alphaFunction(dist,out);
inner[out]*=alpha;
outter[out]*=alpha;
}
Arrays.fill(mr, 1.0);
for(int c=0;c<nClasses;c++){
if(exists[c]){
inner[c]=1.0-inner[c];
}
else{
inner[c]=0;
outter[c]=1.0;
}
for(int r=0;r<nClasses;r++){
if(r!=c){
mr[r]*=outter[c];
}
}
}
KNorm=0;
for(int c=0;c<nClasses;c++){
ms[c]=inner[c]*mr[c];
KNorm+=ms[c];
}
KNorm+=mr[0]*outter[0];
for(int c=0;c<nClasses;c++){
ms[c]/=KNorm;
}
result=getMaximum(ms);
return result;
} //end-method
| int function(int index, double example[]) { double minDist[]; int nearestN[]; double dist; boolean stop; double alpha; int out; double KNorm; int result; nearestN = new int[K]; minDist = new double[K]; for (int i=0; i<K; i++) { nearestN[i] = 0; minDist[i] = Double.MAX_VALUE; } for (int i=0; i<trainData.length; i++) { dist = Util.euclideanDistance(trainData[i],example); stop=false; for(int j=0;j<K && !stop;j++){ if (dist < minDist[j]) { for (int l = K - 1; l >= j+1; l--) { minDist[l] = minDist[l - 1]; nearestN[l] = nearestN[l - 1]; } minDist[j] = dist; nearestN[j] = i; stop=true; } } } Arrays.fill(inner, 1.0); Arrays.fill(outter, 1.0); Arrays.fill(exists, false); for(int i=0;i<nearestN.length;i++){ out=trainOutput[nearestN[i]]; dist=minDist[i]; exists[out]=true; alpha=1.0-alphaFunction(dist,out); inner[out]*=alpha; outter[out]*=alpha; } Arrays.fill(mr, 1.0); for(int c=0;c<nClasses;c++){ if(exists[c]){ inner[c]=1.0-inner[c]; } else{ inner[c]=0; outter[c]=1.0; } for(int r=0;r<nClasses;r++){ if(r!=c){ mr[r]*=outter[c]; } } } KNorm=0; for(int c=0;c<nClasses;c++){ ms[c]=inner[c]*mr[c]; KNorm+=ms[c]; } KNorm+=mr[0]*outter[0]; for(int c=0;c<nClasses;c++){ ms[c]/=KNorm; } result=getMaximum(ms); return result; } | /**
* Classifies an instance of the test set
*
* @param index Index of the instance in the test set
* @param example Instance evaluated
* @return class computed
*/ | Classifies an instance of the test set | classifyTestInstance | {
"repo_name": "SCI2SUGR/KEEL",
"path": "src/keel/Algorithms/Fuzzy_Instance_Based_Learning/D_SKNN/D_SKNN.java",
"license": "gpl-3.0",
"size": 12199
} | [
"java.util.Arrays"
] | import java.util.Arrays; | import java.util.*; | [
"java.util"
] | java.util; | 2,746,024 |
String getOneAnnotation( String id ) throws Exception
{
URL url = new URL(id);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Cookie", cookie);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String anns;
while ( (anns = br.readLine()) != null)
sb.append(anns);
br.close();
return sb.toString();
} | String getOneAnnotation( String id ) throws Exception { URL url = new URL(id); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty(STR, cookie); StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader( new InputStreamReader(connection.getInputStream())); String anns; while ( (anns = br.readLine()) != null) sb.append(anns); br.close(); return sb.toString(); } | /**
* Fetch one annotation from the server
* @param id the id (url) of the annotation
* @return the text of the annotation
* @throws Exception
*/ | Fetch one annotation from the server | getOneAnnotation | {
"repo_name": "discoverygarden/calliope",
"path": "src/calliope/annotation/AnnotationService.java",
"license": "gpl-2.0",
"size": 10590
} | [
"java.io.BufferedReader",
"java.io.InputStreamReader",
"java.net.HttpURLConnection"
] | import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; | import java.io.*; import java.net.*; | [
"java.io",
"java.net"
] | java.io; java.net; | 199,450 |
public static boolean isAvailablePackage(Context context, String packageName) {
final PackageManager packageManager = context.getPackageManager();
List<PackageInfo> infoList = packageManager.getInstalledPackages(0);
for (PackageInfo info : infoList) {
if (info.packageName.equalsIgnoreCase(packageName))
return true;
}
return false;
} | static boolean function(Context context, String packageName) { final PackageManager packageManager = context.getPackageManager(); List<PackageInfo> infoList = packageManager.getInstalledPackages(0); for (PackageInfo info : infoList) { if (info.packageName.equalsIgnoreCase(packageName)) return true; } return false; } | /**
* The system contains specified App packageName
*
* @param context Context
* @param packageName App packageName
* @return isAvailable
*/ | The system contains specified App packageName | isAvailablePackage | {
"repo_name": "nuptboyzhb/Genius-Android",
"path": "library/src/main/java/net/qiujuer/genius/util/ToolUtils.java",
"license": "apache-2.0",
"size": 4239
} | [
"android.content.Context",
"android.content.pm.PackageInfo",
"android.content.pm.PackageManager",
"java.util.List"
] | import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import java.util.List; | import android.content.*; import android.content.pm.*; import java.util.*; | [
"android.content",
"java.util"
] | android.content; java.util; | 38,524 |
private NodeRef addForumNode(NodeRef nodeRef)
{
NodeService nodeService = getNodeService();
// //Add discussable aspect to content node
// if (!nodeService.hasAspect(nodeRef, ForumModel.ASPECT_DISCUSSABLE))
// {
// nodeService.addAspect(nodeRef, ForumModel.ASPECT_DISCUSSABLE, null);
// }
//Create forum node and associate it with content node
Map<QName, Serializable> properties = new HashMap<QName, Serializable>(1);
properties.put(ContentModel.PROP_NAME, forumNodeName);
ChildAssociationRef childAssoc = nodeService.createNode(nodeRef, ForumModel.ASSOC_DISCUSSION, ForumModel.ASSOC_DISCUSSION, ForumModel.TYPE_FORUM, properties);
NodeRef forumNode = childAssoc.getChildRef();
//Add necessary aspects to forum node
properties.clear();
properties.put(ApplicationModel.PROP_ICON, "forum");
nodeService.addAspect(forumNode, ApplicationModel.ASPECT_UIFACETS, properties);
return forumNode;
}
| NodeRef function(NodeRef nodeRef) { NodeService nodeService = getNodeService(); Map<QName, Serializable> properties = new HashMap<QName, Serializable>(1); properties.put(ContentModel.PROP_NAME, forumNodeName); ChildAssociationRef childAssoc = nodeService.createNode(nodeRef, ForumModel.ASSOC_DISCUSSION, ForumModel.ASSOC_DISCUSSION, ForumModel.TYPE_FORUM, properties); NodeRef forumNode = childAssoc.getChildRef(); properties.clear(); properties.put(ApplicationModel.PROP_ICON, "forum"); nodeService.addAspect(forumNode, ApplicationModel.ASPECT_UIFACETS, properties); return forumNode; } | /**
* Adds forum node
*
* @param nodeRef Paren node
* @return Reference to created node
*/ | Adds forum node | addForumNode | {
"repo_name": "Alfresco/alfresco-repository",
"path": "src/main/java/org/alfresco/email/server/handler/DocumentEmailMessageHandler.java",
"license": "lgpl-3.0",
"size": 6329
} | [
"java.io.Serializable",
"java.util.HashMap",
"java.util.Map",
"org.alfresco.model.ApplicationModel",
"org.alfresco.model.ContentModel",
"org.alfresco.model.ForumModel",
"org.alfresco.service.cmr.repository.ChildAssociationRef",
"org.alfresco.service.cmr.repository.NodeRef",
"org.alfresco.service.cmr.repository.NodeService",
"org.alfresco.service.namespace.QName"
] | import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.alfresco.model.ApplicationModel; import org.alfresco.model.ContentModel; import org.alfresco.model.ForumModel; import org.alfresco.service.cmr.repository.ChildAssociationRef; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.namespace.QName; | import java.io.*; import java.util.*; import org.alfresco.model.*; import org.alfresco.service.cmr.repository.*; import org.alfresco.service.namespace.*; | [
"java.io",
"java.util",
"org.alfresco.model",
"org.alfresco.service"
] | java.io; java.util; org.alfresco.model; org.alfresco.service; | 1,268,461 |
public LoggingHandler getLog();
| LoggingHandler function(); | /**
* Gets the logging associated with the operator currently working on this IOObject or the
* global log service if no operator was set.
*
* @return the log
*/ | Gets the logging associated with the operator currently working on this IOObject or the global log service if no operator was set | getLog | {
"repo_name": "cm-is-dog/rapidminer-studio-core",
"path": "src/main/java/com/rapidminer/operator/IOObject.java",
"license": "agpl-3.0",
"size": 4929
} | [
"com.rapidminer.tools.LoggingHandler"
] | import com.rapidminer.tools.LoggingHandler; | import com.rapidminer.tools.*; | [
"com.rapidminer.tools"
] | com.rapidminer.tools; | 2,380,965 |
@FormUrlEncoded
@POST("/1.1/statuses/unretweet/{id}.json")
void unretweet(@Path("id") Long id,
@Field("trim_user") Boolean trimUser,
Callback<Tweet> cb); | @POST(STR) void unretweet(@Path("id") Long id, @Field(STR) Boolean trimUser, Callback<Tweet> cb); | /**
* Destroys the retweet specified by the required source Tweet's ID parameter. Returns the
* source Tweet if successful.
*
* @param id (required) The numerical ID of the source Tweet.
* @param trimUser (optional) When set to either true, t or 1, each Tweet returned in a timeline
* will include a user object including only the status authors numerical ID.
* Omit this parameter to receive the complete user object.
* @param cb The callback to invoke when the request completes.
*/ | Destroys the retweet specified by the required source Tweet's ID parameter. Returns the source Tweet if successful | unretweet | {
"repo_name": "rcastro78/twitter-kit-android",
"path": "twitter-core/src/main/java/com/twitter/sdk/android/core/services/StatusesService.java",
"license": "apache-2.0",
"size": 23105
} | [
"com.twitter.sdk.android.core.Callback",
"com.twitter.sdk.android.core.models.Tweet"
] | import com.twitter.sdk.android.core.Callback; import com.twitter.sdk.android.core.models.Tweet; | import com.twitter.sdk.android.core.*; import com.twitter.sdk.android.core.models.*; | [
"com.twitter.sdk"
] | com.twitter.sdk; | 977,607 |
static boolean isConstantDeclaration(
CodingConvention convention, JSDocInfo info, Node node) {
// TODO(b/77597706): Update this method to handle destructured declarations.
if (node.isName() && node.getParent().isConst()) {
return true;
} else if (node.isName()
&& isLhsByDestructuring(node)
&& getRootTarget(node).getGrandparent().isConst()) {
return true;
}
if (info != null && info.isConstant()) {
return true;
}
// TODO(lukes): does this actually care about things inferred to be constants?
if (node.isName() && (node.isDeclaredConstantVar() || node.isInferredConstantVar())) {
return true;
}
switch (node.getToken()) {
case NAME:
return NodeUtil.isConstantByConvention(convention, node);
case GETPROP:
return node.isQualifiedName()
&& NodeUtil.isConstantByConvention(convention, node.getLastChild());
default:
break;
}
return false;
} | static boolean isConstantDeclaration( CodingConvention convention, JSDocInfo info, Node node) { if (node.isName() && node.getParent().isConst()) { return true; } else if (node.isName() && isLhsByDestructuring(node) && getRootTarget(node).getGrandparent().isConst()) { return true; } if (info != null && info.isConstant()) { return true; } if (node.isName() && (node.isDeclaredConstantVar() node.isInferredConstantVar())) { return true; } switch (node.getToken()) { case NAME: return NodeUtil.isConstantByConvention(convention, node); case GETPROP: return node.isQualifiedName() && NodeUtil.isConstantByConvention(convention, node.getLastChild()); default: break; } return false; } | /**
* Temporary function to determine if a node is constant
* in the old or new world. This does not check its inputs
* carefully because it will go away once we switch to the new
* world.
*/ | Temporary function to determine if a node is constant in the old or new world. This does not check its inputs carefully because it will go away once we switch to the new world | isConstantDeclaration | {
"repo_name": "Yannic/closure-compiler",
"path": "src/com/google/javascript/jscomp/NodeUtil.java",
"license": "apache-2.0",
"size": 170457
} | [
"com.google.javascript.rhino.JSDocInfo",
"com.google.javascript.rhino.Node"
] | import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; | import com.google.javascript.rhino.*; | [
"com.google.javascript"
] | com.google.javascript; | 2,364,113 |
public boolean acceptTask() {
return true;
}
protected class RequestServer extends AchieveREResponder {
public RequestServer(Agent_ComputingAgent agent,
MessageTemplate msgTemplate) {
super(agent, msgTemplate);
}
private static final long serialVersionUID = 1074564968341084444L; | boolean function() { return true; } protected class RequestServer extends AchieveREResponder { public RequestServer(Agent_ComputingAgent agent, MessageTemplate msgTemplate) { super(agent, msgTemplate); } private static final long serialVersionUID = 1074564968341084444L; | /**
* Will we accept or refuse the request? (working,
* size of taksFIFO, latency time...)
*/ | Will we accept or refuse the request? (working, size of taksFIFO, latency time...) | acceptTask | {
"repo_name": "tomkren/pikater",
"path": "src/org/pikater/core/agents/experiment/computing/Agent_ComputingAgent.java",
"license": "apache-2.0",
"size": 9270
} | [
"org.pikater.core.ontology.subtrees.management.Agent"
] | import org.pikater.core.ontology.subtrees.management.Agent; | import org.pikater.core.ontology.subtrees.management.*; | [
"org.pikater.core"
] | org.pikater.core; | 1,910,609 |
private
void readGenreFile() throws DataLoaderException {
try (final BufferedReader reader = new BufferedReader(
new FileReader(Globals.GENRE_FILE_PATH));)
{
String line;
line = reader.readLine();
while (line.contains("#")) {
line = reader.readLine();
}
String[] tokens;
while (line != null) {
if (line.trim().startsWith("//")) {
line = reader.readLine();
continue;
}
tokens = line.split(Globals.GENRE_FILE_SEPERATOR);
final FloatArrayList features = new FloatArrayList();
final int itemId = Integer.parseInt(tokens[0]);
if(doNotAddList.contains(itemId)){
line = reader.readLine();
continue;
}
for (int i = 1; i < tokens.length; i++) {
try {
features.add(Float.parseFloat(tokens[i]));
} catch (final NumberFormatException exception) {
LOG.error("Can not convert genre to numbers."
+ exception);
throw exception;
}
}
if (this.dataModel.getItem(itemId) == null) {
final Item item = new Item(itemId);
item.setGenres(features);
this.dataModel.addItem(item);
} else {
this.dataModel.getItem(itemId).setGenres(features);
}
line = reader.readLine();
}
reader.close();
if(!alreadyReduced){
LOG.info("Genre file loaded from "+Globals.GENRE_FILE_PATH);
}
} catch (final Exception exception) {
throw new DataLoaderException("Can not load genre file: " + Globals.GENRE_FILE_PATH, exception);
}
} | void function() throws DataLoaderException { try (final BufferedReader reader = new BufferedReader( new FileReader(Globals.GENRE_FILE_PATH));) { String line; line = reader.readLine(); while (line.contains("#")) { line = reader.readLine(); } String[] tokens; while (line != null) { if (line.trim().startsWith(STRCan not convert genre to numbers.STRGenre file loaded from STRCan not load genre file: " + Globals.GENRE_FILE_PATH, exception); } } | /**
* Reads genre file and parse it. Genres are presented as boolean vector The
* format of genre file should be like this: ItemId,0,1,0,.... which 1 means
* the movie is in the corresponding genre nad 0 means not
* @throws DataLoaderException
*
*/ | Reads genre file and parse it. Genres are presented as boolean vector The format of genre file should be like this: ItemId,0,1,0,.... which 1 means the movie is in the corresponding genre nad 0 means not | readGenreFile | {
"repo_name": "fmoghaddam/RecommendationEngine",
"path": "src/main/java/controller/DataLoader.java",
"license": "mit",
"size": 15475
} | [
"java.io.BufferedReader",
"java.io.FileReader"
] | import java.io.BufferedReader; import java.io.FileReader; | import java.io.*; | [
"java.io"
] | java.io; | 700,632 |
public void closeIfNotShared(Object rcpt) throws IgniteCheckedException {
assert isDone();
synchronized (recipients) {
if (recipients.isEmpty())
return;
recipients.remove(rcpt);
if (recipients.isEmpty())
get().close();
}
} | void function(Object rcpt) throws IgniteCheckedException { assert isDone(); synchronized (recipients) { if (recipients.isEmpty()) return; recipients.remove(rcpt); if (recipients.isEmpty()) get().close(); } } | /**
* Close if this result does not have any other recipients.
*
* @param rcpt ID of the recipient.
* @throws IgniteCheckedException If failed.
*/ | Close if this result does not have any other recipients | closeIfNotShared | {
"repo_name": "a1vanov/ignite",
"path": "modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryManager.java",
"license": "apache-2.0",
"size": 103606
} | [
"org.apache.ignite.IgniteCheckedException"
] | import org.apache.ignite.IgniteCheckedException; | import org.apache.ignite.*; | [
"org.apache.ignite"
] | org.apache.ignite; | 862,175 |
@Override
protected ProcessResult processImpl(SSPHandler sspHandler) {
TestSolution testSolution = TestSolution.NOT_TESTED;
Collection<ProcessRemark> remarkList = new ArrayList<ProcessRemark>();
DefiniteResult result = definiteResultFactory.create(
test,
sspHandler.getSSP().getPage(),
testSolution,
remarkList);
return result;
} | ProcessResult function(SSPHandler sspHandler) { TestSolution testSolution = TestSolution.NOT_TESTED; Collection<ProcessRemark> remarkList = new ArrayList<ProcessRemark>(); DefiniteResult result = definiteResultFactory.create( test, sspHandler.getSSP().getPage(), testSolution, remarkList); return result; } | /**
* Concrete implementation of the 4.22.1 rule.
* @param sspHandler
* @return
* the processResult of the test
*/ | Concrete implementation of the 4.22.1 rule | processImpl | {
"repo_name": "medsob/Tanaguru",
"path": "rules/accessiweb2.1/src/main/java/org/tanaguru/rules/accessiweb21/Aw21Rule04221.java",
"license": "agpl-3.0",
"size": 2382
} | [
"java.util.ArrayList",
"java.util.Collection",
"org.tanaguru.entity.audit.DefiniteResult",
"org.tanaguru.entity.audit.ProcessRemark",
"org.tanaguru.entity.audit.ProcessResult",
"org.tanaguru.entity.audit.TestSolution",
"org.tanaguru.processor.SSPHandler"
] | import java.util.ArrayList; import java.util.Collection; import org.tanaguru.entity.audit.DefiniteResult; import org.tanaguru.entity.audit.ProcessRemark; import org.tanaguru.entity.audit.ProcessResult; import org.tanaguru.entity.audit.TestSolution; import org.tanaguru.processor.SSPHandler; | import java.util.*; import org.tanaguru.entity.audit.*; import org.tanaguru.processor.*; | [
"java.util",
"org.tanaguru.entity",
"org.tanaguru.processor"
] | java.util; org.tanaguru.entity; org.tanaguru.processor; | 1,599,787 |
CompletableFuture<MultipleJobsDetails> requestMultipleJobDetails(@RpcTimeout Time timeout); | CompletableFuture<MultipleJobsDetails> requestMultipleJobDetails(@RpcTimeout Time timeout); | /**
* Requests job details currently being executed on the Flink cluster.
*
* @param timeout for the asynchronous operation
* @return Future containing the job details
*/ | Requests job details currently being executed on the Flink cluster | requestMultipleJobDetails | {
"repo_name": "godfreyhe/flink",
"path": "flink-runtime/src/main/java/org/apache/flink/runtime/webmonitor/RestfulGateway.java",
"license": "apache-2.0",
"size": 10566
} | [
"java.util.concurrent.CompletableFuture",
"org.apache.flink.api.common.time.Time",
"org.apache.flink.runtime.messages.webmonitor.MultipleJobsDetails",
"org.apache.flink.runtime.rpc.RpcTimeout"
] | import java.util.concurrent.CompletableFuture; import org.apache.flink.api.common.time.Time; import org.apache.flink.runtime.messages.webmonitor.MultipleJobsDetails; import org.apache.flink.runtime.rpc.RpcTimeout; | import java.util.concurrent.*; import org.apache.flink.api.common.time.*; import org.apache.flink.runtime.messages.webmonitor.*; import org.apache.flink.runtime.rpc.*; | [
"java.util",
"org.apache.flink"
] | java.util; org.apache.flink; | 1,838,506 |
@Override
public GallicWeight plus(GallicWeight a, GallicWeight b) {
if (isZero(a)) return b;
if (isZero(b)) return a;
if (mode == RESTRICT_GALLIC) {
if (SHORTLEX_ORDERING.compare(a, b) != 0) {
throw new IllegalArgumentException("Trying to plus two different gallic weights, which isn't allowed in " +
"this context. Did you pass a non-functional FST where a functional one was required? a = " + a +
"; b = " + b);
}
double newWeight = this.weightSemiring.plus(a.getWeight(), b.getWeight());
return GallicWeight.create(new IntArrayList(a.getLabels()), newWeight);
} else {
Preconditions.checkState(mode == MIN_GALLIC);
return this.weightSemiring.naturalLess(a.getWeight(), b.getWeight()) ? a : b;
}
} | GallicWeight function(GallicWeight a, GallicWeight b) { if (isZero(a)) return b; if (isZero(b)) return a; if (mode == RESTRICT_GALLIC) { if (SHORTLEX_ORDERING.compare(a, b) != 0) { throw new IllegalArgumentException(STR + STR + a + STR + b); } double newWeight = this.weightSemiring.plus(a.getWeight(), b.getWeight()); return GallicWeight.create(new IntArrayList(a.getLabels()), newWeight); } else { Preconditions.checkState(mode == MIN_GALLIC); return this.weightSemiring.naturalLess(a.getWeight(), b.getWeight()) ? a : b; } } | /**
* gallic plus just delegates to the string semiring plus + the primitive semiring plus
* NOTE this isn't the Union ('general') Gallic Plus from openfst (i have split this out for sanity at the expense of
* elegance).
*/ | gallic plus just delegates to the string semiring plus + the primitive semiring plus NOTE this isn't the Union ('general') Gallic Plus from openfst (i have split this out for sanity at the expense of elegance) | plus | {
"repo_name": "steveash/jopenfst",
"path": "src/main/java/com/github/steveash/jopenfst/semiring/GallicSemiring.java",
"license": "mit",
"size": 12627
} | [
"com.carrotsearch.hppc.IntArrayList",
"com.github.steveash.jopenfst.semiring.GallicSemiring",
"com.google.common.base.Preconditions"
] | import com.carrotsearch.hppc.IntArrayList; import com.github.steveash.jopenfst.semiring.GallicSemiring; import com.google.common.base.Preconditions; | import com.carrotsearch.hppc.*; import com.github.steveash.jopenfst.semiring.*; import com.google.common.base.*; | [
"com.carrotsearch.hppc",
"com.github.steveash",
"com.google.common"
] | com.carrotsearch.hppc; com.github.steveash; com.google.common; | 2,768,649 |
@Test
public void testWang05a() throws IOException
{
List<TextSectionDefinition> sectionDefinitions = Arrays.asList(
new TextSectionDefinition("Titel", x->x.get(0).get(0).getFont().getName().contains("CMBX12"), MultiLine.singleLine, false),
new TextSectionDefinition("Authors", x->x.get(0).get(0).getFont().getName().contains("CMR10"), MultiLine.multiLine, false),
new TextSectionDefinition("Institutions", x->x.get(0).get(0).getFont().getName().contains("CMR9"), MultiLine.multiLine, false),
new TextSectionDefinition("Addresses", x->x.get(0).get(0).getFont().getName().contains("CMTT9"), MultiLine.multiLine, false),
new TextSectionDefinition("Abstract", x->x.get(0).get(0).getFont().getName().contains("CMBX9"), MultiLine.multiLineIntro, false),
new TextSectionDefinition("Section", x->x.get(0).get(0).getFont().getName().contains("CMBX12"), MultiLine.multiLineHeader, true)
);
try ( InputStream resource = getClass().getResourceAsStream("Wang05a.pdf") )
{
PDDocument document = Loader.loadPDF(resource);
PDFTextSectionStripper stripper = new PDFTextSectionStripper(sectionDefinitions);
stripper.getText(document);
System.out.println("Sections:");
List<String> texts = new ArrayList<>();
for (TextSection textSection : stripper.getSections())
{
String text = textSection.toString();
System.out.println(text);
texts.add(text);
}
Files.write(new File(RESULT_FOLDER, "Wang05a.txt").toPath(), texts);
}
} | void function() throws IOException { List<TextSectionDefinition> sectionDefinitions = Arrays.asList( new TextSectionDefinition("Titel", x->x.get(0).get(0).getFont().getName().contains(STR), MultiLine.singleLine, false), new TextSectionDefinition(STR, x->x.get(0).get(0).getFont().getName().contains("CMR10"), MultiLine.multiLine, false), new TextSectionDefinition(STR, x->x.get(0).get(0).getFont().getName().contains("CMR9"), MultiLine.multiLine, false), new TextSectionDefinition(STR, x->x.get(0).get(0).getFont().getName().contains("CMTT9"), MultiLine.multiLine, false), new TextSectionDefinition(STR, x->x.get(0).get(0).getFont().getName().contains("CMBX9"), MultiLine.multiLineIntro, false), new TextSectionDefinition(STR, x->x.get(0).get(0).getFont().getName().contains(STR), MultiLine.multiLineHeader, true) ); try ( InputStream resource = getClass().getResourceAsStream(STR) ) { PDDocument document = Loader.loadPDF(resource); PDFTextSectionStripper stripper = new PDFTextSectionStripper(sectionDefinitions); stripper.getText(document); System.out.println(STR); List<String> texts = new ArrayList<>(); for (TextSection textSection : stripper.getSections()) { String text = textSection.toString(); System.out.println(text); texts.add(text); } Files.write(new File(RESULT_FOLDER, STR).toPath(), texts); } } | /**
* <a href="http://stackoverflow.com/questions/41654518/how-to-read-pdf-departmentsheader-abstract-refrences-with-pdfbox">
* How to read PDF departments(header,abstract,refrences) With PDFBox?
* </a>
* <br/>
* <a href="http://merlot.usc.edu/csac-f06/papers/Wang05a.pdf">
* Wang05a.pdf
* </a>
* <p>
* This test demonstrates a simple framework for extraction of semantic text sections
* which are recognizable by their characteristics of each line alone.
* </p>
*/ | How to read PDF departments(header,abstract,refrences) With PDFBox? Wang05a.pdf This test demonstrates a simple framework for extraction of semantic text sections which are recognizable by their characteristics of each line alone. | testWang05a | {
"repo_name": "mkl-public/testarea-pdfbox2",
"path": "src/test/java/mkl/testarea/pdfbox2/extract/ExtractTextSections.java",
"license": "apache-2.0",
"size": 2943
} | [
"java.io.File",
"java.io.IOException",
"java.io.InputStream",
"java.nio.file.Files",
"java.util.ArrayList",
"java.util.Arrays",
"java.util.List",
"org.apache.pdfbox.Loader",
"org.apache.pdfbox.pdmodel.PDDocument"
] | import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; | import java.io.*; import java.nio.file.*; import java.util.*; import org.apache.pdfbox.*; import org.apache.pdfbox.pdmodel.*; | [
"java.io",
"java.nio",
"java.util",
"org.apache.pdfbox"
] | java.io; java.nio; java.util; org.apache.pdfbox; | 2,278,916 |
@Test
public void testConstructorParams() throws Exception {
// verify construction params
RMQConnectionConfig.Builder builder = new RMQConnectionConfig.Builder();
builder.setHost("hostTest").setPort(999).setUserName("userTest").setPassword("passTest").setVirtualHost("/");
ConstructorTestClass testObj = new ConstructorTestClass(
builder.build(), "queueTest", false, new StringDeserializationScheme());
try {
testObj.open(new Configuration());
} catch (Exception e) {
// connection fails but check if args have been passed correctly
}
assertEquals("hostTest", testObj.getFactory().getHost());
assertEquals(999, testObj.getFactory().getPort());
assertEquals("userTest", testObj.getFactory().getUsername());
assertEquals("passTest", testObj.getFactory().getPassword());
} | void function() throws Exception { RMQConnectionConfig.Builder builder = new RMQConnectionConfig.Builder(); builder.setHost(STR).setPort(999).setUserName(STR).setPassword(STR).setVirtualHost("/"); ConstructorTestClass testObj = new ConstructorTestClass( builder.build(), STR, false, new StringDeserializationScheme()); try { testObj.open(new Configuration()); } catch (Exception e) { } assertEquals(STR, testObj.getFactory().getHost()); assertEquals(999, testObj.getFactory().getPort()); assertEquals(STR, testObj.getFactory().getUsername()); assertEquals(STR, testObj.getFactory().getPassword()); } | /**
* Tests whether constructor params are passed correctly.
*/ | Tests whether constructor params are passed correctly | testConstructorParams | {
"repo_name": "jinglining/flink",
"path": "flink-connectors/flink-connector-rabbitmq/src/test/java/org/apache/flink/streaming/connectors/rabbitmq/RMQSourceTest.java",
"license": "apache-2.0",
"size": 18434
} | [
"org.apache.flink.configuration.Configuration",
"org.apache.flink.streaming.connectors.rabbitmq.common.RMQConnectionConfig",
"org.junit.Assert"
] | import org.apache.flink.configuration.Configuration; import org.apache.flink.streaming.connectors.rabbitmq.common.RMQConnectionConfig; import org.junit.Assert; | import org.apache.flink.configuration.*; import org.apache.flink.streaming.connectors.rabbitmq.common.*; import org.junit.*; | [
"org.apache.flink",
"org.junit"
] | org.apache.flink; org.junit; | 1,940,875 |
protected void transportDataReceived(ReadableBuffer frame, boolean endOfStream) {
if (transportError == null && inboundPhase() == Phase.HEADERS) {
// Must receive headers prior to receiving any payload as we use headers to check for
// protocol correctness.
transportError = Status.INTERNAL.withDescription("no headers received prior to data");
}
if (transportError != null) {
// We've already detected a transport error and now we're just accumulating more detail
// for it.
transportError = transportError.augmentDescription("DATA-----------------------------\n" +
ReadableBuffers.readAsString(frame, errorCharset));
frame.close();
if (transportError.getDescription().length() > 1000 || endOfStream) {
inboundTransportError(transportError);
if (!endOfStream) {
// We have enough error detail so lets cancel.
sendCancel();
}
}
} else {
inboundDataReceived(frame);
if (endOfStream) {
// This is a protocol violation as we expect to receive trailers.
transportError = Status.INTERNAL.withDescription("Recevied EOS on DATA frame");
inboundTransportError(transportError);
}
}
} | void function(ReadableBuffer frame, boolean endOfStream) { if (transportError == null && inboundPhase() == Phase.HEADERS) { transportError = Status.INTERNAL.withDescription(STR); } if (transportError != null) { transportError = transportError.augmentDescription(STR + ReadableBuffers.readAsString(frame, errorCharset)); frame.close(); if (transportError.getDescription().length() > 1000 endOfStream) { inboundTransportError(transportError); if (!endOfStream) { sendCancel(); } } } else { inboundDataReceived(frame); if (endOfStream) { transportError = Status.INTERNAL.withDescription(STR); inboundTransportError(transportError); } } } | /**
* Called by subclasses whenever a data frame is received from the transport.
*
* @param frame the received data frame
* @param endOfStream {@code true} if there will be no more data received for this stream
*/ | Called by subclasses whenever a data frame is received from the transport | transportDataReceived | {
"repo_name": "kaustubh-walokar/grpc-poll-service",
"path": "core/src/main/java/io/grpc/transport/Http2ClientStream.java",
"license": "bsd-3-clause",
"size": 8929
} | [
"io.grpc.Status"
] | import io.grpc.Status; | import io.grpc.*; | [
"io.grpc"
] | io.grpc; | 1,029,078 |
public static void acceptArmorModifier(EntityLivingBase entity, DamageSource damageSource, DamageModifier modifier, double damage) {
Optional<DamageObject> property = modifier.getCause().first(DamageObject.class);
final Iterable<net.minecraft.item.ItemStack> inventory = entity.getArmorInventoryList();
if (property.isPresent()) {
damage = Math.abs(damage) * 25;
net.minecraft.item.ItemStack stack = Iterables.get(inventory, property.get().slot);
if (stack.isEmpty()) {
throw new IllegalStateException("Invalid slot position " + property.get().slot);
}
int itemDamage = (int) (damage / 25D < 1 ? 1 : damage / 25D);
stack.damageItem(itemDamage, entity);
}
} | static void function(EntityLivingBase entity, DamageSource damageSource, DamageModifier modifier, double damage) { Optional<DamageObject> property = modifier.getCause().first(DamageObject.class); final Iterable<net.minecraft.item.ItemStack> inventory = entity.getArmorInventoryList(); if (property.isPresent()) { damage = Math.abs(damage) * 25; net.minecraft.item.ItemStack stack = Iterables.get(inventory, property.get().slot); if (stack.isEmpty()) { throw new IllegalStateException(STR + property.get().slot); } int itemDamage = (int) (damage / 25D < 1 ? 1 : damage / 25D); stack.damageItem(itemDamage, entity); } } | /**
* Only used in Vanilla. The Forge version is much different.
* Basically, this accepts the various "objects" needed to work for an armor piece to be "damaged".
*
* This is also where we can likely throw a damage item event.
*
* @param entity
* @param damageSource
* @param modifier
* @param damage
*/ | Only used in Vanilla. The Forge version is much different. Basically, this accepts the various "objects" needed to work for an armor piece to be "damaged". This is also where we can likely throw a damage item event | acceptArmorModifier | {
"repo_name": "JBYoshi/SpongeCommon",
"path": "src/main/java/org/spongepowered/common/event/damage/DamageEventHandler.java",
"license": "mit",
"size": 24588
} | [
"com.google.common.collect.Iterables",
"java.util.Optional",
"net.minecraft.entity.EntityLivingBase",
"net.minecraft.util.DamageSource",
"org.spongepowered.api.event.cause.entity.damage.DamageModifier",
"org.spongepowered.api.item.inventory.ItemStack"
] | import com.google.common.collect.Iterables; import java.util.Optional; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.DamageSource; import org.spongepowered.api.event.cause.entity.damage.DamageModifier; import org.spongepowered.api.item.inventory.ItemStack; | import com.google.common.collect.*; import java.util.*; import net.minecraft.entity.*; import net.minecraft.util.*; import org.spongepowered.api.event.cause.entity.damage.*; import org.spongepowered.api.item.inventory.*; | [
"com.google.common",
"java.util",
"net.minecraft.entity",
"net.minecraft.util",
"org.spongepowered.api"
] | com.google.common; java.util; net.minecraft.entity; net.minecraft.util; org.spongepowered.api; | 1,857,369 |
@Override
public boolean onMarkerClick(Marker marker) {
for (GoogleMap.OnMarkerClickListener m : onClickListeners) {
m.onMarkerClick(marker);
marker.hideInfoWindow();
}
return true;
} | boolean function(Marker marker) { for (GoogleMap.OnMarkerClickListener m : onClickListeners) { m.onMarkerClick(marker); marker.hideInfoWindow(); } return true; } | /**
* Calls onMarkerClick listener and hides info window
*
* @param marker clicked marker
*/ | Calls onMarkerClick listener and hides info window | onMarkerClick | {
"repo_name": "alessio-b-zak/myRivers",
"path": "android/app/src/main/java/com/epimorphics/android/myrivers/helpers/MultiListener.java",
"license": "mit",
"size": 1939
} | [
"com.google.android.gms.maps.GoogleMap",
"com.google.android.gms.maps.model.Marker"
] | import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.Marker; | import com.google.android.gms.maps.*; import com.google.android.gms.maps.model.*; | [
"com.google.android"
] | com.google.android; | 1,048,140 |
if (!ANALYTICS_ENABLED) {
return sEmptyAnalyticsUtils;
}
if (sInstance == null) {
if (context == null) {
return sEmptyAnalyticsUtils;
}
sInstance = new AnalyticsUtils(context);
}
return sInstance;
}
private AnalyticsUtils(Context context) {
if (context == null) {
// This should only occur for the empty Analytics utils object.
return;
}
mApplicationContext = context.getApplicationContext();
mTracker = GoogleAnalyticsTracker.getInstance();
// Unfortunately this needs to be synchronous.
mTracker.start(UACODE, 300, mApplicationContext);
Log.d(TAG, "Initializing Analytics");
// Since visitor CV's should only be declared the first time an app runs, check if
// it's run before. Add as necessary.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
mApplicationContext);
final boolean firstRun = prefs.getBoolean(FIRST_RUN_KEY, true);
if (firstRun) {
Log.d(TAG, "Analytics firstRun");
String apiLevel = Integer.toString(Build.VERSION.SDK_INT);
String model = Build.MODEL;
mTracker.setCustomVar(1, "apiLevel", apiLevel, VISITOR_SCOPE);
mTracker.setCustomVar(2, "model", model, VISITOR_SCOPE);
// Close out so we never run this block again, unless app is removed & =
// reinstalled.
prefs.edit().putBoolean(FIRST_RUN_KEY, false).commit();
}
} | if (!ANALYTICS_ENABLED) { return sEmptyAnalyticsUtils; } if (sInstance == null) { if (context == null) { return sEmptyAnalyticsUtils; } sInstance = new AnalyticsUtils(context); } return sInstance; } private AnalyticsUtils(Context context) { if (context == null) { return; } mApplicationContext = context.getApplicationContext(); mTracker = GoogleAnalyticsTracker.getInstance(); mTracker.start(UACODE, 300, mApplicationContext); Log.d(TAG, STR); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( mApplicationContext); final boolean firstRun = prefs.getBoolean(FIRST_RUN_KEY, true); if (firstRun) { Log.d(TAG, STR); String apiLevel = Integer.toString(Build.VERSION.SDK_INT); String model = Build.MODEL; mTracker.setCustomVar(1, STR, apiLevel, VISITOR_SCOPE); mTracker.setCustomVar(2, "model", model, VISITOR_SCOPE); prefs.edit().putBoolean(FIRST_RUN_KEY, false).commit(); } } | /**
* Returns the global {@link AnalyticsUtils} singleton object, creating one if necessary.
*/ | Returns the global <code>AnalyticsUtils</code> singleton object, creating one if necessary | getInstance | {
"repo_name": "HeneryH/AquaNotesBU",
"path": "src/com/heneryh/aquanotes/util/AnalyticsUtils.java",
"license": "apache-2.0",
"size": 5491
} | [
"android.content.Context",
"android.content.SharedPreferences",
"android.os.Build",
"android.preference.PreferenceManager",
"android.util.Log",
"com.google.android.apps.analytics.GoogleAnalyticsTracker"
] | import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceManager; import android.util.Log; import com.google.android.apps.analytics.GoogleAnalyticsTracker; | import android.content.*; import android.os.*; import android.preference.*; import android.util.*; import com.google.android.apps.analytics.*; | [
"android.content",
"android.os",
"android.preference",
"android.util",
"com.google.android"
] | android.content; android.os; android.preference; android.util; com.google.android; | 2,327,861 |
public void setModelViewMatrix(Matrix4 modelViewMatrix) {
mModelViewMatrix = modelViewMatrix.getFloatValues();
mVertexShader.setModelViewMatrix(mModelViewMatrix);
}
/**
* Indicates whether lighting should be used or not. This must be set to true when using a
* {@link DiffuseMethod} or a {@link SpecularMethod}. Lights are added to a scene {@link Scene} | void function(Matrix4 modelViewMatrix) { mModelViewMatrix = modelViewMatrix.getFloatValues(); mVertexShader.setModelViewMatrix(mModelViewMatrix); } /** * Indicates whether lighting should be used or not. This must be set to true when using a * {@link DiffuseMethod} or a {@link SpecularMethod}. Lights are added to a scene {@link Scene} | /**
* Sets the model view matrix. The model view matrix is used to transform vertices to eye coordinates
*
* @param modelViewMatrix
*/ | Sets the model view matrix. The model view matrix is used to transform vertices to eye coordinates | setModelViewMatrix | {
"repo_name": "paoloach/zdomus",
"path": "temperature_monitor/opengl/src/main/java/it/achdjian/paolo/opengl/materials/Material.java",
"license": "gpl-2.0",
"size": 50323
} | [
"it.achdjian.paolo.opengl.math.Matrix4"
] | import it.achdjian.paolo.opengl.math.Matrix4; | import it.achdjian.paolo.opengl.math.*; | [
"it.achdjian.paolo"
] | it.achdjian.paolo; | 1,740,908 |
public static <T extends StripeObjectInterface> void stubRequest(
ApiResource.RequestMethod method, String path, Class<T> clazz, String response)
throws StripeException {
stubRequest(method, path, null, null, clazz, response);
} | static <T extends StripeObjectInterface> void function( ApiResource.RequestMethod method, String path, Class<T> clazz, String response) throws StripeException { stubRequest(method, path, null, null, clazz, response); } | /**
* {@code params} and {@code options} defaults to {@code null}.
*
* @see BaseStripeTest#stubRequest(ApiResource.RequestMethod, String, Map, RequestOptions, Class,
* String)
*/ | params and options defaults to null | stubRequest | {
"repo_name": "stripe/stripe-java",
"path": "src/test/java/com/stripe/BaseStripeTest.java",
"license": "mit",
"size": 18995
} | [
"com.stripe.exception.StripeException",
"com.stripe.model.StripeObjectInterface",
"com.stripe.net.ApiResource"
] | import com.stripe.exception.StripeException; import com.stripe.model.StripeObjectInterface; import com.stripe.net.ApiResource; | import com.stripe.exception.*; import com.stripe.model.*; import com.stripe.net.*; | [
"com.stripe.exception",
"com.stripe.model",
"com.stripe.net"
] | com.stripe.exception; com.stripe.model; com.stripe.net; | 340,456 |
public String metaTag(Word word, String predLabel, String nextLabel) {
if (metaTagger != null) {
String wordValue = word.getValue();
if (metaTagger.getWordDict() != null && metaTagger.containsWord(word)) {
metaTagger.wordDictionary(word);
} else if (metaTagger.singleCategory(wordValue)) {
predLabel = word.getCategory();
} else if ((metaTagger.isNumeral(wordValue)) != null) {
predLabel = "numeral/--/--/--/--";
} else if (predLabel.matches("^article.*") || predLabel.matches("^pronoun.*")) {
predLabel = metaTagger.pronounAdj(predLabel, nextLabel, multicat);
}
}
return predLabel;
} | String function(Word word, String predLabel, String nextLabel) { if (metaTagger != null) { String wordValue = word.getValue(); if (metaTagger.getWordDict() != null && metaTagger.containsWord(word)) { metaTagger.wordDictionary(word); } else if (metaTagger.singleCategory(wordValue)) { predLabel = word.getCategory(); } else if ((metaTagger.isNumeral(wordValue)) != null) { predLabel = STR; } else if (predLabel.matches(STR) predLabel.matches(STR)) { predLabel = metaTagger.pronounAdj(predLabel, nextLabel, multicat); } } return predLabel; } | /**
* Applies metatagging rules when evaluating. For now they are hardcoded.
* @param word, the current words
* @param predLabel, the previous word in seuence
* @param nextLabel, the next word in sequence
* @return
*/ | Applies metatagging rules when evaluating. For now they are hardcoded | metaTag | {
"repo_name": "alevas/word.tagging",
"path": "src/gr/aueb/cs/nlp/wordtagger/classifier/evaluation/Evaluation.java",
"license": "mit",
"size": 4377
} | [
"gr.aueb.cs.nlp.wordtagger.data.structure.Word"
] | import gr.aueb.cs.nlp.wordtagger.data.structure.Word; | import gr.aueb.cs.nlp.wordtagger.data.structure.*; | [
"gr.aueb.cs"
] | gr.aueb.cs; | 2,841,362 |
public T3<Object, Object, Object> processRowForUpdate(List<?> row) throws IgniteCheckedException {
GridH2RowDescriptor rowDesc = tbl.rowDescriptor();
GridQueryTypeDescriptor desc = rowDesc.type();
GridCacheContext cctx = rowDesc.context();
boolean hasNewVal = (valColIdx != -1);
boolean hasProps = !hasNewVal || colNames.length > 1;
Object key = row.get(0);
Object oldVal = row.get(1);
if (cctx.binaryMarshaller() && !(oldVal instanceof BinaryObject))
oldVal = cctx.grid().binary().toBinary(oldVal);
Object newVal;
Map<String, Object> newColVals = new HashMap<>();
for (int i = 0; i < colNames.length; i++) {
if (hasNewVal && i == valColIdx - 2)
continue;
GridQueryProperty prop = tbl.rowDescriptor().type().property(colNames[i]);
assert prop != null : "Unknown property: " + colNames[i];
newColVals.put(colNames[i], DmlUtils.convert(row.get(i + 2), rowDesc, prop.type(), colTypes[i], colNames[i]));
}
newVal = valSupplier.apply(row);
if (newVal == null)
throw new IgniteSQLException("New value for UPDATE must not be null", IgniteQueryErrorCode.NULL_VALUE);
// Skip key and value - that's why we start off with 3rd column
for (int i = 0; i < tbl.getColumns().length - QueryUtils.DEFAULT_COLUMNS_COUNT; i++) {
Column c = tbl.getColumn(i + QueryUtils.DEFAULT_COLUMNS_COUNT);
if (rowDesc.isKeyValueOrVersionColumn(c.getColumnId()))
continue;
GridQueryProperty prop = desc.property(c.getName());
if (prop.key())
continue; // Don't get values of key's columns - we won't use them anyway
boolean hasNewColVal = newColVals.containsKey(c.getName());
if (!hasNewColVal)
continue;
Object colVal = newColVals.get(c.getName());
// UPDATE currently does not allow to modify key or its fields, so we must be safe to pass null as key.
rowDesc.setColumnValue(null, newVal, colVal, i);
}
if (cctx.binaryMarshaller() && hasProps) {
assert newVal instanceof BinaryObjectBuilder;
newVal = ((BinaryObjectBuilder)newVal).build();
}
desc.validateKeyAndValue(key, newVal);
return new T3<>(key, oldVal, newVal);
} | T3<Object, Object, Object> function(List<?> row) throws IgniteCheckedException { GridH2RowDescriptor rowDesc = tbl.rowDescriptor(); GridQueryTypeDescriptor desc = rowDesc.type(); GridCacheContext cctx = rowDesc.context(); boolean hasNewVal = (valColIdx != -1); boolean hasProps = !hasNewVal colNames.length > 1; Object key = row.get(0); Object oldVal = row.get(1); if (cctx.binaryMarshaller() && !(oldVal instanceof BinaryObject)) oldVal = cctx.grid().binary().toBinary(oldVal); Object newVal; Map<String, Object> newColVals = new HashMap<>(); for (int i = 0; i < colNames.length; i++) { if (hasNewVal && i == valColIdx - 2) continue; GridQueryProperty prop = tbl.rowDescriptor().type().property(colNames[i]); assert prop != null : STR + colNames[i]; newColVals.put(colNames[i], DmlUtils.convert(row.get(i + 2), rowDesc, prop.type(), colTypes[i], colNames[i])); } newVal = valSupplier.apply(row); if (newVal == null) throw new IgniteSQLException(STR, IgniteQueryErrorCode.NULL_VALUE); for (int i = 0; i < tbl.getColumns().length - QueryUtils.DEFAULT_COLUMNS_COUNT; i++) { Column c = tbl.getColumn(i + QueryUtils.DEFAULT_COLUMNS_COUNT); if (rowDesc.isKeyValueOrVersionColumn(c.getColumnId())) continue; GridQueryProperty prop = desc.property(c.getName()); if (prop.key()) continue; boolean hasNewColVal = newColVals.containsKey(c.getName()); if (!hasNewColVal) continue; Object colVal = newColVals.get(c.getName()); rowDesc.setColumnValue(null, newVal, colVal, i); } if (cctx.binaryMarshaller() && hasProps) { assert newVal instanceof BinaryObjectBuilder; newVal = ((BinaryObjectBuilder)newVal).build(); } desc.validateKeyAndValue(key, newVal); return new T3<>(key, oldVal, newVal); } | /**
* Convert a row into value.
*
* @param row Row to process.
* @throws IgniteCheckedException if failed.
* @return Tuple contains: [key, old value, new value]
*/ | Convert a row into value | processRowForUpdate | {
"repo_name": "xtern/ignite",
"path": "modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/dml/UpdatePlan.java",
"license": "apache-2.0",
"size": 23884
} | [
"java.util.HashMap",
"java.util.List",
"java.util.Map",
"org.apache.ignite.IgniteCheckedException",
"org.apache.ignite.binary.BinaryObject",
"org.apache.ignite.binary.BinaryObjectBuilder",
"org.apache.ignite.internal.processors.cache.GridCacheContext",
"org.apache.ignite.internal.processors.cache.query.IgniteQueryErrorCode",
"org.apache.ignite.internal.processors.query.GridQueryProperty",
"org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor",
"org.apache.ignite.internal.processors.query.IgniteSQLException",
"org.apache.ignite.internal.processors.query.QueryUtils",
"org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor",
"org.h2.table.Column"
] | import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.binary.BinaryObject; import org.apache.ignite.binary.BinaryObjectBuilder; import org.apache.ignite.internal.processors.cache.GridCacheContext; import org.apache.ignite.internal.processors.cache.query.IgniteQueryErrorCode; import org.apache.ignite.internal.processors.query.GridQueryProperty; import org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor; import org.apache.ignite.internal.processors.query.IgniteSQLException; import org.apache.ignite.internal.processors.query.QueryUtils; import org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor; import org.h2.table.Column; | import java.util.*; import org.apache.ignite.*; import org.apache.ignite.binary.*; import org.apache.ignite.internal.processors.cache.*; import org.apache.ignite.internal.processors.cache.query.*; import org.apache.ignite.internal.processors.query.*; import org.apache.ignite.internal.processors.query.h2.opt.*; import org.h2.table.*; | [
"java.util",
"org.apache.ignite",
"org.h2.table"
] | java.util; org.apache.ignite; org.h2.table; | 82,250 |
protected AbstractActionExt createBoundAction(String actionCommand, String methodName) {
String actionName = getUIString(actionCommand);
BoundAction action = new BoundAction(actionName,
actionCommand);
action.registerCallback(this, methodName);
return action;
}
//------------------------ dynamic locale support
| AbstractActionExt function(String actionCommand, String methodName) { String actionName = getUIString(actionCommand); BoundAction action = new BoundAction(actionName, actionCommand); action.registerCallback(this, methodName); return action; } | /**
* creates, configures and returns a bound action to the given method of
* this.
*
* @param actionCommand the actionCommand, same as key to find localizable resources
* @param methodName the method to call an actionPerformed.
* @return newly created action
*/ | creates, configures and returns a bound action to the given method of this | createBoundAction | {
"repo_name": "sing-group/aibench-project",
"path": "aibench-pluginmanager/src/main/java/org/jdesktop/swingx/AbstractPatternPanel.java",
"license": "lgpl-3.0",
"size": 16341
} | [
"org.jdesktop.swingx.action.AbstractActionExt",
"org.jdesktop.swingx.action.BoundAction"
] | import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.action.BoundAction; | import org.jdesktop.swingx.action.*; | [
"org.jdesktop.swingx"
] | org.jdesktop.swingx; | 2,686,043 |
public ScheduleModel getEventModel() {
return eventModel;
} | ScheduleModel function() { return eventModel; } | /**
* Gets the event model.
*
* @return the event model
*/ | Gets the event model | getEventModel | {
"repo_name": "uaijug/chronos",
"path": "src/main/java/br/com/uaijug/chronos/controller/MainCalendar.java",
"license": "gpl-3.0",
"size": 7227
} | [
"org.primefaces.model.ScheduleModel"
] | import org.primefaces.model.ScheduleModel; | import org.primefaces.model.*; | [
"org.primefaces.model"
] | org.primefaces.model; | 1,836,914 |
protected void checkParams() {
if ((m_defaultCollectorName == null) || (m_defaultCollectorParam == null)) {
throw new CmsIllegalArgumentException(Messages.get().container(
Messages.ERR_COLLECTOR_DEFAULTS_INVALID_2,
m_defaultCollectorName,
m_defaultCollectorParam));
}
} | void function() { if ((m_defaultCollectorName == null) (m_defaultCollectorParam == null)) { throw new CmsIllegalArgumentException(Messages.get().container( Messages.ERR_COLLECTOR_DEFAULTS_INVALID_2, m_defaultCollectorName, m_defaultCollectorParam)); } } | /**
* Checks if the required parameters have been set.<p>
*
* @see #setDefaultCollectorName(String)
* @see #setDefaultCollectorParam(String)
*/ | Checks if the required parameters have been set | checkParams | {
"repo_name": "serrapos/opencms-core",
"path": "src/org/opencms/file/collectors/A_CmsResourceCollector.java",
"license": "lgpl-2.1",
"size": 7534
} | [
"org.opencms.main.CmsIllegalArgumentException"
] | import org.opencms.main.CmsIllegalArgumentException; | import org.opencms.main.*; | [
"org.opencms.main"
] | org.opencms.main; | 261,965 |
public boolean getInstanceEnabledForPartition(String resource, String partition) {
// TODO: Remove this old partition list check once old get API removed.
List<String> oldDisabledPartition =
_record.getListField(InstanceConfigProperty.HELIX_DISABLED_PARTITION.name());
Map<String, String> disabledPartitionsMap =
_record.getMapField(InstanceConfigProperty.HELIX_DISABLED_PARTITION.name());
if ((disabledPartitionsMap != null && disabledPartitionsMap.containsKey(resource) && HelixUtil
.deserializeByComma(disabledPartitionsMap.get(resource)).contains(partition))
|| oldDisabledPartition != null && oldDisabledPartition.contains(partition)) {
return false;
} else {
return true;
}
} | boolean function(String resource, String partition) { List<String> oldDisabledPartition = _record.getListField(InstanceConfigProperty.HELIX_DISABLED_PARTITION.name()); Map<String, String> disabledPartitionsMap = _record.getMapField(InstanceConfigProperty.HELIX_DISABLED_PARTITION.name()); if ((disabledPartitionsMap != null && disabledPartitionsMap.containsKey(resource) && HelixUtil .deserializeByComma(disabledPartitionsMap.get(resource)).contains(partition)) oldDisabledPartition != null && oldDisabledPartition.contains(partition)) { return false; } else { return true; } } | /**
* Check if this instance is enabled for a given partition
* @param partition the partition name to check
* @return true if the instance is enabled for the partition, false otherwise
*/ | Check if this instance is enabled for a given partition | getInstanceEnabledForPartition | {
"repo_name": "apache/helix",
"path": "helix-core/src/main/java/org/apache/helix/model/InstanceConfig.java",
"license": "apache-2.0",
"size": 23389
} | [
"java.util.List",
"java.util.Map",
"org.apache.helix.util.HelixUtil"
] | import java.util.List; import java.util.Map; import org.apache.helix.util.HelixUtil; | import java.util.*; import org.apache.helix.util.*; | [
"java.util",
"org.apache.helix"
] | java.util; org.apache.helix; | 106,234 |
@SuppressWarnings({"UnusedDeclaration"})
protected boolean processUnhandledPath(final String actionPath, final ServletRequest request, final ServletResponse response) {
return false;
} | @SuppressWarnings({STR}) boolean function(final String actionPath, final ServletRequest request, final ServletResponse response) { return false; } | /**
* Process unconsumed action paths. Returns {@code true} if action path is consumed,
* otherwise returns {@code false} so to be consumed by filter chain.
*/ | Process unconsumed action paths. Returns true if action path is consumed, otherwise returns false so to be consumed by filter chain | processUnhandledPath | {
"repo_name": "mosoft521/jodd",
"path": "jodd-madvoc/src/main/java/jodd/madvoc/MadvocServletFilter.java",
"license": "bsd-2-clause",
"size": 4546
} | [
"javax.servlet.ServletRequest",
"javax.servlet.ServletResponse"
] | import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; | import javax.servlet.*; | [
"javax.servlet"
] | javax.servlet; | 2,146,703 |
public void testDeserialize_NullInput()
throws IOException, ClassNotFoundException
{
// SETUP
CompressingSerializer serializer = new CompressingSerializer();
// DO WORK
Object result = serializer.deSerialize( null, null );
// VERIFY
assertNull( "Should have nothing.", result );
} | void function() throws IOException, ClassNotFoundException { CompressingSerializer serializer = new CompressingSerializer(); Object result = serializer.deSerialize( null, null ); assertNull( STR, result ); } | /**
* Verify that we don't get any erorrs for null input.
* <p>
* @throws ClassNotFoundException
* @throws IOException
*/ | Verify that we don't get any erorrs for null input. | testDeserialize_NullInput | {
"repo_name": "mohanaraosv/commons-jcs",
"path": "commons-jcs-core/src/test/java/org/apache/commons/jcs/utils/serialization/CompressingSerializerUnitTest.java",
"license": "apache-2.0",
"size": 3866
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 1,318,774 |
List<Field> getDefaultFields(); | List<Field> getDefaultFields(); | /**
* Get the default field list for loading this event from text fields.
* @return The default field list for parsing events of this type.
*/ | Get the default field list for loading this event from text fields | getDefaultFields | {
"repo_name": "aglne/lenskit",
"path": "lenskit-core/src/main/java/org/grouplens/lenskit/data/text/EventTypeDefinition.java",
"license": "lgpl-2.1",
"size": 2291
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 2,271,812 |
public String getDecryptedMessage(String message) {
try {
Cipher cipher = getCipher(Cipher.DECRYPT_MODE);
byte[] encryptedTextBytes = BaseEncoding.base64().decode(message);
byte[] decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
return new String(decryptedTextBytes);
} catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) {
throw Throwables.propagate(e);
}
} | String function(String message) { try { Cipher cipher = getCipher(Cipher.DECRYPT_MODE); byte[] encryptedTextBytes = BaseEncoding.base64().decode(message); byte[] decryptedTextBytes = cipher.doFinal(encryptedTextBytes); return new String(decryptedTextBytes); } catch (IllegalBlockSizeException BadPaddingException InvalidKeyException InvalidAlgorithmParameterException e) { throw Throwables.propagate(e); } } | /**
* Takes Base64 encoded String and decodes with provided key
*
* @param message String encoded with Base64
* @return String
*/ | Takes Base64 encoded String and decodes with provided key | getDecryptedMessage | {
"repo_name": "roalva1/opencga",
"path": "opencga-server/src/main/java/encryption/AESCipher.java",
"license": "apache-2.0",
"size": 5147
} | [
"com.google.common.base.Throwables",
"com.google.common.io.BaseEncoding",
"java.security.InvalidAlgorithmParameterException",
"java.security.InvalidKeyException",
"javax.crypto.BadPaddingException",
"javax.crypto.Cipher",
"javax.crypto.IllegalBlockSizeException"
] | import com.google.common.base.Throwables; import com.google.common.io.BaseEncoding; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; | import com.google.common.base.*; import com.google.common.io.*; import java.security.*; import javax.crypto.*; | [
"com.google.common",
"java.security",
"javax.crypto"
] | com.google.common; java.security; javax.crypto; | 2,260,374 |
public static void setProperty(final String propertyName, final Object value, final Object target, final BeanInfo info) {
try {
final PropertyDescriptor pd = getPropertyDescriptor(info, propertyName);
pd.getWriteMethod().invoke(target, value);
} catch (final InvocationTargetException e) {
throw new RuntimeException("Error setting property " + propertyName, e.getCause());
} catch (final Exception e) {
throw new RuntimeException("Error setting property " + propertyName, e);
}
} | static void function(final String propertyName, final Object value, final Object target, final BeanInfo info) { try { final PropertyDescriptor pd = getPropertyDescriptor(info, propertyName); pd.getWriteMethod().invoke(target, value); } catch (final InvocationTargetException e) { throw new RuntimeException(STR + propertyName, e.getCause()); } catch (final Exception e) { throw new RuntimeException(STR + propertyName, e); } } | /**
* Sets the given property on the target JavaBean using bean instrospection.
* @param propertyName Property to set.
* @param value Property value to set.
* @param target Target JavaBean on which to set property.
* @param info BeanInfo describing the target JavaBean.
*/ | Sets the given property on the target JavaBean using bean instrospection | setProperty | {
"repo_name": "nano-projects/nano-framework",
"path": "nano-commons/src/main/java/org/nanoframework/commons/util/ReflectUtils.java",
"license": "apache-2.0",
"size": 6059
} | [
"java.beans.BeanInfo",
"java.beans.PropertyDescriptor",
"java.lang.reflect.InvocationTargetException"
] | import java.beans.BeanInfo; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; | import java.beans.*; import java.lang.reflect.*; | [
"java.beans",
"java.lang"
] | java.beans; java.lang; | 2,464,583 |
@Override
public void afterPropertiesSet() {
if (getPersistenceManagerFactory() == null) {
throw new IllegalArgumentException("Property 'persistenceManagerFactory' is required");
}
// Build default JdoDialect if none explicitly specified.
if (this.jdoDialect == null) {
this.jdoDialect = new DefaultJdoDialect(getPersistenceManagerFactory().getConnectionFactory());
}
// Check for DataSource as connection factory.
if (this.autodetectDataSource && getDataSource() == null) {
Object pmfcf = getPersistenceManagerFactory().getConnectionFactory();
if (pmfcf instanceof DataSource) {
// Use the PersistenceManagerFactory's DataSource for exposing transactions to JDBC code.
this.dataSource = (DataSource) pmfcf;
if (logger.isInfoEnabled()) {
logger.info("Using DataSource [" + this.dataSource +
"] of JDO PersistenceManagerFactory for JdoTransactionManager");
}
}
}
} | void function() { if (getPersistenceManagerFactory() == null) { throw new IllegalArgumentException(STR); } if (this.jdoDialect == null) { this.jdoDialect = new DefaultJdoDialect(getPersistenceManagerFactory().getConnectionFactory()); } if (this.autodetectDataSource && getDataSource() == null) { Object pmfcf = getPersistenceManagerFactory().getConnectionFactory(); if (pmfcf instanceof DataSource) { this.dataSource = (DataSource) pmfcf; if (logger.isInfoEnabled()) { logger.info(STR + this.dataSource + STR); } } } } | /**
* Eagerly initialize the JDO dialect, creating a default one
* for the specified PersistenceManagerFactory if none set.
* Auto-detect the PersistenceManagerFactory's DataSource, if any.
*/ | Eagerly initialize the JDO dialect, creating a default one for the specified PersistenceManagerFactory if none set. Auto-detect the PersistenceManagerFactory's DataSource, if any | afterPropertiesSet | {
"repo_name": "leogoing/spring_jeesite",
"path": "spring-orm-4.0/org/springframework/orm/jdo/JdoTransactionManager.java",
"license": "apache-2.0",
"size": 24746
} | [
"javax.sql.DataSource"
] | import javax.sql.DataSource; | import javax.sql.*; | [
"javax.sql"
] | javax.sql; | 756,768 |
private void mergeQueryParameters(Request<?> request,
Map<String, List<String>> params) {
Map<String, List<String>> existingParams = request.getParameters();
for (Entry<String, List<String>> param : params.entrySet()) {
String pName = param.getKey();
List<String> pValues = param.getValue();
existingParams.put(pName,
CollectionUtils.mergeLists(existingParams.get(pName), pValues));
}
} | void function(Request<?> request, Map<String, List<String>> params) { Map<String, List<String>> existingParams = request.getParameters(); for (Entry<String, List<String>> param : params.entrySet()) { String pName = param.getKey(); List<String> pValues = param.getValue(); existingParams.put(pName, CollectionUtils.mergeLists(existingParams.get(pName), pValues)); } } | /**
* Merge query parameters into the given request.
*/ | Merge query parameters into the given request | mergeQueryParameters | {
"repo_name": "priyatransbit/aws-sdk-java",
"path": "aws-java-sdk-core/src/main/java/com/amazonaws/http/AmazonHttpClient.java",
"license": "apache-2.0",
"size": 60393
} | [
"com.amazonaws.Request",
"com.amazonaws.util.CollectionUtils",
"java.util.List",
"java.util.Map"
] | import com.amazonaws.Request; import com.amazonaws.util.CollectionUtils; import java.util.List; import java.util.Map; | import com.amazonaws.*; import com.amazonaws.util.*; import java.util.*; | [
"com.amazonaws",
"com.amazonaws.util",
"java.util"
] | com.amazonaws; com.amazonaws.util; java.util; | 326,039 |
public static String getToggledElements() {
HttpSession session = WebContextFactory.get().getSession();
WebState webState = SessionMethods.getWebState(session);
Collection<JSONObject> lists = new HashSet<JSONObject>();
try {
for (Map.Entry<String, Boolean> entry : webState.getToggledElements().entrySet()) {
JSONObject list = new JSONObject();
list.put("id", entry.getKey());
list.put("opened", entry.getValue().toString());
lists.add(list);
}
} catch (JSONException jse) {
LOG.error("Errors generating json objects", jse);
}
return lists.toString();
} | static String function() { HttpSession session = WebContextFactory.get().getSession(); WebState webState = SessionMethods.getWebState(session); Collection<JSONObject> lists = new HashSet<JSONObject>(); try { for (Map.Entry<String, Boolean> entry : webState.getToggledElements().entrySet()) { JSONObject list = new JSONObject(); list.put("id", entry.getKey()); list.put(STR, entry.getValue().toString()); lists.add(list); } } catch (JSONException jse) { LOG.error(STR, jse); } return lists.toString(); } | /**
* This method gets a map of ids of elements that were in the past (during session) toggled and
* returns them in JSON
* @return JSON serialized to a String
* @throws JSONException
*/ | This method gets a map of ids of elements that were in the past (during session) toggled and returns them in JSON | getToggledElements | {
"repo_name": "julie-sullivan/phytomine",
"path": "intermine/web/main/src/org/intermine/dwr/AjaxServices.java",
"license": "lgpl-2.1",
"size": 63770
} | [
"java.util.Collection",
"java.util.HashSet",
"java.util.Map",
"javax.servlet.http.HttpSession",
"org.directwebremoting.WebContextFactory",
"org.intermine.web.logic.results.WebState",
"org.intermine.web.logic.session.SessionMethods",
"org.json.JSONException",
"org.json.JSONObject"
] | import java.util.Collection; import java.util.HashSet; import java.util.Map; import javax.servlet.http.HttpSession; import org.directwebremoting.WebContextFactory; import org.intermine.web.logic.results.WebState; import org.intermine.web.logic.session.SessionMethods; import org.json.JSONException; import org.json.JSONObject; | import java.util.*; import javax.servlet.http.*; import org.directwebremoting.*; import org.intermine.web.logic.results.*; import org.intermine.web.logic.session.*; import org.json.*; | [
"java.util",
"javax.servlet",
"org.directwebremoting",
"org.intermine.web",
"org.json"
] | java.util; javax.servlet; org.directwebremoting; org.intermine.web; org.json; | 2,101,281 |
void renameTable(Session session, TableHandle tableHandle, QualifiedTableName newTableName); | void renameTable(Session session, TableHandle tableHandle, QualifiedTableName newTableName); | /**
* Rename the specified table.
*/ | Rename the specified table | renameTable | {
"repo_name": "saidalaoui/presto",
"path": "presto-main/src/main/java/com/facebook/presto/metadata/Metadata.java",
"license": "apache-2.0",
"size": 7293
} | [
"com.facebook.presto.Session"
] | import com.facebook.presto.Session; | import com.facebook.presto.*; | [
"com.facebook.presto"
] | com.facebook.presto; | 2,221,623 |
private void initMenu() throws Exception {
if (menuResolver != null) {
popup = new Menupopup();
popup.setStyle("overflow: auto; max-height: 100vh;");
for(MenuItem i : menuResolver.getItems()) {
// Add items to the popup menu
FieldMenuItem item = new FieldMenuItem(i);
item.setLabel(i.getLabel().toString());
item.addEventListener(Events.ON_CLICK, new EventListener<MouseEvent>() { | void function() throws Exception { if (menuResolver != null) { popup = new Menupopup(); popup.setStyle(STR); for(MenuItem i : menuResolver.getItems()) { FieldMenuItem item = new FieldMenuItem(i); item.setLabel(i.getLabel().toString()); item.addEventListener(Events.ON_CLICK, new EventListener<MouseEvent>() { | /**
* Initialize menu items
* @throws Exception
*/ | Initialize menu items | initMenu | {
"repo_name": "sinnlabs/dbvim",
"path": "src/org/sinnlabs/dbvim/ui/db/BaseField.java",
"license": "lgpl-3.0",
"size": 11866
} | [
"org.sinnlabs.dbvim.menu.MenuItem",
"org.zkoss.zk.ui.event.EventListener",
"org.zkoss.zk.ui.event.Events",
"org.zkoss.zk.ui.event.MouseEvent",
"org.zkoss.zul.Menupopup"
] | import org.sinnlabs.dbvim.menu.MenuItem; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.Events; import org.zkoss.zk.ui.event.MouseEvent; import org.zkoss.zul.Menupopup; | import org.sinnlabs.dbvim.menu.*; import org.zkoss.zk.ui.event.*; import org.zkoss.zul.*; | [
"org.sinnlabs.dbvim",
"org.zkoss.zk",
"org.zkoss.zul"
] | org.sinnlabs.dbvim; org.zkoss.zk; org.zkoss.zul; | 500,519 |
public static ComponentNetherBridgeCrossing3 createValidComponent(List par0List, Random par1Random, int par2, int par3, int par4, int par5, int par6)
{
StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(par2, par3, par4, -8, -3, 0, 19, 10, 19, par5);
return isAboveGround(structureboundingbox) && StructureComponent.findIntersecting(par0List, structureboundingbox) == null ? new ComponentNetherBridgeCrossing3(par6, par1Random, structureboundingbox, par5) : null;
} | static ComponentNetherBridgeCrossing3 function(List par0List, Random par1Random, int par2, int par3, int par4, int par5, int par6) { StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(par2, par3, par4, -8, -3, 0, 19, 10, 19, par5); return isAboveGround(structureboundingbox) && StructureComponent.findIntersecting(par0List, structureboundingbox) == null ? new ComponentNetherBridgeCrossing3(par6, par1Random, structureboundingbox, par5) : null; } | /**
* Creates and returns a new component piece. Or null if it could not find enough room to place it.
*/ | Creates and returns a new component piece. Or null if it could not find enough room to place it | createValidComponent | {
"repo_name": "HATB0T/RuneCraftery",
"path": "forge/mcp/src/minecraft/net/minecraft/world/gen/structure/ComponentNetherBridgeCrossing3.java",
"license": "lgpl-3.0",
"size": 6329
} | [
"java.util.List",
"java.util.Random"
] | import java.util.List; import java.util.Random; | import java.util.*; | [
"java.util"
] | java.util; | 1,888,715 |
public final ColumnVisibility getColumnVisibilityParsed() {
return new ColumnVisibility(colVisibility);
} | final ColumnVisibility function() { return new ColumnVisibility(colVisibility); } | /**
* Gets the column visibility. <b>WARNING:</b> using this method may inhibit
* performance since a new ColumnVisibility object is created on every call.
*
* @return ColumnVisibility representing the column visibility
* @since 1.5.0
*/ | performance since a new ColumnVisibility object is created on every call | getColumnVisibilityParsed | {
"repo_name": "joshelser/accumulo",
"path": "core/src/main/java/org/apache/accumulo/core/data/Key.java",
"license": "apache-2.0",
"size": 34335
} | [
"org.apache.accumulo.core.security.ColumnVisibility"
] | import org.apache.accumulo.core.security.ColumnVisibility; | import org.apache.accumulo.core.security.*; | [
"org.apache.accumulo"
] | org.apache.accumulo; | 2,580,933 |
public void parse(String systemId) throws SAXException, IOException {
// parse document
XMLInputSource source = new XMLInputSource(null, systemId, null);
try {
parse(source);
}
// wrap XNI exceptions as SAX exceptions
catch (XMLParseException e) {
Exception ex = e.getException();
if (ex == null) {
// must be a parser exception; mine it for locator info and throw
// a SAXParseException
LocatorImpl locatorImpl = new LocatorImpl();
locatorImpl.setPublicId(e.getPublicId());
locatorImpl.setSystemId(e.getExpandedSystemId());
locatorImpl.setLineNumber(e.getLineNumber());
locatorImpl.setColumnNumber(e.getColumnNumber());
throw new SAXParseException(e.getMessage(), locatorImpl);
}
if (ex instanceof SAXException) {
// why did we create an XMLParseException?
throw (SAXException)ex;
}
if (ex instanceof IOException) {
throw (IOException)ex;
}
throw new SAXException(ex);
}
catch (XNIException e) {
e.printStackTrace();
Exception ex = e.getException();
if (ex == null) {
throw new SAXException(e.getMessage());
}
if (ex instanceof SAXException) {
throw (SAXException)ex;
}
if (ex instanceof IOException) {
throw (IOException)ex;
}
throw new SAXException(ex);
}
} // parse(String) | void function(String systemId) throws SAXException, IOException { XMLInputSource source = new XMLInputSource(null, systemId, null); try { parse(source); } catch (XMLParseException e) { Exception ex = e.getException(); if (ex == null) { LocatorImpl locatorImpl = new LocatorImpl(); locatorImpl.setPublicId(e.getPublicId()); locatorImpl.setSystemId(e.getExpandedSystemId()); locatorImpl.setLineNumber(e.getLineNumber()); locatorImpl.setColumnNumber(e.getColumnNumber()); throw new SAXParseException(e.getMessage(), locatorImpl); } if (ex instanceof SAXException) { throw (SAXException)ex; } if (ex instanceof IOException) { throw (IOException)ex; } throw new SAXException(ex); } catch (XNIException e) { e.printStackTrace(); Exception ex = e.getException(); if (ex == null) { throw new SAXException(e.getMessage()); } if (ex instanceof SAXException) { throw (SAXException)ex; } if (ex instanceof IOException) { throw (IOException)ex; } throw new SAXException(ex); } } | /**
* Parses the input source specified by the given system identifier.
* <p>
* This method is equivalent to the following:
* <pre>
* parse(new InputSource(systemId));
* </pre>
*
* @param systemId The system identifier (URI).
*
* @exception org.xml.sax.SAXException Throws exception on SAX error.
* @exception java.io.IOException Throws exception on i/o error.
*/ | Parses the input source specified by the given system identifier. This method is equivalent to the following: <code> parse(new InputSource(systemId)); </code> | parse | {
"repo_name": "openjdk/jdk8u",
"path": "jaxp/src/com/sun/org/apache/xerces/internal/parsers/DOMParser.java",
"license": "gpl-2.0",
"size": 24818
} | [
"com.sun.org.apache.xerces.internal.xni.XNIException",
"com.sun.org.apache.xerces.internal.xni.parser.XMLInputSource",
"com.sun.org.apache.xerces.internal.xni.parser.XMLParseException",
"java.io.IOException",
"org.xml.sax.SAXException",
"org.xml.sax.SAXParseException",
"org.xml.sax.helpers.LocatorImpl"
] | import com.sun.org.apache.xerces.internal.xni.XNIException; import com.sun.org.apache.xerces.internal.xni.parser.XMLInputSource; import com.sun.org.apache.xerces.internal.xni.parser.XMLParseException; import java.io.IOException; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.LocatorImpl; | import com.sun.org.apache.xerces.internal.xni.*; import com.sun.org.apache.xerces.internal.xni.parser.*; import java.io.*; import org.xml.sax.*; import org.xml.sax.helpers.*; | [
"com.sun.org",
"java.io",
"org.xml.sax"
] | com.sun.org; java.io; org.xml.sax; | 791,429 |
public VirtualMachineScaleSetInner withAdditionalCapabilities(AdditionalCapabilities additionalCapabilities) {
this.additionalCapabilities = additionalCapabilities;
return this;
} | VirtualMachineScaleSetInner function(AdditionalCapabilities additionalCapabilities) { this.additionalCapabilities = additionalCapabilities; return this; } | /**
* Set specifies additional capabilities enabled or disabled on the Virtual Machines in the Virtual Machine Scale Set. For instance: whether the Virtual Machines have the capability to support attaching managed data disks with UltraSSD_LRS storage account type.
*
* @param additionalCapabilities the additionalCapabilities value to set
* @return the VirtualMachineScaleSetInner object itself.
*/ | Set specifies additional capabilities enabled or disabled on the Virtual Machines in the Virtual Machine Scale Set. For instance: whether the Virtual Machines have the capability to support attaching managed data disks with UltraSSD_LRS storage account type | withAdditionalCapabilities | {
"repo_name": "navalev/azure-sdk-for-java",
"path": "sdk/compute/mgmt-v2019_03_01/src/main/java/com/microsoft/azure/management/compute/v2019_03_01/implementation/VirtualMachineScaleSetInner.java",
"license": "mit",
"size": 16799
} | [
"com.microsoft.azure.management.compute.v2019_03_01.AdditionalCapabilities"
] | import com.microsoft.azure.management.compute.v2019_03_01.AdditionalCapabilities; | import com.microsoft.azure.management.compute.v2019_03_01.*; | [
"com.microsoft.azure"
] | com.microsoft.azure; | 2,890,237 |
IdmTreeNodeDto getDefaultNode();
| IdmTreeNodeDto getDefaultNode(); | /**
* Returns default tree node
*
* @return
*/ | Returns default tree node | getDefaultNode | {
"repo_name": "bcvsolutions/CzechIdMng",
"path": "Realization/backend/core/core-api/src/main/java/eu/bcvsolutions/idm/core/api/config/domain/TreeConfiguration.java",
"license": "mit",
"size": 1729
} | [
"eu.bcvsolutions.idm.core.api.dto.IdmTreeNodeDto"
] | import eu.bcvsolutions.idm.core.api.dto.IdmTreeNodeDto; | import eu.bcvsolutions.idm.core.api.dto.*; | [
"eu.bcvsolutions.idm"
] | eu.bcvsolutions.idm; | 347,423 |
public static int[] getIntArray(String filename) {
int[] array = null;
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
String line = br.readLine();
StringTokenizer st = new StringTokenizer(line);
int maxlen = st.countTokens();
int len = 0;
array = new int[maxlen];
while ( st.hasMoreTokens() ) {
String tok = st.nextToken();
if ( tok.startsWith("#") ) // commented int
continue;
array[len++] = Integer.parseInt(tok);
}
if ( len != maxlen )
array = ArrayLib.trim(array, len);
return array;
} catch ( Exception e ) {
e.printStackTrace();
return null;
}
}
| static int[] function(String filename) { int[] array = null; try { BufferedReader br = new BufferedReader(new FileReader(filename)); String line = br.readLine(); StringTokenizer st = new StringTokenizer(line); int maxlen = st.countTokens(); int len = 0; array = new int[maxlen]; while ( st.hasMoreTokens() ) { String tok = st.nextToken(); if ( tok.startsWith("#") ) continue; array[len++] = Integer.parseInt(tok); } if ( len != maxlen ) array = ArrayLib.trim(array, len); return array; } catch ( Exception e ) { e.printStackTrace(); return null; } } | /**
* Read in a text file as an array of integers. Uses the default java
* StringTokenizer to segment the text file. Additionally, tokens beginning
* with the '#' character are ignored.
* @param filename the name of the file to read in
* @return an array of integers parsed from the file
*/ | Read in a text file as an array of integers. Uses the default java StringTokenizer to segment the text file. Additionally, tokens beginning with the '#' character are ignored | getIntArray | {
"repo_name": "giacomovagni/Prefuse",
"path": "src/prefuse/util/ArrayLib.java",
"license": "bsd-3-clause",
"size": 44177
} | [
"java.io.BufferedReader",
"java.io.FileReader",
"java.util.StringTokenizer"
] | import java.io.BufferedReader; import java.io.FileReader; import java.util.StringTokenizer; | import java.io.*; import java.util.*; | [
"java.io",
"java.util"
] | java.io; java.util; | 1,972,823 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.