repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 196 | func_name stringlengths 7 107 | whole_func_string stringlengths 76 3.82k | language stringclasses 1
value | func_code_string stringlengths 76 3.82k | func_code_tokens listlengths 22 717 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 508 | split_name stringclasses 1
value | func_code_url stringlengths 111 310 |
|---|---|---|---|---|---|---|---|---|---|---|
google/error-prone | core/src/main/java/com/google/errorprone/bugpatterns/NonAtomicVolatileUpdate.java | NonAtomicVolatileUpdate.variableFromAssignmentTree | private static Matcher<AssignmentTree> variableFromAssignmentTree(
final Matcher<ExpressionTree> exprMatcher) {
return new Matcher<AssignmentTree>() {
@Override
public boolean matches(AssignmentTree tree, VisitorState state) {
return exprMatcher.matches(tree.getVariable(), state);
}
};
} | java | private static Matcher<AssignmentTree> variableFromAssignmentTree(
final Matcher<ExpressionTree> exprMatcher) {
return new Matcher<AssignmentTree>() {
@Override
public boolean matches(AssignmentTree tree, VisitorState state) {
return exprMatcher.matches(tree.getVariable(), state);
}
};
} | [
"private",
"static",
"Matcher",
"<",
"AssignmentTree",
">",
"variableFromAssignmentTree",
"(",
"final",
"Matcher",
"<",
"ExpressionTree",
">",
"exprMatcher",
")",
"{",
"return",
"new",
"Matcher",
"<",
"AssignmentTree",
">",
"(",
")",
"{",
"@",
"Override",
"publi... | Extracts the variable from an AssignmentTree and applies a matcher to it. | [
"Extracts",
"the",
"variable",
"from",
"an",
"AssignmentTree",
"and",
"applies",
"a",
"matcher",
"to",
"it",
"."
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/NonAtomicVolatileUpdate.java#L79-L87 |
PrashamTrivedi/SharedPreferenceInspector | sharedpreferenceinspector/src/main/java/com/ceelites/sharedpreferenceinspector/Utils/SharedPreferenceUtils.java | SharedPreferenceUtils.putLong | public void putLong(String key, long value) {
sharedPreferences.edit().putLong(key, value).commit();
} | java | public void putLong(String key, long value) {
sharedPreferences.edit().putLong(key, value).commit();
} | [
"public",
"void",
"putLong",
"(",
"String",
"key",
",",
"long",
"value",
")",
"{",
"sharedPreferences",
".",
"edit",
"(",
")",
".",
"putLong",
"(",
"key",
",",
"value",
")",
".",
"commit",
"(",
")",
";",
"}"
] | put the int value to shared preference
@param key
the name of the preference to save
@param value
the name of the preference to modify.
@see android.content.SharedPreferences#edit()#putLong(String, long) | [
"put",
"the",
"int",
"value",
"to",
"shared",
"preference"
] | train | https://github.com/PrashamTrivedi/SharedPreferenceInspector/blob/c04d567c4d0fc5e0f8cda308ca85df19c6b3b838/sharedpreferenceinspector/src/main/java/com/ceelites/sharedpreferenceinspector/Utils/SharedPreferenceUtils.java#L475-L477 |
lessthanoptimal/ddogleg | src/org/ddogleg/optimization/FactoryOptimization.java | FactoryOptimization.levenbergMarquardtSchur | public static UnconstrainedLeastSquaresSchur<DMatrixRMaj> levenbergMarquardtSchur(
boolean robust,
@Nullable ConfigLevenbergMarquardt config )
{
if( config == null )
config = new ConfigLevenbergMarquardt();
HessianSchurComplement_DDRM hessian;
if( robust ) {
LinearSolverDense<DMatrixRMaj> solverA = LinearSolverFactory_DDRM.pseudoInverse(true);
LinearSolverDense<DMatrixRMaj> solverD = LinearSolverFactory_DDRM.pseudoInverse(true);
hessian = new HessianSchurComplement_DDRM(solverA,solverD);
} else {
// defaults to cholesky
hessian = new HessianSchurComplement_DDRM();
}
UnconLeastSqLevenbergMarquardtSchur_F64<DMatrixRMaj> lm =
new UnconLeastSqLevenbergMarquardtSchur_F64<>(new MatrixMath_DDRM(),hessian);
lm.configure(config);
return lm;
} | java | public static UnconstrainedLeastSquaresSchur<DMatrixRMaj> levenbergMarquardtSchur(
boolean robust,
@Nullable ConfigLevenbergMarquardt config )
{
if( config == null )
config = new ConfigLevenbergMarquardt();
HessianSchurComplement_DDRM hessian;
if( robust ) {
LinearSolverDense<DMatrixRMaj> solverA = LinearSolverFactory_DDRM.pseudoInverse(true);
LinearSolverDense<DMatrixRMaj> solverD = LinearSolverFactory_DDRM.pseudoInverse(true);
hessian = new HessianSchurComplement_DDRM(solverA,solverD);
} else {
// defaults to cholesky
hessian = new HessianSchurComplement_DDRM();
}
UnconLeastSqLevenbergMarquardtSchur_F64<DMatrixRMaj> lm =
new UnconLeastSqLevenbergMarquardtSchur_F64<>(new MatrixMath_DDRM(),hessian);
lm.configure(config);
return lm;
} | [
"public",
"static",
"UnconstrainedLeastSquaresSchur",
"<",
"DMatrixRMaj",
">",
"levenbergMarquardtSchur",
"(",
"boolean",
"robust",
",",
"@",
"Nullable",
"ConfigLevenbergMarquardt",
"config",
")",
"{",
"if",
"(",
"config",
"==",
"null",
")",
"config",
"=",
"new",
... | LM with Schur Complement
@param robust If true then a slow by robust solver is used. true = use SVD
@param config configuration for LM
@return the solver | [
"LM",
"with",
"Schur",
"Complement"
] | train | https://github.com/lessthanoptimal/ddogleg/blob/3786bf448ba23d0e04962dd08c34fa68de276029/src/org/ddogleg/optimization/FactoryOptimization.java#L194-L216 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/RecommendationsInner.java | RecommendationsInner.getRuleDetailsByWebApp | public RecommendationRuleInner getRuleDetailsByWebApp(String resourceGroupName, String siteName, String name) {
return getRuleDetailsByWebAppWithServiceResponseAsync(resourceGroupName, siteName, name).toBlocking().single().body();
} | java | public RecommendationRuleInner getRuleDetailsByWebApp(String resourceGroupName, String siteName, String name) {
return getRuleDetailsByWebAppWithServiceResponseAsync(resourceGroupName, siteName, name).toBlocking().single().body();
} | [
"public",
"RecommendationRuleInner",
"getRuleDetailsByWebApp",
"(",
"String",
"resourceGroupName",
",",
"String",
"siteName",
",",
"String",
"name",
")",
"{",
"return",
"getRuleDetailsByWebAppWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"siteName",
",",
"name",... | Get a recommendation rule for an app.
Get a recommendation rule for an app.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param siteName Name of the app.
@param name Name of the recommendation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws DefaultErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the RecommendationRuleInner object if successful. | [
"Get",
"a",
"recommendation",
"rule",
"for",
"an",
"app",
".",
"Get",
"a",
"recommendation",
"rule",
"for",
"an",
"app",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/RecommendationsInner.java#L1210-L1212 |
prestodb/presto | presto-rcfile/src/main/java/com/facebook/presto/rcfile/RcFileDecoderUtils.java | RcFileDecoderUtils.findFirstSyncPosition | public static long findFirstSyncPosition(RcFileDataSource dataSource, long offset, long length, long syncFirst, long syncSecond)
throws IOException
{
requireNonNull(dataSource, "dataSource is null");
checkArgument(offset >= 0, "offset is negative");
checkArgument(length >= 1, "length must be at least 1");
checkArgument(offset + length <= dataSource.getSize(), "offset plus length is greater than data size");
// The full sync sequence is "0xFFFFFFFF syncFirst syncSecond". If
// this sequence begins the file range, the start position is returned
// even if the sequence finishes after length.
// NOTE: this decision must agree with RcFileReader.nextBlock
Slice sync = Slices.allocate(SIZE_OF_INT + SIZE_OF_LONG + SIZE_OF_LONG);
sync.setInt(0, 0xFFFF_FFFF);
sync.setLong(SIZE_OF_INT, syncFirst);
sync.setLong(SIZE_OF_INT + SIZE_OF_LONG, syncSecond);
// read 4 MB chunks at a time, but only skip ahead 4 MB - SYNC_SEQUENCE_LENGTH bytes
// this causes a re-read of SYNC_SEQUENCE_LENGTH bytes each time, but is much simpler code
byte[] buffer = new byte[toIntExact(min(1 << 22, length + (SYNC_SEQUENCE_LENGTH - 1)))];
Slice bufferSlice = Slices.wrappedBuffer(buffer);
for (long position = 0; position < length; position += bufferSlice.length() - (SYNC_SEQUENCE_LENGTH - 1)) {
// either fill the buffer entirely, or read enough to allow all bytes in offset + length to be a start sequence
int bufferSize = toIntExact(min(buffer.length, length + (SYNC_SEQUENCE_LENGTH - 1) - position));
// don't read off the end of the file
bufferSize = toIntExact(min(bufferSize, dataSource.getSize() - offset - position));
dataSource.readFully(offset + position, buffer, 0, bufferSize);
// find the starting index position of the sync sequence
int index = bufferSlice.indexOf(sync);
if (index >= 0) {
// If the starting position is before the end of the search region, return the
// absolute start position of the sequence.
if (position + index < length) {
long startOfSyncSequence = offset + position + index;
return startOfSyncSequence;
}
else {
// Otherwise, this is not a match for this region
// Note: this case isn't strictly needed as the loop will exit, but it is
// simpler to explicitly call it out.
return -1;
}
}
}
return -1;
} | java | public static long findFirstSyncPosition(RcFileDataSource dataSource, long offset, long length, long syncFirst, long syncSecond)
throws IOException
{
requireNonNull(dataSource, "dataSource is null");
checkArgument(offset >= 0, "offset is negative");
checkArgument(length >= 1, "length must be at least 1");
checkArgument(offset + length <= dataSource.getSize(), "offset plus length is greater than data size");
// The full sync sequence is "0xFFFFFFFF syncFirst syncSecond". If
// this sequence begins the file range, the start position is returned
// even if the sequence finishes after length.
// NOTE: this decision must agree with RcFileReader.nextBlock
Slice sync = Slices.allocate(SIZE_OF_INT + SIZE_OF_LONG + SIZE_OF_LONG);
sync.setInt(0, 0xFFFF_FFFF);
sync.setLong(SIZE_OF_INT, syncFirst);
sync.setLong(SIZE_OF_INT + SIZE_OF_LONG, syncSecond);
// read 4 MB chunks at a time, but only skip ahead 4 MB - SYNC_SEQUENCE_LENGTH bytes
// this causes a re-read of SYNC_SEQUENCE_LENGTH bytes each time, but is much simpler code
byte[] buffer = new byte[toIntExact(min(1 << 22, length + (SYNC_SEQUENCE_LENGTH - 1)))];
Slice bufferSlice = Slices.wrappedBuffer(buffer);
for (long position = 0; position < length; position += bufferSlice.length() - (SYNC_SEQUENCE_LENGTH - 1)) {
// either fill the buffer entirely, or read enough to allow all bytes in offset + length to be a start sequence
int bufferSize = toIntExact(min(buffer.length, length + (SYNC_SEQUENCE_LENGTH - 1) - position));
// don't read off the end of the file
bufferSize = toIntExact(min(bufferSize, dataSource.getSize() - offset - position));
dataSource.readFully(offset + position, buffer, 0, bufferSize);
// find the starting index position of the sync sequence
int index = bufferSlice.indexOf(sync);
if (index >= 0) {
// If the starting position is before the end of the search region, return the
// absolute start position of the sequence.
if (position + index < length) {
long startOfSyncSequence = offset + position + index;
return startOfSyncSequence;
}
else {
// Otherwise, this is not a match for this region
// Note: this case isn't strictly needed as the loop will exit, but it is
// simpler to explicitly call it out.
return -1;
}
}
}
return -1;
} | [
"public",
"static",
"long",
"findFirstSyncPosition",
"(",
"RcFileDataSource",
"dataSource",
",",
"long",
"offset",
",",
"long",
"length",
",",
"long",
"syncFirst",
",",
"long",
"syncSecond",
")",
"throws",
"IOException",
"{",
"requireNonNull",
"(",
"dataSource",
"... | Find the beginning of the first full sync sequence that starts within the specified range. | [
"Find",
"the",
"beginning",
"of",
"the",
"first",
"full",
"sync",
"sequence",
"that",
"starts",
"within",
"the",
"specified",
"range",
"."
] | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-rcfile/src/main/java/com/facebook/presto/rcfile/RcFileDecoderUtils.java#L119-L167 |
apache/flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/operations/AggregateOperationFactory.java | AggregateOperationFactory.createResolvedWindow | public ResolvedGroupWindow createResolvedWindow(GroupWindow window, ExpressionResolver resolver) {
Expression alias = window.getAlias();
if (!(alias instanceof UnresolvedReferenceExpression)) {
throw new ValidationException("Only unresolved reference supported for alias of a group window.");
}
final String windowName = ((UnresolvedReferenceExpression) alias).getName();
FieldReferenceExpression timeField = getValidatedTimeAttribute(window, resolver);
if (window instanceof TumbleWithSizeOnTimeWithAlias) {
return validateAndCreateTumbleWindow(
(TumbleWithSizeOnTimeWithAlias) window,
windowName,
timeField);
} else if (window instanceof SlideWithSizeAndSlideOnTimeWithAlias) {
return validateAndCreateSlideWindow(
(SlideWithSizeAndSlideOnTimeWithAlias) window,
windowName,
timeField);
} else if (window instanceof SessionWithGapOnTimeWithAlias) {
return validateAndCreateSessionWindow(
(SessionWithGapOnTimeWithAlias) window,
windowName,
timeField);
} else {
throw new TableException("Unknown window type: " + window);
}
} | java | public ResolvedGroupWindow createResolvedWindow(GroupWindow window, ExpressionResolver resolver) {
Expression alias = window.getAlias();
if (!(alias instanceof UnresolvedReferenceExpression)) {
throw new ValidationException("Only unresolved reference supported for alias of a group window.");
}
final String windowName = ((UnresolvedReferenceExpression) alias).getName();
FieldReferenceExpression timeField = getValidatedTimeAttribute(window, resolver);
if (window instanceof TumbleWithSizeOnTimeWithAlias) {
return validateAndCreateTumbleWindow(
(TumbleWithSizeOnTimeWithAlias) window,
windowName,
timeField);
} else if (window instanceof SlideWithSizeAndSlideOnTimeWithAlias) {
return validateAndCreateSlideWindow(
(SlideWithSizeAndSlideOnTimeWithAlias) window,
windowName,
timeField);
} else if (window instanceof SessionWithGapOnTimeWithAlias) {
return validateAndCreateSessionWindow(
(SessionWithGapOnTimeWithAlias) window,
windowName,
timeField);
} else {
throw new TableException("Unknown window type: " + window);
}
} | [
"public",
"ResolvedGroupWindow",
"createResolvedWindow",
"(",
"GroupWindow",
"window",
",",
"ExpressionResolver",
"resolver",
")",
"{",
"Expression",
"alias",
"=",
"window",
".",
"getAlias",
"(",
")",
";",
"if",
"(",
"!",
"(",
"alias",
"instanceof",
"UnresolvedRef... | Converts an API class to a resolved window for planning with expressions already resolved.
It performs following validations:
<ul>
<li>The alias is represented with an unresolved reference</li>
<li>The time attribute is a single field reference of a {@link TimeIndicatorTypeInfo}(stream),
{@link SqlTimeTypeInfo}(batch), or {@link BasicTypeInfo#LONG_TYPE_INFO}(batch) type</li>
<li>The size & slide are value literals of either {@link RowIntervalTypeInfo#INTERVAL_ROWS},
or {@link TimeIntervalTypeInfo} type</li>
<li>The size & slide are of the same type</li>
<li>The gap is a value literal of a {@link TimeIntervalTypeInfo} type</li>
</ul>
@param window window to resolve
@param resolver resolver to resolve potential unresolved field references
@return window with expressions resolved | [
"Converts",
"an",
"API",
"class",
"to",
"a",
"resolved",
"window",
"for",
"planning",
"with",
"expressions",
"already",
"resolved",
".",
"It",
"performs",
"following",
"validations",
":",
"<ul",
">",
"<li",
">",
"The",
"alias",
"is",
"represented",
"with",
"... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/operations/AggregateOperationFactory.java#L183-L211 |
mikepenz/MaterialDrawer | library/src/main/java/com/mikepenz/materialdrawer/DrawerBuilder.java | DrawerBuilder.addMenuItems | private void addMenuItems(Menu mMenu, boolean subMenu) {
int groupId = R.id.material_drawer_menu_default_group;
for (int i = 0; i < mMenu.size(); i++) {
MenuItem mMenuItem = mMenu.getItem(i);
IDrawerItem iDrawerItem;
if (!subMenu && mMenuItem.getGroupId() != groupId && mMenuItem.getGroupId() != 0) {
groupId = mMenuItem.getGroupId();
iDrawerItem = new DividerDrawerItem();
getItemAdapter().add(iDrawerItem);
}
if (mMenuItem.hasSubMenu()) {
iDrawerItem = new PrimaryDrawerItem()
.withName(mMenuItem.getTitle().toString())
.withIcon(mMenuItem.getIcon())
.withIdentifier(mMenuItem.getItemId())
.withEnabled(mMenuItem.isEnabled())
.withSelectable(false);
getItemAdapter().add(iDrawerItem);
addMenuItems(mMenuItem.getSubMenu(), true);
} else if (mMenuItem.getGroupId() != 0 || subMenu) {
iDrawerItem = new SecondaryDrawerItem()
.withName(mMenuItem.getTitle().toString())
.withIcon(mMenuItem.getIcon())
.withIdentifier(mMenuItem.getItemId())
.withEnabled(mMenuItem.isEnabled());
getItemAdapter().add(iDrawerItem);
} else {
iDrawerItem = new PrimaryDrawerItem()
.withName(mMenuItem.getTitle().toString())
.withIcon(mMenuItem.getIcon())
.withIdentifier(mMenuItem.getItemId())
.withEnabled(mMenuItem.isEnabled());
getItemAdapter().add(iDrawerItem);
}
}
} | java | private void addMenuItems(Menu mMenu, boolean subMenu) {
int groupId = R.id.material_drawer_menu_default_group;
for (int i = 0; i < mMenu.size(); i++) {
MenuItem mMenuItem = mMenu.getItem(i);
IDrawerItem iDrawerItem;
if (!subMenu && mMenuItem.getGroupId() != groupId && mMenuItem.getGroupId() != 0) {
groupId = mMenuItem.getGroupId();
iDrawerItem = new DividerDrawerItem();
getItemAdapter().add(iDrawerItem);
}
if (mMenuItem.hasSubMenu()) {
iDrawerItem = new PrimaryDrawerItem()
.withName(mMenuItem.getTitle().toString())
.withIcon(mMenuItem.getIcon())
.withIdentifier(mMenuItem.getItemId())
.withEnabled(mMenuItem.isEnabled())
.withSelectable(false);
getItemAdapter().add(iDrawerItem);
addMenuItems(mMenuItem.getSubMenu(), true);
} else if (mMenuItem.getGroupId() != 0 || subMenu) {
iDrawerItem = new SecondaryDrawerItem()
.withName(mMenuItem.getTitle().toString())
.withIcon(mMenuItem.getIcon())
.withIdentifier(mMenuItem.getItemId())
.withEnabled(mMenuItem.isEnabled());
getItemAdapter().add(iDrawerItem);
} else {
iDrawerItem = new PrimaryDrawerItem()
.withName(mMenuItem.getTitle().toString())
.withIcon(mMenuItem.getIcon())
.withIdentifier(mMenuItem.getItemId())
.withEnabled(mMenuItem.isEnabled());
getItemAdapter().add(iDrawerItem);
}
}
} | [
"private",
"void",
"addMenuItems",
"(",
"Menu",
"mMenu",
",",
"boolean",
"subMenu",
")",
"{",
"int",
"groupId",
"=",
"R",
".",
"id",
".",
"material_drawer_menu_default_group",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"mMenu",
".",
"size",
... | helper method to init the drawerItems from a menu
@param mMenu
@param subMenu | [
"helper",
"method",
"to",
"init",
"the",
"drawerItems",
"from",
"a",
"menu"
] | train | https://github.com/mikepenz/MaterialDrawer/blob/f4fb31635767edead0a01cee7b7588942b89d8d9/library/src/main/java/com/mikepenz/materialdrawer/DrawerBuilder.java#L1048-L1083 |
hawkular/hawkular-apm | client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java | DefaultTraceCollector.spawnFragment | protected void spawnFragment(FragmentBuilder parentBuilder, Node node, int position,
FragmentBuilder spawnedBuilder) {
Trace trace = parentBuilder.getTrace();
String id = UUID.randomUUID().toString();
String location = null;
String uri = null;
String operation = null;
String type = null; // Set to null to indicate internal
if (!trace.getNodes().isEmpty()) {
Node rootNode = trace.getNodes().get(0);
uri = rootNode.getUri();
operation = rootNode.getOperation();
}
// Create Producer node to represent the internal connection to the spawned fragment
Producer producer = new Producer();
producer.setEndpointType(type);
producer.setUri(uri);
producer.setOperation(operation);
producer.getCorrelationIds().add(new CorrelationIdentifier(Scope.ControlFlow, id));
if (node != null && node.containerNode()) {
parentBuilder.initNode(producer);
if (position == -1) {
((ContainerNode)node).getNodes().add(producer);
} else {
((ContainerNode)node).getNodes().add(position, producer);
}
} else {
push(location, parentBuilder, producer);
pop(location, parentBuilder, Producer.class, uri);
}
// Transfer relevant details to the spawned trace and builder
Trace spawnedTrace = spawnedBuilder.getTrace();
spawnedTrace.setTraceId(trace.getTraceId());
spawnedTrace.setTransaction(trace.getTransaction());
spawnedBuilder.setLevel(parentBuilder.getLevel());
// Create Consumer node to represent other end of internal spawn link
Consumer consumer = new Consumer();
consumer.setEndpointType(type);
consumer.setUri(uri);
consumer.setOperation(operation);
consumer.getCorrelationIds().add(new CorrelationIdentifier(Scope.ControlFlow, id));
push(location, spawnedBuilder, consumer);
// Pop immediately as easier than attempting to determine end of spawned scope and
// removing it from the stack then.
// TODO: Could look at moving subsequent top level nodes under this Consumer
// at the point when the fragment is recorded
pop(location, spawnedBuilder, Consumer.class, uri);
} | java | protected void spawnFragment(FragmentBuilder parentBuilder, Node node, int position,
FragmentBuilder spawnedBuilder) {
Trace trace = parentBuilder.getTrace();
String id = UUID.randomUUID().toString();
String location = null;
String uri = null;
String operation = null;
String type = null; // Set to null to indicate internal
if (!trace.getNodes().isEmpty()) {
Node rootNode = trace.getNodes().get(0);
uri = rootNode.getUri();
operation = rootNode.getOperation();
}
// Create Producer node to represent the internal connection to the spawned fragment
Producer producer = new Producer();
producer.setEndpointType(type);
producer.setUri(uri);
producer.setOperation(operation);
producer.getCorrelationIds().add(new CorrelationIdentifier(Scope.ControlFlow, id));
if (node != null && node.containerNode()) {
parentBuilder.initNode(producer);
if (position == -1) {
((ContainerNode)node).getNodes().add(producer);
} else {
((ContainerNode)node).getNodes().add(position, producer);
}
} else {
push(location, parentBuilder, producer);
pop(location, parentBuilder, Producer.class, uri);
}
// Transfer relevant details to the spawned trace and builder
Trace spawnedTrace = spawnedBuilder.getTrace();
spawnedTrace.setTraceId(trace.getTraceId());
spawnedTrace.setTransaction(trace.getTransaction());
spawnedBuilder.setLevel(parentBuilder.getLevel());
// Create Consumer node to represent other end of internal spawn link
Consumer consumer = new Consumer();
consumer.setEndpointType(type);
consumer.setUri(uri);
consumer.setOperation(operation);
consumer.getCorrelationIds().add(new CorrelationIdentifier(Scope.ControlFlow, id));
push(location, spawnedBuilder, consumer);
// Pop immediately as easier than attempting to determine end of spawned scope and
// removing it from the stack then.
// TODO: Could look at moving subsequent top level nodes under this Consumer
// at the point when the fragment is recorded
pop(location, spawnedBuilder, Consumer.class, uri);
} | [
"protected",
"void",
"spawnFragment",
"(",
"FragmentBuilder",
"parentBuilder",
",",
"Node",
"node",
",",
"int",
"position",
",",
"FragmentBuilder",
"spawnedBuilder",
")",
"{",
"Trace",
"trace",
"=",
"parentBuilder",
".",
"getTrace",
"(",
")",
";",
"String",
"id"... | This method creates a new linked fragment to handle some asynchronous
activities. | [
"This",
"method",
"creates",
"a",
"new",
"linked",
"fragment",
"to",
"handle",
"some",
"asynchronous",
"activities",
"."
] | train | https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java#L1505-L1560 |
wcm-io/wcm-io-handler | media/src/main/java/io/wcm/handler/media/format/MediaFormat.java | MediaFormat.guessHumanReadableRatioString | private static String guessHumanReadableRatioString(double ratio, NumberFormat numberFormat) {
for (long width = 1; width <= 50; width++) {
double height = width / ratio;
if (isLong(height)) {
return numberFormat.format(width) + ":" + numberFormat.format(height);
}
}
for (long width = 1; width <= 200; width++) {
double height = width / 2d / ratio;
if (isHalfLong(height)) {
return numberFormat.format(width / 2d) + ":" + numberFormat.format(height);
}
}
return null;
} | java | private static String guessHumanReadableRatioString(double ratio, NumberFormat numberFormat) {
for (long width = 1; width <= 50; width++) {
double height = width / ratio;
if (isLong(height)) {
return numberFormat.format(width) + ":" + numberFormat.format(height);
}
}
for (long width = 1; width <= 200; width++) {
double height = width / 2d / ratio;
if (isHalfLong(height)) {
return numberFormat.format(width / 2d) + ":" + numberFormat.format(height);
}
}
return null;
} | [
"private",
"static",
"String",
"guessHumanReadableRatioString",
"(",
"double",
"ratio",
",",
"NumberFormat",
"numberFormat",
")",
"{",
"for",
"(",
"long",
"width",
"=",
"1",
";",
"width",
"<=",
"50",
";",
"width",
"++",
")",
"{",
"double",
"height",
"=",
"... | Try to guess a nice human readable ratio string from the given decimal ratio
@param ratio Ratio
@param numberFormat Number format
@return Ratio display string or null if no nice string was found | [
"Try",
"to",
"guess",
"a",
"nice",
"human",
"readable",
"ratio",
"string",
"from",
"the",
"given",
"decimal",
"ratio"
] | train | https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/media/format/MediaFormat.java#L265-L279 |
yidongnan/grpc-spring-boot-starter | grpc-client-spring-boot-autoconfigure/src/main/java/net/devh/boot/grpc/client/channelfactory/AbstractChannelFactory.java | AbstractChannelFactory.configureKeepAlive | protected void configureKeepAlive(final T builder, final String name) {
final GrpcChannelProperties properties = getPropertiesFor(name);
if (properties.isEnableKeepAlive()) {
builder.keepAliveTime(properties.getKeepAliveTime().toNanos(), TimeUnit.NANOSECONDS)
.keepAliveTimeout(properties.getKeepAliveTimeout().toNanos(), TimeUnit.NANOSECONDS)
.keepAliveWithoutCalls(properties.isKeepAliveWithoutCalls());
}
} | java | protected void configureKeepAlive(final T builder, final String name) {
final GrpcChannelProperties properties = getPropertiesFor(name);
if (properties.isEnableKeepAlive()) {
builder.keepAliveTime(properties.getKeepAliveTime().toNanos(), TimeUnit.NANOSECONDS)
.keepAliveTimeout(properties.getKeepAliveTimeout().toNanos(), TimeUnit.NANOSECONDS)
.keepAliveWithoutCalls(properties.isKeepAliveWithoutCalls());
}
} | [
"protected",
"void",
"configureKeepAlive",
"(",
"final",
"T",
"builder",
",",
"final",
"String",
"name",
")",
"{",
"final",
"GrpcChannelProperties",
"properties",
"=",
"getPropertiesFor",
"(",
"name",
")",
";",
"if",
"(",
"properties",
".",
"isEnableKeepAlive",
... | Configures the keep alive options that should be used by the channel.
@param builder The channel builder to configure.
@param name The name of the client to configure. | [
"Configures",
"the",
"keep",
"alive",
"options",
"that",
"should",
"be",
"used",
"by",
"the",
"channel",
"."
] | train | https://github.com/yidongnan/grpc-spring-boot-starter/blob/07f8853cfafc9707584f2371aff012e590217b85/grpc-client-spring-boot-autoconfigure/src/main/java/net/devh/boot/grpc/client/channelfactory/AbstractChannelFactory.java#L168-L175 |
google/closure-compiler | src/com/google/javascript/jscomp/Es6RewriteClassExtendsExpressions.java | Es6RewriteClassExtendsExpressions.decomposeInIIFE | private void decomposeInIIFE(NodeTraversal t, Node classNode) {
// converts
// `class X extends something {}`
// to
// `(function() { return class X extends something {}; })()`
Node functionBody = IR.block();
Node function = IR.function(IR.name(""), IR.paramList(), functionBody);
Node call = NodeUtil.newCallNode(function);
classNode.replaceWith(call);
functionBody.addChildToBack(IR.returnNode(classNode));
call.useSourceInfoIfMissingFromForTree(classNode);
// NOTE: extractExtends() will end up reporting the change for the new function, so we only
// need to report the change to the enclosing scope
t.reportCodeChange(call);
// Now do the extends expression extraction within the IIFE
extractExtends(t, classNode);
} | java | private void decomposeInIIFE(NodeTraversal t, Node classNode) {
// converts
// `class X extends something {}`
// to
// `(function() { return class X extends something {}; })()`
Node functionBody = IR.block();
Node function = IR.function(IR.name(""), IR.paramList(), functionBody);
Node call = NodeUtil.newCallNode(function);
classNode.replaceWith(call);
functionBody.addChildToBack(IR.returnNode(classNode));
call.useSourceInfoIfMissingFromForTree(classNode);
// NOTE: extractExtends() will end up reporting the change for the new function, so we only
// need to report the change to the enclosing scope
t.reportCodeChange(call);
// Now do the extends expression extraction within the IIFE
extractExtends(t, classNode);
} | [
"private",
"void",
"decomposeInIIFE",
"(",
"NodeTraversal",
"t",
",",
"Node",
"classNode",
")",
"{",
"// converts",
"// `class X extends something {}`",
"// to",
"// `(function() { return class X extends something {}; })()`",
"Node",
"functionBody",
"=",
"IR",
".",
"block",
... | When a class is used in an expressions where adding an alias as the previous statement might
change execution order of a side-effect causing statement, wrap the class in an IIFE so that
decomposition can happen safely. | [
"When",
"a",
"class",
"is",
"used",
"in",
"an",
"expressions",
"where",
"adding",
"an",
"alias",
"as",
"the",
"previous",
"statement",
"might",
"change",
"execution",
"order",
"of",
"a",
"side",
"-",
"effect",
"causing",
"statement",
"wrap",
"the",
"class",
... | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteClassExtendsExpressions.java#L156-L172 |
geomajas/geomajas-project-client-gwt | client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java | DomHelper.setController | public void setController(Object object, GraphicsController controller) {
// set them all
doSetController(getGroup(object), controller, Event.MOUSEEVENTS | Event.ONDBLCLICK | Event.ONMOUSEWHEEL);
} | java | public void setController(Object object, GraphicsController controller) {
// set them all
doSetController(getGroup(object), controller, Event.MOUSEEVENTS | Event.ONDBLCLICK | Event.ONMOUSEWHEEL);
} | [
"public",
"void",
"setController",
"(",
"Object",
"object",
",",
"GraphicsController",
"controller",
")",
"{",
"// set them all",
"doSetController",
"(",
"getGroup",
"(",
"object",
")",
",",
"controller",
",",
"Event",
".",
"MOUSEEVENTS",
"|",
"Event",
".",
"OND... | Set the controller on an element of this <code>GraphicsContext</code> so it can react to events.
@param object
the element on which the controller should be set.
@param controller
The new <code>GraphicsController</code> | [
"Set",
"the",
"controller",
"on",
"an",
"element",
"of",
"this",
"<code",
">",
"GraphicsContext<",
"/",
"code",
">",
"so",
"it",
"can",
"react",
"to",
"events",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java#L552-L555 |
pawelprazak/java-extended | guava/src/main/java/com/bluecatcode/common/base/Environment.java | Environment.isPortAvailable | public static boolean isPortAvailable(int port) {
StringBuilder builder = new StringBuilder();
builder.append("Testing port ").append(port).append("\n");
try (Socket s = new Socket("localhost", port)) {
// If the code makes it this far without an exception it means
// something is using the port and has responded.
builder.append("Port ").append(port).append(" is not available").append("\n");
return false;
} catch (IOException e) {
builder.append("Port ").append(port).append(" is available").append("\n");
return true;
} finally {
log.fine(builder.toString());
}
} | java | public static boolean isPortAvailable(int port) {
StringBuilder builder = new StringBuilder();
builder.append("Testing port ").append(port).append("\n");
try (Socket s = new Socket("localhost", port)) {
// If the code makes it this far without an exception it means
// something is using the port and has responded.
builder.append("Port ").append(port).append(" is not available").append("\n");
return false;
} catch (IOException e) {
builder.append("Port ").append(port).append(" is available").append("\n");
return true;
} finally {
log.fine(builder.toString());
}
} | [
"public",
"static",
"boolean",
"isPortAvailable",
"(",
"int",
"port",
")",
"{",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"builder",
".",
"append",
"(",
"\"Testing port \"",
")",
".",
"append",
"(",
"port",
")",
".",
"append",
... | Checks if a port is available by opening a socket on it
@param port the port to test
@return true if the port is available | [
"Checks",
"if",
"a",
"port",
"is",
"available",
"by",
"opening",
"a",
"socket",
"on",
"it"
] | train | https://github.com/pawelprazak/java-extended/blob/ce1a556a95cbbf7c950a03662938bc02622de69b/guava/src/main/java/com/bluecatcode/common/base/Environment.java#L141-L155 |
UrielCh/ovh-java-sdk | ovh-java-sdk-msServices/src/main/java/net/minidev/ovh/api/ApiOvhMsServices.java | ApiOvhMsServices.serviceName_sharepoint_PUT | public void serviceName_sharepoint_PUT(String serviceName, OvhSharepointService body) throws IOException {
String qPath = "/msServices/{serviceName}/sharepoint";
StringBuilder sb = path(qPath, serviceName);
exec(qPath, "PUT", sb.toString(), body);
} | java | public void serviceName_sharepoint_PUT(String serviceName, OvhSharepointService body) throws IOException {
String qPath = "/msServices/{serviceName}/sharepoint";
StringBuilder sb = path(qPath, serviceName);
exec(qPath, "PUT", sb.toString(), body);
} | [
"public",
"void",
"serviceName_sharepoint_PUT",
"(",
"String",
"serviceName",
",",
"OvhSharepointService",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/msServices/{serviceName}/sharepoint\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath... | Alter this object properties
REST: PUT /msServices/{serviceName}/sharepoint
@param body [required] New object properties
@param serviceName [required] The internal name of your Active Directory organization
API beta | [
"Alter",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-msServices/src/main/java/net/minidev/ovh/api/ApiOvhMsServices.java#L673-L677 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/functions/DifferentialFunctionFactory.java | DifferentialFunctionFactory.avgPooling2d | public SDVariable avgPooling2d(SDVariable input, Pooling2DConfig pooling2DConfig) {
AvgPooling2D avgPooling2D = AvgPooling2D.builder()
.input(input)
.sameDiff(sameDiff())
.config(pooling2DConfig)
.build();
return avgPooling2D.outputVariable();
} | java | public SDVariable avgPooling2d(SDVariable input, Pooling2DConfig pooling2DConfig) {
AvgPooling2D avgPooling2D = AvgPooling2D.builder()
.input(input)
.sameDiff(sameDiff())
.config(pooling2DConfig)
.build();
return avgPooling2D.outputVariable();
} | [
"public",
"SDVariable",
"avgPooling2d",
"(",
"SDVariable",
"input",
",",
"Pooling2DConfig",
"pooling2DConfig",
")",
"{",
"AvgPooling2D",
"avgPooling2D",
"=",
"AvgPooling2D",
".",
"builder",
"(",
")",
".",
"input",
"(",
"input",
")",
".",
"sameDiff",
"(",
"sameDi... | Average pooling 2d operation.
@param input the inputs to pooling
@param pooling2DConfig the configuration
@return | [
"Average",
"pooling",
"2d",
"operation",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/functions/DifferentialFunctionFactory.java#L317-L325 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java | MapUtil.joinIgnoreNull | public static <K, V> String joinIgnoreNull(Map<K, V> map, String separator, String keyValueSeparator) {
return join(map, separator, keyValueSeparator, true);
} | java | public static <K, V> String joinIgnoreNull(Map<K, V> map, String separator, String keyValueSeparator) {
return join(map, separator, keyValueSeparator, true);
} | [
"public",
"static",
"<",
"K",
",",
"V",
">",
"String",
"joinIgnoreNull",
"(",
"Map",
"<",
"K",
",",
"V",
">",
"map",
",",
"String",
"separator",
",",
"String",
"keyValueSeparator",
")",
"{",
"return",
"join",
"(",
"map",
",",
"separator",
",",
"keyValu... | 将map转成字符串,忽略null的键和值
@param <K> 键类型
@param <V> 值类型
@param map Map
@param separator entry之间的连接符
@param keyValueSeparator kv之间的连接符
@return 连接后的字符串
@since 3.1.1 | [
"将map转成字符串,忽略null的键和值"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java#L442-L444 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/OperationDefinition.java | OperationDefinition.validateAndSet | @SuppressWarnings("deprecation")
@Deprecated
public final void validateAndSet(ModelNode operationObject, final ModelNode model) throws OperationFailedException {
validateOperation(operationObject);
for (AttributeDefinition ad : this.parameters) {
ad.validateAndSet(operationObject, model);
}
} | java | @SuppressWarnings("deprecation")
@Deprecated
public final void validateAndSet(ModelNode operationObject, final ModelNode model) throws OperationFailedException {
validateOperation(operationObject);
for (AttributeDefinition ad : this.parameters) {
ad.validateAndSet(operationObject, model);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"@",
"Deprecated",
"public",
"final",
"void",
"validateAndSet",
"(",
"ModelNode",
"operationObject",
",",
"final",
"ModelNode",
"model",
")",
"throws",
"OperationFailedException",
"{",
"validateOperation",
"(",
"op... | validates operation against the definition and sets model for the parameters passed.
@param operationObject model node of type {@link ModelType#OBJECT}, typically representing an operation request
@param model model node in which the value should be stored
@throws OperationFailedException if the value is not valid
@deprecated Not used by the WildFly management kernel; will be removed in a future release | [
"validates",
"operation",
"against",
"the",
"definition",
"and",
"sets",
"model",
"for",
"the",
"parameters",
"passed",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/OperationDefinition.java#L192-L199 |
mikepenz/MaterialDrawer | library/src/main/java/com/mikepenz/materialdrawer/Drawer.java | Drawer.updateBadge | public void updateBadge(long identifier, StringHolder badge) {
IDrawerItem drawerItem = getDrawerItem(identifier);
if (drawerItem instanceof Badgeable) {
Badgeable badgeable = (Badgeable) drawerItem;
badgeable.withBadge(badge);
updateItem((IDrawerItem) badgeable);
}
} | java | public void updateBadge(long identifier, StringHolder badge) {
IDrawerItem drawerItem = getDrawerItem(identifier);
if (drawerItem instanceof Badgeable) {
Badgeable badgeable = (Badgeable) drawerItem;
badgeable.withBadge(badge);
updateItem((IDrawerItem) badgeable);
}
} | [
"public",
"void",
"updateBadge",
"(",
"long",
"identifier",
",",
"StringHolder",
"badge",
")",
"{",
"IDrawerItem",
"drawerItem",
"=",
"getDrawerItem",
"(",
"identifier",
")",
";",
"if",
"(",
"drawerItem",
"instanceof",
"Badgeable",
")",
"{",
"Badgeable",
"badgea... | update the badge for a specific drawerItem
identified by its id
@param identifier
@param badge | [
"update",
"the",
"badge",
"for",
"a",
"specific",
"drawerItem",
"identified",
"by",
"its",
"id"
] | train | https://github.com/mikepenz/MaterialDrawer/blob/f4fb31635767edead0a01cee7b7588942b89d8d9/library/src/main/java/com/mikepenz/materialdrawer/Drawer.java#L665-L672 |
webmetrics/browsermob-proxy | src/main/java/org/browsermob/proxy/jetty/jetty/servlet/ServletHandler.java | ServletHandler.addServlet | public ServletHolder addServlet(String name,
String pathSpec,
String servletClass)
{
return addServlet(name,pathSpec,servletClass,null);
} | java | public ServletHolder addServlet(String name,
String pathSpec,
String servletClass)
{
return addServlet(name,pathSpec,servletClass,null);
} | [
"public",
"ServletHolder",
"addServlet",
"(",
"String",
"name",
",",
"String",
"pathSpec",
",",
"String",
"servletClass",
")",
"{",
"return",
"addServlet",
"(",
"name",
",",
"pathSpec",
",",
"servletClass",
",",
"null",
")",
";",
"}"
] | Add a servlet.
@param name The servlet name.
@param pathSpec A path specification to map this servlet to.
@param servletClass The class name of the servlet.
@return The ServletHolder for the servlet. | [
"Add",
"a",
"servlet",
"."
] | train | https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/jetty/servlet/ServletHandler.java#L323-L328 |
jeremylong/DependencyCheck | core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractFileTypeAnalyzer.java | AbstractFileTypeAnalyzer.newHashSet | protected static Set<String> newHashSet(String... strings) {
final Set<String> set = new HashSet<>(strings.length);
Collections.addAll(set, strings);
return set;
} | java | protected static Set<String> newHashSet(String... strings) {
final Set<String> set = new HashSet<>(strings.length);
Collections.addAll(set, strings);
return set;
} | [
"protected",
"static",
"Set",
"<",
"String",
">",
"newHashSet",
"(",
"String",
"...",
"strings",
")",
"{",
"final",
"Set",
"<",
"String",
">",
"set",
"=",
"new",
"HashSet",
"<>",
"(",
"strings",
".",
"length",
")",
";",
"Collections",
".",
"addAll",
"(... | <p>
Utility method to help in the creation of the extensions set. This
constructs a new Set that can be used in a final static declaration.</p>
<p>
This implementation was copied from
http://stackoverflow.com/questions/2041778/prepare-java-hashset-values-by-construction</p>
@param strings a list of strings to add to the set.
@return a Set of strings. | [
"<p",
">",
"Utility",
"method",
"to",
"help",
"in",
"the",
"creation",
"of",
"the",
"extensions",
"set",
".",
"This",
"constructs",
"a",
"new",
"Set",
"that",
"can",
"be",
"used",
"in",
"a",
"final",
"static",
"declaration",
".",
"<",
"/",
"p",
">",
... | train | https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractFileTypeAnalyzer.java#L148-L152 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/WorldGame.java | WorldGame.saveToFile | public final void saveToFile(Media media)
{
try (FileWriting writing = new FileWriting(media))
{
saving(writing);
}
catch (final IOException exception)
{
throw new LionEngineException(exception, media, "Error on saving to file !");
}
} | java | public final void saveToFile(Media media)
{
try (FileWriting writing = new FileWriting(media))
{
saving(writing);
}
catch (final IOException exception)
{
throw new LionEngineException(exception, media, "Error on saving to file !");
}
} | [
"public",
"final",
"void",
"saveToFile",
"(",
"Media",
"media",
")",
"{",
"try",
"(",
"FileWriting",
"writing",
"=",
"new",
"FileWriting",
"(",
"media",
")",
")",
"{",
"saving",
"(",
"writing",
")",
";",
"}",
"catch",
"(",
"final",
"IOException",
"except... | Save world to the specified file.
@param media The output media.
@throws LionEngineException If error on saving to file. | [
"Save",
"world",
"to",
"the",
"specified",
"file",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/WorldGame.java#L141-L151 |
jglobus/JGlobus | gridftp/src/main/java/org/globus/ftp/GridFTPClient.java | GridFTPClient.createSymbolicLink | public void createSymbolicLink(String link_target, String link_name)
throws IOException, ServerException {
String arguments = link_target.replaceAll(" ", "%20") + " " + link_name;
Command cmd = new Command("SITE SYMLINK", arguments);
try {
controlChannel.execute(cmd);
}catch (UnexpectedReplyCodeException urce) {
throw ServerException.embedUnexpectedReplyCodeException(urce);
} catch (FTPReplyParseException rpe) {
throw ServerException.embedFTPReplyParseException(rpe);
}
} | java | public void createSymbolicLink(String link_target, String link_name)
throws IOException, ServerException {
String arguments = link_target.replaceAll(" ", "%20") + " " + link_name;
Command cmd = new Command("SITE SYMLINK", arguments);
try {
controlChannel.execute(cmd);
}catch (UnexpectedReplyCodeException urce) {
throw ServerException.embedUnexpectedReplyCodeException(urce);
} catch (FTPReplyParseException rpe) {
throw ServerException.embedFTPReplyParseException(rpe);
}
} | [
"public",
"void",
"createSymbolicLink",
"(",
"String",
"link_target",
",",
"String",
"link_name",
")",
"throws",
"IOException",
",",
"ServerException",
"{",
"String",
"arguments",
"=",
"link_target",
".",
"replaceAll",
"(",
"\" \"",
",",
"\"%20\"",
")",
"+",
"\"... | Create a symbolic link on the FTP server.
@param link_target the path to which the symbolic link should point
@param link_name the path of the symbolic link to create
@throws IOException
@throws ServerException if an error occurred. | [
"Create",
"a",
"symbolic",
"link",
"on",
"the",
"FTP",
"server",
"."
] | train | https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/gridftp/src/main/java/org/globus/ftp/GridFTPClient.java#L1137-L1150 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/field/BaseField.java | BaseField.init | public void init(Record record, String strName, int iDataLength, String strDesc, Object strDefault)
{
m_bJustChanged = false;
m_DBObject = null;
m_listener = null;
m_bVirtual = false;
m_bSelected = true;
m_bNullable = true;
super.init(record, strName, iDataLength, strDesc, strDefault);
this.setModified(false); // No modifications to start with
} | java | public void init(Record record, String strName, int iDataLength, String strDesc, Object strDefault)
{
m_bJustChanged = false;
m_DBObject = null;
m_listener = null;
m_bVirtual = false;
m_bSelected = true;
m_bNullable = true;
super.init(record, strName, iDataLength, strDesc, strDefault);
this.setModified(false); // No modifications to start with
} | [
"public",
"void",
"init",
"(",
"Record",
"record",
",",
"String",
"strName",
",",
"int",
"iDataLength",
",",
"String",
"strDesc",
",",
"Object",
"strDefault",
")",
"{",
"m_bJustChanged",
"=",
"false",
";",
"m_DBObject",
"=",
"null",
";",
"m_listener",
"=",
... | Constructor.
@param record The parent record.
@param strName The field name.
@param iDataLength The maximum string length (pass -1 for default).
@param strDesc The string description (usually pass null, to use the resource file desc).
@param strDefault The default value (if object, this value is the default value, if string, the string is the default). | [
"Constructor",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/BaseField.java#L126-L138 |
exoplatform/jcr | exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/lnkproducer/LinkGenerator.java | LinkGenerator.writeInts | private void writeInts(int[] bytes, OutputStream outStream) throws IOException
{
for (int i = 0; i < bytes.length; i++)
{
byte curByte = (byte)bytes[i];
outStream.write(curByte);
}
} | java | private void writeInts(int[] bytes, OutputStream outStream) throws IOException
{
for (int i = 0; i < bytes.length; i++)
{
byte curByte = (byte)bytes[i];
outStream.write(curByte);
}
} | [
"private",
"void",
"writeInts",
"(",
"int",
"[",
"]",
"bytes",
",",
"OutputStream",
"outStream",
")",
"throws",
"IOException",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"bytes",
".",
"length",
";",
"i",
"++",
")",
"{",
"byte",
"curByte",
... | Writes int array into stream.
@param bytes int array
@param outStream stream
@throws IOException {@link IOException} | [
"Writes",
"int",
"array",
"into",
"stream",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/lnkproducer/LinkGenerator.java#L384-L391 |
jtrfp/javamod | src/main/java/de/quippy/javamod/multimedia/mp3/id3/MP3FileID3Controller.java | MP3FileID3Controller.setUserDefinedURL | public void setUserDefinedURL(String desc, String url)
{
if (allow(ID3V2))
{
id3v2.setUserDefinedURLFrame(desc, url);
}
} | java | public void setUserDefinedURL(String desc, String url)
{
if (allow(ID3V2))
{
id3v2.setUserDefinedURLFrame(desc, url);
}
} | [
"public",
"void",
"setUserDefinedURL",
"(",
"String",
"desc",
",",
"String",
"url",
")",
"{",
"if",
"(",
"allow",
"(",
"ID3V2",
")",
")",
"{",
"id3v2",
".",
"setUserDefinedURLFrame",
"(",
"desc",
",",
"url",
")",
";",
"}",
"}"
] | Add a link to this mp3 (id3v2 only). This includes a description of
the url and the url itself.
@param desc a description of the url
@param url the url itself | [
"Add",
"a",
"link",
"to",
"this",
"mp3",
"(",
"id3v2",
"only",
")",
".",
"This",
"includes",
"a",
"description",
"of",
"the",
"url",
"and",
"the",
"url",
"itself",
"."
] | train | https://github.com/jtrfp/javamod/blob/cda4fe943a589dc49415f4413453e2eece72076a/src/main/java/de/quippy/javamod/multimedia/mp3/id3/MP3FileID3Controller.java#L319-L325 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/util/Environment.java | Environment.getMessageManager | public MessageManager getMessageManager(App application, boolean bCreateIfNotFound)
{
if (application == null)
application = this.getDefaultApplication();
if (this.getMessageApplication(bCreateIfNotFound, application.getProperties()) != null)
return this.getMessageApplication(bCreateIfNotFound, application.getProperties()).getThickMessageManager();
return null;
} | java | public MessageManager getMessageManager(App application, boolean bCreateIfNotFound)
{
if (application == null)
application = this.getDefaultApplication();
if (this.getMessageApplication(bCreateIfNotFound, application.getProperties()) != null)
return this.getMessageApplication(bCreateIfNotFound, application.getProperties()).getThickMessageManager();
return null;
} | [
"public",
"MessageManager",
"getMessageManager",
"(",
"App",
"application",
",",
"boolean",
"bCreateIfNotFound",
")",
"{",
"if",
"(",
"application",
"==",
"null",
")",
"application",
"=",
"this",
".",
"getDefaultApplication",
"(",
")",
";",
"if",
"(",
"this",
... | Get this Message Queue (or create one if this name doesn't exist).
@param application The parent application
@param bCreateIfNotFound Create the manager if not found?
@return The message manager. | [
"Get",
"this",
"Message",
"Queue",
"(",
"or",
"create",
"one",
"if",
"this",
"name",
"doesn",
"t",
"exist",
")",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/util/Environment.java#L365-L372 |
BoltsFramework/Bolts-Android | bolts-tasks/src/main/java/bolts/Task.java | Task.callInBackground | public static <TResult> Task<TResult> callInBackground(Callable<TResult> callable, CancellationToken ct) {
return call(callable, BACKGROUND_EXECUTOR, ct);
} | java | public static <TResult> Task<TResult> callInBackground(Callable<TResult> callable, CancellationToken ct) {
return call(callable, BACKGROUND_EXECUTOR, ct);
} | [
"public",
"static",
"<",
"TResult",
">",
"Task",
"<",
"TResult",
">",
"callInBackground",
"(",
"Callable",
"<",
"TResult",
">",
"callable",
",",
"CancellationToken",
"ct",
")",
"{",
"return",
"call",
"(",
"callable",
",",
"BACKGROUND_EXECUTOR",
",",
"ct",
")... | Invokes the callable on a background thread, returning a Task to represent the operation. | [
"Invokes",
"the",
"callable",
"on",
"a",
"background",
"thread",
"returning",
"a",
"Task",
"to",
"represent",
"the",
"operation",
"."
] | train | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-tasks/src/main/java/bolts/Task.java#L324-L326 |
kotcrab/vis-ui | ui/src/main/java/com/kotcrab/vis/ui/widget/VisDialog.java | VisDialog.text | public VisDialog text (String text) {
if (skin == null)
throw new IllegalStateException("This method may only be used if the dialog was constructed with a Skin.");
return text(text, skin.get(LabelStyle.class));
} | java | public VisDialog text (String text) {
if (skin == null)
throw new IllegalStateException("This method may only be used if the dialog was constructed with a Skin.");
return text(text, skin.get(LabelStyle.class));
} | [
"public",
"VisDialog",
"text",
"(",
"String",
"text",
")",
"{",
"if",
"(",
"skin",
"==",
"null",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"This method may only be used if the dialog was constructed with a Skin.\"",
")",
";",
"return",
"text",
"(",
"text",
... | Adds a label to the content table. The dialog must have been constructed with a skin to use this method. | [
"Adds",
"a",
"label",
"to",
"the",
"content",
"table",
".",
"The",
"dialog",
"must",
"have",
"been",
"constructed",
"with",
"a",
"skin",
"to",
"use",
"this",
"method",
"."
] | train | https://github.com/kotcrab/vis-ui/blob/3b68f82d94ae32bffa2a3399c63f432e0f4908e0/ui/src/main/java/com/kotcrab/vis/ui/widget/VisDialog.java#L144-L148 |
EdwardRaff/JSAT | JSAT/src/jsat/classifiers/neuralnetwork/BackPropagationNet.java | BackPropagationNet.setWeightDecay | public void setWeightDecay(double weightDecay)
{
if(weightDecay < 0 || weightDecay >= 1 || Double.isNaN(weightDecay))
throw new ArithmeticException("Weight decay must be in [0,1), not " + weightDecay);
this.weightDecay = weightDecay;
} | java | public void setWeightDecay(double weightDecay)
{
if(weightDecay < 0 || weightDecay >= 1 || Double.isNaN(weightDecay))
throw new ArithmeticException("Weight decay must be in [0,1), not " + weightDecay);
this.weightDecay = weightDecay;
} | [
"public",
"void",
"setWeightDecay",
"(",
"double",
"weightDecay",
")",
"{",
"if",
"(",
"weightDecay",
"<",
"0",
"||",
"weightDecay",
">=",
"1",
"||",
"Double",
".",
"isNaN",
"(",
"weightDecay",
")",
")",
"throw",
"new",
"ArithmeticException",
"(",
"\"Weight ... | Sets the weight decay used for each update. The weight decay must be in
the range [0, 1). Weight decay values must often be very small, often
1e-8 or less.
@param weightDecay the weight decay to apply when training | [
"Sets",
"the",
"weight",
"decay",
"used",
"for",
"each",
"update",
".",
"The",
"weight",
"decay",
"must",
"be",
"in",
"the",
"range",
"[",
"0",
"1",
")",
".",
"Weight",
"decay",
"values",
"must",
"often",
"be",
"very",
"small",
"often",
"1e",
"-",
"8... | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/neuralnetwork/BackPropagationNet.java#L397-L402 |
Impetus/Kundera | src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/TableProcessor.java | TableProcessor.onBuildMetaModelSuperClass | private <X, T> void onBuildMetaModelSuperClass(Class<? super X> clazz, MetaModelBuilder<X, T> metaModelBuilder)
{
if (clazz != null && clazz.isAnnotationPresent(javax.persistence.Entity.class))
{
while (clazz != null && clazz.isAnnotationPresent(javax.persistence.Entity.class))
{
metaModelBuilder.process((Class<X>) clazz);
for (Field f : clazz.getDeclaredFields())
{
if (f != null && !Modifier.isStatic(f.getModifiers()) && !Modifier.isTransient(f.getModifiers())
&& !f.isAnnotationPresent(Transient.class))
{
metaModelBuilder.construct((Class<X>) clazz, f);
}
}
clazz = clazz.getSuperclass();
}
}
} | java | private <X, T> void onBuildMetaModelSuperClass(Class<? super X> clazz, MetaModelBuilder<X, T> metaModelBuilder)
{
if (clazz != null && clazz.isAnnotationPresent(javax.persistence.Entity.class))
{
while (clazz != null && clazz.isAnnotationPresent(javax.persistence.Entity.class))
{
metaModelBuilder.process((Class<X>) clazz);
for (Field f : clazz.getDeclaredFields())
{
if (f != null && !Modifier.isStatic(f.getModifiers()) && !Modifier.isTransient(f.getModifiers())
&& !f.isAnnotationPresent(Transient.class))
{
metaModelBuilder.construct((Class<X>) clazz, f);
}
}
clazz = clazz.getSuperclass();
}
}
} | [
"private",
"<",
"X",
",",
"T",
">",
"void",
"onBuildMetaModelSuperClass",
"(",
"Class",
"<",
"?",
"super",
"X",
">",
"clazz",
",",
"MetaModelBuilder",
"<",
"X",
",",
"T",
">",
"metaModelBuilder",
")",
"{",
"if",
"(",
"clazz",
"!=",
"null",
"&&",
"clazz... | Populate metadata.
@param <X>
the generic type
@param <T>
the generic type
@param metaModelBuilder
the metaModelBuilder | [
"Populate",
"metadata",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/TableProcessor.java#L193-L213 |
sniggle/simple-pgp | simple-pgp-java/src/main/java/me/sniggle/pgp/crypt/PGPKeyPairGenerator.java | PGPKeyPairGenerator.generateKeyPair | @Override
public boolean generateKeyPair(String userId, String password, int keySize, OutputStream publicKey, OutputStream secrectKey) {
LOGGER.trace("generateKeyPair(String, String, int, OutputStream, OutputStream)");
LOGGER.trace("User ID: {}, Password: {}, Key Size: {}, Public Key: {}, Secret Key: {}", userId, password == null ? "not set" : "********", keySize, publicKey == null ? "not set" : "set", secrectKey == null ? "not set" : "set");
boolean result = true;
LOGGER.debug("Generating key ring generator");
PGPKeyRingGenerator keyRingGenerator = createKeyRingGenerator(userId, password, keySize);
LOGGER.debug("Generating public key ring");
PGPPublicKeyRing publicKeyRing = keyRingGenerator.generatePublicKeyRing();
LOGGER.debug("Generating secret key ring");
PGPSecretKeyRing secretKeyRing = keyRingGenerator.generateSecretKeyRing();
LOGGER.debug("Wrapping public key target stream in ArmoredOutputStream");
try( OutputStream targetStream = new ArmoredOutputStream(publicKey) ) {
LOGGER.info("Saving public key ring to public target");
publicKeyRing.encode(targetStream);
} catch (IOException e) {
LOGGER.error("{}", e.getMessage());
result &= false;
}
LOGGER.debug("Wrapping secret key target stream in ArmoredOutputStream");
try( OutputStream targetStream = new ArmoredOutputStream(secrectKey) ) {
LOGGER.debug("Create secret key ring collection");
PGPSecretKeyRingCollection secretKeyRingCollection = new PGPSecretKeyRingCollection(Arrays.asList(secretKeyRing));
LOGGER.info("Saving secret key ring to secret key target");
secretKeyRingCollection.encode(targetStream);
} catch (IOException | PGPException e) {
LOGGER.error("{}", e.getMessage());
result &= false;
}
return result;
} | java | @Override
public boolean generateKeyPair(String userId, String password, int keySize, OutputStream publicKey, OutputStream secrectKey) {
LOGGER.trace("generateKeyPair(String, String, int, OutputStream, OutputStream)");
LOGGER.trace("User ID: {}, Password: {}, Key Size: {}, Public Key: {}, Secret Key: {}", userId, password == null ? "not set" : "********", keySize, publicKey == null ? "not set" : "set", secrectKey == null ? "not set" : "set");
boolean result = true;
LOGGER.debug("Generating key ring generator");
PGPKeyRingGenerator keyRingGenerator = createKeyRingGenerator(userId, password, keySize);
LOGGER.debug("Generating public key ring");
PGPPublicKeyRing publicKeyRing = keyRingGenerator.generatePublicKeyRing();
LOGGER.debug("Generating secret key ring");
PGPSecretKeyRing secretKeyRing = keyRingGenerator.generateSecretKeyRing();
LOGGER.debug("Wrapping public key target stream in ArmoredOutputStream");
try( OutputStream targetStream = new ArmoredOutputStream(publicKey) ) {
LOGGER.info("Saving public key ring to public target");
publicKeyRing.encode(targetStream);
} catch (IOException e) {
LOGGER.error("{}", e.getMessage());
result &= false;
}
LOGGER.debug("Wrapping secret key target stream in ArmoredOutputStream");
try( OutputStream targetStream = new ArmoredOutputStream(secrectKey) ) {
LOGGER.debug("Create secret key ring collection");
PGPSecretKeyRingCollection secretKeyRingCollection = new PGPSecretKeyRingCollection(Arrays.asList(secretKeyRing));
LOGGER.info("Saving secret key ring to secret key target");
secretKeyRingCollection.encode(targetStream);
} catch (IOException | PGPException e) {
LOGGER.error("{}", e.getMessage());
result &= false;
}
return result;
} | [
"@",
"Override",
"public",
"boolean",
"generateKeyPair",
"(",
"String",
"userId",
",",
"String",
"password",
",",
"int",
"keySize",
",",
"OutputStream",
"publicKey",
",",
"OutputStream",
"secrectKey",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"generateKeyPair(Strin... | @see KeyPairGenerator#generateKeyPair(String, String, int, OutputStream, OutputStream)
@param userId
the user id for the PGP key pair
@param password
the password used to secure the secret (private) key
@param keySize
the custom key size
@param publicKey
the target stream for the public key
@param secrectKey
the target stream for the secret (private) key
@return | [
"@see",
"KeyPairGenerator#generateKeyPair",
"(",
"String",
"String",
"int",
"OutputStream",
"OutputStream",
")"
] | train | https://github.com/sniggle/simple-pgp/blob/2ab83e4d370b8189f767d8e4e4c7e6020e60fbe3/simple-pgp-java/src/main/java/me/sniggle/pgp/crypt/PGPKeyPairGenerator.java#L104-L134 |
alkacon/opencms-core | src/org/opencms/relations/CmsCategory.java | CmsCategory.getCategoryPath | public static String getCategoryPath(String rootPath, String baseFolder) throws CmsException {
String base;
if (rootPath.startsWith(CmsCategoryService.CENTRALIZED_REPOSITORY)) {
base = CmsCategoryService.CENTRALIZED_REPOSITORY;
} else {
base = baseFolder;
if (!base.endsWith("/")) {
base += "/";
}
if (!base.startsWith("/")) {
base = "/" + base;
}
int pos = rootPath.indexOf(base);
if (pos < 0) {
throw new CmsDataAccessException(
Messages.get().container(Messages.ERR_CATEGORY_INVALID_LOCATION_1, rootPath));
}
base = rootPath.substring(0, pos + base.length());
}
return rootPath.substring(base.length());
} | java | public static String getCategoryPath(String rootPath, String baseFolder) throws CmsException {
String base;
if (rootPath.startsWith(CmsCategoryService.CENTRALIZED_REPOSITORY)) {
base = CmsCategoryService.CENTRALIZED_REPOSITORY;
} else {
base = baseFolder;
if (!base.endsWith("/")) {
base += "/";
}
if (!base.startsWith("/")) {
base = "/" + base;
}
int pos = rootPath.indexOf(base);
if (pos < 0) {
throw new CmsDataAccessException(
Messages.get().container(Messages.ERR_CATEGORY_INVALID_LOCATION_1, rootPath));
}
base = rootPath.substring(0, pos + base.length());
}
return rootPath.substring(base.length());
} | [
"public",
"static",
"String",
"getCategoryPath",
"(",
"String",
"rootPath",
",",
"String",
"baseFolder",
")",
"throws",
"CmsException",
"{",
"String",
"base",
";",
"if",
"(",
"rootPath",
".",
"startsWith",
"(",
"CmsCategoryService",
".",
"CENTRALIZED_REPOSITORY",
... | Returns the category path for the given root path.<p>
@param rootPath the root path
@param baseFolder the categories base folder name
@return the category path
@throws CmsException if the root path does not match the given base folder | [
"Returns",
"the",
"category",
"path",
"for",
"the",
"given",
"root",
"path",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/relations/CmsCategory.java#L134-L155 |
square/picasso | picasso/src/main/java/com/squareup/picasso3/PicassoDrawable.java | PicassoDrawable.setResult | static void setResult(ImageView target, Context context, RequestHandler.Result result,
boolean noFade, boolean debugging) {
Drawable placeholder = target.getDrawable();
if (placeholder instanceof Animatable) {
((Animatable) placeholder).stop();
}
Bitmap bitmap = result.getBitmap();
if (bitmap != null) {
Picasso.LoadedFrom loadedFrom = result.getLoadedFrom();
PicassoDrawable drawable =
new PicassoDrawable(context, bitmap, placeholder, loadedFrom, noFade, debugging);
target.setImageDrawable(drawable);
return;
}
Drawable drawable = result.getDrawable();
if (drawable != null) {
target.setImageDrawable(drawable);
if (drawable instanceof Animatable) {
((Animatable) drawable).start();
}
}
} | java | static void setResult(ImageView target, Context context, RequestHandler.Result result,
boolean noFade, boolean debugging) {
Drawable placeholder = target.getDrawable();
if (placeholder instanceof Animatable) {
((Animatable) placeholder).stop();
}
Bitmap bitmap = result.getBitmap();
if (bitmap != null) {
Picasso.LoadedFrom loadedFrom = result.getLoadedFrom();
PicassoDrawable drawable =
new PicassoDrawable(context, bitmap, placeholder, loadedFrom, noFade, debugging);
target.setImageDrawable(drawable);
return;
}
Drawable drawable = result.getDrawable();
if (drawable != null) {
target.setImageDrawable(drawable);
if (drawable instanceof Animatable) {
((Animatable) drawable).start();
}
}
} | [
"static",
"void",
"setResult",
"(",
"ImageView",
"target",
",",
"Context",
"context",
",",
"RequestHandler",
".",
"Result",
"result",
",",
"boolean",
"noFade",
",",
"boolean",
"debugging",
")",
"{",
"Drawable",
"placeholder",
"=",
"target",
".",
"getDrawable",
... | Create or update the drawable on the target {@link ImageView} to display the supplied bitmap
image. | [
"Create",
"or",
"update",
"the",
"drawable",
"on",
"the",
"target",
"{"
] | train | https://github.com/square/picasso/blob/89f55b76e3be2b65e5997b7698f782f16f8547e3/picasso/src/main/java/com/squareup/picasso3/PicassoDrawable.java#L44-L67 |
chalup/microorm | library/src/main/java/org/chalup/microorm/MicroOrm.java | MicroOrm.fromCursor | public <T> T fromCursor(Cursor c, Class<T> klass) {
DaoAdapter<T> adapter = getAdapter(klass);
return adapter.fromCursor(c, adapter.createInstance());
} | java | public <T> T fromCursor(Cursor c, Class<T> klass) {
DaoAdapter<T> adapter = getAdapter(klass);
return adapter.fromCursor(c, adapter.createInstance());
} | [
"public",
"<",
"T",
">",
"T",
"fromCursor",
"(",
"Cursor",
"c",
",",
"Class",
"<",
"T",
">",
"klass",
")",
"{",
"DaoAdapter",
"<",
"T",
">",
"adapter",
"=",
"getAdapter",
"(",
"klass",
")",
";",
"return",
"adapter",
".",
"fromCursor",
"(",
"c",
","... | Creates an object of the specified type from the current row in
{@link Cursor}.
@param <T> the type of the desired object
@param c an open {@link Cursor} with position set to valid row
@param klass The {@link Class} of the desired object
@return an object of type T created from the current row in {@link Cursor} | [
"Creates",
"an",
"object",
"of",
"the",
"specified",
"type",
"from",
"the",
"current",
"row",
"in",
"{",
"@link",
"Cursor",
"}",
"."
] | train | https://github.com/chalup/microorm/blob/54c437608c4563daa207950d6a7af663f820da89/library/src/main/java/org/chalup/microorm/MicroOrm.java#L57-L60 |
fozziethebeat/S-Space | src/main/java/edu/ucla/sspace/clustering/seeding/GeneralizedOrssSeed.java | GeneralizedOrssSeed.chooseSeeds | public DoubleVector[] chooseSeeds(Matrix dataPoints, int k, int[] weights) {
IntSet selected = new TroveIntSet();
int rows = dataPoints.rows();
// Edge case for where the user has requested more seeds than are
// available. In this case, just return indices for all the rows
if (rows <= k) {
DoubleVector[] arr = new DoubleVector[rows];
for (int i = 0; i < rows; ++i)
arr[i] = dataPoints.getRowVector(i);
return arr;
}
// This array keeps the relative probability of that index's data point
// being selected as a centroid. Although the probabilities change with
// each center added, the array is only allocated once and is refilled
// using determineProbabilities() method.
double[] probabilities = new double[rows];
// This array keeps the memoized computation of the maximum similarity
// of each data point i, to any center currently in selected. After the
// first two points are selected, each iteration updates this array with
// the maximum simiarlity of the new center to that point's index.
double[] inverseSimilarities = new double[rows];
// Pick the first two centers, x, y, with probability proportional to
// 1/sim(x, y). In the original paper the probility is proportional to
// ||x - y||^2, which is the square of the distance between the two
// points. However, since we use the simiarlity (which is conceptually
// the inverse of distance), we use the inverse similarity so that
// elements that are more similarity (i.e., larger values) have smaller
// probabilities.
IntPair firstTwoCenters =
pickFirstTwo(dataPoints, simFunc, weights, inverseSimilarities);
selected.add(firstTwoCenters.x);
selected.add(firstTwoCenters.y);
// For the remaining k-2 points to select, pick a random point, x, with
// probability min(1/sim(x, c_i)) for all centers c_i in selected.
// Again, this probability-based selection is updated from the original
// ORSS paper, which used || x - c_i ||^2 for all centers c. See the
// comment above for the reasoning.
for (int i = 2; i < k; i++) {
// First, calculate the probabilities for selecting each point given
// its similarity to any of the currently selected centers
determineProbabilities(inverseSimilarities, weights,
probabilities, selected);
// Then sample a point from the multinomial distribution over the
// remaining points in dataPoints
int point = selectWithProb(probabilities);
// Once we've selected a point, add it the set that we will return
// and update the similarity all other non-selected points relative
// to be the highest similarity to any selected point
boolean added = selected.add(point);
assert added : "Added duplicate row to the set of selected points";
updateNearestCenter(inverseSimilarities, dataPoints,
point, simFunc);
}
IntIterator iter = selected.iterator();
DoubleVector[] centroids = new DoubleVector[k];
for (int i = 0; iter.hasNext(); ++i)
centroids[i] = dataPoints.getRowVector(iter.nextInt());
return centroids;
} | java | public DoubleVector[] chooseSeeds(Matrix dataPoints, int k, int[] weights) {
IntSet selected = new TroveIntSet();
int rows = dataPoints.rows();
// Edge case for where the user has requested more seeds than are
// available. In this case, just return indices for all the rows
if (rows <= k) {
DoubleVector[] arr = new DoubleVector[rows];
for (int i = 0; i < rows; ++i)
arr[i] = dataPoints.getRowVector(i);
return arr;
}
// This array keeps the relative probability of that index's data point
// being selected as a centroid. Although the probabilities change with
// each center added, the array is only allocated once and is refilled
// using determineProbabilities() method.
double[] probabilities = new double[rows];
// This array keeps the memoized computation of the maximum similarity
// of each data point i, to any center currently in selected. After the
// first two points are selected, each iteration updates this array with
// the maximum simiarlity of the new center to that point's index.
double[] inverseSimilarities = new double[rows];
// Pick the first two centers, x, y, with probability proportional to
// 1/sim(x, y). In the original paper the probility is proportional to
// ||x - y||^2, which is the square of the distance between the two
// points. However, since we use the simiarlity (which is conceptually
// the inverse of distance), we use the inverse similarity so that
// elements that are more similarity (i.e., larger values) have smaller
// probabilities.
IntPair firstTwoCenters =
pickFirstTwo(dataPoints, simFunc, weights, inverseSimilarities);
selected.add(firstTwoCenters.x);
selected.add(firstTwoCenters.y);
// For the remaining k-2 points to select, pick a random point, x, with
// probability min(1/sim(x, c_i)) for all centers c_i in selected.
// Again, this probability-based selection is updated from the original
// ORSS paper, which used || x - c_i ||^2 for all centers c. See the
// comment above for the reasoning.
for (int i = 2; i < k; i++) {
// First, calculate the probabilities for selecting each point given
// its similarity to any of the currently selected centers
determineProbabilities(inverseSimilarities, weights,
probabilities, selected);
// Then sample a point from the multinomial distribution over the
// remaining points in dataPoints
int point = selectWithProb(probabilities);
// Once we've selected a point, add it the set that we will return
// and update the similarity all other non-selected points relative
// to be the highest similarity to any selected point
boolean added = selected.add(point);
assert added : "Added duplicate row to the set of selected points";
updateNearestCenter(inverseSimilarities, dataPoints,
point, simFunc);
}
IntIterator iter = selected.iterator();
DoubleVector[] centroids = new DoubleVector[k];
for (int i = 0; iter.hasNext(); ++i)
centroids[i] = dataPoints.getRowVector(iter.nextInt());
return centroids;
} | [
"public",
"DoubleVector",
"[",
"]",
"chooseSeeds",
"(",
"Matrix",
"dataPoints",
",",
"int",
"k",
",",
"int",
"[",
"]",
"weights",
")",
"{",
"IntSet",
"selected",
"=",
"new",
"TroveIntSet",
"(",
")",
";",
"int",
"rows",
"=",
"dataPoints",
".",
"rows",
"... | Selects {@code k} rows of {@code dataPoints}, weighted by the specified
amount, to be seeds of a <i>k</i>-means instance. If more seeds are
requested than are available, all possible rows are returned.
@param dataPoints a matrix whose rows are to be evaluated and from which
{@code k} data points will be selected
@param k the number of data points (rows) to select
@param weights as set of scalar int weights that reflect the importance
of each data points.
@return the set of rows that were selected | [
"Selects",
"{",
"@code",
"k",
"}",
"rows",
"of",
"{",
"@code",
"dataPoints",
"}",
"weighted",
"by",
"the",
"specified",
"amount",
"to",
"be",
"seeds",
"of",
"a",
"<i",
">",
"k<",
"/",
"i",
">",
"-",
"means",
"instance",
".",
"If",
"more",
"seeds",
... | train | https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/clustering/seeding/GeneralizedOrssSeed.java#L121-L188 |
Axway/Grapes | server/src/main/java/org/axway/grapes/server/core/DependencyHandler.java | DependencyHandler.getModuleDependencies | public List<Dependency> getModuleDependencies(final String moduleId, final FiltersHolder filters){
final DbModule module = moduleHandler.getModule(moduleId);
final DbOrganization organization = moduleHandler.getOrganization(module);
filters.setCorporateFilter(new CorporateFilter(organization));
return getModuleDependencies(module, filters, 1, new ArrayList<String>());
} | java | public List<Dependency> getModuleDependencies(final String moduleId, final FiltersHolder filters){
final DbModule module = moduleHandler.getModule(moduleId);
final DbOrganization organization = moduleHandler.getOrganization(module);
filters.setCorporateFilter(new CorporateFilter(organization));
return getModuleDependencies(module, filters, 1, new ArrayList<String>());
} | [
"public",
"List",
"<",
"Dependency",
">",
"getModuleDependencies",
"(",
"final",
"String",
"moduleId",
",",
"final",
"FiltersHolder",
"filters",
")",
"{",
"final",
"DbModule",
"module",
"=",
"moduleHandler",
".",
"getModule",
"(",
"moduleId",
")",
";",
"final",
... | Returns the list of module dependencies regarding the provided filters
@param moduleId String
@param filters FiltersHolder
@return List<Dependency> | [
"Returns",
"the",
"list",
"of",
"module",
"dependencies",
"regarding",
"the",
"provided",
"filters"
] | train | https://github.com/Axway/Grapes/blob/ce9cc73d85f83eaa5fbc991abb593915a8c8374e/server/src/main/java/org/axway/grapes/server/core/DependencyHandler.java#L52-L58 |
fuinorg/utils4j | src/main/java/org/fuin/utils4j/JandexUtils.java | JandexUtils.indexDir | public static void indexDir(final Indexer indexer, final List<File> knownFiles, final File dir) {
final List<File> classes = Utils4J.pathsFiles(dir.getPath(), Utils4J::classFile);
for (final File file : classes) {
indexClassFile(indexer, knownFiles, file);
}
} | java | public static void indexDir(final Indexer indexer, final List<File> knownFiles, final File dir) {
final List<File> classes = Utils4J.pathsFiles(dir.getPath(), Utils4J::classFile);
for (final File file : classes) {
indexClassFile(indexer, knownFiles, file);
}
} | [
"public",
"static",
"void",
"indexDir",
"(",
"final",
"Indexer",
"indexer",
",",
"final",
"List",
"<",
"File",
">",
"knownFiles",
",",
"final",
"File",
"dir",
")",
"{",
"final",
"List",
"<",
"File",
">",
"classes",
"=",
"Utils4J",
".",
"pathsFiles",
"(",... | Indexes all classes in a directory or it's sub directories.
@param indexer
Indexer to use.
@param knownFiles
List of files already analyzed. New files will be added within this method.
@param dir
Directory to analyze. | [
"Indexes",
"all",
"classes",
"in",
"a",
"directory",
"or",
"it",
"s",
"sub",
"directories",
"."
] | train | https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/JandexUtils.java#L81-L86 |
dita-ot/dita-ot | src/main/java/org/dita/dost/reader/DitaValReader.java | DitaValReader.setSubjectScheme | public void setSubjectScheme(final Map<QName, Map<String, Set<Element>>> bindingMap) {
this.bindingMap = bindingMap;
} | java | public void setSubjectScheme(final Map<QName, Map<String, Set<Element>>> bindingMap) {
this.bindingMap = bindingMap;
} | [
"public",
"void",
"setSubjectScheme",
"(",
"final",
"Map",
"<",
"QName",
",",
"Map",
"<",
"String",
",",
"Set",
"<",
"Element",
">",
">",
">",
"bindingMap",
")",
"{",
"this",
".",
"bindingMap",
"=",
"bindingMap",
";",
"}"
] | Set the map of subject scheme definitions. The contents of the map is in pseudo-code
{@code Map<AttName, Map<ElemName, Set<Element>>>}. For default element mapping, the value is {@code *}. | [
"Set",
"the",
"map",
"of",
"subject",
"scheme",
"definitions",
".",
"The",
"contents",
"of",
"the",
"map",
"is",
"in",
"pseudo",
"-",
"code",
"{"
] | train | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/reader/DitaValReader.java#L128-L130 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/config/MappedParametrizedObjectEntry.java | MappedParametrizedObjectEntry.getParameterDouble | public Double getParameterDouble(String name, Double defaultValue)
{
String value = getParameterValue(name, null);
if (value != null)
{
try
{
return StringNumberParser.parseDouble(value);
}
catch (NumberFormatException e)
{
if (LOG.isTraceEnabled())
{
LOG.trace("An exception occurred: " + e.getMessage());
}
}
}
return defaultValue;
} | java | public Double getParameterDouble(String name, Double defaultValue)
{
String value = getParameterValue(name, null);
if (value != null)
{
try
{
return StringNumberParser.parseDouble(value);
}
catch (NumberFormatException e)
{
if (LOG.isTraceEnabled())
{
LOG.trace("An exception occurred: " + e.getMessage());
}
}
}
return defaultValue;
} | [
"public",
"Double",
"getParameterDouble",
"(",
"String",
"name",
",",
"Double",
"defaultValue",
")",
"{",
"String",
"value",
"=",
"getParameterValue",
"(",
"name",
",",
"null",
")",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"try",
"{",
"return",
"... | Parse named parameter as Double.
@param name
parameter name
@param defaultValue
default Double value
@return Double value | [
"Parse",
"named",
"parameter",
"as",
"Double",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/config/MappedParametrizedObjectEntry.java#L247-L266 |
Azure/azure-sdk-for-java | storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/implementation/StorageAccountsInner.java | StorageAccountsInner.deleteManagementPolicies | public void deleteManagementPolicies(String resourceGroupName, String accountName) {
deleteManagementPoliciesWithServiceResponseAsync(resourceGroupName, accountName).toBlocking().single().body();
} | java | public void deleteManagementPolicies(String resourceGroupName, String accountName) {
deleteManagementPoliciesWithServiceResponseAsync(resourceGroupName, accountName).toBlocking().single().body();
} | [
"public",
"void",
"deleteManagementPolicies",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
")",
"{",
"deleteManagementPoliciesWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"... | Deletes the data policy rules associated with the specified storage account.
@param resourceGroupName The name of the resource group within the user's subscription. The name is case insensitive.
@param accountName The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent | [
"Deletes",
"the",
"data",
"policy",
"rules",
"associated",
"with",
"the",
"specified",
"storage",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/implementation/StorageAccountsInner.java#L1464-L1466 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerImpl.java | TransformerImpl.setContentHandler | public void setContentHandler(ContentHandler handler)
{
if (handler == null)
{
throw new NullPointerException(XSLMessages.createMessage(XSLTErrorResources.ER_NULL_CONTENT_HANDLER, null)); //"Null content handler");
}
else
{
m_outputContentHandler = handler;
if (null == m_serializationHandler)
{
ToXMLSAXHandler h = new ToXMLSAXHandler();
h.setContentHandler(handler);
h.setTransformer(this);
m_serializationHandler = h;
}
else
m_serializationHandler.setContentHandler(handler);
}
} | java | public void setContentHandler(ContentHandler handler)
{
if (handler == null)
{
throw new NullPointerException(XSLMessages.createMessage(XSLTErrorResources.ER_NULL_CONTENT_HANDLER, null)); //"Null content handler");
}
else
{
m_outputContentHandler = handler;
if (null == m_serializationHandler)
{
ToXMLSAXHandler h = new ToXMLSAXHandler();
h.setContentHandler(handler);
h.setTransformer(this);
m_serializationHandler = h;
}
else
m_serializationHandler.setContentHandler(handler);
}
} | [
"public",
"void",
"setContentHandler",
"(",
"ContentHandler",
"handler",
")",
"{",
"if",
"(",
"handler",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"XSLMessages",
".",
"createMessage",
"(",
"XSLTErrorResources",
".",
"ER_NULL_CONTENT_HANDLE... | Set the content event handler.
NEEDSDOC @param handler
@throws java.lang.NullPointerException If the handler
is null.
@see org.xml.sax.XMLReader#setContentHandler | [
"Set",
"the",
"content",
"event",
"handler",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerImpl.java#L1703-L1725 |
wildfly/wildfly-maven-plugin | plugin/src/main/java/org/wildfly/plugin/deployment/resource/AddResourceMojo.java | AddResourceMojo.buildAddOperation | private ModelNode buildAddOperation(final ModelNode address, final Map<String, String> properties) {
final ModelNode op = ServerOperations.createAddOperation(address);
for (Map.Entry<String, String> prop : properties.entrySet()) {
final String[] props = prop.getKey().split(",");
if (props.length == 0) {
throw new RuntimeException("Invalid property " + prop);
}
ModelNode node = op;
for (int i = 0; i < props.length - 1; ++i) {
node = node.get(props[i]);
}
final String value = prop.getValue() == null ? "" : prop.getValue();
if (value.startsWith("!!")) {
handleDmrString(node, props[props.length - 1], value);
} else {
node.get(props[props.length - 1]).set(value);
}
}
return op;
} | java | private ModelNode buildAddOperation(final ModelNode address, final Map<String, String> properties) {
final ModelNode op = ServerOperations.createAddOperation(address);
for (Map.Entry<String, String> prop : properties.entrySet()) {
final String[] props = prop.getKey().split(",");
if (props.length == 0) {
throw new RuntimeException("Invalid property " + prop);
}
ModelNode node = op;
for (int i = 0; i < props.length - 1; ++i) {
node = node.get(props[i]);
}
final String value = prop.getValue() == null ? "" : prop.getValue();
if (value.startsWith("!!")) {
handleDmrString(node, props[props.length - 1], value);
} else {
node.get(props[props.length - 1]).set(value);
}
}
return op;
} | [
"private",
"ModelNode",
"buildAddOperation",
"(",
"final",
"ModelNode",
"address",
",",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"properties",
")",
"{",
"final",
"ModelNode",
"op",
"=",
"ServerOperations",
".",
"createAddOperation",
"(",
"address",
")"... | Creates the operation to add a resource.
@param address the address of the operation to add.
@param properties the properties to set for the resource.
@return the operation. | [
"Creates",
"the",
"operation",
"to",
"add",
"a",
"resource",
"."
] | train | https://github.com/wildfly/wildfly-maven-plugin/blob/c0e2d7ee28e511092561801959eae253b2b56def/plugin/src/main/java/org/wildfly/plugin/deployment/resource/AddResourceMojo.java#L215-L234 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/processor/StylesheetHandler.java | StylesheetHandler.startPrefixMapping | public void startPrefixMapping(String prefix, String uri)
throws org.xml.sax.SAXException
{
// m_nsSupport.pushContext();
// this.getNamespaceSupport().declarePrefix(prefix, uri);
//m_prefixMappings.add(prefix); // JDK 1.2+ only -sc
//m_prefixMappings.add(uri); // JDK 1.2+ only -sc
m_prefixMappings.addElement(prefix); // JDK 1.1.x compat -sc
m_prefixMappings.addElement(uri); // JDK 1.1.x compat -sc
} | java | public void startPrefixMapping(String prefix, String uri)
throws org.xml.sax.SAXException
{
// m_nsSupport.pushContext();
// this.getNamespaceSupport().declarePrefix(prefix, uri);
//m_prefixMappings.add(prefix); // JDK 1.2+ only -sc
//m_prefixMappings.add(uri); // JDK 1.2+ only -sc
m_prefixMappings.addElement(prefix); // JDK 1.1.x compat -sc
m_prefixMappings.addElement(uri); // JDK 1.1.x compat -sc
} | [
"public",
"void",
"startPrefixMapping",
"(",
"String",
"prefix",
",",
"String",
"uri",
")",
"throws",
"org",
".",
"xml",
".",
"sax",
".",
"SAXException",
"{",
"// m_nsSupport.pushContext();",
"// this.getNamespaceSupport().declarePrefix(prefix, uri);",
"//m_prefixMappings.a... | Receive notification of the start of a Namespace mapping.
<p>By default, do nothing. Application writers may override this
method in a subclass to take specific actions at the start of
each element (such as allocating a new tree node or writing
output to a file).</p>
@param prefix The Namespace prefix being declared.
@param uri The Namespace URI mapped to the prefix.
@see org.xml.sax.ContentHandler#startPrefixMapping
@throws org.xml.sax.SAXException Any SAX exception, possibly
wrapping another exception. | [
"Receive",
"notification",
"of",
"the",
"start",
"of",
"a",
"Namespace",
"mapping",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/processor/StylesheetHandler.java#L515-L525 |
jimmoores/quandl4j | core/src/main/java/com/jimmoores/quandl/QuandlCodeRequest.java | QuandlCodeRequest.singleColumn | public static QuandlCodeRequest singleColumn(final String quandlCode, final int columnNumber) {
ArgumentChecker.notNull(quandlCode, "quandlCode");
return new QuandlCodeRequest(quandlCode, columnNumber);
} | java | public static QuandlCodeRequest singleColumn(final String quandlCode, final int columnNumber) {
ArgumentChecker.notNull(quandlCode, "quandlCode");
return new QuandlCodeRequest(quandlCode, columnNumber);
} | [
"public",
"static",
"QuandlCodeRequest",
"singleColumn",
"(",
"final",
"String",
"quandlCode",
",",
"final",
"int",
"columnNumber",
")",
"{",
"ArgumentChecker",
".",
"notNull",
"(",
"quandlCode",
",",
"\"quandlCode\"",
")",
";",
"return",
"new",
"QuandlCodeRequest",... | Request just a single column for a given quandlCode.
@param quandlCode the Quandl code you're interested in, not null
@param columnNumber the column number (determined by meta-data or a single request) of the data you want, not null
@return an request instance, not null | [
"Request",
"just",
"a",
"single",
"column",
"for",
"a",
"given",
"quandlCode",
"."
] | train | https://github.com/jimmoores/quandl4j/blob/5d67ae60279d889da93ae7aa3bf6b7d536f88822/core/src/main/java/com/jimmoores/quandl/QuandlCodeRequest.java#L25-L28 |
wildfly/wildfly-core | request-controller/src/main/java/org/wildfly/extension/requestcontroller/RequestController.java | RequestController.pauseDeployment | public synchronized void pauseDeployment(final String deployment, ServerActivityCallback listener) {
final List<ControlPoint> eps = new ArrayList<ControlPoint>();
for (ControlPoint ep : entryPoints.values()) {
if (ep.getDeployment().equals(deployment)) {
if(!ep.isPaused()) {
eps.add(ep);
}
}
}
CountingRequestCountCallback realListener = new CountingRequestCountCallback(eps.size(), listener);
for (ControlPoint ep : eps) {
ep.pause(realListener);
}
} | java | public synchronized void pauseDeployment(final String deployment, ServerActivityCallback listener) {
final List<ControlPoint> eps = new ArrayList<ControlPoint>();
for (ControlPoint ep : entryPoints.values()) {
if (ep.getDeployment().equals(deployment)) {
if(!ep.isPaused()) {
eps.add(ep);
}
}
}
CountingRequestCountCallback realListener = new CountingRequestCountCallback(eps.size(), listener);
for (ControlPoint ep : eps) {
ep.pause(realListener);
}
} | [
"public",
"synchronized",
"void",
"pauseDeployment",
"(",
"final",
"String",
"deployment",
",",
"ServerActivityCallback",
"listener",
")",
"{",
"final",
"List",
"<",
"ControlPoint",
">",
"eps",
"=",
"new",
"ArrayList",
"<",
"ControlPoint",
">",
"(",
")",
";",
... | Pauses a given deployment
@param deployment The deployment to pause
@param listener The listener that will be notified when the pause is complete | [
"Pauses",
"a",
"given",
"deployment"
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/request-controller/src/main/java/org/wildfly/extension/requestcontroller/RequestController.java#L136-L149 |
undertow-io/undertow | core/src/main/java/io/undertow/Handlers.java | Handlers.proxyHandler | public static ProxyHandler proxyHandler(ProxyClient proxyClient, HttpHandler next) {
return ProxyHandler.builder().setProxyClient(proxyClient).setNext(next).build();
} | java | public static ProxyHandler proxyHandler(ProxyClient proxyClient, HttpHandler next) {
return ProxyHandler.builder().setProxyClient(proxyClient).setNext(next).build();
} | [
"public",
"static",
"ProxyHandler",
"proxyHandler",
"(",
"ProxyClient",
"proxyClient",
",",
"HttpHandler",
"next",
")",
"{",
"return",
"ProxyHandler",
".",
"builder",
"(",
")",
".",
"setProxyClient",
"(",
"proxyClient",
")",
".",
"setNext",
"(",
"next",
")",
"... | Returns a handler that can act as a load balancing reverse proxy.
@param proxyClient The proxy client to use to connect to the remote server
@param next The next handler to invoke if the proxy client does not know how to proxy the request
@return The proxy handler | [
"Returns",
"a",
"handler",
"that",
"can",
"act",
"as",
"a",
"load",
"balancing",
"reverse",
"proxy",
"."
] | train | https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/Handlers.java#L498-L500 |
OpenHFT/Chronicle-Map | src/main/java/net/openhft/chronicle/hash/impl/stage/hash/Chaining.java | Chaining.initUsed | @Override
public void initUsed(boolean used, VanillaChronicleMap map) {
assert used;
firstContextLockedInThisThread = rootContextInThisThread.lockContextLocally(map);
initMap(map);
this.used = true;
} | java | @Override
public void initUsed(boolean used, VanillaChronicleMap map) {
assert used;
firstContextLockedInThisThread = rootContextInThisThread.lockContextLocally(map);
initMap(map);
this.used = true;
} | [
"@",
"Override",
"public",
"void",
"initUsed",
"(",
"boolean",
"used",
",",
"VanillaChronicleMap",
"map",
")",
"{",
"assert",
"used",
";",
"firstContextLockedInThisThread",
"=",
"rootContextInThisThread",
".",
"lockContextLocally",
"(",
"map",
")",
";",
"initMap",
... | Init method parameterized to avoid automatic initialization. {@code used} argument should
always be {@code true}. | [
"Init",
"method",
"parameterized",
"to",
"avoid",
"automatic",
"initialization",
".",
"{"
] | train | https://github.com/OpenHFT/Chronicle-Map/blob/0b09733cc96302f96be4394a261699eeb021fe37/src/main/java/net/openhft/chronicle/hash/impl/stage/hash/Chaining.java#L114-L120 |
offbynull/coroutines | instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/GenericGenerators.java | GenericGenerators.throwThrowable | public static InsnList throwThrowable() {
InsnList ret = new InsnList();
// ret.add(new TypeInsnNode(Opcodes.CHECKCAST, "java/lang/Throwable")); // If required, do it outside this method
ret.add(new InsnNode(Opcodes.ATHROW));
return ret;
} | java | public static InsnList throwThrowable() {
InsnList ret = new InsnList();
// ret.add(new TypeInsnNode(Opcodes.CHECKCAST, "java/lang/Throwable")); // If required, do it outside this method
ret.add(new InsnNode(Opcodes.ATHROW));
return ret;
} | [
"public",
"static",
"InsnList",
"throwThrowable",
"(",
")",
"{",
"InsnList",
"ret",
"=",
"new",
"InsnList",
"(",
")",
";",
"// ret.add(new TypeInsnNode(Opcodes.CHECKCAST, \"java/lang/Throwable\")); // If required, do it outside this method",
"ret",
".",
"add",
"(",
"ne... | Generates instructions to throw the exception type at top of stack. You may run in to problems if the item on top of the stack isn't
a {@link Throwable} type.
@return instructions to throw an exception
@throws NullPointerException if any argument is {@code null} | [
"Generates",
"instructions",
"to",
"throw",
"the",
"exception",
"type",
"at",
"top",
"of",
"stack",
".",
"You",
"may",
"run",
"in",
"to",
"problems",
"if",
"the",
"item",
"on",
"top",
"of",
"the",
"stack",
"isn",
"t",
"a",
"{"
] | train | https://github.com/offbynull/coroutines/blob/b1b83c293945f53a2f63fca8f15a53e88b796bf5/instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/GenericGenerators.java#L915-L922 |
Whiley/WhileyCompiler | src/main/java/wyc/io/WhileyFileParser.java | WhileyFileParser.parseArrayInitialiserExpression | private Expr parseArrayInitialiserExpression(EnclosingScope scope, boolean terminated) {
int start = index;
match(LeftSquare);
ArrayList<Expr> exprs = new ArrayList<>();
boolean firstTime = true;
while (eventuallyMatch(RightSquare) == null) {
if (!firstTime) {
match(Comma);
}
firstTime = false;
// NOTE: we require the following expression be a "non-tuple"
// expression. That is, it cannot be composed using ',' unless
// braces enclose the entire expression. This is because the outer
// list constructor expression is used ',' to distinguish elements.
// Also, expression is guaranteed to be terminated, either by ']' or
// ','.
exprs.add(parseExpression(scope, true));
}
// Convert to array
return annotateSourceLocation(new Expr.ArrayInitialiser(Type.Void, new Tuple<>(exprs)), start);
} | java | private Expr parseArrayInitialiserExpression(EnclosingScope scope, boolean terminated) {
int start = index;
match(LeftSquare);
ArrayList<Expr> exprs = new ArrayList<>();
boolean firstTime = true;
while (eventuallyMatch(RightSquare) == null) {
if (!firstTime) {
match(Comma);
}
firstTime = false;
// NOTE: we require the following expression be a "non-tuple"
// expression. That is, it cannot be composed using ',' unless
// braces enclose the entire expression. This is because the outer
// list constructor expression is used ',' to distinguish elements.
// Also, expression is guaranteed to be terminated, either by ']' or
// ','.
exprs.add(parseExpression(scope, true));
}
// Convert to array
return annotateSourceLocation(new Expr.ArrayInitialiser(Type.Void, new Tuple<>(exprs)), start);
} | [
"private",
"Expr",
"parseArrayInitialiserExpression",
"(",
"EnclosingScope",
"scope",
",",
"boolean",
"terminated",
")",
"{",
"int",
"start",
"=",
"index",
";",
"match",
"(",
"LeftSquare",
")",
";",
"ArrayList",
"<",
"Expr",
">",
"exprs",
"=",
"new",
"ArrayLis... | Parse an array initialiser expression, which is of the form:
<pre>
ArrayInitialiserExpr ::= '[' [ Expr (',' Expr)+ ] ']'
</pre>
@param scope
The enclosing scope for this statement, which determines the
set of visible (i.e. declared) variables and also the current
indentation level.
@param terminated
This indicates that the expression is known to be terminated
(or not). An expression that's known to be terminated is one
which is guaranteed to be followed by something. This is
important because it means that we can ignore any newline
characters encountered in parsing this expression, and that
we'll never overrun the end of the expression (i.e. because
there's guaranteed to be something which terminates this
expression). A classic situation where terminated is true is
when parsing an expression surrounded in braces. In such case,
we know the right-brace will always terminate this expression.
@return | [
"Parse",
"an",
"array",
"initialiser",
"expression",
"which",
"is",
"of",
"the",
"form",
":"
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyc/io/WhileyFileParser.java#L2686-L2706 |
elibom/jogger | src/main/java/com/elibom/jogger/http/servlet/multipart/ParameterParser.java | ParameterParser.parse | public Map<String,String> parse(final String str, char[] separators) {
if (separators == null || separators.length == 0) {
return new HashMap<String,String>();
}
char separator = separators[0];
if (str != null) {
int idx = str.length();
for (int i = 0; i < separators.length; i++) {
int tmp = str.indexOf(separators[i]);
if (tmp != -1) {
if (tmp < idx) {
idx = tmp;
separator = separators[i];
}
}
}
}
return parse(str, separator);
} | java | public Map<String,String> parse(final String str, char[] separators) {
if (separators == null || separators.length == 0) {
return new HashMap<String,String>();
}
char separator = separators[0];
if (str != null) {
int idx = str.length();
for (int i = 0; i < separators.length; i++) {
int tmp = str.indexOf(separators[i]);
if (tmp != -1) {
if (tmp < idx) {
idx = tmp;
separator = separators[i];
}
}
}
}
return parse(str, separator);
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"parse",
"(",
"final",
"String",
"str",
",",
"char",
"[",
"]",
"separators",
")",
"{",
"if",
"(",
"separators",
"==",
"null",
"||",
"separators",
".",
"length",
"==",
"0",
")",
"{",
"return",
"new",... | Extracts a map of name/value pairs from the given string. Names are expected to be unique. Multiple separators
may be specified and the earliest found in the input string is used.
@param str the string that contains a sequence of name/value pairs
@param separators the name/value pairs separators
@return a map of name/value pairs | [
"Extracts",
"a",
"map",
"of",
"name",
"/",
"value",
"pairs",
"from",
"the",
"given",
"string",
".",
"Names",
"are",
"expected",
"to",
"be",
"unique",
".",
"Multiple",
"separators",
"may",
"be",
"specified",
"and",
"the",
"earliest",
"found",
"in",
"the",
... | train | https://github.com/elibom/jogger/blob/d5892ff45e76328d444a68b5a38c26e7bdd0692b/src/main/java/com/elibom/jogger/http/servlet/multipart/ParameterParser.java#L208-L226 |
Alluxio/alluxio | core/server/common/src/main/java/alluxio/master/journal/JournalTool.java | JournalTool.parseInputArgs | private static boolean parseInputArgs(String[] args) {
CommandLineParser parser = new DefaultParser();
CommandLine cmd;
try {
cmd = parser.parse(OPTIONS, args);
} catch (ParseException e) {
System.out.println("Failed to parse input args: " + e);
return false;
}
sHelp = cmd.hasOption("help");
sMaster = cmd.getOptionValue("master", "FileSystemMaster");
sStart = Long.decode(cmd.getOptionValue("start", "0"));
sEnd = Long.decode(cmd.getOptionValue("end", Long.valueOf(Long.MAX_VALUE).toString()));
sOutputDir =
new File(cmd.getOptionValue("outputDir", "journal_dump-" + System.currentTimeMillis()))
.getAbsolutePath();
sCheckpointsDir = PathUtils.concatPath(sOutputDir, "checkpoints");
sJournalEntryFile = PathUtils.concatPath(sOutputDir, "edits.txt");
return true;
} | java | private static boolean parseInputArgs(String[] args) {
CommandLineParser parser = new DefaultParser();
CommandLine cmd;
try {
cmd = parser.parse(OPTIONS, args);
} catch (ParseException e) {
System.out.println("Failed to parse input args: " + e);
return false;
}
sHelp = cmd.hasOption("help");
sMaster = cmd.getOptionValue("master", "FileSystemMaster");
sStart = Long.decode(cmd.getOptionValue("start", "0"));
sEnd = Long.decode(cmd.getOptionValue("end", Long.valueOf(Long.MAX_VALUE).toString()));
sOutputDir =
new File(cmd.getOptionValue("outputDir", "journal_dump-" + System.currentTimeMillis()))
.getAbsolutePath();
sCheckpointsDir = PathUtils.concatPath(sOutputDir, "checkpoints");
sJournalEntryFile = PathUtils.concatPath(sOutputDir, "edits.txt");
return true;
} | [
"private",
"static",
"boolean",
"parseInputArgs",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"CommandLineParser",
"parser",
"=",
"new",
"DefaultParser",
"(",
")",
";",
"CommandLine",
"cmd",
";",
"try",
"{",
"cmd",
"=",
"parser",
".",
"parse",
"(",
"OPTIONS... | Parses the input args with a command line format, using
{@link org.apache.commons.cli.CommandLineParser}.
@param args the input args
@return true if parsing succeeded | [
"Parses",
"the",
"input",
"args",
"with",
"a",
"command",
"line",
"format",
"using",
"{",
"@link",
"org",
".",
"apache",
".",
"commons",
".",
"cli",
".",
"CommandLineParser",
"}",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/master/journal/JournalTool.java#L211-L230 |
igniterealtime/REST-API-Client | src/main/java/org/igniterealtime/restclient/RestApiClient.java | RestApiClient.deleteOwner | public Response deleteOwner(String roomName, String jid) {
return restClient.delete("chatrooms/" + roomName + "/owners/" + jid,
new HashMap<String, String>());
} | java | public Response deleteOwner(String roomName, String jid) {
return restClient.delete("chatrooms/" + roomName + "/owners/" + jid,
new HashMap<String, String>());
} | [
"public",
"Response",
"deleteOwner",
"(",
"String",
"roomName",
",",
"String",
"jid",
")",
"{",
"return",
"restClient",
".",
"delete",
"(",
"\"chatrooms/\"",
"+",
"roomName",
"+",
"\"/owners/\"",
"+",
"jid",
",",
"new",
"HashMap",
"<",
"String",
",",
"String... | Delete owner from chatroom.
@param roomName
the room name
@param jid
the jid
@return the response | [
"Delete",
"owner",
"from",
"chatroom",
"."
] | train | https://github.com/igniterealtime/REST-API-Client/blob/fd544dd770ec2ababa47fef51579522ddce09f05/src/main/java/org/igniterealtime/restclient/RestApiClient.java#L261-L264 |
powermock/powermock | powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java | PowerMock.createStrictPartialMockForAllMethodsExcept | public static synchronized <T> T createStrictPartialMockForAllMethodsExcept(Class<T> type,
String methodNameToExclude, Class<?> firstArgumentType, Class<?>... moreTypes) {
/*
* The reason why we've split the first and "additional types" is
* because it should not intervene with the mockAllExcept(type,
* String...methodNames) method.
*/
final Class<?>[] argumentTypes = mergeArgumentTypes(firstArgumentType, moreTypes);
return createStrictMock(type, WhiteboxImpl.getAllMethodsExcept(type, methodNameToExclude, argumentTypes));
} | java | public static synchronized <T> T createStrictPartialMockForAllMethodsExcept(Class<T> type,
String methodNameToExclude, Class<?> firstArgumentType, Class<?>... moreTypes) {
/*
* The reason why we've split the first and "additional types" is
* because it should not intervene with the mockAllExcept(type,
* String...methodNames) method.
*/
final Class<?>[] argumentTypes = mergeArgumentTypes(firstArgumentType, moreTypes);
return createStrictMock(type, WhiteboxImpl.getAllMethodsExcept(type, methodNameToExclude, argumentTypes));
} | [
"public",
"static",
"synchronized",
"<",
"T",
">",
"T",
"createStrictPartialMockForAllMethodsExcept",
"(",
"Class",
"<",
"T",
">",
"type",
",",
"String",
"methodNameToExclude",
",",
"Class",
"<",
"?",
">",
"firstArgumentType",
",",
"Class",
"<",
"?",
">",
"...... | Mock all methods of a class except for a specific one strictly. Use this
method only if you have several overloaded methods.
@param <T> The type of the mock.
@param type The type that'll be used to create a mock instance.
@param methodNameToExclude The name of the method not to mock.
@param firstArgumentType The type of the first parameter of the method not to mock
@param moreTypes Optionally more parameter types that defines the method. Note
that this is only needed to separate overloaded methods.
@return A mock object of type <T>. | [
"Mock",
"all",
"methods",
"of",
"a",
"class",
"except",
"for",
"a",
"specific",
"one",
"strictly",
".",
"Use",
"this",
"method",
"only",
"if",
"you",
"have",
"several",
"overloaded",
"methods",
"."
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L444-L454 |
mikepenz/FastAdapter | app/src/main/java/com/mikepenz/fastadapter/app/items/expandable/SimpleSubExpandableItem.java | SimpleSubExpandableItem.bindView | @Override
public void bindView(ViewHolder viewHolder, List<Object> payloads) {
super.bindView(viewHolder, payloads);
//get the context
Context ctx = viewHolder.itemView.getContext();
//set the background for the item
viewHolder.view.clearAnimation();
ViewCompat.setBackground(viewHolder.view, FastAdapterUIUtils.getSelectableBackground(ctx, Color.RED, true));
//set the text for the name
StringHolder.applyTo(name, viewHolder.name);
//set the text for the description or hide
StringHolder.applyToOrHide(description, viewHolder.description);
if (getSubItems() == null || getSubItems().size() == 0) {
viewHolder.icon.setVisibility(View.GONE);
} else {
viewHolder.icon.setVisibility(View.VISIBLE);
}
if (isExpanded()) {
ViewCompat.setRotation(viewHolder.icon, 0);
} else {
ViewCompat.setRotation(viewHolder.icon, 180);
}
} | java | @Override
public void bindView(ViewHolder viewHolder, List<Object> payloads) {
super.bindView(viewHolder, payloads);
//get the context
Context ctx = viewHolder.itemView.getContext();
//set the background for the item
viewHolder.view.clearAnimation();
ViewCompat.setBackground(viewHolder.view, FastAdapterUIUtils.getSelectableBackground(ctx, Color.RED, true));
//set the text for the name
StringHolder.applyTo(name, viewHolder.name);
//set the text for the description or hide
StringHolder.applyToOrHide(description, viewHolder.description);
if (getSubItems() == null || getSubItems().size() == 0) {
viewHolder.icon.setVisibility(View.GONE);
} else {
viewHolder.icon.setVisibility(View.VISIBLE);
}
if (isExpanded()) {
ViewCompat.setRotation(viewHolder.icon, 0);
} else {
ViewCompat.setRotation(viewHolder.icon, 180);
}
} | [
"@",
"Override",
"public",
"void",
"bindView",
"(",
"ViewHolder",
"viewHolder",
",",
"List",
"<",
"Object",
">",
"payloads",
")",
"{",
"super",
".",
"bindView",
"(",
"viewHolder",
",",
"payloads",
")",
";",
"//get the context",
"Context",
"ctx",
"=",
"viewHo... | binds the data of this item onto the viewHolder
@param viewHolder the viewHolder of this item | [
"binds",
"the",
"data",
"of",
"this",
"item",
"onto",
"the",
"viewHolder"
] | train | https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/app/src/main/java/com/mikepenz/fastadapter/app/items/expandable/SimpleSubExpandableItem.java#L130-L156 |
foundation-runtime/service-directory | 2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryServiceClient.java | DirectoryServiceClient.updateServiceInstanceStatus | public void updateServiceInstanceStatus(String serviceName, String instanceId, OperationalStatus status, final RegistrationCallback cb, Object context){
ProtocolHeader header = new ProtocolHeader();
header.setType(ProtocolType.UpdateServiceInstanceStatus);
UpdateServiceInstanceStatusProtocol p = new UpdateServiceInstanceStatusProtocol(serviceName, instanceId, status);
ProtocolCallback pcb = new ProtocolCallback(){
@Override
public void call(boolean result, Response response,
ErrorCode error, Object ctx) {
cb.call(result, error, ctx);
}
};
connection.submitCallbackRequest(header, p, pcb, context);
} | java | public void updateServiceInstanceStatus(String serviceName, String instanceId, OperationalStatus status, final RegistrationCallback cb, Object context){
ProtocolHeader header = new ProtocolHeader();
header.setType(ProtocolType.UpdateServiceInstanceStatus);
UpdateServiceInstanceStatusProtocol p = new UpdateServiceInstanceStatusProtocol(serviceName, instanceId, status);
ProtocolCallback pcb = new ProtocolCallback(){
@Override
public void call(boolean result, Response response,
ErrorCode error, Object ctx) {
cb.call(result, error, ctx);
}
};
connection.submitCallbackRequest(header, p, pcb, context);
} | [
"public",
"void",
"updateServiceInstanceStatus",
"(",
"String",
"serviceName",
",",
"String",
"instanceId",
",",
"OperationalStatus",
"status",
",",
"final",
"RegistrationCallback",
"cb",
",",
"Object",
"context",
")",
"{",
"ProtocolHeader",
"header",
"=",
"new",
"P... | Update ServiceInstance status with Callback.
@param serviceName
the servicename.
@param instanceId
the instanceId.
@param status
the OperationalStaus
@param cb
the Callback.
@param context
the context object. | [
"Update",
"ServiceInstance",
"status",
"with",
"Callback",
"."
] | train | https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryServiceClient.java#L423-L440 |
ironjacamar/ironjacamar | common/src/main/java/org/ironjacamar/common/metadata/common/CommonIronJacamarParser.java | CommonIronJacamarParser.storeSecurity | protected void storeSecurity(Security s, XMLStreamWriter writer) throws Exception
{
writer.writeStartElement(CommonXML.ELEMENT_SECURITY);
if (s.getSecurityDomain() != null)
{
writer.writeStartElement(CommonXML.ELEMENT_SECURITY_DOMAIN);
writer.writeCharacters(s.getValue(CommonXML.ELEMENT_SECURITY_DOMAIN, s.getSecurityDomain()));
writer.writeEndElement();
}
writer.writeEndElement();
} | java | protected void storeSecurity(Security s, XMLStreamWriter writer) throws Exception
{
writer.writeStartElement(CommonXML.ELEMENT_SECURITY);
if (s.getSecurityDomain() != null)
{
writer.writeStartElement(CommonXML.ELEMENT_SECURITY_DOMAIN);
writer.writeCharacters(s.getValue(CommonXML.ELEMENT_SECURITY_DOMAIN, s.getSecurityDomain()));
writer.writeEndElement();
}
writer.writeEndElement();
} | [
"protected",
"void",
"storeSecurity",
"(",
"Security",
"s",
",",
"XMLStreamWriter",
"writer",
")",
"throws",
"Exception",
"{",
"writer",
".",
"writeStartElement",
"(",
"CommonXML",
".",
"ELEMENT_SECURITY",
")",
";",
"if",
"(",
"s",
".",
"getSecurityDomain",
"(",... | Store security
@param s The security
@param writer The writer
@exception Exception Thrown if an error occurs | [
"Store",
"security"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/common/src/main/java/org/ironjacamar/common/metadata/common/CommonIronJacamarParser.java#L982-L994 |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/NetUtil.java | NetUtil.createURLFromInetAddress | public static URL createURLFromInetAddress(InetAddress pIP, String pProtocol) {
try {
return new URL(pProtocol, pIP.getHostName(), "");
}
catch (MalformedURLException e) {
return null;
}
} | java | public static URL createURLFromInetAddress(InetAddress pIP, String pProtocol) {
try {
return new URL(pProtocol, pIP.getHostName(), "");
}
catch (MalformedURLException e) {
return null;
}
} | [
"public",
"static",
"URL",
"createURLFromInetAddress",
"(",
"InetAddress",
"pIP",
",",
"String",
"pProtocol",
")",
"{",
"try",
"{",
"return",
"new",
"URL",
"(",
"pProtocol",
",",
"pIP",
".",
"getHostName",
"(",
")",
",",
"\"\"",
")",
";",
"}",
"catch",
"... | Creates an URL from the given InetAddress object, using the given
protocol.
Equivalent to calling
{@code new URL(protocol, InetAddress.getHostName(), "")}
except that it returns null, instead of throwing MalformedURLException.
@param pIP the IP address to look up
@param pProtocol the protocol to use in the new URL
@return the created URL or null, if the URL could not be created.
@see java.net.URL
@see java.net.InetAddress | [
"Creates",
"an",
"URL",
"from",
"the",
"given",
"InetAddress",
"object",
"using",
"the",
"given",
"protocol",
".",
"Equivalent",
"to",
"calling",
"{",
"@code",
"new",
"URL",
"(",
"protocol",
"InetAddress",
".",
"getHostName",
"()",
")",
"}",
"except",
"that"... | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/NetUtil.java#L1207-L1214 |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/examples/SlashdotPolicyExample.java | SlashdotPolicyExample.main | public static void main(String[] args) throws IOException {
if (args.length != 0) {
System.err.println("Reads from STDIN and writes to STDOUT");
System.exit(-1);
}
System.err.println("[Reading from STDIN]");
// Fetch the HTML to sanitize.
String html = CharStreams.toString(
new InputStreamReader(System.in, Charsets.UTF_8));
// Set up an output channel to receive the sanitized HTML.
HtmlStreamRenderer renderer = HtmlStreamRenderer.create(
System.out,
// Receives notifications on a failure to write to the output.
new Handler<IOException>() {
public void handle(IOException ex) {
// System.out suppresses IOExceptions
throw new AssertionError(null, ex);
}
},
// Our HTML parser is very lenient, but this receives notifications on
// truly bizarre inputs.
new Handler<String>() {
public void handle(String x) {
throw new AssertionError(x);
}
});
// Use the policy defined above to sanitize the HTML.
HtmlSanitizer.sanitize(html, POLICY_DEFINITION.apply(renderer));
} | java | public static void main(String[] args) throws IOException {
if (args.length != 0) {
System.err.println("Reads from STDIN and writes to STDOUT");
System.exit(-1);
}
System.err.println("[Reading from STDIN]");
// Fetch the HTML to sanitize.
String html = CharStreams.toString(
new InputStreamReader(System.in, Charsets.UTF_8));
// Set up an output channel to receive the sanitized HTML.
HtmlStreamRenderer renderer = HtmlStreamRenderer.create(
System.out,
// Receives notifications on a failure to write to the output.
new Handler<IOException>() {
public void handle(IOException ex) {
// System.out suppresses IOExceptions
throw new AssertionError(null, ex);
}
},
// Our HTML parser is very lenient, but this receives notifications on
// truly bizarre inputs.
new Handler<String>() {
public void handle(String x) {
throw new AssertionError(x);
}
});
// Use the policy defined above to sanitize the HTML.
HtmlSanitizer.sanitize(html, POLICY_DEFINITION.apply(renderer));
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"throws",
"IOException",
"{",
"if",
"(",
"args",
".",
"length",
"!=",
"0",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"\"Reads from STDIN and writes to STDOUT\"",
")",
";",... | A test-bed that reads HTML from stdin and writes sanitized content to
stdout. | [
"A",
"test",
"-",
"bed",
"that",
"reads",
"HTML",
"from",
"stdin",
"and",
"writes",
"sanitized",
"content",
"to",
"stdout",
"."
] | train | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/examples/SlashdotPolicyExample.java#L95-L123 |
TheHortonMachine/hortonmachine | dbs/src/main/java/org/hortonmachine/dbs/compat/ASpatialDb.java | ASpatialDb.createSpatialTable | public void createSpatialTable( String tableName, int tableSrid, String geometryFieldData, String[] fieldData )
throws Exception {
createSpatialTable(tableName, tableSrid, geometryFieldData, fieldData, null, false);
} | java | public void createSpatialTable( String tableName, int tableSrid, String geometryFieldData, String[] fieldData )
throws Exception {
createSpatialTable(tableName, tableSrid, geometryFieldData, fieldData, null, false);
} | [
"public",
"void",
"createSpatialTable",
"(",
"String",
"tableName",
",",
"int",
"tableSrid",
",",
"String",
"geometryFieldData",
",",
"String",
"[",
"]",
"fieldData",
")",
"throws",
"Exception",
"{",
"createSpatialTable",
"(",
"tableName",
",",
"tableSrid",
",",
... | Creates a spatial table with default values for foreign keys and index.
@param tableName
the table name.
@param tableSrid the table's epsg code.
@param geometryFieldData the data for the geometry column, ex. the_geom MULTIPOLYGON
@param fieldData
the data for each the field (ex. id INTEGER NOT NULL PRIMARY
KEY).
@throws Exception | [
"Creates",
"a",
"spatial",
"table",
"with",
"default",
"values",
"for",
"foreign",
"keys",
"and",
"index",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/org/hortonmachine/dbs/compat/ASpatialDb.java#L86-L89 |
lessthanoptimal/ejml | main/ejml-core/src/org/ejml/ops/ReadMatrixCsv.java | ReadMatrixCsv.readDDRM | public DMatrixRMaj readDDRM(int numRows, int numCols) throws IOException {
DMatrixRMaj A = new DMatrixRMaj(numRows,numCols);
for( int i = 0; i < numRows; i++ ) {
List<String> words = extractWords();
if( words == null )
throw new IOException("Too few rows found. expected "+numRows+" actual "+i);
if( words.size() != numCols )
throw new IOException("Unexpected number of words in column. Found "+words.size()+" expected "+numCols);
for( int j = 0; j < numCols; j++ ) {
A.set(i,j,Double.parseDouble(words.get(j)));
}
}
return A;
} | java | public DMatrixRMaj readDDRM(int numRows, int numCols) throws IOException {
DMatrixRMaj A = new DMatrixRMaj(numRows,numCols);
for( int i = 0; i < numRows; i++ ) {
List<String> words = extractWords();
if( words == null )
throw new IOException("Too few rows found. expected "+numRows+" actual "+i);
if( words.size() != numCols )
throw new IOException("Unexpected number of words in column. Found "+words.size()+" expected "+numCols);
for( int j = 0; j < numCols; j++ ) {
A.set(i,j,Double.parseDouble(words.get(j)));
}
}
return A;
} | [
"public",
"DMatrixRMaj",
"readDDRM",
"(",
"int",
"numRows",
",",
"int",
"numCols",
")",
"throws",
"IOException",
"{",
"DMatrixRMaj",
"A",
"=",
"new",
"DMatrixRMaj",
"(",
"numRows",
",",
"numCols",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"... | Reads in a {@link DMatrixRMaj} from the IO stream where the user specifies the matrix dimensions.
@param numRows Number of rows in the matrix
@param numCols Number of columns in the matrix
@return DMatrixRMaj
@throws IOException | [
"Reads",
"in",
"a",
"{",
"@link",
"DMatrixRMaj",
"}",
"from",
"the",
"IO",
"stream",
"where",
"the",
"user",
"specifies",
"the",
"matrix",
"dimensions",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-core/src/org/ejml/ops/ReadMatrixCsv.java#L128-L145 |
diffplug/JMatIO | src/main/java/ca/mjdsystems/jmatio/types/MLNumericArray.java | MLNumericArray.directByteBufferEquals | private static boolean directByteBufferEquals(ByteBuffer buffa, ByteBuffer buffb)
{
if ( buffa == buffb )
{
return true;
}
if ( buffa ==null || buffb == null )
{
return false;
}
buffa.rewind();
buffb.rewind();
int length = buffa.remaining();
if ( buffb.remaining() != length )
{
return false;
}
for ( int i = 0; i < length; i++ )
{
if ( buffa.get() != buffb.get() )
{
return false;
}
}
return true;
} | java | private static boolean directByteBufferEquals(ByteBuffer buffa, ByteBuffer buffb)
{
if ( buffa == buffb )
{
return true;
}
if ( buffa ==null || buffb == null )
{
return false;
}
buffa.rewind();
buffb.rewind();
int length = buffa.remaining();
if ( buffb.remaining() != length )
{
return false;
}
for ( int i = 0; i < length; i++ )
{
if ( buffa.get() != buffb.get() )
{
return false;
}
}
return true;
} | [
"private",
"static",
"boolean",
"directByteBufferEquals",
"(",
"ByteBuffer",
"buffa",
",",
"ByteBuffer",
"buffb",
")",
"{",
"if",
"(",
"buffa",
"==",
"buffb",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"buffa",
"==",
"null",
"||",
"buffb",
"==",
"n... | Equals implementation for direct <code>ByteBuffer</code>
@param buffa the source buffer to be compared
@param buffb the destination buffer to be compared
@return <code>true</code> if buffers are equal in terms of content | [
"Equals",
"implementation",
"for",
"direct",
"<code",
">",
"ByteBuffer<",
"/",
"code",
">"
] | train | https://github.com/diffplug/JMatIO/blob/dab8a54fa21a8faeaa81537cdc45323c5c4e6ca6/src/main/java/ca/mjdsystems/jmatio/types/MLNumericArray.java#L354-L385 |
fozziethebeat/S-Space | src/main/java/edu/ucla/sspace/tools/SemanticSpaceExplorer.java | SemanticSpaceExplorer.getCurrentSSpaceFileName | private String getCurrentSSpaceFileName() {
// REMINDER: This instruction is expected to be rare, so rather than
// save the name and require a lookup every time the current sspace
// is needed, we use an O(n) call to find the name as necessary
for (Map.Entry<String,SemanticSpace> e : fileNameToSSpace.entrySet()) {
if (e.getValue() == current) {
return e.getKey();
}
}
return null;
} | java | private String getCurrentSSpaceFileName() {
// REMINDER: This instruction is expected to be rare, so rather than
// save the name and require a lookup every time the current sspace
// is needed, we use an O(n) call to find the name as necessary
for (Map.Entry<String,SemanticSpace> e : fileNameToSSpace.entrySet()) {
if (e.getValue() == current) {
return e.getKey();
}
}
return null;
} | [
"private",
"String",
"getCurrentSSpaceFileName",
"(",
")",
"{",
"// REMINDER: This instruction is expected to be rare, so rather than",
"// save the name and require a lookup every time the current sspace",
"// is needed, we use an O(n) call to find the name as necessary",
"for",
"(",
"Map",
... | Returns the name of the file form which the current {@code SemanticSpace}
was loaded, or {@code null} if no semantic space is currently open.
@return the name of the file from which the current space was loaded | [
"Returns",
"the",
"name",
"of",
"the",
"file",
"form",
"which",
"the",
"current",
"{",
"@code",
"SemanticSpace",
"}",
"was",
"loaded",
"or",
"{",
"@code",
"null",
"}",
"if",
"no",
"semantic",
"space",
"is",
"currently",
"open",
"."
] | train | https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/tools/SemanticSpaceExplorer.java#L150-L160 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/internal/KernelResolver.java | KernelResolver.addBootJars | private void addBootJars(List<File> jarFiles, List<URL> urlList) {
for (File jarFile : jarFiles) {
try {
urlList.add(jarFile.toURI().toURL());
} catch (MalformedURLException e) {
// Unlikely: we're making URLs for files we know exist
}
}
} | java | private void addBootJars(List<File> jarFiles, List<URL> urlList) {
for (File jarFile : jarFiles) {
try {
urlList.add(jarFile.toURI().toURL());
} catch (MalformedURLException e) {
// Unlikely: we're making URLs for files we know exist
}
}
} | [
"private",
"void",
"addBootJars",
"(",
"List",
"<",
"File",
">",
"jarFiles",
",",
"List",
"<",
"URL",
">",
"urlList",
")",
"{",
"for",
"(",
"File",
"jarFile",
":",
"jarFiles",
")",
"{",
"try",
"{",
"urlList",
".",
"add",
"(",
"jarFile",
".",
"toURI",... | Given the list of files, add the URL for each file to the list of URLs
@param jarFiles List of Files (source)
@param urlList List of URLs (target) | [
"Given",
"the",
"list",
"of",
"files",
"add",
"the",
"URL",
"for",
"each",
"file",
"to",
"the",
"list",
"of",
"URLs"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/internal/KernelResolver.java#L252-L260 |
lukas-krecan/JsonUnit | json-unit/src/main/java/net/javacrumbs/jsonunit/JsonAssert.java | JsonAssert.setOptions | public static void setOptions(Option firstOption, Option... rest) {
configuration = configuration.withOptions(Options.empty().with(firstOption, rest));
} | java | public static void setOptions(Option firstOption, Option... rest) {
configuration = configuration.withOptions(Options.empty().with(firstOption, rest));
} | [
"public",
"static",
"void",
"setOptions",
"(",
"Option",
"firstOption",
",",
"Option",
"...",
"rest",
")",
"{",
"configuration",
"=",
"configuration",
".",
"withOptions",
"(",
"Options",
".",
"empty",
"(",
")",
".",
"with",
"(",
"firstOption",
",",
"rest",
... | Sets options changing comparison behavior. For more
details see {@link net.javacrumbs.jsonunit.core.Option}
@see net.javacrumbs.jsonunit.core.Option | [
"Sets",
"options",
"changing",
"comparison",
"behavior",
".",
"For",
"more",
"details",
"see",
"{",
"@link",
"net",
".",
"javacrumbs",
".",
"jsonunit",
".",
"core",
".",
"Option",
"}"
] | train | https://github.com/lukas-krecan/JsonUnit/blob/2b12ed792e8dd787bddd6f3b8eb2325737435791/json-unit/src/main/java/net/javacrumbs/jsonunit/JsonAssert.java#L242-L244 |
Appendium/flatpack | flatpack/src/main/java/net/sf/flatpack/AbstractParser.java | AbstractParser.addError | protected void addError(final DefaultDataSet ds, final String errorDesc, final int lineNo, final int errorLevel) {
addError(ds, errorDesc, lineNo, errorLevel, null);
} | java | protected void addError(final DefaultDataSet ds, final String errorDesc, final int lineNo, final int errorLevel) {
addError(ds, errorDesc, lineNo, errorLevel, null);
} | [
"protected",
"void",
"addError",
"(",
"final",
"DefaultDataSet",
"ds",
",",
"final",
"String",
"errorDesc",
",",
"final",
"int",
"lineNo",
",",
"final",
"int",
"errorLevel",
")",
"{",
"addError",
"(",
"ds",
",",
"errorDesc",
",",
"lineNo",
",",
"errorLevel",... | Adds a new error to this DataSet. These can be collected, and retrieved
after processing
@param ds
the dataset
@param errorDesc
String description of error
@param lineNo
line number error occurred on
@param errorLevel
errorLevel 1,2,3 1=warning 2=error 3= severe error | [
"Adds",
"a",
"new",
"error",
"to",
"this",
"DataSet",
".",
"These",
"can",
"be",
"collected",
"and",
"retrieved",
"after",
"processing"
] | train | https://github.com/Appendium/flatpack/blob/5e09875d97db7038e3ba6af9468f5313d99b0082/flatpack/src/main/java/net/sf/flatpack/AbstractParser.java#L256-L258 |
jenkinsci/jenkins | core/src/main/java/hudson/util/Iterators.java | Iterators.reverseSequence | public static List<Integer> reverseSequence(int start, int end, int step) {
return sequence(end-1,start-1,-step);
} | java | public static List<Integer> reverseSequence(int start, int end, int step) {
return sequence(end-1,start-1,-step);
} | [
"public",
"static",
"List",
"<",
"Integer",
">",
"reverseSequence",
"(",
"int",
"start",
",",
"int",
"end",
",",
"int",
"step",
")",
"{",
"return",
"sequence",
"(",
"end",
"-",
"1",
",",
"start",
"-",
"1",
",",
"-",
"step",
")",
";",
"}"
] | The short cut for {@code reverse(sequence(start,end,step))}.
@since 1.150 | [
"The",
"short",
"cut",
"for",
"{",
"@code",
"reverse",
"(",
"sequence",
"(",
"start",
"end",
"step",
"))",
"}",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/util/Iterators.java#L253-L255 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/v3/MetricServiceClient.java | MetricServiceClient.createTimeSeries | public final void createTimeSeries(String name, List<TimeSeries> timeSeries) {
CreateTimeSeriesRequest request =
CreateTimeSeriesRequest.newBuilder().setName(name).addAllTimeSeries(timeSeries).build();
createTimeSeries(request);
} | java | public final void createTimeSeries(String name, List<TimeSeries> timeSeries) {
CreateTimeSeriesRequest request =
CreateTimeSeriesRequest.newBuilder().setName(name).addAllTimeSeries(timeSeries).build();
createTimeSeries(request);
} | [
"public",
"final",
"void",
"createTimeSeries",
"(",
"String",
"name",
",",
"List",
"<",
"TimeSeries",
">",
"timeSeries",
")",
"{",
"CreateTimeSeriesRequest",
"request",
"=",
"CreateTimeSeriesRequest",
".",
"newBuilder",
"(",
")",
".",
"setName",
"(",
"name",
")"... | Creates or adds data to one or more time series. The response is empty if all time series in
the request were written. If any time series could not be written, a corresponding failure
message is included in the error response.
<p>Sample code:
<pre><code>
try (MetricServiceClient metricServiceClient = MetricServiceClient.create()) {
ProjectName name = ProjectName.of("[PROJECT]");
List<TimeSeries> timeSeries = new ArrayList<>();
metricServiceClient.createTimeSeries(name.toString(), timeSeries);
}
</code></pre>
@param name The project on which to execute the request. The format is
`"projects/{project_id_or_number}"`.
@param timeSeries The new data to be added to a list of time series. Adds at most one data
point to each of several time series. The new data point must be more recent than any other
point in its time series. Each `TimeSeries` value must fully specify a unique time series
by supplying all label values for the metric and the monitored resource.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"or",
"adds",
"data",
"to",
"one",
"or",
"more",
"time",
"series",
".",
"The",
"response",
"is",
"empty",
"if",
"all",
"time",
"series",
"in",
"the",
"request",
"were",
"written",
".",
"If",
"any",
"time",
"series",
"could",
"not",
"be",
"wr... | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/v3/MetricServiceClient.java#L1125-L1130 |
Impetus/Kundera | src/kundera-kudu/src/main/java/com/impetus/client/kudu/query/KuduDBQuery.java | KuduDBQuery.parseAndBuildFilters | private void parseAndBuildFilters(EntityType entityType, KuduScannerBuilder scannerBuilder, Expression whereExp)
{
if (whereExp instanceof ComparisonExpression)
{
String left = ((ComparisonExpression) whereExp).getLeftExpression().toActualText();
String right = ((ComparisonExpression) whereExp).getRightExpression().toActualText();
if (right.startsWith(POSITIONAL_PREFIX) || right.startsWith(PARAMETERIZED_PREFIX))
{
right = kunderaQuery.getParametersMap().get(right) + "";
}
Attribute attribute = entityType.getAttribute(left.split(DOT_REGEX)[1]);
addColumnRangePredicateToBuilder((Field) attribute.getJavaMember(), scannerBuilder,
((AbstractAttribute) attribute).getJPAColumnName(), right,
((ComparisonExpression) whereExp).getActualIdentifier());
}
else if (whereExp instanceof AndExpression)
{
parseAndBuildFilters(entityType, scannerBuilder, ((AndExpression) whereExp).getLeftExpression());
parseAndBuildFilters(entityType, scannerBuilder, ((AndExpression) whereExp).getRightExpression());
}
else if (whereExp instanceof InExpression)
{
ListIterator<Expression> inIter = ((InExpression) whereExp).getInItems().children().iterator();
Attribute attribute = entityType.getAttribute(((InExpression) whereExp).getExpression().toActualText()
.split(DOT_REGEX)[1]);
addInPredicateToBuilder(scannerBuilder, inIter, attribute);
}
else
{
logger.error("Operation not supported");
throw new KunderaException("Operation not supported");
}
} | java | private void parseAndBuildFilters(EntityType entityType, KuduScannerBuilder scannerBuilder, Expression whereExp)
{
if (whereExp instanceof ComparisonExpression)
{
String left = ((ComparisonExpression) whereExp).getLeftExpression().toActualText();
String right = ((ComparisonExpression) whereExp).getRightExpression().toActualText();
if (right.startsWith(POSITIONAL_PREFIX) || right.startsWith(PARAMETERIZED_PREFIX))
{
right = kunderaQuery.getParametersMap().get(right) + "";
}
Attribute attribute = entityType.getAttribute(left.split(DOT_REGEX)[1]);
addColumnRangePredicateToBuilder((Field) attribute.getJavaMember(), scannerBuilder,
((AbstractAttribute) attribute).getJPAColumnName(), right,
((ComparisonExpression) whereExp).getActualIdentifier());
}
else if (whereExp instanceof AndExpression)
{
parseAndBuildFilters(entityType, scannerBuilder, ((AndExpression) whereExp).getLeftExpression());
parseAndBuildFilters(entityType, scannerBuilder, ((AndExpression) whereExp).getRightExpression());
}
else if (whereExp instanceof InExpression)
{
ListIterator<Expression> inIter = ((InExpression) whereExp).getInItems().children().iterator();
Attribute attribute = entityType.getAttribute(((InExpression) whereExp).getExpression().toActualText()
.split(DOT_REGEX)[1]);
addInPredicateToBuilder(scannerBuilder, inIter, attribute);
}
else
{
logger.error("Operation not supported");
throw new KunderaException("Operation not supported");
}
} | [
"private",
"void",
"parseAndBuildFilters",
"(",
"EntityType",
"entityType",
",",
"KuduScannerBuilder",
"scannerBuilder",
",",
"Expression",
"whereExp",
")",
"{",
"if",
"(",
"whereExp",
"instanceof",
"ComparisonExpression",
")",
"{",
"String",
"left",
"=",
"(",
"(",
... | Parses the and build filters.
@param entityType
the entity type
@param scannerBuilder
the scanner builder
@param whereExp
the where exp | [
"Parses",
"the",
"and",
"build",
"filters",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-kudu/src/main/java/com/impetus/client/kudu/query/KuduDBQuery.java#L191-L226 |
reactor/reactor-netty | src/main/java/reactor/netty/http/client/HttpClient.java | HttpClient.doAfterRequest | public final HttpClient doAfterRequest(BiConsumer<? super HttpClientRequest, ? super Connection> doAfterRequest) {
Objects.requireNonNull(doAfterRequest, "doAfterRequest");
return new HttpClientDoOn(this, null, doAfterRequest, null, null);
} | java | public final HttpClient doAfterRequest(BiConsumer<? super HttpClientRequest, ? super Connection> doAfterRequest) {
Objects.requireNonNull(doAfterRequest, "doAfterRequest");
return new HttpClientDoOn(this, null, doAfterRequest, null, null);
} | [
"public",
"final",
"HttpClient",
"doAfterRequest",
"(",
"BiConsumer",
"<",
"?",
"super",
"HttpClientRequest",
",",
"?",
"super",
"Connection",
">",
"doAfterRequest",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"doAfterRequest",
",",
"\"doAfterRequest\"",
")",
... | Setup a callback called when {@link HttpClientRequest} has been sent
@param doAfterRequest a consumer observing connected events
@return a new {@link HttpClient} | [
"Setup",
"a",
"callback",
"called",
"when",
"{",
"@link",
"HttpClientRequest",
"}",
"has",
"been",
"sent"
] | train | https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/http/client/HttpClient.java#L543-L546 |
Azure/azure-sdk-for-java | locks/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/locks/v2016_09_01/implementation/ManagementLocksInner.java | ManagementLocksInner.createOrUpdateByScopeAsync | public Observable<ManagementLockObjectInner> createOrUpdateByScopeAsync(String scope, String lockName, ManagementLockObjectInner parameters) {
return createOrUpdateByScopeWithServiceResponseAsync(scope, lockName, parameters).map(new Func1<ServiceResponse<ManagementLockObjectInner>, ManagementLockObjectInner>() {
@Override
public ManagementLockObjectInner call(ServiceResponse<ManagementLockObjectInner> response) {
return response.body();
}
});
} | java | public Observable<ManagementLockObjectInner> createOrUpdateByScopeAsync(String scope, String lockName, ManagementLockObjectInner parameters) {
return createOrUpdateByScopeWithServiceResponseAsync(scope, lockName, parameters).map(new Func1<ServiceResponse<ManagementLockObjectInner>, ManagementLockObjectInner>() {
@Override
public ManagementLockObjectInner call(ServiceResponse<ManagementLockObjectInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ManagementLockObjectInner",
">",
"createOrUpdateByScopeAsync",
"(",
"String",
"scope",
",",
"String",
"lockName",
",",
"ManagementLockObjectInner",
"parameters",
")",
"{",
"return",
"createOrUpdateByScopeWithServiceResponseAsync",
"(",
"scope",
... | Create or update a management lock by scope.
@param scope The scope for the lock. When providing a scope for the assignment, use '/subscriptions/{subscriptionId}' for subscriptions, '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' for resources.
@param lockName The name of lock.
@param parameters Create or update management lock parameters.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ManagementLockObjectInner object | [
"Create",
"or",
"update",
"a",
"management",
"lock",
"by",
"scope",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/locks/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/locks/v2016_09_01/implementation/ManagementLocksInner.java#L453-L460 |
Omertron/api-themoviedb | src/main/java/com/omertron/themoviedbapi/methods/TmdbSeasons.java | TmdbSeasons.getSeasonInfo | public TVSeasonInfo getSeasonInfo(int tvID, int seasonNumber, String language, String... appendToResponse) throws MovieDbException {
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, tvID);
parameters.add(Param.SEASON_NUMBER, seasonNumber);
parameters.add(Param.LANGUAGE, language);
parameters.add(Param.APPEND, appendToResponse);
URL url = new ApiUrl(apiKey, MethodBase.SEASON).buildUrl(parameters);
String webpage = httpTools.getRequest(url);
try {
return MAPPER.readValue(webpage, TVSeasonInfo.class);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get TV Season Info", url, ex);
}
} | java | public TVSeasonInfo getSeasonInfo(int tvID, int seasonNumber, String language, String... appendToResponse) throws MovieDbException {
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, tvID);
parameters.add(Param.SEASON_NUMBER, seasonNumber);
parameters.add(Param.LANGUAGE, language);
parameters.add(Param.APPEND, appendToResponse);
URL url = new ApiUrl(apiKey, MethodBase.SEASON).buildUrl(parameters);
String webpage = httpTools.getRequest(url);
try {
return MAPPER.readValue(webpage, TVSeasonInfo.class);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get TV Season Info", url, ex);
}
} | [
"public",
"TVSeasonInfo",
"getSeasonInfo",
"(",
"int",
"tvID",
",",
"int",
"seasonNumber",
",",
"String",
"language",
",",
"String",
"...",
"appendToResponse",
")",
"throws",
"MovieDbException",
"{",
"TmdbParameters",
"parameters",
"=",
"new",
"TmdbParameters",
"(",... | Get the primary information about a TV season by its season number.
@param tvID
@param seasonNumber
@param language
@param appendToResponse
@return
@throws MovieDbException | [
"Get",
"the",
"primary",
"information",
"about",
"a",
"TV",
"season",
"by",
"its",
"season",
"number",
"."
] | train | https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbSeasons.java#L71-L86 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/io/las/index/strtree/STRtreeJGT.java | STRtreeJGT.createParentBoundables | protected List createParentBoundables( List childBoundables, int newLevel ) {
Assert.isTrue(!childBoundables.isEmpty());
int minLeafCount = (int) Math.ceil((childBoundables.size() / (double) getNodeCapacity()));
ArrayList sortedChildBoundables = new ArrayList(childBoundables);
Collections.sort(sortedChildBoundables, xComparator);
List[] verticalSlices = verticalSlices(sortedChildBoundables, (int) Math.ceil(Math.sqrt(minLeafCount)));
return createParentBoundablesFromVerticalSlices(verticalSlices, newLevel);
} | java | protected List createParentBoundables( List childBoundables, int newLevel ) {
Assert.isTrue(!childBoundables.isEmpty());
int minLeafCount = (int) Math.ceil((childBoundables.size() / (double) getNodeCapacity()));
ArrayList sortedChildBoundables = new ArrayList(childBoundables);
Collections.sort(sortedChildBoundables, xComparator);
List[] verticalSlices = verticalSlices(sortedChildBoundables, (int) Math.ceil(Math.sqrt(minLeafCount)));
return createParentBoundablesFromVerticalSlices(verticalSlices, newLevel);
} | [
"protected",
"List",
"createParentBoundables",
"(",
"List",
"childBoundables",
",",
"int",
"newLevel",
")",
"{",
"Assert",
".",
"isTrue",
"(",
"!",
"childBoundables",
".",
"isEmpty",
"(",
")",
")",
";",
"int",
"minLeafCount",
"=",
"(",
"int",
")",
"Math",
... | Creates the parent level for the given child level. First, orders the items
by the x-values of the midpoints, and groups them into vertical slices.
For each slice, orders the items by the y-values of the midpoints, and
group them into runs of size M (the node capacity). For each run, creates
a new (parent) node. | [
"Creates",
"the",
"parent",
"level",
"for",
"the",
"given",
"child",
"level",
".",
"First",
"orders",
"the",
"items",
"by",
"the",
"x",
"-",
"values",
"of",
"the",
"midpoints",
"and",
"groups",
"them",
"into",
"vertical",
"slices",
".",
"For",
"each",
"s... | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/las/index/strtree/STRtreeJGT.java#L108-L115 |
google/error-prone | check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessPropagationTransfer.java | NullnessPropagationTransfer.visitArrayAccess | @Override
Nullness visitArrayAccess(ArrayAccessNode node, SubNodeValues inputs, Updates updates) {
setNonnullIfTrackable(updates, node.getArray());
return hasPrimitiveType(node) ? NONNULL : defaultAssumption;
} | java | @Override
Nullness visitArrayAccess(ArrayAccessNode node, SubNodeValues inputs, Updates updates) {
setNonnullIfTrackable(updates, node.getArray());
return hasPrimitiveType(node) ? NONNULL : defaultAssumption;
} | [
"@",
"Override",
"Nullness",
"visitArrayAccess",
"(",
"ArrayAccessNode",
"node",
",",
"SubNodeValues",
"inputs",
",",
"Updates",
"updates",
")",
"{",
"setNonnullIfTrackable",
"(",
"updates",
",",
"node",
".",
"getArray",
"(",
")",
")",
";",
"return",
"hasPrimiti... | Refines the accessed array to non-null after a successful array access.
<p>Note: If the array access occurs when the node is an l-value, the analysis won't call this
method. Instead, it will call {@link #visitAssignment}. | [
"Refines",
"the",
"accessed",
"array",
"to",
"non",
"-",
"null",
"after",
"a",
"successful",
"array",
"access",
"."
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessPropagationTransfer.java#L551-L555 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/LabelsApi.java | LabelsApi.updateLabel | public Label updateLabel(Object projectIdOrPath, String name, String newName, String color, String description, Integer priority) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("name", name, true)
.withParam("new_name", newName)
.withParam("color", color)
.withParam("description", description)
.withParam("priority", priority);
Response response = put(Response.Status.OK, formData.asMap(),
"projects", getProjectIdOrPath(projectIdOrPath), "labels");
return (response.readEntity(Label.class));
} | java | public Label updateLabel(Object projectIdOrPath, String name, String newName, String color, String description, Integer priority) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("name", name, true)
.withParam("new_name", newName)
.withParam("color", color)
.withParam("description", description)
.withParam("priority", priority);
Response response = put(Response.Status.OK, formData.asMap(),
"projects", getProjectIdOrPath(projectIdOrPath), "labels");
return (response.readEntity(Label.class));
} | [
"public",
"Label",
"updateLabel",
"(",
"Object",
"projectIdOrPath",
",",
"String",
"name",
",",
"String",
"newName",
",",
"String",
"color",
",",
"String",
"description",
",",
"Integer",
"priority",
")",
"throws",
"GitLabApiException",
"{",
"GitLabApiForm",
"formD... | Update the specified label
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param name the name for the label
@param newName the new name for the label
@param color the color for the label
@param description the description for the label
@param priority the priority for the label
@return the modified Label instance
@throws GitLabApiException if any exception occurs | [
"Update",
"the",
"specified",
"label"
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/LabelsApi.java#L174-L185 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/ThreadLocalRandom.java | ThreadLocalRandom.nextInt | public int nextInt(int origin, int bound) {
if (origin >= bound)
throw new IllegalArgumentException(BAD_RANGE);
return internalNextInt(origin, bound);
} | java | public int nextInt(int origin, int bound) {
if (origin >= bound)
throw new IllegalArgumentException(BAD_RANGE);
return internalNextInt(origin, bound);
} | [
"public",
"int",
"nextInt",
"(",
"int",
"origin",
",",
"int",
"bound",
")",
"{",
"if",
"(",
"origin",
">=",
"bound",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"BAD_RANGE",
")",
";",
"return",
"internalNextInt",
"(",
"origin",
",",
"bound",
")",... | Returns a pseudorandom {@code int} value between the specified
origin (inclusive) and the specified bound (exclusive).
@param origin the least value returned
@param bound the upper bound (exclusive)
@return a pseudorandom {@code int} value between the origin
(inclusive) and the bound (exclusive)
@throws IllegalArgumentException if {@code origin} is greater than
or equal to {@code bound} | [
"Returns",
"a",
"pseudorandom",
"{",
"@code",
"int",
"}",
"value",
"between",
"the",
"specified",
"origin",
"(",
"inclusive",
")",
"and",
"the",
"specified",
"bound",
"(",
"exclusive",
")",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/ThreadLocalRandom.java#L322-L326 |
micronaut-projects/micronaut-core | inject/src/main/java/io/micronaut/inject/annotation/AnnotationMetadataSupport.java | AnnotationMetadataSupport.registerDefaultValues | static void registerDefaultValues(AnnotationClassValue<?> annotation, Map<String, Object> defaultValues) {
if (defaultValues != null) {
registerDefaultValues(annotation.getName(), defaultValues);
}
registerAnnotationType(annotation);
} | java | static void registerDefaultValues(AnnotationClassValue<?> annotation, Map<String, Object> defaultValues) {
if (defaultValues != null) {
registerDefaultValues(annotation.getName(), defaultValues);
}
registerAnnotationType(annotation);
} | [
"static",
"void",
"registerDefaultValues",
"(",
"AnnotationClassValue",
"<",
"?",
">",
"annotation",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"defaultValues",
")",
"{",
"if",
"(",
"defaultValues",
"!=",
"null",
")",
"{",
"registerDefaultValues",
"(",
"an... | Registers default values for the given annotation and values.
@param annotation The annotation
@param defaultValues The default values | [
"Registers",
"default",
"values",
"for",
"the",
"given",
"annotation",
"and",
"values",
"."
] | train | https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/inject/annotation/AnnotationMetadataSupport.java#L178-L183 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/XPathAPI.java | XPathAPI.selectNodeList | public static NodeList selectNodeList(Node contextNode, String str)
throws TransformerException
{
return selectNodeList(contextNode, str, contextNode);
} | java | public static NodeList selectNodeList(Node contextNode, String str)
throws TransformerException
{
return selectNodeList(contextNode, str, contextNode);
} | [
"public",
"static",
"NodeList",
"selectNodeList",
"(",
"Node",
"contextNode",
",",
"String",
"str",
")",
"throws",
"TransformerException",
"{",
"return",
"selectNodeList",
"(",
"contextNode",
",",
"str",
",",
"contextNode",
")",
";",
"}"
] | Use an XPath string to select a nodelist.
XPath namespace prefixes are resolved from the contextNode.
@param contextNode The node to start searching from.
@param str A valid XPath string.
@return A NodeIterator, should never be null.
@throws TransformerException | [
"Use",
"an",
"XPath",
"string",
"to",
"select",
"a",
"nodelist",
".",
"XPath",
"namespace",
"prefixes",
"are",
"resolved",
"from",
"the",
"contextNode",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/XPathAPI.java#L144-L148 |
alkacon/opencms-core | src/org/opencms/ui/components/CmsResourceTable.java | CmsResourceTable.fillItem | protected void fillItem(CmsObject cms, CmsResource resource, Locale locale) {
Item resourceItem = m_container.getItem(resource.getStructureId().toString());
if (resourceItem == null) {
resourceItem = m_container.addItem(resource.getStructureId().toString());
}
fillItemDefault(resourceItem, cms, resource, locale);
for (I_ResourcePropertyProvider provider : m_propertyProviders) {
provider.addItemProperties(resourceItem, cms, resource, locale);
}
} | java | protected void fillItem(CmsObject cms, CmsResource resource, Locale locale) {
Item resourceItem = m_container.getItem(resource.getStructureId().toString());
if (resourceItem == null) {
resourceItem = m_container.addItem(resource.getStructureId().toString());
}
fillItemDefault(resourceItem, cms, resource, locale);
for (I_ResourcePropertyProvider provider : m_propertyProviders) {
provider.addItemProperties(resourceItem, cms, resource, locale);
}
} | [
"protected",
"void",
"fillItem",
"(",
"CmsObject",
"cms",
",",
"CmsResource",
"resource",
",",
"Locale",
"locale",
")",
"{",
"Item",
"resourceItem",
"=",
"m_container",
".",
"getItem",
"(",
"resource",
".",
"getStructureId",
"(",
")",
".",
"toString",
"(",
"... | Fills the file item data.<p>
@param cms the cms context
@param resource the resource
@param locale the workplace locale | [
"Fills",
"the",
"file",
"item",
"data",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/components/CmsResourceTable.java#L729-L739 |
Dempsy/dempsy | dempsy-framework.api/src/main/java/net/dempsy/lifecycle/simple/MessageProcessor.java | MessageProcessor.newInstance | @Override
public Mp newInstance() throws DempsyException {
try {
return newMp.get();
} catch(final RuntimeException rte) {
throw new DempsyException(rte, true);
}
} | java | @Override
public Mp newInstance() throws DempsyException {
try {
return newMp.get();
} catch(final RuntimeException rte) {
throw new DempsyException(rte, true);
}
} | [
"@",
"Override",
"public",
"Mp",
"newInstance",
"(",
")",
"throws",
"DempsyException",
"{",
"try",
"{",
"return",
"newMp",
".",
"get",
"(",
")",
";",
"}",
"catch",
"(",
"final",
"RuntimeException",
"rte",
")",
"{",
"throw",
"new",
"DempsyException",
"(",
... | This lifecycle phase is implemented by invoking the {@link Supplier} the was provided in the constructor.
@see MessageProcessorLifecycle#newInstance() | [
"This",
"lifecycle",
"phase",
"is",
"implemented",
"by",
"invoking",
"the",
"{",
"@link",
"Supplier",
"}",
"the",
"was",
"provided",
"in",
"the",
"constructor",
"."
] | train | https://github.com/Dempsy/dempsy/blob/cd3415b51b6787a6a9d9589b15f00ce674b6f113/dempsy-framework.api/src/main/java/net/dempsy/lifecycle/simple/MessageProcessor.java#L69-L76 |
Stratio/Decision | api/src/main/scala/com/stratio/decision/api/partitioner/JenkinsHash.java | JenkinsHash.gatherPartialIntLE | private static final int gatherPartialIntLE(final byte[] data, final int index, final int available) {
int i = data[index] & 0xFF;
if(available > 1) {
i |= (data[index + 1] & 0xFF) << 8;
if(available > 2) {
i |= (data[index + 2] & 0xFF) << 16;
}
}
return i;
} | java | private static final int gatherPartialIntLE(final byte[] data, final int index, final int available) {
int i = data[index] & 0xFF;
if(available > 1) {
i |= (data[index + 1] & 0xFF) << 8;
if(available > 2) {
i |= (data[index + 2] & 0xFF) << 16;
}
}
return i;
} | [
"private",
"static",
"final",
"int",
"gatherPartialIntLE",
"(",
"final",
"byte",
"[",
"]",
"data",
",",
"final",
"int",
"index",
",",
"final",
"int",
"available",
")",
"{",
"int",
"i",
"=",
"data",
"[",
"index",
"]",
"&",
"0xFF",
";",
"if",
"(",
"ava... | gather a partial int from the specified index using the specified number
of bytes into the byte array | [
"gather",
"a",
"partial",
"int",
"from",
"the",
"specified",
"index",
"using",
"the",
"specified",
"number",
"of",
"bytes",
"into",
"the",
"byte",
"array"
] | train | https://github.com/Stratio/Decision/blob/675eb4f005031bfcaa6cf43200f37aa5ba288139/api/src/main/scala/com/stratio/decision/api/partitioner/JenkinsHash.java#L471-L482 |
rhuss/jolokia | agent/jvm/src/main/java/org/jolokia/jvmagent/JolokiaServerConfig.java | JolokiaServerConfig.initConfigAndValidate | protected void initConfigAndValidate(Map<String,String> agentConfig) {
initContext();
initProtocol(agentConfig);
initAddress(agentConfig);
port = Integer.parseInt(agentConfig.get("port"));
backlog = Integer.parseInt(agentConfig.get("backlog"));
initExecutor(agentConfig);
initThreadNamePrefix(agentConfig);
initThreadNr(agentConfig);
initHttpsRelatedSettings(agentConfig);
initAuthenticator();
} | java | protected void initConfigAndValidate(Map<String,String> agentConfig) {
initContext();
initProtocol(agentConfig);
initAddress(agentConfig);
port = Integer.parseInt(agentConfig.get("port"));
backlog = Integer.parseInt(agentConfig.get("backlog"));
initExecutor(agentConfig);
initThreadNamePrefix(agentConfig);
initThreadNr(agentConfig);
initHttpsRelatedSettings(agentConfig);
initAuthenticator();
} | [
"protected",
"void",
"initConfigAndValidate",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"agentConfig",
")",
"{",
"initContext",
"(",
")",
";",
"initProtocol",
"(",
"agentConfig",
")",
";",
"initAddress",
"(",
"agentConfig",
")",
";",
"port",
"=",
"Integ... | Initialise and validate early in order to fail fast in case of an configuration error | [
"Initialise",
"and",
"validate",
"early",
"in",
"order",
"to",
"fail",
"fast",
"in",
"case",
"of",
"an",
"configuration",
"error"
] | train | https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/jvm/src/main/java/org/jolokia/jvmagent/JolokiaServerConfig.java#L354-L365 |
aspectran/aspectran | core/src/main/java/com/aspectran/core/util/nodelet/NodeletParser.java | NodeletParser.addNodelet | public void addNodelet(String xpath, NodeletAdder nodeletAdder) {
nodeletAdder.add(xpath, this);
setXpath(xpath);
} | java | public void addNodelet(String xpath, NodeletAdder nodeletAdder) {
nodeletAdder.add(xpath, this);
setXpath(xpath);
} | [
"public",
"void",
"addNodelet",
"(",
"String",
"xpath",
",",
"NodeletAdder",
"nodeletAdder",
")",
"{",
"nodeletAdder",
".",
"add",
"(",
"xpath",
",",
"this",
")",
";",
"setXpath",
"(",
"xpath",
")",
";",
"}"
] | Adds the nodelet.
@param xpath the xpath
@param nodeletAdder the nodelet adder | [
"Adds",
"the",
"nodelet",
"."
] | train | https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/nodelet/NodeletParser.java#L142-L145 |
lucee/Lucee | core/src/main/java/lucee/transformer/bytecode/op/OpNegate.java | OpNegate.toExprBoolean | public static ExprBoolean toExprBoolean(Expression expr, Position start, Position end) {
if (expr instanceof Literal) {
Boolean b = ((Literal) expr).getBoolean(null);
if (b != null) {
return expr.getFactory().createLitBoolean(!b.booleanValue(), start, end);
}
}
return new OpNegate(expr, start, end);
} | java | public static ExprBoolean toExprBoolean(Expression expr, Position start, Position end) {
if (expr instanceof Literal) {
Boolean b = ((Literal) expr).getBoolean(null);
if (b != null) {
return expr.getFactory().createLitBoolean(!b.booleanValue(), start, end);
}
}
return new OpNegate(expr, start, end);
} | [
"public",
"static",
"ExprBoolean",
"toExprBoolean",
"(",
"Expression",
"expr",
",",
"Position",
"start",
",",
"Position",
"end",
")",
"{",
"if",
"(",
"expr",
"instanceof",
"Literal",
")",
"{",
"Boolean",
"b",
"=",
"(",
"(",
"Literal",
")",
"expr",
")",
"... | Create a String expression from a Expression
@param left
@param right
@return String expression
@throws TemplateException | [
"Create",
"a",
"String",
"expression",
"from",
"a",
"Expression"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/transformer/bytecode/op/OpNegate.java#L55-L63 |
openbase/jul | exception/src/main/java/org/openbase/jul/exception/printer/ExceptionPrinter.java | ExceptionPrinter.printHistory | public static <T extends Throwable> void printHistory(final T th, final Logger logger) {
printHistory(th, logger, LogLevel.ERROR);
} | java | public static <T extends Throwable> void printHistory(final T th, final Logger logger) {
printHistory(th, logger, LogLevel.ERROR);
} | [
"public",
"static",
"<",
"T",
"extends",
"Throwable",
">",
"void",
"printHistory",
"(",
"final",
"T",
"th",
",",
"final",
"Logger",
"logger",
")",
"{",
"printHistory",
"(",
"th",
",",
"logger",
",",
"LogLevel",
".",
"ERROR",
")",
";",
"}"
] | Print Exception messages without stack trace in non debug mode. Method prints recursive all messages of the given exception stack to get a history overview of the causes. In verbose mode (app
-v) the stacktrace is printed in the end of history. The logging level is fixed to level "error".
@param <T> Exception type
@param th exception stack to print.
@param logger | [
"Print",
"Exception",
"messages",
"without",
"stack",
"trace",
"in",
"non",
"debug",
"mode",
".",
"Method",
"prints",
"recursive",
"all",
"messages",
"of",
"the",
"given",
"exception",
"stack",
"to",
"get",
"a",
"history",
"overview",
"of",
"the",
"causes",
... | train | https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/exception/src/main/java/org/openbase/jul/exception/printer/ExceptionPrinter.java#L146-L148 |
SonarSource/sonarqube | server/sonar-server/src/main/java/org/sonar/server/component/ws/SuggestionsAction.java | SuggestionsAction.loadSuggestionsWithoutSearch | private SuggestionsWsResponse loadSuggestionsWithoutSearch(int skip, int limit, Set<String> recentlyBrowsedKeys, List<String> qualifiers) {
List<ComponentDto> favoriteDtos = favoriteFinder.list();
if (favoriteDtos.isEmpty() && recentlyBrowsedKeys.isEmpty()) {
return newBuilder().build();
}
try (DbSession dbSession = dbClient.openSession(false)) {
Set<ComponentDto> componentDtos = new HashSet<>(favoriteDtos);
if (!recentlyBrowsedKeys.isEmpty()) {
componentDtos.addAll(dbClient.componentDao().selectByKeys(dbSession, recentlyBrowsedKeys));
}
List<ComponentDto> authorizedComponents = userSession.keepAuthorizedComponents(USER, componentDtos);
ListMultimap<String, ComponentDto> componentsPerQualifier = authorizedComponents.stream()
.collect(MoreCollectors.index(ComponentDto::qualifier));
if (componentsPerQualifier.isEmpty()) {
return newBuilder().build();
}
Set<String> favoriteUuids = favoriteDtos.stream().map(ComponentDto::uuid).collect(MoreCollectors.toSet(favoriteDtos.size()));
Comparator<ComponentDto> favoriteComparator = Comparator.comparing(c -> favoriteUuids.contains(c.uuid()) ? -1 : +1);
Comparator<ComponentDto> comparator = favoriteComparator.thenComparing(ComponentDto::name);
ComponentIndexResults componentsPerQualifiers = ComponentIndexResults.newBuilder().setQualifiers(
qualifiers.stream().map(q -> {
List<ComponentDto> componentsOfThisQualifier = componentsPerQualifier.get(q);
List<ComponentHit> hits = componentsOfThisQualifier
.stream()
.sorted(comparator)
.skip(skip)
.limit(limit)
.map(ComponentDto::uuid)
.map(ComponentHit::new)
.collect(MoreCollectors.toList(limit));
int totalHits = componentsOfThisQualifier.size();
return new ComponentHitsPerQualifier(q, hits, totalHits);
})).build();
return buildResponse(recentlyBrowsedKeys, favoriteUuids, componentsPerQualifiers, dbSession, authorizedComponents, skip + limit).build();
}
} | java | private SuggestionsWsResponse loadSuggestionsWithoutSearch(int skip, int limit, Set<String> recentlyBrowsedKeys, List<String> qualifiers) {
List<ComponentDto> favoriteDtos = favoriteFinder.list();
if (favoriteDtos.isEmpty() && recentlyBrowsedKeys.isEmpty()) {
return newBuilder().build();
}
try (DbSession dbSession = dbClient.openSession(false)) {
Set<ComponentDto> componentDtos = new HashSet<>(favoriteDtos);
if (!recentlyBrowsedKeys.isEmpty()) {
componentDtos.addAll(dbClient.componentDao().selectByKeys(dbSession, recentlyBrowsedKeys));
}
List<ComponentDto> authorizedComponents = userSession.keepAuthorizedComponents(USER, componentDtos);
ListMultimap<String, ComponentDto> componentsPerQualifier = authorizedComponents.stream()
.collect(MoreCollectors.index(ComponentDto::qualifier));
if (componentsPerQualifier.isEmpty()) {
return newBuilder().build();
}
Set<String> favoriteUuids = favoriteDtos.stream().map(ComponentDto::uuid).collect(MoreCollectors.toSet(favoriteDtos.size()));
Comparator<ComponentDto> favoriteComparator = Comparator.comparing(c -> favoriteUuids.contains(c.uuid()) ? -1 : +1);
Comparator<ComponentDto> comparator = favoriteComparator.thenComparing(ComponentDto::name);
ComponentIndexResults componentsPerQualifiers = ComponentIndexResults.newBuilder().setQualifiers(
qualifiers.stream().map(q -> {
List<ComponentDto> componentsOfThisQualifier = componentsPerQualifier.get(q);
List<ComponentHit> hits = componentsOfThisQualifier
.stream()
.sorted(comparator)
.skip(skip)
.limit(limit)
.map(ComponentDto::uuid)
.map(ComponentHit::new)
.collect(MoreCollectors.toList(limit));
int totalHits = componentsOfThisQualifier.size();
return new ComponentHitsPerQualifier(q, hits, totalHits);
})).build();
return buildResponse(recentlyBrowsedKeys, favoriteUuids, componentsPerQualifiers, dbSession, authorizedComponents, skip + limit).build();
}
} | [
"private",
"SuggestionsWsResponse",
"loadSuggestionsWithoutSearch",
"(",
"int",
"skip",
",",
"int",
"limit",
",",
"Set",
"<",
"String",
">",
"recentlyBrowsedKeys",
",",
"List",
"<",
"String",
">",
"qualifiers",
")",
"{",
"List",
"<",
"ComponentDto",
">",
"favori... | we are generating suggestions, by using (1) favorites and (2) recently browsed components (without searchin in Elasticsearch) | [
"we",
"are",
"generating",
"suggestions",
"by",
"using",
"(",
"1",
")",
"favorites",
"and",
"(",
"2",
")",
"recently",
"browsed",
"components",
"(",
"without",
"searchin",
"in",
"Elasticsearch",
")"
] | train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server/src/main/java/org/sonar/server/component/ws/SuggestionsAction.java#L175-L212 |
joniles/mpxj | src/main/java/net/sf/mpxj/explorer/ProjectTreeController.java | ProjectTreeController.addAssignments | private void addAssignments(MpxjTreeNode parentNode, ProjectFile file)
{
for (ResourceAssignment assignment : file.getResourceAssignments())
{
final ResourceAssignment a = assignment;
MpxjTreeNode childNode = new MpxjTreeNode(a)
{
@Override public String toString()
{
Resource resource = a.getResource();
String resourceName = resource == null ? "(unknown resource)" : resource.getName();
Task task = a.getTask();
String taskName = task == null ? "(unknown task)" : task.getName();
return resourceName + "->" + taskName;
}
};
parentNode.add(childNode);
}
} | java | private void addAssignments(MpxjTreeNode parentNode, ProjectFile file)
{
for (ResourceAssignment assignment : file.getResourceAssignments())
{
final ResourceAssignment a = assignment;
MpxjTreeNode childNode = new MpxjTreeNode(a)
{
@Override public String toString()
{
Resource resource = a.getResource();
String resourceName = resource == null ? "(unknown resource)" : resource.getName();
Task task = a.getTask();
String taskName = task == null ? "(unknown task)" : task.getName();
return resourceName + "->" + taskName;
}
};
parentNode.add(childNode);
}
} | [
"private",
"void",
"addAssignments",
"(",
"MpxjTreeNode",
"parentNode",
",",
"ProjectFile",
"file",
")",
"{",
"for",
"(",
"ResourceAssignment",
"assignment",
":",
"file",
".",
"getResourceAssignments",
"(",
")",
")",
"{",
"final",
"ResourceAssignment",
"a",
"=",
... | Add assignments to the tree.
@param parentNode parent tree node
@param file assignments container | [
"Add",
"assignments",
"to",
"the",
"tree",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/explorer/ProjectTreeController.java#L488-L506 |
VoltDB/voltdb | src/frontend/org/voltdb/TheHashinator.java | TheHashinator.getPartitionKeys | public static VoltTable getPartitionKeys(TheHashinator hashinator, VoltType type) {
// get partitionKeys response table so we can copy it
final VoltTable partitionKeys;
switch (type) {
case INTEGER:
partitionKeys = hashinator.m_integerPartitionKeys.get();
break;
case STRING:
partitionKeys = hashinator.m_stringPartitionKeys.get();
break;
case VARBINARY:
partitionKeys = hashinator.m_varbinaryPartitionKeys.get();
break;
default:
return null;
}
// return a clone because if the table is used at all in the voltdb process,
// (like by an NT procedure),
// you can corrupt the various offsets and positions in the underlying buffer
return partitionKeys.semiDeepCopy();
} | java | public static VoltTable getPartitionKeys(TheHashinator hashinator, VoltType type) {
// get partitionKeys response table so we can copy it
final VoltTable partitionKeys;
switch (type) {
case INTEGER:
partitionKeys = hashinator.m_integerPartitionKeys.get();
break;
case STRING:
partitionKeys = hashinator.m_stringPartitionKeys.get();
break;
case VARBINARY:
partitionKeys = hashinator.m_varbinaryPartitionKeys.get();
break;
default:
return null;
}
// return a clone because if the table is used at all in the voltdb process,
// (like by an NT procedure),
// you can corrupt the various offsets and positions in the underlying buffer
return partitionKeys.semiDeepCopy();
} | [
"public",
"static",
"VoltTable",
"getPartitionKeys",
"(",
"TheHashinator",
"hashinator",
",",
"VoltType",
"type",
")",
"{",
"// get partitionKeys response table so we can copy it",
"final",
"VoltTable",
"partitionKeys",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"INT... | Get a VoltTable containing the partition keys for each partition that can be found for the given hashinator.
May be missing some partitions during elastic rebalance when the partitions don't own
enough of the ring to be probed
If the type is not supported returns null
@param hashinator a particular hashinator to get partition keys
@param type key type
@return a VoltTable containing the partition keys | [
"Get",
"a",
"VoltTable",
"containing",
"the",
"partition",
"keys",
"for",
"each",
"partition",
"that",
"can",
"be",
"found",
"for",
"the",
"given",
"hashinator",
".",
"May",
"be",
"missing",
"some",
"partitions",
"during",
"elastic",
"rebalance",
"when",
"the"... | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/TheHashinator.java#L529-L551 |
LGoodDatePicker/LGoodDatePicker | Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java | FormLayout.shiftComponentsHorizontally | private void shiftComponentsHorizontally(int columnIndex, boolean remove) {
final int offset = remove ? -1 : 1;
for (Object element : constraintMap.entrySet()) {
Map.Entry entry = (Map.Entry) element;
CellConstraints constraints = (CellConstraints) entry.getValue();
int x1 = constraints.gridX;
int w = constraints.gridWidth;
int x2 = x1 + w - 1;
if (x1 == columnIndex && remove) {
throw new IllegalStateException(
"The removed column " + columnIndex
+ " must not contain component origins.\n"
+ "Illegal component=" + entry.getKey());
} else if (x1 >= columnIndex) {
constraints.gridX += offset;
} else if (x2 >= columnIndex) {
constraints.gridWidth += offset;
}
}
} | java | private void shiftComponentsHorizontally(int columnIndex, boolean remove) {
final int offset = remove ? -1 : 1;
for (Object element : constraintMap.entrySet()) {
Map.Entry entry = (Map.Entry) element;
CellConstraints constraints = (CellConstraints) entry.getValue();
int x1 = constraints.gridX;
int w = constraints.gridWidth;
int x2 = x1 + w - 1;
if (x1 == columnIndex && remove) {
throw new IllegalStateException(
"The removed column " + columnIndex
+ " must not contain component origins.\n"
+ "Illegal component=" + entry.getKey());
} else if (x1 >= columnIndex) {
constraints.gridX += offset;
} else if (x2 >= columnIndex) {
constraints.gridWidth += offset;
}
}
} | [
"private",
"void",
"shiftComponentsHorizontally",
"(",
"int",
"columnIndex",
",",
"boolean",
"remove",
")",
"{",
"final",
"int",
"offset",
"=",
"remove",
"?",
"-",
"1",
":",
"1",
";",
"for",
"(",
"Object",
"element",
":",
"constraintMap",
".",
"entrySet",
... | Shifts components horizontally, either to the right if a column has been inserted or to the
left if a column has been removed.
@param columnIndex index of the column to remove
@param remove true for remove, false for insert
@throws IllegalStateException if a removed column contains components | [
"Shifts",
"components",
"horizontally",
"either",
"to",
"the",
"right",
"if",
"a",
"column",
"has",
"been",
"inserted",
"or",
"to",
"the",
"left",
"if",
"a",
"column",
"has",
"been",
"removed",
"."
] | train | https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java#L652-L671 |
alkacon/opencms-core | src/org/opencms/db/CmsSubscriptionManager.java | CmsSubscriptionManager.unsubscribeResourceForAll | public void unsubscribeResourceForAll(CmsObject cms, CmsResource resource) throws CmsException {
if (!isEnabled()) {
throw new CmsRuntimeException(Messages.get().container(Messages.ERR_SUBSCRIPTION_MANAGER_DISABLED_0));
}
m_securityManager.unsubscribeResourceForAll(cms.getRequestContext(), getPoolName(), resource);
} | java | public void unsubscribeResourceForAll(CmsObject cms, CmsResource resource) throws CmsException {
if (!isEnabled()) {
throw new CmsRuntimeException(Messages.get().container(Messages.ERR_SUBSCRIPTION_MANAGER_DISABLED_0));
}
m_securityManager.unsubscribeResourceForAll(cms.getRequestContext(), getPoolName(), resource);
} | [
"public",
"void",
"unsubscribeResourceForAll",
"(",
"CmsObject",
"cms",
",",
"CmsResource",
"resource",
")",
"throws",
"CmsException",
"{",
"if",
"(",
"!",
"isEnabled",
"(",
")",
")",
"{",
"throw",
"new",
"CmsRuntimeException",
"(",
"Messages",
".",
"get",
"("... | Unsubscribes all groups and users from the resource.<p>
@param cms the current users context
@param resource the resource to unsubscribe all groups and users from
@throws CmsException if something goes wrong | [
"Unsubscribes",
"all",
"groups",
"and",
"users",
"from",
"the",
"resource",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSubscriptionManager.java#L475-L481 |
NoraUi/NoraUi | src/main/java/com/github/noraui/application/steps/CommonSteps.java | CommonSteps.checkMandatoryField | @Conditioned
@Lorsque("Je vérifie le champ obligatoire '(.*)-(.*)' de type '(.*)'[\\.|\\?]")
@Then("I check mandatory field '(.*)-(.*)' of type '(.*)'[\\.|\\?]")
public void checkMandatoryField(String page, String fieldName, String type, List<GherkinStepCondition> conditions) throws TechnicalException, FailureException {
final PageElement pageElement = Page.getInstance(page).getPageElementByKey('-' + fieldName);
if ("text".equals(type)) {
if (!checkMandatoryTextField(pageElement)) {
new Result.Failure<>(pageElement, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_EMPTY_MANDATORY_FIELD), pageElement, pageElement.getPage().getApplication()), true,
pageElement.getPage().getCallBack());
}
} else {
new Result.Failure<>(type, Messages.format(Messages.getMessage(Messages.SCENARIO_ERROR_MESSAGE_TYPE_NOT_IMPLEMENTED), type, "checkMandatoryField"), false,
pageElement.getPage().getCallBack());
}
} | java | @Conditioned
@Lorsque("Je vérifie le champ obligatoire '(.*)-(.*)' de type '(.*)'[\\.|\\?]")
@Then("I check mandatory field '(.*)-(.*)' of type '(.*)'[\\.|\\?]")
public void checkMandatoryField(String page, String fieldName, String type, List<GherkinStepCondition> conditions) throws TechnicalException, FailureException {
final PageElement pageElement = Page.getInstance(page).getPageElementByKey('-' + fieldName);
if ("text".equals(type)) {
if (!checkMandatoryTextField(pageElement)) {
new Result.Failure<>(pageElement, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_EMPTY_MANDATORY_FIELD), pageElement, pageElement.getPage().getApplication()), true,
pageElement.getPage().getCallBack());
}
} else {
new Result.Failure<>(type, Messages.format(Messages.getMessage(Messages.SCENARIO_ERROR_MESSAGE_TYPE_NOT_IMPLEMENTED), type, "checkMandatoryField"), false,
pageElement.getPage().getCallBack());
}
} | [
"@",
"Conditioned",
"@",
"Lorsque",
"(",
"\"Je vérifie le champ obligatoire '(.*)-(.*)' de type '(.*)'[\\\\.|\\\\?]\")",
"\r",
"@",
"Then",
"(",
"\"I check mandatory field '(.*)-(.*)' of type '(.*)'[\\\\.|\\\\?]\"",
")",
"public",
"void",
"checkMandatoryField",
"(",
"String",
"page... | Checks that mandatory field is no empty with conditions.
@param page
The concerned page of fieldName
@param fieldName
Name of the field to check (see .ini file)
@param type
Type of the field ('text', 'select'...). Only 'text' is implemented for the moment!
@param conditions
list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
@throws TechnicalException
is throws if you have a technical error (format, configuration, datas, ...) in NoraUi.
Exception with message and with screenshot and with exception if functional error but no screenshot and no exception if technical error.
@throws FailureException
if the scenario encounters a functional error | [
"Checks",
"that",
"mandatory",
"field",
"is",
"no",
"empty",
"with",
"conditions",
"."
] | train | https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/CommonSteps.java#L653-L668 |
couchbase/couchbase-lite-java | src/main/java/com/couchbase/lite/Join.java | Join.leftOuterJoin | @NonNull
public static On leftOuterJoin(@NonNull DataSource datasource) {
if (datasource == null) {
throw new IllegalArgumentException("datasource cannot be null.");
}
return new On(Type.LEFT_OUTER, datasource);
} | java | @NonNull
public static On leftOuterJoin(@NonNull DataSource datasource) {
if (datasource == null) {
throw new IllegalArgumentException("datasource cannot be null.");
}
return new On(Type.LEFT_OUTER, datasource);
} | [
"@",
"NonNull",
"public",
"static",
"On",
"leftOuterJoin",
"(",
"@",
"NonNull",
"DataSource",
"datasource",
")",
"{",
"if",
"(",
"datasource",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"datasource cannot be null.\"",
")",
";",
"}... | Create a LEFT OUTER JOIN component with the given data source.
Use the returned On component to specify join conditions.
@param datasource The DataSource object of the JOIN clause.
@return The On object used for specifying join conditions. | [
"Create",
"a",
"LEFT",
"OUTER",
"JOIN",
"component",
"with",
"the",
"given",
"data",
"source",
".",
"Use",
"the",
"returned",
"On",
"component",
"to",
"specify",
"join",
"conditions",
"."
] | train | https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/com/couchbase/lite/Join.java#L139-L145 |
libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/sched/LoadBalancingScheduler.java | LoadBalancingScheduler.addWithAutomaticPhasing | @Override
public void addWithAutomaticPhasing (Schedulable schedulable, int frequency) {
// Calculate the phase and add the schedulable to the list
add(schedulable, frequency, calculatePhase(frequency));
} | java | @Override
public void addWithAutomaticPhasing (Schedulable schedulable, int frequency) {
// Calculate the phase and add the schedulable to the list
add(schedulable, frequency, calculatePhase(frequency));
} | [
"@",
"Override",
"public",
"void",
"addWithAutomaticPhasing",
"(",
"Schedulable",
"schedulable",
",",
"int",
"frequency",
")",
"{",
"// Calculate the phase and add the schedulable to the list",
"add",
"(",
"schedulable",
",",
"frequency",
",",
"calculatePhase",
"(",
"freq... | Adds the {@code schedulable} to the list using the given {@code frequency} and a phase calculated by a dry run of the
scheduler.
@param schedulable the task to schedule
@param frequency the frequency | [
"Adds",
"the",
"{"
] | train | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/sched/LoadBalancingScheduler.java#L67-L71 |
zeroturnaround/zt-zip | src/main/java/org/zeroturnaround/zip/commons/FileUtilsV2_2.java | FileUtilsV2_2.copyDirectory | public static void copyDirectory(File srcDir, File destDir) throws IOException {
copyDirectory(srcDir, destDir, true);
} | java | public static void copyDirectory(File srcDir, File destDir) throws IOException {
copyDirectory(srcDir, destDir, true);
} | [
"public",
"static",
"void",
"copyDirectory",
"(",
"File",
"srcDir",
",",
"File",
"destDir",
")",
"throws",
"IOException",
"{",
"copyDirectory",
"(",
"srcDir",
",",
"destDir",
",",
"true",
")",
";",
"}"
] | Copies a whole directory to a new location preserving the file dates.
<p>
This method copies the specified directory and all its child
directories and files to the specified destination.
The destination is the new location and name of the directory.
<p>
The destination directory is created if it does not exist.
If the destination directory did exist, then this method merges
the source with the destination, with the source taking precedence.
<p>
<strong>Note:</strong> This method tries to preserve the files' last
modified date/times using {@link File#setLastModified(long)}, however
it is not guaranteed that those operations will succeed.
If the modification operation fails, no indication is provided.
@param srcDir an existing directory to copy, must not be <code>null</code>
@param destDir the new directory, must not be <code>null</code>
@throws NullPointerException if source or destination is <code>null</code>
@throws IOException if source or destination is invalid
@throws IOException if an IO error occurs during copying
@since 1.1 | [
"Copies",
"a",
"whole",
"directory",
"to",
"a",
"new",
"location",
"preserving",
"the",
"file",
"dates",
".",
"<p",
">",
"This",
"method",
"copies",
"the",
"specified",
"directory",
"and",
"all",
"its",
"child",
"directories",
"and",
"files",
"to",
"the",
... | train | https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/commons/FileUtilsV2_2.java#L478-L480 |
jenkinsci/github-plugin | src/main/java/com/cloudbees/jenkins/GitHubRepositoryNameContributor.java | GitHubRepositoryNameContributor.parseAssociatedNames | @Deprecated
public void parseAssociatedNames(AbstractProject<?, ?> job, Collection<GitHubRepositoryName> result) {
parseAssociatedNames((Item) job, result);
} | java | @Deprecated
public void parseAssociatedNames(AbstractProject<?, ?> job, Collection<GitHubRepositoryName> result) {
parseAssociatedNames((Item) job, result);
} | [
"@",
"Deprecated",
"public",
"void",
"parseAssociatedNames",
"(",
"AbstractProject",
"<",
"?",
",",
"?",
">",
"job",
",",
"Collection",
"<",
"GitHubRepositoryName",
">",
"result",
")",
"{",
"parseAssociatedNames",
"(",
"(",
"Item",
")",
"job",
",",
"result",
... | Looks at the definition of {@link AbstractProject} and list up the related github repositories,
then puts them into the collection.
@deprecated Use {@link #parseAssociatedNames(Item, Collection)} | [
"Looks",
"at",
"the",
"definition",
"of",
"{",
"@link",
"AbstractProject",
"}",
"and",
"list",
"up",
"the",
"related",
"github",
"repositories",
"then",
"puts",
"them",
"into",
"the",
"collection",
"."
] | train | https://github.com/jenkinsci/github-plugin/blob/4e05b9aeb488af5342c78f78aa3c55114e8d462a/src/main/java/com/cloudbees/jenkins/GitHubRepositoryNameContributor.java#L42-L45 |
dadoonet/fscrawler | framework/src/main/java/fr/pilato/elasticsearch/crawler/fs/framework/MetaFileHandler.java | MetaFileHandler.removeFile | protected void removeFile(String subdir, String filename) throws IOException {
Path dir = root;
if (subdir != null) {
dir = dir.resolve(subdir);
}
Files.deleteIfExists(dir.resolve(filename));
} | java | protected void removeFile(String subdir, String filename) throws IOException {
Path dir = root;
if (subdir != null) {
dir = dir.resolve(subdir);
}
Files.deleteIfExists(dir.resolve(filename));
} | [
"protected",
"void",
"removeFile",
"(",
"String",
"subdir",
",",
"String",
"filename",
")",
"throws",
"IOException",
"{",
"Path",
"dir",
"=",
"root",
";",
"if",
"(",
"subdir",
"!=",
"null",
")",
"{",
"dir",
"=",
"dir",
".",
"resolve",
"(",
"subdir",
")... | Remove a file from ~/.fscrawler/{subdir} dir
@param subdir subdir where we can read the file (null if we read in the root dir)
@param filename filename
@throws IOException in case of error while reading | [
"Remove",
"a",
"file",
"from",
"~",
"/",
".",
"fscrawler",
"/",
"{",
"subdir",
"}",
"dir"
] | train | https://github.com/dadoonet/fscrawler/blob/cca00a14e21ef9986aa30e19b160463aed6bf921/framework/src/main/java/fr/pilato/elasticsearch/crawler/fs/framework/MetaFileHandler.java#L83-L89 |
google/closure-templates | java/src/com/google/template/soy/pysrc/internal/TranslateToPyExprVisitor.java | TranslateToPyExprVisitor.genCodeForFieldAccess | private String genCodeForFieldAccess(
ExprNode node, SoyType baseType, String containerExpr, String fieldName) {
if (baseType != null && baseType.getKind() == SoyType.Kind.PROTO) {
errorReporter.report(node.getSourceLocation(), PROTO_ACCESS_NOT_SUPPORTED);
return ".ERROR";
}
return genCodeForLiteralKeyAccess(containerExpr, fieldName);
} | java | private String genCodeForFieldAccess(
ExprNode node, SoyType baseType, String containerExpr, String fieldName) {
if (baseType != null && baseType.getKind() == SoyType.Kind.PROTO) {
errorReporter.report(node.getSourceLocation(), PROTO_ACCESS_NOT_SUPPORTED);
return ".ERROR";
}
return genCodeForLiteralKeyAccess(containerExpr, fieldName);
} | [
"private",
"String",
"genCodeForFieldAccess",
"(",
"ExprNode",
"node",
",",
"SoyType",
"baseType",
",",
"String",
"containerExpr",
",",
"String",
"fieldName",
")",
"{",
"if",
"(",
"baseType",
"!=",
"null",
"&&",
"baseType",
".",
"getKind",
"(",
")",
"==",
"S... | Generates the code for a field name access, e.g. ".foo" or "['bar']".
@param node the field access source node
@param baseType the type of the object that contains the field
@param containerExpr an expression that evaluates to the container of the named field. This
expression may have any operator precedence that binds more tightly than exponentiation.
@param fieldName the field name | [
"Generates",
"the",
"code",
"for",
"a",
"field",
"name",
"access",
"e",
".",
"g",
".",
".",
"foo",
"or",
"[",
"bar",
"]",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/TranslateToPyExprVisitor.java#L625-L632 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/vod/VodClient.java | VodClient.getMediaSourceDownload | public GetMediaSourceDownloadResponse getMediaSourceDownload(GetMediaSourceDownloadRequest request) {
checkStringNotEmpty(request.getMediaId(), "Media ID should not be null or empty!");
InternalRequest internalRequest =
createRequest(HttpMethodName.GET, request, PATH_MEDIA, request.getMediaId());
internalRequest.addParameter(PARA_DOWNLOAD, null);
internalRequest.addParameter(PARA_EXPIREDINSECONDS, String.valueOf(request.getExpiredInSeconds()));
return invokeHttpClient(internalRequest, GetMediaSourceDownloadResponse.class);
} | java | public GetMediaSourceDownloadResponse getMediaSourceDownload(GetMediaSourceDownloadRequest request) {
checkStringNotEmpty(request.getMediaId(), "Media ID should not be null or empty!");
InternalRequest internalRequest =
createRequest(HttpMethodName.GET, request, PATH_MEDIA, request.getMediaId());
internalRequest.addParameter(PARA_DOWNLOAD, null);
internalRequest.addParameter(PARA_EXPIREDINSECONDS, String.valueOf(request.getExpiredInSeconds()));
return invokeHttpClient(internalRequest, GetMediaSourceDownloadResponse.class);
} | [
"public",
"GetMediaSourceDownloadResponse",
"getMediaSourceDownload",
"(",
"GetMediaSourceDownloadRequest",
"request",
")",
"{",
"checkStringNotEmpty",
"(",
"request",
".",
"getMediaId",
"(",
")",
",",
"\"Media ID should not be null or empty!\"",
")",
";",
"InternalRequest",
... | Transcode the media again. Only status is FAILED or PUBLISHED media can use.
@param request The request object containing mediaid
@return | [
"Transcode",
"the",
"media",
"again",
".",
"Only",
"status",
"is",
"FAILED",
"or",
"PUBLISHED",
"media",
"can",
"use",
"."
] | train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/vod/VodClient.java#L918-L928 |
Whiley/WhileyCompiler | src/main/java/wyil/check/FlowTypeCheck.java | FlowTypeCheck.checkStaticVariableDeclaration | public void checkStaticVariableDeclaration(Decl.StaticVariable decl) {
Environment environment = new Environment();
// Check type not void
checkVariableDeclaration(decl, environment);
} | java | public void checkStaticVariableDeclaration(Decl.StaticVariable decl) {
Environment environment = new Environment();
// Check type not void
checkVariableDeclaration(decl, environment);
} | [
"public",
"void",
"checkStaticVariableDeclaration",
"(",
"Decl",
".",
"StaticVariable",
"decl",
")",
"{",
"Environment",
"environment",
"=",
"new",
"Environment",
"(",
")",
";",
"// Check type not void",
"checkVariableDeclaration",
"(",
"decl",
",",
"environment",
")"... | check and check types for a given constant declaration.
@param cd
Constant declaration to check.
@throws IOException | [
"check",
"and",
"check",
"types",
"for",
"a",
"given",
"constant",
"declaration",
"."
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/check/FlowTypeCheck.java#L181-L185 |
tvesalainen/util | util/src/main/java/d3/env/TSAGeoMag.java | TSAGeoMag.getDeclination | public double getDeclination( double dlat, double dlong, double year, double altitude )
{
calcGeoMag( dlat, dlong, year, altitude );
return dec;
} | java | public double getDeclination( double dlat, double dlong, double year, double altitude )
{
calcGeoMag( dlat, dlong, year, altitude );
return dec;
} | [
"public",
"double",
"getDeclination",
"(",
"double",
"dlat",
",",
"double",
"dlong",
",",
"double",
"year",
",",
"double",
"altitude",
")",
"{",
"calcGeoMag",
"(",
"dlat",
",",
"dlong",
",",
"year",
",",
"altitude",
")",
";",
"return",
"dec",
";",
"}"
] | Returns the declination from the Department of
Defense geomagnetic model and data, in degrees. The
magnetic heading + declination = true heading.
(True heading + variation = magnetic heading.)
@param dlat Latitude in decimal degrees.
@param dlong Longitude in decimal degrees.
@param year The date as a decimial year.
@param altitude The altitude in kilometers.
@return The declination in degrees. | [
"Returns",
"the",
"declination",
"from",
"the",
"Department",
"of",
"Defense",
"geomagnetic",
"model",
"and",
"data",
"in",
"degrees",
".",
"The",
"magnetic",
"heading",
"+",
"declination",
"=",
"true",
"heading",
".",
"(",
"True",
"heading",
"+",
"variation",... | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/d3/env/TSAGeoMag.java#L933-L937 |
CloudSlang/cs-actions | cs-commons/src/main/java/io/cloudslang/content/utils/StringEscapeUtilities.java | StringEscapeUtilities.removeEscapedChars | @NotNull
public static String removeEscapedChars(@NotNull final String string, final char[] toRemove) {
String toReturn = string;
for (char character : toRemove) {
toReturn = removeEscapedChar(toReturn, character);
}
return toReturn;
} | java | @NotNull
public static String removeEscapedChars(@NotNull final String string, final char[] toRemove) {
String toReturn = string;
for (char character : toRemove) {
toReturn = removeEscapedChar(toReturn, character);
}
return toReturn;
} | [
"@",
"NotNull",
"public",
"static",
"String",
"removeEscapedChars",
"(",
"@",
"NotNull",
"final",
"String",
"string",
",",
"final",
"char",
"[",
"]",
"toRemove",
")",
"{",
"String",
"toReturn",
"=",
"string",
";",
"for",
"(",
"char",
"character",
":",
"toR... | Removes all the occurrences of the \<toRemove> characters from the <string>
@param string the string from which to remove the characters
@param toRemove the \character to remove from the <string>
@return a new string with the removed \<toRemove> characters | [
"Removes",
"all",
"the",
"occurrences",
"of",
"the",
"\\",
"<toRemove",
">",
"characters",
"from",
"the",
"<string",
">"
] | train | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-commons/src/main/java/io/cloudslang/content/utils/StringEscapeUtilities.java#L109-L116 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.