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
156,400
pip-services3-java/pip-services3-components-java
src/org/pipservices3/components/connect/ConnectionResolver.java
ConnectionResolver.resolveAll
public List<ConnectionParams> resolveAll(String correlationId) throws ApplicationException { List<ConnectionParams> resolved = new ArrayList<ConnectionParams>(); List<ConnectionParams> toResolve = new ArrayList<ConnectionParams>(); // Sort connections for (ConnectionParams connection : _connections) { if (connection.useDiscovery()) toResolve.add(connection); else resolved.add(connection); } // Resolve addresses that require that if (toResolve.size() > 0) { for (ConnectionParams connection : toResolve) { List<ConnectionParams> resolvedConnections = resolveAllInDiscovery(correlationId, connection); for (ConnectionParams resolvedConnection : resolvedConnections) { // Merge configured and new parameters resolvedConnection = new ConnectionParams( ConfigParams.mergeConfigs(connection, resolvedConnection)); resolved.add(resolvedConnection); } } } return resolved; }
java
public List<ConnectionParams> resolveAll(String correlationId) throws ApplicationException { List<ConnectionParams> resolved = new ArrayList<ConnectionParams>(); List<ConnectionParams> toResolve = new ArrayList<ConnectionParams>(); // Sort connections for (ConnectionParams connection : _connections) { if (connection.useDiscovery()) toResolve.add(connection); else resolved.add(connection); } // Resolve addresses that require that if (toResolve.size() > 0) { for (ConnectionParams connection : toResolve) { List<ConnectionParams> resolvedConnections = resolveAllInDiscovery(correlationId, connection); for (ConnectionParams resolvedConnection : resolvedConnections) { // Merge configured and new parameters resolvedConnection = new ConnectionParams( ConfigParams.mergeConfigs(connection, resolvedConnection)); resolved.add(resolvedConnection); } } } return resolved; }
[ "public", "List", "<", "ConnectionParams", ">", "resolveAll", "(", "String", "correlationId", ")", "throws", "ApplicationException", "{", "List", "<", "ConnectionParams", ">", "resolved", "=", "new", "ArrayList", "<", "ConnectionParams", ">", "(", ")", ";", "List", "<", "ConnectionParams", ">", "toResolve", "=", "new", "ArrayList", "<", "ConnectionParams", ">", "(", ")", ";", "// Sort connections", "for", "(", "ConnectionParams", "connection", ":", "_connections", ")", "{", "if", "(", "connection", ".", "useDiscovery", "(", ")", ")", "toResolve", ".", "add", "(", "connection", ")", ";", "else", "resolved", ".", "add", "(", "connection", ")", ";", "}", "// Resolve addresses that require that", "if", "(", "toResolve", ".", "size", "(", ")", ">", "0", ")", "{", "for", "(", "ConnectionParams", "connection", ":", "toResolve", ")", "{", "List", "<", "ConnectionParams", ">", "resolvedConnections", "=", "resolveAllInDiscovery", "(", "correlationId", ",", "connection", ")", ";", "for", "(", "ConnectionParams", "resolvedConnection", ":", "resolvedConnections", ")", "{", "// Merge configured and new parameters", "resolvedConnection", "=", "new", "ConnectionParams", "(", "ConfigParams", ".", "mergeConfigs", "(", "connection", ",", "resolvedConnection", ")", ")", ";", "resolved", ".", "add", "(", "resolvedConnection", ")", ";", "}", "}", "}", "return", "resolved", ";", "}" ]
Resolves all component connection. If connections are configured to be retrieved from Discovery service it finds a IDiscovery and resolves the connection there. @param correlationId (optional) transaction id to trace execution through call chain. @return a list of resolved connections. @throws ApplicationException when error occured. @see IDiscovery
[ "Resolves", "all", "component", "connection", ".", "If", "connections", "are", "configured", "to", "be", "retrieved", "from", "Discovery", "service", "it", "finds", "a", "IDiscovery", "and", "resolves", "the", "connection", "there", "." ]
122352fbf9b208f6417376da7b8ad725bc85ee58
https://github.com/pip-services3-java/pip-services3-components-java/blob/122352fbf9b208f6417376da7b8ad725bc85ee58/src/org/pipservices3/components/connect/ConnectionResolver.java#L276-L302
156,401
onepf/OPFUtils
opfutils/src/main/java/org/onepf/opfutils/OPFUtils.java
OPFUtils.getAppVersion
public static int getAppVersion(@NonNull final Context context) { try { final PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (PackageManager.NameNotFoundException ignore) { // ignore } return Integer.MIN_VALUE; }
java
public static int getAppVersion(@NonNull final Context context) { try { final PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (PackageManager.NameNotFoundException ignore) { // ignore } return Integer.MIN_VALUE; }
[ "public", "static", "int", "getAppVersion", "(", "@", "NonNull", "final", "Context", "context", ")", "{", "try", "{", "final", "PackageInfo", "packageInfo", "=", "context", ".", "getPackageManager", "(", ")", ".", "getPackageInfo", "(", "context", ".", "getPackageName", "(", ")", ",", "0", ")", ";", "return", "packageInfo", ".", "versionCode", ";", "}", "catch", "(", "PackageManager", ".", "NameNotFoundException", "ignore", ")", "{", "// ignore", "}", "return", "Integer", ".", "MIN_VALUE", ";", "}" ]
Returns the version code of the application. @return The version code of the application.
[ "Returns", "the", "version", "code", "of", "the", "application", "." ]
e30c2c64077c5d577c0cd7d3cead809d31f7dab1
https://github.com/onepf/OPFUtils/blob/e30c2c64077c5d577c0cd7d3cead809d31f7dab1/opfutils/src/main/java/org/onepf/opfutils/OPFUtils.java#L71-L81
156,402
onepf/OPFUtils
opfutils/src/main/java/org/onepf/opfutils/OPFUtils.java
OPFUtils.getPackageInstaller
@Nullable public static String getPackageInstaller(@NonNull final Context context) { final PackageManager packageManager = context.getPackageManager(); return packageManager.getInstallerPackageName(context.getPackageName()); }
java
@Nullable public static String getPackageInstaller(@NonNull final Context context) { final PackageManager packageManager = context.getPackageManager(); return packageManager.getInstallerPackageName(context.getPackageName()); }
[ "@", "Nullable", "public", "static", "String", "getPackageInstaller", "(", "@", "NonNull", "final", "Context", "context", ")", "{", "final", "PackageManager", "packageManager", "=", "context", ".", "getPackageManager", "(", ")", ";", "return", "packageManager", ".", "getInstallerPackageName", "(", "context", ".", "getPackageName", "(", ")", ")", ";", "}" ]
Returns the package name of the application installer. @param context The instance of {@link android.content.Context}. @return The package name of the application installer.
[ "Returns", "the", "package", "name", "of", "the", "application", "installer", "." ]
e30c2c64077c5d577c0cd7d3cead809d31f7dab1
https://github.com/onepf/OPFUtils/blob/e30c2c64077c5d577c0cd7d3cead809d31f7dab1/opfutils/src/main/java/org/onepf/opfutils/OPFUtils.java#L126-L130
156,403
jmeetsma/Iglu-Common
src/main/java/org/ijsberg/iglu/mvc/component/StandardRequestMapper.java
StandardRequestMapper.start
public void start() { boolean succeeded = true; Iterator i = mappingFilesMap.keySet().iterator(); while (i.hasNext()) { String mappingName = (String) i.next(); String fileName = mappingFilesMap.getProperty(mappingName); System.out.println(new LogEntry("loading mapping '" + mappingName + "' from '" + fileName + '\'')); //TODO filename sometimes null IndentedConfigReaderMapping mapping = new IndentedConfigReaderMapping(mappingName, fileName, assembly); succeeded = succeeded && mapping.isLoaded(); if (!mapping.isLoaded()) { System.out.println(new LogEntry("loading NOT succeeded", (Serializable) mapping.getLoadMessages())); } mappingMap.put(mappingName, mapping); } loadSucceeded = succeeded; isStarted = true; }
java
public void start() { boolean succeeded = true; Iterator i = mappingFilesMap.keySet().iterator(); while (i.hasNext()) { String mappingName = (String) i.next(); String fileName = mappingFilesMap.getProperty(mappingName); System.out.println(new LogEntry("loading mapping '" + mappingName + "' from '" + fileName + '\'')); //TODO filename sometimes null IndentedConfigReaderMapping mapping = new IndentedConfigReaderMapping(mappingName, fileName, assembly); succeeded = succeeded && mapping.isLoaded(); if (!mapping.isLoaded()) { System.out.println(new LogEntry("loading NOT succeeded", (Serializable) mapping.getLoadMessages())); } mappingMap.put(mappingName, mapping); } loadSucceeded = succeeded; isStarted = true; }
[ "public", "void", "start", "(", ")", "{", "boolean", "succeeded", "=", "true", ";", "Iterator", "i", "=", "mappingFilesMap", ".", "keySet", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "i", ".", "hasNext", "(", ")", ")", "{", "String", "mappingName", "=", "(", "String", ")", "i", ".", "next", "(", ")", ";", "String", "fileName", "=", "mappingFilesMap", ".", "getProperty", "(", "mappingName", ")", ";", "System", ".", "out", ".", "println", "(", "new", "LogEntry", "(", "\"loading mapping '\"", "+", "mappingName", "+", "\"' from '\"", "+", "fileName", "+", "'", "'", ")", ")", ";", "//TODO filename sometimes null", "IndentedConfigReaderMapping", "mapping", "=", "new", "IndentedConfigReaderMapping", "(", "mappingName", ",", "fileName", ",", "assembly", ")", ";", "succeeded", "=", "succeeded", "&&", "mapping", ".", "isLoaded", "(", ")", ";", "if", "(", "!", "mapping", ".", "isLoaded", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "new", "LogEntry", "(", "\"loading NOT succeeded\"", ",", "(", "Serializable", ")", "mapping", ".", "getLoadMessages", "(", ")", ")", ")", ";", "}", "mappingMap", ".", "put", "(", "mappingName", ",", "mapping", ")", ";", "}", "loadSucceeded", "=", "succeeded", ";", "isStarted", "=", "true", ";", "}" ]
Loads mappings.
[ "Loads", "mappings", "." ]
0fb0885775b576209ff1b5a0f67e3c25a99a6420
https://github.com/jmeetsma/Iglu-Common/blob/0fb0885775b576209ff1b5a0f67e3c25a99a6420/src/main/java/org/ijsberg/iglu/mvc/component/StandardRequestMapper.java#L100-L117
156,404
jmeetsma/Iglu-Common
src/main/java/org/ijsberg/iglu/mvc/component/StandardRequestMapper.java
StandardRequestMapper.setProperties
public void setProperties(Properties properties) throws ConfigurationException { // initialRequest = application.getCurrentRequest(); autoReload = Boolean.valueOf(properties.getProperty("autoreload", "true")); defaultMappingName = properties.getProperty("defaultmapping", defaultMappingName); /* strict = section.getValue("strict", new GenericValue(strict), "abort mapping loading on errors").toBoolean().booleanValue(); Environment.System.out.println("checking mapping strictly: " + strict);*/ mappingFilesMap = PropertiesSupport.getSubsection(properties, "mapping"); }
java
public void setProperties(Properties properties) throws ConfigurationException { // initialRequest = application.getCurrentRequest(); autoReload = Boolean.valueOf(properties.getProperty("autoreload", "true")); defaultMappingName = properties.getProperty("defaultmapping", defaultMappingName); /* strict = section.getValue("strict", new GenericValue(strict), "abort mapping loading on errors").toBoolean().booleanValue(); Environment.System.out.println("checking mapping strictly: " + strict);*/ mappingFilesMap = PropertiesSupport.getSubsection(properties, "mapping"); }
[ "public", "void", "setProperties", "(", "Properties", "properties", ")", "throws", "ConfigurationException", "{", "//\t\tinitialRequest = application.getCurrentRequest();", "autoReload", "=", "Boolean", ".", "valueOf", "(", "properties", ".", "getProperty", "(", "\"autoreload\"", ",", "\"true\"", ")", ")", ";", "defaultMappingName", "=", "properties", ".", "getProperty", "(", "\"defaultmapping\"", ",", "defaultMappingName", ")", ";", "/*\t\tstrict = section.getValue(\"strict\", new GenericValue(strict), \"abort mapping loading on errors\").toBoolean().booleanValue();\n Environment.System.out.println(\"checking mapping strictly: \" + strict);*/", "mappingFilesMap", "=", "PropertiesSupport", ".", "getSubsection", "(", "properties", ",", "\"mapping\"", ")", ";", "}" ]
Loads mapping values. @throws ConfigurationException if no properties section exists where mapping definition files are specified
[ "Loads", "mapping", "values", "." ]
0fb0885775b576209ff1b5a0f67e3c25a99a6420
https://github.com/jmeetsma/Iglu-Common/blob/0fb0885775b576209ff1b5a0f67e3c25a99a6420/src/main/java/org/ijsberg/iglu/mvc/component/StandardRequestMapper.java#L164-L174
156,405
lotaris/rox-commons-maven-plugin
src/main/java/org/twdata/maven/mojoexecutor/MojoExecutor.java
MojoExecutor.executeMojo
public static void executeMojo(Plugin plugin, String goal, Xpp3Dom configuration, ExecutionEnvironment env) throws MojoExecutionException { if (configuration == null) { throw new NullPointerException("configuration may not be null"); } try { String executionId = null; if (goal != null && goal.length() > 0 && goal.indexOf('#') > -1) { int pos = goal.indexOf('#'); executionId = goal.substring(pos + 1); goal = goal.substring(0, pos); } MavenSession session = env.getMavenSession(); PluginDescriptor pluginDescriptor = env.getPluginManager().loadPlugin( plugin, env.getMavenProject().getRemotePluginRepositories(), session.getRepositorySession()); MojoDescriptor mojoDescriptor = pluginDescriptor.getMojo(goal); if (mojoDescriptor == null) { throw new MojoExecutionException("Could not find goal '" + goal + "' in plugin " + plugin.getGroupId() + ":" + plugin.getArtifactId() + ":" + plugin.getVersion()); } MojoExecution exec = mojoExecution(mojoDescriptor, executionId, configuration); env.getPluginManager().executeMojo(session, exec); } catch (PluginNotFoundException | PluginResolutionException | PluginDescriptorParsingException | InvalidPluginDescriptorException | MojoExecutionException | MojoFailureException | PluginConfigurationException | PluginManagerException e) { throw new MojoExecutionException("Unable to execute mojo", e); } }
java
public static void executeMojo(Plugin plugin, String goal, Xpp3Dom configuration, ExecutionEnvironment env) throws MojoExecutionException { if (configuration == null) { throw new NullPointerException("configuration may not be null"); } try { String executionId = null; if (goal != null && goal.length() > 0 && goal.indexOf('#') > -1) { int pos = goal.indexOf('#'); executionId = goal.substring(pos + 1); goal = goal.substring(0, pos); } MavenSession session = env.getMavenSession(); PluginDescriptor pluginDescriptor = env.getPluginManager().loadPlugin( plugin, env.getMavenProject().getRemotePluginRepositories(), session.getRepositorySession()); MojoDescriptor mojoDescriptor = pluginDescriptor.getMojo(goal); if (mojoDescriptor == null) { throw new MojoExecutionException("Could not find goal '" + goal + "' in plugin " + plugin.getGroupId() + ":" + plugin.getArtifactId() + ":" + plugin.getVersion()); } MojoExecution exec = mojoExecution(mojoDescriptor, executionId, configuration); env.getPluginManager().executeMojo(session, exec); } catch (PluginNotFoundException | PluginResolutionException | PluginDescriptorParsingException | InvalidPluginDescriptorException | MojoExecutionException | MojoFailureException | PluginConfigurationException | PluginManagerException e) { throw new MojoExecutionException("Unable to execute mojo", e); } }
[ "public", "static", "void", "executeMojo", "(", "Plugin", "plugin", ",", "String", "goal", ",", "Xpp3Dom", "configuration", ",", "ExecutionEnvironment", "env", ")", "throws", "MojoExecutionException", "{", "if", "(", "configuration", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"configuration may not be null\"", ")", ";", "}", "try", "{", "String", "executionId", "=", "null", ";", "if", "(", "goal", "!=", "null", "&&", "goal", ".", "length", "(", ")", ">", "0", "&&", "goal", ".", "indexOf", "(", "'", "'", ")", ">", "-", "1", ")", "{", "int", "pos", "=", "goal", ".", "indexOf", "(", "'", "'", ")", ";", "executionId", "=", "goal", ".", "substring", "(", "pos", "+", "1", ")", ";", "goal", "=", "goal", ".", "substring", "(", "0", ",", "pos", ")", ";", "}", "MavenSession", "session", "=", "env", ".", "getMavenSession", "(", ")", ";", "PluginDescriptor", "pluginDescriptor", "=", "env", ".", "getPluginManager", "(", ")", ".", "loadPlugin", "(", "plugin", ",", "env", ".", "getMavenProject", "(", ")", ".", "getRemotePluginRepositories", "(", ")", ",", "session", ".", "getRepositorySession", "(", ")", ")", ";", "MojoDescriptor", "mojoDescriptor", "=", "pluginDescriptor", ".", "getMojo", "(", "goal", ")", ";", "if", "(", "mojoDescriptor", "==", "null", ")", "{", "throw", "new", "MojoExecutionException", "(", "\"Could not find goal '\"", "+", "goal", "+", "\"' in plugin \"", "+", "plugin", ".", "getGroupId", "(", ")", "+", "\":\"", "+", "plugin", ".", "getArtifactId", "(", ")", "+", "\":\"", "+", "plugin", ".", "getVersion", "(", ")", ")", ";", "}", "MojoExecution", "exec", "=", "mojoExecution", "(", "mojoDescriptor", ",", "executionId", ",", "configuration", ")", ";", "env", ".", "getPluginManager", "(", ")", ".", "executeMojo", "(", "session", ",", "exec", ")", ";", "}", "catch", "(", "PluginNotFoundException", "|", "PluginResolutionException", "|", "PluginDescriptorParsingException", "|", "InvalidPluginDescriptorException", "|", "MojoExecutionException", "|", "MojoFailureException", "|", "PluginConfigurationException", "|", "PluginManagerException", "e", ")", "{", "throw", "new", "MojoExecutionException", "(", "\"Unable to execute mojo\"", ",", "e", ")", ";", "}", "}" ]
Entry point for executing a mojo @param plugin The plugin to execute @param goal The goal to execute @param configuration The execution configuration @param env The execution environment @throws MojoExecutionException If there are any exceptions locating or executing the mojo
[ "Entry", "point", "for", "executing", "a", "mojo" ]
e2602d7f1e8c2e6994c0df07cc0003828adfa2af
https://github.com/lotaris/rox-commons-maven-plugin/blob/e2602d7f1e8c2e6994c0df07cc0003828adfa2af/src/main/java/org/twdata/maven/mojoexecutor/MojoExecutor.java#L73-L112
156,406
lotaris/rox-commons-maven-plugin
src/main/java/org/twdata/maven/mojoexecutor/MojoExecutor.java
MojoExecutor.configuration
public static Xpp3Dom configuration(Element... elements) { Xpp3Dom dom = new Xpp3Dom("configuration"); for (Element e : elements) { dom.addChild(e.toDom()); } return dom; }
java
public static Xpp3Dom configuration(Element... elements) { Xpp3Dom dom = new Xpp3Dom("configuration"); for (Element e : elements) { dom.addChild(e.toDom()); } return dom; }
[ "public", "static", "Xpp3Dom", "configuration", "(", "Element", "...", "elements", ")", "{", "Xpp3Dom", "dom", "=", "new", "Xpp3Dom", "(", "\"configuration\"", ")", ";", "for", "(", "Element", "e", ":", "elements", ")", "{", "dom", ".", "addChild", "(", "e", ".", "toDom", "(", ")", ")", ";", "}", "return", "dom", ";", "}" ]
Builds the configuration for the goal using Elements @param elements A list of elements for the configuration section @return The elements transformed into the Maven-native XML format
[ "Builds", "the", "configuration", "for", "the", "goal", "using", "Elements" ]
e2602d7f1e8c2e6994c0df07cc0003828adfa2af
https://github.com/lotaris/rox-commons-maven-plugin/blob/e2602d7f1e8c2e6994c0df07cc0003828adfa2af/src/main/java/org/twdata/maven/mojoexecutor/MojoExecutor.java#L143-L151
156,407
lotaris/rox-commons-maven-plugin
src/main/java/org/twdata/maven/mojoexecutor/MojoExecutor.java
MojoExecutor.plugin
public static Plugin plugin(String groupId, String artifactId) { return plugin(groupId, artifactId, null); }
java
public static Plugin plugin(String groupId, String artifactId) { return plugin(groupId, artifactId, null); }
[ "public", "static", "Plugin", "plugin", "(", "String", "groupId", ",", "String", "artifactId", ")", "{", "return", "plugin", "(", "groupId", ",", "artifactId", ",", "null", ")", ";", "}" ]
Defines the plugin without its version @param groupId The group id @param artifactId The artifact id @return The plugin instance
[ "Defines", "the", "plugin", "without", "its", "version" ]
e2602d7f1e8c2e6994c0df07cc0003828adfa2af
https://github.com/lotaris/rox-commons-maven-plugin/blob/e2602d7f1e8c2e6994c0df07cc0003828adfa2af/src/main/java/org/twdata/maven/mojoexecutor/MojoExecutor.java#L160-L162
156,408
lotaris/rox-commons-maven-plugin
src/main/java/org/twdata/maven/mojoexecutor/MojoExecutor.java
MojoExecutor.plugin
public static Plugin plugin(String groupId, String artifactId, String version) { Plugin plugin = new Plugin(); plugin.setArtifactId(artifactId); plugin.setGroupId(groupId); plugin.setVersion(version); return plugin; }
java
public static Plugin plugin(String groupId, String artifactId, String version) { Plugin plugin = new Plugin(); plugin.setArtifactId(artifactId); plugin.setGroupId(groupId); plugin.setVersion(version); return plugin; }
[ "public", "static", "Plugin", "plugin", "(", "String", "groupId", ",", "String", "artifactId", ",", "String", "version", ")", "{", "Plugin", "plugin", "=", "new", "Plugin", "(", ")", ";", "plugin", ".", "setArtifactId", "(", "artifactId", ")", ";", "plugin", ".", "setGroupId", "(", "groupId", ")", ";", "plugin", ".", "setVersion", "(", "version", ")", ";", "return", "plugin", ";", "}" ]
Defines a plugin @param groupId The group id @param artifactId The artifact id @param version The plugin version @return The plugin instance
[ "Defines", "a", "plugin" ]
e2602d7f1e8c2e6994c0df07cc0003828adfa2af
https://github.com/lotaris/rox-commons-maven-plugin/blob/e2602d7f1e8c2e6994c0df07cc0003828adfa2af/src/main/java/org/twdata/maven/mojoexecutor/MojoExecutor.java#L172-L178
156,409
foundation-runtime/monitoring
monitoring-jmx-lib/src/main/java/com/cisco/oss/foundation/monitoring/RMIRegistryManager.java
RMIRegistryManager.isRMIRegistryRunning
public static boolean isRMIRegistryRunning(Configuration configuration, int port) { try { final Registry registry = RegistryFinder.getInstance().getRegistry(configuration, port); registry.list(); return true; } catch (RemoteException ex) { return false; } catch (Exception e) { return false; } }
java
public static boolean isRMIRegistryRunning(Configuration configuration, int port) { try { final Registry registry = RegistryFinder.getInstance().getRegistry(configuration, port); registry.list(); return true; } catch (RemoteException ex) { return false; } catch (Exception e) { return false; } }
[ "public", "static", "boolean", "isRMIRegistryRunning", "(", "Configuration", "configuration", ",", "int", "port", ")", "{", "try", "{", "final", "Registry", "registry", "=", "RegistryFinder", ".", "getInstance", "(", ")", ".", "getRegistry", "(", "configuration", ",", "port", ")", ";", "registry", ".", "list", "(", ")", ";", "return", "true", ";", "}", "catch", "(", "RemoteException", "ex", ")", "{", "return", "false", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "false", ";", "}", "}" ]
Checks if rmiregistry is running on the specified port. @param port @return true if rmiregistry is running on the specified port, false otherwise
[ "Checks", "if", "rmiregistry", "is", "running", "on", "the", "specified", "port", "." ]
a85ec72dc5558f787704fb13d9125a5803403ee5
https://github.com/foundation-runtime/monitoring/blob/a85ec72dc5558f787704fb13d9125a5803403ee5/monitoring-jmx-lib/src/main/java/com/cisco/oss/foundation/monitoring/RMIRegistryManager.java#L45-L55
156,410
foundation-runtime/monitoring
monitoring-jmx-lib/src/main/java/com/cisco/oss/foundation/monitoring/RMIRegistryManager.java
RMIRegistryManager.isServiceExported
public static boolean isServiceExported(Configuration configuration, int port, String serviceName) { if (serviceName == null) return false; try { final Registry registry = RegistryFinder.getInstance().getRegistry(configuration, port); String[] list = registry.list(); if (list != null) { for (int i = 0; i < list.length; i++) { if (serviceName.equals(list[i])) return true; } } } catch (RemoteException ex) { return false; } catch (Exception e) { return false; } return false; }
java
public static boolean isServiceExported(Configuration configuration, int port, String serviceName) { if (serviceName == null) return false; try { final Registry registry = RegistryFinder.getInstance().getRegistry(configuration, port); String[] list = registry.list(); if (list != null) { for (int i = 0; i < list.length; i++) { if (serviceName.equals(list[i])) return true; } } } catch (RemoteException ex) { return false; } catch (Exception e) { return false; } return false; }
[ "public", "static", "boolean", "isServiceExported", "(", "Configuration", "configuration", ",", "int", "port", ",", "String", "serviceName", ")", "{", "if", "(", "serviceName", "==", "null", ")", "return", "false", ";", "try", "{", "final", "Registry", "registry", "=", "RegistryFinder", ".", "getInstance", "(", ")", ".", "getRegistry", "(", "configuration", ",", "port", ")", ";", "String", "[", "]", "list", "=", "registry", ".", "list", "(", ")", ";", "if", "(", "list", "!=", "null", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "i", "++", ")", "{", "if", "(", "serviceName", ".", "equals", "(", "list", "[", "i", "]", ")", ")", "return", "true", ";", "}", "}", "}", "catch", "(", "RemoteException", "ex", ")", "{", "return", "false", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "false", ";", "}", "return", "false", ";", "}" ]
Checks if a service is exported on the rmi registry with specified port. @param port @return true if rmiregistry is running on the specified port and service is exported on the rmi registry, false otherwise
[ "Checks", "if", "a", "service", "is", "exported", "on", "the", "rmi", "registry", "with", "specified", "port", "." ]
a85ec72dc5558f787704fb13d9125a5803403ee5
https://github.com/foundation-runtime/monitoring/blob/a85ec72dc5558f787704fb13d9125a5803403ee5/monitoring-jmx-lib/src/main/java/com/cisco/oss/foundation/monitoring/RMIRegistryManager.java#L64-L83
156,411
foundation-runtime/monitoring
monitoring-jmx-lib/src/main/java/com/cisco/oss/foundation/monitoring/RMIRegistryManager.java
RMIRegistryManager.startRMIRegistry
public static boolean startRMIRegistry(Configuration configuration, int port) { if (isRMIRegistryRunning(configuration, port)) return true; if (configuration.getBoolean(FoundationMonitoringConstants.IN_PROC_RMI)) { return startInProcRMIRegistry(port); } else { return startOutProcRMIRegistry(configuration, port); } }
java
public static boolean startRMIRegistry(Configuration configuration, int port) { if (isRMIRegistryRunning(configuration, port)) return true; if (configuration.getBoolean(FoundationMonitoringConstants.IN_PROC_RMI)) { return startInProcRMIRegistry(port); } else { return startOutProcRMIRegistry(configuration, port); } }
[ "public", "static", "boolean", "startRMIRegistry", "(", "Configuration", "configuration", ",", "int", "port", ")", "{", "if", "(", "isRMIRegistryRunning", "(", "configuration", ",", "port", ")", ")", "return", "true", ";", "if", "(", "configuration", ".", "getBoolean", "(", "FoundationMonitoringConstants", ".", "IN_PROC_RMI", ")", ")", "{", "return", "startInProcRMIRegistry", "(", "port", ")", ";", "}", "else", "{", "return", "startOutProcRMIRegistry", "(", "configuration", ",", "port", ")", ";", "}", "}" ]
Starts rmiregistry on the specified port. If property "service.monitor.inProcess" is set to true in configSchema.xml, then an in-process rmiregistry is started. Otherwise rmiregistry will be started in a seperate process. @param port on which the rmiregistry needs to be started @return true if successful or it is already started, false otherwise
[ "Starts", "rmiregistry", "on", "the", "specified", "port", ".", "If", "property", "service", ".", "monitor", ".", "inProcess", "is", "set", "to", "true", "in", "configSchema", ".", "xml", "then", "an", "in", "-", "process", "rmiregistry", "is", "started", ".", "Otherwise", "rmiregistry", "will", "be", "started", "in", "a", "seperate", "process", "." ]
a85ec72dc5558f787704fb13d9125a5803403ee5
https://github.com/foundation-runtime/monitoring/blob/a85ec72dc5558f787704fb13d9125a5803403ee5/monitoring-jmx-lib/src/main/java/com/cisco/oss/foundation/monitoring/RMIRegistryManager.java#L94-L103
156,412
foundation-runtime/monitoring
monitoring-jmx-lib/src/main/java/com/cisco/oss/foundation/monitoring/RMIRegistryManager.java
RMIRegistryManager.startInProcRMIRegistry
public static boolean startInProcRMIRegistry(final int port) { LOGGER.info("Starting In-Process rmiregistry on port " + port); boolean result = true; try { LocateRegistry.createRegistry(port); LOGGER.info("In-Process rmiregistry started on port " + port); } catch (RemoteException e) { LOGGER.error("Failed to start In-Process rmiregistry on port " + port); result = false; } return result; }
java
public static boolean startInProcRMIRegistry(final int port) { LOGGER.info("Starting In-Process rmiregistry on port " + port); boolean result = true; try { LocateRegistry.createRegistry(port); LOGGER.info("In-Process rmiregistry started on port " + port); } catch (RemoteException e) { LOGGER.error("Failed to start In-Process rmiregistry on port " + port); result = false; } return result; }
[ "public", "static", "boolean", "startInProcRMIRegistry", "(", "final", "int", "port", ")", "{", "LOGGER", ".", "info", "(", "\"Starting In-Process rmiregistry on port \"", "+", "port", ")", ";", "boolean", "result", "=", "true", ";", "try", "{", "LocateRegistry", ".", "createRegistry", "(", "port", ")", ";", "LOGGER", ".", "info", "(", "\"In-Process rmiregistry started on port \"", "+", "port", ")", ";", "}", "catch", "(", "RemoteException", "e", ")", "{", "LOGGER", ".", "error", "(", "\"Failed to start In-Process rmiregistry on port \"", "+", "port", ")", ";", "result", "=", "false", ";", "}", "return", "result", ";", "}" ]
Starts in-process rmiregistry on the specified port. @param port on which the rmiregistry needs to be started @return true if successful, false otherwise
[ "Starts", "in", "-", "process", "rmiregistry", "on", "the", "specified", "port", "." ]
a85ec72dc5558f787704fb13d9125a5803403ee5
https://github.com/foundation-runtime/monitoring/blob/a85ec72dc5558f787704fb13d9125a5803403ee5/monitoring-jmx-lib/src/main/java/com/cisco/oss/foundation/monitoring/RMIRegistryManager.java#L111-L122
156,413
foundation-runtime/monitoring
monitoring-jmx-lib/src/main/java/com/cisco/oss/foundation/monitoring/RMIRegistryManager.java
RMIRegistryManager.startOutProcRMIRegistry
public static boolean startOutProcRMIRegistry(Configuration configuration, final int port) { LOGGER.info("Starting rmiregistry on port " + port); try { Registry registryStarted = RegistryFinder.getInstance().getRegistry(configuration, port); if (registryStarted != null) { LOGGER.info("rmiregistry started on " + port); } else { LOGGER.error("Failed to start rmiregistry on " + port); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; //return startProcess(port, JAVA_HOME_RMI_REGISTRY) || startProcess(port, RMI_REGISTRY); }
java
public static boolean startOutProcRMIRegistry(Configuration configuration, final int port) { LOGGER.info("Starting rmiregistry on port " + port); try { Registry registryStarted = RegistryFinder.getInstance().getRegistry(configuration, port); if (registryStarted != null) { LOGGER.info("rmiregistry started on " + port); } else { LOGGER.error("Failed to start rmiregistry on " + port); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; //return startProcess(port, JAVA_HOME_RMI_REGISTRY) || startProcess(port, RMI_REGISTRY); }
[ "public", "static", "boolean", "startOutProcRMIRegistry", "(", "Configuration", "configuration", ",", "final", "int", "port", ")", "{", "LOGGER", ".", "info", "(", "\"Starting rmiregistry on port \"", "+", "port", ")", ";", "try", "{", "Registry", "registryStarted", "=", "RegistryFinder", ".", "getInstance", "(", ")", ".", "getRegistry", "(", "configuration", ",", "port", ")", ";", "if", "(", "registryStarted", "!=", "null", ")", "{", "LOGGER", ".", "info", "(", "\"rmiregistry started on \"", "+", "port", ")", ";", "}", "else", "{", "LOGGER", ".", "error", "(", "\"Failed to start rmiregistry on \"", "+", "port", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "// TODO Auto-generated catch block", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "false", ";", "//return startProcess(port, JAVA_HOME_RMI_REGISTRY) || startProcess(port, RMI_REGISTRY);", "}" ]
Starts rmiregistry in a separate process on the specified port. @param port on which the rmiregistry needs to be started @return true if successful, false otherwise
[ "Starts", "rmiregistry", "in", "a", "separate", "process", "on", "the", "specified", "port", "." ]
a85ec72dc5558f787704fb13d9125a5803403ee5
https://github.com/foundation-runtime/monitoring/blob/a85ec72dc5558f787704fb13d9125a5803403ee5/monitoring-jmx-lib/src/main/java/com/cisco/oss/foundation/monitoring/RMIRegistryManager.java#L130-L146
156,414
jpelzer/pelzer-util
src/main/java/com/pelzer/util/PasswordCrypt.java
PasswordCrypt.computePasswordHash
public static String computePasswordHash(final String password, final byte[] salt) { if (StringMan.isEmpty(password)) return (StringMan.encodeBytesToString(salt)); final KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 2048, 160); SecretKeyFactory f; try { f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); final byte[] hash = f.generateSecret(spec).getEncoded(); return StringMan.encodeBytesToString(hash); } catch (final NoSuchAlgorithmException ex) { throw new RuntimeException("Missing encryption algorithm:", ex); } catch (final InvalidKeySpecException ex) { throw new RuntimeException("Key spec is incorrect.", ex); } }
java
public static String computePasswordHash(final String password, final byte[] salt) { if (StringMan.isEmpty(password)) return (StringMan.encodeBytesToString(salt)); final KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 2048, 160); SecretKeyFactory f; try { f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); final byte[] hash = f.generateSecret(spec).getEncoded(); return StringMan.encodeBytesToString(hash); } catch (final NoSuchAlgorithmException ex) { throw new RuntimeException("Missing encryption algorithm:", ex); } catch (final InvalidKeySpecException ex) { throw new RuntimeException("Key spec is incorrect.", ex); } }
[ "public", "static", "String", "computePasswordHash", "(", "final", "String", "password", ",", "final", "byte", "[", "]", "salt", ")", "{", "if", "(", "StringMan", ".", "isEmpty", "(", "password", ")", ")", "return", "(", "StringMan", ".", "encodeBytesToString", "(", "salt", ")", ")", ";", "final", "KeySpec", "spec", "=", "new", "PBEKeySpec", "(", "password", ".", "toCharArray", "(", ")", ",", "salt", ",", "2048", ",", "160", ")", ";", "SecretKeyFactory", "f", ";", "try", "{", "f", "=", "SecretKeyFactory", ".", "getInstance", "(", "\"PBKDF2WithHmacSHA1\"", ")", ";", "final", "byte", "[", "]", "hash", "=", "f", ".", "generateSecret", "(", "spec", ")", ".", "getEncoded", "(", ")", ";", "return", "StringMan", ".", "encodeBytesToString", "(", "hash", ")", ";", "}", "catch", "(", "final", "NoSuchAlgorithmException", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "\"Missing encryption algorithm:\"", ",", "ex", ")", ";", "}", "catch", "(", "final", "InvalidKeySpecException", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "\"Key spec is incorrect.\"", ",", "ex", ")", ";", "}", "}" ]
Uses PBKDF2WithHmacSHA1 to hash the password using the given salt, returning the has in encoded hexadecimal form. If the password is empty, returns the salt.
[ "Uses", "PBKDF2WithHmacSHA1", "to", "hash", "the", "password", "using", "the", "given", "salt", "returning", "the", "has", "in", "encoded", "hexadecimal", "form", ".", "If", "the", "password", "is", "empty", "returns", "the", "salt", "." ]
ec14f2573fd977d1442dba5d1507a264f5ea9aa6
https://github.com/jpelzer/pelzer-util/blob/ec14f2573fd977d1442dba5d1507a264f5ea9aa6/src/main/java/com/pelzer/util/PasswordCrypt.java#L28-L42
156,415
jpelzer/pelzer-util
src/main/java/com/pelzer/util/PasswordCrypt.java
PasswordCrypt.stringToSalt
public static byte[] stringToSalt(final String string) { try { final MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); return digest.digest(string.getBytes("UTF-8")); } catch (final NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } catch (final UnsupportedEncodingException ex) { throw new RuntimeException(ex); } }
java
public static byte[] stringToSalt(final String string) { try { final MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); return digest.digest(string.getBytes("UTF-8")); } catch (final NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } catch (final UnsupportedEncodingException ex) { throw new RuntimeException(ex); } }
[ "public", "static", "byte", "[", "]", "stringToSalt", "(", "final", "String", "string", ")", "{", "try", "{", "final", "MessageDigest", "digest", "=", "MessageDigest", ".", "getInstance", "(", "\"SHA-1\"", ")", ";", "digest", ".", "reset", "(", ")", ";", "return", "digest", ".", "digest", "(", "string", ".", "getBytes", "(", "\"UTF-8\"", ")", ")", ";", "}", "catch", "(", "final", "NoSuchAlgorithmException", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "ex", ")", ";", "}", "catch", "(", "final", "UnsupportedEncodingException", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "ex", ")", ";", "}", "}" ]
Uses SHA-1 to hash the given string and returns the byte array.
[ "Uses", "SHA", "-", "1", "to", "hash", "the", "given", "string", "and", "returns", "the", "byte", "array", "." ]
ec14f2573fd977d1442dba5d1507a264f5ea9aa6
https://github.com/jpelzer/pelzer-util/blob/ec14f2573fd977d1442dba5d1507a264f5ea9aa6/src/main/java/com/pelzer/util/PasswordCrypt.java#L55-L65
156,416
keub/remote-resources-maven-plugin
src/main/java/com/github/keub/maven/plugin/service/ResourceService.java
ResourceService.execute
public static void execute(CopyResourcesMojo copyResourcesMojo, Resource resource, File outputDirectory) throws ResourceExecutionException { copyResourcesMojo.getLog().debug("Execute resource : " + resource); // choose a location to checkout project File workspacePlugin = PathUtils.getWorkspace(copyResourcesMojo); // security if (workspacePlugin.exists()) { copyResourcesMojo.getLog().debug( "delete workspacePlugin resource because already exist : '" + workspacePlugin.getAbsolutePath() + "'"); if (workspacePlugin.delete()) { copyResourcesMojo.getLog().debug( "Unable to delete workspace plugin directory '" + workspacePlugin + "'"); } } // find correct strategy ProtocolStrategy strategy; try { strategy = ProtocolService.getStrategy(resource); copyResourcesMojo.getLog().debug( "current strategy is " + strategy.getClass().getSimpleName()); } catch (ProtocolException e) { throw new ResourceExecutionException( "Protocol implementation not found", e); } // strategy return a source folder String sourceFolder = strategy.getSourceFolder(resource, copyResourcesMojo, workspacePlugin); // source folder is copied into destination try { boolean flatten = resource.getFlatten() == null ? false : resource .getFlatten(); FileService.copyFilesIntoOutputDirectory(copyResourcesMojo, new File(sourceFolder), outputDirectory, resource, flatten); } catch (FileNotFoundException e) { throw new ResourceExecutionException(e); } catch (InvalidSourceException e) { throw new ResourceExecutionException(e); } catch (IOException e) { throw new ResourceExecutionException(e); } }
java
public static void execute(CopyResourcesMojo copyResourcesMojo, Resource resource, File outputDirectory) throws ResourceExecutionException { copyResourcesMojo.getLog().debug("Execute resource : " + resource); // choose a location to checkout project File workspacePlugin = PathUtils.getWorkspace(copyResourcesMojo); // security if (workspacePlugin.exists()) { copyResourcesMojo.getLog().debug( "delete workspacePlugin resource because already exist : '" + workspacePlugin.getAbsolutePath() + "'"); if (workspacePlugin.delete()) { copyResourcesMojo.getLog().debug( "Unable to delete workspace plugin directory '" + workspacePlugin + "'"); } } // find correct strategy ProtocolStrategy strategy; try { strategy = ProtocolService.getStrategy(resource); copyResourcesMojo.getLog().debug( "current strategy is " + strategy.getClass().getSimpleName()); } catch (ProtocolException e) { throw new ResourceExecutionException( "Protocol implementation not found", e); } // strategy return a source folder String sourceFolder = strategy.getSourceFolder(resource, copyResourcesMojo, workspacePlugin); // source folder is copied into destination try { boolean flatten = resource.getFlatten() == null ? false : resource .getFlatten(); FileService.copyFilesIntoOutputDirectory(copyResourcesMojo, new File(sourceFolder), outputDirectory, resource, flatten); } catch (FileNotFoundException e) { throw new ResourceExecutionException(e); } catch (InvalidSourceException e) { throw new ResourceExecutionException(e); } catch (IOException e) { throw new ResourceExecutionException(e); } }
[ "public", "static", "void", "execute", "(", "CopyResourcesMojo", "copyResourcesMojo", ",", "Resource", "resource", ",", "File", "outputDirectory", ")", "throws", "ResourceExecutionException", "{", "copyResourcesMojo", ".", "getLog", "(", ")", ".", "debug", "(", "\"Execute resource : \"", "+", "resource", ")", ";", "// choose a location to checkout project", "File", "workspacePlugin", "=", "PathUtils", ".", "getWorkspace", "(", "copyResourcesMojo", ")", ";", "// security", "if", "(", "workspacePlugin", ".", "exists", "(", ")", ")", "{", "copyResourcesMojo", ".", "getLog", "(", ")", ".", "debug", "(", "\"delete workspacePlugin resource because already exist : '\"", "+", "workspacePlugin", ".", "getAbsolutePath", "(", ")", "+", "\"'\"", ")", ";", "if", "(", "workspacePlugin", ".", "delete", "(", ")", ")", "{", "copyResourcesMojo", ".", "getLog", "(", ")", ".", "debug", "(", "\"Unable to delete workspace plugin directory '\"", "+", "workspacePlugin", "+", "\"'\"", ")", ";", "}", "}", "// find correct strategy", "ProtocolStrategy", "strategy", ";", "try", "{", "strategy", "=", "ProtocolService", ".", "getStrategy", "(", "resource", ")", ";", "copyResourcesMojo", ".", "getLog", "(", ")", ".", "debug", "(", "\"current strategy is \"", "+", "strategy", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", ")", ";", "}", "catch", "(", "ProtocolException", "e", ")", "{", "throw", "new", "ResourceExecutionException", "(", "\"Protocol implementation not found\"", ",", "e", ")", ";", "}", "// strategy return a source folder", "String", "sourceFolder", "=", "strategy", ".", "getSourceFolder", "(", "resource", ",", "copyResourcesMojo", ",", "workspacePlugin", ")", ";", "// source folder is copied into destination", "try", "{", "boolean", "flatten", "=", "resource", ".", "getFlatten", "(", ")", "==", "null", "?", "false", ":", "resource", ".", "getFlatten", "(", ")", ";", "FileService", ".", "copyFilesIntoOutputDirectory", "(", "copyResourcesMojo", ",", "new", "File", "(", "sourceFolder", ")", ",", "outputDirectory", ",", "resource", ",", "flatten", ")", ";", "}", "catch", "(", "FileNotFoundException", "e", ")", "{", "throw", "new", "ResourceExecutionException", "(", "e", ")", ";", "}", "catch", "(", "InvalidSourceException", "e", ")", "{", "throw", "new", "ResourceExecutionException", "(", "e", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "ResourceExecutionException", "(", "e", ")", ";", "}", "}" ]
execute with a resource @param copyResourcesMojo @param resource @param outputDirectory @param flatten @throws ResourceExecutionException
[ "execute", "with", "a", "resource" ]
543445731412aa15db2ea2b9b7840da1f40302d0
https://github.com/keub/remote-resources-maven-plugin/blob/543445731412aa15db2ea2b9b7840da1f40302d0/src/main/java/com/github/keub/maven/plugin/service/ResourceService.java#L26-L71
156,417
schallee/alib4j
osgi/slf4j_log_listener/src/main/java/net/darkmist/alib/osgi/slf4j_log_listener/LogBridge.java
LogBridge.getLogEntries
@SuppressWarnings("unchecked") private static Enumeration<LogEntry> getLogEntries(LogReaderService lrs) { return (Enumeration<LogEntry>)lrs.getLog(); }
java
@SuppressWarnings("unchecked") private static Enumeration<LogEntry> getLogEntries(LogReaderService lrs) { return (Enumeration<LogEntry>)lrs.getLog(); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "static", "Enumeration", "<", "LogEntry", ">", "getLogEntries", "(", "LogReaderService", "lrs", ")", "{", "return", "(", "Enumeration", "<", "LogEntry", ">", ")", "lrs", ".", "getLog", "(", ")", ";", "}" ]
Utility method to reduce unchecked area.
[ "Utility", "method", "to", "reduce", "unchecked", "area", "." ]
0e0718aee574bbb62268e1cf58e99286529ce529
https://github.com/schallee/alib4j/blob/0e0718aee574bbb62268e1cf58e99286529ce529/osgi/slf4j_log_listener/src/main/java/net/darkmist/alib/osgi/slf4j_log_listener/LogBridge.java#L75-L79
156,418
pip-services3-java/pip-services3-components-java
src/org/pipservices3/components/connect/MemoryDiscovery.java
MemoryDiscovery.readConnections
public void readConnections(ConfigParams connections) { synchronized (_lock) { _items.clear(); for (Map.Entry<String, String> entry : connections.entrySet()) { DiscoveryItem item = new DiscoveryItem(); item.key = entry.getKey(); item.connection = ConnectionParams.fromString(entry.getValue()); _items.add(item); } } }
java
public void readConnections(ConfigParams connections) { synchronized (_lock) { _items.clear(); for (Map.Entry<String, String> entry : connections.entrySet()) { DiscoveryItem item = new DiscoveryItem(); item.key = entry.getKey(); item.connection = ConnectionParams.fromString(entry.getValue()); _items.add(item); } } }
[ "public", "void", "readConnections", "(", "ConfigParams", "connections", ")", "{", "synchronized", "(", "_lock", ")", "{", "_items", ".", "clear", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "connections", ".", "entrySet", "(", ")", ")", "{", "DiscoveryItem", "item", "=", "new", "DiscoveryItem", "(", ")", ";", "item", ".", "key", "=", "entry", ".", "getKey", "(", ")", ";", "item", ".", "connection", "=", "ConnectionParams", ".", "fromString", "(", "entry", ".", "getValue", "(", ")", ")", ";", "_items", ".", "add", "(", "item", ")", ";", "}", "}", "}" ]
Reads connections from configuration parameters. Each section represents an individual Connection params @param connections configuration parameters to be read
[ "Reads", "connections", "from", "configuration", "parameters", ".", "Each", "section", "represents", "an", "individual", "Connection", "params" ]
122352fbf9b208f6417376da7b8ad725bc85ee58
https://github.com/pip-services3-java/pip-services3-components-java/blob/122352fbf9b208f6417376da7b8ad725bc85ee58/src/org/pipservices3/components/connect/MemoryDiscovery.java#L77-L87
156,419
pip-services3-java/pip-services3-components-java
src/org/pipservices3/components/connect/MemoryDiscovery.java
MemoryDiscovery.register
public void register(String correlationId, String key, ConnectionParams connection) { synchronized (_lock) { DiscoveryItem item = new DiscoveryItem(); item.key = key; item.connection = connection; _items.add(item); } }
java
public void register(String correlationId, String key, ConnectionParams connection) { synchronized (_lock) { DiscoveryItem item = new DiscoveryItem(); item.key = key; item.connection = connection; _items.add(item); } }
[ "public", "void", "register", "(", "String", "correlationId", ",", "String", "key", ",", "ConnectionParams", "connection", ")", "{", "synchronized", "(", "_lock", ")", "{", "DiscoveryItem", "item", "=", "new", "DiscoveryItem", "(", ")", ";", "item", ".", "key", "=", "key", ";", "item", ".", "connection", "=", "connection", ";", "_items", ".", "add", "(", "item", ")", ";", "}", "}" ]
Registers connection parameters into the discovery service. @param correlationId (optional) transaction id to trace execution through call chain. @param key a key to uniquely identify the connection parameters. @param connection a connection to be registered.
[ "Registers", "connection", "parameters", "into", "the", "discovery", "service", "." ]
122352fbf9b208f6417376da7b8ad725bc85ee58
https://github.com/pip-services3-java/pip-services3-components-java/blob/122352fbf9b208f6417376da7b8ad725bc85ee58/src/org/pipservices3/components/connect/MemoryDiscovery.java#L97-L104
156,420
pip-services3-java/pip-services3-components-java
src/org/pipservices3/components/connect/MemoryDiscovery.java
MemoryDiscovery.resolveOne
public ConnectionParams resolveOne(String correlationId, String key) { ConnectionParams connection = null; synchronized (_lock) { for (DiscoveryItem item : _items) { if (item.key == key && item.connection != null) { connection = item.connection; break; } } } return connection; }
java
public ConnectionParams resolveOne(String correlationId, String key) { ConnectionParams connection = null; synchronized (_lock) { for (DiscoveryItem item : _items) { if (item.key == key && item.connection != null) { connection = item.connection; break; } } } return connection; }
[ "public", "ConnectionParams", "resolveOne", "(", "String", "correlationId", ",", "String", "key", ")", "{", "ConnectionParams", "connection", "=", "null", ";", "synchronized", "(", "_lock", ")", "{", "for", "(", "DiscoveryItem", "item", ":", "_items", ")", "{", "if", "(", "item", ".", "key", "==", "key", "&&", "item", ".", "connection", "!=", "null", ")", "{", "connection", "=", "item", ".", "connection", ";", "break", ";", "}", "}", "}", "return", "connection", ";", "}" ]
Resolves a single connection parameters by its key. @param correlationId (optional) transaction id to trace execution through call chain. @param key a key to uniquely identify the connection. @return receives found connection.
[ "Resolves", "a", "single", "connection", "parameters", "by", "its", "key", "." ]
122352fbf9b208f6417376da7b8ad725bc85ee58
https://github.com/pip-services3-java/pip-services3-components-java/blob/122352fbf9b208f6417376da7b8ad725bc85ee58/src/org/pipservices3/components/connect/MemoryDiscovery.java#L114-L127
156,421
pip-services3-java/pip-services3-components-java
src/org/pipservices3/components/connect/MemoryDiscovery.java
MemoryDiscovery.resolveAll
public List<ConnectionParams> resolveAll(String correlationId, String key) { List<ConnectionParams> connections = new ArrayList<ConnectionParams>(); synchronized (_lock) { for (DiscoveryItem item : _items) { if (item.key == key && item.connection != null) connections.add(item.connection); } } return connections; }
java
public List<ConnectionParams> resolveAll(String correlationId, String key) { List<ConnectionParams> connections = new ArrayList<ConnectionParams>(); synchronized (_lock) { for (DiscoveryItem item : _items) { if (item.key == key && item.connection != null) connections.add(item.connection); } } return connections; }
[ "public", "List", "<", "ConnectionParams", ">", "resolveAll", "(", "String", "correlationId", ",", "String", "key", ")", "{", "List", "<", "ConnectionParams", ">", "connections", "=", "new", "ArrayList", "<", "ConnectionParams", ">", "(", ")", ";", "synchronized", "(", "_lock", ")", "{", "for", "(", "DiscoveryItem", "item", ":", "_items", ")", "{", "if", "(", "item", ".", "key", "==", "key", "&&", "item", ".", "connection", "!=", "null", ")", "connections", ".", "add", "(", "item", ".", "connection", ")", ";", "}", "}", "return", "connections", ";", "}" ]
Resolves all connection parameters by their key. @param correlationId (optional) transaction id to trace execution through call chain. @param key a key to uniquely identify the connections. @return receives found connections.
[ "Resolves", "all", "connection", "parameters", "by", "their", "key", "." ]
122352fbf9b208f6417376da7b8ad725bc85ee58
https://github.com/pip-services3-java/pip-services3-components-java/blob/122352fbf9b208f6417376da7b8ad725bc85ee58/src/org/pipservices3/components/connect/MemoryDiscovery.java#L137-L148
156,422
bwkimmel/java-util
src/main/java/ca/eandb/util/progress/ProgressPanel.java
ProgressPanel.getScrollPane
private JScrollPane getScrollPane() { if (scrollPane == null) { scrollPane = new JScrollPane(); scrollPane.setViewportView(getTable()); } return scrollPane; }
java
private JScrollPane getScrollPane() { if (scrollPane == null) { scrollPane = new JScrollPane(); scrollPane.setViewportView(getTable()); } return scrollPane; }
[ "private", "JScrollPane", "getScrollPane", "(", ")", "{", "if", "(", "scrollPane", "==", "null", ")", "{", "scrollPane", "=", "new", "JScrollPane", "(", ")", ";", "scrollPane", ".", "setViewportView", "(", "getTable", "(", ")", ")", ";", "}", "return", "scrollPane", ";", "}" ]
This method initializes scrollPane @return javax.swing.JScrollPane
[ "This", "method", "initializes", "scrollPane" ]
0c03664d42f0e6b111f64447f222aa73c2819e5c
https://github.com/bwkimmel/java-util/blob/0c03664d42f0e6b111f64447f222aa73c2819e5c/src/main/java/ca/eandb/util/progress/ProgressPanel.java#L87-L93
156,423
bwkimmel/java-util
src/main/java/ca/eandb/util/progress/ProgressPanel.java
ProgressPanel.getTable
private JTable getTable() { if (table == null) { table = new JTable(); table.setModel(getModel()); ProgressBarRenderer.applyTo(table); } return table; }
java
private JTable getTable() { if (table == null) { table = new JTable(); table.setModel(getModel()); ProgressBarRenderer.applyTo(table); } return table; }
[ "private", "JTable", "getTable", "(", ")", "{", "if", "(", "table", "==", "null", ")", "{", "table", "=", "new", "JTable", "(", ")", ";", "table", ".", "setModel", "(", "getModel", "(", ")", ")", ";", "ProgressBarRenderer", ".", "applyTo", "(", "table", ")", ";", "}", "return", "table", ";", "}" ]
This method initializes table @return javax.swing.JTable
[ "This", "method", "initializes", "table" ]
0c03664d42f0e6b111f64447f222aa73c2819e5c
https://github.com/bwkimmel/java-util/blob/0c03664d42f0e6b111f64447f222aa73c2819e5c/src/main/java/ca/eandb/util/progress/ProgressPanel.java#L100-L107
156,424
javagl/ND
nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java
DoubleTuples.dot
public static double dot(DoubleTuple t0, DoubleTuple t1) { Utils.checkForEqualSize(t0, t1); double result = 0; for (int i=0; i<t0.getSize(); i++) { result += t0.get(i) * t1.get(i); } return result; }
java
public static double dot(DoubleTuple t0, DoubleTuple t1) { Utils.checkForEqualSize(t0, t1); double result = 0; for (int i=0; i<t0.getSize(); i++) { result += t0.get(i) * t1.get(i); } return result; }
[ "public", "static", "double", "dot", "(", "DoubleTuple", "t0", ",", "DoubleTuple", "t1", ")", "{", "Utils", ".", "checkForEqualSize", "(", "t0", ",", "t1", ")", ";", "double", "result", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "t0", ".", "getSize", "(", ")", ";", "i", "++", ")", "{", "result", "+=", "t0", ".", "get", "(", "i", ")", "*", "t1", ".", "get", "(", "i", ")", ";", "}", "return", "result", ";", "}" ]
Computes the dot product of the given tuples @param t0 The first input tuple @param t1 The second input tuple @return The dot product @throws IllegalArgumentException If the given tuples do not have the same {@link Tuple#getSize() size}
[ "Computes", "the", "dot", "product", "of", "the", "given", "tuples" ]
bcb655aaf5fc88af6194f73a27cca079186ff559
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java#L808-L817
156,425
javagl/ND
nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java
DoubleTuples.appendRange
private static void appendRange( StringBuilder sb, DoubleTuple tuple, Locale locale, String format, int min, int max) { for (int i=min; i<max; i++) { if (i > min) { sb.append(", "); } if (locale != null && format != null) { sb.append(String.format(locale, format, tuple.get(i))); } else { sb.append(String.valueOf(tuple.get(i))); } } }
java
private static void appendRange( StringBuilder sb, DoubleTuple tuple, Locale locale, String format, int min, int max) { for (int i=min; i<max; i++) { if (i > min) { sb.append(", "); } if (locale != null && format != null) { sb.append(String.format(locale, format, tuple.get(i))); } else { sb.append(String.valueOf(tuple.get(i))); } } }
[ "private", "static", "void", "appendRange", "(", "StringBuilder", "sb", ",", "DoubleTuple", "tuple", ",", "Locale", "locale", ",", "String", "format", ",", "int", "min", ",", "int", "max", ")", "{", "for", "(", "int", "i", "=", "min", ";", "i", "<", "max", ";", "i", "++", ")", "{", "if", "(", "i", ">", "min", ")", "{", "sb", ".", "append", "(", "\", \"", ")", ";", "}", "if", "(", "locale", "!=", "null", "&&", "format", "!=", "null", ")", "{", "sb", ".", "append", "(", "String", ".", "format", "(", "locale", ",", "format", ",", "tuple", ".", "get", "(", "i", ")", ")", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "String", ".", "valueOf", "(", "tuple", ".", "get", "(", "i", ")", ")", ")", ";", "}", "}", "}" ]
Append the string representation of the specified range of the given tuple to the given string builder @param sb The string builder @param tuple The tuple @param locale The locale. If this is <code>null</code>, then a canonical string representation of the elements will be used. @param format The format. If this is <code>null</code>, then a canonical string representation of the elements will be used. @param min The minimum index to append, inclusive @param max The maximum index to append, exclusive
[ "Append", "the", "string", "representation", "of", "the", "specified", "range", "of", "the", "given", "tuple", "to", "the", "given", "string", "builder" ]
bcb655aaf5fc88af6194f73a27cca079186ff559
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java#L1320-L1339
156,426
javagl/ND
nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java
DoubleTuples.randomize
public static void randomize( MutableDoubleTuple t, double min, double max, Random random) { double delta = max - min; for (int i=0; i<t.getSize(); i++) { t.set(i, min + random.nextDouble() * delta); } }
java
public static void randomize( MutableDoubleTuple t, double min, double max, Random random) { double delta = max - min; for (int i=0; i<t.getSize(); i++) { t.set(i, min + random.nextDouble() * delta); } }
[ "public", "static", "void", "randomize", "(", "MutableDoubleTuple", "t", ",", "double", "min", ",", "double", "max", ",", "Random", "random", ")", "{", "double", "delta", "=", "max", "-", "min", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "t", ".", "getSize", "(", ")", ";", "i", "++", ")", "{", "t", ".", "set", "(", "i", ",", "min", "+", "random", ".", "nextDouble", "(", ")", "*", "delta", ")", ";", "}", "}" ]
Fill the given tuple with random values in the specified range, using the given random number generator @param t The tuple to fill @param min The minimum value, inclusive @param max The maximum value, exclusive @param random The random number generator
[ "Fill", "the", "given", "tuple", "with", "random", "values", "in", "the", "specified", "range", "using", "the", "given", "random", "number", "generator" ]
bcb655aaf5fc88af6194f73a27cca079186ff559
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java#L1455-L1463
156,427
javagl/ND
nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java
DoubleTuples.createRandom
public static MutableDoubleTuple createRandom(int size, Random random) { MutableDoubleTuple t = create(size); randomize(t, random); return t; }
java
public static MutableDoubleTuple createRandom(int size, Random random) { MutableDoubleTuple t = create(size); randomize(t, random); return t; }
[ "public", "static", "MutableDoubleTuple", "createRandom", "(", "int", "size", ",", "Random", "random", ")", "{", "MutableDoubleTuple", "t", "=", "create", "(", "size", ")", ";", "randomize", "(", "t", ",", "random", ")", ";", "return", "t", ";", "}" ]
Creates a tuple with the given size that is filled with random values in [0,1) @param size The size @param random The random number generator @return The new tuple
[ "Creates", "a", "tuple", "with", "the", "given", "size", "that", "is", "filled", "with", "random", "values", "in", "[", "0", "1", ")" ]
bcb655aaf5fc88af6194f73a27cca079186ff559
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java#L1485-L1490
156,428
javagl/ND
nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java
DoubleTuples.randomizeGaussian
public static void randomizeGaussian(MutableDoubleTuple t, Random random) { for (int i=0; i<t.getSize(); i++) { double value = random.nextGaussian(); t.set(i, value); } }
java
public static void randomizeGaussian(MutableDoubleTuple t, Random random) { for (int i=0; i<t.getSize(); i++) { double value = random.nextGaussian(); t.set(i, value); } }
[ "public", "static", "void", "randomizeGaussian", "(", "MutableDoubleTuple", "t", ",", "Random", "random", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "t", ".", "getSize", "(", ")", ";", "i", "++", ")", "{", "double", "value", "=", "random", ".", "nextGaussian", "(", ")", ";", "t", ".", "set", "(", "i", ",", "value", ")", ";", "}", "}" ]
Randomize the given tuple with a gaussian distribution with a mean of 0.0 and standard deviation of 1.0 @param t The tuple to fill @param random The random number generator
[ "Randomize", "the", "given", "tuple", "with", "a", "gaussian", "distribution", "with", "a", "mean", "of", "0", ".", "0", "and", "standard", "deviation", "of", "1", ".", "0" ]
bcb655aaf5fc88af6194f73a27cca079186ff559
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java#L1519-L1526
156,429
javagl/ND
nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java
DoubleTuples.createRandomGaussian
public static MutableDoubleTuple createRandomGaussian( int size, Random random) { MutableDoubleTuple t = create(size); randomizeGaussian(t, random); return t; }
java
public static MutableDoubleTuple createRandomGaussian( int size, Random random) { MutableDoubleTuple t = create(size); randomizeGaussian(t, random); return t; }
[ "public", "static", "MutableDoubleTuple", "createRandomGaussian", "(", "int", "size", ",", "Random", "random", ")", "{", "MutableDoubleTuple", "t", "=", "create", "(", "size", ")", ";", "randomizeGaussian", "(", "t", ",", "random", ")", ";", "return", "t", ";", "}" ]
Creates a tuple with the given size that was filled with values from a gaussian distribution with mean 0.0 and standard deviation 1.0 @param size The size @param random The random number generator @return The new tuple
[ "Creates", "a", "tuple", "with", "the", "given", "size", "that", "was", "filled", "with", "values", "from", "a", "gaussian", "distribution", "with", "mean", "0", ".", "0", "and", "standard", "deviation", "1", ".", "0" ]
bcb655aaf5fc88af6194f73a27cca079186ff559
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java#L1537-L1543
156,430
javagl/ND
nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java
DoubleTuples.normalizeElements
public static MutableDoubleTuple normalizeElements( DoubleTuple t, double min, double max, MutableDoubleTuple result) { return rescaleElements(t, min(t), max(t), min, max, result); }
java
public static MutableDoubleTuple normalizeElements( DoubleTuple t, double min, double max, MutableDoubleTuple result) { return rescaleElements(t, min(t), max(t), min, max, result); }
[ "public", "static", "MutableDoubleTuple", "normalizeElements", "(", "DoubleTuple", "t", ",", "double", "min", ",", "double", "max", ",", "MutableDoubleTuple", "result", ")", "{", "return", "rescaleElements", "(", "t", ",", "min", "(", "t", ")", ",", "max", "(", "t", ")", ",", "min", ",", "max", ",", "result", ")", ";", "}" ]
Normalize the elements of the given tuple, so that its minimum and maximum elements match the given minimum and maximum values. @param t The input tuple @param min The minimum value @param max The maximum value @param result The tuple that will store the result @return The result tuple @throws IllegalArgumentException If the given tuples do not have the same {@link Tuple#getSize() size}
[ "Normalize", "the", "elements", "of", "the", "given", "tuple", "so", "that", "its", "minimum", "and", "maximum", "elements", "match", "the", "given", "minimum", "and", "maximum", "values", "." ]
bcb655aaf5fc88af6194f73a27cca079186ff559
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java#L1595-L1599
156,431
javagl/ND
nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java
DoubleTuples.normalizeElements
public static MutableDoubleTuple normalizeElements( DoubleTuple t, DoubleTuple min, DoubleTuple max, MutableDoubleTuple result) { result = validate(t, result); for (int i=0; i<result.getSize(); i++) { double value = t.get(i); double minValue = min.get(i); double maxValue = max.get(i); double alpha = (value - minValue) / (maxValue - minValue); double newValue = alpha; result.set(i, newValue); } return result; }
java
public static MutableDoubleTuple normalizeElements( DoubleTuple t, DoubleTuple min, DoubleTuple max, MutableDoubleTuple result) { result = validate(t, result); for (int i=0; i<result.getSize(); i++) { double value = t.get(i); double minValue = min.get(i); double maxValue = max.get(i); double alpha = (value - minValue) / (maxValue - minValue); double newValue = alpha; result.set(i, newValue); } return result; }
[ "public", "static", "MutableDoubleTuple", "normalizeElements", "(", "DoubleTuple", "t", ",", "DoubleTuple", "min", ",", "DoubleTuple", "max", ",", "MutableDoubleTuple", "result", ")", "{", "result", "=", "validate", "(", "t", ",", "result", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "getSize", "(", ")", ";", "i", "++", ")", "{", "double", "value", "=", "t", ".", "get", "(", "i", ")", ";", "double", "minValue", "=", "min", ".", "get", "(", "i", ")", ";", "double", "maxValue", "=", "max", ".", "get", "(", "i", ")", ";", "double", "alpha", "=", "(", "value", "-", "minValue", ")", "/", "(", "maxValue", "-", "minValue", ")", ";", "double", "newValue", "=", "alpha", ";", "result", ".", "set", "(", "i", ",", "newValue", ")", ";", "}", "return", "result", ";", "}" ]
Normalize the elements of the given tuple, so that each element will be linearly rescaled to the interval defined by the corresponding elements of the given minimum and maximum tuple. Each element that is equal to the corresponding minimum element will be 0.0 in the resulting tuple. Each element that is equal to the corresponding maximum element will be 1.0 in the resulting tuple. Other values will be interpolated accordingly. @param t The input tuple @param min The minimum value @param max The maximum value @param result The tuple that will store the result @return The result tuple @throws IllegalArgumentException If the given tuples do not have the same {@link Tuple#getSize() size}
[ "Normalize", "the", "elements", "of", "the", "given", "tuple", "so", "that", "each", "element", "will", "be", "linearly", "rescaled", "to", "the", "interval", "defined", "by", "the", "corresponding", "elements", "of", "the", "given", "minimum", "and", "maximum", "tuple", ".", "Each", "element", "that", "is", "equal", "to", "the", "corresponding", "minimum", "element", "will", "be", "0", ".", "0", "in", "the", "resulting", "tuple", ".", "Each", "element", "that", "is", "equal", "to", "the", "corresponding", "maximum", "element", "will", "be", "1", ".", "0", "in", "the", "resulting", "tuple", ".", "Other", "values", "will", "be", "interpolated", "accordingly", "." ]
bcb655aaf5fc88af6194f73a27cca079186ff559
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java#L1619-L1634
156,432
javagl/ND
nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java
DoubleTuples.rescaleElements
public static MutableDoubleTuple rescaleElements( DoubleTuple t, double oldMin, double oldMax, double newMin, double newMax, MutableDoubleTuple result) { double invDelta = 1.0 / (oldMax - oldMin); double newRange = newMax - newMin; double scaling = invDelta * newRange; return DoubleTupleFunctions.apply( t, (a)->(newMin + (a - oldMin) * scaling), result); }
java
public static MutableDoubleTuple rescaleElements( DoubleTuple t, double oldMin, double oldMax, double newMin, double newMax, MutableDoubleTuple result) { double invDelta = 1.0 / (oldMax - oldMin); double newRange = newMax - newMin; double scaling = invDelta * newRange; return DoubleTupleFunctions.apply( t, (a)->(newMin + (a - oldMin) * scaling), result); }
[ "public", "static", "MutableDoubleTuple", "rescaleElements", "(", "DoubleTuple", "t", ",", "double", "oldMin", ",", "double", "oldMax", ",", "double", "newMin", ",", "double", "newMax", ",", "MutableDoubleTuple", "result", ")", "{", "double", "invDelta", "=", "1.0", "/", "(", "oldMax", "-", "oldMin", ")", ";", "double", "newRange", "=", "newMax", "-", "newMin", ";", "double", "scaling", "=", "invDelta", "*", "newRange", ";", "return", "DoubleTupleFunctions", ".", "apply", "(", "t", ",", "(", "a", ")", "-", ">", "(", "newMin", "+", "(", "a", "-", "oldMin", ")", "*", "scaling", ")", ",", "result", ")", ";", "}" ]
Rescale the elements of the given tuple, so that the specified old range is mapped to the specified new range. @param t The input tuple @param oldMin The old minimum value @param oldMax The old maximum value @param newMin The new minimum value @param newMax The new maximum value @param result The tuple that will store the result @return The result tuple @throws IllegalArgumentException If the given tuples do not have the same {@link Tuple#getSize() size}
[ "Rescale", "the", "elements", "of", "the", "given", "tuple", "so", "that", "the", "specified", "old", "range", "is", "mapped", "to", "the", "specified", "new", "range", "." ]
bcb655aaf5fc88af6194f73a27cca079186ff559
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java#L1651-L1660
156,433
javagl/ND
nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java
DoubleTuples.geometricMean
public static double geometricMean(DoubleTuple t) { double product = DoubleTupleFunctions.reduce(t, 1.0, (a,b) -> (a*b)); return Math.pow(product, 1.0 / t.getSize()); }
java
public static double geometricMean(DoubleTuple t) { double product = DoubleTupleFunctions.reduce(t, 1.0, (a,b) -> (a*b)); return Math.pow(product, 1.0 / t.getSize()); }
[ "public", "static", "double", "geometricMean", "(", "DoubleTuple", "t", ")", "{", "double", "product", "=", "DoubleTupleFunctions", ".", "reduce", "(", "t", ",", "1.0", ",", "(", "a", ",", "b", ")", "->", "(", "a", "*", "b", ")", ")", ";", "return", "Math", ".", "pow", "(", "product", ",", "1.0", "/", "t", ".", "getSize", "(", ")", ")", ";", "}" ]
Returns the geometric mean of the given tuple @param t The input tuple @return The mean
[ "Returns", "the", "geometric", "mean", "of", "the", "given", "tuple" ]
bcb655aaf5fc88af6194f73a27cca079186ff559
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java#L1690-L1694
156,434
javagl/ND
nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java
DoubleTuples.harmonicMean
public static double harmonicMean(DoubleTuple t) { double s = DoubleTupleFunctions.reduce(t, 0.0, (a, b) -> (a + (1.0 / b))); return t.getSize() / s; }
java
public static double harmonicMean(DoubleTuple t) { double s = DoubleTupleFunctions.reduce(t, 0.0, (a, b) -> (a + (1.0 / b))); return t.getSize() / s; }
[ "public", "static", "double", "harmonicMean", "(", "DoubleTuple", "t", ")", "{", "double", "s", "=", "DoubleTupleFunctions", ".", "reduce", "(", "t", ",", "0.0", ",", "(", "a", ",", "b", ")", "->", "(", "a", "+", "(", "1.0", "/", "b", ")", ")", ")", ";", "return", "t", ".", "getSize", "(", ")", "/", "s", ";", "}" ]
Returns the harmonic mean of the given tuple @param t The input tuple @return The mean
[ "Returns", "the", "harmonic", "mean", "of", "the", "given", "tuple" ]
bcb655aaf5fc88af6194f73a27cca079186ff559
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java#L1702-L1707
156,435
javagl/ND
nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java
DoubleTuples.standardize
public static MutableDoubleTuple standardize( DoubleTuple t, MutableDoubleTuple result) { result = DoubleTuples.validate(t, result); double mean = arithmeticMean(t); double standardDeviation = standardDeviationFromMean(t, mean); double invStandardDeviation = 1.0 / standardDeviation; return DoubleTupleFunctions.apply( t, (a) -> ((a - mean) * invStandardDeviation), result); }
java
public static MutableDoubleTuple standardize( DoubleTuple t, MutableDoubleTuple result) { result = DoubleTuples.validate(t, result); double mean = arithmeticMean(t); double standardDeviation = standardDeviationFromMean(t, mean); double invStandardDeviation = 1.0 / standardDeviation; return DoubleTupleFunctions.apply( t, (a) -> ((a - mean) * invStandardDeviation), result); }
[ "public", "static", "MutableDoubleTuple", "standardize", "(", "DoubleTuple", "t", ",", "MutableDoubleTuple", "result", ")", "{", "result", "=", "DoubleTuples", ".", "validate", "(", "t", ",", "result", ")", ";", "double", "mean", "=", "arithmeticMean", "(", "t", ")", ";", "double", "standardDeviation", "=", "standardDeviationFromMean", "(", "t", ",", "mean", ")", ";", "double", "invStandardDeviation", "=", "1.0", "/", "standardDeviation", ";", "return", "DoubleTupleFunctions", ".", "apply", "(", "t", ",", "(", "a", ")", "-", ">", "(", "(", "a", "-", "mean", ")", "*", "invStandardDeviation", ")", ",", "result", ")", ";", "}" ]
Standardize the given tuple. This means that the mean of the elements is subtracted from them, and they are divided by the standard deviation. @param t The tuple @param result The result tuple @return The result tuple @throws IllegalArgumentException If the given tuples do not have the same {@link Tuple#getSize() size}
[ "Standardize", "the", "given", "tuple", ".", "This", "means", "that", "the", "mean", "of", "the", "elements", "is", "subtracted", "from", "them", "and", "they", "are", "divided", "by", "the", "standard", "deviation", "." ]
bcb655aaf5fc88af6194f73a27cca079186ff559
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java#L1739-L1748
156,436
javagl/ND
nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java
DoubleTuples.arithmeticMean
public static double arithmeticMean(DoubleTuple t) { double sum = DoubleTupleFunctions.reduce(t, 0.0, (a,b) -> (a+b)); return sum / t.getSize(); }
java
public static double arithmeticMean(DoubleTuple t) { double sum = DoubleTupleFunctions.reduce(t, 0.0, (a,b) -> (a+b)); return sum / t.getSize(); }
[ "public", "static", "double", "arithmeticMean", "(", "DoubleTuple", "t", ")", "{", "double", "sum", "=", "DoubleTupleFunctions", ".", "reduce", "(", "t", ",", "0.0", ",", "(", "a", ",", "b", ")", "->", "(", "a", "+", "b", ")", ")", ";", "return", "sum", "/", "t", ".", "getSize", "(", ")", ";", "}" ]
Returns the arithmetic mean of the given tuple @param t The input tuple @return The mean
[ "Returns", "the", "arithmetic", "mean", "of", "the", "given", "tuple" ]
bcb655aaf5fc88af6194f73a27cca079186ff559
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java#L1756-L1760
156,437
javagl/ND
nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java
DoubleTuples.variance
public static double variance(DoubleTuple t, double mean) { int d = t.getSize(); double variance = 0; for (int i=0; i<d; i++) { double difference = t.get(i) - mean; variance += difference * difference; } return variance / (d - 1); }
java
public static double variance(DoubleTuple t, double mean) { int d = t.getSize(); double variance = 0; for (int i=0; i<d; i++) { double difference = t.get(i) - mean; variance += difference * difference; } return variance / (d - 1); }
[ "public", "static", "double", "variance", "(", "DoubleTuple", "t", ",", "double", "mean", ")", "{", "int", "d", "=", "t", ".", "getSize", "(", ")", ";", "double", "variance", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "d", ";", "i", "++", ")", "{", "double", "difference", "=", "t", ".", "get", "(", "i", ")", "-", "mean", ";", "variance", "+=", "difference", "*", "difference", ";", "}", "return", "variance", "/", "(", "d", "-", "1", ")", ";", "}" ]
Returns the bias-corrected sample variance of the given tuple. @param t The input tuple @param mean The mean, which may have been computed before with {@link #arithmeticMean(DoubleTuple)} @return The variance
[ "Returns", "the", "bias", "-", "corrected", "sample", "variance", "of", "the", "given", "tuple", "." ]
bcb655aaf5fc88af6194f73a27cca079186ff559
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java#L1786-L1796
156,438
javagl/ND
nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java
DoubleTuples.containsNaN
public static boolean containsNaN(DoubleTuple tuple) { for (int i=0; i<tuple.getSize(); i++) { if (Double.isNaN(tuple.get(i))) { return true; } } return false; }
java
public static boolean containsNaN(DoubleTuple tuple) { for (int i=0; i<tuple.getSize(); i++) { if (Double.isNaN(tuple.get(i))) { return true; } } return false; }
[ "public", "static", "boolean", "containsNaN", "(", "DoubleTuple", "tuple", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "tuple", ".", "getSize", "(", ")", ";", "i", "++", ")", "{", "if", "(", "Double", ".", "isNaN", "(", "tuple", ".", "get", "(", "i", ")", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns whether the given tuple contains an element that is Not A Number @param tuple The tuple @return Whether the tuple contains a NaN element
[ "Returns", "whether", "the", "given", "tuple", "contains", "an", "element", "that", "is", "Not", "A", "Number" ]
bcb655aaf5fc88af6194f73a27cca079186ff559
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java#L1839-L1849
156,439
javagl/ND
nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java
DoubleTuples.replaceNaN
public static MutableDoubleTuple replaceNaN( DoubleTuple t, double newValue, MutableDoubleTuple result) { return DoubleTupleFunctions.apply( t, d -> Double.isNaN(d) ? newValue : d, result); }
java
public static MutableDoubleTuple replaceNaN( DoubleTuple t, double newValue, MutableDoubleTuple result) { return DoubleTupleFunctions.apply( t, d -> Double.isNaN(d) ? newValue : d, result); }
[ "public", "static", "MutableDoubleTuple", "replaceNaN", "(", "DoubleTuple", "t", ",", "double", "newValue", ",", "MutableDoubleTuple", "result", ")", "{", "return", "DoubleTupleFunctions", ".", "apply", "(", "t", ",", "d", "->", "Double", ".", "isNaN", "(", "d", ")", "?", "newValue", ":", "d", ",", "result", ")", ";", "}" ]
Replace all occurrences of "Not A Number" in the given tuple with the given value, and store the result in the given result tuple @param t The tuple @param newValue The value that should replace the NaN value @param result The tuple that will store the result @return The result tuple @throws IllegalArgumentException If the given tuples do not have the same {@link Tuple#getSize() size}
[ "Replace", "all", "occurrences", "of", "Not", "A", "Number", "in", "the", "given", "tuple", "with", "the", "given", "value", "and", "store", "the", "result", "in", "the", "given", "result", "tuple" ]
bcb655aaf5fc88af6194f73a27cca079186ff559
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java#L1863-L1868
156,440
intellimate/Izou
src/main/java/org/intellimate/izou/system/sound/replaced/MixerAspect.java
MixerAspect.getAndRegisterLine
static Line getAndRegisterLine(Line line) { AddOnModel addOnModel; Optional<AddOnModel> addOnModelForClassLoader = main.getSecurityManager().getAddOnModelForClassLoader(); if (!addOnModelForClassLoader.isPresent()) { logger.debug("the SoundManager will not manage this line, obtained by system"); return line; } else { addOnModel = addOnModelForClassLoader.get(); } IzouSoundLineBaseClass izouSoundLine; if (line instanceof SourceDataLine) { if (line instanceof Clip) { izouSoundLine = new IzouSoundLineClipAndSDLine((Clip) line, (SourceDataLine) line, main, false, addOnModel); } else { izouSoundLine = new IzouSoundSourceDataLine((SourceDataLine) line, main, false, addOnModel); } } else if (line instanceof Clip) { izouSoundLine = new IzouSoundLineClip((Clip) line, main, false, addOnModel); } else if (line instanceof DataLine) { izouSoundLine = new IzouSoundDataLine((DataLine) line, main, false, addOnModel); } else { izouSoundLine = new IzouSoundLineBaseClass(line, main, false, addOnModel); } main.getSoundManager().addIzouSoundLine(addOnModel, izouSoundLine); return izouSoundLine; }
java
static Line getAndRegisterLine(Line line) { AddOnModel addOnModel; Optional<AddOnModel> addOnModelForClassLoader = main.getSecurityManager().getAddOnModelForClassLoader(); if (!addOnModelForClassLoader.isPresent()) { logger.debug("the SoundManager will not manage this line, obtained by system"); return line; } else { addOnModel = addOnModelForClassLoader.get(); } IzouSoundLineBaseClass izouSoundLine; if (line instanceof SourceDataLine) { if (line instanceof Clip) { izouSoundLine = new IzouSoundLineClipAndSDLine((Clip) line, (SourceDataLine) line, main, false, addOnModel); } else { izouSoundLine = new IzouSoundSourceDataLine((SourceDataLine) line, main, false, addOnModel); } } else if (line instanceof Clip) { izouSoundLine = new IzouSoundLineClip((Clip) line, main, false, addOnModel); } else if (line instanceof DataLine) { izouSoundLine = new IzouSoundDataLine((DataLine) line, main, false, addOnModel); } else { izouSoundLine = new IzouSoundLineBaseClass(line, main, false, addOnModel); } main.getSoundManager().addIzouSoundLine(addOnModel, izouSoundLine); return izouSoundLine; }
[ "static", "Line", "getAndRegisterLine", "(", "Line", "line", ")", "{", "AddOnModel", "addOnModel", ";", "Optional", "<", "AddOnModel", ">", "addOnModelForClassLoader", "=", "main", ".", "getSecurityManager", "(", ")", ".", "getAddOnModelForClassLoader", "(", ")", ";", "if", "(", "!", "addOnModelForClassLoader", ".", "isPresent", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"the SoundManager will not manage this line, obtained by system\"", ")", ";", "return", "line", ";", "}", "else", "{", "addOnModel", "=", "addOnModelForClassLoader", ".", "get", "(", ")", ";", "}", "IzouSoundLineBaseClass", "izouSoundLine", ";", "if", "(", "line", "instanceof", "SourceDataLine", ")", "{", "if", "(", "line", "instanceof", "Clip", ")", "{", "izouSoundLine", "=", "new", "IzouSoundLineClipAndSDLine", "(", "(", "Clip", ")", "line", ",", "(", "SourceDataLine", ")", "line", ",", "main", ",", "false", ",", "addOnModel", ")", ";", "}", "else", "{", "izouSoundLine", "=", "new", "IzouSoundSourceDataLine", "(", "(", "SourceDataLine", ")", "line", ",", "main", ",", "false", ",", "addOnModel", ")", ";", "}", "}", "else", "if", "(", "line", "instanceof", "Clip", ")", "{", "izouSoundLine", "=", "new", "IzouSoundLineClip", "(", "(", "Clip", ")", "line", ",", "main", ",", "false", ",", "addOnModel", ")", ";", "}", "else", "if", "(", "line", "instanceof", "DataLine", ")", "{", "izouSoundLine", "=", "new", "IzouSoundDataLine", "(", "(", "DataLine", ")", "line", ",", "main", ",", "false", ",", "addOnModel", ")", ";", "}", "else", "{", "izouSoundLine", "=", "new", "IzouSoundLineBaseClass", "(", "line", ",", "main", ",", "false", ",", "addOnModel", ")", ";", "}", "main", ".", "getSoundManager", "(", ")", ".", "addIzouSoundLine", "(", "addOnModel", ",", "izouSoundLine", ")", ";", "return", "izouSoundLine", ";", "}" ]
creates the appropriate IzouSoundLine if the request originates from an AddOn. @param line the line @return an IzouSoundLine if an addon requested the line
[ "creates", "the", "appropriate", "IzouSoundLine", "if", "the", "request", "originates", "from", "an", "AddOn", "." ]
40a808b97998e17655c4a78e30ce7326148aed27
https://github.com/intellimate/Izou/blob/40a808b97998e17655c4a78e30ce7326148aed27/src/main/java/org/intellimate/izou/system/sound/replaced/MixerAspect.java#L37-L63
156,441
jmeetsma/Iglu-Common
src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java
StandardCache.getReport
public String getReport() { StringBuffer info = new StringBuffer(); if (!isCachingEnabled()) { info.append("cache behaviour: DISABLED\n"); } else if (isCachingPermanent()) { info.append("cache behaviour: PERMANENT\n"); } else { info.append("cache behaviour: NORMAL\n"); } info.append("time to live: " + ttlInSeconds + " s\n"); info.append("cleanup interval: " + cleanupInterval + " s\n"); info.append("cache size: " + data.size() + " objects\n"); info.append("cache mirror size: " + mirror.size() + " object(s)\n"); info.append("cache hits: " + hits + '\n'); info.append("cache misses: " + misses + '\n'); info.append("cache unavailable: " + unavailable + '\n'); info.append("cache delayed hits: " + delayedHits + '\n'); info.append("cache delayed misses: " + delayedMisses + '\n'); info.append("next cleanup run: " + new Date(lastRun.getTime() + (cleanupInterval * 1000)) + "\n"); return info.toString(); }
java
public String getReport() { StringBuffer info = new StringBuffer(); if (!isCachingEnabled()) { info.append("cache behaviour: DISABLED\n"); } else if (isCachingPermanent()) { info.append("cache behaviour: PERMANENT\n"); } else { info.append("cache behaviour: NORMAL\n"); } info.append("time to live: " + ttlInSeconds + " s\n"); info.append("cleanup interval: " + cleanupInterval + " s\n"); info.append("cache size: " + data.size() + " objects\n"); info.append("cache mirror size: " + mirror.size() + " object(s)\n"); info.append("cache hits: " + hits + '\n'); info.append("cache misses: " + misses + '\n'); info.append("cache unavailable: " + unavailable + '\n'); info.append("cache delayed hits: " + delayedHits + '\n'); info.append("cache delayed misses: " + delayedMisses + '\n'); info.append("next cleanup run: " + new Date(lastRun.getTime() + (cleanupInterval * 1000)) + "\n"); return info.toString(); }
[ "public", "String", "getReport", "(", ")", "{", "StringBuffer", "info", "=", "new", "StringBuffer", "(", ")", ";", "if", "(", "!", "isCachingEnabled", "(", ")", ")", "{", "info", ".", "append", "(", "\"cache behaviour: DISABLED\\n\"", ")", ";", "}", "else", "if", "(", "isCachingPermanent", "(", ")", ")", "{", "info", ".", "append", "(", "\"cache behaviour: PERMANENT\\n\"", ")", ";", "}", "else", "{", "info", ".", "append", "(", "\"cache behaviour: NORMAL\\n\"", ")", ";", "}", "info", ".", "append", "(", "\"time to live: \"", "+", "ttlInSeconds", "+", "\" s\\n\"", ")", ";", "info", ".", "append", "(", "\"cleanup interval: \"", "+", "cleanupInterval", "+", "\" s\\n\"", ")", ";", "info", ".", "append", "(", "\"cache size: \"", "+", "data", ".", "size", "(", ")", "+", "\" objects\\n\"", ")", ";", "info", ".", "append", "(", "\"cache mirror size: \"", "+", "mirror", ".", "size", "(", ")", "+", "\" object(s)\\n\"", ")", ";", "info", ".", "append", "(", "\"cache hits: \"", "+", "hits", "+", "'", "'", ")", ";", "info", ".", "append", "(", "\"cache misses: \"", "+", "misses", "+", "'", "'", ")", ";", "info", ".", "append", "(", "\"cache unavailable: \"", "+", "unavailable", "+", "'", "'", ")", ";", "info", ".", "append", "(", "\"cache delayed hits: \"", "+", "delayedHits", "+", "'", "'", ")", ";", "info", ".", "append", "(", "\"cache delayed misses: \"", "+", "delayedMisses", "+", "'", "'", ")", ";", "info", ".", "append", "(", "\"next cleanup run: \"", "+", "new", "Date", "(", "lastRun", ".", "getTime", "(", ")", "+", "(", "cleanupInterval", "*", "1000", ")", ")", "+", "\"\\n\"", ")", ";", "return", "info", ".", "toString", "(", ")", ";", "}" ]
Returns a status report containing behavior and statistics. @return status report
[ "Returns", "a", "status", "report", "containing", "behavior", "and", "statistics", "." ]
0fb0885775b576209ff1b5a0f67e3c25a99a6420
https://github.com/jmeetsma/Iglu-Common/blob/0fb0885775b576209ff1b5a0f67e3c25a99a6420/src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java#L75-L96
156,442
jmeetsma/Iglu-Common
src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java
StandardCache.stop
public void stop() { hits = 0; misses = 0; unavailable = 0; delayedHits = 0; delayedMisses = 0; data.clear(); mirror.clear(); isStarted = false; }
java
public void stop() { hits = 0; misses = 0; unavailable = 0; delayedHits = 0; delayedMisses = 0; data.clear(); mirror.clear(); isStarted = false; }
[ "public", "void", "stop", "(", ")", "{", "hits", "=", "0", ";", "misses", "=", "0", ";", "unavailable", "=", "0", ";", "delayedHits", "=", "0", ";", "delayedMisses", "=", "0", ";", "data", ".", "clear", "(", ")", ";", "mirror", ".", "clear", "(", ")", ";", "isStarted", "=", "false", ";", "}" ]
Clears storage. Resets statistics. Is invoked by superclass.
[ "Clears", "storage", ".", "Resets", "statistics", ".", "Is", "invoked", "by", "superclass", "." ]
0fb0885775b576209ff1b5a0f67e3c25a99a6420
https://github.com/jmeetsma/Iglu-Common/blob/0fb0885775b576209ff1b5a0f67e3c25a99a6420/src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java#L111-L120
156,443
jmeetsma/Iglu-Common
src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java
StandardCache.retrieve
public Object retrieve(K key, int timeout) { Object retval = null; if (isCachingEnabled()) { CachedObject<V> co = getCachedObject(key); if (co == null || isCachedObjectExpired(co)) { misses++; co = new CachedObject<V>(); co.setBeingRetrieved(); this.storeCachedObject(key, co); } else if (co.getObject() != null) { hits++; retval = co.getObject(); } else { //the timeout for retrieving an object is used instead of the cache timeout co = getCachedObjectOnceRetrievedByOtherThread(key, timeout); if (co == null) { //this could happen on a rare occasion and may not lead to problems delayedMisses++; } else if (co.getObject() == null) { // still null delayedMisses++; if (co.isExpired(timeout) && co.isBeingRetrieved()) { // prolongate retrieval state if cached object is not a designated null co.setBeingRetrieved(); } } else { delayedHits++; retval = co.getObject(); } } } return retval; }
java
public Object retrieve(K key, int timeout) { Object retval = null; if (isCachingEnabled()) { CachedObject<V> co = getCachedObject(key); if (co == null || isCachedObjectExpired(co)) { misses++; co = new CachedObject<V>(); co.setBeingRetrieved(); this.storeCachedObject(key, co); } else if (co.getObject() != null) { hits++; retval = co.getObject(); } else { //the timeout for retrieving an object is used instead of the cache timeout co = getCachedObjectOnceRetrievedByOtherThread(key, timeout); if (co == null) { //this could happen on a rare occasion and may not lead to problems delayedMisses++; } else if (co.getObject() == null) { // still null delayedMisses++; if (co.isExpired(timeout) && co.isBeingRetrieved()) { // prolongate retrieval state if cached object is not a designated null co.setBeingRetrieved(); } } else { delayedHits++; retval = co.getObject(); } } } return retval; }
[ "public", "Object", "retrieve", "(", "K", "key", ",", "int", "timeout", ")", "{", "Object", "retval", "=", "null", ";", "if", "(", "isCachingEnabled", "(", ")", ")", "{", "CachedObject", "<", "V", ">", "co", "=", "getCachedObject", "(", "key", ")", ";", "if", "(", "co", "==", "null", "||", "isCachedObjectExpired", "(", "co", ")", ")", "{", "misses", "++", ";", "co", "=", "new", "CachedObject", "<", "V", ">", "(", ")", ";", "co", ".", "setBeingRetrieved", "(", ")", ";", "this", ".", "storeCachedObject", "(", "key", ",", "co", ")", ";", "}", "else", "if", "(", "co", ".", "getObject", "(", ")", "!=", "null", ")", "{", "hits", "++", ";", "retval", "=", "co", ".", "getObject", "(", ")", ";", "}", "else", "{", "//the timeout for retrieving an object is used instead of the cache timeout", "co", "=", "getCachedObjectOnceRetrievedByOtherThread", "(", "key", ",", "timeout", ")", ";", "if", "(", "co", "==", "null", ")", "{", "//this could happen on a rare occasion and may not lead to problems", "delayedMisses", "++", ";", "}", "else", "if", "(", "co", ".", "getObject", "(", ")", "==", "null", ")", "{", "// still null", "delayedMisses", "++", ";", "if", "(", "co", ".", "isExpired", "(", "timeout", ")", "&&", "co", ".", "isBeingRetrieved", "(", ")", ")", "{", "// prolongate retrieval state if cached object is not a designated null", "co", ".", "setBeingRetrieved", "(", ")", ";", "}", "}", "else", "{", "delayedHits", "++", ";", "retval", "=", "co", ".", "getObject", "(", ")", ";", "}", "}", "}", "return", "retval", ";", "}" ]
Retrieves an object from cache. This method should be used if a programmer suspects bursts of requests for a particular object. If this is the case, the first thread will retrieve the object, the others will wait for some time, in order to save overhead. @param key the key to retrieve the object by @param timeout time in millis to wait for the first thread to retrieve an object from the original location @return the cached object or null if it's not found
[ "Retrieves", "an", "object", "from", "cache", ".", "This", "method", "should", "be", "used", "if", "a", "programmer", "suspects", "bursts", "of", "requests", "for", "a", "particular", "object", ".", "If", "this", "is", "the", "case", "the", "first", "thread", "will", "retrieve", "the", "object", "the", "others", "will", "wait", "for", "some", "time", "in", "order", "to", "save", "overhead", "." ]
0fb0885775b576209ff1b5a0f67e3c25a99a6420
https://github.com/jmeetsma/Iglu-Common/blob/0fb0885775b576209ff1b5a0f67e3c25a99a6420/src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java#L180-L211
156,444
jmeetsma/Iglu-Common
src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java
StandardCache.storeCachedObject
private Object storeCachedObject(K key, CachedObject<V> co) { //data is only locked if cleanup removes cached objects synchronized (data) { data.put(key, co); } //mirror is also locked if cleanup is busy collecting cached objects synchronized (mirror) { mirror.put(key, co); } System.out.println(new LogEntry("object with key " + key + " stored in cache")); return co; }
java
private Object storeCachedObject(K key, CachedObject<V> co) { //data is only locked if cleanup removes cached objects synchronized (data) { data.put(key, co); } //mirror is also locked if cleanup is busy collecting cached objects synchronized (mirror) { mirror.put(key, co); } System.out.println(new LogEntry("object with key " + key + " stored in cache")); return co; }
[ "private", "Object", "storeCachedObject", "(", "K", "key", ",", "CachedObject", "<", "V", ">", "co", ")", "{", "//data is only locked if cleanup removes cached objects", "synchronized", "(", "data", ")", "{", "data", ".", "put", "(", "key", ",", "co", ")", ";", "}", "//mirror is also locked if cleanup is busy collecting cached objects", "synchronized", "(", "mirror", ")", "{", "mirror", ".", "put", "(", "key", ",", "co", ")", ";", "}", "System", ".", "out", ".", "println", "(", "new", "LogEntry", "(", "\"object with key \"", "+", "key", "+", "\" stored in cache\"", ")", ")", ";", "return", "co", ";", "}" ]
Places an empty wrapper in the cache to indicate that some thread should be busy retrieving the object, after which it should be cached after all. @param co @return
[ "Places", "an", "empty", "wrapper", "in", "the", "cache", "to", "indicate", "that", "some", "thread", "should", "be", "busy", "retrieving", "the", "object", "after", "which", "it", "should", "be", "cached", "after", "all", "." ]
0fb0885775b576209ff1b5a0f67e3c25a99a6420
https://github.com/jmeetsma/Iglu-Common/blob/0fb0885775b576209ff1b5a0f67e3c25a99a6420/src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java#L237-L248
156,445
jmeetsma/Iglu-Common
src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java
StandardCache.retrieve
public V retrieve(K key) { V retval = null; if (isCachingEnabled()) { CachedObject<V> co = getCachedObject(key); if (co == null || (isCachedObjectExpired(co))) { //take pressure off of cleanup misses++; } else if (co.getObject() == null) { unavailable++; } else { hits++; retval = co.getObject(); } } return retval; }
java
public V retrieve(K key) { V retval = null; if (isCachingEnabled()) { CachedObject<V> co = getCachedObject(key); if (co == null || (isCachedObjectExpired(co))) { //take pressure off of cleanup misses++; } else if (co.getObject() == null) { unavailable++; } else { hits++; retval = co.getObject(); } } return retval; }
[ "public", "V", "retrieve", "(", "K", "key", ")", "{", "V", "retval", "=", "null", ";", "if", "(", "isCachingEnabled", "(", ")", ")", "{", "CachedObject", "<", "V", ">", "co", "=", "getCachedObject", "(", "key", ")", ";", "if", "(", "co", "==", "null", "||", "(", "isCachedObjectExpired", "(", "co", ")", ")", ")", "{", "//take pressure off of cleanup", "misses", "++", ";", "}", "else", "if", "(", "co", ".", "getObject", "(", ")", "==", "null", ")", "{", "unavailable", "++", ";", "}", "else", "{", "hits", "++", ";", "retval", "=", "co", ".", "getObject", "(", ")", ";", "}", "}", "return", "retval", ";", "}" ]
Retrieves an object from cache. @param key the key to retrieve the object by @return the cached object or null if it's not found
[ "Retrieves", "an", "object", "from", "cache", "." ]
0fb0885775b576209ff1b5a0f67e3c25a99a6420
https://github.com/jmeetsma/Iglu-Common/blob/0fb0885775b576209ff1b5a0f67e3c25a99a6420/src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java#L272-L287
156,446
jmeetsma/Iglu-Common
src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java
StandardCache.cleanup
public long cleanup() { int garbageSize = 0; if (isCachingEnabled()) { System.out.println(new LogEntry(Level.VERBOSE, "Identifying expired objects")); ArrayList<K> garbage = getExpiredObjects(); garbageSize = garbage.size(); System.out.println(new LogEntry("cache cleanup: expired objects: " + garbageSize)); for (K key : garbage) { clear(key); } } return garbageSize; }
java
public long cleanup() { int garbageSize = 0; if (isCachingEnabled()) { System.out.println(new LogEntry(Level.VERBOSE, "Identifying expired objects")); ArrayList<K> garbage = getExpiredObjects(); garbageSize = garbage.size(); System.out.println(new LogEntry("cache cleanup: expired objects: " + garbageSize)); for (K key : garbage) { clear(key); } } return garbageSize; }
[ "public", "long", "cleanup", "(", ")", "{", "int", "garbageSize", "=", "0", ";", "if", "(", "isCachingEnabled", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "new", "LogEntry", "(", "Level", ".", "VERBOSE", ",", "\"Identifying expired objects\"", ")", ")", ";", "ArrayList", "<", "K", ">", "garbage", "=", "getExpiredObjects", "(", ")", ";", "garbageSize", "=", "garbage", ".", "size", "(", ")", ";", "System", ".", "out", ".", "println", "(", "new", "LogEntry", "(", "\"cache cleanup: expired objects: \"", "+", "garbageSize", ")", ")", ";", "for", "(", "K", "key", ":", "garbage", ")", "{", "clear", "(", "key", ")", ";", "}", "}", "return", "garbageSize", ";", "}" ]
Removes all expired objects. @return the number of removed objects.
[ "Removes", "all", "expired", "objects", "." ]
0fb0885775b576209ff1b5a0f67e3c25a99a6420
https://github.com/jmeetsma/Iglu-Common/blob/0fb0885775b576209ff1b5a0f67e3c25a99a6420/src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java#L320-L332
156,447
jmeetsma/Iglu-Common
src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java
StandardCache.clear
public void clear(Object key) { Object removed; if (isCachingEnabled()) { synchronized (mirror) { synchronized (data) { removed = data.remove(key); mirror.remove(key); } } System.out.println(new LogEntry("object with key " + key + (removed == null ? " NOT" : "") + " removed from cache")); } }
java
public void clear(Object key) { Object removed; if (isCachingEnabled()) { synchronized (mirror) { synchronized (data) { removed = data.remove(key); mirror.remove(key); } } System.out.println(new LogEntry("object with key " + key + (removed == null ? " NOT" : "") + " removed from cache")); } }
[ "public", "void", "clear", "(", "Object", "key", ")", "{", "Object", "removed", ";", "if", "(", "isCachingEnabled", "(", ")", ")", "{", "synchronized", "(", "mirror", ")", "{", "synchronized", "(", "data", ")", "{", "removed", "=", "data", ".", "remove", "(", "key", ")", ";", "mirror", ".", "remove", "(", "key", ")", ";", "}", "}", "System", ".", "out", ".", "println", "(", "new", "LogEntry", "(", "\"object with key \"", "+", "key", "+", "(", "removed", "==", "null", "?", "\" NOT\"", ":", "\"\"", ")", "+", "\" removed from cache\"", ")", ")", ";", "}", "}" ]
Removes an object from cache. @param key object key
[ "Removes", "an", "object", "from", "cache", "." ]
0fb0885775b576209ff1b5a0f67e3c25a99a6420
https://github.com/jmeetsma/Iglu-Common/blob/0fb0885775b576209ff1b5a0f67e3c25a99a6420/src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java#L354-L365
156,448
jmeetsma/Iglu-Common
src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java
StandardCache.clear
public void clear(Collection keys) { synchronized (mirror) { synchronized (data) { Iterator i = keys.iterator(); while (i.hasNext()) { Object key = i.next(); data.remove(key); mirror.remove(key); } } } }
java
public void clear(Collection keys) { synchronized (mirror) { synchronized (data) { Iterator i = keys.iterator(); while (i.hasNext()) { Object key = i.next(); data.remove(key); mirror.remove(key); } } } }
[ "public", "void", "clear", "(", "Collection", "keys", ")", "{", "synchronized", "(", "mirror", ")", "{", "synchronized", "(", "data", ")", "{", "Iterator", "i", "=", "keys", ".", "iterator", "(", ")", ";", "while", "(", "i", ".", "hasNext", "(", ")", ")", "{", "Object", "key", "=", "i", ".", "next", "(", ")", ";", "data", ".", "remove", "(", "key", ")", ";", "mirror", ".", "remove", "(", "key", ")", ";", "}", "}", "}", "}" ]
Removes a collection of objects from cache. @param keys object keys
[ "Removes", "a", "collection", "of", "objects", "from", "cache", "." ]
0fb0885775b576209ff1b5a0f67e3c25a99a6420
https://github.com/jmeetsma/Iglu-Common/blob/0fb0885775b576209ff1b5a0f67e3c25a99a6420/src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java#L372-L383
156,449
pip-services3-java/pip-services3-components-java
src/org/pipservices3/components/auth/MemoryCredentialStore.java
MemoryCredentialStore.readCredentials
public void readCredentials(ConfigParams credentials) { synchronized (_lock) { _items.clear(); for (Map.Entry<String, String> entry : credentials.entrySet()) _items.put(entry.getKey(), CredentialParams.fromString(entry.getValue())); } }
java
public void readCredentials(ConfigParams credentials) { synchronized (_lock) { _items.clear(); for (Map.Entry<String, String> entry : credentials.entrySet()) _items.put(entry.getKey(), CredentialParams.fromString(entry.getValue())); } }
[ "public", "void", "readCredentials", "(", "ConfigParams", "credentials", ")", "{", "synchronized", "(", "_lock", ")", "{", "_items", ".", "clear", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "credentials", ".", "entrySet", "(", ")", ")", "_items", ".", "put", "(", "entry", ".", "getKey", "(", ")", ",", "CredentialParams", ".", "fromString", "(", "entry", ".", "getValue", "(", ")", ")", ")", ";", "}", "}" ]
Reads credentials from configuration parameters. Each section represents an individual CredentialParams @param credentials configuration parameters to be read
[ "Reads", "credentials", "from", "configuration", "parameters", ".", "Each", "section", "represents", "an", "individual", "CredentialParams" ]
122352fbf9b208f6417376da7b8ad725bc85ee58
https://github.com/pip-services3-java/pip-services3-components-java/blob/122352fbf9b208f6417376da7b8ad725bc85ee58/src/org/pipservices3/components/auth/MemoryCredentialStore.java#L72-L78
156,450
pip-services3-java/pip-services3-components-java
src/org/pipservices3/components/auth/MemoryCredentialStore.java
MemoryCredentialStore.store
public void store(String correlationId, String key, CredentialParams credential) { synchronized (_lock) { if (credential != null) _items.put(key, credential); else _items.remove(key); } }
java
public void store(String correlationId, String key, CredentialParams credential) { synchronized (_lock) { if (credential != null) _items.put(key, credential); else _items.remove(key); } }
[ "public", "void", "store", "(", "String", "correlationId", ",", "String", "key", ",", "CredentialParams", "credential", ")", "{", "synchronized", "(", "_lock", ")", "{", "if", "(", "credential", "!=", "null", ")", "_items", ".", "put", "(", "key", ",", "credential", ")", ";", "else", "_items", ".", "remove", "(", "key", ")", ";", "}", "}" ]
Stores credential parameters into the store. @param correlationId (optional) transaction id to trace execution through call chain. @param key a key to uniquely identify the credential parameters. @param credential a credential parameters to be stored.
[ "Stores", "credential", "parameters", "into", "the", "store", "." ]
122352fbf9b208f6417376da7b8ad725bc85ee58
https://github.com/pip-services3-java/pip-services3-components-java/blob/122352fbf9b208f6417376da7b8ad725bc85ee58/src/org/pipservices3/components/auth/MemoryCredentialStore.java#L88-L95
156,451
pip-services3-java/pip-services3-components-java
src/org/pipservices3/components/auth/MemoryCredentialStore.java
MemoryCredentialStore.lookup
public CredentialParams lookup(String correlationId, String key) { synchronized (_lock) { return _items.get(key); } }
java
public CredentialParams lookup(String correlationId, String key) { synchronized (_lock) { return _items.get(key); } }
[ "public", "CredentialParams", "lookup", "(", "String", "correlationId", ",", "String", "key", ")", "{", "synchronized", "(", "_lock", ")", "{", "return", "_items", ".", "get", "(", "key", ")", ";", "}", "}" ]
Lookups credential parameters by its key. @param correlationId (optional) transaction id to trace execution through call chain. @param key a key to uniquely identify the credential parameters. @return resolved credential parameters or null if nothing was found.
[ "Lookups", "credential", "parameters", "by", "its", "key", "." ]
122352fbf9b208f6417376da7b8ad725bc85ee58
https://github.com/pip-services3-java/pip-services3-components-java/blob/122352fbf9b208f6417376da7b8ad725bc85ee58/src/org/pipservices3/components/auth/MemoryCredentialStore.java#L105-L109
156,452
loicoudot/java4cpp-core
src/main/java/com/github/loicoudot/java4cpp/Context.java
Context.createClassLoader
private void createClassLoader() { if (!Utils.isNullOrEmpty(settings.getJarFiles())) { try { String[] files = settings.getJarFiles().split(";"); List<URL> urls = newArrayList(); for (String path : files) { File file = new File(path); if (file.isFile()) { urls.add(file.toURI().toURL()); } } classLoader = new Java4CppClassLoader(urls.toArray(new URL[files.length]), classLoader); } catch (Exception e) { throw new RuntimeException("Failed to load jar " + e.getMessage()); } } }
java
private void createClassLoader() { if (!Utils.isNullOrEmpty(settings.getJarFiles())) { try { String[] files = settings.getJarFiles().split(";"); List<URL> urls = newArrayList(); for (String path : files) { File file = new File(path); if (file.isFile()) { urls.add(file.toURI().toURL()); } } classLoader = new Java4CppClassLoader(urls.toArray(new URL[files.length]), classLoader); } catch (Exception e) { throw new RuntimeException("Failed to load jar " + e.getMessage()); } } }
[ "private", "void", "createClassLoader", "(", ")", "{", "if", "(", "!", "Utils", ".", "isNullOrEmpty", "(", "settings", ".", "getJarFiles", "(", ")", ")", ")", "{", "try", "{", "String", "[", "]", "files", "=", "settings", ".", "getJarFiles", "(", ")", ".", "split", "(", "\";\"", ")", ";", "List", "<", "URL", ">", "urls", "=", "newArrayList", "(", ")", ";", "for", "(", "String", "path", ":", "files", ")", "{", "File", "file", "=", "new", "File", "(", "path", ")", ";", "if", "(", "file", ".", "isFile", "(", ")", ")", "{", "urls", ".", "add", "(", "file", ".", "toURI", "(", ")", ".", "toURL", "(", ")", ")", ";", "}", "}", "classLoader", "=", "new", "Java4CppClassLoader", "(", "urls", ".", "toArray", "(", "new", "URL", "[", "files", ".", "length", "]", ")", ",", "classLoader", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Failed to load jar \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "}" ]
Construct the context class loader by adding all jars.
[ "Construct", "the", "context", "class", "loader", "by", "adding", "all", "jars", "." ]
7fe5a5dd5a29c3f95b62f46eaacbb8f8778b9493
https://github.com/loicoudot/java4cpp-core/blob/7fe5a5dd5a29c3f95b62f46eaacbb8f8778b9493/src/main/java/com/github/loicoudot/java4cpp/Context.java#L74-L90
156,453
eiichiro/jaguar
jaguar-core/src/main/java/org/eiichiro/jaguar/Container.java
Container.installed
public boolean installed(Class<?> component) { Preconditions.checkArgument(component != null, "Parameter 'component' must not be [" + component + "]"); return installed.contains(component); }
java
public boolean installed(Class<?> component) { Preconditions.checkArgument(component != null, "Parameter 'component' must not be [" + component + "]"); return installed.contains(component); }
[ "public", "boolean", "installed", "(", "Class", "<", "?", ">", "component", ")", "{", "Preconditions", ".", "checkArgument", "(", "component", "!=", "null", ",", "\"Parameter 'component' must not be [\"", "+", "component", "+", "\"]\"", ")", ";", "return", "installed", ".", "contains", "(", "component", ")", ";", "}" ]
Indicates the specified component installed or not in the container. @param component The component class to be examined. @return <code>true</code> if the specified component installed in the container.
[ "Indicates", "the", "specified", "component", "installed", "or", "not", "in", "the", "container", "." ]
9da0b8677fa306f10f848402490c75d05c213547
https://github.com/eiichiro/jaguar/blob/9da0b8677fa306f10f848402490c75d05c213547/jaguar-core/src/main/java/org/eiichiro/jaguar/Container.java#L447-L451
156,454
CubeEngine/Dirigent
src/main/java/org/cubeengine/dirigent/formatter/AbstractFormatter.java
AbstractFormatter.getGenericType
@SuppressWarnings("unchecked") private static <T> Class<T> getGenericType(Class<?> thisClass) { Type type = thisClass; do { type = ((Class<?>)type).getGenericSuperclass(); if (type instanceof ParameterizedType) { return (Class<T>)((ParameterizedType)type).getActualTypeArguments()[0]; } } while (type instanceof Class<?> && !type.equals(AbstractFormatter.class)); return (Class<T>)Object.class; }
java
@SuppressWarnings("unchecked") private static <T> Class<T> getGenericType(Class<?> thisClass) { Type type = thisClass; do { type = ((Class<?>)type).getGenericSuperclass(); if (type instanceof ParameterizedType) { return (Class<T>)((ParameterizedType)type).getActualTypeArguments()[0]; } } while (type instanceof Class<?> && !type.equals(AbstractFormatter.class)); return (Class<T>)Object.class; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "static", "<", "T", ">", "Class", "<", "T", ">", "getGenericType", "(", "Class", "<", "?", ">", "thisClass", ")", "{", "Type", "type", "=", "thisClass", ";", "do", "{", "type", "=", "(", "(", "Class", "<", "?", ">", ")", "type", ")", ".", "getGenericSuperclass", "(", ")", ";", "if", "(", "type", "instanceof", "ParameterizedType", ")", "{", "return", "(", "Class", "<", "T", ">", ")", "(", "(", "ParameterizedType", ")", "type", ")", ".", "getActualTypeArguments", "(", ")", "[", "0", "]", ";", "}", "}", "while", "(", "type", "instanceof", "Class", "<", "?", ">", "&&", "!", "type", ".", "equals", "(", "AbstractFormatter", ".", "class", ")", ")", ";", "return", "(", "Class", "<", "T", ">", ")", "Object", ".", "class", ";", "}" ]
Loads the class information from the generic type of the specified class. @param thisClass The class. @param <T> The parameter object type. @return the class information.
[ "Loads", "the", "class", "information", "from", "the", "generic", "type", "of", "the", "specified", "class", "." ]
68587a8202754a6a6b629cc15e14c516806badaa
https://github.com/CubeEngine/Dirigent/blob/68587a8202754a6a6b629cc15e14c516806badaa/src/main/java/org/cubeengine/dirigent/formatter/AbstractFormatter.java#L101-L116
156,455
micwin/ticino
events/src/main/java/net/micwin/ticino/events/EventScope.java
EventScope.registerInternal
private void registerInternal(final Object receiver, final Method method, final Class<? extends T> eventClass) { List<ReceiverDescriptor> receivers = this.receiverMap.get(eventClass); if (receivers == null) { receivers = new LinkedList<ReceiverDescriptor>(); this.receiverMap.put(eventClass, receivers); } final ReceiverDescriptor rd = new ReceiverDescriptor(); rd.receiverReference = new SoftReference<Object>(receiver); rd.method = method; receivers.add(rd); }
java
private void registerInternal(final Object receiver, final Method method, final Class<? extends T> eventClass) { List<ReceiverDescriptor> receivers = this.receiverMap.get(eventClass); if (receivers == null) { receivers = new LinkedList<ReceiverDescriptor>(); this.receiverMap.put(eventClass, receivers); } final ReceiverDescriptor rd = new ReceiverDescriptor(); rd.receiverReference = new SoftReference<Object>(receiver); rd.method = method; receivers.add(rd); }
[ "private", "void", "registerInternal", "(", "final", "Object", "receiver", ",", "final", "Method", "method", ",", "final", "Class", "<", "?", "extends", "T", ">", "eventClass", ")", "{", "List", "<", "ReceiverDescriptor", ">", "receivers", "=", "this", ".", "receiverMap", ".", "get", "(", "eventClass", ")", ";", "if", "(", "receivers", "==", "null", ")", "{", "receivers", "=", "new", "LinkedList", "<", "ReceiverDescriptor", ">", "(", ")", ";", "this", ".", "receiverMap", ".", "put", "(", "eventClass", ",", "receivers", ")", ";", "}", "final", "ReceiverDescriptor", "rd", "=", "new", "ReceiverDescriptor", "(", ")", ";", "rd", ".", "receiverReference", "=", "new", "SoftReference", "<", "Object", ">", "(", "receiver", ")", ";", "rd", ".", "method", "=", "method", ";", "receivers", ".", "add", "(", "rd", ")", ";", "}" ]
Registers a receiver to an internal map. @param receiver @param method @param eventClass
[ "Registers", "a", "receiver", "to", "an", "internal", "map", "." ]
4d143093500cd2fb9767ebe8cd05ddda23e35613
https://github.com/micwin/ticino/blob/4d143093500cd2fb9767ebe8cd05ddda23e35613/events/src/main/java/net/micwin/ticino/events/EventScope.java#L201-L214
156,456
micwin/ticino
events/src/main/java/net/micwin/ticino/events/EventScope.java
EventScope.dispatch
private <Q extends T> Q dispatch(final Q event, boolean stopOnFirstException) { if (event == null) { throw new IllegalArgumentException("event is null"); } if (this.baseClass != null && !this.baseClass.isAssignableFrom(event.getClass())) { throw new IllegalArgumentException("event of type " + event.getClass().getName() + " not dispatchable over this event scope of base type '" + this.baseClass.getName() + "'"); } final Collection<ReceiverDescriptor> receivers = new TreeSet<ReceiverDescriptor>(new DispatchComparator()); this.collectReceiver(event.getClass(), receivers); // no receivers registered, so bye-bye if (receivers == null || receivers.size() < 1) { return event; } // when finding a garbage collected receiver, store here final List<ReceiverDescriptor> defunct = new LinkedList<ReceiverDescriptor>(); try { for (final ReceiverDescriptor receiverDescriptor : receivers) { final Object receiver = receiverDescriptor.receiverReference.get(); if (receiver == null) { defunct.add(receiverDescriptor); continue; } try { receiverDescriptor.method.setAccessible(true); receiverDescriptor.method.invoke(receiver, event); } catch (final Exception e) { if (stopOnFirstException) { // wrap non runtime exception and throw up throw new DispatchException(receiver, event, e); } } } } finally { // throw away gc'ed items receivers.removeAll(defunct); } return event; }
java
private <Q extends T> Q dispatch(final Q event, boolean stopOnFirstException) { if (event == null) { throw new IllegalArgumentException("event is null"); } if (this.baseClass != null && !this.baseClass.isAssignableFrom(event.getClass())) { throw new IllegalArgumentException("event of type " + event.getClass().getName() + " not dispatchable over this event scope of base type '" + this.baseClass.getName() + "'"); } final Collection<ReceiverDescriptor> receivers = new TreeSet<ReceiverDescriptor>(new DispatchComparator()); this.collectReceiver(event.getClass(), receivers); // no receivers registered, so bye-bye if (receivers == null || receivers.size() < 1) { return event; } // when finding a garbage collected receiver, store here final List<ReceiverDescriptor> defunct = new LinkedList<ReceiverDescriptor>(); try { for (final ReceiverDescriptor receiverDescriptor : receivers) { final Object receiver = receiverDescriptor.receiverReference.get(); if (receiver == null) { defunct.add(receiverDescriptor); continue; } try { receiverDescriptor.method.setAccessible(true); receiverDescriptor.method.invoke(receiver, event); } catch (final Exception e) { if (stopOnFirstException) { // wrap non runtime exception and throw up throw new DispatchException(receiver, event, e); } } } } finally { // throw away gc'ed items receivers.removeAll(defunct); } return event; }
[ "private", "<", "Q", "extends", "T", ">", "Q", "dispatch", "(", "final", "Q", "event", ",", "boolean", "stopOnFirstException", ")", "{", "if", "(", "event", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"event is null\"", ")", ";", "}", "if", "(", "this", ".", "baseClass", "!=", "null", "&&", "!", "this", ".", "baseClass", ".", "isAssignableFrom", "(", "event", ".", "getClass", "(", ")", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"event of type \"", "+", "event", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\" not dispatchable over this event scope of base type '\"", "+", "this", ".", "baseClass", ".", "getName", "(", ")", "+", "\"'\"", ")", ";", "}", "final", "Collection", "<", "ReceiverDescriptor", ">", "receivers", "=", "new", "TreeSet", "<", "ReceiverDescriptor", ">", "(", "new", "DispatchComparator", "(", ")", ")", ";", "this", ".", "collectReceiver", "(", "event", ".", "getClass", "(", ")", ",", "receivers", ")", ";", "// no receivers registered, so bye-bye", "if", "(", "receivers", "==", "null", "||", "receivers", ".", "size", "(", ")", "<", "1", ")", "{", "return", "event", ";", "}", "// when finding a garbage collected receiver, store here", "final", "List", "<", "ReceiverDescriptor", ">", "defunct", "=", "new", "LinkedList", "<", "ReceiverDescriptor", ">", "(", ")", ";", "try", "{", "for", "(", "final", "ReceiverDescriptor", "receiverDescriptor", ":", "receivers", ")", "{", "final", "Object", "receiver", "=", "receiverDescriptor", ".", "receiverReference", ".", "get", "(", ")", ";", "if", "(", "receiver", "==", "null", ")", "{", "defunct", ".", "add", "(", "receiverDescriptor", ")", ";", "continue", ";", "}", "try", "{", "receiverDescriptor", ".", "method", ".", "setAccessible", "(", "true", ")", ";", "receiverDescriptor", ".", "method", ".", "invoke", "(", "receiver", ",", "event", ")", ";", "}", "catch", "(", "final", "Exception", "e", ")", "{", "if", "(", "stopOnFirstException", ")", "{", "// wrap non runtime exception and throw up", "throw", "new", "DispatchException", "(", "receiver", ",", "event", ",", "e", ")", ";", "}", "}", "}", "}", "finally", "{", "// throw away gc'ed items", "receivers", ".", "removeAll", "(", "defunct", ")", ";", "}", "return", "event", ";", "}" ]
Dispatch an event to receivers synchronously. @param event The event object to dispatch. @param stopOnFirstException wether to wrap first exception that comes up in a {@link DispatchException} and then cancel execution. @throws DispatchException if stopOnFirstException == true, then first exception that comes up wrapped in {@link DispatchException}. @return the throws event for convenience in case of chaining and events also holding results.
[ "Dispatch", "an", "event", "to", "receivers", "synchronously", "." ]
4d143093500cd2fb9767ebe8cd05ddda23e35613
https://github.com/micwin/ticino/blob/4d143093500cd2fb9767ebe8cd05ddda23e35613/events/src/main/java/net/micwin/ticino/events/EventScope.java#L332-L379
156,457
micwin/ticino
events/src/main/java/net/micwin/ticino/events/EventScope.java
EventScope.dispatchAsynchronous
public synchronized <Q extends T> void dispatchAsynchronous(final Q event, final IPostProcessor<Q> pPostProcessor) { new Thread(new Runnable() { @Override public void run() { try { // delegate dispatch result pPostProcessor.done(dispatch(event)); } catch (DispatchException lEx) { // delegate exception handling as well pPostProcessor.done(lEx); } } }).start(); }
java
public synchronized <Q extends T> void dispatchAsynchronous(final Q event, final IPostProcessor<Q> pPostProcessor) { new Thread(new Runnable() { @Override public void run() { try { // delegate dispatch result pPostProcessor.done(dispatch(event)); } catch (DispatchException lEx) { // delegate exception handling as well pPostProcessor.done(lEx); } } }).start(); }
[ "public", "synchronized", "<", "Q", "extends", "T", ">", "void", "dispatchAsynchronous", "(", "final", "Q", "event", ",", "final", "IPostProcessor", "<", "Q", ">", "pPostProcessor", ")", "{", "new", "Thread", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "// delegate dispatch result", "pPostProcessor", ".", "done", "(", "dispatch", "(", "event", ")", ")", ";", "}", "catch", "(", "DispatchException", "lEx", ")", "{", "// delegate exception handling as well", "pPostProcessor", ".", "done", "(", "lEx", ")", ";", "}", "}", "}", ")", ".", "start", "(", ")", ";", "}" ]
Dispatch an event to receivers asynchronously. Does start a thread and then return immediately. @param event The event object to dispatch. @param pPostProcessor The postprocessor to call when the event doispatchment returns.
[ "Dispatch", "an", "event", "to", "receivers", "asynchronously", ".", "Does", "start", "a", "thread", "and", "then", "return", "immediately", "." ]
4d143093500cd2fb9767ebe8cd05ddda23e35613
https://github.com/micwin/ticino/blob/4d143093500cd2fb9767ebe8cd05ddda23e35613/events/src/main/java/net/micwin/ticino/events/EventScope.java#L391-L412
156,458
micwin/ticino
events/src/main/java/net/micwin/ticino/events/EventScope.java
EventScope.collectReceiver
private void collectReceiver(final Class<?> eventClass, final Collection<ReceiverDescriptor> receiverCollection) { if (this.receiverMap.get(eventClass) != null) { receiverCollection.addAll(this.receiverMap.get(eventClass)); } if (!eventClass.isInterface() && eventClass.getSuperclass() != Object.class) { this.collectReceiver(eventClass.getSuperclass(), receiverCollection); } for (final Class interfaceClass : eventClass.getInterfaces()) { this.collectReceiver(interfaceClass, receiverCollection); } }
java
private void collectReceiver(final Class<?> eventClass, final Collection<ReceiverDescriptor> receiverCollection) { if (this.receiverMap.get(eventClass) != null) { receiverCollection.addAll(this.receiverMap.get(eventClass)); } if (!eventClass.isInterface() && eventClass.getSuperclass() != Object.class) { this.collectReceiver(eventClass.getSuperclass(), receiverCollection); } for (final Class interfaceClass : eventClass.getInterfaces()) { this.collectReceiver(interfaceClass, receiverCollection); } }
[ "private", "void", "collectReceiver", "(", "final", "Class", "<", "?", ">", "eventClass", ",", "final", "Collection", "<", "ReceiverDescriptor", ">", "receiverCollection", ")", "{", "if", "(", "this", ".", "receiverMap", ".", "get", "(", "eventClass", ")", "!=", "null", ")", "{", "receiverCollection", ".", "addAll", "(", "this", ".", "receiverMap", ".", "get", "(", "eventClass", ")", ")", ";", "}", "if", "(", "!", "eventClass", ".", "isInterface", "(", ")", "&&", "eventClass", ".", "getSuperclass", "(", ")", "!=", "Object", ".", "class", ")", "{", "this", ".", "collectReceiver", "(", "eventClass", ".", "getSuperclass", "(", ")", ",", "receiverCollection", ")", ";", "}", "for", "(", "final", "Class", "interfaceClass", ":", "eventClass", ".", "getInterfaces", "(", ")", ")", "{", "this", ".", "collectReceiver", "(", "interfaceClass", ",", "receiverCollection", ")", ";", "}", "}" ]
collects receiver descriptors of super classes and interfaces. @param eventClass @param receiverCollection the collection receivers are put in.
[ "collects", "receiver", "descriptors", "of", "super", "classes", "and", "interfaces", "." ]
4d143093500cd2fb9767ebe8cd05ddda23e35613
https://github.com/micwin/ticino/blob/4d143093500cd2fb9767ebe8cd05ddda23e35613/events/src/main/java/net/micwin/ticino/events/EventScope.java#L421-L432
156,459
maestrano/maestrano-java
src/main/java/com/maestrano/net/MnoHttpClient.java
MnoHttpClient.getAuthenticatedClient
public static MnoHttpClient getAuthenticatedClient(String key, String secret, String contentType) { MnoHttpClient client = new MnoHttpClient(contentType); String authStr = key + ":" + secret; client.basicAuthHash = "Basic " + DatatypeConverter.printBase64Binary(authStr.getBytes()); return client; }
java
public static MnoHttpClient getAuthenticatedClient(String key, String secret, String contentType) { MnoHttpClient client = new MnoHttpClient(contentType); String authStr = key + ":" + secret; client.basicAuthHash = "Basic " + DatatypeConverter.printBase64Binary(authStr.getBytes()); return client; }
[ "public", "static", "MnoHttpClient", "getAuthenticatedClient", "(", "String", "key", ",", "String", "secret", ",", "String", "contentType", ")", "{", "MnoHttpClient", "client", "=", "new", "MnoHttpClient", "(", "contentType", ")", ";", "String", "authStr", "=", "key", "+", "\":\"", "+", "secret", ";", "client", ".", "basicAuthHash", "=", "\"Basic \"", "+", "DatatypeConverter", ".", "printBase64Binary", "(", "authStr", ".", "getBytes", "(", ")", ")", ";", "return", "client", ";", "}" ]
Return a client with HTTP Basic Authentication setup
[ "Return", "a", "client", "with", "HTTP", "Basic", "Authentication", "setup" ]
e71c6d3172d7645529d678d1cb3ea9e0a59de314
https://github.com/maestrano/maestrano-java/blob/e71c6d3172d7645529d678d1cb3ea9e0a59de314/src/main/java/com/maestrano/net/MnoHttpClient.java#L60-L66
156,460
maestrano/maestrano-java
src/main/java/com/maestrano/net/MnoHttpClient.java
MnoHttpClient.post
public String post(String url, String payload) throws AuthenticationException, ApiException { return performRequest(url, "POST", null, null, payload); }
java
public String post(String url, String payload) throws AuthenticationException, ApiException { return performRequest(url, "POST", null, null, payload); }
[ "public", "String", "post", "(", "String", "url", ",", "String", "payload", ")", "throws", "AuthenticationException", ",", "ApiException", "{", "return", "performRequest", "(", "url", ",", "\"POST\"", ",", "null", ",", "null", ",", "payload", ")", ";", "}" ]
Perform a POST request on the specified endpoint @param url @param header @param payload @return response body @throws ApiException @throws AuthenticationException
[ "Perform", "a", "POST", "request", "on", "the", "specified", "endpoint" ]
e71c6d3172d7645529d678d1cb3ea9e0a59de314
https://github.com/maestrano/maestrano-java/blob/e71c6d3172d7645529d678d1cb3ea9e0a59de314/src/main/java/com/maestrano/net/MnoHttpClient.java#L117-L119
156,461
maestrano/maestrano-java
src/main/java/com/maestrano/net/MnoHttpClient.java
MnoHttpClient.openConnection
protected HttpURLConnection openConnection(String url, Map<String, String> header) throws IOException { // Initialize connection URL urlObj = null; HttpURLConnection conn = null; int redirectCount = 0; boolean redirect = true; while (redirect) { if (redirectCount > 10) { throw new ProtocolException("Too many redirects: " + redirectCount); } if (conn == null) { urlObj = new URL(url); } else { // get redirect url from "location" header field urlObj = new URL(conn.getHeaderField("Location")); } // open the new connection again conn = (HttpURLConnection) urlObj.openConnection(); conn.setRequestMethod(header.get("method")); conn.setInstanceFollowRedirects(true); // Set output if PUT or POST if (conn.getRequestMethod() == "POST" || conn.getRequestMethod() == "PUT") { conn.setDoOutput(true); } // Set request header for (Map.Entry<String, String> headerAttr : header.entrySet()) { conn.addRequestProperty(headerAttr.getKey(), headerAttr.getValue()); } // Check if redirect redirect = false; if (conn.getRequestMethod() == "GET") { int status = conn.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; redirectCount++; } } } return conn; }
java
protected HttpURLConnection openConnection(String url, Map<String, String> header) throws IOException { // Initialize connection URL urlObj = null; HttpURLConnection conn = null; int redirectCount = 0; boolean redirect = true; while (redirect) { if (redirectCount > 10) { throw new ProtocolException("Too many redirects: " + redirectCount); } if (conn == null) { urlObj = new URL(url); } else { // get redirect url from "location" header field urlObj = new URL(conn.getHeaderField("Location")); } // open the new connection again conn = (HttpURLConnection) urlObj.openConnection(); conn.setRequestMethod(header.get("method")); conn.setInstanceFollowRedirects(true); // Set output if PUT or POST if (conn.getRequestMethod() == "POST" || conn.getRequestMethod() == "PUT") { conn.setDoOutput(true); } // Set request header for (Map.Entry<String, String> headerAttr : header.entrySet()) { conn.addRequestProperty(headerAttr.getKey(), headerAttr.getValue()); } // Check if redirect redirect = false; if (conn.getRequestMethod() == "GET") { int status = conn.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; redirectCount++; } } } return conn; }
[ "protected", "HttpURLConnection", "openConnection", "(", "String", "url", ",", "Map", "<", "String", ",", "String", ">", "header", ")", "throws", "IOException", "{", "// Initialize connection", "URL", "urlObj", "=", "null", ";", "HttpURLConnection", "conn", "=", "null", ";", "int", "redirectCount", "=", "0", ";", "boolean", "redirect", "=", "true", ";", "while", "(", "redirect", ")", "{", "if", "(", "redirectCount", ">", "10", ")", "{", "throw", "new", "ProtocolException", "(", "\"Too many redirects: \"", "+", "redirectCount", ")", ";", "}", "if", "(", "conn", "==", "null", ")", "{", "urlObj", "=", "new", "URL", "(", "url", ")", ";", "}", "else", "{", "// get redirect url from \"location\" header field", "urlObj", "=", "new", "URL", "(", "conn", ".", "getHeaderField", "(", "\"Location\"", ")", ")", ";", "}", "// open the new connection again", "conn", "=", "(", "HttpURLConnection", ")", "urlObj", ".", "openConnection", "(", ")", ";", "conn", ".", "setRequestMethod", "(", "header", ".", "get", "(", "\"method\"", ")", ")", ";", "conn", ".", "setInstanceFollowRedirects", "(", "true", ")", ";", "// Set output if PUT or POST", "if", "(", "conn", ".", "getRequestMethod", "(", ")", "==", "\"POST\"", "||", "conn", ".", "getRequestMethod", "(", ")", "==", "\"PUT\"", ")", "{", "conn", ".", "setDoOutput", "(", "true", ")", ";", "}", "// Set request header", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "headerAttr", ":", "header", ".", "entrySet", "(", ")", ")", "{", "conn", ".", "addRequestProperty", "(", "headerAttr", ".", "getKey", "(", ")", ",", "headerAttr", ".", "getValue", "(", ")", ")", ";", "}", "// Check if redirect", "redirect", "=", "false", ";", "if", "(", "conn", ".", "getRequestMethod", "(", ")", "==", "\"GET\"", ")", "{", "int", "status", "=", "conn", ".", "getResponseCode", "(", ")", ";", "if", "(", "status", "!=", "HttpURLConnection", ".", "HTTP_OK", ")", "{", "if", "(", "status", "==", "HttpURLConnection", ".", "HTTP_MOVED_TEMP", "||", "status", "==", "HttpURLConnection", ".", "HTTP_MOVED_PERM", "||", "status", "==", "HttpURLConnection", ".", "HTTP_SEE_OTHER", ")", "redirect", "=", "true", ";", "redirectCount", "++", ";", "}", "}", "}", "return", "conn", ";", "}" ]
Open a connection and follow the redirect @param String url @param header contain @return HttpURLConnection connection @throws IOException
[ "Open", "a", "connection", "and", "follow", "the", "redirect" ]
e71c6d3172d7645529d678d1cb3ea9e0a59de314
https://github.com/maestrano/maestrano-java/blob/e71c6d3172d7645529d678d1cb3ea9e0a59de314/src/main/java/com/maestrano/net/MnoHttpClient.java#L302-L349
156,462
micwin/ticino
static/src/main/java/net/micwin/ticino/events/PublicScopes.java
PublicScopes.get
@SuppressWarnings("unchecked") public static <T> EventScope<T> get (final Class<T> pEventType) { if (pEventType == Object.class) { return null; } EventScope<T> lResult = (EventScope<T>) sScopes.get (pEventType); if (lResult != null) { return lResult; } for (final Class<?> lInterface : pEventType.getInterfaces ()) { lResult = (EventScope<T>) sScopes.get (pEventType); if (lResult != null) { return lResult; } } // still here - dive into super class return (EventScope<T>) get (pEventType.getSuperclass ()); }
java
@SuppressWarnings("unchecked") public static <T> EventScope<T> get (final Class<T> pEventType) { if (pEventType == Object.class) { return null; } EventScope<T> lResult = (EventScope<T>) sScopes.get (pEventType); if (lResult != null) { return lResult; } for (final Class<?> lInterface : pEventType.getInterfaces ()) { lResult = (EventScope<T>) sScopes.get (pEventType); if (lResult != null) { return lResult; } } // still here - dive into super class return (EventScope<T>) get (pEventType.getSuperclass ()); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "EventScope", "<", "T", ">", "get", "(", "final", "Class", "<", "T", ">", "pEventType", ")", "{", "if", "(", "pEventType", "==", "Object", ".", "class", ")", "{", "return", "null", ";", "}", "EventScope", "<", "T", ">", "lResult", "=", "(", "EventScope", "<", "T", ">", ")", "sScopes", ".", "get", "(", "pEventType", ")", ";", "if", "(", "lResult", "!=", "null", ")", "{", "return", "lResult", ";", "}", "for", "(", "final", "Class", "<", "?", ">", "lInterface", ":", "pEventType", ".", "getInterfaces", "(", ")", ")", "{", "lResult", "=", "(", "EventScope", "<", "T", ">", ")", "sScopes", ".", "get", "(", "pEventType", ")", ";", "if", "(", "lResult", "!=", "null", ")", "{", "return", "lResult", ";", "}", "}", "// still here - dive into super class", "return", "(", "EventScope", "<", "T", ">", ")", "get", "(", "pEventType", ".", "getSuperclass", "(", ")", ")", ";", "}" ]
Returns the event scope bound to that event type. This is an expensive operation, so make sure to only call as seldom as possible. @param pEventType @return
[ "Returns", "the", "event", "scope", "bound", "to", "that", "event", "type", ".", "This", "is", "an", "expensive", "operation", "so", "make", "sure", "to", "only", "call", "as", "seldom", "as", "possible", "." ]
4d143093500cd2fb9767ebe8cd05ddda23e35613
https://github.com/micwin/ticino/blob/4d143093500cd2fb9767ebe8cd05ddda23e35613/static/src/main/java/net/micwin/ticino/events/PublicScopes.java#L57-L83
156,463
javagl/ND
nd-iteration/src/main/java/de/javagl/nd/iteration/tuples/i/VonNeumannIntTupleIterator.java
VonNeumannIntTupleIterator.increment
private boolean increment(int index) { if (index == -1) { return false; } int value = current.get(index); if (value < max.get(index)) { current.set(index, value+1); updateMinMax(index+1); return true; } boolean hasNext = increment(index-1); if (hasNext) { current.set(index, min.get(index)); } return hasNext; }
java
private boolean increment(int index) { if (index == -1) { return false; } int value = current.get(index); if (value < max.get(index)) { current.set(index, value+1); updateMinMax(index+1); return true; } boolean hasNext = increment(index-1); if (hasNext) { current.set(index, min.get(index)); } return hasNext; }
[ "private", "boolean", "increment", "(", "int", "index", ")", "{", "if", "(", "index", "==", "-", "1", ")", "{", "return", "false", ";", "}", "int", "value", "=", "current", ".", "get", "(", "index", ")", ";", "if", "(", "value", "<", "max", ".", "get", "(", "index", ")", ")", "{", "current", ".", "set", "(", "index", ",", "value", "+", "1", ")", ";", "updateMinMax", "(", "index", "+", "1", ")", ";", "return", "true", ";", "}", "boolean", "hasNext", "=", "increment", "(", "index", "-", "1", ")", ";", "if", "(", "hasNext", ")", "{", "current", ".", "set", "(", "index", ",", "min", ".", "get", "(", "index", ")", ")", ";", "}", "return", "hasNext", ";", "}" ]
Increment the current value starting at the given index, and return whether this was possible @param index The index @return Whether the value could be incremented
[ "Increment", "the", "current", "value", "starting", "at", "the", "given", "index", "and", "return", "whether", "this", "was", "possible" ]
bcb655aaf5fc88af6194f73a27cca079186ff559
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-iteration/src/main/java/de/javagl/nd/iteration/tuples/i/VonNeumannIntTupleIterator.java#L129-L148
156,464
soulwarelabs/jCommons-API
src/main/java/com/soulwarelabs/jcommons/data/Credentials.java
Credentials.copy
public static Credentials copy(Credentials credentials) { if (credentials == null) { return null; } return new Credentials(credentials.login, credentials.password); }
java
public static Credentials copy(Credentials credentials) { if (credentials == null) { return null; } return new Credentials(credentials.login, credentials.password); }
[ "public", "static", "Credentials", "copy", "(", "Credentials", "credentials", ")", "{", "if", "(", "credentials", "==", "null", ")", "{", "return", "null", ";", "}", "return", "new", "Credentials", "(", "credentials", ".", "login", ",", "credentials", ".", "password", ")", ";", "}" ]
Creates a new copy of authentication pair. @param credentials original authentication pair (optional). @return copied authentication pair (optional). @since v1.1.0
[ "Creates", "a", "new", "copy", "of", "authentication", "pair", "." ]
57795ae28aea144e68502149506ec99dd67f0c67
https://github.com/soulwarelabs/jCommons-API/blob/57795ae28aea144e68502149506ec99dd67f0c67/src/main/java/com/soulwarelabs/jcommons/data/Credentials.java#L53-L58
156,465
CubeEngine/Dirigent
src/main/java/org/cubeengine/dirigent/formatter/NumberFormatter.java
NumberFormatter.parseNumberToString
protected String parseNumberToString(Number number, Context context, Arguments args) { final NumberFormat numberFormat = parseFormatter(context, args); final Currency currency = context.get(Contexts.CURRENCY); if (currency != null) { numberFormat.setCurrency(currency); } return numberFormat.format(number); }
java
protected String parseNumberToString(Number number, Context context, Arguments args) { final NumberFormat numberFormat = parseFormatter(context, args); final Currency currency = context.get(Contexts.CURRENCY); if (currency != null) { numberFormat.setCurrency(currency); } return numberFormat.format(number); }
[ "protected", "String", "parseNumberToString", "(", "Number", "number", ",", "Context", "context", ",", "Arguments", "args", ")", "{", "final", "NumberFormat", "numberFormat", "=", "parseFormatter", "(", "context", ",", "args", ")", ";", "final", "Currency", "currency", "=", "context", ".", "get", "(", "Contexts", ".", "CURRENCY", ")", ";", "if", "(", "currency", "!=", "null", ")", "{", "numberFormat", ".", "setCurrency", "(", "currency", ")", ";", "}", "return", "numberFormat", ".", "format", "(", "number", ")", ";", "}" ]
Parses the given number to a string depending on the context. @param number The number to parse. @param context The context to use. @param args The arguments of the macro. @return The number as a string.
[ "Parses", "the", "given", "number", "to", "a", "string", "depending", "on", "the", "context", "." ]
68587a8202754a6a6b629cc15e14c516806badaa
https://github.com/CubeEngine/Dirigent/blob/68587a8202754a6a6b629cc15e14c516806badaa/src/main/java/org/cubeengine/dirigent/formatter/NumberFormatter.java#L113-L124
156,466
wg/scrypt
src/main/java/com/lambdaworks/crypto/SCryptUtil.java
SCryptUtil.check
public static boolean check(String passwd, String hashed) { try { String[] parts = hashed.split("\\$"); if (parts.length != 5 || !parts[1].equals("s0")) { throw new IllegalArgumentException("Invalid hashed value"); } long params = Long.parseLong(parts[2], 16); byte[] salt = decode(parts[3].toCharArray()); byte[] derived0 = decode(parts[4].toCharArray()); int N = (int) Math.pow(2, params >> 16 & 0xffff); int r = (int) params >> 8 & 0xff; int p = (int) params & 0xff; byte[] derived1 = SCrypt.scrypt(passwd.getBytes("UTF-8"), salt, N, r, p, 32); if (derived0.length != derived1.length) return false; int result = 0; for (int i = 0; i < derived0.length; i++) { result |= derived0[i] ^ derived1[i]; } return result == 0; } catch (UnsupportedEncodingException e) { throw new IllegalStateException("JVM doesn't support UTF-8?"); } catch (GeneralSecurityException e) { throw new IllegalStateException("JVM doesn't support SHA1PRNG or HMAC_SHA256?"); } }
java
public static boolean check(String passwd, String hashed) { try { String[] parts = hashed.split("\\$"); if (parts.length != 5 || !parts[1].equals("s0")) { throw new IllegalArgumentException("Invalid hashed value"); } long params = Long.parseLong(parts[2], 16); byte[] salt = decode(parts[3].toCharArray()); byte[] derived0 = decode(parts[4].toCharArray()); int N = (int) Math.pow(2, params >> 16 & 0xffff); int r = (int) params >> 8 & 0xff; int p = (int) params & 0xff; byte[] derived1 = SCrypt.scrypt(passwd.getBytes("UTF-8"), salt, N, r, p, 32); if (derived0.length != derived1.length) return false; int result = 0; for (int i = 0; i < derived0.length; i++) { result |= derived0[i] ^ derived1[i]; } return result == 0; } catch (UnsupportedEncodingException e) { throw new IllegalStateException("JVM doesn't support UTF-8?"); } catch (GeneralSecurityException e) { throw new IllegalStateException("JVM doesn't support SHA1PRNG or HMAC_SHA256?"); } }
[ "public", "static", "boolean", "check", "(", "String", "passwd", ",", "String", "hashed", ")", "{", "try", "{", "String", "[", "]", "parts", "=", "hashed", ".", "split", "(", "\"\\\\$\"", ")", ";", "if", "(", "parts", ".", "length", "!=", "5", "||", "!", "parts", "[", "1", "]", ".", "equals", "(", "\"s0\"", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid hashed value\"", ")", ";", "}", "long", "params", "=", "Long", ".", "parseLong", "(", "parts", "[", "2", "]", ",", "16", ")", ";", "byte", "[", "]", "salt", "=", "decode", "(", "parts", "[", "3", "]", ".", "toCharArray", "(", ")", ")", ";", "byte", "[", "]", "derived0", "=", "decode", "(", "parts", "[", "4", "]", ".", "toCharArray", "(", ")", ")", ";", "int", "N", "=", "(", "int", ")", "Math", ".", "pow", "(", "2", ",", "params", ">>", "16", "&", "0xffff", ")", ";", "int", "r", "=", "(", "int", ")", "params", ">>", "8", "&", "0xff", ";", "int", "p", "=", "(", "int", ")", "params", "&", "0xff", ";", "byte", "[", "]", "derived1", "=", "SCrypt", ".", "scrypt", "(", "passwd", ".", "getBytes", "(", "\"UTF-8\"", ")", ",", "salt", ",", "N", ",", "r", ",", "p", ",", "32", ")", ";", "if", "(", "derived0", ".", "length", "!=", "derived1", ".", "length", ")", "return", "false", ";", "int", "result", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "derived0", ".", "length", ";", "i", "++", ")", "{", "result", "|=", "derived0", "[", "i", "]", "^", "derived1", "[", "i", "]", ";", "}", "return", "result", "==", "0", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"JVM doesn't support UTF-8?\"", ")", ";", "}", "catch", "(", "GeneralSecurityException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"JVM doesn't support SHA1PRNG or HMAC_SHA256?\"", ")", ";", "}", "}" ]
Compare the supplied plaintext password to a hashed password. @param passwd Plaintext password. @param hashed scrypt hashed password. @return true if passwd matches hashed value.
[ "Compare", "the", "supplied", "plaintext", "password", "to", "a", "hashed", "password", "." ]
0675236370458e819ee21e4427c5f7f3f9485d33
https://github.com/wg/scrypt/blob/0675236370458e819ee21e4427c5f7f3f9485d33/src/main/java/com/lambdaworks/crypto/SCryptUtil.java#L72-L102
156,467
wg/scrypt
src/main/java/com/lambdaworks/jni/Platform.java
Platform.detect
public static Platform detect() throws UnsupportedPlatformException { String osArch = getProperty("os.arch"); String osName = getProperty("os.name"); for (Arch arch : Arch.values()) { if (arch.pattern.matcher(osArch).matches()) { for (OS os : OS.values()) { if (os.pattern.matcher(osName).matches()) { return new Platform(arch, os); } } } } String msg = String.format("Unsupported platform %s %s", osArch, osName); throw new UnsupportedPlatformException(msg); }
java
public static Platform detect() throws UnsupportedPlatformException { String osArch = getProperty("os.arch"); String osName = getProperty("os.name"); for (Arch arch : Arch.values()) { if (arch.pattern.matcher(osArch).matches()) { for (OS os : OS.values()) { if (os.pattern.matcher(osName).matches()) { return new Platform(arch, os); } } } } String msg = String.format("Unsupported platform %s %s", osArch, osName); throw new UnsupportedPlatformException(msg); }
[ "public", "static", "Platform", "detect", "(", ")", "throws", "UnsupportedPlatformException", "{", "String", "osArch", "=", "getProperty", "(", "\"os.arch\"", ")", ";", "String", "osName", "=", "getProperty", "(", "\"os.name\"", ")", ";", "for", "(", "Arch", "arch", ":", "Arch", ".", "values", "(", ")", ")", "{", "if", "(", "arch", ".", "pattern", ".", "matcher", "(", "osArch", ")", ".", "matches", "(", ")", ")", "{", "for", "(", "OS", "os", ":", "OS", ".", "values", "(", ")", ")", "{", "if", "(", "os", ".", "pattern", ".", "matcher", "(", "osName", ")", ".", "matches", "(", ")", ")", "{", "return", "new", "Platform", "(", "arch", ",", "os", ")", ";", "}", "}", "}", "}", "String", "msg", "=", "String", ".", "format", "(", "\"Unsupported platform %s %s\"", ",", "osArch", ",", "osName", ")", ";", "throw", "new", "UnsupportedPlatformException", "(", "msg", ")", ";", "}" ]
Attempt to detect the current platform. @return The current platform. @throws UnsupportedPlatformException if the platform cannot be detected.
[ "Attempt", "to", "detect", "the", "current", "platform", "." ]
0675236370458e819ee21e4427c5f7f3f9485d33
https://github.com/wg/scrypt/blob/0675236370458e819ee21e4427c5f7f3f9485d33/src/main/java/com/lambdaworks/jni/Platform.java#L56-L72
156,468
groovy/groovy-core
src/main/org/codehaus/groovy/ast/ASTNode.java
ASTNode.getNodeMetaData
public <T> T getNodeMetaData(Object key) { if (metaDataMap == null) { return (T) null; } return (T) metaDataMap.get(key); }
java
public <T> T getNodeMetaData(Object key) { if (metaDataMap == null) { return (T) null; } return (T) metaDataMap.get(key); }
[ "public", "<", "T", ">", "T", "getNodeMetaData", "(", "Object", "key", ")", "{", "if", "(", "metaDataMap", "==", "null", ")", "{", "return", "(", "T", ")", "null", ";", "}", "return", "(", "T", ")", "metaDataMap", ".", "get", "(", "key", ")", ";", "}" ]
Gets the node meta data. @param key - the meta data key @return the node meta data value for this key
[ "Gets", "the", "node", "meta", "data", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/ast/ASTNode.java#L119-L124
156,469
groovy/groovy-core
src/main/org/codehaus/groovy/ast/ASTNode.java
ASTNode.copyNodeMetaData
public void copyNodeMetaData(ASTNode other) { if (other.metaDataMap == null) { return; } if (metaDataMap == null) { metaDataMap = new ListHashMap(); } metaDataMap.putAll(other.metaDataMap); }
java
public void copyNodeMetaData(ASTNode other) { if (other.metaDataMap == null) { return; } if (metaDataMap == null) { metaDataMap = new ListHashMap(); } metaDataMap.putAll(other.metaDataMap); }
[ "public", "void", "copyNodeMetaData", "(", "ASTNode", "other", ")", "{", "if", "(", "other", ".", "metaDataMap", "==", "null", ")", "{", "return", ";", "}", "if", "(", "metaDataMap", "==", "null", ")", "{", "metaDataMap", "=", "new", "ListHashMap", "(", ")", ";", "}", "metaDataMap", ".", "putAll", "(", "other", ".", "metaDataMap", ")", ";", "}" ]
Copies all node meta data from the other node to this one @param other - the other node
[ "Copies", "all", "node", "meta", "data", "from", "the", "other", "node", "to", "this", "one" ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/ast/ASTNode.java#L130-L138
156,470
groovy/groovy-core
src/main/org/codehaus/groovy/ast/ASTNode.java
ASTNode.setNodeMetaData
public void setNodeMetaData(Object key, Object value) { if (key==null) throw new GroovyBugError("Tried to set meta data with null key on "+this+"."); if (metaDataMap == null) { metaDataMap = new ListHashMap(); } Object old = metaDataMap.put(key,value); if (old!=null) throw new GroovyBugError("Tried to overwrite existing meta data "+this+"."); }
java
public void setNodeMetaData(Object key, Object value) { if (key==null) throw new GroovyBugError("Tried to set meta data with null key on "+this+"."); if (metaDataMap == null) { metaDataMap = new ListHashMap(); } Object old = metaDataMap.put(key,value); if (old!=null) throw new GroovyBugError("Tried to overwrite existing meta data "+this+"."); }
[ "public", "void", "setNodeMetaData", "(", "Object", "key", ",", "Object", "value", ")", "{", "if", "(", "key", "==", "null", ")", "throw", "new", "GroovyBugError", "(", "\"Tried to set meta data with null key on \"", "+", "this", "+", "\".\"", ")", ";", "if", "(", "metaDataMap", "==", "null", ")", "{", "metaDataMap", "=", "new", "ListHashMap", "(", ")", ";", "}", "Object", "old", "=", "metaDataMap", ".", "put", "(", "key", ",", "value", ")", ";", "if", "(", "old", "!=", "null", ")", "throw", "new", "GroovyBugError", "(", "\"Tried to overwrite existing meta data \"", "+", "this", "+", "\".\"", ")", ";", "}" ]
Sets the node meta data. @param key - the meta data key @param value - the meta data value @throws GroovyBugError if key is null or there is already meta data under that key
[ "Sets", "the", "node", "meta", "data", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/ast/ASTNode.java#L148-L155
156,471
groovy/groovy-core
src/main/org/codehaus/groovy/ast/ASTNode.java
ASTNode.putNodeMetaData
public Object putNodeMetaData(Object key, Object value) { if (key == null) throw new GroovyBugError("Tried to set meta data with null key on " + this + "."); if (metaDataMap == null) { metaDataMap = new ListHashMap(); } return metaDataMap.put(key, value); }
java
public Object putNodeMetaData(Object key, Object value) { if (key == null) throw new GroovyBugError("Tried to set meta data with null key on " + this + "."); if (metaDataMap == null) { metaDataMap = new ListHashMap(); } return metaDataMap.put(key, value); }
[ "public", "Object", "putNodeMetaData", "(", "Object", "key", ",", "Object", "value", ")", "{", "if", "(", "key", "==", "null", ")", "throw", "new", "GroovyBugError", "(", "\"Tried to set meta data with null key on \"", "+", "this", "+", "\".\"", ")", ";", "if", "(", "metaDataMap", "==", "null", ")", "{", "metaDataMap", "=", "new", "ListHashMap", "(", ")", ";", "}", "return", "metaDataMap", ".", "put", "(", "key", ",", "value", ")", ";", "}" ]
Sets the node meta data but allows overwriting values. @param key - the meta data key @param value - the meta data value @return the old node meta data value for this key @throws GroovyBugError if key is null
[ "Sets", "the", "node", "meta", "data", "but", "allows", "overwriting", "values", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/ast/ASTNode.java#L165-L171
156,472
groovy/groovy-core
src/main/org/codehaus/groovy/ast/ASTNode.java
ASTNode.removeNodeMetaData
public void removeNodeMetaData(Object key) { if (key==null) throw new GroovyBugError("Tried to remove meta data with null key "+this+"."); if (metaDataMap == null) { return; } metaDataMap.remove(key); }
java
public void removeNodeMetaData(Object key) { if (key==null) throw new GroovyBugError("Tried to remove meta data with null key "+this+"."); if (metaDataMap == null) { return; } metaDataMap.remove(key); }
[ "public", "void", "removeNodeMetaData", "(", "Object", "key", ")", "{", "if", "(", "key", "==", "null", ")", "throw", "new", "GroovyBugError", "(", "\"Tried to remove meta data with null key \"", "+", "this", "+", "\".\"", ")", ";", "if", "(", "metaDataMap", "==", "null", ")", "{", "return", ";", "}", "metaDataMap", ".", "remove", "(", "key", ")", ";", "}" ]
Removes a node meta data entry. @param key - the meta data key @throws GroovyBugError if the key is null
[ "Removes", "a", "node", "meta", "data", "entry", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/ast/ASTNode.java#L179-L185
156,473
groovy/groovy-core
src/main/groovy/lang/IntRange.java
IntRange.subListBorders
public RangeInfo subListBorders(int size) { if (inclusive == null) throw new IllegalStateException("Should not call subListBorders on a non-inclusive aware IntRange"); int tempFrom = from; if (tempFrom < 0) { tempFrom += size; } int tempTo = to; if (tempTo < 0) { tempTo += size; } if (tempFrom > tempTo) { return new RangeInfo(inclusive ? tempTo : tempTo + 1, tempFrom + 1, true); } return new RangeInfo(tempFrom, inclusive ? tempTo + 1 : tempTo, false); }
java
public RangeInfo subListBorders(int size) { if (inclusive == null) throw new IllegalStateException("Should not call subListBorders on a non-inclusive aware IntRange"); int tempFrom = from; if (tempFrom < 0) { tempFrom += size; } int tempTo = to; if (tempTo < 0) { tempTo += size; } if (tempFrom > tempTo) { return new RangeInfo(inclusive ? tempTo : tempTo + 1, tempFrom + 1, true); } return new RangeInfo(tempFrom, inclusive ? tempTo + 1 : tempTo, false); }
[ "public", "RangeInfo", "subListBorders", "(", "int", "size", ")", "{", "if", "(", "inclusive", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "\"Should not call subListBorders on a non-inclusive aware IntRange\"", ")", ";", "int", "tempFrom", "=", "from", ";", "if", "(", "tempFrom", "<", "0", ")", "{", "tempFrom", "+=", "size", ";", "}", "int", "tempTo", "=", "to", ";", "if", "(", "tempTo", "<", "0", ")", "{", "tempTo", "+=", "size", ";", "}", "if", "(", "tempFrom", ">", "tempTo", ")", "{", "return", "new", "RangeInfo", "(", "inclusive", "?", "tempTo", ":", "tempTo", "+", "1", ",", "tempFrom", "+", "1", ",", "true", ")", ";", "}", "return", "new", "RangeInfo", "(", "tempFrom", ",", "inclusive", "?", "tempTo", "+", "1", ":", "tempTo", ",", "false", ")", ";", "}" ]
A method for determining from and to information when using this IntRange to index an aggregate object of the specified size. Normally only used internally within Groovy but useful if adding range indexing support for your own aggregates. @param size the size of the aggregate being indexed @return the calculated range information (with 1 added to the to value, ready for providing to subList
[ "A", "method", "for", "determining", "from", "and", "to", "information", "when", "using", "this", "IntRange", "to", "index", "an", "aggregate", "object", "of", "the", "specified", "size", ".", "Normally", "only", "used", "internally", "within", "Groovy", "but", "useful", "if", "adding", "range", "indexing", "support", "for", "your", "own", "aggregates", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/groovy/lang/IntRange.java#L197-L211
156,474
groovy/groovy-core
src/main/groovy/beans/BindableASTTransformation.java
BindableASTTransformation.createSetterMethod
protected void createSetterMethod(ClassNode declaringClass, PropertyNode propertyNode, String setterName, Statement setterBlock) { MethodNode setter = new MethodNode( setterName, propertyNode.getModifiers(), ClassHelper.VOID_TYPE, params(param(propertyNode.getType(), "value")), ClassNode.EMPTY_ARRAY, setterBlock); setter.setSynthetic(true); // add it to the class declaringClass.addMethod(setter); }
java
protected void createSetterMethod(ClassNode declaringClass, PropertyNode propertyNode, String setterName, Statement setterBlock) { MethodNode setter = new MethodNode( setterName, propertyNode.getModifiers(), ClassHelper.VOID_TYPE, params(param(propertyNode.getType(), "value")), ClassNode.EMPTY_ARRAY, setterBlock); setter.setSynthetic(true); // add it to the class declaringClass.addMethod(setter); }
[ "protected", "void", "createSetterMethod", "(", "ClassNode", "declaringClass", ",", "PropertyNode", "propertyNode", ",", "String", "setterName", ",", "Statement", "setterBlock", ")", "{", "MethodNode", "setter", "=", "new", "MethodNode", "(", "setterName", ",", "propertyNode", ".", "getModifiers", "(", ")", ",", "ClassHelper", ".", "VOID_TYPE", ",", "params", "(", "param", "(", "propertyNode", ".", "getType", "(", ")", ",", "\"value\"", ")", ")", ",", "ClassNode", ".", "EMPTY_ARRAY", ",", "setterBlock", ")", ";", "setter", ".", "setSynthetic", "(", "true", ")", ";", "// add it to the class\r", "declaringClass", ".", "addMethod", "(", "setter", ")", ";", "}" ]
Creates a setter method with the given body. @param declaringClass the class to which we will add the setter @param propertyNode the field to back the setter @param setterName the name of the setter @param setterBlock the statement representing the setter block
[ "Creates", "a", "setter", "method", "with", "the", "given", "body", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/groovy/beans/BindableASTTransformation.java#L247-L258
156,475
groovy/groovy-core
src/main/org/codehaus/groovy/control/CompilationUnit.java
CompilationUnit.applyToPrimaryClassNodes
public void applyToPrimaryClassNodes(PrimaryClassNodeOperation body) throws CompilationFailedException { Iterator classNodes = getPrimaryClassNodes(body.needSortedInput()).iterator(); while (classNodes.hasNext()) { SourceUnit context = null; try { ClassNode classNode = (ClassNode) classNodes.next(); context = classNode.getModule().getContext(); if (context == null || context.phase < phase || (context.phase == phase && !context.phaseComplete)) { int offset = 1; Iterator<InnerClassNode> iterator = classNode.getInnerClasses(); while (iterator.hasNext()) { iterator.next(); offset++; } body.call(context, new GeneratorContext(this.ast, offset), classNode); } } catch (CompilationFailedException e) { // fall through, getErrorReporter().failIfErrors() will trigger } catch (NullPointerException npe) { GroovyBugError gbe = new GroovyBugError("unexpected NullpointerException", npe); changeBugText(gbe, context); throw gbe; } catch (GroovyBugError e) { changeBugText(e, context); throw e; } catch (NoClassDefFoundError e) { // effort to get more logging in case a dependency of a class is loaded // although it shouldn't have convertUncaughtExceptionToCompilationError(e); } catch (Exception e) { convertUncaughtExceptionToCompilationError(e); } } getErrorCollector().failIfErrors(); }
java
public void applyToPrimaryClassNodes(PrimaryClassNodeOperation body) throws CompilationFailedException { Iterator classNodes = getPrimaryClassNodes(body.needSortedInput()).iterator(); while (classNodes.hasNext()) { SourceUnit context = null; try { ClassNode classNode = (ClassNode) classNodes.next(); context = classNode.getModule().getContext(); if (context == null || context.phase < phase || (context.phase == phase && !context.phaseComplete)) { int offset = 1; Iterator<InnerClassNode> iterator = classNode.getInnerClasses(); while (iterator.hasNext()) { iterator.next(); offset++; } body.call(context, new GeneratorContext(this.ast, offset), classNode); } } catch (CompilationFailedException e) { // fall through, getErrorReporter().failIfErrors() will trigger } catch (NullPointerException npe) { GroovyBugError gbe = new GroovyBugError("unexpected NullpointerException", npe); changeBugText(gbe, context); throw gbe; } catch (GroovyBugError e) { changeBugText(e, context); throw e; } catch (NoClassDefFoundError e) { // effort to get more logging in case a dependency of a class is loaded // although it shouldn't have convertUncaughtExceptionToCompilationError(e); } catch (Exception e) { convertUncaughtExceptionToCompilationError(e); } } getErrorCollector().failIfErrors(); }
[ "public", "void", "applyToPrimaryClassNodes", "(", "PrimaryClassNodeOperation", "body", ")", "throws", "CompilationFailedException", "{", "Iterator", "classNodes", "=", "getPrimaryClassNodes", "(", "body", ".", "needSortedInput", "(", ")", ")", ".", "iterator", "(", ")", ";", "while", "(", "classNodes", ".", "hasNext", "(", ")", ")", "{", "SourceUnit", "context", "=", "null", ";", "try", "{", "ClassNode", "classNode", "=", "(", "ClassNode", ")", "classNodes", ".", "next", "(", ")", ";", "context", "=", "classNode", ".", "getModule", "(", ")", ".", "getContext", "(", ")", ";", "if", "(", "context", "==", "null", "||", "context", ".", "phase", "<", "phase", "||", "(", "context", ".", "phase", "==", "phase", "&&", "!", "context", ".", "phaseComplete", ")", ")", "{", "int", "offset", "=", "1", ";", "Iterator", "<", "InnerClassNode", ">", "iterator", "=", "classNode", ".", "getInnerClasses", "(", ")", ";", "while", "(", "iterator", ".", "hasNext", "(", ")", ")", "{", "iterator", ".", "next", "(", ")", ";", "offset", "++", ";", "}", "body", ".", "call", "(", "context", ",", "new", "GeneratorContext", "(", "this", ".", "ast", ",", "offset", ")", ",", "classNode", ")", ";", "}", "}", "catch", "(", "CompilationFailedException", "e", ")", "{", "// fall through, getErrorReporter().failIfErrors() will trigger", "}", "catch", "(", "NullPointerException", "npe", ")", "{", "GroovyBugError", "gbe", "=", "new", "GroovyBugError", "(", "\"unexpected NullpointerException\"", ",", "npe", ")", ";", "changeBugText", "(", "gbe", ",", "context", ")", ";", "throw", "gbe", ";", "}", "catch", "(", "GroovyBugError", "e", ")", "{", "changeBugText", "(", "e", ",", "context", ")", ";", "throw", "e", ";", "}", "catch", "(", "NoClassDefFoundError", "e", ")", "{", "// effort to get more logging in case a dependency of a class is loaded", "// although it shouldn't have", "convertUncaughtExceptionToCompilationError", "(", "e", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "convertUncaughtExceptionToCompilationError", "(", "e", ")", ";", "}", "}", "getErrorCollector", "(", ")", ".", "failIfErrors", "(", ")", ";", "}" ]
A loop driver for applying operations to all primary ClassNodes in our AST. Automatically skips units that have already been processed through the current phase.
[ "A", "loop", "driver", "for", "applying", "operations", "to", "all", "primary", "ClassNodes", "in", "our", "AST", ".", "Automatically", "skips", "units", "that", "have", "already", "been", "processed", "through", "the", "current", "phase", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/control/CompilationUnit.java#L1041-L1076
156,476
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/SocketGroovyMethods.java
SocketGroovyMethods.withStreams
public static <T> T withStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={"java.io.InputStream","java.io.OutputStream"}) Closure<T> closure) throws IOException { InputStream input = socket.getInputStream(); OutputStream output = socket.getOutputStream(); try { T result = closure.call(new Object[]{input, output}); InputStream temp1 = input; input = null; temp1.close(); OutputStream temp2 = output; output = null; temp2.close(); return result; } finally { closeWithWarning(input); closeWithWarning(output); } }
java
public static <T> T withStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={"java.io.InputStream","java.io.OutputStream"}) Closure<T> closure) throws IOException { InputStream input = socket.getInputStream(); OutputStream output = socket.getOutputStream(); try { T result = closure.call(new Object[]{input, output}); InputStream temp1 = input; input = null; temp1.close(); OutputStream temp2 = output; output = null; temp2.close(); return result; } finally { closeWithWarning(input); closeWithWarning(output); } }
[ "public", "static", "<", "T", ">", "T", "withStreams", "(", "Socket", "socket", ",", "@", "ClosureParams", "(", "value", "=", "SimpleType", ".", "class", ",", "options", "=", "{", "\"java.io.InputStream\"", ",", "\"java.io.OutputStream\"", "}", ")", "Closure", "<", "T", ">", "closure", ")", "throws", "IOException", "{", "InputStream", "input", "=", "socket", ".", "getInputStream", "(", ")", ";", "OutputStream", "output", "=", "socket", ".", "getOutputStream", "(", ")", ";", "try", "{", "T", "result", "=", "closure", ".", "call", "(", "new", "Object", "[", "]", "{", "input", ",", "output", "}", ")", ";", "InputStream", "temp1", "=", "input", ";", "input", "=", "null", ";", "temp1", ".", "close", "(", ")", ";", "OutputStream", "temp2", "=", "output", ";", "output", "=", "null", ";", "temp2", ".", "close", "(", ")", ";", "return", "result", ";", "}", "finally", "{", "closeWithWarning", "(", "input", ")", ";", "closeWithWarning", "(", "output", ")", ";", "}", "}" ]
Passes the Socket's InputStream and OutputStream to the closure. The streams will be closed after the closure returns, even if an exception is thrown. @param socket a Socket @param closure a Closure @return the value returned by the closure @throws IOException if an IOException occurs. @since 1.5.2
[ "Passes", "the", "Socket", "s", "InputStream", "and", "OutputStream", "to", "the", "closure", ".", "The", "streams", "will", "be", "closed", "after", "the", "closure", "returns", "even", "if", "an", "exception", "is", "thrown", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/SocketGroovyMethods.java#L61-L79
156,477
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/SocketGroovyMethods.java
SocketGroovyMethods.withObjectStreams
public static <T> T withObjectStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={"java.io.ObjectInputStream","java.io.ObjectOutputStream"}) Closure<T> closure) throws IOException { InputStream input = socket.getInputStream(); OutputStream output = socket.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(output); ObjectInputStream ois = new ObjectInputStream(input); try { T result = closure.call(new Object[]{ois, oos}); InputStream temp1 = ois; ois = null; temp1.close(); temp1 = input; input = null; temp1.close(); OutputStream temp2 = oos; oos = null; temp2.close(); temp2 = output; output = null; temp2.close(); return result; } finally { closeWithWarning(ois); closeWithWarning(input); closeWithWarning(oos); closeWithWarning(output); } }
java
public static <T> T withObjectStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={"java.io.ObjectInputStream","java.io.ObjectOutputStream"}) Closure<T> closure) throws IOException { InputStream input = socket.getInputStream(); OutputStream output = socket.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(output); ObjectInputStream ois = new ObjectInputStream(input); try { T result = closure.call(new Object[]{ois, oos}); InputStream temp1 = ois; ois = null; temp1.close(); temp1 = input; input = null; temp1.close(); OutputStream temp2 = oos; oos = null; temp2.close(); temp2 = output; output = null; temp2.close(); return result; } finally { closeWithWarning(ois); closeWithWarning(input); closeWithWarning(oos); closeWithWarning(output); } }
[ "public", "static", "<", "T", ">", "T", "withObjectStreams", "(", "Socket", "socket", ",", "@", "ClosureParams", "(", "value", "=", "SimpleType", ".", "class", ",", "options", "=", "{", "\"java.io.ObjectInputStream\"", ",", "\"java.io.ObjectOutputStream\"", "}", ")", "Closure", "<", "T", ">", "closure", ")", "throws", "IOException", "{", "InputStream", "input", "=", "socket", ".", "getInputStream", "(", ")", ";", "OutputStream", "output", "=", "socket", ".", "getOutputStream", "(", ")", ";", "ObjectOutputStream", "oos", "=", "new", "ObjectOutputStream", "(", "output", ")", ";", "ObjectInputStream", "ois", "=", "new", "ObjectInputStream", "(", "input", ")", ";", "try", "{", "T", "result", "=", "closure", ".", "call", "(", "new", "Object", "[", "]", "{", "ois", ",", "oos", "}", ")", ";", "InputStream", "temp1", "=", "ois", ";", "ois", "=", "null", ";", "temp1", ".", "close", "(", ")", ";", "temp1", "=", "input", ";", "input", "=", "null", ";", "temp1", ".", "close", "(", ")", ";", "OutputStream", "temp2", "=", "oos", ";", "oos", "=", "null", ";", "temp2", ".", "close", "(", ")", ";", "temp2", "=", "output", ";", "output", "=", "null", ";", "temp2", ".", "close", "(", ")", ";", "return", "result", ";", "}", "finally", "{", "closeWithWarning", "(", "ois", ")", ";", "closeWithWarning", "(", "input", ")", ";", "closeWithWarning", "(", "oos", ")", ";", "closeWithWarning", "(", "output", ")", ";", "}", "}" ]
Creates an InputObjectStream and an OutputObjectStream from a Socket, and passes them to the closure. The streams will be closed after the closure returns, even if an exception is thrown. @param socket this Socket @param closure a Closure @return the value returned by the closure @throws IOException if an IOException occurs. @since 1.5.0
[ "Creates", "an", "InputObjectStream", "and", "an", "OutputObjectStream", "from", "a", "Socket", "and", "passes", "them", "to", "the", "closure", ".", "The", "streams", "will", "be", "closed", "after", "the", "closure", "returns", "even", "if", "an", "exception", "is", "thrown", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/SocketGroovyMethods.java#L92-L120
156,478
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/MethodKey.java
MethodKey.createCopy
public MethodKey createCopy() { int size = getParameterCount(); Class[] paramTypes = new Class[size]; for (int i = 0; i < size; i++) { paramTypes[i] = getParameterType(i); } return new DefaultMethodKey(sender, name, paramTypes, isCallToSuper); }
java
public MethodKey createCopy() { int size = getParameterCount(); Class[] paramTypes = new Class[size]; for (int i = 0; i < size; i++) { paramTypes[i] = getParameterType(i); } return new DefaultMethodKey(sender, name, paramTypes, isCallToSuper); }
[ "public", "MethodKey", "createCopy", "(", ")", "{", "int", "size", "=", "getParameterCount", "(", ")", ";", "Class", "[", "]", "paramTypes", "=", "new", "Class", "[", "size", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "{", "paramTypes", "[", "i", "]", "=", "getParameterType", "(", "i", ")", ";", "}", "return", "new", "DefaultMethodKey", "(", "sender", ",", "name", ",", "paramTypes", ",", "isCallToSuper", ")", ";", "}" ]
Creates an immutable copy that we can cache.
[ "Creates", "an", "immutable", "copy", "that", "we", "can", "cache", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/MethodKey.java#L49-L56
156,479
groovy/groovy-core
src/main/org/codehaus/groovy/transform/trait/TraitComposer.java
TraitComposer.doExtendTraits
public static void doExtendTraits(final ClassNode cNode, final SourceUnit unit, final CompilationUnit cu) { if (cNode.isInterface()) return; boolean isItselfTrait = Traits.isTrait(cNode); SuperCallTraitTransformer superCallTransformer = new SuperCallTraitTransformer(unit); if (isItselfTrait) { checkTraitAllowed(cNode, unit); return; } if (!cNode.getNameWithoutPackage().endsWith(Traits.TRAIT_HELPER)) { List<ClassNode> traits = findTraits(cNode); for (ClassNode trait : traits) { TraitHelpersTuple helpers = Traits.findHelpers(trait); applyTrait(trait, cNode, helpers); superCallTransformer.visitClass(cNode); if (unit!=null) { ASTTransformationCollectorCodeVisitor collector = new ASTTransformationCollectorCodeVisitor(unit, cu.getTransformLoader()); collector.visitClass(cNode); } } } }
java
public static void doExtendTraits(final ClassNode cNode, final SourceUnit unit, final CompilationUnit cu) { if (cNode.isInterface()) return; boolean isItselfTrait = Traits.isTrait(cNode); SuperCallTraitTransformer superCallTransformer = new SuperCallTraitTransformer(unit); if (isItselfTrait) { checkTraitAllowed(cNode, unit); return; } if (!cNode.getNameWithoutPackage().endsWith(Traits.TRAIT_HELPER)) { List<ClassNode> traits = findTraits(cNode); for (ClassNode trait : traits) { TraitHelpersTuple helpers = Traits.findHelpers(trait); applyTrait(trait, cNode, helpers); superCallTransformer.visitClass(cNode); if (unit!=null) { ASTTransformationCollectorCodeVisitor collector = new ASTTransformationCollectorCodeVisitor(unit, cu.getTransformLoader()); collector.visitClass(cNode); } } } }
[ "public", "static", "void", "doExtendTraits", "(", "final", "ClassNode", "cNode", ",", "final", "SourceUnit", "unit", ",", "final", "CompilationUnit", "cu", ")", "{", "if", "(", "cNode", ".", "isInterface", "(", ")", ")", "return", ";", "boolean", "isItselfTrait", "=", "Traits", ".", "isTrait", "(", "cNode", ")", ";", "SuperCallTraitTransformer", "superCallTransformer", "=", "new", "SuperCallTraitTransformer", "(", "unit", ")", ";", "if", "(", "isItselfTrait", ")", "{", "checkTraitAllowed", "(", "cNode", ",", "unit", ")", ";", "return", ";", "}", "if", "(", "!", "cNode", ".", "getNameWithoutPackage", "(", ")", ".", "endsWith", "(", "Traits", ".", "TRAIT_HELPER", ")", ")", "{", "List", "<", "ClassNode", ">", "traits", "=", "findTraits", "(", "cNode", ")", ";", "for", "(", "ClassNode", "trait", ":", "traits", ")", "{", "TraitHelpersTuple", "helpers", "=", "Traits", ".", "findHelpers", "(", "trait", ")", ";", "applyTrait", "(", "trait", ",", "cNode", ",", "helpers", ")", ";", "superCallTransformer", ".", "visitClass", "(", "cNode", ")", ";", "if", "(", "unit", "!=", "null", ")", "{", "ASTTransformationCollectorCodeVisitor", "collector", "=", "new", "ASTTransformationCollectorCodeVisitor", "(", "unit", ",", "cu", ".", "getTransformLoader", "(", ")", ")", ";", "collector", ".", "visitClass", "(", "cNode", ")", ";", "}", "}", "}", "}" ]
Given a class node, if this class node implements a trait, then generate all the appropriate code which delegates calls to the trait. It is safe to call this method on a class node which does not implement a trait. @param cNode a class node @param unit the source unit
[ "Given", "a", "class", "node", "if", "this", "class", "node", "implements", "a", "trait", "then", "generate", "all", "the", "appropriate", "code", "which", "delegates", "calls", "to", "the", "trait", ".", "It", "is", "safe", "to", "call", "this", "method", "on", "a", "class", "node", "which", "does", "not", "implement", "a", "trait", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/transform/trait/TraitComposer.java#L102-L122
156,480
groovy/groovy-core
src/main/org/codehaus/groovy/control/ErrorCollector.java
ErrorCollector.getSyntaxError
public SyntaxException getSyntaxError(int index) { SyntaxException exception = null; Message message = getError(index); if (message != null && message instanceof SyntaxErrorMessage) { exception = ((SyntaxErrorMessage) message).getCause(); } return exception; }
java
public SyntaxException getSyntaxError(int index) { SyntaxException exception = null; Message message = getError(index); if (message != null && message instanceof SyntaxErrorMessage) { exception = ((SyntaxErrorMessage) message).getCause(); } return exception; }
[ "public", "SyntaxException", "getSyntaxError", "(", "int", "index", ")", "{", "SyntaxException", "exception", "=", "null", ";", "Message", "message", "=", "getError", "(", "index", ")", ";", "if", "(", "message", "!=", "null", "&&", "message", "instanceof", "SyntaxErrorMessage", ")", "{", "exception", "=", "(", "(", "SyntaxErrorMessage", ")", "message", ")", ".", "getCause", "(", ")", ";", "}", "return", "exception", ";", "}" ]
Convenience routine to return the specified error's underlying SyntaxException, or null if it isn't one.
[ "Convenience", "routine", "to", "return", "the", "specified", "error", "s", "underlying", "SyntaxException", "or", "null", "if", "it", "isn", "t", "one", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/control/ErrorCollector.java#L240-L248
156,481
groovy/groovy-core
src/main/org/apache/commons/cli/GroovyInternalPosixParser.java
GroovyInternalPosixParser.gobble
private void gobble(Iterator iter) { if (eatTheRest) { while (iter.hasNext()) { tokens.add(iter.next()); } } }
java
private void gobble(Iterator iter) { if (eatTheRest) { while (iter.hasNext()) { tokens.add(iter.next()); } } }
[ "private", "void", "gobble", "(", "Iterator", "iter", ")", "{", "if", "(", "eatTheRest", ")", "{", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "tokens", ".", "add", "(", "iter", ".", "next", "(", ")", ")", ";", "}", "}", "}" ]
Adds the remaining tokens to the processed tokens list. @param iter An iterator over the remaining tokens
[ "Adds", "the", "remaining", "tokens", "to", "the", "processed", "tokens", "list", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/apache/commons/cli/GroovyInternalPosixParser.java#L165-L174
156,482
groovy/groovy-core
src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java
StaticTypeCheckingSupport.allParametersAndArgumentsMatch
public static int allParametersAndArgumentsMatch(Parameter[] params, ClassNode[] args) { if (params==null) { params = Parameter.EMPTY_ARRAY; } int dist = 0; if (args.length<params.length) return -1; // we already know the lengths are equal for (int i = 0; i < params.length; i++) { ClassNode paramType = params[i].getType(); ClassNode argType = args[i]; if (!isAssignableTo(argType, paramType)) return -1; else { if (!paramType.equals(argType)) dist+=getDistance(argType, paramType); } } return dist; }
java
public static int allParametersAndArgumentsMatch(Parameter[] params, ClassNode[] args) { if (params==null) { params = Parameter.EMPTY_ARRAY; } int dist = 0; if (args.length<params.length) return -1; // we already know the lengths are equal for (int i = 0; i < params.length; i++) { ClassNode paramType = params[i].getType(); ClassNode argType = args[i]; if (!isAssignableTo(argType, paramType)) return -1; else { if (!paramType.equals(argType)) dist+=getDistance(argType, paramType); } } return dist; }
[ "public", "static", "int", "allParametersAndArgumentsMatch", "(", "Parameter", "[", "]", "params", ",", "ClassNode", "[", "]", "args", ")", "{", "if", "(", "params", "==", "null", ")", "{", "params", "=", "Parameter", ".", "EMPTY_ARRAY", ";", "}", "int", "dist", "=", "0", ";", "if", "(", "args", ".", "length", "<", "params", ".", "length", ")", "return", "-", "1", ";", "// we already know the lengths are equal", "for", "(", "int", "i", "=", "0", ";", "i", "<", "params", ".", "length", ";", "i", "++", ")", "{", "ClassNode", "paramType", "=", "params", "[", "i", "]", ".", "getType", "(", ")", ";", "ClassNode", "argType", "=", "args", "[", "i", "]", ";", "if", "(", "!", "isAssignableTo", "(", "argType", ",", "paramType", ")", ")", "return", "-", "1", ";", "else", "{", "if", "(", "!", "paramType", ".", "equals", "(", "argType", ")", ")", "dist", "+=", "getDistance", "(", "argType", ",", "paramType", ")", ";", "}", "}", "return", "dist", ";", "}" ]
Checks that arguments and parameter types match. @param params method parameters @param args type arguments @return -1 if arguments do not match, 0 if arguments are of the exact type and >0 when one or more argument is not of the exact type but still match
[ "Checks", "that", "arguments", "and", "parameter", "types", "match", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java#L216-L232
156,483
groovy/groovy-core
src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java
StaticTypeCheckingSupport.excessArgumentsMatchesVargsParameter
static int excessArgumentsMatchesVargsParameter(Parameter[] params, ClassNode[] args) { // we already know parameter length is bigger zero and last is a vargs // the excess arguments are all put in an array for the vargs call // so check against the component type int dist = 0; ClassNode vargsBase = params[params.length - 1].getType().getComponentType(); for (int i = params.length; i < args.length; i++) { if (!isAssignableTo(args[i],vargsBase)) return -1; else if (!args[i].equals(vargsBase)) dist+=getDistance(args[i], vargsBase); } return dist; }
java
static int excessArgumentsMatchesVargsParameter(Parameter[] params, ClassNode[] args) { // we already know parameter length is bigger zero and last is a vargs // the excess arguments are all put in an array for the vargs call // so check against the component type int dist = 0; ClassNode vargsBase = params[params.length - 1].getType().getComponentType(); for (int i = params.length; i < args.length; i++) { if (!isAssignableTo(args[i],vargsBase)) return -1; else if (!args[i].equals(vargsBase)) dist+=getDistance(args[i], vargsBase); } return dist; }
[ "static", "int", "excessArgumentsMatchesVargsParameter", "(", "Parameter", "[", "]", "params", ",", "ClassNode", "[", "]", "args", ")", "{", "// we already know parameter length is bigger zero and last is a vargs", "// the excess arguments are all put in an array for the vargs call", "// so check against the component type", "int", "dist", "=", "0", ";", "ClassNode", "vargsBase", "=", "params", "[", "params", ".", "length", "-", "1", "]", ".", "getType", "(", ")", ".", "getComponentType", "(", ")", ";", "for", "(", "int", "i", "=", "params", ".", "length", ";", "i", "<", "args", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "isAssignableTo", "(", "args", "[", "i", "]", ",", "vargsBase", ")", ")", "return", "-", "1", ";", "else", "if", "(", "!", "args", "[", "i", "]", ".", "equals", "(", "vargsBase", ")", ")", "dist", "+=", "getDistance", "(", "args", "[", "i", "]", ",", "vargsBase", ")", ";", "}", "return", "dist", ";", "}" ]
Checks that excess arguments match the vararg signature parameter. @param params @param args @return -1 if no match, 0 if all arguments matches the vararg type and >0 if one or more vararg argument is assignable to the vararg type, but still not an exact match
[ "Checks", "that", "excess", "arguments", "match", "the", "vararg", "signature", "parameter", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java#L276-L287
156,484
groovy/groovy-core
src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java
StaticTypeCheckingSupport.lastArgMatchesVarg
static int lastArgMatchesVarg(Parameter[] params, ClassNode... args) { if (!isVargs(params)) return -1; // case length ==0 handled already // we have now two cases, // the argument is wrapped in the vargs array or // the argument is an array that can be used for the vargs part directly // we test only the wrapping part, since the non wrapping is done already ClassNode lastParamType = params[params.length - 1].getType(); ClassNode ptype = lastParamType.getComponentType(); ClassNode arg = args[args.length - 1]; if (isNumberType(ptype) && isNumberType(arg) && !ptype.equals(arg)) return -1; return isAssignableTo(arg, ptype)?Math.min(getDistance(arg, lastParamType), getDistance(arg, ptype)):-1; }
java
static int lastArgMatchesVarg(Parameter[] params, ClassNode... args) { if (!isVargs(params)) return -1; // case length ==0 handled already // we have now two cases, // the argument is wrapped in the vargs array or // the argument is an array that can be used for the vargs part directly // we test only the wrapping part, since the non wrapping is done already ClassNode lastParamType = params[params.length - 1].getType(); ClassNode ptype = lastParamType.getComponentType(); ClassNode arg = args[args.length - 1]; if (isNumberType(ptype) && isNumberType(arg) && !ptype.equals(arg)) return -1; return isAssignableTo(arg, ptype)?Math.min(getDistance(arg, lastParamType), getDistance(arg, ptype)):-1; }
[ "static", "int", "lastArgMatchesVarg", "(", "Parameter", "[", "]", "params", ",", "ClassNode", "...", "args", ")", "{", "if", "(", "!", "isVargs", "(", "params", ")", ")", "return", "-", "1", ";", "// case length ==0 handled already", "// we have now two cases,", "// the argument is wrapped in the vargs array or", "// the argument is an array that can be used for the vargs part directly", "// we test only the wrapping part, since the non wrapping is done already", "ClassNode", "lastParamType", "=", "params", "[", "params", ".", "length", "-", "1", "]", ".", "getType", "(", ")", ";", "ClassNode", "ptype", "=", "lastParamType", ".", "getComponentType", "(", ")", ";", "ClassNode", "arg", "=", "args", "[", "args", ".", "length", "-", "1", "]", ";", "if", "(", "isNumberType", "(", "ptype", ")", "&&", "isNumberType", "(", "arg", ")", "&&", "!", "ptype", ".", "equals", "(", "arg", ")", ")", "return", "-", "1", ";", "return", "isAssignableTo", "(", "arg", ",", "ptype", ")", "?", "Math", ".", "min", "(", "getDistance", "(", "arg", ",", "lastParamType", ")", ",", "getDistance", "(", "arg", ",", "ptype", ")", ")", ":", "-", "1", ";", "}" ]
Checks if the last argument matches the vararg type. @param params @param args @return -1 if no match, 0 if the last argument is exactly the vararg type and 1 if of an assignable type
[ "Checks", "if", "the", "last", "argument", "matches", "the", "vararg", "type", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java#L295-L307
156,485
groovy/groovy-core
src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java
StaticTypeCheckingSupport.buildParameter
private static Parameter buildParameter(final Map<String, GenericsType> genericFromReceiver, final Map<String, GenericsType> placeholdersFromContext, final Parameter methodParameter, final ClassNode paramType) { if (genericFromReceiver.isEmpty() && (placeholdersFromContext==null||placeholdersFromContext.isEmpty())) { return methodParameter; } if (paramType.isArray()) { ClassNode componentType = paramType.getComponentType(); Parameter subMethodParameter = new Parameter(componentType, methodParameter.getName()); Parameter component = buildParameter(genericFromReceiver, placeholdersFromContext, subMethodParameter, componentType); return new Parameter(component.getType().makeArray(), component.getName()); } ClassNode resolved = resolveClassNodeGenerics(genericFromReceiver, placeholdersFromContext, paramType); return new Parameter(resolved, methodParameter.getName()); }
java
private static Parameter buildParameter(final Map<String, GenericsType> genericFromReceiver, final Map<String, GenericsType> placeholdersFromContext, final Parameter methodParameter, final ClassNode paramType) { if (genericFromReceiver.isEmpty() && (placeholdersFromContext==null||placeholdersFromContext.isEmpty())) { return methodParameter; } if (paramType.isArray()) { ClassNode componentType = paramType.getComponentType(); Parameter subMethodParameter = new Parameter(componentType, methodParameter.getName()); Parameter component = buildParameter(genericFromReceiver, placeholdersFromContext, subMethodParameter, componentType); return new Parameter(component.getType().makeArray(), component.getName()); } ClassNode resolved = resolveClassNodeGenerics(genericFromReceiver, placeholdersFromContext, paramType); return new Parameter(resolved, methodParameter.getName()); }
[ "private", "static", "Parameter", "buildParameter", "(", "final", "Map", "<", "String", ",", "GenericsType", ">", "genericFromReceiver", ",", "final", "Map", "<", "String", ",", "GenericsType", ">", "placeholdersFromContext", ",", "final", "Parameter", "methodParameter", ",", "final", "ClassNode", "paramType", ")", "{", "if", "(", "genericFromReceiver", ".", "isEmpty", "(", ")", "&&", "(", "placeholdersFromContext", "==", "null", "||", "placeholdersFromContext", ".", "isEmpty", "(", ")", ")", ")", "{", "return", "methodParameter", ";", "}", "if", "(", "paramType", ".", "isArray", "(", ")", ")", "{", "ClassNode", "componentType", "=", "paramType", ".", "getComponentType", "(", ")", ";", "Parameter", "subMethodParameter", "=", "new", "Parameter", "(", "componentType", ",", "methodParameter", ".", "getName", "(", ")", ")", ";", "Parameter", "component", "=", "buildParameter", "(", "genericFromReceiver", ",", "placeholdersFromContext", ",", "subMethodParameter", ",", "componentType", ")", ";", "return", "new", "Parameter", "(", "component", ".", "getType", "(", ")", ".", "makeArray", "(", ")", ",", "component", ".", "getName", "(", ")", ")", ";", "}", "ClassNode", "resolved", "=", "resolveClassNodeGenerics", "(", "genericFromReceiver", ",", "placeholdersFromContext", ",", "paramType", ")", ";", "return", "new", "Parameter", "(", "resolved", ",", "methodParameter", ".", "getName", "(", ")", ")", ";", "}" ]
Given a parameter, builds a new parameter for which the known generics placeholders are resolved. @param genericFromReceiver resolved generics from the receiver of the message @param placeholdersFromContext, resolved generics from the method context @param methodParameter the method parameter for which we want to resolve generic types @param paramType the (unresolved) type of the method parameter @return a new parameter with the same name and type as the original one, but with resolved generic types
[ "Given", "a", "parameter", "builds", "a", "new", "parameter", "for", "which", "the", "known", "generics", "placeholders", "are", "resolved", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java#L1170-L1183
156,486
groovy/groovy-core
src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java
StaticTypeCheckingSupport.isClassClassNodeWrappingConcreteType
public static boolean isClassClassNodeWrappingConcreteType(ClassNode classNode) { GenericsType[] genericsTypes = classNode.getGenericsTypes(); return ClassHelper.CLASS_Type.equals(classNode) && classNode.isUsingGenerics() && genericsTypes!=null && !genericsTypes[0].isPlaceholder() && !genericsTypes[0].isWildcard(); }
java
public static boolean isClassClassNodeWrappingConcreteType(ClassNode classNode) { GenericsType[] genericsTypes = classNode.getGenericsTypes(); return ClassHelper.CLASS_Type.equals(classNode) && classNode.isUsingGenerics() && genericsTypes!=null && !genericsTypes[0].isPlaceholder() && !genericsTypes[0].isWildcard(); }
[ "public", "static", "boolean", "isClassClassNodeWrappingConcreteType", "(", "ClassNode", "classNode", ")", "{", "GenericsType", "[", "]", "genericsTypes", "=", "classNode", ".", "getGenericsTypes", "(", ")", ";", "return", "ClassHelper", ".", "CLASS_Type", ".", "equals", "(", "classNode", ")", "&&", "classNode", ".", "isUsingGenerics", "(", ")", "&&", "genericsTypes", "!=", "null", "&&", "!", "genericsTypes", "[", "0", "]", ".", "isPlaceholder", "(", ")", "&&", "!", "genericsTypes", "[", "0", "]", ".", "isWildcard", "(", ")", ";", "}" ]
Returns true if the class node represents a the class node for the Class class and if the parametrized type is a neither a placeholder or a wildcard. For example, the class node Class&lt;Foo&gt; where Foo is a class would return true, but the class node for Class&lt;?&gt; would return false. @param classNode a class node to be tested @return true if it is the class node for Class and its generic type is a real class
[ "Returns", "true", "if", "the", "class", "node", "represents", "a", "the", "class", "node", "for", "the", "Class", "class", "and", "if", "the", "parametrized", "type", "is", "a", "neither", "a", "placeholder", "or", "a", "wildcard", ".", "For", "example", "the", "class", "node", "Class&lt", ";", "Foo&gt", ";", "where", "Foo", "is", "a", "class", "would", "return", "true", "but", "the", "class", "node", "for", "Class&lt", ";", "?&gt", ";", "would", "return", "false", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java#L2069-L2076
156,487
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/IOGroovyMethods.java
IOGroovyMethods.splitEachLine
public static <T> T splitEachLine(InputStream stream, String regex, String charset, @ClosureParams(value=FromString.class,options="List<String>") Closure<T> closure) throws IOException { return splitEachLine(new BufferedReader(new InputStreamReader(stream, charset)), regex, closure); }
java
public static <T> T splitEachLine(InputStream stream, String regex, String charset, @ClosureParams(value=FromString.class,options="List<String>") Closure<T> closure) throws IOException { return splitEachLine(new BufferedReader(new InputStreamReader(stream, charset)), regex, closure); }
[ "public", "static", "<", "T", ">", "T", "splitEachLine", "(", "InputStream", "stream", ",", "String", "regex", ",", "String", "charset", ",", "@", "ClosureParams", "(", "value", "=", "FromString", ".", "class", ",", "options", "=", "\"List<String>\"", ")", "Closure", "<", "T", ">", "closure", ")", "throws", "IOException", "{", "return", "splitEachLine", "(", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "stream", ",", "charset", ")", ")", ",", "regex", ",", "closure", ")", ";", "}" ]
Iterates through the given InputStream line by line using the specified encoding, splitting each line using the given separator. The list of tokens for each line is then passed to the given closure. Finally, the stream is closed. @param stream an InputStream @param regex the delimiting regular expression @param charset opens the stream with a specified charset @param closure a closure @return the last value returned by the closure @throws IOException if an IOException occurs. @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid @see #splitEachLine(java.io.Reader, java.lang.String, groovy.lang.Closure) @since 1.5.5
[ "Iterates", "through", "the", "given", "InputStream", "line", "by", "line", "using", "the", "specified", "encoding", "splitting", "each", "line", "using", "the", "given", "separator", ".", "The", "list", "of", "tokens", "for", "each", "line", "is", "then", "passed", "to", "the", "given", "closure", ".", "Finally", "the", "stream", "is", "closed", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/IOGroovyMethods.java#L603-L605
156,488
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/IOGroovyMethods.java
IOGroovyMethods.transformChar
public static void transformChar(Reader self, Writer writer, @ClosureParams(value=SimpleType.class, options="java.lang.String") Closure closure) throws IOException { int c; try { char[] chars = new char[1]; while ((c = self.read()) != -1) { chars[0] = (char) c; writer.write((String) closure.call(new String(chars))); } writer.flush(); Writer temp2 = writer; writer = null; temp2.close(); Reader temp1 = self; self = null; temp1.close(); } finally { closeWithWarning(self); closeWithWarning(writer); } }
java
public static void transformChar(Reader self, Writer writer, @ClosureParams(value=SimpleType.class, options="java.lang.String") Closure closure) throws IOException { int c; try { char[] chars = new char[1]; while ((c = self.read()) != -1) { chars[0] = (char) c; writer.write((String) closure.call(new String(chars))); } writer.flush(); Writer temp2 = writer; writer = null; temp2.close(); Reader temp1 = self; self = null; temp1.close(); } finally { closeWithWarning(self); closeWithWarning(writer); } }
[ "public", "static", "void", "transformChar", "(", "Reader", "self", ",", "Writer", "writer", ",", "@", "ClosureParams", "(", "value", "=", "SimpleType", ".", "class", ",", "options", "=", "\"java.lang.String\"", ")", "Closure", "closure", ")", "throws", "IOException", "{", "int", "c", ";", "try", "{", "char", "[", "]", "chars", "=", "new", "char", "[", "1", "]", ";", "while", "(", "(", "c", "=", "self", ".", "read", "(", ")", ")", "!=", "-", "1", ")", "{", "chars", "[", "0", "]", "=", "(", "char", ")", "c", ";", "writer", ".", "write", "(", "(", "String", ")", "closure", ".", "call", "(", "new", "String", "(", "chars", ")", ")", ")", ";", "}", "writer", ".", "flush", "(", ")", ";", "Writer", "temp2", "=", "writer", ";", "writer", "=", "null", ";", "temp2", ".", "close", "(", ")", ";", "Reader", "temp1", "=", "self", ";", "self", "=", "null", ";", "temp1", ".", "close", "(", ")", ";", "}", "finally", "{", "closeWithWarning", "(", "self", ")", ";", "closeWithWarning", "(", "writer", ")", ";", "}", "}" ]
Transforms each character from this reader by passing it to the given closure. The Closure should return each transformed character, which will be passed to the Writer. The reader and writer will be both be closed before this method returns. @param self a Reader object @param writer a Writer to receive the transformed characters @param closure a closure that performs the required transformation @throws IOException if an IOException occurs. @since 1.5.0
[ "Transforms", "each", "character", "from", "this", "reader", "by", "passing", "it", "to", "the", "given", "closure", ".", "The", "Closure", "should", "return", "each", "transformed", "character", "which", "will", "be", "passed", "to", "the", "Writer", ".", "The", "reader", "and", "writer", "will", "be", "both", "be", "closed", "before", "this", "method", "returns", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/IOGroovyMethods.java#L1398-L1418
156,489
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/IOGroovyMethods.java
IOGroovyMethods.withCloseable
public static <T, U extends Closeable> T withCloseable(U self, @ClosureParams(value=FirstParam.class) Closure<T> action) throws IOException { try { T result = action.call(self); Closeable temp = self; self = null; temp.close(); return result; } finally { DefaultGroovyMethodsSupport.closeWithWarning(self); } }
java
public static <T, U extends Closeable> T withCloseable(U self, @ClosureParams(value=FirstParam.class) Closure<T> action) throws IOException { try { T result = action.call(self); Closeable temp = self; self = null; temp.close(); return result; } finally { DefaultGroovyMethodsSupport.closeWithWarning(self); } }
[ "public", "static", "<", "T", ",", "U", "extends", "Closeable", ">", "T", "withCloseable", "(", "U", "self", ",", "@", "ClosureParams", "(", "value", "=", "FirstParam", ".", "class", ")", "Closure", "<", "T", ">", "action", ")", "throws", "IOException", "{", "try", "{", "T", "result", "=", "action", ".", "call", "(", "self", ")", ";", "Closeable", "temp", "=", "self", ";", "self", "=", "null", ";", "temp", ".", "close", "(", ")", ";", "return", "result", ";", "}", "finally", "{", "DefaultGroovyMethodsSupport", ".", "closeWithWarning", "(", "self", ")", ";", "}", "}" ]
Allows this closeable to be used within the closure, ensuring that it is closed once the closure has been executed and before this method returns. @param self the Closeable @param action the closure taking the Closeable as parameter @return the value returned by the closure @throws IOException if an IOException occurs. @since 2.4.0
[ "Allows", "this", "closeable", "to", "be", "used", "within", "the", "closure", "ensuring", "that", "it", "is", "closed", "once", "the", "closure", "has", "been", "executed", "and", "before", "this", "method", "returns", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/IOGroovyMethods.java#L1620-L1632
156,490
groovy/groovy-core
src/main/groovy/lang/MetaArrayLengthProperty.java
MetaArrayLengthProperty.getProperty
public Object getProperty(Object object) { return java.lang.reflect.Array.getLength(object); }
java
public Object getProperty(Object object) { return java.lang.reflect.Array.getLength(object); }
[ "public", "Object", "getProperty", "(", "Object", "object", ")", "{", "return", "java", ".", "lang", ".", "reflect", ".", "Array", ".", "getLength", "(", "object", ")", ";", "}" ]
Get this property from the given object. @param object an array @return the length of the array object @throws IllegalArgumentException if object is not an array
[ "Get", "this", "property", "from", "the", "given", "object", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/groovy/lang/MetaArrayLengthProperty.java#L43-L45
156,491
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/ProxyGeneratorAdapter.java
ProxyGeneratorAdapter.makeDelegateCall
protected MethodVisitor makeDelegateCall(final String name, final String desc, final String signature, final String[] exceptions, final int accessFlags) { MethodVisitor mv = super.visitMethod(accessFlags, name, desc, signature, exceptions); mv.visitVarInsn(ALOAD, 0); // load this mv.visitFieldInsn(GETFIELD, proxyName, DELEGATE_OBJECT_FIELD, BytecodeHelper.getTypeDescription(delegateClass)); // load delegate // using InvokerHelper to allow potential intercepted calls int size; mv.visitLdcInsn(name); // method name Type[] args = Type.getArgumentTypes(desc); BytecodeHelper.pushConstant(mv, args.length); mv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); size = 6; int idx = 1; for (int i = 0; i < args.length; i++) { Type arg = args[i]; mv.visitInsn(DUP); BytecodeHelper.pushConstant(mv, i); // primitive types must be boxed if (isPrimitive(arg)) { mv.visitIntInsn(getLoadInsn(arg), idx); String wrappedType = getWrappedClassDescriptor(arg); mv.visitMethodInsn(INVOKESTATIC, wrappedType, "valueOf", "(" + arg.getDescriptor() + ")L" + wrappedType + ";", false); } else { mv.visitVarInsn(ALOAD, idx); // load argument i } size = Math.max(size, 5+registerLen(arg)); idx += registerLen(arg); mv.visitInsn(AASTORE); // store value into array } mv.visitMethodInsn(INVOKESTATIC, "org/codehaus/groovy/runtime/InvokerHelper", "invokeMethod", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;", false); unwrapResult(mv, desc); mv.visitMaxs(size, registerLen(args) + 1); return mv; }
java
protected MethodVisitor makeDelegateCall(final String name, final String desc, final String signature, final String[] exceptions, final int accessFlags) { MethodVisitor mv = super.visitMethod(accessFlags, name, desc, signature, exceptions); mv.visitVarInsn(ALOAD, 0); // load this mv.visitFieldInsn(GETFIELD, proxyName, DELEGATE_OBJECT_FIELD, BytecodeHelper.getTypeDescription(delegateClass)); // load delegate // using InvokerHelper to allow potential intercepted calls int size; mv.visitLdcInsn(name); // method name Type[] args = Type.getArgumentTypes(desc); BytecodeHelper.pushConstant(mv, args.length); mv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); size = 6; int idx = 1; for (int i = 0; i < args.length; i++) { Type arg = args[i]; mv.visitInsn(DUP); BytecodeHelper.pushConstant(mv, i); // primitive types must be boxed if (isPrimitive(arg)) { mv.visitIntInsn(getLoadInsn(arg), idx); String wrappedType = getWrappedClassDescriptor(arg); mv.visitMethodInsn(INVOKESTATIC, wrappedType, "valueOf", "(" + arg.getDescriptor() + ")L" + wrappedType + ";", false); } else { mv.visitVarInsn(ALOAD, idx); // load argument i } size = Math.max(size, 5+registerLen(arg)); idx += registerLen(arg); mv.visitInsn(AASTORE); // store value into array } mv.visitMethodInsn(INVOKESTATIC, "org/codehaus/groovy/runtime/InvokerHelper", "invokeMethod", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;", false); unwrapResult(mv, desc); mv.visitMaxs(size, registerLen(args) + 1); return mv; }
[ "protected", "MethodVisitor", "makeDelegateCall", "(", "final", "String", "name", ",", "final", "String", "desc", ",", "final", "String", "signature", ",", "final", "String", "[", "]", "exceptions", ",", "final", "int", "accessFlags", ")", "{", "MethodVisitor", "mv", "=", "super", ".", "visitMethod", "(", "accessFlags", ",", "name", ",", "desc", ",", "signature", ",", "exceptions", ")", ";", "mv", ".", "visitVarInsn", "(", "ALOAD", ",", "0", ")", ";", "// load this", "mv", ".", "visitFieldInsn", "(", "GETFIELD", ",", "proxyName", ",", "DELEGATE_OBJECT_FIELD", ",", "BytecodeHelper", ".", "getTypeDescription", "(", "delegateClass", ")", ")", ";", "// load delegate", "// using InvokerHelper to allow potential intercepted calls", "int", "size", ";", "mv", ".", "visitLdcInsn", "(", "name", ")", ";", "// method name", "Type", "[", "]", "args", "=", "Type", ".", "getArgumentTypes", "(", "desc", ")", ";", "BytecodeHelper", ".", "pushConstant", "(", "mv", ",", "args", ".", "length", ")", ";", "mv", ".", "visitTypeInsn", "(", "ANEWARRAY", ",", "\"java/lang/Object\"", ")", ";", "size", "=", "6", ";", "int", "idx", "=", "1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "i", "++", ")", "{", "Type", "arg", "=", "args", "[", "i", "]", ";", "mv", ".", "visitInsn", "(", "DUP", ")", ";", "BytecodeHelper", ".", "pushConstant", "(", "mv", ",", "i", ")", ";", "// primitive types must be boxed", "if", "(", "isPrimitive", "(", "arg", ")", ")", "{", "mv", ".", "visitIntInsn", "(", "getLoadInsn", "(", "arg", ")", ",", "idx", ")", ";", "String", "wrappedType", "=", "getWrappedClassDescriptor", "(", "arg", ")", ";", "mv", ".", "visitMethodInsn", "(", "INVOKESTATIC", ",", "wrappedType", ",", "\"valueOf\"", ",", "\"(\"", "+", "arg", ".", "getDescriptor", "(", ")", "+", "\")L\"", "+", "wrappedType", "+", "\";\"", ",", "false", ")", ";", "}", "else", "{", "mv", ".", "visitVarInsn", "(", "ALOAD", ",", "idx", ")", ";", "// load argument i", "}", "size", "=", "Math", ".", "max", "(", "size", ",", "5", "+", "registerLen", "(", "arg", ")", ")", ";", "idx", "+=", "registerLen", "(", "arg", ")", ";", "mv", ".", "visitInsn", "(", "AASTORE", ")", ";", "// store value into array", "}", "mv", ".", "visitMethodInsn", "(", "INVOKESTATIC", ",", "\"org/codehaus/groovy/runtime/InvokerHelper\"", ",", "\"invokeMethod\"", ",", "\"(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;\"", ",", "false", ")", ";", "unwrapResult", "(", "mv", ",", "desc", ")", ";", "mv", ".", "visitMaxs", "(", "size", ",", "registerLen", "(", "args", ")", "+", "1", ")", ";", "return", "mv", ";", "}" ]
Generate a call to the delegate object.
[ "Generate", "a", "call", "to", "the", "delegate", "object", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/ProxyGeneratorAdapter.java#L708-L741
156,492
groovy/groovy-core
src/main/org/codehaus/groovy/reflection/stdclasses/CachedSAMClass.java
CachedSAMClass.getSAMMethod
public static Method getSAMMethod(Class<?> c) { // SAM = single public abstract method // if the class is not abstract there is no abstract method if (!Modifier.isAbstract(c.getModifiers())) return null; if (c.isInterface()) { Method[] methods = c.getMethods(); // res stores the first found abstract method Method res = null; for (Method mi : methods) { // ignore methods, that are not abstract and from Object if (!Modifier.isAbstract(mi.getModifiers())) continue; // ignore trait methods which have a default implementation if (mi.getAnnotation(Traits.Implemented.class)!=null) continue; try { Object.class.getMethod(mi.getName(), mi.getParameterTypes()); continue; } catch (NoSuchMethodException e) {/*ignore*/} // we have two methods, so no SAM if (res!=null) return null; res = mi; } return res; } else { LinkedList<Method> methods = new LinkedList(); getAbstractMethods(c, methods); if (methods.isEmpty()) return null; ListIterator<Method> it = methods.listIterator(); while (it.hasNext()) { Method m = it.next(); if (hasUsableImplementation(c, m)) it.remove(); } return getSingleNonDuplicateMethod(methods); } }
java
public static Method getSAMMethod(Class<?> c) { // SAM = single public abstract method // if the class is not abstract there is no abstract method if (!Modifier.isAbstract(c.getModifiers())) return null; if (c.isInterface()) { Method[] methods = c.getMethods(); // res stores the first found abstract method Method res = null; for (Method mi : methods) { // ignore methods, that are not abstract and from Object if (!Modifier.isAbstract(mi.getModifiers())) continue; // ignore trait methods which have a default implementation if (mi.getAnnotation(Traits.Implemented.class)!=null) continue; try { Object.class.getMethod(mi.getName(), mi.getParameterTypes()); continue; } catch (NoSuchMethodException e) {/*ignore*/} // we have two methods, so no SAM if (res!=null) return null; res = mi; } return res; } else { LinkedList<Method> methods = new LinkedList(); getAbstractMethods(c, methods); if (methods.isEmpty()) return null; ListIterator<Method> it = methods.listIterator(); while (it.hasNext()) { Method m = it.next(); if (hasUsableImplementation(c, m)) it.remove(); } return getSingleNonDuplicateMethod(methods); } }
[ "public", "static", "Method", "getSAMMethod", "(", "Class", "<", "?", ">", "c", ")", "{", "// SAM = single public abstract method", "// if the class is not abstract there is no abstract method", "if", "(", "!", "Modifier", ".", "isAbstract", "(", "c", ".", "getModifiers", "(", ")", ")", ")", "return", "null", ";", "if", "(", "c", ".", "isInterface", "(", ")", ")", "{", "Method", "[", "]", "methods", "=", "c", ".", "getMethods", "(", ")", ";", "// res stores the first found abstract method", "Method", "res", "=", "null", ";", "for", "(", "Method", "mi", ":", "methods", ")", "{", "// ignore methods, that are not abstract and from Object", "if", "(", "!", "Modifier", ".", "isAbstract", "(", "mi", ".", "getModifiers", "(", ")", ")", ")", "continue", ";", "// ignore trait methods which have a default implementation", "if", "(", "mi", ".", "getAnnotation", "(", "Traits", ".", "Implemented", ".", "class", ")", "!=", "null", ")", "continue", ";", "try", "{", "Object", ".", "class", ".", "getMethod", "(", "mi", ".", "getName", "(", ")", ",", "mi", ".", "getParameterTypes", "(", ")", ")", ";", "continue", ";", "}", "catch", "(", "NoSuchMethodException", "e", ")", "{", "/*ignore*/", "}", "// we have two methods, so no SAM", "if", "(", "res", "!=", "null", ")", "return", "null", ";", "res", "=", "mi", ";", "}", "return", "res", ";", "}", "else", "{", "LinkedList", "<", "Method", ">", "methods", "=", "new", "LinkedList", "(", ")", ";", "getAbstractMethods", "(", "c", ",", "methods", ")", ";", "if", "(", "methods", ".", "isEmpty", "(", ")", ")", "return", "null", ";", "ListIterator", "<", "Method", ">", "it", "=", "methods", ".", "listIterator", "(", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "Method", "m", "=", "it", ".", "next", "(", ")", ";", "if", "(", "hasUsableImplementation", "(", "c", ",", "m", ")", ")", "it", ".", "remove", "(", ")", ";", "}", "return", "getSingleNonDuplicateMethod", "(", "methods", ")", ";", "}", "}" ]
returns the abstract method from a SAM type, if it is a SAM type. @param c the SAM class @return null if nothing was found, the method otherwise
[ "returns", "the", "abstract", "method", "from", "a", "SAM", "type", "if", "it", "is", "a", "SAM", "type", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/reflection/stdclasses/CachedSAMClass.java#L159-L195
156,493
groovy/groovy-core
src/main/org/codehaus/groovy/classgen/asm/MopWriter.java
MopWriter.generateMopCalls
protected void generateMopCalls(LinkedList<MethodNode> mopCalls, boolean useThis) { for (MethodNode method : mopCalls) { String name = getMopMethodName(method, useThis); Parameter[] parameters = method.getParameters(); String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameters()); MethodVisitor mv = controller.getClassVisitor().visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, name, methodDescriptor, null, null); controller.setMethodVisitor(mv); mv.visitVarInsn(ALOAD, 0); int newRegister = 1; OperandStack operandStack = controller.getOperandStack(); for (Parameter parameter : parameters) { ClassNode type = parameter.getType(); operandStack.load(parameter.getType(), newRegister); // increment to next register, double/long are using two places newRegister++; if (type == ClassHelper.double_TYPE || type == ClassHelper.long_TYPE) newRegister++; } operandStack.remove(parameters.length); ClassNode declaringClass = method.getDeclaringClass(); // JDK 8 support for default methods in interfaces // this should probably be strenghtened when we support the A.super.foo() syntax int opcode = declaringClass.isInterface()?INVOKEINTERFACE:INVOKESPECIAL; mv.visitMethodInsn(opcode, BytecodeHelper.getClassInternalName(declaringClass), method.getName(), methodDescriptor, opcode == INVOKEINTERFACE); BytecodeHelper.doReturn(mv, method.getReturnType()); mv.visitMaxs(0, 0); mv.visitEnd(); controller.getClassNode().addMethod(name, ACC_PUBLIC | ACC_SYNTHETIC, method.getReturnType(), parameters, null, null); } }
java
protected void generateMopCalls(LinkedList<MethodNode> mopCalls, boolean useThis) { for (MethodNode method : mopCalls) { String name = getMopMethodName(method, useThis); Parameter[] parameters = method.getParameters(); String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameters()); MethodVisitor mv = controller.getClassVisitor().visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, name, methodDescriptor, null, null); controller.setMethodVisitor(mv); mv.visitVarInsn(ALOAD, 0); int newRegister = 1; OperandStack operandStack = controller.getOperandStack(); for (Parameter parameter : parameters) { ClassNode type = parameter.getType(); operandStack.load(parameter.getType(), newRegister); // increment to next register, double/long are using two places newRegister++; if (type == ClassHelper.double_TYPE || type == ClassHelper.long_TYPE) newRegister++; } operandStack.remove(parameters.length); ClassNode declaringClass = method.getDeclaringClass(); // JDK 8 support for default methods in interfaces // this should probably be strenghtened when we support the A.super.foo() syntax int opcode = declaringClass.isInterface()?INVOKEINTERFACE:INVOKESPECIAL; mv.visitMethodInsn(opcode, BytecodeHelper.getClassInternalName(declaringClass), method.getName(), methodDescriptor, opcode == INVOKEINTERFACE); BytecodeHelper.doReturn(mv, method.getReturnType()); mv.visitMaxs(0, 0); mv.visitEnd(); controller.getClassNode().addMethod(name, ACC_PUBLIC | ACC_SYNTHETIC, method.getReturnType(), parameters, null, null); } }
[ "protected", "void", "generateMopCalls", "(", "LinkedList", "<", "MethodNode", ">", "mopCalls", ",", "boolean", "useThis", ")", "{", "for", "(", "MethodNode", "method", ":", "mopCalls", ")", "{", "String", "name", "=", "getMopMethodName", "(", "method", ",", "useThis", ")", ";", "Parameter", "[", "]", "parameters", "=", "method", ".", "getParameters", "(", ")", ";", "String", "methodDescriptor", "=", "BytecodeHelper", ".", "getMethodDescriptor", "(", "method", ".", "getReturnType", "(", ")", ",", "method", ".", "getParameters", "(", ")", ")", ";", "MethodVisitor", "mv", "=", "controller", ".", "getClassVisitor", "(", ")", ".", "visitMethod", "(", "ACC_PUBLIC", "|", "ACC_SYNTHETIC", ",", "name", ",", "methodDescriptor", ",", "null", ",", "null", ")", ";", "controller", ".", "setMethodVisitor", "(", "mv", ")", ";", "mv", ".", "visitVarInsn", "(", "ALOAD", ",", "0", ")", ";", "int", "newRegister", "=", "1", ";", "OperandStack", "operandStack", "=", "controller", ".", "getOperandStack", "(", ")", ";", "for", "(", "Parameter", "parameter", ":", "parameters", ")", "{", "ClassNode", "type", "=", "parameter", ".", "getType", "(", ")", ";", "operandStack", ".", "load", "(", "parameter", ".", "getType", "(", ")", ",", "newRegister", ")", ";", "// increment to next register, double/long are using two places", "newRegister", "++", ";", "if", "(", "type", "==", "ClassHelper", ".", "double_TYPE", "||", "type", "==", "ClassHelper", ".", "long_TYPE", ")", "newRegister", "++", ";", "}", "operandStack", ".", "remove", "(", "parameters", ".", "length", ")", ";", "ClassNode", "declaringClass", "=", "method", ".", "getDeclaringClass", "(", ")", ";", "// JDK 8 support for default methods in interfaces", "// this should probably be strenghtened when we support the A.super.foo() syntax", "int", "opcode", "=", "declaringClass", ".", "isInterface", "(", ")", "?", "INVOKEINTERFACE", ":", "INVOKESPECIAL", ";", "mv", ".", "visitMethodInsn", "(", "opcode", ",", "BytecodeHelper", ".", "getClassInternalName", "(", "declaringClass", ")", ",", "method", ".", "getName", "(", ")", ",", "methodDescriptor", ",", "opcode", "==", "INVOKEINTERFACE", ")", ";", "BytecodeHelper", ".", "doReturn", "(", "mv", ",", "method", ".", "getReturnType", "(", ")", ")", ";", "mv", ".", "visitMaxs", "(", "0", ",", "0", ")", ";", "mv", ".", "visitEnd", "(", ")", ";", "controller", ".", "getClassNode", "(", ")", ".", "addMethod", "(", "name", ",", "ACC_PUBLIC", "|", "ACC_SYNTHETIC", ",", "method", ".", "getReturnType", "(", ")", ",", "parameters", ",", "null", ",", "null", ")", ";", "}", "}" ]
generates a Meta Object Protocol method, that is used to call a non public method, or to make a call to super. @param mopCalls list of methods a mop call method should be generated for @param useThis true if "this" should be used for the naming
[ "generates", "a", "Meta", "Object", "Protocol", "method", "that", "is", "used", "to", "call", "a", "non", "public", "method", "or", "to", "make", "a", "call", "to", "super", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/classgen/asm/MopWriter.java#L174-L202
156,494
groovy/groovy-core
src/main/org/codehaus/groovy/ast/ClassHelper.java
ClassHelper.getWrapper
public static ClassNode getWrapper(ClassNode cn) { cn = cn.redirect(); if (!isPrimitiveType(cn)) return cn; if (cn==boolean_TYPE) { return Boolean_TYPE; } else if (cn==byte_TYPE) { return Byte_TYPE; } else if (cn==char_TYPE) { return Character_TYPE; } else if (cn==short_TYPE) { return Short_TYPE; } else if (cn==int_TYPE) { return Integer_TYPE; } else if (cn==long_TYPE) { return Long_TYPE; } else if (cn==float_TYPE) { return Float_TYPE; } else if (cn==double_TYPE) { return Double_TYPE; } else if (cn==VOID_TYPE) { return void_WRAPPER_TYPE; } else { return cn; } }
java
public static ClassNode getWrapper(ClassNode cn) { cn = cn.redirect(); if (!isPrimitiveType(cn)) return cn; if (cn==boolean_TYPE) { return Boolean_TYPE; } else if (cn==byte_TYPE) { return Byte_TYPE; } else if (cn==char_TYPE) { return Character_TYPE; } else if (cn==short_TYPE) { return Short_TYPE; } else if (cn==int_TYPE) { return Integer_TYPE; } else if (cn==long_TYPE) { return Long_TYPE; } else if (cn==float_TYPE) { return Float_TYPE; } else if (cn==double_TYPE) { return Double_TYPE; } else if (cn==VOID_TYPE) { return void_WRAPPER_TYPE; } else { return cn; } }
[ "public", "static", "ClassNode", "getWrapper", "(", "ClassNode", "cn", ")", "{", "cn", "=", "cn", ".", "redirect", "(", ")", ";", "if", "(", "!", "isPrimitiveType", "(", "cn", ")", ")", "return", "cn", ";", "if", "(", "cn", "==", "boolean_TYPE", ")", "{", "return", "Boolean_TYPE", ";", "}", "else", "if", "(", "cn", "==", "byte_TYPE", ")", "{", "return", "Byte_TYPE", ";", "}", "else", "if", "(", "cn", "==", "char_TYPE", ")", "{", "return", "Character_TYPE", ";", "}", "else", "if", "(", "cn", "==", "short_TYPE", ")", "{", "return", "Short_TYPE", ";", "}", "else", "if", "(", "cn", "==", "int_TYPE", ")", "{", "return", "Integer_TYPE", ";", "}", "else", "if", "(", "cn", "==", "long_TYPE", ")", "{", "return", "Long_TYPE", ";", "}", "else", "if", "(", "cn", "==", "float_TYPE", ")", "{", "return", "Float_TYPE", ";", "}", "else", "if", "(", "cn", "==", "double_TYPE", ")", "{", "return", "Double_TYPE", ";", "}", "else", "if", "(", "cn", "==", "VOID_TYPE", ")", "{", "return", "void_WRAPPER_TYPE", ";", "}", "else", "{", "return", "cn", ";", "}", "}" ]
Creates a ClassNode containing the wrapper of a ClassNode of primitive type. Any ClassNode representing a primitive type should be created using the predefined types used in class. The method will check the parameter for known references of ClassNode representing a primitive type. If Reference is found, then a ClassNode will be contained that represents the wrapper class. For example for boolean, the wrapper class is java.lang.Boolean. If the parameter is no primitive type, the redirected ClassNode will be returned @see #make(Class) @see #make(String) @param cn the ClassNode containing a possible primitive type
[ "Creates", "a", "ClassNode", "containing", "the", "wrapper", "of", "a", "ClassNode", "of", "primitive", "type", ".", "Any", "ClassNode", "representing", "a", "primitive", "type", "should", "be", "created", "using", "the", "predefined", "types", "used", "in", "class", ".", "The", "method", "will", "check", "the", "parameter", "for", "known", "references", "of", "ClassNode", "representing", "a", "primitive", "type", ".", "If", "Reference", "is", "found", "then", "a", "ClassNode", "will", "be", "contained", "that", "represents", "the", "wrapper", "class", ".", "For", "example", "for", "boolean", "the", "wrapper", "class", "is", "java", ".", "lang", ".", "Boolean", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/ast/ClassHelper.java#L257-L282
156,495
groovy/groovy-core
src/main/org/codehaus/groovy/ast/ClassHelper.java
ClassHelper.findSAM
public static MethodNode findSAM(ClassNode type) { if (!Modifier.isAbstract(type.getModifiers())) return null; if (type.isInterface()) { List<MethodNode> methods = type.getMethods(); MethodNode found=null; for (MethodNode mi : methods) { // ignore methods, that are not abstract and from Object if (!Modifier.isAbstract(mi.getModifiers())) continue; // ignore trait methods which have a default implementation if (Traits.hasDefaultImplementation(mi)) continue; if (mi.getDeclaringClass().equals(OBJECT_TYPE)) continue; if (OBJECT_TYPE.getDeclaredMethod(mi.getName(), mi.getParameters())!=null) continue; // we have two methods, so no SAM if (found!=null) return null; found = mi; } return found; } else { List<MethodNode> methods = type.getAbstractMethods(); MethodNode found = null; if (methods!=null) { for (MethodNode mi : methods) { if (!hasUsableImplementation(type, mi)) { if (found!=null) return null; found = mi; } } } return found; } }
java
public static MethodNode findSAM(ClassNode type) { if (!Modifier.isAbstract(type.getModifiers())) return null; if (type.isInterface()) { List<MethodNode> methods = type.getMethods(); MethodNode found=null; for (MethodNode mi : methods) { // ignore methods, that are not abstract and from Object if (!Modifier.isAbstract(mi.getModifiers())) continue; // ignore trait methods which have a default implementation if (Traits.hasDefaultImplementation(mi)) continue; if (mi.getDeclaringClass().equals(OBJECT_TYPE)) continue; if (OBJECT_TYPE.getDeclaredMethod(mi.getName(), mi.getParameters())!=null) continue; // we have two methods, so no SAM if (found!=null) return null; found = mi; } return found; } else { List<MethodNode> methods = type.getAbstractMethods(); MethodNode found = null; if (methods!=null) { for (MethodNode mi : methods) { if (!hasUsableImplementation(type, mi)) { if (found!=null) return null; found = mi; } } } return found; } }
[ "public", "static", "MethodNode", "findSAM", "(", "ClassNode", "type", ")", "{", "if", "(", "!", "Modifier", ".", "isAbstract", "(", "type", ".", "getModifiers", "(", ")", ")", ")", "return", "null", ";", "if", "(", "type", ".", "isInterface", "(", ")", ")", "{", "List", "<", "MethodNode", ">", "methods", "=", "type", ".", "getMethods", "(", ")", ";", "MethodNode", "found", "=", "null", ";", "for", "(", "MethodNode", "mi", ":", "methods", ")", "{", "// ignore methods, that are not abstract and from Object", "if", "(", "!", "Modifier", ".", "isAbstract", "(", "mi", ".", "getModifiers", "(", ")", ")", ")", "continue", ";", "// ignore trait methods which have a default implementation", "if", "(", "Traits", ".", "hasDefaultImplementation", "(", "mi", ")", ")", "continue", ";", "if", "(", "mi", ".", "getDeclaringClass", "(", ")", ".", "equals", "(", "OBJECT_TYPE", ")", ")", "continue", ";", "if", "(", "OBJECT_TYPE", ".", "getDeclaredMethod", "(", "mi", ".", "getName", "(", ")", ",", "mi", ".", "getParameters", "(", ")", ")", "!=", "null", ")", "continue", ";", "// we have two methods, so no SAM", "if", "(", "found", "!=", "null", ")", "return", "null", ";", "found", "=", "mi", ";", "}", "return", "found", ";", "}", "else", "{", "List", "<", "MethodNode", ">", "methods", "=", "type", ".", "getAbstractMethods", "(", ")", ";", "MethodNode", "found", "=", "null", ";", "if", "(", "methods", "!=", "null", ")", "{", "for", "(", "MethodNode", "mi", ":", "methods", ")", "{", "if", "(", "!", "hasUsableImplementation", "(", "type", ",", "mi", ")", ")", "{", "if", "(", "found", "!=", "null", ")", "return", "null", ";", "found", "=", "mi", ";", "}", "}", "}", "return", "found", ";", "}", "}" ]
Returns the single abstract method of a class node, if it is a SAM type, or null otherwise. @param type a type for which to search for a single abstract method @return the method node if type is a SAM type, null otherwise
[ "Returns", "the", "single", "abstract", "method", "of", "a", "class", "node", "if", "it", "is", "a", "SAM", "type", "or", "null", "otherwise", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/ast/ClassHelper.java#L395-L428
156,496
groovy/groovy-core
src/main/org/codehaus/groovy/syntax/Types.java
Types.getPrecedence
public static int getPrecedence( int type, boolean throwIfInvalid ) { switch( type ) { case LEFT_PARENTHESIS: return 0; case EQUAL: case PLUS_EQUAL: case MINUS_EQUAL: case MULTIPLY_EQUAL: case DIVIDE_EQUAL: case INTDIV_EQUAL: case MOD_EQUAL: case POWER_EQUAL: case LOGICAL_OR_EQUAL: case LOGICAL_AND_EQUAL: case LEFT_SHIFT_EQUAL: case RIGHT_SHIFT_EQUAL: case RIGHT_SHIFT_UNSIGNED_EQUAL: case BITWISE_OR_EQUAL: case BITWISE_AND_EQUAL: case BITWISE_XOR_EQUAL: return 5; case QUESTION: return 10; case LOGICAL_OR: return 15; case LOGICAL_AND: return 20; case BITWISE_OR: case BITWISE_AND: case BITWISE_XOR: return 22; case COMPARE_IDENTICAL: case COMPARE_NOT_IDENTICAL: return 24; case COMPARE_NOT_EQUAL: case COMPARE_EQUAL: case COMPARE_LESS_THAN: case COMPARE_LESS_THAN_EQUAL: case COMPARE_GREATER_THAN: case COMPARE_GREATER_THAN_EQUAL: case COMPARE_TO: case FIND_REGEX: case MATCH_REGEX: case KEYWORD_INSTANCEOF: return 25; case DOT_DOT: case DOT_DOT_DOT: return 30; case LEFT_SHIFT: case RIGHT_SHIFT: case RIGHT_SHIFT_UNSIGNED: return 35; case PLUS: case MINUS: return 40; case MULTIPLY: case DIVIDE: case INTDIV: case MOD: return 45; case NOT: case REGEX_PATTERN: return 50; case SYNTH_CAST: return 55; case PLUS_PLUS: case MINUS_MINUS: case PREFIX_PLUS_PLUS: case PREFIX_MINUS_MINUS: case POSTFIX_PLUS_PLUS: case POSTFIX_MINUS_MINUS: return 65; case PREFIX_PLUS: case PREFIX_MINUS: return 70; case POWER: return 72; case SYNTH_METHOD: case LEFT_SQUARE_BRACKET: return 75; case DOT: case NAVIGATE: return 80; case KEYWORD_NEW: return 85; } if( throwIfInvalid ) { throw new GroovyBugError( "precedence requested for non-operator" ); } return -1; }
java
public static int getPrecedence( int type, boolean throwIfInvalid ) { switch( type ) { case LEFT_PARENTHESIS: return 0; case EQUAL: case PLUS_EQUAL: case MINUS_EQUAL: case MULTIPLY_EQUAL: case DIVIDE_EQUAL: case INTDIV_EQUAL: case MOD_EQUAL: case POWER_EQUAL: case LOGICAL_OR_EQUAL: case LOGICAL_AND_EQUAL: case LEFT_SHIFT_EQUAL: case RIGHT_SHIFT_EQUAL: case RIGHT_SHIFT_UNSIGNED_EQUAL: case BITWISE_OR_EQUAL: case BITWISE_AND_EQUAL: case BITWISE_XOR_EQUAL: return 5; case QUESTION: return 10; case LOGICAL_OR: return 15; case LOGICAL_AND: return 20; case BITWISE_OR: case BITWISE_AND: case BITWISE_XOR: return 22; case COMPARE_IDENTICAL: case COMPARE_NOT_IDENTICAL: return 24; case COMPARE_NOT_EQUAL: case COMPARE_EQUAL: case COMPARE_LESS_THAN: case COMPARE_LESS_THAN_EQUAL: case COMPARE_GREATER_THAN: case COMPARE_GREATER_THAN_EQUAL: case COMPARE_TO: case FIND_REGEX: case MATCH_REGEX: case KEYWORD_INSTANCEOF: return 25; case DOT_DOT: case DOT_DOT_DOT: return 30; case LEFT_SHIFT: case RIGHT_SHIFT: case RIGHT_SHIFT_UNSIGNED: return 35; case PLUS: case MINUS: return 40; case MULTIPLY: case DIVIDE: case INTDIV: case MOD: return 45; case NOT: case REGEX_PATTERN: return 50; case SYNTH_CAST: return 55; case PLUS_PLUS: case MINUS_MINUS: case PREFIX_PLUS_PLUS: case PREFIX_MINUS_MINUS: case POSTFIX_PLUS_PLUS: case POSTFIX_MINUS_MINUS: return 65; case PREFIX_PLUS: case PREFIX_MINUS: return 70; case POWER: return 72; case SYNTH_METHOD: case LEFT_SQUARE_BRACKET: return 75; case DOT: case NAVIGATE: return 80; case KEYWORD_NEW: return 85; } if( throwIfInvalid ) { throw new GroovyBugError( "precedence requested for non-operator" ); } return -1; }
[ "public", "static", "int", "getPrecedence", "(", "int", "type", ",", "boolean", "throwIfInvalid", ")", "{", "switch", "(", "type", ")", "{", "case", "LEFT_PARENTHESIS", ":", "return", "0", ";", "case", "EQUAL", ":", "case", "PLUS_EQUAL", ":", "case", "MINUS_EQUAL", ":", "case", "MULTIPLY_EQUAL", ":", "case", "DIVIDE_EQUAL", ":", "case", "INTDIV_EQUAL", ":", "case", "MOD_EQUAL", ":", "case", "POWER_EQUAL", ":", "case", "LOGICAL_OR_EQUAL", ":", "case", "LOGICAL_AND_EQUAL", ":", "case", "LEFT_SHIFT_EQUAL", ":", "case", "RIGHT_SHIFT_EQUAL", ":", "case", "RIGHT_SHIFT_UNSIGNED_EQUAL", ":", "case", "BITWISE_OR_EQUAL", ":", "case", "BITWISE_AND_EQUAL", ":", "case", "BITWISE_XOR_EQUAL", ":", "return", "5", ";", "case", "QUESTION", ":", "return", "10", ";", "case", "LOGICAL_OR", ":", "return", "15", ";", "case", "LOGICAL_AND", ":", "return", "20", ";", "case", "BITWISE_OR", ":", "case", "BITWISE_AND", ":", "case", "BITWISE_XOR", ":", "return", "22", ";", "case", "COMPARE_IDENTICAL", ":", "case", "COMPARE_NOT_IDENTICAL", ":", "return", "24", ";", "case", "COMPARE_NOT_EQUAL", ":", "case", "COMPARE_EQUAL", ":", "case", "COMPARE_LESS_THAN", ":", "case", "COMPARE_LESS_THAN_EQUAL", ":", "case", "COMPARE_GREATER_THAN", ":", "case", "COMPARE_GREATER_THAN_EQUAL", ":", "case", "COMPARE_TO", ":", "case", "FIND_REGEX", ":", "case", "MATCH_REGEX", ":", "case", "KEYWORD_INSTANCEOF", ":", "return", "25", ";", "case", "DOT_DOT", ":", "case", "DOT_DOT_DOT", ":", "return", "30", ";", "case", "LEFT_SHIFT", ":", "case", "RIGHT_SHIFT", ":", "case", "RIGHT_SHIFT_UNSIGNED", ":", "return", "35", ";", "case", "PLUS", ":", "case", "MINUS", ":", "return", "40", ";", "case", "MULTIPLY", ":", "case", "DIVIDE", ":", "case", "INTDIV", ":", "case", "MOD", ":", "return", "45", ";", "case", "NOT", ":", "case", "REGEX_PATTERN", ":", "return", "50", ";", "case", "SYNTH_CAST", ":", "return", "55", ";", "case", "PLUS_PLUS", ":", "case", "MINUS_MINUS", ":", "case", "PREFIX_PLUS_PLUS", ":", "case", "PREFIX_MINUS_MINUS", ":", "case", "POSTFIX_PLUS_PLUS", ":", "case", "POSTFIX_MINUS_MINUS", ":", "return", "65", ";", "case", "PREFIX_PLUS", ":", "case", "PREFIX_MINUS", ":", "return", "70", ";", "case", "POWER", ":", "return", "72", ";", "case", "SYNTH_METHOD", ":", "case", "LEFT_SQUARE_BRACKET", ":", "return", "75", ";", "case", "DOT", ":", "case", "NAVIGATE", ":", "return", "80", ";", "case", "KEYWORD_NEW", ":", "return", "85", ";", "}", "if", "(", "throwIfInvalid", ")", "{", "throw", "new", "GroovyBugError", "(", "\"precedence requested for non-operator\"", ")", ";", "}", "return", "-", "1", ";", "}" ]
Returns the precedence of the specified operator. Non-operator's will receive -1 or a GroovyBugError, depending on your preference.
[ "Returns", "the", "precedence", "of", "the", "specified", "operator", ".", "Non", "-", "operator", "s", "will", "receive", "-", "1", "or", "a", "GroovyBugError", "depending", "on", "your", "preference", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/syntax/Types.java#L976-L1089
156,497
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/NullObject.java
NullObject.with
public <T> T with( Closure<T> closure ) { return DefaultGroovyMethods.with( null, closure ) ; }
java
public <T> T with( Closure<T> closure ) { return DefaultGroovyMethods.with( null, closure ) ; }
[ "public", "<", "T", ">", "T", "with", "(", "Closure", "<", "T", ">", "closure", ")", "{", "return", "DefaultGroovyMethods", ".", "with", "(", "null", ",", "closure", ")", ";", "}" ]
Allows the closure to be called for NullObject @param closure the closure to call on the object @return result of calling the closure
[ "Allows", "the", "closure", "to", "be", "called", "for", "NullObject" ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/NullObject.java#L69-L71
156,498
groovy/groovy-core
src/examples/org/codehaus/groovy/grails/compiler/injection/DefaultGrailsDomainClassInjector.java
DefaultGrailsDomainClassInjector.implementsMethod
private static boolean implementsMethod(ClassNode classNode, String methodName, Class[] argTypes) { List methods = classNode.getMethods(); if (argTypes == null || argTypes.length ==0) { for (Iterator i = methods.iterator(); i.hasNext();) { MethodNode mn = (MethodNode) i.next(); boolean methodMatch = mn.getName().equals(methodName); if(methodMatch)return true; // TODO Implement further parameter analysis } } return false; }
java
private static boolean implementsMethod(ClassNode classNode, String methodName, Class[] argTypes) { List methods = classNode.getMethods(); if (argTypes == null || argTypes.length ==0) { for (Iterator i = methods.iterator(); i.hasNext();) { MethodNode mn = (MethodNode) i.next(); boolean methodMatch = mn.getName().equals(methodName); if(methodMatch)return true; // TODO Implement further parameter analysis } } return false; }
[ "private", "static", "boolean", "implementsMethod", "(", "ClassNode", "classNode", ",", "String", "methodName", ",", "Class", "[", "]", "argTypes", ")", "{", "List", "methods", "=", "classNode", ".", "getMethods", "(", ")", ";", "if", "(", "argTypes", "==", "null", "||", "argTypes", ".", "length", "==", "0", ")", "{", "for", "(", "Iterator", "i", "=", "methods", ".", "iterator", "(", ")", ";", "i", ".", "hasNext", "(", ")", ";", ")", "{", "MethodNode", "mn", "=", "(", "MethodNode", ")", "i", ".", "next", "(", ")", ";", "boolean", "methodMatch", "=", "mn", ".", "getName", "(", ")", ".", "equals", "(", "methodName", ")", ";", "if", "(", "methodMatch", ")", "return", "true", ";", "// TODO Implement further parameter analysis\r", "}", "}", "return", "false", ";", "}" ]
Tests whether the ClassNode implements the specified method name @param classNode The ClassNode @param methodName The method name @param argTypes @return True if it implements the method
[ "Tests", "whether", "the", "ClassNode", "implements", "the", "specified", "method", "name" ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/examples/org/codehaus/groovy/grails/compiler/injection/DefaultGrailsDomainClassInjector.java#L243-L254
156,499
groovy/groovy-core
src/main/org/codehaus/groovy/ast/MethodNode.java
MethodNode.getTypeDescriptor
public String getTypeDescriptor() { if (typeDescriptor == null) { StringBuilder buf = new StringBuilder(name.length() + parameters.length * 10); buf.append(returnType.getName()); buf.append(' '); buf.append(name); buf.append('('); for (int i = 0; i < parameters.length; i++) { if (i > 0) { buf.append(", "); } Parameter param = parameters[i]; buf.append(formatTypeName(param.getType())); } buf.append(')'); typeDescriptor = buf.toString(); } return typeDescriptor; }
java
public String getTypeDescriptor() { if (typeDescriptor == null) { StringBuilder buf = new StringBuilder(name.length() + parameters.length * 10); buf.append(returnType.getName()); buf.append(' '); buf.append(name); buf.append('('); for (int i = 0; i < parameters.length; i++) { if (i > 0) { buf.append(", "); } Parameter param = parameters[i]; buf.append(formatTypeName(param.getType())); } buf.append(')'); typeDescriptor = buf.toString(); } return typeDescriptor; }
[ "public", "String", "getTypeDescriptor", "(", ")", "{", "if", "(", "typeDescriptor", "==", "null", ")", "{", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", "name", ".", "length", "(", ")", "+", "parameters", ".", "length", "*", "10", ")", ";", "buf", ".", "append", "(", "returnType", ".", "getName", "(", ")", ")", ";", "buf", ".", "append", "(", "'", "'", ")", ";", "buf", ".", "append", "(", "name", ")", ";", "buf", ".", "append", "(", "'", "'", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "parameters", ".", "length", ";", "i", "++", ")", "{", "if", "(", "i", ">", "0", ")", "{", "buf", ".", "append", "(", "\", \"", ")", ";", "}", "Parameter", "param", "=", "parameters", "[", "i", "]", ";", "buf", ".", "append", "(", "formatTypeName", "(", "param", ".", "getType", "(", ")", ")", ")", ";", "}", "buf", ".", "append", "(", "'", "'", ")", ";", "typeDescriptor", "=", "buf", ".", "toString", "(", ")", ";", "}", "return", "typeDescriptor", ";", "}" ]
The type descriptor for a method node is a string containing the name of the method, its return type, and its parameter types in a canonical form. For simplicity, I'm using the format of a Java declaration without parameter names. @return the type descriptor
[ "The", "type", "descriptor", "for", "a", "method", "node", "is", "a", "string", "containing", "the", "name", "of", "the", "method", "its", "return", "type", "and", "its", "parameter", "types", "in", "a", "canonical", "form", ".", "For", "simplicity", "I", "m", "using", "the", "format", "of", "a", "Java", "declaration", "without", "parameter", "names", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/ast/MethodNode.java#L76-L94