method stringlengths 13 441k | clean_method stringlengths 7 313k | doc stringlengths 17 17.3k | comment stringlengths 3 1.42k | method_name stringlengths 1 273 | extra dict | imports list | imports_info stringlengths 19 34.8k | cluster_imports_info stringlengths 15 3.66k | libraries list | libraries_info stringlengths 6 661 | id int64 0 2.92M |
|---|---|---|---|---|---|---|---|---|---|---|---|
private static boolean setSession(String user, String session, SharedPreferences preferences) {
Log.v(TAG, "setting session");
return preferences.edit()
.putString("session", session)
.putString("username", user)
.commit();
} | static boolean function(String user, String session, SharedPreferences preferences) { Log.v(TAG, STR); return preferences.edit() .putString(STR, session) .putString(STR, user) .commit(); } | /**
* commits the cookie (AKA session) to the shared preferences.
*
* @param session String
* @param preferences SharedPreferences
*/ | commits the cookie (AKA session) to the shared preferences | setSession | {
"repo_name": "KeizerDev/Dumpert",
"path": "Dumpert/src/main/java/io/jari/dumpert/api/Login.java",
"license": "mit",
"size": 11537
} | [
"android.content.SharedPreferences",
"android.util.Log"
] | import android.content.SharedPreferences; import android.util.Log; | import android.content.*; import android.util.*; | [
"android.content",
"android.util"
] | android.content; android.util; | 222,682 |
protected void gen_trust() throws Exception {
double[] ws = model.getFeatureWeights();
Logs.debug("Predict trust values ...");
for (String a : userTNsMap.keySet()) {
// positive instances
Map<String, Double> tns = userTNsMap.get(a);
for (Entry<String, Double> en : tns.entrySet()) {
String b = en.getKey();
if (a.equals(b))
continue;
double be = benevolence(a, b);
double co = competence(a, b, epsilon);
double in = Double.NaN;
if (user_ins.containsKey(b))
in = user_ins.get(b);
double pr = predictability(a, b, theta);
double[] fs = new double[4];
fs[0] = be;
fs[1] = co;
fs[2] = in;
fs[3] = pr;
// single component
String line = a + " " + b;
String content = null;
int[] indexes = null;
double val = 0;
for (int i = 0; i < 4; i++) {
indexes = new int[] { i };
val = combine_features(ws, fs, indexes);
content = line + " " + val;
output_trust(content, indexes);
}
// double components
for (int i = 0; i < 4; i++) {
for (int j = i + 1; j < 4; j++) {
indexes = new int[] { i, j };
val = combine_features(ws, fs, indexes);
content = line + " " + val;
output_trust(content, indexes);
}
}
// three components
for (int i = 0; i < 4; i++) {
indexes = Randoms.nextIntArray(3, 0, 4,
new int[] { i });
val = combine_features(ws, fs, indexes);
content = line + " " + val;
output_trust(content, indexes);
}
// four components
indexes = new int[] { 0, 1, 2, 3 };
val = combine_features(ws, fs, indexes);
content = line + " " + val;
output_trust(content, indexes);
}
}
Logs.debug("Done!");
}
| void function() throws Exception { double[] ws = model.getFeatureWeights(); Logs.debug(STR); for (String a : userTNsMap.keySet()) { Map<String, Double> tns = userTNsMap.get(a); for (Entry<String, Double> en : tns.entrySet()) { String b = en.getKey(); if (a.equals(b)) continue; double be = benevolence(a, b); double co = competence(a, b, epsilon); double in = Double.NaN; if (user_ins.containsKey(b)) in = user_ins.get(b); double pr = predictability(a, b, theta); double[] fs = new double[4]; fs[0] = be; fs[1] = co; fs[2] = in; fs[3] = pr; String line = a + " " + b; String content = null; int[] indexes = null; double val = 0; for (int i = 0; i < 4; i++) { indexes = new int[] { i }; val = combine_features(ws, fs, indexes); content = line + " " + val; output_trust(content, indexes); } for (int i = 0; i < 4; i++) { for (int j = i + 1; j < 4; j++) { indexes = new int[] { i, j }; val = combine_features(ws, fs, indexes); content = line + " " + val; output_trust(content, indexes); } } for (int i = 0; i < 4; i++) { indexes = Randoms.nextIntArray(3, 0, 4, new int[] { i }); val = combine_features(ws, fs, indexes); content = line + " " + val; output_trust(content, indexes); } indexes = new int[] { 0, 1, 2, 3 }; val = combine_features(ws, fs, indexes); content = line + " " + val; output_trust(content, indexes); } } Logs.debug("Done!"); } | /**
* Trust values are re-generated based on different features<br/>
* Distrust values are not re-generated as we will not use them in our work.
*
*/ | Trust values are re-generated based on different features Distrust values are not re-generated as we will not use them in our work | gen_trust | {
"repo_name": "466152112/HappyResearch",
"path": "happyresearch/src/main/java/happy/research/cf/MATrust_mt.java",
"license": "gpl-3.0",
"size": 18486
} | [
"java.util.Map"
] | import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 2,205,419 |
private void restartTimer() {
int timeTillNextIteration;
try {
timeTillNextIteration = (int) Math.max(Duration.ofSeconds(Long.parseLong(properties.get(RAPIDMINER_CONFIG_REFRESH))).toMillis(), MIN_REFETCH);
} catch (NumberFormatException nfe) {
timeTillNextIteration = (int) DEFAULT_REFETCH;
}
// Update timer
if (timer == null) {
timer = new Timer(timeTillNextIteration, e -> readAndRestart());
timer.setRepeats(false);
} else if (timeTillNextIteration != timer.getDelay()) {
timer.setInitialDelay(timeTillNextIteration);
}
timer.restart();
} | void function() { int timeTillNextIteration; try { timeTillNextIteration = (int) Math.max(Duration.ofSeconds(Long.parseLong(properties.get(RAPIDMINER_CONFIG_REFRESH))).toMillis(), MIN_REFETCH); } catch (NumberFormatException nfe) { timeTillNextIteration = (int) DEFAULT_REFETCH; } if (timer == null) { timer = new Timer(timeTillNextIteration, e -> readAndRestart()); timer.setRepeats(false); } else if (timeTillNextIteration != timer.getDelay()) { timer.setInitialDelay(timeTillNextIteration); } timer.restart(); } | /**
* (Re-)starts the timer
*/ | (Re-)starts the timer | restartTimer | {
"repo_name": "aborg0/rapidminer-studio",
"path": "src/main/java/com/rapidminer/tools/parameter/admin/ParameterEnforcer.java",
"license": "agpl-3.0",
"size": 7698
} | [
"java.time.Duration",
"javax.swing.Timer"
] | import java.time.Duration; import javax.swing.Timer; | import java.time.*; import javax.swing.*; | [
"java.time",
"javax.swing"
] | java.time; javax.swing; | 578,533 |
List<ModulePlugin> getModulePluginForModuleId(String moduleId); | List<ModulePlugin> getModulePluginForModuleId(String moduleId); | /**
* API to fetch Module Plugin for Module Id.
*
* @param moduleId String
* @return List<ModulePlugin>
*/ | API to fetch Module Plugin for Module Id | getModulePluginForModuleId | {
"repo_name": "kuzavas/ephesoft",
"path": "dcma-data-access/src/main/java/com/ephesoft/dcma/da/dao/ModulePluginDao.java",
"license": "agpl-3.0",
"size": 2770
} | [
"com.ephesoft.dcma.da.domain.ModulePlugin",
"java.util.List"
] | import com.ephesoft.dcma.da.domain.ModulePlugin; import java.util.List; | import com.ephesoft.dcma.da.domain.*; import java.util.*; | [
"com.ephesoft.dcma",
"java.util"
] | com.ephesoft.dcma; java.util; | 179,149 |
public static <InputType, TransformedInputType, OutputType> InputOutputTransformedBatchLearner<InputType, TransformedInputType, OutputType, OutputType> createInputTransformed(
final BatchLearner<? super Collection<? extends InputType>, ? extends Evaluator<? super InputType, ? extends TransformedInputType>> inputLearner,
final BatchLearner<? super Collection<? extends InputOutputPair<? extends TransformedInputType, OutputType>>, ? extends Evaluator<? super TransformedInputType, ? extends OutputType>> learner)
{
return create(inputLearner, learner,
new IdentityEvaluator<OutputType>());
} | static <InputType, TransformedInputType, OutputType> InputOutputTransformedBatchLearner<InputType, TransformedInputType, OutputType, OutputType> function( final BatchLearner<? super Collection<? extends InputType>, ? extends Evaluator<? super InputType, ? extends TransformedInputType>> inputLearner, final BatchLearner<? super Collection<? extends InputOutputPair<? extends TransformedInputType, OutputType>>, ? extends Evaluator<? super TransformedInputType, ? extends OutputType>> learner) { return create(inputLearner, learner, new IdentityEvaluator<OutputType>()); } | /**
* Creates a new {@code InputOutputTransformedBatchLearner} from the
* input and supervised learners, performing no transformation on the
* output type.
*
* @param <InputType>
* The input type of the data to learn on. This is passed into the
* unsupervised learner for the input transform to create the evaluator
* that will then produce the {@code TransformedInputType}.
* @param <TransformedInputType>
* The output type of the input transformer, which will be used as the
* input values to train the (middle) supervised learner.
* @param <OutputType>
* The output type of the data to learn on. It will be used as the
* output values to train the (middle) supervised learner.
* @param inputLearner
* The unsupervised learning algorithm for creating the input
* transformation.
* @param learner
* The supervised learner whose input is being adapted.
* @return
* A new input transformed batch learner.
*/ | Creates a new InputOutputTransformedBatchLearner from the input and supervised learners, performing no transformation on the output type | createInputTransformed | {
"repo_name": "codeaudit/Foundry",
"path": "Components/LearningCore/Source/gov/sandia/cognition/learning/algorithm/InputOutputTransformedBatchLearner.java",
"license": "bsd-3-clause",
"size": 28022
} | [
"gov.sandia.cognition.evaluator.Evaluator",
"gov.sandia.cognition.evaluator.IdentityEvaluator",
"gov.sandia.cognition.learning.data.InputOutputPair",
"java.util.Collection"
] | import gov.sandia.cognition.evaluator.Evaluator; import gov.sandia.cognition.evaluator.IdentityEvaluator; import gov.sandia.cognition.learning.data.InputOutputPair; import java.util.Collection; | import gov.sandia.cognition.evaluator.*; import gov.sandia.cognition.learning.data.*; import java.util.*; | [
"gov.sandia.cognition",
"java.util"
] | gov.sandia.cognition; java.util; | 1,510,564 |
protected Registry createRegistry() {
JndiRegistry jndi = new JndiRegistry();
try {
// getContext() will force setting up JNDI
jndi.getContext();
return jndi;
} catch (Throwable e) {
log.debug("Cannot create javax.naming.InitialContext due " + e.getMessage() + ". Will fallback and use SimpleRegistry instead. This exception is ignored.", e);
return new SimpleRegistry();
}
}
/**
* A pluggable strategy to allow an endpoint to be created without requiring
* a component to be its factory, such as for looking up the URI inside some
* {@link Registry} | Registry function() { JndiRegistry jndi = new JndiRegistry(); try { jndi.getContext(); return jndi; } catch (Throwable e) { log.debug(STR + e.getMessage() + STR, e); return new SimpleRegistry(); } } /** * A pluggable strategy to allow an endpoint to be created without requiring * a component to be its factory, such as for looking up the URI inside some * {@link Registry} | /**
* Lazily create a default implementation
*/ | Lazily create a default implementation | createRegistry | {
"repo_name": "oscerd/camel",
"path": "camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java",
"license": "apache-2.0",
"size": 155046
} | [
"org.apache.camel.spi.Registry"
] | import org.apache.camel.spi.Registry; | import org.apache.camel.spi.*; | [
"org.apache.camel"
] | org.apache.camel; | 1,786,414 |
public static ImmuTable make(Object something) {
return makeCoordinateSpace(((CoordinateSpace) something));
}
public ImmuTable() {
}
public ImmuTable(Rcvr receiver) {
super(receiver);
} | static ImmuTable function(Object something) { return makeCoordinateSpace(((CoordinateSpace) something)); } public ImmuTable() { } public ImmuTable(Rcvr receiver) { super(receiver); } | /**
* (something isKindOf: MuTable)
* ifTrue: [^self make.MuTable: something].
*/ | (something isKindOf: MuTable) ifTrue: [^self make.MuTable: something] | make | {
"repo_name": "jonesd/udanax-gold2java",
"path": "abora-gold/src/generated-sources/translator/info/dgjones/abora/gold/collection/tables/ImmuTable.java",
"license": "mit",
"size": 12354
} | [
"info.dgjones.abora.gold.collection.tables.ImmuTable",
"info.dgjones.abora.gold.spaces.basic.CoordinateSpace",
"info.dgjones.abora.gold.xcvr.Rcvr"
] | import info.dgjones.abora.gold.collection.tables.ImmuTable; import info.dgjones.abora.gold.spaces.basic.CoordinateSpace; import info.dgjones.abora.gold.xcvr.Rcvr; | import info.dgjones.abora.gold.collection.tables.*; import info.dgjones.abora.gold.spaces.basic.*; import info.dgjones.abora.gold.xcvr.*; | [
"info.dgjones.abora"
] | info.dgjones.abora; | 2,875,823 |
public static String getURI(Element elem) {
Attr attr = elem.getAttributeNodeNS(URI, SRC_ATTR);
return attr != null ? attr.getValue() : LocationUtils.UNKNOWN_STRING;
} | static String function(Element elem) { Attr attr = elem.getAttributeNodeNS(URI, SRC_ATTR); return attr != null ? attr.getValue() : LocationUtils.UNKNOWN_STRING; } | /**
* Returns the URI of an element (DOM flavor)
*
* @param elem the element that holds the location information
* @return the element's URI or "<code>[unknown location]</code>" if <code>elem</code>
* has no location information.
*/ | Returns the URI of an element (DOM flavor) | getURI | {
"repo_name": "adragomir/hbase-indexing-library",
"path": "src/util/src/main/java/org/lilycms/util/location/LocationAttributes.java",
"license": "apache-2.0",
"size": 13735
} | [
"org.w3c.dom.Attr",
"org.w3c.dom.Element"
] | import org.w3c.dom.Attr; import org.w3c.dom.Element; | import org.w3c.dom.*; | [
"org.w3c.dom"
] | org.w3c.dom; | 228,612 |
@CalledByNative
public final boolean hasPermission(String permission) {
if (mPermissionDelegate != null) return mPermissionDelegate.hasPermission(permission);
return ApiCompatibilityUtils.checkPermission(
mApplicationContext, permission, Process.myPid(), Process.myUid())
== PackageManager.PERMISSION_GRANTED;
} | final boolean function(String permission) { if (mPermissionDelegate != null) return mPermissionDelegate.hasPermission(permission); return ApiCompatibilityUtils.checkPermission( mApplicationContext, permission, Process.myPid(), Process.myUid()) == PackageManager.PERMISSION_GRANTED; } | /**
* Determine whether access to a particular permission is granted.
* @param permission The permission whose access is to be checked.
* @return Whether access to the permission is granted.
*/ | Determine whether access to a particular permission is granted | hasPermission | {
"repo_name": "mogoweb/365browser",
"path": "app/src/main/java/org/chromium/ui/base/WindowAndroid.java",
"license": "apache-2.0",
"size": 30912
} | [
"android.content.pm.PackageManager",
"android.os.Process",
"org.chromium.base.ApiCompatibilityUtils"
] | import android.content.pm.PackageManager; import android.os.Process; import org.chromium.base.ApiCompatibilityUtils; | import android.content.pm.*; import android.os.*; import org.chromium.base.*; | [
"android.content",
"android.os",
"org.chromium.base"
] | android.content; android.os; org.chromium.base; | 1,184,938 |
private static void setAllCharacterOffline()
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection())
{
Statement statement = con.createStatement();
statement.executeUpdate("UPDATE characters SET online = 0");
statement.close();
_log.info("Updated characters online status.");
}
catch (SQLException e)
{
}
}
| static void function() { try (Connection con = L2DatabaseFactory.getInstance().getConnection()) { Statement statement = con.createStatement(); statement.executeUpdate(STR); statement.close(); _log.info(STR); } catch (SQLException e) { } } | /**
* Sets all character offline
*/ | Sets all character offline | setAllCharacterOffline | {
"repo_name": "VytautasBoznis/l2.skilas.lt",
"path": "aCis_gameserver/java/net/sf/l2j/gameserver/idfactory/IdFactory.java",
"license": "gpl-2.0",
"size": 9525
} | [
"java.sql.Connection",
"java.sql.SQLException",
"java.sql.Statement",
"net.sf.l2j.L2DatabaseFactory"
] | import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import net.sf.l2j.L2DatabaseFactory; | import java.sql.*; import net.sf.l2j.*; | [
"java.sql",
"net.sf.l2j"
] | java.sql; net.sf.l2j; | 1,293,590 |
@Override
public Object loadUserBySAML(SAMLCredential credential)
{
PortalUserDetails userDetailsObj = null;
String userId = null;
List<String> userRoles = new ArrayList<String>();
// get userid and roles: iterate over attributes searching for "email" and "roles":
for (Attribute cAttribute : credential.getAttributes()) {
String attrName = cAttribute.getName();
log.debug("loadUserBySAML(), parsing attribute -" + attrName);
if (userId == null && attrName.equals(SAML_IDP_METADATA_EMAIL_ATTR_NAME)) {
userId = credential.getAttributeAsString(cAttribute.getName());
log.debug(userId);
}
if (attrName.equals(SAML_IDP_METADATA_ROLE_ATTR_NAME)) {
List<XMLObject> attributeValues = cAttribute.getAttributeValues();
if (!attributeValues.isEmpty()) {
userRoles.add(new StringBuilder(APP_NAME).append(":").append(
getAttributeValue(attributeValues.get(0))).toString());
}
}
}
try {
if (userId == null) {
String errorMsg = "loadUserBySAML(), can not instantiate PortalUserDetails from SAML assertion."
+ "Expected 'email' attribute was not found or has no values. ";
log.error(errorMsg);
throw new Exception(errorMsg);
}
log.debug("loadUserBySAML(), IDP successfully authenticated user, userid: " + userId);
//add granted authorities:
if (userRoles.size() > 0) userDetailsObj = new PortalUserDetails(userId,
AuthorityUtils.createAuthorityList(userRoles.toArray(new String[userRoles.size()])));
else
userDetailsObj = new PortalUserDetails(userId, AuthorityUtils.createAuthorityList(new String[0]));
userDetailsObj.setEmail(userId);
userDetailsObj.setName(userId);
return userDetailsObj;
}
catch (Exception e) {
throw new RuntimeException("Error occurs during authentication: " + e.getMessage());
}
} | Object function(SAMLCredential credential) { PortalUserDetails userDetailsObj = null; String userId = null; List<String> userRoles = new ArrayList<String>(); for (Attribute cAttribute : credential.getAttributes()) { String attrName = cAttribute.getName(); log.debug(STR + attrName); if (userId == null && attrName.equals(SAML_IDP_METADATA_EMAIL_ATTR_NAME)) { userId = credential.getAttributeAsString(cAttribute.getName()); log.debug(userId); } if (attrName.equals(SAML_IDP_METADATA_ROLE_ATTR_NAME)) { List<XMLObject> attributeValues = cAttribute.getAttributeValues(); if (!attributeValues.isEmpty()) { userRoles.add(new StringBuilder(APP_NAME).append(":").append( getAttributeValue(attributeValues.get(0))).toString()); } } } try { if (userId == null) { String errorMsg = STR + STR; log.error(errorMsg); throw new Exception(errorMsg); } log.debug(STR + userId); if (userRoles.size() > 0) userDetailsObj = new PortalUserDetails(userId, AuthorityUtils.createAuthorityList(userRoles.toArray(new String[userRoles.size()]))); else userDetailsObj = new PortalUserDetails(userId, AuthorityUtils.createAuthorityList(new String[0])); userDetailsObj.setEmail(userId); userDetailsObj.setName(userId); return userDetailsObj; } catch (Exception e) { throw new RuntimeException(STR + e.getMessage()); } } | /**
* Implementation of {@code SAMLUserDetailsService}.
* Instantiate PortalUserDetails object from
* SAML assertion received from keycloak Identity Provider
*/ | Implementation of SAMLUserDetailsService. Instantiate PortalUserDetails object from SAML assertion received from keycloak Identity Provider | loadUserBySAML | {
"repo_name": "adamabeshouse/cbioportal",
"path": "security/security-spring/src/main/java/org/cbioportal/security/spring/authentication/keycloak/SAMLUserDetailsServiceImpl.java",
"license": "agpl-3.0",
"size": 5232
} | [
"java.util.ArrayList",
"java.util.List",
"org.cbioportal.security.spring.authentication.PortalUserDetails",
"org.opensaml.saml2.core.Attribute",
"org.opensaml.xml.XMLObject",
"org.springframework.security.core.authority.AuthorityUtils",
"org.springframework.security.saml.SAMLCredential"
] | import java.util.ArrayList; import java.util.List; import org.cbioportal.security.spring.authentication.PortalUserDetails; import org.opensaml.saml2.core.Attribute; import org.opensaml.xml.XMLObject; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.saml.SAMLCredential; | import java.util.*; import org.cbioportal.security.spring.authentication.*; import org.opensaml.saml2.core.*; import org.opensaml.xml.*; import org.springframework.security.core.authority.*; import org.springframework.security.saml.*; | [
"java.util",
"org.cbioportal.security",
"org.opensaml.saml2",
"org.opensaml.xml",
"org.springframework.security"
] | java.util; org.cbioportal.security; org.opensaml.saml2; org.opensaml.xml; org.springframework.security; | 2,614,810 |
synchronized public TransactionStats txnStat( StatsConfig config) throws DatabaseException {
return txnManager.txnStat(config);
}
| synchronized TransactionStats function( StatsConfig config) throws DatabaseException { return txnManager.txnStat(config); } | /**
* Retrieve txn statistics
*/ | Retrieve txn statistics | txnStat | {
"repo_name": "SergiyKolesnikov/fuji",
"path": "examples/BerkeleyDB-fuji-compilable/Statistics/com/sleepycat/je/dbi/EnvironmentImpl.java",
"license": "lgpl-3.0",
"size": 1318
} | [
"com.sleepycat.je.StatsConfig",
"com.sleepycat.je.TransactionStats"
] | import com.sleepycat.je.StatsConfig; import com.sleepycat.je.TransactionStats; | import com.sleepycat.je.*; | [
"com.sleepycat.je"
] | com.sleepycat.je; | 864,196 |
protected void checkPartitionsMatch(Path inputPath) throws IOException {
if (!dpPath.equals(inputPath)) {
// Temp partition input path does not match exist temp path
String msg = "Multiple partitions for one merge mapper: " + dpPath +
" NOT EQUAL TO "
+ inputPath;
LOG.error(msg);
throw new IOException(msg);
}
} | void function(Path inputPath) throws IOException { if (!dpPath.equals(inputPath)) { String msg = STR + dpPath + STR + inputPath; LOG.error(msg); throw new IOException(msg); } } | /**
* Validates that each input path belongs to the same partition since each
* mapper merges the input to a single output directory
*
* @param inputPath - input path
*/ | Validates that each input path belongs to the same partition since each mapper merges the input to a single output directory | checkPartitionsMatch | {
"repo_name": "alanfgates/hive",
"path": "ql/src/java/org/apache/hadoop/hive/ql/exec/AbstractFileMergeOperator.java",
"license": "apache-2.0",
"size": 15244
} | [
"java.io.IOException",
"org.apache.hadoop.fs.Path"
] | import java.io.IOException; import org.apache.hadoop.fs.Path; | import java.io.*; import org.apache.hadoop.fs.*; | [
"java.io",
"org.apache.hadoop"
] | java.io; org.apache.hadoop; | 1,295,133 |
@Test
public void pcepUpdateMsgTest12() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] updateMsg = new byte[] {0x20, 0x0b, 0x00, (byte) 0x70,
0x21, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, //SRP object
0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, //LSP object
0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
(byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
(byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
0x07, 0x10, 0x00, 0x14, 0x01, 0x08, 0x11, 0x01, //ERO object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x01, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, //LSPA object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x07, 0x00, 0x00,
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20 }; //Metric object
byte[] testupdateMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(updateMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepUpdateMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
testupdateMsg = buf.array();
int readLen = buf.writerIndex() - 0;
testupdateMsg = new byte[readLen];
buf.readBytes(testupdateMsg, 0, readLen);
assertThat(testupdateMsg, is(updateMsg));
} | void function() throws PcepParseException, PcepOutOfBoundMessageException { byte[] updateMsg = new byte[] {0x20, 0x0b, 0x00, (byte) 0x70, 0x21, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, 0x00, 0x12, 0x00, 0x10, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01, (byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, 0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, 0x07, 0x10, 0x00, 0x14, 0x01, 0x08, 0x11, 0x01, 0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01, 0x01, 0x01, 0x04, 0x00, 0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x07, 0x00, 0x00, 0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20 }; byte[] testupdateMsg = {0}; ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(); buffer.writeBytes(updateMsg); PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader(); PcepMessage message = null; message = reader.readFrom(buffer); assertThat(message, instanceOf(PcepUpdateMsg.class)); ChannelBuffer buf = ChannelBuffers.dynamicBuffer(); message.writeTo(buf); testupdateMsg = buf.array(); int readLen = buf.writerIndex() - 0; testupdateMsg = new byte[readLen]; buf.readBytes(testupdateMsg, 0, readLen); assertThat(testupdateMsg, is(updateMsg)); } | /**
* This test case checks for SRP, LSP (StatefulIPv4LspIdentidiersTlv, SymbolicPathNameTlv,
* StatefulLspErrorCodeTlv), ERO (IPv4SubObject, IPv4SubObject),LSPA, metric objects in PcUpd message.
*/ | This test case checks for SRP, LSP (StatefulIPv4LspIdentidiersTlv, SymbolicPathNameTlv, StatefulLspErrorCodeTlv), ERO (IPv4SubObject, IPv4SubObject),LSPA, metric objects in PcUpd message | pcepUpdateMsgTest12 | {
"repo_name": "donNewtonAlpha/onos",
"path": "protocols/pcep/pcepio/src/test/java/org/onosproject/pcepio/protocol/PcepUpdateMsgTest.java",
"license": "apache-2.0",
"size": 66899
} | [
"org.hamcrest.MatcherAssert",
"org.hamcrest.Matchers",
"org.hamcrest.core.Is",
"org.jboss.netty.buffer.ChannelBuffer",
"org.jboss.netty.buffer.ChannelBuffers",
"org.onosproject.pcepio.exceptions.PcepOutOfBoundMessageException",
"org.onosproject.pcepio.exceptions.PcepParseException"
] | import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.hamcrest.core.Is; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.onosproject.pcepio.exceptions.PcepOutOfBoundMessageException; import org.onosproject.pcepio.exceptions.PcepParseException; | import org.hamcrest.*; import org.hamcrest.core.*; import org.jboss.netty.buffer.*; import org.onosproject.pcepio.exceptions.*; | [
"org.hamcrest",
"org.hamcrest.core",
"org.jboss.netty",
"org.onosproject.pcepio"
] | org.hamcrest; org.hamcrest.core; org.jboss.netty; org.onosproject.pcepio; | 2,576,825 |
Class<V> classObject = TypeGenerator.generate(type, TECHNICAL_TYPE, WRAPPER_CLASS);
return invokeConstructor(classObject, assertNotNull(value));
} | Class<V> classObject = TypeGenerator.generate(type, TECHNICAL_TYPE, WRAPPER_CLASS); return invokeConstructor(classObject, assertNotNull(value)); } | /**
* Create value object with {@code type} and {@code value}.
*
* @param <V>
* - the value type
* @param type
* - object type
* @param value
* - value for the object
* @return value object
*/ | Create value object with type and value | create | {
"repo_name": "javanarior/valueobject-library",
"path": "src/main/java/de/javanarior/vo/TypeJodaLocalDateTime.java",
"license": "apache-2.0",
"size": 2403
} | [
"de.javanarior.vo.generator.TypeGenerator",
"de.javanarior.vo.types.AbstractValue"
] | import de.javanarior.vo.generator.TypeGenerator; import de.javanarior.vo.types.AbstractValue; | import de.javanarior.vo.generator.*; import de.javanarior.vo.types.*; | [
"de.javanarior.vo"
] | de.javanarior.vo; | 204,430 |
public boolean canDeleteIndexContents(Index index, IndexSettings indexSettings) {
// index contents can be deleted if the index is not on a shared file system,
// or if its on a shared file system but its an already closed index (so all
// its resources have already been relinquished)
if (indexSettings.isOnSharedFilesystem() == false || indexSettings.getIndexMetaData().getState() == IndexMetaData.State.CLOSE) {
final IndexService indexService = indexService(index);
if (indexService == null && nodeEnv.hasNodeFile()) {
return true;
}
} else {
logger.trace("{} skipping index directory deletion due to shadow replicas", index);
}
return false;
} | boolean function(Index index, IndexSettings indexSettings) { if (indexSettings.isOnSharedFilesystem() == false indexSettings.getIndexMetaData().getState() == IndexMetaData.State.CLOSE) { final IndexService indexService = indexService(index); if (indexService == null && nodeEnv.hasNodeFile()) { return true; } } else { logger.trace(STR, index); } return false; } | /**
* This method returns true if the current node is allowed to delete the given index.
* This is the case if the index is deleted in the metadata or there is no allocation
* on the local node and the index isn't on a shared file system.
* @param index {@code Index} to check whether deletion is allowed
* @param indexSettings {@code IndexSettings} for the given index
* @return true if the index can be deleted on this node
*/ | This method returns true if the current node is allowed to delete the given index. This is the case if the index is deleted in the metadata or there is no allocation on the local node and the index isn't on a shared file system | canDeleteIndexContents | {
"repo_name": "strapdata/elassandra5-rc",
"path": "core/src/main/java/org/elasticsearch/indices/IndicesService.java",
"license": "apache-2.0",
"size": 65029
} | [
"org.elasticsearch.cluster.metadata.IndexMetaData",
"org.elasticsearch.index.Index",
"org.elasticsearch.index.IndexService",
"org.elasticsearch.index.IndexSettings"
] | import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.index.Index; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.IndexSettings; | import org.elasticsearch.cluster.metadata.*; import org.elasticsearch.index.*; | [
"org.elasticsearch.cluster",
"org.elasticsearch.index"
] | org.elasticsearch.cluster; org.elasticsearch.index; | 389,194 |
public Result getClosestRowBefore(final byte [] row, final byte [] family)
throws IOException {
if (coprocessorHost != null) {
Result result = new Result();
if (coprocessorHost.preGetClosestRowBefore(row, family, result)) {
return result;
}
}
// look across all the HStores for this region and determine what the
// closest key is across all column families, since the data may be sparse
checkRow(row, "getClosestRowBefore");
startRegionOperation();
this.readRequestsCount.increment();
try {
Store store = getStore(family);
// get the closest key. (HStore.getRowKeyAtOrBefore can return null)
KeyValue key = store.getRowKeyAtOrBefore(row);
Result result = null;
if (key != null) {
Get get = new Get(key.getRow());
get.addFamily(family);
result = get(get, null);
}
if (coprocessorHost != null) {
coprocessorHost.postGetClosestRowBefore(row, family, result);
}
return result;
} finally {
closeRegionOperation();
}
}
/**
* Return an iterator that scans over the HRegion, returning the indicated
* columns and rows specified by the {@link Scan}.
* <p>
* This Iterator must be closed by the caller.
*
* @param scan configured {@link Scan} | Result function(final byte [] row, final byte [] family) throws IOException { if (coprocessorHost != null) { Result result = new Result(); if (coprocessorHost.preGetClosestRowBefore(row, family, result)) { return result; } } checkRow(row, STR); startRegionOperation(); this.readRequestsCount.increment(); try { Store store = getStore(family); KeyValue key = store.getRowKeyAtOrBefore(row); Result result = null; if (key != null) { Get get = new Get(key.getRow()); get.addFamily(family); result = get(get, null); } if (coprocessorHost != null) { coprocessorHost.postGetClosestRowBefore(row, family, result); } return result; } finally { closeRegionOperation(); } } /** * Return an iterator that scans over the HRegion, returning the indicated * columns and rows specified by the {@link Scan}. * <p> * This Iterator must be closed by the caller. * * @param scan configured {@link Scan} | /**
* Return all the data for the row that matches <i>row</i> exactly,
* or the one that immediately preceeds it, at or immediately before
* <i>ts</i>.
*
* @param row row key
* @param family column family to find on
* @return map of values
* @throws IOException read exceptions
*/ | Return all the data for the row that matches row exactly, or the one that immediately preceeds it, at or immediately before ts | getClosestRowBefore | {
"repo_name": "indi60/hbase-pmc",
"path": "target/hbase-0.94.1/hbase-0.94.1/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java",
"license": "apache-2.0",
"size": 184604
} | [
"java.io.IOException",
"org.apache.hadoop.hbase.KeyValue",
"org.apache.hadoop.hbase.client.Get",
"org.apache.hadoop.hbase.client.Result",
"org.apache.hadoop.hbase.client.Scan"
] | import java.io.IOException; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; | import java.io.*; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.client.*; | [
"java.io",
"org.apache.hadoop"
] | java.io; org.apache.hadoop; | 1,166,348 |
private static
String getZuluCharFromTimeZoneOffset(Date time)
{
TimeZone tz = TimeZone.getDefault();
Date offset = new Date(tz.getOffset(time.getTime()));
long lOffset = offset.getTime() / 3600000;//3600000 = (1000(ms)*60(s)*60(m))
int hour = (int) lOffset;
return getZuluCharFromTimeZoneOffset(hour);
} | static String function(Date time) { TimeZone tz = TimeZone.getDefault(); Date offset = new Date(tz.getOffset(time.getTime())); long lOffset = offset.getTime() / 3600000; int hour = (int) lOffset; return getZuluCharFromTimeZoneOffset(hour); } | /**
* Given date, return character String representing which NATO time zone
* you're in.
*
* @param time
* @return
*/ | Given date, return character String representing which NATO time zone you're in | getZuluCharFromTimeZoneOffset | {
"repo_name": "missioncommand/mil-sym-android",
"path": "renderer/src/main/java/armyc2/c2sd/renderer/utilities/SymbolUtilities.java",
"license": "apache-2.0",
"size": 143364
} | [
"java.util.Date",
"java.util.TimeZone"
] | import java.util.Date; import java.util.TimeZone; | import java.util.*; | [
"java.util"
] | java.util; | 898,584 |
String name = config.getName();
Descriptor desc = getDescriptor();
if (name.equals(ContextMapperModel.CONTEXT_MAPPER)) {
return new V1ContextMapperModel(config, desc);
} else if (name.equals(MessageComposerModel.MESSAGE_COMPOSER)) {
return new V1MessageComposerModel(config, desc);
}
return super.read(config);
} | String name = config.getName(); Descriptor desc = getDescriptor(); if (name.equals(ContextMapperModel.CONTEXT_MAPPER)) { return new V1ContextMapperModel(config, desc); } else if (name.equals(MessageComposerModel.MESSAGE_COMPOSER)) { return new V1MessageComposerModel(config, desc); } return super.read(config); } | /**
* Reads in the Configuration, looking for various knowledge models.
* If not found, it falls back to the super class (V1CompositeMarshaller).
*
* @param config the Configuration
* @return the Model
*/ | Reads in the Configuration, looking for various knowledge models. If not found, it falls back to the super class (V1CompositeMarshaller) | read | {
"repo_name": "tadayosi/switchyard",
"path": "components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1BaseCamelMarshaller.java",
"license": "apache-2.0",
"size": 1622
} | [
"org.switchyard.config.model.Descriptor",
"org.switchyard.config.model.composer.ContextMapperModel",
"org.switchyard.config.model.composer.MessageComposerModel",
"org.switchyard.config.model.composer.v1.V1ContextMapperModel",
"org.switchyard.config.model.composer.v1.V1MessageComposerModel"
] | import org.switchyard.config.model.Descriptor; import org.switchyard.config.model.composer.ContextMapperModel; import org.switchyard.config.model.composer.MessageComposerModel; import org.switchyard.config.model.composer.v1.V1ContextMapperModel; import org.switchyard.config.model.composer.v1.V1MessageComposerModel; | import org.switchyard.config.model.*; import org.switchyard.config.model.composer.*; import org.switchyard.config.model.composer.v1.*; | [
"org.switchyard.config"
] | org.switchyard.config; | 2,027,621 |
public void setTopPulledView(View view) {
if (view != null) {
clearTopPulledView();
topPulledView.addView(view);
} else {
throw new NullPointerException("The attached view cannot be null!");
}
} | void function(View view) { if (view != null) { clearTopPulledView(); topPulledView.addView(view); } else { throw new NullPointerException(STR); } } | /**
* Replaces the top pulled view with the given view
*
* @param view The view to be added
*/ | Replaces the top pulled view with the given view | setTopPulledView | {
"repo_name": "yggie/pulltorefresh",
"path": "PullToRefreshLib/src/main/java/com/github/yggie/pulltorefresh/PullListFragment.java",
"license": "mit",
"size": 73344
} | [
"android.view.View"
] | import android.view.View; | import android.view.*; | [
"android.view"
] | android.view; | 2,556,946 |
public @CheckForNull Plugin getPlugin() {
PluginInstanceStore pis = Jenkins.lookup(PluginInstanceStore.class);
return pis != null ? pis.store.get(this) : null;
} | @CheckForNull Plugin function() { PluginInstanceStore pis = Jenkins.lookup(PluginInstanceStore.class); return pis != null ? pis.store.get(this) : null; } | /**
* Gets the instance of {@link Plugin} contributed by this plugin.
*/ | Gets the instance of <code>Plugin</code> contributed by this plugin | getPlugin | {
"repo_name": "oleg-nenashev/jenkins",
"path": "core/src/main/java/hudson/PluginWrapper.java",
"license": "mit",
"size": 47783
} | [
"edu.umd.cs.findbugs.annotations.CheckForNull"
] | import edu.umd.cs.findbugs.annotations.CheckForNull; | import edu.umd.cs.findbugs.annotations.*; | [
"edu.umd.cs"
] | edu.umd.cs; | 594,128 |
if(keys == null || keys.length < 1) return EMPTY_KEYS;
return Arrays.copyOf(keys, keys.length);
} | if(keys == null keys.length < 1) return EMPTY_KEYS; return Arrays.copyOf(keys, keys.length); } | /**
* Returns a array copy of this {@code NamedTuple}'s keys.
* @return
*/ | Returns a array copy of this NamedTuple's keys | keys | {
"repo_name": "UniKnow/htm.java",
"path": "src/main/java/org/numenta/nupic/util/NamedTuple.java",
"license": "gpl-3.0",
"size": 10543
} | [
"java.util.Arrays"
] | import java.util.Arrays; | import java.util.*; | [
"java.util"
] | java.util; | 1,688,999 |
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
} | synchronized void function() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addApi(LocationServices.API) .build(); } | /**
* Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API.
*/ | Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API | buildGoogleApiClient | {
"repo_name": "TheDelus/cfto_leipzig",
"path": "Cfto_leipzig/app/src/main/java/com/cfto_leipzig/mainActivity.java",
"license": "agpl-3.0",
"size": 10067
} | [
"com.google.android.gms.common.api.GoogleApiClient",
"com.google.android.gms.location.LocationServices"
] | import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationServices; | import com.google.android.gms.common.api.*; import com.google.android.gms.location.*; | [
"com.google.android"
] | com.google.android; | 1,223,517 |
@Override
public Map<String, List<DisbursementVoucherDocument>> retrievePaymentSourcesByCampus(boolean immediatesOnly) {
if (LOG.isDebugEnabled()) {
LOG.debug("retrievePaymentSourcesByCampus() started");
}
if (immediatesOnly) {
throw new UnsupportedOperationException("DisbursementVoucher PDP does immediates extraction through normal document processing; immediates for DisbursementVoucher should not be run through batch.");
}
Map<String, List<DisbursementVoucherDocument>> documentsByCampus = new HashMap<String, List<DisbursementVoucherDocument>>();
Collection<DisbursementVoucherDocument> docs = disbursementVoucherDao.getDocumentsByHeaderStatus(KFSConstants.DocumentStatusCodes.APPROVED, false);
for (DisbursementVoucherDocument element : docs) {
String dvdCampusCode = element.getCampusCode();
if (StringUtils.isNotBlank(dvdCampusCode)) {
if (documentsByCampus.containsKey(dvdCampusCode)) {
List<DisbursementVoucherDocument> documents = documentsByCampus.get(dvdCampusCode);
documents.add(element);
}
else {
List<DisbursementVoucherDocument> documents = new ArrayList<DisbursementVoucherDocument>();
documents.add(element);
documentsByCampus.put(dvdCampusCode, documents);
}
}
}
return documentsByCampus;
}
| Map<String, List<DisbursementVoucherDocument>> function(boolean immediatesOnly) { if (LOG.isDebugEnabled()) { LOG.debug(STR); } if (immediatesOnly) { throw new UnsupportedOperationException(STR); } Map<String, List<DisbursementVoucherDocument>> documentsByCampus = new HashMap<String, List<DisbursementVoucherDocument>>(); Collection<DisbursementVoucherDocument> docs = disbursementVoucherDao.getDocumentsByHeaderStatus(KFSConstants.DocumentStatusCodes.APPROVED, false); for (DisbursementVoucherDocument element : docs) { String dvdCampusCode = element.getCampusCode(); if (StringUtils.isNotBlank(dvdCampusCode)) { if (documentsByCampus.containsKey(dvdCampusCode)) { List<DisbursementVoucherDocument> documents = documentsByCampus.get(dvdCampusCode); documents.add(element); } else { List<DisbursementVoucherDocument> documents = new ArrayList<DisbursementVoucherDocument>(); documents.add(element); documentsByCampus.put(dvdCampusCode, documents); } } } return documentsByCampus; } | /**
* Retrieve disbursement vouchers for extraction
* @see org.kuali.kfs.sys.batch.service.PaymentSourceToExtractService#retrievePaymentSourcesByCampus(boolean)
*/ | Retrieve disbursement vouchers for extraction | retrievePaymentSourcesByCampus | {
"repo_name": "ua-eas/ua-kfs-5.3",
"path": "work/src/org/kuali/kfs/fp/document/service/impl/DisbursementVoucherExtractionHelperServiceImpl.java",
"license": "agpl-3.0",
"size": 37018
} | [
"java.util.ArrayList",
"java.util.Collection",
"java.util.HashMap",
"java.util.List",
"java.util.Map",
"org.apache.commons.lang.StringUtils",
"org.kuali.kfs.fp.document.DisbursementVoucherDocument",
"org.kuali.kfs.sys.KFSConstants"
] | import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.kuali.kfs.fp.document.DisbursementVoucherDocument; import org.kuali.kfs.sys.KFSConstants; | import java.util.*; import org.apache.commons.lang.*; import org.kuali.kfs.fp.document.*; import org.kuali.kfs.sys.*; | [
"java.util",
"org.apache.commons",
"org.kuali.kfs"
] | java.util; org.apache.commons; org.kuali.kfs; | 925,871 |
public List<Task> generateTaskList(int numGenerated) throws Exception {
List<Task> tasks = new ArrayList<>();
for (int i = 1; i <= numGenerated; i++) {
tasks.add(generateTask(i));
}
return tasks;
} | List<Task> function(int numGenerated) throws Exception { List<Task> tasks = new ArrayList<>(); for (int i = 1; i <= numGenerated; i++) { tasks.add(generateTask(i)); } return tasks; } | /**
* Generates a list of Tasks based on the flags.
*/ | Generates a list of Tasks based on the flags | generateTaskList | {
"repo_name": "CS2103JAN2017-F14-B2/main",
"path": "src/test/java/seedu/task/testutil/TestDataHelper.java",
"license": "mit",
"size": 5113
} | [
"java.util.ArrayList",
"java.util.List"
] | import java.util.ArrayList; import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 1,348,533 |
public HttpSession getSession(); | HttpSession function(); | /**
* Return the <code>HttpSession</code> for which this object
* is the facade.
*/ | Return the <code>HttpSession</code> for which this object is the facade | getSession | {
"repo_name": "plumer/codana",
"path": "tomcat_files/8.0.22/Session (3).java",
"license": "mit",
"size": 10223
} | [
"javax.servlet.http.HttpSession"
] | import javax.servlet.http.HttpSession; | import javax.servlet.http.*; | [
"javax.servlet"
] | javax.servlet; | 1,067,230 |
@SuppressWarnings("deprecation")
public static Security getInstance(Delegator delegator) throws SecurityConfigurationException {
Assert.notNull("delegator", delegator);
Security security = authorizationCache.get(delegator.getDelegatorName());
if (security == null) {
Iterator<Security> iterator = ServiceLoader.load(Security.class).iterator();
if (iterator.hasNext()) {
security = iterator.next();
} else {
security = new OFBizSecurity();
}
security.setDelegator(delegator);
security = authorizationCache.putIfAbsentAndGet(delegator.getDelegatorName(), security);
if (Debug.verboseOn()) {
Debug.logVerbose("Security implementation " + security.getClass().getName() + " created for delegator " + delegator.getDelegatorName(), module);
}
}
return security;
}
private SecurityFactory() {}
private static final class OFBizSecurity implements Security {
private Delegator delegator = null;
private static final Map<String, Map<String, String>> simpleRoleEntity = UtilMisc.toMap(
"ORDERMGR", UtilMisc.<String, String>toMap("name", "OrderRole", "pkey", "orderId"),
"FACILITY", UtilMisc.<String, String>toMap("name", "FacilityParty", "pkey", "facilityId"),
"MARKETING", UtilMisc.<String, String>toMap("name", "MarketingCampaignRole", "pkey", "marketingCampaignId"));
private OFBizSecurity() {} | @SuppressWarnings(STR) static Security function(Delegator delegator) throws SecurityConfigurationException { Assert.notNull(STR, delegator); Security security = authorizationCache.get(delegator.getDelegatorName()); if (security == null) { Iterator<Security> iterator = ServiceLoader.load(Security.class).iterator(); if (iterator.hasNext()) { security = iterator.next(); } else { security = new OFBizSecurity(); } security.setDelegator(delegator); security = authorizationCache.putIfAbsentAndGet(delegator.getDelegatorName(), security); if (Debug.verboseOn()) { Debug.logVerbose(STR + security.getClass().getName() + STR + delegator.getDelegatorName(), module); } } return security; } private SecurityFactory() {} private static final class OFBizSecurity implements Security { private Delegator delegator = null; private static final Map<String, Map<String, String>> simpleRoleEntity = UtilMisc.toMap( STR, UtilMisc.<String, String>toMap("name", STR, "pkey", STR), STR, UtilMisc.<String, String>toMap("name", STR, "pkey", STR), STR, UtilMisc.<String, String>toMap("name", STR, "pkey", STR)); private OFBizSecurity() {} | /**
* Returns a <code>Security</code> instance. The method uses Java's
* <a href="http://docs.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html"><code>ServiceLoader</code></a>
* to get a <code>Security</code> instance. If no instance is found, a default implementation is used.
* The default implementation is based on/backed by the OFBiz entity engine.
*
* @param delegator The delegator
* @return A <code>Security</code> instance
*/ | Returns a <code>Security</code> instance. The method uses Java's <code>ServiceLoader</code> to get a <code>Security</code> instance. If no instance is found, a default implementation is used. The default implementation is based on/backed by the OFBiz entity engine | getInstance | {
"repo_name": "yuri0x7c1/ofbiz-explorer",
"path": "src/test/resources/apache-ofbiz-17.12.04/framework/security/src/main/java/org/apache/ofbiz/security/SecurityFactory.java",
"license": "apache-2.0",
"size": 13476
} | [
"java.util.Iterator",
"java.util.Map",
"java.util.ServiceLoader",
"org.apache.ofbiz.base.util.Assert",
"org.apache.ofbiz.base.util.Debug",
"org.apache.ofbiz.base.util.UtilMisc",
"org.apache.ofbiz.entity.Delegator"
] | import java.util.Iterator; import java.util.Map; import java.util.ServiceLoader; import org.apache.ofbiz.base.util.Assert; import org.apache.ofbiz.base.util.Debug; import org.apache.ofbiz.base.util.UtilMisc; import org.apache.ofbiz.entity.Delegator; | import java.util.*; import org.apache.ofbiz.base.util.*; import org.apache.ofbiz.entity.*; | [
"java.util",
"org.apache.ofbiz"
] | java.util; org.apache.ofbiz; | 307,564 |
protected boolean serializeTargetValueType(Version version) {
return false;
} | boolean function(Version version) { return false; } | /**
* DO NOT OVERRIDE THIS!
*
* This method only exists for legacy support. No new aggregations need this, nor should they override it.
*
* @param version For backwards compatibility, subclasses can change behavior based on the version
*/ | DO NOT OVERRIDE THIS! This method only exists for legacy support. No new aggregations need this, nor should they override it | serializeTargetValueType | {
"repo_name": "uschindler/elasticsearch",
"path": "server/src/main/java/org/elasticsearch/search/aggregations/support/ValuesSourceAggregationBuilder.java",
"license": "apache-2.0",
"size": 16207
} | [
"org.elasticsearch.Version"
] | import org.elasticsearch.Version; | import org.elasticsearch.*; | [
"org.elasticsearch"
] | org.elasticsearch; | 2,278,626 |
@Override
public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException {
super.looseMarshal(wireFormat, o, dataOut);
} | void function(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException { super.looseMarshal(wireFormat, o, dataOut); } | /**
* Write the booleans that this object uses to a BooleanStream
*/ | Write the booleans that this object uses to a BooleanStream | looseMarshal | {
"repo_name": "apache/activemq-openwire",
"path": "openwire-legacy/src/main/java/org/apache/activemq/openwire/codec/v3/KeepAliveInfoMarshaller.java",
"license": "apache-2.0",
"size": 3538
} | [
"java.io.DataOutput",
"java.io.IOException",
"org.apache.activemq.openwire.codec.OpenWireFormat"
] | import java.io.DataOutput; import java.io.IOException; import org.apache.activemq.openwire.codec.OpenWireFormat; | import java.io.*; import org.apache.activemq.openwire.codec.*; | [
"java.io",
"org.apache.activemq"
] | java.io; org.apache.activemq; | 1,838,242 |
public String getConstructed()
{
JsonObject tResultObject = new JsonObject();
if( Message != "" )
tResultObject.addProperty( "text", Message );
if( Translate != "" )
tResultObject.addProperty( "translate", Translate );
if( TranslateArray != null )
tResultObject.add( "with", new Gson().toJsonTree( TranslateArray ) );
if( Bold != false )
tResultObject.addProperty( "bold", true );
if( Italic != false )
tResultObject.addProperty( "italic", true );
if( Underlined != false )
tResultObject.addProperty( "underlined", true );
if( Strikethrough != false )
tResultObject.addProperty( "strikethrough", true );
if( Obfuscated != false )
tResultObject.addProperty( "obfuscated", true );
if( Color != null )
tResultObject.addProperty( "color", Color.getFriendlyName() );
if( HoverEvent != null )
tResultObject.add( "hoverEvent", HoverEvent.getJson() );
if( ClickEvent != null )
tResultObject.add( "clickEvent", ClickEvent.getJson() );
return tResultObject.toString();
} | String function() { JsonObject tResultObject = new JsonObject(); if( Message != STRtext", Message ); if( Translate != STRtranslateSTRwithSTRboldSTRitalicSTRunderlinedSTRstrikethroughSTRobfuscatedSTRcolorSTRhoverEventSTRclickEvent", ClickEvent.getJson() ); return tResultObject.toString(); } | /**
* Construct the chat object into an useable JSON string for sending
*
* @return
*/ | Construct the chat object into an useable JSON string for sending | getConstructed | {
"repo_name": "GTNewHorizons/Yamcl",
"path": "src/main/java/eu/usrv/yamcore/auxiliary/classes/JSONChatText.java",
"license": "gpl-2.0",
"size": 5054
} | [
"com.google.gson.JsonObject"
] | import com.google.gson.JsonObject; | import com.google.gson.*; | [
"com.google.gson"
] | com.google.gson; | 1,451,507 |
@Test
public void testRevokeAllOnTable() throws Exception{
super.setupAdmin();
//copy data file to test dir
File dataDir = context.getDataDir();
File dataFile = new File(dataDir, SINGLE_TYPE_DATA_FILE_NAME);
FileOutputStream to = new FileOutputStream(dataFile);
Resources.copy(Resources.getResource(SINGLE_TYPE_DATA_FILE_NAME), to);
to.close();
Connection connection = context.createConnection(ADMIN1);
Statement statement = context.createStatement(connection);
statement.execute("CREATE ROLE user_role");
statement.execute("DROP DATABASE IF EXISTS " + DB1 + " CASCADE");
statement.execute("CREATE DATABASE " + DB1);
statement.execute("USE " + DB1);
statement.execute("DROP TABLE IF EXISTS t1");
statement.execute("CREATE TABLE t1 (c1 string)");
statement.execute("GRANT ALL ON TABLE t1 TO ROLE user_role");
statement.execute("GRANT SELECT ON TABLE t1 TO ROLE user_role");
statement.execute("GRANT INSERT ON TABLE t1 TO ROLE user_role");
statement.execute("GRANT ALL ON URI 'file://" + dataFile.getPath() + "' TO ROLE user_role");
statement.execute("GRANT ROLE user_role TO GROUP " + USERGROUP1);
statement.close();
connection.close();
connection = context.createConnection(USER1_1);
statement = context.createStatement(connection);
// Ensure everything works
statement.execute("SELECT * FROM " + DB1 + ".t1");
statement.execute("LOAD DATA LOCAL INPATH '" + dataFile.getPath() + "' INTO TABLE " + DB1 + ".t1");
connection = context.createConnection(ADMIN1);
statement = context.createStatement(connection);
assertResultSize(statement.executeQuery("SHOW GRANT ROLE user_role"), 2);
statement.close();
connection.close();
connection = context.createConnection(ADMIN1);
statement = context.createStatement(connection);
statement.execute("USE " + DB1);
statement.execute("REVOKE ALL ON TABLE t1 from ROLE user_role");
statement.close();
connection.close();
connection = context.createConnection(USER1_1);
statement = context.createStatement(connection);
// Ensure nothing works
try {
statement.execute("SELECT * FROM " + DB1 + ".t1");
assertTrue("SELECT should not be allowed !!", false);
} catch (SQLException se) {
// Ignore
}
try {
statement.execute("LOAD DATA LOCAL INPATH '" + dataFile.getPath() + "' INTO TABLE " + DB1 + ".t1");
assertTrue("INSERT should not be allowed !!", false);
} catch (SQLException se) {
// Ignore
}
statement.close();
connection.close();
connection = context.createConnection(ADMIN1);
statement = context.createStatement(connection);
assertResultSize(statement.executeQuery("SHOW GRANT ROLE user_role"), 1);
statement.close();
connection.close();
} | void function() throws Exception{ super.setupAdmin(); File dataDir = context.getDataDir(); File dataFile = new File(dataDir, SINGLE_TYPE_DATA_FILE_NAME); FileOutputStream to = new FileOutputStream(dataFile); Resources.copy(Resources.getResource(SINGLE_TYPE_DATA_FILE_NAME), to); to.close(); Connection connection = context.createConnection(ADMIN1); Statement statement = context.createStatement(connection); statement.execute(STR); statement.execute(STR + DB1 + STR); statement.execute(STR + DB1); statement.execute(STR + DB1); statement.execute(STR); statement.execute(STR); statement.execute(STR); statement.execute(STR); statement.execute(STR); statement.execute(STRGRANT ROLE user_role TO GROUP STRSELECT * FROM STR.t1STRLOAD DATA LOCAL INPATH 'STR' INTO TABLE STR.t1STRSHOW GRANT ROLE user_role"), 2); statement.close(); connection.close(); connection = context.createConnection(ADMIN1); statement = context.createStatement(connection); statement.execute(STR + DB1); statement.execute("REVOKE ALL ON TABLE t1 from ROLE user_roleSTRSELECT * FROM STR.t1STRSELECT should not be allowed !!STRLOAD DATA LOCAL INPATH 'STR' INTO TABLE STR.t1STRINSERT should not be allowed !!STRSHOW GRANT ROLE user_role"), 1); statement.close(); connection.close(); } | /**
* Revoke all on table after:
* - grant all on table
* - grant select on table
* - grant insert on table
*/ | Revoke all on table after: - grant all on table - grant select on table - grant insert on table | testRevokeAllOnTable | {
"repo_name": "intel-hadoop/incubator-sentry",
"path": "sentry-tests/sentry-tests-hive/src/test/java/org/apache/sentry/tests/e2e/dbprovider/TestDatabaseProvider.java",
"license": "apache-2.0",
"size": 90665
} | [
"com.google.common.io.Resources",
"java.io.File",
"java.io.FileOutputStream",
"java.sql.Connection",
"java.sql.Statement"
] | import com.google.common.io.Resources; import java.io.File; import java.io.FileOutputStream; import java.sql.Connection; import java.sql.Statement; | import com.google.common.io.*; import java.io.*; import java.sql.*; | [
"com.google.common",
"java.io",
"java.sql"
] | com.google.common; java.io; java.sql; | 2,856,783 |
@Override
boolean handleResponse(JmDNSImpl dns) {
if (dns.getLocalHost().conflictWithRecord(this)) {
logger1.finer("handleResponse() Denial detected");
if (dns.isProbing()) {
dns.getLocalHost().incrementHostName();
dns.getCache().clear();
for (ServiceInfo serviceInfo : dns.getServices().values()) {
ServiceInfoImpl info = (ServiceInfoImpl) serviceInfo;
info.revertState();
}
}
dns.revertState();
return true;
}
return false;
} | boolean handleResponse(JmDNSImpl dns) { if (dns.getLocalHost().conflictWithRecord(this)) { logger1.finer(STR); if (dns.isProbing()) { dns.getLocalHost().incrementHostName(); dns.getCache().clear(); for (ServiceInfo serviceInfo : dns.getServices().values()) { ServiceInfoImpl info = (ServiceInfoImpl) serviceInfo; info.revertState(); } } dns.revertState(); return true; } return false; } | /**
* Does the necessary actions, when this as a response.
*/ | Does the necessary actions, when this as a response | handleResponse | {
"repo_name": "thunderace/mpd-control",
"path": "src/org/thunder/jmdns/impl/DNSRecord.java",
"license": "apache-2.0",
"size": 36621
} | [
"org.thunder.jmdns.ServiceInfo"
] | import org.thunder.jmdns.ServiceInfo; | import org.thunder.jmdns.*; | [
"org.thunder.jmdns"
] | org.thunder.jmdns; | 1,390,525 |
public void setExpiresOn(final Date expiresOn) {
mExpiresOn = Utility.getImmutableDateObject(expiresOn);
} | void function(final Date expiresOn) { mExpiresOn = Utility.getImmutableDateObject(expiresOn); } | /**
* Set the expire date.
*
* @param expiresOn the expire time.
*/ | Set the expire date | setExpiresOn | {
"repo_name": "iambmelt/azure-activedirectory-library-for-android",
"path": "adal/src/main/java/com/microsoft/aad/adal/TokenCacheItem.java",
"license": "apache-2.0",
"size": 14626
} | [
"java.util.Date"
] | import java.util.Date; | import java.util.*; | [
"java.util"
] | java.util; | 309,428 |
try {
return (BigDecimal) eventEm.createNamedQuery("Inventory.findUnitaryBalanceByProductItemAndArticle")
.setParameter("warehouseId", warehouseId)
.setParameter("productItemId", productItemId)
.getSingleResult();
} catch (NoResultException exception) {
return BigDecimal.ZERO;
}
} | try { return (BigDecimal) eventEm.createNamedQuery(STR) .setParameter(STR, warehouseId) .setParameter(STR, productItemId) .getSingleResult(); } catch (NoResultException exception) { return BigDecimal.ZERO; } } | /**
* Finds the unitaryBalance quantity by ProductItemPK and WarehousePK
*
* @param warehouseId the warehouse filter
* @param productItemId the productItem filter
* @return the unitaryBalance quantity by ProductItemPK and WarehousePK
*/ | Finds the unitaryBalance quantity by ProductItemPK and WarehousePK | findUnitaryBalanceByProductItemAndArticle | {
"repo_name": "arielsiles/sisk1",
"path": "src/main/com/encens/khipus/service/warehouse/InventoryServiceBean.java",
"license": "gpl-3.0",
"size": 2010
} | [
"java.math.BigDecimal",
"javax.persistence.NoResultException"
] | import java.math.BigDecimal; import javax.persistence.NoResultException; | import java.math.*; import javax.persistence.*; | [
"java.math",
"javax.persistence"
] | java.math; javax.persistence; | 65,757 |
@Test
public void testAttributeAssignments() throws IOException {
assertEqual(createFile("attributeAssignment"), "attributeAssignment", "0");
} | void function() throws IOException { assertEqual(createFile(STR), STR, "0"); } | /**
* Tests attribute assignments.
*
* @throws IOException
* should not occur
*/ | Tests attribute assignments | testAttributeAssignments | {
"repo_name": "SSEHUB/EASyProducer",
"path": "Plugins/IVML/de.uni_hildesheim.sse.ivml.tests/src/test/de/uni_hildesheim/sse/AdvancedTests.java",
"license": "apache-2.0",
"size": 34167
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 796,488 |
protected void initContent() {
// save initialized instance of this class in request attribute for included sub-elements
getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this);
// get the default encoding
String content = getParamContent();
if (CmsStringUtil.isNotEmpty(content)) {
// content already read, must be decoded
setParamContent(decodeContent(content));
return;
} else {
content = "";
}
try {
// lock resource if autolock is enabled
checkLock(getParamResource());
CmsFile editFile = getCms().readFile(getParamResource(), CmsResourceFilter.ALL);
content = CmsEncoder.createString(editFile.getContents(), getFileEncoding());
} catch (CmsException e) {
// reading of file contents failed, show error dialog
try {
showErrorPage(this, e);
} catch (JspException exc) {
// should usually never happen
if (LOG.isInfoEnabled()) {
LOG.info(exc);
}
}
}
setParamContent(content);
}
| void function() { getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this); String content = getParamContent(); if (CmsStringUtil.isNotEmpty(content)) { setParamContent(decodeContent(content)); return; } else { content = ""; } try { checkLock(getParamResource()); CmsFile editFile = getCms().readFile(getParamResource(), CmsResourceFilter.ALL); content = CmsEncoder.createString(editFile.getContents(), getFileEncoding()); } catch (CmsException e) { try { showErrorPage(this, e); } catch (JspException exc) { if (LOG.isInfoEnabled()) { LOG.info(exc); } } } setParamContent(content); } | /**
* Initializes the editor content when openening the editor for the first time.<p>
*/ | Initializes the editor content when openening the editor for the first time | initContent | {
"repo_name": "comundus/opencms-comundus",
"path": "src/main/java/org/opencms/workplace/editors/CmsSimpleEditor.java",
"license": "lgpl-2.1",
"size": 8725
} | [
"javax.servlet.jsp.JspException",
"org.opencms.file.CmsFile",
"org.opencms.file.CmsResourceFilter",
"org.opencms.i18n.CmsEncoder",
"org.opencms.main.CmsException",
"org.opencms.util.CmsStringUtil"
] | import javax.servlet.jsp.JspException; import org.opencms.file.CmsFile; import org.opencms.file.CmsResourceFilter; import org.opencms.i18n.CmsEncoder; import org.opencms.main.CmsException; import org.opencms.util.CmsStringUtil; | import javax.servlet.jsp.*; import org.opencms.file.*; import org.opencms.i18n.*; import org.opencms.main.*; import org.opencms.util.*; | [
"javax.servlet",
"org.opencms.file",
"org.opencms.i18n",
"org.opencms.main",
"org.opencms.util"
] | javax.servlet; org.opencms.file; org.opencms.i18n; org.opencms.main; org.opencms.util; | 1,121,433 |
public void start(final String cmd[], final Map<String, String> environment, // can be null
final String path // can be null
) throws IOException, OSUserException, FileNotFoundException {
// Merge the command array into a single string
final String lpCommandLine = this.internalMergeCommand(cmd);
// The handle must be always closed
final HANDLEByReference hTokenRef = new HANDLEByReference();
try {
/////////////////////////////////////////////////////////////////////////////////////
// The client subprocess cannot be created with CreateProcessWithLogonW since it
// breaks away from ProActive Agent job object. Instead we must use
// LogonUser, Impersonate, CreateProcessAsUser, Revert ...
/////////////////////////////////////////////////////////////////////////////////////
if (!Advapi32.INSTANCE.LogonUser(this.user, this.domain, this.password,
WinBase.LOGON32_LOGON_INTERACTIVE, WinBase.LOGON32_PROVIDER_DEFAULT, hTokenRef)) {
// The logon failure must result as a OSUserException
final int err = Kernel32.INSTANCE.GetLastError();
final String mess = "LogonUser error=" + err + ", " +
Kernel32Util.formatMessageFromLastErrorCode(err);
throw new OSUserException(mess);
}
/////////////////////////////////////////////////////////////////////////////////////
// To get the user env from a non-admin context (LoadUserProfile requires to be admin),
// the user env is read from the stdout of the cmd.exe process created using
// CreateProcessWithLogonW, this works from a non-admin context.
/////////////////////////////////////////////////////////////////////////////////////
Map<String, String> resEnv = environment;
// If not defined create get a new ProcessEnvironment from the java ProcessBuilder
if (resEnv == null) {
ProcessBuilder b = new ProcessBuilder();
resEnv = b.environment();
resEnv.clear();
}
String lpEnvironment = null;
try {
// Dump user env
lpEnvironment = this.internalGetUserEnv(resEnv);
} catch (Exception e) {
// If the env dump has failed the user profile path cannot be found
e.printStackTrace();
}
// try to get the USERPROFILE from dumped env
String lpPath = (path == null ? resEnv.get("USERPROFILE") : path);
if (lpPath == null) {
// Use another way to get the user profile
IntByReference cbSid = new IntByReference(WinDef.MAX_PATH);
Memory m = new Memory(cbSid.getValue());
boolean success = MyUserenv.INSTANCE.GetUserProfileDirectoryW(hTokenRef.getValue(), m, cbSid);
if (!success) {
// No way to get the user profile, we cannot let the process start in C:\Windows
win32ErrorIOException("GetUserProfileDirectoryW");
}
lpPath = m.getString(0, true);
}
// Fill the security attributes
final WinBase.SECURITY_ATTRIBUTES sa = new WinBase.SECURITY_ATTRIBUTES();
sa.lpSecurityDescriptor = null;
sa.bInheritHandle = true;// true otherwise streams are not piped
sa.write();
// Create pipes
if (!(Kernel32.INSTANCE.CreatePipe(this.inRead, this.inWrite, sa, 0) &&
Kernel32.INSTANCE.CreatePipe(this.outRead, this.outWrite, sa, 0) && Kernel32.INSTANCE
.CreatePipe(this.errRead, this.errWrite, sa, 0))) {
throw win32ErrorIOException("CreatePipe");
}
final WinBase.STARTUPINFO si = new WinBase.STARTUPINFO();
si.dwFlags = WinBase.STARTF_USESHOWWINDOW | WinBase.STARTF_USESTDHANDLES;
si.hStdInput = this.inRead.getValue();
si.hStdOutput = this.outWrite.getValue();
si.hStdError = this.errWrite.getValue();
si.lpDesktop = "\0"; // the system tries to create the window station and a default desktop
si.wShowWindow = new WinDef.WORD(0); // SW_HIDE
si.write();
if (!Kernel32.INSTANCE.SetHandleInformation(inWrite.getValue(), WinBase.HANDLE_FLAG_INHERIT, 0) ||
!Kernel32.INSTANCE.SetHandleInformation(outRead.getValue(), WinBase.HANDLE_FLAG_INHERIT, 0) ||
!Kernel32.INSTANCE.SetHandleInformation(errRead.getValue(), WinBase.HANDLE_FLAG_INHERIT, 0)) {
throw win32ErrorIOException("SetHandleInformation");
}
final WinBase.PROCESS_INFORMATION pi = new WinBase.PROCESS_INFORMATION();
/////////////////////////////////////////////////////////////////////////////////////
// If the environment is NULL, the new process uses the environment of the calling
// process. An env block consists of a null-terminated block of null-terminated strings.
// Each string is in the following form: name=value\0
/////////////////////////////////////////////////////////////////////////////////////
final HANDLE hToken = hTokenRef.getValue();
// Impersonate current user
if (!Advapi32.INSTANCE.ImpersonateLoggedOnUser(hToken)) {
throw win32ErrorIOException("ImpersonateLoggedOnUser");
}
/////////////////////////////////////////////////////////////////////////////////////
// If lpDesktop is NULL or "winsta0\\default"
// and the current process does not have the rights to access the default desktop
// the call to CreateProcessAsUserW will return true but
// GetLastError return 1307 ERROR_INVALID_OWNER This security ID may not be assigned as the owner of this object
/////////////////////////////////////////////////////////////////////////////////////
boolean success = Advapi32.INSTANCE.CreateProcessAsUser(
hToken, // user primary token
null, // the name of the module to be executed
lpCommandLine, // the command line
null, // the security attributes inherited by child process
null, // the security attributes inherited by child thread
true, // inherit handles
WinBase.CREATE_NO_WINDOW | WinBase.CREATE_UNICODE_ENVIRONMENT, // creation flags
lpEnvironment, // block of null terminated strings
lpPath, // path to current directory for the process
si, // pointer to STARTUPINFO or STARTUPINFOEX structure
pi); // pointer to PROCESS_FORMATION structure
// The error that corresponds to createProcessAsUser
final int createProcessAsUserError = Kernel32.INSTANCE.GetLastError();
// Always revert to self
if (!Advapi32.INSTANCE.RevertToSelf()) {
// The error that corresponds to RevertToSelf
final int revertToSelfError = Kernel32.INSTANCE.GetLastError();
// We must not continue to run in the context of the client, kill the process
if (success) {
try {
Kernel32.INSTANCE.TerminateProcess(pi.hProcess, 1);
} finally {
Kernel32.INSTANCE.CloseHandle(pi.hProcess);
}
}
// This is a really bad situation the current process should be killed
final String mess = Kernel32Util.formatMessageFromLastErrorCode(revertToSelfError);
throw new Error("RevertToSelf error=" + revertToSelfError + ", " + mess +
" The current process should be killed!");
}
if (!success) {
final String mess = Kernel32Util.formatMessageFromLastErrorCode(createProcessAsUserError);
throw new IOException("CreateProcessAsUser error=" + createProcessAsUserError + ", " + mess);
}
Kernel32.INSTANCE.CloseHandle(pi.hThread);
this.pid = pi.dwProcessId.intValue();
this.handle = pi.hProcess;
// Connect java-side streams
this.internalConnectStreams();
} catch (Exception ex) {
// Clean up the parent's side of the pipes in case of failure only
closeSafely(this.inWrite);
closeSafely(this.outRead);
closeSafely(this.errRead);
// If RuntimeException re-throw the internal IOException
if (ex instanceof IOException) {
throw (IOException) ex;
} else if (ex instanceof OSUserException) {
throw (OSUserException) ex;
} else {
throw new IOException(ex);
}
} finally {
// Always clean up the child's side of the pipes
closeSafely(this.inRead);
closeSafely(this.outWrite);
closeSafely(this.errWrite);
// Always clean up the user token handle
closeSafely(hTokenRef);
}
} | void function(final String cmd[], final Map<String, String> environment, final String path ) throws IOException, OSUserException, FileNotFoundException { final String lpCommandLine = this.internalMergeCommand(cmd); final HANDLEByReference hTokenRef = new HANDLEByReference(); try { if (!Advapi32.INSTANCE.LogonUser(this.user, this.domain, this.password, WinBase.LOGON32_LOGON_INTERACTIVE, WinBase.LOGON32_PROVIDER_DEFAULT, hTokenRef)) { final int err = Kernel32.INSTANCE.GetLastError(); final String mess = STR + err + STR + Kernel32Util.formatMessageFromLastErrorCode(err); throw new OSUserException(mess); } Map<String, String> resEnv = environment; if (resEnv == null) { ProcessBuilder b = new ProcessBuilder(); resEnv = b.environment(); resEnv.clear(); } String lpEnvironment = null; try { lpEnvironment = this.internalGetUserEnv(resEnv); } catch (Exception e) { e.printStackTrace(); } String lpPath = (path == null ? resEnv.get(STR) : path); if (lpPath == null) { IntByReference cbSid = new IntByReference(WinDef.MAX_PATH); Memory m = new Memory(cbSid.getValue()); boolean success = MyUserenv.INSTANCE.GetUserProfileDirectoryW(hTokenRef.getValue(), m, cbSid); if (!success) { win32ErrorIOException(STR); } lpPath = m.getString(0, true); } final WinBase.SECURITY_ATTRIBUTES sa = new WinBase.SECURITY_ATTRIBUTES(); sa.lpSecurityDescriptor = null; sa.bInheritHandle = true; sa.write(); if (!(Kernel32.INSTANCE.CreatePipe(this.inRead, this.inWrite, sa, 0) && Kernel32.INSTANCE.CreatePipe(this.outRead, this.outWrite, sa, 0) && Kernel32.INSTANCE .CreatePipe(this.errRead, this.errWrite, sa, 0))) { throw win32ErrorIOException(STR); } final WinBase.STARTUPINFO si = new WinBase.STARTUPINFO(); si.dwFlags = WinBase.STARTF_USESHOWWINDOW WinBase.STARTF_USESTDHANDLES; si.hStdInput = this.inRead.getValue(); si.hStdOutput = this.outWrite.getValue(); si.hStdError = this.errWrite.getValue(); si.lpDesktop = "\0"; si.wShowWindow = new WinDef.WORD(0); si.write(); if (!Kernel32.INSTANCE.SetHandleInformation(inWrite.getValue(), WinBase.HANDLE_FLAG_INHERIT, 0) !Kernel32.INSTANCE.SetHandleInformation(outRead.getValue(), WinBase.HANDLE_FLAG_INHERIT, 0) !Kernel32.INSTANCE.SetHandleInformation(errRead.getValue(), WinBase.HANDLE_FLAG_INHERIT, 0)) { throw win32ErrorIOException(STR); } final WinBase.PROCESS_INFORMATION pi = new WinBase.PROCESS_INFORMATION(); final HANDLE hToken = hTokenRef.getValue(); if (!Advapi32.INSTANCE.ImpersonateLoggedOnUser(hToken)) { throw win32ErrorIOException(STR); } boolean success = Advapi32.INSTANCE.CreateProcessAsUser( hToken, null, lpCommandLine, null, null, true, WinBase.CREATE_NO_WINDOW WinBase.CREATE_UNICODE_ENVIRONMENT, lpEnvironment, lpPath, si, pi); final int createProcessAsUserError = Kernel32.INSTANCE.GetLastError(); if (!Advapi32.INSTANCE.RevertToSelf()) { final int revertToSelfError = Kernel32.INSTANCE.GetLastError(); if (success) { try { Kernel32.INSTANCE.TerminateProcess(pi.hProcess, 1); } finally { Kernel32.INSTANCE.CloseHandle(pi.hProcess); } } final String mess = Kernel32Util.formatMessageFromLastErrorCode(revertToSelfError); throw new Error(STR + revertToSelfError + STR + mess + STR); } if (!success) { final String mess = Kernel32Util.formatMessageFromLastErrorCode(createProcessAsUserError); throw new IOException(STR + createProcessAsUserError + STR + mess); } Kernel32.INSTANCE.CloseHandle(pi.hThread); this.pid = pi.dwProcessId.intValue(); this.handle = pi.hProcess; this.internalConnectStreams(); } catch (Exception ex) { closeSafely(this.inWrite); closeSafely(this.outRead); closeSafely(this.errRead); if (ex instanceof IOException) { throw (IOException) ex; } else if (ex instanceof OSUserException) { throw (OSUserException) ex; } else { throw new IOException(ex); } } finally { closeSafely(this.inRead); closeSafely(this.outWrite); closeSafely(this.errWrite); closeSafely(hTokenRef); } } | /**
* Starts a new process under the specified user.
* <p>
* The default priority is normal.
*
* @return <tt>true</tt> if the process has started successfully, <tt>false</tt> if the process is already running
*/ | Starts a new process under the specified user. The default priority is normal | start | {
"repo_name": "acontes/programming",
"path": "src/Extensions/org/objectweb/proactive/extensions/processbuilder/WindowsProcess.java",
"license": "agpl-3.0",
"size": 57759
} | [
"com.sun.jna.Memory",
"com.sun.jna.platform.win32.Advapi32",
"com.sun.jna.platform.win32.Kernel32",
"com.sun.jna.platform.win32.Kernel32Util",
"com.sun.jna.platform.win32.WinBase",
"com.sun.jna.platform.win32.WinDef",
"com.sun.jna.platform.win32.WinNT",
"com.sun.jna.ptr.IntByReference",
"java.io.FileNotFoundException",
"java.io.IOException",
"java.util.Map",
"org.objectweb.proactive.extensions.processbuilder.exception.OSUserException"
] | import com.sun.jna.Memory; import com.sun.jna.platform.win32.Advapi32; import com.sun.jna.platform.win32.Kernel32; import com.sun.jna.platform.win32.Kernel32Util; import com.sun.jna.platform.win32.WinBase; import com.sun.jna.platform.win32.WinDef; import com.sun.jna.platform.win32.WinNT; import com.sun.jna.ptr.IntByReference; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Map; import org.objectweb.proactive.extensions.processbuilder.exception.OSUserException; | import com.sun.jna.*; import com.sun.jna.platform.win32.*; import com.sun.jna.ptr.*; import java.io.*; import java.util.*; import org.objectweb.proactive.extensions.processbuilder.exception.*; | [
"com.sun.jna",
"java.io",
"java.util",
"org.objectweb.proactive"
] | com.sun.jna; java.io; java.util; org.objectweb.proactive; | 2,096,344 |
public Properties getProperties(); | Properties function(); | /**
* get configuration properties
*
* @return configuration properties as defined by the server or client Wink module
*/ | get configuration properties | getProperties | {
"repo_name": "mitchellsundt/wink-jackson2",
"path": "wink-jackson2-common/src/main/java/org/apache/wink/common/internal/WinkConfiguration.java",
"license": "apache-2.0",
"size": 1465
} | [
"java.util.Properties"
] | import java.util.Properties; | import java.util.*; | [
"java.util"
] | java.util; | 140,004 |
public List<? super OpenShiftResource> processTemplateResources() {
List<? extends OpenShiftResource> resources;
final List<? super OpenShiftResource> processedResources = new ArrayList<>();
templates = OpenShiftResourceFactory.getTemplates(getType());
boolean sync_instantiation = OpenShiftResourceFactory.syncInstantiation(getType());
for (Template template : templates) {
resources = processTemplate(template);
if (resources != null) {
if (sync_instantiation) {
processedResources.addAll(resources);
} else {
try {
delay(openShiftAdapter, resources);
} catch (Throwable t) {
throw new IllegalArgumentException(asynchronousDelayErrorMessage(), t);
}
}
}
}
return processedResources;
} | List<? super OpenShiftResource> function() { List<? extends OpenShiftResource> resources; final List<? super OpenShiftResource> processedResources = new ArrayList<>(); templates = OpenShiftResourceFactory.getTemplates(getType()); boolean sync_instantiation = OpenShiftResourceFactory.syncInstantiation(getType()); for (Template template : templates) { resources = processTemplate(template); if (resources != null) { if (sync_instantiation) { processedResources.addAll(resources); } else { try { delay(openShiftAdapter, resources); } catch (Throwable t) { throw new IllegalArgumentException(asynchronousDelayErrorMessage(), t); } } } } return processedResources; } | /**
* Instantiates the templates specified by @Template within @Templates
*/ | Instantiates the templates specified by @Template within @Templates | processTemplateResources | {
"repo_name": "arquillian/arquillian-cube",
"path": "openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/resources/TemplateProcessor.java",
"license": "apache-2.0",
"size": 5919
} | [
"java.util.ArrayList",
"java.util.List",
"org.arquillian.cube.openshift.api.Template",
"org.arquillian.cube.openshift.api.model.OpenShiftResource"
] | import java.util.ArrayList; import java.util.List; import org.arquillian.cube.openshift.api.Template; import org.arquillian.cube.openshift.api.model.OpenShiftResource; | import java.util.*; import org.arquillian.cube.openshift.api.*; import org.arquillian.cube.openshift.api.model.*; | [
"java.util",
"org.arquillian.cube"
] | java.util; org.arquillian.cube; | 2,634,747 |
@Override
public void setFeedbacks(List<Feedback> feedbacks) {
this.feedbacks = feedbacks;
} | void function(List<Feedback> feedbacks) { this.feedbacks = feedbacks; } | /**
* Sets the feedbacks.
*
* @param feedbacks the feedbacks
*/ | Sets the feedbacks | setFeedbacks | {
"repo_name": "WestCoastInformatics/OTF-Mapping-Service",
"path": "jpa-model/src/main/java/org/ihtsdo/otf/mapping/jpa/FeedbackConversationJpa.java",
"license": "apache-2.0",
"size": 12527
} | [
"java.util.List",
"org.ihtsdo.otf.mapping.model.Feedback"
] | import java.util.List; import org.ihtsdo.otf.mapping.model.Feedback; | import java.util.*; import org.ihtsdo.otf.mapping.model.*; | [
"java.util",
"org.ihtsdo.otf"
] | java.util; org.ihtsdo.otf; | 264,451 |
private void createGeneralImage(){
try{
BufferedImage bimg = ImageIO.read(new File(url));
Graphics2D g = image.createGraphics();
g.drawImage(bimg, 0, 0, (int)area.getWidth(), (int)area.getHeight(), 0, 0 , bimg.getWidth(), bimg.getHeight(), null);
g.dispose();
}
catch (Exception e) {
createErrorImage();
Viewer.logException(e);
}
}
| void function(){ try{ BufferedImage bimg = ImageIO.read(new File(url)); Graphics2D g = image.createGraphics(); g.drawImage(bimg, 0, 0, (int)area.getWidth(), (int)area.getHeight(), 0, 0 , bimg.getWidth(), bimg.getHeight(), null); g.dispose(); } catch (Exception e) { createErrorImage(); Viewer.logException(e); } } | /**
* Creates image
* @return
*/ | Creates image | createGeneralImage | {
"repo_name": "rob-work/iwbcff",
"path": "src/becta/viewer/drawing/ImageElement.java",
"license": "bsd-2-clause",
"size": 17514
} | [
"java.awt.Graphics2D",
"java.awt.image.BufferedImage",
"java.io.File",
"javax.imageio.ImageIO"
] | import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; | import java.awt.*; import java.awt.image.*; import java.io.*; import javax.imageio.*; | [
"java.awt",
"java.io",
"javax.imageio"
] | java.awt; java.io; javax.imageio; | 2,309,538 |
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
} | void function(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } | /**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing
* the children that can be created under this object. <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/ | This adds <code>org.eclipse.emf.edit.command.CommandParameter</code>s describing the children that can be created under this object. | collectNewChildDescriptors | {
"repo_name": "enterpriseDomain/ClassMaker",
"path": "bundles/org.enterprisedomain.classmaker.edit/src/org/enterprisedomain/classmaker/provider/StrategyItemProvider.java",
"license": "apache-2.0",
"size": 7265
} | [
"java.util.Collection"
] | import java.util.Collection; | import java.util.*; | [
"java.util"
] | java.util; | 1,368,897 |
protected StringDistance getStringDistance() {
throw new UnsupportedOperationException();
} | StringDistance function() { throw new UnsupportedOperationException(); } | /**
* Get the distance implementation used by this spellchecker, or NULL if not applicable.
*/ | Get the distance implementation used by this spellchecker, or NULL if not applicable | getStringDistance | {
"repo_name": "yintaoxue/read-open-source-code",
"path": "solr-4.10.4/src/org/apache/solr/spelling/SolrSpellChecker.java",
"license": "apache-2.0",
"size": 7335
} | [
"org.apache.lucene.search.spell.StringDistance"
] | import org.apache.lucene.search.spell.StringDistance; | import org.apache.lucene.search.spell.*; | [
"org.apache.lucene"
] | org.apache.lucene; | 1,989,108 |
@Override
public void run() {
//SocketChannel sock;
try {
sock = masterSocket.accept();
sock.setKeepAlive(true);
//sock.setTcpNoDelay(true);
sock.setSendBufferSize(32767);
sock.setReceiveBufferSize(32767);
// At this point we have a connection back from 'slave'
} catch (IOException e1) {
System.out.println("RelatrixKVClient server socket accept failed with "+e1);
shutdown();
return;
}
if( DEBUG ) {
System.out.println("RelatrixKVClient got connection "+sock);
}
try {
while(shouldRun ) {
InputStream ins = sock.getInputStream();
ObjectInputStream ois = new ObjectInputStream(ins);
RemoteResponseInterface iori = (RemoteResponseInterface) ois.readObject();
// get the original request from the stored table
if( DEBUG )
System.out.println("FROM Remote, response:"+iori+" master port:"+MASTERPORT+" slave:"+SLAVEPORT);
Object o = iori.getObjectReturn();
if( o instanceof Exception ) {
if( !(((Throwable)o).getCause() instanceof DuplicateKeyException) || SHOWDUPEKEYEXCEPTION )
System.out.println("RelatrixKVClient: ******** REMOTE EXCEPTION ******** "+((Throwable)o).getCause());
o = ((Throwable)o).getCause();
}
RelatrixKVStatement rs = outstandingRequests.get(iori.getSession());
if( rs == null ) {
ois.close();
throw new Exception("REQUEST/RESPONSE MISMATCH, statement:"+iori);
} else {
// We have the request after its session round trip, get it from outstanding waiters and signal
// set it with the response object
rs.setObjectReturn(o);
// and signal the latch we have finished
rs.getCountDownLatch().countDown();
}
}
} catch(Exception e) {
// we lost the remote, try to close worker and wait for reconnect
//System.out.println("RelatrixClient: receive IO error "+e+" Address:"+IPAddress+" master port:"+MASTERPORT+" slave:"+SLAVEPORT);
} finally {
shutdown();
}
synchronized(waitHalt) {
waitHalt.notifyAll();
}
} | void function() { try { sock = masterSocket.accept(); sock.setKeepAlive(true); sock.setSendBufferSize(32767); sock.setReceiveBufferSize(32767); } catch (IOException e1) { System.out.println(STR+e1); shutdown(); return; } if( DEBUG ) { System.out.println(STR+sock); } try { while(shouldRun ) { InputStream ins = sock.getInputStream(); ObjectInputStream ois = new ObjectInputStream(ins); RemoteResponseInterface iori = (RemoteResponseInterface) ois.readObject(); if( DEBUG ) System.out.println(STR+iori+STR+MASTERPORT+STR+SLAVEPORT); Object o = iori.getObjectReturn(); if( o instanceof Exception ) { if( !(((Throwable)o).getCause() instanceof DuplicateKeyException) SHOWDUPEKEYEXCEPTION ) System.out.println(STR+((Throwable)o).getCause()); o = ((Throwable)o).getCause(); } RelatrixKVStatement rs = outstandingRequests.get(iori.getSession()); if( rs == null ) { ois.close(); throw new Exception(STR+iori); } else { rs.setObjectReturn(o); rs.getCountDownLatch().countDown(); } } } catch(Exception e) { } finally { shutdown(); } synchronized(waitHalt) { waitHalt.notifyAll(); } } | /**
* Set up the socket
*/ | Set up the socket | run | {
"repo_name": "neocoretechs/Relatrix",
"path": "src/com/neocoretechs/relatrix/client/RelatrixKVClient.java",
"license": "apache-2.0",
"size": 61869
} | [
"com.neocoretechs.relatrix.DuplicateKeyException",
"java.io.IOException",
"java.io.InputStream",
"java.io.ObjectInputStream"
] | import com.neocoretechs.relatrix.DuplicateKeyException; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; | import com.neocoretechs.relatrix.*; import java.io.*; | [
"com.neocoretechs.relatrix",
"java.io"
] | com.neocoretechs.relatrix; java.io; | 2,425,839 |
public HashMap<String, ExchangeSite> getAvailableSites() {
return sites;
} | HashMap<String, ExchangeSite> function() { return sites; } | /**
* Get a list of available sites
* @return
*/ | Get a list of available sites | getAvailableSites | {
"repo_name": "santiagorp/bitcointrader",
"path": "src/server/src/main/java/com/srp/trading/server/ExchangeFactory.java",
"license": "gpl-2.0",
"size": 5149
} | [
"com.srp.trading.plugin.ExchangeSite",
"java.util.HashMap"
] | import com.srp.trading.plugin.ExchangeSite; import java.util.HashMap; | import com.srp.trading.plugin.*; import java.util.*; | [
"com.srp.trading",
"java.util"
] | com.srp.trading; java.util; | 745 |
public static TRetCTeOS enviarCteOS(ConfiguracoesCte configuracoesCte, TCTeOS enviCTe) throws CteException {
return EnvioCteOS.enviaCteOS(ConfiguracoesUtil.iniciaConfiguracoes(configuracoesCte), enviCTe);
} | static TRetCTeOS function(ConfiguracoesCte configuracoesCte, TCTeOS enviCTe) throws CteException { return EnvioCteOS.enviaCteOS(ConfiguracoesUtil.iniciaConfiguracoes(configuracoesCte), enviCTe); } | /**
* Metodo para Enviar a CTEOS.
*
* @param configuracoesCte
* @param enviCTe
* @return
* @throws CteException
*/ | Metodo para Enviar a CTEOS | enviarCteOS | {
"repo_name": "Samuel-Oliveira/Java_CTe",
"path": "src/main/java/br/com/swconsultoria/cte/Cte.java",
"license": "mit",
"size": 8955
} | [
"br.com.swconsultoria.cte.dom.ConfiguracoesCte",
"br.com.swconsultoria.cte.exception.CteException",
"br.com.swconsultoria.cte.schema_300.cteOS.TCTeOS",
"br.com.swconsultoria.cte.schema_300.retCTeOS.TRetCTeOS",
"br.com.swconsultoria.cte.util.ConfiguracoesUtil"
] | import br.com.swconsultoria.cte.dom.ConfiguracoesCte; import br.com.swconsultoria.cte.exception.CteException; import br.com.swconsultoria.cte.schema_300.cteOS.TCTeOS; import br.com.swconsultoria.cte.schema_300.retCTeOS.TRetCTeOS; import br.com.swconsultoria.cte.util.ConfiguracoesUtil; | import br.com.swconsultoria.cte.dom.*; import br.com.swconsultoria.cte.exception.*; import br.com.swconsultoria.cte.schema_300.*; import br.com.swconsultoria.cte.util.*; | [
"br.com.swconsultoria"
] | br.com.swconsultoria; | 137,777 |
public final boolean startAction(Action<?> action) {
if (this.action != null) {
if (this.action.equals(action)) {
return false;
}
stopAction();
}
this.action = action;
return world.schedule(action);
} | final boolean function(Action<?> action) { if (this.action != null) { if (this.action.equals(action)) { return false; } stopAction(); } this.action = action; return world.schedule(action); } | /**
* Starts a new action, stopping the current one if it exists.
*
* @param action The new action.
* @return A flag indicating if the action was started.
*/ | Starts a new action, stopping the current one if it exists | startAction | {
"repo_name": "Major-/apollo",
"path": "game/src/main/org/apollo/game/model/entity/Mob.java",
"license": "isc",
"size": 13644
} | [
"org.apollo.game.action.Action"
] | import org.apollo.game.action.Action; | import org.apollo.game.action.*; | [
"org.apollo.game"
] | org.apollo.game; | 2,541,777 |
@Override
public FormStatus process(String actionName) {
FormStatus retStatus;
if (PROTEUSModel.proteusProcessActionString.equals(actionName)) {
// Get the file from the project space to create the output
String filename = getName().replaceAll("\\s+", "_") + "_" + getId()
+ ".inp";
// Get the file path and build the URI that will be used to write
IFile outputFile = project.getFile(filename);
// Get the data from the form
ArrayList<Component> components = form.getComponents();
// A valid VibeModel needs 4 components
if (components.size() > 0) {
// create a new IPSWriter with the output file
INIWriter writer = (INIWriter) ioService.getWriter("INIWriter");
writer.setSectionPattern("!", " ");
try {
// Write the output file
writer.write(form, outputFile);
// Refresh the project space
project.refreshLocal(IResource.DEPTH_ONE, null);
} catch (CoreException e) {
// Complain
System.err.println("ProteusModel Message: "
+ "Failed to refresh the project space.");
logger.error(getClass().getName() + " Exception!",e);
}
// return a success
retStatus = FormStatus.Processed;
} else {
// return an error
System.err.println("Not enough components to write new file!");
retStatus = FormStatus.InfoError;
}
} else {
retStatus = super.process(actionName);
}
return retStatus;
} | FormStatus function(String actionName) { FormStatus retStatus; if (PROTEUSModel.proteusProcessActionString.equals(actionName)) { String filename = getName().replaceAll("\\s+", "_") + "_" + getId() + ".inp"; IFile outputFile = project.getFile(filename); ArrayList<Component> components = form.getComponents(); if (components.size() > 0) { INIWriter writer = (INIWriter) ioService.getWriter(STR); writer.setSectionPattern("!", " "); try { writer.write(form, outputFile); project.refreshLocal(IResource.DEPTH_ONE, null); } catch (CoreException e) { System.err.println(STR + STR); logger.error(getClass().getName() + STR,e); } retStatus = FormStatus.Processed; } else { System.err.println(STR); retStatus = FormStatus.InfoError; } } else { retStatus = super.process(actionName); } return retStatus; } | /**
* <p>
* This operation creates the PROTEUS input file.
* </p>
*
* @param actionName
* The name of action that should be performed using the
* processed Form data.
* @return The status of the Item after processing the Form and executing
* the action. It returns FormStatus.InfoError if it is unable to
* run for any reason, including being asked to run actions that are
* not in the list of available actions.
*/ | This operation creates the PROTEUS input file. | process | {
"repo_name": "gorindn/ice",
"path": "src/org.eclipse.ice.proteus/src/org/eclipse/ice/proteus/PROTEUSModel.java",
"license": "epl-1.0",
"size": 9566
} | [
"java.util.ArrayList",
"org.eclipse.core.resources.IFile",
"org.eclipse.core.resources.IResource",
"org.eclipse.core.runtime.CoreException",
"org.eclipse.ice.datastructures.ICEObject",
"org.eclipse.ice.datastructures.form.FormStatus",
"org.eclipse.ice.io.ini.INIWriter"
] | import java.util.ArrayList; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.ice.datastructures.ICEObject; import org.eclipse.ice.datastructures.form.FormStatus; import org.eclipse.ice.io.ini.INIWriter; | import java.util.*; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.ice.datastructures.*; import org.eclipse.ice.datastructures.form.*; import org.eclipse.ice.io.ini.*; | [
"java.util",
"org.eclipse.core",
"org.eclipse.ice"
] | java.util; org.eclipse.core; org.eclipse.ice; | 1,459,520 |
public MaprElasticSearchService build() {
ensureFieldNonNull("port", this.port);
ensureFieldNonNull("hostname", this.inetAddress);
ensureFieldNonNull("indexName", this.indexName);
ensureFieldNonNull("typeName", this.typeName);
ensureFieldNonNull("changelog", this.changelog);
ensureFieldNonNull("fields", this.fields);
return () -> {
// Create ES Client
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(inetAddress, port));
// Create CDC Listener
ChangelogListener listener = ChangelogListenerImpl.forChangelog(changelog);
// Set 'onInsert' callback
listener.onInsert(new SaveIndexCDCCallback(client));
// Set 'onUpdate' callback
listener.onUpdate(new SaveIndexCDCCallback(client));
// Define and set 'onDelete' callback
listener.onDelete((id) -> client.prepareDelete(indexName, typeName, id).get());
listener.listen();
};
} | MaprElasticSearchService function() { ensureFieldNonNull("port", this.port); ensureFieldNonNull(STR, this.inetAddress); ensureFieldNonNull(STR, this.indexName); ensureFieldNonNull(STR, this.typeName); ensureFieldNonNull(STR, this.changelog); ensureFieldNonNull(STR, this.fields); return () -> { TransportClient client = new PreBuiltTransportClient(Settings.EMPTY) .addTransportAddress(new InetSocketTransportAddress(inetAddress, port)); ChangelogListener listener = ChangelogListenerImpl.forChangelog(changelog); listener.onInsert(new SaveIndexCDCCallback(client)); listener.onUpdate(new SaveIndexCDCCallback(client)); listener.onDelete((id) -> client.prepareDelete(indexName, typeName, id).get()); listener.listen(); }; } | /**
* Builds the {@link MaprElasticSearchService} according to the specified properties.
*
* @return instence of {@link MaprElasticSearchService}, which can be started via {@link MaprElasticSearchService#start()}.
* @throws IllegalStateException in case when some of the required properties are missed.
*/ | Builds the <code>MaprElasticSearchService</code> according to the specified properties | build | {
"repo_name": "mapr-demos/mapr-music",
"path": "elasticsearch-service/src/main/java/com/mapr/elasticsearch/service/service/MaprElasticSearchServiceBuilder.java",
"license": "apache-2.0",
"size": 9248
} | [
"com.mapr.elasticsearch.service.listener.ChangelogListener",
"com.mapr.elasticsearch.service.listener.impl.ChangelogListenerImpl",
"org.elasticsearch.client.transport.TransportClient",
"org.elasticsearch.common.settings.Settings",
"org.elasticsearch.common.transport.InetSocketTransportAddress",
"org.elasticsearch.transport.client.PreBuiltTransportClient"
] | import com.mapr.elasticsearch.service.listener.ChangelogListener; import com.mapr.elasticsearch.service.listener.impl.ChangelogListenerImpl; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.transport.client.PreBuiltTransportClient; | import com.mapr.elasticsearch.service.listener.*; import com.mapr.elasticsearch.service.listener.impl.*; import org.elasticsearch.client.transport.*; import org.elasticsearch.common.settings.*; import org.elasticsearch.common.transport.*; import org.elasticsearch.transport.client.*; | [
"com.mapr.elasticsearch",
"org.elasticsearch.client",
"org.elasticsearch.common",
"org.elasticsearch.transport"
] | com.mapr.elasticsearch; org.elasticsearch.client; org.elasticsearch.common; org.elasticsearch.transport; | 313,920 |
String execute(List<String> parameterList, TestContext context); | String execute(List<String> parameterList, TestContext context); | /**
* Method called on execution.
*
* @param parameterList list of function arguments.
* @param context
* @return function result as string.
*/ | Method called on execution | execute | {
"repo_name": "christophd/citrus",
"path": "core/citrus-api/src/main/java/com/consol/citrus/functions/Function.java",
"license": "apache-2.0",
"size": 2038
} | [
"com.consol.citrus.context.TestContext",
"java.util.List"
] | import com.consol.citrus.context.TestContext; import java.util.List; | import com.consol.citrus.context.*; import java.util.*; | [
"com.consol.citrus",
"java.util"
] | com.consol.citrus; java.util; | 998,414 |
protected void firePacketSendingListeners(Packet packet) {
// Notify the listeners of the new sent packet
for (ListenerWrapper listenerWrapper : sendListeners.values()) {
listenerWrapper.notifyListener(packet);
}
} | void function(Packet packet) { for (ListenerWrapper listenerWrapper : sendListeners.values()) { listenerWrapper.notifyListener(packet); } } | /**
* Process all packet listeners for sending packets.
*
* @param packet the packet to process.
*/ | Process all packet listeners for sending packets | firePacketSendingListeners | {
"repo_name": "JackieFlower/androidpn-client1.2.1test0605",
"path": "asmack/org/jivesoftware/smack/Connection.java",
"license": "apache-2.0",
"size": 34375
} | [
"org.jivesoftware.smack.packet.Packet"
] | import org.jivesoftware.smack.packet.Packet; | import org.jivesoftware.smack.packet.*; | [
"org.jivesoftware.smack"
] | org.jivesoftware.smack; | 1,950,934 |
public String setFileName(String path) {
if(path==null) {
fileName = null;
} else {
fileName = XML.getPathRelativeTo(path, Launcher.tabSetBasePath);
}
return fileName;
} | String function(String path) { if(path==null) { fileName = null; } else { fileName = XML.getPathRelativeTo(path, Launcher.tabSetBasePath); } return fileName; } | /**
* Sets the fileName. Accepts relative paths or
* will convert absolute paths to relative.
*
* @param path the path to the file
* @return the file name
*/ | Sets the fileName. Accepts relative paths or will convert absolute paths to relative | setFileName | {
"repo_name": "OpenSourcePhysics/osp",
"path": "src/org/opensourcephysics/tools/LaunchNode.java",
"license": "gpl-3.0",
"size": 58827
} | [
"org.opensourcephysics.controls.XML"
] | import org.opensourcephysics.controls.XML; | import org.opensourcephysics.controls.*; | [
"org.opensourcephysics.controls"
] | org.opensourcephysics.controls; | 1,952,953 |
public void loadScripts() {
NodeList scripts = document.getElementsByTagNameNS
(SVGConstants.SVG_NAMESPACE_URI, SVGConstants.SVG_SCRIPT_TAG);
int len = scripts.getLength();
for (int i = 0; i < len; i++) {
AbstractElement script = (AbstractElement) scripts.item(i);
loadScript(script);
}
} | void function() { NodeList scripts = document.getElementsByTagNameNS (SVGConstants.SVG_NAMESPACE_URI, SVGConstants.SVG_SCRIPT_TAG); int len = scripts.getLength(); for (int i = 0; i < len; i++) { AbstractElement script = (AbstractElement) scripts.item(i); loadScript(script); } } | /**
* Loads the scripts contained in the <script> elements.
*/ | Loads the scripts contained in the <script> elements | loadScripts | {
"repo_name": "apache/batik",
"path": "batik-bridge/src/main/java/org/apache/batik/bridge/BaseScriptingEnvironment.java",
"license": "apache-2.0",
"size": 31241
} | [
"org.apache.batik.dom.AbstractElement",
"org.apache.batik.util.SVGConstants",
"org.w3c.dom.NodeList"
] | import org.apache.batik.dom.AbstractElement; import org.apache.batik.util.SVGConstants; import org.w3c.dom.NodeList; | import org.apache.batik.dom.*; import org.apache.batik.util.*; import org.w3c.dom.*; | [
"org.apache.batik",
"org.w3c.dom"
] | org.apache.batik; org.w3c.dom; | 2,585,338 |
@VisibleForTesting
static Map<String, String> getMapping(List<String> variables,
Map<String, String> environment) {
Map<String, String> result = new HashMap<>();
for (String var : variables) {
if (environment.containsKey(var)) {
result.put(var, environment.get(var));
}
}
return result;
} | static Map<String, String> getMapping(List<String> variables, Map<String, String> environment) { Map<String, String> result = new HashMap<>(); for (String var : variables) { if (environment.containsKey(var)) { result.put(var, environment.get(var)); } } return result; } | /**
* For an given environment, returns a subset containing all
* variables in the given list if they are defined in the given
* environment.
*/ | For an given environment, returns a subset containing all variables in the given list if they are defined in the given environment | getMapping | {
"repo_name": "vt09/bazel",
"path": "src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java",
"license": "apache-2.0",
"size": 92111
} | [
"java.util.HashMap",
"java.util.List",
"java.util.Map"
] | import java.util.HashMap; import java.util.List; import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 1,573,034 |
public void setMapSize(int mapWidth, int mapHeight) {
double x = horizontalMargin;
double y = verticalMargin;
// Calculate horizontal position:
switch (alignment) {
case LEFT:
break;
case CENTER:
x = Math.round((mapWidth - width) / 2);
break;
case RIGHT:
x = mapWidth - width - horizontalMargin;
}
// Calculate vertical position:
switch (verticalAlignment) {
case TOP:
break;
case CENTER:
y = Math.round((mapHeight - height) / 2);
break;
case BOTTOM:
y = mapHeight - height - verticalMargin;
}
upperLeftCorner = new Coordinate(x, y);
} | void function(int mapWidth, int mapHeight) { double x = horizontalMargin; double y = verticalMargin; switch (alignment) { case LEFT: break; case CENTER: x = Math.round((mapWidth - width) / 2); break; case RIGHT: x = mapWidth - width - horizontalMargin; } switch (verticalAlignment) { case TOP: break; case CENTER: y = Math.round((mapHeight - height) / 2); break; case BOTTOM: y = mapHeight - height - verticalMargin; } upperLeftCorner = new Coordinate(x, y); } | /**
* Apply a new width and height for the map onto whom this add-on is drawn. This method is triggered automatically
* when the map resizes.
*
* @param mapWidth
* The map's new width.
* @param mapHeight
* The map's new height.
*/ | Apply a new width and height for the map onto whom this add-on is drawn. This method is triggered automatically when the map resizes | setMapSize | {
"repo_name": "geomajas/geomajas-project-client-gwt",
"path": "client/src/main/java/org/geomajas/gwt/client/gfx/paintable/mapaddon/MapAddon.java",
"license": "agpl-3.0",
"size": 6523
} | [
"org.geomajas.geometry.Coordinate"
] | import org.geomajas.geometry.Coordinate; | import org.geomajas.geometry.*; | [
"org.geomajas.geometry"
] | org.geomajas.geometry; | 2,392,433 |
public Connection getConnection() throws IOException {
if (this.connection == null) {
this.connection = ConnectionFactory.createConnection(this.conf);
}
return this.connection;
} | Connection function() throws IOException { if (this.connection == null) { this.connection = ConnectionFactory.createConnection(this.conf); } return this.connection; } | /**
* Get a Connection to the cluster.
* Not thread-safe (This class needs a lot of work to make it thread-safe).
* @return A Connection that can be shared. Don't close. Will be closed on shutdown of cluster.
* @throws IOException
*/ | Get a Connection to the cluster. Not thread-safe (This class needs a lot of work to make it thread-safe) | getConnection | {
"repo_name": "juwi/hbase",
"path": "hbase-server/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java",
"license": "apache-2.0",
"size": 151512
} | [
"java.io.IOException",
"org.apache.hadoop.hbase.client.Connection",
"org.apache.hadoop.hbase.client.ConnectionFactory"
] | import java.io.IOException; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; | import java.io.*; import org.apache.hadoop.hbase.client.*; | [
"java.io",
"org.apache.hadoop"
] | java.io; org.apache.hadoop; | 95,163 |
public void convertResultCurrencyUsingReportingRules() {
double[] values = {1, 2, 3};
List<FxRate> rates = ImmutableList.of(1.61, 1.62, 1.63).stream()
.map(rate -> FxRate.of(Currency.GBP, Currency.USD, rate))
.collect(toImmutableList());
CurrencyValuesArray list = CurrencyValuesArray.of(Currency.GBP, values);
ScenarioCalculationEnvironment marketData = ScenarioCalculationEnvironment.builder(3, date(2011, 3, 8))
.addValues(FxRateId.of(Currency.GBP, Currency.USD), rates)
.build();
ConvertibleFunction fn = ConvertibleFunction.of(() -> list);
CalculationTask task = new CalculationTask(TARGET, 0, 0, fn, MAPPINGS, REPORTING_RULES);
double[] expectedValues = {1 * 1.61, 2 * 1.62, 3 * 1.63};
CurrencyValuesArray expectedArray = CurrencyValuesArray.of(Currency.USD, expectedValues);
CalculationResult calculationResult = task.execute(marketData);
Result<?> result = calculationResult.getResult();
assertThat(result).hasValue(expectedArray);
} | void function() { double[] values = {1, 2, 3}; List<FxRate> rates = ImmutableList.of(1.61, 1.62, 1.63).stream() .map(rate -> FxRate.of(Currency.GBP, Currency.USD, rate)) .collect(toImmutableList()); CurrencyValuesArray list = CurrencyValuesArray.of(Currency.GBP, values); ScenarioCalculationEnvironment marketData = ScenarioCalculationEnvironment.builder(3, date(2011, 3, 8)) .addValues(FxRateId.of(Currency.GBP, Currency.USD), rates) .build(); ConvertibleFunction fn = ConvertibleFunction.of(() -> list); CalculationTask task = new CalculationTask(TARGET, 0, 0, fn, MAPPINGS, REPORTING_RULES); double[] expectedValues = {1 * 1.61, 2 * 1.62, 3 * 1.63}; CurrencyValuesArray expectedArray = CurrencyValuesArray.of(Currency.USD, expectedValues); CalculationResult calculationResult = task.execute(marketData); Result<?> result = calculationResult.getResult(); assertThat(result).hasValue(expectedArray); } | /**
* Test that the result is converted to the reporting currency if it implements CurrencyConvertible and
* the FX rates are available in the market data. The reporting currency is taken from the reporting rules.
*/ | Test that the result is converted to the reporting currency if it implements CurrencyConvertible and the FX rates are available in the market data. The reporting currency is taken from the reporting rules | convertResultCurrencyUsingReportingRules | {
"repo_name": "nssales/Strata",
"path": "modules/engine/src/test/java/com/opengamma/strata/engine/calculation/CalculationTaskTest.java",
"license": "apache-2.0",
"size": 16479
} | [
"com.google.common.collect.ImmutableList",
"com.opengamma.strata.basics.currency.Currency",
"com.opengamma.strata.basics.currency.FxRate",
"com.opengamma.strata.basics.market.FxRateId",
"com.opengamma.strata.collect.CollectProjectAssertions",
"com.opengamma.strata.collect.TestHelper",
"com.opengamma.strata.collect.result.Result",
"com.opengamma.strata.engine.calculation.function.result.CurrencyValuesArray",
"com.opengamma.strata.engine.marketdata.ScenarioCalculationEnvironment",
"java.util.List",
"org.assertj.core.api.Assertions"
] | import com.google.common.collect.ImmutableList; import com.opengamma.strata.basics.currency.Currency; import com.opengamma.strata.basics.currency.FxRate; import com.opengamma.strata.basics.market.FxRateId; import com.opengamma.strata.collect.CollectProjectAssertions; import com.opengamma.strata.collect.TestHelper; import com.opengamma.strata.collect.result.Result; import com.opengamma.strata.engine.calculation.function.result.CurrencyValuesArray; import com.opengamma.strata.engine.marketdata.ScenarioCalculationEnvironment; import java.util.List; import org.assertj.core.api.Assertions; | import com.google.common.collect.*; import com.opengamma.strata.basics.currency.*; import com.opengamma.strata.basics.market.*; import com.opengamma.strata.collect.*; import com.opengamma.strata.collect.result.*; import com.opengamma.strata.engine.calculation.function.result.*; import com.opengamma.strata.engine.marketdata.*; import java.util.*; import org.assertj.core.api.*; | [
"com.google.common",
"com.opengamma.strata",
"java.util",
"org.assertj.core"
] | com.google.common; com.opengamma.strata; java.util; org.assertj.core; | 2,433,251 |
@Override
public Class<OauthRefreshTokenRecord> getRecordType() {
return OauthRefreshTokenRecord.class;
}
public final TableField<OauthRefreshTokenRecord, String> TOKEN_ID = createField("token_id", org.jooq.impl.SQLDataType.VARCHAR(256), this, "");
public final TableField<OauthRefreshTokenRecord, byte[]> TOKEN = createField("token", org.jooq.impl.SQLDataType.BLOB, this, "");
public final TableField<OauthRefreshTokenRecord, byte[]> AUTHENTICATION = createField("authentication", org.jooq.impl.SQLDataType.BLOB, this, "");
public OauthRefreshToken() {
this(DSL.name("oauth_refresh_token"), null);
}
public OauthRefreshToken(String alias) {
this(DSL.name(alias), OAUTH_REFRESH_TOKEN);
}
public OauthRefreshToken(Name alias) {
this(alias, OAUTH_REFRESH_TOKEN);
}
private OauthRefreshToken(Name alias, Table<OauthRefreshTokenRecord> aliased) {
this(alias, aliased, null);
}
private OauthRefreshToken(Name alias, Table<OauthRefreshTokenRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, "");
}
/**
* {@inheritDoc} | Class<OauthRefreshTokenRecord> function() { return OauthRefreshTokenRecord.class; } public final TableField<OauthRefreshTokenRecord, String> TOKEN_ID = createField(STR, org.jooq.impl.SQLDataType.VARCHAR(256), this, STRtokenSTRSTRauthenticationSTRSTRoauth_refresh_tokenSTR"); } /** * {@inheritDoc} | /**
* The class holding records for this type
*/ | The class holding records for this type | getRecordType | {
"repo_name": "zbeboy/ISY",
"path": "src/main/java/top/zbeboy/isy/domain/tables/OauthRefreshToken.java",
"license": "mit",
"size": 3456
} | [
"org.jooq.TableField",
"top.zbeboy.isy.domain.tables.records.OauthRefreshTokenRecord"
] | import org.jooq.TableField; import top.zbeboy.isy.domain.tables.records.OauthRefreshTokenRecord; | import org.jooq.*; import top.zbeboy.isy.domain.tables.records.*; | [
"org.jooq",
"top.zbeboy.isy"
] | org.jooq; top.zbeboy.isy; | 2,080,598 |
void addOrUpdateBundleRecords(List<ModulePropertiesRecord> records); | void addOrUpdateBundleRecords(List<ModulePropertiesRecord> records); | /**
* Bulk add or update method for the Bundle Properties records. Iterates through
* the passed records and either adds them, if they are not present, or updates otherwise.
*
* @param records a list of properties records
*/ | Bulk add or update method for the Bundle Properties records. Iterates through the passed records and either adds them, if they are not present, or updates otherwise | addOrUpdateBundleRecords | {
"repo_name": "smalecki/motech",
"path": "platform/server-config/src/main/java/org/motechproject/config/service/ConfigurationService.java",
"license": "bsd-3-clause",
"size": 13199
} | [
"java.util.List",
"org.motechproject.config.domain.ModulePropertiesRecord"
] | import java.util.List; import org.motechproject.config.domain.ModulePropertiesRecord; | import java.util.*; import org.motechproject.config.domain.*; | [
"java.util",
"org.motechproject.config"
] | java.util; org.motechproject.config; | 368,877 |
public void cancel()
{
for(BukkitRunnable thread : threads)
{
try
{
thread.cancel();
}
catch(Exception e){}
}
} | void function() { for(BukkitRunnable thread : threads) { try { thread.cancel(); } catch(Exception e){} } } | /**
* Cancels all of the threads in the sequence
*/ | Cancels all of the threads in the sequence | cancel | {
"repo_name": "Kloudy/Slots",
"path": "src/com/antarescraft/kloudy/slots/util/BukkitIntervalRunnableScheduler.java",
"license": "apache-2.0",
"size": 2189
} | [
"org.bukkit.scheduler.BukkitRunnable"
] | import org.bukkit.scheduler.BukkitRunnable; | import org.bukkit.scheduler.*; | [
"org.bukkit.scheduler"
] | org.bukkit.scheduler; | 574,884 |
public static byte[] decode(
byte[] data)
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try
{
encoder.decode(data, 0, data.length, bOut);
}
catch (IOException e)
{
throw new RuntimeException("exception decoding Hex string: " + e);
}
return bOut.toByteArray();
} | static byte[] function( byte[] data) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.decode(data, 0, data.length, bOut); } catch (IOException e) { throw new RuntimeException(STR + e); } return bOut.toByteArray(); } | /**
* decode the Hex encoded input data. It is assumed the input data is valid.
*
* @return a byte array representing the decoded data.
*/ | decode the Hex encoded input data. It is assumed the input data is valid | decode | {
"repo_name": "Z-Shang/onscripter-gbk",
"path": "svn/onscripter-read-only/src/org/bouncycastle/util/encoders/Hex.java",
"license": "gpl-2.0",
"size": 3300
} | [
"java.io.ByteArrayOutputStream",
"java.io.IOException"
] | import java.io.ByteArrayOutputStream; import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 1,771,110 |
@Override
protected double predictedReduction( DenseMatrix64F param, DenseMatrix64F gradientNegative , double mu ) {
double p_dot_p = VectorVectorMult.innerProd(param,param);
double p_dot_g = VectorVectorMult.innerProd(param,gradientNegative);
return 0.5*(mu*p_dot_p + p_dot_g);
} | double function( DenseMatrix64F param, DenseMatrix64F gradientNegative , double mu ) { double p_dot_p = VectorVectorMult.innerProd(param,param); double p_dot_g = VectorVectorMult.innerProd(param,gradientNegative); return 0.5*(mu*p_dot_p + p_dot_g); } | /**
* compute the change predicted by the model
*
* m_k(0) - m_k(p_k) = -g_k'*p - 0.5*p'*B*p
* (J'*J+mu*I)*p = -J'*r = -g
*
* @return predicted reduction
*/ | compute the change predicted by the model m_k(0) - m_k(p_k) = -g_k'*p - 0.5*p'*B*p (J'*J+mu*I)*p = -J'*r = -g | predictedReduction | {
"repo_name": "bladestery/Sapphire",
"path": "example_apps/AndroidStudioMinnie/sapphire/src/main/java/org/ddogleg/optimization/impl/LevenbergDampened.java",
"license": "mit",
"size": 5008
} | [
"org.ejml.alg.dense.mult.VectorVectorMult",
"org.ejml.data.DenseMatrix64F"
] | import org.ejml.alg.dense.mult.VectorVectorMult; import org.ejml.data.DenseMatrix64F; | import org.ejml.alg.dense.mult.*; import org.ejml.data.*; | [
"org.ejml.alg",
"org.ejml.data"
] | org.ejml.alg; org.ejml.data; | 1,173,936 |
public void addPruneTagNodeCondition(ITagNodeCondition condition){
pruneTagSet.add(condition);
} | void function(ITagNodeCondition condition){ pruneTagSet.add(condition); } | /**
* Adds the condition to existing prune tag set.
*
* @param condition
*/ | Adds the condition to existing prune tag set | addPruneTagNodeCondition | {
"repo_name": "finanzer/epubfx",
"path": "src/main/java/de/machmireinebook/epubeditor/htmlcleaner/CleanerProperties.java",
"license": "apache-2.0",
"size": 18125
} | [
"de.machmireinebook.epubeditor.htmlcleaner.conditional.ITagNodeCondition"
] | import de.machmireinebook.epubeditor.htmlcleaner.conditional.ITagNodeCondition; | import de.machmireinebook.epubeditor.htmlcleaner.conditional.*; | [
"de.machmireinebook.epubeditor"
] | de.machmireinebook.epubeditor; | 1,678,161 |
public QuestionPoolDataIfc getData(){
return this.data;
} | QuestionPoolDataIfc function(){ return this.data; } | /**
* Get the data for this QuestionPoolFacade.
* @return QuestionPoolDataIfc
*/ | Get the data for this QuestionPoolFacade | getData | {
"repo_name": "payten/nyu-sakai-10.4",
"path": "samigo/samigo-services/src/java/org/sakaiproject/tool/assessment/facade/QuestionPoolFacade.java",
"license": "apache-2.0",
"size": 23703
} | [
"org.sakaiproject.tool.assessment.data.ifc.questionpool.QuestionPoolDataIfc"
] | import org.sakaiproject.tool.assessment.data.ifc.questionpool.QuestionPoolDataIfc; | import org.sakaiproject.tool.assessment.data.ifc.questionpool.*; | [
"org.sakaiproject.tool"
] | org.sakaiproject.tool; | 2,367,555 |
public void setBackgroundColor(ColorRGBA c) {
// if color is null set background to white.
if (c == null) {
backgroundColor.a = 1.0f;
backgroundColor.b = 1.0f;
backgroundColor.g = 1.0f;
backgroundColor.r = 1.0f;
} else {
backgroundColor = c;
}
if (!isSupported) {
return;
}
try {
activate();
GL11.glClearColor(backgroundColor.r, backgroundColor.g,
backgroundColor.b, backgroundColor.a);
}
finally {
deactivate();
}
} | void function(ColorRGBA c) { if (c == null) { backgroundColor.a = 1.0f; backgroundColor.b = 1.0f; backgroundColor.g = 1.0f; backgroundColor.r = 1.0f; } else { backgroundColor = c; } if (!isSupported) { return; } try { activate(); GL11.glClearColor(backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a); } finally { deactivate(); } } | /**
* <code>setBackgroundColor</code> sets the OpenGL clear color to the
* color specified.
*
* @see com.jme.renderer.TextureRenderer#setBackgroundColor(com.jme.renderer.ColorRGBA)
* @param c
* the color to set the background color to.
*/ | <code>setBackgroundColor</code> sets the OpenGL clear color to the color specified | setBackgroundColor | {
"repo_name": "tectronics/xenogeddon",
"path": "src/com/jme/renderer/lwjgl/LWJGLPbufferTextureRenderer.java",
"license": "gpl-2.0",
"size": 27888
} | [
"com.jme.renderer.ColorRGBA"
] | import com.jme.renderer.ColorRGBA; | import com.jme.renderer.*; | [
"com.jme.renderer"
] | com.jme.renderer; | 2,692,421 |
ImmutableCollection<V> values(); | ImmutableCollection<V> values(); | /**
* Retrieves an {@link ImmutableCollection} of all available values within
* this map.
*
* @return The collection of values
*/ | Retrieves an <code>ImmutableCollection</code> of all available values within this map | values | {
"repo_name": "jonk1993/SpongeAPI",
"path": "src/main/java/org/spongepowered/api/data/value/immutable/ImmutableMapValue.java",
"license": "mit",
"size": 5107
} | [
"com.google.common.collect.ImmutableCollection"
] | import com.google.common.collect.ImmutableCollection; | import com.google.common.collect.*; | [
"com.google.common"
] | com.google.common; | 2,692,023 |
public void addPatterns(final Collection<? extends String> stringPatterns) {
if (stringPatterns != null && !stringPatterns.isEmpty()) {
for (String stringPattern : stringPatterns) {
if (stringPattern != null && !stringPattern.isEmpty()) {
stringPattern = stringPattern.trim();
if (!stringPattern.isEmpty() && !stringPattern.startsWith("#")) {
if (stringPattern.equals("!") || stringPattern.equals("/")) {
throw new IllegalArgumentException("invalid pattern: " + stringPattern);
} else if (stringPattern.contains("**")) {
throw new IllegalArgumentException("invalid pattern: " + stringPattern + " (double-star (**) syntax is not supported)"); // see rules.go
}
final boolean negate;
if (stringPattern.startsWith("!")) {
assert stringPattern.length() > 1;
negate = true;
stringPattern = stringPattern.substring(1);
} else {
negate = false;
}
final boolean requireDirectory;
if (stringPattern.endsWith("/")) {
assert stringPattern.length() > 1;
requireDirectory = true;
stringPattern = stringPattern.substring(0, stringPattern.length() - 1);
} else {
requireDirectory = false;
}
final boolean basename;
final int firstSlashIndex = stringPattern.indexOf('/');
if (firstSlashIndex < 0) {
basename = true;
} else {
if (firstSlashIndex == 0) {
assert stringPattern.length() > 1;
stringPattern = stringPattern.substring(1);
}
basename = false;
}
final StringBuilder regex = new StringBuilder("^");
final char[] chars = stringPattern.toCharArray();
assert chars != null;
assert chars.length > 0;
final int length = chars.length;
for (int i = 0; i < length; i++) {
final char c = chars[i];
switch (c) {
case '.':
regex.append("\\.");
break;
case '*':
regex.append("[^").append(File.separator).append("]*");
break;
case '?':
regex.append("[^").append(File.separator).append("]?");
break;
default:
regex.append(c);
break;
}
}
regex.append("$");
final Predicate<Path> rule = new RegexRule(Pattern.compile(regex.toString()), requireDirectory, basename);
synchronized (this.rules) {
this.rules.add(negate ? rule.negate() : rule);
}
}
}
}
}
}
/**
* Calls the {@link #matches(Path)} method with the supplied {@link
* Path} and returns its results.
*
* @param path a {@link Path} to test; may be {@code null} | void function(final Collection<? extends String> stringPatterns) { if (stringPatterns != null && !stringPatterns.isEmpty()) { for (String stringPattern : stringPatterns) { if (stringPattern != null && !stringPattern.isEmpty()) { stringPattern = stringPattern.trim(); if (!stringPattern.isEmpty() && !stringPattern.startsWith("#")) { if (stringPattern.equals("!") stringPattern.equals("/")) { throw new IllegalArgumentException(STR + stringPattern); } else if (stringPattern.contains("**")) { throw new IllegalArgumentException(STR + stringPattern + STR); } final boolean negate; if (stringPattern.startsWith("!")) { assert stringPattern.length() > 1; negate = true; stringPattern = stringPattern.substring(1); } else { negate = false; } final boolean requireDirectory; if (stringPattern.endsWith("/")) { assert stringPattern.length() > 1; requireDirectory = true; stringPattern = stringPattern.substring(0, stringPattern.length() - 1); } else { requireDirectory = false; } final boolean basename; final int firstSlashIndex = stringPattern.indexOf('/'); if (firstSlashIndex < 0) { basename = true; } else { if (firstSlashIndex == 0) { assert stringPattern.length() > 1; stringPattern = stringPattern.substring(1); } basename = false; } final StringBuilder regex = new StringBuilder("^"); final char[] chars = stringPattern.toCharArray(); assert chars != null; assert chars.length > 0; final int length = chars.length; for (int i = 0; i < length; i++) { final char c = chars[i]; switch (c) { case '.': regex.append("\\."); break; case '*': regex.append("[^").append(File.separator).append("]*"); break; case '?': regex.append("[^").append(File.separator).append("]?"); break; default: regex.append(c); break; } } regex.append("$"); final Predicate<Path> rule = new RegexRule(Pattern.compile(regex.toString()), requireDirectory, basename); synchronized (this.rules) { this.rules.add(negate ? rule.negate() : rule); } } } } } } /** * Calls the {@link #matches(Path)} method with the supplied { * Path} and returns its results. * * @param path a {@link Path} to test; may be {@code null} | /**
* Adds all of the <a
* href="http://godoc.org/k8s.io/helm/pkg/ignore">valid {@code
* .helmignore} patterns</a> present in the supplied {@link
* Collection} of such patterns.
*
* <p>Overrides must not call {@link #addPattern(String)}.</p>
*
* @param stringPatterns a {@link Collection} of <a
* href="http://godoc.org/k8s.io/helm/pkg/ignore">valid {@code
* .helmignore} patterns</a>; may be {@code null} in which case no
* action will be taken
*
* @see #matches(Path)
*/ | Adds all of the valid .helmignore patterns present in the supplied <code>Collection</code> of such patterns. Overrides must not call <code>#addPattern(String)</code> | addPatterns | {
"repo_name": "microbean/microbean-helm",
"path": "src/main/java/org/microbean/helm/chart/HelmIgnorePathMatcher.java",
"license": "apache-2.0",
"size": 15513
} | [
"java.io.File",
"java.nio.file.Path",
"java.util.Collection",
"java.util.function.Predicate",
"java.util.regex.Pattern"
] | import java.io.File; import java.nio.file.Path; import java.util.Collection; import java.util.function.Predicate; import java.util.regex.Pattern; | import java.io.*; import java.nio.file.*; import java.util.*; import java.util.function.*; import java.util.regex.*; | [
"java.io",
"java.nio",
"java.util"
] | java.io; java.nio; java.util; | 2,192,089 |
private void showWelcomeView() {
new ViewLoader().displayPane("welcomeView.fxml");
} | void function() { new ViewLoader().displayPane(STR); } | /**
* Shows the welcome view inside the root layout.
*/ | Shows the welcome view inside the root layout | showWelcomeView | {
"repo_name": "stef78ano/winebrewdb",
"path": "src/main/java/uk/co/pbellchambers/winebrewdb/MainApp.java",
"license": "apache-2.0",
"size": 3877
} | [
"uk.co.pbellchambers.winebrewdb.util.ViewLoader"
] | import uk.co.pbellchambers.winebrewdb.util.ViewLoader; | import uk.co.pbellchambers.winebrewdb.util.*; | [
"uk.co.pbellchambers"
] | uk.co.pbellchambers; | 855,473 |
private static PeakListRow copyPeakRow(final PeakListRow row) {
// Copy the peak list row.
final PeakListRow newRow = new SimplePeakListRow(row.getID());
PeakUtils.copyPeakListRowProperties(row, newRow);
// Copy the peaks.
for (final Feature peak : row.getPeaks()) {
final Feature newPeak = new SimpleFeature(peak);
PeakUtils.copyPeakProperties(peak, newPeak);
newRow.addPeak(peak.getDataFile(), newPeak);
}
return newRow;
} | static PeakListRow function(final PeakListRow row) { final PeakListRow newRow = new SimplePeakListRow(row.getID()); PeakUtils.copyPeakListRowProperties(row, newRow); for (final Feature peak : row.getPeaks()) { final Feature newPeak = new SimpleFeature(peak); PeakUtils.copyPeakProperties(peak, newPeak); newRow.addPeak(peak.getDataFile(), newPeak); } return newRow; } | /**
* Create a copy of a peak list row.
*/ | Create a copy of a peak list row | copyPeakRow | {
"repo_name": "DrewG/mzmine2",
"path": "src/main/java/net/sf/mzmine/modules/peaklistmethods/io/gnpsexport/GNPSExportTask.java",
"license": "gpl-2.0",
"size": 6753
} | [
"net.sf.mzmine.datamodel.Feature",
"net.sf.mzmine.datamodel.PeakListRow",
"net.sf.mzmine.datamodel.impl.SimpleFeature",
"net.sf.mzmine.datamodel.impl.SimplePeakListRow",
"net.sf.mzmine.util.PeakUtils"
] | import net.sf.mzmine.datamodel.Feature; import net.sf.mzmine.datamodel.PeakListRow; import net.sf.mzmine.datamodel.impl.SimpleFeature; import net.sf.mzmine.datamodel.impl.SimplePeakListRow; import net.sf.mzmine.util.PeakUtils; | import net.sf.mzmine.datamodel.*; import net.sf.mzmine.datamodel.impl.*; import net.sf.mzmine.util.*; | [
"net.sf.mzmine"
] | net.sf.mzmine; | 114,230 |
String createBackupFilename(File file, String subDirectorySuffix, boolean saveBackupDate, boolean reusePreviousBackupDate, String suffixToUse)
throws IOException {
String filenameLong = file.getAbsolutePath(); // Full path.
String filenameShort = file.getName(); // Just the filename.
String topLevelBackupDirectoryName = calculateTopLevelBackupDirectoryName(file);
createDirectoryIfNecessary(topLevelBackupDirectoryName);
// Find suffix and stems of filename.
int suffixSeparatorLong = filenameLong.lastIndexOf('.');
String stemLong = filenameLong.substring(0, suffixSeparatorLong);
int suffixSeparatorShort= filenameShort.lastIndexOf('.');
String stemShort = filenameShort.substring(0, suffixSeparatorShort);
String suffix;
if (suffixToUse != null) {
suffix = "." + suffixToUse;
} else {
suffix = filenameLong.substring(suffixSeparatorLong); // Includes separating dot.
}
Date backupDateToUse = new Date();
if (saveBackupDate) {
dateForBackupName = backupDateToUse;
}
if (reusePreviousBackupDate) {
backupDateToUse = dateForBackupName;
}
String backupFilename;
if (dateFormat == null) {
dateFormat = new SimpleDateFormat(BACKUP_SUFFIX_FORMAT);
}
if (subDirectorySuffix != null && subDirectorySuffix.length() > 0) {
String backupFilenameShort = stemShort + SEPARATOR + dateFormat.format(backupDateToUse) + suffix;
String subDirectoryName = topLevelBackupDirectoryName + File.separator + subDirectorySuffix;
createDirectoryIfNecessary(subDirectoryName);
backupFilename = subDirectoryName + File.separator + backupFilenameShort;
} else {
backupFilename = stemLong + SEPARATOR + dateFormat.format(backupDateToUse) + suffix;
}
return backupFilename;
} | String createBackupFilename(File file, String subDirectorySuffix, boolean saveBackupDate, boolean reusePreviousBackupDate, String suffixToUse) throws IOException { String filenameLong = file.getAbsolutePath(); String filenameShort = file.getName(); String topLevelBackupDirectoryName = calculateTopLevelBackupDirectoryName(file); createDirectoryIfNecessary(topLevelBackupDirectoryName); int suffixSeparatorLong = filenameLong.lastIndexOf('.'); String stemLong = filenameLong.substring(0, suffixSeparatorLong); int suffixSeparatorShort= filenameShort.lastIndexOf('.'); String stemShort = filenameShort.substring(0, suffixSeparatorShort); String suffix; if (suffixToUse != null) { suffix = "." + suffixToUse; } else { suffix = filenameLong.substring(suffixSeparatorLong); } Date backupDateToUse = new Date(); if (saveBackupDate) { dateForBackupName = backupDateToUse; } if (reusePreviousBackupDate) { backupDateToUse = dateForBackupName; } String backupFilename; if (dateFormat == null) { dateFormat = new SimpleDateFormat(BACKUP_SUFFIX_FORMAT); } if (subDirectorySuffix != null && subDirectorySuffix.length() > 0) { String backupFilenameShort = stemShort + SEPARATOR + dateFormat.format(backupDateToUse) + suffix; String subDirectoryName = topLevelBackupDirectoryName + File.separator + subDirectorySuffix; createDirectoryIfNecessary(subDirectoryName); backupFilename = subDirectoryName + File.separator + backupFilenameShort; } else { backupFilename = stemLong + SEPARATOR + dateFormat.format(backupDateToUse) + suffix; } return backupFilename; } | /**
* Create a backup filename the format is: original file: filename.suffix.
* backup file:
* (without subDirectorySuffix) filename-yyyymmddhhmmss.suffix
* (with subDirectorySuffix) filename-data/subDirectorySuffix/filename-yyyymmddhhmmss.suffix
*
* (Any intermediate directories are automatically created if necessary)
*
* @param file
* @param subDirectorySuffix - subdirectory to add to backup file e.g key-backup. null for no subdirectory.
* @param saveBackupDate - save the backup date for use later
* @param reusePreviousBackupDate
* Reuse the previously created backup date so that wallet and wallet info names match
* @param suffixToUse
* the suffix text to use
* @return String the name of the created filename.
* @throws IOException
*/ | Create a backup filename the format is: original file: filename.suffix. backup file: (without subDirectorySuffix) filename-yyyymmddhhmmss.suffix (with subDirectorySuffix) filename-data/subDirectorySuffix/filename-yyyymmddhhmmss.suffix (Any intermediate directories are automatically created if necessary) | createBackupFilename | {
"repo_name": "ychaim/sparkbit",
"path": "src/main/java/org/multibit/file/BackupManager.java",
"license": "mit",
"size": 38985
} | [
"java.io.File",
"java.io.IOException",
"java.text.SimpleDateFormat",
"java.util.Date"
] | import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; | import java.io.*; import java.text.*; import java.util.*; | [
"java.io",
"java.text",
"java.util"
] | java.io; java.text; java.util; | 1,833,209 |
public static Textbox bind(final Textbox textBox,
final Getter<String> getter, final Setter<String> setter) {
textBox.setValue(getter.get());
textBox.addEventListener(Events.ON_CHANGE, new EventListener() { | static Textbox function(final Textbox textBox, final Getter<String> getter, final Setter<String> setter) { textBox.setValue(getter.get()); textBox.addEventListener(Events.ON_CHANGE, new EventListener() { | /**
* Binds a {@link Textbox} with a {@link Getter}. The {@link Getter} will be
* used to get the value that is going to be showed in the {@link Textbox}.
* The {@link Setter} will be used to store the value inserted by the user
* in the {@link Textbox}.
* @param textBox
* The {@link Textbox} to be bound
* @param getter
* The {@link Getter} interface that will implement a get method.
* @param setter
* The {@link Setter} interface that will implement a set method.
* @return The {@link Textbox} bound
*/ | Binds a <code>Textbox</code> with a <code>Getter</code>. The <code>Getter</code> will be used to get the value that is going to be showed in the <code>Textbox</code>. The <code>Setter</code> will be used to store the value inserted by the user in the <code>Textbox</code> | bind | {
"repo_name": "Marine-22/libre",
"path": "libreplan-webapp/src/main/java/org/libreplan/web/common/Util.java",
"license": "agpl-3.0",
"size": 34636
} | [
"org.zkoss.zk.ui.event.EventListener",
"org.zkoss.zk.ui.event.Events",
"org.zkoss.zul.Textbox"
] | import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.Events; import org.zkoss.zul.Textbox; | import org.zkoss.zk.ui.event.*; import org.zkoss.zul.*; | [
"org.zkoss.zk",
"org.zkoss.zul"
] | org.zkoss.zk; org.zkoss.zul; | 2,598,482 |
@SuppressWarnings("unchecked")
public static ElementaryFluxModes.Impl getEfmImpl(XmlConfig config, Element efmImplConfig) throws XmlConfigException {
//impl
String implClass = XmlUtil.getRequiredAttributeValue(efmImplConfig, XmlAttribute.class_);
//model
Element elModel = XmlUtil.getRequiredSingleChildElement(efmImplConfig, XmlElement.model);
String modelClass = XmlUtil.getRequiredAttributeValue(elModel, XmlAttribute.factory);
//memory
Element elMemory = XmlUtil.getRequiredSingleChildElement(efmImplConfig, XmlElement.memory);
String memoryClass = XmlUtil.getRequiredAttributeValue(elMemory, XmlAttribute.factory);
try {
Class<ElementaryFluxModes.Impl> clsImpl = (Class<ElementaryFluxModes.Impl>)Class.forName(implClass);
Class<EfmModelFactory> clsModel = (Class<EfmModelFactory>)Class.forName(modelClass);
Class<MemoryFactory> clsMemory = (Class<MemoryFactory>)Class.forName(memoryClass);
Constructor<ElementaryFluxModes.Impl> cons = clsImpl.getConstructor(new Class[] {Config.class, EfmModelFactory.class, MemoryFactory.class});
//instantiate arguments (the factories)
EfmModelFactory facModel = clsModel.newInstance();
MemoryFactory facMemory = clsMemory.newInstance();
return cons.newInstance(new Object[] {Config.getFromXmlConfig(config), facModel, facMemory});
}
catch (Exception ex) {
throw new XmlConfigException("cannot instantiate efm-impl class '" + implClass + "', e=" + ex, efmImplConfig, ex);
}
} | @SuppressWarnings(STR) static ElementaryFluxModes.Impl function(XmlConfig config, Element efmImplConfig) throws XmlConfigException { String implClass = XmlUtil.getRequiredAttributeValue(efmImplConfig, XmlAttribute.class_); Element elModel = XmlUtil.getRequiredSingleChildElement(efmImplConfig, XmlElement.model); String modelClass = XmlUtil.getRequiredAttributeValue(elModel, XmlAttribute.factory); Element elMemory = XmlUtil.getRequiredSingleChildElement(efmImplConfig, XmlElement.memory); String memoryClass = XmlUtil.getRequiredAttributeValue(elMemory, XmlAttribute.factory); try { Class<ElementaryFluxModes.Impl> clsImpl = (Class<ElementaryFluxModes.Impl>)Class.forName(implClass); Class<EfmModelFactory> clsModel = (Class<EfmModelFactory>)Class.forName(modelClass); Class<MemoryFactory> clsMemory = (Class<MemoryFactory>)Class.forName(memoryClass); Constructor<ElementaryFluxModes.Impl> cons = clsImpl.getConstructor(new Class[] {Config.class, EfmModelFactory.class, MemoryFactory.class}); EfmModelFactory facModel = clsModel.newInstance(); MemoryFactory facMemory = clsMemory.newInstance(); return cons.newInstance(new Object[] {Config.getFromXmlConfig(config), facModel, facMemory}); } catch (Exception ex) { throw new XmlConfigException(STR + implClass + STR + ex, efmImplConfig, ex); } } | /**
* Returns the ElementaryFluxMode implementation as configured in the
* given xml config
*/ | Returns the ElementaryFluxMode implementation as configured in the given xml config | getEfmImpl | {
"repo_name": "mpgerstl/tEFMA",
"path": "ch/javasoft/metabolic/efm/config/Config.java",
"license": "bsd-2-clause",
"size": 37828
} | [
"ch.javasoft.metabolic.efm.ElementaryFluxModes",
"ch.javasoft.metabolic.efm.memory.MemoryFactory",
"ch.javasoft.metabolic.efm.model.EfmModelFactory",
"ch.javasoft.xml.config.XmlConfig",
"ch.javasoft.xml.config.XmlConfigException",
"ch.javasoft.xml.config.XmlUtil",
"java.lang.reflect.Constructor",
"org.dom4j.Element"
] | import ch.javasoft.metabolic.efm.ElementaryFluxModes; import ch.javasoft.metabolic.efm.memory.MemoryFactory; import ch.javasoft.metabolic.efm.model.EfmModelFactory; import ch.javasoft.xml.config.XmlConfig; import ch.javasoft.xml.config.XmlConfigException; import ch.javasoft.xml.config.XmlUtil; import java.lang.reflect.Constructor; import org.dom4j.Element; | import ch.javasoft.metabolic.efm.*; import ch.javasoft.metabolic.efm.memory.*; import ch.javasoft.metabolic.efm.model.*; import ch.javasoft.xml.config.*; import java.lang.reflect.*; import org.dom4j.*; | [
"ch.javasoft.metabolic",
"ch.javasoft.xml",
"java.lang",
"org.dom4j"
] | ch.javasoft.metabolic; ch.javasoft.xml; java.lang; org.dom4j; | 101,183 |
if (ev.getType()==TableModelEvent.INSERT) { //adding a stats update listener only appropriate for the insert event
| if (ev.getType()==TableModelEvent.INSERT) { | /**
* We piggyback of the indexnode communicator tablemodel to get notified when events happen.
*
* This method will always be called in the swing thread, by contract.
*/ | We piggyback of the indexnode communicator tablemodel to get notified when events happen. This method will always be called in the swing thread, by contract | tableChanged | {
"repo_name": "conicalflask/fs2",
"path": "src/client/indexnode/IndexNodeStatsTableModel.java",
"license": "bsd-3-clause",
"size": 3973
} | [
"javax.swing.event.TableModelEvent"
] | import javax.swing.event.TableModelEvent; | import javax.swing.event.*; | [
"javax.swing"
] | javax.swing; | 832,177 |
EAttribute getNode_Changed(); | EAttribute getNode_Changed(); | /**
* Returns the meta object for the attribute '{@link org.dawnsci.marketplace.Node#getChanged <em>Changed</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Changed</em>'.
* @see org.dawnsci.marketplace.Node#getChanged()
* @see #getNode()
* @generated
*/ | Returns the meta object for the attribute '<code>org.dawnsci.marketplace.Node#getChanged Changed</code>'. | getNode_Changed | {
"repo_name": "Itema-as/dawn-marketplace-server",
"path": "org.dawnsci.marketplace.core/src-gen/org/dawnsci/marketplace/MarketplacePackage.java",
"license": "epl-1.0",
"size": 104026
} | [
"org.eclipse.emf.ecore.EAttribute"
] | import org.eclipse.emf.ecore.EAttribute; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 1,373,333 |
public void addDirectSpecialisationWitnessForAxiom(OWLAxiom effAx, OWLAxiom witnessAx) {
if(dirSpecWitsOfAx.containsKey(effAx)) {
Set<OWLAxiom> wits = dirSpecWitsOfAx.get(effAx);
wits.add(witnessAx);
dirSpecWitsOfAx.put(effAx, wits);
}
else
dirSpecWitsOfAx.put(effAx, new HashSet<OWLAxiom>(Collections.singleton(witnessAx)));
}
| void function(OWLAxiom effAx, OWLAxiom witnessAx) { if(dirSpecWitsOfAx.containsKey(effAx)) { Set<OWLAxiom> wits = dirSpecWitsOfAx.get(effAx); wits.add(witnessAx); dirSpecWitsOfAx.put(effAx, wits); } else dirSpecWitsOfAx.put(effAx, new HashSet<OWLAxiom>(Collections.singleton(witnessAx))); } | /**
* Add an entailment (witness) axiom which is a consequence of an effectual axiom change (which in turn directly specialises the concept)
* @param effAx Effectual axiom which gives rise to the entailment (witness) axiom change
* @param witnessAx Entailment in the diff - the witness axiom
*/ | Add an entailment (witness) axiom which is a consequence of an effectual axiom change (which in turn directly specialises the concept) | addDirectSpecialisationWitnessForAxiom | {
"repo_name": "rsgoncalves/ecco",
"path": "src/main/java/uk/ac/manchester/cs/diff/concept/change/ConceptChange.java",
"license": "lgpl-3.0",
"size": 11897
} | [
"java.util.Collections",
"java.util.HashSet",
"java.util.Set",
"org.semanticweb.owlapi.model.OWLAxiom"
] | import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.semanticweb.owlapi.model.OWLAxiom; | import java.util.*; import org.semanticweb.owlapi.model.*; | [
"java.util",
"org.semanticweb.owlapi"
] | java.util; org.semanticweb.owlapi; | 1,755,977 |
Optional<List<TaskIndex>> indicesList = ParserUtil.parseMultipleInteger(args);
if (!indicesList.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UnmarkCommand.MESSAGE_USAGE));
}
return new UnmarkCommand(indicesList.get());
} | Optional<List<TaskIndex>> indicesList = ParserUtil.parseMultipleInteger(args); if (!indicesList.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UnmarkCommand.MESSAGE_USAGE)); } return new UnmarkCommand(indicesList.get()); } | /**
* Parses the given {@code String} of arguments in the context of the UnmarkCommand
* and returns an UnmarkCommand object for execution.
*/ | Parses the given String of arguments in the context of the UnmarkCommand and returns an UnmarkCommand object for execution | parse | {
"repo_name": "CS2103JAN2017-F12-B1/main",
"path": "src/main/java/savvytodo/logic/parser/UnmarkCommandParser.java",
"license": "mit",
"size": 950
} | [
"java.util.List",
"java.util.Optional"
] | import java.util.List; import java.util.Optional; | import java.util.*; | [
"java.util"
] | java.util; | 1,204,378 |
private String resolveRefidToClassName(Map<String, String> idToNameMap, String refid) throws Exception {
String className = idToNameMap.get(refid);
if (className == null) {
throw new Exception("refid " + refid + " in domain model is not defined by any XML element.");
}
return className;
}
| String function(Map<String, String> idToNameMap, String refid) throws Exception { String className = idToNameMap.get(refid); if (className == null) { throw new Exception(STR + refid + STR); } return className; } | /**
* Return the name of the class that corresponds to the given refid.
*
* @param idToNameMap
* a map from refid's to class names.
* @param refid
* the refid to resolve to a class name.
* @return the name of the class that is referred to by the given refid.
* @throws Exception
* if there is a problem such as no class name corresponds to
* the given refid.
*/ | Return the name of the class that corresponds to the given refid | resolveRefidToClassName | {
"repo_name": "NCIP/cagrid-grid-incubation",
"path": "grid-incubation/incubator/projects/CQL_CSM/src/edu/emory/cci/domainModel/DomainModelAccessor.java",
"license": "bsd-3-clause",
"size": 18242
} | [
"java.util.Map"
] | import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 825,430 |
public TimeValue getRetryBackoffInitialTime() {
return retryBackoffInitialTime;
} | TimeValue function() { return retryBackoffInitialTime; } | /**
* Initial delay after a rejection before retrying request.
*/ | Initial delay after a rejection before retrying request | getRetryBackoffInitialTime | {
"repo_name": "HonzaKral/elasticsearch",
"path": "server/src/main/java/org/elasticsearch/index/reindex/AbstractBulkByScrollRequest.java",
"license": "apache-2.0",
"size": 16493
} | [
"org.elasticsearch.common.unit.TimeValue"
] | import org.elasticsearch.common.unit.TimeValue; | import org.elasticsearch.common.unit.*; | [
"org.elasticsearch.common"
] | org.elasticsearch.common; | 783,207 |
protected Map<String, List<String>> decodeParameters(Map<String, String> parms) {
return this.decodeParameters(parms.get(QUERY_STRING_PARAMETER));
} | Map<String, List<String>> function(Map<String, String> parms) { return this.decodeParameters(parms.get(QUERY_STRING_PARAMETER)); } | /**
* Decode parameters from a URL, handing the case where a single parameter name might have been
* supplied several times, by return lists of values. In general these lists will contain a single
* element.
*
* @param parms original <b>NanoHttpd</b> parameters values, as passed to the <code>serve()</code> method.
* @return a map of <code>String</code> (parameter name) to <code>List<String></code> (a list of the values supplied).
*/ | Decode parameters from a URL, handing the case where a single parameter name might have been supplied several times, by return lists of values. In general these lists will contain a single element | decodeParameters | {
"repo_name": "MosumTree/lightning",
"path": "app/src/main/java/connect/NanoHTTPD.java",
"license": "apache-2.0",
"size": 52874
} | [
"java.util.List",
"java.util.Map"
] | import java.util.List; import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 51,780 |
private void selectNode(){
//Remove all items before regenerating the combobox.
//This is because if a users selects the node twice, it would add the interfaces twice.
cmbInterface.removeAllItems();
NodeName = (String)cmbNodeName.getSelectedItem();
try {
Object nics[] = Sim.getNode(NodeName).getAllInterfaces(); //Get object array of interface names
//Sort the array
Arrays.sort(nics);
for (int i = 0; i < nics.length; i++) { //Add them to the combobox
if(Sim.getNode(NodeName).isActiveInterface((String)nics[i]) )
cmbInterface.addItem(nics[i]);
}
cmbInterface.setEnabled(true);
DefaultGWAddress = ((core.NetworkLayerDevice)Sim.getNode(NodeName)).getDefaultGateway();
if(DefaultGWAddress != null){
txtDefaultGW.setText(DefaultGWAddress);
}
txtDefaultGW.setEnabled(true);
} catch (Exception e) { //This should never happen
e.printStackTrace();
}
}
| void function(){ cmbInterface.removeAllItems(); NodeName = (String)cmbNodeName.getSelectedItem(); try { Object nics[] = Sim.getNode(NodeName).getAllInterfaces(); Arrays.sort(nics); for (int i = 0; i < nics.length; i++) { if(Sim.getNode(NodeName).isActiveInterface((String)nics[i]) ) cmbInterface.addItem(nics[i]); } cmbInterface.setEnabled(true); DefaultGWAddress = ((core.NetworkLayerDevice)Sim.getNode(NodeName)).getDefaultGateway(); if(DefaultGWAddress != null){ txtDefaultGW.setText(DefaultGWAddress); } txtDefaultGW.setEnabled(true); } catch (Exception e) { e.printStackTrace(); } } | /**
* This method will generate the data within the Interface combobox based
* on the node that is selected. It will also get the default gateway if there is one set
* for the node and add the text to the text field
*
* @author luke_hamilton
*
*/ | This method will generate the data within the Interface combobox based on the node that is selected. It will also get the default gateway if there is one set for the node and add the text to the text field | selectNode | {
"repo_name": "Darkkey/javaNetSim",
"path": "src/guiUI/SetTCPIPPropertiesDialog.java",
"license": "bsd-3-clause",
"size": 19804
} | [
"java.util.Arrays"
] | import java.util.Arrays; | import java.util.*; | [
"java.util"
] | java.util; | 2,393,690 |
public static void writeTo( OutputStream outputStream, List<?> sheet ) throws UncheckedIOException {
getHandler().writeTo( outputStream, sheet );
} | static void function( OutputStream outputStream, List<?> sheet ) throws UncheckedIOException { getHandler().writeTo( outputStream, sheet ); } | /**
* Write data to excel file in sheet named 'Sheet1'
*
* @param outputStream output stream to write data
* @param sheet grid data
* @throws UncheckedIOException file I/O exception
*/ | Write data to excel file in sheet named 'Sheet1' | writeTo | {
"repo_name": "NyBatis/NyBatisCore",
"path": "src/main/java/org/nybatis/core/file/ExcelUtil.java",
"license": "apache-2.0",
"size": 15563
} | [
"java.io.OutputStream",
"java.util.List",
"org.nybatis.core.exception.unchecked.UncheckedIOException"
] | import java.io.OutputStream; import java.util.List; import org.nybatis.core.exception.unchecked.UncheckedIOException; | import java.io.*; import java.util.*; import org.nybatis.core.exception.unchecked.*; | [
"java.io",
"java.util",
"org.nybatis.core"
] | java.io; java.util; org.nybatis.core; | 2,798,279 |
@Schema(required = true, description = "File ID")
public Long getFileId() {
return fileId;
} | @Schema(required = true, description = STR) Long function() { return fileId; } | /**
* File ID
* @return fileId
**/ | File ID | getFileId | {
"repo_name": "iterate-ch/cyberduck",
"path": "dracoon/src/main/java/ch/cyberduck/core/sds/io/swagger/client/model/UserFileKeySetRequest.java",
"license": "gpl-3.0",
"size": 3962
} | [
"io.swagger.v3.oas.annotations.media.Schema"
] | import io.swagger.v3.oas.annotations.media.Schema; | import io.swagger.v3.oas.annotations.media.*; | [
"io.swagger.v3"
] | io.swagger.v3; | 230,053 |
@Test
public void traceFormattedStringWithSingleInt() {
logger.tracef("Hello %d!", 42);
if (traceEnabled) {
verify(provider).log(eq(2), isNull(), eq(Level.TRACE), same(null), any(PrintfStyleFormatter.class), eq("Hello %d!"), eq(42));
} else {
verify(provider, never()).log(anyInt(), anyString(), any(), any(), any(), any(), any());
}
}
/**
* Verifies that a formatted string with two integer arguments will be logged correctly at {@link Level#TRACE TRACE} | void function() { logger.tracef(STR, 42); if (traceEnabled) { verify(provider).log(eq(2), isNull(), eq(Level.TRACE), same(null), any(PrintfStyleFormatter.class), eq(STR), eq(42)); } else { verify(provider, never()).log(anyInt(), anyString(), any(), any(), any(), any(), any()); } } /** * Verifies that a formatted string with two integer arguments will be logged correctly at {@link Level#TRACE TRACE} | /**
* Verifies that a formatted string with a single integer argument will be logged correctly at {@link Level#TRACE
* TRACE} level.
*/ | Verifies that a formatted string with a single integer argument will be logged correctly at <code>Level#TRACE TRACE</code> level | traceFormattedStringWithSingleInt | {
"repo_name": "pmwmedia/tinylog",
"path": "jboss-tinylog/src/test/java/org/tinylog/jboss/TinylogLoggerTest.java",
"license": "apache-2.0",
"size": 189291
} | [
"org.mockito.ArgumentMatchers",
"org.mockito.Mockito",
"org.tinylog.Level",
"org.tinylog.format.PrintfStyleFormatter"
] | import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.tinylog.Level; import org.tinylog.format.PrintfStyleFormatter; | import org.mockito.*; import org.tinylog.*; import org.tinylog.format.*; | [
"org.mockito",
"org.tinylog",
"org.tinylog.format"
] | org.mockito; org.tinylog; org.tinylog.format; | 1,061,088 |
@Test
public void testAutoComponentMissingInParentWithMarkupContainer() {
this.tester.startPage(AutoComponentInChildMarkupContainer.class);
AutoWire autoWire = getAutoWire();
assertFalse(autoWire.hasAutoComponentAnnotatedFields(AutoComponentInChildMarkupContainer.class));
assertTrue(autoWire.hasAutoComponentAnnotatedFields(AutoComponentInChildMarkupContainer.NestedContainer.class));
}
| void function() { this.tester.startPage(AutoComponentInChildMarkupContainer.class); AutoWire autoWire = getAutoWire(); assertFalse(autoWire.hasAutoComponentAnnotatedFields(AutoComponentInChildMarkupContainer.class)); assertTrue(autoWire.hasAutoComponentAnnotatedFields(AutoComponentInChildMarkupContainer.NestedContainer.class)); } | /**
* Assert that {@link AutoWire#hasAutoComponentAnnotatedFields(Class class)} returns true for classes
* with AutoComponent annotated fields.
*/ | Assert that <code>AutoWire#hasAutoComponentAnnotatedFields(Class class)</code> returns true for classes with AutoComponent annotated fields | testAutoComponentMissingInParentWithMarkupContainer | {
"repo_name": "wicket-acc/wicket-autowire",
"path": "src/test/java/com/github/wicket/autowire/AutoWireTest.java",
"license": "apache-2.0",
"size": 6682
} | [
"org.junit.Assert"
] | import org.junit.Assert; | import org.junit.*; | [
"org.junit"
] | org.junit; | 2,340,874 |
public byte[] readAllBytes(final Path path) throws IOException {
return Files.readAllBytes(path);
} | byte[] function(final Path path) throws IOException { return Files.readAllBytes(path); } | /**
* Reads all the bytes from a file.
* This is a wrapper for the static {@link Files#readAllBytes(Path)} method.
*
* @param path the path to the file
* @return a byte array containing the bytes read from the file
* @throws IOException if an IO error occurs
*/ | Reads all the bytes from a file. This is a wrapper for the static <code>Files#readAllBytes(Path)</code> method | readAllBytes | {
"repo_name": "1element/sc",
"path": "src/main/java/com/github/_1element/sc/service/FileService.java",
"license": "agpl-3.0",
"size": 4115
} | [
"java.io.IOException",
"java.nio.file.Files",
"java.nio.file.Path"
] | import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; | import java.io.*; import java.nio.file.*; | [
"java.io",
"java.nio"
] | java.io; java.nio; | 2,136,211 |
private void actionRefreshGameInfoList() {
sendRequest(new Request("client.lobby.refresh"));
} | void function() { sendRequest(new Request(STR)); } | /**
* Asks the server for an updated list of the games it currently hosts.
*/ | Asks the server for an updated list of the games it currently hosts | actionRefreshGameInfoList | {
"repo_name": "CopyrightInfringement/ChineseCheckers",
"path": "src/main/java/org/copinf/cc/controller/LobbyController.java",
"license": "mit",
"size": 5332
} | [
"org.copinf.cc.net.Request"
] | import org.copinf.cc.net.Request; | import org.copinf.cc.net.*; | [
"org.copinf.cc"
] | org.copinf.cc; | 2,773,283 |
@SuppressWarnings("unchecked")
public static List<Object> castRequestToDataModels(WSRequestDTO request , Class<?> clazz) {
Object dataModel = null;
LinkedHashMap<Long, Object> requestMap = null;
List<Object> dataModelList = new ArrayList<>();
try {
List<?> list= (List<?>) request.getDataModel();
for (Object object : list) {
requestMap = (LinkedHashMap<Long, Object>) object;
String jsonString = new JSONObject(requestMap).toString();
dataModel = new ObjectMapper().readValue(jsonString, clazz);
dataModelList.add(dataModel);
}
} catch (IOException e) {
logger.error("Error while casting data Model:", e);
}
return dataModelList;
}
| @SuppressWarnings(STR) static List<Object> function(WSRequestDTO request , Class<?> clazz) { Object dataModel = null; LinkedHashMap<Long, Object> requestMap = null; List<Object> dataModelList = new ArrayList<>(); try { List<?> list= (List<?>) request.getDataModel(); for (Object object : list) { requestMap = (LinkedHashMap<Long, Object>) object; String jsonString = new JSONObject(requestMap).toString(); dataModel = new ObjectMapper().readValue(jsonString, clazz); dataModelList.add(dataModel); } } catch (IOException e) { logger.error(STR, e); } return dataModelList; } | /**
* use this method to cast models of same type from request received
* @param request
* @param clazz :pass destination data model class to cast
* @return list of passed data model to cast
*/ | use this method to cast models of same type from request received | castRequestToDataModels | {
"repo_name": "abmindiarepomanager/ABMOpenMainet",
"path": "Mainet1.1/MainetBRMS/Mainet_BRMS_BPMN/src/main/java/com/abm/mainet/brms/core/utility/CommonMasterUtility.java",
"license": "gpl-3.0",
"size": 13325
} | [
"com.abm.mainet.brms.core.dto.WSRequestDTO",
"com.fasterxml.jackson.databind.ObjectMapper",
"java.io.IOException",
"java.util.ArrayList",
"java.util.LinkedHashMap",
"java.util.List",
"org.json.JSONObject"
] | import com.abm.mainet.brms.core.dto.WSRequestDTO; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import org.json.JSONObject; | import com.abm.mainet.brms.core.dto.*; import com.fasterxml.jackson.databind.*; import java.io.*; import java.util.*; import org.json.*; | [
"com.abm.mainet",
"com.fasterxml.jackson",
"java.io",
"java.util",
"org.json"
] | com.abm.mainet; com.fasterxml.jackson; java.io; java.util; org.json; | 1,973,495 |
// ------------------------------------------------------------------------
protected static void dumpNode(Node node, int depth) {
while (node != null) {
StringBuilder s = new StringBuilder();
s.append(indent(depth));
if (node instanceof Code) {
s.append("Code{literal=").append(((Code) node).getLiteral()).append("}");
} else {
s.append(node.toString());
}
System.out.println(s.toString());
dumpNode(node.getFirstChild(), depth + 1);
node = node.getNext();
}
} | static void function(Node node, int depth) { while (node != null) { StringBuilder s = new StringBuilder(); s.append(indent(depth)); if (node instanceof Code) { s.append(STR).append(((Code) node).getLiteral()).append("}"); } else { s.append(node.toString()); } System.out.println(s.toString()); dumpNode(node.getFirstChild(), depth + 1); node = node.getNext(); } } | /**
* Dump the specified node at the specified depth of nesting.
*
* @param node the node.
* @param depth the nesting depth or number of parents of node.
*/ | Dump the specified node at the specified depth of nesting | dumpNode | {
"repo_name": "NerdNu/HelpHelp",
"path": "src/nu/nerd/help/Nodes.java",
"license": "mit",
"size": 8203
} | [
"org.commonmark.node.Code",
"org.commonmark.node.Node"
] | import org.commonmark.node.Code; import org.commonmark.node.Node; | import org.commonmark.node.*; | [
"org.commonmark.node"
] | org.commonmark.node; | 1,456,183 |
public Character getCharacter(final long characterId)
throws UdpConnectionException, AniDbException {
return this.characterFactory.getCharacter(characterId);
}
| Character function(final long characterId) throws UdpConnectionException, AniDbException { return this.characterFactory.getCharacter(characterId); } | /**
* Returns the character with the given character Id.
* @param characterId The character Id.
* @return The character.
* @throws UdpConnectionException If a connection problem occured.
* @throws AniDbException If a problem with AniDB occured.
* @see UdpReturnCodes#NO_SUCH_CHARACTER
*/ | Returns the character with the given character Id | getCharacter | {
"repo_name": "derBeukatt/AniDBTool",
"path": "src/net/anidb/udp/UdpConnection.java",
"license": "gpl-3.0",
"size": 45351
} | [
"net.anidb.Character"
] | import net.anidb.Character; | import net.anidb.*; | [
"net.anidb"
] | net.anidb; | 454,141 |
protected PaletteEntry getEntry(String label) {
for (Iterator iterator = getChildren().iterator(); iterator.hasNext();) {
Object o = (Object) iterator.next();
if (o instanceof PaletteDrawer) {
if (((PaletteDrawer) o).getLabel().equals(label))
return (PaletteDrawer) o;
}
}
return null;
} | PaletteEntry function(String label) { for (Iterator iterator = getChildren().iterator(); iterator.hasNext();) { Object o = (Object) iterator.next(); if (o instanceof PaletteDrawer) { if (((PaletteDrawer) o).getLabel().equals(label)) return (PaletteDrawer) o; } } return null; } | /**
* Find a palette entry from a label name
*
* @param label
* @return
*/ | Find a palette entry from a label name | getEntry | {
"repo_name": "McGill-DP-Group/seg.jUCMNav",
"path": "src/seg/jUCMNav/editors/palette/FmdPaletteRoot.java",
"license": "epl-1.0",
"size": 4833
} | [
"java.util.Iterator",
"org.eclipse.gef.palette.PaletteDrawer",
"org.eclipse.gef.palette.PaletteEntry"
] | import java.util.Iterator; import org.eclipse.gef.palette.PaletteDrawer; import org.eclipse.gef.palette.PaletteEntry; | import java.util.*; import org.eclipse.gef.palette.*; | [
"java.util",
"org.eclipse.gef"
] | java.util; org.eclipse.gef; | 240,762 |
private void addPerspectiveActions(MenuManager menu)
{
{
String openText = IDEWorkbenchMessages.Workbench_openPerspective;
MenuManager changePerspMenuMgr = new MenuManager(openText,
"openPerspective"); //$NON-NLS-1$
IContributionItem changePerspMenuItem = ContributionItemFactory.PERSPECTIVES_SHORTLIST
.create(getWindow());
changePerspMenuMgr.add(changePerspMenuItem);
menu.add(changePerspMenuMgr);
}
{
MenuManager showViewMenuMgr = new MenuManager(
IDEWorkbenchMessages.Workbench_showView, "showView"); //$NON-NLS-1$
IContributionItem showViewMenu = ContributionItemFactory.VIEWS_SHORTLIST
.create(getWindow());
showViewMenuMgr.add(showViewMenu);
menu.add(showViewMenuMgr);
}
menu.add(new Separator());
menu.add(getSavePerspectiveItem());
menu.add(getResetPerspectiveItem());
menu.add(closePerspAction);
menu.add(closeAllPerspsAction);
} | void function(MenuManager menu) { { String openText = IDEWorkbenchMessages.Workbench_openPerspective; MenuManager changePerspMenuMgr = new MenuManager(openText, STR); IContributionItem changePerspMenuItem = ContributionItemFactory.PERSPECTIVES_SHORTLIST .create(getWindow()); changePerspMenuMgr.add(changePerspMenuItem); menu.add(changePerspMenuMgr); } { MenuManager showViewMenuMgr = new MenuManager( IDEWorkbenchMessages.Workbench_showView, STR); IContributionItem showViewMenu = ContributionItemFactory.VIEWS_SHORTLIST .create(getWindow()); showViewMenuMgr.add(showViewMenu); menu.add(showViewMenuMgr); } menu.add(new Separator()); menu.add(getSavePerspectiveItem()); menu.add(getResetPerspectiveItem()); menu.add(closePerspAction); menu.add(closeAllPerspsAction); } | /**
* Adds the perspective actions to the specified menu.
*/ | Adds the perspective actions to the specified menu | addPerspectiveActions | {
"repo_name": "pecko/testlimpet",
"path": "info.limpet.rcp/src/info/limpet/rcp/product/ApplicationActionBarAdvisor.java",
"license": "epl-1.0",
"size": 29207
} | [
"org.eclipse.jface.action.IContributionItem",
"org.eclipse.jface.action.MenuManager",
"org.eclipse.jface.action.Separator",
"org.eclipse.ui.actions.ContributionItemFactory",
"org.eclipse.ui.internal.ide.IDEWorkbenchMessages"
] | import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.ui.actions.ContributionItemFactory; import org.eclipse.ui.internal.ide.IDEWorkbenchMessages; | import org.eclipse.jface.action.*; import org.eclipse.ui.actions.*; import org.eclipse.ui.internal.ide.*; | [
"org.eclipse.jface",
"org.eclipse.ui"
] | org.eclipse.jface; org.eclipse.ui; | 2,003,290 |
private File saveScreenshotToTmpFile (Bitmap screenshot) {
try {
File tmpFile = File.createTempFile("screenshot", ".tmp");
FileOutputStream stream = new FileOutputStream(tmpFile);
screenshot.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
return tmpFile;
} catch (IOException e) {
e.printStackTrace();
}
return null;
} | File function (Bitmap screenshot) { try { File tmpFile = File.createTempFile(STR, ".tmp"); FileOutputStream stream = new FileOutputStream(tmpFile); screenshot.compress(Bitmap.CompressFormat.PNG, 100, stream); stream.close(); return tmpFile; } catch (IOException e) { e.printStackTrace(); } return null; } | /**
* Speichert den Screenshot der Seite in einer tmp. Datei ab.
*/ | Speichert den Screenshot der Seite in einer tmp. Datei ab | saveScreenshotToTmpFile | {
"repo_name": "pankajnirwan103/cordova-phonegap-print-plugin",
"path": "src/android/Printer.java",
"license": "apache-2.0",
"size": 13279
} | [
"android.graphics.Bitmap",
"java.io.File",
"java.io.FileOutputStream",
"java.io.IOException"
] | import android.graphics.Bitmap; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; | import android.graphics.*; import java.io.*; | [
"android.graphics",
"java.io"
] | android.graphics; java.io; | 6,393 |
public static Range iterateDomainBounds(XYDataset dataset,
boolean includeInterval) {
ParamChecks.nullNotPermitted(dataset, "dataset");
double minimum = Double.POSITIVE_INFINITY;
double maximum = Double.NEGATIVE_INFINITY;
int seriesCount = dataset.getSeriesCount();
double lvalue, uvalue;
if (includeInterval && dataset instanceof IntervalXYDataset) {
IntervalXYDataset intervalXYData = (IntervalXYDataset) dataset;
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double value = intervalXYData.getXValue(series, item);
lvalue = intervalXYData.getStartXValue(series, item);
uvalue = intervalXYData.getEndXValue(series, item);
if (!Double.isNaN(value)) {
minimum = Math.min(minimum, value);
maximum = Math.max(maximum, value);
}
if (!Double.isNaN(lvalue)) {
minimum = Math.min(minimum, lvalue);
maximum = Math.max(maximum, lvalue);
}
if (!Double.isNaN(uvalue)) {
minimum = Math.min(minimum, uvalue);
maximum = Math.max(maximum, uvalue);
}
}
}
}
else {
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
lvalue = dataset.getXValue(series, item);
uvalue = lvalue;
if (!Double.isNaN(lvalue)) {
minimum = Math.min(minimum, lvalue);
maximum = Math.max(maximum, uvalue);
}
}
}
}
if (minimum > maximum) {
return null;
}
else {
return new Range(minimum, maximum);
}
} | static Range function(XYDataset dataset, boolean includeInterval) { ParamChecks.nullNotPermitted(dataset, STR); double minimum = Double.POSITIVE_INFINITY; double maximum = Double.NEGATIVE_INFINITY; int seriesCount = dataset.getSeriesCount(); double lvalue, uvalue; if (includeInterval && dataset instanceof IntervalXYDataset) { IntervalXYDataset intervalXYData = (IntervalXYDataset) dataset; for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double value = intervalXYData.getXValue(series, item); lvalue = intervalXYData.getStartXValue(series, item); uvalue = intervalXYData.getEndXValue(series, item); if (!Double.isNaN(value)) { minimum = Math.min(minimum, value); maximum = Math.max(maximum, value); } if (!Double.isNaN(lvalue)) { minimum = Math.min(minimum, lvalue); maximum = Math.max(maximum, lvalue); } if (!Double.isNaN(uvalue)) { minimum = Math.min(minimum, uvalue); maximum = Math.max(maximum, uvalue); } } } } else { for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { lvalue = dataset.getXValue(series, item); uvalue = lvalue; if (!Double.isNaN(lvalue)) { minimum = Math.min(minimum, lvalue); maximum = Math.max(maximum, uvalue); } } } } if (minimum > maximum) { return null; } else { return new Range(minimum, maximum); } } | /**
* Iterates over the items in an {@link XYDataset} to find
* the range of x-values.
*
* @param dataset the dataset ({@code null} not permitted).
* @param includeInterval a flag that determines, for an
* {@link IntervalXYDataset}, whether the x-interval or just the
* x-value is used to determine the overall range.
*
* @return The range (possibly {@code null}).
*/ | Iterates over the items in an <code>XYDataset</code> to find the range of x-values | iterateDomainBounds | {
"repo_name": "simon04/jfreechart",
"path": "src/main/java/org/jfree/data/general/DatasetUtilities.java",
"license": "lgpl-2.1",
"size": 94747
} | [
"org.jfree.chart.util.ParamChecks",
"org.jfree.data.Range",
"org.jfree.data.xy.IntervalXYDataset",
"org.jfree.data.xy.XYDataset"
] | import org.jfree.chart.util.ParamChecks; import org.jfree.data.Range; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.XYDataset; | import org.jfree.chart.util.*; import org.jfree.data.*; import org.jfree.data.xy.*; | [
"org.jfree.chart",
"org.jfree.data"
] | org.jfree.chart; org.jfree.data; | 613,232 |
public Collection<Device> getDeviceList() {
return Collections.unmodifiableCollection(getDeviceMap().values());
}
/**
* Returns the {@link Device}, that has the {@link Message} with the given messageId.
*
* @param messageId the id of the {@link Message} | Collection<Device> function() { return Collections.unmodifiableCollection(getDeviceMap().values()); } /** * Returns the {@link Device}, that has the {@link Message} with the given messageId. * * @param messageId the id of the {@link Message} | /**
* Returns a {@link Collection} of all {@link Device}s handled by the {@link DeviceStructureManager}.
*
* @return
*/ | Returns a <code>Collection</code> of all <code>Device</code>s handled by the <code>DeviceStructureManager</code> | getDeviceList | {
"repo_name": "tavalin/openhab2-addons",
"path": "addons/binding/org.openhab.binding.innogysmarthome/src/main/java/org/openhab/binding/innogysmarthome/internal/manager/DeviceStructureManager.java",
"license": "epl-1.0",
"size": 8232
} | [
"java.util.Collection",
"java.util.Collections",
"org.openhab.binding.innogysmarthome.internal.client.entity.Message",
"org.openhab.binding.innogysmarthome.internal.client.entity.device.Device"
] | import java.util.Collection; import java.util.Collections; import org.openhab.binding.innogysmarthome.internal.client.entity.Message; import org.openhab.binding.innogysmarthome.internal.client.entity.device.Device; | import java.util.*; import org.openhab.binding.innogysmarthome.internal.client.entity.*; import org.openhab.binding.innogysmarthome.internal.client.entity.device.*; | [
"java.util",
"org.openhab.binding"
] | java.util; org.openhab.binding; | 354,200 |
public void focusGained(FocusEvent event, EditPartViewer viewer) {
Tool tool = getActiveTool();
if (tool != null)
tool.focusGained(event, viewer);
} | void function(FocusEvent event, EditPartViewer viewer) { Tool tool = getActiveTool(); if (tool != null) tool.focusGained(event, viewer); } | /**
* Called when one of the EditDomain's Viewers receives keyboard focus.
*
* @param event
* The SWT focus event
* @param viewer
* the Viewer that received the event.
*/ | Called when one of the EditDomain's Viewers receives keyboard focus | focusGained | {
"repo_name": "archimatetool/archi",
"path": "org.eclipse.gef/src/org/eclipse/gef/EditDomain.java",
"license": "mit",
"size": 14480
} | [
"org.eclipse.swt.events.FocusEvent"
] | import org.eclipse.swt.events.FocusEvent; | import org.eclipse.swt.events.*; | [
"org.eclipse.swt"
] | org.eclipse.swt; | 1,271,143 |
@Override
public Iterator<KeyRecord> iterator() {
return new RecordSetIterator(this);
}
//-------------------------------------------------------
// Meta-data retrieval methods
//-------------------------------------------------------
| Iterator<KeyRecord> function() { return new RecordSetIterator(this); } | /**
* Provide Iterator for RecordSet.
*/ | Provide Iterator for RecordSet | iterator | {
"repo_name": "wgpshashank/aerospike-client-java",
"path": "client/src/com/aerospike/client/query/RecordSet.java",
"license": "apache-2.0",
"size": 5201
} | [
"java.util.Iterator"
] | import java.util.Iterator; | import java.util.*; | [
"java.util"
] | java.util; | 1,421,309 |
public final class PrivateEndpointConnectionsDeleteSamples {
public static void deletesAPrivateEndpointConnectionWithAGivenName(
com.azure.resourcemanager.postgresql.PostgreSqlManager manager) {
manager
.privateEndpointConnections()
.delete("Default", "test-svr", "private-endpoint-connection-name", Context.NONE);
} | final class PrivateEndpointConnectionsDeleteSamples { public static void function( com.azure.resourcemanager.postgresql.PostgreSqlManager manager) { manager .privateEndpointConnections() .delete(STR, STR, STR, Context.NONE); } | /**
* Sample code: Deletes a private endpoint connection with a given name.
*
* @param manager Entry point to PostgreSqlManager.
*/ | Sample code: Deletes a private endpoint connection with a given name | deletesAPrivateEndpointConnectionWithAGivenName | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/postgresql/azure-resourcemanager-postgresql/src/samples/java/com/azure/resourcemanager/postgresql/generated/PrivateEndpointConnectionsDeleteSamples.java",
"license": "mit",
"size": 1002
} | [
"com.azure.core.util.Context"
] | import com.azure.core.util.Context; | import com.azure.core.util.*; | [
"com.azure.core"
] | com.azure.core; | 1,427,071 |
private static boolean closeDirectByteBufferPrivileged(final ByteBuffer byteBuffer, final LogNode log) {
try {
if (cleanMethod == null) {
if (log != null) {
log.log("Could not unmap ByteBuffer, cleanMethod == null");
}
return false;
}
if (VersionFinder.JAVA_MAJOR_VERSION < 9) {
if (attachmentMethod == null) {
if (log != null) {
log.log("Could not unmap ByteBuffer, attachmentMethod == null");
}
return false;
}
// Make sure duplicates and slices are not cleaned, since this can result in duplicate
// attempts to clean the same buffer, which trigger a crash with:
// "A fatal error has been detected by the Java Runtime Environment: EXCEPTION_ACCESS_VIOLATION"
// See: https://stackoverflow.com/a/31592947/3950982
if (attachmentMethod.invoke(byteBuffer) != null) {
// Buffer is a duplicate or slice
return false;
}
// Invoke ((DirectBuffer) byteBuffer).cleaner().clean()
final Method cleaner = byteBuffer.getClass().getMethod("cleaner");
if (cleaner == null) {
if (log != null) {
log.log("Could not unmap ByteBuffer, cleaner == null");
}
return false;
}
try {
cleaner.setAccessible(true);
} catch (final Exception e) {
if (log != null) {
log.log("Could not unmap ByteBuffer, cleaner.setAccessible(true) failed");
}
return false;
}
final Object cleanerResult = cleaner.invoke(byteBuffer);
if (cleanerResult == null) {
if (log != null) {
log.log("Could not unmap ByteBuffer, cleanerResult == null");
}
return false;
}
try {
cleanMethod.invoke(cleaner.invoke(byteBuffer));
return true;
} catch (final Exception e) {
if (log != null) {
log.log("Could not unmap ByteBuffer, cleanMethod.invoke(cleanerResult) failed: " + e);
}
return false;
}
} else {
if (theUnsafe == null) {
if (log != null) {
log.log("Could not unmap ByteBuffer, theUnsafe == null");
}
return false;
}
try {
cleanMethod.invoke(theUnsafe, byteBuffer);
return true;
} catch (final IllegalArgumentException e) {
// Buffer is a duplicate or slice
return false;
}
}
} catch (final ReflectiveOperationException | SecurityException e) {
if (log != null) {
log.log("Could not unmap ByteBuffer: " + e);
}
return false;
}
} | static boolean function(final ByteBuffer byteBuffer, final LogNode log) { try { if (cleanMethod == null) { if (log != null) { log.log(STR); } return false; } if (VersionFinder.JAVA_MAJOR_VERSION < 9) { if (attachmentMethod == null) { if (log != null) { log.log(STR); } return false; } if (attachmentMethod.invoke(byteBuffer) != null) { return false; } final Method cleaner = byteBuffer.getClass().getMethod(STR); if (cleaner == null) { if (log != null) { log.log(STR); } return false; } try { cleaner.setAccessible(true); } catch (final Exception e) { if (log != null) { log.log(STR); } return false; } final Object cleanerResult = cleaner.invoke(byteBuffer); if (cleanerResult == null) { if (log != null) { log.log(STR); } return false; } try { cleanMethod.invoke(cleaner.invoke(byteBuffer)); return true; } catch (final Exception e) { if (log != null) { log.log(STR + e); } return false; } } else { if (theUnsafe == null) { if (log != null) { log.log(STR); } return false; } try { cleanMethod.invoke(theUnsafe, byteBuffer); return true; } catch (final IllegalArgumentException e) { return false; } } } catch (final ReflectiveOperationException SecurityException e) { if (log != null) { log.log(STR + e); } return false; } } | /**
* Close a direct byte buffer (run in doPrivileged).
*
* @param byteBuffer
* the byte buffer
* @param log
* the log
* @return true if successful
*/ | Close a direct byte buffer (run in doPrivileged) | closeDirectByteBufferPrivileged | {
"repo_name": "lukehutch/fast-classpath-scanner",
"path": "src/main/java/nonapi/io/github/classgraph/utils/FileUtils.java",
"license": "mit",
"size": 23570
} | [
"java.lang.reflect.Method",
"java.nio.ByteBuffer"
] | import java.lang.reflect.Method; import java.nio.ByteBuffer; | import java.lang.reflect.*; import java.nio.*; | [
"java.lang",
"java.nio"
] | java.lang; java.nio; | 445,935 |
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
return first.item;
} | Item function() { if (isEmpty()) throw new NoSuchElementException(STR); return first.item; } | /**
* Returns (but does not remove) the item most recently added to this stack.
*
* @return the item most recently added to this stack
* @throws java.util.NoSuchElementException if this stack is empty
*/ | Returns (but does not remove) the item most recently added to this stack | peek | {
"repo_name": "tigerforest/tiger-forest",
"path": "demo-http/src/main/java/com/xhh/demo/http/algorithms/chapter1/optimal/LinkedStack.java",
"license": "apache-2.0",
"size": 5731
} | [
"java.util.NoSuchElementException"
] | import java.util.NoSuchElementException; | import java.util.*; | [
"java.util"
] | java.util; | 10,764 |
public void removeItem(PersonaEntity personaEntity, String entitlementTag, Integer quantity) {
InventoryEntity inventoryEntity = inventoryDAO.findByPersonaId(personaEntity.getPersonaId());
removeItem(personaEntity, inventoryEntity, entitlementTag, quantity);
} | void function(PersonaEntity personaEntity, String entitlementTag, Integer quantity) { InventoryEntity inventoryEntity = inventoryDAO.findByPersonaId(personaEntity.getPersonaId()); removeItem(personaEntity, inventoryEntity, entitlementTag, quantity); } | /**
* Removes the FIRST item with the given entitlement tag from the inventory belonging to the persona with the given ID.
* Changes are persisted!
*
* @param personaEntity The ID of the persona whose inventory should be updated
* @param entitlementTag The entitlement tag to search for in the inventory.
* @throws EngineException if no item with the given entitlement
*/ | Removes the FIRST item with the given entitlement tag from the inventory belonging to the persona with the given ID. Changes are persisted | removeItem | {
"repo_name": "SoapboxRaceWorld/soapbox-race-core",
"path": "src/main/java/com/soapboxrace/core/bo/InventoryBO.java",
"license": "gpl-3.0",
"size": 25919
} | [
"com.soapboxrace.core.jpa.InventoryEntity",
"com.soapboxrace.core.jpa.PersonaEntity"
] | import com.soapboxrace.core.jpa.InventoryEntity; import com.soapboxrace.core.jpa.PersonaEntity; | import com.soapboxrace.core.jpa.*; | [
"com.soapboxrace.core"
] | com.soapboxrace.core; | 46,394 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.