repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 218 | func_name stringlengths 4 140 | whole_func_string stringlengths 153 5.32k | language stringclasses 1
value | func_code_string stringlengths 72 4k | func_code_tokens listlengths 20 832 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 102 339 |
|---|---|---|---|---|---|---|---|---|---|---|
wildfly/wildfly-core | server/src/main/java/org/jboss/as/server/deployment/DeploymentResourceSupport.java | DeploymentResourceSupport.getDeploymentSubModel | public ModelNode getDeploymentSubModel(final String subsystemName, final PathAddress address) {
"""
Gets the sub-model for a components from the deployment itself. Operations, metrics and descriptions have to be
registered as part of the subsystem registration {@link org.jboss.as.controller.ExtensionContext} and
{@link org.jboss.as.controller.SubsystemRegistration#registerDeploymentModel(org.jboss.as.controller.ResourceDefinition)}.
<p>
The subsystem resource as well as each {@link org.jboss.as.controller.PathAddress#getParent()} parent element}
from the address will be created if it does not already exist.
</p>
@param subsystemName the name of the subsystem
@param address the path address this sub-model should return the model for
@return the model for the resource
"""
assert subsystemName != null : "The subsystemName cannot be null";
assert address != null : "The address cannot be null";
return getDeploymentSubModel(subsystemName, address, null, deploymentUnit);
} | java | public ModelNode getDeploymentSubModel(final String subsystemName, final PathAddress address) {
assert subsystemName != null : "The subsystemName cannot be null";
assert address != null : "The address cannot be null";
return getDeploymentSubModel(subsystemName, address, null, deploymentUnit);
} | [
"public",
"ModelNode",
"getDeploymentSubModel",
"(",
"final",
"String",
"subsystemName",
",",
"final",
"PathAddress",
"address",
")",
"{",
"assert",
"subsystemName",
"!=",
"null",
":",
"\"The subsystemName cannot be null\"",
";",
"assert",
"address",
"!=",
"null",
":"... | Gets the sub-model for a components from the deployment itself. Operations, metrics and descriptions have to be
registered as part of the subsystem registration {@link org.jboss.as.controller.ExtensionContext} and
{@link org.jboss.as.controller.SubsystemRegistration#registerDeploymentModel(org.jboss.as.controller.ResourceDefinition)}.
<p>
The subsystem resource as well as each {@link org.jboss.as.controller.PathAddress#getParent()} parent element}
from the address will be created if it does not already exist.
</p>
@param subsystemName the name of the subsystem
@param address the path address this sub-model should return the model for
@return the model for the resource | [
"Gets",
"the",
"sub",
"-",
"model",
"for",
"a",
"components",
"from",
"the",
"deployment",
"itself",
".",
"Operations",
"metrics",
"and",
"descriptions",
"have",
"to",
"be",
"registered",
"as",
"part",
"of",
"the",
"subsystem",
"registration",
"{",
"@link",
... | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/DeploymentResourceSupport.java#L176-L180 |
defei/codelogger-utils | src/main/java/org/codelogger/utils/DateUtils.java | DateUtils.subMinutes | public static long subMinutes(final Date date1, final Date date2) {
"""
Get how many minutes between two date.
@param date1 date to be tested.
@param date2 date to be tested.
@return how many minutes between two date.
"""
return subTime(date1, date2, DatePeriod.MINUTE);
} | java | public static long subMinutes(final Date date1, final Date date2) {
return subTime(date1, date2, DatePeriod.MINUTE);
} | [
"public",
"static",
"long",
"subMinutes",
"(",
"final",
"Date",
"date1",
",",
"final",
"Date",
"date2",
")",
"{",
"return",
"subTime",
"(",
"date1",
",",
"date2",
",",
"DatePeriod",
".",
"MINUTE",
")",
";",
"}"
] | Get how many minutes between two date.
@param date1 date to be tested.
@param date2 date to be tested.
@return how many minutes between two date. | [
"Get",
"how",
"many",
"minutes",
"between",
"two",
"date",
"."
] | train | https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/DateUtils.java#L423-L426 |
radkovo/CSSBox | src/main/java/org/fit/cssbox/demo/SimpleBrowser.java | SimpleBrowser.initComponents | private void initComponents(URL baseurl) {
"""
Creates and initializes the GUI components
@param baseurl The base URL of the document used for completing the relative paths
"""
documentScroll = new javax.swing.JScrollPane();
//Create the browser canvas
browserCanvas = new BrowserCanvas(docroot, decoder, new java.awt.Dimension(1000, 600), baseurl);
//A simple mouse listener that displays the coordinates clicked
browserCanvas.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e)
{
System.out.println("Click: " + e.getX() + ":" + e.getY());
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
});
getContentPane().setLayout(new java.awt.GridLayout(1, 0));
setTitle("CSSBox Browser");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
documentScroll.setViewportView(browserCanvas);
getContentPane().add(documentScroll);
pack();
} | java | private void initComponents(URL baseurl)
{
documentScroll = new javax.swing.JScrollPane();
//Create the browser canvas
browserCanvas = new BrowserCanvas(docroot, decoder, new java.awt.Dimension(1000, 600), baseurl);
//A simple mouse listener that displays the coordinates clicked
browserCanvas.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e)
{
System.out.println("Click: " + e.getX() + ":" + e.getY());
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
});
getContentPane().setLayout(new java.awt.GridLayout(1, 0));
setTitle("CSSBox Browser");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
documentScroll.setViewportView(browserCanvas);
getContentPane().add(documentScroll);
pack();
} | [
"private",
"void",
"initComponents",
"(",
"URL",
"baseurl",
")",
"{",
"documentScroll",
"=",
"new",
"javax",
".",
"swing",
".",
"JScrollPane",
"(",
")",
";",
"//Create the browser canvas",
"browserCanvas",
"=",
"new",
"BrowserCanvas",
"(",
"docroot",
",",
"decod... | Creates and initializes the GUI components
@param baseurl The base URL of the document used for completing the relative paths | [
"Creates",
"and",
"initializes",
"the",
"GUI",
"components"
] | train | https://github.com/radkovo/CSSBox/blob/38aaf8f22d233d7b4dbc12a56cdbc72b447bc559/src/main/java/org/fit/cssbox/demo/SimpleBrowser.java#L78-L109 |
RKumsher/utils | src/main/java/com/github/rkumsher/number/RandomNumberUtils.java | RandomNumberUtils.randomLongGreaterThan | public static long randomLongGreaterThan(long minExclusive) {
"""
Returns a random long that is greater than the given long.
@param minExclusive the value that returned long must be greater than
@return the random long
@throws IllegalArgumentException if minExclusive is greater than or equal to {@link
Long#MAX_VALUE}
"""
checkArgument(
minExclusive < Long.MAX_VALUE, "Cannot produce long greater than %s", Long.MAX_VALUE);
return randomLong(minExclusive + 1, Long.MAX_VALUE);
} | java | public static long randomLongGreaterThan(long minExclusive) {
checkArgument(
minExclusive < Long.MAX_VALUE, "Cannot produce long greater than %s", Long.MAX_VALUE);
return randomLong(minExclusive + 1, Long.MAX_VALUE);
} | [
"public",
"static",
"long",
"randomLongGreaterThan",
"(",
"long",
"minExclusive",
")",
"{",
"checkArgument",
"(",
"minExclusive",
"<",
"Long",
".",
"MAX_VALUE",
",",
"\"Cannot produce long greater than %s\"",
",",
"Long",
".",
"MAX_VALUE",
")",
";",
"return",
"rando... | Returns a random long that is greater than the given long.
@param minExclusive the value that returned long must be greater than
@return the random long
@throws IllegalArgumentException if minExclusive is greater than or equal to {@link
Long#MAX_VALUE} | [
"Returns",
"a",
"random",
"long",
"that",
"is",
"greater",
"than",
"the",
"given",
"long",
"."
] | train | https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/number/RandomNumberUtils.java#L139-L143 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/builder/EqualsBuilder.java | EqualsBuilder.isRegistered | @GwtIncompatible("incompatible method")
static boolean isRegistered(final Object lhs, final Object rhs) {
"""
<p>
Returns <code>true</code> if the registry contains the given object pair.
Used by the reflection methods to avoid infinite loops.
Objects might be swapped therefore a check is needed if the object pair
is registered in given or swapped order.
</p>
@param lhs <code>this</code> object to lookup in registry
@param rhs the other object to lookup on registry
@return boolean <code>true</code> if the registry contains the given object.
@since 3.0
"""
final Set<Pair<IDKey, IDKey>> registry = getRegistry();
final Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
final Pair<IDKey, IDKey> swappedPair = Pair.of(pair.getRight(), pair.getLeft());
return registry != null
&& (registry.contains(pair) || registry.contains(swappedPair));
} | java | @GwtIncompatible("incompatible method")
static boolean isRegistered(final Object lhs, final Object rhs) {
final Set<Pair<IDKey, IDKey>> registry = getRegistry();
final Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
final Pair<IDKey, IDKey> swappedPair = Pair.of(pair.getRight(), pair.getLeft());
return registry != null
&& (registry.contains(pair) || registry.contains(swappedPair));
} | [
"@",
"GwtIncompatible",
"(",
"\"incompatible method\"",
")",
"static",
"boolean",
"isRegistered",
"(",
"final",
"Object",
"lhs",
",",
"final",
"Object",
"rhs",
")",
"{",
"final",
"Set",
"<",
"Pair",
"<",
"IDKey",
",",
"IDKey",
">",
">",
"registry",
"=",
"g... | <p>
Returns <code>true</code> if the registry contains the given object pair.
Used by the reflection methods to avoid infinite loops.
Objects might be swapped therefore a check is needed if the object pair
is registered in given or swapped order.
</p>
@param lhs <code>this</code> object to lookup in registry
@param rhs the other object to lookup on registry
@return boolean <code>true</code> if the registry contains the given object.
@since 3.0 | [
"<p",
">",
"Returns",
"<code",
">",
"true<",
"/",
"code",
">",
"if",
"the",
"registry",
"contains",
"the",
"given",
"object",
"pair",
".",
"Used",
"by",
"the",
"reflection",
"methods",
"to",
"avoid",
"infinite",
"loops",
".",
"Objects",
"might",
"be",
"s... | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/builder/EqualsBuilder.java#L161-L169 |
openengsb/openengsb | components/edb/src/main/java/org/openengsb/core/edb/jpa/internal/Diff.java | Diff.addNewObjects | private void addNewObjects(List<EDBObject> tempList) {
"""
add all new object to the diff collection. As base to indicate if an object is new, the list of elements from the
end state which are left is taken.
"""
for (EDBObject b : tempList) {
String oid = b.getOID();
ObjectDiff odiff = new ObjectDiff(this.startCommit, this.endCommit, null, b);
if (odiff.getDifferenceCount() > 0) {
diff.put(oid, odiff);
}
}
} | java | private void addNewObjects(List<EDBObject> tempList) {
for (EDBObject b : tempList) {
String oid = b.getOID();
ObjectDiff odiff = new ObjectDiff(this.startCommit, this.endCommit, null, b);
if (odiff.getDifferenceCount() > 0) {
diff.put(oid, odiff);
}
}
} | [
"private",
"void",
"addNewObjects",
"(",
"List",
"<",
"EDBObject",
">",
"tempList",
")",
"{",
"for",
"(",
"EDBObject",
"b",
":",
"tempList",
")",
"{",
"String",
"oid",
"=",
"b",
".",
"getOID",
"(",
")",
";",
"ObjectDiff",
"odiff",
"=",
"new",
"ObjectDi... | add all new object to the diff collection. As base to indicate if an object is new, the list of elements from the
end state which are left is taken. | [
"add",
"all",
"new",
"object",
"to",
"the",
"diff",
"collection",
".",
"As",
"base",
"to",
"indicate",
"if",
"an",
"object",
"is",
"new",
"the",
"list",
"of",
"elements",
"from",
"the",
"end",
"state",
"which",
"are",
"left",
"is",
"taken",
"."
] | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/edb/src/main/java/org/openengsb/core/edb/jpa/internal/Diff.java#L93-L101 |
JodaOrg/joda-time | src/main/java/org/joda/time/format/DateTimeFormat.java | DateTimeFormat.isNumericToken | private static boolean isNumericToken(String token) {
"""
Returns true if token should be parsed as a numeric field.
@param token the token to parse
@return true if numeric field
"""
int tokenLen = token.length();
if (tokenLen > 0) {
char c = token.charAt(0);
switch (c) {
case 'c': // century (number)
case 'C': // century of era (number)
case 'x': // weekyear (number)
case 'y': // year (number)
case 'Y': // year of era (number)
case 'd': // day of month (number)
case 'h': // hour of day (number, 1..12)
case 'H': // hour of day (number, 0..23)
case 'm': // minute of hour (number)
case 's': // second of minute (number)
case 'S': // fraction of second (number)
case 'e': // day of week (number)
case 'D': // day of year (number)
case 'F': // day of week in month (number)
case 'w': // week of year (number)
case 'W': // week of month (number)
case 'k': // hour of day (1..24)
case 'K': // hour of day (0..11)
return true;
case 'M': // month of year (text and number)
if (tokenLen <= 2) {
return true;
}
}
}
return false;
} | java | private static boolean isNumericToken(String token) {
int tokenLen = token.length();
if (tokenLen > 0) {
char c = token.charAt(0);
switch (c) {
case 'c': // century (number)
case 'C': // century of era (number)
case 'x': // weekyear (number)
case 'y': // year (number)
case 'Y': // year of era (number)
case 'd': // day of month (number)
case 'h': // hour of day (number, 1..12)
case 'H': // hour of day (number, 0..23)
case 'm': // minute of hour (number)
case 's': // second of minute (number)
case 'S': // fraction of second (number)
case 'e': // day of week (number)
case 'D': // day of year (number)
case 'F': // day of week in month (number)
case 'w': // week of year (number)
case 'W': // week of month (number)
case 'k': // hour of day (1..24)
case 'K': // hour of day (0..11)
return true;
case 'M': // month of year (text and number)
if (tokenLen <= 2) {
return true;
}
}
}
return false;
} | [
"private",
"static",
"boolean",
"isNumericToken",
"(",
"String",
"token",
")",
"{",
"int",
"tokenLen",
"=",
"token",
".",
"length",
"(",
")",
";",
"if",
"(",
"tokenLen",
">",
"0",
")",
"{",
"char",
"c",
"=",
"token",
".",
"charAt",
"(",
"0",
")",
"... | Returns true if token should be parsed as a numeric field.
@param token the token to parse
@return true if numeric field | [
"Returns",
"true",
"if",
"token",
"should",
"be",
"parsed",
"as",
"a",
"numeric",
"field",
"."
] | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/format/DateTimeFormat.java#L638-L670 |
comapi/comapi-sdk-android | COMAPI/foundation/src/main/java/com/comapi/internal/log/AppenderFile.java | AppenderFile.mergeFiles | private void mergeFiles(@NonNull File mergedFile) throws IOException {
"""
Merged content of internal log files.
@param mergedFile Instance of a file to merge logs into.
"""
Context context = appContextRef.get();
if (context != null) {
FileWriter fw;
BufferedWriter bw;
fw = new FileWriter(mergedFile, true);
bw = new BufferedWriter(fw);
File dir = context.getFilesDir();
for (int i = 1; i <= maxFiles; i++) {
File file = new File(dir, name(i));
if (file.exists()) {
FileInputStream fis;
try {
fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
//noinspection TryFinallyCanBeTryWithResources
try {
String aLine;
while ((aLine = br.readLine()) != null) {
bw.write(aLine);
bw.newLine();
}
} finally {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
bw.close();
}
} | java | private void mergeFiles(@NonNull File mergedFile) throws IOException {
Context context = appContextRef.get();
if (context != null) {
FileWriter fw;
BufferedWriter bw;
fw = new FileWriter(mergedFile, true);
bw = new BufferedWriter(fw);
File dir = context.getFilesDir();
for (int i = 1; i <= maxFiles; i++) {
File file = new File(dir, name(i));
if (file.exists()) {
FileInputStream fis;
try {
fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
//noinspection TryFinallyCanBeTryWithResources
try {
String aLine;
while ((aLine = br.readLine()) != null) {
bw.write(aLine);
bw.newLine();
}
} finally {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
bw.close();
}
} | [
"private",
"void",
"mergeFiles",
"(",
"@",
"NonNull",
"File",
"mergedFile",
")",
"throws",
"IOException",
"{",
"Context",
"context",
"=",
"appContextRef",
".",
"get",
"(",
")",
";",
"if",
"(",
"context",
"!=",
"null",
")",
"{",
"FileWriter",
"fw",
";",
"... | Merged content of internal log files.
@param mergedFile Instance of a file to merge logs into. | [
"Merged",
"content",
"of",
"internal",
"log",
"files",
"."
] | train | https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/log/AppenderFile.java#L284-L324 |
spotbugs/spotbugs | spotbugs/src/gui/main/edu/umd/cs/findbugs/gui2/BugLoader.java | BugLoader.doAnalysis | public static BugCollection doAnalysis(@Nonnull Project p, FindBugsProgress progressCallback) throws IOException,
InterruptedException {
"""
Performs an analysis and returns the BugSet created
@param p
The Project to run the analysis on
@param progressCallback
the progressCallBack is supposed to be supplied by analyzing
dialog, FindBugs supplies progress information while it runs
the analysis
@return the bugs found
@throws InterruptedException
@throws IOException
"""
StringWriter stringWriter = new StringWriter();
BugCollectionBugReporter pcb = new BugCollectionBugReporter(p, new PrintWriter(stringWriter, true));
pcb.setPriorityThreshold(Priorities.LOW_PRIORITY);
IFindBugsEngine fb = createEngine(p, pcb);
fb.setUserPreferences(getUserPreferences());
fb.setProgressCallback(progressCallback);
fb.setProjectName(p.getProjectName());
fb.execute();
String warnings = stringWriter.toString();
if (warnings.length() > 0) {
JTextArea tp = new JTextArea(warnings);
tp.setEditable(false);
JScrollPane pane = new JScrollPane(tp);
pane.setPreferredSize(new Dimension(600, 400));
JOptionPane.showMessageDialog(MainFrame.getInstance(),
pane, "Analysis errors",
JOptionPane.WARNING_MESSAGE);
}
return pcb.getBugCollection();
} | java | public static BugCollection doAnalysis(@Nonnull Project p, FindBugsProgress progressCallback) throws IOException,
InterruptedException {
StringWriter stringWriter = new StringWriter();
BugCollectionBugReporter pcb = new BugCollectionBugReporter(p, new PrintWriter(stringWriter, true));
pcb.setPriorityThreshold(Priorities.LOW_PRIORITY);
IFindBugsEngine fb = createEngine(p, pcb);
fb.setUserPreferences(getUserPreferences());
fb.setProgressCallback(progressCallback);
fb.setProjectName(p.getProjectName());
fb.execute();
String warnings = stringWriter.toString();
if (warnings.length() > 0) {
JTextArea tp = new JTextArea(warnings);
tp.setEditable(false);
JScrollPane pane = new JScrollPane(tp);
pane.setPreferredSize(new Dimension(600, 400));
JOptionPane.showMessageDialog(MainFrame.getInstance(),
pane, "Analysis errors",
JOptionPane.WARNING_MESSAGE);
}
return pcb.getBugCollection();
} | [
"public",
"static",
"BugCollection",
"doAnalysis",
"(",
"@",
"Nonnull",
"Project",
"p",
",",
"FindBugsProgress",
"progressCallback",
")",
"throws",
"IOException",
",",
"InterruptedException",
"{",
"StringWriter",
"stringWriter",
"=",
"new",
"StringWriter",
"(",
")",
... | Performs an analysis and returns the BugSet created
@param p
The Project to run the analysis on
@param progressCallback
the progressCallBack is supposed to be supplied by analyzing
dialog, FindBugs supplies progress information while it runs
the analysis
@return the bugs found
@throws InterruptedException
@throws IOException | [
"Performs",
"an",
"analysis",
"and",
"returns",
"the",
"BugSet",
"created"
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/gui/main/edu/umd/cs/findbugs/gui2/BugLoader.java#L90-L113 |
apache/flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/InternalTimerServiceImpl.java | InternalTimerServiceImpl.restoreTimersForKeyGroup | @SuppressWarnings("unchecked")
public void restoreTimersForKeyGroup(InternalTimersSnapshot<?, ?> restoredSnapshot, int keyGroupIdx) {
"""
Restore the timers (both processing and event time ones) for a given {@code keyGroupIdx}.
@param restoredSnapshot the restored snapshot containing the key-group's timers,
and the serializers that were used to write them
@param keyGroupIdx the id of the key-group to be put in the snapshot.
"""
this.restoredTimersSnapshot = (InternalTimersSnapshot<K, N>) restoredSnapshot;
TypeSerializer<K> restoredKeySerializer = restoredTimersSnapshot.getKeySerializerSnapshot().restoreSerializer();
if (this.keyDeserializer != null && !this.keyDeserializer.equals(restoredKeySerializer)) {
throw new IllegalArgumentException("Tried to restore timers for the same service with different key serializers.");
}
this.keyDeserializer = restoredKeySerializer;
TypeSerializer<N> restoredNamespaceSerializer = restoredTimersSnapshot.getNamespaceSerializerSnapshot().restoreSerializer();
if (this.namespaceDeserializer != null && !this.namespaceDeserializer.equals(restoredNamespaceSerializer)) {
throw new IllegalArgumentException("Tried to restore timers for the same service with different namespace serializers.");
}
this.namespaceDeserializer = restoredNamespaceSerializer;
checkArgument(localKeyGroupRange.contains(keyGroupIdx),
"Key Group " + keyGroupIdx + " does not belong to the local range.");
// restore the event time timers
eventTimeTimersQueue.addAll(restoredTimersSnapshot.getEventTimeTimers());
// restore the processing time timers
processingTimeTimersQueue.addAll(restoredTimersSnapshot.getProcessingTimeTimers());
} | java | @SuppressWarnings("unchecked")
public void restoreTimersForKeyGroup(InternalTimersSnapshot<?, ?> restoredSnapshot, int keyGroupIdx) {
this.restoredTimersSnapshot = (InternalTimersSnapshot<K, N>) restoredSnapshot;
TypeSerializer<K> restoredKeySerializer = restoredTimersSnapshot.getKeySerializerSnapshot().restoreSerializer();
if (this.keyDeserializer != null && !this.keyDeserializer.equals(restoredKeySerializer)) {
throw new IllegalArgumentException("Tried to restore timers for the same service with different key serializers.");
}
this.keyDeserializer = restoredKeySerializer;
TypeSerializer<N> restoredNamespaceSerializer = restoredTimersSnapshot.getNamespaceSerializerSnapshot().restoreSerializer();
if (this.namespaceDeserializer != null && !this.namespaceDeserializer.equals(restoredNamespaceSerializer)) {
throw new IllegalArgumentException("Tried to restore timers for the same service with different namespace serializers.");
}
this.namespaceDeserializer = restoredNamespaceSerializer;
checkArgument(localKeyGroupRange.contains(keyGroupIdx),
"Key Group " + keyGroupIdx + " does not belong to the local range.");
// restore the event time timers
eventTimeTimersQueue.addAll(restoredTimersSnapshot.getEventTimeTimers());
// restore the processing time timers
processingTimeTimersQueue.addAll(restoredTimersSnapshot.getProcessingTimeTimers());
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"void",
"restoreTimersForKeyGroup",
"(",
"InternalTimersSnapshot",
"<",
"?",
",",
"?",
">",
"restoredSnapshot",
",",
"int",
"keyGroupIdx",
")",
"{",
"this",
".",
"restoredTimersSnapshot",
"=",
"(",
"Int... | Restore the timers (both processing and event time ones) for a given {@code keyGroupIdx}.
@param restoredSnapshot the restored snapshot containing the key-group's timers,
and the serializers that were used to write them
@param keyGroupIdx the id of the key-group to be put in the snapshot. | [
"Restore",
"the",
"timers",
"(",
"both",
"processing",
"and",
"event",
"time",
"ones",
")",
"for",
"a",
"given",
"{",
"@code",
"keyGroupIdx",
"}",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/InternalTimerServiceImpl.java#L288-L312 |
osglworks/java-tool | src/main/java/org/osgl/util/E.java | E.invalidStateIf | public static void invalidStateIf(boolean tester, String msg, Object... args) {
"""
Throws out an {@link InvalidStateException} when `tester` evaluated to `true`.
@param tester
when `true` then an {@link InvalidStateException} will be thrown out.
@param msg
the message format template
@param args
the message format arguments
"""
if (tester) {
invalidState(msg, args);
}
} | java | public static void invalidStateIf(boolean tester, String msg, Object... args) {
if (tester) {
invalidState(msg, args);
}
} | [
"public",
"static",
"void",
"invalidStateIf",
"(",
"boolean",
"tester",
",",
"String",
"msg",
",",
"Object",
"...",
"args",
")",
"{",
"if",
"(",
"tester",
")",
"{",
"invalidState",
"(",
"msg",
",",
"args",
")",
";",
"}",
"}"
] | Throws out an {@link InvalidStateException} when `tester` evaluated to `true`.
@param tester
when `true` then an {@link InvalidStateException} will be thrown out.
@param msg
the message format template
@param args
the message format arguments | [
"Throws",
"out",
"an",
"{",
"@link",
"InvalidStateException",
"}",
"when",
"tester",
"evaluated",
"to",
"true",
"."
] | train | https://github.com/osglworks/java-tool/blob/8b6eee2bccb067eb32e6a7bc4a4dfef7a7d9008b/src/main/java/org/osgl/util/E.java#L92-L96 |
s1-platform/s1 | s1-core/src/java/org/s1/format/json/org_json_simple/JSONArray.java | JSONArray.writeJSONString | public static void writeJSONString(Collection collection, Writer out) throws IOException {
"""
Encode a list into JSON text and write it to out.
If this list is also a JSONStreamAware or a JSONAware, JSONStreamAware and JSONAware specific behaviours will be ignored at this top level.
@see org.json.simple.JSONValue#writeJSONString(Object, java.io.Writer)
@param collection
@param out
"""
if(collection == null){
out.write("null");
return;
}
boolean first = true;
Iterator iter=collection.iterator();
out.write('[');
while(iter.hasNext()){
if(first)
first = false;
else
out.write(',');
Object value=iter.next();
if(value == null){
out.write("null");
continue;
}
JSONValue.writeJSONString(value, out);
}
out.write(']');
} | java | public static void writeJSONString(Collection collection, Writer out) throws IOException{
if(collection == null){
out.write("null");
return;
}
boolean first = true;
Iterator iter=collection.iterator();
out.write('[');
while(iter.hasNext()){
if(first)
first = false;
else
out.write(',');
Object value=iter.next();
if(value == null){
out.write("null");
continue;
}
JSONValue.writeJSONString(value, out);
}
out.write(']');
} | [
"public",
"static",
"void",
"writeJSONString",
"(",
"Collection",
"collection",
",",
"Writer",
"out",
")",
"throws",
"IOException",
"{",
"if",
"(",
"collection",
"==",
"null",
")",
"{",
"out",
".",
"write",
"(",
"\"null\"",
")",
";",
"return",
";",
"}",
... | Encode a list into JSON text and write it to out.
If this list is also a JSONStreamAware or a JSONAware, JSONStreamAware and JSONAware specific behaviours will be ignored at this top level.
@see org.json.simple.JSONValue#writeJSONString(Object, java.io.Writer)
@param collection
@param out | [
"Encode",
"a",
"list",
"into",
"JSON",
"text",
"and",
"write",
"it",
"to",
"out",
".",
"If",
"this",
"list",
"is",
"also",
"a",
"JSONStreamAware",
"or",
"a",
"JSONAware",
"JSONStreamAware",
"and",
"JSONAware",
"specific",
"behaviours",
"will",
"be",
"ignored... | train | https://github.com/s1-platform/s1/blob/370101c13fef01af524bc171bcc1a97e5acc76e8/s1-core/src/java/org/s1/format/json/org_json_simple/JSONArray.java#L64-L89 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/convert/NumberChineseFormater.java | NumberChineseFormater.toChinese | private static String toChinese(int amountPart, boolean isUseTraditional) {
"""
把一个 0~9999 之间的整数转换为汉字的字符串,如果是 0 则返回 ""
@param amountPart 数字部分
@param isUseTraditional 是否使用繁体单位
@return 转换后的汉字
"""
// if (amountPart < 0 || amountPart > 10000) {
// throw new IllegalArgumentException("Number must 0 < num < 10000!");
// }
String[] numArray = isUseTraditional ? traditionalDigits : simpleDigits;
String[] units = isUseTraditional ? traditionalUnits : simpleUnits;
int temp = amountPart;
String chineseStr = "";
boolean lastIsZero = true; // 在从低位往高位循环时,记录上一位数字是不是 0
for (int i = 0; temp > 0; i++) {
if (temp == 0) {
// 高位已无数据
break;
}
int digit = temp % 10;
if (digit == 0) { // 取到的数字为 0
if (false == lastIsZero) {
// 前一个数字不是 0,则在当前汉字串前加“零”字;
chineseStr = "零" + chineseStr;
}
lastIsZero = true;
} else { // 取到的数字不是 0
chineseStr = numArray[digit] + units[i] + chineseStr;
lastIsZero = false;
}
temp = temp / 10;
}
return chineseStr;
} | java | private static String toChinese(int amountPart, boolean isUseTraditional) {
// if (amountPart < 0 || amountPart > 10000) {
// throw new IllegalArgumentException("Number must 0 < num < 10000!");
// }
String[] numArray = isUseTraditional ? traditionalDigits : simpleDigits;
String[] units = isUseTraditional ? traditionalUnits : simpleUnits;
int temp = amountPart;
String chineseStr = "";
boolean lastIsZero = true; // 在从低位往高位循环时,记录上一位数字是不是 0
for (int i = 0; temp > 0; i++) {
if (temp == 0) {
// 高位已无数据
break;
}
int digit = temp % 10;
if (digit == 0) { // 取到的数字为 0
if (false == lastIsZero) {
// 前一个数字不是 0,则在当前汉字串前加“零”字;
chineseStr = "零" + chineseStr;
}
lastIsZero = true;
} else { // 取到的数字不是 0
chineseStr = numArray[digit] + units[i] + chineseStr;
lastIsZero = false;
}
temp = temp / 10;
}
return chineseStr;
} | [
"private",
"static",
"String",
"toChinese",
"(",
"int",
"amountPart",
",",
"boolean",
"isUseTraditional",
")",
"{",
"//\t\tif (amountPart < 0 || amountPart > 10000) {",
"//\t\t\tthrow new IllegalArgumentException(\"Number must 0 < num < 10000!\");",
"//\t\t}",
"String",
"[",
"]",
... | 把一个 0~9999 之间的整数转换为汉字的字符串,如果是 0 则返回 ""
@param amountPart 数字部分
@param isUseTraditional 是否使用繁体单位
@return 转换后的汉字 | [
"把一个",
"0~9999",
"之间的整数转换为汉字的字符串,如果是",
"0",
"则返回"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/convert/NumberChineseFormater.java#L140-L171 |
trellis-ldp/trellis | core/http/src/main/java/org/trellisldp/http/TrellisHttpResource.java | TrellisHttpResource.updateResource | @PATCH
@Timed
public void updateResource(@Suspended final AsyncResponse response, @Context final Request request,
@Context final UriInfo uriInfo, @Context final HttpHeaders headers,
@Context final SecurityContext secContext, final String body) {
"""
Perform a PATCH operation on an LDP Resource.
@param response the async response
@param uriInfo the URI info
@param secContext the security context
@param headers the HTTP headers
@param request the request
@param body the body
"""
final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, secContext);
final String urlBase = getBaseUrl(req);
final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + req.getPath());
final PatchHandler patchHandler = new PatchHandler(req, body, trellis, defaultJsonLdProfile, urlBase);
getParent(identifier).thenCombine(trellis.getResourceService().get(identifier), patchHandler::initialize)
.thenCompose(patchHandler::updateResource).thenCompose(patchHandler::updateMemento)
.thenApply(ResponseBuilder::build).exceptionally(this::handleException).thenApply(response::resume);
} | java | @PATCH
@Timed
public void updateResource(@Suspended final AsyncResponse response, @Context final Request request,
@Context final UriInfo uriInfo, @Context final HttpHeaders headers,
@Context final SecurityContext secContext, final String body) {
final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, secContext);
final String urlBase = getBaseUrl(req);
final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + req.getPath());
final PatchHandler patchHandler = new PatchHandler(req, body, trellis, defaultJsonLdProfile, urlBase);
getParent(identifier).thenCombine(trellis.getResourceService().get(identifier), patchHandler::initialize)
.thenCompose(patchHandler::updateResource).thenCompose(patchHandler::updateMemento)
.thenApply(ResponseBuilder::build).exceptionally(this::handleException).thenApply(response::resume);
} | [
"@",
"PATCH",
"@",
"Timed",
"public",
"void",
"updateResource",
"(",
"@",
"Suspended",
"final",
"AsyncResponse",
"response",
",",
"@",
"Context",
"final",
"Request",
"request",
",",
"@",
"Context",
"final",
"UriInfo",
"uriInfo",
",",
"@",
"Context",
"final",
... | Perform a PATCH operation on an LDP Resource.
@param response the async response
@param uriInfo the URI info
@param secContext the security context
@param headers the HTTP headers
@param request the request
@param body the body | [
"Perform",
"a",
"PATCH",
"operation",
"on",
"an",
"LDP",
"Resource",
"."
] | train | https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/core/http/src/main/java/org/trellisldp/http/TrellisHttpResource.java#L261-L274 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/circuit/CircuitsConfig.java | CircuitsConfig.exports | public static void exports(Media media, Map<Circuit, Collection<TileRef>> circuits) {
"""
Export all circuits to an XML file.
@param media The export output (must not be <code>null</code>).
@param circuits The circuits reference (must not be <code>null</code>).
@throws LionEngineException If error on export.
"""
Check.notNull(media);
Check.notNull(circuits);
final Xml nodeCircuits = new Xml(NODE_CIRCUITS);
for (final Map.Entry<Circuit, Collection<TileRef>> entry : circuits.entrySet())
{
final Circuit circuit = entry.getKey();
final Xml nodeCircuit = nodeCircuits.createChild(NODE_CIRCUIT);
nodeCircuit.writeString(ATT_CIRCUIT_TYPE, circuit.getType().name());
nodeCircuit.writeString(ATT_GROUP_IN, circuit.getIn());
nodeCircuit.writeString(ATT_GROUP_OUT, circuit.getOut());
exportTiles(nodeCircuit, entry.getValue());
}
nodeCircuits.save(media);
} | java | public static void exports(Media media, Map<Circuit, Collection<TileRef>> circuits)
{
Check.notNull(media);
Check.notNull(circuits);
final Xml nodeCircuits = new Xml(NODE_CIRCUITS);
for (final Map.Entry<Circuit, Collection<TileRef>> entry : circuits.entrySet())
{
final Circuit circuit = entry.getKey();
final Xml nodeCircuit = nodeCircuits.createChild(NODE_CIRCUIT);
nodeCircuit.writeString(ATT_CIRCUIT_TYPE, circuit.getType().name());
nodeCircuit.writeString(ATT_GROUP_IN, circuit.getIn());
nodeCircuit.writeString(ATT_GROUP_OUT, circuit.getOut());
exportTiles(nodeCircuit, entry.getValue());
}
nodeCircuits.save(media);
} | [
"public",
"static",
"void",
"exports",
"(",
"Media",
"media",
",",
"Map",
"<",
"Circuit",
",",
"Collection",
"<",
"TileRef",
">",
">",
"circuits",
")",
"{",
"Check",
".",
"notNull",
"(",
"media",
")",
";",
"Check",
".",
"notNull",
"(",
"circuits",
")",... | Export all circuits to an XML file.
@param media The export output (must not be <code>null</code>).
@param circuits The circuits reference (must not be <code>null</code>).
@throws LionEngineException If error on export. | [
"Export",
"all",
"circuits",
"to",
"an",
"XML",
"file",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/circuit/CircuitsConfig.java#L119-L138 |
spotbugs/spotbugs | eclipsePlugin/src/edu/umd/cs/findbugs/plugin/eclipse/quickfix/util/ASTUtil.java | ASTUtil.getTypeDeclaration | public static TypeDeclaration getTypeDeclaration(CompilationUnit compilationUnit, ClassAnnotation classAnno)
throws TypeDeclarationNotFoundException {
"""
Returns the <CODE>TypeDeclaration</CODE> for the specified
<CODE>ClassAnnotation</CODE>. The type has to be declared in the
specified <CODE>CompilationUnit</CODE>.
@param compilationUnit
The <CODE>CompilationUnit</CODE>, where the
<CODE>TypeDeclaration</CODE> is declared in.
@param classAnno
The <CODE>ClassAnnotation</CODE>, which contains the class
name of the <CODE>TypeDeclaration</CODE>.
@return the <CODE>TypeDeclaration</CODE> found in the specified
<CODE>CompilationUnit</CODE>.
@throws TypeDeclarationNotFoundException
if no matching <CODE>TypeDeclaration</CODE> was found.
"""
requireNonNull(classAnno, "class annotation");
return getTypeDeclaration(compilationUnit, classAnno.getClassName());
} | java | public static TypeDeclaration getTypeDeclaration(CompilationUnit compilationUnit, ClassAnnotation classAnno)
throws TypeDeclarationNotFoundException {
requireNonNull(classAnno, "class annotation");
return getTypeDeclaration(compilationUnit, classAnno.getClassName());
} | [
"public",
"static",
"TypeDeclaration",
"getTypeDeclaration",
"(",
"CompilationUnit",
"compilationUnit",
",",
"ClassAnnotation",
"classAnno",
")",
"throws",
"TypeDeclarationNotFoundException",
"{",
"requireNonNull",
"(",
"classAnno",
",",
"\"class annotation\"",
")",
";",
"r... | Returns the <CODE>TypeDeclaration</CODE> for the specified
<CODE>ClassAnnotation</CODE>. The type has to be declared in the
specified <CODE>CompilationUnit</CODE>.
@param compilationUnit
The <CODE>CompilationUnit</CODE>, where the
<CODE>TypeDeclaration</CODE> is declared in.
@param classAnno
The <CODE>ClassAnnotation</CODE>, which contains the class
name of the <CODE>TypeDeclaration</CODE>.
@return the <CODE>TypeDeclaration</CODE> found in the specified
<CODE>CompilationUnit</CODE>.
@throws TypeDeclarationNotFoundException
if no matching <CODE>TypeDeclaration</CODE> was found. | [
"Returns",
"the",
"<CODE",
">",
"TypeDeclaration<",
"/",
"CODE",
">",
"for",
"the",
"specified",
"<CODE",
">",
"ClassAnnotation<",
"/",
"CODE",
">",
".",
"The",
"type",
"has",
"to",
"be",
"declared",
"in",
"the",
"specified",
"<CODE",
">",
"CompilationUnit<"... | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/eclipsePlugin/src/edu/umd/cs/findbugs/plugin/eclipse/quickfix/util/ASTUtil.java#L228-L232 |
haraldk/TwelveMonkeys | common/common-image/src/main/java/com/twelvemonkeys/image/CopyDither.java | CopyDither.filter | public final WritableRaster filter(final Raster pSource, WritableRaster pDest) {
"""
Performs a single-input/single-output dither operation, applying basic
Floyd-Steinberg error-diffusion to the image.
@param pSource
@param pDest
@return the destination raster, or a new raster, if {@code pDest} was
{@code null}.
"""
return filter(pSource, pDest, getICM(pSource));
} | java | public final WritableRaster filter(final Raster pSource, WritableRaster pDest) {
return filter(pSource, pDest, getICM(pSource));
} | [
"public",
"final",
"WritableRaster",
"filter",
"(",
"final",
"Raster",
"pSource",
",",
"WritableRaster",
"pDest",
")",
"{",
"return",
"filter",
"(",
"pSource",
",",
"pDest",
",",
"getICM",
"(",
"pSource",
")",
")",
";",
"}"
] | Performs a single-input/single-output dither operation, applying basic
Floyd-Steinberg error-diffusion to the image.
@param pSource
@param pDest
@return the destination raster, or a new raster, if {@code pDest} was
{@code null}. | [
"Performs",
"a",
"single",
"-",
"input",
"/",
"single",
"-",
"output",
"dither",
"operation",
"applying",
"basic",
"Floyd",
"-",
"Steinberg",
"error",
"-",
"diffusion",
"to",
"the",
"image",
"."
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-image/src/main/java/com/twelvemonkeys/image/CopyDither.java#L220-L222 |
ag-gipp/MathMLTools | mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/distances/Distances.java | Distances.cleanupHistogram | private static void cleanupHistogram(String tagName, Map<String, Double> histogram) {
"""
this cleanup is necessary due to errors in the xslt conversion script (contentmathmml to strict cmml)
@param tagName
@param histogram
"""
switch (tagName) {
case "csymbol":
histogram.remove("based_integer");
for (String key : ValidCSymbols.VALID_CSYMBOLS) {
histogram.remove(key);
}
break;
case "ci":
histogram.remove("integer");
break;
case "cn":
Set<String> toberemovedKeys = new HashSet<>();
for (String key : histogram.keySet()) {
if (!isNumeric(key)) {
toberemovedKeys.add(key);
}
}
// now we can remove the keys
for (String key : toberemovedKeys) {
histogram.remove(key);
}
break;
default: // ignore others
}
} | java | private static void cleanupHistogram(String tagName, Map<String, Double> histogram) {
switch (tagName) {
case "csymbol":
histogram.remove("based_integer");
for (String key : ValidCSymbols.VALID_CSYMBOLS) {
histogram.remove(key);
}
break;
case "ci":
histogram.remove("integer");
break;
case "cn":
Set<String> toberemovedKeys = new HashSet<>();
for (String key : histogram.keySet()) {
if (!isNumeric(key)) {
toberemovedKeys.add(key);
}
}
// now we can remove the keys
for (String key : toberemovedKeys) {
histogram.remove(key);
}
break;
default: // ignore others
}
} | [
"private",
"static",
"void",
"cleanupHistogram",
"(",
"String",
"tagName",
",",
"Map",
"<",
"String",
",",
"Double",
">",
"histogram",
")",
"{",
"switch",
"(",
"tagName",
")",
"{",
"case",
"\"csymbol\"",
":",
"histogram",
".",
"remove",
"(",
"\"based_integer... | this cleanup is necessary due to errors in the xslt conversion script (contentmathmml to strict cmml)
@param tagName
@param histogram | [
"this",
"cleanup",
"is",
"necessary",
"due",
"to",
"errors",
"in",
"the",
"xslt",
"conversion",
"script",
"(",
"contentmathmml",
"to",
"strict",
"cmml",
")"
] | train | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/distances/Distances.java#L220-L245 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FacesImpl.java | FacesImpl.identifyWithServiceResponseAsync | public Observable<ServiceResponse<List<IdentifyResult>>> identifyWithServiceResponseAsync(String personGroupId, List<UUID> faceIds, IdentifyOptionalParameter identifyOptionalParameter) {
"""
Identify unknown faces from a person group.
@param personGroupId PersonGroupId of the target person group, created by PersonGroups.Create
@param faceIds Array of query faces faceIds, created by the Face - Detect. Each of the faces are identified independently. The valid number of faceIds is between [1, 10].
@param identifyOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<IdentifyResult> object
"""
if (this.client.azureRegion() == null) {
throw new IllegalArgumentException("Parameter this.client.azureRegion() is required and cannot be null.");
}
if (personGroupId == null) {
throw new IllegalArgumentException("Parameter personGroupId is required and cannot be null.");
}
if (faceIds == null) {
throw new IllegalArgumentException("Parameter faceIds is required and cannot be null.");
}
Validator.validate(faceIds);
final Integer maxNumOfCandidatesReturned = identifyOptionalParameter != null ? identifyOptionalParameter.maxNumOfCandidatesReturned() : null;
final Double confidenceThreshold = identifyOptionalParameter != null ? identifyOptionalParameter.confidenceThreshold() : null;
return identifyWithServiceResponseAsync(personGroupId, faceIds, maxNumOfCandidatesReturned, confidenceThreshold);
} | java | public Observable<ServiceResponse<List<IdentifyResult>>> identifyWithServiceResponseAsync(String personGroupId, List<UUID> faceIds, IdentifyOptionalParameter identifyOptionalParameter) {
if (this.client.azureRegion() == null) {
throw new IllegalArgumentException("Parameter this.client.azureRegion() is required and cannot be null.");
}
if (personGroupId == null) {
throw new IllegalArgumentException("Parameter personGroupId is required and cannot be null.");
}
if (faceIds == null) {
throw new IllegalArgumentException("Parameter faceIds is required and cannot be null.");
}
Validator.validate(faceIds);
final Integer maxNumOfCandidatesReturned = identifyOptionalParameter != null ? identifyOptionalParameter.maxNumOfCandidatesReturned() : null;
final Double confidenceThreshold = identifyOptionalParameter != null ? identifyOptionalParameter.confidenceThreshold() : null;
return identifyWithServiceResponseAsync(personGroupId, faceIds, maxNumOfCandidatesReturned, confidenceThreshold);
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"List",
"<",
"IdentifyResult",
">",
">",
">",
"identifyWithServiceResponseAsync",
"(",
"String",
"personGroupId",
",",
"List",
"<",
"UUID",
">",
"faceIds",
",",
"IdentifyOptionalParameter",
"identifyOptionalParameter"... | Identify unknown faces from a person group.
@param personGroupId PersonGroupId of the target person group, created by PersonGroups.Create
@param faceIds Array of query faces faceIds, created by the Face - Detect. Each of the faces are identified independently. The valid number of faceIds is between [1, 10].
@param identifyOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<IdentifyResult> object | [
"Identify",
"unknown",
"faces",
"from",
"a",
"person",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FacesImpl.java#L431-L446 |
roskart/dropwizard-jaxws | dropwizard-jaxws/src/main/java/com/roskart/dropwizard/jaxws/JAXWSBundle.java | JAXWSBundle.publishEndpoint | public Endpoint publishEndpoint(String path, Object service, BasicAuthentication auth,
SessionFactory sessionFactory) {
"""
Publish JAX-WS protected endpoint using Dropwizard BasicAuthentication with Dropwizard Hibernate Bundle
integration. Service is scanned for @UnitOfWork annotations. EndpointBuilder is published relative to the CXF
servlet path.
@param path Relative endpoint path.
@param service Service implementation.
@param auth BasicAuthentication implementation.
@param sessionFactory Hibernate session factory.
@return javax.xml.ws.Endpoint
@deprecated Use the {@link #publishEndpoint(EndpointBuilder)} publishEndpoint} method instead.
"""
checkArgument(service != null, "Service is null");
checkArgument(path != null, "Path is null");
checkArgument((path).trim().length() > 0, "Path is empty");
return this.publishEndpoint(new EndpointBuilder(path, service)
.authentication(auth)
.sessionFactory(sessionFactory)
);
} | java | public Endpoint publishEndpoint(String path, Object service, BasicAuthentication auth,
SessionFactory sessionFactory) {
checkArgument(service != null, "Service is null");
checkArgument(path != null, "Path is null");
checkArgument((path).trim().length() > 0, "Path is empty");
return this.publishEndpoint(new EndpointBuilder(path, service)
.authentication(auth)
.sessionFactory(sessionFactory)
);
} | [
"public",
"Endpoint",
"publishEndpoint",
"(",
"String",
"path",
",",
"Object",
"service",
",",
"BasicAuthentication",
"auth",
",",
"SessionFactory",
"sessionFactory",
")",
"{",
"checkArgument",
"(",
"service",
"!=",
"null",
",",
"\"Service is null\"",
")",
";",
"c... | Publish JAX-WS protected endpoint using Dropwizard BasicAuthentication with Dropwizard Hibernate Bundle
integration. Service is scanned for @UnitOfWork annotations. EndpointBuilder is published relative to the CXF
servlet path.
@param path Relative endpoint path.
@param service Service implementation.
@param auth BasicAuthentication implementation.
@param sessionFactory Hibernate session factory.
@return javax.xml.ws.Endpoint
@deprecated Use the {@link #publishEndpoint(EndpointBuilder)} publishEndpoint} method instead. | [
"Publish",
"JAX",
"-",
"WS",
"protected",
"endpoint",
"using",
"Dropwizard",
"BasicAuthentication",
"with",
"Dropwizard",
"Hibernate",
"Bundle",
"integration",
".",
"Service",
"is",
"scanned",
"for",
"@UnitOfWork",
"annotations",
".",
"EndpointBuilder",
"is",
"publish... | train | https://github.com/roskart/dropwizard-jaxws/blob/972eb63ba9626f3282d4a1d6127dc2b60b28f2bc/dropwizard-jaxws/src/main/java/com/roskart/dropwizard/jaxws/JAXWSBundle.java#L140-L149 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/InvalidationAuditDaemon.java | InvalidationAuditDaemon.filterEntryList | public ArrayList filterEntryList(String cacheName, ArrayList incomingList) {
"""
This ensures all incoming CacheEntrys have not been invalidated.
@param incomingList The unfiltered list of CacheEntrys.
@return The filtered list of CacheEntrys.
"""
InvalidationTableList invalidationTableList = getInvalidationTableList(cacheName);
try {
invalidationTableList.readWriteLock.readLock().lock();
Iterator it = incomingList.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (obj instanceof CacheEntry) {// ignore any "push-pull" String id's in DRS case
CacheEntry cacheEntry = (CacheEntry) obj;
if (internalFilterEntry(cacheName, invalidationTableList, cacheEntry) == null) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "filterEntryList(): Filtered OUT cacheName=" + cacheName + " id=" + cacheEntry.id);
}
it.remove();
}
}
}
return incomingList;
} finally {
invalidationTableList.readWriteLock.readLock().unlock();
}
} | java | public ArrayList filterEntryList(String cacheName, ArrayList incomingList) {
InvalidationTableList invalidationTableList = getInvalidationTableList(cacheName);
try {
invalidationTableList.readWriteLock.readLock().lock();
Iterator it = incomingList.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (obj instanceof CacheEntry) {// ignore any "push-pull" String id's in DRS case
CacheEntry cacheEntry = (CacheEntry) obj;
if (internalFilterEntry(cacheName, invalidationTableList, cacheEntry) == null) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "filterEntryList(): Filtered OUT cacheName=" + cacheName + " id=" + cacheEntry.id);
}
it.remove();
}
}
}
return incomingList;
} finally {
invalidationTableList.readWriteLock.readLock().unlock();
}
} | [
"public",
"ArrayList",
"filterEntryList",
"(",
"String",
"cacheName",
",",
"ArrayList",
"incomingList",
")",
"{",
"InvalidationTableList",
"invalidationTableList",
"=",
"getInvalidationTableList",
"(",
"cacheName",
")",
";",
"try",
"{",
"invalidationTableList",
".",
"re... | This ensures all incoming CacheEntrys have not been invalidated.
@param incomingList The unfiltered list of CacheEntrys.
@return The filtered list of CacheEntrys. | [
"This",
"ensures",
"all",
"incoming",
"CacheEntrys",
"have",
"not",
"been",
"invalidated",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/InvalidationAuditDaemon.java#L170-L192 |
sebastiangraf/treetank | interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/parser/XPathParser.java | XPathParser.parseRelativePathExpr | private void parseRelativePathExpr() throws TTXPathException {
"""
Parses the the rule RelativePathExpr according to the following
production rule:
<p>
[26] RelativePathExpr ::= StepExpr (("/" | "//") StepExpr)* .
</p>
@throws TTXPathException
"""
parseStepExpr();
while (mToken.getType() == TokenType.SLASH || mToken.getType() == TokenType.DESC_STEP) {
if (is(TokenType.DESC_STEP, true)) {
final AbsAxis mAxis = new DescendantAxis(getTransaction(), true);
mPipeBuilder.addStep(mAxis);
} else {
// in this case the slash is just a separator
consume(TokenType.SLASH, true);
}
parseStepExpr();
}
} | java | private void parseRelativePathExpr() throws TTXPathException {
parseStepExpr();
while (mToken.getType() == TokenType.SLASH || mToken.getType() == TokenType.DESC_STEP) {
if (is(TokenType.DESC_STEP, true)) {
final AbsAxis mAxis = new DescendantAxis(getTransaction(), true);
mPipeBuilder.addStep(mAxis);
} else {
// in this case the slash is just a separator
consume(TokenType.SLASH, true);
}
parseStepExpr();
}
} | [
"private",
"void",
"parseRelativePathExpr",
"(",
")",
"throws",
"TTXPathException",
"{",
"parseStepExpr",
"(",
")",
";",
"while",
"(",
"mToken",
".",
"getType",
"(",
")",
"==",
"TokenType",
".",
"SLASH",
"||",
"mToken",
".",
"getType",
"(",
")",
"==",
"Tok... | Parses the the rule RelativePathExpr according to the following
production rule:
<p>
[26] RelativePathExpr ::= StepExpr (("/" | "//") StepExpr)* .
</p>
@throws TTXPathException | [
"Parses",
"the",
"the",
"rule",
"RelativePathExpr",
"according",
"to",
"the",
"following",
"production",
"rule",
":",
"<p",
">",
"[",
"26",
"]",
"RelativePathExpr",
"::",
"=",
"StepExpr",
"((",
"/",
"|",
"//",
")",
"StepExpr",
")",
"*",
".",
"<",
"/",
... | train | https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/parser/XPathParser.java#L722-L739 |
google/closure-compiler | src/com/google/javascript/jscomp/NodeUtil.java | NodeUtil.tryMergeBlock | public static boolean tryMergeBlock(Node block, boolean alwaysMerge) {
"""
Merge a block with its parent block.
@return Whether the block was removed.
"""
checkState(block.isBlock());
Node parent = block.getParent();
boolean canMerge = alwaysMerge || canMergeBlock(block);
// Try to remove the block if its parent is a block/script or if its
// parent is label and it has exactly one child.
if (isStatementBlock(parent) && canMerge) {
Node previous = block;
while (block.hasChildren()) {
Node child = block.removeFirstChild();
parent.addChildAfter(child, previous);
previous = child;
}
parent.removeChild(block);
return true;
} else {
return false;
}
} | java | public static boolean tryMergeBlock(Node block, boolean alwaysMerge) {
checkState(block.isBlock());
Node parent = block.getParent();
boolean canMerge = alwaysMerge || canMergeBlock(block);
// Try to remove the block if its parent is a block/script or if its
// parent is label and it has exactly one child.
if (isStatementBlock(parent) && canMerge) {
Node previous = block;
while (block.hasChildren()) {
Node child = block.removeFirstChild();
parent.addChildAfter(child, previous);
previous = child;
}
parent.removeChild(block);
return true;
} else {
return false;
}
} | [
"public",
"static",
"boolean",
"tryMergeBlock",
"(",
"Node",
"block",
",",
"boolean",
"alwaysMerge",
")",
"{",
"checkState",
"(",
"block",
".",
"isBlock",
"(",
")",
")",
";",
"Node",
"parent",
"=",
"block",
".",
"getParent",
"(",
")",
";",
"boolean",
"ca... | Merge a block with its parent block.
@return Whether the block was removed. | [
"Merge",
"a",
"block",
"with",
"its",
"parent",
"block",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/NodeUtil.java#L2920-L2938 |
cdk/cdk | base/standard/src/main/java/org/openscience/cdk/stereo/StereoTool.java | StereoTool.getHandedness | public static TetrahedralSign getHandedness(IAtom baseAtomA, IAtom baseAtomB, IAtom baseAtomC, IAtom apexAtom) {
"""
Gets the tetrahedral handedness of four atoms - three of which form the
'base' of the tetrahedron, and the other the apex. Note that it assumes
a right-handed coordinate system, and that the points {A,B,C} are in
a counter-clockwise order in the plane they share.
@param baseAtomA the first atom in the base of the tetrahedron
@param baseAtomB the second atom in the base of the tetrahedron
@param baseAtomC the third atom in the base of the tetrahedron
@param apexAtom the atom in the point of the tetrahedron
@return the sign of the tetrahedron
"""
Point3d pointA = baseAtomA.getPoint3d();
Point3d pointB = baseAtomB.getPoint3d();
Point3d pointC = baseAtomC.getPoint3d();
Point3d pointD = apexAtom.getPoint3d();
return StereoTool.getHandedness(pointA, pointB, pointC, pointD);
} | java | public static TetrahedralSign getHandedness(IAtom baseAtomA, IAtom baseAtomB, IAtom baseAtomC, IAtom apexAtom) {
Point3d pointA = baseAtomA.getPoint3d();
Point3d pointB = baseAtomB.getPoint3d();
Point3d pointC = baseAtomC.getPoint3d();
Point3d pointD = apexAtom.getPoint3d();
return StereoTool.getHandedness(pointA, pointB, pointC, pointD);
} | [
"public",
"static",
"TetrahedralSign",
"getHandedness",
"(",
"IAtom",
"baseAtomA",
",",
"IAtom",
"baseAtomB",
",",
"IAtom",
"baseAtomC",
",",
"IAtom",
"apexAtom",
")",
"{",
"Point3d",
"pointA",
"=",
"baseAtomA",
".",
"getPoint3d",
"(",
")",
";",
"Point3d",
"po... | Gets the tetrahedral handedness of four atoms - three of which form the
'base' of the tetrahedron, and the other the apex. Note that it assumes
a right-handed coordinate system, and that the points {A,B,C} are in
a counter-clockwise order in the plane they share.
@param baseAtomA the first atom in the base of the tetrahedron
@param baseAtomB the second atom in the base of the tetrahedron
@param baseAtomC the third atom in the base of the tetrahedron
@param apexAtom the atom in the point of the tetrahedron
@return the sign of the tetrahedron | [
"Gets",
"the",
"tetrahedral",
"handedness",
"of",
"four",
"atoms",
"-",
"three",
"of",
"which",
"form",
"the",
"base",
"of",
"the",
"tetrahedron",
"and",
"the",
"other",
"the",
"apex",
".",
"Note",
"that",
"it",
"assumes",
"a",
"right",
"-",
"handed",
"c... | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/standard/src/main/java/org/openscience/cdk/stereo/StereoTool.java#L305-L311 |
svenkubiak/mangooio | mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java | Validator.expectIpv6 | public void expectIpv6(String name, String message) {
"""
Validates a field to be a valid IPv6 address
@param name The field to check
@param message A custom error message instead of the default one
"""
String value = Optional.ofNullable(get(name)).orElse("");
if (!InetAddressValidator.getInstance().isValidInet6Address(value)) {
addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.IPV6_KEY.name(), name)));
}
} | java | public void expectIpv6(String name, String message) {
String value = Optional.ofNullable(get(name)).orElse("");
if (!InetAddressValidator.getInstance().isValidInet6Address(value)) {
addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.IPV6_KEY.name(), name)));
}
} | [
"public",
"void",
"expectIpv6",
"(",
"String",
"name",
",",
"String",
"message",
")",
"{",
"String",
"value",
"=",
"Optional",
".",
"ofNullable",
"(",
"get",
"(",
"name",
")",
")",
".",
"orElse",
"(",
"\"\"",
")",
";",
"if",
"(",
"!",
"InetAddressValid... | Validates a field to be a valid IPv6 address
@param name The field to check
@param message A custom error message instead of the default one | [
"Validates",
"a",
"field",
"to",
"be",
"a",
"valid",
"IPv6",
"address"
] | train | https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java#L326-L332 |
dustin/java-memcached-client | src/main/java/net/spy/memcached/MemcachedClient.java | MemcachedClient.asyncGets | @Override
public OperationFuture<CASValue<Object>> asyncGets(final String key) {
"""
Gets (with CAS support) the given key asynchronously and decode using the
default transcoder.
@param key the key to fetch
@return a future that will hold the return value of the fetch
@throws IllegalStateException in the rare circumstance where queue is too
full to accept any more requests
"""
return asyncGets(key, transcoder);
} | java | @Override
public OperationFuture<CASValue<Object>> asyncGets(final String key) {
return asyncGets(key, transcoder);
} | [
"@",
"Override",
"public",
"OperationFuture",
"<",
"CASValue",
"<",
"Object",
">",
">",
"asyncGets",
"(",
"final",
"String",
"key",
")",
"{",
"return",
"asyncGets",
"(",
"key",
",",
"transcoder",
")",
";",
"}"
] | Gets (with CAS support) the given key asynchronously and decode using the
default transcoder.
@param key the key to fetch
@return a future that will hold the return value of the fetch
@throws IllegalStateException in the rare circumstance where queue is too
full to accept any more requests | [
"Gets",
"(",
"with",
"CAS",
"support",
")",
"the",
"given",
"key",
"asynchronously",
"and",
"decode",
"using",
"the",
"default",
"transcoder",
"."
] | train | https://github.com/dustin/java-memcached-client/blob/c232307ad8e0c7ccc926e495dd7d5aad2d713318/src/main/java/net/spy/memcached/MemcachedClient.java#L1116-L1119 |
algolia/instantsearch-android | ui/src/main/java/com/algolia/instantsearch/ui/databinding/RenderingHelper.java | RenderingHelper.shouldSnippet | public boolean shouldSnippet(@NonNull View view, @NonNull String attribute) {
"""
Checks if an attribute should be snippetted in a view.
@param view the view using this attribute.
@param attribute the attribute's name.
@return {@code true} if the attribute was marked for snippeting.
"""
return snippettedAttributes.contains(new Pair<>(view.getId(), attribute));
} | java | public boolean shouldSnippet(@NonNull View view, @NonNull String attribute) {
return snippettedAttributes.contains(new Pair<>(view.getId(), attribute));
} | [
"public",
"boolean",
"shouldSnippet",
"(",
"@",
"NonNull",
"View",
"view",
",",
"@",
"NonNull",
"String",
"attribute",
")",
"{",
"return",
"snippettedAttributes",
".",
"contains",
"(",
"new",
"Pair",
"<>",
"(",
"view",
".",
"getId",
"(",
")",
",",
"attribu... | Checks if an attribute should be snippetted in a view.
@param view the view using this attribute.
@param attribute the attribute's name.
@return {@code true} if the attribute was marked for snippeting. | [
"Checks",
"if",
"an",
"attribute",
"should",
"be",
"snippetted",
"in",
"a",
"view",
"."
] | train | https://github.com/algolia/instantsearch-android/blob/12092ec30140df9ffc2bf916339b433372034616/ui/src/main/java/com/algolia/instantsearch/ui/databinding/RenderingHelper.java#L97-L99 |
prestodb/presto | presto-hive/src/main/java/com/facebook/presto/hive/HiveColumnHandle.java | HiveColumnHandle.bucketColumnHandle | public static HiveColumnHandle bucketColumnHandle() {
"""
The column indicating the bucket id.
When table bucketing differs from partition bucketing, this column indicates
what bucket the row will fall in under the table bucketing scheme.
"""
return new HiveColumnHandle(BUCKET_COLUMN_NAME, BUCKET_HIVE_TYPE, BUCKET_TYPE_SIGNATURE, BUCKET_COLUMN_INDEX, SYNTHESIZED, Optional.empty());
} | java | public static HiveColumnHandle bucketColumnHandle()
{
return new HiveColumnHandle(BUCKET_COLUMN_NAME, BUCKET_HIVE_TYPE, BUCKET_TYPE_SIGNATURE, BUCKET_COLUMN_INDEX, SYNTHESIZED, Optional.empty());
} | [
"public",
"static",
"HiveColumnHandle",
"bucketColumnHandle",
"(",
")",
"{",
"return",
"new",
"HiveColumnHandle",
"(",
"BUCKET_COLUMN_NAME",
",",
"BUCKET_HIVE_TYPE",
",",
"BUCKET_TYPE_SIGNATURE",
",",
"BUCKET_COLUMN_INDEX",
",",
"SYNTHESIZED",
",",
"Optional",
".",
"emp... | The column indicating the bucket id.
When table bucketing differs from partition bucketing, this column indicates
what bucket the row will fall in under the table bucketing scheme. | [
"The",
"column",
"indicating",
"the",
"bucket",
"id",
".",
"When",
"table",
"bucketing",
"differs",
"from",
"partition",
"bucketing",
"this",
"column",
"indicates",
"what",
"bucket",
"the",
"row",
"will",
"fall",
"in",
"under",
"the",
"table",
"bucketing",
"sc... | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-hive/src/main/java/com/facebook/presto/hive/HiveColumnHandle.java#L183-L186 |
jbehave/jbehave-core | jbehave-core/src/main/java/org/jbehave/core/io/StoryFinder.java | StoryFinder.findPaths | public List<String> findPaths(String searchIn, String[] includes, String[] excludes) {
"""
Finds paths from a source path, allowing for include/exclude patterns.
Paths found are normalised by {@link StoryFinder#normalise(List<String>)}
@param searchIn the source path to search in
@param includes the Array of include patterns, or <code>null</code> if
none
@param excludes the Array of exclude patterns, or <code>null</code> if
none
@return A List of paths found
"""
return findPaths(searchIn, asList(includes), asList(excludes));
} | java | public List<String> findPaths(String searchIn, String[] includes, String[] excludes) {
return findPaths(searchIn, asList(includes), asList(excludes));
} | [
"public",
"List",
"<",
"String",
">",
"findPaths",
"(",
"String",
"searchIn",
",",
"String",
"[",
"]",
"includes",
",",
"String",
"[",
"]",
"excludes",
")",
"{",
"return",
"findPaths",
"(",
"searchIn",
",",
"asList",
"(",
"includes",
")",
",",
"asList",
... | Finds paths from a source path, allowing for include/exclude patterns.
Paths found are normalised by {@link StoryFinder#normalise(List<String>)}
@param searchIn the source path to search in
@param includes the Array of include patterns, or <code>null</code> if
none
@param excludes the Array of exclude patterns, or <code>null</code> if
none
@return A List of paths found | [
"Finds",
"paths",
"from",
"a",
"source",
"path",
"allowing",
"for",
"include",
"/",
"exclude",
"patterns",
".",
"Paths",
"found",
"are",
"normalised",
"by",
"{",
"@link",
"StoryFinder#normalise",
"(",
"List<String",
">",
")",
"}"
] | train | https://github.com/jbehave/jbehave-core/blob/bdd6a6199528df3c35087e72d4644870655b23e6/jbehave-core/src/main/java/org/jbehave/core/io/StoryFinder.java#L119-L121 |
apiman/apiman | gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/AbstractClientFactory.java | AbstractClientFactory.initializeClient | protected void initializeClient(JestClient client, String indexName, String defaultIndexName) {
"""
Called to initialize the storage.
@param client the jest client
@param indexName the name of the ES index to initialize
@param defaultIndexName the default ES index - used to determine which -settings.json file to use
"""
try {
client.execute(new Health.Builder().build());
Action<JestResult> action = new IndicesExists.Builder(indexName).build();
// There was occasions where a race occurred here when multiple threads try to
// create the index simultaneously. This caused a non-fatal, but annoying, exception.
synchronized(AbstractClientFactory.class) {
JestResult result = client.execute(action);
if (!result.isSucceeded()) {
createIndex(client, indexName, defaultIndexName + "-settings.json"); //$NON-NLS-1$
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java | protected void initializeClient(JestClient client, String indexName, String defaultIndexName) {
try {
client.execute(new Health.Builder().build());
Action<JestResult> action = new IndicesExists.Builder(indexName).build();
// There was occasions where a race occurred here when multiple threads try to
// create the index simultaneously. This caused a non-fatal, but annoying, exception.
synchronized(AbstractClientFactory.class) {
JestResult result = client.execute(action);
if (!result.isSucceeded()) {
createIndex(client, indexName, defaultIndexName + "-settings.json"); //$NON-NLS-1$
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
} | [
"protected",
"void",
"initializeClient",
"(",
"JestClient",
"client",
",",
"String",
"indexName",
",",
"String",
"defaultIndexName",
")",
"{",
"try",
"{",
"client",
".",
"execute",
"(",
"new",
"Health",
".",
"Builder",
"(",
")",
".",
"build",
"(",
")",
")"... | Called to initialize the storage.
@param client the jest client
@param indexName the name of the ES index to initialize
@param defaultIndexName the default ES index - used to determine which -settings.json file to use | [
"Called",
"to",
"initialize",
"the",
"storage",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/AbstractClientFactory.java#L63-L78 |
BorderTech/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WCheckBoxSelectExample.java | WCheckBoxSelectExample.addDisabledExamples | private void addDisabledExamples() {
"""
Examples of disabled state. You should use {@link WSubordinateControl} to set and manage the disabled state
unless there is no facility for the user to enable a control.
"""
add(new WHeading(HeadingLevel.H2, "Disabled WCheckBoxSelect examples"));
WFieldLayout layout = new WFieldLayout();
add(layout);
WCheckBoxSelect select = new WCheckBoxSelect("australian_state");
select.setDisabled(true);
layout.addField("Disabled with no default selection", select);
add(new WHeading(HeadingLevel.H3, "Disabled with no selection and no frame"));
select = new WCheckBoxSelect("australian_state");
select.setDisabled(true);
select.setFrameless(true);
layout.addField("Disabled with no selection and no frame", select);
select = new SelectWithSingleSelected("australian_state");
select.setDisabled(true);
layout.addField("Disabled with one selection", select);
select = new SelectWithManySelected("australian_state");
select.setDisabled(true);
select.setButtonLayout(WCheckBoxSelect.LAYOUT_COLUMNS);
select.setButtonColumns(3);
layout.addField("Disabled with many selections and COLUMN layout", select);
} | java | private void addDisabledExamples() {
add(new WHeading(HeadingLevel.H2, "Disabled WCheckBoxSelect examples"));
WFieldLayout layout = new WFieldLayout();
add(layout);
WCheckBoxSelect select = new WCheckBoxSelect("australian_state");
select.setDisabled(true);
layout.addField("Disabled with no default selection", select);
add(new WHeading(HeadingLevel.H3, "Disabled with no selection and no frame"));
select = new WCheckBoxSelect("australian_state");
select.setDisabled(true);
select.setFrameless(true);
layout.addField("Disabled with no selection and no frame", select);
select = new SelectWithSingleSelected("australian_state");
select.setDisabled(true);
layout.addField("Disabled with one selection", select);
select = new SelectWithManySelected("australian_state");
select.setDisabled(true);
select.setButtonLayout(WCheckBoxSelect.LAYOUT_COLUMNS);
select.setButtonColumns(3);
layout.addField("Disabled with many selections and COLUMN layout", select);
} | [
"private",
"void",
"addDisabledExamples",
"(",
")",
"{",
"add",
"(",
"new",
"WHeading",
"(",
"HeadingLevel",
".",
"H2",
",",
"\"Disabled WCheckBoxSelect examples\"",
")",
")",
";",
"WFieldLayout",
"layout",
"=",
"new",
"WFieldLayout",
"(",
")",
";",
"add",
"("... | Examples of disabled state. You should use {@link WSubordinateControl} to set and manage the disabled state
unless there is no facility for the user to enable a control. | [
"Examples",
"of",
"disabled",
"state",
".",
"You",
"should",
"use",
"{"
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WCheckBoxSelectExample.java#L377-L400 |
hdecarne/java-default | src/main/java/de/carne/io/Closeables.java | Closeables.safeClose | public static void safeClose(Throwable exception, @Nullable Object object) {
"""
Close potential {@linkplain Closeable}.
<p>
An {@linkplain IOException} caused by {@linkplain Closeable#close()} is suppressed and added to the given outer
exception.
@param exception the currently handled outer exception.
@param object the object to check and close.
"""
if (object instanceof Closeable) {
try {
((Closeable) object).close();
} catch (IOException e) {
exception.addSuppressed(e);
}
}
} | java | public static void safeClose(Throwable exception, @Nullable Object object) {
if (object instanceof Closeable) {
try {
((Closeable) object).close();
} catch (IOException e) {
exception.addSuppressed(e);
}
}
} | [
"public",
"static",
"void",
"safeClose",
"(",
"Throwable",
"exception",
",",
"@",
"Nullable",
"Object",
"object",
")",
"{",
"if",
"(",
"object",
"instanceof",
"Closeable",
")",
"{",
"try",
"{",
"(",
"(",
"Closeable",
")",
"object",
")",
".",
"close",
"("... | Close potential {@linkplain Closeable}.
<p>
An {@linkplain IOException} caused by {@linkplain Closeable#close()} is suppressed and added to the given outer
exception.
@param exception the currently handled outer exception.
@param object the object to check and close. | [
"Close",
"potential",
"{",
"@linkplain",
"Closeable",
"}",
".",
"<p",
">",
"An",
"{",
"@linkplain",
"IOException",
"}",
"caused",
"by",
"{",
"@linkplain",
"Closeable#close",
"()",
"}",
"is",
"suppressed",
"and",
"added",
"to",
"the",
"given",
"outer",
"excep... | train | https://github.com/hdecarne/java-default/blob/ca16f6fdb0436e90e9e2df3106055e320bb3c9e3/src/main/java/de/carne/io/Closeables.java#L107-L115 |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/threading/Deadline.java | Deadline.getTimeoutLeft | public Timeout getTimeoutLeft() {
"""
Determines the amount of time leftuntil the deadline and returns it as a timeout
@return a timeout representing the amount of time remaining until this deadline expires
"""
final long left = getTimeLeft();
if (left != 0)
return new Timeout(left, TimeUnit.MILLISECONDS);
else
return Timeout.ZERO;
} | java | public Timeout getTimeoutLeft()
{
final long left = getTimeLeft();
if (left != 0)
return new Timeout(left, TimeUnit.MILLISECONDS);
else
return Timeout.ZERO;
} | [
"public",
"Timeout",
"getTimeoutLeft",
"(",
")",
"{",
"final",
"long",
"left",
"=",
"getTimeLeft",
"(",
")",
";",
"if",
"(",
"left",
"!=",
"0",
")",
"return",
"new",
"Timeout",
"(",
"left",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
";",
"else",
"retur... | Determines the amount of time leftuntil the deadline and returns it as a timeout
@return a timeout representing the amount of time remaining until this deadline expires | [
"Determines",
"the",
"amount",
"of",
"time",
"leftuntil",
"the",
"deadline",
"and",
"returns",
"it",
"as",
"a",
"timeout"
] | train | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/threading/Deadline.java#L120-L128 |
nguillaumin/slick2d-maven | slick2d-core/src/main/java/org/newdawn/slick/openal/SoundStore.java | SoundStore.getMOD | public Audio getMOD(String ref, InputStream in) throws IOException {
"""
Get a MOD sound (mod/xm etc)
@param ref The stream to the MOD to load
@param in The stream to the MOD to load
@return The sound for play back
@throws IOException Indicates a failure to read the data
"""
if (!soundWorks) {
return new NullAudio();
}
if (!inited) {
throw new RuntimeException("Can't load sounds until SoundStore is init(). Use the container init() method.");
}
if (deferred) {
return new DeferredSound(ref, in, DeferredSound.MOD);
}
return new MODSound(this, in);
} | java | public Audio getMOD(String ref, InputStream in) throws IOException {
if (!soundWorks) {
return new NullAudio();
}
if (!inited) {
throw new RuntimeException("Can't load sounds until SoundStore is init(). Use the container init() method.");
}
if (deferred) {
return new DeferredSound(ref, in, DeferredSound.MOD);
}
return new MODSound(this, in);
} | [
"public",
"Audio",
"getMOD",
"(",
"String",
"ref",
",",
"InputStream",
"in",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"soundWorks",
")",
"{",
"return",
"new",
"NullAudio",
"(",
")",
";",
"}",
"if",
"(",
"!",
"inited",
")",
"{",
"throw",
"ne... | Get a MOD sound (mod/xm etc)
@param ref The stream to the MOD to load
@param in The stream to the MOD to load
@return The sound for play back
@throws IOException Indicates a failure to read the data | [
"Get",
"a",
"MOD",
"sound",
"(",
"mod",
"/",
"xm",
"etc",
")"
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/openal/SoundStore.java#L574-L586 |
structurizr/java | structurizr-core/src/com/structurizr/documentation/ViewpointsAndPerspectivesDocumentationTemplate.java | ViewpointsAndPerspectivesDocumentationTemplate.addArchitecturalForcesSection | public Section addArchitecturalForcesSection(SoftwareSystem softwareSystem, File... files) throws IOException {
"""
Adds an "Architectural Forces" section relating to a {@link SoftwareSystem} from one or more files.
@param softwareSystem the {@link SoftwareSystem} the documentation content relates to
@param files one or more File objects that point to the documentation content
@return a documentation {@link Section}
@throws IOException if there is an error reading the files
"""
return addSection(softwareSystem, "Architectural Forces", files);
} | java | public Section addArchitecturalForcesSection(SoftwareSystem softwareSystem, File... files) throws IOException {
return addSection(softwareSystem, "Architectural Forces", files);
} | [
"public",
"Section",
"addArchitecturalForcesSection",
"(",
"SoftwareSystem",
"softwareSystem",
",",
"File",
"...",
"files",
")",
"throws",
"IOException",
"{",
"return",
"addSection",
"(",
"softwareSystem",
",",
"\"Architectural Forces\"",
",",
"files",
")",
";",
"}"
] | Adds an "Architectural Forces" section relating to a {@link SoftwareSystem} from one or more files.
@param softwareSystem the {@link SoftwareSystem} the documentation content relates to
@param files one or more File objects that point to the documentation content
@return a documentation {@link Section}
@throws IOException if there is an error reading the files | [
"Adds",
"an",
"Architectural",
"Forces",
"section",
"relating",
"to",
"a",
"{",
"@link",
"SoftwareSystem",
"}",
"from",
"one",
"or",
"more",
"files",
"."
] | train | https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/documentation/ViewpointsAndPerspectivesDocumentationTemplate.java#L116-L118 |
facebookarchive/hadoop-20 | src/contrib/corona/src/java/org/apache/hadoop/corona/Utilities.java | Utilities.removeReference | public static Object removeReference(List l, Object o) {
"""
Remove the object o from the list l. Different from l.remove(o)
because this method only removes it if it is the same object
@param l the list to remove from
@param o the object to remove
@return removed object if it was found in the list, null otherwise
"""
Iterator iter = l.iterator();
while (iter.hasNext()) {
Object no = iter.next();
if (no == o) {
iter.remove();
return o;
}
}
return null;
} | java | public static Object removeReference(List l, Object o) {
Iterator iter = l.iterator();
while (iter.hasNext()) {
Object no = iter.next();
if (no == o) {
iter.remove();
return o;
}
}
return null;
} | [
"public",
"static",
"Object",
"removeReference",
"(",
"List",
"l",
",",
"Object",
"o",
")",
"{",
"Iterator",
"iter",
"=",
"l",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"iter",
".",
"hasNext",
"(",
")",
")",
"{",
"Object",
"no",
"=",
"iter",
".... | Remove the object o from the list l. Different from l.remove(o)
because this method only removes it if it is the same object
@param l the list to remove from
@param o the object to remove
@return removed object if it was found in the list, null otherwise | [
"Remove",
"the",
"object",
"o",
"from",
"the",
"list",
"l",
".",
"Different",
"from",
"l",
".",
"remove",
"(",
"o",
")",
"because",
"this",
"method",
"only",
"removes",
"it",
"if",
"it",
"is",
"the",
"same",
"object"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/Utilities.java#L112-L122 |
apache/groovy | subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java | NioGroovyMethods.newPrintWriter | public static PrintWriter newPrintWriter(Path self, String charset) throws IOException {
"""
Create a new PrintWriter for this file, using specified
charset.
@param self a Path
@param charset the charset
@return a PrintWriter
@throws java.io.IOException if an IOException occurs.
@since 2.3.0
"""
return new GroovyPrintWriter(newWriter(self, charset));
} | java | public static PrintWriter newPrintWriter(Path self, String charset) throws IOException {
return new GroovyPrintWriter(newWriter(self, charset));
} | [
"public",
"static",
"PrintWriter",
"newPrintWriter",
"(",
"Path",
"self",
",",
"String",
"charset",
")",
"throws",
"IOException",
"{",
"return",
"new",
"GroovyPrintWriter",
"(",
"newWriter",
"(",
"self",
",",
"charset",
")",
")",
";",
"}"
] | Create a new PrintWriter for this file, using specified
charset.
@param self a Path
@param charset the charset
@return a PrintWriter
@throws java.io.IOException if an IOException occurs.
@since 2.3.0 | [
"Create",
"a",
"new",
"PrintWriter",
"for",
"this",
"file",
"using",
"specified",
"charset",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java#L1747-L1749 |
hmsonline/cassandra-triggers | src/main/java/com/hmsonline/cassandra/triggers/CassandraServerTriggerAspect.java | CassandraServerTriggerAspect.logErrorFromThrownException | @AfterThrowing(pointcut = "execution(* org.apache.cassandra.thrift.CassandraServer.doInsert(..))", throwing = "throwable")
public void logErrorFromThrownException(final JoinPoint joinPoint, final Throwable throwable) {
"""
Logs an error message for unhandled exception thrown from the target method.
@param joinPoint - the joint point cut that contains information about the target
@param throwable - the cause of the exception from the target method invocation
"""
final String className = joinPoint.getTarget().getClass().getName();
final String methodName = joinPoint.getSignature().getName();
logger.error("Could not write to cassandra! Method: " + className + "."+ methodName + "()", throwable);
} | java | @AfterThrowing(pointcut = "execution(* org.apache.cassandra.thrift.CassandraServer.doInsert(..))", throwing = "throwable")
public void logErrorFromThrownException(final JoinPoint joinPoint, final Throwable throwable) {
final String className = joinPoint.getTarget().getClass().getName();
final String methodName = joinPoint.getSignature().getName();
logger.error("Could not write to cassandra! Method: " + className + "."+ methodName + "()", throwable);
} | [
"@",
"AfterThrowing",
"(",
"pointcut",
"=",
"\"execution(* org.apache.cassandra.thrift.CassandraServer.doInsert(..))\"",
",",
"throwing",
"=",
"\"throwable\"",
")",
"public",
"void",
"logErrorFromThrownException",
"(",
"final",
"JoinPoint",
"joinPoint",
",",
"final",
"Throwab... | Logs an error message for unhandled exception thrown from the target method.
@param joinPoint - the joint point cut that contains information about the target
@param throwable - the cause of the exception from the target method invocation | [
"Logs",
"an",
"error",
"message",
"for",
"unhandled",
"exception",
"thrown",
"from",
"the",
"target",
"method",
"."
] | train | https://github.com/hmsonline/cassandra-triggers/blob/022862c7e4bbdd3423b5926f360ea9bf8f81c8b7/src/main/java/com/hmsonline/cassandra/triggers/CassandraServerTriggerAspect.java#L56-L62 |
spockframework/spock | spock-core/src/main/java/org/spockframework/runtime/SpockRuntime.java | SpockRuntime.verifyMethodCondition | public static void verifyMethodCondition(@Nullable ErrorCollector errorCollector, @Nullable ValueRecorder recorder, @Nullable String text, int line, int column,
@Nullable Object message, Object target, String method, Object[] args, boolean safe, boolean explicit, int lastVariableNum) {
"""
method calls with spread-dot operator are not rewritten, hence this method doesn't have to care about spread-dot
"""
MatcherCondition matcherCondition = MatcherCondition.parse(target, method, args, safe);
if (matcherCondition != null) {
matcherCondition.verify(errorCollector, getValues(recorder), text, line, column, messageToString(message));
return;
}
if (recorder != null) {
recorder.startRecordingValue(lastVariableNum);
}
Object result = safe ? GroovyRuntimeUtil.invokeMethodNullSafe(target, method, args) :
GroovyRuntimeUtil.invokeMethod(target, method, args);
if (!explicit && result == null && isVoidMethod(target, method, args)) return;
if (!GroovyRuntimeUtil.isTruthy(result)) {
List<Object> values = getValues(recorder);
if (values != null) CollectionUtil.setLastElement(values, result);
final ConditionNotSatisfiedError conditionNotSatisfiedError = new ConditionNotSatisfiedError(
new Condition(values, text, TextPosition.create(line, column), messageToString(message), null, null));
errorCollector.collectOrThrow(conditionNotSatisfiedError);
}
} | java | public static void verifyMethodCondition(@Nullable ErrorCollector errorCollector, @Nullable ValueRecorder recorder, @Nullable String text, int line, int column,
@Nullable Object message, Object target, String method, Object[] args, boolean safe, boolean explicit, int lastVariableNum) {
MatcherCondition matcherCondition = MatcherCondition.parse(target, method, args, safe);
if (matcherCondition != null) {
matcherCondition.verify(errorCollector, getValues(recorder), text, line, column, messageToString(message));
return;
}
if (recorder != null) {
recorder.startRecordingValue(lastVariableNum);
}
Object result = safe ? GroovyRuntimeUtil.invokeMethodNullSafe(target, method, args) :
GroovyRuntimeUtil.invokeMethod(target, method, args);
if (!explicit && result == null && isVoidMethod(target, method, args)) return;
if (!GroovyRuntimeUtil.isTruthy(result)) {
List<Object> values = getValues(recorder);
if (values != null) CollectionUtil.setLastElement(values, result);
final ConditionNotSatisfiedError conditionNotSatisfiedError = new ConditionNotSatisfiedError(
new Condition(values, text, TextPosition.create(line, column), messageToString(message), null, null));
errorCollector.collectOrThrow(conditionNotSatisfiedError);
}
} | [
"public",
"static",
"void",
"verifyMethodCondition",
"(",
"@",
"Nullable",
"ErrorCollector",
"errorCollector",
",",
"@",
"Nullable",
"ValueRecorder",
"recorder",
",",
"@",
"Nullable",
"String",
"text",
",",
"int",
"line",
",",
"int",
"column",
",",
"@",
"Nullabl... | method calls with spread-dot operator are not rewritten, hence this method doesn't have to care about spread-dot | [
"method",
"calls",
"with",
"spread",
"-",
"dot",
"operator",
"are",
"not",
"rewritten",
"hence",
"this",
"method",
"doesn",
"t",
"have",
"to",
"care",
"about",
"spread",
"-",
"dot"
] | train | https://github.com/spockframework/spock/blob/d751a0abd8d5a2ec5338aa10bc2d19371b3b3ad9/spock-core/src/main/java/org/spockframework/runtime/SpockRuntime.java#L96-L119 |
olivergondza/dumpling | core/src/main/java/com/github/olivergondza/dumpling/model/StackTrace.java | StackTrace.nativeElement | public static StackTraceElement nativeElement(String declaringClass, String methodName, String fileName) {
"""
Get {@link StackTraceElement} for native method.
Some native method {@link StackTraceElement}s have filename, even though it is not shown.
"""
return new StackTraceElement(declaringClass, methodName, fileName, -2);
} | java | public static StackTraceElement nativeElement(String declaringClass, String methodName, String fileName) {
return new StackTraceElement(declaringClass, methodName, fileName, -2);
} | [
"public",
"static",
"StackTraceElement",
"nativeElement",
"(",
"String",
"declaringClass",
",",
"String",
"methodName",
",",
"String",
"fileName",
")",
"{",
"return",
"new",
"StackTraceElement",
"(",
"declaringClass",
",",
"methodName",
",",
"fileName",
",",
"-",
... | Get {@link StackTraceElement} for native method.
Some native method {@link StackTraceElement}s have filename, even though it is not shown. | [
"Get",
"{",
"@link",
"StackTraceElement",
"}",
"for",
"native",
"method",
"."
] | train | https://github.com/olivergondza/dumpling/blob/ac698735fcc7c023db0c1637cc1f522cb3576c7f/core/src/main/java/com/github/olivergondza/dumpling/model/StackTrace.java#L71-L73 |
alipay/sofa-rpc | core/api/src/main/java/com/alipay/sofa/rpc/common/utils/NetUtils.java | NetUtils.canTelnet | public static boolean canTelnet(String ip, int port, int timeout) {
"""
是否可以telnet
@param ip 远程地址
@param port 远程端口
@param timeout 连接超时
@return 是否可连接
"""
Socket socket = null;
try {
socket = new Socket();
socket.connect(new InetSocketAddress(ip, port), timeout);
return socket.isConnected() && !socket.isClosed();
} catch (Exception e) {
return false;
} finally {
IOUtils.closeQuietly(socket);
}
} | java | public static boolean canTelnet(String ip, int port, int timeout) {
Socket socket = null;
try {
socket = new Socket();
socket.connect(new InetSocketAddress(ip, port), timeout);
return socket.isConnected() && !socket.isClosed();
} catch (Exception e) {
return false;
} finally {
IOUtils.closeQuietly(socket);
}
} | [
"public",
"static",
"boolean",
"canTelnet",
"(",
"String",
"ip",
",",
"int",
"port",
",",
"int",
"timeout",
")",
"{",
"Socket",
"socket",
"=",
"null",
";",
"try",
"{",
"socket",
"=",
"new",
"Socket",
"(",
")",
";",
"socket",
".",
"connect",
"(",
"new... | 是否可以telnet
@param ip 远程地址
@param port 远程端口
@param timeout 连接超时
@return 是否可连接 | [
"是否可以telnet"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/common/utils/NetUtils.java#L486-L497 |
lestard/advanced-bindings | src/main/java/eu/lestard/advanced_bindings/api/CollectionBindings.java | CollectionBindings.join | public static StringBinding join(final ObservableList<?> items, final ObservableValue<String> delimiter) {
"""
Creates a string binding that constructs a sequence of characters separated by a delimiter.
@param items the observable list of items.
@param delimiter the sequence of characters to be used between each element.
@return a string binding.
"""
return Bindings.createStringBinding(() -> items.stream().map(String::valueOf).collect(Collectors.joining(delimiter.getValue())), items, delimiter);
} | java | public static StringBinding join(final ObservableList<?> items, final ObservableValue<String> delimiter) {
return Bindings.createStringBinding(() -> items.stream().map(String::valueOf).collect(Collectors.joining(delimiter.getValue())), items, delimiter);
} | [
"public",
"static",
"StringBinding",
"join",
"(",
"final",
"ObservableList",
"<",
"?",
">",
"items",
",",
"final",
"ObservableValue",
"<",
"String",
">",
"delimiter",
")",
"{",
"return",
"Bindings",
".",
"createStringBinding",
"(",
"(",
")",
"->",
"items",
"... | Creates a string binding that constructs a sequence of characters separated by a delimiter.
@param items the observable list of items.
@param delimiter the sequence of characters to be used between each element.
@return a string binding. | [
"Creates",
"a",
"string",
"binding",
"that",
"constructs",
"a",
"sequence",
"of",
"characters",
"separated",
"by",
"a",
"delimiter",
"."
] | train | https://github.com/lestard/advanced-bindings/blob/054a5dde261c29f862b971765fa3da3704a13ab4/src/main/java/eu/lestard/advanced_bindings/api/CollectionBindings.java#L136-L138 |
kenyee/android-ddp-client | src/com/keysolutions/ddpclient/android/MeteorAuthCommands.java | MeteorAuthCommands.forgotPassword | public void forgotPassword(String email) {
"""
Sends password reset mail to specified email address
@param email email address of user
"""
if (email == null) {
return;
}
Object[] methodArgs = new Object[1];
Map<String,Object> options = new HashMap<>();
methodArgs[0] = options;
options.put("email", email);
getDDP().call("forgotPassword", methodArgs, new DDPListener() {
@Override
public void onResult(Map<String, Object> jsonFields) {
handleLoginResult(jsonFields);
}
});
} | java | public void forgotPassword(String email)
{
if (email == null) {
return;
}
Object[] methodArgs = new Object[1];
Map<String,Object> options = new HashMap<>();
methodArgs[0] = options;
options.put("email", email);
getDDP().call("forgotPassword", methodArgs, new DDPListener() {
@Override
public void onResult(Map<String, Object> jsonFields) {
handleLoginResult(jsonFields);
}
});
} | [
"public",
"void",
"forgotPassword",
"(",
"String",
"email",
")",
"{",
"if",
"(",
"email",
"==",
"null",
")",
"{",
"return",
";",
"}",
"Object",
"[",
"]",
"methodArgs",
"=",
"new",
"Object",
"[",
"1",
"]",
";",
"Map",
"<",
"String",
",",
"Object",
"... | Sends password reset mail to specified email address
@param email email address of user | [
"Sends",
"password",
"reset",
"mail",
"to",
"specified",
"email",
"address"
] | train | https://github.com/kenyee/android-ddp-client/blob/6ab416e415570a03f96c383497144dd742de3f08/src/com/keysolutions/ddpclient/android/MeteorAuthCommands.java#L108-L123 |
lucee/Lucee | loader/src/main/java/lucee/loader/engine/CFMLEngineFactorySupport.java | CFMLEngineFactorySupport.toVersion | public static Version toVersion(String version, final Version defaultValue) {
"""
cast a lucee string version to a int version
@param version
@return int version
"""
// remove extension if there is any
final int rIndex = version.lastIndexOf(".lco");
if (rIndex != -1) version = version.substring(0, rIndex);
try {
return Version.parseVersion(version);
}
catch (final IllegalArgumentException iae) {
return defaultValue;
}
} | java | public static Version toVersion(String version, final Version defaultValue) {
// remove extension if there is any
final int rIndex = version.lastIndexOf(".lco");
if (rIndex != -1) version = version.substring(0, rIndex);
try {
return Version.parseVersion(version);
}
catch (final IllegalArgumentException iae) {
return defaultValue;
}
} | [
"public",
"static",
"Version",
"toVersion",
"(",
"String",
"version",
",",
"final",
"Version",
"defaultValue",
")",
"{",
"// remove extension if there is any",
"final",
"int",
"rIndex",
"=",
"version",
".",
"lastIndexOf",
"(",
"\".lco\"",
")",
";",
"if",
"(",
"r... | cast a lucee string version to a int version
@param version
@return int version | [
"cast",
"a",
"lucee",
"string",
"version",
"to",
"a",
"int",
"version"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/loader/src/main/java/lucee/loader/engine/CFMLEngineFactorySupport.java#L106-L117 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/DTMNamedNodeMap.java | DTMNamedNodeMap.getNamedItemNS | public Node getNamedItemNS(String namespaceURI, String localName) {
"""
Retrieves a node specified by local name and namespace URI. HTML-only
DOM implementations do not need to implement this method.
@param namespaceURI The namespace URI of the node to retrieve.
@param localName The local name of the node to retrieve.
@return A <code>Node</code> (of any type) with the specified local
name and namespace URI, or <code>null</code> if they do not
identify any node in this map.
@since DOM Level 2
"""
Node retNode = null;
for (int n = dtm.getFirstAttribute(element); n != DTM.NULL;
n = dtm.getNextAttribute(n))
{
if (localName.equals(dtm.getLocalName(n)))
{
String nsURI = dtm.getNamespaceURI(n);
if ((namespaceURI == null && nsURI == null)
|| (namespaceURI != null && namespaceURI.equals(nsURI)))
{
retNode = dtm.getNode(n);
break;
}
}
}
return retNode;
} | java | public Node getNamedItemNS(String namespaceURI, String localName)
{
Node retNode = null;
for (int n = dtm.getFirstAttribute(element); n != DTM.NULL;
n = dtm.getNextAttribute(n))
{
if (localName.equals(dtm.getLocalName(n)))
{
String nsURI = dtm.getNamespaceURI(n);
if ((namespaceURI == null && nsURI == null)
|| (namespaceURI != null && namespaceURI.equals(nsURI)))
{
retNode = dtm.getNode(n);
break;
}
}
}
return retNode;
} | [
"public",
"Node",
"getNamedItemNS",
"(",
"String",
"namespaceURI",
",",
"String",
"localName",
")",
"{",
"Node",
"retNode",
"=",
"null",
";",
"for",
"(",
"int",
"n",
"=",
"dtm",
".",
"getFirstAttribute",
"(",
"element",
")",
";",
"n",
"!=",
"DTM",
".",
... | Retrieves a node specified by local name and namespace URI. HTML-only
DOM implementations do not need to implement this method.
@param namespaceURI The namespace URI of the node to retrieve.
@param localName The local name of the node to retrieve.
@return A <code>Node</code> (of any type) with the specified local
name and namespace URI, or <code>null</code> if they do not
identify any node in this map.
@since DOM Level 2 | [
"Retrieves",
"a",
"node",
"specified",
"by",
"local",
"name",
"and",
"namespace",
"URI",
".",
"HTML",
"-",
"only",
"DOM",
"implementations",
"do",
"not",
"need",
"to",
"implement",
"this",
"method",
".",
"@param",
"namespaceURI",
"The",
"namespace",
"URI",
"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/DTMNamedNodeMap.java#L197-L215 |
intendia-oss/rxjava-gwt | src/main/modified/io/reactivex/super/io/reactivex/Flowable.java | Flowable.repeatWhen | @CheckReturnValue
@BackpressureSupport(BackpressureKind.FULL)
@SchedulerSupport(SchedulerSupport.NONE)
public final Flowable<T> repeatWhen(final Function<? super Flowable<Object>, ? extends Publisher<?>> handler) {
"""
Returns a Flowable that emits the same values as the source Publisher with the exception of an
{@code onComplete}. An {@code onComplete} notification from the source will result in the emission of
a {@code void} item to the Publisher provided as an argument to the {@code notificationHandler}
function. If that Publisher calls {@code onComplete} or {@code onError} then {@code repeatWhen} will
call {@code onComplete} or {@code onError} on the child subscription. Otherwise, this Publisher will
resubscribe to the source Publisher.
<p>
<img width="640" height="430" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/repeatWhen.f.png" alt="">
<dl>
<dt><b>Backpressure:</b></dt>
<dd>The operator honors downstream backpressure and expects the source {@code Publisher} to honor backpressure as well.
If this expectation is violated, the operator <em>may</em> throw an {@code IllegalStateException}.</dd>
<dt><b>Scheduler:</b></dt>
<dd>{@code repeatWhen} does not operate by default on a particular {@link Scheduler}.</dd>
</dl>
@param handler
receives a Publisher of notifications with which a user can complete or error, aborting the repeat.
@return the source Publisher modified with repeat logic
@see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a>
"""
ObjectHelper.requireNonNull(handler, "handler is null");
return RxJavaPlugins.onAssembly(new FlowableRepeatWhen<T>(this, handler));
} | java | @CheckReturnValue
@BackpressureSupport(BackpressureKind.FULL)
@SchedulerSupport(SchedulerSupport.NONE)
public final Flowable<T> repeatWhen(final Function<? super Flowable<Object>, ? extends Publisher<?>> handler) {
ObjectHelper.requireNonNull(handler, "handler is null");
return RxJavaPlugins.onAssembly(new FlowableRepeatWhen<T>(this, handler));
} | [
"@",
"CheckReturnValue",
"@",
"BackpressureSupport",
"(",
"BackpressureKind",
".",
"FULL",
")",
"@",
"SchedulerSupport",
"(",
"SchedulerSupport",
".",
"NONE",
")",
"public",
"final",
"Flowable",
"<",
"T",
">",
"repeatWhen",
"(",
"final",
"Function",
"<",
"?",
... | Returns a Flowable that emits the same values as the source Publisher with the exception of an
{@code onComplete}. An {@code onComplete} notification from the source will result in the emission of
a {@code void} item to the Publisher provided as an argument to the {@code notificationHandler}
function. If that Publisher calls {@code onComplete} or {@code onError} then {@code repeatWhen} will
call {@code onComplete} or {@code onError} on the child subscription. Otherwise, this Publisher will
resubscribe to the source Publisher.
<p>
<img width="640" height="430" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/repeatWhen.f.png" alt="">
<dl>
<dt><b>Backpressure:</b></dt>
<dd>The operator honors downstream backpressure and expects the source {@code Publisher} to honor backpressure as well.
If this expectation is violated, the operator <em>may</em> throw an {@code IllegalStateException}.</dd>
<dt><b>Scheduler:</b></dt>
<dd>{@code repeatWhen} does not operate by default on a particular {@link Scheduler}.</dd>
</dl>
@param handler
receives a Publisher of notifications with which a user can complete or error, aborting the repeat.
@return the source Publisher modified with repeat logic
@see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a> | [
"Returns",
"a",
"Flowable",
"that",
"emits",
"the",
"same",
"values",
"as",
"the",
"source",
"Publisher",
"with",
"the",
"exception",
"of",
"an",
"{",
"@code",
"onComplete",
"}",
".",
"An",
"{",
"@code",
"onComplete",
"}",
"notification",
"from",
"the",
"s... | train | https://github.com/intendia-oss/rxjava-gwt/blob/8d5635b12ce40da99e76b59dc6bfe6fc2fffc1fa/src/main/modified/io/reactivex/super/io/reactivex/Flowable.java#L12389-L12395 |
jaxio/javaee-lab | javaee7-jpa-query-by-example/src/main/java/com/jaxio/jpa/querybyexample/DefaultLuceneQueryBuilder.java | DefaultLuceneQueryBuilder.escapeForFuzzy | private String escapeForFuzzy(String word) {
"""
Apply same filtering as "custom" analyzer. Lowercase is done by QueryParser for fuzzy search.
@param word word
@return word escaped
"""
int length = word.length();
char[] tmp = new char[length * 4];
length = ASCIIFoldingFilter.foldToASCII(word.toCharArray(), 0, tmp, 0, length);
return new String(tmp, 0, length);
} | java | private String escapeForFuzzy(String word) {
int length = word.length();
char[] tmp = new char[length * 4];
length = ASCIIFoldingFilter.foldToASCII(word.toCharArray(), 0, tmp, 0, length);
return new String(tmp, 0, length);
} | [
"private",
"String",
"escapeForFuzzy",
"(",
"String",
"word",
")",
"{",
"int",
"length",
"=",
"word",
".",
"length",
"(",
")",
";",
"char",
"[",
"]",
"tmp",
"=",
"new",
"char",
"[",
"length",
"*",
"4",
"]",
";",
"length",
"=",
"ASCIIFoldingFilter",
"... | Apply same filtering as "custom" analyzer. Lowercase is done by QueryParser for fuzzy search.
@param word word
@return word escaped | [
"Apply",
"same",
"filtering",
"as",
"custom",
"analyzer",
".",
"Lowercase",
"is",
"done",
"by",
"QueryParser",
"for",
"fuzzy",
"search",
"."
] | train | https://github.com/jaxio/javaee-lab/blob/61238b967952446d81cc68424a4e809093a77fcf/javaee7-jpa-query-by-example/src/main/java/com/jaxio/jpa/querybyexample/DefaultLuceneQueryBuilder.java#L163-L168 |
oehf/ipf-oht-atna | auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/XDSConsumerAuditor.java | XDSConsumerAuditor.auditRetrieveDocumentEvent | public void auditRetrieveDocumentEvent(RFC3881EventOutcomeCodes eventOutcome,
String repositoryRetrieveUri,
String userName,
String documentUniqueId,
String patientId) {
"""
Audits an ITI-17 Retrieve Document event for XDS.a Document Consumer actors.
@param eventOutcome The event outcome indicator
@param repositoryRetrieveUri The URI of the document being retrieved
@param documentUniqueId The Document Entry Unique ID of the document being retrieved (if known)
@param patientId The patient ID the document relates to (if known)
"""
if (!isAuditorEnabled()) {
return;
}
ImportEvent importEvent = new ImportEvent(false, eventOutcome, new IHETransactionEventTypeCodes.RetrieveDocument(), null);
importEvent.setAuditSourceId(getAuditSourceId(), getAuditEnterpriseSiteId());
importEvent.addSourceActiveParticipant(repositoryRetrieveUri, null, null, EventUtils.getAddressForUrl(repositoryRetrieveUri, false), false);
importEvent.addDestinationActiveParticipant(getSystemUserId(), getSystemAltUserId(), getSystemUserName(), getSystemNetworkId(), true);
if (!EventUtils.isEmptyOrNull(userName)) {
importEvent.addHumanRequestorActiveParticipant(userName, null, userName, (List<CodedValueType>) null);
}
if (!EventUtils.isEmptyOrNull(patientId)) {
importEvent.addPatientParticipantObject(patientId);
}
importEvent.addDocumentUriParticipantObject(repositoryRetrieveUri, documentUniqueId);
audit(importEvent);
} | java | public void auditRetrieveDocumentEvent(RFC3881EventOutcomeCodes eventOutcome,
String repositoryRetrieveUri,
String userName,
String documentUniqueId,
String patientId)
{
if (!isAuditorEnabled()) {
return;
}
ImportEvent importEvent = new ImportEvent(false, eventOutcome, new IHETransactionEventTypeCodes.RetrieveDocument(), null);
importEvent.setAuditSourceId(getAuditSourceId(), getAuditEnterpriseSiteId());
importEvent.addSourceActiveParticipant(repositoryRetrieveUri, null, null, EventUtils.getAddressForUrl(repositoryRetrieveUri, false), false);
importEvent.addDestinationActiveParticipant(getSystemUserId(), getSystemAltUserId(), getSystemUserName(), getSystemNetworkId(), true);
if (!EventUtils.isEmptyOrNull(userName)) {
importEvent.addHumanRequestorActiveParticipant(userName, null, userName, (List<CodedValueType>) null);
}
if (!EventUtils.isEmptyOrNull(patientId)) {
importEvent.addPatientParticipantObject(patientId);
}
importEvent.addDocumentUriParticipantObject(repositoryRetrieveUri, documentUniqueId);
audit(importEvent);
} | [
"public",
"void",
"auditRetrieveDocumentEvent",
"(",
"RFC3881EventOutcomeCodes",
"eventOutcome",
",",
"String",
"repositoryRetrieveUri",
",",
"String",
"userName",
",",
"String",
"documentUniqueId",
",",
"String",
"patientId",
")",
"{",
"if",
"(",
"!",
"isAuditorEnabled... | Audits an ITI-17 Retrieve Document event for XDS.a Document Consumer actors.
@param eventOutcome The event outcome indicator
@param repositoryRetrieveUri The URI of the document being retrieved
@param documentUniqueId The Document Entry Unique ID of the document being retrieved (if known)
@param patientId The patient ID the document relates to (if known) | [
"Audits",
"an",
"ITI",
"-",
"17",
"Retrieve",
"Document",
"event",
"for",
"XDS",
".",
"a",
"Document",
"Consumer",
"actors",
"."
] | train | https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/XDSConsumerAuditor.java#L132-L154 |
wiselenium/wiselenium | wiselenium-factory/src/main/java/com/github/wiselenium/factory/RootInjector.java | RootInjector.rootDriver | public static <E> void rootDriver(WebDriver root, E page) {
"""
Injects the webdriver into a page.
@param root The webdriver.
@param element The element.
@since 0.3.0
"""
if (page == null || root == null) return;
for (Class<?> clazz = page.getClass(); !clazz.equals(Object.class);
clazz = clazz.getSuperclass()) {
if (Enhancer.isEnhanced(clazz)) continue;
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
setRootDriverField(root, page, field);
}
}
} | java | public static <E> void rootDriver(WebDriver root, E page) {
if (page == null || root == null) return;
for (Class<?> clazz = page.getClass(); !clazz.equals(Object.class);
clazz = clazz.getSuperclass()) {
if (Enhancer.isEnhanced(clazz)) continue;
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
setRootDriverField(root, page, field);
}
}
} | [
"public",
"static",
"<",
"E",
">",
"void",
"rootDriver",
"(",
"WebDriver",
"root",
",",
"E",
"page",
")",
"{",
"if",
"(",
"page",
"==",
"null",
"||",
"root",
"==",
"null",
")",
"return",
";",
"for",
"(",
"Class",
"<",
"?",
">",
"clazz",
"=",
"pag... | Injects the webdriver into a page.
@param root The webdriver.
@param element The element.
@since 0.3.0 | [
"Injects",
"the",
"webdriver",
"into",
"a",
"page",
"."
] | train | https://github.com/wiselenium/wiselenium/blob/15de6484d8f516b3d02391d3bd6a56a03e632706/wiselenium-factory/src/main/java/com/github/wiselenium/factory/RootInjector.java#L72-L85 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/persistent/infinispan/ISPNCacheWorkspaceStorageCache.java | ISPNCacheWorkspaceStorageCache.putNode | protected ItemData putNode(NodeData node, ModifyChildOption modifyListsOfChild) {
"""
Internal put Node.
@param node, NodeData, new data to put in the cache
@return NodeData, previous data or null
"""
if (node.getParentIdentifier() != null)
{
if (modifyListsOfChild == ModifyChildOption.NOT_MODIFY)
{
cache.putIfAbsent(new CacheQPath(getOwnerId(), node.getParentIdentifier(), node.getQPath(), ItemType.NODE),
node.getIdentifier());
}
else
{
cache.put(new CacheQPath(getOwnerId(), node.getParentIdentifier(), node.getQPath(), ItemType.NODE),
node.getIdentifier());
}
// if MODIFY and List present OR FORCE_MODIFY, then write
if (modifyListsOfChild != ModifyChildOption.NOT_MODIFY)
{
cache.addToPatternList(new CachePatternNodesId(getOwnerId(), node.getParentIdentifier()), node);
cache.addToList(new CacheNodesId(getOwnerId(), node.getParentIdentifier()), node.getIdentifier(),
modifyListsOfChild == ModifyChildOption.FORCE_MODIFY);
cache.remove(new CacheNodesByPageId(getOwnerId(), node.getParentIdentifier()));
}
}
if (modifyListsOfChild == ModifyChildOption.NOT_MODIFY)
{
return (ItemData)cache.putIfAbsent(new CacheId(getOwnerId(), node.getIdentifier()), node);
}
else
{
return (ItemData)cache.put(new CacheId(getOwnerId(), node.getIdentifier()), node, true);
}
} | java | protected ItemData putNode(NodeData node, ModifyChildOption modifyListsOfChild)
{
if (node.getParentIdentifier() != null)
{
if (modifyListsOfChild == ModifyChildOption.NOT_MODIFY)
{
cache.putIfAbsent(new CacheQPath(getOwnerId(), node.getParentIdentifier(), node.getQPath(), ItemType.NODE),
node.getIdentifier());
}
else
{
cache.put(new CacheQPath(getOwnerId(), node.getParentIdentifier(), node.getQPath(), ItemType.NODE),
node.getIdentifier());
}
// if MODIFY and List present OR FORCE_MODIFY, then write
if (modifyListsOfChild != ModifyChildOption.NOT_MODIFY)
{
cache.addToPatternList(new CachePatternNodesId(getOwnerId(), node.getParentIdentifier()), node);
cache.addToList(new CacheNodesId(getOwnerId(), node.getParentIdentifier()), node.getIdentifier(),
modifyListsOfChild == ModifyChildOption.FORCE_MODIFY);
cache.remove(new CacheNodesByPageId(getOwnerId(), node.getParentIdentifier()));
}
}
if (modifyListsOfChild == ModifyChildOption.NOT_MODIFY)
{
return (ItemData)cache.putIfAbsent(new CacheId(getOwnerId(), node.getIdentifier()), node);
}
else
{
return (ItemData)cache.put(new CacheId(getOwnerId(), node.getIdentifier()), node, true);
}
} | [
"protected",
"ItemData",
"putNode",
"(",
"NodeData",
"node",
",",
"ModifyChildOption",
"modifyListsOfChild",
")",
"{",
"if",
"(",
"node",
".",
"getParentIdentifier",
"(",
")",
"!=",
"null",
")",
"{",
"if",
"(",
"modifyListsOfChild",
"==",
"ModifyChildOption",
".... | Internal put Node.
@param node, NodeData, new data to put in the cache
@return NodeData, previous data or null | [
"Internal",
"put",
"Node",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/persistent/infinispan/ISPNCacheWorkspaceStorageCache.java#L1318-L1352 |
tropo/tropo-webapi-java | src/main/java/com/voxeo/tropo/Key.java | Key.JOIN_PROMPT | public static Key JOIN_PROMPT(String value, Voice voice) {
"""
Defines a prompt that plays to all participants of a conference when
someone joins the conference.It's possible to define either TTS or an audio
URL using additional attributes value and voice
@param value
value is used to play simple TTS and/or an audio URL, and supports
SSML
@param voice
voice is used to define which of the available voices should be
used for TTS; if voice is left undefined, the default voice will
be used
@return
"""
Map<String, String> map = new HashMap<String, String>();
map.put("value", value);
if (voice != null) {
map.put("voice", voice.toString());
}
return createKey("joinPrompt", map);
} | java | public static Key JOIN_PROMPT(String value, Voice voice) {
Map<String, String> map = new HashMap<String, String>();
map.put("value", value);
if (voice != null) {
map.put("voice", voice.toString());
}
return createKey("joinPrompt", map);
} | [
"public",
"static",
"Key",
"JOIN_PROMPT",
"(",
"String",
"value",
",",
"Voice",
"voice",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"map",
"=",
"new",
"HashMap",
"<",
"String",
",",
"String",
">",
"(",
")",
";",
"map",
".",
"put",
"(",
"\"... | Defines a prompt that plays to all participants of a conference when
someone joins the conference.It's possible to define either TTS or an audio
URL using additional attributes value and voice
@param value
value is used to play simple TTS and/or an audio URL, and supports
SSML
@param voice
voice is used to define which of the available voices should be
used for TTS; if voice is left undefined, the default voice will
be used
@return | [
"Defines",
"a",
"prompt",
"that",
"plays",
"to",
"all",
"participants",
"of",
"a",
"conference",
"when",
"someone",
"joins",
"the",
"conference",
".",
"It",
"s",
"possible",
"to",
"define",
"either",
"TTS",
"or",
"an",
"audio",
"URL",
"using",
"additional",
... | train | https://github.com/tropo/tropo-webapi-java/blob/96af1fa292c1d4b6321d85a559d9718d33eec7e0/src/main/java/com/voxeo/tropo/Key.java#L421-L430 |
apache/flink | flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/generator/GraphGeneratorUtils.java | GraphGeneratorUtils.vertexSequence | public static DataSet<Vertex<LongValue, NullValue>> vertexSequence(ExecutionEnvironment env, int parallelism, long vertexCount) {
"""
Generates {@link Vertex Vertices} with sequential, numerical labels.
@param env the Flink execution environment.
@param parallelism operator parallelism
@param vertexCount number of sequential vertex labels
@return {@link DataSet} of sequentially labeled {@link Vertex vertices}
"""
Preconditions.checkArgument(vertexCount >= 0, "Vertex count must be non-negative");
if (vertexCount == 0) {
return env
.fromCollection(Collections.emptyList(), TypeInformation.of(new TypeHint<Vertex<LongValue, NullValue>>(){}))
.setParallelism(parallelism)
.name("Empty vertex set");
} else {
LongValueSequenceIterator iterator = new LongValueSequenceIterator(0, vertexCount - 1);
DataSource<LongValue> vertexLabels = env
.fromParallelCollection(iterator, LongValue.class)
.setParallelism(parallelism)
.name("Vertex indices");
return vertexLabels
.map(new CreateVertex())
.setParallelism(parallelism)
.name("Vertex sequence");
}
} | java | public static DataSet<Vertex<LongValue, NullValue>> vertexSequence(ExecutionEnvironment env, int parallelism, long vertexCount) {
Preconditions.checkArgument(vertexCount >= 0, "Vertex count must be non-negative");
if (vertexCount == 0) {
return env
.fromCollection(Collections.emptyList(), TypeInformation.of(new TypeHint<Vertex<LongValue, NullValue>>(){}))
.setParallelism(parallelism)
.name("Empty vertex set");
} else {
LongValueSequenceIterator iterator = new LongValueSequenceIterator(0, vertexCount - 1);
DataSource<LongValue> vertexLabels = env
.fromParallelCollection(iterator, LongValue.class)
.setParallelism(parallelism)
.name("Vertex indices");
return vertexLabels
.map(new CreateVertex())
.setParallelism(parallelism)
.name("Vertex sequence");
}
} | [
"public",
"static",
"DataSet",
"<",
"Vertex",
"<",
"LongValue",
",",
"NullValue",
">",
">",
"vertexSequence",
"(",
"ExecutionEnvironment",
"env",
",",
"int",
"parallelism",
",",
"long",
"vertexCount",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"vertex... | Generates {@link Vertex Vertices} with sequential, numerical labels.
@param env the Flink execution environment.
@param parallelism operator parallelism
@param vertexCount number of sequential vertex labels
@return {@link DataSet} of sequentially labeled {@link Vertex vertices} | [
"Generates",
"{",
"@link",
"Vertex",
"Vertices",
"}",
"with",
"sequential",
"numerical",
"labels",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/generator/GraphGeneratorUtils.java#L56-L77 |
kaazing/gateway | service/http.proxy/src/main/java/org/kaazing/gateway/service/http/proxy/HttpProxyServiceHandler.java | HttpProxyServiceHandler.processHopByHopHeaders | private static boolean processHopByHopHeaders(HttpSession src, HttpSession dest) {
"""
/*
Write all (except hop-by-hop) headers from source session to destination session.
If the header is an upgrade one, let the Upgrade header go through as this service supports upgrade
"""
Set<String> hopByHopHeaders = getHopByHopHeaders(src);
boolean upgrade = src.getReadHeader(HEADER_UPGRADE) != null;
if (upgrade) {
hopByHopHeaders.remove(HEADER_UPGRADE);
}
// Add source session headers to destination session
for (Map.Entry<String, List<String>> e : src.getReadHeaders().entrySet()) {
String name = e.getKey();
for (String value : e.getValue()) {
if (!hopByHopHeaders.contains(name)) {
dest.addWriteHeader(name, value);
}
}
}
return upgrade;
} | java | private static boolean processHopByHopHeaders(HttpSession src, HttpSession dest) {
Set<String> hopByHopHeaders = getHopByHopHeaders(src);
boolean upgrade = src.getReadHeader(HEADER_UPGRADE) != null;
if (upgrade) {
hopByHopHeaders.remove(HEADER_UPGRADE);
}
// Add source session headers to destination session
for (Map.Entry<String, List<String>> e : src.getReadHeaders().entrySet()) {
String name = e.getKey();
for (String value : e.getValue()) {
if (!hopByHopHeaders.contains(name)) {
dest.addWriteHeader(name, value);
}
}
}
return upgrade;
} | [
"private",
"static",
"boolean",
"processHopByHopHeaders",
"(",
"HttpSession",
"src",
",",
"HttpSession",
"dest",
")",
"{",
"Set",
"<",
"String",
">",
"hopByHopHeaders",
"=",
"getHopByHopHeaders",
"(",
"src",
")",
";",
"boolean",
"upgrade",
"=",
"src",
".",
"ge... | /*
Write all (except hop-by-hop) headers from source session to destination session.
If the header is an upgrade one, let the Upgrade header go through as this service supports upgrade | [
"/",
"*",
"Write",
"all",
"(",
"except",
"hop",
"-",
"by",
"-",
"hop",
")",
"headers",
"from",
"source",
"session",
"to",
"destination",
"session",
"."
] | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/service/http.proxy/src/main/java/org/kaazing/gateway/service/http/proxy/HttpProxyServiceHandler.java#L444-L462 |
couchbase/couchbase-lite-java-core | src/main/java/com/couchbase/lite/util/Utils.java | Utils.shutdownAndAwaitTermination | public static void shutdownAndAwaitTermination(ExecutorService pool,
long timeToWait4ShutDown,
long timeToWait4ShutDownNow) {
"""
The following method shuts down an ExecutorService in two phases,
first by calling shutdown to reject incoming tasks, and then calling shutdownNow,
if necessary, to cancel any lingering tasks:
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html
@param timeToWait4ShutDown - Seconds
@param timeToWait4ShutDownNow - Seconds
"""
synchronized (pool) {
// Disable new tasks from being submitted
pool.shutdown();
}
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(timeToWait4ShutDown, TimeUnit.SECONDS)) {
synchronized (pool) {
pool.shutdownNow(); // Cancel currently executing tasks
}
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(timeToWait4ShutDownNow, TimeUnit.SECONDS)) {
Log.e(Log.TAG_DATABASE, "Pool did not terminate");
}
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
synchronized (pool) {
pool.shutdownNow();
}
// Preserve interrupt status
Thread.currentThread().interrupt();
}
} | java | public static void shutdownAndAwaitTermination(ExecutorService pool,
long timeToWait4ShutDown,
long timeToWait4ShutDownNow) {
synchronized (pool) {
// Disable new tasks from being submitted
pool.shutdown();
}
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(timeToWait4ShutDown, TimeUnit.SECONDS)) {
synchronized (pool) {
pool.shutdownNow(); // Cancel currently executing tasks
}
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(timeToWait4ShutDownNow, TimeUnit.SECONDS)) {
Log.e(Log.TAG_DATABASE, "Pool did not terminate");
}
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
synchronized (pool) {
pool.shutdownNow();
}
// Preserve interrupt status
Thread.currentThread().interrupt();
}
} | [
"public",
"static",
"void",
"shutdownAndAwaitTermination",
"(",
"ExecutorService",
"pool",
",",
"long",
"timeToWait4ShutDown",
",",
"long",
"timeToWait4ShutDownNow",
")",
"{",
"synchronized",
"(",
"pool",
")",
"{",
"// Disable new tasks from being submitted",
"pool",
".",... | The following method shuts down an ExecutorService in two phases,
first by calling shutdown to reject incoming tasks, and then calling shutdownNow,
if necessary, to cancel any lingering tasks:
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html
@param timeToWait4ShutDown - Seconds
@param timeToWait4ShutDownNow - Seconds | [
"The",
"following",
"method",
"shuts",
"down",
"an",
"ExecutorService",
"in",
"two",
"phases",
"first",
"by",
"calling",
"shutdown",
"to",
"reject",
"incoming",
"tasks",
"and",
"then",
"calling",
"shutdownNow",
"if",
"necessary",
"to",
"cancel",
"any",
"lingerin... | train | https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/util/Utils.java#L315-L341 |
Mozu/mozu-java | mozu-java-core/src/main/java/com/mozu/api/urls/commerce/customer/accounts/CardUrl.java | CardUrl.deleteAccountCardUrl | public static MozuUrl deleteAccountCardUrl(Integer accountId, String cardId) {
"""
Get Resource Url for DeleteAccountCard
@param accountId Unique identifier of the customer account.
@param cardId Unique identifier of the card associated with the customer account billing contact.
@return String Resource Url
"""
UrlFormatter formatter = new UrlFormatter("/api/commerce/customer/accounts/{accountId}/cards/{cardId}");
formatter.formatUrl("accountId", accountId);
formatter.formatUrl("cardId", cardId);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl deleteAccountCardUrl(Integer accountId, String cardId)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/customer/accounts/{accountId}/cards/{cardId}");
formatter.formatUrl("accountId", accountId);
formatter.formatUrl("cardId", cardId);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"deleteAccountCardUrl",
"(",
"Integer",
"accountId",
",",
"String",
"cardId",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/commerce/customer/accounts/{accountId}/cards/{cardId}\"",
")",
";",
"formatter",
".... | Get Resource Url for DeleteAccountCard
@param accountId Unique identifier of the customer account.
@param cardId Unique identifier of the card associated with the customer account billing contact.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"DeleteAccountCard"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/customer/accounts/CardUrl.java#L82-L88 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/SynchronousRequest.java | SynchronousRequest.getTPTransaction | public List<Transaction> getTPTransaction(String API, Transaction.Time time, Transaction.Type type) throws GuildWars2Exception {
"""
For more info on Transaction API go <a href="https://wiki.guildwars2.com/wiki/API:2/commerce/transactions">here</a><br/>
Get transaction info linked to given API key
@param API API key
@param time current | History
@param type buy | sell
@return list of transaction base on the selection, if there is nothing, return empty list
@throws GuildWars2Exception see {@link ErrorCode} for detail
@see Transaction transaction info
"""
isParamValid(new ParamChecker(ParamType.API, API));
if (time == null || type == null)
throw new GuildWars2Exception(ErrorCode.TransTime, "Transaction time/type cannot be empty");
try {
Response<List<Transaction>> response = gw2API.getTPTransaction(time.getValue(), type.getValue(), API).execute();
if (!response.isSuccessful()) throwError(response.code(), response.errorBody());
return response.body();
} catch (IOException e) {
throw new GuildWars2Exception(ErrorCode.Network, "Network Error: " + e.getMessage());
}
} | java | public List<Transaction> getTPTransaction(String API, Transaction.Time time, Transaction.Type type) throws GuildWars2Exception {
isParamValid(new ParamChecker(ParamType.API, API));
if (time == null || type == null)
throw new GuildWars2Exception(ErrorCode.TransTime, "Transaction time/type cannot be empty");
try {
Response<List<Transaction>> response = gw2API.getTPTransaction(time.getValue(), type.getValue(), API).execute();
if (!response.isSuccessful()) throwError(response.code(), response.errorBody());
return response.body();
} catch (IOException e) {
throw new GuildWars2Exception(ErrorCode.Network, "Network Error: " + e.getMessage());
}
} | [
"public",
"List",
"<",
"Transaction",
">",
"getTPTransaction",
"(",
"String",
"API",
",",
"Transaction",
".",
"Time",
"time",
",",
"Transaction",
".",
"Type",
"type",
")",
"throws",
"GuildWars2Exception",
"{",
"isParamValid",
"(",
"new",
"ParamChecker",
"(",
"... | For more info on Transaction API go <a href="https://wiki.guildwars2.com/wiki/API:2/commerce/transactions">here</a><br/>
Get transaction info linked to given API key
@param API API key
@param time current | History
@param type buy | sell
@return list of transaction base on the selection, if there is nothing, return empty list
@throws GuildWars2Exception see {@link ErrorCode} for detail
@see Transaction transaction info | [
"For",
"more",
"info",
"on",
"Transaction",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"commerce",
"/",
"transactions",
">",
"here<",
"/",
"a",
">",
"<br",
"/",... | train | https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/SynchronousRequest.java#L1330-L1341 |
saxsys/SynchronizeFX | synchronizefx-core/src/main/java/de/saxsys/synchronizefx/core/metamodel/executors/lists/RemoveFromListRepairer.java | RemoveFromListRepairer.repairCommand | public List<RemoveFromList> repairCommand(final RemoveFromList toRepair, final RemoveFromList repairAgainst) {
"""
Repairs a {@link RemoveFromList} in relation to a {@link RemoveFromList} command.
@param toRepair
The command to repair.
@param repairAgainst
The command to repair against.
@return The repaired command.
"""
if (toRepair.getStartPosition() + toRepair.getRemoveCount() <= repairAgainst.getStartPosition()) {
return asList(toRepair);
}
if (toRepair.getStartPosition() >= repairAgainst.getStartPosition() + repairAgainst.getRemoveCount()) {
return asList(createRepaired(toRepair, toRepair.getStartPosition() - repairAgainst.getRemoveCount(),
toRepair.getRemoveCount()));
}
final int startPosition = toRepair.getStartPosition() < repairAgainst.getStartPosition() ? toRepair
.getStartPosition() : repairAgainst.getStartPosition();
final int indicesBefore = repairAgainst.getStartPosition() - toRepair.getStartPosition();
final int indicesAfter = (toRepair.getStartPosition() + toRepair.getRemoveCount())
- (repairAgainst.getStartPosition() + repairAgainst.getRemoveCount());
final int indicesBeforeAndAfter = max(indicesBefore, 0) + max(indicesAfter, 0);
if (indicesBeforeAndAfter == 0) {
return asList(createRepaired(toRepair, 0, 0));
}
final int removeCount = min(indicesBeforeAndAfter, toRepair.getRemoveCount());
return asList(createRepaired(toRepair, startPosition, removeCount));
} | java | public List<RemoveFromList> repairCommand(final RemoveFromList toRepair, final RemoveFromList repairAgainst) {
if (toRepair.getStartPosition() + toRepair.getRemoveCount() <= repairAgainst.getStartPosition()) {
return asList(toRepair);
}
if (toRepair.getStartPosition() >= repairAgainst.getStartPosition() + repairAgainst.getRemoveCount()) {
return asList(createRepaired(toRepair, toRepair.getStartPosition() - repairAgainst.getRemoveCount(),
toRepair.getRemoveCount()));
}
final int startPosition = toRepair.getStartPosition() < repairAgainst.getStartPosition() ? toRepair
.getStartPosition() : repairAgainst.getStartPosition();
final int indicesBefore = repairAgainst.getStartPosition() - toRepair.getStartPosition();
final int indicesAfter = (toRepair.getStartPosition() + toRepair.getRemoveCount())
- (repairAgainst.getStartPosition() + repairAgainst.getRemoveCount());
final int indicesBeforeAndAfter = max(indicesBefore, 0) + max(indicesAfter, 0);
if (indicesBeforeAndAfter == 0) {
return asList(createRepaired(toRepair, 0, 0));
}
final int removeCount = min(indicesBeforeAndAfter, toRepair.getRemoveCount());
return asList(createRepaired(toRepair, startPosition, removeCount));
} | [
"public",
"List",
"<",
"RemoveFromList",
">",
"repairCommand",
"(",
"final",
"RemoveFromList",
"toRepair",
",",
"final",
"RemoveFromList",
"repairAgainst",
")",
"{",
"if",
"(",
"toRepair",
".",
"getStartPosition",
"(",
")",
"+",
"toRepair",
".",
"getRemoveCount",
... | Repairs a {@link RemoveFromList} in relation to a {@link RemoveFromList} command.
@param toRepair
The command to repair.
@param repairAgainst
The command to repair against.
@return The repaired command. | [
"Repairs",
"a",
"{",
"@link",
"RemoveFromList",
"}",
"in",
"relation",
"to",
"a",
"{",
"@link",
"RemoveFromList",
"}",
"command",
"."
] | train | https://github.com/saxsys/SynchronizeFX/blob/f3683020e4749110b38514eb5bc73a247998b579/synchronizefx-core/src/main/java/de/saxsys/synchronizefx/core/metamodel/executors/lists/RemoveFromListRepairer.java#L69-L91 |
javafxports/javafxmobile-plugin | src/main/java/org/javafxports/jfxmobile/plugin/android/task/ApkBuilder.java | ApkBuilder.checkFileForPackaging | public static boolean checkFileForPackaging(String fileName, String extension) {
"""
Checks a file to make sure it should be packaged as standard resources.
@param fileName the name of the file (including extension)
@param extension the extension of the file (excluding '.')
@return true if the file should be packaged as standard java resources.
"""
// ignore hidden files and backup files
if (fileName.charAt(0) == '.' || fileName.charAt(fileName.length()-1) == '~') {
return false;
}
return !"aidl".equalsIgnoreCase(extension) && // Aidl files
!"rs".equalsIgnoreCase(extension) && // RenderScript files
!"fs".equalsIgnoreCase(extension) && // FilterScript files
!"rsh".equalsIgnoreCase(extension) && // RenderScript header files
!"d".equalsIgnoreCase(extension) && // Dependency files
!"java".equalsIgnoreCase(extension) && // Java files
!"scala".equalsIgnoreCase(extension) && // Scala files
!"class".equalsIgnoreCase(extension) && // Java class files
!"scc".equalsIgnoreCase(extension) && // VisualSourceSafe
!"swp".equalsIgnoreCase(extension) && // vi swap file
!"thumbs.db".equalsIgnoreCase(fileName) && // image index file
!"picasa.ini".equalsIgnoreCase(fileName) && // image index file
!"package.html".equalsIgnoreCase(fileName) && // Javadoc
!"overview.html".equalsIgnoreCase(fileName); // Javadoc
} | java | public static boolean checkFileForPackaging(String fileName, String extension) {
// ignore hidden files and backup files
if (fileName.charAt(0) == '.' || fileName.charAt(fileName.length()-1) == '~') {
return false;
}
return !"aidl".equalsIgnoreCase(extension) && // Aidl files
!"rs".equalsIgnoreCase(extension) && // RenderScript files
!"fs".equalsIgnoreCase(extension) && // FilterScript files
!"rsh".equalsIgnoreCase(extension) && // RenderScript header files
!"d".equalsIgnoreCase(extension) && // Dependency files
!"java".equalsIgnoreCase(extension) && // Java files
!"scala".equalsIgnoreCase(extension) && // Scala files
!"class".equalsIgnoreCase(extension) && // Java class files
!"scc".equalsIgnoreCase(extension) && // VisualSourceSafe
!"swp".equalsIgnoreCase(extension) && // vi swap file
!"thumbs.db".equalsIgnoreCase(fileName) && // image index file
!"picasa.ini".equalsIgnoreCase(fileName) && // image index file
!"package.html".equalsIgnoreCase(fileName) && // Javadoc
!"overview.html".equalsIgnoreCase(fileName); // Javadoc
} | [
"public",
"static",
"boolean",
"checkFileForPackaging",
"(",
"String",
"fileName",
",",
"String",
"extension",
")",
"{",
"// ignore hidden files and backup files",
"if",
"(",
"fileName",
".",
"charAt",
"(",
"0",
")",
"==",
"'",
"'",
"||",
"fileName",
".",
"charA... | Checks a file to make sure it should be packaged as standard resources.
@param fileName the name of the file (including extension)
@param extension the extension of the file (excluding '.')
@return true if the file should be packaged as standard java resources. | [
"Checks",
"a",
"file",
"to",
"make",
"sure",
"it",
"should",
"be",
"packaged",
"as",
"standard",
"resources",
"."
] | train | https://github.com/javafxports/javafxmobile-plugin/blob/a9bef513b7e1bfa85f9a668226e6943c6d9f847f/src/main/java/org/javafxports/jfxmobile/plugin/android/task/ApkBuilder.java#L1036-L1056 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Vector.java | Vector.setElementAt | public synchronized void setElementAt(E obj, int index) {
"""
Sets the component at the specified {@code index} of this
vector to be the specified object. The previous component at that
position is discarded.
<p>The index must be a value greater than or equal to {@code 0}
and less than the current size of the vector.
<p>This method is identical in functionality to the
{@link #set(int, Object) set(int, E)}
method (which is part of the {@link List} interface). Note that the
{@code set} method reverses the order of the parameters, to more closely
match array usage. Note also that the {@code set} method returns the
old value that was stored at the specified position.
@param obj what the component is to be set to
@param index the specified index
@throws ArrayIndexOutOfBoundsException if the index is out of range
({@code index < 0 || index >= size()})
"""
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
elementData[index] = obj;
} | java | public synchronized void setElementAt(E obj, int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
elementData[index] = obj;
} | [
"public",
"synchronized",
"void",
"setElementAt",
"(",
"E",
"obj",
",",
"int",
"index",
")",
"{",
"if",
"(",
"index",
">=",
"elementCount",
")",
"{",
"throw",
"new",
"ArrayIndexOutOfBoundsException",
"(",
"index",
"+",
"\" >= \"",
"+",
"elementCount",
")",
"... | Sets the component at the specified {@code index} of this
vector to be the specified object. The previous component at that
position is discarded.
<p>The index must be a value greater than or equal to {@code 0}
and less than the current size of the vector.
<p>This method is identical in functionality to the
{@link #set(int, Object) set(int, E)}
method (which is part of the {@link List} interface). Note that the
{@code set} method reverses the order of the parameters, to more closely
match array usage. Note also that the {@code set} method returns the
old value that was stored at the specified position.
@param obj what the component is to be set to
@param index the specified index
@throws ArrayIndexOutOfBoundsException if the index is out of range
({@code index < 0 || index >= size()}) | [
"Sets",
"the",
"component",
"at",
"the",
"specified",
"{",
"@code",
"index",
"}",
"of",
"this",
"vector",
"to",
"be",
"the",
"specified",
"object",
".",
"The",
"previous",
"component",
"at",
"that",
"position",
"is",
"discarded",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Vector.java#L528-L534 |
yatechorg/jedis-utils | src/main/java/org/yatech/jedis/collections/JedisCollections.java | JedisCollections.getSortedSet | public JedisSortedSet getSortedSet(int db, String key, ScoreProvider scoreProvider) {
"""
Get a {@link java.util.Set} abstraction of a sorted set redis value in the specified database index and key.
@param db the database index where the key with the sorted set value is / should be stored.
@param key the key of the sorted set value in redis
@param scoreProvider the provider to use for assigning scores when none is given explicitly.
@return the {@link JedisSortedSet} instance
"""
return new JedisSortedSet(jedisPool, db, key, scoreProvider);
} | java | public JedisSortedSet getSortedSet(int db, String key, ScoreProvider scoreProvider) {
return new JedisSortedSet(jedisPool, db, key, scoreProvider);
} | [
"public",
"JedisSortedSet",
"getSortedSet",
"(",
"int",
"db",
",",
"String",
"key",
",",
"ScoreProvider",
"scoreProvider",
")",
"{",
"return",
"new",
"JedisSortedSet",
"(",
"jedisPool",
",",
"db",
",",
"key",
",",
"scoreProvider",
")",
";",
"}"
] | Get a {@link java.util.Set} abstraction of a sorted set redis value in the specified database index and key.
@param db the database index where the key with the sorted set value is / should be stored.
@param key the key of the sorted set value in redis
@param scoreProvider the provider to use for assigning scores when none is given explicitly.
@return the {@link JedisSortedSet} instance | [
"Get",
"a",
"{"
] | train | https://github.com/yatechorg/jedis-utils/blob/1951609fa6697df4f69be76e7d66b9284924bd97/src/main/java/org/yatech/jedis/collections/JedisCollections.java#L131-L133 |
UrielCh/ovh-java-sdk | ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java | ApiOvhIpLoadbalancing.serviceName_task_GET | public ArrayList<Long> serviceName_task_GET(String serviceName, OvhTaskActionEnum action, Date creationDate_from, Date creationDate_to, Date doneDate_from, Date doneDate_to, OvhTaskStatusEnum status) throws IOException {
"""
Task for this iplb
REST: GET /ipLoadbalancing/{serviceName}/task
@param doneDate_to [required] Filter the value of doneDate property (<=)
@param doneDate_from [required] Filter the value of doneDate property (>=)
@param action [required] Filter the value of action property (=)
@param creationDate_to [required] Filter the value of creationDate property (<=)
@param creationDate_from [required] Filter the value of creationDate property (>=)
@param status [required] Filter the value of status property (=)
@param serviceName [required] The internal name of your IP load balancing
"""
String qPath = "/ipLoadbalancing/{serviceName}/task";
StringBuilder sb = path(qPath, serviceName);
query(sb, "action", action);
query(sb, "creationDate.from", creationDate_from);
query(sb, "creationDate.to", creationDate_to);
query(sb, "doneDate.from", doneDate_from);
query(sb, "doneDate.to", doneDate_to);
query(sb, "status", status);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t2);
} | java | public ArrayList<Long> serviceName_task_GET(String serviceName, OvhTaskActionEnum action, Date creationDate_from, Date creationDate_to, Date doneDate_from, Date doneDate_to, OvhTaskStatusEnum status) throws IOException {
String qPath = "/ipLoadbalancing/{serviceName}/task";
StringBuilder sb = path(qPath, serviceName);
query(sb, "action", action);
query(sb, "creationDate.from", creationDate_from);
query(sb, "creationDate.to", creationDate_to);
query(sb, "doneDate.from", doneDate_from);
query(sb, "doneDate.to", doneDate_to);
query(sb, "status", status);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t2);
} | [
"public",
"ArrayList",
"<",
"Long",
">",
"serviceName_task_GET",
"(",
"String",
"serviceName",
",",
"OvhTaskActionEnum",
"action",
",",
"Date",
"creationDate_from",
",",
"Date",
"creationDate_to",
",",
"Date",
"doneDate_from",
",",
"Date",
"doneDate_to",
",",
"OvhTa... | Task for this iplb
REST: GET /ipLoadbalancing/{serviceName}/task
@param doneDate_to [required] Filter the value of doneDate property (<=)
@param doneDate_from [required] Filter the value of doneDate property (>=)
@param action [required] Filter the value of action property (=)
@param creationDate_to [required] Filter the value of creationDate property (<=)
@param creationDate_from [required] Filter the value of creationDate property (>=)
@param status [required] Filter the value of status property (=)
@param serviceName [required] The internal name of your IP load balancing | [
"Task",
"for",
"this",
"iplb"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java#L1068-L1079 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/serialization/impl/SerializationUtil.java | SerializationUtil.writeNullableList | public static <T> void writeNullableList(List<T> items, ObjectDataOutput out) throws IOException {
"""
Writes a list to an {@link ObjectDataOutput}. The list's size is written
to the data output, then each object in the list is serialized.
The list is allowed to be null.
@param items list of items to be serialized
@param out data output to write to
@param <T> type of items
@throws IOException when an error occurs while writing to the output
"""
writeNullableCollection(items, out);
} | java | public static <T> void writeNullableList(List<T> items, ObjectDataOutput out) throws IOException {
writeNullableCollection(items, out);
} | [
"public",
"static",
"<",
"T",
">",
"void",
"writeNullableList",
"(",
"List",
"<",
"T",
">",
"items",
",",
"ObjectDataOutput",
"out",
")",
"throws",
"IOException",
"{",
"writeNullableCollection",
"(",
"items",
",",
"out",
")",
";",
"}"
] | Writes a list to an {@link ObjectDataOutput}. The list's size is written
to the data output, then each object in the list is serialized.
The list is allowed to be null.
@param items list of items to be serialized
@param out data output to write to
@param <T> type of items
@throws IOException when an error occurs while writing to the output | [
"Writes",
"a",
"list",
"to",
"an",
"{",
"@link",
"ObjectDataOutput",
"}",
".",
"The",
"list",
"s",
"size",
"is",
"written",
"to",
"the",
"data",
"output",
"then",
"each",
"object",
"in",
"the",
"list",
"is",
"serialized",
".",
"The",
"list",
"is",
"all... | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/serialization/impl/SerializationUtil.java#L234-L236 |
OpenBEL/openbel-framework | org.openbel.framework.core/src/main/java/org/openbel/framework/core/df/cache/DefaultCacheableResourceService.java | DefaultCacheableResourceService.hashCompare | private HashState hashCompare(String location, File resource)
throws ResourceDownloadError {
"""
Compare hashes of the remote resource to the local resource. The
comparison can result in the following:
<ul>
<li>If the resource's remote hash does not exist then return
{@link HashState#MISSING_REMOTE_HASH}.</li>
<li>If the resource's remote hash matches the local resource's hash then
return {@link HashState#HASH_MATCH}</li>
<li>If the resource's remote hash does not match the local resource's
hash then return {@link HashState#HASH_MISMATCH}.</li>
</ul>
@param location {@link String}, the remote resource location
@param resource {@link File}, the resource's local copy in the cache
@return {@link HashState} the state of the hash comparison which is
useful for deciding how to deal further with the resource
@throws IOException Thrown if there was an IO error in handling hash
files
"""
String tmpPath = getSystemConfiguration().getCacheDirectory()
.getAbsolutePath();
String remoteHashLocation = location + SHA256_EXTENSION;
String tempHashPath = asPath(
ResourceType.TMP_FILE.getResourceFolderName(),
encodeLocation(location),
CacheLookupService.DEFAULT_RESOURCE_FILE_NAME
+ SHA256_EXTENSION);
// download resource hash
File remoteHashFile = null;
try {
remoteHashFile = resolveResource(remoteHashLocation, tmpPath,
tempHashPath);
} catch (ResourceDownloadError e) {
return HashState.MISSING_REMOTE_HASH;
}
String absPath = resource.getAbsolutePath();
File localHashFile = new File(absPath + SHA256_EXTENSION);
if (!localHashFile.exists() || !localHashFile.canRead()) {
localHashFile = createLocalHash(resource, location);
}
// compare hash files
try {
if (areHashFilesEqual(localHashFile, remoteHashFile, location)) {
// hashes are equal, so cached resource is the latest
// return cached resource
return HashState.HASH_MATCH;
}
// hashes are not equal
return HashState.HASH_MISMATCH;
} finally {
// delete the downloaded temporary hash
if (!remoteHashFile.delete()) {
remoteHashFile.deleteOnExit();
}
}
} | java | private HashState hashCompare(String location, File resource)
throws ResourceDownloadError {
String tmpPath = getSystemConfiguration().getCacheDirectory()
.getAbsolutePath();
String remoteHashLocation = location + SHA256_EXTENSION;
String tempHashPath = asPath(
ResourceType.TMP_FILE.getResourceFolderName(),
encodeLocation(location),
CacheLookupService.DEFAULT_RESOURCE_FILE_NAME
+ SHA256_EXTENSION);
// download resource hash
File remoteHashFile = null;
try {
remoteHashFile = resolveResource(remoteHashLocation, tmpPath,
tempHashPath);
} catch (ResourceDownloadError e) {
return HashState.MISSING_REMOTE_HASH;
}
String absPath = resource.getAbsolutePath();
File localHashFile = new File(absPath + SHA256_EXTENSION);
if (!localHashFile.exists() || !localHashFile.canRead()) {
localHashFile = createLocalHash(resource, location);
}
// compare hash files
try {
if (areHashFilesEqual(localHashFile, remoteHashFile, location)) {
// hashes are equal, so cached resource is the latest
// return cached resource
return HashState.HASH_MATCH;
}
// hashes are not equal
return HashState.HASH_MISMATCH;
} finally {
// delete the downloaded temporary hash
if (!remoteHashFile.delete()) {
remoteHashFile.deleteOnExit();
}
}
} | [
"private",
"HashState",
"hashCompare",
"(",
"String",
"location",
",",
"File",
"resource",
")",
"throws",
"ResourceDownloadError",
"{",
"String",
"tmpPath",
"=",
"getSystemConfiguration",
"(",
")",
".",
"getCacheDirectory",
"(",
")",
".",
"getAbsolutePath",
"(",
"... | Compare hashes of the remote resource to the local resource. The
comparison can result in the following:
<ul>
<li>If the resource's remote hash does not exist then return
{@link HashState#MISSING_REMOTE_HASH}.</li>
<li>If the resource's remote hash matches the local resource's hash then
return {@link HashState#HASH_MATCH}</li>
<li>If the resource's remote hash does not match the local resource's
hash then return {@link HashState#HASH_MISMATCH}.</li>
</ul>
@param location {@link String}, the remote resource location
@param resource {@link File}, the resource's local copy in the cache
@return {@link HashState} the state of the hash comparison which is
useful for deciding how to deal further with the resource
@throws IOException Thrown if there was an IO error in handling hash
files | [
"Compare",
"hashes",
"of",
"the",
"remote",
"resource",
"to",
"the",
"local",
"resource",
".",
"The",
"comparison",
"can",
"result",
"in",
"the",
"following",
":",
"<ul",
">",
"<li",
">",
"If",
"the",
"resource",
"s",
"remote",
"hash",
"does",
"not",
"ex... | train | https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.core/src/main/java/org/openbel/framework/core/df/cache/DefaultCacheableResourceService.java#L140-L185 |
guardtime/ksi-java-sdk | ksi-common/src/main/java/com/guardtime/ksi/util/Base16.java | Base16.encodeWithColons | public static String encodeWithColons(byte[] in) {
"""
Encodes the given bytes into a base-16 string, inserting colons after
every 2 characters of output.
@param in
the bytes to encode.
@return The formatted base-16 string, or null if {@code in} is null.
"""
if (in == null) {
return null;
}
return encodeWithColons(in, 0, in.length);
} | java | public static String encodeWithColons(byte[] in) {
if (in == null) {
return null;
}
return encodeWithColons(in, 0, in.length);
} | [
"public",
"static",
"String",
"encodeWithColons",
"(",
"byte",
"[",
"]",
"in",
")",
"{",
"if",
"(",
"in",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"encodeWithColons",
"(",
"in",
",",
"0",
",",
"in",
".",
"length",
")",
";",
"}"... | Encodes the given bytes into a base-16 string, inserting colons after
every 2 characters of output.
@param in
the bytes to encode.
@return The formatted base-16 string, or null if {@code in} is null. | [
"Encodes",
"the",
"given",
"bytes",
"into",
"a",
"base",
"-",
"16",
"string",
"inserting",
"colons",
"after",
"every",
"2",
"characters",
"of",
"output",
"."
] | train | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-common/src/main/java/com/guardtime/ksi/util/Base16.java#L75-L80 |
box/box-android-sdk | box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFolder.java | BoxApiFolder.getCopyRequest | public BoxRequestsFolder.CopyFolder getCopyRequest(String id, String parentId) {
"""
Gets a request that copies a folder
@param id id of folder to copy
@param parentId id of parent folder to copy folder into
@return request to copy a folder
"""
BoxRequestsFolder.CopyFolder request = new BoxRequestsFolder.CopyFolder(id, parentId, getFolderCopyUrl(id), mSession);
return request;
} | java | public BoxRequestsFolder.CopyFolder getCopyRequest(String id, String parentId) {
BoxRequestsFolder.CopyFolder request = new BoxRequestsFolder.CopyFolder(id, parentId, getFolderCopyUrl(id), mSession);
return request;
} | [
"public",
"BoxRequestsFolder",
".",
"CopyFolder",
"getCopyRequest",
"(",
"String",
"id",
",",
"String",
"parentId",
")",
"{",
"BoxRequestsFolder",
".",
"CopyFolder",
"request",
"=",
"new",
"BoxRequestsFolder",
".",
"CopyFolder",
"(",
"id",
",",
"parentId",
",",
... | Gets a request that copies a folder
@param id id of folder to copy
@param parentId id of parent folder to copy folder into
@return request to copy a folder | [
"Gets",
"a",
"request",
"that",
"copies",
"a",
"folder"
] | train | https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFolder.java#L170-L173 |
JOML-CI/JOML | src/org/joml/Matrix4f.java | Matrix4f.translationRotateScale | public Matrix4f translationRotateScale(float tx, float ty, float tz,
float qx, float qy, float qz, float qw,
float scale) {
"""
Set <code>this</code> matrix to <code>T * R * S</code>, where <code>T</code> is a translation by the given <code>(tx, ty, tz)</code>,
<code>R</code> is a rotation transformation specified by the quaternion <code>(qx, qy, qz, qw)</code>, and <code>S</code> is a scaling transformation
which scales all three axes by <code>scale</code>.
<p>
When transforming a vector by the resulting matrix the scaling transformation will be applied first, then the rotation and
at last the translation.
<p>
When used with a right-handed coordinate system, the produced rotation will rotate a vector
counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin.
When used with a left-handed coordinate system, the rotation is clockwise.
<p>
This method is equivalent to calling: <code>translation(tx, ty, tz).rotate(quat).scale(scale)</code>
@see #translation(float, float, float)
@see #rotate(Quaternionfc)
@see #scale(float)
@param tx
the number of units by which to translate the x-component
@param ty
the number of units by which to translate the y-component
@param tz
the number of units by which to translate the z-component
@param qx
the x-coordinate of the vector part of the quaternion
@param qy
the y-coordinate of the vector part of the quaternion
@param qz
the z-coordinate of the vector part of the quaternion
@param qw
the scalar part of the quaternion
@param scale
the scaling factor for all three axes
@return this
"""
return translationRotateScale(tx, ty, tz, qx, qy, qz, qw, scale, scale, scale);
} | java | public Matrix4f translationRotateScale(float tx, float ty, float tz,
float qx, float qy, float qz, float qw,
float scale) {
return translationRotateScale(tx, ty, tz, qx, qy, qz, qw, scale, scale, scale);
} | [
"public",
"Matrix4f",
"translationRotateScale",
"(",
"float",
"tx",
",",
"float",
"ty",
",",
"float",
"tz",
",",
"float",
"qx",
",",
"float",
"qy",
",",
"float",
"qz",
",",
"float",
"qw",
",",
"float",
"scale",
")",
"{",
"return",
"translationRotateScale",... | Set <code>this</code> matrix to <code>T * R * S</code>, where <code>T</code> is a translation by the given <code>(tx, ty, tz)</code>,
<code>R</code> is a rotation transformation specified by the quaternion <code>(qx, qy, qz, qw)</code>, and <code>S</code> is a scaling transformation
which scales all three axes by <code>scale</code>.
<p>
When transforming a vector by the resulting matrix the scaling transformation will be applied first, then the rotation and
at last the translation.
<p>
When used with a right-handed coordinate system, the produced rotation will rotate a vector
counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin.
When used with a left-handed coordinate system, the rotation is clockwise.
<p>
This method is equivalent to calling: <code>translation(tx, ty, tz).rotate(quat).scale(scale)</code>
@see #translation(float, float, float)
@see #rotate(Quaternionfc)
@see #scale(float)
@param tx
the number of units by which to translate the x-component
@param ty
the number of units by which to translate the y-component
@param tz
the number of units by which to translate the z-component
@param qx
the x-coordinate of the vector part of the quaternion
@param qy
the y-coordinate of the vector part of the quaternion
@param qz
the z-coordinate of the vector part of the quaternion
@param qw
the scalar part of the quaternion
@param scale
the scaling factor for all three axes
@return this | [
"Set",
"<code",
">",
"this<",
"/",
"code",
">",
"matrix",
"to",
"<code",
">",
"T",
"*",
"R",
"*",
"S<",
"/",
"code",
">",
"where",
"<code",
">",
"T<",
"/",
"code",
">",
"is",
"a",
"translation",
"by",
"the",
"given",
"<code",
">",
"(",
"tx",
"t... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L4107-L4111 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java | MutateInBuilder.arrayInsert | public <T> MutateInBuilder arrayInsert(String path, T value) {
"""
Insert into an existing array at a specific position
(denoted in the path, eg. "sub.array[2]").
@param path the path (including array position) where to insert the value.
@param value the value to insert in the array.
"""
asyncBuilder.arrayInsert(path, value);
return this;
} | java | public <T> MutateInBuilder arrayInsert(String path, T value) {
asyncBuilder.arrayInsert(path, value);
return this;
} | [
"public",
"<",
"T",
">",
"MutateInBuilder",
"arrayInsert",
"(",
"String",
"path",
",",
"T",
"value",
")",
"{",
"asyncBuilder",
".",
"arrayInsert",
"(",
"path",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Insert into an existing array at a specific position
(denoted in the path, eg. "sub.array[2]").
@param path the path (including array position) where to insert the value.
@param value the value to insert in the array. | [
"Insert",
"into",
"an",
"existing",
"array",
"at",
"a",
"specific",
"position",
"(",
"denoted",
"in",
"the",
"path",
"eg",
".",
"sub",
".",
"array",
"[",
"2",
"]",
")",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java#L911-L914 |
carewebframework/carewebframework-core | org.carewebframework.shell/src/main/java/org/carewebframework/shell/layout/LayoutUtil.java | LayoutUtil.copyAttributes | public static void copyAttributes(Map<String, String> source, Element dest) {
"""
Copy attributes from a map to a DOM node.
@param source Source map.
@param dest DOM node.
"""
for (Entry<String, String> entry : source.entrySet()) {
dest.setAttribute(entry.getKey(), entry.getValue());
}
} | java | public static void copyAttributes(Map<String, String> source, Element dest) {
for (Entry<String, String> entry : source.entrySet()) {
dest.setAttribute(entry.getKey(), entry.getValue());
}
} | [
"public",
"static",
"void",
"copyAttributes",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"source",
",",
"Element",
"dest",
")",
"{",
"for",
"(",
"Entry",
"<",
"String",
",",
"String",
">",
"entry",
":",
"source",
".",
"entrySet",
"(",
")",
")",
"... | Copy attributes from a map to a DOM node.
@param source Source map.
@param dest DOM node. | [
"Copy",
"attributes",
"from",
"a",
"map",
"to",
"a",
"DOM",
"node",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/layout/LayoutUtil.java#L164-L168 |
google/closure-templates | java/src/com/google/template/soy/pysrc/restricted/PyExprUtils.java | PyExprUtils.genPyNotNullCheck | public static PyExpr genPyNotNullCheck(PyExpr pyExpr) {
"""
Generates a Python not null (None) check expression for the given {@link PyExpr}.
"""
ImmutableList<PyExpr> exprs = ImmutableList.of(pyExpr, new PyExpr("None", Integer.MAX_VALUE));
// Note: is/is not is Python's identity comparison. It's used for None checks for performance.
String conditionalExpr = genExprWithNewToken(Operator.NOT_EQUAL, exprs, "is not");
return new PyExpr(conditionalExpr, PyExprUtils.pyPrecedenceForOperator(Operator.NOT_EQUAL));
} | java | public static PyExpr genPyNotNullCheck(PyExpr pyExpr) {
ImmutableList<PyExpr> exprs = ImmutableList.of(pyExpr, new PyExpr("None", Integer.MAX_VALUE));
// Note: is/is not is Python's identity comparison. It's used for None checks for performance.
String conditionalExpr = genExprWithNewToken(Operator.NOT_EQUAL, exprs, "is not");
return new PyExpr(conditionalExpr, PyExprUtils.pyPrecedenceForOperator(Operator.NOT_EQUAL));
} | [
"public",
"static",
"PyExpr",
"genPyNotNullCheck",
"(",
"PyExpr",
"pyExpr",
")",
"{",
"ImmutableList",
"<",
"PyExpr",
">",
"exprs",
"=",
"ImmutableList",
".",
"of",
"(",
"pyExpr",
",",
"new",
"PyExpr",
"(",
"\"None\"",
",",
"Integer",
".",
"MAX_VALUE",
")",
... | Generates a Python not null (None) check expression for the given {@link PyExpr}. | [
"Generates",
"a",
"Python",
"not",
"null",
"(",
"None",
")",
"check",
"expression",
"for",
"the",
"given",
"{"
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/restricted/PyExprUtils.java#L129-L134 |
sebastiangraf/treetank | interfacemodules/filelistener/src/main/java/org/treetank/filelistener/file/Filelistener.java | Filelistener.addFilelistener | public static boolean addFilelistener(String pResourcename, String pListenerPath)
throws FileNotFoundException, IOException, ClassNotFoundException {
"""
Add a new filelistener to the system.
@param pResourcename
@param pListenerPath
@return return true if there has been a success.
@throws FileNotFoundException
@throws IOException
@throws ClassNotFoundException
"""
mFilelistenerToPaths = new HashMap<String, String>();
File listenerFilePaths = new File(StorageManager.ROOT_PATH + File.separator + "mapping.data");
getFileListenersFromSystem(listenerFilePaths);
mFilelistenerToPaths.put(pResourcename, pListenerPath);
ByteArrayDataOutput output = ByteStreams.newDataOutput();
for (Entry<String, String> e : mFilelistenerToPaths.entrySet()) {
output.write((e.getKey() + "\n").getBytes());
output.write((e.getValue() + "\n").getBytes());
}
java.nio.file.Files.write(listenerFilePaths.toPath(), output.toByteArray(),
StandardOpenOption.TRUNCATE_EXISTING);
return true;
} | java | public static boolean addFilelistener(String pResourcename, String pListenerPath)
throws FileNotFoundException, IOException, ClassNotFoundException {
mFilelistenerToPaths = new HashMap<String, String>();
File listenerFilePaths = new File(StorageManager.ROOT_PATH + File.separator + "mapping.data");
getFileListenersFromSystem(listenerFilePaths);
mFilelistenerToPaths.put(pResourcename, pListenerPath);
ByteArrayDataOutput output = ByteStreams.newDataOutput();
for (Entry<String, String> e : mFilelistenerToPaths.entrySet()) {
output.write((e.getKey() + "\n").getBytes());
output.write((e.getValue() + "\n").getBytes());
}
java.nio.file.Files.write(listenerFilePaths.toPath(), output.toByteArray(),
StandardOpenOption.TRUNCATE_EXISTING);
return true;
} | [
"public",
"static",
"boolean",
"addFilelistener",
"(",
"String",
"pResourcename",
",",
"String",
"pListenerPath",
")",
"throws",
"FileNotFoundException",
",",
"IOException",
",",
"ClassNotFoundException",
"{",
"mFilelistenerToPaths",
"=",
"new",
"HashMap",
"<",
"String"... | Add a new filelistener to the system.
@param pResourcename
@param pListenerPath
@return return true if there has been a success.
@throws FileNotFoundException
@throws IOException
@throws ClassNotFoundException | [
"Add",
"a",
"new",
"filelistener",
"to",
"the",
"system",
"."
] | train | https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/filelistener/src/main/java/org/treetank/filelistener/file/Filelistener.java#L487-L507 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/color/ColorYuv.java | ColorYuv.rgbToYCbCr | public static void rgbToYCbCr( int r , int g , int b , byte yuv[] ) {
"""
Conversion from RGB to YCbCr. See [Jack07].
@param r Red [0 to 255]
@param g Green [0 to 255]
@param b Blue [0 to 255]
"""
// multiply coefficients in book by 1024, which is 2^10
yuv[0] = (byte)((( 187*r + 629*g + 63*b ) >> 10) + 16);
yuv[1] = (byte)(((-103*r - 346*g + 450*b) >> 10) + 128);
yuv[2] = (byte)((( 450*r - 409*g - 41*b ) >> 10) + 128);
} | java | public static void rgbToYCbCr( int r , int g , int b , byte yuv[] ) {
// multiply coefficients in book by 1024, which is 2^10
yuv[0] = (byte)((( 187*r + 629*g + 63*b ) >> 10) + 16);
yuv[1] = (byte)(((-103*r - 346*g + 450*b) >> 10) + 128);
yuv[2] = (byte)((( 450*r - 409*g - 41*b ) >> 10) + 128);
} | [
"public",
"static",
"void",
"rgbToYCbCr",
"(",
"int",
"r",
",",
"int",
"g",
",",
"int",
"b",
",",
"byte",
"yuv",
"[",
"]",
")",
"{",
"// multiply coefficients in book by 1024, which is 2^10",
"yuv",
"[",
"0",
"]",
"=",
"(",
"byte",
")",
"(",
"(",
"(",
... | Conversion from RGB to YCbCr. See [Jack07].
@param r Red [0 to 255]
@param g Green [0 to 255]
@param b Blue [0 to 255] | [
"Conversion",
"from",
"RGB",
"to",
"YCbCr",
".",
"See",
"[",
"Jack07",
"]",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/color/ColorYuv.java#L104-L109 |
whitfin/siphash-java | src/main/java/io/whitfin/siphash/SipHasher.java | SipHasher.bytesToLong | static long bytesToLong(byte[] bytes, int offset) {
"""
Converts a chunk of 8 bytes to a number in little endian.
Accepts an offset to determine where the chunk begins.
@param bytes
the byte array containing our bytes to convert.
@param offset
the index to start at when chunking bytes.
@return
a long representation, in little endian.
"""
long m = 0;
for (int i = 0; i < 8; i++) {
m |= ((((long) bytes[i + offset]) & 0xff) << (8 * i));
}
return m;
} | java | static long bytesToLong(byte[] bytes, int offset) {
long m = 0;
for (int i = 0; i < 8; i++) {
m |= ((((long) bytes[i + offset]) & 0xff) << (8 * i));
}
return m;
} | [
"static",
"long",
"bytesToLong",
"(",
"byte",
"[",
"]",
"bytes",
",",
"int",
"offset",
")",
"{",
"long",
"m",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"8",
";",
"i",
"++",
")",
"{",
"m",
"|=",
"(",
"(",
"(",
"(",
"l... | Converts a chunk of 8 bytes to a number in little endian.
Accepts an offset to determine where the chunk begins.
@param bytes
the byte array containing our bytes to convert.
@param offset
the index to start at when chunking bytes.
@return
a long representation, in little endian. | [
"Converts",
"a",
"chunk",
"of",
"8",
"bytes",
"to",
"a",
"number",
"in",
"little",
"endian",
"."
] | train | https://github.com/whitfin/siphash-java/blob/0744d68238bf6d0258154a8152bf2f4537b3cbb8/src/main/java/io/whitfin/siphash/SipHasher.java#L189-L195 |
AzureAD/azure-activedirectory-library-for-java | src/samples/web-app-samples-for-adal4j/src/main/java/com/microsoft/aad/adal4jsample/HttpClientHelper.java | HttpClientHelper.processResponse | public static JSONObject processResponse(int responseCode, String errorCode, String errorMsg) throws JSONException {
"""
for bad response, whose responseCode is not 200 level
@param responseCode
@param errorCode
@param errorMsg
@return
@throws JSONException
"""
JSONObject response = new JSONObject();
response.put("responseCode", responseCode);
response.put("errorCode", errorCode);
response.put("errorMsg", errorMsg);
return response;
} | java | public static JSONObject processResponse(int responseCode, String errorCode, String errorMsg) throws JSONException {
JSONObject response = new JSONObject();
response.put("responseCode", responseCode);
response.put("errorCode", errorCode);
response.put("errorMsg", errorMsg);
return response;
} | [
"public",
"static",
"JSONObject",
"processResponse",
"(",
"int",
"responseCode",
",",
"String",
"errorCode",
",",
"String",
"errorMsg",
")",
"throws",
"JSONException",
"{",
"JSONObject",
"response",
"=",
"new",
"JSONObject",
"(",
")",
";",
"response",
".",
"put"... | for bad response, whose responseCode is not 200 level
@param responseCode
@param errorCode
@param errorMsg
@return
@throws JSONException | [
"for",
"bad",
"response",
"whose",
"responseCode",
"is",
"not",
"200",
"level"
] | train | https://github.com/AzureAD/azure-activedirectory-library-for-java/blob/7f0004fee6faee5818e75623113993a267ceb1c4/src/samples/web-app-samples-for-adal4j/src/main/java/com/microsoft/aad/adal4jsample/HttpClientHelper.java#L115-L122 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/AssertKripton.java | AssertKripton.assertTrueOrUnknownClassInJQLException | public static void assertTrueOrUnknownClassInJQLException(boolean expression, SQLiteModelMethod method,
String className) {
"""
Assert true or unknown class in JQL exception.
@param expression
the expression
@param method
the method
@param className
the class name
"""
if (!expression) {
throw (new UnknownClassInJQLException(method, className));
}
} | java | public static void assertTrueOrUnknownClassInJQLException(boolean expression, SQLiteModelMethod method,
String className) {
if (!expression) {
throw (new UnknownClassInJQLException(method, className));
}
} | [
"public",
"static",
"void",
"assertTrueOrUnknownClassInJQLException",
"(",
"boolean",
"expression",
",",
"SQLiteModelMethod",
"method",
",",
"String",
"className",
")",
"{",
"if",
"(",
"!",
"expression",
")",
"{",
"throw",
"(",
"new",
"UnknownClassInJQLException",
"... | Assert true or unknown class in JQL exception.
@param expression
the expression
@param method
the method
@param className
the class name | [
"Assert",
"true",
"or",
"unknown",
"class",
"in",
"JQL",
"exception",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/AssertKripton.java#L275-L280 |
apache/flink | flink-queryable-state/flink-queryable-state-client-java/src/main/java/org/apache/flink/queryablestate/client/QueryableStateClient.java | QueryableStateClient.getKvState | @PublicEvolving
public <K, S extends State, V> CompletableFuture<S> getKvState(
final JobID jobId,
final String queryableStateName,
final K key,
final TypeHint<K> keyTypeHint,
final StateDescriptor<S, V> stateDescriptor) {
"""
Returns a future holding the request result.
@param jobId JobID of the job the queryable state belongs to.
@param queryableStateName Name under which the state is queryable.
@param key The key we are interested in.
@param keyTypeHint A {@link TypeHint} used to extract the type of the key.
@param stateDescriptor The {@link StateDescriptor} of the state we want to query.
@return Future holding the immutable {@link State} object containing the result.
"""
Preconditions.checkNotNull(keyTypeHint);
TypeInformation<K> keyTypeInfo = keyTypeHint.getTypeInfo();
return getKvState(jobId, queryableStateName, key, keyTypeInfo, stateDescriptor);
} | java | @PublicEvolving
public <K, S extends State, V> CompletableFuture<S> getKvState(
final JobID jobId,
final String queryableStateName,
final K key,
final TypeHint<K> keyTypeHint,
final StateDescriptor<S, V> stateDescriptor) {
Preconditions.checkNotNull(keyTypeHint);
TypeInformation<K> keyTypeInfo = keyTypeHint.getTypeInfo();
return getKvState(jobId, queryableStateName, key, keyTypeInfo, stateDescriptor);
} | [
"@",
"PublicEvolving",
"public",
"<",
"K",
",",
"S",
"extends",
"State",
",",
"V",
">",
"CompletableFuture",
"<",
"S",
">",
"getKvState",
"(",
"final",
"JobID",
"jobId",
",",
"final",
"String",
"queryableStateName",
",",
"final",
"K",
"key",
",",
"final",
... | Returns a future holding the request result.
@param jobId JobID of the job the queryable state belongs to.
@param queryableStateName Name under which the state is queryable.
@param key The key we are interested in.
@param keyTypeHint A {@link TypeHint} used to extract the type of the key.
@param stateDescriptor The {@link StateDescriptor} of the state we want to query.
@return Future holding the immutable {@link State} object containing the result. | [
"Returns",
"a",
"future",
"holding",
"the",
"request",
"result",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-queryable-state/flink-queryable-state-client-java/src/main/java/org/apache/flink/queryablestate/client/QueryableStateClient.java#L196-L208 |
moparisthebest/beehive | beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/internal/DomUtils.java | DomUtils.getChildElementText | static String getChildElementText(Element parent, String name) {
"""
<p>Returns the text value of a child element. Returns
<code>null</code> if there is no child element found.</p>
@param parent parent element
@param name name of the child element
@return text value
"""
// Get children
List list = DomUtils.getChildElementsByName(parent, name);
if (list.size() == 1) {
Element child = (Element) list.get(0);
StringBuffer buf = new StringBuffer();
NodeList children = child.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node node = children.item(i);
if (node.getNodeType() == Node.TEXT_NODE ||
node.getNodeType() == Node.CDATA_SECTION_NODE) {
Text text = (Text) node;
buf.append(text.getData().trim());
}
}
return buf.toString();
} else {
return null;
}
} | java | static String getChildElementText(Element parent, String name) {
// Get children
List list = DomUtils.getChildElementsByName(parent, name);
if (list.size() == 1) {
Element child = (Element) list.get(0);
StringBuffer buf = new StringBuffer();
NodeList children = child.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node node = children.item(i);
if (node.getNodeType() == Node.TEXT_NODE ||
node.getNodeType() == Node.CDATA_SECTION_NODE) {
Text text = (Text) node;
buf.append(text.getData().trim());
}
}
return buf.toString();
} else {
return null;
}
} | [
"static",
"String",
"getChildElementText",
"(",
"Element",
"parent",
",",
"String",
"name",
")",
"{",
"// Get children",
"List",
"list",
"=",
"DomUtils",
".",
"getChildElementsByName",
"(",
"parent",
",",
"name",
")",
";",
"if",
"(",
"list",
".",
"size",
"("... | <p>Returns the text value of a child element. Returns
<code>null</code> if there is no child element found.</p>
@param parent parent element
@param name name of the child element
@return text value | [
"<p",
">",
"Returns",
"the",
"text",
"value",
"of",
"a",
"child",
"element",
".",
"Returns",
"<code",
">",
"null<",
"/",
"code",
">",
"if",
"there",
"is",
"no",
"child",
"element",
"found",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/internal/DomUtils.java#L94-L117 |
liferay/com-liferay-commerce | commerce-discount-service/src/main/java/com/liferay/commerce/discount/service/persistence/impl/CommerceDiscountPersistenceImpl.java | CommerceDiscountPersistenceImpl.findByUUID_G | @Override
public CommerceDiscount findByUUID_G(String uuid, long groupId)
throws NoSuchDiscountException {
"""
Returns the commerce discount where uuid = ? and groupId = ? or throws a {@link NoSuchDiscountException} if it could not be found.
@param uuid the uuid
@param groupId the group ID
@return the matching commerce discount
@throws NoSuchDiscountException if a matching commerce discount could not be found
"""
CommerceDiscount commerceDiscount = fetchByUUID_G(uuid, groupId);
if (commerceDiscount == null) {
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(", groupId=");
msg.append(groupId);
msg.append("}");
if (_log.isDebugEnabled()) {
_log.debug(msg.toString());
}
throw new NoSuchDiscountException(msg.toString());
}
return commerceDiscount;
} | java | @Override
public CommerceDiscount findByUUID_G(String uuid, long groupId)
throws NoSuchDiscountException {
CommerceDiscount commerceDiscount = fetchByUUID_G(uuid, groupId);
if (commerceDiscount == null) {
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(", groupId=");
msg.append(groupId);
msg.append("}");
if (_log.isDebugEnabled()) {
_log.debug(msg.toString());
}
throw new NoSuchDiscountException(msg.toString());
}
return commerceDiscount;
} | [
"@",
"Override",
"public",
"CommerceDiscount",
"findByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"throws",
"NoSuchDiscountException",
"{",
"CommerceDiscount",
"commerceDiscount",
"=",
"fetchByUUID_G",
"(",
"uuid",
",",
"groupId",
")",
";",
"if",
... | Returns the commerce discount where uuid = ? and groupId = ? or throws a {@link NoSuchDiscountException} if it could not be found.
@param uuid the uuid
@param groupId the group ID
@return the matching commerce discount
@throws NoSuchDiscountException if a matching commerce discount could not be found | [
"Returns",
"the",
"commerce",
"discount",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"or",
"throws",
"a",
"{",
"@link",
"NoSuchDiscountException",
"}",
"if",
"it",
"could",
"not",
"be",
"found",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-discount-service/src/main/java/com/liferay/commerce/discount/service/persistence/impl/CommerceDiscountPersistenceImpl.java#L670-L696 |
j-a-w-r/jawr-main-repo | jawr-tools/jawr-bundle-processor/src/main/java/net/jawr/web/bundle/processor/renderer/BasicBundleRenderer.java | BasicBundleRenderer.createBundleLink | protected String createBundleLink(String bundleId, String contextPath) {
"""
Creates a link to a bundle in the page.
@param bundleId the bundle id
@param contextPath the context path
@return the link to a bundle in the page
"""
// When debug mode is on and the resource is generated the path must include a parameter
JawrConfig config = bundler.getConfig();
if( config.isDebugModeOn() &&
config.getGeneratorRegistry().isPathGenerated(bundleId)) {
bundleId = PathNormalizer.createGenerationPath(bundleId, config.getGeneratorRegistry(), null);
}
String fullPath = PathNormalizer.joinPaths(config.getServletMapping(), bundleId);
fullPath = PathNormalizer.joinPaths(contextPath,fullPath);
return renderLink(fullPath);
} | java | protected String createBundleLink(String bundleId, String contextPath) {
// When debug mode is on and the resource is generated the path must include a parameter
JawrConfig config = bundler.getConfig();
if( config.isDebugModeOn() &&
config.getGeneratorRegistry().isPathGenerated(bundleId)) {
bundleId = PathNormalizer.createGenerationPath(bundleId, config.getGeneratorRegistry(), null);
}
String fullPath = PathNormalizer.joinPaths(config.getServletMapping(), bundleId);
fullPath = PathNormalizer.joinPaths(contextPath,fullPath);
return renderLink(fullPath);
} | [
"protected",
"String",
"createBundleLink",
"(",
"String",
"bundleId",
",",
"String",
"contextPath",
")",
"{",
"// When debug mode is on and the resource is generated the path must include a parameter",
"JawrConfig",
"config",
"=",
"bundler",
".",
"getConfig",
"(",
")",
";",
... | Creates a link to a bundle in the page.
@param bundleId the bundle id
@param contextPath the context path
@return the link to a bundle in the page | [
"Creates",
"a",
"link",
"to",
"a",
"bundle",
"in",
"the",
"page",
"."
] | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr-tools/jawr-bundle-processor/src/main/java/net/jawr/web/bundle/processor/renderer/BasicBundleRenderer.java#L95-L107 |
casbin/jcasbin | src/main/java/org/casbin/jcasbin/model/Policy.java | Policy.addPolicy | public boolean addPolicy(String sec, String ptype, List<String> rule) {
"""
addPolicy adds a policy rule to the model.
@param sec the section, "p" or "g".
@param ptype the policy type, "p", "p2", .. or "g", "g2", ..
@param rule the policy rule.
@return succeeds or not.
"""
if (!hasPolicy(sec, ptype, rule)) {
model.get(sec).get(ptype).policy.add(rule);
return true;
}
return false;
} | java | public boolean addPolicy(String sec, String ptype, List<String> rule) {
if (!hasPolicy(sec, ptype, rule)) {
model.get(sec).get(ptype).policy.add(rule);
return true;
}
return false;
} | [
"public",
"boolean",
"addPolicy",
"(",
"String",
"sec",
",",
"String",
"ptype",
",",
"List",
"<",
"String",
">",
"rule",
")",
"{",
"if",
"(",
"!",
"hasPolicy",
"(",
"sec",
",",
"ptype",
",",
"rule",
")",
")",
"{",
"model",
".",
"get",
"(",
"sec",
... | addPolicy adds a policy rule to the model.
@param sec the section, "p" or "g".
@param ptype the policy type, "p", "p2", .. or "g", "g2", ..
@param rule the policy rule.
@return succeeds or not. | [
"addPolicy",
"adds",
"a",
"policy",
"rule",
"to",
"the",
"model",
"."
] | train | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/model/Policy.java#L147-L153 |
lessthanoptimal/BoofCV | main/boofcv-sfm/src/main/java/boofcv/alg/sfm/d3/direct/VisOdomDirectColorDepth.java | VisOdomDirectColorDepth.setKeyFrame | void setKeyFrame(Planar<I> input, ImagePixelTo3D pixelTo3D) {
"""
Set's the keyframe. This is the image which motion is estimated relative to. The 3D location of points in
the keyframe must be known.
@param input Image which is to be used as the key frame
@param pixelTo3D Used to compute 3D points from pixels in key frame
"""
InputSanityCheck.checkSameShape(derivX,input);
wrapI.wrap(input);
keypixels.reset();
for (int y = 0; y < input.height; y++) {
for (int x = 0; x < input.width; x++) {
// See if there's a valid 3D point at this location
if( !pixelTo3D.process(x,y) ) {
continue;
}
float P_x = (float)pixelTo3D.getX();
float P_y = (float)pixelTo3D.getY();
float P_z = (float)pixelTo3D.getZ();
float P_w = (float)pixelTo3D.getW();
// skip point if it's at infinity or has a negative value
if( P_w <= 0 )
continue;
// save the results
Pixel p = keypixels.grow();
p.valid = true;
wrapI.get(x,y,p.bands);
p.x = x;
p.y = y;
p.p3.set(P_x/P_w,P_y/P_w,P_z/P_w);
}
}
} | java | void setKeyFrame(Planar<I> input, ImagePixelTo3D pixelTo3D) {
InputSanityCheck.checkSameShape(derivX,input);
wrapI.wrap(input);
keypixels.reset();
for (int y = 0; y < input.height; y++) {
for (int x = 0; x < input.width; x++) {
// See if there's a valid 3D point at this location
if( !pixelTo3D.process(x,y) ) {
continue;
}
float P_x = (float)pixelTo3D.getX();
float P_y = (float)pixelTo3D.getY();
float P_z = (float)pixelTo3D.getZ();
float P_w = (float)pixelTo3D.getW();
// skip point if it's at infinity or has a negative value
if( P_w <= 0 )
continue;
// save the results
Pixel p = keypixels.grow();
p.valid = true;
wrapI.get(x,y,p.bands);
p.x = x;
p.y = y;
p.p3.set(P_x/P_w,P_y/P_w,P_z/P_w);
}
}
} | [
"void",
"setKeyFrame",
"(",
"Planar",
"<",
"I",
">",
"input",
",",
"ImagePixelTo3D",
"pixelTo3D",
")",
"{",
"InputSanityCheck",
".",
"checkSameShape",
"(",
"derivX",
",",
"input",
")",
";",
"wrapI",
".",
"wrap",
"(",
"input",
")",
";",
"keypixels",
".",
... | Set's the keyframe. This is the image which motion is estimated relative to. The 3D location of points in
the keyframe must be known.
@param input Image which is to be used as the key frame
@param pixelTo3D Used to compute 3D points from pixels in key frame | [
"Set",
"s",
"the",
"keyframe",
".",
"This",
"is",
"the",
"image",
"which",
"motion",
"is",
"estimated",
"relative",
"to",
".",
"The",
"3D",
"location",
"of",
"points",
"in",
"the",
"keyframe",
"must",
"be",
"known",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-sfm/src/main/java/boofcv/alg/sfm/d3/direct/VisOdomDirectColorDepth.java#L192-L223 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/PdfContentByte.java | PdfContentByte.setAction | public void setAction(PdfAction action, float llx, float lly, float urx, float ury) {
"""
Implements an action in an area.
@param action the <CODE>PdfAction</CODE>
@param llx the lower left x corner of the activation area
@param lly the lower left y corner of the activation area
@param urx the upper right x corner of the activation area
@param ury the upper right y corner of the activation area
"""
pdf.setAction(action, llx, lly, urx, ury);
} | java | public void setAction(PdfAction action, float llx, float lly, float urx, float ury) {
pdf.setAction(action, llx, lly, urx, ury);
} | [
"public",
"void",
"setAction",
"(",
"PdfAction",
"action",
",",
"float",
"llx",
",",
"float",
"lly",
",",
"float",
"urx",
",",
"float",
"ury",
")",
"{",
"pdf",
".",
"setAction",
"(",
"action",
",",
"llx",
",",
"lly",
",",
"urx",
",",
"ury",
")",
";... | Implements an action in an area.
@param action the <CODE>PdfAction</CODE>
@param llx the lower left x corner of the activation area
@param lly the lower left y corner of the activation area
@param urx the upper right x corner of the activation area
@param ury the upper right y corner of the activation area | [
"Implements",
"an",
"action",
"in",
"an",
"area",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfContentByte.java#L2616-L2618 |
opsmatters/newrelic-api | src/main/java/com/opsmatters/newrelic/api/httpclient/GsonMessageBodyHandler.java | GsonMessageBodyHandler.writeTo | @Override
public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException {
"""
Write a type to a HTTP message.
@param object The instance to write
@param type The class of instance that is to be written
@param genericType The type of instance to be written
@param annotations An array of the annotations attached to the message entity instance
@param mediaType The media type of the HTTP entity
@param httpHeaders A mutable map of the HTTP message headers
@param entityStream the OutputStream for the HTTP entity
"""
OutputStreamWriter outputStreamWriter = null;
try
{
outputStreamWriter = new OutputStreamWriter(entityStream, CHARSET);
Type jsonType = getAppropriateType(type, genericType);
String json = getGson().toJson(object, jsonType);
if(logger.isLoggable(Level.FINE))
logger.fine("Outgoing JSON Entity: "+json);
getGson().toJson(object, jsonType, outputStreamWriter);
}
finally
{
if(outputStreamWriter != null)
outputStreamWriter.close();
}
} | java | @Override
public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException
{
OutputStreamWriter outputStreamWriter = null;
try
{
outputStreamWriter = new OutputStreamWriter(entityStream, CHARSET);
Type jsonType = getAppropriateType(type, genericType);
String json = getGson().toJson(object, jsonType);
if(logger.isLoggable(Level.FINE))
logger.fine("Outgoing JSON Entity: "+json);
getGson().toJson(object, jsonType, outputStreamWriter);
}
finally
{
if(outputStreamWriter != null)
outputStreamWriter.close();
}
} | [
"@",
"Override",
"public",
"void",
"writeTo",
"(",
"Object",
"object",
",",
"Class",
"<",
"?",
">",
"type",
",",
"Type",
"genericType",
",",
"Annotation",
"[",
"]",
"annotations",
",",
"MediaType",
"mediaType",
",",
"MultivaluedMap",
"<",
"String",
",",
"O... | Write a type to a HTTP message.
@param object The instance to write
@param type The class of instance that is to be written
@param genericType The type of instance to be written
@param annotations An array of the annotations attached to the message entity instance
@param mediaType The media type of the HTTP entity
@param httpHeaders A mutable map of the HTTP message headers
@param entityStream the OutputStream for the HTTP entity | [
"Write",
"a",
"type",
"to",
"a",
"HTTP",
"message",
"."
] | train | https://github.com/opsmatters/newrelic-api/blob/5bc2ea62ec368db891e4fd5fe3dcdf529d086b5e/src/main/java/com/opsmatters/newrelic/api/httpclient/GsonMessageBodyHandler.java#L325-L346 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/api/jms/impl/MsgDestEncodingUtilsImpl.java | MsgDestEncodingUtilsImpl.getMessageRepresentationFromDest | public final byte[] getMessageRepresentationFromDest(JmsDestination dest, EncodingLevel encodingLevel) throws JMSException {
"""
/*
@see com.ibm.ws.sib.api.jms.MessageDestEncodingUtils#getMessageRepresentationFromDest(com.ibm.websphere.sib.api.jms.JmsDestination)
Returns the efficient byte[] representation of the parameter destination
that can be stored in the message for transmission. The boolean parameter
indicates whether a full (normal dest) or partial (reply dest) encoding
should be carried out.
@throws JMSException if
dest is null - generates FFDC
getShortPropertyValue throws it - FFDCs already generated.
an UnsupportedEncodingException is generated - generates FFDC.
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getMessageRepresentationFromDest", new Object[]{dest, encodingLevel});
boolean isTopic = false;
byte[] encodedDest = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream(); // initial size of 32 is probably OK
if (dest == null) {
// Error case.
JMSException e = (JMSException)JmsErrorUtils.newThrowable(JMSException.class,
"INTERNAL_INVALID_VALUE_CWSIA0361",
new Object[] {"null", "JmsDestination"}, tc);
FFDCFilter.processException(e,"MsgDestEncodingUtilsImpl","getMessageRepresentationFromDest#1", this);
throw e;
}
// If the JmsDestination is a Topic, note it for later use
if (dest instanceof Topic) {
isTopic = true;
}
// This variable is used to obtain a list of all the destination's properties,
// giving us a copy which is safe for us to mess around with.
Map<String,Object> destProps = ((JmsDestinationImpl)dest).getCopyOfProperties();
// Now fiddle around with our copy of the properties, so we get the set we need to encode
manipulateProperties(destProps, isTopic, encodingLevel);
// Encode the basic stuff - Queue/Topic, DeliveryMode, Priority & TTL
encodeBasicProperties(baos, isTopic, destProps);
// Encode the rest of the properties
encodeOtherProperties(baos, destProps);
// Extract the byte array to return
encodedDest = baos.toByteArray();
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getMessageRepresentationFromDest", encodedDest);
return encodedDest;
} | java | public final byte[] getMessageRepresentationFromDest(JmsDestination dest, EncodingLevel encodingLevel) throws JMSException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getMessageRepresentationFromDest", new Object[]{dest, encodingLevel});
boolean isTopic = false;
byte[] encodedDest = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream(); // initial size of 32 is probably OK
if (dest == null) {
// Error case.
JMSException e = (JMSException)JmsErrorUtils.newThrowable(JMSException.class,
"INTERNAL_INVALID_VALUE_CWSIA0361",
new Object[] {"null", "JmsDestination"}, tc);
FFDCFilter.processException(e,"MsgDestEncodingUtilsImpl","getMessageRepresentationFromDest#1", this);
throw e;
}
// If the JmsDestination is a Topic, note it for later use
if (dest instanceof Topic) {
isTopic = true;
}
// This variable is used to obtain a list of all the destination's properties,
// giving us a copy which is safe for us to mess around with.
Map<String,Object> destProps = ((JmsDestinationImpl)dest).getCopyOfProperties();
// Now fiddle around with our copy of the properties, so we get the set we need to encode
manipulateProperties(destProps, isTopic, encodingLevel);
// Encode the basic stuff - Queue/Topic, DeliveryMode, Priority & TTL
encodeBasicProperties(baos, isTopic, destProps);
// Encode the rest of the properties
encodeOtherProperties(baos, destProps);
// Extract the byte array to return
encodedDest = baos.toByteArray();
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getMessageRepresentationFromDest", encodedDest);
return encodedDest;
} | [
"public",
"final",
"byte",
"[",
"]",
"getMessageRepresentationFromDest",
"(",
"JmsDestination",
"dest",
",",
"EncodingLevel",
"encodingLevel",
")",
"throws",
"JMSException",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"... | /*
@see com.ibm.ws.sib.api.jms.MessageDestEncodingUtils#getMessageRepresentationFromDest(com.ibm.websphere.sib.api.jms.JmsDestination)
Returns the efficient byte[] representation of the parameter destination
that can be stored in the message for transmission. The boolean parameter
indicates whether a full (normal dest) or partial (reply dest) encoding
should be carried out.
@throws JMSException if
dest is null - generates FFDC
getShortPropertyValue throws it - FFDCs already generated.
an UnsupportedEncodingException is generated - generates FFDC. | [
"/",
"*",
"@see",
"com",
".",
"ibm",
".",
"ws",
".",
"sib",
".",
"api",
".",
"jms",
".",
"MessageDestEncodingUtils#getMessageRepresentationFromDest",
"(",
"com",
".",
"ibm",
".",
"websphere",
".",
"sib",
".",
"api",
".",
"jms",
".",
"JmsDestination",
")"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/api/jms/impl/MsgDestEncodingUtilsImpl.java#L183-L223 |
duracloud/management-console | account-management-monitor/src/main/java/org/duracloud/account/monitor/duplication/DuplicationMonitor.java | DuplicationMonitor.getStoreManager | private ContentStoreManager getStoreManager(String host)
throws DBNotFoundException {
"""
/*
Create the store manager to connect to this DuraCloud account instance
"""
ContentStoreManager storeManager =
new ContentStoreManagerImpl(host, PORT, CONTEXT);
Credential credential = getRootCredential();
storeManager.login(credential);
return storeManager;
} | java | private ContentStoreManager getStoreManager(String host)
throws DBNotFoundException {
ContentStoreManager storeManager =
new ContentStoreManagerImpl(host, PORT, CONTEXT);
Credential credential = getRootCredential();
storeManager.login(credential);
return storeManager;
} | [
"private",
"ContentStoreManager",
"getStoreManager",
"(",
"String",
"host",
")",
"throws",
"DBNotFoundException",
"{",
"ContentStoreManager",
"storeManager",
"=",
"new",
"ContentStoreManagerImpl",
"(",
"host",
",",
"PORT",
",",
"CONTEXT",
")",
";",
"Credential",
"cred... | /*
Create the store manager to connect to this DuraCloud account instance | [
"/",
"*",
"Create",
"the",
"store",
"manager",
"to",
"connect",
"to",
"this",
"DuraCloud",
"account",
"instance"
] | train | https://github.com/duracloud/management-console/blob/7331015c01f9ac5cc5c0aa8ae9a2a1a77e9f4ac6/account-management-monitor/src/main/java/org/duracloud/account/monitor/duplication/DuplicationMonitor.java#L107-L114 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/ba/Hierarchy.java | Hierarchy.resolveMethodCallTargets | public static Set<JavaClassAndMethod> resolveMethodCallTargets(ReferenceType receiverType,
InvokeInstruction invokeInstruction, ConstantPoolGen cpg) throws ClassNotFoundException {
"""
Resolve possible instance method call targets. Assumes that invokevirtual
and invokeinterface methods may call any subtype of the receiver class.
@param receiverType
type of the receiver object
@param invokeInstruction
the InvokeInstruction
@param cpg
the ConstantPoolGen
@return Set of methods which might be called
@throws ClassNotFoundException
"""
return resolveMethodCallTargets(receiverType, invokeInstruction, cpg, false);
} | java | public static Set<JavaClassAndMethod> resolveMethodCallTargets(ReferenceType receiverType,
InvokeInstruction invokeInstruction, ConstantPoolGen cpg) throws ClassNotFoundException {
return resolveMethodCallTargets(receiverType, invokeInstruction, cpg, false);
} | [
"public",
"static",
"Set",
"<",
"JavaClassAndMethod",
">",
"resolveMethodCallTargets",
"(",
"ReferenceType",
"receiverType",
",",
"InvokeInstruction",
"invokeInstruction",
",",
"ConstantPoolGen",
"cpg",
")",
"throws",
"ClassNotFoundException",
"{",
"return",
"resolveMethodC... | Resolve possible instance method call targets. Assumes that invokevirtual
and invokeinterface methods may call any subtype of the receiver class.
@param receiverType
type of the receiver object
@param invokeInstruction
the InvokeInstruction
@param cpg
the ConstantPoolGen
@return Set of methods which might be called
@throws ClassNotFoundException | [
"Resolve",
"possible",
"instance",
"method",
"call",
"targets",
".",
"Assumes",
"that",
"invokevirtual",
"and",
"invokeinterface",
"methods",
"may",
"call",
"any",
"subtype",
"of",
"the",
"receiver",
"class",
"."
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/Hierarchy.java#L774-L777 |
wuman/JReadability | src/main/java/com/wuman/jreadability/Readability.java | Readability.getElementsByTag | private static Elements getElementsByTag(Element e, String tag) {
"""
Jsoup's Element.getElementsByTag(Element e) includes e itself, which is
different from W3C standards. This utility function is exclusive of the
Element e.
@param e
@param tag
@return
"""
Elements es = e.getElementsByTag(tag);
es.remove(e);
return es;
} | java | private static Elements getElementsByTag(Element e, String tag) {
Elements es = e.getElementsByTag(tag);
es.remove(e);
return es;
} | [
"private",
"static",
"Elements",
"getElementsByTag",
"(",
"Element",
"e",
",",
"String",
"tag",
")",
"{",
"Elements",
"es",
"=",
"e",
".",
"getElementsByTag",
"(",
"tag",
")",
";",
"es",
".",
"remove",
"(",
"e",
")",
";",
"return",
"es",
";",
"}"
] | Jsoup's Element.getElementsByTag(Element e) includes e itself, which is
different from W3C standards. This utility function is exclusive of the
Element e.
@param e
@param tag
@return | [
"Jsoup",
"s",
"Element",
".",
"getElementsByTag",
"(",
"Element",
"e",
")",
"includes",
"e",
"itself",
"which",
"is",
"different",
"from",
"W3C",
"standards",
".",
"This",
"utility",
"function",
"is",
"exclusive",
"of",
"the",
"Element",
"e",
"."
] | train | https://github.com/wuman/JReadability/blob/16c18c42402bd13c6e024c2fd3a86dd28ba53e74/src/main/java/com/wuman/jreadability/Readability.java#L880-L884 |
apereo/cas | support/cas-server-support-saml-idp-web/src/main/java/org/apereo/cas/support/saml/web/idp/profile/artifact/Saml1ArtifactResolutionProfileHandlerController.java | Saml1ArtifactResolutionProfileHandlerController.handlePostRequest | @PostMapping(path = SamlIdPConstants.ENDPOINT_SAML1_SOAP_ARTIFACT_RESOLUTION)
protected void handlePostRequest(final HttpServletResponse response,
final HttpServletRequest request) {
"""
Handle post request.
@param response the response
@param request the request
"""
val ctx = decodeSoapRequest(request);
val artifactMsg = (ArtifactResolve) ctx.getMessage();
try {
val issuer = artifactMsg.getIssuer().getValue();
val service = verifySamlRegisteredService(issuer);
val adaptor = getSamlMetadataFacadeFor(service, artifactMsg);
if (adaptor.isEmpty()) {
throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + issuer);
}
val facade = adaptor.get();
verifyAuthenticationContextSignature(ctx, request, artifactMsg, facade);
val artifactId = artifactMsg.getArtifact().getArtifact();
val ticketId = getSamlProfileHandlerConfigurationContext().getArtifactTicketFactory().createTicketIdFor(artifactId);
val ticket = getSamlProfileHandlerConfigurationContext().getTicketRegistry().getTicket(ticketId, SamlArtifactTicket.class);
val issuerService = getSamlProfileHandlerConfigurationContext().getWebApplicationServiceFactory().createService(issuer);
val casAssertion = buildCasAssertion(ticket.getTicketGrantingTicket().getAuthentication(),
issuerService, service,
CollectionUtils.wrap("artifact", ticket));
getSamlProfileHandlerConfigurationContext().getResponseBuilder().build(artifactMsg, request, response, casAssertion,
service, facade, SAMLConstants.SAML2_ARTIFACT_BINDING_URI, ctx);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
request.setAttribute(SamlIdPConstants.REQUEST_ATTRIBUTE_ERROR, e.getMessage());
getSamlProfileHandlerConfigurationContext().getSamlFaultResponseBuilder().build(artifactMsg, request, response,
null, null, null, SAMLConstants.SAML2_ARTIFACT_BINDING_URI, ctx);
}
} | java | @PostMapping(path = SamlIdPConstants.ENDPOINT_SAML1_SOAP_ARTIFACT_RESOLUTION)
protected void handlePostRequest(final HttpServletResponse response,
final HttpServletRequest request) {
val ctx = decodeSoapRequest(request);
val artifactMsg = (ArtifactResolve) ctx.getMessage();
try {
val issuer = artifactMsg.getIssuer().getValue();
val service = verifySamlRegisteredService(issuer);
val adaptor = getSamlMetadataFacadeFor(service, artifactMsg);
if (adaptor.isEmpty()) {
throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + issuer);
}
val facade = adaptor.get();
verifyAuthenticationContextSignature(ctx, request, artifactMsg, facade);
val artifactId = artifactMsg.getArtifact().getArtifact();
val ticketId = getSamlProfileHandlerConfigurationContext().getArtifactTicketFactory().createTicketIdFor(artifactId);
val ticket = getSamlProfileHandlerConfigurationContext().getTicketRegistry().getTicket(ticketId, SamlArtifactTicket.class);
val issuerService = getSamlProfileHandlerConfigurationContext().getWebApplicationServiceFactory().createService(issuer);
val casAssertion = buildCasAssertion(ticket.getTicketGrantingTicket().getAuthentication(),
issuerService, service,
CollectionUtils.wrap("artifact", ticket));
getSamlProfileHandlerConfigurationContext().getResponseBuilder().build(artifactMsg, request, response, casAssertion,
service, facade, SAMLConstants.SAML2_ARTIFACT_BINDING_URI, ctx);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
request.setAttribute(SamlIdPConstants.REQUEST_ATTRIBUTE_ERROR, e.getMessage());
getSamlProfileHandlerConfigurationContext().getSamlFaultResponseBuilder().build(artifactMsg, request, response,
null, null, null, SAMLConstants.SAML2_ARTIFACT_BINDING_URI, ctx);
}
} | [
"@",
"PostMapping",
"(",
"path",
"=",
"SamlIdPConstants",
".",
"ENDPOINT_SAML1_SOAP_ARTIFACT_RESOLUTION",
")",
"protected",
"void",
"handlePostRequest",
"(",
"final",
"HttpServletResponse",
"response",
",",
"final",
"HttpServletRequest",
"request",
")",
"{",
"val",
"ctx... | Handle post request.
@param response the response
@param request the request | [
"Handle",
"post",
"request",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-saml-idp-web/src/main/java/org/apereo/cas/support/saml/web/idp/profile/artifact/Saml1ArtifactResolutionProfileHandlerController.java#L37-L67 |
btrplace/scheduler | btrpsl/src/main/java/org/btrplace/btrpsl/tree/BtrPlaceTree.java | BtrPlaceTree.ignoreError | public IgnorableOperand ignoreError(Token t, String msg) {
"""
Add an error message to a given error
@param t the token that points to the error
@param msg the error message
@return {@link IgnorableOperand} to indicate to skip the operand
"""
append(t, msg);
return IgnorableOperand.getInstance();
} | java | public IgnorableOperand ignoreError(Token t, String msg) {
append(t, msg);
return IgnorableOperand.getInstance();
} | [
"public",
"IgnorableOperand",
"ignoreError",
"(",
"Token",
"t",
",",
"String",
"msg",
")",
"{",
"append",
"(",
"t",
",",
"msg",
")",
";",
"return",
"IgnorableOperand",
".",
"getInstance",
"(",
")",
";",
"}"
] | Add an error message to a given error
@param t the token that points to the error
@param msg the error message
@return {@link IgnorableOperand} to indicate to skip the operand | [
"Add",
"an",
"error",
"message",
"to",
"a",
"given",
"error"
] | train | https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/btrpsl/src/main/java/org/btrplace/btrpsl/tree/BtrPlaceTree.java#L102-L105 |
kite-sdk/kite | kite-morphlines/kite-morphlines-core/src/main/java/org/kitesdk/morphline/base/Validator.java | Validator.validateEnum | public <T extends Enum<T>> T validateEnum(Config config, String value, Class<T> type, T... choices) {
"""
Validates that an enum of the given type with the given value exists, and that this enum is
contained in the given list of permitted choices; finally returns that enum object.
"""
if (choices.length == 0) {
choices = type.getEnumConstants();
}
Preconditions.checkArgument(choices.length > 0);
try {
T result = Enum.valueOf(type, value);
if (!Arrays.asList(choices).contains(result)) {
throw new IllegalArgumentException();
}
return result;
} catch (IllegalArgumentException e) {
throw new MorphlineCompilationException(
String.format("Invalid choice: '%s' (choose from {%s})",
value,
Joiner.on(",").join(choices)),
config);
}
} | java | public <T extends Enum<T>> T validateEnum(Config config, String value, Class<T> type, T... choices) {
if (choices.length == 0) {
choices = type.getEnumConstants();
}
Preconditions.checkArgument(choices.length > 0);
try {
T result = Enum.valueOf(type, value);
if (!Arrays.asList(choices).contains(result)) {
throw new IllegalArgumentException();
}
return result;
} catch (IllegalArgumentException e) {
throw new MorphlineCompilationException(
String.format("Invalid choice: '%s' (choose from {%s})",
value,
Joiner.on(",").join(choices)),
config);
}
} | [
"public",
"<",
"T",
"extends",
"Enum",
"<",
"T",
">",
">",
"T",
"validateEnum",
"(",
"Config",
"config",
",",
"String",
"value",
",",
"Class",
"<",
"T",
">",
"type",
",",
"T",
"...",
"choices",
")",
"{",
"if",
"(",
"choices",
".",
"length",
"==",
... | Validates that an enum of the given type with the given value exists, and that this enum is
contained in the given list of permitted choices; finally returns that enum object. | [
"Validates",
"that",
"an",
"enum",
"of",
"the",
"given",
"type",
"with",
"the",
"given",
"value",
"exists",
"and",
"that",
"this",
"enum",
"is",
"contained",
"in",
"the",
"given",
"list",
"of",
"permitted",
"choices",
";",
"finally",
"returns",
"that",
"en... | train | https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-morphlines/kite-morphlines-core/src/main/java/org/kitesdk/morphline/base/Validator.java#L50-L68 |
jferard/fastods | fastods/src/main/java/com/github/jferard/fastods/TextBuilder.java | TextBuilder.styledLink | public TextBuilder styledLink(final String text, final TextStyle ts, final URL url) {
"""
Create a styled link in the current paragraph.
@param text the text
@param ts the style
@param url the destination
@return this for fluent style
"""
this.curParagraphBuilder.styledLink(text, ts, url);
return this;
} | java | public TextBuilder styledLink(final String text, final TextStyle ts, final URL url) {
this.curParagraphBuilder.styledLink(text, ts, url);
return this;
} | [
"public",
"TextBuilder",
"styledLink",
"(",
"final",
"String",
"text",
",",
"final",
"TextStyle",
"ts",
",",
"final",
"URL",
"url",
")",
"{",
"this",
".",
"curParagraphBuilder",
".",
"styledLink",
"(",
"text",
",",
"ts",
",",
"url",
")",
";",
"return",
"... | Create a styled link in the current paragraph.
@param text the text
@param ts the style
@param url the destination
@return this for fluent style | [
"Create",
"a",
"styled",
"link",
"in",
"the",
"current",
"paragraph",
"."
] | train | https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/TextBuilder.java#L176-L179 |
cdk/cdk | tool/sdg/src/main/java/org/openscience/cdk/layout/OverlapResolver.java | OverlapResolver.getBondOverlapScore | public double getBondOverlapScore(IAtomContainer ac, Vector overlappingBonds) {
"""
Calculates a score based on the intersection of bonds.
@param ac The Atomcontainer to work on
@param overlappingBonds Description of the Parameter
@return The overlapScore value
"""
overlappingBonds.removeAllElements();
double overlapScore = 0;
IBond bond1 = null;
IBond bond2 = null;
double bondLength = GeometryUtil.getBondLengthAverage(ac);;
double overlapCutoff = bondLength / 2;
for (int f = 0; f < ac.getBondCount(); f++) {
bond1 = ac.getBond(f);
for (int g = f; g < ac.getBondCount(); g++) {
bond2 = ac.getBond(g);
/* bonds must not be connected */
if (!bond1.isConnectedTo(bond2)) {
if (areIntersected(bond1, bond2)) {
overlapScore += overlapCutoff;
overlappingBonds.addElement(new OverlapPair(bond1, bond2));
}
}
}
}
return overlapScore;
} | java | public double getBondOverlapScore(IAtomContainer ac, Vector overlappingBonds) {
overlappingBonds.removeAllElements();
double overlapScore = 0;
IBond bond1 = null;
IBond bond2 = null;
double bondLength = GeometryUtil.getBondLengthAverage(ac);;
double overlapCutoff = bondLength / 2;
for (int f = 0; f < ac.getBondCount(); f++) {
bond1 = ac.getBond(f);
for (int g = f; g < ac.getBondCount(); g++) {
bond2 = ac.getBond(g);
/* bonds must not be connected */
if (!bond1.isConnectedTo(bond2)) {
if (areIntersected(bond1, bond2)) {
overlapScore += overlapCutoff;
overlappingBonds.addElement(new OverlapPair(bond1, bond2));
}
}
}
}
return overlapScore;
} | [
"public",
"double",
"getBondOverlapScore",
"(",
"IAtomContainer",
"ac",
",",
"Vector",
"overlappingBonds",
")",
"{",
"overlappingBonds",
".",
"removeAllElements",
"(",
")",
";",
"double",
"overlapScore",
"=",
"0",
";",
"IBond",
"bond1",
"=",
"null",
";",
"IBond"... | Calculates a score based on the intersection of bonds.
@param ac The Atomcontainer to work on
@param overlappingBonds Description of the Parameter
@return The overlapScore value | [
"Calculates",
"a",
"score",
"based",
"on",
"the",
"intersection",
"of",
"bonds",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/sdg/src/main/java/org/openscience/cdk/layout/OverlapResolver.java#L215-L236 |
mikepenz/FastAdapter | library-core/src/main/java/com/mikepenz/fastadapter/items/AbstractItem.java | AbstractItem.generateView | @Override
public View generateView(Context ctx) {
"""
generates a view by the defined LayoutRes
@param ctx
@return
"""
VH viewHolder = getViewHolder(createView(ctx, null));
//as we already know the type of our ViewHolder cast it to our type
bindView(viewHolder, Collections.EMPTY_LIST);
//return the bound view
return viewHolder.itemView;
} | java | @Override
public View generateView(Context ctx) {
VH viewHolder = getViewHolder(createView(ctx, null));
//as we already know the type of our ViewHolder cast it to our type
bindView(viewHolder, Collections.EMPTY_LIST);
//return the bound view
return viewHolder.itemView;
} | [
"@",
"Override",
"public",
"View",
"generateView",
"(",
"Context",
"ctx",
")",
"{",
"VH",
"viewHolder",
"=",
"getViewHolder",
"(",
"createView",
"(",
"ctx",
",",
"null",
")",
")",
";",
"//as we already know the type of our ViewHolder cast it to our type",
"bindView",
... | generates a view by the defined LayoutRes
@param ctx
@return | [
"generates",
"a",
"view",
"by",
"the",
"defined",
"LayoutRes"
] | train | https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library-core/src/main/java/com/mikepenz/fastadapter/items/AbstractItem.java#L256-L265 |
Impetus/Kundera | src/jpa-engine/core/src/main/java/com/impetus/kundera/query/QueryImpl.java | QueryImpl.setHint | @Override
public Query setHint(String hintName, Object value) {
"""
Sets hint name and value into hints map and returns instance of
{@link Query}.
@param hintName
the hint name
@param value
the value
@return the query
"""
hints.put(hintName, value);
return this;
} | java | @Override
public Query setHint(String hintName, Object value)
{
hints.put(hintName, value);
return this;
} | [
"@",
"Override",
"public",
"Query",
"setHint",
"(",
"String",
"hintName",
",",
"Object",
"value",
")",
"{",
"hints",
".",
"put",
"(",
"hintName",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Sets hint name and value into hints map and returns instance of
{@link Query}.
@param hintName
the hint name
@param value
the value
@return the query | [
"Sets",
"hint",
"name",
"and",
"value",
"into",
"hints",
"map",
"and",
"returns",
"instance",
"of",
"{",
"@link",
"Query",
"}",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/query/QueryImpl.java#L805-L810 |
DiUS/pact-jvm | pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonArray.java | PactDslJsonArray.arrayMinLike | public static PactDslJsonBody arrayMinLike(int minSize, int numberExamples) {
"""
Array with a minimum size where each item must match the following example
@param minSize minimum size
@param numberExamples Number of examples to generate
"""
if (numberExamples < minSize) {
throw new IllegalArgumentException(String.format("Number of example %d is less than the minimum size of %d",
numberExamples, minSize));
}
PactDslJsonArray parent = new PactDslJsonArray("", "", null, true);
parent.setNumberExamples(numberExamples);
parent.matchers.addRule("", parent.matchMin(minSize));
return new PactDslJsonBody(".", "", parent);
} | java | public static PactDslJsonBody arrayMinLike(int minSize, int numberExamples) {
if (numberExamples < minSize) {
throw new IllegalArgumentException(String.format("Number of example %d is less than the minimum size of %d",
numberExamples, minSize));
}
PactDslJsonArray parent = new PactDslJsonArray("", "", null, true);
parent.setNumberExamples(numberExamples);
parent.matchers.addRule("", parent.matchMin(minSize));
return new PactDslJsonBody(".", "", parent);
} | [
"public",
"static",
"PactDslJsonBody",
"arrayMinLike",
"(",
"int",
"minSize",
",",
"int",
"numberExamples",
")",
"{",
"if",
"(",
"numberExamples",
"<",
"minSize",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"String",
".",
"format",
"(",
"\"Number ... | Array with a minimum size where each item must match the following example
@param minSize minimum size
@param numberExamples Number of examples to generate | [
"Array",
"with",
"a",
"minimum",
"size",
"where",
"each",
"item",
"must",
"match",
"the",
"following",
"example"
] | train | https://github.com/DiUS/pact-jvm/blob/2f447e9dd4ac152a6a36b7fcf8962d07de9ef3ef/pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonArray.java#L778-L787 |
landawn/AbacusUtil | src/com/landawn/abacus/util/N.java | N.checkArgument | public static void checkArgument(boolean b, String errorMessageTemplate, double p) {
"""
Ensures the truth of an expression involving one or more parameters to the calling method.
<p>See {@link #checkArgument(boolean, String, Object...)} for details.
"""
if (!b) {
throw new IllegalArgumentException(format(errorMessageTemplate, p));
}
} | java | public static void checkArgument(boolean b, String errorMessageTemplate, double p) {
if (!b) {
throw new IllegalArgumentException(format(errorMessageTemplate, p));
}
} | [
"public",
"static",
"void",
"checkArgument",
"(",
"boolean",
"b",
",",
"String",
"errorMessageTemplate",
",",
"double",
"p",
")",
"{",
"if",
"(",
"!",
"b",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"format",
"(",
"errorMessageTemplate",
",",
... | Ensures the truth of an expression involving one or more parameters to the calling method.
<p>See {@link #checkArgument(boolean, String, Object...)} for details. | [
"Ensures",
"the",
"truth",
"of",
"an",
"expression",
"involving",
"one",
"or",
"more",
"parameters",
"to",
"the",
"calling",
"method",
"."
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/N.java#L5471-L5475 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/vpn/vpnsessionpolicy.java | vpnsessionpolicy.get | public static vpnsessionpolicy get(nitro_service service, String name) throws Exception {
"""
Use this API to fetch vpnsessionpolicy resource of given name .
"""
vpnsessionpolicy obj = new vpnsessionpolicy();
obj.set_name(name);
vpnsessionpolicy response = (vpnsessionpolicy) obj.get_resource(service);
return response;
} | java | public static vpnsessionpolicy get(nitro_service service, String name) throws Exception{
vpnsessionpolicy obj = new vpnsessionpolicy();
obj.set_name(name);
vpnsessionpolicy response = (vpnsessionpolicy) obj.get_resource(service);
return response;
} | [
"public",
"static",
"vpnsessionpolicy",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"name",
")",
"throws",
"Exception",
"{",
"vpnsessionpolicy",
"obj",
"=",
"new",
"vpnsessionpolicy",
"(",
")",
";",
"obj",
".",
"set_name",
"(",
"name",
")",
";",
"... | Use this API to fetch vpnsessionpolicy resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"vpnsessionpolicy",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/vpn/vpnsessionpolicy.java#L324-L329 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/shared/renderkit/html/HtmlLinkRendererBase.java | HtmlLinkRendererBase.getStyle | protected String getStyle(FacesContext facesContext, UIComponent link) {
"""
Can be overwritten by derived classes to overrule the style to be used.
"""
if (link instanceof HtmlCommandLink)
{
return ((HtmlCommandLink)link).getStyle();
}
return (String)link.getAttributes().get(HTML.STYLE_ATTR);
} | java | protected String getStyle(FacesContext facesContext, UIComponent link)
{
if (link instanceof HtmlCommandLink)
{
return ((HtmlCommandLink)link).getStyle();
}
return (String)link.getAttributes().get(HTML.STYLE_ATTR);
} | [
"protected",
"String",
"getStyle",
"(",
"FacesContext",
"facesContext",
",",
"UIComponent",
"link",
")",
"{",
"if",
"(",
"link",
"instanceof",
"HtmlCommandLink",
")",
"{",
"return",
"(",
"(",
"HtmlCommandLink",
")",
"link",
")",
".",
"getStyle",
"(",
")",
";... | Can be overwritten by derived classes to overrule the style to be used. | [
"Can",
"be",
"overwritten",
"by",
"derived",
"classes",
"to",
"overrule",
"the",
"style",
"to",
"be",
"used",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/shared/renderkit/html/HtmlLinkRendererBase.java#L161-L170 |
pryzach/midao | midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/type/TypeHandlerUtils.java | TypeHandlerUtils.convertClob | public static Object convertClob(Connection conn, InputStream input) throws SQLException {
"""
Transfers data from InputStream into sql.Clob
<p/>
Using default locale. If different locale is required see
{@link #convertClob(java.sql.Connection, String)}
@param conn connection for which sql.Clob object would be created
@param input InputStream
@return sql.Clob from InputStream
@throws SQLException
"""
return convertClob(conn, toByteArray(input));
} | java | public static Object convertClob(Connection conn, InputStream input) throws SQLException {
return convertClob(conn, toByteArray(input));
} | [
"public",
"static",
"Object",
"convertClob",
"(",
"Connection",
"conn",
",",
"InputStream",
"input",
")",
"throws",
"SQLException",
"{",
"return",
"convertClob",
"(",
"conn",
",",
"toByteArray",
"(",
"input",
")",
")",
";",
"}"
] | Transfers data from InputStream into sql.Clob
<p/>
Using default locale. If different locale is required see
{@link #convertClob(java.sql.Connection, String)}
@param conn connection for which sql.Clob object would be created
@param input InputStream
@return sql.Clob from InputStream
@throws SQLException | [
"Transfers",
"data",
"from",
"InputStream",
"into",
"sql",
".",
"Clob",
"<p",
"/",
">",
"Using",
"default",
"locale",
".",
"If",
"different",
"locale",
"is",
"required",
"see",
"{",
"@link",
"#convertClob",
"(",
"java",
".",
"sql",
".",
"Connection",
"Stri... | train | https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/type/TypeHandlerUtils.java#L204-L206 |
fcrepo3/fcrepo | fcrepo-server/src/main/java/org/fcrepo/server/journal/readerwriter/multifile/JournalOutputFile.java | JournalOutputFile.createTempFilename | private File createTempFilename(File permanentFile, File journalDirectory) {
"""
The "temporary" filename is the permanent name preceded by an underscore.
"""
String tempFilename = "_" + permanentFile.getName();
File file2 = new File(journalDirectory, tempFilename);
return file2;
} | java | private File createTempFilename(File permanentFile, File journalDirectory) {
String tempFilename = "_" + permanentFile.getName();
File file2 = new File(journalDirectory, tempFilename);
return file2;
} | [
"private",
"File",
"createTempFilename",
"(",
"File",
"permanentFile",
",",
"File",
"journalDirectory",
")",
"{",
"String",
"tempFilename",
"=",
"\"_\"",
"+",
"permanentFile",
".",
"getName",
"(",
")",
";",
"File",
"file2",
"=",
"new",
"File",
"(",
"journalDir... | The "temporary" filename is the permanent name preceded by an underscore. | [
"The",
"temporary",
"filename",
"is",
"the",
"permanent",
"name",
"preceded",
"by",
"an",
"underscore",
"."
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/journal/readerwriter/multifile/JournalOutputFile.java#L131-L135 |
grpc/grpc-java | core/src/main/java/io/grpc/internal/Rescheduler.java | Rescheduler.reschedule | void reschedule(long delay, TimeUnit timeUnit) {
"""
/* must be called from the {@link #serializingExecutor} originally passed in.
"""
long delayNanos = timeUnit.toNanos(delay);
long newRunAtNanos = nanoTime() + delayNanos;
enabled = true;
if (newRunAtNanos - runAtNanos < 0 || wakeUp == null) {
if (wakeUp != null) {
wakeUp.cancel(false);
}
wakeUp = scheduler.schedule(new FutureRunnable(), delayNanos, TimeUnit.NANOSECONDS);
}
runAtNanos = newRunAtNanos;
} | java | void reschedule(long delay, TimeUnit timeUnit) {
long delayNanos = timeUnit.toNanos(delay);
long newRunAtNanos = nanoTime() + delayNanos;
enabled = true;
if (newRunAtNanos - runAtNanos < 0 || wakeUp == null) {
if (wakeUp != null) {
wakeUp.cancel(false);
}
wakeUp = scheduler.schedule(new FutureRunnable(), delayNanos, TimeUnit.NANOSECONDS);
}
runAtNanos = newRunAtNanos;
} | [
"void",
"reschedule",
"(",
"long",
"delay",
",",
"TimeUnit",
"timeUnit",
")",
"{",
"long",
"delayNanos",
"=",
"timeUnit",
".",
"toNanos",
"(",
"delay",
")",
";",
"long",
"newRunAtNanos",
"=",
"nanoTime",
"(",
")",
"+",
"delayNanos",
";",
"enabled",
"=",
... | /* must be called from the {@link #serializingExecutor} originally passed in. | [
"/",
"*",
"must",
"be",
"called",
"from",
"the",
"{"
] | train | https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/core/src/main/java/io/grpc/internal/Rescheduler.java#L55-L66 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.