query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Generates a change event for a local update of a document in the given namespace referring to the given document _id. @param namespace the namespace where the document was inserted. @param documentId the _id of the document that was updated. @param update the update specifier. @return a change event for a local update of a document in the given namespace referring to the given document _id.
[ "static ChangeEvent<BsonDocument> changeEventForLocalUpdate(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final UpdateDescription update,\n final BsonDocument fullDocumentAfterUpdate,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.UPDATE,\n fullDocumentAfterUpdate,\n namespace,\n new BsonDocument(\"_id\", documentId),\n update,\n writePending);\n }" ]
[ "private static EndpointReferenceType createEPR(String address, SLProperties props) {\n EndpointReferenceType epr = WSAEndpointReferenceUtils.getEndpointReference(address);\n if (props != null) {\n addProperties(epr, props);\n }\n return epr;\n }", "public Mapping<T> addFields() {\n\n if (idColumn == null) {\n throw new RuntimeException(\"Map ID column before adding class fields\");\n }\n\n for (Field f : ReflectionUtils.getDeclaredFieldsInHierarchy(clazz)) {\n if (!Modifier.isStatic(f.getModifiers())\n && !isFieldMapped(f.getName())\n && !ignoredFields.contains(f.getName())) {\n addColumn(f.getName());\n }\n }\n\n return this;\n }", "public List<String> asList() {\n final List<String> result = new ArrayList<>();\n for (Collection<Argument> args : map.values()) {\n for (Argument arg : args) {\n result.add(arg.asCommandLineArgument());\n }\n }\n return result;\n }", "public void forAllValuePairs(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = attributes.getProperty(ATTRIBUTE_NAME, \"attributes\");\r\n String defaultValue = attributes.getProperty(ATTRIBUTE_DEFAULT_RIGHT, \"\");\r\n String attributePairs = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), name);\r\n\r\n if ((attributePairs == null) || (attributePairs.length() == 0))\r\n {\r\n return;\r\n }\r\n\r\n String token;\r\n int pos;\r\n\r\n for (CommaListIterator it = new CommaListIterator(attributePairs); it.hasNext();)\r\n {\r\n token = it.getNext();\r\n pos = token.indexOf('=');\r\n if (pos >= 0)\r\n {\r\n _curPairLeft = token.substring(0, pos);\r\n _curPairRight = (pos < token.length() - 1 ? token.substring(pos + 1) : defaultValue);\r\n }\r\n else\r\n {\r\n _curPairLeft = token;\r\n _curPairRight = defaultValue;\r\n }\r\n if (_curPairLeft.length() > 0)\r\n {\r\n generate(template);\r\n }\r\n }\r\n _curPairLeft = null;\r\n _curPairRight = null;\r\n }", "public Duration getStartSlack()\n {\n Duration startSlack = (Duration) getCachedValue(TaskField.START_SLACK);\n if (startSlack == null)\n {\n Duration duration = getDuration();\n if (duration != null)\n {\n startSlack = DateHelper.getVariance(this, getEarlyStart(), getLateStart(), duration.getUnits());\n set(TaskField.START_SLACK, startSlack);\n }\n }\n return (startSlack);\n }", "public static Expression type(String lhs, Type rhs) {\n return new Expression(lhs, \"$type\", rhs.toString());\n }", "public HashMap<String, Object> getFirstResult(String query)\n throws Exception {\n HashMap<String, Object> result = null;\n\n Statement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = getConnection()) {\n queryStatement = sqlConnection.createStatement();\n results = queryStatement.executeQuery(query);\n if (results.next()) {\n result = new HashMap<>();\n String[] columns = getColumnNames(results.getMetaData());\n\n for (String column : columns) {\n result.put(column, results.getObject(column));\n }\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return result;\n }", "@Override\n public void close() throws VoldemortException {\n logger.debug(\"Close called for read-only store.\");\n this.fileModificationLock.writeLock().lock();\n\n try {\n if(isOpen) {\n this.isOpen = false;\n fileSet.close();\n } else {\n logger.debug(\"Attempt to close already closed store \" + getName());\n }\n } finally {\n this.fileModificationLock.writeLock().unlock();\n }\n }", "private void populateCurrencySettings(Record record, ProjectProperties properties)\n {\n properties.setCurrencySymbol(record.getString(0));\n properties.setSymbolPosition(record.getCurrencySymbolPosition(1));\n properties.setCurrencyDigits(record.getInteger(2));\n\n Character c = record.getCharacter(3);\n if (c != null)\n {\n properties.setThousandsSeparator(c.charValue());\n }\n\n c = record.getCharacter(4);\n if (c != null)\n {\n properties.setDecimalSeparator(c.charValue());\n }\n }" ]
Sets the number of views for this Photo. For un-authenticated calls this value is not available and will be set to -1. @param views @deprecated attribute no longer available
[ "@Deprecated\r\n public void setViews(String views) {\r\n if (views != null) {\r\n try {\r\n setViews(Integer.parseInt(views));\r\n } catch (NumberFormatException e) {\r\n setViews(-1);\r\n }\r\n }\r\n }" ]
[ "public String p(double value ) {\n return UtilEjml.fancyString(value,format,false,length,significant);\n }", "static PatchingResult executeTasks(final IdentityPatchContext context, final IdentityPatchContext.FinalizeCallback callback) throws Exception {\n final List<PreparedTask> tasks = new ArrayList<PreparedTask>();\n final List<ContentItem> conflicts = new ArrayList<ContentItem>();\n // Identity\n prepareTasks(context.getIdentityEntry(), context, tasks, conflicts);\n // Layers\n for (final IdentityPatchContext.PatchEntry layer : context.getLayers()) {\n prepareTasks(layer, context, tasks, conflicts);\n }\n // AddOns\n for (final IdentityPatchContext.PatchEntry addOn : context.getAddOns()) {\n prepareTasks(addOn, context, tasks, conflicts);\n }\n // If there were problems report them\n if (!conflicts.isEmpty()) {\n throw PatchLogger.ROOT_LOGGER.conflictsDetected(conflicts);\n }\n // Execute the tasks\n for (final PreparedTask task : tasks) {\n // Unless it's excluded by the user\n final ContentItem item = task.getContentItem();\n if (item != null && context.isExcluded(item)) {\n continue;\n }\n // Run the task\n task.execute();\n }\n return context.finalize(callback);\n }", "public static String getColumnSharedPrefix(String[] associationKeyColumns) {\n\t\tString prefix = null;\n\t\tfor ( String column : associationKeyColumns ) {\n\t\t\tString newPrefix = getPrefix( column );\n\t\t\tif ( prefix == null ) { // first iteration\n\t\t\t\tprefix = newPrefix;\n\t\t\t\tif ( prefix == null ) { // no prefix, quit\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse { // subsequent iterations\n\t\t\t\tif ( ! equals( prefix, newPrefix ) ) { // different prefixes\n\t\t\t\t\tprefix = null;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn prefix;\n\t}", "public static <T> JacksonParser<T> json(Class<T> contentType) {\n return new JacksonParser<>(null, contentType);\n }", "public static boolean isFalse(Expression expression) {\r\n if (expression == null) {\r\n return false;\r\n }\r\n if (expression instanceof PropertyExpression && classNodeImplementsType(((PropertyExpression) expression).getObjectExpression().getType(), Boolean.class)) {\r\n if (((PropertyExpression) expression).getProperty() instanceof ConstantExpression\r\n && \"FALSE\".equals(((ConstantExpression) ((PropertyExpression) expression).getProperty()).getValue())) {\r\n return true;\r\n }\r\n }\r\n return ((expression instanceof ConstantExpression) && ((ConstantExpression) expression).isFalseExpression())\r\n || \"Boolean.FALSE\".equals(expression.getText());\r\n }", "public static int hoursDiff(Date earlierDate, Date laterDate) {\n if (earlierDate == null || laterDate == null) {\n return 0;\n }\n\n return (int) ((laterDate.getTime() / HOUR_MILLIS) - (earlierDate.getTime() / HOUR_MILLIS));\n }", "@SuppressWarnings(\"unchecked\")\n public static <E> E getObject(String className) {\n if (className == null) {\n return (E) null;\n }\n try {\n return (E) Class.forName(className).newInstance();\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }", "public static Date getDateFromLong(long date)\n {\n TimeZone tz = TimeZone.getDefault();\n return (new Date(date - tz.getRawOffset()));\n }", "public CredentialsConfig getResolvingCredentialsConfig() {\n if (resolverCredentialsConfig != null && resolverCredentialsConfig.isCredentialsProvided()) {\n return getResolverCredentialsConfig();\n }\n if (deployerCredentialsConfig != null) {\n return getDeployerCredentialsConfig();\n }\n\n return CredentialsConfig.EMPTY_CREDENTIALS_CONFIG;\n }" ]
Validate arguments and state.
[ "private void validate() {\n if (Strings.emptyToNull(random) == null) {\n random = Strings.emptyToNull(getProject().getProperty(SYSPROP_RANDOM_SEED())); \n }\n \n if (random == null) {\n throw new BuildException(\"Required attribute 'seed' must not be empty. Look at <junit4:pickseed>.\");\n }\n \n long[] seeds = SeedUtils.parseSeedChain(random);\n if (seeds.length < 1) {\n throw new BuildException(\"Random seed is required.\");\n }\n \n if (values.isEmpty() && !allowUndefined) {\n throw new BuildException(\"No values to pick from and allowUndefined=false.\");\n }\n }" ]
[ "private int getFixedDataFieldSize(FieldType type)\n {\n int result = 0;\n DataType dataType = type.getDataType();\n if (dataType != null)\n {\n switch (dataType)\n {\n case DATE:\n case INTEGER:\n case DURATION:\n {\n result = 4;\n break;\n }\n\n case TIME_UNITS:\n case CONSTRAINT:\n case PRIORITY:\n case PERCENTAGE:\n case TASK_TYPE:\n case ACCRUE:\n case SHORT:\n case BOOLEAN:\n case DELAY:\n case WORKGROUP:\n case RATE_UNITS:\n case EARNED_VALUE_METHOD:\n case RESOURCE_REQUEST_TYPE:\n {\n result = 2;\n break;\n }\n\n case CURRENCY:\n case UNITS:\n case RATE:\n case WORK:\n {\n result = 8;\n break;\n }\n\n case WORK_UNITS:\n {\n result = 1;\n break;\n }\n\n case GUID:\n {\n result = 16;\n break;\n }\n\n default:\n {\n result = 0;\n break;\n }\n }\n }\n\n return result;\n }", "protected void splitCriteria()\r\n {\r\n Criteria whereCrit = getQuery().getCriteria();\r\n Criteria havingCrit = getQuery().getHavingCriteria();\r\n\r\n if (whereCrit == null || whereCrit.isEmpty())\r\n {\r\n getJoinTreeToCriteria().put(getRoot(), null);\r\n }\r\n else\r\n {\r\n // TODO: parameters list shold be modified when the form is reduced to DNF.\r\n getJoinTreeToCriteria().put(getRoot(), whereCrit);\r\n buildJoinTree(whereCrit);\r\n }\r\n\r\n if (havingCrit != null && !havingCrit.isEmpty())\r\n {\r\n buildJoinTree(havingCrit);\r\n }\r\n\r\n }", "public static dnsnsecrec[] get(nitro_service service, String hostname[]) throws Exception{\n\t\tif (hostname !=null && hostname.length>0) {\n\t\t\tdnsnsecrec response[] = new dnsnsecrec[hostname.length];\n\t\t\tdnsnsecrec obj[] = new dnsnsecrec[hostname.length];\n\t\t\tfor (int i=0;i<hostname.length;i++) {\n\t\t\t\tobj[i] = new dnsnsecrec();\n\t\t\t\tobj[i].set_hostname(hostname[i]);\n\t\t\t\tresponse[i] = (dnsnsecrec) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "static void rethrowIrrecoverableConnectionFailures(IOException e) throws SlaveRegistrationException {\n Throwable cause = e;\n while ((cause = cause.getCause()) != null) {\n if (cause instanceof SaslException) {\n throw HostControllerLogger.ROOT_LOGGER.authenticationFailureUnableToConnect(cause);\n } else if (cause instanceof SSLHandshakeException) {\n throw HostControllerLogger.ROOT_LOGGER.sslFailureUnableToConnect(cause);\n } else if (cause instanceof SlaveRegistrationException) {\n throw (SlaveRegistrationException) cause;\n }\n }\n }", "private static TimeUnit getDurationUnits(Integer value)\n {\n TimeUnit result = null;\n\n if (value != null)\n {\n int index = value.intValue();\n if (index >= 0 && index < DURATION_UNITS.length)\n {\n result = DURATION_UNITS[index];\n }\n }\n\n if (result == null)\n {\n result = TimeUnit.DAYS;\n }\n\n return (result);\n }", "public void visitParameter(String name, int access) {\n if (mv != null) {\n mv.visitParameter(name, access);\n }\n }", "public String getPublicConfigValue(String key) throws ConfigurationException {\n if (!allProps.containsKey(key)) {\n throw new UndefinedPropertyException(\"The requested config key does not exist.\");\n }\n if (restrictedConfigs.contains(key)) {\n throw new ConfigurationException(\"The requested config key is not publicly available!\");\n }\n return allProps.get(key);\n }", "public void onDrawerOpened(View drawerView) {\n super.onDrawerOpened(drawerView);\n if (listener != null) listener.onDrawerClosed(drawerView);\n }", "public void sendLoadTrackCommand(int targetPlayer, int rekordboxId,\n int sourcePlayer, CdjStatus.TrackSourceSlot sourceSlot, CdjStatus.TrackType sourceType)\n throws IOException {\n final DeviceUpdate update = getLatestStatusFor(targetPlayer);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + targetPlayer + \" not found on network.\");\n }\n sendLoadTrackCommand(update, rekordboxId, sourcePlayer, sourceSlot, sourceType);\n }" ]
Returns a collection of all profiles @return Collection of all Profiles @throws Exception exception
[ "public List<Profile> findAllProfiles() throws Exception {\n ArrayList<Profile> allProfiles = new ArrayList<>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_PROFILE);\n results = statement.executeQuery();\n while (results.next()) {\n allProfiles.add(this.getProfileFromResultSet(results));\n }\n } catch (Exception e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n return allProfiles;\n }" ]
[ "private static Path resolveDockerDefinition(Path fullpath) {\n final Path ymlPath = fullpath.resolveSibling(fullpath.getFileName() + \".yml\");\n if (Files.exists(ymlPath)) {\n return ymlPath;\n } else {\n final Path yamlPath = fullpath.resolveSibling(fullpath.getFileName() + \".yaml\");\n if (Files.exists(yamlPath)) {\n return yamlPath;\n }\n }\n\n return null;\n }", "protected CmsAccessControlEntry getImportAccessControlEntry(\n CmsResource res,\n String id,\n String allowed,\n String denied,\n String flags) {\n\n return new CmsAccessControlEntry(\n res.getResourceId(),\n new CmsUUID(id),\n Integer.parseInt(allowed),\n Integer.parseInt(denied),\n Integer.parseInt(flags));\n }", "@PostConstruct\n\tprotected void checkPluginDependencies() throws GeomajasException {\n\t\tif (\"true\".equals(System.getProperty(\"skipPluginDependencyCheck\"))) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (null == declaredPlugins) {\n\t\t\treturn;\n\t\t}\n\n\t\t// start by going through all plug-ins to build a map of versions for plug-in keys\n\t\t// includes verification that each key is only used once\n\t\tMap<String, String> versions = new HashMap<String, String>();\n\t\tfor (PluginInfo plugin : declaredPlugins.values()) {\n\t\t\tString name = plugin.getVersion().getName();\n\t\t\tString version = plugin.getVersion().getVersion();\n\t\t\t// check for multiple plugin with same name but different versions (duplicates allowed for jar+source dep)\n\t\t\tif (null != version) {\n\t\t\t\tString otherVersion = versions.get(name);\n\t\t\t\tif (null != otherVersion) {\n\t\t\t\t\tif (!version.startsWith(EXPR_START)) {\n\t\t\t\t\t\tif (!otherVersion.startsWith(EXPR_START) && !otherVersion.equals(version)) {\n\t\t\t\t\t\t\tthrow new GeomajasException(ExceptionCode.DEPENDENCY_CHECK_INVALID_DUPLICATE,\n\t\t\t\t\t\t\t\t\tname, version, versions.get(name));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tversions.put(name, version);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tversions.put(name, version);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check dependencies\n\t\tStringBuilder message = new StringBuilder();\n\t\tString backendVersion = versions.get(\"Geomajas\");\n\t\tfor (PluginInfo plugin : declaredPlugins.values()) {\n\t\t\tString name = plugin.getVersion().getName();\n\t\t\tmessage.append(checkVersion(name, \"Geomajas back-end\", plugin.getBackendVersion(), backendVersion));\n\t\t\tList<PluginVersionInfo> dependencies = plugin.getDependencies();\n\t\t\tif (null != dependencies) {\n\t\t\t\tfor (PluginVersionInfo dependency : plugin.getDependencies()) {\n\t\t\t\t\tString depName = dependency.getName();\n\t\t\t\t\tmessage.append(checkVersion(name, depName, dependency.getVersion(), versions.get(depName)));\n\t\t\t\t}\n\t\t\t}\n\t\t\tdependencies = plugin.getOptionalDependencies();\n\t\t\tif (null != dependencies) {\n\t\t\t\tfor (PluginVersionInfo dependency : dependencies) {\n\t\t\t\t\tString depName = dependency.getName();\n\t\t\t\t\tString availableVersion = versions.get(depName);\n\t\t\t\t\tif (null != availableVersion) {\n\t\t\t\t\t\tmessage.append(checkVersion(name, depName, dependency.getVersion(), versions.get(depName)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (message.length() > 0) {\n\t\t\tthrow new GeomajasException(ExceptionCode.DEPENDENCY_CHECK_FAILED, message.toString());\n\t\t}\n\n\t\trecorder.record(GROUP, VALUE);\n\t}", "public void add(ServiceReference<D> declarationSRef) {\n D declaration = getDeclaration(declarationSRef);\n boolean matchFilter = declarationFilter.matches(declaration.getMetadata());\n declarations.put(declarationSRef, matchFilter);\n }", "public void setColor(int n, int color) {\n\t\tint firstColor = map[0];\n\t\tint lastColor = map[256-1];\n\t\tif (n > 0)\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\tmap[i] = ImageMath.mixColors((float)i/n, firstColor, color);\n\t\tif (n < 256-1)\n\t\t\tfor (int i = n; i < 256; i++)\n\t\t\t\tmap[i] = ImageMath.mixColors((float)(i-n)/(256-n), color, lastColor);\n\t}", "protected long preConnection() throws SQLException{\r\n\t\tlong statsObtainTime = 0;\r\n\t\t\r\n\t\tif (this.pool.poolShuttingDown){\r\n\t\t\tthrow new SQLException(this.pool.shutdownStackTrace);\r\n\t\t}\r\n\r\n\r\n\t\tif (this.pool.statisticsEnabled){\r\n\t\t\tstatsObtainTime = System.nanoTime();\r\n\t\t\tthis.pool.statistics.incrementConnectionsRequested();\r\n\t\t}\r\n\t\t\r\n\t\treturn statsObtainTime;\r\n\t}", "private String toPath(String name, IconSize size) {\n\n return CmsStringUtil.joinPaths(CmsWorkplace.getSkinUri(), ICON_FOLDER, \"\" + name.hashCode()) + size.getSuffix();\n }", "public static systemuser[] get(nitro_service service) throws Exception{\n\t\tsystemuser obj = new systemuser();\n\t\tsystemuser[] response = (systemuser[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static base_response add(nitro_service client, nsip6 resource) throws Exception {\n\t\tnsip6 addresource = new nsip6();\n\t\taddresource.ipv6address = resource.ipv6address;\n\t\taddresource.scope = resource.scope;\n\t\taddresource.type = resource.type;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.nd = resource.nd;\n\t\taddresource.icmp = resource.icmp;\n\t\taddresource.vserver = resource.vserver;\n\t\taddresource.telnet = resource.telnet;\n\t\taddresource.ftp = resource.ftp;\n\t\taddresource.gui = resource.gui;\n\t\taddresource.ssh = resource.ssh;\n\t\taddresource.snmp = resource.snmp;\n\t\taddresource.mgmtaccess = resource.mgmtaccess;\n\t\taddresource.restrictaccess = resource.restrictaccess;\n\t\taddresource.dynamicrouting = resource.dynamicrouting;\n\t\taddresource.hostroute = resource.hostroute;\n\t\taddresource.ip6hostrtgw = resource.ip6hostrtgw;\n\t\taddresource.metric = resource.metric;\n\t\taddresource.vserverrhilevel = resource.vserverrhilevel;\n\t\taddresource.ospf6lsatype = resource.ospf6lsatype;\n\t\taddresource.ospfarea = resource.ospfarea;\n\t\taddresource.state = resource.state;\n\t\taddresource.map = resource.map;\n\t\taddresource.ownernode = resource.ownernode;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}" ]
Fires the event. @param source the event source @param date the date @param isTyping true if event was caused by user pressing key that may have changed the value
[ "public static void fire(I_CmsHasDateBoxEventHandlers source, Date date, boolean isTyping) {\n\n if (TYPE != null) {\n CmsDateBoxEvent event = new CmsDateBoxEvent(date, isTyping);\n source.fireEvent(event);\n }\n }" ]
[ "synchronized void transitionFailed(final InternalState state) {\n final InternalState current = this.internalState;\n if(state == current) {\n // Revert transition and mark as failed\n switch (current) {\n case PROCESS_ADDING:\n this.internalState = InternalState.PROCESS_STOPPED;\n break;\n case PROCESS_STARTED:\n internalSetState(getTransitionTask(InternalState.PROCESS_STOPPING), InternalState.PROCESS_STARTED, InternalState.PROCESS_ADDED);\n break;\n case PROCESS_STARTING:\n this.internalState = InternalState.PROCESS_ADDED;\n break;\n case SEND_STDIN:\n case SERVER_STARTING:\n this.internalState = InternalState.PROCESS_STARTED;\n break;\n }\n this.requiredState = InternalState.FAILED;\n notifyAll();\n }\n }", "protected static String getTimePrecisionString(byte precision) {\n\t\tswitch (precision) {\n\t\tcase TimeValue.PREC_SECOND:\n\t\t\treturn \"sec\";\n\t\tcase TimeValue.PREC_MINUTE:\n\t\t\treturn \"min\";\n\t\tcase TimeValue.PREC_HOUR:\n\t\t\treturn \"hour\";\n\t\tcase TimeValue.PREC_DAY:\n\t\t\treturn \"day\";\n\t\tcase TimeValue.PREC_MONTH:\n\t\t\treturn \"month\";\n\t\tcase TimeValue.PREC_YEAR:\n\t\t\treturn \"year\";\n\t\tcase TimeValue.PREC_DECADE:\n\t\t\treturn \"decade\";\n\t\tcase TimeValue.PREC_100Y:\n\t\t\treturn \"100 years\";\n\t\tcase TimeValue.PREC_1KY:\n\t\t\treturn \"1000 years\";\n\t\tcase TimeValue.PREC_10KY:\n\t\t\treturn \"10K years\";\n\t\tcase TimeValue.PREC_100KY:\n\t\t\treturn \"100K years\";\n\t\tcase TimeValue.PREC_1MY:\n\t\t\treturn \"1 million years\";\n\t\tcase TimeValue.PREC_10MY:\n\t\t\treturn \"10 million years\";\n\t\tcase TimeValue.PREC_100MY:\n\t\t\treturn \"100 million years\";\n\t\tcase TimeValue.PREC_1GY:\n\t\t\treturn \"1000 million years\";\n\t\tdefault:\n\t\t\treturn \"Unsupported precision \" + precision;\n\t\t}\n\t}", "protected void handleExceptions(MessageEvent messageEvent, Exception exception) {\n logger.error(\"Unknown exception. Internal Server Error.\", exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n \"Internal Server Error\");\n }", "public String getPublicConfigValue(String key) throws ConfigurationException {\n if (!allProps.containsKey(key)) {\n throw new UndefinedPropertyException(\"The requested config key does not exist.\");\n }\n if (restrictedConfigs.contains(key)) {\n throw new ConfigurationException(\"The requested config key is not publicly available!\");\n }\n return allProps.get(key);\n }", "public static <T> T assertNotNull(T value, String name) {\n if (value == null)\n throw new IllegalArgumentException(\"Null \" + name);\n\n return value;\n }", "void createDirectory(Path path) throws IOException {\n\t\tif (Files.exists(path) && Files.isDirectory(path)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.readOnly) {\n\t\t\tthrow new FileNotFoundException(\n\t\t\t\t\t\"The requested directory \\\"\"\n\t\t\t\t\t\t\t+ path.toString()\n\t\t\t\t\t\t\t+ \"\\\" does not exist and we are in read-only mode, so it cannot be created.\");\n\t\t}\n\n\t\tFiles.createDirectory(path);\n\t}", "public static HashMap<String, String> getParameters(String query) {\n HashMap<String, String> params = new HashMap<String, String>();\n if (query == null || query.length() == 0) {\n return params;\n }\n\n String[] splitQuery = query.split(\"&\");\n for (String splitItem : splitQuery) {\n String[] items = splitItem.split(\"=\");\n\n if (items.length == 1) {\n params.put(items[0], \"\");\n } else {\n params.put(items[0], items[1]);\n }\n }\n\n return params;\n }", "public UpdateBuilder<T, ID> updateColumnExpression(String columnName, String expression) throws SQLException {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new SQLException(\"Can't update foreign colletion field: \" + columnName);\n\t\t}\n\t\taddUpdateColumnToList(columnName, new SetExpression(columnName, fieldType, expression));\n\t\treturn this;\n\t}", "public ModelNode buildRequest() throws OperationFormatException {\n\n ModelNode address = request.get(Util.ADDRESS);\n if(prefix.isEmpty()) {\n address.setEmptyList();\n } else {\n Iterator<Node> iterator = prefix.iterator();\n while (iterator.hasNext()) {\n OperationRequestAddress.Node node = iterator.next();\n if (node.getName() != null) {\n address.add(node.getType(), node.getName());\n } else if (iterator.hasNext()) {\n throw new OperationFormatException(\n \"The node name is not specified for type '\"\n + node.getType() + \"'\");\n }\n }\n }\n\n if(!request.hasDefined(Util.OPERATION)) {\n throw new OperationFormatException(\"The operation name is missing or the format of the operation request is wrong.\");\n }\n\n return request;\n }" ]
Retrieve a byte array of containing the data starting at the supplied offset in the FixDeferFix file. Note that this method will return null if the requested data is not found for some reason. @param offset Offset into the file @return Byte array containing the requested data
[ "public byte[] getByteArray(int offset)\n {\n byte[] result = null;\n\n if (offset > 0 && offset < m_data.length)\n {\n int nextBlockOffset = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n int itemSize = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n if (itemSize > 0 && itemSize < m_data.length)\n {\n int blockRemainingSize = 28;\n\n if (nextBlockOffset != -1 || itemSize <= blockRemainingSize)\n {\n int itemRemainingSize = itemSize;\n result = new byte[itemSize];\n int resultOffset = 0;\n\n while (nextBlockOffset != -1)\n {\n MPPUtility.getByteArray(m_data, offset, blockRemainingSize, result, resultOffset);\n resultOffset += blockRemainingSize;\n offset += blockRemainingSize;\n itemRemainingSize -= blockRemainingSize;\n\n if (offset != nextBlockOffset)\n {\n offset = nextBlockOffset;\n }\n\n nextBlockOffset = MPPUtility.getInt(m_data, offset);\n offset += 4;\n blockRemainingSize = 32;\n }\n\n MPPUtility.getByteArray(m_data, offset, itemRemainingSize, result, resultOffset);\n }\n }\n }\n\n return (result);\n }" ]
[ "protected boolean isDuplicate(String eventID) {\n if (this.receivedEvents == null) {\n this.receivedEvents = new LRUCache<String>();\n }\n\n return !this.receivedEvents.add(eventID);\n }", "public int getTrailingBitCount(boolean network) {\n\t\tint count = getDivisionCount();\n\t\tif(count == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tlong back = network ? 0 : getDivision(0).getMaxValue();\n\t\tint bitLen = 0;\n\t\tfor(int i = count - 1; i >= 0; i--) {\n\t\t\tIPAddressDivision seg = getDivision(i);\n\t\t\tlong value = seg.getDivisionValue();\n\t\t\tif(value != back) {\n\t\t\t\treturn bitLen + seg.getTrailingBitCount(network);\n\t\t\t}\n\t\t\tbitLen += seg.getBitCount();\n\t\t}\n\t\treturn bitLen;\n\t}", "public static final long getLong(InputStream is) throws IOException\n {\n byte[] data = new byte[8];\n is.read(data);\n return getLong(data, 0);\n }", "String decodeCString(ByteBuf buffer) throws IOException {\n int length = buffer.bytesBefore(BsonConstants.STRING_TERMINATION);\n if (length < 0)\n throw new IOException(\"string termination not found\");\n\n String result = buffer.toString(buffer.readerIndex(), length, StandardCharsets.UTF_8);\n buffer.skipBytes(length + 1);\n return result;\n }", "boolean processUnstable() {\n boolean change = !unstable;\n if (change) { // Only once until the process is removed. A process is unstable until removed.\n unstable = true;\n HostControllerLogger.ROOT_LOGGER.managedServerUnstable(serverName);\n }\n return change;\n }", "private PlayState3 findPlayState3() {\n PlayState3 result = PLAY_STATE_3_MAP.get(packetBytes[157]);\n if (result == null) {\n return PlayState3.UNKNOWN;\n }\n return result;\n }", "public void removeHoursFromDay(ProjectCalendarHours hours)\n {\n if (hours.getParentCalendar() != this)\n {\n throw new IllegalArgumentException();\n }\n m_hours[hours.getDay().getValue() - 1] = null;\n }", "public int nullity() {\n if( is64 ) {\n return SingularOps_DDRM.nullity((SingularValueDecomposition_F64)svd, 10.0 * UtilEjml.EPS);\n } else {\n return SingularOps_FDRM.nullity((SingularValueDecomposition_F32)svd, 5.0f * UtilEjml.F_EPS);\n }\n }", "public void init(final MultivaluedMap<String, String> queryParameters) {\n final String scopeCompileParam = queryParameters.getFirst(ServerAPI.SCOPE_COMPILE_PARAM);\n if(scopeCompileParam != null){\n this.scopeComp = Boolean.valueOf(scopeCompileParam);\n }\n final String scopeProvidedParam = queryParameters.getFirst(ServerAPI.SCOPE_PROVIDED_PARAM);\n if(scopeProvidedParam != null){\n this.scopePro = Boolean.valueOf(scopeProvidedParam);\n }\n final String scopeRuntimeParam = queryParameters.getFirst(ServerAPI.SCOPE_RUNTIME_PARAM);\n if(scopeRuntimeParam != null){\n this.scopeRun = Boolean.valueOf(scopeRuntimeParam);\n }\n final String scopeTestParam = queryParameters.getFirst(ServerAPI.SCOPE_TEST_PARAM);\n if(scopeTestParam != null){\n this.scopeTest = Boolean.valueOf(scopeTestParam);\n }\n }" ]
Calculate Mode value. @param values Values. @return Returns mode value of the histogram array.
[ "public static int Mode( int[] values ){\n int mode = 0, curMax = 0;\n\n for ( int i = 0, length = values.length; i < length; i++ )\n {\n if ( values[i] > curMax )\n {\n curMax = values[i];\n mode = i;\n }\n }\n return mode;\n }" ]
[ "protected void addFreeConnection(ConnectionHandle connectionHandle) throws SQLException{\r\n\t\tconnectionHandle.setOriginatingPartition(this);\r\n\t\t// assume success to avoid racing where we insert an item in a queue and having that item immediately\r\n\t\t// taken and closed off thus decrementing the created connection count.\r\n\t\tupdateCreatedConnections(1);\r\n\t\tif (!this.disableTracking){\r\n\t\t\ttrackConnectionFinalizer(connectionHandle); \r\n\t\t}\r\n\t\t\r\n\t\t// the instant the following line is executed, consumers can start making use of this \r\n\t\t// connection.\r\n\t\tif (!this.freeConnections.offer(connectionHandle)){\r\n\t\t\t// we failed. rollback.\r\n\t\t\tupdateCreatedConnections(-1); // compensate our createdConnection count.\r\n\t\t\t\r\n\t\t\tif (!this.disableTracking){\r\n\t\t\t\tthis.pool.getFinalizableRefs().remove(connectionHandle.getInternalConnection());\r\n\t\t\t}\r\n\t\t\t// terminate the internal handle.\r\n\t\t\tconnectionHandle.internalClose();\r\n\t\t}\r\n\t}", "protected void endDragging(MouseUpEvent event) {\n\n m_dragging = false;\n DOM.releaseCapture(getElement());\n removeStyleName(I_CmsLayoutBundle.INSTANCE.dialogCss().dragging());\n }", "public void setAttributes(final Map<String, Attribute> attributes) {\n this.internalAttributes = attributes;\n this.allAttributes.putAll(attributes);\n }", "protected Map<String, String> getGalleryOpenParams(\n CmsObject cms,\n CmsMessages messages,\n I_CmsWidgetParameter param,\n String resource,\n long hashId) {\n\n Map<String, String> result = new HashMap<String, String>();\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_MODE, A_CmsAjaxGallery.MODE_WIDGET);\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_STORAGE_PREFIX, getGalleryStoragePrefix());\n result.put(I_CmsGalleryProviderConstants.CONFIG_RESOURCE_TYPES, getGalleryTypes());\n if (param.getId() != null) {\n result.put(I_CmsGalleryProviderConstants.KEY_FIELD_ID, param.getId());\n // use javascript to read the current field value\n result.put(\n I_CmsGalleryProviderConstants.CONFIG_CURRENT_ELEMENT,\n \"'+document.getElementById('\" + param.getId() + \"').getAttribute('value')+'\");\n }\n result.put(I_CmsGalleryProviderConstants.KEY_HASH_ID, \"\" + hashId);\n // the edited resource\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(resource)) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_REFERENCE_PATH, resource);\n }\n // the start up gallery path\n CmsGalleryWidgetConfiguration configuration = getWidgetConfiguration(cms, messages, param);\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(configuration.getStartup())) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_PATH, configuration.getStartup());\n }\n // set gallery types if available\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(configuration.getGalleryTypes())) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_TYPES, configuration.getGalleryTypes());\n }\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_NAME, getGalleryName());\n return result;\n }", "private void init() {\n if (initialized.compareAndSet(false, true)) {\n final RowSorter<? extends TableModel> rowSorter = table.getRowSorter();\n rowSorter.toggleSortOrder(1); // sort by date\n rowSorter.toggleSortOrder(1); // descending\n final TableColumnModel columnModel = table.getColumnModel();\n columnModel.getColumn(1).setCellRenderer(dateRenderer);\n columnModel.getColumn(2).setCellRenderer(sizeRenderer);\n }\n }", "public ProjectCalendar addDefaultBaseCalendar()\n {\n ProjectCalendar calendar = add();\n\n calendar.setName(ProjectCalendar.DEFAULT_BASE_CALENDAR_NAME);\n\n calendar.setWorkingDay(Day.SUNDAY, false);\n calendar.setWorkingDay(Day.MONDAY, true);\n calendar.setWorkingDay(Day.TUESDAY, true);\n calendar.setWorkingDay(Day.WEDNESDAY, true);\n calendar.setWorkingDay(Day.THURSDAY, true);\n calendar.setWorkingDay(Day.FRIDAY, true);\n calendar.setWorkingDay(Day.SATURDAY, false);\n\n calendar.addDefaultCalendarHours();\n\n return (calendar);\n }", "private void readDefinitions()\n {\n for (MapRow row : m_tables.get(\"TTL\"))\n {\n Integer id = row.getInteger(\"DEFINITION_ID\");\n List<MapRow> list = m_definitions.get(id);\n if (list == null)\n {\n list = new ArrayList<MapRow>();\n m_definitions.put(id, list);\n }\n list.add(row);\n }\n\n List<MapRow> rows = m_definitions.get(WBS_FORMAT_ID);\n if (rows != null)\n {\n m_wbsFormat = new SureTrakWbsFormat(rows.get(0));\n }\n }", "public static double extractColumnAndMax( ZMatrixRMaj A ,\n int row0 , int row1 ,\n int col , double u[], int offsetU) {\n int indexU = (offsetU+row0)*2;\n\n // find the largest value in this column\n // this is used to normalize the column and mitigate overflow/underflow\n double max = 0;\n\n int indexA = A.getIndex(row0,col);\n double h[] = A.data;\n\n for( int i = row0; i < row1; i++, indexA += A.numCols*2 ) {\n // copy the householder vector to an array to reduce cache misses\n // big improvement on larger matrices and a relatively small performance hit on small matrices.\n double realVal = u[indexU++] = h[indexA];\n double imagVal = u[indexU++] = h[indexA+1];\n\n double magVal = realVal*realVal + imagVal*imagVal;\n if( max < magVal ) {\n max = magVal;\n }\n }\n return Math.sqrt(max);\n }", "public boolean matchesWithMask(IPAddress other, IPAddress mask) {\n\t\treturn getSection().matchesWithMask(other.getSection(), mask.getSection());\n\t}" ]
Use this API to fetch systemsession resources of given names .
[ "public static systemsession[] get(nitro_service service, Long sid[]) throws Exception{\n\t\tif (sid !=null && sid.length>0) {\n\t\t\tsystemsession response[] = new systemsession[sid.length];\n\t\t\tsystemsession obj[] = new systemsession[sid.length];\n\t\t\tfor (int i=0;i<sid.length;i++) {\n\t\t\t\tobj[i] = new systemsession();\n\t\t\t\tobj[i].set_sid(sid[i]);\n\t\t\t\tresponse[i] = (systemsession) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}" ]
[ "public void setValue(Quaternionf rot) {\n mX = rot.x;\n mY = rot.y;\n mZ = rot.z;\n mW = rot.w;\n }", "private String toResourceNameOnClasspath(String classPathRootOnDisk, File file) {\n String fileName = file.getAbsolutePath().replace(\"\\\\\", \"/\");\n return fileName.substring(classPathRootOnDisk.length());\n }", "private void checkAndAddForbiddenStrings(final List<String> forbiddenSubStrings) {\n\t\tfor( String forbidden : forbiddenSubStrings ) {\n\t\t\tif( forbidden == null ) {\n\t\t\t\tthrow new NullPointerException(\"forbidden substring should not be null\");\n\t\t\t}\n\t\t\tthis.forbiddenSubStrings.add(forbidden);\n\t\t}\n\t}", "public CrosstabBuilder setRowStyles(Style headerStyle, Style totalStyle, Style totalHeaderStyle) {\r\n\t\tcrosstab.setRowHeaderStyle(headerStyle);\r\n\t\tcrosstab.setRowTotalheaderStyle(totalHeaderStyle);\r\n\t\tcrosstab.setRowTotalStyle(totalStyle);\r\n\t\treturn this;\r\n\t}", "public <T extends Widget & Checkable> List<Integer> getCheckedWidgetIndexes() {\n List<Integer> checked = new ArrayList<>();\n List<Widget> children = getChildren();\n\n final int size = children.size();\n for (int i = 0, j = -1; i < size; ++i) {\n Widget c = children.get(i);\n if (c instanceof Checkable) {\n ++j;\n if (((Checkable) c).isChecked()) {\n checked.add(j);\n }\n }\n }\n\n return checked;\n }", "public static boolean organizeAssociationMapByRowKey(\n\t\t\torg.hibernate.ogm.model.spi.Association association,\n\t\t\tAssociationKey key,\n\t\t\tAssociationContext associationContext) {\n\n\t\tif ( association.isEmpty() ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif ( key.getMetadata().getRowKeyIndexColumnNames().length != 1 ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tObject valueOfFirstRow = association.get( association.getKeys().iterator().next() )\n\t\t\t\t.get( key.getMetadata().getRowKeyIndexColumnNames()[0] );\n\n\t\tif ( !( valueOfFirstRow instanceof String ) ) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// The list style may be explicitly enforced for compatibility reasons\n\t\treturn getMapStorage( associationContext ) == MapStorageType.BY_KEY;\n\t}", "public static String retrieveVendorId() {\n if (MapboxTelemetry.applicationContext == null) {\n return updateVendorId();\n }\n\n SharedPreferences sharedPreferences = obtainSharedPreferences(MapboxTelemetry.applicationContext);\n String mapboxVendorId = sharedPreferences.getString(MAPBOX_SHARED_PREFERENCE_KEY_VENDOR_ID, \"\");\n if (TelemetryUtils.isEmpty(mapboxVendorId)) {\n mapboxVendorId = TelemetryUtils.updateVendorId();\n }\n return mapboxVendorId;\n }", "private void addCriteria(List<GenericCriteria> list, byte[] block)\n {\n byte[] leftBlock = getChildBlock(block);\n byte[] rightBlock1 = getListNextBlock(leftBlock);\n byte[] rightBlock2 = getListNextBlock(rightBlock1);\n TestOperator operator = TestOperator.getInstance(MPPUtility.getShort(block, 0) - 0x3E7);\n FieldType leftValue = getFieldType(leftBlock);\n Object rightValue1 = getValue(leftValue, rightBlock1);\n Object rightValue2 = rightBlock2 == null ? null : getValue(leftValue, rightBlock2);\n\n GenericCriteria criteria = new GenericCriteria(m_properties);\n criteria.setLeftValue(leftValue);\n criteria.setOperator(operator);\n criteria.setRightValue(0, rightValue1);\n criteria.setRightValue(1, rightValue2);\n list.add(criteria);\n\n if (m_criteriaType != null)\n {\n m_criteriaType[0] = leftValue.getFieldTypeClass() == FieldTypeClass.TASK;\n m_criteriaType[1] = !m_criteriaType[0];\n }\n\n if (m_fields != null)\n {\n m_fields.add(leftValue);\n }\n\n processBlock(list, getListNextBlock(block));\n }", "public Bundler put(String key, String value) {\n delegate.putString(key, value);\n return this;\n }" ]
if you have a default, it's automatically optional
[ "public ConfigOptionBuilder setDefaultWith( Object defaultValue ) {\n co.setHasDefault( true );\n co.setValue( defaultValue );\n return setOptional();\n }" ]
[ "public void deleteRebalancingState(RebalanceTaskInfo stealInfo) {\n // acquire write lock\n writeLock.lock();\n try {\n RebalancerState rebalancerState = getRebalancerState();\n\n if(!rebalancerState.remove(stealInfo))\n throw new IllegalArgumentException(\"Couldn't find \" + stealInfo + \" in \"\n + rebalancerState + \" while deleting\");\n\n if(rebalancerState.isEmpty()) {\n logger.debug(\"Cleaning all rebalancing state\");\n cleanAllRebalancingState();\n } else {\n put(REBALANCING_STEAL_INFO, rebalancerState);\n initCache(REBALANCING_STEAL_INFO);\n }\n } finally {\n writeLock.unlock();\n }\n }", "public static void write(Path self, String text, String charset) throws IOException {\n Writer writer = null;\n try {\n writer = new OutputStreamWriter(Files.newOutputStream(self, CREATE, APPEND), Charset.forName(charset));\n writer.write(text);\n writer.flush();\n\n Writer temp = writer;\n writer = null;\n temp.close();\n } finally {\n closeWithWarning(writer);\n }\n }", "private void processActivities(Storepoint phoenixProject)\n {\n final AlphanumComparator comparator = new AlphanumComparator();\n List<Activity> activities = phoenixProject.getActivities().getActivity();\n Collections.sort(activities, new Comparator<Activity>()\n {\n @Override public int compare(Activity o1, Activity o2)\n {\n Map<UUID, UUID> codes1 = getActivityCodes(o1);\n Map<UUID, UUID> codes2 = getActivityCodes(o2);\n for (UUID code : m_codeSequence)\n {\n UUID codeValue1 = codes1.get(code);\n UUID codeValue2 = codes2.get(code);\n\n if (codeValue1 == null || codeValue2 == null)\n {\n if (codeValue1 == null && codeValue2 == null)\n {\n continue;\n }\n\n if (codeValue1 == null)\n {\n return -1;\n }\n\n if (codeValue2 == null)\n {\n return 1;\n }\n }\n\n if (!codeValue1.equals(codeValue2))\n {\n Integer sequence1 = m_activityCodeSequence.get(codeValue1);\n Integer sequence2 = m_activityCodeSequence.get(codeValue2);\n\n return NumberHelper.compare(sequence1, sequence2);\n }\n }\n\n return comparator.compare(o1.getId(), o2.getId());\n }\n });\n\n for (Activity activity : activities)\n {\n processActivity(activity);\n }\n }", "public static BuildRetention createBuildRetention(Run build, boolean discardOldArtifacts) {\n BuildRetention buildRetention = new BuildRetention(discardOldArtifacts);\n LogRotator rotator = null;\n BuildDiscarder buildDiscarder = build.getParent().getBuildDiscarder();\n if (buildDiscarder != null && buildDiscarder instanceof LogRotator) {\n rotator = (LogRotator) buildDiscarder;\n }\n if (rotator == null) {\n return buildRetention;\n }\n if (rotator.getNumToKeep() > -1) {\n buildRetention.setCount(rotator.getNumToKeep());\n }\n if (rotator.getDaysToKeep() > -1) {\n Calendar calendar = Calendar.getInstance();\n calendar.add(Calendar.DAY_OF_YEAR, -rotator.getDaysToKeep());\n buildRetention.setMinimumBuildDate(new Date(calendar.getTimeInMillis()));\n }\n List<String> notToBeDeleted = ExtractorUtils.getBuildNumbersNotToBeDeleted(build);\n buildRetention.setBuildNumbersNotToBeDiscarded(notToBeDeleted);\n return buildRetention;\n }", "public static base_responses update(nitro_service client, gslbsite resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbsite updateresources[] = new gslbsite[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new gslbsite();\n\t\t\t\tupdateresources[i].sitename = resources[i].sitename;\n\t\t\t\tupdateresources[i].metricexchange = resources[i].metricexchange;\n\t\t\t\tupdateresources[i].nwmetricexchange = resources[i].nwmetricexchange;\n\t\t\t\tupdateresources[i].sessionexchange = resources[i].sessionexchange;\n\t\t\t\tupdateresources[i].triggermonitor = resources[i].triggermonitor;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public int addKey(String key) {\n JdkUtils.requireNonNull(key);\n int nextIndex = keys.size();\n final Integer mapIndex = JdkUtils.putIfAbsent(keys, key, nextIndex);\n return mapIndex == null ? nextIndex : mapIndex;\n }", "public String getString(String fieldName) {\n\t\treturn hasValue(fieldName) ? String.valueOf(resultMap.get(fieldName)) : null;\n\t}", "public boolean getWorkModified(List<TimephasedWork> list)\n {\n boolean result = false;\n for (TimephasedWork assignment : list)\n {\n result = assignment.getModified();\n if (result)\n {\n break;\n }\n }\n return result;\n }", "public static final double round(double value, double precision)\n {\n precision = Math.pow(10, precision);\n return Math.round(value * precision) / precision;\n }" ]
Gets the visibility modifiers for the property as defined by the getter and setter methods. @return the visibility modifer of the getter, the setter, or both depending on which exist
[ "public int getModifiers() {\n MetaMethod getter = getGetter();\n MetaMethod setter = getSetter();\n if (setter != null && getter == null) return setter.getModifiers();\n if (getter != null && setter == null) return getter.getModifiers();\n int modifiers = getter.getModifiers() | setter.getModifiers();\n int visibility = 0;\n if (Modifier.isPublic(modifiers)) visibility = Modifier.PUBLIC;\n if (Modifier.isProtected(modifiers)) visibility = Modifier.PROTECTED;\n if (Modifier.isPrivate(modifiers)) visibility = Modifier.PRIVATE;\n int states = getter.getModifiers() & setter.getModifiers();\n states &= ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE);\n states |= visibility;\n return states;\n }" ]
[ "protected void convertSearchResults(final Collection<CmsSearchResource> searchResults) {\n\n m_foundResources = new ArrayList<I_CmsSearchResourceBean>();\n for (final CmsSearchResource searchResult : searchResults) {\n m_foundResources.add(new CmsSearchResourceBean(searchResult, m_cmsObject));\n }\n }", "protected boolean intersect(GVRSceneObject.BoundingVolume bv1, GVRSceneObject.BoundingVolume bv2)\n {\n return (bv1.maxCorner.x >= bv2.minCorner.x) &&\n (bv1.maxCorner.y >= bv2.minCorner.y) &&\n (bv1.maxCorner.z >= bv2.minCorner.z) &&\n (bv1.minCorner.x <= bv2.maxCorner.x) &&\n (bv1.minCorner.y <= bv2.maxCorner.y) &&\n (bv1.minCorner.z <= bv2.maxCorner.z);\n }", "private static void bodyWithBuilderAndSeparator(\n SourceBuilder code,\n Datatype datatype,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n String typename) {\n Variable result = new Variable(\"result\");\n Variable separator = new Variable(\"separator\");\n\n code.addLine(\" %1$s %2$s = new %1$s(\\\"%3$s{\\\");\", StringBuilder.class, result, typename);\n if (generatorsByProperty.size() > 1) {\n // If there's a single property, we don't actually use the separator variable\n code.addLine(\" %s %s = \\\"\\\";\", String.class, separator);\n }\n\n Property first = generatorsByProperty.keySet().iterator().next();\n Property last = getLast(generatorsByProperty.keySet());\n for (Property property : generatorsByProperty.keySet()) {\n PropertyCodeGenerator generator = generatorsByProperty.get(property);\n switch (generator.initialState()) {\n case HAS_DEFAULT:\n throw new RuntimeException(\"Internal error: unexpected default field\");\n\n case OPTIONAL:\n code.addLine(\" if (%s) {\", (Excerpt) generator::addToStringCondition);\n break;\n\n case REQUIRED:\n code.addLine(\" if (!%s.contains(%s.%s)) {\",\n UNSET_PROPERTIES, datatype.getPropertyEnum(), property.getAllCapsName());\n break;\n }\n code.add(\" \").add(result);\n if (property != first) {\n code.add(\".append(%s)\", separator);\n }\n code.add(\".append(\\\"%s=\\\").append(%s)\",\n property.getName(), (Excerpt) generator::addToStringValue);\n if (property != last) {\n code.add(\";%n %s = \\\", \\\"\", separator);\n }\n code.add(\";%n }%n\");\n }\n code.addLine(\" return %s.append(\\\"}\\\").toString();\", result);\n }", "public static void close(Statement stmt) {\n try {\n Connection conn = stmt.getConnection();\n try {\n if (!stmt.isClosed())\n stmt.close();\n } catch (UnsupportedOperationException e) {\n // not all JDBC drivers implement the isClosed() method.\n // ugly, but probably the only way to get around this.\n // http://stackoverflow.com/questions/12845385/duke-fast-deduplication-java-lang-unsupportedoperationexception-operation-not\n stmt.close();\n }\n if (conn != null && !conn.isClosed())\n conn.close();\n } catch (SQLException e) {\n throw new DukeException(e);\n }\n }", "@Override public void close() throws IOException\n {\n long skippedLast = 0;\n if (m_remaining > 0)\n {\n skippedLast = skip(m_remaining);\n while (m_remaining > 0 && skippedLast > 0)\n {\n skippedLast = skip(m_remaining);\n }\n }\n }", "public synchronized void submitOperation(int requestId, AsyncOperation operation) {\n if(this.operations.containsKey(requestId))\n throw new VoldemortException(\"Request \" + requestId\n + \" already submitted to the system\");\n\n this.operations.put(requestId, operation);\n scheduler.scheduleNow(operation);\n logger.debug(\"Handling async operation \" + requestId);\n }", "public static final boolean isMouseInside(NativeEvent event, Element element) {\n return isInside(event.getClientX() + Window.getScrollLeft(), event.getClientY() + Window.getScrollTop(), getBounds(element));\n }", "public RedwoodConfiguration rootHandler(final LogRecordHandler handler){\r\n tasks.add(new Runnable(){ public void run(){ Redwood.appendHandler(handler); } });\r\n Redwood.appendHandler(handler);\r\n return this;\r\n }", "public PreparedStatement getUpdateStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getUpdateStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }" ]
Sorts the specified list itself into ascending order, according to the natural ordering of its elements. @param list the list to be sorted. May not be <code>null</code>. @return the sorted list itself. @see Collections#sort(List)
[ "public static <T extends Comparable<? super T>> List<T> sortInplace(List<T> list) {\n\t\tCollections.sort(list);\n\t\treturn list;\n\t}" ]
[ "public void setColorInterpolated(int index, int firstIndex, int lastIndex, int color) {\n\t\tint firstColor = map[firstIndex];\n\t\tint lastColor = map[lastIndex];\n\t\tfor (int i = firstIndex; i <= index; i++)\n\t\t\tmap[i] = ImageMath.mixColors((float)(i-firstIndex)/(index-firstIndex), firstColor, color);\n\t\tfor (int i = index; i < lastIndex; i++)\n\t\t\tmap[i] = ImageMath.mixColors((float)(i-index)/(lastIndex-index), color, lastColor);\n\t}", "public static boolean validate(final String ip) {\n Matcher matcher = pattern.matcher(ip);\n return matcher.matches();\n }", "private ProjectCalendar getTaskCalendar(Project.Tasks.Task task)\n {\n ProjectCalendar calendar = null;\n\n BigInteger calendarID = task.getCalendarUID();\n if (calendarID != null)\n {\n calendar = m_projectFile.getCalendarByUniqueID(Integer.valueOf(calendarID.intValue()));\n }\n\n return (calendar);\n }", "private static StackTraceElement getStackTrace() {\r\n StackTraceElement[] stack = Thread.currentThread().getStackTrace();\r\n\r\n int i = 2; // we can skip the first two (first is getStackTrace(), second is this method)\r\n while (i < stack.length) {\r\n boolean isLoggingClass = false;\r\n for (String loggingClass : loggingClasses) {\r\n String className = stack[i].getClassName();\r\n if (className.startsWith(loggingClass)) {\r\n isLoggingClass = true;\r\n break;\r\n }\r\n }\r\n if (!isLoggingClass) {\r\n break;\r\n }\r\n\r\n i += 1;\r\n }\r\n\r\n // if we didn't find anything, keep last element (probably shouldn't happen, but could if people add too many logging classes)\r\n if (i >= stack.length) {\r\n i = stack.length - 1;\r\n }\r\n return stack[i];\r\n }", "public ValueContainer[] getKeyValues(ClassDescriptor cld, Object objectOrProxy) throws PersistenceBrokerException\r\n {\r\n return getKeyValues(cld, objectOrProxy, true);\r\n }", "public V get(K key) {\n ManagedReference<V> ref = internalMap.get(key);\n if (ref!=null) return ref.get();\n return null;\n }", "public static base_response add(nitro_service client, locationfile resource) throws Exception {\n\t\tlocationfile addresource = new locationfile();\n\t\taddresource.Locationfile = resource.Locationfile;\n\t\taddresource.format = resource.format;\n\t\treturn addresource.add_resource(client);\n\t}", "public boolean isValid() {\n\t\tif(addressProvider.isUninitialized()) {\n\t\t\ttry {\n\t\t\t\tvalidate();\n\t\t\t\treturn true;\n\t\t\t} catch(AddressStringException e) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn !addressProvider.isInvalid();\n\t}", "protected String createGlobalStyle()\n {\n StringBuilder ret = new StringBuilder();\n ret.append(createFontFaces());\n ret.append(\"\\n\");\n ret.append(defaultStyle);\n return ret.toString();\n }" ]
Use this API to update nsdiameter.
[ "public static base_response update(nitro_service client, nsdiameter resource) throws Exception {\n\t\tnsdiameter updateresource = new nsdiameter();\n\t\tupdateresource.identity = resource.identity;\n\t\tupdateresource.realm = resource.realm;\n\t\tupdateresource.serverclosepropagation = resource.serverclosepropagation;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
[ "public Where<T, ID> or(Where<T, ID> left, Where<T, ID> right, Where<T, ID>... others) {\n\t\tClause[] clauses = buildClauseArray(others, \"OR\");\n\t\tClause secondClause = pop(\"OR\");\n\t\tClause firstClause = pop(\"OR\");\n\t\taddClause(new ManyClause(firstClause, secondClause, clauses, ManyClause.OR_OPERATION));\n\t\treturn this;\n\t}", "public void doLocalClear()\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"Clear materialization cache\");\r\n invokeCounter = 0;\r\n enabledReadCache = false;\r\n objectBuffer.clear();\r\n }", "public void addChannel(String boneName, GVRAnimationChannel channel)\n {\n int boneId = mSkeleton.getBoneIndex(boneName);\n if (boneId >= 0)\n {\n mBoneChannels[boneId] = channel;\n mSkeleton.setBoneOptions(boneId, GVRSkeleton.BONE_ANIMATE);\n Log.d(\"BONE\", \"Adding animation channel %d %s \", boneId, boneName);\n }\n }", "public GridCoverage2D call() {\n try {\n BufferedImage coverageImage = this.tiledLayer.createBufferedImage(\n this.tilePreparationInfo.getImageWidth(),\n this.tilePreparationInfo.getImageHeight());\n Graphics2D graphics = coverageImage.createGraphics();\n try {\n for (SingleTilePreparationInfo tileInfo: this.tilePreparationInfo.getSingleTiles()) {\n final TileTask task;\n if (tileInfo.getTileRequest() != null) {\n task = new SingleTileLoaderTask(\n tileInfo.getTileRequest(), this.errorImage, tileInfo.getTileIndexX(),\n tileInfo.getTileIndexY(), this.failOnError, this.registry, this.context);\n } else {\n task = new PlaceHolderImageTask(this.tiledLayer.getMissingTileImage(),\n tileInfo.getTileIndexX(), tileInfo.getTileIndexY());\n }\n Tile tile = task.call();\n if (tile.getImage() != null) {\n graphics.drawImage(tile.getImage(),\n tile.getxIndex() * this.tiledLayer.getTileSize().width,\n tile.getyIndex() * this.tiledLayer.getTileSize().height, null);\n }\n }\n } finally {\n graphics.dispose();\n }\n\n GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null);\n GeneralEnvelope gridEnvelope = new GeneralEnvelope(this.tilePreparationInfo.getMapProjection());\n gridEnvelope.setEnvelope(this.tilePreparationInfo.getGridCoverageOrigin().x,\n this.tilePreparationInfo.getGridCoverageOrigin().y,\n this.tilePreparationInfo.getGridCoverageMaxX(),\n this.tilePreparationInfo.getGridCoverageMaxY());\n return factory.create(this.tiledLayer.createCommonUrl(), coverageImage, gridEnvelope,\n null, null, null);\n } catch (Exception e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }", "public static base_response delete(nitro_service client, dnsaaaarec resource) throws Exception {\n\t\tdnsaaaarec deleteresource = new dnsaaaarec();\n\t\tdeleteresource.hostname = resource.hostname;\n\t\tdeleteresource.ipv6address = resource.ipv6address;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "static void processRoot(final File root, final ProcessedLayers layers, final LayerPathSetter setter) throws IOException {\n final LayersConfig layersConfig = LayersConfig.getLayersConfig(root);\n // Process layers\n final File layersDir = new File(root, layersConfig.getLayersPath());\n if (!layersDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationNoLayersConfigFound(layersDir.getAbsolutePath());\n }\n // else this isn't a root that has layers and add-ons\n } else {\n // check for a valid layer configuration\n for (final String layer : layersConfig.getLayers()) {\n File layerDir = new File(layersDir, layer);\n if (!layerDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationMissingLayer(layer, layersDir.getAbsolutePath());\n }\n // else this isn't a standard layers and add-ons structure\n return;\n }\n layers.addLayer(layer, layerDir, setter);\n }\n }\n // Finally process the add-ons\n final File addOnsDir = new File(root, layersConfig.getAddOnsPath());\n final File[] addOnsList = addOnsDir.listFiles();\n if (addOnsList != null) {\n for (final File addOn : addOnsList) {\n layers.addAddOn(addOn.getName(), addOn, setter);\n }\n }\n }", "public String getUuidFromResponse(ResponseOnSingeRequest myResponse) {\n\n String uuid = PcConstants.NA;\n String responseBody = myResponse.getResponseBody();\n Pattern regex = Pattern.compile(getJobIdRegex());\n Matcher matcher = regex.matcher(responseBody);\n if (matcher.matches()) {\n uuid = matcher.group(1);\n }\n\n return uuid;\n }", "public static clusterinstance[] get(nitro_service service) throws Exception{\n\t\tclusterinstance obj = new clusterinstance();\n\t\tclusterinstance[] response = (clusterinstance[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private List<ModelNode> describeAsNodeList(PathAddress rootAddress, final Resource resource, boolean isRuntimeChange) {\n final List<ModelNode> list = new ArrayList<ModelNode>();\n\n describe(rootAddress, resource, list, isRuntimeChange);\n return list;\n }" ]
Use this API to convert sslpkcs12.
[ "public static base_response convert(nitro_service client, sslpkcs12 resource) throws Exception {\n\t\tsslpkcs12 convertresource = new sslpkcs12();\n\t\tconvertresource.outfile = resource.outfile;\n\t\tconvertresource.Import = resource.Import;\n\t\tconvertresource.pkcs12file = resource.pkcs12file;\n\t\tconvertresource.des = resource.des;\n\t\tconvertresource.des3 = resource.des3;\n\t\tconvertresource.export = resource.export;\n\t\tconvertresource.certfile = resource.certfile;\n\t\tconvertresource.keyfile = resource.keyfile;\n\t\tconvertresource.password = resource.password;\n\t\tconvertresource.pempassphrase = resource.pempassphrase;\n\t\treturn convertresource.perform_operation(client,\"convert\");\n\t}" ]
[ "public static base_response clear(nitro_service client) throws Exception {\n\t\tnspbr6 clearresource = new nspbr6();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}", "public static <T, ID> int dropTable(ConnectionSource connectionSource, Class<T> dataClass, boolean ignoreErrors)\n\t\t\tthrows SQLException {\n\t\tDao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);\n\t\treturn dropTable(dao, ignoreErrors);\n\t}", "public ViewPort then(Functions.Func1<ViewPortChange> then, ViewPortFallback fallback) {\n assert then != null : \"'then' callback cannot be null\";\n this.then = then;\n this.fallback = fallback;\n return load();\n }", "private boolean isSplit(ProjectCalendar calendar, List<TimephasedWork> list)\n {\n boolean result = false;\n for (TimephasedWork assignment : list)\n {\n if (calendar != null && assignment.getTotalAmount().getDuration() == 0)\n {\n Duration calendarWork = calendar.getWork(assignment.getStart(), assignment.getFinish(), TimeUnit.MINUTES);\n if (calendarWork.getDuration() != 0)\n {\n result = true;\n break;\n }\n }\n }\n return result;\n }", "public double getCouponPayment(int periodIndex, AnalyticModel model) {\n\n\t\tForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName);\n\t\tif(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {\n\t\t\tthrow new IllegalArgumentException(\"No forward curve with name '\" + forwardCurveName + \"' was found in the model:\\n\" + model.toString());\n\t\t}\n\n\t\tdouble periodLength\t= schedule.getPeriodLength(periodIndex);\n\t\tdouble couponPayment=fixedCoupon ;\n\t\tif(forwardCurve != null ) {\n\t\t\tcouponPayment = floatingSpread+forwardCurve.getForward(model, schedule.getFixing(periodIndex));\n\t\t}\n\t\treturn couponPayment*periodLength;\n\t}", "protected void processTaskBaseline(Row row)\n {\n Integer id = row.getInteger(\"TASK_UID\");\n Task task = m_project.getTaskByUniqueID(id);\n if (task != null)\n {\n int index = row.getInt(\"TB_BASE_NUM\");\n\n task.setBaselineDuration(index, MPDUtility.getAdjustedDuration(m_project, row.getInt(\"TB_BASE_DUR\"), MPDUtility.getDurationTimeUnits(row.getInt(\"TB_BASE_DUR_FMT\"))));\n task.setBaselineStart(index, row.getDate(\"TB_BASE_START\"));\n task.setBaselineFinish(index, row.getDate(\"TB_BASE_FINISH\"));\n task.setBaselineWork(index, row.getDuration(\"TB_BASE_WORK\"));\n task.setBaselineCost(index, row.getCurrency(\"TB_BASE_COST\"));\n }\n }", "private EditorState getMasterState() {\n\n List<TableProperty> cols = new ArrayList<TableProperty>(4);\n cols.add(TableProperty.KEY);\n cols.add(TableProperty.DESCRIPTION);\n cols.add(TableProperty.DEFAULT);\n cols.add(TableProperty.TRANSLATION);\n return new EditorState(cols, true);\n }", "public static Credential getServiceAccountCredential(String serviceAccountId,\n String privateKeyFile, Collection<String> serviceAccountScopes)\n throws GeneralSecurityException, IOException {\n return getCredentialBuilderWithoutPrivateKey(serviceAccountId, serviceAccountScopes)\n .setServiceAccountPrivateKeyFromP12File(new File(privateKeyFile))\n .build();\n }", "public UriComponentsBuilder replaceQueryParam(String name, Object... values) {\n\t\tAssert.notNull(name, \"'name' must not be null\");\n\t\tthis.queryParams.remove(name);\n\t\tif (!ObjectUtils.isEmpty(values)) {\n\t\t\tqueryParam(name, values);\n\t\t}\n\t\tresetSchemeSpecificPart();\n\t\treturn this;\n\t}" ]
Generated the report.
[ "@Override\n public void postCrawling(CrawlSession session, ExitStatus exitStatus) {\n LOG.debug(\"postCrawling\");\n StateFlowGraph sfg = session.getStateFlowGraph();\n checkSFG(sfg);\n // TODO: call state abstraction function to get distance matrix and run rscript on it to\n // create clusters\n String[][] clusters = null;\n // generateClusters(session);\n\n result = outModelCache.close(session, exitStatus, clusters);\n\n outputBuilder.write(result, session.getConfig(), clusters);\n StateWriter writer =\n new StateWriter(outputBuilder, sfg, ImmutableMap.copyOf(visitedStates));\n for (State state : result.getStates().values()) {\n try {\n writer.writeHtmlForState(state);\n } catch (Exception Ex) {\n LOG.info(\"couldn't write state :\" + state.getName());\n }\n }\n LOG.info(\"Crawl overview plugin has finished\");\n }" ]
[ "@Pure\n\t@Inline(value = \"$3.union($1, $2)\", imported = MapExtensions.class)\n\tpublic static <K, V> Map<K, V> operator_plus(Map<K, V> left, Map<? extends K, ? extends V> right) {\n\t\treturn union(left, right);\n\t}", "public String getAttribute(String section, String name) {\n Attributes attr = getManifest().getAttributes(section);\n return attr != null ? attr.getValue(name) : null;\n }", "public NestedDef getNested(String name)\r\n {\r\n NestedDef nestedDef = null;\r\n\r\n for (Iterator it = _nested.iterator(); it.hasNext(); )\r\n {\r\n nestedDef = (NestedDef)it.next();\r\n if (nestedDef.getName().equals(name))\r\n {\r\n return nestedDef;\r\n }\r\n }\r\n return null;\r\n }", "private Entry getEntry(Object key)\r\n {\r\n if (key == null) return null;\r\n int hash = hashCode(key);\r\n int index = indexFor(hash);\r\n for (Entry entry = table[index]; entry != null; entry = entry.next)\r\n {\r\n if ((entry.hash == hash) && equals(key, entry.getKey()))\r\n {\r\n return entry;\r\n }\r\n }\r\n return null;\r\n }", "private boolean markAsObsolete(ContentReference ref) {\n if (obsoleteContents.containsKey(ref.getHexHash())) { //This content is already marked as obsolete\n if (obsoleteContents.get(ref.getHexHash()) + obsolescenceTimeout < System.currentTimeMillis()) {\n DeploymentRepositoryLogger.ROOT_LOGGER.obsoleteContentCleaned(ref.getContentIdentifier());\n removeContent(ref);\n return true;\n }\n } else {\n obsoleteContents.put(ref.getHexHash(), System.currentTimeMillis()); //Mark content as obsolete\n }\n return false;\n }", "private void initStoreDefinitions(Version storesXmlVersion) {\n if(this.storeDefinitionsStorageEngine == null) {\n throw new VoldemortException(\"The store definitions directory is empty\");\n }\n\n String allStoreDefinitions = \"<stores>\";\n Version finalStoresXmlVersion = null;\n if(storesXmlVersion != null) {\n finalStoresXmlVersion = storesXmlVersion;\n }\n this.storeNames.clear();\n\n ClosableIterator<Pair<String, Versioned<String>>> storesIterator = this.storeDefinitionsStorageEngine.entries();\n\n // Some test setups may result in duplicate entries for 'store' element.\n // Do the de-dup here\n Map<String, Versioned<String>> storeNameToDefMap = new HashMap<String, Versioned<String>>();\n Version maxVersion = null;\n while(storesIterator.hasNext()) {\n Pair<String, Versioned<String>> storeDetail = storesIterator.next();\n String storeName = storeDetail.getFirst();\n Versioned<String> versionedStoreDef = storeDetail.getSecond();\n storeNameToDefMap.put(storeName, versionedStoreDef);\n Version curVersion = versionedStoreDef.getVersion();\n\n // Get the highest version from all the store entries\n if(maxVersion == null) {\n maxVersion = curVersion;\n } else if(maxVersion.compare(curVersion) == Occurred.BEFORE) {\n maxVersion = curVersion;\n }\n }\n\n // If the specified version is null, assign highest Version to\n // 'stores.xml' key\n if(finalStoresXmlVersion == null) {\n finalStoresXmlVersion = maxVersion;\n }\n\n // Go through all the individual stores and update metadata\n for(Entry<String, Versioned<String>> storeEntry: storeNameToDefMap.entrySet()) {\n String storeName = storeEntry.getKey();\n Versioned<String> versionedStoreDef = storeEntry.getValue();\n\n // Add all the store names to the list of storeNames\n this.storeNames.add(storeName);\n\n this.metadataCache.put(storeName, new Versioned<Object>(versionedStoreDef.getValue(),\n versionedStoreDef.getVersion()));\n }\n\n Collections.sort(this.storeNames);\n for(String storeName: this.storeNames) {\n Versioned<String> versionedStoreDef = storeNameToDefMap.get(storeName);\n // Stitch together to form the complete store definition list.\n allStoreDefinitions += versionedStoreDef.getValue();\n\n }\n\n allStoreDefinitions += \"</stores>\";\n\n // Update cache with the composite store definition list.\n metadataCache.put(STORES_KEY,\n convertStringToObject(STORES_KEY,\n new Versioned<String>(allStoreDefinitions,\n finalStoresXmlVersion)));\n }", "private void setTableAliasForClassDescriptor(ClassDescriptor aCld, TableAlias anAlias)\r\n {\r\n if (m_cldToAlias.get(aCld) == null)\r\n {\r\n m_cldToAlias.put(aCld, anAlias);\r\n } \r\n }", "private boolean isSecuredByPolicy(Server server) {\n boolean isSecured = false;\n\n EndpointInfo ei = server.getEndpoint().getEndpointInfo();\n\n PolicyEngine pe = bus.getExtension(PolicyEngine.class);\n if (null == pe) {\n LOG.finest(\"No Policy engine found\");\n return isSecured;\n }\n\n Destination destination = server.getDestination();\n EndpointPolicy ep = pe.getServerEndpointPolicy(ei, destination, null);\n Collection<Assertion> assertions = ep.getChosenAlternative();\n for (Assertion a : assertions) {\n if (a instanceof TransportBinding) {\n TransportBinding tb = (TransportBinding) a;\n TransportToken tt = tb.getTransportToken();\n AbstractToken t = tt.getToken();\n if (t instanceof HttpsToken) {\n isSecured = true;\n break;\n }\n }\n }\n\n Policy policy = ep.getPolicy();\n List<PolicyComponent> pcList = policy.getPolicyComponents();\n for (PolicyComponent a : pcList) {\n if (a instanceof TransportBinding) {\n TransportBinding tb = (TransportBinding) a;\n TransportToken tt = tb.getTransportToken();\n AbstractToken t = tt.getToken();\n if (t instanceof HttpsToken) {\n isSecured = true;\n break;\n }\n }\n }\n\n return isSecured;\n }", "public static base_responses delete(nitro_service client, String ipv6address[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (ipv6address != null && ipv6address.length > 0) {\n\t\t\tnsip6 deleteresources[] = new nsip6[ipv6address.length];\n\t\t\tfor (int i=0;i<ipv6address.length;i++){\n\t\t\t\tdeleteresources[i] = new nsip6();\n\t\t\t\tdeleteresources[i].ipv6address = ipv6address[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Releases a database connection, and cleans up any resources associated with that connection.
[ "private void releaseConnection()\n {\n if (m_rs != null)\n {\n try\n {\n m_rs.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore errors on close\n }\n\n m_rs = null;\n }\n\n if (m_ps != null)\n {\n try\n {\n m_ps.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore errors on close\n }\n\n m_ps = null;\n }\n }" ]
[ "public void processAnonymousField(Properties attributes) throws XDocletException\r\n {\r\n if (!attributes.containsKey(ATTRIBUTE_NAME))\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.PARAMETER_IS_REQUIRED,\r\n new String[]{ATTRIBUTE_NAME}));\r\n }\r\n\r\n String name = attributes.getProperty(ATTRIBUTE_NAME);\r\n FieldDescriptorDef fieldDef = _curClassDef.getField(name);\r\n String attrName;\r\n\r\n if (fieldDef == null)\r\n {\r\n fieldDef = new FieldDescriptorDef(name);\r\n _curClassDef.addField(fieldDef);\r\n }\r\n fieldDef.setAnonymous();\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processAnonymousField\", \" Processing anonymous field \"+fieldDef.getName());\r\n\r\n attributes.remove(ATTRIBUTE_NAME);\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n fieldDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_ACCESS, \"anonymous\");\r\n }", "public static wisite_accessmethod_binding[] get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_accessmethod_binding obj = new wisite_accessmethod_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_accessmethod_binding response[] = (wisite_accessmethod_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@Override\r\n public String upload(File file, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(file);\r\n return sendUploadRequest(metaData, payload);\r\n }", "protected static final String formatUsingFormat(Long value, DateTimeFormat fmt) {\n if (value == null) {\n return \"\";\n }\n else {\n // midnight GMT\n Date date = new Date(0);\n // offset by timezone and value\n date.setTime(UTCDateBox.timezoneOffsetMillis(date) + value.longValue());\n // format it\n return fmt.format(date);\n }\n }", "public static void startTimer(final String type) {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return;\n }\n\n instance.components.putIfAbsent(type, new Component(type));\n instance.components.get(type).startTimer();\n }", "private void writeAssignments() throws IOException\n {\n writeAttributeTypes(\"assignment_types\", AssignmentField.values());\n\n m_writer.writeStartList(\"assignments\");\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n writeFields(null, assignment, AssignmentField.values());\n }\n m_writer.writeEndList();\n\n }", "public static nstrafficdomain_bridgegroup_binding[] get(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_bridgegroup_binding obj = new nstrafficdomain_bridgegroup_binding();\n\t\tobj.set_td(td);\n\t\tnstrafficdomain_bridgegroup_binding response[] = (nstrafficdomain_bridgegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public String getCanonicalTypeName(Object object) {\n ensureNotNull(\"object\", object);\n\n for (TypeDetector typeDetector : typeDetectors) {\n if (typeDetector.canHandle(object)) {\n return typeDetector.detectType(object);\n }\n }\n\n throw LOG.unableToDetectCanonicalType(object);\n }", "protected void mergeSameCost(LinkedList<TimephasedCost> list)\n {\n LinkedList<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n TimephasedCost previousAssignment = null;\n for (TimephasedCost assignment : list)\n {\n if (previousAssignment == null)\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n result.add(assignment);\n }\n else\n {\n Number previousAssignmentCost = previousAssignment.getAmountPerDay();\n Number assignmentCost = assignment.getTotalAmount();\n\n if (NumberHelper.equals(previousAssignmentCost.doubleValue(), assignmentCost.doubleValue(), 0.01))\n {\n Date assignmentStart = previousAssignment.getStart();\n Date assignmentFinish = assignment.getFinish();\n double total = previousAssignment.getTotalAmount().doubleValue();\n total += assignmentCost.doubleValue();\n\n TimephasedCost merged = new TimephasedCost();\n merged.setStart(assignmentStart);\n merged.setFinish(assignmentFinish);\n merged.setAmountPerDay(assignmentCost);\n merged.setTotalAmount(Double.valueOf(total));\n\n result.removeLast();\n assignment = merged;\n }\n else\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n }\n result.add(assignment);\n }\n\n previousAssignment = assignment;\n }\n\n list.clear();\n list.addAll(result);\n }" ]
Initialization method. @param t1 @param t2
[ "public void init(LblTree t1, LblTree t2) {\n\t\tLabelDictionary ld = new LabelDictionary();\n\t\tit1 = new InfoTree(t1, ld);\n\t\tit2 = new InfoTree(t2, ld);\n\t\tsize1 = it1.getSize();\n\t\tsize2 = it2.getSize();\n\t\tIJ = new int[Math.max(size1, size2)][Math.max(size1, size2)];\n\t\tdelta = new double[size1][size2];\n\t\tdeltaBit = new byte[size1][size2];\n\t\tcostV = new long[3][size1][size2];\n\t\tcostW = new long[3][size2];\n\n\t\t// Calculate delta between every leaf in G (empty tree) and all the nodes in F.\n\t\t// Calculate it both sides: leafs of F and nodes of G & leafs of G and nodes of\n\t\t// F.\n\t\tint[] labels1 = it1.getInfoArray(POST2_LABEL);\n\t\tint[] labels2 = it2.getInfoArray(POST2_LABEL);\n\t\tint[] sizes1 = it1.getInfoArray(POST2_SIZE);\n\t\tint[] sizes2 = it2.getInfoArray(POST2_SIZE);\n\t\tfor (int x = 0; x < sizes1.length; x++) { // for all nodes of initially left tree\n\t\t\tfor (int y = 0; y < sizes2.length; y++) { // for all nodes of initially right tree\n\n\t\t\t\t// This is an attempt for distances of single-node subtree and anything alse\n\t\t\t\t// The differences between pairs of labels are stored\n\t\t\t\tif (labels1[x] == labels2[y]) {\n\t\t\t\t\tdeltaBit[x][y] = 0;\n\t\t\t\t} else {\n\t\t\t\t\tdeltaBit[x][y] =\n\t\t\t\t\t\t\t1; // if this set, the labels differ, cost of relabeling is set\n\t\t\t\t\t// to costMatch\n\t\t\t\t}\n\n\t\t\t\tif (sizes1[x] == 1 && sizes2[y] == 1) { // both nodes are leafs\n\t\t\t\t\tdelta[x][y] = 0;\n\t\t\t\t} else {\n\t\t\t\t\tif (sizes1[x] == 1) {\n\t\t\t\t\t\tdelta[x][y] = sizes2[y] - 1;\n\t\t\t\t\t}\n\t\t\t\t\tif (sizes2[y] == 1) {\n\t\t\t\t\t\tdelta[x][y] = sizes1[x] - 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}" ]
[ "public CollectionRequest<Section> findByProject(String project) {\n \n String path = String.format(\"/projects/%s/sections\", project);\n return new CollectionRequest<Section>(this, Section.class, path, \"GET\");\n }", "public void setWeekDays(SortedSet<WeekDay> weekDays) {\n\n final SortedSet<WeekDay> newWeekDays = null == weekDays ? new TreeSet<WeekDay>() : weekDays;\n SortedSet<WeekDay> currentWeekDays = m_model.getWeekDays();\n if (!currentWeekDays.equals(newWeekDays)) {\n conditionallyRemoveExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDays(newWeekDays);\n onValueChange();\n }\n }, !newWeekDays.containsAll(m_model.getWeekDays()));\n }\n }", "@Nullable\n public final String getStringContent(final long blobHandle, @NotNull final Transaction txn) throws IOException {\n String result;\n result = stringContentCache.tryKey(this, blobHandle);\n if (result == null) {\n final InputStream content = getContent(blobHandle, txn);\n if (content == null) {\n logger.error(\"Blob string not found: \" + getBlobLocation(blobHandle), new FileNotFoundException());\n }\n result = content == null ? null : UTFUtil.readUTF(content);\n if (result != null && result.length() <= config.getBlobStringsCacheMaxValueSize()) {\n if (stringContentCache.getObject(this, blobHandle) == null) {\n stringContentCache.cacheObject(this, blobHandle, result);\n }\n }\n }\n return result;\n }", "AlbumArt getArtwork(int artworkId, SlotReference slot, CdjStatus.TrackType trackType, Client client)\n throws IOException {\n\n // Send the artwork request\n Message response = client.simpleRequest(Message.KnownType.ALBUM_ART_REQ, Message.KnownType.ALBUM_ART,\n client.buildRMST(Message.MenuIdentifier.DATA, slot.slot, trackType), new NumberField((long)artworkId));\n\n // Create an image from the response bytes\n return new AlbumArt(new DataReference(slot, artworkId), ((BinaryField)response.arguments.get(3)).getValue());\n }", "public F resolve(R resolvable, boolean cache) {\n R wrappedResolvable = wrap(resolvable);\n if (cache) {\n return resolved.getValue(wrappedResolvable);\n } else {\n return resolverFunction.apply(wrappedResolvable);\n }\n }", "public List<Response> bulk(List<?> objects, boolean allOrNothing) {\n assertNotEmpty(objects, \"objects\");\n InputStream responseStream = null;\n HttpConnection connection;\n try {\n final JsonObject jsonObject = new JsonObject();\n if(allOrNothing) {\n jsonObject.addProperty(\"all_or_nothing\", true);\n }\n final URI uri = new DatabaseURIHelper(dbUri).bulkDocsUri();\n jsonObject.add(\"docs\", getGson().toJsonTree(objects));\n connection = Http.POST(uri, \"application/json\");\n if (jsonObject.toString().length() != 0) {\n connection.setRequestBody(jsonObject.toString());\n }\n couchDbClient.execute(connection);\n responseStream = connection.responseAsInputStream();\n List<Response> bulkResponses = getResponseList(responseStream, getGson(),\n DeserializationTypes.LC_RESPONSES);\n for(Response response : bulkResponses) {\n response.setStatusCode(connection.getConnection().getResponseCode());\n }\n return bulkResponses;\n }\n catch (IOException e) {\n throw new CouchDbException(\"Error retrieving response input stream.\", e);\n } finally {\n close(responseStream);\n }\n }", "public static int getIbanLength(final CountryCode countryCode) {\n final BbanStructure structure = getBbanStructure(countryCode);\n return COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH + structure.getBbanLength();\n }", "@UiHandler(\"m_addButton\")\r\n void addButtonClick(ClickEvent e) {\r\n\r\n if (null != m_newDate.getValue()) {\r\n m_dateList.addDate(m_newDate.getValue());\r\n m_newDate.setValue(null);\r\n if (handleChange()) {\r\n m_controller.setDates(m_dateList.getDates());\r\n }\r\n }\r\n }", "public ParallelTaskBuilder setSshPassword(String password) {\n this.sshMeta.setPassword(password);\n this.sshMeta.setSshLoginType(SshLoginType.PASSWORD);\n return this;\n }" ]
Returns the configured fields of the current field configuration. @return the configured fields of the current field configuration
[ "private List<CmsSearchField> getFields() {\n\n CmsSearchManager manager = OpenCms.getSearchManager();\n I_CmsSearchFieldConfiguration fieldConfig = manager.getFieldConfiguration(getParamFieldconfiguration());\n List<CmsSearchField> result;\n if (fieldConfig != null) {\n result = fieldConfig.getFields();\n } else {\n result = Collections.emptyList();\n if (LOG.isErrorEnabled()) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_SEARCHINDEX_EDIT_MISSING_PARAM_1,\n A_CmsFieldConfigurationDialog.PARAM_FIELDCONFIGURATION));\n }\n }\n return result;\n }" ]
[ "public static EventLog getEnterpriseEvents(BoxAPIConnection api, Date after, Date before, BoxEvent.Type... types) {\n return getEnterpriseEvents(api, null, after, before, ENTERPRISE_LIMIT, types);\n }", "public static void validate(final String bic) throws BicFormatException,\n UnsupportedCountryException {\n try {\n validateEmpty(bic);\n validateLength(bic);\n validateCase(bic);\n validateBankCode(bic);\n validateCountryCode(bic);\n validateLocationCode(bic);\n\n if(hasBranchCode(bic)) {\n validateBranchCode(bic);\n }\n } catch (UnsupportedCountryException e) {\n throw e;\n } catch (RuntimeException e) {\n throw new BicFormatException(UNKNOWN, e.getMessage());\n }\n }", "public static String unexpandLine(CharSequence self, int tabStop) {\n StringBuilder builder = new StringBuilder(self.toString());\n int index = 0;\n while (index + tabStop < builder.length()) {\n // cut original string in tabstop-length pieces\n String piece = builder.substring(index, index + tabStop);\n // count trailing whitespace characters\n int count = 0;\n while ((count < tabStop) && (Character.isWhitespace(piece.charAt(tabStop - (count + 1)))))\n count++;\n // replace if whitespace was found\n if (count > 0) {\n piece = piece.substring(0, tabStop - count) + '\\t';\n builder.replace(index, index + tabStop, piece);\n index = index + tabStop - (count - 1);\n } else\n index = index + tabStop;\n }\n return builder.toString();\n }", "protected void process(String text, Map params, Writer writer){\n\n try{\n Template t = new Template(\"temp\", new StringReader(text), FreeMarkerTL.getEnvironment().getConfiguration());\n t.process(params, writer);\n }catch(Exception e){ \n throw new ViewException(e);\n }\n }", "@Override\n\tpublic String getInputToParse(String completeInput, int offset, int completionOffset) {\n\t\tint fixedOffset = getOffsetIncludingWhitespace(completeInput, offset, Math.min(completeInput.length(), completionOffset));\n\t\treturn super.getInputToParse(completeInput, fixedOffset, completionOffset);\n\t}", "@SuppressWarnings(\"unchecked\")\n\tstatic void logToFile(String filename) {\n\t\tLogger rootLogger = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);\n\n\t\tFileAppender<ILoggingEvent> fileappender = new FileAppender<>();\n\t\tfileappender.setContext(rootLogger.getLoggerContext());\n\t\tfileappender.setFile(filename);\n\t\tfileappender.setName(\"FILE\");\n\n\t\tConsoleAppender<?> console = (ConsoleAppender<?>) rootLogger.getAppender(\"STDOUT\");\n\t\tfileappender.setEncoder((Encoder<ILoggingEvent>) console.getEncoder());\n\n\t\tfileappender.start();\n\n\t\trootLogger.addAppender(fileappender);\n\n\t\tconsole.stop();\n\t}", "public Versioned<E> getVersionedById(int id) {\n Versioned<VListNode<E>> listNode = getListNode(id);\n if(listNode == null)\n throw new IndexOutOfBoundsException();\n return new Versioned<E>(listNode.getValue().getValue(), listNode.getVersion());\n }", "public static EffectiveAssignmentInsnFinder newInstance(final FieldNode targetVariable,\n final Collection<ControlFlowBlock> controlFlowBlocks) {\n return new EffectiveAssignmentInsnFinder(checkNotNull(targetVariable), checkNotNull(controlFlowBlocks));\n }", "public static XMLGregorianCalendar convertDate(Date date) {\n if (date == null) {\n return null;\n }\n\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTimeInMillis(date.getTime());\n\n try {\n return getDatatypeFactory().newXMLGregorianCalendar(gc);\r\n } catch (DatatypeConfigurationException ex) {\n return null;\n }\n }" ]
Should be called after all rows have been created @param headerStyle @param totalStyle @param totalHeaderStyle @return
[ "public CrosstabBuilder setRowStyles(Style headerStyle, Style totalStyle, Style totalHeaderStyle) {\r\n\t\tcrosstab.setRowHeaderStyle(headerStyle);\r\n\t\tcrosstab.setRowTotalheaderStyle(totalHeaderStyle);\r\n\t\tcrosstab.setRowTotalStyle(totalStyle);\r\n\t\treturn this;\r\n\t}" ]
[ "public synchronized void cleanWaitTaskQueue() {\n\n for (ParallelTask task : waitQ) {\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.USER_CANCELED, \"NA\"));\n logger.info(\n \"task {} removed from wait q. This task has been marked as USER CANCELED.\",\n task.getTaskId());\n\n }\n\n waitQ.clear();\n }", "public List<Method> getMethodsFromGroupIds(int[] groupIds, String[] filters) throws Exception {\n ArrayList<Method> methods = new ArrayList<Method>();\n\n for (int groupId : groupIds) {\n methods.addAll(getMethodsFromGroupId(groupId, filters));\n }\n\n return methods;\n }", "public boolean add(long key) {\n final int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;\n final Entry entryOriginal = table[index];\n for (Entry entry = entryOriginal; entry != null; entry = entry.next) {\n if (entry.key == key) {\n return false;\n }\n }\n table[index] = new Entry(key, entryOriginal);\n size++;\n if (size > threshold) {\n setCapacity(2 * capacity);\n }\n return true;\n }", "public void setProxyClass(Class newProxyClass)\r\n {\r\n proxyClass = newProxyClass;\r\n if (proxyClass == null)\r\n {\r\n setProxyClassName(null);\r\n }\r\n else\r\n {\r\n proxyClassName = proxyClass.getName();\r\n }\r\n }", "GcsRestCreationToken handlePutResponse(final GcsRestCreationToken token,\n final boolean isFinalChunk,\n final int length,\n final HTTPRequestInfo reqInfo,\n HTTPResponse resp) throws Error, IOException {\n switch (resp.getResponseCode()) {\n case 200:\n if (!isFinalChunk) {\n throw new RuntimeException(\"Unexpected response code 200 on non-final chunk. Request: \\n\"\n + URLFetchUtils.describeRequestAndResponse(reqInfo, resp));\n } else {\n return null;\n }\n case 308:\n if (isFinalChunk) {\n throw new RuntimeException(\"Unexpected response code 308 on final chunk: \"\n + URLFetchUtils.describeRequestAndResponse(reqInfo, resp));\n } else {\n return new GcsRestCreationToken(token.filename, token.uploadId, token.offset + length);\n }\n default:\n throw HttpErrorHandler.error(resp.getResponseCode(),\n URLFetchUtils.describeRequestAndResponse(reqInfo, resp));\n }\n }", "protected PersistenceBrokerInternal createNewBrokerInstance(PBKey key) throws PBFactoryException\r\n {\r\n if (key == null) throw new PBFactoryException(\"Could not create new broker with PBkey argument 'null'\");\r\n // check if the given key really exists\r\n if (MetadataManager.getInstance().connectionRepository().getDescriptor(key) == null)\r\n {\r\n throw new PBFactoryException(\"Given PBKey \" + key + \" does not match in metadata configuration\");\r\n }\r\n if (log.isEnabledFor(Logger.INFO))\r\n {\r\n // only count created instances when INFO-Log-Level\r\n log.info(\"Create new PB instance for PBKey \" + key +\r\n \", already created persistence broker instances: \" + instanceCount);\r\n // useful for testing\r\n ++this.instanceCount;\r\n }\r\n\r\n PersistenceBrokerInternal instance = null;\r\n Class[] types = {PBKey.class, PersistenceBrokerFactoryIF.class};\r\n Object[] args = {key, this};\r\n try\r\n {\r\n instance = (PersistenceBrokerInternal) ClassHelper.newInstance(implementationClass, types, args);\r\n OjbConfigurator.getInstance().configure(instance);\r\n instance = (PersistenceBrokerInternal) InterceptorFactory.getInstance().createInterceptorFor(instance);\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Creation of a new PB instance failed\", e);\r\n throw new PBFactoryException(\"Creation of a new PB instance failed\", e);\r\n }\r\n return instance;\r\n }", "public static List<Artifact> getAllArtifacts(final Module module){\n final List<Artifact> artifacts = new ArrayList<Artifact>();\n\n for(final Module subModule: module.getSubmodules()){\n artifacts.addAll(getAllArtifacts(subModule));\n }\n\n artifacts.addAll(module.getArtifacts());\n\n return artifacts;\n }", "void killAll()\n {\n for (RjiRegistration reg : this.instancesById.values().toArray(new RjiRegistration[] {}))\n {\n reg.rji.handleInstruction(Instruction.KILL);\n }\n }", "private synchronized void initSystemCache() {\n List<StoreDefinition> value = storeMapper.readStoreList(new StringReader(SystemStoreConstants.SYSTEM_STORE_SCHEMA));\n metadataCache.put(SYSTEM_STORES_KEY, new Versioned<Object>(value));\n }" ]
Add a new script @param model @param name @param script @return @throws Exception
[ "@RequestMapping(value = \"/api/scripts\", method = RequestMethod.POST)\n public\n @ResponseBody\n Script addScript(Model model,\n @RequestParam(required = true) String name,\n @RequestParam(required = true) String script) throws Exception {\n\n return ScriptService.getInstance().addScript(name, script);\n }" ]
[ "public static snmpalarm[] get(nitro_service service) throws Exception{\n\t\tsnmpalarm obj = new snmpalarm();\n\t\tsnmpalarm[] response = (snmpalarm[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public void setDataOffsets(int[] offsets)\n {\n assert(mLevels == offsets.length);\n NativeBitmapImage.updateCompressed(getNative(), mWidth, mHeight, mImageSize, mData, mLevels, offsets);\n mData = null;\n }", "public void addSubmodule(final Module submodule) {\n if (!submodules.contains(submodule)) {\n submodule.setSubmodule(true);\n\n if (promoted) {\n submodule.setPromoted(promoted);\n }\n\n submodules.add(submodule);\n }\n }", "public static void acceptsZone(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_Z, OPT_ZONE), \"zone id\")\n .withRequiredArg()\n .describedAs(\"zone-id\")\n .ofType(Integer.class);\n }", "static boolean isInCircle(float x, float y, float centerX, float centerY, float\n radius) {\n return Math.abs(x - centerX) < radius && Math.abs(y - centerY) < radius;\n }", "public void addSerie(AbstractColumn column, StringExpression labelExpression) {\r\n\t\tseries.add(column);\r\n\t\tseriesLabels.put(column, labelExpression);\r\n\t}", "private void validateSegments(List<LogSegment> segments) {\n synchronized (lock) {\n for (int i = 0; i < segments.size() - 1; i++) {\n LogSegment curr = segments.get(i);\n LogSegment next = segments.get(i + 1);\n if (curr.start() + curr.size() != next.start()) {\n throw new IllegalStateException(\"The following segments don't validate: \" + curr.getFile()\n .getAbsolutePath() + \", \" + next.getFile().getAbsolutePath());\n }\n }\n }\n }", "public ConfigBuilder withHost(final String host) {\n if (host == null || \"\".equals(host)) {\n throw new IllegalArgumentException(\"host must not be null or empty: \" + host);\n }\n this.host = host;\n return this;\n }", "@Override\n public void setDraggable(Element elem, String draggable) {\n super.setDraggable(elem, draggable);\n if (\"true\".equals(draggable)) {\n elem.getStyle().setProperty(\"webkitUserDrag\", \"element\");\n } else {\n elem.getStyle().clearProperty(\"webkitUserDrag\");\n }\n }" ]
Export the odo overrides setup and odo configuration @param oldExport Whether this is a backup from scratch or backing up because user will upload after (matches API) @return The odo configuration and overrides in JSON format, can be written to a file after
[ "public JSONObject exportConfigurationAndProfile(String oldExport) {\n try {\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"oldExport\", oldExport)\n };\n String url = BASE_BACKUP_PROFILE + \"/\" + uriEncode(this._profileName) + \"/\" + this._clientId;\n return new JSONObject(doGet(url, new BasicNameValuePair[]{}));\n } catch (Exception e) {\n return new JSONObject();\n }\n }" ]
[ "public final void setOrientation(int orientation) {\n mOrientation = orientation;\n mOrientationState = getOrientationStateFromParam(mOrientation);\n invalidate();\n if (mOuterAdapter != null) {\n mOuterAdapter.setOrientation(mOrientation);\n }\n\n }", "public static void ensureXPathNotEmpty(NodeList nodeList, String expression) {\n if (nodeList == null || nodeList.getLength() == 0) {\n throw LOG.unableToFindXPathExpression(expression);\n }\n }", "public static Deployment of(final Path content) {\n final DeploymentContent deploymentContent = DeploymentContent.of(Assert.checkNotNullParam(\"content\", content));\n return new Deployment(deploymentContent, null);\n }", "public void addConverter(int index, IConverter converter) {\r\n\t\tconverterList.add(index, converter);\r\n\t\tif (converter instanceof IContainerConverter) {\r\n\t\t\tIContainerConverter containerConverter = (IContainerConverter) converter;\r\n\t\t\tif (containerConverter.getElementConverter() == null) {\r\n\t\t\t\tcontainerConverter.setElementConverter(elementConverter);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "private CostRateTableEntry getCostRateTableEntry(Date date)\n {\n CostRateTableEntry result;\n\n CostRateTable table = getCostRateTable();\n if (table == null)\n {\n Resource resource = getResource();\n result = new CostRateTableEntry(resource.getStandardRate(), TimeUnit.HOURS, resource.getOvertimeRate(), TimeUnit.HOURS, resource.getCostPerUse(), null);\n }\n else\n {\n if (table.size() == 1)\n {\n result = table.get(0);\n }\n else\n {\n result = table.getEntryByDate(date);\n }\n }\n\n return result;\n }", "public List getFeedback()\n\t {\n\t List<?> messages = new ArrayList();\n\t for ( ValueSource vs : valueSources )\n\t {\n\t List feedback = vs.getFeedback();\n\t if ( feedback != null && !feedback.isEmpty() )\n\t {\n\t messages.addAll( feedback );\n\t }\n\t }\n\n\t return messages;\n\t }", "protected void importUserFromFile() {\n\n CmsImportUserThread thread = new CmsImportUserThread(\n m_cms,\n m_ou,\n m_userImportList,\n getGroupsList(m_importGroups, true),\n getRolesList(m_importRoles, true),\n m_sendMail.getValue().booleanValue());\n thread.start();\n CmsShowReportDialog dialog = new CmsShowReportDialog(thread, new Runnable() {\n\n public void run() {\n\n m_window.close();\n }\n });\n m_window.setContent(dialog);\n\n }", "protected void layoutChild(final int dataIndex) {\n Widget child = mContainer.get(dataIndex);\n if (child != null) {\n float offset = mOffset.get(Axis.X);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.X, offset);\n }\n\n offset = mOffset.get(Axis.Y);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.Y, offset);\n }\n\n offset = mOffset.get(Axis.Z);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.Z, offset);\n }\n }\n }", "public ThreadInfo[] getThreadDump() {\n ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();\n return threadMxBean.dumpAllThreads(true, true);\n }" ]
Run a CLI script from a File. @param script The script file.
[ "protected void runScript(File script) {\n if (!script.exists()) {\n JOptionPane.showMessageDialog(cliGuiCtx.getMainPanel(), script.getAbsolutePath() + \" does not exist.\",\n \"Unable to run script.\", JOptionPane.ERROR_MESSAGE);\n return;\n }\n\n int choice = JOptionPane.showConfirmDialog(cliGuiCtx.getMainPanel(), \"Run CLI script \" + script.getName() + \"?\",\n \"Confirm run script\", JOptionPane.YES_NO_OPTION);\n if (choice != JOptionPane.YES_OPTION) return;\n\n menu.addScript(script);\n\n cliGuiCtx.getTabs().setSelectedIndex(1); // set to Output tab to view the output\n output.post(\"\\n\");\n\n SwingWorker scriptRunner = new ScriptRunner(script);\n scriptRunner.execute();\n }" ]
[ "private void readAssignments(Resource mpxjResource, net.sf.mpxj.phoenix.schema.Project.Storepoints.Storepoint.Resources.Resource res)\n {\n for (Assignment assignment : res.getAssignment())\n {\n readAssignment(mpxjResource, assignment);\n }\n }", "public Collection<Contact> getList() throws FlickrException {\r\n \t ContactList<Contact> contacts = new ContactList<Contact>();\r\n \r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element contactsElement = response.getPayload();\r\n contacts.setPage(contactsElement.getAttribute(\"page\"));\r\n contacts.setPages(contactsElement.getAttribute(\"pages\"));\r\n contacts.setPerPage(contactsElement.getAttribute(\"perpage\"));\r\n contacts.setTotal(contactsElement.getAttribute(\"total\"));\r\n NodeList contactNodes = contactsElement.getElementsByTagName(\"contact\");\r\n for (int i = 0; i < contactNodes.getLength(); i++) {\r\n Element contactElement = (Element) contactNodes.item(i);\r\n Contact contact = new Contact();\r\n contact.setId(contactElement.getAttribute(\"nsid\"));\r\n contact.setUsername(contactElement.getAttribute(\"username\"));\r\n contact.setRealName(contactElement.getAttribute(\"realname\"));\r\n contact.setFriend(\"1\".equals(contactElement.getAttribute(\"friend\")));\r\n contact.setFamily(\"1\".equals(contactElement.getAttribute(\"family\")));\r\n contact.setIgnored(\"1\".equals(contactElement.getAttribute(\"ignored\")));\r\n String lPathAlias = contactElement.getAttribute(\"path_alias\");\r\n contact.setPathAlias(lPathAlias == null || \"\".equals(lPathAlias) ? null : lPathAlias);\r\n contact.setOnline(OnlineStatus.fromType(contactElement.getAttribute(\"online\")));\r\n contact.setIconFarm(contactElement.getAttribute(\"iconfarm\"));\r\n contact.setIconServer(contactElement.getAttribute(\"iconserver\"));\r\n if (contact.getOnline() == OnlineStatus.AWAY) {\r\n contactElement.normalize();\r\n contact.setAwayMessage(XMLUtilities.getValue(contactElement));\r\n }\r\n contacts.add(contact);\r\n }\r\n return contacts;\r\n }", "public static base_response update(nitro_service client, clusternodegroup resource) throws Exception {\n\t\tclusternodegroup updateresource = new clusternodegroup();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.strict = resource.strict;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static base_responses delete(nitro_service client, String serverip[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (serverip != null && serverip.length > 0) {\n\t\t\tntpserver deleteresources[] = new ntpserver[serverip.length];\n\t\t\tfor (int i=0;i<serverip.length;i++){\n\t\t\t\tdeleteresources[i] = new ntpserver();\n\t\t\t\tdeleteresources[i].serverip = serverip[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public static long addressToLong(InetAddress address) {\n long result = 0;\n for (byte element : address.getAddress()) {\n result = (result << 8) + unsign(element);\n }\n return result;\n }", "public static boolean xpathExists(Node document, String xpathExpression, Map<String, String> namespaceMapping) throws XPathException,\n MarshallingException\n {\n Boolean result = (Boolean) executeXPath(document, xpathExpression, namespaceMapping, XPathConstants.BOOLEAN);\n return result != null && result;\n }", "private void handleArchiveByFile(Predicate<String> filter, File archive, List<String> discoveredFiles)\n {\n try\n {\n try (ZipFile zip = new ZipFile(archive))\n {\n Enumeration<? extends ZipEntry> entries = zip.entries();\n \n while (entries.hasMoreElements())\n {\n ZipEntry entry = entries.nextElement();\n String name = entry.getName();\n if (filter.accept(name))\n discoveredFiles.add(name);\n }\n }\n }\n catch (IOException e)\n {\n throw new RuntimeException(\"Error handling file \" + archive, e);\n }\n }", "public synchronized void setDeviceName(String name) {\n if (name.getBytes().length > DEVICE_NAME_LENGTH) {\n throw new IllegalArgumentException(\"name cannot be more than \" + DEVICE_NAME_LENGTH + \" bytes long\");\n }\n Arrays.fill(announcementBytes, DEVICE_NAME_OFFSET, DEVICE_NAME_LENGTH, (byte)0);\n System.arraycopy(name.getBytes(), 0, announcementBytes, DEVICE_NAME_OFFSET, name.getBytes().length);\n }", "public static Constructor<?> getConstructor(final Class<?> clazz,\n final Class<?>... argumentTypes) throws NoSuchMethodException {\n try {\n return AccessController\n .doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {\n public Constructor<?> run()\n throws NoSuchMethodException {\n return clazz.getConstructor(argumentTypes);\n }\n });\n }\n // Unwrap\n catch (final PrivilegedActionException pae) {\n final Throwable t = pae.getCause();\n // Rethrow\n if (t instanceof NoSuchMethodException) {\n throw (NoSuchMethodException) t;\n } else {\n // No other checked Exception thrown by Class.getConstructor\n try {\n throw (RuntimeException) t;\n }\n // Just in case we've really messed up\n catch (final ClassCastException cce) {\n throw new RuntimeException(\n \"Obtained unchecked Exception; this code should never be reached\",\n t);\n }\n }\n }\n }" ]
Concats an element and an array. @param firstElement the first element @param array the array @param <T> the type of the element in the array @return a new array created adding the element in the second array after the first element
[ "public static <T> T[] concat(T firstElement, T... array) {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT[] result = (T[]) Array.newInstance( firstElement.getClass(), 1 + array.length );\n\t\tresult[0] = firstElement;\n\t\tSystem.arraycopy( array, 0, result, 1, array.length );\n\n\t\treturn result;\n\t}" ]
[ "private void setCorrectDay(Calendar date) {\n\n if (monthHasNotDay(date)) {\n date.set(Calendar.DAY_OF_MONTH, date.getActualMaximum(Calendar.DAY_OF_MONTH));\n } else {\n date.set(Calendar.DAY_OF_MONTH, m_dayOfMonth);\n }\n }", "public GetSingleConversationOptions filters(List<String> filters) {\n if(filters.size() == 1) { //Canvas API doesn't want the [] if it is only one value\n addSingleItem(\"filter\", filters.get(0));\n } else {\n optionsMap.put(\"filter[]\", filters);\n }\n return this;\n }", "@Subscribe\n @SuppressForbidden(\"legitimate printStackTrace().\")\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n try {\n if (jsonWriter == null)\n return;\n\n slaves.put(e.getSlave().id, e.getSlave());\n e.serialize(jsonWriter, outputStreams);\n } catch (Exception ex) {\n ex.printStackTrace();\n junit4.log(\"Error serializing to JSON file: \"\n + Throwables.getStackTraceAsString(ex), Project.MSG_WARN);\n if (jsonWriter != null) {\n try {\n jsonWriter.close();\n } catch (Throwable ignored) {\n // Ignore.\n } finally {\n jsonWriter = null;\n }\n }\n }\n }", "public static protocoludp_stats get(nitro_service service) throws Exception{\n\t\tprotocoludp_stats obj = new protocoludp_stats();\n\t\tprotocoludp_stats[] response = (protocoludp_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}", "OTMConnection getConnection()\r\n {\r\n if (m_connection == null)\r\n {\r\n OTMConnectionRuntimeException ex = new OTMConnectionRuntimeException(\"Connection is null.\");\r\n sendEvents(ConnectionEvent.CONNECTION_ERROR_OCCURRED, ex, null);\r\n }\r\n return m_connection;\r\n }", "public void setSessionFactory(SessionFactory sessionFactory) throws HibernateLayerException {\n\t\ttry {\n\t\t\tthis.sessionFactory = sessionFactory;\n\t\t\tif (null != layerInfo) {\n\t\t\t\tentityMetadata = sessionFactory.getClassMetadata(layerInfo.getFeatureInfo().getDataSourceName());\n\t\t\t}\n\t\t} catch (Exception e) { // NOSONAR\n\t\t\tthrow new HibernateLayerException(e, ExceptionCode.HIBERNATE_NO_SESSION_FACTORY);\n\t\t}\n\t}", "public static tunneltrafficpolicy[] get(nitro_service service, options option) throws Exception{\n\t\ttunneltrafficpolicy obj = new tunneltrafficpolicy();\n\t\ttunneltrafficpolicy[] response = (tunneltrafficpolicy[])obj.get_resources(service,option);\n\t\treturn response;\n\t}", "protected String getExtraSolrParams() {\n\n try {\n return m_configObject.getString(JSON_KEY_EXTRASOLRPARAMS);\n } catch (JSONException e) {\n if (null == m_baseConfig) {\n if (LOG.isInfoEnabled()) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_EXTRA_PARAMETERS_0), e);\n }\n return \"\";\n } else {\n return m_baseConfig.getGeneralConfig().getExtraSolrParams();\n }\n }\n }", "public Map<Integer, RandomVariable> getGradient(){\r\n\r\n\t\tint numberOfCalculationSteps = getFunctionList().size();\r\n\r\n\t\tRandomVariable[] omegaHat = new RandomVariable[numberOfCalculationSteps];\r\n\r\n\t\tomegaHat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0);\r\n\r\n\t\tfor(int variableIndex = numberOfCalculationSteps-2; variableIndex >= 0; variableIndex--){\r\n\r\n\t\t\tomegaHat[variableIndex] = new RandomVariableFromDoubleArray(0.0);\r\n\r\n\t\t\tArrayList<Integer> childrenList = getAADRandomVariableFromList(variableIndex).getChildrenIndices();\r\n\r\n\t\t\tfor(int functionIndex:childrenList){\r\n\t\t\t\tRandomVariable D_i_j = getPartialDerivative(functionIndex, variableIndex);\r\n\t\t\t\tomegaHat[variableIndex] = omegaHat[variableIndex].addProduct(D_i_j, omegaHat[functionIndex]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tArrayList<Integer> arrayListOfAllIndicesOfDependentRandomVariables = getArrayListOfAllIndicesOfDependentRandomVariables();\r\n\r\n\t\tMap<Integer, RandomVariable> gradient = new HashMap<Integer, RandomVariable>();\r\n\r\n\t\tfor(Integer indexOfDependentRandomVariable: arrayListOfAllIndicesOfDependentRandomVariables){\r\n\t\t\tgradient.put(indexOfDependentRandomVariable, omegaHat[arrayListOfAllIndicesOfDependentRandomVariables.get(indexOfDependentRandomVariable)]);\r\n\t\t}\r\n\r\n\t\treturn gradient;\r\n\t}" ]
Returns a SimpleConfiguration clientConfig with properties set from this configuration @return SimpleConfiguration
[ "public SimpleConfiguration getClientConfiguration() {\n SimpleConfiguration clientConfig = new SimpleConfiguration();\n Iterator<String> iter = getKeys();\n while (iter.hasNext()) {\n String key = iter.next();\n if (key.startsWith(CONNECTION_PREFIX) || key.startsWith(ACCUMULO_PREFIX)\n || key.startsWith(CLIENT_PREFIX)) {\n clientConfig.setProperty(key, getRawString(key));\n }\n }\n return clientConfig;\n }" ]
[ "private void addFoldersToSearchIn(final List<String> folders) {\n\n if (null == folders) {\n return;\n }\n\n for (String folder : folders) {\n if (!CmsResource.isFolder(folder)) {\n folder += \"/\";\n }\n\n m_foldersToSearchIn.add(folder);\n }\n }", "private HashMap<String, StoreDefinition> makeStoreDefinitionMap(List<StoreDefinition> storeDefs) {\n HashMap<String, StoreDefinition> storeDefMap = new HashMap<String, StoreDefinition>();\n for(StoreDefinition storeDef: storeDefs)\n storeDefMap.put(storeDef.getName(), storeDef);\n return storeDefMap;\n }", "public static aaa_stats get(nitro_service service) throws Exception{\n\t\taaa_stats obj = new aaa_stats();\n\t\taaa_stats[] response = (aaa_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}", "public void save() throws CmsException {\n\n if (hasChanges()) {\n switch (m_bundleType) {\n case PROPERTY:\n saveLocalization();\n saveToPropertyVfsBundle();\n break;\n\n case XML:\n saveLocalization();\n saveToXmlVfsBundle();\n\n break;\n\n case DESCRIPTOR:\n break;\n default:\n throw new IllegalArgumentException();\n }\n if (null != m_descFile) {\n saveToBundleDescriptor();\n }\n\n resetChanges();\n }\n\n }", "public List<TimephasedWork> getCompleteWork(ProjectCalendar calendar, ResourceAssignment resourceAssignment, byte[] data)\n {\n LinkedList<TimephasedWork> list = new LinkedList<TimephasedWork>();\n\n if (calendar != null && data != null && data.length > 2 && MPPUtility.getShort(data, 0) > 0)\n {\n Date startDate = resourceAssignment.getStart();\n double finishTime = MPPUtility.getInt(data, 24);\n\n int blockCount = MPPUtility.getShort(data, 0);\n double previousCumulativeWork = 0;\n TimephasedWork previousAssignment = null;\n\n int index = 32;\n int currentBlock = 0;\n while (currentBlock < blockCount && index + 20 <= data.length)\n {\n double time = MPPUtility.getInt(data, index + 0);\n\n // If the start of this block is before the start of the assignment, or after the end of the assignment\n // the values don't make sense, so we'll just set the start of this block to be the start of the assignment.\n // This deals with an issue where odd timephased data like this was causing an MPP file to be read\n // extremely slowly.\n if (time < 0 || time > finishTime)\n {\n time = 0;\n }\n else\n {\n time /= 80;\n }\n Duration startWork = Duration.getInstance(time, TimeUnit.MINUTES);\n\n double currentCumulativeWork = (long) MPPUtility.getDouble(data, index + 4);\n double assignmentDuration = currentCumulativeWork - previousCumulativeWork;\n previousCumulativeWork = currentCumulativeWork;\n assignmentDuration /= 1000;\n Duration totalWork = Duration.getInstance(assignmentDuration, TimeUnit.MINUTES);\n time = (long) MPPUtility.getDouble(data, index + 12);\n time /= 125;\n time *= 6;\n Duration workPerDay = Duration.getInstance(time, TimeUnit.MINUTES);\n\n Date start;\n if (startWork.getDuration() == 0)\n {\n start = startDate;\n }\n else\n {\n start = calendar.getDate(startDate, startWork, true);\n }\n\n TimephasedWork assignment = new TimephasedWork();\n assignment.setStart(start);\n assignment.setAmountPerDay(workPerDay);\n assignment.setTotalAmount(totalWork);\n\n if (previousAssignment != null)\n {\n Date finish = calendar.getDate(startDate, startWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n\n list.add(assignment);\n previousAssignment = assignment;\n\n index += 20;\n ++currentBlock;\n }\n\n if (previousAssignment != null)\n {\n Duration finishWork = Duration.getInstance(finishTime / 80, TimeUnit.MINUTES);\n Date finish = calendar.getDate(startDate, finishWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n }\n\n return list;\n }", "static DefaultContainerDescription lookup(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadResourceOperation(new ModelNode().setEmptyList());\n op.get(ClientConstants.INCLUDE_RUNTIME).set(true);\n final ModelNode result = client.execute(op);\n if (Operations.isSuccessfulOutcome(result)) {\n final ModelNode model = Operations.readResult(result);\n final String productName = getValue(model, \"product-name\", \"WildFly\");\n final String productVersion = getValue(model, \"product-version\");\n final String releaseVersion = getValue(model, \"release-version\");\n final String launchType = getValue(model, \"launch-type\");\n return new DefaultContainerDescription(productName, productVersion, releaseVersion, launchType, \"DOMAIN\".equalsIgnoreCase(launchType));\n }\n throw new OperationExecutionException(op, result);\n }", "@Override\n public void setActive(boolean active) {\n this.active = active;\n\n if (parent != null) {\n fireCollapsibleHandler();\n removeStyleName(CssName.ACTIVE);\n if (header != null) {\n header.removeStyleName(CssName.ACTIVE);\n }\n if (active) {\n if (parent != null && parent.isAccordion()) {\n parent.clearActive();\n }\n addStyleName(CssName.ACTIVE);\n\n if (header != null) {\n header.addStyleName(CssName.ACTIVE);\n }\n }\n\n if (body != null) {\n body.setDisplay(active ? Display.BLOCK : Display.NONE);\n }\n } else {\n GWT.log(\"Please make sure that the Collapsible parent is attached or existed.\", new IllegalStateException());\n }\n }", "public static base_responses update(nitro_service client, route6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\troute6 updateresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new route6();\n\t\t\t\tupdateresources[i].network = resources[i].network;\n\t\t\t\tupdateresources[i].gateway = resources[i].gateway;\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].weight = resources[i].weight;\n\t\t\t\tupdateresources[i].distance = resources[i].distance;\n\t\t\t\tupdateresources[i].cost = resources[i].cost;\n\t\t\t\tupdateresources[i].advertise = resources[i].advertise;\n\t\t\t\tupdateresources[i].msr = resources[i].msr;\n\t\t\t\tupdateresources[i].monitor = resources[i].monitor;\n\t\t\t\tupdateresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private String extractAndConvertTaskType(Task task)\n {\n String activityType = (String) task.getCachedValue(m_activityTypeField);\n if (activityType == null)\n {\n activityType = \"Resource Dependent\";\n }\n else\n {\n if (ACTIVITY_TYPE_MAP.containsKey(activityType))\n {\n activityType = ACTIVITY_TYPE_MAP.get(activityType);\n }\n }\n return activityType;\n }" ]
Go through all nodes and determine how many partition Ids each node hosts. @param cluster @return map of nodeId to number of primary partitions hosted on node.
[ "private Map<Integer, Integer> getNodeIdToPrimaryCount(Cluster cluster) {\n Map<Integer, Integer> nodeIdToPrimaryCount = Maps.newHashMap();\n for(Node node: cluster.getNodes()) {\n nodeIdToPrimaryCount.put(node.getId(), node.getPartitionIds().size());\n }\n\n return nodeIdToPrimaryCount;\n }" ]
[ "public static SpinXmlElement XML(Object input) {\n return SpinFactory.INSTANCE.createSpin(input, DataFormats.xml());\n }", "public void checkSpecialization() {\n if (isSpecializing()) {\n boolean isNameDefined = getAnnotated().isAnnotationPresent(Named.class);\n String previousSpecializedBeanName = null;\n for (AbstractBean<?, ?> specializedBean : getSpecializedBeans()) {\n String name = specializedBean.getName();\n if (previousSpecializedBeanName != null && name != null && !previousSpecializedBeanName.equals(specializedBean.getName())) {\n // there may be multiple beans specialized by this bean - make sure they all share the same name\n throw BeanLogger.LOG.beansWithDifferentBeanNamesCannotBeSpecialized(previousSpecializedBeanName, specializedBean.getName(), this);\n }\n previousSpecializedBeanName = name;\n if (isNameDefined && name != null) {\n throw BeanLogger.LOG.nameNotAllowedOnSpecialization(getAnnotated(), specializedBean.getAnnotated());\n }\n\n // When a specializing bean extends the raw type of a generic superclass, types of the generic superclass are\n // added into types of the specializing bean because of assignability rules. However, ParameterizedTypes among\n // these types are NOT types of the specializing bean (that's the way java works)\n boolean rawInsteadOfGeneric = (this instanceof AbstractClassBean<?>\n && specializedBean.getBeanClass().getTypeParameters().length > 0\n && !(((AbstractClassBean<?>) this).getBeanClass().getGenericSuperclass() instanceof ParameterizedType));\n for (Type specializedType : specializedBean.getTypes()) {\n if (rawInsteadOfGeneric && specializedType instanceof ParameterizedType) {\n throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean);\n }\n boolean contains = getTypes().contains(specializedType);\n if (!contains) {\n for (Type specializingType : getTypes()) {\n // In case 'type' is a ParameterizedType, two bean types equivalent in the CDI sense may not be\n // equal in the java sense. Therefore we have to use our own equality util.\n if (TypeEqualitySpecializationUtils.areTheSame(specializingType, specializedType)) {\n contains = true;\n break;\n }\n }\n }\n if (!contains) {\n throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean);\n }\n }\n }\n }\n }", "public static service_dospolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tservice_dospolicy_binding obj = new service_dospolicy_binding();\n\t\tobj.set_name(name);\n\t\tservice_dospolicy_binding response[] = (service_dospolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static String cutEnd(String data, int maxLength) {\n if (data.length() > maxLength) {\n return data.substring(0, maxLength) + \"...\";\n } else {\n return data;\n }\n }", "public <T> void cleanNullReferences(Class<T> clazz) {\n\t\tMap<Object, Reference<Object>> objectMap = getMapForClass(clazz);\n\t\tif (objectMap != null) {\n\t\t\tcleanMap(objectMap);\n\t\t}\n\t}", "public void removeCollaborator(String appName, String collaborator) {\n connection.execute(new SharingRemove(appName, collaborator), apiKey);\n }", "@SuppressWarnings(\"resource\")\n public static FileChannel openChannel(File file, boolean mutable) throws IOException {\n if (mutable) {\n return new RandomAccessFile(file, \"rw\").getChannel();\n }\n return new FileInputStream(file).getChannel();\n }", "private void _handleMultiValues(ArrayList<String> values, String key, String command) {\n if (key == null) return;\n\n if (values == null || values.isEmpty()) {\n _generateEmptyMultiValueError(key);\n return;\n }\n\n ValidationResult vr;\n\n // validate the key\n vr = validator.cleanMultiValuePropertyKey(key);\n\n // Check for an error\n if (vr.getErrorCode() != 0) {\n pushValidationResult(vr);\n }\n\n // reset the key\n Object _key = vr.getObject();\n String cleanKey = (_key != null) ? vr.getObject().toString() : null;\n\n // if key is empty generate an error and return\n if (cleanKey == null || cleanKey.isEmpty()) {\n _generateInvalidMultiValueKeyError(key);\n return;\n }\n\n key = cleanKey;\n\n try {\n JSONArray currentValues = _constructExistingMultiValue(key, command);\n JSONArray newValues = _cleanMultiValues(values, key);\n _validateAndPushMultiValue(currentValues, newValues, values, key, command);\n\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"Error handling multi value operation for key \" + key, t);\n }\n }", "public int createLogs(String topic, final int partitions, final boolean forceEnlarge) {\n TopicNameValidator.validate(topic);\n synchronized (logCreationLock) {\n final int configPartitions = getPartition(topic);\n if (configPartitions >= partitions || !forceEnlarge) {\n return configPartitions;\n }\n topicPartitionsMap.put(topic, partitions);\n if (config.getEnableZookeeper()) {\n if (getLogPool(topic, 0) != null) {//created already\n topicRegisterTasks.add(new TopicTask(TopicTask.TaskType.ENLARGE, topic));\n } else {\n topicRegisterTasks.add(new TopicTask(TopicTask.TaskType.CREATE, topic));\n }\n }\n return partitions;\n }\n }" ]
Creates a proxy object which implements a given bean interface. @param proxyInterface the interface the the proxy will implement @param <T> the proxy implementation type @return the proxy implementation @throws NullPointerException if proxyInterface is null
[ "public static <T> T createProxy(final Class<T> proxyInterface) {\n\t\tif( proxyInterface == null ) {\n\t\t\tthrow new NullPointerException(\"proxyInterface should not be null\");\n\t\t}\n\t\treturn proxyInterface.cast(Proxy.newProxyInstance(proxyInterface.getClassLoader(),\n\t\t\tnew Class[] { proxyInterface }, new BeanInterfaceProxy()));\n\t}" ]
[ "public synchronized void removeAllSceneObjects() {\n final GVRCameraRig rig = getMainCameraRig();\n final GVRSceneObject head = rig.getOwnerObject();\n rig.removeAllChildren();\n\n NativeScene.removeAllSceneObjects(getNative());\n for (final GVRSceneObject child : mSceneRoot.getChildren()) {\n child.getParent().removeChildObject(child);\n }\n\n if (null != head) {\n mSceneRoot.addChildObject(head);\n }\n\n final int numControllers = getGVRContext().getInputManager().clear();\n if (numControllers > 0)\n {\n getGVRContext().getInputManager().selectController();\n }\n\n getGVRContext().runOnGlThread(new Runnable() {\n @Override\n public void run() {\n NativeScene.deleteLightsAndDepthTextureOnRenderThread(getNative());\n }\n });\n }", "public static base_response update(nitro_service client, snmpoption resource) throws Exception {\n\t\tsnmpoption updateresource = new snmpoption();\n\t\tupdateresource.snmpset = resource.snmpset;\n\t\tupdateresource.snmptraplogging = resource.snmptraplogging;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static <E extends Enum<E>> EnumStringConverter<E> create(Class<E> enumType) {\n return new EnumStringConverter<E>(enumType);\n }", "public static base_response unset(nitro_service client, Interface resource, String[] args) throws Exception{\n\t\tInterface unsetresource = new Interface();\n\t\tunsetresource.id = resource.id;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public static boolean readBooleanAttributeElement(final XMLExtendedStreamReader reader, final String attributeName)\n throws XMLStreamException {\n requireSingleAttribute(reader, attributeName);\n final boolean value = Boolean.parseBoolean(reader.getAttributeValue(0));\n requireNoContent(reader);\n return value;\n }", "private void addServer(CmsSiteMatcher matcher, CmsSite site) {\n\n Map<CmsSiteMatcher, CmsSite> siteMatcherSites = new HashMap<CmsSiteMatcher, CmsSite>(m_siteMatcherSites);\n siteMatcherSites.put(matcher, site);\n setSiteMatcherSites(siteMatcherSites);\n }", "public String addClassification(String classificationType) {\n Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType);\n Metadata classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY,\n \"enterprise\", metadata);\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }", "public ItemRequest<OrganizationExport> findById(String organizationExport) {\n \n String path = String.format(\"/organization_exports/%s\", organizationExport);\n return new ItemRequest<OrganizationExport>(this, OrganizationExport.class, path, \"GET\");\n }", "private String resolveExpressionString(final String unresolvedString) throws OperationFailedException {\n\n // parseAndResolve should only be providing expressions with no leading or trailing chars\n assert unresolvedString.startsWith(\"${\") && unresolvedString.endsWith(\"}\");\n\n // Default result is no change from input\n String result = unresolvedString;\n\n ModelNode resolveNode = new ModelNode(new ValueExpression(unresolvedString));\n\n // Try plug-in resolution; i.e. vault\n resolvePluggableExpression(resolveNode);\n\n if (resolveNode.getType() == ModelType.EXPRESSION ) {\n // resolvePluggableExpression did nothing. Try standard resolution\n String resolvedString = resolveStandardExpression(resolveNode);\n if (!unresolvedString.equals(resolvedString)) {\n // resolveStandardExpression made progress\n result = resolvedString;\n } // else there is nothing more we can do with this string\n } else {\n // resolvePluggableExpression made progress\n result = resolveNode.asString();\n }\n\n return result;\n }" ]
Skips the given count of bytes, but at most the currently available count. @return number of bytes actually skipped from this buffer (0 if no bytes are available)
[ "public synchronized int skip(int count) {\n if (count > available) {\n count = available;\n }\n idxGet = (idxGet + count) % capacity;\n available -= count;\n return count;\n }" ]
[ "private static List<String> parseModifiers(int modifiers) {\n List<String> result = new ArrayList<String>();\n if (Modifier.isPrivate(modifiers)) {\n result.add(\"private\");\n }\n if (Modifier.isProtected(modifiers)) {\n result.add(\"protected\");\n }\n if (Modifier.isPublic(modifiers)) {\n result.add(\"public\");\n }\n if (Modifier.isAbstract(modifiers)) {\n result.add(\"abstract\");\n }\n if (Modifier.isFinal(modifiers)) {\n result.add(\"final\");\n }\n if (Modifier.isNative(modifiers)) {\n result.add(\"native\");\n }\n if (Modifier.isStatic(modifiers)) {\n result.add(\"static\");\n }\n if (Modifier.isStrict(modifiers)) {\n result.add(\"strict\");\n }\n if (Modifier.isSynchronized(modifiers)) {\n result.add(\"synchronized\");\n }\n if (Modifier.isTransient(modifiers)) {\n result.add(\"transient\");\n }\n if (Modifier.isVolatile(modifiers)) {\n result.add(\"volatile\");\n }\n if (Modifier.isInterface(modifiers)) {\n result.add(\"interface\");\n }\n return result;\n }", "public Date getTime(String fieldName) {\n\t\ttry {\n\t\t\tif (hasValue(fieldName)) {\n\t\t\t\treturn new Date(Long.valueOf(String.valueOf(resultMap.get(fieldName))) * 1000);\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a time.\", e);\n\t\t}\n\t}", "public boolean measureAll(List<Widget> measuredChildren) {\n boolean changed = false;\n for (int i = 0; i < mContainer.size(); ++i) {\n\n if (!isChildMeasured(i)) {\n Widget child = measureChild(i, false);\n if (child != null) {\n if (measuredChildren != null) {\n measuredChildren.add(child);\n }\n changed = true;\n }\n }\n }\n if (changed) {\n postMeasurement();\n }\n return changed;\n }", "public void process(ProjectFile file, Var2Data varData, byte[] fixedData) throws IOException\n {\n Props props = getProps(varData);\n //System.out.println(props);\n if (props != null)\n {\n String viewName = MPPUtility.removeAmpersands(props.getUnicodeString(VIEW_NAME));\n byte[] listData = props.getByteArray(VIEW_CONTENTS);\n List<Integer> uniqueIdList = new LinkedList<Integer>();\n if (listData != null)\n {\n for (int index = 0; index < listData.length; index += 4)\n {\n Integer uniqueID = Integer.valueOf(MPPUtility.getInt(listData, index));\n\n //\n // Ensure that we have a valid task, and that if we have and\n // ID of zero, this is the first task shown.\n //\n if (file.getTaskByUniqueID(uniqueID) != null && (uniqueID.intValue() != 0 || index == 0))\n {\n uniqueIdList.add(uniqueID);\n }\n }\n }\n\n int filterID = MPPUtility.getShort(fixedData, 128);\n\n ViewState state = new ViewState(file, viewName, uniqueIdList, filterID);\n file.getViews().setViewState(state);\n }\n }", "public static List<String> getValueList(List<String> valuePairs, String delim) {\n List<String> valueList = Lists.newArrayList();\n for(String valuePair: valuePairs) {\n String[] value = valuePair.split(delim, 2);\n if(value.length != 2)\n throw new VoldemortException(\"Invalid argument pair: \" + valuePair);\n valueList.add(value[0]);\n valueList.add(value[1]);\n }\n return valueList;\n }", "@Override\n public void removeCapabilityRequirement(RuntimeRequirementRegistration requirementRegistration) {\n // We don't know if this got registered as an runtime-only requirement or a hard one\n // so clean it from both maps\n writeLock.lock();\n try {\n removeRequirement(requirementRegistration, false);\n removeRequirement(requirementRegistration, true);\n } finally {\n writeLock.unlock();\n }\n }", "public static int wavelengthToRGB(float wavelength) {\n\t\tfloat gamma = 0.80f;\n\t\tfloat r, g, b, factor;\n\n\t\tint w = (int)wavelength;\n\t\tif (w < 380) {\n\t\t\tr = 0.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t} else if (w < 440) {\n\t\t\tr = -(wavelength - 440) / (440 - 380);\n\t\t\tg = 0.0f;\n\t\t\tb = 1.0f;\n\t\t} else if (w < 490) {\n\t\t\tr = 0.0f;\n\t\t\tg = (wavelength - 440) / (490 - 440);\n\t\t\tb = 1.0f;\n\t\t} else if (w < 510) {\n\t\t\tr = 0.0f;\n\t\t\tg = 1.0f;\n\t\t\tb = -(wavelength - 510) / (510 - 490);\n\t\t} else if (w < 580) {\n\t\t\tr = (wavelength - 510) / (580 - 510);\n\t\t\tg = 1.0f;\n\t\t\tb = 0.0f;\n\t\t} else if (w < 645) {\n\t\t\tr = 1.0f;\n\t\t\tg = -(wavelength - 645) / (645 - 580);\n\t\t\tb = 0.0f;\n\t\t} else if (w <= 780) {\n\t\t\tr = 1.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t} else {\n\t\t\tr = 0.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t}\n\n\t\t// Let the intensity fall off near the vision limits\n\t\tif (380 <= w && w <= 419)\n\t\t\tfactor = 0.3f + 0.7f*(wavelength - 380) / (420 - 380);\n\t\telse if (420 <= w && w <= 700)\n\t\t\tfactor = 1.0f;\n\t\telse if (701 <= w && w <= 780)\n\t\t\tfactor = 0.3f + 0.7f*(780 - wavelength) / (780 - 700);\n\t\telse\n\t\t\tfactor = 0.0f;\n\n\t\tint ir = adjust(r, factor, gamma);\n\t\tint ig = adjust(g, factor, gamma);\n\t\tint ib = adjust(b, factor, gamma);\n\n\t\treturn 0xff000000 | (ir << 16) | (ig << 8) | ib;\n\t}", "public static void main(String[] args) throws LoginFailedException,\n\t\t\tIOException, MediaWikiApiErrorException {\n\t\tExampleHelpers.configureLogging();\n\t\tprintDocumentation();\n\n\t\tSetLabelsForNumbersBot bot = new SetLabelsForNumbersBot();\n\t\tExampleHelpers.processEntitiesFromWikidataDump(bot);\n\t\tbot.finish();\n\n\t\tSystem.out.println(\"*** Done.\");\n\t}", "public RedwoodConfiguration stderr(){\r\n LogRecordHandler visibility = new VisibilityHandler();\r\n LogRecordHandler console = Redwood.ConsoleHandler.err();\r\n return this\r\n .rootHandler(visibility)\r\n .handler(visibility, console);\r\n }" ]
Retrieve the details of a single project from the database. @param result Map instance containing the results @param row result set row read from the database
[ "protected void processProjectListItem(Map<Integer, String> result, Row row)\n {\n Integer id = row.getInteger(\"PROJ_ID\");\n String name = row.getString(\"PROJ_NAME\");\n result.put(id, name);\n }" ]
[ "public void setValue(int numStrings, String[] newValues) {\n value.clear();\n if (numStrings == newValues.length) {\n for (int i = 0; i < newValues.length; i++) {\n value.add(newValues[i]);\n }\n }\n else {\n Log.e(TAG, \"X3D MFString setValue() numStrings not equal total newValues\");\n }\n }", "static AbstractLazyPatchableTarget createPatchableTarget(final String name, final LayerPathConfig layer, final File metadata, final InstalledImage image) throws IOException {\n // patchable target\n return new AbstractLazyPatchableTarget() {\n\n @Override\n public InstalledImage getInstalledImage() {\n return image;\n }\n\n @Override\n public File getModuleRoot() {\n return layer.modulePath;\n }\n\n @Override\n public File getBundleRepositoryRoot() {\n return layer.bundlePath;\n }\n\n public File getPatchesMetadata() {\n return metadata;\n }\n\n @Override\n public String getName() {\n return name;\n }\n };\n }", "public Map<String, String> getUploadParameters() {\r\n Map<String, String> parameters = new TreeMap<>();\r\n\r\n\r\n String title = getTitle();\r\n if (title != null) {\r\n parameters.put(\"title\", title);\r\n }\r\n\r\n String description = getDescription();\r\n if (description != null) {\r\n parameters.put(\"description\", description);\r\n }\r\n\r\n Collection<String> tags = getTags();\r\n if (tags != null) {\r\n parameters.put(\"tags\", StringUtilities.join(tags, \" \"));\r\n }\r\n\r\n if (isHidden() != null) {\r\n parameters.put(\"hidden\", isHidden().booleanValue() ? \"1\" : \"0\");\r\n }\r\n\r\n if (getSafetyLevel() != null) {\r\n parameters.put(\"safety_level\", getSafetyLevel());\r\n }\r\n\r\n if (getContentType() != null) {\r\n parameters.put(\"content_type\", getContentType());\r\n }\r\n\r\n if (getPhotoId() != null) {\r\n parameters.put(\"photo_id\", getPhotoId());\r\n }\r\n\r\n parameters.put(\"is_public\", isPublicFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_family\", isFamilyFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_friend\", isFriendFlag() ? \"1\" : \"0\");\r\n parameters.put(\"async\", isAsync() ? \"1\" : \"0\");\r\n\r\n return parameters;\r\n }", "public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize)\n throws InterruptedException, IOException {\n URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL());\n return new LargeFileUpload().\n upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize);\n }", "private void debugLogEnd(String operationType,\n Long OriginTimeInMs,\n Long RequestStartTimeInMs,\n Long ResponseReceivedTimeInMs,\n String keyString,\n int numVectorClockEntries) {\n long durationInMs = ResponseReceivedTimeInMs - RequestStartTimeInMs;\n logger.debug(\"Received a response from voldemort server for Operation Type: \"\n + operationType\n + \" , For key(s): \"\n + keyString\n + \" , Store: \"\n + this.storeName\n + \" , Origin time of request (in ms): \"\n + OriginTimeInMs\n + \" , Response received at time (in ms): \"\n + ResponseReceivedTimeInMs\n + \" . Request sent at(in ms): \"\n + RequestStartTimeInMs\n + \" , Num vector clock entries: \"\n + numVectorClockEntries\n + \" , Duration from CoordinatorFatClient back to CoordinatorFatClient(in ms): \"\n + durationInMs);\n }", "public ManageableCollection createCollectionProxy(PBKey brokerKey, Query query, Class collectionClass)\r\n {\r\n Object args[] = {brokerKey, collectionClass, query};\r\n\r\n try\r\n {\r\n return (ManageableCollection) getCollectionProxyConstructor(collectionClass).newInstance(args);\r\n }\r\n catch(InstantiationException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new collection proxy instance\", ex);\r\n }\r\n catch(InvocationTargetException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new collection proxy instance\", ex);\r\n }\r\n catch(IllegalAccessException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new collection proxy instance\", ex);\r\n }\r\n }", "public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable, long maxWaitTime, TimeUnit unit) {\n \tCollection<MemberResponse<T>> result = new ArrayList<MemberResponse<T>>(members.size());\n \t\n \tMap<Member, Future<T>> resultFutures = execSvc.submitToMembers(callable, members);\n \tfor(Entry<Member, Future<T>> futureEntry : resultFutures.entrySet()) {\n \t\tFuture<T> future = futureEntry.getValue();\n \t\tMember member = futureEntry.getKey();\n \t\t\n \t\ttry {\n if(maxWaitTime > 0) {\n \tresult.add(new MemberResponse<T>(member, future.get(maxWaitTime, unit)));\n } else {\n \tresult.add(new MemberResponse<T>(member, future.get()));\n } \n //ignore exceptions... return what you can\n } catch (InterruptedException e) {\n \tThread.currentThread().interrupt(); //restore interrupted status and return what we have\n \treturn result;\n } catch (MemberLeftException e) {\n \tlog.warn(\"Member {} left while trying to get a distributed callable result\", member);\n } catch (ExecutionException e) {\n \tif(e.getCause() instanceof InterruptedException) {\n \t //restore interrupted state and return\n \t Thread.currentThread().interrupt();\n \t return result;\n \t} else {\n \t log.warn(\"Unable to execute callable on \"+member+\". There was an error.\", e);\n \t}\n } catch (TimeoutException e) {\n \tlog.error(\"Unable to execute task on \"+member+\" within 10 seconds.\");\n } catch (RuntimeException e) {\n \tlog.error(\"Unable to execute task on \"+member+\". An unexpected error occurred.\", e);\n }\n \t}\n \n return result;\n }", "public DownloadRequest addCustomHeader(String key, String value) {\n mCustomHeader.put(key, value);\n return this;\n }", "private void countCoordinateStatement(Statement statement,\n\t\t\tItemDocument itemDocument) {\n\t\tValue value = statement.getValue();\n\t\tif (!(value instanceof GlobeCoordinatesValue)) {\n\t\t\treturn;\n\t\t}\n\n\t\tGlobeCoordinatesValue coordsValue = (GlobeCoordinatesValue) value;\n\t\tif (!this.globe.equals((coordsValue.getGlobe()))) {\n\t\t\treturn;\n\t\t}\n\n\t\tint xCoord = (int) (((coordsValue.getLongitude() + 180.0) / 360.0) * this.width)\n\t\t\t\t% this.width;\n\t\tint yCoord = (int) (((coordsValue.getLatitude() + 90.0) / 180.0) * this.height)\n\t\t\t\t% this.height;\n\n\t\tif (xCoord < 0 || yCoord < 0 || xCoord >= this.width\n\t\t\t\t|| yCoord >= this.height) {\n\t\t\tSystem.out.println(\"Dropping out-of-range coordinate: \"\n\t\t\t\t\t+ coordsValue);\n\t\t\treturn;\n\t\t}\n\n\t\tcountCoordinates(xCoord, yCoord, itemDocument);\n\t\tthis.count += 1;\n\n\t\tif (this.count % 100000 == 0) {\n\t\t\treportProgress();\n\t\t\twriteImages();\n\t\t}\n\t}" ]
Retrieve a number of rows matching the supplied query. @param sql query statement @return result set @throws SQLException
[ "private List<Row> getRows(String sql) throws SQLException\n {\n allocateConnection();\n\n try\n {\n List<Row> result = new LinkedList<Row>();\n\n m_ps = m_connection.prepareStatement(sql);\n m_rs = m_ps.executeQuery();\n populateMetaData();\n while (m_rs.next())\n {\n result.add(new MpdResultSetRow(m_rs, m_meta));\n }\n\n return (result);\n }\n\n finally\n {\n releaseConnection();\n }\n }" ]
[ "public static File[] getVersionDirs(File rootDir, final long minId, final long maxId) {\n return rootDir.listFiles(new FileFilter() {\n\n public boolean accept(File pathName) {\n if(checkVersionDirName(pathName)) {\n long versionId = getVersionId(pathName);\n if(versionId != -1 && versionId <= maxId && versionId >= minId) {\n return true;\n }\n }\n return false;\n }\n });\n }", "public void weeksChange(String week, Boolean value) {\n\n final WeekOfMonth changedWeek = WeekOfMonth.valueOf(week);\n boolean newValue = (null != value) && value.booleanValue();\n boolean currentValue = m_model.getWeeksOfMonth().contains(changedWeek);\n if (newValue != currentValue) {\n if (newValue) {\n setPatternScheme(true, false);\n m_model.addWeekOfMonth(changedWeek);\n onValueChange();\n } else {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.removeWeekOfMonth(changedWeek);\n onValueChange();\n }\n });\n }\n }\n }", "public List<MapRow> read() throws IOException\n {\n List<MapRow> result = new ArrayList<MapRow>();\n int fileCount = m_stream.readInt();\n if (fileCount != 0)\n {\n for (int index = 0; index < fileCount; index++)\n {\n // We use a LinkedHashMap to preserve insertion order in iteration\n // Useful when debugging the file format.\n Map<String, Object> map = new LinkedHashMap<String, Object>();\n readBlock(map);\n result.add(new MapRow(map));\n }\n }\n return result;\n }", "public Metadata add(String path, String value) {\n this.values.add(this.pathToProperty(path), value);\n this.addOp(\"add\", path, value);\n return this;\n }", "static VaultConfig loadExternalFile(File f) throws XMLStreamException {\n if(f == null) {\n throw new IllegalArgumentException(\"File is null\");\n }\n if(!f.exists()) {\n throw new XMLStreamException(\"Failed to locate vault file \" + f.getAbsolutePath());\n }\n\n final VaultConfig config = new VaultConfig();\n BufferedInputStream input = null;\n try {\n final XMLMapper mapper = XMLMapper.Factory.create();\n final XMLElementReader<VaultConfig> reader = new ExternalVaultConfigReader();\n mapper.registerRootElement(new QName(VAULT), reader);\n FileInputStream is = new FileInputStream(f);\n input = new BufferedInputStream(is);\n XMLStreamReader streamReader = XMLInputFactory.newInstance().createXMLStreamReader(input);\n mapper.parseDocument(config, streamReader);\n streamReader.close();\n } catch(FileNotFoundException e) {\n throw new XMLStreamException(\"Vault file not found\", e);\n } catch(XMLStreamException t) {\n throw t;\n } finally {\n StreamUtils.safeClose(input);\n }\n return config;\n }", "public final static int readMdLinkId(final StringBuilder out, final String in, final int start)\n {\n int pos = start;\n int counter = 1;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n boolean endReached = false;\n switch (ch)\n {\n case '\\n':\n out.append(' ');\n break;\n case '[':\n counter++;\n out.append(ch);\n break;\n case ']':\n counter--;\n if (counter == 0)\n {\n endReached = true;\n }\n else\n {\n out.append(ch);\n }\n break;\n default:\n out.append(ch);\n break;\n }\n if (endReached)\n {\n break;\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }", "public static onlinkipv6prefix[] get(nitro_service service, String ipv6prefix[]) throws Exception{\n\t\tif (ipv6prefix !=null && ipv6prefix.length>0) {\n\t\t\tonlinkipv6prefix response[] = new onlinkipv6prefix[ipv6prefix.length];\n\t\t\tonlinkipv6prefix obj[] = new onlinkipv6prefix[ipv6prefix.length];\n\t\t\tfor (int i=0;i<ipv6prefix.length;i++) {\n\t\t\t\tobj[i] = new onlinkipv6prefix();\n\t\t\t\tobj[i].set_ipv6prefix(ipv6prefix[i]);\n\t\t\t\tresponse[i] = (onlinkipv6prefix) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public void afterDeploymentValidation(@Observes @Priority(1) AfterDeploymentValidation event, BeanManager beanManager) {\n BeanManagerImpl manager = BeanManagerProxy.unwrap(beanManager);\n probe.init(manager);\n if (isJMXSupportEnabled(manager)) {\n try {\n MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();\n mbs.registerMBean(new ProbeDynamicMBean(jsonDataProvider, JsonDataProvider.class), constructProbeJsonDataMBeanName(manager, probe));\n } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {\n event.addDeploymentProblem(ProbeLogger.LOG.unableToRegisterMBean(JsonDataProvider.class, manager.getContextId(), e));\n }\n }\n addContainerLifecycleEvent(event, null, beanManager);\n exportDataIfNeeded(manager);\n }", "public static void pow(ComplexPolar_F64 a , int N , ComplexPolar_F64 result )\n {\n result.r = Math.pow(a.r,N);\n result.theta = N*a.theta;\n }" ]
Support the range subscript operator for String @param text a String @param range a Range @return a substring corresponding to the Range @since 1.0
[ "public static String getAt(String text, Range range) {\n RangeInfo info = subListBorders(text.length(), range);\n String answer = text.substring(info.from, info.to);\n if (info.reverse) {\n answer = reverse(answer);\n }\n return answer;\n }" ]
[ "private int getCostRateTableEntryIndex(Date date)\n {\n int result = -1;\n\n CostRateTable table = getCostRateTable();\n if (table != null)\n {\n if (table.size() == 1)\n {\n result = 0;\n }\n else\n {\n result = table.getIndexByDate(date);\n }\n }\n\n return result;\n }", "public Node createEmbedded(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\tResult result = executionEngine.execute( getCreateEmbeddedNodeQuery(), params );\n\t\treturn singleResult( result );\n\t}", "public static transformpolicy get(nitro_service service, String name) throws Exception{\n\t\ttransformpolicy obj = new transformpolicy();\n\t\tobj.set_name(name);\n\t\ttransformpolicy response = (transformpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void writeTaskExtendedAttributes(Project.Tasks.Task xml, Task mpx)\n {\n Project.Tasks.Task.ExtendedAttribute attrib;\n List<Project.Tasks.Task.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute();\n\n for (TaskField mpxFieldID : getAllTaskExtendedAttributes())\n {\n Object value = mpx.getCachedValue(mpxFieldID);\n\n if (FieldTypeHelper.valueIsNotDefault(mpxFieldID, value))\n {\n m_extendedAttributesInUse.add(mpxFieldID);\n\n Integer xmlFieldID = Integer.valueOf(MPPTaskField.getID(mpxFieldID) | MPPTaskField.TASK_FIELD_BASE);\n\n attrib = m_factory.createProjectTasksTaskExtendedAttribute();\n extendedAttributes.add(attrib);\n attrib.setFieldID(xmlFieldID.toString());\n attrib.setValue(DatatypeConverter.printExtendedAttribute(this, value, mpxFieldID.getDataType()));\n attrib.setDurationFormat(printExtendedAttributeDurationFormat(value));\n }\n }\n }", "public static void finishThread(){\r\n //--Create Task\r\n final long threadId = Thread.currentThread().getId();\r\n Runnable finish = new Runnable(){\r\n public void run(){\r\n releaseThreadControl(threadId);\r\n }\r\n };\r\n //--Run Task\r\n if(isThreaded){\r\n //(case: multithreaded)\r\n attemptThreadControl( threadId, finish );\r\n } else {\r\n //(case: no threading)\r\n throw new IllegalStateException(\"finishThreads() called outside of threaded environment\");\r\n }\r\n }", "public static base_responses restore(nitro_service client, appfwprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwprofile restoreresources[] = new appfwprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\trestoreresources[i] = new appfwprofile();\n\t\t\t\trestoreresources[i].archivename = resources[i].archivename;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, restoreresources,\"restore\");\n\t\t}\n\t\treturn result;\n\t}", "@SuppressWarnings(\"deprecation\")\n private void cancelRequestAndWorkers() {\n\n for (ActorRef worker : workers.values()) {\n if (worker != null && !worker.isTerminated()) {\n worker.tell(OperationWorkerMsgType.CANCEL, getSelf());\n }\n }\n\n logger.info(\"ExecutionManager sending cancelPendingRequest at time: \"\n + PcDateUtils.getNowDateTimeStr());\n }", "private boolean hasAbstractPackagePrivateSuperClassWithImplementation(Class<?> clazz, BridgeMethod bridgeMethod) {\n Class<?> superClass = clazz.getSuperclass();\n while (superClass != null) {\n if (Modifier.isAbstract(superClass.getModifiers()) && Reflections.isPackagePrivate(superClass.getModifiers())) {\n // if superclass is abstract, we need to dig deeper\n for (Method method : superClass.getDeclaredMethods()) {\n if (bridgeMethod.signature.matches(method) && method.getGenericReturnType().equals(bridgeMethod.returnType)\n && !Reflections.isAbstract(method)) {\n // this is the case we are after -> methods have same signature and the one in super class has actual implementation\n return true;\n }\n }\n }\n superClass = superClass.getSuperclass();\n }\n return false;\n }", "public static Chart getMSDLineWithConfinedModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double a, double b, double c, double d) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tdouble[] modelData = new double[lagMax - lagMin + 1];\n\t\tMeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(\n\t\t\t\tt, lagMin);\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t\tmodelData[i - lagMin] = a\n\t\t\t\t\t* (1 - b * Math.exp((-4 * d) * ((i * timelag) / a) * c));\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\t\tif(Math.abs(1-b)<0.00001 && Math.abs(1-a)<0.00001){\n\t\t\tchart.addSeries(\"y=a*(1-exp(-4*D*t/a))\", xData, modelData);\n\t\t}else{\n\t\t\tchart.addSeries(\"y=a*(1-b*exp(-4*c*D*t/a))\", xData, modelData);\n\t\t}\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}" ]
Read project data from a database. @return ProjectFile instance @throws MPXJException
[ "public ProjectFile read() throws MPXJException\n {\n MPD9DatabaseReader reader = new MPD9DatabaseReader();\n reader.setProjectID(m_projectID);\n reader.setPreserveNoteFormatting(m_preserveNoteFormatting);\n reader.setDataSource(m_dataSource);\n reader.setConnection(m_connection);\n ProjectFile project = reader.read();\n return (project);\n }" ]
[ "public FieldDescriptorDef getField(String name)\r\n {\r\n FieldDescriptorDef fieldDef = null;\r\n\r\n for (Iterator it = _fields.iterator(); it.hasNext(); )\r\n {\r\n fieldDef = (FieldDescriptorDef)it.next();\r\n if (fieldDef.getName().equals(name))\r\n {\r\n return fieldDef;\r\n }\r\n }\r\n return null;\r\n }", "public void generateMapFile(File jarFile, String mapFileName, boolean mapClassMethods) throws XMLStreamException, IOException, ClassNotFoundException, IntrospectionException\n {\n m_responseList = new LinkedList<String>();\n writeMapFile(mapFileName, jarFile, mapClassMethods);\n }", "public AT_Row setPaddingBottomChar(Character paddingBottomChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingBottomChar(paddingBottomChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public static void addInterceptors(InterceptorProvider provider) {\n PhaseManager phases = BusFactory.getDefaultBus().getExtension(PhaseManager.class);\n for (Phase p : phases.getInPhases()) {\n provider.getInInterceptors().add(new DemoInterceptor(p.getName()));\n provider.getInFaultInterceptors().add(new DemoInterceptor(p.getName()));\n }\n for (Phase p : phases.getOutPhases()) {\n provider.getOutInterceptors().add(new DemoInterceptor(p.getName()));\n provider.getOutFaultInterceptors().add(new DemoInterceptor(p.getName()));\n }\n }", "private void merge(Integer cid1, Integer cid2) {\n Collection<String> klass1 = classix.get(cid1);\n Collection<String> klass2 = classix.get(cid2);\n\n // if klass1 is the smaller, swap the two\n if (klass1.size() < klass2.size()) {\n Collection<String> tmp = klass2;\n klass2 = klass1;\n klass1 = tmp;\n\n Integer itmp = cid2;\n cid2 = cid1;\n cid1 = itmp;\n }\n\n // now perform the actual merge\n for (String id : klass2) {\n klass1.add(id);\n recordix.put(id, cid1);\n }\n\n // delete the smaller class, and we're done\n classix.remove(cid2);\n }", "private boolean hasToBuilderMethod(\n DeclaredType builder,\n boolean isExtensible,\n Iterable<ExecutableElement> methods) {\n for (ExecutableElement method : methods) {\n if (isToBuilderMethod(builder, method)) {\n if (!isExtensible) {\n messager.printMessage(ERROR,\n \"No accessible no-args Builder constructor available to implement toBuilder\",\n method);\n }\n return true;\n }\n }\n return false;\n }", "public static boolean isRevisionDumpFile(DumpContentType dumpContentType) {\n\t\tif (WmfDumpFile.REVISION_DUMP.containsKey(dumpContentType)) {\n\t\t\treturn WmfDumpFile.REVISION_DUMP.get(dumpContentType);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Unsupported dump type \"\n\t\t\t\t\t+ dumpContentType);\n\t\t}\n\t}", "public static base_response add(nitro_service client, vpath resource) throws Exception {\n\t\tvpath addresource = new vpath();\n\t\taddresource.name = resource.name;\n\t\taddresource.destip = resource.destip;\n\t\taddresource.encapmode = resource.encapmode;\n\t\treturn addresource.add_resource(client);\n\t}", "public void add(T value) {\n Element<T> element = new Element<T>(bundle, value);\n element.previous = tail;\n if (tail != null) tail.next = element;\n tail = element;\n if (head == null) head = element;\n }" ]
Loads the currently known phases from Furnace to the map.
[ "private Map<String, Class<? extends RulePhase>> loadPhases()\n {\n Map<String, Class<? extends RulePhase>> phases;\n phases = new HashMap<>();\n Furnace furnace = FurnaceHolder.getFurnace();\n for (RulePhase phase : furnace.getAddonRegistry().getServices(RulePhase.class))\n {\n @SuppressWarnings(\"unchecked\")\n Class<? extends RulePhase> unwrappedClass = (Class<? extends RulePhase>) Proxies.unwrap(phase).getClass();\n String simpleName = unwrappedClass.getSimpleName();\n phases.put(classNameToMapKey(simpleName), unwrappedClass);\n }\n return Collections.unmodifiableMap(phases);\n }" ]
[ "public static boolean isSinglePositionPrefix(FieldInfo fieldInfo,\n String prefix) throws IOException {\n if (fieldInfo == null) {\n throw new IOException(\"no fieldInfo\");\n } else {\n String info = fieldInfo.getAttribute(\n MtasCodecPostingsFormat.MTAS_FIELDINFO_ATTRIBUTE_PREFIX_SINGLE_POSITION);\n if (info == null) {\n throw new IOException(\"no \"\n + MtasCodecPostingsFormat.MTAS_FIELDINFO_ATTRIBUTE_PREFIX_SINGLE_POSITION);\n } else {\n return Arrays.asList(info.split(Pattern.quote(MtasToken.DELIMITER)))\n .contains(prefix);\n }\n }\n }", "public static String getURLParentDirectory(String urlString) throws IllegalArgumentException {\n URL url = null;\n try {\n url = new URL(urlString);\n } catch (MalformedURLException e) {\n throw Exceptions.IllegalArgument(\"Malformed URL: %s\", url);\n }\n\n String path = url.getPath();\n int lastSlashIndex = path.lastIndexOf(\"/\");\n String directory = lastSlashIndex == -1 ? \"\" : path.substring(0, lastSlashIndex);\n return String.format(\"%s://%s%s%s%s\", url.getProtocol(),\n url.getUserInfo() == null ? \"\" : url.getUserInfo() + \"@\",\n url.getHost(),\n url.getPort() == -1 ? \"\" : \":\" + Integer.toString(url.getPort()),\n directory);\n }", "public void set(float val, Layout.Axis axis) {\n switch (axis) {\n case X:\n x = val;\n break;\n case Y:\n y = val;\n break;\n case Z:\n z = val;\n break;\n default:\n throw new RuntimeAssertion(\"Bad axis specified: %s\", axis);\n }\n }", "public List<Task> getActiveTasks() {\n InputStream response = null;\n URI uri = new URIBase(getBaseUri()).path(\"_active_tasks\").build();\n try {\n response = couchDbClient.get(uri);\n return getResponseList(response, couchDbClient.getGson(), DeserializationTypes.TASKS);\n } finally {\n close(response);\n }\n }", "private final String getHeader(Map /* String, String */ headers, String name) {\n return (String) headers.get(name.toLowerCase());\n }", "public String getDynamicValue(String attribute) {\n\n return null == m_dynamicValues ? null : m_dynamicValues.get(attribute);\n }", "public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax,\n\t\t\tAbstractMeanSquaredDisplacmentEvaluator msdeval) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}", "@Nullable public View findViewById(int id) {\n if (searchView != null) {\n return searchView.findViewById(id);\n } else if (supportView != null) {\n return supportView.findViewById(id);\n }\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }", "public static pqbinding[] get(nitro_service service, pqbinding_args args) throws Exception{\n\t\tpqbinding obj = new pqbinding();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tpqbinding[] response = (pqbinding[])obj.get_resources(service, option);\n\t\treturn response;\n\t}" ]
Identifies the canonical type of an object heuristically. @return the canonical type identifier of the object's class according to Jackson's type format (see {@link TypeFactory#constructFromCanonical(String)})
[ "public String getCanonicalTypeName(Object object) {\n ensureNotNull(\"object\", object);\n\n for (TypeDetector typeDetector : typeDetectors) {\n if (typeDetector.canHandle(object)) {\n return typeDetector.detectType(object);\n }\n }\n\n throw LOG.unableToDetectCanonicalType(object);\n }" ]
[ "private void readTableData(List<SynchroTable> tables, InputStream is) throws IOException\n {\n for (SynchroTable table : tables)\n {\n if (REQUIRED_TABLES.contains(table.getName()))\n {\n readTable(is, table);\n }\n }\n }", "public void getRepresentationContent(String representationHint, String assetPath, OutputStream output) {\n\n List<Representation> reps = this.getInfoWithRepresentations(representationHint).getRepresentations();\n if (reps.size() < 1) {\n throw new BoxAPIException(\"No matching representations found\");\n }\n Representation representation = reps.get(0);\n String repState = representation.getStatus().getState();\n\n if (repState.equals(\"viewable\") || repState.equals(\"success\")) {\n\n this.makeRepresentationContentRequest(representation.getContent().getUrlTemplate(),\n assetPath, output);\n return;\n } else if (repState.equals(\"pending\") || repState.equals(\"none\")) {\n\n String repContentURLString = null;\n while (repContentURLString == null) {\n repContentURLString = this.pollRepInfo(representation.getInfo().getUrl());\n }\n\n this.makeRepresentationContentRequest(repContentURLString, assetPath, output);\n return;\n\n } else if (repState.equals(\"error\")) {\n\n throw new BoxAPIException(\"Representation had error status\");\n } else {\n\n throw new BoxAPIException(\"Representation had unknown status\");\n }\n\n }", "private void configureCaching(HttpServletResponse response, int seconds) {\n\t\t// HTTP 1.0 header\n\t\tresponse.setDateHeader(HTTP_EXPIRES_HEADER, System.currentTimeMillis() + seconds * 1000L);\n\t\tif (seconds > 0) {\n\t\t\t// HTTP 1.1 header\n\t\t\tresponse.setHeader(HTTP_CACHE_CONTROL_HEADER, \"max-age=\" + seconds);\n\t\t} else {\n\t\t\t// HTTP 1.1 header\n\t\t\tresponse.setHeader(HTTP_CACHE_CONTROL_HEADER, \"no-cache\");\n\n\t\t}\n\t}", "public String addDependency(FunctionalTaskItem dependencyTaskItem) {\n IndexableTaskItem dependency = IndexableTaskItem.create(dependencyTaskItem);\n this.addDependency(dependency);\n return dependency.key();\n }", "public static String post(String url, Map<String, String> customHeaders, Map<String, String> params) throws IOException, HTTPException {\n LOGGER.log(Level.INFO, \"Sending POST request to the url {0}\", url);\n\n HttpPost httpPost = new HttpPost(url);\n\n populateHeaders(httpPost, customHeaders);\n\n if (params != null && params.size() > 0) {\n List<NameValuePair> nameValuePairs = new ArrayList<>();\n for (Map.Entry<String, String> param : params.entrySet()) {\n nameValuePairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));\n }\n httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));\n }\n\n HttpClient httpClient = HttpClientBuilder.create().build();\n\n HttpResponse httpResponse = httpClient.execute(httpPost);\n\n int statusCode = httpResponse.getStatusLine().getStatusCode();\n if (isErrorStatus(statusCode)) {\n String jsonErrorResponse = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);\n throw new HTTPException(statusCode, httpResponse.getStatusLine().getReasonPhrase(), jsonErrorResponse);\n }\n\n return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);\n }", "private long getTime(Date start1, Date end1, Date start2, Date end2)\n {\n long total = 0;\n\n if (start1 != null && end1 != null && start2 != null && end2 != null)\n {\n long start;\n long end;\n\n if (start1.getTime() < start2.getTime())\n {\n start = start2.getTime();\n }\n else\n {\n start = start1.getTime();\n }\n\n if (end1.getTime() < end2.getTime())\n {\n end = end1.getTime();\n }\n else\n {\n end = end2.getTime();\n }\n\n if (start < end)\n {\n total = end - start;\n }\n }\n\n return (total);\n }", "public Number getCostVariance()\n {\n Number variance = (Number) getCachedValue(TaskField.COST_VARIANCE);\n if (variance == null)\n {\n Number cost = getCost();\n Number baselineCost = getBaselineCost();\n if (cost != null && baselineCost != null)\n {\n variance = NumberHelper.getDouble(cost.doubleValue() - baselineCost.doubleValue());\n set(TaskField.COST_VARIANCE, variance);\n }\n }\n return (variance);\n }", "static boolean isOnClasspath(String className) {\n boolean isOnClassPath = true;\n try {\n Class.forName(className);\n } catch (ClassNotFoundException exception) {\n isOnClassPath = false;\n }\n return isOnClassPath;\n }", "public AppMsg setLayoutGravity(int gravity) {\n mLayoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, gravity);\n return this;\n }" ]
Answer the FieldConversions for the PkFields @param cld @return the pk FieldConversions
[ "private FieldConversion[] getPkFieldConversion(ClassDescriptor cld)\r\n {\r\n FieldDescriptor[] pks = cld.getPkFields();\r\n FieldConversion[] fc = new FieldConversion[pks.length]; \r\n \r\n for (int i= 0; i < pks.length; i++)\r\n {\r\n fc[i] = pks[i].getFieldConversion();\r\n }\r\n \r\n return fc;\r\n }" ]
[ "private void deliverSyncCommand(byte command) {\n for (final SyncListener listener : getSyncListeners()) {\n try {\n switch (command) {\n\n case 0x01:\n listener.becomeMaster();\n\n case 0x10:\n listener.setSyncMode(true);\n break;\n\n case 0x20:\n listener.setSyncMode(false);\n break;\n\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering sync command to listener\", t);\n }\n }\n }", "private String formatCurrency(Number value)\n {\n return (value == null ? null : m_formats.getCurrencyFormat().format(value));\n }", "private SubProject readSubProject(byte[] data, int uniqueIDOffset, int filePathOffset, int fileNameOffset, int subprojectIndex)\n {\n try\n {\n SubProject sp = new SubProject();\n int type = SUBPROJECT_TASKUNIQUEID0;\n\n if (uniqueIDOffset != -1)\n {\n int value = MPPUtility.getInt(data, uniqueIDOffset);\n type = MPPUtility.getInt(data, uniqueIDOffset + 4);\n switch (type)\n {\n case SUBPROJECT_TASKUNIQUEID0:\n case SUBPROJECT_TASKUNIQUEID1:\n case SUBPROJECT_TASKUNIQUEID2:\n case SUBPROJECT_TASKUNIQUEID3:\n case SUBPROJECT_TASKUNIQUEID4:\n case SUBPROJECT_TASKUNIQUEID5:\n case SUBPROJECT_TASKUNIQUEID6:\n {\n sp.setTaskUniqueID(Integer.valueOf(value));\n m_taskSubProjects.put(sp.getTaskUniqueID(), sp);\n break;\n }\n\n default:\n {\n if (value != 0)\n {\n sp.addExternalTaskUniqueID(Integer.valueOf(value));\n m_taskSubProjects.put(Integer.valueOf(value), sp);\n }\n break;\n }\n }\n\n // Now get the unique id offset for this subproject\n value = 0x00800000 + ((subprojectIndex - 1) * 0x00400000);\n sp.setUniqueIDOffset(Integer.valueOf(value));\n }\n\n if (type == SUBPROJECT_TASKUNIQUEID4)\n {\n sp.setFullPath(MPPUtility.getUnicodeString(data, filePathOffset));\n }\n else\n {\n //\n // First block header\n //\n filePathOffset += 18;\n\n //\n // String size as a 4 byte int\n //\n filePathOffset += 4;\n\n //\n // Full DOS path\n //\n sp.setDosFullPath(MPPUtility.getString(data, filePathOffset));\n filePathOffset += (sp.getDosFullPath().length() + 1);\n\n //\n // 24 byte block\n //\n filePathOffset += 24;\n\n //\n // 4 byte block size\n //\n int size = MPPUtility.getInt(data, filePathOffset);\n filePathOffset += 4;\n if (size == 0)\n {\n sp.setFullPath(sp.getDosFullPath());\n }\n else\n {\n //\n // 4 byte unicode string size in bytes\n //\n size = MPPUtility.getInt(data, filePathOffset);\n filePathOffset += 4;\n\n //\n // 2 byte data\n //\n filePathOffset += 2;\n\n //\n // Unicode string\n //\n sp.setFullPath(MPPUtility.getUnicodeString(data, filePathOffset, size));\n //filePathOffset += size;\n }\n\n //\n // Second block header\n //\n fileNameOffset += 18;\n\n //\n // String size as a 4 byte int\n //\n fileNameOffset += 4;\n\n //\n // DOS file name\n //\n sp.setDosFileName(MPPUtility.getString(data, fileNameOffset));\n fileNameOffset += (sp.getDosFileName().length() + 1);\n\n //\n // 24 byte block\n //\n fileNameOffset += 24;\n\n //\n // 4 byte block size\n //\n size = MPPUtility.getInt(data, fileNameOffset);\n fileNameOffset += 4;\n\n if (size == 0)\n {\n sp.setFileName(sp.getDosFileName());\n }\n else\n {\n //\n // 4 byte unicode string size in bytes\n //\n size = MPPUtility.getInt(data, fileNameOffset);\n fileNameOffset += 4;\n\n //\n // 2 byte data\n //\n fileNameOffset += 2;\n\n //\n // Unicode string\n //\n sp.setFileName(MPPUtility.getUnicodeString(data, fileNameOffset, size));\n //fileNameOffset += size;\n }\n }\n\n //System.out.println(sp.toString());\n\n // Add to the list of subprojects\n m_file.getSubProjects().add(sp);\n\n return (sp);\n }\n\n //\n // Admit defeat at this point - we have probably stumbled\n // upon a data format we don't understand, so we'll fail\n // gracefully here. This will now be reported as a missing\n // sub project error by end users of the library, rather\n // than as an exception being thrown.\n //\n catch (ArrayIndexOutOfBoundsException ex)\n {\n return (null);\n }\n }", "@Override public void render() {\n Video video = getContent();\n renderThumbnail(video);\n renderTitle(video);\n renderMarker(video);\n renderLabel();\n }", "final public void addPositionRange(int start, int end) {\n if (tokenPosition == null) {\n tokenPosition = new MtasPosition(start, end);\n } else {\n int[] positions = new int[end - start + 1];\n for (int i = start; i <= end; i++) {\n positions[i - start] = i;\n }\n tokenPosition.add(positions);\n }\n }", "private List<File> getConfigFiles() {\n\n String[] filenames = {\n \"opencms-modules.xml\",\n \"opencms-system.xml\",\n \"opencms-vfs.xml\",\n \"opencms-importexport.xml\",\n \"opencms-sites.xml\",\n \"opencms-variables.xml\",\n \"opencms-scheduler.xml\",\n \"opencms-workplace.xml\",\n \"opencms-search.xml\"};\n List<File> result = new ArrayList<>();\n for (String fn : filenames) {\n File file = new File(m_configDir, fn);\n if (file.exists()) {\n result.add(file);\n }\n }\n return result;\n }", "public void setFullscreen(boolean fullscreen) {\n if (mBuilder.mScrimInsetsLayout != null) {\n mBuilder.mScrimInsetsLayout.setTintStatusBar(!fullscreen);\n mBuilder.mScrimInsetsLayout.setTintNavigationBar(!fullscreen);\n }\n }", "private Collection<? extends ResourceRoot> handleClassPathItems(final DeploymentUnit deploymentUnit) {\n final Set<ResourceRoot> additionalRoots = new HashSet<ResourceRoot>();\n final ArrayDeque<ResourceRoot> toProcess = new ArrayDeque<ResourceRoot>();\n final List<ResourceRoot> resourceRoots = DeploymentUtils.allResourceRoots(deploymentUnit);\n toProcess.addAll(resourceRoots);\n final Set<ResourceRoot> processed = new HashSet<ResourceRoot>(resourceRoots);\n\n while (!toProcess.isEmpty()) {\n final ResourceRoot root = toProcess.pop();\n final List<ResourceRoot> classPathRoots = root.getAttachmentList(Attachments.CLASS_PATH_RESOURCE_ROOTS);\n for(ResourceRoot cpRoot : classPathRoots) {\n if(!processed.contains(cpRoot)) {\n additionalRoots.add(cpRoot);\n toProcess.add(cpRoot);\n processed.add(cpRoot);\n }\n }\n }\n return additionalRoots;\n }", "protected void setRandom(double lower, double upper, Random generator) {\n double range = upper - lower;\n\n x = generator.nextDouble() * range + lower;\n y = generator.nextDouble() * range + lower;\n z = generator.nextDouble() * range + lower;\n }" ]
Returns the name of the current object on the specified level. @param attributes The attributes of the tag @return The property value @exception XDocletException If an error occurs @doc.tag type="content" @doc.param name="level" optional="false" description="The level for the current object" values="class,field,reference,collection"
[ "public String name(Properties attributes) throws XDocletException\r\n {\r\n return getDefForLevel(attributes.getProperty(ATTRIBUTE_LEVEL)).getName();\r\n }" ]
[ "public static base_response add(nitro_service client, nsip6 resource) throws Exception {\n\t\tnsip6 addresource = new nsip6();\n\t\taddresource.ipv6address = resource.ipv6address;\n\t\taddresource.scope = resource.scope;\n\t\taddresource.type = resource.type;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.nd = resource.nd;\n\t\taddresource.icmp = resource.icmp;\n\t\taddresource.vserver = resource.vserver;\n\t\taddresource.telnet = resource.telnet;\n\t\taddresource.ftp = resource.ftp;\n\t\taddresource.gui = resource.gui;\n\t\taddresource.ssh = resource.ssh;\n\t\taddresource.snmp = resource.snmp;\n\t\taddresource.mgmtaccess = resource.mgmtaccess;\n\t\taddresource.restrictaccess = resource.restrictaccess;\n\t\taddresource.dynamicrouting = resource.dynamicrouting;\n\t\taddresource.hostroute = resource.hostroute;\n\t\taddresource.ip6hostrtgw = resource.ip6hostrtgw;\n\t\taddresource.metric = resource.metric;\n\t\taddresource.vserverrhilevel = resource.vserverrhilevel;\n\t\taddresource.ospf6lsatype = resource.ospf6lsatype;\n\t\taddresource.ospfarea = resource.ospfarea;\n\t\taddresource.state = resource.state;\n\t\taddresource.map = resource.map;\n\t\taddresource.ownernode = resource.ownernode;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}", "private void modifyBeliefCount(int count){\n introspector.setBeliefValue(getLocalName(), Definitions.RECEIVED_MESSAGE_COUNT, getBeliefCount()+count, null);\n }", "public void setRegularExpression(String regularExpression) {\n\t\tif (regularExpression != null)\n\t\t\tthis.regularExpression = Pattern.compile(regularExpression);\n\t\telse\n\t\t\tthis.regularExpression = null;\n\t}", "public static authorizationpolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tauthorizationpolicylabel_binding obj = new authorizationpolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tauthorizationpolicylabel_binding response = (authorizationpolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static boolean isInteger(CharSequence self) {\n try {\n Integer.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "private void readResource(net.sf.mpxj.planner.schema.Resource plannerResource) throws MPXJException\n {\n Resource mpxjResource = m_projectFile.addResource();\n\n //mpxjResource.setResourceCalendar(m_projectFile.getBaseCalendarByUniqueID(getInteger(plannerResource.getCalendar())));\n mpxjResource.setEmailAddress(plannerResource.getEmail());\n mpxjResource.setUniqueID(getInteger(plannerResource.getId()));\n mpxjResource.setName(plannerResource.getName());\n mpxjResource.setNotes(plannerResource.getNote());\n mpxjResource.setInitials(plannerResource.getShortName());\n mpxjResource.setType(getInt(plannerResource.getType()) == 2 ? ResourceType.MATERIAL : ResourceType.WORK);\n //plannerResource.getStdRate();\n //plannerResource.getOvtRate();\n //plannerResource.getUnits();\n //plannerResource.getProperties();\n\n ProjectCalendar calendar = mpxjResource.addResourceCalendar();\n\n calendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n\n ProjectCalendar baseCalendar = m_projectFile.getCalendarByUniqueID(getInteger(plannerResource.getCalendar()));\n if (baseCalendar == null)\n {\n baseCalendar = m_defaultCalendar;\n }\n calendar.setParent(baseCalendar);\n\n m_eventManager.fireResourceReadEvent(mpxjResource);\n }", "@SuppressWarnings(\"unchecked\")\n\tprivate void addParameters(Model model, HttpServletRequest request) {\n\t\tfor (Object objectEntry : request.getParameterMap().entrySet()) {\n\t\t\tMap.Entry<String, String[]> entry = (Map.Entry<String, String[]>) objectEntry;\n\t\t\tString key = entry.getKey();\n\t\t\tString[] values = entry.getValue();\n\t\t\tif (null != values && values.length > 0) {\n\t\t\t\tString value = values[0];\n\t\t\t\ttry {\n\t\t\t\t\tmodel.addAttribute(key, getParameter(key, value));\n\t\t\t\t} catch (ParseException pe) {\n\t\t\t\t\tlog.error(\"Could not parse parameter value {} for {}, ignoring parameter.\", key, value);\n\t\t\t\t} catch (NumberFormatException nfe) {\n\t\t\t\t\tlog.error(\"Could not parse parameter value {} for {}, ignoring parameter.\", key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public CollectionDescriptor getCollectionDescriptorByName(String name)\r\n {\r\n if (name == null)\r\n {\r\n return null;\r\n }\r\n\r\n CollectionDescriptor cod = (CollectionDescriptor) getCollectionDescriptorNameMap().get(name);\r\n\r\n //\r\n // BRJ: if the CollectionDescriptor is not found\r\n // look in the ClassDescriptor referenced by 'super' for it\r\n //\r\n if (cod == null)\r\n {\r\n ClassDescriptor superCld = getSuperClassDescriptor();\r\n if (superCld != null)\r\n {\r\n cod = superCld.getCollectionDescriptorByName(name);\r\n }\r\n }\r\n\r\n return cod;\r\n }", "public final void setIndividualDates(SortedSet<Date> dates) {\n\n m_individualDates.clear();\n if (null != dates) {\n m_individualDates.addAll(dates);\n }\n for (Date d : getExceptions()) {\n if (!m_individualDates.contains(d)) {\n m_exceptions.remove(d);\n }\n }\n\n }" ]
Puts strings inside quotes and numerics are left as they are. @param str @return
[ "public static String createQuotedConstant(String str) {\n if (str == null || str.isEmpty()) {\n return str;\n }\n try {\n Double.parseDouble(str);\n } catch (NumberFormatException nfe) {\n return \"\\\"\" + str + \"\\\"\";\n }\n return str;\n }" ]
[ "public String getTexCoordAttr(String texName)\n {\n GVRTexture tex = textures.get(texName);\n if (tex != null)\n {\n return tex.getTexCoordAttr();\n }\n return null;\n }", "public Long getLong(String fieldName) {\n\t\ttry {\n\t\t\treturn hasValue(fieldName) ? Long.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a number.\", e);\n\t\t}\n\t}", "public static <T> List<T> copyOf(Collection<T> source) {\n Preconditions.checkNotNull(source);\n if (source instanceof ImmutableList<?>) {\n return (ImmutableList<T>) source;\n }\n if (source.isEmpty()) {\n return Collections.emptyList();\n }\n return ofInternal(source.toArray());\n }", "public static base_responses update(nitro_service client, inat resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tinat updateresources[] = new inat[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new inat();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].privateip = resources[i].privateip;\n\t\t\t\tupdateresources[i].tcpproxy = resources[i].tcpproxy;\n\t\t\t\tupdateresources[i].ftp = resources[i].ftp;\n\t\t\t\tupdateresources[i].tftp = resources[i].tftp;\n\t\t\t\tupdateresources[i].usip = resources[i].usip;\n\t\t\t\tupdateresources[i].usnip = resources[i].usnip;\n\t\t\t\tupdateresources[i].proxyip = resources[i].proxyip;\n\t\t\t\tupdateresources[i].mode = resources[i].mode;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private synchronized Class<?> getClass(String className) throws Exception {\n // see if we need to invalidate the class\n ClassInformation classInfo = classInformation.get(className);\n File classFile = new File(classInfo.pluginPath);\n if (classFile.lastModified() > classInfo.lastModified) {\n logger.info(\"Class {} has been modified, reloading\", className);\n logger.info(\"Thread ID: {}\", Thread.currentThread().getId());\n classInfo.loaded = false;\n classInformation.put(className, classInfo);\n\n // also cleanup anything in methodInformation with this className so it gets reloaded\n Iterator<Map.Entry<String, com.groupon.odo.proxylib.models.Method>> iter = methodInformation.entrySet().iterator();\n while (iter.hasNext()) {\n Map.Entry<String, com.groupon.odo.proxylib.models.Method> entry = iter.next();\n if (entry.getKey().startsWith(className)) {\n iter.remove();\n }\n }\n }\n\n if (!classInfo.loaded) {\n loadClass(className);\n }\n\n return classInfo.loadedClass;\n }", "public CollectionRequest<Story> findByTask(String task) {\n \n String path = String.format(\"/tasks/%s/stories\", task);\n return new CollectionRequest<Story>(this, Story.class, path, \"GET\");\n }", "public static void main(final String[] args) {\n if (System.getProperty(\"db.name\") == null) {\n System.out.println(\"Not running in multi-instance mode: no DB to connect to\");\n System.exit(1);\n }\n while (true) {\n try {\n Class.forName(\"org.postgresql.Driver\");\n DriverManager.getConnection(\"jdbc:postgresql://\" + System.getProperty(\"db.host\") + \":5432/\" +\n System.getProperty(\"db.name\"),\n System.getProperty(\"db.username\"),\n System.getProperty(\"db.password\"));\n System.out.println(\"Opened database successfully. Running in multi-instance mode\");\n System.exit(0);\n return;\n } catch (Exception e) {\n System.out.println(\"Failed to connect to the DB: \" + e.toString());\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e1) {\n //ignored\n }\n }\n }\n }", "public static void cleanIneligibleKeys(Map<ByteArray, Map<Value, Set<ClusterNode>>> keyVersionNodeSetMap,\n int requiredWrite) {\n Set<ByteArray> keysToDelete = new HashSet<ByteArray>();\n for (Map.Entry<ByteArray, Map<Value, Set<ClusterNode>>> entry : keyVersionNodeSetMap.entrySet()) {\n Set<Value> valuesToDelete = new HashSet<Value>();\n\n ByteArray key = entry.getKey();\n Map<Value, Set<ClusterNode>> valueNodeSetMap = entry.getValue();\n // mark version for deletion if not enough writes\n for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : valueNodeSetMap.entrySet()) {\n Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue();\n if (nodeSet.size() < requiredWrite) {\n valuesToDelete.add(versionNodeSetEntry.getKey());\n }\n }\n // delete versions\n for (Value v : valuesToDelete) {\n valueNodeSetMap.remove(v);\n }\n // mark key for deletion if no versions left\n if (valueNodeSetMap.size() == 0) {\n keysToDelete.add(key);\n }\n }\n // delete keys\n for (ByteArray k : keysToDelete) {\n keyVersionNodeSetMap.remove(k);\n }\n }", "public static Map<String, Object> introspect(Object obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {\n\t\tMap<String, Object> result = new HashMap<>();\n\t\tBeanInfo info = Introspector.getBeanInfo( obj.getClass() );\n\t\tfor ( PropertyDescriptor pd : info.getPropertyDescriptors() ) {\n\t\t\tMethod reader = pd.getReadMethod();\n\t\t\tString name = pd.getName();\n\t\t\tif ( reader != null && !\"class\".equals( name ) ) {\n\t\t\t\tresult.put( name, reader.invoke( obj ) );\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}" ]
Print classes that were parts of relationships, but not parsed by javadoc
[ "public void printExtraClasses(RootDoc root) {\n\tSet<String> names = new HashSet<String>(classnames.keySet()); \n\tfor(String className: names) {\n\t ClassInfo info = getClassInfo(className, true);\n\t if (info.nodePrinted)\n\t\tcontinue;\n\t ClassDoc c = root.classNamed(className);\n\t if(c != null) {\n\t\tprintClass(c, false);\n\t\tcontinue;\n\t }\n\t // Handle missing classes:\n\t Options opt = optionProvider.getOptionsFor(className);\n\t if(opt.matchesHideExpression(className))\n\t\tcontinue;\n\t w.println(linePrefix + \"// \" + className);\n\t w.print(linePrefix + info.name + \"[label=\");\n\t externalTableStart(opt, className, classToUrl(className));\n\t innerTableStart();\n\t String qualifiedName = qualifiedName(opt, className);\n\t int startTemplate = qualifiedName.indexOf('<');\n\t int idx = qualifiedName.lastIndexOf('.', startTemplate < 0 ? qualifiedName.length() - 1 : startTemplate);\n\t if(opt.postfixPackage && idx > 0 && idx < (qualifiedName.length() - 1)) {\n\t\tString packageName = qualifiedName.substring(0, idx);\n\t\tString cn = qualifiedName.substring(idx + 1);\n\t\ttableLine(Align.CENTER, Font.CLASS.wrap(opt, escape(cn)));\n\t\ttableLine(Align.CENTER, Font.PACKAGE.wrap(opt, packageName));\n\t } else {\n\t\ttableLine(Align.CENTER, Font.CLASS.wrap(opt, escape(qualifiedName)));\n\t }\n\t innerTableEnd();\n\t externalTableEnd();\n\t if (className == null || className.length() == 0)\n\t\tw.print(\",URL=\\\"\" + classToUrl(className) + \"\\\"\");\n\t nodeProperties(opt);\n\t}\n }" ]
[ "public static Object newInstance(String className, Class[] types, Object[] args) throws InstantiationException,\r\n IllegalAccessException,\r\n IllegalArgumentException,\r\n InvocationTargetException,\r\n NoSuchMethodException,\r\n SecurityException,\r\n ClassNotFoundException\r\n {\r\n return newInstance(getClass(className), types, args);\r\n }", "protected void putConnectionBackInPartition(ConnectionHandle connectionHandle) throws SQLException {\r\n\r\n\t\tif (this.cachedPoolStrategy && ((CachedConnectionStrategy)this.connectionStrategy).tlConnections.dumbGet().getValue()){\r\n\t\t\tconnectionHandle.logicallyClosed.set(true);\r\n\t\t\t((CachedConnectionStrategy)this.connectionStrategy).tlConnections.set(new AbstractMap.SimpleEntry<ConnectionHandle, Boolean>(connectionHandle, false));\r\n\t\t} else {\r\n\t\t\tBlockingQueue<ConnectionHandle> queue = connectionHandle.getOriginatingPartition().getFreeConnections();\r\n\t\t\t\tif (!queue.offer(connectionHandle)){ // this shouldn't fail\r\n\t\t\t\t\tconnectionHandle.internalClose();\r\n\t\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t}", "protected void checkJobType(final String jobName, final Class<?> jobType) {\n if (jobName == null) {\n throw new IllegalArgumentException(\"jobName must not be null\");\n }\n if (jobType == null) {\n throw new IllegalArgumentException(\"jobType must not be null\");\n }\n if (!(Runnable.class.isAssignableFrom(jobType)) \n && !(Callable.class.isAssignableFrom(jobType))) {\n throw new IllegalArgumentException(\n \"jobType must implement either Runnable or Callable: \" + jobType);\n }\n }", "public static URI setQueryParams(final URI initialUri, final Multimap<String, String> queryParams) {\n StringBuilder queryString = new StringBuilder();\n for (Map.Entry<String, String> entry: queryParams.entries()) {\n if (queryString.length() > 0) {\n queryString.append(\"&\");\n }\n queryString.append(entry.getKey()).append(\"=\").append(entry.getValue());\n }\n try {\n if (initialUri.getHost() == null && initialUri.getAuthority() != null) {\n return new URI(initialUri.getScheme(), initialUri.getAuthority(), initialUri.getPath(),\n queryString.toString(),\n initialUri.getFragment());\n } else {\n return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),\n initialUri.getPort(),\n initialUri.getPath(),\n queryString.toString(), initialUri.getFragment());\n }\n } catch (URISyntaxException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }", "public final int getJdbcType()\r\n {\r\n switch (this.fieldSource)\r\n {\r\n case SOURCE_FIELD :\r\n return this.getFieldRef().getJdbcType().getType();\r\n case SOURCE_NULL :\r\n return java.sql.Types.NULL;\r\n case SOURCE_VALUE :\r\n return java.sql.Types.VARCHAR;\r\n default :\r\n return java.sql.Types.NULL;\r\n }\r\n }", "public static Attachment fromBinaryInputStream( InputStream inputStream, MediaType mediaType ) throws IOException {\n return fromBinaryBytes( ByteStreams.toByteArray( inputStream ), mediaType );\n }", "public static Filter.Builder makeAncestorFilter(Key ancestor) {\n return makeFilter(\n DatastoreHelper.KEY_PROPERTY_NAME, PropertyFilter.Operator.HAS_ANCESTOR,\n makeValue(ancestor));\n }", "public static java.sql.Date newDate() {\n return new java.sql.Date((System.currentTimeMillis() / DAY_MILLIS) * DAY_MILLIS);\n }", "public Set<Annotation> getPropertyAnnotations()\n\t{\n\t\tif (accessor instanceof PropertyAwareAccessor)\n\t\t{\n\t\t\treturn unmodifiableSet(((PropertyAwareAccessor) accessor).getReadMethodAnnotations());\n\t\t}\n\t\treturn unmodifiableSet(Collections.<Annotation>emptySet());\n\t}" ]
parse when there are two date-times
[ "private static Interval parseEndDateTime(Instant start, ZoneOffset offset, CharSequence endStr) {\n try {\n TemporalAccessor temporal = DateTimeFormatter.ISO_DATE_TIME.parseBest(endStr, OffsetDateTime::from, LocalDateTime::from);\n if (temporal instanceof OffsetDateTime) {\n OffsetDateTime odt = (OffsetDateTime) temporal;\n return Interval.of(start, odt.toInstant());\n } else {\n // infer offset from start if not specified by end\n LocalDateTime ldt = (LocalDateTime) temporal;\n return Interval.of(start, ldt.toInstant(offset));\n }\n } catch (DateTimeParseException ex) {\n Instant end = Instant.parse(endStr);\n return Interval.of(start, end);\n }\n }" ]
[ "public ReferrerList getCollectionReferrers(Date date, String domain, String collectionId, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_COLLECTION_REFERRERS, domain, \"collection_id\", collectionId, date, perPage, page);\n }", "public ItemRequest<CustomField> updateEnumOption(String enumOption) {\n \n String path = String.format(\"/enum_options/%s\", enumOption);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"PUT\");\n }", "public static ComplexNumber Tan(ComplexNumber z1) {\r\n ComplexNumber result = new ComplexNumber();\r\n\r\n if (z1.imaginary == 0.0) {\r\n result.real = Math.tan(z1.real);\r\n result.imaginary = 0.0;\r\n } else {\r\n double real2 = 2 * z1.real;\r\n double imag2 = 2 * z1.imaginary;\r\n double denom = Math.cos(real2) + Math.cosh(real2);\r\n\r\n result.real = Math.sin(real2) / denom;\r\n result.imaginary = Math.sinh(imag2) / denom;\r\n }\r\n\r\n return result;\r\n }", "private static JsonNode findNestedNode(JsonNode jsonNode, String composedKey) {\n String[] jsonNodeKeys = splitKeyByFlatteningDots(composedKey);\n for (String jsonNodeKey : jsonNodeKeys) {\n jsonNode = jsonNode.get(unescapeEscapedDots(jsonNodeKey));\n if (jsonNode == null) {\n return null;\n }\n }\n return jsonNode;\n }", "private static boolean isDpiSet(final Multimap<String, String> extraParams) {\n String searchKey = \"FORMAT_OPTIONS\";\n for (String key: extraParams.keys()) {\n if (key.equalsIgnoreCase(searchKey)) {\n for (String value: extraParams.get(key)) {\n if (value.toLowerCase().contains(\"dpi:\")) {\n return true;\n }\n }\n }\n }\n return false;\n }", "public static ProjectReader getProjectReader(String name) throws MPXJException\n {\n int index = name.lastIndexOf('.');\n if (index == -1)\n {\n throw new IllegalArgumentException(\"Filename has no extension: \" + name);\n }\n\n String extension = name.substring(index + 1).toUpperCase();\n\n Class<? extends ProjectReader> fileClass = READER_MAP.get(extension);\n if (fileClass == null)\n {\n throw new IllegalArgumentException(\"Cannot read files of type: \" + extension);\n }\n\n try\n {\n ProjectReader file = fileClass.newInstance();\n return (file);\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to load project reader\", ex);\n }\n }", "@Override\n public Symmetry454Date date(int prolepticYear, int month, int dayOfMonth) {\n return Symmetry454Date.of(prolepticYear, month, dayOfMonth);\n }", "protected boolean isValidLayout(Gravity gravity, Orientation orientation) {\n boolean isValid = true;\n\n switch (gravity) {\n case TOP:\n case BOTTOM:\n isValid = (!isUnlimitedSize() && orientation == Orientation.VERTICAL);\n break;\n case LEFT:\n case RIGHT:\n isValid = (!isUnlimitedSize() && orientation == Orientation.HORIZONTAL);\n break;\n case FRONT:\n case BACK:\n isValid = (!isUnlimitedSize() && orientation == Orientation.STACK);\n break;\n case FILL:\n isValid = !isUnlimitedSize();\n break;\n case CENTER:\n break;\n default:\n isValid = false;\n break;\n }\n if (!isValid) {\n Log.w(TAG, \"Cannot set the gravity %s and orientation %s - \" +\n \"due to unlimited bounds or incompatibility\", gravity, orientation);\n }\n return isValid;\n }", "@SuppressWarnings(\"serial\")\n private Component createCloseButton() {\n\n Button closeBtn = CmsToolBar.createButton(\n FontOpenCms.CIRCLE_INV_CANCEL,\n m_messages.key(Messages.GUI_BUTTON_CANCEL_0));\n closeBtn.addClickListener(new ClickListener() {\n\n public void buttonClick(ClickEvent event) {\n\n closeAction();\n }\n\n });\n return closeBtn;\n }" ]
Use this API to update rsskeytype.
[ "public static base_response update(nitro_service client, rsskeytype resource) throws Exception {\n\t\trsskeytype updateresource = new rsskeytype();\n\t\tupdateresource.rsstype = resource.rsstype;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
[ "private static synchronized FileOutputWriter createFileWriter(final TypeDefinition type, final DecompilerSettings settings)\n throws IOException\n {\n final String outputDirectory = settings.getOutputDirectory();\n\n final String fileName = type.getName() + settings.getLanguage().getFileExtension();\n final String packageName = type.getPackageName();\n\n // foo.Bar -> foo/Bar.java\n final String subDir = StringUtils.defaultIfEmpty(packageName, \"\").replace('.', File.separatorChar);\n final String outputPath = PathHelper.combine(outputDirectory, subDir, fileName);\n\n final File outputFile = new File(outputPath);\n final File parentDir = outputFile.getParentFile();\n\n if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs())\n {\n throw new IllegalStateException(\"Could not create directory:\" + parentDir);\n }\n\n if (!outputFile.exists() && !outputFile.createNewFile())\n {\n throw new IllegalStateException(\"Could not create output file: \" + outputPath);\n }\n\n return new FileOutputWriter(outputFile, settings);\n }", "public final void notifyFooterItemRangeRemoved(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemRangeRemoved(positionStart + headerItemCount + contentItemCount, itemCount);\n }", "public static int rank( DMatrixRMaj A ) {\n SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(A.numRows,A.numCols,false,true,true);\n\n if( svd.inputModified() ) {\n A = A.copy();\n }\n if( !svd.decompose(A)) {\n throw new RuntimeException(\"SVD Failed!\");\n }\n\n int N = svd.numberOfSingularValues();\n double sv[] = svd.getSingularValues();\n\n double threshold = singularThreshold(sv,N);\n int count = 0;\n for (int i = 0; i < sv.length; i++) {\n if( sv[i] >= threshold ) {\n count++;\n }\n }\n return count;\n }", "private boolean checkDeploymentDir(File directory) {\n if (!directory.exists()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.directoryIsNonexistent(deploymentDir.getAbsolutePath());\n }\n }\n else if (!directory.isDirectory()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.isNotADirectory(deploymentDir.getAbsolutePath());\n }\n }\n else if (!directory.canRead()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.directoryIsNotReadable(deploymentDir.getAbsolutePath());\n }\n }\n else if (!directory.canWrite()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.directoryIsNotWritable(deploymentDir.getAbsolutePath());\n }\n } else {\n deploymentDirAccessible = true;\n }\n\n return deploymentDirAccessible;\n }", "private void handleMultiInstanceEncapResponse(\r\n\t\t\tSerialMessage serialMessage, int offset) {\r\n\t\tlogger.trace(\"Process Multi-instance Encapsulation\");\r\n\t\tint instance = serialMessage.getMessagePayloadByte(offset);\r\n\t\tint commandClassCode = serialMessage.getMessagePayloadByte(offset + 1);\r\n\t\tCommandClass commandClass = CommandClass.getCommandClass(commandClassCode);\r\n\r\n\t\tif (commandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d Requested Command Class = %s (0x%02x)\", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));\r\n\t\tZWaveCommandClass zwaveCommandClass = this.getNode().getCommandClass(commandClass);\r\n\t\t\r\n\t\tif (zwaveCommandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Unsupported command class %s (0x%02x)\", commandClass.getLabel(), commandClassCode));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d, Instance = %d, calling handleApplicationCommandRequest.\", this.getNode().getNodeId(), instance));\r\n\t\tzwaveCommandClass.handleApplicationCommandRequest(serialMessage, offset+ 3, instance);\r\n\t}", "private String getRelativePomPath(MavenModule mavenModule, MavenModuleSetBuild mavenBuild) {\n String relativePath = mavenModule.getRelativePath();\n if (StringUtils.isBlank(relativePath)) {\n return POM_NAME;\n }\n\n // If this is the root module, return the root pom path.\n if (mavenModule.getModuleName().toString().\n equals(mavenBuild.getProject().getRootModule().getModuleName().toString())) {\n return mavenBuild.getProject().getRootPOM(null);\n }\n\n // to remove the project folder name if exists\n // keeps only the name of the module\n String modulePath = relativePath.substring(relativePath.indexOf(\"/\") + 1);\n for (String moduleName : mavenModules) {\n if (moduleName.contains(modulePath)) {\n return createPomPath(relativePath, moduleName);\n }\n }\n\n // In case this module is not in the parent pom\n return relativePath + \"/\" + POM_NAME;\n }", "public AsciiTable setPaddingRight(int paddingRight) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingRight(paddingRight);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public List<Integer> getTrackIds() {\n ArrayList<Integer> results = new ArrayList<Integer>(trackCount);\n Enumeration<? extends ZipEntry> entries = zipFile.entries();\n while (entries.hasMoreElements()) {\n ZipEntry entry = entries.nextElement();\n if (entry.getName().startsWith(CACHE_METADATA_ENTRY_PREFIX)) {\n String idPart = entry.getName().substring(CACHE_METADATA_ENTRY_PREFIX.length());\n if (idPart.length() > 0) {\n results.add(Integer.valueOf(idPart));\n }\n }\n }\n\n return Collections.unmodifiableList(results);\n }", "public static String formatConnectionTerminationMessage(final String connectionName, final String host, final String connectionReason, final String terminationReason) {\n\t\treturn CON_TERMINATION_FORMAT.format(new Object[] { connectionName, host, connectionReason, terminationReason });\n\t}" ]
open a readable or writeable FileChannel @param file file object @param mutable writeable @return open the FileChannel @throws IOException any io exception
[ "@SuppressWarnings(\"resource\")\n public static FileChannel openChannel(File file, boolean mutable) throws IOException {\n if (mutable) {\n return new RandomAccessFile(file, \"rw\").getChannel();\n }\n return new FileInputStream(file).getChannel();\n }" ]
[ "public static LinearSolverDense<DMatrixRMaj> general(int numRows , int numCols ) {\n if( numRows == numCols )\n return linear(numRows);\n else\n return leastSquares(numRows,numCols);\n }", "public synchronized HttpServer<Buffer, Buffer> start() throws Exception {\n\t\tif (server == null) {\n\t\t\tserver = createProtocolListener();\n\t\t}\n\t\treturn server;\n\t}", "public static final Double getPercentage(byte[] data, int offset)\n {\n int value = MPPUtility.getShort(data, offset);\n Double result = null;\n if (value >= 0 && value <= 100)\n {\n result = NumberHelper.getDouble(value);\n }\n return result;\n }", "@Pure\n\tpublic static <P1> Procedure0 curry(final Procedure1<? super P1> procedure, final P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure0() {\n\t\t\t@Override\n\t\t\tpublic void apply() {\n\t\t\t\tprocedure.apply(argument);\n\t\t\t}\n\t\t};\n\t}", "public PathElement getLastElement() {\n final List<PathElement> list = pathAddressList;\n return list.size() == 0 ? null : list.get(list.size() - 1);\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<AccountingDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<AccountingDate>) super.localDateTime(temporal);\n }", "private boolean hasToBuilderMethod(\n DeclaredType builder,\n boolean isExtensible,\n Iterable<ExecutableElement> methods) {\n for (ExecutableElement method : methods) {\n if (isToBuilderMethod(builder, method)) {\n if (!isExtensible) {\n messager.printMessage(ERROR,\n \"No accessible no-args Builder constructor available to implement toBuilder\",\n method);\n }\n return true;\n }\n }\n return false;\n }", "public float getLayoutSize(final Layout.Axis axis) {\n float size = 0;\n for (Layout layout : mLayouts) {\n size = Math.max(size, layout.getSize(axis));\n }\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"getLayoutSize [%s] axis [%s] size [%f]\", getName(), axis, size);\n return size;\n }", "public Object get(int dataSet) throws SerializationException {\r\n\t\tObject result = null;\r\n\t\tfor (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) {\r\n\t\t\tDataSet ds = i.next();\r\n\t\t\tDataSetInfo info = ds.getInfo();\r\n\t\t\tif (info.getDataSetNumber() == dataSet) {\r\n\t\t\t\tresult = getData(ds);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}" ]
Adds another condition for an element within this annotation.
[ "public AnnotationTypeCondition addCondition(String element, AnnotationCondition condition)\n {\n this.conditions.put(element, condition);\n return this;\n }" ]
[ "@Api\n\tpublic void setNamedRoles(Map<String, List<NamedRoleInfo>> namedRoles) {\n\t\tthis.namedRoles = namedRoles;\n\t\tldapRoleMapping = new HashMap<String, Set<String>>();\n\t\tfor (String roleName : namedRoles.keySet()) {\n\t\t\tif (!ldapRoleMapping.containsKey(roleName)) {\n\t\t\t\tldapRoleMapping.put(roleName, new HashSet<String>());\n\t\t\t}\n\t\t\tfor (NamedRoleInfo role : namedRoles.get(roleName)) {\n\t\t\t\tldapRoleMapping.get(roleName).add(role.getName());\n\t\t\t}\n\t\t}\n\t}", "public static void dumpBlockData(int headerSize, int blockSize, byte[] data)\n {\n if (data != null)\n {\n System.out.println(ByteArrayHelper.hexdump(data, 0, headerSize, false));\n int index = headerSize;\n while (index < data.length)\n {\n System.out.println(ByteArrayHelper.hexdump(data, index, blockSize, false));\n index += blockSize;\n }\n }\n }", "private void addForward(AnalyticModel model, double fixingTime, RandomVariable forward, boolean isParameter) {\n\t\tdouble interpolationEntitiyTime;\n\t\tRandomVariable interpolationEntityForwardValue;\n\t\tswitch(interpolationEntityForward) {\n\t\tcase FORWARD:\n\t\tdefault:\n\t\t\tinterpolationEntitiyTime = fixingTime;\n\t\t\tinterpolationEntityForwardValue = forward;\n\t\t\tbreak;\n\t\tcase FORWARD_TIMES_DISCOUNTFACTOR:\n\t\t\tinterpolationEntitiyTime = fixingTime;\n\t\t\tinterpolationEntityForwardValue = forward.mult(model.getDiscountCurve(getDiscountCurveName()).getValue(model, fixingTime+getPaymentOffset(fixingTime)));\n\t\t\tbreak;\n\t\tcase ZERO:\n\t\t{\n\t\t\tdouble paymentOffset = getPaymentOffset(fixingTime);\n\t\t\tinterpolationEntitiyTime = fixingTime+paymentOffset;\n\t\t\tinterpolationEntityForwardValue = forward.mult(paymentOffset).add(1.0).log().div(paymentOffset);\n\t\t\tbreak;\n\t\t}\n\t\tcase DISCOUNTFACTOR:\n\t\t{\n\t\t\tdouble paymentOffset = getPaymentOffset(fixingTime);\n\t\t\tinterpolationEntitiyTime\t\t= fixingTime+paymentOffset;\n\t\t\tinterpolationEntityForwardValue = getValue(fixingTime).div(forward.mult(paymentOffset).add(1.0));\n\t\t\tbreak;\n\t\t}\n\t\t}\n\t\tsuper.addPoint(interpolationEntitiyTime, interpolationEntityForwardValue, isParameter);\n\t}", "private void convertJdkPath(Launcher launcher, EnvVars extendedEnv) {\n String separator = launcher.isUnix() ? \"/\" : \"\\\\\";\n String java_home = extendedEnv.get(\"JAVA_HOME\");\n if (StringUtils.isNotEmpty(java_home)) {\n if (!StringUtils.endsWith(java_home, separator)) {\n java_home += separator;\n }\n extendedEnv.put(\"PATH+JDK\", java_home + \"bin\");\n }\n }", "public static String notNullOrEmpty(String argument, String argumentName) {\n if (argument == null || argument.trim().isEmpty()) {\n throw new IllegalArgumentException(\"Argument \" + argumentName + \" must not be null or empty.\");\n }\n return argument;\n }", "protected Element createImageElement(float x, float y, float width, float height, ImageResource resource) throws IOException\n {\n StringBuilder pstyle = new StringBuilder(\"position:absolute;\");\n pstyle.append(\"left:\").append(x).append(UNIT).append(';');\n pstyle.append(\"top:\").append(y).append(UNIT).append(';');\n pstyle.append(\"width:\").append(width).append(UNIT).append(';');\n pstyle.append(\"height:\").append(height).append(UNIT).append(';');\n //pstyle.append(\"border:1px solid red;\");\n \n Element el = doc.createElement(\"img\");\n el.setAttribute(\"style\", pstyle.toString());\n\n String imgSrc = config.getImageHandler().handleResource(resource);\n\n if (!disableImageData && !imgSrc.isEmpty())\n el.setAttribute(\"src\", imgSrc);\n else\n el.setAttribute(\"src\", \"\");\n \n return el;\n }", "@Override\n\tprotected void doLinking() {\n\t\tIParseResult parseResult = getParseResult();\n\t\tif (parseResult == null || parseResult.getRootASTElement() == null)\n\t\t\treturn;\n\n\t\tXtextLinker castedLinker = (XtextLinker) getLinker();\n\t\tcastedLinker.discardGeneratedPackages(parseResult.getRootASTElement());\n\t}", "public synchronized X509Certificate getCertificateByHostname(final String hostname) throws KeyStoreException, CertificateParsingException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, SignatureException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, UnrecoverableKeyException{\n\n\t\tString alias = _subjectMap.get(getSubjectForHostname(hostname));\n\n\t\tif(alias != null) {\n\t\t\treturn (X509Certificate)_ks.getCertificate(alias);\n\t\t}\n return getMappedCertificateForHostname(hostname);\n\t}", "ProtectionDomain getProtectionDomainForProxy(ProtectionDomain domain) {\n if (domain.getCodeSource() == null) {\n // no codesource to cache on\n return create(domain);\n }\n ProtectionDomain proxyProtectionDomain = proxyProtectionDomains.get(domain.getCodeSource());\n if (proxyProtectionDomain == null) {\n // as this is not atomic create() may be called multiple times for the same domain\n // we ignore that\n proxyProtectionDomain = create(domain);\n ProtectionDomain existing = proxyProtectionDomains.putIfAbsent(domain.getCodeSource(), proxyProtectionDomain);\n if (existing != null) {\n proxyProtectionDomain = existing;\n }\n }\n return proxyProtectionDomain;\n }" ]
Determine whether the given method is a "readString" method. @see Object#toString()
[ "public static boolean isToStringMethod(Method method) {\n return (method != null && method.getName().equals(\"readString\") && method.getParameterTypes().length == 0);\n }" ]
[ "public List getFeedback()\n\t {\n\t List<?> messages = new ArrayList();\n\t for ( ValueSource vs : valueSources )\n\t {\n\t List feedback = vs.getFeedback();\n\t if ( feedback != null && !feedback.isEmpty() )\n\t {\n\t messages.addAll( feedback );\n\t }\n\t }\n\n\t return messages;\n\t }", "@Override\n\tpublic CrawlSession call() {\n\t\tsetMaximumCrawlTimeIfNeeded();\n\t\tplugins.runPreCrawlingPlugins(config);\n\t\tCrawlTaskConsumer firstConsumer = consumerFactory.get();\n\t\tStateVertex firstState = firstConsumer.crawlIndex();\n\t\tcrawlSessionProvider.setup(firstState);\n\t\tplugins.runOnNewStatePlugins(firstConsumer.getContext(), firstState);\n\t\texecuteConsumers(firstConsumer);\n\t\treturn crawlSessionProvider.get();\n\t}", "public int size(final K1 firstKey) {\n\t\t// existence check on inner map\n\t\tfinal HashMap<K2, HashMap<K3, V>> innerMap = map.get(firstKey);\n\t\tif( innerMap == null ) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn innerMap.size();\n\t}", "public String join(List<String> list) {\n\n if (list == null) {\n return null;\n }\n\n StringBuilder sb = new StringBuilder();\n boolean first = true;\n for (String s : list) {\n\n if (s == null) {\n if (convertEmptyToNull) {\n s = \"\";\n } else {\n throw new IllegalArgumentException(\"StringListFlattener does not support null strings in the list. Consider calling setConvertEmptyToNull(true).\");\n }\n }\n\n if (!first) {\n sb.append(separator);\n }\n\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (c == escapeChar || c == separator) {\n sb.append(escapeChar);\n }\n sb.append(c);\n }\n\n first = false;\n }\n return sb.toString();\n }", "private static long createLongSeed(byte[] seed)\n {\n if (seed == null || seed.length != SEED_SIZE_BYTES)\n {\n throw new IllegalArgumentException(\"Java RNG requires a 64-bit (8-byte) seed.\");\n }\n return BinaryUtils.convertBytesToLong(seed, 0);\n }", "public Set<String> rangeByRankReverse(final long start, final long end) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n return jedis.zrevrange(getKey(), start, end);\n }\n });\n }", "private void validationRelations(Task task)\n {\n List<Relation> predecessors = task.getPredecessors();\n if (!predecessors.isEmpty())\n {\n ArrayList<Relation> invalid = new ArrayList<Relation>();\n for (Relation relation : predecessors)\n {\n Task sourceTask = relation.getSourceTask();\n Task targetTask = relation.getTargetTask();\n\n String sourceOutlineNumber = sourceTask.getOutlineNumber();\n String targetOutlineNumber = targetTask.getOutlineNumber();\n\n if (sourceOutlineNumber != null && targetOutlineNumber != null && sourceOutlineNumber.startsWith(targetOutlineNumber + '.'))\n {\n invalid.add(relation);\n }\n }\n\n for (Relation relation : invalid)\n {\n relation.getSourceTask().removePredecessor(relation.getTargetTask(), relation.getType(), relation.getLag());\n }\n }\n }", "private String parseLayerId(HttpServletRequest request) {\n\t\tStringTokenizer tokenizer = new StringTokenizer(request.getRequestURI(), \"/\");\n\t\tString token = \"\";\n\t\twhile (tokenizer.hasMoreTokens()) {\n\t\t\ttoken = tokenizer.nextToken();\n\t\t}\n\t\treturn token;\n\t}", "protected void setBeanDeploymentArchivesAccessibility() {\n for (WeldBeanDeploymentArchive beanDeploymentArchive : beanDeploymentArchives) {\n Set<WeldBeanDeploymentArchive> accessibleArchives = new HashSet<>();\n for (WeldBeanDeploymentArchive candidate : beanDeploymentArchives) {\n if (candidate.equals(beanDeploymentArchive)) {\n continue;\n }\n accessibleArchives.add(candidate);\n }\n beanDeploymentArchive.setAccessibleBeanDeploymentArchives(accessibleArchives);\n }\n }" ]
Stops the current debug server. Active connections are not affected.
[ "public synchronized void stopDebugServer() {\n if (mDebugServer == null) {\n Log.e(TAG, \"Debug server is not running.\");\n return;\n }\n\n mDebugServer.shutdown();\n mDebugServer = null;\n }" ]
[ "@Override\n public void start(String[] arguments) {\n boolean notStarted = !started.getAndSet(true);\n if (notStarted) {\n start(new MultiInstanceWorkloadStrategy(factory, name, arguments, endpointRegistry, execService));\n }\n }", "private void processEncodedPayload() throws IOException {\n if (!readPayload) {\n payloadSpanCollector.reset();\n collect(payloadSpanCollector);\n Collection<byte[]> originalPayloadCollection = payloadSpanCollector\n .getPayloads();\n if (originalPayloadCollection.iterator().hasNext()) {\n byte[] payload = originalPayloadCollection.iterator().next();\n if (payload == null) {\n throw new IOException(\"no payload\");\n }\n MtasPayloadDecoder payloadDecoder = new MtasPayloadDecoder();\n payloadDecoder.init(startPosition(), payload);\n mtasPosition = payloadDecoder.getMtasPosition();\n } else {\n throw new IOException(\"no payload\");\n }\n }\n }", "private String getTaskField(int key)\n {\n String result = null;\n\n if ((key > 0) && (key < m_taskNames.length))\n {\n result = m_taskNames[key];\n }\n\n return (result);\n }", "public static Integer getDurationValue(ProjectProperties properties, Duration duration)\n {\n Integer result;\n if (duration == null)\n {\n result = null;\n }\n else\n {\n if (duration.getUnits() != TimeUnit.MINUTES)\n {\n duration = duration.convertUnits(TimeUnit.MINUTES, properties);\n }\n result = Integer.valueOf((int) duration.getDuration());\n }\n return (result);\n }", "public static String getOperationName(final ModelNode op) {\n if (op.hasDefined(OP)) {\n return op.get(OP).asString();\n }\n throw ControllerClientLogger.ROOT_LOGGER.operationNameNotFound();\n }", "public static <T> T buildInstanceForMap(Class<T> clazz, Map<String, Object> values, MyReflectionDifferenceHandler differenceHandler)\n throws InstantiationException, IllegalAccessException, IntrospectionException,\n IllegalArgumentException, InvocationTargetException {\n\n log.debug(\"Building new instance of Class \" + clazz.getName());\n\n T instance = clazz.newInstance();\n\n for (String key : values.keySet()) {\n Object value = values.get(key);\n\n if (value == null) {\n log.debug(\"Value for field \" + key + \" is null, so ignoring it...\");\n continue;\n }\n \n log.debug(\n \"Invoke setter for \" + key + \" (\" + value.getClass() + \" / \" + value.toString() + \")\");\n Method setter = null;\n try {\n setter = new PropertyDescriptor(key.replace('.', '_'), clazz).getWriteMethod();\n } catch (Exception e) {\n throw new IllegalArgumentException(\"Setter for field \" + key + \" was not found\", e);\n }\n\n Class<?> argumentType = setter.getParameterTypes()[0];\n\n if (argumentType.isAssignableFrom(value.getClass())) {\n setter.invoke(instance, value);\n } else {\n\n Object newValue = differenceHandler.handleDifference(value, setter.getParameterTypes()[0]);\n setter.invoke(instance, newValue);\n\n }\n }\n\n return instance;\n }", "public void setWorkConnection(CmsSetupDb db) {\n\n db.setConnection(\n m_setupBean.getDbDriver(),\n m_setupBean.getDbWorkConStr(),\n m_setupBean.getDbConStrParams(),\n m_setupBean.getDbWorkUser(),\n m_setupBean.getDbWorkPwd());\n }", "@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher cancelPendingRequests() {\n if (pendingRequests.size() != 0) {\n for (int i = 0; i < pendingRequests.size(); i++) {\n int reqId = pendingRequests.keyAt(i);\n Request r = pendingRequests.valueAt(i);\n if (!r.isFinished() && !r.isCancelled()) {\n cancelRequest(r, reqId);\n }\n }\n }\n return this;\n }", "public PhotoList<Photo> getPopularPhotos(Date date, StatsSort sort, int perPage, int page) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_POPULAR_PHOTOS);\n if (date != null) {\n parameters.put(\"date\", String.valueOf(date.getTime() / 1000L));\n }\n if (sort != null) {\n parameters.put(\"sort\", sort.name());\n }\n addPaginationParameters(parameters, perPage, page);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n return parsePopularPhotos(response);\n }" ]
Create a document that parses the tile's featureFragment, using GraphicsWriter classes. @param writer writer @return document @throws RenderException oops
[ "private GraphicsDocument createFeatureDocument(StringWriter writer) throws RenderException {\n\t\tif (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultSvgDocument document = new DefaultSvgDocument(writer, false);\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\tdocument.registerWriter(InternalFeatureImpl.class, new SvgFeatureWriter(getTransformer()));\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new SvgTileWriter());\n\t\t\treturn document;\n\t\t} else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultVmlDocument document = new DefaultVmlDocument(writer);\n\t\t\tint coordWidth = tile.getScreenWidth();\n\t\t\tint coordHeight = tile.getScreenHeight();\n\t\t\tdocument.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth,\n\t\t\t\t\tcoordHeight));\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new VmlTileWriter(coordWidth, coordHeight));\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\treturn document;\n\t\t} else {\n\t\t\tthrow new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer);\n\t\t}\n\t}" ]
[ "@Override\n public Map<String, String> values() {\n Map<String, String> values = new LinkedHashMap<>();\n for (Row each : delegates) {\n for (Entry<String, String> entry : each.values().entrySet()) {\n String name = entry.getKey();\n if (!values.containsKey(name)) {\n values.put(name, entry.getValue());\n }\n }\n }\n return values;\n }", "protected void printCenter(String format, Object... args) {\n String text = S.fmt(format, args);\n info(S.center(text, 80));\n }", "public Point measureImage(Resources resources) {\n BitmapFactory.Options justBoundsOptions = new BitmapFactory.Options();\n justBoundsOptions.inJustDecodeBounds = true;\n\n if (bitmap != null) {\n return new Point(bitmap.getWidth(), bitmap.getHeight());\n } else if (resId != null) {\n BitmapFactory.decodeResource(resources, resId, justBoundsOptions);\n float scale = (float) justBoundsOptions.inTargetDensity / justBoundsOptions.inDensity;\n return new Point((int) (justBoundsOptions.outWidth * scale + 0.5f), (int) (justBoundsOptions.outHeight * scale + 0.5f));\n } else if (fileToBitmap != null) {\n BitmapFactory.decodeFile(fileToBitmap.getAbsolutePath(), justBoundsOptions);\n } else if (inputStream != null) {\n BitmapFactory.decodeStream(inputStream, null, justBoundsOptions);\n try {\n inputStream.reset();\n } catch (IOException ignored) {\n }\n } else if (view != null) {\n return new Point(view.getWidth(), view.getHeight());\n }\n return new Point(justBoundsOptions.outWidth, justBoundsOptions.outHeight);\n }", "public static ProducerRequest readFrom(ByteBuffer buffer) {\n String topic = Utils.readShortString(buffer);\n int partition = buffer.getInt();\n int messageSetSize = buffer.getInt();\n ByteBuffer messageSetBuffer = buffer.slice();\n messageSetBuffer.limit(messageSetSize);\n buffer.position(buffer.position() + messageSetSize);\n return new ProducerRequest(topic, partition, new ByteBufferMessageSet(messageSetBuffer));\n }", "private static <T, ID> void addCreateTableStatements(DatabaseType databaseType, TableInfo<T, ID> tableInfo,\n\t\t\tList<String> statements, List<String> queriesAfter, boolean ifNotExists, boolean logDetails)\n\t\t\tthrows SQLException {\n\t\tStringBuilder sb = new StringBuilder(256);\n\t\tif (logDetails) {\n\t\t\tlogger.info(\"creating table '{}'\", tableInfo.getTableName());\n\t\t}\n\t\tsb.append(\"CREATE TABLE \");\n\t\tif (ifNotExists && databaseType.isCreateIfNotExistsSupported()) {\n\t\t\tsb.append(\"IF NOT EXISTS \");\n\t\t}\n\t\tdatabaseType.appendEscapedEntityName(sb, tableInfo.getTableName());\n\t\tsb.append(\" (\");\n\t\tList<String> additionalArgs = new ArrayList<String>();\n\t\tList<String> statementsBefore = new ArrayList<String>();\n\t\tList<String> statementsAfter = new ArrayList<String>();\n\t\t// our statement will be set here later\n\t\tboolean first = true;\n\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\t// skip foreign collections\n\t\t\tif (fieldType.isForeignCollection()) {\n\t\t\t\tcontinue;\n\t\t\t} else if (first) {\n\t\t\t\tfirst = false;\n\t\t\t} else {\n\t\t\t\tsb.append(\", \");\n\t\t\t}\n\t\t\tString columnDefinition = fieldType.getColumnDefinition();\n\t\t\tif (columnDefinition == null) {\n\t\t\t\t// we have to call back to the database type for the specific create syntax\n\t\t\t\tdatabaseType.appendColumnArg(tableInfo.getTableName(), sb, fieldType, additionalArgs, statementsBefore,\n\t\t\t\t\t\tstatementsAfter, queriesAfter);\n\t\t\t} else {\n\t\t\t\t// hand defined field\n\t\t\t\tdatabaseType.appendEscapedEntityName(sb, fieldType.getColumnName());\n\t\t\t\tsb.append(' ').append(columnDefinition).append(' ');\n\t\t\t}\n\t\t}\n\t\t// add any sql that sets any primary key fields\n\t\tdatabaseType.addPrimaryKeySql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, statementsAfter,\n\t\t\t\tqueriesAfter);\n\t\t// add any sql that sets any unique fields\n\t\tdatabaseType.addUniqueComboSql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, statementsAfter,\n\t\t\t\tqueriesAfter);\n\t\tfor (String arg : additionalArgs) {\n\t\t\t// we will have spat out one argument already so we don't have to do the first dance\n\t\t\tsb.append(\", \").append(arg);\n\t\t}\n\t\tsb.append(\") \");\n\t\tdatabaseType.appendCreateTableSuffix(sb);\n\t\tstatements.addAll(statementsBefore);\n\t\tstatements.add(sb.toString());\n\t\tstatements.addAll(statementsAfter);\n\t\taddCreateIndexStatements(databaseType, tableInfo, statements, ifNotExists, false, logDetails);\n\t\taddCreateIndexStatements(databaseType, tableInfo, statements, ifNotExists, true, logDetails);\n\t}", "void persist(final String key, final String value, final boolean enableDisableMode, final boolean disable, final File file) throws IOException, StartException {\n persist(key, value, enableDisableMode, disable, file, null);\n }", "public QueryBuilder<T, ID> orderBy(String columnName, boolean ascending) {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new IllegalArgumentException(\"Can't orderBy foreign collection field: \" + columnName);\n\t\t}\n\t\taddOrderBy(new OrderBy(columnName, ascending));\n\t\treturn this;\n\t}", "private String getParentOutlineNumber(String outlineNumber)\n {\n String result;\n int index = outlineNumber.lastIndexOf('.');\n if (index == -1)\n {\n result = \"\";\n }\n else\n {\n result = outlineNumber.substring(0, index);\n }\n return result;\n }", "public static Configuration getDefaultFreemarkerConfiguration()\n {\n freemarker.template.Configuration configuration = new freemarker.template.Configuration(Configuration.VERSION_2_3_26);\n DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_26);\n objectWrapperBuilder.setUseAdaptersForContainers(true);\n objectWrapperBuilder.setIterableSupport(true);\n configuration.setObjectWrapper(objectWrapperBuilder.build());\n configuration.setAPIBuiltinEnabled(true);\n\n configuration.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader());\n configuration.setTemplateUpdateDelayMilliseconds(3600);\n return configuration;\n }" ]
Gets the publisher of the specified type, if it is wrapped by the "Flexible Publish" publisher in a project. Null is returned if no such publisher is found. @param project The project @param type The type of the publisher
[ "public T find(AbstractProject<?, ?> project, Class<T> type) {\n // First check that the Flexible Publish plugin is installed:\n if (Jenkins.getInstance().getPlugin(FLEXIBLE_PUBLISH_PLUGIN) != null) {\n // Iterate all the project's publishers and find the flexible publisher:\n for (Publisher publisher : project.getPublishersList()) {\n // Found the flexible publisher:\n if (publisher instanceof FlexiblePublisher) {\n // See if it wraps a publisher of the specified type and if it does, return it:\n T pub = getWrappedPublisher(publisher, type);\n if (pub != null) {\n return pub;\n }\n }\n }\n }\n\n return null;\n }" ]
[ "private void makeSingularPositive() {\n numSingular = qralg.getNumberOfSingularValues();\n singularValues = qralg.getSingularValues();\n\n for( int i = 0; i < numSingular; i++ ) {\n double val = qralg.getSingularValue(i);\n\n if( val < 0 ) {\n singularValues[i] = 0.0 - val;\n\n if( computeU ) {\n // compute the results of multiplying it by an element of -1 at this location in\n // a diagonal matrix.\n int start = i* Ut.numCols;\n int stop = start+ Ut.numCols;\n\n for( int j = start; j < stop; j++ ) {\n Ut.set(j, 0.0 - Ut.get(j));\n }\n }\n } else {\n singularValues[i] = val;\n }\n }\n }", "public boolean hasSameConfiguration(BoneCPConfig that){\n\t\tif ( that != null && Objects.equal(this.acquireIncrement, that.getAcquireIncrement())\n\t\t\t\t&& Objects.equal(this.acquireRetryDelayInMs, that.getAcquireRetryDelayInMs())\n\t\t\t\t&& Objects.equal(this.closeConnectionWatch, that.isCloseConnectionWatch())\n\t\t\t\t&& Objects.equal(this.logStatementsEnabled, that.isLogStatementsEnabled())\n\t\t\t\t&& Objects.equal(this.connectionHook, that.getConnectionHook())\n\t\t\t\t&& Objects.equal(this.connectionTestStatement, that.getConnectionTestStatement())\n\t\t\t\t&& Objects.equal(this.idleConnectionTestPeriodInSeconds, that.getIdleConnectionTestPeriod(TimeUnit.SECONDS))\n\t\t\t\t&& Objects.equal(this.idleMaxAgeInSeconds, that.getIdleMaxAge(TimeUnit.SECONDS))\n\t\t\t\t&& Objects.equal(this.initSQL, that.getInitSQL())\n\t\t\t\t&& Objects.equal(this.jdbcUrl, that.getJdbcUrl())\n\t\t\t\t&& Objects.equal(this.maxConnectionsPerPartition, that.getMaxConnectionsPerPartition())\n\t\t\t\t&& Objects.equal(this.minConnectionsPerPartition, that.getMinConnectionsPerPartition())\n\t\t\t\t&& Objects.equal(this.partitionCount, that.getPartitionCount())\n\t\t\t\t&& Objects.equal(this.releaseHelperThreads, that.getReleaseHelperThreads())\n\t\t\t\t&& Objects.equal(this.statementsCacheSize, that.getStatementsCacheSize())\n\t\t\t\t&& Objects.equal(this.username, that.getUsername())\n\t\t\t\t&& Objects.equal(this.password, that.getPassword())\n\t\t\t\t&& Objects.equal(this.lazyInit, that.isLazyInit())\n\t\t\t\t&& Objects.equal(this.transactionRecoveryEnabled, that.isTransactionRecoveryEnabled())\n\t\t\t\t&& Objects.equal(this.acquireRetryAttempts, that.getAcquireRetryAttempts())\n\t\t\t\t&& Objects.equal(this.statementReleaseHelperThreads, that.getStatementReleaseHelperThreads())\n\t\t\t\t&& Objects.equal(this.closeConnectionWatchTimeoutInMs, that.getCloseConnectionWatchTimeout())\n\t\t\t\t&& Objects.equal(this.connectionTimeoutInMs, that.getConnectionTimeoutInMs())\n\t\t\t\t&& Objects.equal(this.datasourceBean, that.getDatasourceBean())\n\t\t\t\t&& Objects.equal(this.getQueryExecuteTimeLimitInMs(), that.getQueryExecuteTimeLimitInMs())\n\t\t\t\t&& Objects.equal(this.poolAvailabilityThreshold, that.getPoolAvailabilityThreshold())\n\t\t\t\t&& Objects.equal(this.poolName, that.getPoolName())\n\t\t\t\t&& Objects.equal(this.disableConnectionTracking, that.isDisableConnectionTracking())\n\n\t\t\t\t){\n\t\t\treturn true;\n\t\t} \n\n\t\treturn false;\n\t}", "public String astring(ImapRequestLineReader request) throws ProtocolException {\n char next = request.nextWordChar();\n switch (next) {\n case '\"':\n return consumeQuoted(request);\n case '{':\n return consumeLiteral(request);\n default:\n return atom(request);\n }\n }", "public void add(final IndexableTaskItem taskItem) {\n this.dependsOnTaskGroup.addPostRunDependentTaskGroup(taskItem.taskGroup());\n this.collection.add(taskItem);\n }", "public static <T> Object callMethod(Object obj,\n Class<T> c,\n String name,\n Class<?>[] classes,\n Object[] args) {\n try {\n Method m = getMethod(c, name, classes);\n return m.invoke(obj, args);\n } catch(InvocationTargetException e) {\n throw getCause(e);\n } catch(IllegalAccessException e) {\n throw new IllegalStateException(e);\n }\n }", "@JmxGetter(name = \"lastSwapped\", description = \"Time in milliseconds since the store was swapped\")\n public long getLastSwapped() {\n long timeSinceLastSwap = System.currentTimeMillis() - lastSwapped;\n return timeSinceLastSwap > 0 ? timeSinceLastSwap : 0;\n }", "public static lbvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_cachepolicy_binding obj = new lbvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_cachepolicy_binding response[] = (lbvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void handleApplicationCommandRequest(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Application Command Request\");\n\t\tint nodeId = incomingMessage.getMessagePayloadByte(1);\n\t\tlogger.debug(\"Application Command Request from Node \" + nodeId);\n\t\tZWaveNode node = getNode(nodeId);\n\t\t\n\t\tif (node == null) {\n\t\t\tlogger.warn(\"Node {} not initialized yet, ignoring message.\", nodeId);\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tnode.resetResendCount();\n\t\t\n\t\tint commandClassCode = incomingMessage.getMessagePayloadByte(3);\n\t\tZWaveCommandClass.CommandClass commandClass = ZWaveCommandClass.CommandClass.getCommandClass(commandClassCode);\n\n\t\tif (commandClass == null) {\n\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tlogger.debug(String.format(\"Incoming command class %s (0x%02x)\", commandClass.getLabel(), commandClass.getKey()));\n\t\tZWaveCommandClass zwaveCommandClass = node.getCommandClass(commandClass);\n\t\t\n\t\t// We got an unsupported command class, return.\n\t\tif (zwaveCommandClass == null) {\n\t\t\tlogger.error(String.format(\"Unsupported command class %s (0x%02x)\", commandClass.getLabel(), commandClassCode));\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tlogger.trace(\"Found Command Class {}, passing to handleApplicationCommandRequest\", zwaveCommandClass.getCommandClass().getLabel());\n\t\tzwaveCommandClass.handleApplicationCommandRequest(incomingMessage, 4, 1);\n\n\t\tif (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && nodeId == this.lastSentMessage.getMessageNode() && !incomingMessage.isTransActionCanceled()) {\n\t\t\t\tnotifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));\n\t\t\t\ttransactionCompleted.release();\n\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t}\n\t}", "public static <T> ConflictHandler<T> localWins() {\n return new ConflictHandler<T>() {\n @Override\n public T resolveConflict(\n final BsonValue documentId,\n final ChangeEvent<T> localEvent,\n final ChangeEvent<T> remoteEvent\n ) {\n return localEvent.getFullDocument();\n }\n };\n }" ]
Returns the encoding of the file. Encoding is read from the content-encoding property and defaults to the systems default encoding. Since properties can change without rewriting content, the actual encoding can differ. @param cms {@link CmsObject} used to read properties of the given file. @param file the file for which the encoding is requested @return the file's encoding according to the content-encoding property, or the system's default encoding as default.
[ "public static String getEncoding(CmsObject cms, CmsResource file) {\n\n CmsProperty encodingProperty = CmsProperty.getNullProperty();\n try {\n encodingProperty = cms.readPropertyObject(file, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true);\n } catch (CmsException e) {\n LOG.debug(e.getLocalizedMessage(), e);\n }\n return CmsEncoder.lookupEncoding(encodingProperty.getValue(\"\"), OpenCms.getSystemInfo().getDefaultEncoding());\n }" ]
[ "@Override\n public final boolean has(final String key) {\n String result = this.obj.optString(key, null);\n return result != null;\n }", "public static String termPrefix(String term) {\n int i = term.indexOf(MtasToken.DELIMITER);\n String prefix = term;\n if (i >= 0) {\n prefix = term.substring(0, i);\n }\n return prefix.replace(\"\\u0000\", \"\");\n }", "static Object getLCState(StateManagerInternal sm)\r\n\t{\r\n\t\t// unfortunately the LifeCycleState classes are package private.\r\n\t\t// so we have to do some dirty reflection hack to access them\r\n\t\ttry\r\n\t\t{\r\n\t\t\tField myLC = sm.getClass().getDeclaredField(\"myLC\");\r\n\t\t\tmyLC.setAccessible(true);\r\n\t\t\treturn myLC.get(sm);\r\n\t\t}\r\n\t\tcatch (NoSuchFieldException e)\r\n\t\t{\r\n\t\t\treturn e;\r\n\t\t}\r\n\t\tcatch (IllegalAccessException e)\r\n\t\t{\r\n\t\t\treturn e;\r\n\t\t}\t\r\n\t}", "protected void runStatements(Reader reader, PrintStream out)\n throws IOException {\n log.debug(\"runStatements()\");\n StringBuilder txt = new StringBuilder();\n String line = \"\";\n BufferedReader in = new BufferedReader(reader);\n\n while ((line = in.readLine()) != null) {\n line = getProject().replaceProperties(line);\n if (line.indexOf(\"--\") >= 0) {\n txt.append(\"\\n\");\n }\n }\n // Catch any statements not followed by ;\n if (!txt.toString().equals(\"\")) {\n execGroovy(txt.toString(), out);\n }\n }", "public boolean getOverAllocated()\n {\n Boolean overallocated = (Boolean) getCachedValue(ResourceField.OVERALLOCATED);\n if (overallocated == null)\n {\n Number peakUnits = getPeakUnits();\n Number maxUnits = getMaxUnits();\n overallocated = Boolean.valueOf(NumberHelper.getDouble(peakUnits) > NumberHelper.getDouble(maxUnits));\n set(ResourceField.OVERALLOCATED, overallocated);\n }\n return (overallocated.booleanValue());\n }", "public void abort()\r\n {\r\n /*\r\n do nothing if already rolledback\r\n */\r\n if (txStatus == Status.STATUS_NO_TRANSACTION\r\n || txStatus == Status.STATUS_UNKNOWN\r\n || txStatus == Status.STATUS_ROLLEDBACK)\r\n {\r\n log.info(\"Nothing to abort, tx is not active - status is \" + TxUtil.getStatusString(txStatus));\r\n return;\r\n }\r\n // check status of tx\r\n if (txStatus != Status.STATUS_ACTIVE && txStatus != Status.STATUS_PREPARED &&\r\n txStatus != Status.STATUS_MARKED_ROLLBACK)\r\n {\r\n throw new IllegalStateException(\"Illegal state for abort call, state was '\" + TxUtil.getStatusString(txStatus) + \"'\");\r\n }\r\n if(log.isEnabledFor(Logger.INFO))\r\n {\r\n log.info(\"Abort transaction was called on tx \" + this);\r\n }\r\n try\r\n {\r\n try\r\n {\r\n doAbort();\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Error while abort transaction, will be skipped\", e);\r\n }\r\n\r\n // used in managed environments, ignored in non-managed\r\n this.implementation.getTxManager().abortExternalTx(this);\r\n\r\n try\r\n {\r\n if(hasBroker() && getBroker().isInTransaction())\r\n {\r\n getBroker().abortTransaction();\r\n }\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Error while do abort used broker instance, will be skipped\", e);\r\n }\r\n }\r\n finally\r\n {\r\n txStatus = Status.STATUS_ROLLEDBACK;\r\n // cleanup things, e.g. release all locks\r\n doClose();\r\n }\r\n }", "public void postConstruct() {\n parseGeometry();\n\n Assert.isTrue(this.polygon != null, \"Polygon is null. 'area' string is: '\" + this.area + \"'\");\n Assert.isTrue(this.display != null, \"'display' is null\");\n\n Assert.isTrue(this.style == null || this.display == AoiDisplay.RENDER,\n \"'style' does not make sense unless 'display' == RENDER. In this case 'display' == \" +\n this.display);\n }", "public static responderglobal_responderpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tresponderglobal_responderpolicy_binding obj = new responderglobal_responderpolicy_binding();\n\t\tresponderglobal_responderpolicy_binding response[] = (responderglobal_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public String getKeySchema() throws IOException {\n Schema schema = getInputPathAvroSchema();\n String keySchema = schema.getField(keyFieldName).schema().toString();\n return keySchema;\n }" ]
Create the index and associate it with all project models in the Application
[ "private ApplicationReportIndexModel createApplicationReportIndex(GraphContext context,\n ProjectModel applicationProjectModel)\n {\n ApplicationReportIndexService applicationReportIndexService = new ApplicationReportIndexService(context);\n ApplicationReportIndexModel index = applicationReportIndexService.create();\n\n addAllProjectModels(index, applicationProjectModel);\n\n return index;\n }" ]
[ "public static responderhtmlpage get(nitro_service service) throws Exception{\n\t\tresponderhtmlpage obj = new responderhtmlpage();\n\t\tresponderhtmlpage[] response = (responderhtmlpage[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public void remove( Token token ) {\n if( token == first ) {\n first = first.next;\n }\n if( token == last ) {\n last = last.previous;\n }\n if( token.next != null ) {\n token.next.previous = token.previous;\n }\n if( token.previous != null ) {\n token.previous.next = token.next;\n }\n\n token.next = token.previous = null;\n size--;\n }", "private List<CmsResource> getDetailContainerResources(CmsObject cms, CmsResource res) throws CmsException {\n\n CmsRelationFilter filter = CmsRelationFilter.relationsFromStructureId(res.getStructureId()).filterType(\n CmsRelationType.DETAIL_ONLY);\n List<CmsResource> result = Lists.newArrayList();\n List<CmsRelation> relations = cms.readRelations(filter);\n for (CmsRelation relation : relations) {\n try {\n result.add(relation.getTarget(cms, CmsResourceFilter.ALL));\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n return result;\n }", "private void setTableAliasForPath(String aPath, List hintClasses, TableAlias anAlias)\r\n {\r\n m_pathToAlias.put(buildAliasKey(aPath, hintClasses), anAlias);\r\n }", "public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax,\n\t\t\tAbstractMeanSquaredDisplacmentEvaluator msdeval) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}", "public static void setIndex(Matcher matcher, int idx) {\n int count = getCount(matcher);\n if (idx < -count || idx >= count) {\n throw new IndexOutOfBoundsException(\"index is out of range \" + (-count) + \"..\" + (count - 1) + \" (index = \" + idx + \")\");\n }\n if (idx == 0) {\n matcher.reset();\n } else if (idx > 0) {\n matcher.reset();\n for (int i = 0; i < idx; i++) {\n matcher.find();\n }\n } else if (idx < 0) {\n matcher.reset();\n idx += getCount(matcher);\n for (int i = 0; i < idx; i++) {\n matcher.find();\n }\n }\n }", "private String formatPercentage(Number value)\n {\n return (value == null ? null : m_formats.getPercentageDecimalFormat().format(value) + \"%\");\n }", "public Where<T, ID> or(Where<T, ID> left, Where<T, ID> right, Where<T, ID>... others) {\n\t\tClause[] clauses = buildClauseArray(others, \"OR\");\n\t\tClause secondClause = pop(\"OR\");\n\t\tClause firstClause = pop(\"OR\");\n\t\taddClause(new ManyClause(firstClause, secondClause, clauses, ManyClause.OR_OPERATION));\n\t\treturn this;\n\t}", "public void setCustomRequest(int pathId, String customRequest, String clientUUID) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n int profileId = EditService.getProfileIdFromPathID(pathId);\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \" SET \" + Constants.REQUEST_RESPONSE_CUSTOM_REQUEST + \"= ?\" +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \"= ?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \"= ?\" +\n \" AND \" + Constants.REQUEST_RESPONSE_PATH_ID + \"= ?\"\n );\n statement.setString(1, customRequest);\n statement.setInt(2, profileId);\n statement.setString(3, clientUUID);\n statement.setInt(4, pathId);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }" ]
Sends a normal HTTP response containing the serialization information in a XML format
[ "@Override\n public void sendResponse(StoreStats performanceStats,\n boolean isFromLocalZone,\n long startTimeInMs) throws Exception {\n\n ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(this.responseValue.length);\n responseContent.writeBytes(responseValue);\n\n // 1. Create the Response object\n HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);\n\n // 2. Set the right headers\n response.setHeader(CONTENT_TYPE, \"binary\");\n response.setHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n\n // 3. Copy the data into the payload\n response.setContent(responseContent);\n response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());\n\n if(logger.isDebugEnabled()) {\n logger.debug(\"Response = \" + response);\n }\n\n // Write the response to the Netty Channel\n this.messageEvent.getChannel().write(response);\n\n if(performanceStats != null && isFromLocalZone) {\n recordStats(performanceStats, startTimeInMs, Tracked.GET);\n }\n }" ]
[ "protected void removeSequence(String sequenceName)\r\n {\r\n // lookup the sequence map for calling DB\r\n Map mapForDB = (Map) sequencesDBMap.get(getBrokerForClass()\r\n .serviceConnectionManager().getConnectionDescriptor().getJcdAlias());\r\n if(mapForDB != null)\r\n {\r\n synchronized(SequenceManagerHighLowImpl.class)\r\n {\r\n mapForDB.remove(sequenceName);\r\n }\r\n }\r\n }", "public Configuration[] getConfigurations(String name) {\n ArrayList<Configuration> valuesList = new ArrayList<Configuration>();\n\n logger.info(\"Getting data for {}\", name);\n\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n\n String queryString = \"SELECT * FROM \" + Constants.DB_TABLE_CONFIGURATION;\n if (name != null) {\n queryString += \" WHERE \" + Constants.DB_TABLE_CONFIGURATION_NAME + \"=?\";\n }\n\n statement = sqlConnection.prepareStatement(queryString);\n if (name != null) {\n statement.setString(1, name);\n }\n\n results = statement.executeQuery();\n while (results.next()) {\n Configuration config = new Configuration();\n config.setValue(results.getString(Constants.DB_TABLE_CONFIGURATION_VALUE));\n config.setKey(results.getString(Constants.DB_TABLE_CONFIGURATION_NAME));\n config.setId(results.getInt(Constants.GENERIC_ID));\n logger.info(\"the configValue is = {}\", config.getValue());\n valuesList.add(config);\n }\n } catch (SQLException sqe) {\n logger.info(\"Exception in sql\");\n sqe.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n if (valuesList.size() == 0) {\n return null;\n }\n\n return valuesList.toArray(new Configuration[0]);\n }", "private static void checkPreconditions(final String dateFormat, final Locale locale) {\n\t\tif( dateFormat == null ) {\n\t\t\tthrow new NullPointerException(\"dateFormat should not be null\");\n\t\t} else if( locale == null ) {\n\t\t\tthrow new NullPointerException(\"locale should not be null\");\n\t\t}\n\t}", "public static <IN> PaddedList<IN> valueOf(List<IN> list, IN padding) {\r\n return new PaddedList<IN>(list, padding);\r\n }", "public void removeDescriptor(Object validKey)\r\n {\r\n PBKey pbKey;\r\n if (validKey instanceof PBKey)\r\n {\r\n pbKey = (PBKey) validKey;\r\n }\r\n else if (validKey instanceof JdbcConnectionDescriptor)\r\n {\r\n pbKey = ((JdbcConnectionDescriptor) validKey).getPBKey();\r\n }\r\n else\r\n {\r\n throw new MetadataException(\"Could not remove descriptor, given object was no vaild key: \" +\r\n validKey);\r\n }\r\n Object removed = null;\r\n synchronized (jcdMap)\r\n {\r\n removed = jcdMap.remove(pbKey);\r\n jcdAliasToPBKeyMap.remove(pbKey.getAlias());\r\n }\r\n log.info(\"Remove descriptor: \" + removed);\r\n }", "public void setValueSelected(T value, boolean selected) {\n int idx = getIndex(value);\n if (idx >= 0) {\n setItemSelectedInternal(idx, selected);\n }\n }", "private void setAnimationProgress(float progress) {\n if (isAlphaUsedForScale()) {\n setColorViewAlpha((int) (progress * MAX_ALPHA));\n } else {\n ViewCompat.setScaleX(mCircleView, progress);\n ViewCompat.setScaleY(mCircleView, progress);\n }\n }", "public void addSource(GVRAudioSource audioSource)\n {\n synchronized (mAudioSources)\n {\n if (!mAudioSources.contains(audioSource))\n {\n audioSource.setListener(this);\n mAudioSources.add(audioSource);\n }\n }\n }", "public static int getScreenWidth(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n return metrics.widthPixels;\n }" ]
Implements the AAD Algorithm @return HashMap where the key is the internal index of the random variable with respect to which the partial derivative was computed. This key then gives access to the actual derivative.
[ "public Map<Integer, RandomVariable> getGradient(){\r\n\r\n\t\tint numberOfCalculationSteps = getFunctionList().size();\r\n\r\n\t\tRandomVariable[] omegaHat = new RandomVariable[numberOfCalculationSteps];\r\n\r\n\t\tomegaHat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0);\r\n\r\n\t\tfor(int variableIndex = numberOfCalculationSteps-2; variableIndex >= 0; variableIndex--){\r\n\r\n\t\t\tomegaHat[variableIndex] = new RandomVariableFromDoubleArray(0.0);\r\n\r\n\t\t\tArrayList<Integer> childrenList = getAADRandomVariableFromList(variableIndex).getChildrenIndices();\r\n\r\n\t\t\tfor(int functionIndex:childrenList){\r\n\t\t\t\tRandomVariable D_i_j = getPartialDerivative(functionIndex, variableIndex);\r\n\t\t\t\tomegaHat[variableIndex] = omegaHat[variableIndex].addProduct(D_i_j, omegaHat[functionIndex]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tArrayList<Integer> arrayListOfAllIndicesOfDependentRandomVariables = getArrayListOfAllIndicesOfDependentRandomVariables();\r\n\r\n\t\tMap<Integer, RandomVariable> gradient = new HashMap<Integer, RandomVariable>();\r\n\r\n\t\tfor(Integer indexOfDependentRandomVariable: arrayListOfAllIndicesOfDependentRandomVariables){\r\n\t\t\tgradient.put(indexOfDependentRandomVariable, omegaHat[arrayListOfAllIndicesOfDependentRandomVariables.get(indexOfDependentRandomVariable)]);\r\n\t\t}\r\n\r\n\t\treturn gradient;\r\n\t}" ]
[ "private String getIntegerString(Number value)\n {\n return (value == null ? null : Integer.toString(value.intValue()));\n }", "public static <T> T splitEachLine(CharSequence self, Pattern pattern, @ClosureParams(value=FromString.class,options=\"List<String>\") Closure<T> closure) throws IOException {\n final List<String> list = readLines(self);\n T result = null;\n for (String line : list) {\n List vals = Arrays.asList(pattern.split(line));\n result = closure.call(vals);\n }\n return result;\n }", "@Override\n public Iterator<BoxItem.Info> iterator() {\n URL url = GET_COLLECTION_ITEMS_URL.build(this.getAPI().getBaseURL(), BoxCollection.this.getID());\n return new BoxItemIterator(BoxCollection.this.getAPI(), url);\n }", "public void setAttributeEditable(Attribute attribute, boolean editable) {\n\t\tattribute.setEditable(editable);\n\t\tif (!(attribute instanceof LazyAttribute)) { // should not instantiate lazy attributes!\n\t\t\tif (attribute instanceof ManyToOneAttribute) {\n\t\t\t\tsetAttributeEditable(((ManyToOneAttribute) attribute).getValue(), editable);\n\t\t\t} else if (attribute instanceof OneToManyAttribute) {\n\t\t\t\tList<AssociationValue> values = ((OneToManyAttribute) attribute).getValue();\n\t\t\t\tfor (AssociationValue value : values) {\n\t\t\t\t\tsetAttributeEditable(value, editable);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "private static TransportType map2TransportType(String transportId) {\n TransportType type;\n if (CXF_HTTP_TRANSPORT_ID.equals(transportId) || SOAP_HTTP_TRANSPORT_ID.equals(transportId)) {\n type = TransportType.HTTP;\n } else {\n type = TransportType.OTHER;\n }\n return type;\n }", "public Set<String> findResourceNames(String location, URI locationUri) throws IOException {\n String filePath = toFilePath(locationUri);\n File folder = new File(filePath);\n if (!folder.isDirectory()) {\n LOGGER.debug(\"Skipping path as it is not a directory: \" + filePath);\n return new TreeSet<>();\n }\n\n String classPathRootOnDisk = filePath.substring(0, filePath.length() - location.length());\n if (!classPathRootOnDisk.endsWith(File.separator)) {\n classPathRootOnDisk = classPathRootOnDisk + File.separator;\n }\n LOGGER.debug(\"Scanning starting at classpath root in filesystem: \" + classPathRootOnDisk);\n return findResourceNamesFromFileSystem(classPathRootOnDisk, location, folder);\n }", "public long[] keys() {\n long[] values = new long[size];\n int idx = 0;\n for (Entry entry : table) {\n while (entry != null) {\n values[idx++] = entry.key;\n entry = entry.next;\n }\n }\n return values;\n }", "public static String getPropertyUri(PropertyIdValue propertyIdValue,\n\t\t\tPropertyContext propertyContext) {\n\t\tswitch (propertyContext) {\n\t\tcase DIRECT:\n\t\t\treturn PREFIX_PROPERTY_DIRECT + propertyIdValue.getId();\n\t\tcase STATEMENT:\n\t\t\treturn PREFIX_PROPERTY + propertyIdValue.getId();\n\t\tcase VALUE_SIMPLE:\n\t\t\treturn PREFIX_PROPERTY_STATEMENT + propertyIdValue.getId();\n\t\tcase VALUE:\n\t\t\treturn PREFIX_PROPERTY_STATEMENT_VALUE + propertyIdValue.getId();\n\t\tcase QUALIFIER:\n\t\t\treturn PREFIX_PROPERTY_QUALIFIER_VALUE + propertyIdValue.getId();\n\t\tcase QUALIFIER_SIMPLE:\n\t\t\treturn PREFIX_PROPERTY_QUALIFIER + propertyIdValue.getId();\n\t\tcase REFERENCE:\n\t\t\treturn PREFIX_PROPERTY_REFERENCE_VALUE + propertyIdValue.getId();\n\t\tcase REFERENCE_SIMPLE:\n\t\t\treturn PREFIX_PROPERTY_REFERENCE + propertyIdValue.getId();\n\t\tcase NO_VALUE:\n\t\t\treturn PREFIX_WIKIDATA_NO_VALUE + propertyIdValue.getId();\n\t\tcase NO_QUALIFIER_VALUE:\n\t\t\treturn PREFIX_WIKIDATA_NO_QUALIFIER_VALUE + propertyIdValue.getId();\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}", "public static nssimpleacl[] get(nitro_service service) throws Exception{\n\t\tnssimpleacl obj = new nssimpleacl();\n\t\tnssimpleacl[] response = (nssimpleacl[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Renders a time period in human readable form @param time the time in milliseconds @return the time in human readable form
[ "public static String asTime(long time) {\n if (time > HOUR) {\n return String.format(\"%.1f h\", (time / HOUR));\n } else if (time > MINUTE) {\n return String.format(\"%.1f m\", (time / MINUTE));\n } else if (time > SECOND) {\n return String.format(\"%.1f s\", (time / SECOND));\n } else {\n return String.format(\"%d ms\", time);\n }\n }" ]
[ "public static synchronized void unregisterDao(ConnectionSource connectionSource, Dao<?, ?> dao) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\tremoveDaoToClassMap(new ClassConnectionSource(connectionSource, dao.getDataClass()));\n\t}", "public Permissions getPerms(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PERMS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element permissionsElement = response.getPayload();\r\n Permissions permissions = new Permissions();\r\n permissions.setId(permissionsElement.getAttribute(\"id\"));\r\n permissions.setPublicFlag(\"1\".equals(permissionsElement.getAttribute(\"ispublic\")));\r\n permissions.setFamilyFlag(\"1\".equals(permissionsElement.getAttribute(\"isfamily\")));\r\n permissions.setFriendFlag(\"1\".equals(permissionsElement.getAttribute(\"isfriend\")));\r\n permissions.setComment(permissionsElement.getAttribute(\"permcomment\"));\r\n permissions.setAddmeta(permissionsElement.getAttribute(\"permaddmeta\"));\r\n return permissions;\r\n }", "static void addOperationAddress(final ModelNode operation, final PathAddress base, final String key, final String value) {\n operation.get(OP_ADDR).set(base.append(key, value).toModelNode());\n }", "@Override\n public <E> DynamicType.Builder<E> processMethod(final DynamicType.Builder<E> builder, final Method method, final Annotation annotation)\n {\n String methodName = method.getName();\n if (ReflectionUtility.isGetMethod(method))\n return createInterceptor(builder, method);\n else if (ReflectionUtility.isSetMethod(method))\n return createInterceptor(builder, method);\n else if (methodName.startsWith(\"addAll\"))\n return createInterceptor(builder, method);\n else if (methodName.startsWith(\"add\"))\n return createInterceptor(builder, method);\n else\n throw new WindupException(\"Only get*, set*, add*, and addAll* method names are supported for @\"\n + SetInProperties.class.getSimpleName() + \", found at: \" + method.getName());\n }", "private static String preparePlaceHolders(int length) {\n StringBuilder builder = new StringBuilder();\n for (int i = 0; i < length; ) {\n builder.append(\"?\");\n if (++i < length) {\n builder.append(\",\");\n }\n }\n return builder.toString();\n }", "public static String getAt(String text, Range range) {\n RangeInfo info = subListBorders(text.length(), range);\n String answer = text.substring(info.from, info.to);\n if (info.reverse) {\n answer = reverse(answer);\n }\n return answer;\n }", "public <T> T cached(String key) {\n H.Session sess = session();\n if (null != sess) {\n return sess.cached(key);\n } else {\n return app().cache().get(key);\n }\n }", "private void validateSameDay(ProjectCalendar calendar, LinkedList<TimephasedWork> list)\n {\n for (TimephasedWork assignment : list)\n {\n Date assignmentStart = assignment.getStart();\n Date calendarStartTime = calendar.getStartTime(assignmentStart);\n Date assignmentStartTime = DateHelper.getCanonicalTime(assignmentStart);\n Date assignmentFinish = assignment.getFinish();\n Date calendarFinishTime = calendar.getFinishTime(assignmentFinish);\n Date assignmentFinishTime = DateHelper.getCanonicalTime(assignmentFinish);\n double totalWork = assignment.getTotalAmount().getDuration();\n\n if (assignmentStartTime != null && calendarStartTime != null)\n {\n if ((totalWork == 0 && assignmentStartTime.getTime() != calendarStartTime.getTime()) || (assignmentStartTime.getTime() < calendarStartTime.getTime()))\n {\n assignmentStart = DateHelper.setTime(assignmentStart, calendarStartTime);\n assignment.setStart(assignmentStart);\n }\n }\n\n if (assignmentFinishTime != null && calendarFinishTime != null)\n {\n if ((totalWork == 0 && assignmentFinishTime.getTime() != calendarFinishTime.getTime()) || (assignmentFinishTime.getTime() > calendarFinishTime.getTime()))\n {\n assignmentFinish = DateHelper.setTime(assignmentFinish, calendarFinishTime);\n assignment.setFinish(assignmentFinish);\n }\n }\n }\n }", "void endOfRunDb()\n {\n DbConn cnx = null;\n\n try\n {\n cnx = Helpers.getNewDbSession();\n\n // Done: put inside history & remove instance from queue.\n History.create(cnx, this.ji, this.resultStatus, endDate);\n jqmlogger.trace(\"An History was just created for job instance \" + this.ji.getId());\n cnx.runUpdate(\"ji_delete_by_id\", this.ji.getId());\n cnx.commit();\n }\n catch (RuntimeException e)\n {\n endBlockDbFailureAnalysis(e);\n }\n finally\n {\n Helpers.closeQuietly(cnx);\n }\n }" ]
checks if the 2 triangles shares a segment @author Doron Ganel & Eyal Roth(2009) @param t2 - a second triangle @return boolean
[ "public int sharedSegments(Triangle t2) {\n\t\tint counter = 0;\n\n\t\tif(a.equals(t2.a)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(a.equals(t2.b)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(a.equals(t2.c)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(b.equals(t2.a)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(b.equals(t2.b)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(b.equals(t2.c)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(c.equals(t2.a)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(c.equals(t2.b)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(c.equals(t2.c)) {\n\t\t\tcounter++;\n\t\t}\n\n\t\treturn counter;\n\t}" ]
[ "public Object[] getForeignKeyValues(Object obj, ClassDescriptor mif)\r\n throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] fks = getForeignKeyFieldDescriptors(mif);\r\n // materialize object only if FK fields are declared\r\n if(fks.length > 0) obj = ProxyHelper.getRealObject(obj);\r\n Object[] result = new Object[fks.length];\r\n for (int i = 0; i < result.length; i++)\r\n {\r\n FieldDescriptor fmd = fks[i];\r\n PersistentField f = fmd.getPersistentField();\r\n\r\n // BRJ: do NOT convert.\r\n // conversion is done when binding the sql-statement\r\n //\r\n // FieldConversion fc = fmd.getFieldConversion();\r\n // Object val = fc.javaToSql(f.get(obj));\r\n\r\n result[i] = f.get(obj);\r\n }\r\n return result;\r\n }", "protected ServiceName serviceName(final String name) {\n return baseServiceName != null ? baseServiceName.append(name) : null;\n }", "private synchronized JsonSchema getInputPathJsonSchema() throws IOException {\n if (inputPathJsonSchema == null) {\n // No need to query Hadoop more than once as this shouldn't change mid-run,\n // thus, we can lazily initialize and cache the result.\n inputPathJsonSchema = HadoopUtils.getSchemaFromPath(getInputPath());\n }\n return inputPathJsonSchema;\n }", "private void ensurePKsFromHierarchy(ClassDescriptorDef classDef) throws ConstraintException\r\n {\r\n SequencedHashMap pks = new SequencedHashMap();\r\n\r\n for (Iterator it = classDef.getAllExtentClasses(); it.hasNext();)\r\n {\r\n ClassDescriptorDef subTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n ArrayList subPKs = subTypeDef.getPrimaryKeys();\r\n\r\n // check against already present PKs\r\n for (Iterator pkIt = subPKs.iterator(); pkIt.hasNext();)\r\n {\r\n FieldDescriptorDef fieldDef = (FieldDescriptorDef)pkIt.next();\r\n FieldDescriptorDef foundPKDef = (FieldDescriptorDef)pks.get(fieldDef.getName());\r\n\r\n if (foundPKDef != null)\r\n {\r\n if (!isEqual(fieldDef, foundPKDef))\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required primary key \"+fieldDef.getName()+\r\n \" because its definitions in \"+fieldDef.getOwner().getName()+\" and \"+\r\n foundPKDef.getOwner().getName()+\" differ\");\r\n }\r\n }\r\n else\r\n {\r\n pks.put(fieldDef.getName(), fieldDef);\r\n }\r\n }\r\n }\r\n\r\n ensureFields(classDef, pks.values());\r\n }", "void processSiteRow(String siteRow) {\n\t\tString[] row = getSiteRowFields(siteRow);\n\n\t\tString filePath = \"\";\n\t\tString pagePath = \"\";\n\n\t\tString dataArray = row[8].substring(row[8].indexOf('{'),\n\t\t\t\trow[8].length() - 2);\n\n\t\t// Explanation for the regular expression below:\n\t\t// \"'{' or ';'\" followed by either\n\t\t// \"NOT: ';', '{', or '}'\" repeated one or more times; or\n\t\t// \"a single '}'\"\n\t\t// The first case matches \";s:5:\\\"paths\\\"\"\n\t\t// but also \";a:2:\" in \"{s:5:\\\"paths\\\";a:2:{s:9:\\ ...\".\n\t\t// The second case matches \";}\" which terminates (sub)arrays.\n\t\tMatcher matcher = Pattern.compile(\"[{;](([^;}{][^;}{]*)|[}])\").matcher(\n\t\t\t\tdataArray);\n\t\tString prevString = \"\";\n\t\tString curString = \"\";\n\t\tString path = \"\";\n\t\tboolean valuePosition = false;\n\n\t\twhile (matcher.find()) {\n\t\t\tString match = matcher.group().substring(1);\n\t\t\tif (match.length() == 0) {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (match.charAt(0) == 's') {\n\t\t\t\tvaluePosition = !valuePosition && !\"\".equals(prevString);\n\t\t\t\tcurString = match.substring(match.indexOf('\"') + 1,\n\t\t\t\t\t\tmatch.length() - 2);\n\t\t\t} else if (match.charAt(0) == 'a') {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tpath = path + \"/\" + prevString;\n\t\t\t} else if (\"}\".equals(match)) {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tpath = path.substring(0, path.lastIndexOf('/'));\n\t\t\t}\n\n\t\t\tif (valuePosition && \"file_path\".equals(prevString)\n\t\t\t\t\t&& \"/paths\".equals(path)) {\n\t\t\t\tfilePath = curString;\n\t\t\t} else if (valuePosition && \"page_path\".equals(prevString)\n\t\t\t\t\t&& \"/paths\".equals(path)) {\n\t\t\t\tpagePath = curString;\n\t\t\t}\n\n\t\t\tprevString = curString;\n\t\t\tcurString = \"\";\n\t\t}\n\n\t\tMwSitesDumpFileProcessor.logger.debug(\"Found site data \\\"\" + row[1]\n\t\t\t\t+ \"\\\" (group \\\"\" + row[3] + \"\\\", language \\\"\" + row[5]\n\t\t\t\t+ \"\\\", type \\\"\" + row[2] + \"\\\")\");\n\t\tthis.sites.setSiteInformation(row[1], row[3], row[5], row[2], filePath,\n\t\t\t\tpagePath);\n\t}", "public final void visit(final Visitor visitor)\n\t{\n\t\tfinal Visit visit = new Visit();\n\t\ttry\n\t\t{\n\t\t\tvisit(visitor, visit);\n\t\t}\n\t\tcatch (final StopVisitationException ignored)\n\t\t{\n\t\t}\n\t}", "public boolean isBitwiseOrCompatibleWithRange(int maskValue, Integer segmentPrefixLength) throws PrefixLenException {\r\n\t\treturn super.isBitwiseOrCompatibleWithRange(maskValue, segmentPrefixLength, getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets());\r\n\t}", "public static String getVcsRevision(Map<String, String> env) {\n String revision = env.get(\"SVN_REVISION\");\n if (StringUtils.isBlank(revision)) {\n revision = env.get(GIT_COMMIT);\n }\n if (StringUtils.isBlank(revision)) {\n revision = env.get(\"P4_CHANGELIST\");\n }\n return revision;\n }", "public static <T extends EObject> IScope scopeFor(Iterable<? extends T> elements,\n\t\t\tfinal Function<T, QualifiedName> nameComputation, IScope outer) {\n\t\treturn new SimpleScope(outer,scopedElementsFor(elements, nameComputation));\n\t}" ]
Get the target entry for a given patch element. @param element the patch element @return the patch entry @throws PatchingException
[ "protected PatchEntry resolveForElement(final PatchElement element) throws PatchingException {\n assert state == State.NEW;\n final PatchElementProvider provider = element.getProvider();\n final String layerName = provider.getName();\n final LayerType layerType = provider.getLayerType();\n\n final Map<String, PatchEntry> map;\n if (layerType == LayerType.Layer) {\n map = layers;\n } else {\n map = addOns;\n }\n PatchEntry entry = map.get(layerName);\n if (entry == null) {\n final InstallationManager.MutablePatchingTarget target = modification.resolve(layerName, layerType);\n if (target == null) {\n throw PatchLogger.ROOT_LOGGER.noSuchLayer(layerName);\n }\n entry = new PatchEntry(target, element);\n map.put(layerName, entry);\n }\n // Maintain the most recent element\n entry.updateElement(element);\n return entry;\n }" ]
[ "public MapBounds getRotatedBoundsAdjustedForPreciseRotatedMapSize() {\n Rectangle2D.Double paintAreaPrecise = getRotatedMapSizePrecise();\n Rectangle paintArea = new Rectangle(MapfishMapContext.rectangleDoubleToDimension(paintAreaPrecise));\n return getRotatedBounds(paintAreaPrecise, paintArea);\n }", "public void addAliasToConfigSite(String alias, String redirect, String offset) {\n\n long timeOffset = 0;\n try {\n timeOffset = Long.parseLong(offset);\n } catch (Throwable e) {\n // ignore\n }\n CmsSiteMatcher siteMatcher = new CmsSiteMatcher(alias, timeOffset);\n boolean redirectVal = new Boolean(redirect).booleanValue();\n siteMatcher.setRedirect(redirectVal);\n m_aliases.add(siteMatcher);\n }", "protected TransformationDescription buildDefault(final DiscardPolicy discardPolicy, boolean inherited, final AttributeTransformationDescriptionBuilderImpl.AttributeTransformationDescriptionBuilderRegistry registry, List<String> discardedOperations) {\n // Build attribute rules\n final Map<String, AttributeTransformationDescription> attributes = registry.buildAttributes();\n // Create operation transformers\n final Map<String, OperationTransformer> operations = buildOperationTransformers(registry);\n // Process children\n final List<TransformationDescription> children = buildChildren();\n\n if (discardPolicy == DiscardPolicy.NEVER) {\n // TODO override more global operations?\n if(! operations.containsKey(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION)) {\n operations.put(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION, OperationTransformationRules.createWriteOperation(attributes));\n }\n if(! operations.containsKey(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION)) {\n operations.put(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION, OperationTransformationRules.createUndefinedOperation(attributes));\n }\n }\n // Create the description\n Set<String> discarded = new HashSet<>();\n discarded.addAll(discardedOperations);\n return new TransformingDescription(pathElement, pathAddressTransformer, discardPolicy, inherited,\n resourceTransformer, attributes, operations, children, discarded, dynamicDiscardPolicy);\n }", "private void initDatesPanel() {\n\n m_startLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_TIME_STARTTIME_0));\n m_startTime.setAllowInvalidValue(true);\n m_startTime.setValue(m_model.getStart());\n m_endLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_TIME_ENDTIME_0));\n m_endTime.setAllowInvalidValue(true);\n m_endTime.setValue(m_model.getEnd());\n m_seriesCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_SERIES_CHECKBOX_0));\n m_wholeDayCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_WHOLE_DAY_CHECKBOX_0));\n m_currentTillEndCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_CURRENT_TILL_END_CHECKBOX_0));\n m_currentTillEndCheckBox.getButton().setTitle(\n Messages.get().key(Messages.GUI_SERIALDATE_CURRENT_TILL_END_CHECKBOX_HELP_0));\n }", "private void storeToDb(Object obj, ClassDescriptor cld, Identity oid, boolean insert, boolean ignoreReferences)\n {\n // 1. link and store 1:1 references\n storeReferences(obj, cld, insert, ignoreReferences);\n\n Object[] pkValues = oid.getPrimaryKeyValues();\n if (!serviceBrokerHelper().assertValidPksForStore(cld.getPkFields(), pkValues))\n {\n // BRJ: fk values may be part of pk, but the are not known during\n // creation of Identity. so we have to get them here\n pkValues = serviceBrokerHelper().getKeyValues(cld, obj);\n if (!serviceBrokerHelper().assertValidPksForStore(cld.getPkFields(), pkValues))\n {\n String append = insert ? \" on insert\" : \" on update\" ;\n throw new PersistenceBrokerException(\"assertValidPkFields failed for Object of type: \" + cld.getClassNameOfObject() + append);\n }\n }\n\n // get super class cld then store it with the object\n /*\n now for multiple table inheritance\n 1. store super classes, topmost parent first\n 2. go down through heirarchy until current class\n 3. todo: store to full extent?\n\n// arminw: TODO: The extend-attribute feature dosn't work, should we remove this stuff?\n This if-clause will go up the inheritance heirarchy to store all the super classes.\n The id for the top most super class will be the id for all the subclasses too\n */\n if(cld.getSuperClass() != null)\n {\n\n ClassDescriptor superCld = getDescriptorRepository().getDescriptorFor(cld.getSuperClass());\n storeToDb(obj, superCld, oid, insert);\n // arminw: why this?? I comment out this section\n // storeCollections(obj, cld.getCollectionDescriptors(), insert);\n }\n\n // 2. store primitive typed attributes (Or is THIS step 3 ?)\n // if obj not present in db use INSERT\n if (insert)\n {\n dbAccess.executeInsert(cld, obj);\n if(oid.isTransient())\n {\n // Create a new Identity based on the current set of primary key values.\n oid = serviceIdentity().buildIdentity(cld, obj);\n }\n }\n // else use UPDATE\n else\n {\n try\n {\n dbAccess.executeUpdate(cld, obj);\n }\n catch(OptimisticLockException e)\n {\n // ensure that the outdated object be removed from cache\n objectCache.remove(oid);\n throw e;\n }\n }\n // cache object for symmetry with getObjectByXXX()\n // Add the object to the cache.\n objectCache.doInternalCache(oid, obj, ObjectCacheInternal.TYPE_WRITE);\n // 3. store 1:n and m:n associations\n if(!ignoreReferences) storeCollections(obj, cld, insert);\n }", "private void emit(float[] particlePositions, float[] particleVelocities,\n float[] particleTimeStamps)\n {\n float[] allParticlePositions = new float[particlePositions.length + particleBoundingVolume.length];\n System.arraycopy(particlePositions, 0, allParticlePositions, 0, particlePositions.length);\n System.arraycopy(particleBoundingVolume, 0, allParticlePositions,\n particlePositions.length, particleBoundingVolume.length);\n\n float[] allSpawnTimes = new float[particleTimeStamps.length + BVSpawnTimes.length];\n System.arraycopy(particleTimeStamps, 0, allSpawnTimes, 0, particleTimeStamps.length);\n System.arraycopy(BVSpawnTimes, 0, allSpawnTimes, particleTimeStamps.length, BVSpawnTimes.length);\n\n float[] allParticleVelocities = new float[particleVelocities.length + BVVelocities.length];\n System.arraycopy(particleVelocities, 0, allParticleVelocities, 0, particleVelocities.length);\n System.arraycopy(BVVelocities, 0, allParticleVelocities, particleVelocities.length, BVVelocities.length);\n\n\n Particles particleMesh = new Particles(mGVRContext, mMaxAge,\n mParticleSize, mEnvironmentAcceleration, mParticleSizeRate, mFadeWithAge,\n mParticleTexture, mColor, mNoiseFactor);\n\n\n GVRSceneObject particleObject = particleMesh.makeParticleMesh(allParticlePositions,\n allParticleVelocities, allSpawnTimes);\n\n this.addChildObject(particleObject);\n meshInfo.add(Pair.create(particleObject, currTime));\n }", "public UpdateBuilder<T, ID> updateColumnExpression(String columnName, String expression) throws SQLException {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new SQLException(\"Can't update foreign colletion field: \" + columnName);\n\t\t}\n\t\taddUpdateColumnToList(columnName, new SetExpression(columnName, fieldType, expression));\n\t\treturn this;\n\t}", "private List<String> processAllListeners(View rootView) {\n List<String> refinementAttributes = new ArrayList<>();\n\n // Register any AlgoliaResultsListener (unless it has a different variant than searcher)\n final List<AlgoliaResultsListener> resultListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaResultsListener.class);\n if (resultListeners.isEmpty()) {\n throw new IllegalStateException(Errors.LAYOUT_MISSING_RESULT_LISTENER);\n }\n for (AlgoliaResultsListener listener : resultListeners) {\n if (!this.resultListeners.contains(listener)) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n this.resultListeners.add(listener);\n searcher.registerResultListener(listener);\n prepareWidget(listener, refinementAttributes);\n }\n }\n }\n\n // Register any AlgoliaErrorListener (unless it has a different variant than searcher)\n final List<AlgoliaErrorListener> errorListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaErrorListener.class);\n for (AlgoliaErrorListener listener : errorListeners) {\n if (!this.errorListeners.contains(listener)) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n this.errorListeners.add(listener);\n }\n }\n searcher.registerErrorListener(listener);\n prepareWidget(listener, refinementAttributes);\n }\n\n // Register any AlgoliaSearcherListener (unless it has a different variant than searcher)\n final List<AlgoliaSearcherListener> searcherListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaSearcherListener.class);\n for (AlgoliaSearcherListener listener : searcherListeners) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n listener.initWithSearcher(searcher);\n prepareWidget(listener, refinementAttributes);\n }\n }\n\n return refinementAttributes;\n }", "public static String getArtifactoryPluginVersion() {\n String pluginsSortName = \"artifactory\";\n //Validates Jenkins existence because in some jobs the Jenkins instance is unreachable\n if (Jenkins.getInstance() != null\n && Jenkins.getInstance().getPlugin(pluginsSortName) != null\n && Jenkins.getInstance().getPlugin(pluginsSortName).getWrapper() != null) {\n return Jenkins.getInstance().getPlugin(pluginsSortName).getWrapper().getVersion();\n }\n return \"\";\n }" ]
Find the earliest task start date. We treat this as the start date for the project. @return start date
[ "public Date getStartDate()\n {\n Date startDate = null;\n\n for (Task task : m_tasks)\n {\n //\n // If a hidden \"summary\" task is present we ignore it\n //\n if (NumberHelper.getInt(task.getUniqueID()) == 0)\n {\n continue;\n }\n\n //\n // Select the actual or forecast start date. Note that the\n // behaviour is different for milestones. The milestone end date\n // is always correct, the milestone start date may be different\n // to reflect a missed deadline.\n //\n Date taskStartDate;\n if (task.getMilestone() == true)\n {\n taskStartDate = task.getActualFinish();\n if (taskStartDate == null)\n {\n taskStartDate = task.getFinish();\n }\n }\n else\n {\n taskStartDate = task.getActualStart();\n if (taskStartDate == null)\n {\n taskStartDate = task.getStart();\n }\n }\n\n if (taskStartDate != null)\n {\n if (startDate == null)\n {\n startDate = taskStartDate;\n }\n else\n {\n if (taskStartDate.getTime() < startDate.getTime())\n {\n startDate = taskStartDate;\n }\n }\n }\n }\n\n return (startDate);\n }" ]
[ "public void addPropertyChangeListener (String propertyName, java.beans.PropertyChangeListener listener)\r\n {\r\n this.propertyChangeDelegate.addPropertyChangeListener(propertyName, listener);\r\n }", "@Override\n public Map<String, Set<String>> cleanObsoleteContent() {\n if(!readWrite) {\n return Collections.emptyMap();\n }\n Map<String, Set<String>> cleanedContents = new HashMap<>(2);\n cleanedContents.put(MARKED_CONTENT, new HashSet<>());\n cleanedContents.put(DELETED_CONTENT, new HashSet<>());\n synchronized (contentHashReferences) {\n for (ContentReference fsContent : listLocalContents()) {\n if (!readWrite) {\n return Collections.emptyMap();\n }\n if (!contentHashReferences.containsKey(fsContent.getHexHash())) { //We have no reference to this content\n if (markAsObsolete(fsContent)) {\n cleanedContents.get(DELETED_CONTENT).add(fsContent.getContentIdentifier());\n } else {\n cleanedContents.get(MARKED_CONTENT).add(fsContent.getContentIdentifier());\n }\n } else {\n obsoleteContents.remove(fsContent.getHexHash()); //Remove existing references from obsoleteContents\n }\n }\n }\n return cleanedContents;\n }", "private void appendLikeCriteria(TableAlias alias, PathInfo pathInfo, LikeCriteria c, StringBuffer buf)\r\n {\r\n appendColName(alias, pathInfo, c.isTranslateAttribute(), buf);\r\n buf.append(c.getClause());\r\n appendParameter(c.getValue(), buf);\r\n\r\n buf.append(m_platform.getEscapeClause(c));\r\n }", "public SchedulerDocsResponse.Doc schedulerDoc(String docId) {\n assertNotEmpty(docId, \"docId\");\n return this.get(new DatabaseURIHelper(getBaseUri()).\n path(\"_scheduler\").path(\"docs\").path(\"_replicator\").path(docId).build(),\n SchedulerDocsResponse.Doc.class);\n }", "@Api\n\tpublic void setUseCache(boolean useCache) {\n\t\tif (null == cacheManagerService && useCache) {\n\t\t\tlog.warn(\"The caching plugin needs to be available to cache WMS requests. Not setting useCache.\");\n\t\t} else {\n\t\t\tthis.useCache = useCache;\n\t\t}\n\t}", "public Credentials toGrgit() {\n if (username != null && password != null) {\n return new Credentials(username, password);\n } else {\n return null;\n }\n }", "private static Document objectForInsert(Tuple tuple, Document dbObject) {\n\t\tMongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot();\n\t\tfor ( TupleOperation operation : tuple.getOperations() ) {\n\t\t\tString column = operation.getColumn();\n\t\t\tif ( notInIdField( snapshot, column ) ) {\n\t\t\t\tswitch ( operation.getType() ) {\n\t\t\t\t\tcase PUT:\n\t\t\t\t\t\tMongoHelpers.setValue( dbObject, column, operation.getValue() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase PUT_NULL:\n\t\t\t\t\tcase REMOVE:\n\t\t\t\t\t\tMongoHelpers.resetValue( dbObject, column );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn dbObject;\n\t}", "private static void checkSorted(int[] sorted) {\r\n for (int i = 0; i < sorted.length-1; i++) {\r\n if (sorted[i] > sorted[i+1]) {\r\n throw new RuntimeException(\"input must be sorted!\");\r\n }\r\n }\r\n }", "protected void registerValueFormatter(DJGroupVariable djVariable, String variableName) {\n\t\tif ( djVariable.getValueFormatter() == null){\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tJRDesignParameter dparam = new JRDesignParameter();\n\t\tdparam.setName(variableName + \"_vf\"); //value formater suffix\n\t\tdparam.setValueClassName(DJValueFormatter.class.getName());\n\t\tlog.debug(\"Registering value formatter parameter for property \" + dparam.getName() );\n\t\ttry {\n\t\t\tgetDjd().addParameter(dparam);\n\t\t} catch (JRException e) {\n\t\t\tthrow new EntitiesRegistrationException(e.getMessage(),e);\n\t\t}\n\t\tgetDjd().getParametersWithValues().put(dparam.getName(), djVariable.getValueFormatter());\t\t\n\t\t\n\t}" ]
Creates needed textfields for general label in footer groups. @param djgroup @param jgroup
[ "protected void layoutGroupFooterLabels(DJGroup djgroup, JRDesignGroup jgroup, int x, int y, int width, int height) {\n\t\t//List footerVariables = djgroup.getFooterVariables();\n\t\tDJGroupLabel label = djgroup.getFooterLabel();\n\n\t\t//if (label == null || footerVariables.isEmpty())\n\t\t\t//return;\n\n\t\t//PropertyColumn col = djgroup.getColumnToGroupBy();\n\t\tJRDesignBand band = LayoutUtils.getBandFromSection((JRDesignSection) jgroup.getGroupFooterSection());\n\n//\t\tlog.debug(\"Adding footer group label for group \" + djgroup);\n\n\t\t/*DJGroupVariable lmvar = findLeftMostColumn(footerVariables);\n\t\tAbstractColumn lmColumn = lmvar.getColumnToApplyOperation();\n\t\tint width = lmColumn.getPosX().intValue() - col.getPosX().intValue();\n\n\t\tint yOffset = findYOffsetForGroupLabel(band);*/\n\n\t\tJRDesignExpression labelExp;\n\t\tif (label.isJasperExpression()) //a text with things like \"$F{myField}\"\n\t\t\tlabelExp = ExpressionUtils.createStringExpression(label.getText());\n\t\telse if (label.getLabelExpression() != null){\n\t\t\tlabelExp = ExpressionUtils.createExpression(jgroup.getName() + \"_labelExpression\", label.getLabelExpression(), true);\n\t\t} else //a simple text\n\t\t\t//labelExp = ExpressionUtils.createStringExpression(\"\\\"\"+ Utils.escapeTextForExpression(label.getText())+ \"\\\"\");\n\t\t\tlabelExp = ExpressionUtils.createStringExpression(\"\\\"\"+ label.getText() + \"\\\"\");\n\t\tJRDesignTextField labelTf = new JRDesignTextField();\n\t\tlabelTf.setExpression(labelExp);\n\t\tlabelTf.setWidth(width);\n\t\tlabelTf.setHeight(height);\n\t\tlabelTf.setX(x);\n\t\tlabelTf.setY(y);\n\t\t//int yOffsetGlabel = labelTf.getHeight();\n\t\tlabelTf.setPositionType( PositionTypeEnum.FIX_RELATIVE_TO_TOP );\n\t\tapplyStyleToElement(label.getStyle(), labelTf);\n\t\tband.addElement(labelTf);\n\t}" ]
[ "public static IndexedContainer getPrincipalContainer(\n CmsObject cms,\n List<? extends I_CmsPrincipal> list,\n String captionID,\n String descID,\n String iconID,\n String ouID,\n String icon,\n List<FontIcon> iconList) {\n\n IndexedContainer res = new IndexedContainer();\n\n res.addContainerProperty(captionID, String.class, \"\");\n res.addContainerProperty(ouID, String.class, \"\");\n res.addContainerProperty(iconID, FontIcon.class, new CmsCssIcon(icon));\n if (descID != null) {\n res.addContainerProperty(descID, String.class, \"\");\n }\n\n for (I_CmsPrincipal group : list) {\n\n Item item = res.addItem(group);\n item.getItemProperty(captionID).setValue(group.getSimpleName());\n item.getItemProperty(ouID).setValue(group.getOuFqn());\n if (descID != null) {\n item.getItemProperty(descID).setValue(group.getDescription(A_CmsUI.get().getLocale()));\n }\n }\n\n for (int i = 0; i < iconList.size(); i++) {\n res.getItem(res.getIdByIndex(i)).getItemProperty(iconID).setValue(iconList.get(i));\n }\n\n return res;\n }", "private static boolean isVariableInteger(TokenList.Token t) {\n if( t == null )\n return false;\n\n return t.getScalarType() == VariableScalar.Type.INTEGER;\n }", "public void reinitIfClosed() {\n if (isClosed.get()) {\n logger.info(\"External Resource was released. Now Re-initializing resources ...\");\n\n ActorConfig.createAndGetActorSystem();\n httpClientStore.reinit();\n tcpSshPingResourceStore.reinit();\n try {\n Thread.sleep(1000l);\n } catch (InterruptedException e) {\n logger.error(\"error reinit httpClientStore\", e);\n }\n isClosed.set(false);\n logger.info(\"Parallel Client Resources has been reinitialized.\");\n } else {\n logger.debug(\"NO OP. Resource was not released.\");\n }\n }", "protected void update(float scale) {\n GVRSceneObject owner = getOwnerObject();\n if (isEnabled() && (owner != null) && owner.isEnabled())\n {\n float w = getWidth();\n float h = getHeight();\n mPose.update(mARPlane.getCenterPose(), scale);\n Matrix4f m = new Matrix4f();\n m.set(mPose.getPoseMatrix());\n m.scaleLocal(w * 0.95f, h * 0.95f, 1.0f);\n owner.getTransform().setModelMatrix(m);\n }\n }", "public static SPIProviderResolver getInstance(ClassLoader cl)\n {\n SPIProviderResolver resolver = (SPIProviderResolver)ServiceLoader.loadService(SPIProviderResolver.class.getName(), DEFAULT_SPI_PROVIDER_RESOLVER, cl);\n return resolver;\n }", "private static double arcAngle(Point center, Point a, Point b, Rect area, int radius) {\n double angle = threePointsAngle(center, a, b);\n Point innerPoint = findMidnormalPoint(center, a, b, area, radius);\n Point midInsectPoint = new Point((a.x + b.x) / 2, (a.y + b.y) / 2);\n double distance = pointsDistance(midInsectPoint, innerPoint);\n if (distance > radius) {\n return 360 - angle;\n }\n return angle;\n }", "public static MediaType nonBinaryUtf8( MediaType.Type type, String subType ) {\n return new MediaType( type, subType, UTF_8 );\n }", "public ProjectCalendarHours addCalendarHours(Day day)\n {\n ProjectCalendarHours bch = new ProjectCalendarHours(this);\n bch.setDay(day);\n m_hours[day.getValue() - 1] = bch;\n return (bch);\n }", "public void editCoords(String photoId, String userId, Rectangle bounds) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_COORDS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"user_id\", userId);\r\n parameters.put(\"person_x\", bounds.x);\r\n parameters.put(\"person_y\", bounds.y);\r\n parameters.put(\"person_w\", bounds.width);\r\n parameters.put(\"person_h\", bounds.height);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }" ]
Adds OPT_D | OPT_DIR option to OptionParser, with one argument. @param parser OptionParser to be modified @param required Tells if this option is required or optional
[ "public static void acceptsDir(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_D, OPT_DIR), \"directory path for input/output\")\n .withRequiredArg()\n .describedAs(\"dir-path\")\n .ofType(String.class);\n }" ]
[ "public void updateAnimation()\n {\n Date time = new Date();\n long currentTime = time.getTime() - this.beginAnimation;\n if (currentTime > animationTime)\n {\n this.currentQuaternion.set(endQuaternion);\n for (int i = 0; i < 3; i++)\n {\n\n this.currentPos[i] = this.endPos[i];\n }\n this.animate = false;\n }\n\n else\n {\n float t = (float) currentTime / animationTime;\n this.currentQuaternion = this.beginQuaternion.slerp(this.endQuaternion,\n t);\n for (int i = 0; i < 3; i++)\n {\n this.currentPos[i] = this.beginPos[i] + totalTranslation[i] * t;\n }\n\n }\n }", "public static final Integer getInteger(Number value)\n {\n Integer result = null;\n if (value != null)\n {\n if (value instanceof Integer)\n {\n result = (Integer) value;\n }\n else\n {\n result = Integer.valueOf((int) Math.round(value.doubleValue()));\n }\n }\n return (result);\n }", "private IndexedContainer createContainerForBundleWithDescriptor() throws IOException, CmsException {\n\n IndexedContainer container = new IndexedContainer();\n\n // create properties\n container.addContainerProperty(TableProperty.KEY, String.class, \"\");\n container.addContainerProperty(TableProperty.DESCRIPTION, String.class, \"\");\n container.addContainerProperty(TableProperty.DEFAULT, String.class, \"\");\n container.addContainerProperty(TableProperty.TRANSLATION, String.class, \"\");\n\n // add entries\n SortedProperties localization = getLocalization(m_locale);\n CmsXmlContentValueSequence messages = m_descContent.getValueSequence(Descriptor.N_MESSAGE, Descriptor.LOCALE);\n String descValue;\n boolean hasDescription = false;\n String defaultValue;\n boolean hasDefault = false;\n for (int i = 0; i < messages.getElementCount(); i++) {\n\n String prefix = messages.getValue(i).getPath() + \"/\";\n Object itemId = container.addItem();\n Item item = container.getItem(itemId);\n String key = m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).getStringValue(m_cms);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n String translation = localization.getProperty(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == translation ? \"\" : translation);\n descValue = m_descContent.getValue(prefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).getStringValue(\n m_cms);\n item.getItemProperty(TableProperty.DESCRIPTION).setValue(descValue);\n hasDescription = hasDescription || !descValue.isEmpty();\n defaultValue = m_descContent.getValue(prefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).getStringValue(\n m_cms);\n item.getItemProperty(TableProperty.DEFAULT).setValue(defaultValue);\n hasDefault = hasDefault || !defaultValue.isEmpty();\n }\n\n m_hasDefault = hasDefault;\n m_hasDescription = hasDescription;\n return container;\n\n }", "public static final String hexdump(byte[] buffer, int offset, int length, boolean ascii, int columns, String prefix)\n {\n StringBuilder sb = new StringBuilder();\n if (buffer != null)\n {\n int index = offset;\n DecimalFormat df = new DecimalFormat(\"00000\");\n\n while (index < (offset + length))\n {\n if (index + columns > (offset + length))\n {\n columns = (offset + length) - index;\n }\n\n sb.append(prefix);\n sb.append(df.format(index - offset));\n sb.append(\":\");\n sb.append(hexdump(buffer, index, columns, ascii));\n sb.append('\\n');\n\n index += columns;\n }\n }\n\n return (sb.toString());\n }", "public Slice newSlice(long address, int size, Object reference)\n {\n if (address <= 0) {\n throw new IllegalArgumentException(\"Invalid address: \" + address);\n }\n if (reference == null) {\n throw new NullPointerException(\"Object reference is null\");\n }\n if (size == 0) {\n return Slices.EMPTY_SLICE;\n }\n return new Slice(null, address, size, size, reference);\n }", "public AnnotationTypeCondition addCondition(String element, AnnotationCondition condition)\n {\n this.conditions.put(element, condition);\n return this;\n }", "private void writeToDelegate(byte[] data) {\n\n if (m_delegateStream != null) {\n try {\n m_delegateStream.write(data);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n }", "public String isChecked(String value1, String value2) {\n\n if ((value1 == null) || (value2 == null)) {\n return \"\";\n }\n\n if (value1.trim().equalsIgnoreCase(value2.trim())) {\n return \"checked\";\n }\n\n return \"\";\n }", "public static final BigDecimal printUnits(Number value)\n {\n return (value == null ? BIGDECIMAL_ONE : new BigDecimal(value.doubleValue() / 100));\n }" ]
Gets Widget layout dimension @param axis The {@linkplain Layout.Axis axis} to obtain layout size for @return dimension
[ "public float getLayoutSize(final Layout.Axis axis) {\n float size = 0;\n for (Layout layout : mLayouts) {\n size = Math.max(size, layout.getSize(axis));\n }\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"getLayoutSize [%s] axis [%s] size [%f]\", getName(), axis, size);\n return size;\n }" ]
[ "public static Object newInstance(String className, Class type, Object arg) throws InstantiationException,\r\n IllegalAccessException,\r\n IllegalArgumentException,\r\n InvocationTargetException,\r\n NoSuchMethodException,\r\n SecurityException,\r\n ClassNotFoundException\r\n {\r\n return newInstance(className, new Class[]{type}, new Object[]{arg});\r\n }", "private EditorState getDefaultState() {\n\n List<TableProperty> cols = new ArrayList<TableProperty>(1);\n cols.add(TableProperty.TRANSLATION);\n\n return new EditorState(cols, false);\n }", "public static Credential getServiceAccountCredential(String serviceAccountId,\n String privateKeyFile, Collection<String> serviceAccountScopes)\n throws GeneralSecurityException, IOException {\n return getCredentialBuilderWithoutPrivateKey(serviceAccountId, serviceAccountScopes)\n .setServiceAccountPrivateKeyFromP12File(new File(privateKeyFile))\n .build();\n }", "public float DistanceTo(IntPoint anotherPoint) {\r\n float dx = this.x - anotherPoint.x;\r\n float dy = this.y - anotherPoint.y;\r\n\r\n return (float) Math.sqrt(dx * dx + dy * dy);\r\n }", "public static servicegroup_lbmonitor_binding[] get(nitro_service service, String servicegroupname) throws Exception{\n\t\tservicegroup_lbmonitor_binding obj = new servicegroup_lbmonitor_binding();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tservicegroup_lbmonitor_binding response[] = (servicegroup_lbmonitor_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static Date min(Date d1, Date d2)\n {\n Date result;\n if (d1 == null)\n {\n result = d2;\n }\n else\n if (d2 == null)\n {\n result = d1;\n }\n else\n {\n result = (d1.compareTo(d2) < 0) ? d1 : d2;\n }\n return result;\n }", "public static Info neg(final Variable A, ManagerTempVariables manager) {\n Info ret = new Info();\n\n if( A instanceof VariableInteger ) {\n final VariableInteger output = manager.createInteger();\n ret.output = output;\n ret.op = new Operation(\"neg-i\") {\n @Override\n public void process() {\n output.value = -((VariableInteger)A).value;\n }\n };\n } else if( A instanceof VariableScalar ) {\n final VariableDouble output = manager.createDouble();\n ret.output = output;\n ret.op = new Operation(\"neg-s\") {\n @Override\n public void process() {\n output.value = -((VariableScalar)A).getDouble();\n }\n };\n } else if( A instanceof VariableMatrix ) {\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n ret.op = new Operation(\"neg-m\") {\n @Override\n public void process() {\n DMatrixRMaj a = ((VariableMatrix)A).matrix;\n output.matrix.reshape(a.numRows, a.numCols);\n CommonOps_DDRM.changeSign(a, output.matrix);\n }\n };\n } else {\n throw new RuntimeException(\"Unsupported variable \"+A);\n }\n\n return ret;\n }", "private RandomVariableInterface getDrift(int timeIndex, int componentIndex, RandomVariableInterface[] realizationAtTimeIndex, RandomVariableInterface[] realizationPredictor) {\n\n\t\t// Check if this LIBOR is already fixed\n\t\tif(getTime(timeIndex) >= this.getLiborPeriod(componentIndex)) {\n\t\t\treturn null;\n\t\t}\n\n\t\t/*\n\t\t * We implemented several different methods to calculate the drift\n\t\t */\n\t\tif(driftApproximationMethod == Driftapproximation.PREDICTOR_CORRECTOR && realizationPredictor != null) {\n\t\t\tRandomVariableInterface drift\t\t\t\t\t= getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex);\n\t\t\tRandomVariableInterface driftEulerWithPredictor\t= getDriftEuler(timeIndex, componentIndex, realizationPredictor);\n\t\t\tdrift = drift.add(driftEulerWithPredictor).div(2.0);\n\n\t\t\treturn drift;\n\t\t}\n\t\telse if(driftApproximationMethod == Driftapproximation.LINE_INTEGRAL && realizationPredictor != null) {\n\t\t\treturn getDriftLineIntegral(timeIndex, componentIndex, realizationAtTimeIndex, realizationPredictor);\n\t\t}\n\t\telse {\n\t\t\treturn getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex);\n\t\t}\n\t}", "public static KnowledgeBuilderConfiguration newKnowledgeBuilderConfiguration(Properties properties,\n ClassLoader... classLoaders) {\n return FactoryServiceHolder.factoryService.newKnowledgeBuilderConfiguration( properties, classLoaders );\n }" ]
Checks whether the specified event name is restricted. If it is, then create a pending error, and abort. @param name The event name @return Boolean indication whether the event name is restricted
[ "ValidationResult isRestrictedEventName(String name) {\n ValidationResult error = new ValidationResult();\n if (name == null) {\n error.setErrorCode(510);\n error.setErrorDesc(\"Event Name is null\");\n return error;\n }\n for (String x : restrictedNames)\n if (name.equalsIgnoreCase(x)) {\n // The event name is restricted\n\n error.setErrorCode(513);\n error.setErrorDesc(name + \" is a restricted event name. Last event aborted.\");\n Logger.v(name + \" is a restricted system event name. Last event aborted.\");\n return error;\n }\n return error;\n }" ]
[ "protected AssemblyResponse watchStatus() throws LocalOperationException, RequestException {\n AssemblyResponse response;\n do {\n response = getClient().getAssemblyByUrl(url);\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n throw new LocalOperationException(e);\n }\n } while (!response.isFinished());\n\n setState(State.FINISHED);\n return response;\n }", "public static base_responses unset(nitro_service client, String selectorname[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (selectorname != null && selectorname.length > 0) {\n\t\t\tnslimitselector unsetresources[] = new nslimitselector[selectorname.length];\n\t\t\tfor (int i=0;i<selectorname.length;i++){\n\t\t\t\tunsetresources[i] = new nslimitselector();\n\t\t\t\tunsetresources[i].selectorname = selectorname[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "public static void copyRecursively(final Path source, final Path target, boolean overwrite) throws IOException {\n final CopyOption[] options;\n if (overwrite) {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING};\n } else {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES};\n }\n Files.walkFileTree(source, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n Files.copy(dir, target.resolve(source.relativize(dir)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n Files.copy(file, target.resolve(source.relativize(file)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n DeploymentRepositoryLogger.ROOT_LOGGER.cannotCopyFile(exc, file);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n });\n }", "public Class getPersistentFieldClass()\r\n {\r\n if (m_persistenceClass == null)\r\n {\r\n Properties properties = new Properties();\r\n try\r\n {\r\n this.logWarning(\"Loading properties file: \" + getPropertiesFile());\r\n properties.load(new FileInputStream(getPropertiesFile()));\r\n }\r\n catch (IOException e)\r\n {\r\n this.logWarning(\"Could not load properties file '\" + getPropertiesFile()\r\n + \"'. Using PersistentFieldDefaultImpl.\");\r\n e.printStackTrace();\r\n }\r\n try\r\n {\r\n String className = properties.getProperty(\"PersistentFieldClass\");\r\n\r\n m_persistenceClass = loadClass(className);\r\n }\r\n catch (ClassNotFoundException e)\r\n {\r\n e.printStackTrace();\r\n m_persistenceClass = PersistentFieldPrivilegedImpl.class;\r\n }\r\n logWarning(\"PersistentFieldClass: \" + m_persistenceClass.toString());\r\n }\r\n return m_persistenceClass;\r\n }", "public static <T extends DMatrix> boolean decomposeSafe(DecompositionInterface<T> decomp, T M ) {\n if( decomp.inputModified() ) {\n return decomp.decompose(M.<T>copy());\n } else {\n return decomp.decompose(M);\n }\n }", "public CmsResource buildResource() {\n\n return new CmsResource(\n m_structureId,\n m_resourceId,\n m_rootPath,\n m_type,\n m_flags,\n m_projectLastModified,\n m_state,\n m_dateCreated,\n m_userCreated,\n m_dateLastModified,\n m_userLastModified,\n m_dateReleased,\n m_dateExpired,\n m_length,\n m_flags,\n m_dateContent,\n m_version);\n }", "@Override\n public boolean isTempoMaster() {\n DeviceUpdate master = VirtualCdj.getInstance().getTempoMaster();\n return (master != null) && master.getAddress().equals(address);\n }", "public static List<String> getCommaSeparatedStringValues(String paramValue, String type) {\n List<String> commaSeparatedProps = Lists.newArrayList();\n for(String url: Utils.COMMA_SEP.split(paramValue.trim()))\n if(url.trim().length() > 0)\n commaSeparatedProps.add(url);\n\n if(commaSeparatedProps.size() == 0) {\n throw new RuntimeException(\"Number of \" + type + \" should be greater than zero\");\n }\n return commaSeparatedProps;\n }", "public OTMConnection acquireConnection(PBKey pbKey)\r\n {\r\n TransactionFactory txFactory = getTransactionFactory();\r\n return txFactory.acquireConnection(pbKey);\r\n }" ]
Invalidating just the GVRView associated with the GVRViewSceneObject incorrectly set the clip rectangle to just that view. To fix this, we have to create a full screen android View and invalidate this to restore the clip rectangle. @return full screen View object
[ "public View getFullScreenView() {\n if (mFullScreenView != null) {\n return mFullScreenView;\n }\n\n final DisplayMetrics metrics = new DisplayMetrics();\n mActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);\n final int screenWidthPixels = Math.max(metrics.widthPixels, metrics.heightPixels);\n final int screenHeightPixels = Math.min(metrics.widthPixels, metrics.heightPixels);\n\n final ViewGroup.LayoutParams layout = new ViewGroup.LayoutParams(screenWidthPixels, screenHeightPixels);\n mFullScreenView = new View(mActivity);\n mFullScreenView.setLayoutParams(layout);\n mRenderableViewGroup.addView(mFullScreenView);\n\n return mFullScreenView;\n }" ]
[ "protected void getBatch(int batchSize){\r\n\r\n// if (numCalls == 0) {\r\n// for (int i = 0; i < 1538*\\15; i++) {\r\n// randGenerator.nextInt(this.dataDimension());\r\n// }\r\n// }\r\n// numCalls++;\r\n\r\n if (thisBatch == null || thisBatch.length != batchSize){\r\n thisBatch = new int[batchSize];\r\n }\r\n\r\n //-----------------------------\r\n //RANDOM WITH REPLACEMENT\r\n //-----------------------------\r\n if (sampleMethod.equals(SamplingMethod.RandomWithReplacement)){\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = randGenerator.nextInt(this.dataDimension()); //Just generate a random index\r\n// System.err.println(\"numCalls = \"+(numCalls++));\r\n }\r\n //-----------------------------\r\n //ORDERED\r\n //-----------------------------\r\n }else if(sampleMethod.equals(SamplingMethod.Ordered)){\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = (curElement + i) % this.dataDimension() ; //Take the next batchSize points in order\r\n }\r\n curElement = (curElement + batchSize) % this.dataDimension(); //watch out for overflow\r\n\r\n //-----------------------------\r\n //RANDOM WITHOUT REPLACEMENT\r\n //-----------------------------\r\n }else if(sampleMethod.equals(SamplingMethod.RandomWithoutReplacement)){\r\n //Declare the indices array if needed.\r\n if (allIndices == null || allIndices.size()!= this.dataDimension()){\r\n\r\n allIndices = new ArrayList<Integer>();\r\n for(int i=0;i<this.dataDimension();i++){\r\n allIndices.add(i);\r\n }\r\n Collections.shuffle(allIndices,randGenerator);\r\n }\r\n\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = allIndices.get((curElement + i) % allIndices.size()); //Grab the next batchSize indices\r\n }\r\n\r\n if (curElement + batchSize > this.dataDimension()){\r\n Collections.shuffle(Arrays.asList(allIndices),randGenerator); //Shuffle if we got to the end of the list\r\n }\r\n\r\n //watch out for overflow\r\n curElement = (curElement + batchSize) % allIndices.size(); //Rollover\r\n\r\n\r\n }else{\r\n System.err.println(\"NO SAMPLING METHOD SELECTED\");\r\n System.exit(1);\r\n }\r\n\r\n\r\n }", "protected static void captureSystemStreams(boolean captureOut, boolean captureErr){\r\n if(captureOut){\r\n System.setOut(new RedwoodPrintStream(STDOUT, realSysOut));\r\n }\r\n if(captureErr){\r\n System.setErr(new RedwoodPrintStream(STDERR, realSysErr));\r\n }\r\n }", "public static boolean hasFacet(GridDialect gridDialect, Class<? extends GridDialect> facetType) {\n\t\tif ( gridDialect instanceof ForwardingGridDialect ) {\n\t\t\treturn hasFacet( ( (ForwardingGridDialect<?>) gridDialect ).getGridDialect(), facetType );\n\t\t}\n\t\telse {\n\t\t\treturn facetType.isAssignableFrom( gridDialect.getClass() );\n\t\t}\n\t}", "public ItemRequest<Tag> findById(String tag) {\n \n String path = String.format(\"/tags/%s\", tag);\n return new ItemRequest<Tag>(this, Tag.class, path, \"GET\");\n }", "private void readTable(InputStream is, SynchroTable table) throws IOException\n {\n int skip = table.getOffset() - m_offset;\n if (skip != 0)\n {\n StreamHelper.skip(is, skip);\n m_offset += skip;\n }\n\n String tableName = DatatypeConverter.getString(is);\n int tableNameLength = 2 + tableName.length();\n m_offset += tableNameLength;\n\n int dataLength;\n if (table.getLength() == -1)\n {\n dataLength = is.available();\n }\n else\n {\n dataLength = table.getLength() - tableNameLength;\n }\n\n SynchroLogger.log(\"READ\", tableName);\n\n byte[] compressedTableData = new byte[dataLength];\n is.read(compressedTableData);\n m_offset += dataLength;\n\n Inflater inflater = new Inflater();\n inflater.setInput(compressedTableData);\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream(compressedTableData.length);\n byte[] buffer = new byte[1024];\n while (!inflater.finished())\n {\n int count;\n\n try\n {\n count = inflater.inflate(buffer);\n }\n catch (DataFormatException ex)\n {\n throw new IOException(ex);\n }\n outputStream.write(buffer, 0, count);\n }\n outputStream.close();\n byte[] uncompressedTableData = outputStream.toByteArray();\n\n SynchroLogger.log(uncompressedTableData);\n\n m_tableData.put(table.getName(), uncompressedTableData);\n }", "public List<ServerRedirect> tableServers(int clientId) {\n List<ServerRedirect> servers = new ArrayList<>();\n\n try {\n Client client = ClientService.getInstance().getClient(clientId);\n servers = tableServers(client.getProfile().getId(), client.getActiveServerGroup());\n } catch (SQLException e) {\n e.printStackTrace();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return servers;\n }", "public int getNumWeights() {\r\n if (weights == null) return 0;\r\n int numWeights = 0;\r\n for (double[] wts : weights) {\r\n numWeights += wts.length;\r\n }\r\n return numWeights;\r\n }", "public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name) {\n return createEnterpriseUser(api, login, name, null);\n }", "public static vpnglobal_auditnslogpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_auditnslogpolicy_binding obj = new vpnglobal_auditnslogpolicy_binding();\n\t\tvpnglobal_auditnslogpolicy_binding response[] = (vpnglobal_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
return either the first space or the first nbsp
[ "public static int findSpace(String haystack, int begin) {\r\n int space = haystack.indexOf(' ', begin);\r\n int nbsp = haystack.indexOf('\\u00A0', begin);\r\n if (space == -1 && nbsp == -1) {\r\n return -1;\r\n } else if (space >= 0 && nbsp >= 0) {\r\n return Math.min(space, nbsp);\r\n } else {\r\n // eg one is -1, and the other is >= 0\r\n return Math.max(space, nbsp);\r\n }\r\n }" ]
[ "private float[] generateParticleTimeStamps(float totalTime)\n {\n float timeStamps[] = new float[mEmitRate * 2];\n\n if ( burstMode ) {\n for (int i = 0; i < mEmitRate * 2; i += 2) {\n timeStamps[i] = totalTime;\n timeStamps[i + 1] = 0;\n }\n }\n else {\n for (int i = 0; i < mEmitRate * 2; i += 2) {\n timeStamps[i] = totalTime + mRandom.nextFloat();\n timeStamps[i + 1] = 0;\n }\n }\n return timeStamps;\n\n }", "private double CosineInterpolate(double x1, double x2, double a) {\n double f = (1 - Math.cos(a * Math.PI)) * 0.5;\n\n return x1 * (1 - f) + x2 * f;\n }", "public Collection<Exif> getExif(String photoId, String secret) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_EXIF);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n if (secret != null) {\r\n parameters.put(\"secret\", secret);\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n List<Exif> exifs = new ArrayList<Exif>();\r\n Element photoElement = response.getPayload();\r\n NodeList exifElements = photoElement.getElementsByTagName(\"exif\");\r\n for (int i = 0; i < exifElements.getLength(); i++) {\r\n Element exifElement = (Element) exifElements.item(i);\r\n Exif exif = new Exif();\r\n exif.setTagspace(exifElement.getAttribute(\"tagspace\"));\r\n exif.setTagspaceId(exifElement.getAttribute(\"tagspaceid\"));\r\n exif.setTag(exifElement.getAttribute(\"tag\"));\r\n exif.setLabel(exifElement.getAttribute(\"label\"));\r\n exif.setRaw(XMLUtilities.getChildValue(exifElement, \"raw\"));\r\n exif.setClean(XMLUtilities.getChildValue(exifElement, \"clean\"));\r\n exifs.add(exif);\r\n }\r\n return exifs;\r\n }", "private Component createConvertToPropertyBundleButton() {\n\n Button addDescriptorButton = CmsToolBar.createButton(\n FontOpenCms.SETTINGS,\n m_messages.key(Messages.GUI_CONVERT_TO_PROPERTY_BUNDLE_0));\n\n addDescriptorButton.setDisableOnClick(true);\n\n addDescriptorButton.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n try {\n m_model.saveAsPropertyBundle();\n Notification.show(\"Conversion successful.\");\n } catch (CmsException | IOException e) {\n CmsVaadinUtils.showAlert(\"Conversion failed\", e.getLocalizedMessage(), null);\n }\n }\n });\n addDescriptorButton.setDisableOnClick(true);\n return addDescriptorButton;\n }", "private void readTasks(Integer id)\n {\n Integer currentID = id;\n Table table = getTable(\"WBSTAB\");\n\n while (currentID.intValue() != 0)\n {\n MapRow row = table.find(currentID);\n Task task = m_projectFile.getTaskByUniqueID(row.getInteger(\"TASK_ID\"));\n readLeafTasks(task, row.getInteger(\"FIRST_CHILD_TASK_ID\"));\n Integer childID = row.getInteger(\"CHILD_ID\");\n if (childID.intValue() != 0)\n {\n readTasks(childID);\n }\n currentID = row.getInteger(\"NEXT_ID\");\n }\n }", "public static AppDescriptor of(String appName, Class<?> entryClass) {\n System.setProperty(\"osgl.version.suppress-var-found-warning\", \"true\");\n return of(appName, entryClass, Version.of(entryClass));\n }", "public static void cleanIneligibleKeys(Map<ByteArray, Map<Value, Set<ClusterNode>>> keyVersionNodeSetMap,\n int requiredWrite) {\n Set<ByteArray> keysToDelete = new HashSet<ByteArray>();\n for (Map.Entry<ByteArray, Map<Value, Set<ClusterNode>>> entry : keyVersionNodeSetMap.entrySet()) {\n Set<Value> valuesToDelete = new HashSet<Value>();\n\n ByteArray key = entry.getKey();\n Map<Value, Set<ClusterNode>> valueNodeSetMap = entry.getValue();\n // mark version for deletion if not enough writes\n for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : valueNodeSetMap.entrySet()) {\n Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue();\n if (nodeSet.size() < requiredWrite) {\n valuesToDelete.add(versionNodeSetEntry.getKey());\n }\n }\n // delete versions\n for (Value v : valuesToDelete) {\n valueNodeSetMap.remove(v);\n }\n // mark key for deletion if no versions left\n if (valueNodeSetMap.size() == 0) {\n keysToDelete.add(key);\n }\n }\n // delete keys\n for (ByteArray k : keysToDelete) {\n keyVersionNodeSetMap.remove(k);\n }\n }", "public static CuratorFramework newCurator(String zookeepers, int timeout, String secret) {\n\n final ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 10);\n if (secret.isEmpty()) {\n return CuratorFrameworkFactory.newClient(zookeepers, timeout, timeout, retry);\n } else {\n return CuratorFrameworkFactory.builder().connectString(zookeepers)\n .connectionTimeoutMs(timeout).sessionTimeoutMs(timeout).retryPolicy(retry)\n .authorization(\"digest\", (\"fluo:\" + secret).getBytes(StandardCharsets.UTF_8))\n .aclProvider(new ACLProvider() {\n @Override\n public List<ACL> getDefaultAcl() {\n return CREATOR_ALL_ACL;\n }\n\n @Override\n public List<ACL> getAclForPath(String path) {\n switch (path) {\n case ZookeeperPath.ORACLE_GC_TIMESTAMP:\n // The garbage collection iterator running in Accumulo tservers needs to read this\n // value w/o authenticating.\n return PUBLICLY_READABLE_ACL;\n default:\n return CREATOR_ALL_ACL;\n }\n }\n }).build();\n }\n }", "protected <T, A> ActiveOperation<T, A> registerActiveOperation(final Integer id, A attachment, ActiveOperation.CompletedCallback<T> callback) {\n lock.lock();\n try {\n // Check that we still allow registration\n // TODO WFCORE-199 distinguish client uses from server uses and limit this check to server uses\n // Using id==null may be one way to do this, but we need to consider ops that involve multiple requests\n // TODO WFCORE-845 consider using an IllegalStateException for this\n //assert ! shutdown;\n final Integer operationId;\n if(id == null) {\n // If we did not get an operationId, create a new one\n operationId = operationIdManager.createBatchId();\n } else {\n // Check that the operationId is not already taken\n if(! operationIdManager.lockBatchId(id)) {\n throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(id);\n }\n operationId = id;\n }\n final ActiveOperationImpl<T, A> request = new ActiveOperationImpl<T, A>(operationId, attachment, getCheckedCallback(callback), this);\n final ActiveOperation<?, ?> existing = activeRequests.putIfAbsent(operationId, request);\n if(existing != null) {\n throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(operationId);\n }\n ProtocolLogger.ROOT_LOGGER.tracef(\"Registered active operation %d\", operationId);\n activeCount++; // condition.signalAll();\n return request;\n } finally {\n lock.unlock();\n }\n }" ]
Uniformly random numbers
[ "public static Info rand( final Variable A , final Variable B , ManagerTempVariables manager) {\n Info ret = new Info();\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n\n if( A instanceof VariableInteger && B instanceof VariableInteger ) {\n ret.op = new Operation(\"rand-ii\") {\n @Override\n public void process() {\n int numRows = ((VariableInteger)A).value;\n int numCols = ((VariableInteger)B).value;\n output.matrix.reshape(numRows,numCols);\n RandomMatrices_DDRM.fillUniform(output.matrix, 0,1,manager.getRandom());\n }\n };\n } else {\n throw new RuntimeException(\"Expected two integers got \"+A+\" \"+B);\n }\n\n return ret;\n }" ]
[ "public static boolean pullImage(Launcher launcher, final String imageTag, final String username, final String password, final String host)\n throws IOException, InterruptedException {\n\n return launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {\n public Boolean call() throws IOException {\n DockerUtils.pullImage(imageTag, username, password, host);\n return true;\n }\n });\n }", "public static double[][] diag(double[] vector){\n\n\t\t// Note: According to the Java Language spec, an array is initialized with the default value, here 0.\n\t\tdouble[][] diagonalMatrix = new double[vector.length][vector.length];\n\n\t\tfor(int index = 0; index < vector.length; index++) {\n\t\t\tdiagonalMatrix[index][index] = vector[index];\n\t\t}\n\n\t\treturn diagonalMatrix;\n\t}", "public static <T extends JsonRtn> T parseJsonRtn(String jsonRtn, Class<T> jsonRtnClazz) {\n T rtn = JSONObject.parseObject(jsonRtn, jsonRtnClazz);\n appendErrorHumanMsg(rtn);\n return rtn;\n }", "public Where<T, ID> le(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.LESS_THAN_EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}", "private void fillToolBar(final I_CmsAppUIContext context) {\n\n context.setAppTitle(m_messages.key(Messages.GUI_APP_TITLE_0));\n\n // create components\n Component publishBtn = createPublishButton();\n m_saveBtn = createSaveButton();\n m_saveExitBtn = createSaveExitButton();\n Component closeBtn = createCloseButton();\n\n context.enableDefaultToolbarButtons(false);\n context.addToolbarButtonRight(closeBtn);\n context.addToolbarButton(publishBtn);\n context.addToolbarButton(m_saveExitBtn);\n context.addToolbarButton(m_saveBtn);\n\n Component addDescriptorBtn = createAddDescriptorButton();\n if (m_model.hasDescriptor() || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {\n addDescriptorBtn.setEnabled(false);\n }\n context.addToolbarButton(addDescriptorBtn);\n if (m_model.getBundleType().equals(BundleType.XML)) {\n Component convertToPropertyBundleBtn = createConvertToPropertyBundleButton();\n context.addToolbarButton(convertToPropertyBundleBtn);\n }\n }", "public ResponseFromManager generateUpdateExecuteTask(ParallelTask task) {\n\n // add to map now; as can only pass final\n ParallelTaskManager.getInstance().addTaskToInProgressMap(\n task.getTaskId(), task);\n logger.info(\"Added task {} to the running inprogress map...\",\n task.getTaskId());\n\n boolean useReplacementVarMap = false;\n boolean useReplacementVarMapNodeSpecific = false;\n Map<String, StrStrMap> replacementVarMapNodeSpecific = null;\n Map<String, String> replacementVarMap = null;\n\n ResponseFromManager batchResponseFromManager = null;\n\n switch (task.getRequestReplacementType()) {\n case UNIFORM_VAR_REPLACEMENT:\n useReplacementVarMap = true;\n useReplacementVarMapNodeSpecific = false;\n replacementVarMap = task.getReplacementVarMap();\n break;\n case TARGET_HOST_SPECIFIC_VAR_REPLACEMENT:\n useReplacementVarMap = false;\n useReplacementVarMapNodeSpecific = true;\n replacementVarMapNodeSpecific = task\n .getReplacementVarMapNodeSpecific();\n break;\n case NO_REPLACEMENT:\n useReplacementVarMap = false;\n useReplacementVarMapNodeSpecific = false;\n break;\n default:\n logger.error(\"error request replacement type. default as no replacement\");\n }// end switch\n\n // generate content in nodedata\n InternalDataProvider dp = InternalDataProvider.getInstance();\n dp.genNodeDataMap(task);\n\n VarReplacementProvider.getInstance()\n .updateRequestWithReplacement(task, useReplacementVarMap,\n replacementVarMap, useReplacementVarMapNodeSpecific,\n replacementVarMapNodeSpecific);\n\n batchResponseFromManager = \n sendTaskToExecutionManager(task);\n\n removeTaskFromInProgressMap(task.getTaskId());\n logger.info(\n \"Removed task {} from the running inprogress map... \"\n + \". This task should be garbage collected if there are no other pointers.\",\n task.getTaskId());\n return batchResponseFromManager;\n\n }", "public static auditsyslogpolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_systemglobal_binding obj = new auditsyslogpolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_systemglobal_binding response[] = (auditsyslogpolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@Override\n public ModelNode resolveValue(ExpressionResolver resolver, ModelNode value) throws OperationFailedException {\n\n // Pass non-OBJECT values through the superclass so it can reject weird values and, in the odd chance\n // that's how this object is set up, turn undefined into a default list value.\n ModelNode superResult = value.getType() == ModelType.OBJECT ? value : super.resolveValue(resolver, value);\n\n // If it's not an OBJECT (almost certainly UNDEFINED), then nothing more we can do\n if (superResult.getType() != ModelType.OBJECT) {\n return superResult;\n }\n\n // Resolve each field.\n // Don't mess with the original value\n ModelNode clone = superResult == value ? value.clone() : superResult;\n ModelNode result = new ModelNode();\n for (AttributeDefinition field : valueTypes) {\n String fieldName = field.getName();\n if (clone.has(fieldName)) {\n result.get(fieldName).set(field.resolveValue(resolver, clone.get(fieldName)));\n } else {\n // Input doesn't have a child for this field.\n // Don't create one in the output unless the AD produces a default value.\n // TBH this doesn't make a ton of sense, since any object should have\n // all of its fields, just some may be undefined. But doing it this\n // way may avoid breaking some code that is incorrectly checking node.has(\"xxx\")\n // instead of node.hasDefined(\"xxx\")\n ModelNode val = field.resolveValue(resolver, new ModelNode());\n if (val.isDefined()) {\n result.get(fieldName).set(val);\n }\n }\n }\n // Validate the entire object\n getValidator().validateParameter(getName(), result);\n return result;\n }", "public int[] indices(Collection<E> elems) {\r\n int[] indices = new int[elems.size()];\r\n int i = 0;\r\n for (E elem : elems) {\r\n indices[i++] = indexOf(elem);\r\n }\r\n return indices;\r\n }" ]
Use this API to fetch statistics of appfwprofile_stats resource of given name .
[ "public static appfwprofile_stats get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tobj.set_name(name);\n\t\tappfwprofile_stats response = (appfwprofile_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}" ]
[ "protected void bindHelper(GVRScriptBundle scriptBundle, GVRSceneObject rootSceneObject, int bindMask)\n throws IOException, GVRScriptException\n {\n for (GVRScriptBindingEntry entry : scriptBundle.file.binding) {\n GVRAndroidResource rc;\n if (entry.volumeType == null || entry.volumeType.isEmpty()) {\n rc = scriptBundle.volume.openResource(entry.script);\n } else {\n GVRResourceVolume.VolumeType volumeType = GVRResourceVolume.VolumeType.fromString(entry.volumeType);\n if (volumeType == null) {\n throw new GVRScriptException(String.format(\"Volume type %s is not recognized, script=%s\",\n entry.volumeType, entry.script));\n }\n rc = new GVRResourceVolume(mGvrContext, volumeType).openResource(entry.script);\n }\n\n GVRScriptFile scriptFile = (GVRScriptFile)loadScript(rc, entry.language);\n\n String targetName = entry.target;\n if (targetName.startsWith(TARGET_PREFIX)) {\n TargetResolver resolver = sBuiltinTargetMap.get(targetName);\n IScriptable target = resolver.getTarget(mGvrContext, targetName);\n\n // Apply mask\n boolean toBind = false;\n if ((bindMask & BIND_MASK_GVRSCRIPT) != 0 && targetName.equalsIgnoreCase(TARGET_GVRMAIN)) {\n toBind = true;\n }\n\n if ((bindMask & BIND_MASK_GVRACTIVITY) != 0 && targetName.equalsIgnoreCase(TARGET_GVRAPPLICATION)) {\n toBind = true;\n }\n\n if (toBind) {\n attachScriptFile(target, scriptFile);\n }\n } else {\n if ((bindMask & BIND_MASK_SCENE_OBJECTS) != 0) {\n if (targetName.equals(rootSceneObject.getName())) {\n attachScriptFile(rootSceneObject, scriptFile);\n }\n\n // Search in children\n GVRSceneObject[] sceneObjects = rootSceneObject.getSceneObjectsByName(targetName);\n if (sceneObjects != null) {\n for (GVRSceneObject sceneObject : sceneObjects) {\n GVRScriptBehavior b = new GVRScriptBehavior(sceneObject.getGVRContext());\n b.setScriptFile(scriptFile);\n sceneObject.attachComponent(b);\n }\n }\n }\n }\n }\n }", "private static JsonArray getJsonArray(List<String> keys) {\n JsonArray array = new JsonArray();\n for (String key : keys) {\n array.add(key);\n }\n\n return array;\n }", "public boolean isActive(int profileId) {\n boolean active = false;\n PreparedStatement queryStatement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.CLIENT_IS_ACTIVE + \" FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= '-1' \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ? \"\n );\n queryStatement.setInt(1, profileId);\n logger.info(queryStatement.toString());\n ResultSet results = queryStatement.executeQuery();\n if (results.next()) {\n active = results.getBoolean(Constants.CLIENT_IS_ACTIVE);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return active;\n }", "public ProducerPoolData<V> getProducerPoolData(String topic, Partition bidPid, List<V> data) {\n return new ProducerPoolData<V>(topic, bidPid, data);\n }", "public List<RoutableDestination<T>> getDestinations(String path) {\n\n String cleanPath = (path.endsWith(\"/\") && path.length() > 1)\n ? path.substring(0, path.length() - 1) : path;\n\n List<RoutableDestination<T>> result = new ArrayList<>();\n\n for (ImmutablePair<Pattern, RouteDestinationWithGroups> patternRoute : patternRouteList) {\n Map<String, String> groupNameValuesBuilder = new HashMap<>();\n Matcher matcher = patternRoute.getFirst().matcher(cleanPath);\n if (matcher.matches()) {\n int matchIndex = 1;\n for (String name : patternRoute.getSecond().getGroupNames()) {\n String value = matcher.group(matchIndex);\n groupNameValuesBuilder.put(name, value);\n matchIndex++;\n }\n result.add(new RoutableDestination<>(patternRoute.getSecond().getDestination(), groupNameValuesBuilder));\n }\n }\n return result;\n }", "@Override\n\tpublic String toNormalizedString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.normalizedString) == null) {\n\t\t\tif(hasZone()) {\n\t\t\t\tstringCache.normalizedString = result = toNormalizedString(IPv6StringCache.normalizedParams);\n\t\t\t} else {\n\t\t\t\tresult = getSection().toNormalizedString();//the cache is shared so no need to update it here\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}", "public String getCsv() {\n\n StringWriter writer = new StringWriter();\n try (CSVWriter csv = new CSVWriter(writer)) {\n List<String> headers = new ArrayList<>();\n for (String col : m_columns) {\n headers.add(col);\n }\n csv.writeNext(headers.toArray(new String[] {}));\n for (List<Object> row : m_data) {\n List<String> colCsv = new ArrayList<>();\n for (Object col : row) {\n colCsv.add(String.valueOf(col));\n }\n csv.writeNext(colCsv.toArray(new String[] {}));\n }\n return writer.toString();\n } catch (IOException e) {\n return null;\n }\n }", "public void setCapture(boolean capture, float fps) {\n capturing = capture;\n NativeTextureCapturer.setCapture(getNative(), capture, fps);\n }", "private static JSONObject parseProperties(HashMap<String, String> properties) throws JSONException {\n if (properties != null) {\n JSONObject propertiesObject = new JSONObject();\n\n for (String key : properties.keySet()) {\n String propertyValue = properties.get(key);\n\n /*\n * if(propertyValue.matches(\"true|false\")) {\n * \n * propertiesObject.put(key, propertyValue.equals(\"true\"));\n * \n * } else if(propertyValue.matches(\"[0-9]+\")) {\n * \n * Integer value = Integer.parseInt(propertyValue);\n * propertiesObject.put(key, value);\n * \n * } else\n */\n if (propertyValue.startsWith(\"{\") && propertyValue.endsWith(\"}\")) {\n propertiesObject.put(key,\n new JSONObject(propertyValue));\n } else {\n propertiesObject.put(key,\n propertyValue.toString());\n }\n }\n\n return propertiesObject;\n }\n\n return new JSONObject();\n }" ]
Returns an iban with replaced check digit. @param iban The iban @return The iban without the check digit
[ "static String replaceCheckDigit(final String iban, final String checkDigit) {\n return getCountryCode(iban) + checkDigit + getBban(iban);\n }" ]
[ "public static JasperPrint generateJasperPrint(DynamicReport dr, LayoutManager layoutManager, Connection con, Map<String, Object> _parameters) throws JRException {\n log.info(\"generating JasperPrint\");\n JasperPrint jp;\n\n if (_parameters == null)\n _parameters = new HashMap<String, Object>();\n\n visitSubreports(dr, _parameters);\n compileOrLoadSubreports(dr, _parameters, \"r\");\n\n DynamicJasperDesign jd = generateJasperDesign(dr);\n Map<String, Object> params = new HashMap<String, Object>();\n if (!_parameters.isEmpty()) {\n registerParams(jd, _parameters);\n params.putAll(_parameters);\n }\n registerEntities(jd, dr, layoutManager);\n layoutManager.applyLayout(jd, dr);\n JRPropertiesUtil.getInstance(DefaultJasperReportsContext.getInstance()).setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());\n //JRProperties.setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());\n JasperReport jr = JasperCompileManager.compileReport(jd);\n params.putAll(jd.getParametersWithValues());\n jp = JasperFillManager.fillReport(jr, params, con);\n\n return jp;\n }", "private void sendOneAsyncHint(final ByteArray slopKey,\n final Versioned<byte[]> slopVersioned,\n final List<Node> nodesToTry) {\n Node nodeToHostHint = null;\n boolean foundNode = false;\n while(nodesToTry.size() > 0) {\n nodeToHostHint = nodesToTry.remove(0);\n if(!failedNodes.contains(nodeToHostHint) && failureDetector.isAvailable(nodeToHostHint)) {\n foundNode = true;\n break;\n }\n }\n if(!foundNode) {\n Slop slop = slopSerializer.toObject(slopVersioned.getValue());\n logger.error(\"Trying to send an async hint but used up all nodes. key: \"\n + slop.getKey() + \" version: \" + slopVersioned.getVersion().toString());\n return;\n }\n final Node node = nodeToHostHint;\n int nodeId = node.getId();\n\n NonblockingStore nonblockingStore = nonblockingSlopStores.get(nodeId);\n Utils.notNull(nonblockingStore);\n\n final Long startNs = System.nanoTime();\n NonblockingStoreCallback callback = new NonblockingStoreCallback() {\n\n @Override\n public void requestComplete(Object result, long requestTime) {\n Slop slop = null;\n boolean loggerDebugEnabled = logger.isDebugEnabled();\n if(loggerDebugEnabled) {\n slop = slopSerializer.toObject(slopVersioned.getValue());\n }\n Response<ByteArray, Object> response = new Response<ByteArray, Object>(node,\n slopKey,\n result,\n requestTime);\n if(response.getValue() instanceof Exception\n && !(response.getValue() instanceof ObsoleteVersionException)) {\n if(!failedNodes.contains(node))\n failedNodes.add(node);\n if(response.getValue() instanceof UnreachableStoreException) {\n UnreachableStoreException use = (UnreachableStoreException) response.getValue();\n\n if(loggerDebugEnabled) {\n logger.debug(\"Write of key \" + slop.getKey() + \" for \"\n + slop.getNodeId() + \" to node \" + node\n + \" failed due to unreachable: \" + use.getMessage());\n }\n\n failureDetector.recordException(node, (System.nanoTime() - startNs)\n / Time.NS_PER_MS, use);\n }\n sendOneAsyncHint(slopKey, slopVersioned, nodesToTry);\n }\n\n if(loggerDebugEnabled)\n logger.debug(\"Slop write of key \" + slop.getKey() + \" for node \"\n + slop.getNodeId() + \" to node \" + node + \" succeeded in \"\n + (System.nanoTime() - startNs) + \" ns\");\n\n failureDetector.recordSuccess(node, (System.nanoTime() - startNs) / Time.NS_PER_MS);\n\n }\n };\n nonblockingStore.submitPutRequest(slopKey, slopVersioned, null, callback, timeoutMs);\n }", "protected void doPurge(Runnable afterPurgeAction) {\n\n if (LOG.isInfoEnabled()) {\n LOG.info(\n org.opencms.flex.Messages.get().getBundle().key(\n org.opencms.flex.Messages.LOG_FLEXCACHE_WILL_PURGE_JSP_REPOSITORY_0));\n }\n\n File d;\n d = new File(getJspRepository() + CmsFlexCache.REPOSITORY_ONLINE + File.separator);\n CmsFileUtil.purgeDirectory(d);\n\n d = new File(getJspRepository() + CmsFlexCache.REPOSITORY_OFFLINE + File.separator);\n CmsFileUtil.purgeDirectory(d);\n if (afterPurgeAction != null) {\n afterPurgeAction.run();\n }\n\n if (LOG.isInfoEnabled()) {\n LOG.info(\n org.opencms.flex.Messages.get().getBundle().key(\n org.opencms.flex.Messages.LOG_FLEXCACHE_PURGED_JSP_REPOSITORY_0));\n }\n\n }", "public static void createDotStoryFile(String scenarioName,\n String srcTestRootFolder, String packagePath,\n String givenDescription, String whenDescription,\n String thenDescription) throws BeastException {\n String[] folders = packagePath.split(\".\");\n for (String folder : folders) {\n srcTestRootFolder += \"/\" + folder;\n }\n\n FileWriter writer = createFileWriter(createDotStoryName(scenarioName),\n packagePath, srcTestRootFolder);\n try {\n writer.write(\"Scenario: \" + scenarioName + \"\\n\");\n writer.write(\"Given \" + givenDescription + \"\\n\");\n writer.write(\"When \" + whenDescription + \"\\n\");\n writer.write(\"Then \" + thenDescription + \"\\n\");\n writer.close();\n } catch (Exception e) {\n String message = \"Unable to write the .story file for the scenario \"\n + scenarioName;\n logger.severe(message);\n logger.severe(e.getMessage());\n throw new BeastException(message, e);\n }\n }", "public <T extends Widget & Checkable> boolean check(int checkableIndex) {\n List<T> children = getCheckableChildren();\n T checkableWidget = children.get(checkableIndex);\n return checkInternal(checkableWidget, true);\n }", "protected void processDescriptions(List<MonolingualTextValue> descriptions) {\n for(MonolingualTextValue description : descriptions) {\n \tNameWithUpdate currentValue = newDescriptions.get(description.getLanguageCode());\n \t// only mark the description as added if the value we are writing is different from the current one\n \tif (currentValue == null || !currentValue.value.equals(description)) {\n \t\tnewDescriptions.put(description.getLanguageCode(),\n new NameWithUpdate(description, true));\n \t}\n }\n }", "private GenericCriteriaPrompt getPromptValue(FieldType field, byte[] block)\n {\n int textOffset = getPromptOffset(block);\n String value = MPPUtility.getUnicodeString(m_criteriaData, m_criteriaTextStart + textOffset);\n GenericCriteriaPrompt prompt = new GenericCriteriaPrompt(field.getDataType(), value);\n if (m_prompts != null)\n {\n m_prompts.add(prompt);\n }\n return prompt;\n }", "private boolean checkAndSetManifestAndImagePathCandidates(String manifestPath, String candidateImagePath, ArtifactoryDependenciesClient dependenciesClient, TaskListener listener) throws IOException {\n String candidateManifest = getManifestFromArtifactory(dependenciesClient, manifestPath);\n if (candidateManifest == null) {\n return false;\n }\n\n String imageDigest = DockerUtils.getConfigDigest(candidateManifest);\n if (imageDigest.equals(imageId)) {\n manifest = candidateManifest;\n imagePath = candidateImagePath;\n return true;\n }\n\n listener.getLogger().println(String.format(\"Found incorrect manifest.json file in Artifactory in the following path: %s\\nExpecting: %s got: %s\", manifestPath, imageId, imageDigest));\n return false;\n }", "public static double TruncatedPower(double value, double degree) {\r\n double x = Math.pow(value, degree);\r\n return (x > 0) ? x : 0.0;\r\n }" ]
Processes the most recent dump of the sites table to extract information about registered sites. @return a Sites objects that contains the extracted information, or null if no sites dump was available (typically in offline mode without having any previously downloaded sites dumps) @throws IOException if there was a problem accessing the sites table dump or the dump download directory
[ "public Sites getSitesInformation() throws IOException {\n\t\tMwDumpFile sitesTableDump = getMostRecentDump(DumpContentType.SITES);\n\t\tif (sitesTableDump == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Create a suitable processor for such dumps and process the file:\n\t\tMwSitesDumpFileProcessor sitesDumpFileProcessor = new MwSitesDumpFileProcessor();\n\t\tsitesDumpFileProcessor.processDumpFileContents(\n\t\t\t\tsitesTableDump.getDumpFileStream(), sitesTableDump);\n\n\t\treturn sitesDumpFileProcessor.getSites();\n\t}" ]
[ "private void writeCalendar(ProjectCalendar mpxj)\n {\n CalendarType xml = m_factory.createCalendarType();\n m_apibo.getCalendar().add(xml);\n String type = mpxj.getResource() == null ? \"Global\" : \"Resource\";\n\n xml.setBaseCalendarObjectId(getCalendarUniqueID(mpxj.getParent()));\n xml.setIsPersonal(mpxj.getResource() == null ? Boolean.FALSE : Boolean.TRUE);\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setType(type);\n\n StandardWorkWeek xmlStandardWorkWeek = m_factory.createCalendarTypeStandardWorkWeek();\n xml.setStandardWorkWeek(xmlStandardWorkWeek);\n\n for (Day day : EnumSet.allOf(Day.class))\n {\n StandardWorkHours xmlHours = m_factory.createCalendarTypeStandardWorkWeekStandardWorkHours();\n xmlStandardWorkWeek.getStandardWorkHours().add(xmlHours);\n xmlHours.setDayOfWeek(getDayName(day));\n\n for (DateRange range : mpxj.getHours(day))\n {\n WorkTimeType xmlWorkTime = m_factory.createWorkTimeType();\n xmlHours.getWorkTime().add(xmlWorkTime);\n\n xmlWorkTime.setStart(range.getStart());\n xmlWorkTime.setFinish(getEndTime(range.getEnd()));\n }\n }\n\n HolidayOrExceptions xmlExceptions = m_factory.createCalendarTypeHolidayOrExceptions();\n xml.setHolidayOrExceptions(xmlExceptions);\n\n if (!mpxj.getCalendarExceptions().isEmpty())\n {\n Calendar calendar = DateHelper.popCalendar();\n for (ProjectCalendarException mpxjException : mpxj.getCalendarExceptions())\n {\n calendar.setTime(mpxjException.getFromDate());\n while (calendar.getTimeInMillis() < mpxjException.getToDate().getTime())\n {\n HolidayOrException xmlException = m_factory.createCalendarTypeHolidayOrExceptionsHolidayOrException();\n xmlExceptions.getHolidayOrException().add(xmlException);\n\n xmlException.setDate(calendar.getTime());\n\n for (DateRange range : mpxjException)\n {\n WorkTimeType xmlHours = m_factory.createWorkTimeType();\n xmlException.getWorkTime().add(xmlHours);\n\n xmlHours.setStart(range.getStart());\n\n if (range.getEnd() != null)\n {\n xmlHours.setFinish(getEndTime(range.getEnd()));\n }\n }\n calendar.add(Calendar.DAY_OF_YEAR, 1);\n }\n }\n DateHelper.pushCalendar(calendar);\n }\n }", "public void loginAndRedirectBack(Object userIdentifier, String defaultLandingUrl) {\n login(userIdentifier);\n RedirectToLoginUrl.redirectToOriginalUrl(this, defaultLandingUrl);\n }", "PollingState<T> withResponse(Response<ResponseBody> response) {\n this.response = response;\n withPollingUrlFromResponse(response);\n withPollingRetryTimeoutFromResponse(response);\n return this;\n }", "public ImmutableList<CandidateElement> extract(StateVertex currentState)\n\t\t\tthrows CrawljaxException {\n\t\tLinkedList<CandidateElement> results = new LinkedList<>();\n\n\t\tif (!checkedElements.checkCrawlCondition(browser)) {\n\t\t\tLOG.info(\"State {} did not satisfy the CrawlConditions.\", currentState.getName());\n\t\t\treturn ImmutableList.of();\n\t\t}\n\t\tLOG.debug(\"Looking in state: {} for candidate elements\", currentState.getName());\n\n\t\ttry {\n\t\t\tDocument dom = DomUtils.asDocument(browser.getStrippedDomWithoutIframeContent());\n\t\t\textractElements(dom, results, \"\");\n\t\t} catch (IOException e) {\n\t\t\tLOG.error(e.getMessage(), e);\n\t\t\tthrow new CrawljaxException(e);\n\t\t}\n\t\tif (randomizeElementsOrder) {\n\t\t\tCollections.shuffle(results);\n\t\t}\n\t\tcurrentState.setElementsFound(results);\n\t\tLOG.debug(\"Found {} new candidate elements to analyze!\", results.size());\n\t\treturn ImmutableList.copyOf(results);\n\t}", "public void addFile(File file) {\n String name = \"file\";\n files.put(normalizeDuplicateName(name), file);\n }", "public static MethodNode findSAM(ClassNode type) {\n if (!Modifier.isAbstract(type.getModifiers())) return null;\n if (type.isInterface()) {\n List<MethodNode> methods = type.getMethods();\n MethodNode found=null;\n for (MethodNode mi : methods) {\n // ignore methods, that are not abstract and from Object\n if (!Modifier.isAbstract(mi.getModifiers())) continue;\n // ignore trait methods which have a default implementation\n if (Traits.hasDefaultImplementation(mi)) continue;\n if (mi.getDeclaringClass().equals(OBJECT_TYPE)) continue;\n if (OBJECT_TYPE.getDeclaredMethod(mi.getName(), mi.getParameters())!=null) continue;\n\n // we have two methods, so no SAM\n if (found!=null) return null;\n found = mi;\n }\n return found;\n\n } else {\n\n List<MethodNode> methods = type.getAbstractMethods();\n MethodNode found = null;\n if (methods!=null) {\n for (MethodNode mi : methods) {\n if (!hasUsableImplementation(type, mi)) {\n if (found!=null) return null;\n found = mi;\n }\n }\n }\n return found;\n }\n }", "public static CountryList getCountries(Context context) {\n if (mCountries != null) {\n return mCountries;\n }\n mCountries = new CountryList();\n try {\n JSONArray countries = new JSONArray(getJsonFromRaw(context, R.raw.countries));\n for (int i = 0; i < countries.length(); i++) {\n try {\n JSONObject country = (JSONObject) countries.get(i);\n mCountries.add(new Country(country.getString(\"name\"), country.getString(\"iso2\"), country.getInt(\"dialCode\")));\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n return mCountries;\n }", "public double[] getTenors(double moneyness, double maturity) {\r\n\t\tint maturityInMonths\t= (int) Math.round(maturity * 12);\r\n\t\tint[] tenorsInMonths\t= getTenors(convertMoneyness(moneyness), maturityInMonths);\r\n\t\tdouble[] tenors\t\t\t= new double[tenorsInMonths.length];\r\n\r\n\t\tfor(int index = 0; index < tenors.length; index++) {\r\n\t\t\ttenors[index] = convertTenor(maturityInMonths, tenorsInMonths[index]);\r\n\t\t}\r\n\t\treturn tenors;\r\n\t}", "private void readCalendar(Project.Calendars.Calendar calendar, HashMap<BigInteger, ProjectCalendar> map, List<Pair<ProjectCalendar, BigInteger>> baseCalendars)\n {\n ProjectCalendar bc = m_projectFile.addCalendar();\n bc.setUniqueID(NumberHelper.getInteger(calendar.getUID()));\n bc.setName(calendar.getName());\n BigInteger baseCalendarID = calendar.getBaseCalendarUID();\n if (baseCalendarID != null)\n {\n baseCalendars.add(new Pair<ProjectCalendar, BigInteger>(bc, baseCalendarID));\n }\n\n readExceptions(calendar, bc);\n boolean readExceptionsFromDays = bc.getCalendarExceptions().isEmpty();\n\n Project.Calendars.Calendar.WeekDays days = calendar.getWeekDays();\n if (days != null)\n {\n for (Project.Calendars.Calendar.WeekDays.WeekDay weekDay : days.getWeekDay())\n {\n readDay(bc, weekDay, readExceptionsFromDays);\n }\n }\n else\n {\n bc.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n }\n\n readWorkWeeks(calendar, bc);\n\n map.put(calendar.getUID(), bc);\n\n m_eventManager.fireCalendarReadEvent(bc);\n }" ]
Print currency. @param value currency value @return currency value
[ "public static final BigDecimal printCurrency(Number value)\n {\n return (value == null || value.doubleValue() == 0 ? null : new BigDecimal(value.doubleValue() * 100));\n }" ]
[ "private void executeProxyRequest(HttpMethod httpMethodProxyRequest,\n HttpServletRequest httpServletRequest,\n HttpServletResponse httpServletResponse, History history) {\n try {\n RequestInformation requestInfo = requestInformation.get();\n\n // Execute the request\n\n // set virtual host so the server knows how to direct the request\n // If the host header exists then this uses that value\n // Otherwise the hostname from the URL is used\n processVirtualHostName(httpMethodProxyRequest, httpServletRequest);\n cullDisabledPaths();\n\n // check for existence of ODO_PROXY_HEADER\n // finding it indicates a bad loop back through the proxy\n if (httpServletRequest.getHeader(Constants.ODO_PROXY_HEADER) != null) {\n logger.error(\"Request has looped back into the proxy. This will not be executed: {}\", httpServletRequest.getRequestURL());\n return;\n }\n\n // set ODO_PROXY_HEADER\n httpMethodProxyRequest.addRequestHeader(Constants.ODO_PROXY_HEADER, \"proxied\");\n\n requestInfo.blockRequest = hasRequestBlock();\n PluginResponse responseWrapper = new PluginResponse(httpServletResponse);\n requestInfo.jsonpCallback = stripJSONPToOutstr(httpServletRequest, responseWrapper);\n\n if (!requestInfo.blockRequest) {\n logger.info(\"Sending request to server\");\n\n history.setModified(requestInfo.modified);\n history.setRequestSent(true);\n\n executeRequest(httpMethodProxyRequest,\n httpServletRequest,\n responseWrapper,\n history);\n } else {\n history.setRequestSent(false);\n }\n\n logOriginalResponseHistory(responseWrapper, history);\n applyResponseOverrides(responseWrapper, httpServletRequest, httpMethodProxyRequest, history);\n // store history\n history.setModified(requestInfo.modified);\n logRequestHistory(httpMethodProxyRequest, responseWrapper, history);\n\n writeResponseOutput(responseWrapper, requestInfo.jsonpCallback);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }", "private RandomVariable getValueUnderlyingNumeraireRelative(LIBORModelMonteCarloSimulationModel model, Schedule legSchedule, boolean paysFloat, double swaprate, double notional) throws CalculationException {\r\n\t\tRandomVariable value\t= model.getRandomVariableForConstant(0.0);\r\n\r\n\t\tfor(int periodIndex = legSchedule.getNumberOfPeriods() - 1; periodIndex >= 0; periodIndex--) {\r\n\r\n\t\t\tdouble fixingTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getFixing());\r\n\t\t\tdouble paymentTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getPayment());\r\n\t\t\tdouble periodLength\t= legSchedule.getPeriodLength(periodIndex);\r\n\r\n\t\t\tRandomVariable\tnumeraireAtPayment = model.getNumeraire(paymentTime);\r\n\t\t\tRandomVariable\tmonteCarloProbabilitiesAtPayment = model.getMonteCarloWeights(paymentTime);\r\n\t\t\tif(swaprate != 0.0) {\r\n\t\t\t\tRandomVariable periodCashFlowFix = model.getRandomVariableForConstant(swaprate * periodLength * notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment);\r\n\t\t\t\tvalue = value.add(periodCashFlowFix);\r\n\t\t\t}\r\n\t\t\tif(paysFloat) {\r\n\t\t\t\tRandomVariable libor = model.getLIBOR(fixingTime, fixingTime, paymentTime);\r\n\t\t\t\tRandomVariable periodCashFlowFloat = libor.mult(periodLength).mult(notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment);\r\n\t\t\t\tvalue = value.add(periodCashFlowFloat);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn value;\r\n\t}", "@Override\n\tpublic String getFirst(String headerName) {\n\t\tList<String> headerValues = headers.get(headerName);\n\t\treturn headerValues != null ? headerValues.get(0) : null;\n\t}", "public void forAllValuePairs(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = attributes.getProperty(ATTRIBUTE_NAME, \"attributes\");\r\n String defaultValue = attributes.getProperty(ATTRIBUTE_DEFAULT_RIGHT, \"\");\r\n String attributePairs = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), name);\r\n\r\n if ((attributePairs == null) || (attributePairs.length() == 0))\r\n {\r\n return;\r\n }\r\n\r\n String token;\r\n int pos;\r\n\r\n for (CommaListIterator it = new CommaListIterator(attributePairs); it.hasNext();)\r\n {\r\n token = it.getNext();\r\n pos = token.indexOf('=');\r\n if (pos >= 0)\r\n {\r\n _curPairLeft = token.substring(0, pos);\r\n _curPairRight = (pos < token.length() - 1 ? token.substring(pos + 1) : defaultValue);\r\n }\r\n else\r\n {\r\n _curPairLeft = token;\r\n _curPairRight = defaultValue;\r\n }\r\n if (_curPairLeft.length() > 0)\r\n {\r\n generate(template);\r\n }\r\n }\r\n _curPairLeft = null;\r\n _curPairRight = null;\r\n }", "public CollectionRequest<ProjectStatus> findByProject(String project) {\n\n String path = String.format(\"/projects/%s/project_statuses\", project);\n return new CollectionRequest<ProjectStatus>(this, ProjectStatus.class, path, \"GET\");\n }", "public boolean containsIteratorForTable(String aTable)\r\n {\r\n boolean result = false;\r\n\r\n if (m_rsIterators != null)\r\n {\r\n for (int i = 0; i < m_rsIterators.size(); i++)\r\n {\r\n OJBIterator it = (OJBIterator) m_rsIterators.get(i);\r\n if (it instanceof RsIterator)\r\n {\r\n if (((RsIterator) it).getClassDescriptor().getFullTableName().equals(aTable))\r\n {\r\n result = true;\r\n break;\r\n }\r\n }\r\n else if (it instanceof ChainingIterator)\r\n {\r\n result = ((ChainingIterator) it).containsIteratorForTable(aTable);\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n }", "private void sendMessage(Message message) throws IOException {\n logger.debug(\"Sending> {}\", message);\n int totalSize = 0;\n for (Field field : message.fields) {\n totalSize += field.getBytes().remaining();\n }\n ByteBuffer combined = ByteBuffer.allocate(totalSize);\n for (Field field : message.fields) {\n logger.debug(\"..sending> {}\", field);\n combined.put(field.getBytes());\n }\n combined.flip();\n Util.writeFully(combined, channel);\n }", "public void setHtml(String html) {\n this.html = html;\n\n if (widget != null) {\n if (widget.isAttached()) {\n tooltipElement.find(\"span\")\n .html(html != null ? html : \"\");\n } else {\n widget.addAttachHandler(event ->\n tooltipElement.find(\"span\")\n .html(html != null ? html : \"\"));\n }\n } else {\n GWT.log(\"Please initialize the Target widget.\", new IllegalStateException());\n }\n }", "public static XClass getMemberType() throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n return getCurrentField().getType();\r\n }\r\n else if (getCurrentMethod() != null) {\r\n XMethod method = getCurrentMethod();\r\n\r\n if (MethodTagsHandler.isGetterMethod(method)) {\r\n return method.getReturnType().getType();\r\n }\r\n else if (MethodTagsHandler.isSetterMethod(method)) {\r\n XParameter param = (XParameter)method.getParameters().iterator().next();\r\n\r\n return param.getType();\r\n }\r\n }\r\n return null;\r\n }" ]
Determines the field name based on an accessor method name. @param methodName an accessor method name @return the resulting field name
[ "public static String determineFieldName(@Nonnull final String methodName) {\n\t\tCheck.notEmpty(methodName, \"methodName\");\n\t\tfinal Matcher m = PATTERN.matcher(methodName);\n\t\tCheck.stateIsTrue(m.find(), \"passed method name '%s' is not applicable\", methodName);\n\t\treturn m.group(2).substring(0, 1).toLowerCase() + m.group(2).substring(1);\n\t}" ]
[ "public static synchronized ExecutionStatistics get()\n {\n Thread currentThread = Thread.currentThread();\n if (stats.get(currentThread) == null)\n {\n stats.put(currentThread, new ExecutionStatistics());\n }\n return stats.get(currentThread);\n }", "public static snmpmanager[] get(nitro_service service) throws Exception{\n\t\tsnmpmanager obj = new snmpmanager();\n\t\tsnmpmanager[] response = (snmpmanager[])obj.get_resources(service);\n\t\treturn response;\n\t}", "@RequestMapping(value = \"/cert\", method = {RequestMethod.GET, RequestMethod.HEAD})\n public String certPage() throws Exception {\n return \"cert\";\n }", "public static ModelNode addCurrentServerGroupsToHostInfoModel(boolean ignoreUnaffectedServerGroups, Resource hostModel, ModelNode model) {\n if (!ignoreUnaffectedServerGroups) {\n return model;\n }\n model.get(IGNORE_UNUSED_CONFIG).set(ignoreUnaffectedServerGroups);\n addServerGroupsToModel(hostModel, model);\n return model;\n }", "public synchronized void resumeDeployment(final String deployment) {\n for (ControlPoint ep : entryPoints.values()) {\n if (ep.getDeployment().equals(deployment)) {\n ep.resume();\n }\n }\n }", "public Stats getCollectionStats(String collectionId, Date date) throws FlickrException {\n return getStats(METHOD_GET_COLLECTION_STATS, \"collection_id\", collectionId, date);\n }", "public boolean isIPv4Mapped() {\n\t\t//::ffff:x:x/96 indicates IPv6 address mapped to IPv4\n\t\tif(getSegment(5).matches(IPv6Address.MAX_VALUE_PER_SEGMENT)) {\n\t\t\tfor(int i = 0; i < 5; i++) {\n\t\t\t\tif(!getSegment(i).isZero()) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "private void processCalendarDays(ProjectCalendar calendar, Record root)\n {\n // Retrieve working hours ...\n Record daysOfWeek = root.getChild(\"DaysOfWeek\");\n if (daysOfWeek != null)\n {\n for (Record dayRecord : daysOfWeek.getChildren())\n {\n processCalendarHours(calendar, dayRecord);\n }\n }\n }", "public MembersList<Member> getList(String groupId, Set<String> memberTypes, int perPage, int page) throws FlickrException {\r\n MembersList<Member> members = new MembersList<Member>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n\r\n parameters.put(\"group_id\", groupId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n if (memberTypes != null) {\r\n parameters.put(\"membertypes\", StringUtilities.join(memberTypes, \",\"));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element mElement = response.getPayload();\r\n members.setPage(mElement.getAttribute(\"page\"));\r\n members.setPages(mElement.getAttribute(\"pages\"));\r\n members.setPerPage(mElement.getAttribute(\"perpage\"));\r\n members.setTotal(mElement.getAttribute(\"total\"));\r\n\r\n NodeList mNodes = mElement.getElementsByTagName(\"member\");\r\n for (int i = 0; i < mNodes.getLength(); i++) {\r\n Element element = (Element) mNodes.item(i);\r\n members.add(parseMember(element));\r\n }\r\n return members;\r\n }" ]
Visit an open package of the current module. @param packaze the qualified name of the opened package. @param access the access flag of the opened package, valid values are among {@code ACC_SYNTHETIC} and {@code ACC_MANDATED}. @param modules the qualified names of the modules that can use deep reflection to the classes of the open package or <tt>null</tt>.
[ "public void visitOpen(String packaze, int access, String... modules) {\n if (mv != null) {\n mv.visitOpen(packaze, access, modules);\n }\n }" ]
[ "public static boolean decomposeSafe(DecompositionInterface<ZMatrixRMaj> decomposition, ZMatrixRMaj a) {\n\n if( decomposition.inputModified() ) {\n a = a.copy();\n }\n return decomposition.decompose(a);\n }", "@SuppressWarnings(\"WeakerAccess\")\n public synchronized void stop() {\n if (isRunning()) {\n MetadataFinder.getInstance().removeTrackMetadataListener(metadataListener);\n running.set(false);\n pendingUpdates.clear();\n queueHandler.interrupt();\n queueHandler = null;\n\n // Report the loss of our waveforms, on the proper thread, outside our lock\n final Set<DeckReference> dyingPreviewCache = new HashSet<DeckReference>(previewHotCache.keySet());\n previewHotCache.clear();\n final Set<DeckReference> dyingDetailCache = new HashSet<DeckReference>(detailHotCache.keySet());\n detailHotCache.clear();\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (DeckReference deck : dyingPreviewCache) { // Report the loss of our previews.\n if (deck.hotCue == 0) {\n deliverWaveformPreviewUpdate(deck.player, null);\n }\n }\n for (DeckReference deck : dyingDetailCache) { // Report the loss of our details.\n if (deck.hotCue == 0) {\n deliverWaveformDetailUpdate(deck.player, null);\n }\n }\n }\n });\n deliverLifecycleAnnouncement(logger, false);\n }\n }", "private void getMonthlyDates(Calendar calendar, int frequency, List<Date> dates)\n {\n if (m_relative)\n {\n getMonthlyRelativeDates(calendar, frequency, dates);\n }\n else\n {\n getMonthlyAbsoluteDates(calendar, frequency, dates);\n }\n }", "public ItemRequest<Attachment> createOnTask(String task, InputStream fileContent, String fileName, String fileType) {\n MultipartContent.Part part = new MultipartContent.Part()\n .setContent(new InputStreamContent(fileType, fileContent))\n .setHeaders(new HttpHeaders().set(\n \"Content-Disposition\",\n String.format(\"form-data; name=\\\"file\\\"; filename=\\\"%s\\\"\", fileName) // TODO: escape fileName?\n ));\n MultipartContent content = new MultipartContent()\n .setMediaType(new HttpMediaType(\"multipart/form-data\").setParameter(\"boundary\", UUID.randomUUID().toString()))\n .addPart(part);\n\n String path = String.format(\"/tasks/%s/attachments\", task);\n return new ItemRequest<Attachment>(this, Attachment.class, path, \"POST\")\n .data(content);\n }", "@SuppressWarnings(\"unchecked\")\n public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n List<String> metaKeys = null;\n String url = null;\n\n // parse command-line input\n args = AdminToolUtils.copyArrayAddFirst(args, \"--\" + OPT_HEAD_META_CHECK);\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, OPT_HEAD_META_CHECK);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n\n // load parameters\n metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_CHECK);\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n\n\n // execute command\n if(metaKeys.size() == 0\n || (metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL))) {\n metaKeys = Lists.newArrayList();\n metaKeys.add(MetadataStore.CLUSTER_KEY);\n metaKeys.add(MetadataStore.STORES_KEY);\n metaKeys.add(MetadataStore.SERVER_STATE_KEY);\n }\n\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n doMetaCheck(adminClient, metaKeys);\n }", "public void setAttributes(Object feature, Map<String, Attribute> attributes) throws LayerException {\n\t\tfor (Map.Entry<String, Attribute> entry : attributes.entrySet()) {\n\t\t\tString name = entry.getKey();\n\t\t\tif (!name.equals(getGeometryAttributeName())) {\n\t\t\t\tasFeature(feature).setAttribute(name, entry.getValue());\n\t\t\t}\n\t\t}\n\t}", "public static base_response add(nitro_service client, autoscaleprofile resource) throws Exception {\n\t\tautoscaleprofile addresource = new autoscaleprofile();\n\t\taddresource.name = resource.name;\n\t\taddresource.type = resource.type;\n\t\taddresource.url = resource.url;\n\t\taddresource.apikey = resource.apikey;\n\t\taddresource.sharedsecret = resource.sharedsecret;\n\t\treturn addresource.add_resource(client);\n\t}", "public static Map<Integer, Integer> getMapOfContiguousPartitions(final Cluster cluster,\n int zoneId) {\n List<Integer> partitionIds = new ArrayList<Integer>(cluster.getPartitionIdsInZone(zoneId));\n Map<Integer, Integer> partitionIdToRunLength = Maps.newHashMap();\n\n if(partitionIds.isEmpty()) {\n return partitionIdToRunLength;\n }\n\n int lastPartitionId = partitionIds.get(0);\n int initPartitionId = lastPartitionId;\n\n for(int offset = 1; offset < partitionIds.size(); offset++) {\n int partitionId = partitionIds.get(offset);\n if(partitionId == lastPartitionId + 1) {\n lastPartitionId = partitionId;\n continue;\n }\n int runLength = lastPartitionId - initPartitionId + 1;\n\n partitionIdToRunLength.put(initPartitionId, runLength);\n\n initPartitionId = partitionId;\n lastPartitionId = initPartitionId;\n }\n\n int runLength = lastPartitionId - initPartitionId + 1;\n if(lastPartitionId == cluster.getNumberOfPartitions() - 1\n && partitionIdToRunLength.containsKey(0)) {\n // special case of contiguity that wraps around the ring.\n partitionIdToRunLength.put(initPartitionId, runLength + partitionIdToRunLength.get(0));\n partitionIdToRunLength.remove(0);\n } else {\n partitionIdToRunLength.put(initPartitionId, runLength);\n }\n\n return partitionIdToRunLength;\n }", "public void bootstrap() throws Exception {\n final HostRunningModeControl runningModeControl = environment.getRunningModeControl();\n final ControlledProcessState processState = new ControlledProcessState(true);\n shutdownHook.setControlledProcessState(processState);\n ServiceTarget target = serviceContainer.subTarget();\n ControlledProcessStateService controlledProcessStateService = ControlledProcessStateService.addService(target, processState).getValue();\n RunningStateJmx.registerMBean(controlledProcessStateService, null, runningModeControl, false);\n final HostControllerService hcs = new HostControllerService(environment, runningModeControl, authCode, processState);\n target.addService(HostControllerService.HC_SERVICE_NAME, hcs).install();\n }" ]
Sets the content type for this ID @param pathId ID of path @param contentType content type value
[ "public void setContentType(int pathId, String contentType) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_CONTENT_TYPE + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, contentType);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }" ]
[ "public static <T> OptionalValue<T> ofNullable(T value) {\n return new GenericOptionalValue<T>(RUNTIME_SOURCE, DEFAULT_KEY, value);\n }", "protected void handleResponseOut(T message) throws Fault {\n Message reqMsg = message.getExchange().getInMessage();\n if (reqMsg == null) {\n LOG.warning(\"InMessage is null!\");\n return;\n }\n\n // No flowId for oneway message\n Exchange ex = reqMsg.getExchange();\n if (ex.isOneWay()) {\n return;\n }\n\n String reqFid = FlowIdHelper.getFlowId(reqMsg);\n\n // if some interceptor throws fault before FlowIdProducerIn fired\n if (reqFid == null) {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Some interceptor throws fault.Setting FlowId in response.\");\n }\n reqFid = FlowIdProtocolHeaderCodec.readFlowId(message);\n }\n\n // write IN message to SAM repo in case fault\n if (reqFid == null) {\n Message inMsg = ex.getInMessage();\n\n reqFid = FlowIdProtocolHeaderCodec.readFlowId(inMsg);\n if (null != reqFid) {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"FlowId '\" + reqFid\n + \"' found in message of fault incoming exchange.\");\n LOG.fine(\"Calling EventProducerInterceptor to log IN message\");\n }\n handleINEvent(ex, reqFid);\n }\n }\n\n if (reqFid == null) {\n reqFid = FlowIdSoapCodec.readFlowId(message);\n }\n\n if (reqFid != null) {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"FlowId '\" + reqFid + \"' found in incoming message.\");\n }\n } else {\n reqFid = ContextUtils.generateUUID();\n // write IN message to SAM repo in case fault\n if (null != ex.getOutFaultMessage()) {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"FlowId '\" + reqFid\n + \"' generated for fault message.\");\n LOG.fine(\"Calling EventProducerInterceptor to log IN message\");\n }\n handleINEvent(ex, reqFid);\n }\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"No flowId found in incoming message! Generate new flowId \"\n + reqFid);\n }\n }\n\n FlowIdHelper.setFlowId(message, reqFid);\n\n }", "private void userInfoInit() {\n\t\tboolean first = true;\n\t\tuserId = null;\n\t\tuserLocale = null;\n\t\tuserName = null;\n\t\tuserOrganization = null;\n\t\tuserDivision = null;\n\t\tif (null != authentications) {\n\t\t\tfor (Authentication auth : authentications) {\n\t\t\t\tuserId = combine(userId, auth.getUserId());\n\t\t\t\tuserName = combine(userName, auth.getUserName());\n\t\t\t\tif (first) {\n\t\t\t\t\tuserLocale = auth.getUserLocale();\n\t\t\t\t\tfirst = false;\n\t\t\t\t} else {\n\t\t\t\t\tif (null != auth.getUserLocale() &&\n\t\t\t\t\t\t\t(null == userLocale || !userLocale.equals(auth.getUserLocale()))) {\n\t\t\t\t\t\tuserLocale = null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tuserOrganization = combine(userOrganization, auth.getUserOrganization());\n\t\t\t\tuserDivision = combine(userDivision, auth.getUserDivision());\n\t\t\t}\n\t\t}\n\n\t\t// now calculate the \"id\" for this context, this should be independent of the data order, so sort\n\t\tMap<String, List<String>> idParts = new HashMap<String, List<String>>();\n\t\tif (null != authentications) {\n\t\t\tfor (Authentication auth : authentications) {\n\t\t\t\tList<String> auths = new ArrayList<String>();\n\t\t\t\tfor (BaseAuthorization ba : auth.getAuthorizations()) {\n\t\t\t\t\tauths.add(ba.getId());\n\t\t\t\t}\n\t\t\t\tCollections.sort(auths);\n\t\t\t\tidParts.put(auth.getSecurityServiceId(), auths);\n\t\t\t}\n\t\t}\n\t\tStringBuilder sb = new StringBuilder();\n\t\tList<String> sortedKeys = new ArrayList<String>(idParts.keySet());\n\t\tCollections.sort(sortedKeys);\n\t\tfor (String key : sortedKeys) {\n\t\t\tif (sb.length() > 0) {\n\t\t\t\tsb.append('|');\n\t\t\t}\n\t\t\tList<String> auths = idParts.get(key);\n\t\t\tfirst = true;\n\t\t\tfor (String ak : auths) {\n\t\t\t\tif (first) {\n\t\t\t\t\tfirst = false;\n\t\t\t\t} else {\n\t\t\t\t\tsb.append('|');\n\t\t\t\t}\n\t\t\t\tsb.append(ak);\n\t\t\t}\n\t\t\tsb.append('@');\n\t\t\tsb.append(key);\n\t\t}\n\t\tid = sb.toString();\n\t}", "protected void rehash(int newCapacity) {\r\n\tint oldCapacity = table.length;\r\n\t//if (oldCapacity == newCapacity) return;\r\n\t\r\n\tlong oldTable[] = table;\r\n\tint oldValues[] = values;\r\n\tbyte oldState[] = state;\r\n\r\n\tlong newTable[] = new long[newCapacity];\r\n\tint newValues[] = new int[newCapacity];\r\n\tbyte newState[] = new byte[newCapacity];\r\n\r\n\tthis.lowWaterMark = chooseLowWaterMark(newCapacity,this.minLoadFactor);\r\n\tthis.highWaterMark = chooseHighWaterMark(newCapacity,this.maxLoadFactor);\r\n\r\n\tthis.table = newTable;\r\n\tthis.values = newValues;\r\n\tthis.state = newState;\r\n\tthis.freeEntries = newCapacity-this.distinct; // delta\r\n\t\r\n\tfor (int i = oldCapacity ; i-- > 0 ;) {\r\n\t\tif (oldState[i]==FULL) {\r\n\t\t\tlong element = oldTable[i];\r\n\t\t\tint index = indexOfInsertion(element);\r\n\t\t\tnewTable[index]=element;\r\n\t\t\tnewValues[index]=oldValues[i];\r\n\t\t\tnewState[index]=FULL;\r\n\t\t}\r\n\t}\r\n}", "public static License createLicense(final String name, final String longName, final String comments, final String regexp, final String url){\n\t\tfinal License license = new License();\n\n\t\tlicense.setName(name);\n\t\tlicense.setLongName(longName);\n\t\tlicense.setComments(comments);\n\t\tlicense.setRegexp(regexp);\n\t\tlicense.setUrl(url);\n\n\t\treturn license;\n\t}", "private AssignmentField selectField(AssignmentField[] fields, int index)\n {\n if (index < 1 || index > fields.length)\n {\n throw new IllegalArgumentException(index + \" is not a valid field index\");\n }\n return (fields[index - 1]);\n }", "private ProjectFile handleOleCompoundDocument(InputStream stream) throws Exception\n {\n POIFSFileSystem fs = new POIFSFileSystem(POIFSFileSystem.createNonClosingInputStream(stream));\n String fileFormat = MPPReader.getFileFormat(fs);\n if (fileFormat != null && fileFormat.startsWith(\"MSProject\"))\n {\n MPPReader reader = new MPPReader();\n addListeners(reader);\n return reader.read(fs);\n }\n return null;\n }", "private void lockDescriptor() throws CmsException {\n\n if ((null == m_descFile) && (null != m_desc)) {\n m_descFile = LockedFile.lockResource(m_cms, m_desc);\n }\n }", "public ItemRequest<Project> removeFollowers(String project) {\n \n String path = String.format(\"/projects/%s/removeFollowers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }" ]
Set the InputStream of request body data, of known length, to be sent to the server. @param input InputStream of request body data to be sent to the server @param inputLength Length of request body data to be sent to the server, in bytes @return an {@link HttpConnection} for method chaining @deprecated Use {@link #setRequestBody(InputStreamGenerator, long)}
[ "public HttpConnection setRequestBody(final InputStream input, final long inputLength) {\n try {\n return setRequestBody(new InputStreamWrappingGenerator(input, inputLength),\n inputLength);\n } catch (IOException e) {\n logger.log(Level.SEVERE, \"Error copying input stream for request body\", e);\n throw new RuntimeException(e);\n }\n }" ]
[ "public static void acceptsUrlMultiple(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), \"coordinator bootstrap urls\")\n .withRequiredArg()\n .describedAs(\"url-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }", "private void installFastProcessAnnotatedTypeResolver(ServiceRegistry services) {\n ClassFileServices classFileServices = services.get(ClassFileServices.class);\n if (classFileServices != null) {\n final GlobalObserverNotifierService observers = services.get(GlobalObserverNotifierService.class);\n try {\n final FastProcessAnnotatedTypeResolver resolver = new FastProcessAnnotatedTypeResolver(observers.getAllObserverMethods());\n services.add(FastProcessAnnotatedTypeResolver.class, resolver);\n } catch (UnsupportedObserverMethodException e) {\n BootstrapLogger.LOG.notUsingFastResolver(e.getObserver());\n return;\n }\n }\n }", "private static Class<?> extractTypeFromClass(Class<?> clazz, Class<?> source, int typeIndex,\n\t\t\tMap<TypeVariable, Type> typeVariableMap, Map<Integer, Integer> typeIndexesPerLevel,\n\t\t\tint nestingLevel, int currentLevel) {\n\n\t\tif (clazz.getName().startsWith(\"java.util.\")) {\n\t\t\treturn null;\n\t\t}\n\t\tif (clazz.getSuperclass() != null && isIntrospectionCandidate(clazz.getSuperclass())) {\n\t\t\ttry {\n\t\t\t\treturn extractType(clazz.getGenericSuperclass(), source, typeIndex, typeVariableMap,\n\t\t\t\t\t\ttypeIndexesPerLevel, nestingLevel, currentLevel);\n\t\t\t}\n\t\t\tcatch (MalformedParameterizedTypeException ex) {\n\t\t\t\t// from getGenericSuperclass() - ignore and continue with interface introspection\n\t\t\t}\n\t\t}\n\t\tType[] ifcs = clazz.getGenericInterfaces();\n\t\tif (ifcs != null) {\n\t\t\tfor (Type ifc : ifcs) {\n\t\t\t\tType rawType = ifc;\n\t\t\t\tif (ifc instanceof ParameterizedType) {\n\t\t\t\t\trawType = ((ParameterizedType) ifc).getRawType();\n\t\t\t\t}\n\t\t\t\tif (rawType instanceof Class && isIntrospectionCandidate((Class) rawType)) {\n\t\t\t\t\treturn extractType(ifc, source, typeIndex, typeVariableMap, typeIndexesPerLevel, nestingLevel, currentLevel);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "public String expand(String macro) {\n if (!isMacro(macro)) {\n return macro;\n }\n String definition = macros.get(Config.canonical(macro));\n if (null == definition) {\n warn(\"possible missing definition of macro[%s]\", macro);\n }\n return null == definition ? macro : definition;\n }", "public static Multimap<String, String> convertToMultiMap(final PObject objectParams) {\n Multimap<String, String> params = HashMultimap.create();\n if (objectParams != null) {\n Iterator<String> customParamsIter = objectParams.keys();\n while (customParamsIter.hasNext()) {\n String key = customParamsIter.next();\n if (objectParams.isArray(key)) {\n final PArray array = objectParams.optArray(key);\n for (int i = 0; i < array.size(); i++) {\n params.put(key, array.getString(i));\n }\n } else {\n params.put(key, objectParams.optString(key, \"\"));\n }\n }\n }\n\n return params;\n }", "public static String capitalizePropertyName(String s) {\r\n\t\tif (s.length() == 0) {\r\n\t\t\treturn s;\r\n\t\t}\r\n\r\n\t\tchar[] chars = s.toCharArray();\r\n\t\tchars[0] = Character.toUpperCase(chars[0]);\r\n\t\treturn new String(chars);\r\n\t}", "public String getShortMessage(Locale locale) {\n\t\tString message;\n\t\tmessage = translate(Integer.toString(exceptionCode), locale);\n\t\tif (message != null && msgParameters != null && msgParameters.length > 0) {\n\t\t\tfor (int i = 0; i < msgParameters.length; i++) {\n\t\t\t\tboolean isIncluded = false;\n\t\t\t\tString needTranslationParam = \"$${\" + i + \"}\";\n\t\t\t\tif (message.contains(needTranslationParam)) {\n\t\t\t\t\tString translation = translate(msgParameters[i], locale);\n\t\t\t\t\tif (null == translation && null != msgParameters[i]) {\n\t\t\t\t\t\ttranslation = msgParameters[i].toString();\n\t\t\t\t\t}\n\t\t\t\t\tif (null == translation) {\n\t\t\t\t\t\ttranslation = \"[null]\";\n\t\t\t\t\t}\n\t\t\t\t\tmessage = message.replace(needTranslationParam, translation);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tString verbatimParam = \"${\" + i + \"}\";\n\t\t\t\tString rs = null == msgParameters[i] ? \"[null]\" : msgParameters[i].toString();\n\t\t\t\tif (message.contains(verbatimParam)) {\n\t\t\t\t\tmessage = message.replace(verbatimParam, rs);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tif (!isIncluded) {\n\t\t\t\t\tmessage = message + \" (\" + rs + \")\"; // NOSONAR replace/contains makes StringBuilder use difficult\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn message;\n\t}", "private void processGraphicalIndicators()\n {\n GraphicalIndicatorReader graphicalIndicatorReader = new GraphicalIndicatorReader();\n graphicalIndicatorReader.process(m_file.getCustomFields(), m_file.getProjectProperties(), m_projectProps);\n }", "public static cachepolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tcachepolicylabel_binding obj = new cachepolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcachepolicylabel_binding response = (cachepolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
This produces the dotted hexadecimal format aaaa.bbbb.cccc
[ "public String toDottedString() {\r\n\t\tString result = null;\r\n\t\tif(hasNoStringCache() || (result = getStringCache().dottedString) == null) {\r\n\t\t\tAddressDivisionGrouping dottedGrouping = getDottedGrouping();\r\n\t\t\tgetStringCache().dottedString = result = toNormalizedString(MACStringCache.dottedParams, dottedGrouping);\r\n\t\t}\r\n\t\treturn result;\r\n\t}" ]
[ "public static List<Dependency> getCorporateDependencies(final Module module, final List<String> corporateFilters) {\n final List<Dependency> corporateDependencies = new ArrayList<Dependency>();\n final Pattern corporatePattern = generateCorporatePattern(corporateFilters);\n\n for(final Dependency dependency: getAllDependencies(module)){\n if(dependency.getTarget().getGavc().matches(corporatePattern.pattern())){\n corporateDependencies.add(dependency);\n }\n }\n\n return corporateDependencies;\n }", "private void readCalendars(Storepoint phoenixProject)\n {\n Calendars calendars = phoenixProject.getCalendars();\n if (calendars != null)\n {\n for (Calendar calendar : calendars.getCalendar())\n {\n readCalendar(calendar);\n }\n\n ProjectCalendar defaultCalendar = m_projectFile.getCalendarByName(phoenixProject.getDefaultCalendar());\n if (defaultCalendar != null)\n {\n m_projectFile.getProjectProperties().setDefaultCalendarName(defaultCalendar.getName());\n }\n }\n }", "public Collection<EmailAlias> getEmailAliases() {\n URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n Collection<EmailAlias> emailAliases = new ArrayList<EmailAlias>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject emailAliasJSON = value.asObject();\n emailAliases.add(new EmailAlias(emailAliasJSON));\n }\n\n return emailAliases;\n }", "public static HashMap<String, String> getParameters(String query) {\n HashMap<String, String> params = new HashMap<String, String>();\n if (query == null || query.length() == 0) {\n return params;\n }\n\n String[] splitQuery = query.split(\"&\");\n for (String splitItem : splitQuery) {\n String[] items = splitItem.split(\"=\");\n\n if (items.length == 1) {\n params.put(items[0], \"\");\n } else {\n params.put(items[0], items[1]);\n }\n }\n\n return params;\n }", "@Override\n protected StatisticsMatrix createMatrix(int numRows, int numCols, MatrixType type) {\n return new StatisticsMatrix(numRows,numCols);\n }", "public static UpdateDescription fromBsonDocument(final BsonDocument document) {\n keyPresent(Fields.UPDATED_FIELDS_FIELD, document);\n keyPresent(Fields.REMOVED_FIELDS_FIELD, document);\n\n final BsonArray removedFieldsArr =\n document.getArray(Fields.REMOVED_FIELDS_FIELD);\n final Set<String> removedFields = new HashSet<>(removedFieldsArr.size());\n for (final BsonValue field : removedFieldsArr) {\n removedFields.add(field.asString().getValue());\n }\n\n return new UpdateDescription(document.getDocument(Fields.UPDATED_FIELDS_FIELD), removedFields);\n }", "private TestSuiteModel buildModel(AggregatedSuiteResultEvent e) throws IOException {\n SimpleDateFormat df = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss\", Locale.ROOT);\n TestSuiteModel suite = new TestSuiteModel();\n\n suite.hostname = \"nohost.nodomain\";\n suite.name = e.getDescription().getDisplayName();\n suite.properties = buildModel(e.getSlave().getSystemProperties());\n suite.time = e.getExecutionTime() / 1000.0;\n suite.timestamp = df.format(new Date(e.getStartTimestamp()));\n\n suite.testcases = buildModel(e.getTests());\n suite.tests = suite.testcases.size();\n\n if (mavenExtensions) {\n suite.skipped = 0;\n }\n\n // Suite-level failures and errors are simulated as test cases.\n for (FailureMirror m : e.getFailures()) {\n TestCaseModel model = new TestCaseModel();\n model.classname = \"junit.framework.TestSuite\"; // empirical ANT output.\n model.name = applyFilters(m.getDescription().getClassName());\n model.time = 0;\n if (m.isAssertionViolation()) {\n model.failures.add(buildModel(m));\n } else {\n model.errors.add(buildModel(m));\n }\n suite.testcases.add(model);\n }\n\n // Calculate test numbers that match limited view (no ignored tests, \n // faked suite-level errors).\n for (TestCaseModel tc : suite.testcases) {\n suite.errors += tc.errors.size();\n suite.failures += tc.failures.size();\n if (mavenExtensions && tc.skipped != null) {\n suite.skipped += 1;\n }\n }\n\n StringWriter sysout = new StringWriter();\n StringWriter syserr = new StringWriter();\n if (outputStreams) {\n e.getSlave().decodeStreams(e.getEventStream(), sysout, syserr);\n }\n suite.sysout = sysout.toString();\n suite.syserr = syserr.toString();\n\n return suite;\n }", "public void putInWakeUpQueue(SerialMessage serialMessage) {\r\n\t\tif (this.wakeUpQueue.contains(serialMessage)) {\r\n\t\t\tlogger.debug(\"Message already on the wake-up queue for node {}. Discarding.\", this.getNode().getNodeId());\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\t\r\n\t\tlogger.debug(\"Putting message in wakeup queue for node {}.\", this.getNode().getNodeId());\r\n\t\tthis.wakeUpQueue.add(serialMessage);\r\n\t}", "@Override\n public Response toResponse(ErrorDto e)\n {\n // String type = headers.getContentType() == null ? MediaType.APPLICATION_JSON : headers.getContentType();\n return Response.status(e.httpStatus).entity(e).type(MediaType.APPLICATION_JSON).build();\n }" ]
Prepare a parallel HTTP OPTION Task. @param url the UrlPostfix: e.g. in http://localhost:8080/index.html.,the url is "/index.html" @return the parallel task builder
[ "public ParallelTaskBuilder prepareHttpOptions(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.OPTIONS);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n\n }" ]
[ "public URL buildWithQuery(String base, String queryString, Object... values) {\n String urlString = String.format(base + this.template, values) + queryString;\n URL url = null;\n try {\n url = new URL(urlString);\n } catch (MalformedURLException e) {\n assert false : \"An invalid URL template indicates a bug in the SDK.\";\n }\n\n return url;\n }", "public static authenticationtacacspolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationtacacspolicy_systemglobal_binding obj = new authenticationtacacspolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationtacacspolicy_systemglobal_binding response[] = (authenticationtacacspolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public Collection<HazeltaskTask<GROUP>> call() throws Exception {\n try {\n if(isShutdownNow)\n return this.getDistributedExecutorService().shutdownNowWithHazeltask();\n else\n this.getDistributedExecutorService().shutdown();\n } catch(IllegalStateException e) {}\n \n return Collections.emptyList();\n }", "@Subscribe\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n long millis = e.getExecutionTime();\n String suiteName = e.getDescription().getDisplayName();\n \n List<Long> values = hints.get(suiteName);\n if (values == null) {\n hints.put(suiteName, values = new ArrayList<>());\n }\n values.add(millis);\n while (values.size() > historyLength)\n values.remove(0);\n }", "public static void setTime(Calendar cal, Date time)\n {\n if (time != null)\n {\n Calendar startCalendar = popCalendar(time);\n cal.set(Calendar.HOUR_OF_DAY, startCalendar.get(Calendar.HOUR_OF_DAY));\n cal.set(Calendar.MINUTE, startCalendar.get(Calendar.MINUTE));\n cal.set(Calendar.SECOND, startCalendar.get(Calendar.SECOND));\n pushCalendar(startCalendar);\n }\n }", "public void setDialect(String dialect) {\n String[] scripts = createScripts.get(dialect);\n createSql = scripts[0];\n createSqlInd = scripts[1];\n }", "@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n public void blacklistNode(int nodeId) {\n Collection<Node> nodesInCluster = adminClient.getAdminClientCluster().getNodes();\n\n if(blackListedNodes == null) {\n blackListedNodes = new ArrayList();\n }\n blackListedNodes.add(nodeId);\n\n for(Node node: nodesInCluster) {\n\n if(node.getId() == nodeId) {\n nodesToStream.remove(node);\n break;\n }\n\n }\n\n for(String store: storeNames) {\n try {\n SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store, nodeId));\n close(sands.getSocket());\n SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store,\n nodeId));\n streamingSocketPool.checkin(destination, sands);\n } catch(Exception ioE) {\n logger.error(ioE);\n }\n }\n }", "protected void recycleChildren() {\n for (ListItemHostWidget host: getAllHosts()) {\n recycle(host);\n }\n mContent.onTransformChanged();\n mContent.requestLayout();\n }", "public String userAgent() {\n return String.format(\"Azure-SDK-For-Java/%s OS:%s MacAddressHash:%s Java:%s\",\n getClass().getPackage().getImplementationVersion(),\n OS,\n MAC_ADDRESS_HASH,\n JAVA_VERSION);\n }" ]
Adds all categories from one resource to another, skipping categories that are not available for the resource copied to. The resource where categories are copied to has to be locked. @param cms the CmsObject used for reading and writing. @param fromResource the resource to copy the categories from. @param toResourceSitePath the full site path of the resource to copy the categories to. @throws CmsException thrown if copying the resources fails.
[ "public void copyCategories(CmsObject cms, CmsResource fromResource, String toResourceSitePath) throws CmsException {\n\n List<CmsCategory> categories = readResourceCategories(cms, fromResource);\n for (CmsCategory category : categories) {\n addResourceToCategory(cms, toResourceSitePath, category);\n }\n }" ]
[ "public static vlan[] get(nitro_service service) throws Exception{\n\t\tvlan obj = new vlan();\n\t\tvlan[] response = (vlan[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public BoxFile.Info getFileInfo(String fileID, String... fields) {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", fields).toString();\n URL url = FILE_INFO_URL_TEMPLATE.buildWithQuery(this.api.getBaseURL(), queryString, fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFile file = new BoxFile(this.api, jsonObject.get(\"id\").asString());\n return file.new Info(response.getJSON());\n }", "public static base_response update(nitro_service client, cmpparameter resource) throws Exception {\n\t\tcmpparameter updateresource = new cmpparameter();\n\t\tupdateresource.cmplevel = resource.cmplevel;\n\t\tupdateresource.quantumsize = resource.quantumsize;\n\t\tupdateresource.servercmp = resource.servercmp;\n\t\tupdateresource.heurexpiry = resource.heurexpiry;\n\t\tupdateresource.heurexpirythres = resource.heurexpirythres;\n\t\tupdateresource.heurexpiryhistwt = resource.heurexpiryhistwt;\n\t\tupdateresource.minressize = resource.minressize;\n\t\tupdateresource.cmpbypasspct = resource.cmpbypasspct;\n\t\tupdateresource.cmponpush = resource.cmponpush;\n\t\tupdateresource.policytype = resource.policytype;\n\t\tupdateresource.addvaryheader = resource.addvaryheader;\n\t\tupdateresource.externalcache = resource.externalcache;\n\t\treturn updateresource.update_resource(client);\n\t}", "void releaseTransaction(@NotNull final Thread thread, final int permits) {\n try (CriticalSection ignored = criticalSection.enter()) {\n int currentThreadPermits = getThreadPermits(thread);\n if (permits > currentThreadPermits) {\n throw new ExodusException(\"Can't release more permits than it was acquired\");\n }\n acquiredPermits -= permits;\n currentThreadPermits -= permits;\n if (currentThreadPermits == 0) {\n threadPermits.remove(thread);\n } else {\n threadPermits.put(thread, currentThreadPermits);\n }\n notifyNextWaiters();\n }\n }", "public void removePrefetchingListeners()\r\n {\r\n if (prefetchingListeners != null)\r\n {\r\n for (Iterator it = prefetchingListeners.iterator(); it.hasNext(); )\r\n {\r\n PBPrefetchingListener listener = (PBPrefetchingListener) it.next();\r\n listener.removeThisListener();\r\n }\r\n prefetchingListeners.clear();\r\n }\r\n }", "public Iterator getAllBaseTypes()\r\n {\r\n ArrayList baseTypes = new ArrayList();\r\n\r\n baseTypes.addAll(_directBaseTypes.values());\r\n\r\n for (int idx = baseTypes.size() - 1; idx >= 0; idx--)\r\n {\r\n ClassDescriptorDef curClassDef = (ClassDescriptorDef)baseTypes.get(idx);\r\n\r\n for (Iterator it = curClassDef.getDirectBaseTypes(); it.hasNext();)\r\n {\r\n ClassDescriptorDef curBaseTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n if (!baseTypes.contains(curBaseTypeDef))\r\n {\r\n baseTypes.add(0, curBaseTypeDef);\r\n idx++;\r\n }\r\n }\r\n }\r\n return baseTypes.iterator();\r\n }", "public Story storyOfText(Configuration configuration, String storyAsText, String storyId) {\n return configuration.storyParser().parseStory(storyAsText, storyId);\n }", "private Class getDynamicProxyClass(Class baseClass) {\r\n Class[] m_dynamicProxyClassInterfaces;\r\n if (foundInterfaces.containsKey(baseClass)) {\r\n m_dynamicProxyClassInterfaces = (Class[])foundInterfaces.get(baseClass);\r\n } else {\r\n m_dynamicProxyClassInterfaces = getInterfaces(baseClass);\r\n foundInterfaces.put(baseClass, m_dynamicProxyClassInterfaces);\r\n }\r\n\r\n // return dynymic Proxy Class implementing all interfaces\r\n Class proxyClazz = Proxy.getProxyClass(baseClass.getClassLoader(), m_dynamicProxyClassInterfaces);\r\n return proxyClazz;\r\n }", "public static String readStringFromUrlGeneric(String url)\n throws IOException {\n InputStream is = null;\n URL urlObj = null;\n String responseString = PcConstants.NA;\n try {\n urlObj = new URL(url);\n URLConnection con = urlObj.openConnection();\n\n con.setConnectTimeout(ParallecGlobalConfig.urlConnectionConnectTimeoutMillis);\n con.setReadTimeout(ParallecGlobalConfig.urlConnectionReadTimeoutMillis);\n is = con.getInputStream();\n\n BufferedReader rd = new BufferedReader(new InputStreamReader(is,\n Charset.forName(\"UTF-8\")));\n responseString = PcFileNetworkIoUtils.readAll(rd);\n\n } finally {\n\n if (is != null) {\n is.close();\n }\n\n }\n\n return responseString;\n }" ]
Read correlation id. @param message the message @return correlation id from the message
[ "public static String readCorrelationId(Message message) {\n if (!(message instanceof SoapMessage)) {\n return null;\n }\n String correlationId = null;\n Header hdCorrelationId = ((SoapMessage) message).getHeader(CORRELATION_ID_QNAME);\n if (hdCorrelationId != null) {\n if (hdCorrelationId.getObject() instanceof String) {\n correlationId = (String) hdCorrelationId.getObject();\n } else if (hdCorrelationId.getObject() instanceof Node) {\n Node headerNode = (Node) hdCorrelationId.getObject();\n correlationId = headerNode.getTextContent();\n } else {\n LOG.warning(\"Found CorrelationId soap header but value is not a String or a Node! Value: \"\n + hdCorrelationId.getObject().toString());\n }\n }\n return correlationId;\n }" ]
[ "public static int getPercentage(String percentage) {\n if (isNotEmpty(percentage) && isNumeric(percentage)) {\n int p = Integer.parseInt(percentage);\n return p;\n } else {\n return 0;\n }\n }", "public void diffUpdate(List<T> newList) {\n if (getCollection().size() == 0) {\n addAll(newList);\n notifyDataSetChanged();\n } else {\n DiffCallback diffCallback = new DiffCallback(collection, newList);\n DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);\n clear();\n addAll(newList);\n diffResult.dispatchUpdatesTo(this);\n }\n }", "public int getFixedDataOffset(FieldType type)\n {\n int result;\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getFixedDataOffset();\n }\n else\n {\n result = -1;\n }\n return result;\n }", "private FilePath copyClassWorldsFile(FilePath ws, URL resource) {\n try {\n FilePath remoteClassworlds =\n ws.createTextTempFile(\"classworlds\", \"conf\", \"\");\n remoteClassworlds.copyFrom(resource);\n return remoteClassworlds;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "public void setBody(String body) {\n byte[] bytes = body.getBytes(StandardCharsets.UTF_8);\n this.bodyLength = bytes.length;\n this.body = new ByteArrayInputStream(bytes);\n }", "@SuppressWarnings({\"OverlyLongMethod\"})\n public void clearProperties(@NotNull final PersistentStoreTransaction txn, @NotNull final Entity entity) {\n final Transaction envTxn = txn.getEnvironmentTransaction();\n final PersistentEntityId id = (PersistentEntityId) entity.getId();\n final int entityTypeId = id.getTypeId();\n final long entityLocalId = id.getLocalId();\n final PropertiesTable properties = getPropertiesTable(txn, entityTypeId);\n final PropertyKey propertyKey = new PropertyKey(entityLocalId, 0);\n try (Cursor cursor = getPrimaryPropertyIndexCursor(txn, properties)) {\n for (boolean success = cursor.getSearchKeyRange(PropertyKey.propertyKeyToEntry(propertyKey)) != null;\n success; success = cursor.getNext()) {\n ByteIterable keyEntry = cursor.getKey();\n final PropertyKey key = PropertyKey.entryToPropertyKey(keyEntry);\n if (key.getEntityLocalId() != entityLocalId) {\n break;\n }\n final int propertyId = key.getPropertyId();\n final ByteIterable value = cursor.getValue();\n final PropertyValue propValue = propertyTypes.entryToPropertyValue(value);\n txn.propertyChanged(id, propertyId, propValue.getData(), null);\n properties.deleteNoFail(txn, entityLocalId, value, propertyId, propValue.getType());\n }\n }\n }", "@Deprecated\n public static <T> ServiceBuilder<T> addServerExecutorDependency(ServiceBuilder<T> builder, Injector<ExecutorService> injector) {\n return builder.addDependency(ServerService.MANAGEMENT_EXECUTOR, ExecutorService.class, injector);\n }", "public RedwoodConfiguration neatExit(){\r\n tasks.add(new Runnable() { public void run() {\r\n Runtime.getRuntime().addShutdownHook(new Thread(){\r\n @Override public void run(){ Redwood.stop(); }\r\n });\r\n }});\r\n return this;\r\n }", "protected final void hardcodeValidCopyMethod(Class<?> fieldType, String fullyQualifiedMethodName, Class<?> argType) {\r\n if (argType==null || fieldType==null || fullyQualifiedMethodName==null) {\r\n throw new IllegalArgumentException(\"All parameters must be supplied - no nulls\");\r\n }\r\n String className = fullyQualifiedMethodName.substring(0, fullyQualifiedMethodName.lastIndexOf(\".\"));\r\n String methodName = fullyQualifiedMethodName.substring(fullyQualifiedMethodName.lastIndexOf(\".\")+1);\r\n\r\n \r\n String desc = null;\r\n try {\r\n if (MethodIs.aConstructor(methodName)) {\r\n Constructor<?> ctor = Class.forName(className).getDeclaredConstructor(argType);\r\n desc = Type.getConstructorDescriptor(ctor);\r\n } else {\r\n Method method = Class.forName(className).getMethod(methodName, argType);\r\n desc = Type.getMethodDescriptor(method);\r\n }\r\n } catch (NoSuchMethodException e) {\r\n rethrow(\"No such method\", e);\r\n } catch (SecurityException e) {\r\n rethrow(\"Security error\", e);\r\n } catch (ClassNotFoundException e) {\r\n rethrow(\"Class not found\", e);\r\n }\r\n CopyMethod copyMethod = new CopyMethod(dotted(className), methodName, desc);\r\n hardcodeValidCopyMethod(fieldType, copyMethod);\r\n }" ]
The read timeout for the underlying URLConnection to the twitter stream.
[ "public void setReadTimeout(int millis) {\n\t\t// Hack to get round Spring's dynamic loading of http client stuff\n\t\tClientHttpRequestFactory f = getRequestFactory();\n\t\tif (f instanceof SimpleClientHttpRequestFactory) {\n\t\t\t((SimpleClientHttpRequestFactory) f).setReadTimeout(millis);\n\t\t}\n\t\telse {\n\t\t\t((HttpComponentsClientHttpRequestFactory) f).setReadTimeout(millis);\n\t\t}\n\t}" ]
[ "void writeSomeValueRestriction(String propertyUri, String rangeUri,\n\t\t\tResource bnode) throws RDFHandlerException {\n\t\tthis.rdfWriter.writeTripleValueObject(bnode, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.OWL_RESTRICTION);\n\t\tthis.rdfWriter.writeTripleUriObject(bnode, RdfWriter.OWL_ON_PROPERTY,\n\t\t\t\tpropertyUri);\n\t\tthis.rdfWriter.writeTripleUriObject(bnode,\n\t\t\t\tRdfWriter.OWL_SOME_VALUES_FROM, rangeUri);\n\t}", "public void stopDrag() {\n mPhysicsDragger.stopDrag();\n\n mPhysicsContext.runOnPhysicsThread(new Runnable() {\n @Override\n public void run() {\n if (mRigidBodyDragMe != null) {\n NativePhysics3DWorld.stopDrag(getNative());\n mRigidBodyDragMe = null;\n }\n }\n });\n }", "private List<TimephasedCost> getTimephasedActualCostFixedAmount()\n {\n List<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n double actualCost = getActualCost().doubleValue();\n\n if (actualCost > 0)\n {\n AccrueType accrueAt = getResource().getAccrueAt();\n\n if (accrueAt == AccrueType.START)\n {\n result.add(splitCostStart(getCalendar(), actualCost, getActualStart()));\n }\n else\n if (accrueAt == AccrueType.END)\n {\n result.add(splitCostEnd(getCalendar(), actualCost, getActualFinish()));\n }\n else\n {\n //for prorated, we have to deal with it differently; have to 'fill up' each\n //day with the standard amount before going to the next one\n double numWorkingDays = getCalendar().getWork(getStart(), getFinish(), TimeUnit.DAYS).getDuration();\n double standardAmountPerDay = getCost().doubleValue() / numWorkingDays;\n\n result.addAll(splitCostProrated(getCalendar(), actualCost, standardAmountPerDay, getActualStart()));\n }\n }\n\n return result;\n }", "private void readProject(Project project)\n {\n Task mpxjTask = m_projectFile.addTask();\n //project.getAuthor()\n mpxjTask.setBaselineCost(project.getBaselineCost());\n mpxjTask.setBaselineFinish(project.getBaselineFinishDate());\n mpxjTask.setBaselineStart(project.getBaselineStartDate());\n //project.getBudget();\n //project.getCompany()\n mpxjTask.setFinish(project.getFinishDate());\n //project.getGoal()\n //project.getHyperlinks()\n //project.getMarkerID()\n mpxjTask.setName(project.getName());\n mpxjTask.setNotes(project.getNote());\n mpxjTask.setPriority(project.getPriority());\n // project.getSite()\n mpxjTask.setStart(project.getStartDate());\n // project.getStyleProject()\n // project.getTask()\n // project.getTimeScale()\n // project.getViewProperties()\n\n String projectIdentifier = project.getID().toString();\n mpxjTask.setGUID(UUID.nameUUIDFromBytes(projectIdentifier.getBytes()));\n\n //\n // Sort the tasks into the correct order\n //\n List<Document.Projects.Project.Task> tasks = new ArrayList<Document.Projects.Project.Task>(project.getTask());\n final AlphanumComparator comparator = new AlphanumComparator();\n\n Collections.sort(tasks, new Comparator<Document.Projects.Project.Task>()\n {\n @Override public int compare(Document.Projects.Project.Task o1, Document.Projects.Project.Task o2)\n {\n return comparator.compare(o1.getOutlineNumber(), o2.getOutlineNumber());\n }\n });\n\n Map<String, Task> map = new HashMap<String, Task>();\n map.put(\"\", mpxjTask);\n\n for (Document.Projects.Project.Task task : tasks)\n {\n readTask(projectIdentifier, map, task);\n }\n }", "private List<AssignmentField> getAllAssignmentExtendedAttributes()\n {\n ArrayList<AssignmentField> result = new ArrayList<AssignmentField>();\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_COST));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_DATE));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_DURATION));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_COST));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_DATE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_DURATION));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_FLAG));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_NUMBER));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_RESOURCE_MULTI_VALUE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_RESOURCE_OUTLINE_CODE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_TEXT));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_FINISH));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_FLAG));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_NUMBER));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_START));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_TEXT));\n return result;\n }", "public static String fromClassPath() {\n Set<String> versions = new HashSet<>();\n try {\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n Enumeration<URL> manifests = classLoader.getResources(\"META-INF/MANIFEST.MF\");\n\n while (manifests.hasMoreElements()) {\n URL manifestURL = manifests.nextElement();\n try (InputStream is = manifestURL.openStream()) {\n Manifest manifest = new Manifest();\n manifest.read(is);\n\n Attributes buildInfo = manifest.getAttributes(\"Build-Info\");\n if (buildInfo != null) {\n if (buildInfo.getValue(\"Selenium-Version\") != null) {\n versions.add(buildInfo.getValue(\"Selenium-Version\"));\n } else {\n // might be in build-info part\n if (manifest.getEntries() != null) {\n if (manifest.getEntries().containsKey(\"Build-Info\")) {\n final Attributes attributes = manifest.getEntries().get(\"Build-Info\");\n\n if (attributes.getValue(\"Selenium-Version\") != null) {\n versions.add(attributes.getValue(\"Selenium-Version\"));\n }\n }\n }\n }\n }\n }\n }\n } catch (Exception e) {\n logger.log(Level.WARNING,\n \"Exception {0} occurred while resolving selenium version and latest image is going to be used.\",\n e.getMessage());\n return SELENIUM_VERSION;\n }\n\n if (versions.isEmpty()) {\n logger.log(Level.INFO, \"No version of Selenium found in classpath. Using latest image.\");\n return SELENIUM_VERSION;\n }\n\n String foundVersion = versions.iterator().next();\n if (versions.size() > 1) {\n logger.log(Level.WARNING, \"Multiple versions of Selenium found in classpath. Using the first one found {0}.\",\n foundVersion);\n }\n\n return foundVersion;\n }", "public void addForeignKeyField(int newId)\r\n {\r\n if (m_ForeignKeyFields == null)\r\n {\r\n m_ForeignKeyFields = new Vector();\r\n }\r\n m_ForeignKeyFields.add(new Integer(newId));\r\n }", "public static base_response unset(nitro_service client, aaaparameter resource, String[] args) throws Exception{\n\t\taaaparameter unsetresource = new aaaparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "private void readProjectHeader()\n {\n Table table = m_tables.get(\"DIR\");\n MapRow row = table.find(\"\");\n if (row != null)\n {\n setFields(PROJECT_FIELDS, row, m_projectFile.getProjectProperties());\n m_wbsFormat = new P3WbsFormat(row);\n }\n }" ]
Lift a Java Callable to a Scala Function0 @param f the function to lift @returns the Scala function
[ "public static<Z> Function0<Z> lift(Callable<Z> f) {\n\treturn bridge.lift(f);\n }" ]
[ "public void addCommandClass(ZWaveCommandClass commandClass)\n\t{\n\t\tZWaveCommandClass.CommandClass key = commandClass.getCommandClass();\n\t\t\n\t\tif (!supportedCommandClasses.containsKey(key)) {\n\t\t\tsupportedCommandClasses.put(key, commandClass);\n\t\t\t\n\t\t\tif (commandClass instanceof ZWaveEventListener)\n\t\t\t\tthis.controller.addEventListener((ZWaveEventListener)commandClass);\n\t\t\t\n\t\t\tthis.lastUpdated = Calendar.getInstance().getTime();\n\t\t}\n\t}", "public <T> T eval(ELVars vars, String el, Class<T> returnType) throws ELEvalException {\n Utils.checkNotNull(vars, \"vars\");\n Utils.checkNotNull(el, \"expression\");\n Utils.checkNotNull(returnType, \"returnType\");\n VARIABLES_IN_SCOPE_TL.set(vars);\n try {\n return evaluate(vars, el, returnType);\n } finally {\n VARIABLES_IN_SCOPE_TL.set(null);\n }\n }", "public static BufferedImage cloneImage( BufferedImage image ) {\n\t\tBufferedImage newImage = new BufferedImage( image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB );\n\t\tGraphics2D g = newImage.createGraphics();\n\t\tg.drawRenderedImage( image, null );\n\t\tg.dispose();\n\t\treturn newImage;\n\t}", "public byte byteAt(int i) {\n\n if (i < 0) {\n throw new IndexOutOfBoundsException(\"i < 0, \" + i);\n }\n\n if (i >= length) {\n throw new IndexOutOfBoundsException(\"i >= length, \" + i + \" >= \" + length);\n }\n\n return data[offset + i];\n }", "private List<TransformEntry> readTransformEntries(File file) throws Exception {\n\n List<TransformEntry> result = new ArrayList<>();\n try (FileInputStream fis = new FileInputStream(file)) {\n byte[] data = CmsFileUtil.readFully(fis, false);\n Document doc = CmsXmlUtils.unmarshalHelper(data, null, false);\n for (Node node : doc.selectNodes(\"//transform\")) {\n Element elem = ((Element)node);\n String xslt = elem.attributeValue(\"xslt\");\n String conf = elem.attributeValue(\"config\");\n TransformEntry entry = new TransformEntry(conf, xslt);\n result.add(entry);\n }\n }\n return result;\n }", "public double[][] getPositionsAsArray(){\n\t\tdouble[][] posAsArr = new double[size()][3];\n\t\tfor(int i = 0; i < size(); i++){\n\t\t\tif(get(i)!=null){\n\t\t\t\tposAsArr[i][0] = get(i).x;\n\t\t\t\tposAsArr[i][1] = get(i).y;\n\t\t\t\tposAsArr[i][2] = get(i).z;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tposAsArr[i] = null;\n\t\t\t}\n\t\t}\n\t\treturn posAsArr;\n\t}", "public static ConsistencyLevel determineConsistency(Map<Value, Set<ClusterNode>> versionNodeSetMap,\n int replicationFactor) {\n boolean fullyConsistent = true;\n Value latestVersion = null;\n for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : versionNodeSetMap.entrySet()) {\n Value value = versionNodeSetEntry.getKey();\n if (latestVersion == null) {\n latestVersion = value;\n } else if (value.isTimeStampLaterThan(latestVersion)) {\n latestVersion = value;\n }\n Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue();\n fullyConsistent = fullyConsistent && (nodeSet.size() == replicationFactor);\n }\n if (fullyConsistent) {\n return ConsistencyLevel.FULL;\n } else {\n // latest write consistent, effectively consistent\n if (latestVersion != null && versionNodeSetMap.get(latestVersion).size() == replicationFactor) {\n return ConsistencyLevel.LATEST_CONSISTENT;\n }\n // all other states inconsistent\n return ConsistencyLevel.INCONSISTENT;\n }\n }", "public void attachMetadataCache(SlotReference slot, File file)\n throws IOException {\n ensureRunning();\n if (slot.player < 1 || slot.player > 4 || DeviceFinder.getInstance().getLatestAnnouncementFrom(slot.player) == null) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for player \" + slot.player);\n }\n if ((slot.slot != CdjStatus.TrackSourceSlot.USB_SLOT) && (slot.slot != CdjStatus.TrackSourceSlot.SD_SLOT)) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for slot \" + slot.slot);\n }\n\n MetadataCache cache = new MetadataCache(file);\n final MediaDetails slotDetails = getMediaDetailsFor(slot);\n if (cache.sourceMedia != null && slotDetails != null) {\n if (!slotDetails.hashKey().equals(cache.sourceMedia.hashKey())) {\n throw new IllegalArgumentException(\"Cache was created for different media (\" + cache.sourceMedia.hashKey() +\n \") than is in the slot (\" + slotDetails.hashKey() + \").\");\n }\n if (slotDetails.hasChanged(cache.sourceMedia)) {\n logger.warn(\"Media has changed (\" + slotDetails + \") since cache was created (\" + cache.sourceMedia +\n \"). Attaching anyway as instructed.\");\n }\n }\n attachMetadataCacheInternal(slot, cache);\n }", "protected void update(float scale) {\n // Updates only when the plane is in the scene\n GVRSceneObject owner = getOwnerObject();\n\n if ((owner != null) && isEnabled() && owner.isEnabled())\n {\n convertFromARtoVRSpace(scale);\n }\n }" ]
Generates new individual particle radius based on min and max radius setting. @return new particle radius
[ "private float newRandomIndividualParticleRadius(@NonNull final SceneConfiguration scene) {\n return scene.getParticleRadiusMin() == scene.getParticleRadiusMax() ?\n scene.getParticleRadiusMin() : scene.getParticleRadiusMin() + (random.nextInt(\n (int) ((scene.getParticleRadiusMax() - scene.getParticleRadiusMin()) * 100f)))\n / 100f;\n }" ]
[ "public boolean isDuplicateName(String name) {\n if (name == null || name.trim().isEmpty()) {\n return false;\n }\n List<AssignmentRow> as = view.getAssignmentRows();\n if (as != null && !as.isEmpty()) {\n int nameCount = 0;\n for (AssignmentRow row : as) {\n if (name.trim().compareTo(row.getName()) == 0) {\n nameCount++;\n if (nameCount > 1) {\n return true;\n }\n }\n }\n }\n return false;\n }", "public double determinant() {\n if (m != n) {\n throw new IllegalArgumentException(\"Matrix must be square.\");\n }\n double d = (double) pivsign;\n for (int j = 0; j < n; j++) {\n d *= LU[j][j];\n }\n return d;\n }", "public boolean assertValidPkForDelete(ClassDescriptor cld, Object obj)\r\n {\r\n if(!ProxyHelper.isProxy(obj))\r\n {\r\n FieldDescriptor fieldDescriptors[] = cld.getPkFields();\r\n int fieldDescriptorSize = fieldDescriptors.length;\r\n for(int i = 0; i < fieldDescriptorSize; i++)\r\n {\r\n FieldDescriptor fd = fieldDescriptors[i];\r\n Object pkValue = fd.getPersistentField().get(obj);\r\n if (representsNull(fd, pkValue))\r\n {\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n }", "public static <T> T columnStringToObject(Class<?> objClass, String str, Pattern delimiterPattern, String[] fieldNames)\r\n throws InstantiationException, IllegalAccessException, NoSuchMethodException, NoSuchFieldException, InvocationTargetException\r\n {\r\n String[] fields = delimiterPattern.split(str);\r\n T item = ErasureUtils.<T>uncheckedCast(objClass.newInstance());\r\n for (int i = 0; i < fields.length; i++) {\r\n try {\r\n Field field = objClass.getDeclaredField(fieldNames[i]);\r\n field.set(item, fields[i]);\r\n } catch (IllegalAccessException ex) {\r\n Method method = objClass.getDeclaredMethod(\"set\" + StringUtils.capitalize(fieldNames[i]), String.class);\r\n method.invoke(item, fields[i]);\r\n }\r\n }\r\n return item;\r\n }", "public String getString(String fieldName) {\n\t\treturn hasValue(fieldName) ? String.valueOf(resultMap.get(fieldName)) : null;\n\t}", "@SuppressWarnings(\"WeakerAccess\")\n public TrackMetadata requestMetadataFrom(final CdjStatus status) {\n if (status.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.NO_TRACK || status.getRekordboxId() == 0) {\n return null;\n }\n final DataReference track = new DataReference(status.getTrackSourcePlayer(), status.getTrackSourceSlot(),\n status.getRekordboxId());\n return requestMetadataFrom(track, status.getTrackType());\n }", "public static boolean intersectsPointWithRectF(RectF _Rect, float _X, float _Y) {\n return _X > _Rect.left && _X < _Rect.right && _Y > _Rect.top && _Y < _Rect.bottom;\n }", "public void store(Object obj) throws PersistenceBrokerException\n {\n obj = extractObjectToStore(obj);\n // only do something if obj != null\n if(obj == null) return;\n\n ClassDescriptor cld = getClassDescriptor(obj.getClass());\n /*\n if one of the PK fields was null, we assume the objects\n was new and needs insert\n */\n boolean insert = serviceBrokerHelper().hasNullPKField(cld, obj);\n Identity oid = serviceIdentity().buildIdentity(cld, obj);\n /*\n if PK values are set, lookup cache or db to see whether object\n needs insert or update\n */\n if (!insert)\n {\n insert = objectCache.lookup(oid) == null\n && !serviceBrokerHelper().doesExist(cld, oid, obj);\n }\n store(obj, oid, cld, insert);\n }", "private void beforeBatch(BatchBackend backend) {\n\t\tif ( this.purgeAtStart ) {\n\t\t\t// purgeAll for affected entities\n\t\t\tIndexedTypeSet targetedTypes = searchFactoryImplementor.getIndexedTypesPolymorphic( rootIndexedTypes );\n\t\t\tfor ( IndexedTypeIdentifier type : targetedTypes ) {\n\t\t\t\t// needs do be in-sync work to make sure we wait for the end of it.\n\t\t\t\tbackend.doWorkInSync( new PurgeAllLuceneWork( tenantId, type ) );\n\t\t\t}\n\t\t\tif ( this.optimizeAfterPurge ) {\n\t\t\t\tbackend.optimize( targetedTypes );\n\t\t\t}\n\t\t}\n\t}" ]
This method extracts calendar data from an MSPDI file. @param project Root node of the MSPDI file @param map Map of calendar UIDs to names
[ "private void readCalendars(Project project, HashMap<BigInteger, ProjectCalendar> map)\n {\n Project.Calendars calendars = project.getCalendars();\n if (calendars != null)\n {\n LinkedList<Pair<ProjectCalendar, BigInteger>> baseCalendars = new LinkedList<Pair<ProjectCalendar, BigInteger>>();\n for (Project.Calendars.Calendar cal : calendars.getCalendar())\n {\n readCalendar(cal, map, baseCalendars);\n }\n updateBaseCalendarNames(baseCalendars, map);\n }\n\n try\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n BigInteger calendarID = new BigInteger(properties.getDefaultCalendarName());\n ProjectCalendar calendar = map.get(calendarID);\n m_projectFile.setDefaultCalendar(calendar);\n }\n\n catch (Exception ex)\n {\n // Ignore exceptions\n }\n }" ]
[ "protected void checkObserverMethods() {\n Collection<EnhancedAnnotatedMethod<?, ? super T>> observerMethods = BeanMethods.getObserverMethods(this.getEnhancedAnnotated());\n Collection<EnhancedAnnotatedMethod<?, ? super T>> asyncObserverMethods = BeanMethods.getAsyncObserverMethods(this.getEnhancedAnnotated());\n checkObserverMethods(observerMethods);\n checkObserverMethods(asyncObserverMethods);\n }", "private UserAlias getUserAlias(Object attribute)\r\n\t{\r\n\t\tif (m_userAlias != null)\r\n\t\t{\r\n\t\t\treturn m_userAlias;\r\n\t\t}\r\n\t\tif (!(attribute instanceof String))\r\n\t\t{\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tif (m_alias == null)\r\n\t\t{\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tif (m_aliasPath == null)\r\n\t\t{\r\n\t\t\tboolean allPathsAliased = true;\r\n\t\t\treturn new UserAlias(m_alias, (String)attribute, allPathsAliased);\r\n\t\t}\r\n\t\treturn new UserAlias(m_alias, (String)attribute, m_aliasPath);\r\n\t}", "protected void removeWatermark(URLTemplate itemUrl) {\n URL watermarkUrl = itemUrl.build(this.getAPI().getBaseURL(), this.getID());\n URL url = WATERMARK_URL_TEMPLATE.build(watermarkUrl.toString());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "public void removeLinks(ServiceReference<D> declarationSRef) {\n D declaration = getDeclaration(declarationSRef);\n for (ServiceReference serviceReference : declaration.getStatus().getServiceReferencesBounded()) {\n // FIXME : In case of multiples Linker, we will remove the link of all the ServiceReference\n // FIXME : event the ones which dun know nothing about\n linkerManagement.unlink(declaration, serviceReference);\n }\n }", "public List<Method> getMethodsFromGroupIds(int[] groupIds, String[] filters) throws Exception {\n ArrayList<Method> methods = new ArrayList<Method>();\n\n for (int groupId : groupIds) {\n methods.addAll(getMethodsFromGroupId(groupId, filters));\n }\n\n return methods;\n }", "static String guessEntityTypeFromId(String id) {\n\t\tif(id.isEmpty()) {\n\t\t\tthrow new IllegalArgumentException(\"Entity ids should not be empty.\");\n\t\t}\n\t\tswitch (id.charAt(0)) {\n\t\t\tcase 'L':\n\t\t\t\tif(id.contains(\"-F\")) {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_FORM;\n\t\t\t\t} else if(id.contains(\"-S\")) {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_SENSE;\n\t\t\t\t} else {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_LEXEME;\n\t\t\t\t}\n\t\t\tcase 'P':\n\t\t\t\treturn JSON_ENTITY_TYPE_PROPERTY;\n\t\t\tcase 'Q':\n\t\t\t\treturn JSON_ENTITY_TYPE_ITEM;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Entity id \\\"\" + id + \"\\\" is not supported.\");\n\t\t}\n\t}", "public static Cluster swapGreedyRandomPartitions(final Cluster nextCandidateCluster,\n final List<Integer> nodeIds,\n final int greedySwapMaxPartitionsPerNode,\n final int greedySwapMaxPartitionsPerZone,\n List<StoreDefinition> storeDefs) {\n\n System.out.println(\"GreedyRandom : nodeIds:\" + nodeIds);\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n int nodeIdA = -1;\n int nodeIdB = -1;\n int partitionIdA = -1;\n int partitionIdB = -1;\n\n for(int nodeIdAPrime: nodeIds) {\n System.out.println(\"GreedyRandom : processing nodeId:\" + nodeIdAPrime);\n List<Integer> partitionIdsAPrime = new ArrayList<Integer>();\n partitionIdsAPrime.addAll(returnCluster.getNodeById(nodeIdAPrime).getPartitionIds());\n Collections.shuffle(partitionIdsAPrime);\n\n int maxPartitionsInAPrime = Math.min(greedySwapMaxPartitionsPerNode,\n partitionIdsAPrime.size());\n\n for(int offsetAPrime = 0; offsetAPrime < maxPartitionsInAPrime; offsetAPrime++) {\n Integer partitionIdAPrime = partitionIdsAPrime.get(offsetAPrime);\n List<Pair<Integer, Integer>> partitionIdsZone = new ArrayList<Pair<Integer, Integer>>();\n for(int nodeIdBPrime: nodeIds) {\n if(nodeIdBPrime == nodeIdAPrime)\n continue;\n for(Integer partitionIdBPrime: returnCluster.getNodeById(nodeIdBPrime)\n .getPartitionIds()) {\n partitionIdsZone.add(new Pair<Integer, Integer>(nodeIdBPrime,\n partitionIdBPrime));\n }\n }\n\n Collections.shuffle(partitionIdsZone);\n int maxPartitionsInZone = Math.min(greedySwapMaxPartitionsPerZone,\n partitionIdsZone.size());\n for(int offsetZone = 0; offsetZone < maxPartitionsInZone; offsetZone++) {\n Integer nodeIdBPrime = partitionIdsZone.get(offsetZone).getFirst();\n Integer partitionIdBPrime = partitionIdsZone.get(offsetZone).getSecond();\n Cluster swapResult = swapPartitions(returnCluster,\n nodeIdAPrime,\n partitionIdAPrime,\n nodeIdBPrime,\n partitionIdBPrime);\n double swapUtility = new PartitionBalance(swapResult, storeDefs).getUtility();\n if(swapUtility < currentUtility) {\n currentUtility = swapUtility;\n System.out.println(\" -> \" + currentUtility);\n nodeIdA = nodeIdAPrime;\n partitionIdA = partitionIdAPrime;\n nodeIdB = nodeIdBPrime;\n partitionIdB = partitionIdBPrime;\n }\n }\n }\n }\n\n if(nodeIdA == -1) {\n return returnCluster;\n }\n return swapPartitions(returnCluster, nodeIdA, partitionIdA, nodeIdB, partitionIdB);\n }", "protected void generateFile(File file,\n String templateName,\n VelocityContext context) throws Exception\n {\n Writer writer = new BufferedWriter(new FileWriter(file));\n try\n {\n Velocity.mergeTemplate(classpathPrefix + templateName,\n ENCODING,\n context,\n writer);\n writer.flush();\n }\n finally\n {\n writer.close();\n }\n }", "public static int cudnnReduceTensor(\n cudnnHandle handle, \n cudnnReduceTensorDescriptor reduceTensorDesc, \n Pointer indices, \n long indicesSizeInBytes, \n Pointer workspace, \n long workspaceSizeInBytes, \n Pointer alpha, \n cudnnTensorDescriptor aDesc, \n Pointer A, \n Pointer beta, \n cudnnTensorDescriptor cDesc, \n Pointer C)\n {\n return checkResult(cudnnReduceTensorNative(handle, reduceTensorDesc, indices, indicesSizeInBytes, workspace, workspaceSizeInBytes, alpha, aDesc, A, beta, cDesc, C));\n }" ]
Create an info object from an authscope object. @param authscope the authscope
[ "@SuppressWarnings(\"StringEquality\")\n public static MatchInfo fromAuthScope(final AuthScope authscope) {\n String newScheme = StringUtils.equals(authscope.getScheme(), AuthScope.ANY_SCHEME) ? ANY_SCHEME :\n authscope.getScheme();\n String newHost = StringUtils.equals(authscope.getHost(), AuthScope.ANY_HOST) ? ANY_HOST :\n authscope.getHost();\n int newPort = authscope.getPort() == AuthScope.ANY_PORT ? ANY_PORT : authscope.getPort();\n String newRealm = StringUtils.equals(authscope.getRealm(), AuthScope.ANY_REALM) ? ANY_REALM :\n authscope.getRealm();\n\n return new MatchInfo(newScheme, newHost, newPort, ANY_PATH, ANY_QUERY,\n ANY_FRAGMENT, newRealm, ANY_METHOD);\n }" ]
[ "@PostConstruct\n public void init() {\n this.metricRegistry.register(name(\"gc\"), new GarbageCollectorMetricSet());\n this.metricRegistry.register(name(\"memory\"), new MemoryUsageGaugeSet());\n this.metricRegistry.register(name(\"thread-states\"), new ThreadStatesGaugeSet());\n this.metricRegistry.register(name(\"fd-usage\"), new FileDescriptorRatioGauge());\n }", "@Override\n public void preStateCrawling(CrawlerContext context,\n ImmutableList<CandidateElement> candidateElements, StateVertex state) {\n LOG.debug(\"preStateCrawling\");\n List<CandidateElementPosition> newElements = Lists.newLinkedList();\n LOG.info(\"Prestate found new state {} with {} candidates\", state.getName(),\n candidateElements.size());\n for (CandidateElement element : candidateElements) {\n try {\n WebElement webElement = getWebElement(context.getBrowser(), element);\n if (webElement != null) {\n newElements.add(findElement(webElement, element));\n }\n } catch (WebDriverException e) {\n LOG.info(\"Could not get position for {}\", element, e);\n }\n }\n\n StateBuilder stateOut = outModelCache.addStateIfAbsent(state);\n stateOut.addCandidates(newElements);\n LOG.trace(\"preState finished, elements added to state\");\n }", "public <T> Map<String, List<T>> queryGroups(String query, Class<T> classOfT) {\r\n InputStream instream = null;\r\n try {\r\n Reader reader = new InputStreamReader(instream = queryForStream(query), \"UTF-8\");\r\n JsonObject json = new JsonParser().parse(reader).getAsJsonObject();\r\n Map<String, List<T>> result = new LinkedHashMap<String, List<T>>();\r\n if (json.has(\"groups\")) {\r\n for (JsonElement e : json.getAsJsonArray(\"groups\")) {\r\n String groupName = e.getAsJsonObject().get(\"by\").getAsString();\r\n List<T> orows = new ArrayList<T>();\r\n if (!includeDocs) {\r\n log.warning(\"includeDocs set to false and attempting to retrieve doc. \" +\r\n \"null object will be returned\");\r\n }\r\n for (JsonElement rows : e.getAsJsonObject().getAsJsonArray(\"rows\")) {\r\n orows.add(jsonToObject(client.getGson(), rows, \"doc\", classOfT));\r\n }\r\n result.put(groupName, orows);\r\n }// end for(groups)\r\n }// end hasgroups\r\n else {\r\n log.warning(\"No grouped results available. Use query() if non grouped query\");\r\n }\r\n return result;\r\n } catch (UnsupportedEncodingException e1) {\r\n // This should never happen as every implementation of the java platform is required\r\n // to support UTF-8.\r\n throw new RuntimeException(e1);\r\n } finally {\r\n close(instream);\r\n }\r\n }", "private String[] getDatePatterns(ProjectProperties properties)\n {\n String pattern = \"\";\n\n char datesep = properties.getDateSeparator();\n DateOrder dateOrder = properties.getDateOrder();\n\n switch (dateOrder)\n {\n case DMY:\n {\n pattern = \"dd\" + datesep + \"MM\" + datesep + \"yy\";\n break;\n }\n\n case MDY:\n {\n pattern = \"MM\" + datesep + \"dd\" + datesep + \"yy\";\n break;\n }\n\n case YMD:\n {\n pattern = \"yy\" + datesep + \"MM\" + datesep + \"dd\";\n break;\n }\n }\n\n return new String[]\n {\n pattern\n };\n }", "public void createInsertionSql(Database model, Platform platform, Writer writer) throws IOException\r\n {\r\n for (Iterator it = _beans.iterator(); it.hasNext();)\r\n {\r\n writer.write(platform.getInsertSql(model, (DynaBean)it.next()));\r\n if (it.hasNext())\r\n {\r\n writer.write(\"\\n\");\r\n }\r\n }\r\n }", "private long getTotalTime(ProjectCalendarDateRanges exception, Date date, boolean after)\n {\n long currentTime = DateHelper.getCanonicalTime(date).getTime();\n long total = 0;\n for (DateRange range : exception)\n {\n total += getTime(range.getStart(), range.getEnd(), currentTime, after);\n }\n return (total);\n }", "@Deprecated\r\n public Location resolvePlaceURL(String flickrPlacesUrl) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_RESOLVE_PLACE_URL);\r\n\r\n parameters.put(\"url\", flickrPlacesUrl);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }", "private ClassReference processType(Type type, TypeReferenceLocation typeReferenceLocation, int lineNumber, int columnNumber, int length,\n String line)\n {\n if (type == null)\n return null;\n\n ITypeBinding resolveBinding = type.resolveBinding();\n if (resolveBinding == null)\n {\n ResolveClassnameResult resolvedResult = resolveClassname(type.toString());\n ResolutionStatus status = resolvedResult.found ? ResolutionStatus.RECOVERED : ResolutionStatus.UNRESOLVED;\n PackageAndClassName packageAndClassName = PackageAndClassName.parseFromQualifiedName(resolvedResult.result);\n\n return processTypeAsString(resolvedResult.result, packageAndClassName.packageName, packageAndClassName.className, status,\n typeReferenceLocation, lineNumber,\n columnNumber, length, line);\n }\n else\n {\n return processTypeBinding(type.resolveBinding(), ResolutionStatus.RESOLVED, typeReferenceLocation, lineNumber,\n columnNumber, length, line);\n }\n\n }", "public void setBackgroundColor(float r, float g, float b, float a) {\n setBackgroundColorR(r);\n setBackgroundColorG(g);\n setBackgroundColorB(b);\n setBackgroundColorA(a);\n }" ]
Adds OPT_N | OPT_NODE option to OptionParser, with multiple arguments. @param parser OptionParser to be modified @param required Tells if this option is required or optional
[ "public static void acceptsNodeMultiple(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_N, OPT_NODE), \"node id list\")\n .withRequiredArg()\n .describedAs(\"node-id-list\")\n .withValuesSeparatedBy(',')\n .ofType(Integer.class);\n }" ]
[ "private void processCalendarData(ProjectCalendar calendar, List<ResultSetRow> calendarData)\n {\n for (ResultSetRow row : calendarData)\n {\n processCalendarData(calendar, row);\n }\n }", "public ItemRequest<Attachment> findById(String attachment) {\n \n String path = String.format(\"/attachments/%s\", attachment);\n return new ItemRequest<Attachment>(this, Attachment.class, path, \"GET\");\n }", "public static void dumpAnalysisToFile(String outputDirName,\n String baseFileName,\n PartitionBalance partitionBalance) {\n if(outputDirName != null) {\n File outputDir = new File(outputDirName);\n if(!outputDir.exists()) {\n Utils.mkdirs(outputDir);\n }\n\n try {\n FileUtils.writeStringToFile(new File(outputDirName, baseFileName + \".analysis\"),\n partitionBalance.toString());\n } catch(IOException e) {\n logger.error(\"IOException during dumpAnalysisToFile: \" + e);\n }\n }\n }", "public static lbvserver_auditnslogpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_auditnslogpolicy_binding obj = new lbvserver_auditnslogpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_auditnslogpolicy_binding response[] = (lbvserver_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public Metadata add(String path, List<String> values) {\n JsonArray arr = new JsonArray();\n for (String value : values) {\n arr.add(value);\n }\n this.values.add(this.pathToProperty(path), arr);\n this.addOp(\"add\", path, arr);\n return this;\n }", "public static boolean isSpreadSafe(Expression expression) {\r\n if (expression instanceof MethodCallExpression) {\r\n return ((MethodCallExpression) expression).isSpreadSafe();\r\n }\r\n if (expression instanceof PropertyExpression) {\r\n return ((PropertyExpression) expression).isSpreadSafe();\r\n }\r\n return false;\r\n }", "public static String getSolrRangeString(String from, String to) {\n\n // If a parameter is not initialized, use the asterisk '*' operator\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(from)) {\n from = \"*\";\n }\n\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(to)) {\n to = \"*\";\n }\n\n return String.format(\"[%s TO %s]\", from, to);\n }", "public static Shell createSubshell(String pathElement, Shell parent, String appName, Object mainHandler) {\n return createSubshell(pathElement, parent, appName, mainHandler, new EmptyMultiMap<String, Object>());\n }", "@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static byte checkByte(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInByteRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), BYTE_MIN, BYTE_MAX);\n\t\t}\n\n\t\treturn number.byteValue();\n\t}" ]
Create a new custom field setting on the project. @param project The project to associate the custom field with @return Request object
[ "public ItemRequest<Project> addCustomFieldSetting(String project) {\n \n String path = String.format(\"/projects/%s/addCustomFieldSetting\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }" ]
[ "public void rotateWithPivot(float quatW, float quatX, float quatY,\n float quatZ, float pivotX, float pivotY, float pivotZ) {\n NativeTransform.rotateWithPivot(getNative(), quatW, quatX, quatY,\n quatZ, pivotX, pivotY, pivotZ);\n }", "@Override\n public void close() {\n // unregister MBeans\n if(stats != null) {\n try {\n if(this.jmxEnabled)\n JmxUtils.unregisterMbean(getAggregateMetricName());\n } catch(Exception e) {}\n stats.close();\n }\n factory.close();\n queuedPool.close();\n }", "private boolean loadCustomErrorPage(\n CmsObject cms,\n HttpServletRequest req,\n HttpServletResponse res,\n String rootPath) {\n\n try {\n\n // get the site of the error page resource\n CmsSite errorSite = OpenCms.getSiteManager().getSiteForRootPath(rootPath);\n cms.getRequestContext().setSiteRoot(errorSite.getSiteRoot());\n String relPath = cms.getRequestContext().removeSiteRoot(rootPath);\n if (cms.existsResource(relPath)) {\n cms.getRequestContext().setUri(relPath);\n OpenCms.getResourceManager().loadResource(cms, cms.readResource(relPath), req, res);\n return true;\n } else {\n return false;\n }\n } catch (Throwable e) {\n // something went wrong log the exception and return false\n LOG.error(e.getMessage(), e);\n return false;\n }\n }", "protected void importUserFromFile() {\n\n CmsImportUserThread thread = new CmsImportUserThread(\n m_cms,\n m_ou,\n m_userImportList,\n getGroupsList(m_importGroups, true),\n getRolesList(m_importRoles, true),\n m_sendMail.getValue().booleanValue());\n thread.start();\n CmsShowReportDialog dialog = new CmsShowReportDialog(thread, new Runnable() {\n\n public void run() {\n\n m_window.close();\n }\n });\n m_window.setContent(dialog);\n\n }", "public MembersList<Member> getList(String groupId, Set<String> memberTypes, int perPage, int page) throws FlickrException {\r\n MembersList<Member> members = new MembersList<Member>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n\r\n parameters.put(\"group_id\", groupId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n if (memberTypes != null) {\r\n parameters.put(\"membertypes\", StringUtilities.join(memberTypes, \",\"));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element mElement = response.getPayload();\r\n members.setPage(mElement.getAttribute(\"page\"));\r\n members.setPages(mElement.getAttribute(\"pages\"));\r\n members.setPerPage(mElement.getAttribute(\"perpage\"));\r\n members.setTotal(mElement.getAttribute(\"total\"));\r\n\r\n NodeList mNodes = mElement.getElementsByTagName(\"member\");\r\n for (int i = 0; i < mNodes.getLength(); i++) {\r\n Element element = (Element) mNodes.item(i);\r\n members.add(parseMember(element));\r\n }\r\n return members;\r\n }", "public static base_responses update(nitro_service client, nsip6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsip6 updateresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsip6();\n\t\t\t\tupdateresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\tupdateresources[i].td = resources[i].td;\n\t\t\t\tupdateresources[i].nd = resources[i].nd;\n\t\t\t\tupdateresources[i].icmp = resources[i].icmp;\n\t\t\t\tupdateresources[i].vserver = resources[i].vserver;\n\t\t\t\tupdateresources[i].telnet = resources[i].telnet;\n\t\t\t\tupdateresources[i].ftp = resources[i].ftp;\n\t\t\t\tupdateresources[i].gui = resources[i].gui;\n\t\t\t\tupdateresources[i].ssh = resources[i].ssh;\n\t\t\t\tupdateresources[i].snmp = resources[i].snmp;\n\t\t\t\tupdateresources[i].mgmtaccess = resources[i].mgmtaccess;\n\t\t\t\tupdateresources[i].restrictaccess = resources[i].restrictaccess;\n\t\t\t\tupdateresources[i].state = resources[i].state;\n\t\t\t\tupdateresources[i].map = resources[i].map;\n\t\t\t\tupdateresources[i].dynamicrouting = resources[i].dynamicrouting;\n\t\t\t\tupdateresources[i].hostroute = resources[i].hostroute;\n\t\t\t\tupdateresources[i].ip6hostrtgw = resources[i].ip6hostrtgw;\n\t\t\t\tupdateresources[i].metric = resources[i].metric;\n\t\t\t\tupdateresources[i].vserverrhilevel = resources[i].vserverrhilevel;\n\t\t\t\tupdateresources[i].ospf6lsatype = resources[i].ospf6lsatype;\n\t\t\t\tupdateresources[i].ospfarea = resources[i].ospfarea;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public static void createMetadataCache(SlotReference slot, int playlistId, File cache) throws Exception {\n createMetadataCache(slot, playlistId, cache, null);\n }", "public void sendMessageUntilStopCount(int stopCount) {\n\n // always send with valid data.\n for (int i = processedWorkerCount; i < workers.size(); ++i) {\n ActorRef worker = workers.get(i);\n try {\n\n /**\n * !!! This is a must; without this sleep; stuck occured at 5K.\n * AKKA seems cannot handle too much too fast message send out.\n */\n Thread.sleep(1L);\n\n } catch (InterruptedException e) {\n logger.error(\"sleep exception \" + e + \" details: \", e);\n }\n\n // send as if the sender is the origin manager; so reply back to\n // origin manager\n worker.tell(OperationWorkerMsgType.PROCESS_REQUEST, originalManager);\n\n processedWorkerCount++;\n\n if (processedWorkerCount > stopCount) {\n return;\n }\n\n logger.debug(\"REQ_SENT: {} / {} taskId {}\", \n processedWorkerCount, requestTotalCount, taskIdTrim);\n\n }// end for loop\n }", "protected void progressInfoMessage(final String tag) {\n if(logger.isInfoEnabled()) {\n long totalTimeS = (System.currentTimeMillis() - startTimeMs) / Time.MS_PER_SECOND;\n\n logger.info(tag + \" : scanned \" + scanned + \" and fetched \" + fetched + \" for store '\"\n + storageEngine.getName() + \"' partitionIds:\" + partitionIds + \" in \"\n + totalTimeS + \" s\");\n }\n }" ]
returns an Array with an Objects CURRENT locking VALUES , BRJ @throws PersistenceBrokerException if there is an erros accessing o field values
[ "public ValueContainer[] getCurrentLockingValues(Object o) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] fields = getLockingFields();\r\n ValueContainer[] result = new ValueContainer[fields.length];\r\n for (int i = 0; i < result.length; i++)\r\n {\r\n result[i] = new ValueContainer(fields[i].getPersistentField().get(o), fields[i].getJdbcType());\r\n }\r\n return result;\r\n }" ]
[ "public boolean isEmpty() {\n\t\tint snapshotSize = cleared ? 0 : snapshot.size();\n\t\t//nothing in both\n\t\tif ( snapshotSize == 0 && currentState.isEmpty() ) {\n\t\t\treturn true;\n\t\t}\n\t\t//snapshot bigger than changeset\n\t\tif ( snapshotSize > currentState.size() ) {\n\t\t\treturn false;\n\t\t}\n\t\treturn size() == 0;\n\t}", "private void cleanStaleFiles(File backupDir, AsyncOperationStatus status) {\n String[] filesInEnv = env.getHome().list();\n String[] filesInBackupDir = backupDir.list();\n if(filesInEnv != null && filesInBackupDir != null) {\n HashSet<String> envFileSet = new HashSet<String>();\n for(String file: filesInEnv)\n envFileSet.add(file);\n // delete all files in backup which are currently not in environment\n for(String file: filesInBackupDir) {\n if(file.endsWith(BDB_EXT) && !envFileSet.contains(file)) {\n status.setStatus(\"Deleting stale jdb file :\" + file);\n File staleJdbFile = new File(backupDir, file);\n staleJdbFile.delete();\n }\n }\n }\n }", "public void updateEmbeddedColumn(GraphDatabaseService executionEngine, Object[] keyValues, String embeddedColumn, Object value) {\n\t\tString query = getUpdateEmbeddedColumnQuery( keyValues, embeddedColumn );\n\t\tMap<String, Object> params = params( ArrayHelper.concat( keyValues, value, value ) );\n\t\texecutionEngine.execute( query, params );\n\t}", "private byte[] readStreamCompressed(InputStream stream) throws IOException\r\n {\r\n ByteArrayOutputStream bao = new ByteArrayOutputStream();\r\n GZIPOutputStream gos = new GZIPOutputStream(bao);\r\n OutputStreamWriter output = new OutputStreamWriter(gos);\r\n BufferedReader input = new BufferedReader(new InputStreamReader(stream));\r\n String line;\r\n\r\n while ((line = input.readLine()) != null)\r\n {\r\n output.write(line);\r\n output.write('\\n');\r\n }\r\n input.close();\r\n stream.close();\r\n output.close();\r\n gos.close();\r\n bao.close();\r\n return bao.toByteArray();\r\n }", "private long getTime(Date start, Date end, long target, boolean after)\n {\n long total = 0;\n if (start != null && end != null)\n {\n Date startTime = DateHelper.getCanonicalTime(start);\n Date endTime = DateHelper.getCanonicalTime(end);\n\n Date startDay = DateHelper.getDayStartDate(start);\n Date finishDay = DateHelper.getDayStartDate(end);\n\n //\n // Handle the case where the end of the range is at midnight -\n // this will show up as the start and end days not matching\n //\n if (startDay.getTime() != finishDay.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n int diff = DateHelper.compare(startTime, endTime, target);\n if (diff == 0)\n {\n if (after == true)\n {\n total = (endTime.getTime() - target);\n }\n else\n {\n total = (target - startTime.getTime());\n }\n }\n else\n {\n if ((after == true && diff < 0) || (after == false && diff > 0))\n {\n total = (endTime.getTime() - startTime.getTime());\n }\n }\n }\n return (total);\n }", "protected String consumeQuoted(ImapRequestLineReader request)\n throws ProtocolException {\n // The 1st character must be '\"'\n consumeChar(request, '\"');\n\n StringBuilder quoted = new StringBuilder();\n char next = request.nextChar();\n while (next != '\"') {\n if (next == '\\\\') {\n request.consume();\n next = request.nextChar();\n if (!isQuotedSpecial(next)) {\n throw new ProtocolException(\"Invalid escaped character in quote: '\" +\n next + '\\'');\n }\n }\n quoted.append(next);\n request.consume();\n next = request.nextChar();\n }\n\n consumeChar(request, '\"');\n\n return quoted.toString();\n }", "public void updateUniqueCounters()\n {\n //\n // Update task unique IDs\n //\n for (Task task : m_parent.getTasks())\n {\n int uniqueID = NumberHelper.getInt(task.getUniqueID());\n if (uniqueID > m_taskUniqueID)\n {\n m_taskUniqueID = uniqueID;\n }\n }\n\n //\n // Update resource unique IDs\n //\n for (Resource resource : m_parent.getResources())\n {\n int uniqueID = NumberHelper.getInt(resource.getUniqueID());\n if (uniqueID > m_resourceUniqueID)\n {\n m_resourceUniqueID = uniqueID;\n }\n }\n\n //\n // Update calendar unique IDs\n //\n for (ProjectCalendar calendar : m_parent.getCalendars())\n {\n int uniqueID = NumberHelper.getInt(calendar.getUniqueID());\n if (uniqueID > m_calendarUniqueID)\n {\n m_calendarUniqueID = uniqueID;\n }\n }\n\n //\n // Update assignment unique IDs\n //\n for (ResourceAssignment assignment : m_parent.getResourceAssignments())\n {\n int uniqueID = NumberHelper.getInt(assignment.getUniqueID());\n if (uniqueID > m_assignmentUniqueID)\n {\n m_assignmentUniqueID = uniqueID;\n }\n }\n }", "SimpleJsonEncoder appendToJSONUnquoted(final String key, final Object value) {\n if (closed) {\n throw new IllegalStateException(\"Encoder already closed\");\n }\n if (value != null) {\n appendKey(key);\n sb.append(value);\n }\n return this;\n }", "public static RgbaColor fromHex(String hex) {\n if (hex.length() == 0 || hex.charAt(0) != '#') return getDefaultColor();\n\n // #rgb\n if (hex.length() == 4) {\n\n return new RgbaColor(parseHex(hex, 1, 2),\n parseHex(hex, 2, 3),\n parseHex(hex, 3, 4));\n\n }\n // #rrggbb\n else if (hex.length() == 7) {\n\n return new RgbaColor(parseHex(hex, 1, 3),\n parseHex(hex, 3, 5),\n parseHex(hex, 5, 7));\n\n }\n else {\n return getDefaultColor();\n }\n }" ]
Add a new subsystem to a given registry. @param registry the registry @param name the subsystem name @param version the version
[ "void addSubsystem(final OperationTransformerRegistry registry, final String name, final ModelVersion version) {\n final OperationTransformerRegistry profile = registry.getChild(PathAddress.pathAddress(PROFILE));\n final OperationTransformerRegistry server = registry.getChild(PathAddress.pathAddress(HOST, SERVER));\n final PathAddress address = PathAddress.pathAddress(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, name));\n subsystem.mergeSubtree(profile, Collections.singletonMap(address, version));\n if(server != null) {\n subsystem.mergeSubtree(server, Collections.singletonMap(address, version));\n }\n }" ]
[ "public RandomVariable getImpliedBachelierATMOptionVolatility(RandomVariable optionValue, double optionMaturity, double swapAnnuity){\n\t\treturn optionValue.average().mult(Math.sqrt(2.0 * Math.PI / optionMaturity) / swapAnnuity);\n\t}", "@SuppressWarnings(\"unchecked\")\n public Multimap<String, Processor> getAllRequiredAttributes() {\n Multimap<String, Processor> requiredInputs = HashMultimap.create();\n for (ProcessorGraphNode root: this.roots) {\n final BiMap<String, String> inputMapper = root.getInputMapper();\n for (String attr: inputMapper.keySet()) {\n requiredInputs.put(attr, root.getProcessor());\n }\n final Object inputParameter = root.getProcessor().createInputParameter();\n if (inputParameter instanceof Values) {\n continue;\n } else if (inputParameter != null) {\n final Class<?> inputParameterClass = inputParameter.getClass();\n final Set<String> requiredAttributesDefinedInInputParameter =\n getAttributeNames(inputParameterClass,\n FILTER_ONLY_REQUIRED_ATTRIBUTES);\n for (String attName: requiredAttributesDefinedInInputParameter) {\n try {\n if (inputParameterClass.getField(attName).getType() == Values.class) {\n continue;\n }\n } catch (NoSuchFieldException e) {\n throw new RuntimeException(e);\n }\n String mappedName = ProcessorUtils.getInputValueName(\n root.getProcessor().getInputPrefix(),\n inputMapper, attName);\n requiredInputs.put(mappedName, root.getProcessor());\n }\n }\n }\n\n return requiredInputs;\n }", "public static hanode_routemonitor6_binding[] get(nitro_service service, Long id) throws Exception{\n\t\thanode_routemonitor6_binding obj = new hanode_routemonitor6_binding();\n\t\tobj.set_id(id);\n\t\thanode_routemonitor6_binding response[] = (hanode_routemonitor6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void release(Contextual<T> contextual, T instance) {\n synchronized (dependentInstances) {\n for (ContextualInstance<?> dependentInstance : dependentInstances) {\n // do not destroy contextual again, since it's just being destroyed\n if (contextual == null || !(dependentInstance.getContextual().equals(contextual))) {\n destroy(dependentInstance);\n }\n }\n }\n if (resourceReferences != null) {\n for (ResourceReference<?> reference : resourceReferences) {\n reference.release();\n }\n }\n }", "public void addFieldDescriptor(FieldDescriptor fld)\r\n {\r\n fld.setClassDescriptor(this); // BRJ\r\n if (m_FieldDescriptions == null)\r\n {\r\n m_FieldDescriptions = new FieldDescriptor[1];\r\n m_FieldDescriptions[0] = fld;\r\n }\r\n else\r\n {\r\n int size = m_FieldDescriptions.length;\r\n FieldDescriptor[] tmpArray = new FieldDescriptor[size + 1];\r\n System.arraycopy(m_FieldDescriptions, 0, tmpArray, 0, size);\r\n tmpArray[size] = fld;\r\n m_FieldDescriptions = tmpArray;\r\n // 2. Sort fields according to their getOrder() Property\r\n Arrays.sort(m_FieldDescriptions, FieldDescriptor.getComparator());\r\n }\r\n\r\n m_fieldDescriptorNameMap = null;\r\n m_PkFieldDescriptors = null;\r\n m_nonPkFieldDescriptors = null;\r\n m_lockingFieldDescriptors = null;\r\n m_RwFieldDescriptors = null;\r\n m_RwNonPkFieldDescriptors = null;\r\n }", "public final Iterator<AbstractTraceRegion> leafIterator() {\n\t\tif (nestedRegions == null)\n\t\t\treturn Collections.<AbstractTraceRegion> singleton(this).iterator();\n\t\treturn new LeafIterator(this);\n\t}", "public String convertToPrefixLength() throws AddressStringException {\n\t\tIPAddress address = toAddress();\n\t\tInteger prefix;\n\t\tif(address == null) {\n\t\t\tif(isPrefixOnly()) {\n\t\t\t\tprefix = getNetworkPrefixLength();\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} else {\n\t\t\tprefix = address.getBlockMaskPrefixLength(true);\n\t\t\tif(prefix == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn IPAddressSegment.toUnsignedString(prefix, 10, \n\t\t\t\tnew StringBuilder(IPAddressSegment.toUnsignedStringLength(prefix, 10) + 1).append(IPAddress.PREFIX_LEN_SEPARATOR)).toString();\n\t}", "public synchronized int getPartitionStoreCount() {\n int count = 0;\n for (String store : storeToPartitionIds.keySet()) {\n count += storeToPartitionIds.get(store).size();\n }\n return count;\n }", "public final void reset()\n {\n for (int i = 0; i < permutationIndices.length; i++)\n {\n permutationIndices[i] = i;\n }\n remainingPermutations = totalPermutations;\n }" ]
Plots the rotated trajectory, spline and support points.
[ "public void showTrajectoryAndSpline(){\n\t\t\n\t\tif(t.getDimension()==2){\n\t\t \tdouble[] xData = new double[rotatedTrajectory.size()];\n\t\t double[] yData = new double[rotatedTrajectory.size()];\n\t\t for(int i = 0; i < rotatedTrajectory.size(); i++){\n\t\t \txData[i] = rotatedTrajectory.get(i).x;\n\t\t \tyData[i] = rotatedTrajectory.get(i).y;\t\t \t\n\t\t }\n\t\t // Create Chart\n\t\t Chart chart = QuickChart.getChart(\"Spline+Track\", \"X\", \"Y\", \"y(x)\", xData, yData);\n\t\t \n\t\t //Add spline support points\n\t\t double[] subxData = new double[splineSupportPoints.size()];\n\t\t double[] subyData = new double[splineSupportPoints.size()];\n\t\t \n\t\t for(int i = 0; i < splineSupportPoints.size(); i++){\n\t\t \tsubxData[i] = splineSupportPoints.get(i).x;\n\t\t \tsubyData[i] = splineSupportPoints.get(i).y;\n\t\t }\n\t\t Series s = chart.addSeries(\"Spline Support Points\", subxData, subyData);\n\t\t s.setLineStyle(SeriesLineStyle.NONE);\n\t\t s.setSeriesType(SeriesType.Line);\n\t\t \n\t\t //ADd spline points\n\t\t int numberInterpolatedPointsPerSegment = 20;\n\t\t int numberOfSplines = spline.getN();\n\t\t double[] sxData = new double[numberInterpolatedPointsPerSegment*numberOfSplines];\n\t\t \n\t\t double[] syData = new double[numberInterpolatedPointsPerSegment*numberOfSplines];\n\t\t double[] knots = spline.getKnots();\n\t\t for(int i = 0; i < numberOfSplines; i++){\n\t\t \tdouble x = knots[i];\n\t\t \n\t\t \tdouble stopx = knots[i+1];\n\t\t \tdouble dx = (stopx-x)/numberInterpolatedPointsPerSegment;\n\t\t \t\n\t\t \tfor(int j = 0; j < numberInterpolatedPointsPerSegment; j++){\n\n\t\t \t\tsxData[i*numberInterpolatedPointsPerSegment+j] = x;\n\t\t \t\tsyData[i*numberInterpolatedPointsPerSegment+j] = spline.value(x);\n\t\t \t\tx += dx;\n\t\t \t}\n\t\t \t\n\t\t }\n\t\t s = chart.addSeries(\"Spline\", sxData, syData);\n\t\t s.setLineStyle(SeriesLineStyle.DASH_DASH);\n\t\t s.setMarker(SeriesMarker.NONE);\n\t\t s.setSeriesType(SeriesType.Line);\n\t\t \n\t\t \n\t\t //Show it\n\t\t new SwingWrapper(chart).displayChart();\n\t\t} \n\t}" ]
[ "protected boolean shouldApplyThisRuleTo(ClassNode classNode) {\r\n // TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns\r\n boolean shouldApply = true;\r\n\r\n String applyTo = getApplyToClassNames();\r\n String doNotApplyTo = getDoNotApplyToClassNames();\r\n\r\n if (applyTo != null && applyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(applyTo, true);\r\n shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName());\r\n }\r\n\r\n if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true);\r\n shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName());\r\n }\r\n\r\n return shouldApply;\r\n }", "public static base_response clear(nitro_service client) throws Exception {\n\t\tnspbr6 clearresource = new nspbr6();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}", "public boolean getBit(int index)\n {\n assertValidIndex(index);\n int word = index / WORD_LENGTH;\n int offset = index % WORD_LENGTH;\n return (data[word] & (1 << offset)) != 0;\n }", "public BoxFile.Info commit(String digest, List<BoxFileUploadSessionPart> parts,\n Map<String, String> attributes, String ifMatch, String ifNoneMatch) {\n\n URL commitURL = this.sessionInfo.getSessionEndpoints().getCommitEndpoint();\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), commitURL, HttpMethod.POST);\n request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON);\n\n if (ifMatch != null) {\n request.addHeader(HttpHeaders.IF_MATCH, ifMatch);\n }\n\n if (ifNoneMatch != null) {\n request.addHeader(HttpHeaders.IF_NONE_MATCH, ifNoneMatch);\n }\n\n //Creates the body of the request\n String body = this.getCommitBody(parts, attributes);\n request.setBody(body);\n\n BoxAPIResponse response = request.send();\n //Retry the commit operation after the given number of seconds if the HTTP response code is 202.\n if (response.getResponseCode() == 202) {\n String retryInterval = response.getHeaderField(\"retry-after\");\n if (retryInterval != null) {\n try {\n Thread.sleep(new Integer(retryInterval) * 1000);\n } catch (InterruptedException ie) {\n throw new BoxAPIException(\"Commit retry failed. \", ie);\n }\n\n return this.commit(digest, parts, attributes, ifMatch, ifNoneMatch);\n }\n }\n\n if (response instanceof BoxJSONResponse) {\n //Create the file instance from the response\n return this.getFile((BoxJSONResponse) response);\n } else {\n throw new BoxAPIException(\"Commit response content type is not application/json. The response code : \"\n + response.getResponseCode());\n }\n }", "public void onCreate(T content, LayoutInflater layoutInflater, ViewGroup parent) {\n this.content = content;\n this.rootView = inflate(layoutInflater, parent);\n if (rootView == null) {\n throw new NotInflateViewException(\n \"Renderer instances have to return a not null view in inflateView method\");\n }\n this.rootView.setTag(this);\n setUpView(rootView);\n hookListeners(rootView);\n }", "private void readCalendars(Document cdp)\n {\n for (Calendar calendar : cdp.getCalendars().getCalendar())\n {\n readCalendar(calendar);\n }\n\n for (Calendar calendar : cdp.getCalendars().getCalendar())\n {\n ProjectCalendar child = m_calendarMap.get(calendar.getID());\n ProjectCalendar parent = m_calendarMap.get(calendar.getBaseCalendarID());\n if (parent == null)\n {\n m_projectFile.setDefaultCalendar(child);\n }\n else\n {\n child.setParent(parent);\n }\n }\n }", "public static byte[] storeContentAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws IOException, OperationFailedException {\n if (!operation.hasDefined(CONTENT)) {\n throw createFailureException(DomainControllerLogger.ROOT_LOGGER.invalidContentDeclaration());\n }\n final ModelNode content = operation.get(CONTENT).get(0);\n if (content.hasDefined(HASH)) {\n // This should be handled as part of the OSH\n throw createFailureException(DomainControllerLogger.ROOT_LOGGER.invalidContentDeclaration());\n }\n final byte[] hash = storeDeploymentContent(context, operation, contentRepository);\n\n // Clear the contents and update with the hash\n final ModelNode slave = operation.clone();\n slave.get(CONTENT).setEmptyList().add().get(HASH).set(hash);\n // Add the domain op transformer\n List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);\n if (transformers == null) {\n context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());\n }\n transformers.add(new CompositeOperationAwareTransmuter(slave));\n return hash;\n }", "public static boolean isFileExist(String filePath) {\r\n if (StringUtils.isEmpty(filePath)) {\r\n return false;\r\n }\r\n\r\n File file = new File(filePath);\r\n return (file.exists() && file.isFile());\r\n }", "public byte[] getValueAsArray() {\n ByteBuffer buffer = getValue();\n byte[] result = new byte[buffer.remaining()];\n buffer.get(result);\n return result;\n }" ]
Use this API to update responderpolicy resources.
[ "public static base_responses update(nitro_service client, responderpolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tresponderpolicy updateresources[] = new responderpolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new responderpolicy();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].rule = resources[i].rule;\n\t\t\t\tupdateresources[i].action = resources[i].action;\n\t\t\t\tupdateresources[i].undefaction = resources[i].undefaction;\n\t\t\t\tupdateresources[i].comment = resources[i].comment;\n\t\t\t\tupdateresources[i].logaction = resources[i].logaction;\n\t\t\t\tupdateresources[i].appflowaction = resources[i].appflowaction;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}" ]
[ "public static String getTemplateMapperConfig(ServletRequest request) {\n\n String result = null;\n CmsTemplateContext templateContext = (CmsTemplateContext)request.getAttribute(\n CmsTemplateContextManager.ATTR_TEMPLATE_CONTEXT);\n if (templateContext != null) {\n I_CmsTemplateContextProvider provider = templateContext.getProvider();\n if (provider instanceof I_CmsTemplateMappingContextProvider) {\n result = ((I_CmsTemplateMappingContextProvider)provider).getMappingConfigurationPath(\n templateContext.getKey());\n }\n }\n return result;\n }", "public static CmsResourceTypeStatResultList init(CmsResourceTypeStatResultList resList) {\n\n if (resList == null) {\n return new CmsResourceTypeStatResultList();\n }\n\n resList.deleteOld();\n return resList;\n }", "public static String getRelativePathName(Path root, Path path) {\n Path relative = root.relativize(path);\n return Files.isDirectory(path) && !relative.toString().endsWith(\"/\") ? String.format(\"%s/\", relative.toString()) : relative.toString();\n }", "public int readFrom(ByteBuffer src, long destOffset) {\n if (src.remaining() + destOffset >= size())\n throw new BufferOverflowException();\n int readLen = src.remaining();\n ByteBuffer b = toDirectByteBuffer(destOffset, readLen);\n b.position(0);\n b.put(src);\n return readLen;\n }", "private void persistEnabledVersion(long version) throws PersistenceFailureException {\n File disabledMarker = getDisabledMarkerFile(version);\n if (disabledMarker.exists()) {\n if (!disabledMarker.delete()) {\n throw new PersistenceFailureException(\"Failed to create the disabled marker at path: \" +\n disabledMarker.getAbsolutePath() + \"\\nThe store/version \" +\n \"will remain enabled only until the next restart.\");\n }\n }\n }", "public static base_response add(nitro_service client, snmpuser resource) throws Exception {\n\t\tsnmpuser addresource = new snmpuser();\n\t\taddresource.name = resource.name;\n\t\taddresource.group = resource.group;\n\t\taddresource.authtype = resource.authtype;\n\t\taddresource.authpasswd = resource.authpasswd;\n\t\taddresource.privtype = resource.privtype;\n\t\taddresource.privpasswd = resource.privpasswd;\n\t\treturn addresource.add_resource(client);\n\t}", "private static boolean isDpiSet(final Multimap<String, String> extraParams) {\n String searchKey = \"FORMAT_OPTIONS\";\n for (String key: extraParams.keys()) {\n if (key.equalsIgnoreCase(searchKey)) {\n for (String value: extraParams.get(key)) {\n if (value.toLowerCase().contains(\"dpi:\")) {\n return true;\n }\n }\n }\n }\n return false;\n }", "protected final void error(final HttpServletResponse httpServletResponse, final Throwable e) {\n httpServletResponse.setContentType(\"text/plain\");\n httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());\n try (PrintWriter out = httpServletResponse.getWriter()) {\n out.println(\"Error while processing request:\");\n LOGGER.error(\"Error while processing request\", e);\n } catch (IOException ex) {\n throw ExceptionUtils.getRuntimeException(ex);\n }\n }", "private boolean skipBar(Row row)\n {\n List<Row> childRows = row.getChildRows();\n return childRows.size() == 1 && childRows.get(0).getChildRows().isEmpty();\n }" ]
set proper expression text invoking the DJCRosstabMeasurePrecalculatedTotalProvider for the cell @param auxRows @param auxCols @param measureExp @param djmeasure @param crosstabColumn @param crosstabRow @param meausrePrefix
[ "private void setExpressionForPrecalculatedTotalValue(\n\t\t\tDJCrosstabColumn[] auxCols, DJCrosstabRow[] auxRows, JRDesignExpression measureExp, DJCrosstabMeasure djmeasure,\n\t\t\tDJCrosstabColumn crosstabColumn, DJCrosstabRow crosstabRow, String meausrePrefix) {\n\n\t\tString rowValuesExp = \"new Object[]{\";\n\t\tString rowPropsExp = \"new String[]{\";\n\t\tfor (int i = 0; i < auxRows.length; i++) {\n\t\t\tif (auxRows[i].getProperty()== null)\n\t\t\t\tcontinue;\n\t\t\trowValuesExp += \"$V{\" + auxRows[i].getProperty().getProperty() +\"}\";\n\t\t\trowPropsExp += \"\\\"\" + auxRows[i].getProperty().getProperty() +\"\\\"\";\n\t\t\tif (i+1<auxRows.length && auxRows[i+1].getProperty()!= null){\n\t\t\t\trowValuesExp += \", \";\n\t\t\t\trowPropsExp += \", \";\n\t\t\t}\n\t\t}\n\t\trowValuesExp += \"}\";\n\t\trowPropsExp += \"}\";\n\n\t\tString colValuesExp = \"new Object[]{\";\n\t\tString colPropsExp = \"new String[]{\";\n\t\tfor (int i = 0; i < auxCols.length; i++) {\n\t\t\tif (auxCols[i].getProperty()== null)\n\t\t\t\tcontinue;\n\t\t\tcolValuesExp += \"$V{\" + auxCols[i].getProperty().getProperty() +\"}\";\n\t\t\tcolPropsExp += \"\\\"\" + auxCols[i].getProperty().getProperty() +\"\\\"\";\n\t\t\tif (i+1<auxCols.length && auxCols[i+1].getProperty()!= null){\n\t\t\t\tcolValuesExp += \", \";\n\t\t\t\tcolPropsExp += \", \";\n\t\t\t}\n\t\t}\n\t\tcolValuesExp += \"}\";\n\t\tcolPropsExp += \"}\";\n\n\t\tString measureProperty = meausrePrefix + djmeasure.getProperty().getProperty();\n\t\tString expText = \"(((\"+DJCRosstabMeasurePrecalculatedTotalProvider.class.getName()+\")$P{crosstab-measure__\"+measureProperty+\"_totalProvider}).getValueFor( \"\n\t\t+ colPropsExp +\", \"\n\t\t+ colValuesExp +\", \"\n\t\t+ rowPropsExp\n\t\t+ \", \"\n\t\t+ rowValuesExp\n\t\t+\" ))\";\n\n\t\tif (djmeasure.getValueFormatter() != null){\n\n\t\t\tString fieldsMap = ExpressionUtils.getTextForFieldsFromScriptlet();\n\t\t\tString parametersMap = ExpressionUtils.getTextForParametersFromScriptlet();\n\t\t\tString variablesMap = ExpressionUtils.getTextForVariablesFromScriptlet();\n\n\t\t\tString stringExpression = \"(((\"+DJValueFormatter.class.getName()+\")$P{crosstab-measure__\"+measureProperty+\"_vf}).evaluate( \"\n\t\t\t\t+ \"(\"+expText+\"), \" + fieldsMap +\", \" + variablesMap + \", \" + parametersMap +\" ))\";\n\n\t\t\tmeasureExp.setText(stringExpression);\n\t\t\tmeasureExp.setValueClassName(djmeasure.getValueFormatter().getClassName());\n\t\t} else {\n\n//\t\t\tString expText = \"(((\"+DJCRosstabMeasurePrecalculatedTotalProvider.class.getName()+\")$P{crosstab-measure__\"+djmeasure.getProperty().getProperty()+\"_totalProvider}).getValueFor( \"\n//\t\t\t+ colPropsExp +\", \"\n//\t\t\t+ colValuesExp +\", \"\n//\t\t\t+ rowPropsExp\n//\t\t\t+ \", \"\n//\t\t\t+ rowValuesExp\n//\t\t\t+\" ))\";\n//\n\t\t\tlog.debug(\"text for crosstab total provider is: \" + expText);\n\n\t\t\tmeasureExp.setText(expText);\n//\t\t\tmeasureExp.setValueClassName(djmeasure.getValueFormatter().getClassName());\n\t\t\tString valueClassNameForOperation = ExpressionUtils.getValueClassNameForOperation(djmeasure.getOperation(),djmeasure.getProperty());\n\t\t\tmeasureExp.setValueClassName(valueClassNameForOperation);\n\t\t}\n\n\t}" ]
[ "public EndpointOverride getPath(int pathId, String clientUUID, String[] filters) throws Exception {\n EndpointOverride endpoint = null;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = this.getPathSelectString();\n queryString += \" AND \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID + \"=\" + pathId + \";\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n\n results = statement.executeQuery();\n\n if (results.next()) {\n endpoint = this.getEndpointOverrideFromResultSet(results);\n endpoint.setFilters(filters);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return endpoint;\n }", "private void readAssignment(Resource resource, Assignment assignment)\n {\n Task task = m_activityMap.get(assignment.getActivity());\n if (task != null)\n {\n task.addResourceAssignment(resource);\n }\n }", "public void addFkToItemClass(String column)\r\n {\r\n if (fksToItemClass == null)\r\n {\r\n fksToItemClass = new Vector();\r\n }\r\n fksToItemClass.add(column);\r\n fksToItemClassAry = null;\r\n }", "public static void load(File file)\n {\n try(FileInputStream inputStream = new FileInputStream(file))\n {\n LineIterator it = IOUtils.lineIterator(inputStream, \"UTF-8\");\n while (it.hasNext())\n {\n String line = it.next();\n if (!line.startsWith(\"#\") && !line.trim().isEmpty())\n {\n add(line);\n }\n }\n }\n catch (Exception e)\n {\n throw new WindupException(\"Failed loading archive ignore patterns from [\" + file.toString() + \"]\", e);\n }\n }", "public Duration getWork(FastTrackField type)\n {\n Double value = (Double) getObject(type);\n return value == null ? null : Duration.getInstance(value.doubleValue(), m_table.getWorkTimeUnit());\n }", "public static base_response add(nitro_service client, nsip6 resource) throws Exception {\n\t\tnsip6 addresource = new nsip6();\n\t\taddresource.ipv6address = resource.ipv6address;\n\t\taddresource.scope = resource.scope;\n\t\taddresource.type = resource.type;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.nd = resource.nd;\n\t\taddresource.icmp = resource.icmp;\n\t\taddresource.vserver = resource.vserver;\n\t\taddresource.telnet = resource.telnet;\n\t\taddresource.ftp = resource.ftp;\n\t\taddresource.gui = resource.gui;\n\t\taddresource.ssh = resource.ssh;\n\t\taddresource.snmp = resource.snmp;\n\t\taddresource.mgmtaccess = resource.mgmtaccess;\n\t\taddresource.restrictaccess = resource.restrictaccess;\n\t\taddresource.dynamicrouting = resource.dynamicrouting;\n\t\taddresource.hostroute = resource.hostroute;\n\t\taddresource.ip6hostrtgw = resource.ip6hostrtgw;\n\t\taddresource.metric = resource.metric;\n\t\taddresource.vserverrhilevel = resource.vserverrhilevel;\n\t\taddresource.ospf6lsatype = resource.ospf6lsatype;\n\t\taddresource.ospfarea = resource.ospfarea;\n\t\taddresource.state = resource.state;\n\t\taddresource.map = resource.map;\n\t\taddresource.ownernode = resource.ownernode;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}", "public Map<String, ClientWidgetInfo> securityClone(Map<String, ClientWidgetInfo> widgetInfo) {\n\t\tMap<String, ClientWidgetInfo> res = new HashMap<String, ClientWidgetInfo>();\n\t\tfor (Map.Entry<String, ClientWidgetInfo> entry : widgetInfo.entrySet()) {\n\t\t\tClientWidgetInfo value = entry.getValue();\n\t\t\tif (!(value instanceof ServerSideOnlyInfo)) {\n\t\t\t\tres.put(entry.getKey(), value);\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}", "@Override\n protected void addBuildInfoProperties(BuildInfoBuilder builder) {\n if (envVars != null) {\n for (Map.Entry<String, String> entry : envVars.entrySet()) {\n builder.addProperty(BuildInfoProperties.BUILD_INFO_ENVIRONMENT_PREFIX + entry.getKey(), entry.getValue());\n }\n }\n\n if (sysVars != null) {\n for (Map.Entry<String, String> entry : sysVars.entrySet()) {\n builder.addProperty(entry.getKey(), entry.getValue());\n }\n }\n }", "@Override\n public void onKeyDown(KeyDownEvent event) {\n\tchar c = MiscUtils.getCharCode(event.getNativeEvent());\n\tonKeyCodeEvent(event, box.getValue()+c);\n }" ]
Updates event definitions for all throwing events. @param def Definitions
[ "public void revisitThrowEvents(Definitions def) {\n List<RootElement> rootElements = def.getRootElements();\n List<Signal> toAddSignals = new ArrayList<Signal>();\n Set<Error> toAddErrors = new HashSet<Error>();\n Set<Escalation> toAddEscalations = new HashSet<Escalation>();\n Set<Message> toAddMessages = new HashSet<Message>();\n Set<ItemDefinition> toAddItemDefinitions = new HashSet<ItemDefinition>();\n for (RootElement root : rootElements) {\n if (root instanceof Process) {\n setThrowEventsInfo((Process) root,\n def,\n rootElements,\n toAddSignals,\n toAddErrors,\n toAddEscalations,\n toAddMessages,\n toAddItemDefinitions);\n }\n }\n for (Lane lane : _lanes) {\n setThrowEventsInfoForLanes(lane,\n def,\n rootElements,\n toAddSignals,\n toAddErrors,\n toAddEscalations,\n toAddMessages,\n toAddItemDefinitions);\n }\n for (Signal s : toAddSignals) {\n def.getRootElements().add(s);\n }\n for (Error er : toAddErrors) {\n def.getRootElements().add(er);\n }\n for (Escalation es : toAddEscalations) {\n def.getRootElements().add(es);\n }\n for (ItemDefinition idef : toAddItemDefinitions) {\n def.getRootElements().add(idef);\n }\n for (Message msg : toAddMessages) {\n def.getRootElements().add(msg);\n }\n }" ]
[ "public PhotoAllContext getAllContexts(String photoId) throws FlickrException {\r\n PhotoSetList<PhotoSet> setList = new PhotoSetList<PhotoSet>();\r\n PoolList<Pool> poolList = new PoolList<Pool>();\r\n PhotoAllContext allContext = new PhotoAllContext();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_ALL_CONTEXTS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Collection<Element> photosElement = response.getPayloadCollection();\r\n\r\n for (Element setElement : photosElement) {\r\n if (setElement.getTagName().equals(\"set\")) {\r\n PhotoSet pset = new PhotoSet();\r\n pset.setTitle(setElement.getAttribute(\"title\"));\r\n pset.setSecret(setElement.getAttribute(\"secret\"));\r\n pset.setId(setElement.getAttribute(\"id\"));\r\n pset.setFarm(setElement.getAttribute(\"farm\"));\r\n pset.setPrimary(setElement.getAttribute(\"primary\"));\r\n pset.setServer(setElement.getAttribute(\"server\"));\r\n pset.setViewCount(Integer.parseInt(setElement.getAttribute(\"view_count\")));\r\n pset.setCommentCount(Integer.parseInt(setElement.getAttribute(\"comment_count\")));\r\n pset.setCountPhoto(Integer.parseInt(setElement.getAttribute(\"count_photo\")));\r\n pset.setCountVideo(Integer.parseInt(setElement.getAttribute(\"count_video\")));\r\n setList.add(pset);\r\n allContext.setPhotoSetList(setList);\r\n } else if (setElement.getTagName().equals(\"pool\")) {\r\n Pool pool = new Pool();\r\n pool.setTitle(setElement.getAttribute(\"title\"));\r\n pool.setId(setElement.getAttribute(\"id\"));\r\n pool.setUrl(setElement.getAttribute(\"url\"));\r\n pool.setIconServer(setElement.getAttribute(\"iconserver\"));\r\n pool.setIconFarm(setElement.getAttribute(\"iconfarm\"));\r\n pool.setMemberCount(Integer.parseInt(setElement.getAttribute(\"members\")));\r\n pool.setPoolCount(Integer.parseInt(setElement.getAttribute(\"pool_count\")));\r\n poolList.add(pool);\r\n allContext.setPoolList(poolList);\r\n }\r\n }\r\n\r\n return allContext;\r\n\r\n }", "private void processDefaultCurrency(Integer currencyID) throws SQLException\n {\n List<Row> rows = getRows(\"select * from \" + m_schema + \"currtype where curr_id=?\", currencyID);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n m_reader.processDefaultCurrency(row);\n }\n }", "public ChannelInfo getChannel(String name) {\n final URI uri = uriWithPath(\"./channels/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, ChannelInfo.class);\n }", "private void processSubProjects()\n {\n int subprojectIndex = 1;\n for (Task task : m_project.getTasks())\n {\n String subProjectFileName = task.getSubprojectName();\n if (subProjectFileName != null)\n {\n String fileName = subProjectFileName;\n int offset = 0x01000000 + (subprojectIndex * 0x00400000);\n int index = subProjectFileName.lastIndexOf('\\\\');\n if (index != -1)\n {\n fileName = subProjectFileName.substring(index + 1);\n }\n\n SubProject sp = new SubProject();\n sp.setFileName(fileName);\n sp.setFullPath(subProjectFileName);\n sp.setUniqueIDOffset(Integer.valueOf(offset));\n sp.setTaskUniqueID(task.getUniqueID());\n task.setSubProject(sp);\n\n ++subprojectIndex;\n }\n }\n }", "private static int findTrackIdAtOffset(SlotReference slot, Client client, int offset) throws IOException {\n Message entry = client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot.slot, CdjStatus.TrackType.REKORDBOX, offset, 1).get(0);\n if (entry.getMenuItemType() == Message.MenuItemType.UNKNOWN) {\n logger.warn(\"Encountered unrecognized track list entry item type: {}\", entry);\n }\n return (int)((NumberField)entry.arguments.get(1)).getValue();\n }", "public static <T> T assertNull(T value, String message) {\n if (value != null)\n throw new IllegalStateException(message);\n return value;\n }", "public void setColorRange(int firstIndex, int lastIndex, int color1, int color2) {\n\t\tfor (int i = firstIndex; i <= lastIndex; i++)\n\t\t\tmap[i] = ImageMath.mixColors((float)(i-firstIndex)/(lastIndex-firstIndex), color1, color2);\n\t}", "private void processResources() throws SQLException\n {\n List<Row> rows = getRows(\"select * from zresource where zproject=? order by zorderinproject\", m_projectID);\n for (Row row : rows)\n {\n Resource resource = m_project.addResource();\n resource.setUniqueID(row.getInteger(\"Z_PK\"));\n resource.setEmailAddress(row.getString(\"ZEMAIL\"));\n resource.setInitials(row.getString(\"ZINITIALS\"));\n resource.setName(row.getString(\"ZTITLE_\"));\n resource.setGUID(row.getUUID(\"ZUNIQUEID\"));\n resource.setType(row.getResourceType(\"ZTYPE\"));\n resource.setMaterialLabel(row.getString(\"ZMATERIALUNIT\"));\n\n if (resource.getType() == ResourceType.WORK)\n {\n resource.setMaxUnits(Double.valueOf(NumberHelper.getDouble(row.getDouble(\"ZAVAILABLEUNITS_\")) * 100.0));\n }\n\n Integer calendarID = row.getInteger(\"ZRESOURCECALENDAR\");\n if (calendarID != null)\n {\n ProjectCalendar calendar = m_project.getCalendarByUniqueID(calendarID);\n if (calendar != null)\n {\n calendar.setName(resource.getName());\n resource.setResourceCalendar(calendar);\n }\n }\n\n m_eventManager.fireResourceReadEvent(resource);\n }\n }", "@SuppressWarnings(\"boxing\")\r\n public OAuth1Token getAccessToken(OAuth1RequestToken oAuthRequestToken, String verifier) {\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .build(FlickrApi.instance());\r\n\r\n // Flickr seems to return invalid token sometimes so retry a few times.\r\n // See http://www.flickr.com/groups/api/discuss/72157628028927244/\r\n OAuth1Token accessToken = null;\r\n boolean success = false;\r\n for (int i = 0; i < maxGetTokenRetries && !success; i++) {\r\n try {\r\n accessToken = service.getAccessToken(oAuthRequestToken, verifier);\r\n success = true;\r\n } catch (OAuthException | IOException | InterruptedException | ExecutionException e) {\r\n if (i == maxGetTokenRetries - 1) {\r\n logger.error(String.format(\"OAuthService.getAccessToken failing after %d tries, re-throwing exception\", i), e);\r\n throw new FlickrRuntimeException(e);\r\n } else {\r\n logger.warn(String.format(\"OAuthService.getAccessToken failed, try number %d: %s\", i, e.getMessage()));\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException ie) {\r\n // Do nothing\r\n }\r\n }\r\n }\r\n }\r\n\r\n return accessToken;\r\n }" ]
Checks if this has the passed prefix @param prefix is a Bytes object to compare to this @return true or false @since 1.1.0
[ "public boolean startsWith(Bytes prefix) {\n Objects.requireNonNull(prefix, \"startWith(Bytes prefix) cannot have null parameter\");\n\n if (prefix.length > this.length) {\n return false;\n } else {\n int end = this.offset + prefix.length;\n for (int i = this.offset, j = prefix.offset; i < end; i++, j++) {\n if (this.data[i] != prefix.data[j]) {\n return false;\n }\n }\n }\n return true;\n }" ]
[ "public Path relativize(Path other) {\n\t\tif (other.isAbsolute() != isAbsolute())\n\t\t\tthrow new IllegalArgumentException(\"This path and the given path are not both absolute or both relative: \" + toString() + \" | \" + other.toString());\n\t\tif (startsWith(other)) {\n\t\t\treturn internalRelativize(this, other);\n\t\t} else if (other.startsWith(this)) {\n\t\t\treturn internalRelativize(other, this);\n\t\t}\n\t\treturn null;\n\t}", "@Deprecated\r\n public Location resolvePlaceURL(String flickrPlacesUrl) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_RESOLVE_PLACE_URL);\r\n\r\n parameters.put(\"url\", flickrPlacesUrl);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }", "public static base_responses delete(nitro_service client, String serverip[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (serverip != null && serverip.length > 0) {\n\t\t\tntpserver deleteresources[] = new ntpserver[serverip.length];\n\t\t\tfor (int i=0;i<serverip.length;i++){\n\t\t\t\tdeleteresources[i] = new ntpserver();\n\t\t\t\tdeleteresources[i].serverip = serverip[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "private void writePropertyData() {\n\t\ttry (PrintStream out = new PrintStream(openResultFileOuputStream(\n\t\t\t\tresultDirectory, \"properties.json\"))) {\n\t\t\tout.println(\"{\");\n\n\t\t\tint count = 0;\n\t\t\tfor (Entry<Integer, PropertyRecord> propertyEntry : this.propertyRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (count > 0) {\n\t\t\t\t\tout.println(\",\");\n\t\t\t\t}\n\t\t\t\tout.print(\"\\\"\" + propertyEntry.getKey() + \"\\\":\");\n\t\t\t\tmapper.writeValue(out, propertyEntry.getValue());\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tout.println(\"\\n}\");\n\n\t\t\tSystem.out.println(\" Serialized information for \" + count\n\t\t\t\t\t+ \" properties.\");\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "public static LocalDate getDateFromFloatingPointDate(LocalDate referenceDate, double floatingPointDate) {\n\t\tif(referenceDate == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn referenceDate.plusDays((int)Math.round(floatingPointDate*365.0));\n\t}", "public static boolean hasAnyAnnotation(AnnotatedNode node, String... names) {\r\n for (String name : names) {\r\n if (hasAnnotation(node, name)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "private static EventTypeEnum mapEventTypeEnum(EventEnumType eventType) {\n if (eventType != null) {\n return EventTypeEnum.valueOf(eventType.name());\n }\n return EventTypeEnum.UNKNOWN;\n }", "protected I_CmsSearchConfigurationFacetField parseFieldFacet(JSONObject fieldFacetObject) {\n\n try {\n String field = fieldFacetObject.getString(JSON_KEY_FACET_FIELD);\n String name = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_NAME);\n String label = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_LABEL);\n Integer minCount = parseOptionalIntValue(fieldFacetObject, JSON_KEY_FACET_MINCOUNT);\n Integer limit = parseOptionalIntValue(fieldFacetObject, JSON_KEY_FACET_LIMIT);\n String prefix = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_PREFIX);\n String sorder = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_ORDER);\n I_CmsSearchConfigurationFacet.SortOrder order;\n try {\n order = I_CmsSearchConfigurationFacet.SortOrder.valueOf(sorder);\n } catch (Exception e) {\n order = null;\n }\n String filterQueryModifier = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_FILTERQUERYMODIFIER);\n Boolean isAndFacet = parseOptionalBooleanValue(fieldFacetObject, JSON_KEY_FACET_ISANDFACET);\n List<String> preselection = parseOptionalStringValues(fieldFacetObject, JSON_KEY_FACET_PRESELECTION);\n Boolean ignoreFilterAllFacetFilters = parseOptionalBooleanValue(\n fieldFacetObject,\n JSON_KEY_FACET_IGNOREALLFACETFILTERS);\n return new CmsSearchConfigurationFacetField(\n field,\n name,\n minCount,\n limit,\n prefix,\n label,\n order,\n filterQueryModifier,\n isAndFacet,\n preselection,\n ignoreFilterAllFacetFilters);\n } catch (JSONException e) {\n LOG.error(\n Messages.get().getBundle().key(Messages.ERR_FIELD_FACET_MANDATORY_KEY_MISSING_1, JSON_KEY_FACET_FIELD),\n e);\n return null;\n }\n }", "@Override\r\n public String upload(byte[] data, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(data);\r\n return sendUploadRequest(metaData, payload);\r\n }" ]
Concat a List into a CSV String. @param list list to concat @return csv string
[ "private String listToCSV(List<String> list) {\n String csvStr = \"\";\n for (String item : list) {\n csvStr += \",\" + item;\n }\n\n return csvStr.length() > 1 ? csvStr.substring(1) : csvStr;\n }" ]
[ "public static void Shuffle(double[] array, long seed) {\n Random random = new Random();\n if (seed != 0) random.setSeed(seed);\n\n for (int i = array.length - 1; i > 0; i--) {\n int index = random.nextInt(i + 1);\n double temp = array[index];\n array[index] = array[i];\n array[i] = temp;\n }\n }", "public static String common() {\n String common = SysProps.get(KEY_COMMON_CONF_TAG);\n if (S.blank(common)) {\n common = \"common\";\n }\n return common;\n }", "public static <T> FastEvent<T> of(Class<T> type, BeanManagerImpl manager, ObserverNotifier notifier, Annotation... qualifiers) {\n ResolvedObservers<T> resolvedObserverMethods = notifier.<T> resolveObserverMethods(type, qualifiers);\n if (resolvedObserverMethods.isMetadataRequired()) {\n EventMetadata metadata = new EventMetadataImpl(type, null, qualifiers);\n CurrentEventMetadata metadataService = manager.getServices().get(CurrentEventMetadata.class);\n return new FastEventWithMetadataPropagation<T>(resolvedObserverMethods, metadata, metadataService);\n } else {\n return new FastEvent<T>(resolvedObserverMethods);\n }\n }", "public int executeUpdate(String query) throws Exception {\n int returnVal = 0;\n Statement queryStatement = null;\n\n try (Connection sqlConnection = getConnection()) {\n queryStatement = sqlConnection.createStatement();\n returnVal = queryStatement.executeUpdate(query);\n } catch (Exception e) {\n } finally {\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return returnVal;\n }", "void fileWritten() throws ConfigurationPersistenceException {\n if (!doneBootup.get() || interactionPolicy.isReadOnly()) {\n return;\n }\n try {\n FilePersistenceUtils.copyFile(mainFile, lastFile);\n } catch (IOException e) {\n throw ControllerLogger.ROOT_LOGGER.failedToBackup(e, mainFile);\n }\n }", "private static Originator mapOriginatorType(OriginatorType originatorType) {\n Originator originator = new Originator();\n if (originatorType != null) {\n originator.setCustomId(originatorType.getCustomId());\n originator.setHostname(originatorType.getHostname());\n originator.setIp(originatorType.getIp());\n originator.setProcessId(originatorType.getProcessId());\n originator.setPrincipal(originatorType.getPrincipal());\n }\n return originator;\n }", "public Date getFinishTime(Date date)\n {\n Date result = null;\n\n if (date != null)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, null);\n if (ranges == null)\n {\n result = getParentFile().getProjectProperties().getDefaultEndTime();\n result = DateHelper.getCanonicalTime(result);\n }\n else\n {\n Date rangeStart = result = ranges.getRange(0).getStart();\n Date rangeFinish = ranges.getRange(ranges.getRangeCount() - 1).getEnd();\n Date startDay = DateHelper.getDayStartDate(rangeStart);\n Date finishDay = DateHelper.getDayStartDate(rangeFinish);\n\n result = DateHelper.getCanonicalTime(rangeFinish);\n\n //\n // Handle the case where the end of the range is at midnight -\n // this will show up as the start and end days not matching\n //\n if (startDay != null && finishDay != null && startDay.getTime() != finishDay.getTime())\n {\n result = DateHelper.addDays(result, 1);\n }\n }\n }\n return result;\n }", "public void symm2x2_fast( double a11 , double a12, double a22 )\n {\n// double p = (a11 - a22)*0.5;\n// double r = Math.sqrt(p*p + a12*a12);\n//\n// value0.real = a22 + a12*a12/(r-p);\n// value1.real = a22 - a12*a12/(r+p);\n// }\n//\n// public void symm2x2_std( double a11 , double a12, double a22 )\n// {\n double left = (a11+a22)*0.5;\n double b = (a11-a22)*0.5;\n double right = Math.sqrt(b*b+a12*a12);\n value0.real = left + right;\n value1.real = left - right;\n }", "protected List<String> parseWords(String line) {\n List<String> words = new ArrayList<String>();\n boolean insideWord = !isSpace(line.charAt(0));\n int last = 0;\n for( int i = 0; i < line.length(); i++) {\n char c = line.charAt(i);\n\n if( insideWord ) {\n // see if its at the end of a word\n if( isSpace(c)) {\n words.add( line.substring(last,i) );\n insideWord = false;\n }\n } else {\n if( !isSpace(c)) {\n last = i;\n insideWord = true;\n }\n }\n }\n\n // if the line ended add the final word\n if( insideWord ) {\n words.add( line.substring(last));\n }\n return words;\n }" ]
Return true if the Declaration can be linked to the ImporterService. @param declaration The Declaration @param declarationBinderRef The ServiceReference<ImporterService> of the ImporterService @return true if the Declaration can be linked to the ImporterService
[ "public boolean canBeLinked(D declaration, ServiceReference<S> declarationBinderRef) {\n // Evaluate the target filter of the ImporterService on the Declaration\n Filter filter = bindersManager.getTargetFilter(declarationBinderRef);\n return filter.matches(declaration.getMetadata());\n }" ]
[ "public String format() {\r\n if (getName().equals(\"*\")) {\r\n return \"*\";\r\n }\r\n else {\r\n StringBuilder sb = new StringBuilder();\r\n if (isWeak()) {\r\n sb.append(\"W/\");\r\n }\r\n return sb.append('\"').append(getName()).append('\"').toString();\r\n }\r\n }", "public void fetchUninitializedAttributes() {\n for (String prefixedId : getPrefixedAttributeNames()) {\n BeanIdentifier id = getNamingScheme().deprefix(prefixedId);\n if (!beanStore.contains(id)) {\n ContextualInstance<?> instance = (ContextualInstance<?>) getAttribute(prefixedId);\n beanStore.put(id, instance);\n ContextLogger.LOG.addingDetachedContextualUnderId(instance, id);\n }\n }\n }", "public ContentAssistContext.Builder copy() {\n\t\tBuilder result = builderProvider.get();\n\t\tresult.copyFrom(this);\n\t\treturn result;\n\t}", "private ColorItem buildColorItem(int colorId, String label) {\n Color color;\n String colorName;\n switch (colorId) {\n case 0:\n color = new Color(0, 0, 0, 0);\n colorName = \"No Color\";\n break;\n case 1:\n color = Color.PINK;\n colorName = \"Pink\";\n break;\n case 2:\n color = Color.RED;\n colorName = \"Red\";\n break;\n case 3:\n color = Color.ORANGE;\n colorName = \"Orange\";\n break;\n case 4:\n color = Color.YELLOW;\n colorName = \"Yellow\";\n break;\n case 5:\n color = Color.GREEN;\n colorName = \"Green\";\n break;\n case 6:\n color = Color.CYAN;\n colorName = \"Aqua\";\n break;\n case 7:\n color = Color.BLUE;\n colorName = \"Blue\";\n break;\n case 8:\n color = new Color(128, 0, 128);\n colorName = \"Purple\";\n break;\n default:\n color = new Color(0, 0, 0, 0);\n colorName = \"Unknown Color\";\n }\n return new ColorItem(colorId, label, color, colorName);\n }", "public final void notifyFooterItemRangeChanged(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemRangeChanged(positionStart + headerItemCount + contentItemCount, itemCount);\n }", "@Override\r\n\tpublic Token recoverInline(Parser recognizer) throws RecognitionException\r\n\t{\r\n\t\t// SINGLE TOKEN DELETION\r\n\t\tToken matchedSymbol = singleTokenDeletion(recognizer);\r\n\t\tif (matchedSymbol != null)\r\n\t\t{\r\n\t\t\t// we have deleted the extra token.\r\n\t\t\t// now, move past ttype token as if all were ok\r\n\t\t\trecognizer.consume();\r\n\t\t\treturn matchedSymbol;\r\n\t\t}\r\n\r\n\t\t// SINGLE TOKEN INSERTION\r\n\t\tif (singleTokenInsertion(recognizer))\r\n\t\t{\r\n\t\t\treturn getMissingSymbol(recognizer);\r\n\t\t}\r\n\t\t\r\n//\t\tBeetlException exception = new BeetlParserException(BeetlException.PARSER_MISS_ERROR);\r\n//\t\texception.pushToken(this.getGrammarToken(recognizer.getCurrentToken()));\r\n//\t\tthrow exception;\r\n\t\tthrow new InputMismatchException(recognizer);\r\n\t}", "protected Map<String, String> getGalleryOpenParams(\n CmsObject cms,\n CmsMessages messages,\n I_CmsWidgetParameter param,\n String resource,\n long hashId) {\n\n Map<String, String> result = new HashMap<String, String>();\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_MODE, A_CmsAjaxGallery.MODE_WIDGET);\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_STORAGE_PREFIX, getGalleryStoragePrefix());\n result.put(I_CmsGalleryProviderConstants.CONFIG_RESOURCE_TYPES, getGalleryTypes());\n if (param.getId() != null) {\n result.put(I_CmsGalleryProviderConstants.KEY_FIELD_ID, param.getId());\n // use javascript to read the current field value\n result.put(\n I_CmsGalleryProviderConstants.CONFIG_CURRENT_ELEMENT,\n \"'+document.getElementById('\" + param.getId() + \"').getAttribute('value')+'\");\n }\n result.put(I_CmsGalleryProviderConstants.KEY_HASH_ID, \"\" + hashId);\n // the edited resource\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(resource)) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_REFERENCE_PATH, resource);\n }\n // the start up gallery path\n CmsGalleryWidgetConfiguration configuration = getWidgetConfiguration(cms, messages, param);\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(configuration.getStartup())) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_PATH, configuration.getStartup());\n }\n // set gallery types if available\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(configuration.getGalleryTypes())) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_TYPES, configuration.getGalleryTypes());\n }\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_NAME, getGalleryName());\n return result;\n }", "private void addExceptionRange(ProjectCalendarException exception, Date start, Date finish)\n {\n if (start != null && finish != null)\n {\n exception.addRange(new DateRange(start, finish));\n }\n }", "static String createStatsType(Set<String> statsItems, String sortType,\n MtasFunctionParserFunction functionParser) {\n String statsType = STATS_BASIC;\n for (String statsItem : statsItems) {\n if (STATS_FULL_TYPES.contains(statsItem)) {\n statsType = STATS_FULL;\n break;\n } else if (STATS_ADVANCED_TYPES.contains(statsItem)) {\n statsType = STATS_ADVANCED;\n } else if (statsType != STATS_ADVANCED\n && STATS_BASIC_TYPES.contains(statsItem)) {\n statsType = STATS_BASIC;\n } else {\n Matcher m = fpStatsFunctionItems.matcher(statsItem.trim());\n if (m.find()) {\n if (STATS_FUNCTIONS.contains(m.group(2).trim())) {\n statsType = STATS_FULL;\n break;\n }\n }\n }\n }\n if (sortType != null && STATS_TYPES.contains(sortType)) {\n if (STATS_FULL_TYPES.contains(sortType)) {\n statsType = STATS_FULL;\n } else if (STATS_ADVANCED_TYPES.contains(sortType)) {\n statsType = (statsType == null || statsType != STATS_FULL)\n ? STATS_ADVANCED : statsType;\n }\n }\n return statsType;\n }" ]
Resolve the single type argument of the given generic interface against the given target method which is assumed to return the given interface or an implementation of it. @param method the target method to check the return type of @param genericIfc the generic interface or superclass to resolve the type argument from @return the resolved parameter type of the method return type, or {@code null} if not resolvable or if the single argument is of type {@link WildcardType}.
[ "public static Class<?> resolveReturnTypeArgument(Method method, Class<?> genericIfc) {\n\t\tAssert.notNull(method, \"method must not be null\");\n\t\tType returnType = method.getReturnType();\n\t\tType genericReturnType = method.getGenericReturnType();\n\t\tif (returnType.equals(genericIfc)) {\n\t\t\tif (genericReturnType instanceof ParameterizedType) {\n\t\t\t\tParameterizedType targetType = (ParameterizedType) genericReturnType;\n\t\t\t\tType[] actualTypeArguments = targetType.getActualTypeArguments();\n\t\t\t\tType typeArg = actualTypeArguments[0];\n\t\t\t\tif (!(typeArg instanceof WildcardType)) {\n\t\t\t\t\treturn (Class<?>) typeArg;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn resolveTypeArgument((Class<?>) returnType, genericIfc);\n\t}" ]
[ "public void restore(String state) {\n JsonObject json = JsonObject.readFrom(state);\n String accessToken = json.get(\"accessToken\").asString();\n String refreshToken = json.get(\"refreshToken\").asString();\n long lastRefresh = json.get(\"lastRefresh\").asLong();\n long expires = json.get(\"expires\").asLong();\n String userAgent = json.get(\"userAgent\").asString();\n String tokenURL = json.get(\"tokenURL\").asString();\n String baseURL = json.get(\"baseURL\").asString();\n String baseUploadURL = json.get(\"baseUploadURL\").asString();\n boolean autoRefresh = json.get(\"autoRefresh\").asBoolean();\n int maxRequestAttempts = json.get(\"maxRequestAttempts\").asInt();\n\n this.accessToken = accessToken;\n this.refreshToken = refreshToken;\n this.lastRefresh = lastRefresh;\n this.expires = expires;\n this.userAgent = userAgent;\n this.tokenURL = tokenURL;\n this.baseURL = baseURL;\n this.baseUploadURL = baseUploadURL;\n this.autoRefresh = autoRefresh;\n this.maxRequestAttempts = maxRequestAttempts;\n }", "void nextExecuted(String sql) throws SQLException\r\n {\r\n count++;\r\n\r\n if (_order.contains(sql))\r\n {\r\n return;\r\n }\r\n\r\n String sqlCmd = sql.substring(0, 7);\r\n String rest = sql.substring(sqlCmd.equals(\"UPDATE \") ? 7 // \"UPDATE \"\r\n : 12); // \"INSERT INTO \" or \"DELETE FROM \"\r\n String tableName = rest.substring(0, rest.indexOf(' '));\r\n HashSet fkTables = (HashSet) _fkInfo.get(tableName);\r\n\r\n // we should not change order of INSERT/DELETE/UPDATE\r\n // statements for the same table\r\n if (_touched.contains(tableName))\r\n {\r\n executeBatch();\r\n }\r\n if (sqlCmd.equals(\"INSERT \"))\r\n {\r\n if (_dontInsert != null && _dontInsert.contains(tableName))\r\n {\r\n // one of the previous INSERTs contained a table\r\n // that references this table.\r\n // Let's execute that previous INSERT right now so that\r\n // in the future INSERTs into this table will go first\r\n // in the _order array.\r\n executeBatch();\r\n }\r\n }\r\n else\r\n //if (sqlCmd.equals(\"DELETE \") || sqlCmd.equals(\"UPDATE \"))\r\n {\r\n // We process UPDATEs in the same way as DELETEs\r\n // because setting FK to NULL in UPDATE is equivalent\r\n // to DELETE from the referential integrity point of view.\r\n\r\n if (_deleted != null && fkTables != null)\r\n {\r\n HashSet intersection = (HashSet) _deleted.clone();\r\n\r\n intersection.retainAll(fkTables);\r\n if (!intersection.isEmpty())\r\n {\r\n // one of the previous DELETEs contained a table\r\n // that is referenced from this table.\r\n // Let's execute that previous DELETE right now so that\r\n // in the future DELETEs into this table will go first\r\n // in the _order array.\r\n executeBatch();\r\n }\r\n }\r\n }\r\n\r\n _order.add(sql);\r\n\r\n _touched.add(tableName);\r\n if (sqlCmd.equals(\"INSERT \"))\r\n {\r\n if (fkTables != null)\r\n {\r\n if (_dontInsert == null)\r\n {\r\n _dontInsert = new HashSet();\r\n }\r\n _dontInsert.addAll(fkTables);\r\n }\r\n }\r\n else if (sqlCmd.equals(\"DELETE \"))\r\n {\r\n if (_deleted == null)\r\n {\r\n _deleted = new HashSet();\r\n }\r\n _deleted.add(tableName);\r\n }\r\n }", "public static JRDesignExpression getDataSourceExpression(DJDataSource ds) {\n JRDesignExpression exp = new JRDesignExpression();\n exp.setValueClass(JRDataSource.class);\n\n String dsType = getDataSourceTypeStr(ds.getDataSourceType());\n String expText = null;\n if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_ORIGIN_FIELD) {\n expText = dsType + \"$F{\" + ds.getDataSourceExpression() + \"})\";\n } else if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_ORIGIN_PARAMETER) {\n expText = dsType + REPORT_PARAMETERS_MAP + \".get( \\\"\" + ds.getDataSourceExpression() + \"\\\" ) )\";\n } else if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_TYPE_SQL_CONNECTION) {\n expText = dsType + REPORT_PARAMETERS_MAP + \".get( \\\"\" + ds.getDataSourceExpression() + \"\\\" ) )\";\n } else if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_ORIGIN_REPORT_DATASOURCE) {\n expText = \"((\" + JRDataSource.class.getName() + \") $P{REPORT_DATA_SOURCE})\";\n }\n\n exp.setText(expText);\n\n return exp;\n }", "public Collection<EmailAlias> getEmailAliases() {\n URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n Collection<EmailAlias> emailAliases = new ArrayList<EmailAlias>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject emailAliasJSON = value.asObject();\n emailAliases.add(new EmailAlias(emailAliasJSON));\n }\n\n return emailAliases;\n }", "public CompositeGeneratorNode indent(final CompositeGeneratorNode parent, final String indentString) {\n final IndentNode indent = new IndentNode(indentString);\n List<IGeneratorNode> _children = parent.getChildren();\n _children.add(indent);\n return indent;\n }", "private String applyFilters(String methodName) {\n if (filters.isEmpty()) {\n return methodName;\n }\n\n Reader in = new StringReader(methodName);\n for (TokenFilter tf : filters) {\n in = tf.chain(in);\n }\n\n try {\n return CharStreams.toString(in);\n } catch (IOException e) {\n junit4.log(\"Could not apply filters to \" + methodName + \n \": \" + Throwables.getStackTraceAsString(e), Project.MSG_WARN);\n return methodName;\n }\n }", "public static String entityToString(HttpEntity entity) throws IOException {\n if (entity != null) {\n InputStream is = entity.getContent();\n return IOUtils.toString(is, \"UTF-8\");\n }\n return \"\";\n }", "public double[] getMaturities(double moneyness) {\r\n\t\tint[] maturitiesInMonths\t= getMaturities(convertMoneyness(moneyness));\r\n\t\tdouble[] maturities\t\t\t= new double[maturitiesInMonths.length];\r\n\r\n\t\tfor(int index = 0; index < maturities.length; index++) {\r\n\t\t\tmaturities[index] = convertMaturity(maturitiesInMonths[index]);\r\n\t\t}\r\n\t\treturn maturities;\r\n\t}", "public static void setLocale(ProjectProperties properties, Locale locale)\n {\n properties.setMpxDelimiter(LocaleData.getChar(locale, LocaleData.FILE_DELIMITER));\n properties.setMpxProgramName(LocaleData.getString(locale, LocaleData.PROGRAM_NAME));\n properties.setMpxCodePage((CodePage) LocaleData.getObject(locale, LocaleData.CODE_PAGE));\n\n properties.setCurrencySymbol(LocaleData.getString(locale, LocaleData.CURRENCY_SYMBOL));\n properties.setSymbolPosition((CurrencySymbolPosition) LocaleData.getObject(locale, LocaleData.CURRENCY_SYMBOL_POSITION));\n properties.setCurrencyDigits(LocaleData.getInteger(locale, LocaleData.CURRENCY_DIGITS));\n properties.setThousandsSeparator(LocaleData.getChar(locale, LocaleData.CURRENCY_THOUSANDS_SEPARATOR));\n properties.setDecimalSeparator(LocaleData.getChar(locale, LocaleData.CURRENCY_DECIMAL_SEPARATOR));\n\n properties.setDateOrder((DateOrder) LocaleData.getObject(locale, LocaleData.DATE_ORDER));\n properties.setTimeFormat((ProjectTimeFormat) LocaleData.getObject(locale, LocaleData.TIME_FORMAT));\n properties.setDefaultStartTime(DateHelper.getTimeFromMinutesPastMidnight(LocaleData.getInteger(locale, LocaleData.DEFAULT_START_TIME)));\n properties.setDateSeparator(LocaleData.getChar(locale, LocaleData.DATE_SEPARATOR));\n properties.setTimeSeparator(LocaleData.getChar(locale, LocaleData.TIME_SEPARATOR));\n properties.setAMText(LocaleData.getString(locale, LocaleData.AM_TEXT));\n properties.setPMText(LocaleData.getString(locale, LocaleData.PM_TEXT));\n properties.setDateFormat((ProjectDateFormat) LocaleData.getObject(locale, LocaleData.DATE_FORMAT));\n properties.setBarTextDateFormat((ProjectDateFormat) LocaleData.getObject(locale, LocaleData.DATE_FORMAT));\n }" ]
Creates a new indirection handler instance. @param brokerKey The associated {@link PBKey}. @param id The subject's ids @return The new instance
[ "public IndirectionHandler createIndirectionHandler(PBKey brokerKey, Identity id)\r\n {\r\n Object args[] = {brokerKey, id};\r\n\r\n try\r\n {\r\n return (IndirectionHandler) getIndirectionHandlerConstructor().newInstance(args);\r\n }\r\n catch(InvocationTargetException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new indirection handler instance\", ex);\r\n }\r\n catch(InstantiationException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new indirection handler instance\", ex);\r\n }\r\n catch(IllegalAccessException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new indirection handler instance\", ex);\r\n }\r\n }" ]
[ "public void validateOperation(final ModelNode operation) {\n if (operation == null) {\n return;\n }\n final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));\n final String name = operation.get(OP).asString();\n\n OperationEntry entry = root.getOperationEntry(address, name);\n if (entry == null) {\n throwOrWarnAboutDescriptorProblem(ControllerLogger.ROOT_LOGGER.noOperationEntry(name, address));\n }\n //noinspection ConstantConditions\n if (entry.getType() == EntryType.PRIVATE || entry.getFlags().contains(OperationEntry.Flag.HIDDEN)) {\n return;\n }\n if (entry.getOperationHandler() == null) {\n throwOrWarnAboutDescriptorProblem(ControllerLogger.ROOT_LOGGER.noOperationHandler(name, address));\n }\n final DescriptionProvider provider = getDescriptionProvider(operation);\n final ModelNode description = provider.getModelDescription(null);\n\n final Map<String, ModelNode> describedProperties = getDescribedRequestProperties(operation, description);\n final Map<String, ModelNode> actualParams = getActualRequestProperties(operation);\n\n checkActualOperationParamsAreDescribed(operation, describedProperties, actualParams);\n checkAllRequiredPropertiesArePresent(description, operation, describedProperties, actualParams);\n checkParameterTypes(description, operation, describedProperties, actualParams);\n\n //TODO check ranges\n }", "protected synchronized Object materializeSubject() throws PersistenceBrokerException\r\n\t{\r\n\t\tTemporaryBrokerWrapper tmp = getBroker();\r\n try\r\n\t\t{\r\n\t\t\tObject realSubject = tmp.broker.getObjectByIdentity(_id);\r\n\t\t\tif (realSubject == null)\r\n\t\t\t{\r\n\t\t\t\tLoggerFactory.getLogger(IndirectionHandler.class).warn(\r\n\t\t\t\t\t\t\"Can not materialize object for Identity \" + _id + \" - using PBKey \" + getBrokerKey());\r\n\t\t\t}\r\n\t\t\treturn realSubject;\r\n\t\t} catch (Exception ex)\r\n\t\t{\r\n\t\t\tthrow new PersistenceBrokerException(ex);\r\n\t\t} finally\r\n\t\t{\r\n\t\t\ttmp.close();\r\n\t\t}\r\n\t}", "private void setResourceInformation() {\n\n String sitePath = m_cms.getSitePath(m_resource);\n int pathEnd = sitePath.lastIndexOf('/') + 1;\n String baseName = sitePath.substring(pathEnd);\n m_sitepath = sitePath.substring(0, pathEnd);\n switch (CmsMessageBundleEditorTypes.BundleType.toBundleType(\n OpenCms.getResourceManager().getResourceType(m_resource).getTypeName())) {\n case PROPERTY:\n String localeSuffix = CmsStringUtil.getLocaleSuffixForName(baseName);\n if ((null != localeSuffix) && !localeSuffix.isEmpty()) {\n baseName = baseName.substring(\n 0,\n baseName.lastIndexOf(localeSuffix) - (1 /* cut off trailing underscore, too*/));\n m_locale = CmsLocaleManager.getLocale(localeSuffix);\n }\n if ((null == m_locale) || !m_locales.contains(m_locale)) {\n m_switchedLocaleOnOpening = true;\n m_locale = m_locales.iterator().next();\n }\n break;\n case XML:\n m_locale = OpenCms.getLocaleManager().getBestAvailableLocaleForXmlContent(\n m_cms,\n m_resource,\n m_xmlBundle);\n break;\n case DESCRIPTOR:\n m_basename = baseName.substring(\n 0,\n baseName.length() - CmsMessageBundleEditorTypes.Descriptor.POSTFIX.length());\n m_locale = new Locale(\"en\");\n break;\n default:\n throw new IllegalArgumentException(\n Messages.get().container(\n Messages.ERR_UNSUPPORTED_BUNDLE_TYPE_1,\n CmsMessageBundleEditorTypes.BundleType.toBundleType(\n OpenCms.getResourceManager().getResourceType(m_resource).getTypeName())).toString());\n }\n m_basename = baseName;\n\n }", "public static base_response unset(nitro_service client, ipv6 resource, String[] args) throws Exception{\n\t\tipv6 unsetresource = new ipv6();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "void insertOne(final MongoNamespace namespace, final BsonDocument document) {\n this.waitUntilInitialized();\n\n try {\n ongoingOperationsGroup.enter();\n // Remove forbidden fields from the document before inserting it into the local collection.\n final BsonDocument docForStorage = sanitizeDocument(document);\n\n final NamespaceSynchronizationConfig nsConfig =\n this.syncConfig.getNamespaceConfig(namespace);\n final Lock lock = nsConfig.getLock().writeLock();\n lock.lock();\n final ChangeEvent<BsonDocument> event;\n final BsonValue documentId;\n try {\n getLocalCollection(namespace).insertOne(docForStorage);\n documentId = BsonUtils.getDocumentId(docForStorage);\n event = ChangeEvents.changeEventForLocalInsert(namespace, docForStorage, true);\n final CoreDocumentSynchronizationConfig config = syncConfig.addAndGetSynchronizedDocument(\n namespace,\n documentId\n );\n config.setSomePendingWritesAndSave(logicalT, event);\n } finally {\n lock.unlock();\n }\n checkAndInsertNamespaceListener(namespace);\n eventDispatcher.emitEvent(nsConfig, event);\n } finally {\n ongoingOperationsGroup.exit();\n }\n }", "protected void checkVariableName(GraphRewrite event, EvaluationContext context)\n {\n if (getInputVariablesName() == null)\n {\n setInputVariablesName(Iteration.getPayloadVariableName(event, context));\n }\n }", "public MaterialSection getSectionByTitle(String title) {\n\n for(MaterialSection section : sectionList) {\n if(section.getTitle().equals(title)) {\n return section;\n }\n }\n\n for(MaterialSection section : bottomSectionList) {\n if(section.getTitle().equals(title))\n return section;\n }\n\n return null;\n }", "public ItemRequest<ProjectMembership> findById(String projectMembership) {\n \n String path = String.format(\"/project_memberships/%s\", projectMembership);\n return new ItemRequest<ProjectMembership>(this, ProjectMembership.class, path, \"GET\");\n }", "public void updateColor(TestColor color) {\n\n switch (color) {\n case green:\n m_forwardButton.setEnabled(true);\n m_confirmCheckbox.setVisible(false);\n m_status.setValue(STATUS_GREEN);\n break;\n case yellow:\n m_forwardButton.setEnabled(false);\n m_confirmCheckbox.setVisible(true);\n m_status.setValue(STATUS_YELLOW);\n break;\n case red:\n m_forwardButton.setEnabled(false);\n m_confirmCheckbox.setVisible(true);\n m_status.setValue(STATUS_RED);\n break;\n default:\n break;\n }\n }" ]
Returns the boolean value of the specified property. @param name The name of the property @param defaultValue The value to use if the property is not set or not a boolean @return The value
[ "public boolean getBooleanProperty(String name, boolean defaultValue)\r\n {\r\n return PropertyHelper.toBoolean(_properties.getProperty(name), defaultValue);\r\n }" ]
[ "private void appendClazzColumnForSelect(StringBuffer buf)\r\n {\r\n ClassDescriptor cld = getSearchClassDescriptor();\r\n ClassDescriptor[] clds = getMultiJoinedClassDescriptors(cld);\r\n\r\n if (clds.length == 0)\r\n {\r\n return;\r\n }\r\n \r\n buf.append(\",CASE\");\r\n\r\n for (int i = clds.length; i > 0; i--)\r\n {\r\n buf.append(\" WHEN \");\r\n\r\n ClassDescriptor subCld = clds[i - 1];\r\n FieldDescriptor[] fieldDescriptors = subCld.getPkFields();\r\n\r\n TableAlias alias = getTableAliasForClassDescriptor(subCld);\r\n for (int j = 0; j < fieldDescriptors.length; j++)\r\n {\r\n FieldDescriptor field = fieldDescriptors[j];\r\n if (j > 0)\r\n {\r\n buf.append(\" AND \");\r\n }\r\n appendColumn(alias, field, buf);\r\n buf.append(\" IS NOT NULL\");\r\n }\r\n buf.append(\" THEN '\").append(subCld.getClassNameOfObject()).append(\"'\");\r\n }\r\n buf.append(\" ELSE '\").append(cld.getClassNameOfObject()).append(\"'\");\r\n buf.append(\" END AS \" + SqlHelper.OJB_CLASS_COLUMN);\r\n }", "protected void mergeSameWork(LinkedList<TimephasedWork> list)\n {\n LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();\n\n TimephasedWork previousAssignment = null;\n for (TimephasedWork assignment : list)\n {\n if (previousAssignment == null)\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n result.add(assignment);\n }\n else\n {\n Duration previousAssignmentWork = previousAssignment.getAmountPerDay();\n Duration assignmentWork = assignment.getTotalAmount();\n\n if (NumberHelper.equals(previousAssignmentWork.getDuration(), assignmentWork.getDuration(), 0.01))\n {\n Date assignmentStart = previousAssignment.getStart();\n Date assignmentFinish = assignment.getFinish();\n double total = previousAssignment.getTotalAmount().getDuration();\n total += assignmentWork.getDuration();\n Duration totalWork = Duration.getInstance(total, TimeUnit.MINUTES);\n\n TimephasedWork merged = new TimephasedWork();\n merged.setStart(assignmentStart);\n merged.setFinish(assignmentFinish);\n merged.setAmountPerDay(assignmentWork);\n merged.setTotalAmount(totalWork);\n\n result.removeLast();\n assignment = merged;\n }\n else\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n }\n result.add(assignment);\n }\n\n previousAssignment = assignment;\n }\n\n list.clear();\n list.addAll(result);\n }", "private <T> CoreRemoteMongoCollection<T> getRemoteCollection(\n final MongoNamespace namespace,\n final Class<T> resultClass\n ) {\n return remoteClient\n .getDatabase(namespace.getDatabaseName())\n .getCollection(namespace.getCollectionName(), resultClass);\n }", "@Subscribe\n public void onQuit(AggregatedQuitEvent e) {\n if (jsonWriter == null)\n return;\n\n try {\n jsonWriter.endArray();\n\n jsonWriter.name(\"slaves\");\n jsonWriter.beginObject();\n for (Map.Entry<Integer, ForkedJvmInfo> entry : slaves.entrySet()) {\n jsonWriter.name(Integer.toString(entry.getKey()));\n entry.getValue().serialize(jsonWriter);\n }\n jsonWriter.endObject();\n\n jsonWriter.endObject();\n jsonWriter.flush();\n\n if (!Strings.isNullOrEmpty(jsonpMethod)) {\n writer.write(\");\");\n }\n\n jsonWriter.close();\n jsonWriter = null;\n writer = null;\n\n if (method == OutputMethod.HTML) {\n copyScaffolding(targetFile);\n }\n } catch (IOException x) {\n junit4.log(x, Project.MSG_ERR);\n }\n }", "protected static String getTimePrecisionString(byte precision) {\n\t\tswitch (precision) {\n\t\tcase TimeValue.PREC_SECOND:\n\t\t\treturn \"sec\";\n\t\tcase TimeValue.PREC_MINUTE:\n\t\t\treturn \"min\";\n\t\tcase TimeValue.PREC_HOUR:\n\t\t\treturn \"hour\";\n\t\tcase TimeValue.PREC_DAY:\n\t\t\treturn \"day\";\n\t\tcase TimeValue.PREC_MONTH:\n\t\t\treturn \"month\";\n\t\tcase TimeValue.PREC_YEAR:\n\t\t\treturn \"year\";\n\t\tcase TimeValue.PREC_DECADE:\n\t\t\treturn \"decade\";\n\t\tcase TimeValue.PREC_100Y:\n\t\t\treturn \"100 years\";\n\t\tcase TimeValue.PREC_1KY:\n\t\t\treturn \"1000 years\";\n\t\tcase TimeValue.PREC_10KY:\n\t\t\treturn \"10K years\";\n\t\tcase TimeValue.PREC_100KY:\n\t\t\treturn \"100K years\";\n\t\tcase TimeValue.PREC_1MY:\n\t\t\treturn \"1 million years\";\n\t\tcase TimeValue.PREC_10MY:\n\t\t\treturn \"10 million years\";\n\t\tcase TimeValue.PREC_100MY:\n\t\t\treturn \"100 million years\";\n\t\tcase TimeValue.PREC_1GY:\n\t\t\treturn \"1000 million years\";\n\t\tdefault:\n\t\t\treturn \"Unsupported precision \" + precision;\n\t\t}\n\t}", "private static boolean extractSimpleExtents(Variable var, Extents e, boolean row, int length) {\n int lower;\n int upper;\n if( var.getType() == VariableType.INTEGER_SEQUENCE ) {\n IntegerSequence sequence = ((VariableIntegerSequence)var).sequence;\n if( sequence.getType() == IntegerSequence.Type.FOR ) {\n IntegerSequence.For seqFor = (IntegerSequence.For)sequence;\n seqFor.initialize(length);\n if( seqFor.getStep() == 1 ) {\n lower = seqFor.getStart();\n upper = seqFor.getEnd();\n } else {\n return false;\n }\n } else {\n return false;\n }\n } else if( var.getType() == VariableType.SCALAR ) {\n lower = upper = ((VariableInteger)var).value;\n } else {\n throw new RuntimeException(\"How did a bad variable get put here?!?!\");\n }\n if( row ) {\n e.row0 = lower;\n e.row1 = upper;\n } else {\n e.col0 = lower;\n e.col1 = upper;\n }\n return true;\n }", "public CollectionRequest<Team> findByOrganization(String organization) {\n \n String path = String.format(\"/organizations/%s/teams\", organization);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }", "private GregorianCalendar getLastReleventDate(GregorianCalendar currentDate) {\n\t\tint age=this.getProperties().getMaxFileAge();\n\t\tGregorianCalendar result=new GregorianCalendar(currentDate.get(Calendar.YEAR),currentDate.get(Calendar.MONTH),currentDate.get(Calendar.DAY_OF_MONTH));\n\t\tresult.add(Calendar.DAY_OF_MONTH, -age);\n\t\treturn result;\n\t}", "private Object readMetadataFromXML(InputSource source, Class target)\r\n throws MalformedURLException, ParserConfigurationException, SAXException, IOException\r\n {\r\n // TODO: make this configurable\r\n boolean validate = false;\r\n \r\n // get a xml reader instance:\r\n SAXParserFactory factory = SAXParserFactory.newInstance();\r\n log.info(\"RepositoryPersistor using SAXParserFactory : \" + factory.getClass().getName());\r\n if (validate)\r\n {\r\n factory.setValidating(true);\r\n }\r\n SAXParser p = factory.newSAXParser();\r\n XMLReader reader = p.getXMLReader();\r\n if (validate)\r\n {\r\n reader.setErrorHandler(new OJBErrorHandler());\r\n }\r\n\r\n Object result;\r\n if (DescriptorRepository.class.equals(target))\r\n {\r\n // create an empty repository:\r\n DescriptorRepository repository = new DescriptorRepository();\r\n // create handler for building the repository structure\r\n ContentHandler handler = new RepositoryXmlHandler(repository);\r\n // tell parser to use our handler:\r\n reader.setContentHandler(handler);\r\n reader.parse(source);\r\n result = repository;\r\n }\r\n else if (ConnectionRepository.class.equals(target))\r\n {\r\n // create an empty repository:\r\n ConnectionRepository repository = new ConnectionRepository();\r\n // create handler for building the repository structure\r\n ContentHandler handler = new ConnectionDescriptorXmlHandler(repository);\r\n // tell parser to use our handler:\r\n reader.setContentHandler(handler);\r\n reader.parse(source);\r\n //LoggerFactory.getBootLogger().info(\"loading XML took \" + (stop - start) + \" msecs\");\r\n result = repository;\r\n }\r\n else\r\n throw new MetadataException(\"Could not build a repository instance for '\" + target +\r\n \"', using source \" + source);\r\n return result;\r\n }" ]
Use this API to fetch all the gslbservice resources that are configured on netscaler.
[ "public static gslbservice[] get(nitro_service service) throws Exception{\n\t\tgslbservice obj = new gslbservice();\n\t\tgslbservice[] response = (gslbservice[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "protected Boolean parseOptionalBooleanValue(final String path) {\n\n final I_CmsXmlContentValue value = m_xml.getValue(path, m_locale);\n if (value == null) {\n return null;\n } else {\n final String stringValue = value.getStringValue(null);\n try {\n final Boolean boolValue = Boolean.valueOf(stringValue);\n return boolValue;\n } catch (final NumberFormatException e) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_OPTIONAL_BOOLEAN_MISSING_1, path), e);\n return null;\n }\n }\n }", "private static int weekRange(int weekBasedYear) {\n LocalDate date = LocalDate.of(weekBasedYear, 1, 1);\n // 53 weeks if year starts on Thursday, or Wed in a leap year\n if (date.getDayOfWeek() == THURSDAY || (date.getDayOfWeek() == WEDNESDAY && date.isLeapYear())) {\n return 53;\n }\n return 52;\n }", "private void processCalendarHours(ProjectCalendar calendar, Row row, int dayIndex)\n {\n Day day = Day.getInstance(dayIndex);\n boolean working = row.getInt(\"CD_WORKING\") != 0;\n calendar.setWorkingDay(day, working);\n if (working == true)\n {\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n\n Date start = row.getDate(\"CD_FROM_TIME1\");\n Date end = row.getDate(\"CD_TO_TIME1\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME2\");\n end = row.getDate(\"CD_TO_TIME2\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME3\");\n end = row.getDate(\"CD_TO_TIME3\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME4\");\n end = row.getDate(\"CD_TO_TIME4\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME5\");\n end = row.getDate(\"CD_TO_TIME5\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n }\n }", "private void removeAllBroadcasts(Set<String> sessionIds) {\n\n if (sessionIds == null) {\n for (CmsSessionInfo info : OpenCms.getSessionManager().getSessionInfos()) {\n OpenCms.getSessionManager().getBroadcastQueue(info.getSessionId().getStringValue()).clear();\n }\n return;\n }\n for (String sessionId : sessionIds) {\n OpenCms.getSessionManager().getBroadcastQueue(sessionId).clear();\n }\n }", "public static <T> T getBundle(final Class<T> type) {\n return doPrivileged(new PrivilegedAction<T>() {\n public T run() {\n final Locale locale = Locale.getDefault();\n final String lang = locale.getLanguage();\n final String country = locale.getCountry();\n final String variant = locale.getVariant();\n\n Class<? extends T> bundleClass = null;\n if (variant != null && !variant.isEmpty()) try {\n bundleClass = Class.forName(join(type.getName(), \"$bundle\", lang, country, variant), true, type.getClassLoader()).asSubclass(type);\n } catch (ClassNotFoundException e) {\n // ignore\n }\n if (bundleClass == null && country != null && !country.isEmpty()) try {\n bundleClass = Class.forName(join(type.getName(), \"$bundle\", lang, country, null), true, type.getClassLoader()).asSubclass(type);\n } catch (ClassNotFoundException e) {\n // ignore\n }\n if (bundleClass == null && lang != null && !lang.isEmpty()) try {\n bundleClass = Class.forName(join(type.getName(), \"$bundle\", lang, null, null), true, type.getClassLoader()).asSubclass(type);\n } catch (ClassNotFoundException e) {\n // ignore\n }\n if (bundleClass == null) try {\n bundleClass = Class.forName(join(type.getName(), \"$bundle\", null, null, null), true, type.getClassLoader()).asSubclass(type);\n } catch (ClassNotFoundException e) {\n throw new IllegalArgumentException(\"Invalid bundle \" + type + \" (implementation not found)\");\n }\n final Field field;\n try {\n field = bundleClass.getField(\"INSTANCE\");\n } catch (NoSuchFieldException e) {\n throw new IllegalArgumentException(\"Bundle implementation \" + bundleClass + \" has no instance field\");\n }\n try {\n return type.cast(field.get(null));\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Bundle implementation \" + bundleClass + \" could not be instantiated\", e);\n }\n }\n });\n }", "public InputStream getInstance(DirectoryEntry directory, String name) throws IOException\n {\n DocumentEntry entry = (DocumentEntry) directory.getEntry(name);\n InputStream stream;\n if (m_encrypted)\n {\n stream = new EncryptedDocumentInputStream(entry, m_encryptionCode);\n }\n else\n {\n stream = new DocumentInputStream(entry);\n }\n\n return stream;\n }", "private int getCacheKey(InputDevice device, GVRControllerType controllerType) {\n if (controllerType != GVRControllerType.UNKNOWN &&\n controllerType != GVRControllerType.EXTERNAL) {\n // Sometimes a device shows up using two device ids\n // here we try to show both devices as one using the\n // product and vendor id\n\n int key = device.getVendorId();\n key = 31 * key + device.getProductId();\n key = 31 * key + controllerType.hashCode();\n\n return key;\n }\n return -1; // invalid key\n }", "public BoxFile.Info upload(BoxAPIConnection boxApi, String folderId, InputStream stream, URL url,\n String fileName, long fileSize) throws InterruptedException, IOException {\n //Create a upload session\n BoxFileUploadSession.Info session = this.createUploadSession(boxApi, folderId, url, fileName, fileSize);\n return this.uploadHelper(session, stream, fileSize);\n }", "public static <E, V> ServiceFuture<List<E>> fromHeaderPageResponse(Observable<ServiceResponseWithHeaders<Page<E>, V>> first, final Func1<String, Observable<ServiceResponseWithHeaders<Page<E>, V>>> next, final ListOperationCallback<E> callback) {\n final AzureServiceFuture<List<E>> serviceCall = new AzureServiceFuture<>();\n final PagingSubscriber<E> subscriber = new PagingSubscriber<>(serviceCall, new Func1<String, Observable<ServiceResponse<Page<E>>>>() {\n @Override\n public Observable<ServiceResponse<Page<E>>> call(String s) {\n return next.call(s)\n .map(new Func1<ServiceResponseWithHeaders<Page<E>, V>, ServiceResponse<Page<E>>>() {\n @Override\n public ServiceResponse<Page<E>> call(ServiceResponseWithHeaders<Page<E>, V> pageVServiceResponseWithHeaders) {\n return pageVServiceResponseWithHeaders;\n }\n });\n }\n }, callback);\n serviceCall.setSubscription(first\n .single()\n .subscribe(subscriber));\n return serviceCall;\n }" ]
Loads the configuration from file "OBJ.properties". If the system property "OJB.properties" is set, then the configuration in that file is loaded. Otherwise, the file "OJB.properties" is tried. If that is also unsuccessful, then the configuration is filled with default values.
[ "protected void load()\r\n {\r\n // properties file may be set as a System property.\r\n // if no property is set take default name.\r\n String fn = System.getProperty(OJB_PROPERTIES_FILE, OJB_PROPERTIES_FILE);\r\n setFilename(fn);\r\n super.load();\r\n\r\n // default repository & connection descriptor file\r\n repositoryFilename = getString(\"repositoryFile\", OJB_METADATA_FILE);\r\n\r\n // object cache class\r\n objectCacheClass = getClass(\"ObjectCacheClass\", ObjectCacheDefaultImpl.class, ObjectCache.class);\r\n\r\n // load PersistentField Class\r\n persistentFieldClass =\r\n getClass(\"PersistentFieldClass\", PersistentFieldDirectImpl.class, PersistentField.class);\r\n\r\n // load PersistenceBroker Class\r\n persistenceBrokerClass =\r\n getClass(\"PersistenceBrokerClass\", PersistenceBrokerImpl.class, PersistenceBroker.class);\r\n\r\n // load ListProxy Class\r\n listProxyClass = getClass(\"ListProxyClass\", ListProxyDefaultImpl.class);\r\n\r\n // load SetProxy Class\r\n setProxyClass = getClass(\"SetProxyClass\", SetProxyDefaultImpl.class);\r\n\r\n // load CollectionProxy Class\r\n collectionProxyClass = getClass(\"CollectionProxyClass\", CollectionProxyDefaultImpl.class);\r\n\r\n // load IndirectionHandler Class\r\n indirectionHandlerClass =\r\n getClass(\"IndirectionHandlerClass\", IndirectionHandlerJDKImpl.class, IndirectionHandler.class);\r\n \r\n // load ProxyFactory Class\r\n proxyFactoryClass =\r\n getClass(\"ProxyFactoryClass\", ProxyFactoryJDKImpl.class, ProxyFactory.class);\r\n\r\n // load configuration for ImplicitLocking parameter:\r\n useImplicitLocking = getBoolean(\"ImplicitLocking\", false);\r\n\r\n // load configuration for LockAssociations parameter:\r\n lockAssociationAsWrites = (getString(\"LockAssociations\", \"WRITE\").equalsIgnoreCase(\"WRITE\"));\r\n\r\n // load OQL Collection Class\r\n oqlCollectionClass = getClass(\"OqlCollectionClass\", DListImpl.class, ManageableCollection.class);\r\n\r\n // set the limit for IN-sql , -1 for no limits\r\n sqlInLimit = getInteger(\"SqlInLimit\", -1);\r\n\r\n //load configuration for PB pool\r\n maxActive = getInteger(PoolConfiguration.MAX_ACTIVE,\r\n PoolConfiguration.DEFAULT_MAX_ACTIVE);\r\n maxIdle = getInteger(PoolConfiguration.MAX_IDLE,\r\n PoolConfiguration.DEFAULT_MAX_IDLE);\r\n maxWait = getLong(PoolConfiguration.MAX_WAIT,\r\n PoolConfiguration.DEFAULT_MAX_WAIT);\r\n timeBetweenEvictionRunsMillis = getLong(PoolConfiguration.TIME_BETWEEN_EVICTION_RUNS_MILLIS,\r\n PoolConfiguration.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS);\r\n minEvictableIdleTimeMillis = getLong(PoolConfiguration.MIN_EVICTABLE_IDLE_TIME_MILLIS,\r\n PoolConfiguration.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);\r\n whenExhaustedAction = getByte(PoolConfiguration.WHEN_EXHAUSTED_ACTION,\r\n PoolConfiguration.DEFAULT_WHEN_EXHAUSTED_ACTION);\r\n\r\n useSerializedRepository = getBoolean(\"useSerializedRepository\", false);\r\n }" ]
[ "public static base_responses update(nitro_service client, snmpmanager resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpmanager updateresources[] = new snmpmanager[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new snmpmanager();\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].netmask = resources[i].netmask;\n\t\t\t\tupdateresources[i].domainresolveretry = resources[i].domainresolveretry;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "protected void processStop(Endpoint endpoint, EventTypeEnum eventType) {\n if (!sendLifecycleEvent) {\n return;\n }\n\n Event event = createEvent(endpoint, eventType);\n monitoringServiceClient.putEvents(Collections.singletonList(event));\n if (LOG.isLoggable(Level.INFO)) {\n LOG.info(\"Send \" + eventType + \" event to SAM Server successful!\");\n }\n }", "protected void runQuery() {\n\n String pool = m_pool.getValue();\n String stmt = m_script.getValue();\n if (stmt.trim().isEmpty()) {\n return;\n }\n CmsStringBufferReport report = new CmsStringBufferReport(Locale.ENGLISH);\n List<Throwable> errors = new ArrayList<>();\n CmsSqlConsoleResults result = m_console.execute(stmt, pool, report, errors);\n if (errors.size() > 0) {\n CmsErrorDialog.showErrorDialog(report.toString() + errors.get(0).getMessage(), errors.get(0));\n } else {\n Window window = CmsBasicDialog.prepareWindow(DialogWidth.max);\n window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_SQLCONSOLE_QUERY_RESULTS_0));\n window.setContent(new CmsSqlConsoleResultsForm(result, report.toString()));\n A_CmsUI.get().addWindow(window);\n window.center();\n }\n\n }", "public static JRDesignExpression getDataSourceExpression(DJDataSource ds) {\n JRDesignExpression exp = new JRDesignExpression();\n exp.setValueClass(JRDataSource.class);\n\n String dsType = getDataSourceTypeStr(ds.getDataSourceType());\n String expText = null;\n if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_ORIGIN_FIELD) {\n expText = dsType + \"$F{\" + ds.getDataSourceExpression() + \"})\";\n } else if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_ORIGIN_PARAMETER) {\n expText = dsType + REPORT_PARAMETERS_MAP + \".get( \\\"\" + ds.getDataSourceExpression() + \"\\\" ) )\";\n } else if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_TYPE_SQL_CONNECTION) {\n expText = dsType + REPORT_PARAMETERS_MAP + \".get( \\\"\" + ds.getDataSourceExpression() + \"\\\" ) )\";\n } else if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_ORIGIN_REPORT_DATASOURCE) {\n expText = \"((\" + JRDataSource.class.getName() + \") $P{REPORT_DATA_SOURCE})\";\n }\n\n exp.setText(expText);\n\n return exp;\n }", "public Duration getTotalSlack()\n {\n Duration totalSlack = (Duration) getCachedValue(TaskField.TOTAL_SLACK);\n if (totalSlack == null)\n {\n Duration duration = getDuration();\n if (duration == null)\n {\n duration = Duration.getInstance(0, TimeUnit.DAYS);\n }\n\n TimeUnit units = duration.getUnits();\n\n Duration startSlack = getStartSlack();\n if (startSlack == null)\n {\n startSlack = Duration.getInstance(0, units);\n }\n else\n {\n if (startSlack.getUnits() != units)\n {\n startSlack = startSlack.convertUnits(units, getParentFile().getProjectProperties());\n }\n }\n\n Duration finishSlack = getFinishSlack();\n if (finishSlack == null)\n {\n finishSlack = Duration.getInstance(0, units);\n }\n else\n {\n if (finishSlack.getUnits() != units)\n {\n finishSlack = finishSlack.convertUnits(units, getParentFile().getProjectProperties());\n }\n }\n\n double startSlackDuration = startSlack.getDuration();\n double finishSlackDuration = finishSlack.getDuration();\n\n if (startSlackDuration == 0 || finishSlackDuration == 0)\n {\n if (startSlackDuration != 0)\n {\n totalSlack = startSlack;\n }\n else\n {\n totalSlack = finishSlack;\n }\n }\n else\n {\n if (startSlackDuration < finishSlackDuration)\n {\n totalSlack = startSlack;\n }\n else\n {\n totalSlack = finishSlack;\n }\n }\n\n set(TaskField.TOTAL_SLACK, totalSlack);\n }\n\n return (totalSlack);\n }", "public double determinant() {\n if (m != n) {\n throw new IllegalArgumentException(\"Matrix must be square.\");\n }\n double d = (double) pivsign;\n for (int j = 0; j < n; j++) {\n d *= LU[j][j];\n }\n return d;\n }", "public static Info neg(final Variable A, ManagerTempVariables manager) {\n Info ret = new Info();\n\n if( A instanceof VariableInteger ) {\n final VariableInteger output = manager.createInteger();\n ret.output = output;\n ret.op = new Operation(\"neg-i\") {\n @Override\n public void process() {\n output.value = -((VariableInteger)A).value;\n }\n };\n } else if( A instanceof VariableScalar ) {\n final VariableDouble output = manager.createDouble();\n ret.output = output;\n ret.op = new Operation(\"neg-s\") {\n @Override\n public void process() {\n output.value = -((VariableScalar)A).getDouble();\n }\n };\n } else if( A instanceof VariableMatrix ) {\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n ret.op = new Operation(\"neg-m\") {\n @Override\n public void process() {\n DMatrixRMaj a = ((VariableMatrix)A).matrix;\n output.matrix.reshape(a.numRows, a.numCols);\n CommonOps_DDRM.changeSign(a, output.matrix);\n }\n };\n } else {\n throw new RuntimeException(\"Unsupported variable \"+A);\n }\n\n return ret;\n }", "public Class<? extends MonetaryAmount> getAmountType() {\n Class<?> clazz = get(AMOUNT_TYPE, Class.class);\n return clazz.asSubclass(MonetaryAmount.class);\n }", "public ParallelTaskBuilder preparePing() {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.PING);\n return cb;\n }" ]
Helper method to convert seed bytes into the long value required by the super class.
[ "private static long createLongSeed(byte[] seed)\n {\n if (seed == null || seed.length != SEED_SIZE_BYTES)\n {\n throw new IllegalArgumentException(\"Java RNG requires a 64-bit (8-byte) seed.\");\n }\n return BinaryUtils.convertBytesToLong(seed, 0);\n }" ]
[ "private JSONValue toJsonStringList(Collection<? extends Object> list) {\n\n if (null != list) {\n JSONArray array = new JSONArray();\n for (Object o : list) {\n array.set(array.size(), new JSONString(o.toString()));\n }\n return array;\n } else {\n return null;\n }\n }", "public static String serialize(final Object obj) throws IOException {\n\t\tfinal ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n\t\treturn mapper.writeValueAsString(obj);\n\t\t\n\t}", "private static JSONArray parseDockers(ArrayList<Point> dockers) throws JSONException {\n if (dockers != null) {\n JSONArray dockersArray = new JSONArray();\n\n for (Point docker : dockers) {\n JSONObject dockerObject = new JSONObject();\n\n dockerObject.put(\"x\",\n docker.getX().doubleValue());\n dockerObject.put(\"y\",\n docker.getY().doubleValue());\n\n dockersArray.put(dockerObject);\n }\n\n return dockersArray;\n }\n\n return new JSONArray();\n }", "public static String cutEnd(String data, int maxLength) {\n if (data.length() > maxLength) {\n return data.substring(0, maxLength) + \"...\";\n } else {\n return data;\n }\n }", "public ItemRequest<Project> removeCustomFieldSetting(String project) {\n \n String path = String.format(\"/projects/%s/removeCustomFieldSetting\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }", "public void takeNoteOfGradient(IntDoubleVector gradient) {\n gradient.iterate(new FnIntDoubleToVoid() { \n @Override\n public void call(int index, double value) {\n gradSumSquares[index] += value * value;\n assert !Double.isNaN(gradSumSquares[index]);\n }\n });\n }", "public void releaseAll() {\n synchronized(this) {\n Object[] refSet = allocatedMemoryReferences.values().toArray();\n if(refSet.length != 0) {\n logger.finer(\"Releasing allocated memory regions\");\n }\n for(Object ref : refSet) {\n release((MemoryReference) ref);\n }\n }\n }", "public void process(CustomFieldContainer indicators, ProjectProperties properties, Props props)\n {\n m_container = indicators;\n m_properties = properties;\n m_data = props.getByteArray(Props.TASK_FIELD_ATTRIBUTES);\n\n if (m_data != null)\n {\n int columnsCount = MPPUtility.getInt(m_data, 4);\n m_headerOffset = 8;\n for (int loop = 0; loop < columnsCount; loop++)\n {\n processColumns();\n }\n }\n }", "public static boolean containsUid(IdRange[] idRanges, long uid) {\r\n if (null != idRanges && idRanges.length > 0) {\r\n for (IdRange range : idRanges) {\r\n if (range.includes(uid)) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }" ]
Adds a single value to the data set and updates any statistics that are calculated cumulatively. @param value The value to add.
[ "public void addValue(double value)\n {\n if (dataSetSize == dataSet.length)\n {\n // Increase the capacity of the array.\n int newLength = (int) (GROWTH_RATE * dataSetSize);\n double[] newDataSet = new double[newLength];\n System.arraycopy(dataSet, 0, newDataSet, 0, dataSetSize);\n dataSet = newDataSet;\n }\n dataSet[dataSetSize] = value;\n updateStatsWithNewValue(value);\n ++dataSetSize;\n }" ]
[ "private void rotatorPushRight( int m )\n {\n double b11 = off[m];\n double b21 = diag[m+1];\n\n computeRotator(b21,-b11);\n\n // apply rotator on the right\n off[m] = 0;\n diag[m+1] = b21*c-b11*s;\n\n if( m+2 < N) {\n double b22 = off[m+1];\n off[m+1] = b22*c;\n bulge = b22*s;\n } else {\n bulge = 0;\n }\n\n// SimpleMatrix Q = createQ(m,m+1, c, s, true);\n// B=Q.mult(B);\n//\n// B.print();\n// printMatrix();\n// System.out.println(\" bulge = \"+bulge);\n// System.out.println();\n\n if( Ut != null ) {\n updateRotator(Ut,m,m+1,c,s);\n\n// SimpleMatrix.wrap(Ut).mult(B).mult(SimpleMatrix.wrap(Vt).transpose()).print();\n// printMatrix();\n// System.out.println(\"bulge = \"+bulge);\n// System.out.println();\n }\n }", "public HomekitRoot createBridge(\n HomekitAuthInfo authInfo,\n String label,\n String manufacturer,\n String model,\n String serialNumber)\n throws IOException {\n HomekitRoot root = new HomekitRoot(label, http, localAddress, authInfo);\n root.addAccessory(new HomekitBridge(label, serialNumber, model, manufacturer));\n return root;\n }", "public void updateProvider(final String gavc, final String provider) {\n final DbArtifact artifact = getArtifact(gavc);\n repositoryHandler.updateProvider(artifact, provider);\n }", "public void setIntVec(IntBuffer data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input buffer for indices cannot be null\");\n }\n if (getIndexSize() != 4)\n {\n throw new UnsupportedOperationException(\"Cannot update integer indices with short array\");\n }\n if (data.isDirect())\n {\n if (!NativeIndexBuffer.setIntVec(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input array is wrong size\");\n }\n }\n else if (data.hasArray())\n {\n if (!NativeIndexBuffer.setIntArray(getNative(), data.array()))\n {\n throw new IllegalArgumentException(\"Data array incompatible with index buffer\");\n }\n }\n else\n {\n throw new UnsupportedOperationException(\"IntBuffer type not supported. Must be direct or have backing array\");\n }\n }", "public static NamingConvention determineNamingConvention(\n TypeElement type,\n Iterable<ExecutableElement> methods,\n Messager messager,\n Types types) {\n ExecutableElement beanMethod = null;\n ExecutableElement prefixlessMethod = null;\n for (ExecutableElement method : methods) {\n switch (methodNameConvention(method)) {\n case BEAN:\n beanMethod = firstNonNull(beanMethod, method);\n break;\n case PREFIXLESS:\n prefixlessMethod = firstNonNull(prefixlessMethod, method);\n break;\n default:\n break;\n }\n }\n if (prefixlessMethod != null) {\n if (beanMethod != null) {\n messager.printMessage(\n ERROR,\n \"Type contains an illegal mix of get-prefixed and unprefixed getter methods, e.g. '\"\n + beanMethod.getSimpleName() + \"' and '\" + prefixlessMethod.getSimpleName() + \"'\",\n type);\n }\n return new PrefixlessConvention(messager, types);\n } else {\n return new BeanConvention(messager, types);\n }\n }", "public DescriptorRepository readDescriptorRepository(InputStream inst)\r\n {\r\n try\r\n {\r\n RepositoryPersistor persistor = new RepositoryPersistor();\r\n return persistor.readDescriptorRepository(inst);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\"Can not read repository \" + inst, e);\r\n }\r\n }", "public static snmpalarm[] get(nitro_service service) throws Exception{\n\t\tsnmpalarm obj = new snmpalarm();\n\t\tsnmpalarm[] response = (snmpalarm[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private List<Entry> sortEntries(List<Entry> loadedEntries) {\n Collections.sort(loadedEntries, new Comparator<Entry>() {\n @Override\n public int compare(Entry entry1, Entry entry2) {\n int result = (int) (entry1.cuePosition - entry2.cuePosition);\n if (result == 0) {\n int h1 = (entry1.hotCueNumber != 0) ? 1 : 0;\n int h2 = (entry2.hotCueNumber != 0) ? 1 : 0;\n result = h1 - h2;\n }\n return result;\n }\n });\n return Collections.unmodifiableList(loadedEntries);\n }", "public Flags flagList(ImapRequestLineReader request) throws ProtocolException {\n Flags flags = new Flags();\n request.nextWordChar();\n consumeChar(request, '(');\n CharacterValidator validator = new NoopCharValidator();\n String nextWord = consumeWord(request, validator);\n while (!nextWord.endsWith(\")\")) {\n setFlag(nextWord, flags);\n nextWord = consumeWord(request, validator);\n }\n // Got the closing \")\", may be attached to a word.\n if (nextWord.length() > 1) {\n setFlag(nextWord.substring(0, nextWord.length() - 1), flags);\n }\n\n return flags;\n }" ]
Destroys all resource requests in requestQueue. @param requestQueue The queue for which all resource requests are to be destroyed.
[ "private void destroyRequestQueue(Queue<AsyncResourceRequest<V>> requestQueue) {\n if(requestQueue != null) {\n AsyncResourceRequest<V> resourceRequest = requestQueue.poll();\n while(resourceRequest != null) {\n destroyRequest(resourceRequest);\n resourceRequest = requestQueue.poll();\n }\n }\n }" ]
[ "private String validateDuration() {\n\n if (!isValidEndTypeForPattern()) {\n return Messages.ERR_SERIALDATE_INVALID_END_TYPE_FOR_PATTERN_0;\n }\n switch (getEndType()) {\n case DATE:\n return (getStart().getTime() < (getSeriesEndDate().getTime() + DAY_IN_MILLIS))\n ? null\n : Messages.ERR_SERIALDATE_SERIES_END_BEFORE_START_0;\n case TIMES:\n return getOccurrences() > 0 ? null : Messages.ERR_SERIALDATE_INVALID_OCCURRENCES_0;\n default:\n return null;\n }\n\n }", "public static int getMpxField(int value)\n {\n int result = 0;\n\n if (value >= 0 && value < MPXJ_MPX_ARRAY.length)\n {\n result = MPXJ_MPX_ARRAY[value];\n }\n return (result);\n }", "@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher addBooleanFilter(String attribute, Boolean value) {\n booleanFilterMap.put(attribute, value);\n rebuildQueryFacetFilters();\n return this;\n }", "public String stripThreadName(String threadId)\n {\n if (threadId == null)\n {\n return null;\n }\n else\n {\n int index = threadId.lastIndexOf('@');\n return index >= 0 ? threadId.substring(0, index) : threadId;\n }\n }", "protected void writeEntries(final StorageAwareResource resource, final ZipOutputStream zipOut) throws IOException {\n final BufferedOutputStream bufferedOutput = new BufferedOutputStream(zipOut);\n ZipEntry _zipEntry = new ZipEntry(\"emf-contents\");\n zipOut.putNextEntry(_zipEntry);\n try {\n this.writeContents(resource, bufferedOutput);\n } finally {\n bufferedOutput.flush();\n zipOut.closeEntry();\n }\n ZipEntry _zipEntry_1 = new ZipEntry(\"resource-description\");\n zipOut.putNextEntry(_zipEntry_1);\n try {\n this.writeResourceDescription(resource, bufferedOutput);\n } finally {\n bufferedOutput.flush();\n zipOut.closeEntry();\n }\n if (this.storeNodeModel) {\n ZipEntry _zipEntry_2 = new ZipEntry(\"node-model\");\n zipOut.putNextEntry(_zipEntry_2);\n try {\n this.writeNodeModel(resource, bufferedOutput);\n } finally {\n bufferedOutput.flush();\n zipOut.closeEntry();\n }\n }\n }", "public ConnectionRepository readConnectionRepository(InputStream inst)\r\n {\r\n try\r\n {\r\n RepositoryPersistor persistor = new RepositoryPersistor();\r\n return persistor.readConnectionRepository(inst);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\"Can not read repository from \" + inst, e);\r\n }\r\n }", "protected void AddLODSceneObject(GVRSceneObject currentSceneObject) {\n if (this.transformLODSceneObject != null) {\n GVRSceneObject levelOfDetailSceneObject = null;\n if ( currentSceneObject.getParent() == this.transformLODSceneObject) {\n levelOfDetailSceneObject = currentSceneObject;\n }\n else {\n GVRSceneObject lodSceneObj = root.getSceneObjectByName((currentSceneObject.getName() + TRANSFORM_TRANSLATION_));\n if ( lodSceneObj != null ) {\n if (lodSceneObj.getParent() == this.transformLODSceneObject) {\n levelOfDetailSceneObject = lodSceneObj;\n }\n }\n if (levelOfDetailSceneObject == null) {\n lodSceneObj = root.getSceneObjectByName((currentSceneObject.getName() + TRANSFORM_ROTATION_));\n if ( lodSceneObj != null ) {\n if (lodSceneObj.getParent() == this.transformLODSceneObject) {\n levelOfDetailSceneObject = lodSceneObj;\n }\n }\n }\n if (levelOfDetailSceneObject == null) {\n lodSceneObj = root.getSceneObjectByName((currentSceneObject.getName() + TRANSFORM_SCALE_));\n if ( lodSceneObj != null ) {\n if (lodSceneObj.getParent() == this.transformLODSceneObject) {\n levelOfDetailSceneObject = lodSceneObj;\n }\n }\n }\n\n }\n if ( levelOfDetailSceneObject != null) {\n final GVRLODGroup lodGroup = (GVRLODGroup) this.transformLODSceneObject.getComponent(GVRLODGroup.getComponentType());\n lodGroup.addRange(this.getMinRange(), levelOfDetailSceneObject);\n this.increment();\n }\n }\n }", "public static Number parseDouble(String value) throws ParseException\n {\n\n Number result = null;\n value = parseString(value);\n\n // If we still have a value\n if (value != null && !value.isEmpty() && !value.equals(\"-1 -1\"))\n {\n int index = value.indexOf(\"E+\");\n if (index != -1)\n {\n value = value.substring(0, index) + 'E' + value.substring(index + 2, value.length());\n }\n\n if (value.indexOf('E') != -1)\n {\n result = DOUBLE_FORMAT.get().parse(value);\n }\n else\n {\n result = Double.valueOf(value);\n }\n }\n\n return result;\n }", "private Collection<Locale> initLocales() {\n\n Collection<Locale> locales = null;\n switch (m_bundleType) {\n case DESCRIPTOR:\n locales = new ArrayList<Locale>(1);\n locales.add(Descriptor.LOCALE);\n break;\n case XML:\n case PROPERTY:\n locales = OpenCms.getLocaleManager().getAvailableLocales(m_cms, m_resource);\n break;\n default:\n throw new IllegalArgumentException();\n }\n return locales;\n\n }" ]
Removes the given entity from the inverse associations it manages.
[ "private void removeFromInverseAssociations(\n\t\t\tTuple resultset,\n\t\t\tint tableIndex,\n\t\t\tSerializable id,\n\t\t\tSharedSessionContractImplementor session) {\n\t\tnew EntityAssociationUpdater( this )\n\t\t\t\t.id( id )\n\t\t\t\t.resultset( resultset )\n\t\t\t\t.session( session )\n\t\t\t\t.tableIndex( tableIndex )\n\t\t\t\t.propertyMightRequireInverseAssociationManagement( propertyMightBeMainSideOfBidirectionalAssociation )\n\t\t\t\t.removeNavigationalInformationFromInverseSide();\n\t}" ]
[ "public CmsContextMenu getContextMenuForItem(Object itemId) {\n\n CmsContextMenu result = null;\n try {\n final Item item = m_container.getItem(itemId);\n Property<?> keyProp = item.getItemProperty(TableProperty.KEY);\n String key = (String)keyProp.getValue();\n if ((null != key) && !key.isEmpty()) {\n loadAllRemainingLocalizations();\n final Map<Locale, String> localesWithEntries = new HashMap<Locale, String>();\n for (Locale l : m_localizations.keySet()) {\n if (l != m_locale) {\n String value = m_localizations.get(l).getProperty(key);\n if ((null != value) && !value.isEmpty()) {\n localesWithEntries.put(l, value);\n }\n }\n }\n if (!localesWithEntries.isEmpty()) {\n result = new CmsContextMenu();\n ContextMenuItem mainItem = result.addItem(\n Messages.get().getBundle(UI.getCurrent().getLocale()).key(\n Messages.GUI_BUNDLE_EDITOR_CONTEXT_COPY_LOCALE_0));\n for (final Locale l : localesWithEntries.keySet()) {\n\n ContextMenuItem menuItem = mainItem.addItem(l.getDisplayName(UI.getCurrent().getLocale()));\n menuItem.addItemClickListener(new ContextMenuItemClickListener() {\n\n public void contextMenuItemClicked(ContextMenuItemClickEvent event) {\n\n item.getItemProperty(TableProperty.TRANSLATION).setValue(localesWithEntries.get(l));\n\n }\n });\n }\n }\n }\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n //TODO: Improve\n }\n return result;\n }", "private CmsMessageBundleEditorTypes.BundleType initBundleType() {\n\n String resourceTypeName = OpenCms.getResourceManager().getResourceType(m_resource).getTypeName();\n return CmsMessageBundleEditorTypes.BundleType.toBundleType(resourceTypeName);\n }", "public static dnssuffix get(nitro_service service, String Dnssuffix) throws Exception{\n\t\tdnssuffix obj = new dnssuffix();\n\t\tobj.set_Dnssuffix(Dnssuffix);\n\t\tdnssuffix response = (dnssuffix) obj.get_resource(service);\n\t\treturn response;\n\t}", "protected void parseCombineIntegerLists(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n if( t == null || t.next == null )\n return;\n\n int numFound = 0;\n\n TokenList.Token start = null;\n TokenList.Token end = null;\n\n while( t != null ) {\n if( t.getType() == Type.VARIABLE && (isVariableInteger(t) ||\n t.getVariable().getType() == VariableType.INTEGER_SEQUENCE )) {\n if( numFound == 0 ) {\n numFound = 1;\n start = end = t;\n } else {\n numFound++;\n end = t;\n }\n } else if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n numFound = 0;\n } else {\n numFound = 0;\n }\n t = t.next;\n }\n\n if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n }\n }", "@Override\n public void close() throws VoldemortException {\n logger.debug(\"Close called for read-only store.\");\n this.fileModificationLock.writeLock().lock();\n\n try {\n if(isOpen) {\n this.isOpen = false;\n fileSet.close();\n } else {\n logger.debug(\"Attempt to close already closed store \" + getName());\n }\n } finally {\n this.fileModificationLock.writeLock().unlock();\n }\n }", "public static String multiply(CharSequence self, Number factor) {\n String s = self.toString();\n int size = factor.intValue();\n if (size == 0)\n return \"\";\n else if (size < 0) {\n throw new IllegalArgumentException(\"multiply() should be called with a number of 0 or greater not: \" + size);\n }\n StringBuilder answer = new StringBuilder(s);\n for (int i = 1; i < size; i++) {\n answer.append(s);\n }\n return answer.toString();\n }", "public synchronized void addNodesToWorkerList(List<Integer> nodeIds) {\n // Bookkeeping for nodes that will be involved in the next task\n nodeIdsWithWork.addAll(nodeIds);\n logger.info(\"Node IDs with work: \" + nodeIdsWithWork + \" Newly added nodes \" + nodeIds);\n }", "public boolean removeAll(Collection<?> collection) {\n boolean result = false;\n synchronized (mLock) {\n Iterator<?> it;\n if (mOriginalValues != null) {\n it = mOriginalValues.iterator();\n\n } else {\n it = mObjects.iterator();\n }\n while (it.hasNext()) {\n if (collection.contains(it.next())) {\n it.remove();\n result = true;\n }\n }\n }\n if (mNotifyOnChange) notifyDataSetChanged();\n return result;\n }", "public Object getProxyTarget(){\r\n\t\ttry {\r\n\t\t\treturn Proxy.getInvocationHandler(this.connection).invoke(null, this.getClass().getMethod(\"getProxyTarget\"), null);\r\n\t\t} catch (Throwable t) {\r\n\t\t\tthrow new RuntimeException(\"BoneCP: Internal error - transaction replay log is not turned on?\", t);\r\n\t\t}\r\n\t}" ]
Returns a list of metadata property paths. @return the list of metdata property paths.
[ "public List<String> getPropertyPaths() {\n List<String> result = new ArrayList<String>();\n\n for (String property : this.values.names()) {\n if (!property.startsWith(\"$\")) {\n result.add(this.propertyToPath(property));\n }\n }\n\n return result;\n }" ]
[ "public static KnowledgeBuilderConfiguration newKnowledgeBuilderConfiguration(Properties properties,\n ClassLoader... classLoaders) {\n return FactoryServiceHolder.factoryService.newKnowledgeBuilderConfiguration( properties, classLoaders );\n }", "public void updateInfo(BoxTermsOfServiceUserStatus.Info info) {\n URL url = TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(info.getPendingChanges());\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n info.update(responseJSON);\n }", "public static void log(String label, String data)\n {\n if (LOG != null)\n {\n LOG.write(label);\n LOG.write(\": \");\n LOG.println(data);\n LOG.flush();\n }\n }", "private void performScriptedStep() {\n double scale = computeBulgeScale();\n if( steps > giveUpOnKnown ) {\n // give up on the script\n followScript = false;\n } else {\n // use previous singular value to step\n double s = values[x2]/scale;\n performImplicitSingleStep(scale,s*s,false);\n }\n }", "public static Thread newThread(String name, Runnable runnable, boolean daemon) {\n Thread thread = new Thread(runnable, name);\n thread.setDaemon(daemon);\n return thread;\n }", "@SuppressWarnings(\"rawtypes\")\n private static <T> Constructor<T> findConstructor(final Class<T> clazz, final Object... args)\n throws NoSuchConstructorException, AmbiguousConstructorException {\n final Object[] cArgs = (args == null) ? new Object[0] : args;\n Constructor<T> constructorToUse = null;\n final Constructor<?>[] candidates = clazz.getConstructors();\n Arrays.sort(candidates, ConstructorComparator.INSTANCE);\n int minTypeDiffWeight = Integer.MAX_VALUE;\n Set<Constructor<?>> ambiguousConstructors = null;\n for (final Constructor candidate : candidates) {\n final Class[] paramTypes = candidate.getParameterTypes();\n if (constructorToUse != null && cArgs.length > paramTypes.length) {\n // Already found greedy constructor that can be satisfied.\n // Do not look any further, there are only less greedy\n // constructors left.\n break;\n }\n if (paramTypes.length != cArgs.length) {\n continue;\n }\n final int typeDiffWeight = getTypeDifferenceWeight(paramTypes, cArgs);\n if (typeDiffWeight < minTypeDiffWeight) { \n // Choose this constructor if it represents the closest match.\n constructorToUse = candidate;\n minTypeDiffWeight = typeDiffWeight;\n ambiguousConstructors = null;\n } else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {\n if (ambiguousConstructors == null) {\n ambiguousConstructors = new LinkedHashSet<Constructor<?>>();\n ambiguousConstructors.add(constructorToUse);\n }\n ambiguousConstructors.add(candidate);\n }\n }\n if (ambiguousConstructors != null && !ambiguousConstructors.isEmpty()) {\n throw new AmbiguousConstructorException(clazz, cArgs, ambiguousConstructors);\n }\n if (constructorToUse == null) {\n throw new NoSuchConstructorException(clazz, cArgs);\n }\n return constructorToUse;\n }", "public NamespacesList<Namespace> getNamespaces(String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Namespace> nsList = new NamespacesList<Namespace>();\r\n parameters.put(\"method\", METHOD_GET_NAMESPACES);\r\n\r\n if (predicate != null) {\r\n parameters.put(\"predicate\", predicate);\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element nsElement = response.getPayload();\r\n NodeList nsNodes = nsElement.getElementsByTagName(\"namespace\");\r\n nsList.setPage(\"1\");\r\n nsList.setPages(\"1\");\r\n nsList.setPerPage(\"\" + nsNodes.getLength());\r\n nsList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n nsList.add(parseNamespace(element));\r\n }\r\n return nsList;\r\n }", "public void stop(int waitMillis) throws InterruptedException {\n try {\n if (!isDone()) {\n setExitStatus(new Event(EventType.STOPPED_BY_USER, String.format(\"Stopped by user: waiting for %d ms\", waitMillis)));\n }\n if (!waitForFinish(waitMillis)) {\n logger.warn(\"{} Client thread failed to finish in {} millis\", name, waitMillis);\n }\n } finally {\n rateTracker.shutdown();\n }\n }", "public static void writeErrorResponse(MessageEvent messageEvent,\n HttpResponseStatus status,\n String message) {\n\n // Create the Response object\n HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);\n response.setHeader(CONTENT_TYPE, \"text/plain; charset=UTF-8\");\n response.setContent(ChannelBuffers.copiedBuffer(\"Failure: \" + status.toString() + \". \"\n + message + \"\\r\\n\", CharsetUtil.UTF_8));\n response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());\n\n // Write the response to the Netty Channel\n messageEvent.getChannel().write(response);\n }" ]
Returns the configured page size, or the default page size if it is not configured. @return The configured page size, or the default page size if it is not configured.
[ "private List<Integer> getPageSizes() {\n\n final String pageSizes = parseOptionalStringValue(XML_ELEMENT_PAGESIZE);\n if (pageSizes != null) {\n String[] pageSizesArray = pageSizes.split(\"-\");\n if (pageSizesArray.length > 0) {\n try {\n List<Integer> result = new ArrayList<>(pageSizesArray.length);\n for (int i = 0; i < pageSizesArray.length; i++) {\n result.add(Integer.valueOf(pageSizesArray[i]));\n }\n return result;\n } catch (NumberFormatException e) {\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_PARSING_PAGE_SIZES_FAILED_1, pageSizes), e);\n }\n }\n }\n return null;\n }" ]
[ "public void init(Configuration configuration) {\n if (devMode && reload && !listeningToDispatcher) {\n // this is the only way I found to be able to get added to to\n // ConfigurationProvider list\n // listening to events in Dispatcher\n listeningToDispatcher = true;\n Dispatcher.addDispatcherListener(this);\n }\n }", "public void removeValue(T value, boolean reload) {\n int idx = getIndex(value);\n if (idx >= 0) {\n removeItemInternal(idx, reload);\n }\n }", "private void processEncodedPayload() throws IOException {\n if (!readPayload) {\n payloadSpanCollector.reset();\n collect(payloadSpanCollector);\n Collection<byte[]> originalPayloadCollection = payloadSpanCollector\n .getPayloads();\n if (originalPayloadCollection.iterator().hasNext()) {\n byte[] payload = originalPayloadCollection.iterator().next();\n if (payload == null) {\n throw new IOException(\"no payload\");\n }\n MtasPayloadDecoder payloadDecoder = new MtasPayloadDecoder();\n payloadDecoder.init(startPosition(), payload);\n mtasPosition = payloadDecoder.getMtasPosition();\n } else {\n throw new IOException(\"no payload\");\n }\n }\n }", "public static lbvserver_stats get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_stats obj = new lbvserver_stats();\n\t\tobj.set_name(name);\n\t\tlbvserver_stats response = (lbvserver_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public List<ServerRedirect> deleteServerMapping(int serverMappingId) {\n ArrayList<ServerRedirect> servers = new ArrayList<ServerRedirect>();\n try {\n JSONArray serverArray = new JSONArray(doDelete(BASE_SERVER + \"/\" + serverMappingId, null));\n for (int i = 0; i < serverArray.length(); i++) {\n JSONObject jsonServer = serverArray.getJSONObject(i);\n ServerRedirect server = getServerRedirectFromJSON(jsonServer);\n if (server != null) {\n servers.add(server);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n\n return servers;\n }", "private void deleteAsync(final File file) {\n new Thread(new Runnable() {\n\n @Override\n public void run() {\n try {\n try {\n logger.info(\"Waiting for \" + deleteBackupMs\n + \" milliseconds before deleting \" + file.getAbsolutePath());\n Thread.sleep(deleteBackupMs);\n } catch(InterruptedException e) {\n logger.warn(\"Did not sleep enough before deleting backups\");\n }\n logger.info(\"Deleting file \" + file.getAbsolutePath());\n Utils.rm(file);\n logger.info(\"Deleting of \" + file.getAbsolutePath()\n + \" completed successfully.\");\n storeVersionManager.syncInternalStateFromFileSystem(true);\n } catch(Exception e) {\n logger.error(\"Exception during deleteAsync for path: \" + file, e);\n }\n }\n }, \"background-file-delete\").start();\n }", "public static String stringMatcherByPattern(String input, String patternStr) {\n\n String output = PcConstants.SYSTEM_FAIL_MATCH_REGEX;\n\n // 20140105: fix the NPE issue\n if (patternStr == null) {\n logger.error(\"patternStr is NULL! (Expected when the aggregation rule is not defined at \"\n + PcDateUtils.getNowDateTimeStrStandard());\n return output;\n }\n\n if (input == null) {\n logger.error(\"input (Expected when the response is null and now try to match on response) is NULL in stringMatcherByPattern() at \"\n + PcDateUtils.getNowDateTimeStrStandard());\n return output;\n } else {\n input = input.replace(\"\\n\", \"\").replace(\"\\r\", \"\");\n }\n\n logger.debug(\"input: \" + input);\n logger.debug(\"patternStr: \" + patternStr);\n\n Pattern patternMetric = Pattern.compile(patternStr, Pattern.MULTILINE);\n\n final Matcher matcher = patternMetric.matcher(input);\n if (matcher.matches()) {\n output = matcher.group(1);\n }\n return output;\n }", "public void updateConfig(String appName, Map<String, String> config) {\n connection.execute(new ConfigUpdate(appName, config), apiKey);\n }", "public Label htmlLabel(String html) {\n\n Label label = new Label();\n label.setContentMode(ContentMode.HTML);\n label.setValue(html);\n return label;\n\n }" ]
Writes the specified double to the stream, formatted according to the format specified in the constructor. @param d the double to write to the stream @return this writer @throws IOException if an I/O error occurs
[ "public ExtendedOutputStreamWriter append(double d) throws IOException {\n super.append(String.format(Locale.ROOT, doubleFormat, d));\n return this;\n }" ]
[ "private void createTimephasedData(ProjectFile file, ResourceAssignment assignment, List<TimephasedWork> timephasedPlanned, List<TimephasedWork> timephasedComplete)\n {\n if (timephasedPlanned.isEmpty() && timephasedComplete.isEmpty())\n {\n Duration totalMinutes = assignment.getWork().convertUnits(TimeUnit.MINUTES, file.getProjectProperties());\n\n Duration workPerDay;\n\n if (assignment.getResource() == null || assignment.getResource().getType() == ResourceType.WORK)\n {\n workPerDay = totalMinutes.getDuration() == 0 ? totalMinutes : ResourceAssignmentFactory.DEFAULT_NORMALIZER_WORK_PER_DAY;\n int units = NumberHelper.getInt(assignment.getUnits());\n if (units != 100)\n {\n workPerDay = Duration.getInstance((workPerDay.getDuration() * units) / 100.0, workPerDay.getUnits());\n }\n }\n else\n {\n if (assignment.getVariableRateUnits() == null)\n {\n Duration workingDays = assignment.getCalendar().getWork(assignment.getStart(), assignment.getFinish(), TimeUnit.DAYS);\n double units = NumberHelper.getDouble(assignment.getUnits());\n double unitsPerDayAsMinutes = (units * 60) / (workingDays.getDuration() * 100);\n workPerDay = Duration.getInstance(unitsPerDayAsMinutes, TimeUnit.MINUTES);\n }\n else\n {\n double unitsPerHour = NumberHelper.getDouble(assignment.getUnits());\n workPerDay = ResourceAssignmentFactory.DEFAULT_NORMALIZER_WORK_PER_DAY;\n Duration hoursPerDay = workPerDay.convertUnits(TimeUnit.HOURS, file.getProjectProperties());\n double unitsPerDayAsHours = (unitsPerHour * hoursPerDay.getDuration()) / 100;\n double unitsPerDayAsMinutes = unitsPerDayAsHours * 60;\n workPerDay = Duration.getInstance(unitsPerDayAsMinutes, TimeUnit.MINUTES);\n }\n }\n\n Duration overtimeWork = assignment.getOvertimeWork();\n if (overtimeWork != null && overtimeWork.getDuration() != 0)\n {\n Duration totalOvertimeMinutes = overtimeWork.convertUnits(TimeUnit.MINUTES, file.getProjectProperties());\n totalMinutes = Duration.getInstance(totalMinutes.getDuration() - totalOvertimeMinutes.getDuration(), TimeUnit.MINUTES);\n }\n\n TimephasedWork tra = new TimephasedWork();\n tra.setStart(assignment.getStart());\n tra.setAmountPerDay(workPerDay);\n tra.setModified(false);\n tra.setFinish(assignment.getFinish());\n tra.setTotalAmount(totalMinutes);\n timephasedPlanned.add(tra);\n }\n }", "static void merge(Map<ConfigurationKey, Object> original, Map<ConfigurationKey, Object> toMerge, String mergedSourceDescription) {\n for (Entry<ConfigurationKey, Object> entry : toMerge.entrySet()) {\n Object existing = original.get(entry.getKey());\n if (existing != null) {\n ConfigurationLogger.LOG.configurationKeyAlreadySet(entry.getKey().get(), existing, entry.getValue(), mergedSourceDescription);\n } else {\n original.put(entry.getKey(), entry.getValue());\n }\n }\n }", "public static sslocspresponder[] get(nitro_service service) throws Exception{\n\t\tsslocspresponder obj = new sslocspresponder();\n\t\tsslocspresponder[] response = (sslocspresponder[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private void saveToXmlVfsBundle() throws CmsException {\n\n if (m_lockedBundleFiles.get(null) != null) { // If the file was not locked, no changes were made, i.e., storing is not necessary.\n for (Locale l : m_locales) {\n SortedProperties props = m_localizations.get(l);\n if (null != props) {\n if (m_xmlBundle.hasLocale(l)) {\n m_xmlBundle.removeLocale(l);\n }\n m_xmlBundle.addLocale(m_cms, l);\n int i = 0;\n List<Object> keys = new ArrayList<Object>(props.keySet());\n Collections.sort(keys, CmsCaseInsensitiveStringComparator.getInstance());\n for (Object key : keys) {\n if ((null != key) && !key.toString().isEmpty()) {\n String value = props.getProperty(key.toString());\n if (!value.isEmpty()) {\n m_xmlBundle.addValue(m_cms, \"Message\", l, i);\n i++;\n m_xmlBundle.getValue(\"Message[\" + i + \"]/Key\", l).setStringValue(m_cms, key.toString());\n m_xmlBundle.getValue(\"Message[\" + i + \"]/Value\", l).setStringValue(m_cms, value);\n }\n }\n }\n }\n CmsFile bundleFile = m_lockedBundleFiles.get(null).getFile();\n bundleFile.setContents(m_xmlBundle.marshal());\n m_cms.writeFile(bundleFile);\n }\n }\n }", "public static sslocspresponder[] get(nitro_service service) throws Exception{\n\t\tsslocspresponder obj = new sslocspresponder();\n\t\tsslocspresponder[] response = (sslocspresponder[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public Path relativize(Path other) {\n\t\tif (other.isAbsolute() != isAbsolute())\n\t\t\tthrow new IllegalArgumentException(\"This path and the given path are not both absolute or both relative: \" + toString() + \" | \" + other.toString());\n\t\tif (startsWith(other)) {\n\t\t\treturn internalRelativize(this, other);\n\t\t} else if (other.startsWith(this)) {\n\t\t\treturn internalRelativize(other, this);\n\t\t}\n\t\treturn null;\n\t}", "private void initPatternButtonGroup() {\n\n m_groupPattern = new CmsRadioButtonGroup();\n m_patternButtons = new HashMap<>();\n\n createAndAddButton(PatternType.DAILY, Messages.GUI_SERIALDATE_TYPE_DAILY_0);\n m_patternButtons.put(PatternType.NONE, m_patternButtons.get(PatternType.DAILY));\n createAndAddButton(PatternType.WEEKLY, Messages.GUI_SERIALDATE_TYPE_WEEKLY_0);\n createAndAddButton(PatternType.MONTHLY, Messages.GUI_SERIALDATE_TYPE_MONTHLY_0);\n createAndAddButton(PatternType.YEARLY, Messages.GUI_SERIALDATE_TYPE_YEARLY_0);\n // createAndAddButton(PatternType.INDIVIDUAL, Messages.GUI_SERIALDATE_TYPE_INDIVIDUAL_0);\n\n m_groupPattern.addValueChangeHandler(new ValueChangeHandler<String>() {\n\n public void onValueChange(ValueChangeEvent<String> event) {\n\n if (handleChange()) {\n String value = event.getValue();\n if (value != null) {\n m_controller.setPattern(value);\n }\n }\n }\n });\n\n }", "@Deprecated\r\n public Location resolvePlaceURL(String flickrPlacesUrl) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_RESOLVE_PLACE_URL);\r\n\r\n parameters.put(\"url\", flickrPlacesUrl);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }", "public void set(Object receiver, String fieldName, /* @Nullable */ Object value) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {\n\t\tPreconditions.checkNotNull(receiver,\"receiver\");\n\t\tPreconditions.checkNotNull(fieldName,\"fieldName\");\n\t\tClass<? extends Object> clazz = receiver.getClass();\n\t\tField f = getDeclaredField(clazz, fieldName);\n\t\tif (!f.isAccessible())\n\t\t\tf.setAccessible(true);\n\t\tf.set(receiver, value);\n\t}" ]
Add a polygon symbolizer definition to the rule. @param styleJson The old style.
[ "@Nullable\n @VisibleForTesting\n protected PolygonSymbolizer createPolygonSymbolizer(final PJsonObject styleJson) {\n if (this.allowNullSymbolizer && !styleJson.has(JSON_FILL_COLOR)) {\n return null;\n }\n\n final PolygonSymbolizer symbolizer = this.styleBuilder.createPolygonSymbolizer();\n symbolizer.setFill(createFill(styleJson));\n\n symbolizer.setStroke(createStroke(styleJson, false));\n\n return symbolizer;\n }" ]
[ "private void addDependencyToGraph(final DbDependency dependency, final AbstractGraph graph, final int depth, final String parentId) {\n // In that case of Axway artifact we will add a module to the graph\n if (filters.getCorporateFilter().filter(dependency)) {\n final DbModule dbTarget = repoHandler.getModuleOf(dependency.getTarget());\n\n // if there is no module, add the artifact to the graph\n if(dbTarget == null){\n LOG.error(\"Got missing reference: \" + dependency.getTarget());\n final DbArtifact dbArtifact = DataUtils.createDbArtifact(dependency.getTarget());\n final String targetElementId = graph.getId(dbArtifact);\n graph.addElement(targetElementId, dbArtifact.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n return;\n }\n\n // Add the element to the graph\n addModuleToGraph(dbTarget, graph, depth + 1);\n\n //Add the dependency to the graph\n final String moduleElementId = graph.getId(dbTarget);\n graph.addDependency(parentId, moduleElementId, dependency.getScope());\n }\n // In case a third-party we will add an artifact\n else {\n final DbArtifact dbTarget = repoHandler.getArtifact(dependency.getTarget());\n if(dbTarget == null){\n LOG.error(\"Got missing artifact: \" + dependency.getTarget());\n return;\n }\n\n if(!graph.isTreated(graph.getId(dbTarget))){\n final ModelMapper modelMapper = new ModelMapper(repoHandler);\n final Artifact target = modelMapper.getArtifact(dbTarget);\n final String targetElementId = graph.getId(target);\n graph.addElement(targetElementId, target.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n }\n }\n }", "public static cmppolicylabel_policybinding_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel_policybinding_binding obj = new cmppolicylabel_policybinding_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel_policybinding_binding response[] = (cmppolicylabel_policybinding_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void writeBooleanField(String fieldName, Object value) throws IOException\n {\n boolean val = ((Boolean) value).booleanValue();\n if (val)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }", "public static DMatrixRMaj insideSpan(DMatrixRMaj[] span , double min , double max , Random rand ) {\n DMatrixRMaj A = new DMatrixRMaj(span.length,1);\n\n DMatrixRMaj B = new DMatrixRMaj(span[0].getNumElements(),1);\n\n for( int i = 0; i < span.length; i++ ) {\n B.set(span[i]);\n double val = rand.nextDouble()*(max-min)+min;\n CommonOps_DDRM.scale(val,B);\n\n CommonOps_DDRM.add(A,B,A);\n\n }\n\n return A;\n }", "public String readSnippet(String name) {\n\n String path = CmsStringUtil.joinPaths(\n m_context.getSetupBean().getWebAppRfsPath(),\n CmsSetupBean.FOLDER_SETUP,\n \"html\",\n name);\n try (InputStream stream = new FileInputStream(path)) {\n byte[] data = CmsFileUtil.readFully(stream, false);\n String result = new String(data, \"UTF-8\");\n return result;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "public int getIntegerBelief(String name){\n Object belief = introspector.getBeliefBase(this).get(name);\n int count = 0;\n if (belief!=null) {\n count = (Integer) belief;\n }\n return (Integer) count;\n }", "public void forAllExtents(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getExtentClasses(); it.hasNext(); )\r\n {\r\n _curExtent = (ClassDescriptorDef)it.next();\r\n generate(template);\r\n }\r\n _curExtent = null;\r\n }", "private void deliverTempoChangedAnnouncement(final double tempo) {\n for (final MasterListener listener : getMasterListeners()) {\n try {\n listener.tempoChanged(tempo);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering tempo changed announcement to listener\", t);\n }\n }\n }", "private String getDurationString(Duration value)\n {\n String result = null;\n\n if (value != null)\n {\n double seconds = 0;\n\n switch (value.getUnits())\n {\n case MINUTES:\n case ELAPSED_MINUTES:\n {\n seconds = value.getDuration() * 60;\n break;\n }\n\n case HOURS:\n case ELAPSED_HOURS:\n {\n seconds = value.getDuration() * (60 * 60);\n break;\n }\n\n case DAYS:\n {\n double minutesPerDay = m_projectFile.getProjectProperties().getMinutesPerDay().doubleValue();\n seconds = value.getDuration() * (minutesPerDay * 60);\n break;\n }\n\n case ELAPSED_DAYS:\n {\n seconds = value.getDuration() * (24 * 60 * 60);\n break;\n }\n\n case WEEKS:\n {\n double minutesPerWeek = m_projectFile.getProjectProperties().getMinutesPerWeek().doubleValue();\n seconds = value.getDuration() * (minutesPerWeek * 60);\n break;\n }\n\n case ELAPSED_WEEKS:\n {\n seconds = value.getDuration() * (7 * 24 * 60 * 60);\n break;\n }\n\n case MONTHS:\n {\n double minutesPerDay = m_projectFile.getProjectProperties().getMinutesPerDay().doubleValue();\n double daysPerMonth = m_projectFile.getProjectProperties().getDaysPerMonth().doubleValue();\n seconds = value.getDuration() * (daysPerMonth * minutesPerDay * 60);\n break;\n }\n\n case ELAPSED_MONTHS:\n {\n seconds = value.getDuration() * (30 * 24 * 60 * 60);\n break;\n }\n\n case YEARS:\n {\n double minutesPerDay = m_projectFile.getProjectProperties().getMinutesPerDay().doubleValue();\n double daysPerMonth = m_projectFile.getProjectProperties().getDaysPerMonth().doubleValue();\n seconds = value.getDuration() * (12 * daysPerMonth * minutesPerDay * 60);\n break;\n }\n\n case ELAPSED_YEARS:\n {\n seconds = value.getDuration() * (365 * 24 * 60 * 60);\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n result = Long.toString((long) seconds);\n }\n\n return (result);\n }" ]