id int32 0 165k | repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1 value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 |
|---|---|---|---|---|---|---|---|---|---|---|---|
32,700 | pac4j/pac4j | pac4j-http/src/main/java/org/pac4j/http/credentials/DigestCredentials.java | DigestCredentials.calculateServerDigest | public String calculateServerDigest(boolean passwordAlreadyEncoded, String password) {
return generateDigest(passwordAlreadyEncoded, username,
realm, password, httpMethod, uri, qop, nonce, nc, cnonce);
} | java | public String calculateServerDigest(boolean passwordAlreadyEncoded, String password) {
return generateDigest(passwordAlreadyEncoded, username,
realm, password, httpMethod, uri, qop, nonce, nc, cnonce);
} | [
"public",
"String",
"calculateServerDigest",
"(",
"boolean",
"passwordAlreadyEncoded",
",",
"String",
"password",
")",
"{",
"return",
"generateDigest",
"(",
"passwordAlreadyEncoded",
",",
"username",
",",
"realm",
",",
"password",
",",
"httpMethod",
",",
"uri",
",",... | This calculates the server digest value based on user stored password. If the server stores password in clear format
then passwordAlreadyEncoded should be false. If the server stores the password in ha1, digest then the
passwordAlreadyEncoded should be true.
@param passwordAlreadyEncoded false if the server stored password is in clear, true otherwise
@param password user password stored server-side
@return digest value. This value must match the client "response" value in the Authorization http header
for a successful digest authentication | [
"This",
"calculates",
"the",
"server",
"digest",
"value",
"based",
"on",
"user",
"stored",
"password",
".",
"If",
"the",
"server",
"stores",
"password",
"in",
"clear",
"format",
"then",
"passwordAlreadyEncoded",
"should",
"be",
"false",
".",
"If",
"the",
"serv... | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-http/src/main/java/org/pac4j/http/credentials/DigestCredentials.java#L68-L71 |
32,701 | pac4j/pac4j | pac4j-http/src/main/java/org/pac4j/http/credentials/DigestCredentials.java | DigestCredentials.generateDigest | private String generateDigest(boolean passwordAlreadyEncoded, String username,
String realm, String password, String httpMethod, String uri, String qop,
String nonce, String nc, String cnonce) {
String ha1;
String a2 = httpMethod + ":" + uri;
String ha2 = CredentialUtil.encryptMD5(a2);
if (passwordAlreadyEncoded) {
ha1 = password;
} else {
ha1 = CredentialUtil.encryptMD5(username + ":" + realm + ":" +password);
}
String digest;
if (qop == null) {
digest = CredentialUtil.encryptMD5(ha1, nonce + ":" + ha2);
} else if ("auth".equals(qop)) {
digest = CredentialUtil.encryptMD5(ha1, nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2);
} else {
throw new TechnicalException("Invalid qop: '" + qop + "'");
}
return digest;
} | java | private String generateDigest(boolean passwordAlreadyEncoded, String username,
String realm, String password, String httpMethod, String uri, String qop,
String nonce, String nc, String cnonce) {
String ha1;
String a2 = httpMethod + ":" + uri;
String ha2 = CredentialUtil.encryptMD5(a2);
if (passwordAlreadyEncoded) {
ha1 = password;
} else {
ha1 = CredentialUtil.encryptMD5(username + ":" + realm + ":" +password);
}
String digest;
if (qop == null) {
digest = CredentialUtil.encryptMD5(ha1, nonce + ":" + ha2);
} else if ("auth".equals(qop)) {
digest = CredentialUtil.encryptMD5(ha1, nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2);
} else {
throw new TechnicalException("Invalid qop: '" + qop + "'");
}
return digest;
} | [
"private",
"String",
"generateDigest",
"(",
"boolean",
"passwordAlreadyEncoded",
",",
"String",
"username",
",",
"String",
"realm",
",",
"String",
"password",
",",
"String",
"httpMethod",
",",
"String",
"uri",
",",
"String",
"qop",
",",
"String",
"nonce",
",",
... | generate digest token based on RFC 2069 and RFC 2617 guidelines
@return digest token | [
"generate",
"digest",
"token",
"based",
"on",
"RFC",
"2069",
"and",
"RFC",
"2617",
"guidelines"
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-http/src/main/java/org/pac4j/http/credentials/DigestCredentials.java#L78-L102 |
32,702 | pac4j/pac4j | pac4j-oauth/src/main/java/org/pac4j/oauth/profile/creator/OAuthProfileCreator.java | OAuthProfileCreator.retrieveUserProfileFromToken | protected Optional<UserProfile> retrieveUserProfileFromToken(final WebContext context, final T accessToken) {
final OAuthProfileDefinition<U, T, O> profileDefinition = configuration.getProfileDefinition();
final String profileUrl = profileDefinition.getProfileUrl(accessToken, configuration);
final S service = this.configuration.buildService(context, client, null);
final String body = sendRequestForData(service, accessToken, profileUrl, profileDefinition.getProfileVerb());
logger.info("UserProfile: " + body);
if (body == null) {
throw new HttpCommunicationException("No data found for accessToken: " + accessToken);
}
final U profile = (U) configuration.getProfileDefinition().extractUserProfile(body);
addAccessTokenToProfile(profile, accessToken);
return Optional.of(profile);
} | java | protected Optional<UserProfile> retrieveUserProfileFromToken(final WebContext context, final T accessToken) {
final OAuthProfileDefinition<U, T, O> profileDefinition = configuration.getProfileDefinition();
final String profileUrl = profileDefinition.getProfileUrl(accessToken, configuration);
final S service = this.configuration.buildService(context, client, null);
final String body = sendRequestForData(service, accessToken, profileUrl, profileDefinition.getProfileVerb());
logger.info("UserProfile: " + body);
if (body == null) {
throw new HttpCommunicationException("No data found for accessToken: " + accessToken);
}
final U profile = (U) configuration.getProfileDefinition().extractUserProfile(body);
addAccessTokenToProfile(profile, accessToken);
return Optional.of(profile);
} | [
"protected",
"Optional",
"<",
"UserProfile",
">",
"retrieveUserProfileFromToken",
"(",
"final",
"WebContext",
"context",
",",
"final",
"T",
"accessToken",
")",
"{",
"final",
"OAuthProfileDefinition",
"<",
"U",
",",
"T",
",",
"O",
">",
"profileDefinition",
"=",
"... | Retrieve the user profile from the access token.
@param context the web context
@param accessToken the access token
@return the user profile | [
"Retrieve",
"the",
"user",
"profile",
"from",
"the",
"access",
"token",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/creator/OAuthProfileCreator.java#L83-L95 |
32,703 | pac4j/pac4j | pac4j-oauth/src/main/java/org/pac4j/oauth/profile/creator/OAuthProfileCreator.java | OAuthProfileCreator.sendRequestForData | protected String sendRequestForData(final S service, final T accessToken, final String dataUrl, Verb verb) {
logger.debug("accessToken: {} / dataUrl: {}", accessToken, dataUrl);
final long t0 = System.currentTimeMillis();
final OAuthRequest request = createOAuthRequest(dataUrl, verb);
signRequest(service, accessToken, request);
final String body;
final int code;
try {
Response response = service.execute(request);
code = response.getCode();
body = response.getBody();
} catch (final IOException | InterruptedException | ExecutionException e) {
throw new HttpCommunicationException("Error getting body: " + e.getMessage());
}
final long t1 = System.currentTimeMillis();
logger.debug("Request took: " + (t1 - t0) + " ms for: " + dataUrl);
logger.debug("response code: {} / response body: {}", code, body);
if (code != 200) {
throw new HttpCommunicationException(code, body);
}
return body;
} | java | protected String sendRequestForData(final S service, final T accessToken, final String dataUrl, Verb verb) {
logger.debug("accessToken: {} / dataUrl: {}", accessToken, dataUrl);
final long t0 = System.currentTimeMillis();
final OAuthRequest request = createOAuthRequest(dataUrl, verb);
signRequest(service, accessToken, request);
final String body;
final int code;
try {
Response response = service.execute(request);
code = response.getCode();
body = response.getBody();
} catch (final IOException | InterruptedException | ExecutionException e) {
throw new HttpCommunicationException("Error getting body: " + e.getMessage());
}
final long t1 = System.currentTimeMillis();
logger.debug("Request took: " + (t1 - t0) + " ms for: " + dataUrl);
logger.debug("response code: {} / response body: {}", code, body);
if (code != 200) {
throw new HttpCommunicationException(code, body);
}
return body;
} | [
"protected",
"String",
"sendRequestForData",
"(",
"final",
"S",
"service",
",",
"final",
"T",
"accessToken",
",",
"final",
"String",
"dataUrl",
",",
"Verb",
"verb",
")",
"{",
"logger",
".",
"debug",
"(",
"\"accessToken: {} / dataUrl: {}\"",
",",
"accessToken",
"... | Make a request to get the data of the authenticated user for the provider.
@param service the OAuth service
@param accessToken the access token
@param dataUrl url of the data
@param verb method used to request data
@return the user data response | [
"Make",
"a",
"request",
"to",
"get",
"the",
"data",
"of",
"the",
"authenticated",
"user",
"for",
"the",
"provider",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/creator/OAuthProfileCreator.java#L106-L127 |
32,704 | pac4j/pac4j | pac4j-oauth/src/main/java/org/pac4j/oauth/profile/facebook/FacebookProfileCreator.java | FacebookProfileCreator.addExchangeToken | protected String addExchangeToken(final String url, final OAuth2AccessToken accessToken) {
final FacebookProfileDefinition profileDefinition = (FacebookProfileDefinition) configuration.getProfileDefinition();
final FacebookConfiguration facebookConfiguration = (FacebookConfiguration) configuration;
String computedUrl = url;
if (facebookConfiguration.isUseAppsecretProof()) {
computedUrl = profileDefinition.computeAppSecretProof(computedUrl, accessToken, facebookConfiguration);
}
return CommonHelper.addParameter(computedUrl, EXCHANGE_TOKEN_PARAMETER, accessToken.getAccessToken());
} | java | protected String addExchangeToken(final String url, final OAuth2AccessToken accessToken) {
final FacebookProfileDefinition profileDefinition = (FacebookProfileDefinition) configuration.getProfileDefinition();
final FacebookConfiguration facebookConfiguration = (FacebookConfiguration) configuration;
String computedUrl = url;
if (facebookConfiguration.isUseAppsecretProof()) {
computedUrl = profileDefinition.computeAppSecretProof(computedUrl, accessToken, facebookConfiguration);
}
return CommonHelper.addParameter(computedUrl, EXCHANGE_TOKEN_PARAMETER, accessToken.getAccessToken());
} | [
"protected",
"String",
"addExchangeToken",
"(",
"final",
"String",
"url",
",",
"final",
"OAuth2AccessToken",
"accessToken",
")",
"{",
"final",
"FacebookProfileDefinition",
"profileDefinition",
"=",
"(",
"FacebookProfileDefinition",
")",
"configuration",
".",
"getProfileDe... | Adds the token to the URL in question. If we require appsecret_proof, then this method
will also add the appsecret_proof parameter to the URL, as Facebook expects.
@param url the URL to modify
@param accessToken the token we're passing back and forth
@return url with additional parameter(s) | [
"Adds",
"the",
"token",
"to",
"the",
"URL",
"in",
"question",
".",
"If",
"we",
"require",
"appsecret_proof",
"then",
"this",
"method",
"will",
"also",
"add",
"the",
"appsecret_proof",
"parameter",
"to",
"the",
"URL",
"as",
"Facebook",
"expects",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/facebook/FacebookProfileCreator.java#L92-L100 |
32,705 | pac4j/pac4j | pac4j-jwt/src/main/java/org/pac4j/jwt/util/JWKHelper.java | JWKHelper.buildSecretFromJwk | public static String buildSecretFromJwk(final String json) {
CommonHelper.assertNotBlank("json", json);
try {
final OctetSequenceKey octetSequenceKey = OctetSequenceKey.parse(json);
return new String(octetSequenceKey.toByteArray(), "UTF-8");
} catch (final UnsupportedEncodingException | ParseException e) {
throw new TechnicalException(e);
}
} | java | public static String buildSecretFromJwk(final String json) {
CommonHelper.assertNotBlank("json", json);
try {
final OctetSequenceKey octetSequenceKey = OctetSequenceKey.parse(json);
return new String(octetSequenceKey.toByteArray(), "UTF-8");
} catch (final UnsupportedEncodingException | ParseException e) {
throw new TechnicalException(e);
}
} | [
"public",
"static",
"String",
"buildSecretFromJwk",
"(",
"final",
"String",
"json",
")",
"{",
"CommonHelper",
".",
"assertNotBlank",
"(",
"\"json\"",
",",
"json",
")",
";",
"try",
"{",
"final",
"OctetSequenceKey",
"octetSequenceKey",
"=",
"OctetSequenceKey",
".",
... | Build the secret from the JWK JSON.
@param json the json
@return the secret | [
"Build",
"the",
"secret",
"from",
"the",
"JWK",
"JSON",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-jwt/src/main/java/org/pac4j/jwt/util/JWKHelper.java#L28-L37 |
32,706 | pac4j/pac4j | pac4j-jwt/src/main/java/org/pac4j/jwt/util/JWKHelper.java | JWKHelper.buildRSAKeyPairFromJwk | public static KeyPair buildRSAKeyPairFromJwk(final String json) {
CommonHelper.assertNotBlank("json", json);
try {
final RSAKey rsaKey = RSAKey.parse(json);
return rsaKey.toKeyPair();
} catch (final JOSEException | ParseException e) {
throw new TechnicalException(e);
}
} | java | public static KeyPair buildRSAKeyPairFromJwk(final String json) {
CommonHelper.assertNotBlank("json", json);
try {
final RSAKey rsaKey = RSAKey.parse(json);
return rsaKey.toKeyPair();
} catch (final JOSEException | ParseException e) {
throw new TechnicalException(e);
}
} | [
"public",
"static",
"KeyPair",
"buildRSAKeyPairFromJwk",
"(",
"final",
"String",
"json",
")",
"{",
"CommonHelper",
".",
"assertNotBlank",
"(",
"\"json\"",
",",
"json",
")",
";",
"try",
"{",
"final",
"RSAKey",
"rsaKey",
"=",
"RSAKey",
".",
"parse",
"(",
"json... | Build the RSA key pair from the JWK JSON.
@param json the json
@return the key pair | [
"Build",
"the",
"RSA",
"key",
"pair",
"from",
"the",
"JWK",
"JSON",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-jwt/src/main/java/org/pac4j/jwt/util/JWKHelper.java#L45-L54 |
32,707 | pac4j/pac4j | pac4j-jwt/src/main/java/org/pac4j/jwt/util/JWKHelper.java | JWKHelper.buildECKeyPairFromJwk | public static KeyPair buildECKeyPairFromJwk(final String json) {
CommonHelper.assertNotBlank("json", json);
try {
final ECKey ecKey = ECKey.parse(json);
return ecKey.toKeyPair();
} catch (final JOSEException | ParseException e) {
throw new TechnicalException(e);
}
} | java | public static KeyPair buildECKeyPairFromJwk(final String json) {
CommonHelper.assertNotBlank("json", json);
try {
final ECKey ecKey = ECKey.parse(json);
return ecKey.toKeyPair();
} catch (final JOSEException | ParseException e) {
throw new TechnicalException(e);
}
} | [
"public",
"static",
"KeyPair",
"buildECKeyPairFromJwk",
"(",
"final",
"String",
"json",
")",
"{",
"CommonHelper",
".",
"assertNotBlank",
"(",
"\"json\"",
",",
"json",
")",
";",
"try",
"{",
"final",
"ECKey",
"ecKey",
"=",
"ECKey",
".",
"parse",
"(",
"json",
... | Build the EC key pair from the JWK JSON.
@param json the json
@return the key pair | [
"Build",
"the",
"EC",
"key",
"pair",
"from",
"the",
"JWK",
"JSON",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-jwt/src/main/java/org/pac4j/jwt/util/JWKHelper.java#L62-L71 |
32,708 | pac4j/pac4j | pac4j-core/src/main/java/org/pac4j/core/profile/ProfileHelper.java | ProfileHelper.isTypedIdOf | public static boolean isTypedIdOf(final String id, final Class<? extends CommonProfile> clazz) {
if (id != null && clazz != null) {
return id.startsWith(clazz.getName() + CommonProfile.SEPARATOR);
}
return false;
} | java | public static boolean isTypedIdOf(final String id, final Class<? extends CommonProfile> clazz) {
if (id != null && clazz != null) {
return id.startsWith(clazz.getName() + CommonProfile.SEPARATOR);
}
return false;
} | [
"public",
"static",
"boolean",
"isTypedIdOf",
"(",
"final",
"String",
"id",
",",
"final",
"Class",
"<",
"?",
"extends",
"CommonProfile",
">",
"clazz",
")",
"{",
"if",
"(",
"id",
"!=",
"null",
"&&",
"clazz",
"!=",
"null",
")",
"{",
"return",
"id",
".",
... | Indicate if the user identifier matches this kind of profile.
@param id user identifier
@param clazz profile class
@return if the user identifier matches this kind of profile | [
"Indicate",
"if",
"the",
"user",
"identifier",
"matches",
"this",
"kind",
"of",
"profile",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/profile/ProfileHelper.java#L34-L39 |
32,709 | pac4j/pac4j | pac4j-core/src/main/java/org/pac4j/core/profile/ProfileHelper.java | ProfileHelper.restoreOrBuildProfile | public static CommonProfile restoreOrBuildProfile(final ProfileDefinition<? extends CommonProfile> profileDefinition,
final String typedId, final Map<String, Object> profileAttributes, final Map<String, Object> authenticationAttributes,
final Object... parameters) {
if (CommonHelper.isBlank(typedId)) {
return null;
}
logger.info("Building user profile based on typedId: {}", typedId);
final CommonProfile profile;
if (typedId.contains(CommonProfile.SEPARATOR)) {
final String className = CommonHelper.substringBefore(typedId, CommonProfile.SEPARATOR);
try {
profile = buildUserProfileByClassCompleteName(className);
} catch (final TechnicalException e) {
logger.error("Cannot build instance for class name: {}", className, e);
return null;
}
profile.addAttributes(profileAttributes);
profile.addAuthenticationAttributes(authenticationAttributes);
} else {
profile = profileDefinition.newProfile(parameters);
profileDefinition.convertAndAdd(profile, profileAttributes, authenticationAttributes);
}
profile.setId(ProfileHelper.sanitizeIdentifier(profile, typedId));
return profile;
} | java | public static CommonProfile restoreOrBuildProfile(final ProfileDefinition<? extends CommonProfile> profileDefinition,
final String typedId, final Map<String, Object> profileAttributes, final Map<String, Object> authenticationAttributes,
final Object... parameters) {
if (CommonHelper.isBlank(typedId)) {
return null;
}
logger.info("Building user profile based on typedId: {}", typedId);
final CommonProfile profile;
if (typedId.contains(CommonProfile.SEPARATOR)) {
final String className = CommonHelper.substringBefore(typedId, CommonProfile.SEPARATOR);
try {
profile = buildUserProfileByClassCompleteName(className);
} catch (final TechnicalException e) {
logger.error("Cannot build instance for class name: {}", className, e);
return null;
}
profile.addAttributes(profileAttributes);
profile.addAuthenticationAttributes(authenticationAttributes);
} else {
profile = profileDefinition.newProfile(parameters);
profileDefinition.convertAndAdd(profile, profileAttributes, authenticationAttributes);
}
profile.setId(ProfileHelper.sanitizeIdentifier(profile, typedId));
return profile;
} | [
"public",
"static",
"CommonProfile",
"restoreOrBuildProfile",
"(",
"final",
"ProfileDefinition",
"<",
"?",
"extends",
"CommonProfile",
">",
"profileDefinition",
",",
"final",
"String",
"typedId",
",",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"profileAttrib... | Restore or build a profile.
@param profileDefinition the profile definition
@param typedId the typed identifier
@param profileAttributes The profile attributes. May be {@code null}.
@param authenticationAttributes The authentication attributes. May be {@code null}.
@param parameters additional parameters for the profile definition
@return the restored or built profile | [
"Restore",
"or",
"build",
"a",
"profile",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/profile/ProfileHelper.java#L51-L76 |
32,710 | pac4j/pac4j | pac4j-core/src/main/java/org/pac4j/core/profile/ProfileHelper.java | ProfileHelper.buildUserProfileByClassCompleteName | public static CommonProfile buildUserProfileByClassCompleteName(final String completeName) {
try {
final Constructor<? extends CommonProfile> constructor = CommonHelper.getConstructor(completeName);
return constructor.newInstance();
} catch (final ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException
| InstantiationException e) {
throw new TechnicalException(e);
}
} | java | public static CommonProfile buildUserProfileByClassCompleteName(final String completeName) {
try {
final Constructor<? extends CommonProfile> constructor = CommonHelper.getConstructor(completeName);
return constructor.newInstance();
} catch (final ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException
| InstantiationException e) {
throw new TechnicalException(e);
}
} | [
"public",
"static",
"CommonProfile",
"buildUserProfileByClassCompleteName",
"(",
"final",
"String",
"completeName",
")",
"{",
"try",
"{",
"final",
"Constructor",
"<",
"?",
"extends",
"CommonProfile",
">",
"constructor",
"=",
"CommonHelper",
".",
"getConstructor",
"(",... | Build a profile by its class name.
@param completeName the class name
@return the built user profile | [
"Build",
"a",
"profile",
"by",
"its",
"class",
"name",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/profile/ProfileHelper.java#L84-L92 |
32,711 | pac4j/pac4j | pac4j-core/src/main/java/org/pac4j/core/profile/ProfileHelper.java | ProfileHelper.flatIntoAProfileList | public static <U extends UserProfile> List<U> flatIntoAProfileList(final Map<String, U> profiles) {
return new ArrayList<>(profiles.values());
} | java | public static <U extends UserProfile> List<U> flatIntoAProfileList(final Map<String, U> profiles) {
return new ArrayList<>(profiles.values());
} | [
"public",
"static",
"<",
"U",
"extends",
"UserProfile",
">",
"List",
"<",
"U",
">",
"flatIntoAProfileList",
"(",
"final",
"Map",
"<",
"String",
",",
"U",
">",
"profiles",
")",
"{",
"return",
"new",
"ArrayList",
"<>",
"(",
"profiles",
".",
"values",
"(",
... | Flat the map of profiles into a list of profiles.
@param profiles the map of profiles
@param <U> the kind of profile
@return the list of profiles | [
"Flat",
"the",
"map",
"of",
"profiles",
"into",
"a",
"list",
"of",
"profiles",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/profile/ProfileHelper.java#L117-L119 |
32,712 | pac4j/pac4j | pac4j-core/src/main/java/org/pac4j/core/profile/ProfileHelper.java | ProfileHelper.sanitizeIdentifier | public static String sanitizeIdentifier(final BasicUserProfile profile, final Object id) {
if (id != null) {
String sId = id.toString();
if (profile != null) {
final String type = profile.getClass().getName() + BasicUserProfile.SEPARATOR;
if (sId.startsWith(type)) {
sId = sId.substring(type.length());
}
}
return sId;
}
return null;
} | java | public static String sanitizeIdentifier(final BasicUserProfile profile, final Object id) {
if (id != null) {
String sId = id.toString();
if (profile != null) {
final String type = profile.getClass().getName() + BasicUserProfile.SEPARATOR;
if (sId.startsWith(type)) {
sId = sId.substring(type.length());
}
}
return sId;
}
return null;
} | [
"public",
"static",
"String",
"sanitizeIdentifier",
"(",
"final",
"BasicUserProfile",
"profile",
",",
"final",
"Object",
"id",
")",
"{",
"if",
"(",
"id",
"!=",
"null",
")",
"{",
"String",
"sId",
"=",
"id",
".",
"toString",
"(",
")",
";",
"if",
"(",
"pr... | Sanitize into a string identifier.
@param profile the user profile
@param id the identifier object
@return the sanitized identifier | [
"Sanitize",
"into",
"a",
"string",
"identifier",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/profile/ProfileHelper.java#L128-L140 |
32,713 | pac4j/pac4j | pac4j-core/src/main/java/org/pac4j/core/matching/PathMatcher.java | PathMatcher.excludeRegex | public PathMatcher excludeRegex(final String regex) {
CommonHelper.assertNotBlank("regex", regex);
logger.warn("Excluding paths with regexes is an advanced feature: be careful when defining your regular expression " +
"to avoid any security issues!");
if (!regex.startsWith("^") || !regex.endsWith("$")) {
throw new TechnicalException("Your regular expression: '" + regex + "' must start with a ^ and end with a $ " +
"to define a full path matching");
}
excludedPatterns.add(Pattern.compile(regex));
return this;
} | java | public PathMatcher excludeRegex(final String regex) {
CommonHelper.assertNotBlank("regex", regex);
logger.warn("Excluding paths with regexes is an advanced feature: be careful when defining your regular expression " +
"to avoid any security issues!");
if (!regex.startsWith("^") || !regex.endsWith("$")) {
throw new TechnicalException("Your regular expression: '" + regex + "' must start with a ^ and end with a $ " +
"to define a full path matching");
}
excludedPatterns.add(Pattern.compile(regex));
return this;
} | [
"public",
"PathMatcher",
"excludeRegex",
"(",
"final",
"String",
"regex",
")",
"{",
"CommonHelper",
".",
"assertNotBlank",
"(",
"\"regex\"",
",",
"regex",
")",
";",
"logger",
".",
"warn",
"(",
"\"Excluding paths with regexes is an advanced feature: be careful when definin... | Any path matching this regex will be excluded.
@param regex the regular expression matching the paths to be excluded
@return this path matcher | [
"Any",
"path",
"matching",
"this",
"regex",
"will",
"be",
"excluded",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/matching/PathMatcher.java#L61-L73 |
32,714 | pac4j/pac4j | pac4j-core/src/main/java/org/pac4j/core/matching/PathMatcher.java | PathMatcher.matches | boolean matches(final String path) {
logger.debug("path to match: {}", path);
if (excludedPaths.contains(path)) {
return false;
}
for (Pattern pattern : excludedPatterns) {
if (pattern.matcher(path).matches()) {
return false;
}
}
return true;
} | java | boolean matches(final String path) {
logger.debug("path to match: {}", path);
if (excludedPaths.contains(path)) {
return false;
}
for (Pattern pattern : excludedPatterns) {
if (pattern.matcher(path).matches()) {
return false;
}
}
return true;
} | [
"boolean",
"matches",
"(",
"final",
"String",
"path",
")",
"{",
"logger",
".",
"debug",
"(",
"\"path to match: {}\"",
",",
"path",
")",
";",
"if",
"(",
"excludedPaths",
".",
"contains",
"(",
"path",
")",
")",
"{",
"return",
"false",
";",
"}",
"for",
"(... | Returns true if a path should be authenticated, false to skip authentication. | [
"Returns",
"true",
"if",
"a",
"path",
"should",
"be",
"authenticated",
"false",
"to",
"skip",
"authentication",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/matching/PathMatcher.java#L81-L96 |
32,715 | pac4j/pac4j | pac4j-core/src/main/java/org/pac4j/core/engine/AbstractExceptionAwareLogic.java | AbstractExceptionAwareLogic.handleException | protected R handleException(final Exception e, final HttpActionAdapter<R, C> httpActionAdapter, final C context) {
if (httpActionAdapter == null || context == null) {
throw runtimeException(e);
} else if (e instanceof HttpAction) {
final HttpAction action = (HttpAction) e;
logger.debug("extra HTTP action required in security: {}", action.getCode());
return httpActionAdapter.adapt(action, context);
} else {
if (CommonHelper.isNotBlank(errorUrl)) {
final HttpAction action = RedirectionActionHelper.buildRedirectUrlAction(context, errorUrl);
return httpActionAdapter.adapt(action, context);
} else {
throw runtimeException(e);
}
}
} | java | protected R handleException(final Exception e, final HttpActionAdapter<R, C> httpActionAdapter, final C context) {
if (httpActionAdapter == null || context == null) {
throw runtimeException(e);
} else if (e instanceof HttpAction) {
final HttpAction action = (HttpAction) e;
logger.debug("extra HTTP action required in security: {}", action.getCode());
return httpActionAdapter.adapt(action, context);
} else {
if (CommonHelper.isNotBlank(errorUrl)) {
final HttpAction action = RedirectionActionHelper.buildRedirectUrlAction(context, errorUrl);
return httpActionAdapter.adapt(action, context);
} else {
throw runtimeException(e);
}
}
} | [
"protected",
"R",
"handleException",
"(",
"final",
"Exception",
"e",
",",
"final",
"HttpActionAdapter",
"<",
"R",
",",
"C",
">",
"httpActionAdapter",
",",
"final",
"C",
"context",
")",
"{",
"if",
"(",
"httpActionAdapter",
"==",
"null",
"||",
"context",
"==",... | Handle exceptions.
@param e the thrown exception
@param httpActionAdapter the HTTP action adapter
@param context the web context
@return the final HTTP result | [
"Handle",
"exceptions",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/engine/AbstractExceptionAwareLogic.java#L37-L52 |
32,716 | pac4j/pac4j | pac4j-core/src/main/java/org/pac4j/core/engine/AbstractExceptionAwareLogic.java | AbstractExceptionAwareLogic.runtimeException | protected RuntimeException runtimeException(final Exception exception) {
if (exception instanceof RuntimeException) {
throw (RuntimeException) exception;
} else {
throw new RuntimeException(exception);
}
} | java | protected RuntimeException runtimeException(final Exception exception) {
if (exception instanceof RuntimeException) {
throw (RuntimeException) exception;
} else {
throw new RuntimeException(exception);
}
} | [
"protected",
"RuntimeException",
"runtimeException",
"(",
"final",
"Exception",
"exception",
")",
"{",
"if",
"(",
"exception",
"instanceof",
"RuntimeException",
")",
"{",
"throw",
"(",
"RuntimeException",
")",
"exception",
";",
"}",
"else",
"{",
"throw",
"new",
... | Wrap an Exception into a RuntimeException.
@param exception the original exception
@return the RuntimeException | [
"Wrap",
"an",
"Exception",
"into",
"a",
"RuntimeException",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/engine/AbstractExceptionAwareLogic.java#L60-L66 |
32,717 | pac4j/pac4j | pac4j-saml/src/main/java/org/pac4j/saml/util/SAML2Utils.java | SAML2Utils.urisEqualAfterPortNormalization | public static boolean urisEqualAfterPortNormalization(final URI uri1, final URI uri2) {
if (uri1 == null && uri2 == null) {
return true;
}
if (uri1 == null || uri2 == null) {
return false;
}
try {
URI normalizedUri1 = normalizePortNumbersInUri(uri1);
URI normalizedUri2 = normalizePortNumbersInUri(uri2);
boolean eq = normalizedUri1.equals(normalizedUri2);
return eq;
} catch (URISyntaxException use) {
logger.error("Cannot compare 2 URIs.", use);
return false;
}
} | java | public static boolean urisEqualAfterPortNormalization(final URI uri1, final URI uri2) {
if (uri1 == null && uri2 == null) {
return true;
}
if (uri1 == null || uri2 == null) {
return false;
}
try {
URI normalizedUri1 = normalizePortNumbersInUri(uri1);
URI normalizedUri2 = normalizePortNumbersInUri(uri2);
boolean eq = normalizedUri1.equals(normalizedUri2);
return eq;
} catch (URISyntaxException use) {
logger.error("Cannot compare 2 URIs.", use);
return false;
}
} | [
"public",
"static",
"boolean",
"urisEqualAfterPortNormalization",
"(",
"final",
"URI",
"uri1",
",",
"final",
"URI",
"uri2",
")",
"{",
"if",
"(",
"uri1",
"==",
"null",
"&&",
"uri2",
"==",
"null",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"uri1",
... | Compares two URIs for equality, ignoring default port numbers for selected protocols.
By default, {@link URI#equals(Object)} doesn't take into account default port numbers, so http://server:80/resource is a different
URI than http://server/resource.
And URLs should not be used for comparison, as written here:
http://stackoverflow.com/questions/3771081/proper-way-to-check-for-url-equality
@param uri1
URI 1 to be compared.
@param uri2
URI 2 to be compared.
@return True if both URIs are equal. | [
"Compares",
"two",
"URIs",
"for",
"equality",
"ignoring",
"default",
"port",
"numbers",
"for",
"selected",
"protocols",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-saml/src/main/java/org/pac4j/saml/util/SAML2Utils.java#L49-L66 |
32,718 | pac4j/pac4j | pac4j-saml/src/main/java/org/pac4j/saml/util/SAML2Utils.java | SAML2Utils.normalizePortNumbersInUri | private static URI normalizePortNumbersInUri(final URI uri) throws URISyntaxException {
int port = uri.getPort();
final String scheme = uri.getScheme();
if (SCHEME_HTTP.equals(scheme) && port == DEFAULT_HTTP_PORT) {
port = -1;
}
if (SCHEME_HTTPS.equals(scheme) && port == DEFAULT_HTTPS_PORT) {
port = -1;
}
final URI result = new URI(scheme, uri.getUserInfo(), uri.getHost(), port, uri.getPath(), uri.getQuery(), uri.getFragment());
return result;
} | java | private static URI normalizePortNumbersInUri(final URI uri) throws URISyntaxException {
int port = uri.getPort();
final String scheme = uri.getScheme();
if (SCHEME_HTTP.equals(scheme) && port == DEFAULT_HTTP_PORT) {
port = -1;
}
if (SCHEME_HTTPS.equals(scheme) && port == DEFAULT_HTTPS_PORT) {
port = -1;
}
final URI result = new URI(scheme, uri.getUserInfo(), uri.getHost(), port, uri.getPath(), uri.getQuery(), uri.getFragment());
return result;
} | [
"private",
"static",
"URI",
"normalizePortNumbersInUri",
"(",
"final",
"URI",
"uri",
")",
"throws",
"URISyntaxException",
"{",
"int",
"port",
"=",
"uri",
".",
"getPort",
"(",
")",
";",
"final",
"String",
"scheme",
"=",
"uri",
".",
"getScheme",
"(",
")",
";... | Normalizes a URI. If it contains the default port for the used scheme, the method replaces the port with "default".
@param uri
The URI to normalize.
@return A normalized URI.
@throws URISyntaxException
If a URI cannot be created because of wrong syntax. | [
"Normalizes",
"a",
"URI",
".",
"If",
"it",
"contains",
"the",
"default",
"port",
"for",
"the",
"used",
"scheme",
"the",
"method",
"replaces",
"the",
"port",
"with",
"default",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-saml/src/main/java/org/pac4j/saml/util/SAML2Utils.java#L79-L92 |
32,719 | pac4j/pac4j | pac4j-saml/src/main/java/org/pac4j/saml/transport/Pac4jHTTPPostSimpleSignEncoder.java | Pac4jHTTPPostSimpleSignEncoder.getEndpointURL | @Override
protected URI getEndpointURL(MessageContext<SAMLObject> messageContext) throws MessageEncodingException {
try {
return SAMLBindingSupport.getEndpointURL(messageContext);
} catch (BindingException e) {
throw new MessageEncodingException("Could not obtain message endpoint URL", e);
}
} | java | @Override
protected URI getEndpointURL(MessageContext<SAMLObject> messageContext) throws MessageEncodingException {
try {
return SAMLBindingSupport.getEndpointURL(messageContext);
} catch (BindingException e) {
throw new MessageEncodingException("Could not obtain message endpoint URL", e);
}
} | [
"@",
"Override",
"protected",
"URI",
"getEndpointURL",
"(",
"MessageContext",
"<",
"SAMLObject",
">",
"messageContext",
")",
"throws",
"MessageEncodingException",
"{",
"try",
"{",
"return",
"SAMLBindingSupport",
".",
"getEndpointURL",
"(",
"messageContext",
")",
";",
... | Gets the response URL from the message context.
@param messageContext current message context
@return response URL from the message context
@throws MessageEncodingException throw if no relying party endpoint is available | [
"Gets",
"the",
"response",
"URL",
"from",
"the",
"message",
"context",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-saml/src/main/java/org/pac4j/saml/transport/Pac4jHTTPPostSimpleSignEncoder.java#L40-L47 |
32,720 | pac4j/pac4j | pac4j-jwt/src/main/java/org/pac4j/jwt/profile/JwtGenerator.java | JwtGenerator.generate | public String generate(final Map<String, Object> claims) {
// claims builder
final JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();
// add claims
for (final Map.Entry<String, Object> entry : claims.entrySet()) {
builder.claim(entry.getKey(), entry.getValue());
}
if (this.expirationTime != null) {
builder.expirationTime(this.expirationTime);
}
return internalGenerate(builder.build());
} | java | public String generate(final Map<String, Object> claims) {
// claims builder
final JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();
// add claims
for (final Map.Entry<String, Object> entry : claims.entrySet()) {
builder.claim(entry.getKey(), entry.getValue());
}
if (this.expirationTime != null) {
builder.expirationTime(this.expirationTime);
}
return internalGenerate(builder.build());
} | [
"public",
"String",
"generate",
"(",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"claims",
")",
"{",
"// claims builder",
"final",
"JWTClaimsSet",
".",
"Builder",
"builder",
"=",
"new",
"JWTClaimsSet",
".",
"Builder",
"(",
")",
";",
"// add claims",
"... | Generate a JWT from a map of claims.
@param claims the map of claims
@return the created JWT | [
"Generate",
"a",
"JWT",
"from",
"a",
"map",
"of",
"claims",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-jwt/src/main/java/org/pac4j/jwt/profile/JwtGenerator.java#L49-L61 |
32,721 | pac4j/pac4j | pac4j-jwt/src/main/java/org/pac4j/jwt/profile/JwtGenerator.java | JwtGenerator.internalGenerate | protected String internalGenerate(final JWTClaimsSet claimsSet) {
JWT jwt;
// signature?
if (signatureConfiguration == null) {
jwt = new PlainJWT(claimsSet);
} else {
jwt = signatureConfiguration.sign(claimsSet);
}
// encryption?
if (encryptionConfiguration != null) {
return encryptionConfiguration.encrypt(jwt);
} else {
return jwt.serialize();
}
} | java | protected String internalGenerate(final JWTClaimsSet claimsSet) {
JWT jwt;
// signature?
if (signatureConfiguration == null) {
jwt = new PlainJWT(claimsSet);
} else {
jwt = signatureConfiguration.sign(claimsSet);
}
// encryption?
if (encryptionConfiguration != null) {
return encryptionConfiguration.encrypt(jwt);
} else {
return jwt.serialize();
}
} | [
"protected",
"String",
"internalGenerate",
"(",
"final",
"JWTClaimsSet",
"claimsSet",
")",
"{",
"JWT",
"jwt",
";",
"// signature?",
"if",
"(",
"signatureConfiguration",
"==",
"null",
")",
"{",
"jwt",
"=",
"new",
"PlainJWT",
"(",
"claimsSet",
")",
";",
"}",
"... | Generate a JWT from a claims set.
@param claimsSet the claims set
@return the JWT | [
"Generate",
"a",
"JWT",
"from",
"a",
"claims",
"set",
"."
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-jwt/src/main/java/org/pac4j/jwt/profile/JwtGenerator.java#L81-L96 |
32,722 | pac4j/pac4j | pac4j-core/src/main/java/org/pac4j/core/util/HttpUtils.java | HttpUtils.buildHttpErrorMessage | public static String buildHttpErrorMessage(final HttpURLConnection connection) throws IOException {
final StringBuilder messageBuilder = new StringBuilder("(").append(connection.getResponseCode()).append(")");
if (connection.getResponseMessage() != null) {
messageBuilder.append(" ");
messageBuilder.append(connection.getResponseMessage());
}
try (final InputStreamReader isr = new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr)){
String output;
messageBuilder.append("[");
while ((output = br.readLine()) != null) {
messageBuilder.append(output);
}
messageBuilder.append("]");
}finally {
connection.disconnect();
}
return messageBuilder.toString();
} | java | public static String buildHttpErrorMessage(final HttpURLConnection connection) throws IOException {
final StringBuilder messageBuilder = new StringBuilder("(").append(connection.getResponseCode()).append(")");
if (connection.getResponseMessage() != null) {
messageBuilder.append(" ");
messageBuilder.append(connection.getResponseMessage());
}
try (final InputStreamReader isr = new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr)){
String output;
messageBuilder.append("[");
while ((output = br.readLine()) != null) {
messageBuilder.append(output);
}
messageBuilder.append("]");
}finally {
connection.disconnect();
}
return messageBuilder.toString();
} | [
"public",
"static",
"String",
"buildHttpErrorMessage",
"(",
"final",
"HttpURLConnection",
"connection",
")",
"throws",
"IOException",
"{",
"final",
"StringBuilder",
"messageBuilder",
"=",
"new",
"StringBuilder",
"(",
"\"(\"",
")",
".",
"append",
"(",
"connection",
"... | Build error message from connection in case of failure
@param connection HttpURLConnection
@return String by combining response code, message and error stream
@throws IOException an IO exception | [
"Build",
"error",
"message",
"from",
"connection",
"in",
"case",
"of",
"failure"
] | d9cd029f8783792b31dd48bf1e32f80628f2c4a3 | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/util/HttpUtils.java#L35-L53 |
32,723 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/utils/HungarianAlgorithm.java | HungarianAlgorithm.computeInitialFeasibleSolution | protected void computeInitialFeasibleSolution() {
for (int j = 0; j < dim; j++) {
labelByJob[j] = Double.POSITIVE_INFINITY;
}
for (int w = 0; w < dim; w++) {
for (int j = 0; j < dim; j++) {
if (costMatrix[w][j] < labelByJob[j]) {
labelByJob[j] = costMatrix[w][j];
}
}
}
} | java | protected void computeInitialFeasibleSolution() {
for (int j = 0; j < dim; j++) {
labelByJob[j] = Double.POSITIVE_INFINITY;
}
for (int w = 0; w < dim; w++) {
for (int j = 0; j < dim; j++) {
if (costMatrix[w][j] < labelByJob[j]) {
labelByJob[j] = costMatrix[w][j];
}
}
}
} | [
"protected",
"void",
"computeInitialFeasibleSolution",
"(",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"dim",
";",
"j",
"++",
")",
"{",
"labelByJob",
"[",
"j",
"]",
"=",
"Double",
".",
"POSITIVE_INFINITY",
";",
"}",
"for",
"(",
"int",... | Compute an initial feasible solution by assigning zero labels to the
workers and by assigning to each job a label equal to the minimum cost
among its incident edges. | [
"Compute",
"an",
"initial",
"feasible",
"solution",
"by",
"assigning",
"zero",
"labels",
"to",
"the",
"workers",
"and",
"by",
"assigning",
"to",
"each",
"job",
"a",
"label",
"equal",
"to",
"the",
"minimum",
"cost",
"among",
"its",
"incident",
"edges",
"."
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/utils/HungarianAlgorithm.java#L102-L113 |
32,724 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/utils/HungarianAlgorithm.java | HungarianAlgorithm.execute | public int[] execute() {
/*
* Heuristics to improve performance: Reduce rows and columns by their
* smallest element, compute an initial non-zero dual feasible solution
* and create a greedy matching from workers to jobs of the cost matrix.
*/
reduce();
computeInitialFeasibleSolution();
greedyMatch();
int w = fetchUnmatchedWorker();
while (w < dim) {
initializePhase(w);
executePhase();
w = fetchUnmatchedWorker();
}
int[] result = Arrays.copyOf(matchJobByWorker, rows);
for (w = 0; w < result.length; w++) {
if (result[w] >= cols) {
result[w] = -1;
}
}
return result;
} | java | public int[] execute() {
/*
* Heuristics to improve performance: Reduce rows and columns by their
* smallest element, compute an initial non-zero dual feasible solution
* and create a greedy matching from workers to jobs of the cost matrix.
*/
reduce();
computeInitialFeasibleSolution();
greedyMatch();
int w = fetchUnmatchedWorker();
while (w < dim) {
initializePhase(w);
executePhase();
w = fetchUnmatchedWorker();
}
int[] result = Arrays.copyOf(matchJobByWorker, rows);
for (w = 0; w < result.length; w++) {
if (result[w] >= cols) {
result[w] = -1;
}
}
return result;
} | [
"public",
"int",
"[",
"]",
"execute",
"(",
")",
"{",
"/*\n * Heuristics to improve performance: Reduce rows and columns by their\n * smallest element, compute an initial non-zero dual feasible solution\n * and create a greedy matching from workers to jobs of the cost matrix.\... | Execute the algorithm.
@return the minimum cost matching of workers to jobs based upon the
provided cost matrix. A matching value of -1 indicates that the
corresponding worker is unassigned. | [
"Execute",
"the",
"algorithm",
"."
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/utils/HungarianAlgorithm.java#L122-L145 |
32,725 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/utils/HungarianAlgorithm.java | HungarianAlgorithm.greedyMatch | protected void greedyMatch() {
for (int w = 0; w < dim; w++) {
for (int j = 0; j < dim; j++) {
if (matchJobByWorker[w] == -1
&& matchWorkerByJob[j] == -1
&& costMatrix[w][j] - labelByWorker[w] - labelByJob[j] == 0) {
match(w, j);
}
}
}
} | java | protected void greedyMatch() {
for (int w = 0; w < dim; w++) {
for (int j = 0; j < dim; j++) {
if (matchJobByWorker[w] == -1
&& matchWorkerByJob[j] == -1
&& costMatrix[w][j] - labelByWorker[w] - labelByJob[j] == 0) {
match(w, j);
}
}
}
} | [
"protected",
"void",
"greedyMatch",
"(",
")",
"{",
"for",
"(",
"int",
"w",
"=",
"0",
";",
"w",
"<",
"dim",
";",
"w",
"++",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"dim",
";",
"j",
"++",
")",
"{",
"if",
"(",
"matchJobByWor... | Find a valid matching by greedily selecting among zero-cost matchings.
This is a heuristic to jump-start the augmentation algorithm. | [
"Find",
"a",
"valid",
"matching",
"by",
"greedily",
"selecting",
"among",
"zero",
"-",
"cost",
"matchings",
".",
"This",
"is",
"a",
"heuristic",
"to",
"jump",
"-",
"start",
"the",
"augmentation",
"algorithm",
"."
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/utils/HungarianAlgorithm.java#L228-L238 |
32,726 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/utils/HungarianAlgorithm.java | HungarianAlgorithm.initializePhase | protected void initializePhase(int w) {
Arrays.fill(committedWorkers, false);
Arrays.fill(parentWorkerByCommittedJob, -1);
committedWorkers[w] = true;
for (int j = 0; j < dim; j++) {
minSlackValueByJob[j] = costMatrix[w][j] - labelByWorker[w]
- labelByJob[j];
minSlackWorkerByJob[j] = w;
}
} | java | protected void initializePhase(int w) {
Arrays.fill(committedWorkers, false);
Arrays.fill(parentWorkerByCommittedJob, -1);
committedWorkers[w] = true;
for (int j = 0; j < dim; j++) {
minSlackValueByJob[j] = costMatrix[w][j] - labelByWorker[w]
- labelByJob[j];
minSlackWorkerByJob[j] = w;
}
} | [
"protected",
"void",
"initializePhase",
"(",
"int",
"w",
")",
"{",
"Arrays",
".",
"fill",
"(",
"committedWorkers",
",",
"false",
")",
";",
"Arrays",
".",
"fill",
"(",
"parentWorkerByCommittedJob",
",",
"-",
"1",
")",
";",
"committedWorkers",
"[",
"w",
"]",... | Initialize the next phase of the algorithm by clearing the committed
workers and jobs sets and by initializing the slack arrays to the values
corresponding to the specified root worker.
@param w
the worker at which to root the next phase. | [
"Initialize",
"the",
"next",
"phase",
"of",
"the",
"algorithm",
"by",
"clearing",
"the",
"committed",
"workers",
"and",
"jobs",
"sets",
"and",
"by",
"initializing",
"the",
"slack",
"arrays",
"to",
"the",
"values",
"corresponding",
"to",
"the",
"specified",
"ro... | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/utils/HungarianAlgorithm.java#L248-L257 |
32,727 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/utils/HungarianAlgorithm.java | HungarianAlgorithm.reduce | protected void reduce() {
for (int w = 0; w < dim; w++) {
double min = Double.POSITIVE_INFINITY;
for (int j = 0; j < dim; j++) {
if (costMatrix[w][j] < min) {
min = costMatrix[w][j];
}
}
for (int j = 0; j < dim; j++) {
costMatrix[w][j] -= min;
}
}
double[] min = new double[dim];
for (int j = 0; j < dim; j++) {
min[j] = Double.POSITIVE_INFINITY;
}
for (int w = 0; w < dim; w++) {
for (int j = 0; j < dim; j++) {
if (costMatrix[w][j] < min[j]) {
min[j] = costMatrix[w][j];
}
}
}
for (int w = 0; w < dim; w++) {
for (int j = 0; j < dim; j++) {
costMatrix[w][j] -= min[j];
}
}
} | java | protected void reduce() {
for (int w = 0; w < dim; w++) {
double min = Double.POSITIVE_INFINITY;
for (int j = 0; j < dim; j++) {
if (costMatrix[w][j] < min) {
min = costMatrix[w][j];
}
}
for (int j = 0; j < dim; j++) {
costMatrix[w][j] -= min;
}
}
double[] min = new double[dim];
for (int j = 0; j < dim; j++) {
min[j] = Double.POSITIVE_INFINITY;
}
for (int w = 0; w < dim; w++) {
for (int j = 0; j < dim; j++) {
if (costMatrix[w][j] < min[j]) {
min[j] = costMatrix[w][j];
}
}
}
for (int w = 0; w < dim; w++) {
for (int j = 0; j < dim; j++) {
costMatrix[w][j] -= min[j];
}
}
} | [
"protected",
"void",
"reduce",
"(",
")",
"{",
"for",
"(",
"int",
"w",
"=",
"0",
";",
"w",
"<",
"dim",
";",
"w",
"++",
")",
"{",
"double",
"min",
"=",
"Double",
".",
"POSITIVE_INFINITY",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"d... | Reduce the cost matrix by subtracting the smallest element of each row
from all elements of the row as well as the smallest element of each
column from all elements of the column. Note that an optimal assignment
for a reduced cost matrix is optimal for the original cost matrix. | [
"Reduce",
"the",
"cost",
"matrix",
"by",
"subtracting",
"the",
"smallest",
"element",
"of",
"each",
"row",
"from",
"all",
"elements",
"of",
"the",
"row",
"as",
"well",
"as",
"the",
"smallest",
"element",
"of",
"each",
"column",
"from",
"all",
"elements",
"... | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/utils/HungarianAlgorithm.java#L273-L301 |
32,728 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/utils/HungarianAlgorithm.java | HungarianAlgorithm.updateLabeling | protected void updateLabeling(double slack) {
for (int w = 0; w < dim; w++) {
if (committedWorkers[w]) {
labelByWorker[w] += slack;
}
}
for (int j = 0; j < dim; j++) {
if (parentWorkerByCommittedJob[j] != -1) {
labelByJob[j] -= slack;
} else {
minSlackValueByJob[j] -= slack;
}
}
} | java | protected void updateLabeling(double slack) {
for (int w = 0; w < dim; w++) {
if (committedWorkers[w]) {
labelByWorker[w] += slack;
}
}
for (int j = 0; j < dim; j++) {
if (parentWorkerByCommittedJob[j] != -1) {
labelByJob[j] -= slack;
} else {
minSlackValueByJob[j] -= slack;
}
}
} | [
"protected",
"void",
"updateLabeling",
"(",
"double",
"slack",
")",
"{",
"for",
"(",
"int",
"w",
"=",
"0",
";",
"w",
"<",
"dim",
";",
"w",
"++",
")",
"{",
"if",
"(",
"committedWorkers",
"[",
"w",
"]",
")",
"{",
"labelByWorker",
"[",
"w",
"]",
"+=... | Update labels with the specified slack by adding the slack value for
committed workers and by subtracting the slack value for committed jobs.
In addition, update the minimum slack values appropriately. | [
"Update",
"labels",
"with",
"the",
"specified",
"slack",
"by",
"adding",
"the",
"slack",
"value",
"for",
"committed",
"workers",
"and",
"by",
"subtracting",
"the",
"slack",
"value",
"for",
"committed",
"jobs",
".",
"In",
"addition",
"update",
"the",
"minimum",... | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/utils/HungarianAlgorithm.java#L308-L321 |
32,729 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/tree/TreeUtils.java | TreeUtils.preOrder | public static List<ITree> preOrder(ITree tree) {
List<ITree> trees = new ArrayList<>();
preOrder(tree, trees);
return trees;
} | java | public static List<ITree> preOrder(ITree tree) {
List<ITree> trees = new ArrayList<>();
preOrder(tree, trees);
return trees;
} | [
"public",
"static",
"List",
"<",
"ITree",
">",
"preOrder",
"(",
"ITree",
"tree",
")",
"{",
"List",
"<",
"ITree",
">",
"trees",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"preOrder",
"(",
"tree",
",",
"trees",
")",
";",
"return",
"trees",
";",
"}... | Returns a list of every subtrees and the tree ordered using a pre-order.
@param tree a Tree. | [
"Returns",
"a",
"list",
"of",
"every",
"subtrees",
"and",
"the",
"tree",
"ordered",
"using",
"a",
"pre",
"-",
"order",
"."
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/tree/TreeUtils.java#L40-L44 |
32,730 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/tree/TreeUtils.java | TreeUtils.postOrder | public static List<ITree> postOrder(ITree tree) {
List<ITree> trees = new ArrayList<>();
postOrder(tree, trees);
return trees;
} | java | public static List<ITree> postOrder(ITree tree) {
List<ITree> trees = new ArrayList<>();
postOrder(tree, trees);
return trees;
} | [
"public",
"static",
"List",
"<",
"ITree",
">",
"postOrder",
"(",
"ITree",
"tree",
")",
"{",
"List",
"<",
"ITree",
">",
"trees",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"postOrder",
"(",
"tree",
",",
"trees",
")",
";",
"return",
"trees",
";",
... | Returns a list of every subtrees and the tree ordered using a post-order.
@param tree a Tree. | [
"Returns",
"a",
"list",
"of",
"every",
"subtrees",
"and",
"the",
"tree",
"ordered",
"using",
"a",
"post",
"-",
"order",
"."
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/tree/TreeUtils.java#L114-L118 |
32,731 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/tree/AssociationMap.java | AssociationMap.set | public Object set(String key, Object value) {
int idx = keys.indexOf(key);
if (idx == -1) {
keys.add(key);
values.add(value);
return null;
}
return values.set(idx, value);
} | java | public Object set(String key, Object value) {
int idx = keys.indexOf(key);
if (idx == -1) {
keys.add(key);
values.add(value);
return null;
}
return values.set(idx, value);
} | [
"public",
"Object",
"set",
"(",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"int",
"idx",
"=",
"keys",
".",
"indexOf",
"(",
"key",
")",
";",
"if",
"(",
"idx",
"==",
"-",
"1",
")",
"{",
"keys",
".",
"add",
"(",
"key",
")",
";",
"values",
... | set metadata `key` with `value` and returns the previous value
This method won't remove if value == null | [
"set",
"metadata",
"key",
"with",
"value",
"and",
"returns",
"the",
"previous",
"value",
"This",
"method",
"won",
"t",
"remove",
"if",
"value",
"==",
"null"
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/tree/AssociationMap.java#L44-L52 |
32,732 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/io/IndentingXMLStreamWriter.java | IndentingXMLStreamWriter.beforeMarkup | protected void beforeMarkup() {
int soFar = stack[depth];
if ((soFar & WROTE_DATA) == 0 // no data in this scope
&& (depth > 0 || soFar != 0)) {
try {
writeNewLine(depth);
if (depth > 0 && getIndent().length() > 0) {
afterMarkup(); // indentation was written
}
} catch (Exception e) {
e.printStackTrace();
}
}
} | java | protected void beforeMarkup() {
int soFar = stack[depth];
if ((soFar & WROTE_DATA) == 0 // no data in this scope
&& (depth > 0 || soFar != 0)) {
try {
writeNewLine(depth);
if (depth > 0 && getIndent().length() > 0) {
afterMarkup(); // indentation was written
}
} catch (Exception e) {
e.printStackTrace();
}
}
} | [
"protected",
"void",
"beforeMarkup",
"(",
")",
"{",
"int",
"soFar",
"=",
"stack",
"[",
"depth",
"]",
";",
"if",
"(",
"(",
"soFar",
"&",
"WROTE_DATA",
")",
"==",
"0",
"// no data in this scope",
"&&",
"(",
"depth",
">",
"0",
"||",
"soFar",
"!=",
"0",
... | Prepare to write markup, by writing a new line and indentation. | [
"Prepare",
"to",
"write",
"markup",
"by",
"writing",
"a",
"new",
"line",
"and",
"indentation",
"."
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/io/IndentingXMLStreamWriter.java#L271-L284 |
32,733 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/io/IndentingXMLStreamWriter.java | IndentingXMLStreamWriter.beforeStartElement | protected void beforeStartElement() {
beforeMarkup();
if (stack.length <= depth + 1) {
// Allocate more space for the stack:
int[] newStack = new int[stack.length * 2];
System.arraycopy(stack, 0, newStack, 0, stack.length);
stack = newStack;
}
stack[depth + 1] = 0; // nothing written yet
} | java | protected void beforeStartElement() {
beforeMarkup();
if (stack.length <= depth + 1) {
// Allocate more space for the stack:
int[] newStack = new int[stack.length * 2];
System.arraycopy(stack, 0, newStack, 0, stack.length);
stack = newStack;
}
stack[depth + 1] = 0; // nothing written yet
} | [
"protected",
"void",
"beforeStartElement",
"(",
")",
"{",
"beforeMarkup",
"(",
")",
";",
"if",
"(",
"stack",
".",
"length",
"<=",
"depth",
"+",
"1",
")",
"{",
"// Allocate more space for the stack:",
"int",
"[",
"]",
"newStack",
"=",
"new",
"int",
"[",
"st... | Prepare to start an element, by allocating stack space. | [
"Prepare",
"to",
"start",
"an",
"element",
"by",
"allocating",
"stack",
"space",
"."
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/io/IndentingXMLStreamWriter.java#L297-L306 |
32,734 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/io/IndentingXMLStreamWriter.java | IndentingXMLStreamWriter.writeNewLine | protected void writeNewLine(int indentation) throws XMLStreamException {
final int newLineLength = getNewLine().length();
final int prefixLength = newLineLength + (getIndent().length() * indentation);
if (prefixLength > 0) {
if (linePrefix == null) {
linePrefix = (getNewLine() + getIndent()).toCharArray();
}
while (prefixLength > linePrefix.length) {
// make linePrefix longer:
char[] newPrefix = new char[newLineLength
+ ((linePrefix.length - newLineLength) * 2)];
System.arraycopy(linePrefix, 0, newPrefix, 0, linePrefix.length);
System.arraycopy(linePrefix, newLineLength, newPrefix, linePrefix.length,
linePrefix.length - newLineLength);
linePrefix = newPrefix;
}
out.writeCharacters(linePrefix, 0, prefixLength);
}
} | java | protected void writeNewLine(int indentation) throws XMLStreamException {
final int newLineLength = getNewLine().length();
final int prefixLength = newLineLength + (getIndent().length() * indentation);
if (prefixLength > 0) {
if (linePrefix == null) {
linePrefix = (getNewLine() + getIndent()).toCharArray();
}
while (prefixLength > linePrefix.length) {
// make linePrefix longer:
char[] newPrefix = new char[newLineLength
+ ((linePrefix.length - newLineLength) * 2)];
System.arraycopy(linePrefix, 0, newPrefix, 0, linePrefix.length);
System.arraycopy(linePrefix, newLineLength, newPrefix, linePrefix.length,
linePrefix.length - newLineLength);
linePrefix = newPrefix;
}
out.writeCharacters(linePrefix, 0, prefixLength);
}
} | [
"protected",
"void",
"writeNewLine",
"(",
"int",
"indentation",
")",
"throws",
"XMLStreamException",
"{",
"final",
"int",
"newLineLength",
"=",
"getNewLine",
"(",
")",
".",
"length",
"(",
")",
";",
"final",
"int",
"prefixLength",
"=",
"newLineLength",
"+",
"("... | Write a line separator followed by indentation. | [
"Write",
"a",
"line",
"separator",
"followed",
"by",
"indentation",
"."
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/io/IndentingXMLStreamWriter.java#L345-L363 |
32,735 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/tree/TreeContext.java | TreeContext.getMetadata | public Object getMetadata(ITree node, String key) {
Object metadata;
if (node == null || (metadata = node.getMetadata(key)) == null)
return getMetadata(key);
return metadata;
} | java | public Object getMetadata(ITree node, String key) {
Object metadata;
if (node == null || (metadata = node.getMetadata(key)) == null)
return getMetadata(key);
return metadata;
} | [
"public",
"Object",
"getMetadata",
"(",
"ITree",
"node",
",",
"String",
"key",
")",
"{",
"Object",
"metadata",
";",
"if",
"(",
"node",
"==",
"null",
"||",
"(",
"metadata",
"=",
"node",
".",
"getMetadata",
"(",
"key",
")",
")",
"==",
"null",
")",
"ret... | Get a local metadata, if available. Otherwise get a global metadata.
There is no way to know if the metadata is really null or does not exists.
@param key of metadata
@return the metadata or null if not found | [
"Get",
"a",
"local",
"metadata",
"if",
"available",
".",
"Otherwise",
"get",
"a",
"global",
"metadata",
".",
"There",
"is",
"no",
"way",
"to",
"know",
"if",
"the",
"metadata",
"is",
"really",
"null",
"or",
"does",
"not",
"exists",
"."
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/tree/TreeContext.java#L83-L88 |
32,736 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/tree/TreeContext.java | TreeContext.setMetadata | public Object setMetadata(String key, Object value) {
return metadata.put(key, value);
} | java | public Object setMetadata(String key, Object value) {
return metadata.put(key, value);
} | [
"public",
"Object",
"setMetadata",
"(",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"return",
"metadata",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"}"
] | Store a global metadata.
@param key of the metadata
@param value of the metadata
@return the previous value of metadata if existed or null | [
"Store",
"a",
"global",
"metadata",
"."
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/tree/TreeContext.java#L97-L99 |
32,737 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/tree/TreeContext.java | TreeContext.setMetadata | public Object setMetadata(ITree node, String key, Object value) {
if (node == null)
return setMetadata(key, value);
else {
Object res = node.setMetadata(key, value);
if (res == null)
return getMetadata(key);
return res;
}
} | java | public Object setMetadata(ITree node, String key, Object value) {
if (node == null)
return setMetadata(key, value);
else {
Object res = node.setMetadata(key, value);
if (res == null)
return getMetadata(key);
return res;
}
} | [
"public",
"Object",
"setMetadata",
"(",
"ITree",
"node",
",",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"node",
"==",
"null",
")",
"return",
"setMetadata",
"(",
"key",
",",
"value",
")",
";",
"else",
"{",
"Object",
"res",
"=",
"no... | Store a local metadata
@param key of the metadata
@param value of the metadata
@return the previous value of metadata if existed or null | [
"Store",
"a",
"local",
"metadata"
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/tree/TreeContext.java#L108-L117 |
32,738 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/utils/SequenceAlgorithms.java | SequenceAlgorithms.longestCommonSubsequence | public static List<int[]> longestCommonSubsequence(String s0, String s1) {
int[][] lengths = new int[s0.length() + 1][s1.length() + 1];
for (int i = 0; i < s0.length(); i++)
for (int j = 0; j < s1.length(); j++)
if (s0.charAt(i) == (s1.charAt(j)))
lengths[i + 1][j + 1] = lengths[i][j] + 1;
else
lengths[i + 1][j + 1] = Math.max(lengths[i + 1][j], lengths[i][j + 1]);
return extractIndexes(lengths, s0.length(), s1.length());
} | java | public static List<int[]> longestCommonSubsequence(String s0, String s1) {
int[][] lengths = new int[s0.length() + 1][s1.length() + 1];
for (int i = 0; i < s0.length(); i++)
for (int j = 0; j < s1.length(); j++)
if (s0.charAt(i) == (s1.charAt(j)))
lengths[i + 1][j + 1] = lengths[i][j] + 1;
else
lengths[i + 1][j + 1] = Math.max(lengths[i + 1][j], lengths[i][j + 1]);
return extractIndexes(lengths, s0.length(), s1.length());
} | [
"public",
"static",
"List",
"<",
"int",
"[",
"]",
">",
"longestCommonSubsequence",
"(",
"String",
"s0",
",",
"String",
"s1",
")",
"{",
"int",
"[",
"]",
"[",
"]",
"lengths",
"=",
"new",
"int",
"[",
"s0",
".",
"length",
"(",
")",
"+",
"1",
"]",
"["... | Returns the longest common subsequence between two strings.
@return a list of size 2 int arrays that corresponds
to match of index in sequence 1 to index in sequence 2. | [
"Returns",
"the",
"longest",
"common",
"subsequence",
"between",
"two",
"strings",
"."
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/utils/SequenceAlgorithms.java#L38-L48 |
32,739 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/utils/SequenceAlgorithms.java | SequenceAlgorithms.hunks | public static List<int[]> hunks(String s0, String s1) {
List<int[]> lcs = longestCommonSubsequence(s0 ,s1);
List<int[]> hunks = new ArrayList<int[]>();
int inf0 = -1;
int inf1 = -1;
int last0 = -1;
int last1 = -1;
for (int i = 0; i < lcs.size(); i++) {
int[] match = lcs.get(i);
if (inf0 == -1 || inf1 == -1) {
inf0 = match[0];
inf1 = match[1];
} else if (last0 + 1 != match[0] || last1 + 1 != match[1]) {
hunks.add(new int[] {inf0, last0 + 1, inf1, last1 + 1});
inf0 = match[0];
inf1 = match[1];
} else if (i == lcs.size() - 1) {
hunks.add(new int[] {inf0, match[0] + 1, inf1, match[1] + 1});
break;
}
last0 = match[0];
last1 = match[1];
}
return hunks;
} | java | public static List<int[]> hunks(String s0, String s1) {
List<int[]> lcs = longestCommonSubsequence(s0 ,s1);
List<int[]> hunks = new ArrayList<int[]>();
int inf0 = -1;
int inf1 = -1;
int last0 = -1;
int last1 = -1;
for (int i = 0; i < lcs.size(); i++) {
int[] match = lcs.get(i);
if (inf0 == -1 || inf1 == -1) {
inf0 = match[0];
inf1 = match[1];
} else if (last0 + 1 != match[0] || last1 + 1 != match[1]) {
hunks.add(new int[] {inf0, last0 + 1, inf1, last1 + 1});
inf0 = match[0];
inf1 = match[1];
} else if (i == lcs.size() - 1) {
hunks.add(new int[] {inf0, match[0] + 1, inf1, match[1] + 1});
break;
}
last0 = match[0];
last1 = match[1];
}
return hunks;
} | [
"public",
"static",
"List",
"<",
"int",
"[",
"]",
">",
"hunks",
"(",
"String",
"s0",
",",
"String",
"s1",
")",
"{",
"List",
"<",
"int",
"[",
"]",
">",
"lcs",
"=",
"longestCommonSubsequence",
"(",
"s0",
",",
"s1",
")",
";",
"List",
"<",
"int",
"["... | Returns the hunks of the longest common subsequence between s1 and s2.
@return the hunks as a list of int arrays of size 4 with start index and end index of sequence 1
and corresponding start index and end index in sequence 2. | [
"Returns",
"the",
"hunks",
"of",
"the",
"longest",
"common",
"subsequence",
"between",
"s1",
"and",
"s2",
"."
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/utils/SequenceAlgorithms.java#L55-L79 |
32,740 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/utils/SequenceAlgorithms.java | SequenceAlgorithms.longestCommonSequence | public static String longestCommonSequence(String s1, String s2) {
int start = 0;
int max = 0;
for (int i = 0; i < s1.length(); i++) {
for (int j = 0; j < s2.length(); j++) {
int x = 0;
while (s1.charAt(i + x) == s2.charAt(j + x)) {
x++;
if (((i + x) >= s1.length()) || ((j + x) >= s2.length())) break;
}
if (x > max) {
max = x;
start = i;
}
}
}
return s1.substring(start, (start + max));
} | java | public static String longestCommonSequence(String s1, String s2) {
int start = 0;
int max = 0;
for (int i = 0; i < s1.length(); i++) {
for (int j = 0; j < s2.length(); j++) {
int x = 0;
while (s1.charAt(i + x) == s2.charAt(j + x)) {
x++;
if (((i + x) >= s1.length()) || ((j + x) >= s2.length())) break;
}
if (x > max) {
max = x;
start = i;
}
}
}
return s1.substring(start, (start + max));
} | [
"public",
"static",
"String",
"longestCommonSequence",
"(",
"String",
"s1",
",",
"String",
"s2",
")",
"{",
"int",
"start",
"=",
"0",
";",
"int",
"max",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"s1",
".",
"length",
"(",
")",... | Returns the longest common sequence between two strings as a string. | [
"Returns",
"the",
"longest",
"common",
"sequence",
"between",
"two",
"strings",
"as",
"a",
"string",
"."
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/utils/SequenceAlgorithms.java#L84-L101 |
32,741 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/utils/SequenceAlgorithms.java | SequenceAlgorithms.longestCommonSubsequenceWithTypeAndLabel | public static List<int[]> longestCommonSubsequenceWithTypeAndLabel(List<ITree> s0, List<ITree> s1) {
int[][] lengths = new int[s0.size() + 1][s1.size() + 1];
for (int i = 0; i < s0.size(); i++)
for (int j = 0; j < s1.size(); j++)
if (s0.get(i).hasSameTypeAndLabel(s1.get(j)))
lengths[i + 1][j + 1] = lengths[i][j] + 1;
else
lengths[i + 1][j + 1] = Math.max(lengths[i + 1][j], lengths[i][j + 1]);
return extractIndexes(lengths, s0.size(), s1.size());
} | java | public static List<int[]> longestCommonSubsequenceWithTypeAndLabel(List<ITree> s0, List<ITree> s1) {
int[][] lengths = new int[s0.size() + 1][s1.size() + 1];
for (int i = 0; i < s0.size(); i++)
for (int j = 0; j < s1.size(); j++)
if (s0.get(i).hasSameTypeAndLabel(s1.get(j)))
lengths[i + 1][j + 1] = lengths[i][j] + 1;
else
lengths[i + 1][j + 1] = Math.max(lengths[i + 1][j], lengths[i][j + 1]);
return extractIndexes(lengths, s0.size(), s1.size());
} | [
"public",
"static",
"List",
"<",
"int",
"[",
"]",
">",
"longestCommonSubsequenceWithTypeAndLabel",
"(",
"List",
"<",
"ITree",
">",
"s0",
",",
"List",
"<",
"ITree",
">",
"s1",
")",
"{",
"int",
"[",
"]",
"[",
"]",
"lengths",
"=",
"new",
"int",
"[",
"s0... | Returns the longest common subsequence between the two list of nodes. This version use
type and label to ensure equality.
@see ITree#hasSameTypeAndLabel(ITree)
@return a list of size 2 int arrays that corresponds
to match of index in sequence 1 to index in sequence 2. | [
"Returns",
"the",
"longest",
"common",
"subsequence",
"between",
"the",
"two",
"list",
"of",
"nodes",
".",
"This",
"version",
"use",
"type",
"and",
"label",
"to",
"ensure",
"equality",
"."
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/utils/SequenceAlgorithms.java#L111-L121 |
32,742 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/utils/SequenceAlgorithms.java | SequenceAlgorithms.longestCommonSubsequenceWithIsomorphism | public static List<int[]> longestCommonSubsequenceWithIsomorphism(List<ITree> s0, List<ITree> s1) {
int[][] lengths = new int[s0.size() + 1][s1.size() + 1];
for (int i = 0; i < s0.size(); i++)
for (int j = 0; j < s1.size(); j++)
if (s0.get(i).isIsomorphicTo(s1.get(j)))
lengths[i + 1][j + 1] = lengths[i][j] + 1;
else
lengths[i + 1][j + 1] = Math.max(lengths[i + 1][j], lengths[i][j + 1]);
return extractIndexes(lengths, s0.size(), s1.size());
} | java | public static List<int[]> longestCommonSubsequenceWithIsomorphism(List<ITree> s0, List<ITree> s1) {
int[][] lengths = new int[s0.size() + 1][s1.size() + 1];
for (int i = 0; i < s0.size(); i++)
for (int j = 0; j < s1.size(); j++)
if (s0.get(i).isIsomorphicTo(s1.get(j)))
lengths[i + 1][j + 1] = lengths[i][j] + 1;
else
lengths[i + 1][j + 1] = Math.max(lengths[i + 1][j], lengths[i][j + 1]);
return extractIndexes(lengths, s0.size(), s1.size());
} | [
"public",
"static",
"List",
"<",
"int",
"[",
"]",
">",
"longestCommonSubsequenceWithIsomorphism",
"(",
"List",
"<",
"ITree",
">",
"s0",
",",
"List",
"<",
"ITree",
">",
"s1",
")",
"{",
"int",
"[",
"]",
"[",
"]",
"lengths",
"=",
"new",
"int",
"[",
"s0"... | Returns the longest common subsequence between the two list of nodes. This version use
isomorphism to ensure equality.
@see ITree#isIsomorphicTo(ITree)
@return a list of size 2 int arrays that corresponds
to match of index in sequence 1 to index in sequence 2. | [
"Returns",
"the",
"longest",
"common",
"subsequence",
"between",
"the",
"two",
"list",
"of",
"nodes",
".",
"This",
"version",
"use",
"isomorphism",
"to",
"ensure",
"equality",
"."
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/utils/SequenceAlgorithms.java#L131-L141 |
32,743 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/io/LineReader.java | LineReader.positionFor | public int positionFor(int line, int column) {
if (lines.size() < line)
return -1;
return lines.get(line - 1) + column - 1;
} | java | public int positionFor(int line, int column) {
if (lines.size() < line)
return -1;
return lines.get(line - 1) + column - 1;
} | [
"public",
"int",
"positionFor",
"(",
"int",
"line",
",",
"int",
"column",
")",
"{",
"if",
"(",
"lines",
".",
"size",
"(",
")",
"<",
"line",
")",
"return",
"-",
"1",
";",
"return",
"lines",
".",
"get",
"(",
"line",
"-",
"1",
")",
"+",
"column",
... | Line and column starts at 1 | [
"Line",
"and",
"column",
"starts",
"at",
"1"
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/io/LineReader.java#L51-L56 |
32,744 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/matchers/optimal/rted/RtedAlgorithm.java | RtedAlgorithm.spfL | private double spfL(InfoTree it1, InfoTree it2) {
int fPostorder = it1.getCurrentNode();
int gPostorder = it2.getCurrentNode();
int minKR = it2.info[POST2_MIN_KR][gPostorder];
int[] kr = it2.info[KR];
if (minKR > -1) {
for (int j = minKR; kr[j] < gPostorder; j++) {
treeEditDist(it1, it2, fPostorder, kr[j]);
}
}
treeEditDist(it1, it2, fPostorder, gPostorder);
return it1.isSwitched() ? delta[gPostorder][fPostorder]
+ deltaBit[gPostorder][fPostorder] * costMatch
: delta[fPostorder][gPostorder]
+ deltaBit[fPostorder][gPostorder] * costMatch;
} | java | private double spfL(InfoTree it1, InfoTree it2) {
int fPostorder = it1.getCurrentNode();
int gPostorder = it2.getCurrentNode();
int minKR = it2.info[POST2_MIN_KR][gPostorder];
int[] kr = it2.info[KR];
if (minKR > -1) {
for (int j = minKR; kr[j] < gPostorder; j++) {
treeEditDist(it1, it2, fPostorder, kr[j]);
}
}
treeEditDist(it1, it2, fPostorder, gPostorder);
return it1.isSwitched() ? delta[gPostorder][fPostorder]
+ deltaBit[gPostorder][fPostorder] * costMatch
: delta[fPostorder][gPostorder]
+ deltaBit[fPostorder][gPostorder] * costMatch;
} | [
"private",
"double",
"spfL",
"(",
"InfoTree",
"it1",
",",
"InfoTree",
"it2",
")",
"{",
"int",
"fPostorder",
"=",
"it1",
".",
"getCurrentNode",
"(",
")",
";",
"int",
"gPostorder",
"=",
"it2",
".",
"getCurrentNode",
"(",
")",
";",
"int",
"minKR",
"=",
"i... | Single-path function for the left-most path based on Zhang and Shasha
algorithm.
@param it1
@param it2
@return distance between subtrees it1 and it2 | [
"Single",
"-",
"path",
"function",
"for",
"the",
"left",
"-",
"most",
"path",
"based",
"on",
"Zhang",
"and",
"Shasha",
"algorithm",
"."
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/matchers/optimal/rted/RtedAlgorithm.java#L432-L450 |
32,745 | GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/matchers/optimal/rted/RtedAlgorithm.java | RtedAlgorithm.spfR | private double spfR(InfoTree it1, InfoTree it2) {
int fReversedPostorder = it1.getSize() - 1 - it1.info[POST2_PRE][it1.getCurrentNode()];
int gReversedPostorder = it2.getSize() - 1 - it2.info[POST2_PRE][it2.getCurrentNode()];
int minRKR = it2.info[RPOST2_MIN_RKR][gReversedPostorder];
int[] rkr = it2.info[RKR];
if (minRKR > -1) for (int j = minRKR; rkr[j] < gReversedPostorder; j++) treeEditDistRev(it1, it2, fReversedPostorder, rkr[j]);
treeEditDistRev(it1, it2, fReversedPostorder, gReversedPostorder);
return it1.isSwitched() ? delta[it2.getCurrentNode()][it1
.getCurrentNode()]
+ deltaBit[it2.getCurrentNode()][it1.getCurrentNode()]
* costMatch : delta[it1.getCurrentNode()][it2.getCurrentNode()]
+ deltaBit[it1.getCurrentNode()][it2.getCurrentNode()]
* costMatch;
} | java | private double spfR(InfoTree it1, InfoTree it2) {
int fReversedPostorder = it1.getSize() - 1 - it1.info[POST2_PRE][it1.getCurrentNode()];
int gReversedPostorder = it2.getSize() - 1 - it2.info[POST2_PRE][it2.getCurrentNode()];
int minRKR = it2.info[RPOST2_MIN_RKR][gReversedPostorder];
int[] rkr = it2.info[RKR];
if (minRKR > -1) for (int j = minRKR; rkr[j] < gReversedPostorder; j++) treeEditDistRev(it1, it2, fReversedPostorder, rkr[j]);
treeEditDistRev(it1, it2, fReversedPostorder, gReversedPostorder);
return it1.isSwitched() ? delta[it2.getCurrentNode()][it1
.getCurrentNode()]
+ deltaBit[it2.getCurrentNode()][it1.getCurrentNode()]
* costMatch : delta[it1.getCurrentNode()][it2.getCurrentNode()]
+ deltaBit[it1.getCurrentNode()][it2.getCurrentNode()]
* costMatch;
} | [
"private",
"double",
"spfR",
"(",
"InfoTree",
"it1",
",",
"InfoTree",
"it2",
")",
"{",
"int",
"fReversedPostorder",
"=",
"it1",
".",
"getSize",
"(",
")",
"-",
"1",
"-",
"it1",
".",
"info",
"[",
"POST2_PRE",
"]",
"[",
"it1",
".",
"getCurrentNode",
"(",
... | Single-path function for right-most path based on symmetric version of
Zhang and Shasha algorithm.
@param it1
@param it2
@return distance between subtrees it1 and it2 | [
"Single",
"-",
"path",
"function",
"for",
"right",
"-",
"most",
"path",
"based",
"on",
"symmetric",
"version",
"of",
"Zhang",
"and",
"Shasha",
"algorithm",
"."
] | a772d4d652af44bff22c38a234ddffbfbd365a37 | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/matchers/optimal/rted/RtedAlgorithm.java#L494-L510 |
32,746 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/btree/Task.java | Task.addChild | public final int addChild (Task<E> child) {
int index = addChildToTask(child);
if (tree != null && tree.listeners != null) tree.notifyChildAdded(this, index);
return index;
} | java | public final int addChild (Task<E> child) {
int index = addChildToTask(child);
if (tree != null && tree.listeners != null) tree.notifyChildAdded(this, index);
return index;
} | [
"public",
"final",
"int",
"addChild",
"(",
"Task",
"<",
"E",
">",
"child",
")",
"{",
"int",
"index",
"=",
"addChildToTask",
"(",
"child",
")",
";",
"if",
"(",
"tree",
"!=",
"null",
"&&",
"tree",
".",
"listeners",
"!=",
"null",
")",
"tree",
".",
"no... | This method will add a child to the list of this task's children
@param child the child task which will be added
@return the index where the child has been added.
@throws IllegalStateException if the child cannot be added for whatever reason. | [
"This",
"method",
"will",
"add",
"a",
"child",
"to",
"the",
"list",
"of",
"this",
"task",
"s",
"children"
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/btree/Task.java#L91-L95 |
32,747 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/btree/Task.java | Task.checkGuard | public boolean checkGuard (Task<E> control) {
// No guard to check
if (guard == null) return true;
// Check the guard of the guard recursively
if (!guard.checkGuard(control)) return false;
// Use the tree's guard evaluator task to check the guard of this task
guard.setControl(control.tree.guardEvaluator);
guard.start();
guard.run();
switch (guard.getStatus()) {
case SUCCEEDED:
return true;
case FAILED:
return false;
default:
throw new IllegalStateException("Illegal guard status '" + guard.getStatus() + "'. Guards must either succeed or fail in one step.");
}
} | java | public boolean checkGuard (Task<E> control) {
// No guard to check
if (guard == null) return true;
// Check the guard of the guard recursively
if (!guard.checkGuard(control)) return false;
// Use the tree's guard evaluator task to check the guard of this task
guard.setControl(control.tree.guardEvaluator);
guard.start();
guard.run();
switch (guard.getStatus()) {
case SUCCEEDED:
return true;
case FAILED:
return false;
default:
throw new IllegalStateException("Illegal guard status '" + guard.getStatus() + "'. Guards must either succeed or fail in one step.");
}
} | [
"public",
"boolean",
"checkGuard",
"(",
"Task",
"<",
"E",
">",
"control",
")",
"{",
"// No guard to check",
"if",
"(",
"guard",
"==",
"null",
")",
"return",
"true",
";",
"// Check the guard of the guard recursively",
"if",
"(",
"!",
"guard",
".",
"checkGuard",
... | Checks the guard of this task.
@param control the parent task
@return {@code true} if guard evaluation succeeds or there's no guard; {@code false} otherwise.
@throws IllegalStateException if guard evaluation returns any status other than {@link Status#SUCCEEDED} and
{@link Status#FAILED}. | [
"Checks",
"the",
"guard",
"of",
"this",
"task",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/btree/Task.java#L148-L167 |
32,748 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/btree/Task.java | Task.cancel | public final void cancel () {
cancelRunningChildren(0);
Status previousStatus = status;
status = Status.CANCELLED;
if (tree.listeners != null && tree.listeners.size > 0) tree.notifyStatusUpdated(this, previousStatus);
end();
} | java | public final void cancel () {
cancelRunningChildren(0);
Status previousStatus = status;
status = Status.CANCELLED;
if (tree.listeners != null && tree.listeners.size > 0) tree.notifyStatusUpdated(this, previousStatus);
end();
} | [
"public",
"final",
"void",
"cancel",
"(",
")",
"{",
"cancelRunningChildren",
"(",
"0",
")",
";",
"Status",
"previousStatus",
"=",
"status",
";",
"status",
"=",
"Status",
".",
"CANCELLED",
";",
"if",
"(",
"tree",
".",
"listeners",
"!=",
"null",
"&&",
"tre... | Terminates this task and all its running children. This method MUST be called only if this task is running. | [
"Terminates",
"this",
"task",
"and",
"all",
"its",
"running",
"children",
".",
"This",
"method",
"MUST",
"be",
"called",
"only",
"if",
"this",
"task",
"is",
"running",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/btree/Task.java#L225-L231 |
32,749 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/btree/Task.java | Task.cancelRunningChildren | protected void cancelRunningChildren (int startIndex) {
for (int i = startIndex, n = getChildCount(); i < n; i++) {
Task<E> child = getChild(i);
if (child.status == Status.RUNNING) child.cancel();
}
} | java | protected void cancelRunningChildren (int startIndex) {
for (int i = startIndex, n = getChildCount(); i < n; i++) {
Task<E> child = getChild(i);
if (child.status == Status.RUNNING) child.cancel();
}
} | [
"protected",
"void",
"cancelRunningChildren",
"(",
"int",
"startIndex",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"startIndex",
",",
"n",
"=",
"getChildCount",
"(",
")",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"Task",
"<",
"E",
">",
"child",
"="... | Terminates the running children of this task starting from the specified index up to the end.
@param startIndex the start index | [
"Terminates",
"the",
"running",
"children",
"of",
"this",
"task",
"starting",
"from",
"the",
"specified",
"index",
"up",
"to",
"the",
"end",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/btree/Task.java#L235-L240 |
32,750 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/btree/Task.java | Task.resetTask | public void resetTask () {
if (status == Status.RUNNING) cancel();
for (int i = 0, n = getChildCount(); i < n; i++) {
getChild(i).resetTask();
}
status = Status.FRESH;
tree = null;
control = null;
} | java | public void resetTask () {
if (status == Status.RUNNING) cancel();
for (int i = 0, n = getChildCount(); i < n; i++) {
getChild(i).resetTask();
}
status = Status.FRESH;
tree = null;
control = null;
} | [
"public",
"void",
"resetTask",
"(",
")",
"{",
"if",
"(",
"status",
"==",
"Status",
".",
"RUNNING",
")",
"cancel",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"n",
"=",
"getChildCount",
"(",
")",
";",
"i",
"<",
"n",
";",
"i",
"++",
"... | Resets this task to make it restart from scratch on next run. | [
"Resets",
"this",
"task",
"to",
"make",
"it",
"restart",
"from",
"scratch",
"on",
"next",
"run",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/btree/Task.java#L243-L251 |
32,751 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/utils/ArithmeticUtils.java | ArithmeticUtils.mulAndCheck | public static int mulAndCheck (int x, int y) throws ArithmeticException {
long m = ((long)x) * ((long)y);
if (m < Integer.MIN_VALUE || m > Integer.MAX_VALUE) {
throw new ArithmeticException();
}
return (int)m;
} | java | public static int mulAndCheck (int x, int y) throws ArithmeticException {
long m = ((long)x) * ((long)y);
if (m < Integer.MIN_VALUE || m > Integer.MAX_VALUE) {
throw new ArithmeticException();
}
return (int)m;
} | [
"public",
"static",
"int",
"mulAndCheck",
"(",
"int",
"x",
",",
"int",
"y",
")",
"throws",
"ArithmeticException",
"{",
"long",
"m",
"=",
"(",
"(",
"long",
")",
"x",
")",
"*",
"(",
"(",
"long",
")",
"y",
")",
";",
"if",
"(",
"m",
"<",
"Integer",
... | Multiply two integers, checking for overflow.
@param x first factor
@param y second factor
@return the product {@code x * y}.
@throws ArithmeticException if the result can not be represented as an {@code int}. | [
"Multiply",
"two",
"integers",
"checking",
"for",
"overflow",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/utils/ArithmeticUtils.java#L149-L155 |
32,752 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/btree/utils/PooledBehaviorTreeLibrary.java | PooledBehaviorTreeLibrary.getPool | protected Pool<BehaviorTree> getPool(final String treeReference){
Pool<BehaviorTree> treePool = pools.get(treeReference);
if(treePool == null){
treePool = new Pool<BehaviorTree>(){
@Override
protected BehaviorTree newObject() {
return newBehaviorTree(treeReference);
}
};
pools.put(treeReference, treePool);
}
return treePool;
} | java | protected Pool<BehaviorTree> getPool(final String treeReference){
Pool<BehaviorTree> treePool = pools.get(treeReference);
if(treePool == null){
treePool = new Pool<BehaviorTree>(){
@Override
protected BehaviorTree newObject() {
return newBehaviorTree(treeReference);
}
};
pools.put(treeReference, treePool);
}
return treePool;
} | [
"protected",
"Pool",
"<",
"BehaviorTree",
">",
"getPool",
"(",
"final",
"String",
"treeReference",
")",
"{",
"Pool",
"<",
"BehaviorTree",
">",
"treePool",
"=",
"pools",
".",
"get",
"(",
"treeReference",
")",
";",
"if",
"(",
"treePool",
"==",
"null",
")",
... | retrieve pool by tree reference, create it if not already exists.
@param treeReference
@return existing or newly created pool. | [
"retrieve",
"pool",
"by",
"tree",
"reference",
"create",
"it",
"if",
"not",
"already",
"exists",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/btree/utils/PooledBehaviorTreeLibrary.java#L26-L38 |
32,753 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/btree/utils/PooledBehaviorTreeLibrary.java | PooledBehaviorTreeLibrary.clear | public void clear(String treeReference){
Pool<BehaviorTree> treePool = pools.get(treeReference);
if(treePool != null){
treePool.clear();
}
} | java | public void clear(String treeReference){
Pool<BehaviorTree> treePool = pools.get(treeReference);
if(treePool != null){
treePool.clear();
}
} | [
"public",
"void",
"clear",
"(",
"String",
"treeReference",
")",
"{",
"Pool",
"<",
"BehaviorTree",
">",
"treePool",
"=",
"pools",
".",
"get",
"(",
"treeReference",
")",
";",
"if",
"(",
"treePool",
"!=",
"null",
")",
"{",
"treePool",
".",
"clear",
"(",
"... | Clear pool for a tree reference.
@param treeReference | [
"Clear",
"pool",
"for",
"a",
"tree",
"reference",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/btree/utils/PooledBehaviorTreeLibrary.java#L68-L73 |
32,754 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/btree/utils/PooledBehaviorTreeLibrary.java | PooledBehaviorTreeLibrary.clear | public void clear(){
for(Entry<String, Pool<BehaviorTree>> entry : pools.entries()){
entry.value.clear();
}
pools.clear();
} | java | public void clear(){
for(Entry<String, Pool<BehaviorTree>> entry : pools.entries()){
entry.value.clear();
}
pools.clear();
} | [
"public",
"void",
"clear",
"(",
")",
"{",
"for",
"(",
"Entry",
"<",
"String",
",",
"Pool",
"<",
"BehaviorTree",
">",
">",
"entry",
":",
"pools",
".",
"entries",
"(",
")",
")",
"{",
"entry",
".",
"value",
".",
"clear",
"(",
")",
";",
"}",
"pools",... | clear all pools. | [
"clear",
"all",
"pools",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/btree/utils/PooledBehaviorTreeLibrary.java#L78-L83 |
32,755 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/steer/behaviors/ReachOrientation.java | ReachOrientation.reachOrientation | protected SteeringAcceleration<T> reachOrientation (SteeringAcceleration<T> steering, float targetOrientation) {
// Get the rotation direction to the target wrapped to the range [-PI, PI]
float rotation = ArithmeticUtils.wrapAngleAroundZero(targetOrientation - owner.getOrientation());
// Absolute rotation
float rotationSize = rotation < 0f ? -rotation : rotation;
// Check if we are there, return no steering
if (rotationSize <= alignTolerance) return steering.setZero();
Limiter actualLimiter = getActualLimiter();
// Use maximum rotation
float targetRotation = actualLimiter.getMaxAngularSpeed();
// If we are inside the slow down radius, then calculate a scaled rotation
if (rotationSize <= decelerationRadius) targetRotation *= rotationSize / decelerationRadius;
// The final target rotation combines
// speed (already in the variable) and direction
targetRotation *= rotation / rotationSize;
// Acceleration tries to get to the target rotation
steering.angular = (targetRotation - owner.getAngularVelocity()) / timeToTarget;
// Check if the absolute acceleration is too great
float angularAcceleration = steering.angular < 0f ? -steering.angular : steering.angular;
if (angularAcceleration > actualLimiter.getMaxAngularAcceleration())
steering.angular *= actualLimiter.getMaxAngularAcceleration() / angularAcceleration;
// No linear acceleration
steering.linear.setZero();
// Output the steering
return steering;
} | java | protected SteeringAcceleration<T> reachOrientation (SteeringAcceleration<T> steering, float targetOrientation) {
// Get the rotation direction to the target wrapped to the range [-PI, PI]
float rotation = ArithmeticUtils.wrapAngleAroundZero(targetOrientation - owner.getOrientation());
// Absolute rotation
float rotationSize = rotation < 0f ? -rotation : rotation;
// Check if we are there, return no steering
if (rotationSize <= alignTolerance) return steering.setZero();
Limiter actualLimiter = getActualLimiter();
// Use maximum rotation
float targetRotation = actualLimiter.getMaxAngularSpeed();
// If we are inside the slow down radius, then calculate a scaled rotation
if (rotationSize <= decelerationRadius) targetRotation *= rotationSize / decelerationRadius;
// The final target rotation combines
// speed (already in the variable) and direction
targetRotation *= rotation / rotationSize;
// Acceleration tries to get to the target rotation
steering.angular = (targetRotation - owner.getAngularVelocity()) / timeToTarget;
// Check if the absolute acceleration is too great
float angularAcceleration = steering.angular < 0f ? -steering.angular : steering.angular;
if (angularAcceleration > actualLimiter.getMaxAngularAcceleration())
steering.angular *= actualLimiter.getMaxAngularAcceleration() / angularAcceleration;
// No linear acceleration
steering.linear.setZero();
// Output the steering
return steering;
} | [
"protected",
"SteeringAcceleration",
"<",
"T",
">",
"reachOrientation",
"(",
"SteeringAcceleration",
"<",
"T",
">",
"steering",
",",
"float",
"targetOrientation",
")",
"{",
"// Get the rotation direction to the target wrapped to the range [-PI, PI]",
"float",
"rotation",
"=",... | Produces a steering that tries to align the owner to the target orientation. This method is called by subclasses that want
to align to a certain orientation.
@param steering the steering to be calculated.
@param targetOrientation the target orientation you want to align to.
@return the calculated steering for chaining. | [
"Produces",
"a",
"steering",
"that",
"tries",
"to",
"align",
"the",
"owner",
"to",
"the",
"target",
"orientation",
".",
"This",
"method",
"is",
"called",
"by",
"subclasses",
"that",
"want",
"to",
"align",
"to",
"a",
"certain",
"orientation",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/steer/behaviors/ReachOrientation.java#L78-L113 |
32,756 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/steer/behaviors/Jump.java | Jump.calculateTarget | private Steerable<T> calculateTarget () {
this.jumpTarget.position = jumpDescriptor.takeoffPosition;
this.airborneTime = calculateAirborneTimeAndVelocity(jumpTarget.linearVelocity, jumpDescriptor, getActualLimiter()
.getMaxLinearSpeed());
this.isJumpAchievable = airborneTime >= 0;
return jumpTarget;
} | java | private Steerable<T> calculateTarget () {
this.jumpTarget.position = jumpDescriptor.takeoffPosition;
this.airborneTime = calculateAirborneTimeAndVelocity(jumpTarget.linearVelocity, jumpDescriptor, getActualLimiter()
.getMaxLinearSpeed());
this.isJumpAchievable = airborneTime >= 0;
return jumpTarget;
} | [
"private",
"Steerable",
"<",
"T",
">",
"calculateTarget",
"(",
")",
"{",
"this",
".",
"jumpTarget",
".",
"position",
"=",
"jumpDescriptor",
".",
"takeoffPosition",
";",
"this",
".",
"airborneTime",
"=",
"calculateAirborneTimeAndVelocity",
"(",
"jumpTarget",
".",
... | Works out the trajectory calculation. | [
"Works",
"out",
"the",
"trajectory",
"calculation",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/steer/behaviors/Jump.java#L117-L123 |
32,757 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/steer/behaviors/Jump.java | Jump.setJumpDescriptor | public Jump<T> setJumpDescriptor (JumpDescriptor<T> jumpDescriptor) {
this.jumpDescriptor = jumpDescriptor;
this.target = null;
this.isJumpAchievable = false;
return this;
} | java | public Jump<T> setJumpDescriptor (JumpDescriptor<T> jumpDescriptor) {
this.jumpDescriptor = jumpDescriptor;
this.target = null;
this.isJumpAchievable = false;
return this;
} | [
"public",
"Jump",
"<",
"T",
">",
"setJumpDescriptor",
"(",
"JumpDescriptor",
"<",
"T",
">",
"jumpDescriptor",
")",
"{",
"this",
".",
"jumpDescriptor",
"=",
"jumpDescriptor",
";",
"this",
".",
"target",
"=",
"null",
";",
"this",
".",
"isJumpAchievable",
"=",
... | Sets the jump descriptor to use.
@param jumpDescriptor the jump descriptor to set
@return this behavior for chaining. | [
"Sets",
"the",
"jump",
"descriptor",
"to",
"use",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/steer/behaviors/Jump.java#L185-L190 |
32,758 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/sched/LoadBalancingScheduler.java | LoadBalancingScheduler.run | @Override
public void run (long timeToRun) {
// Increment the frame number
frame++;
// Clear the list of tasks to run
runList.size = 0;
// Go through each task
for (int i = 0; i < schedulableRecords.size; i++) {
SchedulableRecord record = schedulableRecords.get(i);
// If it is due, schedule it
if ((frame + record.phase) % record.frequency == 0) runList.add(record);
}
// Keep track of the current time
long lastTime = TimeUtils.nanoTime();
// Find the number of tasks we need to run
int numToRun = runList.size;
// Go through the tasks to run
for (int i = 0; i < numToRun; i++) {
// Find the available time
long currentTime = TimeUtils.nanoTime();
timeToRun -= currentTime - lastTime;
long availableTime = timeToRun / (numToRun - i);
// Run the schedulable object
runList.get(i).schedulable.run(availableTime);
// Store the current time
lastTime = currentTime;
}
} | java | @Override
public void run (long timeToRun) {
// Increment the frame number
frame++;
// Clear the list of tasks to run
runList.size = 0;
// Go through each task
for (int i = 0; i < schedulableRecords.size; i++) {
SchedulableRecord record = schedulableRecords.get(i);
// If it is due, schedule it
if ((frame + record.phase) % record.frequency == 0) runList.add(record);
}
// Keep track of the current time
long lastTime = TimeUtils.nanoTime();
// Find the number of tasks we need to run
int numToRun = runList.size;
// Go through the tasks to run
for (int i = 0; i < numToRun; i++) {
// Find the available time
long currentTime = TimeUtils.nanoTime();
timeToRun -= currentTime - lastTime;
long availableTime = timeToRun / (numToRun - i);
// Run the schedulable object
runList.get(i).schedulable.run(availableTime);
// Store the current time
lastTime = currentTime;
}
} | [
"@",
"Override",
"public",
"void",
"run",
"(",
"long",
"timeToRun",
")",
"{",
"// Increment the frame number",
"frame",
"++",
";",
"// Clear the list of tasks to run",
"runList",
".",
"size",
"=",
"0",
";",
"// Go through each task",
"for",
"(",
"int",
"i",
"=",
... | Executes scheduled tasks based on their frequency and phase. This method must be called once per frame.
@param timeToRun the maximum time in nanoseconds this scheduler should run on the current frame. | [
"Executes",
"scheduled",
"tasks",
"based",
"on",
"their",
"frequency",
"and",
"phase",
".",
"This",
"method",
"must",
"be",
"called",
"once",
"per",
"frame",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/sched/LoadBalancingScheduler.java#L81-L115 |
32,759 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/utils/Collision.java | Collision.set | public Collision<T> set (Collision<T> collision) {
this.point.set(collision.point);
this.normal.set(collision.normal);
return this;
} | java | public Collision<T> set (Collision<T> collision) {
this.point.set(collision.point);
this.normal.set(collision.normal);
return this;
} | [
"public",
"Collision",
"<",
"T",
">",
"set",
"(",
"Collision",
"<",
"T",
">",
"collision",
")",
"{",
"this",
".",
"point",
".",
"set",
"(",
"collision",
".",
"point",
")",
";",
"this",
".",
"normal",
".",
"set",
"(",
"collision",
".",
"normal",
")"... | Sets this collision from the given collision.
@param collision The collision
@return this collision for chaining. | [
"Sets",
"this",
"collision",
"from",
"the",
"given",
"collision",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/utils/Collision.java#L45-L49 |
32,760 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/utils/Collision.java | Collision.set | public Collision<T> set (T point, T normal) {
this.point.set(point);
this.normal.set(normal);
return this;
} | java | public Collision<T> set (T point, T normal) {
this.point.set(point);
this.normal.set(normal);
return this;
} | [
"public",
"Collision",
"<",
"T",
">",
"set",
"(",
"T",
"point",
",",
"T",
"normal",
")",
"{",
"this",
".",
"point",
".",
"set",
"(",
"point",
")",
";",
"this",
".",
"normal",
".",
"set",
"(",
"normal",
")",
";",
"return",
"this",
";",
"}"
] | Sets this collision from the given point and normal.
@param point the collision point
@param normal the normal of this collision
@return this collision for chaining. | [
"Sets",
"this",
"collision",
"from",
"the",
"given",
"point",
"and",
"normal",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/utils/Collision.java#L55-L59 |
32,761 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/btree/utils/BehaviorTreeLibrary.java | BehaviorTreeLibrary.retrieveArchetypeTree | protected BehaviorTree<?> retrieveArchetypeTree (String treeReference) {
BehaviorTree<?> archetypeTree = repository.get(treeReference);
if (archetypeTree == null) {
// if (assetManager != null) {
// // TODO: fix me!!!
// // archetypeTree = assetManager.load(name, BehaviorTree.class, null);
// repository.put(treeReference, archetypeTree);
// return null;
// }
archetypeTree = parser.parse(resolver.resolve(treeReference), null);
registerArchetypeTree(treeReference, archetypeTree);
}
return archetypeTree;
} | java | protected BehaviorTree<?> retrieveArchetypeTree (String treeReference) {
BehaviorTree<?> archetypeTree = repository.get(treeReference);
if (archetypeTree == null) {
// if (assetManager != null) {
// // TODO: fix me!!!
// // archetypeTree = assetManager.load(name, BehaviorTree.class, null);
// repository.put(treeReference, archetypeTree);
// return null;
// }
archetypeTree = parser.parse(resolver.resolve(treeReference), null);
registerArchetypeTree(treeReference, archetypeTree);
}
return archetypeTree;
} | [
"protected",
"BehaviorTree",
"<",
"?",
">",
"retrieveArchetypeTree",
"(",
"String",
"treeReference",
")",
"{",
"BehaviorTree",
"<",
"?",
">",
"archetypeTree",
"=",
"repository",
".",
"get",
"(",
"treeReference",
")",
";",
"if",
"(",
"archetypeTree",
"==",
"nul... | Retrieves the archetype tree from the library. If the library doesn't contain the archetype tree it is loaded and added to
the library.
@param treeReference the tree identifier, typically a path
@return the archetype tree.
@throws SerializationException if the reference cannot be successfully parsed. | [
"Retrieves",
"the",
"archetype",
"tree",
"from",
"the",
"library",
".",
"If",
"the",
"library",
"doesn",
"t",
"contain",
"the",
"archetype",
"tree",
"it",
"is",
"loaded",
"and",
"added",
"to",
"the",
"library",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/btree/utils/BehaviorTreeLibrary.java#L121-L134 |
32,762 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/btree/utils/BehaviorTreeLibrary.java | BehaviorTreeLibrary.disposeBehaviorTree | public void disposeBehaviorTree(String treeReference, BehaviorTree<?> behaviorTree){
if(Task.TASK_CLONER != null){
Task.TASK_CLONER.freeTask(behaviorTree);
}
} | java | public void disposeBehaviorTree(String treeReference, BehaviorTree<?> behaviorTree){
if(Task.TASK_CLONER != null){
Task.TASK_CLONER.freeTask(behaviorTree);
}
} | [
"public",
"void",
"disposeBehaviorTree",
"(",
"String",
"treeReference",
",",
"BehaviorTree",
"<",
"?",
">",
"behaviorTree",
")",
"{",
"if",
"(",
"Task",
".",
"TASK_CLONER",
"!=",
"null",
")",
"{",
"Task",
".",
"TASK_CLONER",
".",
"freeTask",
"(",
"behaviorT... | Dispose behavior tree obtain by this library.
@param treeReference the tree identifier.
@param behaviorTree the tree to dispose. | [
"Dispose",
"behavior",
"tree",
"obtain",
"by",
"this",
"library",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/btree/utils/BehaviorTreeLibrary.java#L160-L164 |
32,763 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/pfa/PathFinderRequestControl.java | PathFinderRequestControl.execute | public boolean execute (PathFinderRequest<N> request) {
request.executionFrames++;
while (true) {
if (DEBUG) GdxAI.getLogger().debug(TAG, "------");
// Should perform search begin?
if (request.status == PathFinderRequest.SEARCH_NEW) {
long currentTime = TimeUtils.nanoTime();
timeToRun -= currentTime - lastTime;
if (timeToRun <= timeTolerance) return false;
if (DEBUG) GdxAI.getLogger().debug(TAG, "search begin");
if (!request.initializeSearch(timeToRun)) return false;
request.changeStatus(PathFinderRequest.SEARCH_INITIALIZED);
lastTime = currentTime;
}
// Should perform search path?
if (request.status == PathFinderRequest.SEARCH_INITIALIZED) {
long currentTime = TimeUtils.nanoTime();
timeToRun -= currentTime - lastTime;
if (timeToRun <= timeTolerance) return false;
if (DEBUG) GdxAI.getLogger().debug(TAG, "search path");
if (!request.search(pathFinder, timeToRun)) return false;
request.changeStatus(PathFinderRequest.SEARCH_DONE);
lastTime = currentTime;
}
// Should perform search end?
if (request.status == PathFinderRequest.SEARCH_DONE) {
long currentTime = TimeUtils.nanoTime();
timeToRun -= currentTime - lastTime;
if (timeToRun <= timeTolerance) return false;
if (DEBUG) GdxAI.getLogger().debug(TAG, "search end");
if (!request.finalizeSearch(timeToRun)) return false;
request.changeStatus(PathFinderRequest.SEARCH_FINALIZED);
// Search finished, send result to the client
if (server != null) {
MessageDispatcher dispatcher = request.dispatcher != null ? request.dispatcher : MessageManager.getInstance();
dispatcher.dispatchMessage(server, request.client, request.responseMessageCode, request);
}
lastTime = currentTime;
if (request.statusChanged && request.status == PathFinderRequest.SEARCH_NEW) {
if (DEBUG) GdxAI.getLogger().debug(TAG, "search renew");
continue;
}
}
return true;
}
} | java | public boolean execute (PathFinderRequest<N> request) {
request.executionFrames++;
while (true) {
if (DEBUG) GdxAI.getLogger().debug(TAG, "------");
// Should perform search begin?
if (request.status == PathFinderRequest.SEARCH_NEW) {
long currentTime = TimeUtils.nanoTime();
timeToRun -= currentTime - lastTime;
if (timeToRun <= timeTolerance) return false;
if (DEBUG) GdxAI.getLogger().debug(TAG, "search begin");
if (!request.initializeSearch(timeToRun)) return false;
request.changeStatus(PathFinderRequest.SEARCH_INITIALIZED);
lastTime = currentTime;
}
// Should perform search path?
if (request.status == PathFinderRequest.SEARCH_INITIALIZED) {
long currentTime = TimeUtils.nanoTime();
timeToRun -= currentTime - lastTime;
if (timeToRun <= timeTolerance) return false;
if (DEBUG) GdxAI.getLogger().debug(TAG, "search path");
if (!request.search(pathFinder, timeToRun)) return false;
request.changeStatus(PathFinderRequest.SEARCH_DONE);
lastTime = currentTime;
}
// Should perform search end?
if (request.status == PathFinderRequest.SEARCH_DONE) {
long currentTime = TimeUtils.nanoTime();
timeToRun -= currentTime - lastTime;
if (timeToRun <= timeTolerance) return false;
if (DEBUG) GdxAI.getLogger().debug(TAG, "search end");
if (!request.finalizeSearch(timeToRun)) return false;
request.changeStatus(PathFinderRequest.SEARCH_FINALIZED);
// Search finished, send result to the client
if (server != null) {
MessageDispatcher dispatcher = request.dispatcher != null ? request.dispatcher : MessageManager.getInstance();
dispatcher.dispatchMessage(server, request.client, request.responseMessageCode, request);
}
lastTime = currentTime;
if (request.statusChanged && request.status == PathFinderRequest.SEARCH_NEW) {
if (DEBUG) GdxAI.getLogger().debug(TAG, "search renew");
continue;
}
}
return true;
}
} | [
"public",
"boolean",
"execute",
"(",
"PathFinderRequest",
"<",
"N",
">",
"request",
")",
"{",
"request",
".",
"executionFrames",
"++",
";",
"while",
"(",
"true",
")",
"{",
"if",
"(",
"DEBUG",
")",
"GdxAI",
".",
"getLogger",
"(",
")",
".",
"debug",
"(",... | Executes the given pathfinding request resuming it if needed.
@param request the pathfinding request
@return {@code true} if this operation has completed; {@code false} if more time is needed to complete. | [
"Executes",
"the",
"given",
"pathfinding",
"request",
"resuming",
"it",
"if",
"needed",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/pfa/PathFinderRequestControl.java#L48-L101 |
32,764 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/fsm/StackStateMachine.java | StackStateMachine.revertToPreviousState | @Override
public boolean revertToPreviousState () {
if (stateStack.size == 0) {
return false;
}
S previousState = stateStack.pop();
changeState(previousState, false);
return true;
} | java | @Override
public boolean revertToPreviousState () {
if (stateStack.size == 0) {
return false;
}
S previousState = stateStack.pop();
changeState(previousState, false);
return true;
} | [
"@",
"Override",
"public",
"boolean",
"revertToPreviousState",
"(",
")",
"{",
"if",
"(",
"stateStack",
".",
"size",
"==",
"0",
")",
"{",
"return",
"false",
";",
"}",
"S",
"previousState",
"=",
"stateStack",
".",
"pop",
"(",
")",
";",
"changeState",
"(",
... | Changes the Change state back to the previous state. That is the high-most state on the internal stack of previous states.
@return {@code True} in case there was a previous state that we were able to revert to. In case there is no previous state,
no state change occurs and {@code false} will be returned. | [
"Changes",
"the",
"Change",
"state",
"back",
"to",
"the",
"previous",
"state",
".",
"That",
"is",
"the",
"high",
"-",
"most",
"state",
"on",
"the",
"internal",
"stack",
"of",
"previous",
"states",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/fsm/StackStateMachine.java#L92-L101 |
32,765 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/steer/behaviors/FollowPath.java | FollowPath.setPath | public FollowPath<T, P> setPath (Path<T, P> path) {
this.path = path;
return this;
} | java | public FollowPath<T, P> setPath (Path<T, P> path) {
this.path = path;
return this;
} | [
"public",
"FollowPath",
"<",
"T",
",",
"P",
">",
"setPath",
"(",
"Path",
"<",
"T",
",",
"P",
">",
"path",
")",
"{",
"this",
".",
"path",
"=",
"path",
";",
"return",
"this",
";",
"}"
] | Sets the path followed by this behavior.
@param path the path to set
@return this behavior for chaining. | [
"Sets",
"the",
"path",
"followed",
"by",
"this",
"behavior",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/steer/behaviors/FollowPath.java#L146-L149 |
32,766 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/pfa/PathSmoother.java | PathSmoother.smoothPath | public int smoothPath (SmoothableGraphPath<N, V> path) {
int inputPathLength = path.getCount();
// If the path is two nodes long or less, then we can't smooth it
if (inputPathLength <= 2) return 0;
// Make sure the ray is instantiated
if (this.ray == null) {
V vec = path.getNodePosition(0);
this.ray = new Ray<V>(vec.cpy(), vec.cpy());
}
// Keep track of where we are in the smoothed path.
// We start at 1, because we must always include the start node in the smoothed path.
int outputIndex = 1;
// Keep track of where we are in the input path
// We start at 2, because we assume two adjacent
// nodes will pass the ray cast
int inputIndex = 2;
// Loop until we find the last item in the input
while (inputIndex < inputPathLength) {
// Set the ray
ray.start.set(path.getNodePosition(outputIndex - 1));
ray.end.set(path.getNodePosition(inputIndex));
// Do the ray cast
boolean collides = raycastCollisionDetector.collides(ray);
if (collides) {
// The ray test failed, swap nodes and consider the next output node
path.swapNodes(outputIndex, inputIndex - 1);
outputIndex++;
}
// Consider the next input node
inputIndex++;
}
// Reached the last input node, always add it to the smoothed path.
path.swapNodes(outputIndex, inputIndex - 1);
path.truncatePath(outputIndex + 1);
// Return the number of removed nodes
return inputIndex - outputIndex - 1;
} | java | public int smoothPath (SmoothableGraphPath<N, V> path) {
int inputPathLength = path.getCount();
// If the path is two nodes long or less, then we can't smooth it
if (inputPathLength <= 2) return 0;
// Make sure the ray is instantiated
if (this.ray == null) {
V vec = path.getNodePosition(0);
this.ray = new Ray<V>(vec.cpy(), vec.cpy());
}
// Keep track of where we are in the smoothed path.
// We start at 1, because we must always include the start node in the smoothed path.
int outputIndex = 1;
// Keep track of where we are in the input path
// We start at 2, because we assume two adjacent
// nodes will pass the ray cast
int inputIndex = 2;
// Loop until we find the last item in the input
while (inputIndex < inputPathLength) {
// Set the ray
ray.start.set(path.getNodePosition(outputIndex - 1));
ray.end.set(path.getNodePosition(inputIndex));
// Do the ray cast
boolean collides = raycastCollisionDetector.collides(ray);
if (collides) {
// The ray test failed, swap nodes and consider the next output node
path.swapNodes(outputIndex, inputIndex - 1);
outputIndex++;
}
// Consider the next input node
inputIndex++;
}
// Reached the last input node, always add it to the smoothed path.
path.swapNodes(outputIndex, inputIndex - 1);
path.truncatePath(outputIndex + 1);
// Return the number of removed nodes
return inputIndex - outputIndex - 1;
} | [
"public",
"int",
"smoothPath",
"(",
"SmoothableGraphPath",
"<",
"N",
",",
"V",
">",
"path",
")",
"{",
"int",
"inputPathLength",
"=",
"path",
".",
"getCount",
"(",
")",
";",
"// If the path is two nodes long or less, then we can't smooth it",
"if",
"(",
"inputPathLen... | Smoothes the given path in place.
@param path the path to smooth
@return the number of nodes removed from the path. | [
"Smoothes",
"the",
"given",
"path",
"in",
"place",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/pfa/PathSmoother.java#L59-L105 |
32,767 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/pfa/PathSmoother.java | PathSmoother.smoothPath | public boolean smoothPath (PathSmootherRequest<N, V> request, long timeToRun) {
long lastTime = TimeUtils.nanoTime();
SmoothableGraphPath<N, V> path = request.path;
int inputPathLength = path.getCount();
// If the path is two nodes long or less, then we can't smooth it
if (inputPathLength <= 2) return true;
if (request.isNew) {
request.isNew = false;
// Make sure the ray is instantiated
if (this.ray == null) {
V vec = request.path.getNodePosition(0);
this.ray = new Ray<V>(vec.cpy(), vec.cpy());
}
// Keep track of where we are in the smoothed path.
// We start at 1, because we must always include the start node in the smoothed path.
request.outputIndex = 1;
// Keep track of where we are in the input path
// We start at 2, because we assume two adjacent
// nodes will pass the ray cast
request.inputIndex = 2;
}
// Loop until we find the last item in the input
while (request.inputIndex < inputPathLength) {
// Check the available time
long currentTime = TimeUtils.nanoTime();
timeToRun -= currentTime - lastTime;
if (timeToRun <= PathFinderQueue.TIME_TOLERANCE) return false;
// Set the ray
ray.start.set(path.getNodePosition(request.outputIndex - 1));
ray.end.set(path.getNodePosition(request.inputIndex));
// Do the ray cast
boolean collided = raycastCollisionDetector.collides(ray);
if (collided) {
// The ray test failed, swap nodes and consider the next output node
path.swapNodes(request.outputIndex, request.inputIndex - 1);
request.outputIndex++;
}
// Consider the next input node
request.inputIndex++;
// Store the current time
lastTime = currentTime;
}
// Reached the last input node, always add it to the smoothed path
path.swapNodes(request.outputIndex, request.inputIndex - 1);
path.truncatePath(request.outputIndex + 1);
// Smooth completed
return true;
} | java | public boolean smoothPath (PathSmootherRequest<N, V> request, long timeToRun) {
long lastTime = TimeUtils.nanoTime();
SmoothableGraphPath<N, V> path = request.path;
int inputPathLength = path.getCount();
// If the path is two nodes long or less, then we can't smooth it
if (inputPathLength <= 2) return true;
if (request.isNew) {
request.isNew = false;
// Make sure the ray is instantiated
if (this.ray == null) {
V vec = request.path.getNodePosition(0);
this.ray = new Ray<V>(vec.cpy(), vec.cpy());
}
// Keep track of where we are in the smoothed path.
// We start at 1, because we must always include the start node in the smoothed path.
request.outputIndex = 1;
// Keep track of where we are in the input path
// We start at 2, because we assume two adjacent
// nodes will pass the ray cast
request.inputIndex = 2;
}
// Loop until we find the last item in the input
while (request.inputIndex < inputPathLength) {
// Check the available time
long currentTime = TimeUtils.nanoTime();
timeToRun -= currentTime - lastTime;
if (timeToRun <= PathFinderQueue.TIME_TOLERANCE) return false;
// Set the ray
ray.start.set(path.getNodePosition(request.outputIndex - 1));
ray.end.set(path.getNodePosition(request.inputIndex));
// Do the ray cast
boolean collided = raycastCollisionDetector.collides(ray);
if (collided) {
// The ray test failed, swap nodes and consider the next output node
path.swapNodes(request.outputIndex, request.inputIndex - 1);
request.outputIndex++;
}
// Consider the next input node
request.inputIndex++;
// Store the current time
lastTime = currentTime;
}
// Reached the last input node, always add it to the smoothed path
path.swapNodes(request.outputIndex, request.inputIndex - 1);
path.truncatePath(request.outputIndex + 1);
// Smooth completed
return true;
} | [
"public",
"boolean",
"smoothPath",
"(",
"PathSmootherRequest",
"<",
"N",
",",
"V",
">",
"request",
",",
"long",
"timeToRun",
")",
"{",
"long",
"lastTime",
"=",
"TimeUtils",
".",
"nanoTime",
"(",
")",
";",
"SmoothableGraphPath",
"<",
"N",
",",
"V",
">",
"... | Smoothes in place the path specified by the given request, possibly over multiple consecutive frames.
@param request the path smoothing request
@param timeToRun the time in nanoseconds that this call can use on the current frame
@return {@code true} if this operation has completed; {@code false} if more time is needed to complete. | [
"Smoothes",
"in",
"place",
"the",
"path",
"specified",
"by",
"the",
"given",
"request",
"possibly",
"over",
"multiple",
"consecutive",
"frames",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/pfa/PathSmoother.java#L111-L175 |
32,768 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/utils/Ray.java | Ray.set | public Ray<T> set (Ray<T> ray) {
start.set(ray.start);
end.set(ray.end);
return this;
} | java | public Ray<T> set (Ray<T> ray) {
start.set(ray.start);
end.set(ray.end);
return this;
} | [
"public",
"Ray",
"<",
"T",
">",
"set",
"(",
"Ray",
"<",
"T",
">",
"ray",
")",
"{",
"start",
".",
"set",
"(",
"ray",
".",
"start",
")",
";",
"end",
".",
"set",
"(",
"ray",
".",
"end",
")",
";",
"return",
"this",
";",
"}"
] | Sets this ray from the given ray.
@param ray The ray
@return this ray for chaining. | [
"Sets",
"this",
"ray",
"from",
"the",
"given",
"ray",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/utils/Ray.java#L45-L49 |
32,769 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/utils/Ray.java | Ray.set | public Ray<T> set (T start, T end) {
this.start.set(start);
this.end.set(end);
return this;
} | java | public Ray<T> set (T start, T end) {
this.start.set(start);
this.end.set(end);
return this;
} | [
"public",
"Ray",
"<",
"T",
">",
"set",
"(",
"T",
"start",
",",
"T",
"end",
")",
"{",
"this",
".",
"start",
".",
"set",
"(",
"start",
")",
";",
"this",
".",
"end",
".",
"set",
"(",
"end",
")",
";",
"return",
"this",
";",
"}"
] | Sets this Ray from the given start and end points.
@param start the starting point of this ray
@param end the starting point of this ray
@return this ray for chaining. | [
"Sets",
"this",
"Ray",
"from",
"the",
"given",
"start",
"and",
"end",
"points",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/utils/Ray.java#L55-L59 |
32,770 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/steer/behaviors/BlendedSteering.java | BlendedSteering.remove | public void remove (SteeringBehavior<T> behavior) {
for (int i = 0; i < list.size; i++) {
if(list.get(i).behavior == behavior) {
list.removeIndex(i);
return;
}
}
} | java | public void remove (SteeringBehavior<T> behavior) {
for (int i = 0; i < list.size; i++) {
if(list.get(i).behavior == behavior) {
list.removeIndex(i);
return;
}
}
} | [
"public",
"void",
"remove",
"(",
"SteeringBehavior",
"<",
"T",
">",
"behavior",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"list",
".",
"size",
";",
"i",
"++",
")",
"{",
"if",
"(",
"list",
".",
"get",
"(",
"i",
")",
".",
"beha... | Removes a steering behavior from the list.
@param behavior the steering behavior to remove | [
"Removes",
"a",
"steering",
"behavior",
"from",
"the",
"list",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/steer/behaviors/BlendedSteering.java#L90-L97 |
32,771 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/steer/SteeringAcceleration.java | SteeringAcceleration.add | public SteeringAcceleration<T> add (SteeringAcceleration<T> steering) {
linear.add(steering.linear);
angular += steering.angular;
return this;
} | java | public SteeringAcceleration<T> add (SteeringAcceleration<T> steering) {
linear.add(steering.linear);
angular += steering.angular;
return this;
} | [
"public",
"SteeringAcceleration",
"<",
"T",
">",
"add",
"(",
"SteeringAcceleration",
"<",
"T",
">",
"steering",
")",
"{",
"linear",
".",
"add",
"(",
"steering",
".",
"linear",
")",
";",
"angular",
"+=",
"steering",
".",
"angular",
";",
"return",
"this",
... | Adds the given steering acceleration to this steering acceleration.
@param steering the steering acceleration
@return this steering acceleration for chaining | [
"Adds",
"the",
"given",
"steering",
"acceleration",
"to",
"this",
"steering",
"acceleration",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/steer/SteeringAcceleration.java#L68-L72 |
32,772 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/steer/SteeringAcceleration.java | SteeringAcceleration.mulAdd | public SteeringAcceleration<T> mulAdd (SteeringAcceleration<T> steering, float scalar) {
linear.mulAdd(steering.linear, scalar);
angular += steering.angular * scalar;
return this;
} | java | public SteeringAcceleration<T> mulAdd (SteeringAcceleration<T> steering, float scalar) {
linear.mulAdd(steering.linear, scalar);
angular += steering.angular * scalar;
return this;
} | [
"public",
"SteeringAcceleration",
"<",
"T",
">",
"mulAdd",
"(",
"SteeringAcceleration",
"<",
"T",
">",
"steering",
",",
"float",
"scalar",
")",
"{",
"linear",
".",
"mulAdd",
"(",
"steering",
".",
"linear",
",",
"scalar",
")",
";",
"angular",
"+=",
"steerin... | First scale a supplied steering acceleration, then add it to this steering acceleration.
@param steering the steering acceleration
@param scalar the scalar
@return this steering acceleration for chaining | [
"First",
"scale",
"a",
"supplied",
"steering",
"acceleration",
"then",
"add",
"it",
"to",
"this",
"steering",
"acceleration",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/steer/SteeringAcceleration.java#L89-L93 |
32,773 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/msg/MessageDispatcher.java | MessageDispatcher.addListener | public void addListener (Telegraph listener, int msg) {
Array<Telegraph> listeners = msgListeners.get(msg);
if (listeners == null) {
// Associate an empty unordered array with the message code
listeners = new Array<Telegraph>(false, 16);
msgListeners.put(msg, listeners);
}
listeners.add(listener);
// Dispatch messages from registered providers
Array<TelegramProvider> providers = msgProviders.get(msg);
if (providers != null) {
for (int i = 0, n = providers.size; i < n; i++) {
TelegramProvider provider = providers.get(i);
Object info = provider.provideMessageInfo(msg, listener);
if (info != null) {
Telegraph sender = ClassReflection.isInstance(Telegraph.class, provider) ? (Telegraph)provider : null;
dispatchMessage(0, sender, listener, msg, info, false);
}
}
}
} | java | public void addListener (Telegraph listener, int msg) {
Array<Telegraph> listeners = msgListeners.get(msg);
if (listeners == null) {
// Associate an empty unordered array with the message code
listeners = new Array<Telegraph>(false, 16);
msgListeners.put(msg, listeners);
}
listeners.add(listener);
// Dispatch messages from registered providers
Array<TelegramProvider> providers = msgProviders.get(msg);
if (providers != null) {
for (int i = 0, n = providers.size; i < n; i++) {
TelegramProvider provider = providers.get(i);
Object info = provider.provideMessageInfo(msg, listener);
if (info != null) {
Telegraph sender = ClassReflection.isInstance(Telegraph.class, provider) ? (Telegraph)provider : null;
dispatchMessage(0, sender, listener, msg, info, false);
}
}
}
} | [
"public",
"void",
"addListener",
"(",
"Telegraph",
"listener",
",",
"int",
"msg",
")",
"{",
"Array",
"<",
"Telegraph",
">",
"listeners",
"=",
"msgListeners",
".",
"get",
"(",
"msg",
")",
";",
"if",
"(",
"listeners",
"==",
"null",
")",
"{",
"// Associate ... | Registers a listener for the specified message code. Messages without an explicit receiver are broadcasted to all its
registered listeners.
@param listener the listener to add
@param msg the message code | [
"Registers",
"a",
"listener",
"for",
"the",
"specified",
"message",
"code",
".",
"Messages",
"without",
"an",
"explicit",
"receiver",
"are",
"broadcasted",
"to",
"all",
"its",
"registered",
"listeners",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/msg/MessageDispatcher.java#L69-L90 |
32,774 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/steer/SteeringBehavior.java | SteeringBehavior.calculateSteering | public SteeringAcceleration<T> calculateSteering (SteeringAcceleration<T> steering) {
return isEnabled() ? calculateRealSteering(steering) : steering.setZero();
} | java | public SteeringAcceleration<T> calculateSteering (SteeringAcceleration<T> steering) {
return isEnabled() ? calculateRealSteering(steering) : steering.setZero();
} | [
"public",
"SteeringAcceleration",
"<",
"T",
">",
"calculateSteering",
"(",
"SteeringAcceleration",
"<",
"T",
">",
"steering",
")",
"{",
"return",
"isEnabled",
"(",
")",
"?",
"calculateRealSteering",
"(",
"steering",
")",
":",
"steering",
".",
"setZero",
"(",
"... | If this behavior is enabled calculates the steering acceleration and writes it to the given steering output. If it is
disabled the steering output is set to zero.
@param steering the steering acceleration to be calculated.
@return the calculated steering acceleration for chaining. | [
"If",
"this",
"behavior",
"is",
"enabled",
"calculates",
"the",
"steering",
"acceleration",
"and",
"writes",
"it",
"to",
"the",
"given",
"steering",
"output",
".",
"If",
"it",
"is",
"disabled",
"the",
"steering",
"output",
"is",
"set",
"to",
"zero",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/steer/SteeringBehavior.java#L78-L80 |
32,775 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/fma/Formation.java | Formation.updateSlotAssignments | public void updateSlotAssignments () {
// Apply the strategy to update slot assignments
slotAssignmentStrategy.updateSlotAssignments(slotAssignments);
// Set the newly calculated number of slots
pattern.setNumberOfSlots(slotAssignmentStrategy.calculateNumberOfSlots(slotAssignments));
// Update the drift offset if a motion moderator is set
if (motionModerator != null) motionModerator.calculateDriftOffset(driftOffset, slotAssignments, pattern);
} | java | public void updateSlotAssignments () {
// Apply the strategy to update slot assignments
slotAssignmentStrategy.updateSlotAssignments(slotAssignments);
// Set the newly calculated number of slots
pattern.setNumberOfSlots(slotAssignmentStrategy.calculateNumberOfSlots(slotAssignments));
// Update the drift offset if a motion moderator is set
if (motionModerator != null) motionModerator.calculateDriftOffset(driftOffset, slotAssignments, pattern);
} | [
"public",
"void",
"updateSlotAssignments",
"(",
")",
"{",
"// Apply the strategy to update slot assignments",
"slotAssignmentStrategy",
".",
"updateSlotAssignments",
"(",
"slotAssignments",
")",
";",
"// Set the newly calculated number of slots",
"pattern",
".",
"setNumberOfSlots",... | Updates the assignment of members to slots | [
"Updates",
"the",
"assignment",
"of",
"members",
"to",
"slots"
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/fma/Formation.java#L147-L156 |
32,776 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/fma/Formation.java | Formation.changePattern | public boolean changePattern (FormationPattern<T> pattern) {
// Find out how many slots we have occupied
int occupiedSlots = slotAssignments.size;
// Check if the pattern supports one more slot
if (pattern.supportsSlots(occupiedSlots)) {
setPattern(pattern);
// Update the slot assignments and return success
updateSlotAssignments();
return true;
}
return false;
} | java | public boolean changePattern (FormationPattern<T> pattern) {
// Find out how many slots we have occupied
int occupiedSlots = slotAssignments.size;
// Check if the pattern supports one more slot
if (pattern.supportsSlots(occupiedSlots)) {
setPattern(pattern);
// Update the slot assignments and return success
updateSlotAssignments();
return true;
}
return false;
} | [
"public",
"boolean",
"changePattern",
"(",
"FormationPattern",
"<",
"T",
">",
"pattern",
")",
"{",
"// Find out how many slots we have occupied",
"int",
"occupiedSlots",
"=",
"slotAssignments",
".",
"size",
";",
"// Check if the pattern supports one more slot",
"if",
"(",
... | Changes the pattern of this formation and updates slot assignments if the number of member is supported by the given
pattern.
@param pattern the pattern to set
@return {@code true} if the pattern has effectively changed; {@code false} otherwise. | [
"Changes",
"the",
"pattern",
"of",
"this",
"formation",
"and",
"updates",
"slot",
"assignments",
"if",
"the",
"number",
"of",
"member",
"is",
"supported",
"by",
"the",
"given",
"pattern",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/fma/Formation.java#L162-L177 |
32,777 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/fma/Formation.java | Formation.addMember | public boolean addMember (FormationMember<T> member) {
// Find out how many slots we have occupied
int occupiedSlots = slotAssignments.size;
// Check if the pattern supports one more slot
if (pattern.supportsSlots(occupiedSlots + 1)) {
// Add a new slot assignment
slotAssignments.add(new SlotAssignment<T>(member, occupiedSlots));
// Update the slot assignments and return success
updateSlotAssignments();
return true;
}
return false;
} | java | public boolean addMember (FormationMember<T> member) {
// Find out how many slots we have occupied
int occupiedSlots = slotAssignments.size;
// Check if the pattern supports one more slot
if (pattern.supportsSlots(occupiedSlots + 1)) {
// Add a new slot assignment
slotAssignments.add(new SlotAssignment<T>(member, occupiedSlots));
// Update the slot assignments and return success
updateSlotAssignments();
return true;
}
return false;
} | [
"public",
"boolean",
"addMember",
"(",
"FormationMember",
"<",
"T",
">",
"member",
")",
"{",
"// Find out how many slots we have occupied",
"int",
"occupiedSlots",
"=",
"slotAssignments",
".",
"size",
";",
"// Check if the pattern supports one more slot",
"if",
"(",
"patt... | Adds a new member to the first available slot and updates slot assignments if the number of member is supported by the
current pattern.
@param member the member to add
@return {@code false} if no more slots are available; {@code true} otherwise. | [
"Adds",
"a",
"new",
"member",
"to",
"the",
"first",
"available",
"slot",
"and",
"updates",
"slot",
"assignments",
"if",
"the",
"number",
"of",
"member",
"is",
"supported",
"by",
"the",
"current",
"pattern",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/fma/Formation.java#L183-L198 |
32,778 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/fma/Formation.java | Formation.removeMember | public void removeMember (FormationMember<T> member) {
// Find the member's slot
int slot = findMemberSlot(member);
// Make sure we've found a valid result
if (slot >= 0) {
// Remove the slot
// slotAssignments.removeIndex(slot);
slotAssignmentStrategy.removeSlotAssignment(slotAssignments, slot);
// Update the assignments
updateSlotAssignments();
}
} | java | public void removeMember (FormationMember<T> member) {
// Find the member's slot
int slot = findMemberSlot(member);
// Make sure we've found a valid result
if (slot >= 0) {
// Remove the slot
// slotAssignments.removeIndex(slot);
slotAssignmentStrategy.removeSlotAssignment(slotAssignments, slot);
// Update the assignments
updateSlotAssignments();
}
} | [
"public",
"void",
"removeMember",
"(",
"FormationMember",
"<",
"T",
">",
"member",
")",
"{",
"// Find the member's slot",
"int",
"slot",
"=",
"findMemberSlot",
"(",
"member",
")",
";",
"// Make sure we've found a valid result",
"if",
"(",
"slot",
">=",
"0",
")",
... | Removes a member from its slot and updates slot assignments.
@param member the member to remove | [
"Removes",
"a",
"member",
"from",
"its",
"slot",
"and",
"updates",
"slot",
"assignments",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/fma/Formation.java#L202-L215 |
32,779 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/fma/Formation.java | Formation.updateSlots | public void updateSlots () {
// Find the anchor point
Location<T> anchor = getAnchorPoint();
positionOffset.set(anchor.getPosition());
float orientationOffset = anchor.getOrientation();
if (motionModerator != null) {
positionOffset.sub(driftOffset.getPosition());
orientationOffset -= driftOffset.getOrientation();
}
// Get the orientation of the anchor point as a matrix
orientationMatrix.idt().rotateRad(anchor.getOrientation());
// Go through each member in turn
for (int i = 0; i < slotAssignments.size; i++) {
SlotAssignment<T> slotAssignment = slotAssignments.get(i);
// Retrieve the location reference of the formation member to calculate the new value
Location<T> relativeLoc = slotAssignment.member.getTargetLocation();
// Ask for the location of the slot relative to the anchor point
pattern.calculateSlotLocation(relativeLoc, slotAssignment.slotNumber);
T relativeLocPosition = relativeLoc.getPosition();
// System.out.println("relativeLoc.position = " + relativeLocPosition);
// [17:31] <@Xoppa> davebaol, interface Transform<T extends Vector<T>> { T getTranslation(); T getScale(); float getRotation();
// void transform(T val); }
// [17:31] <@Xoppa>
// https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g3d/utils/BaseAnimationController.java#L40
// [17:34] * ThreadL0ck (~ThreadL0c@197.220.114.182) Quit (Remote host closed the connection)
// [17:35] <davebaol> thanks Xoppa, sounds interesting
// TODO Consider the possibility of declaring mul(orientationMatrix) in Vector
// Transform it by the anchor point's position and orientation
// relativeLocPosition.mul(orientationMatrix).add(anchor.position);
if (relativeLocPosition instanceof Vector2)
((Vector2)relativeLocPosition).mul(orientationMatrix);
else if (relativeLocPosition instanceof Vector3) ((Vector3)relativeLocPosition).mul(orientationMatrix);
// Add the anchor and drift components
relativeLocPosition.add(positionOffset);
relativeLoc.setOrientation(relativeLoc.getOrientation() + orientationOffset);
}
// Possibly reset the anchor point if a moderator is set
if (motionModerator != null) {
motionModerator.updateAnchorPoint(anchor);
}
} | java | public void updateSlots () {
// Find the anchor point
Location<T> anchor = getAnchorPoint();
positionOffset.set(anchor.getPosition());
float orientationOffset = anchor.getOrientation();
if (motionModerator != null) {
positionOffset.sub(driftOffset.getPosition());
orientationOffset -= driftOffset.getOrientation();
}
// Get the orientation of the anchor point as a matrix
orientationMatrix.idt().rotateRad(anchor.getOrientation());
// Go through each member in turn
for (int i = 0; i < slotAssignments.size; i++) {
SlotAssignment<T> slotAssignment = slotAssignments.get(i);
// Retrieve the location reference of the formation member to calculate the new value
Location<T> relativeLoc = slotAssignment.member.getTargetLocation();
// Ask for the location of the slot relative to the anchor point
pattern.calculateSlotLocation(relativeLoc, slotAssignment.slotNumber);
T relativeLocPosition = relativeLoc.getPosition();
// System.out.println("relativeLoc.position = " + relativeLocPosition);
// [17:31] <@Xoppa> davebaol, interface Transform<T extends Vector<T>> { T getTranslation(); T getScale(); float getRotation();
// void transform(T val); }
// [17:31] <@Xoppa>
// https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g3d/utils/BaseAnimationController.java#L40
// [17:34] * ThreadL0ck (~ThreadL0c@197.220.114.182) Quit (Remote host closed the connection)
// [17:35] <davebaol> thanks Xoppa, sounds interesting
// TODO Consider the possibility of declaring mul(orientationMatrix) in Vector
// Transform it by the anchor point's position and orientation
// relativeLocPosition.mul(orientationMatrix).add(anchor.position);
if (relativeLocPosition instanceof Vector2)
((Vector2)relativeLocPosition).mul(orientationMatrix);
else if (relativeLocPosition instanceof Vector3) ((Vector3)relativeLocPosition).mul(orientationMatrix);
// Add the anchor and drift components
relativeLocPosition.add(positionOffset);
relativeLoc.setOrientation(relativeLoc.getOrientation() + orientationOffset);
}
// Possibly reset the anchor point if a moderator is set
if (motionModerator != null) {
motionModerator.updateAnchorPoint(anchor);
}
} | [
"public",
"void",
"updateSlots",
"(",
")",
"{",
"// Find the anchor point",
"Location",
"<",
"T",
">",
"anchor",
"=",
"getAnchorPoint",
"(",
")",
";",
"positionOffset",
".",
"set",
"(",
"anchor",
".",
"getPosition",
"(",
")",
")",
";",
"float",
"orientationO... | Writes new slot locations to each member | [
"Writes",
"new",
"slot",
"locations",
"to",
"each",
"member"
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/fma/Formation.java#L235-L286 |
32,780 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/btree/utils/BehaviorTreeReader.java | BehaviorTreeReader.containsFloatingPointCharacters | private static boolean containsFloatingPointCharacters (String value) {
for (int i = 0, n = value.length(); i < n; i++) {
switch (value.charAt(i)) {
case '.':
case 'E':
case 'e':
return true;
}
}
return false;
} | java | private static boolean containsFloatingPointCharacters (String value) {
for (int i = 0, n = value.length(); i < n; i++) {
switch (value.charAt(i)) {
case '.':
case 'E':
case 'e':
return true;
}
}
return false;
} | [
"private",
"static",
"boolean",
"containsFloatingPointCharacters",
"(",
"String",
"value",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"n",
"=",
"value",
".",
"length",
"(",
")",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"switch",
"(",
"va... | line 315 "BehaviorTreeReader.rl" | [
"line",
"315",
"BehaviorTreeReader",
".",
"rl"
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/btree/utils/BehaviorTreeReader.java#L728-L738 |
32,781 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/fsm/DefaultStateMachine.java | DefaultStateMachine.handleMessage | @Override
public boolean handleMessage (Telegram telegram) {
// First see if the current state is valid and that it can handle the message
if (currentState != null && currentState.onMessage(owner, telegram)) {
return true;
}
// If not, and if a global state has been implemented, send
// the message to the global state
if (globalState != null && globalState.onMessage(owner, telegram)) {
return true;
}
return false;
} | java | @Override
public boolean handleMessage (Telegram telegram) {
// First see if the current state is valid and that it can handle the message
if (currentState != null && currentState.onMessage(owner, telegram)) {
return true;
}
// If not, and if a global state has been implemented, send
// the message to the global state
if (globalState != null && globalState.onMessage(owner, telegram)) {
return true;
}
return false;
} | [
"@",
"Override",
"public",
"boolean",
"handleMessage",
"(",
"Telegram",
"telegram",
")",
"{",
"// First see if the current state is valid and that it can handle the message",
"if",
"(",
"currentState",
"!=",
"null",
"&&",
"currentState",
".",
"onMessage",
"(",
"owner",
",... | Handles received telegrams. The telegram is first routed to the current state. If the current state does not deal with the
message, it's routed to the global state's message handler.
@param telegram the received telegram
@return true if telegram has been successfully handled; false otherwise. | [
"Handles",
"received",
"telegrams",
".",
"The",
"telegram",
"is",
"first",
"routed",
"to",
"the",
"current",
"state",
".",
"If",
"the",
"current",
"state",
"does",
"not",
"deal",
"with",
"the",
"message",
"it",
"s",
"routed",
"to",
"the",
"global",
"state"... | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/fsm/DefaultStateMachine.java#L158-L173 |
32,782 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/utils/CircularBuffer.java | CircularBuffer.store | public boolean store (T item) {
if (size == items.length) {
if (!resizable) return false;
// Resize this queue
resize(Math.max(8, (int)(items.length * 1.75f)));
}
size++;
items[tail++] = item;
if (tail == items.length) tail = 0;
return true;
} | java | public boolean store (T item) {
if (size == items.length) {
if (!resizable) return false;
// Resize this queue
resize(Math.max(8, (int)(items.length * 1.75f)));
}
size++;
items[tail++] = item;
if (tail == items.length) tail = 0;
return true;
} | [
"public",
"boolean",
"store",
"(",
"T",
"item",
")",
"{",
"if",
"(",
"size",
"==",
"items",
".",
"length",
")",
"{",
"if",
"(",
"!",
"resizable",
")",
"return",
"false",
";",
"// Resize this queue",
"resize",
"(",
"Math",
".",
"max",
"(",
"8",
",",
... | Adds the given item to the tail of this circular buffer.
@param item the item to add
@return {@code true} if the item has been successfully added to this circular buffer; {@code false} otherwise. | [
"Adds",
"the",
"given",
"item",
"to",
"the",
"tail",
"of",
"this",
"circular",
"buffer",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/utils/CircularBuffer.java#L57-L68 |
32,783 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/utils/CircularBuffer.java | CircularBuffer.clear | public void clear () {
final T[] items = this.items;
if (tail > head) {
int i = head, n = tail;
do {
items[i++] = null;
} while (i < n);
} else if (size > 0) { // NOTE: when head == tail the buffer can be empty or full
for (int i = head, n = items.length; i < n; i++)
items[i] = null;
for (int i = 0, n = tail; i < n; i++)
items[i] = null;
}
this.head = 0;
this.tail = 0;
this.size = 0;
} | java | public void clear () {
final T[] items = this.items;
if (tail > head) {
int i = head, n = tail;
do {
items[i++] = null;
} while (i < n);
} else if (size > 0) { // NOTE: when head == tail the buffer can be empty or full
for (int i = head, n = items.length; i < n; i++)
items[i] = null;
for (int i = 0, n = tail; i < n; i++)
items[i] = null;
}
this.head = 0;
this.tail = 0;
this.size = 0;
} | [
"public",
"void",
"clear",
"(",
")",
"{",
"final",
"T",
"[",
"]",
"items",
"=",
"this",
".",
"items",
";",
"if",
"(",
"tail",
">",
"head",
")",
"{",
"int",
"i",
"=",
"head",
",",
"n",
"=",
"tail",
";",
"do",
"{",
"items",
"[",
"i",
"++",
"]... | Removes all items from this circular buffer. | [
"Removes",
"all",
"items",
"from",
"this",
"circular",
"buffer",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/utils/CircularBuffer.java#L85-L101 |
32,784 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/utils/CircularBuffer.java | CircularBuffer.resize | protected void resize (int newCapacity) {
@SuppressWarnings("unchecked")
T[] newItems = (T[])ArrayReflection.newInstance(items.getClass().getComponentType(), newCapacity);
if (tail > head) {
System.arraycopy(items, head, newItems, 0, size);
} else if (size > 0) { // NOTE: when head == tail the buffer can be empty or full
System.arraycopy(items, head, newItems, 0, items.length - head);
System.arraycopy(items, 0, newItems, items.length - head, tail);
}
head = 0;
tail = size;
items = newItems;
} | java | protected void resize (int newCapacity) {
@SuppressWarnings("unchecked")
T[] newItems = (T[])ArrayReflection.newInstance(items.getClass().getComponentType(), newCapacity);
if (tail > head) {
System.arraycopy(items, head, newItems, 0, size);
} else if (size > 0) { // NOTE: when head == tail the buffer can be empty or full
System.arraycopy(items, head, newItems, 0, items.length - head);
System.arraycopy(items, 0, newItems, items.length - head, tail);
}
head = 0;
tail = size;
items = newItems;
} | [
"protected",
"void",
"resize",
"(",
"int",
"newCapacity",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"T",
"[",
"]",
"newItems",
"=",
"(",
"T",
"[",
"]",
")",
"ArrayReflection",
".",
"newInstance",
"(",
"items",
".",
"getClass",
"(",
")... | Creates a new backing array with the specified capacity containing the current items.
@param newCapacity the new capacity | [
"Creates",
"a",
"new",
"backing",
"array",
"with",
"the",
"specified",
"capacity",
"containing",
"the",
"current",
"items",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/utils/CircularBuffer.java#L139-L151 |
32,785 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/btree/BehaviorTree.java | BehaviorTree.addChildToTask | @Override
protected int addChildToTask (Task<E> child) {
if (this.rootTask != null) throw new IllegalStateException("A behavior tree cannot have more than one root task");
this.rootTask = child;
return 0;
} | java | @Override
protected int addChildToTask (Task<E> child) {
if (this.rootTask != null) throw new IllegalStateException("A behavior tree cannot have more than one root task");
this.rootTask = child;
return 0;
} | [
"@",
"Override",
"protected",
"int",
"addChildToTask",
"(",
"Task",
"<",
"E",
">",
"child",
")",
"{",
"if",
"(",
"this",
".",
"rootTask",
"!=",
"null",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"A behavior tree cannot have more than one root task\"",
")... | This method will add a child, namely the root, to this behavior tree.
@param child the root task to add
@return the index where the root task has been added (always 0).
@throws IllegalStateException if the root task is already set. | [
"This",
"method",
"will",
"add",
"a",
"child",
"namely",
"the",
"root",
"to",
"this",
"behavior",
"tree",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/btree/BehaviorTree.java#L82-L87 |
32,786 | libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/fma/FormationMotionModerator.java | FormationMotionModerator.calculateDriftOffset | public Location<T> calculateDriftOffset (Location<T> centerOfMass, Array<SlotAssignment<T>> slotAssignments,
FormationPattern<T> pattern) {
// Clear the center of mass
centerOfMass.getPosition().setZero();
float centerOfMassOrientation = 0;
// Make sure tempLocation is instantiated
if (tempLocation == null) tempLocation = centerOfMass.newLocation();
T centerOfMassPos = centerOfMass.getPosition();
T tempLocationPos = tempLocation.getPosition();
// Go through each assignment and add its contribution to the center
float numberOfAssignments = slotAssignments.size;
for (int i = 0; i < numberOfAssignments; i++) {
pattern.calculateSlotLocation(tempLocation, slotAssignments.get(i).slotNumber);
centerOfMassPos.add(tempLocationPos);
centerOfMassOrientation += tempLocation.getOrientation();
}
// Divide through to get the drift offset.
centerOfMassPos.scl(1f / numberOfAssignments);
centerOfMassOrientation /= numberOfAssignments;
centerOfMass.setOrientation(centerOfMassOrientation);
return centerOfMass;
} | java | public Location<T> calculateDriftOffset (Location<T> centerOfMass, Array<SlotAssignment<T>> slotAssignments,
FormationPattern<T> pattern) {
// Clear the center of mass
centerOfMass.getPosition().setZero();
float centerOfMassOrientation = 0;
// Make sure tempLocation is instantiated
if (tempLocation == null) tempLocation = centerOfMass.newLocation();
T centerOfMassPos = centerOfMass.getPosition();
T tempLocationPos = tempLocation.getPosition();
// Go through each assignment and add its contribution to the center
float numberOfAssignments = slotAssignments.size;
for (int i = 0; i < numberOfAssignments; i++) {
pattern.calculateSlotLocation(tempLocation, slotAssignments.get(i).slotNumber);
centerOfMassPos.add(tempLocationPos);
centerOfMassOrientation += tempLocation.getOrientation();
}
// Divide through to get the drift offset.
centerOfMassPos.scl(1f / numberOfAssignments);
centerOfMassOrientation /= numberOfAssignments;
centerOfMass.setOrientation(centerOfMassOrientation);
return centerOfMass;
} | [
"public",
"Location",
"<",
"T",
">",
"calculateDriftOffset",
"(",
"Location",
"<",
"T",
">",
"centerOfMass",
",",
"Array",
"<",
"SlotAssignment",
"<",
"T",
">",
">",
"slotAssignments",
",",
"FormationPattern",
"<",
"T",
">",
"pattern",
")",
"{",
"// Clear th... | Calculates the drift offset when members are in the given set of slots for the specified pattern.
@param centerOfMass the output location set to the calculated drift offset
@param slotAssignments the set of slots
@param pattern the pattern
@return the given location for chaining. | [
"Calculates",
"the",
"drift",
"offset",
"when",
"members",
"are",
"in",
"the",
"given",
"set",
"of",
"slots",
"for",
"the",
"specified",
"pattern",
"."
] | 2d1523a97193a45e18e11a4837c6800d08f177c5 | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/fma/FormationMotionModerator.java#L43-L70 |
32,787 | bbottema/simple-java-mail | modules/cli-module/src/main/java/org/simplejavamail/internal/clisupport/CliCommandLineConsumer.java | CliCommandLineConsumer.consumeCommandLineInput | static CliReceivedCommand consumeCommandLineInput(ParseResult providedCommand, @SuppressWarnings("SameParameterValue") Iterable<CliDeclaredOptionSpec> declaredOptions) {
assumeTrue(providedCommand.hasSubcommand(), "Command was empty, expected one of: " + Arrays.toString(CliCommandType.values()));
final ParseResult mailCommand = providedCommand.subcommand();
final CliCommandType matchedCommand = CliCommandType.valueOf(mailCommand.commandSpec().name());
final Map<CliDeclaredOptionSpec, OptionSpec> matchedOptionsInOrderProvision = matchProvidedOptions(declaredOptions, mailCommand.matchedOptions());
logParsedInput(matchedCommand, matchedOptionsInOrderProvision);
List<CliReceivedOptionData> receivedOptions = new ArrayList<>();
for (Entry<CliDeclaredOptionSpec, OptionSpec> cliOption : matchedOptionsInOrderProvision.entrySet()) {
final Method sourceMethod = cliOption.getKey().getSourceMethod();
final int mandatoryParameters = MiscUtil.countMandatoryParameters(sourceMethod);
final List<String> providedStringValues = cliOption.getValue().getValue();
assumeTrue(providedStringValues.size() >= mandatoryParameters,
format("provided %s arguments, but need at least %s", providedStringValues.size(), mandatoryParameters));
assumeTrue(providedStringValues.size() <= sourceMethod.getParameterTypes().length,
format("provided %s arguments, but need at most %s", providedStringValues.size(), sourceMethod.getParameterTypes().length));
receivedOptions.add(new CliReceivedOptionData(cliOption.getKey(), convertProvidedOptionValues(providedStringValues, sourceMethod)));
LOGGER.debug("\tconverted option values: {}", getLast(receivedOptions).getProvidedOptionValues());
}
return new CliReceivedCommand(matchedCommand, receivedOptions);
} | java | static CliReceivedCommand consumeCommandLineInput(ParseResult providedCommand, @SuppressWarnings("SameParameterValue") Iterable<CliDeclaredOptionSpec> declaredOptions) {
assumeTrue(providedCommand.hasSubcommand(), "Command was empty, expected one of: " + Arrays.toString(CliCommandType.values()));
final ParseResult mailCommand = providedCommand.subcommand();
final CliCommandType matchedCommand = CliCommandType.valueOf(mailCommand.commandSpec().name());
final Map<CliDeclaredOptionSpec, OptionSpec> matchedOptionsInOrderProvision = matchProvidedOptions(declaredOptions, mailCommand.matchedOptions());
logParsedInput(matchedCommand, matchedOptionsInOrderProvision);
List<CliReceivedOptionData> receivedOptions = new ArrayList<>();
for (Entry<CliDeclaredOptionSpec, OptionSpec> cliOption : matchedOptionsInOrderProvision.entrySet()) {
final Method sourceMethod = cliOption.getKey().getSourceMethod();
final int mandatoryParameters = MiscUtil.countMandatoryParameters(sourceMethod);
final List<String> providedStringValues = cliOption.getValue().getValue();
assumeTrue(providedStringValues.size() >= mandatoryParameters,
format("provided %s arguments, but need at least %s", providedStringValues.size(), mandatoryParameters));
assumeTrue(providedStringValues.size() <= sourceMethod.getParameterTypes().length,
format("provided %s arguments, but need at most %s", providedStringValues.size(), sourceMethod.getParameterTypes().length));
receivedOptions.add(new CliReceivedOptionData(cliOption.getKey(), convertProvidedOptionValues(providedStringValues, sourceMethod)));
LOGGER.debug("\tconverted option values: {}", getLast(receivedOptions).getProvidedOptionValues());
}
return new CliReceivedCommand(matchedCommand, receivedOptions);
} | [
"static",
"CliReceivedCommand",
"consumeCommandLineInput",
"(",
"ParseResult",
"providedCommand",
",",
"@",
"SuppressWarnings",
"(",
"\"SameParameterValue\"",
")",
"Iterable",
"<",
"CliDeclaredOptionSpec",
">",
"declaredOptions",
")",
"{",
"assumeTrue",
"(",
"providedComman... | we reach here when terminal input was value and no help was requested | [
"we",
"reach",
"here",
"when",
"terminal",
"input",
"was",
"value",
"and",
"no",
"help",
"was",
"requested"
] | b03635328aeecd525e35eddfef8f5b9a184559d8 | https://github.com/bbottema/simple-java-mail/blob/b03635328aeecd525e35eddfef8f5b9a184559d8/modules/cli-module/src/main/java/org/simplejavamail/internal/clisupport/CliCommandLineConsumer.java#L38-L61 |
32,788 | bbottema/simple-java-mail | modules/core-module/src/main/java/org/simplejavamail/internal/util/MiscUtil.java | MiscUtil.encodeText | @Nullable
public static String encodeText(@Nullable final String name) {
if (name == null) {
return null;
}
try {
return MimeUtility.encodeText(name);
} catch (final UnsupportedEncodingException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
} | java | @Nullable
public static String encodeText(@Nullable final String name) {
if (name == null) {
return null;
}
try {
return MimeUtility.encodeText(name);
} catch (final UnsupportedEncodingException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
} | [
"@",
"Nullable",
"public",
"static",
"String",
"encodeText",
"(",
"@",
"Nullable",
"final",
"String",
"name",
")",
"{",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"try",
"{",
"return",
"MimeUtility",
".",
"encodeText",
"(",
... | To make sure email clients can interpret text properly, we need to encode some values according to RFC-2047. | [
"To",
"make",
"sure",
"email",
"clients",
"can",
"interpret",
"text",
"properly",
"we",
"need",
"to",
"encode",
"some",
"values",
"according",
"to",
"RFC",
"-",
"2047",
"."
] | b03635328aeecd525e35eddfef8f5b9a184559d8 | https://github.com/bbottema/simple-java-mail/blob/b03635328aeecd525e35eddfef8f5b9a184559d8/modules/core-module/src/main/java/org/simplejavamail/internal/util/MiscUtil.java#L82-L92 |
32,789 | bbottema/simple-java-mail | modules/simple-java-mail/src/main/java/org/simplejavamail/converter/internal/mimemessage/MimeMessageParser.java | MimeMessageParser.parseMimeMessage | public static ParsedMimeMessageComponents parseMimeMessage(@Nonnull final MimeMessage mimeMessage) {
final ParsedMimeMessageComponents parsedComponents = new ParsedMimeMessageComponents();
parsedComponents.messageId = parseMessageId(mimeMessage);
parsedComponents.subject = parseSubject(mimeMessage);
parsedComponents.toAddresses.addAll(parseToAddresses(mimeMessage));
parsedComponents.ccAddresses.addAll(parseCcAddresses(mimeMessage));
parsedComponents.bccAddresses.addAll(parseBccAddresses(mimeMessage));
parsedComponents.fromAddress = parseFromAddress(mimeMessage);
parsedComponents.replyToAddresses = parseReplyToAddresses(mimeMessage);
parseMimePartTree(mimeMessage, parsedComponents);
moveInvalidEmbeddedResourcesToAttachments(parsedComponents);
return parsedComponents;
} | java | public static ParsedMimeMessageComponents parseMimeMessage(@Nonnull final MimeMessage mimeMessage) {
final ParsedMimeMessageComponents parsedComponents = new ParsedMimeMessageComponents();
parsedComponents.messageId = parseMessageId(mimeMessage);
parsedComponents.subject = parseSubject(mimeMessage);
parsedComponents.toAddresses.addAll(parseToAddresses(mimeMessage));
parsedComponents.ccAddresses.addAll(parseCcAddresses(mimeMessage));
parsedComponents.bccAddresses.addAll(parseBccAddresses(mimeMessage));
parsedComponents.fromAddress = parseFromAddress(mimeMessage);
parsedComponents.replyToAddresses = parseReplyToAddresses(mimeMessage);
parseMimePartTree(mimeMessage, parsedComponents);
moveInvalidEmbeddedResourcesToAttachments(parsedComponents);
return parsedComponents;
} | [
"public",
"static",
"ParsedMimeMessageComponents",
"parseMimeMessage",
"(",
"@",
"Nonnull",
"final",
"MimeMessage",
"mimeMessage",
")",
"{",
"final",
"ParsedMimeMessageComponents",
"parsedComponents",
"=",
"new",
"ParsedMimeMessageComponents",
"(",
")",
";",
"parsedComponen... | Extracts the content of a MimeMessage recursively. | [
"Extracts",
"the",
"content",
"of",
"a",
"MimeMessage",
"recursively",
"."
] | b03635328aeecd525e35eddfef8f5b9a184559d8 | https://github.com/bbottema/simple-java-mail/blob/b03635328aeecd525e35eddfef8f5b9a184559d8/modules/simple-java-mail/src/main/java/org/simplejavamail/converter/internal/mimemessage/MimeMessageParser.java#L115-L127 |
32,790 | bbottema/simple-java-mail | modules/simple-java-mail/src/main/java/org/simplejavamail/converter/internal/mimemessage/MimeMessageParser.java | MimeMessageParser.isMimeType | @SuppressWarnings("WeakerAccess")
public static boolean isMimeType(@Nonnull final MimePart part, @Nonnull final String mimeType) {
// Do not use part.isMimeType(String) as it is broken for MimeBodyPart
// and does not really check the actual content type.
try {
final ContentType contentType = new ContentType(retrieveDataHandler(part).getContentType());
return contentType.match(mimeType);
} catch (final ParseException ex) {
return retrieveContentType(part).equalsIgnoreCase(mimeType);
}
} | java | @SuppressWarnings("WeakerAccess")
public static boolean isMimeType(@Nonnull final MimePart part, @Nonnull final String mimeType) {
// Do not use part.isMimeType(String) as it is broken for MimeBodyPart
// and does not really check the actual content type.
try {
final ContentType contentType = new ContentType(retrieveDataHandler(part).getContentType());
return contentType.match(mimeType);
} catch (final ParseException ex) {
return retrieveContentType(part).equalsIgnoreCase(mimeType);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"WeakerAccess\"",
")",
"public",
"static",
"boolean",
"isMimeType",
"(",
"@",
"Nonnull",
"final",
"MimePart",
"part",
",",
"@",
"Nonnull",
"final",
"String",
"mimeType",
")",
"{",
"// Do not use part.isMimeType(String) as it is broken for... | Checks whether the MimePart contains an object of the given mime type.
@param part the current MimePart
@param mimeType the mime type to check
@return {@code true} if the MimePart matches the given mime type, {@code false} otherwise | [
"Checks",
"whether",
"the",
"MimePart",
"contains",
"an",
"object",
"of",
"the",
"given",
"mime",
"type",
"."
] | b03635328aeecd525e35eddfef8f5b9a184559d8 | https://github.com/bbottema/simple-java-mail/blob/b03635328aeecd525e35eddfef8f5b9a184559d8/modules/simple-java-mail/src/main/java/org/simplejavamail/converter/internal/mimemessage/MimeMessageParser.java#L300-L311 |
32,791 | bbottema/simple-java-mail | modules/simple-java-mail/src/main/java/org/simplejavamail/converter/internal/mimemessage/MimeMessageParser.java | MimeMessageParser.createDataSource | @Nonnull
private static DataSource createDataSource(@Nonnull final MimePart part) {
final DataHandler dataHandler = retrieveDataHandler(part);
final DataSource dataSource = dataHandler.getDataSource();
final String contentType = parseBaseMimeType(dataSource.getContentType());
final byte[] content = readContent(retrieveInputStream(dataSource));
final ByteArrayDataSource result = new ByteArrayDataSource(content, contentType);
final String dataSourceName = parseDataSourceName(part, dataSource);
result.setName(dataSourceName);
return result;
} | java | @Nonnull
private static DataSource createDataSource(@Nonnull final MimePart part) {
final DataHandler dataHandler = retrieveDataHandler(part);
final DataSource dataSource = dataHandler.getDataSource();
final String contentType = parseBaseMimeType(dataSource.getContentType());
final byte[] content = readContent(retrieveInputStream(dataSource));
final ByteArrayDataSource result = new ByteArrayDataSource(content, contentType);
final String dataSourceName = parseDataSourceName(part, dataSource);
result.setName(dataSourceName);
return result;
} | [
"@",
"Nonnull",
"private",
"static",
"DataSource",
"createDataSource",
"(",
"@",
"Nonnull",
"final",
"MimePart",
"part",
")",
"{",
"final",
"DataHandler",
"dataHandler",
"=",
"retrieveDataHandler",
"(",
"part",
")",
";",
"final",
"DataSource",
"dataSource",
"=",
... | Parses the MimePart to create a DataSource.
@param part the current part to be processed
@return the DataSource | [
"Parses",
"the",
"MimePart",
"to",
"create",
"a",
"DataSource",
"."
] | b03635328aeecd525e35eddfef8f5b9a184559d8 | https://github.com/bbottema/simple-java-mail/blob/b03635328aeecd525e35eddfef8f5b9a184559d8/modules/simple-java-mail/src/main/java/org/simplejavamail/converter/internal/mimemessage/MimeMessageParser.java#L337-L348 |
32,792 | bbottema/simple-java-mail | modules/core-module/src/main/java/org/simplejavamail/config/ConfigLoader.java | ConfigLoader.loadProperties | public static Map<Property, Object> loadProperties(final String filename, final boolean addProperties) {
final InputStream input = ConfigLoader.class.getClassLoader().getResourceAsStream(filename);
if (input != null) {
return loadProperties(input, addProperties);
}
LOGGER.debug("Property file not found on classpath, skipping config file");
return new HashMap<>();
} | java | public static Map<Property, Object> loadProperties(final String filename, final boolean addProperties) {
final InputStream input = ConfigLoader.class.getClassLoader().getResourceAsStream(filename);
if (input != null) {
return loadProperties(input, addProperties);
}
LOGGER.debug("Property file not found on classpath, skipping config file");
return new HashMap<>();
} | [
"public",
"static",
"Map",
"<",
"Property",
",",
"Object",
">",
"loadProperties",
"(",
"final",
"String",
"filename",
",",
"final",
"boolean",
"addProperties",
")",
"{",
"final",
"InputStream",
"input",
"=",
"ConfigLoader",
".",
"class",
".",
"getClassLoader",
... | Loads properties from property file on the classpath, if provided. Calling this method only has effect on new Email and Mailer instances after
this.
@param filename Any file that is on the classpath that holds a list of key=value pairs.
@param addProperties Flag to indicate if the new properties should be added or replacing the old properties.
@return The updated properties map that is used internally. | [
"Loads",
"properties",
"from",
"property",
"file",
"on",
"the",
"classpath",
"if",
"provided",
".",
"Calling",
"this",
"method",
"only",
"has",
"effect",
"on",
"new",
"Email",
"and",
"Mailer",
"instances",
"after",
"this",
"."
] | b03635328aeecd525e35eddfef8f5b9a184559d8 | https://github.com/bbottema/simple-java-mail/blob/b03635328aeecd525e35eddfef8f5b9a184559d8/modules/core-module/src/main/java/org/simplejavamail/config/ConfigLoader.java#L214-L221 |
32,793 | bbottema/simple-java-mail | modules/core-module/src/main/java/org/simplejavamail/config/ConfigLoader.java | ConfigLoader.loadProperties | public static Map<Property, Object> loadProperties(final Properties properties, final boolean addProperties) {
if (!addProperties) {
RESOLVED_PROPERTIES.clear();
}
RESOLVED_PROPERTIES.putAll(readProperties(properties));
return unmodifiableMap(RESOLVED_PROPERTIES);
} | java | public static Map<Property, Object> loadProperties(final Properties properties, final boolean addProperties) {
if (!addProperties) {
RESOLVED_PROPERTIES.clear();
}
RESOLVED_PROPERTIES.putAll(readProperties(properties));
return unmodifiableMap(RESOLVED_PROPERTIES);
} | [
"public",
"static",
"Map",
"<",
"Property",
",",
"Object",
">",
"loadProperties",
"(",
"final",
"Properties",
"properties",
",",
"final",
"boolean",
"addProperties",
")",
"{",
"if",
"(",
"!",
"addProperties",
")",
"{",
"RESOLVED_PROPERTIES",
".",
"clear",
"(",... | Loads properties from another properties source, in case you want to provide your own list.
@param properties Your own list of properties
@param addProperties Flag to indicate if the new properties should be added or replacing the old properties.
@return The updated properties map that is used internally. | [
"Loads",
"properties",
"from",
"another",
"properties",
"source",
"in",
"case",
"you",
"want",
"to",
"provide",
"your",
"own",
"list",
"."
] | b03635328aeecd525e35eddfef8f5b9a184559d8 | https://github.com/bbottema/simple-java-mail/blob/b03635328aeecd525e35eddfef8f5b9a184559d8/modules/core-module/src/main/java/org/simplejavamail/config/ConfigLoader.java#L230-L236 |
32,794 | bbottema/simple-java-mail | modules/simple-java-mail/src/main/java/org/simplejavamail/converter/internal/mimemessage/MimeMessageHelper.java | MimeMessageHelper.determineResourceName | static String determineResourceName(final AttachmentResource attachmentResource, final boolean includeExtension) {
final String datasourceName = attachmentResource.getDataSource().getName();
String resourceName;
if (!valueNullOrEmpty(attachmentResource.getName())) {
resourceName = attachmentResource.getName();
} else if (!valueNullOrEmpty(datasourceName)) {
resourceName = datasourceName;
} else {
resourceName = "resource" + UUID.randomUUID();
}
if (includeExtension && !valueNullOrEmpty(datasourceName)) {
@SuppressWarnings("UnnecessaryLocalVariable")
final String possibleFilename = datasourceName;
if (!resourceName.contains(".") && possibleFilename.contains(".")) {
final String extension = possibleFilename.substring(possibleFilename.lastIndexOf("."));
if (!resourceName.endsWith(extension)) {
resourceName += extension;
}
}
} else if (!includeExtension && resourceName.contains(".") && resourceName.equals(datasourceName)) {
final String extension = resourceName.substring(resourceName.lastIndexOf("."));
resourceName = resourceName.replace(extension, "");
}
return resourceName;
} | java | static String determineResourceName(final AttachmentResource attachmentResource, final boolean includeExtension) {
final String datasourceName = attachmentResource.getDataSource().getName();
String resourceName;
if (!valueNullOrEmpty(attachmentResource.getName())) {
resourceName = attachmentResource.getName();
} else if (!valueNullOrEmpty(datasourceName)) {
resourceName = datasourceName;
} else {
resourceName = "resource" + UUID.randomUUID();
}
if (includeExtension && !valueNullOrEmpty(datasourceName)) {
@SuppressWarnings("UnnecessaryLocalVariable")
final String possibleFilename = datasourceName;
if (!resourceName.contains(".") && possibleFilename.contains(".")) {
final String extension = possibleFilename.substring(possibleFilename.lastIndexOf("."));
if (!resourceName.endsWith(extension)) {
resourceName += extension;
}
}
} else if (!includeExtension && resourceName.contains(".") && resourceName.equals(datasourceName)) {
final String extension = resourceName.substring(resourceName.lastIndexOf("."));
resourceName = resourceName.replace(extension, "");
}
return resourceName;
} | [
"static",
"String",
"determineResourceName",
"(",
"final",
"AttachmentResource",
"attachmentResource",
",",
"final",
"boolean",
"includeExtension",
")",
"{",
"final",
"String",
"datasourceName",
"=",
"attachmentResource",
".",
"getDataSource",
"(",
")",
".",
"getName",
... | Determines the right resource name and optionally attaches the correct extension to the name. | [
"Determines",
"the",
"right",
"resource",
"name",
"and",
"optionally",
"attaches",
"the",
"correct",
"extension",
"to",
"the",
"name",
"."
] | b03635328aeecd525e35eddfef8f5b9a184559d8 | https://github.com/bbottema/simple-java-mail/blob/b03635328aeecd525e35eddfef8f5b9a184559d8/modules/simple-java-mail/src/main/java/org/simplejavamail/converter/internal/mimemessage/MimeMessageHelper.java#L246-L272 |
32,795 | bbottema/simple-java-mail | modules/simple-java-mail/src/main/java/org/simplejavamail/converter/internal/mimemessage/NamedDataSource.java | NamedDataSource.getEncoding | @Override
@Nullable
public String getEncoding() {
return (this.dataSource instanceof EncodingAware) ? ((EncodingAware) this.dataSource).getEncoding() : null;
} | java | @Override
@Nullable
public String getEncoding() {
return (this.dataSource instanceof EncodingAware) ? ((EncodingAware) this.dataSource).getEncoding() : null;
} | [
"@",
"Override",
"@",
"Nullable",
"public",
"String",
"getEncoding",
"(",
")",
"{",
"return",
"(",
"this",
".",
"dataSource",
"instanceof",
"EncodingAware",
")",
"?",
"(",
"(",
"EncodingAware",
")",
"this",
".",
"dataSource",
")",
".",
"getEncoding",
"(",
... | Optimization to help Java Mail determine encoding for attachments.
@return The encoding from the nested data source if it implements {@link EncodingAware} as well.
@see <a href="https://github.com/bbottema/simple-java-mail/issues/131">Bug report #131</a> | [
"Optimization",
"to",
"help",
"Java",
"Mail",
"determine",
"encoding",
"for",
"attachments",
"."
] | b03635328aeecd525e35eddfef8f5b9a184559d8 | https://github.com/bbottema/simple-java-mail/blob/b03635328aeecd525e35eddfef8f5b9a184559d8/modules/simple-java-mail/src/main/java/org/simplejavamail/converter/internal/mimemessage/NamedDataSource.java#L81-L85 |
32,796 | bbottema/simple-java-mail | modules/simple-java-mail/src/main/java/org/simplejavamail/mailer/internal/mailsender/AsyncOperationHelper.java | AsyncOperationHelper.executeAsync | static AsyncResponse executeAsync(final @Nonnull String processName,
final @Nonnull Runnable operation) {
return executeAsync(newSingleThreadExecutor(), processName, operation, true);
} | java | static AsyncResponse executeAsync(final @Nonnull String processName,
final @Nonnull Runnable operation) {
return executeAsync(newSingleThreadExecutor(), processName, operation, true);
} | [
"static",
"AsyncResponse",
"executeAsync",
"(",
"final",
"@",
"Nonnull",
"String",
"processName",
",",
"final",
"@",
"Nonnull",
"Runnable",
"operation",
")",
"{",
"return",
"executeAsync",
"(",
"newSingleThreadExecutor",
"(",
")",
",",
"processName",
",",
"operati... | Executes using a single-execution ExecutorService, which shutdown immediately after the thread finishes.
@see Executors#newSingleThreadExecutor() | [
"Executes",
"using",
"a",
"single",
"-",
"execution",
"ExecutorService",
"which",
"shutdown",
"immediately",
"after",
"the",
"thread",
"finishes",
"."
] | b03635328aeecd525e35eddfef8f5b9a184559d8 | https://github.com/bbottema/simple-java-mail/blob/b03635328aeecd525e35eddfef8f5b9a184559d8/modules/simple-java-mail/src/main/java/org/simplejavamail/mailer/internal/mailsender/AsyncOperationHelper.java#L30-L33 |
32,797 | bbottema/simple-java-mail | modules/simple-java-mail/src/main/java/org/simplejavamail/mailer/internal/mailsender/AsyncOperationHelper.java | AsyncOperationHelper.executeAsync | static AsyncResponse executeAsync(final @Nonnull ExecutorService executorService,
final @Nonnull String processName,
final @Nonnull Runnable operation) {
return executeAsync(executorService, processName, operation, false);
} | java | static AsyncResponse executeAsync(final @Nonnull ExecutorService executorService,
final @Nonnull String processName,
final @Nonnull Runnable operation) {
return executeAsync(executorService, processName, operation, false);
} | [
"static",
"AsyncResponse",
"executeAsync",
"(",
"final",
"@",
"Nonnull",
"ExecutorService",
"executorService",
",",
"final",
"@",
"Nonnull",
"String",
"processName",
",",
"final",
"@",
"Nonnull",
"Runnable",
"operation",
")",
"{",
"return",
"executeAsync",
"(",
"e... | Executes using a the given ExecutorService, which is left running after the thread finishes running.
@see Executors#newSingleThreadExecutor() | [
"Executes",
"using",
"a",
"the",
"given",
"ExecutorService",
"which",
"is",
"left",
"running",
"after",
"the",
"thread",
"finishes",
"running",
"."
] | b03635328aeecd525e35eddfef8f5b9a184559d8 | https://github.com/bbottema/simple-java-mail/blob/b03635328aeecd525e35eddfef8f5b9a184559d8/modules/simple-java-mail/src/main/java/org/simplejavamail/mailer/internal/mailsender/AsyncOperationHelper.java#L40-L44 |
32,798 | bbottema/simple-java-mail | modules/simple-java-mail/src/main/java/org/simplejavamail/mailer/internal/mailsender/MailSenderImpl.java | MailSenderImpl.checkShutDownRunningProcesses | private synchronized void checkShutDownRunningProcesses() {
smtpRequestsPhaser.arriveAndDeregister();
LOGGER.trace("SMTP request threads left: {}", smtpRequestsPhaser.getUnarrivedParties());
// if this thread is the last one finishing
if (smtpRequestsPhaser.getUnarrivedParties() == 0) {
LOGGER.trace("all threads have finished processing");
//noinspection ConstantConditions
if (needsAuthenticatedProxy() && proxyServer.isRunning() && !proxyServer.isStopping()) {
LOGGER.trace("stopping proxy bridge...");
proxyServer.stop();
}
// shutdown the threadpool, or else the Mailer will keep any JVM alive forever
// executor is only available in async mode
if (executor != null) {
executor.shutdown();
}
}
} | java | private synchronized void checkShutDownRunningProcesses() {
smtpRequestsPhaser.arriveAndDeregister();
LOGGER.trace("SMTP request threads left: {}", smtpRequestsPhaser.getUnarrivedParties());
// if this thread is the last one finishing
if (smtpRequestsPhaser.getUnarrivedParties() == 0) {
LOGGER.trace("all threads have finished processing");
//noinspection ConstantConditions
if (needsAuthenticatedProxy() && proxyServer.isRunning() && !proxyServer.isStopping()) {
LOGGER.trace("stopping proxy bridge...");
proxyServer.stop();
}
// shutdown the threadpool, or else the Mailer will keep any JVM alive forever
// executor is only available in async mode
if (executor != null) {
executor.shutdown();
}
}
} | [
"private",
"synchronized",
"void",
"checkShutDownRunningProcesses",
"(",
")",
"{",
"smtpRequestsPhaser",
".",
"arriveAndDeregister",
"(",
")",
";",
"LOGGER",
".",
"trace",
"(",
"\"SMTP request threads left: {}\"",
",",
"smtpRequestsPhaser",
".",
"getUnarrivedParties",
"("... | We need to keep a count of running threads in case a proxyserver is running or a connection pool needs to be shut down. | [
"We",
"need",
"to",
"keep",
"a",
"count",
"of",
"running",
"threads",
"in",
"case",
"a",
"proxyserver",
"is",
"running",
"or",
"a",
"connection",
"pool",
"needs",
"to",
"be",
"shut",
"down",
"."
] | b03635328aeecd525e35eddfef8f5b9a184559d8 | https://github.com/bbottema/simple-java-mail/blob/b03635328aeecd525e35eddfef8f5b9a184559d8/modules/simple-java-mail/src/main/java/org/simplejavamail/mailer/internal/mailsender/MailSenderImpl.java#L306-L323 |
32,799 | alexa/alexa-skills-kit-sdk-for-java | ask-sdk-core/src/com/amazon/ask/request/RequestHelper.java | RequestHelper.isNewSession | public boolean isNewSession() {
Session session = handlerInput.getRequestEnvelope().getSession();
if (session == null) {
throw new IllegalArgumentException("The provided request doesn't contain a session");
}
return session.getNew();
} | java | public boolean isNewSession() {
Session session = handlerInput.getRequestEnvelope().getSession();
if (session == null) {
throw new IllegalArgumentException("The provided request doesn't contain a session");
}
return session.getNew();
} | [
"public",
"boolean",
"isNewSession",
"(",
")",
"{",
"Session",
"session",
"=",
"handlerInput",
".",
"getRequestEnvelope",
"(",
")",
".",
"getSession",
"(",
")",
";",
"if",
"(",
"session",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(... | Returns whether the request is a new session.
The method retrieves the new value from the input request's session, which indicates if it's a new session or
not. More information can be found here :
https://developer.amazon.com/docs/custom-skills/request-and-response-json-reference.html#session-object
This method returns an {@link IllegalArgumentException} if the request is not an in-session request.
@return true if the request is a new session | [
"Returns",
"whether",
"the",
"request",
"is",
"a",
"new",
"session",
"."
] | c49194da0693898c70f3f2c4a372f5a12da04e3e | https://github.com/alexa/alexa-skills-kit-sdk-for-java/blob/c49194da0693898c70f3f2c4a372f5a12da04e3e/ask-sdk-core/src/com/amazon/ask/request/RequestHelper.java#L203-L209 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.