query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Get new vector clock based on this clock but incremented on index nodeId
@param nodeId The id of the node to increment
@return A vector clock equal on each element execept that indexed by
nodeId | [
"public VectorClock incremented(int nodeId, long time) {\n VectorClock copyClock = this.clone();\n copyClock.incrementVersion(nodeId, time);\n return copyClock;\n }"
] | [
"public static ServiceController<DeploymentScanner> addService(final OperationContext context, final PathAddress resourceAddress, final String relativeTo, final String path,\n final int scanInterval, TimeUnit unit, final boolean autoDeployZip,\n final boolean autoDeployExploded, final boolean autoDeployXml, final boolean scanEnabled, final long deploymentTimeout, boolean rollbackOnRuntimeFailure,\n final FileSystemDeploymentService bootTimeService, final ScheduledExecutorService scheduledExecutorService) {\n final DeploymentScannerService service = new DeploymentScannerService(resourceAddress, relativeTo, path, scanInterval, unit, autoDeployZip,\n autoDeployExploded, autoDeployXml, scanEnabled, deploymentTimeout, rollbackOnRuntimeFailure, bootTimeService);\n final ServiceName serviceName = getServiceName(resourceAddress.getLastElement().getValue());\n service.scheduledExecutorValue.inject(scheduledExecutorService);\n final ServiceBuilder<DeploymentScanner> sb = context.getServiceTarget().addService(serviceName, service);\n sb.addDependency(context.getCapabilityServiceName(PATH_MANAGER_CAPABILITY, PathManager.class), PathManager.class, service.pathManagerValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.notification-handler-registry\", null),\n NotificationHandlerRegistry.class, service.notificationRegistryValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.model-controller-client-factory\", null),\n ModelControllerClientFactory.class, service.clientFactoryValue);\n sb.requires(org.jboss.as.server.deployment.Services.JBOSS_DEPLOYMENT_CHAINS);\n sb.addDependency(ControlledProcessStateService.SERVICE_NAME, ControlledProcessStateService.class, service.controlledProcessStateServiceValue);\n return sb.install();\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}",
"public static base_responses update(nitro_service client, clusterinstance resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusterinstance updateresources[] = new clusterinstance[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new clusterinstance();\n\t\t\t\tupdateresources[i].clid = resources[i].clid;\n\t\t\t\tupdateresources[i].deadinterval = resources[i].deadinterval;\n\t\t\t\tupdateresources[i].hellointerval = resources[i].hellointerval;\n\t\t\t\tupdateresources[i].preemption = resources[i].preemption;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"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 void recurseAndAddFiles(GraphRewrite event, EvaluationContext context,\n Path tempFolder,\n FileService fileService, ArchiveModel archiveModel,\n FileModel parentFileModel, boolean subArchivesOnly)\n {\n checkCancelled(event);\n\n int numberAdded = 0;\n\n FileFilter filter = TrueFileFilter.TRUE;\n if (archiveModel instanceof IdentifiedArchiveModel)\n {\n filter = new IdentifiedArchiveFileFilter(archiveModel);\n }\n\n File fileReference;\n if (parentFileModel instanceof ArchiveModel)\n fileReference = new File(((ArchiveModel) parentFileModel).getUnzippedDirectory());\n else\n fileReference = parentFileModel.asFile();\n\n WindupJavaConfigurationService windupJavaConfigurationService = new WindupJavaConfigurationService(event.getGraphContext());\n File[] subFiles = fileReference.listFiles();\n if (subFiles == null)\n return;\n\n for (File subFile : subFiles)\n {\n if (!filter.accept(subFile))\n continue;\n\n if (subArchivesOnly && !ZipUtil.endsWithZipExtension(subFile.getAbsolutePath()))\n continue;\n\n FileModel subFileModel = fileService.createByFilePath(parentFileModel, subFile.getAbsolutePath());\n\n // check if this file should be ignored\n if (windupJavaConfigurationService.checkIfIgnored(event, subFileModel))\n continue;\n\n numberAdded++;\n if (numberAdded % 250 == 0)\n event.getGraphContext().commit();\n\n if (subFile.isFile() && ZipUtil.endsWithZipExtension(subFileModel.getFilePath()))\n {\n File newZipFile = subFileModel.asFile();\n ArchiveModel newArchiveModel = GraphService.addTypeToModel(event.getGraphContext(), subFileModel, ArchiveModel.class);\n newArchiveModel.setParentArchive(archiveModel);\n newArchiveModel.setArchiveName(newZipFile.getName());\n\n /*\n * New archive must be reloaded in case the archive should be ignored\n */\n newArchiveModel = GraphService.refresh(event.getGraphContext(), newArchiveModel);\n\n ArchiveModel canonicalArchiveModel = null;\n for (FileModel otherMatches : fileService.findAllByProperty(FileModel.SHA1_HASH, newArchiveModel.getSHA1Hash()))\n {\n if (otherMatches instanceof ArchiveModel && !otherMatches.equals(newArchiveModel) && !(otherMatches instanceof DuplicateArchiveModel))\n {\n canonicalArchiveModel = (ArchiveModel)otherMatches;\n break;\n }\n }\n\n if (canonicalArchiveModel != null)\n {\n // handle as duplicate\n DuplicateArchiveModel duplicateArchive = GraphService.addTypeToModel(event.getGraphContext(), newArchiveModel, DuplicateArchiveModel.class);\n duplicateArchive.setCanonicalArchive(canonicalArchiveModel);\n\n // create dupes for child archives\n unzipToTempDirectory(event, context, tempFolder, newZipFile, duplicateArchive, true);\n } else\n {\n unzipToTempDirectory(event, context, tempFolder, newZipFile, newArchiveModel, false);\n }\n } else if (subFile.isDirectory())\n {\n recurseAndAddFiles(event, context, tempFolder, fileService, archiveModel, subFileModel, false);\n }\n }\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 }",
"private static void checkPreconditions(final List<String> forbiddenSubStrings) {\n\t\tif( forbiddenSubStrings == null ) {\n\t\t\tthrow new NullPointerException(\"forbiddenSubStrings list should not be null\");\n\t\t} else if( forbiddenSubStrings.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"forbiddenSubStrings list should not be empty\");\n\t\t}\n\t}",
"@UiHandler(\"m_endTime\")\n void onEndTimeChange(CmsDateBoxEvent event) {\n\n if (handleChange() && !event.isUserTyping()) {\n m_controller.setEndTime(event.getDate());\n }\n }",
"public ProjectCalendarException addCalendarException(Date fromDate, Date toDate)\n {\n ProjectCalendarException bce = new ProjectCalendarException(fromDate, toDate);\n m_exceptions.add(bce);\n m_expandedExceptions.clear();\n m_exceptionsSorted = false;\n clearWorkingDateCache();\n return bce;\n }"
] |
Remove duplicate Strings from the given array. Also sorts the array, as
it uses a TreeSet.
@param array the String array
@return an array without duplicates, in natural sort order | [
"public static String[] removeDuplicateStrings(String[] array) {\n if (isEmpty(array)) {\n return array;\n }\n Set<String> set = new TreeSet<String>();\n Collections.addAll(set, array);\n return toStringArray(set);\n }"
] | [
"public static dbdbprofile get(nitro_service service, String name) throws Exception{\n\t\tdbdbprofile obj = new dbdbprofile();\n\t\tobj.set_name(name);\n\t\tdbdbprofile response = (dbdbprofile) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public void addDependency(final ProcessorGraphNode node) {\n Assert.isTrue(node != this, \"A processor can't depends on himself\");\n\n this.dependencies.add(node);\n node.addRequirement(this);\n }",
"public boolean checkXpathStartsWithXpathEventableCondition(Document dom,\n\t\t\tEventableCondition eventableCondition, String xpath) throws XPathExpressionException {\n\t\tif (eventableCondition == null || Strings\n\t\t\t\t.isNullOrEmpty(eventableCondition.getInXPath())) {\n\t\t\tthrow new CrawljaxException(\"Eventable has no XPath condition\");\n\t\t}\n\t\tList<String> expressions =\n\t\t\t\tXPathHelper.getXpathForXPathExpressions(dom, eventableCondition.getInXPath());\n\n\t\treturn checkXPathUnderXPaths(xpath, expressions);\n\t}",
"public void combine(CRFClassifier<IN> crf, double weight) {\r\n Timing timer = new Timing();\r\n\r\n // Check the CRFClassifiers are compatible\r\n if (!this.pad.equals(crf.pad)) {\r\n throw new RuntimeException(\"Incompatible CRFClassifier: pad does not match\");\r\n }\r\n if (this.windowSize != crf.windowSize) {\r\n throw new RuntimeException(\"Incompatible CRFClassifier: windowSize does not match\");\r\n }\r\n if (this.labelIndices.length != crf.labelIndices.length) {\r\n // Should match since this should be same as the windowSize\r\n throw new RuntimeException(\"Incompatible CRFClassifier: labelIndices length does not match\");\r\n }\r\n this.classIndex.addAll(crf.classIndex.objectsList());\r\n\r\n // Combine weights of the other classifier with this classifier,\r\n // weighing the other classifier's weights by weight\r\n // First merge the feature indicies\r\n int oldNumFeatures1 = this.featureIndex.size();\r\n int oldNumFeatures2 = crf.featureIndex.size();\r\n int oldNumWeights1 = this.getNumWeights();\r\n int oldNumWeights2 = crf.getNumWeights();\r\n this.featureIndex.addAll(crf.featureIndex.objectsList());\r\n this.knownLCWords.addAll(crf.knownLCWords);\r\n assert (weights.length == oldNumFeatures1);\r\n\r\n // Combine weights of this classifier with other classifier\r\n for (int i = 0; i < labelIndices.length; i++) {\r\n this.labelIndices[i].addAll(crf.labelIndices[i].objectsList());\r\n }\r\n System.err.println(\"Combining weights: will automatically match labelIndices\");\r\n combineWeights(crf, weight);\r\n\r\n int numFeatures = featureIndex.size();\r\n int numWeights = getNumWeights();\r\n long elapsedMs = timer.stop();\r\n System.err.println(\"numFeatures: orig1=\" + oldNumFeatures1 + \", orig2=\" + oldNumFeatures2 + \", combined=\"\r\n + numFeatures);\r\n System.err\r\n .println(\"numWeights: orig1=\" + oldNumWeights1 + \", orig2=\" + oldNumWeights2 + \", combined=\" + numWeights);\r\n System.err.println(\"Time to combine CRFClassifier: \" + Timing.toSecondsString(elapsedMs) + \" seconds\");\r\n }",
"private D createAndRegisterDeclaration(Map<String, Object> metadata) {\n D declaration;\n if (klass.equals(ImportDeclaration.class)) {\n declaration = (D) ImportDeclarationBuilder.fromMetadata(metadata).build();\n } else if (klass.equals(ExportDeclaration.class)) {\n declaration = (D) ExportDeclarationBuilder.fromMetadata(metadata).build();\n } else {\n throw new IllegalStateException(\"\");\n }\n declarationRegistrationManager.registerDeclaration(declaration);\n return declaration;\n }",
"@Override\n public ActivityInterface getActivityInterface() {\n if (activityInterface == null) {\n activityInterface = new ActivityInterface(apiKey, sharedSecret, transport);\n }\n return activityInterface;\n }",
"public static Predicate anyBitsSet(final String expr, final long bits) {\n return new Predicate() {\n private String param;\n public void init(AbstractSqlCreator creator) {\n param = creator.allocateParameter();\n creator.setParameter(param, bits);\n }\n public String toSql() {\n return String.format(\"(%s & :%s) > 0\", expr, param);\n }\n };\n }",
"protected Class<?> loadClass(String clazz) throws ClassNotFoundException {\n\t\tif (this.classLoader == null){\n\t\t\treturn Class.forName(clazz);\n\t\t}\n\n\t\treturn Class.forName(clazz, true, this.classLoader);\n\n\t}",
"public int addServerRedirect(String region, String srcUrl, String destUrl, String hostHeader, int profileId, int groupId) throws Exception {\n int serverId = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_SERVERS\n + \"(\" + Constants.SERVER_REDIRECT_REGION + \",\" +\n Constants.SERVER_REDIRECT_SRC_URL + \",\" +\n Constants.SERVER_REDIRECT_DEST_URL + \",\" +\n Constants.SERVER_REDIRECT_HOST_HEADER + \",\" +\n Constants.SERVER_REDIRECT_PROFILE_ID + \",\" +\n Constants.SERVER_REDIRECT_GROUP_ID + \")\"\n + \" VALUES (?, ?, ?, ?, ?, ?);\", PreparedStatement.RETURN_GENERATED_KEYS);\n statement.setString(1, region);\n statement.setString(2, srcUrl);\n statement.setString(3, destUrl);\n statement.setString(4, hostHeader);\n statement.setInt(5, profileId);\n statement.setInt(6, groupId);\n statement.executeUpdate();\n\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n serverId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add path\");\n }\n } catch (SQLException 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 serverId;\n }"
] |
Creates a Blob holding a single-sheet spreadsheet with a pivot of the domain objects. The sheet name is derived from the
class name.
<p>
Minimal requirements for the domain object are:
</p>
<ul>
<li>
One property has annotation {@link PivotRow} and will be used as row identifier in left column of pivot.
Empty values are supported.
</li>
<li>
At least one property has annotation {@link PivotColumn}. Its values will be used in columns of pivot.
Empty values are supported.
</li>
<li>
At least one property has annotation {@link PivotValue}. Its values will be distributed in the pivot.
</li>
</ul> | [
"@Programmatic\n public <T> Blob toExcelPivot(\n final List<T> domainObjects,\n final Class<T> cls,\n final String fileName) throws ExcelService.Exception {\n return toExcelPivot(domainObjects, cls, null, fileName);\n }"
] | [
"protected I_CmsSearchDocument appendFieldMappingsFromElementsOnThePage(\n I_CmsSearchDocument document,\n CmsObject cms,\n CmsResource resource,\n List<String> systemFields) {\n\n try {\n CmsFile file = cms.readFile(resource);\n CmsXmlContainerPage containerPage = CmsXmlContainerPageFactory.unmarshal(cms, file);\n CmsContainerPageBean containerBean = containerPage.getContainerPage(cms);\n if (containerBean != null) {\n for (CmsContainerElementBean element : containerBean.getElements()) {\n element.initResource(cms);\n CmsResource elemResource = element.getResource();\n Set<CmsSearchField> mappedFields = getXSDMappingsForPage(cms, elemResource);\n if (mappedFields != null) {\n\n for (CmsSearchField field : mappedFields) {\n if (!systemFields.contains(field.getName())) {\n document = appendFieldMapping(\n document,\n field,\n cms,\n elemResource,\n CmsSolrDocumentXmlContent.extractXmlContent(cms, elemResource, getIndex()),\n cms.readPropertyObjects(resource, false),\n cms.readPropertyObjects(resource, true));\n } else {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.LOG_SOLR_ERR_MAPPING_TO_INTERNALLY_USED_FIELD_3,\n elemResource.getRootPath(),\n field.getName(),\n resource.getRootPath()));\n }\n }\n }\n }\n }\n } catch (CmsException e) {\n // Should be thrown if element on the page does not exist anymore - this is possible, but not necessarily an error.\n // Hence, just notice it in the debug log.\n if (LOG.isDebugEnabled()) {\n LOG.debug(e.getLocalizedMessage(), e);\n }\n }\n return document;\n }",
"public List<Map<String, String>> produceNWise(int nWise, String[] coVariables, Map<String, String[]> variableDomains) {\r\n List<Set<String>> tuples = makeNWiseTuples(coVariables, nWise);\n\r\n List<Map<String, String>> testCases = new ArrayList<>();\r\n for (Set<String> tuple : tuples) {\r\n testCases.addAll(expandTupleIntoTestCases(tuple, variableDomains));\r\n }\n\r\n return testCases;\r\n }",
"public static Interface[] get(nitro_service service) throws Exception{\n\t\tInterface obj = new Interface();\n\t\tInterface[] response = (Interface[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"protected ObjectPool setupPool(JdbcConnectionDescriptor jcd)\r\n {\r\n log.info(\"Create new ObjectPool for DBCP connections:\" + jcd);\r\n\r\n try\r\n {\r\n ClassHelper.newInstance(jcd.getDriver());\r\n }\r\n catch (InstantiationException e)\r\n {\r\n log.fatal(\"Unable to instantiate the driver class: \" + jcd.getDriver() + \" in ConnectionFactoryDBCImpl!\" , e);\r\n }\r\n catch (IllegalAccessException e)\r\n {\r\n log.fatal(\"IllegalAccessException while instantiating the driver class: \" + jcd.getDriver() + \" in ConnectionFactoryDBCImpl!\" , e);\r\n }\r\n catch (ClassNotFoundException e)\r\n {\r\n log.fatal(\"Could not find the driver class : \" + jcd.getDriver() + \" in ConnectionFactoryDBCImpl!\" , e);\r\n }\r\n\r\n // Get the configuration for the connection pool\r\n GenericObjectPool.Config conf = jcd.getConnectionPoolDescriptor().getObjectPoolConfig();\r\n\r\n // Get the additional abandoned configuration\r\n AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig();\r\n\r\n // Create the ObjectPool that serves as the actual pool of connections.\r\n final ObjectPool connectionPool = createConnectionPool(conf, ac);\r\n\r\n // Create a DriverManager-based ConnectionFactory that\r\n // the connectionPool will use to create Connection instances\r\n final org.apache.commons.dbcp.ConnectionFactory connectionFactory;\r\n connectionFactory = createConnectionFactory(jcd);\r\n\r\n // Create PreparedStatement object pool (if any)\r\n KeyedObjectPoolFactory statementPoolFactory = createStatementPoolFactory(jcd);\r\n\r\n // Set validation query and auto-commit mode\r\n final String validationQuery;\r\n final boolean defaultAutoCommit;\r\n final boolean defaultReadOnly = false;\r\n validationQuery = jcd.getConnectionPoolDescriptor().getValidationQuery();\r\n defaultAutoCommit = (jcd.getUseAutoCommit() != JdbcConnectionDescriptor.AUTO_COMMIT_SET_FALSE);\r\n\r\n //\r\n // Now we'll create the PoolableConnectionFactory, which wraps\r\n // the \"real\" Connections created by the ConnectionFactory with\r\n // the classes that implement the pooling functionality.\r\n //\r\n final PoolableConnectionFactory poolableConnectionFactory;\r\n poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,\r\n connectionPool,\r\n statementPoolFactory,\r\n validationQuery,\r\n defaultReadOnly,\r\n defaultAutoCommit,\r\n ac);\r\n return poolableConnectionFactory.getPool();\r\n }",
"public void setEmptyDefault(String iso) {\n if (iso == null || iso.isEmpty()) {\n iso = DEFAULT_COUNTRY;\n }\n int defaultIdx = mCountries.indexOfIso(iso);\n mSelectedCountry = mCountries.get(defaultIdx);\n mCountrySpinner.setSelection(defaultIdx);\n }",
"protected Date getPickerDate() {\n try {\n JsDate pickerDate = getPicker().get(\"select\").obj;\n return new Date((long) pickerDate.getTime());\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }",
"public void setCalendar(ProjectCalendar calendar)\n {\n set(TaskField.CALENDAR, calendar);\n setCalendarUniqueID(calendar == null ? null : calendar.getUniqueID());\n }",
"private SortedSet<Date> filterExceptions(SortedSet<Date> dates) {\n\n SortedSet<Date> result = new TreeSet<Date>();\n for (Date d : dates) {\n if (!m_exceptions.contains(d)) {\n result.add(d);\n }\n }\n return result;\n }",
"public static void main(String[] args) throws ParseException, IOException {\n\t\tClient client = new Client(\n\t\t\t\tnew DumpProcessingController(\"wikidatawiki\"), args);\n\t\tclient.performActions();\n\t}"
] |
Creates a "delta clone" of this Map, where only the differences are
represented. | [
"public CollectionValuedMap<K, V> deltaClone() {\r\n CollectionValuedMap<K, V> result = new CollectionValuedMap<K, V>(null, cf, true);\r\n result.map = new DeltaMap<K, Collection<V>>(this.map);\r\n return result;\r\n }"
] | [
"public static DMatrixRMaj symmetric(int length, double min, double max, Random rand) {\n DMatrixRMaj A = new DMatrixRMaj(length,length);\n\n symmetric(A,min,max,rand);\n\n return A;\n }",
"public String[] init(String[] argv, int min, int max,\n Collection<CommandLineParser.Option> options)\n throws IOException, SAXException {\n // parse command line\n parser = new CommandLineParser();\n parser.setMinimumArguments(min);\n parser.setMaximumArguments(max);\n parser.registerOption(new CommandLineParser.BooleanOption(\"reindex\", 'I'));\n if (options != null)\n for (CommandLineParser.Option option : options)\n parser.registerOption(option);\n\n try {\n argv = parser.parse(argv);\n } catch (CommandLineParser.CommandLineParserException e) {\n System.err.println(\"ERROR: \" + e.getMessage());\n usage();\n System.exit(1);\n }\n\n // do we need to reindex?\n boolean reindex = parser.getOptionState(\"reindex\");\n\n // load configuration\n config = ConfigLoader.load(argv[0]);\n database = config.getDatabase(reindex); // overwrite iff reindex\n if (database.isInMemory())\n reindex = true; // no other way to do it in this case\n\n // reindex, if requested\n if (reindex)\n reindex(config, database);\n\n return argv;\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 }",
"public static base_response update(nitro_service client, systemuser resource) throws Exception {\n\t\tsystemuser updateresource = new systemuser();\n\t\tupdateresource.username = resource.username;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.externalauth = resource.externalauth;\n\t\tupdateresource.promptstring = resource.promptstring;\n\t\tupdateresource.timeout = resource.timeout;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static Enum<?> findMatchingEnumVal(Field field, String unknownEnumName) {\n\t\tif (unknownEnumName == null || unknownEnumName.length() == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tfor (Enum<?> enumVal : (Enum<?>[]) field.getType().getEnumConstants()) {\n\t\t\tif (enumVal.name().equals(unknownEnumName)) {\n\t\t\t\treturn enumVal;\n\t\t\t}\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Unknwown enum unknown name \" + unknownEnumName + \" for field \" + field);\n\t}",
"public void callFunction(\n final String name,\n final List<?> args,\n final @Nullable Long requestTimeout) {\n this.functionService.callFunction(name, args, requestTimeout);\n }",
"public static Field getField(Class clazz, String fieldName)\r\n {\r\n try\r\n {\r\n return clazz.getField(fieldName);\r\n }\r\n catch (Exception ignored)\r\n {}\r\n return null;\r\n }",
"public ItemRequest<Workspace> update(String workspace) {\n \n String path = String.format(\"/workspaces/%s\", workspace);\n return new ItemRequest<Workspace>(this, Workspace.class, path, \"PUT\");\n }",
"private Date getTimeFromInteger(Integer time)\n {\n Date result = null;\n\n if (time != null)\n {\n int minutes = time.intValue();\n int hours = minutes / 60;\n minutes -= (hours * 60);\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.MILLISECOND, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.HOUR_OF_DAY, hours);\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n\n return (result);\n }"
] |
Prints text to output stream, replacing parameter start and end
placeholders
@param text the String to print | [
"protected void print(String text) {\n String tableStart = format(PARAMETER_TABLE_START, PARAMETER_TABLE_START);\n String tableEnd = format(PARAMETER_TABLE_END, PARAMETER_TABLE_END);\n boolean containsTable = text.contains(tableStart) && text.contains(tableEnd);\n String textToPrint = containsTable ? transformPrintingTable(text, tableStart, tableEnd) : text;\n print(output, textToPrint\n .replace(format(PARAMETER_VALUE_START, PARAMETER_VALUE_START), format(\"parameterValueStart\", EMPTY))\n .replace(format(PARAMETER_VALUE_END, PARAMETER_VALUE_END), format(\"parameterValueEnd\", EMPTY))\n .replace(format(PARAMETER_VALUE_NEWLINE, PARAMETER_VALUE_NEWLINE), format(\"parameterValueNewline\", NL)));\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 void setDoubleAttribute(String name, Double value) {\n\t\tensureAttributes();\n\t\tAttribute attribute = new DoubleAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetAllAttributes().put(name, attribute);\n\n\t}",
"String encodePath(String in) {\n try {\n String encodedString = HierarchicalUriComponents.encodeUriComponent(in, \"UTF-8\",\n HierarchicalUriComponents.Type.PATH_SEGMENT);\n if (encodedString.startsWith(_design_prefix_encoded) ||\n encodedString.startsWith(_local_prefix_encoded)) {\n // we replaced the first slash in the design or local doc URL, which we shouldn't\n // so let's put it back\n return encodedString.replaceFirst(\"%2F\", \"/\");\n } else {\n return encodedString;\n }\n } catch (UnsupportedEncodingException uee) {\n // This should never happen as every implementation of the java platform is required\n // to support UTF-8.\n throw new RuntimeException(\n \"Couldn't encode ID \" + in,\n uee);\n }\n }",
"protected TableFontStyle getColumnFontStyle(byte[] data, int offset, Map<Integer, FontBase> fontBases)\n {\n int uniqueID = MPPUtility.getInt(data, offset);\n FieldType fieldType = MPPTaskField.getInstance(MPPUtility.getShort(data, offset + 4));\n Integer index = Integer.valueOf(MPPUtility.getByte(data, offset + 8));\n int style = MPPUtility.getByte(data, offset + 9);\n ColorType color = ColorType.getInstance(MPPUtility.getByte(data, offset + 10));\n int change = MPPUtility.getByte(data, offset + 12);\n\n FontBase fontBase = fontBases.get(index);\n\n boolean bold = ((style & 0x01) != 0);\n boolean italic = ((style & 0x02) != 0);\n boolean underline = ((style & 0x04) != 0);\n\n boolean boldChanged = ((change & 0x01) != 0);\n boolean underlineChanged = ((change & 0x02) != 0);\n boolean italicChanged = ((change & 0x04) != 0);\n boolean colorChanged = ((change & 0x08) != 0);\n boolean fontChanged = ((change & 0x10) != 0);\n boolean backgroundColorChanged = (uniqueID == -1);\n boolean backgroundPatternChanged = (uniqueID == -1);\n\n return (new TableFontStyle(uniqueID, fieldType, fontBase, italic, bold, underline, false, color.getColor(), Color.BLACK, BackgroundPattern.TRANSPARENT, italicChanged, boldChanged, underlineChanged, false, colorChanged, fontChanged, backgroundColorChanged, backgroundPatternChanged));\n }",
"private void writeAvailability(Project.Resources.Resource xml, Resource mpx)\n {\n AvailabilityPeriods periods = m_factory.createProjectResourcesResourceAvailabilityPeriods();\n xml.setAvailabilityPeriods(periods);\n List<AvailabilityPeriod> list = periods.getAvailabilityPeriod();\n for (Availability availability : mpx.getAvailability())\n {\n AvailabilityPeriod period = m_factory.createProjectResourcesResourceAvailabilityPeriodsAvailabilityPeriod();\n list.add(period);\n DateRange range = availability.getRange();\n\n period.setAvailableFrom(range.getStart());\n period.setAvailableTo(range.getEnd());\n period.setAvailableUnits(DatatypeConverter.printUnits(availability.getUnits()));\n }\n }",
"public void printAnswers(List<CoreLabel> doc, PrintWriter out) {\r\n // boolean tagsMerged = flags.mergeTags;\r\n // boolean useHead = flags.splitOnHead;\r\n\r\n if ( ! \"iob1\".equalsIgnoreCase(flags.entitySubclassification)) {\r\n deEndify(doc);\r\n }\r\n\r\n for (CoreLabel fl : doc) {\r\n String word = fl.word();\r\n if (word == BOUNDARY) { // Using == is okay, because it is set to constant\r\n out.println();\r\n } else {\r\n String gold = fl.get(OriginalAnswerAnnotation.class);\r\n if(gold == null) gold = \"\";\r\n String guess = fl.get(AnswerAnnotation.class);\r\n // System.err.println(fl.word() + \"\\t\" + fl.get(AnswerAnnotation.class) + \"\\t\" + fl.get(AnswerAnnotation.class));\r\n String pos = fl.tag();\r\n String chunk = (fl.get(ChunkAnnotation.class) == null ? \"\" : fl.get(ChunkAnnotation.class));\r\n out.println(fl.word() + '\\t' + pos + '\\t' + chunk + '\\t' +\r\n gold + '\\t' + guess);\r\n }\r\n }\r\n }",
"public Map<String, String> getAttributes() {\n if (attributes == null) {\n return null;\n } else {\n return Collections.unmodifiableMap(attributes);\n }\n }",
"private static <D extends DatastoreConfiguration<G>, G extends GlobalContext<?, ?>> AppendableConfigurationContext invokeOptionConfigurator(\n\t\t\tOptionConfigurator configurator) {\n\n\t\tConfigurableImpl configurable = new ConfigurableImpl();\n\t\tconfigurator.configure( configurable );\n\t\treturn configurable.getContext();\n\t}",
"public RedwoodConfiguration printChannels(final int width){\r\n tasks.add(new Runnable() { public void run() { Redwood.Util.printChannels(width);} });\r\n return this;\r\n }"
] |
Create a WebDriver backed EmbeddedBrowser.
@param driver The WebDriver to use.
@param filterAttributes the attributes to be filtered from DOM.
@param crawlWaitReload the period to wait after a reload.
@param crawlWaitEvent the period to wait after an event is fired.
@return The EmbeddedBrowser. | [
"public static WebDriverBackedEmbeddedBrowser withDriver(WebDriver driver,\n\t\t\tImmutableSortedSet<String> filterAttributes, long crawlWaitEvent,\n\t\t\tlong crawlWaitReload) {\n\t\treturn new WebDriverBackedEmbeddedBrowser(driver, filterAttributes, crawlWaitEvent,\n\t\t\t\tcrawlWaitReload);\n\t}"
] | [
"public boolean verify(String signatureVersion, String signatureAlgorithm, String primarySignature,\n String secondarySignature, String webHookPayload, String deliveryTimestamp) {\n\n // enforce versions supported by this implementation\n if (!SUPPORTED_VERSIONS.contains(signatureVersion)) {\n return false;\n }\n\n // enforce algorithms supported by this implementation\n BoxSignatureAlgorithm algorithm = BoxSignatureAlgorithm.byName(signatureAlgorithm);\n if (!SUPPORTED_ALGORITHMS.contains(algorithm)) {\n return false;\n }\n\n // check primary key signature if primary key exists\n if (this.primarySignatureKey != null && this.verify(this.primarySignatureKey, algorithm, primarySignature,\n webHookPayload, deliveryTimestamp)) {\n return true;\n }\n\n // check secondary key signature if secondary key exists\n if (this.secondarySignatureKey != null && this.verify(this.secondarySignatureKey, algorithm, secondarySignature,\n webHookPayload, deliveryTimestamp)) {\n return true;\n }\n\n // default strategy is false, to minimize security issues\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 }",
"public int executeUpdateSQL(\r\n String sqlStatement,\r\n ClassDescriptor cld,\r\n ValueContainer[] values1,\r\n ValueContainer[] values2)\r\n throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeUpdateSQL: \" + sqlStatement);\r\n\r\n int result;\r\n int index;\r\n PreparedStatement stmt = null;\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n try\r\n {\r\n stmt = sm.getPreparedStatement(cld, sqlStatement,\r\n Query.NOT_SCROLLABLE, StatementManagerIF.FETCH_SIZE_NOT_APPLICABLE, isStoredProcedure(sqlStatement));\r\n index = sm.bindValues(stmt, values1, 1);\r\n sm.bindValues(stmt, values2, index);\r\n result = stmt.executeUpdate();\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n logger.error(\"PersistenceBrokerException during the execution of the Update SQL query: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n ValueContainer[] tmp = addValues(values1, values2);\r\n throw ExceptionHelper.generateException(e, sqlStatement, cld, tmp, logger, null);\r\n }\r\n finally\r\n {\r\n sm.closeResources(stmt, null);\r\n }\r\n return result;\r\n }",
"void reportError(Throwable throwable) {\n if (logger != null)\n logger.error(\"Timer reported error\", throwable);\n status = \"Thread blocked on error: \" + throwable;\n error_skips = error_factor;\n }",
"public String getAttribute(String section, String name) {\n Attributes attr = getManifest().getAttributes(section);\n return attr != null ? attr.getValue(name) : null;\n }",
"private static boolean isAssignableFrom(Type from, ParameterizedType to,\n\t\t\tMap<String, Type> typeVarMap) {\n\n\t\tif (from == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (to.equals(from)) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// First figure out the class and any type information.\n\t\tClass<?> clazz = getRawType(from);\n\t\tParameterizedType ptype = null;\n\t\tif (from instanceof ParameterizedType) {\n\t\t\tptype = (ParameterizedType) from;\n\t\t}\n\n\t\t// Load up parameterized variable info if it was parameterized.\n\t\tif (ptype != null) {\n\t\t\tType[] tArgs = ptype.getActualTypeArguments();\n\t\t\tTypeVariable<?>[] tParams = clazz.getTypeParameters();\n\t\t\tfor (int i = 0; i < tArgs.length; i++) {\n\t\t\t\tType arg = tArgs[i];\n\t\t\t\tTypeVariable<?> var = tParams[i];\n\t\t\t\twhile (arg instanceof TypeVariable) {\n\t\t\t\t\tTypeVariable<?> v = (TypeVariable<?>) arg;\n\t\t\t\t\targ = typeVarMap.get(v.getName());\n\t\t\t\t}\n\t\t\t\ttypeVarMap.put(var.getName(), arg);\n\t\t\t}\n\n\t\t\t// check if they are equivalent under our current mapping.\n\t\t\tif (typeEquals(ptype, to, typeVarMap)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tfor (Type itype : clazz.getGenericInterfaces()) {\n\t\t\tif (isAssignableFrom(itype, to, new HashMap<String, Type>(\n\t\t\t\t\ttypeVarMap))) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\t// Interfaces didn't work, try the superclass.\n\t\tType sType = clazz.getGenericSuperclass();\n\t\tif (isAssignableFrom(sType, to, new HashMap<String, Type>(typeVarMap))) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}",
"void setPaused(final boolean isPaused) {\n docLock.writeLock().lock();\n try {\n docsColl.updateOne(\n getDocFilter(namespace, documentId),\n new BsonDocument(\"$set\",\n new BsonDocument(\n ConfigCodec.Fields.IS_PAUSED,\n new BsonBoolean(isPaused))));\n this.isPaused = isPaused;\n } catch (IllegalStateException e) {\n // eat this\n } finally {\n docLock.writeLock().unlock();\n }\n }",
"public int getMinutesPerDay()\n {\n return m_minutesPerDay == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerDay()) : m_minutesPerDay.intValue();\n }",
"public void emitEvent(\n final NamespaceSynchronizationConfig nsConfig,\n final ChangeEvent<BsonDocument> event) {\n listenersLock.lock();\n try {\n if (nsConfig.getNamespaceListenerConfig() == null) {\n return;\n }\n final NamespaceListenerConfig namespaceListener =\n nsConfig.getNamespaceListenerConfig();\n eventDispatcher.dispatch(() -> {\n try {\n if (namespaceListener.getEventListener() != null) {\n namespaceListener.getEventListener().onEvent(\n BsonUtils.getDocumentId(event.getDocumentKey()),\n ChangeEvents.transformChangeEventForUser(\n event, namespaceListener.getDocumentCodec()));\n }\n } catch (final Exception ex) {\n logger.error(String.format(\n Locale.US,\n \"emitEvent ns=%s documentId=%s emit exception: %s\",\n event.getNamespace(),\n BsonUtils.getDocumentId(event.getDocumentKey()),\n ex), ex);\n }\n return null;\n });\n } finally {\n listenersLock.unlock();\n }\n }"
] |
Presents the Cursor Settings to the User. Only works if scene is set. | [
"private void showSettingsMenu(final Cursor cursor) {\n Log.d(TAG, \"showSettingsMenu\");\n enableSettingsCursor(cursor);\n context.runOnGlThread(new Runnable() {\n @Override\n public void run() {\n new SettingsView(context, scene, CursorManager.this,\n settingsCursor.getIoDevice().getCursorControllerId(), cursor, new\n SettingsChangeListener() {\n @Override\n public void onBack(boolean cascading) {\n disableSettingsCursor();\n }\n\n @Override\n public int onDeviceChanged(IoDevice device) {\n // we are changing the io device on the settings cursor\n removeCursorFromScene(settingsCursor);\n IoDevice clickedDevice = getAvailableIoDevice(device);\n settingsCursor.setIoDevice(clickedDevice);\n addCursorToScene(settingsCursor);\n return device.getCursorControllerId();\n }\n });\n }\n });\n }"
] | [
"public static BufferedImage convertImageToARGB( Image image ) {\n\t\tif ( image instanceof BufferedImage && ((BufferedImage)image).getType() == BufferedImage.TYPE_INT_ARGB )\n\t\t\treturn (BufferedImage)image;\n\t\tBufferedImage p = new BufferedImage( image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);\n\t\tGraphics2D g = p.createGraphics();\n\t\tg.drawImage( image, 0, 0, null );\n\t\tg.dispose();\n\t\treturn p;\n\t}",
"private void getWeeklyDates(Calendar calendar, int frequency, List<Date> dates)\n {\n int currentDay = calendar.get(Calendar.DAY_OF_WEEK);\n\n while (moreDates(calendar, dates))\n {\n int offset = 0;\n for (int dayIndex = 0; dayIndex < 7; dayIndex++)\n {\n if (getWeeklyDay(Day.getInstance(currentDay)))\n {\n if (offset != 0)\n {\n calendar.add(Calendar.DAY_OF_YEAR, offset);\n offset = 0;\n }\n if (!moreDates(calendar, dates))\n {\n break;\n }\n dates.add(calendar.getTime());\n }\n\n ++offset;\n ++currentDay;\n\n if (currentDay > 7)\n {\n currentDay = 1;\n }\n }\n\n if (frequency > 1)\n {\n offset += (7 * (frequency - 1));\n }\n calendar.add(Calendar.DAY_OF_YEAR, offset);\n }\n }",
"public static void fillProcessorAttributes(\n final List<Processor> processors,\n final Map<String, Attribute> initialAttributes) {\n Map<String, Attribute> currentAttributes = new HashMap<>(initialAttributes);\n for (Processor processor: processors) {\n if (processor instanceof RequireAttributes) {\n for (ProcessorDependencyGraphFactory.InputValue inputValue:\n ProcessorDependencyGraphFactory.getInputs(processor)) {\n if (inputValue.type == Values.class) {\n if (processor instanceof CustomDependencies) {\n for (String attributeName: ((CustomDependencies) processor).getDependencies()) {\n Attribute attribute = currentAttributes.get(attributeName);\n if (attribute != null) {\n ((RequireAttributes) processor).setAttribute(\n attributeName, currentAttributes.get(attributeName));\n }\n }\n\n } else {\n for (Map.Entry<String, Attribute> attribute: currentAttributes.entrySet()) {\n ((RequireAttributes) processor).setAttribute(\n attribute.getKey(), attribute.getValue());\n }\n }\n } else {\n try {\n ((RequireAttributes) processor).setAttribute(\n inputValue.internalName,\n currentAttributes.get(inputValue.name));\n } catch (ClassCastException e) {\n throw new IllegalArgumentException(String.format(\"The processor '%s' requires \" +\n \"the attribute '%s' \" +\n \"(%s) but he has the \" +\n \"wrong type:\\n%s\",\n processor, inputValue.name,\n inputValue.internalName,\n e.getMessage()), e);\n }\n }\n }\n }\n if (processor instanceof ProvideAttributes) {\n Map<String, Attribute> newAttributes = ((ProvideAttributes) processor).getAttributes();\n for (ProcessorDependencyGraphFactory.OutputValue ouputValue:\n ProcessorDependencyGraphFactory.getOutputValues(processor)) {\n currentAttributes.put(\n ouputValue.name, newAttributes.get(ouputValue.internalName));\n }\n }\n }\n }",
"protected String sendRequestToDF(String df_service, Object msgContent) {\n\n IDFComponentDescription[] receivers = getReceivers(df_service);\n if (receivers.length > 0) {\n IMessageEvent mevent = createMessageEvent(\"send_request\");\n mevent.getParameter(SFipa.CONTENT).setValue(msgContent);\n for (int i = 0; i < receivers.length; i++) {\n mevent.getParameterSet(SFipa.RECEIVERS).addValue(\n receivers[i].getName());\n logger.info(\"The receiver is \" + receivers[i].getName());\n }\n sendMessage(mevent);\n }\n logger.info(\"Message sended to \" + df_service + \" to \"\n + receivers.length + \" receivers\");\n return (\"Message sended to \" + df_service);\n }",
"public static void startCheck(String extra) {\n startCheckTime = System.currentTimeMillis();\n nextCheckTime = startCheckTime;\n Log.d(Log.SUBSYSTEM.TRACING, \"FPSCounter\" , \"[%d] startCheck %s\", startCheckTime, extra);\n }",
"public Optional<ServerPort> activePort() {\n final Server server = this.server;\n return server != null ? server.activePort() : Optional.empty();\n }",
"protected PrintResult withOpenOutputStream(final PrintAction function) throws Exception {\n final File reportFile = getReportFile();\n final Processor.ExecutionContext executionContext;\n try (FileOutputStream out = new FileOutputStream(reportFile);\n BufferedOutputStream bout = new BufferedOutputStream(out)) {\n executionContext = function.run(bout);\n }\n return new PrintResult(reportFile.length(), executionContext);\n }",
"public static Boolean assertTrue(Boolean value, String message) {\n if (!Boolean.valueOf(value))\n throw new IllegalStateException(message);\n\n return value;\n }",
"protected static InstallationModificationImpl.InstallationState load(final InstalledIdentity installedIdentity) throws IOException {\n final InstallationModificationImpl.InstallationState state = new InstallationModificationImpl.InstallationState();\n for (final Layer layer : installedIdentity.getLayers()) {\n state.putLayer(layer);\n }\n for (final AddOn addOn : installedIdentity.getAddOns()) {\n state.putAddOn(addOn);\n }\n return state;\n }"
] |
Sets the replacement var map.
@param replacementVarMap
the replacement var map
@return the parallel task builder | [
"public ParallelTaskBuilder setReplacementVarMap(\n Map<String, String> replacementVarMap) {\n this.replacementVarMap = replacementVarMap;\n\n // TODO Check and warning of overwriting\n // set as uniform\n this.requestReplacementType = RequestReplacementType.UNIFORM_VAR_REPLACEMENT;\n return this;\n }"
] | [
"public void useOldRESTService() throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n com.example.customerservice.CustomerService customerService = JAXRSClientFactory\n .createFromModel(\"http://localhost:\" + port + \"/examples/direct/rest\", \n com.example.customerservice.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n\n System.out.println(\"Using old RESTful CustomerService with old client\");\n\n customer.v1.Customer customer = createOldCustomer(\"Smith Old REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith Old REST\");\n printOldCustomerDetails(customer);\n }",
"public static int getDayAsReadableInt(Calendar calendar) {\n int day = calendar.get(Calendar.DAY_OF_MONTH);\n int month = calendar.get(Calendar.MONTH) + 1;\n int year = calendar.get(Calendar.YEAR);\n return year * 10000 + month * 100 + day;\n }",
"public void setProjectionMatrix(float x1, float y1, float z1, float w1,\n float x2, float y2, float z2, float w2, float x3, float y3,\n float z3, float w3, float x4, float y4, float z4, float w4) {\n NativeCustomCamera.setProjectionMatrix(getNative(), x1, y1, z1, w1, x2,\n y2, z2, w2, x3, y3, z3, w3, x4, y4, z4, w4);\n }",
"public static <T> T withStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={\"java.io.InputStream\",\"java.io.OutputStream\"}) Closure<T> closure) throws IOException {\n InputStream input = socket.getInputStream();\n OutputStream output = socket.getOutputStream();\n try {\n T result = closure.call(new Object[]{input, output});\n\n InputStream temp1 = input;\n input = null;\n temp1.close();\n OutputStream temp2 = output;\n output = null;\n temp2.close();\n\n return result;\n } finally {\n closeWithWarning(input);\n closeWithWarning(output);\n }\n }",
"public void writeLine(String pattern, Object... parameters) {\n String line = (parameters == null || parameters.length == 0) ? pattern\n : String.format(pattern, parameters);\n lines.add(0, line); // we'll write bottom to top, then purge unwritten\n // lines from end\n updateHUD();\n }",
"public <T> DiffNode compare(final T working, final T base)\n\t{\n\t\tdispatcher.resetInstanceMemory();\n\t\ttry\n\t\t{\n\t\t\treturn dispatcher.dispatch(DiffNode.ROOT, Instances.of(working, base), RootAccessor.getInstance());\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tdispatcher.clearInstanceMemory();\n\t\t}\n\t}",
"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, dnsaaaarec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnsaaaarec deleteresources[] = new dnsaaaarec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new dnsaaaarec();\n\t\t\t\tdeleteresources[i].hostname = resources[i].hostname;\n\t\t\t\tdeleteresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"private <T> T request(ClientRequest<T> delegate, String operationName) {\n long startTimeMs = -1;\n long startTimeNs = -1;\n\n if(logger.isDebugEnabled()) {\n startTimeMs = System.currentTimeMillis();\n }\n ClientRequestExecutor clientRequestExecutor = pool.checkout(destination);\n String debugMsgStr = \"\";\n\n startTimeNs = System.nanoTime();\n\n BlockingClientRequest<T> blockingClientRequest = null;\n try {\n blockingClientRequest = new BlockingClientRequest<T>(delegate, timeoutMs);\n clientRequestExecutor.addClientRequest(blockingClientRequest,\n timeoutMs,\n System.nanoTime() - startTimeNs);\n\n boolean awaitResult = blockingClientRequest.await();\n\n if(awaitResult == false) {\n blockingClientRequest.timeOut();\n }\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"success\";\n\n return blockingClientRequest.getResult();\n } catch(InterruptedException e) {\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"unreachable: \" + e.getMessage();\n\n throw new UnreachableStoreException(\"Failure in \" + operationName + \" on \"\n + destination + \": \" + e.getMessage(), e);\n } catch(UnreachableStoreException e) {\n clientRequestExecutor.close();\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"failure: \" + e.getMessage();\n\n throw new UnreachableStoreException(\"Failure in \" + operationName + \" on \"\n + destination + \": \" + e.getMessage(), e.getCause());\n } finally {\n if(blockingClientRequest != null && !blockingClientRequest.isComplete()) {\n // close the executor if we timed out\n clientRequestExecutor.close();\n }\n // Record operation time\n long opTimeNs = Utils.elapsedTimeNs(startTimeNs, System.nanoTime());\n if(stats != null) {\n stats.recordSyncOpTimeNs(destination, opTimeNs);\n }\n if(logger.isDebugEnabled()) {\n logger.debug(\"Sync request end, type: \"\n + operationName\n + \" requestRef: \"\n + System.identityHashCode(delegate)\n + \" totalTimeNs: \"\n + opTimeNs\n + \" start time: \"\n + startTimeMs\n + \" end time: \"\n + System.currentTimeMillis()\n + \" client:\"\n + clientRequestExecutor.getSocketChannel().socket().getLocalAddress()\n + \":\"\n + clientRequestExecutor.getSocketChannel().socket().getLocalPort()\n + \" server: \"\n + clientRequestExecutor.getSocketChannel()\n .socket()\n .getRemoteSocketAddress() + \" outcome: \"\n + debugMsgStr);\n }\n\n pool.checkin(destination, clientRequestExecutor);\n }\n }"
] |
Stops the service. If a timeout is given and the service has still not
gracefully been stopped after timeout ms the service is stopped by force.
@param millis value in ms | [
"@Override\n public final synchronized void stopService(long millis) {\n running = false;\n try {\n if (keepRunning) {\n keepRunning = false;\n interrupt();\n quit();\n if (0L == millis) {\n join();\n } else {\n join(millis);\n }\n }\n } catch (InterruptedException e) {\n //its possible that the thread exits between the lines keepRunning=false and interrupt above\n log.warn(\"Got interrupted while stopping {}\", this, e);\n\n Thread.currentThread().interrupt();\n }\n }"
] | [
"public void setLicense(String photoId, int licenseId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_LICENSE);\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"license_id\", Integer.toString(licenseId));\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // This method has no specific response - It returns an empty sucess response if it completes without error.\r\n\r\n }",
"public SwaptionDataLattice append(SwaptionDataLattice other, AnalyticModel model) {\r\n\r\n\t\tSwaptionDataLattice combined = new SwaptionDataLattice(referenceDate, quotingConvention, displacement,\r\n\t\t\t\tforwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule);\r\n\t\tcombined.entryMap.putAll(entryMap);\r\n\r\n\t\tif(quotingConvention == other.quotingConvention && displacement == other.displacement) {\r\n\t\t\tcombined.entryMap.putAll(other.entryMap);\r\n\t\t} else {\r\n\t\t\tSwaptionDataLattice converted = other.convertLattice(quotingConvention, displacement, model);\r\n\t\t\tcombined.entryMap.putAll(converted.entryMap);\r\n\t\t}\r\n\r\n\t\treturn combined;\r\n\t}",
"private static JSONObject parseBounds(Bounds bounds) throws JSONException {\n if (bounds != null) {\n JSONObject boundsObject = new JSONObject();\n JSONObject lowerRight = new JSONObject();\n JSONObject upperLeft = new JSONObject();\n\n lowerRight.put(\"x\",\n bounds.getLowerRight().getX().doubleValue());\n lowerRight.put(\"y\",\n bounds.getLowerRight().getY().doubleValue());\n\n upperLeft.put(\"x\",\n bounds.getUpperLeft().getX().doubleValue());\n upperLeft.put(\"y\",\n bounds.getUpperLeft().getY().doubleValue());\n\n boundsObject.put(\"lowerRight\",\n lowerRight);\n boundsObject.put(\"upperLeft\",\n upperLeft);\n\n return boundsObject;\n }\n\n return new JSONObject();\n }",
"protected void processCalendarData(ProjectCalendar calendar, Row row)\n {\n int dayIndex = row.getInt(\"CD_DAY_OR_EXCEPTION\");\n if (dayIndex == 0)\n {\n processCalendarException(calendar, row);\n }\n else\n {\n processCalendarHours(calendar, row, dayIndex);\n }\n }",
"protected void maybeSignalForMoreConnections(ConnectionPartition connectionPartition) {\r\n\r\n\t\tif (!connectionPartition.isUnableToCreateMoreTransactions() \r\n\t\t\t\t&& !this.poolShuttingDown &&\r\n\t\t\t\tconnectionPartition.getAvailableConnections()*100/connectionPartition.getMaxConnections() <= this.poolAvailabilityThreshold){\r\n\t\t\tconnectionPartition.getPoolWatchThreadSignalQueue().offer(new Object()); // item being pushed is not important.\r\n\t\t}\r\n\t}",
"static BsonDocument getDocumentVersionDoc(final BsonDocument document) {\n if (document == null || !document.containsKey(DOCUMENT_VERSION_FIELD)) {\n return null;\n }\n return document.getDocument(DOCUMENT_VERSION_FIELD, null);\n }",
"protected void updateModel(final ModelNode operation, final Resource resource) throws OperationFailedException {\n updateModel(operation, resource.getModel());\n }",
"protected final void setParentNode(final DiffNode parentNode)\n\t{\n\t\tif (this.parentNode != null && this.parentNode != parentNode)\n\t\t{\n\t\t\tthrow new IllegalStateException(\"The parent of a node cannot be changed, once it's set.\");\n\t\t}\n\t\tthis.parentNode = parentNode;\n\t}",
"public void build(Set<Bean<?>> beans) {\n\n if (isBuilt()) {\n throw new IllegalStateException(\"BeanIdentifier index is already built!\");\n }\n\n if (beans.isEmpty()) {\n index = new BeanIdentifier[0];\n reverseIndex = Collections.emptyMap();\n indexHash = 0;\n indexBuilt.set(true);\n return;\n }\n\n List<BeanIdentifier> tempIndex = new ArrayList<BeanIdentifier>(beans.size());\n\n for (Bean<?> bean : beans) {\n if (bean instanceof CommonBean<?>) {\n tempIndex.add(((CommonBean<?>) bean).getIdentifier());\n } else if (bean instanceof PassivationCapable) {\n tempIndex.add(new StringBeanIdentifier(((PassivationCapable) bean).getId()));\n }\n }\n\n Collections.sort(tempIndex, new Comparator<BeanIdentifier>() {\n @Override\n public int compare(BeanIdentifier o1, BeanIdentifier o2) {\n return o1.asString().compareTo(o2.asString());\n }\n });\n\n index = tempIndex.toArray(new BeanIdentifier[tempIndex.size()]);\n\n ImmutableMap.Builder<BeanIdentifier, Integer> builder = ImmutableMap.builder();\n for (int i = 0; i < index.length; i++) {\n builder.put(index[i], i);\n }\n reverseIndex = builder.build();\n\n indexHash = Arrays.hashCode(index);\n\n if(BootstrapLogger.LOG.isDebugEnabled()) {\n BootstrapLogger.LOG.beanIdentifierIndexBuilt(getDebugInfo());\n }\n indexBuilt.set(true);\n }"
] |
Set a bean in the context.
@param name bean name
@param object bean value | [
"public void setBean(String name, Object object) {\n\t\tBean bean = beans.get(name);\n\t\tif (null == bean) {\n\t\t\tbean = new Bean();\n\t\t\tbeans.put(name, bean);\n\t\t}\n\t\tbean.object = object;\n\t}"
] | [
"synchronized public void completeTask(int taskId, int partitionStoresMigrated) {\n tasksInFlight.remove(taskId);\n\n numTasksCompleted++;\n numPartitionStoresMigrated += partitionStoresMigrated;\n\n updateProgressBar();\n }",
"protected void updateTables()\n {\n byte[] data = m_model.getData();\n int columns = m_model.getColumns();\n int rows = (data.length / columns) + 1;\n int offset = m_model.getOffset();\n\n String[][] hexData = new String[rows][columns];\n String[][] asciiData = new String[rows][columns];\n\n int row = 0;\n int column = 0;\n StringBuilder hexValue = new StringBuilder();\n for (int index = offset; index < data.length; index++)\n {\n int value = data[index];\n hexValue.setLength(0);\n hexValue.append(HEX_DIGITS[(value & 0xF0) >> 4]);\n hexValue.append(HEX_DIGITS[value & 0x0F]);\n\n char c = (char) value;\n if ((c > 200) || (c < 27))\n {\n c = ' ';\n }\n\n hexData[row][column] = hexValue.toString();\n asciiData[row][column] = Character.toString(c);\n\n ++column;\n if (column == columns)\n {\n column = 0;\n ++row;\n }\n }\n\n String[] columnHeadings = new String[columns];\n TableModel hexTableModel = new DefaultTableModel(hexData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n TableModel asciiTableModel = new DefaultTableModel(asciiData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n m_model.setSizeValueLabel(Integer.toString(data.length));\n m_model.setHexTableModel(hexTableModel);\n m_model.setAsciiTableModel(asciiTableModel);\n m_model.setCurrentSelectionIndex(0);\n m_model.setPreviousSelectionIndex(0);\n }",
"public Number getMinutesPerMonth()\n {\n return Integer.valueOf(NumberHelper.getInt(getMinutesPerDay()) * NumberHelper.getInt(getDaysPerMonth()));\n }",
"public static JRDesignGroup getJRDesignGroup(DynamicJasperDesign jd, LayoutManager layoutManager, DJGroup group) {\n\t\tMap references = layoutManager.getReferencesMap();\n\t\tfor (Object o : references.keySet()) {\n\t\t\tString groupName = (String) o;\n\t\t\tDJGroup djGroup = (DJGroup) references.get(groupName);\n\t\t\tif (group == djGroup) {\n\t\t\t\treturn (JRDesignGroup) jd.getGroupsMap().get(groupName);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public AwsServiceClient withCodecRegistry(@Nonnull final CodecRegistry codecRegistry) {\n return new AwsServiceClientImpl(proxy.withCodecRegistry(codecRegistry), dispatcher);\n }",
"public static dnsview[] get(nitro_service service, String viewname[]) throws Exception{\n\t\tif (viewname !=null && viewname.length>0) {\n\t\t\tdnsview response[] = new dnsview[viewname.length];\n\t\t\tdnsview obj[] = new dnsview[viewname.length];\n\t\t\tfor (int i=0;i<viewname.length;i++) {\n\t\t\t\tobj[i] = new dnsview();\n\t\t\t\tobj[i].set_viewname(viewname[i]);\n\t\t\t\tresponse[i] = (dnsview) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"public boolean absolute(int row) throws PersistenceBrokerException\r\n {\r\n boolean retval;\r\n if (supportsAdvancedJDBCCursorControl())\r\n {\r\n retval = absoluteAdvanced(row);\r\n }\r\n else\r\n {\r\n retval = absoluteBasic(row);\r\n }\r\n return retval;\r\n }",
"public synchronized static SQLiteDatabase getConnection(Context context) {\n\t\tif (database == null) {\n\t\t\t// Construct the single helper and open the unique(!) db connection for the app\n\t\t\tdatabase = new CupboardDbHelper(context.getApplicationContext()).getWritableDatabase();\n\t\t}\n\t\treturn database;\n\t}",
"public void addRequest(long timeNS,\n long numEmptyResponses,\n long valueBytes,\n long keyBytes,\n long getAllAggregatedCount) {\n // timing instrumentation (trace only)\n long startTimeNs = 0;\n if(logger.isTraceEnabled()) {\n startTimeNs = System.nanoTime();\n }\n\n long currentTime = time.milliseconds();\n\n timeSensor.record((double) timeNS / voldemort.utils.Time.NS_PER_MS, currentTime);\n emptyResponseKeysSensor.record(numEmptyResponses, currentTime);\n valueBytesSensor.record(valueBytes, currentTime);\n keyBytesSensor.record(keyBytes, currentTime);\n getAllKeysCountSensor.record(getAllAggregatedCount, currentTime);\n\n // timing instrumentation (trace only)\n if(logger.isTraceEnabled()) {\n logger.trace(\"addRequest took \" + (System.nanoTime() - startTimeNs) + \" ns.\");\n }\n }"
] |
Returns the string id of the entity that this document refers to. Only
for use by Jackson during serialization.
@return string id | [
"@JsonInclude(Include.NON_EMPTY)\n\t@JsonProperty(\"id\")\n\tpublic String getJsonId() {\n\t\tif (!EntityIdValue.SITE_LOCAL.equals(this.siteIri)) {\n\t\t\treturn this.entityId;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}"
] | [
"private void prefetchRelationships(Query query)\r\n {\r\n List prefetchedRel;\r\n Collection owners;\r\n String relName;\r\n RelationshipPrefetcher[] prefetchers;\r\n\r\n if (query == null || query.getPrefetchedRelationships() == null || query.getPrefetchedRelationships().isEmpty())\r\n {\r\n return;\r\n }\r\n\r\n if (!supportsAdvancedJDBCCursorControl())\r\n {\r\n logger.info(\"prefetching relationships requires JDBC level 2.0\");\r\n return;\r\n }\r\n\r\n // prevent releasing of DBResources\r\n setInBatchedMode(true);\r\n\r\n prefetchedRel = query.getPrefetchedRelationships();\r\n prefetchers = new RelationshipPrefetcher[prefetchedRel.size()];\r\n\r\n // disable auto retrieve for all prefetched relationships\r\n for (int i = 0; i < prefetchedRel.size(); i++)\r\n {\r\n relName = (String) prefetchedRel.get(i);\r\n prefetchers[i] = getBroker().getRelationshipPrefetcherFactory()\r\n .createRelationshipPrefetcher(getQueryObject().getClassDescriptor(), relName);\r\n prefetchers[i].prepareRelationshipSettings();\r\n }\r\n\r\n // materialize ALL owners of this Iterator\r\n owners = getOwnerObjects();\r\n\r\n // prefetch relationships and associate with owners\r\n for (int i = 0; i < prefetchedRel.size(); i++)\r\n {\r\n prefetchers[i].prefetchRelationship(owners);\r\n }\r\n\r\n // reset auto retrieve for all prefetched relationships\r\n for (int i = 0; i < prefetchedRel.size(); i++)\r\n {\r\n prefetchers[i].restoreRelationshipSettings();\r\n }\r\n\r\n try\r\n {\r\n getRsAndStmt().m_rs.beforeFirst(); // reposition resultset jdbc 2.0\r\n }\r\n catch (SQLException e)\r\n {\r\n logger.error(\"beforeFirst failed !\", e);\r\n }\r\n\r\n setInBatchedMode(false);\r\n setHasCalledCheck(false);\r\n }",
"private Set<Artifact> findThriftDependencies() throws IOException, MojoExecutionException {\n Set<Artifact> thriftDependencies = new HashSet<Artifact>();\n\n Set<Artifact> deps = new HashSet<Artifact>();\n deps.addAll(project.getArtifacts());\n deps.addAll(project.getDependencyArtifacts());\n\n Map<String, Artifact> depsMap = new HashMap<String, Artifact>();\n for (Artifact dep : deps) {\n depsMap.put(dep.getId(), dep);\n }\n\n for (Artifact artifact : deps) {\n // This artifact has an idl classifier.\n if (isIdlCalssifier(artifact, classifier)) {\n thriftDependencies.add(artifact);\n } else {\n if (isDepOfIdlArtifact(artifact, depsMap)) {\n // Fetch idl artifact for dependency of an idl artifact.\n try {\n Artifact idlArtifact = MavenScroogeCompilerUtil.getIdlArtifact(\n artifact,\n artifactFactory,\n artifactResolver,\n localRepository,\n remoteArtifactRepositories,\n classifier);\n thriftDependencies.add(idlArtifact);\n } catch (MojoExecutionException e) {\n /* Do nothing as this artifact is not an idl artifact\n binary jars may have dependency on thrift lib etc.\n */\n getLog().debug(\"Could not fetch idl jar for \" + artifact);\n }\n }\n }\n }\n return thriftDependencies;\n }",
"private JSONValue datesToJsonArray(Collection<Date> dates) {\n\n if (null != dates) {\n JSONArray result = new JSONArray();\n for (Date d : dates) {\n result.set(result.size(), dateToJson(d));\n }\n return result;\n }\n return null;\n }",
"public void processField(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n String defaultType = getDefaultJdbcTypeForCurrentMember();\r\n String defaultConversion = getDefaultJdbcConversionForCurrentMember();\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 LogHelper.debug(false, OjbTagsHandler.class, \"processField\", \" Processing field \"+fieldDef.getName());\r\n\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 // storing additional info for later use\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_JAVA_TYPE,\r\n OjbMemberTagsHandler.getMemberType().getQualifiedName());\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_JDBC_TYPE, defaultType);\r\n if (defaultConversion != null)\r\n { \r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION, defaultConversion);\r\n }\r\n\r\n _curFieldDef = fieldDef;\r\n generate(template);\r\n _curFieldDef = null;\r\n }",
"public static base_responses add(nitro_service client, dospolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdospolicy addresources[] = new dospolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dospolicy();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].qdepth = resources[i].qdepth;\n\t\t\t\taddresources[i].cltdetectrate = resources[i].cltdetectrate;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static nsacl6 get(nitro_service service, String acl6name) throws Exception{\n\t\tnsacl6 obj = new nsacl6();\n\t\tobj.set_acl6name(acl6name);\n\t\tnsacl6 response = (nsacl6) obj.get_resource(service);\n\t\treturn response;\n\t}",
"@Override\n public void onRotationSensor(long timeStamp, float rotationW, float rotationX, float rotationY, float rotationZ,\n float gyroX, float gyroY, float gyroZ) {\n GVRCameraRig cameraRig = null;\n if (mMainScene != null) {\n cameraRig = mMainScene.getMainCameraRig();\n }\n\n if (cameraRig != null) {\n cameraRig.setRotationSensorData(timeStamp, rotationW, rotationX, rotationY, rotationZ, gyroX, gyroY, gyroZ);\n updateSensoredScene();\n }\n }",
"CapabilityRegistry createShadowCopy() {\n CapabilityRegistry result = new CapabilityRegistry(forServer, this);\n readLock.lock();\n try {\n try {\n result.writeLock.lock();\n copy(this, result);\n } finally {\n result.writeLock.unlock();\n }\n } finally {\n readLock.unlock();\n }\n return result;\n }",
"public static aaapreauthenticationpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\taaapreauthenticationpolicy_binding obj = new aaapreauthenticationpolicy_binding();\n\t\tobj.set_name(name);\n\t\taaapreauthenticationpolicy_binding response = (aaapreauthenticationpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Creates all propertyvfsbundle files for the currently loaded translations.
The method is used to convert xmlvfsbundle files into propertyvfsbundle files.
@throws CmsIllegalArgumentException thrown if resource creation fails.
@throws CmsLoaderException thrown if the propertyvfsbundle type can't be read from the resource manager.
@throws CmsException thrown if creation, type retrieval or locking fails. | [
"private void createPropertyVfsBundleFiles() throws CmsIllegalArgumentException, CmsLoaderException, CmsException {\n\n String bundleFileBasePath = m_sitepath + m_basename + \"_\";\n for (Locale l : m_localizations.keySet()) {\n CmsResource res = m_cms.createResource(\n bundleFileBasePath + l.toString(),\n OpenCms.getResourceManager().getResourceType(\n CmsMessageBundleEditorTypes.BundleType.PROPERTY.toString()));\n m_bundleFiles.put(l, res);\n LockedFile file = LockedFile.lockResource(m_cms, res);\n file.setCreated(true);\n m_lockedBundleFiles.put(l, file);\n m_changedTranslations.add(l);\n }\n\n }"
] | [
"public static String parseString(String value)\n {\n if (value != null)\n {\n // Strip angle brackets if present\n if (!value.isEmpty() && value.charAt(0) == '<')\n {\n value = value.substring(1, value.length() - 1);\n }\n\n // Strip quotes if present\n if (!value.isEmpty() && value.charAt(0) == '\"')\n {\n value = value.substring(1, value.length() - 1);\n }\n }\n return value;\n }",
"public static <T> T objectify(ObjectMapper mapper, Object source, JavaType targetType) {\n try {\n return mapper.readValue(mapper.writeValueAsBytes(source), targetType);\n } catch (RuntimeException e) {\n throw e;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"public static long getGcTimestamp(String zookeepers) {\n ZooKeeper zk = null;\n try {\n zk = new ZooKeeper(zookeepers, 30000, null);\n\n // wait until zookeeper is connected\n long start = System.currentTimeMillis();\n while (!zk.getState().isConnected() && System.currentTimeMillis() - start < 30000) {\n Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS);\n }\n\n byte[] d = zk.getData(ZookeeperPath.ORACLE_GC_TIMESTAMP, false, null);\n return LongUtil.fromByteArray(d);\n } catch (KeeperException | InterruptedException | IOException e) {\n log.warn(\"Failed to get oldest timestamp of Oracle from Zookeeper\", e);\n return OLDEST_POSSIBLE;\n } finally {\n if (zk != null) {\n try {\n zk.close();\n } catch (InterruptedException e) {\n log.error(\"Failed to close zookeeper client\", e);\n }\n }\n }\n }",
"public int getIndexByDate(Date date)\n {\n int result = -1;\n int index = 0;\n\n for (CostRateTableEntry entry : this)\n {\n if (DateHelper.compare(date, entry.getEndDate()) < 0)\n {\n result = index;\n break;\n }\n ++index;\n }\n\n return result;\n }",
"public static Object[] filterMapToObjectArray(final Map<String, ?> values, final String[] nameMapping) {\n\t\t\n\t\tif( values == null ) {\n\t\t\tthrow new NullPointerException(\"values should not be null\");\n\t\t} else if( nameMapping == null ) {\n\t\t\tthrow new NullPointerException(\"nameMapping should not be null\");\n\t\t}\n\t\t\n\t\tfinal Object[] targetArray = new Object[nameMapping.length];\n\t\tint i = 0;\n\t\tfor( final String name : nameMapping ) {\n\t\t\ttargetArray[i++] = values.get(name);\n\t\t}\n\t\treturn targetArray;\n\t}",
"@Override\n public void detachScriptFile(IScriptable target) {\n IScriptFile scriptFile = mScriptMap.remove(target);\n if (scriptFile != null) {\n scriptFile.invokeFunction(\"onDetach\", new Object[] { target });\n }\n }",
"protected void appendFacetOption(StringBuffer query, final String name, final String value) {\n\n query.append(\" facet.\").append(name).append(\"=\").append(value);\n }",
"@Override\n\tpublic <T> T get(Object key, Resource resource, Provider<T> provider) {\n\t\tif(resource == null) {\n\t\t\treturn provider.get();\n\t\t}\n\t\tCacheAdapter adapter = getOrCreate(resource);\n\t\tT element = adapter.<T>internalGet(key);\n\t\tif (element==null) {\n\t\t\telement = provider.get();\n\t\t\tcacheMiss(adapter);\n\t\t\tadapter.set(key, element);\n\t\t} else {\n\t\t\tcacheHit(adapter);\n\t\t}\n\t\tif (element == CacheAdapter.NULL) {\n\t\t\treturn null;\n\t\t}\n\t\treturn element;\n\t}",
"public List<Widget> getAllViews() {\n List<Widget> views = new ArrayList<>();\n for (Widget child: mContent.getChildren()) {\n Widget item = ((ListItemHostWidget) child).getGuest();\n if (item != null) {\n views.add(item);\n }\n }\n return views;\n }"
] |
Checks to see if the submatrix has its boundaries along inner blocks.
@param blockLength Size of an inner block.
@param A Submatrix.
@return If it is block aligned or not. | [
"public static boolean blockAligned( int blockLength , DSubmatrixD1 A ) {\n if( A.col0 % blockLength != 0 )\n return false;\n if( A.row0 % blockLength != 0 )\n return false;\n\n if( A.col1 % blockLength != 0 && A.col1 != A.original.numCols ) {\n return false;\n }\n\n if( A.row1 % blockLength != 0 && A.row1 != A.original.numRows) {\n return false;\n }\n\n return true;\n }"
] | [
"public static <T> List<T> load(ClassLoader classLoader, Class<T> serviceType) {\n List<T> foundServices = new ArrayList<>();\n Iterator<T> iterator = ServiceLoader.load(serviceType, classLoader).iterator();\n\n while (checkHasNextSafely(iterator)) {\n try {\n T item = iterator.next();\n foundServices.add(item);\n LOGGER.debug(String.format(\"Found %s [%s]\", serviceType.getSimpleName(), item.toString()));\n } catch (ServiceConfigurationError e) {\n LOGGER.trace(\"Can't find services using Java SPI\", e);\n LOGGER.error(e.getMessage());\n }\n }\n return foundServices;\n }",
"public static File createFolder(String path, String dest_dir)\n throws BeastException {\n File f = new File(dest_dir);\n if (!f.isDirectory()) {\n try {\n f.mkdirs();\n } catch (Exception e) {\n logger.severe(\"Problem creating directory: \" + path\n + File.separator + dest_dir);\n }\n }\n\n String folderPath = createFolderPath(path);\n\n f = new File(f, folderPath);\n if (!f.isDirectory()) {\n try {\n f.mkdirs();\n } catch (Exception e) {\n String message = \"Problem creating directory: \" + path\n + File.separator + dest_dir;\n logger.severe(message);\n throw new BeastException(message, e);\n }\n }\n\n return f;\n }",
"private static Map<String, String> mapCustomInfo(CustomInfoType ciType){\n Map<String, String> customInfo = new HashMap<String, String>();\n if (ciType != null){\n for (CustomInfoType.Item item : ciType.getItem()) {\n customInfo.put(item.getKey(), item.getValue());\n }\n }\n return customInfo;\n }",
"public static base_response add(nitro_service client, inat resource) throws Exception {\n\t\tinat addresource = new inat();\n\t\taddresource.name = resource.name;\n\t\taddresource.publicip = resource.publicip;\n\t\taddresource.privateip = resource.privateip;\n\t\taddresource.tcpproxy = resource.tcpproxy;\n\t\taddresource.ftp = resource.ftp;\n\t\taddresource.tftp = resource.tftp;\n\t\taddresource.usip = resource.usip;\n\t\taddresource.usnip = resource.usnip;\n\t\taddresource.proxyip = resource.proxyip;\n\t\taddresource.mode = resource.mode;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}",
"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}",
"public void setBackgroundColor(int color) {\n colorUnpressed = color;\n\n if(!isSelected()) {\n if (rippleAnimationSupport()) {\n ripple.setRippleBackground(colorUnpressed);\n }\n else {\n view.setBackgroundColor(colorUnpressed);\n }\n }\n }",
"@Override\n public void put(ByteArray keyBytes, Versioned<byte[]> valueBytes, byte[] transforms)\n throws VoldemortException {\n // acquire write lock\n writeLock.lock();\n try {\n String key = ByteUtils.getString(keyBytes.get(), \"UTF-8\");\n Versioned<String> value = new Versioned<String>(ByteUtils.getString(valueBytes.getValue(),\n \"UTF-8\"),\n valueBytes.getVersion());\n\n Versioned<Object> valueObject = convertStringToObject(key, value);\n\n this.put(key, valueObject);\n } finally {\n writeLock.unlock();\n }\n }",
"protected static <R extends AddressSection, S extends AddressSegment> R fastIncrement(\n\t\t\tR section,\n\t\t\tlong increment,\n\t\t\tAddressCreator<?, R, ?, S> addrCreator, \n\t\t\tSupplier<R> lowerProducer,\n\t\t\tSupplier<R> upperProducer,\n\t\t\tInteger prefixLength) {\n\t\tif(increment >= 0) {\n\t\t\tBigInteger count = section.getCount();\n\t\t\tif(count.compareTo(LONG_MAX) <= 0) {\n\t\t\t\tlong longCount = count.longValue();\n\t\t\t\tif(longCount > increment) {\n\t\t\t\t\tif(longCount == increment + 1) {\n\t\t\t\t\t\treturn upperProducer.get();\n\t\t\t\t\t}\n\t\t\t\t\treturn incrementRange(section, increment, addrCreator, lowerProducer, prefixLength);\n\t\t\t\t}\n\t\t\t\tBigInteger value = section.getValue();\n\t\t\t\tBigInteger upperValue;\n\t\t\t\tif(value.compareTo(LONG_MAX) <= 0 && (upperValue = section.getUpperValue()).compareTo(LONG_MAX) <= 0) {\n\t\t\t\t\treturn increment(\n\t\t\t\t\t\t\tsection,\n\t\t\t\t\t\t\tincrement,\n\t\t\t\t\t\t\taddrCreator,\n\t\t\t\t\t\t\tcount.longValue(),\n\t\t\t\t\t\t\tvalue.longValue(),\n\t\t\t\t\t\t\tupperValue.longValue(),\n\t\t\t\t\t\t\tlowerProducer,\n\t\t\t\t\t\t\tupperProducer,\n\t\t\t\t\t\t\tprefixLength);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tBigInteger value = section.getValue();\n\t\t\tif(value.compareTo(LONG_MAX) <= 0) {\n\t\t\t\treturn add(lowerProducer.get(), value.longValue(), increment, addrCreator, prefixLength);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public QueryBuilder<T, ID> groupByRaw(String rawSql) {\n\t\taddGroupBy(ColumnNameOrRawSql.withRawSql(rawSql));\n\t\treturn this;\n\t}"
] |
Use this API to fetch dnssuffix resource of given name . | [
"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}"
] | [
"public static base_response delete(nitro_service client, String servicename) throws Exception {\n\t\tgslbservice deleteresource = new gslbservice();\n\t\tdeleteresource.servicename = servicename;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public static void assertValidNode(MetadataStore metadataStore, Integer nodeId) {\n if(!metadataStore.getCluster().hasNodeWithId(nodeId)) {\n throw new InvalidMetadataException(\"NodeId \" + nodeId + \" is not or no longer in this cluster\");\n }\n }",
"public static void logBeforeExit(ExitLogger logger) {\n try {\n if (logged.compareAndSet(false, true)) {\n logger.logExit();\n }\n } catch (Throwable ignored){\n // ignored\n }\n }",
"public String getLinkCopyText(JSONObject jsonObject){\n if(jsonObject == null) return \"\";\n try {\n JSONObject copyObject = jsonObject.has(\"copyText\") ? jsonObject.getJSONObject(\"copyText\") : null;\n if(copyObject != null){\n return copyObject.has(\"text\") ? copyObject.getString(\"text\") : \"\";\n }else{\n return \"\";\n }\n } catch (JSONException e) {\n Logger.v(\"Unable to get Link Text with JSON - \"+e.getLocalizedMessage());\n return \"\";\n }\n }",
"public static void mergeReports(File reportOverall, File... reports) {\n SessionInfoStore infoStore = new SessionInfoStore();\n ExecutionDataStore dataStore = new ExecutionDataStore();\n boolean isCurrentVersionFormat = loadSourceFiles(infoStore, dataStore, reports);\n\n try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(reportOverall))) {\n Object visitor;\n if (isCurrentVersionFormat) {\n visitor = new ExecutionDataWriter(outputStream);\n } else {\n visitor = new org.jacoco.previous.core.data.ExecutionDataWriter(outputStream);\n }\n infoStore.accept((ISessionInfoVisitor) visitor);\n dataStore.accept((IExecutionDataVisitor) visitor);\n } catch (IOException e) {\n throw new IllegalStateException(String.format(\"Unable to write overall coverage report %s\", reportOverall.getAbsolutePath()), e);\n }\n }",
"static DocumentVersionInfo getRemoteVersionInfo(final BsonDocument remoteDocument) {\n final BsonDocument version = getDocumentVersionDoc(remoteDocument);\n return new DocumentVersionInfo(\n version,\n remoteDocument != null\n ? BsonUtils.getDocumentId(remoteDocument) : null\n );\n }",
"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 }",
"private static void parseSsextensions(JSONObject modelJSON,\n Diagram current) throws JSONException {\n if (modelJSON.has(\"ssextensions\")) {\n JSONArray array = modelJSON.getJSONArray(\"ssextensions\");\n for (int i = 0; i < array.length(); i++) {\n current.addSsextension(array.getString(i));\n }\n }\n }",
"public void setMonitoringService(org.talend.esb.sam.common.service.MonitoringService monitoringService) {\n this.monitoringService = monitoringService;\n }"
] |
Delete with retry.
@param file
@return <tt>true</tt> if the file was successfully deleted. | [
"public boolean deleteExisting(final File file) {\n if (!file.exists()) {\n return true;\n }\n boolean deleted = false;\n if (file.canWrite()) {\n deleted = file.delete();\n } else {\n LogLog.debug(file + \" is not writeable for delete (retrying)\");\n }\n if (!deleted) {\n if (!file.exists()) {\n deleted = true;\n } else {\n file.delete();\n deleted = (!file.exists());\n }\n }\n return deleted;\n }"
] | [
"public double distanceFrom(LatLong end) {\n\n double dLat = (end.getLatitude() - getLatitude()) * Math.PI / 180;\n double dLon = (end.getLongitude() - getLongitude()) * Math.PI / 180;\n\n double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)\n + Math.cos(getLatitude() * Math.PI / 180)\n * Math.cos(end.getLatitude() * Math.PI / 180)\n * Math.sin(dLon / 2) * Math.sin(dLon / 2);\n\n double c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n double d = EarthRadiusMeters * c;\n return d;\n }",
"public String name(Properties attributes) throws XDocletException\r\n {\r\n return getDefForLevel(attributes.getProperty(ATTRIBUTE_LEVEL)).getName();\r\n }",
"public void writeLine(String pattern, Object... parameters) {\n String line = (parameters == null || parameters.length == 0) ? pattern\n : String.format(pattern, parameters);\n lines.add(0, line); // we'll write bottom to top, then purge unwritten\n // lines from end\n updateHUD();\n }",
"public void setDefaults(Annotation[] defaultAnnotations) {\n if (defaultAnnotations == null) {\n return;\n }\n for (Annotation each : defaultAnnotations) {\n Class<? extends Annotation> key = each.annotationType();\n if (Title.class.equals(key) || Description.class.equals(key)) {\n continue;\n }\n if (!annotations.containsKey(key)) {\n annotations.put(key, each);\n }\n }\n }",
"public double getSpread(double bondPrice, Curve referenceCurve, AnalyticModel model) {\n\t\tGoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0);\n\t\twhile(search.getAccuracy() > 1E-11 && !search.isDone()) {\n\t\t\tdouble x = search.getNextPoint();\n\t\t\tdouble fx=getValueWithGivenSpreadOverCurve(0.0,referenceCurve,x,model);\n\t\t\tdouble y = (bondPrice-fx)*(bondPrice-fx);\n\n\t\t\tsearch.setValue(y);\n\t\t}\n\t\treturn search.getBestPoint();\n\t}",
"synchronized boolean reload(int permit, boolean suspend) {\n return internalSetState(new ReloadTask(permit, suspend), InternalState.SERVER_STARTED, InternalState.RELOADING);\n }",
"public static vlan_interface_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tvlan_interface_binding obj = new vlan_interface_binding();\n\t\tobj.set_id(id);\n\t\tvlan_interface_binding response[] = (vlan_interface_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public List<NodeInfo> getNodes() {\n final URI uri = uriWithPath(\"./nodes/\");\n return Arrays.asList(this.rt.getForObject(uri, NodeInfo[].class));\n }",
"public void generateTracedFile(final IFileSystemAccess2 fsa, final String path, final EObject rootTrace, final StringConcatenationClient code) {\n final CompositeGeneratorNode node = this.trace(rootTrace, code);\n this.generateTracedFile(fsa, path, node);\n }"
] |
Creates and returns a matrix which is idential to this one.
@return A new identical matrix. | [
"public T copy() {\n T ret = createLike();\n ret.getMatrix().set(this.getMatrix());\n return ret;\n }"
] | [
"public void loadAnimation(GVRAndroidResource animResource, String boneMap)\n {\n String filePath = animResource.getResourcePath();\n GVRContext ctx = mAvatarRoot.getGVRContext();\n GVRResourceVolume volume = new GVRResourceVolume(ctx, animResource);\n\n if (filePath.endsWith(\".bvh\"))\n {\n GVRAnimator animator = new GVRAnimator(ctx);\n animator.setName(filePath);\n try\n {\n BVHImporter importer = new BVHImporter(ctx);\n GVRSkeletonAnimation skelAnim;\n\n if (boneMap != null)\n {\n GVRSkeleton skel = importer.importSkeleton(animResource);\n skelAnim = importer.readMotion(skel);\n animator.addAnimation(skelAnim);\n\n GVRPoseMapper retargeter = new GVRPoseMapper(mSkeleton, skel, skelAnim.getDuration());\n retargeter.setBoneMap(boneMap);\n animator.addAnimation(retargeter);\n }\n else\n {\n skelAnim = importer.importAnimation(animResource, mSkeleton);\n animator.addAnimation(skelAnim);\n }\n addAnimation(animator);\n ctx.getEventManager().sendEvent(this,\n IAvatarEvents.class,\n \"onAnimationLoaded\",\n GVRAvatar.this,\n animator,\n filePath,\n null);\n }\n catch (IOException ex)\n {\n ctx.getEventManager().sendEvent(this,\n IAvatarEvents.class,\n \"onAnimationLoaded\",\n GVRAvatar.this,\n null,\n filePath,\n ex.getMessage());\n }\n }\n else\n {\n EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_TEXTURING));\n\n GVRSceneObject animRoot = new GVRSceneObject(ctx);\n ctx.getAssetLoader().loadModel(volume, animRoot, settings, false, mLoadAnimHandler);\n }\n }",
"public static onlinkipv6prefix get(nitro_service service, String ipv6prefix) throws Exception{\n\t\tonlinkipv6prefix obj = new onlinkipv6prefix();\n\t\tobj.set_ipv6prefix(ipv6prefix);\n\t\tonlinkipv6prefix response = (onlinkipv6prefix) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static double blackScholesDigitalOptionVega(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0 || optionMaturity <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate vega\n\t\t\tdouble dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\t\t\tdouble dMinus = dPlus - volatility * Math.sqrt(optionMaturity);\n\n\t\t\tdouble vega = - Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI) * dPlus / volatility;\n\n\t\t\treturn vega;\n\t\t}\n\t}",
"public final void configureAccess(final Template template, final ApplicationContext context) {\n final Configuration configuration = template.getConfiguration();\n\n AndAccessAssertion accessAssertion = context.getBean(AndAccessAssertion.class);\n accessAssertion.setPredicates(configuration.getAccessAssertion(), template.getAccessAssertion());\n this.access = accessAssertion;\n }",
"public void performActions() {\n\t\tif (this.clientConfiguration.getActions().isEmpty()) {\n\t\t\tthis.clientConfiguration.printHelp();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.dumpProcessingController.setOfflineMode(this.clientConfiguration\n\t\t\t\t.getOfflineMode());\n\n\t\tif (this.clientConfiguration.getDumpDirectoryLocation() != null) {\n\t\t\ttry {\n\t\t\t\tthis.dumpProcessingController\n\t\t\t\t\t\t.setDownloadDirectory(this.clientConfiguration\n\t\t\t\t\t\t\t\t.getDumpDirectoryLocation());\n\t\t\t} catch (IOException e) {\n\t\t\t\tlogger.error(\"Could not set download directory to \"\n\t\t\t\t\t\t+ this.clientConfiguration.getDumpDirectoryLocation()\n\t\t\t\t\t\t+ \": \" + e.getMessage());\n\t\t\t\tlogger.error(\"Aborting\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tdumpProcessingController.setLanguageFilter(this.clientConfiguration\n\t\t\t\t.getFilterLanguages());\n\t\tdumpProcessingController.setSiteLinkFilter(this.clientConfiguration\n\t\t\t\t.getFilterSiteKeys());\n\t\tdumpProcessingController.setPropertyFilter(this.clientConfiguration\n\t\t\t\t.getFilterProperties());\n\n\t\tMwDumpFile dumpFile = this.clientConfiguration.getLocalDumpFile();\n\n\t\tif (dumpFile == null) {\n\t\t\tdumpFile = dumpProcessingController\n\t\t\t\t\t.getMostRecentDump(DumpContentType.JSON);\n\t\t} else {\n\t\t\tif (!dumpFile.isAvailable()) {\n\t\t\t\tlogger.error(\"Dump file not found or not readable: \"\n\t\t\t\t\t\t+ dumpFile.toString());\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tthis.clientConfiguration.setProjectName(dumpFile.getProjectName());\n\t\tthis.clientConfiguration.setDateStamp(dumpFile.getDateStamp());\n\n\t\tboolean hasReadyProcessor = false;\n\t\tfor (DumpProcessingAction props : this.clientConfiguration.getActions()) {\n\n\t\t\tif (!props.isReady()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (props.needsSites()) {\n\t\t\t\tprepareSites();\n\t\t\t\tif (this.sites == null) { // sites unavailable\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tprops.setSites(this.sites);\n\t\t\t}\n\t\t\tprops.setDumpInformation(dumpFile.getProjectName(),\n\t\t\t\t\tdumpFile.getDateStamp());\n\t\t\tthis.dumpProcessingController.registerEntityDocumentProcessor(\n\t\t\t\t\tprops, null, true);\n\t\t\thasReadyProcessor = true;\n\t\t}\n\n\t\tif (!hasReadyProcessor) {\n\t\t\treturn; // silent; non-ready action should report its problem\n\t\t\t\t\t// directly\n\t\t}\n\n\t\tif (!this.clientConfiguration.isQuiet()) {\n\t\t\tEntityTimerProcessor entityTimerProcessor = new EntityTimerProcessor(\n\t\t\t\t\t0);\n\t\t\tthis.dumpProcessingController.registerEntityDocumentProcessor(\n\t\t\t\t\tentityTimerProcessor, null, true);\n\t\t}\n\t\topenActions();\n\t\tthis.dumpProcessingController.processDump(dumpFile);\n\t\tcloseActions();\n\n\t\ttry {\n\t\t\twriteReport();\n\t\t} catch (IOException e) {\n\t\t\tlogger.error(\"Could not print report file: \" + e.getMessage());\n\t\t}\n\n\t}",
"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 void handleMultiInstanceReportResponse(SerialMessage serialMessage,\r\n\t\t\tint offset) {\r\n\t\tlogger.trace(\"Process Multi-instance Report\");\r\n\t\tint commandClassCode = serialMessage.getMessagePayloadByte(offset);\r\n\t\tint instances = serialMessage.getMessagePayloadByte(offset + 1);\r\n\r\n\t\tif (instances == 0) {\r\n\t\t\tsetInstances(1);\r\n\t\t} else \r\n\t\t{\r\n\t\t\tCommandClass commandClass = CommandClass.getCommandClass(commandClassCode);\r\n\t\t\t\r\n\t\t\tif (commandClass == null) {\r\n\t\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tlogger.debug(String.format(\"Node %d Requested Command Class = %s (0x%02x)\", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));\r\n\t\t\tZWaveCommandClass zwaveCommandClass = this.getNode().getCommandClass(commandClass);\r\n\t\t\t\r\n\t\t\tif (zwaveCommandClass == null) {\r\n\t\t\t\tlogger.error(String.format(\"Unsupported command class %s (0x%02x)\", commandClass.getLabel(), commandClassCode));\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tzwaveCommandClass.setInstances(instances);\r\n\t\t\tlogger.debug(String.format(\"Node %d Instances = %d, number of instances set.\", this.getNode().getNodeId(), instances));\r\n\t\t}\r\n\t\t\r\n\t\tfor (ZWaveCommandClass zwaveCommandClass : this.getNode().getCommandClasses())\r\n\t\t\tif (zwaveCommandClass.getInstances() == 0) // still waiting for an instance report of another command class. \r\n\t\t\t\treturn;\r\n\t\t\r\n\t\t// advance node stage.\r\n\t\tthis.getNode().advanceNodeStage();\r\n\t}",
"public Indexes listIndexes() {\n URI uri = new DatabaseURIHelper(db.getDBUri()).path(\"_index\").build();\n return client.couchDbClient.get(uri, Indexes.class);\n }",
"public synchronized void createImportationDeclaration(String deviceId, String deviceType, String deviceSubType) {\n Map<String, Object> metadata = new HashMap<String, Object>();\n metadata.put(Constants.DEVICE_ID, deviceId);\n metadata.put(Constants.DEVICE_TYPE, deviceType);\n metadata.put(Constants.DEVICE_TYPE_SUB, deviceSubType);\n metadata.put(\"scope\", \"generic\");\n ImportDeclaration declaration = ImportDeclarationBuilder.fromMetadata(metadata).build();\n\n importDeclarations.put(deviceId, declaration);\n\n registerImportDeclaration(declaration);\n }"
] |
Use this API to update systemcollectionparam. | [
"public static base_response update(nitro_service client, systemcollectionparam resource) throws Exception {\n\t\tsystemcollectionparam updateresource = new systemcollectionparam();\n\t\tupdateresource.communityname = resource.communityname;\n\t\tupdateresource.loglevel = resource.loglevel;\n\t\tupdateresource.datapath = resource.datapath;\n\t\treturn updateresource.update_resource(client);\n\t}"
] | [
"public static base_response update(nitro_service client, nsrpcnode resource) throws Exception {\n\t\tnsrpcnode updateresource = new nsrpcnode();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.srcip = resource.srcip;\n\t\tupdateresource.secure = resource.secure;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public Curve getRegressionCurve(){\n\t\t// @TODO Add threadsafe lazy init.\n\t\tif(regressionCurve !=null) {\n\t\t\treturn regressionCurve;\n\t\t}\n\t\tDoubleMatrix a = solveEquationSystem();\n\t\tdouble[] curvePoints=new double[partition.getLength()];\n\t\tcurvePoints[0]=a.get(0);\n\t\tfor(int i=1;i<curvePoints.length;i++) {\n\t\t\tcurvePoints[i]=curvePoints[i-1]+a.get(i)*(partition.getIntervalLength(i-1));\n\t\t}\n\t\treturn new CurveInterpolation(\n\t\t\t\t\"RegressionCurve\",\n\t\t\t\treferenceDate,\n\t\t\t\tCurveInterpolation.InterpolationMethod.LINEAR,\n\t\t\t\tCurveInterpolation.ExtrapolationMethod.CONSTANT,\n\t\t\t\tCurveInterpolation.InterpolationEntity.VALUE,\n\t\t\t\tpartition.getPoints(),\n\t\t\t\tcurvePoints);\n\t}",
"public ItemRequest<Section> delete(String section) {\n \n String path = String.format(\"/sections/%s\", section);\n return new ItemRequest<Section>(this, Section.class, path, \"DELETE\");\n }",
"private DefBase getDefForLevel(String level)\r\n {\r\n if (LEVEL_CLASS.equals(level))\r\n {\r\n return _curClassDef;\r\n }\r\n else if (LEVEL_FIELD.equals(level))\r\n {\r\n return _curFieldDef;\r\n }\r\n else if (LEVEL_REFERENCE.equals(level))\r\n {\r\n return _curReferenceDef;\r\n }\r\n else if (LEVEL_COLLECTION.equals(level))\r\n {\r\n return _curCollectionDef;\r\n }\r\n else if (LEVEL_OBJECT_CACHE.equals(level))\r\n {\r\n return _curObjectCacheDef;\r\n }\r\n else if (LEVEL_INDEX_DESC.equals(level))\r\n {\r\n return _curIndexDescriptorDef;\r\n }\r\n else if (LEVEL_TABLE.equals(level))\r\n {\r\n return _curTableDef;\r\n }\r\n else if (LEVEL_COLUMN.equals(level))\r\n {\r\n return _curColumnDef;\r\n }\r\n else if (LEVEL_FOREIGNKEY.equals(level))\r\n {\r\n return _curForeignkeyDef;\r\n }\r\n else if (LEVEL_INDEX.equals(level))\r\n {\r\n return _curIndexDef;\r\n }\r\n else if (LEVEL_PROCEDURE.equals(level))\r\n {\r\n return _curProcedureDef;\r\n }\r\n else if (LEVEL_PROCEDURE_ARGUMENT.equals(level))\r\n {\r\n return _curProcedureArgumentDef;\r\n }\r\n else\r\n {\r\n return null;\r\n }\r\n }",
"public <Result> Result process(IUnitOfWork<Result, State> work) {\n\t\treleaseReadLock();\n\t\tacquireWriteLock();\n\t\ttry {\n\t\t\tif (log.isTraceEnabled())\n\t\t\t\tlog.trace(\"process - \" + Thread.currentThread().getName());\n\t\t\treturn modify(work);\n\t\t} finally {\n\t\t\tif (log.isTraceEnabled())\n\t\t\t\tlog.trace(\"Downgrading from write lock to read lock...\");\n\t\t\tacquireReadLock();\n\t\t\treleaseWriteLock();\n\t\t}\n\t}",
"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 void serialize(final File folder, final String content, final String fileName) throws IOException {\n if (!folder.exists()) {\n folder.mkdirs();\n }\n\n final File output = new File(folder, fileName);\n\n try (\n final FileWriter writer = new FileWriter(output);\n ) {\n writer.write(content);\n writer.flush();\n } catch (Exception e) {\n throw new IOException(\"Failed to serialize the notification in folder \" + folder.getPath(), e);\n }\n }",
"private void readUDFTypes(FieldContainer mpxj, List<UDFAssignmentType> udfs)\n {\n for (UDFAssignmentType udf : udfs)\n {\n FieldType fieldType = m_fieldTypeMap.get(Integer.valueOf(udf.getTypeObjectId()));\n if (fieldType != null)\n {\n mpxj.set(fieldType, getUdfValue(udf));\n }\n }\n }",
"protected AbstractColumn buildSimpleColumn() {\n\t\tSimpleColumn column = new SimpleColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tcolumnProperty.getFieldProperties().putAll(fieldProperties);\n\t\tcolumn.setColumnProperty(columnProperty);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setFieldDescription(fieldDescription);\n\t\treturn column;\n\t}"
] |
Use this API to fetch all the locationfile resources that are configured on netscaler. | [
"public static locationfile get(nitro_service service) throws Exception{\n\t\tlocationfile obj = new locationfile();\n\t\tlocationfile[] response = (locationfile[])obj.get_resources(service);\n\t\treturn response[0];\n\t}"
] | [
"public <T> void setState(HttpConnectionInterceptor interceptor, String stateName, T\n stateObjectToStore) {\n Map<String, Object> state = interceptorStates.get(interceptor);\n if (state == null) {\n interceptorStates.put(interceptor, (state = new ConcurrentHashMap<String, Object>()));\n }\n state.put(stateName, stateObjectToStore);\n }",
"public int getPropertyId(@NotNull final PersistentStoreTransaction txn, @NotNull final String propertyName, final boolean allowCreate) {\n return allowCreate ? propertyIds.getOrAllocateId(txn, propertyName) : propertyIds.getId(txn, propertyName);\n }",
"public static void writeProcessorOutputToValues(\n final Object output,\n final Processor<?, ?> processor,\n final Values values) {\n Map<String, String> mapper = processor.getOutputMapperBiMap();\n if (mapper == null) {\n mapper = Collections.emptyMap();\n }\n\n final Collection<Field> fields = getAllAttributes(output.getClass());\n for (Field field: fields) {\n String name = getOutputValueName(processor.getOutputPrefix(), mapper, field);\n try {\n final Object value = field.get(output);\n if (value != null) {\n values.put(name, value);\n } else {\n values.remove(name);\n }\n } catch (IllegalAccessException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }\n }",
"@Override\n protected void reset() {\n super.reset();\n mapClassesToNamedBoundProviders.clear();\n mapClassesToUnNamedBoundProviders.clear();\n hasTestModules = false;\n installBindingForScope();\n }",
"private void removeListener(CmsUUID listenerId) {\n\n getRequest().getSession().removeAttribute(SESSION_ATTRIBUTE_LISTENER_ID);\n m_listeners.remove(listenerId);\n }",
"public BoxFileUploadSession.Info getStatus() {\n URL statusURL = this.sessionInfo.getSessionEndpoints().getStatusEndpoint();\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), statusURL, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n this.sessionInfo.update(jsonObject);\n\n return this.sessionInfo;\n }",
"private void validateAttributesToCreateANewRendererViewHolder() {\n if (viewType == null) {\n throw new NullContentException(\n \"RendererBuilder needs a view type to create a RendererViewHolder\");\n }\n if (layoutInflater == null) {\n throw new NullLayoutInflaterException(\n \"RendererBuilder needs a LayoutInflater to create a RendererViewHolder\");\n }\n if (parent == null) {\n throw new NullParentException(\n \"RendererBuilder needs a parent to create a RendererViewHolder\");\n }\n }",
"public void setTargetDirectory(String directory) {\n if (directory != null && directory.length() > 0) {\n this.targetDirectory = new File(directory);\n } else {\n this.targetDirectory = null;\n }\n }",
"private void setFieldType(FastTrackTableType tableType)\n {\n switch (tableType)\n {\n case ACTBARS:\n {\n m_type = ActBarField.getInstance(m_header.getColumnType());\n break;\n }\n case ACTIVITIES:\n {\n m_type = ActivityField.getInstance(m_header.getColumnType());\n break;\n }\n case RESOURCES:\n {\n m_type = ResourceField.getInstance(m_header.getColumnType());\n break;\n }\n }\n }"
] |
Returns the perma link for the current page based on the URI and detail content id stored in the CmsObject passed as a parameter.<p<
@param cms the CMS context to use to generate the permalink
@return the permalink | [
"public String getPermalinkForCurrentPage(CmsObject cms) {\n\n return getPermalink(cms, cms.getRequestContext().getUri(), cms.getRequestContext().getDetailContentId());\n }"
] | [
"public static base_responses flush(nitro_service client, cachecontentgroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcachecontentgroup flushresources[] = new cachecontentgroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tflushresources[i] = new cachecontentgroup();\n\t\t\t\tflushresources[i].name = resources[i].name;\n\t\t\t\tflushresources[i].query = resources[i].query;\n\t\t\t\tflushresources[i].host = resources[i].host;\n\t\t\t\tflushresources[i].selectorvalue = resources[i].selectorvalue;\n\t\t\t\tflushresources[i].force = resources[i].force;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, flushresources,\"flush\");\n\t\t}\n\t\treturn result;\n\t}",
"public static InputStream getContentStream(String stringUrl) throws MalformedURLException, IOException {\n URL url = new URL(stringUrl);\n \n URLConnection urlConnection = url.openConnection();\n \n InputStream is = urlConnection.getInputStream();\n if (\"gzip\".equals(urlConnection.getContentEncoding())) {\n is = new GZIPInputStream(is);\n }\n\n return is;\n }",
"List<File> getRecursiveThriftFiles(MavenProject project, String outputDirectory, List<File> files) throws IOException {\n HashFunction hashFun = Hashing.md5();\n File dir = new File(new File(project.getFile().getParent(), \"target\"), outputDirectory);\n if (dir.exists()) {\n URI baseDir = getFileURI(dir);\n for (File f : findThriftFilesInDirectory(dir)) {\n URI fileURI = getFileURI(f);\n String relPath = baseDir.relativize(fileURI).getPath();\n File destFolder = getResourcesOutputDirectory();\n destFolder.mkdirs();\n File destFile = new File(destFolder, relPath);\n if (!destFile.exists() || (destFile.isFile() && !Files.hash(f, hashFun).equals(Files.hash(destFile, hashFun)))) {\n getLog().info(format(\"copying %s to %s\", f.getCanonicalPath(), destFile.getCanonicalPath()));\n copyFile(f, destFile);\n }\n files.add(destFile);\n }\n }\n Map<String, MavenProject> refs = project.getProjectReferences();\n for (String name : refs.keySet()) {\n getRecursiveThriftFiles(refs.get(name), outputDirectory, files);\n }\n return files;\n }",
"public MethodKey createCopy() {\n int size = getParameterCount();\n Class[] paramTypes = new Class[size];\n for (int i = 0; i < size; i++) {\n paramTypes[i] = getParameterType(i);\n }\n return new DefaultMethodKey(sender, name, paramTypes, isCallToSuper);\n }",
"public static base_response clear(nitro_service client) throws Exception {\n\t\tnssimpleacl clearresource = new nssimpleacl();\n\t\treturn clearresource.perform_operation(client,\"clear\");\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 histogramToStructure(int histogram[] ) {\n col_idx[0] = 0;\n int index = 0;\n for (int i = 1; i <= numCols; i++) {\n col_idx[i] = index += histogram[i-1];\n }\n nz_length = index;\n growMaxLength( nz_length , false);\n if( col_idx[numCols] != nz_length )\n throw new RuntimeException(\"Egads\");\n }",
"private void reInitLayoutElements() {\n\n m_panel.clear();\n for (CmsCheckBox cb : m_checkBoxes) {\n m_panel.add(setStyle(m_onlyLabels ? new Label(cb.getText()) : cb));\n }\n }",
"public CrosstabBuilder addInvisibleMeasure(String property, String className, String title) {\r\n DJCrosstabMeasure measure = new DJCrosstabMeasure(property, className, DJCalculation.NOTHING, title);\r\n measure.setVisible(false);\r\n crosstab.getMeasures().add(measure);\r\n return this;\r\n }"
] |
Use this API to clear nsconfig. | [
"public static base_response clear(nitro_service client, nsconfig resource) throws Exception {\n\t\tnsconfig clearresource = new nsconfig();\n\t\tclearresource.force = resource.force;\n\t\tclearresource.level = resource.level;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}"
] | [
"private TypeArgSignature getTypeArgSignature(Type type) {\r\n\t\tif (type instanceof WildcardType) {\r\n\t\t\tWildcardType wildcardType = (WildcardType) type;\r\n\t\t\tType lowerBound = wildcardType.getLowerBounds().length == 0 ? null\r\n\t\t\t\t\t: wildcardType.getLowerBounds()[0];\r\n\t\t\tType upperBound = wildcardType.getUpperBounds().length == 0 ? null\r\n\t\t\t\t\t: wildcardType.getUpperBounds()[0];\r\n\r\n\t\t\tif (lowerBound == null && Object.class.equals(upperBound)) {\r\n\t\t\t\treturn new TypeArgSignature(\r\n\t\t\t\t\t\tTypeArgSignature.UNBOUNDED_WILDCARD,\r\n\t\t\t\t\t\t(FieldTypeSignature) getFullTypeSignature(upperBound));\r\n\t\t\t} else if (lowerBound == null && upperBound != null) {\r\n\t\t\t\treturn new TypeArgSignature(\r\n\t\t\t\t\t\tTypeArgSignature.UPPERBOUND_WILDCARD,\r\n\t\t\t\t\t\t(FieldTypeSignature) getFullTypeSignature(upperBound));\r\n\t\t\t} else if (lowerBound != null) {\r\n\t\t\t\treturn new TypeArgSignature(\r\n\t\t\t\t\t\tTypeArgSignature.LOWERBOUND_WILDCARD,\r\n\t\t\t\t\t\t(FieldTypeSignature) getFullTypeSignature(lowerBound));\r\n\t\t\t} else {\r\n\t\t\t\tthrow new RuntimeException(\"Invalid type\");\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\treturn new TypeArgSignature(TypeArgSignature.NO_WILDCARD,\r\n\t\t\t\t\t(FieldTypeSignature) getFullTypeSignature(type));\r\n\t\t}\r\n\t}",
"private void writeNewLineIndent() throws IOException\n {\n if (m_pretty)\n {\n if (!m_indent.isEmpty())\n {\n m_writer.write('\\n');\n m_writer.write(m_indent);\n }\n }\n }",
"private static ModelNode createOperation(ServerIdentity identity) {\n // The server address\n final ModelNode address = new ModelNode();\n address.add(ModelDescriptionConstants.HOST, identity.getHostName());\n address.add(ModelDescriptionConstants.RUNNING_SERVER, identity.getServerName());\n //\n final ModelNode operation = OPERATION.clone();\n operation.get(ModelDescriptionConstants.OP_ADDR).set(address);\n return operation;\n }",
"public String getString(String fieldName) {\n\t\treturn hasValue(fieldName) ? String.valueOf(resultMap.get(fieldName)) : null;\n\t}",
"public static CRFClassifier getClassifier(InputStream in) throws IOException, ClassCastException,\r\n ClassNotFoundException {\r\n CRFClassifier crf = new CRFClassifier();\r\n crf.loadClassifier(in);\r\n return crf;\r\n }",
"private static XMLStreamException unexpectedElement(final XMLStreamReader reader) {\n return SecurityManagerLogger.ROOT_LOGGER.unexpectedElement(reader.getName(), reader.getLocation());\n }",
"public static Attachment fromBinaryInputStream( InputStream inputStream, MediaType mediaType ) throws IOException {\n return fromBinaryBytes( ByteStreams.toByteArray( inputStream ), mediaType );\n }",
"public <Result, Param extends Resource> Result execWithoutCacheClear(Param resource, IUnitOfWork<Result, Param> transaction) throws WrappedException {\n\t\tCacheAdapter cacheAdapter = getOrCreate(resource);\n\t\ttry {\n\t\t\tcacheAdapter.ignoreNotifications();\n\t\t\treturn transaction.exec(resource);\n\t\t} catch (RuntimeException e) {\n\t\t\tthrow e;\n\t\t} catch (Exception e) {\n\t\t\tthrow new WrappedException(e);\n\t\t} finally {\n\t\t\tcacheAdapter.listenToNotifications();\n\t\t}\n\t}",
"public List<Set<String>> makeNWiseTuples(String[] variables, int nWise) {\r\n List<Set<String>> completeTuples = new ArrayList<>();\r\n makeNWiseTuplesHelper(completeTuples, variables, 0, new HashSet<String>(), nWise);\n\r\n return completeTuples;\r\n }"
] |
This is private because the execute is the only method that should be called here. | [
"private static <T, ID> MappedDeleteCollection<T, ID> build(Dao<T, ID> dao, TableInfo<T, ID> tableInfo, int dataSize)\n\t\t\tthrows SQLException {\n\t\tFieldType idField = tableInfo.getIdField();\n\t\tif (idField == null) {\n\t\t\tthrow new SQLException(\n\t\t\t\t\t\"Cannot delete \" + tableInfo.getDataClass() + \" because it doesn't have an id field defined\");\n\t\t}\n\t\tStringBuilder sb = new StringBuilder(128);\n\t\tDatabaseType databaseType = dao.getConnectionSource().getDatabaseType();\n\t\tappendTableName(databaseType, sb, \"DELETE FROM \", tableInfo.getTableName());\n\t\tFieldType[] argFieldTypes = new FieldType[dataSize];\n\t\tappendWhereIds(databaseType, idField, sb, dataSize, argFieldTypes);\n\t\treturn new MappedDeleteCollection<T, ID>(dao, tableInfo, sb.toString(), argFieldTypes);\n\t}"
] | [
"public int getOpacity() {\n\t\tint opacity = Math\n\t\t\t\t.round((mPosToOpacFactor * (mBarPointerPosition - mBarPointerHaloRadius)));\n\t\tif (opacity < 5) {\n\t\t\treturn 0x00;\n\t\t} else if (opacity > 250) {\n\t\t\treturn 0xFF;\n\t\t} else {\n\t\t\treturn opacity;\n\t\t}\n\t}",
"public static base_responses update(nitro_service client, gslbservice resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbservice updateresources[] = new gslbservice[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new gslbservice();\n\t\t\t\tupdateresources[i].servicename = resources[i].servicename;\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].publicip = resources[i].publicip;\n\t\t\t\tupdateresources[i].publicport = resources[i].publicport;\n\t\t\t\tupdateresources[i].cip = resources[i].cip;\n\t\t\t\tupdateresources[i].cipheader = resources[i].cipheader;\n\t\t\t\tupdateresources[i].sitepersistence = resources[i].sitepersistence;\n\t\t\t\tupdateresources[i].siteprefix = resources[i].siteprefix;\n\t\t\t\tupdateresources[i].maxclient = resources[i].maxclient;\n\t\t\t\tupdateresources[i].healthmonitor = resources[i].healthmonitor;\n\t\t\t\tupdateresources[i].maxbandwidth = resources[i].maxbandwidth;\n\t\t\t\tupdateresources[i].downstateflush = resources[i].downstateflush;\n\t\t\t\tupdateresources[i].maxaaausers = resources[i].maxaaausers;\n\t\t\t\tupdateresources[i].viewname = resources[i].viewname;\n\t\t\t\tupdateresources[i].viewip = resources[i].viewip;\n\t\t\t\tupdateresources[i].monthreshold = resources[i].monthreshold;\n\t\t\t\tupdateresources[i].weight = resources[i].weight;\n\t\t\t\tupdateresources[i].monitor_name_svc = resources[i].monitor_name_svc;\n\t\t\t\tupdateresources[i].hashid = resources[i].hashid;\n\t\t\t\tupdateresources[i].comment = resources[i].comment;\n\t\t\t\tupdateresources[i].appflowlog = resources[i].appflowlog;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"private Proctor getProctorNotNull() {\n final Proctor proctor = proctorLoader.get();\n if (proctor == null) {\n throw new IllegalStateException(\"Proctor specification and/or text matrix has not been loaded\");\n }\n return proctor;\n }",
"private void verityLicenseIsConflictFree(final DbLicense newComer) {\n if(newComer.getRegexp() == null || newComer.getRegexp().isEmpty()) {\n return;\n }\n\n final DbLicense existing = repoHandler.getLicense(newComer.getName());\n final List<DbLicense> licenses = repoHandler.getAllLicenses();\n\n if(null == existing) {\n licenses.add(newComer);\n } else {\n existing.setRegexp(newComer.getRegexp());\n }\n\n\n final Optional<Report> reportOp = ReportsRegistry.findById(MULTIPLE_LICENSE_MATCHING_STRINGS);\n if (reportOp.isPresent()) {\n final Report reportDef = reportOp.get();\n ReportRequest reportRequest = new ReportRequest();\n reportRequest.setReportId(reportDef.getId());\n\n Map<String, String> params = new HashMap<>();\n\n //\n // TODO: Make the organization come as an external parameter from the client side.\n // This may have impact on the UI, as when the user will update a license he will\n // have to specify which organization he's editing the license for (in case there\n // are more organizations defined in the collection).\n //\n params.put(\"organization\", \"Axway\");\n reportRequest.setParamValues(params);\n\n final RepositoryHandler wrapped = wrapperBuilder\n .start(repoHandler)\n .replaceGetMethod(\"getAllLicenses\", licenses)\n .build();\n\n final ReportExecution execution = reportDef.execute(wrapped, reportRequest);\n\n List<String[]> data = execution.getData();\n\n final Optional<String[]> first = data\n .stream()\n .filter(strings -> strings[2].contains(newComer.getName()))\n .findFirst();\n\n if(first.isPresent()) {\n final String[] strings = first.get();\n final String message = String.format(\n \"Pattern conflict for string entry %s matching multiple licenses: %s\",\n strings[1], strings[2]);\n LOG.info(message);\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(message)\n .build());\n } else {\n if(!data.isEmpty() && !data.get(0)[2].isEmpty()) {\n LOG.info(\"There are remote conflicts between existing licenses and artifact strings\");\n }\n }\n } else {\n if(LOG.isWarnEnabled()) {\n LOG.warn(String.format(\"Cannot find report by id %s\", MULTIPLE_LICENSE_MATCHING_STRINGS));\n }\n }\n }",
"public void deleteById(Object id) {\n\n int count = beginDelete().whereEquals(idColumn.getColumnName(), id).delete();\n\n if (count == 0) {\n throw new RowNotFoundException(table, id);\n }\n }",
"public static CmsPair<String, Map<String, String>> parseEmbeddedGalleryOptions(String configuration) {\n\n final Map<String, String> galleryOptions = Maps.newHashMap();\n String resultConfig = CmsStringUtil.substitute(\n PATTERN_EMBEDDED_GALLERY_CONFIG,\n configuration,\n new I_CmsRegexSubstitution() {\n\n public String substituteMatch(String string, Matcher matcher) {\n\n String galleryName = string.substring(matcher.start(1), matcher.end(1));\n String embeddedConfig = string.substring(matcher.start(2), matcher.end(2));\n galleryOptions.put(galleryName, embeddedConfig);\n return galleryName;\n }\n });\n return CmsPair.create(resultConfig, galleryOptions);\n }",
"private ProctorContext getProctorContext(final HttpServletRequest request) throws IllegalAccessException, InstantiationException {\n final ProctorContext proctorContext = contextClass.newInstance();\n final BeanWrapper beanWrapper = new BeanWrapperImpl(proctorContext);\n for (final PropertyDescriptor descriptor : beanWrapper.getPropertyDescriptors()) {\n final String propertyName = descriptor.getName();\n if (!\"class\".equals(propertyName)) { // ignore class property which every object has\n final String parameterValue = request.getParameter(propertyName);\n if (parameterValue != null) {\n beanWrapper.setPropertyValue(propertyName, parameterValue);\n }\n }\n }\n return proctorContext;\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 ParallelTaskBuilder preparePing() {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.PING);\n return cb;\n }"
] |
Process a single criteria block.
@param list parent criteria list
@param block current block | [
"private void processBlock(List<GenericCriteria> list, byte[] block)\n {\n if (block != null)\n {\n if (MPPUtility.getShort(block, 0) > 0x3E6)\n {\n addCriteria(list, block);\n }\n else\n {\n switch (block[0])\n {\n case (byte) 0x0B:\n {\n processBlock(list, getChildBlock(block));\n break;\n }\n\n case (byte) 0x06:\n {\n processBlock(list, getListNextBlock(block));\n break;\n }\n\n case (byte) 0xED: // EQUALS\n {\n addCriteria(list, block);\n break;\n }\n\n case (byte) 0x19: // AND\n case (byte) 0x1B:\n {\n addBlock(list, block, TestOperator.AND);\n break;\n }\n\n case (byte) 0x1A: // OR\n case (byte) 0x1C:\n {\n addBlock(list, block, TestOperator.OR);\n break;\n }\n }\n }\n }\n }"
] | [
"public void sendJsonToTagged(Object data, String ... labels) {\n for (String label : labels) {\n sendJsonToTagged(data, label);\n }\n }",
"public double compute( DMatrix1Row mat ) {\n if( width != mat.numCols || width != mat.numRows ) {\n throw new RuntimeException(\"Unexpected matrix dimension\");\n }\n\n // make sure everything is in the proper state before it starts\n initStructures();\n\n// System.arraycopy(mat.data,0,minorMatrix[0],0,mat.data.length);\n\n int level = 0;\n while( true ) {\n int levelWidth = width-level;\n int levelIndex = levelIndexes[level];\n\n if( levelIndex == levelWidth ) {\n if( level == 0 ) {\n return levelResults[0];\n }\n int prevLevelIndex = levelIndexes[level-1]++;\n\n double val = mat.get((level-1)*width+levelRemoved[level-1]);\n if( prevLevelIndex % 2 == 0 ) {\n levelResults[level-1] += val * levelResults[level];\n } else {\n levelResults[level-1] -= val * levelResults[level];\n }\n\n putIntoOpen(level-1);\n\n levelResults[level] = 0;\n levelIndexes[level] = 0;\n level--;\n } else {\n int excluded = openRemove( levelIndex );\n\n levelRemoved[level] = excluded;\n\n if( levelWidth == minWidth ) {\n createMinor(mat);\n double subresult = mat.get(level*width+levelRemoved[level]);\n\n subresult *= UnrolledDeterminantFromMinor_DDRM.det(tempMat);\n\n if( levelIndex % 2 == 0 ) {\n levelResults[level] += subresult;\n } else {\n levelResults[level] -= subresult;\n }\n\n // put it back into the list\n putIntoOpen(level);\n levelIndexes[level]++;\n } else {\n level++;\n }\n }\n }\n }",
"@Override\n public boolean isCompleteRequest(ByteBuffer buffer) {\n DataInputStream inputStream = new DataInputStream(new ByteBufferBackedInputStream(buffer));\n\n try {\n int dataSize = inputStream.readInt();\n\n if(logger.isTraceEnabled())\n logger.trace(\"In isCompleteRequest, dataSize: \" + dataSize + \", buffer position: \"\n + buffer.position());\n\n if(dataSize == -1)\n return true;\n\n // Here we skip over the data (without reading it in) and\n // move our position to just past it.\n buffer.position(buffer.position() + dataSize);\n\n return true;\n } catch(Exception e) {\n // This could also occur if the various methods we call into\n // re-throw a corrupted value error as some other type of exception.\n // For example, updating the position on a buffer past its limit\n // throws an InvalidArgumentException.\n if(logger.isTraceEnabled())\n logger.trace(\"In isCompleteRequest, probable partial read occurred: \" + e);\n\n return false;\n }\n }",
"public ParallelTaskBuilder prepareHttpPut(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.PUT);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n\n }",
"public static <T> T splitEachLine(InputStream stream, String regex, String charset, @ClosureParams(value=FromString.class,options=\"List<String>\") Closure<T> closure) throws IOException {\n return splitEachLine(new BufferedReader(new InputStreamReader(stream, charset)), regex, closure);\n }",
"private void writeActivity(Task mpxj)\n {\n ActivityType xml = m_factory.createActivityType();\n m_project.getActivity().add(xml);\n\n Task parentTask = mpxj.getParentTask();\n Integer parentObjectID = parentTask == null ? null : parentTask.getUniqueID();\n\n xml.setActualStartDate(mpxj.getActualStart());\n xml.setActualFinishDate(mpxj.getActualFinish());\n xml.setAtCompletionDuration(getDuration(mpxj.getDuration()));\n xml.setCalendarObjectId(getCalendarUniqueID(mpxj.getCalendar()));\n xml.setDurationPercentComplete(getPercentage(mpxj.getPercentageComplete()));\n xml.setDurationType(DURATION_TYPE_MAP.get(mpxj.getType()));\n xml.setFinishDate(mpxj.getFinish());\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setId(getActivityID(mpxj));\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setPercentComplete(getPercentage(mpxj.getPercentageComplete()));\n xml.setPercentCompleteType(\"Duration\");\n xml.setPrimaryConstraintType(CONSTRAINT_TYPE_MAP.get(mpxj.getConstraintType()));\n xml.setPrimaryConstraintDate(mpxj.getConstraintDate());\n xml.setPlannedDuration(getDuration(mpxj.getDuration()));\n xml.setPlannedFinishDate(mpxj.getFinish());\n xml.setPlannedStartDate(mpxj.getStart());\n xml.setProjectObjectId(PROJECT_OBJECT_ID);\n xml.setRemainingDuration(getDuration(mpxj.getRemainingDuration()));\n xml.setRemainingEarlyFinishDate(mpxj.getEarlyFinish());\n xml.setRemainingEarlyStartDate(mpxj.getResume());\n xml.setRemainingLaborCost(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingLaborUnits(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingNonLaborCost(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingNonLaborUnits(NumberHelper.DOUBLE_ZERO);\n xml.setStartDate(mpxj.getStart());\n xml.setStatus(getActivityStatus(mpxj));\n xml.setType(extractAndConvertTaskType(mpxj));\n xml.setWBSObjectId(parentObjectID);\n xml.getUDF().addAll(writeUDFType(FieldTypeClass.TASK, mpxj));\n\n writePredecessors(mpxj);\n }",
"public T addModule(final String moduleName, final String slot, final byte[] newHash) {\n final ContentItem item = createModuleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.ADD, NO_CONTENT));\n return returnThis();\n }",
"public static base_responses save(nitro_service client, cachecontentgroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcachecontentgroup saveresources[] = new cachecontentgroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tsaveresources[i] = new cachecontentgroup();\n\t\t\t\tsaveresources[i].name = resources[i].name;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, saveresources,\"save\");\n\t\t}\n\t\treturn result;\n\t}",
"private PBKey buildDefaultKey()\r\n {\r\n List descriptors = connectionRepository().getAllDescriptor();\r\n JdbcConnectionDescriptor descriptor;\r\n PBKey result = null;\r\n for (Iterator iterator = descriptors.iterator(); iterator.hasNext();)\r\n {\r\n descriptor = (JdbcConnectionDescriptor) iterator.next();\r\n if (descriptor.isDefaultConnection())\r\n {\r\n if(result != null)\r\n {\r\n log.error(\"Found additional connection descriptor with enabled 'default-connection' \"\r\n + descriptor.getPBKey() + \". This is NOT allowed. Will use the first found descriptor \" + result\r\n + \" as default connection\");\r\n }\r\n else\r\n {\r\n result = descriptor.getPBKey();\r\n }\r\n }\r\n }\r\n\r\n if(result == null)\r\n {\r\n log.info(\"No 'default-connection' attribute set in jdbc-connection-descriptors,\" +\r\n \" thus it's currently not possible to use 'defaultPersistenceBroker()' \" +\r\n \" convenience method to lookup PersistenceBroker instances. But it's possible\"+\r\n \" to enable this at runtime using 'setDefaultKey' method.\");\r\n }\r\n return result;\r\n }"
] |
Print a constraint type.
@param value ConstraintType instance
@return constraint type value | [
"public static final BigInteger printConstraintType(ConstraintType value)\n {\n return (value == null ? null : BigInteger.valueOf(value.getValue()));\n }"
] | [
"private void readRecord(byte[] buffer, Table table)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, true, 16, \"\"));\n int deletedFlag = getShort(buffer, 0);\n if (deletedFlag != 0)\n {\n Map<String, Object> row = new HashMap<String, Object>();\n for (ColumnDefinition column : m_definition.getColumns())\n {\n Object value = column.read(0, buffer);\n //System.out.println(column.getName() + \": \" + value);\n row.put(column.getName(), value);\n }\n\n table.addRow(m_definition.getPrimaryKeyColumnName(), row);\n }\n }",
"public boolean hasForeignkey(String name)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n ForeignkeyDef def = null;\r\n\r\n for (Iterator it = getForeignkeys(); it.hasNext();)\r\n {\r\n def = (ForeignkeyDef)it.next();\r\n if (realName.equals(def.getName()))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"public SelectStatement getPreparedSelectByPkStatement(ClassDescriptor cld)\r\n {\r\n SelectStatement sql;\r\n SqlForClass sfc = getSqlForClass(cld);\r\n sql = sfc.getSelectByPKSql();\r\n if(sql == null)\r\n {\r\n sql = new SqlSelectByPkStatement(m_platform, cld, logger);\r\n\r\n // set the sql string\r\n sfc.setSelectByPKSql(sql);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n }\r\n return sql;\r\n }",
"public void populateFromAttributes(\n @Nonnull final Template template,\n @Nonnull final Map<String, Attribute> attributes,\n @Nonnull final PObject requestJsonAttributes) {\n if (requestJsonAttributes.has(JSON_REQUEST_HEADERS) &&\n requestJsonAttributes.getObject(JSON_REQUEST_HEADERS).has(JSON_REQUEST_HEADERS) &&\n !attributes.containsKey(JSON_REQUEST_HEADERS)) {\n attributes.put(JSON_REQUEST_HEADERS, new HttpRequestHeadersAttribute());\n }\n for (Map.Entry<String, Attribute> attribute: attributes.entrySet()) {\n try {\n put(attribute.getKey(),\n attribute.getValue().getValue(template, attribute.getKey(), requestJsonAttributes));\n } catch (ObjectMissingException | IllegalArgumentException e) {\n throw e;\n } catch (Throwable e) {\n String templateName = \"unknown\";\n for (Map.Entry<String, Template> entry: template.getConfiguration().getTemplates()\n .entrySet()) {\n if (entry.getValue() == template) {\n templateName = entry.getKey();\n break;\n }\n }\n\n String defaults = \"\";\n\n if (attribute instanceof ReflectiveAttribute<?>) {\n ReflectiveAttribute<?> reflectiveAttribute = (ReflectiveAttribute<?>) attribute;\n defaults = \"\\n\\n The attribute defaults are: \" + reflectiveAttribute.getDefaultValue();\n }\n\n String errorMsg = \"An error occurred when creating a value from the '\" + attribute.getKey() +\n \"' attribute for the '\" +\n templateName + \"' template.\\n\\nThe JSON is: \\n\" + requestJsonAttributes + defaults +\n \"\\n\" +\n e.toString();\n\n throw new AttributeParsingException(errorMsg, e);\n }\n }\n\n if (template.getConfiguration().isThrowErrorOnExtraParameters()) {\n final List<String> extraProperties = new ArrayList<>();\n for (Iterator<String> it = requestJsonAttributes.keys(); it.hasNext(); ) {\n final String attributeName = it.next();\n if (!attributes.containsKey(attributeName)) {\n extraProperties.add(attributeName);\n }\n }\n\n if (!extraProperties.isEmpty()) {\n throw new ExtraPropertyException(\"Extra properties found in the request attributes\",\n extraProperties, attributes.keySet());\n }\n }\n }",
"private ModelNode createJVMNode() throws OperationFailedException {\n ModelNode jvm = new ModelNode().setEmptyObject();\n jvm.get(NAME).set(getProperty(\"java.vm.name\"));\n jvm.get(JAVA_VERSION).set(getProperty(\"java.vm.specification.version\"));\n jvm.get(JVM_VERSION).set(getProperty(\"java.version\"));\n jvm.get(JVM_VENDOR).set(getProperty(\"java.vm.vendor\"));\n jvm.get(JVM_HOME).set(getProperty(\"java.home\"));\n return jvm;\n }",
"public void logException(Level level) {\n if (!LOG.isLoggable(level)) {\n return;\n }\n final StringBuilder builder = new StringBuilder();\n builder.append(\"\\n----------------------------------------------------\");\n builder.append(\"\\nMonitoringException\");\n builder.append(\"\\n----------------------------------------------------\");\n builder.append(\"\\nCode: \").append(code);\n builder.append(\"\\nMessage: \").append(message);\n builder.append(\"\\n----------------------------------------------------\");\n if (events != null) {\n for (Event event : events) {\n builder.append(\"\\nEvent:\");\n if (event.getMessageInfo() != null) {\n builder.append(\"\\nMessage id: \").append(event.getMessageInfo().getMessageId());\n builder.append(\"\\nFlow id: \").append(event.getMessageInfo().getFlowId());\n builder.append(\"\\n----------------------------------------------------\");\n } else {\n builder.append(\"\\nNo message id and no flow id\");\n }\n }\n }\n builder.append(\"\\n----------------------------------------------------\\n\");\n LOG.log(level, builder.toString(), this);\n }",
"private boolean hidden(ProgramElementDoc c) {\n\tif (c.tags(\"hidden\").length > 0 || c.tags(\"view\").length > 0)\n\t return true;\n\tOptions opt = optionProvider.getOptionsFor(c instanceof ClassDoc ? (ClassDoc) c : c.containingClass());\n\treturn opt.matchesHideExpression(c.toString()) //\n\t\t|| (opt.hidePrivateInner && c instanceof ClassDoc && c.isPrivate() && ((ClassDoc) c).containingClass() != null);\n }",
"private String getPathSelectString() {\n String queryString = \"SELECT \" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.GENERIC_CLIENT_UUID +\n \",\" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID +\n \",\" + Constants.PATH_PROFILE_PATHNAME +\n \",\" + Constants.PATH_PROFILE_ACTUAL_PATH +\n \",\" + Constants.PATH_PROFILE_BODY_FILTER +\n \",\" + Constants.PATH_PROFILE_GROUP_IDS +\n \",\" + Constants.DB_TABLE_PATH + \".\" + Constants.PATH_PROFILE_PROFILE_ID +\n \",\" + Constants.PATH_PROFILE_PATH_ORDER +\n \",\" + Constants.REQUEST_RESPONSE_REPEAT_NUMBER +\n \",\" + Constants.REQUEST_RESPONSE_REQUEST_ENABLED +\n \",\" + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED +\n \",\" + Constants.PATH_PROFILE_CONTENT_TYPE +\n \",\" + Constants.PATH_PROFILE_REQUEST_TYPE +\n \",\" + Constants.PATH_PROFILE_GLOBAL +\n \" FROM \" + Constants.DB_TABLE_PATH +\n \" JOIN \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \" ON \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID +\n \"=\" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.REQUEST_RESPONSE_PATH_ID +\n \" AND \" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.GENERIC_CLIENT_UUID + \" = ?\";\n\n return queryString;\n }",
"public Collection<Size> getSizes(String photoId, boolean sign) throws FlickrException {\r\n SizeList<Size> sizes = new SizeList<Size>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_SIZES);\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 sizesElement = response.getPayload();\r\n sizes.setIsCanBlog(\"1\".equals(sizesElement.getAttribute(\"canblog\")));\r\n sizes.setIsCanDownload(\"1\".equals(sizesElement.getAttribute(\"candownload\")));\r\n sizes.setIsCanPrint(\"1\".equals(sizesElement.getAttribute(\"canprint\")));\r\n NodeList sizeNodes = sizesElement.getElementsByTagName(\"size\");\r\n for (int i = 0; i < sizeNodes.getLength(); i++) {\r\n Element sizeElement = (Element) sizeNodes.item(i);\r\n Size size = new Size();\r\n size.setLabel(sizeElement.getAttribute(\"label\"));\r\n size.setWidth(sizeElement.getAttribute(\"width\"));\r\n size.setHeight(sizeElement.getAttribute(\"height\"));\r\n size.setSource(sizeElement.getAttribute(\"source\"));\r\n size.setUrl(sizeElement.getAttribute(\"url\"));\r\n size.setMedia(sizeElement.getAttribute(\"media\"));\r\n sizes.add(size);\r\n }\r\n return sizes;\r\n }"
] |
Print the visibility adornment of element e prefixed by
any stereotypes | [
"private String visibility(Options opt, ProgramElementDoc e) {\n\treturn opt.showVisibility ? Visibility.get(e).symbol : \" \";\n }"
] | [
"private void writeAvailability(Project.Resources.Resource xml, Resource mpx)\n {\n AvailabilityPeriods periods = m_factory.createProjectResourcesResourceAvailabilityPeriods();\n xml.setAvailabilityPeriods(periods);\n List<AvailabilityPeriod> list = periods.getAvailabilityPeriod();\n for (Availability availability : mpx.getAvailability())\n {\n AvailabilityPeriod period = m_factory.createProjectResourcesResourceAvailabilityPeriodsAvailabilityPeriod();\n list.add(period);\n DateRange range = availability.getRange();\n\n period.setAvailableFrom(range.getStart());\n period.setAvailableTo(range.getEnd());\n period.setAvailableUnits(DatatypeConverter.printUnits(availability.getUnits()));\n }\n }",
"@Override\n public boolean isCompleteRequest(ByteBuffer buffer) {\n DataInputStream inputStream = new DataInputStream(new ByteBufferBackedInputStream(buffer));\n\n try {\n int dataSize = inputStream.readInt();\n\n if(logger.isTraceEnabled())\n logger.trace(\"In isCompleteRequest, dataSize: \" + dataSize + \", buffer position: \"\n + buffer.position());\n\n if(dataSize == -1)\n return true;\n\n // Here we skip over the data (without reading it in) and\n // move our position to just past it.\n buffer.position(buffer.position() + dataSize);\n\n return true;\n } catch(Exception e) {\n // This could also occur if the various methods we call into\n // re-throw a corrupted value error as some other type of exception.\n // For example, updating the position on a buffer past its limit\n // throws an InvalidArgumentException.\n if(logger.isTraceEnabled())\n logger.trace(\"In isCompleteRequest, probable partial read occurred: \" + e);\n\n return false;\n }\n }",
"public static int Median( int[] values ){\n int total = 0, n = values.length;\n\n // for all values\n for ( int i = 0; i < n; i++ )\n {\n // accumalate total\n total += values[i];\n }\n\n int halfTotal = total / 2;\n int median = 0, v = 0;\n\n // find median value\n for ( ; median < n; median++ )\n {\n v += values[median];\n if ( v >= halfTotal )\n break;\n }\n\n return median;\n }",
"public Iterable<RowKey> getKeys() {\n\t\tif ( currentState.isEmpty() ) {\n\t\t\tif ( cleared ) {\n\t\t\t\t// if the association has been cleared and the currentState is empty, we consider that there are no rows.\n\t\t\t\treturn Collections.emptyList();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// otherwise, the snapshot rows are the current ones\n\t\t\t\treturn snapshot.getRowKeys();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// It may be a bit too large in case of removals, but that's fine for now\n\t\t\tSet<RowKey> keys = CollectionHelper.newLinkedHashSet( cleared ? currentState.size() : snapshot.size() + currentState.size() );\n\n\t\t\tif ( !cleared ) {\n\t\t\t\t// we add the snapshot RowKeys only if the association has not been cleared\n\t\t\t\tfor ( RowKey rowKey : snapshot.getRowKeys() ) {\n\t\t\t\t\tkeys.add( rowKey );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor ( Map.Entry<RowKey,AssociationOperation> op : currentState.entrySet() ) {\n\t\t\t\tswitch ( op.getValue().getType() ) {\n\t\t\t\t\tcase PUT:\n\t\t\t\t\t\tkeys.add( op.getKey() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase REMOVE:\n\t\t\t\t\t\tkeys.remove( op.getKey() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn keys;\n\t\t}\n\t}",
"protected <T extends Listener> Collection<T> copyList(Class<T> listenerClass,\n Stream<Object> listeners, int sizeHint) {\n if (sizeHint == 0) {\n return Collections.emptyList();\n }\n return listeners\n .map(listenerClass::cast)\n .collect(Collectors.toCollection(() -> new ArrayList<>(sizeHint)));\n }",
"public static ModelNode getOperationAddress(final ModelNode op) {\n return op.hasDefined(OP_ADDR) ? op.get(OP_ADDR) : new ModelNode();\n }",
"public boolean mapsCell(String cell) {\n return mappers.values().stream().anyMatch(mapper -> mapper.mapsCell(cell));\n }",
"protected void registerUnregisterJMX(boolean doRegister) {\r\n\t\tif (this.mbs == null ){ // this way makes it easier for mocking.\r\n\t\t\tthis.mbs = ManagementFactory.getPlatformMBeanServer();\r\n\t\t}\r\n\t\ttry {\r\n\t\t\tString suffix = \"\";\r\n\r\n\t\t\tif (this.config.getPoolName()!=null){\r\n\t\t\t\tsuffix=\"-\"+this.config.getPoolName();\r\n\t\t\t}\r\n\r\n\t\t\tObjectName name = new ObjectName(MBEAN_BONECP +suffix);\r\n\t\t\tObjectName configname = new ObjectName(MBEAN_CONFIG + suffix);\r\n\r\n\r\n\t\t\tif (doRegister){\r\n\t\t\t\tif (!this.mbs.isRegistered(name)){\r\n\t\t\t\t\tthis.mbs.registerMBean(this.statistics, name);\r\n\t\t\t\t}\r\n\t\t\t\tif (!this.mbs.isRegistered(configname)){\r\n\t\t\t\t\tthis.mbs.registerMBean(this.config, configname);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tif (this.mbs.isRegistered(name)){\r\n\t\t\t\t\tthis.mbs.unregisterMBean(name);\r\n\t\t\t\t}\r\n\t\t\t\tif (this.mbs.isRegistered(configname)){\r\n\t\t\t\t\tthis.mbs.unregisterMBean(configname);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tlogger.error(\"Unable to start/stop JMX\", e);\r\n\t\t}\r\n\t}",
"public boolean runOnMainThreadNext(Runnable r) {\n assert handler != null;\n\n if (!sanityCheck(\"runOnMainThreadNext \" + r)) {\n return false;\n }\n return handler.post(r);\n }"
] |
updates the values for locking fields , BRJ
handles int, long, Timestamp
respects updateLock so locking field are only updated when updateLock is true
@throws PersistenceBrokerException if there is an erros accessing obj field values | [
"public void updateLockingValues(Object obj) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] fields = getLockingFields();\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fmd = fields[i];\r\n if (fmd.isUpdateLock())\r\n {\r\n PersistentField f = fmd.getPersistentField();\r\n Object cv = f.get(obj);\r\n // int\r\n if ((f.getType() == int.class) || (f.getType() == Integer.class))\r\n {\r\n int newCv = 0;\r\n if (cv != null)\r\n {\r\n newCv = ((Number) cv).intValue();\r\n }\r\n newCv++;\r\n f.set(obj, new Integer(newCv));\r\n }\r\n // long\r\n else if ((f.getType() == long.class) || (f.getType() == Long.class))\r\n {\r\n long newCv = 0;\r\n if (cv != null)\r\n {\r\n newCv = ((Number) cv).longValue();\r\n }\r\n newCv++;\r\n f.set(obj, new Long(newCv));\r\n }\r\n // Timestamp\r\n else if (f.getType() == Timestamp.class)\r\n {\r\n long newCv = System.currentTimeMillis();\r\n f.set(obj, new Timestamp(newCv));\r\n }\r\n }\r\n }\r\n }"
] | [
"private String hibcProcess(String source) {\n\n // HIBC 2.6 allows up to 110 characters, not including the \"+\" prefix or the check digit\n if (source.length() > 110) {\n throw new OkapiException(\"Data too long for HIBC LIC\");\n }\n\n source = source.toUpperCase();\n if (!source.matches(\"[A-Z0-9-\\\\. \\\\$/+\\\\%]+?\")) {\n throw new OkapiException(\"Invalid characters in input\");\n }\n\n int counter = 41;\n for (int i = 0; i < source.length(); i++) {\n counter += positionOf(source.charAt(i), HIBC_CHAR_TABLE);\n }\n counter = counter % 43;\n\n char checkDigit = HIBC_CHAR_TABLE[counter];\n\n encodeInfo += \"HIBC Check Digit Counter: \" + counter + \"\\n\";\n encodeInfo += \"HIBC Check Digit: \" + checkDigit + \"\\n\";\n\n return \"+\" + source + checkDigit;\n }",
"public static Broker createBroker(int id, String brokerInfoString) {\n String[] brokerInfo = brokerInfoString.split(\":\");\n String creator = brokerInfo[0].replace('#', ':');\n String hostname = brokerInfo[1].replace('#', ':');\n String port = brokerInfo[2];\n boolean autocreated = Boolean.valueOf(brokerInfo.length > 3 ? brokerInfo[3] : \"true\");\n return new Broker(id, creator, hostname, Integer.parseInt(port), autocreated);\n }",
"protected void appendWhereClause(FieldDescriptor[] fields, StringBuffer stmt) throws PersistenceBrokerException\r\n {\r\n stmt.append(\" WHERE \");\r\n\r\n for(int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fmd = fields[i];\r\n\r\n stmt.append(fmd.getColumnName());\r\n stmt.append(\" = ? \");\r\n if(i < fields.length - 1)\r\n {\r\n stmt.append(\" AND \");\r\n }\r\n }\r\n }",
"public final void setVolumeByIncrement(float level) throws IOException {\n Volume volume = this.getStatus().volume;\n float total = volume.level;\n\n if (volume.increment <= 0f) {\n throw new ChromeCastException(\"Volume.increment is <= 0\");\n }\n\n // With floating points we always have minor decimal variations, using the Math.min/max\n // works around this issue\n // Increase volume\n if (level > total) {\n while (total < level) {\n total = Math.min(total + volume.increment, level);\n setVolume(total);\n }\n // Decrease Volume\n } else if (level < total) {\n while (total > level) {\n total = Math.max(total - volume.increment, level);\n setVolume(total);\n }\n }\n }",
"protected static PatchElement createRollbackElement(final PatchEntry entry) {\n final PatchElement patchElement = entry.element;\n final String patchId;\n final Patch.PatchType patchType = patchElement.getProvider().getPatchType();\n if (patchType == Patch.PatchType.CUMULATIVE) {\n patchId = entry.getCumulativePatchID();\n } else {\n patchId = patchElement.getId();\n }\n return createPatchElement(entry, patchId, entry.rollbackActions);\n }",
"public String format(String value) {\n StringBuilder s = new StringBuilder();\n\n if (value != null && value.trim().length() > 0) {\n boolean continuationLine = false;\n\n s.append(getName()).append(\":\");\n if (isFirstLineEmpty()) {\n s.append(\"\\n\");\n continuationLine = true;\n }\n\n try {\n BufferedReader reader = new BufferedReader(new StringReader(value));\n String line;\n while ((line = reader.readLine()) != null) {\n if (continuationLine && line.trim().length() == 0) {\n // put a dot on the empty continuation lines\n s.append(\" .\\n\");\n } else {\n s.append(\" \").append(line).append(\"\\n\");\n }\n\n continuationLine = true;\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n return s.toString();\n }",
"public void setDateMin(Date dateMin) {\n this.dateMin = dateMin;\n\n if (isAttached() && dateMin != null) {\n getPicker().set(\"min\", JsDate.create((double) dateMin.getTime()));\n }\n }",
"public static String[] allUpperCase(String... strings){\n\t\tString[] tmp = new String[strings.length];\n\t\tfor(int idx=0;idx<strings.length;idx++){\n\t\t\tif(strings[idx] != null){\n\t\t\t\ttmp[idx] = strings[idx].toUpperCase();\n\t\t\t}\n\t\t}\n\t\treturn tmp;\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 }"
] |
Deletes the VFS XML bundle file.
@throws CmsException thrown if the delete operation fails. | [
"private void removeXmlBundleFile() throws CmsException {\n\n lockLocalization(null);\n m_cms.deleteResource(m_resource, CmsResource.DELETE_PRESERVE_SIBLINGS);\n m_resource = null;\n\n }"
] | [
"public Set<PlaybackState> getPlaybackState() {\n Set<PlaybackState> result = new HashSet<PlaybackState>(playbackStateMap.values());\n return Collections.unmodifiableSet(result);\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 }",
"private StateVertex addStateToCurrentState(StateVertex newState, Eventable eventable) {\n\t\tLOGGER.debug(\"addStateToCurrentState currentState: {} newState {}\",\n\t\t\t\tcurrentState.getName(), newState.getName());\n\n\t\t// Add the state to the stateFlowGraph. Store the result\n\t\tStateVertex cloneState = stateFlowGraph.putIfAbsent(newState);\n\n\t\t// Is there a clone detected?\n\t\tif (cloneState != null) {\n\t\t\tLOGGER.info(\"CLONE State detected: {} and {} are the same.\", newState.getName(),\n\t\t\t\t\tcloneState.getName());\n\t\t\tLOGGER.debug(\"CLONE CURRENT STATE: {}\", currentState.getName());\n\t\t\tLOGGER.debug(\"CLONE STATE: {}\", cloneState.getName());\n\t\t\tLOGGER.debug(\"CLONE CLICKABLE: {}\", eventable);\n\t\t\tboolean added = stateFlowGraph.addEdge(currentState, cloneState, eventable);\n\t\t\tif (!added) {\n\t\t\t\tLOGGER.debug(\"Clone edge !! Need to fix the crawlPath??\");\n\t\t\t}\n\t\t} else {\n\t\t\tstateFlowGraph.addEdge(currentState, newState, eventable);\n\t\t\tLOGGER.info(\"State {} added to the StateMachine.\", newState.getName());\n\t\t}\n\n\t\treturn cloneState;\n\t}",
"public static base_response rename(nitro_service client, gslbservice resource, String new_servicename) throws Exception {\n\t\tgslbservice renameresource = new gslbservice();\n\t\trenameresource.servicename = resource.servicename;\n\t\treturn renameresource.rename_resource(client,new_servicename);\n\t}",
"public void process(String name) throws Exception\n {\n ProjectFile file = new UniversalProjectReader().read(name);\n for (Task task : file.getTasks())\n {\n if (!task.getSummary())\n {\n System.out.print(task.getWBS());\n System.out.print(\"\\t\");\n System.out.print(task.getName());\n System.out.print(\"\\t\");\n System.out.print(format(task.getStart()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getActualStart()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getFinish()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getActualFinish()));\n System.out.println();\n }\n }\n }",
"public static synchronized void clearDaoCache() {\n\t\tif (classMap != null) {\n\t\t\tclassMap.clear();\n\t\t\tclassMap = null;\n\t\t}\n\t\tif (tableConfigMap != null) {\n\t\t\ttableConfigMap.clear();\n\t\t\ttableConfigMap = null;\n\t\t}\n\t}",
"private String parseEnvelope() {\r\n List<String> response = new ArrayList<>();\r\n //1. Date ---------------\r\n response.add(LB + Q + sentDateEnvelopeString + Q + SP);\r\n //2. Subject ---------------\r\n if (subject != null && (subject.length() != 0)) {\r\n response.add(Q + escapeHeader(subject) + Q + SP);\r\n } else {\r\n response.add(NIL + SP);\r\n }\r\n //3. From ---------------\r\n addAddressToEnvelopeIfAvailable(from, response);\r\n response.add(SP);\r\n //4. Sender ---------------\r\n addAddressToEnvelopeIfAvailableWithNetscapeFeature(sender, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailableWithNetscapeFeature(replyTo, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailable(to, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailable(cc, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailable(bcc, response);\r\n response.add(SP);\r\n if (inReplyTo != null && inReplyTo.length > 0) {\r\n response.add(inReplyTo[0]);\r\n } else {\r\n response.add(NIL);\r\n }\r\n response.add(SP);\r\n if (messageID != null && messageID.length > 0) {\r\n messageID[0] = escapeHeader(messageID[0]);\r\n response.add(Q + messageID[0] + Q);\r\n } else {\r\n response.add(NIL);\r\n }\r\n response.add(RB);\r\n\r\n StringBuilder buf = new StringBuilder(16 * response.size());\r\n for (String aResponse : response) {\r\n buf.append(aResponse);\r\n }\r\n\r\n return buf.toString();\r\n }",
"public static RemoteProxyController create(final TransactionalProtocolClient client, final PathAddress pathAddress,\n final ProxyOperationAddressTranslator addressTranslator,\n final ModelVersion targetKernelVersion) {\n return new RemoteProxyController(client, pathAddress, addressTranslator, targetKernelVersion);\n }",
"public static server_service_binding[] get(nitro_service service, String name) throws Exception{\n\t\tserver_service_binding obj = new server_service_binding();\n\t\tobj.set_name(name);\n\t\tserver_service_binding response[] = (server_service_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Returns the value of the identified field as a Long.
@param fieldName the name of the field
@return the value of the field as a Long
@throws FqlException if the field cannot be expressed as an Long | [
"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 base_response Import(nitro_service client, application resource) throws Exception {\n\t\tapplication Importresource = new application();\n\t\tImportresource.apptemplatefilename = resource.apptemplatefilename;\n\t\tImportresource.appname = resource.appname;\n\t\tImportresource.deploymentfilename = resource.deploymentfilename;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}",
"public void adjustGlassSize() {\n if (isGlassEnabled()) {\n ResizeHandler handler = getGlassResizer();\n if (handler != null) handler.onResize(null);\n }\n }",
"public <T extends CanvasWriter> T getWriter(Class<T> type, OauthToken oauthToken, Boolean serializeNulls) {\n LOG.debug(\"Factory call to instantiate class: \" + type.getName());\n RestClient restClient = new RefreshingRestClient();\n\n @SuppressWarnings(\"unchecked\")\n Class<T> concreteClass = (Class<T>) writerMap.get(type);\n\n if (concreteClass == null) {\n throw new UnsupportedOperationException(\"No implementation for requested interface found: \" + type.getName());\n }\n\n LOG.debug(\"got writer class: \" + concreteClass);\n try {\n Constructor<T> constructor = concreteClass.getConstructor(String.class, Integer.class, OauthToken.class,\n RestClient.class, Integer.TYPE, Integer.TYPE, Integer.class, Boolean.class);\n return constructor.newInstance(canvasBaseUrl, CANVAS_API_VERSION, oauthToken, restClient,\n connectTimeout, readTimeout, null, serializeNulls);\n } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {\n throw new UnsupportedOperationException(\"Unknown error instantiating the concrete API class: \" + type.getName(), e);\n }\n }",
"@Override\n public boolean postBuild(MavenBuildProxy build, MavenProject pom, BuildListener listener)\n throws InterruptedException, IOException {\n build.executeAsync(new BuildCallable<Void, IOException>() {\n // record is transient, so needs to make a copy first\n private final Set<MavenDependency> d = dependencies;\n\n public Void call(MavenBuild build) throws IOException, InterruptedException {\n // add the action\n //TODO: [by yl] These actions are persisted into the build.xml of each build run - we need another\n //context to store these actions\n build.getActions().add(new MavenDependenciesRecord(build, d));\n return null;\n }\n });\n return true;\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 }",
"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 }",
"public void rotateToFront() {\n GVRTransform transform = mSceneRootObject.getTransform();\n transform.setRotation(1, 0, 0, 0);\n transform.rotateByAxisWithPivot(-frontFacingRotation + 180, 0, 1, 0, 0, 0, 0);\n }",
"public static base_response Shutdown(nitro_service client, shutdown resource) throws Exception {\n\t\tshutdown Shutdownresource = new shutdown();\n\t\treturn Shutdownresource.perform_operation(client);\n\t}",
"@Override\n\tpublic String toCanonicalString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.canonicalString) == null) {\n\t\t\tstringCache.canonicalString = result = toNormalizedString(IPv6StringCache.canonicalParams);\n\t\t}\n\t\treturn result;\n\t}"
] |
Get range around median containing specified percentage of values.
@param values Values.
@param percent Values percentage around median.
@return Returns the range which containes specifies percentage of values. | [
"public static IntRange GetRange( int[] values, double percent ){\n int total = 0, n = values.length;\n\n // for all values\n for ( int i = 0; i < n; i++ )\n {\n // accumalate total\n total += values[i];\n }\n\n int min, max, hits;\n int h = (int) ( total * ( percent + ( 1 - percent ) / 2 ) );\n\n // get range min value\n for ( min = 0, hits = total; min < n; min++ )\n {\n hits -= values[min];\n if ( hits < h )\n break;\n }\n // get range max value\n for ( max = n - 1, hits = total; max >= 0; max-- )\n {\n hits -= values[max];\n if ( hits < h )\n break;\n }\n return new IntRange( min, max );\n }"
] | [
"public void insertValue(int index, float[] newValue) {\n if ( newValue.length == 2) {\n try {\n value.add( index, new SFVec2f(newValue[0], newValue[1]) );\n }\n catch (IndexOutOfBoundsException e) {\n Log.e(TAG, \"X3D MFVec2f get1Value(index) out of bounds.\" + e);\n }\n catch (Exception e) {\n Log.e(TAG, \"X3D MFVec2f get1Value(index) exception \" + e);\n }\n }\n else {\n Log.e(TAG, \"X3D MFVec2f insertValue set with array length not equal to 2\");\n }\n }",
"private void writeCostRateTables(Project.Resources.Resource xml, Resource mpx)\n {\n //Rates rates = m_factory.createProjectResourcesResourceRates();\n //xml.setRates(rates);\n //List<Project.Resources.Resource.Rates.Rate> ratesList = rates.getRate();\n\n List<Project.Resources.Resource.Rates.Rate> ratesList = null;\n\n for (int tableIndex = 0; tableIndex < 5; tableIndex++)\n {\n CostRateTable table = mpx.getCostRateTable(tableIndex);\n if (table != null)\n {\n Date from = DateHelper.FIRST_DATE;\n for (CostRateTableEntry entry : table)\n {\n if (costRateTableWriteRequired(entry, from))\n {\n if (ratesList == null)\n {\n Rates rates = m_factory.createProjectResourcesResourceRates();\n xml.setRates(rates);\n ratesList = rates.getRate();\n }\n\n Project.Resources.Resource.Rates.Rate rate = m_factory.createProjectResourcesResourceRatesRate();\n ratesList.add(rate);\n\n rate.setCostPerUse(DatatypeConverter.printCurrency(entry.getCostPerUse()));\n rate.setOvertimeRate(DatatypeConverter.printRate(entry.getOvertimeRate()));\n rate.setOvertimeRateFormat(DatatypeConverter.printTimeUnit(entry.getOvertimeRateFormat()));\n rate.setRatesFrom(from);\n from = entry.getEndDate();\n rate.setRatesTo(from);\n rate.setRateTable(BigInteger.valueOf(tableIndex));\n rate.setStandardRate(DatatypeConverter.printRate(entry.getStandardRate()));\n rate.setStandardRateFormat(DatatypeConverter.printTimeUnit(entry.getStandardRateFormat()));\n }\n }\n }\n }\n }",
"public static base_response update(nitro_service client, systemuser resource) throws Exception {\n\t\tsystemuser updateresource = new systemuser();\n\t\tupdateresource.username = resource.username;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.externalauth = resource.externalauth;\n\t\tupdateresource.promptstring = resource.promptstring;\n\t\tupdateresource.timeout = resource.timeout;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private void processOutlineCodeValues() throws IOException\n {\n DirectoryEntry outlineCodeDir = (DirectoryEntry) m_projectDir.getEntry(\"TBkndOutlCode\");\n FixedMeta fm = new FixedMeta(new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry(\"FixedMeta\"))), 10);\n FixedData fd = new FixedData(fm, new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry(\"FixedData\"))));\n\n Map<Integer, FieldType> map = new HashMap<Integer, FieldType>();\n\n int items = fm.getItemCount();\n for (int loop = 0; loop < items; loop++)\n {\n byte[] data = fd.getByteArrayValue(loop);\n if (data.length < 18)\n {\n continue;\n }\n\n int index = MPPUtility.getShort(data, 0);\n int fieldID = MPPUtility.getInt(data, 12);\n FieldType fieldType = FieldTypeHelper.getInstance(fieldID);\n if (fieldType.getFieldTypeClass() != FieldTypeClass.UNKNOWN)\n {\n map.put(Integer.valueOf(index), fieldType);\n }\n }\n\n VarMeta outlineCodeVarMeta = new VarMeta9(new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry(\"VarMeta\"))));\n Var2Data outlineCodeVarData = new Var2Data(outlineCodeVarMeta, new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry(\"Var2Data\"))));\n\n Map<FieldType, List<Pair<String, String>>> valueMap = new HashMap<FieldType, List<Pair<String, String>>>();\n\n for (Integer id : outlineCodeVarMeta.getUniqueIdentifierArray())\n {\n FieldType fieldType = map.get(id);\n String value = outlineCodeVarData.getUnicodeString(id, VALUE);\n String description = outlineCodeVarData.getUnicodeString(id, DESCRIPTION);\n\n List<Pair<String, String>> list = valueMap.get(fieldType);\n if (list == null)\n {\n list = new ArrayList<Pair<String, String>>();\n valueMap.put(fieldType, list);\n }\n list.add(new Pair<String, String>(value, description));\n }\n\n for (Entry<FieldType, List<Pair<String, String>>> entry : valueMap.entrySet())\n {\n populateContainer(entry.getKey(), entry.getValue());\n }\n }",
"public final void printClientConfig(final JSONWriter json) throws JSONException {\n json.key(\"attributes\");\n json.array();\n for (Map.Entry<String, Attribute> entry: this.attributes.entrySet()) {\n Attribute attribute = entry.getValue();\n if (attribute.getClass().getAnnotation(InternalAttribute.class) == null) {\n json.object();\n attribute.printClientConfig(json, this);\n json.endObject();\n }\n }\n json.endArray();\n }",
"protected DirectiveStatement parseDirectiveStatement(DirectiveStContext node)\r\n\t{\r\n\t\tDirectiveStContext stContext = (DirectiveStContext) node;\r\n\t\tDirectiveExpContext direExp = stContext.directiveExp();\r\n\t\tToken token = direExp.Identifier().getSymbol();\r\n\t\tString directive = token.getText().toLowerCase().intern();\r\n\t\tTerminalNode value = direExp.StringLiteral();\r\n\t\tList<TerminalNode> idNodeList = null;\r\n\t\tDirectiveExpIDListContext directExpidLisCtx = direExp.directiveExpIDList();\r\n\t\tif (directExpidLisCtx != null)\r\n\t\t{\r\n\t\t\tidNodeList = directExpidLisCtx.Identifier();\r\n\t\t}\r\n\r\n\t\tSet<String> idList = null;\r\n\t\tDirectiveStatement ds = null;\r\n\r\n\t\tif (value != null)\r\n\t\t{\r\n\t\t\tString idListValue = this.getStringValue(value.getText());\r\n\t\t\tidList = new HashSet(Arrays.asList(idListValue.split(\",\")));\r\n\t\t\tds = new DirectiveStatement(directive, idList, this.getBTToken(token));\r\n\r\n\t\t}\r\n\t\telse if (idNodeList != null)\r\n\t\t{\r\n\t\t\tidList = new HashSet<String>();\r\n\t\t\tfor (TerminalNode t : idNodeList)\r\n\t\t\t{\r\n\t\t\t\tidList.add(t.getText());\r\n\t\t\t}\r\n\t\t\tds = new DirectiveStatement(directive, idList, this.getBTToken(token));\r\n\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tds = new DirectiveStatement(directive, Collections.EMPTY_SET, this.getBTToken(token));\r\n\t\t}\r\n\r\n\t\tif (directive.equals(\"dynamic\"))\r\n\t\t{\r\n\r\n\t\t\tif (ds.getIdList().size() == 0)\r\n\t\t\t{\r\n\t\t\t\tdata.allDynamic = true;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tdata.dynamicObjectSet = ds.getIdList();\r\n\t\t\t}\r\n\t\t\tds = new DirectiveStatement(directive, Collections.EMPTY_SET, this.getBTToken(token));\r\n\t\t\t\r\n\t\t\treturn ds;\r\n\r\n\t\t}\r\n\t\telse if (directive.equalsIgnoreCase(\"safe_output_open\".intern()))\r\n\t\t{\r\n\t\t\tthis.pbCtx.isSafeOutput = true;\r\n\t\t\treturn ds;\r\n\t\t}\r\n\t\telse if (directive.equalsIgnoreCase(\"safe_output_close\".intern()))\r\n\t\t{\r\n\t\t\tthis.pbCtx.isSafeOutput = false;\r\n\t\t\treturn ds;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn ds;\r\n\t\t}\r\n\t}",
"public static Index index(String keyspace, String table, String name) {\n return new Index(table, name).keyspace(keyspace);\n }",
"public void deleteIndex(String indexName, String designDocId, String type) {\n assertNotEmpty(indexName, \"indexName\");\n assertNotEmpty(designDocId, \"designDocId\");\n assertNotNull(type, \"type\");\n if (!designDocId.startsWith(\"_design\")) {\n designDocId = \"_design/\" + designDocId;\n }\n URI uri = new DatabaseURIHelper(db.getDBUri()).path(\"_index\").path(designDocId)\n .path(type).path(indexName).build();\n InputStream response = null;\n try {\n HttpConnection connection = Http.DELETE(uri);\n response = client.couchDbClient.executeToInputStream(connection);\n getResponse(response, Response.class, client.getGson());\n } finally {\n close(response);\n }\n }",
"public Integer getBlockMaskPrefixLength(boolean network) {\n\t\tInteger prefixLen;\n\t\tif(network) {\n\t\t\tif(hasNoPrefixCache() || (prefixLen = prefixCache.networkMaskPrefixLen) == null) {\n\t\t\t\tprefixLen = setNetworkMaskPrefix(checkForPrefixMask(network));\n\t\t\t}\n\t\t} else {\n\t\t\tif(hasNoPrefixCache() || (prefixLen = prefixCache.hostMaskPrefixLen) == null) {\n\t\t\t\tprefixLen = setHostMaskPrefix(checkForPrefixMask(network));\n\t\t\t}\n\t\t}\n\t\tif(prefixLen < 0) {\n\t\t\treturn null;\n\t\t}\n\t\treturn prefixLen;\n\t}"
] |
Create a WebMBeanAdaptor for a specified MBean name.
@param mBeanName the MBean name (can be URL-encoded).
@param encoding the string encoding to be used (i.e. UTF-8)
@return the created WebMBeanAdaptor.
@throws JMException Java Management Exception
@throws UnsupportedEncodingException if the encoding is not supported. | [
"public WebMBeanAdapter createWebMBeanAdapter(String mBeanName, String encoding)\n throws JMException, UnsupportedEncodingException {\n return new WebMBeanAdapter(mBeanServer, mBeanName, encoding);\n }"
] | [
"private void calculateSCL(double[] x) {\r\n //System.out.println(\"Checking at: \"+x[0]+\" \"+x[1]+\" \"+x[2]);\r\n value = 0.0;\r\n Arrays.fill(derivative, 0.0);\r\n double[] sums = new double[numClasses];\r\n double[] probs = new double[numClasses];\r\n double[] counts = new double[numClasses];\r\n Arrays.fill(counts, 0.0);\r\n for (int d = 0; d < data.length; d++) {\r\n // if (d == testMin) {\r\n // d = testMax - 1;\r\n // continue;\r\n // }\r\n int[] features = data[d];\r\n // activation\r\n Arrays.fill(sums, 0.0);\r\n for (int c = 0; c < numClasses; c++) {\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n sums[c] += x[i];\r\n }\r\n }\r\n // expectation (slower routine replaced by fast way)\r\n // double total = Double.NEGATIVE_INFINITY;\r\n // for (int c=0; c<numClasses; c++) {\r\n // total = SloppyMath.logAdd(total, sums[c]);\r\n // }\r\n double total = ArrayMath.logSum(sums);\r\n int ld = labels[d];\r\n for (int c = 0; c < numClasses; c++) {\r\n probs[c] = Math.exp(sums[c] - total);\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n derivative[i] += probs[ld] * probs[c];\r\n }\r\n }\r\n // observed\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], labels[d]);\r\n derivative[i] -= probs[ld];\r\n }\r\n value -= probs[ld];\r\n }\r\n // priors\r\n if (true) {\r\n for (int i = 0; i < x.length; i++) {\r\n double k = 1.0;\r\n double w = x[i];\r\n value += k * w * w / 2.0;\r\n derivative[i] += k * w;\r\n }\r\n }\r\n }",
"private static long hexdump(InputStream is, PrintWriter pw) throws Exception\n {\n byte[] buffer = new byte[BUFFER_SIZE];\n long byteCount = 0;\n\n char c;\n int loop;\n int count;\n StringBuilder sb = new StringBuilder();\n\n while (true)\n {\n count = is.read(buffer);\n if (count == -1)\n {\n break;\n }\n\n byteCount += count;\n\n sb.setLength(0);\n\n for (loop = 0; loop < count; loop++)\n {\n sb.append(\" \");\n sb.append(HEX_DIGITS[(buffer[loop] & 0xF0) >> 4]);\n sb.append(HEX_DIGITS[buffer[loop] & 0x0F]);\n }\n\n while (loop < BUFFER_SIZE)\n {\n sb.append(\" \");\n ++loop;\n }\n\n sb.append(\" \");\n\n for (loop = 0; loop < count; loop++)\n {\n c = (char) buffer[loop];\n if (c > 200 || c < 27)\n {\n c = ' ';\n }\n\n sb.append(c);\n }\n\n pw.println(sb.toString());\n }\n\n return (byteCount);\n }",
"protected String getPayload(Message message) {\n try {\n String encoding = (String) message.get(Message.ENCODING);\n if (encoding == null) {\n encoding = \"UTF-8\";\n }\n CachedOutputStream cos = message.getContent(CachedOutputStream.class);\n if (cos == null) {\n LOG.warning(\"Could not find CachedOutputStream in message.\"\n + \" Continuing without message content\");\n return \"\";\n }\n return new String(cos.getBytes(), encoding);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }",
"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 }",
"public Map<InetSocketAddress, ServerPort> activePorts() {\n final Server server = this.server;\n if (server != null) {\n return server.activePorts();\n } else {\n return Collections.emptyMap();\n }\n }",
"public static <K, V> Map<K, V> copyOf(Map<K, V> map) {\n Preconditions.checkNotNull(map);\n return ImmutableMap.<K, V> builder().putAll(map).build();\n }",
"public WebSocketContext sendToTagged(String message, String tag, boolean excludeSelf) {\n return sendToConnections(message, tag, manager.tagRegistry(), excludeSelf);\n }",
"public Token add( Symbol symbol ) {\n Token t = new Token(symbol);\n push( t );\n return t;\n }",
"private int getFlagResource(Country country) {\n return getContext().getResources().getIdentifier(\"country_\" + country.getIso().toLowerCase(), \"drawable\", getContext().getPackageName());\n }"
] |
Returns the bundle jar classpath element. | [
"protected String getBundleJarPath() throws MalformedURLException {\n Path path = PROPERTIES.getAllureHome().resolve(\"app/allure-bundle.jar\").toAbsolutePath();\n if (Files.notExists(path)) {\n throw new AllureCommandException(String.format(\"Bundle not found by path <%s>\", path));\n }\n return path.toUri().toURL().toString();\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 static CentralDogma forConfig(File configFile) throws IOException {\n requireNonNull(configFile, \"configFile\");\n return new CentralDogma(Jackson.readValue(configFile, CentralDogmaConfig.class));\n }",
"public PreparedStatement getSelectByPKStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getSelectByPKStmt(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 }",
"public void unlink(Object obj, ObjectReferenceDescriptor ord, boolean insert)\r\n {\r\n linkOrUnlink(false, obj, ord, insert);\r\n }",
"private void processSchedulingProjectProperties() throws SQLException\n {\n List<Row> rows = getRows(\"select * from \" + m_schema + \"projprop where proj_id=? and prop_name='scheduling'\", m_projectID);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n Record record = Record.getRecord(row.getString(\"prop_value\"));\n if (record != null)\n {\n String[] keyValues = record.getValue().split(\"\\\\|\");\n for (int i = 0; i < keyValues.length - 1; ++i)\n {\n if (\"sched_calendar_on_relationship_lag\".equals(keyValues[i]))\n {\n Map<String, Object> customProperties = new HashMap<String, Object>();\n customProperties.put(\"LagCalendar\", keyValues[i + 1]);\n m_reader.getProject().getProjectProperties().setCustomProperties(customProperties);\n break;\n }\n }\n }\n }\n }",
"public static String join(int[] array, String separator) {\n if (array != null) {\n StringBuilder buf = new StringBuilder(Math.max(16, (separator.length() + 1) * array.length));\n char singleChar = separator.length() == 1 ? separator.charAt(0) : 0;\n for (int i = 0; i < array.length; i++) {\n if (i != 0) {\n if (singleChar != 0) {\n // More efficient\n buf.append(singleChar);\n } else {\n buf.append(separator);\n }\n }\n buf.append(array[i]);\n }\n return buf.toString();\n } else {\n return \"\";\n }\n }",
"public static lbvserver_servicegroup_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_servicegroup_binding obj = new lbvserver_servicegroup_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_servicegroup_binding response[] = (lbvserver_servicegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void useOldRESTService() throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n com.example.customerservice.CustomerService customerService = JAXRSClientFactory\n .createFromModel(\"http://localhost:\" + port + \"/examples/direct/rest\", \n com.example.customerservice.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n\n System.out.println(\"Using old RESTful CustomerService with old client\");\n\n customer.v1.Customer customer = createOldCustomer(\"Smith Old REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith Old REST\");\n printOldCustomerDetails(customer);\n }",
"public static AliasOperationTransformer replaceLastElement(final PathElement element) {\n return create(new AddressTransformer() {\n @Override\n public PathAddress transformAddress(final PathAddress original) {\n final PathAddress address = original.subAddress(0, original.size() -1);\n return address.append(element);\n }\n });\n }"
] |
Gets the SerialMessage as a byte array.
@return the message | [
"public byte[] getMessageBuffer() {\n\t\tByteArrayOutputStream resultByteBuffer = new ByteArrayOutputStream();\n\t\tbyte[] result;\n\t\tresultByteBuffer.write((byte)0x01);\n\t\tint messageLength = messagePayload.length + \n\t\t\t\t(this.messageClass == SerialMessageClass.SendData && \n\t\t\t\tthis.messageType == SerialMessageType.Request ? 5 : 3); // calculate and set length\n\t\t\n\t\tresultByteBuffer.write((byte) messageLength);\n\t\tresultByteBuffer.write((byte) messageType.ordinal());\n\t\tresultByteBuffer.write((byte) messageClass.getKey());\n\t\t\n\t\ttry {\n\t\t\tresultByteBuffer.write(messagePayload);\n\t\t} catch (IOException e) {\n\t\t\t\n\t\t}\n\n\t\t// callback ID and transmit options for a Send Data message.\n\t\tif (this.messageClass == SerialMessageClass.SendData && this.messageType == SerialMessageType.Request) {\n\t\t\tresultByteBuffer.write(transmitOptions);\n\t\t\tresultByteBuffer.write(callbackId);\n\t\t}\n\t\t\n\t\tresultByteBuffer.write((byte) 0x00);\n\t\tresult = resultByteBuffer.toByteArray();\n\t\tresult[result.length - 1] = 0x01;\n\t\tresult[result.length - 1] = calculateChecksum(result);\n\t\tlogger.debug(\"Assembled message buffer = \" + SerialMessage.bb2hex(result));\n\t\treturn result;\n\t}"
] | [
"public void addResourceAssignment(ResourceAssignment assignment)\n {\n if (getExistingResourceAssignment(assignment.getResource()) == null)\n {\n m_assignments.add(assignment);\n getParentFile().getResourceAssignments().add(assignment);\n\n Resource resource = assignment.getResource();\n if (resource != null)\n {\n resource.addResourceAssignment(assignment);\n }\n }\n }",
"public String getVertexString() {\n if (tail() != null) {\n return \"\" + tail().index + \"-\" + head().index;\n } else {\n return \"?-\" + head().index;\n }\n }",
"public static base_responses renumber(nitro_service client, nspbr6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnspbr6 renumberresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\trenumberresources[i] = new nspbr6();\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, renumberresources,\"renumber\");\n\t\t}\n\t\treturn result;\n\t}",
"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 }",
"private void initManagementPart() {\n\n m_manageExceptionsButton.setText(Messages.get().key(Messages.GUI_SERIALDATE_BUTTON_MANAGE_EXCEPTIONS_0));\n m_manageExceptionsButton.getElement().getStyle().setFloat(Style.Float.RIGHT);\n }",
"public void setMesh(GVRMesh mesh) {\n mMesh = mesh;\n NativeMeshCollider.setMesh(getNative(), mesh.getNative());\n }",
"public static Timer getNamedTimer(String timerName, int todoFlags) {\n\t\treturn getNamedTimer(timerName, todoFlags, Thread.currentThread()\n\t\t\t\t.getId());\n\t}",
"synchronized public String getPrettyProgressBar() {\n StringBuilder sb = new StringBuilder();\n\n double taskRate = numTasksCompleted / (double) totalTaskCount;\n double partitionStoreRate = numPartitionStoresMigrated / (double) totalPartitionStoreCount;\n\n long deltaTimeMs = System.currentTimeMillis() - startTimeMs;\n long taskTimeRemainingMs = Long.MAX_VALUE;\n if(taskRate > 0) {\n taskTimeRemainingMs = (long) (deltaTimeMs * ((1.0 / taskRate) - 1.0));\n }\n long partitionStoreTimeRemainingMs = Long.MAX_VALUE;\n if(partitionStoreRate > 0) {\n partitionStoreTimeRemainingMs = (long) (deltaTimeMs * ((1.0 / partitionStoreRate) - 1.0));\n }\n\n // Title line\n sb.append(\"Progress update on rebalancing batch \" + batchId).append(Utils.NEWLINE);\n // Tasks in flight update\n sb.append(\"There are currently \" + tasksInFlight.size() + \" rebalance tasks executing: \")\n .append(tasksInFlight)\n .append(\".\")\n .append(Utils.NEWLINE);\n // Tasks completed update\n sb.append(\"\\t\" + numTasksCompleted + \" out of \" + totalTaskCount\n + \" rebalance tasks complete.\")\n .append(Utils.NEWLINE)\n .append(\"\\t\")\n .append(decimalFormatter.format(taskRate * 100.0))\n .append(\"% done, estimate \")\n .append(taskTimeRemainingMs)\n .append(\" ms (\")\n .append(TimeUnit.MILLISECONDS.toMinutes(taskTimeRemainingMs))\n .append(\" minutes) remaining.\")\n .append(Utils.NEWLINE);\n // Partition-stores migrated update\n sb.append(\"\\t\" + numPartitionStoresMigrated + \" out of \" + totalPartitionStoreCount\n + \" partition-stores migrated.\")\n .append(Utils.NEWLINE)\n .append(\"\\t\")\n .append(decimalFormatter.format(partitionStoreRate * 100.0))\n .append(\"% done, estimate \")\n .append(partitionStoreTimeRemainingMs)\n .append(\" ms (\")\n .append(TimeUnit.MILLISECONDS.toMinutes(partitionStoreTimeRemainingMs))\n .append(\" minutes) remaining.\")\n .append(Utils.NEWLINE);\n return sb.toString();\n }",
"private ArrayList<RunListener> instantiateRunListeners() throws Exception {\n ArrayList<RunListener> instances = new ArrayList<>();\n\n if (runListeners != null) {\n for (String className : Arrays.asList(runListeners.split(\",\"))) {\n instances.add((RunListener) this.instantiate(className).newInstance());\n }\n }\n\n return instances;\n }"
] |
Record a device announcement in the devices map, so we know whe saw it.
@param announcement the announcement to be recorded | [
"private void updateDevices(DeviceAnnouncement announcement) {\n firstDeviceTime.compareAndSet(0, System.currentTimeMillis());\n devices.put(announcement.getAddress(), announcement);\n }"
] | [
"public void addRequiredBundles(Set<String> bundles) {\n\t\t// TODO manage transitive dependencies\n\t\t// don't require self\n\t\tSet<String> bundlesToMerge;\n\t\tString bundleName = (String) getMainAttributes().get(BUNDLE_SYMBOLIC_NAME);\n\t\tif (bundleName != null) {\n\t\t\tint idx = bundleName.indexOf(';');\n\t\t\tif (idx >= 0) {\n\t\t\t\tbundleName = bundleName.substring(0, idx);\n\t\t\t}\n\t\t}\n\t\tif (bundleName != null && bundles.contains(bundleName)\n\t\t\t\t|| projectName != null && bundles.contains(projectName)) {\n\t\t\tbundlesToMerge = new LinkedHashSet<String>(bundles);\n\t\t\tbundlesToMerge.remove(bundleName);\n\t\t\tbundlesToMerge.remove(projectName);\n\t\t} else {\n\t\t\tbundlesToMerge = bundles;\n\t\t}\n\t\tString s = (String) getMainAttributes().get(REQUIRE_BUNDLE);\n\t\tWrapper<Boolean> modified = Wrapper.wrap(this.modified);\n\t\tString result = mergeIntoCommaSeparatedList(s, bundlesToMerge, modified, lineDelimiter);\n\t\tthis.modified = modified.get();\n\t\tgetMainAttributes().put(REQUIRE_BUNDLE, result);\n\t}",
"protected Element createPageElement()\n {\n String pstyle = \"\";\n PDRectangle layout = getCurrentMediaBox();\n if (layout != null)\n {\n /*System.out.println(\"x1 \" + layout.getLowerLeftX());\n System.out.println(\"y1 \" + layout.getLowerLeftY());\n System.out.println(\"x2 \" + layout.getUpperRightX());\n System.out.println(\"y2 \" + layout.getUpperRightY());\n System.out.println(\"rot \" + pdpage.findRotation());*/\n \n float w = layout.getWidth();\n float h = layout.getHeight();\n final int rot = pdpage.getRotation();\n if (rot == 90 || rot == 270)\n {\n float x = w; w = h; h = x;\n }\n \n pstyle = \"width:\" + w + UNIT + \";\" + \"height:\" + h + UNIT + \";\";\n pstyle += \"overflow:hidden;\";\n }\n else\n log.warn(\"No media box found\");\n \n Element el = doc.createElement(\"div\");\n el.setAttribute(\"id\", \"page_\" + (pagecnt++));\n el.setAttribute(\"class\", \"page\");\n el.setAttribute(\"style\", pstyle);\n return el;\n }",
"protected void convertToHours(LinkedList<TimephasedWork> list)\n {\n for (TimephasedWork assignment : list)\n {\n Duration totalWork = assignment.getTotalAmount();\n Duration workPerDay = assignment.getAmountPerDay();\n totalWork = Duration.getInstance(totalWork.getDuration() / 60, TimeUnit.HOURS);\n workPerDay = Duration.getInstance(workPerDay.getDuration() / 60, TimeUnit.HOURS);\n assignment.setTotalAmount(totalWork);\n assignment.setAmountPerDay(workPerDay);\n }\n }",
"private void checkId(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String id = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID);\r\n\r\n if ((id != null) && (id.length() > 0))\r\n {\r\n try\r\n {\r\n Integer.parseInt(id);\r\n }\r\n catch (NumberFormatException ex)\r\n {\r\n throw new ConstraintException(\"The id attribute of field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" is not a valid number\");\r\n }\r\n }\r\n }",
"public double distance(Vector3d v) {\n double dx = x - v.x;\n double dy = y - v.y;\n double dz = z - v.z;\n\n return Math.sqrt(dx * dx + dy * dy + dz * dz);\n }",
"private static Constraint loadConstraint(Annotation context) {\n Constraint constraint = null;\n final ServiceLoader<Constraint> constraints = ServiceLoader.load(Constraint.class);\n\n for (Constraint aConstraint : constraints) {\n try {\n aConstraint.getClass().getDeclaredMethod(\"check\", context.annotationType());\n constraint = aConstraint;\n break;\n } catch (NoSuchMethodException e) {\n // Look for next implementation if method not found with required signature.\n }\n }\n\n if (constraint == null) {\n throw new IllegalStateException(\"Couldn't found any implementation of \" + Constraint.class.getName());\n }\n return constraint;\n }",
"public Jar addPackageOf(Class<?> clazz, Filter filter) throws IOException {\n try {\n final String path = clazz.getPackage().getName().replace('.', '/');\n URL dirURL = clazz.getClassLoader().getResource(path);\n if (dirURL != null && dirURL.getProtocol().equals(\"file\"))\n addDir(Paths.get(path), Paths.get(dirURL.toURI()), filter, false);\n else {\n if (dirURL == null) // In case of a jar file, we can't actually find a directory.\n dirURL = clazz.getClassLoader().getResource(clazz.getName().replace('.', '/') + \".class\");\n\n if (dirURL.getProtocol().equals(\"jar\")) {\n final URI jarUri = new URI(dirURL.getPath().substring(0, dirURL.getPath().indexOf('!')));\n try (JarInputStream jis1 = newJarInputStream(Files.newInputStream(Paths.get(jarUri)))) {\n for (JarEntry entry; (entry = jis1.getNextJarEntry()) != null;) {\n try {\n if (entry.getName().startsWith(path + '/')) {\n if (filter == null || filter.filter(entry.getName()))\n addEntryNoClose(jos, entry.getName(), jis1);\n }\n } catch (ZipException e) {\n if (!e.getMessage().startsWith(\"duplicate entry\"))\n throw e;\n }\n }\n }\n } else\n throw new AssertionError();\n }\n return this;\n } catch (URISyntaxException e) {\n throw new AssertionError(e);\n }\n }",
"public DocumentReaderAndWriter<IN> makePlainTextReaderAndWriter() {\r\n String readerClassName = flags.plainTextDocumentReaderAndWriter;\r\n // We set this default here if needed because there may be models\r\n // which don't have the reader flag set\r\n if (readerClassName == null) {\r\n readerClassName = SeqClassifierFlags.DEFAULT_PLAIN_TEXT_READER;\r\n }\r\n DocumentReaderAndWriter<IN> readerAndWriter;\r\n try {\r\n readerAndWriter = ((DocumentReaderAndWriter<IN>) Class.forName(readerClassName).newInstance());\r\n } catch (Exception e) {\r\n throw new RuntimeException(String.format(\"Error loading flags.plainTextDocumentReaderAndWriter: '%s'\", flags.plainTextDocumentReaderAndWriter), e);\r\n }\r\n readerAndWriter.init(flags);\r\n return readerAndWriter;\r\n }",
"public static void openFavoriteDialog(CmsFileExplorer explorer) {\n\n try {\n CmsExplorerFavoriteContext context = new CmsExplorerFavoriteContext(A_CmsUI.getCmsObject(), explorer);\n CmsFavoriteDialog dialog = new CmsFavoriteDialog(context, new CmsFavoriteDAO(A_CmsUI.getCmsObject()));\n Window window = CmsBasicDialog.prepareWindow(DialogWidth.max);\n window.setContent(dialog);\n window.setCaption(CmsVaadinUtils.getMessageText(org.opencms.ui.Messages.GUI_FAVORITES_DIALOG_TITLE_0));\n A_CmsUI.get().addWindow(window);\n window.center();\n } catch (CmsException e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n }"
] |
Gets an entry point for the given deployment. If one does not exist it will be created. If the request controller is disabled
this will return null.
Entry points are reference counted. If this method is called n times then {@link #removeControlPoint(ControlPoint)}
must also be called n times to clean up the entry points.
@param deploymentName The top level deployment name
@param entryPointName The entry point name
@return The entry point, or null if the request controller is disabled | [
"public synchronized ControlPoint getControlPoint(final String deploymentName, final String entryPointName) {\n ControlPointIdentifier id = new ControlPointIdentifier(deploymentName, entryPointName);\n ControlPoint ep = entryPoints.get(id);\n if (ep == null) {\n ep = new ControlPoint(this, deploymentName, entryPointName, trackIndividualControlPoints);\n entryPoints.put(id, ep);\n }\n ep.increaseReferenceCount();\n return ep;\n }"
] | [
"public ApnsServiceBuilder withSocksProxy(String host, int port) {\n Proxy proxy = new Proxy(Proxy.Type.SOCKS,\n new InetSocketAddress(host, port));\n return withProxy(proxy);\n }",
"protected final void _onConnect(WebSocketContext context) {\n if (null != connectionListener) {\n connectionListener.onConnect(context);\n }\n connectionListenerManager.notifyFreeListeners(context, false);\n Act.eventBus().emit(new WebSocketConnectEvent(context));\n }",
"public static Shell createConsoleShell(String prompt, String appName, Object mainHandler) {\n return createConsoleShell(prompt, appName, mainHandler, new EmptyMultiMap<String, Object>());\n }",
"public byte[] getThumbnail(ThumbnailFileType fileType, int minWidth, int minHeight, int maxWidth, int maxHeight) {\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(\"min_width\", minWidth);\n builder.appendParam(\"min_height\", minHeight);\n builder.appendParam(\"max_width\", maxWidth);\n builder.appendParam(\"max_height\", maxHeight);\n\n URLTemplate template;\n if (fileType == ThumbnailFileType.PNG) {\n template = GET_THUMBNAIL_PNG_TEMPLATE;\n } else if (fileType == ThumbnailFileType.JPG) {\n template = GET_THUMBNAIL_JPG_TEMPLATE;\n } else {\n throw new BoxAPIException(\"Unsupported thumbnail file type\");\n }\n URL url = template.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxAPIResponse response = request.send();\n\n ByteArrayOutputStream thumbOut = new ByteArrayOutputStream();\n InputStream body = response.getBody();\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = body.read(buffer);\n while (n != -1) {\n thumbOut.write(buffer, 0, n);\n n = body.read(buffer);\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Error reading thumbnail bytes from response body\", e);\n } finally {\n response.disconnect();\n }\n\n return thumbOut.toByteArray();\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<BritishCutoverDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<BritishCutoverDate>) super.zonedDateTime(temporal);\n }",
"public List<URL> scan(Predicate<String> filter)\n {\n List<URL> discoveredURLs = new ArrayList<>(128);\n\n // For each Forge addon...\n for (Addon addon : furnace.getAddonRegistry().getAddons(AddonFilters.allStarted()))\n {\n List<String> filteredResourcePaths = filterAddonResources(addon, filter);\n for (String filePath : filteredResourcePaths)\n {\n URL ruleFile = addon.getClassLoader().getResource(filePath);\n if (ruleFile != null)\n discoveredURLs.add(ruleFile);\n }\n }\n return discoveredURLs;\n }",
"public static void popShell() {\n\n ArrayList<CmsShell> shells = SHELL_STACK.get();\n if (shells.size() > 0) {\n shells.remove(shells.size() - 1);\n }\n\n }",
"public <OD> Where<T, ID> idEq(Dao<OD, ?> dataDao, OD data) throws SQLException {\n\t\tif (idColumnName == null) {\n\t\t\tthrow new SQLException(\"Object has no id column specified\");\n\t\t}\n\t\taddClause(new SimpleComparison(idColumnName, idFieldType, dataDao.extractId(data),\n\t\t\t\tSimpleComparison.EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}",
"public MaterialAccount getAccountByTitle(String title) {\n for(MaterialAccount account : accountManager)\n if(currentAccount.getTitle().equals(title))\n return account;\n\n return null;\n }"
] |
Converts the real matrix into a complex matrix.
@param input Real matrix. Not modified.
@param output Complex matrix. Modified. | [
"public static void convert(DMatrixD1 input , ZMatrixD1 output ) {\n if( input.numCols != output.numCols || input.numRows != output.numRows ) {\n throw new IllegalArgumentException(\"The matrices are not all the same dimension.\");\n }\n\n Arrays.fill(output.data, 0, output.getDataLength(), 0);\n\n final int length = output.getDataLength();\n\n for( int i = 0; i < length; i += 2 ) {\n output.data[i] = input.data[i/2];\n }\n }"
] | [
"public double d(double x){\n\t\tint intervalNumber =getIntervalNumber(x);\n\t\tif (intervalNumber==0 || intervalNumber==points.length) {\n\t\t\treturn x;\n\t\t}\n\t\treturn getIntervalReferencePoint(intervalNumber-1);\n\t}",
"private void writePropertyStatisticsToFile(UsageStatistics usageStatistics,\n\t\t\tString fileName) {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(fileName))) {\n\n\t\t\tout.println(\"Property id,in statements,in qualifiers,in references,total\");\n\n\t\t\tfor (Entry<PropertyIdValue, Integer> entry : usageStatistics.propertyCountsMain\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tint qCount = usageStatistics.propertyCountsQualifier.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tint rCount = usageStatistics.propertyCountsReferences.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tint total = entry.getValue() + qCount + rCount;\n\t\t\t\tout.println(entry.getKey().getId() + \",\" + entry.getValue()\n\t\t\t\t\t\t+ \",\" + qCount + \",\" + rCount + \",\" + total);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"static synchronized void clearLogContext() {\n final LogContext embeddedLogContext = Holder.LOG_CONTEXT;\n // Remove the configurator and clear the log context\n final Configurator configurator = embeddedLogContext.getLogger(\"\").detach(Configurator.ATTACHMENT_KEY);\n // If this was a PropertyConfigurator we can use the LogContextConfiguration API to tear down the LogContext\n if (configurator instanceof PropertyConfigurator) {\n final LogContextConfiguration logContextConfiguration = ((PropertyConfigurator) configurator).getLogContextConfiguration();\n clearLogContext(logContextConfiguration);\n } else if (configurator instanceof LogContextConfiguration) {\n clearLogContext((LogContextConfiguration) configurator);\n } else {\n // Remove all the handlers and close them as well as reset the loggers\n final List<String> loggerNames = Collections.list(embeddedLogContext.getLoggerNames());\n for (String name : loggerNames) {\n final Logger logger = embeddedLogContext.getLoggerIfExists(name);\n if (logger != null) {\n final Handler[] handlers = logger.clearHandlers();\n if (handlers != null) {\n for (Handler handler : handlers) {\n handler.close();\n }\n }\n logger.setFilter(null);\n logger.setUseParentFilters(false);\n logger.setUseParentHandlers(true);\n logger.setLevel(Level.INFO);\n }\n }\n }\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 ServerRedirect getRedirect(int id) throws Exception {\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, id);\n results = queryStatement.executeQuery();\n if (results.next()) {\n ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.SERVER_REDIRECT_REGION),\n results.getString(Constants.SERVER_REDIRECT_SRC_URL),\n results.getString(Constants.SERVER_REDIRECT_DEST_URL),\n results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));\n curServer.setProfileId(results.getInt(Constants.GENERIC_PROFILE_ID));\n\n return curServer;\n }\n logger.info(\"Did not find the ID: {}\", id);\n } catch (SQLException 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 (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return null;\n }",
"public void edit(Note note) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT);\r\n\r\n parameters.put(\"note_id\", note.getId());\r\n Rectangle bounds = note.getBounds();\r\n if (bounds != null) {\r\n parameters.put(\"note_x\", String.valueOf(bounds.x));\r\n parameters.put(\"note_y\", String.valueOf(bounds.y));\r\n parameters.put(\"note_w\", String.valueOf(bounds.width));\r\n parameters.put(\"note_h\", String.valueOf(bounds.height));\r\n }\r\n String text = note.getText();\r\n if (text != null) {\r\n parameters.put(\"note_text\", text);\r\n }\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\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 }",
"@Subscribe\n public void onEnd(AggregatedQuitEvent e) {\n try {\n writeHints(hintsFile, hints);\n } catch (IOException exception) {\n outer.log(\"Could not write back the hints file.\", exception, Project.MSG_ERR);\n }\n }",
"public static final Long date2utc(Date date) {\n\n // use null for a null date\n if (date == null) return null;\n \n long time = date.getTime();\n \n // remove the timezone offset \n time -= timezoneOffsetMillis(date);\n \n return time;\n }"
] |
another media scan way | [
"public static void addToMediaStore(Context context, File file) {\n String[] path = new String[]{file.getPath()};\n MediaScannerConnection.scanFile(context, path, null, null);\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 }",
"public void growInternal(int amount ) {\n int tmp[] = new int[ data.length + amount ];\n\n System.arraycopy(data,0,tmp,0,data.length);\n this.data = tmp;\n }",
"public static int Hamming(String first, String second) {\n\n if (first.length() != second.length())\n throw new IllegalArgumentException(\"The size of string must be the same.\");\n\n int diff = 0;\n for (int i = 0; i < first.length(); i++)\n if (first.charAt(i) != second.charAt(i))\n diff++;\n return diff;\n }",
"protected void doSave() {\n\n List<CmsFavoriteEntry> entries = getEntries();\n try {\n m_favDao.saveFavorites(entries);\n } catch (Exception e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n }",
"public static Set<String> getRoundingNames(String... providers) {\n return Optional.ofNullable(monetaryRoundingsSingletonSpi()).orElseThrow(\n () -> new MonetaryException(\"No MonetaryRoundingsSpi loaded, query functionality is not available.\"))\n .getRoundingNames(providers);\n }",
"@Override\n protected Deque<Step> childValue(Deque<Step> parentValue) {\n Deque<Step> queue = new LinkedList<>();\n queue.add(parentValue.getFirst());\n return queue;\n }",
"private Revision uncachedHeadRevision() {\n try (RevWalk revWalk = new RevWalk(jGitRepository)) {\n final ObjectId headRevisionId = jGitRepository.resolve(R_HEADS_MASTER);\n if (headRevisionId != null) {\n final RevCommit revCommit = revWalk.parseCommit(headRevisionId);\n return CommitUtil.extractRevision(revCommit.getFullMessage());\n }\n } catch (CentralDogmaException e) {\n throw e;\n } catch (Exception e) {\n throw new StorageException(\"failed to get the current revision\", e);\n }\n\n throw new StorageException(\"failed to determine the HEAD: \" + jGitRepository.getDirectory());\n }",
"private void readProjectProperties(Document cdp)\n {\n WorkspaceProperties props = cdp.getWorkspaceProperties();\n ProjectProperties mpxjProps = m_projectFile.getProjectProperties();\n mpxjProps.setSymbolPosition(props.getCurrencyPosition());\n mpxjProps.setCurrencyDigits(props.getCurrencyDigits());\n mpxjProps.setCurrencySymbol(props.getCurrencySymbol());\n mpxjProps.setDaysPerMonth(props.getDaysPerMonth());\n mpxjProps.setMinutesPerDay(props.getHoursPerDay());\n mpxjProps.setMinutesPerWeek(props.getHoursPerWeek());\n\n m_workHoursPerDay = mpxjProps.getMinutesPerDay().doubleValue() / 60.0;\n }",
"private void readTableBlock(int startIndex, int blockLength)\n {\n for (int index = startIndex; index < (startIndex + blockLength - 11); index++)\n {\n if (matchPattern(TABLE_BLOCK_PATTERNS, index))\n {\n int offset = index + 7;\n int nameLength = FastTrackUtility.getInt(m_buffer, offset);\n offset += 4;\n String name = new String(m_buffer, offset, nameLength, CharsetHelper.UTF16LE).toUpperCase();\n FastTrackTableType type = REQUIRED_TABLES.get(name);\n if (type != null)\n {\n m_currentTable = new FastTrackTable(type, this);\n m_tables.put(type, m_currentTable);\n }\n else\n {\n m_currentTable = null;\n }\n m_currentFields.clear();\n break;\n }\n }\n }"
] |
Formats the supplied value using the specified DateTimeFormat.
@return "" if the value is null | [
"private String long2string(Long value, DateTimeFormat fmt) {\n // for html5 inputs, use \"\" for no value\n if (value == null) return \"\";\n Date date = UTCDateBox.utc2date(value);\n return date != null ? fmt.format(date) : null;\n }"
] | [
"public void put(String key, String value) {\n synchronized (this.cache) {\n this.cache.put(key, value);\n }\n }",
"protected Date getPickerDate() {\n try {\n JsDate pickerDate = getPicker().get(\"select\").obj;\n return new Date((long) pickerDate.getTime());\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }",
"static VaultConfig readVaultElement_3_0(XMLExtendedStreamReader reader, Namespace expectedNs) throws XMLStreamException {\n final VaultConfig config = new VaultConfig();\n\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n final String value = reader.getAttributeValue(i);\n String name = reader.getAttributeLocalName(i);\n if (name.equals(CODE)){\n config.code = value;\n } else if (name.equals(MODULE)){\n config.module = value;\n } else {\n unexpectedVaultAttribute(reader.getAttributeLocalName(i), reader);\n }\n }\n if (config.code == null && config.module != null){\n throw new XMLStreamException(\"Attribute 'module' was specified without an attribute\"\n + \" 'code' for element '\" + VAULT + \"' at \" + reader.getLocation());\n }\n readVaultOptions(reader, config);\n return config;\n }",
"public String getScopes() {\n final StringBuilder sb = new StringBuilder();\n for (final Scope scope : Scope.values()) {\n sb.append(scope);\n sb.append(\", \");\n }\n final String scopes = sb.toString().trim();\n return scopes.substring(0, scopes.length() - 1);\n }",
"private void onChangedImpl(final int preferableCenterPosition) {\n for (ListOnChangedListener listener: mOnChangedListeners) {\n listener.onChangedStart(this);\n }\n\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"onChangedImpl(%s): items [%d] views [%d] mLayouts.size() = %d \" +\n \"preferableCenterPosition = %d\",\n getName(), getDataCount(), getViewCount(), mContent.mLayouts.size(), preferableCenterPosition);\n\n // TODO: selectively recycle data based on the changes in the data set\n mPreferableCenterPosition = preferableCenterPosition;\n recycleChildren();\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 List<TimephasedCost> getTimephasedCostMultipleRates(List<TimephasedWork> standardWorkList, List<TimephasedWork> overtimeWorkList)\n {\n List<TimephasedWork> standardWorkResult = new LinkedList<TimephasedWork>();\n List<TimephasedWork> overtimeWorkResult = new LinkedList<TimephasedWork>();\n CostRateTable table = getCostRateTable();\n ProjectCalendar calendar = getCalendar();\n\n Iterator<TimephasedWork> iter = overtimeWorkList.iterator();\n for (TimephasedWork standardWork : standardWorkList)\n {\n TimephasedWork overtimeWork = iter.hasNext() ? iter.next() : null;\n\n int startIndex = getCostRateTableEntryIndex(standardWork.getStart());\n int finishIndex = getCostRateTableEntryIndex(standardWork.getFinish());\n\n if (startIndex == finishIndex)\n {\n standardWorkResult.add(standardWork);\n if (overtimeWork != null)\n {\n overtimeWorkResult.add(overtimeWork);\n }\n }\n else\n {\n standardWorkResult.addAll(splitWork(table, calendar, standardWork, startIndex));\n if (overtimeWork != null)\n {\n overtimeWorkResult.addAll(splitWork(table, calendar, overtimeWork, startIndex));\n }\n }\n }\n\n return getTimephasedCostSingleRate(standardWorkResult, overtimeWorkResult);\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public static synchronized SlotReference getSlotReference(int player, CdjStatus.TrackSourceSlot slot) {\n Map<CdjStatus.TrackSourceSlot, SlotReference> playerMap = instances.get(player);\n if (playerMap == null) {\n playerMap = new HashMap<CdjStatus.TrackSourceSlot, SlotReference>();\n instances.put(player, playerMap);\n }\n SlotReference result = playerMap.get(slot);\n if (result == null) {\n result = new SlotReference(player, slot);\n playerMap.put(slot, result);\n }\n return result;\n }",
"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 }"
] |
Searches the model for all variable assignments and makes a default map of those variables, setting them to ""
@return the default variable assignment map | [
"private Map<String, String> fillInitialVariables() {\r\n Map<String, TransitionTarget> targets = model.getChildren();\n\r\n Set<String> variables = new HashSet<>();\r\n for (TransitionTarget target : targets.values()) {\r\n OnEntry entry = target.getOnEntry();\r\n List<Action> actions = entry.getActions();\r\n for (Action action : actions) {\r\n if (action instanceof Assign) {\r\n String variable = ((Assign) action).getName();\r\n variables.add(variable);\r\n } else if (action instanceof SetAssignExtension.SetAssignTag) {\r\n String variable = ((SetAssignExtension.SetAssignTag) action).getName();\r\n variables.add(variable);\r\n }\r\n }\r\n }\n\r\n Map<String, String> result = new HashMap<>();\r\n for (String variable : variables) {\r\n result.put(variable, \"\");\r\n }\n\r\n return result;\r\n }"
] | [
"public static ManagementProtocolHeader parse(DataInput input) throws IOException {\n validateSignature(input);\n expectHeader(input, ManagementProtocol.VERSION_FIELD);\n int version = input.readInt();\n expectHeader(input, ManagementProtocol.TYPE);\n byte type = input.readByte();\n switch (type) {\n case ManagementProtocol.TYPE_REQUEST:\n return new ManagementRequestHeader(version, input);\n case ManagementProtocol.TYPE_RESPONSE:\n return new ManagementResponseHeader(version, input);\n case ManagementProtocol.TYPE_BYE_BYE:\n return new ManagementByeByeHeader(version);\n case ManagementProtocol.TYPE_PING:\n return new ManagementPingHeader(version);\n case ManagementProtocol.TYPE_PONG:\n return new ManagementPongHeader(version);\n default:\n throw ProtocolLogger.ROOT_LOGGER.invalidType(\"0x\" + Integer.toHexString(type));\n }\n }",
"public synchronized void stop() {\r\n\r\n if (m_thread != null) {\r\n long timeBeforeShutdownWasCalled = System.currentTimeMillis();\r\n JLANServer.shutdownServer(new String[] {});\r\n while (m_thread.isAlive()\r\n && ((System.currentTimeMillis() - timeBeforeShutdownWasCalled) < MAX_SHUTDOWN_WAIT_MILLIS)) {\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException e) {\r\n // ignore\r\n }\r\n }\r\n }\r\n\r\n }",
"public final void setColorPreferred(boolean preferColor) {\n if (this.preferColor.compareAndSet(!preferColor, preferColor) && isRunning()) {\n stop();\n try {\n start();\n } catch (Exception e) {\n logger.error(\"Unexplained exception restarting; we had been running already!\", e);\n }\n }\n }",
"public void setRegistrationConfig(RegistrationConfig registrationConfig) {\n this.registrationConfig = registrationConfig;\n\n if (registrationConfig.getDefaultConfig()!=null) {\n for (String key : registrationConfig.getDefaultConfig().keySet()) {\n dynamicConfig.put(key, registrationConfig.getDefaultConfig().get(key));\n }\n }\n }",
"public EventBus emitAsync(Enum<?> event, Object... args) {\n return _emitWithOnceBus(eventContextAsync(event, args));\n }",
"public static PersistenceStrategy<?, ?, ?> getInstance(\n\t\t\tCacheMappingType cacheMapping,\n\t\t\tEmbeddedCacheManager externalCacheManager,\n\t\t\tURL configurationUrl,\n\t\t\tJtaPlatform jtaPlatform,\n\t\t\tSet<EntityKeyMetadata> entityTypes,\n\t\t\tSet<AssociationKeyMetadata> associationTypes,\n\t\t\tSet<IdSourceKeyMetadata> idSourceTypes ) {\n\n\t\tif ( cacheMapping == CacheMappingType.CACHE_PER_KIND ) {\n\t\t\treturn getPerKindStrategy(\n\t\t\t\t\texternalCacheManager,\n\t\t\t\t\tconfigurationUrl,\n\t\t\t\t\tjtaPlatform\n\t\t\t);\n\t\t}\n\t\telse {\n\t\t\treturn getPerTableStrategy(\n\t\t\t\t\texternalCacheManager,\n\t\t\t\t\tconfigurationUrl,\n\t\t\t\t\tjtaPlatform,\n\t\t\t\t\tentityTypes,\n\t\t\t\t\tassociationTypes,\n\t\t\t\t\tidSourceTypes\n\t\t\t);\n\t\t}\n\t}",
"private static Bitmap crop(Bitmap srcBmp, View canvasView, int downsampling) {\n float scale = 1f / downsampling;\n return Bitmap.createBitmap(\n srcBmp,\n (int) Math.floor((ViewCompat.getX(canvasView)) * scale),\n (int) Math.floor((ViewCompat.getY(canvasView)) * scale),\n (int) Math.floor((canvasView.getWidth()) * scale),\n (int) Math.floor((canvasView.getHeight()) * scale)\n );\n }",
"public static Bic valueOf(final String bic) throws BicFormatException,\n UnsupportedCountryException {\n BicUtil.validate(bic);\n return new Bic(bic);\n }",
"public static SimpleMatrix wrap( Matrix internalMat ) {\n SimpleMatrix ret = new SimpleMatrix();\n ret.setMatrix(internalMat);\n return ret;\n }"
] |
Take four bytes from the specified position in the specified
block and convert them into a 32-bit int, using the big-endian
convention.
@param bytes The data to read from.
@param offset The position to start reading the 4-byte int from.
@return The 32-bit integer represented by the four bytes. | [
"public static int convertBytesToInt(byte[] bytes, int offset)\n {\n return (BITWISE_BYTE_TO_INT & bytes[offset + 3])\n | ((BITWISE_BYTE_TO_INT & bytes[offset + 2]) << 8)\n | ((BITWISE_BYTE_TO_INT & bytes[offset + 1]) << 16)\n | ((BITWISE_BYTE_TO_INT & bytes[offset]) << 24);\n }"
] | [
"public RelatedTagsList getRelated(String tag) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_RELATED);\n\n parameters.put(\"tag\", tag);\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 Element tagsElement = response.getPayload();\n\n RelatedTagsList tags = new RelatedTagsList();\n tags.setSource(tagsElement.getAttribute(\"source\"));\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag t = new Tag();\n t.setValue(XMLUtilities.getValue(tagElement));\n tags.add(t);\n }\n return tags;\n }",
"public DomainList getCollectionDomains(Date date, String collectionId, int perPage, int page) throws FlickrException {\n return getDomains(METHOD_GET_COLLECTION_DOMAINS, \"collection_id\", collectionId, date, perPage, page);\n }",
"public Integer getNodesPartitionIdForKey(int nodeId, final byte[] key) {\n // this is all the partitions the key replicates to.\n List<Integer> partitionIds = getReplicatingPartitionList(key);\n for(Integer partitionId: partitionIds) {\n // check which of the replicating partitions belongs to the node in\n // question\n if(getNodeIdForPartitionId(partitionId) == nodeId) {\n return partitionId;\n }\n }\n return null;\n }",
"public static spilloverpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tspilloverpolicy_lbvserver_binding obj = new spilloverpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\tspilloverpolicy_lbvserver_binding response[] = (spilloverpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"@Override\n public void sendResponse(StoreStats performanceStats,\n boolean isFromLocalZone,\n long startTimeInMs) throws Exception {\n\n /*\n * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage.\n * However when writing to the outputStream we only send the multiPart object and not the entire\n * mimeMessage. This is intentional.\n *\n * In the earlier version of this code we used to create a multiPart object and just send that multiPart\n * across the wire.\n *\n * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates\n * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated\n * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the\n * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders()\n * on the body part. It's this updateHeaders call that transfers the content type from the\n * DataHandler to the part's MIME Content-Type header.\n *\n * To make sure that the Content-Type headers are being updated (without changing too much code), we decided\n * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart.\n * This is to make sure multiPart's headers are updated accurately.\n */\n\n MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));\n MimeMultipart multiPart = new MimeMultipart();\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n String base64Key = RestUtils.encodeVoldemortKey(key.get());\n String contentLocationKey = \"/\" + this.storeName + \"/\" + base64Key;\n\n for(Versioned<byte[]> versionedValue: versionedValues) {\n\n byte[] responseValue = versionedValue.getValue();\n\n VectorClock vectorClock = (VectorClock) versionedValue.getVersion();\n String eTag = RestUtils.getSerializedVectorClock(vectorClock);\n numVectorClockEntries += vectorClock.getVersionMap().size();\n\n // Create the individual body part for each versioned value of the\n // requested key\n MimeBodyPart body = new MimeBodyPart();\n try {\n // Add the right headers\n body.addHeader(CONTENT_TYPE, \"application/octet-stream\");\n body.addHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n body.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag);\n body.setContent(responseValue, \"application/octet-stream\");\n body.addHeader(RestMessageHeaders.CONTENT_LENGTH,\n Integer.toString(responseValue.length));\n\n multiPart.addBodyPart(body);\n } catch(MessagingException me) {\n logger.error(\"Exception while constructing body part\", me);\n outputStream.close();\n throw me;\n }\n\n }\n message.setContent(multiPart);\n message.saveChanges();\n try {\n multiPart.writeTo(outputStream);\n } catch(Exception e) {\n logger.error(\"Exception while writing multipart to output stream\", e);\n outputStream.close();\n throw e;\n }\n ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();\n responseContent.writeBytes(outputStream.toByteArray());\n\n // Create the Response object\n HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);\n\n // Set the right headers\n response.setHeader(CONTENT_TYPE, \"multipart/binary\");\n response.setHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n response.setHeader(CONTENT_LOCATION, contentLocationKey);\n\n // Copy the data into the payload\n response.setContent(responseContent);\n response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());\n\n // Write the response to the Netty Channel\n if(logger.isDebugEnabled()) {\n String keyStr = RestUtils.getKeyHexString(this.key);\n debugLog(\"GET\",\n this.storeName,\n keyStr,\n startTimeInMs,\n System.currentTimeMillis(),\n numVectorClockEntries);\n }\n this.messageEvent.getChannel().write(response);\n\n if(performanceStats != null && isFromLocalZone) {\n recordStats(performanceStats, startTimeInMs, Tracked.GET);\n }\n\n outputStream.close();\n\n }",
"public SerialMessage setValueMessage(int level) {\r\n\t\tlogger.debug(\"Creating new message for application command BASIC_SET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.Set);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t3, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) BASIC_SET,\r\n\t\t\t\t\t\t\t\t(byte) level\r\n\t\t\t\t\t\t\t\t};\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}",
"public Collection<Contact> getListRecentlyUploaded(Date lastUpload, String filter) throws FlickrException {\r\n List<Contact> contacts = new ArrayList<Contact>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST_RECENTLY_UPLOADED);\r\n\r\n if (lastUpload != null) {\r\n parameters.put(\"date_lastupload\", String.valueOf(lastUpload.getTime() / 1000L));\r\n }\r\n if (filter != null) {\r\n parameters.put(\"filter\", filter);\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\r\n Element contactsElement = response.getPayload();\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 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 }",
"@SuppressWarnings(\"unchecked\") public static TimeUnit getInstance(String units, Locale locale) throws MPXJException\n {\n Map<String, Integer> map = LocaleData.getMap(locale, LocaleData.TIME_UNITS_MAP);\n Integer result = map.get(units.toLowerCase());\n if (result == null)\n {\n throw new MPXJException(MPXJException.INVALID_TIME_UNIT + \" \" + units);\n }\n return (TimeUnit.getInstance(result.intValue()));\n }",
"public static CmsShell getTopShell() {\n\n ArrayList<CmsShell> shells = SHELL_STACK.get();\n if (shells.isEmpty()) {\n return null;\n }\n return shells.get(shells.size() - 1);\n\n }"
] |
return the ctc costs and gradients, given the probabilities and labels | [
"public static int cudnnCTCLoss(\n cudnnHandle handle, \n cudnnTensorDescriptor probsDesc, /** Tensor descriptor for probabilities, the dimensions are T,N,A (T is the timing steps, N is the\n mini batch size, A is the alphabet size) */\n Pointer probs, /** probabilities after softmax, in GPU memory */\n int[] labels, /** labels, in CPU memory */\n int[] labelLengths, /** the length of each label, in CPU memory */\n int[] inputLengths, /** the lengths of timing steps in each batch, in CPU memory */\n Pointer costs, /** the returned costs of CTC, in GPU memory */\n cudnnTensorDescriptor gradientsDesc, /** Tensor descriptor for gradients, the dimensions are T,N,A */\n Pointer gradients, /** the returned CTC gradients, in GPU memory, to compute costs only, set it to NULL */\n int algo, /** algorithm selected, supported now 0 and 1 */\n cudnnCTCLossDescriptor ctcLossDesc, \n Pointer workspace, /** pointer to the workspace, in GPU memory */\n long workSpaceSizeInBytes)/** the workspace size needed */\n {\n return checkResult(cudnnCTCLossNative(handle, probsDesc, probs, labels, labelLengths, inputLengths, costs, gradientsDesc, gradients, algo, ctcLossDesc, workspace, workSpaceSizeInBytes));\n }"
] | [
"public static final String printDateTime(Date value)\n {\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }",
"public Object getBeliefValue(String agent_name, final String belief_name,\n Connector connector) {\n\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Integer>() {\n\n public IFuture<Integer> execute(IInternalAccess ia) {\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n belief_value = bia.getBeliefbase()\n .getBelief(belief_name).getFact();\n return null;\n }\n }).get(new ThreadSuspendable());\n return belief_value;\n }",
"public Iterable<BoxRetentionPolicyAssignment.Info> getAllAssignments(int limit, String ... fields) {\r\n return this.getAssignments(null, limit, fields);\r\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 }",
"public void getElevationForLocations(LocationElevationRequest req, ElevationServiceCallback callback) {\n \n this.callback = callback;\n \n JSObject doc = (JSObject) getJSObject().eval(\"document\");\n doc.setMember(getVariableName(), this);\n \n StringBuilder r = new StringBuilder(getVariableName())\n .append(\".\")\n .append(\"getElevationForLocations(\")\n .append(req.getVariableName())\n .append(\", \")\n .append(\"function(results, status) {alert('rec:'+status);\\ndocument.\")\n .append(getVariableName())\n .append(\".processResponse(results, status);});\");\n \n LOG.trace(\"ElevationService direct call: \" + r.toString());\n \n getJSObject().eval(r.toString());\n \n }",
"public void processSplitData(Task task, List<TimephasedWork> timephasedComplete, List<TimephasedWork> timephasedPlanned)\n {\n Date splitsComplete = null;\n TimephasedWork lastComplete = null;\n TimephasedWork firstPlanned = null;\n if (!timephasedComplete.isEmpty())\n {\n lastComplete = timephasedComplete.get(timephasedComplete.size() - 1);\n splitsComplete = lastComplete.getFinish();\n }\n\n if (!timephasedPlanned.isEmpty())\n {\n firstPlanned = timephasedPlanned.get(0);\n }\n\n LinkedList<DateRange> splits = new LinkedList<DateRange>();\n TimephasedWork lastAssignment = null;\n DateRange lastRange = null;\n for (TimephasedWork assignment : timephasedComplete)\n {\n if (lastAssignment != null && lastRange != null && lastAssignment.getTotalAmount().getDuration() != 0 && assignment.getTotalAmount().getDuration() != 0)\n {\n splits.removeLast();\n lastRange = new DateRange(lastRange.getStart(), assignment.getFinish());\n }\n else\n {\n lastRange = new DateRange(assignment.getStart(), assignment.getFinish());\n }\n splits.add(lastRange);\n lastAssignment = assignment;\n }\n\n //\n // We may not have a split, we may just have a partially\n // complete split.\n //\n Date splitStart = null;\n if (lastComplete != null && firstPlanned != null && lastComplete.getTotalAmount().getDuration() != 0 && firstPlanned.getTotalAmount().getDuration() != 0)\n {\n lastRange = splits.removeLast();\n splitStart = lastRange.getStart();\n }\n\n lastAssignment = null;\n lastRange = null;\n for (TimephasedWork assignment : timephasedPlanned)\n {\n if (splitStart == null)\n {\n if (lastAssignment != null && lastRange != null && lastAssignment.getTotalAmount().getDuration() != 0 && assignment.getTotalAmount().getDuration() != 0)\n {\n splits.removeLast();\n lastRange = new DateRange(lastRange.getStart(), assignment.getFinish());\n }\n else\n {\n lastRange = new DateRange(assignment.getStart(), assignment.getFinish());\n }\n }\n else\n {\n lastRange = new DateRange(splitStart, assignment.getFinish());\n }\n splits.add(lastRange);\n splitStart = null;\n lastAssignment = assignment;\n }\n\n //\n // We must have a minimum of 3 entries for this to be a valid split task\n //\n if (splits.size() > 2)\n {\n task.getSplits().addAll(splits);\n task.setSplitCompleteDuration(splitsComplete);\n }\n else\n {\n task.setSplits(null);\n task.setSplitCompleteDuration(null);\n }\n }",
"public static void checkRequired(OptionSet options, String opt) throws VoldemortException {\n List<String> opts = Lists.newArrayList();\n opts.add(opt);\n checkRequired(options, opts);\n }",
"public UriComponentsBuilder queryParams(MultiValueMap<String, String> params) {\n\t\tAssert.notNull(params, \"'params' must not be null\");\n\t\tthis.queryParams.putAll(params);\n\t\treturn this;\n\t}",
"public ConfigBuilder withMasterName(final String masterName) {\n if (masterName == null || \"\".equals(masterName)) {\n throw new IllegalArgumentException(\"masterName is null or empty: \" + masterName);\n }\n this.masterName = masterName;\n return this;\n }"
] |
Use this API to fetch servicegroupbindings resource of given name . | [
"public static servicegroupbindings get(nitro_service service, String servicegroupname) throws Exception{\n\t\tservicegroupbindings obj = new servicegroupbindings();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tservicegroupbindings response = (servicegroupbindings) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"public Swagger read(Class<?> cls) {\n SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);\n if (swaggerDefinition != null) {\n readSwaggerConfig(cls, swaggerDefinition);\n }\n\n return read(cls, \"\", null, false, new String[0], new String[0], new LinkedHashMap<>(), new ArrayList<>(), new HashSet<>());\n }",
"public void sortIndices(SortCoupledArray_F64 sorter ) {\n if( sorter == null )\n sorter = new SortCoupledArray_F64();\n\n sorter.quick(col_idx,numCols+1,nz_rows,nz_values);\n indicesSorted = true;\n }",
"public void setNearClippingDistance(float near) {\n if(leftCamera instanceof GVRCameraClippingDistanceInterface &&\n centerCamera instanceof GVRCameraClippingDistanceInterface &&\n rightCamera instanceof GVRCameraClippingDistanceInterface) {\n ((GVRCameraClippingDistanceInterface)leftCamera).setNearClippingDistance(near);\n centerCamera.setNearClippingDistance(near);\n ((GVRCameraClippingDistanceInterface)rightCamera).setNearClippingDistance(near);\n }\n }",
"static void setSingleParam(String key, String value, DbConn cnx)\n {\n QueryResult r = cnx.runUpdate(\"globalprm_update_value_by_key\", value, key);\n if (r.nbUpdated == 0)\n {\n cnx.runUpdate(\"globalprm_insert\", key, value);\n }\n cnx.commit();\n }",
"public static StringTemplateGroup readStringTemplateGroup(InputStream stream) {\n\n try {\n return new StringTemplateGroup(\n new InputStreamReader(stream, \"UTF-8\"),\n DefaultTemplateLexer.class,\n new StringTemplateErrorListener() {\n\n @SuppressWarnings(\"synthetic-access\")\n public void error(String arg0, Throwable arg1) {\n\n LOG.error(arg0 + \": \" + arg1.getMessage(), arg1);\n }\n\n @SuppressWarnings(\"synthetic-access\")\n public void warning(String arg0) {\n\n LOG.warn(arg0);\n\n }\n });\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n return new StringTemplateGroup(\"dummy\");\n }\n }",
"public void racRent() {\n\t\tpos = pos - 1;\n\t\tString userName = CarSearch.getLastSearchParams()[0];\n\t\tString pickupDate = CarSearch.getLastSearchParams()[1];\n\t\tString returnDate = CarSearch.getLastSearchParams()[2];\n\t\tthis.searcher.search(userName, pickupDate, returnDate);\n\t\tif (searcher!=null && searcher.getCars()!= null && pos < searcher.getCars().size() && searcher.getCars().get(pos) != null) {\n\t\t\tRESStatusType resStatus = reserver.reserveCar(searcher.getCustomer()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCars().get(pos)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, pickupDate\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, returnDate);\n\t\t\tConfirmationType confirm = reserver.getConfirmation(resStatus\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCustomer()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCars().get(pos)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, pickupDate\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, returnDate);\n\n\t\t\tRESCarType car = confirm.getCar();\n\t\t\tCustomerDetailsType customer = confirm.getCustomer();\n\t\t\t\n\t\t\tSystem.out.println(MessageFormat.format(CONFIRMATION\n\t\t\t\t\t, confirm.getDescription()\n\t\t\t\t\t, confirm.getReservationId()\n\t\t\t\t\t, customer.getName()\n\t\t\t\t\t, customer.getEmail()\n\t\t\t\t\t, customer.getCity()\n\t\t\t\t\t, customer.getStatus()\n\t\t\t\t\t, car.getBrand()\n\t\t\t\t\t, car.getDesignModel()\n\t\t\t\t\t, confirm.getFromDate()\n\t\t\t\t\t, confirm.getToDate()\n\t\t\t\t\t, padl(car.getRateDay(), 10)\n\t\t\t\t\t, padl(car.getRateWeekend(), 10)\n\t\t\t\t\t, padl(confirm.getCreditPoints().toString(), 7)));\n\t\t} else {\n\t\t\tSystem.out.println(\"Invalid selection: \" + (pos+1)); //$NON-NLS-1$\n\t\t}\n\t}",
"public static Long getSize(final File file){\n if ( file!=null && file.exists() ){\n return file.length();\n }\n return null;\n }",
"public <TYPE> TYPE get(String key, Class<TYPE> type) {\n\t\treturn cache.get(key, type);\n\t}",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<InternationalFixedDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<InternationalFixedDate>) super.localDateTime(temporal);\n }"
] |
Iterates through this file line by line, splitting each line using
the given regex separator. For each line, the given closure is called with
a single parameter being the list of strings computed by splitting the line
around matches of the given regular expression.
Finally the resources used for processing the file are closed.
@param self a File
@param regex the delimiting regular expression
@param closure a closure
@return the last value returned by the closure
@throws IOException if an IOException occurs.
@throws java.util.regex.PatternSyntaxException
if the regular expression's syntax is invalid
@see IOGroovyMethods#splitEachLine(java.io.Reader, java.lang.String, groovy.lang.Closure)
@since 1.5.5 | [
"public static <T> T splitEachLine(File self, String regex, @ClosureParams(value=SimpleType.class, options=\"java.lang.String[]\") Closure<T> closure) throws IOException {\n return IOGroovyMethods.splitEachLine(newReader(self), regex, closure);\n }"
] | [
"Object readResolve() throws ObjectStreamException {\n Bean<?> bean = Container.instance(contextId).services().get(ContextualStore.class).<Bean<Object>, Object>getContextual(beanId);\n if (bean == null) {\n throw BeanLogger.LOG.proxyDeserializationFailure(beanId);\n }\n return Container.instance(contextId).deploymentManager().getClientProxyProvider().getClientProxy(bean);\n }",
"public void setHeader(String header, String value) {\n StringValidator.throwIfEmptyOrNull(\"header\", header);\n StringValidator.throwIfEmptyOrNull(\"value\", value);\n\n if (headers == null) {\n headers = new HashMap<String, String>();\n }\n\n headers.put(header, value);\n }",
"public static <K, V> HashMap<K, V> newEmptyHashMap(Iterable<?> iterable) {\n if(iterable instanceof Collection<?>)\n return Maps.newHashMapWithExpectedSize(((Collection<?>) iterable).size());\n return Maps.newHashMap();\n }",
"public String getName()\n {\n GVRSceneObject owner = getOwnerObject();\n String name = \"\";\n\n if (owner != null)\n {\n name = owner.getName();\n if (name == null)\n return \"\";\n }\n return name;\n }",
"public static String[] randomResourceNames(String prefix, int maxLen, int count) {\n String[] names = new String[count];\n ResourceNamer resourceNamer = SdkContext.getResourceNamerFactory().createResourceNamer(\"\");\n for (int i = 0; i < count; i++) {\n names[i] = resourceNamer.randomName(prefix, maxLen);\n }\n return names;\n }",
"public AreaOfInterest copy() {\n AreaOfInterest aoi = new AreaOfInterest();\n aoi.display = this.display;\n aoi.area = this.area;\n aoi.polygon = this.polygon;\n aoi.style = this.style;\n aoi.renderAsSvg = this.renderAsSvg;\n return aoi;\n }",
"public static Message create( String text, Object data, ProcessingUnit owner )\n {\n return new SimpleMessage( text, data, owner);\n }",
"public CollectionRequest<Task> subtasks(String task) {\n \n String path = String.format(\"/tasks/%s/subtasks\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"private void init()\r\n {\r\n jdbcProperties = new Properties();\r\n dbcpProperties = new Properties();\r\n setFetchSize(0);\r\n this.setTestOnBorrow(true);\r\n this.setTestOnReturn(false);\r\n this.setTestWhileIdle(false);\r\n this.setLogAbandoned(false);\r\n this.setRemoveAbandoned(false);\r\n }"
] |
Get a store definition from the given list of store definitions
@param list A list of store definitions
@param name The name of the store
@return The store definition | [
"public static StoreDefinition getStoreDef(List<StoreDefinition> list, String name) {\n for(StoreDefinition def: list)\n if(def.getName().equals(name))\n return def;\n return null;\n }"
] | [
"private static void close(Closeable closeable) {\n\t\tif (closeable != null) {\n\t\t\ttry {\n\t\t\t\tcloseable.close();\n\t\t\t} catch (IOException ignored) {\n\t\t\t\tlogger.error(\"Failed to close output stream: \"\n\t\t\t\t\t\t+ ignored.getMessage());\n\t\t\t}\n\t\t}\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 }",
"public List<String> getArtifactVersions(final String gavc) {\n final DbArtifact artifact = getArtifact(gavc);\n return repositoryHandler.getArtifactVersions(artifact);\n }",
"private QueueCursor updateCursorForDBObject(JSONObject dbObject, QueueCursor cursor) {\n\n if (dbObject == null) return cursor;\n\n Iterator<String> keys = dbObject.keys();\n if (keys.hasNext()) {\n String key = keys.next();\n cursor.setLastId(key);\n try {\n cursor.setData(dbObject.getJSONArray(key));\n } catch (JSONException e) {\n cursor.setLastId(null);\n cursor.setData(null);\n }\n }\n\n return cursor;\n }",
"private static void writeCharSequence(CharSequence seq, CharBuf buffer) {\n if (seq.length() > 0) {\n buffer.addJsonEscapedString(seq.toString());\n } else {\n buffer.addChars(EMPTY_STRING_CHARS);\n }\n }",
"public int getIndexMin() {\n int indexMin = 0;\n double min = getEigenvalue(0).getMagnitude2();\n\n final int N = getNumberOfEigenvalues();\n for( int i = 1; i < N; i++ ) {\n double m = getEigenvalue(i).getMagnitude2();\n if( m < min ) {\n min = m;\n indexMin = i;\n }\n }\n\n return indexMin;\n }",
"public TagSetModel getOrCreate(GraphRewrite event, Set<String> tags)\n {\n Map<Set<String>, Vertex> cache = getCache(event);\n Vertex vertex = cache.get(tags);\n if (vertex == null)\n {\n TagSetModel model = create();\n model.setTags(tags);\n cache.put(tags, model.getElement());\n return model;\n }\n else\n {\n return frame(vertex);\n }\n }",
"public static byte[] synchronizeSlaveHostController(ModelNode operation, final PathAddress address, HostFileRepository fileRepository, ContentRepository contentRepository, boolean backup, byte[] oldHash) {\n ModelNode operationContentItem = operation.get(DeploymentAttributes.CONTENT_RESOURCE_ALL.getName()).get(0);\n byte[] newHash = operationContentItem.require(CONTENT_HASH.getName()).asBytes();\n if (needRemoteContent(fileRepository, contentRepository, backup, oldHash)) { // backup DC needs to pull the content\n fileRepository.getDeploymentFiles(ModelContentReference.fromModelAddress(address, newHash));\n }\n return newHash;\n }",
"public static sslfipskey[] get(nitro_service service, String fipskeyname[]) throws Exception{\n\t\tif (fipskeyname !=null && fipskeyname.length>0) {\n\t\t\tsslfipskey response[] = new sslfipskey[fipskeyname.length];\n\t\t\tsslfipskey obj[] = new sslfipskey[fipskeyname.length];\n\t\t\tfor (int i=0;i<fipskeyname.length;i++) {\n\t\t\t\tobj[i] = new sslfipskey();\n\t\t\t\tobj[i].set_fipskeyname(fipskeyname[i]);\n\t\t\t\tresponse[i] = (sslfipskey) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}"
] |
Replace a photo from a File.
@param file
@param flickrId
@param async
@return photoId or ticketId
@throws FlickrException | [
"@Override\r\n public String replace(File file, String flickrId, boolean async) throws FlickrException {\r\n Payload payload = new Payload(file, flickrId);\r\n return sendReplaceRequest(async, payload);\r\n }"
] | [
"public List<WebSocketConnection> get(String key) {\n final List<WebSocketConnection> retList = new ArrayList<>();\n accept(key, C.F.addTo(retList));\n return retList;\n }",
"@Override\n public String logFile() {\n if(logFile == null) {\n logFile = Config.getTmpDir()+Config.getPathSeparator()+\"aesh.log\";\n }\n return logFile;\n }",
"protected int getDonorId(StoreRoutingPlan currentSRP,\n StoreRoutingPlan finalSRP,\n int stealerZoneId,\n int stealerNodeId,\n int stealerPartitionId) {\n int stealerZoneNAry = finalSRP.getZoneNaryForNodesPartition(stealerZoneId,\n stealerNodeId,\n stealerPartitionId);\n\n int donorZoneId;\n if(currentSRP.zoneNAryExists(stealerZoneId, stealerZoneNAry, stealerPartitionId)) {\n // Steal from local n-ary (since one exists).\n donorZoneId = stealerZoneId;\n } else {\n // Steal from zone that hosts primary partition Id.\n int currentMasterNodeId = currentSRP.getNodeIdForPartitionId(stealerPartitionId);\n donorZoneId = currentCluster.getNodeById(currentMasterNodeId).getZoneId();\n }\n\n return currentSRP.getNodeIdForZoneNary(donorZoneId, stealerZoneNAry, stealerPartitionId);\n\n }",
"private void updateSession(Session newSession) {\n if (this.currentSession == null) {\n this.currentSession = newSession;\n } else {\n synchronized (this.currentSession) {\n this.currentSession = newSession;\n }\n }\n }",
"@Deprecated\n public int getEntityTypeId(@NotNull final String entityType, final boolean allowCreate) {\n return getEntityTypeId(txnProvider, entityType, allowCreate);\n }",
"private void populateExpandedExceptions()\n {\n if (!m_exceptions.isEmpty() && m_expandedExceptions.isEmpty())\n {\n for (ProjectCalendarException exception : m_exceptions)\n {\n RecurringData recurring = exception.getRecurring();\n if (recurring == null)\n {\n m_expandedExceptions.add(exception);\n }\n else\n {\n for (Date date : recurring.getDates())\n {\n Date startDate = DateHelper.getDayStartDate(date);\n Date endDate = DateHelper.getDayEndDate(date);\n ProjectCalendarException newException = new ProjectCalendarException(startDate, endDate);\n int rangeCount = exception.getRangeCount();\n for (int rangeIndex = 0; rangeIndex < rangeCount; rangeIndex++)\n {\n newException.addRange(exception.getRange(rangeIndex));\n }\n m_expandedExceptions.add(newException);\n }\n }\n }\n Collections.sort(m_expandedExceptions);\n }\n }",
"private <T> T populateBean(final T resultBean, final String[] nameMapping) {\n\t\t\n\t\t// map each column to its associated field on the bean\n\t\tfor( int i = 0; i < nameMapping.length; i++ ) {\n\t\t\t\n\t\t\tfinal Object fieldValue = processedColumns.get(i);\n\t\t\t\n\t\t\t// don't call a set-method in the bean if there is no name mapping for the column or no result to store\n\t\t\tif( nameMapping[i] == null || fieldValue == null ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\t// invoke the setter on the bean\n\t\t\tMethod setMethod = cache.getSetMethod(resultBean, nameMapping[i], fieldValue.getClass());\n\t\t\tinvokeSetter(resultBean, setMethod, fieldValue);\n\t\t\t\n\t\t}\n\t\t\n\t\treturn resultBean;\n\t}",
"final void roll(final long timeForSuffix) {\n\n final File backupFile = this.prepareBackupFile(timeForSuffix);\n\n // close filename\n this.getAppender().closeFile();\n\n // rename filename on disk to filename+suffix(+number)\n this.doFileRoll(this.getAppender().getIoFile(), backupFile);\n\n // setup new file 'filename'\n this.getAppender().openFile();\n\n this.fireFileRollEvent(new FileRollEvent(this, backupFile));\n }",
"public static String toJson(Calendar cal) {\n if (cal == null) {\n return NULL_VALUE;\n }\n\n CharBuf buffer = CharBuf.create(26);\n writeDate(cal.getTime(), buffer);\n\n return buffer.toString();\n }"
] |
Will auto format the given string to provide support for pickadate.js formats. | [
"public static String format(String format) {\n\n if (format == null) {\n format = DEFAULT_FORMAT;\n } else {\n if (format.contains(\"M\")) {\n format = format.replace(\"M\", \"m\");\n }\n\n if (format.contains(\"Y\")) {\n format = format.replace(\"Y\", \"y\");\n }\n\n if (format.contains(\"D\")) {\n format = format.replace(\"D\", \"d\");\n }\n }\n return format;\n }"
] | [
"public <V> V attachIfAbsent(final AttachmentKey<V> key, final V value) {\n assert key != null;\n return key.cast(contextAttachments.putIfAbsent(key, value));\n }",
"public static java.util.Date newDateTime() {\n return new java.util.Date((System.currentTimeMillis() / SECOND_MILLIS) * SECOND_MILLIS);\n }",
"public DbArtifact getArtifact(final String gavc) {\n final DbArtifact artifact = repositoryHandler.getArtifact(gavc);\n\n if(artifact == null){\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Artifact \" + gavc + \" does not exist.\").build());\n }\n\n return artifact;\n }",
"protected String addPostRunDependent(TaskGroup.HasTaskGroup dependent) {\n Objects.requireNonNull(dependent);\n this.taskGroup.addPostRunDependentTaskGroup(dependent.taskGroup());\n return dependent.taskGroup().key();\n }",
"public void setProjectionMatrix(float x1, float y1, float z1, float w1,\n float x2, float y2, float z2, float w2, float x3, float y3,\n float z3, float w3, float x4, float y4, float z4, float w4) {\n NativeCustomCamera.setProjectionMatrix(getNative(), x1, y1, z1, w1, x2,\n y2, z2, w2, x3, y3, z3, w3, x4, y4, z4, w4);\n }",
"public static void printResults(Counter<String> entityTP, Counter<String> entityFP,\r\n Counter<String> entityFN) {\r\n Set<String> entities = new TreeSet<String>();\r\n entities.addAll(entityTP.keySet());\r\n entities.addAll(entityFP.keySet());\r\n entities.addAll(entityFN.keySet());\r\n boolean printedHeader = false;\r\n for (String entity : entities) {\r\n double tp = entityTP.getCount(entity);\r\n double fp = entityFP.getCount(entity);\r\n double fn = entityFN.getCount(entity);\r\n printedHeader = printPRLine(entity, tp, fp, fn, printedHeader);\r\n }\r\n double tp = entityTP.totalCount();\r\n double fp = entityFP.totalCount();\r\n double fn = entityFN.totalCount();\r\n printedHeader = printPRLine(\"Totals\", tp, fp, fn, printedHeader);\r\n }",
"public void revertWorkingCopy() throws IOException, InterruptedException {\n build.getWorkspace()\n .act(new RevertWorkingCopyCallable(getLocation(), getSvnAuthenticationProvider(build), buildListener));\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 <T extends Widget & Checkable> void clearChecks() {\n List<T> children = getCheckableChildren();\n for (T c : children) {\n c.setChecked(false);\n }\n }"
] |
Get the real Object
@param objectOrProxy
@return Object | [
"public final Object getRealObject(Object objectOrProxy)\r\n {\r\n if(isNormalOjbProxy(objectOrProxy))\r\n {\r\n String msg;\r\n\r\n try\r\n {\r\n return getIndirectionHandler(objectOrProxy).getRealSubject();\r\n }\r\n catch(ClassCastException e)\r\n {\r\n // shouldn't happen but still ...\r\n msg = \"The InvocationHandler for the provided Proxy was not an instance of \" + IndirectionHandler.class.getName();\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(IllegalArgumentException e)\r\n {\r\n msg = \"Could not retrieve real object for given Proxy: \" + objectOrProxy;\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for given Proxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else if(isVirtualOjbProxy(objectOrProxy))\r\n {\r\n try\r\n {\r\n return ((VirtualProxy) objectOrProxy).getRealSubject();\r\n }\r\n catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for VirtualProxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else\r\n {\r\n return objectOrProxy;\r\n }\r\n }"
] | [
"public static <K> Map<K, Integer> rankMapOnIntegerValue(Map<K, Integer> inputMap) {\n Map<K, Integer> newMap = new TreeMap<K, Integer>(new IntegerValueComparator(inputMap));\n newMap.putAll(inputMap);\n\n Map<K, Integer> linkedMap = new LinkedHashMap<K, Integer>(newMap);\n return linkedMap;\n }",
"public String toUriString(final java.net.URI uri) {\n return this.toUriString(URI.createURI(uri.normalize().toString()));\n }",
"public static HttpConnection createPost(URI uri, String body, String contentType) {\n HttpConnection connection = Http.POST(uri, \"application/json\");\n if(body != null) {\n setEntity(connection, body, contentType);\n }\n return connection;\n }",
"public static void divideElementsCol(final int blockLength ,\n final DSubmatrixD1 Y , final int col , final double val ) {\n final int width = Math.min(blockLength,Y.col1-Y.col0);\n\n final double dataY[] = Y.original.data;\n\n for( int i = Y.row0; i < Y.row1; i += blockLength ) {\n int height = Math.min( blockLength , Y.row1 - i );\n\n int index = i*Y.original.numCols + height*Y.col0 + col;\n\n if( i == Y.row0 ) {\n index += width*(col+1);\n\n for( int k = col+1; k < height; k++ , index += width ) {\n dataY[index] /= val;\n }\n } else {\n int endIndex = index + width*height;\n //for( int k = 0; k < height; k++\n for( ; index != endIndex; index += width ) {\n dataY[index] /= val;\n }\n }\n }\n }",
"private List<org.jfrog.hudson.pipeline.types.File> getBuildFilesList(Stream<? extends BaseBuildFileBean> buildFilesStream) {\n return buildFilesStream\n .filter(buildFile -> StringUtils.isNotBlank(buildFile.getLocalPath()))\n .filter(buildFile -> StringUtils.isNotBlank(buildFile.getRemotePath()))\n .map(org.jfrog.hudson.pipeline.types.File::new)\n .distinct()\n .collect(Collectors.toList());\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 SimpleFeatureType createGridFeatureType(\n @Nonnull final MapfishMapContext mapContext,\n @Nonnull final Class<? extends Geometry> geomClass) {\n final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();\n CoordinateReferenceSystem projection = mapContext.getBounds().getProjection();\n typeBuilder.add(Constants.Style.Grid.ATT_GEOM, geomClass, projection);\n typeBuilder.setName(Constants.Style.Grid.NAME_LINES);\n\n return typeBuilder.buildFeatureType();\n }",
"public SqlStatement getPreparedDeleteStatement(Query query, ClassDescriptor cld)\r\n {\r\n return new SqlDeleteByQuery(m_platform, cld, query, logger);\r\n }",
"public void removePropertyChangeListener (String propertyName, java.beans.PropertyChangeListener listener)\r\n {\r\n this.propertyChangeDelegate.removePropertyChangeListener(propertyName, listener);\r\n }"
] |
This is a convenience method used to add a default set of calendar
hours to a calendar.
@param day Day for which to add default hours for | [
"public void addDefaultCalendarHours(Day day)\n {\n ProjectCalendarHours hours = addCalendarHours(day);\n\n if (day != Day.SATURDAY && day != Day.SUNDAY)\n {\n hours.addRange(DEFAULT_WORKING_MORNING);\n hours.addRange(DEFAULT_WORKING_AFTERNOON);\n }\n }"
] | [
"public static UndeployDescription of(final DeploymentDescription deploymentDescription) {\n Assert.checkNotNullParam(\"deploymentDescription\", deploymentDescription);\n return of(deploymentDescription.getName()).addServerGroups(deploymentDescription.getServerGroups());\n }",
"public static Document removeTags(Document dom, String tagName) {\n NodeList list;\n try {\n list = XPathHelper.evaluateXpathExpression(dom,\n \"//\" + tagName.toUpperCase());\n\n while (list.getLength() > 0) {\n Node sc = list.item(0);\n\n if (sc != null) {\n sc.getParentNode().removeChild(sc);\n }\n\n list = XPathHelper.evaluateXpathExpression(dom,\n \"//\" + tagName.toUpperCase());\n }\n } catch (XPathExpressionException e) {\n LOGGER.error(\"Error while removing tag \" + tagName, e);\n }\n\n return dom;\n\n }",
"@Deprecated\n public static PersistentResourceXMLBuilder decorator(final String elementName) {\n return new PersistentResourceXMLBuilder(PathElement.pathElement(elementName), null).setDecoratorGroup(elementName);\n }",
"public synchronized boolean isComplete(int requestId, boolean remove) {\n if (!operations.containsKey(requestId))\n throw new VoldemortException(\"No operation with id \" + requestId + \" found\");\n\n if (operations.get(requestId).getStatus().isComplete()) {\n if (logger.isDebugEnabled())\n logger.debug(\"Operation complete \" + requestId);\n\n if (remove)\n operations.remove(requestId);\n\n return true;\n }\n\n return false;\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 }",
"private static boolean isWideningPrimitive(Class<?> argumentClass, Class<?> targetClass) {\n return WIDENING_TABLE.containsKey(argumentClass) && WIDENING_TABLE.get(argumentClass).contains(targetClass);\n }",
"@SuppressWarnings(\"unchecked\")\n protected static void visitSubreports(DynamicReport dr, Map _parameters) {\n for (DJGroup group : dr.getColumnsGroups()) {\n //Header Subreports\n for (Subreport subreport : group.getHeaderSubreports()) {\n if (subreport.getDynamicReport() != null) {\n visitSubreport(dr, subreport);\n visitSubreports(subreport.getDynamicReport(), _parameters);\n }\n }\n\n //Footer Subreports\n for (Subreport subreport : group.getFooterSubreports()) {\n if (subreport.getDynamicReport() != null) {\n visitSubreport(dr, subreport);\n visitSubreports(subreport.getDynamicReport(), _parameters);\n }\n }\n }\n\n }",
"public static base_responses delete(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 deleteresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new route6();\n\t\t\t\tdeleteresources[i].network = resources[i].network;\n\t\t\t\tdeleteresources[i].gateway = resources[i].gateway;\n\t\t\t\tdeleteresources[i].vlan = resources[i].vlan;\n\t\t\t\tdeleteresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public void rename(String newName) {\n URL url = FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject updateInfo = new JsonObject();\n updateInfo.add(\"name\", newName);\n\n request.setBody(updateInfo.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n response.getJSON();\n }"
] |
Sets up Log4J to write log messages to the console. Low-priority messages
are logged to stdout while high-priority messages go to stderr. | [
"private void initializeLogging() {\n\t\t// Since logging is static, make sure this is done only once even if\n\t\t// multiple clients are created (e.g., during tests)\n\t\tif (consoleAppender != null) {\n\t\t\treturn;\n\t\t}\n\n\t\tconsoleAppender = new ConsoleAppender();\n\t\tconsoleAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\tconsoleAppender.setThreshold(Level.INFO);\n\t\tLevelRangeFilter filter = new LevelRangeFilter();\n\t\tfilter.setLevelMin(Level.TRACE);\n\t\tfilter.setLevelMax(Level.INFO);\n\t\tconsoleAppender.addFilter(filter);\n\t\tconsoleAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(consoleAppender);\n\n\t\terrorAppender = new ConsoleAppender();\n\t\terrorAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\terrorAppender.setThreshold(Level.WARN);\n\t\terrorAppender.setTarget(ConsoleAppender.SYSTEM_ERR);\n\t\terrorAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(errorAppender);\n\t}"
] | [
"protected ServiceRegistration registerProxy(Object objectProxy, Class clazz) {\n Dictionary<String, Object> props = new Hashtable<String, Object>();\n ServiceRegistration registration;\n registration = context.registerService(clazz, objectProxy, props);\n\n return registration;\n }",
"public static responderparam get(nitro_service service) throws Exception{\n\t\tresponderparam obj = new responderparam();\n\t\tresponderparam[] response = (responderparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static base_response update(nitro_service client, clusterinstance resource) throws Exception {\n\t\tclusterinstance updateresource = new clusterinstance();\n\t\tupdateresource.clid = resource.clid;\n\t\tupdateresource.deadinterval = resource.deadinterval;\n\t\tupdateresource.hellointerval = resource.hellointerval;\n\t\tupdateresource.preemption = resource.preemption;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static void checkCreateUpload(CmsObject cms, CmsUgcConfiguration config, String name, long size)\n throws CmsUgcException {\n\n if (!config.getUploadParentFolder().isPresent()) {\n String message = Messages.get().container(Messages.ERR_NO_UPLOADS_ALLOWED_0).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errNoUploadAllowed, message);\n }\n\n if (config.getMaxUploadSize().isPresent()) {\n if (config.getMaxUploadSize().get().longValue() < size) {\n String message = Messages.get().container(Messages.ERR_UPLOAD_TOO_BIG_1, name).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errMaxUploadSizeExceeded, message);\n }\n }\n\n if (config.getValidExtensions().isPresent()) {\n List<String> validExtensions = config.getValidExtensions().get();\n boolean foundExtension = false;\n for (String extension : validExtensions) {\n if (name.toLowerCase().endsWith(extension.toLowerCase())) {\n foundExtension = true;\n break;\n }\n }\n if (!foundExtension) {\n String message = Messages.get().container(Messages.ERR_UPLOAD_FILE_EXTENSION_NOT_ALLOWED_1, name).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errInvalidExtension, message);\n }\n }\n }",
"public static String getTextContent(Document document, boolean individualTokens) {\n String textContent = null;\n if (individualTokens) {\n List<String> tokens = getTextTokens(document);\n textContent = StringUtils.join(tokens, \",\");\n } else {\n textContent =\n document.getDocumentElement().getTextContent().trim().replaceAll(\"\\\\s+\", \",\");\n }\n return textContent;\n }",
"public AreaOfInterest copy() {\n AreaOfInterest aoi = new AreaOfInterest();\n aoi.display = this.display;\n aoi.area = this.area;\n aoi.polygon = this.polygon;\n aoi.style = this.style;\n aoi.renderAsSvg = this.renderAsSvg;\n return aoi;\n }",
"public void setValue(String constantValue)\r\n {\r\n this.fieldSource = SOURCE_VALUE;\r\n this.fieldRefName = null;\r\n this.returnedByProcedure = false;\r\n this.constantValue = constantValue;\r\n }",
"private String readOptionalString(JSONObject json, String key, String defaultValue) {\n\n try {\n String str = json.getString(key);\n if (str != null) {\n return str;\n }\n\n } catch (JSONException e) {\n LOG.debug(\"Reading optional JSON string failed. Default to provided default value.\", e);\n }\n return defaultValue;\n }",
"public static int[] toInt(double[] array) {\n int[] n = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n n[i] = (int) array[i];\n }\n return n;\n }"
] |
Accessor method used to retrieve an Rate object representing the
contents of an individual field. If the field does not exist in the
record, null is returned.
@param field the index number of the field to be retrieved
@return the value of the required field
@throws MPXJException normally thrown when parsing fails | [
"public Rate getRate(int field) throws MPXJException\n {\n Rate result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n try\n {\n String rate = m_fields[field];\n int index = rate.indexOf('/');\n double amount;\n TimeUnit units;\n\n if (index == -1)\n {\n amount = m_formats.getCurrencyFormat().parse(rate).doubleValue();\n units = TimeUnit.HOURS;\n }\n else\n {\n amount = m_formats.getCurrencyFormat().parse(rate.substring(0, index)).doubleValue();\n units = TimeUnitUtility.getInstance(rate.substring(index + 1), m_locale);\n }\n\n result = new Rate(amount, units);\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse rate\", ex);\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }"
] | [
"public boolean merge(final PluginXmlAccess other) {\n boolean _xblockexpression = false;\n {\n String _path = this.getPath();\n String _path_1 = other.getPath();\n boolean _notEquals = (!Objects.equal(_path, _path_1));\n if (_notEquals) {\n String _path_2 = this.getPath();\n String _plus = (\"Merging plugin.xml files with different paths: \" + _path_2);\n String _plus_1 = (_plus + \", \");\n String _path_3 = other.getPath();\n String _plus_2 = (_plus_1 + _path_3);\n PluginXmlAccess.LOG.warn(_plus_2);\n }\n _xblockexpression = this.entries.addAll(other.entries);\n }\n return _xblockexpression;\n }",
"public Optional<Project> findProject(String name) throws IllegalArgumentException {\n if (name == null || name.isEmpty()) {\n throw new IllegalArgumentException(\"Project name cannot be empty\");\n }\n return getProject(name);\n }",
"boolean hasNoAlternativeWildcardRegistration() {\n return parent == null || PathElement.WILDCARD_VALUE.equals(valueString) || !parent.getChildNames().contains(PathElement.WILDCARD_VALUE);\n }",
"public void writeTo(IIMWriter writer) throws IOException {\r\n\t\tfinal boolean doLog = log != null;\r\n\t\tfor (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) {\r\n\t\t\tDataSet ds = i.next();\r\n\t\t\twriter.write(ds);\r\n\t\t\tif (doLog) {\r\n\t\t\t\tlog.debug(\"Wrote data set \" + ds);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"private void checkForCycles(DefaultDirectedWeightedGraph<RuleProvider, DefaultEdge> graph)\n {\n CycleDetector<RuleProvider, DefaultEdge> cycleDetector = new CycleDetector<>(graph);\n\n if (cycleDetector.detectCycles())\n {\n // if we have cycles, then try to throw an exception with some usable data\n Set<RuleProvider> cycles = cycleDetector.findCycles();\n StringBuilder errorSB = new StringBuilder();\n for (RuleProvider cycle : cycles)\n {\n errorSB.append(\"Found dependency cycle involving: \" + cycle.getMetadata().getID()).append(System.lineSeparator());\n Set<RuleProvider> subCycleSet = cycleDetector.findCyclesContainingVertex(cycle);\n for (RuleProvider subCycle : subCycleSet)\n {\n errorSB.append(\"\\tSubcycle: \" + subCycle.getMetadata().getID()).append(System.lineSeparator());\n }\n }\n throw new RuntimeException(\"Dependency cycles detected: \" + errorSB.toString());\n }\n }",
"public static int getBytesToken(ParsingContext ctx) {\n String input = ctx.getInput().substring(ctx.getLocation());\n int tokenOffset = 0;\n int i = 0;\n char[] inputChars = input.toCharArray();\n for (; i < input.length(); i += 1) {\n char c = inputChars[i];\n if (c == ' ') {\n continue;\n }\n if (c != BYTES_TOKEN_CHARS[tokenOffset]) {\n return -1;\n } else {\n tokenOffset += 1;\n if (tokenOffset == BYTES_TOKEN_CHARS.length) {\n // Found the token.\n return i;\n }\n }\n }\n return -1;\n }",
"private Map<Set<ServerIdentity>, ModelNode> getDeploymentOverlayOperations(ModelNode operation,\n ModelNode host) {\n final PathAddress realAddress = PathAddress.pathAddress(operation.get(OP_ADDR));\n if (realAddress.size() == 0 && COMPOSITE.equals(operation.get(OP).asString())) {\n //We have a composite operation resulting from a transformation to redeploy affected deployments\n //See redeploying deployments affected by an overlay.\n ModelNode serverOp = operation.clone();\n Map<ServerIdentity, Operations.CompositeOperationBuilder> composite = new HashMap<>();\n for (ModelNode step : serverOp.get(STEPS).asList()) {\n ModelNode newStep = step.clone();\n String groupName = PathAddress.pathAddress(step.get(OP_ADDR)).getElement(0).getValue();\n newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode());\n Set<ServerIdentity> servers = getServersForGroup(groupName, host, localHostName, serverProxies);\n for(ServerIdentity server : servers) {\n if(!composite.containsKey(server)) {\n composite.put(server, Operations.CompositeOperationBuilder.create());\n }\n composite.get(server).addStep(newStep);\n }\n if(!servers.isEmpty()) {\n newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode());\n }\n }\n if(!composite.isEmpty()) {\n Map<Set<ServerIdentity>, ModelNode> result = new HashMap<>();\n for(Entry<ServerIdentity, Operations.CompositeOperationBuilder> entry : composite.entrySet()) {\n result.put(Collections.singleton(entry.getKey()), entry.getValue().build().getOperation());\n }\n return result;\n }\n return Collections.emptyMap();\n }\n final Set<ServerIdentity> allServers = getAllRunningServers(host, localHostName, serverProxies);\n return Collections.singletonMap(allServers, operation.clone());\n }",
"protected List<Object> executeProcessors(final List<Object> processedColumns, final CellProcessor[] processors) {\n\t\tUtil.executeCellProcessors(processedColumns, getColumns(), processors, getLineNumber(), getRowNumber());\n\t\treturn processedColumns;\n\t}",
"private void executePlan(RebalancePlan rebalancePlan) {\n logger.info(\"Starting to execute rebalance Plan!\");\n\n int batchCount = 0;\n int partitionStoreCount = 0;\n long totalTimeMs = 0;\n\n List<RebalanceBatchPlan> entirePlan = rebalancePlan.getPlan();\n int numBatches = entirePlan.size();\n int numPartitionStores = rebalancePlan.getPartitionStoresMoved();\n\n for(RebalanceBatchPlan batchPlan: entirePlan) {\n logger.info(\"======== REBALANCING BATCH \" + (batchCount + 1)\n + \" ========\");\n RebalanceUtils.printBatchLog(batchCount,\n logger,\n batchPlan.toString());\n\n long startTimeMs = System.currentTimeMillis();\n // ACTUALLY DO A BATCH OF REBALANCING!\n executeBatch(batchCount, batchPlan);\n totalTimeMs += (System.currentTimeMillis() - startTimeMs);\n\n // Bump up the statistics\n batchCount++;\n partitionStoreCount += batchPlan.getPartitionStoreMoves();\n batchStatusLog(batchCount,\n numBatches,\n partitionStoreCount,\n numPartitionStores,\n totalTimeMs);\n }\n }"
] |
Find the user by their email address.
This method does not require authentication.
@param email
The email address
@return The User
@throws FlickrException | [
"public User findByEmail(String email) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_FIND_BY_EMAIL);\r\n\r\n parameters.put(\"find_email\", email);\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 userElement = response.getPayload();\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"nsid\"));\r\n user.setUsername(XMLUtilities.getChildValue(userElement, \"username\"));\r\n return user;\r\n }"
] | [
"private static String resolveJavaCommand(final Path javaHome) {\n final String exe;\n if (javaHome == null) {\n exe = \"java\";\n } else {\n exe = javaHome.resolve(\"bin\").resolve(\"java\").toString();\n }\n if (exe.contains(\" \")) {\n return \"\\\"\" + exe + \"\\\"\";\n }\n return exe;\n }",
"public List<Map<String, String>> pipelinePossibleStates(Assign action, List<Map<String, String>> possibleStateList) {\r\n for (Map<String, String> possibleState : possibleStateList) {\r\n possibleState.put(action.getName(), action.getExpr());\r\n }\n\r\n return possibleStateList;\r\n }",
"public void process()\n {\n if (m_data != null)\n {\n int index = 0;\n int offset = 0;\n // First the length (repeated twice)\n int length = MPPUtility.getInt(m_data, offset);\n offset += 8;\n // Then the number of custom columns\n int numberOfAliases = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n // Then the aliases themselves\n while (index < numberOfAliases && offset < length)\n {\n // Each item consists of the Field ID (2 bytes), 40 0B marker (2 bytes), and the\n // offset to the string (4 bytes)\n\n // Get the Field ID\n int fieldID = MPPUtility.getInt(m_data, offset);\n offset += 4;\n // Get the alias offset (offset + 4 for some reason).\n int aliasOffset = MPPUtility.getInt(m_data, offset) + 4;\n offset += 4;\n // Read the alias itself\n if (aliasOffset < m_data.length)\n {\n String alias = MPPUtility.getUnicodeString(m_data, aliasOffset);\n m_fields.getCustomField(FieldTypeHelper.getInstance(fieldID)).setAlias(alias);\n }\n index++;\n }\n }\n }",
"private String getName(CommandContext ctx, boolean failInBatch) throws CommandLineException {\n final ParsedCommandLine args = ctx.getParsedCommandLine();\n final String name = this.name.getValue(args, true);\n if (name == null) {\n throw new CommandFormatException(this.name + \" is missing value.\");\n }\n if (!ctx.isBatchMode() || failInBatch) {\n if (!Util.isValidPath(ctx.getModelControllerClient(), Util.DEPLOYMENT_OVERLAY, name)) {\n throw new CommandFormatException(\"Deployment overlay \" + name + \" does not exist.\");\n }\n }\n return name;\n }",
"public void setup( int numSamples , int sampleSize ) {\n mean = new double[ sampleSize ];\n A.reshape(numSamples,sampleSize,false);\n sampleIndex = 0;\n numComponents = -1;\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 }",
"public static void setViewBackground(View v, Drawable d) {\n if (Build.VERSION.SDK_INT >= 16) {\n v.setBackground(d);\n } else {\n v.setBackgroundDrawable(d);\n }\n }",
"public T findById(Object id) throws RowNotFoundException, TooManyRowsException {\n return findWhere(eq(idColumn.getColumnName(), id)).getSingleResult();\n }",
"public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, java.io.IOException\r\n {\r\n if (flavor.isMimeTypeEqual(OJBMETADATA_FLAVOR))\r\n return selectedDescriptors;\r\n else\r\n throw new UnsupportedFlavorException(flavor);\r\n }"
] |
Set the classpath for loading the driver using the classpath reference.
@param r reference to the classpath | [
"public void setClasspathRef(Reference r)\r\n {\r\n createClasspath().setRefid(r);\r\n log(\"Verification classpath is \"+ _classpath,\r\n Project.MSG_VERBOSE);\r\n }"
] | [
"@AsParameterConverter\n\tpublic Trader retrieveTrader(String name) {\n\t\tfor (Trader trader : traders) {\n\t\t\tif (trader.getName().equals(name)) {\n\t\t\t\treturn trader;\n\t\t\t}\n\t\t}\n\t\treturn mockTradePersister().retrieveTrader(name);\n\t}",
"public static <T> List<T> sortWith(Iterable<T> iterable, Comparator<? super T> comparator) {\n\t\treturn ListExtensions.sortInplace(Lists.newArrayList(iterable), comparator);\n\t}",
"public void remove(Object pKey)\r\n {\r\n Identity id;\r\n if(pKey instanceof Identity)\r\n {\r\n id = (Identity) pKey;\r\n }\r\n else\r\n {\r\n id = transaction.getBroker().serviceIdentity().buildIdentity(pKey);\r\n }\r\n mhtObjectEnvelopes.remove(id);\r\n mvOrderOfIds.remove(id);\r\n }",
"public static <T extends Spin<?>> T S(Object input, DataFormat<T> format) {\n return SpinFactory.INSTANCE.createSpin(input, format);\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 }",
"public String getOriginalValue(ParsedCommandLine parsedLine, boolean required) throws CommandFormatException {\n String value = null;\n if(parsedLine.hasProperties()) {\n if(index >= 0) {\n List<String> others = parsedLine.getOtherProperties();\n if(others.size() > index) {\n return others.get(index);\n }\n }\n\n value = parsedLine.getPropertyValue(fullName);\n if(value == null && shortName != null) {\n value = parsedLine.getPropertyValue(shortName);\n }\n }\n\n if(required && value == null && !isPresent(parsedLine)) {\n StringBuilder buf = new StringBuilder();\n buf.append(\"Required argument \");\n buf.append('\\'').append(fullName).append('\\'');\n buf.append(\" is missing.\");\n throw new CommandFormatException(buf.toString());\n }\n return value;\n }",
"private String extractNumericVersion(Collection<String> versionStrings) {\n if (versionStrings == null) {\n return \"\";\n }\n for (String value : versionStrings) {\n String releaseValue = calculateReleaseVersion(value);\n if (!releaseValue.equals(value)) {\n return releaseValue;\n }\n }\n return \"\";\n }",
"protected boolean determineFeatureState(final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, boolean defaultState) {\n final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(context.getConfiguration());\n final IStandardExpression expression = expressionParser.parseExpression(context, attributeValue);\n final Object value = expression.execute(context);\n if (value != null) {\n return isFeatureActive(value.toString());\n }\n else {\n return defaultState;\n }\n }",
"public static ObjectName createObjectName(String domain, String type) {\n try {\n return new ObjectName(domain + \":type=\" + type);\n } catch(MalformedObjectNameException e) {\n throw new VoldemortException(e);\n }\n }"
] |
Computes the null space using QR decomposition. This is much faster than using SVD
@param A (Input) Matrix
@param totalSingular Number of singular values
@return Null space | [
"public static DMatrixRMaj nullspaceQR( DMatrixRMaj A , int totalSingular ) {\n SolveNullSpaceQR_DDRM solver = new SolveNullSpaceQR_DDRM();\n\n DMatrixRMaj nullspace = new DMatrixRMaj(1,1);\n\n if( !solver.process(A,totalSingular,nullspace))\n throw new RuntimeException(\"Solver failed. try SVD based method instead?\");\n\n return nullspace;\n }"
] | [
"public void removeAt(int index) {\n synchronized (mLock) {\n if (mOriginalValues != null) {\n mOriginalValues.remove(index);\n } else {\n mObjects.remove(index);\n }\n }\n if (mNotifyOnChange) notifyDataSetChanged();\n }",
"public List<Integer> getPathOrder(int profileId) {\n ArrayList<Integer> pathOrder = new ArrayList<Integer>();\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \"\n + Constants.DB_TABLE_PATH + \" WHERE \"\n + Constants.GENERIC_PROFILE_ID + \" = ? \"\n + \" ORDER BY \" + Constants.PATH_PROFILE_PATH_ORDER + \" ASC\"\n );\n queryStatement.setInt(1, profileId);\n results = queryStatement.executeQuery();\n while (results.next()) {\n pathOrder.add(results.getInt(Constants.GENERIC_ID));\n }\n } catch (SQLException 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 (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n logger.info(\"pathOrder = {}\", pathOrder);\n return pathOrder;\n }",
"private void setViewPagerScroller() {\n try {\n Field scrollerField = ViewPager.class.getDeclaredField(\"mScroller\");\n scrollerField.setAccessible(true);\n Field interpolatorField = ViewPager.class.getDeclaredField(\"sInterpolator\");\n interpolatorField.setAccessible(true);\n\n scroller = new CustomDurationScroller(getContext(), (Interpolator)interpolatorField.get(null));\n scrollerField.set(this, scroller);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }",
"private int[] readColorTable(int ncolors) {\n int nbytes = 3 * ncolors;\n int[] tab = null;\n byte[] c = new byte[nbytes];\n\n try {\n rawData.get(c);\n\n // Max size to avoid bounds checks.\n tab = new int[MAX_BLOCK_SIZE];\n int i = 0;\n int j = 0;\n while (i < ncolors) {\n int r = ((int) c[j++]) & 0xff;\n int g = ((int) c[j++]) & 0xff;\n int b = ((int) c[j++]) & 0xff;\n tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;\n }\n } catch (BufferUnderflowException e) {\n //if (Log.isLoggable(TAG, Log.DEBUG)) {\n Logger.d(TAG, \"Format Error Reading Color Table\", e);\n //}\n header.status = GifDecoder.STATUS_FORMAT_ERROR;\n }\n\n return tab;\n }",
"public void wireSteps( CanWire canWire ) {\n for( StageState steps : stages.values() ) {\n canWire.wire( steps.instance );\n }\n }",
"public String getFullContentType() {\n final String url = this.url.toExternalForm().substring(\"data:\".length());\n final int endIndex = url.indexOf(',');\n if (endIndex >= 0) {\n final String contentType = url.substring(0, endIndex);\n if (!contentType.isEmpty()) {\n return contentType;\n }\n }\n return \"text/plain;charset=US-ASCII\";\n }",
"protected String getArgString(Object arg) {\n //if (arg instanceof LatLong) {\n // return ((LatLong) arg).getVariableName();\n //} else \n if (arg instanceof JavascriptObject) {\n return ((JavascriptObject) arg).getVariableName();\n // return ((JavascriptObject) arg).getPropertiesAsString();\n } else if( arg instanceof JavascriptEnum ) {\n return ((JavascriptEnum) arg).getEnumValue().toString();\n } else {\n return arg.toString();\n }\n }",
"public static Trajectory resample(Trajectory t, int n){\n\t\tTrajectory t1 = new Trajectory(2);\n\t\t\n\t\tfor(int i = 0; i < t.size(); i=i+n){\n\t\t\tt1.add(t.get(i));\n\t\t}\n\t\t\n\t\treturn t1;\n\t}",
"private boolean initCheckTypeModifiers() {\n\n Class<?> classInfoclass = Reflections.loadClass(CLASSINFO_CLASS_NAME, new ClassLoaderResourceLoader(classFileServices.getClass().getClassLoader()));\n if (classInfoclass != null) {\n try {\n Method setFlags = AccessController.doPrivileged(GetDeclaredMethodAction.of(classInfoclass, \"setFlags\", short.class));\n return setFlags != null;\n } catch (Exception exceptionIgnored) {\n BootstrapLogger.LOG.usingOldJandexVersion();\n return false;\n }\n } else {\n return true;\n }\n }"
] |
Create and return a new Violation for this rule and the specified import
@param sourceCode - the SourceCode
@param importNode - the ImportNode for the import triggering the violation
@return a new Violation object | [
"protected Violation createViolationForImport(SourceCode sourceCode, ImportNode importNode, String message) {\n Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, importNode);\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine((String) importInfo.get(\"sourceLine\"));\n violation.setLineNumber((Integer) importInfo.get(\"lineNumber\"));\n violation.setMessage(message);\n return violation;\n }"
] | [
"public static String groupFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null;\n }",
"protected void animateOffsetTo(int position, int velocity, boolean animate) {\n endDrag();\n endPeek();\n\n final int startX = (int) mOffsetPixels;\n final int dx = position - startX;\n if (dx == 0 || !animate) {\n setOffsetPixels(position);\n setDrawerState(position == 0 ? STATE_CLOSED : STATE_OPEN);\n stopLayerTranslation();\n return;\n }\n\n int duration;\n\n velocity = Math.abs(velocity);\n if (velocity > 0) {\n duration = 4 * Math.round(1000.f * Math.abs((float) dx / velocity));\n } else {\n duration = (int) (600.f * Math.abs((float) dx / mMenuSize));\n }\n\n duration = Math.min(duration, mMaxAnimationDuration);\n animateOffsetTo(position, duration);\n }",
"public static base_response add(nitro_service client, transformpolicy resource) throws Exception {\n\t\ttransformpolicy addresource = new transformpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.profilename = resource.profilename;\n\t\taddresource.comment = resource.comment;\n\t\taddresource.logaction = resource.logaction;\n\t\treturn addresource.add_resource(client);\n\t}",
"@Override\n public synchronized void start() {\n if (!started.getAndSet(true)) {\n finished.set(false);\n thread.start();\n }\n }",
"private void setFileNotWorldReadablePermissions(File file) {\n file.setReadable(false, false);\n file.setWritable(false, false);\n file.setExecutable(false, false);\n file.setReadable(true, true);\n file.setWritable(true, true);\n }",
"public void beforeCompletion()\r\n {\r\n // avoid redundant calls\r\n if(beforeCompletionCall) return;\r\n\r\n log.info(\"Method beforeCompletion was called\");\r\n int status = Status.STATUS_UNKNOWN;\r\n try\r\n {\r\n JTATxManager mgr = (JTATxManager) getImplementation().getTxManager();\r\n status = mgr.getJTATransaction().getStatus();\r\n // ensure proper work, check all possible status\r\n // normally only check for 'STATUS_MARKED_ROLLBACK' is necessary\r\n if(status == Status.STATUS_MARKED_ROLLBACK\r\n || status == Status.STATUS_ROLLEDBACK\r\n || status == Status.STATUS_ROLLING_BACK\r\n || status == Status.STATUS_UNKNOWN\r\n || status == Status.STATUS_NO_TRANSACTION)\r\n {\r\n log.error(\"Synchronization#beforeCompletion: Can't prepare for commit, because tx status was \"\r\n + TxUtil.getStatusString(status) + \". Do internal cleanup only.\");\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Synchronization#beforeCompletion: Prepare for commit\");\r\n }\r\n // write objects to database\r\n prepareCommit();\r\n }\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Synchronization#beforeCompletion: Error while prepare for commit\", e);\r\n if(e instanceof LockNotGrantedException)\r\n {\r\n throw (LockNotGrantedException) e;\r\n }\r\n else if(e instanceof TransactionAbortedException)\r\n {\r\n throw (TransactionAbortedException) e;\r\n }\r\n else if(e instanceof ODMGRuntimeException)\r\n {\r\n throw (ODMGRuntimeException) e;\r\n }\r\n else\r\n { \r\n throw new ODMGRuntimeException(\"Method beforeCompletion() fails, status of JTA-tx was \"\r\n + TxUtil.getStatusString(status) + \", message: \" + e.getMessage());\r\n }\r\n\r\n }\r\n finally\r\n {\r\n beforeCompletionCall = true;\r\n setInExternTransaction(false);\r\n internalCleanup();\r\n }\r\n }",
"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}",
"public static nsrollbackcmd[] get(nitro_service service, nsrollbackcmd_args args) throws Exception{\n\t\tnsrollbackcmd obj = new nsrollbackcmd();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tnsrollbackcmd[] response = (nsrollbackcmd[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"private float[] generateParticleTimeStamps(float totalTime)\n {\n float timeStamps[] = new float[mEmitRate * 2];\n for ( int i = 0; i < mEmitRate * 2; i +=2 )\n {\n timeStamps[i] = totalTime + mRandom.nextFloat();\n timeStamps[i + 1] = 0;\n }\n return timeStamps;\n }"
] |
Checks the given class descriptor.
@param classDef The class descriptor
@param checkLevel The amount of checks to perform
@exception ConstraintException If a constraint has been violated | [
"public void check(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureNoTableInfoIfNoRepositoryInfo(classDef, checkLevel);\r\n checkModifications(classDef, checkLevel);\r\n checkExtents(classDef, checkLevel);\r\n ensureTableIfNecessary(classDef, checkLevel);\r\n checkFactoryClassAndMethod(classDef, checkLevel);\r\n checkInitializationMethod(classDef, checkLevel);\r\n checkPrimaryKey(classDef, checkLevel);\r\n checkProxyPrefetchingLimit(classDef, checkLevel);\r\n checkRowReader(classDef, checkLevel);\r\n checkObjectCache(classDef, checkLevel);\r\n checkProcedures(classDef, checkLevel);\r\n }"
] | [
"public InsertBuilder set(String column, String value) {\n columns.add(column);\n values.add(value);\n return this;\n }",
"public static base_responses add(nitro_service client, dnstxtrec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnstxtrec addresources[] = new dnstxtrec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnstxtrec();\n\t\t\t\taddresources[i].domain = resources[i].domain;\n\t\t\t\taddresources[i].String = resources[i].String;\n\t\t\t\taddresources[i].ttl = resources[i].ttl;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static csvserver_cspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cspolicy_binding obj = new csvserver_cspolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cspolicy_binding response[] = (csvserver_cspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"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 }",
"private static String getColumnTitle(final PropertyDescriptor _property) {\n final StringBuilder buffer = new StringBuilder();\n final String name = _property.getName();\n buffer.append(Character.toUpperCase(name.charAt(0)));\n for (int i = 1; i < name.length(); i++) {\n final char c = name.charAt(i);\n if (Character.isUpperCase(c)) {\n buffer.append(' ');\n }\n buffer.append(c);\n }\n return buffer.toString();\n }",
"private String getPropertyName(Method method)\n {\n String result = method.getName();\n if (result.startsWith(\"get\"))\n {\n result = result.substring(3);\n }\n return result;\n }",
"public static DMatrixRMaj symmetric(int length, double min, double max, Random rand) {\n DMatrixRMaj A = new DMatrixRMaj(length,length);\n\n symmetric(A,min,max,rand);\n\n return A;\n }",
"public void checkConstraints(String checkLevel) throws ConstraintException\r\n {\r\n // now checking constraints\r\n FieldDescriptorConstraints fieldConstraints = new FieldDescriptorConstraints();\r\n ReferenceDescriptorConstraints refConstraints = new ReferenceDescriptorConstraints();\r\n CollectionDescriptorConstraints collConstraints = new CollectionDescriptorConstraints();\r\n\r\n for (Iterator it = getFields(); it.hasNext();)\r\n {\r\n fieldConstraints.check((FieldDescriptorDef)it.next(), checkLevel);\r\n }\r\n for (Iterator it = getReferences(); it.hasNext();)\r\n {\r\n refConstraints.check((ReferenceDescriptorDef)it.next(), checkLevel);\r\n }\r\n for (Iterator it = getCollections(); it.hasNext();)\r\n {\r\n collConstraints.check((CollectionDescriptorDef)it.next(), checkLevel);\r\n }\r\n new ClassDescriptorConstraints().check(this, checkLevel);\r\n }",
"public boolean detectNintendo() {\r\n\r\n if ((userAgent.indexOf(deviceNintendo) != -1)\r\n || (userAgent.indexOf(deviceWii) != -1)\r\n || (userAgent.indexOf(deviceNintendoDs) != -1)) {\r\n return true;\r\n }\r\n return false;\r\n }"
] |
Match the Origin header with the allowed origins.
If it doesn't match then a 403 response code is set on the response and it returns null.
@param exchange the current HttpExchange.
@param allowedOrigins list of sanitized allowed origins.
@return the first matching origin, null otherwise.
@throws Exception | [
"public static String matchOrigin(HttpServerExchange exchange, Collection<String> allowedOrigins) throws Exception {\n HeaderMap headers = exchange.getRequestHeaders();\n String[] origins = headers.get(Headers.ORIGIN).toArray();\n if (allowedOrigins != null && !allowedOrigins.isEmpty()) {\n for (String allowedOrigin : allowedOrigins) {\n for (String origin : origins) {\n if (allowedOrigin.equalsIgnoreCase(sanitizeDefaultPort(origin))) {\n return allowedOrigin;\n }\n }\n }\n }\n String allowedOrigin = defaultOrigin(exchange);\n for (String origin : origins) {\n if (allowedOrigin.equalsIgnoreCase(sanitizeDefaultPort(origin))) {\n return allowedOrigin;\n }\n }\n ROOT_LOGGER.debug(\"Request rejected due to HOST/ORIGIN mis-match.\");\n ResponseCodeHandler.HANDLE_403.handleRequest(exchange);\n return null;\n }"
] | [
"public static String chomp(String s) {\r\n if(s.length() == 0)\r\n return s;\r\n int l_1 = s.length() - 1;\r\n if (s.charAt(l_1) == '\\n') {\r\n return s.substring(0, l_1);\r\n }\r\n return s;\r\n }",
"public static void addToString(\n SourceBuilder code,\n Datatype datatype,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n boolean forPartial) {\n String typename = (forPartial ? \"partial \" : \"\") + datatype.getType().getSimpleName();\n Predicate<PropertyCodeGenerator> isOptional = generator -> {\n Initially initially = generator.initialState();\n return (initially == Initially.OPTIONAL || (initially == Initially.REQUIRED && forPartial));\n };\n boolean anyOptional = generatorsByProperty.values().stream().anyMatch(isOptional);\n boolean allOptional = generatorsByProperty.values().stream().allMatch(isOptional)\n && !generatorsByProperty.isEmpty();\n\n code.addLine(\"\")\n .addLine(\"@%s\", Override.class)\n .addLine(\"public %s toString() {\", String.class);\n if (allOptional) {\n bodyWithBuilderAndSeparator(code, datatype, generatorsByProperty, typename);\n } else if (anyOptional) {\n bodyWithBuilder(code, datatype, generatorsByProperty, typename, isOptional);\n } else {\n bodyWithConcatenation(code, generatorsByProperty, typename);\n }\n code.addLine(\"}\");\n }",
"public void notifyHeaderItemMoved(int fromPosition, int toPosition) {\n if (fromPosition < 0 || toPosition < 0 || fromPosition >= headerItemCount || toPosition >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given fromPosition \" + fromPosition + \" or toPosition \" + toPosition + \" is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemMoved(fromPosition, toPosition);\n }",
"private void deleteDir(File dir)\r\n {\r\n if (dir.exists() && dir.isDirectory())\r\n {\r\n File[] files = dir.listFiles();\r\n\r\n for (int idx = 0; idx < files.length; idx++)\r\n {\r\n if (!files[idx].exists())\r\n {\r\n continue;\r\n }\r\n if (files[idx].isDirectory())\r\n {\r\n deleteDir(files[idx]);\r\n }\r\n else\r\n {\r\n files[idx].delete();\r\n }\r\n }\r\n dir.delete();\r\n }\r\n }",
"public MIMEType addParameter(String name, String value) {\n Map<String, String> copy = new LinkedHashMap<>(this.parameters);\n copy.put(name, value);\n return new MIMEType(type, subType, copy);\n }",
"public <T> T get(Class<T> type) {\n return get(type.getName(), type);\n }",
"@Deprecated\r\n public static URL buildUrl(String host, int port, String path, Map<String, String> parameters) throws MalformedURLException {\r\n return buildUrl(\"http\", port, path, parameters);\r\n }",
"@SuppressWarnings({\"unchecked\", \"WeakerAccess\"})\n public static <T> List<T> readListAttributeElement(final XMLExtendedStreamReader reader, final String attributeName,\n final Class<T> type) throws XMLStreamException {\n requireSingleAttribute(reader, attributeName);\n // todo: fix this when this method signature is corrected\n final List<T> value = (List<T>) reader.getListAttributeValue(0, type);\n requireNoContent(reader);\n return value;\n }",
"public void retrieveProxyCollections(Object newObj, ClassDescriptor cld, boolean forced) throws PersistenceBrokerException\r\n {\r\n doRetrieveCollections(newObj, cld, forced, true);\r\n }"
] |
To get all the textual content in the dom
@param document
@param individualTokens : default True : when set to true, each text node from dom is used to build the
text content : when set to false, the text content of whole is obtained at once.
@return | [
"public static String getTextContent(Document document, boolean individualTokens) {\n String textContent = null;\n if (individualTokens) {\n List<String> tokens = getTextTokens(document);\n textContent = StringUtils.join(tokens, \",\");\n } else {\n textContent =\n document.getDocumentElement().getTextContent().trim().replaceAll(\"\\\\s+\", \",\");\n }\n return textContent;\n }"
] | [
"private void writeAvailability(Project.Resources.Resource xml, Resource mpx)\n {\n AvailabilityPeriods periods = m_factory.createProjectResourcesResourceAvailabilityPeriods();\n xml.setAvailabilityPeriods(periods);\n List<AvailabilityPeriod> list = periods.getAvailabilityPeriod();\n for (Availability availability : mpx.getAvailability())\n {\n AvailabilityPeriod period = m_factory.createProjectResourcesResourceAvailabilityPeriodsAvailabilityPeriod();\n list.add(period);\n DateRange range = availability.getRange();\n\n period.setAvailableFrom(range.getStart());\n period.setAvailableTo(range.getEnd());\n period.setAvailableUnits(DatatypeConverter.printUnits(availability.getUnits()));\n }\n }",
"public static base_responses add(nitro_service client, cmppolicylabel resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcmppolicylabel addresources[] = new cmppolicylabel[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new cmppolicylabel();\n\t\t\t\taddresources[i].labelname = resources[i].labelname;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"private Object runWithPossibleProxySwap(Method method, Object target, Object[] args)\n\t\t\tthrows IllegalAccessException, InvocationTargetException {\n\t\tObject result;\n\t\t// swap with proxies to these too.\n\t\tif (method.getName().equals(\"createStatement\")){\n\t\t\tresult = memorize((Statement)method.invoke(target, args), this.connectionHandle.get());\n\t\t}\n\t\telse if (method.getName().equals(\"prepareStatement\")){\n\t\t\tresult = memorize((PreparedStatement)method.invoke(target, args), this.connectionHandle.get());\n\t\t}\n\t\telse if (method.getName().equals(\"prepareCall\")){\n\t\t\tresult = memorize((CallableStatement)method.invoke(target, args), this.connectionHandle.get());\n\t\t}\n\t\telse result = method.invoke(target, args);\n\t\treturn result;\n\t}",
"public void useNewRESTService(String address) throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n org.customer.service.CustomerService customerService = JAXRSClientFactory\n .createFromModel(address, \n org.customer.service.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n\n System.out.println(\"Using new RESTful CustomerService with new client\");\n\n customer.v2.Customer customer = createNewCustomer(\"Smith New REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith New REST\");\n printNewCustomerDetails(customer);\n }",
"protected void markStatementsForDeletion(StatementDocument currentDocument,\n\t\t\tList<Statement> deleteStatements) {\n\t\tfor (Statement statement : deleteStatements) {\n\t\t\tboolean found = false;\n\t\t\tfor (StatementGroup sg : currentDocument.getStatementGroups()) {\n\t\t\t\tif (!sg.getProperty().equals(statement.getMainSnak().getPropertyId())) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tStatement changedStatement = null;\n\t\t\t\tfor (Statement existingStatement : sg) {\n\t\t\t\t\tif (existingStatement.equals(statement)) {\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\ttoDelete.add(statement.getStatementId());\n\t\t\t\t\t} else if (existingStatement.getStatementId().equals(\n\t\t\t\t\t\t\tstatement.getStatementId())) {\n\t\t\t\t\t\t// (we assume all existing statement ids to be nonempty\n\t\t\t\t\t\t// here)\n\t\t\t\t\t\tchangedStatement = existingStatement;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!found) {\n\t\t\t\t\tStringBuilder warning = new StringBuilder();\n\t\t\t\t\twarning.append(\"Cannot delete statement (id \")\n\t\t\t\t\t\t\t.append(statement.getStatementId())\n\t\t\t\t\t\t\t.append(\") since it is not present in data. Statement was:\\n\")\n\t\t\t\t\t\t\t.append(statement);\n\n\t\t\t\t\tif (changedStatement != null) {\n\t\t\t\t\t\twarning.append(\n\t\t\t\t\t\t\t\t\"\\nThe data contains another statement with the same id: maybe it has been edited? Other statement was:\\n\")\n\t\t\t\t\t\t\t\t.append(changedStatement);\n\t\t\t\t\t}\n\t\t\t\t\tlogger.warn(warning.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public float getNormalX(int vertex) {\n if (!hasNormals()) {\n throw new IllegalStateException(\"mesh has no normals\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_normals.getFloat(vertex * 3 * SIZEOF_FLOAT);\n }",
"public void setVariable(String name, Iterable<? extends WindupVertexFrame> frames)\n {\n Map<String, Iterable<? extends WindupVertexFrame>> frame = peek();\n if (!Iteration.DEFAULT_VARIABLE_LIST_STRING.equals(name) && findVariable(name) != null)\n {\n throw new IllegalArgumentException(\"Variable \\\"\" + name\n + \"\\\" has already been assigned and cannot be reassigned\");\n }\n\n frame.put(name, frames);\n }",
"public CollectionDescriptorDef getCollection(String name)\r\n {\r\n CollectionDescriptorDef collDef = null;\r\n\r\n for (Iterator it = _collections.iterator(); it.hasNext(); )\r\n {\r\n collDef = (CollectionDescriptorDef)it.next();\r\n if (collDef.getName().equals(name))\r\n {\r\n return collDef;\r\n }\r\n }\r\n return null;\r\n }",
"public void performStep() {\n // check for zeros\n for( int i = helper.x2-1; i >= helper.x1; i-- ) {\n if( helper.isZero(i) ) {\n helper.splits[helper.numSplits++] = i;\n helper.x1 = i+1;\n return;\n }\n }\n\n double lambda;\n\n if( followingScript ) {\n if( helper.steps > 10 ) {\n followingScript = false;\n return;\n } else {\n // Using the true eigenvalues will in general lead to the fastest convergence\n // typically takes 1 or 2 steps\n lambda = eigenvalues[helper.x2];\n }\n } else {\n // the current eigenvalue isn't working so try something else\n lambda = helper.computeShift();\n }\n\n // similar transforms\n helper.performImplicitSingleStep(lambda,false);\n }"
] |
This method is used to quote any special characters that appear in
literal text that is required as part of the currency format.
@param literal Literal text
@return literal text with special characters in quotes | [
"private String quoteFormatCharacters(String literal)\n {\n StringBuilder sb = new StringBuilder();\n int length = literal.length();\n char c;\n\n for (int loop = 0; loop < length; loop++)\n {\n c = literal.charAt(loop);\n switch (c)\n {\n case '0':\n case '#':\n case '.':\n case '-':\n case ',':\n case 'E':\n case ';':\n case '%':\n {\n sb.append(\"'\");\n sb.append(c);\n sb.append(\"'\");\n break;\n }\n\n default:\n {\n sb.append(c);\n break;\n }\n }\n }\n\n return (sb.toString());\n }"
] | [
"protected <H extends EventHandler> HandlerRegistration addHandler(final H handler, GwtEvent.Type<H> type) {\r\n\r\n return ensureHandlers().addHandlerToSource(type, this, handler);\r\n }",
"public List<ServerRedirect> getServerMappings() {\n ArrayList<ServerRedirect> servers = new ArrayList<ServerRedirect>();\n try {\n JSONObject response = new JSONObject(doGet(BASE_SERVER, null));\n JSONArray serverArray = response.getJSONArray(\"servers\");\n\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 return servers;\n }",
"public String getAttributeValue(String attributeName)\n throws JMException, UnsupportedEncodingException {\n String decodedAttributeName = sanitizer.urlDecode(attributeName, encoding);\n return sanitizer.escapeValue(mBeanServer.getAttribute(objectName, decodedAttributeName));\n }",
"private void writeProjectProperties()\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n\n m_plannerProject.setCompany(properties.getCompany());\n m_plannerProject.setManager(properties.getManager());\n m_plannerProject.setName(getString(properties.getName()));\n m_plannerProject.setProjectStart(getDateTime(properties.getStartDate()));\n m_plannerProject.setCalendar(getIntegerString(m_projectFile.getDefaultCalendar().getUniqueID()));\n m_plannerProject.setMrprojectVersion(\"2\");\n }",
"private void removeObservation( int index ) {\n final int N = y.numRows-1;\n final double d[] = y.data;\n\n // shift\n for( int i = index; i < N; i++ ) {\n d[i] = d[i+1];\n }\n y.numRows--;\n }",
"public void writeLock(EntityKey key, int timeout) {\n\t\tReadWriteLock lock = getLock( key );\n\t\tLock writeLock = lock.writeLock();\n\t\tacquireLock( key, timeout, writeLock );\n\t}",
"protected void setJsonValue(JsonObjectBuilder builder, T value) {\n // I don't like this - there should really be a way to construct a disconnected JSONValue...\n if (value instanceof Boolean) {\n builder.add(\"value\", (Boolean) value);\n } else if (value instanceof Double) {\n builder.add(\"value\", (Double) value);\n } else if (value instanceof Integer) {\n builder.add(\"value\", (Integer) value);\n } else if (value instanceof Long) {\n builder.add(\"value\", (Long) value);\n } else if (value instanceof BigInteger) {\n builder.add(\"value\", (BigInteger) value);\n } else if (value instanceof BigDecimal) {\n builder.add(\"value\", (BigDecimal) value);\n } else if (value == null) {\n builder.addNull(\"value\");\n } else {\n builder.add(\"value\", value.toString());\n }\n }",
"protected void unregisterDriver(){\r\n\t\tString jdbcURL = this.config.getJdbcUrl();\r\n\t\tif ((jdbcURL != null) && this.config.isDeregisterDriverOnClose()){\r\n\t\t\tlogger.info(\"Unregistering JDBC driver for : \"+jdbcURL);\r\n\t\t\ttry {\r\n\t\t\t\tDriverManager.deregisterDriver(DriverManager.getDriver(jdbcURL));\r\n\t\t\t} catch (SQLException e) {\r\n\t\t\t\tlogger.info(\"Unregistering driver failed.\", e);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"@Override\n\tpublic T next() {\n\t\tSQLException sqlException = null;\n\t\ttry {\n\t\t\tT result = nextThrow();\n\t\t\tif (result != null) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t} catch (SQLException e) {\n\t\t\tsqlException = e;\n\t\t}\n\t\t// we have to throw if there is no next or on a SQLException\n\t\tlast = null;\n\t\tcloseQuietly();\n\t\tthrow new IllegalStateException(\"Could not get next result for \" + dataClass, sqlException);\n\t}"
] |
Assigns an element a value based on its index in the internal array..
@param index The matrix element that is being assigned a value.
@param value The element's new value. | [
"public void set( int index , double value ) {\n if( mat.getType() == MatrixType.DDRM ) {\n ((DMatrixRMaj) mat).set(index, value);\n } else if( mat.getType() == MatrixType.FDRM ) {\n ((FMatrixRMaj) mat).set(index, (float)value);\n } else {\n throw new RuntimeException(\"Not supported yet for this matrix type\");\n }\n }"
] | [
"@Override\n public SuggestAccountsRequest suggestAccounts() throws RestApiException {\n return new SuggestAccountsRequest() {\n @Override\n public List<AccountInfo> get() throws RestApiException {\n return AccountsRestClient.this.suggestAccounts(this);\n }\n };\n }",
"public void processActivityCodes(List<Row> types, List<Row> typeValues, List<Row> assignments)\n {\n ActivityCodeContainer container = m_project.getActivityCodes();\n Map<Integer, ActivityCode> map = new HashMap<Integer, ActivityCode>();\n\n for (Row row : types)\n {\n ActivityCode code = new ActivityCode(row.getInteger(\"actv_code_type_id\"), row.getString(\"actv_code_type\"));\n container.add(code);\n map.put(code.getUniqueID(), code);\n }\n\n for (Row row : typeValues)\n {\n ActivityCode code = map.get(row.getInteger(\"actv_code_type_id\"));\n if (code != null)\n {\n ActivityCodeValue value = code.addValue(row.getInteger(\"actv_code_id\"), row.getString(\"short_name\"), row.getString(\"actv_code_name\"));\n m_activityCodeMap.put(value.getUniqueID(), value);\n }\n }\n\n for (Row row : assignments)\n {\n Integer taskID = row.getInteger(\"task_id\");\n List<Integer> list = m_activityCodeAssignments.get(taskID);\n if (list == null)\n {\n list = new ArrayList<Integer>();\n m_activityCodeAssignments.put(taskID, list);\n }\n list.add(row.getInteger(\"actv_code_id\"));\n }\n }",
"public String toStringByValue() {\r\n\tIntArrayList theKeys = new IntArrayList();\r\n\tkeysSortedByValue(theKeys);\r\n\r\n\tStringBuffer buf = new StringBuffer();\r\n\tbuf.append(\"[\");\r\n\tint maxIndex = theKeys.size() - 1;\r\n\tfor (int i = 0; i <= maxIndex; i++) {\r\n\t\tint key = theKeys.get(i);\r\n\t buf.append(String.valueOf(key));\r\n\t\tbuf.append(\"->\");\r\n\t buf.append(String.valueOf(get(key)));\r\n\t\tif (i < maxIndex) buf.append(\", \");\r\n\t}\r\n\tbuf.append(\"]\");\r\n\treturn buf.toString();\r\n}",
"@Nonnull\n public static XMLDSigValidationResult createReferenceErrors (@Nonnull @Nonempty final List <Integer> aInvalidReferences)\n {\n return new XMLDSigValidationResult (aInvalidReferences);\n }",
"private String formatAccrueType(AccrueType type)\n {\n return (type == null ? null : LocaleData.getStringArray(m_locale, LocaleData.ACCRUE_TYPES)[type.getValue() - 1]);\n }",
"public static byte[] concat(Bytes... listOfBytes) {\n int offset = 0;\n int size = 0;\n\n for (Bytes b : listOfBytes) {\n size += b.length() + checkVlen(b.length());\n }\n\n byte[] data = new byte[size];\n for (Bytes b : listOfBytes) {\n offset = writeVint(data, offset, b.length());\n b.copyTo(0, b.length(), data, offset);\n offset += b.length();\n }\n return data;\n }",
"public static base_response update(nitro_service client, nsacl6 resource) throws Exception {\n\t\tnsacl6 updateresource = new nsacl6();\n\t\tupdateresource.acl6name = resource.acl6name;\n\t\tupdateresource.aclaction = resource.aclaction;\n\t\tupdateresource.srcipv6 = resource.srcipv6;\n\t\tupdateresource.srcipop = resource.srcipop;\n\t\tupdateresource.srcipv6val = resource.srcipv6val;\n\t\tupdateresource.srcport = resource.srcport;\n\t\tupdateresource.srcportop = resource.srcportop;\n\t\tupdateresource.srcportval = resource.srcportval;\n\t\tupdateresource.destipv6 = resource.destipv6;\n\t\tupdateresource.destipop = resource.destipop;\n\t\tupdateresource.destipv6val = resource.destipv6val;\n\t\tupdateresource.destport = resource.destport;\n\t\tupdateresource.destportop = resource.destportop;\n\t\tupdateresource.destportval = resource.destportval;\n\t\tupdateresource.srcmac = resource.srcmac;\n\t\tupdateresource.protocol = resource.protocol;\n\t\tupdateresource.protocolnumber = resource.protocolnumber;\n\t\tupdateresource.icmptype = resource.icmptype;\n\t\tupdateresource.icmpcode = resource.icmpcode;\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.Interface = resource.Interface;\n\t\tupdateresource.priority = resource.priority;\n\t\tupdateresource.established = resource.established;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public List<Artifact> getArtifacts(final Boolean hasLicense) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactsPath());\n final ClientResponse response = resource.queryParam(ServerAPI.HAS_LICENSE_PARAM, hasLicense.toString())\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to get artifacts\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(ArtifactList.class);\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 }"
] |
Use this API to update nstimeout. | [
"public static base_response update(nitro_service client, nstimeout resource) throws Exception {\n\t\tnstimeout updateresource = new nstimeout();\n\t\tupdateresource.zombie = resource.zombie;\n\t\tupdateresource.client = resource.client;\n\t\tupdateresource.server = resource.server;\n\t\tupdateresource.httpclient = resource.httpclient;\n\t\tupdateresource.httpserver = resource.httpserver;\n\t\tupdateresource.tcpclient = resource.tcpclient;\n\t\tupdateresource.tcpserver = resource.tcpserver;\n\t\tupdateresource.anyclient = resource.anyclient;\n\t\tupdateresource.anyserver = resource.anyserver;\n\t\tupdateresource.halfclose = resource.halfclose;\n\t\tupdateresource.nontcpzombie = resource.nontcpzombie;\n\t\tupdateresource.reducedfintimeout = resource.reducedfintimeout;\n\t\tupdateresource.newconnidletimeout = resource.newconnidletimeout;\n\t\treturn updateresource.update_resource(client);\n\t}"
] | [
"public static int scanright(Color color, int height, int width, int col, PixelsExtractor f, int tolerance) {\n if (col == width || !PixelTools.colorMatches(color, tolerance, f.apply(new Area(col, 0, 1, height))))\n return col;\n else\n return scanright(color, height, width, col + 1, f, tolerance);\n }",
"public <T> T getNodeMetaData(Object key) {\n if (metaDataMap == null) {\n return (T) null;\n }\n return (T) metaDataMap.get(key);\n }",
"void scan() {\n if (acquireScanLock()) {\n boolean scheduleRescan = false;\n try {\n scheduleRescan = scan(false, deploymentOperations);\n } finally {\n try {\n if (scheduleRescan) {\n synchronized (this) {\n if (scanEnabled) {\n rescanIncompleteTask = scheduledExecutor.schedule(scanRunnable, 200, TimeUnit.MILLISECONDS);\n }\n }\n }\n } finally {\n releaseScanLock();\n }\n }\n }\n }",
"public float getPositionY(int vertex) {\n if (!hasPositions()) {\n throw new IllegalStateException(\"mesh has no positions\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_vertices.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\n }",
"private static TechReportPlacement processPlaceLabels(GraphContext graphContext, Set<String> tagNames)\n {\n TagGraphService tagService = new TagGraphService(graphContext);\n\n if (tagNames.size() < 3)\n throw new WindupException(\"There should always be exactly 3 placement labels - row, sector, column/box. It was: \" + tagNames);\n if (tagNames.size() > 3)\n LOG.severe(\"There should always be exactly 3 placement labels - row, sector, column/box. It was: \" + tagNames);\n\n TechReportPlacement placement = new TechReportPlacement();\n\n final TagModel placeSectorsTag = tagService.getTagByName(\"techReport:placeSectors\");\n final TagModel placeBoxesTag = tagService.getTagByName(\"techReport:placeBoxes\");\n final TagModel placeRowsTag = tagService.getTagByName(\"techReport:placeRows\");\n\n Set<String> unknownTags = new HashSet<>();\n for (String name : tagNames)\n {\n final TagModel tag = tagService.getTagByName(name);\n if (null == tag)\n continue;\n\n if (TagGraphService.isTagUnderTagOrSame(tag, placeSectorsTag))\n {\n placement.sector = tag;\n }\n else if (TagGraphService.isTagUnderTagOrSame(tag, placeBoxesTag))\n {\n placement.box = tag;\n }\n else if (TagGraphService.isTagUnderTagOrSame(tag, placeRowsTag))\n {\n placement.row = tag;\n }\n else\n {\n unknownTags.add(name);\n }\n }\n placement.unknown = unknownTags;\n\n LOG.fine(String.format(\"\\t\\tLabels %s identified as: sector: %s, box: %s, row: %s\", tagNames, placement.sector, placement.box,\n placement.row));\n if (placement.box == null || placement.row == null)\n {\n LOG.severe(String.format(\n \"There should always be exactly 3 placement labels - row, sector, column/box. Found: %s, of which box: %s, row: %s\", tagNames,\n placement.box, placement.row));\n }\n return placement;\n }",
"private void readPredecessors(net.sf.mpxj.planner.schema.Task plannerTask)\n {\n Task mpxjTask = m_projectFile.getTaskByUniqueID(getInteger(plannerTask.getId()));\n\n Predecessors predecessors = plannerTask.getPredecessors();\n if (predecessors != null)\n {\n List<Predecessor> predecessorList = predecessors.getPredecessor();\n for (Predecessor predecessor : predecessorList)\n {\n Integer predecessorID = getInteger(predecessor.getPredecessorId());\n Task predecessorTask = m_projectFile.getTaskByUniqueID(predecessorID);\n if (predecessorTask != null)\n {\n Duration lag = getDuration(predecessor.getLag());\n if (lag == null)\n {\n lag = Duration.getInstance(0, TimeUnit.HOURS);\n }\n Relation relation = mpxjTask.addPredecessor(predecessorTask, RELATIONSHIP_TYPES.get(predecessor.getType()), lag);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }\n\n //\n // Process child tasks\n //\n List<net.sf.mpxj.planner.schema.Task> childTasks = plannerTask.getTask();\n for (net.sf.mpxj.planner.schema.Task childTask : childTasks)\n {\n readPredecessors(childTask);\n }\n }",
"private void addContentInfo() {\n\n if (!m_cms.getRequestContext().getCurrentProject().isOnlineProject()\n && (null == m_searchController.getCommon().getConfig().getSolrIndex())\n && (null != m_addContentInfoForEntries)) {\n CmsSolrQuery query = new CmsSolrQuery();\n m_searchController.addQueryParts(query, m_cms);\n query.setStart(Integer.valueOf(0));\n query.setRows(m_addContentInfoForEntries);\n CmsContentLoadCollectorInfo info = new CmsContentLoadCollectorInfo();\n info.setCollectorClass(this.getClass().getName());\n info.setCollectorParams(query.getQuery());\n info.setId((new CmsUUID()).getStringValue());\n if (CmsJspTagEditable.getDirectEditProvider(pageContext) != null) {\n try {\n CmsJspTagEditable.getDirectEditProvider(pageContext).insertDirectEditListMetadata(\n pageContext,\n info);\n } catch (JspException e) {\n LOG.error(\"Could not write content info.\", e);\n }\n }\n }\n }",
"protected String parseOptionalStringValue(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 return value.getStringValue(null);\n }\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}"
] |
appends a WHERE-clause to the Statement
@param where
@param crit
@param stmt | [
"protected void appendWhereClause(StringBuffer where, Criteria crit, StringBuffer stmt)\r\n {\r\n if (where.length() == 0)\r\n {\r\n where = null;\r\n }\r\n\r\n if (where != null || (crit != null && !crit.isEmpty()))\r\n {\r\n stmt.append(\" WHERE \");\r\n appendClause(where, crit, stmt);\r\n }\r\n }"
] | [
"public ColumnBuilder addFieldProperty(String propertyName, String value) {\n\t\tfieldProperties.put(propertyName, value);\n\t\treturn this;\n\t}",
"public List<Group> findAllGroups() {\n ArrayList<Group> allGroups = new ArrayList<Group>();\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\"SELECT * FROM \"\n + Constants.DB_TABLE_GROUPS +\n \" ORDER BY \" + Constants.GROUPS_GROUP_NAME);\n results = queryStatement.executeQuery();\n while (results.next()) {\n Group group = new Group();\n group.setId(results.getInt(Constants.GENERIC_ID));\n group.setName(results.getString(Constants.GROUPS_GROUP_NAME));\n allGroups.add(group);\n }\n } catch (SQLException 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 (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return allGroups;\n }",
"protected float getStartingOffset(final float totalSize) {\n final float axisSize = getViewPortSize(getOrientationAxis());\n float startingOffset = 0;\n\n switch (getGravityInternal()) {\n case LEFT:\n case FILL:\n case TOP:\n case FRONT:\n startingOffset = -axisSize / 2;\n break;\n case RIGHT:\n case BOTTOM:\n case BACK:\n startingOffset = (axisSize / 2 - totalSize);\n break;\n case CENTER:\n startingOffset = -totalSize / 2;\n break;\n default:\n Log.w(TAG, \"Cannot calculate starting offset: \" +\n \"gravity %s is not supported!\", mGravity);\n break;\n\n }\n\n Log.d(LAYOUT, TAG, \"getStartingOffset(): totalSize: %5.4f, dimension: %5.4f, startingOffset: %5.4f\",\n totalSize, axisSize, startingOffset);\n\n return startingOffset;\n }",
"public long getStartTime(List<IInvokedMethod> methods)\n {\n long startTime = System.currentTimeMillis();\n for (IInvokedMethod method : methods)\n {\n startTime = Math.min(startTime, method.getDate());\n }\n return startTime;\n }",
"public Operation.Info create( Symbol op , Variable left , Variable right ) {\n switch( op ) {\n case PLUS:\n return Operation.add(left, right, managerTemp);\n\n case MINUS:\n return Operation.subtract(left, right, managerTemp);\n\n case TIMES:\n return Operation.multiply(left, right, managerTemp);\n\n case RDIVIDE:\n return Operation.divide(left, right, managerTemp);\n\n case LDIVIDE:\n return Operation.divide(right, left, managerTemp);\n\n case POWER:\n return Operation.pow(left, right, managerTemp);\n\n case ELEMENT_DIVIDE:\n return Operation.elementDivision(left, right, managerTemp);\n\n case ELEMENT_TIMES:\n return Operation.elementMult(left, right, managerTemp);\n\n case ELEMENT_POWER:\n return Operation.elementPow(left, right, managerTemp);\n\n default:\n throw new RuntimeException(\"Unknown operation \" + op);\n }\n }",
"public static <T> T withObjectStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={\"java.io.ObjectInputStream\",\"java.io.ObjectOutputStream\"}) Closure<T> closure) throws IOException {\n InputStream input = socket.getInputStream();\n OutputStream output = socket.getOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(output);\n ObjectInputStream ois = new ObjectInputStream(input);\n try {\n T result = closure.call(new Object[]{ois, oos});\n\n InputStream temp1 = ois;\n ois = null;\n temp1.close();\n temp1 = input;\n input = null;\n temp1.close();\n OutputStream temp2 = oos;\n oos = null;\n temp2.close();\n temp2 = output;\n output = null;\n temp2.close();\n\n return result;\n } finally {\n closeWithWarning(ois);\n closeWithWarning(input);\n closeWithWarning(oos);\n closeWithWarning(output);\n }\n }",
"public static long readUnsignedInt(byte[] bytes, int offset) {\n return (((bytes[offset + 0] & 0xffL) << 24) | ((bytes[offset + 1] & 0xffL) << 16)\n | ((bytes[offset + 2] & 0xffL) << 8) | (bytes[offset + 3] & 0xffL));\n }",
"private static void listAssignmentsByResource(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n System.out.println(\"Assignments for resource \" + resource.getName() + \":\");\n\n for (ResourceAssignment assignment : resource.getTaskAssignments())\n {\n Task task = assignment.getTask();\n System.out.println(\" \" + task.getName());\n }\n }\n\n System.out.println();\n }",
"public void beforeClose(PBStateEvent event)\r\n {\r\n /*\r\n arminw:\r\n this is a workaround for use in managed environments. When a PB instance is used\r\n within a container a PB.close call is done when leave the container method. This close\r\n the PB handle (but the real instance is still in use) and the PB listener are notified.\r\n But the JTA tx was not committed at\r\n this point in time and the session cache should not be cleared, because the updated/new\r\n objects will be pushed to the real cache on commit call (if we clear, nothing to push).\r\n So we check if the real broker is in a local tx (in this case we are in a JTA tx and the handle\r\n is closed), if true we don't reset the session cache.\r\n */\r\n if(!broker.isInTransaction())\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"Clearing the session cache\");\r\n resetSessionCache();\r\n }\r\n }"
] |
If you have priorities based on enums, this is the recommended prioritizer to use as it will prevent
starvation of low priority items
@param groupClass
@return | [
"public ExecutorLoadBalancingConfig<GROUP> useLoadBalancedEnumOrdinalPrioritizer(Class<GROUP> groupClass) {\n if(!groupClass.isEnum()) {\n throw new IllegalArgumentException(\"The group class \"+groupClass+\" is not an enum\");\n }\n groupPrioritizer = new LoadBalancedPriorityPrioritizer<GROUP>(new EnumOrdinalPrioritizer<GROUP>());\n return this;\n }"
] | [
"public void setFullscreen(boolean fullscreen) {\n if (mBuilder.mScrimInsetsLayout != null) {\n mBuilder.mScrimInsetsLayout.setTintStatusBar(!fullscreen);\n mBuilder.mScrimInsetsLayout.setTintNavigationBar(!fullscreen);\n }\n }",
"public static List<String> enableJMX(List<String> jvmArgs) {\n final String arg = \"-D\" + OPT_JMX_REMOTE;\n if (jvmArgs.contains(arg))\n return jvmArgs;\n final List<String> cmdLine2 = new ArrayList<>(jvmArgs);\n cmdLine2.add(arg);\n return cmdLine2;\n }",
"private boolean readNextRow() {\n while (!stop) {\n String row = getLineWrapped();\n // end of stream - null indicates end of stream before we see last_seq which shouldn't\n // be possible but we should handle it\n if (row == null || row.startsWith(\"{\\\"last_seq\\\":\")) {\n terminate();\n return false;\n } else if (row.isEmpty()) {\n // heartbeat\n continue;\n }\n setNextRow(gson.fromJson(row, ChangesResult.Row.class));\n return true;\n }\n // we were stopped, end of changes feed\n terminate();\n return false;\n }",
"public List<Widget> getAllViews() {\n List<Widget> views = new ArrayList<>();\n for (Widget child: mContent.getChildren()) {\n Widget item = ((ListItemHostWidget) child).getGuest();\n if (item != null) {\n views.add(item);\n }\n }\n return views;\n }",
"public void setShiftOrientation(OrientedLayout.Orientation orientation) {\n if (mShiftLayout.getOrientation() != orientation &&\n orientation != OrientedLayout.Orientation.STACK) {\n mShiftLayout.setOrientation(orientation);\n requestLayout();\n }\n }",
"public static GregorianCalendar millisToCalendar(long millis) {\r\n\r\n GregorianCalendar result = new GregorianCalendar();\r\n result.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\r\n result.setTimeInMillis((long)(Math.ceil(millis / 1000) * 1000));\r\n return result;\r\n }",
"public static <K, V> Map<K, V> of(K key, V value) {\n return new ImmutableMapEntry<K, V>(key, value);\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 static List<String> getParameterNames(MethodNode node) {\r\n ArrayList<String> result = new ArrayList<String>();\r\n\r\n if (node.getParameters() != null) {\r\n for (Parameter parameter : node.getParameters()) {\r\n result.add(parameter.getName());\r\n }\r\n }\r\n return result;\r\n }"
] |
Appends the query part for the facet to the query string.
@param query The current query string.
@param name The name of the facet parameter, e.g. "limit", "order", ....
@param value The value to set for the parameter specified by name. | [
"protected void appendFacetOption(StringBuffer query, final String name, final String value) {\n\n query.append(\" facet.\").append(name).append(\"=\").append(value);\n }"
] | [
"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 static ipset[] get(nitro_service service) throws Exception{\n\t\tipset obj = new ipset();\n\t\tipset[] response = (ipset[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private static EventTypeEnum mapEventTypeEnum(EventEnumType eventType) {\n if (eventType != null) {\n return EventTypeEnum.valueOf(eventType.name());\n }\n return EventTypeEnum.UNKNOWN;\n }",
"private void processGeneratedProperties(\n\t\t\tSerializable id,\n\t\t\tObject entity,\n\t\t\tObject[] state,\n\t\t\tSharedSessionContractImplementor session,\n\t\t\tGenerationTiming matchTiming) {\n\n\t\tTuple tuple = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );\n\t\tsaveSharedTuple( entity, tuple, session );\n\n\t\tif ( tuple == null || tuple.getSnapshot().isEmpty() ) {\n\t\t\tthrow log.couldNotRetrieveEntityForRetrievalOfGeneratedProperties( getEntityName(), id );\n\t\t}\n\n\t\tint propertyIndex = -1;\n\t\tfor ( NonIdentifierAttribute attribute : getEntityMetamodel().getProperties() ) {\n\t\t\tpropertyIndex++;\n\t\t\tfinal ValueGeneration valueGeneration = attribute.getValueGenerationStrategy();\n\t\t\tif ( isReadRequired( valueGeneration, matchTiming ) ) {\n\t\t\t\tObject hydratedState = gridPropertyTypes[propertyIndex].hydrate( tuple, getPropertyAliases( \"\", propertyIndex ), session, entity );\n\t\t\t\tstate[propertyIndex] = gridPropertyTypes[propertyIndex].resolve( hydratedState, session, entity );\n\t\t\t\tsetPropertyValue( entity, propertyIndex, state[propertyIndex] );\n\t\t\t}\n\t\t}\n\t}",
"public void setGamma(float rGamma, float gGamma, float bGamma) {\n\t\tthis.rGamma = rGamma;\n\t\tthis.gGamma = gGamma;\n\t\tthis.bGamma = bGamma;\n\t\tinitialized = false;\n\t}",
"public static base_response delete(nitro_service client, nssimpleacl resource) throws Exception {\n\t\tnssimpleacl deleteresource = new nssimpleacl();\n\t\tdeleteresource.aclname = resource.aclname;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public void delete() {\r\n URL url = DEVICE_PIN_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\r\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\r\n BoxAPIResponse response = request.send();\r\n response.disconnect();\r\n }",
"protected boolean isStoredProcedure(String sql)\r\n {\r\n /*\r\n Stored procedures start with\r\n {?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n or\r\n {call <procedure-name>[<arg1>,<arg2>, ...]}\r\n but also statements with white space like\r\n { ?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n are possible.\r\n */\r\n int k = 0, i = 0;\r\n char c;\r\n while(k < 3 && i < sql.length())\r\n {\r\n c = sql.charAt(i);\r\n if(c != ' ')\r\n {\r\n switch (k)\r\n {\r\n case 0:\r\n if(c != '{') return false;\r\n break;\r\n case 1:\r\n if(c != '?' && c != 'c') return false;\r\n break;\r\n case 2:\r\n if(c != '=' && c != 'a') return false;\r\n break;\r\n }\r\n k++;\r\n }\r\n i++;\r\n }\r\n return true;\r\n }",
"public static base_responses unset(nitro_service client, String ipaddress[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (ipaddress != null && ipaddress.length > 0) {\n\t\t\tnsrpcnode unsetresources[] = new nsrpcnode[ipaddress.length];\n\t\t\tfor (int i=0;i<ipaddress.length;i++){\n\t\t\t\tunsetresources[i] = new nsrpcnode();\n\t\t\t\tunsetresources[i].ipaddress = ipaddress[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}"
] |
Sets the values of this input field. Only Applicable check-boxes and a radio buttons.
@param values Values to set. | [
"public void inputValues(boolean... values) {\n\t\tfor (boolean value : values) {\n\t\t\tInputValue inputValue = new InputValue();\n\t\t\tinputValue.setChecked(value);\n\n\t\t\tthis.inputValues.add(inputValue);\n\t\t}\n\t}"
] | [
"public EventsRequest<Event> get(String resource, String sync) {\n return new EventsRequest<Event>(this, Event.class, \"/events\", \"GET\")\n .query(\"resource\", resource)\n .query(\"sync\", sync);\n }",
"public final SimpleFeatureCollection autoTreat(final Template template, final String features)\n throws IOException {\n SimpleFeatureCollection featuresCollection = treatStringAsURL(template, features);\n if (featuresCollection == null) {\n featuresCollection = treatStringAsGeoJson(features);\n }\n return featuresCollection;\n }",
"private String getActivityID(Task task)\n {\n String result = null;\n if (m_activityIDField != null)\n {\n Object value = task.getCachedValue(m_activityIDField);\n if (value != null)\n {\n result = value.toString();\n }\n }\n return result;\n }",
"private String formatTimeUnit(TimeUnit timeUnit)\n {\n int units = timeUnit.getValue();\n String result;\n String[][] unitNames = LocaleData.getStringArrays(m_locale, LocaleData.TIME_UNITS_ARRAY);\n\n if (units < 0 || units >= unitNames.length)\n {\n result = \"\";\n }\n else\n {\n result = unitNames[units][0];\n }\n\n return (result);\n }",
"public static base_response unset(nitro_service client, rnatparam resource, String[] args) throws Exception{\n\t\trnatparam unsetresource = new rnatparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static String getAt(String text, IntRange range) {\n return getAt(text, (Range) range);\n }",
"public int[] getCurrentValuesArray() {\n int[] currentValues = new int[5];\n\n currentValues[0] = getMinFilterType().getFilterValue(); // MIN FILTER\n currentValues[1] = getMagFilterType().getFilterValue(); // MAG FILTER\n currentValues[2] = getAnisotropicValue(); // ANISO FILTER\n currentValues[3] = getWrapSType().getWrapValue(); // WRAP S\n currentValues[4] = getWrapTType().getWrapValue(); // WRAP T\n\n return currentValues;\n }",
"public static CombinedInterceptorAndDecoratorStackMethodHandler peekIfNotEmpty() {\n Stack stack = interceptionContexts.get();\n if (stack == null) {\n return null;\n }\n return stack.peek();\n }",
"public long[] append(MessageSet messages) throws IOException {\n checkMutable();\n long written = 0L;\n while (written < messages.getSizeInBytes())\n written += messages.writeTo(channel, 0, messages.getSizeInBytes());\n long beforeOffset = setSize.getAndAdd(written);\n return new long[]{written, beforeOffset};\n }"
] |
Return a list of place IDs for a query string.
The flickr.places.find method is not a geocoder. It will round "up" to the nearest place type to which place IDs apply. For example, if you pass it a
street level address it will return the city that contains the address rather than the street, or building, itself.
<p>
This method does not require authentication.
</p>
@param query
@return PlacesList
@throws FlickrException | [
"public PlacesList<Place> find(String query) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n PlacesList<Place> placesList = new PlacesList<Place>();\r\n parameters.put(\"method\", METHOD_FIND);\r\n\r\n parameters.put(\"query\", query);\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 placesElement = response.getPayload();\r\n NodeList placesNodes = placesElement.getElementsByTagName(\"place\");\r\n placesList.setPage(\"1\");\r\n placesList.setPages(\"1\");\r\n placesList.setPerPage(\"\" + placesNodes.getLength());\r\n placesList.setTotal(\"\" + placesNodes.getLength());\r\n for (int i = 0; i < placesNodes.getLength(); i++) {\r\n Element placeElement = (Element) placesNodes.item(i);\r\n placesList.add(parsePlace(placeElement));\r\n }\r\n return placesList;\r\n }"
] | [
"public void store(String gavc,\n String action,\n String commentText,\n DbCredential credential,\n String entityType) {\n DbComment comment = new DbComment();\n comment.setEntityId(gavc);\n comment.setEntityType(entityType);\n comment.setDbCommentedBy(credential.getUser());\n comment.setAction(action);\n\n if(!commentText.isEmpty()) {\n comment.setDbCommentText(commentText);\n }\n\n comment.setDbCreatedDateTime(new Date());\n\n repositoryHandler.store(comment);\n }",
"public ItemRequest<Tag> delete(String tag) {\n \n String path = String.format(\"/tags/%s\", tag);\n return new ItemRequest<Tag>(this, Tag.class, path, \"DELETE\");\n }",
"public String getHealthMemory() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"Logging JVM Stats\\n\");\n MonitorProvider mp = MonitorProvider.getInstance();\n PerformUsage perf = mp.getJVMMemoryUsage();\n sb.append(perf.toString());\n\n if (perf.memoryUsagePercent >= THRESHOLD_PERCENT) {\n sb.append(\"========= WARNING: MEM USAGE > \" + THRESHOLD_PERCENT\n + \"!!\");\n sb.append(\" !! Live Threads List=============\\n\");\n sb.append(mp.getThreadUsage().toString());\n sb.append(\"========================================\\n\");\n sb.append(\"========================JVM Thread Dump====================\\n\");\n ThreadInfo[] threadDump = mp.getThreadDump();\n for (ThreadInfo threadInfo : threadDump) {\n sb.append(threadInfo.toString() + \"\\n\");\n }\n sb.append(\"===========================================================\\n\");\n }\n sb.append(\"Logged JVM Stats\\n\");\n\n return sb.toString();\n }",
"public void initializePersistenceStrategy(CacheMappingType cacheMappingType, Set<EntityKeyMetadata> entityTypes, Set<AssociationKeyMetadata> associationTypes, Set<IdSourceKeyMetadata> idSourceTypes, Iterable<Namespace> namespaces) {\n\t\tpersistenceStrategy = PersistenceStrategy.getInstance(\n\t\t\t\tcacheMappingType,\n\t\t\t\texternalCacheManager,\n\t\t\t\tconfig.getConfigurationUrl(),\n\t\t\t\tjtaPlatform,\n\t\t\t\tentityTypes,\n\t\t\t\tassociationTypes,\n\t\t\t\tidSourceTypes\n\t\t);\n\n\t\t// creates handler for TableGenerator Id sources\n\t\tboolean requiresCounter = hasIdGeneration( idSourceTypes );\n\t\tif ( requiresCounter ) {\n\t\t\tthis.tableClusterHandler = new TableClusteredCounterHandler( persistenceStrategy.getCacheManager().getCacheManager() );\n\t\t}\n\n\t\t// creates handlers for SequenceGenerator Id sources\n\t\tfor ( Namespace namespace : namespaces ) {\n\t\t\tfor ( Sequence seq : namespace.getSequences() ) {\n\t\t\t\tthis.sequenceCounterHandlers.put( seq.getExportIdentifier(),\n\t\t\t\t\t\tnew SequenceClusteredCounterHandler( persistenceStrategy.getCacheManager().getCacheManager(), seq ) );\n\t\t\t}\n\t\t}\n\n\t\t// clear resources\n\t\tthis.externalCacheManager = null;\n\t\tthis.jtaPlatform = null;\n\t}",
"private SortedSet<Date> filterExceptions(SortedSet<Date> dates) {\n\n SortedSet<Date> result = new TreeSet<Date>();\n for (Date d : dates) {\n if (!m_exceptions.contains(d)) {\n result.add(d);\n }\n }\n return result;\n }",
"public Boolean getBoolean(String fieldName) {\n\t\treturn hasValue(fieldName) ? Boolean.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t}",
"protected void createKeystore() {\n\n\t\tjava.security.cert.Certificate signingCert = null;\n\t\tPrivateKey caPrivKey = null;\n\n\t\tif(_caCert == null || _caPrivKey == null)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tlog.debug(\"Keystore or signing cert & keypair not found. Generating...\");\n\n\t\t\t\tKeyPair caKeypair = getRSAKeyPair();\n\t\t\t\tcaPrivKey = caKeypair.getPrivate();\n\t\t\t\tsigningCert = CertificateCreator.createTypicalMasterCert(caKeypair);\n\n\t\t\t\tlog.debug(\"Done generating signing cert\");\n\t\t\t\tlog.debug(signingCert);\n\n\t\t\t\t_ks.load(null, _keystorepass);\n\n\t\t\t\t_ks.setCertificateEntry(_caCertAlias, signingCert);\n\t\t\t\t_ks.setKeyEntry(_caPrivKeyAlias, caPrivKey, _keypassword, new java.security.cert.Certificate[] {signingCert});\n\n\t\t\t\tFile caKsFile = new File(root, _caPrivateKeystore);\n\n\t\t\t\tOutputStream os = new FileOutputStream(caKsFile);\n\t\t\t\t_ks.store(os, _keystorepass);\n\n\t\t\t\tlog.debug(\"Wrote JKS keystore to: \" +\n\t\t\t\t\t\tcaKsFile.getAbsolutePath());\n\n\t\t\t\t// also export a .cer that can be imported as a trusted root\n\t\t\t\t// to disable all warning dialogs for interception\n\n\t\t\t\tFile signingCertFile = new File(root, EXPORTED_CERT_NAME);\n\n\t\t\t\tFileOutputStream cerOut = new FileOutputStream(signingCertFile);\n\n\t\t\t\tbyte[] buf = signingCert.getEncoded();\n\n\t\t\t\tlog.debug(\"Wrote signing cert to: \" + signingCertFile.getAbsolutePath());\n\n\t\t\t\tcerOut.write(buf);\n\t\t\t\tcerOut.flush();\n\t\t\t\tcerOut.close();\n\n\t\t\t\t_caCert = (X509Certificate)signingCert;\n\t\t\t\t_caPrivKey = caPrivKey;\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tlog.error(\"Fatal error creating/storing keystore or signing cert.\", e);\n\t\t\t\tthrow new Error(e);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlog.debug(\"Successfully loaded keystore.\");\n\t\t\tlog.debug(_caCert);\n\n\t\t}\n\n\t}",
"private void updateWorkTimeUnit(FastTrackColumn column)\n {\n if (m_workTimeUnit == null && isWorkColumn(column))\n {\n int value = ((DurationColumn) column).getTimeUnitValue();\n if (value != 1)\n {\n m_workTimeUnit = FastTrackUtility.getTimeUnit(value);\n }\n }\n }",
"private void readTasks(Project project)\n {\n Project.Tasks tasks = project.getTasks();\n if (tasks != null)\n {\n int tasksWithoutIDCount = 0;\n\n for (Project.Tasks.Task task : tasks.getTask())\n {\n Task mpxjTask = readTask(task);\n if (mpxjTask.getID() == null)\n {\n ++tasksWithoutIDCount;\n }\n }\n\n for (Project.Tasks.Task task : tasks.getTask())\n {\n readPredecessors(task);\n }\n\n //\n // MS Project will happily read tasks from an MSPDI file without IDs,\n // it will just generate ID values based on the task order in the file.\n // If we find that there are no ID values present, we'll do the same.\n //\n if (tasksWithoutIDCount == tasks.getTask().size())\n {\n m_projectFile.getTasks().renumberIDs();\n }\n }\n\n m_projectFile.updateStructure();\n }"
] |
Detach the component of the specified type from this scene object.
Each scene object has a list of components. Only one component
of a particular type can be attached. Components are detached based on their type.
@return GVRComponent detached or null if component not found
@param type type of component to detach
@see GVRSceneObject#attachComponent(GVRComponent) | [
"public GVRComponent detachComponent(long type) {\n NativeSceneObject.detachComponent(getNative(), type);\n synchronized (mComponents) {\n GVRComponent component = mComponents.remove(type);\n if (component != null) {\n component.setOwnerObject(null);\n }\n return component;\n }\n }"
] | [
"public static sslciphersuite get(nitro_service service, String ciphername) throws Exception{\n\t\tsslciphersuite obj = new sslciphersuite();\n\t\tobj.set_ciphername(ciphername);\n\t\tsslciphersuite response = (sslciphersuite) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static <T> List<T> toList(Iterator<? extends T> iterator) {\n\t\treturn Lists.newArrayList(iterator);\n\t}",
"public static BoxUser.Info createAppUser(BoxAPIConnection api, String name) {\n return createAppUser(api, name, new CreateUserParams());\n }",
"public String getRemoteUrl(String defaultRemoteUrl) {\n if (StringUtils.isBlank(defaultRemoteUrl)) {\n RemoteConfig remoteConfig = getJenkinsScm().getRepositories().get(0);\n URIish uri = remoteConfig.getURIs().get(0);\n return uri.toPrivateString();\n }\n\n return defaultRemoteUrl;\n }",
"protected List<TransformationDescription> buildChildren() {\n if(children.isEmpty()) {\n return Collections.emptyList();\n }\n final List<TransformationDescription> children = new ArrayList<TransformationDescription>();\n for(final TransformationDescriptionBuilder builder : this.children) {\n children.add(builder.build());\n }\n return children;\n }",
"private void primeCache() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) {\n if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck\n handleUpdate(new TrackMetadataUpdate(entry.getKey().player, entry.getValue()));\n }\n }\n }\n });\n }",
"public boolean handleKeyDeletion(final String key) {\n\n if (m_keyset.getKeySet().contains(key)) {\n if (removeKeyForAllLanguages(key)) {\n m_keyset.removeKey(key);\n return true;\n } else {\n return false;\n }\n }\n return true;\n }",
"public static void validateClusterNodeCounts(final Cluster lhs, final Cluster rhs) {\n if(!lhs.getNodeIds().equals(rhs.getNodeIds())) {\n throw new VoldemortException(\"Node ids are not the same [ lhs cluster node ids (\"\n + lhs.getNodeIds()\n + \") not equal to rhs cluster node ids (\"\n + rhs.getNodeIds() + \") ]\");\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}"
] |
Use this API to fetch csvserver_copolicy_binding resources of given name . | [
"public static csvserver_copolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_copolicy_binding obj = new csvserver_copolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_copolicy_binding response[] = (csvserver_copolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public static dbdbprofile[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tdbdbprofile obj = new dbdbprofile();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tdbdbprofile[] response = (dbdbprofile[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"@SuppressWarnings(\"deprecation\")\n public BUILDER addAccessConstraint(final AccessConstraintDefinition accessConstraint) {\n if (accessConstraints == null) {\n accessConstraints = new AccessConstraintDefinition[] {accessConstraint};\n } else {\n accessConstraints = Arrays.copyOf(accessConstraints, accessConstraints.length + 1);\n accessConstraints[accessConstraints.length - 1] = accessConstraint;\n }\n return (BUILDER) this;\n }",
"public void setSchema(String schema)\n {\n if (schema.charAt(schema.length() - 1) != '.')\n {\n schema = schema + '.';\n }\n m_schema = schema;\n }",
"void flushLogQueue() {\n Set<String> problems = new LinkedHashSet<String>();\n synchronized (messageQueue) {\n Iterator<LogEntry> i = messageQueue.iterator();\n while (i.hasNext()) {\n problems.add(\"\\t\\t\" + i.next().getMessage() + \"\\n\");\n i.remove();\n }\n }\n if (!problems.isEmpty()) {\n logger.transformationWarnings(target.getHostName(), problems);\n }\n }",
"@JsonProperty(\"descriptions\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, TermImpl> getDescriptionUpdates() {\n \treturn getMonolingualUpdatedValues(newDescriptions);\n }",
"static BsonDocument getDocumentVersionDoc(final BsonDocument document) {\n if (document == null || !document.containsKey(DOCUMENT_VERSION_FIELD)) {\n return null;\n }\n return document.getDocument(DOCUMENT_VERSION_FIELD, null);\n }",
"public static boolean isPrimitiveWrapperArray(Class<?> clazz) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\treturn (clazz.isArray() && isPrimitiveWrapper(clazz.getComponentType()));\n\t}",
"public void setWidth(int width) {\n this.width = width;\n getElement().getStyle().setWidth(width, Style.Unit.PX);\n }",
"public static BatchASTFuture analyze(final BatchASTListener listener, final WildcardImportResolver importResolver,\n final Set<String> libraryPaths,\n final Set<String> sourcePaths, Set<Path> sourceFiles)\n {\n\n final String[] encodings = null;\n final String[] bindingKeys = new String[0];\n final ExecutorService executor = WindupExecutors.newFixedThreadPool(WindupExecutors.getDefaultThreadCount());\n final FileASTRequestor requestor = new FileASTRequestor()\n {\n @Override\n public void acceptAST(String sourcePath, CompilationUnit ast)\n {\n try\n {\n /*\n * This super() call doesn't do anything, but we call it just to be nice, in case that ever changes.\n */\n super.acceptAST(sourcePath, ast);\n ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, ast, sourcePath);\n ast.accept(visitor);\n listener.processed(Paths.get(sourcePath), visitor.getJavaClassReferences());\n }\n catch (WindupStopException ex)\n {\n throw ex;\n }\n catch (Throwable t)\n {\n listener.failed(Paths.get(sourcePath), t);\n }\n }\n };\n\n List<List<String>> batches = createBatches(sourceFiles);\n\n for (final List<String> batch : batches)\n {\n executor.submit(new Callable<Void>()\n {\n @Override\n public Void call() throws Exception\n {\n ASTParser parser = ASTParser.newParser(AST.JLS8);\n parser.setBindingsRecovery(false);\n parser.setResolveBindings(true);\n Map<String, String> options = JavaCore.getOptions();\n JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);\n // these options seem to slightly reduce the number of times that JDT aborts on compilation errors\n options.put(JavaCore.CORE_INCOMPLETE_CLASSPATH, \"warning\");\n options.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, \"warning\");\n options.put(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, \"warning\");\n options.put(JavaCore.CORE_CIRCULAR_CLASSPATH, \"warning\");\n options.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, \"warning\");\n options.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION, \"warning\");\n options.put(JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, \"ignore\");\n options.put(JavaCore.COMPILER_PB_NULL_ANNOTATION_INFERENCE_CONFLICT, \"warning\");\n options.put(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, \"warning\");\n options.put(JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, \"warning\");\n\n parser.setCompilerOptions(options);\n parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]),\n sourcePaths.toArray(new String[sourcePaths.size()]),\n null,\n true);\n\n parser.createASTs(batch.toArray(new String[batch.size()]), encodings, bindingKeys, requestor, null);\n return null;\n }\n });\n }\n\n executor.shutdown();\n\n return new BatchASTFuture()\n {\n @Override\n public boolean isDone()\n {\n return executor.isTerminated();\n }\n };\n }"
] |
Find all the values of the requested type.
@param valueTypeToFind the type of the value to return.
@param <T> the type of the value to find.
@return the key, value pairs found. | [
"@SuppressWarnings(\"unchecked\")\n public <T> Map<String, T> find(final Class<T> valueTypeToFind) {\n return (Map<String, T>) this.values.entrySet().stream()\n .filter(input -> valueTypeToFind.isInstance(input.getValue()))\n .collect(\n Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\n }"
] | [
"public static base_response update(nitro_service client, ipv6 resource) throws Exception {\n\t\tipv6 updateresource = new ipv6();\n\t\tupdateresource.ralearning = resource.ralearning;\n\t\tupdateresource.routerredirection = resource.routerredirection;\n\t\tupdateresource.ndbasereachtime = resource.ndbasereachtime;\n\t\tupdateresource.ndretransmissiontime = resource.ndretransmissiontime;\n\t\tupdateresource.natprefix = resource.natprefix;\n\t\tupdateresource.dodad = resource.dodad;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public RelatedTagsList getRelated(String tag) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_RELATED);\n\n parameters.put(\"tag\", tag);\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 Element tagsElement = response.getPayload();\n\n RelatedTagsList tags = new RelatedTagsList();\n tags.setSource(tagsElement.getAttribute(\"source\"));\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag t = new Tag();\n t.setValue(XMLUtilities.getValue(tagElement));\n tags.add(t);\n }\n return tags;\n }",
"public static base_responses clear(nitro_service client, gslbldnsentries resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbldnsentries clearresources[] = new gslbldnsentries[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tclearresources[i] = new gslbldnsentries();\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, clearresources,\"clear\");\n\t\t}\n\t\treturn result;\n\t}",
"public void close() throws SQLException {\r\n\t\ttry {\r\n\r\n\t\t\tif (this.resetConnectionOnClose /*FIXME: && !getAutoCommit() && !isTxResolved() */){\r\n\t\t\t\t/*if (this.autoCommitStackTrace != null){\r\n\t\t\t\t\t\tlogger.debug(this.autoCommitStackTrace);\r\n\t\t\t\t\t\tthis.autoCommitStackTrace = null; \r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tlogger.debug(DISABLED_AUTO_COMMIT_WARNING);\r\n\t\t\t\t\t}*/\r\n\t\t\t\trollback();\r\n\t\t\t\tif (!getAutoCommit()){\r\n\t\t\t\t\tsetAutoCommit(true);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (this.logicallyClosed.compareAndSet(false, true)) {\r\n\r\n\r\n\t\t\t\tif (this.threadWatch != null){\r\n\t\t\t\t\tthis.threadWatch.interrupt(); // if we returned the connection to the pool, terminate thread watch thread if it's\r\n\t\t\t\t\t// running even if thread is still alive (eg thread has been recycled for use in some\r\n\t\t\t\t\t// container).\r\n\t\t\t\t\tthis.threadWatch = null;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (this.closeOpenStatements){\r\n\t\t\t\t\tfor (Entry<Statement, String> statementEntry: this.trackedStatement.entrySet()){\r\n\t\t\t\t\t\tstatementEntry.getKey().close();\r\n\t\t\t\t\t\tif (this.detectUnclosedStatements){\r\n\t\t\t\t\t\t\tlogger.warn(String.format(UNCLOSED_LOG_ERROR_MESSAGE, statementEntry.getValue()));\t\t\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tthis.trackedStatement.clear();\r\n\t\t\t\t} \r\n\r\n\t\t\t\tif (!this.connectionTrackingDisabled){\r\n\t\t\t\t\tpool.getFinalizableRefs().remove(this.connection);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tConnectionHandle handle = null;\r\n\r\n\t\t\t\t//recreate can throw a SQLException in constructor on recreation\r\n\t\t\t\ttry {\r\n\t\t\t\t handle = this.recreateConnectionHandle();\r\n\t\t\t\t this.pool.connectionStrategy.cleanupConnection(this, handle);\r\n\t\t\t\t this.pool.releaseConnection(handle);\t\t\t\t \r\n\t\t\t\t} catch(SQLException e) {\r\n\t\t\t\t //check if the connection was already closed by the recreation\r\n\t\t\t\t if (!isClosed()) {\r\n\t\t\t\t \tthis.pool.connectionStrategy.cleanupConnection(this, handle);\r\n\t\t\t\t \tthis.pool.releaseConnection(this);\r\n\t\t\t\t }\r\n\t\t\t\t throw e;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\tif (this.doubleCloseCheck){\r\n\t\t\t\t\tthis.doubleCloseException = this.pool.captureStackTrace(CLOSED_TWICE_EXCEPTION_MESSAGE);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tif (this.doubleCloseCheck && this.doubleCloseException != null){\r\n\t\t\t\t\tString currentLocation = this.pool.captureStackTrace(\"Last closed trace from thread [\"+Thread.currentThread().getName()+\"]:\\n\");\r\n\t\t\t\t\tlogger.error(String.format(LOG_ERROR_MESSAGE, this.doubleCloseException, currentLocation));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (SQLException e) {\r\n\t\t\tthrow markPossiblyBroken(e);\r\n\t\t}\r\n\t}",
"public static TransactionalProtocolClient.PreparedOperation<TransactionalProtocolClient.Operation> executeBlocking(final ModelNode operation, TransactionalProtocolClient client) throws IOException, InterruptedException {\n final BlockingQueueOperationListener<TransactionalProtocolClient.Operation> listener = new BlockingQueueOperationListener<>();\n client.execute(listener, operation, OperationMessageHandler.DISCARD, OperationAttachments.EMPTY);\n return listener.retrievePreparedOperation();\n }",
"public void resetResendCount() {\n\t\tthis.resendCount = 0;\n\t\tif (this.initializationComplete)\n\t\t\tthis.nodeStage = NodeStage.NODEBUILDINFO_DONE;\n\t\tthis.lastUpdated = Calendar.getInstance().getTime();\n\t}",
"protected T createInstance() {\n try {\n Constructor<T> ctor = clazz.getDeclaredConstructor();\n ctor.setAccessible(true);\n return ctor.newInstance();\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (SecurityException e) {\n throw new RuntimeException(e);\n } catch (NoSuchMethodException e) {\n throw new RuntimeException(e);\n } catch (IllegalArgumentException e) {\n throw new RuntimeException(e);\n } catch (InvocationTargetException e) {\n throw new RuntimeException(e);\n }\n }",
"private static int getBlockLength(String text, int offset)\n {\n int startIndex = offset;\n boolean finished = false;\n char c;\n\n while (finished == false)\n {\n c = text.charAt(offset);\n switch (c)\n {\n case '\\r':\n case '\\n':\n case '}':\n {\n finished = true;\n break;\n }\n\n default:\n {\n ++offset;\n break;\n }\n }\n }\n\n int length = offset - startIndex;\n\n return (length);\n }",
"public ItemRequest<Task> update(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"PUT\");\n }"
] |
Finish initialization of state object.
@param geoService geo service
@param converterService converter service
@throws GeomajasException oops | [
"public void postConstruct(GeoService geoService, DtoConverterService converterService) throws GeomajasException {\n\t\tif (null == layerInfo) {\n\t\t\tlayerInfo = new RasterLayerInfo();\n\t\t}\n\t\tlayerInfo.setCrs(TiledRasterLayerService.MERCATOR);\n\t\tcrs = geoService.getCrs2(TiledRasterLayerService.MERCATOR);\n\t\tlayerInfo.setTileWidth(tileSize);\n\t\tlayerInfo.setTileHeight(tileSize);\n\t\tBbox bbox = new Bbox(-TiledRasterLayerService.HALF_EQUATOR_IN_METERS,\n\t\t\t\t-TiledRasterLayerService.HALF_EQUATOR_IN_METERS, TiledRasterLayerService.EQUATOR_IN_METERS,\n\t\t\t\tTiledRasterLayerService.EQUATOR_IN_METERS);\n\t\tlayerInfo.setMaxExtent(bbox);\n\t\tmaxBounds = converterService.toInternal(bbox);\n\n\t\tresolutions = new double[maxZoomLevel + 1];\n\t\tdouble powerOfTwo = 1;\n\t\tfor (int zoomLevel = 0; zoomLevel <= maxZoomLevel; zoomLevel++) {\n\t\t\tdouble resolution = (TiledRasterLayerService.EQUATOR_IN_METERS) / (tileSize * powerOfTwo);\n\t\t\tresolutions[zoomLevel] = resolution;\n\t\t\tpowerOfTwo *= 2;\n\t\t}\n\t}"
] | [
"public void createLinks(ServiceReference<D> declarationSRef) {\n D declaration = getDeclaration(declarationSRef);\n for (ServiceReference<S> serviceReference : linkerManagement.getMatchedBinderServiceRef()) {\n if (linkerManagement.canBeLinked(declaration, serviceReference)) {\n linkerManagement.link(declaration, serviceReference);\n }\n }\n }",
"public static boolean deleteDatabase(final StitchAppClientInfo appInfo,\n final String serviceName,\n final EmbeddedMongoClientFactory clientFactory,\n final String userId) {\n final String dataDir = appInfo.getDataDirectory();\n if (dataDir == null) {\n throw new IllegalArgumentException(\"StitchAppClient not configured with a data directory\");\n }\n\n final String instanceKey = String.format(\n \"%s-%s_sync_%s_%s\", appInfo.getClientAppId(), dataDir, serviceName, userId);\n final String dbPath = String.format(\n \"%s/%s/sync_mongodb_%s/%s/0/\", dataDir, appInfo.getClientAppId(), serviceName, userId);\n final MongoClient client =\n clientFactory.getClient(instanceKey, dbPath, appInfo.getCodecRegistry());\n\n for (final String listDatabaseName : client.listDatabaseNames()) {\n try {\n client.getDatabase(listDatabaseName).drop();\n } catch (Exception e) {\n // do nothing\n }\n }\n\n client.close();\n clientFactory.removeClient(instanceKey);\n\n return new File(dbPath).delete();\n }",
"@GET\n @Produces(MediaType.APPLICATION_JSON)\n @Path(\"/graph/{name}/{version}\")\n public Response getModuleGraph(@PathParam(\"name\") final String moduleName,\n @PathParam(\"version\") final String moduleVersion,\n @Context final UriInfo uriInfo){\n\n LOG.info(\"Dependency Checker got a get module graph export request.\");\n\n if(moduleName == null || moduleVersion == null){\n return Response.serverError().status(HttpStatus.NOT_ACCEPTABLE_406).build();\n }\n\n final FiltersHolder filters = new FiltersHolder();\n filters.init(uriInfo.getQueryParameters());\n\n final String moduleId = DbModule.generateID(moduleName, moduleVersion);\n final AbstractGraph moduleGraph = getGraphsHandler(filters).getModuleGraph(moduleId);\n\n return Response.ok(moduleGraph).build();\n }",
"public void normalize() {\n double lenSqr = x * x + y * y + z * z;\n double err = lenSqr - 1;\n if (err > (2 * DOUBLE_PREC) || err < -(2 * DOUBLE_PREC)) {\n double len = Math.sqrt(lenSqr);\n x /= len;\n y /= len;\n z /= len;\n }\n }",
"public static Filter.Builder makeAndFilter(Iterable<Filter> subfilters) {\n return Filter.newBuilder()\n .setCompositeFilter(CompositeFilter.newBuilder()\n .addAllFilters(subfilters)\n .setOp(CompositeFilter.Operator.AND));\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public String getProperty(Enum<?> key, boolean lowerCase) {\n final String keyName;\n if (lowerCase) {\n keyName = key.name().toLowerCase(Locale.ENGLISH);\n } else {\n keyName = key.name();\n }\n return getProperty(keyName);\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}",
"public String getPendingChanges() {\n JsonObject jsonObject = this.getPendingJSONObject();\n if (jsonObject == null) {\n return null;\n }\n\n return jsonObject.toString();\n }",
"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 }"
] |
Sets the origin and direction of the pick ray.
@param ox X coordinate of origin.
@param oy Y coordinate of origin.
@param oz Z coordinate of origin.
@param dx X coordinate of ray direction.
@param dy Y coordinate of ray direction.
@param dz Z coordinate of ray direction.
The coordinate system of the ray depends on the whether the
picker is attached to a scene object or not. When attached
to a scene object, the ray is in the coordinate system of
that object where (0, 0, 0) is the center of the scene object
and (0, 0, 1) is it's positive Z axis. If not attached to an
object, the ray is in the coordinate system of the scene's
main camera with (0, 0, 0) at the viewer and (0, 0, -1)
where the viewer is looking.
@see #doPick()
@see #getPickRay()
@see #getWorldPickRay(Vector3f, Vector3f) | [
"public void setPickRay(float ox, float oy, float oz, float dx, float dy, float dz)\n {\n synchronized (this)\n {\n mRayOrigin.x = ox;\n mRayOrigin.y = oy;\n mRayOrigin.z = oz;\n mRayDirection.x = dx;\n mRayDirection.y = dy;\n mRayDirection.z = dz;\n }\n }"
] | [
"public static final void deleteQuietly(File file)\n {\n if (file != null)\n {\n if (file.isDirectory())\n {\n File[] children = file.listFiles();\n if (children != null)\n {\n for (File child : children)\n {\n deleteQuietly(child);\n }\n }\n }\n file.delete();\n }\n }",
"public TransformersSubRegistration getHostRegistration(final ModelVersionRange range) {\n final PathAddress address = PathAddress.EMPTY_ADDRESS.append(HOST);\n return new TransformersSubRegistrationImpl(range, domain, address);\n }",
"public List<Index<Field>> allIndexes() {\n List<Index<Field>> indexesOfAnyType = new ArrayList<Index<Field>>();\n indexesOfAnyType.addAll(listIndexType(null, ListableIndex.class));\n return indexesOfAnyType;\n }",
"private static void listHierarchy(ProjectFile file)\n {\n for (Task task : file.getChildTasks())\n {\n System.out.println(\"Task: \" + task.getName() + \"\\t\" + task.getStart() + \"\\t\" + task.getFinish());\n listHierarchy(task, \" \");\n }\n\n System.out.println();\n }",
"protected final boolean isPatternValid() {\n\n switch (getPatternType()) {\n case DAILY:\n return isEveryWorkingDay() || isIntervalValid();\n case WEEKLY:\n return isIntervalValid() && isWeekDaySet();\n case MONTHLY:\n return isIntervalValid() && isWeekDaySet() ? isWeekOfMonthSet() : isDayOfMonthValid();\n case YEARLY:\n return isMonthSet() && isWeekDaySet() ? isWeekOfMonthSet() : isDayOfMonthValid();\n case INDIVIDUAL:\n case NONE:\n return true;\n default:\n return false;\n }\n }",
"@Nonnull\n public BufferedImage createBufferedImage(final int imageWidth, final int imageHeight) {\n return new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_4BYTE_ABGR);\n }",
"@Override\n\tpublic void handlePopups() {\n\t\t/*\n\t\t * try { executeJavaScript(\"window.alert = function(msg){return true;};\" +\n\t\t * \"window.confirm = function(msg){return true;};\" +\n\t\t * \"window.prompt = function(msg){return true;};\"); } catch (CrawljaxException e) {\n\t\t * LOGGER.error(\"Handling of PopUp windows failed\", e); }\n\t\t */\n\n\t\t/* Workaround: Popups handling currently not supported in PhantomJS. */\n\t\tif (browser instanceof PhantomJSDriver) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (ExpectedConditions.alertIsPresent().apply(browser) != null) {\n\t\t\ttry {\n\t\t\t\tbrowser.switchTo().alert().accept();\n\t\t\t\tLOGGER.info(\"Alert accepted\");\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOGGER.error(\"Handling of PopUp windows failed\");\n\t\t\t}\n\t\t}\n\t}",
"public void useNewRESTService(String address) throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n org.customer.service.CustomerService customerService = JAXRSClientFactory\n .createFromModel(address, \n org.customer.service.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n\n System.out.println(\"Using new RESTful CustomerService with new client\");\n\n customer.v2.Customer customer = createNewCustomer(\"Smith New REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith New REST\");\n printNewCustomerDetails(customer);\n }",
"private void updateDetail(TrackMetadataUpdate update, WaveformDetail detail) {\n detailHotCache.put(DeckReference.getDeckReference(update.player, 0), detail); // Main deck\n if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well\n for (CueList.Entry entry : update.metadata.getCueList().entries) {\n if (entry.hotCueNumber != 0) {\n detailHotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), detail);\n }\n }\n }\n deliverWaveformDetailUpdate(update.player, detail);\n }"
] |
Updates the indices in the index buffer from a Java CharBuffer.
All of the entries of the input buffer are copied into
the storage for the index buffer. The new indices must be the
same size as the old indices - the index buffer size cannot be changed.
@param data CharBuffer containing the new values
@throws IllegalArgumentException if char array is wrong size | [
"public void setShortVec(CharBuffer data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input data for indices cannot be null\");\n }\n if (getIndexSize() != 2)\n {\n throw new UnsupportedOperationException(\"Cannot update integer indices with char array\");\n }\n if (data.isDirect())\n {\n if (!NativeIndexBuffer.setShortVec(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input buffer is wrong size\");\n }\n }\n else if (data.hasArray())\n {\n if (!NativeIndexBuffer.setShortArray(getNative(), data.array()))\n {\n throw new UnsupportedOperationException(\"Input buffer is wrong size\");\n }\n }\n else\n {\n throw new UnsupportedOperationException(\n \"CharBuffer type not supported. Must be direct or have backing array\");\n }\n }"
] | [
"public Indexable taskResult(String taskId) {\n TaskGroupEntry<TaskItem> taskGroupEntry = super.getNode(taskId);\n if (taskGroupEntry != null) {\n return taskGroupEntry.taskResult();\n }\n if (!this.proxyTaskGroupWrapper.isActive()) {\n throw new IllegalArgumentException(\"A dependency task with id '\" + taskId + \"' is not found\");\n }\n taskGroupEntry = this.proxyTaskGroupWrapper.proxyTaskGroup.getNode(taskId);\n if (taskGroupEntry != null) {\n return taskGroupEntry.taskResult();\n }\n throw new IllegalArgumentException(\"A dependency task or 'post-run' dependent task with with id '\" + taskId + \"' not found\");\n }",
"private void addSequence(String sequenceName, HighLowSequence seq)\r\n {\r\n // lookup the sequence map for calling DB\r\n String jcdAlias = getBrokerForClass()\r\n .serviceConnectionManager().getConnectionDescriptor().getJcdAlias();\r\n Map mapForDB = (Map) sequencesDBMap.get(jcdAlias);\r\n if(mapForDB == null)\r\n {\r\n mapForDB = new HashMap();\r\n }\r\n mapForDB.put(sequenceName, seq);\r\n sequencesDBMap.put(jcdAlias, mapForDB);\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}",
"protected boolean isFiltered(Param param) {\n\t\tAbstractElement elementToParse = param.elementToParse;\n\t\twhile (elementToParse != null) {\n\t\t\tif (isFiltered(elementToParse, param)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telementToParse = getEnclosingSingleElementGroup(elementToParse);\n\t\t}\n\t\treturn false;\n\t}",
"public static Class<?> resolveReturnType(Method method, Class<?> clazz) {\n\t\tAssert.notNull(method, \"Method must not be null\");\n\t\tType genericType = method.getGenericReturnType();\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\tMap<TypeVariable, Type> typeVariableMap = getTypeVariableMap(clazz);\n\t\tType rawType = getRawType(genericType, typeVariableMap);\n\t\treturn (rawType instanceof Class ? (Class<?>) rawType : method.getReturnType());\n\t}",
"private void readTextsCompressed(File dir, HashMap results) throws IOException\r\n {\r\n if (dir.exists() && dir.isDirectory())\r\n {\r\n File[] files = dir.listFiles();\r\n\r\n for (int idx = 0; idx < files.length; idx++)\r\n {\r\n if (files[idx].isDirectory())\r\n {\r\n continue;\r\n }\r\n results.put(files[idx].getName(), readTextCompressed(files[idx]));\r\n }\r\n }\r\n }",
"public static wisite_binding get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_binding obj = new wisite_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_binding response = (wisite_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private String formatAccrueType(AccrueType type)\n {\n return (type == null ? null : LocaleData.getStringArray(m_locale, LocaleData.ACCRUE_TYPES)[type.getValue() - 1]);\n }",
"private static void flushCurrentWord( StringBuilder currentWords, List<Word> formattedWords, boolean cutWhitespace ) {\n if( currentWords.length() > 0 ) {\n if( cutWhitespace && currentWords.charAt( currentWords.length() - 1 ) == ' ' ) {\n currentWords.setLength( currentWords.length() - 1 );\n }\n formattedWords.add( new Word( currentWords.toString() ) );\n currentWords.setLength( 0 );\n }\n }"
] |
Use this API to fetch all the cacheselector resources that are configured on netscaler. | [
"public static cacheselector[] get(nitro_service service, options option) throws Exception{\n\t\tcacheselector obj = new cacheselector();\n\t\tcacheselector[] response = (cacheselector[])obj.get_resources(service,option);\n\t\treturn response;\n\t}"
] | [
"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}",
"public static FullTypeSignature getTypeSignature(String typeSignatureString,\n\t\t\tboolean useInternalFormFullyQualifiedName) {\n\t\tString key;\n\t\tif (!useInternalFormFullyQualifiedName) {\n\t\t\tkey = typeSignatureString.replace('.', '/')\n\t\t\t\t\t.replace('$', '.');\n\t\t} else {\n\t\t\tkey = typeSignatureString;\n\t\t}\n\n\t\t// we always use the internal form as a key for cache\n\t\tFullTypeSignature typeSignature = typeSignatureCache\n\t\t\t\t.get(key);\n\t\tif (typeSignature == null) {\n\t\t\tClassFileTypeSignatureParser typeSignatureParser = new ClassFileTypeSignatureParser(\n\t\t\t\t\ttypeSignatureString);\n\t\t\ttypeSignatureParser.setUseInternalFormFullyQualifiedName(useInternalFormFullyQualifiedName);\n\t\t\ttypeSignature = typeSignatureParser.parseTypeSignature();\n\t\t\ttypeSignatureCache.put(typeSignatureString, typeSignature);\n\t\t}\n\t\treturn typeSignature;\n\t}",
"public boolean getBooleanProperty(String name, boolean defaultValue)\r\n {\r\n return PropertyHelper.toBoolean(_properties.getProperty(name), defaultValue);\r\n }",
"synchronized long storeUserProfile(String id, JSONObject obj) {\n\n if (id == null) return DB_UPDATE_ERROR;\n\n if (!this.belowMemThreshold()) {\n getConfigLogger().verbose(\"There is not enough space left on the device to store data, data discarded\");\n return DB_OUT_OF_MEMORY_ERROR;\n }\n\n final String tableName = Table.USER_PROFILES.getName();\n\n long ret = DB_UPDATE_ERROR;\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n final ContentValues cv = new ContentValues();\n cv.put(KEY_DATA, obj.toString());\n cv.put(\"_id\", id);\n ret = db.insertWithOnConflict(tableName, null, cv, SQLiteDatabase.CONFLICT_REPLACE);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error adding data to table \" + tableName + \" Recreating DB\");\n dbHelper.deleteDatabase();\n } finally {\n dbHelper.close();\n }\n return ret;\n }",
"private void countGender(EntityIdValue gender, SiteRecord siteRecord) {\n\t\tInteger curValue = siteRecord.genderCounts.get(gender);\n\t\tif (curValue == null) {\n\t\t\tsiteRecord.genderCounts.put(gender, 1);\n\t\t} else {\n\t\t\tsiteRecord.genderCounts.put(gender, curValue + 1);\n\t\t}\n\t}",
"protected CmsProject createAndSetModuleImportProject(CmsObject cms, CmsModule module) throws CmsException {\n\n CmsProject importProject = cms.createProject(\n org.opencms.module.Messages.get().getBundle(cms.getRequestContext().getLocale()).key(\n org.opencms.module.Messages.GUI_IMPORT_MODULE_PROJECT_NAME_1,\n new Object[] {module.getName()}),\n org.opencms.module.Messages.get().getBundle(cms.getRequestContext().getLocale()).key(\n org.opencms.module.Messages.GUI_IMPORT_MODULE_PROJECT_DESC_1,\n new Object[] {module.getName()}),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n CmsProject.PROJECT_TYPE_TEMPORARY);\n cms.getRequestContext().setCurrentProject(importProject);\n cms.copyResourceToProject(\"/\");\n return importProject;\n }",
"@Override\n public void finish() {\n if (started.get() && !finished.getAndSet(true)) {\n waitUntilFinished();\n super.finish();\n // recreate thread (don't start) for processor reuse\n createProcessorThread();\n clearQueues();\n started.set(false);\n }\n }",
"int getDelay(int n) {\n int delay = -1;\n if ((n >= 0) && (n < header.frameCount)) {\n delay = header.frames.get(n).delay;\n }\n return delay;\n }",
"public boolean matches(Property property) {\n return property.getName().equals(key) && (value == WILDCARD_VALUE || property.getValue().asString().equals(value));\n }"
] |
Takes an HTML file, looks for the first instance of the specified insertion point, and
inserts the diagram image reference and a client side map in that point. | [
"private static void alterHtmlDocs(Options opt, String outputFolder, String packageName, String className,\n\t String htmlFileName, Pattern insertPointPattern, RootDoc root) throws IOException {\n\t// setup files\n\tFile output = new File(outputFolder, packageName.replace(\".\", \"/\"));\n\tFile htmlFile = new File(output, htmlFileName);\n\tFile alteredFile = new File(htmlFile.getAbsolutePath() + \".uml\");\n\tif (!htmlFile.exists()) {\n\t System.err.println(\"Expected file not found: \" + htmlFile.getAbsolutePath());\n\t return;\n\t}\n\n\t// parse & rewrite\n\tBufferedWriter writer = null;\n\tBufferedReader reader = null;\n\tboolean matched = false;\n\ttry {\n\t writer = new BufferedWriter(new OutputStreamWriter(new\n\t\t FileOutputStream(alteredFile), opt.outputEncoding));\n\t reader = new BufferedReader(new InputStreamReader(new\n\t\t FileInputStream(htmlFile), opt.outputEncoding));\n\n\t String line;\n\t while ((line = reader.readLine()) != null) {\n\t\twriter.write(line);\n\t\twriter.newLine();\n\t\tif (!matched && insertPointPattern.matcher(line).matches()) {\n\t\t matched = true;\n\t\t\t\n\t\t String tag;\n\t\t if (opt.autoSize)\n\t\t tag = String.format(UML_AUTO_SIZED_DIV_TAG, className);\n\t\t else\n tag = String.format(UML_DIV_TAG, className);\n\t\t if (opt.collapsibleDiagrams)\n\t\t \ttag = String.format(EXPANDABLE_UML, tag, \"Show UML class diagram\", \"Hide UML class diagram\");\n\t\t writer.write(\"<!-- UML diagram added by UMLGraph version \" +\n\t\t \t\tVersion.VERSION + \n\t\t\t\t\" (http://www.spinellis.gr/umlgraph/) -->\");\n\t\t writer.newLine();\n\t\t writer.write(tag);\n\t\t writer.newLine();\n\t\t}\n\t }\n\t} finally {\n\t if (writer != null)\n\t\twriter.close();\n\t if (reader != null)\n\t\treader.close();\n\t}\n\n\t// if altered, delete old file and rename new one to the old file name\n\tif (matched) {\n\t htmlFile.delete();\n\t alteredFile.renameTo(htmlFile);\n\t} else {\n\t root.printNotice(\"Warning, could not find a line that matches the pattern '\" + insertPointPattern.pattern() \n\t\t + \"'.\\n Class diagram reference not inserted\");\n\t alteredFile.delete();\n\t}\n }"
] | [
"private void readTableBlock(int startIndex, int blockLength)\n {\n for (int index = startIndex; index < (startIndex + blockLength - 11); index++)\n {\n if (matchPattern(TABLE_BLOCK_PATTERNS, index))\n {\n int offset = index + 7;\n int nameLength = FastTrackUtility.getInt(m_buffer, offset);\n offset += 4;\n String name = new String(m_buffer, offset, nameLength, CharsetHelper.UTF16LE).toUpperCase();\n FastTrackTableType type = REQUIRED_TABLES.get(name);\n if (type != null)\n {\n m_currentTable = new FastTrackTable(type, this);\n m_tables.put(type, m_currentTable);\n }\n else\n {\n m_currentTable = null;\n }\n m_currentFields.clear();\n break;\n }\n }\n }",
"public Collection<Contact> getListRecentlyUploaded(Date lastUpload, String filter) throws FlickrException {\r\n List<Contact> contacts = new ArrayList<Contact>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST_RECENTLY_UPLOADED);\r\n\r\n if (lastUpload != null) {\r\n parameters.put(\"date_lastupload\", String.valueOf(lastUpload.getTime() / 1000L));\r\n }\r\n if (filter != null) {\r\n parameters.put(\"filter\", filter);\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\r\n Element contactsElement = response.getPayload();\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 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 double huntKennedyCMSAdjustedRate(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble swapAnnuity,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble swapMaturity,\n\t\t\tdouble payoffUnit)\n\t{\n\t\tdouble a = 1.0/swapMaturity;\n\t\tdouble b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;\n\t\tdouble convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);\n\n\t\tdouble rateUnadjusted\t= forwardSwaprate;\n\t\tdouble rateAdjusted\t\t= forwardSwaprate * convexityAdjustment;\n\n\t\treturn (a * rateUnadjusted + b * forwardSwaprate * rateAdjusted) * swapAnnuity / payoffUnit;\n\t}",
"public int addCollidable(GVRSceneObject sceneObj)\n {\n synchronized (mCollidables)\n {\n int index = mCollidables.indexOf(sceneObj);\n if (index >= 0)\n {\n return index;\n }\n mCollidables.add(sceneObj);\n return mCollidables.size() - 1;\n }\n }",
"protected int compare(MethodDesc o1, MethodDesc o2) {\n\t\tfinal Class<?>[] paramTypes1 = o1.getParameterTypes();\n\t\tfinal Class<?>[] paramTypes2 = o2.getParameterTypes();\n\n\t\t// sort by parameter types from left to right\n\t\tfor (int i = 0; i < paramTypes1.length; i++) {\n\t\t\tfinal Class<?> class1 = paramTypes1[i];\n\t\t\tfinal Class<?> class2 = paramTypes2[i];\n\n\t\t\tif (class1.equals(class2))\n\t\t\t\tcontinue;\n\t\t\tif (class1.isAssignableFrom(class2) || Void.class.equals(class2))\n\t\t\t\treturn -1;\n\t\t\tif (class2.isAssignableFrom(class1) || Void.class.equals(class1))\n\t\t\t\treturn 1;\n\t\t}\n\n\t\t// sort by declaring class (more specific comes first).\n\t\tif (!o1.getDeclaringClass().equals(o2.getDeclaringClass())) {\n\t\t\tif (o1.getDeclaringClass().isAssignableFrom(o2.getDeclaringClass()))\n\t\t\t\treturn 1;\n\t\t\tif (o2.getDeclaringClass().isAssignableFrom(o1.getDeclaringClass()))\n\t\t\t\treturn -1;\n\t\t}\n\n\t\t// sort by target\n\t\tfinal int compareTo = ((Integer) targets.indexOf(o2.target)).compareTo(targets.indexOf(o1.target));\n\t\treturn compareTo;\n\t}",
"public ConditionalExpectationEstimator getConditionalExpectationEstimator(double exerciseTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException {\r\n\t\tRandomVariable[] regressionBasisFunctions = regressionBasisFunctionProvider.getBasisFunctions(exerciseTime, model);\r\n\t\treturn conditionalExpectationRegressionFactory.getConditionalExpectationEstimator(regressionBasisFunctions, regressionBasisFunctions);\r\n\t}",
"public static base_response restore(nitro_service client, appfwprofile resource) throws Exception {\n\t\tappfwprofile restoreresource = new appfwprofile();\n\t\trestoreresource.archivename = resource.archivename;\n\t\treturn restoreresource.perform_operation(client,\"restore\");\n\t}",
"static synchronized void clearLogContext() {\n final LogContext embeddedLogContext = Holder.LOG_CONTEXT;\n // Remove the configurator and clear the log context\n final Configurator configurator = embeddedLogContext.getLogger(\"\").detach(Configurator.ATTACHMENT_KEY);\n // If this was a PropertyConfigurator we can use the LogContextConfiguration API to tear down the LogContext\n if (configurator instanceof PropertyConfigurator) {\n final LogContextConfiguration logContextConfiguration = ((PropertyConfigurator) configurator).getLogContextConfiguration();\n clearLogContext(logContextConfiguration);\n } else if (configurator instanceof LogContextConfiguration) {\n clearLogContext((LogContextConfiguration) configurator);\n } else {\n // Remove all the handlers and close them as well as reset the loggers\n final List<String> loggerNames = Collections.list(embeddedLogContext.getLoggerNames());\n for (String name : loggerNames) {\n final Logger logger = embeddedLogContext.getLoggerIfExists(name);\n if (logger != null) {\n final Handler[] handlers = logger.clearHandlers();\n if (handlers != null) {\n for (Handler handler : handlers) {\n handler.close();\n }\n }\n logger.setFilter(null);\n logger.setUseParentFilters(false);\n logger.setUseParentHandlers(true);\n logger.setLevel(Level.INFO);\n }\n }\n }\n }",
"public <T extends Variable> T lookupVariable(String token) {\n Variable result = variables.get(token);\n return (T)result;\n }"
] |
Print an extended attribute value.
@param writer parent MSPDIWriter instance
@param value attribute value
@param type type of the value being passed
@return string representation | [
"public static final String printExtendedAttribute(MSPDIWriter writer, Object value, DataType type)\n {\n String result;\n\n if (type == DataType.DATE)\n {\n result = printExtendedAttributeDate((Date) value);\n }\n else\n {\n if (value instanceof Boolean)\n {\n result = printExtendedAttributeBoolean((Boolean) value);\n }\n else\n {\n if (value instanceof Duration)\n {\n result = printDuration(writer, (Duration) value);\n }\n else\n {\n if (type == DataType.CURRENCY)\n {\n result = printExtendedAttributeCurrency((Number) value);\n }\n else\n {\n if (value instanceof Number)\n {\n result = printExtendedAttributeNumber((Number) value);\n }\n else\n {\n result = value.toString();\n }\n }\n }\n }\n }\n\n return (result);\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 DockerContainerObjectBuilder<T> withContainerObjectClass(Class<T> containerObjectClass) {\n if (containerObjectClass == null) {\n throw new IllegalArgumentException(\"container object class cannot be null\");\n }\n this.containerObjectClass = containerObjectClass;\n\n //First we check if this ContainerObject is defining a @CubeDockerFile in static method\n final List<Method> methodsWithCubeDockerFile =\n ReflectionUtil.getMethodsWithAnnotation(containerObjectClass, CubeDockerFile.class);\n\n if (methodsWithCubeDockerFile.size() > 1) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Methods where annotation was found are: %s\",\n CubeDockerFile.class.getSimpleName(), methodsWithCubeDockerFile));\n }\n\n classHasMethodWithCubeDockerFile = !methodsWithCubeDockerFile.isEmpty();\n classDefinesCubeDockerFile = containerObjectClass.isAnnotationPresent(CubeDockerFile.class);\n classDefinesImage = containerObjectClass.isAnnotationPresent(Image.class);\n\n if (classHasMethodWithCubeDockerFile) {\n methodWithCubeDockerFile = methodsWithCubeDockerFile.get(0);\n boolean isMethodStatic = Modifier.isStatic(methodWithCubeDockerFile.getModifiers());\n boolean methodHasNoArguments = methodWithCubeDockerFile.getParameterCount() == 0;\n boolean methodReturnsAnArchive = Archive.class.isAssignableFrom(methodWithCubeDockerFile.getReturnType());\n if (!isMethodStatic || !methodHasNoArguments || !methodReturnsAnArchive) {\n throw new IllegalArgumentException(\n String.format(\"Method %s annotated with %s is expected to be static, no args and return %s.\",\n methodWithCubeDockerFile, CubeDockerFile.class.getSimpleName(), Archive.class.getSimpleName()));\n }\n }\n\n // User has defined @CubeDockerfile on the class and a method\n if (classHasMethodWithCubeDockerFile && classDefinesCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Both class and method %s has the annotation.\",\n CubeDockerFile.class.getSimpleName(), methodWithCubeDockerFile));\n }\n\n // User has defined @CubeDockerfile and @Image\n if ((classHasMethodWithCubeDockerFile || classDefinesCubeDockerFile) && classDefinesImage) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s has defined %s annotation and %s annotation together.\",\n containerObjectClass.getSimpleName(), Image.class.getSimpleName(),\n CubeDockerFile.class.getSimpleName()));\n }\n\n // User has not defined either @CubeDockerfile or @Image\n if (!classDefinesCubeDockerFile && !classDefinesImage && !classHasMethodWithCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s is not annotated with either %s or %s annotations.\",\n containerObjectClass.getName(), CubeDockerFile.class.getSimpleName(), Image.class.getSimpleName()));\n }\n\n return this;\n }",
"private void setMasterTempo(double newTempo) {\n double oldTempo = Double.longBitsToDouble(masterTempo.getAndSet(Double.doubleToLongBits(newTempo)));\n if ((getTempoMaster() != null) && (Math.abs(newTempo - oldTempo) > getTempoEpsilon())) {\n // This is a change in tempo, so report it to any registered listeners, and update our metronome if we are synced.\n if (isSynced()) {\n metronome.setTempo(newTempo);\n notifyBeatSenderOfChange();\n }\n deliverTempoChangedAnnouncement(newTempo);\n }\n }",
"@Override\n public void setValue(Boolean value, boolean fireEvents) {\n boolean oldValue = getValue();\n if (value) {\n input.getElement().setAttribute(\"checked\", \"true\");\n } else {\n input.getElement().removeAttribute(\"checked\");\n }\n\n if (fireEvents && oldValue != value) {\n ValueChangeEvent.fire(this, getValue());\n }\n }",
"public void setMenuView(int layoutResId) {\n mMenuContainer.removeAllViews();\n mMenuView = LayoutInflater.from(getContext()).inflate(layoutResId, mMenuContainer, false);\n mMenuContainer.addView(mMenuView);\n }",
"private void processKeyValue(Map<ConfigurationKey, Object> properties, ConfigurationKey key, Object value) {\n if (value instanceof String) {\n value = key.convertValue((String) value);\n }\n if (key.isValidValue(value)) {\n Object previous = properties.put(key, value);\n if (previous != null && !previous.equals(value)) {\n throw ConfigurationLogger.LOG.configurationKeyHasDifferentValues(key.get(), previous, value);\n }\n } else {\n throw ConfigurationLogger.LOG.invalidConfigurationPropertyValue(value, key.get());\n }\n }",
"private void saveToBundleDescriptor() throws CmsException {\n\n if (null != m_descFile) {\n m_removeDescriptorOnCancel = false;\n updateBundleDescriptorContent();\n m_descFile.getFile().setContents(m_descContent.marshal());\n m_cms.writeFile(m_descFile.getFile());\n }\n }",
"public void addItem(T value, String text, boolean reload) {\n values.add(value);\n listBox.addItem(text, keyFactory.generateKey(value));\n\n if (reload) {\n reload();\n }\n }",
"private String getPropertyName(Method method)\n {\n String result = method.getName();\n if (result.startsWith(\"get\"))\n {\n result = result.substring(3);\n }\n return result;\n }"
] |
Apply the layout to the each page in the list
@param itemLayout item layout in the page
@return true if the new layout is applied successfully, otherwise - false | [
"@Override\n public boolean applyLayout(Layout itemLayout) {\n boolean applied = false;\n if (itemLayout != null && mItemLayouts.add(itemLayout)) {\n\n // apply the layout to all visible pages\n List<Widget> views = getAllViews();\n for (Widget view: views) {\n view.applyLayout(itemLayout.clone());\n }\n applied = true;\n }\n return applied;\n }"
] | [
"protected Boolean getEscapeQueryChars() {\n\n Boolean isEscape = parseOptionalBooleanValue(m_configObject, JSON_KEY_ESCAPE_QUERY_CHARACTERS);\n return (null == isEscape) && (m_baseConfig != null)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getEscapeQueryChars())\n : isEscape;\n }",
"final protected String getTrimmedString() throws BadMessage {\n if (_bufferPosition == 0) return \"\";\n\n int start = 0;\n boolean quoted = false;\n // Look for start\n while (start < _bufferPosition) {\n final char ch = _internalBuffer[start];\n if (ch == '\"') {\n quoted = true;\n break;\n }\n else if (ch != HttpTokens.SPACE && ch != HttpTokens.TAB) {\n break;\n }\n start++;\n }\n\n int end = _bufferPosition; // Position is of next write\n\n // Look for end\n while(end > start) {\n final char ch = _internalBuffer[end - 1];\n\n if (quoted) {\n if (ch == '\"') break;\n else if (ch != HttpTokens.SPACE && ch != HttpTokens.TAB) {\n throw new BadMessage(\"String might not quoted correctly: '\" + getString() + \"'\");\n }\n }\n else if (ch != HttpTokens.SPACE && ch != HttpTokens.TAB) break;\n end--;\n }\n\n String str = new String(_internalBuffer, start, end - start);\n\n return str;\n }",
"public static appfwpolicylabel_stats get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_stats obj = new appfwpolicylabel_stats();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_stats response = (appfwpolicylabel_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public String makeReport(String name, String report) {\n long increment = Long.valueOf(report);\n long currentLineCount = globalLineCounter.addAndGet(increment);\n\n if (currentLineCount >= maxScenarios) {\n return \"exit\";\n } else {\n return \"ok\";\n }\n }",
"private static String toColumnName(String fieldName) {\n int lastDot = fieldName.indexOf('.');\n if (lastDot > -1) {\n return fieldName.substring(lastDot + 1);\n } else {\n return fieldName;\n }\n }",
"public static void Backward(double[] data) {\n\n double[] result = new double[data.length];\n double sum;\n double scale = Math.sqrt(2.0 / data.length);\n for (int t = 0; t < data.length; t++) {\n sum = 0;\n for (int j = 0; j < data.length; j++) {\n double cos = Math.cos(((2 * t + 1) * j * Math.PI) / (2 * data.length));\n sum += alpha(j) * data[j] * cos;\n }\n result[t] = scale * sum;\n }\n for (int i = 0; i < data.length; i++) {\n data[i] = result[i];\n }\n }",
"public void setTabs(ArrayList<String>tabs) {\n if (tabs == null || tabs.size() <= 0) return;\n\n if (platformSupportsTabs) {\n ArrayList<String> toAdd;\n if (tabs.size() > MAX_TABS) {\n toAdd = new ArrayList<>(tabs.subList(0, MAX_TABS));\n } else {\n toAdd = tabs;\n }\n this.tabs = toAdd.toArray(new String[0]);\n } else {\n Logger.d(\"Please upgrade com.android.support:design library to v28.0.0 to enable Tabs for App Inbox, dropping Tabs\");\n }\n }",
"public static appfwwsdl get(nitro_service service, String name) throws Exception{\n\t\tappfwwsdl obj = new appfwwsdl();\n\t\tobj.set_name(name);\n\t\tappfwwsdl response = (appfwwsdl) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static String removeOpenCmsContext(final String path) {\n\n String context = OpenCms.getSystemInfo().getOpenCmsContext();\n if (path.startsWith(context + \"/\")) {\n return path.substring(context.length());\n }\n String renderPrefix = OpenCms.getStaticExportManager().getVfsPrefix();\n if (path.startsWith(renderPrefix + \"/\")) {\n return path.substring(renderPrefix.length());\n }\n return path;\n }"
] |
Removes all the given tags from the document.
@param dom the document object.
@param tagName the tag name, examples: script, style, meta
@return the changed dom. | [
"public static Document removeTags(Document dom, String tagName) {\n NodeList list;\n try {\n list = XPathHelper.evaluateXpathExpression(dom,\n \"//\" + tagName.toUpperCase());\n\n while (list.getLength() > 0) {\n Node sc = list.item(0);\n\n if (sc != null) {\n sc.getParentNode().removeChild(sc);\n }\n\n list = XPathHelper.evaluateXpathExpression(dom,\n \"//\" + tagName.toUpperCase());\n }\n } catch (XPathExpressionException e) {\n LOGGER.error(\"Error while removing tag \" + tagName, e);\n }\n\n return dom;\n\n }"
] | [
"public static dos_stats get(nitro_service service, options option) throws Exception{\n\t\tdos_stats obj = new dos_stats();\n\t\tdos_stats[] response = (dos_stats[])obj.stat_resources(service,option);\n\t\treturn response[0];\n\t}",
"public static vpath_stats get(nitro_service service) throws Exception{\n\t\tvpath_stats obj = new vpath_stats();\n\t\tvpath_stats[] response = (vpath_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}",
"private D createAndRegisterDeclaration(Map<String, Object> metadata) {\n D declaration;\n if (klass.equals(ImportDeclaration.class)) {\n declaration = (D) ImportDeclarationBuilder.fromMetadata(metadata).build();\n } else if (klass.equals(ExportDeclaration.class)) {\n declaration = (D) ExportDeclarationBuilder.fromMetadata(metadata).build();\n } else {\n throw new IllegalStateException(\"\");\n }\n declarationRegistrationManager.registerDeclaration(declaration);\n return declaration;\n }",
"protected TypeReference<?> getBeanPropertyType(Class<?> clazz,\r\n\t\t\tString propertyName, TypeReference<?> originalType) {\r\n\t\tTypeReference<?> propertyDestinationType = null;\r\n\t\tif (beanDestinationPropertyTypeProvider != null) {\r\n\t\t\tpropertyDestinationType = beanDestinationPropertyTypeProvider\r\n\t\t\t\t\t.getPropertyType(clazz, propertyName, originalType);\r\n\t\t}\r\n\t\tif (propertyDestinationType == null) {\r\n\t\t\tpropertyDestinationType = originalType;\r\n\t\t}\r\n\t\treturn propertyDestinationType;\r\n\t}",
"@SuppressWarnings(\"unchecked\")\n public static <T> AttachmentKey<T> create(final Class<? super T> valueClass) {\n return new SimpleAttachmentKey(valueClass);\n }",
"public static String getGetterName(String propertyName, Class type) {\n String prefix = type == boolean.class || type == Boolean.class ? \"is\" : \"get\";\n return prefix + MetaClassHelper.capitalize(propertyName);\n }",
"public double getAccruedInterest(double time, AnalyticModel model) {\n\t\tLocalDate date= FloatingpointDate.getDateFromFloatingPointDate(schedule.getReferenceDate(), time);\n\t\treturn getAccruedInterest(date, model);\n\t}",
"void handleFacebookError(HttpStatus statusCode, FacebookError error) {\n\t\tif (error != null && error.getCode() != null) {\n\t\t\tint code = error.getCode();\n\t\t\t\n\t\t\tif (code == UNKNOWN) {\n\t\t\t\tthrow new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);\n\t\t\t} else if (code == SERVICE) {\n\t\t\t\tthrow new ServerException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == TOO_MANY_CALLS || code == USER_TOO_MANY_CALLS || code == EDIT_FEED_TOO_MANY_USER_CALLS || code == EDIT_FEED_TOO_MANY_USER_ACTION_CALLS) {\n\t\t\t\tthrow new RateLimitExceededException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PERMISSION_DENIED || isUserPermissionError(code)) {\n\t\t\t\tthrow new InsufficientPermissionException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PARAM_SESSION_KEY || code == PARAM_SIGNATURE) {\n\t\t\t\tthrow new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == null) {\n\t\t\t\tthrow new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == 463) {\n\t\t\t\tthrow new ExpiredAuthorizationException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN) {\n\t\t\t\tthrow new RevokedAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == MESG_DUPLICATE) { \n\t\t\t\tthrow new DuplicateStatusException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == DATA_OBJECT_NOT_FOUND || code == PATH_UNKNOWN) {\n\t\t\t\tthrow new ResourceNotFoundException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else {\n\t\t\t\tthrow new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);\n\t\t\t}\n\t\t}\n\n\t}",
"public final ProcessorDependencyGraph getProcessorGraph() {\n if (this.processorGraph == null) {\n synchronized (this) {\n if (this.processorGraph == null) {\n final Map<String, Class<?>> attcls = new HashMap<>();\n for (Map.Entry<String, Attribute> attribute: this.attributes.entrySet()) {\n attcls.put(attribute.getKey(), attribute.getValue().getValueType());\n }\n this.processorGraph = this.processorGraphFactory.build(this.processors, attcls);\n }\n }\n }\n return this.processorGraph;\n }"
] |
Wrapper to avoid throwing an exception over JMX | [
"@JmxOperation\n public String stopAsyncOperation(int requestId) {\n try {\n stopOperation(requestId);\n } catch(VoldemortException e) {\n return e.getMessage();\n }\n\n return \"Stopping operation \" + requestId;\n }"
] | [
"protected RollbackPatch createRollbackPatch(final String patchId, final Patch.PatchType patchType) {\n // Process elements\n final List<PatchElement> elements = new ArrayList<PatchElement>();\n // Process layers\n for (final PatchEntry entry : getLayers()) {\n final PatchElement element = createRollbackElement(entry);\n elements.add(element);\n }\n // Process add-ons\n for (final PatchEntry entry : getAddOns()) {\n final PatchElement element = createRollbackElement(entry);\n elements.add(element);\n }\n\n final InstalledIdentity installedIdentity = modification.getUnmodifiedInstallationState();\n final String name = installedIdentity.getIdentity().getName();\n final IdentityImpl identity = new IdentityImpl(name, modification.getVersion());\n if (patchType == Patch.PatchType.CUMULATIVE) {\n identity.setPatchType(Patch.PatchType.CUMULATIVE);\n identity.setResultingVersion(installedIdentity.getIdentity().getVersion());\n } else if (patchType == Patch.PatchType.ONE_OFF) {\n identity.setPatchType(Patch.PatchType.ONE_OFF);\n }\n final List<ContentModification> modifications = identityEntry.rollbackActions;\n final Patch delegate = new PatchImpl(patchId, \"rollback patch\", identity, elements, modifications);\n return new PatchImpl.RollbackPatchImpl(delegate, installedIdentity);\n }",
"public void removeMarker(Marker marker) {\n if (markers != null && markers.contains(marker)) {\n markers.remove(marker);\n }\n marker.setMap(null);\n }",
"private boolean shouldWrapMethodCall(String methodName) {\n if (methodList == null) {\n return true; // Wrap all by default\n }\n\n if (methodList.contains(methodName)) {\n return true; //Wrap a specific method\n }\n\n // If I get to this point, I should not wrap the call.\n return false;\n }",
"public static int optionLength(String option) {\n if(matchOption(option, \"qualify\", true) ||\n matchOption(option, \"qualifyGenerics\", true) ||\n matchOption(option, \"hideGenerics\", true) ||\n matchOption(option, \"horizontal\", true) ||\n matchOption(option, \"all\") ||\n matchOption(option, \"attributes\", true) ||\n matchOption(option, \"enumconstants\", true) ||\n matchOption(option, \"operations\", true) ||\n matchOption(option, \"enumerations\", true) ||\n matchOption(option, \"constructors\", true) ||\n matchOption(option, \"visibility\", true) ||\n matchOption(option, \"types\", true) ||\n matchOption(option, \"autosize\", true) ||\n matchOption(option, \"commentname\", true) ||\n matchOption(option, \"nodefontabstractitalic\", true) ||\n matchOption(option, \"postfixpackage\", true) ||\n matchOption(option, \"noguillemot\", true) ||\n matchOption(option, \"views\", true) ||\n matchOption(option, \"inferrel\", true) ||\n matchOption(option, \"useimports\", true) ||\n matchOption(option, \"collapsible\", true) ||\n matchOption(option, \"inferdep\", true) ||\n matchOption(option, \"inferdepinpackage\", true) ||\n matchOption(option, \"hideprivateinner\", true) ||\n matchOption(option, \"compact\", true))\n\n return 1;\n else if(matchOption(option, \"nodefillcolor\") ||\n matchOption(option, \"nodefontcolor\") ||\n matchOption(option, \"nodefontsize\") ||\n matchOption(option, \"nodefontname\") ||\n matchOption(option, \"nodefontclasssize\") ||\n matchOption(option, \"nodefontclassname\") ||\n matchOption(option, \"nodefonttagsize\") ||\n matchOption(option, \"nodefonttagname\") ||\n matchOption(option, \"nodefontpackagesize\") ||\n matchOption(option, \"nodefontpackagename\") ||\n matchOption(option, \"edgefontcolor\") ||\n matchOption(option, \"edgecolor\") ||\n matchOption(option, \"edgefontsize\") ||\n matchOption(option, \"edgefontname\") ||\n matchOption(option, \"shape\") ||\n matchOption(option, \"output\") ||\n matchOption(option, \"outputencoding\") ||\n matchOption(option, \"bgcolor\") ||\n matchOption(option, \"hide\") ||\n matchOption(option, \"include\") ||\n matchOption(option, \"apidocroot\") ||\n matchOption(option, \"apidocmap\") ||\n matchOption(option, \"d\") ||\n matchOption(option, \"view\") ||\n matchOption(option, \"inferreltype\") ||\n matchOption(option, \"inferdepvis\") ||\n matchOption(option, \"collpackages\") ||\n matchOption(option, \"nodesep\") ||\n matchOption(option, \"ranksep\") ||\n matchOption(option, \"dotexecutable\") ||\n matchOption(option, \"link\"))\n return 2;\n else if(matchOption(option, \"contextPattern\") ||\n matchOption(option, \"linkoffline\"))\n return 3;\n else\n return 0;\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 void createResourceFieldMap(Props props)\n {\n byte[] fieldMapData = null;\n for (Integer key : RESOURCE_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData == null)\n {\n populateDefaultData(getDefaultResourceData());\n }\n else\n {\n createFieldMap(fieldMapData);\n }\n }",
"private void SetNewViewpoint(String url) {\n Viewpoint vp = null;\n // get the name without the '#' sign\n String vpURL = url.substring(1, url.length());\n for (Viewpoint viewpoint : viewpoints) {\n if ( viewpoint.getName().equalsIgnoreCase(vpURL) ) {\n vp = viewpoint;\n }\n }\n if ( vp != null ) {\n // found the Viewpoint matching the url\n GVRCameraRig mainCameraRig = gvrContext.getMainScene().getMainCameraRig();\n float[] cameraPosition = vp.getPosition();\n mainCameraRig.getTransform().setPosition( cameraPosition[0], cameraPosition[1], cameraPosition[2] );\n\n // Set the Gaze controller position which is where the pick ray\n // begins in the direction of camera.lookt()\n GVRCursorController gazeController = null;\n GVRInputManager inputManager = gvrContext.getInputManager();\n\n List<GVRCursorController> controllerList = inputManager.getCursorControllers();\n\n for(GVRCursorController controller: controllerList){\n if(controller.getControllerType() == GVRControllerType.GAZE);\n {\n gazeController = controller;\n break;\n }\n }\n if ( gazeController != null) {\n gazeController.setOrigin(cameraPosition[0], cameraPosition[1], cameraPosition[2]);\n }\n }\n else {\n Log.e(TAG, \"Viewpoint named \" + vpURL + \" not found (defined).\");\n }\n }",
"public final PJsonArray getJSONArray(final int i) {\n JSONArray val = this.array.optJSONArray(i);\n final String context = \"[\" + i + \"]\";\n if (val == null) {\n throw new ObjectMissingException(this, context);\n }\n return new PJsonArray(this, val, context);\n }",
"public ApnsServiceBuilder withSocksProxy(String host, int port) {\n Proxy proxy = new Proxy(Proxy.Type.SOCKS,\n new InetSocketAddress(host, port));\n return withProxy(proxy);\n }"
] |
Wrapper functions with no bounds checking are used to access matrix internals | [
"public static long wrapped(DMatrixRMaj a , DMatrixRMaj b , DMatrixRMaj c )\n {\n long timeBefore = System.currentTimeMillis();\n double valA;\n int indexCbase= 0;\n int endOfKLoop = b.numRows*b.numCols;\n\n for( int i = 0; i < a.numRows; i++ ) {\n int indexA = i*a.numCols;\n\n // need to assign dataC to a value initially\n int indexB = 0;\n int indexC = indexCbase;\n int end = indexB + b.numCols;\n\n valA = a.get(indexA++);\n\n while( indexB < end ) {\n c.set( indexC++ , valA*b.get(indexB++));\n }\n\n // now add to it\n while( indexB != endOfKLoop ) { // k loop\n indexC = indexCbase;\n end = indexB + b.numCols;\n\n valA = a.get(indexA++);\n\n while( indexB < end ) { // j loop\n c.plus( indexC++ , valA*b.get(indexB++));\n }\n }\n indexCbase += c.numCols;\n }\n\n return System.currentTimeMillis() - timeBefore;\n }"
] | [
"@Override\n public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n EnvVars env = build.getEnvironment(listener);\n FilePath workDir = build.getModuleRoot();\n FilePath ws = build.getWorkspace();\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.error(\"Couldn't find Maven home: \" + mavenHome.getRemote());\n throw new Run.RunnerAbortedException();\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, ws, ws);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }",
"public ItemRequest<Team> removeUser(String team) {\n \n String path = String.format(\"/teams/%s/removeUser\", team);\n return new ItemRequest<Team>(this, Team.class, path, \"POST\");\n }",
"public void checkConnection() {\n long start = Time.currentTimeMillis();\n\n while (clientChannel == null) {\n\n tcpSocketConsumer.checkNotShutdown();\n\n if (start + timeoutMs > Time.currentTimeMillis())\n try {\n condition.await(1, TimeUnit.MILLISECONDS);\n\n } catch (InterruptedException e) {\n throw new IORuntimeException(\"Interrupted\");\n }\n else\n throw new IORuntimeException(\"Not connected to \" + socketAddressSupplier);\n }\n\n if (clientChannel == null)\n throw new IORuntimeException(\"Not connected to \" + socketAddressSupplier);\n }",
"private void updateSortedServices() {\n List<T> copiedList = new ArrayList<T>(serviceMap.values());\n sortedServices = Collections.unmodifiableList(copiedList);\n if (changeListener != null) {\n changeListener.changed();\n }\n }",
"public PlacesList<Place> placesForUser(int placeType, String woeId, String placeId, String threshold, Date minUploadDate, Date maxUploadDate,\r\n Date minTakenDate, Date maxTakenDate) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n PlacesList<Place> placesList = new PlacesList<Place>();\r\n parameters.put(\"method\", METHOD_PLACES_FOR_USER);\r\n\r\n parameters.put(\"place_type\", intPlaceTypeToString(placeType));\r\n if (placeId != null) {\r\n parameters.put(\"place_id\", placeId);\r\n }\r\n if (woeId != null) {\r\n parameters.put(\"woe_id\", woeId);\r\n }\r\n if (threshold != null) {\r\n parameters.put(\"threshold\", threshold);\r\n }\r\n if (minUploadDate != null) {\r\n parameters.put(\"min_upload_date\", Long.toString(minUploadDate.getTime() / 1000L));\r\n }\r\n if (maxUploadDate != null) {\r\n parameters.put(\"max_upload_date\", Long.toString(maxUploadDate.getTime() / 1000L));\r\n }\r\n if (minTakenDate != null) {\r\n parameters.put(\"min_taken_date\", ((DateFormat) SearchParameters.MYSQL_DATE_FORMATS.get()).format(minTakenDate));\r\n }\r\n if (maxTakenDate != null) {\r\n parameters.put(\"max_taken_date\", ((DateFormat) SearchParameters.MYSQL_DATE_FORMATS.get()).format(maxTakenDate));\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 placesElement = response.getPayload();\r\n NodeList placesNodes = placesElement.getElementsByTagName(\"place\");\r\n placesList.setPage(\"1\");\r\n placesList.setPages(\"1\");\r\n placesList.setPerPage(\"\" + placesNodes.getLength());\r\n placesList.setTotal(\"\" + placesNodes.getLength());\r\n for (int i = 0; i < placesNodes.getLength(); i++) {\r\n Element placeElement = (Element) placesNodes.item(i);\r\n placesList.add(parsePlace(placeElement));\r\n }\r\n return placesList;\r\n }",
"public static final Duration getDuration(double value, TimeUnit type)\n {\n double duration;\n // Value is given in 1/10 of minute\n switch (type)\n {\n case MINUTES:\n case ELAPSED_MINUTES:\n {\n duration = value / 10;\n break;\n }\n\n case HOURS:\n case ELAPSED_HOURS:\n {\n duration = value / 600; // 60 * 10\n break;\n }\n\n case DAYS:\n {\n duration = value / 4800; // 8 * 60 * 10\n break;\n }\n\n case ELAPSED_DAYS:\n {\n duration = value / 14400; // 24 * 60 * 10\n break;\n }\n\n case WEEKS:\n {\n duration = value / 24000; // 5 * 8 * 60 * 10\n break;\n }\n\n case ELAPSED_WEEKS:\n {\n duration = value / 100800; // 7 * 24 * 60 * 10\n break;\n }\n\n case MONTHS:\n {\n duration = value / 96000; // 4 * 5 * 8 * 60 * 10\n break;\n }\n\n case ELAPSED_MONTHS:\n {\n duration = value / 432000; // 30 * 24 * 60 * 10\n break;\n }\n\n default:\n {\n duration = value;\n break;\n }\n }\n return (Duration.getInstance(duration, type));\n }",
"public Iterable<RowKey> getKeys() {\n\t\tif ( currentState.isEmpty() ) {\n\t\t\tif ( cleared ) {\n\t\t\t\t// if the association has been cleared and the currentState is empty, we consider that there are no rows.\n\t\t\t\treturn Collections.emptyList();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// otherwise, the snapshot rows are the current ones\n\t\t\t\treturn snapshot.getRowKeys();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// It may be a bit too large in case of removals, but that's fine for now\n\t\t\tSet<RowKey> keys = CollectionHelper.newLinkedHashSet( cleared ? currentState.size() : snapshot.size() + currentState.size() );\n\n\t\t\tif ( !cleared ) {\n\t\t\t\t// we add the snapshot RowKeys only if the association has not been cleared\n\t\t\t\tfor ( RowKey rowKey : snapshot.getRowKeys() ) {\n\t\t\t\t\tkeys.add( rowKey );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor ( Map.Entry<RowKey,AssociationOperation> op : currentState.entrySet() ) {\n\t\t\t\tswitch ( op.getValue().getType() ) {\n\t\t\t\t\tcase PUT:\n\t\t\t\t\t\tkeys.add( op.getKey() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase REMOVE:\n\t\t\t\t\t\tkeys.remove( op.getKey() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn keys;\n\t\t}\n\t}",
"public static void createEphemeralPath(ZkClient zkClient, String path, String data) {\n try {\n zkClient.createEphemeral(path, Utils.getBytes(data));\n } catch (ZkNoNodeException e) {\n createParentPath(zkClient, path);\n zkClient.createEphemeral(path, Utils.getBytes(data));\n }\n }",
"private void queryDatabaseMetaData()\n {\n ResultSet rs = null;\n\n try\n {\n Set<String> tables = new HashSet<String>();\n DatabaseMetaData dmd = m_connection.getMetaData();\n rs = dmd.getTables(null, null, null, null);\n while (rs.next())\n {\n tables.add(rs.getString(\"TABLE_NAME\"));\n }\n\n m_hasResourceBaselines = tables.contains(\"MSP_RESOURCE_BASELINES\");\n m_hasTaskBaselines = tables.contains(\"MSP_TASK_BASELINES\");\n m_hasAssignmentBaselines = tables.contains(\"MSP_ASSIGNMENT_BASELINES\");\n }\n\n catch (Exception ex)\n {\n // Ignore errors when reading meta data\n }\n\n finally\n {\n if (rs != null)\n {\n try\n {\n rs.close();\n }\n\n catch (SQLException ex)\n {\n // Ignore errors when closing result set\n }\n rs = null;\n }\n }\n }"
] |
Write a set of fields from a field container to a JSON file.
@param objectName name of the object, or null if no name required
@param container field container
@param fields fields to write | [
"private void writeFields(String objectName, FieldContainer container, FieldType[] fields) throws IOException\n {\n m_writer.writeStartObject(objectName);\n for (FieldType field : fields)\n {\n Object value = container.getCurrentValue(field);\n if (value != null)\n {\n writeField(field, value);\n }\n }\n m_writer.writeEndObject();\n }"
] | [
"static boolean killProcess(final String processName, int id) {\n int pid;\n try {\n pid = processUtils.resolveProcessId(processName, id);\n if(pid > 0) {\n try {\n Runtime.getRuntime().exec(processUtils.getKillCommand(pid));\n return true;\n } catch (Throwable t) {\n ProcessLogger.ROOT_LOGGER.debugf(t, \"failed to kill process '%s' with pid '%s'\", processName, pid);\n }\n }\n } catch (Throwable t) {\n ProcessLogger.ROOT_LOGGER.debugf(t, \"failed to resolve pid of process '%s'\", processName);\n }\n return false;\n }",
"public String getElementId() {\r\n\t\tfor (Entry<String, String> attribute : attributes.entrySet()) {\r\n\t\t\tif (attribute.getKey().equalsIgnoreCase(\"id\")) {\r\n\t\t\t\treturn attribute.getValue();\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}",
"@Override\n public boolean setA(DMatrixRBlock A) {\n if( A.numRows < A.numCols )\n throw new IllegalArgumentException(\"Number of rows must be more than or equal to the number of columns. \" +\n \"Can't solve an underdetermined system.\");\n\n if( !decomposer.decompose(A))\n return false;\n\n this.QR = decomposer.getQR();\n\n return true;\n }",
"protected final void verify() {\n collectInitialisers();\n verifyCandidates();\n verifyInitialisers();\n collectPossibleInitialValues();\n verifyPossibleInitialValues();\n collectEffectiveAssignmentInstructions();\n verifyEffectiveAssignmentInstructions();\n collectAssignmentGuards();\n verifyAssignmentGuards();\n end();\n }",
"public void setOwner(Graph<DataT, NodeT> ownerGraph) {\n if (this.ownerGraph != null) {\n throw new RuntimeException(\"Changing owner graph is not allowed\");\n }\n this.ownerGraph = ownerGraph;\n }",
"public Record getChild(String key)\n {\n Record result = null;\n if (key != null)\n {\n for (Record record : m_records)\n {\n if (key.equals(record.getField()))\n {\n result = record;\n break;\n }\n }\n }\n return result;\n }",
"private void readHours(ProjectCalendar calendar, Day day, Integer hours)\n {\n int value = hours.intValue();\n int startHour = 0;\n ProjectCalendarHours calendarHours = null;\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, 0);\n cal.set(Calendar.MINUTE, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n\n calendar.setWorkingDay(day, false);\n\n while (value != 0)\n {\n // Move forward until we find a working hour\n while (startHour < 24 && (value & 0x1) == 0)\n {\n value = value >> 1;\n ++startHour;\n }\n\n // No more working hours, bail out\n if (startHour >= 24)\n {\n break;\n }\n\n // Move forward until we find the end of the working hours\n int endHour = startHour;\n while (endHour < 24 && (value & 0x1) != 0)\n {\n value = value >> 1;\n ++endHour;\n }\n\n cal.set(Calendar.HOUR_OF_DAY, startHour);\n Date startDate = cal.getTime();\n cal.set(Calendar.HOUR_OF_DAY, endHour);\n Date endDate = cal.getTime();\n\n if (calendarHours == null)\n {\n calendarHours = calendar.addCalendarHours(day);\n calendar.setWorkingDay(day, true);\n }\n calendarHours.addRange(new DateRange(startDate, endDate));\n startHour = endHour;\n }\n \n DateHelper.pushCalendar(cal);\n }",
"private static Map<Integer, LinkedList<MetadataCache>> gatherCandidateAttachmentGroups() {\n Map<Integer,LinkedList<MetadataCache>> candidateGroups = new TreeMap<Integer, LinkedList<MetadataCache>>();\n final Iterator<File> iterator = MetadataFinder.getInstance().getAutoAttachCacheFiles().iterator();\n while (iterator.hasNext()) {\n final File file = iterator.next();\n try {\n final MetadataCache candidate = new MetadataCache(file);\n if (candidateGroups.get(candidate.sourcePlaylist) == null) {\n candidateGroups.put(candidate.sourcePlaylist, new LinkedList<MetadataCache>());\n }\n candidateGroups.get(candidate.sourcePlaylist).add(candidate);\n } catch (Exception e) {\n logger.error(\"Unable to open metadata cache file \" + file + \", discarding\", e);\n iterator.remove();\n }\n }\n return candidateGroups;\n }",
"public static byte[] concat(Bytes... listOfBytes) {\n int offset = 0;\n int size = 0;\n\n for (Bytes b : listOfBytes) {\n size += b.length() + checkVlen(b.length());\n }\n\n byte[] data = new byte[size];\n for (Bytes b : listOfBytes) {\n offset = writeVint(data, offset, b.length());\n b.copyTo(0, b.length(), data, offset);\n offset += b.length();\n }\n return data;\n }"
] |
Check that all nodes in the new cluster have a corresponding entry in
storeRepository and innerStores. add a NodeStore if not present, is
needed as with rebalancing we can add new nodes on the fly. | [
"private void checkAndAddNodeStore() {\n for(Node node: metadata.getCluster().getNodes()) {\n if(!routedStore.getInnerStores().containsKey(node.getId())) {\n if(!storeRepository.hasNodeStore(getName(), node.getId())) {\n storeRepository.addNodeStore(node.getId(), createNodeStore(node));\n }\n routedStore.getInnerStores().put(node.getId(),\n storeRepository.getNodeStore(getName(),\n node.getId()));\n }\n }\n }"
] | [
"public static base_response update(nitro_service client, inat resource) throws Exception {\n\t\tinat updateresource = new inat();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.privateip = resource.privateip;\n\t\tupdateresource.tcpproxy = resource.tcpproxy;\n\t\tupdateresource.ftp = resource.ftp;\n\t\tupdateresource.tftp = resource.tftp;\n\t\tupdateresource.usip = resource.usip;\n\t\tupdateresource.usnip = resource.usnip;\n\t\tupdateresource.proxyip = resource.proxyip;\n\t\tupdateresource.mode = resource.mode;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public void setEndTime(final Date date) {\r\n\r\n if (!Objects.equals(m_model.getEnd(), date)) {\r\n m_model.setEnd(date);\r\n valueChanged();\r\n }\r\n\r\n }",
"private void deliverWaveformDetailUpdate(final int player, final WaveformDetail detail) {\n if (!getWaveformListeners().isEmpty()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n final WaveformDetailUpdate update = new WaveformDetailUpdate(player, detail);\n for (final WaveformListener listener : getWaveformListeners()) {\n try {\n listener.detailChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering waveform detail update to listener\", t);\n }\n }\n }\n });\n }\n }",
"public static void printResults(Counter<String> entityTP, Counter<String> entityFP,\r\n Counter<String> entityFN) {\r\n Set<String> entities = new TreeSet<String>();\r\n entities.addAll(entityTP.keySet());\r\n entities.addAll(entityFP.keySet());\r\n entities.addAll(entityFN.keySet());\r\n boolean printedHeader = false;\r\n for (String entity : entities) {\r\n double tp = entityTP.getCount(entity);\r\n double fp = entityFP.getCount(entity);\r\n double fn = entityFN.getCount(entity);\r\n printedHeader = printPRLine(entity, tp, fp, fn, printedHeader);\r\n }\r\n double tp = entityTP.totalCount();\r\n double fp = entityFP.totalCount();\r\n double fn = entityFN.totalCount();\r\n printedHeader = printPRLine(\"Totals\", tp, fp, fn, printedHeader);\r\n }",
"@SuppressWarnings(\"unchecked\")\n protected Class<? extends Annotation> annotationTypeForName(String name) {\n try {\n return (Class<? extends Annotation>) resourceLoader.classForName(name);\n } catch (ResourceLoadingException cnfe) {\n return DUMMY_ANNOTATION;\n }\n }",
"private Query getQueryByCriteriaCount(QueryByCriteria aQuery)\r\n {\r\n Class searchClass = aQuery.getSearchClass();\r\n ReportQueryByCriteria countQuery = null;\r\n Criteria countCrit = null;\r\n String[] columns = new String[1];\r\n\r\n // BRJ: copied Criteria without groupby, orderby, and prefetched relationships\r\n if (aQuery.getCriteria() != null)\r\n {\r\n countCrit = aQuery.getCriteria().copy(false, false, false);\r\n }\r\n\r\n if (aQuery.isDistinct())\r\n {\r\n // BRJ: Count distinct is dbms dependent\r\n // hsql/sapdb: select count (distinct(person_id || project_id)) from person_project\r\n // mysql: select count (distinct person_id,project_id) from person_project\r\n // [tomdz]\r\n // Some databases have no support for multi-column count distinct (e.g. Derby)\r\n // Here we use a SELECT count(*) FROM (SELECT DISTINCT ...) instead \r\n //\r\n // concatenation of pk-columns is a simple way to obtain a single column\r\n // but concatenation is also dbms dependent:\r\n //\r\n // SELECT count(distinct concat(row1, row2, row3)) mysql\r\n // SELECT count(distinct (row1 || row2 || row3)) ansi\r\n // SELECT count(distinct (row1 + row2 + row3)) ms sql-server\r\n\r\n FieldDescriptor[] pkFields = m_broker.getClassDescriptor(searchClass).getPkFields();\r\n String[] keyColumns = new String[pkFields.length];\r\n\r\n if (pkFields.length > 1)\r\n {\r\n // TODO: Use ColumnName. This is a temporary solution because\r\n // we cannot yet resolve multiple columns in the same attribute.\r\n for (int idx = 0; idx < pkFields.length; idx++)\r\n {\r\n keyColumns[idx] = pkFields[idx].getColumnName();\r\n }\r\n }\r\n else\r\n {\r\n for (int idx = 0; idx < pkFields.length; idx++)\r\n {\r\n keyColumns[idx] = pkFields[idx].getAttributeName();\r\n }\r\n }\r\n // [tomdz]\r\n // TODO: Add support for databases that do not support COUNT DISTINCT over multiple columns\r\n// if (getPlatform().supportsMultiColumnCountDistinct())\r\n// {\r\n// columns[0] = \"count(distinct \" + getPlatform().concatenate(keyColumns) + \")\";\r\n// }\r\n// else\r\n// {\r\n// columns = keyColumns;\r\n// }\r\n\r\n columns[0] = \"count(distinct \" + getPlatform().concatenate(keyColumns) + \")\";\r\n }\r\n else\r\n {\r\n columns[0] = \"count(*)\";\r\n }\r\n\r\n // BRJ: we have to preserve indirection table !\r\n if (aQuery instanceof MtoNQuery)\r\n {\r\n MtoNQuery mnQuery = (MtoNQuery)aQuery;\r\n ReportQueryByMtoNCriteria mnReportQuery = new ReportQueryByMtoNCriteria(searchClass, columns, countCrit);\r\n\r\n mnReportQuery.setIndirectionTable(mnQuery.getIndirectionTable());\r\n countQuery = mnReportQuery;\r\n }\r\n else\r\n {\r\n countQuery = new ReportQueryByCriteria(searchClass, columns, countCrit);\r\n }\r\n\r\n // BRJ: we have to preserve outer-join-settings (by André Markwalder)\r\n for (Iterator outerJoinPath = aQuery.getOuterJoinPaths().iterator(); outerJoinPath.hasNext();)\r\n {\r\n String path = (String) outerJoinPath.next();\r\n\r\n if (aQuery.isPathOuterJoin(path))\r\n {\r\n countQuery.setPathOuterJoin(path);\r\n }\r\n }\r\n\r\n //BRJ: add orderBy Columns asJoinAttributes\r\n List orderBy = aQuery.getOrderBy();\r\n\r\n if ((orderBy != null) && !orderBy.isEmpty())\r\n {\r\n String[] joinAttributes = new String[orderBy.size()];\r\n\r\n for (int idx = 0; idx < orderBy.size(); idx++)\r\n {\r\n joinAttributes[idx] = ((FieldHelper)orderBy.get(idx)).name;\r\n }\r\n countQuery.setJoinAttributes(joinAttributes);\r\n }\r\n\r\n // [tomdz]\r\n // TODO:\r\n // For those databases that do not support COUNT DISTINCT over multiple columns\r\n // we wrap the normal SELECT DISTINCT that we just created, into a SELECT count(*)\r\n // For this however we need a report query that gets its data from a sub query instead\r\n // of a table (target class)\r\n// if (aQuery.isDistinct() && !getPlatform().supportsMultiColumnCountDistinct())\r\n// {\r\n// }\r\n\r\n return countQuery;\r\n }",
"public static void configureLogging() {\n\t\t// Create the appender that will write log messages to the console.\n\t\tConsoleAppender consoleAppender = new ConsoleAppender();\n\t\t// Define the pattern of log messages.\n\t\t// Insert the string \"%c{1}:%L\" to also show class name and line.\n\t\tString pattern = \"%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n\";\n\t\tconsoleAppender.setLayout(new PatternLayout(pattern));\n\t\t// Change to Level.ERROR for fewer messages:\n\t\tconsoleAppender.setThreshold(Level.INFO);\n\n\t\tconsoleAppender.activateOptions();\n\t\tLogger.getRootLogger().addAppender(consoleAppender);\n\t}",
"public ExecutionChain setErrorCallback(ErrorCallback callback) {\n if (state.get() == State.RUNNING) {\n throw new IllegalStateException(\n \"Invalid while ExecutionChain is running\");\n }\n errorCallback = callback;\n return this;\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 }"
] |
Check if the gravity and orientation are not in conflict one with other.
@param gravity
@param orientation
@return true if orientation and gravity can be applied together, false - otherwise | [
"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 }"
] | [
"public static int removeDuplicateNodeList(List<String> list) {\n\n int originCount = list.size();\n // add elements to all, including duplicates\n HashSet<String> hs = new LinkedHashSet<String>();\n hs.addAll(list);\n list.clear();\n list.addAll(hs);\n\n return originCount - list.size();\n }",
"protected static void appendHandler(LogRecordHandler parent, LogRecordHandler child){\r\n RecordHandlerTree p = handlers.find(parent);\r\n if(p != null){\r\n p.addChild(child);\r\n } else {\r\n throw new IllegalArgumentException(\"No such parent handler: \" + parent);\r\n }\r\n }",
"protected void failedToCleanupDir(final File file) {\n checkForGarbageOnRestart = true;\n PatchLogger.ROOT_LOGGER.cannotDeleteFile(file.getAbsolutePath());\n }",
"public synchronized void stop(long quietPeriod, long timeout, TimeUnit unit) throws Exception {\n if (state == State.STOPPED) {\n LOG.debug(\"Ignore stop() call on HTTP service {} since it has already been stopped.\", serviceName);\n return;\n }\n\n LOG.info(\"Stopping HTTP Service {}\", serviceName);\n\n try {\n try {\n channelGroup.close().awaitUninterruptibly();\n } finally {\n try {\n shutdownExecutorGroups(quietPeriod, timeout, unit,\n bootstrap.config().group(), bootstrap.config().childGroup(), eventExecutorGroup);\n } finally {\n resourceHandler.destroy(handlerContext);\n }\n }\n } catch (Throwable t) {\n state = State.FAILED;\n throw t;\n }\n state = State.STOPPED;\n LOG.debug(\"Stopped HTTP Service {} on address {}\", serviceName, bindAddress);\n }",
"public static String getAggregatedResultHuman(Map<String, LinkedHashSet<String>> aggregateResultMap){\n\n StringBuilder res = new StringBuilder();\n\n for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap\n .entrySet()) {\n LinkedHashSet<String> valueSet = entry.getValue(); \n res.append(\"[\" + entry.getKey() + \" COUNT: \" +valueSet.size() + \" ]:\\n\");\n for(String str: valueSet){\n res.append(\"\\t\" + str + \"\\n\");\n }\n res.append(\"###################################\\n\\n\");\n }\n \n return res.toString();\n \n }",
"private void writeResources() throws IOException\n {\n writeAttributeTypes(\"resource_types\", ResourceField.values());\n\n m_writer.writeStartList(\"resources\");\n for (Resource resource : m_projectFile.getResources())\n {\n writeFields(null, resource, ResourceField.values());\n }\n m_writer.writeEndList();\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 }",
"public static String getFileFormat(POIFSFileSystem fs) throws IOException\n {\n String fileFormat = \"\";\n DirectoryEntry root = fs.getRoot();\n if (root.getEntryNames().contains(\"\\1CompObj\"))\n {\n CompObj compObj = new CompObj(new DocumentInputStream((DocumentEntry) root.getEntry(\"\\1CompObj\")));\n fileFormat = compObj.getFileFormat();\n }\n return fileFormat;\n }",
"public Set<Tag> getAncestorTags(Tag tag)\n {\n Set<Tag> ancestors = new HashSet<>();\n getAncestorTags(tag, ancestors);\n return ancestors;\n }"
] |
Ensures that the given collection descriptor has the collection-class property if necessary.
@param collDef The collection descriptor
@param checkLevel The current check level (this constraint is checked in basic (partly) and strict)
@exception ConstraintException If collection-class is given for an array or if no collection-class is given but required | [
"private void ensureCollectionClass(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_ARRAY_ELEMENT_CLASS_REF))\r\n {\r\n // an array cannot have a collection-class specified \r\n if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLLECTION_CLASS))\r\n {\r\n throw new ConstraintException(\"Collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" is an array but does specify collection-class\");\r\n }\r\n else\r\n {\r\n // no further processing necessary as its an array\r\n return;\r\n }\r\n }\r\n\r\n if (CHECKLEVEL_STRICT.equals(checkLevel))\r\n { \r\n InheritanceHelper helper = new InheritanceHelper();\r\n ModelDef model = (ModelDef)collDef.getOwner().getOwner();\r\n String specifiedClass = collDef.getProperty(PropertyHelper.OJB_PROPERTY_COLLECTION_CLASS);\r\n String variableType = collDef.getProperty(PropertyHelper.OJB_PROPERTY_VARIABLE_TYPE);\r\n \r\n try\r\n {\r\n if (specifiedClass != null)\r\n {\r\n // if we have a specified class then it has to implement the manageable collection and be a sub type of the variable type\r\n if (!helper.isSameOrSubTypeOf(specifiedClass, variableType))\r\n {\r\n throw new ConstraintException(\"The type \"+specifiedClass+\" specified as collection-class of the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" is not a sub type of the variable type \"+variableType);\r\n }\r\n if (!helper.isSameOrSubTypeOf(specifiedClass, MANAGEABLE_COLLECTION_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The type \"+specifiedClass+\" specified as collection-class of the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" does not implement \"+MANAGEABLE_COLLECTION_INTERFACE);\r\n }\r\n }\r\n else\r\n {\r\n // no collection class specified so the variable type has to be a collection type\r\n if (helper.isSameOrSubTypeOf(variableType, MANAGEABLE_COLLECTION_INTERFACE))\r\n {\r\n // we can specify it as a collection-class as it is an manageable collection\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_COLLECTION_CLASS, variableType);\r\n }\r\n else if (!helper.isSameOrSubTypeOf(variableType, JAVA_COLLECTION_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" needs the collection-class attribute as its variable type does not implement \"+JAVA_COLLECTION_INTERFACE);\r\n }\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName());\r\n }\r\n }\r\n }"
] | [
"public ProjectCalendar getCalendar()\n {\n ProjectCalendar calendar = null;\n Resource resource = getResource();\n if (resource != null)\n {\n calendar = resource.getResourceCalendar();\n }\n\n Task task = getTask();\n if (calendar == null || task.getIgnoreResourceCalendar())\n {\n calendar = task.getEffectiveCalendar();\n }\n\n return calendar;\n }",
"public void setDefaultInterval(long defaultInterval) {\n \tif(defaultInterval <= 0) {\n \t\tLOG.severe(\"collector.scheduler.interval must be greater than 0. Recommended value is 500-1000. Current value is \" + defaultInterval);\n \t\tthrow new IllegalArgumentException(\"collector.scheduler.interval must be greater than 0. Recommended value is 500-1000. Current value is \" + defaultInterval);\n \t}\n this.defaultInterval = defaultInterval;\n }",
"public static lbvserver_servicegroup_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_servicegroup_binding obj = new lbvserver_servicegroup_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_servicegroup_binding response[] = (lbvserver_servicegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private String dumpZoneNAryDetails(StoreRoutingPlan storeRoutingPlan) {\n StringBuilder sb = new StringBuilder();\n\n sb.append(\"\\tDetailed Dump (Zone N-Aries):\").append(Utils.NEWLINE);\n for(Node node: storeRoutingPlan.getCluster().getNodes()) {\n int zoneId = node.getZoneId();\n int nodeId = node.getId();\n sb.append(\"\\tNode ID: \" + nodeId + \" in zone \" + zoneId).append(Utils.NEWLINE);\n List<Integer> naries = storeRoutingPlan.getZoneNAryPartitionIds(nodeId);\n Map<Integer, List<Integer>> zoneNaryTypeToPartitionIds = new HashMap<Integer, List<Integer>>();\n for(int nary: naries) {\n int zoneReplicaType = storeRoutingPlan.getZoneNaryForNodesPartition(zoneId,\n nodeId,\n nary);\n if(!zoneNaryTypeToPartitionIds.containsKey(zoneReplicaType)) {\n zoneNaryTypeToPartitionIds.put(zoneReplicaType, new ArrayList<Integer>());\n }\n zoneNaryTypeToPartitionIds.get(zoneReplicaType).add(nary);\n }\n\n for(int replicaType: new TreeSet<Integer>(zoneNaryTypeToPartitionIds.keySet())) {\n sb.append(\"\\t\\t\" + replicaType + \" : \");\n sb.append(zoneNaryTypeToPartitionIds.get(replicaType).toString());\n sb.append(Utils.NEWLINE);\n }\n }\n\n return sb.toString();\n }",
"public void visitExport(String packaze, int access, String... modules) {\n if (mv != null) {\n mv.visitExport(packaze, access, modules);\n }\n }",
"public void eol() throws ProtocolException {\r\n char next = nextChar();\r\n\r\n // Ignore trailing spaces.\r\n while (next == ' ') {\r\n consume();\r\n next = nextChar();\r\n }\r\n\r\n // handle DOS and unix end-of-lines\r\n if (next == '\\r') {\r\n consume();\r\n next = nextChar();\r\n }\r\n\r\n // Check if we found extra characters.\r\n if (next != '\\n') {\r\n throw new ProtocolException(\"Expected end-of-line, found more character(s): \"+next);\r\n }\r\n dumpLine();\r\n }",
"public UniqueEntityLoader buildLoader(\n\t\t\tOuterJoinLoadable persister,\n\t\t\tint batchSize,\n\t\t\tLockMode lockMode,\n\t\t\tSessionFactoryImplementor factory,\n\t\t\tLoadQueryInfluencers influencers,\n\t\t\tBatchableEntityLoaderBuilder innerEntityLoaderBuilder) {\n\t\tif ( batchSize <= 1 ) {\n\t\t\t// no batching\n\t\t\treturn buildNonBatchingLoader( persister, lockMode, factory, influencers, innerEntityLoaderBuilder );\n\t\t}\n\t\treturn buildBatchingLoader( persister, batchSize, lockMode, factory, influencers, innerEntityLoaderBuilder );\n\t}",
"public PreparedStatement getInsertStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getInsertStmt(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 }",
"private String appendXmlStartTag(String value) {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"<\").append(value).append(\">\");\n\r\n return sb.toString();\r\n }"
] |
Compares two avro strings which contains single store configs
@param configAvro1
@param configAvro2
@return true if two config avro strings have same content | [
"public static Boolean compareSingleClientConfigAvro(String configAvro1, String configAvro2) {\n Properties props1 = readSingleClientConfigAvro(configAvro1);\n Properties props2 = readSingleClientConfigAvro(configAvro2);\n if(props1.equals(props2)) {\n return true;\n } else {\n return false;\n }\n }"
] | [
"public static String fill(int color) {\n final String colorCode = Integer.toHexString(color & 0xFFFFFF); // Strip alpha\n return FILTER_FILL + \"(\" + colorCode + \")\";\n }",
"public void process(InputStream is) throws Exception\n {\n readHeader(is);\n readVersion(is);\n readTableData(readTableHeaders(is), is);\n }",
"@SuppressForbidden(\"legitimate sysstreams.\")\n private static void redirectStreams(final Serializer serializer, final boolean flushFrequently) {\n final PrintStream origSysOut = System.out;\n final PrintStream origSysErr = System.err;\n\n // Set warnings stream to System.err.\n warnings = System.err;\n AccessController.doPrivileged(new PrivilegedAction<Void>() {\n @SuppressForbidden(\"legitimate PrintStream with default charset.\")\n @Override\n public Void run() {\n System.setOut(new PrintStream(new BufferedOutputStream(new ChunkedStream() {\n @Override\n public void write(byte[] b, int off, int len) throws IOException {\n if (multiplexStdStreams) {\n origSysOut.write(b, off, len);\n }\n serializer.serialize(new AppendStdOutEvent(b, off, len));\n if (flushFrequently) serializer.flush();\n }\n })));\n\n System.setErr(new PrintStream(new BufferedOutputStream(new ChunkedStream() {\n @Override\n public void write(byte[] b, int off, int len) throws IOException {\n if (multiplexStdStreams) {\n origSysErr.write(b, off, len);\n }\n serializer.serialize(new AppendStdErrEvent(b, off, len));\n if (flushFrequently) serializer.flush();\n }\n })));\n return null;\n }\n });\n }",
"public void getGradient(int[] batch, double[] gradient) {\n for (int i=0; i<batch.length; i++) {\n addGradient(i, gradient);\n }\n }",
"public static String getURL(String sourceURI) {\n String retval = sourceURI;\n int qPos = sourceURI.indexOf(\"?\");\n if (qPos != -1) {\n retval = retval.substring(0, qPos);\n }\n\n return retval;\n }",
"public static double getFloatingPointDateFromDate(LocalDateTime referenceDate, LocalDateTime date) {\n\t\tDuration duration = Duration.between(referenceDate, date);\n\t\treturn ((double)duration.getSeconds()) / SECONDS_PER_DAY;\n\t}",
"public void setNodeMetaData(Object key, Object value) {\n if (key==null) throw new GroovyBugError(\"Tried to set meta data with null key on \"+this+\".\");\n if (metaDataMap == null) {\n metaDataMap = new ListHashMap();\n }\n Object old = metaDataMap.put(key,value);\n if (old!=null) throw new GroovyBugError(\"Tried to overwrite existing meta data \"+this+\".\");\n }",
"private void rotatorPushRight2( int m , int offset)\n {\n double b11 = bulge;\n double b12 = diag[m+offset];\n\n computeRotator(b12,-b11);\n\n diag[m+offset] = b12*c-b11*s;\n\n if( m+offset<N-1) {\n double b22 = off[m+offset];\n off[m+offset] = b22*c;\n bulge = b22*s;\n }\n\n// SimpleMatrix Q = createQ(m,m+offset, 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+offset,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 static vpnvserver_vpnsessionpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_vpnsessionpolicy_binding obj = new vpnvserver_vpnsessionpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_vpnsessionpolicy_binding response[] = (vpnvserver_vpnsessionpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Add a Comparator to the end of the chain using the provided sort order.
@param comparator the Comparator to add to the end of the chain
@param ascending the sort order: ascending (true) or descending (false) | [
"public void addComparator(Comparator<T> comparator, boolean ascending) {\n\t\tthis.comparators.add(new InvertibleComparator<T>(comparator, ascending));\n\t}"
] | [
"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 }",
"public Object convertStringToJavaField(String value, int columnPos) throws SQLException {\n\t\tif (value == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn fieldConverter.resultStringToJava(this, value, columnPos);\n\t\t}\n\t}",
"public void splitSpan(int n) {\n\t\tint x = (xKnots[n] + xKnots[n+1])/2;\n\t\taddKnot(x, getColor(x/256.0f), knotTypes[n]);\n\t\trebuildGradient();\n\t}",
"protected void validateRIBean(CommonBean<?> bean, BeanManagerImpl beanManager, Collection<CommonBean<?>> specializedBeans) {\n validateGeneralBean(bean, beanManager);\n if (bean instanceof NewBean) {\n return;\n }\n if (bean instanceof DecorableBean) {\n validateDecorators(beanManager, (DecorableBean<?>) bean);\n }\n if ((bean instanceof AbstractClassBean<?>)) {\n AbstractClassBean<?> classBean = (AbstractClassBean<?>) bean;\n // validate CDI-defined interceptors\n if (classBean.hasInterceptors()) {\n validateInterceptors(beanManager, classBean);\n }\n }\n // for each producer bean validate its disposer method\n if (bean instanceof AbstractProducerBean<?, ?, ?>) {\n AbstractProducerBean<?, ?, ?> producerBean = Reflections.<AbstractProducerBean<?, ?, ?>> cast(bean);\n if (producerBean.getProducer() instanceof AbstractMemberProducer<?, ?>) {\n AbstractMemberProducer<?, ?> producer = Reflections.<AbstractMemberProducer<?, ?>> cast(producerBean\n .getProducer());\n if (producer.getDisposalMethod() != null) {\n for (InjectionPoint ip : producer.getDisposalMethod().getInjectionPoints()) {\n // pass the producer bean instead of the disposal method bean\n validateInjectionPointForDefinitionErrors(ip, null, beanManager);\n validateMetadataInjectionPoint(ip, null, ValidatorLogger.INJECTION_INTO_DISPOSER_METHOD);\n validateEventMetadataInjectionPoint(ip);\n validateInjectionPointForDeploymentProblems(ip, null, beanManager);\n }\n }\n }\n }\n }",
"@Override public void render() {\n Video video = getContent();\n renderThumbnail(video);\n renderTitle(video);\n renderMarker(video);\n renderLabel();\n }",
"public static List<DesignDocument> fromDirectory(File directory) throws FileNotFoundException {\r\n List<DesignDocument> designDocuments = new ArrayList<DesignDocument>();\r\n if (directory.isDirectory()) {\r\n Collection<File> files = FileUtils.listFiles(directory, null, true);\r\n for (File designDocFile : files) {\r\n designDocuments.add(fromFile(designDocFile));\r\n }\r\n } else {\r\n designDocuments.add(fromFile(directory));\r\n }\r\n return designDocuments;\r\n }",
"public String getWorkplaceLink(CmsObject cms, String resourceName, boolean forceSecure) {\n\n String result = substituteLinkForUnknownTarget(cms, resourceName, forceSecure);\n return appendServerPrefix(cms, result, resourceName, true);\n\n }",
"public PhotoList<Photo> getContactsPublicPhotos(String userId, int count, boolean justFriends, boolean singlePhoto, boolean includeSelf)\r\n throws FlickrException {\r\n return getContactsPublicPhotos(userId, Extras.MIN_EXTRAS, count, justFriends, singlePhoto, includeSelf);\r\n }",
"private void readTask(String projectIdentifier, Map<String, Task> map, Document.Projects.Project.Task task)\n {\n Task parentTask = map.get(getParentOutlineNumber(task.getOutlineNumber()));\n Task mpxjTask = parentTask.addTask();\n\n TimeUnit units = task.getBaseDurationTimeUnit();\n\n mpxjTask.setCost(task.getActualCost());\n mpxjTask.setDuration(getDuration(units, task.getActualDuration()));\n mpxjTask.setFinish(task.getActualFinishDate());\n mpxjTask.setStart(task.getActualStartDate());\n mpxjTask.setBaselineDuration(getDuration(units, task.getBaseDuration()));\n mpxjTask.setBaselineFinish(task.getBaseFinishDate());\n mpxjTask.setBaselineCost(task.getBaselineCost());\n // task.getBaselineFinishDate()\n // task.getBaselineFinishTemplateOffset()\n // task.getBaselineStartDate()\n // task.getBaselineStartTemplateOffset()\n mpxjTask.setBaselineStart(task.getBaseStartDate());\n // task.getCallouts()\n mpxjTask.setPercentageComplete(task.getComplete());\n mpxjTask.setDeadline(task.getDeadlineDate());\n // task.getDeadlineTemplateOffset()\n // task.getHyperlinks()\n // task.getMarkerID()\n mpxjTask.setName(task.getName());\n mpxjTask.setNotes(task.getNote());\n mpxjTask.setPriority(task.getPriority());\n // task.getRecalcBase1()\n // task.getRecalcBase2()\n mpxjTask.setType(task.getSchedulingType());\n // task.getStyleProject()\n // task.getTemplateOffset()\n // task.getValidatedByProject()\n\n if (task.isIsMilestone())\n {\n mpxjTask.setMilestone(true);\n mpxjTask.setDuration(Duration.getInstance(0, TimeUnit.HOURS));\n mpxjTask.setBaselineDuration(Duration.getInstance(0, TimeUnit.HOURS));\n }\n\n String taskIdentifier = projectIdentifier + \".\" + task.getID();\n m_taskIdMap.put(task.getID(), mpxjTask);\n mpxjTask.setGUID(UUID.nameUUIDFromBytes(taskIdentifier.getBytes()));\n\n map.put(task.getOutlineNumber(), mpxjTask);\n\n for (Document.Projects.Project.Task.ResourceAssignments.ResourceAssignment assignment : task.getResourceAssignments().getResourceAssignment())\n {\n readResourceAssignment(mpxjTask, assignment);\n }\n }"
] |
Tests if this partition has hit a threshold and signal to the pool watch thread to create new connections
@param connectionPartition to test for. | [
"protected void maybeSignalForMoreConnections(ConnectionPartition connectionPartition) {\r\n\r\n\t\tif (!connectionPartition.isUnableToCreateMoreTransactions() \r\n\t\t\t\t&& !this.poolShuttingDown &&\r\n\t\t\t\tconnectionPartition.getAvailableConnections()*100/connectionPartition.getMaxConnections() <= this.poolAvailabilityThreshold){\r\n\t\t\tconnectionPartition.getPoolWatchThreadSignalQueue().offer(new Object()); // item being pushed is not important.\r\n\t\t}\r\n\t}"
] | [
"public static <T> List<T> toList(Iterable<T> items) {\r\n List<T> list = new ArrayList<T>();\r\n addAll(list, items);\r\n return list;\r\n }",
"public static void generateOutputFile(Random rng,\n File outputFile) throws IOException\n {\n DataOutputStream dataOutput = null;\n try\n {\n dataOutput = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));\n for (int i = 0; i < INT_COUNT; i++)\n {\n dataOutput.writeInt(rng.nextInt());\n }\n dataOutput.flush();\n }\n finally\n {\n if (dataOutput != null)\n {\n dataOutput.close();\n }\n }\n }",
"public boolean accept(String str) {\r\n int k = str.length() - 1;\r\n char c = str.charAt(k);\r\n while (k >= 0 && !Character.isDigit(c)) {\r\n k--;\r\n if (k >= 0) {\r\n c = str.charAt(k);\r\n }\r\n }\r\n if (k < 0) {\r\n return false;\r\n }\r\n int j = k;\r\n c = str.charAt(j);\r\n while (j >= 0 && Character.isDigit(c)) {\r\n j--;\r\n if (j >= 0) {\r\n c = str.charAt(j);\r\n }\r\n }\r\n j++;\r\n k++;\r\n String theNumber = str.substring(j, k);\r\n int number = Integer.parseInt(theNumber);\r\n for (Pair<Integer,Integer> p : ranges) {\r\n int low = p.first().intValue();\r\n int high = p.second().intValue();\r\n if (number >= low && number <= high) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"public void addRequest(long timeNS,\n long numEmptyResponses,\n long valueBytes,\n long keyBytes,\n long getAllAggregatedCount) {\n // timing instrumentation (trace only)\n long startTimeNs = 0;\n if(logger.isTraceEnabled()) {\n startTimeNs = System.nanoTime();\n }\n\n long currentTime = time.milliseconds();\n\n timeSensor.record((double) timeNS / voldemort.utils.Time.NS_PER_MS, currentTime);\n emptyResponseKeysSensor.record(numEmptyResponses, currentTime);\n valueBytesSensor.record(valueBytes, currentTime);\n keyBytesSensor.record(keyBytes, currentTime);\n getAllKeysCountSensor.record(getAllAggregatedCount, currentTime);\n\n // timing instrumentation (trace only)\n if(logger.isTraceEnabled()) {\n logger.trace(\"addRequest took \" + (System.nanoTime() - startTimeNs) + \" ns.\");\n }\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<EthiopicDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<EthiopicDate>) super.zonedDateTime(temporal);\n }",
"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 writeUserFieldDefinitions()\n {\n for (CustomField cf : m_sortedCustomFieldsList)\n {\n if (cf.getFieldType() != null && cf.getFieldType().getDataType() != null)\n {\n UDFTypeType udf = m_factory.createUDFTypeType();\n udf.setObjectId(Integer.valueOf(FieldTypeHelper.getFieldID(cf.getFieldType())));\n\n udf.setDataType(UserFieldDataType.inferUserFieldDataType(cf.getFieldType().getDataType()));\n udf.setSubjectArea(UserFieldDataType.inferUserFieldSubjectArea(cf.getFieldType()));\n udf.setTitle(cf.getAlias());\n m_apibo.getUDFType().add(udf);\n }\n }\n }",
"public ConnectionlessBootstrap bootStrapUdpClient()\n throws HttpRequestCreateException {\n\n ConnectionlessBootstrap udpClient = null;\n try {\n\n // Configure the client.\n udpClient = new ConnectionlessBootstrap(udpMeta.getChannelFactory());\n\n udpClient.setPipeline(new UdpPipelineFactory(\n TcpUdpSshPingResourceStore.getInstance().getTimer(), this)\n .getPipeline());\n\n } catch (Exception t) {\n throw new TcpUdpRequestCreateException(\n \"Error in creating request in udp worker. \"\n + \" If udpClient is null. Then fail to create.\", t);\n }\n\n return udpClient;\n\n }",
"public void setUserInfo(String username, String infoName, String value) throws CmsException {\n\n CmsUser user = m_cms.readUser(username);\n user.setAdditionalInfo(infoName, value);\n m_cms.writeUser(user);\n }"
] |
Add a new profile with the profileName given.
@param profileName name of new profile
@return newly created profile
@throws Exception exception | [
"public Profile add(String profileName) throws Exception {\n Profile profile = new Profile();\n int id = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n Clob clobProfileName = sqlService.toClob(profileName, sqlConnection);\n\n statement = sqlConnection.prepareStatement(\n \"INSERT INTO \" + Constants.DB_TABLE_PROFILE\n + \"(\" + Constants.PROFILE_PROFILE_NAME + \") \" +\n \" VALUES (?)\", PreparedStatement.RETURN_GENERATED_KEYS\n );\n\n statement.setClob(1, clobProfileName);\n statement.executeUpdate();\n results = statement.getGeneratedKeys();\n if (results.next()) {\n id = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add client\");\n }\n results.close();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_CLIENT +\n \"(\" + Constants.CLIENT_CLIENT_UUID + \",\" + Constants.CLIENT_IS_ACTIVE + \",\"\n + Constants.CLIENT_PROFILE_ID + \") \" +\n \" VALUES (?, ?, ?)\");\n statement.setString(1, Constants.PROFILE_CLIENT_DEFAULT_ID);\n statement.setBoolean(2, false);\n statement.setInt(3, id);\n statement.executeUpdate();\n\n profile.setName(profileName);\n profile.setId(id);\n } catch (SQLException 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\n return profile;\n }"
] | [
"private ProjectFile handleDosExeFile(InputStream stream) throws Exception\n {\n File file = InputStreamHelper.writeStreamToTempFile(stream, \".tmp\");\n InputStream is = null;\n\n try\n {\n is = new FileInputStream(file);\n if (is.available() > 1350)\n {\n StreamHelper.skip(is, 1024);\n\n // Bytes at offset 1024\n byte[] data = new byte[2];\n is.read(data);\n\n if (matchesFingerprint(data, WINDOWS_NE_EXE_FINGERPRINT))\n {\n StreamHelper.skip(is, 286);\n\n // Bytes at offset 1312\n data = new byte[34];\n is.read(data);\n if (matchesFingerprint(data, PRX_FINGERPRINT))\n {\n is.close();\n is = null;\n return readProjectFile(new P3PRXFileReader(), file);\n }\n }\n\n if (matchesFingerprint(data, STX_FINGERPRINT))\n {\n StreamHelper.skip(is, 31742);\n // Bytes at offset 32768\n data = new byte[4];\n is.read(data);\n if (matchesFingerprint(data, PRX3_FINGERPRINT))\n {\n is.close();\n is = null;\n return readProjectFile(new SureTrakSTXFileReader(), file);\n }\n }\n }\n return null;\n }\n\n finally\n {\n StreamHelper.closeQuietly(is);\n FileHelper.deleteQuietly(file);\n }\n }",
"private FieldType getFieldType(byte[] data, int offset)\n {\n int fieldIndex = MPPUtility.getInt(data, offset);\n return FieldTypeHelper.mapTextFields(FieldTypeHelper.getInstance14(fieldIndex));\n }",
"public void publish() {\n\n CmsDirectPublishDialogAction action = new CmsDirectPublishDialogAction();\n List<CmsResource> resources = getBundleResources();\n I_CmsDialogContext context = new A_CmsDialogContext(\"\", ContextType.appToolbar, resources) {\n\n public void focus(CmsUUID structureId) {\n\n //Nothing to do.\n }\n\n public List<CmsUUID> getAllStructureIdsInView() {\n\n return null;\n }\n\n public void updateUserInfo() {\n\n //Nothing to do.\n }\n };\n action.executeAction(context);\n updateLockInformation();\n\n }",
"public static void clear() {\n JobContext ctx = current_.get();\n if (null != ctx) {\n ctx.bag_.clear();\n JobContext parent = ctx.parent;\n if (null != parent) {\n current_.set(parent);\n ctx.parent = null;\n } else {\n current_.remove();\n Act.eventBus().trigger(new JobContextDestroyed(ctx));\n }\n }\n }",
"private void addHours(ProjectCalendarDateRanges ranges, Record hoursRecord)\n {\n if (hoursRecord.getValue() != null)\n {\n String[] wh = hoursRecord.getValue().split(\"\\\\|\");\n try\n {\n String startText;\n String endText;\n\n if (wh[0].equals(\"s\"))\n {\n startText = wh[1];\n endText = wh[3];\n }\n else\n {\n startText = wh[3];\n endText = wh[1];\n }\n\n // for end time treat midnight as midnight next day\n if (endText.equals(\"00:00\"))\n {\n endText = \"24:00\";\n }\n Date start = m_calendarTimeFormat.parse(startText);\n Date end = m_calendarTimeFormat.parse(endText);\n\n ranges.addRange(new DateRange(start, end));\n }\n catch (ParseException e)\n {\n // silently ignore date parse exceptions\n }\n }\n }",
"public final void notifyContentItemRangeRemoved(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for content items [0 - \"\n + (contentItemCount - 1) + \"].\");\n }\n notifyItemRangeRemoved(positionStart + headerItemCount, itemCount);\n }",
"public static List<Integer> checkKeyBelongsToPartition(byte[] key,\n Set<Pair<Integer, HashMap<Integer, List<Integer>>>> stealerNodeToMappingTuples,\n Cluster cluster,\n StoreDefinition storeDef) {\n List<Integer> keyPartitions = new RoutingStrategyFactory().updateRoutingStrategy(storeDef,\n cluster)\n .getPartitionList(key);\n List<Integer> nodesToPush = Lists.newArrayList();\n for(Pair<Integer, HashMap<Integer, List<Integer>>> stealNodeToMap: stealerNodeToMappingTuples) {\n List<Integer> nodePartitions = cluster.getNodeById(stealNodeToMap.getFirst())\n .getPartitionIds();\n if(StoreRoutingPlan.checkKeyBelongsToPartition(keyPartitions,\n nodePartitions,\n stealNodeToMap.getSecond())) {\n nodesToPush.add(stealNodeToMap.getFirst());\n }\n }\n return nodesToPush;\n }",
"private void deleteBackups() {\n File[] storeDirList = ReadOnlyUtils.getVersionDirs(storeDir, 0L, getCurrentVersionId());\n if(storeDirList != null && storeDirList.length > (numBackups + 1)) {\n // delete ALL old directories asynchronously\n File[] extraBackups = ReadOnlyUtils.findKthVersionedDir(storeDirList,\n 0,\n storeDirList.length\n - (numBackups + 1) - 1);\n if(extraBackups != null) {\n for(File backUpFile: extraBackups) {\n deleteAsync(backUpFile);\n }\n }\n }\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 }"
] |
Add the given person to the photo. Optionally, send in co-ordinates
@param photoId
@param userId
@param bounds
@throws FlickrException | [
"public void add(String photoId, String userId, Rectangle bounds) throws FlickrException {\r\n\r\n // Delegating this to photos.people.PeopleInterface - Naming standard would be to use PeopleInterface but having 2 the same name can cause issues\r\n com.flickr4java.flickr.photos.people.PeopleInterface pi = new com.flickr4java.flickr.photos.people.PeopleInterface(apiKey, sharedSecret, transportAPI);\r\n pi.add(photoId, userId, bounds);\r\n }"
] | [
"public void addFileSet(FileSet fs) {\n add(fs);\n if (fs.getProject() == null) {\n fs.setProject(getProject());\n }\n }",
"public Response remove(String id) {\r\n assertNotEmpty(id, \"id\");\r\n id = ensureDesignPrefix(id);\r\n String revision = null;\r\n // Get the revision ID from ETag, removing leading and trailing \"\r\n revision = client.executeRequest(Http.HEAD(new DatabaseURIHelper(db.getDBUri()\r\n ).documentUri(id))).getConnection().getHeaderField(\"ETag\");\r\n if (revision != null) {\r\n revision = revision.substring(1, revision.length() - 1);\r\n return db.remove(id, revision);\r\n } else {\r\n throw new CouchDbException(\"No ETag header found for design document with id \" + id);\r\n }\r\n }",
"@SuppressWarnings({})\n public synchronized void removeStoreFromSession(List<String> storeNameToRemove) {\n\n logger.info(\"closing the Streaming session for a few stores\");\n\n commitToVoldemort(storeNameToRemove);\n cleanupSessions(storeNameToRemove);\n\n }",
"protected final boolean isDurationValid() {\n\n if (isValidEndTypeForPattern()) {\n switch (getEndType()) {\n case DATE:\n return (getStart().getTime() < (getSeriesEndDate().getTime() + DAY_IN_MILLIS));\n case TIMES:\n return getOccurrences() > 0;\n case SINGLE:\n return true;\n default:\n return false;\n }\n } else {\n return false;\n }\n }",
"public void identifyClasses(final String pluginDirectory) throws Exception {\n methodInformation.clear();\n jarInformation.clear();\n try {\n new FileTraversal() {\n public void onDirectory(final File d) {\n }\n\n public void onFile(final File f) {\n try {\n // loads class files\n if (f.getName().endsWith(\".class\")) {\n // get the class name for this path\n String className = f.getAbsolutePath();\n className = className.replace(pluginDirectory, \"\");\n className = getClassNameFromPath(className);\n\n logger.info(\"Storing plugin information: {}, {}\", className,\n f.getName());\n\n ClassInformation classInfo = new ClassInformation();\n classInfo.pluginPath = pluginDirectory;\n classInformation.put(className, classInfo);\n } else if (f.getName().endsWith(\".jar\")) {\n // loads JAR packages\n // open up jar and discover files\n // look for anything with /proxy/ in it\n // this may discover things we don't need but that is OK\n try {\n jarInformation.add(f.getAbsolutePath());\n JarFile jarFile = new JarFile(f);\n Enumeration<?> enumer = jarFile.entries();\n\n // Use the Plugin-Name manifest entry to match with the provided pluginName\n String pluginPackageName = jarFile.getManifest().getMainAttributes().getValue(\"plugin-package\");\n if (pluginPackageName == null) {\n return;\n }\n\n while (enumer.hasMoreElements()) {\n Object element = enumer.nextElement();\n String elementName = element.toString();\n\n if (!elementName.endsWith(\".class\")) {\n continue;\n }\n\n String className = getClassNameFromPath(elementName);\n if (className.contains(pluginPackageName)) {\n logger.info(\"Storing plugin information: {}, {}\", className,\n f.getAbsolutePath());\n\n ClassInformation classInfo = new ClassInformation();\n classInfo.pluginPath = f.getAbsolutePath();\n classInformation.put(className, classInfo);\n }\n }\n } catch (Exception e) {\n\n }\n }\n } catch (Exception e) {\n logger.warn(\"Exception caught: {}, {}\", e.getMessage(), e.getCause());\n }\n }\n }.traverse(new File(pluginDirectory));\n } catch (IOException e) {\n throw new Exception(\"Could not identify all plugins: \" + e.getMessage());\n }\n }",
"public Object moveToNextValue(Object val) throws SQLException {\n\t\tif (dataPersister == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn dataPersister.moveToNextValue(val);\n\t\t}\n\t}",
"public void addAttribute(String attributeName, String attributeValue)\r\n {\r\n if (attributeName != null && attributeName.startsWith(JDBC_PROPERTY_NAME_PREFIX))\r\n {\r\n final String jdbcPropertyName = attributeName.substring(JDBC_PROPERTY_NAME_LENGTH);\r\n jdbcProperties.setProperty(jdbcPropertyName, attributeValue);\r\n }\r\n else if (attributeName != null && attributeName.startsWith(DBCP_PROPERTY_NAME_PREFIX))\r\n {\r\n final String dbcpPropertyName = attributeName.substring(DBCP_PROPERTY_NAME_LENGTH);\r\n dbcpProperties.setProperty(dbcpPropertyName, attributeValue);\r\n }\r\n else\r\n {\r\n super.addAttribute(attributeName, attributeValue);\r\n }\r\n }",
"public final void setWeekOfMonth(WeekOfMonth weekOfMonth) {\n\n SortedSet<WeekOfMonth> woms = new TreeSet<>();\n if (null != weekOfMonth) {\n woms.add(weekOfMonth);\n }\n setWeeksOfMonth(woms);\n }",
"protected HttpUriRequest createHttpRequest(HttpMethod httpMethod, URI uri) {\n\t\tswitch (httpMethod) {\n\t\t\tcase GET:\n\t\t\t\treturn new HttpGet(uri);\n\t\t\tcase DELETE:\n\t\t\t\treturn new HttpDelete(uri);\n\t\t\tcase HEAD:\n\t\t\t\treturn new HttpHead(uri);\n\t\t\tcase OPTIONS:\n\t\t\t\treturn new HttpOptions(uri);\n\t\t\tcase POST:\n\t\t\t\treturn new HttpPost(uri);\n\t\t\tcase PUT:\n\t\t\t\treturn new HttpPut(uri);\n\t\t\tcase TRACE:\n\t\t\t\treturn new HttpTrace(uri);\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid HTTP method: \" + httpMethod);\n\t\t}\n\t}"
] |
Get string value of flow context for current instance
@return string value of flow context | [
"public static String getFlowContext() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.flowContext;\n }"
] | [
"public void normalize() {\n double lenSqr = x * x + y * y + z * z;\n double err = lenSqr - 1;\n if (err > (2 * DOUBLE_PREC) || err < -(2 * DOUBLE_PREC)) {\n double len = Math.sqrt(lenSqr);\n x /= len;\n y /= len;\n z /= len;\n }\n }",
"public String getValueSchema() throws IOException {\n Schema schema = getInputPathAvroSchema();\n String valueSchema = schema.getField(valueFieldName).schema().toString();\n return valueSchema;\n }",
"private boolean shouldWrapMethodCall(String methodName) {\n if (methodList == null) {\n return true; // Wrap all by default\n }\n\n if (methodList.contains(methodName)) {\n return true; //Wrap a specific method\n }\n\n // If I get to this point, I should not wrap the call.\n return false;\n }",
"public AsciiTable setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setHtmlElementTranslator(htmlElementTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public PeriodicEvent runEvery(Runnable task, float delay, float period,\n int repetitions) {\n if (repetitions < 1) {\n return null;\n } else if (repetitions == 1) {\n // Better to burn a handful of CPU cycles than to churn memory by\n // creating a new callback\n return runAfter(task, delay);\n } else {\n return runEvery(task, delay, period, new RunFor(repetitions));\n }\n }",
"public Object getJavaDefaultValueDefault() {\n\t\tif (field.getType() == boolean.class) {\n\t\t\treturn DEFAULT_VALUE_BOOLEAN;\n\t\t} else if (field.getType() == byte.class || field.getType() == Byte.class) {\n\t\t\treturn DEFAULT_VALUE_BYTE;\n\t\t} else if (field.getType() == char.class || field.getType() == Character.class) {\n\t\t\treturn DEFAULT_VALUE_CHAR;\n\t\t} else if (field.getType() == short.class || field.getType() == Short.class) {\n\t\t\treturn DEFAULT_VALUE_SHORT;\n\t\t} else if (field.getType() == int.class || field.getType() == Integer.class) {\n\t\t\treturn DEFAULT_VALUE_INT;\n\t\t} else if (field.getType() == long.class || field.getType() == Long.class) {\n\t\t\treturn DEFAULT_VALUE_LONG;\n\t\t} else if (field.getType() == float.class || field.getType() == Float.class) {\n\t\t\treturn DEFAULT_VALUE_FLOAT;\n\t\t} else if (field.getType() == double.class || field.getType() == Double.class) {\n\t\t\treturn DEFAULT_VALUE_DOUBLE;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}",
"public void setDay(Day d)\n {\n if (m_day != null)\n {\n m_parentCalendar.removeHoursFromDay(this);\n }\n\n m_day = d;\n\n m_parentCalendar.attachHoursToDay(this);\n }",
"public NodeT getNext() {\n String nextItemKey = queue.poll();\n if (nextItemKey == null) {\n return null;\n }\n return nodeTable.get(nextItemKey);\n }",
"public static void unregisterMbean(ObjectName name) {\n try {\n ManagementFactory.getPlatformMBeanServer().unregisterMBean(name);\n } catch(Exception e) {\n logger.error(\"Error unregistering mbean\", e);\n }\n }"
] |
Switches DB type.
@param dbName the database type
@param webapp the webapp name | [
"private void updateDb(String dbName, String webapp) {\n\n m_mainLayout.removeAllComponents();\n m_setupBean.setDatabase(dbName);\n CmsDbSettingsPanel panel = new CmsDbSettingsPanel(m_setupBean);\n m_panel[0] = panel;\n panel.initFromSetupBean(webapp);\n m_mainLayout.addComponent(panel);\n }"
] | [
"public void setSeriesEndDate(Date date) {\r\n\r\n if (!Objects.equals(m_model.getSeriesEndDate(), date)) {\r\n m_model.setSeriesEndDate(date);\r\n valueChanged();\r\n }\r\n\r\n }",
"@CheckReturnValue\n private LocalSyncWriteModelContainer resolveConflict(\n final NamespaceSynchronizationConfig nsConfig,\n final CoreDocumentSynchronizationConfig docConfig,\n final ChangeEvent<BsonDocument> remoteEvent\n ) {\n return resolveConflict(nsConfig, docConfig, docConfig.getLastUncommittedChangeEvent(),\n remoteEvent);\n }",
"public String getBaselineDurationText()\n {\n Object result = getCachedValue(TaskField.BASELINE_DURATION);\n if (result == null)\n {\n result = getCachedValue(TaskField.BASELINE_ESTIMATED_DURATION);\n }\n\n if (!(result instanceof String))\n {\n result = null;\n }\n return (String) result;\n }",
"@Override\n public boolean invokeFunction(String funcName, Object[] params) {\n // Run script if it is dirty. This makes sure the script is run\n // on the same thread as the caller (suppose the caller is always\n // calling from the same thread).\n checkDirty();\n\n // Skip bad functions\n if (isBadFunction(funcName)) {\n return false;\n }\n\n String statement = getInvokeStatementCached(funcName, params);\n\n synchronized (mEngineLock) {\n localBindings = mLocalEngine.getBindings(ScriptContext.ENGINE_SCOPE);\n if (localBindings == null) {\n localBindings = mLocalEngine.createBindings();\n mLocalEngine.setBindings(localBindings, ScriptContext.ENGINE_SCOPE);\n }\n }\n\n fillBindings(localBindings, params);\n\n try {\n mLocalEngine.eval(statement);\n } catch (ScriptException e) {\n // The function is either undefined or throws, avoid invoking it later\n addBadFunction(funcName);\n mLastError = e.getMessage();\n return false;\n } finally {\n removeBindings(localBindings, params);\n }\n\n return true;\n }",
"protected void destroyConnection(ConnectionHandle conn) {\r\n\t\tpostDestroyConnection(conn);\r\n\t\tconn.setInReplayMode(true); // we're dead, stop attempting to replay anything\r\n\t\ttry {\r\n\t\t\t\tconn.internalClose();\r\n\t\t} catch (SQLException e) {\r\n\t\t\tlogger.error(\"Error in attempting to close connection\", e);\r\n\t\t}\r\n\t}",
"public static void log(String label, byte[] data)\n {\n if (LOG != null)\n {\n LOG.write(label);\n LOG.write(\": \");\n LOG.println(ByteArrayHelper.hexdump(data, true));\n LOG.flush();\n }\n }",
"final void compress(final File backupFile,\n final AppenderRollingProperties properties) {\n if (this.isCompressed(backupFile)) {\n LogLog.debug(\"Backup log file \" + backupFile.getName()\n + \" is already compressed\");\n return; // try not to do unnecessary work\n }\n final long lastModified = backupFile.lastModified();\n if (0L == lastModified) {\n LogLog.debug(\"Backup log file \" + backupFile.getName()\n + \" may have been scavenged\");\n return; // backup file may have been scavenged\n }\n final File deflatedFile = this.createDeflatedFile(backupFile);\n if (deflatedFile == null) {\n LogLog.debug(\"Backup log file \" + backupFile.getName()\n + \" may have been scavenged\");\n return; // an error occurred creating the file\n }\n if (this.compress(backupFile, deflatedFile, properties)) {\n deflatedFile.setLastModified(lastModified);\n FileHelper.getInstance().deleteExisting(backupFile);\n LogLog.debug(\"Compressed backup log file to \" + deflatedFile.getName());\n } else {\n FileHelper.getInstance().deleteExisting(deflatedFile); // clean up\n LogLog\n .debug(\"Unable to compress backup log file \" + backupFile.getName());\n }\n }",
"public String getOriginalValue(ParsedCommandLine parsedLine, boolean required) throws CommandFormatException {\n String value = null;\n if(parsedLine.hasProperties()) {\n if(index >= 0) {\n List<String> others = parsedLine.getOtherProperties();\n if(others.size() > index) {\n return others.get(index);\n }\n }\n\n value = parsedLine.getPropertyValue(fullName);\n if(value == null && shortName != null) {\n value = parsedLine.getPropertyValue(shortName);\n }\n }\n\n if(required && value == null && !isPresent(parsedLine)) {\n StringBuilder buf = new StringBuilder();\n buf.append(\"Required argument \");\n buf.append('\\'').append(fullName).append('\\'');\n buf.append(\" is missing.\");\n throw new CommandFormatException(buf.toString());\n }\n return value;\n }",
"WaveformDetail getWaveformDetail(int rekordboxId, SlotReference slot, Client client)\n throws IOException {\n final NumberField idField = new NumberField(rekordboxId);\n\n // First try to get the NXS2-style color waveform if we are supposed to.\n if (preferColor.get()) {\n try {\n Message response = client.simpleRequest(Message.KnownType.ANLZ_TAG_REQ, Message.KnownType.ANLZ_TAG,\n client.buildRMST(Message.MenuIdentifier.MAIN_MENU, slot.slot), idField,\n new NumberField(Message.ANLZ_FILE_TAG_COLOR_WAVEFORM_DETAIL), new NumberField(Message.ALNZ_FILE_TYPE_EXT));\n return new WaveformDetail(new DataReference(slot, rekordboxId), response);\n } catch (Exception e) {\n logger.info(\"No color waveform available for slot \" + slot + \", id \" + rekordboxId + \"; requesting blue version.\", e);\n }\n }\n\n Message response = client.simpleRequest(Message.KnownType.WAVE_DETAIL_REQ, Message.KnownType.WAVE_DETAIL,\n client.buildRMST(Message.MenuIdentifier.MAIN_MENU, slot.slot), idField, NumberField.WORD_0);\n return new WaveformDetail(new DataReference(slot, rekordboxId), response);\n }"
] |
Build the operation transformers.
@param registry the shared resource registry
@return the operation transformers | [
"protected Map<String, OperationTransformer> buildOperationTransformers(AttributeTransformationDescriptionBuilderImpl.AttributeTransformationDescriptionBuilderRegistry registry) {\n final Map<String, OperationTransformer> operations = new HashMap<String, OperationTransformer>();\n for(final Map.Entry<String, OperationTransformationEntry> entry: operationTransformers.entrySet()) {\n final OperationTransformer transformer = entry.getValue().getOperationTransformer(registry);\n operations.put(entry.getKey(), transformer);\n }\n return operations;\n }"
] | [
"public static void addToListIfNotExists(List<String> list, String value) {\n boolean found = false;\n for (String item : list) {\n if (item.equalsIgnoreCase(value)) {\n found = true;\n break;\n }\n }\n if (!found) {\n list.add(value);\n }\n }",
"public Set<CoreDocumentSynchronizationConfig> getSynchronizedDocuments(\n final MongoNamespace namespace\n ) {\n this.waitUntilInitialized();\n try {\n ongoingOperationsGroup.enter();\n return this.syncConfig.getSynchronizedDocuments(namespace);\n } finally {\n ongoingOperationsGroup.exit();\n }\n }",
"public Object getJavaDefaultValueDefault() {\n\t\tif (field.getType() == boolean.class) {\n\t\t\treturn DEFAULT_VALUE_BOOLEAN;\n\t\t} else if (field.getType() == byte.class || field.getType() == Byte.class) {\n\t\t\treturn DEFAULT_VALUE_BYTE;\n\t\t} else if (field.getType() == char.class || field.getType() == Character.class) {\n\t\t\treturn DEFAULT_VALUE_CHAR;\n\t\t} else if (field.getType() == short.class || field.getType() == Short.class) {\n\t\t\treturn DEFAULT_VALUE_SHORT;\n\t\t} else if (field.getType() == int.class || field.getType() == Integer.class) {\n\t\t\treturn DEFAULT_VALUE_INT;\n\t\t} else if (field.getType() == long.class || field.getType() == Long.class) {\n\t\t\treturn DEFAULT_VALUE_LONG;\n\t\t} else if (field.getType() == float.class || field.getType() == Float.class) {\n\t\t\treturn DEFAULT_VALUE_FLOAT;\n\t\t} else if (field.getType() == double.class || field.getType() == Double.class) {\n\t\t\treturn DEFAULT_VALUE_DOUBLE;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}",
"public static String createFirstLowCaseName(String scenarioDescription) {\n String[] words = scenarioDescription.trim().split(\" \");\n String name = \"\";\n for (int i = 0; i < words.length; i++) {\n name += changeFirstLetterToCapital(words[i]);\n }\n return changeFirstLetterToLowerCase(name);\n }",
"@Override\n public Optional<String> hash(final Optional<URL> url) throws IOException {\n if (!url.isPresent()) {\n return Optional.absent();\n }\n logger.debug(\"Calculating md5 hash, url:{}\", url);\n if (isHotReloadModeOff()) {\n final String md5 = cache.getIfPresent(url.get());\n\n logger.debug(\"md5 hash:{}\", md5);\n\n if (md5 != null) {\n return Optional.of(md5);\n }\n }\n\n final InputStream is = url.get().openStream();\n final String md5 = getMD5Checksum(is);\n\n if (isHotReloadModeOff()) {\n logger.debug(\"caching url:{} with hash:{}\", url, md5);\n\n cache.put(url.get(), md5);\n }\n\n return Optional.fromNullable(md5);\n }",
"private String getInverseOneToOneProperty(String property, OgmEntityPersister otherSidePersister) {\n\t\tfor ( String candidate : otherSidePersister.getPropertyNames() ) {\n\t\t\tType candidateType = otherSidePersister.getPropertyType( candidate );\n\t\t\tif ( candidateType.isEntityType()\n\t\t\t\t\t&& ( ( (EntityType) candidateType ).isOneToOne()\n\t\t\t\t\t&& isOneToOneMatching( this, property, (OneToOneType) candidateType ) ) ) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"public Photo getListPhoto(String photoId) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_LIST_PHOTO);\n\n parameters.put(\"photo_id\", photoId);\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 Element photoElement = response.getPayload();\n Photo photo = new Photo();\n photo.setId(photoElement.getAttribute(\"id\"));\n\n List<Tag> tags = new ArrayList<Tag>();\n Element tagsElement = (Element) photoElement.getElementsByTagName(\"tags\").item(0);\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag tag = new Tag();\n tag.setId(tagElement.getAttribute(\"id\"));\n tag.setAuthor(tagElement.getAttribute(\"author\"));\n tag.setAuthorName(tagElement.getAttribute(\"authorname\"));\n tag.setRaw(tagElement.getAttribute(\"raw\"));\n tag.setValue(((Text) tagElement.getFirstChild()).getData());\n tags.add(tag);\n }\n photo.setTags(tags);\n return photo;\n }",
"public Date getEnd() {\n\n if (null != m_explicitEnd) {\n return isWholeDay() ? adjustForWholeDay(m_explicitEnd, true) : m_explicitEnd;\n }\n if ((null == m_end) && (m_series.getInstanceDuration() != null)) {\n m_end = new Date(m_start.getTime() + m_series.getInstanceDuration().longValue());\n }\n return isWholeDay() && !m_series.isWholeDay() ? adjustForWholeDay(m_end, true) : m_end;\n }",
"@SuppressWarnings(\"unchecked\")\n protected String addPostRunDependent(Appliable<? extends Indexable> appliable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) appliable;\n return this.addPostRunDependent(dependency);\n }"
] |
creates a bounds object with both point parsed from the json and set it
to the current shape
@param modelJSON
@param current
@throws org.json.JSONException | [
"private static void parseBounds(JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"bounds\")) {\n JSONObject boundsObject = modelJSON.getJSONObject(\"bounds\");\n current.setBounds(new Bounds(new Point(boundsObject.getJSONObject(\"lowerRight\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"lowerRight\").getDouble(\n \"y\")),\n new Point(boundsObject.getJSONObject(\"upperLeft\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"upperLeft\").getDouble(\"y\"))));\n }\n }"
] | [
"public static void registerDeploymentResource(final DeploymentResourceSupport deploymentResourceSupport, final LoggingConfigurationService service) {\n final PathElement base = PathElement.pathElement(\"configuration\", service.getConfiguration());\n deploymentResourceSupport.getDeploymentSubModel(LoggingExtension.SUBSYSTEM_NAME, base);\n final LogContextConfiguration configuration = service.getValue();\n // Register the child resources if the configuration is not null in cases where a log4j configuration was used\n if (configuration != null) {\n registerDeploymentResource(deploymentResourceSupport, base, HANDLER, configuration.getHandlerNames());\n registerDeploymentResource(deploymentResourceSupport, base, LOGGER, configuration.getLoggerNames());\n registerDeploymentResource(deploymentResourceSupport, base, FORMATTER, configuration.getFormatterNames());\n registerDeploymentResource(deploymentResourceSupport, base, FILTER, configuration.getFilterNames());\n registerDeploymentResource(deploymentResourceSupport, base, POJO, configuration.getPojoNames());\n registerDeploymentResource(deploymentResourceSupport, base, ERROR_MANAGER, configuration.getErrorManagerNames());\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 static String stripHtml(String html) {\n\n if (html == null) {\n return null;\n }\n Element el = DOM.createDiv();\n el.setInnerHTML(html);\n return el.getInnerText();\n }",
"public Map<String, String> getParams() {\n\n Map<String, String> params = new HashMap<>(1);\n params.put(PARAM_COLLAPSED, Boolean.TRUE.toString());\n return params;\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 }",
"private static XMLStreamException unexpectedAttribute(final XMLStreamReader reader, final int index) {\n return SecurityManagerLogger.ROOT_LOGGER.unexpectedAttribute(reader.getAttributeName(index), reader.getLocation());\n }",
"public Duration getDuration(int field) throws MPXJException\n {\n Duration result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = DurationUtility.getInstance(m_fields[field], m_formats.getDurationDecimalFormat(), m_locale);\n }\n else\n {\n result = null;\n }\n\n return (result);\n }",
"public void removeJobType(final Class<?> jobType) {\n if (jobType == null) {\n throw new IllegalArgumentException(\"jobType must not be null\");\n }\n this.jobTypes.values().remove(jobType);\n }",
"protected CDI11Deployment createDeployment(ServletContext context, CDI11Bootstrap bootstrap) {\n\n ImmutableSet.Builder<Metadata<Extension>> extensionsBuilder = ImmutableSet.builder();\n extensionsBuilder.addAll(bootstrap.loadExtensions(WeldResourceLoader.getClassLoader()));\n if (isDevModeEnabled) {\n extensionsBuilder.add(new MetadataImpl<Extension>(DevelopmentMode.getProbeExtension(resourceLoader), \"N/A\"));\n }\n\n final Iterable<Metadata<Extension>> extensions = extensionsBuilder.build();\n final TypeDiscoveryConfiguration typeDiscoveryConfiguration = bootstrap.startExtensions(extensions);\n final EEModuleDescriptor eeModule = new EEModuleDescriptorImpl(context.getContextPath(), ModuleType.WEB);\n\n final DiscoveryStrategy strategy = DiscoveryStrategyFactory.create(resourceLoader, bootstrap, typeDiscoveryConfiguration.getKnownBeanDefiningAnnotations(),\n Boolean.parseBoolean(context.getInitParameter(Jandex.DISABLE_JANDEX_DISCOVERY_STRATEGY)));\n\n if (Jandex.isJandexAvailable(resourceLoader)) {\n try {\n Class<? extends BeanArchiveHandler> handlerClass = Reflections.loadClass(resourceLoader, JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER);\n strategy.registerHandler((SecurityActions.newConstructorInstance(handlerClass, new Class<?>[] { ServletContext.class }, context)));\n } catch (Exception e) {\n throw CommonLogger.LOG.unableToInstantiate(JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER, Arrays.toString(new Object[] { context }), e);\n }\n } else {\n strategy.registerHandler(new ServletContextBeanArchiveHandler(context));\n }\n strategy.setScanner(new WebAppBeanArchiveScanner(resourceLoader, bootstrap, context));\n Set<WeldBeanDeploymentArchive> beanDeploymentArchives = strategy.performDiscovery();\n\n String isolation = context.getInitParameter(CONTEXT_PARAM_ARCHIVE_ISOLATION);\n\n if (isolation == null || Boolean.valueOf(isolation)) {\n CommonLogger.LOG.archiveIsolationEnabled();\n } else {\n CommonLogger.LOG.archiveIsolationDisabled();\n Set<WeldBeanDeploymentArchive> flatDeployment = new HashSet<WeldBeanDeploymentArchive>();\n flatDeployment.add(WeldBeanDeploymentArchive.merge(bootstrap, beanDeploymentArchives));\n beanDeploymentArchives = flatDeployment;\n }\n\n for (BeanDeploymentArchive archive : beanDeploymentArchives) {\n archive.getServices().add(EEModuleDescriptor.class, eeModule);\n }\n\n CDI11Deployment deployment = new WeldDeployment(resourceLoader, bootstrap, beanDeploymentArchives, extensions) {\n @Override\n protected WeldBeanDeploymentArchive createAdditionalBeanDeploymentArchive() {\n WeldBeanDeploymentArchive archive = super.createAdditionalBeanDeploymentArchive();\n archive.getServices().add(EEModuleDescriptor.class, eeModule);\n return archive;\n }\n };\n\n if (strategy.getClassFileServices() != null) {\n deployment.getServices().add(ClassFileServices.class, strategy.getClassFileServices());\n }\n return deployment;\n }"
] |
Retrieves a vertex attribute as an integer array.
The attribute name must be one of the
attributes named in the descriptor passed to the constructor.
@param attributeName name of the attribute to update
@throws IllegalArgumentException if attribute name not in descriptor vertex attribute is not <i>int</i>
@see #setIntVec(String, IntBuffer)
@see #getIntArray(String) | [
"public int[] getIntArray(String attributeName)\n {\n int[] array = NativeVertexBuffer.getIntArray(getNative(), attributeName);\n if (array == null)\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return array;\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}",
"public static DMatrixRMaj extractRow(DMatrixRMaj a , int row , DMatrixRMaj out ) {\n if( out == null)\n out = new DMatrixRMaj(1,a.numCols);\n else if( !MatrixFeatures_DDRM.isVector(out) || out.getNumElements() != a.numCols )\n throw new MatrixDimensionException(\"Output must be a vector of length \"+a.numCols);\n\n System.arraycopy(a.data,a.getIndex(row,0),out.data,0,a.numCols);\n\n return out;\n }",
"public static Shell createSubshell(String pathElement, Shell parent, String appName, Object mainHandler,\n MultiMap<String, Object> auxHandlers) {\n\n List<String> newPath = new ArrayList<String>(parent.getPath());\n newPath.add(pathElement);\n\n Shell subshell = new Shell(parent.getSettings().createWithAddedAuxHandlers(auxHandlers),\n new CommandTable(parent.getCommandTable().getNamer()), newPath);\n\n subshell.setAppName(appName);\n subshell.addMainHandler(subshell, \"!\");\n subshell.addMainHandler(new HelpCommandHandler(), \"?\");\n\n subshell.addMainHandler(mainHandler, \"\");\n return subshell;\n }",
"public float getNormalZ(int vertex) {\n if (!hasNormals()) {\n throw new IllegalStateException(\"mesh has no normals\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_normals.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT);\n }",
"public static String fill(int color) {\n final String colorCode = Integer.toHexString(color & 0xFFFFFF); // Strip alpha\n return FILTER_FILL + \"(\" + colorCode + \")\";\n }",
"public static SimpleDeploymentDescription of(final String name, @SuppressWarnings(\"TypeMayBeWeakened\") final Set<String> serverGroups) {\n final SimpleDeploymentDescription result = of(name);\n if (serverGroups != null) {\n result.addServerGroups(serverGroups);\n }\n return result;\n }",
"public static long crc32(byte[] bytes, int offset, int size) {\n CRC32 crc = new CRC32();\n crc.update(bytes, offset, size);\n return crc.getValue();\n }",
"public void removeCorporateGroupId(final String organizationId, final String corporateGroupId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n\n if(dbOrganization.getCorporateGroupIdPrefixes().contains(corporateGroupId)){\n dbOrganization.getCorporateGroupIdPrefixes().remove(corporateGroupId);\n repositoryHandler.store(dbOrganization);\n }\n\n repositoryHandler.removeModulesOrganization(corporateGroupId, dbOrganization);\n }",
"public void addJobType(final String jobName, final Class<?> jobType) {\n checkJobType(jobName, jobType);\n this.jobTypes.put(jobName, jobType);\n }"
] |
Calculate the Hamming distance between two hashes
@param h1
@param h2
@return | [
"public static Integer distance(String h1, String h2) {\n\t\tHammingDistance distance = new HammingDistance();\n\t\treturn distance.apply(h1, h2);\n\t}"
] | [
"@SuppressWarnings(\"deprecation\")\n @Deprecated\n public final void validateAndSet(ModelNode operationObject, final ModelNode model) throws OperationFailedException {\n validateOperation(operationObject);\n for (AttributeDefinition ad : this.parameters) {\n ad.validateAndSet(operationObject, model);\n }\n }",
"public void addFile(String description, FileModel fileModel)\n {\n Map<FileModel, ProblemFileSummary> files = addDescription(description);\n\n if (files.containsKey(fileModel))\n {\n files.get(fileModel).addOccurrence();\n } else {\n files.put(fileModel, new ProblemFileSummary(fileModel, 1));\n }\n }",
"public static DMatrixSparseCSC symmetric( int N , int nz_total ,\n double min , double max , Random rand) {\n\n // compute the number of elements in the triangle, including diagonal\n int Ntriagle = (N*N+N)/2;\n // create a list of open elements\n int open[] = new int[Ntriagle];\n for (int row = 0, index = 0; row < N; row++) {\n for (int col = row; col < N; col++, index++) {\n open[index] = row*N+col;\n }\n }\n\n // perform a random draw\n UtilEjml.shuffle(open,open.length,0,nz_total,rand);\n Arrays.sort(open,0,nz_total);\n\n // construct the matrix\n DMatrixSparseTriplet A = new DMatrixSparseTriplet(N,N,nz_total*2);\n for (int i = 0; i < nz_total; i++) {\n int index = open[i];\n int row = index/N;\n int col = index%N;\n\n double value = rand.nextDouble()*(max-min)+min;\n\n if( row == col ) {\n A.addItem(row,col,value);\n } else {\n A.addItem(row,col,value);\n A.addItem(col,row,value);\n }\n }\n\n DMatrixSparseCSC B = new DMatrixSparseCSC(N,N,A.nz_length);\n ConvertDMatrixStruct.convert(A,B);\n\n return B;\n }",
"public ClassNode annotatedWith(String name) {\n ClassNode anno = infoBase.node(name);\n this.annotations.add(anno);\n anno.annotated.add(this);\n return this;\n }",
"private void maybeUpdateScrollbarPositions() {\r\n\r\n if (!isAttached()) {\r\n return;\r\n }\r\n\r\n if (m_scrollbar != null) {\r\n int vPos = getVerticalScrollPosition();\r\n if (m_scrollbar.getVerticalScrollPosition() != vPos) {\r\n m_scrollbar.setVerticalScrollPosition(vPos);\r\n }\r\n }\r\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 void convert(DMatrixD1 input , ZMatrixD1 output ) {\n if( input.numCols != output.numCols || input.numRows != output.numRows ) {\n throw new IllegalArgumentException(\"The matrices are not all the same dimension.\");\n }\n\n Arrays.fill(output.data, 0, output.getDataLength(), 0);\n\n final int length = output.getDataLength();\n\n for( int i = 0; i < length; i += 2 ) {\n output.data[i] = input.data[i/2];\n }\n }",
"protected I_CmsSearchConfigurationFacetRange parseRangeFacet(String pathPrefix) {\n\n try {\n final String range = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_RANGE);\n final String name = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_NAME);\n final String label = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_LABEL);\n final Integer minCount = parseOptionalIntValue(pathPrefix + XML_ELEMENT_FACET_MINCOUNT);\n final String start = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_START);\n final String end = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_END);\n final String gap = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_GAP);\n final String sother = parseOptionalStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_OTHER);\n List<I_CmsSearchConfigurationFacetRange.Other> other = null;\n if (sother != null) {\n final List<String> sothers = Arrays.asList(sother.split(\",\"));\n other = new ArrayList<I_CmsSearchConfigurationFacetRange.Other>(sothers.size());\n for (String so : sothers) {\n try {\n I_CmsSearchConfigurationFacetRange.Other o = I_CmsSearchConfigurationFacetRange.Other.valueOf(\n so);\n other.add(o);\n } catch (final Exception e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_INVALID_OTHER_OPTION_1, so), e);\n }\n }\n }\n final Boolean hardEnd = parseOptionalBooleanValue(pathPrefix + XML_ELEMENT_RANGE_FACET_HARDEND);\n final Boolean isAndFacet = parseOptionalBooleanValue(pathPrefix + XML_ELEMENT_FACET_ISANDFACET);\n final List<String> preselection = parseOptionalStringValues(pathPrefix + XML_ELEMENT_FACET_PRESELECTION);\n final Boolean ignoreAllFacetFilters = parseOptionalBooleanValue(\n pathPrefix + XML_ELEMENT_FACET_IGNOREALLFACETFILTERS);\n return new CmsSearchConfigurationFacetRange(\n range,\n start,\n end,\n gap,\n other,\n hardEnd,\n name,\n minCount,\n label,\n isAndFacet,\n preselection,\n ignoreAllFacetFilters);\n } catch (final Exception e) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_RANGE_FACET_MANDATORY_KEY_MISSING_1,\n XML_ELEMENT_RANGE_FACET_RANGE\n + \", \"\n + XML_ELEMENT_RANGE_FACET_START\n + \", \"\n + XML_ELEMENT_RANGE_FACET_END\n + \", \"\n + XML_ELEMENT_RANGE_FACET_GAP),\n e);\n return null;\n }\n\n }",
"private void clearMetadata(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(hotCache.keySet())) {\n if (deck.player == player) {\n hotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverTrackMetadataUpdate(player, null); // Inform listeners the metadata is gone.\n }\n }\n }\n }"
] |
Sets any application-specific custom fields. The values
are presented to the application and the iPhone doesn't
display them automatically.
This can be used to pass specific values (urls, ids, etc) to
the application in addition to the notification message
itself.
@param key the custom field name
@param value the custom field value
@return this | [
"public PayloadBuilder customField(final String key, final Object value) {\n root.put(key, value);\n return this;\n }"
] | [
"@Override\n\tpublic int compareTo(IPAddressString other) {\n\t\tif(this == other) {\n\t\t\treturn 0;\n\t\t}\n\t\tboolean isValid = isValid();\n\t\tboolean otherIsValid = other.isValid();\n\t\tif(!isValid && !otherIsValid) {\n\t\t\treturn toString().compareTo(other.toString());\n\t\t}\n\t\treturn addressProvider.providerCompare(other.addressProvider);\n\t}",
"public Optional<ServerPort> activePort() {\n final Server server = this.server;\n return server != null ? server.activePort() : Optional.empty();\n }",
"public T update(T entity) throws RowNotFoundException, OptimisticLockException {\n\n if (!hasPrimaryKey(entity)) {\n throw new RuntimeException(String.format(\"Tried to update entity of type %s without a primary key\", entity\n .getClass().getSimpleName()));\n }\n\n UpdateCreator update = new UpdateCreator(table);\n\n update.whereEquals(idColumn.getColumnName(), getPrimaryKey(entity));\n\n if (versionColumn != null) {\n update.set(versionColumn.getColumnName() + \" = \" + versionColumn.getColumnName() + \" + 1\");\n update.whereEquals(versionColumn.getColumnName(), getVersion(entity));\n }\n\n for (Column column : columns) {\n if (!column.isReadOnly()) {\n update.setValue(column.getColumnName(), getFieldValueAsColumn(entity, column));\n }\n }\n\n int rows = new JdbcTemplate(ormConfig.getDataSource()).update(update);\n\n if (rows == 1) {\n\n if (versionColumn != null) {\n ReflectionUtils.setFieldValue(entity, versionColumn.getFieldName(), getVersion(entity) + 1);\n }\n\n return entity;\n\n } else if (rows > 1) {\n\n throw new RuntimeException(\n String.format(\"Updating table %s with id %s updated %d rows. There must be a mapping problem. Is column %s really the primary key?\",\n table, getPrimaryKey(entity), rows, idColumn));\n\n } else {\n\n //\n // Updated zero rows. This could be because our ID is wrong, or\n // because our object is out-of date. Let's try querying just by ID.\n //\n\n SelectCreator selectById = new SelectCreator()\n .column(\"count(*)\")\n .from(table)\n .whereEquals(idColumn.getColumnName(), getPrimaryKey(entity));\n\n rows = new JdbcTemplate(ormConfig.getDataSource()).query(selectById, new ResultSetExtractor<Integer>() {\n @Override\n public Integer extractData(ResultSet rs) throws SQLException, DataAccessException {\n rs.next();\n return rs.getInt(1);\n }\n });\n\n if (rows == 0) {\n throw new RowNotFoundException(table, getPrimaryKey(entity));\n } else {\n throw new OptimisticLockException(table, getPrimaryKey(entity));\n }\n }\n }",
"public static int scanright(Color color, int height, int width, int col, PixelsExtractor f, int tolerance) {\n if (col == width || !PixelTools.colorMatches(color, tolerance, f.apply(new Area(col, 0, 1, height))))\n return col;\n else\n return scanright(color, height, width, col + 1, f, tolerance);\n }",
"protected Integer getCorrectIndex(Integer index) {\n Integer size = jsonNode.size();\n Integer newIndex = index;\n\n // reverse walking through the array\n if(index < 0) {\n newIndex = size + index;\n }\n\n // the negative index would be greater than the size a second time!\n if(newIndex < 0) {\n throw LOG.indexOutOfBounds(index, size);\n }\n\n // the index is greater as the actual size\n if(index > size) {\n throw LOG.indexOutOfBounds(index, size);\n }\n\n return newIndex;\n }",
"public static String get(Properties props, String name, String defval) {\n String value = props.getProperty(name);\n if (value == null)\n value = defval;\n return value;\n }",
"public static base_responses delete(nitro_service client, ntpserver resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tntpserver deleteresources[] = new ntpserver[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new ntpserver();\n\t\t\t\tdeleteresources[i].serverip = resources[i].serverip;\n\t\t\t\tdeleteresources[i].servername = resources[i].servername;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public String getNotes()\n {\n String notes = (String) getCachedValue(ResourceField.NOTES);\n return (notes == null ? \"\" : notes);\n }",
"private void writeTasks(Project project)\n {\n Project.Tasks tasks = m_factory.createProjectTasks();\n project.setTasks(tasks);\n List<Project.Tasks.Task> list = tasks.getTask();\n\n for (Task task : m_projectFile.getTasks())\n {\n list.add(writeTask(task));\n }\n }"
] |
If a policy already exists on a folder, this will apply that policy to all existing files and sub folders within
the target folder.
@param conflictResolution the desired behavior for conflict-resolution. Set to either none or overwrite. | [
"public void forceApply(String conflictResolution) {\n\n URL url = FORCE_METADATA_CASCADE_POLICIES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"conflict_resolution\", conflictResolution);\n request.setBody(requestJSON.toString());\n request.send();\n }"
] | [
"public static int[] randomSubset(int k, int n) {\n assert(0 < k && k <= n);\n Random r = new Random();\n int t = 0, m = 0;\n int[] result = new int[k];\n\n while (m < k) {\n double u = r.nextDouble();\n if ( (n - t) * u < k - m ) {\n result[m] = t;\n m++;\n }\n t++;\n }\n return result;\n }",
"public static final Long date2utc(Date date) {\n\n // use null for a null date\n if (date == null) return null;\n \n long time = date.getTime();\n \n // remove the timezone offset \n time -= timezoneOffsetMillis(date);\n \n return time;\n }",
"protected void writeRow(final String... columns) throws IOException {\n\t\t\n\t\tif( columns == null ) {\n\t\t\tthrow new NullPointerException(String.format(\"columns to write should not be null on line %d\", lineNumber));\n\t\t} else if( columns.length == 0 ) {\n\t\t\tthrow new IllegalArgumentException(String.format(\"columns to write should not be empty on line %d\",\n\t\t\t\tlineNumber));\n\t\t}\n\t\t\n\t\tStringBuilder builder = new StringBuilder();\n\t\tfor( int i = 0; i < columns.length; i++ ) {\n\t\t\t\n\t\t\tcolumnNumber = i + 1; // column no used by CsvEncoder\n\t\t\t\n\t\t\tif( i > 0 ) {\n\t\t\t\tbuilder.append((char) preference.getDelimiterChar()); // delimiter\n\t\t\t}\n\t\t\t\n\t\t\tfinal String csvElement = columns[i];\n\t\t\tif( csvElement != null ) {\n\t\t\t\tfinal CsvContext context = new CsvContext(lineNumber, rowNumber, columnNumber);\n\t\t\t\tfinal String escapedCsv = encoder.encode(csvElement, context, preference);\n\t\t\t\tbuilder.append(escapedCsv);\n\t\t\t\tlineNumber = context.getLineNumber(); // line number can increment when encoding multi-line columns\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tbuilder.append(preference.getEndOfLineSymbols()); // EOL\n\t\twriter.write(builder.toString());\n\t}",
"public Boolean invoke(File pomFile, VirtualChannel channel) throws IOException, InterruptedException {\n\n org.jfrog.build.extractor.maven.reader.ModuleName current = new org.jfrog.build.extractor.maven.reader.ModuleName(\n currentModule.groupId, currentModule.artifactId);\n\n Map<org.jfrog.build.extractor.maven.reader.ModuleName, String> modules = Maps.newLinkedHashMap();\n for (Map.Entry<ModuleName, String> entry : versionsByModule.entrySet()) {\n modules.put(new org.jfrog.build.extractor.maven.reader.ModuleName(\n entry.getKey().groupId, entry.getKey().artifactId), entry.getValue());\n }\n\n org.jfrog.build.extractor.maven.transformer.PomTransformer transformer =\n new org.jfrog.build.extractor.maven.transformer.PomTransformer(current, modules, scmUrl,\n failOnSnapshot);\n\n return transformer.transform(pomFile);\n }",
"public static Bitmap flip(Bitmap src) {\n Matrix m = new Matrix();\n m.preScale(-1, 1);\n return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), m, false);\n }",
"private void setConstraints(Task task, MapRow row)\n {\n ConstraintType constraintType = null;\n Date constraintDate = null;\n Date lateDate = row.getDate(\"CONSTRAINT_LATE_DATE\");\n Date earlyDate = row.getDate(\"CONSTRAINT_EARLY_DATE\");\n\n switch (row.getInteger(\"CONSTRAINT_TYPE\").intValue())\n {\n case 2: // Cannot Reschedule\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = task.getStart();\n break;\n }\n\n case 12: //Finish Between\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = lateDate;\n break;\n }\n\n case 10: // Finish On or After\n {\n constraintType = ConstraintType.FINISH_NO_EARLIER_THAN;\n constraintDate = earlyDate;\n break;\n }\n\n case 11: // Finish On or Before\n {\n constraintType = ConstraintType.FINISH_NO_LATER_THAN;\n constraintDate = lateDate;\n break;\n }\n\n case 13: // Mandatory Start\n case 5: // Start On\n case 9: // Finish On\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = earlyDate;\n break;\n }\n\n case 14: // Mandatory Finish\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = earlyDate;\n break;\n }\n\n case 4: // Start As Late As Possible\n {\n constraintType = ConstraintType.AS_LATE_AS_POSSIBLE;\n break;\n }\n\n case 3: // Start As Soon As Possible\n {\n constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n break;\n }\n\n case 8: // Start Between\n {\n constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n constraintDate = earlyDate;\n break;\n }\n\n case 6: // Start On or Before\n {\n constraintType = ConstraintType.START_NO_LATER_THAN;\n constraintDate = earlyDate;\n break;\n }\n\n case 15: // Work Between\n {\n constraintType = ConstraintType.START_NO_EARLIER_THAN;\n constraintDate = earlyDate;\n break;\n }\n }\n task.setConstraintType(constraintType);\n task.setConstraintDate(constraintDate);\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 }",
"private synchronized Response doAuthenticatedRequest(\n final StitchAuthRequest stitchReq,\n final AuthInfo authInfo\n ) {\n try {\n return requestClient.doRequest(prepareAuthRequest(stitchReq, authInfo));\n } catch (final StitchServiceException ex) {\n return handleAuthFailure(ex, stitchReq);\n }\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}"
] |
why isn't this functionality in enum? | [
"private static LogPriorType intToType(int intPrior) {\r\n LogPriorType[] values = LogPriorType.values();\r\n for (LogPriorType val : values) {\r\n if (val.ordinal() == intPrior) {\r\n return val;\r\n }\r\n }\r\n throw new IllegalArgumentException(intPrior + \" is not a legal LogPrior.\");\r\n }"
] | [
"public ParallelTaskBuilder setSshPrivKeyRelativePath(\n String privKeyRelativePath) {\n this.sshMeta.setPrivKeyRelativePath(privKeyRelativePath);\n this.sshMeta.setSshLoginType(SshLoginType.KEY);\n return this;\n }",
"private void createSimpleCubeSixMeshes(GVRContext gvrContext,\n boolean facingOut, String vertexDesc, ArrayList<GVRTexture> textureList)\n {\n GVRSceneObject[] children = new GVRSceneObject[6];\n GVRMesh[] meshes = new GVRMesh[6];\n GVRVertexBuffer vbuf = new GVRVertexBuffer(gvrContext, vertexDesc, SIMPLE_VERTICES.length / 3);\n\n if (facingOut)\n {\n vbuf.setFloatArray(\"a_position\", SIMPLE_VERTICES, 3, 0);\n vbuf.setFloatArray(\"a_normal\", SIMPLE_OUTWARD_NORMALS, 3, 0);\n vbuf.setFloatArray(\"a_texcoord\", SIMPLE_OUTWARD_TEXCOORDS, 2, 0);\n meshes[0] = createMesh(vbuf, SIMPLE_OUTWARD_FRONT_INDICES);\n meshes[1] = createMesh(vbuf, SIMPLE_OUTWARD_RIGHT_INDICES);\n meshes[2] = createMesh(vbuf, SIMPLE_OUTWARD_BACK_INDICES);\n meshes[3] = createMesh(vbuf, SIMPLE_OUTWARD_LEFT_INDICES);\n meshes[4] = createMesh(vbuf, SIMPLE_OUTWARD_TOP_INDICES);\n meshes[5] = createMesh(vbuf, SIMPLE_OUTWARD_BOTTOM_INDICES);\n }\n else\n {\n vbuf.setFloatArray(\"a_position\", SIMPLE_VERTICES, 3, 0);\n vbuf.setFloatArray(\"a_normal\", SIMPLE_INWARD_NORMALS, 3, 0);\n vbuf.setFloatArray(\"a_texcoord\", SIMPLE_INWARD_TEXCOORDS, 2, 0);\n meshes[0] = createMesh(vbuf, SIMPLE_INWARD_FRONT_INDICES);\n meshes[1] = createMesh(vbuf, SIMPLE_INWARD_RIGHT_INDICES);\n meshes[2] = createMesh(vbuf, SIMPLE_INWARD_BACK_INDICES);\n meshes[3] = createMesh(vbuf, SIMPLE_INWARD_LEFT_INDICES);\n meshes[4] = createMesh(vbuf, SIMPLE_INWARD_TOP_INDICES);\n meshes[5] = createMesh(vbuf, SIMPLE_INWARD_BOTTOM_INDICES);\n }\n\n for (int i = 0; i < 6; i++)\n {\n children[i] = new GVRSceneObject(gvrContext, meshes[i], textureList.get(i));\n addChildObject(children[i]);\n }\n\n // attached an empty renderData for parent object, so that we can set some common properties\n GVRRenderData renderData = new GVRRenderData(gvrContext);\n attachRenderData(renderData);\n }",
"public float getBoundsWidth() {\n if (mSceneObject != null) {\n GVRSceneObject.BoundingVolume v = mSceneObject.getBoundingVolume();\n return v.maxCorner.x - v.minCorner.x;\n }\n return 0f;\n }",
"private long size(final Jedis jedis, final String queueName) {\n final String key = key(QUEUE, queueName);\n final long size;\n if (JedisUtils.isDelayedQueue(jedis, key)) { // If delayed queue, use ZCARD\n size = jedis.zcard(key);\n } else { // Else, use LLEN\n size = jedis.llen(key);\n }\n return size;\n }",
"public double[] getZeroRates(double[] maturities)\n\t{\n\t\tdouble[] values = new double[maturities.length];\n\n\t\tfor(int i=0; i<maturities.length; i++) {\n\t\t\tvalues[i] = getZeroRate(maturities[i]);\n\t\t}\n\n\t\treturn values;\n\t}",
"public void addComparator(Comparator<T> comparator, boolean ascending) {\n\t\tthis.comparators.add(new InvertibleComparator<T>(comparator, ascending));\n\t}",
"@RequestMapping(value = \"/api/backup\", method = RequestMethod.POST)\n public\n @ResponseBody\n Backup processBackup(@RequestParam(\"fileData\") MultipartFile fileData) throws Exception {\n // Method taken from: http://spring.io/guides/gs/uploading-files/\n if (!fileData.isEmpty()) {\n try {\n byte[] bytes = fileData.getBytes();\n BufferedOutputStream stream =\n new BufferedOutputStream(new FileOutputStream(new File(\"backup-uploaded.json\")));\n stream.write(bytes);\n stream.close();\n\n } catch (Exception e) {\n }\n }\n File f = new File(\"backup-uploaded.json\");\n BackupService.getInstance().restoreBackupData(new FileInputStream(f));\n return BackupService.getInstance().getBackupData();\n }",
"public static String resourceProviderFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).providerNamespace() : null;\n }",
"void insertMacros(TokenList tokens ) {\n TokenList.Token t = tokens.getFirst();\n while( t != null ) {\n if( t.getType() == Type.WORD ) {\n Macro v = lookupMacro(t.word);\n if (v != null) {\n TokenList.Token before = t.previous;\n List<TokenList.Token> inputs = new ArrayList<TokenList.Token>();\n t = parseMacroInput(inputs,t.next);\n\n TokenList sniplet = v.execute(inputs);\n tokens.extractSubList(before.next,t);\n tokens.insertAfter(before,sniplet);\n t = sniplet.last;\n }\n }\n t = t.next;\n }\n }"
] |
Adds the specified list of users as members of the project. Returns the updated project record.
@param project The project to add members to.
@return Request object | [
"public ItemRequest<Project> addMembers(String project) {\n \n String path = String.format(\"/projects/%s/addMembers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }"
] | [
"public synchronized void jumpToBeat(int beat) {\n\n if (beat < 1) {\n beat = 1;\n } else {\n beat = wrapBeat(beat);\n }\n\n if (playing.get()) {\n metronome.jumpToBeat(beat);\n } else {\n whereStopped.set(metronome.getSnapshot(metronome.getTimeOfBeat(beat)));\n }\n }",
"public String interpolate( String input, RecursionInterceptor recursionInterceptor )\n\t throws InterpolationException\n\t {\n\t try\n\t {\n\t return interpolate( input, recursionInterceptor, new HashSet<String>() );\n\t }\n\t finally\n\t {\n\t if ( !cacheAnswers )\n\t {\n\t existingAnswers.clear();\n\t }\n\t }\n\t }",
"@Override\n public void sendResponse(StoreStats performanceStats,\n boolean isFromLocalZone,\n long startTimeInMs) throws Exception {\n\n /*\n * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage.\n * However when writing to the outputStream we only send the multiPart object and not the entire\n * mimeMessage. This is intentional.\n *\n * In the earlier version of this code we used to create a multiPart object and just send that multiPart\n * across the wire.\n *\n * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates\n * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated\n * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the\n * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders()\n * on the body part. It's this updateHeaders call that transfers the content type from the\n * DataHandler to the part's MIME Content-Type header.\n *\n * To make sure that the Content-Type headers are being updated (without changing too much code), we decided\n * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart.\n * This is to make sure multiPart's headers are updated accurately.\n */\n\n MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));\n MimeMultipart multiPart = new MimeMultipart();\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n String base64Key = RestUtils.encodeVoldemortKey(key.get());\n String contentLocationKey = \"/\" + this.storeName + \"/\" + base64Key;\n\n for(Versioned<byte[]> versionedValue: versionedValues) {\n\n byte[] responseValue = versionedValue.getValue();\n\n VectorClock vectorClock = (VectorClock) versionedValue.getVersion();\n String eTag = RestUtils.getSerializedVectorClock(vectorClock);\n numVectorClockEntries += vectorClock.getVersionMap().size();\n\n // Create the individual body part for each versioned value of the\n // requested key\n MimeBodyPart body = new MimeBodyPart();\n try {\n // Add the right headers\n body.addHeader(CONTENT_TYPE, \"application/octet-stream\");\n body.addHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n body.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag);\n body.setContent(responseValue, \"application/octet-stream\");\n body.addHeader(RestMessageHeaders.CONTENT_LENGTH,\n Integer.toString(responseValue.length));\n\n multiPart.addBodyPart(body);\n } catch(MessagingException me) {\n logger.error(\"Exception while constructing body part\", me);\n outputStream.close();\n throw me;\n }\n\n }\n message.setContent(multiPart);\n message.saveChanges();\n try {\n multiPart.writeTo(outputStream);\n } catch(Exception e) {\n logger.error(\"Exception while writing multipart to output stream\", e);\n outputStream.close();\n throw e;\n }\n ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();\n responseContent.writeBytes(outputStream.toByteArray());\n\n // Create the Response object\n HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);\n\n // Set the right headers\n response.setHeader(CONTENT_TYPE, \"multipart/binary\");\n response.setHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n response.setHeader(CONTENT_LOCATION, contentLocationKey);\n\n // Copy the data into the payload\n response.setContent(responseContent);\n response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());\n\n // Write the response to the Netty Channel\n if(logger.isDebugEnabled()) {\n String keyStr = RestUtils.getKeyHexString(this.key);\n debugLog(\"GET\",\n this.storeName,\n keyStr,\n startTimeInMs,\n System.currentTimeMillis(),\n numVectorClockEntries);\n }\n this.messageEvent.getChannel().write(response);\n\n if(performanceStats != null && isFromLocalZone) {\n recordStats(performanceStats, startTimeInMs, Tracked.GET);\n }\n\n outputStream.close();\n\n }",
"public static List<Object> listOfEntities(SharedSessionContractImplementor session, Type[] resultTypes, ClosableIterator<Tuple> tuples) {\n\t\tClass<?> returnedClass = resultTypes[0].getReturnedClass();\n\t\tTupleBasedEntityLoader loader = getLoader( session, returnedClass );\n\t\tOgmLoadingContext ogmLoadingContext = new OgmLoadingContext();\n\t\togmLoadingContext.setTuples( getTuplesAsList( tuples ) );\n\t\treturn loader.loadEntitiesFromTuples( session, LockOptions.NONE, ogmLoadingContext );\n\t}",
"public static nspbr6_stats[] get(nitro_service service, options option) throws Exception{\n\t\tnspbr6_stats obj = new nspbr6_stats();\n\t\tnspbr6_stats[] response = (nspbr6_stats[])obj.stat_resources(service,option);\n\t\treturn response;\n\t}",
"private Map<String, Entry> readEntries(String mapping, boolean ignoreCase) {\n\t\tMap<String, Entry> entries = new HashMap<>();\n\n\t\ttry {\n\t\t\t// ms, 2010-10-05: try to load the file from the CLASSPATH first\n\t\t\tInputStream is = getClass().getClassLoader().getResourceAsStream(mapping);\n\t\t\t// if not found in the CLASSPATH, load from the file system\n\t\t\tif (is == null) is = new FileInputStream(mapping);\n\t\t\tBufferedReader rd = new BufferedReader(new InputStreamReader(is));\n\n\t\t\tint lineCount = 0;\n\t\t\tfor (String line; (line = rd.readLine()) != null; ) {\n\t\t\t\tlineCount ++;\n\t\t\t\tString[] split = line.split(\"\\t\");\n\t\t\t\tif (split.length < 2 || split.length > 4)\n\t\t\t\t\tthrow new RuntimeException(\"Provided mapping file is in wrong format\");\n\t\t\t\tif (split[1].trim().equalsIgnoreCase(\"AS\")) System.err.println(\"ERRRR \" + mapping + \"|\" + line + \" at \" + lineCount);\n\t\t\t\tString stringLine = split[1].trim();\n\t\t\t\tif (ignoreCase) stringLine = stringLine.toLowerCase();\n\t\t\t\tString[] words = stringLine.split(\"\\\\s+\");\n\t\t\t\tString type = split[0].trim();\n\t\t\t\tSet<String> overwritableTypes = new HashSet<String>();\n\t\t\t\toverwritableTypes.add(flags.backgroundSymbol);\n\t\t\t\toverwritableTypes.add(null);\n\t\t\t\tdouble priority = 0;\n\t\t\t\tList<String> tokens = new ArrayList<String>();\n\n\t\t\t\ttry {\n\t\t\t\t\tif (split.length >= 3)\n\t\t\t\t\t\toverwritableTypes.addAll(Arrays.asList(split[2].trim().split(\",\")));\n\t\t\t\t\tif (split.length == 4)\n\t\t\t\t\t\tpriority = Double.parseDouble(split[3].trim());\n\n\t\t\t\t\tfor (String str : words) {\n\t\t\t\t\t\ttokens.add(str);\n\t\t\t\t\t}\n\t\t\t\t} catch(NumberFormatException e) {\n\t\t\t\t\tSystem.err.println(\"ERROR: Invalid line \" + lineCount + \" in regexner file \" + mapping + \": \\\"\" + line + \"\\\"!\");\n\t\t\t\t\tthrow e;\n\t\t\t\t}\n\t\t\t\taddEntry(words, type, priority, overwritableTypes);\n\t\t\t}\n\t\t\trd.close();\n\t\t\tis.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn entries;\n\t}",
"@Override\n public void attachScriptFile(IScriptable target, IScriptFile scriptFile) {\n mScriptMap.put(target, scriptFile);\n scriptFile.invokeFunction(\"onAttach\", new Object[] { target });\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 void setSomePendingWritesAndSave(\n final long atTime,\n final ChangeEvent<BsonDocument> changeEvent\n ) {\n docLock.writeLock().lock();\n try {\n // if we were frozen\n if (isPaused) {\n // unfreeze the document due to the local write\n setPaused(false);\n // and now the unfrozen document is now stale\n setStale(true);\n }\n\n this.lastUncommittedChangeEvent =\n coalesceChangeEvents(this.lastUncommittedChangeEvent, changeEvent);\n this.lastResolution = atTime;\n docsColl.replaceOne(\n getDocFilter(namespace, documentId),\n this);\n } finally {\n docLock.writeLock().unlock();\n }\n }"
] |
Determines if the queue identified by the given key is used.
@param jedis
connection to Redis
@param key
the key that identifies a queue
@return true if the key is used, false otherwise | [
"public static boolean isKeyUsed(final Jedis jedis, final String key) {\n return !NONE.equalsIgnoreCase(jedis.type(key));\n }"
] | [
"public Object getJavaDefaultValueDefault() {\n\t\tif (field.getType() == boolean.class) {\n\t\t\treturn DEFAULT_VALUE_BOOLEAN;\n\t\t} else if (field.getType() == byte.class || field.getType() == Byte.class) {\n\t\t\treturn DEFAULT_VALUE_BYTE;\n\t\t} else if (field.getType() == char.class || field.getType() == Character.class) {\n\t\t\treturn DEFAULT_VALUE_CHAR;\n\t\t} else if (field.getType() == short.class || field.getType() == Short.class) {\n\t\t\treturn DEFAULT_VALUE_SHORT;\n\t\t} else if (field.getType() == int.class || field.getType() == Integer.class) {\n\t\t\treturn DEFAULT_VALUE_INT;\n\t\t} else if (field.getType() == long.class || field.getType() == Long.class) {\n\t\t\treturn DEFAULT_VALUE_LONG;\n\t\t} else if (field.getType() == float.class || field.getType() == Float.class) {\n\t\t\treturn DEFAULT_VALUE_FLOAT;\n\t\t} else if (field.getType() == double.class || field.getType() == Double.class) {\n\t\t\treturn DEFAULT_VALUE_DOUBLE;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}",
"public boolean validation() throws ParallelTaskInvalidException {\n\n ParallelTask task = new ParallelTask();\n targetHostMeta = new TargetHostMeta(targetHosts);\n\n task = new ParallelTask(requestProtocol, concurrency, httpMeta,\n targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta, null, responseContext,\n replacementVarMapNodeSpecific,\n replacementVarMap, requestReplacementType, config);\n boolean valid = false;\n\n try {\n valid = task.validateWithFillDefault();\n } catch (ParallelTaskInvalidException e) {\n logger.info(\"task is invalid \" + e);\n }\n\n return valid;\n\n }",
"private void compile(ICompilationUnit[] sourceUnits, boolean lastRound) {\n this.stats.startTime = System.currentTimeMillis();\n try {\n // build and record parsed units\n reportProgress(Messages.compilation_beginningToCompile);\n\n if (this.options.complianceLevel >= ClassFileConstants.JDK9) {\n // in Java 9 the compiler must never ask the oracle for a module that is contained in the input units:\n sortModuleDeclarationsFirst(sourceUnits);\n }\n if (this.annotationProcessorManager == null) {\n beginToCompile(sourceUnits);\n } else {\n ICompilationUnit[] originalUnits = sourceUnits.clone(); // remember source units in case a source type collision occurs\n try {\n beginToCompile(sourceUnits);\n if (!lastRound) {\n processAnnotations();\n }\n if (!this.options.generateClassFiles) {\n // -proc:only was set on the command line\n return;\n }\n } catch (SourceTypeCollisionException e) {\n backupAptProblems();\n reset();\n // a generated type was referenced before it was created\n // the compiler either created a MissingType or found a BinaryType for it\n // so add the processor's generated files & start over,\n // but remember to only pass the generated files to the annotation processor\n int originalLength = originalUnits.length;\n int newProcessedLength = e.newAnnotationProcessorUnits.length;\n ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength];\n System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength);\n System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength);\n this.annotationProcessorStartIndex = originalLength;\n compile(combinedUnits, e.isLastRound);\n return;\n }\n }\n // Restore the problems before the results are processed and cleaned up.\n restoreAptProblems();\n processCompiledUnits(0, lastRound);\n } catch (AbortCompilation e) {\n this.handleInternalException(e, null);\n }\n if (this.options.verbose) {\n if (this.totalUnits > 1) {\n this.out.println(\n Messages.bind(Messages.compilation_units, String.valueOf(this.totalUnits)));\n } else {\n this.out.println(\n Messages.bind(Messages.compilation_unit, String.valueOf(this.totalUnits)));\n }\n }\n }",
"public Widget addControl(String name, int resId, String label, Widget.OnTouchListener listener) {\n return addControl(name, resId, label, listener, -1);\n }",
"public static <T> Set<T> toSet(Iterable<T> items) {\r\n Set<T> set = new HashSet<T>();\r\n addAll(set, items);\r\n return set;\r\n }",
"public void setProductModules(final String name, final List<String> moduleNames) {\n final DbProduct dbProduct = getProduct(name);\n dbProduct.setModules(moduleNames);\n repositoryHandler.store(dbProduct);\n }",
"public void fillRect(int x, int y, int w, int h, Color c) {\n int color = c.getRGB();\n for (int i = x; i < x + w; i++) {\n for (int j = y; j < y + h; j++) {\n setIntColor(i, j, color);\n }\n }\n }",
"private void readResource(net.sf.mpxj.ganttproject.schema.Resource gpResource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n mpxjResource.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpResource.getId()) + 1));\n mpxjResource.setName(gpResource.getName());\n mpxjResource.setEmailAddress(gpResource.getContacts());\n mpxjResource.setText(1, gpResource.getPhone());\n mpxjResource.setGroup(m_roleDefinitions.get(gpResource.getFunction()));\n\n net.sf.mpxj.ganttproject.schema.Rate gpRate = gpResource.getRate();\n if (gpRate != null)\n {\n mpxjResource.setStandardRate(new Rate(gpRate.getValueAttribute(), TimeUnit.DAYS));\n }\n readResourceCustomFields(gpResource, mpxjResource);\n m_eventManager.fireResourceReadEvent(mpxjResource);\n }",
"public AutomatonInstance doClone() {\n\t\tAutomatonInstance clone = new AutomatonInstance(this.automatonEng, this.current, this.instanceId, this.safeGuard);\n\t\tclone.failed = this.failed;\n\t\tclone.transitionCount = this.transitionCount;\n\t\tclone.failCount = this.failCount;\n\t\tclone.iterateCount = this.iterateCount;\n\t\tclone.backtrackCount = this.backtrackCount;\n\t\tclone.trace = new LinkedList<>();\n\t\tfor(StateExploration se:this.trace) {\n\t\t\tclone.trace.add(se.doClone());\n\t\t}\n\t\treturn clone;\n\t}"
] |
Returns the overtime cost of this resource assignment.
@return cost | [
"public Number getOvertimeCost()\n {\n Number cost = (Number) getCachedValue(AssignmentField.OVERTIME_COST);\n if (cost == null)\n {\n Number actual = getActualOvertimeCost();\n Number remaining = getRemainingOvertimeCost();\n if (actual != null && remaining != null)\n {\n cost = NumberHelper.getDouble(actual.doubleValue() + remaining.doubleValue());\n set(AssignmentField.OVERTIME_COST, cost);\n }\n }\n return (cost);\n }"
] | [
"public PartialCollection<BoxItem.Info> getItemsRange(long offset, long limit, String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder()\n .appendParam(\"offset\", offset)\n .appendParam(\"limit\", limit);\n\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n\n URL url = GET_COLLECTION_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), builder.toString(), 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 String totalCountString = responseJSON.get(\"total_count\").toString();\n long fullSize = Double.valueOf(totalCountString).longValue();\n PartialCollection<BoxItem.Info> items = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue entry : entries) {\n BoxItem.Info entryInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), entry.asObject());\n if (entryInfo != null) {\n items.add(entryInfo);\n }\n }\n return items;\n }",
"public <T> T find(Class<T> classType, String id) {\n return db.find(classType, id);\n }",
"public static base_response add(nitro_service client, tmtrafficaction resource) throws Exception {\n\t\ttmtrafficaction addresource = new tmtrafficaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.apptimeout = resource.apptimeout;\n\t\taddresource.sso = resource.sso;\n\t\taddresource.formssoaction = resource.formssoaction;\n\t\taddresource.persistentcookie = resource.persistentcookie;\n\t\taddresource.initiatelogout = resource.initiatelogout;\n\t\taddresource.kcdaccount = resource.kcdaccount;\n\t\taddresource.samlssoprofile = resource.samlssoprofile;\n\t\treturn addresource.add_resource(client);\n\t}",
"public void setDropShadowColor(int color) {\n GradientDrawable.Orientation orientation = getDropShadowOrientation();\n\n final int endColor = color & 0x00FFFFFF;\n mDropShadowDrawable = new GradientDrawable(orientation,\n new int[] {\n color,\n endColor,\n });\n invalidate();\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 base_response add(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup addresource = new cachecontentgroup();\n\t\taddresource.name = resource.name;\n\t\taddresource.weakposrelexpiry = resource.weakposrelexpiry;\n\t\taddresource.heurexpiryparam = resource.heurexpiryparam;\n\t\taddresource.relexpiry = resource.relexpiry;\n\t\taddresource.relexpirymillisec = resource.relexpirymillisec;\n\t\taddresource.absexpiry = resource.absexpiry;\n\t\taddresource.absexpirygmt = resource.absexpirygmt;\n\t\taddresource.weaknegrelexpiry = resource.weaknegrelexpiry;\n\t\taddresource.hitparams = resource.hitparams;\n\t\taddresource.invalparams = resource.invalparams;\n\t\taddresource.ignoreparamvaluecase = resource.ignoreparamvaluecase;\n\t\taddresource.matchcookies = resource.matchcookies;\n\t\taddresource.invalrestrictedtohost = resource.invalrestrictedtohost;\n\t\taddresource.polleverytime = resource.polleverytime;\n\t\taddresource.ignorereloadreq = resource.ignorereloadreq;\n\t\taddresource.removecookies = resource.removecookies;\n\t\taddresource.prefetch = resource.prefetch;\n\t\taddresource.prefetchperiod = resource.prefetchperiod;\n\t\taddresource.prefetchperiodmillisec = resource.prefetchperiodmillisec;\n\t\taddresource.prefetchmaxpending = resource.prefetchmaxpending;\n\t\taddresource.flashcache = resource.flashcache;\n\t\taddresource.expireatlastbyte = resource.expireatlastbyte;\n\t\taddresource.insertvia = resource.insertvia;\n\t\taddresource.insertage = resource.insertage;\n\t\taddresource.insertetag = resource.insertetag;\n\t\taddresource.cachecontrol = resource.cachecontrol;\n\t\taddresource.quickabortsize = resource.quickabortsize;\n\t\taddresource.minressize = resource.minressize;\n\t\taddresource.maxressize = resource.maxressize;\n\t\taddresource.memlimit = resource.memlimit;\n\t\taddresource.ignorereqcachinghdrs = resource.ignorereqcachinghdrs;\n\t\taddresource.minhits = resource.minhits;\n\t\taddresource.alwaysevalpolicies = resource.alwaysevalpolicies;\n\t\taddresource.persist = resource.persist;\n\t\taddresource.pinned = resource.pinned;\n\t\taddresource.lazydnsresolve = resource.lazydnsresolve;\n\t\taddresource.hitselector = resource.hitselector;\n\t\taddresource.invalselector = resource.invalselector;\n\t\taddresource.type = resource.type;\n\t\treturn addresource.add_resource(client);\n\t}",
"public Collection<Size> getSizes(String photoId, boolean sign) throws FlickrException {\r\n SizeList<Size> sizes = new SizeList<Size>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_SIZES);\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 sizesElement = response.getPayload();\r\n sizes.setIsCanBlog(\"1\".equals(sizesElement.getAttribute(\"canblog\")));\r\n sizes.setIsCanDownload(\"1\".equals(sizesElement.getAttribute(\"candownload\")));\r\n sizes.setIsCanPrint(\"1\".equals(sizesElement.getAttribute(\"canprint\")));\r\n NodeList sizeNodes = sizesElement.getElementsByTagName(\"size\");\r\n for (int i = 0; i < sizeNodes.getLength(); i++) {\r\n Element sizeElement = (Element) sizeNodes.item(i);\r\n Size size = new Size();\r\n size.setLabel(sizeElement.getAttribute(\"label\"));\r\n size.setWidth(sizeElement.getAttribute(\"width\"));\r\n size.setHeight(sizeElement.getAttribute(\"height\"));\r\n size.setSource(sizeElement.getAttribute(\"source\"));\r\n size.setUrl(sizeElement.getAttribute(\"url\"));\r\n size.setMedia(sizeElement.getAttribute(\"media\"));\r\n sizes.add(size);\r\n }\r\n return sizes;\r\n }",
"private Object getColumnValue(String table, String column, String data, int type, boolean epochDateFormat) throws MPXJException\n {\n try\n {\n Object value = null;\n\n switch (type)\n {\n case Types.BIT:\n {\n value = DatatypeConverter.parseBoolean(data);\n break;\n }\n\n case Types.VARCHAR:\n case Types.LONGVARCHAR:\n {\n value = DatatypeConverter.parseString(data);\n break;\n }\n\n case Types.TIME:\n {\n value = DatatypeConverter.parseBasicTime(data);\n break;\n }\n\n case Types.TIMESTAMP:\n {\n if (epochDateFormat)\n {\n value = DatatypeConverter.parseEpochTimestamp(data);\n }\n else\n {\n value = DatatypeConverter.parseBasicTimestamp(data);\n }\n break;\n }\n\n case Types.DOUBLE:\n {\n value = DatatypeConverter.parseDouble(data);\n break;\n }\n\n case Types.INTEGER:\n {\n value = DatatypeConverter.parseInteger(data);\n break;\n }\n\n default:\n {\n throw new IllegalArgumentException(\"Unsupported SQL type: \" + type);\n }\n }\n\n return value;\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to parse \" + table + \".\" + column + \" (data=\" + data + \", type=\" + type + \")\", ex);\n }\n }",
"public static boolean isInverse(DMatrixRMaj a , DMatrixRMaj b , double tol ) {\n if( a.numRows != b.numRows || a.numCols != b.numCols ) {\n return false;\n }\n\n int numRows = a.numRows;\n int numCols = a.numCols;\n\n for( int i = 0; i < numRows; i++ ) {\n for( int j = 0; j < numCols; j++ ) {\n double total = 0;\n for( int k = 0; k < numCols; k++ ) {\n total += a.get(i,k)*b.get(k,j);\n }\n\n if( i == j ) {\n if( !(Math.abs(total-1) <= tol) )\n return false;\n } else if( !(Math.abs(total) <= tol) )\n return false;\n }\n }\n\n return true;\n }"
] |
Get the time zone for a specific exchange suffix
@param suffix suffix for the exchange in YahooFinance
@return time zone of the exchange | [
"public static TimeZone get(String suffix) {\n if(SUFFIX_TIMEZONES.containsKey(suffix)) {\n return SUFFIX_TIMEZONES.get(suffix);\n }\n log.warn(\"Cannot find time zone for exchange suffix: '{}'. Using default: America/New_York\", suffix);\n return SUFFIX_TIMEZONES.get(\"\");\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 }",
"public void doRun(Properties properties) {\n ServerSetup[] serverSetup = new PropertiesBasedServerSetupBuilder().build(properties);\n\n if (serverSetup.length == 0) {\n printUsage(System.out);\n\n } else {\n greenMail = new GreenMail(serverSetup);\n log.info(\"Starting GreenMail standalone v{} using {}\",\n BuildInfo.INSTANCE.getProjectVersion(), Arrays.toString(serverSetup));\n greenMail.withConfiguration(new PropertiesBasedGreenMailConfigurationBuilder().build(properties))\n .start();\n }\n }",
"public static final boolean setSelectedValue(ListBox list, String value, boolean addMissingValues) {\n\tif (value == null) {\n\t list.setSelectedIndex(0);\n\t return false;\n\t}\n\telse {\n\t int index = findValueInListBox(list, value);\n\t if (index >= 0) {\n\t\tlist.setSelectedIndex(index);\n\t\treturn true;\n\t }\n\n\t if (addMissingValues) {\n\t\tlist.addItem(value, value);\n\n\t\t// now that it's there, search again\n\t\tindex = findValueInListBox(list, value);\n\t\tlist.setSelectedIndex(index);\n\t\treturn true;\n\t }\n\n\t return false;\n\t}\n }",
"private void countCooccurringProperties(\n\t\t\tStatementDocument statementDocument, UsageRecord usageRecord,\n\t\t\tPropertyIdValue thisPropertyIdValue) {\n\t\tfor (StatementGroup sg : statementDocument.getStatementGroups()) {\n\t\t\tif (!sg.getProperty().equals(thisPropertyIdValue)) {\n\t\t\t\tInteger propertyId = getNumId(sg.getProperty().getId(), false);\n\t\t\t\tif (!usageRecord.propertyCoCounts.containsKey(propertyId)) {\n\t\t\t\t\tusageRecord.propertyCoCounts.put(propertyId, 1);\n\t\t\t\t} else {\n\t\t\t\t\tusageRecord.propertyCoCounts.put(propertyId,\n\t\t\t\t\t\t\tusageRecord.propertyCoCounts.get(propertyId) + 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public long queryForCountStar(DatabaseConnection databaseConnection) throws SQLException {\n\t\tif (countStarQuery == null) {\n\t\t\tStringBuilder sb = new StringBuilder(64);\n\t\t\tsb.append(\"SELECT COUNT(*) FROM \");\n\t\t\tdatabaseType.appendEscapedEntityName(sb, tableInfo.getTableName());\n\t\t\tcountStarQuery = sb.toString();\n\t\t}\n\t\tlong count = databaseConnection.queryForLong(countStarQuery);\n\t\tlogger.debug(\"query of '{}' returned {}\", countStarQuery, count);\n\t\treturn count;\n\t}",
"public void bindMappers()\n {\n JacksonXmlModule xmlModule = new JacksonXmlModule();\n\n xmlModule.setDefaultUseWrapper(false);\n\n XmlMapper xmlMapper = new XmlMapper(xmlModule);\n\n xmlMapper.enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION);\n\n this.bind(XmlMapper.class).toInstance(xmlMapper);\n\n ObjectMapper objectMapper = new ObjectMapper();\n\n objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true);\n objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);\n objectMapper.configure(DeserializationFeature.EAGER_DESERIALIZER_FETCH, true);\n objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);\n objectMapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);\n objectMapper.registerModule(new AfterburnerModule());\n objectMapper.registerModule(new Jdk8Module());\n\n this.bind(ObjectMapper.class).toInstance(objectMapper);\n this.requestStaticInjection(Extractors.class);\n this.requestStaticInjection(ServerResponse.class);\n }",
"private void batchStatusLog(int batchCount,\n int numBatches,\n int partitionStoreCount,\n int numPartitionStores,\n long totalTimeMs) {\n // Calculate the estimated end time and pretty print stats\n double rate = 1;\n long estimatedTimeMs = 0;\n if(numPartitionStores > 0) {\n rate = partitionStoreCount / numPartitionStores;\n estimatedTimeMs = (long) (totalTimeMs / rate) - totalTimeMs;\n }\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"Batch Complete!\")\n .append(Utils.NEWLINE)\n .append(\"\\tbatches moved: \")\n .append(batchCount)\n .append(\" out of \")\n .append(numBatches)\n .append(Utils.NEWLINE)\n .append(\"\\tPartition stores moved: \")\n .append(partitionStoreCount)\n .append(\" out of \")\n .append(numPartitionStores)\n .append(Utils.NEWLINE)\n .append(\"\\tPercent done: \")\n .append(decimalFormatter.format(rate * 100.0))\n .append(Utils.NEWLINE)\n .append(\"\\tEstimated time left: \")\n .append(estimatedTimeMs)\n .append(\" ms (\")\n .append(TimeUnit.MILLISECONDS.toHours(estimatedTimeMs))\n .append(\" hours)\");\n RebalanceUtils.printBatchLog(batchCount, logger, sb.toString());\n }",
"static EntityIdValue fromId(String id, String siteIri) {\n\t\tswitch (guessEntityTypeFromId(id)) {\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_ITEM:\n\t\t\t\treturn new ItemIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_PROPERTY:\n\t\t\t\treturn new PropertyIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_LEXEME:\n\t\t\t\treturn new LexemeIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_FORM:\n\t\t\t\treturn new FormIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_SENSE:\n\t\t\t\treturn new SenseIdValueImpl(id, siteIri);\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Entity id \\\"\" + id + \"\\\" is not supported.\");\n\t\t}\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 }"
] |
Returns a lazily generated map from site paths of resources to the available locales for the resource.
@return a lazily generated map from site paths of resources to the available locales for the resource. | [
"public Map<String, List<Locale>> getAvailableLocales() {\n\n if (m_availableLocales == null) {\n // create lazy map only on demand\n m_availableLocales = CmsCollectionsGenericWrapper.createLazyMap(new CmsAvailableLocaleLoaderTransformer());\n }\n return m_availableLocales;\n }"
] | [
"private void logBlock(int blockIndex, int startIndex, int blockLength)\n {\n if (m_log != null)\n {\n m_log.println(\"Block Index: \" + blockIndex);\n m_log.println(\"Length: \" + blockLength + \" (\" + Integer.toHexString(blockLength) + \")\");\n m_log.println();\n m_log.println(FastTrackUtility.hexdump(m_buffer, startIndex, blockLength, true, 16, \"\"));\n m_log.flush();\n }\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 List<Integer> nodeIds = null;\n Boolean allNodes = true;\n List<String> storeNames = null;\n\n // parse command-line input\n args = AdminToolUtils.copyArrayAddFirst(args, \"--\" + OPT_HEAD_META_GET_RO);\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_GET_RO);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n AdminParserUtils.checkOptional(options,\n AdminParserUtils.OPT_NODE,\n AdminParserUtils.OPT_ALL_NODES);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_STORE);\n\n // load parameters\n metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET_RO);\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_NODE)) {\n nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);\n allNodes = false;\n }\n storeNames = (List<String>) options.valuesOf(AdminParserUtils.OPT_STORE);\n\n // execute command\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n if(allNodes) {\n nodeIds = AdminToolUtils.getAllNodeIds(adminClient);\n }\n\n if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) {\n metaKeys = Lists.newArrayList();\n metaKeys.add(KEY_MAX_VERSION);\n metaKeys.add(KEY_CURRENT_VERSION);\n metaKeys.add(KEY_STORAGE_FORMAT);\n }\n\n doMetaGetRO(adminClient, nodeIds, storeNames, metaKeys);\n }",
"public int scrollToItem(int position) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToItem position = %d\", position);\n scrollToPosition(position);\n return mCurrentItemIndex;\n }",
"protected Patch createProcessedPatch(final Patch original) {\n\n // Process elements\n final List<PatchElement> elements = new ArrayList<PatchElement>();\n // Process layers\n for (final PatchEntry entry : getLayers()) {\n final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications);\n elements.add(element);\n }\n // Process add-ons\n for (final PatchEntry entry : getAddOns()) {\n final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications);\n elements.add(element);\n }\n\n // Swap the patch element modifications, keep the identity ones since we don't need to fix the misc modifications\n return new PatchImpl(original.getPatchId(), original.getDescription(), original.getLink(), original.getIdentity(), elements, identityEntry.modifications);\n }",
"protected int adjustIndex(Widget child, int beforeIndex) {\n\n checkIndexBoundsForInsertion(beforeIndex);\n\n // Check to see if this widget is already a direct child.\n if (child.getParent() == this) {\n // If the Widget's previous position was left of the desired new position\n // shift the desired position left to reflect the removal\n int idx = getWidgetIndex(child);\n if (idx < beforeIndex) {\n beforeIndex--;\n }\n }\n\n return beforeIndex;\n }",
"protected float computeUniformPadding(final CacheDataSet cache) {\n float axisSize = getViewPortSize(getOrientationAxis());\n float totalPadding = axisSize - cache.getTotalSize();\n float uniformPadding = totalPadding > 0 && cache.count() > 1 ?\n totalPadding / (cache.count() - 1) : 0;\n return uniformPadding;\n }",
"public static final BigInteger printConstraintType(ConstraintType value)\n {\n return (value == null ? null : BigInteger.valueOf(value.getValue()));\n }",
"private void nodeProperties(Options opt) {\n\tOptions def = opt.getGlobalOptions();\n\tif (opt.nodeFontName != def.nodeFontName)\n\t w.print(\",fontname=\\\"\" + opt.nodeFontName + \"\\\"\");\n\tif (opt.nodeFontColor != def.nodeFontColor)\n\t w.print(\",fontcolor=\\\"\" + opt.nodeFontColor + \"\\\"\");\n\tif (opt.nodeFontSize != def.nodeFontSize)\n\t w.print(\",fontsize=\" + fmt(opt.nodeFontSize));\n\tw.print(opt.shape.style);\n\tw.println(\"];\");\n }",
"protected String addDependency(TaskGroup.HasTaskGroup dependency) {\n Objects.requireNonNull(dependency);\n this.taskGroup().addDependencyTaskGroup(dependency.taskGroup());\n return dependency.taskGroup().key();\n }"
] |
Notifies all interested subscribers of the given revision.
@param mwRevision
the given revision
@param isCurrent
true if this is guaranteed to be the most current revision | [
"void notifyMwRevisionProcessors(MwRevision mwRevision, boolean isCurrent) {\n\t\tif (mwRevision == null || mwRevision.getPageId() <= 0) {\n\t\t\treturn;\n\t\t}\n\t\tfor (MwRevisionProcessorBroker.RevisionSubscription rs : this.revisionSubscriptions) {\n\t\t\tif (rs.onlyCurrentRevisions == isCurrent\n\t\t\t\t\t&& (rs.model == null || mwRevision.getModel().equals(\n\t\t\t\t\t\t\trs.model))) {\n\t\t\t\trs.mwRevisionProcessor.processRevision(mwRevision);\n\t\t\t}\n\t\t}\n\t}"
] | [
"private ChildTaskContainer getParentTask(Activity activity)\n {\n //\n // Make a map of activity codes and their values for this activity\n //\n Map<UUID, UUID> map = getActivityCodes(activity);\n\n //\n // Work through the activity codes in sequence\n //\n ChildTaskContainer parent = m_projectFile;\n StringBuilder uniqueIdentifier = new StringBuilder();\n for (UUID activityCode : m_codeSequence)\n {\n UUID activityCodeValue = map.get(activityCode);\n String activityCodeText = m_activityCodeValues.get(activityCodeValue);\n if (activityCodeText != null)\n {\n if (uniqueIdentifier.length() != 0)\n {\n uniqueIdentifier.append('>');\n }\n uniqueIdentifier.append(activityCodeValue.toString());\n UUID uuid = UUID.nameUUIDFromBytes(uniqueIdentifier.toString().getBytes());\n Task newParent = findChildTaskByUUID(parent, uuid);\n if (newParent == null)\n {\n newParent = parent.addTask();\n newParent.setGUID(uuid);\n newParent.setName(activityCodeText);\n }\n parent = newParent;\n }\n }\n return parent;\n }",
"private synchronized void finishTransition(final InternalState current, final InternalState next) {\n internalSetState(getTransitionTask(next), current, next);\n transition();\n }",
"private Object getParameter(String name, String value) throws ParseException, NumberFormatException {\n\t\tObject result = null;\n\t\tif (name.length() > 0) {\n\n\t\t\tswitch (name.charAt(0)) {\n\t\t\t\tcase 'i':\n\t\t\t\t\tif (null == value || value.length() == 0) {\n\t\t\t\t\t\tvalue = \"0\";\n\t\t\t\t\t}\n\t\t\t\t\tresult = new Integer(value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'f':\n\t\t\t\t\tif (name.startsWith(\"form\")) {\n\t\t\t\t\t\tresult = value;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (null == value || value.length() == 0) {\n\t\t\t\t\t\t\tvalue = \"0.0\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresult = new Double(value);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'd':\n\t\t\t\t\tif (null == value || value.length() == 0) {\n\t\t\t\t\t\tresult = null;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tSimpleDateFormat dateParser = new SimpleDateFormat(\"yyyy-MM-dd\");\n\t\t\t\t\t\tresult = dateParser.parse(value);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 't':\n\t\t\t\t\tif (null == value || value.length() == 0) {\n\t\t\t\t\t\tresult = null;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tSimpleDateFormat timeParser = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\t\t\t\t\t\tresult = timeParser.parse(value);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'b':\n\t\t\t\t\tresult = \"true\".equalsIgnoreCase(value) ? Boolean.TRUE : Boolean.FALSE;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tresult = value;\n\t\t\t}\n\t\t\tif (log.isDebugEnabled()) {\n\t\t\t\tif (result != null) {\n\t\t\t\t\tlog.debug(\n\t\t\t\t\t\t\t\"parameter \" + name + \" value \" + result + \" class \" + result.getClass().getName());\n\t\t\t\t} else {\n\t\t\t\t\tlog.debug(\"parameter\" + name + \"is null\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}",
"public Plugin[] getPlugins(Boolean onlyValid) {\n Configuration[] configurations = ConfigurationService.getInstance().getConfigurations(Constants.DB_TABLE_CONFIGURATION_PLUGIN_PATH);\n\n ArrayList<Plugin> plugins = new ArrayList<Plugin>();\n\n if (configurations == null) {\n return new Plugin[0];\n }\n\n for (Configuration config : configurations) {\n Plugin plugin = new Plugin();\n plugin.setId(config.getId());\n plugin.setPath(config.getValue());\n\n File path = new File(plugin.getPath());\n if (path.isDirectory()) {\n plugin.setStatus(Constants.PLUGIN_STATUS_VALID);\n plugin.setStatusMessage(\"Valid\");\n } else {\n plugin.setStatus(Constants.PLUGIN_STATUS_NOT_DIRECTORY);\n plugin.setStatusMessage(\"Path is not a directory\");\n }\n\n if (!onlyValid || plugin.getStatus() == Constants.PLUGIN_STATUS_VALID) {\n plugins.add(plugin);\n }\n }\n\n return plugins.toArray(new Plugin[0]);\n }",
"public static base_response disable(nitro_service client, nsfeature resource) throws Exception {\n\t\tnsfeature disableresource = new nsfeature();\n\t\tdisableresource.feature = resource.feature;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}",
"public static base_response update(nitro_service client, systemuser resource) throws Exception {\n\t\tsystemuser updateresource = new systemuser();\n\t\tupdateresource.username = resource.username;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.externalauth = resource.externalauth;\n\t\tupdateresource.promptstring = resource.promptstring;\n\t\tupdateresource.timeout = resource.timeout;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public void setEndTime(final Date date) {\r\n\r\n if (!Objects.equals(m_model.getEnd(), date)) {\r\n m_model.setEnd(date);\r\n valueChanged();\r\n }\r\n\r\n }",
"public boolean process( int sideLength,\n double diag[] ,\n double off[] ,\n double eigenvalues[] ) {\n if( diag != null )\n helper.init(diag,off,sideLength);\n if( Q == null )\n Q = CommonOps_DDRM.identity(helper.N);\n helper.setQ(Q);\n\n this.followingScript = true;\n this.eigenvalues = eigenvalues;\n this.fastEigenvalues = false;\n\n return _process();\n }",
"public static csvserver_cspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cspolicy_binding obj = new csvserver_cspolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cspolicy_binding response[] = (csvserver_cspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.