repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
218
func_name
stringlengths
5
140
whole_func_string
stringlengths
79
3.99k
language
stringclasses
1 value
func_code_string
stringlengths
79
3.99k
func_code_tokens
listlengths
20
624
func_documentation_string
stringlengths
61
1.96k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
107
339
code4everything/util
src/main/java/com/zhazhapan/util/MailSender.java
MailSender.config
public static void config(String host, String personal, String from, String key, int port) { config(host, personal, from, key); setPort(port); }
java
public static void config(String host, String personal, String from, String key, int port) { config(host, personal, from, key); setPort(port); }
[ "public", "static", "void", "config", "(", "String", "host", ",", "String", "personal", ",", "String", "from", ",", "String", "key", ",", "int", "port", ")", "{", "config", "(", "host", ",", "personal", ",", "from", ",", "key", ")", ";", "setPort", "...
配置邮箱 @param host 邮件服务器 @param personal 个人名称 @param from 发件箱 @param key 密码 @param port 端口
[ "配置邮箱" ]
train
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/MailSender.java#L79-L82
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataPropertyImpl_CustomFieldSerializer.java
OWLDataPropertyImpl_CustomFieldSerializer.serializeInstance
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataPropertyImpl instance) throws SerializationException { serialize(streamWriter, instance); }
java
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataPropertyImpl instance) throws SerializationException { serialize(streamWriter, instance); }
[ "@", "Override", "public", "void", "serializeInstance", "(", "SerializationStreamWriter", "streamWriter", ",", "OWLDataPropertyImpl", "instance", ")", "throws", "SerializationException", "{", "serialize", "(", "streamWriter", ",", "instance", ")", ";", "}" ]
Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful
[ "Serializes", "the", "content", "of", "the", "object", "into", "the", "{" ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataPropertyImpl_CustomFieldSerializer.java#L63-L66
aws/aws-sdk-java
aws-java-sdk-lightsail/src/main/java/com/amazonaws/services/lightsail/model/DomainEntry.java
DomainEntry.withOptions
@Deprecated public DomainEntry withOptions(java.util.Map<String, String> options) { setOptions(options); return this; }
java
@Deprecated public DomainEntry withOptions(java.util.Map<String, String> options) { setOptions(options); return this; }
[ "@", "Deprecated", "public", "DomainEntry", "withOptions", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "options", ")", "{", "setOptions", "(", "options", ")", ";", "return", "this", ";", "}" ]
<p> (Deprecated) The options for the domain entry. </p> <note> <p> In releases prior to November 29, 2017, this parameter was not included in the API response. It is now deprecated. </p> </note> @param options (Deprecated) The options for the domain entry.</p> <note> <p> In releases prior to November 29, 2017, this parameter was not included in the API response. It is now deprecated. </p> @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "(", "Deprecated", ")", "The", "options", "for", "the", "domain", "entry", ".", "<", "/", "p", ">", "<note", ">", "<p", ">", "In", "releases", "prior", "to", "November", "29", "2017", "this", "parameter", "was", "not", "included", "in", "t...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-lightsail/src/main/java/com/amazonaws/services/lightsail/model/DomainEntry.java#L685-L689
j256/simplecsv
src/main/java/com/j256/simplecsv/processor/CsvProcessor.java
CsvProcessor.writeAll
public void writeAll(File file, Collection<T> entities, boolean writeHeader) throws IOException { writeAll(new FileWriter(file), entities, writeHeader); }
java
public void writeAll(File file, Collection<T> entities, boolean writeHeader) throws IOException { writeAll(new FileWriter(file), entities, writeHeader); }
[ "public", "void", "writeAll", "(", "File", "file", ",", "Collection", "<", "T", ">", "entities", ",", "boolean", "writeHeader", ")", "throws", "IOException", "{", "writeAll", "(", "new", "FileWriter", "(", "file", ")", ",", "entities", ",", "writeHeader", ...
Write a collection of entities to the writer. @param file Where to write the header and entities. @param entities Collection of entities to write to the writer. @param writeHeader Set to true to write header at the start of the output file. @throws IOException If there are any IO exceptions thrown when writing.
[ "Write", "a", "collection", "of", "entities", "to", "the", "writer", "." ]
train
https://github.com/j256/simplecsv/blob/964fe53073c43e2a311341e3f8fd2c94372f60cb/src/main/java/com/j256/simplecsv/processor/CsvProcessor.java#L410-L412
Kickflip/kickflip-android-sdk
sdk/src/main/java/io/kickflip/sdk/Kickflip.java
Kickflip.startBroadcastActivity
public static void startBroadcastActivity(Activity host, BroadcastListener listener) { checkNotNull(listener, host.getString(R.string.error_no_broadcastlistener)); if (sSessionConfig == null) { setupDefaultSessionConfig(); } checkNotNull(sClientKey); checkNotNull(sClientSecret); sBroadcastListener = listener; Intent broadcastIntent = new Intent(host, BroadcastActivity.class); broadcastIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); host.startActivity(broadcastIntent); }
java
public static void startBroadcastActivity(Activity host, BroadcastListener listener) { checkNotNull(listener, host.getString(R.string.error_no_broadcastlistener)); if (sSessionConfig == null) { setupDefaultSessionConfig(); } checkNotNull(sClientKey); checkNotNull(sClientSecret); sBroadcastListener = listener; Intent broadcastIntent = new Intent(host, BroadcastActivity.class); broadcastIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); host.startActivity(broadcastIntent); }
[ "public", "static", "void", "startBroadcastActivity", "(", "Activity", "host", ",", "BroadcastListener", "listener", ")", "{", "checkNotNull", "(", "listener", ",", "host", ".", "getString", "(", "R", ".", "string", ".", "error_no_broadcastlistener", ")", ")", "...
Start {@link io.kickflip.sdk.activity.BroadcastActivity}. This Activity facilitates control over a single live broadcast. <p/> <b>Must be called after {@link Kickflip#setup(android.content.Context, String, String)} or {@link Kickflip#setup(android.content.Context, String, String, io.kickflip.sdk.api.KickflipCallback)}.</b> @param host the host {@link android.app.Activity} initiating this action @param listener an optional {@link io.kickflip.sdk.av.BroadcastListener} to be notified on broadcast events
[ "Start", "{", "@link", "io", ".", "kickflip", ".", "sdk", ".", "activity", ".", "BroadcastActivity", "}", ".", "This", "Activity", "facilitates", "control", "over", "a", "single", "live", "broadcast", ".", "<p", "/", ">", "<b", ">", "Must", "be", "called...
train
https://github.com/Kickflip/kickflip-android-sdk/blob/af3aae5f1128d7376e67aefe11a3a1a3844be734/sdk/src/main/java/io/kickflip/sdk/Kickflip.java#L135-L146
Samsung/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/jassimp/AiMaterial.java
AiMaterial.checkTexRange
private void checkTexRange(AiTextureType type, int index) { if (index < 0 || index > m_numTextures.get(type)) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + m_numTextures.get(type)); } }
java
private void checkTexRange(AiTextureType type, int index) { if (index < 0 || index > m_numTextures.get(type)) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + m_numTextures.get(type)); } }
[ "private", "void", "checkTexRange", "(", "AiTextureType", "type", ",", "int", "index", ")", "{", "if", "(", "index", "<", "0", "||", "index", ">", "m_numTextures", ".", "get", "(", "type", ")", ")", "{", "throw", "new", "IndexOutOfBoundsException", "(", ...
Checks that index is valid an throw an exception if not. @param type the type @param index the index to check
[ "Checks", "that", "index", "is", "valid", "an", "throw", "an", "exception", "if", "not", "." ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/jassimp/AiMaterial.java#L1268-L1273
Azure/azure-sdk-for-java
sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/ServerTableAuditingPoliciesInner.java
ServerTableAuditingPoliciesInner.listByServerAsync
public Observable<ServerTableAuditingPolicyListResultInner> listByServerAsync(String resourceGroupName, String serverName) { return listByServerWithServiceResponseAsync(resourceGroupName, serverName).map(new Func1<ServiceResponse<ServerTableAuditingPolicyListResultInner>, ServerTableAuditingPolicyListResultInner>() { @Override public ServerTableAuditingPolicyListResultInner call(ServiceResponse<ServerTableAuditingPolicyListResultInner> response) { return response.body(); } }); }
java
public Observable<ServerTableAuditingPolicyListResultInner> listByServerAsync(String resourceGroupName, String serverName) { return listByServerWithServiceResponseAsync(resourceGroupName, serverName).map(new Func1<ServiceResponse<ServerTableAuditingPolicyListResultInner>, ServerTableAuditingPolicyListResultInner>() { @Override public ServerTableAuditingPolicyListResultInner call(ServiceResponse<ServerTableAuditingPolicyListResultInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ServerTableAuditingPolicyListResultInner", ">", "listByServerAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ")", "{", "return", "listByServerWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ")", ...
Lists a servers's table auditing policies. Table auditing is deprecated, use blob auditing instead. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ServerTableAuditingPolicyListResultInner object
[ "Lists", "a", "servers", "s", "table", "auditing", "policies", ".", "Table", "auditing", "is", "deprecated", "use", "blob", "auditing", "instead", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/ServerTableAuditingPoliciesInner.java#L289-L296
digitalfondue/stampo
src/main/java/ch/digitalfondue/stampo/processor/IncludeAllPaginator.java
IncludeAllPaginator.flattenAndGroupRecursively
private List<IncludeAllPage> flattenAndGroupRecursively(Directory dir, int maxDepth, int depth) { List<FileOrDir> fileOrDirs = new ArrayList<>(); Set<String> pairedDirectories = new HashSet<>(); Map<String, Directory> childDirs = dir.getDirectories(); Map<String, FileResource> childFiles = dir.getFiles(); for (FileResource fr : childFiles.values()) { String fileNameWithoutExt = fr.getFileNameWithoutExtensions(); Optional<Directory> pairedDir = childDirs.containsKey(fileNameWithoutExt) ? of(childDirs.get(fileNameWithoutExt)) : empty(); fileOrDirs.add(new FileOrDir(of(fr), pairedDir)); pairedDir.ifPresent(d -> { pairedDirectories.add(d.getName()); }); } fileOrDirs.addAll(childDirs.values().stream() .filter(d -> !pairedDirectories.contains(d.getName())) .map(d -> new FileOrDir(empty(), of(d))).collect(Collectors.toList())); fileOrDirs.sort(FILE_OR_DIR_COMPARATOR); List<IncludeAllPage> frs = new ArrayList<>(); for (FileOrDir fd : fileOrDirs) { if (depth > maxDepth) { if (frs.isEmpty()) { frs.add(new IncludeAllPage(depth, new ArrayList<>())); } IncludeAllPage singleFile = frs.get(0); fd.file.ifPresent(singleFile.files::add); fd.dir.ifPresent(d -> flattenAndGroupRecursively(d, maxDepth, depth + 1).forEach(iap -> singleFile.files.addAll(iap.files))); } else { IncludeAllPage fileRes = new IncludeAllPage(depth, new ArrayList<>()); frs.add(fileRes); fd.file.ifPresent(fileRes.files::add); List<IncludeAllPage> pairedFiles = fd.dir.map(d -> flattenAndGroupRecursively(d, maxDepth, depth + 1)).orElse(Collections.emptyList()); if (depth >= maxDepth) { pairedFiles.forEach(iap -> fileRes.files.addAll(iap.files)); } else { pairedFiles.forEach(frs::add); } } } return frs; }
java
private List<IncludeAllPage> flattenAndGroupRecursively(Directory dir, int maxDepth, int depth) { List<FileOrDir> fileOrDirs = new ArrayList<>(); Set<String> pairedDirectories = new HashSet<>(); Map<String, Directory> childDirs = dir.getDirectories(); Map<String, FileResource> childFiles = dir.getFiles(); for (FileResource fr : childFiles.values()) { String fileNameWithoutExt = fr.getFileNameWithoutExtensions(); Optional<Directory> pairedDir = childDirs.containsKey(fileNameWithoutExt) ? of(childDirs.get(fileNameWithoutExt)) : empty(); fileOrDirs.add(new FileOrDir(of(fr), pairedDir)); pairedDir.ifPresent(d -> { pairedDirectories.add(d.getName()); }); } fileOrDirs.addAll(childDirs.values().stream() .filter(d -> !pairedDirectories.contains(d.getName())) .map(d -> new FileOrDir(empty(), of(d))).collect(Collectors.toList())); fileOrDirs.sort(FILE_OR_DIR_COMPARATOR); List<IncludeAllPage> frs = new ArrayList<>(); for (FileOrDir fd : fileOrDirs) { if (depth > maxDepth) { if (frs.isEmpty()) { frs.add(new IncludeAllPage(depth, new ArrayList<>())); } IncludeAllPage singleFile = frs.get(0); fd.file.ifPresent(singleFile.files::add); fd.dir.ifPresent(d -> flattenAndGroupRecursively(d, maxDepth, depth + 1).forEach(iap -> singleFile.files.addAll(iap.files))); } else { IncludeAllPage fileRes = new IncludeAllPage(depth, new ArrayList<>()); frs.add(fileRes); fd.file.ifPresent(fileRes.files::add); List<IncludeAllPage> pairedFiles = fd.dir.map(d -> flattenAndGroupRecursively(d, maxDepth, depth + 1)).orElse(Collections.emptyList()); if (depth >= maxDepth) { pairedFiles.forEach(iap -> fileRes.files.addAll(iap.files)); } else { pairedFiles.forEach(frs::add); } } } return frs; }
[ "private", "List", "<", "IncludeAllPage", ">", "flattenAndGroupRecursively", "(", "Directory", "dir", ",", "int", "maxDepth", ",", "int", "depth", ")", "{", "List", "<", "FileOrDir", ">", "fileOrDirs", "=", "new", "ArrayList", "<>", "(", ")", ";", "Set", "...
/* From a given directory, it will flatten the file hierarchy in a list of "pages" (That can contain more than one FileResource)
[ "/", "*", "From", "a", "given", "directory", "it", "will", "flatten", "the", "file", "hierarchy", "in", "a", "list", "of", "pages", "(", "That", "can", "contain", "more", "than", "one", "FileResource", ")" ]
train
https://github.com/digitalfondue/stampo/blob/5a41f20acd9211cf3951c30d0e0825994ae95573/src/main/java/ch/digitalfondue/stampo/processor/IncludeAllPaginator.java#L133-L185
woo-j/OkapiBarcode
src/main/java/uk/org/okapibarcode/util/Arrays.java
Arrays.containsAt
public static boolean containsAt(byte[] array, byte[] searchFor, int index) { for (int i = 0; i < searchFor.length; i++) { if (index + i >= array.length || array[index + i] != searchFor[i]) { return false; } } return true; }
java
public static boolean containsAt(byte[] array, byte[] searchFor, int index) { for (int i = 0; i < searchFor.length; i++) { if (index + i >= array.length || array[index + i] != searchFor[i]) { return false; } } return true; }
[ "public", "static", "boolean", "containsAt", "(", "byte", "[", "]", "array", ",", "byte", "[", "]", "searchFor", ",", "int", "index", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "searchFor", ".", "length", ";", "i", "++", ")", "{",...
Returns <code>true</code> if the specified array contains the specified sub-array at the specified index. @param array the array to search in @param searchFor the sub-array to search for @param index the index at which to search @return whether or not the specified array contains the specified sub-array at the specified index
[ "Returns", "<code", ">", "true<", "/", "code", ">", "if", "the", "specified", "array", "contains", "the", "specified", "sub", "-", "array", "at", "the", "specified", "index", "." ]
train
https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/util/Arrays.java#L88-L95
ixa-ehu/ixa-pipe-ml
src/main/java/eus/ixa/ixa/pipe/ml/features/MFSFeatureGenerator.java
MFSFeatureGenerator.processRangeOptions
private void processRangeOptions(final Map<String, String> properties) { final String featuresRange = properties.get("range"); final String[] rangeArray = Flags.processMFSFeaturesRange(featuresRange); // options if (rangeArray[0].equalsIgnoreCase("pos")) { this.isPos = true; } if (rangeArray[1].equalsIgnoreCase("posclass")) { this.isPosClass = true; } if (rangeArray[2].equalsIgnoreCase("lemma")) { this.isLemma = true; } if (rangeArray[3].equalsIgnoreCase("mfs")) { this.isMFS = true; } if (rangeArray[4].equalsIgnoreCase("monosemic")) { this.isMonosemic = true; } }
java
private void processRangeOptions(final Map<String, String> properties) { final String featuresRange = properties.get("range"); final String[] rangeArray = Flags.processMFSFeaturesRange(featuresRange); // options if (rangeArray[0].equalsIgnoreCase("pos")) { this.isPos = true; } if (rangeArray[1].equalsIgnoreCase("posclass")) { this.isPosClass = true; } if (rangeArray[2].equalsIgnoreCase("lemma")) { this.isLemma = true; } if (rangeArray[3].equalsIgnoreCase("mfs")) { this.isMFS = true; } if (rangeArray[4].equalsIgnoreCase("monosemic")) { this.isMonosemic = true; } }
[ "private", "void", "processRangeOptions", "(", "final", "Map", "<", "String", ",", "String", ">", "properties", ")", "{", "final", "String", "featuresRange", "=", "properties", ".", "get", "(", "\"range\"", ")", ";", "final", "String", "[", "]", "rangeArray"...
Process the options of which kind of features are to be generated. @param properties the properties map
[ "Process", "the", "options", "of", "which", "kind", "of", "features", "are", "to", "be", "generated", "." ]
train
https://github.com/ixa-ehu/ixa-pipe-ml/blob/c817fa1e40e96ed15fc79d22c3a7c25f1a40d172/src/main/java/eus/ixa/ixa/pipe/ml/features/MFSFeatureGenerator.java#L156-L175
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/TasksImpl.java
TasksImpl.listAsync
public ServiceFuture<List<CloudTask>> listAsync(final String jobId, final ListOperationCallback<CloudTask> serviceCallback) { return AzureServiceFuture.fromHeaderPageResponse( listSinglePageAsync(jobId), new Func1<String, Observable<ServiceResponseWithHeaders<Page<CloudTask>, TaskListHeaders>>>() { @Override public Observable<ServiceResponseWithHeaders<Page<CloudTask>, TaskListHeaders>> call(String nextPageLink) { return listNextSinglePageAsync(nextPageLink, null); } }, serviceCallback); }
java
public ServiceFuture<List<CloudTask>> listAsync(final String jobId, final ListOperationCallback<CloudTask> serviceCallback) { return AzureServiceFuture.fromHeaderPageResponse( listSinglePageAsync(jobId), new Func1<String, Observable<ServiceResponseWithHeaders<Page<CloudTask>, TaskListHeaders>>>() { @Override public Observable<ServiceResponseWithHeaders<Page<CloudTask>, TaskListHeaders>> call(String nextPageLink) { return listNextSinglePageAsync(nextPageLink, null); } }, serviceCallback); }
[ "public", "ServiceFuture", "<", "List", "<", "CloudTask", ">", ">", "listAsync", "(", "final", "String", "jobId", ",", "final", "ListOperationCallback", "<", "CloudTask", ">", "serviceCallback", ")", "{", "return", "AzureServiceFuture", ".", "fromHeaderPageResponse"...
Lists all of the tasks that are associated with the specified job. For multi-instance tasks, information such as affinityId, executionInfo and nodeInfo refer to the primary task. Use the list subtasks API to retrieve information about subtasks. @param jobId The ID of the job. @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object
[ "Lists", "all", "of", "the", "tasks", "that", "are", "associated", "with", "the", "specified", "job", ".", "For", "multi", "-", "instance", "tasks", "information", "such", "as", "affinityId", "executionInfo", "and", "nodeInfo", "refer", "to", "the", "primary",...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/TasksImpl.java#L373-L383
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/SearchIndex.java
SearchIndex.createSortFields
protected SortField[] createSortFields(QPath[] orderProps, boolean[] orderSpecs, FieldComparatorSource scs) throws RepositoryException { List<SortField> sortFields = new ArrayList<SortField>(); for (int i = 0; i < orderProps.length; i++) { if (orderProps[i].getEntries().length == 1 && Constants.JCR_SCORE.equals(orderProps[i].getName())) { // order on jcr:score does not use the natural order as // implemented in lucene. score ascending in lucene means that // higher scores are first. JCR specs that lower score values // are first. sortFields.add(new SortField(null, SortField.SCORE, orderSpecs[i])); } else { String jcrPath = npResolver.createJCRPath(orderProps[i]).getAsString(false); sortFields.add(new SortField(jcrPath, scs, !orderSpecs[i])); } } return sortFields.toArray(new SortField[sortFields.size()]); }
java
protected SortField[] createSortFields(QPath[] orderProps, boolean[] orderSpecs, FieldComparatorSource scs) throws RepositoryException { List<SortField> sortFields = new ArrayList<SortField>(); for (int i = 0; i < orderProps.length; i++) { if (orderProps[i].getEntries().length == 1 && Constants.JCR_SCORE.equals(orderProps[i].getName())) { // order on jcr:score does not use the natural order as // implemented in lucene. score ascending in lucene means that // higher scores are first. JCR specs that lower score values // are first. sortFields.add(new SortField(null, SortField.SCORE, orderSpecs[i])); } else { String jcrPath = npResolver.createJCRPath(orderProps[i]).getAsString(false); sortFields.add(new SortField(jcrPath, scs, !orderSpecs[i])); } } return sortFields.toArray(new SortField[sortFields.size()]); }
[ "protected", "SortField", "[", "]", "createSortFields", "(", "QPath", "[", "]", "orderProps", ",", "boolean", "[", "]", "orderSpecs", ",", "FieldComparatorSource", "scs", ")", "throws", "RepositoryException", "{", "List", "<", "SortField", ">", "sortFields", "="...
Creates the SortFields for the order properties. @param orderProps the order properties. @param orderSpecs the order specs for the properties. @param scs {@link FieldComparatorSource} case sensitive or case insensitive comparator @return an array of sort fields @throws RepositoryException
[ "Creates", "the", "SortFields", "for", "the", "order", "properties", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/SearchIndex.java#L1773-L1794
line/armeria
core/src/main/java/com/linecorp/armeria/server/cors/AbstractCorsPolicyBuilder.java
AbstractCorsPolicyBuilder.preflightResponseHeader
public B preflightResponseHeader(CharSequence name, Object... values) { requireNonNull(name, "name"); requireNonNull(values, "values"); checkArgument(values.length > 0, "values should not be empty."); for (int i = 0; i < values.length; i++) { if (values[i] == null) { throw new NullPointerException("values[" + i + ']'); } } preflightResponseHeaders.put(HttpHeaderNames.of(name), new ConstantValueSupplier(ImmutableList.copyOf(values))); return self(); }
java
public B preflightResponseHeader(CharSequence name, Object... values) { requireNonNull(name, "name"); requireNonNull(values, "values"); checkArgument(values.length > 0, "values should not be empty."); for (int i = 0; i < values.length; i++) { if (values[i] == null) { throw new NullPointerException("values[" + i + ']'); } } preflightResponseHeaders.put(HttpHeaderNames.of(name), new ConstantValueSupplier(ImmutableList.copyOf(values))); return self(); }
[ "public", "B", "preflightResponseHeader", "(", "CharSequence", "name", ",", "Object", "...", "values", ")", "{", "requireNonNull", "(", "name", ",", "\"name\"", ")", ";", "requireNonNull", "(", "values", ",", "\"values\"", ")", ";", "checkArgument", "(", "valu...
Specifies HTTP response headers that should be added to a CORS preflight response. <p>An intermediary like a load balancer might require that a CORS preflight request have certain headers set. This enables such headers to be added. @param name the name of the HTTP header. @param values the values for the HTTP header. @return {@code this} to support method chaining.
[ "Specifies", "HTTP", "response", "headers", "that", "should", "be", "added", "to", "a", "CORS", "preflight", "response", "." ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/cors/AbstractCorsPolicyBuilder.java#L291-L303
EdwardRaff/JSAT
JSAT/src/jsat/distributions/Levy.java
Levy.setScale
public void setScale(double scale) { if(scale <= 0 || Double.isNaN(scale) || Double.isInfinite(scale)) throw new ArithmeticException("Scale must be a positive value, not " + scale); this.scale = scale; this.logScale = log(scale); }
java
public void setScale(double scale) { if(scale <= 0 || Double.isNaN(scale) || Double.isInfinite(scale)) throw new ArithmeticException("Scale must be a positive value, not " + scale); this.scale = scale; this.logScale = log(scale); }
[ "public", "void", "setScale", "(", "double", "scale", ")", "{", "if", "(", "scale", "<=", "0", "||", "Double", ".", "isNaN", "(", "scale", ")", "||", "Double", ".", "isInfinite", "(", "scale", ")", ")", "throw", "new", "ArithmeticException", "(", "\"Sc...
Sets the scale of the Levy distribution @param scale the new scale value, must be positive
[ "Sets", "the", "scale", "of", "the", "Levy", "distribution" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/distributions/Levy.java#L33-L39
Waikato/moa
moa/src/main/java/moa/clusterers/dstream/Dstream.java
Dstream.mergeClusters
private void mergeClusters (int smallClus, int bigClus) { //System.out.println("Merge clusters "+smallClus+" and "+bigClus+"."); // Iterate through the density grids in grid_list to find those which are in highClass for (Map.Entry<DensityGrid, CharacteristicVector> grid : grid_list.entrySet()) { DensityGrid dg = grid.getKey(); CharacteristicVector cv = grid.getValue(); // Assign density grids in smallClus to bigClus if(cv.getLabel() == smallClus) { cv.setLabel(bigClus); this.grid_list.put(dg, cv); } } //System.out.println("Density grids assigned to cluster "+bigClus+"."); // Merge the GridCluster objects representing each cluster GridCluster bGC = this.cluster_list.get(bigClus); bGC.absorbCluster(this.cluster_list.get(smallClus)); this.cluster_list.set(bigClus, bGC); this.cluster_list.remove(smallClus); //System.out.println("Cluster "+smallClus+" removed from list."); cleanClusters(); }
java
private void mergeClusters (int smallClus, int bigClus) { //System.out.println("Merge clusters "+smallClus+" and "+bigClus+"."); // Iterate through the density grids in grid_list to find those which are in highClass for (Map.Entry<DensityGrid, CharacteristicVector> grid : grid_list.entrySet()) { DensityGrid dg = grid.getKey(); CharacteristicVector cv = grid.getValue(); // Assign density grids in smallClus to bigClus if(cv.getLabel() == smallClus) { cv.setLabel(bigClus); this.grid_list.put(dg, cv); } } //System.out.println("Density grids assigned to cluster "+bigClus+"."); // Merge the GridCluster objects representing each cluster GridCluster bGC = this.cluster_list.get(bigClus); bGC.absorbCluster(this.cluster_list.get(smallClus)); this.cluster_list.set(bigClus, bGC); this.cluster_list.remove(smallClus); //System.out.println("Cluster "+smallClus+" removed from list."); cleanClusters(); }
[ "private", "void", "mergeClusters", "(", "int", "smallClus", ",", "int", "bigClus", ")", "{", "//System.out.println(\"Merge clusters \"+smallClus+\" and \"+bigClus+\".\");", "// Iterate through the density grids in grid_list to find those which are in highClass", "for", "(", "Map", "...
Reassign all grids belonging in the small cluster to the big cluster Merge the GridCluster objects representing each cluster @param smallClus - the index of the smaller cluster @param bigClus - the index of the bigger cluster
[ "Reassign", "all", "grids", "belonging", "in", "the", "small", "cluster", "to", "the", "big", "cluster", "Merge", "the", "GridCluster", "objects", "representing", "each", "cluster" ]
train
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/dstream/Dstream.java#L1255-L1280
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.subsidiaryPrice_GET
public OvhPrice subsidiaryPrice_GET(String flavorId, OvhOvhSubsidiaryEnum ovhSubsidiary, String region) throws IOException { String qPath = "/cloud/subsidiaryPrice"; StringBuilder sb = path(qPath); query(sb, "flavorId", flavorId); query(sb, "ovhSubsidiary", ovhSubsidiary); query(sb, "region", region); String resp = execN(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhPrice.class); }
java
public OvhPrice subsidiaryPrice_GET(String flavorId, OvhOvhSubsidiaryEnum ovhSubsidiary, String region) throws IOException { String qPath = "/cloud/subsidiaryPrice"; StringBuilder sb = path(qPath); query(sb, "flavorId", flavorId); query(sb, "ovhSubsidiary", ovhSubsidiary); query(sb, "region", region); String resp = execN(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhPrice.class); }
[ "public", "OvhPrice", "subsidiaryPrice_GET", "(", "String", "flavorId", ",", "OvhOvhSubsidiaryEnum", "ovhSubsidiary", ",", "String", "region", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/subsidiaryPrice\"", ";", "StringBuilder", "sb", "=", "pa...
Get services prices for a subsidiary REST: GET /cloud/subsidiaryPrice @param ovhSubsidiary [required] OVH subsidiary @param flavorId [required] OVH cloud flavor id @param region [required] Region
[ "Get", "services", "prices", "for", "a", "subsidiary" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L107-L115
foundation-runtime/service-directory
2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/connect/DirectoryConnection.java
DirectoryConnection.generateDirectoryAuthData
private AuthData generateDirectoryAuthData(String userName, String password) { if(password != null && ! password.isEmpty()){ byte[] secret = ObfuscatUtil.base64Encode(password.getBytes()); return new AuthData(AuthScheme.DIRECTORY, userName, secret, true); } else { return new AuthData(AuthScheme.DIRECTORY, userName, null, false); } }
java
private AuthData generateDirectoryAuthData(String userName, String password) { if(password != null && ! password.isEmpty()){ byte[] secret = ObfuscatUtil.base64Encode(password.getBytes()); return new AuthData(AuthScheme.DIRECTORY, userName, secret, true); } else { return new AuthData(AuthScheme.DIRECTORY, userName, null, false); } }
[ "private", "AuthData", "generateDirectoryAuthData", "(", "String", "userName", ",", "String", "password", ")", "{", "if", "(", "password", "!=", "null", "&&", "!", "password", ".", "isEmpty", "(", ")", ")", "{", "byte", "[", "]", "secret", "=", "ObfuscatUt...
Generate the obfuscated auth data. @param userName the user name. @param password the password. @return the AuthData.
[ "Generate", "the", "obfuscated", "auth", "data", "." ]
train
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/connect/DirectoryConnection.java#L960-L968
infinispan/infinispan
core/src/main/java/org/infinispan/util/stream/Streams.java
Streams.copySome
public static long copySome(final InputStream input, final OutputStream output, final long length) throws IOException { return copySome(input, output, DEFAULT_BUFFER_SIZE, length); }
java
public static long copySome(final InputStream input, final OutputStream output, final long length) throws IOException { return copySome(input, output, DEFAULT_BUFFER_SIZE, length); }
[ "public", "static", "long", "copySome", "(", "final", "InputStream", "input", ",", "final", "OutputStream", "output", ",", "final", "long", "length", ")", "throws", "IOException", "{", "return", "copySome", "(", "input", ",", "output", ",", "DEFAULT_BUFFER_SIZE"...
Copy a limited number of bytes from the input stream to the output stream. @param input Stream to read bytes from. @param output Stream to write bytes to. @param length The maximum number of bytes to copy. @return The total number of bytes copied. @throws IOException Failed to copy bytes.
[ "Copy", "a", "limited", "number", "of", "bytes", "from", "the", "input", "stream", "to", "the", "output", "stream", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/util/stream/Streams.java#L407-L412
Waikato/moa
moa/src/main/java/moa/clusterers/clustree/Entry.java
Entry.emptyBuffer
protected ClusKernel emptyBuffer(long currentTime, double negLambda) { this.buffer.makeOlder(currentTime - this.timestamp, negLambda); ClusKernel bufferCopy = new ClusKernel(this.buffer); this.buffer.clear(); return bufferCopy; }
java
protected ClusKernel emptyBuffer(long currentTime, double negLambda) { this.buffer.makeOlder(currentTime - this.timestamp, negLambda); ClusKernel bufferCopy = new ClusKernel(this.buffer); this.buffer.clear(); return bufferCopy; }
[ "protected", "ClusKernel", "emptyBuffer", "(", "long", "currentTime", ",", "double", "negLambda", ")", "{", "this", ".", "buffer", ".", "makeOlder", "(", "currentTime", "-", "this", ".", "timestamp", ",", "negLambda", ")", ";", "ClusKernel", "bufferCopy", "=",...
Clear the buffer in this entry and return a copy. No side effects are possible (given that the copy constructor of <code>Kernel</code> makes a deep copy). @return A copy of the buffer.
[ "Clear", "the", "buffer", "in", "this", "entry", "and", "return", "a", "copy", ".", "No", "side", "effects", "are", "possible", "(", "given", "that", "the", "copy", "constructor", "of", "<code", ">", "Kernel<", "/", "code", ">", "makes", "a", "deep", "...
train
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/clustree/Entry.java#L371-L376
michael-rapp/AndroidPreferenceActivity
example/src/main/java/de/mrapp/android/preference/activity/example/fragment/AppearancePreferenceFragment.java
AppearancePreferenceFragment.createThemeChangeListener
private OnPreferenceChangeListener createThemeChangeListener() { return new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(final Preference preference, final Object newValue) { Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); return true; } }; }
java
private OnPreferenceChangeListener createThemeChangeListener() { return new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(final Preference preference, final Object newValue) { Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); return true; } }; }
[ "private", "OnPreferenceChangeListener", "createThemeChangeListener", "(", ")", "{", "return", "new", "OnPreferenceChangeListener", "(", ")", "{", "@", "Override", "public", "boolean", "onPreferenceChange", "(", "final", "Preference", "preference", ",", "final", "Object...
Creates and returns a listener, which allows to adapt the app's theme, when the value of the corresponding preference has been changed. @return The listener, which has been created, as an instance of the type {@link OnPreferenceChangeListener}
[ "Creates", "and", "returns", "a", "listener", "which", "allows", "to", "adapt", "the", "app", "s", "theme", "when", "the", "value", "of", "the", "corresponding", "preference", "has", "been", "changed", "." ]
train
https://github.com/michael-rapp/AndroidPreferenceActivity/blob/0fcde73815b4b3bf6bcb36acd3d5733e301bbba5/example/src/main/java/de/mrapp/android/preference/activity/example/fragment/AppearancePreferenceFragment.java#L46-L58
dickschoeller/gedbrowser
gedbrowser/src/main/java/org/schoellerfamily/gedbrowser/controller/PersonController.java
PersonController.nameHtml
private String nameHtml(final RenderingContext context, final Person person) { return nameRenderer(context, person).getNameHtml(); }
java
private String nameHtml(final RenderingContext context, final Person person) { return nameRenderer(context, person).getNameHtml(); }
[ "private", "String", "nameHtml", "(", "final", "RenderingContext", "context", ",", "final", "Person", "person", ")", "{", "return", "nameRenderer", "(", "context", ",", "person", ")", ".", "getNameHtml", "(", ")", ";", "}" ]
Get the name string in an html fragment format. @param context the rendering context @param person the person being rendered @return the name string
[ "Get", "the", "name", "string", "in", "an", "html", "fragment", "format", "." ]
train
https://github.com/dickschoeller/gedbrowser/blob/e3e10b1ff3a34ebde9b7edcbfafcd5fe6fb3b3e1/gedbrowser/src/main/java/org/schoellerfamily/gedbrowser/controller/PersonController.java#L113-L116
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/network/forwardingsession.java
forwardingsession.get
public static forwardingsession get(nitro_service service, String name) throws Exception{ forwardingsession obj = new forwardingsession(); obj.set_name(name); forwardingsession response = (forwardingsession) obj.get_resource(service); return response; }
java
public static forwardingsession get(nitro_service service, String name) throws Exception{ forwardingsession obj = new forwardingsession(); obj.set_name(name); forwardingsession response = (forwardingsession) obj.get_resource(service); return response; }
[ "public", "static", "forwardingsession", "get", "(", "nitro_service", "service", ",", "String", "name", ")", "throws", "Exception", "{", "forwardingsession", "obj", "=", "new", "forwardingsession", "(", ")", ";", "obj", ".", "set_name", "(", "name", ")", ";", ...
Use this API to fetch forwardingsession resource of given name .
[ "Use", "this", "API", "to", "fetch", "forwardingsession", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/network/forwardingsession.java#L320-L325
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/GanttBarStyleFactory14.java
GanttBarStyleFactory14.extractFlags
private void extractFlags(GanttBarStyle style, GanttBarShowForTasks baseCriteria, long flagValue) { int index = 0; long flag = 0x0001; while (index < 64) { if ((flagValue & flag) != 0) { GanttBarShowForTasks enumValue = GanttBarShowForTasks.getInstance(baseCriteria.getValue() + index); if (enumValue != null) { style.addShowForTasks(enumValue); } } flag = flag << 1; index++; } }
java
private void extractFlags(GanttBarStyle style, GanttBarShowForTasks baseCriteria, long flagValue) { int index = 0; long flag = 0x0001; while (index < 64) { if ((flagValue & flag) != 0) { GanttBarShowForTasks enumValue = GanttBarShowForTasks.getInstance(baseCriteria.getValue() + index); if (enumValue != null) { style.addShowForTasks(enumValue); } } flag = flag << 1; index++; } }
[ "private", "void", "extractFlags", "(", "GanttBarStyle", "style", ",", "GanttBarShowForTasks", "baseCriteria", ",", "long", "flagValue", ")", "{", "int", "index", "=", "0", ";", "long", "flag", "=", "0x0001", ";", "while", "(", "index", "<", "64", ")", "{"...
Extract the flags indicating which task types this bar style is relevant for. Note that this work for the "normal" task types and the "negated" task types (e.g. Normal Task, Not Normal task). The set of values used is determined by the baseCriteria argument. @param style parent bar style @param baseCriteria determines if the normal or negated enums are used @param flagValue flag data
[ "Extract", "the", "flags", "indicating", "which", "task", "types", "this", "bar", "style", "is", "relevant", "for", ".", "Note", "that", "this", "work", "for", "the", "normal", "task", "types", "and", "the", "negated", "task", "types", "(", "e", ".", "g"...
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/GanttBarStyleFactory14.java#L145-L165
netty/netty
transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueStreamChannel.java
AbstractKQueueStreamChannel.writeFileRegion
private int writeFileRegion(ChannelOutboundBuffer in, FileRegion region) throws Exception { if (region.transferred() >= region.count()) { in.remove(); return 0; } if (byteChannel == null) { byteChannel = new KQueueSocketWritableByteChannel(); } final long flushedAmount = region.transferTo(byteChannel, region.transferred()); if (flushedAmount > 0) { in.progress(flushedAmount); if (region.transferred() >= region.count()) { in.remove(); } return 1; } return WRITE_STATUS_SNDBUF_FULL; }
java
private int writeFileRegion(ChannelOutboundBuffer in, FileRegion region) throws Exception { if (region.transferred() >= region.count()) { in.remove(); return 0; } if (byteChannel == null) { byteChannel = new KQueueSocketWritableByteChannel(); } final long flushedAmount = region.transferTo(byteChannel, region.transferred()); if (flushedAmount > 0) { in.progress(flushedAmount); if (region.transferred() >= region.count()) { in.remove(); } return 1; } return WRITE_STATUS_SNDBUF_FULL; }
[ "private", "int", "writeFileRegion", "(", "ChannelOutboundBuffer", "in", ",", "FileRegion", "region", ")", "throws", "Exception", "{", "if", "(", "region", ".", "transferred", "(", ")", ">=", "region", ".", "count", "(", ")", ")", "{", "in", ".", "remove",...
Write a {@link FileRegion} @param in the collection which contains objects to write. @param region the {@link FileRegion} from which the bytes should be written @return The value that should be decremented from the write quantum which starts at {@link ChannelConfig#getWriteSpinCount()}. The typical use cases are as follows: <ul> <li>0 - if no write was attempted. This is appropriate if an empty {@link ByteBuf} (or other empty content) is encountered</li> <li>1 - if a single call to write data was made to the OS</li> <li>{@link ChannelUtils#WRITE_STATUS_SNDBUF_FULL} - if an attempt to write data was made to the OS, but no data was accepted</li> </ul>
[ "Write", "a", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueStreamChannel.java#L247-L265
roboconf/roboconf-platform
core/roboconf-plugin-script/src/main/java/net/roboconf/plugin/script/internal/templating/InstanceTemplateHelper.java
InstanceTemplateHelper.injectInstanceImports
public static void injectInstanceImports(Instance instance, String templateFilePath, File targetFile) throws IOException { OutputStream os = null; try { os = new FileOutputStream( targetFile ); OutputStreamWriter writer = new OutputStreamWriter( os, StandardCharsets.UTF_8.newEncoder()); injectInstanceImports( instance, templateFilePath, writer ); } finally { Utils.closeQuietly( os ); } }
java
public static void injectInstanceImports(Instance instance, String templateFilePath, File targetFile) throws IOException { OutputStream os = null; try { os = new FileOutputStream( targetFile ); OutputStreamWriter writer = new OutputStreamWriter( os, StandardCharsets.UTF_8.newEncoder()); injectInstanceImports( instance, templateFilePath, writer ); } finally { Utils.closeQuietly( os ); } }
[ "public", "static", "void", "injectInstanceImports", "(", "Instance", "instance", ",", "String", "templateFilePath", ",", "File", "targetFile", ")", "throws", "IOException", "{", "OutputStream", "os", "=", "null", ";", "try", "{", "os", "=", "new", "FileOutputSt...
Reads the import values of the instances and injects them into the template file. <p> See test resources to see the associated way to write templates </p> @param instance the instance whose imports must be injected @param templateFilePath the path of the template file @param targetFile the file to write into @throws IOException if something went wrong
[ "Reads", "the", "import", "values", "of", "the", "instances", "and", "injects", "them", "into", "the", "template", "file", ".", "<p", ">", "See", "test", "resources", "to", "see", "the", "associated", "way", "to", "write", "templates", "<", "/", "p", ">"...
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-plugin-script/src/main/java/net/roboconf/plugin/script/internal/templating/InstanceTemplateHelper.java#L105-L117
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java
BytecodeUtils.logicalNot
public static Expression logicalNot(final Expression baseExpr) { baseExpr.checkAssignableTo(Type.BOOLEAN_TYPE); checkArgument(baseExpr.resultType().equals(Type.BOOLEAN_TYPE), "not a boolean expression"); return new Expression(Type.BOOLEAN_TYPE, baseExpr.features()) { @Override protected void doGen(CodeBuilder mv) { baseExpr.gen(mv); // Surprisingly, java bytecode uses a branch (instead of 'xor 1' or something) to implement // this. This is most likely useful for allowing true to be represented by any non-zero // number. Label ifTrue = mv.newLabel(); Label end = mv.newLabel(); mv.ifZCmp(Opcodes.IFNE, ifTrue); // if not 0 goto ifTrue mv.pushBoolean(true); mv.goTo(end); mv.mark(ifTrue); mv.pushBoolean(false); mv.mark(end); } }; }
java
public static Expression logicalNot(final Expression baseExpr) { baseExpr.checkAssignableTo(Type.BOOLEAN_TYPE); checkArgument(baseExpr.resultType().equals(Type.BOOLEAN_TYPE), "not a boolean expression"); return new Expression(Type.BOOLEAN_TYPE, baseExpr.features()) { @Override protected void doGen(CodeBuilder mv) { baseExpr.gen(mv); // Surprisingly, java bytecode uses a branch (instead of 'xor 1' or something) to implement // this. This is most likely useful for allowing true to be represented by any non-zero // number. Label ifTrue = mv.newLabel(); Label end = mv.newLabel(); mv.ifZCmp(Opcodes.IFNE, ifTrue); // if not 0 goto ifTrue mv.pushBoolean(true); mv.goTo(end); mv.mark(ifTrue); mv.pushBoolean(false); mv.mark(end); } }; }
[ "public", "static", "Expression", "logicalNot", "(", "final", "Expression", "baseExpr", ")", "{", "baseExpr", ".", "checkAssignableTo", "(", "Type", ".", "BOOLEAN_TYPE", ")", ";", "checkArgument", "(", "baseExpr", ".", "resultType", "(", ")", ".", "equals", "(...
Returns an expression that evaluates to the logical negation of the given boolean valued expression.
[ "Returns", "an", "expression", "that", "evaluates", "to", "the", "logical", "negation", "of", "the", "given", "boolean", "valued", "expression", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java#L553-L573
carewebframework/carewebframework-vista
org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/Request.java
Request.addParameter
public void addParameter(String name, RPCParameter parameter) { for (String subscript : parameter) { addParameter(name, subscript, parameter.get(subscript)); } }
java
public void addParameter(String name, RPCParameter parameter) { for (String subscript : parameter) { addParameter(name, subscript, parameter.get(subscript)); } }
[ "public", "void", "addParameter", "(", "String", "name", ",", "RPCParameter", "parameter", ")", "{", "for", "(", "String", "subscript", ":", "parameter", ")", "{", "addParameter", "(", "name", ",", "subscript", ",", "parameter", ".", "get", "(", "subscript",...
Adds an RPC parameter to the request. @param name Parameter name. @param parameter RPC parameter.
[ "Adds", "an", "RPC", "parameter", "to", "the", "request", "." ]
train
https://github.com/carewebframework/carewebframework-vista/blob/883b2cbe395d9e8a21cd19db820f0876bda6b1c6/org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/Request.java#L166-L170
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF3.java
CommonOps_DDF3.addEquals
public static void addEquals( DMatrix3 a , DMatrix3 b ) { a.a1 += b.a1; a.a2 += b.a2; a.a3 += b.a3; }
java
public static void addEquals( DMatrix3 a , DMatrix3 b ) { a.a1 += b.a1; a.a2 += b.a2; a.a3 += b.a3; }
[ "public", "static", "void", "addEquals", "(", "DMatrix3", "a", ",", "DMatrix3", "b", ")", "{", "a", ".", "a1", "+=", "b", ".", "a1", ";", "a", ".", "a2", "+=", "b", ".", "a2", ";", "a", ".", "a3", "+=", "b", ".", "a3", ";", "}" ]
<p>Performs the following operation:<br> <br> a = a + b <br> a<sub>i</sub> = a<sub>i</sub> + b<sub>i</sub> <br> </p> @param a A Vector. Modified. @param b A Vector. Not modified.
[ "<p", ">", "Performs", "the", "following", "operation", ":", "<br", ">", "<br", ">", "a", "=", "a", "+", "b", "<br", ">", "a<sub", ">", "i<", "/", "sub", ">", "=", "a<sub", ">", "i<", "/", "sub", ">", "+", "b<sub", ">", "i<", "/", "sub", ">",...
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF3.java#L112-L116
apache/incubator-shardingsphere
sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/orderby/CompareUtil.java
CompareUtil.compareTo
@SuppressWarnings({ "rawtypes", "unchecked" }) public static int compareTo(final Comparable thisValue, final Comparable otherValue, final OrderDirection orderDirection, final OrderDirection nullOrderDirection) { if (null == thisValue && null == otherValue) { return 0; } if (null == thisValue) { return orderDirection == nullOrderDirection ? -1 : 1; } if (null == otherValue) { return orderDirection == nullOrderDirection ? 1 : -1; } return OrderDirection.ASC == orderDirection ? thisValue.compareTo(otherValue) : -thisValue.compareTo(otherValue); }
java
@SuppressWarnings({ "rawtypes", "unchecked" }) public static int compareTo(final Comparable thisValue, final Comparable otherValue, final OrderDirection orderDirection, final OrderDirection nullOrderDirection) { if (null == thisValue && null == otherValue) { return 0; } if (null == thisValue) { return orderDirection == nullOrderDirection ? -1 : 1; } if (null == otherValue) { return orderDirection == nullOrderDirection ? 1 : -1; } return OrderDirection.ASC == orderDirection ? thisValue.compareTo(otherValue) : -thisValue.compareTo(otherValue); }
[ "@", "SuppressWarnings", "(", "{", "\"rawtypes\"", ",", "\"unchecked\"", "}", ")", "public", "static", "int", "compareTo", "(", "final", "Comparable", "thisValue", ",", "final", "Comparable", "otherValue", ",", "final", "OrderDirection", "orderDirection", ",", "fi...
Compare two object with order type. @param thisValue this value @param otherValue other value @param orderDirection order direction @param nullOrderDirection order direction for null value @return compare result
[ "Compare", "two", "object", "with", "order", "type", "." ]
train
https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/orderby/CompareUtil.java#L41-L53
lucmoreau/ProvToolbox
prov-model/src/main/java/org/openprovenance/prov/model/ProvFactory.java
ProvFactory.newWasAssociatedWith
public WasAssociatedWith newWasAssociatedWith(QualifiedName id) { return newWasAssociatedWith(id, (QualifiedName)null,(QualifiedName)null); }
java
public WasAssociatedWith newWasAssociatedWith(QualifiedName id) { return newWasAssociatedWith(id, (QualifiedName)null,(QualifiedName)null); }
[ "public", "WasAssociatedWith", "newWasAssociatedWith", "(", "QualifiedName", "id", ")", "{", "return", "newWasAssociatedWith", "(", "id", ",", "(", "QualifiedName", ")", "null", ",", "(", "QualifiedName", ")", "null", ")", ";", "}" ]
A factory method to create an instance of an Association {@link WasAssociatedWith} @param id an identifier for the association @return an instance of {@link WasAssociatedWith}
[ "A", "factory", "method", "to", "create", "an", "instance", "of", "an", "Association", "{" ]
train
https://github.com/lucmoreau/ProvToolbox/blob/f865952868ffb69432937b08728c86bebbe4678a/prov-model/src/main/java/org/openprovenance/prov/model/ProvFactory.java#L1066-L1068
banq/jdonframework
src/main/java/com/jdon/aop/reflection/MethodConstructor.java
MethodConstructor.createObjectMethod
public Method createObjectMethod(Object ownerClass, MethodMetaArgs methodMetaArgs) { Method m = null; try { m = ownerClass.getClass().getMethod(methodMetaArgs.getMethodName(), methodMetaArgs.getParamTypes()); } catch (NoSuchMethodException nsme) { String errS = " NoSuchMethod:" + methodMetaArgs.getMethodName() + " in MethodMetaArgs of className:" + ownerClass.getClass().getName(); Debug.logError(errS, module); } catch (Exception ex) { Debug.logError("[JdonFramework] createMethod error:" + ex, module); } return m; }
java
public Method createObjectMethod(Object ownerClass, MethodMetaArgs methodMetaArgs) { Method m = null; try { m = ownerClass.getClass().getMethod(methodMetaArgs.getMethodName(), methodMetaArgs.getParamTypes()); } catch (NoSuchMethodException nsme) { String errS = " NoSuchMethod:" + methodMetaArgs.getMethodName() + " in MethodMetaArgs of className:" + ownerClass.getClass().getName(); Debug.logError(errS, module); } catch (Exception ex) { Debug.logError("[JdonFramework] createMethod error:" + ex, module); } return m; }
[ "public", "Method", "createObjectMethod", "(", "Object", "ownerClass", ",", "MethodMetaArgs", "methodMetaArgs", ")", "{", "Method", "m", "=", "null", ";", "try", "{", "m", "=", "ownerClass", ".", "getClass", "(", ")", ".", "getMethod", "(", "methodMetaArgs", ...
create a method object by target Object @param ownerClass @param methodMetaArgs @return
[ "create", "a", "method", "object", "by", "target", "Object" ]
train
https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/aop/reflection/MethodConstructor.java#L118-L131
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java
VirtualNetworkGatewaysInner.updateTagsAsync
public Observable<VirtualNetworkGatewayInner> updateTagsAsync(String resourceGroupName, String virtualNetworkGatewayName, Map<String, String> tags) { return updateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, tags).map(new Func1<ServiceResponse<VirtualNetworkGatewayInner>, VirtualNetworkGatewayInner>() { @Override public VirtualNetworkGatewayInner call(ServiceResponse<VirtualNetworkGatewayInner> response) { return response.body(); } }); }
java
public Observable<VirtualNetworkGatewayInner> updateTagsAsync(String resourceGroupName, String virtualNetworkGatewayName, Map<String, String> tags) { return updateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, tags).map(new Func1<ServiceResponse<VirtualNetworkGatewayInner>, VirtualNetworkGatewayInner>() { @Override public VirtualNetworkGatewayInner call(ServiceResponse<VirtualNetworkGatewayInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "VirtualNetworkGatewayInner", ">", "updateTagsAsync", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkGatewayName", ",", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "return", "updateTagsWithServiceResponseAs...
Updates a virtual network gateway tags. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @param tags Resource tags. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Updates", "a", "virtual", "network", "gateway", "tags", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java#L708-L715
Mozu/mozu-java
mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/OrderUrl.java
OrderUrl.getOrderUrl
public static MozuUrl getOrderUrl(Boolean draft, Boolean includeBin, String orderId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}?draft={draft}&includeBin={includeBin}&responseFields={responseFields}"); formatter.formatUrl("draft", draft); formatter.formatUrl("includeBin", includeBin); formatter.formatUrl("orderId", orderId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl getOrderUrl(Boolean draft, Boolean includeBin, String orderId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}?draft={draft}&includeBin={includeBin}&responseFields={responseFields}"); formatter.formatUrl("draft", draft); formatter.formatUrl("includeBin", includeBin); formatter.formatUrl("orderId", orderId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "getOrderUrl", "(", "Boolean", "draft", ",", "Boolean", "includeBin", ",", "String", "orderId", ",", "String", "responseFields", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/commerce/orders/{orderId}?dr...
Get Resource Url for GetOrder @param draft If true, retrieve the draft version of the order, which might include uncommitted changes to the order or its components. @param includeBin @param orderId Unique identifier of the order. @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @return String Resource Url
[ "Get", "Resource", "Url", "for", "GetOrder" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/OrderUrl.java#L74-L82
apache/incubator-heron
heron/packing/src/java/org/apache/heron/packing/binpacking/FirstFitDecreasingPacking.java
FirstFitDecreasingPacking.repack
public PackingPlan repack(PackingPlan currentPackingPlan, Map<String, Integer> componentChanges) { PackingPlanBuilder planBuilder = newPackingPlanBuilder(currentPackingPlan); // Get the instances using FFD allocation try { planBuilder = getFFDAllocation(planBuilder, currentPackingPlan, componentChanges); } catch (ConstraintViolationException e) { throw new PackingException("Could not repack instances into existing packing plan", e); } return planBuilder.build(); }
java
public PackingPlan repack(PackingPlan currentPackingPlan, Map<String, Integer> componentChanges) { PackingPlanBuilder planBuilder = newPackingPlanBuilder(currentPackingPlan); // Get the instances using FFD allocation try { planBuilder = getFFDAllocation(planBuilder, currentPackingPlan, componentChanges); } catch (ConstraintViolationException e) { throw new PackingException("Could not repack instances into existing packing plan", e); } return planBuilder.build(); }
[ "public", "PackingPlan", "repack", "(", "PackingPlan", "currentPackingPlan", ",", "Map", "<", "String", ",", "Integer", ">", "componentChanges", ")", "{", "PackingPlanBuilder", "planBuilder", "=", "newPackingPlanBuilder", "(", "currentPackingPlan", ")", ";", "// Get t...
Get a new packing plan given an existing packing plan and component-level changes. @return new packing plan
[ "Get", "a", "new", "packing", "plan", "given", "an", "existing", "packing", "plan", "and", "component", "-", "level", "changes", "." ]
train
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/binpacking/FirstFitDecreasingPacking.java#L153-L164
lucee/Lucee
core/src/main/java/lucee/runtime/config/XMLConfigAdmin.java
XMLConfigAdmin.updateCacheHandler
public void updateCacheHandler(String id, ClassDefinition cd) throws PageException { checkWriteAccess(); _updateCacheHandler(id, cd); }
java
public void updateCacheHandler(String id, ClassDefinition cd) throws PageException { checkWriteAccess(); _updateCacheHandler(id, cd); }
[ "public", "void", "updateCacheHandler", "(", "String", "id", ",", "ClassDefinition", "cd", ")", "throws", "PageException", "{", "checkWriteAccess", "(", ")", ";", "_updateCacheHandler", "(", "id", ",", "cd", ")", ";", "}" ]
/* public static void updateCacheHandler(ConfigImpl config, String id, ClassDefinition cd, boolean reload) throws IOException, SAXException, PageException, BundleException { ConfigWebAdmin admin = new ConfigWebAdmin(config, null); admin._updateCacheHandler(id, cd); admin._store(); if(reload)admin._reload(); }
[ "/", "*", "public", "static", "void", "updateCacheHandler", "(", "ConfigImpl", "config", "String", "id", "ClassDefinition", "cd", "boolean", "reload", ")", "throws", "IOException", "SAXException", "PageException", "BundleException", "{", "ConfigWebAdmin", "admin", "="...
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/config/XMLConfigAdmin.java#L4066-L4069
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUBinary.java
ICUBinary.readHeaderAndDataVersion
public static VersionInfo readHeaderAndDataVersion(ByteBuffer bytes, int dataFormat, Authenticate authenticate) throws IOException { return getVersionInfoFromCompactInt(readHeader(bytes, dataFormat, authenticate)); }
java
public static VersionInfo readHeaderAndDataVersion(ByteBuffer bytes, int dataFormat, Authenticate authenticate) throws IOException { return getVersionInfoFromCompactInt(readHeader(bytes, dataFormat, authenticate)); }
[ "public", "static", "VersionInfo", "readHeaderAndDataVersion", "(", "ByteBuffer", "bytes", ",", "int", "dataFormat", ",", "Authenticate", "authenticate", ")", "throws", "IOException", "{", "return", "getVersionInfoFromCompactInt", "(", "readHeader", "(", "bytes", ",", ...
Same as readHeader(), but returns a VersionInfo rather than a compact int.
[ "Same", "as", "readHeader", "()", "but", "returns", "a", "VersionInfo", "rather", "than", "a", "compact", "int", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUBinary.java#L556-L561
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/UnitQuaternions.java
UnitQuaternions.orientationMetric
public static double orientationMetric(Quat4d q1, Quat4d q2) { return Math.acos(Math.abs(dotProduct(q1, q2))); }
java
public static double orientationMetric(Quat4d q1, Quat4d q2) { return Math.acos(Math.abs(dotProduct(q1, q2))); }
[ "public", "static", "double", "orientationMetric", "(", "Quat4d", "q1", ",", "Quat4d", "q2", ")", "{", "return", "Math", ".", "acos", "(", "Math", ".", "abs", "(", "dotProduct", "(", "q1", ",", "q2", ")", ")", ")", ";", "}" ]
The orientation metric is obtained by comparing two unit quaternion orientations. <p> The two quaternions are compared using the formula: d(q1,q2) = arccos(|q1*q2|). The range of the metric is [0, Pi/2], where 0 means the same orientation and Pi/2 means the opposite orientation. <p> The formula is taken from: Huynh, D. Q. (2009). Metrics for 3D rotations: comparison and analysis. Journal of Mathematical Imaging and Vision, 35(2), 155–164. http://doi.org/10.1007/s10851-009-0161-2 @param q1 quaternion as Quat4d object @param q2 quaternion as Quat4d object @return the quaternion orientation metric
[ "The", "orientation", "metric", "is", "obtained", "by", "comparing", "two", "unit", "quaternion", "orientations", ".", "<p", ">", "The", "two", "quaternions", "are", "compared", "using", "the", "formula", ":", "d", "(", "q1", "q2", ")", "=", "arccos", "(",...
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/UnitQuaternions.java#L98-L100
jbundle/jbundle
thin/base/util/util/src/main/java/org/jbundle/thin/base/util/Application.java
Application.getRemoteTask
public RemoteTask getRemoteTask(Task localTaskOwner, String strUserID, boolean bCreateIfNotFound) { return this.getRemoteTask(localTaskOwner, strUserID, null, bCreateIfNotFound); }
java
public RemoteTask getRemoteTask(Task localTaskOwner, String strUserID, boolean bCreateIfNotFound) { return this.getRemoteTask(localTaskOwner, strUserID, null, bCreateIfNotFound); }
[ "public", "RemoteTask", "getRemoteTask", "(", "Task", "localTaskOwner", ",", "String", "strUserID", ",", "boolean", "bCreateIfNotFound", ")", "{", "return", "this", ".", "getRemoteTask", "(", "localTaskOwner", ",", "strUserID", ",", "null", ",", "bCreateIfNotFound",...
Get the connection to the server for this applet. Optionally create the server connection. @param localTaskOwner The task that will own this remote task (or application) server) [If null, get the app server]. @param strUserID The user id (or name) to initialize the server's application to. @param bCreateIfNotFound If the server is null, initialize the server. @return The server object (application defined).
[ "Get", "the", "connection", "to", "the", "server", "for", "this", "applet", ".", "Optionally", "create", "the", "server", "connection", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/util/util/src/main/java/org/jbundle/thin/base/util/Application.java#L382-L385
oasp/oasp4j
modules/rest/src/main/java/io/oasp/module/rest/service/impl/RestServiceExceptionFacade.java
RestServiceExceptionFacade.handleGenericError
protected Response handleGenericError(Throwable exception, Throwable catched) { NlsRuntimeException userError; boolean logged = false; if (exception instanceof NlsThrowable) { NlsThrowable nlsError = (NlsThrowable) exception; if (!nlsError.isTechnical()) { LOG.warn("Service failed due to business error: {}", nlsError.getMessage()); logged = true; } userError = TechnicalErrorUserException.getOrCreateUserException(exception); } else { userError = TechnicalErrorUserException.getOrCreateUserException(catched); } if (!logged) { LOG.error("Service failed on server", userError); } return createResponse(userError); }
java
protected Response handleGenericError(Throwable exception, Throwable catched) { NlsRuntimeException userError; boolean logged = false; if (exception instanceof NlsThrowable) { NlsThrowable nlsError = (NlsThrowable) exception; if (!nlsError.isTechnical()) { LOG.warn("Service failed due to business error: {}", nlsError.getMessage()); logged = true; } userError = TechnicalErrorUserException.getOrCreateUserException(exception); } else { userError = TechnicalErrorUserException.getOrCreateUserException(catched); } if (!logged) { LOG.error("Service failed on server", userError); } return createResponse(userError); }
[ "protected", "Response", "handleGenericError", "(", "Throwable", "exception", ",", "Throwable", "catched", ")", "{", "NlsRuntimeException", "userError", ";", "boolean", "logged", "=", "false", ";", "if", "(", "exception", "instanceof", "NlsThrowable", ")", "{", "N...
Exception handling for generic exception (fallback). @param exception the exception to handle @param catched the original exception that was cached. Either same as {@code error} or a (child-) {@link Throwable#getCause() cause} of it. @return the response build from the exception
[ "Exception", "handling", "for", "generic", "exception", "(", "fallback", ")", "." ]
train
https://github.com/oasp/oasp4j/blob/03f90132699fad95e52ec8efa54aa391f8d3c7e4/modules/rest/src/main/java/io/oasp/module/rest/service/impl/RestServiceExceptionFacade.java#L270-L288
Netflix/eureka
eureka-client/src/main/java/com/netflix/discovery/shared/Applications.java
Applications.shuffleAndFilterInstances
private void shuffleAndFilterInstances(Map<String, VipIndexSupport> srcMap, boolean filterUpInstances) { Random shuffleRandom = new Random(); for (Map.Entry<String, VipIndexSupport> entries : srcMap.entrySet()) { VipIndexSupport vipIndexSupport = entries.getValue(); AbstractQueue<InstanceInfo> vipInstances = vipIndexSupport.instances; final List<InstanceInfo> filteredInstances; if (filterUpInstances) { filteredInstances = vipInstances.stream().filter(ii -> ii.getStatus() == InstanceStatus.UP) .collect(Collectors.toCollection(() -> new ArrayList<>(vipInstances.size()))); } else { filteredInstances = new ArrayList<InstanceInfo>(vipInstances); } Collections.shuffle(filteredInstances, shuffleRandom); vipIndexSupport.vipList.set(filteredInstances); vipIndexSupport.roundRobinIndex.set(0); } }
java
private void shuffleAndFilterInstances(Map<String, VipIndexSupport> srcMap, boolean filterUpInstances) { Random shuffleRandom = new Random(); for (Map.Entry<String, VipIndexSupport> entries : srcMap.entrySet()) { VipIndexSupport vipIndexSupport = entries.getValue(); AbstractQueue<InstanceInfo> vipInstances = vipIndexSupport.instances; final List<InstanceInfo> filteredInstances; if (filterUpInstances) { filteredInstances = vipInstances.stream().filter(ii -> ii.getStatus() == InstanceStatus.UP) .collect(Collectors.toCollection(() -> new ArrayList<>(vipInstances.size()))); } else { filteredInstances = new ArrayList<InstanceInfo>(vipInstances); } Collections.shuffle(filteredInstances, shuffleRandom); vipIndexSupport.vipList.set(filteredInstances); vipIndexSupport.roundRobinIndex.set(0); } }
[ "private", "void", "shuffleAndFilterInstances", "(", "Map", "<", "String", ",", "VipIndexSupport", ">", "srcMap", ",", "boolean", "filterUpInstances", ")", "{", "Random", "shuffleRandom", "=", "new", "Random", "(", ")", ";", "for", "(", "Map", ".", "Entry", ...
Shuffle the instances and filter for only {@link InstanceStatus#UP} if required.
[ "Shuffle", "the", "instances", "and", "filter", "for", "only", "{", "@link", "InstanceStatus#UP", "}", "if", "required", "." ]
train
https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-client/src/main/java/com/netflix/discovery/shared/Applications.java#L350-L367
ironjacamar/ironjacamar
codegenerator/src/main/java/org/ironjacamar/codegenerator/code/MlCodeGen.java
MlCodeGen.writeClassBody
@Override public void writeClassBody(Definition def, Writer out) throws IOException { int indent = 1; out.write("public interface " + getClassName(def)); writeLeftCurlyBracket(out, 0); writeWithIndent(out, indent, "/**\n"); writeWithIndent(out, indent, " * Receive message\n"); writeWithIndent(out, indent, " * @param msg String.\n"); writeWithIndent(out, indent, " */\n"); writeWithIndent(out, indent, "public void onMessage(String msg);"); writeRightCurlyBracket(out, 0); }
java
@Override public void writeClassBody(Definition def, Writer out) throws IOException { int indent = 1; out.write("public interface " + getClassName(def)); writeLeftCurlyBracket(out, 0); writeWithIndent(out, indent, "/**\n"); writeWithIndent(out, indent, " * Receive message\n"); writeWithIndent(out, indent, " * @param msg String.\n"); writeWithIndent(out, indent, " */\n"); writeWithIndent(out, indent, "public void onMessage(String msg);"); writeRightCurlyBracket(out, 0); }
[ "@", "Override", "public", "void", "writeClassBody", "(", "Definition", "def", ",", "Writer", "out", ")", "throws", "IOException", "{", "int", "indent", "=", "1", ";", "out", ".", "write", "(", "\"public interface \"", "+", "getClassName", "(", "def", ")", ...
Output class @param def definition @param out Writer @throws IOException ioException
[ "Output", "class" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/code/MlCodeGen.java#L44-L58
zandero/http
src/main/java/com/zandero/http/RequestUtils.java
RequestUtils.checkBasicAuth
public static boolean checkBasicAuth(HttpServletRequest servletRequest, String username, String password) { String basicAuth = servletRequest.getHeader("Authorization"); if (StringUtils.isNullOrEmptyTrimmed(basicAuth) || !basicAuth.startsWith("Basic ")) { return false; } String base64Credentials = basicAuth.substring("Basic".length()).trim(); String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8")); // credentials = username:password final String[] values = credentials.split(":", 2); if (values.length != 2) { return false; } return StringUtils.equals(values[0], username) && StringUtils.equals(values[1], password); }
java
public static boolean checkBasicAuth(HttpServletRequest servletRequest, String username, String password) { String basicAuth = servletRequest.getHeader("Authorization"); if (StringUtils.isNullOrEmptyTrimmed(basicAuth) || !basicAuth.startsWith("Basic ")) { return false; } String base64Credentials = basicAuth.substring("Basic".length()).trim(); String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8")); // credentials = username:password final String[] values = credentials.split(":", 2); if (values.length != 2) { return false; } return StringUtils.equals(values[0], username) && StringUtils.equals(values[1], password); }
[ "public", "static", "boolean", "checkBasicAuth", "(", "HttpServletRequest", "servletRequest", ",", "String", "username", ",", "String", "password", ")", "{", "String", "basicAuth", "=", "servletRequest", ".", "getHeader", "(", "\"Authorization\"", ")", ";", "if", ...
Checks if request is made by cron job @param servletRequest must be GET request with cron job basic authorization set @param username to check agains @param password to check against @return true if cron job request, false if not
[ "Checks", "if", "request", "is", "made", "by", "cron", "job" ]
train
https://github.com/zandero/http/blob/909eb879f1193adf24545360c3b76bd813865f65/src/main/java/com/zandero/http/RequestUtils.java#L162-L179
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/distort/brown/AddBrownPtoN_F32.java
AddBrownPtoN_F32.setDistortion
public AddBrownPtoN_F32 setDistortion( /**/double[] radial, /**/double t1, /**/double t2) { params = new RadialTangential_F32(radial, t1, t2); return this; }
java
public AddBrownPtoN_F32 setDistortion( /**/double[] radial, /**/double t1, /**/double t2) { params = new RadialTangential_F32(radial, t1, t2); return this; }
[ "public", "AddBrownPtoN_F32", "setDistortion", "(", "/**/", "double", "[", "]", "radial", ",", "/**/", "double", "t1", ",", "/**/", "double", "t2", ")", "{", "params", "=", "new", "RadialTangential_F32", "(", "radial", ",", "t1", ",", "t2", ")", ";", "re...
Specify intrinsic camera parameters @param radial Radial distortion parameters
[ "Specify", "intrinsic", "camera", "parameters" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/distort/brown/AddBrownPtoN_F32.java#L67-L70
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderService.java
SpiderService.scalarValueToString
public static String scalarValueToString(TableDefinition tableDef, String fieldName, byte[] colValue) { // Only binary fields are treated specially. FieldDefinition fieldDef = tableDef.getFieldDef(fieldName); if (fieldDef != null && fieldDef.isBinaryField()) { return fieldDef.getEncoding().encode(colValue); } else { return Utils.toString(colValue); } }
java
public static String scalarValueToString(TableDefinition tableDef, String fieldName, byte[] colValue) { // Only binary fields are treated specially. FieldDefinition fieldDef = tableDef.getFieldDef(fieldName); if (fieldDef != null && fieldDef.isBinaryField()) { return fieldDef.getEncoding().encode(colValue); } else { return Utils.toString(colValue); } }
[ "public", "static", "String", "scalarValueToString", "(", "TableDefinition", "tableDef", ",", "String", "fieldName", ",", "byte", "[", "]", "colValue", ")", "{", "// Only binary fields are treated specially.\r", "FieldDefinition", "fieldDef", "=", "tableDef", ".", "getF...
Convert the given binary scalar field value to string form based on its definition. This method is the twin of {@link #scalarValueToBinary(TableDefinition, String, String)}. @param tableDef TableDefinition that defines field. @param fieldName Name of a scalar field. @param colValue Binary column value. @return Scalar value as a string.
[ "Convert", "the", "given", "binary", "scalar", "field", "value", "to", "string", "form", "based", "on", "its", "definition", ".", "This", "method", "is", "the", "twin", "of", "{", "@link", "#scalarValueToBinary", "(", "TableDefinition", "String", "String", ")"...
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderService.java#L339-L347
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/NodeImpl.java
NodeImpl.doAddNode
private NodeImpl doAddNode(NodeImpl parentNode, InternalQName name, InternalQName primaryTypeName, NodeDefinitionData nodeDef) throws ItemExistsException, RepositoryException, ConstraintViolationException, VersionException, LockException { validateChildNode(parentNode, name, primaryTypeName, nodeDef); // Initialize data InternalQName[] mixinTypeNames = new InternalQName[0]; String identifier = IdGenerator.generate(); int orderNum = parentNode.getNextChildOrderNum(); int index = parentNode.getNextChildIndex(name, primaryTypeName, parentNode.nodeData(), nodeDef); QPath path = QPath.makeChildPath(parentNode.getInternalPath(), name, index); AccessControlList acl = parentNode.getACL(); // create new nodedata, [PN] fix of use index as persisted version NodeData nodeData = new TransientNodeData(path, identifier, -1, primaryTypeName, mixinTypeNames, orderNum, parentNode .getInternalIdentifier(), acl); // Create new Node ItemState state = ItemState.createAddedState(nodeData, false); NodeImpl node = (NodeImpl)dataManager.update(state, true); NodeTypeDataManager ntmanager = session.getWorkspace().getNodeTypesHolder(); ItemAutocreator itemAutocreator = new ItemAutocreator(ntmanager, valueFactory, dataManager, true); PlainChangesLog changes = itemAutocreator.makeAutoCreatedItems(node.nodeData(), primaryTypeName, dataManager, session.getUserID()); for (ItemState autoCreatedState : changes.getAllStates()) { dataManager.updateItemState(autoCreatedState); } session.getActionHandler().postAddNode(node); return node; }
java
private NodeImpl doAddNode(NodeImpl parentNode, InternalQName name, InternalQName primaryTypeName, NodeDefinitionData nodeDef) throws ItemExistsException, RepositoryException, ConstraintViolationException, VersionException, LockException { validateChildNode(parentNode, name, primaryTypeName, nodeDef); // Initialize data InternalQName[] mixinTypeNames = new InternalQName[0]; String identifier = IdGenerator.generate(); int orderNum = parentNode.getNextChildOrderNum(); int index = parentNode.getNextChildIndex(name, primaryTypeName, parentNode.nodeData(), nodeDef); QPath path = QPath.makeChildPath(parentNode.getInternalPath(), name, index); AccessControlList acl = parentNode.getACL(); // create new nodedata, [PN] fix of use index as persisted version NodeData nodeData = new TransientNodeData(path, identifier, -1, primaryTypeName, mixinTypeNames, orderNum, parentNode .getInternalIdentifier(), acl); // Create new Node ItemState state = ItemState.createAddedState(nodeData, false); NodeImpl node = (NodeImpl)dataManager.update(state, true); NodeTypeDataManager ntmanager = session.getWorkspace().getNodeTypesHolder(); ItemAutocreator itemAutocreator = new ItemAutocreator(ntmanager, valueFactory, dataManager, true); PlainChangesLog changes = itemAutocreator.makeAutoCreatedItems(node.nodeData(), primaryTypeName, dataManager, session.getUserID()); for (ItemState autoCreatedState : changes.getAllStates()) { dataManager.updateItemState(autoCreatedState); } session.getActionHandler().postAddNode(node); return node; }
[ "private", "NodeImpl", "doAddNode", "(", "NodeImpl", "parentNode", ",", "InternalQName", "name", ",", "InternalQName", "primaryTypeName", ",", "NodeDefinitionData", "nodeDef", ")", "throws", "ItemExistsException", ",", "RepositoryException", ",", "ConstraintViolationExcepti...
Do add node internally. If nodeDef not null it is used in getNextChildIndex() method to avoid double calculation.
[ "Do", "add", "node", "internally", ".", "If", "nodeDef", "not", "null", "it", "is", "used", "in", "getNextChildIndex", "()", "method", "to", "avoid", "double", "calculation", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/NodeImpl.java#L3054-L3093
pac4j/pac4j
pac4j-core/src/main/java/org/pac4j/core/profile/service/AbstractProfileService.java
AbstractProfileService.convertProfileAndPasswordToAttributes
protected Map<String, Object> convertProfileAndPasswordToAttributes(final U profile, final String password) { final Map<String, Object> storageAttributes = new HashMap<>(); storageAttributes.put(getIdAttribute(), profile.getId()); storageAttributes.put(LINKEDID, profile.getLinkedId()); storageAttributes.put(getUsernameAttribute(), profile.getUsername()); // if a password has been provided, encode it if (isNotBlank(password)) { final String encodedPassword; // encode password if we have a passwordEncoder (MongoDB, SQL but not for LDAP) if (passwordEncoder != null) { encodedPassword = passwordEncoder.encode(password); } else { encodedPassword = password; } storageAttributes.put(getPasswordAttribute(), encodedPassword); } // legacy mode: save the defined attributes if (isLegacyMode()) { for (final String attributeName : attributeNames) { storageAttributes.put(attributeName, profile.getAttribute(attributeName)); } } else { // new behaviour (>= v2.0): save the serialized profile storageAttributes.put(SERIALIZED_PROFILE, javaSerializationHelper.serializeToBase64(profile)); } return storageAttributes; }
java
protected Map<String, Object> convertProfileAndPasswordToAttributes(final U profile, final String password) { final Map<String, Object> storageAttributes = new HashMap<>(); storageAttributes.put(getIdAttribute(), profile.getId()); storageAttributes.put(LINKEDID, profile.getLinkedId()); storageAttributes.put(getUsernameAttribute(), profile.getUsername()); // if a password has been provided, encode it if (isNotBlank(password)) { final String encodedPassword; // encode password if we have a passwordEncoder (MongoDB, SQL but not for LDAP) if (passwordEncoder != null) { encodedPassword = passwordEncoder.encode(password); } else { encodedPassword = password; } storageAttributes.put(getPasswordAttribute(), encodedPassword); } // legacy mode: save the defined attributes if (isLegacyMode()) { for (final String attributeName : attributeNames) { storageAttributes.put(attributeName, profile.getAttribute(attributeName)); } } else { // new behaviour (>= v2.0): save the serialized profile storageAttributes.put(SERIALIZED_PROFILE, javaSerializationHelper.serializeToBase64(profile)); } return storageAttributes; }
[ "protected", "Map", "<", "String", ",", "Object", ">", "convertProfileAndPasswordToAttributes", "(", "final", "U", "profile", ",", "final", "String", "password", ")", "{", "final", "Map", "<", "String", ",", "Object", ">", "storageAttributes", "=", "new", "Has...
Convert a profile and a password into a map of attributes for the storage. @param profile the profile @param password the password @return the attributes
[ "Convert", "a", "profile", "and", "a", "password", "into", "a", "map", "of", "attributes", "for", "the", "storage", "." ]
train
https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/profile/service/AbstractProfileService.java#L122-L148
opsmatters/opsmatters-core
src/main/java/com/opsmatters/core/documents/Workbook.java
Workbook.getWorkbook
public static Workbook getWorkbook(String filename, InputStream stream) throws IOException { Workbook ret = null; String lowerFilename = filename.toLowerCase(); if(lowerFilename.endsWith("."+CommonFiles.XLS_EXT)) { ret = XlsWorkbook.getWorkbook(stream); } else if(lowerFilename.endsWith("."+CommonFiles.XLSX_EXT)) { XlsxWorkbook.initJaxbContexts(); ret = XlsxWorkbook.getWorkbook(stream); } return ret; }
java
public static Workbook getWorkbook(String filename, InputStream stream) throws IOException { Workbook ret = null; String lowerFilename = filename.toLowerCase(); if(lowerFilename.endsWith("."+CommonFiles.XLS_EXT)) { ret = XlsWorkbook.getWorkbook(stream); } else if(lowerFilename.endsWith("."+CommonFiles.XLSX_EXT)) { XlsxWorkbook.initJaxbContexts(); ret = XlsxWorkbook.getWorkbook(stream); } return ret; }
[ "public", "static", "Workbook", "getWorkbook", "(", "String", "filename", ",", "InputStream", "stream", ")", "throws", "IOException", "{", "Workbook", "ret", "=", "null", ";", "String", "lowerFilename", "=", "filename", ".", "toLowerCase", "(", ")", ";", "if",...
Returns an existing workbook object. @param filename The filename of the workbook @param stream The input stream for the workbook @return The existing workbook object @throws IOException if the file cannot be read
[ "Returns", "an", "existing", "workbook", "object", "." ]
train
https://github.com/opsmatters/opsmatters-core/blob/c48904f7e8d029fd45357811ec38a735e261e3fd/src/main/java/com/opsmatters/core/documents/Workbook.java#L66-L81
RestComm/sip-servlets
sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java
FacebookRestClient.pages_getInfo
public T pages_getInfo(Collection<Long> pageIds, EnumSet<PageProfileField> fields) throws FacebookException, IOException { if (pageIds == null || pageIds.isEmpty()) { throw new IllegalArgumentException("pageIds cannot be empty or null"); } if (fields == null || fields.isEmpty()) { throw new IllegalArgumentException("fields cannot be empty or null"); } IFacebookMethod method = null == this._sessionKey ? FacebookMethod.PAGES_GET_INFO_NO_SESSION : FacebookMethod.PAGES_GET_INFO; return this.callMethod(method, new Pair<String, CharSequence>("page_ids", delimit(pageIds)), new Pair<String, CharSequence>("fields", delimit(fields))); }
java
public T pages_getInfo(Collection<Long> pageIds, EnumSet<PageProfileField> fields) throws FacebookException, IOException { if (pageIds == null || pageIds.isEmpty()) { throw new IllegalArgumentException("pageIds cannot be empty or null"); } if (fields == null || fields.isEmpty()) { throw new IllegalArgumentException("fields cannot be empty or null"); } IFacebookMethod method = null == this._sessionKey ? FacebookMethod.PAGES_GET_INFO_NO_SESSION : FacebookMethod.PAGES_GET_INFO; return this.callMethod(method, new Pair<String, CharSequence>("page_ids", delimit(pageIds)), new Pair<String, CharSequence>("fields", delimit(fields))); }
[ "public", "T", "pages_getInfo", "(", "Collection", "<", "Long", ">", "pageIds", ",", "EnumSet", "<", "PageProfileField", ">", "fields", ")", "throws", "FacebookException", ",", "IOException", "{", "if", "(", "pageIds", "==", "null", "||", "pageIds", ".", "is...
Retrieves the requested profile fields for the Facebook Pages with the given <code>pageIds</code>. Can be called for pages that have added the application without establishing a session. @param pageIds the page IDs @param fields a set of page profile fields @return a T consisting of a list of pages, with each page element containing the requested fields. @see <a href="http://wiki.developers.facebook.com/index.php/Pages.getInfo"> Developers Wiki: Pages.getInfo</a>
[ "Retrieves", "the", "requested", "profile", "fields", "for", "the", "Facebook", "Pages", "with", "the", "given", "<code", ">", "pageIds<", "/", "code", ">", ".", "Can", "be", "called", "for", "pages", "that", "have", "added", "the", "application", "without",...
train
https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L2078-L2091
eclipse/xtext-core
org.eclipse.xtext/src-gen/org/eclipse/xtext/serializer/XtextSemanticSequencer.java
XtextSemanticSequencer.sequence_Conjunction
protected void sequence_Conjunction(ISerializationContext context, Conjunction semanticObject) { if (errorAcceptor != null) { if (transientValues.isValueTransient(semanticObject, XtextPackage.Literals.COMPOSITE_CONDITION__LEFT) == ValueTransient.YES) errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, XtextPackage.Literals.COMPOSITE_CONDITION__LEFT)); if (transientValues.isValueTransient(semanticObject, XtextPackage.Literals.COMPOSITE_CONDITION__RIGHT) == ValueTransient.YES) errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, XtextPackage.Literals.COMPOSITE_CONDITION__RIGHT)); } SequenceFeeder feeder = createSequencerFeeder(context, semanticObject); feeder.accept(grammarAccess.getConjunctionAccess().getConjunctionLeftAction_1_0(), semanticObject.getLeft()); feeder.accept(grammarAccess.getConjunctionAccess().getRightNegationParserRuleCall_1_2_0(), semanticObject.getRight()); feeder.finish(); }
java
protected void sequence_Conjunction(ISerializationContext context, Conjunction semanticObject) { if (errorAcceptor != null) { if (transientValues.isValueTransient(semanticObject, XtextPackage.Literals.COMPOSITE_CONDITION__LEFT) == ValueTransient.YES) errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, XtextPackage.Literals.COMPOSITE_CONDITION__LEFT)); if (transientValues.isValueTransient(semanticObject, XtextPackage.Literals.COMPOSITE_CONDITION__RIGHT) == ValueTransient.YES) errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, XtextPackage.Literals.COMPOSITE_CONDITION__RIGHT)); } SequenceFeeder feeder = createSequencerFeeder(context, semanticObject); feeder.accept(grammarAccess.getConjunctionAccess().getConjunctionLeftAction_1_0(), semanticObject.getLeft()); feeder.accept(grammarAccess.getConjunctionAccess().getRightNegationParserRuleCall_1_2_0(), semanticObject.getRight()); feeder.finish(); }
[ "protected", "void", "sequence_Conjunction", "(", "ISerializationContext", "context", ",", "Conjunction", "semanticObject", ")", "{", "if", "(", "errorAcceptor", "!=", "null", ")", "{", "if", "(", "transientValues", ".", "isValueTransient", "(", "semanticObject", ",...
Contexts: Disjunction returns Conjunction Disjunction.Disjunction_1_0 returns Conjunction Conjunction returns Conjunction Conjunction.Conjunction_1_0 returns Conjunction Negation returns Conjunction Atom returns Conjunction ParenthesizedCondition returns Conjunction Constraint: (left=Conjunction_Conjunction_1_0 right=Negation)
[ "Contexts", ":", "Disjunction", "returns", "Conjunction", "Disjunction", ".", "Disjunction_1_0", "returns", "Conjunction", "Conjunction", "returns", "Conjunction", "Conjunction", ".", "Conjunction_1_0", "returns", "Conjunction", "Negation", "returns", "Conjunction", "Atom",...
train
https://github.com/eclipse/xtext-core/blob/bac941cb75cb24706519845ec174cfef874d7557/org.eclipse.xtext/src-gen/org/eclipse/xtext/serializer/XtextSemanticSequencer.java#L673-L684
google/j2objc
jre_emul/android/frameworks/base/core/java/android/util/Log.java
Log.wtf
public static int wtf(String tag, String msg) { return wtf(LOG_ID_MAIN, tag, msg, null, false); }
java
public static int wtf(String tag, String msg) { return wtf(LOG_ID_MAIN, tag, msg, null, false); }
[ "public", "static", "int", "wtf", "(", "String", "tag", ",", "String", "msg", ")", "{", "return", "wtf", "(", "LOG_ID_MAIN", ",", "tag", ",", "msg", ",", "null", ",", "false", ")", ";", "}" ]
What a Terrible Failure: Report a condition that should never happen. The error will always be logged at level ASSERT with the call stack. @param tag Used to identify the source of a log message. @param msg The message you would like logged.
[ "What", "a", "Terrible", "Failure", ":", "Report", "a", "condition", "that", "should", "never", "happen", ".", "The", "error", "will", "always", "be", "logged", "at", "level", "ASSERT", "with", "the", "call", "stack", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/frameworks/base/core/java/android/util/Log.java#L303-L305
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/xen/xen_panwvpx_image.java
xen_panwvpx_image.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { xen_panwvpx_image_responses result = (xen_panwvpx_image_responses) service.get_payload_formatter().string_to_resource(xen_panwvpx_image_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.xen_panwvpx_image_response_array); } xen_panwvpx_image[] result_xen_panwvpx_image = new xen_panwvpx_image[result.xen_panwvpx_image_response_array.length]; for(int i = 0; i < result.xen_panwvpx_image_response_array.length; i++) { result_xen_panwvpx_image[i] = result.xen_panwvpx_image_response_array[i].xen_panwvpx_image[0]; } return result_xen_panwvpx_image; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { xen_panwvpx_image_responses result = (xen_panwvpx_image_responses) service.get_payload_formatter().string_to_resource(xen_panwvpx_image_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.xen_panwvpx_image_response_array); } xen_panwvpx_image[] result_xen_panwvpx_image = new xen_panwvpx_image[result.xen_panwvpx_image_response_array.length]; for(int i = 0; i < result.xen_panwvpx_image_response_array.length; i++) { result_xen_panwvpx_image[i] = result.xen_panwvpx_image_response_array[i].xen_panwvpx_image[0]; } return result_xen_panwvpx_image; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "xen_panwvpx_image_responses", "result", "=", "(", "xen_panwvpx_image_responses", ")", "service", ".", "get_pa...
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/xen/xen_panwvpx_image.java#L264-L281
molgenis/molgenis
molgenis-data-postgresql/src/main/java/org/molgenis/data/postgresql/PostgreSqlExceptionTranslator.java
PostgreSqlExceptionTranslator.translateDependentObjectsStillExist
MolgenisValidationException translateDependentObjectsStillExist(PSQLException pSqlException) { ServerErrorMessage serverErrorMessage = pSqlException.getServerErrorMessage(); String detail = serverErrorMessage.getDetail(); Matcher matcher = Pattern.compile( "constraint (.+) on table \"?([^\"]+)\"? depends on table \"?([^\"]+)\"?\n?") .matcher(detail); Map<String, Set<String>> entityTypeDependencyMap = new LinkedHashMap<>(); while (matcher.find()) { String tableName = matcher.group(2); String dependentTableName = matcher.group(3); String entityTypeName = tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN); String dependentEntityTypeName = tryGetEntityTypeName(dependentTableName).orElse(TOKEN_UNKNOWN); Set<String> dependentTableNames = entityTypeDependencyMap.computeIfAbsent( dependentEntityTypeName, k -> new LinkedHashSet<>()); dependentTableNames.add(entityTypeName); } if (entityTypeDependencyMap.isEmpty()) // no matches { LOG.error(ERROR_TRANSLATING_POSTGRES_EXC_MSG, pSqlException); throw new RuntimeException(ERROR_TRANSLATING_EXCEPTION_MSG, pSqlException); } Set<ConstraintViolation> constraintViolations = entityTypeDependencyMap .entrySet() .stream() .map( entry -> { String message; if (entry.getValue().size() == 1) { message = format( "Cannot delete entity '%s' because entity '%s' depends on it.", entry.getKey(), entry.getValue().iterator().next()); } else { message = format( "Cannot delete entity '%s' because entities '%s' depend on it.", entry.getKey(), entry.getValue().stream().collect(joining(", "))); } return new ConstraintViolation(message, null); }) .collect(toCollection(LinkedHashSet::new)); return new MolgenisValidationException(constraintViolations); }
java
MolgenisValidationException translateDependentObjectsStillExist(PSQLException pSqlException) { ServerErrorMessage serverErrorMessage = pSqlException.getServerErrorMessage(); String detail = serverErrorMessage.getDetail(); Matcher matcher = Pattern.compile( "constraint (.+) on table \"?([^\"]+)\"? depends on table \"?([^\"]+)\"?\n?") .matcher(detail); Map<String, Set<String>> entityTypeDependencyMap = new LinkedHashMap<>(); while (matcher.find()) { String tableName = matcher.group(2); String dependentTableName = matcher.group(3); String entityTypeName = tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN); String dependentEntityTypeName = tryGetEntityTypeName(dependentTableName).orElse(TOKEN_UNKNOWN); Set<String> dependentTableNames = entityTypeDependencyMap.computeIfAbsent( dependentEntityTypeName, k -> new LinkedHashSet<>()); dependentTableNames.add(entityTypeName); } if (entityTypeDependencyMap.isEmpty()) // no matches { LOG.error(ERROR_TRANSLATING_POSTGRES_EXC_MSG, pSqlException); throw new RuntimeException(ERROR_TRANSLATING_EXCEPTION_MSG, pSqlException); } Set<ConstraintViolation> constraintViolations = entityTypeDependencyMap .entrySet() .stream() .map( entry -> { String message; if (entry.getValue().size() == 1) { message = format( "Cannot delete entity '%s' because entity '%s' depends on it.", entry.getKey(), entry.getValue().iterator().next()); } else { message = format( "Cannot delete entity '%s' because entities '%s' depend on it.", entry.getKey(), entry.getValue().stream().collect(joining(", "))); } return new ConstraintViolation(message, null); }) .collect(toCollection(LinkedHashSet::new)); return new MolgenisValidationException(constraintViolations); }
[ "MolgenisValidationException", "translateDependentObjectsStillExist", "(", "PSQLException", "pSqlException", ")", "{", "ServerErrorMessage", "serverErrorMessage", "=", "pSqlException", ".", "getServerErrorMessage", "(", ")", ";", "String", "detail", "=", "serverErrorMessage", ...
Package private for testability @param pSqlException PostgreSQL exception @return translated validation exception
[ "Package", "private", "for", "testability" ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-data-postgresql/src/main/java/org/molgenis/data/postgresql/PostgreSqlExceptionTranslator.java#L172-L223
apereo/cas
support/cas-server-support-saml-sp-integrations/src/main/java/org/apereo/cas/util/SamlSPUtils.java
SamlSPUtils.saveService
public static void saveService(final RegisteredService service, final ServicesManager servicesManager) { servicesManager.load(); if (servicesManager.findServiceBy(registeredService -> registeredService instanceof SamlRegisteredService && registeredService.getServiceId().equals(service.getServiceId())).isEmpty()) { LOGGER.info("Service [{}] does not exist in the registry and will be added.", service.getServiceId()); servicesManager.save(service); servicesManager.load(); } else { LOGGER.info("Service [{}] exists in the registry and will not be added again.", service.getServiceId()); } }
java
public static void saveService(final RegisteredService service, final ServicesManager servicesManager) { servicesManager.load(); if (servicesManager.findServiceBy(registeredService -> registeredService instanceof SamlRegisteredService && registeredService.getServiceId().equals(service.getServiceId())).isEmpty()) { LOGGER.info("Service [{}] does not exist in the registry and will be added.", service.getServiceId()); servicesManager.save(service); servicesManager.load(); } else { LOGGER.info("Service [{}] exists in the registry and will not be added again.", service.getServiceId()); } }
[ "public", "static", "void", "saveService", "(", "final", "RegisteredService", "service", ",", "final", "ServicesManager", "servicesManager", ")", "{", "servicesManager", ".", "load", "(", ")", ";", "if", "(", "servicesManager", ".", "findServiceBy", "(", "register...
Save service only if it's not already found in the registry. @param service the service @param servicesManager the services manager
[ "Save", "service", "only", "if", "it", "s", "not", "already", "found", "in", "the", "registry", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-saml-sp-integrations/src/main/java/org/apereo/cas/util/SamlSPUtils.java#L146-L157
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.msgstore/src/com/ibm/ws/sib/msgstore/cache/links/AbstractItemLink.java
AbstractItemLink.removeIfMatches
public final AbstractItem removeIfMatches(final Filter filter, PersistentTransaction transaction) throws ProtocolException, TransactionException, SevereMessageStoreException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "removeIfMatches", new Object[] { filter, transaction }); AbstractItem foundItem = cmdRemoveIfMatches(filter, transaction); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "removeIfMatches", foundItem); return foundItem; }
java
public final AbstractItem removeIfMatches(final Filter filter, PersistentTransaction transaction) throws ProtocolException, TransactionException, SevereMessageStoreException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "removeIfMatches", new Object[] { filter, transaction }); AbstractItem foundItem = cmdRemoveIfMatches(filter, transaction); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "removeIfMatches", foundItem); return foundItem; }
[ "public", "final", "AbstractItem", "removeIfMatches", "(", "final", "Filter", "filter", ",", "PersistentTransaction", "transaction", ")", "throws", "ProtocolException", ",", "TransactionException", ",", "SevereMessageStoreException", "{", "if", "(", "TraceComponent", ".",...
remove the item if it matches and is available @param filter @param transaction @return item if locked @throws ProtocolException Thrown if an add is attempted when the transaction cannot allow any further work to be added i.e. after completion of the transaction. @throws TransactionException Thrown if an unexpected error occurs. @throws SevereMessageStoreException
[ "remove", "the", "item", "if", "it", "matches", "and", "is", "available" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.msgstore/src/com/ibm/ws/sib/msgstore/cache/links/AbstractItemLink.java#L3916-L3926
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/geom/GoogleMapShapeConverter.java
GoogleMapShapeConverter.toCompoundCurve
public CompoundCurve toCompoundCurve(List<Polyline> polylineList, boolean hasZ, boolean hasM) { CompoundCurve compoundCurve = new CompoundCurve(hasZ, hasM); for (Polyline polyline : polylineList) { LineString lineString = toLineString(polyline); compoundCurve.addLineString(lineString); } return compoundCurve; }
java
public CompoundCurve toCompoundCurve(List<Polyline> polylineList, boolean hasZ, boolean hasM) { CompoundCurve compoundCurve = new CompoundCurve(hasZ, hasM); for (Polyline polyline : polylineList) { LineString lineString = toLineString(polyline); compoundCurve.addLineString(lineString); } return compoundCurve; }
[ "public", "CompoundCurve", "toCompoundCurve", "(", "List", "<", "Polyline", ">", "polylineList", ",", "boolean", "hasZ", ",", "boolean", "hasM", ")", "{", "CompoundCurve", "compoundCurve", "=", "new", "CompoundCurve", "(", "hasZ", ",", "hasM", ")", ";", "for",...
Convert a list of {@link Polyline} to a {@link CompoundCurve} @param polylineList polyline list @param hasZ has z flag @param hasM has m flag @return compound curve
[ "Convert", "a", "list", "of", "{", "@link", "Polyline", "}", "to", "a", "{", "@link", "CompoundCurve", "}" ]
train
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/geom/GoogleMapShapeConverter.java#L1136-L1147
aws/aws-sdk-java
aws-java-sdk-mq/src/main/java/com/amazonaws/services/mq/model/Configuration.java
Configuration.withTags
public Configuration withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
java
public Configuration withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "Configuration", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
The list of all tags associated with this configuration. @param tags The list of all tags associated with this configuration. @return Returns a reference to this object so that method calls can be chained together.
[ "The", "list", "of", "all", "tags", "associated", "with", "this", "configuration", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-mq/src/main/java/com/amazonaws/services/mq/model/Configuration.java#L384-L387
dwdyer/watchmaker
framework/src/java/main/org/uncommons/watchmaker/framework/CachingFitnessEvaluator.java
CachingFitnessEvaluator.getFitness
public double getFitness(T candidate, List<? extends T> population) { Double fitness = cache.get(candidate); if (fitness == null) { fitness = delegate.getFitness(candidate, population); cache.put(candidate, fitness); } return fitness; }
java
public double getFitness(T candidate, List<? extends T> population) { Double fitness = cache.get(candidate); if (fitness == null) { fitness = delegate.getFitness(candidate, population); cache.put(candidate, fitness); } return fitness; }
[ "public", "double", "getFitness", "(", "T", "candidate", ",", "List", "<", "?", "extends", "T", ">", "population", ")", "{", "Double", "fitness", "=", "cache", ".", "get", "(", "candidate", ")", ";", "if", "(", "fitness", "==", "null", ")", "{", "fit...
{@inheritDoc} <p>This implementation performs a cache look-up every time it is invoked. If the fitness evaluator has already calculated the fitness score for the specified candidate that score is returned without delegating to the wrapped evaluator.</p>
[ "{", "@inheritDoc", "}" ]
train
https://github.com/dwdyer/watchmaker/blob/33d942350e6bf7d9a17b9262a4f898158530247e/framework/src/java/main/org/uncommons/watchmaker/framework/CachingFitnessEvaluator.java#L78-L87
samskivert/pythagoras
src/main/java/pythagoras/d/Matrix4.java
Matrix4.setToTransform
public Matrix4 setToTransform (IVector3 translation, IQuaternion rotation) { return setToRotation(rotation).setTranslation(translation); }
java
public Matrix4 setToTransform (IVector3 translation, IQuaternion rotation) { return setToRotation(rotation).setTranslation(translation); }
[ "public", "Matrix4", "setToTransform", "(", "IVector3", "translation", ",", "IQuaternion", "rotation", ")", "{", "return", "setToRotation", "(", "rotation", ")", ".", "setTranslation", "(", "translation", ")", ";", "}" ]
Sets this to a matrix that first rotates, then translates. @return a reference to this matrix, for chaining.
[ "Sets", "this", "to", "a", "matrix", "that", "first", "rotates", "then", "translates", "." ]
train
https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/d/Matrix4.java#L103-L105
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractMemberWriter.java
AbstractMemberWriter.addNavDetailLink
protected void addNavDetailLink(SortedSet<Element> members, Content liNav) { addNavDetailLink(!members.isEmpty(), liNav); }
java
protected void addNavDetailLink(SortedSet<Element> members, Content liNav) { addNavDetailLink(!members.isEmpty(), liNav); }
[ "protected", "void", "addNavDetailLink", "(", "SortedSet", "<", "Element", ">", "members", ",", "Content", "liNav", ")", "{", "addNavDetailLink", "(", "!", "members", ".", "isEmpty", "(", ")", ",", "liNav", ")", ";", "}" ]
Add the navigation detail link. @param members the members to be linked @param liNav the content tree to which the navigation detail link will be added
[ "Add", "the", "navigation", "detail", "link", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractMemberWriter.java#L477-L479
jtablesaw/tablesaw
core/src/main/java/tech/tablesaw/joining/DataFrameJoiner.java
DataFrameJoiner.inner
public Table inner(boolean allowDuplicateColumnNames, Table... tables) { Table joined = table; for (Table currT : tables) { joined = joinInternal(joined, currT, false, allowDuplicateColumnNames, columnNames); } return joined; }
java
public Table inner(boolean allowDuplicateColumnNames, Table... tables) { Table joined = table; for (Table currT : tables) { joined = joinInternal(joined, currT, false, allowDuplicateColumnNames, columnNames); } return joined; }
[ "public", "Table", "inner", "(", "boolean", "allowDuplicateColumnNames", ",", "Table", "...", "tables", ")", "{", "Table", "joined", "=", "table", ";", "for", "(", "Table", "currT", ":", "tables", ")", "{", "joined", "=", "joinInternal", "(", "joined", ","...
Joins to the given tables assuming that they have a column of the name we're joining on @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column have the same name if {@code true} the join will succeed and duplicate columns are renamed* @param tables The tables to join with
[ "Joins", "to", "the", "given", "tables", "assuming", "that", "they", "have", "a", "column", "of", "the", "name", "we", "re", "joining", "on" ]
train
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/joining/DataFrameJoiner.java#L86-L93
aws/aws-sdk-java
aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/GetMethodResponseResult.java
GetMethodResponseResult.withResponseModels
public GetMethodResponseResult withResponseModels(java.util.Map<String, String> responseModels) { setResponseModels(responseModels); return this; }
java
public GetMethodResponseResult withResponseModels(java.util.Map<String, String> responseModels) { setResponseModels(responseModels); return this; }
[ "public", "GetMethodResponseResult", "withResponseModels", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "responseModels", ")", "{", "setResponseModels", "(", "responseModels", ")", ";", "return", "this", ";", "}" ]
<p> Specifies the <a>Model</a> resources used for the response's content-type. Response models are represented as a key/value map, with a content-type as the key and a <a>Model</a> name as the value. </p> @param responseModels Specifies the <a>Model</a> resources used for the response's content-type. Response models are represented as a key/value map, with a content-type as the key and a <a>Model</a> name as the value. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "Specifies", "the", "<a", ">", "Model<", "/", "a", ">", "resources", "used", "for", "the", "response", "s", "content", "-", "type", ".", "Response", "models", "are", "represented", "as", "a", "key", "/", "value", "map", "with", "a", "content...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/GetMethodResponseResult.java#L278-L281
santhosh-tekuri/jlibs
core/src/main/java/jlibs/core/io/IOUtil.java
IOUtil.pump
public static CharArrayWriter2 pump(Reader reader, boolean closeReader) throws IOException{ return pump(reader, new CharArrayWriter2(), closeReader, true); }
java
public static CharArrayWriter2 pump(Reader reader, boolean closeReader) throws IOException{ return pump(reader, new CharArrayWriter2(), closeReader, true); }
[ "public", "static", "CharArrayWriter2", "pump", "(", "Reader", "reader", ",", "boolean", "closeReader", ")", "throws", "IOException", "{", "return", "pump", "(", "reader", ",", "new", "CharArrayWriter2", "(", ")", ",", "closeReader", ",", "true", ")", ";", "...
Reads data from <code>reader</code> and writes it into an instanceof {@link CharArrayWriter2}.<br> @param reader reader from which data is read @param closeReader close reader or not @return the instance of {@link CharArrayWriter2} into which data is written @throws IOException if an I/O error occurs.
[ "Reads", "data", "from", "<code", ">", "reader<", "/", "code", ">", "and", "writes", "it", "into", "an", "instanceof", "{", "@link", "CharArrayWriter2", "}", ".", "<br", ">" ]
train
https://github.com/santhosh-tekuri/jlibs/blob/59c28719f054123cf778278154e1b92e943ad232/core/src/main/java/jlibs/core/io/IOUtil.java#L157-L159
threerings/narya
core/src/main/java/com/threerings/presents/server/InvocationManager.java
InvocationManager.registerProvider
public <T extends InvocationMarshaller<?>> T registerProvider ( InvocationProvider provider, Class<T> mclass) { return registerProvider(provider, mclass, null); }
java
public <T extends InvocationMarshaller<?>> T registerProvider ( InvocationProvider provider, Class<T> mclass) { return registerProvider(provider, mclass, null); }
[ "public", "<", "T", "extends", "InvocationMarshaller", "<", "?", ">", ">", "T", "registerProvider", "(", "InvocationProvider", "provider", ",", "Class", "<", "T", ">", "mclass", ")", "{", "return", "registerProvider", "(", "provider", ",", "mclass", ",", "nu...
Registers the supplied invocation service provider. @param provider the provider to be registered. @param mclass the class of the invocation marshaller generated for the service.
[ "Registers", "the", "supplied", "invocation", "service", "provider", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/InvocationManager.java#L110-L114
apache/flink
flink-optimizer/src/main/java/org/apache/flink/optimizer/Optimizer.java
Optimizer.createPreOptimizedPlan
public static List<DataSinkNode> createPreOptimizedPlan(Plan program) { GraphCreatingVisitor graphCreator = new GraphCreatingVisitor(1, null); program.accept(graphCreator); return graphCreator.getSinks(); }
java
public static List<DataSinkNode> createPreOptimizedPlan(Plan program) { GraphCreatingVisitor graphCreator = new GraphCreatingVisitor(1, null); program.accept(graphCreator); return graphCreator.getSinks(); }
[ "public", "static", "List", "<", "DataSinkNode", ">", "createPreOptimizedPlan", "(", "Plan", "program", ")", "{", "GraphCreatingVisitor", "graphCreator", "=", "new", "GraphCreatingVisitor", "(", "1", ",", "null", ")", ";", "program", ".", "accept", "(", "graphCr...
This function performs only the first step to the compilation process - the creation of the optimizer representation of the plan. No estimations or enumerations of alternatives are done here. @param program The plan to generate the optimizer representation for. @return The optimizer representation of the plan, as a collection of all data sinks from the plan can be traversed.
[ "This", "function", "performs", "only", "the", "first", "step", "to", "the", "compilation", "process", "-", "the", "creation", "of", "the", "optimizer", "representation", "of", "the", "plan", ".", "No", "estimations", "or", "enumerations", "of", "alternatives", ...
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-optimizer/src/main/java/org/apache/flink/optimizer/Optimizer.java#L540-L544
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java
TaskManagerService.buildTaskRecord
private TaskRecord buildTaskRecord(String taskID, Iterator<DColumn> colIter) { TaskRecord taskRecord = new TaskRecord(taskID); while (colIter.hasNext()) { DColumn col = colIter.next(); taskRecord.setProperty(col.getName(), col.getValue()); } return taskRecord; }
java
private TaskRecord buildTaskRecord(String taskID, Iterator<DColumn> colIter) { TaskRecord taskRecord = new TaskRecord(taskID); while (colIter.hasNext()) { DColumn col = colIter.next(); taskRecord.setProperty(col.getName(), col.getValue()); } return taskRecord; }
[ "private", "TaskRecord", "buildTaskRecord", "(", "String", "taskID", ",", "Iterator", "<", "DColumn", ">", "colIter", ")", "{", "TaskRecord", "taskRecord", "=", "new", "TaskRecord", "(", "taskID", ")", ";", "while", "(", "colIter", ".", "hasNext", "(", ")", ...
Create a TaskRecord from a task status row read from the Tasks table.
[ "Create", "a", "TaskRecord", "from", "a", "task", "status", "row", "read", "from", "the", "Tasks", "table", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java#L474-L481
eurekaclinical/eurekaclinical-common
src/main/java/org/eurekaclinical/common/comm/clients/EurekaClinicalClient.java
EurekaClinicalClient.doPostCreateMultipart
protected URI doPostCreateMultipart(String path, InputStream inputStream) throws ClientException { return doPostCreateMultipart(path, inputStream, null); }
java
protected URI doPostCreateMultipart(String path, InputStream inputStream) throws ClientException { return doPostCreateMultipart(path, inputStream, null); }
[ "protected", "URI", "doPostCreateMultipart", "(", "String", "path", ",", "InputStream", "inputStream", ")", "throws", "ClientException", "{", "return", "doPostCreateMultipart", "(", "path", ",", "inputStream", ",", "null", ")", ";", "}" ]
Creates a resource specified as a multi-part form in an input stream. Adds appropriate Accepts and Content Type headers. @param path the the API to call. @param inputStream the multi-part form content. @return the URI representing the created resource, for use in subsequent operations on the resource. @throws ClientException if a status code other than 200 (OK) and 201 (Created) is returned.
[ "Creates", "a", "resource", "specified", "as", "a", "multi", "-", "part", "form", "in", "an", "input", "stream", ".", "Adds", "appropriate", "Accepts", "and", "Content", "Type", "headers", "." ]
train
https://github.com/eurekaclinical/eurekaclinical-common/blob/1867102ff43fe94e519f76a074d5f5923e9be61c/src/main/java/org/eurekaclinical/common/comm/clients/EurekaClinicalClient.java#L784-L786
eclipse/xtext-extras
org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/binary/asm/SignatureUtil.java
SignatureUtil.scanBaseTypeSignature
private static int scanBaseTypeSignature(String string, int start) { // need a minimum 1 char if (start >= string.length()) { throw new IllegalArgumentException(); } char c = string.charAt(start); if ("BCDFIJSVZ".indexOf(c) >= 0) { //$NON-NLS-1$ return start; } else { throw new IllegalArgumentException(); } }
java
private static int scanBaseTypeSignature(String string, int start) { // need a minimum 1 char if (start >= string.length()) { throw new IllegalArgumentException(); } char c = string.charAt(start); if ("BCDFIJSVZ".indexOf(c) >= 0) { //$NON-NLS-1$ return start; } else { throw new IllegalArgumentException(); } }
[ "private", "static", "int", "scanBaseTypeSignature", "(", "String", "string", ",", "int", "start", ")", "{", "// need a minimum 1 char", "if", "(", "start", ">=", "string", ".", "length", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", ")"...
Scans the given string for a base type signature starting at the given index and returns the index of the last character. <pre> BaseTypeSignature: <b>B</b> | <b>C</b> | <b>D</b> | <b>F</b> | <b>I</b> | <b>J</b> | <b>S</b> | <b>V</b> | <b>Z</b> </pre> Note that although the base type "V" is only allowed in method return types, there is no syntactic ambiguity. This method will accept them anywhere without complaint. @param string the signature string @param start the 0-based character index of the first character @return the 0-based character index of the last character @exception IllegalArgumentException if this is not a base type signature
[ "Scans", "the", "given", "string", "for", "a", "base", "type", "signature", "starting", "at", "the", "given", "index", "and", "returns", "the", "index", "of", "the", "last", "character", ".", "<pre", ">", "BaseTypeSignature", ":", "<b", ">", "B<", "/", "...
train
https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/binary/asm/SignatureUtil.java#L221-L232
spring-projects/spring-retry
src/main/java/org/springframework/retry/policy/ExceptionClassifierRetryPolicy.java
ExceptionClassifierRetryPolicy.setPolicyMap
public void setPolicyMap(Map<Class<? extends Throwable>, RetryPolicy> policyMap) { this.exceptionClassifier = new SubclassClassifier<Throwable, RetryPolicy>( policyMap, new NeverRetryPolicy()); }
java
public void setPolicyMap(Map<Class<? extends Throwable>, RetryPolicy> policyMap) { this.exceptionClassifier = new SubclassClassifier<Throwable, RetryPolicy>( policyMap, new NeverRetryPolicy()); }
[ "public", "void", "setPolicyMap", "(", "Map", "<", "Class", "<", "?", "extends", "Throwable", ">", ",", "RetryPolicy", ">", "policyMap", ")", "{", "this", ".", "exceptionClassifier", "=", "new", "SubclassClassifier", "<", "Throwable", ",", "RetryPolicy", ">", ...
Setter for policy map used to create a classifier. Either this property or the exception classifier directly should be set, but not both. @param policyMap a map of Throwable class to {@link RetryPolicy} that will be used to create a {@link Classifier} to locate a policy.
[ "Setter", "for", "policy", "map", "used", "to", "create", "a", "classifier", ".", "Either", "this", "property", "or", "the", "exception", "classifier", "directly", "should", "be", "set", "but", "not", "both", "." ]
train
https://github.com/spring-projects/spring-retry/blob/e2b0555f96594c2321990d0deeac45fc44d4f123/src/main/java/org/springframework/retry/policy/ExceptionClassifierRetryPolicy.java#L49-L52
apache/groovy
src/main/java/org/codehaus/groovy/control/ErrorCollector.java
ErrorCollector.addError
public void addError(Message message, boolean fatal) throws CompilationFailedException { if (fatal) { addFatalError(message); } else { addError(message); } }
java
public void addError(Message message, boolean fatal) throws CompilationFailedException { if (fatal) { addFatalError(message); } else { addError(message); } }
[ "public", "void", "addError", "(", "Message", "message", ",", "boolean", "fatal", ")", "throws", "CompilationFailedException", "{", "if", "(", "fatal", ")", "{", "addFatalError", "(", "message", ")", ";", "}", "else", "{", "addError", "(", "message", ")", ...
Adds an optionally-fatal error to the message set. The message is not required to have a source line and column specified, but it is best practice to try and include that information. @param fatal if true then then processing will stop
[ "Adds", "an", "optionally", "-", "fatal", "error", "to", "the", "message", "set", ".", "The", "message", "is", "not", "required", "to", "have", "a", "source", "line", "and", "column", "specified", "but", "it", "is", "best", "practice", "to", "try", "and"...
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/control/ErrorCollector.java#L119-L126
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.getAt
public static <T> List<T> getAt(List<T> self, EmptyRange range) { return createSimilarList(self, 0); }
java
public static <T> List<T> getAt(List<T> self, EmptyRange range) { return createSimilarList(self, 0); }
[ "public", "static", "<", "T", ">", "List", "<", "T", ">", "getAt", "(", "List", "<", "T", ">", "self", ",", "EmptyRange", "range", ")", "{", "return", "createSimilarList", "(", "self", ",", "0", ")", ";", "}" ]
Support the range subscript operator for a List. <pre class="groovyTestCase"> def list = [true, 1, 3.4] {@code assert list[0..<0] == []} </pre> @param self a List @param range a Range indicating the items to get @return a new list instance based on range borders @since 1.0
[ "Support", "the", "range", "subscript", "operator", "for", "a", "List", ".", "<pre", "class", "=", "groovyTestCase", ">", "def", "list", "=", "[", "true", "1", "3", ".", "4", "]", "{", "@code", "assert", "list", "[", "0", "..", "<0", "]", "==", "[]...
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L7654-L7656
RestComm/sip-servlets
sip-servlets-spec/src/main/java/javax/servlet/sip/SipServlet.java
SipServlet.service
public void service(javax.servlet.ServletRequest req, javax.servlet.ServletResponse resp) throws javax.servlet.ServletException, java.io.IOException{ if (req != null) { doRequest((SipServletRequest) req); } else { SipServletResponse response = (SipServletResponse)resp; if(response.isBranchResponse()) { doBranchResponse(response); } else { doResponse(response); } } }
java
public void service(javax.servlet.ServletRequest req, javax.servlet.ServletResponse resp) throws javax.servlet.ServletException, java.io.IOException{ if (req != null) { doRequest((SipServletRequest) req); } else { SipServletResponse response = (SipServletResponse)resp; if(response.isBranchResponse()) { doBranchResponse(response); } else { doResponse(response); } } }
[ "public", "void", "service", "(", "javax", ".", "servlet", ".", "ServletRequest", "req", ",", "javax", ".", "servlet", ".", "ServletResponse", "resp", ")", "throws", "javax", ".", "servlet", ".", "ServletException", ",", "java", ".", "io", ".", "IOException"...
Invoked to handle incoming SIP messages: requests or responses. Exactly one of the arguments is null: if the event is a request the response argument is null, and vice versa, if the event is a response the request argument is null. This method dispatched to doRequest() or doResponse() as appropriate. Servlets will not usually need to override this method.
[ "Invoked", "to", "handle", "incoming", "SIP", "messages", ":", "requests", "or", "responses", ".", "Exactly", "one", "of", "the", "arguments", "is", "null", ":", "if", "the", "event", "is", "a", "request", "the", "response", "argument", "is", "null", "and"...
train
https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-spec/src/main/java/javax/servlet/sip/SipServlet.java#L326-L337
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/interestrate/products/SwaptionWithComponents.java
SwaptionWithComponents.getValue
@Override public RandomVariable getValue(double evaluationTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException { RandomVariable values = option.getValue(evaluationTime, model); return values; }
java
@Override public RandomVariable getValue(double evaluationTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException { RandomVariable values = option.getValue(evaluationTime, model); return values; }
[ "@", "Override", "public", "RandomVariable", "getValue", "(", "double", "evaluationTime", ",", "LIBORModelMonteCarloSimulationModel", "model", ")", "throws", "CalculationException", "{", "RandomVariable", "values", "=", "option", ".", "getValue", "(", "evaluationTime", ...
This method returns the value random variable of the product within the specified model, evaluated at a given evalutationTime. Note: For a lattice this is often the value conditional to evalutationTime, for a Monte-Carlo simulation this is the (sum of) value discounted to evaluation time. Cashflows prior evaluationTime are not considered. @param evaluationTime The time on which this products value should be observed. @param model The model used to price the product. @return The random variable representing the value of the product discounted to evaluation time @throws CalculationException Thrown when valuation fails from valuation model.
[ "This", "method", "returns", "the", "value", "random", "variable", "of", "the", "product", "within", "the", "specified", "model", "evaluated", "at", "a", "given", "evalutationTime", ".", "Note", ":", "For", "a", "lattice", "this", "is", "often", "the", "valu...
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/products/SwaptionWithComponents.java#L93-L98
contentful/contentful-management.java
src/main/java/com/contentful/java/cma/AbsModule.java
AbsModule.defer
<R> CMACallback<R> defer(DefFunc<R> func, CMACallback<R> callback) { assertNotNull(callback, "callback"); Observable.defer(func) .subscribeOn(Schedulers.io()) .subscribe( new ActionSuccess<R>(callbackExecutor, callback), new ActionError(callbackExecutor, callback)); return callback; }
java
<R> CMACallback<R> defer(DefFunc<R> func, CMACallback<R> callback) { assertNotNull(callback, "callback"); Observable.defer(func) .subscribeOn(Schedulers.io()) .subscribe( new ActionSuccess<R>(callbackExecutor, callback), new ActionError(callbackExecutor, callback)); return callback; }
[ "<", "R", ">", "CMACallback", "<", "R", ">", "defer", "(", "DefFunc", "<", "R", ">", "func", ",", "CMACallback", "<", "R", ">", "callback", ")", "{", "assertNotNull", "(", "callback", ",", "\"callback\"", ")", ";", "Observable", ".", "defer", "(", "f...
Creates an Observable with the given {@code func} function and subscribes to it with a set of pre-defined actions. The provided {@code callback} will be passed to these actions in order to populate the events.
[ "Creates", "an", "Observable", "with", "the", "given", "{" ]
train
https://github.com/contentful/contentful-management.java/blob/ca310fb9ea9577fcff0ca57949ab7c2315fa2534/src/main/java/com/contentful/java/cma/AbsModule.java#L112-L120
dkpro/dkpro-jwpl
de.tudarmstadt.ukp.wikipedia.revisionmachine/src/main/java/de/tudarmstadt/ukp/wikipedia/revisionmachine/api/RevisionApi.java
RevisionApi.getUserContributionMap
public Map<String, Timestamp> getUserContributionMap(final int articleID, String[] groupfilter) throws WikiApiException { return getUserContributionMap(articleID, groupfilter, false); }
java
public Map<String, Timestamp> getUserContributionMap(final int articleID, String[] groupfilter) throws WikiApiException { return getUserContributionMap(articleID, groupfilter, false); }
[ "public", "Map", "<", "String", ",", "Timestamp", ">", "getUserContributionMap", "(", "final", "int", "articleID", ",", "String", "[", "]", "groupfilter", ")", "throws", "WikiApiException", "{", "return", "getUserContributionMap", "(", "articleID", ",", "groupfilt...
Returns a map of usernames mapped to the timestamps of their contributions. Users of certain user groups (e.g. bots) can be filtered by providing the unwanted groups in the {@code groupFilter}. Nothing is filtered if the {@code groupFilter} is {@code null} or empty.<br> <br> Filtered results also include unregistered users (because they cannot be filtered using user groups) In order to get results containing only registered users, use {@link #getUserContributionMap(int, String[], boolean)} and set {@code onlyRegistered=true}.<br> <br> In order to make this query fast, create a MySQL-Index (BTREE) on the ArticleID in the revisions-table. @param articleID ID of the article @param groupfilter a list of unwanted user groups @return map of Timestamp-DiffPart-Collection pairs @throws WikiApiException if an error occurs
[ "Returns", "a", "map", "of", "usernames", "mapped", "to", "the", "timestamps", "of", "their", "contributions", "." ]
train
https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.revisionmachine/src/main/java/de/tudarmstadt/ukp/wikipedia/revisionmachine/api/RevisionApi.java#L740-L744
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/AbstractMemberWriter.java
AbstractMemberWriter.getMemberTree
public Content getMemberTree(Content memberTree, boolean isLastContent) { if (isLastContent) return HtmlTree.UL(HtmlStyle.blockListLast, memberTree); else return HtmlTree.UL(HtmlStyle.blockList, memberTree); }
java
public Content getMemberTree(Content memberTree, boolean isLastContent) { if (isLastContent) return HtmlTree.UL(HtmlStyle.blockListLast, memberTree); else return HtmlTree.UL(HtmlStyle.blockList, memberTree); }
[ "public", "Content", "getMemberTree", "(", "Content", "memberTree", ",", "boolean", "isLastContent", ")", "{", "if", "(", "isLastContent", ")", "return", "HtmlTree", ".", "UL", "(", "HtmlStyle", ".", "blockListLast", ",", "memberTree", ")", ";", "else", "retur...
Get the member tree to be documented. @param memberTree the content tree of member to be documented @param isLastContent true if the content to be added is the last content @return a content tree that will be added to the class documentation
[ "Get", "the", "member", "tree", "to", "be", "documented", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/AbstractMemberWriter.java#L693-L698
jbake-org/jbake
jbake-core/src/main/java/org/jbake/app/configuration/JBakeConfigurationFactory.java
JBakeConfigurationFactory.createDefaultJbakeConfiguration
public DefaultJBakeConfiguration createDefaultJbakeConfiguration(File sourceFolder, File destination, CompositeConfiguration compositeConfiguration, boolean isClearCache) { DefaultJBakeConfiguration configuration = new DefaultJBakeConfiguration(sourceFolder, compositeConfiguration); configuration.setDestinationFolder(destination); configuration.setClearCache(isClearCache); return configuration; }
java
public DefaultJBakeConfiguration createDefaultJbakeConfiguration(File sourceFolder, File destination, CompositeConfiguration compositeConfiguration, boolean isClearCache) { DefaultJBakeConfiguration configuration = new DefaultJBakeConfiguration(sourceFolder, compositeConfiguration); configuration.setDestinationFolder(destination); configuration.setClearCache(isClearCache); return configuration; }
[ "public", "DefaultJBakeConfiguration", "createDefaultJbakeConfiguration", "(", "File", "sourceFolder", ",", "File", "destination", ",", "CompositeConfiguration", "compositeConfiguration", ",", "boolean", "isClearCache", ")", "{", "DefaultJBakeConfiguration", "configuration", "=...
Creates a {@link DefaultJBakeConfiguration} This is a compatibility factory method @param sourceFolder The source folder of the project @param destination The destination folder to render and copy files to @param compositeConfiguration A given {@link CompositeConfiguration} @param isClearCache Whether to clear database cache or not @return A configuration by given parameters
[ "Creates", "a", "{", "@link", "DefaultJBakeConfiguration", "}" ]
train
https://github.com/jbake-org/jbake/blob/beb9042a54bf0eb168821d524c88b9ea0bee88dc/jbake-core/src/main/java/org/jbake/app/configuration/JBakeConfigurationFactory.java#L47-L52
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_operation_GET
public ArrayList<OvhOperation> project_serviceName_operation_GET(String serviceName) throws IOException { String qPath = "/cloud/project/{serviceName}/operation"; StringBuilder sb = path(qPath, serviceName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t8); }
java
public ArrayList<OvhOperation> project_serviceName_operation_GET(String serviceName) throws IOException { String qPath = "/cloud/project/{serviceName}/operation"; StringBuilder sb = path(qPath, serviceName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t8); }
[ "public", "ArrayList", "<", "OvhOperation", ">", "project_serviceName_operation_GET", "(", "String", "serviceName", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{serviceName}/operation\"", ";", "StringBuilder", "sb", "=", "path", "(", "qP...
List your operations REST: GET /cloud/project/{serviceName}/operation @param serviceName [required] Public Cloud project API beta
[ "List", "your", "operations" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L892-L897
maven-nar/nar-maven-plugin
src/main/java/com/github/maven_nar/cpptasks/apple/PropertyListSerialization.java
PropertyListSerialization.serializeObject
private static void serializeObject(final Object obj, final ContentHandler handler) throws SAXException { if (obj instanceof Map) { serializeMap((Map) obj, handler); } else if (obj instanceof List) { serializeList((List) obj, handler); } else if (obj instanceof Number) { if (obj instanceof Double || obj instanceof Float) { serializeReal((Number) obj, handler); } else { serializeInteger((Number) obj, handler); } } else if (obj instanceof Boolean) { serializeBoolean((Boolean) obj, handler); } else { serializeString(String.valueOf(obj), handler); } }
java
private static void serializeObject(final Object obj, final ContentHandler handler) throws SAXException { if (obj instanceof Map) { serializeMap((Map) obj, handler); } else if (obj instanceof List) { serializeList((List) obj, handler); } else if (obj instanceof Number) { if (obj instanceof Double || obj instanceof Float) { serializeReal((Number) obj, handler); } else { serializeInteger((Number) obj, handler); } } else if (obj instanceof Boolean) { serializeBoolean((Boolean) obj, handler); } else { serializeString(String.valueOf(obj), handler); } }
[ "private", "static", "void", "serializeObject", "(", "final", "Object", "obj", ",", "final", "ContentHandler", "handler", ")", "throws", "SAXException", "{", "if", "(", "obj", "instanceof", "Map", ")", "{", "serializeMap", "(", "(", "Map", ")", "obj", ",", ...
Serialize an object using the best available element. @param obj object to serialize. @param handler destination of serialization events. @throws SAXException if exception during serialization.
[ "Serialize", "an", "object", "using", "the", "best", "available", "element", "." ]
train
https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/apple/PropertyListSerialization.java#L196-L212
Kickflip/kickflip-android-sdk
sdk/src/main/java/io/kickflip/sdk/location/DeviceLocation.java
DeviceLocation.getLastKnownLocation
public static void getLastKnownLocation(Context context, boolean waitForGpsFix, final LocationResult cb) { DeviceLocation deviceLocation = new DeviceLocation(); LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); Location last_loc; last_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (last_loc == null) last_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (last_loc != null && cb != null) { cb.gotLocation(last_loc); } else { deviceLocation.getLocation(context, cb, waitForGpsFix); } }
java
public static void getLastKnownLocation(Context context, boolean waitForGpsFix, final LocationResult cb) { DeviceLocation deviceLocation = new DeviceLocation(); LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); Location last_loc; last_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (last_loc == null) last_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (last_loc != null && cb != null) { cb.gotLocation(last_loc); } else { deviceLocation.getLocation(context, cb, waitForGpsFix); } }
[ "public", "static", "void", "getLastKnownLocation", "(", "Context", "context", ",", "boolean", "waitForGpsFix", ",", "final", "LocationResult", "cb", ")", "{", "DeviceLocation", "deviceLocation", "=", "new", "DeviceLocation", "(", ")", ";", "LocationManager", "lm", ...
Get the last known location. If one is not available, fetch a fresh location @param context @param waitForGpsFix @param cb
[ "Get", "the", "last", "known", "location", ".", "If", "one", "is", "not", "available", "fetch", "a", "fresh", "location" ]
train
https://github.com/Kickflip/kickflip-android-sdk/blob/af3aae5f1128d7376e67aefe11a3a1a3844be734/sdk/src/main/java/io/kickflip/sdk/location/DeviceLocation.java#L41-L55
Netflix/Hystrix
hystrix-core/src/main/java/com/netflix/hystrix/AbstractCommand.java
AbstractCommand.initThreadPoolKey
private static HystrixThreadPoolKey initThreadPoolKey(HystrixThreadPoolKey threadPoolKey, HystrixCommandGroupKey groupKey, String threadPoolKeyOverride) { if (threadPoolKeyOverride == null) { // we don't have a property overriding the value so use either HystrixThreadPoolKey or HystrixCommandGroup if (threadPoolKey == null) { /* use HystrixCommandGroup if HystrixThreadPoolKey is null */ return HystrixThreadPoolKey.Factory.asKey(groupKey.name()); } else { return threadPoolKey; } } else { // we have a property defining the thread-pool so use it instead return HystrixThreadPoolKey.Factory.asKey(threadPoolKeyOverride); } }
java
private static HystrixThreadPoolKey initThreadPoolKey(HystrixThreadPoolKey threadPoolKey, HystrixCommandGroupKey groupKey, String threadPoolKeyOverride) { if (threadPoolKeyOverride == null) { // we don't have a property overriding the value so use either HystrixThreadPoolKey or HystrixCommandGroup if (threadPoolKey == null) { /* use HystrixCommandGroup if HystrixThreadPoolKey is null */ return HystrixThreadPoolKey.Factory.asKey(groupKey.name()); } else { return threadPoolKey; } } else { // we have a property defining the thread-pool so use it instead return HystrixThreadPoolKey.Factory.asKey(threadPoolKeyOverride); } }
[ "private", "static", "HystrixThreadPoolKey", "initThreadPoolKey", "(", "HystrixThreadPoolKey", "threadPoolKey", ",", "HystrixCommandGroupKey", "groupKey", ",", "String", "threadPoolKeyOverride", ")", "{", "if", "(", "threadPoolKeyOverride", "==", "null", ")", "{", "// we ...
/* ThreadPoolKey This defines which thread-pool this command should run on. It uses the HystrixThreadPoolKey if provided, then defaults to use HystrixCommandGroup. It can then be overridden by a property if defined so it can be changed at runtime.
[ "/", "*", "ThreadPoolKey" ]
train
https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-core/src/main/java/com/netflix/hystrix/AbstractCommand.java#L221-L234
davidmoten/rxjava-jdbc
src/main/java/com/github/davidmoten/rx/jdbc/Database.java
Database.from
public static Database from(String url, String username, String password) { return new Database(url, username, password); }
java
public static Database from(String url, String username, String password) { return new Database(url, username, password); }
[ "public", "static", "Database", "from", "(", "String", "url", ",", "String", "username", ",", "String", "password", ")", "{", "return", "new", "Database", "(", "url", ",", "username", ",", "password", ")", ";", "}" ]
Returns a {@link Database} based on a jdbc connection string. @param url jdbc url @param username username for connection @param password password for connection @return the database object
[ "Returns", "a", "{", "@link", "Database", "}", "based", "on", "a", "jdbc", "connection", "string", "." ]
train
https://github.com/davidmoten/rxjava-jdbc/blob/81e157d7071a825086bde81107b8694684cdff14/src/main/java/com/github/davidmoten/rx/jdbc/Database.java#L225-L227
elki-project/elki
elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/lof/LoOP.java
LoOP.run
public OutlierResult run(Database database, Relation<O> relation) { StepProgress stepprog = LOG.isVerbose() ? new StepProgress(5) : null; Pair<KNNQuery<O>, KNNQuery<O>> pair = getKNNQueries(database, relation, stepprog); KNNQuery<O> knnComp = pair.getFirst(); KNNQuery<O> knnReach = pair.getSecond(); // Assert we got something if(knnComp == null) { throw new AbortException("No kNN queries supported by database for comparison distance function."); } if(knnReach == null) { throw new AbortException("No kNN queries supported by database for density estimation distance function."); } // FIXME: tie handling! // Probabilistic distances WritableDoubleDataStore pdists = DataStoreUtil.makeDoubleStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_DB); LOG.beginStep(stepprog, 3, "Computing pdists"); computePDists(relation, knnReach, pdists); // Compute PLOF values. WritableDoubleDataStore plofs = DataStoreUtil.makeDoubleStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP); LOG.beginStep(stepprog, 4, "Computing PLOF"); double nplof = computePLOFs(relation, knnComp, pdists, plofs); // Normalize the outlier scores. DoubleMinMax mm = new DoubleMinMax(); {// compute LOOP_SCORE of each db object LOG.beginStep(stepprog, 5, "Computing LoOP scores"); FiniteProgress progressLOOPs = LOG.isVerbose() ? new FiniteProgress("LoOP for objects", relation.size(), LOG) : null; final double norm = 1. / (nplof * MathUtil.SQRT2); for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) { double loop = NormalDistribution.erf((plofs.doubleValue(iditer) - 1.) * norm); plofs.putDouble(iditer, loop); mm.put(loop); LOG.incrementProcessed(progressLOOPs); } LOG.ensureCompleted(progressLOOPs); } LOG.setCompleted(stepprog); // Build result representation. DoubleRelation scoreResult = new MaterializedDoubleRelation("Local Outlier Probabilities", "loop-outlier", plofs, relation.getDBIDs()); OutlierScoreMeta scoreMeta = new ProbabilisticOutlierScore(mm.getMin(), mm.getMax(), 0.); return new OutlierResult(scoreMeta, scoreResult); }
java
public OutlierResult run(Database database, Relation<O> relation) { StepProgress stepprog = LOG.isVerbose() ? new StepProgress(5) : null; Pair<KNNQuery<O>, KNNQuery<O>> pair = getKNNQueries(database, relation, stepprog); KNNQuery<O> knnComp = pair.getFirst(); KNNQuery<O> knnReach = pair.getSecond(); // Assert we got something if(knnComp == null) { throw new AbortException("No kNN queries supported by database for comparison distance function."); } if(knnReach == null) { throw new AbortException("No kNN queries supported by database for density estimation distance function."); } // FIXME: tie handling! // Probabilistic distances WritableDoubleDataStore pdists = DataStoreUtil.makeDoubleStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_DB); LOG.beginStep(stepprog, 3, "Computing pdists"); computePDists(relation, knnReach, pdists); // Compute PLOF values. WritableDoubleDataStore plofs = DataStoreUtil.makeDoubleStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP); LOG.beginStep(stepprog, 4, "Computing PLOF"); double nplof = computePLOFs(relation, knnComp, pdists, plofs); // Normalize the outlier scores. DoubleMinMax mm = new DoubleMinMax(); {// compute LOOP_SCORE of each db object LOG.beginStep(stepprog, 5, "Computing LoOP scores"); FiniteProgress progressLOOPs = LOG.isVerbose() ? new FiniteProgress("LoOP for objects", relation.size(), LOG) : null; final double norm = 1. / (nplof * MathUtil.SQRT2); for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) { double loop = NormalDistribution.erf((plofs.doubleValue(iditer) - 1.) * norm); plofs.putDouble(iditer, loop); mm.put(loop); LOG.incrementProcessed(progressLOOPs); } LOG.ensureCompleted(progressLOOPs); } LOG.setCompleted(stepprog); // Build result representation. DoubleRelation scoreResult = new MaterializedDoubleRelation("Local Outlier Probabilities", "loop-outlier", plofs, relation.getDBIDs()); OutlierScoreMeta scoreMeta = new ProbabilisticOutlierScore(mm.getMin(), mm.getMax(), 0.); return new OutlierResult(scoreMeta, scoreResult); }
[ "public", "OutlierResult", "run", "(", "Database", "database", ",", "Relation", "<", "O", ">", "relation", ")", "{", "StepProgress", "stepprog", "=", "LOG", ".", "isVerbose", "(", ")", "?", "new", "StepProgress", "(", "5", ")", ":", "null", ";", "Pair", ...
Performs the LoOP algorithm on the given database. @param database Database to process @param relation Relation to process @return Outlier result
[ "Performs", "the", "LoOP", "algorithm", "on", "the", "given", "database", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/lof/LoOP.java#L184-L232
CloudSlang/cs-actions
cs-amazon/src/main/java/io/cloudslang/content/amazon/services/helpers/AwsSignatureV4.java
AwsSignatureV4.calculateHmacSHA256
private byte[] calculateHmacSHA256(String data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { Mac mac = Mac.getInstance(HMAC_ALGORITHM); mac.init(new SecretKeySpec(key, HMAC_ALGORITHM)); return mac.doFinal(data.getBytes(ENCODING)); }
java
private byte[] calculateHmacSHA256(String data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { Mac mac = Mac.getInstance(HMAC_ALGORITHM); mac.init(new SecretKeySpec(key, HMAC_ALGORITHM)); return mac.doFinal(data.getBytes(ENCODING)); }
[ "private", "byte", "[", "]", "calculateHmacSHA256", "(", "String", "data", ",", "byte", "[", "]", "key", ")", "throws", "NoSuchAlgorithmException", ",", "InvalidKeyException", ",", "UnsupportedEncodingException", "{", "Mac", "mac", "=", "Mac", ".", "getInstance", ...
Calculates the keyed-hash message authentication code for the data string. @param data String for which the HMAC will be calculated. @param key Key used for HMAC calculation. @return HMAC's bytes. This result is not encoded.
[ "Calculates", "the", "keyed", "-", "hash", "message", "authentication", "code", "for", "the", "data", "string", "." ]
train
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-amazon/src/main/java/io/cloudslang/content/amazon/services/helpers/AwsSignatureV4.java#L147-L152
soklet/soklet
src/main/java/com/soklet/util/PathUtils.java
PathUtils.copyDirectory
public static void copyDirectory(Path sourceDirectory, Path targetDirectory) throws IOException { copyDirectory(sourceDirectory, targetDirectory, emptySet()); }
java
public static void copyDirectory(Path sourceDirectory, Path targetDirectory) throws IOException { copyDirectory(sourceDirectory, targetDirectory, emptySet()); }
[ "public", "static", "void", "copyDirectory", "(", "Path", "sourceDirectory", ",", "Path", "targetDirectory", ")", "throws", "IOException", "{", "copyDirectory", "(", "sourceDirectory", ",", "targetDirectory", ",", "emptySet", "(", ")", ")", ";", "}" ]
Copies a directory. <p> NOTE: This method is not thread-safe. <p> Most of the implementation is thanks to http://stackoverflow.com/questions/17641706/how-to-copy-a-directory-with-its-attributes-permissions-from-one -location-to-ano/18691793#18691793 @param sourceDirectory the directory to copy from @param targetDirectory the directory to copy into @throws IOException if an I/O error occurs
[ "Copies", "a", "directory", ".", "<p", ">", "NOTE", ":", "This", "method", "is", "not", "thread", "-", "safe", ".", "<p", ">", "Most", "of", "the", "implementation", "is", "thanks", "to", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions"...
train
https://github.com/soklet/soklet/blob/4f12de07d9c132e0126d50ad11cc1d8576594700/src/main/java/com/soklet/util/PathUtils.java#L123-L125
app55/app55-java
src/support/java/com/googlecode/openbeans/Introspector.java
Introspector.getBeanInfo
public static BeanInfo getBeanInfo(Class<?> beanClass, int flags) throws IntrospectionException { if (flags == USE_ALL_BEANINFO) { // try to use cache return getBeanInfo(beanClass); } return getBeanInfoImplAndInit(beanClass, null, flags); }
java
public static BeanInfo getBeanInfo(Class<?> beanClass, int flags) throws IntrospectionException { if (flags == USE_ALL_BEANINFO) { // try to use cache return getBeanInfo(beanClass); } return getBeanInfoImplAndInit(beanClass, null, flags); }
[ "public", "static", "BeanInfo", "getBeanInfo", "(", "Class", "<", "?", ">", "beanClass", ",", "int", "flags", ")", "throws", "IntrospectionException", "{", "if", "(", "flags", "==", "USE_ALL_BEANINFO", ")", "{", "// try to use cache", "return", "getBeanInfo", "(...
Gets the <code>BeanInfo</code> object which contains the information of the properties, events and methods of the specified bean class. <ol> <li>If <code>flag==IGNORE_ALL_BEANINFO</code>, the <code>Introspector</code> will ignore all <code>BeanInfo</code> class.</li> <li>If <code>flag==IGNORE_IMMEDIATE_BEANINFO</code>, the <code>Introspector</code> will ignore the <code>BeanInfo</code> class of the current bean class. </li> <li>If <code>flag==USE_ALL_BEANINFO</code>, the <code>Introspector</code> will use all <code>BeanInfo</code> class which have been found.</li> </ol> <p> The <code>Introspector</code> will cache the <code>BeanInfo</code> object. Subsequent calls to this method will be answered with the cached data. </p> @param beanClass the specified bean class. @param flags the flag to control the usage of the explicit <code>BeanInfo</code> class. @return the <code>BeanInfo</code> of the bean class. @throws IntrospectionException
[ "Gets", "the", "<code", ">", "BeanInfo<", "/", "code", ">", "object", "which", "contains", "the", "information", "of", "the", "properties", "events", "and", "methods", "of", "the", "specified", "bean", "class", ".", "<ol", ">", "<li", ">", "If", "<code", ...
train
https://github.com/app55/app55-java/blob/73e51d0f3141a859dfbd37ca9becef98477e553e/src/support/java/com/googlecode/openbeans/Introspector.java#L205-L213
derari/cthul
strings/src/main/java/org/cthul/strings/format/FormatImplBase.java
FormatImplBase.containsFlag
protected boolean containsFlag(final char flag, final String flags) { if (flags == null) return false; return flags.indexOf(flag) >= 0; }
java
protected boolean containsFlag(final char flag, final String flags) { if (flags == null) return false; return flags.indexOf(flag) >= 0; }
[ "protected", "boolean", "containsFlag", "(", "final", "char", "flag", ",", "final", "String", "flags", ")", "{", "if", "(", "flags", "==", "null", ")", "return", "false", ";", "return", "flags", ".", "indexOf", "(", "flag", ")", ">=", "0", ";", "}" ]
Returns whether {@code flags} contains {@code flag}. @param flag @param flags @return whether {@code flags} contains {@code flag}.
[ "Returns", "whether", "{" ]
train
https://github.com/derari/cthul/blob/74a31e3cb6a94f5f25cc5253d1dbd42e19a17ebc/strings/src/main/java/org/cthul/strings/format/FormatImplBase.java#L194-L197
netty/netty
codec/src/main/java/io/netty/handler/codec/DateFormatter.java
DateFormatter.parseHttpDate
public static Date parseHttpDate(CharSequence txt, int start, int end) { int length = end - start; if (length == 0) { return null; } else if (length < 0) { throw new IllegalArgumentException("Can't have end < start"); } else if (length > 64) { throw new IllegalArgumentException("Can't parse more than 64 chars," + "looks like a user error or a malformed header"); } return formatter().parse0(checkNotNull(txt, "txt"), start, end); }
java
public static Date parseHttpDate(CharSequence txt, int start, int end) { int length = end - start; if (length == 0) { return null; } else if (length < 0) { throw new IllegalArgumentException("Can't have end < start"); } else if (length > 64) { throw new IllegalArgumentException("Can't parse more than 64 chars," + "looks like a user error or a malformed header"); } return formatter().parse0(checkNotNull(txt, "txt"), start, end); }
[ "public", "static", "Date", "parseHttpDate", "(", "CharSequence", "txt", ",", "int", "start", ",", "int", "end", ")", "{", "int", "length", "=", "end", "-", "start", ";", "if", "(", "length", "==", "0", ")", "{", "return", "null", ";", "}", "else", ...
Parse some text into a {@link Date}, according to RFC6265 @param txt text to parse @param start the start index inside {@code txt} @param end the end index inside {@code txt} @return a {@link Date}, or null if text couldn't be parsed
[ "Parse", "some", "text", "into", "a", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec/src/main/java/io/netty/handler/codec/DateFormatter.java#L95-L106
alkacon/opencms-core
src/org/opencms/workplace/CmsWorkplaceMessages.java
CmsWorkplaceMessages.getResourceTypeName
public static String getResourceTypeName(CmsWorkplace wp, String name) { // try to find the localized key CmsExplorerTypeSettings typeSettings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(name); if (typeSettings == null) { return name; } String key = typeSettings.getKey(); return wp.keyDefault(key, name); }
java
public static String getResourceTypeName(CmsWorkplace wp, String name) { // try to find the localized key CmsExplorerTypeSettings typeSettings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(name); if (typeSettings == null) { return name; } String key = typeSettings.getKey(); return wp.keyDefault(key, name); }
[ "public", "static", "String", "getResourceTypeName", "(", "CmsWorkplace", "wp", ",", "String", "name", ")", "{", "// try to find the localized key", "CmsExplorerTypeSettings", "typeSettings", "=", "OpenCms", ".", "getWorkplaceManager", "(", ")", ".", "getExplorerTypeSetti...
Returns the localized name of the given resource type name.<p> If this key is not found, the value of the name input will be returned.<p> @param wp an instance of a {@link CmsWorkplace} to resolve the key name with @param name the resource type name to generate the nice name for @return the localized name of the given resource type name
[ "Returns", "the", "localized", "name", "of", "the", "given", "resource", "type", "name", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsWorkplaceMessages.java#L172-L181
Tristan971/EasyFXML
easyfxml/src/main/java/moe/tristan/easyfxml/model/exception/ExceptionHandler.java
ExceptionHandler.asPane
public Pane asPane(final String userReadableError) { LOG.debug("Generating node corresponding to ExceptionPane..."); final Label messageLabel = new Label(userReadableError); final TextArea throwableDataLabel = new TextArea(formatErrorMessage(this.exception)); AnchorPane.setLeftAnchor(messageLabel, ERROR_FIELD_MARGIN_SIZE); Nodes.centerNode(throwableDataLabel, ERROR_FIELD_MARGIN_SIZE); return new AnchorPane(messageLabel, throwableDataLabel); }
java
public Pane asPane(final String userReadableError) { LOG.debug("Generating node corresponding to ExceptionPane..."); final Label messageLabel = new Label(userReadableError); final TextArea throwableDataLabel = new TextArea(formatErrorMessage(this.exception)); AnchorPane.setLeftAnchor(messageLabel, ERROR_FIELD_MARGIN_SIZE); Nodes.centerNode(throwableDataLabel, ERROR_FIELD_MARGIN_SIZE); return new AnchorPane(messageLabel, throwableDataLabel); }
[ "public", "Pane", "asPane", "(", "final", "String", "userReadableError", ")", "{", "LOG", ".", "debug", "(", "\"Generating node corresponding to ExceptionPane...\"", ")", ";", "final", "Label", "messageLabel", "=", "new", "Label", "(", "userReadableError", ")", ";",...
Same as {@link #asPane()} but with a custom error label on top of the stack trace. @param userReadableError The custom error message. @return The exception in a pane with the custom error message as a label over the stacktrace.
[ "Same", "as", "{", "@link", "#asPane", "()", "}", "but", "with", "a", "custom", "error", "label", "on", "top", "of", "the", "stack", "trace", "." ]
train
https://github.com/Tristan971/EasyFXML/blob/f82cad1d54e62903ca5e4a250279ad315b028aef/easyfxml/src/main/java/moe/tristan/easyfxml/model/exception/ExceptionHandler.java#L53-L61
elki-project/elki
elki-core-dbids/src/main/java/de/lmu/ifi/dbs/elki/database/ids/DBIDUtil.java
DBIDUtil.randomSplit
public static ArrayDBIDs[] randomSplit(DBIDs ids, int p, RandomFactory rnd) { return randomSplit(ids, p, rnd.getSingleThreadedRandom()); }
java
public static ArrayDBIDs[] randomSplit(DBIDs ids, int p, RandomFactory rnd) { return randomSplit(ids, p, rnd.getSingleThreadedRandom()); }
[ "public", "static", "ArrayDBIDs", "[", "]", "randomSplit", "(", "DBIDs", "ids", ",", "int", "p", ",", "RandomFactory", "rnd", ")", "{", "return", "randomSplit", "(", "ids", ",", "p", ",", "rnd", ".", "getSingleThreadedRandom", "(", ")", ")", ";", "}" ]
Randomly split IDs into {@code p} partitions of almost-equal size. @param ids Original DBIDs @param p Desired number of partitions. @param rnd Random generator
[ "Randomly", "split", "IDs", "into", "{", "@code", "p", "}", "partitions", "of", "almost", "-", "equal", "size", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-dbids/src/main/java/de/lmu/ifi/dbs/elki/database/ids/DBIDUtil.java#L736-L738
couchbase/couchbase-jvm-core
src/main/java/com/couchbase/client/core/config/refresher/HttpRefresher.java
HttpRefresher.repeatConfigUntilUnsubscribed
private void repeatConfigUntilUnsubscribed(final String name, Observable<BucketStreamingResponse> response) { response.flatMap(new Func1<BucketStreamingResponse, Observable<ProposedBucketConfigContext>>() { @Override public Observable<ProposedBucketConfigContext> call(final BucketStreamingResponse response) { LOGGER.debug("Config stream started for {} on {}.", name, response.host()); return response .configs() .map(new Func1<String, ProposedBucketConfigContext>() { @Override public ProposedBucketConfigContext call(String s) { String raw = s.replace("$HOST", response.host()); return new ProposedBucketConfigContext(name, raw, NetworkAddress.create(response.host())); } }) .doOnCompleted(new Action0() { @Override public void call() { LOGGER.debug("Config stream ended for {} on {}.", name, response.host()); } }); } }) .repeatWhen(new Func1<Observable<? extends Void>, Observable<?>>() { @Override public Observable<?> call(Observable<? extends Void> observable) { return observable.flatMap(new Func1<Void, Observable<?>>() { @Override public Observable<?> call(Void aVoid) { if (HttpRefresher.this.registrations().containsKey(name)) { LOGGER.debug("Resubscribing config stream for bucket {}, still registered.", name); return Observable.just(true); } else { LOGGER.debug("Not resubscribing config stream for bucket {}, not registered.", name); return Observable.empty(); } } }); } }).subscribe(new Subscriber<ProposedBucketConfigContext>() { @Override public void onCompleted() { // ignored on purpose } @Override public void onError(Throwable e) { LOGGER.error("Error while subscribing to Http refresh stream!", e); } @Override public void onNext(ProposedBucketConfigContext ctx) { pushConfig(ctx); } }); }
java
private void repeatConfigUntilUnsubscribed(final String name, Observable<BucketStreamingResponse> response) { response.flatMap(new Func1<BucketStreamingResponse, Observable<ProposedBucketConfigContext>>() { @Override public Observable<ProposedBucketConfigContext> call(final BucketStreamingResponse response) { LOGGER.debug("Config stream started for {} on {}.", name, response.host()); return response .configs() .map(new Func1<String, ProposedBucketConfigContext>() { @Override public ProposedBucketConfigContext call(String s) { String raw = s.replace("$HOST", response.host()); return new ProposedBucketConfigContext(name, raw, NetworkAddress.create(response.host())); } }) .doOnCompleted(new Action0() { @Override public void call() { LOGGER.debug("Config stream ended for {} on {}.", name, response.host()); } }); } }) .repeatWhen(new Func1<Observable<? extends Void>, Observable<?>>() { @Override public Observable<?> call(Observable<? extends Void> observable) { return observable.flatMap(new Func1<Void, Observable<?>>() { @Override public Observable<?> call(Void aVoid) { if (HttpRefresher.this.registrations().containsKey(name)) { LOGGER.debug("Resubscribing config stream for bucket {}, still registered.", name); return Observable.just(true); } else { LOGGER.debug("Not resubscribing config stream for bucket {}, not registered.", name); return Observable.empty(); } } }); } }).subscribe(new Subscriber<ProposedBucketConfigContext>() { @Override public void onCompleted() { // ignored on purpose } @Override public void onError(Throwable e) { LOGGER.error("Error while subscribing to Http refresh stream!", e); } @Override public void onNext(ProposedBucketConfigContext ctx) { pushConfig(ctx); } }); }
[ "private", "void", "repeatConfigUntilUnsubscribed", "(", "final", "String", "name", ",", "Observable", "<", "BucketStreamingResponse", ">", "response", ")", "{", "response", ".", "flatMap", "(", "new", "Func1", "<", "BucketStreamingResponse", ",", "Observable", "<",...
Helper method to push configs until unsubscribed, even when a stream closes. @param name the name of the bucket. @param response the response source observable to resubscribe if needed.
[ "Helper", "method", "to", "push", "configs", "until", "unsubscribed", "even", "when", "a", "stream", "closes", "." ]
train
https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/config/refresher/HttpRefresher.java#L151-L206
JOML-CI/JOML
src/org/joml/Matrix4d.java
Matrix4d.orthoSymmetric
public Matrix4d orthoSymmetric(double width, double height, double zNear, double zFar, boolean zZeroToOne) { return orthoSymmetric(width, height, zNear, zFar, zZeroToOne, this); }
java
public Matrix4d orthoSymmetric(double width, double height, double zNear, double zFar, boolean zZeroToOne) { return orthoSymmetric(width, height, zNear, zFar, zZeroToOne, this); }
[ "public", "Matrix4d", "orthoSymmetric", "(", "double", "width", ",", "double", "height", ",", "double", "zNear", ",", "double", "zFar", ",", "boolean", "zZeroToOne", ")", "{", "return", "orthoSymmetric", "(", "width", ",", "height", ",", "zNear", ",", "zFar"...
Apply a symmetric orthographic projection transformation for a right-handed coordinate system using the given NDC z range to this matrix. <p> This method is equivalent to calling {@link #ortho(double, double, double, double, double, double, boolean) ortho()} with <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, then the new matrix will be <code>M * O</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the orthographic projection transformation will be applied first! <p> In order to set the matrix to a symmetric orthographic projection without post-multiplying it, use {@link #setOrthoSymmetric(double, double, double, double, boolean) setOrthoSymmetric()}. <p> Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> @see #setOrthoSymmetric(double, double, double, double, boolean) @param width the distance between the right and left frustum edges @param height the distance between the top and bottom frustum edges @param zNear near clipping plane distance @param zFar far clipping plane distance @param zZeroToOne whether to use Vulkan's and Direct3D's NDC z range of <code>[0..+1]</code> when <code>true</code> or whether to use OpenGL's NDC z range of <code>[-1..+1]</code> when <code>false</code> @return this
[ "Apply", "a", "symmetric", "orthographic", "projection", "transformation", "for", "a", "right", "-", "handed", "coordinate", "system", "using", "the", "given", "NDC", "z", "range", "to", "this", "matrix", ".", "<p", ">", "This", "method", "is", "equivalent", ...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L10190-L10192
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/core/urls/URLRewriterService.java
URLRewriterService.getAjaxUrl
public static AjaxUrlInfo getAjaxUrl(ServletContext servletContext, ServletRequest request, Object nameable) { ArrayList/*< URLRewriter >*/ rewriters = getRewriters( request ); if ( rewriters != null ) { for ( Iterator i = rewriters.iterator(); i.hasNext(); ) { URLRewriter rewriter = ( URLRewriter ) i.next(); AjaxUrlInfo info = rewriter.getAjaxUrl(servletContext,request,nameable); if (info != null) return info; } } return null; }
java
public static AjaxUrlInfo getAjaxUrl(ServletContext servletContext, ServletRequest request, Object nameable) { ArrayList/*< URLRewriter >*/ rewriters = getRewriters( request ); if ( rewriters != null ) { for ( Iterator i = rewriters.iterator(); i.hasNext(); ) { URLRewriter rewriter = ( URLRewriter ) i.next(); AjaxUrlInfo info = rewriter.getAjaxUrl(servletContext,request,nameable); if (info != null) return info; } } return null; }
[ "public", "static", "AjaxUrlInfo", "getAjaxUrl", "(", "ServletContext", "servletContext", ",", "ServletRequest", "request", ",", "Object", "nameable", ")", "{", "ArrayList", "/*< URLRewriter >*/", "rewriters", "=", "getRewriters", "(", "request", ")", ";", "if", "("...
This method will return two bits of information that are used by components that want run through the AJAX facilities. The <code>AjaxUrlInfo</code> class is returned and specifies this information. Unlike the other URLRewriter method, this is a true Chain of Responsibility (CoR) implementation. The first URLRewriter to return the AjaxUrlInfo object wins and that is returned from this call. The reason for this is that the implementation of the Ajax Context is also a true CoR implementation. These must match. @param servletContext the current ServletContext. @param request the current ServletRequest. @param nameable this object that is the target of the Ajax request. Typically it is an INameable.
[ "This", "method", "will", "return", "two", "bits", "of", "information", "that", "are", "used", "by", "components", "that", "want", "run", "through", "the", "AJAX", "facilities", ".", "The", "<code", ">", "AjaxUrlInfo<", "/", "code", ">", "class", "is", "re...
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/core/urls/URLRewriterService.java#L98-L113
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/ArchiveService.java
ArchiveService.getAssemblyFiles
public AssemblyFiles getAssemblyFiles(ImageConfiguration imageConfig, MojoParameters mojoParameters) throws MojoExecutionException { String name = imageConfig.getName(); try { return dockerAssemblyManager.getAssemblyFiles(name, imageConfig.getBuildConfiguration(), mojoParameters, log); } catch (InvalidAssemblerConfigurationException | ArchiveCreationException | AssemblyFormattingException e) { throw new MojoExecutionException("Cannot extract assembly files for image " + name + ": " + e, e); } }
java
public AssemblyFiles getAssemblyFiles(ImageConfiguration imageConfig, MojoParameters mojoParameters) throws MojoExecutionException { String name = imageConfig.getName(); try { return dockerAssemblyManager.getAssemblyFiles(name, imageConfig.getBuildConfiguration(), mojoParameters, log); } catch (InvalidAssemblerConfigurationException | ArchiveCreationException | AssemblyFormattingException e) { throw new MojoExecutionException("Cannot extract assembly files for image " + name + ": " + e, e); } }
[ "public", "AssemblyFiles", "getAssemblyFiles", "(", "ImageConfiguration", "imageConfig", ",", "MojoParameters", "mojoParameters", ")", "throws", "MojoExecutionException", "{", "String", "name", "=", "imageConfig", ".", "getName", "(", ")", ";", "try", "{", "return", ...
Get a mapping of original to destination files which a covered by an assembly. This can be used to watch the source files for changes in order to update the target (either by recreating a docker image or by copying it into a running container) @param imageConfig image config for which to get files. The build- and assembly configuration in this image config must not be null. @param mojoParameters needed for tracking the assembly @return mapping of assembly files @throws MojoExecutionException
[ "Get", "a", "mapping", "of", "original", "to", "destination", "files", "which", "a", "covered", "by", "an", "assembly", ".", "This", "can", "be", "used", "to", "watch", "the", "source", "files", "for", "changes", "in", "order", "to", "update", "the", "ta...
train
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/ArchiveService.java#L91-L100
blinkfox/zealot
src/main/java/com/blinkfox/zealot/helpers/SqlInfoPrinter.java
SqlInfoPrinter.printZealotSqlInfo
public void printZealotSqlInfo(SqlInfo sqlInfo, boolean hasXml, String nameSpace, String zealotId) { // 如果可以配置的打印SQL信息,且日志级别是info级别,则打印SQL信息. if (NormalConfig.getInstance().isPrintSqlInfo()) { StringBuilder sb = new StringBuilder(LINE_BREAK); sb.append(PRINT_START).append(LINE_BREAK); // 如果是xml版本的SQL,则打印xml的相关信息. if (hasXml) { sb.append("--zealot xml: ").append(XmlContext.INSTANCE.getXmlPathMap().get(nameSpace)) .append(" -> ").append(zealotId).append(LINE_BREAK); } sb.append("-------- SQL: ").append(sqlInfo.getSql()).append(LINE_BREAK) .append("----- Params: ").append(Arrays.toString(sqlInfo.getParamsArr())).append(LINE_BREAK); sb.append(PRINT_END).append(LINE_BREAK); log.info(sb.toString()); } }
java
public void printZealotSqlInfo(SqlInfo sqlInfo, boolean hasXml, String nameSpace, String zealotId) { // 如果可以配置的打印SQL信息,且日志级别是info级别,则打印SQL信息. if (NormalConfig.getInstance().isPrintSqlInfo()) { StringBuilder sb = new StringBuilder(LINE_BREAK); sb.append(PRINT_START).append(LINE_BREAK); // 如果是xml版本的SQL,则打印xml的相关信息. if (hasXml) { sb.append("--zealot xml: ").append(XmlContext.INSTANCE.getXmlPathMap().get(nameSpace)) .append(" -> ").append(zealotId).append(LINE_BREAK); } sb.append("-------- SQL: ").append(sqlInfo.getSql()).append(LINE_BREAK) .append("----- Params: ").append(Arrays.toString(sqlInfo.getParamsArr())).append(LINE_BREAK); sb.append(PRINT_END).append(LINE_BREAK); log.info(sb.toString()); } }
[ "public", "void", "printZealotSqlInfo", "(", "SqlInfo", "sqlInfo", ",", "boolean", "hasXml", ",", "String", "nameSpace", ",", "String", "zealotId", ")", "{", "// 如果可以配置的打印SQL信息,且日志级别是info级别,则打印SQL信息.", "if", "(", "NormalConfig", ".", "getInstance", "(", ")", ".", ...
打印SqlInfo的日志信息. @param nameSpace XML命名空间 @param zealotId XML中的zealotId @param sqlInfo 要打印的SqlInfo对象 @param hasXml 是否包含xml的打印信息
[ "打印SqlInfo的日志信息", "." ]
train
https://github.com/blinkfox/zealot/blob/21b00fa3e4ed42188eef3116d494e112e7a4194c/src/main/java/com/blinkfox/zealot/helpers/SqlInfoPrinter.java#L49-L66
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/ConstructorBuilder.java
ConstructorBuilder.buildConstructorDoc
public void buildConstructorDoc(XMLNode node, Content memberDetailsTree) { if (writer == null) { return; } int size = constructors.size(); if (size > 0) { Content constructorDetailsTree = writer.getConstructorDetailsTreeHeader( classDoc, memberDetailsTree); for (currentConstructorIndex = 0; currentConstructorIndex < size; currentConstructorIndex++) { Content constructorDocTree = writer.getConstructorDocTreeHeader( (ConstructorDoc) constructors.get(currentConstructorIndex), constructorDetailsTree); buildChildren(node, constructorDocTree); constructorDetailsTree.addContent(writer.getConstructorDoc( constructorDocTree, (currentConstructorIndex == size - 1))); } memberDetailsTree.addContent( writer.getConstructorDetails(constructorDetailsTree)); } }
java
public void buildConstructorDoc(XMLNode node, Content memberDetailsTree) { if (writer == null) { return; } int size = constructors.size(); if (size > 0) { Content constructorDetailsTree = writer.getConstructorDetailsTreeHeader( classDoc, memberDetailsTree); for (currentConstructorIndex = 0; currentConstructorIndex < size; currentConstructorIndex++) { Content constructorDocTree = writer.getConstructorDocTreeHeader( (ConstructorDoc) constructors.get(currentConstructorIndex), constructorDetailsTree); buildChildren(node, constructorDocTree); constructorDetailsTree.addContent(writer.getConstructorDoc( constructorDocTree, (currentConstructorIndex == size - 1))); } memberDetailsTree.addContent( writer.getConstructorDetails(constructorDetailsTree)); } }
[ "public", "void", "buildConstructorDoc", "(", "XMLNode", "node", ",", "Content", "memberDetailsTree", ")", "{", "if", "(", "writer", "==", "null", ")", "{", "return", ";", "}", "int", "size", "=", "constructors", ".", "size", "(", ")", ";", "if", "(", ...
Build the constructor documentation. @param node the XML element that specifies which components to document @param memberDetailsTree the content tree to which the documentation will be added
[ "Build", "the", "constructor", "documentation", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/ConstructorBuilder.java#L161-L181
lessthanoptimal/ejml
main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java
CommonOps_DSCC.permutationVector
public static void permutationVector( DMatrixSparseCSC P , int[] vector) { if( P.numCols != P.numRows ) { throw new MatrixDimensionException("Expected a square matrix"); } else if( P.nz_length != P.numCols ) { throw new IllegalArgumentException("Expected N non-zero elements in permutation matrix"); } else if( vector.length < P.numCols ) { throw new IllegalArgumentException("vector is too short"); } int M = P.numCols; for (int i = 0; i < M; i++) { if( P.col_idx[i+1] != i+1 ) throw new IllegalArgumentException("Unexpected number of elements in a column"); vector[P.nz_rows[i]] = i; } }
java
public static void permutationVector( DMatrixSparseCSC P , int[] vector) { if( P.numCols != P.numRows ) { throw new MatrixDimensionException("Expected a square matrix"); } else if( P.nz_length != P.numCols ) { throw new IllegalArgumentException("Expected N non-zero elements in permutation matrix"); } else if( vector.length < P.numCols ) { throw new IllegalArgumentException("vector is too short"); } int M = P.numCols; for (int i = 0; i < M; i++) { if( P.col_idx[i+1] != i+1 ) throw new IllegalArgumentException("Unexpected number of elements in a column"); vector[P.nz_rows[i]] = i; } }
[ "public", "static", "void", "permutationVector", "(", "DMatrixSparseCSC", "P", ",", "int", "[", "]", "vector", ")", "{", "if", "(", "P", ".", "numCols", "!=", "P", ".", "numRows", ")", "{", "throw", "new", "MatrixDimensionException", "(", "\"Expected a squar...
Converts the permutation matrix into a vector @param P (Input) Permutation matrix @param vector (Output) Permutation vector
[ "Converts", "the", "permutation", "matrix", "into", "a", "vector" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java#L842-L859
Ordinastie/MalisisCore
src/main/java/net/malisis/core/renderer/icon/provider/IconProviderBuilder.java
IconProviderBuilder.forShape
public IconProviderBuilder forShape(String shapeName, String iconName) { setType(Type.MODEL); shapeIcons.put(shapeName, icon(iconName)); return this; }
java
public IconProviderBuilder forShape(String shapeName, String iconName) { setType(Type.MODEL); shapeIcons.put(shapeName, icon(iconName)); return this; }
[ "public", "IconProviderBuilder", "forShape", "(", "String", "shapeName", ",", "String", "iconName", ")", "{", "setType", "(", "Type", ".", "MODEL", ")", ";", "shapeIcons", ".", "put", "(", "shapeName", ",", "icon", "(", "iconName", ")", ")", ";", "return",...
Sets the icon to use for a specific shape/group in a {@link MalisisModel}. @param shapeName the shape name @param iconName the icon name @return the icon provider builder
[ "Sets", "the", "icon", "to", "use", "for", "a", "specific", "shape", "/", "group", "in", "a", "{", "@link", "MalisisModel", "}", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/renderer/icon/provider/IconProviderBuilder.java#L281-L286
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/ULocale.java
ULocale.getDisplayLanguage
public static String getDisplayLanguage(String localeID, String displayLocaleID) { return getDisplayLanguageInternal(new ULocale(localeID), new ULocale(displayLocaleID), false); }
java
public static String getDisplayLanguage(String localeID, String displayLocaleID) { return getDisplayLanguageInternal(new ULocale(localeID), new ULocale(displayLocaleID), false); }
[ "public", "static", "String", "getDisplayLanguage", "(", "String", "localeID", ",", "String", "displayLocaleID", ")", "{", "return", "getDisplayLanguageInternal", "(", "new", "ULocale", "(", "localeID", ")", ",", "new", "ULocale", "(", "displayLocaleID", ")", ",",...
<strong>[icu]</strong> Returns a locale's language localized for display in the provided locale. This is a cover for the ICU4C API. @param localeID the id of the locale whose language will be displayed @param displayLocaleID the id of the locale in which to display the name. @return the localized language name.
[ "<strong", ">", "[", "icu", "]", "<", "/", "strong", ">", "Returns", "a", "locale", "s", "language", "localized", "for", "display", "in", "the", "provided", "locale", ".", "This", "is", "a", "cover", "for", "the", "ICU4C", "API", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/ULocale.java#L1393-L1396
otto-de/edison-hal
src/main/java/de/otto/edison/hal/traverson/Traverson.java
Traverson.startWith
public Traverson startWith(final URL contextUrl, final HalRepresentation resource) { this.startWith = null; this.contextUrl = requireNonNull(contextUrl); this.lastResult = singletonList(requireNonNull(resource)); return this; }
java
public Traverson startWith(final URL contextUrl, final HalRepresentation resource) { this.startWith = null; this.contextUrl = requireNonNull(contextUrl); this.lastResult = singletonList(requireNonNull(resource)); return this; }
[ "public", "Traverson", "startWith", "(", "final", "URL", "contextUrl", ",", "final", "HalRepresentation", "resource", ")", "{", "this", ".", "startWith", "=", "null", ";", "this", ".", "contextUrl", "=", "requireNonNull", "(", "contextUrl", ")", ";", "this", ...
Start traversal at the given HAL resource, using the {@code contextUrl} to resolve relative links. <p> If the {@code resource} is obtained from another Traverson, {@link Traverson#getCurrentContextUrl()} can be called to get this URL. </p> @param contextUrl URL of the Traverson's current context, used to resolve relative links @param resource the initial HAL resource. @return Traverson initialized with the specified {@link HalRepresentation} and {@code contextUrl}. @since 1.0.0
[ "Start", "traversal", "at", "the", "given", "HAL", "resource", "using", "the", "{", "@code", "contextUrl", "}", "to", "resolve", "relative", "links", "." ]
train
https://github.com/otto-de/edison-hal/blob/1582d2b49d1f0d9103e03bf742f18afa9d166992/src/main/java/de/otto/edison/hal/traverson/Traverson.java#L331-L336