repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
196
func_name
stringlengths
7
107
whole_func_string
stringlengths
76
3.82k
language
stringclasses
1 value
func_code_string
stringlengths
76
3.82k
func_code_tokens
listlengths
22
717
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
508
split_name
stringclasses
1 value
func_code_url
stringlengths
111
310
JRebirth/JRebirth
org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/ui/AbstractController.java
AbstractController.getTarget
protected <T> Optional<T> getTarget(Event event, Class<T> type) { return getValue(event, event::getTarget, type); }
java
protected <T> Optional<T> getTarget(Event event, Class<T> type) { return getValue(event, event::getTarget, type); }
[ "protected", "<", "T", ">", "Optional", "<", "T", ">", "getTarget", "(", "Event", "event", ",", "Class", "<", "T", ">", "type", ")", "{", "return", "getValue", "(", "event", ",", "event", "::", "getTarget", ",", "type", ")", ";", "}" ]
Gets the target. @param event the event @param type the cls @param <T> the generic type @return the target
[ "Gets", "the", "target", "." ]
train
https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/ui/AbstractController.java#L347-L349
phax/ph-masterdata
ph-masterdata/src/main/java/com/helger/masterdata/postal/PostalCodeManager.java
PostalCodeManager.isValidPostalCodeDefaultNo
public boolean isValidPostalCodeDefaultNo (@Nullable final Locale aCountry, @Nullable final String sPostalCode) { return isValidPostalCode (aCountry, sPostalCode).getAsBooleanValue (false); }
java
public boolean isValidPostalCodeDefaultNo (@Nullable final Locale aCountry, @Nullable final String sPostalCode) { return isValidPostalCode (aCountry, sPostalCode).getAsBooleanValue (false); }
[ "public", "boolean", "isValidPostalCodeDefaultNo", "(", "@", "Nullable", "final", "Locale", "aCountry", ",", "@", "Nullable", "final", "String", "sPostalCode", ")", "{", "return", "isValidPostalCode", "(", "aCountry", ",", "sPostalCode", ")", ".", "getAsBooleanValue...
Check if the passed postal code is valid for the passed country. If no information for that specific country is defined, the postal code is assumed invalid! @param aCountry The country to check. May be <code>null</code>. @param sPostalCode The postal code to check. May be <code>null</code>. @return <code>true</code> if the postal code is valid for the passed country, <code>false</code> otherwise also if no information for the passed country are present.
[ "Check", "if", "the", "passed", "postal", "code", "is", "valid", "for", "the", "passed", "country", ".", "If", "no", "information", "for", "that", "specific", "country", "is", "defined", "the", "postal", "code", "is", "assumed", "invalid!" ]
train
https://github.com/phax/ph-masterdata/blob/ca5e0b03c735b30b47930c018bfb5e71f00d0ff4/ph-masterdata/src/main/java/com/helger/masterdata/postal/PostalCodeManager.java#L151-L154
goldmansachs/gs-collections
collections/src/main/java/com/gs/collections/impl/utility/ListIterate.java
ListIterate.reverseForEach
public static <T> void reverseForEach(List<T> list, Procedure<? super T> procedure) { if (!list.isEmpty()) { ListIterate.forEach(list, list.size() - 1, 0, procedure); } }
java
public static <T> void reverseForEach(List<T> list, Procedure<? super T> procedure) { if (!list.isEmpty()) { ListIterate.forEach(list, list.size() - 1, 0, procedure); } }
[ "public", "static", "<", "T", ">", "void", "reverseForEach", "(", "List", "<", "T", ">", "list", ",", "Procedure", "<", "?", "super", "T", ">", "procedure", ")", "{", "if", "(", "!", "list", ".", "isEmpty", "(", ")", ")", "{", "ListIterate", ".", ...
Iterates over the List in reverse order executing the Procedure for each element
[ "Iterates", "over", "the", "List", "in", "reverse", "order", "executing", "the", "Procedure", "for", "each", "element" ]
train
https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/ListIterate.java#L668-L674
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/nio/IOUtil.java
IOUtil.readFullyOrNothing
public static boolean readFullyOrNothing(InputStream in, byte[] buffer) throws IOException { int bytesRead = 0; do { int count = in.read(buffer, bytesRead, buffer.length - bytesRead); if (count < 0) { if (bytesRead == 0) { return false; } throw new EOFException(); } bytesRead += count; } while (bytesRead < buffer.length); return true; }
java
public static boolean readFullyOrNothing(InputStream in, byte[] buffer) throws IOException { int bytesRead = 0; do { int count = in.read(buffer, bytesRead, buffer.length - bytesRead); if (count < 0) { if (bytesRead == 0) { return false; } throw new EOFException(); } bytesRead += count; } while (bytesRead < buffer.length); return true; }
[ "public", "static", "boolean", "readFullyOrNothing", "(", "InputStream", "in", ",", "byte", "[", "]", "buffer", ")", "throws", "IOException", "{", "int", "bytesRead", "=", "0", ";", "do", "{", "int", "count", "=", "in", ".", "read", "(", "buffer", ",", ...
Fills a buffer from an {@link InputStream}. If it doesn't contain any more data, returns {@code false}. If it contains some data, but not enough to fill the buffer, {@link EOFException} is thrown. @param in the {@link InputStream} to read from @param buffer the buffer to fill @return {@code true} if the buffer was filled completely, {@code false} if there was no data in the {@link InputStream} @throws EOFException if there was some, but not enough, data in the {@link InputStream} to fill the buffer
[ "Fills", "a", "buffer", "from", "an", "{", "@link", "InputStream", "}", ".", "If", "it", "doesn", "t", "contain", "any", "more", "data", "returns", "{", "@code", "false", "}", ".", "If", "it", "contains", "some", "data", "but", "not", "enough", "to", ...
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/nio/IOUtil.java#L147-L160
Azure/azure-sdk-for-java
mediaservices/resource-manager/v2018_03_30_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_03_30_preview/implementation/TransformsInner.java
TransformsInner.updateAsync
public Observable<TransformInner> updateAsync(String resourceGroupName, String accountName, String transformName, TransformInner parameters) { return updateWithServiceResponseAsync(resourceGroupName, accountName, transformName, parameters).map(new Func1<ServiceResponse<TransformInner>, TransformInner>() { @Override public TransformInner call(ServiceResponse<TransformInner> response) { return response.body(); } }); }
java
public Observable<TransformInner> updateAsync(String resourceGroupName, String accountName, String transformName, TransformInner parameters) { return updateWithServiceResponseAsync(resourceGroupName, accountName, transformName, parameters).map(new Func1<ServiceResponse<TransformInner>, TransformInner>() { @Override public TransformInner call(ServiceResponse<TransformInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "TransformInner", ">", "updateAsync", "(", "String", "resourceGroupName", ",", "String", "accountName", ",", "String", "transformName", ",", "TransformInner", "parameters", ")", "{", "return", "updateWithServiceResponseAsync", "(", "resource...
Update Transform. Updates a Transform. @param resourceGroupName The name of the resource group within the Azure subscription. @param accountName The Media Services account name. @param transformName The Transform name. @param parameters The request parameters @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the TransformInner object
[ "Update", "Transform", ".", "Updates", "a", "Transform", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_03_30_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_03_30_preview/implementation/TransformsInner.java#L703-L710
ACRA/acra
acra-core/src/main/java/org/acra/builder/ReportExecutor.java
ReportExecutor.sendReport
private void sendReport(@NonNull File report, boolean onlySendSilentReports) { if (enabled) { schedulerStarter.scheduleReports(report, onlySendSilentReports); } else { ACRA.log.w(LOG_TAG, "Would be sending reports, but ACRA is disabled"); } }
java
private void sendReport(@NonNull File report, boolean onlySendSilentReports) { if (enabled) { schedulerStarter.scheduleReports(report, onlySendSilentReports); } else { ACRA.log.w(LOG_TAG, "Would be sending reports, but ACRA is disabled"); } }
[ "private", "void", "sendReport", "(", "@", "NonNull", "File", "report", ",", "boolean", "onlySendSilentReports", ")", "{", "if", "(", "enabled", ")", "{", "schedulerStarter", ".", "scheduleReports", "(", "report", ",", "onlySendSilentReports", ")", ";", "}", "...
Starts a Process to start sending outstanding error reports. @param onlySendSilentReports If true then only send silent reports.
[ "Starts", "a", "Process", "to", "start", "sending", "outstanding", "error", "reports", "." ]
train
https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-core/src/main/java/org/acra/builder/ReportExecutor.java#L246-L252
alkacon/opencms-core
src/org/opencms/ade/configuration/CmsDetailNameCache.java
CmsDetailNameCache.checkIfUpdateIsNeeded
private void checkIfUpdateIsNeeded(CmsUUID structureId, String rootPath, int typeId) { try { I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(typeId); if ((resType instanceof CmsResourceTypeXmlContent) && !OpenCms.getResourceManager().matchResourceType( CmsResourceTypeXmlContainerPage.RESOURCE_TYPE_NAME, typeId)) { markForUpdate(structureId); } } catch (CmsLoaderException e) { // resource type not found, just log an error LOG.error(e.getLocalizedMessage(), e); } }
java
private void checkIfUpdateIsNeeded(CmsUUID structureId, String rootPath, int typeId) { try { I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(typeId); if ((resType instanceof CmsResourceTypeXmlContent) && !OpenCms.getResourceManager().matchResourceType( CmsResourceTypeXmlContainerPage.RESOURCE_TYPE_NAME, typeId)) { markForUpdate(structureId); } } catch (CmsLoaderException e) { // resource type not found, just log an error LOG.error(e.getLocalizedMessage(), e); } }
[ "private", "void", "checkIfUpdateIsNeeded", "(", "CmsUUID", "structureId", ",", "String", "rootPath", ",", "int", "typeId", ")", "{", "try", "{", "I_CmsResourceType", "resType", "=", "OpenCms", ".", "getResourceManager", "(", ")", ".", "getResourceType", "(", "t...
Checks if the cache needs to be updated for the resource, and if so, marks the structure id for updating.<p> @param structureId the structure id for the resource @param rootPath the path of the resource @param typeId the resource type id
[ "Checks", "if", "the", "cache", "needs", "to", "be", "updated", "for", "the", "resource", "and", "if", "so", "marks", "the", "structure", "id", "for", "updating", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/configuration/CmsDetailNameCache.java#L188-L202
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/internal/KernelUtils.java
KernelUtils.getProperties
public static Properties getProperties(final InputStream is) throws IOException { Properties p = new Properties(); try { if (is != null) { p.load(is); // Look for "values" and strip the quotes to values for (Entry<Object, Object> entry : p.entrySet()) { String s = ((String) entry.getValue()).trim(); // If first and last characters are ", strip them off.. if (s.length() > 1 && s.startsWith("\"") && s.endsWith("\"")) { entry.setValue(s.substring(1, s.length() - 1)); } } } } finally { Utils.tryToClose(is); } return p; }
java
public static Properties getProperties(final InputStream is) throws IOException { Properties p = new Properties(); try { if (is != null) { p.load(is); // Look for "values" and strip the quotes to values for (Entry<Object, Object> entry : p.entrySet()) { String s = ((String) entry.getValue()).trim(); // If first and last characters are ", strip them off.. if (s.length() > 1 && s.startsWith("\"") && s.endsWith("\"")) { entry.setValue(s.substring(1, s.length() - 1)); } } } } finally { Utils.tryToClose(is); } return p; }
[ "public", "static", "Properties", "getProperties", "(", "final", "InputStream", "is", ")", "throws", "IOException", "{", "Properties", "p", "=", "new", "Properties", "(", ")", ";", "try", "{", "if", "(", "is", "!=", "null", ")", "{", "p", ".", "load", ...
Read properties from input stream. Will close the input stream before returning. @param is InputStream to read properties from @return Properties object; will be empty if InputStream is null or empty. @throws LaunchException
[ "Read", "properties", "from", "input", "stream", ".", "Will", "close", "the", "input", "stream", "before", "returning", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/internal/KernelUtils.java#L128-L149
alkacon/opencms-core
src/org/opencms/workplace/explorer/CmsExplorerTypeSettings.java
CmsExplorerTypeSettings.setTypeAttributes
public void setTypeAttributes(String name, String key, String icon) { setName(name); setKey(key); setIcon(icon); }
java
public void setTypeAttributes(String name, String key, String icon) { setName(name); setKey(key); setIcon(icon); }
[ "public", "void", "setTypeAttributes", "(", "String", "name", ",", "String", "key", ",", "String", "icon", ")", "{", "setName", "(", "name", ")", ";", "setKey", "(", "key", ")", ";", "setIcon", "(", "icon", ")", ";", "}" ]
Sets the basic attributes of the type settings.<p> @param name the name of the type setting @param key the key name of the explorer type setting @param icon the icon path and file name of the explorer type setting
[ "Sets", "the", "basic", "attributes", "of", "the", "type", "settings", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/explorer/CmsExplorerTypeSettings.java#L891-L896
alipay/sofa-rpc
extension-impl/fault-tolerance/src/main/java/com/alipay/sofa/rpc/client/aft/impl/ServiceHorizontalMeasureStrategy.java
ServiceHorizontalMeasureStrategy.calculateAverageExceptionRate
private double calculateAverageExceptionRate(List<InvocationStat> invocationStats, long leastWindowCount) { long sumException = 0; long sumCall = 0; for (InvocationStat invocationStat : invocationStats) { long invocationLeastWindowCount = getInvocationLeastWindowCount(invocationStat, ProviderInfoWeightManager.getWeight(invocationStat.getDimension().getProviderInfo()), leastWindowCount); if (invocationLeastWindowCount != -1 && invocationStat.getInvokeCount() >= invocationLeastWindowCount) { sumException += invocationStat.getExceptionCount(); sumCall += invocationStat.getInvokeCount(); } } if (sumCall == 0) { return -1; } return CalculateUtils.divide(sumException, sumCall); }
java
private double calculateAverageExceptionRate(List<InvocationStat> invocationStats, long leastWindowCount) { long sumException = 0; long sumCall = 0; for (InvocationStat invocationStat : invocationStats) { long invocationLeastWindowCount = getInvocationLeastWindowCount(invocationStat, ProviderInfoWeightManager.getWeight(invocationStat.getDimension().getProviderInfo()), leastWindowCount); if (invocationLeastWindowCount != -1 && invocationStat.getInvokeCount() >= invocationLeastWindowCount) { sumException += invocationStat.getExceptionCount(); sumCall += invocationStat.getInvokeCount(); } } if (sumCall == 0) { return -1; } return CalculateUtils.divide(sumException, sumCall); }
[ "private", "double", "calculateAverageExceptionRate", "(", "List", "<", "InvocationStat", ">", "invocationStats", ",", "long", "leastWindowCount", ")", "{", "long", "sumException", "=", "0", ";", "long", "sumCall", "=", "0", ";", "for", "(", "InvocationStat", "i...
计算平均异常率,如果调用次数小于leastWindowCount则不参与计算。 如果所有调用次数均为0则返回-1 @param invocationStats List<InvocationStat> @param leastWindowCount leastWindowCount @return The average exception rate of all invocation statics
[ "计算平均异常率,如果调用次数小于leastWindowCount则不参与计算。", "如果所有调用次数均为0则返回", "-", "1" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/fault-tolerance/src/main/java/com/alipay/sofa/rpc/client/aft/impl/ServiceHorizontalMeasureStrategy.java#L265-L284
ontop/ontop
core/obda/src/main/java/it/unibz/inf/ontop/spec/ontology/impl/OntologyBuilderImpl.java
OntologyBuilderImpl.addSubPropertyOfAxiom
@Override public void addSubPropertyOfAxiom(ObjectPropertyExpression ope1, ObjectPropertyExpression ope2) throws InconsistentOntologyException { checkSignature(ope1); checkSignature(ope2); objectPropertyAxioms.addInclusion(ope1, ope2); }
java
@Override public void addSubPropertyOfAxiom(ObjectPropertyExpression ope1, ObjectPropertyExpression ope2) throws InconsistentOntologyException { checkSignature(ope1); checkSignature(ope2); objectPropertyAxioms.addInclusion(ope1, ope2); }
[ "@", "Override", "public", "void", "addSubPropertyOfAxiom", "(", "ObjectPropertyExpression", "ope1", ",", "ObjectPropertyExpression", "ope2", ")", "throws", "InconsistentOntologyException", "{", "checkSignature", "(", "ope1", ")", ";", "checkSignature", "(", "ope2", ")"...
Normalizes and adds an object subproperty axiom <p> SubObjectPropertyOf := 'SubObjectPropertyOf' '(' axiomAnnotations ObjectPropertyExpression ObjectPropertyExpression ')' <p> Implements rule [O1]:<br> - ignore the axiom if the first argument is owl:bottomObjectProperty or the second argument is owl:topObjectProperty<br> - replace by a disjointness axiom if the second argument is owl:bottomObjectProperty but the first one is not owl:topObjectProperty<br> - inconsistency if the first is owl:topObjectProperty but the second is owl:bottomObjectProperty @throws InconsistentOntologyException
[ "Normalizes", "and", "adds", "an", "object", "subproperty", "axiom", "<p", ">", "SubObjectPropertyOf", ":", "=", "SubObjectPropertyOf", "(", "axiomAnnotations", "ObjectPropertyExpression", "ObjectPropertyExpression", ")", "<p", ">", "Implements", "rule", "[", "O1", "]...
train
https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/core/obda/src/main/java/it/unibz/inf/ontop/spec/ontology/impl/OntologyBuilderImpl.java#L268-L273
line/centraldogma
server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/MetadataService.java
MetadataService.removeToken
public CompletableFuture<Revision> removeToken(Author author, String projectName, String appId) { requireNonNull(author, "author"); requireNonNull(projectName, "projectName"); requireNonNull(appId, "appId"); return removeToken(projectName, author, appId, false); }
java
public CompletableFuture<Revision> removeToken(Author author, String projectName, String appId) { requireNonNull(author, "author"); requireNonNull(projectName, "projectName"); requireNonNull(appId, "appId"); return removeToken(projectName, author, appId, false); }
[ "public", "CompletableFuture", "<", "Revision", ">", "removeToken", "(", "Author", "author", ",", "String", "projectName", ",", "String", "appId", ")", "{", "requireNonNull", "(", "author", ",", "\"author\"", ")", ";", "requireNonNull", "(", "projectName", ",", ...
Removes the {@link Token} of the specified {@code appId} from the specified {@code projectName}. It also removes every token permission belonging to {@link Token} from every {@link RepositoryMetadata}.
[ "Removes", "the", "{" ]
train
https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/MetadataService.java#L370-L376
alkacon/opencms-core
src/org/opencms/loader/CmsTemplateContextManager.java
CmsTemplateContextManager.getContextInfoBean
public CmsTemplateContextInfo getContextInfoBean(CmsObject cms, HttpServletRequest request) { CmsTemplateContextInfo result = new CmsTemplateContextInfo(); CmsTemplateContext context = (CmsTemplateContext)request.getAttribute(ATTR_TEMPLATE_CONTEXT); if (context != null) { result.setCurrentContext(context.getKey()); I_CmsTemplateContextProvider provider = context.getProvider(); Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); CmsXmlContentProperty settingDefinition = createTemplateContextsPropertyDefinition(provider, locale); result.setSettingDefinition(settingDefinition); String cookieName = context.getProvider().getOverrideCookieName(); if (cookieName != null) { String cookieValue = CmsRequestUtil.getCookieValue(request.getCookies(), cookieName); result.setSelectedContext(cookieValue); } result.setCookieName(cookieName); Map<String, String> niceNames = new LinkedHashMap<String, String>(); for (Map.Entry<String, CmsTemplateContext> entry : provider.getAllContexts().entrySet()) { CmsTemplateContext otherContext = entry.getValue(); String niceName = otherContext.getLocalizedName(locale); niceNames.put(otherContext.getKey(), niceName); for (CmsClientVariant variant : otherContext.getClientVariants().values()) { CmsClientVariantInfo info = new CmsClientVariantInfo( variant.getName(), variant.getNiceName(locale), variant.getScreenWidth(), variant.getScreenHeight(), variant.getParameters()); result.setClientVariant(otherContext.getKey(), variant.getName(), info); } } result.setContextLabels(niceNames); result.setContextProvider(provider.getClass().getName()); } Map<String, CmsDefaultSet<String>> allowedContextMap = safeGetAllowedContextMap(); result.setAllowedContexts(allowedContextMap); return result; }
java
public CmsTemplateContextInfo getContextInfoBean(CmsObject cms, HttpServletRequest request) { CmsTemplateContextInfo result = new CmsTemplateContextInfo(); CmsTemplateContext context = (CmsTemplateContext)request.getAttribute(ATTR_TEMPLATE_CONTEXT); if (context != null) { result.setCurrentContext(context.getKey()); I_CmsTemplateContextProvider provider = context.getProvider(); Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); CmsXmlContentProperty settingDefinition = createTemplateContextsPropertyDefinition(provider, locale); result.setSettingDefinition(settingDefinition); String cookieName = context.getProvider().getOverrideCookieName(); if (cookieName != null) { String cookieValue = CmsRequestUtil.getCookieValue(request.getCookies(), cookieName); result.setSelectedContext(cookieValue); } result.setCookieName(cookieName); Map<String, String> niceNames = new LinkedHashMap<String, String>(); for (Map.Entry<String, CmsTemplateContext> entry : provider.getAllContexts().entrySet()) { CmsTemplateContext otherContext = entry.getValue(); String niceName = otherContext.getLocalizedName(locale); niceNames.put(otherContext.getKey(), niceName); for (CmsClientVariant variant : otherContext.getClientVariants().values()) { CmsClientVariantInfo info = new CmsClientVariantInfo( variant.getName(), variant.getNiceName(locale), variant.getScreenWidth(), variant.getScreenHeight(), variant.getParameters()); result.setClientVariant(otherContext.getKey(), variant.getName(), info); } } result.setContextLabels(niceNames); result.setContextProvider(provider.getClass().getName()); } Map<String, CmsDefaultSet<String>> allowedContextMap = safeGetAllowedContextMap(); result.setAllowedContexts(allowedContextMap); return result; }
[ "public", "CmsTemplateContextInfo", "getContextInfoBean", "(", "CmsObject", "cms", ",", "HttpServletRequest", "request", ")", "{", "CmsTemplateContextInfo", "result", "=", "new", "CmsTemplateContextInfo", "(", ")", ";", "CmsTemplateContext", "context", "=", "(", "CmsTem...
Creates a bean with information about the current template context, for use in the client-side code.<p> @param cms the current CMS context @param request the current request @return the bean with the template context information
[ "Creates", "a", "bean", "with", "information", "about", "the", "current", "template", "context", "for", "use", "in", "the", "client", "-", "side", "code", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/loader/CmsTemplateContextManager.java#L165-L203
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java
ComputeNodeOperations.getComputeNodeRemoteDesktop
public String getComputeNodeRemoteDesktop(String poolId, String nodeId) throws BatchErrorException, IOException { return getComputeNodeRemoteDesktop(poolId, nodeId, null); }
java
public String getComputeNodeRemoteDesktop(String poolId, String nodeId) throws BatchErrorException, IOException { return getComputeNodeRemoteDesktop(poolId, nodeId, null); }
[ "public", "String", "getComputeNodeRemoteDesktop", "(", "String", "poolId", ",", "String", "nodeId", ")", "throws", "BatchErrorException", ",", "IOException", "{", "return", "getComputeNodeRemoteDesktop", "(", "poolId", ",", "nodeId", ",", "null", ")", ";", "}" ]
Gets a Remote Desktop Protocol (RDP) file for the specified node. @param poolId The ID of the pool that contains the compute node. @param nodeId The ID of the compute node for which to get a Remote Desktop file. @return The RDP file contents. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
[ "Gets", "a", "Remote", "Desktop", "Protocol", "(", "RDP", ")", "file", "for", "the", "specified", "node", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java#L441-L443
apache/incubator-gobblin
gobblin-modules/gobblin-http/src/main/java/org/apache/gobblin/r2/R2RestRequestBuilder.java
R2RestRequestBuilder.addPayload
protected int addPayload(RestRequestBuilder builder, String payload) { if (payload == null || payload.length() == 0) { return 0; } builder.setHeader(RestConstants.HEADER_CONTENT_TYPE, RestConstants.HEADER_VALUE_APPLICATION_JSON); try { DataMap data = JACKSON_DATA_CODEC.stringToMap(payload); byte[] bytes = JACKSON_DATA_CODEC.mapToBytes(data); builder.setEntity(bytes); return bytes.length; } catch (IOException e) { throw new RuntimeException("Fail to convert payload: " + payload, e); } }
java
protected int addPayload(RestRequestBuilder builder, String payload) { if (payload == null || payload.length() == 0) { return 0; } builder.setHeader(RestConstants.HEADER_CONTENT_TYPE, RestConstants.HEADER_VALUE_APPLICATION_JSON); try { DataMap data = JACKSON_DATA_CODEC.stringToMap(payload); byte[] bytes = JACKSON_DATA_CODEC.mapToBytes(data); builder.setEntity(bytes); return bytes.length; } catch (IOException e) { throw new RuntimeException("Fail to convert payload: " + payload, e); } }
[ "protected", "int", "addPayload", "(", "RestRequestBuilder", "builder", ",", "String", "payload", ")", "{", "if", "(", "payload", "==", "null", "||", "payload", ".", "length", "(", ")", "==", "0", ")", "{", "return", "0", ";", "}", "builder", ".", "set...
Add payload to request. By default, payload is sent as application/json
[ "Add", "payload", "to", "request", ".", "By", "default", "payload", "is", "sent", "as", "application", "/", "json" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-http/src/main/java/org/apache/gobblin/r2/R2RestRequestBuilder.java#L107-L121
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/files/FileUtilities.java
FileUtilities.writeFile
public static void writeFile( String text, File file ) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) { bw.write(text); } }
java
public static void writeFile( String text, File file ) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) { bw.write(text); } }
[ "public", "static", "void", "writeFile", "(", "String", "text", ",", "File", "file", ")", "throws", "IOException", "{", "try", "(", "BufferedWriter", "bw", "=", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "file", ")", ")", ")", "{", "bw", "."...
Write text to a file in one line. @param text the text to write. @param file the file to write to. @throws IOException
[ "Write", "text", "to", "a", "file", "in", "one", "line", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/files/FileUtilities.java#L218-L223
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/db/event/SoftDeleteHandler.java
SoftDeleteHandler.doRecordChange
public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption) { // Read a valid record if (iChangeType == DBConstants.DELETE_TYPE) if ((this.getOwner().getEditMode() & DBConstants.EDIT_ADD) != DBConstants.EDIT_ADD) if (this.isSoftDeleteThisRecord()) { int iErrorCode = this.softDeleteThisRecord(); if (iErrorCode != DBConstants.NORMAL_RETURN) return iErrorCode; try { this.getOwner().set(); // Update the record } catch (DBException ex) { return ex.getErrorCode(); } return iErrorCode; } return super.doRecordChange(field, iChangeType, bDisplayOption); // Initialize the record }
java
public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption) { // Read a valid record if (iChangeType == DBConstants.DELETE_TYPE) if ((this.getOwner().getEditMode() & DBConstants.EDIT_ADD) != DBConstants.EDIT_ADD) if (this.isSoftDeleteThisRecord()) { int iErrorCode = this.softDeleteThisRecord(); if (iErrorCode != DBConstants.NORMAL_RETURN) return iErrorCode; try { this.getOwner().set(); // Update the record } catch (DBException ex) { return ex.getErrorCode(); } return iErrorCode; } return super.doRecordChange(field, iChangeType, bDisplayOption); // Initialize the record }
[ "public", "int", "doRecordChange", "(", "FieldInfo", "field", ",", "int", "iChangeType", ",", "boolean", "bDisplayOption", ")", "{", "// Read a valid record", "if", "(", "iChangeType", "==", "DBConstants", ".", "DELETE_TYPE", ")", "if", "(", "(", "this", ".", ...
Called when a change is the record status is about to happen/has happened. On an add or lock, makes sure the main key field is set to the current main target field so it will be a child of the current main record. @param field If this file change is due to a field, this is the field. @param iChangeType The type of change that occurred. @param bDisplayOption If true, display any changes. @return an error code. Before an add, set the key back to the original value.
[ "Called", "when", "a", "change", "is", "the", "record", "status", "is", "about", "to", "happen", "/", "has", "happened", ".", "On", "an", "add", "or", "lock", "makes", "sure", "the", "main", "key", "field", "is", "set", "to", "the", "current", "main", ...
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/event/SoftDeleteHandler.java#L120-L140
zzsrv/torrent-utils
src/main/java/cc/vcode/util/Constants.java
Constants.compareVersions
public static int compareVersions(String version_1, String version_2) { for (int j = 0; j < Math.min(version_2.length(), version_1.length()); j++) { char v1_c = version_1.charAt(j); char v2_c = version_2.charAt(j); if (v1_c == v2_c) { continue; } if (v2_c == '.') { // version1 higher (e.g. 10.2 -vs- 1.2) return (+1); } else if (v1_c == '.') { // version2 higher ( e.g. 1.2 -vs- 10.2 ) return (-1); } else { return (v1_c - v2_c); } } // longest one wins. e.g. 1.2.1 -vs- 1.2 return (version_1.length() - version_2.length()); }
java
public static int compareVersions(String version_1, String version_2) { for (int j = 0; j < Math.min(version_2.length(), version_1.length()); j++) { char v1_c = version_1.charAt(j); char v2_c = version_2.charAt(j); if (v1_c == v2_c) { continue; } if (v2_c == '.') { // version1 higher (e.g. 10.2 -vs- 1.2) return (+1); } else if (v1_c == '.') { // version2 higher ( e.g. 1.2 -vs- 10.2 ) return (-1); } else { return (v1_c - v2_c); } } // longest one wins. e.g. 1.2.1 -vs- 1.2 return (version_1.length() - version_2.length()); }
[ "public", "static", "int", "compareVersions", "(", "String", "version_1", ",", "String", "version_2", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "Math", ".", "min", "(", "version_2", ".", "length", "(", ")", ",", "version_1", ".", "le...
compare two version strings of form n.n.n.n (e.g. 1.2.3.4) @param version_1 @param version_2 @return -ve -> version_1 lower, 0 = same, +ve -> version_1 higher
[ "compare", "two", "version", "strings", "of", "form", "n", ".", "n", ".", "n", ".", "n", "(", "e", ".", "g", ".", "1", ".", "2", ".", "3", ".", "4", ")" ]
train
https://github.com/zzsrv/torrent-utils/blob/70ba8bccd5af1ed7a18c42c61ad409256e9865f3/src/main/java/cc/vcode/util/Constants.java#L160-L198
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/DefaultInternalConfiguration.java
DefaultInternalConfiguration.parseStringArray
private String[] parseStringArray(final String list) { StringTokenizer tokenizer = new StringTokenizer(list, ",", false); int length = tokenizer.countTokens(); String[] arr = new String[length]; for (int i = 0; tokenizer.hasMoreElements(); i++) { arr[i] = cleanSpaces(tokenizer.nextToken()); } return arr; }
java
private String[] parseStringArray(final String list) { StringTokenizer tokenizer = new StringTokenizer(list, ",", false); int length = tokenizer.countTokens(); String[] arr = new String[length]; for (int i = 0; tokenizer.hasMoreElements(); i++) { arr[i] = cleanSpaces(tokenizer.nextToken()); } return arr; }
[ "private", "String", "[", "]", "parseStringArray", "(", "final", "String", "list", ")", "{", "StringTokenizer", "tokenizer", "=", "new", "StringTokenizer", "(", "list", ",", "\",\"", ",", "false", ")", ";", "int", "length", "=", "tokenizer", ".", "countToken...
Splits the given comma-delimited string into an an array. Leading/trailing spaces in list items will be trimmed. @param list the String to split. @return the split version of the list.
[ "Splits", "the", "given", "comma", "-", "delimited", "string", "into", "an", "an", "array", ".", "Leading", "/", "trailing", "spaces", "in", "list", "items", "will", "be", "trimmed", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/DefaultInternalConfiguration.java#L189-L199
looly/hutool
hutool-extra/src/main/java/cn/hutool/extra/template/engine/velocity/VelocityUtil.java
VelocityUtil.toFile
public static void toFile(Template template, VelocityContext context, String destPath) { PrintWriter writer = null; try { writer = FileUtil.getPrintWriter(destPath, Velocity.getProperty(Velocity.INPUT_ENCODING).toString(), false); merge(template, context, writer); } catch (IORuntimeException e) { throw new UtilException(e, "Write Velocity content to [{}] error!", destPath); } finally { IoUtil.close(writer); } }
java
public static void toFile(Template template, VelocityContext context, String destPath) { PrintWriter writer = null; try { writer = FileUtil.getPrintWriter(destPath, Velocity.getProperty(Velocity.INPUT_ENCODING).toString(), false); merge(template, context, writer); } catch (IORuntimeException e) { throw new UtilException(e, "Write Velocity content to [{}] error!", destPath); } finally { IoUtil.close(writer); } }
[ "public", "static", "void", "toFile", "(", "Template", "template", ",", "VelocityContext", "context", ",", "String", "destPath", ")", "{", "PrintWriter", "writer", "=", "null", ";", "try", "{", "writer", "=", "FileUtil", ".", "getPrintWriter", "(", "destPath",...
生成文件 @param template 模板 @param context 模板上下文 @param destPath 目标路径(绝对)
[ "生成文件" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/template/engine/velocity/VelocityUtil.java#L165-L175
jayantk/jklol
src/com/jayantkrish/jklol/cfg/CfgParser.java
CfgParser.calculateOutside
private void calculateOutside(int spanStart, int spanEnd, CfgParseChart chart, double[] newValues) { Factor parentOutside = chart.getOutsideEntries(spanStart, spanEnd); Tensor parentWeights = parentOutside.coerceToDiscrete().getWeights(); Tensor binaryDistributionWeights = binaryDistribution.coerceToDiscrete().getWeights(); int parentIndex = Ints.indexOf(binaryDistributionWeights.getDimensionNumbers(), parentVar.getOnlyVariableNum()); int leftIndex = Ints.indexOf(binaryDistributionWeights.getDimensionNumbers(), leftVar.getOnlyVariableNum()); int rightIndex = Ints.indexOf(binaryDistributionWeights.getDimensionNumbers(), rightVar.getOnlyVariableNum()); int length = newValues.length; double[] binaryDistributionValues = binaryDistributionWeights.getValues(); for (int i = 0; i < spanEnd - spanStart; i++) { double[] leftInside = chart.getInsideEntriesArray(spanStart, spanStart + i); double[] rightInside = chart.getInsideEntriesArray(spanStart + i + 1, spanEnd); for (int j = 0; j < length; j++) { newValues[j] = binaryDistributionValues[j] * parentWeights.get(binaryDistributionWeights.indexToPartialDimKey(j, parentIndex)); newValues[j] *= rightInside[binaryDistributionWeights.indexToPartialDimKey(j, rightIndex)]; } chart.updateOutsideEntry(spanStart, spanStart + i, newValues, binaryDistribution, leftVar); for (int j = 0; j < length; j++) { newValues[j] *= leftInside[binaryDistributionWeights.indexToPartialDimKey(j, leftIndex)]; } chart.updateBinaryRuleExpectations(newValues); for (int j = 0; j < length; j++) { if (newValues[j] != 0.0) { newValues[j] = newValues[j] / rightInside[binaryDistributionWeights.indexToPartialDimKey(j, rightIndex)]; } } chart.updateOutsideEntry(spanStart + i + 1, spanEnd, newValues, binaryDistribution, rightVar); } }
java
private void calculateOutside(int spanStart, int spanEnd, CfgParseChart chart, double[] newValues) { Factor parentOutside = chart.getOutsideEntries(spanStart, spanEnd); Tensor parentWeights = parentOutside.coerceToDiscrete().getWeights(); Tensor binaryDistributionWeights = binaryDistribution.coerceToDiscrete().getWeights(); int parentIndex = Ints.indexOf(binaryDistributionWeights.getDimensionNumbers(), parentVar.getOnlyVariableNum()); int leftIndex = Ints.indexOf(binaryDistributionWeights.getDimensionNumbers(), leftVar.getOnlyVariableNum()); int rightIndex = Ints.indexOf(binaryDistributionWeights.getDimensionNumbers(), rightVar.getOnlyVariableNum()); int length = newValues.length; double[] binaryDistributionValues = binaryDistributionWeights.getValues(); for (int i = 0; i < spanEnd - spanStart; i++) { double[] leftInside = chart.getInsideEntriesArray(spanStart, spanStart + i); double[] rightInside = chart.getInsideEntriesArray(spanStart + i + 1, spanEnd); for (int j = 0; j < length; j++) { newValues[j] = binaryDistributionValues[j] * parentWeights.get(binaryDistributionWeights.indexToPartialDimKey(j, parentIndex)); newValues[j] *= rightInside[binaryDistributionWeights.indexToPartialDimKey(j, rightIndex)]; } chart.updateOutsideEntry(spanStart, spanStart + i, newValues, binaryDistribution, leftVar); for (int j = 0; j < length; j++) { newValues[j] *= leftInside[binaryDistributionWeights.indexToPartialDimKey(j, leftIndex)]; } chart.updateBinaryRuleExpectations(newValues); for (int j = 0; j < length; j++) { if (newValues[j] != 0.0) { newValues[j] = newValues[j] / rightInside[binaryDistributionWeights.indexToPartialDimKey(j, rightIndex)]; } } chart.updateOutsideEntry(spanStart + i + 1, spanEnd, newValues, binaryDistribution, rightVar); } }
[ "private", "void", "calculateOutside", "(", "int", "spanStart", ",", "int", "spanEnd", ",", "CfgParseChart", "chart", ",", "double", "[", "]", "newValues", ")", "{", "Factor", "parentOutside", "=", "chart", ".", "getOutsideEntries", "(", "spanStart", ",", "spa...
/* Calculate a single outside probability entry (and its corresponding marginal).
[ "/", "*", "Calculate", "a", "single", "outside", "probability", "entry", "(", "and", "its", "corresponding", "marginal", ")", "." ]
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/cfg/CfgParser.java#L485-L518
phax/ph-pdf-layout
src/main/java/com/helger/pdflayout4/pdfbox/PDPageContentStreamExt.java
PDPageContentStreamExt.setNonStrokingColor
public void setNonStrokingColor (final double c, final double m, final double y, final double k) throws IOException { if (_isOutsideOneInterval (c) || _isOutsideOneInterval (m) || _isOutsideOneInterval (y) || _isOutsideOneInterval (k)) { throw new IllegalArgumentException ("Parameters must be within 0..1, but are (" + c + "," + m + "," + y + "," + k + ")"); } writeOperand ((float) c); writeOperand ((float) m); writeOperand ((float) y); writeOperand ((float) k); writeOperator ((byte) 'k'); }
java
public void setNonStrokingColor (final double c, final double m, final double y, final double k) throws IOException { if (_isOutsideOneInterval (c) || _isOutsideOneInterval (m) || _isOutsideOneInterval (y) || _isOutsideOneInterval (k)) { throw new IllegalArgumentException ("Parameters must be within 0..1, but are (" + c + "," + m + "," + y + "," + k + ")"); } writeOperand ((float) c); writeOperand ((float) m); writeOperand ((float) y); writeOperand ((float) k); writeOperator ((byte) 'k'); }
[ "public", "void", "setNonStrokingColor", "(", "final", "double", "c", ",", "final", "double", "m", ",", "final", "double", "y", ",", "final", "double", "k", ")", "throws", "IOException", "{", "if", "(", "_isOutsideOneInterval", "(", "c", ")", "||", "_isOut...
Set the non-stroking color in the DeviceRGB color space. Range is 0..1. @param c The cyan value. @param m The magenta value. @param y The yellow value. @param k The black value. @throws IOException If an IO error occurs while writing to the stream.
[ "Set", "the", "non", "-", "stroking", "color", "in", "the", "DeviceRGB", "color", "space", ".", "Range", "is", "0", "..", "1", "." ]
train
https://github.com/phax/ph-pdf-layout/blob/777d9f3a131cbe8f592c0de1cf554084e541bb54/src/main/java/com/helger/pdflayout4/pdfbox/PDPageContentStreamExt.java#L1014-L1036
googleads/googleads-java-lib
examples/admanager_axis/src/main/java/admanager/axis/v201902/customtargetingservice/GetAllCustomTargetingKeysAndValues.java
GetAllCustomTargetingKeysAndValues.runExample
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { // Get the CustomTargetingService. CustomTargetingServiceInterface customTargetingService = adManagerServices.get(session, CustomTargetingServiceInterface.class); // Get all custom targeting keys. List<Long> customTargetingKeyIds = getAllCustomTargetingKeyIds(adManagerServices, session); // Create a statement to get all custom targeting values for a custom // targeting key. StatementBuilder statementBuilder = new StatementBuilder() .where("customTargetingKeyId = :customTargetingKeyId") .orderBy("id ASC") .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); int totalResultsCounter = 0; for (Long customTargetingKeyId : customTargetingKeyIds) { // Set the custom targeting key ID to select from. statementBuilder.withBindVariableValue("customTargetingKeyId", customTargetingKeyId); // Default for total result set size and offset. int totalResultSetSize = 0; statementBuilder.offset(0); do { // Get custom targeting values by statement. CustomTargetingValuePage page = customTargetingService.getCustomTargetingValuesByStatement( statementBuilder.toStatement()); if (page.getResults() != null) { totalResultSetSize = page.getTotalResultSetSize(); for (CustomTargetingValue customTargetingValue : page.getResults()) { System.out.printf( "%d) Custom targeting value with ID %d, belonging to key " + "with ID %d, name '%s' and display name '%s' was found.%n", totalResultsCounter++, customTargetingValue.getId(), customTargetingValue.getCustomTargetingKeyId(), customTargetingValue.getName(), customTargetingValue.getDisplayName()); } } statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.getOffset() < totalResultSetSize); } System.out.printf("Number of results found: %d%n", totalResultsCounter); }
java
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { // Get the CustomTargetingService. CustomTargetingServiceInterface customTargetingService = adManagerServices.get(session, CustomTargetingServiceInterface.class); // Get all custom targeting keys. List<Long> customTargetingKeyIds = getAllCustomTargetingKeyIds(adManagerServices, session); // Create a statement to get all custom targeting values for a custom // targeting key. StatementBuilder statementBuilder = new StatementBuilder() .where("customTargetingKeyId = :customTargetingKeyId") .orderBy("id ASC") .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); int totalResultsCounter = 0; for (Long customTargetingKeyId : customTargetingKeyIds) { // Set the custom targeting key ID to select from. statementBuilder.withBindVariableValue("customTargetingKeyId", customTargetingKeyId); // Default for total result set size and offset. int totalResultSetSize = 0; statementBuilder.offset(0); do { // Get custom targeting values by statement. CustomTargetingValuePage page = customTargetingService.getCustomTargetingValuesByStatement( statementBuilder.toStatement()); if (page.getResults() != null) { totalResultSetSize = page.getTotalResultSetSize(); for (CustomTargetingValue customTargetingValue : page.getResults()) { System.out.printf( "%d) Custom targeting value with ID %d, belonging to key " + "with ID %d, name '%s' and display name '%s' was found.%n", totalResultsCounter++, customTargetingValue.getId(), customTargetingValue.getCustomTargetingKeyId(), customTargetingValue.getName(), customTargetingValue.getDisplayName()); } } statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.getOffset() < totalResultSetSize); } System.out.printf("Number of results found: %d%n", totalResultsCounter); }
[ "public", "static", "void", "runExample", "(", "AdManagerServices", "adManagerServices", ",", "AdManagerSession", "session", ")", "throws", "RemoteException", "{", "// Get the CustomTargetingService.", "CustomTargetingServiceInterface", "customTargetingService", "=", "adManagerSe...
Runs the example. @param adManagerServices the services factory. @param session the session. @throws ApiException if the API request failed with one or more service errors. @throws RemoteException if the API request failed due to other errors.
[ "Runs", "the", "example", "." ]
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/admanager_axis/src/main/java/admanager/axis/v201902/customtargetingservice/GetAllCustomTargetingKeysAndValues.java#L56-L108
marvec/encryptor
encryptor-util/src/main/java/org/marvec/encryptor/util/EncryptionUtil.java
EncryptionUtil.getPemPublicKey
private PublicKey getPemPublicKey(final String keyString) throws EncryptionException { try { final String publicKeyPEM = keyString.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "").replaceAll("\\v", ""); final Base64 b64 = new Base64(); final byte[] decoded = b64.decode(publicKeyPEM); final X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded); final KeyFactory kf = KeyFactory.getInstance(ALGORITHM); return kf.generatePublic(spec); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new EncryptionException("Unable to obtain public key: ", e); } }
java
private PublicKey getPemPublicKey(final String keyString) throws EncryptionException { try { final String publicKeyPEM = keyString.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "").replaceAll("\\v", ""); final Base64 b64 = new Base64(); final byte[] decoded = b64.decode(publicKeyPEM); final X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded); final KeyFactory kf = KeyFactory.getInstance(ALGORITHM); return kf.generatePublic(spec); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new EncryptionException("Unable to obtain public key: ", e); } }
[ "private", "PublicKey", "getPemPublicKey", "(", "final", "String", "keyString", ")", "throws", "EncryptionException", "{", "try", "{", "final", "String", "publicKeyPEM", "=", "keyString", ".", "replace", "(", "\"-----BEGIN PUBLIC KEY-----\"", ",", "\"\"", ")", ".", ...
Initializes a public key from a string. @param keyString String representation of the key. @return An initialized public key. @throws EncryptionException When it was not possible to initialize the key.
[ "Initializes", "a", "public", "key", "from", "a", "string", "." ]
train
https://github.com/marvec/encryptor/blob/a3fd82fd98ee5aeec4116b66ae3320f724cc6097/encryptor-util/src/main/java/org/marvec/encryptor/util/EncryptionUtil.java#L164-L178
ddf-project/DDF
spark/src/main/java/io/ddf/spark/SparkDDFManager.java
SparkDDFManager.createSparkContext
private SparkContext createSparkContext(Map<String, String> params) throws DDFException { this.setSparkContextParams(this.mergeSparkParamsFromSettings(params)); String ddfSparkJar = params.get("DDFSPARK_JAR"); String[] jobJars = ddfSparkJar != null ? ddfSparkJar.split(",") : new String[] { }; ArrayList<String> finalJobJars = new ArrayList<String>(); // DDFSPARK_JAR could contain directories too, used in case of Databricks Cloud where we don't have the jars at start-up // time but the directory and we will search and includes all of jars at run-time for (String jobJar: jobJars) { if ((!jobJar.endsWith(".jar")) && (new File(jobJar).list() != null)) { // This is a directory ArrayList<String> jars = Utils.listJars(jobJar); if (jars != null) { finalJobJars.addAll(jars); } } else { finalJobJars.add(jobJar); } } mLog.info(">>>>> ddfSparkJar = " + ddfSparkJar); for(String jar: finalJobJars) { mLog.info(">>>>> " + jar); } jobJars = new String[finalJobJars.size()]; jobJars = finalJobJars.toArray(jobJars); for (String key : params.keySet()) { mLog.info(">>>> key = " + key + ", value = " + params.get(key)); } SparkContext context = SparkUtils.createSparkContext(params.get("SPARK_MASTER"), params.get("SPARK_APPNAME"), params.get("SPARK_HOME"), jobJars, params); this.mSparkContext = context; this.mJavaSparkContext = new JavaSparkContext(context); return this.getSparkContext(); }
java
private SparkContext createSparkContext(Map<String, String> params) throws DDFException { this.setSparkContextParams(this.mergeSparkParamsFromSettings(params)); String ddfSparkJar = params.get("DDFSPARK_JAR"); String[] jobJars = ddfSparkJar != null ? ddfSparkJar.split(",") : new String[] { }; ArrayList<String> finalJobJars = new ArrayList<String>(); // DDFSPARK_JAR could contain directories too, used in case of Databricks Cloud where we don't have the jars at start-up // time but the directory and we will search and includes all of jars at run-time for (String jobJar: jobJars) { if ((!jobJar.endsWith(".jar")) && (new File(jobJar).list() != null)) { // This is a directory ArrayList<String> jars = Utils.listJars(jobJar); if (jars != null) { finalJobJars.addAll(jars); } } else { finalJobJars.add(jobJar); } } mLog.info(">>>>> ddfSparkJar = " + ddfSparkJar); for(String jar: finalJobJars) { mLog.info(">>>>> " + jar); } jobJars = new String[finalJobJars.size()]; jobJars = finalJobJars.toArray(jobJars); for (String key : params.keySet()) { mLog.info(">>>> key = " + key + ", value = " + params.get(key)); } SparkContext context = SparkUtils.createSparkContext(params.get("SPARK_MASTER"), params.get("SPARK_APPNAME"), params.get("SPARK_HOME"), jobJars, params); this.mSparkContext = context; this.mJavaSparkContext = new JavaSparkContext(context); return this.getSparkContext(); }
[ "private", "SparkContext", "createSparkContext", "(", "Map", "<", "String", ",", "String", ">", "params", ")", "throws", "DDFException", "{", "this", ".", "setSparkContextParams", "(", "this", ".", "mergeSparkParamsFromSettings", "(", "params", ")", ")", ";", "S...
Side effect: also sets SharkContext and SparkContextParams in case the client wants to examine or use those. @param params @return @throws DDFException
[ "Side", "effect", ":", "also", "sets", "SharkContext", "and", "SparkContextParams", "in", "case", "the", "client", "wants", "to", "examine", "or", "use", "those", "." ]
train
https://github.com/ddf-project/DDF/blob/e4e68315dcec1ed8b287bf1ee73baa88e7e41eba/spark/src/main/java/io/ddf/spark/SparkDDFManager.java#L166-L206
apache/spark
sql/hive-thriftserver/src/main/java/org/apache/hive/service/cli/operation/SQLOperation.java
SQLOperation.getConfigForOperation
private HiveConf getConfigForOperation() throws HiveSQLException { HiveConf sqlOperationConf = getParentSession().getHiveConf(); if (!getConfOverlay().isEmpty() || shouldRunAsync()) { // clone the parent session config for this query sqlOperationConf = new HiveConf(sqlOperationConf); // apply overlay query specific settings, if any for (Map.Entry<String, String> confEntry : getConfOverlay().entrySet()) { try { sqlOperationConf.verifyAndSet(confEntry.getKey(), confEntry.getValue()); } catch (IllegalArgumentException e) { throw new HiveSQLException("Error applying statement specific settings", e); } } } return sqlOperationConf; }
java
private HiveConf getConfigForOperation() throws HiveSQLException { HiveConf sqlOperationConf = getParentSession().getHiveConf(); if (!getConfOverlay().isEmpty() || shouldRunAsync()) { // clone the parent session config for this query sqlOperationConf = new HiveConf(sqlOperationConf); // apply overlay query specific settings, if any for (Map.Entry<String, String> confEntry : getConfOverlay().entrySet()) { try { sqlOperationConf.verifyAndSet(confEntry.getKey(), confEntry.getValue()); } catch (IllegalArgumentException e) { throw new HiveSQLException("Error applying statement specific settings", e); } } } return sqlOperationConf; }
[ "private", "HiveConf", "getConfigForOperation", "(", ")", "throws", "HiveSQLException", "{", "HiveConf", "sqlOperationConf", "=", "getParentSession", "(", ")", ".", "getHiveConf", "(", ")", ";", "if", "(", "!", "getConfOverlay", "(", ")", ".", "isEmpty", "(", ...
If there are query specific settings to overlay, then create a copy of config There are two cases we need to clone the session config that's being passed to hive driver 1. Async query - If the client changes a config setting, that shouldn't reflect in the execution already underway 2. confOverlay - The query specific settings should only be applied to the query config and not session @return new configuration @throws HiveSQLException
[ "If", "there", "are", "query", "specific", "settings", "to", "overlay", "then", "create", "a", "copy", "of", "config", "There", "are", "two", "cases", "we", "need", "to", "clone", "the", "session", "config", "that", "s", "being", "passed", "to", "hive", ...
train
https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/sql/hive-thriftserver/src/main/java/org/apache/hive/service/cli/operation/SQLOperation.java#L443-L459
carewebframework/carewebframework-core
org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/util/TreeUtil.java
TreeUtil.getPath
public static String getPath(Treenode item, boolean useLabels) { StringBuilder sb = new StringBuilder(); boolean needsDelim = false; while (item != null) { if (needsDelim) { sb.insert(0, '\\'); } else { needsDelim = true; } sb.insert(0, useLabels ? item.getLabel() : item.getIndex()); item = (Treenode) item.getParent(); } return sb.toString(); }
java
public static String getPath(Treenode item, boolean useLabels) { StringBuilder sb = new StringBuilder(); boolean needsDelim = false; while (item != null) { if (needsDelim) { sb.insert(0, '\\'); } else { needsDelim = true; } sb.insert(0, useLabels ? item.getLabel() : item.getIndex()); item = (Treenode) item.getParent(); } return sb.toString(); }
[ "public", "static", "String", "getPath", "(", "Treenode", "item", ",", "boolean", "useLabels", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "boolean", "needsDelim", "=", "false", ";", "while", "(", "item", "!=", "null", ")",...
Returns the path of the specified tree node. This consists of the indexes or labels of this and all parent nodes separated by a "\" character. @param item The node (tree item) whose path is to be returned. If this value is null, a zero length string is returned. @param useLabels If true, use the labels as identifiers; otherwise, use indexes. @return The path of the node as described.
[ "Returns", "the", "path", "of", "the", "specified", "tree", "node", ".", "This", "consists", "of", "the", "indexes", "or", "labels", "of", "this", "and", "all", "parent", "nodes", "separated", "by", "a", "\\", "character", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/util/TreeUtil.java#L191-L207
apereo/cas
support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/support/oauth/util/OAuth20Utils.java
OAuth20Utils.isResponseModeTypeFormPost
public static boolean isResponseModeTypeFormPost(final OAuthRegisteredService registeredService, final OAuth20ResponseModeTypes responseType) { return responseType == OAuth20ResponseModeTypes.FORM_POST || StringUtils.equalsIgnoreCase("post", registeredService.getResponseType()); }
java
public static boolean isResponseModeTypeFormPost(final OAuthRegisteredService registeredService, final OAuth20ResponseModeTypes responseType) { return responseType == OAuth20ResponseModeTypes.FORM_POST || StringUtils.equalsIgnoreCase("post", registeredService.getResponseType()); }
[ "public", "static", "boolean", "isResponseModeTypeFormPost", "(", "final", "OAuthRegisteredService", "registeredService", ",", "final", "OAuth20ResponseModeTypes", "responseType", ")", "{", "return", "responseType", "==", "OAuth20ResponseModeTypes", ".", "FORM_POST", "||", ...
Is response mode type form post? @param registeredService the registered service @param responseType the response type @return the boolean
[ "Is", "response", "mode", "type", "form", "post?" ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/support/oauth/util/OAuth20Utils.java#L196-L198
lievendoclo/Valkyrie-RCP
valkyrie-rcp-core/src/main/java/org/valkyriercp/command/support/LazyGroupMember.java
LazyGroupMember.loadIfNecessary
private void loadIfNecessary() { if (loadedMember != null) { return; } CommandRegistry commandRegistry = parentGroup.getCommandRegistry(); Assert.isTrue(parentGroup.getCommandRegistry() != null, "Command registry must be set for group '" + parentGroup.getId() + "' in order to load lazy command '" + lazyCommandId + "'."); if (commandRegistry.containsCommandGroup(lazyCommandId)) { CommandGroup group = commandRegistry.getCommandGroup(lazyCommandId); loadedMember = new SimpleGroupMember(parentGroup, group); } else if (commandRegistry.containsActionCommand(lazyCommandId)) { ActionCommand command = commandRegistry.getActionCommand(lazyCommandId); loadedMember = new SimpleGroupMember(parentGroup, command); } else { if (logger.isWarnEnabled()) { logger.warn("Lazy command '" + lazyCommandId + "' was asked to display; however, no backing command instance exists in registry."); } } if (addedLazily && loadedMember != null) { loadedMember.onAdded(); } }
java
private void loadIfNecessary() { if (loadedMember != null) { return; } CommandRegistry commandRegistry = parentGroup.getCommandRegistry(); Assert.isTrue(parentGroup.getCommandRegistry() != null, "Command registry must be set for group '" + parentGroup.getId() + "' in order to load lazy command '" + lazyCommandId + "'."); if (commandRegistry.containsCommandGroup(lazyCommandId)) { CommandGroup group = commandRegistry.getCommandGroup(lazyCommandId); loadedMember = new SimpleGroupMember(parentGroup, group); } else if (commandRegistry.containsActionCommand(lazyCommandId)) { ActionCommand command = commandRegistry.getActionCommand(lazyCommandId); loadedMember = new SimpleGroupMember(parentGroup, command); } else { if (logger.isWarnEnabled()) { logger.warn("Lazy command '" + lazyCommandId + "' was asked to display; however, no backing command instance exists in registry."); } } if (addedLazily && loadedMember != null) { loadedMember.onAdded(); } }
[ "private", "void", "loadIfNecessary", "(", ")", "{", "if", "(", "loadedMember", "!=", "null", ")", "{", "return", ";", "}", "CommandRegistry", "commandRegistry", "=", "parentGroup", ".", "getCommandRegistry", "(", ")", ";", "Assert", ".", "isTrue", "(", "par...
Attempts to load the lazy command from the command registry of the parent command group, but only if it hasn't already been loaded.
[ "Attempts", "to", "load", "the", "lazy", "command", "from", "the", "command", "registry", "of", "the", "parent", "command", "group", "but", "only", "if", "it", "hasn", "t", "already", "been", "loaded", "." ]
train
https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/command/support/LazyGroupMember.java#L93-L126
davidmoten/rxjava-jdbc
src/main/java/com/github/davidmoten/rx/RxUtil.java
RxUtil.getAndAddRequest
public static <T> long getAndAddRequest(AtomicLongFieldUpdater<T> requested, T object, long n) { // add n to field but check for overflow while (true) { long current = requested.get(object); long next = current + n; // check for overflow if (next < 0) { next = Long.MAX_VALUE; } if (requested.compareAndSet(object, current, next)) { return current; } } }
java
public static <T> long getAndAddRequest(AtomicLongFieldUpdater<T> requested, T object, long n) { // add n to field but check for overflow while (true) { long current = requested.get(object); long next = current + n; // check for overflow if (next < 0) { next = Long.MAX_VALUE; } if (requested.compareAndSet(object, current, next)) { return current; } } }
[ "public", "static", "<", "T", ">", "long", "getAndAddRequest", "(", "AtomicLongFieldUpdater", "<", "T", ">", "requested", ",", "T", "object", ",", "long", "n", ")", "{", "// add n to field but check for overflow", "while", "(", "true", ")", "{", "long", "curre...
Adds {@code n} to {@code requested} field and returns the value prior to addition once the addition is successful (uses CAS semantics). If overflows then sets {@code requested} field to {@code Long.MAX_VALUE}. @param requested atomic field updater for a request count @param object contains the field updated by the updater @param n the number of requests to add to the requested count @return requested value just prior to successful addition
[ "Adds", "{", "@code", "n", "}", "to", "{", "@code", "requested", "}", "field", "and", "returns", "the", "value", "prior", "to", "addition", "once", "the", "addition", "is", "successful", "(", "uses", "CAS", "semantics", ")", ".", "If", "overflows", "then...
train
https://github.com/davidmoten/rxjava-jdbc/blob/81e157d7071a825086bde81107b8694684cdff14/src/main/java/com/github/davidmoten/rx/RxUtil.java#L159-L172
wildfly/wildfly-core
patching/src/main/java/org/jboss/as/patching/metadata/ModificationBuilderTarget.java
ModificationBuilderTarget.modifyBundle
public T modifyBundle(final String moduleName, final String slot, final byte[] existingHash, final byte[] newHash) { final ContentItem item = createBundleItem(moduleName, slot, newHash); addContentModification(createContentModification(item, ModificationType.MODIFY, existingHash)); return returnThis(); }
java
public T modifyBundle(final String moduleName, final String slot, final byte[] existingHash, final byte[] newHash) { final ContentItem item = createBundleItem(moduleName, slot, newHash); addContentModification(createContentModification(item, ModificationType.MODIFY, existingHash)); return returnThis(); }
[ "public", "T", "modifyBundle", "(", "final", "String", "moduleName", ",", "final", "String", "slot", ",", "final", "byte", "[", "]", "existingHash", ",", "final", "byte", "[", "]", "newHash", ")", "{", "final", "ContentItem", "item", "=", "createBundleItem",...
Modify a bundle. @param moduleName the module name @param slot the module slot @param existingHash the existing hash @param newHash the new hash of the modified content @return the builder
[ "Modify", "a", "bundle", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/patching/src/main/java/org/jboss/as/patching/metadata/ModificationBuilderTarget.java#L87-L91
goldmansachs/gs-collections
collections/src/main/java/com/gs/collections/impl/parallel/ParallelMapIterate.java
ParallelMapIterate.forEachKeyValue
public static <K, V> void forEachKeyValue(Map<K, V> map, Procedure2<? super K, ? super V> procedure2) { ParallelMapIterate.forEachKeyValue(map, procedure2, 2, map.size()); }
java
public static <K, V> void forEachKeyValue(Map<K, V> map, Procedure2<? super K, ? super V> procedure2) { ParallelMapIterate.forEachKeyValue(map, procedure2, 2, map.size()); }
[ "public", "static", "<", "K", ",", "V", ">", "void", "forEachKeyValue", "(", "Map", "<", "K", ",", "V", ">", "map", ",", "Procedure2", "<", "?", "super", "K", ",", "?", "super", "V", ">", "procedure2", ")", "{", "ParallelMapIterate", ".", "forEachKey...
A parallel form of forEachKeyValue. @see MapIterate#forEachKeyValue(Map, Procedure2) @see ParallelIterate
[ "A", "parallel", "form", "of", "forEachKeyValue", "." ]
train
https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/parallel/ParallelMapIterate.java#L48-L51
bbottema/simple-java-mail
modules/simple-java-mail/src/main/java/org/simplejavamail/converter/internal/mimemessage/MimeMessageHelper.java
MimeMessageHelper.getBodyPartFromDatasource
private static BodyPart getBodyPartFromDatasource(final AttachmentResource attachmentResource, final String dispositionType) throws MessagingException { final BodyPart attachmentPart = new MimeBodyPart(); // setting headers isn't working nicely using the javax mail API, so let's do that manually final String resourceName = determineResourceName(attachmentResource, false); final String fileName = determineResourceName(attachmentResource, true); attachmentPart.setDataHandler(new DataHandler(new NamedDataSource(fileName, attachmentResource.getDataSource()))); attachmentPart.setFileName(fileName); final String contentType = attachmentResource.getDataSource().getContentType(); attachmentPart.setHeader("Content-Type", contentType + "; filename=" + fileName + "; name=" + resourceName); attachmentPart.setHeader("Content-ID", format("<%s>", resourceName)); attachmentPart.setDisposition(dispositionType); return attachmentPart; }
java
private static BodyPart getBodyPartFromDatasource(final AttachmentResource attachmentResource, final String dispositionType) throws MessagingException { final BodyPart attachmentPart = new MimeBodyPart(); // setting headers isn't working nicely using the javax mail API, so let's do that manually final String resourceName = determineResourceName(attachmentResource, false); final String fileName = determineResourceName(attachmentResource, true); attachmentPart.setDataHandler(new DataHandler(new NamedDataSource(fileName, attachmentResource.getDataSource()))); attachmentPart.setFileName(fileName); final String contentType = attachmentResource.getDataSource().getContentType(); attachmentPart.setHeader("Content-Type", contentType + "; filename=" + fileName + "; name=" + resourceName); attachmentPart.setHeader("Content-ID", format("<%s>", resourceName)); attachmentPart.setDisposition(dispositionType); return attachmentPart; }
[ "private", "static", "BodyPart", "getBodyPartFromDatasource", "(", "final", "AttachmentResource", "attachmentResource", ",", "final", "String", "dispositionType", ")", "throws", "MessagingException", "{", "final", "BodyPart", "attachmentPart", "=", "new", "MimeBodyPart", ...
Helper method which generates a {@link BodyPart} from an {@link AttachmentResource} (from its {@link DataSource}) and a disposition type ({@link Part#INLINE} or {@link Part#ATTACHMENT}). With this the attachment data can be converted into objects that fit in the email structure. <p> For every attachment and embedded image a header needs to be set. @param attachmentResource An object that describes the attachment and contains the actual content data. @param dispositionType The type of attachment, {@link Part#INLINE} or {@link Part#ATTACHMENT} . @return An object with the attachment data read for placement in the email structure. @throws MessagingException All BodyPart setters.
[ "Helper", "method", "which", "generates", "a", "{", "@link", "BodyPart", "}", "from", "an", "{", "@link", "AttachmentResource", "}", "(", "from", "its", "{", "@link", "DataSource", "}", ")", "and", "a", "disposition", "type", "(", "{", "@link", "Part#INLIN...
train
https://github.com/bbottema/simple-java-mail/blob/b03635328aeecd525e35eddfef8f5b9a184559d8/modules/simple-java-mail/src/main/java/org/simplejavamail/converter/internal/mimemessage/MimeMessageHelper.java#L228-L241
gsi-upm/Shanks
shanks-core/src/main/java/es/upm/dit/gsi/shanks/agent/capability/movement/Location.java
Location.isNearTo
public boolean isNearTo(Double2D location, double distance) { if (this.is2DLocation()) { return this.getLocation2D().distance(location) < distance; } else { return false; } }
java
public boolean isNearTo(Double2D location, double distance) { if (this.is2DLocation()) { return this.getLocation2D().distance(location) < distance; } else { return false; } }
[ "public", "boolean", "isNearTo", "(", "Double2D", "location", ",", "double", "distance", ")", "{", "if", "(", "this", ".", "is2DLocation", "(", ")", ")", "{", "return", "this", ".", "getLocation2D", "(", ")", ".", "distance", "(", "location", ")", "<", ...
Compare two locations and return if the locations are near or not @param location Location to compare with @param distance The distance between two locations @return true is the real distance is lower or equals than the distance parameter
[ "Compare", "two", "locations", "and", "return", "if", "the", "locations", "are", "near", "or", "not" ]
train
https://github.com/gsi-upm/Shanks/blob/35d87a81c22731f4f83bbd0571c9c6d466bd16be/shanks-core/src/main/java/es/upm/dit/gsi/shanks/agent/capability/movement/Location.java#L153-L159
facebook/fresco
imagepipeline-base/src/main/java/com/facebook/imageutils/TiffUtil.java
TiffUtil.readTiffHeader
private static int readTiffHeader(InputStream is, int length, TiffHeader tiffHeader) throws IOException { if (length <= 8) { return 0; } // read the byte order tiffHeader.byteOrder = StreamProcessor.readPackedInt(is, 4, false); length -= 4; if (tiffHeader.byteOrder != TIFF_BYTE_ORDER_LITTLE_END && tiffHeader.byteOrder != TIFF_BYTE_ORDER_BIG_END) { FLog.e(TAG, "Invalid TIFF header"); return 0; } tiffHeader.isLittleEndian = (tiffHeader.byteOrder == TIFF_BYTE_ORDER_LITTLE_END); // read the offset of the first IFD and check if it is reasonable tiffHeader.firstIfdOffset = StreamProcessor.readPackedInt(is, 4, tiffHeader.isLittleEndian); length -= 4; if (tiffHeader.firstIfdOffset < 8 || tiffHeader.firstIfdOffset - 8 > length) { FLog.e(TAG, "Invalid offset"); return 0; } return length; }
java
private static int readTiffHeader(InputStream is, int length, TiffHeader tiffHeader) throws IOException { if (length <= 8) { return 0; } // read the byte order tiffHeader.byteOrder = StreamProcessor.readPackedInt(is, 4, false); length -= 4; if (tiffHeader.byteOrder != TIFF_BYTE_ORDER_LITTLE_END && tiffHeader.byteOrder != TIFF_BYTE_ORDER_BIG_END) { FLog.e(TAG, "Invalid TIFF header"); return 0; } tiffHeader.isLittleEndian = (tiffHeader.byteOrder == TIFF_BYTE_ORDER_LITTLE_END); // read the offset of the first IFD and check if it is reasonable tiffHeader.firstIfdOffset = StreamProcessor.readPackedInt(is, 4, tiffHeader.isLittleEndian); length -= 4; if (tiffHeader.firstIfdOffset < 8 || tiffHeader.firstIfdOffset - 8 > length) { FLog.e(TAG, "Invalid offset"); return 0; } return length; }
[ "private", "static", "int", "readTiffHeader", "(", "InputStream", "is", ",", "int", "length", ",", "TiffHeader", "tiffHeader", ")", "throws", "IOException", "{", "if", "(", "length", "<=", "8", ")", "{", "return", "0", ";", "}", "// read the byte order", "ti...
Reads the TIFF header to the provided structure. @param is the input stream of TIFF data @param length length of the TIFF data @return remaining length of the data on success, 0 on failure @throws IOException
[ "Reads", "the", "TIFF", "header", "to", "the", "provided", "structure", "." ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imageutils/TiffUtil.java#L92-L117
infinispan/infinispan
core/src/main/java/org/infinispan/factories/components/ComponentMetadataRepo.java
ComponentMetadataRepo.injectFactoryForComponent
@Deprecated public void injectFactoryForComponent(Class<?> componentType, Class<?> factoryType) { factories.put(componentType.getName(), factoryType.getName()); }
java
@Deprecated public void injectFactoryForComponent(Class<?> componentType, Class<?> factoryType) { factories.put(componentType.getName(), factoryType.getName()); }
[ "@", "Deprecated", "public", "void", "injectFactoryForComponent", "(", "Class", "<", "?", ">", "componentType", ",", "Class", "<", "?", ">", "factoryType", ")", "{", "factories", ".", "put", "(", "componentType", ".", "getName", "(", ")", ",", "factoryType",...
Inject a factory for a given component type. @param componentType Component type that the factory will produce @param factoryType Factory that produces the given type of components @deprecated For testing purposes only.
[ "Inject", "a", "factory", "for", "a", "given", "component", "type", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/factories/components/ComponentMetadataRepo.java#L195-L198
Stratio/cassandra-lucene-index
plugin/src/main/java/com/stratio/cassandra/lucene/schema/SchemaAnalyzer.java
SchemaAnalyzer.getAnalyzer
protected static Analyzer getAnalyzer(Map<String, Analyzer> analyzers, String name) { if (StringUtils.isBlank(name)) { throw new IndexException("Not empty analyzer name required"); } Analyzer analyzer = analyzers.get(name); if (analyzer == null) { analyzer = StandardAnalyzers.get(name); if (analyzer == null) { try { analyzer = (new ClasspathAnalyzerBuilder(name)).analyzer(); } catch (Exception e) { throw new IndexException(e, "Not found analyzer '{}'", name); } } } return analyzer; }
java
protected static Analyzer getAnalyzer(Map<String, Analyzer> analyzers, String name) { if (StringUtils.isBlank(name)) { throw new IndexException("Not empty analyzer name required"); } Analyzer analyzer = analyzers.get(name); if (analyzer == null) { analyzer = StandardAnalyzers.get(name); if (analyzer == null) { try { analyzer = (new ClasspathAnalyzerBuilder(name)).analyzer(); } catch (Exception e) { throw new IndexException(e, "Not found analyzer '{}'", name); } } } return analyzer; }
[ "protected", "static", "Analyzer", "getAnalyzer", "(", "Map", "<", "String", ",", "Analyzer", ">", "analyzers", ",", "String", "name", ")", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "name", ")", ")", "{", "throw", "new", "IndexException", "(", ...
Returns the {@link Analyzer} identified by the specified name. If there is no analyzer with the specified name, then it will be interpreted as a class name and it will be instantiated by reflection. @param analyzers the per field analyzers to be used @param name the name of the {@link Analyzer} to be returned @return the analyzer identified by the specified name
[ "Returns", "the", "{", "@link", "Analyzer", "}", "identified", "by", "the", "specified", "name", ".", "If", "there", "is", "no", "analyzer", "with", "the", "specified", "name", "then", "it", "will", "be", "interpreted", "as", "a", "class", "name", "and", ...
train
https://github.com/Stratio/cassandra-lucene-index/blob/a94a4d9af6c25d40e1108729974c35c27c54441c/plugin/src/main/java/com/stratio/cassandra/lucene/schema/SchemaAnalyzer.java#L73-L89
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/javadoc/RootDocImpl.java
RootDocImpl.setPackages
private void setPackages(DocEnv env, List<String> packages) { ListBuffer<PackageDocImpl> packlist = new ListBuffer<PackageDocImpl>(); for (String name : packages) { PackageDocImpl pkg = env.lookupPackage(name); if (pkg != null) { pkg.isIncluded = true; packlist.append(pkg); } else { env.warning(null, "main.no_source_files_for_package", name); } } cmdLinePackages = packlist.toList(); }
java
private void setPackages(DocEnv env, List<String> packages) { ListBuffer<PackageDocImpl> packlist = new ListBuffer<PackageDocImpl>(); for (String name : packages) { PackageDocImpl pkg = env.lookupPackage(name); if (pkg != null) { pkg.isIncluded = true; packlist.append(pkg); } else { env.warning(null, "main.no_source_files_for_package", name); } } cmdLinePackages = packlist.toList(); }
[ "private", "void", "setPackages", "(", "DocEnv", "env", ",", "List", "<", "String", ">", "packages", ")", "{", "ListBuffer", "<", "PackageDocImpl", ">", "packlist", "=", "new", "ListBuffer", "<", "PackageDocImpl", ">", "(", ")", ";", "for", "(", "String", ...
Initialize packages information. @param env the compilation environment @param packages a list of package names (String)
[ "Initialize", "packages", "information", "." ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javadoc/RootDocImpl.java#L139-L151
infinispan/infinispan
core/src/main/java/org/infinispan/factories/AbstractComponentRegistry.java
AbstractComponentRegistry.getOrCreateComponent
protected <T> T getOrCreateComponent(Class<T> componentClass) { return getComponent(componentClass, componentClass.getName()); }
java
protected <T> T getOrCreateComponent(Class<T> componentClass) { return getComponent(componentClass, componentClass.getName()); }
[ "protected", "<", "T", ">", "T", "getOrCreateComponent", "(", "Class", "<", "T", ">", "componentClass", ")", "{", "return", "getComponent", "(", "componentClass", ",", "componentClass", ".", "getName", "(", ")", ")", ";", "}" ]
Retrieves a component if one exists, and if not, attempts to find a factory capable of constructing the component (factories annotated with the {@link DefaultFactoryFor} annotation that is capable of creating the component class). <p/> If an instance needs to be constructed, dependencies are then automatically wired into the instance, based on methods on the component type annotated with {@link Inject}. <p/> Summing it up, component retrieval happens in the following order:<br /> 1. Look for a component that has already been created and registered. 2. Look for an appropriate component that exists in the {@link Configuration} that may be injected from an external system. 3. Look for a class definition passed in to the {@link Configuration} - such as an EvictionPolicy implementation 4. Attempt to create it by looking for an appropriate factory (annotated with {@link DefaultFactoryFor}) <p/> @param componentClass type of component to be retrieved. Should not be null. @return a fully wired component instance, or null if one cannot be found or constructed. @throws CacheConfigurationException if there is a problem with constructing or wiring the instance.
[ "Retrieves", "a", "component", "if", "one", "exists", "and", "if", "not", "attempts", "to", "find", "a", "factory", "capable", "of", "constructing", "the", "component", "(", "factories", "annotated", "with", "the", "{", "@link", "DefaultFactoryFor", "}", "anno...
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/factories/AbstractComponentRegistry.java#L162-L164
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/f/FundamentalLinear8.java
FundamentalLinear8.process
protected boolean process(DMatrixRMaj A, DMatrixRMaj F ) { if( !solverNull.process(A,1,F) ) return true; F.numRows = 3; F.numCols = 3; return false; }
java
protected boolean process(DMatrixRMaj A, DMatrixRMaj F ) { if( !solverNull.process(A,1,F) ) return true; F.numRows = 3; F.numCols = 3; return false; }
[ "protected", "boolean", "process", "(", "DMatrixRMaj", "A", ",", "DMatrixRMaj", "F", ")", "{", "if", "(", "!", "solverNull", ".", "process", "(", "A", ",", "1", ",", "F", ")", ")", "return", "true", ";", "F", ".", "numRows", "=", "3", ";", "F", "...
Computes the SVD of A and extracts the essential/fundamental matrix from its null space
[ "Computes", "the", "SVD", "of", "A", "and", "extracts", "the", "essential", "/", "fundamental", "matrix", "from", "its", "null", "space" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/f/FundamentalLinear8.java#L94-L102
JodaOrg/joda-time
src/main/java/org/joda/time/convert/ReadablePartialConverter.java
ReadablePartialConverter.getChronology
public Chronology getChronology(Object object, DateTimeZone zone) { return getChronology(object, (Chronology) null).withZone(zone); }
java
public Chronology getChronology(Object object, DateTimeZone zone) { return getChronology(object, (Chronology) null).withZone(zone); }
[ "public", "Chronology", "getChronology", "(", "Object", "object", ",", "DateTimeZone", "zone", ")", "{", "return", "getChronology", "(", "object", ",", "(", "Chronology", ")", "null", ")", ".", "withZone", "(", "zone", ")", ";", "}" ]
Gets the chronology, which is taken from the ReadablePartial. @param object the ReadablePartial to convert, must not be null @param zone the specified zone to use, null means default zone @return the chronology, never null
[ "Gets", "the", "chronology", "which", "is", "taken", "from", "the", "ReadablePartial", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/convert/ReadablePartialConverter.java#L52-L54
VoltDB/voltdb
src/frontend/org/voltdb/importer/ChannelDistributer.java
ChannelDistributer.loggedDistributerException
static DistributerException loggedDistributerException(Throwable cause, String format, Object...args) { Optional<DistributerException> causeFor = DistributerException.isCauseFor(cause); if (causeFor.isPresent()) { return causeFor.get(); } String msg = String.format(format, args); if (cause != null) { LOG.error(msg, cause); return new DistributerException(msg, cause); } else { LOG.error(msg); return new DistributerException(msg); } }
java
static DistributerException loggedDistributerException(Throwable cause, String format, Object...args) { Optional<DistributerException> causeFor = DistributerException.isCauseFor(cause); if (causeFor.isPresent()) { return causeFor.get(); } String msg = String.format(format, args); if (cause != null) { LOG.error(msg, cause); return new DistributerException(msg, cause); } else { LOG.error(msg); return new DistributerException(msg); } }
[ "static", "DistributerException", "loggedDistributerException", "(", "Throwable", "cause", ",", "String", "format", ",", "Object", "...", "args", ")", "{", "Optional", "<", "DistributerException", ">", "causeFor", "=", "DistributerException", ".", "isCauseFor", "(", ...
Boiler plate method to log an error message and wrap, and return a {@link DistributerException} around the message and cause @param cause fault origin {@link Throwable} @param format a {@link String#format(String, Object...) compliant format string @param args formatter arguments @return a {@link DistributerException}
[ "Boiler", "plate", "method", "to", "log", "an", "error", "message", "and", "wrap", "and", "return", "a", "{", "@link", "DistributerException", "}", "around", "the", "message", "and", "cause" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/importer/ChannelDistributer.java#L129-L142
Azure/azure-sdk-for-java
network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java
NetworkWatchersInner.beginGetFlowLogStatusAsync
public Observable<FlowLogInformationInner> beginGetFlowLogStatusAsync(String resourceGroupName, String networkWatcherName, String targetResourceId) { return beginGetFlowLogStatusWithServiceResponseAsync(resourceGroupName, networkWatcherName, targetResourceId).map(new Func1<ServiceResponse<FlowLogInformationInner>, FlowLogInformationInner>() { @Override public FlowLogInformationInner call(ServiceResponse<FlowLogInformationInner> response) { return response.body(); } }); }
java
public Observable<FlowLogInformationInner> beginGetFlowLogStatusAsync(String resourceGroupName, String networkWatcherName, String targetResourceId) { return beginGetFlowLogStatusWithServiceResponseAsync(resourceGroupName, networkWatcherName, targetResourceId).map(new Func1<ServiceResponse<FlowLogInformationInner>, FlowLogInformationInner>() { @Override public FlowLogInformationInner call(ServiceResponse<FlowLogInformationInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "FlowLogInformationInner", ">", "beginGetFlowLogStatusAsync", "(", "String", "resourceGroupName", ",", "String", "networkWatcherName", ",", "String", "targetResourceId", ")", "{", "return", "beginGetFlowLogStatusWithServiceResponseAsync", "(", "re...
Queries status of flow log on a specified resource. @param resourceGroupName The name of the network watcher resource group. @param networkWatcherName The name of the network watcher resource. @param targetResourceId The target resource where getting the flow logging status. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the FlowLogInformationInner object
[ "Queries", "status", "of", "flow", "log", "on", "a", "specified", "resource", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java#L2073-L2080
graphhopper/graphhopper
core/src/main/java/com/graphhopper/util/GHUtility.java
GHUtility.getEdgeKey
public static int getEdgeKey(Graph graph, int edgeId, int node, boolean reverse) { EdgeIteratorState edgeIteratorState = graph.getEdgeIteratorState(edgeId, node); return GHUtility.createEdgeKey(edgeIteratorState.getBaseNode(), edgeIteratorState.getAdjNode(), edgeId, reverse); }
java
public static int getEdgeKey(Graph graph, int edgeId, int node, boolean reverse) { EdgeIteratorState edgeIteratorState = graph.getEdgeIteratorState(edgeId, node); return GHUtility.createEdgeKey(edgeIteratorState.getBaseNode(), edgeIteratorState.getAdjNode(), edgeId, reverse); }
[ "public", "static", "int", "getEdgeKey", "(", "Graph", "graph", ",", "int", "edgeId", ",", "int", "node", ",", "boolean", "reverse", ")", "{", "EdgeIteratorState", "edgeIteratorState", "=", "graph", ".", "getEdgeIteratorState", "(", "edgeId", ",", "node", ")",...
Returns the edge key for a given edge id and adjacent node. This is needed in a few places where the base node is not known.
[ "Returns", "the", "edge", "key", "for", "a", "given", "edge", "id", "and", "adjacent", "node", ".", "This", "is", "needed", "in", "a", "few", "places", "where", "the", "base", "node", "is", "not", "known", "." ]
train
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/GHUtility.java#L498-L501
jferard/fastods
fastods/src/main/java/com/github/jferard/fastods/NamedOdsDocument.java
NamedOdsDocument.addChildCellStyle
public void addChildCellStyle(final TableCellStyle style, final TableCell.Type type) { this.odsElements.addChildCellStyle(style, type); }
java
public void addChildCellStyle(final TableCellStyle style, final TableCell.Type type) { this.odsElements.addChildCellStyle(style, type); }
[ "public", "void", "addChildCellStyle", "(", "final", "TableCellStyle", "style", ",", "final", "TableCell", ".", "Type", "type", ")", "{", "this", ".", "odsElements", ".", "addChildCellStyle", "(", "style", ",", "type", ")", ";", "}" ]
Add a cell style for a given data type. Use only if you want to flush data before the end of the document construction. Do not produce any effect if the type is Type.STRING or Type.VOID @param style the style @param type the data type
[ "Add", "a", "cell", "style", "for", "a", "given", "data", "type", ".", "Use", "only", "if", "you", "want", "to", "flush", "data", "before", "the", "end", "of", "the", "document", "construction", ".", "Do", "not", "produce", "any", "effect", "if", "the"...
train
https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/NamedOdsDocument.java#L168-L170
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/modules/r/morpher/Thin.java
Thin.processSkeleton
public void processSkeleton( BinaryFast binary, int[][] kernel ) { int oldForeEdge = 0; int oldBackEdge = 0; while( !(binary.getForegroundEdgePixels().size() == oldForeEdge && binary.getBackgroundEdgePixels().size() == oldBackEdge) ) { oldForeEdge = binary.getForegroundEdgePixels().size(); oldBackEdge = binary.getBackgroundEdgePixels().size(); for( int i = 0; i < kernel.length; ++i ) { binary = thinBinaryRep(binary, kernel[i]); binary.generateBackgroundEdgeFromForegroundEdge(); } } }
java
public void processSkeleton( BinaryFast binary, int[][] kernel ) { int oldForeEdge = 0; int oldBackEdge = 0; while( !(binary.getForegroundEdgePixels().size() == oldForeEdge && binary.getBackgroundEdgePixels().size() == oldBackEdge) ) { oldForeEdge = binary.getForegroundEdgePixels().size(); oldBackEdge = binary.getBackgroundEdgePixels().size(); for( int i = 0; i < kernel.length; ++i ) { binary = thinBinaryRep(binary, kernel[i]); binary.generateBackgroundEdgeFromForegroundEdge(); } } }
[ "public", "void", "processSkeleton", "(", "BinaryFast", "binary", ",", "int", "[", "]", "[", "]", "kernel", ")", "{", "int", "oldForeEdge", "=", "0", ";", "int", "oldBackEdge", "=", "0", ";", "while", "(", "!", "(", "binary", ".", "getForegroundEdgePixel...
Takes an image and a kernel and thins it the specified number of times. @param binary the BinaryFast input image. @param kernel the kernel to apply.
[ "Takes", "an", "image", "and", "a", "kernel", "and", "thins", "it", "the", "specified", "number", "of", "times", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/modules/r/morpher/Thin.java#L94-L105
citrusframework/citrus
modules/citrus-core/src/main/java/com/consol/citrus/message/ZipMessage.java
ZipMessage.addEntry
public ZipMessage addEntry(File file) { try { addEntry(new Entry(file)); } catch (IOException e) { throw new CitrusRuntimeException("Failed to read zip entry content from given file", e); } return this; }
java
public ZipMessage addEntry(File file) { try { addEntry(new Entry(file)); } catch (IOException e) { throw new CitrusRuntimeException("Failed to read zip entry content from given file", e); } return this; }
[ "public", "ZipMessage", "addEntry", "(", "File", "file", ")", "{", "try", "{", "addEntry", "(", "new", "Entry", "(", "file", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "CitrusRuntimeException", "(", "\"Failed to read zi...
Adds new zip archive entry. Entry can be a file or directory. In case of directory all files will be automatically added to the zip archive. Directory structures are retained throughout this process. @param file @return
[ "Adds", "new", "zip", "archive", "entry", ".", "Entry", "can", "be", "a", "file", "or", "directory", ".", "In", "case", "of", "directory", "all", "files", "will", "be", "automatically", "added", "to", "the", "zip", "archive", ".", "Directory", "structures"...
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/message/ZipMessage.java#L83-L90
JodaOrg/joda-time
src/main/java/org/joda/time/LocalDate.java
LocalDate.withPeriodAdded
public LocalDate withPeriodAdded(ReadablePeriod period, int scalar) { if (period == null || scalar == 0) { return this; } long instant = getLocalMillis(); Chronology chrono = getChronology(); for (int i = 0; i < period.size(); i++) { long value = FieldUtils.safeMultiply(period.getValue(i), scalar); DurationFieldType type = period.getFieldType(i); if (isSupported(type)) { instant = type.getField(chrono).add(instant, value); } } return withLocalMillis(instant); }
java
public LocalDate withPeriodAdded(ReadablePeriod period, int scalar) { if (period == null || scalar == 0) { return this; } long instant = getLocalMillis(); Chronology chrono = getChronology(); for (int i = 0; i < period.size(); i++) { long value = FieldUtils.safeMultiply(period.getValue(i), scalar); DurationFieldType type = period.getFieldType(i); if (isSupported(type)) { instant = type.getField(chrono).add(instant, value); } } return withLocalMillis(instant); }
[ "public", "LocalDate", "withPeriodAdded", "(", "ReadablePeriod", "period", ",", "int", "scalar", ")", "{", "if", "(", "period", "==", "null", "||", "scalar", "==", "0", ")", "{", "return", "this", ";", "}", "long", "instant", "=", "getLocalMillis", "(", ...
Returns a copy of this date with the specified period added. <p> If the addition is zero, then <code>this</code> is returned. <p> This method is typically used to add multiple copies of complex period instances. Adding one field is best achieved using methods like {@link #withFieldAdded(DurationFieldType, int)} or {@link #plusYears(int)}. <p> Unsupported time fields are ignored, thus adding a period of 24 hours will not have any effect. @param period the period to add to this one, null means zero @param scalar the amount of times to add, such as -1 to subtract once @return a copy of this date with the period added @throws ArithmeticException if the result exceeds the internal capacity
[ "Returns", "a", "copy", "of", "this", "date", "with", "the", "specified", "period", "added", ".", "<p", ">", "If", "the", "addition", "is", "zero", "then", "<code", ">", "this<", "/", "code", ">", "is", "returned", ".", "<p", ">", "This", "method", "...
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/LocalDate.java#L1159-L1173
groovy/groovy-core
src/main/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java
StaticInvocationWriter.tryBridgeMethod
protected boolean tryBridgeMethod(MethodNode target, Expression receiver, boolean implicitThis, TupleExpression args) { ClassNode lookupClassNode; if (target.isProtected()) { lookupClassNode = controller.getClassNode(); if (controller.isInClosure()) { lookupClassNode = lookupClassNode.getOuterClass(); } } else { lookupClassNode = target.getDeclaringClass().redirect(); } Map<MethodNode, MethodNode> bridges = lookupClassNode.getNodeMetaData(PRIVATE_BRIDGE_METHODS); MethodNode bridge = bridges==null?null:bridges.get(target); if (bridge != null) { Expression fixedReceiver = receiver; ClassNode classNode = implicitThis?controller.getClassNode():null; ClassNode declaringClass = bridge.getDeclaringClass(); if (implicitThis && !controller.isInClosure() && !classNode.isDerivedFrom(declaringClass) && !classNode.implementsInterface(declaringClass) && classNode instanceof InnerClassNode) { fixedReceiver = new PropertyExpression(new ClassExpression(classNode.getOuterClass()), "this"); } ArgumentListExpression newArgs = new ArgumentListExpression(target.isStatic()?new ConstantExpression(null):fixedReceiver); for (Expression expression : args.getExpressions()) { newArgs.addExpression(expression); } return writeDirectMethodCall(bridge, implicitThis, fixedReceiver, newArgs); } return false; }
java
protected boolean tryBridgeMethod(MethodNode target, Expression receiver, boolean implicitThis, TupleExpression args) { ClassNode lookupClassNode; if (target.isProtected()) { lookupClassNode = controller.getClassNode(); if (controller.isInClosure()) { lookupClassNode = lookupClassNode.getOuterClass(); } } else { lookupClassNode = target.getDeclaringClass().redirect(); } Map<MethodNode, MethodNode> bridges = lookupClassNode.getNodeMetaData(PRIVATE_BRIDGE_METHODS); MethodNode bridge = bridges==null?null:bridges.get(target); if (bridge != null) { Expression fixedReceiver = receiver; ClassNode classNode = implicitThis?controller.getClassNode():null; ClassNode declaringClass = bridge.getDeclaringClass(); if (implicitThis && !controller.isInClosure() && !classNode.isDerivedFrom(declaringClass) && !classNode.implementsInterface(declaringClass) && classNode instanceof InnerClassNode) { fixedReceiver = new PropertyExpression(new ClassExpression(classNode.getOuterClass()), "this"); } ArgumentListExpression newArgs = new ArgumentListExpression(target.isStatic()?new ConstantExpression(null):fixedReceiver); for (Expression expression : args.getExpressions()) { newArgs.addExpression(expression); } return writeDirectMethodCall(bridge, implicitThis, fixedReceiver, newArgs); } return false; }
[ "protected", "boolean", "tryBridgeMethod", "(", "MethodNode", "target", ",", "Expression", "receiver", ",", "boolean", "implicitThis", ",", "TupleExpression", "args", ")", "{", "ClassNode", "lookupClassNode", ";", "if", "(", "target", ".", "isProtected", "(", ")",...
Attempts to make a direct method call on a bridge method, if it exists.
[ "Attempts", "to", "make", "a", "direct", "method", "call", "on", "a", "bridge", "method", "if", "it", "exists", "." ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java#L177-L206
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Node.java
Node.getSubscriptions
public List<Subscription> getSubscriptions(List<ExtensionElement> additionalExtensions, Collection<ExtensionElement> returnedExtensions) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return getSubscriptions(SubscriptionsNamespace.basic, additionalExtensions, returnedExtensions); }
java
public List<Subscription> getSubscriptions(List<ExtensionElement> additionalExtensions, Collection<ExtensionElement> returnedExtensions) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return getSubscriptions(SubscriptionsNamespace.basic, additionalExtensions, returnedExtensions); }
[ "public", "List", "<", "Subscription", ">", "getSubscriptions", "(", "List", "<", "ExtensionElement", ">", "additionalExtensions", ",", "Collection", "<", "ExtensionElement", ">", "returnedExtensions", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ","...
Get the subscriptions currently associated with this node. <p> {@code additionalExtensions} can be used e.g. to add a "Result Set Management" extension. {@code returnedExtensions} will be filled with the stanza extensions found in the answer. </p> @param additionalExtensions @param returnedExtensions a collection that will be filled with the returned packet extensions @return List of {@link Subscription} @throws NoResponseException @throws XMPPErrorException @throws NotConnectedException @throws InterruptedException
[ "Get", "the", "subscriptions", "currently", "associated", "with", "this", "node", ".", "<p", ">", "{", "@code", "additionalExtensions", "}", "can", "be", "used", "e", ".", "g", ".", "to", "add", "a", "Result", "Set", "Management", "extension", ".", "{", ...
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Node.java#L155-L158
apereo/cas
core/cas-server-core-webflow-api/src/main/java/org/apereo/cas/web/flow/configurer/AbstractCasWebflowConfigurer.java
AbstractCasWebflowConfigurer.getState
public <T> T getState(final Flow flow, final String stateId, final Class<T> clazz) { if (containsFlowState(flow, stateId)) { val state = flow.getState(stateId); return clazz.cast(state); } return null; }
java
public <T> T getState(final Flow flow, final String stateId, final Class<T> clazz) { if (containsFlowState(flow, stateId)) { val state = flow.getState(stateId); return clazz.cast(state); } return null; }
[ "public", "<", "T", ">", "T", "getState", "(", "final", "Flow", "flow", ",", "final", "String", "stateId", ",", "final", "Class", "<", "T", ">", "clazz", ")", "{", "if", "(", "containsFlowState", "(", "flow", ",", "stateId", ")", ")", "{", "val", "...
Gets state. @param <T> the type parameter @param flow the flow @param stateId the state id @param clazz the clazz @return the state
[ "Gets", "state", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-webflow-api/src/main/java/org/apereo/cas/web/flow/configurer/AbstractCasWebflowConfigurer.java#L726-L732
mpetazzoni/ttorrent
common/src/main/java/com/turn/ttorrent/common/creation/MetadataBuilder.java
MetadataBuilder.setFilesInfo
public MetadataBuilder setFilesInfo(@NotNull List<byte[]> hashes, @NotNull List<String> filesPaths, @NotNull List<Long> filesLengths) { if (dataSources.size() != 0) { throw new IllegalStateException("Unable to add hashes-based files info. Some data sources already added"); } this.filesPaths.clear(); this.filesPaths.addAll(filesPaths); this.hashingResult = new HashingResult(hashes, filesLengths); return this; }
java
public MetadataBuilder setFilesInfo(@NotNull List<byte[]> hashes, @NotNull List<String> filesPaths, @NotNull List<Long> filesLengths) { if (dataSources.size() != 0) { throw new IllegalStateException("Unable to add hashes-based files info. Some data sources already added"); } this.filesPaths.clear(); this.filesPaths.addAll(filesPaths); this.hashingResult = new HashingResult(hashes, filesLengths); return this; }
[ "public", "MetadataBuilder", "setFilesInfo", "(", "@", "NotNull", "List", "<", "byte", "[", "]", ">", "hashes", ",", "@", "NotNull", "List", "<", "String", ">", "filesPaths", ",", "@", "NotNull", "List", "<", "Long", ">", "filesLengths", ")", "{", "if", ...
allow to create information about files via speicified hashes, files paths and files lengths. Using of this method is not compatible with using source-based methods ({@link #addFile(File)}, {@link #addDataSource(InputStream, String, boolean)}, etc because it's not possible to calculate concat this hashes and calculated hashes. each byte array in hashes list should have {{@link Constants#PIECE_HASH_SIZE}} length @param hashes list of files hashes in same order as files in files paths list @param filesPaths list of files paths @param filesLengths list of files lengths in same order as files in files paths list
[ "allow", "to", "create", "information", "about", "files", "via", "speicified", "hashes", "files", "paths", "and", "files", "lengths", ".", "Using", "of", "this", "method", "is", "not", "compatible", "with", "using", "source", "-", "based", "methods", "(", "{...
train
https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/common/src/main/java/com/turn/ttorrent/common/creation/MetadataBuilder.java#L252-L262
needle4j/needle4j
src/main/java/org/needle4j/db/operation/AbstractDBOperation.java
AbstractDBOperation.executeScript
protected void executeScript(final String filename, final Statement statement) throws SQLException { LOG.info("Executing sql script: " + filename); InputStream fileInputStream; try { fileInputStream = ConfigurationLoader.loadResource(filename); } catch (FileNotFoundException e) { LOG.error("could not execute script", e); return; } final BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream)); executeScript(reader, statement); }
java
protected void executeScript(final String filename, final Statement statement) throws SQLException { LOG.info("Executing sql script: " + filename); InputStream fileInputStream; try { fileInputStream = ConfigurationLoader.loadResource(filename); } catch (FileNotFoundException e) { LOG.error("could not execute script", e); return; } final BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream)); executeScript(reader, statement); }
[ "protected", "void", "executeScript", "(", "final", "String", "filename", ",", "final", "Statement", "statement", ")", "throws", "SQLException", "{", "LOG", ".", "info", "(", "\"Executing sql script: \"", "+", "filename", ")", ";", "InputStream", "fileInputStream", ...
Execute the given sql script. @param filename the filename of the sql script @param statement the {@link Statement} to be used for executing a SQL statement. @throws SQLException if a database access error occurs
[ "Execute", "the", "given", "sql", "script", "." ]
train
https://github.com/needle4j/needle4j/blob/55fbcdeed72be5cf26e4404b0fe40282792b51f2/src/main/java/org/needle4j/db/operation/AbstractDBOperation.java#L183-L196
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/deps/ModuleDeps.java
ModuleDeps.resolveWith
public ModuleDeps resolveWith(Features features, boolean coerceUndefinedToFalse) { for (ModuleDepInfo info : values()) { info.resolveWith(features, coerceUndefinedToFalse); } return this; }
java
public ModuleDeps resolveWith(Features features, boolean coerceUndefinedToFalse) { for (ModuleDepInfo info : values()) { info.resolveWith(features, coerceUndefinedToFalse); } return this; }
[ "public", "ModuleDeps", "resolveWith", "(", "Features", "features", ",", "boolean", "coerceUndefinedToFalse", ")", "{", "for", "(", "ModuleDepInfo", "info", ":", "values", "(", ")", ")", "{", "info", ".", "resolveWith", "(", "features", ",", "coerceUndefinedToFa...
Calls {@link ModuleDepInfo#resolveWith(Features)} on each of the values in the map. @param features the feature set to apply. @param coerceUndefinedToFalse if true, undefined features will be treated as false @return the current object
[ "Calls", "{", "@link", "ModuleDepInfo#resolveWith", "(", "Features", ")", "}", "on", "each", "of", "the", "values", "in", "the", "map", "." ]
train
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/deps/ModuleDeps.java#L254-L259
elvishew/xLog
library/src/main/java/com/elvishew/xlog/printer/AndroidPrinter.java
AndroidPrinter.printChunk
void printChunk(int logLevel, String tag, String msg) { android.util.Log.println(logLevel, tag, msg); }
java
void printChunk(int logLevel, String tag, String msg) { android.util.Log.println(logLevel, tag, msg); }
[ "void", "printChunk", "(", "int", "logLevel", ",", "String", "tag", ",", "String", "msg", ")", "{", "android", ".", "util", ".", "Log", ".", "println", "(", "logLevel", ",", "tag", ",", "msg", ")", ";", "}" ]
Print single chunk of log in new line. @param logLevel the level of log @param tag the tag of log @param msg the msg of log
[ "Print", "single", "chunk", "of", "log", "in", "new", "line", "." ]
train
https://github.com/elvishew/xLog/blob/c6fb95555ce619d3e527f5ba6c45d4d247c5a838/library/src/main/java/com/elvishew/xlog/printer/AndroidPrinter.java#L103-L105
pryzach/midao
midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/type/TypeHandlerUtils.java
TypeHandlerUtils.convertBlob
public static Object convertBlob(Object blob, InputStream input) throws SQLException { return convertBlob(blob, toByteArray(input)); }
java
public static Object convertBlob(Object blob, InputStream input) throws SQLException { return convertBlob(blob, toByteArray(input)); }
[ "public", "static", "Object", "convertBlob", "(", "Object", "blob", ",", "InputStream", "input", ")", "throws", "SQLException", "{", "return", "convertBlob", "(", "blob", ",", "toByteArray", "(", "input", ")", ")", ";", "}" ]
Transfers data from InputStream into sql.Blob @param blob sql.Blob which would be filled @param input InputStream @return sql.Blob from InputStream @throws SQLException
[ "Transfers", "data", "from", "InputStream", "into", "sql", ".", "Blob" ]
train
https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/type/TypeHandlerUtils.java#L149-L151
sarxos/win-registry
src/main/java/com/github/sarxos/winreg/WindowsRegistry.java
WindowsRegistry.readString
public String readString(HKey hk, String key, String valueName) throws RegistryException { return readString(hk, key, valueName, null); }
java
public String readString(HKey hk, String key, String valueName) throws RegistryException { return readString(hk, key, valueName, null); }
[ "public", "String", "readString", "(", "HKey", "hk", ",", "String", "key", ",", "String", "valueName", ")", "throws", "RegistryException", "{", "return", "readString", "(", "hk", ",", "key", ",", "valueName", ",", "null", ")", ";", "}" ]
Read a value from key and value name @param hk the HKEY @param key the key @param valueName the value name @return String value @throws RegistryException when something is not right
[ "Read", "a", "value", "from", "key", "and", "value", "name" ]
train
https://github.com/sarxos/win-registry/blob/5ccbe2157ae0ee894de7c41bec4bd7b1e0f5c437/src/main/java/com/github/sarxos/winreg/WindowsRegistry.java#L45-L47
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/bos/BosClient.java
BosClient.putObject
public PutObjectResponse putObject(String bucketName, String key, InputStream input) { return this.putObject(new PutObjectRequest(bucketName, key, input)); }
java
public PutObjectResponse putObject(String bucketName, String key, InputStream input) { return this.putObject(new PutObjectRequest(bucketName, key, input)); }
[ "public", "PutObjectResponse", "putObject", "(", "String", "bucketName", ",", "String", "key", ",", "InputStream", "input", ")", "{", "return", "this", ".", "putObject", "(", "new", "PutObjectRequest", "(", "bucketName", ",", "key", ",", "input", ")", ")", "...
Uploads the specified input stream to Bos under the specified bucket and key name. @param bucketName The name of an existing bucket, to which you have Write permission. @param key The key under which to store the specified file. @param input The input stream containing the value to be uploaded to Bos. @return A PutObjectResponse object containing the information returned by Bos for the newly created object.
[ "Uploads", "the", "specified", "input", "stream", "to", "Bos", "under", "the", "specified", "bucket", "and", "key", "name", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/bos/BosClient.java#L877-L879
xhsun/gw2wrapper
src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java
AsynchronousRequest.getMiniInfo
public void getMiniInfo(int[] ids, Callback<List<Mini>> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ids)); gw2API.getMiniInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback); }
java
public void getMiniInfo(int[] ids, Callback<List<Mini>> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ids)); gw2API.getMiniInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback); }
[ "public", "void", "getMiniInfo", "(", "int", "[", "]", "ids", ",", "Callback", "<", "List", "<", "Mini", ">", ">", "callback", ")", "throws", "GuildWars2Exception", ",", "NullPointerException", "{", "isParamValid", "(", "new", "ParamChecker", "(", "ids", ")"...
For more info on Mini API go <a href="https://wiki.guildwars2.com/wiki/API:2/minis">here</a><br/> Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions @param ids list of mini id @param callback callback that is going to be used for {@link Call#enqueue(Callback)} @throws GuildWars2Exception empty ID list @throws NullPointerException if given {@link Callback} is empty @see Mini mini info
[ "For", "more", "info", "on", "Mini", "API", "go", "<a", "href", "=", "https", ":", "//", "wiki", ".", "guildwars2", ".", "com", "/", "wiki", "/", "API", ":", "2", "/", "minis", ">", "here<", "/", "a", ">", "<br", "/", ">", "Give", "user", "the"...
train
https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L1892-L1895
eclipse/xtext-extras
org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/scoping/batch/FeatureScopes.java
FeatureScopes.createReceiverFeatureScope
protected IScope createReceiverFeatureScope( EObject featureCall, XExpression receiver, LightweightTypeReference receiverType, JvmIdentifiableElement receiverFeature, boolean implicitReceiver, boolean validStatic, TypeBucket receiverBucket, IScope parent, IFeatureScopeSession session) { return new ReceiverFeatureScope(parent, session, receiver, receiverType, implicitReceiver, asAbstractFeatureCall(featureCall), receiverBucket, receiverFeature, operatorMapping, validStatic); }
java
protected IScope createReceiverFeatureScope( EObject featureCall, XExpression receiver, LightweightTypeReference receiverType, JvmIdentifiableElement receiverFeature, boolean implicitReceiver, boolean validStatic, TypeBucket receiverBucket, IScope parent, IFeatureScopeSession session) { return new ReceiverFeatureScope(parent, session, receiver, receiverType, implicitReceiver, asAbstractFeatureCall(featureCall), receiverBucket, receiverFeature, operatorMapping, validStatic); }
[ "protected", "IScope", "createReceiverFeatureScope", "(", "EObject", "featureCall", ",", "XExpression", "receiver", ",", "LightweightTypeReference", "receiverType", ",", "JvmIdentifiableElement", "receiverFeature", ",", "boolean", "implicitReceiver", ",", "boolean", "validSta...
Creates a scope that returns the features of a given receiver type. @param featureCall the feature call that is currently processed by the scoping infrastructure @param receiver an optionally available receiver expression @param receiverType the type of the receiver. It may be available even if the receiver itself is null, which indicates an implicit receiver. @param receiverFeature the feature that was linked as the receiver @param implicitReceiver true if the receiver is an implicit receiver @param validStatic true if the receiver is valid according the its static flag, e.g an implicit this in a static method is invalid @param receiverBucket the types that contribute the static features. @param parent the parent scope. Is never null. @param session the currently known scope session. Is never null.
[ "Creates", "a", "scope", "that", "returns", "the", "features", "of", "a", "given", "receiver", "type", "." ]
train
https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/scoping/batch/FeatureScopes.java#L660-L671
OpenLiberty/open-liberty
dev/com.ibm.ws.monitor/src/com/ibm/wsspi/pmi/factory/StatsFactory.java
StatsFactory.createStatsInstance
@Deprecated public static StatsInstance createStatsInstance(String instanceName, String statsTemplate, ObjectName mBean, StatisticActionListener listener) throws StatsFactoryException { if (tc.isEntryEnabled()) Tr.entry(tc, new StringBuffer("createStatsInstance:name=").append(instanceName).append(";template="). append(statsTemplate).append(";mBean=").append((mBean == null) ? null : mBean.toString()).toString()); // call sibling method using a StatisticActions object StatsInstance rv = createStatsInstance(instanceName, statsTemplate, mBean, new StatisticActions(listener)); if (tc.isEntryEnabled()) Tr.exit(tc, "createStatsInstance"); return rv; }
java
@Deprecated public static StatsInstance createStatsInstance(String instanceName, String statsTemplate, ObjectName mBean, StatisticActionListener listener) throws StatsFactoryException { if (tc.isEntryEnabled()) Tr.entry(tc, new StringBuffer("createStatsInstance:name=").append(instanceName).append(";template="). append(statsTemplate).append(";mBean=").append((mBean == null) ? null : mBean.toString()).toString()); // call sibling method using a StatisticActions object StatsInstance rv = createStatsInstance(instanceName, statsTemplate, mBean, new StatisticActions(listener)); if (tc.isEntryEnabled()) Tr.exit(tc, "createStatsInstance"); return rv; }
[ "@", "Deprecated", "public", "static", "StatsInstance", "createStatsInstance", "(", "String", "instanceName", ",", "String", "statsTemplate", ",", "ObjectName", "mBean", ",", "StatisticActionListener", "listener", ")", "throws", "StatsFactoryException", "{", "if", "(", ...
Create a StatsInstance using the Stats template and add to the PMI tree at the root level. This method will associate the MBean provided by the caller to the Stats instance. @param instanceName name of the instance @param statsTemplate location of the Stats template XML file @param mBean MBean that needs to be associated with the Stats instance @param listener a StatisticActionListener object. This object will be called when a statistic is created for this instance @return Stats instance @exception StatsFactoryException if error while creating Stats instance @deprecated As of 6.1, replaced by createStatsInstance(String, String, ObjectName, StatisticActions ).
[ "Create", "a", "StatsInstance", "using", "the", "Stats", "template", "and", "add", "to", "the", "PMI", "tree", "at", "the", "root", "level", ".", "This", "method", "will", "associate", "the", "MBean", "provided", "by", "the", "caller", "to", "the", "Stats"...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.monitor/src/com/ibm/wsspi/pmi/factory/StatsFactory.java#L226-L243
BorderTech/wcomponents
wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/datatable/DataTableBeanExample.java
DataTableBeanExample.createTable
private WDataTable createTable() { WDataTable tbl = new WDataTable(); tbl.addColumn(new WTableColumn("First name", new WTextField())); tbl.addColumn(new WTableColumn("Last name", new WTextField())); tbl.addColumn(new WTableColumn("DOB", new WDateField())); return tbl; }
java
private WDataTable createTable() { WDataTable tbl = new WDataTable(); tbl.addColumn(new WTableColumn("First name", new WTextField())); tbl.addColumn(new WTableColumn("Last name", new WTextField())); tbl.addColumn(new WTableColumn("DOB", new WDateField())); return tbl; }
[ "private", "WDataTable", "createTable", "(", ")", "{", "WDataTable", "tbl", "=", "new", "WDataTable", "(", ")", ";", "tbl", ".", "addColumn", "(", "new", "WTableColumn", "(", "\"First name\"", ",", "new", "WTextField", "(", ")", ")", ")", ";", "tbl", "."...
Creates and configures the table to be used by the example. @return a new configured table.
[ "Creates", "and", "configures", "the", "table", "to", "be", "used", "by", "the", "example", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/datatable/DataTableBeanExample.java#L104-L110
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/geometry/GeometryUtilities.java
GeometryUtilities.distance3d
public static double distance3d( Coordinate c1, Coordinate c2, GeodeticCalculator geodeticCalculator ) { if (Double.isNaN(c1.z) || Double.isNaN(c2.z)) { throw new IllegalArgumentException("Missing elevation information in the supplied coordinates."); } double deltaElev = Math.abs(c1.z - c2.z); double projectedDistance; if (geodeticCalculator != null) { geodeticCalculator.setStartingGeographicPoint(c1.x, c1.y); geodeticCalculator.setDestinationGeographicPoint(c2.x, c2.y); projectedDistance = geodeticCalculator.getOrthodromicDistance(); } else { projectedDistance = c1.distance(c2); } double distance = NumericsUtilities.pythagoras(projectedDistance, deltaElev); return distance; }
java
public static double distance3d( Coordinate c1, Coordinate c2, GeodeticCalculator geodeticCalculator ) { if (Double.isNaN(c1.z) || Double.isNaN(c2.z)) { throw new IllegalArgumentException("Missing elevation information in the supplied coordinates."); } double deltaElev = Math.abs(c1.z - c2.z); double projectedDistance; if (geodeticCalculator != null) { geodeticCalculator.setStartingGeographicPoint(c1.x, c1.y); geodeticCalculator.setDestinationGeographicPoint(c2.x, c2.y); projectedDistance = geodeticCalculator.getOrthodromicDistance(); } else { projectedDistance = c1.distance(c2); } double distance = NumericsUtilities.pythagoras(projectedDistance, deltaElev); return distance; }
[ "public", "static", "double", "distance3d", "(", "Coordinate", "c1", ",", "Coordinate", "c2", ",", "GeodeticCalculator", "geodeticCalculator", ")", "{", "if", "(", "Double", ".", "isNaN", "(", "c1", ".", "z", ")", "||", "Double", ".", "isNaN", "(", "c2", ...
Calculates the 3d distance between two coordinates that have an elevation information. <p>Note that the {@link Coordinate#distance(Coordinate)} method does only 2d. @param c1 coordinate 1. @param c2 coordinate 2. @param geodeticCalculator If supplied it will be used for planar distance calculation. @return the distance considering also elevation.
[ "Calculates", "the", "3d", "distance", "between", "two", "coordinates", "that", "have", "an", "elevation", "information", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/geometry/GeometryUtilities.java#L308-L324
Samsung/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/GVRLight.java
GVRLight.setVec3
public void setVec3(String key, float x, float y, float z) { checkKeyIsUniform(key); NativeLight.setVec3(getNative(), key, x, y, z); }
java
public void setVec3(String key, float x, float y, float z) { checkKeyIsUniform(key); NativeLight.setVec3(getNative(), key, x, y, z); }
[ "public", "void", "setVec3", "(", "String", "key", ",", "float", "x", ",", "float", "y", ",", "float", "z", ")", "{", "checkKeyIsUniform", "(", "key", ")", ";", "NativeLight", ".", "setVec3", "(", "getNative", "(", ")", ",", "key", ",", "x", ",", "...
Set the value for a floating point vector of length 3. @param key name of uniform to set. @param x new X value @param y new Y value @param z new Z value @see #getVec3 @see #getFloatVec(String)
[ "Set", "the", "value", "for", "a", "floating", "point", "vector", "of", "length", "3", "." ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRLight.java#L426-L430
sagiegurari/fax4j
src/main/java/org/fax4j/common/JDKLogger.java
JDKLogger.initializeLogger
protected static final Logger initializeLogger() { //get logger Logger logger=Logger.getLogger(FaxClient.class.getName()); //enable all log events (fax4j logger filters out uneeded log events) logger.setLevel(Level.ALL); logger.setFilter(null); //enable to pass log events to parent loggers logger.setUseParentHandlers(true); //create handler Formatter formatter=new SimpleFormatter(); Handler handler=new StreamHandler(System.out,formatter); //set filtering handler.setLevel(logger.getLevel()); handler.setFilter(logger.getFilter()); //add handler logger.addHandler(handler); return logger; }
java
protected static final Logger initializeLogger() { //get logger Logger logger=Logger.getLogger(FaxClient.class.getName()); //enable all log events (fax4j logger filters out uneeded log events) logger.setLevel(Level.ALL); logger.setFilter(null); //enable to pass log events to parent loggers logger.setUseParentHandlers(true); //create handler Formatter formatter=new SimpleFormatter(); Handler handler=new StreamHandler(System.out,formatter); //set filtering handler.setLevel(logger.getLevel()); handler.setFilter(logger.getFilter()); //add handler logger.addHandler(handler); return logger; }
[ "protected", "static", "final", "Logger", "initializeLogger", "(", ")", "{", "//get logger", "Logger", "logger", "=", "Logger", ".", "getLogger", "(", "FaxClient", ".", "class", ".", "getName", "(", ")", ")", ";", "//enable all log events (fax4j logger filters out u...
This function initializes and returns the logger. @return The logger
[ "This", "function", "initializes", "and", "returns", "the", "logger", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/common/JDKLogger.java#L40-L64
b3dgs/lionengine
lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/Graphics.java
Graphics.createImageBuffer
public static ImageBuffer createImageBuffer(int width, int height, ColorRgba transparency) { return factoryGraphic.createImageBuffer(width, height, transparency); }
java
public static ImageBuffer createImageBuffer(int width, int height, ColorRgba transparency) { return factoryGraphic.createImageBuffer(width, height, transparency); }
[ "public", "static", "ImageBuffer", "createImageBuffer", "(", "int", "width", ",", "int", "height", ",", "ColorRgba", "transparency", ")", "{", "return", "factoryGraphic", ".", "createImageBuffer", "(", "width", ",", "height", ",", "transparency", ")", ";", "}" ]
Create an image buffer. @param width The image width (must be strictly positive). @param height The image height (must be strictly positive). @param transparency The color transparency (must not be <code>null</code>). @return The image buffer. @throws LionEngineException If invalid arguments.
[ "Create", "an", "image", "buffer", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/Graphics.java#L126-L129
fcrepo3/fcrepo
fcrepo-security/fcrepo-security-pdp/src/main/java/org/fcrepo/server/security/xacml/util/RelationshipResolverBase.java
RelationshipResolverBase.getFedoraResourceURI
protected String getFedoraResourceURI(String res) { // strip off info URI part if present String strippedRes; if (res.startsWith(Constants.FEDORA.uri)) { strippedRes = res.substring(Constants.FEDORA.uri.length()); } else { strippedRes = res; } // split into pid + datastream (if present), validate PID and then recombine datastream back in using URI form of PID String parts[] = strippedRes.split("/"); PID pid; try { pid = new PID(parts[0]); } catch (MalformedPIDException e1) { logger.warn("Invalid Fedora resource identifier: {}. PID part of URI is malformed", res); return null; } String resURI; if (parts.length == 1) { resURI = pid.toURI(); } else if (parts.length == 2) { resURI = pid.toURI() + "/" + parts[1]; // add datastream ID back } else { logger.warn("Invalid Fedora resource identifier: {}. Should be pid or datastream (URI form optional", res); return null; } return resURI; }
java
protected String getFedoraResourceURI(String res) { // strip off info URI part if present String strippedRes; if (res.startsWith(Constants.FEDORA.uri)) { strippedRes = res.substring(Constants.FEDORA.uri.length()); } else { strippedRes = res; } // split into pid + datastream (if present), validate PID and then recombine datastream back in using URI form of PID String parts[] = strippedRes.split("/"); PID pid; try { pid = new PID(parts[0]); } catch (MalformedPIDException e1) { logger.warn("Invalid Fedora resource identifier: {}. PID part of URI is malformed", res); return null; } String resURI; if (parts.length == 1) { resURI = pid.toURI(); } else if (parts.length == 2) { resURI = pid.toURI() + "/" + parts[1]; // add datastream ID back } else { logger.warn("Invalid Fedora resource identifier: {}. Should be pid or datastream (URI form optional", res); return null; } return resURI; }
[ "protected", "String", "getFedoraResourceURI", "(", "String", "res", ")", "{", "// strip off info URI part if present", "String", "strippedRes", ";", "if", "(", "res", ".", "startsWith", "(", "Constants", ".", "FEDORA", ".", "uri", ")", ")", "{", "strippedRes", ...
given either a ns:pid/ds identifier or an info:fedora/ URI form of the same return the URI form, validating the PID part. Returns null if the argument was invalid/could not be validated/converted @param res identifier for fedora resource @return URI form
[ "given", "either", "a", "ns", ":", "pid", "/", "ds", "identifier", "or", "an", "info", ":", "fedora", "/", "URI", "form", "of", "the", "same", "return", "the", "URI", "form", "validating", "the", "PID", "part", ".", "Returns", "null", "if", "the", "a...
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-security/fcrepo-security-pdp/src/main/java/org/fcrepo/server/security/xacml/util/RelationshipResolverBase.java#L79-L107
graphql-java/graphql-java
src/main/java/graphql/execution/nextgen/DefaultExecutionStrategy.java
DefaultExecutionStrategy.execute
@Override public CompletableFuture<RootExecutionResultNode> execute(ExecutionContext context, FieldSubSelection fieldSubSelection) { return resolveSubSelection(context, fieldSubSelection) .thenApply(RootExecutionResultNode::new); }
java
@Override public CompletableFuture<RootExecutionResultNode> execute(ExecutionContext context, FieldSubSelection fieldSubSelection) { return resolveSubSelection(context, fieldSubSelection) .thenApply(RootExecutionResultNode::new); }
[ "@", "Override", "public", "CompletableFuture", "<", "RootExecutionResultNode", ">", "execute", "(", "ExecutionContext", "context", ",", "FieldSubSelection", "fieldSubSelection", ")", "{", "return", "resolveSubSelection", "(", "context", ",", "fieldSubSelection", ")", "...
/* the fundamental algorithm is: - fetch sub selection and analyze it - convert the fetched value analysis into result node - get all unresolved result nodes and resolve the sub selection (start again recursively)
[ "/", "*", "the", "fundamental", "algorithm", "is", ":", "-", "fetch", "sub", "selection", "and", "analyze", "it", "-", "convert", "the", "fetched", "value", "analysis", "into", "result", "node", "-", "get", "all", "unresolved", "result", "nodes", "and", "r...
train
https://github.com/graphql-java/graphql-java/blob/9214b6044317849388bd88a14b54fc1c18c9f29f/src/main/java/graphql/execution/nextgen/DefaultExecutionStrategy.java#L31-L35
alkacon/opencms-core
src-setup/org/opencms/setup/xml/CmsSetupXmlHelper.java
CmsSetupXmlHelper.getDocument
public Document getDocument(String xmlFilename) throws CmsXmlException { // try to get it from the cache Document document = m_cache.get(xmlFilename); if (document == null) { try { document = CmsXmlUtils.unmarshalHelper( new InputSource(new FileReader(getFile(xmlFilename))), NO_ENTITY_RESOLVER); } catch (FileNotFoundException e) { LOG.error("Could not read file " + xmlFilename, e); throw new CmsXmlException(new CmsMessageContainer(null, e.toString())); } catch (Exception e) { LOG.error("Could not parse file " + xmlFilename, e); throw new CmsXmlException( Messages.get().container(Messages.ERR_XML_COULD_NOT_PARSE_FILE_1, xmlFilename), e); } // cache the doc m_cache.put(xmlFilename, document); } return document; }
java
public Document getDocument(String xmlFilename) throws CmsXmlException { // try to get it from the cache Document document = m_cache.get(xmlFilename); if (document == null) { try { document = CmsXmlUtils.unmarshalHelper( new InputSource(new FileReader(getFile(xmlFilename))), NO_ENTITY_RESOLVER); } catch (FileNotFoundException e) { LOG.error("Could not read file " + xmlFilename, e); throw new CmsXmlException(new CmsMessageContainer(null, e.toString())); } catch (Exception e) { LOG.error("Could not parse file " + xmlFilename, e); throw new CmsXmlException( Messages.get().container(Messages.ERR_XML_COULD_NOT_PARSE_FILE_1, xmlFilename), e); } // cache the doc m_cache.put(xmlFilename, document); } return document; }
[ "public", "Document", "getDocument", "(", "String", "xmlFilename", ")", "throws", "CmsXmlException", "{", "// try to get it from the cache", "Document", "document", "=", "m_cache", ".", "get", "(", "xmlFilename", ")", ";", "if", "(", "document", "==", "null", ")",...
Returns the document for the given filename.<p> It can be new read or come from the document cache.<p> @param xmlFilename the filename to read @return the document for the given filename @throws CmsXmlException if something goes wrong while reading
[ "Returns", "the", "document", "for", "the", "given", "filename", ".", "<p", ">", "It", "can", "be", "new", "read", "or", "come", "from", "the", "document", "cache", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/xml/CmsSetupXmlHelper.java#L389-L413
facebookarchive/hadoop-20
src/core/org/apache/hadoop/fs/FreightStreamer.java
FreightStreamer.cat
void cat(String src, boolean verifyChecksum) throws IOException { //cat behavior in Linux // [~/1207]$ ls ?.txt // x.txt z.txt // [~/1207]$ cat x.txt y.txt z.txt // xxx // cat: y.txt: No such file or directory // zzz Path srcPattern = new Path(src); new DelayedExceptionThrowing() { @Override void process(Path p, FileSystem srcFs) throws IOException { if (srcFs.getFileStatus(p).isDir()) { throw new IOException("Source must be a file."); } printToStdout(srcFs.open(p)); } }.globAndProcess(srcPattern, getSrcFileSystem(srcPattern, verifyChecksum)); }
java
void cat(String src, boolean verifyChecksum) throws IOException { //cat behavior in Linux // [~/1207]$ ls ?.txt // x.txt z.txt // [~/1207]$ cat x.txt y.txt z.txt // xxx // cat: y.txt: No such file or directory // zzz Path srcPattern = new Path(src); new DelayedExceptionThrowing() { @Override void process(Path p, FileSystem srcFs) throws IOException { if (srcFs.getFileStatus(p).isDir()) { throw new IOException("Source must be a file."); } printToStdout(srcFs.open(p)); } }.globAndProcess(srcPattern, getSrcFileSystem(srcPattern, verifyChecksum)); }
[ "void", "cat", "(", "String", "src", ",", "boolean", "verifyChecksum", ")", "throws", "IOException", "{", "//cat behavior in Linux", "// [~/1207]$ ls ?.txt", "// x.txt z.txt", "// [~/1207]$ cat x.txt y.txt z.txt", "// xxx", "// cat: y.txt: No such file or directory", "// z...
Fetch all files that match the file pattern <i>srcf</i> and display their content on stdout. @param srcf: a file pattern specifying source files @exception: IOException @see org.apache.hadoop.fs.FileSystem.globStatus
[ "Fetch", "all", "files", "that", "match", "the", "file", "pattern", "<i", ">", "srcf<", "/", "i", ">", "and", "display", "their", "content", "on", "stdout", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/FreightStreamer.java#L253-L272
HadoopGenomics/Hadoop-BAM
src/main/java/org/seqdoop/hadoop_bam/util/SAMOutputPreparer.java
SAMOutputPreparer.prepareForRecords
public OutputStream prepareForRecords( OutputStream out, final SAMFormat format, final SAMFileHeader header) throws IOException { switch (format) { case SAM: out = prepareSAMOrBAMStream(out, format, header); break; case BAM: out = prepareSAMOrBAMStream(out, format, header); break; case CRAM: out = prepareCRAMStream(out, format, header); break; default: throw new IllegalArgumentException ("Unsupported SAM file format, must be one of SAM, BAM or CRAM"); } // Important for BAM: if the caller doesn't want to use the new stream // for some reason, the BlockCompressedOutputStream's buffer would never // be flushed. out.flush(); return out; }
java
public OutputStream prepareForRecords( OutputStream out, final SAMFormat format, final SAMFileHeader header) throws IOException { switch (format) { case SAM: out = prepareSAMOrBAMStream(out, format, header); break; case BAM: out = prepareSAMOrBAMStream(out, format, header); break; case CRAM: out = prepareCRAMStream(out, format, header); break; default: throw new IllegalArgumentException ("Unsupported SAM file format, must be one of SAM, BAM or CRAM"); } // Important for BAM: if the caller doesn't want to use the new stream // for some reason, the BlockCompressedOutputStream's buffer would never // be flushed. out.flush(); return out; }
[ "public", "OutputStream", "prepareForRecords", "(", "OutputStream", "out", ",", "final", "SAMFormat", "format", ",", "final", "SAMFileHeader", "header", ")", "throws", "IOException", "{", "switch", "(", "format", ")", "{", "case", "SAM", ":", "out", "=", "prep...
Prepares the given output stream for writing of SAMRecords in the given format. This includes writing the given SAM header and, in the case of BAM or CRAM, writing some further metadata as well as compressing everything written. Returns a new stream to replace the original: it will do the appropriate compression for BAM/CRAM files.
[ "Prepares", "the", "given", "output", "stream", "for", "writing", "of", "SAMRecords", "in", "the", "given", "format", ".", "This", "includes", "writing", "the", "given", "SAM", "header", "and", "in", "the", "case", "of", "BAM", "or", "CRAM", "writing", "so...
train
https://github.com/HadoopGenomics/Hadoop-BAM/blob/9f974cf635a8d72f69604021cc3d5f3469d38d2f/src/main/java/org/seqdoop/hadoop_bam/util/SAMOutputPreparer.java#L60-L85
kurbatov/firmata4j
src/main/java/org/firmata4j/firmata/FirmataI2CDevice.java
FirmataI2CDevice.onReceive
void onReceive(int register, byte[] message) { I2CEvent evt = new I2CEvent(this, register, message); I2CListener listener = callbacks.remove(register); if (listener == null) { for (I2CListener subscriber : subscribers) { subscriber.onReceive(evt); } } else { listener.onReceive(evt); } }
java
void onReceive(int register, byte[] message) { I2CEvent evt = new I2CEvent(this, register, message); I2CListener listener = callbacks.remove(register); if (listener == null) { for (I2CListener subscriber : subscribers) { subscriber.onReceive(evt); } } else { listener.onReceive(evt); } }
[ "void", "onReceive", "(", "int", "register", ",", "byte", "[", "]", "message", ")", "{", "I2CEvent", "evt", "=", "new", "I2CEvent", "(", "this", ",", "register", ",", "message", ")", ";", "I2CListener", "listener", "=", "callbacks", ".", "remove", "(", ...
{@link FirmataDevice} calls this method when receives a message from I2C device. @param register The device register read from. @param message actual data from I2C device
[ "{", "@link", "FirmataDevice", "}", "calls", "this", "method", "when", "receives", "a", "message", "from", "I2C", "device", "." ]
train
https://github.com/kurbatov/firmata4j/blob/1bf75cd7f4f8d11dc2a91cf2bc6808f583d9a4ea/src/main/java/org/firmata4j/firmata/FirmataI2CDevice.java#L129-L139
eldur/jwbf
src/main/java/net/sourceforge/jwbf/mediawiki/actions/queries/UnreviewedPagesTitles.java
UnreviewedPagesTitles.generateRequest
private HttpAction generateRequest(int[] namespace, String urstart, String urend) { RequestBuilder requestBuilder = new ApiRequestBuilder() // .action("query") // .formatXml() // .param("list", "unreviewedpages") // .param("urlimit", LIMIT) // ; if (namespace != null) { String urnamespace = MediaWiki.urlEncode(MWAction.createNsString(namespace)); requestBuilder.param("urnamespace", urnamespace); } if (urstart.length() > 0) { requestBuilder.param("urstart", urstart); } if (urend.length() > 0) { requestBuilder.param("urend", urend); } return requestBuilder.buildGet(); }
java
private HttpAction generateRequest(int[] namespace, String urstart, String urend) { RequestBuilder requestBuilder = new ApiRequestBuilder() // .action("query") // .formatXml() // .param("list", "unreviewedpages") // .param("urlimit", LIMIT) // ; if (namespace != null) { String urnamespace = MediaWiki.urlEncode(MWAction.createNsString(namespace)); requestBuilder.param("urnamespace", urnamespace); } if (urstart.length() > 0) { requestBuilder.param("urstart", urstart); } if (urend.length() > 0) { requestBuilder.param("urend", urend); } return requestBuilder.buildGet(); }
[ "private", "HttpAction", "generateRequest", "(", "int", "[", "]", "namespace", ",", "String", "urstart", ",", "String", "urend", ")", "{", "RequestBuilder", "requestBuilder", "=", "new", "ApiRequestBuilder", "(", ")", "//", ".", "action", "(", "\"query\"", ")"...
generates the next MediaWiki-request (GetMethod) and adds it to msgs. @param namespace the namespace(s) that will be searched for links, as a string of numbers separated by '|'; if null, this parameter is omitted @param urstart Start listing at this page title @param urend Stop listing at this page title
[ "generates", "the", "next", "MediaWiki", "-", "request", "(", "GetMethod", ")", "and", "adds", "it", "to", "msgs", "." ]
train
https://github.com/eldur/jwbf/blob/ee17ea2fa5a26f17c8332a094b2db86dd596d1ff/src/main/java/net/sourceforge/jwbf/mediawiki/actions/queries/UnreviewedPagesTitles.java#L59-L80
alkacon/opencms-core
src/org/opencms/ui/CmsVaadinUtils.java
CmsVaadinUtils.showAlert
public static void showAlert(String title, String message, final Runnable callback) { final Window window = new Window(); window.setModal(true); Panel panel = new Panel(); panel.setCaption(title); panel.setWidth("500px"); VerticalLayout layout = new VerticalLayout(); layout.setMargin(true); panel.setContent(layout); layout.addComponent(new Label(message)); Button okButton = new Button(); okButton.addClickListener(new ClickListener() { /** The serial version id. */ private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { window.close(); if (callback != null) { callback.run(); } } }); layout.addComponent(okButton); layout.setComponentAlignment(okButton, Alignment.BOTTOM_RIGHT); okButton.setCaption( org.opencms.workplace.Messages.get().getBundle(A_CmsUI.get().getLocale()).key( org.opencms.workplace.Messages.GUI_DIALOG_BUTTON_OK_0)); window.setContent(panel); window.setClosable(false); window.setResizable(false); A_CmsUI.get().addWindow(window); }
java
public static void showAlert(String title, String message, final Runnable callback) { final Window window = new Window(); window.setModal(true); Panel panel = new Panel(); panel.setCaption(title); panel.setWidth("500px"); VerticalLayout layout = new VerticalLayout(); layout.setMargin(true); panel.setContent(layout); layout.addComponent(new Label(message)); Button okButton = new Button(); okButton.addClickListener(new ClickListener() { /** The serial version id. */ private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { window.close(); if (callback != null) { callback.run(); } } }); layout.addComponent(okButton); layout.setComponentAlignment(okButton, Alignment.BOTTOM_RIGHT); okButton.setCaption( org.opencms.workplace.Messages.get().getBundle(A_CmsUI.get().getLocale()).key( org.opencms.workplace.Messages.GUI_DIALOG_BUTTON_OK_0)); window.setContent(panel); window.setClosable(false); window.setResizable(false); A_CmsUI.get().addWindow(window); }
[ "public", "static", "void", "showAlert", "(", "String", "title", ",", "String", "message", ",", "final", "Runnable", "callback", ")", "{", "final", "Window", "window", "=", "new", "Window", "(", ")", ";", "window", ".", "setModal", "(", "true", ")", ";",...
Shows an alert box to the user with the given information, which will perform the given action after the user clicks on OK.<p> @param title the title @param message the message @param callback the callback to execute after clicking OK
[ "Shows", "an", "alert", "box", "to", "the", "user", "with", "the", "given", "information", "which", "will", "perform", "the", "given", "action", "after", "the", "user", "clicks", "on", "OK", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/CmsVaadinUtils.java#L1163-L1198
JodaOrg/joda-beans
src/main/java/org/joda/beans/ser/CollectSerIteratorFactory.java
CollectSerIteratorFactory.createChild
@Override public SerIterator createChild(final Object value, final SerIterator parent) { Class<?> declaredType = parent.valueType(); List<Class<?>> childGenericTypes = parent.valueTypeTypes(); if (value instanceof Grid) { if (childGenericTypes.size() == 1) { return grid((Grid<?>) value, declaredType, childGenericTypes.get(0), EMPTY_VALUE_TYPES); } return grid((Grid<?>) value, Object.class, Object.class, EMPTY_VALUE_TYPES); } return super.createChild(value, parent); }
java
@Override public SerIterator createChild(final Object value, final SerIterator parent) { Class<?> declaredType = parent.valueType(); List<Class<?>> childGenericTypes = parent.valueTypeTypes(); if (value instanceof Grid) { if (childGenericTypes.size() == 1) { return grid((Grid<?>) value, declaredType, childGenericTypes.get(0), EMPTY_VALUE_TYPES); } return grid((Grid<?>) value, Object.class, Object.class, EMPTY_VALUE_TYPES); } return super.createChild(value, parent); }
[ "@", "Override", "public", "SerIterator", "createChild", "(", "final", "Object", "value", ",", "final", "SerIterator", "parent", ")", "{", "Class", "<", "?", ">", "declaredType", "=", "parent", ".", "valueType", "(", ")", ";", "List", "<", "Class", "<", ...
Creates an iterator wrapper for a value retrieved from a parent iterator. <p> Allows the parent iterator to define the child iterator using generic type information. This handles cases such as a {@code List} as the value in a {@code Map}. @param value the possible collection-like object, not null @param parent the parent iterator, not null @return the iterator, null if not a collection-like type
[ "Creates", "an", "iterator", "wrapper", "for", "a", "value", "retrieved", "from", "a", "parent", "iterator", ".", "<p", ">", "Allows", "the", "parent", "iterator", "to", "define", "the", "child", "iterator", "using", "generic", "type", "information", ".", "T...
train
https://github.com/JodaOrg/joda-beans/blob/f07dbe42947150b23a173f35984c6ab33c5529bf/src/main/java/org/joda/beans/ser/CollectSerIteratorFactory.java#L63-L74
joniles/mpxj
src/main/java/net/sf/mpxj/json/JsonStreamWriter.java
JsonStreamWriter.writeNameValuePair
public void writeNameValuePair(String name, long value) throws IOException { internalWriteNameValuePair(name, Long.toString(value)); }
java
public void writeNameValuePair(String name, long value) throws IOException { internalWriteNameValuePair(name, Long.toString(value)); }
[ "public", "void", "writeNameValuePair", "(", "String", "name", ",", "long", "value", ")", "throws", "IOException", "{", "internalWriteNameValuePair", "(", "name", ",", "Long", ".", "toString", "(", "value", ")", ")", ";", "}" ]
Write a long attribute. @param name attribute name @param value attribute value
[ "Write", "a", "long", "attribute", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/json/JsonStreamWriter.java#L162-L165
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
MutableBigInteger.divide2n1n
private MutableBigInteger divide2n1n(MutableBigInteger b, MutableBigInteger quotient) { int n = b.intLen; // step 1: base case if (n%2 != 0 || n < BigInteger.BURNIKEL_ZIEGLER_THRESHOLD) { return divideKnuth(b, quotient); } // step 2: view this as [a1,a2,a3,a4] where each ai is n/2 ints or less MutableBigInteger aUpper = new MutableBigInteger(this); aUpper.safeRightShift(32*(n/2)); // aUpper = [a1,a2,a3] keepLower(n/2); // this = a4 // step 3: q1=aUpper/b, r1=aUpper%b MutableBigInteger q1 = new MutableBigInteger(); MutableBigInteger r1 = aUpper.divide3n2n(b, q1); // step 4: quotient=[r1,this]/b, r2=[r1,this]%b addDisjoint(r1, n/2); // this = [r1,this] MutableBigInteger r2 = divide3n2n(b, quotient); // step 5: let quotient=[q1,quotient] and return r2 quotient.addDisjoint(q1, n/2); return r2; }
java
private MutableBigInteger divide2n1n(MutableBigInteger b, MutableBigInteger quotient) { int n = b.intLen; // step 1: base case if (n%2 != 0 || n < BigInteger.BURNIKEL_ZIEGLER_THRESHOLD) { return divideKnuth(b, quotient); } // step 2: view this as [a1,a2,a3,a4] where each ai is n/2 ints or less MutableBigInteger aUpper = new MutableBigInteger(this); aUpper.safeRightShift(32*(n/2)); // aUpper = [a1,a2,a3] keepLower(n/2); // this = a4 // step 3: q1=aUpper/b, r1=aUpper%b MutableBigInteger q1 = new MutableBigInteger(); MutableBigInteger r1 = aUpper.divide3n2n(b, q1); // step 4: quotient=[r1,this]/b, r2=[r1,this]%b addDisjoint(r1, n/2); // this = [r1,this] MutableBigInteger r2 = divide3n2n(b, quotient); // step 5: let quotient=[q1,quotient] and return r2 quotient.addDisjoint(q1, n/2); return r2; }
[ "private", "MutableBigInteger", "divide2n1n", "(", "MutableBigInteger", "b", ",", "MutableBigInteger", "quotient", ")", "{", "int", "n", "=", "b", ".", "intLen", ";", "// step 1: base case", "if", "(", "n", "%", "2", "!=", "0", "||", "n", "<", "BigInteger", ...
This method implements algorithm 1 from pg. 4 of the Burnikel-Ziegler paper. It divides a 2n-digit number by a n-digit number.<br/> The parameter beta is 2<sup>32</sup> so all shifts are multiples of 32 bits. <br/> {@code this} must be a nonnegative number such that {@code this.bitLength() <= 2*b.bitLength()} @param b a positive number such that {@code b.bitLength()} is even @param quotient output parameter for {@code this/b} @return {@code this%b}
[ "This", "method", "implements", "algorithm", "1", "from", "pg", ".", "4", "of", "the", "Burnikel", "-", "Ziegler", "paper", ".", "It", "divides", "a", "2n", "-", "digit", "number", "by", "a", "n", "-", "digit", "number", ".", "<br", "/", ">", "The", ...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java#L1310-L1334
Javacord/Javacord
javacord-api/src/main/java/org/javacord/api/entity/webhook/WebhookBuilder.java
WebhookBuilder.setAvatar
public WebhookBuilder setAvatar(BufferedImage avatar, String fileType) { delegate.setAvatar(avatar, fileType); return this; }
java
public WebhookBuilder setAvatar(BufferedImage avatar, String fileType) { delegate.setAvatar(avatar, fileType); return this; }
[ "public", "WebhookBuilder", "setAvatar", "(", "BufferedImage", "avatar", ",", "String", "fileType", ")", "{", "delegate", ".", "setAvatar", "(", "avatar", ",", "fileType", ")", ";", "return", "this", ";", "}" ]
Sets the avatar. @param avatar The avatar to set. @param fileType The type of the avatar, e.g. "png" or "jpg". @return The current instance in order to chain call methods.
[ "Sets", "the", "avatar", "." ]
train
https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-api/src/main/java/org/javacord/api/entity/webhook/WebhookBuilder.java#L74-L77
knowm/XChange
xchange-dsx/src/main/java/org/knowm/xchange/dsx/service/core/DSXMarketDataServiceCore.java
DSXMarketDataServiceCore.getTrades
@Override public Trades getTrades(CurrencyPair currencyPair, Object... args) throws IOException { String marketName = DSXAdapters.currencyPairToMarketName(currencyPair); int numberOfItems = -1; try { if (args != null) { numberOfItems = (Integer) args[0]; // can this really be args[0] if we are also using args[0] as a string// // below?? } } catch (ArrayIndexOutOfBoundsException e) { // ignore, can happen if no argument given. } DSXTrade[] dsxTrades; String accountType = null; try { if (args != null) { accountType = (String) args[1]; } } catch (ArrayIndexOutOfBoundsException e) { // ignore, can happen if no argument given. } if (numberOfItems == -1) { dsxTrades = getDSXTrades(marketName, FULL_SIZE, accountType).getTrades(marketName); } else { dsxTrades = getDSXTrades(marketName, numberOfItems, accountType).getTrades(marketName); } return DSXAdapters.adaptTrades(dsxTrades, currencyPair); }
java
@Override public Trades getTrades(CurrencyPair currencyPair, Object... args) throws IOException { String marketName = DSXAdapters.currencyPairToMarketName(currencyPair); int numberOfItems = -1; try { if (args != null) { numberOfItems = (Integer) args[0]; // can this really be args[0] if we are also using args[0] as a string// // below?? } } catch (ArrayIndexOutOfBoundsException e) { // ignore, can happen if no argument given. } DSXTrade[] dsxTrades; String accountType = null; try { if (args != null) { accountType = (String) args[1]; } } catch (ArrayIndexOutOfBoundsException e) { // ignore, can happen if no argument given. } if (numberOfItems == -1) { dsxTrades = getDSXTrades(marketName, FULL_SIZE, accountType).getTrades(marketName); } else { dsxTrades = getDSXTrades(marketName, numberOfItems, accountType).getTrades(marketName); } return DSXAdapters.adaptTrades(dsxTrades, currencyPair); }
[ "@", "Override", "public", "Trades", "getTrades", "(", "CurrencyPair", "currencyPair", ",", "Object", "...", "args", ")", "throws", "IOException", "{", "String", "marketName", "=", "DSXAdapters", ".", "currencyPairToMarketName", "(", "currencyPair", ")", ";", "int...
Get recent trades from exchange @param currencyPair @param args Optional arguments. Exchange-specific. This implementation assumes args[0] is integer value @return Trades object @throws IOException
[ "Get", "recent", "trades", "from", "exchange" ]
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-dsx/src/main/java/org/knowm/xchange/dsx/service/core/DSXMarketDataServiceCore.java#L100-L133
looly/hutool
hutool-extra/src/main/java/cn/hutool/extra/ftp/Ftp.java
Ftp.download
public void download(String path, String fileName, OutputStream out) { cd(path); try { client.setFileType(FTPClient.BINARY_FILE_TYPE); client.retrieveFile(fileName, out); } catch (IOException e) { throw new FtpException(e); } }
java
public void download(String path, String fileName, OutputStream out) { cd(path); try { client.setFileType(FTPClient.BINARY_FILE_TYPE); client.retrieveFile(fileName, out); } catch (IOException e) { throw new FtpException(e); } }
[ "public", "void", "download", "(", "String", "path", ",", "String", "fileName", ",", "OutputStream", "out", ")", "{", "cd", "(", "path", ")", ";", "try", "{", "client", ".", "setFileType", "(", "FTPClient", ".", "BINARY_FILE_TYPE", ")", ";", "client", "....
下载文件到输出流 @param path 文件路径 @param fileName 文件名 @param out 输出位置
[ "下载文件到输出流" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/ftp/Ftp.java#L468-L476
profesorfalken/jPowerShell
src/main/java/com/profesorfalken/jpowershell/PowerShell.java
PowerShell.initalize
private PowerShell initalize(String powerShellExecutablePath) throws PowerShellNotAvailableException { String codePage = PowerShellCodepage.getIdentifierByCodePageName(Charset.defaultCharset().name()); ProcessBuilder pb; //Start powershell executable in process if (OSDetector.isWindows()) { pb = new ProcessBuilder("cmd.exe", "/c", "chcp", codePage, ">", "NUL", "&", powerShellExecutablePath, "-ExecutionPolicy", "Bypass", "-NoExit", "-NoProfile", "-Command", "-"); } else { pb = new ProcessBuilder(powerShellExecutablePath, "-nologo", "-noexit", "-Command", "-"); } //Merge standard and error streams pb.redirectErrorStream(true); try { //Launch process p = pb.start(); if (p.waitFor(5, TimeUnit.SECONDS) && !p.isAlive()) { throw new PowerShellNotAvailableException( "Cannot execute PowerShell. Please make sure that it is installed in your system. Errorcode:" + p.exitValue()); } } catch (IOException | InterruptedException ex) { throw new PowerShellNotAvailableException( "Cannot execute PowerShell. Please make sure that it is installed in your system", ex); } //Prepare writer that will be used to send commands to powershell this.commandWriter = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true); // Init thread pool. 2 threads are needed: one to write and read console and the other to close it this.threadpool = Executors.newFixedThreadPool(2); //Get and store the PID of the process this.pid = getPID(); return this; }
java
private PowerShell initalize(String powerShellExecutablePath) throws PowerShellNotAvailableException { String codePage = PowerShellCodepage.getIdentifierByCodePageName(Charset.defaultCharset().name()); ProcessBuilder pb; //Start powershell executable in process if (OSDetector.isWindows()) { pb = new ProcessBuilder("cmd.exe", "/c", "chcp", codePage, ">", "NUL", "&", powerShellExecutablePath, "-ExecutionPolicy", "Bypass", "-NoExit", "-NoProfile", "-Command", "-"); } else { pb = new ProcessBuilder(powerShellExecutablePath, "-nologo", "-noexit", "-Command", "-"); } //Merge standard and error streams pb.redirectErrorStream(true); try { //Launch process p = pb.start(); if (p.waitFor(5, TimeUnit.SECONDS) && !p.isAlive()) { throw new PowerShellNotAvailableException( "Cannot execute PowerShell. Please make sure that it is installed in your system. Errorcode:" + p.exitValue()); } } catch (IOException | InterruptedException ex) { throw new PowerShellNotAvailableException( "Cannot execute PowerShell. Please make sure that it is installed in your system", ex); } //Prepare writer that will be used to send commands to powershell this.commandWriter = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true); // Init thread pool. 2 threads are needed: one to write and read console and the other to close it this.threadpool = Executors.newFixedThreadPool(2); //Get and store the PID of the process this.pid = getPID(); return this; }
[ "private", "PowerShell", "initalize", "(", "String", "powerShellExecutablePath", ")", "throws", "PowerShellNotAvailableException", "{", "String", "codePage", "=", "PowerShellCodepage", ".", "getIdentifierByCodePageName", "(", "Charset", ".", "defaultCharset", "(", ")", "....
Initializes PowerShell console in which we will enter the commands
[ "Initializes", "PowerShell", "console", "in", "which", "we", "will", "enter", "the", "commands" ]
train
https://github.com/profesorfalken/jPowerShell/blob/a0fb9d3b9db12dd5635de810e6366e17b932ee10/src/main/java/com/profesorfalken/jpowershell/PowerShell.java#L136-L174
pippo-java/pippo
pippo-core/src/main/java/ro/pippo/core/PippoSettings.java
PippoSettings.getChar
public char getChar(String name, char defaultValue) { String value = getString(name, null); if (!StringUtils.isNullOrEmpty(value)) { return value.trim().charAt(0); } return defaultValue; }
java
public char getChar(String name, char defaultValue) { String value = getString(name, null); if (!StringUtils.isNullOrEmpty(value)) { return value.trim().charAt(0); } return defaultValue; }
[ "public", "char", "getChar", "(", "String", "name", ",", "char", "defaultValue", ")", "{", "String", "value", "=", "getString", "(", "name", ",", "null", ")", ";", "if", "(", "!", "StringUtils", ".", "isNullOrEmpty", "(", "value", ")", ")", "{", "retur...
Returns the char value for the specified name. If the name does not exist or the value for the name can not be interpreted as a char, the defaultValue is returned. @param name @param defaultValue @return name value or defaultValue
[ "Returns", "the", "char", "value", "for", "the", "specified", "name", ".", "If", "the", "name", "does", "not", "exist", "or", "the", "value", "for", "the", "name", "can", "not", "be", "interpreted", "as", "a", "char", "the", "defaultValue", "is", "return...
train
https://github.com/pippo-java/pippo/blob/cb5ccb453bffcc3cf386adc660674812d10b9726/pippo-core/src/main/java/ro/pippo/core/PippoSettings.java#L587-L594
jboss/jboss-jsf-api_spec
src/main/java/javax/faces/application/ViewHandler.java
ViewHandler.getRedirectURL
public String getRedirectURL(FacesContext context, String viewId, Map<String,List<String>>parameters, boolean includeViewParams) { return getActionURL(context, viewId); }
java
public String getRedirectURL(FacesContext context, String viewId, Map<String,List<String>>parameters, boolean includeViewParams) { return getActionURL(context, viewId); }
[ "public", "String", "getRedirectURL", "(", "FacesContext", "context", ",", "String", "viewId", ",", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "parameters", ",", "boolean", "includeViewParams", ")", "{", "return", "getActionURL", "(", "context...
<p class="changed_added_2_0"> Return a JSF action URL derived from the <code>viewId</code> argument that is suitable to be used by the {@link NavigationHandler} to issue a redirect request to the URL using a NonFaces request. Compliant implementations must implement this method as specified in section JSF.7.6.2. The default implementation simply calls through to {@link #getActionURL}, passing the arguments <code>context</code> and <code>viewId</code>.</p> @param context The FacesContext processing this request @param viewId The view identifier of the target page @param parameters A mapping of parameter names to one or more values @param includeViewParams A flag indicating whether view parameters should be encoded into this URL @since 2.0
[ "<p", "class", "=", "changed_added_2_0", ">", "Return", "a", "JSF", "action", "URL", "derived", "from", "the", "<code", ">", "viewId<", "/", "code", ">", "argument", "that", "is", "suitable", "to", "be", "used", "by", "the", "{", "@link", "NavigationHandle...
train
https://github.com/jboss/jboss-jsf-api_spec/blob/cb33d215acbab847f2db5cdf2c6fe4d99c0a01c3/src/main/java/javax/faces/application/ViewHandler.java#L543-L550
jparsec/jparsec
jparsec/src/main/java/org/jparsec/OperatorTable.java
OperatorTable.infixr
public OperatorTable<T> infixr( Parser<? extends BiFunction<? super T, ? super T, ? extends T>> parser, int precedence) { ops.add(new Operator(parser, precedence, Associativity.RASSOC)); return this; }
java
public OperatorTable<T> infixr( Parser<? extends BiFunction<? super T, ? super T, ? extends T>> parser, int precedence) { ops.add(new Operator(parser, precedence, Associativity.RASSOC)); return this; }
[ "public", "OperatorTable", "<", "T", ">", "infixr", "(", "Parser", "<", "?", "extends", "BiFunction", "<", "?", "super", "T", ",", "?", "super", "T", ",", "?", "extends", "T", ">", ">", "parser", ",", "int", "precedence", ")", "{", "ops", ".", "add...
Adds an infix right-associative binary operator. @param parser the parser for the operator. @param precedence the precedence number. @return this.
[ "Adds", "an", "infix", "right", "-", "associative", "binary", "operator", "." ]
train
https://github.com/jparsec/jparsec/blob/df1280259f5da9eb5ffc537437569dddba66cb94/jparsec/src/main/java/org/jparsec/OperatorTable.java#L128-L132
GenesysPureEngage/provisioning-client-java
src/main/java/com/genesys/internal/provisioning/api/SamlSettingsApi.java
SamlSettingsApi.getSPMetadata
public GetSPMetadataResponse getSPMetadata(String location, Boolean download, Boolean noSpinner) throws ApiException { ApiResponse<GetSPMetadataResponse> resp = getSPMetadataWithHttpInfo(location, download, noSpinner); return resp.getData(); }
java
public GetSPMetadataResponse getSPMetadata(String location, Boolean download, Boolean noSpinner) throws ApiException { ApiResponse<GetSPMetadataResponse> resp = getSPMetadataWithHttpInfo(location, download, noSpinner); return resp.getData(); }
[ "public", "GetSPMetadataResponse", "getSPMetadata", "(", "String", "location", ",", "Boolean", "download", ",", "Boolean", "noSpinner", ")", "throws", "ApiException", "{", "ApiResponse", "<", "GetSPMetadataResponse", ">", "resp", "=", "getSPMetadataWithHttpInfo", "(", ...
Get Metadata Returns exist Metadata xml file. @param location Define SAML location. (required) @param download Define if need download file. (required) @param noSpinner Define if need page reload (optional) @return GetSPMetadataResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Get", "Metadata", "Returns", "exist", "Metadata", "xml", "file", "." ]
train
https://github.com/GenesysPureEngage/provisioning-client-java/blob/1ad594c3767cec83052168e350994f922a26f75e/src/main/java/com/genesys/internal/provisioning/api/SamlSettingsApi.java#L623-L626
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java
TrainingsImpl.createTagAsync
public Observable<Tag> createTagAsync(UUID projectId, String name, CreateTagOptionalParameter createTagOptionalParameter) { return createTagWithServiceResponseAsync(projectId, name, createTagOptionalParameter).map(new Func1<ServiceResponse<Tag>, Tag>() { @Override public Tag call(ServiceResponse<Tag> response) { return response.body(); } }); }
java
public Observable<Tag> createTagAsync(UUID projectId, String name, CreateTagOptionalParameter createTagOptionalParameter) { return createTagWithServiceResponseAsync(projectId, name, createTagOptionalParameter).map(new Func1<ServiceResponse<Tag>, Tag>() { @Override public Tag call(ServiceResponse<Tag> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Tag", ">", "createTagAsync", "(", "UUID", "projectId", ",", "String", "name", ",", "CreateTagOptionalParameter", "createTagOptionalParameter", ")", "{", "return", "createTagWithServiceResponseAsync", "(", "projectId", ",", "name", ",", "c...
Create a tag for the project. @param projectId The project id @param name The tag name @param createTagOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the Tag object
[ "Create", "a", "tag", "for", "the", "project", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L313-L320
UrielCh/ovh-java-sdk
ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java
ApiOvhEmaildomain.domain_account_accountName_DELETE
public OvhTaskPop domain_account_accountName_DELETE(String domain, String accountName) throws IOException { String qPath = "/email/domain/{domain}/account/{accountName}"; StringBuilder sb = path(qPath, domain, accountName); String resp = exec(qPath, "DELETE", sb.toString(), null); return convertTo(resp, OvhTaskPop.class); }
java
public OvhTaskPop domain_account_accountName_DELETE(String domain, String accountName) throws IOException { String qPath = "/email/domain/{domain}/account/{accountName}"; StringBuilder sb = path(qPath, domain, accountName); String resp = exec(qPath, "DELETE", sb.toString(), null); return convertTo(resp, OvhTaskPop.class); }
[ "public", "OvhTaskPop", "domain_account_accountName_DELETE", "(", "String", "domain", ",", "String", "accountName", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/email/domain/{domain}/account/{accountName}\"", ";", "StringBuilder", "sb", "=", "path", "(",...
Delete an existing mailbox in server REST: DELETE /email/domain/{domain}/account/{accountName} @param domain [required] Name of your domain name @param accountName [required] Name of account
[ "Delete", "an", "existing", "mailbox", "in", "server" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java#L856-L861
oboehm/jfachwert
src/main/java/de/jfachwert/post/Postfach.java
Postfach.validate
public static void validate(String postfach) { String[] lines = split(postfach); toNumber(lines[0]); Ort ort = new Ort(lines[1]); if (!ort.getPLZ().isPresent()) { throw new InvalidValueException(postfach, "postal_code"); } }
java
public static void validate(String postfach) { String[] lines = split(postfach); toNumber(lines[0]); Ort ort = new Ort(lines[1]); if (!ort.getPLZ().isPresent()) { throw new InvalidValueException(postfach, "postal_code"); } }
[ "public", "static", "void", "validate", "(", "String", "postfach", ")", "{", "String", "[", "]", "lines", "=", "split", "(", "postfach", ")", ";", "toNumber", "(", "lines", "[", "0", "]", ")", ";", "Ort", "ort", "=", "new", "Ort", "(", "lines", "["...
Zerlegt das uebergebene Postfach in seine Einzelteile und validiert sie. Folgende Heuristiken werden fuer die Zerlegung herangezogen: <ul> <li>Format ist "Postfach, Ort" oder nur "Ort" (mit PLZ)</li> <li>Postfach ist vom Ort durch Komma oder Zeilenvorschub getrennt</li> </ul> @param postfach z.B. "Postfach 98765, 12345 Entenhausen"
[ "Zerlegt", "das", "uebergebene", "Postfach", "in", "seine", "Einzelteile", "und", "validiert", "sie", ".", "Folgende", "Heuristiken", "werden", "fuer", "die", "Zerlegung", "herangezogen", ":", "<ul", ">", "<li", ">", "Format", "ist", "Postfach", "Ort", "oder", ...
train
https://github.com/oboehm/jfachwert/blob/67b513d29e3114c7aee65cd1ea7a5b7e540b0d1b/src/main/java/de/jfachwert/post/Postfach.java#L192-L199
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/serialization/impl/PortablePositionNavigator.java
PortablePositionNavigator.navigateToPathTokenWithNumberQuantifier
private static PortablePosition navigateToPathTokenWithNumberQuantifier( PortableNavigatorContext ctx, PortablePathCursor path) throws IOException { // makes sure that the field type is an array and parses the qantifier validateArrayType(ctx.getCurrentClassDefinition(), ctx.getCurrentFieldDefinition(), path.path()); int index = validateAndGetArrayQuantifierFromCurrentToken(path.token(), path.path()); // reads the array length and checks if the index is in-bound int len = getArrayLengthOfTheField(ctx); if (len == 0) { return emptyAnyPosition(path.isLastToken()); } else if (len == Bits.NULL_ARRAY_LENGTH) { return nilAnyPosition(path.isLastToken()); } else if (index >= len) { return nilAnyPosition(path.isLastToken()); } else { // when index in-bound if (path.isLastToken()) { // if it's a token that's on the last position we calculate its direct access position and return it for // reading in the value reader. return createPositionForReadAccess(ctx, path, index); } else if (ctx.isCurrentFieldOfType(FieldType.PORTABLE_ARRAY)) { // otherwise we advance only if the type is a portable_array. We cannot navigate further in a primitive // type and the portable arrays may store portable or primitive types only. navigateContextToNextPortableTokenFromPortableArrayCell(ctx, path, index); } } return null; }
java
private static PortablePosition navigateToPathTokenWithNumberQuantifier( PortableNavigatorContext ctx, PortablePathCursor path) throws IOException { // makes sure that the field type is an array and parses the qantifier validateArrayType(ctx.getCurrentClassDefinition(), ctx.getCurrentFieldDefinition(), path.path()); int index = validateAndGetArrayQuantifierFromCurrentToken(path.token(), path.path()); // reads the array length and checks if the index is in-bound int len = getArrayLengthOfTheField(ctx); if (len == 0) { return emptyAnyPosition(path.isLastToken()); } else if (len == Bits.NULL_ARRAY_LENGTH) { return nilAnyPosition(path.isLastToken()); } else if (index >= len) { return nilAnyPosition(path.isLastToken()); } else { // when index in-bound if (path.isLastToken()) { // if it's a token that's on the last position we calculate its direct access position and return it for // reading in the value reader. return createPositionForReadAccess(ctx, path, index); } else if (ctx.isCurrentFieldOfType(FieldType.PORTABLE_ARRAY)) { // otherwise we advance only if the type is a portable_array. We cannot navigate further in a primitive // type and the portable arrays may store portable or primitive types only. navigateContextToNextPortableTokenFromPortableArrayCell(ctx, path, index); } } return null; }
[ "private", "static", "PortablePosition", "navigateToPathTokenWithNumberQuantifier", "(", "PortableNavigatorContext", "ctx", ",", "PortablePathCursor", "path", ")", "throws", "IOException", "{", "// makes sure that the field type is an array and parses the qantifier", "validateArrayType...
Token with [number] quantifier. It means we are navigating in an array cell.
[ "Token", "with", "[", "number", "]", "quantifier", ".", "It", "means", "we", "are", "navigating", "in", "an", "array", "cell", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/serialization/impl/PortablePositionNavigator.java#L332-L359
VoltDB/voltdb
src/frontend/org/voltdb/jni/ExecutionEngineJNI.java
ExecutionEngineJNI.releaseLargeTempTableBlock
public boolean releaseLargeTempTableBlock(long siteId, long blockCounter) { LargeBlockTask task = LargeBlockTask.getReleaseTask(new BlockId(siteId, blockCounter)); return executeLargeBlockTaskSynchronously(task); }
java
public boolean releaseLargeTempTableBlock(long siteId, long blockCounter) { LargeBlockTask task = LargeBlockTask.getReleaseTask(new BlockId(siteId, blockCounter)); return executeLargeBlockTaskSynchronously(task); }
[ "public", "boolean", "releaseLargeTempTableBlock", "(", "long", "siteId", ",", "long", "blockCounter", ")", "{", "LargeBlockTask", "task", "=", "LargeBlockTask", ".", "getReleaseTask", "(", "new", "BlockId", "(", "siteId", ",", "blockCounter", ")", ")", ";", "re...
Delete the block with the given id from disk. @param siteId The originating site id of the block to release @param blockCounter The serial number of the block to release @return True if the operation succeeded, and false otherwise
[ "Delete", "the", "block", "with", "the", "given", "id", "from", "disk", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jni/ExecutionEngineJNI.java#L904-L907
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/proxyhandler/Neighbours.java
Neighbours.createBus
private BusGroup createBus(String busId) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createBus", busId); // Create a new group and add it to the list. boolean isLocalBus = busId.equals(_localBusName); final BusGroup group = new BusGroup(busId, _proxyHandler, isLocalBus); final BusGroup[] tempBuses = _buses; _buses = new BusGroup[tempBuses.length + 1]; System.arraycopy(tempBuses, 0, _buses, 0, tempBuses.length); _buses[tempBuses.length] = group; // Do not need to propogate local subs to foreign buses // addSubscriptionsToBus(group, busId); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "createBus", group); return group; }
java
private BusGroup createBus(String busId) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createBus", busId); // Create a new group and add it to the list. boolean isLocalBus = busId.equals(_localBusName); final BusGroup group = new BusGroup(busId, _proxyHandler, isLocalBus); final BusGroup[] tempBuses = _buses; _buses = new BusGroup[tempBuses.length + 1]; System.arraycopy(tempBuses, 0, _buses, 0, tempBuses.length); _buses[tempBuses.length] = group; // Do not need to propogate local subs to foreign buses // addSubscriptionsToBus(group, busId); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "createBus", group); return group; }
[ "private", "BusGroup", "createBus", "(", "String", "busId", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "entry", "(", "tc", ",", "\"createBus\"", ",", "busId",...
Creates a BusGroup with the given name. As this is a new Bus, the current subscription state in the MatchSpace is read and assigned to the Bus as active subscriptions. @param busId The name of the Busgroup @return The new BusGroup object representing the bus.
[ "Creates", "a", "BusGroup", "with", "the", "given", "name", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/proxyhandler/Neighbours.java#L1127-L1147
bwkimmel/jdcp
jdcp-worker/src/main/java/ca/eandb/jdcp/worker/CachingJobServiceClassLoaderStrategy.java
CachingJobServiceClassLoaderStrategy.endLookup
private synchronized void endLookup(Map<String, String> pending, String name) { String canonical = pending.remove(name); if (canonical != null) { canonical.notifyAll(); } }
java
private synchronized void endLookup(Map<String, String> pending, String name) { String canonical = pending.remove(name); if (canonical != null) { canonical.notifyAll(); } }
[ "private", "synchronized", "void", "endLookup", "(", "Map", "<", "String", ",", "String", ">", "pending", ",", "String", "name", ")", "{", "String", "canonical", "=", "pending", ".", "remove", "(", "name", ")", ";", "if", "(", "canonical", "!=", "null", ...
Signals that the current thread is done looking up a class digest or definition. @param pending The <code>Map</code> in which to store pending lookups. @param name The name of the class that was looked up.
[ "Signals", "that", "the", "current", "thread", "is", "done", "looking", "up", "a", "class", "digest", "or", "definition", "." ]
train
https://github.com/bwkimmel/jdcp/blob/630c5150c245054e2556ff370f4bad2ec793dfb7/jdcp-worker/src/main/java/ca/eandb/jdcp/worker/CachingJobServiceClassLoaderStrategy.java#L145-L150
lagom/lagom
service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/RequestHeader.java
RequestHeader.clearPrincipal
public RequestHeader clearPrincipal() { return new RequestHeader(method, uri, protocol, acceptedResponseProtocols, Optional.empty(), headers, lowercaseHeaders); }
java
public RequestHeader clearPrincipal() { return new RequestHeader(method, uri, protocol, acceptedResponseProtocols, Optional.empty(), headers, lowercaseHeaders); }
[ "public", "RequestHeader", "clearPrincipal", "(", ")", "{", "return", "new", "RequestHeader", "(", "method", ",", "uri", ",", "protocol", ",", "acceptedResponseProtocols", ",", "Optional", ".", "empty", "(", ")", ",", "headers", ",", "lowercaseHeaders", ")", "...
Return a copy of this request header with the principal cleared. @return A copy of this request header.
[ "Return", "a", "copy", "of", "this", "request", "header", "with", "the", "principal", "cleared", "." ]
train
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/RequestHeader.java#L137-L139
JM-Lab/utils-java8
src/main/java/kr/jm/utils/time/JMTimeUtil.java
JMTimeUtil.getCurrentTimestamp
public static String getCurrentTimestamp(String timeFormat, String zoneId) { return getTime(System.currentTimeMillis(), timeFormat, zoneId); }
java
public static String getCurrentTimestamp(String timeFormat, String zoneId) { return getTime(System.currentTimeMillis(), timeFormat, zoneId); }
[ "public", "static", "String", "getCurrentTimestamp", "(", "String", "timeFormat", ",", "String", "zoneId", ")", "{", "return", "getTime", "(", "System", ".", "currentTimeMillis", "(", ")", ",", "timeFormat", ",", "zoneId", ")", ";", "}" ]
Gets current timestamp. @param timeFormat the time format @param zoneId the zone id @return the current timestamp
[ "Gets", "current", "timestamp", "." ]
train
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/time/JMTimeUtil.java#L178-L180
OpenLiberty/open-liberty
dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/shared/renderkit/html/HtmlTableRendererBase.java
HtmlTableRendererBase.beforeBody
protected void beforeBody(FacesContext facesContext, UIData uiData) throws IOException { ResponseWriter writer = facesContext.getResponseWriter(); renderCaptionFacet(facesContext, writer, uiData); renderColgroupsFacet(facesContext, writer, uiData); renderFacet(facesContext, writer, uiData, true); renderFacet(facesContext, writer, uiData, false); }
java
protected void beforeBody(FacesContext facesContext, UIData uiData) throws IOException { ResponseWriter writer = facesContext.getResponseWriter(); renderCaptionFacet(facesContext, writer, uiData); renderColgroupsFacet(facesContext, writer, uiData); renderFacet(facesContext, writer, uiData, true); renderFacet(facesContext, writer, uiData, false); }
[ "protected", "void", "beforeBody", "(", "FacesContext", "facesContext", ",", "UIData", "uiData", ")", "throws", "IOException", "{", "ResponseWriter", "writer", "=", "facesContext", ".", "getResponseWriter", "(", ")", ";", "renderCaptionFacet", "(", "facesContext", "...
Perform any operations necessary after TABLE start tag is output but before the TBODY start tag. <p> This method generates the THEAD/TFOOT sections of a table if there are any header or footer facets defined on the table or on any child UIColumn component. @param facesContext the <code>FacesContext</code>. @param uiData the <code>UIData</code> being rendered.
[ "Perform", "any", "operations", "necessary", "after", "TABLE", "start", "tag", "is", "output", "but", "before", "the", "TBODY", "start", "tag", ".", "<p", ">", "This", "method", "generates", "the", "THEAD", "/", "TFOOT", "sections", "of", "a", "table", "if...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/shared/renderkit/html/HtmlTableRendererBase.java#L763-L771
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/CharInfo.java
CharInfo.defineEntity
private boolean defineEntity(String name, char value) { StringBuffer sb = new StringBuffer("&"); sb.append(name); sb.append(';'); String entityString = sb.toString(); boolean extra = defineChar2StringMapping(entityString, value); return extra; }
java
private boolean defineEntity(String name, char value) { StringBuffer sb = new StringBuffer("&"); sb.append(name); sb.append(';'); String entityString = sb.toString(); boolean extra = defineChar2StringMapping(entityString, value); return extra; }
[ "private", "boolean", "defineEntity", "(", "String", "name", ",", "char", "value", ")", "{", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", "\"&\"", ")", ";", "sb", ".", "append", "(", "name", ")", ";", "sb", ".", "append", "(", "'", "'", ")"...
Defines a new character reference. The reference's name and value are supplied. Nothing happens if the character reference is already defined. <p>Unlike internal entities, character references are a string to single character mapping. They are used to map non-ASCII characters both on parsing and printing, primarily for HTML documents. '&amp;lt;' is an example of a character reference.</p> @param name The entity's name @param value The entity's value @return true if the mapping is not one of: <ul> <li> '<' to "&lt;" <li> '>' to "&gt;" <li> '&' to "&amp;" <li> '"' to "&quot;" </ul>
[ "Defines", "a", "new", "character", "reference", ".", "The", "reference", "s", "name", "and", "value", "are", "supplied", ".", "Nothing", "happens", "if", "the", "character", "reference", "is", "already", "defined", ".", "<p", ">", "Unlike", "internal", "ent...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/CharInfo.java#L373-L382
mgormley/pacaya
src/main/java/edu/jhu/pacaya/parse/cky/chart/Chart.java
Chart.getNewChart
private static ChartCell[][] getNewChart(Sentence sentence, CnfGrammar grammar, ChartCellType cellType, ParseType parseType, ChartCellConstraint constraint) { ChartCell[][] chart = new ChartCell[sentence.size()][sentence.size()+1]; for (int i = 0; i < chart.length; i++) { for (int j = i+1; j < chart[i].length; j++) { if (parseType == ParseType.INSIDE && cellType != ChartCellType.FULL) { throw new RuntimeException("Inside algorithm not implemented for cell type: " + cellType); } ChartCell cell; switch(cellType) { case SINGLE_HASH: chart[i][j] = new SingleHashChartCell(grammar, false); break; case SINGLE_HASH_BREAK_TIES: chart[i][j] = new SingleHashChartCell(grammar, true); break; case CONSTRAINED_SINGLE: cell = new SingleHashChartCell(grammar, true); chart[i][j] = new ConstrainedChartCell(i, j, cell, constraint, sentence); break; case DOUBLE_HASH: chart[i][j] = new DoubleHashChartCell(grammar); break; case FULL: chart[i][j] = new FullChartCell(i, j, grammar, parseType); break; case FULL_BREAK_TIES: chart[i][j] = new FullTieBreakerChartCell(grammar, true); break; case CONSTRAINED_FULL: cell = new FullTieBreakerChartCell(grammar, true); chart[i][j] = new ConstrainedChartCell(i, j, cell, constraint, sentence); break; default: throw new RuntimeException("not implemented for " + cellType); } } } return chart; }
java
private static ChartCell[][] getNewChart(Sentence sentence, CnfGrammar grammar, ChartCellType cellType, ParseType parseType, ChartCellConstraint constraint) { ChartCell[][] chart = new ChartCell[sentence.size()][sentence.size()+1]; for (int i = 0; i < chart.length; i++) { for (int j = i+1; j < chart[i].length; j++) { if (parseType == ParseType.INSIDE && cellType != ChartCellType.FULL) { throw new RuntimeException("Inside algorithm not implemented for cell type: " + cellType); } ChartCell cell; switch(cellType) { case SINGLE_HASH: chart[i][j] = new SingleHashChartCell(grammar, false); break; case SINGLE_HASH_BREAK_TIES: chart[i][j] = new SingleHashChartCell(grammar, true); break; case CONSTRAINED_SINGLE: cell = new SingleHashChartCell(grammar, true); chart[i][j] = new ConstrainedChartCell(i, j, cell, constraint, sentence); break; case DOUBLE_HASH: chart[i][j] = new DoubleHashChartCell(grammar); break; case FULL: chart[i][j] = new FullChartCell(i, j, grammar, parseType); break; case FULL_BREAK_TIES: chart[i][j] = new FullTieBreakerChartCell(grammar, true); break; case CONSTRAINED_FULL: cell = new FullTieBreakerChartCell(grammar, true); chart[i][j] = new ConstrainedChartCell(i, j, cell, constraint, sentence); break; default: throw new RuntimeException("not implemented for " + cellType); } } } return chart; }
[ "private", "static", "ChartCell", "[", "]", "[", "]", "getNewChart", "(", "Sentence", "sentence", ",", "CnfGrammar", "grammar", ",", "ChartCellType", "cellType", ",", "ParseType", "parseType", ",", "ChartCellConstraint", "constraint", ")", "{", "ChartCell", "[", ...
Gets a new chart of the appropriate size for the sentence, specific to this grammar, and with cells of the specified type.
[ "Gets", "a", "new", "chart", "of", "the", "appropriate", "size", "for", "the", "sentence", "specific", "to", "this", "grammar", "and", "with", "cells", "of", "the", "specified", "type", "." ]
train
https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/parse/cky/chart/Chart.java#L93-L131
scireum/s3ninja
src/main/java/ninja/Aws4HashCalculator.java
Aws4HashCalculator.computeHash
public String computeHash(WebContext ctx, String pathPrefix) throws Exception { Matcher matcher = AWS_AUTH4_PATTERN.matcher(ctx.getHeaderValue("Authorization").asString("")); if (!matcher.matches()) { // If the header doesn't match, let's try an URL parameter as we might be processing a presigned URL matcher = X_AMZ_CREDENTIAL_PATTERN.matcher(ctx.get("X-Amz-Credential").asString("")); if (!matcher.matches()) { throw new IllegalArgumentException("Unknown AWS4 auth pattern"); } } String date = matcher.group(2); String region = matcher.group(3); String service = matcher.group(4); String serviceType = matcher.group(5); // For header based requests, the signed headers are in the "Credentials" header, for presigned URLs // an extra parameter is given... String signedHeaders = matcher.groupCount() == 7 ? matcher.group(6) : ctx.get("X-Amz-SignedHeaders").asString(); byte[] dateKey = hmacSHA256(("AWS4" + storage.getAwsSecretKey()).getBytes(Charsets.UTF_8), date); byte[] dateRegionKey = hmacSHA256(dateKey, region); byte[] dateRegionServiceKey = hmacSHA256(dateRegionKey, service); byte[] signingKey = hmacSHA256(dateRegionServiceKey, serviceType); byte[] signedData = hmacSHA256(signingKey, buildStringToSign(ctx, signedHeaders, region, service, serviceType)); return BaseEncoding.base16().lowerCase().encode(signedData); }
java
public String computeHash(WebContext ctx, String pathPrefix) throws Exception { Matcher matcher = AWS_AUTH4_PATTERN.matcher(ctx.getHeaderValue("Authorization").asString("")); if (!matcher.matches()) { // If the header doesn't match, let's try an URL parameter as we might be processing a presigned URL matcher = X_AMZ_CREDENTIAL_PATTERN.matcher(ctx.get("X-Amz-Credential").asString("")); if (!matcher.matches()) { throw new IllegalArgumentException("Unknown AWS4 auth pattern"); } } String date = matcher.group(2); String region = matcher.group(3); String service = matcher.group(4); String serviceType = matcher.group(5); // For header based requests, the signed headers are in the "Credentials" header, for presigned URLs // an extra parameter is given... String signedHeaders = matcher.groupCount() == 7 ? matcher.group(6) : ctx.get("X-Amz-SignedHeaders").asString(); byte[] dateKey = hmacSHA256(("AWS4" + storage.getAwsSecretKey()).getBytes(Charsets.UTF_8), date); byte[] dateRegionKey = hmacSHA256(dateKey, region); byte[] dateRegionServiceKey = hmacSHA256(dateRegionKey, service); byte[] signingKey = hmacSHA256(dateRegionServiceKey, serviceType); byte[] signedData = hmacSHA256(signingKey, buildStringToSign(ctx, signedHeaders, region, service, serviceType)); return BaseEncoding.base16().lowerCase().encode(signedData); }
[ "public", "String", "computeHash", "(", "WebContext", "ctx", ",", "String", "pathPrefix", ")", "throws", "Exception", "{", "Matcher", "matcher", "=", "AWS_AUTH4_PATTERN", ".", "matcher", "(", "ctx", ".", "getHeaderValue", "(", "\"Authorization\"", ")", ".", "asS...
Computes the authentication hash as specified by the AWS SDK for verification purposes. @param ctx the current request to fetch parameters from @param pathPrefix the path prefix to preped to the {@link S3Dispatcher#getEffectiveURI(WebContext) effective URI} of the request @return the computes hash value @throws Exception when hashing fails
[ "Computes", "the", "authentication", "hash", "as", "specified", "by", "the", "AWS", "SDK", "for", "verification", "purposes", "." ]
train
https://github.com/scireum/s3ninja/blob/445eec55c91780267a7f987818b3fedecae009c5/src/main/java/ninja/Aws4HashCalculator.java#L68-L95
Azure/azure-sdk-for-java
cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabasesInner.java
DatabasesInner.listMetricDefinitions
public List<MetricDefinitionInner> listMetricDefinitions(String resourceGroupName, String accountName, String databaseRid) { return listMetricDefinitionsWithServiceResponseAsync(resourceGroupName, accountName, databaseRid).toBlocking().single().body(); }
java
public List<MetricDefinitionInner> listMetricDefinitions(String resourceGroupName, String accountName, String databaseRid) { return listMetricDefinitionsWithServiceResponseAsync(resourceGroupName, accountName, databaseRid).toBlocking().single().body(); }
[ "public", "List", "<", "MetricDefinitionInner", ">", "listMetricDefinitions", "(", "String", "resourceGroupName", ",", "String", "accountName", ",", "String", "databaseRid", ")", "{", "return", "listMetricDefinitionsWithServiceResponseAsync", "(", "resourceGroupName", ",", ...
Retrieves metric defintions for the given database. @param resourceGroupName Name of an Azure resource group. @param accountName Cosmos DB database account name. @param databaseRid Cosmos DB database rid. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the List&lt;MetricDefinitionInner&gt; object if successful.
[ "Retrieves", "metric", "defintions", "for", "the", "given", "database", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabasesInner.java#L379-L381
SonarSource/sonarqube
server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueIndex.java
IssueIndex.configureRouting
private static void configureRouting(IssueQuery query, SearchOptions options, SearchRequestBuilder requestBuilder) { Collection<String> uuids = query.projectUuids(); if (!uuids.isEmpty() && options.getFacets().isEmpty()) { requestBuilder.setRouting(uuids.stream().map(AuthorizationDoc::idOf).toArray(String[]::new)); } }
java
private static void configureRouting(IssueQuery query, SearchOptions options, SearchRequestBuilder requestBuilder) { Collection<String> uuids = query.projectUuids(); if (!uuids.isEmpty() && options.getFacets().isEmpty()) { requestBuilder.setRouting(uuids.stream().map(AuthorizationDoc::idOf).toArray(String[]::new)); } }
[ "private", "static", "void", "configureRouting", "(", "IssueQuery", "query", ",", "SearchOptions", "options", ",", "SearchRequestBuilder", "requestBuilder", ")", "{", "Collection", "<", "String", ">", "uuids", "=", "query", ".", "projectUuids", "(", ")", ";", "i...
Optimization - do not send ES request to all shards when scope is restricted to a set of projects. Because project UUID is used for routing, the request can be sent to only the shards containing the specified projects. Note that sticky facets may involve all projects, so this optimization must be disabled when facets are enabled.
[ "Optimization", "-", "do", "not", "send", "ES", "request", "to", "all", "shards", "when", "scope", "is", "restricted", "to", "a", "set", "of", "projects", ".", "Because", "project", "UUID", "is", "used", "for", "routing", "the", "request", "can", "be", "...
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueIndex.java#L319-L324