query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Use this API to update tmtrafficaction.
[ "public static base_response update(nitro_service client, tmtrafficaction resource) throws Exception {\n\t\ttmtrafficaction updateresource = new tmtrafficaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.apptimeout = resource.apptimeout;\n\t\tupdateresource.sso = resource.sso;\n\t\tupdateresource.formssoaction = resource.formssoaction;\n\t\tupdateresource.persistentcookie = resource.persistentcookie;\n\t\tupdateresource.initiatelogout = resource.initiatelogout;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\tupdateresource.samlssoprofile = resource.samlssoprofile;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
[ "@SuppressWarnings(\"deprecation\")\n public boolean cancelOnTargetHosts(List<String> targetHosts) {\n\n boolean success = false;\n\n try {\n\n switch (state) {\n\n case IN_PROGRESS:\n if (executionManager != null\n && !executionManager.isTerminated()) {\n executionManager.tell(new CancelTaskOnHostRequest(\n targetHosts), executionManager);\n logger.info(\n \"asked task to stop from running on target hosts with count {}...\",\n targetHosts.size());\n } else {\n logger.info(\"manager already killed or not exist.. NO OP\");\n }\n success = true;\n break;\n case COMPLETED_WITHOUT_ERROR:\n case COMPLETED_WITH_ERROR:\n case WAITING:\n logger.info(\"will NO OP for cancelOnTargetHost as it is not in IN_PROGRESS state\");\n success = true;\n break;\n default:\n break;\n\n }\n\n } catch (Exception e) {\n logger.error(\n \"cancel task {} on hosts with count {} error with exception details \",\n this.getTaskId(), targetHosts.size(), e);\n }\n\n return success;\n }", "private static MessageInfoType mapMessageInfo(MessageInfo messageInfo) {\n if (messageInfo == null) {\n return null;\n }\n MessageInfoType miType = new MessageInfoType();\n miType.setMessageId(messageInfo.getMessageId());\n miType.setFlowId(messageInfo.getFlowId());\n miType.setPorttype(convertString(messageInfo.getPortType()));\n miType.setOperationName(messageInfo.getOperationName());\n miType.setTransport(messageInfo.getTransportType());\n return miType;\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 static BoxAPIConnection getTransactionConnection(String accessToken, String scope, String resource) {\n BoxAPIConnection apiConnection = new BoxAPIConnection(accessToken);\n\n URL url;\n try {\n url = new URL(apiConnection.getTokenURL());\n } catch (MalformedURLException e) {\n assert false : \"An invalid token URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid token URL indicates a bug in the SDK.\", e);\n }\n\n String urlParameters;\n try {\n urlParameters = String.format(\"grant_type=%s&subject_token=%s&subject_token_type=%s&scope=%s\", GRANT_TYPE,\n URLEncoder.encode(accessToken, \"UTF-8\"), SUBJECT_TOKEN_TYPE, URLEncoder.encode(scope, \"UTF-8\"));\n\n if (resource != null) {\n urlParameters += \"&resource=\" + URLEncoder.encode(resource, \"UTF-8\");\n }\n } catch (UnsupportedEncodingException e) {\n throw new BoxAPIException(\n \"An error occurred while attempting to encode url parameters for a transactional token request\"\n );\n }\n\n BoxAPIRequest request = new BoxAPIRequest(apiConnection, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n final String fileToken = responseJSON.get(\"access_token\").asString();\n BoxTransactionalAPIConnection transactionConnection = new BoxTransactionalAPIConnection(fileToken);\n transactionConnection.setExpires(responseJSON.get(\"expires_in\").asLong() * 1000);\n\n return transactionConnection;\n }", "public static double getHaltonNumberForGivenBase(long index, int base) {\n\t\tindex += 1;\n\n\t\tdouble x = 0.0;\n\t\tdouble factor = 1.0 / base;\n\t\twhile(index > 0) {\n\t\t\tx += (index % base) * factor;\n\t\t\tfactor /= base;\n\t\t\tindex /= base;\n\t\t}\n\n\t\treturn x;\n\t}", "public ItemRequest<Task> addTag(String task) {\n \n String path = String.format(\"/tasks/%s/addTag\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "private void writeToFile(List<DomainControllerData> data, String domainName) throws IOException {\n if(domainName == null || data == null) {\n return;\n }\n\n if (conn == null) {\n init();\n }\n\n try {\n String key = S3Util.sanitize(domainName) + \"/\" + S3Util.sanitize(DC_FILE_NAME);\n byte[] buf = S3Util.domainControllerDataToByteBuffer(data);\n S3Object val = new S3Object(buf, null);\n if (usingPreSignedUrls()) {\n Map headers = new TreeMap();\n headers.put(\"x-amz-acl\", Arrays.asList(\"public-read\"));\n conn.put(pre_signed_put_url, val, headers).connection.getResponseMessage();\n } else {\n Map headers = new TreeMap();\n headers.put(\"Content-Type\", Arrays.asList(\"text/plain\"));\n conn.put(location, key, val, headers).connection.getResponseMessage();\n }\n }\n catch(Exception e) {\n throw HostControllerLogger.ROOT_LOGGER.cannotWriteToS3File(e.getLocalizedMessage());\n }\n }", "public static base_responses unset(nitro_service client, String acl6name[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 unsetresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tunsetresources[i] = new nsacl6();\n\t\t\t\tunsetresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "static void checkUpgradeConditions(final UpgradeCondition condition, final InstallationManager.MutablePatchingTarget target) throws PatchingException {\n // See if the prerequisites are met\n for (final String required : condition.getRequires()) {\n if (!target.isApplied(required)) {\n throw PatchLogger.ROOT_LOGGER.requiresPatch(required);\n }\n }\n // Check for incompatibilities\n for (final String incompatible : condition.getIncompatibleWith()) {\n if (target.isApplied(incompatible)) {\n throw PatchLogger.ROOT_LOGGER.incompatiblePatch(incompatible);\n }\n }\n }" ]
checks whether the specified Object obj is write-locked by Transaction tx. @param tx the transaction @param obj the Object to be checked @return true if lock exists, else false
[ "public boolean checkWrite(TransactionImpl tx, Object obj)\r\n {\r\n LockEntry writer = getWriter(obj);\r\n if (writer == null)\r\n return false;\r\n else if (writer.isOwnedBy(tx))\r\n return true;\r\n else\r\n return false;\r\n }" ]
[ "public ConverterServerBuilder workerPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) {\n assertNumericArgument(corePoolSize, true);\n assertNumericArgument(maximumPoolSize, true);\n assertNumericArgument(corePoolSize + maximumPoolSize, false);\n assertNumericArgument(keepAliveTime, true);\n this.corePoolSize = corePoolSize;\n this.maximumPoolSize = maximumPoolSize;\n this.keepAliveTime = unit.toMillis(keepAliveTime);\n return this;\n }", "private void createAndAddButton(PatternType pattern, String messageKey) {\n\n CmsRadioButton btn = new CmsRadioButton(pattern.toString(), Messages.get().key(messageKey));\n btn.addStyleName(I_CmsWidgetsLayoutBundle.INSTANCE.widgetCss().radioButtonlabel());\n btn.setGroup(m_groupPattern);\n m_patternButtons.put(pattern, btn);\n m_patternRadioButtonsPanel.add(btn);\n\n }", "protected boolean isSingleConnection(DatabaseConnection conn1, DatabaseConnection conn2) throws SQLException {\n\t\t// initialize the connections auto-commit flags\n\t\tconn1.setAutoCommit(true);\n\t\tconn2.setAutoCommit(true);\n\t\ttry {\n\t\t\t// change conn1's auto-commit to be false\n\t\t\tconn1.setAutoCommit(false);\n\t\t\tif (conn2.isAutoCommit()) {\n\t\t\t\t// if the 2nd connection's auto-commit is still true then we have multiple connections\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\t// if the 2nd connection's auto-commit is also false then we have a single connection\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} finally {\n\t\t\t// restore its auto-commit\n\t\t\tconn1.setAutoCommit(true);\n\t\t}\n\t}", "public void process(String inputFile, String outputFile) throws Exception\n {\n System.out.println(\"Reading input file started.\");\n long start = System.currentTimeMillis();\n ProjectFile projectFile = readFile(inputFile);\n long elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Reading input file completed in \" + elapsed + \"ms.\");\n\n System.out.println(\"Writing output file started.\");\n start = System.currentTimeMillis();\n ProjectWriter writer = ProjectWriterUtility.getProjectWriter(outputFile);\n writer.write(projectFile, outputFile);\n elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Writing output completed in \" + elapsed + \"ms.\");\n }", "public static List<Map<String, Object>> listify(ObjectMapper mapper, Object source) {\n return (List<Map<String, Object>>) collectify(mapper, source, List.class);\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 deploySchema(String generatedProtobufName, RemoteCache<String, String> protobufCache, SchemaCapture schemaCapture, SchemaOverride schemaOverrideService,\n\t\t\tURL schemaOverrideResource) {\n\t\t// user defined schema\n\t\tif ( schemaOverrideService != null || schemaOverrideResource != null ) {\n\t\t\tcachedSchema = new SchemaValidator( this, schemaOverrideService, schemaOverrideResource, generatedProtobufName ).provideSchema();\n\t\t}\n\n\t\t// or generate them\n\t\tgenerateProtoschema();\n\n\t\ttry {\n\t\t\tprotobufCache.put( generatedProtobufName, cachedSchema );\n\t\t\tString errors = protobufCache.get( generatedProtobufName + \".errors\" );\n\t\t\tif ( errors != null ) {\n\t\t\t\tthrow LOG.errorAtSchemaDeploy( generatedProtobufName, errors );\n\t\t\t}\n\t\t\tLOG.successfulSchemaDeploy( generatedProtobufName );\n\t\t}\n\t\tcatch (HotRodClientException hrce) {\n\t\t\tthrow LOG.errorAtSchemaDeploy( generatedProtobufName, hrce );\n\t\t}\n\t\tif ( schemaCapture != null ) {\n\t\t\tschemaCapture.put( generatedProtobufName, cachedSchema );\n\t\t}\n\t}", "public Date getStart()\n {\n Date result = null;\n for (ResourceAssignment assignment : m_assignments)\n {\n if (result == null || DateHelper.compare(result, assignment.getStart()) > 0)\n {\n result = assignment.getStart();\n }\n }\n return (result);\n }", "private Envelope getBoundsLocal(Filter filter) throws LayerException {\n\t\ttry {\n\t\t\tSession session = getSessionFactory().getCurrentSession();\n\t\t\tCriteria criteria = session.createCriteria(getFeatureInfo().getDataSourceName());\n\t\t\tCriteriaVisitor visitor = new CriteriaVisitor((HibernateFeatureModel) getFeatureModel(), dateFormat);\n\t\t\tCriterion c = (Criterion) filter.accept(visitor, criteria);\n\t\t\tif (c != null) {\n\t\t\t\tcriteria.add(c);\n\t\t\t}\n\t\t\tcriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);\n\t\t\tList<?> features = criteria.list();\n\t\t\tEnvelope bounds = new Envelope();\n\t\t\tfor (Object f : features) {\n\t\t\t\tEnvelope geomBounds = getFeatureModel().getGeometry(f).getEnvelopeInternal();\n\t\t\t\tif (!geomBounds.isNull()) {\n\t\t\t\t\tbounds.expandToInclude(geomBounds);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bounds;\n\t\t} catch (HibernateException he) {\n\t\t\tthrow new HibernateLayerException(he, ExceptionCode.HIBERNATE_LOAD_FILTER_FAIL, getFeatureInfo()\n\t\t\t\t\t.getDataSourceName(), filter.toString());\n\t\t}\n\t}" ]
Replaces the translations in an existing container with the translations for the provided locale. @param locale the locale for which translations should be loaded. @return <code>true</code> if replacing succeeded, <code>false</code> otherwise.
[ "private boolean replaceValues(Locale locale) {\n\n try {\n SortedProperties localization = getLocalization(locale);\n if (hasDescriptor()) {\n for (Object itemId : m_container.getItemIds()) {\n Item item = m_container.getItem(itemId);\n String key = item.getItemProperty(TableProperty.KEY).getValue().toString();\n Object value = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == value ? \"\" : value);\n }\n } else {\n m_container.removeAllItems();\n Set<Object> keyset = m_keyset.getKeySet();\n for (Object key : keyset) {\n Object itemId = m_container.addItem();\n Item item = m_container.getItem(itemId);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n Object value = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == value ? \"\" : value);\n }\n if (m_container.getItemIds().isEmpty()) {\n m_container.addItem();\n }\n }\n return true;\n } catch (IOException | CmsException e) {\n // The problem should typically be a problem with locking or reading the file containing the translation.\n // This should be reported in the editor, if false is returned here.\n return false;\n }\n }" ]
[ "public static void createUsers(GreenMailOperations greenMail, InternetAddress... addresses) {\n for (InternetAddress address : addresses) {\n greenMail.setUser(address.getAddress(), address.getAddress());\n }\n }", "public static AiScene importFile(String filename) throws IOException {\n \n return importFile(filename, EnumSet.noneOf(AiPostProcessSteps.class));\n }", "private void processResponse(Response<ByteArray, Object> response, Pipeline pipeline) {\n if(response == null) {\n logger.warn(\"RoutingTimedout on waiting for async ops; parallelResponseToWait: \"\n + numNodesPendingResponse + \"; preferred-1: \" + (preferred - 1)\n + \"; quorumOK: \" + quorumSatisfied + \"; zoneOK: \" + zonesSatisfied);\n } else {\n numNodesPendingResponse = numNodesPendingResponse - 1;\n numResponsesGot = numResponsesGot + 1;\n if(response.getValue() instanceof Exception\n && !(response.getValue() instanceof ObsoleteVersionException)) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key + \"} handling async put error\");\n }\n if(response.getValue() instanceof QuotaExceededException) {\n /**\n * TODO Not sure if we need to count this Exception for\n * stats or silently ignore and just log a warning. While\n * QuotaExceededException thrown from other places mean the\n * operation failed, this one does not fail the operation\n * but instead stores slops. Introduce a new Exception in\n * client side to just monitor how mamy Async writes fail on\n * exceeding Quota?\n * \n */\n if(logger.isDebugEnabled()) {\n logger.debug(\"Received quota exceeded exception after a successful \"\n + pipeline.getOperation().getSimpleName() + \" call on node \"\n + response.getNode().getId() + \", store '\"\n + pipelineData.getStoreName() + \"', master-node '\"\n + pipelineData.getMaster().getId() + \"'\");\n }\n } else if(handleResponseError(response, pipeline, failureDetector)) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key\n + \"} severe async put error, exiting parallel put stage\");\n }\n\n return;\n }\n if(PipelineRoutedStore.isSlopableFailure(response.getValue())\n || response.getValue() instanceof QuotaExceededException) {\n /**\n * We want to slop ParallelPuts which fail due to\n * QuotaExceededException.\n * \n * TODO Though this is not the right way of doing things, in\n * order to avoid inconsistencies and data loss, we chose to\n * slop the quota failed parallel puts.\n * \n * As a long term solution - 1) either Quota management\n * should be hidden completely in a routing layer like\n * Coordinator or 2) the Server should be able to\n * distinguish between serial and parallel puts and should\n * only quota for serial puts\n * \n */\n pipelineData.getSynchronizer().tryDelegateSlop(response.getNode());\n }\n\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key + \"} handled async put error\");\n }\n\n } else {\n pipelineData.incrementSuccesses();\n failureDetector.recordSuccess(response.getNode(), response.getRequestTime());\n pipelineData.getZoneResponses().add(response.getNode().getZoneId());\n }\n }\n }", "@SuppressWarnings(\"unchecked\")\n protected void addPostRunDependent(Executable<? extends Indexable> executable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) executable;\n this.addPostRunDependent(dependency);\n }", "protected void appendList(StringBuilder sql, List<?> list, String init, String sep) {\n\n boolean first = true;\n\n for (Object s : list) {\n if (first) {\n sql.append(init);\n } else {\n sql.append(sep);\n }\n sql.append(s);\n first = false;\n }\n }", "private void clearWorkingDateCache()\n {\n m_workingDateCache.clear();\n m_startTimeCache.clear();\n m_getDateLastResult = null;\n for (ProjectCalendar calendar : m_derivedCalendars)\n {\n calendar.clearWorkingDateCache();\n }\n }", "public Slice newSlice(long address, int size, Object reference)\n {\n if (address <= 0) {\n throw new IllegalArgumentException(\"Invalid address: \" + address);\n }\n if (reference == null) {\n throw new NullPointerException(\"Object reference is null\");\n }\n if (size == 0) {\n return Slices.EMPTY_SLICE;\n }\n return new Slice(null, address, size, size, reference);\n }", "private static void processResourceFilter(ProjectFile project, Filter filter)\n {\n for (Resource resource : project.getResources())\n {\n if (filter.evaluate(resource, null))\n {\n System.out.println(resource.getID() + \",\" + resource.getUniqueID() + \",\" + resource.getName());\n }\n }\n }", "private void addFilters(MpxjTreeNode parentNode, List<Filter> filters)\n {\n for (Filter field : filters)\n {\n final Filter f = field;\n MpxjTreeNode childNode = new MpxjTreeNode(field)\n {\n @Override public String toString()\n {\n return f.getName();\n }\n };\n parentNode.add(childNode);\n }\n }" ]
Returns the result of calling a closure with the first occurrence of a regular expression found within a CharSequence. If the regex doesn't match, the closure will not be called and find will return null. @param self a CharSequence @param regex the capturing regex CharSequence @param closure the closure that will be passed the full match, plus each of the capturing groups (if any) @return a String containing the result of calling the closure (calling toString() if needed), or null if the regex pattern doesn't match @see #find(String, java.util.regex.Pattern, groovy.lang.Closure) @since 1.8.2
[ "public static String find(CharSequence self, CharSequence regex, @ClosureParams(value=SimpleType.class, options=\"java.lang.String[]\") Closure closure) {\n return find(self.toString(), Pattern.compile(regex.toString()), closure);\n }" ]
[ "protected byte[] getBytesInternal() {\n\t\tbyte cached[];\n\t\tif(hasNoValueCache() || (cached = valueCache.lowerBytes) == null) {\n\t\t\tvalueCache.lowerBytes = cached = getBytesImpl(true);\n\t\t}\n\t\treturn cached;\n\t}", "public void setFloatAttribute(String name, Float value) {\n\t\tensureValue();\n\t\tAttribute attribute = new FloatAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}", "public static base_response delete(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager deleteresource = new snmpmanager();\n\t\tdeleteresource.ipaddress = resource.ipaddress;\n\t\tdeleteresource.netmask = resource.netmask;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static final String getString(InputStream is) throws IOException\n {\n int type = is.read();\n if (type != 1)\n {\n throw new IllegalArgumentException(\"Unexpected string format\");\n }\n\n Charset charset = CharsetHelper.UTF8;\n \n int length = is.read();\n if (length == 0xFF)\n {\n length = getShort(is);\n if (length == 0xFFFE)\n {\n charset = CharsetHelper.UTF16LE;\n length = (is.read() * 2);\n }\n }\n\n String result;\n if (length == 0)\n {\n result = null;\n }\n else\n {\n byte[] stringData = new byte[length]; \n is.read(stringData);\n result = new String(stringData, charset);\n }\n return result;\n }", "public static int cudnnPoolingForward(\n cudnnHandle handle, \n cudnnPoolingDescriptor poolingDesc, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnPoolingForwardNative(handle, poolingDesc, alpha, xDesc, x, beta, yDesc, y));\n }", "public void link(Object targetObject, ClassDescriptor cld, ObjectReferenceDescriptor rds, Object referencedObject, boolean insert)\n {\n // MBAIRD: we have 'disassociated' this object from the referenced object,\n // the object represented by the reference descriptor is now null, so set\n // the fk in the target object to null.\n // arminw: if an insert was done and ref object was null, we should allow\n // to pass FK fields of main object (maybe only the FK fields are set)\n if (referencedObject == null)\n {\n /*\n arminw:\n if update we set FK fields to 'null', because reference was disassociated\n We do nothing on insert, maybe only the FK fields of main object (without\n materialization of the reference object) are set by the user\n */\n if(!insert)\n {\n unlinkFK(targetObject, cld, rds);\n }\n }\n else\n {\n setFKField(targetObject, cld, rds, referencedObject);\n }\n }", "protected synchronized int loadSize() throws PersistenceBrokerException\r\n {\r\n PersistenceBroker broker = getBroker();\r\n try\r\n {\r\n return broker.getCount(getQuery());\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(ex);\r\n }\r\n finally\r\n {\r\n releaseBroker(broker);\r\n }\r\n }", "public void postConstruct() {\n parseGeometry();\n\n Assert.isTrue(this.polygon != null, \"Polygon is null. 'area' string is: '\" + this.area + \"'\");\n Assert.isTrue(this.display != null, \"'display' is null\");\n\n Assert.isTrue(this.style == null || this.display == AoiDisplay.RENDER,\n \"'style' does not make sense unless 'display' == RENDER. In this case 'display' == \" +\n this.display);\n }", "protected void beforeLoading()\r\n {\r\n if (_listeners != null)\r\n {\r\n CollectionProxyListener listener;\r\n\r\n if (_perThreadDescriptorsEnabled) {\r\n loadProfileIfNeeded();\r\n }\r\n for (int idx = _listeners.size() - 1; idx >= 0; idx--)\r\n {\r\n listener = (CollectionProxyListener)_listeners.get(idx);\r\n listener.beforeLoading(this);\r\n }\r\n }\r\n }" ]
Use this API to fetch the statistics of all systemmemory_stats resources that are configured on netscaler.
[ "public static systemmemory_stats get(nitro_service service) throws Exception{\n\t\tsystemmemory_stats obj = new systemmemory_stats();\n\t\tsystemmemory_stats[] response = (systemmemory_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}" ]
[ "private ModelNode resolveExpressionsRecursively(final ModelNode node) throws OperationFailedException {\n if (!node.isDefined()) {\n return node;\n }\n\n ModelType type = node.getType();\n ModelNode resolved;\n if (type == ModelType.EXPRESSION) {\n resolved = resolveExpressionStringRecursively(node.asExpression().getExpressionString(), lenient, true);\n } else if (type == ModelType.OBJECT) {\n resolved = node.clone();\n for (Property prop : resolved.asPropertyList()) {\n resolved.get(prop.getName()).set(resolveExpressionsRecursively(prop.getValue()));\n }\n } else if (type == ModelType.LIST) {\n resolved = node.clone();\n ModelNode list = new ModelNode();\n list.setEmptyList();\n for (ModelNode current : resolved.asList()) {\n list.add(resolveExpressionsRecursively(current));\n }\n resolved = list;\n } else if (type == ModelType.PROPERTY) {\n resolved = node.clone();\n resolved.set(resolved.asProperty().getName(), resolveExpressionsRecursively(resolved.asProperty().getValue()));\n } else {\n resolved = node;\n }\n\n return resolved;\n }", "private void processWorkWeeks(byte[] data, int offset, ProjectCalendar cal)\n {\n // System.out.println(\"Calendar=\" + cal.getName());\n // System.out.println(\"Work week block start offset=\" + offset);\n // System.out.println(ByteArrayHelper.hexdump(data, true, 16, \"\"));\n\n // skip 4 byte header\n offset += 4;\n\n while (data.length >= offset + ((7 * 60) + 2 + 2 + 8 + 4))\n {\n //System.out.println(\"Week start offset=\" + offset);\n ProjectCalendarWeek week = cal.addWorkWeek();\n for (Day day : Day.values())\n {\n // 60 byte block per day\n processWorkWeekDay(data, offset, week, day);\n offset += 60;\n }\n\n Date startDate = DateHelper.getDayStartDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n Date finishDate = DateHelper.getDayEndDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n // skip unknown 8 bytes\n //System.out.println(ByteArrayHelper.hexdump(data, offset, 8, false));\n offset += 8;\n\n //\n // Extract the name length - ensure that it is aligned to a 4 byte boundary\n //\n int nameLength = MPPUtility.getInt(data, offset);\n if (nameLength % 4 != 0)\n {\n nameLength = ((nameLength / 4) + 1) * 4;\n }\n offset += 4;\n\n if (nameLength != 0)\n {\n String name = MPPUtility.getUnicodeString(data, offset, nameLength);\n offset += nameLength;\n week.setName(name);\n }\n\n week.setDateRange(new DateRange(startDate, finishDate));\n // System.out.println(week);\n }\n }", "public String convertToJavaString(String input, boolean useUnicode) {\n\t\tint length = input.length();\n\t\tStringBuilder result = new StringBuilder(length + 4);\n\t\tfor (int i = 0; i < length; i++) {\n\t\t\tescapeAndAppendTo(input.charAt(i), useUnicode, result);\n\t\t}\n\t\treturn result.toString();\n\t}", "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 void showOnlyChannels(Object... channels){\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n visHandler.hideAll();\r\n for (Object channel : channels) {\r\n visHandler.alsoShow(channel);\r\n }\r\n }\r\n }\r\n }", "public static List<File> extract(File zipFile, File outputFolder) throws IOException {\n List<File> extracted = new ArrayList<File>();\n\n byte[] buffer = new byte[2048];\n\n if (!outputFolder.exists()) {\n outputFolder.mkdir();\n }\n\n ZipInputStream zipInput = new ZipInputStream(new FileInputStream(zipFile));\n\n ZipEntry zipEntry = zipInput.getNextEntry();\n\n while (zipEntry != null) {\n\n String neFileNameName = zipEntry.getName();\n File newFile = new File(outputFolder + File.separator + neFileNameName);\n\n newFile.getParentFile().mkdirs();\n\n if (!zipEntry.isDirectory()) {\n FileOutputStream fos = new FileOutputStream(newFile);\n\n int size;\n while ((size = zipInput.read(buffer)) > 0) {\n fos.write(buffer, 0, size);\n }\n\n fos.close();\n extracted.add(newFile);\n }\n\n zipEntry = zipInput.getNextEntry();\n }\n\n zipInput.closeEntry();\n zipInput.close();\n\n return extracted;\n\n }", "public void removeLicenseFromArtifact(final String gavc, final String licenseId) {\n final DbArtifact dbArtifact = getArtifact(gavc);\n\n //\n // The artifact may not have the exact string associated with it, but rather one\n // matching license regexp expression.\n //\n repositoryHandler.removeLicenseFromArtifact(dbArtifact, licenseId, licenseMatcher);\n }", "public static void Forward(double[][] data) {\n double[][] result = new double[data.length][data[0].length];\n\n for (int m = 0; m < data.length; m++) {\n for (int n = 0; n < data[0].length; n++) {\n double sum = 0;\n for (int i = 0; i < result.length; i++) {\n for (int k = 0; k < data.length; k++) {\n sum += data[i][k] * cas(((2.0 * Math.PI) / data.length) * (i * m + k * n));\n }\n result[m][n] = (1.0 / data.length) * sum;\n }\n }\n }\n\n for (int i = 0; i < data.length; i++) {\n for (int j = 0; j < data[0].length; j++) {\n data[i][j] = result[i][j];\n }\n }\n }", "private ProjectFile handleSQLiteFile(InputStream stream) throws Exception\n {\n File file = InputStreamHelper.writeStreamToTempFile(stream, \".sqlite\");\n\n try\n {\n Class.forName(\"org.sqlite.JDBC\");\n String url = \"jdbc:sqlite:\" + file.getCanonicalPath();\n Set<String> tableNames = populateTableNames(url);\n\n if (tableNames.contains(\"EXCEPTIONN\"))\n {\n return readProjectFile(new AstaDatabaseFileReader(), file);\n }\n\n if (tableNames.contains(\"PROJWBS\"))\n {\n Connection connection = null;\n try\n {\n Properties props = new Properties();\n props.setProperty(\"date_string_format\", \"yyyy-MM-dd HH:mm:ss\");\n connection = DriverManager.getConnection(url, props);\n PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader();\n reader.setConnection(connection);\n addListeners(reader);\n return reader.read();\n }\n finally\n {\n if (connection != null)\n {\n connection.close();\n }\n }\n }\n\n if (tableNames.contains(\"ZSCHEDULEITEM\"))\n {\n return readProjectFile(new MerlinReader(), file);\n }\n\n return null;\n }\n\n finally\n {\n FileHelper.deleteQuietly(file);\n }\n }" ]
Adds an option to the Jvm options @param value the option to add
[ "void addOption(final String value) {\n Assert.checkNotNullParam(\"value\", value);\n synchronized (options) {\n options.add(value);\n }\n }" ]
[ "public String getAlias(String path)\r\n {\r\n if (m_allPathsAliased && m_attributePath.lastIndexOf(path) != -1)\r\n {\r\n return m_name;\r\n }\r\n Object retObj = m_mapping.get(path);\r\n if (retObj != null)\r\n {\r\n return (String) retObj;\r\n }\r\n return null;\r\n }", "public static Integer getDay(Day day)\n {\n Integer result = null;\n if (day != null)\n {\n result = DAY_MAP.get(day);\n }\n return (result);\n }", "private void handleMultiChannelEncapResponse(\r\n\t\t\tSerialMessage serialMessage, int offset) {\r\n\t\tlogger.trace(\"Process Multi-channel Encapsulation\");\r\n\t\tCommandClass commandClass;\r\n\t\tZWaveCommandClass zwaveCommandClass;\r\n\t\tint endpointId = serialMessage.getMessagePayloadByte(offset);\r\n\t\tint commandClassCode = serialMessage.getMessagePayloadByte(offset + 2);\r\n\t\tcommandClass = CommandClass.getCommandClass(commandClassCode);\r\n\t\t\r\n\t\tif (commandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d Requested Command Class = %s (0x%02x)\", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));\r\n\t\tZWaveEndpoint endpoint = this.endpoints.get(endpointId);\r\n\t\t\r\n\t\tif (endpoint == null){\r\n\t\t\tlogger.error(\"Endpoint {} not found on node {}. Cannot set command classes.\", endpoint, this.getNode().getNodeId());\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tzwaveCommandClass = endpoint.getCommandClass(commandClass);\r\n\t\t\r\n\t\tif (zwaveCommandClass == null) {\r\n\t\t\tlogger.warn(String.format(\"CommandClass %s (0x%02x) not implemented by endpoint %d, fallback to main node.\", commandClass.getLabel(), commandClassCode, endpointId));\r\n\t\t\tzwaveCommandClass = this.getNode().getCommandClass(commandClass);\r\n\t\t}\r\n\t\t\r\n\t\tif (zwaveCommandClass == null) {\r\n\t\t\tlogger.error(String.format(\"CommandClass %s (0x%02x) not implemented by node %d.\", commandClass.getLabel(), commandClassCode, this.getNode().getNodeId()));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d, Endpoint = %d, calling handleApplicationCommandRequest.\", this.getNode().getNodeId(), endpointId));\r\n\t\tzwaveCommandClass.handleApplicationCommandRequest(serialMessage, offset + 3, endpointId);\r\n\t}", "public static DMatrixRMaj extractColumn(DMatrixRMaj a , int column , DMatrixRMaj out ) {\n if( out == null)\n out = new DMatrixRMaj(a.numRows,1);\n else if( !MatrixFeatures_DDRM.isVector(out) || out.getNumElements() != a.numRows )\n throw new MatrixDimensionException(\"Output must be a vector of length \"+a.numRows);\n\n int index = column;\n for (int i = 0; i < a.numRows; i++, index += a.numCols ) {\n out.data[i] = a.data[index];\n }\n return out;\n }", "public static List<CmsJspResourceWrapper> convertResourceList(CmsObject cms, List<CmsResource> list) {\n\n List<CmsJspResourceWrapper> result = new ArrayList<CmsJspResourceWrapper>(list.size());\n for (CmsResource res : list) {\n result.add(CmsJspResourceWrapper.wrap(cms, res));\n }\n return result;\n }", "public void setWorkConnection(CmsSetupDb db) {\n\n db.setConnection(\n m_setupBean.getDbDriver(),\n m_setupBean.getDbWorkConStr(),\n m_setupBean.getDbConStrParams(),\n m_setupBean.getDbWorkUser(),\n m_setupBean.getDbWorkPwd());\n }", "public static PJsonObject parseSpec(final String spec) {\n final JSONObject jsonSpec;\n try {\n jsonSpec = new JSONObject(spec);\n } catch (JSONException e) {\n throw new RuntimeException(\"Cannot parse the spec file: \" + spec, e);\n }\n return new PJsonObject(jsonSpec, \"spec\");\n }", "private boolean renameKeyForAllLanguages(String oldKey, String newKey) {\n\n try {\n loadAllRemainingLocalizations();\n lockAllLocalizations(oldKey);\n if (hasDescriptor()) {\n lockDescriptor();\n }\n } catch (CmsException | IOException e) {\n LOG.error(e.getLocalizedMessage(), e);\n return false;\n }\n for (Entry<Locale, SortedProperties> entry : m_localizations.entrySet()) {\n SortedProperties localization = entry.getValue();\n if (localization.containsKey(oldKey)) {\n String value = localization.getProperty(oldKey);\n localization.remove(oldKey);\n localization.put(newKey, value);\n m_changedTranslations.add(entry.getKey());\n }\n }\n if (hasDescriptor()) {\n CmsXmlContentValueSequence messages = m_descContent.getValueSequence(\n Descriptor.N_MESSAGE,\n Descriptor.LOCALE);\n for (int i = 0; i < messages.getElementCount(); i++) {\n\n String prefix = messages.getValue(i).getPath() + \"/\";\n String key = m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).getStringValue(m_cms);\n if (key == oldKey) {\n m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).setStringValue(m_cms, newKey);\n break;\n }\n }\n m_descriptorHasChanges = true;\n }\n m_keyset.renameKey(oldKey, newKey);\n return true;\n }", "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 }" ]
Retrieves the working hours on the given date. @param date required date @param cal optional calendar instance @param day optional day instance @return working hours
[ "private ProjectCalendarDateRanges getRanges(Date date, Calendar cal, Day day)\n {\n ProjectCalendarDateRanges ranges = getException(date);\n if (ranges == null)\n {\n ProjectCalendarWeek week = getWorkWeek(date);\n if (week == null)\n {\n week = this;\n }\n\n if (day == null)\n {\n if (cal == null)\n {\n cal = Calendar.getInstance();\n cal.setTime(date);\n }\n day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n }\n\n ranges = week.getHours(day);\n }\n return ranges;\n }" ]
[ "private static void validate(String name, Collection<Geometry> geometries, int extent) {\n if (name == null) {\n throw new IllegalArgumentException(\"layer name is null\");\n }\n if (geometries == null) {\n throw new IllegalArgumentException(\"geometry collection is null\");\n }\n if (extent <= 0) {\n throw new IllegalArgumentException(\"extent is less than or equal to 0\");\n }\n }", "private void clearDeck(TrackMetadataUpdate update) {\n if (hotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) {\n deliverBeatGridUpdate(update.player, null);\n }\n }", "public String getUrl(){\n\t\tfinal StringBuilder sb = new StringBuilder();\n\t\tsb.append(\"http://\");\n\t\tsb.append(getHttpConfiguration().getBindHost().get());\n\t\tsb.append(\":\");\n\t\tsb.append(getHttpConfiguration().getPort());\n\t\t\n\t\treturn sb.toString();\n\t}", "public static CmsResource getDescriptor(CmsObject cms, String basename) {\n\n CmsSolrQuery query = new CmsSolrQuery();\n query.setResourceTypes(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR.toString());\n query.setFilterQueries(\"filename:\\\"\" + basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX + \"\\\"\");\n query.add(\"fl\", \"path\");\n CmsSolrResultList results;\n try {\n boolean isOnlineProject = cms.getRequestContext().getCurrentProject().isOnlineProject();\n String indexName = isOnlineProject\n ? CmsSolrIndex.DEFAULT_INDEX_NAME_ONLINE\n : CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE;\n results = OpenCms.getSearchManager().getIndexSolr(indexName).search(cms, query, true, null, true, null);\n } catch (CmsSearchException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_SEARCH_ERROR_0), e);\n return null;\n }\n\n switch (results.size()) {\n case 0:\n return null;\n case 1:\n return results.get(0);\n default:\n String files = \"\";\n for (CmsResource res : results) {\n files += \" \" + res.getRootPath();\n }\n LOG.warn(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_NOT_UNIQUE_1, files));\n return results.get(0);\n }\n }", "public static base_response add(nitro_service client, ipset resource) throws Exception {\n\t\tipset addresource = new ipset();\n\t\taddresource.name = resource.name;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}", "public void setStringValue(String value) {\n\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(value)) {\n try {\n m_editValue = CmsLocationValue.parse(value);\n m_currentValue = m_editValue.cloneValue();\n displayValue();\n if ((m_popup != null) && m_popup.isVisible()) {\n m_popupContent.displayValues(m_editValue);\n updateMarkerPosition();\n }\n } catch (Exception e) {\n CmsLog.log(e.getLocalizedMessage() + \"\\n\" + CmsClientStringUtil.getStackTrace(e, \"\\n\"));\n }\n } else {\n m_currentValue = null;\n displayValue();\n }\n }", "protected void setBandsFinalHeight() {\n log.debug(\"Setting bands final height...\");\n\n List<JRBand> bands = new ArrayList<JRBand>();\n\n Utils.addNotNull(bands, design.getPageHeader());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getColumnHeader());\n Utils.addNotNull(bands, design.getColumnFooter());\n Utils.addNotNull(bands, design.getSummary());\n Utils.addNotNull(bands, design.getBackground());\n bands.addAll(((JRDesignSection) design.getDetailSection()).getBandsList());\n Utils.addNotNull(bands, design.getLastPageFooter());\n Utils.addNotNull(bands, design.getTitle());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getNoData());\n\n for (JRGroup jrgroup : design.getGroupsList()) {\n DJGroup djGroup = (DJGroup) getReferencesMap().get(jrgroup.getName());\n JRDesignSection headerSection = (JRDesignSection) jrgroup.getGroupHeaderSection();\n JRDesignSection footerSection = (JRDesignSection) jrgroup.getGroupFooterSection();\n if (djGroup != null) {\n for (JRBand headerBand : headerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) headerBand, djGroup.getHeaderHeight(), djGroup.isFitHeaderHeightToContent());\n\n }\n for (JRBand footerBand : footerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) footerBand, djGroup.getFooterHeight(), djGroup.isFitFooterHeightToContent());\n\n }\n } else {\n bands.addAll(headerSection.getBandsList());\n bands.addAll(footerSection.getBandsList());\n }\n }\n\n for (JRBand jrDesignBand : bands) {\n setBandFinalHeight((JRDesignBand) jrDesignBand);\n }\n }", "public static void readAndCheckVersion(ObjectInput input, int supportedVersion, Class<?> externalizedType) throws IOException {\n\t\tint version = input.readInt();\n\n\t\tif ( version != supportedVersion ) {\n\t\t\tthrow LOG.unexpectedKeyVersion( externalizedType, version, supportedVersion );\n\t\t}\n\t}", "synchronized boolean deleteMessageForId(String messageId, String userId){\n if(messageId == null || userId == null) return false;\n\n final String tName = Table.INBOX_MESSAGES.getName();\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n db.delete(tName, _ID + \" = ? AND \" + USER_ID + \" = ?\", new String[]{messageId,userId});\n return true;\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error removing stale records from \" + tName, e);\n return false;\n } finally {\n dbHelper.close();\n }\n }" ]
validates operation against the definition and sets model for the parameters passed. @param operationObject model node of type {@link ModelType#OBJECT}, typically representing an operation request @param model model node in which the value should be stored @throws OperationFailedException if the value is not valid @deprecated Not used by the WildFly management kernel; will be removed in a future release
[ "@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 }" ]
[ "private void initPropertyBundle() throws CmsLoaderException, CmsException, IOException {\n\n for (Locale l : m_locales) {\n String filePath = m_sitepath + m_basename + \"_\" + l.toString();\n CmsResource resource = null;\n if (m_cms.existsResource(\n filePath,\n CmsResourceFilter.requireType(\n OpenCms.getResourceManager().getResourceType(BundleType.PROPERTY.toString())))) {\n resource = m_cms.readResource(filePath);\n SortedProperties props = new SortedProperties();\n CmsFile file = m_cms.readFile(resource);\n props.load(\n new InputStreamReader(\n new ByteArrayInputStream(file.getContents()),\n CmsFileUtil.getEncoding(m_cms, file)));\n m_keyset.updateKeySet(null, props.keySet());\n m_bundleFiles.put(l, resource);\n }\n }\n\n }", "public void setYearlyAbsoluteFromDate(Date date)\n {\n if (date != null)\n {\n Calendar cal = DateHelper.popCalendar(date);\n m_dayNumber = Integer.valueOf(cal.get(Calendar.DAY_OF_MONTH));\n m_monthNumber = Integer.valueOf(cal.get(Calendar.MONTH) + 1);\n DateHelper.pushCalendar(cal);\n }\n }", "@Nullable\n public static String readUTF(@NotNull final InputStream stream) throws IOException {\n final DataInputStream dataInput = new DataInputStream(stream);\n if (stream instanceof ByteArraySizedInputStream) {\n final ByteArraySizedInputStream sizedStream = (ByteArraySizedInputStream) stream;\n final int streamSize = sizedStream.size();\n if (streamSize >= 2) {\n sizedStream.mark(Integer.MAX_VALUE);\n final int utfLen = dataInput.readUnsignedShort();\n if (utfLen == streamSize - 2) {\n boolean isAscii = true;\n final byte[] bytes = sizedStream.toByteArray();\n for (int i = 0; i < utfLen; ++i) {\n if ((bytes[i + 2] & 0xff) > 127) {\n isAscii = false;\n break;\n }\n }\n if (isAscii) {\n return fromAsciiByteArray(bytes, 2, utfLen);\n }\n }\n sizedStream.reset();\n }\n }\n try {\n String result = null;\n StringBuilder builder = null;\n for (; ; ) {\n final String temp;\n try {\n temp = dataInput.readUTF();\n if (result != null && result.length() == 0 &&\n builder != null && builder.length() == 0 && temp.length() == 0) {\n break;\n }\n } catch (EOFException e) {\n break;\n }\n if (result == null) {\n result = temp;\n } else {\n if (builder == null) {\n builder = new StringBuilder();\n builder.append(result);\n }\n builder.append(temp);\n }\n }\n return (builder != null) ? builder.toString() : result;\n } finally {\n dataInput.close();\n }\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 Set<T> findMatching(R resolvable) {\n Set<T> result = new HashSet<T>();\n for (T bean : getAllBeans(resolvable)) {\n if (matches(resolvable, bean)) {\n result.add(bean);\n }\n }\n return result;\n }", "private void readTasks(Project plannerProject) throws MPXJException\n {\n Tasks tasks = plannerProject.getTasks();\n if (tasks != null)\n {\n for (net.sf.mpxj.planner.schema.Task task : tasks.getTask())\n {\n readTask(null, task);\n }\n\n for (net.sf.mpxj.planner.schema.Task task : tasks.getTask())\n {\n readPredecessors(task);\n }\n }\n\n m_projectFile.updateStructure();\n }", "public final void begin() {\n this.file = this.getAppender().getIoFile();\n if (this.file == null) {\n this.getAppender().getErrorHandler()\n .error(\"Scavenger not started: missing log file name\");\n return;\n }\n if (this.getProperties().getScavengeInterval() > -1) {\n final Thread thread = new Thread(this, \"Log4J File Scavenger\");\n thread.setDaemon(true);\n thread.start();\n this.threadRef = thread;\n }\n }", "private void deliverBeatGridUpdate(int player, BeatGrid beatGrid) {\n if (!getBeatGridListeners().isEmpty()) {\n final BeatGridUpdate update = new BeatGridUpdate(player, beatGrid);\n for (final BeatGridListener listener : getBeatGridListeners()) {\n try {\n listener.beatGridChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering beat grid update to listener\", t);\n }\n }\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}" ]
simple echo implementation
[ "private void handleTextWebSocketFrameInternal(TextWebSocketFrame frame, ChannelHandlerContext ctx) {\n\t\tif (logger.isTraceEnabled()) {\n\t\t\tlogger.trace(String.format(\"%s received %s\", ctx.channel(), frame.text()));\n\t\t}\n\n\t\taddTraceForFrame(frame, \"text\");\n\t\tctx.channel().write(new TextWebSocketFrame(\"Echo: \" + frame.text()));\n\t}" ]
[ "public static void pauseTimer(final String type) {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return;\n }\n\n instance.components.get(type).pauseTimer();\n }", "public void setIndexBuffer(GVRIndexBuffer ibuf)\n {\n mIndices = ibuf;\n NativeMesh.setIndexBuffer(getNative(), (ibuf != null) ? ibuf.getNative() : 0L);\n }", "public void setValue(FieldContainer container, byte[] data)\n {\n if (data != null)\n {\n container.set(m_type, ((MPPUtility.getInt(data, m_offset) & m_mask) == 0) ? m_zeroValue : m_nonZeroValue);\n }\n }", "public static Module createModule(final String name,final String version){\n final Module module = new Module();\n\n module.setName(name);\n module.setVersion(version);\n module.setPromoted(false);\n\n return module;\n\n }", "protected <T> T getProperty(String key, Class<T> type) {\n Object returnValue = getProperty(key);\n if (returnValue != null) {\n return (T) returnValue;\n } else {\n return null;\n }\n }", "public List<TimephasedCost> getTimephasedCost()\n {\n if (m_timephasedCost == null)\n {\n Resource r = getResource();\n ResourceType type = r != null ? r.getType() : ResourceType.WORK;\n\n //for Work and Material resources, we will calculate in the normal way\n if (type != ResourceType.COST)\n {\n if (m_timephasedWork != null && m_timephasedWork.hasData())\n {\n if (hasMultipleCostRates())\n {\n m_timephasedCost = getTimephasedCostMultipleRates(getTimephasedWork(), getTimephasedOvertimeWork());\n }\n else\n {\n m_timephasedCost = getTimephasedCostSingleRate(getTimephasedWork(), getTimephasedOvertimeWork());\n }\n }\n }\n else\n {\n m_timephasedCost = getTimephasedCostFixedAmount();\n }\n\n }\n return m_timephasedCost;\n }", "public static void archiveFile(@NotNull final ArchiveOutputStream out,\n @NotNull final VirtualFileDescriptor source,\n final long fileSize) throws IOException {\n if (!source.hasContent()) {\n throw new IllegalArgumentException(\"Provided source is not a file: \" + source.getPath());\n }\n //noinspection ChainOfInstanceofChecks\n if (out instanceof TarArchiveOutputStream) {\n final TarArchiveEntry entry = new TarArchiveEntry(source.getPath() + source.getName());\n entry.setSize(fileSize);\n entry.setModTime(source.getTimeStamp());\n out.putArchiveEntry(entry);\n } else if (out instanceof ZipArchiveOutputStream) {\n final ZipArchiveEntry entry = new ZipArchiveEntry(source.getPath() + source.getName());\n entry.setSize(fileSize);\n entry.setTime(source.getTimeStamp());\n out.putArchiveEntry(entry);\n } else {\n throw new IOException(\"Unknown archive output stream\");\n }\n final InputStream input = source.getInputStream();\n try {\n IOUtil.copyStreams(input, fileSize, out, IOUtil.BUFFER_ALLOCATOR);\n } finally {\n if (source.shouldCloseStream()) {\n input.close();\n }\n }\n out.closeArchiveEntry();\n }", "private static int blockLength(int start, QrMode[] inputMode) {\n\n QrMode mode = inputMode[start];\n int count = 0;\n int i = start;\n\n do {\n count++;\n } while (((i + count) < inputMode.length) && (inputMode[i + count] == mode));\n\n return count;\n }", "public <X> Set<DisposalMethod<X, ?>> resolveDisposalBeans(Set<Type> types, Set<Annotation> qualifiers, AbstractClassBean<X> declaringBean) {\n // We can always cache as this is only ever called by Weld where we avoid non-static inner classes for annotation literals\n Set<DisposalMethod<X, ?>> beans = cast(disposalMethodResolver.resolve(new ResolvableBuilder(manager).addTypes(types).addQualifiers(qualifiers).setDeclaringBean(declaringBean).create(), true));\n resolvedDisposalBeans.addAll(beans);\n return Collections.unmodifiableSet(beans);\n }" ]
Capture stdout and route them through Redwood @return this
[ "public RedwoodConfiguration captureStdout(){\r\n tasks.add(new Runnable() { public void run() { Redwood.captureSystemStreams(true, false); } });\r\n return this;\r\n }" ]
[ "private void readResources()\n {\n for (MapRow row : getTable(\"RTAB\"))\n {\n Resource resource = m_projectFile.addResource();\n setFields(RESOURCE_FIELDS, row, resource);\n m_eventManager.fireResourceReadEvent(resource);\n // TODO: Correctly handle calendar\n }\n }", "public int getShort(Integer id, Integer type)\n {\n int result = 0;\n\n Integer offset = m_meta.getOffset(id, type);\n\n if (offset != null)\n {\n byte[] value = m_map.get(offset);\n\n if (value != null && value.length >= 2)\n {\n result = MPPUtility.getShort(value, 0);\n }\n }\n\n return (result);\n }", "public synchronized void delete(String name) {\n if (isEmpty(name)) {\n indexedProps.remove(name);\n } else {\n synchronized (context) {\n int scope = context.getAttributesScope(name);\n if (scope != -1) {\n context.removeAttribute(name, scope);\n }\n }\n }\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 }", "private void bubbleUpNodeTable(DAGraph<DataT, NodeT> from, LinkedList<String> path) {\n if (path.contains(from.rootNode.key())) {\n path.push(from.rootNode.key()); // For better error message\n throw new IllegalStateException(\"Detected circular dependency: \" + StringUtils.join(path, \" -> \"));\n }\n path.push(from.rootNode.key());\n for (DAGraph<DataT, NodeT> to : from.parentDAGs) {\n this.merge(from.nodeTable, to.nodeTable);\n this.bubbleUpNodeTable(to, path);\n }\n path.pop();\n }", "private Map<String, String> mergeItem(\r\n String item,\r\n Map<String, String> localeValues,\r\n Map<String, String> resultLocaleValues) {\r\n\r\n if (resultLocaleValues.get(item) != null) {\r\n if (localeValues.get(item) != null) {\r\n localeValues.put(item, localeValues.get(item) + \" \" + resultLocaleValues.get(item));\r\n } else {\r\n localeValues.put(item, resultLocaleValues.get(item));\r\n }\r\n }\r\n\r\n return localeValues;\r\n }", "public static List<TestSuiteResult> unmarshalSuites(File... directories) throws IOException {\n List<TestSuiteResult> results = new ArrayList<>();\n\n List<File> files = listTestSuiteFiles(directories);\n\n for (File file : files) {\n results.add(unmarshal(file));\n }\n return results;\n }", "public void setCurrencySymbol(String symbol)\n {\n if (symbol == null)\n {\n symbol = DEFAULT_CURRENCY_SYMBOL;\n }\n\n set(ProjectField.CURRENCY_SYMBOL, symbol);\n }", "public static boolean isToStringMethod(Method method) {\n return (method != null && method.getName().equals(\"readString\") && method.getParameterTypes().length == 0);\n }" ]
Calculates the middle point between two points and multiplies its coordinates with the given smoothness _Mulitplier. @param _P1 First point @param _P2 Second point @param _Result Resulting point @param _Multiplier Smoothness multiplier
[ "public static void calculatePointDiff(Point2D _P1, Point2D _P2, Point2D _Result, float _Multiplier) {\n float diffX = _P2.getX() - _P1.getX();\n float diffY = _P2.getY() - _P1.getY();\n _Result.setX(_P1.getX() + (diffX * _Multiplier));\n _Result.setY(_P1.getY() + (diffY * _Multiplier));\n }" ]
[ "public boolean matchesWithMask(IPAddressSection other, IPAddressSection mask) {\n\t\tcheckMaskSectionCount(mask);\n\t\tcheckSectionCount(other);\n\t\tint divCount = getSegmentCount();\n\t\tfor(int i = 0; i < divCount; i++) {\n\t\t\tIPAddressSegment div = getSegment(i);\n\t\t\tIPAddressSegment maskSegment = mask.getSegment(i);\n\t\t\tIPAddressSegment otherSegment = other.getSegment(i);\n\t\t\tif(!div.matchesWithMask(\n\t\t\t\t\totherSegment.getSegmentValue(), \n\t\t\t\t\totherSegment.getUpperSegmentValue(), \n\t\t\t\t\tmaskSegment.getSegmentValue())) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "public void loadObject(Object object, Set<String> excludedMethods)\n {\n m_model.setTableModel(createTableModel(object, excludedMethods));\n }", "public static base_responses delete(nitro_service client, appfwlearningdata resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwlearningdata deleteresources[] = new appfwlearningdata[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new appfwlearningdata();\n\t\t\t\tdeleteresources[i].profilename = resources[i].profilename;\n\t\t\t\tdeleteresources[i].starturl = resources[i].starturl;\n\t\t\t\tdeleteresources[i].cookieconsistency = resources[i].cookieconsistency;\n\t\t\t\tdeleteresources[i].fieldconsistency = resources[i].fieldconsistency;\n\t\t\t\tdeleteresources[i].formactionurl_ffc = resources[i].formactionurl_ffc;\n\t\t\t\tdeleteresources[i].crosssitescripting = resources[i].crosssitescripting;\n\t\t\t\tdeleteresources[i].formactionurl_xss = resources[i].formactionurl_xss;\n\t\t\t\tdeleteresources[i].sqlinjection = resources[i].sqlinjection;\n\t\t\t\tdeleteresources[i].formactionurl_sql = resources[i].formactionurl_sql;\n\t\t\t\tdeleteresources[i].fieldformat = resources[i].fieldformat;\n\t\t\t\tdeleteresources[i].formactionurl_ff = resources[i].formactionurl_ff;\n\t\t\t\tdeleteresources[i].csrftag = resources[i].csrftag;\n\t\t\t\tdeleteresources[i].csrfformoriginurl = resources[i].csrfformoriginurl;\n\t\t\t\tdeleteresources[i].xmldoscheck = resources[i].xmldoscheck;\n\t\t\t\tdeleteresources[i].xmlwsicheck = resources[i].xmlwsicheck;\n\t\t\t\tdeleteresources[i].xmlattachmentcheck = resources[i].xmlattachmentcheck;\n\t\t\t\tdeleteresources[i].totalxmlrequests = resources[i].totalxmlrequests;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public static void init(Context cx, Scriptable scope, boolean sealed)\n throws RhinoException {\n JSAdapter obj = new JSAdapter(cx.newObject(scope));\n obj.setParentScope(scope);\n obj.setPrototype(getFunctionPrototype(scope));\n obj.isPrototype = true;\n ScriptableObject.defineProperty(scope, \"JSAdapter\", obj,\n ScriptableObject.DONTENUM);\n }", "private JSONArray datesToJson(Collection<Date> individualDates) {\n\n if (null != individualDates) {\n JSONArray result = new JSONArray();\n for (Date d : individualDates) {\n result.put(dateToJson(d));\n }\n return result;\n }\n return null;\n }", "private CmsFavInfo createFavInfo(CmsFavoriteEntry entry) throws CmsException {\n\n String title = \"\";\n String subtitle = \"\";\n CmsFavInfo result = new CmsFavInfo(entry);\n CmsObject cms = A_CmsUI.getCmsObject();\n String project = getProject(cms, entry);\n String site = getSite(cms, entry);\n try {\n CmsUUID idToLoad = entry.getDetailId() != null ? entry.getDetailId() : entry.getStructureId();\n CmsResource resource = cms.readResource(idToLoad, CmsResourceFilter.IGNORE_EXPIRATION.addRequireVisible());\n CmsResourceUtil resutil = new CmsResourceUtil(cms, resource);\n switch (entry.getType()) {\n case explorerFolder:\n title = CmsStringUtil.isEmpty(resutil.getTitle())\n ? CmsResource.getName(resource.getRootPath())\n : resutil.getTitle();\n break;\n case page:\n title = resutil.getTitle();\n break;\n }\n subtitle = resource.getRootPath();\n CmsResourceIcon icon = result.getResourceIcon();\n icon.initContent(resutil, CmsResource.STATE_UNCHANGED, false, false);\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n result.getTopLine().setValue(title);\n result.getBottomLine().setValue(subtitle);\n result.getProjectLabel().setValue(project);\n result.getSiteLabel().setValue(site);\n\n return result;\n\n }", "@PostConstruct\n\tprotected void postConstruct() throws GeomajasException {\n\t\tif (null != crsDefinitions) {\n\t\t\tfor (CrsInfo crsInfo : crsDefinitions.values()) {\n\t\t\t\ttry {\n\t\t\t\t\tCoordinateReferenceSystem crs = CRS.parseWKT(crsInfo.getCrsWkt());\n\t\t\t\t\tString code = crsInfo.getKey();\n\t\t\t\t\tcrsCache.put(code, CrsFactory.getCrs(code, crs));\n\t\t\t\t} catch (FactoryException e) {\n\t\t\t\t\tthrow new GeomajasException(e, ExceptionCode.CRS_DECODE_FAILURE_FOR_MAP, crsInfo.getKey());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (null != crsTransformDefinitions) {\n\t\t\tfor (CrsTransformInfo crsTransformInfo : crsTransformDefinitions.values()) {\n\t\t\t\tString key = getTransformKey(crsTransformInfo);\n\t\t\t\ttransformCache.put(key, getCrsTransform(key, crsTransformInfo));\n\t\t\t}\n\t\t}\n\t\tGeometryFactory factory = new GeometryFactory();\n\t\tEMPTY_GEOMETRIES.put(Point.class, factory.createPoint((Coordinate) null));\n\t\tEMPTY_GEOMETRIES.put(LineString.class, factory.createLineString((Coordinate[]) null));\n\t\tEMPTY_GEOMETRIES.put(Polygon.class, factory.createPolygon(null, null));\n\t\tEMPTY_GEOMETRIES.put(MultiPoint.class, factory.createMultiPoint((Coordinate[]) null));\n\t\tEMPTY_GEOMETRIES.put(MultiLineString.class, factory.createMultiLineString((LineString[]) null)); // cast needed!\n\t\tEMPTY_GEOMETRIES.put(MultiPolygon.class, factory.createMultiPolygon((Polygon[]) null)); // cast needed!\n\t\tEMPTY_GEOMETRIES.put(Geometry.class, factory.createGeometryCollection(null));\n\t}", "public static base_response update(nitro_service client, spilloverpolicy resource) throws Exception {\n\t\tspilloverpolicy updateresource = new spilloverpolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.rule = resource.rule;\n\t\tupdateresource.action = resource.action;\n\t\tupdateresource.comment = resource.comment;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static boolean isAssignable(Type lhsType, Type rhsType) {\n\t\tAssert.notNull(lhsType, \"Left-hand side type must not be null\");\n\t\tAssert.notNull(rhsType, \"Right-hand side type must not be null\");\n\n\t\t// all types are assignable to themselves and to class Object\n\t\tif (lhsType.equals(rhsType) || lhsType.equals(Object.class)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (lhsType instanceof Class<?>) {\n\t\t\tClass<?> lhsClass = (Class<?>) lhsType;\n\n\t\t\t// just comparing two classes\n\t\t\tif (rhsType instanceof Class<?>) {\n\t\t\t\treturn ClassUtils.isAssignable(lhsClass, (Class<?>) rhsType);\n\t\t\t}\n\n\t\t\tif (rhsType instanceof ParameterizedType) {\n\t\t\t\tType rhsRaw = ((ParameterizedType) rhsType).getRawType();\n\n\t\t\t\t// a parameterized type is always assignable to its raw class type\n\t\t\t\tif (rhsRaw instanceof Class<?>) {\n\t\t\t\t\treturn ClassUtils.isAssignable(lhsClass, (Class<?>) rhsRaw);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (lhsClass.isArray() && rhsType instanceof GenericArrayType) {\n\t\t\t\tType rhsComponent = ((GenericArrayType) rhsType).getGenericComponentType();\n\n\t\t\t\treturn isAssignable(lhsClass.getComponentType(), rhsComponent);\n\t\t\t}\n\t\t}\n\n\t\t// parameterized types are only assignable to other parameterized types and class types\n\t\tif (lhsType instanceof ParameterizedType) {\n\t\t\tif (rhsType instanceof Class<?>) {\n\t\t\t\tType lhsRaw = ((ParameterizedType) lhsType).getRawType();\n\n\t\t\t\tif (lhsRaw instanceof Class<?>) {\n\t\t\t\t\treturn ClassUtils.isAssignable((Class<?>) lhsRaw, (Class<?>) rhsType);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (rhsType instanceof ParameterizedType) {\n\t\t\t\treturn isAssignable((ParameterizedType) lhsType, (ParameterizedType) rhsType);\n\t\t\t}\n\t\t}\n\n\t\tif (lhsType instanceof GenericArrayType) {\n\t\t\tType lhsComponent = ((GenericArrayType) lhsType).getGenericComponentType();\n\n\t\t\tif (rhsType instanceof Class<?>) {\n\t\t\t\tClass<?> rhsClass = (Class<?>) rhsType;\n\n\t\t\t\tif (rhsClass.isArray()) {\n\t\t\t\t\treturn isAssignable(lhsComponent, rhsClass.getComponentType());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (rhsType instanceof GenericArrayType) {\n\t\t\t\tType rhsComponent = ((GenericArrayType) rhsType).getGenericComponentType();\n\n\t\t\t\treturn isAssignable(lhsComponent, rhsComponent);\n\t\t\t}\n\t\t}\n\n\t\tif (lhsType instanceof WildcardType) {\n\t\t\treturn isAssignable((WildcardType) lhsType, rhsType);\n\t\t}\n\n\t\treturn false;\n\t}" ]
Merge the contents of the given plugin.xml into this one.
[ "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 void add(Vector3d v1) {\n x += v1.x;\n y += v1.y;\n z += v1.z;\n }", "public static void createDotStoryFile(String scenarioName,\n String srcTestRootFolder, String packagePath,\n String givenDescription, String whenDescription,\n String thenDescription) throws BeastException {\n String[] folders = packagePath.split(\".\");\n for (String folder : folders) {\n srcTestRootFolder += \"/\" + folder;\n }\n\n FileWriter writer = createFileWriter(createDotStoryName(scenarioName),\n packagePath, srcTestRootFolder);\n try {\n writer.write(\"Scenario: \" + scenarioName + \"\\n\");\n writer.write(\"Given \" + givenDescription + \"\\n\");\n writer.write(\"When \" + whenDescription + \"\\n\");\n writer.write(\"Then \" + thenDescription + \"\\n\");\n writer.close();\n } catch (Exception e) {\n String message = \"Unable to write the .story file for the scenario \"\n + scenarioName;\n logger.severe(message);\n logger.severe(e.getMessage());\n throw new BeastException(message, e);\n }\n }", "@Override public Object instantiateItem(ViewGroup parent, int position) {\n T content = getItem(position);\n rendererBuilder.withContent(content);\n rendererBuilder.withParent(parent);\n rendererBuilder.withLayoutInflater(LayoutInflater.from(parent.getContext()));\n Renderer<T> renderer = rendererBuilder.build();\n if (renderer == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null Renderer\");\n }\n updateRendererExtraValues(content, renderer, position);\n renderer.render();\n View view = renderer.getRootView();\n parent.addView(view);\n return view;\n }", "public boolean startDrag(final GVRSceneObject sceneObject,\n final float hitX, final float hitY, final float hitZ) {\n final GVRRigidBody dragMe = (GVRRigidBody)sceneObject.getComponent(GVRRigidBody.getComponentType());\n if (dragMe == null || dragMe.getSimulationType() != GVRRigidBody.DYNAMIC || !contains(dragMe))\n return false;\n\n GVRTransform t = sceneObject.getTransform();\n\n final Vector3f relPos = new Vector3f(hitX, hitY, hitZ);\n relPos.mul(t.getScaleX(), t.getScaleY(), t.getScaleZ());\n relPos.rotate(new Quaternionf(t.getRotationX(), t.getRotationY(), t.getRotationZ(), t.getRotationW()));\n\n final GVRSceneObject pivotObject = mPhysicsDragger.startDrag(sceneObject,\n relPos.x, relPos.y, relPos.z);\n if (pivotObject == null)\n return false;\n\n mPhysicsContext.runOnPhysicsThread(new Runnable() {\n @Override\n public void run() {\n mRigidBodyDragMe = dragMe;\n NativePhysics3DWorld.startDrag(getNative(), pivotObject.getNative(), dragMe.getNative(),\n hitX, hitY, hitZ);\n }\n });\n\n return true;\n }", "public Launcher addEnvironmentVariable(final String key, final String value) {\n env.put(key, value);\n return this;\n }", "public void deleteMetadata(String templateName) {\n String scope = Metadata.scopeBasedOnType(templateName);\n this.deleteMetadata(templateName, scope);\n }", "public static String getHeaders(HttpMethod method) {\n String headerString = \"\";\n Header[] headers = method.getRequestHeaders();\n for (Header header : headers) {\n String name = header.getName();\n if (name.equals(Constants.ODO_PROXY_HEADER)) {\n // skip.. don't want to log this\n continue;\n }\n\n if (headerString.length() != 0) {\n headerString += \"\\n\";\n }\n\n headerString += header.getName() + \": \" + header.getValue();\n }\n\n return headerString;\n }", "private InputStream runSparqlQuery(String query) throws IOException {\n\t\ttry {\n\t\t\tString queryString = \"query=\" + URLEncoder.encode(query, \"UTF-8\")\n\t\t\t\t\t+ \"&format=json\";\n\t\t\tURL url = new URL(\"https://query.wikidata.org/sparql?\"\n\t\t\t\t\t+ queryString);\n\t\t\tHttpURLConnection connection = (HttpURLConnection) url\n\t\t\t\t\t.openConnection();\n\t\t\tconnection.setRequestMethod(\"GET\");\n\n\t\t\treturn connection.getInputStream();\n\t\t} catch (UnsupportedEncodingException | MalformedURLException e) {\n\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t}\n\t}", "protected String getExecutableJar() throws IOException {\n Manifest manifest = new Manifest();\n manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, \"1.0\");\n manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, MAIN);\n manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, getClasspath());\n\n Path jar = createTempDirectory(\"exec\").resolve(\"generate.jar\");\n try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(jar), manifest)) {\n output.putNextEntry(new JarEntry(\"allure.properties\"));\n Path allureConfig = PROPERTIES.getAllureConfig();\n if (Files.exists(allureConfig)) {\n byte[] bytes = Files.readAllBytes(allureConfig);\n output.write(bytes);\n }\n output.closeEntry();\n }\n\n return jar.toAbsolutePath().toString();\n }" ]
Copy the settings from another calendar to this calendar. @param cal calendar data source
[ "public void copy(ProjectCalendar cal)\n {\n setName(cal.getName());\n setParent(cal.getParent());\n System.arraycopy(cal.getDays(), 0, getDays(), 0, getDays().length);\n for (ProjectCalendarException ex : cal.m_exceptions)\n {\n addCalendarException(ex.getFromDate(), ex.getToDate());\n for (DateRange range : ex)\n {\n ex.addRange(new DateRange(range.getStart(), range.getEnd()));\n }\n }\n\n for (ProjectCalendarHours hours : getHours())\n {\n if (hours != null)\n {\n ProjectCalendarHours copyHours = cal.addCalendarHours(hours.getDay());\n for (DateRange range : hours)\n {\n copyHours.addRange(new DateRange(range.getStart(), range.getEnd()));\n }\n }\n }\n }" ]
[ "static PatchingResult executeTasks(final IdentityPatchContext context, final IdentityPatchContext.FinalizeCallback callback) throws Exception {\n final List<PreparedTask> tasks = new ArrayList<PreparedTask>();\n final List<ContentItem> conflicts = new ArrayList<ContentItem>();\n // Identity\n prepareTasks(context.getIdentityEntry(), context, tasks, conflicts);\n // Layers\n for (final IdentityPatchContext.PatchEntry layer : context.getLayers()) {\n prepareTasks(layer, context, tasks, conflicts);\n }\n // AddOns\n for (final IdentityPatchContext.PatchEntry addOn : context.getAddOns()) {\n prepareTasks(addOn, context, tasks, conflicts);\n }\n // If there were problems report them\n if (!conflicts.isEmpty()) {\n throw PatchLogger.ROOT_LOGGER.conflictsDetected(conflicts);\n }\n // Execute the tasks\n for (final PreparedTask task : tasks) {\n // Unless it's excluded by the user\n final ContentItem item = task.getContentItem();\n if (item != null && context.isExcluded(item)) {\n continue;\n }\n // Run the task\n task.execute();\n }\n return context.finalize(callback);\n }", "public Object toInternal(Attribute<?> attribute) throws GeomajasException {\n\t\tif (attribute instanceof PrimitiveAttribute<?>) {\n\t\t\treturn toPrimitiveObject((PrimitiveAttribute<?>) attribute);\n\t\t} else if (attribute instanceof AssociationAttribute<?>) {\n\t\t\treturn toAssociationObject((AssociationAttribute<?>) attribute);\n\t\t} else {\n\t\t\tthrow new GeomajasException(ExceptionCode.CONVERSION_PROBLEM, attribute);\n\t\t}\n\t}", "protected String escapeApostrophes(String text) {\r\n\t\tString resultString;\r\n\t\tif (text.contains(\"'\")) {\r\n\t\t\tStringBuilder stringBuilder = new StringBuilder();\r\n\t\t\tstringBuilder.append(\"concat('\");\r\n\t\t\tstringBuilder.append(text.replace(\"'\", \"',\\\"'\\\",'\"));\r\n\t\t\tstringBuilder.append(\"')\");\r\n\t\t\tresultString = stringBuilder.toString();\r\n\t\t} else {\r\n\t\t\tresultString = \"'\" + text + \"'\";\r\n\t\t}\r\n\t\treturn resultString;\r\n\t}", "public static int getStatusBarHeight(Context context, boolean force) {\n int result = 0;\n int resourceId = context.getResources().getIdentifier(\"status_bar_height\", \"dimen\", \"android\");\n if (resourceId > 0) {\n result = context.getResources().getDimensionPixelSize(resourceId);\n }\n\n int dimenResult = context.getResources().getDimensionPixelSize(R.dimen.tool_bar_top_padding);\n //if our dimension is 0 return 0 because on those devices we don't need the height\n if (dimenResult == 0 && !force) {\n return 0;\n } else {\n //if our dimens is > 0 && the result == 0 use the dimenResult else the result;\n return result == 0 ? dimenResult : result;\n }\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 }", "private void stripCommas(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n\n while( t != null ) {\n TokenList.Token next = t.next;\n if( t.getSymbol() == Symbol.COMMA ) {\n tokens.remove(t);\n }\n t = next;\n }\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<PaxDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<PaxDate>) super.localDateTime(temporal);\n }", "public StatementBuilder withQualifierValue(PropertyIdValue propertyIdValue,\n\t\t\tValue value) {\n\t\twithQualifier(factory.getValueSnak(propertyIdValue, value));\n\t\treturn getThis();\n\t}", "public static boolean ensureJedisConnection(final Jedis jedis) {\n final boolean jedisOK = testJedisConnection(jedis);\n if (!jedisOK) {\n try {\n jedis.quit();\n } catch (Exception e) {\n } // Ignore\n try {\n jedis.disconnect();\n } catch (Exception e) {\n } // Ignore\n jedis.connect();\n }\n return jedisOK;\n }" ]
Samples a batch of indices in the range [0, numExamples) without replacement.
[ "public int[] sampleBatchWithoutReplacement() {\n int[] batch = new int[batchSize];\n for (int i=0; i<batch.length; i++) {\n if (cur == indices.length) {\n cur = 0;\n }\n if (cur == 0) {\n IntArrays.shuffle(indices);\n }\n batch[i] = indices[cur++];\n }\n return batch;\n }" ]
[ "public static gslbservice_stats get(nitro_service service, String servicename) throws Exception{\n\t\tgslbservice_stats obj = new gslbservice_stats();\n\t\tobj.set_servicename(servicename);\n\t\tgslbservice_stats response = (gslbservice_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<BritishCutoverDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<BritishCutoverDate>) super.zonedDateTime(temporal);\n }", "public void removeAll() {\n LOGGER.debug(\"Removing {} reverse connections from subscription manager\", reverse.size());\n Iterator<HomekitClientConnection> i = reverse.keySet().iterator();\n while (i.hasNext()) {\n HomekitClientConnection connection = i.next();\n LOGGER.debug(\"Removing connection {}\", connection.hashCode());\n removeConnection(connection);\n }\n LOGGER.debug(\"Subscription sizes are {} and {}\", reverse.size(), subscriptions.size());\n }", "public void sendJsonToUser(Object data, String username) {\n sendToUser(JSON.toJSONString(data), username);\n }", "protected void setProperty(String propertyName, JavascriptEnum propertyValue) {\n jsObject.setMember(propertyName, propertyValue.getEnumValue());\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}", "public static boolean oracleExists(CuratorFramework curator) {\n boolean exists = false;\n try {\n exists = curator.checkExists().forPath(ZookeeperPath.ORACLE_SERVER) != null\n && !curator.getChildren().forPath(ZookeeperPath.ORACLE_SERVER).isEmpty();\n } catch (Exception nne) {\n if (nne instanceof KeeperException.NoNodeException) {\n // you'll do nothing\n } else {\n throw new RuntimeException(nne);\n }\n }\n return exists;\n }", "public static void dumpStoreDefsToFile(String outputDirName,\n String fileName,\n List<StoreDefinition> storeDefs) {\n\n if(outputDirName != null) {\n File outputDir = new File(outputDirName);\n if(!outputDir.exists()) {\n Utils.mkdirs(outputDir);\n }\n\n try {\n FileUtils.writeStringToFile(new File(outputDirName, fileName),\n new StoreDefinitionsMapper().writeStoreList(storeDefs));\n } catch(IOException e) {\n logger.error(\"IOException during dumpStoreDefsToFile: \" + e);\n }\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}" ]
Assign FK value to all n-side objects referenced by given object. @param obj real object with 1:n reference @param cod {@link CollectionDescriptor} of referenced 1:n objects @param insert flag signal insert operation, false signals update operation
[ "public void linkOneToMany(Object obj, CollectionDescriptor cod, boolean insert)\n {\n Object referencedObjects = cod.getPersistentField().get(obj);\n storeAndLinkOneToMany(true, obj, cod,referencedObjects, insert);\n }" ]
[ "public List<GVRAtlasInformation> getAtlasInformation()\n {\n if ((mImage != null) && (mImage instanceof GVRImageAtlas))\n {\n return ((GVRImageAtlas) mImage).getAtlasInformation();\n }\n return null;\n }", "public static Boolean areCoordinatesWithinThreshold(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) {\r\n return getDistanceBetweenCoordinates(point1, point2) < COORDINATE_THRESHOLD;\r\n }", "private String getSlashyPath(final String path) {\n String changedPath = path;\n if (File.separatorChar != '/')\n changedPath = changedPath.replace(File.separatorChar, '/');\n\n return changedPath;\n }", "public static void append(Path self, Object text) throws IOException {\n Writer writer = null;\n try {\n writer = new OutputStreamWriter(Files.newOutputStream(self, CREATE, APPEND), Charset.defaultCharset());\n InvokerHelper.write(writer, text);\n writer.flush();\n\n Writer temp = writer;\n writer = null;\n temp.close();\n } finally {\n closeWithWarning(writer);\n }\n }", "public void invalidate() {\n synchronized (mMeasuredChildren) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"invalidate all [%d]\", mMeasuredChildren.size());\n mMeasuredChildren.clear();\n }\n }", "public static LayersConfig getLayersConfig(final File repoRoot) throws IOException {\n final File layersList = new File(repoRoot, LAYERS_CONF);\n if (!layersList.exists()) {\n return new LayersConfig();\n }\n final Properties properties = PatchUtils.loadProperties(layersList);\n return new LayersConfig(properties);\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 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 }", "public void ojbAdd(Object anObject)\r\n {\r\n DSetEntry entry = prepareEntry(anObject);\r\n entry.setPosition(elements.size());\r\n elements.add(entry);\r\n }" ]
Initializes unspecified sign properties using available defaults and global settings.
[ "private void initializeSignProperties() {\n if (!signPackage && !signChanges) {\n return;\n }\n\n if (key != null && keyring != null && passphrase != null) {\n return;\n }\n\n Map<String, String> properties =\n readPropertiesFromActiveProfiles(signCfgPrefix, KEY, KEYRING, PASSPHRASE);\n\n key = lookupIfEmpty(key, properties, KEY);\n keyring = lookupIfEmpty(keyring, properties, KEYRING);\n passphrase = decrypt(lookupIfEmpty(passphrase, properties, PASSPHRASE));\n\n if (keyring == null) {\n try {\n keyring = Utils.guessKeyRingFile().getAbsolutePath();\n console.info(\"Located keyring at \" + keyring);\n } catch (FileNotFoundException e) {\n console.warn(e.getMessage());\n }\n }\n }" ]
[ "public static double extractColumnAndMax( ZMatrixRMaj A ,\n int row0 , int row1 ,\n int col , double u[], int offsetU) {\n int indexU = (offsetU+row0)*2;\n\n // find the largest value in this column\n // this is used to normalize the column and mitigate overflow/underflow\n double max = 0;\n\n int indexA = A.getIndex(row0,col);\n double h[] = A.data;\n\n for( int i = row0; i < row1; i++, indexA += A.numCols*2 ) {\n // copy the householder vector to an array to reduce cache misses\n // big improvement on larger matrices and a relatively small performance hit on small matrices.\n double realVal = u[indexU++] = h[indexA];\n double imagVal = u[indexU++] = h[indexA+1];\n\n double magVal = realVal*realVal + imagVal*imagVal;\n if( max < magVal ) {\n max = magVal;\n }\n }\n return Math.sqrt(max);\n }", "private static void displayAvailableFilters(ProjectFile project)\n {\n System.out.println(\"Unknown filter name supplied.\");\n System.out.println(\"Available task filters:\");\n for (Filter filter : project.getFilters().getTaskFilters())\n {\n System.out.println(\" \" + filter.getName());\n }\n\n System.out.println(\"Available resource filters:\");\n for (Filter filter : project.getFilters().getResourceFilters())\n {\n System.out.println(\" \" + filter.getName());\n }\n\n }", "public static AccrueType getInstance(String type, Locale locale)\n {\n AccrueType result = null;\n\n String[] typeNames = LocaleData.getStringArray(locale, LocaleData.ACCRUE_TYPES);\n\n for (int loop = 0; loop < typeNames.length; loop++)\n {\n if (typeNames[loop].equalsIgnoreCase(type) == true)\n {\n result = AccrueType.getInstance(loop + 1);\n break;\n }\n }\n\n if (result == null)\n {\n result = AccrueType.PRORATED;\n }\n\n return (result);\n }", "public static String paramMapToString(final Map<String, String[]> parameters) {\n\n final StringBuffer result = new StringBuffer();\n for (final String key : parameters.keySet()) {\n String[] values = parameters.get(key);\n if (null == values) {\n result.append(key).append('&');\n } else {\n for (final String value : parameters.get(key)) {\n result.append(key).append('=').append(CmsEncoder.encode(value)).append('&');\n }\n }\n }\n // remove last '&'\n if (result.length() > 0) {\n result.setLength(result.length() - 1);\n }\n return result.toString();\n }", "public String[] getReportSamples() {\n final Map<String, String> sampleValues = new HashMap<>();\n sampleValues.put(\"name1\", \"Secure Transpiler Mars\");\n sampleValues.put(\"version1\", \"4.7.0\");\n sampleValues.put(\"name2\", \"Secure Transpiler Bounty\");\n sampleValues.put(\"version2\", \"5.0.0\");\n sampleValues.put(\"license\", \"CDDL-1.1\");\n sampleValues.put(\"name\", \"Secure Pretender\");\n sampleValues.put(\"version\", \"2.7.0\");\n sampleValues.put(\"organization\", \"Axway\");\n\n return ReportsRegistry.allReports()\n .stream()\n .map(report -> ReportUtils.generateSampleRequest(report, sampleValues))\n .map(request -> {\n try {\n String desc = \"\";\n final Optional<Report> byId = ReportsRegistry.findById(request.getReportId());\n\n if(byId.isPresent()) {\n desc = byId.get().getDescription() + \"<br/><br/>\";\n }\n\n return String.format(TWO_PLACES, desc, JsonUtils.serialize(request));\n } catch(IOException e) {\n return \"Error \" + e.getMessage();\n }\n })\n .collect(Collectors.toList())\n .toArray(new String[] {});\n }", "@Override public void setID(Integer val)\n {\n ProjectFile parent = getParentFile();\n Integer previous = getID();\n if (previous != null)\n {\n parent.getResources().unmapID(previous);\n }\n parent.getResources().mapID(val, this);\n\n set(ResourceField.ID, val);\n }", "public void mergeSubtree(final OperationTransformerRegistry targetRegistry, final Map<PathAddress, ModelVersion> subTree) {\n for(Map.Entry<PathAddress, ModelVersion> entry: subTree.entrySet()) {\n mergeSubtree(targetRegistry, entry.getKey(), entry.getValue());\n }\n }", "public static base_response update(nitro_service client, responderpolicy resource) throws Exception {\n\t\tresponderpolicy updateresource = new responderpolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.rule = resource.rule;\n\t\tupdateresource.action = resource.action;\n\t\tupdateresource.undefaction = resource.undefaction;\n\t\tupdateresource.comment = resource.comment;\n\t\tupdateresource.logaction = resource.logaction;\n\t\tupdateresource.appflowaction = resource.appflowaction;\n\t\treturn updateresource.update_resource(client);\n\t}", "public synchronized void resumeControlPoint(final String entryPoint) {\n for (ControlPoint ep : entryPoints.values()) {\n if (ep.getEntryPoint().equals(entryPoint)) {\n ep.resume();\n }\n }\n }" ]
Use this API to fetch statistics of servicegroup_stats resource of given name .
[ "public static servicegroup_stats get(nitro_service service, String servicegroupname) throws Exception{\n\t\tservicegroup_stats obj = new servicegroup_stats();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tservicegroup_stats response = (servicegroup_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}" ]
[ "@PostConstruct\n public void initDatabase() {\n MongoDBInit.LOGGER.info(\"initializing MongoDB\");\n String dbName = System.getProperty(\"mongodb.name\");\n if (dbName == null) {\n throw new RuntimeException(\"Missing database name; Set system property 'mongodb.name'\");\n }\n MongoDatabase db = this.mongo.getDatabase(dbName);\n\n try {\n PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();\n Resource[] resources = resolver.getResources(\"classpath*:mongodb/*.ndjson\");\n MongoDBInit.LOGGER.info(\"Scanning for collection data\");\n for (Resource res : resources) {\n String filename = res.getFilename();\n String collection = filename.substring(0, filename.length() - 7);\n MongoDBInit.LOGGER.info(\"Found collection file: {}\", collection);\n MongoCollection<DBObject> dbCollection = db.getCollection(collection, DBObject.class);\n try (Scanner scan = new Scanner(res.getInputStream(), \"UTF-8\")) {\n int lines = 0;\n while (scan.hasNextLine()) {\n String json = scan.nextLine();\n Object parse = JSON.parse(json);\n if (parse instanceof DBObject) {\n DBObject dbObject = (DBObject) parse;\n dbCollection.insertOne(dbObject);\n } else {\n MongoDBInit.LOGGER.error(\"Invalid object found: {}\", parse);\n throw new RuntimeException(\"Invalid object\");\n }\n lines++;\n }\n MongoDBInit.LOGGER.info(\"Imported {} objects into collection {}\", lines, collection);\n }\n }\n } catch (IOException e) {\n throw new RuntimeException(\"Error importing objects\", e);\n }\n }", "public List<DbLicense> getArtifactLicenses(final String gavc, final FiltersHolder filters) {\n final DbArtifact artifact = getArtifact(gavc);\n final List<DbLicense> licenses = new ArrayList<>();\n\n for(final String name: artifact.getLicenses()){\n final Set<DbLicense> matchingLicenses = licenseMatcher.getMatchingLicenses(name);\n\n // Here is a license to identify\n if(matchingLicenses.isEmpty()){\n final DbLicense notIdentifiedLicense = new DbLicense();\n notIdentifiedLicense.setName(name);\n licenses.add(notIdentifiedLicense);\n } else {\n matchingLicenses.stream()\n .filter(filters::shouldBeInReport)\n .forEach(licenses::add);\n }\n }\n\n return licenses;\n }", "public Task<RemoteInsertOneResult> insertOne(final DocumentT document) {\n return dispatcher.dispatchTask(new Callable<RemoteInsertOneResult>() {\n @Override\n public RemoteInsertOneResult call() {\n return proxy.insertOne(document);\n }\n });\n }", "public int getModifiers() {\n MetaMethod getter = getGetter();\n MetaMethod setter = getSetter();\n if (setter != null && getter == null) return setter.getModifiers();\n if (getter != null && setter == null) return getter.getModifiers();\n int modifiers = getter.getModifiers() | setter.getModifiers();\n int visibility = 0;\n if (Modifier.isPublic(modifiers)) visibility = Modifier.PUBLIC;\n if (Modifier.isProtected(modifiers)) visibility = Modifier.PROTECTED;\n if (Modifier.isPrivate(modifiers)) visibility = Modifier.PRIVATE;\n int states = getter.getModifiers() & setter.getModifiers();\n states &= ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE);\n states |= visibility;\n return states;\n }", "public static void changeSign(DMatrixSparseCSC A , DMatrixSparseCSC B ) {\n if( A != B ) {\n B.copyStructure(A);\n }\n\n for (int i = 0; i < A.nz_length; i++) {\n B.nz_values[i] = -A.nz_values[i];\n }\n }", "public static boolean isPortletEnvSupported() {\n if (enabled == null) {\n synchronized (PortletSupport.class) {\n if (enabled == null) {\n try {\n PortletSupport.class.getClassLoader().loadClass(\"javax.portlet.PortletContext\");\n enabled = true;\n } catch (Throwable ignored) {\n enabled = false;\n }\n }\n }\n }\n return enabled;\n }", "public static void populateSubject(final LinkedHashMap<String, CommonProfile> profiles) {\n if (profiles != null && profiles.size() > 0) {\n final List<CommonProfile> listProfiles = ProfileHelper.flatIntoAProfileList(profiles);\n try {\n if (IS_FULLY_AUTHENTICATED_AUTHORIZER.isAuthorized(null, listProfiles)) {\n SecurityUtils.getSubject().login(new Pac4jToken(listProfiles, false));\n } else if (IS_REMEMBERED_AUTHORIZER.isAuthorized(null, listProfiles)) {\n SecurityUtils.getSubject().login(new Pac4jToken(listProfiles, true));\n }\n } catch (final HttpAction e) {\n throw new TechnicalException(e);\n }\n }\n }", "public Release getReleaseInfo(String appName, String releaseName) {\n return connection.execute(new ReleaseInfo(appName, releaseName), apiKey);\n }", "public static Info eye( final Variable A , ManagerTempVariables manager) {\n Info ret = new Info();\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n\n if( A instanceof VariableMatrix ) {\n ret.op = new Operation(\"eye-m\") {\n @Override\n public void process() {\n DMatrixRMaj mA = ((VariableMatrix)A).matrix;\n output.matrix.reshape(mA.numRows,mA.numCols);\n CommonOps_DDRM.setIdentity(output.matrix);\n }\n };\n } else if( A instanceof VariableInteger ) {\n ret.op = new Operation(\"eye-i\") {\n @Override\n public void process() {\n int N = ((VariableInteger)A).value;\n output.matrix.reshape(N,N);\n CommonOps_DDRM.setIdentity(output.matrix);\n }\n };\n } else {\n throw new RuntimeException(\"Unsupported variable type \"+A);\n }\n\n return ret;\n }" ]
Static factory method to build a JSON Patch out of a JSON representation. @param node the JSON representation of the generated JSON Patch @return a JSON Patch @throws IOException input is not a valid JSON patch @throws NullPointerException input is null
[ "public static JsonPatch fromJson(final JsonNode node) throws IOException {\n requireNonNull(node, \"node\");\n try {\n return Jackson.treeToValue(node, JsonPatch.class);\n } catch (JsonMappingException e) {\n throw new JsonPatchException(\"invalid JSON patch\", e);\n }\n }" ]
[ "private void processRedirect(String stringStatusCode,\n HttpMethod httpMethodProxyRequest,\n HttpServletRequest httpServletRequest,\n HttpServletResponse httpServletResponse) throws Exception {\n // Check if the proxy response is a redirect\n // The following code is adapted from\n // org.tigris.noodle.filters.CheckForRedirect\n // Hooray for open source software\n\n String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();\n if (stringLocation == null) {\n throw new ServletException(\"Received status code: \"\n + stringStatusCode + \" but no \"\n + STRING_LOCATION_HEADER\n + \" header was found in the response\");\n }\n // Modify the redirect to go to this proxy servlet rather than the proxied host\n String stringMyHostName = httpServletRequest.getServerName();\n if (httpServletRequest.getServerPort() != 80) {\n stringMyHostName += \":\" + httpServletRequest.getServerPort();\n }\n stringMyHostName += httpServletRequest.getContextPath();\n httpServletResponse.sendRedirect(stringLocation.replace(\n getProxyHostAndPort() + this.getProxyPath(),\n stringMyHostName));\n }", "public static String base64Encode(byte[] bytes) {\n if (bytes == null) {\n throw new IllegalArgumentException(\"Input bytes must not be null.\");\n }\n if (bytes.length >= BASE64_UPPER_BOUND) {\n throw new IllegalArgumentException(\n \"Input bytes length must not exceed \" + BASE64_UPPER_BOUND);\n }\n\n // Every three bytes is encoded into four characters.\n //\n // Example:\n // input |0 1 0 1 0 0 1 0|0 1 1 0 1 1 1 1|0 1 1 0 0 0 1 0|\n // encode grouping |0 1 0 1 0 0|1 0 0 1 1 0|1 1 1 1 0 1|1 0 0 0 1 0|\n // encoded ascii | U | m | 9 | i |\n\n int triples = bytes.length / 3;\n\n // If the number of input bytes is not a multiple of three, padding characters will be added.\n if (bytes.length % 3 != 0) {\n triples += 1;\n }\n\n // The encoded string will have four characters for every three bytes.\n char[] encoding = new char[triples << 2];\n\n for (int in = 0, out = 0; in < bytes.length; in += 3, out += 4) {\n int triple = (bytes[in] & 0xff) << 16;\n if (in + 1 < bytes.length) {\n triple |= ((bytes[in + 1] & 0xff) << 8);\n }\n if (in + 2 < bytes.length) {\n triple |= (bytes[in + 2] & 0xff);\n }\n encoding[out] = BASE64_CHARS.charAt((triple >> 18) & 0x3f);\n encoding[out + 1] = BASE64_CHARS.charAt((triple >> 12) & 0x3f);\n encoding[out + 2] = BASE64_CHARS.charAt((triple >> 6) & 0x3f);\n encoding[out + 3] = BASE64_CHARS.charAt(triple & 0x3f);\n }\n\n // Add padding characters if needed.\n for (int i = encoding.length - (triples * 3 - bytes.length); i < encoding.length; i++) {\n encoding[i] = '=';\n }\n\n return String.valueOf(encoding);\n }", "private void initXmlBundle() throws CmsException {\n\n CmsFile file = m_cms.readFile(m_resource);\n m_bundleFiles.put(null, m_resource);\n m_xmlBundle = CmsXmlContentFactory.unmarshal(m_cms, file);\n initKeySetForXmlBundle();\n\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 final void debug(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.DEBUG, pObject, null);\r\n\t}", "@CheckResult\n public boolean isCompatible(AbstractTransition another) {\n if (getClass().equals(another.getClass()) && mTarget == another.mTarget && mReverse == another.mReverse && ((mInterpolator == null && another.mInterpolator == null) ||\n mInterpolator.getClass().equals(another.mInterpolator.getClass()))) {\n return true;\n }\n return false;\n }", "public String getUniformDescriptor(GVRContext ctx)\n {\n if (mShaderTemplate == null)\n {\n mShaderTemplate = makeTemplate(ID, ctx);\n ctx.getShaderManager().addShaderID(this);\n }\n return mShaderTemplate.getUniformDescriptor();\n }", "public Where<T, ID> or() {\n\t\tManyClause clause = new ManyClause(pop(\"OR\"), ManyClause.OR_OPERATION);\n\t\tpush(clause);\n\t\taddNeedsFuture(clause);\n\t\treturn this;\n\t}", "public Class<?> getColumnType(int c) {\n\n for (int r = 0; r < m_data.size(); r++) {\n Object val = m_data.get(r).get(c);\n if (val != null) {\n return val.getClass();\n }\n }\n return Object.class;\n }" ]
Parses the input stream to read the header @param input data input to read from @return the parsed protocol header @throws IOException
[ "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 PeriodicEvent runEvery(Runnable task, float delay, float period) {\n return runEvery(task, delay, period, null);\n }", "public Date toDate(Object date) {\n\n Date d = null;\n if (null != date) {\n if (date instanceof Date) {\n d = (Date)date;\n } else if (date instanceof Long) {\n d = new Date(((Long)date).longValue());\n } else {\n try {\n long l = Long.parseLong(date.toString());\n d = new Date(l);\n } catch (Exception e) {\n // do nothing, just let d remain null\n }\n }\n }\n return d;\n }", "private void setW() {\n if( saveW ) {\n W.col0 = Y.col0;\n W.col1 = Y.col1;\n W.row0 = Y.row0;\n W.row1 = Y.row1;\n } else {\n W.col1 = Y.col1 - Y.col0;\n W.row0 = Y.row0;\n }\n }", "private void initFieldFactories() {\n\n if (m_model.hasMasterMode()) {\n TranslateTableFieldFactory masterFieldFactory = new CmsMessageBundleEditorTypes.TranslateTableFieldFactory(\n m_table,\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.MASTER));\n masterFieldFactory.registerKeyChangeListener(this);\n m_fieldFactories.put(CmsMessageBundleEditorTypes.EditMode.MASTER, masterFieldFactory);\n }\n TranslateTableFieldFactory defaultFieldFactory = new CmsMessageBundleEditorTypes.TranslateTableFieldFactory(\n m_table,\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.DEFAULT));\n defaultFieldFactory.registerKeyChangeListener(this);\n m_fieldFactories.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, defaultFieldFactory);\n\n }", "public MediaType removeQualityValue() {\n\t\tif (!this.parameters.containsKey(PARAM_QUALITY_FACTOR)) {\n\t\t\treturn this;\n\t\t}\n\t\tMap<String, String> params = new LinkedHashMap<String, String>(this.parameters);\n\t\tparams.remove(PARAM_QUALITY_FACTOR);\n\t\treturn new MediaType(this, params);\n\t}", "static List<NamedArgument> getNamedArgs( ExtensionContext context ) {\n List<NamedArgument> namedArgs = new ArrayList<>();\n\n if( context.getTestMethod().get().getParameterCount() > 0 ) {\n try {\n if( context.getClass().getCanonicalName().equals( METHOD_EXTENSION_CONTEXT ) ) {\n Field field = context.getClass().getSuperclass().getDeclaredField( \"testDescriptor\" );\n Object testDescriptor = ReflectionUtil.getFieldValueOrNull( field, context, ERROR );\n if( testDescriptor != null\n && testDescriptor.getClass().getCanonicalName().equals( TEST_TEMPLATE_INVOCATION_TEST_DESCRIPTOR ) ) {\n Object invocationContext = ReflectionUtil.getFieldValueOrNull( \"invocationContext\", testDescriptor, ERROR );\n if( invocationContext != null\n && invocationContext.getClass().getCanonicalName().equals( PARAMETERIZED_TEST_INVOCATION_CONTEXT ) ) {\n Object arguments = ReflectionUtil.getFieldValueOrNull( \"arguments\", invocationContext, ERROR );\n List<Object> args = Arrays.asList( (Object[]) arguments );\n namedArgs = ParameterNameUtil.mapArgumentsWithParameterNames( context.getTestMethod().get(), args );\n }\n }\n }\n } catch( Exception e ) {\n log.warn( ERROR, e );\n }\n }\n\n return namedArgs;\n }", "protected String getDBManipulationUrl()\r\n {\r\n JdbcConnectionDescriptor jcd = getConnection();\r\n\r\n return jcd.getProtocol()+\":\"+jcd.getSubProtocol()+\":\"+jcd.getDbAlias();\r\n }", "public F resolve(R resolvable, boolean cache) {\n R wrappedResolvable = wrap(resolvable);\n if (cache) {\n return resolved.getValue(wrappedResolvable);\n } else {\n return resolverFunction.apply(wrappedResolvable);\n }\n }", "public void removeSource(GVRAudioSource audioSource)\n {\n synchronized (mAudioSources)\n {\n audioSource.setListener(null);\n mAudioSources.remove(audioSource);\n }\n }" ]
Get the account knowing his title @param title the title of the account (it can change at runtime!) @return the account founded or null if the account not exists
[ "public MaterialAccount getAccountByTitle(String title) {\n for(MaterialAccount account : accountManager)\n if(currentAccount.getTitle().equals(title))\n return account;\n\n return null;\n }" ]
[ "private List<Row> createTimeEntryRowList(String shiftData) throws ParseException\n {\n List<Row> list = new ArrayList<Row>();\n String[] shifts = shiftData.split(\",|:\");\n int index = 1;\n while (index < shifts.length)\n {\n index += 2;\n int entryCount = Integer.parseInt(shifts[index]);\n index++;\n\n for (int entryIndex = 0; entryIndex < entryCount; entryIndex++)\n {\n Integer exceptionTypeID = Integer.valueOf(shifts[index + 0]);\n Date startTime = DatatypeConverter.parseBasicTime(shifts[index + 1]);\n Date endTime = DatatypeConverter.parseBasicTime(shifts[index + 2]);\n\n Map<String, Object> map = new HashMap<String, Object>();\n map.put(\"START_TIME\", startTime);\n map.put(\"END_TIME\", endTime);\n map.put(\"EXCEPTIOP\", exceptionTypeID);\n\n list.add(new MapRow(map));\n\n index += 3;\n }\n }\n\n return list;\n }", "public boolean filter(Event event) {\n LOG.info(\"StringContentFilter called\");\n \n if (wordsToFilter != null) {\n for (String filterWord : wordsToFilter) {\n if (event.getContent() != null\n && -1 != event.getContent().indexOf(filterWord)) {\n return true;\n }\n }\n }\n return false;\n }", "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 static aaagroup_vpntrafficpolicy_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_vpntrafficpolicy_binding obj = new aaagroup_vpntrafficpolicy_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_vpntrafficpolicy_binding response[] = (aaagroup_vpntrafficpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static String format(ImageFormat format) {\n if (format == null) {\n throw new IllegalArgumentException(\"You must specify an image format.\");\n }\n return FILTER_FORMAT + \"(\" + format.value + \")\";\n }", "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 }", "@Override\r\n public ImageSource apply(ImageSource source) {\r\n if (radius != 0) {\r\n if (source.isGrayscale()) {\r\n return applyGrayscale(source, radius);\r\n } else {\r\n return applyRGB(source, radius);\r\n }\r\n } else {\r\n if (source.isGrayscale()) {\r\n return applyGrayscale(source, kernel);\r\n } else {\r\n return applyRGB(source, kernel);\r\n }\r\n }\r\n }", "@Inline(value = \"$1.remove($2)\", statementExpression = true)\n\tpublic static <K, V> V operator_remove(Map<K, V> map, K key) {\n\t\treturn map.remove(key);\n\t}", "protected void updatePicker(MotionEvent event, boolean isActive)\n {\n final MotionEvent newEvent = (event != null) ? event : null;\n final ControllerPick controllerPick = new ControllerPick(mPicker, newEvent, isActive);\n context.runOnGlThread(controllerPick);\n }" ]
Syncronously creates a Renderscript context if none exists. Creating a Renderscript context takes about 20 ms in Nexus 5 @return
[ "public RenderScript getRenderScript() {\n if (renderScript == null) {\n renderScript = RenderScript.create(context, renderScriptContextType);\n }\n return renderScript;\n }" ]
[ "private void writeWBS(Task mpxj)\n {\n if (mpxj.getUniqueID().intValue() != 0)\n {\n WBSType xml = m_factory.createWBSType();\n m_project.getWBS().add(xml);\n String code = mpxj.getWBS();\n code = code == null || code.length() == 0 ? DEFAULT_WBS_CODE : code;\n\n Task parentTask = mpxj.getParentTask();\n Integer parentObjectID = parentTask == null ? null : parentTask.getUniqueID();\n\n xml.setCode(code);\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setName(mpxj.getName());\n\n xml.setObjectId(mpxj.getUniqueID());\n xml.setParentObjectId(parentObjectID);\n xml.setProjectObjectId(PROJECT_OBJECT_ID);\n xml.setSequenceNumber(Integer.valueOf(m_wbsSequence++));\n\n xml.setStatus(\"Active\");\n }\n\n writeChildTasks(mpxj);\n }", "@Override\n public ConditionBuilder as(String variable)\n {\n Assert.notNull(variable, \"Variable name must not be null.\");\n this.setOutputVariablesName(variable);\n return this;\n }", "private void setTableAliasForPath(String aPath, List hintClasses, TableAlias anAlias)\r\n {\r\n m_pathToAlias.put(buildAliasKey(aPath, hintClasses), anAlias);\r\n }", "public void setMesh(GVRMesh mesh) {\n mMesh = mesh;\n NativeMeshCollider.setMesh(getNative(), mesh.getNative());\n }", "public int getSridFromCrs(String crs) {\n\t\tint crsInt;\n\t\tif (crs.indexOf(':') != -1) {\n\t\t\tcrsInt = Integer.parseInt(crs.substring(crs.indexOf(':') + 1));\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tcrsInt = Integer.parseInt(crs);\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\tcrsInt = 0;\n\t\t\t}\n\t\t}\n\t\treturn crsInt;\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 }", "private static RemoteWebDriver buildRemoteWebDriver(String hubUrl) {\n\t\tDesiredCapabilities capabilities = new DesiredCapabilities();\n\t\tcapabilities.setPlatform(Platform.ANY);\n\t\tURL url;\n\t\ttry {\n\t\t\turl = new URL(hubUrl);\n\t\t} catch (MalformedURLException e) {\n\t\t\tLOGGER.error(\"The given hub url of the remote server is malformed can not continue!\",\n\t\t\t\t\te);\n\t\t\treturn null;\n\t\t}\n\t\tHttpCommandExecutor executor = null;\n\t\ttry {\n\t\t\texecutor = new HttpCommandExecutor(url);\n\t\t} catch (Exception e) {\n\t\t\t// TODO Stefan; refactor this catch, this will definitely result in\n\t\t\t// NullPointers, why\n\t\t\t// not throw RuntimeException direct?\n\t\t\tLOGGER.error(\n\t\t\t\t\t\"Received unknown exception while creating the \"\n\t\t\t\t\t\t\t+ \"HttpCommandExecutor, can not continue!\",\n\t\t\t\t\te);\n\t\t\treturn null;\n\t\t}\n\t\treturn new RemoteWebDriver(executor, capabilities);\n\t}", "private List<Integer> getPageSizes() {\n\n final String pageSizes = parseOptionalStringValue(XML_ELEMENT_PAGESIZE);\n if (pageSizes != null) {\n String[] pageSizesArray = pageSizes.split(\"-\");\n if (pageSizesArray.length > 0) {\n try {\n List<Integer> result = new ArrayList<>(pageSizesArray.length);\n for (int i = 0; i < pageSizesArray.length; i++) {\n result.add(Integer.valueOf(pageSizesArray[i]));\n }\n return result;\n } catch (NumberFormatException e) {\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_PARSING_PAGE_SIZES_FAILED_1, pageSizes), e);\n }\n }\n }\n return null;\n }", "public Collection<Service> getServices() throws FlickrException {\r\n List<Service> list = new ArrayList<Service>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_SERVICES);\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 servicesElement = response.getPayload();\r\n NodeList serviceNodes = servicesElement.getElementsByTagName(\"service\");\r\n for (int i = 0; i < serviceNodes.getLength(); i++) {\r\n Element serviceElement = (Element) serviceNodes.item(i);\r\n Service srv = new Service();\r\n srv.setId(serviceElement.getAttribute(\"id\"));\r\n srv.setName(XMLUtilities.getValue(serviceElement));\r\n list.add(srv);\r\n }\r\n return list;\r\n }" ]
Appends formatted text to the source. <p>Formatting supports {@code %s} and {@code %n$s}. Most args are converted according to their {@link Object#toString()} method, except that:<ul> <li> {@link Package} and {@link PackageElement} instances use their fully-qualified names (no "package " prefix). <li> {@link Class}, {@link TypeElement}, {@link DeclaredType} and {@link QualifiedName} instances use their qualified names where necessary, or shorter versions if a suitable import line can be added. <li> {@link Excerpt} instances have {@link Excerpt#addTo(SourceBuilder)} called. </ul>
[ "public SourceBuilder add(String fmt, Object... args) {\n TemplateApplier.withParams(args).onText(source::append).onParam(this::add).parse(fmt);\n return this;\n }" ]
[ "static BsonDocument getVersionedFilter(\n @Nonnull final BsonValue documentId,\n @Nullable final BsonValue version\n ) {\n final BsonDocument filter = new BsonDocument(\"_id\", documentId);\n if (version == null) {\n filter.put(DOCUMENT_VERSION_FIELD, new BsonDocument(\"$exists\", BsonBoolean.FALSE));\n } else {\n filter.put(DOCUMENT_VERSION_FIELD, version);\n }\n return filter;\n }", "@SuppressWarnings(\"unchecked\")\n private void addPrivateFieldsAccessors(ClassNode node) {\n Set<ASTNode> accessedFields = (Set<ASTNode>) node.getNodeMetaData(StaticTypesMarker.PV_FIELDS_ACCESS);\n if (accessedFields==null) return;\n Map<String, MethodNode> privateConstantAccessors = (Map<String, MethodNode>) node.getNodeMetaData(PRIVATE_FIELDS_ACCESSORS);\n if (privateConstantAccessors!=null) {\n // already added\n return;\n }\n int acc = -1;\n privateConstantAccessors = new HashMap<String, MethodNode>();\n final int access = Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC;\n for (FieldNode fieldNode : node.getFields()) {\n if (accessedFields.contains(fieldNode)) {\n\n acc++;\n Parameter param = new Parameter(node.getPlainNodeReference(), \"$that\");\n Expression receiver = fieldNode.isStatic()?new ClassExpression(node):new VariableExpression(param);\n Statement stmt = new ExpressionStatement(new PropertyExpression(\n receiver,\n fieldNode.getName()\n ));\n MethodNode accessor = node.addMethod(\"pfaccess$\"+acc, access, fieldNode.getOriginType(), new Parameter[]{param}, ClassNode.EMPTY_ARRAY, stmt);\n privateConstantAccessors.put(fieldNode.getName(), accessor);\n }\n }\n node.setNodeMetaData(PRIVATE_FIELDS_ACCESSORS, privateConstantAccessors);\n }", "public void setMeta(String photoId, String title, String description) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_META);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"title\", title);\r\n parameters.put(\"description\", description);\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "public static synchronized ExecutionStatistics get()\n {\n Thread currentThread = Thread.currentThread();\n if (stats.get(currentThread) == null)\n {\n stats.put(currentThread, new ExecutionStatistics());\n }\n return stats.get(currentThread);\n }", "public void addNotIn(String attribute, Query subQuery)\r\n {\r\n\t\t// PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildNotInCriteria(attribute, subQuery, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildNotInCriteria(attribute, subQuery, getUserAlias(attribute)));\r\n }", "public Label htmlLabel(String html) {\n\n Label label = new Label();\n label.setContentMode(ContentMode.HTML);\n label.setValue(html);\n return label;\n\n }", "private EndpointOverride getEndpointOverrideFromResultSet(ResultSet results) throws Exception {\n EndpointOverride endpoint = new EndpointOverride();\n endpoint.setPathId(results.getInt(Constants.GENERIC_ID));\n endpoint.setPath(results.getString(Constants.PATH_PROFILE_ACTUAL_PATH));\n endpoint.setBodyFilter(results.getString(Constants.PATH_PROFILE_BODY_FILTER));\n endpoint.setPathName(results.getString(Constants.PATH_PROFILE_PATHNAME));\n endpoint.setContentType(results.getString(Constants.PATH_PROFILE_CONTENT_TYPE));\n endpoint.setRequestType(results.getInt(Constants.PATH_PROFILE_REQUEST_TYPE));\n endpoint.setRepeatNumber(results.getInt(Constants.REQUEST_RESPONSE_REPEAT_NUMBER));\n endpoint.setGroupIds(results.getString(Constants.PATH_PROFILE_GROUP_IDS));\n endpoint.setRequestEnabled(results.getBoolean(Constants.REQUEST_RESPONSE_REQUEST_ENABLED));\n endpoint.setResponseEnabled(results.getBoolean(Constants.REQUEST_RESPONSE_RESPONSE_ENABLED));\n endpoint.setClientUUID(results.getString(Constants.GENERIC_CLIENT_UUID));\n endpoint.setProfileId(results.getInt(Constants.GENERIC_PROFILE_ID));\n endpoint.setGlobal(results.getBoolean(Constants.PATH_PROFILE_GLOBAL));\n return endpoint;\n }", "private Map<Integer, List<Row>> createExceptionAssignmentMap(List<Row> rows)\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer calendarID = row.getInteger(\"ID\");\n String exceptions = row.getString(\"EXCEPTIONS\");\n map.put(calendarID, createExceptionAssignmentRowList(exceptions));\n }\n return map;\n }", "public static String getShortClassName(Object o) {\r\n String name = o.getClass().getName();\r\n int index = name.lastIndexOf('.');\r\n if (index >= 0) {\r\n name = name.substring(index + 1);\r\n }\r\n return name;\r\n }" ]
Read data for an individual task. @param row task data from database @param task Task instance
[ "private void populateTask(Row row, Task task)\n {\n task.setUniqueID(row.getInteger(\"Z_PK\"));\n task.setName(row.getString(\"ZTITLE\"));\n task.setPriority(Priority.getInstance(row.getInt(\"ZPRIORITY\")));\n task.setMilestone(row.getBoolean(\"ZISMILESTONE\"));\n task.setActualFinish(row.getTimestamp(\"ZGIVENACTUALENDDATE_\"));\n task.setActualStart(row.getTimestamp(\"ZGIVENACTUALSTARTDATE_\"));\n task.setNotes(row.getString(\"ZOBJECTDESCRIPTION\"));\n task.setDuration(row.getDuration(\"ZGIVENDURATION_\"));\n task.setOvertimeWork(row.getWork(\"ZGIVENWORKOVERTIME_\"));\n task.setWork(row.getWork(\"ZGIVENWORK_\"));\n task.setLevelingDelay(row.getDuration(\"ZLEVELINGDELAY_\"));\n task.setActualOvertimeWork(row.getWork(\"ZGIVENACTUALWORKOVERTIME_\"));\n task.setActualWork(row.getWork(\"ZGIVENACTUALWORK_\"));\n task.setRemainingWork(row.getWork(\"ZGIVENACTUALWORK_\"));\n task.setGUID(row.getUUID(\"ZUNIQUEID\"));\n\n Integer calendarID = row.getInteger(\"ZGIVENCALENDAR\");\n if (calendarID != null)\n {\n ProjectCalendar calendar = m_project.getCalendarByUniqueID(calendarID);\n if (calendar != null)\n {\n task.setCalendar(calendar);\n }\n }\n\n populateConstraints(row, task);\n\n // Percent complete is calculated bottom up from assignments and actual work vs. planned work\n\n m_eventManager.fireTaskReadEvent(task);\n }" ]
[ "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 systemsession[] get(nitro_service service, Long sid[]) throws Exception{\n\t\tif (sid !=null && sid.length>0) {\n\t\t\tsystemsession response[] = new systemsession[sid.length];\n\t\t\tsystemsession obj[] = new systemsession[sid.length];\n\t\t\tfor (int i=0;i<sid.length;i++) {\n\t\t\t\tobj[i] = new systemsession();\n\t\t\t\tobj[i].set_sid(sid[i]);\n\t\t\t\tresponse[i] = (systemsession) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public PhotoList<Photo> getClusterPhotos(String tag, String clusterId) throws FlickrException {\n\n PhotoList<Photo> photos = new PhotoList<Photo>();\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_CLUSTER_PHOTOS);\n\n parameters.put(\"tag\", tag);\n parameters.put(\"cluster_id\", clusterId);\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 photosElement = response.getPayload();\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\n photos.setPage(\"1\");\n photos.setPages(\"1\");\n photos.setPerPage(\"\" + photoNodes.getLength());\n photos.setTotal(\"\" + photoNodes.getLength());\n for (int i = 0; i < photoNodes.getLength(); i++) {\n Element photoElement = (Element) photoNodes.item(i);\n photos.add(PhotoUtils.createPhoto(photoElement));\n }\n return photos;\n }", "public void displayUseCases()\r\n {\r\n System.out.println();\r\n for (int i = 0; i < useCases.size(); i++)\r\n {\r\n System.out.println(\"[\" + i + \"] \" + ((UseCase) useCases.get(i)).getDescription());\r\n }\r\n }", "public static clusternodegroup_nslimitidentifier_binding[] get(nitro_service service, String name) throws Exception{\n\t\tclusternodegroup_nslimitidentifier_binding obj = new clusternodegroup_nslimitidentifier_binding();\n\t\tobj.set_name(name);\n\t\tclusternodegroup_nslimitidentifier_binding response[] = (clusternodegroup_nslimitidentifier_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static boolean isLogDownloadAvailable(CliGuiContext cliGuiCtx) {\n ModelNode readOps = null;\n try {\n readOps = cliGuiCtx.getExecutor().doCommand(\"/subsystem=logging:read-children-types\");\n } catch (CommandFormatException | IOException e) {\n return false;\n }\n if (!readOps.get(\"result\").isDefined()) return false;\n for (ModelNode op: readOps.get(\"result\").asList()) {\n if (\"log-file\".equals(op.asString())) return true;\n }\n return false;\n }", "public static Integer convertPathIdentifier(String identifier, Integer profileId) throws Exception {\n Integer pathId = -1;\n try {\n pathId = Integer.parseInt(identifier);\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n if (profileId == null)\n throw new Exception(\"A profileId must be specified\");\n\n pathId = PathOverrideService.getInstance().getPathId(identifier, profileId);\n }\n\n return pathId;\n }", "private void populateDateTimeSettings(Record record, ProjectProperties properties)\n {\n properties.setDateOrder(record.getDateOrder(0));\n properties.setTimeFormat(record.getTimeFormat(1));\n\n Date time = getTimeFromInteger(record.getInteger(2));\n if (time != null)\n {\n properties.setDefaultStartTime(time);\n }\n\n Character c = record.getCharacter(3);\n if (c != null)\n {\n properties.setDateSeparator(c.charValue());\n }\n\n c = record.getCharacter(4);\n if (c != null)\n {\n properties.setTimeSeparator(c.charValue());\n }\n\n properties.setAMText(record.getString(5));\n properties.setPMText(record.getString(6));\n properties.setDateFormat(record.getDateFormat(7));\n properties.setBarTextDateFormat(record.getDateFormat(8));\n }", "public Range<App> listApps(String range) {\n return connection.execute(new AppList(range), apiKey);\n }" ]
Returns the value associated with the given key, if any. @return the value associated with the given key, or <Code>null</Code> if the key maps to no value
[ "public Object get(Object key)\r\n {\r\n purge();\r\n Entry entry = getEntry(key);\r\n if (entry == null) return null;\r\n return entry.getValue();\r\n }" ]
[ "private void processAssignments() throws SQLException\n {\n List<Row> rows = getRows(\"select * from zscheduleitem where zproject=? and z_ent=? order by zorderinactivity\", m_projectID, m_entityMap.get(\"Assignment\"));\n for (Row row : rows)\n {\n Task task = m_project.getTaskByUniqueID(row.getInteger(\"ZACTIVITY_\"));\n Resource resource = m_project.getResourceByUniqueID(row.getInteger(\"ZRESOURCE\"));\n if (task != null && resource != null)\n {\n ResourceAssignment assignment = task.addResourceAssignment(resource);\n assignment.setGUID(row.getUUID(\"ZUNIQUEID\"));\n assignment.setActualFinish(row.getTimestamp(\"ZGIVENACTUALENDDATE_\"));\n assignment.setActualStart(row.getTimestamp(\"ZGIVENACTUALSTARTDATE_\"));\n\n assignment.setWork(assignmentDuration(task, row.getWork(\"ZGIVENWORK_\")));\n assignment.setOvertimeWork(assignmentDuration(task, row.getWork(\"ZGIVENWORKOVERTIME_\")));\n assignment.setActualWork(assignmentDuration(task, row.getWork(\"ZGIVENACTUALWORK_\")));\n assignment.setActualOvertimeWork(assignmentDuration(task, row.getWork(\"ZGIVENACTUALWORKOVERTIME_\")));\n assignment.setRemainingWork(assignmentDuration(task, row.getWork(\"ZGIVENREMAININGWORK_\")));\n\n assignment.setLevelingDelay(row.getDuration(\"ZLEVELINGDELAY_\"));\n\n if (assignment.getRemainingWork() == null)\n {\n assignment.setRemainingWork(assignment.getWork());\n }\n\n if (resource.getType() == ResourceType.WORK)\n {\n assignment.setUnits(Double.valueOf(NumberHelper.getDouble(row.getDouble(\"ZRESOURCEUNITS_\")) * 100.0));\n }\n }\n }\n }", "public synchronized void stop() throws DatastoreEmulatorException {\n // We intentionally don't check the internal state. If people want to try and stop the server\n // multiple times that's fine.\n stopEmulatorInternal();\n if (state != State.STOPPED) {\n state = State.STOPPED;\n if (projectDirectory != null) {\n try {\n Process process =\n new ProcessBuilder(\"rm\", \"-r\", projectDirectory.getAbsolutePath()).start();\n if (process.waitFor() != 0) {\n throw new IOException(\n \"Temporary project directory deletion exited with \" + process.exitValue());\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Could not delete temporary project directory\", e);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new IllegalStateException(\"Could not delete temporary project directory\", e);\n }\n }\n }\n }", "public static String format(final String code, final Properties options, final LineEnding lineEnding) {\n\t\tCheck.notEmpty(code, \"code\");\n\t\tCheck.notEmpty(options, \"options\");\n\t\tCheck.notNull(lineEnding, \"lineEnding\");\n\n\t\tfinal CodeFormatter formatter = ToolFactory.createCodeFormatter(options);\n\t\tfinal String lineSeparator = LineEnding.find(lineEnding, code);\n\t\tTextEdit te = null;\n\t\ttry {\n\t\t\tte = formatter.format(CodeFormatter.K_COMPILATION_UNIT, code, 0, code.length(), 0, lineSeparator);\n\t\t} catch (final Exception formatFailed) {\n\t\t\tLOG.warn(\"Formatting failed\", formatFailed);\n\t\t}\n\n\t\tString formattedCode = code;\n\t\tif (te == null) {\n\t\t\tLOG.info(\"Code cannot be formatted. Possible cause is unmatched source/target/compliance version.\");\n\t\t} else {\n\n\t\t\tfinal IDocument doc = new Document(code);\n\t\t\ttry {\n\t\t\t\tte.apply(doc);\n\t\t\t} catch (final Exception e) {\n\t\t\t\tLOG.warn(e.getLocalizedMessage(), e);\n\t\t\t}\n\t\t\tformattedCode = doc.get();\n\t\t}\n\t\treturn formattedCode;\n\t}", "public boolean hasSameConfiguration(BoneCPConfig that){\n\t\tif ( that != null && Objects.equal(this.acquireIncrement, that.getAcquireIncrement())\n\t\t\t\t&& Objects.equal(this.acquireRetryDelayInMs, that.getAcquireRetryDelayInMs())\n\t\t\t\t&& Objects.equal(this.closeConnectionWatch, that.isCloseConnectionWatch())\n\t\t\t\t&& Objects.equal(this.logStatementsEnabled, that.isLogStatementsEnabled())\n\t\t\t\t&& Objects.equal(this.connectionHook, that.getConnectionHook())\n\t\t\t\t&& Objects.equal(this.connectionTestStatement, that.getConnectionTestStatement())\n\t\t\t\t&& Objects.equal(this.idleConnectionTestPeriodInSeconds, that.getIdleConnectionTestPeriod(TimeUnit.SECONDS))\n\t\t\t\t&& Objects.equal(this.idleMaxAgeInSeconds, that.getIdleMaxAge(TimeUnit.SECONDS))\n\t\t\t\t&& Objects.equal(this.initSQL, that.getInitSQL())\n\t\t\t\t&& Objects.equal(this.jdbcUrl, that.getJdbcUrl())\n\t\t\t\t&& Objects.equal(this.maxConnectionsPerPartition, that.getMaxConnectionsPerPartition())\n\t\t\t\t&& Objects.equal(this.minConnectionsPerPartition, that.getMinConnectionsPerPartition())\n\t\t\t\t&& Objects.equal(this.partitionCount, that.getPartitionCount())\n\t\t\t\t&& Objects.equal(this.releaseHelperThreads, that.getReleaseHelperThreads())\n\t\t\t\t&& Objects.equal(this.statementsCacheSize, that.getStatementsCacheSize())\n\t\t\t\t&& Objects.equal(this.username, that.getUsername())\n\t\t\t\t&& Objects.equal(this.password, that.getPassword())\n\t\t\t\t&& Objects.equal(this.lazyInit, that.isLazyInit())\n\t\t\t\t&& Objects.equal(this.transactionRecoveryEnabled, that.isTransactionRecoveryEnabled())\n\t\t\t\t&& Objects.equal(this.acquireRetryAttempts, that.getAcquireRetryAttempts())\n\t\t\t\t&& Objects.equal(this.statementReleaseHelperThreads, that.getStatementReleaseHelperThreads())\n\t\t\t\t&& Objects.equal(this.closeConnectionWatchTimeoutInMs, that.getCloseConnectionWatchTimeout())\n\t\t\t\t&& Objects.equal(this.connectionTimeoutInMs, that.getConnectionTimeoutInMs())\n\t\t\t\t&& Objects.equal(this.datasourceBean, that.getDatasourceBean())\n\t\t\t\t&& Objects.equal(this.getQueryExecuteTimeLimitInMs(), that.getQueryExecuteTimeLimitInMs())\n\t\t\t\t&& Objects.equal(this.poolAvailabilityThreshold, that.getPoolAvailabilityThreshold())\n\t\t\t\t&& Objects.equal(this.poolName, that.getPoolName())\n\t\t\t\t&& Objects.equal(this.disableConnectionTracking, that.isDisableConnectionTracking())\n\n\t\t\t\t){\n\t\t\treturn true;\n\t\t} \n\n\t\treturn false;\n\t}", "public static void shutDownActorSystemForce() {\n if (!actorSystem.isTerminated()) {\n logger.info(\"shutting down actor system...\");\n actorSystem.shutdown();\n actorSystem.awaitTermination(timeOutDuration);\n logger.info(\"Actor system has been shut down.\");\n } else {\n logger.info(\"Actor system has been terminated already. NO OP.\");\n }\n\n }", "public static final <T> T getSingle( Iterable<T> it ) {\n if( ! it.iterator().hasNext() )\n return null;\n\n final Iterator<T> iterator = it.iterator();\n T o = iterator.next();\n if(iterator.hasNext())\n throw new IllegalStateException(\"Found multiple items in iterator over \" + o.getClass().getName() );\n\n return o;\n }", "public String createSessionForResource(String configPath, String fileName) throws CmsUgcException {\n\n CmsUgcSession formSession = CmsUgcSessionFactory.getInstance().createSessionForFile(\n getCmsObject(),\n getRequest(),\n configPath,\n fileName);\n return \"\" + formSession.getId();\n }", "public static DMatrixSparseCSC triangle( boolean upper , int N , double minFill , double maxFill , Random rand ) {\n int nz = (int)(((N-1)*(N-1)/2)*(rand.nextDouble()*(maxFill-minFill)+minFill))+N;\n\n if( upper ) {\n return triangleUpper(N,0,nz,-1,1,rand);\n } else {\n return triangleLower(N,0,nz,-1,1,rand);\n }\n }", "public synchronized void cleanWaitTaskQueue() {\n\n for (ParallelTask task : waitQ) {\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.USER_CANCELED, \"NA\"));\n logger.info(\n \"task {} removed from wait q. This task has been marked as USER CANCELED.\",\n task.getTaskId());\n\n }\n\n waitQ.clear();\n }" ]
Gets a property with a default value. @param key The key string. @param defaultValue The default value. @return The property string.
[ "public String getProperty(String key, String defaultValue) {\n return mProperties.getProperty(key, defaultValue);\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 }", "public static void registerAgent(Agent agent, String serviceName, String serviceType) throws FIPAException{\n DFAgentDescription dfd = new DFAgentDescription();\n ServiceDescription sd = new ServiceDescription();\n \n sd.setType(serviceType);\n sd.setName(serviceName);\n \n //NOTE El serviceType es un string que define el tipo de servicio publicado en el DF por el Agente X. \n // He escogido crear nombres en clave en jade.common.Definitions para este campo. \n //NOTE El serviceName es el nombre efectivo del servicio. \n // Esto es lo que el usuario va a definir en MockConfiguration.DFNameService y no el tipo como estaba puesto. \n // sd.setType(agentType);\n // sd.setName(agent.getLocalName());\n \n //Add services??\n \n // Sets the agent description\n dfd.setName(agent.getAID());\n dfd.addServices(sd);\n \n // Register the agent\n DFService.register(agent, dfd);\n }", "public Collection getAllObjects(Class target)\r\n {\r\n PersistenceBroker broker = getBroker();\r\n Collection result;\r\n try\r\n {\r\n Query q = new QueryByCriteria(target);\r\n result = broker.getCollectionByQuery(q);\r\n }\r\n finally\r\n {\r\n if (broker != null) broker.close();\r\n }\r\n return result;\r\n }", "private String toSQLClause(FieldCriteria c, ClassDescriptor cld)\r\n {\r\n String colName = toSqlClause(c.getAttribute(), cld);\r\n return colName + c.getClause() + c.getValue();\r\n }", "public static base_responses unset(nitro_service client, gslbservice resources[], String[] args) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbservice unsetresources[] = new gslbservice[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunsetresources[i] = new gslbservice();\n\t\t\t\tunsetresources[i].servicename = resources[i].servicename;\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "@RequestMapping(value = \"/legendgraphic\", method = RequestMethod.GET)\n\tpublic ModelAndView getGraphic(@RequestParam(\"layerId\") String layerId,\n\t\t\t@RequestParam(value = \"styleName\", required = false) String styleName,\n\t\t\t@RequestParam(value = \"ruleIndex\", required = false) Integer ruleIndex,\n\t\t\t@RequestParam(value = \"format\", required = false) String format,\n\t\t\t@RequestParam(value = \"width\", required = false) Integer width,\n\t\t\t@RequestParam(value = \"height\", required = false) Integer height,\n\t\t\t@RequestParam(value = \"scale\", required = false) Double scale,\n\t\t\t@RequestParam(value = \"allRules\", required = false) Boolean allRules, HttpServletRequest request)\n\t\t\tthrows GeomajasException {\n\t\tif (!allRules) {\n\t\t\treturn getGraphic(layerId, styleName, ruleIndex, format, width, height, scale);\n\t\t} else {\n\t\t\treturn getGraphics(layerId, styleName, format, width, height, scale);\n\t\t}\n\t}", "public static String readFlowId(Message message) {\n if (!(message instanceof SoapMessage)) {\n return null;\n }\n String flowId = null;\n Header hdFlowId = ((SoapMessage)message).getHeader(FLOW_ID_QNAME);\n if (hdFlowId != null) {\n if (hdFlowId.getObject() instanceof String) {\n flowId = (String)hdFlowId.getObject();\n } else if (hdFlowId.getObject() instanceof Node) {\n Node headerNode = (Node)hdFlowId.getObject();\n flowId = headerNode.getTextContent();\n } else {\n LOG.warning(\"Found FlowId soap header but value is not a String or a Node! Value: \"\n + hdFlowId.getObject().toString());\n }\n }\n return flowId;\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}", "private void updateBaseCalendarNames(List<Pair<ProjectCalendar, Integer>> baseCalendars)\n {\n for (Pair<ProjectCalendar, Integer> pair : baseCalendars)\n {\n ProjectCalendar cal = pair.getFirst();\n Integer baseCalendarID = pair.getSecond();\n ProjectCalendar baseCal = m_calendarMap.get(baseCalendarID);\n if (baseCal != null)\n {\n cal.setParent(baseCal);\n }\n }\n }" ]
Builds the mapping table.
[ "private static char[] buildTable() {\n char[] table = new char[26];\n for (int ix = 0; ix < table.length; ix++)\n table[ix] = '0';\n table['B' - 'A'] = '1';\n table['P' - 'A'] = '1';\n table['F' - 'A'] = '1';\n table['V' - 'A'] = '1';\n table['C' - 'A'] = '2';\n table['S' - 'A'] = '2';\n table['K' - 'A'] = '2';\n table['G' - 'A'] = '2';\n table['J' - 'A'] = '2';\n table['Q' - 'A'] = '2';\n table['X' - 'A'] = '2';\n table['Z' - 'A'] = '2';\n table['D' - 'A'] = '3';\n table['T' - 'A'] = '3';\n table['L' - 'A'] = '4';\n table['M' - 'A'] = '5';\n table['N' - 'A'] = '5';\n table['R' - 'A'] = '6';\n return table;\n }" ]
[ "public static ExecutorService newSingleThreadDaemonExecutor() {\n return Executors.newSingleThreadExecutor(r -> {\n Thread t = Executors.defaultThreadFactory().newThread(r);\n t.setDaemon(true);\n return t;\n });\n }", "static synchronized LogContext configureLogContext(final File logDir, final File configDir, final String defaultLogFileName, final CommandContext ctx) {\n final LogContext embeddedLogContext = Holder.LOG_CONTEXT;\n final Path bootLog = logDir.toPath().resolve(Paths.get(defaultLogFileName));\n final Path loggingProperties = configDir.toPath().resolve(Paths.get(\"logging.properties\"));\n if (Files.exists(loggingProperties)) {\n WildFlySecurityManager.setPropertyPrivileged(\"org.jboss.boot.log.file\", bootLog.toAbsolutePath().toString());\n\n try (final InputStream in = Files.newInputStream(loggingProperties)) {\n // Attempt to get the configurator from the root logger\n Configurator configurator = embeddedLogContext.getAttachment(\"\", Configurator.ATTACHMENT_KEY);\n if (configurator == null) {\n configurator = new PropertyConfigurator(embeddedLogContext);\n final Configurator existing = embeddedLogContext.getLogger(\"\").attachIfAbsent(Configurator.ATTACHMENT_KEY, configurator);\n if (existing != null) {\n configurator = existing;\n }\n }\n configurator.configure(in);\n } catch (IOException e) {\n ctx.printLine(String.format(\"Unable to configure logging from configuration file %s. Reason: %s\", loggingProperties, e.getLocalizedMessage()));\n }\n }\n return embeddedLogContext;\n }", "public List<String> getPropertyPaths() {\n List<String> result = new ArrayList<String>();\n\n for (String property : this.values.names()) {\n if (!property.startsWith(\"$\")) {\n result.add(this.propertyToPath(property));\n }\n }\n\n return result;\n }", "public void sort(ChildTaskContainer container)\n {\n // Do we have any tasks?\n List<Task> tasks = container.getChildTasks();\n if (!tasks.isEmpty())\n {\n for (Task task : tasks)\n {\n //\n // Sort child activities\n //\n sort(task);\n\n //\n // Sort Order:\n // 1. Activities come first\n // 2. WBS come last\n // 3. Activities ordered by activity ID\n // 4. WBS ordered by ID\n //\n Collections.sort(tasks, new Comparator<Task>()\n {\n @Override public int compare(Task t1, Task t2)\n {\n boolean t1IsWbs = m_wbsTasks.contains(t1);\n boolean t2IsWbs = m_wbsTasks.contains(t2);\n\n // Both are WBS\n if (t1IsWbs && t2IsWbs)\n {\n return t1.getID().compareTo(t2.getID());\n }\n\n // Both are activities\n if (!t1IsWbs && !t2IsWbs)\n {\n String activityID1 = (String) t1.getCurrentValue(m_activityIDField);\n String activityID2 = (String) t2.getCurrentValue(m_activityIDField);\n\n if (activityID1 == null || activityID2 == null)\n {\n return (activityID1 == null && activityID2 == null ? 0 : (activityID1 == null ? 1 : -1));\n }\n\n return activityID1.compareTo(activityID2);\n }\n\n // One activity one WBS\n return t1IsWbs ? 1 : -1;\n }\n });\n }\n }\n }", "public static base_responses expire(nitro_service client, cacheobject resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheobject expireresources[] = new cacheobject[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\texpireresources[i] = new cacheobject();\n\t\t\t\texpireresources[i].locator = resources[i].locator;\n\t\t\t\texpireresources[i].url = resources[i].url;\n\t\t\t\texpireresources[i].host = resources[i].host;\n\t\t\t\texpireresources[i].port = resources[i].port;\n\t\t\t\texpireresources[i].groupname = resources[i].groupname;\n\t\t\t\texpireresources[i].httpmethod = resources[i].httpmethod;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, expireresources,\"expire\");\n\t\t}\n\t\treturn result;\n\t}", "public AT_Row setTextAlignment(TextAlignment textAlignment){\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setTextAlignment(textAlignment);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "private String safeToString(Object obj)\r\n\t{\r\n\t\tString toString = null;\r\n\t\tif (obj != null)\r\n\t\t{\r\n\t\t try\r\n\t\t {\r\n\t\t toString = obj.toString();\r\n\t\t }\r\n\t\t catch (Throwable ex)\r\n\t\t {\r\n\t\t toString = \"BAD toString() impl for \" + obj.getClass().getName();\r\n\t\t }\r\n\t\t}\r\n\t\treturn toString;\r\n\t}", "private void gobble(Iterator iter)\n {\n if (eatTheRest)\n {\n while (iter.hasNext())\n {\n tokens.add(iter.next());\n }\n }\n }", "public Map<TimestampMode, List<String>> getDefaultTimestampModes() {\n\n Map<TimestampMode, List<String>> result = new HashMap<TimestampMode, List<String>>();\n for (String resourcetype : m_defaultTimestampModes.keySet()) {\n TimestampMode mode = m_defaultTimestampModes.get(resourcetype);\n if (result.containsKey(mode)) {\n result.get(mode).add(resourcetype);\n } else {\n List<String> list = new ArrayList<String>();\n list.add(resourcetype);\n result.put(mode, list);\n }\n }\n return result;\n }" ]
This filter adds rounded corners to the image using the specified color as the background. @param radiusInner amount of pixels to use as radius. @param radiusOuter specifies the second value for the ellipse used for the radius. Use 0 for no value. @param color fill color for clipped region.
[ "public static String roundCorner(int radiusInner, int radiusOuter, int color) {\n if (radiusInner < 1) {\n throw new IllegalArgumentException(\"Radius must be greater than zero.\");\n }\n if (radiusOuter < 0) {\n throw new IllegalArgumentException(\"Outer radius must be greater than or equal to zero.\");\n }\n StringBuilder builder = new StringBuilder(FILTER_ROUND_CORNER).append(\"(\").append(radiusInner);\n if (radiusOuter > 0) {\n builder.append(\"|\").append(radiusOuter);\n }\n final int r = (color & 0xFF0000) >>> 16;\n final int g = (color & 0xFF00) >>> 8;\n final int b = color & 0xFF;\n return builder.append(\",\") //\n .append(r).append(\",\") //\n .append(g).append(\",\") //\n .append(b).append(\")\") //\n .toString();\n }" ]
[ "protected final ByteBuffer parseContent(ByteBuffer in) throws BaseExceptions.ParserException {\n if (contentComplete()) {\n throw new BaseExceptions.InvalidState(\"content already complete: \" + _endOfContent);\n } else {\n switch (_endOfContent) {\n case UNKNOWN_CONTENT:\n // This makes sense only for response parsing. Requests must always have\n // either Content-Length or Transfer-Encoding\n\n _endOfContent = EndOfContent.EOF_CONTENT;\n _contentLength = Long.MAX_VALUE; // Its up to the user to limit a body size\n return parseContent(in);\n\n case CONTENT_LENGTH:\n case EOF_CONTENT:\n return nonChunkedContent(in);\n\n case CHUNKED_CONTENT:\n return chunkedContent(in);\n\n default:\n throw new BaseExceptions.InvalidState(\"not implemented: \" + _endOfContent);\n }\n }\n }", "public static Transformers.ResourceIgnoredTransformationRegistry createServerIgnoredRegistry(final RequiredConfigurationHolder rc, final Transformers.ResourceIgnoredTransformationRegistry delegate) {\n return new Transformers.ResourceIgnoredTransformationRegistry() {\n @Override\n public boolean isResourceTransformationIgnored(PathAddress address) {\n final int length = address.size();\n if (length == 0) {\n return false;\n } else if (length >= 1) {\n if (delegate.isResourceTransformationIgnored(address)) {\n return true;\n }\n\n final PathElement element = address.getElement(0);\n final String type = element.getKey();\n switch (type) {\n case ModelDescriptionConstants.EXTENSION:\n // Don't ignore extensions for now\n return false;\n// if (local) {\n// return false; // Always include all local extensions\n// } else if (rc.getExtensions().contains(element.getValue())) {\n// return false;\n// }\n// break;\n case ModelDescriptionConstants.PROFILE:\n if (rc.getProfiles().contains(element.getValue())) {\n return false;\n }\n break;\n case ModelDescriptionConstants.SERVER_GROUP:\n if (rc.getServerGroups().contains(element.getValue())) {\n return false;\n }\n break;\n case ModelDescriptionConstants.SOCKET_BINDING_GROUP:\n if (rc.getSocketBindings().contains(element.getValue())) {\n return false;\n }\n break;\n }\n }\n return true;\n }\n };\n }", "public void populateContainer(Class<? extends FieldType> type, FieldContainer container, Integer id, byte[][] fixedData, Var2Data varData)\n {\n //System.out.println(container.getClass().getSimpleName()+\": \" + id);\n for (FieldItem item : m_map.values())\n {\n if (item.getType().getClass().equals(type))\n {\n //System.out.println(item.m_type);\n Object value = item.read(id, fixedData, varData);\n //System.out.println(item.m_type.getClass().getSimpleName() + \".\" + item.m_type + \": \" + value);\n container.set(item.getType(), value);\n }\n }\n }", "private RelationType getRelationType(Integer gpType)\n {\n RelationType result = null;\n if (gpType != null)\n {\n int index = NumberHelper.getInt(gpType);\n if (index > 0 && index < RELATION.length)\n {\n result = RELATION[index];\n }\n }\n\n if (result == null)\n {\n result = RelationType.FINISH_START;\n }\n\n return result;\n }", "private boolean setNextIterator()\r\n {\r\n boolean retval = false;\r\n // first, check if the activeIterator is null, and set it.\r\n if (m_activeIterator == null)\r\n {\r\n if (m_rsIterators.size() > 0)\r\n {\r\n m_activeIteratorIndex = 0;\r\n m_currentCursorPosition = 0;\r\n m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);\r\n }\r\n }\r\n else if (!m_activeIterator.hasNext())\r\n {\r\n if (m_rsIterators.size() > (m_activeIteratorIndex + 1))\r\n {\r\n // we still have iterators in the collection, move to the\r\n // next one, increment the counter, and set the active\r\n // iterator.\r\n m_activeIteratorIndex++;\r\n m_currentCursorPosition = 0;\r\n m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);\r\n retval = true;\r\n }\r\n }\r\n\r\n return retval;\r\n }", "public static cmpglobal_cmppolicy_binding[] get(nitro_service service) throws Exception{\n\t\tcmpglobal_cmppolicy_binding obj = new cmpglobal_cmppolicy_binding();\n\t\tcmpglobal_cmppolicy_binding response[] = (cmpglobal_cmppolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static<A, B, Z> Function2<A, B, Z> lift(Func2<A, B, Z> f) {\n\treturn bridge.lift(f);\n }", "public static boolean isOperationDefined(final ModelNode operation) {\n for (final AttributeDefinition def : ROOT_ATTRIBUTES) {\n if (operation.hasDefined(def.getName())) {\n return true;\n }\n }\n return false;\n }", "public void addNavigationalInformationForInverseSide() {\n\t\tif ( log.isTraceEnabled() ) {\n\t\t\tlog.trace( \"Adding inverse navigational information for entity: \" + MessageHelper.infoString( persister, id, persister.getFactory() ) );\n\t\t}\n\n\t\tfor ( int propertyIndex = 0; propertyIndex < persister.getEntityMetamodel().getPropertySpan(); propertyIndex++ ) {\n\t\t\tif ( persister.isPropertyOfTable( propertyIndex, tableIndex ) ) {\n\t\t\t\tAssociationKeyMetadata associationKeyMetadata = getInverseAssociationKeyMetadata( propertyIndex );\n\n\t\t\t\t// there is no inverse association for the given property\n\t\t\t\tif ( associationKeyMetadata == null ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tObject[] newColumnValues = LogicalPhysicalConverterHelper.getColumnValuesFromResultset(\n\t\t\t\t\t\tresultset,\n\t\t\t\t\t\tpersister.getPropertyColumnNames( propertyIndex )\n\t\t\t\t);\n\n\t\t\t\t//don't index null columns, this means no association\n\t\t\t\tif ( ! CollectionHelper.isEmptyOrContainsOnlyNull( ( newColumnValues ) ) ) {\n\t\t\t\t\taddNavigationalInformationForInverseSide( propertyIndex, associationKeyMetadata, newColumnValues );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}" ]
Converts a time in UTC to a gwt Date object which is in the timezone of the current browser. @return The Date corresponding to the time, adjusted for the timezone of the current browser. null if the specified time is null or represents a negative number.
[ "public static final Date utc2date(Long time) {\n\n // don't accept negative values\n if (time == null || time < 0) return null;\n \n // add the timezone offset\n time += timezoneOffsetMillis(new Date(time));\n\n return new Date(time);\n }" ]
[ "@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/delete\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> deleteClient(Model model,\n @RequestParam(\"profileIdentifier\") String profileIdentifier,\n @RequestParam(\"clientUUID\") String[] clientUUID) throws Exception {\n\n logger.info(\"Attempting to remove clients from the profile: \", profileIdentifier);\n logger.info(\"Attempting to remove the following clients: {}\", Arrays.toString(clientUUID));\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n for( int i = 0; i < clientUUID.length; i++ )\n {\n if (clientUUID[i].compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) == 0)\n throw new Exception(\"Default client cannot be deleted\");\n\n clientService.remove(profileId, clientUUID[i]);\n }\n\n valueHash.put(\"clients\", clientService.findAllClients(profileId));\n return valueHash;\n }", "public IExternalAccess getAgentsExternalAccess(String agent_name) {\n\n return cmsService.getExternalAccess(getAgentID(agent_name)).get(\n new ThreadSuspendable());\n }", "private int countCharsStart(final char ch, final boolean allowSpaces)\n {\n int count = 0;\n for (int i = 0; i < this.value.length(); i++)\n {\n final char c = this.value.charAt(i);\n if (c == ' ' && allowSpaces)\n {\n continue;\n }\n if (c == ch)\n {\n count++;\n }\n else\n {\n break;\n }\n }\n return count;\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 }", "public void recordResourceRequestQueueLength(SocketDestination dest, int queueLength) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordResourceRequestQueueLength(null, queueLength);\n recordResourceRequestQueueLength(null, queueLength);\n } else {\n this.resourceRequestQueueLengthHistogram.insert(queueLength);\n checkMonitoringInterval();\n }\n }", "private String toSQLPattern(String attribute) {\n String pattern = attribute.replace(\"*\", \"%\");\n if (!pattern.startsWith(\"%\")) {\n pattern = \"%\" + pattern;\n }\n if (!pattern.endsWith(\"%\")) {\n pattern = pattern.concat(\"%\");\n }\n return pattern;\n }", "protected void putConnectionBackInPartition(ConnectionHandle connectionHandle) throws SQLException {\r\n\r\n\t\tif (this.cachedPoolStrategy && ((CachedConnectionStrategy)this.connectionStrategy).tlConnections.dumbGet().getValue()){\r\n\t\t\tconnectionHandle.logicallyClosed.set(true);\r\n\t\t\t((CachedConnectionStrategy)this.connectionStrategy).tlConnections.set(new AbstractMap.SimpleEntry<ConnectionHandle, Boolean>(connectionHandle, false));\r\n\t\t} else {\r\n\t\t\tBlockingQueue<ConnectionHandle> queue = connectionHandle.getOriginatingPartition().getFreeConnections();\r\n\t\t\t\tif (!queue.offer(connectionHandle)){ // this shouldn't fail\r\n\t\t\t\t\tconnectionHandle.internalClose();\r\n\t\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t}", "private void debugLogEnd(String operationType,\n Long OriginTimeInMs,\n Long RequestStartTimeInMs,\n Long ResponseReceivedTimeInMs,\n String keyString,\n int numVectorClockEntries) {\n long durationInMs = ResponseReceivedTimeInMs - RequestStartTimeInMs;\n logger.debug(\"Received a response from voldemort server for Operation Type: \"\n + operationType\n + \" , For key(s): \"\n + keyString\n + \" , Store: \"\n + this.storeName\n + \" , Origin time of request (in ms): \"\n + OriginTimeInMs\n + \" , Response received at time (in ms): \"\n + ResponseReceivedTimeInMs\n + \" . Request sent at(in ms): \"\n + RequestStartTimeInMs\n + \" , Num vector clock entries: \"\n + numVectorClockEntries\n + \" , Duration from CoordinatorFatClient back to CoordinatorFatClient(in ms): \"\n + durationInMs);\n }", "public static List<Map<String, Object>> listify(ObjectMapper mapper, Object source) {\n return (List<Map<String, Object>>) collectify(mapper, source, List.class);\n }" ]
Downloads a part of this file's contents, starting at rangeStart and stopping at rangeEnd. @param output the stream to where the file will be written. @param rangeStart the byte offset at which to start the download. @param rangeEnd the byte offset at which to stop the download.
[ "public void downloadRange(OutputStream output, long rangeStart, long rangeEnd) {\n this.downloadRange(output, rangeStart, rangeEnd, null);\n }" ]
[ "public static snmpalarm[] get(nitro_service service) throws Exception{\n\t\tsnmpalarm obj = new snmpalarm();\n\t\tsnmpalarm[] response = (snmpalarm[])obj.get_resources(service);\n\t\treturn response;\n\t}", "void apply() {\n final FlushLog log = new FlushLog();\n store.logOperations(txn, log);\n final BlobVault blobVault = store.getBlobVault();\n if (blobVault.requiresTxn()) {\n try {\n blobVault.flushBlobs(blobStreams, blobFiles, deferredBlobsToDelete, txn);\n } catch (Exception e) {\n // out of disk space not expected there\n throw ExodusException.toEntityStoreException(e);\n }\n }\n txn.setCommitHook(new Runnable() {\n @Override\n public void run() {\n log.flushed();\n final EntityIterableCacheAdapterMutable cache = PersistentStoreTransaction.this.mutableCache;\n if (cache != null) { // mutableCache can be null if only blobs are modified\n applyAtomicCaches(cache);\n }\n }\n });\n }", "private InputValue getInputValue(FormInput input) {\n\n\t\t/* Get the DOM element from Selenium. */\n\t\tWebElement inputElement = browser.getWebElement(input.getIdentification());\n\n\t\tswitch (input.getType()) {\n\t\t\tcase TEXT:\n\t\t\tcase PASSWORD:\n\t\t\tcase HIDDEN:\n\t\t\tcase SELECT:\n\t\t\tcase TEXTAREA:\n\t\t\t\treturn new InputValue(inputElement.getAttribute(\"value\"));\n\t\t\tcase RADIO:\n\t\t\tcase CHECKBOX:\n\t\t\tdefault:\n\t\t\t\tString value = inputElement.getAttribute(\"value\");\n\t\t\t\tBoolean checked = inputElement.isSelected();\n\t\t\t\treturn new InputValue(value, checked);\n\t\t}\n\n\t}", "public static AT_Row createRule(TableRowType type, TableRowStyle style){\r\n\t\tValidate.notNull(type);\r\n\t\tValidate.validState(type!=TableRowType.UNKNOWN);\r\n\t\tValidate.validState(type!=TableRowType.CONTENT);\r\n\t\tValidate.notNull(style);\r\n\t\tValidate.validState(style!=TableRowStyle.UNKNOWN);\r\n\r\n\t\treturn new AT_Row(){\r\n\t\t\t@Override\r\n\t\t\tpublic TableRowType getType(){\r\n\t\t\t\treturn type;\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic TableRowStyle getStyle(){\r\n\t\t\t\treturn style;\r\n\t\t\t}\r\n\t\t};\r\n\t}", "public String getSQL92LikePattern() throws IllegalArgumentException {\n\t\tif (escape.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> escape char should be of length exactly 1\");\n\t\t}\n\t\tif (wildcardSingle.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> wildcardSingle char should be of length exactly 1\");\n\t\t}\n\t\tif (wildcardMulti.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> wildcardMulti char should be of length exactly 1\");\n\t\t}\n\t\treturn LikeFilterImpl.convertToSQL92(escape.charAt(0), wildcardMulti.charAt(0), wildcardSingle.charAt(0),\n\t\t\t\tisMatchingCase(), pattern);\n\t}", "public void enqueue(SerialMessage serialMessage) {\n\t\tthis.sendQueue.add(serialMessage);\n\t\tlogger.debug(\"Enqueueing message. Queue length = {}\", this.sendQueue.size());\n\t}", "public void fireCalendarWrittenEvent(ProjectCalendar calendar)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.calendarWritten(calendar);\n }\n }\n }", "private void toCorrectDateWithDay(Calendar date, WeekOfMonth week) {\n\n date.set(Calendar.DAY_OF_MONTH, 1);\n int daysToFirstWeekDayMatch = ((m_weekDay.toInt() + I_CmsSerialDateValue.NUM_OF_WEEKDAYS)\n - (date.get(Calendar.DAY_OF_WEEK))) % I_CmsSerialDateValue.NUM_OF_WEEKDAYS;\n date.add(Calendar.DAY_OF_MONTH, daysToFirstWeekDayMatch);\n int wouldBeDayOfMonth = date.get(Calendar.DAY_OF_MONTH)\n + ((week.ordinal()) * I_CmsSerialDateValue.NUM_OF_WEEKDAYS);\n if (wouldBeDayOfMonth > date.getActualMaximum(Calendar.DAY_OF_MONTH)) {\n date.set(Calendar.DAY_OF_MONTH, wouldBeDayOfMonth - I_CmsSerialDateValue.NUM_OF_WEEKDAYS);\n } else {\n date.set(Calendar.DAY_OF_MONTH, wouldBeDayOfMonth);\n }\n\n }", "private void writeClassData() {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"classes.csv\"))) {\n\n\t\t\tout.println(\"Id\" + \",Label\" + \",Description\" + \",URL\" + \",Image\"\n\t\t\t\t\t+ \",Number of direct instances\"\n\t\t\t\t\t+ \",Number of direct subclasses\" + \",Direct superclasses\"\n\t\t\t\t\t+ \",All superclasses\" + \",Related properties\");\n\n\t\t\tList<Entry<EntityIdValue, ClassRecord>> list = new ArrayList<>(\n\t\t\t\t\tthis.classRecords.entrySet());\n\t\t\tCollections.sort(list, new ClassUsageRecordComparator());\n\t\t\tfor (Entry<EntityIdValue, ClassRecord> entry : list) {\n\t\t\t\tif (entry.getValue().itemCount > 0\n\t\t\t\t\t\t|| entry.getValue().subclassCount > 0) {\n\t\t\t\t\tprintClassRecord(out, entry.getValue(), entry.getKey());\n\t\t\t\t}\n\t\t\t}\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}" ]
Process schedule options from SCHEDOPTIONS. This table only seems to exist in XER files, not P6 databases.
[ "private void processScheduleOptions()\n {\n List<Row> rows = getRows(\"schedoptions\", \"proj_id\", m_projectID);\n if (rows.isEmpty() == false)\n {\n Row row = rows.get(0);\n Map<String, Object> customProperties = new HashMap<String, Object>();\n customProperties.put(\"LagCalendar\", row.getString(\"sched_calendar_on_relationship_lag\"));\n customProperties.put(\"RetainedLogic\", Boolean.valueOf(row.getBoolean(\"sched_retained_logic\")));\n customProperties.put(\"ProgressOverride\", Boolean.valueOf(row.getBoolean(\"sched_progress_override\")));\n customProperties.put(\"IgnoreOtherProjectRelationships\", row.getString(\"sched_outer_depend_type\"));\n customProperties.put(\"StartToStartLagCalculationType\", Boolean.valueOf(row.getBoolean(\"sched_lag_early_start_flag\")));\n m_reader.getProject().getProjectProperties().setCustomProperties(customProperties);\n }\n }" ]
[ "public CollectionRequest<Team> findByOrganization(String organization) {\n \n String path = String.format(\"/organizations/%s/teams\", organization);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }", "public void fire(TestCaseStartedEvent event) {\n //init root step in parent thread if needed\n stepStorage.get();\n\n TestCaseResult testCase = testCaseStorage.get();\n event.process(testCase);\n\n synchronized (TEST_SUITE_ADD_CHILD_LOCK) {\n testSuiteStorage.get(event.getSuiteUid()).getTestCases().add(testCase);\n }\n\n notifier.fire(event);\n }", "private void onShow() {\n\n if (m_detailsFieldset != null) {\n m_detailsFieldset.getContentPanel().getElement().getStyle().setPropertyPx(\n \"maxHeight\",\n getAvailableHeight(m_messageWidget.getOffsetHeight()));\n }\n }", "private void processPredecessors()\n {\n for (Map.Entry<Task, List<MapRow>> entry : m_predecessorMap.entrySet())\n {\n Task task = entry.getKey();\n List<MapRow> predecessors = entry.getValue();\n for (MapRow predecessor : predecessors)\n {\n processPredecessor(task, predecessor);\n }\n }\n }", "protected void restoreAutoCommitState()\r\n {\r\n try\r\n {\r\n if(!broker.isManaged())\r\n {\r\n if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE\r\n && originalAutoCommitState == true && con != null && !con.isClosed())\r\n {\r\n platform.changeAutoCommitState(jcd, con, true);\r\n }\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled()) log.debug(\r\n \"Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n // should never be reached\r\n throw new OJBRuntimeException(\"Restore of connection autocommit state failed\", e);\r\n }\r\n }", "private void flushHotCacheSlot(SlotReference slot) {\n // Iterate over a copy to avoid concurrent modification issues\n for (Map.Entry<DeckReference, TrackMetadata> entry : new HashMap<DeckReference,TrackMetadata>(hotCache).entrySet()) {\n if (slot == SlotReference.getSlotReference(entry.getValue().trackReference)) {\n logger.debug(\"Evicting cached metadata in response to unmount report {}\", entry.getValue());\n hotCache.remove(entry.getKey());\n }\n }\n }", "public Date getDate(String path) throws ParseException {\n return BoxDateFormat.parse(this.getValue(path).asString());\n }", "public static HorizontalBandAlignment buildAligment(byte aligment){\n\t\tif (aligment == RIGHT.getAlignment())\n\t\t\treturn RIGHT;\n\t\telse if (aligment == LEFT.getAlignment())\n\t\t\treturn LEFT;\n\t\telse if (aligment == CENTER.getAlignment())\n\t\t\treturn CENTER;\n\n\t\treturn LEFT;\n\t}", "@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}" ]
Validate arguments.
[ "private void validateArguments() throws BuildException {\n Path tempDir = getTempDir();\n\n if (tempDir == null) {\n throw new BuildException(\"Temporary directory cannot be null.\");\n }\n \n if (Files.exists(tempDir)) {\n if (!Files.isDirectory(tempDir)) {\n throw new BuildException(\"Temporary directory is not a folder: \" + tempDir.toAbsolutePath());\n }\n } else {\n try {\n Files.createDirectories(tempDir);\n } catch (IOException e) {\n throw new BuildException(\"Failed to create temporary folder: \" + tempDir, e);\n }\n }\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 OpenShiftAssistantTemplate parameter(String name, String value) {\n parameterValues.put(name, value);\n return this;\n }", "static ParsedHost validateHostImpl(HostName fromHost) throws HostNameException {\n\t\tfinal String str = fromHost.toString();\n\t\tHostNameParameters validationOptions = fromHost.getValidationOptions();\n\t\treturn validateHost(fromHost, str, validationOptions);\n\t}", "public void populateContainer(Class<? extends FieldType> type, FieldContainer container, Integer id, byte[][] fixedData, Var2Data varData)\n {\n //System.out.println(container.getClass().getSimpleName()+\": \" + id);\n for (FieldItem item : m_map.values())\n {\n if (item.getType().getClass().equals(type))\n {\n //System.out.println(item.m_type);\n Object value = item.read(id, fixedData, varData);\n //System.out.println(item.m_type.getClass().getSimpleName() + \".\" + item.m_type + \": \" + value);\n container.set(item.getType(), value);\n }\n }\n }", "private void initStyleGenerators() {\n\n if (m_model.hasMasterMode()) {\n m_styleGenerators.put(\n CmsMessageBundleEditorTypes.EditMode.MASTER,\n new CmsMessageBundleEditorTypes.TranslateTableCellStyleGenerator(\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.MASTER)));\n }\n m_styleGenerators.put(\n CmsMessageBundleEditorTypes.EditMode.DEFAULT,\n new CmsMessageBundleEditorTypes.TranslateTableCellStyleGenerator(\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.DEFAULT)));\n\n }", "private static void validatePseudoScopedBean(Bean<?> bean, BeanManagerImpl beanManager) {\n if (bean.getInjectionPoints().isEmpty()) {\n // Skip validation if there are no injection points (e.g. for classes which are not intended to be used as beans)\n return;\n }\n reallyValidatePseudoScopedBean(bean, beanManager, new LinkedHashSet<Object>(), new HashSet<Bean<?>>());\n }", "@Override\n public JulianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "@Override\n\tpublic IPAddress toAddress() throws UnknownHostException, HostNameException {\n\t\tIPAddress addr = resolvedAddress;\n\t\tif(addr == null && !resolvedIsNull) {\n\t\t\t//note that validation handles empty address resolution\n\t\t\tvalidate();\n\t\t\tsynchronized(this) {\n\t\t\t\taddr = resolvedAddress;\n\t\t\t\tif(addr == null && !resolvedIsNull) {\n\t\t\t\t\tif(parsedHost.isAddressString()) {\n\t\t\t\t\t\taddr = parsedHost.asAddress();\n\t\t\t\t\t\tresolvedIsNull = (addr == null);\n\t\t\t\t\t\t//note there is no need to apply prefix or mask here, it would have been applied to the address already\n\t\t\t\t\t} else {\n\t\t\t\t\t\tString strHost = parsedHost.getHost();\n\t\t\t\t\t\tif(strHost.length() == 0 && !validationOptions.emptyIsLoopback) {\n\t\t\t\t\t\t\taddr = null;\n\t\t\t\t\t\t\tresolvedIsNull = true;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t//Note we do not set resolvedIsNull, so we will attempt to resolve again if the previous attempt threw an exception\n\t\t\t\t\t\t\tInetAddress inetAddress = InetAddress.getByName(strHost);\n\t\t\t\t\t\t\tbyte bytes[] = inetAddress.getAddress();\n\t\t\t\t\t\t\tInteger networkPrefixLength = parsedHost.getNetworkPrefixLength();\n\t\t\t\t\t\t\tif(networkPrefixLength == null) {\n\t\t\t\t\t\t\t\tIPAddress mask = parsedHost.getMask();\n\t\t\t\t\t\t\t\tif(mask != null) {\n\t\t\t\t\t\t\t\t\tbyte maskBytes[] = mask.getBytes();\n\t\t\t\t\t\t\t\t\tif(maskBytes.length != bytes.length) {\n\t\t\t\t\t\t\t\t\t\tthrow new HostNameException(host, \"ipaddress.error.ipMismatch\");\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tfor(int i = 0; i < bytes.length; i++) {\n\t\t\t\t\t\t\t\t\t\tbytes[i] &= maskBytes[i];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tnetworkPrefixLength = mask.getBlockMaskPrefixLength(true);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tIPAddressStringParameters addressParams = validationOptions.addressOptions;\n\t\t\t\t\t\t\tif(bytes.length == IPv6Address.BYTE_COUNT) {\n\t\t\t\t\t\t\t\tIPv6AddressCreator creator = addressParams.getIPv6Parameters().getNetwork().getAddressCreator();\n\t\t\t\t\t\t\t\taddr = creator.createAddressInternal(bytes, networkPrefixLength, null, this); /* address creation */\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tIPv4AddressCreator creator = addressParams.getIPv4Parameters().getNetwork().getAddressCreator();\n\t\t\t\t\t\t\t\taddr = creator.createAddressInternal(bytes, networkPrefixLength, this); /* address creation */\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tresolvedAddress = addr;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn addr;\n\t}", "private String formatAccrueType(AccrueType type)\n {\n return (type == null ? null : LocaleData.getStringArray(m_locale, LocaleData.ACCRUE_TYPES)[type.getValue() - 1]);\n }" ]
Use this API to fetch authenticationradiuspolicy_vpnvserver_binding resources of given name .
[ "public static authenticationradiuspolicy_vpnvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiuspolicy_vpnvserver_binding obj = new authenticationradiuspolicy_vpnvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationradiuspolicy_vpnvserver_binding response[] = (authenticationradiuspolicy_vpnvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public void init(final MultivaluedMap<String, String> queryParameters) {\n final String scopeCompileParam = queryParameters.getFirst(ServerAPI.SCOPE_COMPILE_PARAM);\n if(scopeCompileParam != null){\n this.scopeComp = Boolean.valueOf(scopeCompileParam);\n }\n final String scopeProvidedParam = queryParameters.getFirst(ServerAPI.SCOPE_PROVIDED_PARAM);\n if(scopeProvidedParam != null){\n this.scopePro = Boolean.valueOf(scopeProvidedParam);\n }\n final String scopeRuntimeParam = queryParameters.getFirst(ServerAPI.SCOPE_RUNTIME_PARAM);\n if(scopeRuntimeParam != null){\n this.scopeRun = Boolean.valueOf(scopeRuntimeParam);\n }\n final String scopeTestParam = queryParameters.getFirst(ServerAPI.SCOPE_TEST_PARAM);\n if(scopeTestParam != null){\n this.scopeTest = Boolean.valueOf(scopeTestParam);\n }\n }", "public static void append(Path self, Object text) throws IOException {\n Writer writer = null;\n try {\n writer = new OutputStreamWriter(Files.newOutputStream(self, CREATE, APPEND), Charset.defaultCharset());\n InvokerHelper.write(writer, text);\n writer.flush();\n\n Writer temp = writer;\n writer = null;\n temp.close();\n } finally {\n closeWithWarning(writer);\n }\n }", "public static lbvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_cachepolicy_binding obj = new lbvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_cachepolicy_binding response[] = (lbvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "protected void putConnectionBackInPartition(ConnectionHandle connectionHandle) throws SQLException {\r\n\r\n\t\tif (this.cachedPoolStrategy && ((CachedConnectionStrategy)this.connectionStrategy).tlConnections.dumbGet().getValue()){\r\n\t\t\tconnectionHandle.logicallyClosed.set(true);\r\n\t\t\t((CachedConnectionStrategy)this.connectionStrategy).tlConnections.set(new AbstractMap.SimpleEntry<ConnectionHandle, Boolean>(connectionHandle, false));\r\n\t\t} else {\r\n\t\t\tBlockingQueue<ConnectionHandle> queue = connectionHandle.getOriginatingPartition().getFreeConnections();\r\n\t\t\t\tif (!queue.offer(connectionHandle)){ // this shouldn't fail\r\n\t\t\t\t\tconnectionHandle.internalClose();\r\n\t\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t}", "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 }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushInstallReferrer(Intent intent) {\n try {\n final Bundle extras = intent.getExtras();\n // Preliminary checks\n if (extras == null || !extras.containsKey(\"referrer\")) {\n return;\n }\n final String url;\n try {\n url = URLDecoder.decode(extras.getString(\"referrer\"), \"UTF-8\");\n\n getConfigLogger().verbose(getAccountId(), \"Referrer received: \" + url);\n } catch (Throwable e) {\n // Could not decode\n return;\n }\n if (url == null) {\n return;\n }\n int now = (int) (System.currentTimeMillis() / 1000);\n\n if (installReferrerMap.containsKey(url) && now - installReferrerMap.get(url) < 10) {\n getConfigLogger().verbose(getAccountId(),\"Skipping install referrer due to duplicate within 10 seconds\");\n return;\n }\n\n installReferrerMap.put(url, now);\n\n Uri uri = Uri.parse(\"wzrk://track?install=true&\" + url);\n\n pushDeepLink(uri, true);\n } catch (Throwable t) {\n // no-op\n }\n }", "public void setMatrix(int[] matrix) {\n\t\tthis.matrix = matrix;\n\t\tsum = 0;\n\t\tfor (int i = 0; i < matrix.length; i++)\n\t\t\tsum += matrix[i];\n\t}", "public ClassificationModel attachLink(ClassificationModel classificationModel, LinkModel linkModel)\n {\n for (LinkModel existing : classificationModel.getLinks())\n {\n if (StringUtils.equals(existing.getLink(), linkModel.getLink()))\n {\n return classificationModel;\n }\n }\n classificationModel.addLink(linkModel);\n return classificationModel;\n }", "public static final String printDate(Date value)\n {\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }" ]
Internal method which performs the authenticated request by preparing the auth request with the provided auth info and request.
[ "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 }" ]
[ "public Where<T, ID> isNull(String columnName) throws SQLException {\n\t\taddClause(new IsNull(columnName, findColumnFieldType(columnName)));\n\t\treturn this;\n\t}", "public void execute(CommandHandler handler,\n int timeout,\n TimeUnit unit) throws\n CommandLineException,\n InterruptedException, ExecutionException, TimeoutException {\n ExecutableBuilder builder = new ExecutableBuilder() {\n CommandContext c = newTimeoutCommandContext(ctx);\n @Override\n public Executable build() {\n return () -> {\n handler.handle(c);\n };\n }\n\n @Override\n public CommandContext getCommandContext() {\n return c;\n }\n };\n execute(builder, timeout, unit);\n }", "public List<String> getCorporateGroupIds(final String organizationId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n return dbOrganization.getCorporateGroupIdPrefixes();\n }", "@NonNull\n public static String placeholders(final int numberOfPlaceholders) {\n if (numberOfPlaceholders == 1) {\n return \"?\"; // fffast\n } else if (numberOfPlaceholders == 0) {\n return \"\";\n } else if (numberOfPlaceholders < 0) {\n throw new IllegalArgumentException(\"numberOfPlaceholders must be >= 0, but was = \" + numberOfPlaceholders);\n }\n\n final StringBuilder stringBuilder = new StringBuilder((numberOfPlaceholders * 2) - 1);\n\n for (int i = 0; i < numberOfPlaceholders; i++) {\n stringBuilder.append('?');\n\n if (i != numberOfPlaceholders - 1) {\n stringBuilder.append(',');\n }\n }\n\n return stringBuilder.toString();\n }", "public Object invokeMethod(String name, Object args) {\n Object val = null;\n if (args != null && Object[].class.isAssignableFrom(args.getClass())) {\n Object[] arr = (Object[]) args;\n\n if (arr.length == 1) {\n val = arr[0];\n } else if (arr.length == 2 && arr[0] instanceof Collection && arr[1] instanceof Closure) {\n Closure<?> closure = (Closure<?>) arr[1];\n Iterator<?> iterator = ((Collection) arr[0]).iterator();\n List<Object> list = new ArrayList<Object>();\n while (iterator.hasNext()) {\n list.add(curryDelegateAndGetContent(closure, iterator.next()));\n }\n val = list;\n } else {\n val = Arrays.asList(arr);\n }\n }\n content.put(name, val);\n\n return val;\n }", "public ProjectCalendar getDefaultCalendar()\n {\n String calendarName = m_properties.getDefaultCalendarName();\n ProjectCalendar calendar = getCalendarByName(calendarName);\n if (calendar == null)\n {\n if (m_calendars.isEmpty())\n {\n calendar = addDefaultBaseCalendar();\n }\n else\n {\n calendar = m_calendars.get(0);\n }\n }\n return calendar;\n }", "@Override\n public View getView(int position, View convertView, ViewGroup parent) {\n Country country = getItem(position);\n\n if (convertView == null) {\n convertView = new ImageView(getContext());\n }\n\n ((ImageView) convertView).setImageResource(getFlagResource(country));\n\n return convertView;\n }", "protected String getUserDefinedFieldName(String field) {\n int index = field.indexOf('-');\n char letter = getUserDefinedFieldLetter();\n\n for (int i = 0; i < index; ++i) {\n if (field.charAt(i) == letter) {\n return field.substring(index + 1);\n }\n }\n\n return null;\n }", "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 }" ]
Handles the response of the getVersion request. @param incomingMessage the response message to process.
[ "private void handleGetVersionResponse(SerialMessage incomingMessage) {\n\t\tthis.ZWaveLibraryType = incomingMessage.getMessagePayloadByte(12);\n\t\tthis.zWaveVersion = new String(ArrayUtils.subarray(incomingMessage.getMessagePayload(), 0, 11));\n\t\tlogger.debug(String.format(\"Got MessageGetVersion response. Version = %s, Library Type = 0x%02X\", zWaveVersion, ZWaveLibraryType));\n\t}" ]
[ "public void trace(String msg) {\n\t\tlogIfEnabled(Level.TRACE, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);\n\t}", "@Override\n public List<Revision> getMatrixHistory(final int start, final int limit) throws StoreException {\n return delegate.getMatrixHistory(start, limit);\n }", "public List<Class<?>> scanClasses(Predicate<String> filter)\n {\n List<Class<?>> discoveredClasses = new ArrayList<>(128);\n\n // For each Forge addon...\n for (Addon addon : furnace.getAddonRegistry().getAddons(AddonFilters.allStarted()))\n {\n List<String> discoveredFileNames = filterAddonResources(addon, filter);\n\n // Then try to load the classes.\n for (String discoveredFilename : discoveredFileNames)\n {\n String clsName = PathUtil.classFilePathToClassname(discoveredFilename);\n try\n {\n Class<?> clazz = addon.getClassLoader().loadClass(clsName);\n discoveredClasses.add(clazz);\n }\n catch (ClassNotFoundException ex)\n {\n LOG.log(Level.WARNING, \"Failed to load class for name '\" + clsName + \"':\\n\" + ex.getMessage(), ex);\n }\n }\n }\n return discoveredClasses;\n }", "public Map<AssociationKey, Map<RowKey, Map<String, Object>>> getAssociationsMap() {\n\t\treturn Collections.unmodifiableMap( associationsKeyValueStorage );\n\t}", "public T addContentModification(final ContentModification modification) {\n if (itemFilter.accepts(modification.getItem())) {\n internalAddModification(modification);\n }\n return returnThis();\n }", "protected void countStatements(UsageStatistics usageStatistics,\n\t\t\tStatementDocument statementDocument) {\n\t\t// Count Statement data:\n\t\tfor (StatementGroup sg : statementDocument.getStatementGroups()) {\n\t\t\t// Count Statements:\n\t\t\tusageStatistics.countStatements += sg.size();\n\n\t\t\t// Count uses of properties in Statements:\n\t\t\tcountPropertyMain(usageStatistics, sg.getProperty(), sg.size());\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tfor (SnakGroup q : s.getQualifiers()) {\n\t\t\t\t\tcountPropertyQualifier(usageStatistics, q.getProperty(), q.size());\n\t\t\t\t}\n\t\t\t\tfor (Reference r : s.getReferences()) {\n\t\t\t\t\tusageStatistics.countReferencedStatements++;\n\t\t\t\t\tfor (SnakGroup snakGroup : r.getSnakGroups()) {\n\t\t\t\t\t\tcountPropertyReference(usageStatistics,\n\t\t\t\t\t\t\t\tsnakGroup.getProperty(), snakGroup.size());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "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 ClosableIterator<Tuple> callStoredProcedure(EmbeddedCacheManager embeddedCacheManager, String storedProcedureName, ProcedureQueryParameters queryParameters, ClassLoaderService classLoaderService ) {\n\t\tvalidate( queryParameters );\n\t\tCache<String, String> cache = embeddedCacheManager.getCache( STORED_PROCEDURES_CACHE_NAME, true );\n\t\tString className = cache.getOrDefault( storedProcedureName, storedProcedureName );\n\t\tCallable<?> callable = instantiate( storedProcedureName, className, classLoaderService );\n\t\tsetParams( storedProcedureName, queryParameters, callable );\n\t\tObject res = execute( storedProcedureName, embeddedCacheManager, callable );\n\t\treturn extractResultSet( storedProcedureName, res );\n\t}", "private void readCalendars(Document cdp)\n {\n for (Calendar calendar : cdp.getCalendars().getCalendar())\n {\n readCalendar(calendar);\n }\n\n for (Calendar calendar : cdp.getCalendars().getCalendar())\n {\n ProjectCalendar child = m_calendarMap.get(calendar.getID());\n ProjectCalendar parent = m_calendarMap.get(calendar.getBaseCalendarID());\n if (parent == null)\n {\n m_projectFile.setDefaultCalendar(child);\n }\n else\n {\n child.setParent(parent);\n }\n }\n }" ]
Adds a JSON string representing to the DB. @param obj the JSON to record @return the number of rows in the table, or DB_OUT_OF_MEMORY_ERROR/DB_UPDATE_ERROR
[ "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 }" ]
[ "public static rsskeytype get(nitro_service service) throws Exception{\n\t\trsskeytype obj = new rsskeytype();\n\t\trsskeytype[] response = (rsskeytype[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "@Override public void setID(Integer val)\n {\n ProjectFile parent = getParentFile();\n Integer previous = getID();\n if (previous != null)\n {\n parent.getResources().unmapID(previous);\n }\n parent.getResources().mapID(val, this);\n\n set(ResourceField.ID, val);\n }", "public static base_responses update(nitro_service client, autoscaleaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleaction updateresources[] = new autoscaleaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new autoscaleaction();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].profilename = resources[i].profilename;\n\t\t\t\tupdateresources[i].parameters = resources[i].parameters;\n\t\t\t\tupdateresources[i].vmdestroygraceperiod = resources[i].vmdestroygraceperiod;\n\t\t\t\tupdateresources[i].quiettime = resources[i].quiettime;\n\t\t\t\tupdateresources[i].vserver = resources[i].vserver;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public boolean hasProperties(Set<PropertyKey> keys) {\n for (PropertyKey key : keys) {\n if (null == getProperty(key.m_key)) {\n return false;\n }\n }\n \n return true;\n }", "public static Polygon calculateBounds(final MapfishMapContext context) {\n double rotation = context.getRootContext().getRotation();\n ReferencedEnvelope env = context.getRootContext().toReferencedEnvelope();\n\n Coordinate centre = env.centre();\n AffineTransform rotateInstance = AffineTransform.getRotateInstance(rotation, centre.x, centre.y);\n\n double[] dstPts = new double[8];\n double[] srcPts = {\n env.getMinX(), env.getMinY(), env.getMinX(), env.getMaxY(),\n env.getMaxX(), env.getMaxY(), env.getMaxX(), env.getMinY()\n };\n\n rotateInstance.transform(srcPts, 0, dstPts, 0, 4);\n\n return new GeometryFactory().createPolygon(new Coordinate[]{\n new Coordinate(dstPts[0], dstPts[1]), new Coordinate(dstPts[2], dstPts[3]),\n new Coordinate(dstPts[4], dstPts[5]), new Coordinate(dstPts[6], dstPts[7]),\n new Coordinate(dstPts[0], dstPts[1])\n });\n }", "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 }", "private void processDependencies()\n {\n Set<Task> tasksWithBars = new HashSet<Task>();\n FastTrackTable table = m_data.getTable(FastTrackTableType.ACTBARS);\n for (MapRow row : table)\n {\n Task task = m_project.getTaskByUniqueID(row.getInteger(ActBarField._ACTIVITY));\n if (task == null || tasksWithBars.contains(task))\n {\n continue;\n }\n tasksWithBars.add(task);\n\n String predecessors = row.getString(ActBarField.PREDECESSORS);\n if (predecessors == null || predecessors.isEmpty())\n {\n continue;\n }\n\n for (String predecessor : predecessors.split(\", \"))\n {\n Matcher matcher = RELATION_REGEX.matcher(predecessor);\n matcher.matches();\n\n Integer id = Integer.valueOf(matcher.group(1));\n RelationType type = RELATION_TYPE_MAP.get(matcher.group(3));\n if (type == null)\n {\n type = RelationType.FINISH_START;\n }\n\n String sign = matcher.group(4);\n double lag = NumberHelper.getDouble(matcher.group(5));\n if (\"-\".equals(sign))\n {\n lag = -lag;\n }\n\n Task targetTask = m_project.getTaskByID(id);\n if (targetTask != null)\n {\n Duration lagDuration = Duration.getInstance(lag, m_data.getDurationTimeUnit());\n Relation relation = task.addPredecessor(targetTask, type, lagDuration);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }\n }", "private static JSONObject parseStencilSet(StencilSet stencilSet) throws JSONException {\n if (stencilSet != null) {\n JSONObject stencilSetObject = new JSONObject();\n\n stencilSetObject.put(\"url\",\n stencilSet.getUrl().toString());\n stencilSetObject.put(\"namespace\",\n stencilSet.getNamespace().toString());\n\n return stencilSetObject;\n }\n\n return new JSONObject();\n }", "public static DMatrixRMaj[] splitIntoVectors(DMatrix1Row A , boolean column )\n {\n int w = column ? A.numCols : A.numRows;\n\n int M = column ? A.numRows : 1;\n int N = column ? 1 : A.numCols;\n\n int o = Math.max(M,N);\n\n DMatrixRMaj[] ret = new DMatrixRMaj[w];\n\n for( int i = 0; i < w; i++ ) {\n DMatrixRMaj a = new DMatrixRMaj(M,N);\n\n if( column )\n subvector(A,0,i,o,false,0,a);\n else\n subvector(A,i,0,o,true,0,a);\n\n ret[i] = a;\n }\n\n return ret;\n }" ]
Gets the value of a global editor configuration parameter. @param cms the CMS context @param editor the editor name @param param the name of the parameter @return the editor parameter value
[ "public String getEditorParameter(CmsObject cms, String editor, String param) {\n\n String path = OpenCms.getSystemInfo().getConfigFilePath(cms, \"editors/\" + editor + \".properties\");\n CmsVfsMemoryObjectCache cache = CmsVfsMemoryObjectCache.getVfsMemoryObjectCache();\n CmsParameterConfiguration config = (CmsParameterConfiguration)cache.getCachedObject(cms, path);\n if (config == null) {\n try {\n CmsFile file = cms.readFile(path);\n try (ByteArrayInputStream input = new ByteArrayInputStream(file.getContents())) {\n config = new CmsParameterConfiguration(input); // Uses ISO-8859-1, should be OK for config parameters\n cache.putCachedObject(cms, path, config);\n }\n } catch (CmsVfsResourceNotFoundException e) {\n return null;\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n return null;\n }\n }\n return config.getString(param, null);\n }" ]
[ "public static JqmEngineOperations startEngine(String name, JqmEngineHandler handler)\n {\n JqmEngine e = new JqmEngine();\n e.start(name, handler);\n return e;\n }", "public void growMaxLength( int arrayLength , boolean preserveValue ) {\n if( arrayLength < 0 )\n throw new IllegalArgumentException(\"Negative array length. Overflow?\");\n // see if multiplying numRows*numCols will cause an overflow. If it won't then pick the smaller of the two\n if( numRows != 0 && numCols <= Integer.MAX_VALUE / numRows ) {\n // save the user from themselves\n arrayLength = Math.min(numRows*numCols, arrayLength);\n }\n if( nz_values == null || arrayLength > this.nz_values.length ) {\n double[] data = new double[ arrayLength ];\n int[] row_idx = new int[ arrayLength ];\n\n if( preserveValue ) {\n if( nz_values == null )\n throw new IllegalArgumentException(\"Can't preserve values when uninitialized\");\n System.arraycopy(this.nz_values, 0, data, 0, this.nz_length);\n System.arraycopy(this.nz_rows, 0, row_idx, 0, this.nz_length);\n }\n\n this.nz_values = data;\n this.nz_rows = row_idx;\n }\n }", "public boolean equivalent(Element otherElement, boolean logging) {\n\t\tif (eventable.getElement().equals(otherElement)) {\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element equal\");\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (eventable.getElement().equalAttributes(otherElement)) {\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element attributes equal\");\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (eventable.getElement().equalId(otherElement)) {\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element ID equal\");\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (!eventable.getElement().getText().equals(\"\")\n\t\t\t\t&& eventable.getElement().equalText(otherElement)) {\n\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element text equal\");\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}", "private void recurseAndAddFiles(GraphRewrite event, FileService fileService, WindupJavaConfigurationService javaConfigurationService, FileModel file)\n {\n if (javaConfigurationService.checkIfIgnored(event, file))\n return;\n\n String filePath = file.getFilePath();\n File fileReference = new File(filePath);\n Long directorySize = new Long(0);\n\n if (fileReference.isDirectory())\n {\n File[] subFiles = fileReference.listFiles();\n if (subFiles != null)\n {\n for (File reference : subFiles)\n {\n FileModel subFile = fileService.createByFilePath(file, reference.getAbsolutePath());\n recurseAndAddFiles(event, fileService, javaConfigurationService, subFile);\n if (subFile.isDirectory())\n {\n directorySize = directorySize + subFile.getDirectorySize();\n }\n else\n {\n directorySize = directorySize + subFile.getSize();\n }\n }\n }\n file.setDirectorySize(directorySize);\n }\n }", "protected void concatenateReports() {\n\n if (!concatenatedReports.isEmpty()) { // dummy group for page break if needed\n DJGroup globalGroup = createDummyGroup();\n report.getColumnsGroups().add(0, globalGroup);\n }\n\n for (Subreport subreport : concatenatedReports) {\n DJGroup globalGroup = createDummyGroup();\n globalGroup.getFooterSubreports().add(subreport);\n report.getColumnsGroups().add(0, globalGroup);\n }\n }", "private static MonetaryFormatsSingletonSpi loadMonetaryFormatsSingletonSpi() {\n try {\n return Optional.ofNullable(Bootstrap.getService(MonetaryFormatsSingletonSpi.class))\n .orElseGet(DefaultMonetaryFormatsSingletonSpi::new);\n } catch (Exception e) {\n Logger.getLogger(MonetaryFormats.class.getName())\n .log(Level.WARNING, \"Failed to load MonetaryFormatsSingletonSpi, using default.\", e);\n return new DefaultMonetaryFormatsSingletonSpi();\n }\n }", "public void loadClassifier(InputStream in, Properties props) throws IOException, ClassCastException,\r\n ClassNotFoundException {\r\n loadClassifier(new ObjectInputStream(in), props);\r\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 }", "protected boolean check(String id, List<String> includes, List<String> excludes) {\n\t\treturn check(id, includes) && !check(id, excludes);\n\t}" ]
Convert a query parameter to the correct object type based on the first letter of the name. @param name parameter name @param value parameter value @return parameter object as @throws ParseException value could not be parsed @throws NumberFormatException value could not be parsed
[ "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 synchronized RegistrationPoint getOldestRegistrationPoint() {\n return registrationPoints.size() == 0 ? null : registrationPoints.values().iterator().next().get(0);\n }", "public void setDefault() {\n try {\n TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);\n String phone = telephonyManager.getLine1Number();\n if (phone != null && !phone.isEmpty()) {\n this.setNumber(phone);\n } else {\n String iso = telephonyManager.getNetworkCountryIso();\n setEmptyDefault(iso);\n }\n } catch (SecurityException e) {\n setEmptyDefault();\n }\n }", "public static void setTime(Calendar calendar, int hourOfDay, int minute, int second, int millisecond) {\n calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);\n calendar.set(Calendar.MINUTE, minute);\n calendar.set(Calendar.SECOND, second);\n calendar.set(Calendar.MILLISECOND, millisecond);\n }", "public PhotoList<Photo> getUntagged(int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_UNTAGGED);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n PhotoList<Photo> photos = PhotoUtils.createPhotoList(photosElement);\r\n return photos;\r\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 static <T> String join(Collection<T> col, String delim) {\n StringBuilder sb = new StringBuilder();\n Iterator<T> iter = col.iterator();\n if (iter.hasNext())\n sb.append(iter.next().toString());\n while (iter.hasNext()) {\n sb.append(delim);\n sb.append(iter.next().toString());\n }\n return sb.toString();\n }", "public MACAddress toEUI64(boolean asMAC) {\r\n\t\tif(!isExtended()) {//getSegmentCount() == EXTENDED_UNIQUE_IDENTIFIER_48_SEGMENT_COUNT\r\n\t\t\tMACAddressCreator creator = getAddressCreator();\r\n\t\t\tMACAddressSegment segs[] = creator.createSegmentArray(EXTENDED_UNIQUE_IDENTIFIER_64_SEGMENT_COUNT);\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tsection.getSegments(0, 3, segs, 0);\r\n\t\t\tMACAddressSegment ffSegment = creator.createSegment(0xff);\r\n\t\t\tsegs[3] = ffSegment;\r\n\t\t\tsegs[4] = asMAC ? ffSegment : creator.createSegment(0xfe);\r\n\t\t\tsection.getSegments(3, 6, segs, 5);\r\n\t\t\tInteger prefLength = getPrefixLength();\r\n\t\t\tif(prefLength != null) {\r\n\t\t\t\tMACAddressSection resultSection = creator.createSectionInternal(segs, true);\r\n\t\t\t\tif(prefLength >= 24) {\r\n\t\t\t\t\tprefLength += MACAddress.BITS_PER_SEGMENT << 1; //two segments\r\n\t\t\t\t}\r\n\t\t\t\tresultSection.assignPrefixLength(prefLength);\r\n\t\t\t}\r\n\t\t\treturn creator.createAddressInternal(segs);\r\n\t\t} else {\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tMACAddressSegment seg3 = section.getSegment(3);\r\n\t\t\tMACAddressSegment seg4 = section.getSegment(4);\r\n\t\t\tif(seg3.matches(0xff) && seg4.matches(asMAC ? 0xff : 0xfe)) {\r\n\t\t\t\treturn this;\r\n\t\t\t}\r\n\t\t}\r\n\t\tthrow new IncompatibleAddressException(this, \"ipaddress.mac.error.not.eui.convertible\");\r\n\t}", "public static double blackModelDgitialCapletValue(\n\t\t\tdouble forward,\n\t\t\tdouble volatility,\n\t\t\tdouble periodLength,\n\t\t\tdouble discountFactor,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\t// May be interpreted as a special version of the Black-Scholes Formula\n\t\treturn AnalyticFormulas.blackScholesDigitalOptionValue(forward, 0.0, volatility, optionMaturity, optionStrike) * periodLength * discountFactor;\n\t}", "@SuppressWarnings(\"deprecation\")\n\tpublic static boolean isTimeInRange(java.sql.Time start, java.sql.Time end, java.util.Date d) {\n d = new java.sql.Time(d.getHours(), d.getMinutes(), d.getSeconds());\n\n if (start == null || end == null) {\n return false;\n }\n\n if (start.before(end) && (!(d.after(start) && d.before(end)))) {\n return false;\n }\n\n if (end.before(start) && (!(d.after(end) || d.before(start)))) {\n return false;\n }\n return true;\n }" ]
Get the log if exists or return null @param topic topic name @param partition partition index @return a log for the topic or null if not exist
[ "public ILog getLog(String topic, int partition) {\n TopicNameValidator.validate(topic);\n Pool<Integer, Log> p = getLogPool(topic, partition);\n return p == null ? null : p.get(partition);\n }" ]
[ "public static Object instantiate(Constructor constructor) throws InstantiationException\r\n {\r\n if(constructor == null)\r\n {\r\n throw new ClassNotPersistenceCapableException(\r\n \"A zero argument constructor was not provided!\");\r\n }\r\n\r\n Object result = null;\r\n try\r\n {\r\n result = constructor.newInstance(NO_ARGS);\r\n }\r\n catch(InstantiationException e)\r\n {\r\n throw e;\r\n }\r\n catch(Exception e)\r\n {\r\n throw new ClassNotPersistenceCapableException(\"Can't instantiate class '\"\r\n + (constructor != null ? constructor.getDeclaringClass().getName() : \"null\")\r\n + \"' with given constructor: \" + e.getMessage(), e);\r\n }\r\n return result;\r\n }", "@Nullable\n public final String getStringContent(final long blobHandle, @NotNull final Transaction txn) throws IOException {\n String result;\n result = stringContentCache.tryKey(this, blobHandle);\n if (result == null) {\n final InputStream content = getContent(blobHandle, txn);\n if (content == null) {\n logger.error(\"Blob string not found: \" + getBlobLocation(blobHandle), new FileNotFoundException());\n }\n result = content == null ? null : UTFUtil.readUTF(content);\n if (result != null && result.length() <= config.getBlobStringsCacheMaxValueSize()) {\n if (stringContentCache.getObject(this, blobHandle) == null) {\n stringContentCache.cacheObject(this, blobHandle, result);\n }\n }\n }\n return result;\n }", "public void migrate() {\n if (databaseIsUpToDate()) {\n LOGGER.info(format(\"Keyspace %s is already up to date at version %d\", database.getKeyspaceName(),\n database.getVersion()));\n return;\n }\n\n List<DbMigration> migrations = repository.getMigrationsSinceVersion(database.getVersion());\n migrations.forEach(database::execute);\n LOGGER.info(format(\"Migrated keyspace %s to version %d\", database.getKeyspaceName(), database.getVersion()));\n database.close();\n }", "private int cleanupSegmentsToMaintainSize(final Log log) throws IOException {\n if (logRetentionSize < 0 || log.size() < logRetentionSize) return 0;\n\n List<LogSegment> toBeDeleted = log.markDeletedWhile(new LogSegmentFilter() {\n\n long diff = log.size() - logRetentionSize;\n\n public boolean filter(LogSegment segment) {\n diff -= segment.size();\n return diff >= 0;\n }\n });\n return deleteSegments(log, toBeDeleted);\n }", "public void setWidth(int width) {\n this.width = width;\n getElement().getStyle().setWidth(width, Style.Unit.PX);\n }", "public static base_response update(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup updateresource = new cachecontentgroup();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.weakposrelexpiry = resource.weakposrelexpiry;\n\t\tupdateresource.heurexpiryparam = resource.heurexpiryparam;\n\t\tupdateresource.relexpiry = resource.relexpiry;\n\t\tupdateresource.relexpirymillisec = resource.relexpirymillisec;\n\t\tupdateresource.absexpiry = resource.absexpiry;\n\t\tupdateresource.absexpirygmt = resource.absexpirygmt;\n\t\tupdateresource.weaknegrelexpiry = resource.weaknegrelexpiry;\n\t\tupdateresource.hitparams = resource.hitparams;\n\t\tupdateresource.invalparams = resource.invalparams;\n\t\tupdateresource.ignoreparamvaluecase = resource.ignoreparamvaluecase;\n\t\tupdateresource.matchcookies = resource.matchcookies;\n\t\tupdateresource.invalrestrictedtohost = resource.invalrestrictedtohost;\n\t\tupdateresource.polleverytime = resource.polleverytime;\n\t\tupdateresource.ignorereloadreq = resource.ignorereloadreq;\n\t\tupdateresource.removecookies = resource.removecookies;\n\t\tupdateresource.prefetch = resource.prefetch;\n\t\tupdateresource.prefetchperiod = resource.prefetchperiod;\n\t\tupdateresource.prefetchperiodmillisec = resource.prefetchperiodmillisec;\n\t\tupdateresource.prefetchmaxpending = resource.prefetchmaxpending;\n\t\tupdateresource.flashcache = resource.flashcache;\n\t\tupdateresource.expireatlastbyte = resource.expireatlastbyte;\n\t\tupdateresource.insertvia = resource.insertvia;\n\t\tupdateresource.insertage = resource.insertage;\n\t\tupdateresource.insertetag = resource.insertetag;\n\t\tupdateresource.cachecontrol = resource.cachecontrol;\n\t\tupdateresource.quickabortsize = resource.quickabortsize;\n\t\tupdateresource.minressize = resource.minressize;\n\t\tupdateresource.maxressize = resource.maxressize;\n\t\tupdateresource.memlimit = resource.memlimit;\n\t\tupdateresource.ignorereqcachinghdrs = resource.ignorereqcachinghdrs;\n\t\tupdateresource.minhits = resource.minhits;\n\t\tupdateresource.alwaysevalpolicies = resource.alwaysevalpolicies;\n\t\tupdateresource.persist = resource.persist;\n\t\tupdateresource.pinned = resource.pinned;\n\t\tupdateresource.lazydnsresolve = resource.lazydnsresolve;\n\t\tupdateresource.hitselector = resource.hitselector;\n\t\tupdateresource.invalselector = resource.invalselector;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static base_responses update(nitro_service client, systemuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsystemuser updateresources[] = new systemuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new systemuser();\n\t\t\t\tupdateresources[i].username = resources[i].username;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].externalauth = resources[i].externalauth;\n\t\t\t\tupdateresources[i].promptstring = resources[i].promptstring;\n\t\t\t\tupdateresources[i].timeout = resources[i].timeout;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "protected static <S extends IPAddressSegment> void normalizePrefixBoundary(\n\t\t\tint sectionPrefixBits,\n\t\t\tS segments[],\n\t\t\tint segmentBitCount,\n\t\t\tint segmentByteCount,\n\t\t\tBiFunction<S, Integer, S> segProducer) {\n\t\t//we've already verified segment prefixes in super constructor. We simply need to check the case where the prefix is at a segment boundary,\n\t\t//whether the network side has the correct prefix\n\t\tint networkSegmentIndex = getNetworkSegmentIndex(sectionPrefixBits, segmentByteCount, segmentBitCount);\n\t\tif(networkSegmentIndex >= 0) {\n\t\t\tS segment = segments[networkSegmentIndex];\n\t\t\tif(!segment.isPrefixed()) {\n\t\t\t\tsegments[networkSegmentIndex] = segProducer.apply(segment, segmentBitCount);\n\t\t\t}\n\t\t}\n\t}", "public void setEndType(final String value) {\r\n\r\n final EndType endType = EndType.valueOf(value);\r\n if (!endType.equals(m_model.getEndType())) {\r\n removeExceptionsOnChange(new Command() {\r\n\r\n public void execute() {\r\n\r\n switch (endType) {\r\n case SINGLE:\r\n m_model.setOccurrences(0);\r\n m_model.setSeriesEndDate(null);\r\n break;\r\n case TIMES:\r\n m_model.setOccurrences(10);\r\n m_model.setSeriesEndDate(null);\r\n break;\r\n case DATE:\r\n m_model.setOccurrences(0);\r\n m_model.setSeriesEndDate(m_model.getStart() == null ? new Date() : m_model.getStart());\r\n break;\r\n default:\r\n break;\r\n }\r\n m_model.setEndType(endType);\r\n valueChanged();\r\n }\r\n });\r\n }\r\n\r\n }" ]
Computes the WordNet 2.0 POS tag corresponding to the PTB POS tag s. @param s a Penn TreeBank POS tag.
[ "public static String pennPOSToWordnetPOS(String s) {\r\n if (s.matches(\"NN|NNP|NNS|NNPS\")) {\r\n return \"noun\";\r\n }\r\n if (s.matches(\"VB|VBD|VBG|VBN|VBZ|VBP|MD\")) {\r\n return \"verb\";\r\n }\r\n if (s.matches(\"JJ|JJR|JJS|CD\")) {\r\n return \"adjective\";\r\n }\r\n if (s.matches(\"RB|RBR|RBS|RP|WRB\")) {\r\n return \"adverb\";\r\n }\r\n return null;\r\n }" ]
[ "public static InputStream toStream(String content, Charset charset) {\n byte[] bytes = content.getBytes(charset);\n return new ByteArrayInputStream(bytes);\n }", "public void saveFavorites(List<CmsFavoriteEntry> favorites) throws CmsException {\n\n try {\n JSONObject json = new JSONObject();\n JSONArray array = new JSONArray();\n for (CmsFavoriteEntry entry : favorites) {\n array.put(entry.toJson());\n }\n json.put(BASE_KEY, array);\n String data = json.toString();\n CmsUser user = readUser();\n user.setAdditionalInfo(ADDINFO_KEY, data);\n m_cms.writeUser(user);\n } catch (JSONException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n\n }", "protected static <S extends IPAddressSegment> void normalizePrefixBoundary(\n\t\t\tint sectionPrefixBits,\n\t\t\tS segments[],\n\t\t\tint segmentBitCount,\n\t\t\tint segmentByteCount,\n\t\t\tBiFunction<S, Integer, S> segProducer) {\n\t\t//we've already verified segment prefixes in super constructor. We simply need to check the case where the prefix is at a segment boundary,\n\t\t//whether the network side has the correct prefix\n\t\tint networkSegmentIndex = getNetworkSegmentIndex(sectionPrefixBits, segmentByteCount, segmentBitCount);\n\t\tif(networkSegmentIndex >= 0) {\n\t\t\tS segment = segments[networkSegmentIndex];\n\t\t\tif(!segment.isPrefixed()) {\n\t\t\t\tsegments[networkSegmentIndex] = segProducer.apply(segment, segmentBitCount);\n\t\t\t}\n\t\t}\n\t}", "public void readTags(InputStream tagsXML)\n {\n SAXParserFactory factory = SAXParserFactory.newInstance();\n try\n {\n SAXParser saxParser = factory.newSAXParser();\n saxParser.parse(tagsXML, new TagsSaxHandler(this));\n }\n catch (ParserConfigurationException | SAXException | IOException ex)\n {\n throw new RuntimeException(\"Failed parsing the tags definition: \" + ex.getMessage(), ex);\n }\n }", "public static List<String> asListLines(String content) {\n List<String> retorno = new ArrayList<String>();\n content = content.replace(CARRIAGE_RETURN, RETURN);\n content = content.replace(RETURN, CARRIAGE_RETURN);\n for (String str : content.split(CARRIAGE_RETURN)) {\n retorno.add(str);\n }\n return retorno;\n }", "public static base_response enable(nitro_service client, Long clid) throws Exception {\n\t\tclusterinstance enableresource = new clusterinstance();\n\t\tenableresource.clid = clid;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}", "private Expression getExpression(String expressionString) throws ParseException {\n\t\tif (!expressionCache.containsKey(expressionString)) {\n\t\t\tExpression expression;\n\t\t\texpression = parser.parseExpression(expressionString);\n\t\t\texpressionCache.put(expressionString, expression);\n\t\t}\n\t\treturn expressionCache.get(expressionString);\n\n\t}", "public void resizeKeys(int numKeys)\n {\n int n = numKeys * mFloatsPerKey;\n if (mKeys.length == n)\n {\n return;\n }\n float[] newKeys = new float[n];\n n = Math.min(n, mKeys.length);\n\n System.arraycopy(mKeys, 0, newKeys, 0, n);\n mKeys = newKeys;\n mFloatInterpolator.setKeyData(mKeys);\n }", "public double[] getMoneynessAsOffsets() {\r\n\t\tDoubleStream moneyness = getGridNodesPerMoneyness().keySet().stream().mapToDouble(Integer::doubleValue);\r\n\t\tif(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn x * 0.01;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t} else if(quotingConvention == QuotingConvention.RECEIVERPRICE) {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn - x * 0.0001;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t} else {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn x * 0.0001;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t}\r\n\t\treturn moneyness.toArray();\r\n\t}" ]
Add columns to the tree. @param parentNode parent tree node @param table columns container
[ "private void addColumns(MpxjTreeNode parentNode, Table table)\n {\n for (Column column : table.getColumns())\n {\n final Column c = column;\n MpxjTreeNode childNode = new MpxjTreeNode(column)\n {\n @Override public String toString()\n {\n return c.getTitle();\n }\n };\n parentNode.add(childNode);\n }\n }" ]
[ "public void newLineIfNotEmpty() {\n\t\tfor (int i = segments.size() - 1; i >= 0; i--) {\n\t\t\tString segment = segments.get(i);\n\t\t\tif (lineDelimiter.equals(segment)) {\n\t\t\t\tsegments.subList(i + 1, segments.size()).clear();\n\t\t\t\tcachedToString = null;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (int j = 0; j < segment.length(); j++) {\n\t\t\t\tif (!WhitespaceMatcher.isWhitespace(segment.charAt(j))) {\n\t\t\t\t\tnewLine();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsegments.clear();\n\t\tcachedToString = null;\n\t}", "public EventBus emit(String event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }", "public void setName(int pathId, String pathName) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_PATHNAME + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, pathName);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "protected Object checkUndefined(Object val) {\n if (val instanceof String && ((String) val).equals(\"undefined\")) {\n return null;\n }\n return val;\n }", "static DisplayMetrics getDisplayMetrics(final Context context) {\n final WindowManager\n windowManager =\n (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n final DisplayMetrics metrics = new DisplayMetrics();\n windowManager.getDefaultDisplay().getMetrics(metrics);\n return metrics;\n }", "public void setFrustum(float fovy, float aspect, float znear, float zfar)\n {\n Matrix4f projMatrix = new Matrix4f();\n projMatrix.perspective((float) Math.toRadians(fovy), aspect, znear, zfar);\n setFrustum(projMatrix);\n }", "@Override\n public final String optString(final String key, final String defaultValue) {\n String result = optString(key);\n return result == null ? defaultValue : result;\n }", "public void resolveLazyCrossReferences(final CancelIndicator mon) {\n\t\tfinal CancelIndicator monitor = mon == null ? CancelIndicator.NullImpl : mon;\n\t\tTreeIterator<Object> iterator = EcoreUtil.getAllContents(this, true);\n\t\twhile (iterator.hasNext()) {\n\t\t\toperationCanceledManager.checkCanceled(monitor);\n\t\t\tInternalEObject source = (InternalEObject) iterator.next();\n\t\t\tEStructuralFeature[] eStructuralFeatures = ((EClassImpl.FeatureSubsetSupplier) source.eClass()\n\t\t\t\t\t.getEAllStructuralFeatures()).crossReferences();\n\t\t\tif (eStructuralFeatures != null) {\n\t\t\t\tfor (EStructuralFeature crossRef : eStructuralFeatures) {\n\t\t\t\t\toperationCanceledManager.checkCanceled(monitor);\n\t\t\t\t\tresolveLazyCrossReference(source, crossRef);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "static Map<String, Set<String>> getChildAddresses(final OperationContext context, final PathAddress addr, final ImmutableManagementResourceRegistration registry, Resource resource, final String validChildType) {\n\n Map<String, Set<String>> result = new HashMap<>();\n Predicate<String> validChildTypeFilter = childType -> (validChildType == null) || validChildType.equals(childType);\n\n if (resource != null) {\n for (String childType : registry.getChildNames(PathAddress.EMPTY_ADDRESS)) {\n if (validChildTypeFilter.test(childType)) {\n List<String> list = new ArrayList<>();\n for (String child : resource.getChildrenNames(childType)) {\n if (registry.getSubModel(PathAddress.pathAddress(PathElement.pathElement(childType, child))) != null) {\n list.add(child);\n }\n }\n result.put(childType, new LinkedHashSet<>(list));\n }\n }\n }\n\n Set<PathElement> paths = registry.getChildAddresses(PathAddress.EMPTY_ADDRESS);\n for (PathElement path : paths) {\n String childType = path.getKey();\n if (validChildTypeFilter.test(childType)) {\n Set<String> children = result.get(childType);\n if (children == null) {\n // WFLY-3306 Ensure we have an entry for any valid child type\n children = new LinkedHashSet<>();\n result.put(childType, children);\n }\n ImmutableManagementResourceRegistration childRegistration = registry.getSubModel(PathAddress.pathAddress(path));\n if (childRegistration != null) {\n AliasEntry aliasEntry = childRegistration.getAliasEntry();\n if (aliasEntry != null) {\n PathAddress childAddr = addr.append(path);\n PathAddress target = aliasEntry.convertToTargetAddress(childAddr, AliasContext.create(childAddr, context));\n assert !childAddr.equals(target) : \"Alias was not translated\";\n PathAddress targetParent = target.getParent();\n Resource parentResource = context.readResourceFromRoot(targetParent, false);\n if (parentResource != null) {\n PathElement targetElement = target.getLastElement();\n if (targetElement.isWildcard()) {\n children.addAll(parentResource.getChildrenNames(targetElement.getKey()));\n } else if (parentResource.hasChild(targetElement)) {\n children.add(path.getValue());\n }\n }\n }\n if (!path.isWildcard() && childRegistration.isRemote()) {\n children.add(path.getValue());\n }\n }\n }\n }\n\n return result;\n }" ]
Update the BinderDescriptor of the declarationBinderRef. @param declarationBinderRef the ServiceReference<DeclarationBinder> of the DeclarationBinder
[ "public void modified(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {\n declarationBinders.get(declarationBinderRef).update(declarationBinderRef);\n }" ]
[ "public static String encodeHost(String host, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(host, encoding, HierarchicalUriComponents.Type.HOST_IPV4);\n\t}", "public synchronized static <D extends Dao<T, ?>, T> D lookupDao(ConnectionSource connectionSource, Class<T> clazz) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\tClassConnectionSource key = new ClassConnectionSource(connectionSource, clazz);\n\t\tDao<?, ?> dao = lookupDao(key);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tD castDao = (D) dao;\n\t\treturn castDao;\n\t}", "public ScopedToken getLowerScopedToken(List<String> scopes, String resource) {\n assert (scopes != null);\n assert (scopes.size() > 0);\n URL url = null;\n try {\n url = new URL(this.getTokenURL());\n } catch (MalformedURLException e) {\n assert false : \"An invalid refresh URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid refresh URL indicates a bug in the SDK.\", e);\n }\n\n StringBuilder spaceSeparatedScopes = new StringBuilder();\n for (int i = 0; i < scopes.size(); i++) {\n spaceSeparatedScopes.append(scopes.get(i));\n if (i < scopes.size() - 1) {\n spaceSeparatedScopes.append(\" \");\n }\n }\n\n String urlParameters = null;\n\n if (resource != null) {\n //this.getAccessToken() ensures we have a valid access token\n urlParameters = String.format(\"grant_type=urn:ietf:params:oauth:grant-type:token-exchange\"\n + \"&subject_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=%s\"\n + \"&scope=%s&resource=%s\",\n this.getAccessToken(), spaceSeparatedScopes, resource);\n } else {\n //this.getAccessToken() ensures we have a valid access token\n urlParameters = String.format(\"grant_type=urn:ietf:params:oauth:grant-type:token-exchange\"\n + \"&subject_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=%s\"\n + \"&scope=%s\",\n this.getAccessToken(), spaceSeparatedScopes);\n }\n\n BoxAPIRequest request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n String json;\n try {\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n json = response.getJSON();\n } catch (BoxAPIException e) {\n this.notifyError(e);\n throw e;\n }\n\n JsonObject jsonObject = JsonObject.readFrom(json);\n ScopedToken token = new ScopedToken(jsonObject);\n token.setObtainedAt(System.currentTimeMillis());\n token.setExpiresIn(jsonObject.get(\"expires_in\").asLong() * 1000);\n return token;\n }", "public void cache(String key, Object obj) {\n H.Session sess = session();\n if (null != sess) {\n sess.cache(key, obj);\n } else {\n app().cache().put(key, obj);\n }\n }", "public void setWeekDay(String weekDayStr) {\n\n final WeekDay weekDay = WeekDay.valueOf(weekDayStr);\n if ((m_model.getWeekDay() != null) || !m_model.getWeekDay().equals(weekDay)) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDay(weekDay);\n onValueChange();\n }\n });\n\n }\n\n }", "public static CharSequence getAt(CharSequence text, Range range) {\n RangeInfo info = subListBorders(text.length(), range);\n CharSequence sequence = text.subSequence(info.from, info.to);\n return info.reverse ? reverse(sequence) : sequence;\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 static DMatrixSparseCSC rectangle(int numRows , int numCols , int nz_total ,\n double min , double max , Random rand ) {\n\n nz_total = Math.min(numCols*numRows,nz_total);\n int[] selected = UtilEjml.shuffled(numRows*numCols, nz_total, rand);\n Arrays.sort(selected,0,nz_total);\n\n DMatrixSparseCSC ret = new DMatrixSparseCSC(numRows,numCols,nz_total);\n ret.indicesSorted = true;\n\n // compute the number of elements in each column\n int hist[] = new int[ numCols ];\n for (int i = 0; i < nz_total; i++) {\n hist[selected[i]/numRows]++;\n }\n\n // define col_idx\n ret.histogramToStructure(hist);\n\n for (int i = 0; i < nz_total; i++) {\n int row = selected[i]%numRows;\n\n ret.nz_rows[i] = row;\n ret.nz_values[i] = rand.nextDouble()*(max-min)+min;\n }\n\n return ret;\n }", "public static base_response unset(nitro_service client, lbsipparameters resource, String[] args) throws Exception{\n\t\tlbsipparameters unsetresource = new lbsipparameters();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
Use this API to fetch filterpolicy_binding resource of given name .
[ "public static filterpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tfilterpolicy_binding obj = new filterpolicy_binding();\n\t\tobj.set_name(name);\n\t\tfilterpolicy_binding response = (filterpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "@Override\n public List<String> getDefaultProviderChain() {\n List<String> result = new ArrayList<>(Monetary.getRoundingProviderNames());\n Collections.sort(result);\n return result;\n }", "protected void printCenterWithLead(String lead, String format, Object ... args) {\n String text = S.fmt(format, args);\n int len = 80 - lead.length();\n info(S.concat(lead, S.center(text, len)));\n }", "public IPv6AddressSegment join(IPv6AddressCreator creator, IPv4AddressSegment low) throws IncompatibleAddressException {\r\n\t\tint shift = IPv4Address.BITS_PER_SEGMENT;\r\n\t\tInteger prefix = getJoinedSegmentPrefixLength(shift, getSegmentPrefixLength(), low.getSegmentPrefixLength());\r\n\t\tif(isMultiple()) {\r\n\t\t\t//if the high segment has a range, the low segment must match the full range, \r\n\t\t\t//otherwise it is not possible to create an equivalent range when joining\r\n\t\t\tif(!low.isFullRange()) {\r\n\t\t\t\tthrow new IncompatibleAddressException(this, low, \"ipaddress.error.invalidMixedRange\");\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn creator.createSegment(\r\n\t\t\t\t(getSegmentValue() << shift) | low.getSegmentValue(), \r\n\t\t\t\t(getUpperSegmentValue() << shift) | low.getUpperSegmentValue(),\r\n\t\t\t\tprefix);\r\n\t}", "public byte[] toByteArray() {\n try {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n oos.writeObject(this);\n return baos.toByteArray();\n } catch (IOException e) {\n throw E.ioException(e);\n }\n }", "public List<DbLicense> getArtifactLicenses(final String gavc, final FiltersHolder filters) {\n final DbArtifact artifact = getArtifact(gavc);\n final List<DbLicense> licenses = new ArrayList<>();\n\n for(final String name: artifact.getLicenses()){\n final Set<DbLicense> matchingLicenses = licenseMatcher.getMatchingLicenses(name);\n\n // Here is a license to identify\n if(matchingLicenses.isEmpty()){\n final DbLicense notIdentifiedLicense = new DbLicense();\n notIdentifiedLicense.setName(name);\n licenses.add(notIdentifiedLicense);\n } else {\n matchingLicenses.stream()\n .filter(filters::shouldBeInReport)\n .forEach(licenses::add);\n }\n }\n\n return licenses;\n }", "public static QRDecomposition<DoubleMatrix> qr(DoubleMatrix A) {\n int minmn = min(A.rows, A.columns);\n DoubleMatrix result = A.dup();\n DoubleMatrix tau = new DoubleMatrix(minmn);\n SimpleBlas.geqrf(result, tau);\n DoubleMatrix R = new DoubleMatrix(A.rows, A.columns);\n for (int i = 0; i < A.rows; i++) {\n for (int j = i; j < A.columns; j++) {\n R.put(i, j, result.get(i, j));\n }\n }\n DoubleMatrix Q = DoubleMatrix.eye(A.rows);\n SimpleBlas.ormqr('L', 'N', result, tau, Q);\n return new QRDecomposition<DoubleMatrix>(Q, R);\n }", "void backup() throws ConfigurationPersistenceException {\n if (!doneBootup.get()) {\n return;\n }\n try {\n if (!interactionPolicy.isReadOnly()) {\n //Move the main file to the versioned history\n moveFile(mainFile, getVersionedFile(mainFile));\n } else {\n //Copy the Last file to the versioned history\n moveFile(lastFile, getVersionedFile(mainFile));\n }\n int seq = sequence.get();\n // delete unwanted backup files\n int currentHistoryLength = getInteger(CURRENT_HISTORY_LENGTH_PROPERTY, CURRENT_HISTORY_LENGTH, 0);\n if (seq > currentHistoryLength) {\n for (int k = seq - currentHistoryLength; k > 0; k--) {\n File delete = getVersionedFile(mainFile, k);\n if (! delete.exists()) {\n break;\n }\n delete.delete();\n }\n }\n } catch (IOException e) {\n throw ControllerLogger.ROOT_LOGGER.failedToBackup(e, mainFile);\n }\n }", "public static boolean ensureJedisConnection(final Jedis jedis) {\n final boolean jedisOK = testJedisConnection(jedis);\n if (!jedisOK) {\n try {\n jedis.quit();\n } catch (Exception e) {\n } // Ignore\n try {\n jedis.disconnect();\n } catch (Exception e) {\n } // Ignore\n jedis.connect();\n }\n return jedisOK;\n }", "@SuppressWarnings(\"unchecked\")\n public static <E> String serialize(E object, ParameterizedType<E> parameterizedType) throws IOException {\n return mapperFor(parameterizedType).serialize(object);\n }" ]
Check if zone count policy is satisfied @return whether zone is satisfied
[ "private boolean isZonesSatisfied() {\n boolean zonesSatisfied = false;\n if(pipelineData.getZonesRequired() == null) {\n zonesSatisfied = true;\n } else {\n int numZonesSatisfied = pipelineData.getZoneResponses().size();\n if(numZonesSatisfied >= (pipelineData.getZonesRequired() + 1)) {\n zonesSatisfied = true;\n }\n }\n return zonesSatisfied;\n }" ]
[ "public static base_response add(nitro_service client, dnsview resource) throws Exception {\n\t\tdnsview addresource = new dnsview();\n\t\taddresource.viewname = resource.viewname;\n\t\treturn addresource.add_resource(client);\n\t}", "private void addViews(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (View view : file.getViews())\n {\n final View v = view;\n MpxjTreeNode childNode = new MpxjTreeNode(view)\n {\n @Override public String toString()\n {\n return v.getName();\n }\n };\n parentNode.add(childNode);\n }\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushInstallReferrer(Intent intent) {\n try {\n final Bundle extras = intent.getExtras();\n // Preliminary checks\n if (extras == null || !extras.containsKey(\"referrer\")) {\n return;\n }\n final String url;\n try {\n url = URLDecoder.decode(extras.getString(\"referrer\"), \"UTF-8\");\n\n getConfigLogger().verbose(getAccountId(), \"Referrer received: \" + url);\n } catch (Throwable e) {\n // Could not decode\n return;\n }\n if (url == null) {\n return;\n }\n int now = (int) (System.currentTimeMillis() / 1000);\n\n if (installReferrerMap.containsKey(url) && now - installReferrerMap.get(url) < 10) {\n getConfigLogger().verbose(getAccountId(),\"Skipping install referrer due to duplicate within 10 seconds\");\n return;\n }\n\n installReferrerMap.put(url, now);\n\n Uri uri = Uri.parse(\"wzrk://track?install=true&\" + url);\n\n pushDeepLink(uri, true);\n } catch (Throwable t) {\n // no-op\n }\n }", "public RuleEnvelope getRule(String ruleId) throws ApiException {\n ApiResponse<RuleEnvelope> resp = getRuleWithHttpInfo(ruleId);\n return resp.getData();\n }", "public int compare(Object objA, Object objB)\r\n {\r\n String idAStr = ((FieldDescriptorDef)_fields.get(objA)).getProperty(\"id\");\r\n String idBStr = ((FieldDescriptorDef)_fields.get(objB)).getProperty(\"id\");\r\n int idA;\r\n int idB;\r\n\r\n try\r\n {\r\n idA = Integer.parseInt(idAStr);\r\n }\r\n catch (Exception ex)\r\n {\r\n return 1;\r\n }\r\n try\r\n {\r\n idB = Integer.parseInt(idBStr);\r\n }\r\n catch (Exception ex)\r\n {\r\n return -1;\r\n }\r\n return idA < idB ? -1 : (idA > idB ? 1 : 0);\r\n }", "public UpdateBuilder<T, ID> updateColumnExpression(String columnName, String expression) throws SQLException {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new SQLException(\"Can't update foreign colletion field: \" + columnName);\n\t\t}\n\t\taddUpdateColumnToList(columnName, new SetExpression(columnName, fieldType, expression));\n\t\treturn this;\n\t}", "public Map<DeckReference, TrackMetadata> getLoadedTracks() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, TrackMetadata>(hotCache));\n }", "public String getString(Integer offset)\n {\n String result = null;\n\n if (offset != null)\n {\n byte[] value = m_map.get(offset);\n if (value != null)\n {\n result = MPPUtility.getString(value, 0);\n }\n }\n\n return (result);\n }", "@Deprecated\n @Override\n public File fetch(String source, String dest, long diskQuotaSizeInKB) throws Exception {\n return fetchFromSource(source, dest, null, null, -1, diskQuotaSizeInKB, null);\n }" ]
generate random velocities in the given range @return
[ "private float[] generateParticleVelocities()\n {\n float velocities[] = new float[mEmitRate * 3];\n for ( int i = 0; i < mEmitRate * 3; i +=3 )\n {\n Vector3f nexVel = getNextVelocity();\n velocities[i] = nexVel.x;\n velocities[i+1] = nexVel.y;\n velocities[i+2] = nexVel.z;\n }\n return velocities;\n }" ]
[ "public CollectionRequest<Task> stories(String task) {\n \n String path = String.format(\"/tasks/%s/stories\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }", "protected String getKey(final String ref, final String filename, final String extension) {\n return prefix + ref + \"/\" + filename + \".\" + extension;\n }", "public static transformpolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\ttransformpolicylabel obj = new transformpolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\ttransformpolicylabel response = (transformpolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}", "public boolean perform(Run<?, ?> build, Launcher launcher, TaskListener listener, EnvVars env, FilePath workDir, FilePath tempDir)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.getLogger().println(\"Couldn't find Maven home at \" + mavenHome.getRemote() + \" on agent \" + Utils.getAgentName(workDir) +\n \". This could be because this build is running inside a Docker container.\");\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, workDir, tempDir);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\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 }", "public static BoxRetentionPolicyAssignment.Info createAssignmentToFolder(BoxAPIConnection api, String policyID,\r\n String folderID) {\r\n return createAssignment(api, policyID, new JsonObject().add(\"type\", TYPE_FOLDER).add(\"id\", folderID), null);\r\n }", "public final void visit(final Visitor visitor)\n\t{\n\t\tfinal Visit visit = new Visit();\n\t\ttry\n\t\t{\n\t\t\tvisit(visitor, visit);\n\t\t}\n\t\tcatch (final StopVisitationException ignored)\n\t\t{\n\t\t}\n\t}", "private String validatePattern() {\n\n String error = null;\n switch (getPatternType()) {\n case DAILY:\n error = isEveryWorkingDay() ? null : validateInterval();\n break;\n case WEEKLY:\n error = validateInterval();\n if (null == error) {\n error = validateWeekDaySet();\n }\n break;\n case MONTHLY:\n error = validateInterval();\n if (null == error) {\n error = validateMonthSet();\n if (null == error) {\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n }\n }\n break;\n case YEARLY:\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n break;\n case INDIVIDUAL:\n case NONE:\n default:\n }\n return error;\n }", "protected ManageableCollection createCollection(CollectionDescriptor desc, Class collectionClass)\r\n {\r\n Class fieldType = desc.getPersistentField().getType();\r\n ManageableCollection col;\r\n\r\n if (collectionClass == null)\r\n {\r\n if (ManageableCollection.class.isAssignableFrom(fieldType))\r\n {\r\n try\r\n {\r\n col = (ManageableCollection)fieldType.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n throw new OJBRuntimeException(\"Cannot instantiate the default collection type \"+fieldType.getName()+\" of collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareCollection.class))\r\n {\r\n col = new RemovalAwareCollection();\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareList.class))\r\n {\r\n col = new RemovalAwareList();\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareSet.class))\r\n {\r\n col = new RemovalAwareSet();\r\n }\r\n else\r\n {\r\n throw new MetadataException(\"Cannot determine a default collection type for collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n else\r\n {\r\n try\r\n {\r\n col = (ManageableCollection)collectionClass.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n throw new OJBRuntimeException(\"Cannot instantiate the collection class \"+collectionClass.getName()+\" of collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n return col;\r\n }" ]
Specify the socket to be used as underlying socket to connect to the APN service. This assumes that the socket connects to a SOCKS proxy. @deprecated use {@link ApnsServiceBuilder#withProxy(Proxy)} instead @param proxySocket the underlying socket for connections @return this
[ "@Deprecated\n public ApnsServiceBuilder withProxySocket(Socket proxySocket) {\n return this.withProxy(new Proxy(Proxy.Type.SOCKS,\n proxySocket.getRemoteSocketAddress()));\n }" ]
[ "public static void main(String[] args) throws Exception {\r\n System.err.println(\"CRFBiasedClassifier invoked at \" + new Date()\r\n + \" with arguments:\");\r\n for (String arg : args) {\r\n System.err.print(\" \" + arg);\r\n }\r\n System.err.println();\r\n\r\n Properties props = StringUtils.argsToProperties(args);\r\n CRFBiasedClassifier crf = new CRFBiasedClassifier(props);\r\n String testFile = crf.flags.testFile;\r\n String loadPath = crf.flags.loadClassifier;\r\n\r\n if (loadPath != null) {\r\n crf.loadClassifierNoExceptions(loadPath, props);\r\n } else if (crf.flags.loadJarClassifier != null) {\r\n crf.loadJarClassifier(crf.flags.loadJarClassifier, props);\r\n } else {\r\n crf.loadDefaultClassifier();\r\n }\r\n if(crf.flags.classBias != null) {\r\n StringTokenizer biases = new java.util.StringTokenizer(crf.flags.classBias,\",\");\r\n while (biases.hasMoreTokens()) {\r\n StringTokenizer bias = new java.util.StringTokenizer(biases.nextToken(),\":\");\r\n String cname = bias.nextToken();\r\n double w = Double.parseDouble(bias.nextToken());\r\n crf.setBiasWeight(cname,w);\r\n System.err.println(\"Setting bias for class \"+cname+\" to \"+w);\r\n }\r\n }\r\n\r\n if (testFile != null) {\r\n DocumentReaderAndWriter readerAndWriter = crf.makeReaderAndWriter();\r\n if (crf.flags.printFirstOrderProbs) {\r\n crf.printFirstOrderProbs(testFile, readerAndWriter);\r\n } else if (crf.flags.printProbs) {\r\n crf.printProbs(testFile, readerAndWriter);\r\n } else if (crf.flags.useKBest) {\r\n int k = crf.flags.kBest;\r\n crf.classifyAndWriteAnswersKBest(testFile, k, readerAndWriter);\r\n } else {\r\n crf.classifyAndWriteAnswers(testFile, readerAndWriter);\r\n }\r\n }\r\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}", "public void setVariable(String name, Object value) {\n if (variables == null)\n variables = new LinkedHashMap();\n variables.put(name, value);\n }", "public static base_response delete(nitro_service client, String serverip) throws Exception {\n\t\tntpserver deleteresource = new ntpserver();\n\t\tdeleteresource.serverip = serverip;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public String login(String token, Authentication authentication) {\n\t\tif (null == token) {\n\t\t\treturn login(authentication);\n\t\t}\n\t\ttokens.put(token, new TokenContainer(authentication));\n\t\treturn token;\n\t}", "void onSurfaceChanged(int width, int height) {\n Log.v(TAG, \"onSurfaceChanged\");\n\n final VrAppSettings.EyeBufferParams.DepthFormat depthFormat = mApplication.getAppSettings().getEyeBufferParams().getDepthFormat();\n mApplication.getConfigurationManager().configureRendering(VrAppSettings.EyeBufferParams.DepthFormat.DEPTH_24_STENCIL_8 == depthFormat);\n }", "public static base_responses delete(nitro_service client, nsip6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsip6 deleteresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new nsip6();\n\t\t\t\tdeleteresources[i].ipv6address = resources[i].ipv6address;\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 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 static boolean any(Object self, Closure closure) {\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {\n if (bcw.call(iter.next())) return true;\n }\n return false;\n }" ]
Register the given mbean with the server @param server The server to register with @param mbean The mbean to register @param name The name to register under
[ "public static void registerMbean(MBeanServer server, ModelMBean mbean, ObjectName name) {\n try {\n synchronized(LOCK) {\n if(server.isRegistered(name))\n JmxUtils.unregisterMbean(server, name);\n server.registerMBean(mbean, name);\n }\n } catch(Exception e) {\n logger.error(\"Error registering mbean:\", e);\n }\n }" ]
[ "public base_response clear_config(Boolean force, String level) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsconfig resource = new nsconfig();\n\t\tif (force)\n\t\t\tresource.set_force(force);\n\n\t\tresource.set_level(level);\n\t\toptions option = new options();\n\t\toption.set_action(\"clear\");\n\t\tresult = resource.perform_operation(this, option);\n\t\treturn result;\n\t}", "public static nsconfig get(nitro_service service) throws Exception{\n\t\tnsconfig obj = new nsconfig();\n\t\tnsconfig[] response = (nsconfig[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public static NbtAddress[] getAllByAddress( NbtAddress addr )\n throws UnknownHostException {\n try {\n NbtAddress[] addrs = CLIENT.getNodeStatus( addr );\n cacheAddressArray( addrs );\n return addrs;\n } catch( UnknownHostException uhe ) {\n throw new UnknownHostException( \"no name with type 0x\" +\n Hexdump.toHexString( addr.hostName.hexCode, 2 ) +\n ((( addr.hostName.scope == null ) ||\n ( addr.hostName.scope.length() == 0 )) ?\n \" with no scope\" : \" with scope \" + addr.hostName.scope ) +\n \" for host \" + addr.getHostAddress() );\n }\n }", "public static base_response Force(nitro_service client, hafailover resource) throws Exception {\n\t\thafailover Forceresource = new hafailover();\n\t\tForceresource.force = resource.force;\n\t\treturn Forceresource.perform_operation(client,\"Force\");\n\t}", "public byte[] getByteArray(int offset)\n {\n byte[] result = null;\n\n if (offset > 0 && offset < m_data.length)\n {\n int nextBlockOffset = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n int itemSize = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n if (itemSize > 0 && itemSize < m_data.length)\n {\n int blockRemainingSize = 28;\n\n if (nextBlockOffset != -1 || itemSize <= blockRemainingSize)\n {\n int itemRemainingSize = itemSize;\n result = new byte[itemSize];\n int resultOffset = 0;\n\n while (nextBlockOffset != -1)\n {\n MPPUtility.getByteArray(m_data, offset, blockRemainingSize, result, resultOffset);\n resultOffset += blockRemainingSize;\n offset += blockRemainingSize;\n itemRemainingSize -= blockRemainingSize;\n\n if (offset != nextBlockOffset)\n {\n offset = nextBlockOffset;\n }\n\n nextBlockOffset = MPPUtility.getInt(m_data, offset);\n offset += 4;\n blockRemainingSize = 32;\n }\n\n MPPUtility.getByteArray(m_data, offset, itemRemainingSize, result, resultOffset);\n }\n }\n }\n\n return (result);\n }", "protected void reportProgress(String taskDecription) {\n if (this.progress != null) {\n if (this.progress.isCanceled()) {\n // Only AbortCompilation can stop the compiler cleanly.\n // We check cancellation again following the call to compile.\n throw new AbortCompilation(true, null);\n }\n this.progress.setTaskName(taskDecription);\n }\n }", "public void setWeeklyDay(Day day, boolean value)\n {\n if (value)\n {\n m_days.add(day);\n }\n else\n {\n m_days.remove(day);\n }\n }", "public static String getParentId(String digest, String host) throws IOException {\n DockerClient dockerClient = null;\n try {\n dockerClient = getDockerClient(host);\n return dockerClient.inspectImageCmd(digest).exec().getParent();\n } finally {\n closeQuietly(dockerClient);\n }\n }", "public static base_responses link(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey linkresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tlinkresources[i] = new sslcertkey();\n\t\t\t\tlinkresources[i].certkey = resources[i].certkey;\n\t\t\t\tlinkresources[i].linkcertkeyname = resources[i].linkcertkeyname;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, linkresources,\"link\");\n\t\t}\n\t\treturn result;\n\t}" ]
Add the string representation of the given object to this sequence at the given index. The given indentation will be prepended to each line except the first one if the object has a multi-line string representation. @param object the to-be-appended object. @param indentation the indentation string that should be prepended. May not be <code>null</code>. @param index the index in the list of segments.
[ "protected void append(Object object, String indentation, int index) {\n\t\tif (indentation.length() == 0) {\n\t\t\tappend(object, index);\n\t\t\treturn;\n\t\t}\n\t\tif (object == null)\n\t\t\treturn;\n\t\tif (object instanceof String) {\n\t\t\tappend(indentation, (String)object, index);\n\t\t} else if (object instanceof StringConcatenation) {\n\t\t\tStringConcatenation other = (StringConcatenation) object;\n\t\t\tList<String> otherSegments = other.getSignificantContent();\n\t\t\tappendSegments(indentation, index, otherSegments, other.lineDelimiter);\n\t\t} else if (object instanceof StringConcatenationClient) {\n\t\t\tStringConcatenationClient other = (StringConcatenationClient) object;\n\t\t\tother.appendTo(new IndentedTarget(this, indentation, index));\n\t\t} else {\n\t\t\tfinal String text = getStringRepresentation(object);\n\t\t\tif (text != null) {\n\t\t\t\tappend(indentation, text, index);\n\t\t\t}\n\t\t}\n\t}" ]
[ "private String appendXmlEndingTag(String value) {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"</\").append(value).append(\">\");\n\r\n return sb.toString();\r\n }", "public static <T> String listToString(List<T> list, final boolean justValue) {\r\n return listToString(list, justValue, null);\r\n }", "public Note add(String photoId, Note note) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD);\r\n\r\n parameters.put(\"photo_id\", photoId);\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\r\n Element noteElement = response.getPayload();\r\n note.setId(noteElement.getAttribute(\"id\"));\r\n return note;\r\n }", "public RedwoodConfiguration rootHandler(final LogRecordHandler handler){\r\n tasks.add(new Runnable(){ public void run(){ Redwood.appendHandler(handler); } });\r\n Redwood.appendHandler(handler);\r\n return this;\r\n }", "public static RowColumn toRowColumn(Key key) {\n if (key == null) {\n return RowColumn.EMPTY;\n }\n if ((key.getRow() == null) || key.getRow().getLength() == 0) {\n return RowColumn.EMPTY;\n }\n Bytes row = ByteUtil.toBytes(key.getRow());\n if ((key.getColumnFamily() == null) || key.getColumnFamily().getLength() == 0) {\n return new RowColumn(row);\n }\n Bytes cf = ByteUtil.toBytes(key.getColumnFamily());\n if ((key.getColumnQualifier() == null) || key.getColumnQualifier().getLength() == 0) {\n return new RowColumn(row, new Column(cf));\n }\n Bytes cq = ByteUtil.toBytes(key.getColumnQualifier());\n if ((key.getColumnVisibility() == null) || key.getColumnVisibility().getLength() == 0) {\n return new RowColumn(row, new Column(cf, cq));\n }\n Bytes cv = ByteUtil.toBytes(key.getColumnVisibility());\n return new RowColumn(row, new Column(cf, cq, cv));\n }", "public static <K, V> Map<K, V> immutableMapView(Map<K, V> map) {\n if (map instanceof ImmutableMap<?, ?>) {\n return map;\n }\n return Collections.unmodifiableMap(map);\n }", "@Override\n\tpublic Integer getPrefixLengthForSingleBlock() {\n\t\tint count = getDivisionCount();\n\t\tint totalPrefix = 0;\n\t\tfor(int i = 0; i < count; i++) {\n\t\t\tAddressDivisionBase div = getDivision(i);\n\t\t\tInteger divPrefix = div.getPrefixLengthForSingleBlock();\n\t\t\tif(divPrefix == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\ttotalPrefix += divPrefix;\n\t\t\tif(divPrefix < div.getBitCount()) {\n\t\t\t\t//remaining segments must be full range or we return null\n\t\t\t\tfor(i++; i < count; i++) {\n\t\t\t\t\tAddressDivisionBase laterDiv = getDivision(i);\n\t\t\t\t\tif(!laterDiv.isFullRange()) {\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn cacheBits(totalPrefix);\n\t}", "protected void queryTimerEnd(String sql, long queryStartTime) {\r\n\t\tif ((this.queryExecuteTimeLimit != 0) \r\n\t\t\t\t&& (this.connectionHook != null)){\r\n\t\t\tlong timeElapsed = (System.nanoTime() - queryStartTime);\r\n\t\t\t\r\n\t\t\tif (timeElapsed > this.queryExecuteTimeLimit){\r\n\t\t\t\tthis.connectionHook.onQueryExecuteTimeLimitExceeded(this.connectionHandle, this, sql, this.logParams, timeElapsed);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif (this.statisticsEnabled){\r\n\t\t\tthis.statistics.incrementStatementsExecuted();\r\n\t\t\tthis.statistics.addStatementExecuteTime(System.nanoTime() - queryStartTime);\r\n\t\t\t\r\n\t\t}\r\n\r\n\t}", "public final void setWeeksOfMonth(SortedSet<WeekOfMonth> weeksOfMonth) {\n\n m_weeksOfMonth.clear();\n if (null != weeksOfMonth) {\n m_weeksOfMonth.addAll(weeksOfMonth);\n }\n\n }" ]
Parse a currency symbol position from a string representation. @param value String representation @return CurrencySymbolPosition instance
[ "public static final CurrencySymbolPosition parseCurrencySymbolPosition(String value)\n {\n CurrencySymbolPosition result = MAP_TO_CURRENCY_SYMBOL_POSITION.get(value);\n result = result == null ? CurrencySymbolPosition.BEFORE_WITH_SPACE : result;\n return result;\n }" ]
[ "@RequestMapping(value = \"api/servergroup\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getServerGroups(Model model,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"search\", required = false) String search,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n\n List<ServerGroup> serverGroups = ServerRedirectService.getInstance().tableServerGroups(profileId);\n\n if (search != null) {\n Iterator<ServerGroup> iterator = serverGroups.iterator();\n while (iterator.hasNext()) {\n ServerGroup serverGroup = iterator.next();\n if (!serverGroup.getName().toLowerCase().contains(search.toLowerCase())) {\n iterator.remove();\n }\n }\n }\n HashMap<String, Object> returnJson = Utils.getJQGridJSON(serverGroups, \"servergroups\");\n return returnJson;\n }", "public Metadata replace(String path, String value) {\n this.values.set(this.pathToProperty(path), value);\n this.addOp(\"replace\", path, value);\n return this;\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 writeIntegerField(String fieldName, Object value) throws IOException\n {\n int val = ((Number) value).intValue();\n if (val != 0)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }", "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}", "@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public List<HazeltaskTask<G>> shutdownNow() {\n\t return (List<HazeltaskTask<G>>) (List) localExecutorPool.shutdownNow();\n\t}", "public void writeNameValuePair(String name, long value) throws IOException\n {\n internalWriteNameValuePair(name, Long.toString(value));\n }", "public static systemcore get(nitro_service service) throws Exception{\n\t\tsystemcore obj = new systemcore();\n\t\tsystemcore[] response = (systemcore[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "private void processScheduleOptions()\n {\n List<Row> rows = getRows(\"schedoptions\", \"proj_id\", m_projectID);\n if (rows.isEmpty() == false)\n {\n Row row = rows.get(0);\n Map<String, Object> customProperties = new HashMap<String, Object>();\n customProperties.put(\"LagCalendar\", row.getString(\"sched_calendar_on_relationship_lag\"));\n customProperties.put(\"RetainedLogic\", Boolean.valueOf(row.getBoolean(\"sched_retained_logic\")));\n customProperties.put(\"ProgressOverride\", Boolean.valueOf(row.getBoolean(\"sched_progress_override\")));\n customProperties.put(\"IgnoreOtherProjectRelationships\", row.getString(\"sched_outer_depend_type\"));\n customProperties.put(\"StartToStartLagCalculationType\", Boolean.valueOf(row.getBoolean(\"sched_lag_early_start_flag\")));\n m_reader.getProject().getProjectProperties().setCustomProperties(customProperties);\n }\n }" ]
Use this API to fetch nssimpleacl resources of given names .
[ "public static nssimpleacl[] get(nitro_service service, String aclname[]) throws Exception{\n\t\tif (aclname !=null && aclname.length>0) {\n\t\t\tnssimpleacl response[] = new nssimpleacl[aclname.length];\n\t\t\tnssimpleacl obj[] = new nssimpleacl[aclname.length];\n\t\t\tfor (int i=0;i<aclname.length;i++) {\n\t\t\t\tobj[i] = new nssimpleacl();\n\t\t\t\tobj[i].set_aclname(aclname[i]);\n\t\t\t\tresponse[i] = (nssimpleacl) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}" ]
[ "public static <T extends Comparable<T>> int compareLists(List<T> list1, List<T> list2) {\r\n if (list1 == null && list2 == null)\r\n return 0;\r\n if (list1 == null || list2 == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n int size1 = list1.size();\r\n int size2 = list2.size();\r\n int size = Math.min(size1, size2);\r\n for (int i = 0; i < size; i++) {\r\n int c = list1.get(i).compareTo(list2.get(i));\r\n if (c != 0)\r\n return c;\r\n }\r\n if (size1 < size2)\r\n return -1;\r\n if (size1 > size2)\r\n return 1;\r\n return 0;\r\n }", "public Collection<BoxGroupMembership.Info> getMemberships() {\n final BoxAPIConnection api = this.getAPI();\n final String groupID = this.getID();\n\n Iterable<BoxGroupMembership.Info> iter = new Iterable<BoxGroupMembership.Info>() {\n public Iterator<BoxGroupMembership.Info> iterator() {\n URL url = MEMBERSHIPS_URL_TEMPLATE.build(api.getBaseURL(), groupID);\n return new BoxGroupMembershipIterator(api, url);\n }\n };\n\n // We need to iterate all results because this method must return a Collection. This logic should be removed in\n // the next major version, and instead return the Iterable directly.\n Collection<BoxGroupMembership.Info> memberships = new ArrayList<BoxGroupMembership.Info>();\n for (BoxGroupMembership.Info membership : iter) {\n memberships.add(membership);\n }\n return memberships;\n }", "public void rotateWithPivot(float w, float x, float y, float z,\n float pivotX, float pivotY, float pivotZ) {\n getTransform().rotateWithPivot(w, x, y, z, pivotX, pivotY, pivotZ);\n if (mTransformCache.rotateWithPivot(w, x, y, z, pivotX, pivotY, pivotZ)) {\n onTransformChanged();\n }\n }", "private SynchroTable readTableHeader(byte[] header)\n {\n SynchroTable result = null;\n String tableName = DatatypeConverter.getSimpleString(header, 0);\n if (!tableName.isEmpty())\n {\n int offset = DatatypeConverter.getInt(header, 40);\n result = new SynchroTable(tableName, offset);\n }\n return result;\n }", "public void writeNameValuePair(String name, int value) throws IOException\n {\n internalWriteNameValuePair(name, Integer.toString(value));\n }", "public static JasperPrint generateJasperPrint(DynamicReport dr, LayoutManager layoutManager, JRDataSource ds, Map<String, Object> _parameters) throws JRException {\n log.info(\"generating JasperPrint\");\n JasperPrint jp;\n\n\n JasperReport jr = DynamicJasperHelper.generateJasperReport(dr, layoutManager, _parameters);\n jp = JasperFillManager.fillReport(jr, _parameters, ds);\n\n return jp;\n }", "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 BoxFolder.Info restoreFolder(String folderID, String newName, String newParentID) {\n JsonObject requestJSON = new JsonObject();\n\n if (newName != null) {\n requestJSON.add(\"name\", newName);\n }\n\n if (newParentID != null) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", newParentID);\n requestJSON.add(\"parent\", parent);\n }\n\n URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxJSONRequest request = new BoxJSONRequest(this.api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get(\"id\").asString());\n return restoredFolder.new Info(responseJSON);\n }", "public static URL findConfigResource(String resourceName) {\n if (Strings.isNullOrEmpty(resourceName)) {\n return null;\n }\n\n final URL url = resourceName.startsWith(ROOT) ? DefaultConfiguration.class.getResource(resourceName)\n : DefaultConfiguration.class.getResource(ROOT + resourceName);\n\n if (url != null) {\n return url;\n }\n\n // This is useful to get resource under META-INF directory\n String[] resourceNamePrefix = new String[] {\"META-INF/fabric8/\", \"META-INF/fabric8/\"};\n\n for (String resource : resourceNamePrefix) {\n String fullResourceName = resource + resourceName;\n\n URL candidate = KubernetesResourceLocator.class.getResource(fullResourceName.startsWith(ROOT) ? fullResourceName : ROOT + fullResourceName);\n if (candidate != null) {\n return candidate;\n }\n }\n\n return null;\n }" ]
Should be called each frame.
[ "public synchronized void tick() {\n long currentTime = GVRTime.getMilliTime();\n long cutoffTime = currentTime - BUFFER_SECONDS * 1000;\n ListIterator<Long> it = mTimestamps.listIterator();\n while (it.hasNext()) {\n Long timestamp = it.next();\n if (timestamp < cutoffTime) {\n it.remove();\n } else {\n break;\n }\n }\n\n mTimestamps.add(currentTime);\n mStatColumn.addValue(((float)mTimestamps.size()) / BUFFER_SECONDS);\n }" ]
[ "public void diffUpdate(List<T> newList) {\n if (getCollection().size() == 0) {\n addAll(newList);\n notifyDataSetChanged();\n } else {\n DiffCallback diffCallback = new DiffCallback(collection, newList);\n DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);\n clear();\n addAll(newList);\n diffResult.dispatchUpdatesTo(this);\n }\n }", "protected Boolean getIgnoreReleaseDate() {\n\n Boolean isIgnoreReleaseDate = parseOptionalBooleanValue(m_configObject, JSON_KEY_IGNORE_RELEASE_DATE);\n return (null == isIgnoreReleaseDate) && (m_baseConfig != null)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getIgnoreReleaseDate())\n : isIgnoreReleaseDate;\n }", "public static CallSite bootstrapCurrent(Lookup caller, String name, MethodType type) {\n return realBootstrap(caller, name, CALL_TYPES.METHOD.ordinal(), type, false, true, false);\n }", "public static <E> Set<E> setify(ObjectMapper mapper, Object source, Class<E> targetElementType) {\n return (Set<E>) collectify(mapper, source, Set.class, targetElementType);\n }", "public static authenticationvserver_stats get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_stats obj = new authenticationvserver_stats();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_stats response = (authenticationvserver_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "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 }", "public boolean checkContains(String uri, String[] patterns) {\n\t\tfor (String pattern : patterns) {\n\t\t\tif (pattern.length() > 0) {\n\t\t\t\tif (uri.contains(pattern)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public static DMatrixRMaj triangularUpper(int dimen , int hessenberg , double min , double max , Random rand )\n {\n if( hessenberg < 0 )\n throw new RuntimeException(\"hessenberg must be more than or equal to 0\");\n\n double range = max-min;\n\n DMatrixRMaj A = new DMatrixRMaj(dimen,dimen);\n\n for( int i = 0; i < dimen; i++ ) {\n int start = i <= hessenberg ? 0 : i-hessenberg;\n\n for( int j = start; j < dimen; j++ ) {\n A.set(i,j, rand.nextDouble()*range+min);\n }\n\n }\n\n return A;\n }", "public static nstimer_binding get(nitro_service service, String name) throws Exception{\n\t\tnstimer_binding obj = new nstimer_binding();\n\t\tobj.set_name(name);\n\t\tnstimer_binding response = (nstimer_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Removes the specified type from the frame.
[ "public static <T extends WindupVertexFrame> WindupVertexFrame removeTypeFromModel(GraphContext graphContext, WindupVertexFrame frame, Class<T> type)\n {\n Vertex vertex = frame.getElement();\n graphContext.getGraphTypeManager().removeTypeFromElement(type, vertex);\n return graphContext.getFramed().frameElement(vertex, WindupVertexFrame.class);\n }" ]
[ "private static MenuDrawer createMenuDrawer(Activity activity, int dragMode, Position position, Type type) {\n MenuDrawer drawer;\n\n if (type == Type.STATIC) {\n drawer = new StaticDrawer(activity);\n\n } else if (type == Type.OVERLAY) {\n drawer = new OverlayDrawer(activity, dragMode);\n if (position == Position.LEFT || position == Position.START) {\n drawer.setupUpIndicator(activity);\n }\n\n } else {\n drawer = new SlidingDrawer(activity, dragMode);\n if (position == Position.LEFT || position == Position.START) {\n drawer.setupUpIndicator(activity);\n }\n }\n\n drawer.mDragMode = dragMode;\n drawer.setPosition(position);\n\n return drawer;\n }", "public void initialize(BinaryPackageControlFile packageControlFile) {\n set(\"Binary\", packageControlFile.get(\"Package\"));\n set(\"Source\", Utils.defaultString(packageControlFile.get(\"Source\"), packageControlFile.get(\"Package\")));\n set(\"Architecture\", packageControlFile.get(\"Architecture\"));\n set(\"Version\", packageControlFile.get(\"Version\"));\n set(\"Maintainer\", packageControlFile.get(\"Maintainer\"));\n set(\"Changed-By\", packageControlFile.get(\"Maintainer\"));\n set(\"Distribution\", packageControlFile.get(\"Distribution\"));\n\n for (Entry<String, String> entry : packageControlFile.getUserDefinedFields().entrySet()) {\n set(entry.getKey(), entry.getValue());\n }\n\n StringBuilder description = new StringBuilder();\n description.append(packageControlFile.get(\"Package\"));\n if (packageControlFile.get(\"Description\") != null) {\n description.append(\" - \");\n description.append(packageControlFile.getShortDescription());\n }\n set(\"Description\", description.toString());\n }", "public static base_response unset(nitro_service client, systemuser resource, String[] args) throws Exception{\n\t\tsystemuser unsetresource = new systemuser();\n\t\tunsetresource.username = resource.username;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "protected LayoutManager getLayOutManagerObj(ActionInvocation _invocation) {\n\t\tif (layoutManager == null || \"\".equals(layoutManager)){\n\t\t\tLOG.warn(\"No valid LayoutManager, using ClassicLayoutManager\");\n\t\t\treturn new ClassicLayoutManager();\n\t\t}\n\n\t\tObject los = conditionalParse(layoutManager, _invocation);\n\n\t\tif (los instanceof LayoutManager){\n\t\t\treturn (LayoutManager) los;\n\t\t}\n\n\t\tLayoutManager lo = null;\n\t\tif (los instanceof String){\n\t\t\tif (LAYOUT_CLASSIC.equalsIgnoreCase((String) los))\n\t\t\t\tlo = new ClassicLayoutManager();\n\t\t\telse if (LAYOUT_LIST.equalsIgnoreCase((String) los))\n\t\t\t\tlo = new ListLayoutManager();\n\t\t\telse {\n\t\t\t\ttry {\n\t\t\t\t\tlo = (LayoutManager) Class.forName((String) los).newInstance();\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLOG.warn(\"No valid LayoutManager: \" + e.getMessage(),e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lo;\n\t}", "public boolean remove(long key) {\n int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;\n Entry previous = null;\n Entry entry = table[index];\n while (entry != null) {\n Entry next = entry.next;\n if (entry.key == key) {\n if (previous == null) {\n table[index] = next;\n } else {\n previous.next = next;\n }\n size--;\n return true;\n }\n previous = entry;\n entry = next;\n }\n return false;\n }", "public static final String printDuration(Duration value)\n {\n return value == null ? null : Double.toString(value.getDuration());\n }", "public static auditsyslogpolicy_aaauser_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_aaauser_binding obj = new auditsyslogpolicy_aaauser_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_aaauser_binding response[] = (auditsyslogpolicy_aaauser_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public AirMapViewBuilder builder(AirMapViewTypes mapType) {\n switch (mapType) {\n case NATIVE:\n if (isNativeMapSupported) {\n return new NativeAirMapViewBuilder();\n }\n break;\n case WEB:\n return getWebMapViewBuilder();\n }\n throw new UnsupportedOperationException(\"Requested map type is not supported\");\n }", "public PeriodicEvent runEvery(Runnable task, float delay, float period,\n KeepRunning callback) {\n validateDelay(delay);\n validatePeriod(period);\n return new Event(task, delay, period, callback);\n }" ]
If a text contains double quotes, escape them. @param text the text to escape @return Escaped text or {@code null} if the text is null
[ "public static String escapeDoubleQuotesForJson(String text) {\n\t\tif ( text == null ) {\n\t\t\treturn null;\n\t\t}\n\t\tStringBuilder builder = new StringBuilder( text.length() );\n\t\tfor ( int i = 0; i < text.length(); i++ ) {\n\t\t\tchar c = text.charAt( i );\n\t\t\tswitch ( c ) {\n\t\t\t\tcase '\"':\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tbuilder.append( \"\\\\\" );\n\t\t\t\tdefault:\n\t\t\t\t\tbuilder.append( c );\n\t\t\t}\n\t\t}\n\t\treturn builder.toString();\n\t}" ]
[ "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 processStages() {\n\n // Locate the next step to execute.\n ModelNode primaryResponse = null;\n Step step;\n do {\n step = steps.get(currentStage).pollFirst();\n if (step == null) {\n\n if (currentStage == Stage.MODEL && addModelValidationSteps()) {\n continue;\n }\n // No steps remain in this stage; give subclasses a chance to check status\n // and approve moving to the next stage\n if (!tryStageCompleted(currentStage)) {\n // Can't continue\n resultAction = ResultAction.ROLLBACK;\n executeResultHandlerPhase(null);\n return;\n }\n // Proceed to the next stage\n if (currentStage.hasNext()) {\n currentStage = currentStage.next();\n if (currentStage == Stage.VERIFY) {\n // a change was made to the runtime. Thus, we must wait\n // for stability before resuming in to verify.\n try {\n awaitServiceContainerStability();\n } catch (InterruptedException e) {\n cancelled = true;\n handleContainerStabilityFailure(primaryResponse, e);\n executeResultHandlerPhase(null);\n return;\n } catch (TimeoutException te) {\n // The service container is in an unknown state; but we don't require restart\n // because rollback may allow the container to stabilize. We force require-restart\n // in the rollback handling if the container cannot stabilize (see OperationContextImpl.releaseStepLocks)\n //processState.setRestartRequired(); // don't use our restartRequired() method as this is not reversible in rollback\n handleContainerStabilityFailure(primaryResponse, te);\n executeResultHandlerPhase(null);\n return;\n }\n }\n }\n } else {\n // The response to the first step is what goes to the outside caller\n if (primaryResponse == null) {\n primaryResponse = step.response;\n }\n // Execute the step, but make sure we always finalize any steps\n Throwable toThrow = null;\n // Whether to return after try/finally\n boolean exit = false;\n try {\n CapabilityRegistry.RuntimeStatus stepStatus = getStepExecutionStatus(step);\n if (stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.NORMAL) {\n executeStep(step);\n } else {\n String header = stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.RESTART_REQUIRED\n ? OPERATION_REQUIRES_RESTART : OPERATION_REQUIRES_RELOAD;\n step.response.get(RESPONSE_HEADERS, header).set(true);\n }\n } catch (RuntimeException | Error re) {\n resultAction = ResultAction.ROLLBACK;\n toThrow = re;\n } finally {\n // See if executeStep put us in a state where we shouldn't do any more\n if (toThrow != null || !canContinueProcessing()) {\n // We're done.\n executeResultHandlerPhase(toThrow);\n exit = true; // we're on the return path\n }\n }\n if (exit) {\n return;\n }\n }\n } while (currentStage != Stage.DONE);\n\n assert primaryResponse != null; // else ModelControllerImpl executed an op with no steps\n\n // All steps ran and canContinueProcessing returned true for the last one, so...\n executeDoneStage(primaryResponse);\n }", "public MembersList<Member> getList(String groupId, Set<String> memberTypes, int perPage, int page) throws FlickrException {\r\n MembersList<Member> members = new MembersList<Member>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n\r\n parameters.put(\"group_id\", groupId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n if (memberTypes != null) {\r\n parameters.put(\"membertypes\", StringUtilities.join(memberTypes, \",\"));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element mElement = response.getPayload();\r\n members.setPage(mElement.getAttribute(\"page\"));\r\n members.setPages(mElement.getAttribute(\"pages\"));\r\n members.setPerPage(mElement.getAttribute(\"perpage\"));\r\n members.setTotal(mElement.getAttribute(\"total\"));\r\n\r\n NodeList mNodes = mElement.getElementsByTagName(\"member\");\r\n for (int i = 0; i < mNodes.getLength(); i++) {\r\n Element element = (Element) mNodes.item(i);\r\n members.add(parseMember(element));\r\n }\r\n return members;\r\n }", "private void processEncodedPayload() throws IOException {\n if (!readPayload) {\n payloadSpanCollector.reset();\n collect(payloadSpanCollector);\n Collection<byte[]> originalPayloadCollection = payloadSpanCollector\n .getPayloads();\n if (originalPayloadCollection.iterator().hasNext()) {\n byte[] payload = originalPayloadCollection.iterator().next();\n if (payload == null) {\n throw new IOException(\"no payload\");\n }\n MtasPayloadDecoder payloadDecoder = new MtasPayloadDecoder();\n payloadDecoder.init(startPosition(), payload);\n mtasPosition = payloadDecoder.getMtasPosition();\n } else {\n throw new IOException(\"no payload\");\n }\n }\n }", "public 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 static aaapreauthenticationpolicy_aaaglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\taaapreauthenticationpolicy_aaaglobal_binding obj = new aaapreauthenticationpolicy_aaaglobal_binding();\n\t\tobj.set_name(name);\n\t\taaapreauthenticationpolicy_aaaglobal_binding response[] = (aaapreauthenticationpolicy_aaaglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public int getPathId(String pathName, int profileId) {\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n // first get the pathId for the pathName/profileId\n int pathId = -1;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.GENERIC_ID + \" FROM \" + Constants.DB_TABLE_PATH\n + \" WHERE \" + Constants.PATH_PROFILE_PATHNAME + \"= ? \"\n + \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ?\"\n );\n queryStatement.setString(1, pathName);\n queryStatement.setInt(2, profileId);\n results = queryStatement.executeQuery();\n if (results.next()) {\n pathId = results.getInt(Constants.GENERIC_ID);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return pathId;\n }", "public void cache(Identity oid, Object obj)\r\n {\r\n if (oid != null && obj != null)\r\n {\r\n ObjectCache cache = getCache(oid, obj, METHOD_CACHE);\r\n if (cache != null)\r\n {\r\n cache.cache(oid, obj);\r\n }\r\n }\r\n }", "protected String getClasspath() throws IOException {\n List<String> classpath = new ArrayList<>();\n classpath.add(getBundleJarPath());\n classpath.addAll(getPluginsPath());\n return StringUtils.toString(classpath.toArray(new String[classpath.size()]), \" \");\n }" ]
A convenient way of creating a map on the fly. @param <K> the key type @param <V> the value type @param entries Map.Entry objects to be added to the map @return a LinkedHashMap with the supplied entries
[ "@SafeVarargs\n public static <K, V> Map<K, V> map(final Entry<? extends K, ? extends V>... entries) {\n final Map<K, V> map = new LinkedHashMap<K, V>(entries.length);\n for (final Entry<? extends K, ? extends V> entry : entries) {\n map.put(entry.getKey(), entry.getValue());\n }\n return map;\n }" ]
[ "private Variable createVariableInferred(TokenList.Token t0, Variable variableRight) {\n Variable result;\n\n if( t0.getType() == Type.WORD ) {\n switch( variableRight.getType()) {\n case MATRIX:\n alias(new DMatrixRMaj(1,1),t0.getWord());\n break;\n\n case SCALAR:\n if( variableRight instanceof VariableInteger) {\n alias(0,t0.getWord());\n } else {\n alias(1.0,t0.getWord());\n }\n break;\n\n case INTEGER_SEQUENCE:\n alias((IntegerSequence)null,t0.getWord());\n break;\n\n default:\n throw new RuntimeException(\"Type not supported for assignment: \"+variableRight.getType());\n }\n\n result = variables.get(t0.getWord());\n } else {\n result = t0.getVariable();\n }\n return result;\n }", "@Override\n public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {\n this.problemReporter.abortDueToInternalError(\n Messages.bind(Messages.abort_againstSourceModel, new String[] { String.valueOf(sourceTypes[0].getName()), String.valueOf(sourceTypes[0].getFileName()) }));\n }", "public void updateSchema(String migrationPath) {\n try {\n logger.info(\"Updating schema... \");\n int current_version = 0;\n\n // first check the current schema version\n HashMap<String, Object> configuration = getFirstResult(\"SELECT * FROM \" + Constants.DB_TABLE_CONFIGURATION +\n \" WHERE \" + Constants.DB_TABLE_CONFIGURATION_NAME + \" = \\'\" + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION + \"\\'\");\n\n if (configuration == null) {\n logger.info(\"Creating configuration table..\");\n // create configuration table\n executeUpdate(\"CREATE TABLE \"\n + Constants.DB_TABLE_CONFIGURATION\n + \" (\" + Constants.GENERIC_ID + \" INTEGER IDENTITY,\"\n + Constants.DB_TABLE_CONFIGURATION_NAME + \" VARCHAR(256),\"\n + Constants.DB_TABLE_CONFIGURATION_VALUE + \" VARCHAR(1024));\");\n\n executeUpdate(\"INSERT INTO \" + Constants.DB_TABLE_CONFIGURATION\n + \"(\" + Constants.DB_TABLE_CONFIGURATION_NAME + \",\" + Constants.DB_TABLE_CONFIGURATION_VALUE + \")\"\n + \" VALUES (\\'\"\n + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION\n + \"\\', '0');\");\n } else {\n logger.info(\"Getting current schema version..\");\n // get current version\n current_version = new Integer(configuration.get(\"VALUE\").toString());\n logger.info(\"Current schema version is {}\", current_version);\n }\n\n // loop through until we get up to the right schema version\n while (current_version < Constants.DB_CURRENT_SCHEMA_VERSION) {\n current_version++;\n\n // look for a schema file for this version\n logger.info(\"Updating to schema version {}\", current_version);\n String currentFile = migrationPath + \"/schema.\"\n + current_version;\n Resource migFile = new ClassPathResource(currentFile);\n BufferedReader in = new BufferedReader(new InputStreamReader(\n migFile.getInputStream()));\n\n String str;\n while ((str = in.readLine()) != null) {\n // execute each line\n if (str.length() > 0) {\n executeUpdate(str);\n }\n }\n in.close();\n }\n\n // update the configuration table with the correct version\n executeUpdate(\"UPDATE \" + Constants.DB_TABLE_CONFIGURATION\n + \" SET \" + Constants.DB_TABLE_CONFIGURATION_VALUE + \"='\" + current_version\n + \"' WHERE \" + Constants.DB_TABLE_CONFIGURATION_NAME + \"='\"\n + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION + \"';\");\n } catch (Exception e) {\n logger.info(\"Error in executeUpdate\");\n e.printStackTrace();\n }\n }", "@SuppressWarnings(\"unchecked\")\n public T toObject(byte[] bytes) {\n try {\n return (T) new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject();\n } catch(IOException e) {\n throw new SerializationException(e);\n } catch(ClassNotFoundException c) {\n throw new SerializationException(c);\n }\n }", "@JsonProperty(\"descriptions\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, TermImpl> getDescriptionUpdates() {\n \treturn getMonolingualUpdatedValues(newDescriptions);\n }", "final public void addPositionRange(int start, int end) {\n if (tokenPosition == null) {\n tokenPosition = new MtasPosition(start, end);\n } else {\n int[] positions = new int[end - start + 1];\n for (int i = start; i <= end; i++) {\n positions[i - start] = i;\n }\n tokenPosition.add(positions);\n }\n }", "private List<UDFAssignmentType> writeUDFType(FieldTypeClass type, FieldContainer mpxj)\n {\n List<UDFAssignmentType> out = new ArrayList<UDFAssignmentType>();\n for (CustomField cf : m_sortedCustomFieldsList)\n {\n FieldType fieldType = cf.getFieldType();\n if (fieldType != null && type == fieldType.getFieldTypeClass())\n {\n Object value = mpxj.getCachedValue(fieldType);\n if (FieldTypeHelper.valueIsNotDefault(fieldType, value))\n {\n UDFAssignmentType udf = m_factory.createUDFAssignmentType();\n udf.setTypeObjectId(FieldTypeHelper.getFieldID(fieldType));\n setUserFieldValue(udf, fieldType.getDataType(), value);\n out.add(udf);\n }\n }\n }\n return out;\n }", "private Integer getOutlineLevel(Task task)\n {\n String value = task.getWBS();\n Integer result = Integer.valueOf(1);\n if (value != null && value.length() > 0)\n {\n String[] path = WBS_SPLIT_REGEX.split(value);\n result = Integer.valueOf(path.length);\n }\n return result;\n }", "private ModelNode parseAddress(final String profileName, final String inputAddress) {\n final ModelNode result = new ModelNode();\n if (profileName != null) {\n result.add(ServerOperations.PROFILE, profileName);\n }\n String[] parts = inputAddress.split(\",\");\n for (String part : parts) {\n String[] address = part.split(\"=\");\n if (address.length != 2) {\n throw new RuntimeException(part + \" is not a valid address segment\");\n }\n result.add(address[0], address[1]);\n }\n return result;\n }" ]
Parses the result and returns the failure description. @param result the result of executing an operation @return the failure description if defined, otherwise a new undefined model node @throws IllegalArgumentException if the outcome of the operation was successful
[ "public static ModelNode getFailureDescription(final ModelNode result) {\n if (isSuccessfulOutcome(result)) {\n throw ControllerClientLogger.ROOT_LOGGER.noFailureDescription();\n }\n if (result.hasDefined(FAILURE_DESCRIPTION)) {\n return result.get(FAILURE_DESCRIPTION);\n }\n return new ModelNode();\n }" ]
[ "public void unlock() {\n\n for (Locale l : m_lockedBundleFiles.keySet()) {\n LockedFile f = m_lockedBundleFiles.get(l);\n f.tryUnlock();\n }\n if (null != m_descFile) {\n m_descFile.tryUnlock();\n }\n }", "public static boolean lower( double[]T , int indexT , int n ) {\n double el_ii;\n double div_el_ii=0;\n\n for( int i = 0; i < n; i++ ) {\n for( int j = i; j < n; j++ ) {\n double sum = T[ indexT + j*n+i];\n\n // todo optimize\n for( int k = 0; k < i; k++ ) {\n sum -= T[ indexT + i*n+k] * T[ indexT + j*n+k];\n }\n\n if( i == j ) {\n // is it positive-definite?\n if( sum <= 0.0 )\n return false;\n\n el_ii = Math.sqrt(sum);\n T[ indexT + i*n+i] = el_ii;\n div_el_ii = 1.0/el_ii;\n } else {\n T[ indexT + j*n+i] = sum*div_el_ii;\n }\n }\n }\n\n return true;\n }", "public static OptionalString ofNullable(ResourceKey key, String value) {\n return new GenericOptionalString(RUNTIME_SOURCE, key, value);\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 }", "public static final String getUnicodeString(byte[] data, int offset)\n {\n int length = getUnicodeStringLengthInBytes(data, offset);\n return length == 0 ? \"\" : new String(data, offset, length, CharsetHelper.UTF16LE);\n }", "public <T> T getNodeMetaData(Object key) {\n if (metaDataMap == null) {\n return (T) null;\n }\n return (T) metaDataMap.get(key);\n }", "public Project dependsOnArtifact(Artifact artifact)\n {\n Project project = new Project();\n project.setArtifact(artifact); \n project.setInputVariablesName(inputVarName);\n return project;\n }", "public Set<D> getMatchedDeclaration() {\n Set<D> bindedSet = new HashSet<D>();\n for (Map.Entry<ServiceReference<D>, Boolean> e : declarations.entrySet()) {\n if (e.getValue()) {\n bindedSet.add(getDeclaration(e.getKey()));\n }\n }\n return bindedSet;\n }", "private IndexedContainer createContainerForBundleWithDescriptor() throws IOException, CmsException {\n\n IndexedContainer container = new IndexedContainer();\n\n // create properties\n container.addContainerProperty(TableProperty.KEY, String.class, \"\");\n container.addContainerProperty(TableProperty.DESCRIPTION, String.class, \"\");\n container.addContainerProperty(TableProperty.DEFAULT, String.class, \"\");\n container.addContainerProperty(TableProperty.TRANSLATION, String.class, \"\");\n\n // add entries\n SortedProperties localization = getLocalization(m_locale);\n CmsXmlContentValueSequence messages = m_descContent.getValueSequence(Descriptor.N_MESSAGE, Descriptor.LOCALE);\n String descValue;\n boolean hasDescription = false;\n String defaultValue;\n boolean hasDefault = false;\n for (int i = 0; i < messages.getElementCount(); i++) {\n\n String prefix = messages.getValue(i).getPath() + \"/\";\n Object itemId = container.addItem();\n Item item = container.getItem(itemId);\n String key = m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).getStringValue(m_cms);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n String translation = localization.getProperty(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == translation ? \"\" : translation);\n descValue = m_descContent.getValue(prefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).getStringValue(\n m_cms);\n item.getItemProperty(TableProperty.DESCRIPTION).setValue(descValue);\n hasDescription = hasDescription || !descValue.isEmpty();\n defaultValue = m_descContent.getValue(prefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).getStringValue(\n m_cms);\n item.getItemProperty(TableProperty.DEFAULT).setValue(defaultValue);\n hasDefault = hasDefault || !defaultValue.isEmpty();\n }\n\n m_hasDefault = hasDefault;\n m_hasDescription = hasDescription;\n return container;\n\n }" ]
Gets a list of registered docker images from the images cache, if it has been registered to the cache for a specific build-info ID and if a docker manifest has been captured for it by the build-info proxy. @param buildInfoId @return
[ "public static List<DockerImage> getImagesByBuildId(int buildInfoId) {\n List<DockerImage> list = new ArrayList<DockerImage>();\n Iterator<DockerImage> it = images.iterator();\n while (it.hasNext()) {\n DockerImage image = it.next();\n if (image.getBuildInfoId() == buildInfoId && image.hasManifest()) {\n list.add(image);\n }\n }\n return list;\n }" ]
[ "public static Command newInsert(Object object,\n String outIdentifier) {\n return getCommandFactoryProvider().newInsert( object,\n outIdentifier );\n }", "public CustomHeadersInterceptor addHeader(String name, String value) {\n if (!this.headers.containsKey(name)) {\n this.headers.put(name, new ArrayList<String>());\n }\n this.headers.get(name).add(value);\n return this;\n }", "void publish() {\n assert publishedFullRegistry != null : \"Cannot write directly to main registry\";\n\n writeLock.lock();\n try {\n if (!modified) {\n return;\n }\n publishedFullRegistry.writeLock.lock();\n try {\n publishedFullRegistry.clear(true);\n copy(this, publishedFullRegistry);\n pendingRemoveCapabilities.clear();\n pendingRemoveRequirements.clear();\n modified = false;\n } finally {\n publishedFullRegistry.writeLock.unlock();\n }\n } finally {\n writeLock.unlock();\n }\n }", "@SuppressWarnings(\"unchecked\")\n public final FluentModelImplT withoutTag(String key) {\n if (this.inner().getTags() != null) {\n this.inner().getTags().remove(key);\n }\n return (FluentModelImplT) this;\n }", "public ModelSource resolveModel( Parent parent )\r\n throws UnresolvableModelException {\r\n\r\n Dependency parentDependency = new Dependency();\r\n parentDependency.setGroupId(parent.getGroupId());\r\n parentDependency.setArtifactId(parent.getArtifactId());\r\n parentDependency.setVersion(parent.getVersion());\r\n parentDependency.setClassifier(\"\");\r\n parentDependency.setType(\"pom\");\r\n\r\n Artifact parentArtifact = null;\r\n try\r\n {\r\n Iterable<ArtifactResult> artifactResults = depencencyResolver.resolveDependencies(\r\n projectBuildingRequest, singleton(parentDependency), null, null );\r\n Iterator<ArtifactResult> iterator = artifactResults.iterator();\r\n if (iterator.hasNext()) {\r\n parentArtifact = iterator.next().getArtifact();\r\n }\r\n } catch (DependencyResolverException e) {\r\n throw new UnresolvableModelException( e.getMessage(), parent.getGroupId(), parent.getArtifactId(),\r\n parent.getVersion(), e );\r\n }\r\n\r\n return resolveModel( parentArtifact.getGroupId(), parentArtifact.getArtifactId(), parentArtifact.getVersion() );\r\n }", "public void setEnterpriseDate(int index, Date value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_DATE, index), value);\n }", "public ConfigBuilder withHost(final String host) {\n if (host == null || \"\".equals(host)) {\n throw new IllegalArgumentException(\"host must not be null or empty: \" + host);\n }\n this.host = host;\n return this;\n }", "public static vlan_nsip_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tvlan_nsip_binding obj = new vlan_nsip_binding();\n\t\tobj.set_id(id);\n\t\tvlan_nsip_binding response[] = (vlan_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public int consume(Map<String, String> initialVars) {\r\n int result = 0;\n\r\n for (int i = 0; i < repeatNumber; i++) {\r\n result += super.consume(initialVars);\r\n }\n\r\n return result;\r\n }" ]
Moves the drawer to the position passed. @param position The position the content is moved to. @param velocity Optional velocity if called by releasing a drag event. @param animate Whether the move is animated.
[ "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 }" ]
[ "@Override\n public void removeStorageEngine(StorageEngine<ByteArray, byte[], byte[]> engine) {\n String storeName = engine.getName();\n BdbStorageEngine bdbEngine = (BdbStorageEngine) engine;\n\n synchronized(lock) {\n\n // Only cleanup the environment if it is per store. We cannot\n // cleanup a shared 'Environment' object\n if(useOneEnvPerStore) {\n\n Environment environment = this.environments.get(storeName);\n if(environment == null) {\n // Nothing to clean up.\n return;\n }\n\n // Remove from the set of unreserved stores if needed.\n if(this.unreservedStores.remove(environment)) {\n logger.info(\"Removed environment for store name: \" + storeName\n + \" from unreserved stores\");\n } else {\n logger.info(\"No environment found in unreserved stores for store name: \"\n + storeName);\n }\n\n // Try to delete the BDB directory associated\n File bdbDir = environment.getHome();\n if(bdbDir.exists() && bdbDir.isDirectory()) {\n String bdbDirPath = bdbDir.getPath();\n try {\n FileUtils.deleteDirectory(bdbDir);\n logger.info(\"Successfully deleted BDB directory : \" + bdbDirPath\n + \" for store name: \" + storeName);\n } catch(IOException e) {\n logger.error(\"Unable to delete BDB directory: \" + bdbDirPath\n + \" for store name: \" + storeName);\n }\n }\n\n // Remove the reference to BdbEnvironmentStats, which holds a\n // reference to the Environment\n BdbEnvironmentStats bdbEnvStats = bdbEngine.getBdbEnvironmentStats();\n this.aggBdbStats.unTrackEnvironment(bdbEnvStats);\n\n // Unregister the JMX bean for Environment\n if(voldemortConfig.isJmxEnabled()) {\n ObjectName name = JmxUtils.createObjectName(JmxUtils.getPackageName(bdbEnvStats.getClass()),\n storeName);\n // Un-register the environment stats mbean\n JmxUtils.unregisterMbean(name);\n }\n\n // Cleanup the environment\n environment.close();\n this.environments.remove(storeName);\n logger.info(\"Successfully closed the environment for store name : \" + storeName);\n\n }\n }\n }", "public Metadata replace(String path, String value) {\n this.values.set(this.pathToProperty(path), value);\n this.addOp(\"replace\", path, value);\n return this;\n }", "private void checkAllEnvelopes(PersistenceBroker broker)\r\n {\r\n Iterator iter = ((List) mvOrderOfIds.clone()).iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n // only non transient objects should be performed\r\n if(!mod.getModificationState().isTransient())\r\n {\r\n mod.markReferenceElements(broker);\r\n }\r\n }\r\n }", "private void calculateValueTextHeight() {\n Rect valueRect = new Rect();\n Rect legendRect = new Rect();\n String str = Utils.getFloatString(mFocusedPoint.getValue(), mShowDecimal) + (!mIndicatorTextUnit.isEmpty() ? \" \" + mIndicatorTextUnit : \"\");\n\n // calculate the boundaries for both texts\n mIndicatorPaint.getTextBounds(str, 0, str.length(), valueRect);\n mLegendPaint.getTextBounds(mFocusedPoint.getLegendLabel(), 0, mFocusedPoint.getLegendLabel().length(), legendRect);\n\n // calculate string positions in overlay\n mValueTextHeight = valueRect.height();\n mValueLabelY = (int) (mValueTextHeight + mIndicatorTopPadding);\n mLegendLabelY = (int) (mValueTextHeight + mIndicatorTopPadding + legendRect.height() + Utils.dpToPx(7.f));\n\n int chosenWidth = valueRect.width() > legendRect.width() ? valueRect.width() : legendRect.width();\n\n // check if text reaches over screen\n if (mFocusedPoint.getCoordinates().getX() + chosenWidth + mIndicatorLeftPadding > -Utils.getTranslationX(mDrawMatrixValues) + mGraphWidth) {\n mValueLabelX = (int) (mFocusedPoint.getCoordinates().getX() - (valueRect.width() + mIndicatorLeftPadding));\n mLegendLabelX = (int) (mFocusedPoint.getCoordinates().getX() - (legendRect.width() + mIndicatorLeftPadding));\n } else {\n mValueLabelX = mLegendLabelX = (int) (mFocusedPoint.getCoordinates().getX() + mIndicatorLeftPadding);\n }\n }", "private void add(int field)\n {\n if (field < m_flags.length)\n {\n if (m_flags[field] == false)\n {\n m_flags[field] = true;\n m_fields[m_count] = field;\n ++m_count;\n }\n }\n }", "public static CuratorFramework newCurator(String zookeepers, int timeout, String secret) {\n\n final ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 10);\n if (secret.isEmpty()) {\n return CuratorFrameworkFactory.newClient(zookeepers, timeout, timeout, retry);\n } else {\n return CuratorFrameworkFactory.builder().connectString(zookeepers)\n .connectionTimeoutMs(timeout).sessionTimeoutMs(timeout).retryPolicy(retry)\n .authorization(\"digest\", (\"fluo:\" + secret).getBytes(StandardCharsets.UTF_8))\n .aclProvider(new ACLProvider() {\n @Override\n public List<ACL> getDefaultAcl() {\n return CREATOR_ALL_ACL;\n }\n\n @Override\n public List<ACL> getAclForPath(String path) {\n switch (path) {\n case ZookeeperPath.ORACLE_GC_TIMESTAMP:\n // The garbage collection iterator running in Accumulo tservers needs to read this\n // value w/o authenticating.\n return PUBLICLY_READABLE_ACL;\n default:\n return CREATOR_ALL_ACL;\n }\n }\n }).build();\n }\n }", "public int compare(Object objA, Object objB)\r\n {\r\n String idAStr = ((FieldDescriptorDef)_fields.get(objA)).getProperty(\"id\");\r\n String idBStr = ((FieldDescriptorDef)_fields.get(objB)).getProperty(\"id\");\r\n int idA;\r\n int idB;\r\n\r\n try\r\n {\r\n idA = Integer.parseInt(idAStr);\r\n }\r\n catch (Exception ex)\r\n {\r\n return 1;\r\n }\r\n try\r\n {\r\n idB = Integer.parseInt(idBStr);\r\n }\r\n catch (Exception ex)\r\n {\r\n return -1;\r\n }\r\n return idA < idB ? -1 : (idA > idB ? 1 : 0);\r\n }", "public DesignDocument get(String id, String rev) {\r\n assertNotEmpty(id, \"id\");\r\n assertNotEmpty(id, \"rev\");\r\n return db.find(DesignDocument.class, ensureDesignPrefix(id), rev);\r\n }", "private static void checkPreconditions(final long min, final long max) {\n\t\tif( max < min ) {\n\t\t\tthrow new IllegalArgumentException(String.format(\"max (%d) should not be < min (%d)\", max, min));\n\t\t}\n\t}" ]
Returns the compact records for all teams to which user is assigned. @param user An identifier for the user. Can be one of an email address, the globally unique identifier for the user, or the keyword `me` to indicate the current user making the request. @return Request object
[ "public CollectionRequest<Team> findByUser(String user) {\n \n String path = String.format(\"/users/%s/teams\", user);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }" ]
[ "public boolean isWellKnownIPv4Translatable() { //rfc 6052 rfc 6144\n\t\t//64:ff9b::/96 prefix for auto ipv4/ipv6 translation\n\t\tif(getSegment(0).matches(0x64) && getSegment(1).matches(0xff9b)) {\n\t\t\tfor(int i=2; i<=5; i++) {\n\t\t\t\tif(!getSegment(i).isZero()) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "private RgbaColor withHsl(int index, float value) {\n float[] HSL = convertToHsl();\n HSL[index] = value;\n return RgbaColor.fromHsl(HSL);\n }", "public CollectionRequest<Project> tasks(String project) {\n \n String path = String.format(\"/projects/%s/tasks\", project);\n return new CollectionRequest<Project>(this, Project.class, path, \"GET\");\n }", "public <T> T get(Class<T> type) {\n return get(type.getName(), type);\n }", "public void addConverter(int index, IConverter converter) {\r\n\t\tconverterList.add(index, converter);\r\n\t\tif (converter instanceof IContainerConverter) {\r\n\t\t\tIContainerConverter containerConverter = (IContainerConverter) converter;\r\n\t\t\tif (containerConverter.getElementConverter() == null) {\r\n\t\t\t\tcontainerConverter.setElementConverter(elementConverter);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "public Date getBaselineFinish()\n {\n Object result = getCachedValue(TaskField.BASELINE_FINISH);\n if (result == null)\n {\n result = getCachedValue(TaskField.BASELINE_ESTIMATED_FINISH);\n }\n\n if (!(result instanceof Date))\n {\n result = null;\n }\n return (Date) result;\n }", "public static ClassLoader resolveClassLoaderForBeanProxy(String contextId, Class<?> proxiedType, TypeInfo typeInfo, ProxyServices proxyServices) {\n Class<?> superClass = typeInfo.getSuperClass();\n if (superClass.getName().startsWith(JAVA)) {\n ClassLoader cl = proxyServices.getClassLoader(proxiedType);\n if (cl == null) {\n cl = Thread.currentThread().getContextClassLoader();\n }\n return cl;\n }\n return Container.instance(contextId).services().get(ProxyServices.class).getClassLoader(superClass);\n }", "public static Command newQuery(String identifier,\n String name) {\n return getCommandFactoryProvider().newQuery( identifier,\n name );\n\n }", "public Script updateName(int id, String name) throws Exception {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SCRIPT +\n \" SET \" + Constants.SCRIPT_NAME + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, name);\n statement.setInt(2, id);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return this.getScript(id);\n }" ]
Update all the links of the DeclarationBinder. @param declarationBinderRef the ServiceReference<DeclarationBinder> of the DeclarationBinder
[ "public void updateLinks(ServiceReference<S> serviceReference) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n boolean isAlreadyLinked = declaration.getStatus().getServiceReferencesBounded().contains(serviceReference);\n boolean canBeLinked = linkerManagement.canBeLinked(declaration, serviceReference);\n if (isAlreadyLinked && !canBeLinked) {\n linkerManagement.unlink(declaration, serviceReference);\n } else if (!isAlreadyLinked && canBeLinked) {\n linkerManagement.link(declaration, serviceReference);\n }\n }\n }" ]
[ "protected static List<StackTraceElement> filterStackTrace(StackTraceElement[] stack) {\r\n List<StackTraceElement> filteredStack = new ArrayList<StackTraceElement>();\r\n\r\n int i = 2; // we can skip the first two (first is getStackTrace(), second is this method)\r\n while (i < stack.length) {\r\n boolean isLoggingClass = false;\r\n for (String loggingClass : loggingClasses) {\r\n String className = stack[i].getClassName();\r\n if (className.startsWith(loggingClass)) {\r\n isLoggingClass = true;\r\n break;\r\n }\r\n }\r\n if (!isLoggingClass) {\r\n filteredStack.add(stack[i]);\r\n }\r\n\r\n i += 1;\r\n }\r\n\r\n // if we didn't find anything, keep the full stack\r\n if (filteredStack.size() == 0) {\r\n return Arrays.asList(stack);\r\n }\r\n return filteredStack;\r\n }", "public static boolean isTypesProxyable(Iterable<? extends Type> types, ServiceRegistry services) {\n return getUnproxyableTypesException(types, services) == null;\n }", "public void pause(ServerActivityCallback requestCountListener) {\n if (paused) {\n throw ServerLogger.ROOT_LOGGER.serverAlreadyPaused();\n }\n this.paused = true;\n listenerUpdater.set(this, requestCountListener);\n if (activeRequestCountUpdater.get(this) == 0) {\n if (listenerUpdater.compareAndSet(this, requestCountListener, null)) {\n requestCountListener.done();\n }\n }\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 void setBorderWidth(int borderWidth) {\n\t\tthis.borderWidth = borderWidth;\n\t\tif(paintBorder != null)\n\t\t\tpaintBorder.setStrokeWidth(borderWidth);\n\t\trequestLayout();\n\t\tinvalidate();\n\t}", "public static List<String> toList(CharSequence self) {\n String s = self.toString();\n int size = s.length();\n List<String> answer = new ArrayList<String>(size);\n for (int i = 0; i < size; i++) {\n answer.add(s.substring(i, i + 1));\n }\n return answer;\n }", "@Override\n public T getById(Object id)\n {\n return context.getFramed().getFramedVertex(this.type, id);\n }", "public static Map<String, IDiagramPlugin>\n getLocalPluginsRegistry(ServletContext context) {\n if (LOCAL == null) {\n LOCAL = initializeLocalPlugins(context);\n }\n return LOCAL;\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 }" ]
Returns the coupon payment of the period with the given index. The analytic model is needed in case of floating bonds. @param periodIndex The index of the period of interest. @param model The model under which the product is valued. @return The value of the coupon payment in the given period.
[ "public double getCouponPayment(int periodIndex, AnalyticModel model) {\n\n\t\tForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName);\n\t\tif(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {\n\t\t\tthrow new IllegalArgumentException(\"No forward curve with name '\" + forwardCurveName + \"' was found in the model:\\n\" + model.toString());\n\t\t}\n\n\t\tdouble periodLength\t= schedule.getPeriodLength(periodIndex);\n\t\tdouble couponPayment=fixedCoupon ;\n\t\tif(forwardCurve != null ) {\n\t\t\tcouponPayment = floatingSpread+forwardCurve.getForward(model, schedule.getFixing(periodIndex));\n\t\t}\n\t\treturn couponPayment*periodLength;\n\t}" ]
[ "public static double J(int n, double x) {\r\n int j, m;\r\n double ax, bj, bjm, bjp, sum, tox, ans;\r\n boolean jsum;\r\n\r\n double ACC = 40.0;\r\n double BIGNO = 1.0e+10;\r\n double BIGNI = 1.0e-10;\r\n\r\n if (n == 0) return J0(x);\r\n if (n == 1) return J(x);\r\n\r\n ax = Math.abs(x);\r\n if (ax == 0.0) return 0.0;\r\n else if (ax > (double) n) {\r\n tox = 2.0 / ax;\r\n bjm = J0(ax);\r\n bj = J(ax);\r\n for (j = 1; j < n; j++) {\r\n bjp = j * tox * bj - bjm;\r\n bjm = bj;\r\n bj = bjp;\r\n }\r\n ans = bj;\r\n } else {\r\n tox = 2.0 / ax;\r\n m = 2 * ((n + (int) Math.sqrt(ACC * n)) / 2);\r\n jsum = false;\r\n bjp = ans = sum = 0.0;\r\n bj = 1.0;\r\n for (j = m; j > 0; j--) {\r\n bjm = j * tox * bj - bjp;\r\n bjp = bj;\r\n bj = bjm;\r\n if (Math.abs(bj) > BIGNO) {\r\n bj *= BIGNI;\r\n bjp *= BIGNI;\r\n ans *= BIGNI;\r\n sum *= BIGNI;\r\n }\r\n if (jsum) sum += bj;\r\n jsum = !jsum;\r\n if (j == n) ans = bjp;\r\n }\r\n sum = 2.0 * sum - bj;\r\n ans /= sum;\r\n }\r\n\r\n return x < 0.0 && n % 2 == 1 ? -ans : ans;\r\n }", "private File extractThriftFile(String artifactId, String fileName, Set<File> thriftFiles) {\n for (File thriftFile : thriftFiles) {\n boolean fileFound = false;\n if (fileName.equals(thriftFile.getName())) {\n for (String pathComponent : thriftFile.getPath().split(File.separator)) {\n if (pathComponent.equals(artifactId)) {\n fileFound = true;\n }\n }\n }\n\n if (fileFound) {\n return thriftFile;\n }\n }\n return null;\n }", "public ProductFactoryCascade<T> addFactoryBefore(ProductFactory<? extends T> factory) {\n\t\tArrayList<ProductFactory<? extends T>> factories = new ArrayList<ProductFactory<? extends T>>(this.factories.size()+1);\n\t\tfactories.addAll(this.factories);\n\t\tfactories.add(0, factory);\n\t\treturn new ProductFactoryCascade<>(factories);\n\t}", "public static base_responses clear(nitro_service client, Interface resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tInterface clearresources[] = new Interface[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tclearresources[i] = new Interface();\n\t\t\t\tclearresources[i].id = resources[i].id;\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 static Region create(String name, String label) {\n Region region = VALUES_BY_NAME.get(name.toLowerCase());\n if (region != null) {\n return region;\n } else {\n return new Region(name, label);\n }\n }", "public static final Date getFinishDate(byte[] data, int offset)\n {\n Date result;\n long days = getShort(data, offset);\n\n if (days == 0x8000)\n {\n result = null;\n }\n else\n {\n result = DateHelper.getDateFromLong(EPOCH + ((days - 1) * DateHelper.MS_PER_DAY));\n }\n\n return (result);\n }", "public void addColumnPair(String localColumn, String remoteColumn)\r\n {\r\n if (!_localColumns.contains(localColumn))\r\n { \r\n _localColumns.add(localColumn);\r\n }\r\n if (!_remoteColumns.contains(remoteColumn))\r\n { \r\n _remoteColumns.add(remoteColumn);\r\n }\r\n }", "public void setStartTime(final Date date) {\r\n\r\n if (!Objects.equals(m_model.getStart(), date)) {\r\n removeExceptionsOnChange(new Command() {\r\n\r\n public void execute() {\r\n\r\n m_model.setStart(date);\r\n setPatternDefaultValues(date);\r\n valueChanged();\r\n }\r\n });\r\n }\r\n\r\n }", "static Artifact resolveConstrained(MavenProject project, String gav, Pattern versionRegex,\n ArtifactResolver resolver)\n throws VersionRangeResolutionException, ArtifactResolutionException {\n boolean latest = gav.endsWith(\":LATEST\");\n if (latest || gav.endsWith(\":RELEASE\")) {\n Artifact a = new DefaultArtifact(gav);\n\n if (latest) {\n versionRegex = versionRegex == null ? ANY : versionRegex;\n } else {\n versionRegex = versionRegex == null ? ANY_NON_SNAPSHOT : versionRegex;\n }\n\n String upTo = project.getGroupId().equals(a.getGroupId()) && project.getArtifactId().equals(a.getArtifactId())\n ? project.getVersion()\n : null;\n\n return resolver.resolveNewestMatching(gav, upTo, versionRegex, latest, latest);\n } else {\n String projectGav = getProjectArtifactCoordinates(project, null);\n Artifact ret = null;\n\n if (projectGav.equals(gav)) {\n ret = findProjectArtifact(project);\n }\n\n return ret == null ? resolver.resolveArtifact(gav) : ret;\n }\n }" ]
Sets the HTML entity translator for all cells in the table. It will also remove any other translator set. Nothing will happen if the argument is null. @param htmlElementTranslator translator @return this to allow chaining
[ "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 IndirectionHandler createIndirectionHandler(PBKey brokerKey, Identity id)\r\n {\r\n Object args[] = {brokerKey, id};\r\n\r\n try\r\n {\r\n return (IndirectionHandler) getIndirectionHandlerConstructor().newInstance(args);\r\n }\r\n catch(InvocationTargetException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new indirection handler instance\", ex);\r\n }\r\n catch(InstantiationException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new indirection handler instance\", ex);\r\n }\r\n catch(IllegalAccessException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new indirection handler instance\", ex);\r\n }\r\n }", "public List<Shard> getShards() {\n InputStream response = null;\n try {\n response = client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).path(\"_shards\")\n .build());\n return getResponseList(response, client.getGson(), DeserializationTypes.SHARDS);\n } finally {\n close(response);\n }\n }", "final public void addPositionRange(int start, int end) {\n if (tokenPosition == null) {\n tokenPosition = new MtasPosition(start, end);\n } else {\n int[] positions = new int[end - start + 1];\n for (int i = start; i <= end; i++) {\n positions[i - start] = i;\n }\n tokenPosition.add(positions);\n }\n }", "public String getUniformDescriptor(GVRContext ctx)\n {\n if (mShaderTemplate == null)\n {\n mShaderTemplate = makeTemplate(ID, ctx);\n ctx.getShaderManager().addShaderID(this);\n }\n return mShaderTemplate.getUniformDescriptor();\n }", "private void countPropertyMain(UsageStatistics usageStatistics,\n\t\t\tPropertyIdValue property, int count) {\n\t\taddPropertyCounters(usageStatistics, property);\n\t\tusageStatistics.propertyCountsMain.put(property,\n\t\t\t\tusageStatistics.propertyCountsMain.get(property) + count);\n\t}", "public void addConverter(int index, IConverter converter) {\r\n\t\tconverterList.add(index, converter);\r\n\t\tif (converter instanceof IContainerConverter) {\r\n\t\t\tIContainerConverter containerConverter = (IContainerConverter) converter;\r\n\t\t\tif (containerConverter.getElementConverter() == null) {\r\n\t\t\t\tcontainerConverter.setElementConverter(elementConverter);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "public void writeFinalResults() {\n\t\tprintStatus();\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"gender-ratios.csv\"))) {\n\n\t\t\tout.print(\"Site key,pages total,pages on humans,pages on humans with gender\");\n\t\t\tfor (EntityIdValue gender : this.genderNamesList) {\n\t\t\t\tout.print(\",\" + this.genderNames.get(gender) + \" (\"\n\t\t\t\t\t\t+ gender.getId() + \")\");\n\t\t\t}\n\t\t\tout.println();\n\n\t\t\tList<SiteRecord> siteRecords = new ArrayList<>(\n\t\t\t\t\tthis.siteRecords.values());\n\t\t\tCollections.sort(siteRecords, new SiteRecordComparator());\n\t\t\tfor (SiteRecord siteRecord : siteRecords) {\n\t\t\t\tout.print(siteRecord.siteKey + \",\" + siteRecord.pageCount + \",\"\n\t\t\t\t\t\t+ siteRecord.humanPageCount + \",\"\n\t\t\t\t\t\t+ siteRecord.humanGenderPageCount);\n\n\t\t\t\tfor (EntityIdValue gender : this.genderNamesList) {\n\t\t\t\t\tif (siteRecord.genderCounts.containsKey(gender)) {\n\t\t\t\t\t\tout.print(\",\" + siteRecord.genderCounts.get(gender));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tout.print(\",0\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tout.println();\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "public static double Sin(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return x - (x * x * x) / 6D;\r\n } else {\r\n\r\n double mult = x * x * x;\r\n double fact = 6;\r\n double sign = 1;\r\n int factS = 5;\r\n double result = x - mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += sign * (mult / fact);\r\n sign *= -1;\r\n }\r\n\r\n return result;\r\n }\r\n }", "public static Calendar parseDividendDate(String date) {\n if (!Utils.isParseable(date)) {\n return null;\n }\n date = date.trim();\n SimpleDateFormat format = new SimpleDateFormat(Utils.getDividendDateFormat(date), Locale.US);\n format.setTimeZone(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n try {\n Calendar today = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n Calendar parsedDate = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n parsedDate.setTime(format.parse(date));\n\n if (parsedDate.get(Calendar.YEAR) == 1970) {\n // Not really clear which year the dividend date is... making a reasonable guess.\n int monthDiff = parsedDate.get(Calendar.MONTH) - today.get(Calendar.MONTH);\n int year = today.get(Calendar.YEAR);\n if (monthDiff > 6) {\n year -= 1;\n } else if (monthDiff < -6) {\n year += 1;\n }\n parsedDate.set(Calendar.YEAR, year);\n }\n\n return parsedDate;\n } catch (ParseException ex) {\n log.warn(\"Failed to parse dividend date: \" + date);\n log.debug(\"Failed to parse dividend date: \" + date, ex);\n return null;\n }\n }" ]
Retrieves the notes text for this resource. @return notes text
[ "public String getNotes()\n {\n String notes = (String) getCachedValue(ResourceField.NOTES);\n return (notes == null ? \"\" : notes);\n }" ]
[ "private void applyProperties(AssociationKey associationKey, Tuple associationRow, Relationship relationship) {\n\t\tString[] indexColumns = associationKey.getMetadata().getRowKeyIndexColumnNames();\n\t\tfor ( int i = 0; i < indexColumns.length; i++ ) {\n\t\t\tString propertyName = indexColumns[i];\n\t\t\tObject propertyValue = associationRow.get( propertyName );\n\t\t\trelationship.setProperty( propertyName, propertyValue );\n\t\t}\n\t}", "private void ensureNoTableInfoIfNoRepositoryInfo(ClassDescriptorDef classDef, String checkLevel)\r\n {\r\n if (!classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true))\r\n {\r\n classDef.setProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, \"false\");\r\n }\r\n }", "public static void numberToBytes(int number, byte[] buffer, int start, int length) {\n for (int index = start + length - 1; index >= start; index--) {\n buffer[index] = (byte)(number & 0xff);\n number = number >> 8;\n }\n }", "public static long getVisibilityCacheWeight(FluoConfiguration conf) {\n long size = conf.getLong(VISIBILITY_CACHE_WEIGHT, VISIBILITY_CACHE_WEIGHT_DEFAULT);\n if (size <= 0) {\n throw new IllegalArgumentException(\n \"Cache size must be positive for \" + VISIBILITY_CACHE_WEIGHT);\n }\n return size;\n }", "private void ensurePrecisionAndScale(FieldDescriptorDef fieldDef, String checkLevel)\r\n {\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, null);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, null);\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_PRECISION))\r\n {\r\n String defaultPrecision = JdbcTypeHelper.getDefaultPrecisionFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n\r\n if (defaultPrecision != null)\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureLength\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has no precision setting though its jdbc type requires it (in most databases); using default precision of \"+defaultPrecision);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, defaultPrecision);\r\n }\r\n else if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_SCALE))\r\n {\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, \"1\");\r\n }\r\n }\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_SCALE))\r\n {\r\n String defaultScale = JdbcTypeHelper.getDefaultScaleFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n\r\n if (defaultScale != null)\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureLength\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has no scale setting though its jdbc type requires it (in most databases); using default scale of \"+defaultScale);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, defaultScale);\r\n }\r\n else if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_PRECISION) || fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION))\r\n {\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, \"0\");\r\n }\r\n }\r\n }", "public int update(DatabaseConnection databaseConnection, PreparedUpdate<T> preparedUpdate) throws SQLException {\n\t\tCompiledStatement compiledStatement = preparedUpdate.compile(databaseConnection, StatementType.UPDATE);\n\t\ttry {\n\t\t\tint result = compiledStatement.runUpdate();\n\t\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\t\tdao.notifyChanges();\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tIOUtils.closeThrowSqlException(compiledStatement, \"compiled statement\");\n\t\t}\n\t}", "public static void scaleCol( double alpha , DMatrixRMaj A , int col ) {\n int idx = col;\n for (int row = 0; row < A.numRows; row++, idx += A.numCols) {\n A.data[idx] *= alpha;\n }\n }", "ArgumentsBuilder param(String param, Integer value) {\n if (value != null) {\n args.add(param);\n args.add(value.toString());\n }\n return this;\n }", "public static void zeroTriangle( boolean upper , DMatrixRBlock A )\n {\n int blockLength = A.blockLength;\n\n if( upper ) {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int h = Math.min(blockLength,A.numRows-i);\n\n for( int j = i; j < A.numCols; j += blockLength ) {\n int w = Math.min(blockLength,A.numCols-j);\n\n int index = i*A.numCols + h*j;\n\n if( j == i ) {\n for( int k = 0; k < h; k++ ) {\n for( int l = k+1; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n } else {\n for( int k = 0; k < h; k++ ) {\n for( int l = 0; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n }\n }\n }\n } else {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int h = Math.min(blockLength,A.numRows-i);\n\n for( int j = 0; j <= i; j += blockLength ) {\n int w = Math.min(blockLength,A.numCols-j);\n\n int index = i*A.numCols + h*j;\n\n if( j == i ) {\n for( int k = 0; k < h; k++ ) {\n int z = Math.min(k,w);\n for( int l = 0; l < z; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n } else {\n for( int k = 0; k < h; k++ ) {\n for( int l = 0; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n }\n }\n }\n }\n }" ]
use the design parameters to compute the constraint equation to get the value
[ "private double getConstraint(double x1, double x2)\n {\n double c1,c2,h;\n c1 = -x1*x1-x2*x2+1+0.1*Math.cos(16*Math.atan(x1/x2));\n c2 = (x1-0.5)*(x1-0.5)+(x2-0.5)*(x2-0.5)-0.5;\n if(c1>c2)\n h = (c1>0)?c1:0;\n else\n h = (c2>0)?c2:0;\n return h;\n }" ]
[ "public static final Color getColor(byte[] data, int offset)\n {\n Color result = null;\n\n if (getByte(data, offset + 3) == 0)\n {\n int r = getByte(data, offset);\n int g = getByte(data, offset + 1);\n int b = getByte(data, offset + 2);\n result = new Color(r, g, b);\n }\n\n return result;\n }", "public static List<File> extract(File zipFile, File outputFolder) throws IOException {\n List<File> extracted = new ArrayList<File>();\n\n byte[] buffer = new byte[2048];\n\n if (!outputFolder.exists()) {\n outputFolder.mkdir();\n }\n\n ZipInputStream zipInput = new ZipInputStream(new FileInputStream(zipFile));\n\n ZipEntry zipEntry = zipInput.getNextEntry();\n\n while (zipEntry != null) {\n\n String neFileNameName = zipEntry.getName();\n File newFile = new File(outputFolder + File.separator + neFileNameName);\n\n newFile.getParentFile().mkdirs();\n\n if (!zipEntry.isDirectory()) {\n FileOutputStream fos = new FileOutputStream(newFile);\n\n int size;\n while ((size = zipInput.read(buffer)) > 0) {\n fos.write(buffer, 0, size);\n }\n\n fos.close();\n extracted.add(newFile);\n }\n\n zipEntry = zipInput.getNextEntry();\n }\n\n zipInput.closeEntry();\n zipInput.close();\n\n return extracted;\n\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 boolean isToIgnore(CtElement element) {\n\t\tif (element instanceof CtStatementList && !(element instanceof CtCase)) {\n\t\t\tif (element.getRoleInParent() == CtRole.ELSE || element.getRoleInParent() == CtRole.THEN) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn element.isImplicit() || element instanceof CtReference;\n\t}", "static void processRoot(final File root, final ProcessedLayers layers, final LayerPathSetter setter) throws IOException {\n final LayersConfig layersConfig = LayersConfig.getLayersConfig(root);\n // Process layers\n final File layersDir = new File(root, layersConfig.getLayersPath());\n if (!layersDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationNoLayersConfigFound(layersDir.getAbsolutePath());\n }\n // else this isn't a root that has layers and add-ons\n } else {\n // check for a valid layer configuration\n for (final String layer : layersConfig.getLayers()) {\n File layerDir = new File(layersDir, layer);\n if (!layerDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationMissingLayer(layer, layersDir.getAbsolutePath());\n }\n // else this isn't a standard layers and add-ons structure\n return;\n }\n layers.addLayer(layer, layerDir, setter);\n }\n }\n // Finally process the add-ons\n final File addOnsDir = new File(root, layersConfig.getAddOnsPath());\n final File[] addOnsList = addOnsDir.listFiles();\n if (addOnsList != null) {\n for (final File addOn : addOnsList) {\n layers.addAddOn(addOn.getName(), addOn, setter);\n }\n }\n }", "private void reorder()\r\n {\r\n if(getTransaction().isOrdering() && needsCommit && mhtObjectEnvelopes.size() > 1)\r\n {\r\n ObjectEnvelopeOrdering ordering = new ObjectEnvelopeOrdering(mvOrderOfIds, mhtObjectEnvelopes);\r\n ordering.reorder();\r\n Identity[] newOrder = ordering.getOrdering();\r\n\r\n mvOrderOfIds.clear();\r\n for(int i = 0; i < newOrder.length; i++)\r\n {\r\n mvOrderOfIds.add(newOrder[i]);\r\n }\r\n }\r\n }", "private static Interval parseStartExtended(CharSequence startStr, CharSequence endStr) {\n Instant start = Instant.parse(startStr);\n if (endStr.length() > 0) {\n char c = endStr.charAt(0);\n if (c == 'P' || c == 'p') {\n PeriodDuration amount = PeriodDuration.parse(endStr);\n // addition of PeriodDuration only supported by OffsetDateTime,\n // but to make that work need to move point being added to closer to EPOCH\n long move = start.isBefore(Instant.EPOCH) ? 1000 * 86400 : -1000 * 86400;\n Instant end = start.plusSeconds(move).atOffset(ZoneOffset.UTC).plus(amount).toInstant().minusSeconds(move);\n return Interval.of(start, end);\n }\n }\n // infer offset from start if not specified by end\n return parseEndDateTime(start, ZoneOffset.UTC, endStr);\n }", "public void deployApplication(String applicationName, URL... urls) throws IOException {\n this.applicationName = applicationName;\n\n for (URL url : urls) {\n try (InputStream inputStream = url.openStream()) {\n deploy(inputStream);\n }\n }\n }", "private Integer getNullOnValue(Integer value, int nullValue)\n {\n return (NumberHelper.getInt(value) == nullValue ? null : value);\n }" ]
Use this API to add cachepolicylabel.
[ "public static base_response add(nitro_service client, cachepolicylabel resource) throws Exception {\n\t\tcachepolicylabel addresource = new cachepolicylabel();\n\t\taddresource.labelname = resource.labelname;\n\t\taddresource.evaluates = resource.evaluates;\n\t\treturn addresource.add_resource(client);\n\t}" ]
[ "public void addStep(String name, String robot, Map<String, Object> options) {\n all.put(name, new Step(name, robot, options));\n }", "public void writeStartList(String name) throws IOException\n {\n writeComma();\n writeNewLineIndent();\n writeName(name);\n writeNewLineIndent();\n m_writer.write(\"[\");\n increaseIndent();\n }", "public static base_response add(nitro_service client, nslimitselector resource) throws Exception {\n\t\tnslimitselector addresource = new nslimitselector();\n\t\taddresource.selectorname = resource.selectorname;\n\t\taddresource.rule = resource.rule;\n\t\treturn addresource.add_resource(client);\n\t}", "@Override\n public void join(final long millis) throws InterruptedException {\n for (final Thread thread : this.threads) {\n thread.join(millis);\n }\n }", "@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public List<HazeltaskTask<G>> shutdownNow() {\n\t return (List<HazeltaskTask<G>>) (List) localExecutorPool.shutdownNow();\n\t}", "private Table buildTable(CmsSqlConsoleResults results) {\n\n IndexedContainer container = new IndexedContainer();\n int numCols = results.getColumns().size();\n for (int c = 0; c < numCols; c++) {\n container.addContainerProperty(Integer.valueOf(c), results.getColumnType(c), null);\n }\n int r = 0;\n for (List<Object> row : results.getData()) {\n Item item = container.addItem(Integer.valueOf(r));\n for (int c = 0; c < numCols; c++) {\n item.getItemProperty(Integer.valueOf(c)).setValue(row.get(c));\n }\n r += 1;\n }\n Table table = new Table();\n table.setContainerDataSource(container);\n for (int c = 0; c < numCols; c++) {\n String col = (results.getColumns().get(c));\n table.setColumnHeader(Integer.valueOf(c), col);\n }\n table.setWidth(\"100%\");\n table.setHeight(\"100%\");\n table.setColumnCollapsingAllowed(true);\n return table;\n }", "public ListActiveCoursesInAccountOptions searchTerm(String searchTerm) {\n if(searchTerm == null || searchTerm.length() < 3) {\n throw new IllegalArgumentException(\"Search term must be at least 3 characters\");\n }\n addSingleItem(\"search_term\", searchTerm);\n return this;\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 boolean isAlive(Connection conn)\r\n {\r\n try\r\n {\r\n return con != null ? !con.isClosed() : false;\r\n }\r\n catch (SQLException e)\r\n {\r\n log.error(\"IsAlive check failed, running connection was invalid!!\", e);\r\n return false;\r\n }\r\n }" ]
A find query only given as criterion. Leave it to MongoDB's own parser to handle it. @return the {@link Rule} to identify a find query only
[ "public Rule CriteriaOnlyFindQuery() {\n\t\treturn Sequence( !peek().isCliQuery(), JsonParameter( JsonObject() ) , peek().setOperation( Operation.FIND ), peek().setCriteria( match() ) );\n\t}" ]
[ "public static base_responses change(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey updateresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new sslcertkey();\n\t\t\t\tupdateresources[i].certkey = resources[i].certkey;\n\t\t\t\tupdateresources[i].cert = resources[i].cert;\n\t\t\t\tupdateresources[i].key = resources[i].key;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].fipskey = resources[i].fipskey;\n\t\t\t\tupdateresources[i].inform = resources[i].inform;\n\t\t\t\tupdateresources[i].passplain = resources[i].passplain;\n\t\t\t\tupdateresources[i].nodomaincheck = resources[i].nodomaincheck;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, updateresources,\"update\");\n\t\t}\n\t\treturn result;\n\t}", "private void checkAndAddLengths(final int... requiredLengths) {\n\t\tfor( final int length : requiredLengths ) {\n\t\t\tif( length < 0 ) {\n\t\t\t\tthrow new IllegalArgumentException(String.format(\"required length cannot be negative but was %d\",\n\t\t\t\t\tlength));\n\t\t\t}\n\t\t\tthis.requiredLengths.add(length);\n\t\t}\n\t}", "List getGroupby()\r\n {\r\n List result = _getGroupby();\r\n Iterator iter = getCriteria().iterator();\r\n Object crit;\r\n\r\n while (iter.hasNext())\r\n {\r\n crit = iter.next();\r\n if (crit instanceof Criteria)\r\n {\r\n result.addAll(((Criteria) crit).getGroupby());\r\n }\r\n }\r\n\r\n return result;\r\n }", "public static <GROUP extends Serializable> ExecutorConfig<GROUP> basicGroupable() {\n return new ExecutorConfig<GROUP>()\n .withTaskIdAdapter((TaskIdAdapter<Groupable<GROUP>, GROUP, ?>) new DefaultGroupableTaskIdAdapter<GROUP>());\n }", "public static boolean intersectsPointWithRectF(RectF _Rect, float _X, float _Y) {\n return _X > _Rect.left && _X < _Rect.right && _Y > _Rect.top && _Y < _Rect.bottom;\n }", "public double[] getSingularValues() {\n double ret[] = new double[W.numCols()];\n\n for (int i = 0; i < ret.length; i++) {\n ret[i] = getSingleValue(i);\n }\n return ret;\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 }", "static String[] tokenize(String str) {\n char sep = '.';\n int start = 0;\n int len = str.length();\n int count = 0;\n for (int pos = 0; pos < len; pos++) {\n if (str.charAt(pos) == sep) {\n if (pos != start) {\n count++;\n }\n start = pos + 1;\n }\n }\n if (len != start) {\n count++;\n }\n String[] l = new String[count];\n\n count = 0;\n start = 0;\n for (int pos = 0; pos < len; pos++) {\n if (str.charAt(pos) == sep) {\n if (pos != start) {\n String tok = str.substring(start, pos);\n l[count++] = tok;\n }\n start = pos + 1;\n }\n }\n if (len != start) {\n String tok = str.substring(start);\n l[count/* ++ */] = tok;\n }\n return l;\n }", "public static Date max(Date d1, Date d2)\n {\n Date result;\n if (d1 == null)\n {\n result = d2;\n }\n else\n if (d2 == null)\n {\n result = d1;\n }\n else\n {\n result = (d1.compareTo(d2) > 0) ? d1 : d2;\n }\n return result;\n }" ]
Returns the editable columns for the provided edit mode. @param mode the edit mode. @return the editable columns for the provided edit mode.
[ "public List<TableProperty> getEditableColumns(CmsMessageBundleEditorTypes.EditMode mode) {\n\n return m_editorState.get(mode).getEditableColumns();\n }" ]
[ "protected void update(float scale) {\n GVRSceneObject owner = getOwnerObject();\n if (isEnabled() && (owner != null) && owner.isEnabled())\n {\n float w = getWidth();\n float h = getHeight();\n mPose.update(mARPlane.getCenterPose(), scale);\n Matrix4f m = new Matrix4f();\n m.set(mPose.getPoseMatrix());\n m.scaleLocal(w * 0.95f, h * 0.95f, 1.0f);\n owner.getTransform().setModelMatrix(m);\n }\n }", "protected void aliasGeneric( Object variable , String name ) {\n if( variable.getClass() == Integer.class ) {\n alias(((Integer)variable).intValue(),name);\n } else if( variable.getClass() == Double.class ) {\n alias(((Double)variable).doubleValue(),name);\n } else if( variable.getClass() == DMatrixRMaj.class ) {\n alias((DMatrixRMaj)variable,name);\n } else if( variable.getClass() == FMatrixRMaj.class ) {\n alias((FMatrixRMaj)variable,name);\n } else if( variable.getClass() == DMatrixSparseCSC.class ) {\n alias((DMatrixSparseCSC)variable,name);\n } else if( variable.getClass() == SimpleMatrix.class ) {\n alias((SimpleMatrix) variable, name);\n } else if( variable instanceof DMatrixFixed ) {\n DMatrixRMaj M = new DMatrixRMaj(1,1);\n ConvertDMatrixStruct.convert((DMatrixFixed)variable,M);\n alias(M,name);\n } else if( variable instanceof FMatrixFixed ) {\n FMatrixRMaj M = new FMatrixRMaj(1,1);\n ConvertFMatrixStruct.convert((FMatrixFixed)variable,M);\n alias(M,name);\n } else {\n throw new RuntimeException(\"Unknown value type of \"+\n (variable.getClass().getSimpleName())+\" for variable \"+name);\n }\n }", "public static boolean isConstructorCall(Expression expression, List<String> classNames) {\r\n return expression instanceof ConstructorCallExpression && classNames.contains(expression.getType().getName());\r\n }", "public static void printHelp(PrintStream stream) {\n stream.println();\n stream.println(\"Voldemort Admin Tool Async-Job Commands\");\n stream.println(\"---------------------------------------\");\n stream.println(\"list Get async job list from nodes.\");\n stream.println(\"stop Stop async jobs on one node.\");\n stream.println();\n stream.println(\"To get more information on each command,\");\n stream.println(\"please try \\'help async-job <command-name>\\'.\");\n stream.println();\n }", "public ParallelTaskBuilder setSshPrivKeyRelativePath(\n String privKeyRelativePath) {\n this.sshMeta.setPrivKeyRelativePath(privKeyRelativePath);\n this.sshMeta.setSshLoginType(SshLoginType.KEY);\n return this;\n }", "public boolean isUpToDate(final DbArtifact artifact) {\n final List<String> versions = repoHandler.getArtifactVersions(artifact);\n final String currentVersion = artifact.getVersion();\n\n final String lastDevVersion = getLastVersion(versions);\n final String lastReleaseVersion = getLastRelease(versions);\n\n if(lastDevVersion == null || lastReleaseVersion == null) {\n // Plain Text comparison against version \"strings\"\n for(final String version: versions){\n if(version.compareTo(currentVersion) > 0){\n return false;\n }\n }\n return true;\n } else {\n return currentVersion.equals(lastDevVersion) || currentVersion.equals(lastReleaseVersion);\n }\n }", "public void insertAfter(Token before, TokenList list ) {\n Token after = before.next;\n\n before.next = list.first;\n list.first.previous = before;\n if( after == null ) {\n last = list.last;\n } else {\n after.previous = list.last;\n list.last.next = after;\n }\n size += list.size;\n }", "public synchronized List<String> propertyListOf(Class<?> c) {\n String cn = c.getName();\n List<String> ls = repo.get(cn);\n if (ls != null) {\n return ls;\n }\n Set<Class<?>> circularReferenceDetector = new HashSet<>();\n ls = propertyListOf(c, circularReferenceDetector, null);\n repo.put(c.getName(), ls);\n return ls;\n }", "private void checkCollectionForeignkeys(ModelDef modelDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n ClassDescriptorDef classDef;\r\n CollectionDescriptorDef collDef;\r\n\r\n for (Iterator it = modelDef.getClasses(); it.hasNext();)\r\n {\r\n classDef = (ClassDescriptorDef)it.next();\r\n for (Iterator collIt = classDef.getCollections(); collIt.hasNext();)\r\n {\r\n collDef = (CollectionDescriptorDef)collIt.next();\r\n if (!collDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE))\r\n {\r\n checkIndirectionTable(modelDef, collDef);\r\n }\r\n else\r\n { \r\n checkCollectionForeignkeys(modelDef, collDef);\r\n }\r\n }\r\n }\r\n }\r\n }" ]
Get the remote address. @return the remote address, {@code null} if not available
[ "public InetAddress getRemoteAddress() {\n final Channel channel;\n try {\n channel = strategy.getChannel();\n } catch (IOException e) {\n return null;\n }\n final Connection connection = channel.getConnection();\n final InetSocketAddress peerAddress = connection.getPeerAddress(InetSocketAddress.class);\n return peerAddress == null ? null : peerAddress.getAddress();\n }" ]
[ "public static void startTimer(final String type) {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return;\n }\n\n instance.components.putIfAbsent(type, new Component(type));\n instance.components.get(type).startTimer();\n }", "public void commandLoop() throws IOException {\n for (Object handler : allHandlers) {\n if (handler instanceof ShellManageable) {\n ((ShellManageable)handler).cliEnterLoop();\n }\n }\n output.output(appName, outputConverter);\n String command = \"\";\n while (true) {\n try {\n command = input.readCommand(path);\n if (command.trim().equals(\"exit\")) {\n if (lineProcessor == null)\n break;\n else {\n path = savedPath;\n lineProcessor = null;\n }\n }\n\n processLine(command);\n } catch (TokenException te) {\n lastException = te;\n output.outputException(command, te);\n } catch (CLIException clie) {\n lastException = clie;\n if (!command.trim().equals(\"exit\")) {\n output.outputException(clie);\n }\n }\n }\n for (Object handler : allHandlers) {\n if (handler instanceof ShellManageable) {\n ((ShellManageable)handler).cliLeaveLoop();\n }\n }\n }", "@PostConstruct\n public final void addMetricsAppenderToLogback() {\n final LoggerContext factory = (LoggerContext) LoggerFactory.getILoggerFactory();\n final Logger root = factory.getLogger(Logger.ROOT_LOGGER_NAME);\n\n final InstrumentedAppender metrics = new InstrumentedAppender(this.metricRegistry);\n metrics.setContext(root.getLoggerContext());\n metrics.start();\n root.addAppender(metrics);\n }", "private String addIndexInputToList(String name, IndexInput in,\n String postingsFormatName) throws IOException {\n if (indexInputList.get(name) != null) {\n indexInputList.get(name).close();\n }\n if (in != null) {\n String localPostingsFormatName = postingsFormatName;\n if (localPostingsFormatName == null) {\n localPostingsFormatName = in.readString();\n } else if (!in.readString().equals(localPostingsFormatName)) {\n throw new IOException(\"delegate codec \" + name + \" doesn't equal \"\n + localPostingsFormatName);\n }\n indexInputList.put(name, in);\n indexInputOffsetList.put(name, in.getFilePointer());\n return localPostingsFormatName;\n } else {\n log.debug(\"no \" + name + \" registered\");\n return null;\n }\n }", "public static base_response unset(nitro_service client, sslparameter resource, String[] args) throws Exception{\n\t\tsslparameter unsetresource = new sslparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public static int skipToNextMatchingShort(byte[] buffer, int offset, int value)\n {\n int nextOffset = offset;\n while (getShort(buffer, nextOffset) != value)\n {\n ++nextOffset;\n }\n nextOffset += 2;\n\n return nextOffset;\n }", "public void animate(float animationTime, Matrix4f mat)\n {\n mRotInterpolator.animate(animationTime, mRotKey);\n mPosInterpolator.animate(animationTime, mPosKey);\n mSclInterpolator.animate(animationTime, mScaleKey);\n mat.translationRotateScale(mPosKey[0], mPosKey[1], mPosKey[2], mRotKey[0], mRotKey[1], mRotKey[2], mRotKey[3], mScaleKey[0], mScaleKey[1], mScaleKey[2]);\n\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 ModelNode createCPUNode() throws OperationFailedException {\n ModelNode cpu = new ModelNode().setEmptyObject();\n cpu.get(ARCH).set(getProperty(\"os.arch\"));\n cpu.get(AVAILABLE_PROCESSORS).set(ProcessorInfo.availableProcessors());\n return cpu;\n }" ]
Generate a sql where-clause for the array of fields @param fields array containing all columns used in WHERE clause
[ "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 void setFinalTransformMatrix(Matrix4f finalTransform)\n {\n float[] mat = new float[16];\n finalTransform.get(mat);\n NativeBone.setFinalTransformMatrix(getNative(), mat);\n }", "public Where<T, ID> isNull(String columnName) throws SQLException {\n\t\taddClause(new IsNull(columnName, findColumnFieldType(columnName)));\n\t\treturn this;\n\t}", "public static LinearSolverDense<DMatrixRMaj> general(int numRows , int numCols ) {\n if( numRows == numCols )\n return linear(numRows);\n else\n return leastSquares(numRows,numCols);\n }", "public 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}", "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 }", "private List<String> generateDateTimePatterns(String datePattern, String[] timePatterns)\n {\n List<String> patterns = new ArrayList<String>();\n for (String timePattern : timePatterns)\n {\n patterns.add(datePattern + \" \" + timePattern);\n }\n\n // Always fall back on the date-only pattern\n patterns.add(datePattern);\n\n return patterns;\n }", "public ByteBuffer[] toDirectByteBuffers(long offset, long size) {\n long pos = offset;\n long blockSize = Integer.MAX_VALUE;\n long limit = offset + size;\n int numBuffers = (int) ((size + (blockSize - 1)) / blockSize);\n ByteBuffer[] result = new ByteBuffer[numBuffers];\n int index = 0;\n while (pos < limit) {\n long blockLength = Math.min(limit - pos, blockSize);\n result[index++] = UnsafeUtil.newDirectByteBuffer(address() + pos, (int) blockLength, this)\n .order(ByteOrder.nativeOrder());\n pos += blockLength;\n }\n return result;\n\n }", "public static policydataset_value_binding[] get(nitro_service service, String name) throws Exception{\n\t\tpolicydataset_value_binding obj = new policydataset_value_binding();\n\t\tobj.set_name(name);\n\t\tpolicydataset_value_binding response[] = (policydataset_value_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static int[] Argsort(final float[] array, final boolean ascending) {\n Integer[] indexes = new Integer[array.length];\n for (int i = 0; i < indexes.length; i++) {\n indexes[i] = i;\n }\n Arrays.sort(indexes, new Comparator<Integer>() {\n @Override\n public int compare(final Integer i1, final Integer i2) {\n return (ascending ? 1 : -1) * Float.compare(array[i1], array[i2]);\n }\n });\n return asArray(indexes);\n }" ]
Invoke to find all services for given service type using specified class loader @param classLoader specified class loader @param serviceType given service type @return List of found services
[ "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 ImmutableMap<String, String> getConfigurationTweak(String dbModuleName)\n {\n final DbInfo db = cluster.getNextDb();\n return ImmutableMap.of(\"ness.db.\" + dbModuleName + \".uri\", getJdbcUri(db),\n \"ness.db.\" + dbModuleName + \".ds.user\", db.user);\n }", "protected final boolean isGLThread() {\n final Thread glThread = sGLThread.get();\n return glThread != null && glThread.equals(Thread.currentThread());\n }", "public BoxGroupMembership.Info addMembership(BoxUser user, Role role) {\n BoxAPIConnection api = this.getAPI();\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"user\", new JsonObject().add(\"id\", user.getID()));\n requestJSON.add(\"group\", new JsonObject().add(\"id\", this.getID()));\n if (role != null) {\n requestJSON.add(\"role\", role.toJSONString());\n }\n\n URL url = ADD_MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxGroupMembership membership = new BoxGroupMembership(api, responseJSON.get(\"id\").asString());\n return membership.new Info(responseJSON);\n }", "public static AliasFinder newInstance(final String variableName, final ControlFlowBlock controlFlowBlockToExamine) {\n checkArgument(!variableName.isEmpty());\n return new AliasFinder(variableName, checkNotNull(controlFlowBlockToExamine));\n }", "public ProjectCalendar getEffectiveCalendar()\n {\n ProjectCalendar result = getCalendar();\n if (result == null)\n {\n result = getParentFile().getDefaultCalendar();\n }\n return result;\n }", "protected final void sendObjectToSocket(Object objectToSend, WriteCallback cb) {\n Session sess = this.getSession();\n if (sess != null) {\n String json;\n try {\n json = this.mapper.writeValueAsString(objectToSend);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(\"Failed to serialize object\", e);\n }\n sess.getRemote().sendString(json, cb);\n }\n }", "public GridCoverage2D call() {\n try {\n BufferedImage coverageImage = this.tiledLayer.createBufferedImage(\n this.tilePreparationInfo.getImageWidth(),\n this.tilePreparationInfo.getImageHeight());\n Graphics2D graphics = coverageImage.createGraphics();\n try {\n for (SingleTilePreparationInfo tileInfo: this.tilePreparationInfo.getSingleTiles()) {\n final TileTask task;\n if (tileInfo.getTileRequest() != null) {\n task = new SingleTileLoaderTask(\n tileInfo.getTileRequest(), this.errorImage, tileInfo.getTileIndexX(),\n tileInfo.getTileIndexY(), this.failOnError, this.registry, this.context);\n } else {\n task = new PlaceHolderImageTask(this.tiledLayer.getMissingTileImage(),\n tileInfo.getTileIndexX(), tileInfo.getTileIndexY());\n }\n Tile tile = task.call();\n if (tile.getImage() != null) {\n graphics.drawImage(tile.getImage(),\n tile.getxIndex() * this.tiledLayer.getTileSize().width,\n tile.getyIndex() * this.tiledLayer.getTileSize().height, null);\n }\n }\n } finally {\n graphics.dispose();\n }\n\n GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null);\n GeneralEnvelope gridEnvelope = new GeneralEnvelope(this.tilePreparationInfo.getMapProjection());\n gridEnvelope.setEnvelope(this.tilePreparationInfo.getGridCoverageOrigin().x,\n this.tilePreparationInfo.getGridCoverageOrigin().y,\n this.tilePreparationInfo.getGridCoverageMaxX(),\n this.tilePreparationInfo.getGridCoverageMaxY());\n return factory.create(this.tiledLayer.createCommonUrl(), coverageImage, gridEnvelope,\n null, null, null);\n } catch (Exception e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }", "public 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 }", "public void loadClassifier(InputStream in, Properties props) throws IOException, ClassCastException,\r\n ClassNotFoundException {\r\n loadClassifier(new ObjectInputStream(in), props);\r\n }" ]
This method extracts assignment data from a Planner file. @param plannerProject Root node of the Planner file
[ "private void readAssignments(Project plannerProject)\n {\n Allocations allocations = plannerProject.getAllocations();\n List<Allocation> allocationList = allocations.getAllocation();\n Set<Task> tasksWithAssignments = new HashSet<Task>();\n\n for (Allocation allocation : allocationList)\n {\n Integer taskID = getInteger(allocation.getTaskId());\n Integer resourceID = getInteger(allocation.getResourceId());\n Integer units = getInteger(allocation.getUnits());\n\n Task task = m_projectFile.getTaskByUniqueID(taskID);\n Resource resource = m_projectFile.getResourceByUniqueID(resourceID);\n\n if (task != null && resource != null)\n {\n Duration work = task.getWork();\n int percentComplete = NumberHelper.getInt(task.getPercentageComplete());\n\n ResourceAssignment assignment = task.addResourceAssignment(resource);\n assignment.setUnits(units);\n assignment.setWork(work);\n\n if (percentComplete != 0)\n {\n Duration actualWork = Duration.getInstance((work.getDuration() * percentComplete) / 100, work.getUnits());\n assignment.setActualWork(actualWork);\n assignment.setRemainingWork(Duration.getInstance(work.getDuration() - actualWork.getDuration(), work.getUnits()));\n }\n else\n {\n assignment.setRemainingWork(work);\n }\n\n assignment.setStart(task.getStart());\n assignment.setFinish(task.getFinish());\n\n tasksWithAssignments.add(task);\n\n m_eventManager.fireAssignmentReadEvent(assignment);\n }\n }\n\n //\n // Adjust work per assignment for tasks with multiple assignments\n //\n for (Task task : tasksWithAssignments)\n {\n List<ResourceAssignment> assignments = task.getResourceAssignments();\n if (assignments.size() > 1)\n {\n double maxUnits = 0;\n for (ResourceAssignment assignment : assignments)\n {\n maxUnits += assignment.getUnits().doubleValue();\n }\n\n for (ResourceAssignment assignment : assignments)\n {\n Duration work = assignment.getWork();\n double factor = assignment.getUnits().doubleValue() / maxUnits;\n\n work = Duration.getInstance(work.getDuration() * factor, work.getUnits());\n assignment.setWork(work);\n Duration actualWork = assignment.getActualWork();\n if (actualWork != null)\n {\n actualWork = Duration.getInstance(actualWork.getDuration() * factor, actualWork.getUnits());\n assignment.setActualWork(actualWork);\n }\n\n Duration remainingWork = assignment.getRemainingWork();\n if (remainingWork != null)\n {\n remainingWork = Duration.getInstance(remainingWork.getDuration() * factor, remainingWork.getUnits());\n assignment.setRemainingWork(remainingWork);\n }\n }\n }\n }\n }" ]
[ "public ItemRequest<Project> removeFollowers(String project) {\n \n String path = String.format(\"/projects/%s/removeFollowers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }", "private void clearBeatGrids(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 deliverBeatGridUpdate(player, null); // Inform listeners the beat grid is gone.\n }\n }\n }\n }", "public void resetQuotaAndRecoverEnforcement() {\n for(Integer nodeId: nodeIds) {\n boolean quotaEnforcement = mapNodeToQuotaEnforcingEnabled.get(nodeId);\n adminClient.metadataMgmtOps.updateRemoteMetadata(Arrays.asList(nodeId),\n MetadataStore.QUOTA_ENFORCEMENT_ENABLED_KEY,\n Boolean.toString(quotaEnforcement));\n }\n for(String storeName: storeNames) {\n adminClient.quotaMgmtOps.rebalanceQuota(storeName);\n }\n }", "public static boolean hasFacet(GridDialect gridDialect, Class<? extends GridDialect> facetType) {\n\t\tif ( gridDialect instanceof ForwardingGridDialect ) {\n\t\t\treturn hasFacet( ( (ForwardingGridDialect<?>) gridDialect ).getGridDialect(), facetType );\n\t\t}\n\t\telse {\n\t\t\treturn facetType.isAssignableFrom( gridDialect.getClass() );\n\t\t}\n\t}", "public ClientBootstrap bootStrapTcpClient()\n throws HttpRequestCreateException {\n\n ClientBootstrap tcpClient = null;\n try {\n\n // Configure the client.\n tcpClient = new ClientBootstrap(tcpMeta.getChannelFactory());\n\n // Configure the pipeline factory.\n tcpClient.setPipelineFactory(new MyPipelineFactory(TcpUdpSshPingResourceStore.getInstance().getTimer(),\n this, tcpMeta.getTcpIdleTimeoutSec())\n );\n\n tcpClient.setOption(\"connectTimeoutMillis\",\n tcpMeta.getTcpConnectTimeoutMillis());\n tcpClient.setOption(\"tcpNoDelay\", true);\n // tcpClient.setOption(\"keepAlive\", true);\n\n } catch (Exception t) {\n throw new TcpUdpRequestCreateException(\n \"Error in creating request in Tcpworker. \"\n + \" If tcpClient is null. Then fail to create.\", t);\n }\n\n return tcpClient;\n\n }", "public static void validate(final Organization organization) {\n if(organization.getName() == null ||\n organization.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Organization name cannot be null or empty!\")\n .build());\n }\n }", "public static void registerConverters(Set<?> converters, ConverterRegistry registry) {\n\t\tif (converters != null) {\n\t\t\tfor (Object converter : converters) {\n\t\t\t\tif (converter instanceof GenericConverter) {\n\t\t\t\t\tregistry.addConverter((GenericConverter) converter);\n\t\t\t\t}\n\t\t\t\telse if (converter instanceof Converter<?, ?>) {\n\t\t\t\t\tregistry.addConverter((Converter<?, ?>) converter);\n\t\t\t\t}\n\t\t\t\telse if (converter instanceof ConverterFactory<?, ?>) {\n\t\t\t\t\tregistry.addConverterFactory((ConverterFactory<?, ?>) converter);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Each converter object must implement one of the \" +\n\t\t\t\t\t\t\t\"Converter, ConverterFactory, or GenericConverter interfaces\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {\n final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();\n for (ResourceRoot resourceRoot : DeploymentUtils.allResourceRoots(deploymentUnit)) {\n ResourceRootIndexer.indexResourceRoot(resourceRoot);\n }\n }", "protected void addAllowedValuesToDescription(ModelNode result, ParameterValidator validator) {\n if (allowedValues != null) {\n for (ModelNode allowedValue : allowedValues) {\n result.get(ModelDescriptionConstants.ALLOWED).add(allowedValue);\n }\n } else if (validator instanceof AllowedValuesValidator) {\n AllowedValuesValidator avv = (AllowedValuesValidator) validator;\n List<ModelNode> allowed = avv.getAllowedValues();\n if (allowed != null) {\n for (ModelNode ok : allowed) {\n result.get(ModelDescriptionConstants.ALLOWED).add(ok);\n }\n }\n }\n }" ]
Create an IPv6 mixed address using the given ipv6 segments and using this address for the embedded IPv4 segments @param segs @return
[ "public IPv6Address getIPv6Address(IPv6AddressSegment segs[]) {\n\t\tIPv6AddressCreator creator = getIPv6Network().getAddressCreator();\n\t\treturn creator.createAddress(IPv6AddressSection.createSection(creator, segs, this)); /* address creation */\n\t}" ]
[ "protected void postDestroyConnection(ConnectionHandle handle){\r\n\t\tConnectionPartition partition = handle.getOriginatingPartition();\r\n\r\n\t\tif (this.finalizableRefQueue != null && handle.getInternalConnection() != null){ //safety\r\n\t\t\tthis.finalizableRefs.remove(handle.getInternalConnection());\r\n\t\t\t//\t\t\tassert o != null : \"Did not manage to remove connection from finalizable ref queue\";\r\n\t\t}\r\n\r\n\t\tpartition.updateCreatedConnections(-1);\r\n\t\tpartition.setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization\r\n\r\n\r\n\t\t// \"Destroying\" for us means: don't put it back in the pool.\r\n\t\tif (handle.getConnectionHook() != null){\r\n\t\t\thandle.getConnectionHook().onDestroy(handle);\r\n\t\t}\r\n\r\n\t}", "public Sequence compile( String equation , boolean assignment, boolean debug ) {\n\n functions.setManagerTemp(managerTemp);\n\n Sequence sequence = new Sequence();\n TokenList tokens = extractTokens(equation,managerTemp);\n\n if( tokens.size() < 3 )\n throw new RuntimeException(\"Too few tokens\");\n\n TokenList.Token t0 = tokens.getFirst();\n\n if( t0.word != null && t0.word.compareToIgnoreCase(\"macro\") == 0 ) {\n parseMacro(tokens,sequence);\n } else {\n insertFunctionsAndVariables(tokens);\n insertMacros(tokens);\n if (debug) {\n System.out.println(\"Parsed tokens:\\n------------\");\n tokens.print();\n System.out.println();\n }\n\n // Get the results variable\n if (t0.getType() != Type.VARIABLE && t0.getType() != Type.WORD) {\n compileTokens(sequence,tokens);\n // If there's no output then this is acceptable, otherwise it's assumed to be a bug\n // If there's no output then a configuration was changed\n Variable variable = tokens.getFirst().getVariable();\n if( variable != null ) {\n if( assignment )\n throw new IllegalArgumentException(\"No assignment to an output variable could be found. Found \" + t0);\n else {\n sequence.output = variable; // set this to be the output for print()\n }\n }\n\n } else {\n compileAssignment(sequence, tokens, t0);\n }\n\n if (debug) {\n System.out.println(\"Operations:\\n------------\");\n for (int i = 0; i < sequence.operations.size(); i++) {\n System.out.println(sequence.operations.get(i).name());\n }\n }\n }\n\n return sequence;\n }", "private static long scanForEndSig(final File file, final FileChannel channel, final ScanContext context) throws IOException {\n\n\n\n // TODO Consider just reading in MAX_REVERSE_SCAN bytes -- increased peak memory cost but less complex\n\n ByteBuffer bb = getByteBuffer(CHUNK_SIZE);\n long start = channel.size();\n long end = Math.max(0, start - MAX_REVERSE_SCAN);\n long channelPos = Math.max(0, start - CHUNK_SIZE);\n long lastChannelPos = channelPos;\n while (lastChannelPos >= end) {\n\n read(bb, channel, channelPos);\n\n int actualRead = bb.limit();\n int bufferPos = actualRead - 1;\n while (bufferPos >= SIG_PATTERN_LENGTH) {\n\n // Following is based on the Boyer Moore algorithm but simplified to reflect\n // a) the pattern is static\n // b) the pattern has no repeating bytes\n\n int patternPos;\n for (patternPos = SIG_PATTERN_LENGTH - 1;\n patternPos >= 0 && context.matches(patternPos, bb.get(bufferPos - patternPos));\n --patternPos) {\n // empty loop while bytes match\n }\n\n // Switch gives same results as checking the \"good suffix array\" in the Boyer Moore algorithm\n switch (patternPos) {\n case -1: {\n final State state = context.state;\n // Pattern matched. Confirm is this is the start of a valid end of central dir record\n long startEndRecord = channelPos + bufferPos - SIG_PATTERN_LENGTH + 1;\n if (validateEndRecord(file, channel, startEndRecord, context.getSig())) {\n if (state == State.FOUND) {\n return startEndRecord;\n } else {\n return -1;\n }\n }\n // wasn't a valid end record; continue scan\n bufferPos -= 4;\n break;\n }\n case 3: {\n // No bytes matched; the common case.\n // With our pattern, this is the only case where the Boyer Moore algorithm's \"bad char array\" may\n // produce a shift greater than the \"good suffix array\" (which would shift 1 byte)\n int idx = bb.get(bufferPos - patternPos) - Byte.MIN_VALUE;\n bufferPos -= BAD_BYTE_SKIP[idx];\n break;\n }\n default:\n // 1 or more bytes matched\n bufferPos -= 4;\n }\n }\n\n // Move back a full chunk. If we didn't read a full chunk, that's ok,\n // it means we read all data and the outer while loop will terminate\n if (channelPos <= bufferPos) {\n break;\n }\n lastChannelPos = channelPos;\n channelPos -= Math.min(channelPos - bufferPos, CHUNK_SIZE - bufferPos);\n }\n\n return -1;\n }", "public static sslvserver_sslciphersuite_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslciphersuite_binding obj = new sslvserver_sslciphersuite_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslciphersuite_binding response[] = (sslvserver_sslciphersuite_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}", "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 synchronized void maybeThrottle(int eventsSeen) {\n if (maxRatePerSecond > 0) {\n long now = time.milliseconds();\n try {\n rateSensor.record(eventsSeen, now);\n } catch (QuotaViolationException e) {\n // If we're over quota, we calculate how long to sleep to compensate.\n double currentRate = e.getValue();\n if (currentRate > this.maxRatePerSecond) {\n double excessRate = currentRate - this.maxRatePerSecond;\n long sleepTimeMs = Math.round(excessRate / this.maxRatePerSecond * voldemort.utils.Time.MS_PER_SECOND);\n if(logger.isDebugEnabled()) {\n logger.debug(\"Throttler quota exceeded:\\n\" +\n \"eventsSeen \\t= \" + eventsSeen + \" in this call of maybeThrotte(),\\n\" +\n \"currentRate \\t= \" + currentRate + \" events/sec,\\n\" +\n \"maxRatePerSecond \\t= \" + this.maxRatePerSecond + \" events/sec,\\n\" +\n \"excessRate \\t= \" + excessRate + \" events/sec,\\n\" +\n \"sleeping for \\t\" + sleepTimeMs + \" ms to compensate.\\n\" +\n \"rateConfig.timeWindowMs() = \" + rateConfig.timeWindowMs());\n }\n if (sleepTimeMs > rateConfig.timeWindowMs()) {\n logger.warn(\"Throttler sleep time (\" + sleepTimeMs + \" ms) exceeds \" +\n \"window size (\" + rateConfig.timeWindowMs() + \" ms). This will likely \" +\n \"result in not being able to honor the rate limit accurately.\");\n // When using the HDFS Fetcher, setting the hdfs.fetcher.buffer.size\n // too high could cause this problem.\n }\n time.sleep(sleepTimeMs);\n } else if (logger.isDebugEnabled()) {\n logger.debug(\"Weird. Got QuotaValidationException but measured rate not over rateLimit: \" +\n \"currentRate = \" + currentRate + \" , rateLimit = \" + this.maxRatePerSecond);\n }\n }\n }\n }", "public ParallelTaskBuilder prepareHttpOptions(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.OPTIONS);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n\n }", "static InjectionProvider<?>[] toArray(final Set<InjectionProvider<?>> injectionProviders) {\n return injectionProviders.toArray(new InjectionProvider<?>[injectionProviders.size()]);\n }" ]
Creates a string representation of the given node. Useful for debugging. @return a debug string for the given node.
[ "public static String compactDump(INode node, boolean showHidden) {\n\t\tStringBuilder result = new StringBuilder();\n\t\ttry {\n\t\t\tcompactDump(node, showHidden, \"\", result);\n\t\t} catch (IOException e) {\n\t\t\treturn e.getMessage();\n\t\t}\n\t\treturn result.toString();\n\t}" ]
[ "public static bridgetable[] get(nitro_service service) throws Exception{\n\t\tbridgetable obj = new bridgetable();\n\t\tbridgetable[] response = (bridgetable[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public void setFileFormat(String fileFormat) {\n\n if (fileFormat.toUpperCase().equals(FileFormat.JSON.toString())) {\n m_fileFormat = FileFormat.JSON;\n }\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}", "public static appfwjsoncontenttype[] get(nitro_service service, options option) throws Exception{\n\t\tappfwjsoncontenttype obj = new appfwjsoncontenttype();\n\t\tappfwjsoncontenttype[] response = (appfwjsoncontenttype[])obj.get_resources(service,option);\n\t\treturn response;\n\t}", "@Override\n public boolean isCompleteRequest(final ByteBuffer buffer) throws VoldemortException {\n DataInputStream inputStream = new DataInputStream(new ByteBufferBackedInputStream(buffer));\n\n try {\n\n byte opCode = inputStream.readByte();\n // Store Name\n inputStream.readUTF();\n // Store routing type\n getRoutingType(inputStream);\n\n switch(opCode) {\n case VoldemortOpCode.GET_VERSION_OP_CODE:\n if(!GetVersionRequestHandler.isCompleteRequest(inputStream, buffer))\n return false;\n break;\n case VoldemortOpCode.GET_OP_CODE:\n if(!GetRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))\n return false;\n break;\n case VoldemortOpCode.GET_ALL_OP_CODE:\n if(!GetAllRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))\n return false;\n break;\n case VoldemortOpCode.PUT_OP_CODE: {\n if(!PutRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))\n return false;\n break;\n }\n case VoldemortOpCode.DELETE_OP_CODE: {\n if(!DeleteRequestHandler.isCompleteRequest(inputStream, buffer))\n return false;\n break;\n }\n default:\n throw new VoldemortException(\" Unrecognized Voldemort OpCode \" + opCode);\n }\n // This should not happen, if we reach here and if buffer has more\n // data, there is something wrong.\n if(buffer.hasRemaining()) {\n logger.info(\"Probably a client bug, Discarding additional bytes in isCompleteRequest. Opcode: \"\n + opCode + \", remaining bytes: \" + buffer.remaining());\n }\n return true;\n } catch(IOException 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.isDebugEnabled())\n logger.debug(\"Probable partial read occurred causing exception\", e);\n\n return false;\n }\n }", "protected void copyClasspathResource(File outputDirectory,\n String resourceName,\n String targetFileName) throws IOException\n {\n String resourcePath = classpathPrefix + resourceName;\n InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(resourcePath);\n copyStream(outputDirectory, resourceStream, targetFileName);\n }", "public static dnspolicy_dnspolicylabel_binding[] get(nitro_service service, String name) throws Exception{\n\t\tdnspolicy_dnspolicylabel_binding obj = new dnspolicy_dnspolicylabel_binding();\n\t\tobj.set_name(name);\n\t\tdnspolicy_dnspolicylabel_binding response[] = (dnspolicy_dnspolicylabel_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void beforeBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final Method methodSetExecuteBatch;\r\n final Method methodSendBatch;\r\n methodSetExecuteBatch = ClassHelper.getMethod(stmt, \"setExecuteBatch\", PARAM_TYPE_INTEGER);\r\n methodSendBatch = ClassHelper.getMethod(stmt, \"sendBatch\", null);\r\n\r\n final boolean statementBatchingSupported = methodSetExecuteBatch != null && methodSendBatch != null;\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n // Set number of statements per batch\r\n methodSetExecuteBatch.invoke(stmt, PARAM_STATEMENT_BATCH_SIZE);\r\n m_batchStatementsInProgress.put(stmt, methodSendBatch);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new PlatformException(e.getLocalizedMessage(), e);\r\n }\r\n }\r\n else\r\n {\r\n super.beforeBatch(stmt);\r\n }\r\n }", "public static String encodePath(String path, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(path, encoding, HierarchicalUriComponents.Type.PATH);\n\t}" ]
Adjust submatrices and helper data structures for the input matrix. Must be called before the decomposition can be computed. @param orig
[ "private void setup(DMatrixRBlock orig) {\n blockLength = orig.blockLength;\n dataW.blockLength = blockLength;\n dataWTA.blockLength = blockLength;\n\n this.dataA = orig;\n A.original = dataA;\n\n int l = Math.min(blockLength,orig.numCols);\n dataW.reshape(orig.numRows,l,false);\n dataWTA.reshape(l,orig.numRows,false);\n Y.original = orig;\n Y.row1 = W.row1 = orig.numRows;\n if( temp.length < blockLength )\n temp = new double[blockLength];\n if( gammas.length < orig.numCols )\n gammas = new double[ orig.numCols ];\n\n if( saveW ) {\n dataW.reshape(orig.numRows,orig.numCols,false);\n }\n }" ]
[ "private void writeCalendars() throws JAXBException\n {\n //\n // Create the new Planner calendar list\n //\n Calendars calendars = m_factory.createCalendars();\n m_plannerProject.setCalendars(calendars);\n writeDayTypes(calendars);\n List<net.sf.mpxj.planner.schema.Calendar> calendar = calendars.getCalendar();\n\n //\n // Process each calendar in turn\n //\n for (ProjectCalendar mpxjCalendar : m_projectFile.getCalendars())\n {\n net.sf.mpxj.planner.schema.Calendar plannerCalendar = m_factory.createCalendar();\n calendar.add(plannerCalendar);\n writeCalendar(mpxjCalendar, plannerCalendar);\n }\n }", "public RenderScript getRenderScript() {\n if (renderScript == null) {\n renderScript = RenderScript.create(context, renderScriptContextType);\n }\n return renderScript;\n }", "public ProjectCalendar addDefaultDerivedCalendar()\n {\n ProjectCalendar calendar = add();\n\n calendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n\n return (calendar);\n }", "public ItemRequest<Tag> findById(String tag) {\n \n String path = String.format(\"/tags/%s\", tag);\n return new ItemRequest<Tag>(this, Tag.class, path, \"GET\");\n }", "@Override\n public void begin(String namespace, String name, Attributes attributes) throws Exception {\n\n // not now: 6.0.0\n // digester.setLogger(CmsLog.getLog(digester.getClass()));\n\n // Push an array to capture the parameter values if necessary\n if (m_paramCount > 0) {\n Object[] parameters = new Object[m_paramCount];\n for (int i = 0; i < parameters.length; i++) {\n parameters[i] = null;\n }\n getDigester().pushParams(parameters);\n }\n }", "private String getResourceField(int key)\n {\n String result = null;\n\n if (key > 0 && key < m_resourceNames.length)\n {\n result = m_resourceNames[key];\n }\n\n return (result);\n }", "public static void main(String[] args) {\r\n try {\r\n TreeFactory tf = new LabeledScoredTreeFactory();\r\n Reader r = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), \"UTF-8\"));\r\n TreeReader tr = new PennTreeReader(r, tf);\r\n Tree t = tr.readTree();\r\n while (t != null) {\r\n System.out.println(t);\r\n System.out.println();\r\n t = tr.readTree();\r\n }\r\n r.close();\r\n } catch (IOException ioe) {\r\n ioe.printStackTrace();\r\n }\r\n }", "private Long string2long(String text, DateTimeFormat fmt) {\n \n // null or \"\" returns null\n if (text == null) return null;\n text = text.trim();\n if (text.length() == 0) return null;\n \n Date date = fmt.parse(text);\n return date != null ? UTCDateBox.date2utc(date) : null;\n }", "@SuppressWarnings(\"WeakerAccess\")\n public String formatCueCountdown() {\n int count = getCueCountdown();\n\n if (count == 511) {\n return \"--.-\";\n }\n\n if ((count >= 1) && (count <= 256)) {\n int bars = (count - 1) / 4;\n int beats = ((count - 1) % 4) + 1;\n return String.format(\"%02d.%d\", bars, beats);\n }\n\n if (count == 0) {\n return \"00.0\";\n }\n\n return \"??.?\";\n }" ]
Use this API to add systemuser.
[ "public static base_response add(nitro_service client, systemuser resource) throws Exception {\n\t\tsystemuser addresource = new systemuser();\n\t\taddresource.username = resource.username;\n\t\taddresource.password = resource.password;\n\t\taddresource.externalauth = resource.externalauth;\n\t\taddresource.promptstring = resource.promptstring;\n\t\taddresource.timeout = resource.timeout;\n\t\treturn addresource.add_resource(client);\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 }", "public void addColumnPair(String localColumn, String remoteColumn)\r\n {\r\n if (!_localColumns.contains(localColumn))\r\n { \r\n _localColumns.add(localColumn);\r\n }\r\n if (!_remoteColumns.contains(remoteColumn))\r\n { \r\n _remoteColumns.add(remoteColumn);\r\n }\r\n }", "private static void bodyWithBuilder(\n SourceBuilder code,\n Datatype datatype,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n String typename,\n Predicate<PropertyCodeGenerator> isOptional) {\n Variable result = new Variable(\"result\");\n\n code.add(\" %1$s %2$s = new %1$s(\\\"%3$s{\", StringBuilder.class, result, typename);\n boolean midStringLiteral = true;\n boolean midAppends = true;\n boolean prependCommas = false;\n\n PropertyCodeGenerator lastOptionalGenerator = generatorsByProperty.values()\n .stream()\n .filter(isOptional)\n .reduce((first, second) -> second)\n .get();\n\n for (Property property : generatorsByProperty.keySet()) {\n PropertyCodeGenerator generator = generatorsByProperty.get(property);\n if (isOptional.test(generator)) {\n if (midStringLiteral) {\n code.add(\"\\\")\");\n }\n if (midAppends) {\n code.add(\";%n \");\n }\n code.add(\"if (\");\n if (generator.initialState() == Initially.OPTIONAL) {\n generator.addToStringCondition(code);\n } else {\n code.add(\"!%s.contains(%s.%s)\",\n UNSET_PROPERTIES, datatype.getPropertyEnum(), property.getAllCapsName());\n }\n code.add(\") {%n %s.append(\\\"\", result);\n if (prependCommas) {\n code.add(\", \");\n }\n code.add(\"%s=\\\").append(%s)\", property.getName(), property.getField());\n if (!prependCommas) {\n code.add(\".append(\\\", \\\")\");\n }\n code.add(\";%n }%n \");\n if (generator.equals(lastOptionalGenerator)) {\n code.add(\"return %s.append(\\\"\", result);\n midStringLiteral = true;\n midAppends = true;\n } else {\n midStringLiteral = false;\n midAppends = false;\n }\n } else {\n if (!midAppends) {\n code.add(\"%s\", result);\n }\n if (!midStringLiteral) {\n code.add(\".append(\\\"\");\n }\n if (prependCommas) {\n code.add(\", \");\n }\n code.add(\"%s=\\\").append(%s)\", property.getName(), (Excerpt) generator::addToStringValue);\n midStringLiteral = false;\n midAppends = true;\n prependCommas = true;\n }\n }\n\n checkState(prependCommas, \"Unexpected state at end of toString method\");\n checkState(midAppends, \"Unexpected state at end of toString method\");\n if (!midStringLiteral) {\n code.add(\".append(\\\"\");\n }\n code.add(\"}\\\").toString();%n\", result);\n }", "public static SVGGraphics2D createSvgGraphics(final Dimension size)\n throws ParserConfigurationException {\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n DocumentBuilder db = dbf.newDocumentBuilder();\n Document document = db.getDOMImplementation().createDocument(null, \"svg\", null);\n\n SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);\n ctx.setStyleHandler(new OpacityAdjustingStyleHandler());\n ctx.setComment(\"Generated by GeoTools2 with Batik SVG Generator\");\n\n SVGGraphics2D g2d = new SVGGraphics2D(ctx, true);\n g2d.setSVGCanvasSize(size);\n\n return g2d;\n }", "public static Field[] getDeclaredFieldsInHierarchy(Class<?> clazz) {\n\n if (clazz.isPrimitive()) {\n throw new IllegalArgumentException(\"Primitive types not supported.\");\n }\n\n List<Field> result = new ArrayList<Field>();\n\n while (true) {\n\n if (clazz == Object.class) {\n break;\n }\n\n result.addAll(Arrays.asList(clazz.getDeclaredFields()));\n clazz = clazz.getSuperclass();\n }\n\n return result.toArray(new Field[result.size()]);\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 String getDynamicAttributeValue(\n CmsFile file,\n I_CmsXmlContentValue value,\n String attributeName,\n CmsEntity editedLocalEntity) {\n\n if ((null != editedLocalEntity) && (editedLocalEntity.getAttribute(attributeName) != null)) {\n getSessionCache().setDynamicValue(\n attributeName,\n editedLocalEntity.getAttribute(attributeName).getSimpleValue());\n }\n String currentValue = getSessionCache().getDynamicValue(attributeName);\n if (null != currentValue) {\n return currentValue;\n }\n if (null != file) {\n if (value.getTypeName().equals(CmsXmlDynamicCategoryValue.TYPE_NAME)) {\n List<CmsCategory> categories = new ArrayList<CmsCategory>(0);\n try {\n categories = CmsCategoryService.getInstance().readResourceCategories(getCmsObject(), file);\n } catch (CmsException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERROR_FAILED_READING_CATEGORIES_1), e);\n }\n I_CmsWidget widget = null;\n widget = CmsWidgetUtil.collectWidgetInfo(value).getWidget();\n if ((null != widget) && (widget instanceof CmsCategoryWidget)) {\n String mainCategoryPath = ((CmsCategoryWidget)widget).getStartingCategory(\n getCmsObject(),\n getCmsObject().getSitePath(file));\n StringBuffer pathes = new StringBuffer();\n for (CmsCategory category : categories) {\n if (category.getPath().startsWith(mainCategoryPath)) {\n String path = category.getBasePath() + category.getPath();\n path = getCmsObject().getRequestContext().removeSiteRoot(path);\n pathes.append(path).append(',');\n }\n }\n String dynamicConfigString = pathes.length() > 0 ? pathes.substring(0, pathes.length() - 1) : \"\";\n getSessionCache().setDynamicValue(attributeName, dynamicConfigString);\n return dynamicConfigString;\n }\n }\n }\n return \"\";\n\n }", "public static authenticationradiusaction[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tauthenticationradiusaction[] response = (authenticationradiusaction[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "private List<TimephasedCost> getTimephasedCostFixedAmount()\n {\n List<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n ProjectCalendar cal = getCalendar();\n\n double remainingCost = getRemainingCost().doubleValue();\n\n if (remainingCost > 0)\n {\n AccrueType accrueAt = getResource().getAccrueAt();\n\n if (accrueAt == AccrueType.START)\n {\n result.add(splitCostStart(cal, remainingCost, getStart()));\n }\n else\n if (accrueAt == AccrueType.END)\n {\n result.add(splitCostEnd(cal, remainingCost, getFinish()));\n }\n else\n {\n //for prorated, we have to deal with it differently depending on whether or not\n //any actual has been entered, since we want to mimic the other timephased data\n //where planned and actual values do not overlap\n double numWorkingDays = cal.getWork(getStart(), getFinish(), TimeUnit.DAYS).getDuration();\n double standardAmountPerDay = getCost().doubleValue() / numWorkingDays;\n\n if (getActualCost().intValue() > 0)\n {\n //need to get three possible blocks of data: one for the possible partial amount\n //overlap with timephased actual cost; one with all the standard amount days\n //that happen after the actual cost stops; and one with any remaining\n //partial day cost amount\n\n int numActualDaysUsed = (int) Math.ceil(getActualCost().doubleValue() / standardAmountPerDay);\n Date actualWorkFinish = cal.getDate(getStart(), Duration.getInstance(numActualDaysUsed, TimeUnit.DAYS), false);\n\n double partialDayActualAmount = getActualCost().doubleValue() % standardAmountPerDay;\n\n if (partialDayActualAmount > 0)\n {\n double dayAmount = standardAmountPerDay < remainingCost ? standardAmountPerDay - partialDayActualAmount : remainingCost;\n\n result.add(splitCostEnd(cal, dayAmount, actualWorkFinish));\n\n remainingCost -= dayAmount;\n }\n\n //see if there's anything left to work with\n if (remainingCost > 0)\n {\n //have to split up the amount into standard prorated amount days and whatever is left\n result.addAll(splitCostProrated(cal, remainingCost, standardAmountPerDay, cal.getNextWorkStart(actualWorkFinish)));\n }\n\n }\n else\n {\n //no actual cost to worry about, so just a standard split from the beginning of the assignment\n result.addAll(splitCostProrated(cal, remainingCost, standardAmountPerDay, getStart()));\n }\n }\n }\n\n return result;\n }" ]
Get bean for given name in the "thread" scope. @param name name of bean @param factory factory for new instances @return bean for this scope
[ "public Object get(String name, ObjectFactory<?> factory) {\n\t\tThreadScopeContext context = ThreadScopeContextHolder.getContext();\n\n\t\tObject result = context.getBean(name);\n\t\tif (null == result) {\n\t\t\tresult = factory.getObject();\n\t\t\tcontext.setBean(name, result);\n\t\t}\n\t\treturn result;\n\t}" ]
[ "private ProjectFile handleOleCompoundDocument(InputStream stream) throws Exception\n {\n POIFSFileSystem fs = new POIFSFileSystem(POIFSFileSystem.createNonClosingInputStream(stream));\n String fileFormat = MPPReader.getFileFormat(fs);\n if (fileFormat != null && fileFormat.startsWith(\"MSProject\"))\n {\n MPPReader reader = new MPPReader();\n addListeners(reader);\n return reader.read(fs);\n }\n return null;\n }", "public Map<String, CmsJspCategoryAccessBean> getReadResourceCategories() {\n\n if (null == m_resourceCategories) {\n m_resourceCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object resourceName) {\n\n try {\n CmsResource resource = m_cms.readResource(\n getRequestContext().removeSiteRoot((String)resourceName));\n return new CmsJspCategoryAccessBean(m_cms, resource);\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n });\n }\n return m_resourceCategories;\n }", "public static <T> void callInitializers(T instance, CreationalContext<T> creationalContext, BeanManagerImpl manager,\n Iterable<? extends MethodInjectionPoint<?, ?>> initializerMethods) {\n for (MethodInjectionPoint<?, ?> initializer : initializerMethods) {\n initializer.invoke(instance, null, manager, creationalContext, CreationException.class);\n }\n }", "public void recordAsyncOpTimeNs(SocketDestination dest, long opTimeNs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordAsyncOpTimeNs(null, opTimeNs);\n recordAsyncOpTimeNs(null, opTimeNs);\n } else {\n this.asynOpTimeRequestCounter.addRequest(opTimeNs);\n }\n }", "public void setTotalColorForColumn(int column, Color color){\r\n\t\tint map = (colors.length-1) - column;\r\n\t\tcolors[map][colors[0].length-1]=color;\r\n\t}", "public boolean projectExists(String name) throws IllegalArgumentException {\n if (name == null || name.isEmpty()) {\n throw new IllegalArgumentException(\"Project name cannot be empty\");\n }\n return listProjects().stream()\n .map(p -> p.getMetadata().getName())\n .anyMatch(Predicate.isEqual(name));\n }", "public void adjustGlassSize() {\n if (isGlassEnabled()) {\n ResizeHandler handler = getGlassResizer();\n if (handler != null) handler.onResize(null);\n }\n }", "public static VectorClock makeClock(Set<Integer> serverIds, long clockValue, long timestamp) {\n List<ClockEntry> clockEntries = new ArrayList<ClockEntry>(serverIds.size());\n for(Integer serverId: serverIds) {\n clockEntries.add(new ClockEntry(serverId.shortValue(), clockValue));\n }\n return new VectorClock(clockEntries, timestamp);\n }", "public static String formatDateTime(Context context, ReadablePartial time, int flags) {\n return android.text.format.DateUtils.formatDateTime(context, toMillis(time), flags | FORMAT_UTC);\n }" ]
Replies to this comment with another message. @param message the message for the reply. @return info about the newly created reply comment.
[ "public BoxComment.Info reply(String message) {\n JsonObject itemJSON = new JsonObject();\n itemJSON.add(\"type\", \"comment\");\n itemJSON.add(\"id\", this.getID());\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"item\", itemJSON);\n if (BoxComment.messageContainsMention(message)) {\n requestJSON.add(\"tagged_message\", message);\n } else {\n requestJSON.add(\"message\", message);\n }\n\n URL url = ADD_COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxComment addedComment = new BoxComment(this.getAPI(), responseJSON.get(\"id\").asString());\n return addedComment.new Info(responseJSON);\n }" ]
[ "public final PJsonArray optJSONArray(final String key, final PJsonArray defaultValue) {\n PJsonArray result = optJSONArray(key);\n return result != null ? result : defaultValue;\n }", "public String[] getItemsSelected() {\n List<String> selected = new LinkedList<>();\n for (int i = getIndexOffset(); i < listBox.getItemCount(); i++) {\n if (listBox.isItemSelected(i)) {\n selected.add(listBox.getValue(i));\n }\n }\n return selected.toArray(new String[selected.size()]);\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 static void registerTinyTypes(Class<?> head, Class<?>... tail) {\n final Set<HeaderDelegateProvider> systemRegisteredHeaderProviders = stealAcquireRefToHeaderDelegateProviders();\n register(head, systemRegisteredHeaderProviders);\n for (Class<?> tt : tail) {\n register(tt, systemRegisteredHeaderProviders);\n }\n }", "public static <ObjType, Hashable> Collection<ObjType> uniqueNonhashableObjects(Collection<ObjType> objects, Function<ObjType, Hashable> customHasher) {\r\n Map<Hashable, ObjType> hashesToObjects = new HashMap<Hashable, ObjType>();\r\n for (ObjType object : objects) {\r\n hashesToObjects.put(customHasher.apply(object), object);\r\n }\r\n return hashesToObjects.values();\r\n }", "@Override\r\n\tpublic boolean check(EmbeddedBrowser browser) {\r\n\t\tString js =\r\n\t\t\t\t\"try{ if(\" + expression + \"){return '1';}else{\" + \"return '0';}}catch(e){\"\r\n\t\t\t\t\t\t+ \" return '0';}\";\r\n\t\ttry {\r\n\t\t\tObject object = browser.executeJavaScript(js);\r\n\t\t\tif (object == null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\treturn object.toString().equals(\"1\");\r\n\t\t} catch (CrawljaxException e) {\r\n\t\t\t// Exception is caught, check failed so return false;\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}", "public static <K, V> Map<K, V> of(K key, V value) {\n return new ImmutableMapEntry<K, V>(key, value);\n }", "public static <T extends EObject> IScope scopeFor(Iterable<? extends T> elements,\n\t\t\tfinal Function<T, QualifiedName> nameComputation, IScope outer) {\n\t\treturn new SimpleScope(outer,scopedElementsFor(elements, nameComputation));\n\t}", "private void getSingleValue(Method method, Object object, Map<String, String> map)\n {\n Object value;\n try\n {\n value = filterValue(method.invoke(object));\n }\n catch (Exception ex)\n {\n value = ex.toString();\n }\n\n if (value != null)\n {\n map.put(getPropertyName(method), String.valueOf(value));\n }\n }" ]
Get a property of type java.util.Properties or return the default if no such property is defined @param props properties @param name the key @param defaultProperties default property if empty @return value from the property
[ "public static Properties getProps(Properties props, String name, Properties defaultProperties) {\n final String propString = props.getProperty(name);\n if (propString == null) return defaultProperties;\n String[] propValues = propString.split(\",\");\n if (propValues.length < 1) {\n throw new IllegalArgumentException(\"Illegal format of specifying properties '\" + propString + \"'\");\n }\n Properties properties = new Properties();\n for (int i = 0; i < propValues.length; i++) {\n String[] prop = propValues[i].split(\"=\");\n if (prop.length != 2) throw new IllegalArgumentException(\"Illegal format of specifying properties '\" + propValues[i] + \"'\");\n properties.put(prop[0], prop[1]);\n }\n return properties;\n }" ]
[ "private void checkBindings(EnhancedAnnotation<T> annotatedAnnotation) {\n Set<Annotation> bindings = annotatedAnnotation.getMetaAnnotations(Qualifier.class);\n if (bindings.size() > 0) {\n for (Annotation annotation : bindings) {\n if (!annotation.annotationType().equals(Named.class)) {\n throw MetadataLogger.LOG.qualifierOnStereotype(annotatedAnnotation);\n }\n }\n }\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 }", "public int execute(DatabaseConnection databaseConnection, T data, ID newId, ObjectCache objectCache)\n\t\t\tthrows SQLException {\n\t\ttry {\n\t\t\t// the arguments are the new-id and old-id\n\t\t\tObject[] args = new Object[] { convertIdToFieldObject(newId), extractIdToFieldObject(data) };\n\t\t\tint rowC = databaseConnection.update(statement, args, argFieldTypes);\n\t\t\tif (rowC > 0) {\n\t\t\t\tif (objectCache != null) {\n\t\t\t\t\tObject oldId = idField.extractJavaFieldValue(data);\n\t\t\t\t\tT obj = objectCache.updateId(clazz, oldId, newId);\n\t\t\t\t\tif (obj != null && obj != data) {\n\t\t\t\t\t\t// if our cached value is not the data that will be updated then we need to update it specially\n\t\t\t\t\t\tidField.assignField(connectionSource, obj, newId, false, objectCache);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// adjust the object to assign the new id\n\t\t\t\tidField.assignField(connectionSource, data, newId, false, objectCache);\n\t\t\t}\n\t\t\tlogger.debug(\"updating-id with statement '{}' and {} args, changed {} rows\", statement, args.length, rowC);\n\t\t\tif (args.length > 0) {\n\t\t\t\t// need to do the cast otherwise we only print the first object in args\n\t\t\t\tlogger.trace(\"updating-id arguments: {}\", (Object) args);\n\t\t\t}\n\t\t\treturn rowC;\n\t\t} catch (SQLException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Unable to run update-id stmt on object \" + data + \": \" + statement, e);\n\t\t}\n\t}", "protected void switchTab() {\n\n Component tab = m_tab.getSelectedTab();\n int pos = m_tab.getTabPosition(m_tab.getTab(tab));\n if (m_isWebOU) {\n if (pos == 0) {\n pos = 1;\n }\n }\n m_tab.setSelectedTab(pos + 1);\n }", "public static appqoepolicy[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tappqoepolicy obj = new appqoepolicy();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tappqoepolicy[] response = (appqoepolicy[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "public static boolean oracleExists(CuratorFramework curator) {\n boolean exists = false;\n try {\n exists = curator.checkExists().forPath(ZookeeperPath.ORACLE_SERVER) != null\n && !curator.getChildren().forPath(ZookeeperPath.ORACLE_SERVER).isEmpty();\n } catch (Exception nne) {\n if (nne instanceof KeeperException.NoNodeException) {\n // you'll do nothing\n } else {\n throw new RuntimeException(nne);\n }\n }\n return exists;\n }", "public void revertWorkingCopy() throws IOException, InterruptedException {\n build.getWorkspace()\n .act(new RevertWorkingCopyCallable(getLocation(), getSvnAuthenticationProvider(build), buildListener));\n }", "public static cmppolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tcmppolicy_stats obj = new cmppolicy_stats();\n\t\tobj.set_name(name);\n\t\tcmppolicy_stats response = (cmppolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "@SafeVarargs\n\tpublic static <T> Set<T> asSet(T... ts) {\n\t\tif ( ts == null ) {\n\t\t\treturn null;\n\t\t}\n\t\telse if ( ts.length == 0 ) {\n\t\t\treturn Collections.emptySet();\n\t\t}\n\t\telse {\n\t\t\tSet<T> set = new HashSet<T>( getInitialCapacityFromExpectedSize( ts.length ) );\n\t\t\tCollections.addAll( set, ts );\n\t\t\treturn Collections.unmodifiableSet( set );\n\t\t}\n\t}" ]
Returns the entry associated with the given key. @param key the key of the entry to look up @return the entry associated with that key, or null if the key is not in this map
[ "private Entry getEntry(Object key)\r\n {\r\n if (key == null) return null;\r\n int hash = hashCode(key);\r\n int index = indexFor(hash);\r\n for (Entry entry = table[index]; entry != null; entry = entry.next)\r\n {\r\n if ((entry.hash == hash) && equals(key, entry.getKey()))\r\n {\r\n return entry;\r\n }\r\n }\r\n return null;\r\n }" ]
[ "public String updateContextAndGetFavoriteUrl(CmsObject cms) throws CmsException {\n\n CmsResourceFilter filter = CmsResourceFilter.IGNORE_EXPIRATION;\n CmsProject project = null;\n switch (getType()) {\n case explorerFolder:\n CmsResource folder = cms.readResource(getStructureId(), filter);\n project = cms.readProject(getProjectId());\n cms.getRequestContext().setSiteRoot(getSiteRoot());\n cms.getRequestContext().setCurrentProject(project);\n String explorerLink = CmsVaadinUtils.getWorkplaceLink()\n + \"#!\"\n + CmsFileExplorerConfiguration.APP_ID\n + \"/\"\n + getProjectId()\n + \"!!\"\n + getSiteRoot()\n + \"!!\"\n + cms.getSitePath(folder);\n return explorerLink;\n case page:\n project = cms.readProject(getProjectId());\n CmsResource target = cms.readResource(getStructureId(), filter);\n CmsResource detailContent = null;\n String link = null;\n cms.getRequestContext().setCurrentProject(project);\n cms.getRequestContext().setSiteRoot(getSiteRoot());\n if (getDetailId() != null) {\n detailContent = cms.readResource(getDetailId());\n link = OpenCms.getLinkManager().substituteLinkForUnknownTarget(\n cms,\n cms.getSitePath(detailContent),\n cms.getSitePath(target),\n false);\n } else {\n link = OpenCms.getLinkManager().substituteLink(cms, target);\n }\n return link;\n default:\n return null;\n }\n }", "private void cascadeDeleteFor(ObjectEnvelope mod, List alreadyPrepared)\r\n {\r\n // avoid endless recursion\r\n if(alreadyPrepared.contains(mod.getIdentity())) return;\r\n\r\n alreadyPrepared.add(mod.getIdentity());\r\n\r\n ClassDescriptor cld = getTransaction().getBroker().getClassDescriptor(mod.getObject().getClass());\r\n\r\n List refs = cld.getObjectReferenceDescriptors(true);\r\n cascadeDeleteSingleReferences(mod, refs, alreadyPrepared);\r\n\r\n List colls = cld.getCollectionDescriptors(true);\r\n cascadeDeleteCollectionReferences(mod, colls, alreadyPrepared);\r\n }", "void countNonZeroInR( int[] parent ) {\n TriangularSolver_DSCC.postorder(parent,n,post,gwork);\n columnCounts.process(A,parent,post,countsR);\n nz_in_R = 0;\n for (int k = 0; k < n; k++) {\n nz_in_R += countsR[k];\n }\n if( nz_in_R < 0)\n throw new RuntimeException(\"Too many elements. Numerical overflow in R counts\");\n }", "@SuppressWarnings(\"rawtypes\")\n private static <T> Constructor<T> findConstructor(final Class<T> clazz, final Object... args)\n throws NoSuchConstructorException, AmbiguousConstructorException {\n final Object[] cArgs = (args == null) ? new Object[0] : args;\n Constructor<T> constructorToUse = null;\n final Constructor<?>[] candidates = clazz.getConstructors();\n Arrays.sort(candidates, ConstructorComparator.INSTANCE);\n int minTypeDiffWeight = Integer.MAX_VALUE;\n Set<Constructor<?>> ambiguousConstructors = null;\n for (final Constructor candidate : candidates) {\n final Class[] paramTypes = candidate.getParameterTypes();\n if (constructorToUse != null && cArgs.length > paramTypes.length) {\n // Already found greedy constructor that can be satisfied.\n // Do not look any further, there are only less greedy\n // constructors left.\n break;\n }\n if (paramTypes.length != cArgs.length) {\n continue;\n }\n final int typeDiffWeight = getTypeDifferenceWeight(paramTypes, cArgs);\n if (typeDiffWeight < minTypeDiffWeight) { \n // Choose this constructor if it represents the closest match.\n constructorToUse = candidate;\n minTypeDiffWeight = typeDiffWeight;\n ambiguousConstructors = null;\n } else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {\n if (ambiguousConstructors == null) {\n ambiguousConstructors = new LinkedHashSet<Constructor<?>>();\n ambiguousConstructors.add(constructorToUse);\n }\n ambiguousConstructors.add(candidate);\n }\n }\n if (ambiguousConstructors != null && !ambiguousConstructors.isEmpty()) {\n throw new AmbiguousConstructorException(clazz, cArgs, ambiguousConstructors);\n }\n if (constructorToUse == null) {\n throw new NoSuchConstructorException(clazz, cArgs);\n }\n return constructorToUse;\n }", "public void bind(T service, Map<String, Object> props) {\n synchronized (serviceMap) {\n serviceMap.put(ServiceUtil.getComparableForServiceRanking(props), service);\n updateSortedServices();\n }\n }", "protected void copyClasspathResource(File outputDirectory,\n String resourceName,\n String targetFileName) throws IOException\n {\n String resourcePath = classpathPrefix + resourceName;\n InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(resourcePath);\n copyStream(outputDirectory, resourceStream, targetFileName);\n }", "public void write(Configuration config)\n throws IOException {\n\n pp.startDocument();\n pp.startElement(\"duke\", null);\n\n // FIXME: here we should write the objects, but that's not\n // possible with the current API. we don't need that for the\n // genetic algorithm at the moment, but it would be useful.\n\n pp.startElement(\"schema\", null);\n\n writeElement(\"threshold\", \"\" + config.getThreshold());\n if (config.getMaybeThreshold() != 0.0)\n writeElement(\"maybe-threshold\", \"\" + config.getMaybeThreshold());\n\n for (Property p : config.getProperties())\n writeProperty(p);\n\n pp.endElement(\"schema\");\n\n String dbclass = config.getDatabase(false).getClass().getName();\n AttributeListImpl atts = new AttributeListImpl();\n atts.addAttribute(\"class\", \"CDATA\", dbclass);\n pp.startElement(\"database\", atts);\n pp.endElement(\"database\");\n\n if (config.isDeduplicationMode())\n for (DataSource src : config.getDataSources())\n writeDataSource(src);\n else {\n pp.startElement(\"group\", null);\n for (DataSource src : config.getDataSources(1))\n writeDataSource(src);\n pp.endElement(\"group\");\n\n pp.startElement(\"group\", null);\n for (DataSource src : config.getDataSources(2))\n writeDataSource(src);\n pp.endElement(\"group\");\n }\n\n pp.endElement(\"duke\");\n pp.endDocument();\n }", "public <T> Observable<ServiceResponse<T>> getPutOrPatchResultAsync(Observable<Response<ResponseBody>> observable, final Type resourceType) {\n return this.<T>beginPutOrPatchAsync(observable, resourceType)\n .toObservable()\n .flatMap(new Func1<PollingState<T>, Observable<PollingState<T>>>() {\n @Override\n public Observable<PollingState<T>> call(PollingState<T> pollingState) {\n return pollPutOrPatchAsync(pollingState, resourceType);\n }\n })\n .last()\n .map(new Func1<PollingState<T>, ServiceResponse<T>>() {\n @Override\n public ServiceResponse<T> call(PollingState<T> pollingState) {\n return new ServiceResponse<>(pollingState.resource(), pollingState.response());\n }\n });\n }", "public static String join(Collection<String> s, String delimiter) {\r\n return join(s, delimiter, false);\r\n }" ]
Override for customizing XmlMapper and ObjectMapper
[ "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 }" ]
[ "public Map<String, String> getMapAttribute(String name, String defaultValue) {\n return mapSplit(getAttribute(name), defaultValue);\n }", "public int nextToken() throws IOException\n {\n int c;\n int nextc = -1;\n boolean quoted = false;\n int result = m_next;\n if (m_next != 0)\n {\n m_next = 0;\n }\n\n m_buffer.setLength(0);\n\n while (result == 0)\n {\n if (nextc != -1)\n {\n c = nextc;\n nextc = -1;\n }\n else\n {\n c = read();\n }\n\n switch (c)\n {\n case TT_EOF:\n {\n if (m_buffer.length() != 0)\n {\n result = TT_WORD;\n m_next = TT_EOF;\n }\n else\n {\n result = TT_EOF;\n }\n break;\n }\n\n case TT_EOL:\n {\n int length = m_buffer.length();\n\n if (length != 0 && m_buffer.charAt(length - 1) == '\\r')\n {\n --length;\n m_buffer.setLength(length);\n }\n\n if (length == 0)\n {\n result = TT_EOL;\n }\n else\n {\n result = TT_WORD;\n m_next = TT_EOL;\n }\n\n break;\n }\n\n default:\n {\n if (c == m_quote)\n {\n if (quoted == false && startQuotedIsValid(m_buffer))\n {\n quoted = true;\n }\n else\n {\n if (quoted == false)\n {\n m_buffer.append((char) c);\n }\n else\n {\n nextc = read();\n if (nextc == m_quote)\n {\n m_buffer.append((char) c);\n nextc = -1;\n }\n else\n {\n quoted = false;\n }\n }\n }\n }\n else\n {\n if (c == m_delimiter && quoted == false)\n {\n result = TT_WORD;\n }\n else\n {\n m_buffer.append((char) c);\n }\n }\n }\n }\n }\n\n m_type = result;\n\n return (result);\n }", "public void setBREE(String bree) {\n\t\tString old = mainAttributes.get(BUNDLE_REQUIREDEXECUTIONENVIRONMENT);\n\t\tif (!bree.equals(old)) {\n\t\t\tthis.mainAttributes.put(BUNDLE_REQUIREDEXECUTIONENVIRONMENT, bree);\n\t\t\tthis.modified = true;\n\t\t\tthis.bree = bree;\n\t\t}\n\t}", "public static void closeWithWarning(Closeable c) {\n if (c != null) {\n try {\n c.close();\n } catch (IOException e) {\n LOG.warning(\"Caught exception during close(): \" + e);\n }\n }\n }", "private YearWeek with(int newYear, int newWeek) {\n if (year == newYear && week == newWeek) {\n return this;\n }\n return of(newYear, newWeek);\n }", "@Override\n public void setPosition(float x, float y, float z)\n {\n position.set(x, y, z);\n pickDir.set(x, y, z);\n pickDir.normalize();\n invalidate();\n }", "public void process(Resource resource, int index, byte[] data)\n {\n CostRateTable result = new CostRateTable();\n\n if (data != null)\n {\n for (int i = 16; i + 44 <= data.length; i += 44)\n {\n Rate standardRate = new Rate(MPPUtility.getDouble(data, i), TimeUnit.HOURS);\n TimeUnit standardRateFormat = getFormat(MPPUtility.getShort(data, i + 8));\n Rate overtimeRate = new Rate(MPPUtility.getDouble(data, i + 16), TimeUnit.HOURS);\n TimeUnit overtimeRateFormat = getFormat(MPPUtility.getShort(data, i + 24));\n Double costPerUse = NumberHelper.getDouble(MPPUtility.getDouble(data, i + 32) / 100.0);\n Date endDate = MPPUtility.getTimestampFromTenths(data, i + 40);\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate);\n result.add(entry);\n }\n Collections.sort(result);\n }\n else\n {\n //\n // MS Project economises by not actually storing the first cost rate\n // table if it doesn't need to, so we take this into account here.\n //\n if (index == 0)\n {\n Rate standardRate = resource.getStandardRate();\n Rate overtimeRate = resource.getOvertimeRate();\n Number costPerUse = resource.getCostPerUse();\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRate.getUnits(), overtimeRate, overtimeRate.getUnits(), costPerUse, CostRateTableEntry.DEFAULT_ENTRY.getEndDate());\n result.add(entry);\n }\n else\n {\n result.add(CostRateTableEntry.DEFAULT_ENTRY);\n }\n }\n\n resource.setCostRateTable(index, result);\n }", "public void clear() {\n List<Widget> children = getChildren();\n Log.d(TAG, \"clear(%s): removing %d children\", getName(), children.size());\n for (Widget child : children) {\n removeChild(child, true);\n }\n requestLayout();\n }", "public ItemRequest<Team> findById(String team) {\n \n String path = String.format(\"/teams/%s\", team);\n return new ItemRequest<Team>(this, Team.class, path, \"GET\");\n }" ]
Tokenizes lookup fields and returns all matching buckets in the index.
[ "private List<Bucket> lookup(Record record) {\n List<Bucket> buckets = new ArrayList();\n for (Property p : config.getLookupProperties()) {\n String propname = p.getName();\n Collection<String> values = record.getValues(propname);\n if (values == null)\n continue;\n\n for (String value : values) {\n String[] tokens = StringUtils.split(value);\n for (int ix = 0; ix < tokens.length; ix++) {\n Bucket b = store.lookupToken(propname, tokens[ix]);\n if (b == null || b.records == null)\n continue;\n long[] ids = b.records;\n if (DEBUG)\n System.out.println(propname + \", \" + tokens[ix] + \": \" + b.nextfree + \" (\" + b.getScore() + \")\");\n buckets.add(b);\n }\n }\n }\n\n return buckets;\n }" ]
[ "public static final void getByteArray(byte[] data, int offset, int size, byte[] buffer, int bufferOffset)\n {\n System.arraycopy(data, offset, buffer, bufferOffset, size);\n }", "public static String[] sortStringArray(String[] array) {\n if (isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }", "private Map<Integer, Integer> getNodeIdToPrimaryCount(Cluster cluster) {\n Map<Integer, Integer> nodeIdToPrimaryCount = Maps.newHashMap();\n for(Node node: cluster.getNodes()) {\n nodeIdToPrimaryCount.put(node.getId(), node.getPartitionIds().size());\n }\n\n return nodeIdToPrimaryCount;\n }", "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 }", "public static int getProfileIdFromPathID(int path_id) throws Exception {\n return (Integer) SQLService.getInstance().getFromTable(Constants.GENERIC_PROFILE_ID, Constants.GENERIC_ID, path_id, Constants.DB_TABLE_PATH);\n }", "public void forAllProcedures(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getProcedures(); it.hasNext(); )\r\n {\r\n _curProcedureDef = (ProcedureDef)it.next();\r\n generate(template);\r\n }\r\n _curProcedureDef = null;\r\n }", "private void createStringMappings(MtasTokenIdFactory mtasTokenIdFactory,\n Level level, String stringValue, int offsetStart, int offsetEnd,\n int position) throws IOException {\n // System.out.println(\"createStringMappings string \");\n String[] stringValues = MtasPennTreebankReader.createStrings(stringValue,\n Pattern.quote(STRING_SPLITTER));\n if (stringValues.length > 0 && !stringValues[0].trim().isEmpty()) {\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n \"t\", filterString(stringValues[0].trim()), position);\n token.setOffset(offsetStart, offsetEnd);\n tokenCollection.add(token);\n level.tokens.add(token);\n }\n if (stringValues.length > 1 && !stringValues[1].trim().isEmpty()) {\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n \"lemma\", filterString(stringValues[1].trim()), position);\n token.setOffset(offsetStart, offsetEnd);\n tokenCollection.add(token);\n level.tokens.add(token);\n }\n }", "@UiThread\n protected void collapseView() {\n setExpanded(false);\n onExpansionToggled(true);\n\n if (mParentViewHolderExpandCollapseListener != null) {\n mParentViewHolderExpandCollapseListener.onParentCollapsed(getAdapterPosition());\n }\n }", "public ThumborUrlBuilder align(VerticalAlign valign, HorizontalAlign halign) {\n return align(valign).align(halign);\n }" ]
refresh the most recent history entries @param limit number of entries to populate @param offset number of most recent entries to skip @return populated history entries @throws Exception exception
[ "public History[] refreshHistory(int limit, int offset) throws Exception {\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"limit\", String.valueOf(limit)),\n new BasicNameValuePair(\"offset\", String.valueOf(offset))\n };\n return constructHistory(params);\n }" ]
[ "public static int getPercentage(String percentage) {\n if (isNotEmpty(percentage) && isNumeric(percentage)) {\n int p = Integer.parseInt(percentage);\n return p;\n } else {\n return 0;\n }\n }", "public Where<T, ID> isNotNull(String columnName) throws SQLException {\n\t\taddClause(new IsNotNull(columnName, findColumnFieldType(columnName)));\n\t\treturn this;\n\t}", "public String astring(ImapRequestLineReader request) throws ProtocolException {\n char next = request.nextWordChar();\n switch (next) {\n case '\"':\n return consumeQuoted(request);\n case '{':\n return consumeLiteral(request);\n default:\n return atom(request);\n }\n }", "String checkVersion(String pluginName, String dependency, String requestedVersion, String availableVersion) {\n\t\tif (null == availableVersion) {\n\t\t\treturn \"Dependency \" + dependency + \" not found for \" + pluginName + \", version \" + requestedVersion +\n\t\t\t\t\t\" or higher needed.\\n\";\n\t\t}\n\t\tif (requestedVersion.startsWith(EXPR_START) || availableVersion.startsWith(EXPR_START)) {\n\t\t\treturn \"\";\n\t\t}\n\t\tVersion requested = new Version(requestedVersion);\n\t\tVersion available = new Version(availableVersion);\n\t\tif (requested.getMajor() != available.getMajor()) {\n\t\t\treturn \"Dependency \" + dependency + \" is provided in a incompatible API version for plug-in \" +\n\t\t\t\t\tpluginName + \", which requests version \" + requestedVersion +\n\t\t\t\t\t\", but version \" + availableVersion + \" supplied.\\n\";\n\t\t}\n\t\tif (requested.after(available)) {\n\t\t\treturn \"Dependency \" + dependency + \" too old for \" + pluginName + \", version \" + requestedVersion +\n\t\t\t\t\t\" or higher needed, but version \" + availableVersion + \" supplied.\\n\";\n\t\t}\n\t\treturn \"\";\n\t}", "public void writeReferences() throws RDFHandlerException {\n\t\tIterator<Reference> referenceIterator = this.referenceQueue.iterator();\n\t\tfor (Resource resource : this.referenceSubjectQueue) {\n\t\t\tfinal Reference reference = referenceIterator.next();\n\t\t\tif (this.declaredReferences.add(resource)) {\n\t\t\t\twriteReference(reference, resource);\n\t\t\t}\n\t\t}\n\t\tthis.referenceSubjectQueue.clear();\n\t\tthis.referenceQueue.clear();\n\n\t\tthis.snakRdfConverter.writeAuxiliaryTriples();\n\t}", "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 }", "public static java.sql.Time rollTime(java.util.Date startDate, int period, int amount) {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(startDate);\n gc.add(period, amount);\n return new java.sql.Time(gc.getTime().getTime());\n }", "protected void appendTableWithJoins(TableAlias alias, StringBuffer where, StringBuffer buf)\r\n {\r\n int stmtFromPos = 0;\r\n byte joinSyntax = getJoinSyntaxType();\r\n\r\n if (joinSyntax == SQL92_JOIN_SYNTAX)\r\n {\r\n stmtFromPos = buf.length(); // store position of join (by: Terry Dexter)\r\n }\r\n\r\n if (alias == getRoot())\r\n {\r\n // BRJ: also add indirection table to FROM-clause for MtoNQuery \r\n if (getQuery() instanceof MtoNQuery)\r\n {\r\n MtoNQuery mnQuery = (MtoNQuery)m_query; \r\n buf.append(getTableAliasForPath(mnQuery.getIndirectionTable(), null).getTableAndAlias());\r\n buf.append(\", \");\r\n } \r\n buf.append(alias.getTableAndAlias());\r\n }\r\n else if (joinSyntax != SQL92_NOPAREN_JOIN_SYNTAX)\r\n {\r\n buf.append(alias.getTableAndAlias());\r\n }\r\n\r\n if (!alias.hasJoins())\r\n {\r\n return;\r\n }\r\n\r\n for (Iterator it = alias.iterateJoins(); it.hasNext();)\r\n {\r\n Join join = (Join) it.next();\r\n\r\n if (joinSyntax == SQL92_JOIN_SYNTAX)\r\n {\r\n appendJoinSQL92(join, where, buf);\r\n if (it.hasNext())\r\n {\r\n buf.insert(stmtFromPos, \"(\");\r\n buf.append(\")\");\r\n }\r\n }\r\n else if (joinSyntax == SQL92_NOPAREN_JOIN_SYNTAX)\r\n {\r\n appendJoinSQL92NoParen(join, where, buf);\r\n }\r\n else\r\n {\r\n appendJoin(where, buf, join);\r\n }\r\n\r\n }\r\n }", "public static Node addPartitionsToNode(final Node node, final Set<Integer> donatedPartitions) {\n List<Integer> deepCopy = new ArrayList<Integer>(node.getPartitionIds());\n deepCopy.addAll(donatedPartitions);\n Collections.sort(deepCopy);\n return updateNode(node, deepCopy);\n }" ]
Normalizes the name so it can be used as Maven artifactId or groupId.
[ "private static String normalizeDirName(String name)\n {\n if(name == null)\n return null;\n return name.toLowerCase().replaceAll(\"[^a-zA-Z0-9]\", \"-\");\n }" ]
[ "public Map<String, EntityDocument> wbGetEntities(\n\t\t\tWbGetEntitiesActionData properties)\n\t\t\tthrows MediaWikiApiErrorException, IOException {\n\t\treturn wbGetEntities(properties.ids, properties.sites,\n\t\t\t\tproperties.titles, properties.props, properties.languages,\n\t\t\t\tproperties.sitefilter);\n\t}", "public void initialize() {\n\t\tif (dataClass == null) {\n\t\t\tthrow new IllegalStateException(\"dataClass was never set on \" + getClass().getSimpleName());\n\t\t}\n\t\tif (tableName == null) {\n\t\t\ttableName = extractTableName(databaseType, dataClass);\n\t\t}\n\t}", "public static OptionalString ofNullable(ResourceKey key, String value) {\n return new GenericOptionalString(RUNTIME_SOURCE, key, value);\n }", "@Nonnull\n public final Style getDefaultStyle(@Nonnull final String geometryType) {\n String normalizedGeomName = GEOMETRY_NAME_ALIASES.get(geometryType.toLowerCase());\n if (normalizedGeomName == null) {\n normalizedGeomName = geometryType.toLowerCase();\n }\n Style style = this.defaultStyle.get(normalizedGeomName.toLowerCase());\n if (style == null) {\n style = this.namedStyles.get(normalizedGeomName.toLowerCase());\n }\n\n if (style == null) {\n StyleBuilder builder = new StyleBuilder();\n final Symbolizer symbolizer;\n if (isPointType(normalizedGeomName)) {\n symbolizer = builder.createPointSymbolizer();\n } else if (isLineType(normalizedGeomName)) {\n symbolizer = builder.createLineSymbolizer(Color.black, 2);\n } else if (isPolygonType(normalizedGeomName)) {\n symbolizer = builder.createPolygonSymbolizer(Color.lightGray, Color.black, 2);\n } else if (normalizedGeomName.equalsIgnoreCase(Constants.Style.Raster.NAME)) {\n symbolizer = builder.createRasterSymbolizer();\n } else if (normalizedGeomName.startsWith(Constants.Style.OverviewMap.NAME)) {\n symbolizer = createMapOverviewStyle(normalizedGeomName, builder);\n } else {\n final Style geomStyle = this.defaultStyle.get(Geometry.class.getSimpleName().toLowerCase());\n if (geomStyle != null) {\n return geomStyle;\n } else {\n symbolizer = builder.createPointSymbolizer();\n }\n }\n style = builder.createStyle(symbolizer);\n }\n return style;\n }", "private List<Point2D> merge(final List<Point2D> one, final List<Point2D> two) {\n final Set<Point2D> oneSet = new HashSet<Point2D>(one);\n for (Point2D item : two) {\n if (!oneSet.contains(item)) {\n one.add(item);\n }\n }\n return one;\n }", "private synchronized HostServerGroupEffect getMappableDomainEffect(PathAddress address, String key,\n Map<String, Set<String>> map, Resource root) {\n if (requiresMapping) {\n map(root);\n requiresMapping = false;\n }\n Set<String> mapped = map.get(key);\n return mapped != null ? HostServerGroupEffect.forDomain(address, mapped)\n : HostServerGroupEffect.forUnassignedDomain(address);\n }", "protected void afterMaterialization()\r\n\t{\r\n\t\tif (_listeners != null)\r\n\t\t{\r\n\t\t\tMaterializationListener listener;\r\n\r\n\t\t\t// listeners may remove themselves during the afterMaterialization\r\n\t\t\t// callback.\r\n\t\t\t// thus we must iterate through the listeners vector from back to\r\n\t\t\t// front\r\n\t\t\t// to avoid index problems.\r\n\t\t\tfor (int idx = _listeners.size() - 1; idx >= 0; idx--)\r\n\t\t\t{\r\n\t\t\t\tlistener = (MaterializationListener) _listeners.get(idx);\r\n\t\t\t\tlistener.afterMaterialization(this, _realSubject);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "private int getPrototypeIndex(Renderer renderer) {\n int index = 0;\n for (Renderer prototype : prototypes) {\n if (prototype.getClass().equals(renderer.getClass())) {\n break;\n }\n index++;\n }\n return index;\n }", "protected List<Versioned<V>> resolveAndConstructVersionsToPersist(List<Versioned<V>> valuesInStorage,\n List<Versioned<V>> multiPutValues) {\n List<Versioned<V>> obsoleteVals = new ArrayList<Versioned<V>>(multiPutValues.size());\n // Go over all the values and determine whether the version is\n // acceptable\n for(Versioned<V> value: multiPutValues) {\n Iterator<Versioned<V>> iter = valuesInStorage.iterator();\n boolean obsolete = false;\n // Compare the current version with a set of accepted versions\n while(iter.hasNext()) {\n Versioned<V> curr = iter.next();\n Occurred occurred = value.getVersion().compare(curr.getVersion());\n if(occurred == Occurred.BEFORE) {\n obsolete = true;\n break;\n } else if(occurred == Occurred.AFTER) {\n iter.remove();\n }\n }\n if(obsolete) {\n // add to return value if obsolete\n obsoleteVals.add(value);\n } else {\n // else update the set of accepted versions\n valuesInStorage.add(value);\n }\n }\n\n return obsoleteVals;\n }" ]
Divide two complex numbers. @param z1 Complex Number. @param z2 Complex Number. @return Returns new ComplexNumber instance containing the divide of specified complex numbers.
[ "public static ComplexNumber Divide(ComplexNumber z1, ComplexNumber z2) {\r\n\r\n ComplexNumber conj = ComplexNumber.Conjugate(z2);\r\n\r\n double a = z1.real * conj.real + ((z1.imaginary * conj.imaginary) * -1);\r\n double b = z1.real * conj.imaginary + (z1.imaginary * conj.real);\r\n\r\n double c = z2.real * conj.real + ((z2.imaginary * conj.imaginary) * -1);\r\n\r\n return new ComplexNumber(a / c, b / c);\r\n }" ]
[ "public static Class<?> getRawType(Type type) {\n\t\tif (type instanceof Class) {\n\t\t\treturn (Class<?>) type;\n\t\t} else if (type instanceof ParameterizedType) {\n\t\t\tParameterizedType actualType = (ParameterizedType) type;\n\t\t\treturn getRawType(actualType.getRawType());\n\t\t} else if (type instanceof GenericArrayType) {\n\t\t\tGenericArrayType genericArrayType = (GenericArrayType) type;\n\t\t\tObject rawArrayType = Array.newInstance(getRawType(genericArrayType\n\t\t\t\t\t.getGenericComponentType()), 0);\n\t\t\treturn rawArrayType.getClass();\n\t\t} else if (type instanceof WildcardType) {\n\t\t\tWildcardType castedType = (WildcardType) type;\n\t\t\treturn getRawType(castedType.getUpperBounds()[0]);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Type \\'\"\n\t\t\t\t\t\t\t+ type\n\t\t\t\t\t\t\t+ \"\\' is not a Class, \"\n\t\t\t\t\t\t\t+ \"ParameterizedType, or GenericArrayType. Can't extract class.\");\n\t\t}\n\t}", "private Integer getOutlineLevel(Task task)\n {\n String value = task.getWBS();\n Integer result = Integer.valueOf(1);\n if (value != null && value.length() > 0)\n {\n String[] path = WBS_SPLIT_REGEX.split(value);\n result = Integer.valueOf(path.length);\n }\n return result;\n }", "@Override\n protected <T> CompletableFuture<T> doExecute(Command<T> command) throws Exception {\n final CompletableFuture<T> future = new CompletableFuture<>();\n executor.execute(() -> {\n try {\n future.complete(blockingExecute(command));\n } catch (Throwable t) {\n future.completeExceptionally(t);\n }\n });\n return future;\n }", "public void addIn(Object attribute, Query subQuery)\r\n {\r\n // PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getUserAlias(attribute)));\r\n }", "@PostConstruct\n public void checkUniqueSchemes() {\n Multimap<String, ConfigFileLoaderPlugin> schemeToPluginMap = HashMultimap.create();\n\n for (ConfigFileLoaderPlugin plugin: getLoaderPlugins()) {\n schemeToPluginMap.put(plugin.getUriScheme(), plugin);\n }\n\n StringBuilder violations = new StringBuilder();\n for (String scheme: schemeToPluginMap.keySet()) {\n final Collection<ConfigFileLoaderPlugin> plugins = schemeToPluginMap.get(scheme);\n if (plugins.size() > 1) {\n violations.append(\"\\n\\n* \").append(\"There are has multiple \")\n .append(ConfigFileLoaderPlugin.class.getSimpleName())\n .append(\" plugins that support the scheme: '\").append(scheme).append('\\'')\n .append(\":\\n\\t\").append(plugins);\n }\n }\n\n if (violations.length() > 0) {\n throw new IllegalStateException(violations.toString());\n }\n }", "public static base_responses delete(nitro_service client, String hostname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (hostname != null && hostname.length > 0) {\n\t\t\tdnsaaaarec deleteresources[] = new dnsaaaarec[hostname.length];\n\t\t\tfor (int i=0;i<hostname.length;i++){\n\t\t\t\tdeleteresources[i] = new dnsaaaarec();\n\t\t\t\tdeleteresources[i].hostname = hostname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public static base_response add(nitro_service client, vpnsessionaction resource) throws Exception {\n\t\tvpnsessionaction addresource = new vpnsessionaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.httpport = resource.httpport;\n\t\taddresource.winsip = resource.winsip;\n\t\taddresource.dnsvservername = resource.dnsvservername;\n\t\taddresource.splitdns = resource.splitdns;\n\t\taddresource.sesstimeout = resource.sesstimeout;\n\t\taddresource.clientsecurity = resource.clientsecurity;\n\t\taddresource.clientsecuritygroup = resource.clientsecuritygroup;\n\t\taddresource.clientsecuritymessage = resource.clientsecuritymessage;\n\t\taddresource.clientsecuritylog = resource.clientsecuritylog;\n\t\taddresource.splittunnel = resource.splittunnel;\n\t\taddresource.locallanaccess = resource.locallanaccess;\n\t\taddresource.rfc1918 = resource.rfc1918;\n\t\taddresource.spoofiip = resource.spoofiip;\n\t\taddresource.killconnections = resource.killconnections;\n\t\taddresource.transparentinterception = resource.transparentinterception;\n\t\taddresource.windowsclienttype = resource.windowsclienttype;\n\t\taddresource.defaultauthorizationaction = resource.defaultauthorizationaction;\n\t\taddresource.authorizationgroup = resource.authorizationgroup;\n\t\taddresource.clientidletimeout = resource.clientidletimeout;\n\t\taddresource.proxy = resource.proxy;\n\t\taddresource.allprotocolproxy = resource.allprotocolproxy;\n\t\taddresource.httpproxy = resource.httpproxy;\n\t\taddresource.ftpproxy = resource.ftpproxy;\n\t\taddresource.socksproxy = resource.socksproxy;\n\t\taddresource.gopherproxy = resource.gopherproxy;\n\t\taddresource.sslproxy = resource.sslproxy;\n\t\taddresource.proxyexception = resource.proxyexception;\n\t\taddresource.proxylocalbypass = resource.proxylocalbypass;\n\t\taddresource.clientcleanupprompt = resource.clientcleanupprompt;\n\t\taddresource.forcecleanup = resource.forcecleanup;\n\t\taddresource.clientoptions = resource.clientoptions;\n\t\taddresource.clientconfiguration = resource.clientconfiguration;\n\t\taddresource.sso = resource.sso;\n\t\taddresource.ssocredential = resource.ssocredential;\n\t\taddresource.windowsautologon = resource.windowsautologon;\n\t\taddresource.usemip = resource.usemip;\n\t\taddresource.useiip = resource.useiip;\n\t\taddresource.clientdebug = resource.clientdebug;\n\t\taddresource.loginscript = resource.loginscript;\n\t\taddresource.logoutscript = resource.logoutscript;\n\t\taddresource.homepage = resource.homepage;\n\t\taddresource.icaproxy = resource.icaproxy;\n\t\taddresource.wihome = resource.wihome;\n\t\taddresource.citrixreceiverhome = resource.citrixreceiverhome;\n\t\taddresource.wiportalmode = resource.wiportalmode;\n\t\taddresource.clientchoices = resource.clientchoices;\n\t\taddresource.epaclienttype = resource.epaclienttype;\n\t\taddresource.iipdnssuffix = resource.iipdnssuffix;\n\t\taddresource.forcedtimeout = resource.forcedtimeout;\n\t\taddresource.forcedtimeoutwarning = resource.forcedtimeoutwarning;\n\t\taddresource.ntdomain = resource.ntdomain;\n\t\taddresource.clientlessvpnmode = resource.clientlessvpnmode;\n\t\taddresource.emailhome = resource.emailhome;\n\t\taddresource.clientlessmodeurlencoding = resource.clientlessmodeurlencoding;\n\t\taddresource.clientlesspersistentcookie = resource.clientlesspersistentcookie;\n\t\taddresource.allowedlogingroups = resource.allowedlogingroups;\n\t\taddresource.securebrowse = resource.securebrowse;\n\t\taddresource.storefronturl = resource.storefronturl;\n\t\taddresource.kcdaccount = resource.kcdaccount;\n\t\treturn addresource.add_resource(client);\n\t}", "private void createNodeMappings(MtasTokenIdFactory mtasTokenIdFactory,\n Level level, Level parentLevel) {\n MtasToken nodeToken;\n if (level.node != null && level.positionStart != null\n && level.positionEnd != null) {\n nodeToken = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n level.node, \"\");\n nodeToken.setOffset(level.offsetStart, level.offsetEnd);\n nodeToken.setRealOffset(level.realOffsetStart, level.realOffsetEnd);\n nodeToken.addPositionRange(level.positionStart, level.positionEnd);\n tokenCollection.add(nodeToken);\n if (parentLevel != null) {\n parentLevel.tokens.add(nodeToken);\n }\n // only for first mapping(?)\n for (MtasToken token : level.tokens) {\n token.setParentId(nodeToken.getId());\n }\n }\n }", "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 }" ]
Populate a Command instance with the values parsed from a command line If any parser errors are detected it will throw an exception @param processedCommand command line @param mode do validation or not @throws CommandLineParserException any incorrectness in the parser will abort the populate
[ "@Override\n public void populateObject(ProcessedCommand<Command<CI>, CI> processedCommand, InvocationProviders invocationProviders,\n AeshContext aeshContext, CommandLineParser.Mode mode)\n throws CommandLineParserException, OptionValidatorException {\n if(processedCommand.parserExceptions().size() > 0 && mode == CommandLineParser.Mode.VALIDATE)\n throw processedCommand.parserExceptions().get(0);\n for(ProcessedOption option : processedCommand.getOptions()) {\n if(option.getValues() != null && option.getValues().size() > 0)\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE );\n else if(option.getDefaultValues().size() > 0) {\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n }\n else if(option.getOptionType().equals(OptionType.GROUP) && option.getProperties().size() > 0)\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else\n resetField(getObject(), option.getFieldName(), option.hasValue());\n }\n //arguments\n if(processedCommand.getArguments() != null &&\n (processedCommand.getArguments().getValues().size() > 0 || processedCommand.getArguments().getDefaultValues().size() > 0))\n processedCommand.getArguments().injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else if(processedCommand.getArguments() != null)\n resetField(getObject(), processedCommand.getArguments().getFieldName(), true);\n //argument\n if(processedCommand.getArgument() != null &&\n (processedCommand.getArgument().getValues().size() > 0 || processedCommand.getArgument().getDefaultValues().size() > 0))\n processedCommand.getArgument().injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else if(processedCommand.getArgument() != null)\n resetField(getObject(), processedCommand.getArgument().getFieldName(), true);\n }" ]
[ "public void setWorkDir(String dir) throws IOException\r\n {\r\n File workDir = new File(dir);\r\n\r\n if (!workDir.exists() || !workDir.canWrite() || !workDir.canRead())\r\n {\r\n throw new IOException(\"Cannot access directory \"+dir);\r\n }\r\n _workDir = workDir;\r\n }", "public void setAttributeEditable(Attribute attribute, boolean editable) {\n\t\tattribute.setEditable(editable);\n\t\tif (!(attribute instanceof LazyAttribute)) { // should not instantiate lazy attributes!\n\t\t\tif (attribute instanceof ManyToOneAttribute) {\n\t\t\t\tsetAttributeEditable(((ManyToOneAttribute) attribute).getValue(), editable);\n\t\t\t} else if (attribute instanceof OneToManyAttribute) {\n\t\t\t\tList<AssociationValue> values = ((OneToManyAttribute) attribute).getValue();\n\t\t\t\tfor (AssociationValue value : values) {\n\t\t\t\t\tsetAttributeEditable(value, editable);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public IExternalAccess getAgentsExternalAccess(String agent_name) {\n\n return cmsService.getExternalAccess(getAgentID(agent_name)).get(\n new ThreadSuspendable());\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 }", "public static base_responses delete(nitro_service client, String selectorname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (selectorname != null && selectorname.length > 0) {\n\t\t\tcacheselector deleteresources[] = new cacheselector[selectorname.length];\n\t\t\tfor (int i=0;i<selectorname.length;i++){\n\t\t\t\tdeleteresources[i] = new cacheselector();\n\t\t\t\tdeleteresources[i].selectorname = selectorname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "private void getDailyDates(Calendar calendar, int frequency, List<Date> dates)\n {\n while (moreDates(calendar, dates))\n {\n dates.add(calendar.getTime());\n calendar.add(Calendar.DAY_OF_YEAR, frequency);\n }\n }", "private <T extends ProgramElementDoc> List<T> filterByVisibility(T[] docs, Visibility visibility) {\n\tif (visibility == Visibility.PRIVATE)\n\t return Arrays.asList(docs);\n\n\tList<T> filtered = new ArrayList<T>();\n\tfor (T doc : docs) {\n\t if (Visibility.get(doc).compareTo(visibility) > 0)\n\t\tfiltered.add(doc);\n\t}\n\treturn filtered;\n }", "public boolean addSsextension(String ssExt) {\n if (this.ssextensions == null) {\n this.ssextensions = new ArrayList<String>();\n }\n return this.ssextensions.add(ssExt);\n }", "public static autoscalepolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tautoscalepolicy_binding obj = new autoscalepolicy_binding();\n\t\tobj.set_name(name);\n\t\tautoscalepolicy_binding response = (autoscalepolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Convert weekly recurrence days into a bit field. @param task recurring task @return bit field as a string
[ "public static String getDays(RecurringTask task)\n {\n StringBuilder sb = new StringBuilder();\n for (Day day : Day.values())\n {\n sb.append(task.getWeeklyDay(day) ? \"1\" : \"0\");\n }\n return sb.toString();\n }" ]
[ "private void initializeQueue() {\n this.queue.clear();\n for (Map.Entry<String, NodeT> entry: nodeTable.entrySet()) {\n if (!entry.getValue().hasDependencies()) {\n this.queue.add(entry.getKey());\n }\n }\n if (queue.isEmpty()) {\n throw new IllegalStateException(\"Detected circular dependency\");\n }\n }", "public static void archiveFile(@NotNull final ArchiveOutputStream out,\n @NotNull final VirtualFileDescriptor source,\n final long fileSize) throws IOException {\n if (!source.hasContent()) {\n throw new IllegalArgumentException(\"Provided source is not a file: \" + source.getPath());\n }\n //noinspection ChainOfInstanceofChecks\n if (out instanceof TarArchiveOutputStream) {\n final TarArchiveEntry entry = new TarArchiveEntry(source.getPath() + source.getName());\n entry.setSize(fileSize);\n entry.setModTime(source.getTimeStamp());\n out.putArchiveEntry(entry);\n } else if (out instanceof ZipArchiveOutputStream) {\n final ZipArchiveEntry entry = new ZipArchiveEntry(source.getPath() + source.getName());\n entry.setSize(fileSize);\n entry.setTime(source.getTimeStamp());\n out.putArchiveEntry(entry);\n } else {\n throw new IOException(\"Unknown archive output stream\");\n }\n final InputStream input = source.getInputStream();\n try {\n IOUtil.copyStreams(input, fileSize, out, IOUtil.BUFFER_ALLOCATOR);\n } finally {\n if (source.shouldCloseStream()) {\n input.close();\n }\n }\n out.closeArchiveEntry();\n }", "private GregorianCalendar getLastReleventDate(GregorianCalendar currentDate) {\n\t\tint age=this.getProperties().getMaxFileAge();\n\t\tGregorianCalendar result=new GregorianCalendar(currentDate.get(Calendar.YEAR),currentDate.get(Calendar.MONTH),currentDate.get(Calendar.DAY_OF_MONTH));\n\t\tresult.add(Calendar.DAY_OF_MONTH, -age);\n\t\treturn result;\n\t}", "public static double blackScholesDigitalOptionRho(\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(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 if(optionStrike <= 0.0) {\n\t\t\tdouble rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity);\n\n\t\t\treturn rho;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate rho\n\t\t\tdouble dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\n\t\t\tdouble rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus)\n\t\t\t\t\t+ Math.sqrt(optionMaturity)/volatility * Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI);\n\n\t\t\treturn rho;\n\t\t}\n\t}", "private String formatPercentage(Number value)\n {\n return (value == null ? null : m_formats.getPercentageDecimalFormat().format(value) + \"%\");\n }", "@SuppressWarnings(\"unchecked\")\n\tpublic Map<String, ?> decodeSignedRequest(String signedRequest) throws SignedRequestException {\n\t\treturn decodeSignedRequest(signedRequest, Map.class);\n\t}", "public static <T> T createProxy(final Class<T> proxyInterface) {\n\t\tif( proxyInterface == null ) {\n\t\t\tthrow new NullPointerException(\"proxyInterface should not be null\");\n\t\t}\n\t\treturn proxyInterface.cast(Proxy.newProxyInstance(proxyInterface.getClassLoader(),\n\t\t\tnew Class[] { proxyInterface }, new BeanInterfaceProxy()));\n\t}", "public static String getDefaultJdbcTypeFor(String javaType)\r\n {\r\n return _jdbcMappings.containsKey(javaType) ? (String)_jdbcMappings.get(javaType) : JDBC_DEFAULT_TYPE;\r\n }", "public static base_responses delete(nitro_service client, String sitename[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (sitename != null && sitename.length > 0) {\n\t\t\tgslbsite deleteresources[] = new gslbsite[sitename.length];\n\t\t\tfor (int i=0;i<sitename.length;i++){\n\t\t\t\tdeleteresources[i] = new gslbsite();\n\t\t\t\tdeleteresources[i].sitename = sitename[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Checks to see if a handler is disabled @param handlerName the name of the handler to enable.
[ "private static boolean isDisabledHandler(final LogContext logContext, final String handlerName) {\n final Map<String, String> disableHandlers = logContext.getAttachment(CommonAttributes.ROOT_LOGGER_NAME, DISABLED_HANDLERS_KEY);\n return disableHandlers != null && disableHandlers.containsKey(handlerName);\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 void forAllForeignkeyColumnPairs(String template, Properties attributes) throws XDocletException\r\n {\r\n for (int idx = 0; idx < _curForeignkeyDef.getNumColumnPairs(); idx++)\r\n {\r\n _curPairLeft = _curForeignkeyDef.getLocalColumn(idx);\r\n _curPairRight = _curForeignkeyDef.getRemoteColumn(idx);\r\n generate(template);\r\n }\r\n _curPairLeft = null;\r\n _curPairRight = null;\r\n }", "@PrefMetadata(type = CmsTimeWarpPreference.class)\n public String getTimeWarp() {\n\n long warp = m_settings.getTimeWarp();\n return warp < 0 ? \"\" : \"\" + warp; // if timewarp < 0 (i.e. time warp is not set), use the empty string because we don't want the date selector widget to interpret the negative value\n }", "public static base_response Force(nitro_service client, hafailover resource) throws Exception {\n\t\thafailover Forceresource = new hafailover();\n\t\tForceresource.force = resource.force;\n\t\treturn Forceresource.perform_operation(client,\"Force\");\n\t}", "public static nsconfig diff(nitro_service client, nsconfig resource) throws Exception {\n\t\tnsconfig diffresource = new nsconfig();\n\t\tdiffresource.config1 = resource.config1;\n\t\tdiffresource.config2 = resource.config2;\n\t\tdiffresource.outtype = resource.outtype;\n\t\tdiffresource.template = resource.template;\n\t\tdiffresource.ignoredevicespecific = resource.ignoredevicespecific;\n\t\treturn (nsconfig)diffresource.perform_operationEx(client,\"diff\");\n\t}", "private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) {\n List<T> indexesOfType = new ArrayList<T>();\n Gson g = new Gson();\n for (JsonElement index : indexes) {\n if (index.isJsonObject()) {\n JsonObject indexDefinition = index.getAsJsonObject();\n JsonElement indexType = indexDefinition.get(\"type\");\n if (indexType != null && indexType.isJsonPrimitive()) {\n JsonPrimitive indexTypePrimitive = indexType.getAsJsonPrimitive();\n if (type == null || (indexTypePrimitive.isString() && indexTypePrimitive\n .getAsString().equals(type))) {\n indexesOfType.add(g.fromJson(indexDefinition, modelType));\n }\n }\n }\n }\n return indexesOfType;\n }", "@SuppressWarnings(\"unchecked\")\n private static void parseProperties(JSONObject modelJSON,\n Shape current,\n Boolean keepGlossaryLink) throws JSONException {\n if (modelJSON.has(\"properties\")) {\n JSONObject propsObject = modelJSON.getJSONObject(\"properties\");\n Iterator<String> keys = propsObject.keys();\n Pattern pattern = Pattern.compile(jsonPattern);\n\n while (keys.hasNext()) {\n StringBuilder result = new StringBuilder();\n int lastIndex = 0;\n String key = keys.next();\n String value = propsObject.getString(key);\n\n if (!keepGlossaryLink) {\n Matcher matcher = pattern.matcher(value);\n while (matcher.find()) {\n String id = matcher.group(1);\n current.addGlossaryIds(id);\n String text = matcher.group(2);\n result.append(text);\n lastIndex = matcher.end();\n }\n result.append(value.substring(lastIndex));\n value = result.toString();\n }\n\n current.putProperty(key,\n value);\n }\n }\n }", "public String getStatement() throws SQLException {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tappendSql(null, sb, new ArrayList<ArgumentHolder>());\n\t\treturn sb.toString();\n\t}", "public static dbdbprofile[] get(nitro_service service) throws Exception{\n\t\tdbdbprofile obj = new dbdbprofile();\n\t\tdbdbprofile[] response = (dbdbprofile[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Creates an encryptor for queryable text strings that uses standard password-based encryption. Uses a shared, or constant 16 byte initialization vector so encrypting the same data results in the same encryption result. This is done to allow encrypted data to be queried against. Encrypted text is hex-encoded. @param password the password used to generate the encryptor's secret key; should not be shared @param salt a hex-encoded, random, site-global salt value to use to generate the secret key
[ "public static TextEncryptor queryableText(CharSequence password, CharSequence salt) {\n\t\treturn new HexEncodingTextEncryptor(new AndroidAesBytesEncryptor(password.toString(), salt, AndroidKeyGenerators.shared(16)));\n\t}" ]
[ "public ContentAssistContext.Builder copy() {\n\t\tBuilder result = builderProvider.get();\n\t\tresult.copyFrom(this);\n\t\treturn result;\n\t}", "public void setHeaders(final Set<String> names) {\n // transform to lower-case because header names should be case-insensitive\n Set<String> lowerCaseNames = new HashSet<>();\n for (String name: names) {\n lowerCaseNames.add(name.toLowerCase());\n }\n this.headerNames = lowerCaseNames;\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 Jar setJarPrefix(Path file) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Really executable cannot be set after entries are added.\");\n if (file != null && jarPrefixStr != null)\n throw new IllegalStateException(\"A prefix has already been set (\" + jarPrefixStr + \")\");\n this.jarPrefixFile = file;\n return this;\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 void update(Record record, boolean isText) throws MPXJException\n {\n int length = record.getLength();\n\n for (int i = 0; i < length; i++)\n {\n if (isText == true)\n {\n add(getTaskCode(record.getString(i)));\n }\n else\n {\n add(record.getInteger(i).intValue());\n }\n }\n }", "public Duration getTotalSlack()\n {\n Duration totalSlack = (Duration) getCachedValue(TaskField.TOTAL_SLACK);\n if (totalSlack == null)\n {\n Duration duration = getDuration();\n if (duration == null)\n {\n duration = Duration.getInstance(0, TimeUnit.DAYS);\n }\n\n TimeUnit units = duration.getUnits();\n\n Duration startSlack = getStartSlack();\n if (startSlack == null)\n {\n startSlack = Duration.getInstance(0, units);\n }\n else\n {\n if (startSlack.getUnits() != units)\n {\n startSlack = startSlack.convertUnits(units, getParentFile().getProjectProperties());\n }\n }\n\n Duration finishSlack = getFinishSlack();\n if (finishSlack == null)\n {\n finishSlack = Duration.getInstance(0, units);\n }\n else\n {\n if (finishSlack.getUnits() != units)\n {\n finishSlack = finishSlack.convertUnits(units, getParentFile().getProjectProperties());\n }\n }\n\n double startSlackDuration = startSlack.getDuration();\n double finishSlackDuration = finishSlack.getDuration();\n\n if (startSlackDuration == 0 || finishSlackDuration == 0)\n {\n if (startSlackDuration != 0)\n {\n totalSlack = startSlack;\n }\n else\n {\n totalSlack = finishSlack;\n }\n }\n else\n {\n if (startSlackDuration < finishSlackDuration)\n {\n totalSlack = startSlack;\n }\n else\n {\n totalSlack = finishSlack;\n }\n }\n\n set(TaskField.TOTAL_SLACK, totalSlack);\n }\n\n return (totalSlack);\n }", "public ItemRequest<Section> insertInProject(String project) {\n \n String path = String.format(\"/projects/%s/sections/insert\", project);\n return new ItemRequest<Section>(this, Section.class, path, \"POST\");\n }", "public <FT, FID> BaseForeignCollection<FT, FID> buildForeignCollection(Object parent, FID id) throws SQLException {\n\t\t// this can happen if we have a foreign-auto-refresh scenario\n\t\tif (foreignFieldType == null) {\n\t\t\treturn null;\n\t\t}\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tDao<FT, FID> castDao = (Dao<FT, FID>) foreignDao;\n\t\tif (!fieldConfig.isForeignCollectionEager()) {\n\t\t\t// we know this won't go recursive so no need for the counters\n\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t}\n\n\t\t// try not to create level counter objects unless we have to\n\t\tLevelCounters levelCounters = threadLevelCounters.get();\n\t\tif (levelCounters == null) {\n\t\t\tif (fieldConfig.getForeignCollectionMaxEagerLevel() == 0) {\n\t\t\t\t// then return a lazy collection instead\n\t\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(),\n\t\t\t\t\t\tfieldConfig.isForeignCollectionOrderAscending());\n\t\t\t}\n\t\t\tlevelCounters = new LevelCounters();\n\t\t\tthreadLevelCounters.set(levelCounters);\n\t\t}\n\n\t\tif (levelCounters.foreignCollectionLevel == 0) {\n\t\t\tlevelCounters.foreignCollectionLevelMax = fieldConfig.getForeignCollectionMaxEagerLevel();\n\t\t}\n\t\t// are we over our level limit?\n\t\tif (levelCounters.foreignCollectionLevel >= levelCounters.foreignCollectionLevelMax) {\n\t\t\t// then return a lazy collection instead\n\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t}\n\t\tlevelCounters.foreignCollectionLevel++;\n\t\ttry {\n\t\t\treturn new EagerForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t} finally {\n\t\t\tlevelCounters.foreignCollectionLevel--;\n\t\t}\n\t}" ]
Deletes data associated with the given profile ID @param profileId ID of profile
[ "public void remove(int profileId) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_PROFILE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\");\n statement.setInt(1, profileId);\n statement.executeUpdate();\n statement.close();\n //also want to delete what is in the server redirect table\n statement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\");\n statement.setInt(1, profileId);\n statement.executeUpdate();\n statement.close();\n //also want to delete the path_profile table\n statement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_PATH +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\");\n statement.setInt(1, profileId);\n statement.executeUpdate();\n statement.close();\n //and the enabled overrides table\n statement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\");\n statement.setInt(1, profileId);\n statement.executeUpdate();\n statement.close();\n //and delete all the clients associated with this profile including the default client\n statement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\");\n statement.setInt(1, profileId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }" ]
[ "public float DistanceTo(IntPoint anotherPoint) {\r\n float dx = this.x - anotherPoint.x;\r\n float dy = this.y - anotherPoint.y;\r\n\r\n return (float) Math.sqrt(dx * dx + dy * dy);\r\n }", "public static base_response unset(nitro_service client, inatparam resource, String[] args) throws Exception{\n\t\tinatparam unsetresource = new inatparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "private void writeTask(Task mpxjTask, List<net.sf.mpxj.planner.schema.Task> taskList) throws JAXBException\n {\n net.sf.mpxj.planner.schema.Task plannerTask = m_factory.createTask();\n taskList.add(plannerTask);\n plannerTask.setEnd(getDateTimeString(mpxjTask.getFinish()));\n plannerTask.setId(getIntegerString(mpxjTask.getUniqueID()));\n plannerTask.setName(getString(mpxjTask.getName()));\n plannerTask.setNote(mpxjTask.getNotes());\n plannerTask.setPercentComplete(getIntegerString(mpxjTask.getPercentageWorkComplete()));\n plannerTask.setPriority(mpxjTask.getPriority() == null ? null : getIntegerString(mpxjTask.getPriority().getValue() * 10));\n plannerTask.setScheduling(getScheduling(mpxjTask.getType()));\n plannerTask.setStart(getDateTimeString(DateHelper.getDayStartDate(mpxjTask.getStart())));\n if (mpxjTask.getMilestone())\n {\n plannerTask.setType(\"milestone\");\n }\n else\n {\n plannerTask.setType(\"normal\");\n }\n plannerTask.setWork(getDurationString(mpxjTask.getWork()));\n plannerTask.setWorkStart(getDateTimeString(mpxjTask.getStart()));\n\n ConstraintType mpxjConstraintType = mpxjTask.getConstraintType();\n if (mpxjConstraintType != ConstraintType.AS_SOON_AS_POSSIBLE)\n {\n Constraint plannerConstraint = m_factory.createConstraint();\n plannerTask.setConstraint(plannerConstraint);\n if (mpxjConstraintType == ConstraintType.START_NO_EARLIER_THAN)\n {\n plannerConstraint.setType(\"start-no-earlier-than\");\n }\n else\n {\n if (mpxjConstraintType == ConstraintType.MUST_START_ON)\n {\n plannerConstraint.setType(\"must-start-on\");\n }\n }\n\n plannerConstraint.setTime(getDateTimeString(mpxjTask.getConstraintDate()));\n }\n\n //\n // Write predecessors\n //\n writePredecessors(mpxjTask, plannerTask);\n\n m_eventManager.fireTaskWrittenEvent(mpxjTask);\n\n //\n // Write child tasks\n //\n List<net.sf.mpxj.planner.schema.Task> childTaskList = plannerTask.getTask();\n for (Task task : mpxjTask.getChildTasks())\n {\n writeTask(task, childTaskList);\n }\n }", "public ResourceTransformerEntry resolveResourceTransformer(final PathAddress address, final PlaceholderResolver placeholderResolver) {\n return resolveResourceTransformer(address.iterator(), null, placeholderResolver);\n }", "void countNonZeroInR( int[] parent ) {\n TriangularSolver_DSCC.postorder(parent,n,post,gwork);\n columnCounts.process(A,parent,post,countsR);\n nz_in_R = 0;\n for (int k = 0; k < n; k++) {\n nz_in_R += countsR[k];\n }\n if( nz_in_R < 0)\n throw new RuntimeException(\"Too many elements. Numerical overflow in R counts\");\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 static ModelNode createListDeploymentsOperation() {\n final ModelNode op = createOperation(READ_CHILDREN_NAMES);\n op.get(CHILD_TYPE).set(DEPLOYMENT);\n return op;\n }", "public static Class<?> loadClass(String className) {\n try {\n return Class.forName(className);\n } catch(ClassNotFoundException e) {\n throw new IllegalArgumentException(e);\n }\n }", "public String[] getItemsSelected() {\n List<String> selected = new LinkedList<>();\n for (int i = getIndexOffset(); i < listBox.getItemCount(); i++) {\n if (listBox.isItemSelected(i)) {\n selected.add(listBox.getValue(i));\n }\n }\n return selected.toArray(new String[selected.size()]);\n }" ]
Use this API to add linkset.
[ "public static base_response add(nitro_service client, linkset resource) throws Exception {\n\t\tlinkset addresource = new linkset();\n\t\taddresource.id = resource.id;\n\t\treturn addresource.add_resource(client);\n\t}" ]
[ "@SuppressWarnings(\"unchecked\")\n public <T> T getOptionValue(String name)\n {\n return (T) configurationOptions.get(name);\n }", "private void startInvertedColors() {\n if (managerFeatures.getInvertedColors().isInverted()) {\n managerFeatures.getInvertedColors().turnOff(mGvrContext.getMainScene());\n } else {\n managerFeatures.getInvertedColors().turnOn(mGvrContext.getMainScene());\n }\n }", "public static String formatDateTime(Context context, ReadablePartial time, int flags) {\n return android.text.format.DateUtils.formatDateTime(context, toMillis(time), flags | FORMAT_UTC);\n }", "public static base_responses update(nitro_service client, Interface resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tInterface updateresources[] = new Interface[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new Interface();\n\t\t\t\tupdateresources[i].id = resources[i].id;\n\t\t\t\tupdateresources[i].speed = resources[i].speed;\n\t\t\t\tupdateresources[i].duplex = resources[i].duplex;\n\t\t\t\tupdateresources[i].flowctl = resources[i].flowctl;\n\t\t\t\tupdateresources[i].autoneg = resources[i].autoneg;\n\t\t\t\tupdateresources[i].hamonitor = resources[i].hamonitor;\n\t\t\t\tupdateresources[i].tagall = resources[i].tagall;\n\t\t\t\tupdateresources[i].trunk = resources[i].trunk;\n\t\t\t\tupdateresources[i].lacpmode = resources[i].lacpmode;\n\t\t\t\tupdateresources[i].lacpkey = resources[i].lacpkey;\n\t\t\t\tupdateresources[i].lagtype = resources[i].lagtype;\n\t\t\t\tupdateresources[i].lacppriority = resources[i].lacppriority;\n\t\t\t\tupdateresources[i].lacptimeout = resources[i].lacptimeout;\n\t\t\t\tupdateresources[i].ifalias = resources[i].ifalias;\n\t\t\t\tupdateresources[i].throughput = resources[i].throughput;\n\t\t\t\tupdateresources[i].bandwidthhigh = resources[i].bandwidthhigh;\n\t\t\t\tupdateresources[i].bandwidthnormal = resources[i].bandwidthnormal;\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}", "public int blast(InputStream input, OutputStream output) throws IOException\n {\n m_input = input;\n m_output = output;\n\n int lit; /* true if literals are coded */\n int dict; /* log2(dictionary size) - 6 */\n int symbol; /* decoded symbol, extra bits for distance */\n int len; /* length for copy */\n int dist; /* distance for copy */\n int copy; /* copy counter */\n //unsigned char *from, *to; /* copy pointers */\n\n /* read header */\n lit = bits(8);\n if (lit > 1)\n {\n return -1;\n }\n dict = bits(8);\n if (dict < 4 || dict > 6)\n {\n return -2;\n }\n\n /* decode literals and length/distance pairs */\n do\n {\n if (bits(1) != 0)\n {\n /* get length */\n symbol = decode(LENCODE);\n len = BASE[symbol] + bits(EXTRA[symbol]);\n if (len == 519)\n {\n break; /* end code */\n }\n\n /* get distance */\n symbol = len == 2 ? 2 : dict;\n dist = decode(DISTCODE) << symbol;\n dist += bits(symbol);\n dist++;\n if (m_first != 0 && dist > m_next)\n {\n return -3; /* distance too far back */\n }\n\n /* copy length bytes from distance bytes back */\n do\n {\n //to = m_out + m_next;\n int to = m_next;\n int from = to - dist;\n copy = MAXWIN;\n if (m_next < dist)\n {\n from += copy;\n copy = dist;\n }\n copy -= m_next;\n if (copy > len)\n {\n copy = len;\n }\n len -= copy;\n m_next += copy;\n do\n {\n //*to++ = *from++;\n m_out[to++] = m_out[from++];\n }\n while (--copy != 0);\n if (m_next == MAXWIN)\n {\n //if (s->outfun(s->outhow, s->out, s->next)) return 1;\n m_output.write(m_out, 0, m_next);\n m_next = 0;\n m_first = 0;\n }\n }\n while (len != 0);\n }\n else\n {\n /* get literal and write it */\n symbol = lit != 0 ? decode(LITCODE) : bits(8);\n m_out[m_next++] = (byte) symbol;\n if (m_next == MAXWIN)\n {\n //if (s->outfun(s->outhow, s->out, s->next)) return 1;\n m_output.write(m_out, 0, m_next);\n m_next = 0;\n m_first = 0;\n }\n }\n }\n while (true);\n\n if (m_next != 0)\n {\n m_output.write(m_out, 0, m_next);\n }\n\n return 0;\n }", "private NodeList getNodeList(String document, XPathExpression expression) throws Exception\n {\n Document doc = m_documentBuilder.parse(new InputSource(new StringReader(document)));\n return (NodeList) expression.evaluate(doc, XPathConstants.NODESET);\n }", "public static rnat_stats get(nitro_service service) throws Exception{\n\t\trnat_stats obj = new rnat_stats();\n\t\trnat_stats[] response = (rnat_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}", "void merge(Archetype flatParent, Archetype specialized) {\n expandAttributeNodes(specialized.getDefinition());\n\n flattenCObject(RmPath.ROOT, null, flatParent.getDefinition(), specialized.getDefinition());\n\n\n mergeOntologies(flatParent.getTerminology(), specialized.getTerminology());\n if (flatParent.getAnnotations() != null) {\n if (specialized.getAnnotations() == null) {\n specialized.setAnnotations(new ResourceAnnotations());\n }\n annotationsMerger.merge(flatParent.getAnnotations().getItems(), specialized.getAnnotations().getItems());\n }\n }" ]
Set the Log4j appender. @param appender the log4j appender
[ "public void setAppender(final Appender appender) {\n if (this.appender != null) {\n close();\n }\n checkAccess(this);\n if (applyLayout && appender != null) {\n final Formatter formatter = getFormatter();\n appender.setLayout(formatter == null ? null : new FormatterLayout(formatter));\n }\n appenderUpdater.set(this, appender);\n }" ]
[ "public ManagementModelNode findNode(String address) {\n ManagementModelNode root = (ManagementModelNode)tree.getModel().getRoot();\n Enumeration<javax.swing.tree.TreeNode> allNodes = root.depthFirstEnumeration();\n while (allNodes.hasMoreElements()) {\n ManagementModelNode node = (ManagementModelNode)allNodes.nextElement();\n if (node.addressPath().equals(address)) return node;\n }\n\n return null;\n }", "public Range<App> listApps(String range) {\n return connection.execute(new AppList(range), apiKey);\n }", "@Deprecated\r\n public Location resolvePlaceURL(String flickrPlacesUrl) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_RESOLVE_PLACE_URL);\r\n\r\n parameters.put(\"url\", flickrPlacesUrl);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }", "private String checkinScriptCommand() {\n\n String exportModules = \"\";\n if ((m_modulesToExport != null) && !m_modulesToExport.isEmpty()) {\n StringBuffer exportModulesParam = new StringBuffer();\n for (String moduleName : m_modulesToExport) {\n exportModulesParam.append(\" \").append(moduleName);\n }\n exportModulesParam.replace(0, 1, \" \\\"\");\n exportModulesParam.append(\"\\\" \");\n exportModules = \" --modules \" + exportModulesParam.toString();\n\n }\n String commitMessage = \"\";\n if (m_commitMessage != null) {\n commitMessage = \" -msg \\\"\" + m_commitMessage.replace(\"\\\"\", \"\\\\\\\"\") + \"\\\"\";\n }\n String gitUserName = \"\";\n if (m_gitUserName != null) {\n if (m_gitUserName.trim().isEmpty()) {\n gitUserName = \" --ignore-default-git-user-name\";\n } else {\n gitUserName = \" --git-user-name \\\"\" + m_gitUserName + \"\\\"\";\n }\n }\n String gitUserEmail = \"\";\n if (m_gitUserEmail != null) {\n if (m_gitUserEmail.trim().isEmpty()) {\n gitUserEmail = \" --ignore-default-git-user-email\";\n } else {\n gitUserEmail = \" --git-user-email \\\"\" + m_gitUserEmail + \"\\\"\";\n }\n }\n String autoPullBefore = \"\";\n if (m_autoPullBefore != null) {\n autoPullBefore = m_autoPullBefore.booleanValue() ? \" --pull-before \" : \" --no-pull-before\";\n }\n String autoPullAfter = \"\";\n if (m_autoPullAfter != null) {\n autoPullAfter = m_autoPullAfter.booleanValue() ? \" --pull-after \" : \" --no-pull-after\";\n }\n String autoPush = \"\";\n if (m_autoPush != null) {\n autoPush = m_autoPush.booleanValue() ? \" --push \" : \" --no-push\";\n }\n String exportFolder = \" --export-folder \\\"\" + m_currentConfiguration.getModuleExportPath() + \"\\\"\";\n String exportMode = \" --export-mode \" + m_currentConfiguration.getExportMode();\n String excludeLibs = \"\";\n if (m_excludeLibs != null) {\n excludeLibs = m_excludeLibs.booleanValue() ? \" --exclude-libs\" : \" --no-exclude-libs\";\n }\n String commitMode = \"\";\n if (m_commitMode != null) {\n commitMode = m_commitMode.booleanValue() ? \" --commit\" : \" --no-commit\";\n }\n String ignoreUncleanMode = \"\";\n if (m_ignoreUnclean != null) {\n ignoreUncleanMode = m_ignoreUnclean.booleanValue() ? \" --ignore-unclean\" : \" --no-ignore-unclean\";\n }\n String copyAndUnzip = \"\";\n if (m_copyAndUnzip != null) {\n copyAndUnzip = m_copyAndUnzip.booleanValue() ? \" --copy-and-unzip\" : \" --no-copy-and-unzip\";\n }\n\n String configFilePath = m_currentConfiguration.getFilePath();\n\n return \"\\\"\"\n + DEFAULT_SCRIPT_FILE\n + \"\\\"\"\n + exportModules\n + commitMessage\n + gitUserName\n + gitUserEmail\n + autoPullBefore\n + autoPullAfter\n + autoPush\n + exportFolder\n + exportMode\n + excludeLibs\n + commitMode\n + ignoreUncleanMode\n + copyAndUnzip\n + \" \\\"\"\n + configFilePath\n + \"\\\"\";\n }", "protected List<String> arguments() {\n List<String> args = new ArgumentsBuilder()\n .flag(\"-v\", verbose)\n .flag(\"--package-dir\", packageDir)\n .param(\"-d\", outputDirectory.getPath())\n .param(\"-p\", packageName)\n .map(\"--package:\", packageNameMap())\n .param(\"--class-prefix\", classPrefix)\n .param(\"--param-prefix\", parameterPrefix)\n .param(\"--chunk-size\", chunkSize)\n .flag(\"--no-dispatch-client\", !generateDispatchClient)\n .flag(\"--dispatch-as\", generateDispatchAs)\n .param(\"--dispatch-version\", dispatchVersion)\n .flag(\"--no-runtime\", !generateRuntime)\n .intersperse(\"--wrap-contents\", wrapContents)\n .param(\"--protocol-file\", protocolFile)\n .param(\"--protocol-package\", protocolPackage)\n .param(\"--attribute-prefix\", attributePrefix)\n .flag(\"--prepend-family\", prependFamily)\n .flag(\"--blocking\", !async)\n .flag(\"--lax-any\", laxAny)\n .flag(\"--no-varargs\", !varArgs)\n .flag(\"--ignore-unknown\", ignoreUnknown)\n .flag(\"--autopackages\", autoPackages)\n .flag(\"--mutable\", mutable)\n .flag(\"--visitor\", visitor)\n\n .getArguments();\n return unmodifiableList(args);\n }", "public double getYield(double bondPrice, 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=getValueWithGivenYield(0.0,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}", "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 static String groupFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null;\n }", "public File curDir() {\n File file = session().attribute(ATTR_PWD);\n if (null == file) {\n file = new File(System.getProperty(\"user.dir\"));\n session().attribute(ATTR_PWD, file);\n }\n return file;\n }" ]
Start the rendering of the scalebar.
[ "public final void draw() {\n AffineTransform transform = new AffineTransform(this.transform);\n transform.concatenate(getAlignmentTransform());\n\n // draw the background box\n this.graphics2d.setTransform(transform);\n this.graphics2d.setColor(this.params.getBackgroundColor());\n this.graphics2d.fillRect(0, 0, this.settings.getSize().width, this.settings.getSize().height);\n\n //draw the labels\n this.graphics2d.setColor(this.params.getFontColor());\n drawLabels(transform, this.params.getOrientation(), this.params.getLabelRotation());\n\n //sets the transformation for drawing the bar and do it\n final AffineTransform lineTransform = new AffineTransform(transform);\n setLineTranslate(lineTransform);\n\n if (this.params.getOrientation() == Orientation.VERTICAL_LABELS_LEFT ||\n this.params.getOrientation() == Orientation.VERTICAL_LABELS_RIGHT) {\n final AffineTransform rotate = AffineTransform.getQuadrantRotateInstance(1);\n lineTransform.concatenate(rotate);\n }\n\n this.graphics2d.setTransform(lineTransform);\n this.graphics2d.setStroke(new BasicStroke(this.settings.getLineWidth()));\n this.graphics2d.setColor(this.params.getColor());\n drawBar();\n }" ]
[ "private void writeBufferedValsToStorage() {\n List<Versioned<byte[]>> obsoleteVals = storageEngine.multiVersionPut(currBufferedKey,\n currBufferedVals);\n // log Obsolete versions in debug mode\n if(logger.isDebugEnabled() && obsoleteVals.size() > 0) {\n logger.debug(\"updateEntries (Streaming multi-version-put) rejected these versions as obsolete : \"\n + StoreUtils.getVersions(obsoleteVals) + \" for key \" + currBufferedKey);\n }\n currBufferedVals = new ArrayList<Versioned<byte[]>>(VALS_BUFFER_EXPECTED_SIZE);\n }", "protected FieldDescriptor resolvePayloadField(Message message) {\n for (FieldDescriptor field : message.getDescriptorForType().getFields()) {\n if (message.hasField(field)) {\n return field;\n }\n }\n\n throw new RuntimeException(\"No payload found in message \" + message);\n }", "public String getMethodSignature() {\n if (method != null) {\n String methodSignature = method.toString();\n return methodSignature.replaceFirst(\"public void \", \"\");\n }\n return null;\n }", "public void registerComponent(java.awt.Component c)\r\n {\r\n unregisterComponent(c);\r\n if (recognizerAbstractClass == null)\r\n {\r\n hmDragGestureRecognizers.put(c, \r\n dragSource.createDefaultDragGestureRecognizer(c, \r\n dragWorker.getAcceptableActions(c), dgListener)\r\n );\r\n }\r\n else\r\n {\r\n hmDragGestureRecognizers.put(c, \r\n dragSource.createDragGestureRecognizer (recognizerAbstractClass,\r\n c, dragWorker.getAcceptableActions(c), dgListener)\r\n );\r\n }\r\n }", "protected static final Long parseUsingFallbacksWithColon(String text, DateTimeFormat timeFormat) {\n if (text.indexOf(':') == -1) {\n text = text.replace(\" \", \"\");\n int numdigits = 0;\n int lastdigit = 0;\n for (int i = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n if (Character.isDigit(c)) {\n numdigits++;\n lastdigit = i;\n }\n }\n if (numdigits == 1 || numdigits == 2) {\n // insert :00\n int colon = lastdigit + 1;\n text = text.substring(0, colon) + \":00\" + text.substring(colon);\n }\n else if (numdigits > 2) {\n // insert :\n int colon = lastdigit - 1;\n text = text.substring(0, colon) + \":\" + text.substring(colon);\n }\n return parseUsingFallbacks(text, timeFormat);\n }\n else {\n return null;\n }\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 }", "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 }", "public static String parseServers(String zookeepers) {\n int slashIndex = zookeepers.indexOf(\"/\");\n if (slashIndex != -1) {\n return zookeepers.substring(0, slashIndex);\n }\n return zookeepers;\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 }" ]
Converts the search results from CmsSearchResource to CmsSearchResourceBean. @param searchResults The collection of search results to transform.
[ "protected void convertSearchResults(final Collection<CmsSearchResource> searchResults) {\n\n m_foundResources = new ArrayList<I_CmsSearchResourceBean>();\n for (final CmsSearchResource searchResult : searchResults) {\n m_foundResources.add(new CmsSearchResourceBean(searchResult, m_cmsObject));\n }\n }" ]
[ "void updateFromResponseOnDeletePost(Response<ResponseBody> response) throws IOException {\n this.withResponse(response);\n String responseContent = null;\n if (response.body() != null) {\n responseContent = response.body().string();\n response.body().close();\n }\n this.withResource(serializerAdapter.<T>deserialize(responseContent, resourceType));\n withStatus(AzureAsyncOperation.SUCCESS_STATUS, response.code());\n }", "public static <T> PollingState<T> create(Response<ResponseBody> response, LongRunningOperationOptions lroOptions, int defaultRetryTimeout, Type resourceType, SerializerAdapter<?> serializerAdapter) throws IOException {\n PollingState<T> pollingState = new PollingState<>();\n pollingState.initialHttpMethod = response.raw().request().method();\n pollingState.defaultRetryTimeout = defaultRetryTimeout;\n pollingState.withResponse(response);\n pollingState.resourceType = resourceType;\n pollingState.serializerAdapter = serializerAdapter;\n pollingState.loggingContext = response.raw().request().header(LOGGING_HEADER);\n pollingState.finalStateVia = lroOptions.finalStateVia();\n\n String responseContent = null;\n PollingResource resource = null;\n if (response.body() != null) {\n responseContent = response.body().string();\n response.body().close();\n }\n if (responseContent != null && !responseContent.isEmpty()) {\n pollingState.resource = serializerAdapter.deserialize(responseContent, resourceType);\n resource = serializerAdapter.deserialize(responseContent, PollingResource.class);\n }\n final int statusCode = pollingState.response.code();\n if (resource != null && resource.properties != null\n && resource.properties.provisioningState != null) {\n pollingState.withStatus(resource.properties.provisioningState, statusCode);\n } else {\n switch (statusCode) {\n case 202:\n pollingState.withStatus(AzureAsyncOperation.IN_PROGRESS_STATUS, statusCode);\n break;\n case 204:\n case 201:\n case 200:\n pollingState.withStatus(AzureAsyncOperation.SUCCESS_STATUS, statusCode);\n break;\n default:\n pollingState.withStatus(AzureAsyncOperation.FAILED_STATUS, statusCode);\n }\n }\n return pollingState;\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 static spilloverpolicy_stats[] get(nitro_service service) throws Exception{\n\t\tspilloverpolicy_stats obj = new spilloverpolicy_stats();\n\t\tspilloverpolicy_stats[] response = (spilloverpolicy_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public static <T> void injectBoundFields(T instance, CreationalContext<T> creationalContext, BeanManagerImpl manager,\n Iterable<? extends FieldInjectionPoint<?, ?>> injectableFields) {\n for (FieldInjectionPoint<?, ?> injectableField : injectableFields) {\n injectableField.inject(instance, manager, creationalContext);\n }\n }", "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 void deleteLicense(final String licName) {\n final DbLicense dbLicense = getLicense(licName);\n\n repoHandler.deleteLicense(dbLicense.getName());\n\n final FiltersHolder filters = new FiltersHolder();\n final LicenseIdFilter licenseIdFilter = new LicenseIdFilter(licName);\n filters.addFilter(licenseIdFilter);\n\n for (final DbArtifact artifact : repoHandler.getArtifacts(filters)) {\n repoHandler.removeLicenseFromArtifact(artifact, licName, this);\n }\n }", "protected synchronized StealerBasedRebalanceTask scheduleNextTask(boolean executeService) {\n // Make sure there is work left to do.\n if(doneSignal.getCount() == 0) {\n logger.info(\"All tasks completion signaled... returning\");\n\n return null;\n }\n // Limit number of tasks outstanding.\n if(this.numTasksExecuting >= maxParallelRebalancing) {\n logger.info(\"Executing more tasks than [\" + this.numTasksExecuting\n + \"] the parallel allowed \" + maxParallelRebalancing);\n return null;\n }\n // Shuffle list of stealer IDs each time a new task to schedule needs to\n // be found. Randomizing the order should avoid prioritizing one\n // specific stealer's work ahead of all others.\n List<Integer> stealerIds = new ArrayList<Integer>(tasksByStealer.keySet());\n Collections.shuffle(stealerIds);\n for(int stealerId: stealerIds) {\n if(nodeIdsWithWork.contains(stealerId)) {\n logger.info(\"Stealer \" + stealerId + \" is already working... continuing\");\n continue;\n }\n\n for(StealerBasedRebalanceTask sbTask: tasksByStealer.get(stealerId)) {\n int donorId = sbTask.getStealInfos().get(0).getDonorId();\n if(nodeIdsWithWork.contains(donorId)) {\n logger.info(\"Stealer \" + stealerId + \" Donor \" + donorId\n + \" is already working... continuing\");\n continue;\n }\n // Book keeping\n addNodesToWorkerList(Arrays.asList(stealerId, donorId));\n numTasksExecuting++;\n // Remove this task from list thus destroying list being\n // iterated over. This is safe because returning directly out of\n // this branch.\n tasksByStealer.get(stealerId).remove(sbTask);\n try {\n if(executeService) {\n logger.info(\"Stealer \" + stealerId + \" Donor \" + donorId\n + \" going to schedule work\");\n service.execute(sbTask);\n }\n } catch(RejectedExecutionException ree) {\n logger.error(\"Stealer \" + stealerId\n + \"Rebalancing task rejected by executor service.\", ree);\n throw new VoldemortRebalancingException(\"Stealer \"\n + stealerId\n + \"Rebalancing task rejected by executor service.\");\n }\n return sbTask;\n }\n }\n printRemainingTasks(stealerIds);\n return null;\n }", "private void addDependencyToGraph(final DbDependency dependency, final AbstractGraph graph, final int depth, final String parentId) {\n // In that case of Axway artifact we will add a module to the graph\n if (filters.getCorporateFilter().filter(dependency)) {\n final DbModule dbTarget = repoHandler.getModuleOf(dependency.getTarget());\n\n // if there is no module, add the artifact to the graph\n if(dbTarget == null){\n LOG.error(\"Got missing reference: \" + dependency.getTarget());\n final DbArtifact dbArtifact = DataUtils.createDbArtifact(dependency.getTarget());\n final String targetElementId = graph.getId(dbArtifact);\n graph.addElement(targetElementId, dbArtifact.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n return;\n }\n\n // Add the element to the graph\n addModuleToGraph(dbTarget, graph, depth + 1);\n\n //Add the dependency to the graph\n final String moduleElementId = graph.getId(dbTarget);\n graph.addDependency(parentId, moduleElementId, dependency.getScope());\n }\n // In case a third-party we will add an artifact\n else {\n final DbArtifact dbTarget = repoHandler.getArtifact(dependency.getTarget());\n if(dbTarget == null){\n LOG.error(\"Got missing artifact: \" + dependency.getTarget());\n return;\n }\n\n if(!graph.isTreated(graph.getId(dbTarget))){\n final ModelMapper modelMapper = new ModelMapper(repoHandler);\n final Artifact target = modelMapper.getArtifact(dbTarget);\n final String targetElementId = graph.getId(target);\n graph.addElement(targetElementId, target.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n }\n }\n }" ]
Gets the data by id. @param id the id @return the data by id @throws IOException Signals that an I/O exception has occurred.
[ "public HashSet<String> getDataById(String id) throws IOException {\n if (idToVersion.containsKey(id)) {\n return get(id);\n } else {\n return null;\n }\n }" ]
[ "public void print() {\n Iterator<String> iter = getKeys();\n while (iter.hasNext()) {\n String key = iter.next();\n log.info(key + \" = \" + getRawString(key));\n }\n }", "public static void Forward(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 f = 0; f < data.length; f++) {\n sum = 0;\n for (int t = 0; t < data.length; t++) {\n double cos = Math.cos(((2.0 * t + 1.0) * f * Math.PI) / (2.0 * data.length));\n sum += data[t] * cos * alpha(f);\n }\n result[f] = scale * sum;\n }\n for (int i = 0; i < data.length; i++) {\n data[i] = result[i];\n }\n }", "private static void listTimephasedWork(ResourceAssignment assignment)\n {\n Task task = assignment.getTask();\n int days = (int) ((task.getFinish().getTime() - task.getStart().getTime()) / (1000 * 60 * 60 * 24)) + 1;\n if (days > 1)\n {\n SimpleDateFormat df = new SimpleDateFormat(\"dd/MM/yy\");\n\n TimescaleUtility timescale = new TimescaleUtility();\n ArrayList<DateRange> dates = timescale.createTimescale(task.getStart(), TimescaleUnits.DAYS, days);\n TimephasedUtility timephased = new TimephasedUtility();\n\n ArrayList<Duration> durations = timephased.segmentWork(assignment.getCalendar(), assignment.getTimephasedWork(), TimescaleUnits.DAYS, dates);\n for (DateRange range : dates)\n {\n System.out.print(df.format(range.getStart()) + \"\\t\");\n }\n System.out.println();\n for (Duration duration : durations)\n {\n System.out.print(duration.toString() + \" \".substring(0, 7) + \"\\t\");\n }\n System.out.println();\n }\n }", "public Object getRealSubject() throws PersistenceBrokerException\r\n\t{\r\n\t\tif (_realSubject == null)\r\n\t\t{\r\n\t\t\tbeforeMaterialization();\r\n\t\t\t_realSubject = materializeSubject();\r\n\t\t\tafterMaterialization();\r\n\t\t}\r\n\t\treturn _realSubject;\r\n\t}", "@SuppressWarnings(\"deprecation\")\n\tprivate static WriteConcern mergeWriteConcern(WriteConcern original, WriteConcern writeConcern) {\n\t\tif ( original == null ) {\n\t\t\treturn writeConcern;\n\t\t}\n\t\telse if ( writeConcern == null ) {\n\t\t\treturn original;\n\t\t}\n\t\telse if ( original.equals( writeConcern ) ) {\n\t\t\treturn original;\n\t\t}\n\n\t\tObject wObject;\n\t\tint wTimeoutMS;\n\t\tboolean fsync;\n\t\tBoolean journal;\n\n\t\tif ( original.getWObject() instanceof String ) {\n\t\t\twObject = original.getWString();\n\t\t}\n\t\telse if ( writeConcern.getWObject() instanceof String ) {\n\t\t\twObject = writeConcern.getWString();\n\t\t}\n\t\telse {\n\t\t\twObject = Math.max( original.getW(), writeConcern.getW() );\n\t\t}\n\n\t\twTimeoutMS = Math.min( original.getWtimeout(), writeConcern.getWtimeout() );\n\n\t\tfsync = original.getFsync() || writeConcern.getFsync();\n\n\t\tif ( original.getJournal() == null ) {\n\t\t\tjournal = writeConcern.getJournal();\n\t\t}\n\t\telse if ( writeConcern.getJournal() == null ) {\n\t\t\tjournal = original.getJournal();\n\t\t}\n\t\telse {\n\t\t\tjournal = original.getJournal() || writeConcern.getJournal();\n\t\t}\n\n\t\tif ( wObject instanceof String ) {\n\t\t\treturn new WriteConcern( (String) wObject, wTimeoutMS, fsync, journal );\n\t\t}\n\t\telse {\n\t\t\treturn new WriteConcern( (int) wObject, wTimeoutMS, fsync, journal );\n\t\t}\n\t}", "public boolean setCustomResponse(String pathName, String customResponse) throws Exception {\n // figure out the new ordinal\n int nextOrdinal = this.getNextOrdinalForMethodId(-1, pathName);\n\n // add override\n this.addMethodToResponseOverride(pathName, \"-1\");\n\n // set argument\n return this.setMethodArguments(pathName, \"-1\", nextOrdinal, customResponse);\n }", "public static Mono<Void> waitForCompletion(CloudFoundryClient cloudFoundryClient, Duration completionTimeout, String jobId) {\n return requestJobV3(cloudFoundryClient, jobId)\n .filter(job -> JobState.PROCESSING != job.getState())\n .repeatWhenEmpty(exponentialBackOff(Duration.ofSeconds(1), Duration.ofSeconds(15), completionTimeout))\n .filter(job -> JobState.FAILED == job.getState())\n .flatMap(JobUtils::getError);\n }", "public double getValueWithGivenYield(double evaluationTime, double rate, AnalyticModel model) {\n\t\tDiscountCurve referenceCurve = DiscountCurveInterpolation.createDiscountCurveFromDiscountFactors(\"referenceCurve\", new double[] {0.0, 1.0}, new double[] {1.0, 1.0});\n\t\treturn getValueWithGivenSpreadOverCurve(evaluationTime, referenceCurve, rate, model);\n\t}", "public void setDerivatives(double[] parameters, double[][] derivatives) throws SolverException {\n\t\t// Calculate new derivatives. Note that this method is called only with\n\t\t// parameters = parameterCurrent, so we may use valueCurrent.\n\n\t\tVector<Future<double[]>> valueFutures = new Vector<Future<double[]>>(parameterCurrent.length);\n\t\tfor (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) {\n\t\t\tfinal double[] parametersNew\t= parameters.clone();\n\t\t\tfinal double[] derivative\t\t= derivatives[parameterIndex];\n\n\t\t\tfinal int workerParameterIndex = parameterIndex;\n\t\t\tCallable<double[]> worker = new Callable<double[]>() {\n\t\t\t\tpublic double[] call() {\n\t\t\t\t\tdouble parameterFiniteDifference;\n\t\t\t\t\tif(parameterSteps != null) {\n\t\t\t\t\t\tparameterFiniteDifference = parameterSteps[workerParameterIndex];\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Try to adaptively set a parameter shift. Note that in some\n\t\t\t\t\t\t * applications it may be important to set parameterSteps.\n\t\t\t\t\t\t * appropriately.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tparameterFiniteDifference = (Math.abs(parametersNew[workerParameterIndex]) + 1) * 1E-8;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Shift parameter value\n\t\t\t\t\tparametersNew[workerParameterIndex] += parameterFiniteDifference;\n\n\t\t\t\t\t// Calculate derivative as (valueUpShift - valueCurrent) / parameterFiniteDifference\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsetValues(parametersNew, derivative);\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t// We signal an exception to calculate the derivative as NaN\n\t\t\t\t\t\tArrays.fill(derivative, Double.NaN);\n\t\t\t\t\t}\n\t\t\t\t\tfor (int valueIndex = 0; valueIndex < valueCurrent.length; valueIndex++) {\n\t\t\t\t\t\tderivative[valueIndex] -= valueCurrent[valueIndex];\n\t\t\t\t\t\tderivative[valueIndex] /= parameterFiniteDifference;\n\t\t\t\t\t\tif(Double.isNaN(derivative[valueIndex])) {\n\t\t\t\t\t\t\tderivative[valueIndex] = 0.0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn derivative;\n\t\t\t\t}\n\t\t\t};\n\t\t\tif(executor != null) {\n\t\t\t\tFuture<double[]> valueFuture = executor.submit(worker);\n\t\t\t\tvalueFutures.add(parameterIndex, valueFuture);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tFutureTask<double[]> valueFutureTask = new FutureTask<double[]>(worker);\n\t\t\t\tvalueFutureTask.run();\n\t\t\t\tvalueFutures.add(parameterIndex, valueFutureTask);\n\t\t\t}\n\t\t}\n\n\t\tfor (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) {\n\t\t\ttry {\n\t\t\t\tderivatives[parameterIndex] = valueFutures.get(parameterIndex).get();\n\t\t\t}\n\t\t\tcatch (InterruptedException e) {\n\t\t\t\tthrow new SolverException(e);\n\t\t\t} catch (ExecutionException e) {\n\t\t\t\tthrow new SolverException(e);\n\t\t\t}\n\t\t}\n\t}" ]
Create a ModelNode representing the CPU the instance is running on. @return a ModelNode representing the CPU the instance is running on. @throws OperationFailedException
[ "private ModelNode createCPUNode() throws OperationFailedException {\n ModelNode cpu = new ModelNode().setEmptyObject();\n cpu.get(ARCH).set(getProperty(\"os.arch\"));\n cpu.get(AVAILABLE_PROCESSORS).set(ProcessorInfo.availableProcessors());\n return cpu;\n }" ]
[ "public void setIsSeries(Boolean isSeries) {\r\n\r\n if (null != isSeries) {\r\n final boolean series = isSeries.booleanValue();\r\n if ((null != m_model.getParentSeriesId()) && series) {\r\n m_removeSeriesBindingConfirmDialog.show(new Command() {\r\n\r\n public void execute() {\r\n\r\n m_model.setParentSeriesId(null);\r\n setPattern(PatternType.DAILY.toString());\r\n\r\n }\r\n });\r\n } else {\r\n setPattern(series ? PatternType.DAILY.toString() : PatternType.NONE.toString());\r\n }\r\n }\r\n }", "public void setSessionFactory(SessionFactory sessionFactory) throws HibernateLayerException {\n\t\ttry {\n\t\t\tthis.sessionFactory = sessionFactory;\n\t\t\tif (null != layerInfo) {\n\t\t\t\tentityMetadata = sessionFactory.getClassMetadata(layerInfo.getFeatureInfo().getDataSourceName());\n\t\t\t}\n\t\t} catch (Exception e) { // NOSONAR\n\t\t\tthrow new HibernateLayerException(e, ExceptionCode.HIBERNATE_NO_SESSION_FACTORY);\n\t\t}\n\t}", "public ManagementModelNode findNode(String address) {\n ManagementModelNode root = (ManagementModelNode)tree.getModel().getRoot();\n Enumeration<javax.swing.tree.TreeNode> allNodes = root.depthFirstEnumeration();\n while (allNodes.hasMoreElements()) {\n ManagementModelNode node = (ManagementModelNode)allNodes.nextElement();\n if (node.addressPath().equals(address)) return node;\n }\n\n return null;\n }", "public static ComplexNumber Multiply(ComplexNumber z1, double scalar) {\r\n return new ComplexNumber(z1.real * scalar, z1.imaginary * scalar);\r\n }", "public static lbvserver_appflowpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_appflowpolicy_binding obj = new lbvserver_appflowpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_appflowpolicy_binding response[] = (lbvserver_appflowpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "protected void addFacetPart(CmsSolrQuery query) {\n\n StringBuffer value = new StringBuffer();\n value.append(\"{!key=\").append(m_config.getName());\n addFacetOptions(value);\n if (m_config.getIgnoreAllFacetFilters()\n || (!m_state.getCheckedEntries().isEmpty() && !m_config.getIsAndFacet())) {\n value.append(\" ex=\").append(m_config.getIgnoreTags());\n }\n value.append(\"}\");\n value.append(m_config.getRange());\n query.add(\"facet.range\", value.toString());\n }", "private void writeExceptions(Project.Calendars.Calendar calendar, List<Project.Calendars.Calendar.WeekDays.WeekDay> dayList, List<ProjectCalendarException> exceptions)\n {\n // Always write legacy exception data:\n // Powerproject appears not to recognise new format data at all,\n // and legacy data is ignored in preference to new data post MSP 2003\n writeExceptions9(dayList, exceptions);\n\n if (m_saveVersion.getValue() > SaveVersion.Project2003.getValue())\n {\n writeExceptions12(calendar, exceptions);\n }\n }", "public static void applyWsdlExtensions(Bus bus) {\n\n ExtensionRegistry registry = bus.getExtension(WSDLManager.class).getExtensionRegistry();\n\n try {\n\n JAXBExtensionHelper.addExtensions(registry,\n javax.wsdl.Definition.class,\n org.talend.esb.mep.requestcallback.impl.wsdl.PLType.class);\n\n JAXBExtensionHelper.addExtensions(registry,\n javax.wsdl.Binding.class,\n org.talend.esb.mep.requestcallback.impl.wsdl.CallbackExtension.class);\n\n } catch (JAXBException e) {\n throw new RuntimeException(\"Failed to add WSDL JAXB extensions\", e);\n }\n }", "public String getPrototypeName() {\n\t\tString name = getClass().getName();\n\t\tif (name.startsWith(ORG_GEOMAJAS)) {\n\t\t\tname = name.substring(ORG_GEOMAJAS.length());\n\t\t}\n\t\tname = name.replace(\".dto.\", \".impl.\");\n\t\treturn name.substring(0, name.length() - 4) + \"Impl\";\n\t}" ]
Determine the size of a field in a fixed data block. @param type field data type @return field size in bytes
[ "private int getFixedDataFieldSize(FieldType type)\n {\n int result = 0;\n DataType dataType = type.getDataType();\n if (dataType != null)\n {\n switch (dataType)\n {\n case DATE:\n case INTEGER:\n case DURATION:\n {\n result = 4;\n break;\n }\n\n case TIME_UNITS:\n case CONSTRAINT:\n case PRIORITY:\n case PERCENTAGE:\n case TASK_TYPE:\n case ACCRUE:\n case SHORT:\n case BOOLEAN:\n case DELAY:\n case WORKGROUP:\n case RATE_UNITS:\n case EARNED_VALUE_METHOD:\n case RESOURCE_REQUEST_TYPE:\n {\n result = 2;\n break;\n }\n\n case CURRENCY:\n case UNITS:\n case RATE:\n case WORK:\n {\n result = 8;\n break;\n }\n\n case WORK_UNITS:\n {\n result = 1;\n break;\n }\n\n case GUID:\n {\n result = 16;\n break;\n }\n\n default:\n {\n result = 0;\n break;\n }\n }\n }\n\n return result;\n }" ]
[ "private static Class<?> getGenericReturnType(Method method, Class<?> source, int typeIndex, int nestingLevel) {\n\t\treturn extractType(method.getGenericReturnType(), source, typeIndex, null, null, nestingLevel, 1);\n\t}", "public static HazardCurve createHazardCurveFromSurvivalProbabilities(String name, double[] times, double[] givenSurvivalProbabilities){\n\t\tHazardCurve survivalProbabilities = new HazardCurve(name);\n\n\t\tfor(int timeIndex=0; timeIndex<times.length;timeIndex++) {\n\t\t\tsurvivalProbabilities.addSurvivalProbability(times[timeIndex], givenSurvivalProbabilities[timeIndex], times[timeIndex] > 0);\n\t\t}\n\n\t\treturn survivalProbabilities;\n\t}", "public synchronized int getPartitionStoreMoves() {\n int count = 0;\n for (List<Integer> entry : storeToPartitionIds.values())\n count += entry.size();\n return count;\n }", "public Collection getReaders(Object obj)\r\n {\r\n \tcheckTimedOutLocks();\r\n Identity oid = new Identity(obj,getBroker());\r\n return getReaders(oid);\r\n }", "public void setCalendar(ProjectCalendar calendar)\n {\n set(TaskField.CALENDAR, calendar);\n setCalendarUniqueID(calendar == null ? null : calendar.getUniqueID());\n }", "private List<TokenStream> collectTokenStreams(TokenStream stream) {\n \n // walk through the token stream and build a collection \n // of sub token streams that represent possible date locations\n List<Token> currentGroup = null;\n List<List<Token>> groups = new ArrayList<List<Token>>();\n Token currentToken;\n int currentTokenType;\n StringBuilder tokenString = new StringBuilder();\n while((currentToken = stream.getTokenSource().nextToken()).getType() != DateLexer.EOF) {\n currentTokenType = currentToken.getType();\n tokenString.append(DateParser.tokenNames[currentTokenType]).append(\" \");\n\n // we're currently NOT collecting for a possible date group\n if(currentGroup == null) {\n // skip over white space and known tokens that cannot be the start of a date\n if(currentTokenType != DateLexer.WHITE_SPACE &&\n DateParser.FOLLOW_empty_in_parse186.member(currentTokenType)) {\n\n currentGroup = new ArrayList<Token>();\n currentGroup.add(currentToken);\n }\n }\n\n // we're currently collecting\n else {\n // preserve white space\n if(currentTokenType == DateLexer.WHITE_SPACE) {\n currentGroup.add(currentToken);\n }\n\n else {\n // if this is an unknown token, we'll close out the current group\n if(currentTokenType == DateLexer.UNKNOWN) {\n addGroup(currentGroup, groups);\n currentGroup = null;\n }\n // otherwise, the token is known and we're currently collecting for\n // a group, so we'll add it to the current group\n else {\n currentGroup.add(currentToken);\n }\n }\n }\n }\n\n if(currentGroup != null) {\n addGroup(currentGroup, groups);\n }\n \n _logger.info(\"STREAM: \" + tokenString.toString());\n List<TokenStream> streams = new ArrayList<TokenStream>();\n for(List<Token> group:groups) {\n if(!group.isEmpty()) {\n StringBuilder builder = new StringBuilder();\n builder.append(\"GROUP: \");\n for (Token token : group) {\n builder.append(DateParser.tokenNames[token.getType()]).append(\" \");\n }\n _logger.info(builder.toString());\n\n streams.add(new CommonTokenStream(new NattyTokenSource(group)));\n }\n }\n\n return streams;\n }", "private void handleDmrString(final ModelNode node, final String name, final String value) {\n final String realValue = value.substring(2);\n node.get(name).set(ModelNode.fromString(realValue));\n }", "private String normalizePath(String scriptPath) {\n StringBuilder builder = new StringBuilder(scriptPath.length() + 1);\n if (scriptPath.startsWith(\"/\")) {\n builder.append(scriptPath.substring(1));\n } else {\n builder.append(scriptPath);\n }\n if (!scriptPath.endsWith(\"/\")) {\n builder.append(\"/\");\n }\n return builder.toString();\n }", "private static JsonArray toJsonArray(Collection<String> values) {\n JsonArray array = new JsonArray();\n for (String value : values) {\n array.add(value);\n }\n return array;\n\n }" ]
Creates a new tag in a workspace or organization. Every tag is required to be created in a specific workspace or organization, and this cannot be changed once set. Note that you can use the `workspace` parameter regardless of whether or not it is an organization. Returns the full record of the newly created tag. @param workspace The workspace or organization to create the tag in. @return Request object
[ "public ItemRequest<Tag> createInWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/tags\", workspace);\n return new ItemRequest<Tag>(this, Tag.class, path, \"POST\");\n }" ]
[ "public static ProctorLoadResult verifyWithoutSpecification(@Nonnull final TestMatrixArtifact testMatrix,\n final String matrixSource) {\n final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();\n\n for (final Entry<String, ConsumableTestDefinition> entry : testMatrix.getTests().entrySet()) {\n final String testName = entry.getKey();\n final ConsumableTestDefinition testDefinition = entry.getValue();\n\n try {\n verifyInternallyConsistentDefinition(testName, matrixSource, testDefinition);\n } catch (IncompatibleTestMatrixException e) {\n LOGGER.info(String.format(\"Unable to load test matrix for %s\", testName), e);\n resultBuilder.recordError(testName, e);\n }\n }\n return resultBuilder.build();\n }", "static void sendFailedResponse(final ManagementRequestContext<RegistrationContext> context, final byte errorCode, final String message) throws IOException {\n final ManagementResponseHeader header = ManagementResponseHeader.create(context.getRequestHeader());\n final FlushableDataOutput output = context.writeMessage(header);\n try {\n // This is an error\n output.writeByte(DomainControllerProtocol.PARAM_ERROR);\n // send error code\n output.writeByte(errorCode);\n // error message\n if (message == null) {\n output.writeUTF(\"unknown error\");\n } else {\n output.writeUTF(message);\n }\n // response end\n output.writeByte(ManagementProtocol.RESPONSE_END);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }", "static void logConnectionException(URI uri, DiscoveryOption discoveryOption, boolean moreOptions, Exception e) {\n if (uri == null) {\n HostControllerLogger.ROOT_LOGGER.failedDiscoveringMaster(discoveryOption, e);\n } else {\n HostControllerLogger.ROOT_LOGGER.cannotConnect(uri, e);\n }\n if (!moreOptions) {\n // All discovery options have been exhausted\n HostControllerLogger.ROOT_LOGGER.noDiscoveryOptionsLeft();\n }\n }", "public boolean find() {\r\n if (findIterator == null) {\r\n findIterator = root.iterator();\r\n }\r\n if (findCurrent != null && matches()) {\r\n return true;\r\n }\r\n while (findIterator.hasNext()) {\r\n findCurrent = findIterator.next();\r\n resetChildIter(findCurrent);\r\n if (matches()) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "public static CuratorFramework newCurator(String zookeepers, int timeout, String secret) {\n\n final ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 10);\n if (secret.isEmpty()) {\n return CuratorFrameworkFactory.newClient(zookeepers, timeout, timeout, retry);\n } else {\n return CuratorFrameworkFactory.builder().connectString(zookeepers)\n .connectionTimeoutMs(timeout).sessionTimeoutMs(timeout).retryPolicy(retry)\n .authorization(\"digest\", (\"fluo:\" + secret).getBytes(StandardCharsets.UTF_8))\n .aclProvider(new ACLProvider() {\n @Override\n public List<ACL> getDefaultAcl() {\n return CREATOR_ALL_ACL;\n }\n\n @Override\n public List<ACL> getAclForPath(String path) {\n switch (path) {\n case ZookeeperPath.ORACLE_GC_TIMESTAMP:\n // The garbage collection iterator running in Accumulo tservers needs to read this\n // value w/o authenticating.\n return PUBLICLY_READABLE_ACL;\n default:\n return CREATOR_ALL_ACL;\n }\n }\n }).build();\n }\n }", "public ProjectCalendar getBaselineCalendar()\n {\n //\n // Attempt to locate the calendar normally used by baselines\n // If this isn't present, fall back to using the default\n // project calendar.\n //\n ProjectCalendar result = getCalendarByName(\"Used for Microsoft Project 98 Baseline Calendar\");\n if (result == null)\n {\n result = getDefaultCalendar();\n }\n return result;\n }", "public static base_response add(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey addresource = new sslcertkey();\n\t\taddresource.certkey = resource.certkey;\n\t\taddresource.cert = resource.cert;\n\t\taddresource.key = resource.key;\n\t\taddresource.password = resource.password;\n\t\taddresource.fipskey = resource.fipskey;\n\t\taddresource.inform = resource.inform;\n\t\taddresource.passplain = resource.passplain;\n\t\taddresource.expirymonitor = resource.expirymonitor;\n\t\taddresource.notificationperiod = resource.notificationperiod;\n\t\taddresource.bundle = resource.bundle;\n\t\treturn addresource.add_resource(client);\n\t}", "protected void parseOperationsL(TokenList tokens, Sequence sequence) {\n\n if( tokens.size == 0 )\n return;\n\n TokenList.Token token = tokens.first;\n\n if( token.getType() != Type.VARIABLE )\n throw new ParseError(\"The first token in an equation needs to be a variable and not \"+token);\n\n while( token != null ) {\n if( token.getType() == Type.FUNCTION ) {\n throw new ParseError(\"Function encountered with no parentheses\");\n } else if( token.getType() == Type.SYMBOL && token.getSymbol() == Symbol.TRANSPOSE) {\n if( token.previous.getType() == Type.VARIABLE )\n token = insertTranspose(token.previous,tokens,sequence);\n else\n throw new ParseError(\"Expected variable before transpose\");\n }\n token = token.next;\n }\n }", "public static void init() {\n reports.clear();\n Reflections reflections = new Reflections(REPORTS_PACKAGE);\n final Set<Class<? extends Report>> reportClasses = reflections.getSubTypesOf(Report.class);\n\n for(Class<? extends Report> c : reportClasses) {\n LOG.info(\"Report class: \" + c.getName());\n try {\n reports.add(c.newInstance());\n } catch (IllegalAccessException | InstantiationException e) {\n LOG.error(\"Error while loading report implementation classes\", e);\n }\n }\n\n if(LOG.isInfoEnabled()) {\n LOG.info(String.format(\"Detected %s reports\", reports.size()));\n }\n }" ]
Get a collection of methods declared on this object by method name. @param name the name of the method @return the (possibly empty) collection of methods with the given name
[ "public Collection<Method> getAllMethods(String name) {\n final Map<ParamList, Map<Class<?>, Method>> nameMap = methods.get(name);\n if (nameMap == null) {\n return Collections.emptySet();\n }\n final Collection<Method> methods = new ArrayList<Method>();\n for (Map<Class<?>, Method> map : nameMap.values()) {\n methods.addAll(map.values());\n }\n return methods;\n }" ]
[ "public static void pauseTimer(final String type) {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return;\n }\n\n instance.components.get(type).pauseTimer();\n }", "private static JSONArray parseChildShapesRecursive(ArrayList<Shape> childShapes) throws JSONException {\n if (childShapes != null) {\n JSONArray childShapesArray = new JSONArray();\n\n for (Shape childShape : childShapes) {\n JSONObject childShapeObject = new JSONObject();\n\n childShapeObject.put(\"resourceId\",\n childShape.getResourceId().toString());\n childShapeObject.put(\"properties\",\n parseProperties(childShape.getProperties()));\n childShapeObject.put(\"stencil\",\n parseStencil(childShape.getStencilId()));\n childShapeObject.put(\"childShapes\",\n parseChildShapesRecursive(childShape.getChildShapes()));\n childShapeObject.put(\"outgoing\",\n parseOutgoings(childShape.getOutgoings()));\n childShapeObject.put(\"bounds\",\n parseBounds(childShape.getBounds()));\n childShapeObject.put(\"dockers\",\n parseDockers(childShape.getDockers()));\n\n if (childShape.getTarget() != null) {\n childShapeObject.put(\"target\",\n parseTarget(childShape.getTarget()));\n }\n\n childShapesArray.put(childShapeObject);\n }\n\n return childShapesArray;\n }\n\n return new JSONArray();\n }", "public DateRange getRange(int index)\n {\n DateRange result;\n\n if (index >= 0 && index < m_ranges.size())\n {\n result = m_ranges.get(index);\n }\n else\n {\n result = DateRange.EMPTY_RANGE;\n }\n\n return (result);\n }", "public void showTrajectoryAndSpline(){\n\t\t\n\t\tif(t.getDimension()==2){\n\t\t \tdouble[] xData = new double[rotatedTrajectory.size()];\n\t\t double[] yData = new double[rotatedTrajectory.size()];\n\t\t for(int i = 0; i < rotatedTrajectory.size(); i++){\n\t\t \txData[i] = rotatedTrajectory.get(i).x;\n\t\t \tyData[i] = rotatedTrajectory.get(i).y;\t\t \t\n\t\t }\n\t\t // Create Chart\n\t\t Chart chart = QuickChart.getChart(\"Spline+Track\", \"X\", \"Y\", \"y(x)\", xData, yData);\n\t\t \n\t\t //Add spline support points\n\t\t double[] subxData = new double[splineSupportPoints.size()];\n\t\t double[] subyData = new double[splineSupportPoints.size()];\n\t\t \n\t\t for(int i = 0; i < splineSupportPoints.size(); i++){\n\t\t \tsubxData[i] = splineSupportPoints.get(i).x;\n\t\t \tsubyData[i] = splineSupportPoints.get(i).y;\n\t\t }\n\t\t Series s = chart.addSeries(\"Spline Support Points\", subxData, subyData);\n\t\t s.setLineStyle(SeriesLineStyle.NONE);\n\t\t s.setSeriesType(SeriesType.Line);\n\t\t \n\t\t //ADd spline points\n\t\t int numberInterpolatedPointsPerSegment = 20;\n\t\t int numberOfSplines = spline.getN();\n\t\t double[] sxData = new double[numberInterpolatedPointsPerSegment*numberOfSplines];\n\t\t \n\t\t double[] syData = new double[numberInterpolatedPointsPerSegment*numberOfSplines];\n\t\t double[] knots = spline.getKnots();\n\t\t for(int i = 0; i < numberOfSplines; i++){\n\t\t \tdouble x = knots[i];\n\t\t \n\t\t \tdouble stopx = knots[i+1];\n\t\t \tdouble dx = (stopx-x)/numberInterpolatedPointsPerSegment;\n\t\t \t\n\t\t \tfor(int j = 0; j < numberInterpolatedPointsPerSegment; j++){\n\n\t\t \t\tsxData[i*numberInterpolatedPointsPerSegment+j] = x;\n\t\t \t\tsyData[i*numberInterpolatedPointsPerSegment+j] = spline.value(x);\n\t\t \t\tx += dx;\n\t\t \t}\n\t\t \t\n\t\t }\n\t\t s = chart.addSeries(\"Spline\", sxData, syData);\n\t\t s.setLineStyle(SeriesLineStyle.DASH_DASH);\n\t\t s.setMarker(SeriesMarker.NONE);\n\t\t s.setSeriesType(SeriesType.Line);\n\t\t \n\t\t \n\t\t //Show it\n\t\t new SwingWrapper(chart).displayChart();\n\t\t} \n\t}", "private Integer getIntegerTimeInMinutes(Date date)\n {\n Integer result = null;\n if (date != null)\n {\n Calendar cal = DateHelper.popCalendar(date);\n int time = cal.get(Calendar.HOUR_OF_DAY) * 60;\n time += cal.get(Calendar.MINUTE);\n DateHelper.pushCalendar(cal);\n result = Integer.valueOf(time); \n }\n return (result);\n }", "private static X509Certificate getReqSigCert(Message message) {\n\t\tList<WSHandlerResult> results = \n CastUtils.cast((List<?>)\n message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS));\n\n if (results == null) {\n \treturn null;\n }\n \n /*\n\t\t * Scan the results for a matching actor. Use results only if the\n\t\t * receiving Actor and the sending Actor match.\n\t\t */\n\t\tfor (WSHandlerResult rResult : results) {\n\t\t\tList<WSSecurityEngineResult> wsSecEngineResults = rResult\n\t\t\t\t\t.getResults();\n\t\t\t/*\n\t\t\t * Scan the results for the first Signature action. Use the\n\t\t\t * certificate of this Signature to set the certificate for the\n\t\t\t * encryption action :-).\n\t\t\t */\n\t\t\tfor (WSSecurityEngineResult wser : wsSecEngineResults) {\n\t\t\t\tInteger actInt = (Integer) wser\n\t\t\t\t\t\t.get(WSSecurityEngineResult.TAG_ACTION);\n\t\t\t\tif (actInt.intValue() == WSConstants.SIGN) {\n\t\t\t\t\treturn (X509Certificate) wser\n\t\t\t\t\t\t\t.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "public int[] getDefalutValuesArray() {\n int[] defaultValues = new int[5];\n\n defaultValues[0] = GLES20.GL_LINEAR_MIPMAP_NEAREST; // MIN FILTER\n defaultValues[1] = GLES20.GL_LINEAR; // MAG FILTER\n defaultValues[2] = 1; // ANISO FILTER\n defaultValues[3] = GLES20.GL_CLAMP_TO_EDGE; // WRAP S\n defaultValues[4] = GLES20.GL_CLAMP_TO_EDGE; // WRAP T\n\n return defaultValues;\n }", "public ReferrerList getPhotostreamReferrers(Date date, String domain, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_PHOTOSTREAM_REFERRERS, domain, null, null, date, perPage, page);\n }", "public static int compactDistance(String s1, String s2) {\n if (s1.length() == 0)\n return s2.length();\n if (s2.length() == 0)\n return s1.length();\n\n // the maximum edit distance there is any point in reporting.\n int maxdist = Math.min(s1.length(), s2.length()) / 2;\n \n // we allocate just one column instead of the entire matrix, in\n // order to save space. this also enables us to implement the\n // algorithm somewhat faster. the first cell is always the\n // virtual first row.\n int s1len = s1.length();\n int[] column = new int[s1len + 1];\n\n // first we need to fill in the initial column. we use a separate\n // loop for this, because in this case our basis for comparison is\n // not the previous column, but a virtual first column.\n int ix2 = 0;\n char ch2 = s2.charAt(ix2);\n column[0] = 1; // virtual first row\n for (int ix1 = 1; ix1 <= s1len; ix1++) {\n int cost = s1.charAt(ix1 - 1) == ch2 ? 0 : 1;\n\n // Lowest of three: above (column[ix1 - 1]), aboveleft: ix1 - 1,\n // left: ix1. Latter cannot possibly be lowest, so is\n // ignored.\n column[ix1] = Math.min(column[ix1 - 1], ix1 - 1) + cost;\n }\n\n // okay, now we have an initialized first column, and we can\n // compute the rest of the matrix.\n int above = 0;\n for (ix2 = 1; ix2 < s2.length(); ix2++) {\n ch2 = s2.charAt(ix2);\n above = ix2 + 1; // virtual first row\n\n int smallest = s1len * 2; // used to implement cutoff\n for (int ix1 = 1; ix1 <= s1len; ix1++) {\n int cost = s1.charAt(ix1 - 1) == ch2 ? 0 : 1;\n\n // above: above\n // aboveleft: column[ix1 - 1]\n // left: column[ix1]\n int value = Math.min(Math.min(above, column[ix1 - 1]), column[ix1]) +\n cost;\n column[ix1 - 1] = above; // write previous\n above = value; // keep current\n smallest = Math.min(smallest, value);\n }\n column[s1len] = above;\n\n // check if we can stop because we'll be going over the max distance\n if (smallest > maxdist)\n return smallest;\n }\n\n // ok, we're done\n return above;\n }" ]
Return true if c has a @hidden tag associated with it
[ "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 }" ]
[ "public void addRegexRoute(String urlPattern, Class<? extends Actor> actorClass) throws RouteAlreadyMappedException {\n addRoute(new Route(urlPattern, true), actorClass);\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 static void mainInternal(String[] args) throws Exception {\n\n Options options = new Options();\n CmdLineParser parser = new CmdLineParser(options);\n try {\n parser.parseArgument(args);\n } catch (CmdLineException e) {\n helpScreen(parser);\n return;\n }\n\n try {\n List<String> configs = new ArrayList<>();\n if (options.configs != null) {\n configs.addAll(Arrays.asList(options.configs.split(\",\")));\n }\n ConfigSupport.applyConfigChange(ConfigSupport.getJBossHome(), configs, options.enable);\n } catch (ConfigException ex) {\n ConfigLogger.error(ex);\n throw ex;\n } catch (Throwable th) {\n ConfigLogger.error(th);\n throw th;\n }\n }", "private void add(int field)\n {\n if (field < m_flags.length)\n {\n if (m_flags[field] == false)\n {\n m_flags[field] = true;\n m_fields[m_count] = field;\n ++m_count;\n }\n }\n }", "public PhotoList<Photo> searchInterestingness(SearchParameters params, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INTERESTINGNESS);\r\n\r\n parameters.putAll(params.getAsParameters());\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n Photo photo = new Photo();\r\n photo.setId(photoElement.getAttribute(\"id\"));\r\n\r\n User owner = new User();\r\n owner.setId(photoElement.getAttribute(\"owner\"));\r\n photo.setOwner(owner);\r\n\r\n photo.setSecret(photoElement.getAttribute(\"secret\"));\r\n photo.setServer(photoElement.getAttribute(\"server\"));\r\n photo.setFarm(photoElement.getAttribute(\"farm\"));\r\n photo.setTitle(photoElement.getAttribute(\"title\"));\r\n photo.setPublicFlag(\"1\".equals(photoElement.getAttribute(\"ispublic\")));\r\n photo.setFriendFlag(\"1\".equals(photoElement.getAttribute(\"isfriend\")));\r\n photo.setFamilyFlag(\"1\".equals(photoElement.getAttribute(\"isfamily\")));\r\n photos.add(photo);\r\n }\r\n return photos;\r\n }", "public int getSridFromCrs(String crs) {\n\t\tint crsInt;\n\t\tif (crs.indexOf(':') != -1) {\n\t\t\tcrsInt = Integer.parseInt(crs.substring(crs.indexOf(':') + 1));\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tcrsInt = Integer.parseInt(crs);\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\tcrsInt = 0;\n\t\t\t}\n\t\t}\n\t\treturn crsInt;\n\t}", "private Duration getAssignmentWork(ProjectCalendar calendar, TimephasedWork assignment)\n {\n Date assignmentStart = assignment.getStart();\n\n Date splitStart = assignmentStart;\n Date splitFinishTime = calendar.getFinishTime(splitStart);\n Date splitFinish = DateHelper.setTime(splitStart, splitFinishTime);\n\n Duration calendarSplitWork = calendar.getWork(splitStart, splitFinish, TimeUnit.MINUTES);\n Duration assignmentWorkPerDay = assignment.getAmountPerDay();\n Duration splitWork;\n\n double splitMinutes = assignmentWorkPerDay.getDuration();\n splitMinutes *= calendarSplitWork.getDuration();\n splitMinutes /= (8 * 60); // this appears to be a fixed value\n splitWork = Duration.getInstance(splitMinutes, TimeUnit.MINUTES);\n return splitWork;\n }", "protected boolean check(String id, List<String> includes) {\n\t\tif (null != includes) {\n\t\t\tfor (String check : includes) {\n\t\t\t\tif (check(id, check)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public MACAddressSection toEUI(boolean extended) {\n\t\tMACAddressSegment[] segs = toEUISegments(extended);\n\t\tif(segs == null) {\n\t\t\treturn null;\n\t\t}\n\t\tMACAddressCreator creator = getMACNetwork().getAddressCreator();\n\t\treturn createSectionInternal(creator, segs, Math.max(0, addressSegmentIndex - 4) << 1, extended);\n\t}" ]
Flag that the processor has started execution. @param processorGraphNode the node that has started.
[ "private void started(final ProcessorGraphNode processorGraphNode) {\n this.processorLock.lock();\n try {\n this.runningProcessors.put(processorGraphNode.getProcessor(), null);\n } finally {\n this.processorLock.unlock();\n }\n }" ]
[ "public static Duration add(Duration a, Duration b, ProjectProperties defaults)\n {\n if (a == null && b == null)\n {\n return null;\n }\n if (a == null)\n {\n return b;\n }\n if (b == null)\n {\n return a;\n }\n TimeUnit unit = a.getUnits();\n if (b.getUnits() != unit)\n {\n b = b.convertUnits(unit, defaults);\n }\n\n return Duration.getInstance(a.getDuration() + b.getDuration(), unit);\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 }", "public static BoxLegalHoldPolicy.Info createOngoing(BoxAPIConnection api, String name, String description) {\n URL url = ALL_LEGAL_HOLD_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"policy_name\", name)\n .add(\"is_ongoing\", true);\n if (description != null) {\n requestJSON.add(\"description\", description);\n }\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxLegalHoldPolicy createdPolicy = new BoxLegalHoldPolicy(api, responseJSON.get(\"id\").asString());\n return createdPolicy.new Info(responseJSON);\n }", "private long recover() throws IOException {\n checkMutable();\n long len = channel.size();\n ByteBuffer buffer = ByteBuffer.allocate(4);\n long validUpTo = 0;\n long next = 0L;\n do {\n next = validateMessage(channel, validUpTo, len, buffer);\n if (next >= 0) validUpTo = next;\n } while (next >= 0);\n channel.truncate(validUpTo);\n setSize.set(validUpTo);\n setHighWaterMark.set(validUpTo);\n logger.info(\"recover high water mark:\" + highWaterMark());\n /* This should not be necessary, but fixes bug 6191269 on some OSs. */\n channel.position(validUpTo);\n needRecover.set(false);\n return len - validUpTo;\n }", "public ArrayList<Duration> segmentWork(ProjectCalendar projectCalendar, List<TimephasedWork> work, TimescaleUnits rangeUnits, List<DateRange> dateList)\n {\n ArrayList<Duration> result = new ArrayList<Duration>(dateList.size());\n int lastStartIndex = 0;\n\n //\n // Iterate through the list of dates range we are interested in.\n // Each date range in this list corresponds to a column\n // shown on the \"timescale\" view by MS Project\n //\n for (DateRange range : dateList)\n {\n //\n // If the current date range does not intersect with any of the\n // assignment date ranges in the list, then we show a zero\n // duration for this date range.\n //\n int startIndex = lastStartIndex == -1 ? -1 : getStartIndex(range, work, lastStartIndex);\n if (startIndex == -1)\n {\n result.add(Duration.getInstance(0, TimeUnit.HOURS));\n }\n else\n {\n //\n // We have found an assignment which intersects with the current\n // date range, call the method below to determine how\n // much time from this resource assignment can be allocated\n // to the current date range.\n //\n result.add(getRangeDuration(projectCalendar, rangeUnits, range, work, startIndex));\n lastStartIndex = startIndex;\n }\n }\n\n return result;\n }", "public Result cmd(String cliCommand) {\n try {\n // The intent here is to return a Response when this is doable.\n if (ctx.isWorkflowMode() || ctx.isBatchMode()) {\n ctx.handle(cliCommand);\n return new Result(cliCommand, ctx.getExitCode());\n }\n handler.parse(ctx.getCurrentNodePath(), cliCommand, ctx);\n if (handler.getFormat() == OperationFormat.INSTANCE) {\n ModelNode request = ctx.buildRequest(cliCommand);\n ModelNode response = ctx.execute(request, cliCommand);\n return new Result(cliCommand, request, response);\n } else {\n ctx.handle(cliCommand);\n return new Result(cliCommand, ctx.getExitCode());\n }\n } catch (CommandLineException cfe) {\n throw new IllegalArgumentException(\"Error handling command: \"\n + cliCommand, cfe);\n } catch (IOException ioe) {\n throw new IllegalStateException(\"Unable to send command \"\n + cliCommand + \" to server.\", ioe);\n }\n }", "public <T extends Widget & Checkable> List<T> getCheckableChildren() {\n List<Widget> children = getChildren();\n ArrayList<T> result = new ArrayList<>();\n for (Widget c : children) {\n if (c instanceof Checkable) {\n result.add((T) c);\n }\n }\n return result;\n }", "public String getKeyValue(String key){\n String keyName = keysMap.get(key);\n if (keyName != null){\n return keyName;\n }\n return \"\"; //key wasn't defined in keys properties file\n }", "public static double diagProd( DMatrix1Row T )\n {\n double prod = 1.0;\n int N = Math.min(T.numRows,T.numCols);\n for( int i = 0; i < N; i++ ) {\n prod *= T.unsafe_get(i,i);\n }\n\n return prod;\n }" ]
Use this API to delete systemuser of given name.
[ "public static base_response delete(nitro_service client, String username) throws Exception {\n\t\tsystemuser deleteresource = new systemuser();\n\t\tdeleteresource.username = username;\n\t\treturn deleteresource.delete_resource(client);\n\t}" ]
[ "public static base_response add(nitro_service client, dnssuffix resource) throws Exception {\n\t\tdnssuffix addresource = new dnssuffix();\n\t\taddresource.Dnssuffix = resource.Dnssuffix;\n\t\treturn addresource.add_resource(client);\n\t}", "public static Cluster randomShufflePartitions(final Cluster nextCandidateCluster,\n final int randomSwapAttempts,\n final int randomSwapSuccesses,\n final List<Integer> randomSwapZoneIds,\n List<StoreDefinition> storeDefs) {\n List<Integer> zoneIds = null;\n if(randomSwapZoneIds.isEmpty()) {\n zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds());\n } else {\n zoneIds = new ArrayList<Integer>(randomSwapZoneIds);\n }\n\n List<Integer> nodeIds = new ArrayList<Integer>();\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n\n int successes = 0;\n for(int i = 0; i < randomSwapAttempts; i++) {\n\n // Iterate over zone ids to decide which node ids to include for\n // intra-zone swapping.\n // In future, if there is a need to support inter-zone swapping,\n // then just remove the\n // zone specific logic that populates nodeIdSet and add all nodes\n // from across all zones.\n\n int zoneIdOffset = i % zoneIds.size();\n\n Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset));\n nodeIds = new ArrayList<Integer>(nodeIdSet);\n\n Collections.shuffle(zoneIds, new Random(System.currentTimeMillis()));\n Cluster shuffleResults = swapRandomPartitionsAmongNodes(returnCluster, nodeIds);\n\n double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility();\n if(nextUtility < currentUtility) {\n System.out.println(\"Swap improved max-min ratio: \" + currentUtility + \" -> \"\n + nextUtility + \" (improvement \" + successes\n + \" on swap attempt \" + i + \")\");\n successes++;\n returnCluster = shuffleResults;\n currentUtility = nextUtility;\n }\n if(successes >= randomSwapSuccesses) {\n // Enough successes, move on.\n break;\n }\n }\n return returnCluster;\n }", "public void removeHoursFromDay(ProjectCalendarHours hours)\n {\n if (hours.getParentCalendar() != this)\n {\n throw new IllegalArgumentException();\n }\n m_hours[hours.getDay().getValue() - 1] = null;\n }", "private String tail(String moduleName) {\n if (moduleName.indexOf(MODULE_NAME_SEPARATOR) > 0) {\n return moduleName.substring(moduleName.indexOf(MODULE_NAME_SEPARATOR) + 1);\n } else {\n return \"\";\n }\n }", "public HashMap<String, Object> getFirstResult(String query)\n throws Exception {\n HashMap<String, Object> result = null;\n\n Statement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = getConnection()) {\n queryStatement = sqlConnection.createStatement();\n results = queryStatement.executeQuery(query);\n if (results.next()) {\n result = new HashMap<>();\n String[] columns = getColumnNames(results.getMetaData());\n\n for (String column : columns) {\n result.put(column, results.getObject(column));\n }\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return result;\n }", "public Where<T, ID> like(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.LIKE_OPERATION));\n\t\treturn this;\n\t}", "private void setLanguageFilters(String filters) {\n\t\tthis.filterLanguages = new HashSet<>();\n\t\tif (!\"-\".equals(filters)) {\n\t\t\tCollections.addAll(this.filterLanguages, filters.split(\",\"));\n\t\t}\n\t}", "public Map<String, MBeanOperationInfo> getOperationMetadata() {\n\n MBeanOperationInfo[] operations = mBeanInfo.getOperations();\n\n Map<String, MBeanOperationInfo> operationMap = new TreeMap<String, MBeanOperationInfo>();\n for (MBeanOperationInfo operation: operations) {\n operationMap.put(operation.getName(), operation);\n }\n return operationMap;\n }", "@Nullable\n private static Object valueOf(String value, Class<?> cls) {\n if (cls == Boolean.TYPE) {\n return Boolean.valueOf(value);\n }\n if (cls == Character.TYPE) {\n return value.length() >= 1 ? value.charAt(0) : defaultValue(char.class);\n }\n if (cls == Byte.TYPE) {\n return Byte.valueOf(value);\n }\n if (cls == Short.TYPE) {\n return Short.valueOf(value);\n }\n if (cls == Integer.TYPE) {\n return Integer.valueOf(value);\n }\n if (cls == Long.TYPE) {\n return Long.valueOf(value);\n }\n if (cls == Float.TYPE) {\n return Float.valueOf(value);\n }\n if (cls == Double.TYPE) {\n return Double.valueOf(value);\n }\n return null;\n }" ]
Find the path to the first association in the property path. @param targetTypeName the entity with the property @param pathWithoutAlias the path to the property WITHOUT the alias @return the path to the first association or {@code null} if there isn't an association in the property path
[ "public List<String> findAssociationPath(String targetTypeName, List<String> pathWithoutAlias) {\n\t\tList<String> subPath = new ArrayList<String>( pathWithoutAlias.size() );\n\t\tfor ( String name : pathWithoutAlias ) {\n\t\t\tsubPath.add( name );\n\t\t\tif ( isAssociation( targetTypeName, subPath ) ) {\n\t\t\t\treturn subPath;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}" ]
[ "private String validatePattern() {\n\n String error = null;\n switch (getPatternType()) {\n case DAILY:\n error = isEveryWorkingDay() ? null : validateInterval();\n break;\n case WEEKLY:\n error = validateInterval();\n if (null == error) {\n error = validateWeekDaySet();\n }\n break;\n case MONTHLY:\n error = validateInterval();\n if (null == error) {\n error = validateMonthSet();\n if (null == error) {\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n }\n }\n break;\n case YEARLY:\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n break;\n case INDIVIDUAL:\n case NONE:\n default:\n }\n return error;\n }", "public static boolean isTodoItem(final Document todoItemDoc) {\n return todoItemDoc.containsKey(ID_KEY)\n && todoItemDoc.containsKey(TASK_KEY)\n && todoItemDoc.containsKey(CHECKED_KEY);\n }", "public static Map<String,List<Long>> readHints(File hints) throws IOException {\n Map<String,List<Long>> result = new HashMap<>();\n InputStream is = new FileInputStream(hints);\n mergeHints(is, result);\n return result;\n }", "@Pure\n\tpublic static <P1, P2, P3, P4, P5> Procedure4<P2, P3, P4, P5> curry(final Procedure5<? super P1, ? super P2, ? super P3, ? super P4, ? super P5> procedure,\n\t\t\tfinal P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure4<P2, P3, P4, P5>() {\n\t\t\t@Override\n\t\t\tpublic void apply(P2 p2, P3 p3, P4 p4, P5 p5) {\n\t\t\t\tprocedure.apply(argument, p2, p3, p4, p5);\n\t\t\t}\n\t\t};\n\t}", "public static base_responses add(nitro_service client, cacheselector resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheselector addresources[] = new cacheselector[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new cacheselector();\n\t\t\t\taddresources[i].selectorname = resources[i].selectorname;\n\t\t\t\taddresources[i].rule = resources[i].rule;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static responderpolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tresponderpolicylabel_binding obj = new responderpolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tresponderpolicylabel_binding response = (responderpolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static appfwsignatures get(nitro_service service, String name) throws Exception{\n\t\tappfwsignatures obj = new appfwsignatures();\n\t\tobj.set_name(name);\n\t\tappfwsignatures response = (appfwsignatures) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static base_response clear(nitro_service client) throws Exception {\n\t\tnspbr6 clearresource = new nspbr6();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}", "public Collection<String> getMethods() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_METHODS);\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\r\n Element methodsElement = response.getPayload();\r\n\r\n List<String> methods = new ArrayList<String>();\r\n NodeList methodElements = methodsElement.getElementsByTagName(\"method\");\r\n for (int i = 0; i < methodElements.getLength(); i++) {\r\n Element methodElement = (Element) methodElements.item(i);\r\n methods.add(XMLUtilities.getValue(methodElement));\r\n }\r\n return methods;\r\n }" ]