query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Performs a matrix inversion operations that takes advantage of the special
properties of a covariance matrix.
@param cov A covariance matrix. Not modified.
@param cov_inv The inverse of cov. Modified.
@return true if it could invert the matrix false if it could not. | [
"public static boolean invert(final DMatrixRMaj cov , final DMatrixRMaj cov_inv ) {\n if( cov.numCols <= 4 ) {\n if( cov.numCols != cov.numRows ) {\n throw new IllegalArgumentException(\"Must be a square matrix.\");\n }\n\n if( cov.numCols >= 2 )\n UnrolledInverseFromMinor_DDRM.inv(cov,cov_inv);\n else\n cov_inv.data[0] = 1.0/cov.data[0];\n\n } else {\n LinearSolverDense<DMatrixRMaj> solver = LinearSolverFactory_DDRM.symmPosDef(cov.numRows);\n // wrap it to make sure the covariance is not modified.\n solver = new LinearSolverSafe<DMatrixRMaj>(solver);\n if( !solver.setA(cov) )\n return false;\n solver.invert(cov_inv);\n }\n return true;\n }"
] | [
"public static String confSetName() {\n String profile = SysProps.get(AppConfigKey.PROFILE.key());\n if (S.blank(profile)) {\n profile = Act.mode().name().toLowerCase();\n }\n return profile;\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 addTags(String photoId, String[] tags) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD_TAGS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"tags\", StringUtilities.join(tags, \" \", true));\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 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 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 void setClasspathRef(Reference r)\r\n {\r\n createClasspath().setRefid(r);\r\n log(\"Verification classpath is \"+ _classpath,\r\n Project.MSG_VERBOSE);\r\n }",
"public void sendJsonToTagged(Object data, String label) {\n sendToTagged(JSON.toJSONString(data), label);\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}",
"private Map<ConfigurationKey, Object> getObsoleteSystemProperties() {\n Map<ConfigurationKey, Object> found = new EnumMap<ConfigurationKey, Object>(ConfigurationKey.class);\n String concurrentDeployment = getSystemProperty(\"org.jboss.weld.bootstrap.properties.concurrentDeployment\");\n if (concurrentDeployment != null) {\n processKeyValue(found, ConfigurationKey.CONCURRENT_DEPLOYMENT, concurrentDeployment);\n found.put(ConfigurationKey.CONCURRENT_DEPLOYMENT, ConfigurationKey.CONCURRENT_DEPLOYMENT.convertValue(concurrentDeployment));\n }\n String preloaderThreadPoolSize = getSystemProperty(\"org.jboss.weld.bootstrap.properties.preloaderThreadPoolSize\");\n if (preloaderThreadPoolSize != null) {\n found.put(ConfigurationKey.PRELOADER_THREAD_POOL_SIZE, ConfigurationKey.PRELOADER_THREAD_POOL_SIZE.convertValue(preloaderThreadPoolSize));\n }\n return found;\n }"
] |
generate a message for loglevel WARN
@param pObject the message Object | [
"public final void warn(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.WARN, pObject, null);\r\n\t}"
] | [
"@Override\n public SuggestAccountsRequest suggestAccounts() throws RestApiException {\n return new SuggestAccountsRequest() {\n @Override\n public List<AccountInfo> get() throws RestApiException {\n return AccountsRestClient.this.suggestAccounts(this);\n }\n };\n }",
"private InputStream prepareInputStream(InputStream stream) throws IOException\n {\n InputStream result;\n BufferedInputStream bis = new BufferedInputStream(stream);\n readHeaderProperties(bis);\n if (isCompressed())\n {\n result = new InflaterInputStream(bis);\n }\n else\n {\n result = bis;\n }\n return result;\n }",
"protected void onNewParentObject(GVRSceneObject parent) {\n for (GVRComponent comp : mComponents.values()) {\n comp.onNewOwnersParent(parent);\n }\n }",
"private QueueCursor updateCursorForDBObject(JSONObject dbObject, QueueCursor cursor) {\n\n if (dbObject == null) return cursor;\n\n Iterator<String> keys = dbObject.keys();\n if (keys.hasNext()) {\n String key = keys.next();\n cursor.setLastId(key);\n try {\n cursor.setData(dbObject.getJSONArray(key));\n } catch (JSONException e) {\n cursor.setLastId(null);\n cursor.setData(null);\n }\n }\n\n return cursor;\n }",
"public static int cudnnPoolingBackward(\n cudnnHandle handle, \n cudnnPoolingDescriptor poolingDesc, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnPoolingBackwardNative(handle, poolingDesc, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }",
"private void revisitMessages(Definitions def) {\n List<RootElement> rootElements = def.getRootElements();\n List<ItemDefinition> toAddDefinitions = new ArrayList<ItemDefinition>();\n for (RootElement root : rootElements) {\n if (root instanceof Message) {\n if (!existsMessageItemDefinition(rootElements,\n root.getId())) {\n ItemDefinition itemdef = Bpmn2Factory.eINSTANCE.createItemDefinition();\n itemdef.setId(root.getId() + \"Type\");\n toAddDefinitions.add(itemdef);\n ((Message) root).setItemRef(itemdef);\n }\n }\n }\n for (ItemDefinition id : toAddDefinitions) {\n def.getRootElements().add(id);\n }\n }",
"public static NodeCache startAppIdWatcher(Environment env) {\n try {\n CuratorFramework curator = env.getSharedResources().getCurator();\n\n byte[] uuidBytes = curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);\n if (uuidBytes == null) {\n Halt.halt(\"Fluo Application UUID not found\");\n throw new RuntimeException(); // make findbugs happy\n }\n\n final String uuid = new String(uuidBytes, StandardCharsets.UTF_8);\n\n final NodeCache nodeCache = new NodeCache(curator, ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);\n nodeCache.getListenable().addListener(() -> {\n ChildData node = nodeCache.getCurrentData();\n if (node == null || !uuid.equals(new String(node.getData(), StandardCharsets.UTF_8))) {\n Halt.halt(\"Fluo Application UUID has changed or disappeared\");\n }\n });\n nodeCache.start();\n return nodeCache;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"public static Duration getVariance(Task task, Date date1, Date date2, TimeUnit format)\n {\n Duration variance = null;\n\n if (date1 != null && date2 != null)\n {\n ProjectCalendar calendar = task.getEffectiveCalendar();\n if (calendar != null)\n {\n variance = calendar.getWork(date1, date2, format);\n }\n }\n\n if (variance == null)\n {\n variance = Duration.getInstance(0, format);\n }\n\n return (variance);\n }",
"private static int[] getErrorCorrection(int[] codewords, int ecclen) {\r\n\r\n ReedSolomon rs = new ReedSolomon();\r\n rs.init_gf(0x43);\r\n rs.init_code(ecclen, 1);\r\n rs.encode(codewords.length, codewords);\r\n\r\n int[] results = new int[ecclen];\r\n for (int i = 0; i < ecclen; i++) {\r\n results[i] = rs.getResult(results.length - 1 - i);\r\n }\r\n\r\n return results;\r\n }"
] |
Initializes the editor states for the different modes, depending on the type of the opened file. | [
"private void initEditorStates() {\n\n m_editorState = new HashMap<CmsMessageBundleEditorTypes.EditMode, EditorState>();\n List<TableProperty> cols = null;\n switch (m_bundleType) {\n case PROPERTY:\n case XML:\n if (hasDescriptor()) { // bundle descriptor is present, keys are not editable in default mode, maybe master mode is available\n m_editorState.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, getDefaultState());\n if (hasMasterMode()) { // the bundle descriptor is editable\n m_editorState.put(CmsMessageBundleEditorTypes.EditMode.MASTER, getMasterState());\n }\n } else { // no bundle descriptor given - implies no master mode\n cols = new ArrayList<TableProperty>(1);\n cols.add(TableProperty.KEY);\n cols.add(TableProperty.TRANSLATION);\n m_editorState.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, new EditorState(cols, true));\n }\n break;\n case DESCRIPTOR:\n cols = new ArrayList<TableProperty>(3);\n cols.add(TableProperty.KEY);\n cols.add(TableProperty.DESCRIPTION);\n cols.add(TableProperty.DEFAULT);\n m_editorState.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, new EditorState(cols, true));\n break;\n default:\n throw new IllegalArgumentException();\n }\n\n }"
] | [
"private boolean hasPrimaryKey(T entity) {\n Object pk = getPrimaryKey(entity);\n if (pk == null) {\n return false;\n } else {\n if (pk instanceof Number && ((Number) pk).longValue() == 0) {\n return false;\n }\n }\n return true;\n }",
"public static base_response delete(nitro_service client, String acl6name) throws Exception {\n\t\tnsacl6 deleteresource = new nsacl6();\n\t\tdeleteresource.acl6name = acl6name;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public final B accessToken(String accessToken) {\n requireNonNull(accessToken, \"accessToken\");\n checkArgument(!accessToken.isEmpty(), \"accessToken is empty.\");\n this.accessToken = accessToken;\n return self();\n }",
"public void setRefreshFrequency(IntervalFrequency frequency) {\n if (NONE_REFRESH_INTERVAL == mRefreshInterval && IntervalFrequency.NONE != frequency) {\n // Install draw-frame listener if frequency is no longer NONE\n getGVRContext().unregisterDrawFrameListener(mFrameListener);\n getGVRContext().registerDrawFrameListener(mFrameListener);\n }\n switch (frequency) {\n case REALTIME:\n mRefreshInterval = REALTIME_REFRESH_INTERVAL;\n break;\n case HIGH:\n mRefreshInterval = HIGH_REFRESH_INTERVAL;\n break;\n case MEDIUM:\n mRefreshInterval = MEDIUM_REFRESH_INTERVAL;\n break;\n case LOW:\n mRefreshInterval = LOW_REFRESH_INTERVAL;\n break;\n case NONE:\n mRefreshInterval = NONE_REFRESH_INTERVAL;\n break;\n default:\n break;\n }\n }",
"@JmxGetter(name = \"lastSwapped\", description = \"Time in milliseconds since the store was swapped\")\n public long getLastSwapped() {\n long timeSinceLastSwap = System.currentTimeMillis() - lastSwapped;\n return timeSinceLastSwap > 0 ? timeSinceLastSwap : 0;\n }",
"public boolean getHidden() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_HIDDEN);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element personElement = response.getPayload();\r\n return personElement.getAttribute(\"hidden\").equals(\"1\") ? true : false;\r\n }",
"public synchronized boolean tryDelegateSlop(Node node) {\n if(asyncCallbackShouldSendhint) {\n return false;\n } else {\n slopDestinations.put(node, true);\n return true;\n }\n }",
"public LuaScript endScriptReturn(LuaValue value, LuaScriptConfig config) {\n add(new LuaAstReturnStatement(argument(value)));\n String scriptText = buildScriptText();\n return new BasicLuaScript(scriptText, config);\n }",
"private int calcItemWidth(RecyclerView rvCategories) {\n if (itemWidth == null || itemWidth == 0) {\n for (int i = 0; i < rvCategories.getChildCount(); i++) {\n itemWidth = rvCategories.getChildAt(i).getWidth();\n if (itemWidth != 0) {\n break;\n }\n }\n }\n // in case of call before view was created\n if (itemWidth == null) {\n itemWidth = 0;\n }\n return itemWidth;\n }"
] |
Use this API to update inatparam. | [
"public static base_response update(nitro_service client, inatparam resource) throws Exception {\n\t\tinatparam updateresource = new inatparam();\n\t\tupdateresource.nat46v6prefix = resource.nat46v6prefix;\n\t\tupdateresource.nat46ignoretos = resource.nat46ignoretos;\n\t\tupdateresource.nat46zerochecksum = resource.nat46zerochecksum;\n\t\tupdateresource.nat46v6mtu = resource.nat46v6mtu;\n\t\tupdateresource.nat46fragheader = resource.nat46fragheader;\n\t\treturn updateresource.update_resource(client);\n\t}"
] | [
"public <Result, Param extends Resource> Result execWithTemporaryCaching(Param resource, IUnitOfWork<Result, Param> transaction) throws WrappedException {\n\t\tCacheAdapter cacheAdapter = getOrCreate(resource);\n\t\tIgnoreValuesMemento memento = cacheAdapter.ignoreNewValues();\n\t\ttry {\n\t\t\treturn transaction.exec(resource);\n\t\t} catch (Exception e) {\n\t\t\tthrow new WrappedException(e);\n\t\t} finally {\n\t\t\tmemento.done();\n\t\t}\n\t}",
"public static base_responses flush(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 flushresources[] = new cacheobject[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tflushresources[i] = new cacheobject();\n\t\t\t\tflushresources[i].locator = resources[i].locator;\n\t\t\t\tflushresources[i].url = resources[i].url;\n\t\t\t\tflushresources[i].host = resources[i].host;\n\t\t\t\tflushresources[i].port = resources[i].port;\n\t\t\t\tflushresources[i].groupname = resources[i].groupname;\n\t\t\t\tflushresources[i].httpmethod = resources[i].httpmethod;\n\t\t\t\tflushresources[i].force = resources[i].force;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, flushresources,\"flush\");\n\t\t}\n\t\treturn result;\n\t}",
"protected synchronized Object materializeSubject() throws PersistenceBrokerException\r\n\t{\r\n\t\tTemporaryBrokerWrapper tmp = getBroker();\r\n try\r\n\t\t{\r\n\t\t\tObject realSubject = tmp.broker.getObjectByIdentity(_id);\r\n\t\t\tif (realSubject == null)\r\n\t\t\t{\r\n\t\t\t\tLoggerFactory.getLogger(IndirectionHandler.class).warn(\r\n\t\t\t\t\t\t\"Can not materialize object for Identity \" + _id + \" - using PBKey \" + getBrokerKey());\r\n\t\t\t}\r\n\t\t\treturn realSubject;\r\n\t\t} catch (Exception ex)\r\n\t\t{\r\n\t\t\tthrow new PersistenceBrokerException(ex);\r\n\t\t} finally\r\n\t\t{\r\n\t\t\ttmp.close();\r\n\t\t}\r\n\t}",
"public CollectionRequest<Team> users(String team) {\n \n String path = String.format(\"/teams/%s/users\", team);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }",
"public static base_response update(nitro_service client, snmpoption resource) throws Exception {\n\t\tsnmpoption updateresource = new snmpoption();\n\t\tupdateresource.snmpset = resource.snmpset;\n\t\tupdateresource.snmptraplogging = resource.snmptraplogging;\n\t\treturn updateresource.update_resource(client);\n\t}",
"static int[] toIntArray(List<Integer> integers) {\n\t\tint[] ints = new int[integers.size()];\n\t\tint i = 0;\n\t\tfor (Integer n : integers) {\n\t\t\tints[i++] = n;\n\t\t}\n\t\treturn ints;\n\t}",
"public static boolean propertyExists(Class<?> clazz, String property, ElementType elementType) {\n\t\tif ( ElementType.FIELD.equals( elementType ) ) {\n\t\t\treturn getDeclaredField( clazz, property ) != null;\n\t\t}\n\t\telse {\n\t\t\tString capitalizedPropertyName = capitalize( property );\n\n\t\t\tMethod method = getMethod( clazz, PROPERTY_ACCESSOR_PREFIX_GET + capitalizedPropertyName );\n\t\t\tif ( method != null && method.getReturnType() != void.class ) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tmethod = getMethod( clazz, PROPERTY_ACCESSOR_PREFIX_IS + capitalizedPropertyName );\n\t\t\tif ( method != null && method.getReturnType() == boolean.class ) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}",
"public static Integer convertOverrideIdentifier(String overrideIdentifier) throws Exception {\n Integer overrideId = -1;\n\n try {\n // there is an issue with parseInt where it does not parse negative values correctly\n boolean isNegative = false;\n if (overrideIdentifier.startsWith(\"-\")) {\n isNegative = true;\n overrideIdentifier = overrideIdentifier.substring(1);\n }\n overrideId = Integer.parseInt(overrideIdentifier);\n\n if (isNegative) {\n overrideId = 0 - overrideId;\n }\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n\n // split into two parts\n String className = null;\n String methodName = null;\n int lastDot = overrideIdentifier.lastIndexOf(\".\");\n className = overrideIdentifier.substring(0, lastDot);\n methodName = overrideIdentifier.substring(lastDot + 1);\n\n overrideId = OverrideService.getInstance().getOverrideIdForMethod(className, methodName);\n }\n\n return overrideId;\n }",
"public static void assertValidMetadata(ByteArray key,\n RoutingStrategy routingStrategy,\n Node currentNode) {\n List<Node> nodes = routingStrategy.routeRequest(key.get());\n for(Node node: nodes) {\n if(node.getId() == currentNode.getId()) {\n return;\n }\n }\n\n throw new InvalidMetadataException(\"Client accessing key belonging to partitions \"\n + routingStrategy.getPartitionList(key.get())\n + \" not present at \" + currentNode);\n }"
] |
Creates the udpClient with proper handler.
@return the bound request builder
@throws HttpRequestCreateException
the http request create exception | [
"public ConnectionlessBootstrap bootStrapUdpClient()\n throws HttpRequestCreateException {\n\n ConnectionlessBootstrap udpClient = null;\n try {\n\n // Configure the client.\n udpClient = new ConnectionlessBootstrap(udpMeta.getChannelFactory());\n\n udpClient.setPipeline(new UdpPipelineFactory(\n TcpUdpSshPingResourceStore.getInstance().getTimer(), this)\n .getPipeline());\n\n } catch (Exception t) {\n throw new TcpUdpRequestCreateException(\n \"Error in creating request in udp worker. \"\n + \" If udpClient is null. Then fail to create.\", t);\n }\n\n return udpClient;\n\n }"
] | [
"@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tprivate IntegrationFlowBuilder getFlowBuilder() {\n\n\t\tIntegrationFlowBuilder flowBuilder;\n\t\tURLName urlName = this.properties.getUrl();\n\n\t\tif (this.properties.isIdleImap()) {\n\t\t\tflowBuilder = getIdleImapFlow(urlName);\n\t\t}\n\t\telse {\n\n\t\t\tMailInboundChannelAdapterSpec adapterSpec;\n\t\t\tswitch (urlName.getProtocol().toUpperCase()) {\n\t\t\t\tcase \"IMAP\":\n\t\t\t\tcase \"IMAPS\":\n\t\t\t\t\tadapterSpec = getImapFlowBuilder(urlName);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"POP3\":\n\t\t\t\tcase \"POP3S\":\n\t\t\t\t\tadapterSpec = getPop3FlowBuilder(urlName);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\t\"Unsupported mail protocol: \" + urlName.getProtocol());\n\t\t\t}\n\t\t\tflowBuilder = IntegrationFlows.from(\n\t\t\t\t\tadapterSpec.javaMailProperties(getJavaMailProperties(urlName))\n\t\t\t\t\t\t\t.selectorExpression(this.properties.getExpression())\n\t\t\t\t\t\t\t.shouldDeleteMessages(this.properties.isDelete()),\n\t\t\t\t\tnew Consumer<SourcePollingChannelAdapterSpec>() {\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void accept(\n\t\t\t\t\t\t\t\tSourcePollingChannelAdapterSpec sourcePollingChannelAdapterSpec) {\n\t\t\t\t\t\t\tsourcePollingChannelAdapterSpec.poller(MailSourceConfiguration.this.defaultPoller);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t});\n\n\t\t}\n\t\treturn flowBuilder;\n\t}",
"private boolean hasPrimaryKey(T entity) {\n Object pk = getPrimaryKey(entity);\n if (pk == null) {\n return false;\n } else {\n if (pk instanceof Number && ((Number) pk).longValue() == 0) {\n return false;\n }\n }\n return true;\n }",
"protected void processAssignmentBaseline(Row row)\n {\n Integer id = row.getInteger(\"ASSN_UID\");\n ResourceAssignment assignment = m_assignmentMap.get(id);\n if (assignment != null)\n {\n int index = row.getInt(\"AB_BASE_NUM\");\n\n assignment.setBaselineStart(index, row.getDate(\"AB_BASE_START\"));\n assignment.setBaselineFinish(index, row.getDate(\"AB_BASE_FINISH\"));\n assignment.setBaselineWork(index, row.getDuration(\"AB_BASE_WORK\"));\n assignment.setBaselineCost(index, row.getCurrency(\"AB_BASE_COST\"));\n }\n }",
"public Date getFinishDate()\n {\n Date finishDate = null;\n\n for (Task task : m_tasks)\n {\n //\n // If a hidden \"summary\" task is present we ignore it\n //\n if (NumberHelper.getInt(task.getUniqueID()) == 0)\n {\n continue;\n }\n\n //\n // Select the actual or forecast start date\n //\n Date taskFinishDate;\n taskFinishDate = task.getActualFinish();\n if (taskFinishDate == null)\n {\n taskFinishDate = task.getFinish();\n }\n\n if (taskFinishDate != null)\n {\n if (finishDate == null)\n {\n finishDate = taskFinishDate;\n }\n else\n {\n if (taskFinishDate.getTime() > finishDate.getTime())\n {\n finishDate = taskFinishDate;\n }\n }\n }\n }\n\n return (finishDate);\n }",
"public ReferrerList getCollectionReferrers(Date date, String domain, String collectionId, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_COLLECTION_REFERRERS, domain, \"collection_id\", collectionId, date, perPage, page);\n }",
"public void set1Value(int index, String newValue) {\n try {\n value.set( index, newValue );\n }\n catch (IndexOutOfBoundsException e) {\n Log.e(TAG, \"X3D MFString set1Value(int index, ...) out of bounds.\" + e);\n }\n catch (Exception e) {\n Log.e(TAG, \"X3D MFString set1Value(int index, ...) exception \" + e);\n }\n }",
"public static ServiceName moduleResolvedServiceName(ModuleIdentifier identifier) {\n if (!isDynamicModule(identifier)) {\n throw ServerLogger.ROOT_LOGGER.missingModulePrefix(identifier, MODULE_PREFIX);\n }\n return MODULE_RESOLVED_SERVICE_PREFIX.append(identifier.getName()).append(identifier.getSlot());\n }",
"public static ReportGenerator.Format getFormat( String... args ) {\n ConfigOptionParser configParser = new ConfigOptionParser();\n List<ConfigOption> configOptions = Arrays.asList( format, help );\n\n for( ConfigOption co : configOptions ) {\n if( co.hasDefault() ) {\n configParser.parsedOptions.put( co.getLongName(), co.getValue() );\n }\n }\n\n for( String arg : args ) {\n configParser.commandLineLookup( arg, format, configOptions );\n }\n\n // TODO properties\n // TODO environment\n\n if( !configParser.hasValue( format ) ) {\n configParser.printUsageAndExit( configOptions );\n }\n return (ReportGenerator.Format) configParser.getValue( format );\n }",
"private float getQuaternionW(float x, float y, float z) {\n return (float) Math.cos(Math.asin(Math.sqrt(x * x + y * y + z * z)));\n }"
] |
Bessel function of order n.
@param n Order.
@param x Value.
@return J value. | [
"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 void batchStatusLog(int batchCount,\n int numBatches,\n int partitionStoreCount,\n int numPartitionStores,\n long totalTimeMs) {\n // Calculate the estimated end time and pretty print stats\n double rate = 1;\n long estimatedTimeMs = 0;\n if(numPartitionStores > 0) {\n rate = partitionStoreCount / numPartitionStores;\n estimatedTimeMs = (long) (totalTimeMs / rate) - totalTimeMs;\n }\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"Batch Complete!\")\n .append(Utils.NEWLINE)\n .append(\"\\tbatches moved: \")\n .append(batchCount)\n .append(\" out of \")\n .append(numBatches)\n .append(Utils.NEWLINE)\n .append(\"\\tPartition stores moved: \")\n .append(partitionStoreCount)\n .append(\" out of \")\n .append(numPartitionStores)\n .append(Utils.NEWLINE)\n .append(\"\\tPercent done: \")\n .append(decimalFormatter.format(rate * 100.0))\n .append(Utils.NEWLINE)\n .append(\"\\tEstimated time left: \")\n .append(estimatedTimeMs)\n .append(\" ms (\")\n .append(TimeUnit.MILLISECONDS.toHours(estimatedTimeMs))\n .append(\" hours)\");\n RebalanceUtils.printBatchLog(batchCount, logger, sb.toString());\n }",
"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 App on(Heroku.Stack stack) {\n App newApp = copy();\n newApp.stack = new App.Stack(stack);\n return newApp;\n }",
"public int getMinutesPerMonth()\n {\n return m_minutesPerMonth == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerMonth()) : m_minutesPerMonth.intValue();\n }",
"String getDefaultReturnFields() {\n\n StringBuffer fields = new StringBuffer(\"\");\n fields.append(CmsSearchField.FIELD_PATH);\n fields.append(',');\n fields.append(CmsSearchField.FIELD_INSTANCEDATE).append('_').append(getSearchLocale().toString()).append(\"_dt\");\n fields.append(',');\n fields.append(CmsSearchField.FIELD_INSTANCEDATE_END).append('_').append(getSearchLocale().toString()).append(\n \"_dt\");\n fields.append(',');\n fields.append(CmsSearchField.FIELD_INSTANCEDATE_CURRENT_TILL).append('_').append(\n getSearchLocale().toString()).append(\"_dt\");\n fields.append(',');\n fields.append(CmsSearchField.FIELD_ID);\n fields.append(',');\n fields.append(CmsSearchField.FIELD_SOLR_ID);\n fields.append(',');\n fields.append(CmsSearchField.FIELD_DISPTITLE).append('_').append(getSearchLocale().toString()).append(\"_sort\");\n fields.append(',');\n fields.append(CmsSearchField.FIELD_LINK);\n return fields.toString();\n }",
"public static HashMap<String, String> getMapFromJSONPath(JSONObject record, String path) {\n return getObjectFromJSONPath(record, path);\n }",
"public static CompressionType getDumpFileCompressionType(String fileName) {\n\t\tif (fileName.endsWith(\".gz\")) {\n\t\t\treturn CompressionType.GZIP;\n\t\t} else if (fileName.endsWith(\".bz2\")) {\n\t\t\treturn CompressionType.BZ2;\n\t\t} else {\n\t\t\treturn CompressionType.NONE;\n\t\t}\n\t}",
"public Duration getWork(Date date, TimeUnit format)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, null);\n long time = getTotalTime(ranges);\n return convertFormat(time, format);\n }",
"private AsyncResourceRequest<V> getNextUnexpiredResourceRequest(Queue<AsyncResourceRequest<V>> requestQueue) {\n AsyncResourceRequest<V> resourceRequest = requestQueue.poll();\n while(resourceRequest != null) {\n if(resourceRequest.getDeadlineNs() < System.nanoTime()) {\n resourceRequest.handleTimeout();\n resourceRequest = requestQueue.poll();\n } else {\n break;\n }\n }\n return resourceRequest;\n }"
] |
This function looks for files with the "wrong" replica type in their name, and
if it finds any, renames them.
Those files may have ended up on this server either because:
- 1. We restored them from another server, where they were named according to
another replica type. Or,
- 2. The {@link voldemort.store.readonly.mr.azkaban.VoldemortBuildAndPushJob}
and the {@link voldemort.store.readonly.fetcher.HdfsFetcher} are
operating in 'build.primary.replicas.only' mode, so they only ever built
and fetched replica 0 of any given file.
Note: This is an implementation detail of the READONLY_V2 naming scheme, and should
not be used outside of that scope.
@param masterPartitionId partition ID of the "primary replica"
@param correctReplicaType replica number which should be found on the current
node for the provided masterPartitionId. | [
"private void renameReadOnlyV2Files(int masterPartitionId, int correctReplicaType) {\n for (int replica = 0; replica < routingStrategy.getNumReplicas(); replica++) {\n if (replica != correctReplicaType) {\n int chunkId = 0;\n while (true) {\n String fileName = Integer.toString(masterPartitionId) + \"_\"\n + Integer.toString(replica) + \"_\"\n + Integer.toString(chunkId);\n File index = getIndexFile(fileName);\n File data = getDataFile(fileName);\n\n if(index.exists() && data.exists()) {\n // We found files with the \"wrong\" replica type, so let's rename them\n\n String correctFileName = Integer.toString(masterPartitionId) + \"_\"\n + Integer.toString(correctReplicaType) + \"_\"\n + Integer.toString(chunkId);\n File indexWithCorrectReplicaType = getIndexFile(correctFileName);\n File dataWithCorrectReplicaType = getDataFile(correctFileName);\n\n Utils.move(index, indexWithCorrectReplicaType);\n Utils.move(data, dataWithCorrectReplicaType);\n\n // Maybe change this to DEBUG?\n logger.info(\"Renamed files with wrong replica type: \"\n + index.getAbsolutePath() + \"|data -> \"\n + indexWithCorrectReplicaType.getName() + \"|data\");\n } else if(index.exists() ^ data.exists()) {\n throw new VoldemortException(\"One of the following does not exist: \"\n + index.toString()\n + \" or \"\n + data.toString() + \".\");\n } else {\n // The files don't exist, or we've gone over all available chunks,\n // so let's move on.\n break;\n }\n chunkId++;\n }\n }\n }\n }"
] | [
"private void readTasks(Document cdp)\n {\n //\n // Sort the projects into the correct order\n //\n List<Project> projects = new ArrayList<Project>(cdp.getProjects().getProject());\n final AlphanumComparator comparator = new AlphanumComparator();\n\n Collections.sort(projects, new Comparator<Project>()\n {\n @Override public int compare(Project o1, Project o2)\n {\n return comparator.compare(o1.getOutlineNumber(), o2.getOutlineNumber());\n }\n });\n\n for (Project project : cdp.getProjects().getProject())\n {\n readProject(project);\n }\n }",
"public static DoubleMatrix absi(DoubleMatrix x) { \n\t\t/*# mapfct('Math.abs') #*/\n//RJPP-BEGIN------------------------------------------------------------\n\t for (int i = 0; i < x.length; i++)\n\t x.put(i, (double) Math.abs(x.get(i)));\n\t return x;\n//RJPP-END--------------------------------------------------------------\n\t}",
"public void rollback()\r\n {\r\n try\r\n {\r\n Iterator iter = mvOrderOfIds.iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n if(log.isDebugEnabled())\r\n log.debug(\"rollback: \" + mod);\r\n // if the Object has been modified by transaction, mark object as dirty\r\n if(mod.hasChanged(transaction.getBroker()))\r\n {\r\n mod.setModificationState(mod.getModificationState().markDirty());\r\n }\r\n mod.getModificationState().rollback(mod);\r\n }\r\n }\r\n finally\r\n {\r\n needsCommit = false;\r\n }\r\n afterWriteCleanup();\r\n }",
"public void removeScript(int id) throws Exception {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, 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 }",
"private void expireDevices() {\n long now = System.currentTimeMillis();\n // Make a copy so we don't have to worry about concurrent modification.\n Map<InetAddress, DeviceAnnouncement> copy = new HashMap<InetAddress, DeviceAnnouncement>(devices);\n for (Map.Entry<InetAddress, DeviceAnnouncement> entry : copy.entrySet()) {\n if (now - entry.getValue().getTimestamp() > MAXIMUM_AGE) {\n devices.remove(entry.getKey());\n deliverLostAnnouncement(entry.getValue());\n }\n }\n if (devices.isEmpty()) {\n firstDeviceTime.set(0); // We have lost contact with the Pro DJ Link network, so start over with next device.\n }\n }",
"public void performStep() {\n // check for zeros\n for( int i = helper.x2-1; i >= helper.x1; i-- ) {\n if( helper.isZero(i) ) {\n helper.splits[helper.numSplits++] = i;\n helper.x1 = i+1;\n return;\n }\n }\n\n double lambda;\n\n if( followingScript ) {\n if( helper.steps > 10 ) {\n followingScript = false;\n return;\n } else {\n // Using the true eigenvalues will in general lead to the fastest convergence\n // typically takes 1 or 2 steps\n lambda = eigenvalues[helper.x2];\n }\n } else {\n // the current eigenvalue isn't working so try something else\n lambda = helper.computeShift();\n }\n\n // similar transforms\n helper.performImplicitSingleStep(lambda,false);\n }",
"private void writeTermStatisticsToFile(UsageStatistics usageStatistics,\n\t\t\tString fileName) {\n\n\t\t// Make sure all keys are present in label count map:\n\t\tfor (String key : usageStatistics.aliasCounts.keySet()) {\n\t\t\tcountKey(usageStatistics.labelCounts, key, 0);\n\t\t}\n\t\tfor (String key : usageStatistics.descriptionCounts.keySet()) {\n\t\t\tcountKey(usageStatistics.labelCounts, key, 0);\n\t\t}\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(fileName))) {\n\n\t\t\tout.println(\"Language,Labels,Descriptions,Aliases\");\n\t\t\tfor (Entry<String, Integer> entry : usageStatistics.labelCounts\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tcountKey(usageStatistics.aliasCounts, entry.getKey(), 0);\n\t\t\t\tint aCount = usageStatistics.aliasCounts.get(entry.getKey());\n\t\t\t\tcountKey(usageStatistics.descriptionCounts, entry.getKey(), 0);\n\t\t\t\tint dCount = usageStatistics.descriptionCounts.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tout.println(entry.getKey() + \",\" + entry.getValue() + \",\"\n\t\t\t\t\t\t+ dCount + \",\" + aCount);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"public void hide() {\n div.removeFromParent();\n if (scrollDisabled) {\n RootPanel.get().getElement().getStyle().setOverflow(Style.Overflow.AUTO);\n }\n if (type == LoaderType.CIRCULAR) {\n preLoader.removeFromParent();\n } else if (type == LoaderType.PROGRESS) {\n progress.removeFromParent();\n }\n }",
"private void verifiedCopyFile(File sourceFile, File destFile) throws IOException {\n if(!destFile.exists()) {\n destFile.createNewFile();\n }\n\n FileInputStream source = null;\n FileOutputStream destination = null;\n LogVerificationInputStream verifyStream = null;\n try {\n source = new FileInputStream(sourceFile);\n destination = new FileOutputStream(destFile);\n verifyStream = new LogVerificationInputStream(env, source, sourceFile.getName());\n\n final byte[] buf = new byte[LOGVERIFY_BUFSIZE];\n\n while(true) {\n final int len = verifyStream.read(buf);\n if(len < 0) {\n break;\n }\n destination.write(buf, 0, len);\n }\n\n } finally {\n if(verifyStream != null) {\n verifyStream.close();\n }\n if(destination != null) {\n destination.close();\n }\n }\n }"
] |
Parse duration represented as an arbitrary fraction of minutes.
@param properties project properties
@param value duration value
@param targetTimeUnit required output time units
@param factor required fraction of a minute
@return Duration instance | [
"private static final Duration parseDurationInFractionsOfMinutes(ProjectProperties properties, Number value, TimeUnit targetTimeUnit, int factor)\n {\n Duration result = null;\n\n if (value != null)\n {\n result = Duration.getInstance(value.intValue() / factor, TimeUnit.MINUTES);\n if (targetTimeUnit != result.getUnits())\n {\n result = result.convertUnits(targetTimeUnit, properties);\n }\n }\n\n return (result);\n }"
] | [
"public static base_responses add(nitro_service client, dnsview resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnsview addresources[] = new dnsview[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnsview();\n\t\t\t\taddresources[i].viewname = resources[i].viewname;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public Object materializeObject(ClassDescriptor cld, Identity oid)\r\n throws PersistenceBrokerException\r\n {\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectByPkStatement(cld);\r\n Object result = null;\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n try\r\n {\r\n stmt = sm.getSelectByPKStatement(cld);\r\n if (stmt == null)\r\n {\r\n logger.error(\"getSelectByPKStatement returned a null statement\");\r\n throw new PersistenceBrokerException(\"getSelectByPKStatement returned a null statement\");\r\n }\r\n /*\r\n arminw: currently a select by PK could never be a stored procedure,\r\n thus we can always set 'false'. Is this correct??\r\n */\r\n sm.bindSelect(stmt, oid, cld, false);\r\n rs = stmt.executeQuery();\r\n // data available read object, else return null\r\n ResultSetAndStatement rs_stmt = new ResultSetAndStatement(broker.serviceStatementManager(), stmt, rs, sql);\r\n if (rs.next())\r\n {\r\n Map row = new HashMap();\r\n cld.getRowReader().readObjectArrayFrom(rs_stmt, row);\r\n result = cld.getRowReader().readObjectFrom(row);\r\n }\r\n // close resources\r\n rs_stmt.close();\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n logger.error(\"PersistenceBrokerException during the execution of materializeObject: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n throw ExceptionHelper.generateException(e, sql.getStatement(), cld, logger, null);\r\n }\r\n return result;\r\n }",
"public ProteusApplication setServerConfigurationFunction(Function<Undertow.Builder, Undertow.Builder> serverConfigurationFunction)\n {\n this.serverConfigurationFunction = serverConfigurationFunction;\n return this;\n }",
"private static void listAssignmentsByResource(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n System.out.println(\"Assignments for resource \" + resource.getName() + \":\");\n\n for (ResourceAssignment assignment : resource.getTaskAssignments())\n {\n Task task = assignment.getTask();\n System.out.println(\" \" + task.getName());\n }\n }\n\n System.out.println();\n }",
"public static base_response update(nitro_service client, Interface resource) throws Exception {\n\t\tInterface updateresource = new Interface();\n\t\tupdateresource.id = resource.id;\n\t\tupdateresource.speed = resource.speed;\n\t\tupdateresource.duplex = resource.duplex;\n\t\tupdateresource.flowctl = resource.flowctl;\n\t\tupdateresource.autoneg = resource.autoneg;\n\t\tupdateresource.hamonitor = resource.hamonitor;\n\t\tupdateresource.tagall = resource.tagall;\n\t\tupdateresource.trunk = resource.trunk;\n\t\tupdateresource.lacpmode = resource.lacpmode;\n\t\tupdateresource.lacpkey = resource.lacpkey;\n\t\tupdateresource.lagtype = resource.lagtype;\n\t\tupdateresource.lacppriority = resource.lacppriority;\n\t\tupdateresource.lacptimeout = resource.lacptimeout;\n\t\tupdateresource.ifalias = resource.ifalias;\n\t\tupdateresource.throughput = resource.throughput;\n\t\tupdateresource.bandwidthhigh = resource.bandwidthhigh;\n\t\tupdateresource.bandwidthnormal = resource.bandwidthnormal;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static final String printBookingType(BookingType value)\n {\n return (Integer.toString(value == null ? BookingType.COMMITTED.getValue() : value.getValue()));\n }",
"public Map<String, String> listConfig(String appName) {\n return connection.execute(new ConfigList(appName), apiKey);\n }",
"public List<EnabledEndpoint> getEnabledEndpoints(int pathId, String clientUUID, String[] filters) throws Exception {\n ArrayList<EnabledEndpoint> enabledOverrides = new ArrayList<EnabledEndpoint>();\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \"=?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \"=?\" +\n \" ORDER BY \" + Constants.ENABLED_OVERRIDES_PRIORITY\n );\n query.setInt(1, pathId);\n query.setString(2, clientUUID);\n results = query.executeQuery();\n\n while (results.next()) {\n EnabledEndpoint endpoint = this.getPartialEnabledEndpointFromResultset(results);\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n\n // this is an errant entry.. perhaps a method got deleted from a plugin\n // we'll also remove it from the endpoint\n if (m == null) {\n PathOverrideService.getInstance().removeOverride(endpoint.getOverrideId());\n continue;\n }\n\n // check filters and see if any match\n boolean addOverride = false;\n if (filters != null) {\n for (String filter : filters) {\n if (m.getMethodType().endsWith(filter)) {\n addOverride = true;\n break;\n }\n }\n } else {\n // if there are no filters then we assume that the requester wants all enabled overrides\n addOverride = true;\n }\n\n if (addOverride) {\n enabledOverrides.add(endpoint);\n }\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 (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n // now go through the ArrayList and get the method for all of the endpoints\n // have to do this so we don't have overlapping SQL queries\n ArrayList<EnabledEndpoint> enabledOverridesWithMethods = new ArrayList<EnabledEndpoint>();\n for (EnabledEndpoint endpoint : enabledOverrides) {\n if (endpoint.getOverrideId() >= 0) {\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n endpoint.setMethodInformation(m);\n }\n enabledOverridesWithMethods.add(endpoint);\n }\n\n return enabledOverridesWithMethods;\n }",
"public boolean nextSplit() {\n if( numSplits == 0 )\n return false;\n x2 = splits[--numSplits];\n if( numSplits > 0 )\n x1 = splits[numSplits-1]+1;\n else\n x1 = 0;\n\n return true;\n }"
] |
Check the given JWT
@param jwtString the JSON Web Token
@return the parsed and verified token or null if token is invalid
@throws ParseException if the token cannot be parsed | [
"public SignedJWT verifyToken(String jwtString) throws ParseException {\n try {\n SignedJWT jwt = SignedJWT.parse(jwtString);\n if (jwt.verify(new MACVerifier(this.jwtSharedSecret))) {\n return jwt;\n }\n return null;\n } catch (JOSEException e) {\n throw new RuntimeException(\"Error verifying JSON Web Token\", e);\n }\n }"
] | [
"public Token add( Symbol symbol ) {\n Token t = new Token(symbol);\n push( t );\n return t;\n }",
"public boolean getCritical()\n {\n Boolean critical = (Boolean) getCachedValue(TaskField.CRITICAL);\n if (critical == null)\n {\n Duration totalSlack = getTotalSlack();\n ProjectProperties props = getParentFile().getProjectProperties();\n int criticalSlackLimit = NumberHelper.getInt(props.getCriticalSlackLimit());\n if (criticalSlackLimit != 0 && totalSlack.getDuration() != 0 && totalSlack.getUnits() != TimeUnit.DAYS)\n {\n totalSlack = totalSlack.convertUnits(TimeUnit.DAYS, props);\n }\n critical = Boolean.valueOf(totalSlack.getDuration() <= criticalSlackLimit && NumberHelper.getInt(getPercentageComplete()) != 100 && ((getTaskMode() == TaskMode.AUTO_SCHEDULED) || (getDurationText() == null && getStartText() == null && getFinishText() == null)));\n set(TaskField.CRITICAL, critical);\n }\n return (BooleanHelper.getBoolean(critical));\n }",
"protected String sourceLine(ASTNode node) {\r\n return sourceCode.getLines().get(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1);\r\n }",
"public static void writeUTF(@NotNull final OutputStream stream, @NotNull final String str) throws IOException {\n try (DataOutputStream dataStream = new DataOutputStream(stream)) {\n int len = str.length();\n if (len < SINGLE_UTF_CHUNK_SIZE) {\n dataStream.writeUTF(str);\n } else {\n int startIndex = 0;\n int endIndex;\n do {\n endIndex = startIndex + SINGLE_UTF_CHUNK_SIZE;\n if (endIndex > len) {\n endIndex = len;\n }\n dataStream.writeUTF(str.substring(startIndex, endIndex));\n startIndex += SINGLE_UTF_CHUNK_SIZE;\n } while (endIndex < len);\n }\n }\n }",
"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 ServerGroup updateServerGroupName(int serverGroupId, String name) {\n ServerGroup serverGroup = null;\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"name\", name),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n try {\n JSONObject response = new JSONObject(doPost(BASE_SERVERGROUP + \"/\" + serverGroupId, params));\n serverGroup = getServerGroupFromJSON(response);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return serverGroup;\n }",
"public static void assertValidNode(MetadataStore metadataStore, Integer nodeId) {\n if(!metadataStore.getCluster().hasNodeWithId(nodeId)) {\n throw new InvalidMetadataException(\"NodeId \" + nodeId + \" is not or no longer in this cluster\");\n }\n }",
"public static dnsview get(nitro_service service, String viewname) throws Exception{\n\t\tdnsview obj = new dnsview();\n\t\tobj.set_viewname(viewname);\n\t\tdnsview response = (dnsview) obj.get_resource(service);\n\t\treturn response;\n\t}",
"@Nullable\n public static LocationEngineResult extractResult(Intent intent) {\n LocationEngineResult result = null;\n if (isOnClasspath(GOOGLE_PLAY_LOCATION_RESULT)) {\n result = extractGooglePlayResult(intent);\n }\n return result == null ? extractAndroidResult(intent) : result;\n }"
] |
Set the given, single header value under the given name.
@param headerName the header name
@param headerValue the header value
@throws UnsupportedOperationException if adding headers is not supported
@see #put(String, List)
@see #add(String, String) | [
"@Override\n\tpublic void set(String headerName, String headerValue) {\n\t\tList<String> headerValues = new LinkedList<String>();\n\t\theaderValues.add(headerValue);\n\t\theaders.put(headerName, headerValues);\n\t}"
] | [
"public QueryBuilder<T, ID> orderByRaw(String rawSql) {\n\t\taddOrderBy(new OrderBy(rawSql, (ArgumentHolder[]) null));\n\t\treturn this;\n\t}",
"static Locale getLocale(PageContext pageContext, String name) {\r\n\r\n Locale loc = null;\r\n\r\n Object obj = javax.servlet.jsp.jstl.core.Config.find(pageContext, name);\r\n if (obj != null) {\r\n if (obj instanceof Locale) {\r\n loc = (Locale)obj;\r\n } else {\r\n loc = SetLocaleSupport.parseLocale((String)obj);\r\n }\r\n }\r\n\r\n return loc;\r\n }",
"private List<MapRow> sort(List<MapRow> rows, final String attribute)\n {\n Collections.sort(rows, new Comparator<MapRow>()\n {\n @Override public int compare(MapRow o1, MapRow o2)\n {\n String value1 = o1.getString(attribute);\n String value2 = o2.getString(attribute);\n return value1.compareTo(value2);\n }\n });\n return rows;\n }",
"protected void handleExceptions(MessageEvent messageEvent, Exception exception) {\n logger.error(\"Unknown exception. Internal Server Error.\", exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n \"Internal Server Error\");\n }",
"public void logout() {\n String userIdentifier = session.get(config().sessionKeyUsername());\n SessionManager sessionManager = app().sessionManager();\n sessionManager.logout(session);\n if (S.notBlank(userIdentifier)) {\n app().eventBus().trigger(new LogoutEvent(userIdentifier));\n }\n }",
"public Path relativize(Path other) {\n\t\tif (other.isAbsolute() != isAbsolute())\n\t\t\tthrow new IllegalArgumentException(\"This path and the given path are not both absolute or both relative: \" + toString() + \" | \" + other.toString());\n\t\tif (startsWith(other)) {\n\t\t\treturn internalRelativize(this, other);\n\t\t} else if (other.startsWith(this)) {\n\t\t\treturn internalRelativize(other, this);\n\t\t}\n\t\treturn null;\n\t}",
"public List<NodeInfo> getNodes() {\n final URI uri = uriWithPath(\"./nodes/\");\n return Arrays.asList(this.rt.getForObject(uri, NodeInfo[].class));\n }",
"public LuaScript endScript(LuaScriptConfig config) {\n if (!endsWithReturnStatement()) {\n add(new LuaAstReturnStatement());\n }\n String scriptText = buildScriptText();\n return new BasicLuaScript(scriptText, config);\n }",
"public OperationTransformerEntry resolveOperationTransformer(final PathAddress address, final String operationName, PlaceholderResolver placeholderResolver) {\n final Iterator<PathElement> iterator = address.iterator();\n final OperationTransformerEntry entry = resolveOperationTransformer(iterator, operationName, placeholderResolver);\n if(entry != null) {\n return entry;\n }\n // Default is forward unchanged\n return FORWARD;\n }"
] |
Allows to access the names of the current defined roundings.
@param providers the providers and ordering to be used. By default providers and ordering as defined in
#getDefaultProviders is used.
@return the set of custom rounding ids, never {@code null}. | [
"public static Set<String> getRoundingNames(String... providers) {\n return Optional.ofNullable(monetaryRoundingsSingletonSpi()).orElseThrow(\n () -> new MonetaryException(\"No MonetaryRoundingsSpi loaded, query functionality is not available.\"))\n .getRoundingNames(providers);\n }"
] | [
"@Override public void setID(Integer val)\n {\n ProjectFile parent = getParentFile();\n Integer previous = getID();\n\n if (previous != null)\n {\n parent.getTasks().unmapID(previous);\n }\n\n parent.getTasks().mapID(val, this);\n\n set(TaskField.ID, val);\n }",
"private void readAssignments(Resource mpxjResource, net.sf.mpxj.phoenix.schema.Project.Storepoints.Storepoint.Resources.Resource res)\n {\n for (Assignment assignment : res.getAssignment())\n {\n readAssignment(mpxjResource, assignment);\n }\n }",
"public static base_response disable(nitro_service client, String trapname) throws Exception {\n\t\tsnmpalarm disableresource = new snmpalarm();\n\t\tdisableresource.trapname = trapname;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}",
"public static float Sum(float[] data) {\r\n float sum = 0;\r\n for (int i = 0; i < data.length; i++) {\r\n sum += data[i];\r\n }\r\n return sum;\r\n }",
"public void setPatternScheme(final boolean isByWeekDay, final boolean fireChange) {\n\n if (isByWeekDay ^ (null != m_model.getWeekDay())) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n if (isByWeekDay) {\n m_model.setWeekOfMonth(getPatternDefaultValues().getWeekOfMonth());\n m_model.setWeekDay(getPatternDefaultValues().getWeekDay());\n } else {\n m_model.clearWeekDays();\n m_model.clearWeeksOfMonth();\n m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth());\n }\n m_model.setInterval(getPatternDefaultValues().getInterval());\n if (fireChange) {\n onValueChange();\n }\n }\n });\n }\n\n }",
"public List<RoutableDestination<T>> getDestinations(String path) {\n\n String cleanPath = (path.endsWith(\"/\") && path.length() > 1)\n ? path.substring(0, path.length() - 1) : path;\n\n List<RoutableDestination<T>> result = new ArrayList<>();\n\n for (ImmutablePair<Pattern, RouteDestinationWithGroups> patternRoute : patternRouteList) {\n Map<String, String> groupNameValuesBuilder = new HashMap<>();\n Matcher matcher = patternRoute.getFirst().matcher(cleanPath);\n if (matcher.matches()) {\n int matchIndex = 1;\n for (String name : patternRoute.getSecond().getGroupNames()) {\n String value = matcher.group(matchIndex);\n groupNameValuesBuilder.put(name, value);\n matchIndex++;\n }\n result.add(new RoutableDestination<>(patternRoute.getSecond().getDestination(), groupNameValuesBuilder));\n }\n }\n return result;\n }",
"public void override(HiveRunnerConfig hiveRunnerConfig) {\n config.putAll(hiveRunnerConfig.config);\n hiveConfSystemOverride.putAll(hiveRunnerConfig.hiveConfSystemOverride);\n }",
"public static Object newInstance(String className) throws InstantiationException,\r\n IllegalAccessException,\r\n ClassNotFoundException\r\n {\r\n return newInstance(getClass(className));\r\n }",
"public static String readCorrelationId(Message message) {\n if (!(message instanceof SoapMessage)) {\n return null;\n }\n String correlationId = null;\n Header hdCorrelationId = ((SoapMessage) message).getHeader(CORRELATION_ID_QNAME);\n if (hdCorrelationId != null) {\n if (hdCorrelationId.getObject() instanceof String) {\n correlationId = (String) hdCorrelationId.getObject();\n } else if (hdCorrelationId.getObject() instanceof Node) {\n Node headerNode = (Node) hdCorrelationId.getObject();\n correlationId = headerNode.getTextContent();\n } else {\n LOG.warning(\"Found CorrelationId soap header but value is not a String or a Node! Value: \"\n + hdCorrelationId.getObject().toString());\n }\n }\n return correlationId;\n }"
] |
Called after creating the first connection. The adapter should create its caches and do all initialization it requires. Most
importantly, the SQL query cache should be created.
@param cnx
an open ready to use connection to the database. | [
"public void prepare(Properties p, Connection cnx)\n {\n this.tablePrefix = p.getProperty(\"com.enioka.jqm.jdbc.tablePrefix\", \"\");\n queries.putAll(DbImplBase.queries);\n for (Map.Entry<String, String> entry : DbImplBase.queries.entrySet())\n {\n queries.put(entry.getKey(), this.adaptSql(entry.getValue()));\n }\n }"
] | [
"public void clearHandlers() {\r\n\r\n for (Map<String, CmsAttributeHandler> handlers : m_handlers) {\r\n for (CmsAttributeHandler handler : handlers.values()) {\r\n handler.clearHandlers();\r\n }\r\n handlers.clear();\r\n }\r\n m_handlers.clear();\r\n m_handlers.add(new HashMap<String, CmsAttributeHandler>());\r\n m_handlerById.clear();\r\n }",
"public static String confSetName() {\n String profile = SysProps.get(AppConfigKey.PROFILE.key());\n if (S.blank(profile)) {\n profile = Act.mode().name().toLowerCase();\n }\n return profile;\n }",
"private void sendEmptyRequest(String path, String method) throws DatastoreEmulatorException {\n HttpURLConnection connection = null;\n try {\n URL url = new URL(this.host + path);\n connection = (HttpURLConnection) url.openConnection();\n connection.setDoOutput(true);\n connection.setRequestMethod(method);\n connection.getOutputStream().close();\n if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {\n throw new DatastoreEmulatorException(\n String.format(\n \"%s request to %s returned HTTP status %s\",\n method, path, connection.getResponseCode()));\n }\n } catch (IOException e) {\n throw new DatastoreEmulatorException(\n String.format(\"Exception connecting to emulator on %s request to %s\", method, path), e);\n } finally {\n if (connection != null) {\n connection.disconnect();\n }\n }\n }",
"public TopicList<Topic> getTopicsList(String groupId, int perPage, int page) throws FlickrException {\r\n TopicList<Topic> topicList = new TopicList<Topic>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_TOPICS_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\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element topicElements = response.getPayload();\r\n topicList.setPage(topicElements.getAttribute(\"page\"));\r\n topicList.setPages(topicElements.getAttribute(\"pages\"));\r\n topicList.setPerPage(topicElements.getAttribute(\"perpage\"));\r\n topicList.setTotal(topicElements.getAttribute(\"total\"));\r\n topicList.setGroupId(topicElements.getAttribute(\"group_id\"));\r\n topicList.setIconServer(Integer.parseInt(topicElements.getAttribute(\"iconserver\")));\r\n topicList.setIconFarm(Integer.parseInt(topicElements.getAttribute(\"iconfarm\")));\r\n topicList.setName(topicElements.getAttribute(\"name\"));\r\n topicList.setMembers(Integer.parseInt(topicElements.getAttribute(\"members\")));\r\n topicList.setPrivacy(Integer.parseInt(topicElements.getAttribute(\"privacy\")));\r\n topicList.setLanguage(topicElements.getAttribute(\"lang\"));\r\n topicList.setIsPoolModerated(\"1\".equals(topicElements.getAttribute(\"ispoolmoderated\")));\r\n\r\n NodeList topicNodes = topicElements.getElementsByTagName(\"topic\");\r\n for (int i = 0; i < topicNodes.getLength(); i++) {\r\n Element element = (Element) topicNodes.item(i);\r\n topicList.add(parseTopic(element));\r\n }\r\n return topicList;\r\n }",
"private static void addProperties(EndpointReferenceType epr, SLProperties props) {\n MetadataType metadata = WSAEndpointReferenceUtils.getSetMetadata(epr);\n ServiceLocatorPropertiesType jaxbProps = SLPropertiesConverter.toServiceLocatorPropertiesType(props);\n\n JAXBElement<ServiceLocatorPropertiesType>\n slp = SL_OBJECT_FACTORY.createServiceLocatorProperties(jaxbProps);\n metadata.getAny().add(slp);\n }",
"@SuppressWarnings(\"resource\")\n public static FileChannel openChannel(File file, boolean mutable) throws IOException {\n if (mutable) {\n return new RandomAccessFile(file, \"rw\").getChannel();\n }\n return new FileInputStream(file).getChannel();\n }",
"public void set(int numRows, int numCols, boolean rowMajor, double ...data)\n {\n reshape(numRows,numCols);\n int length = numRows*numCols;\n\n if( length > this.data.length )\n throw new IllegalArgumentException(\"The length of this matrix's data array is too small.\");\n\n if( rowMajor ) {\n System.arraycopy(data,0,this.data,0,length);\n } else {\n int index = 0;\n for( int i = 0; i < numRows; i++ ) {\n for( int j = 0; j < numCols; j++ ) {\n this.data[index++] = data[j*numRows+i];\n }\n }\n }\n }",
"private static ResourceBundle tryBundle(String baseName, Locale locale, boolean wantBase) {\n\n I_CmsResourceBundle first = null; // The most specialized bundle.\n I_CmsResourceBundle last = null; // The least specialized bundle.\n\n List<String> bundleNames = CmsLocaleManager.getLocaleVariants(baseName, locale, true, true);\n for (String bundleName : bundleNames) {\n // break if we would try the base bundle, but we do not want it directly\n if (bundleName.equals(baseName) && !wantBase && (first == null)) {\n break;\n }\n I_CmsResourceBundle foundBundle = tryBundle(bundleName);\n if (foundBundle != null) {\n if (first == null) {\n first = foundBundle;\n }\n\n if (last != null) {\n last.setParent((ResourceBundle)foundBundle);\n }\n foundBundle.setLocale(locale);\n\n last = foundBundle;\n }\n }\n return (ResourceBundle)first;\n }",
"public static void showChannels(Object... channels){\r\n // TODO this could share more code with the other show/hide(Only)Channels methods\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n for (Object channel : channels) {\r\n visHandler.alsoShow(channel);\r\n }\r\n }\r\n }\r\n }"
] |
Invokes the observer method immediately passing the event.
@param event The event to notify observer with | [
"protected void sendEvent(final T event) {\n if (isStatic) {\n sendEvent(event, null, null);\n } else {\n CreationalContext<X> creationalContext = null;\n try {\n Object receiver = getReceiverIfExists(null);\n if (receiver == null && reception != Reception.IF_EXISTS) {\n // creational context is created only if we need it for obtaining receiver\n // ObserverInvocationStrategy takes care of creating CC for parameters, if needed\n creationalContext = beanManager.createCreationalContext(declaringBean);\n receiver = getReceiverIfExists(creationalContext);\n }\n if (receiver != null) {\n sendEvent(event, receiver, creationalContext);\n }\n } finally {\n if (creationalContext != null) {\n creationalContext.release();\n }\n }\n }\n }"
] | [
"public Map<String, String> getUploadParameters() {\r\n Map<String, String> parameters = new TreeMap<>();\r\n\r\n\r\n String title = getTitle();\r\n if (title != null) {\r\n parameters.put(\"title\", title);\r\n }\r\n\r\n String description = getDescription();\r\n if (description != null) {\r\n parameters.put(\"description\", description);\r\n }\r\n\r\n Collection<String> tags = getTags();\r\n if (tags != null) {\r\n parameters.put(\"tags\", StringUtilities.join(tags, \" \"));\r\n }\r\n\r\n if (isHidden() != null) {\r\n parameters.put(\"hidden\", isHidden().booleanValue() ? \"1\" : \"0\");\r\n }\r\n\r\n if (getSafetyLevel() != null) {\r\n parameters.put(\"safety_level\", getSafetyLevel());\r\n }\r\n\r\n if (getContentType() != null) {\r\n parameters.put(\"content_type\", getContentType());\r\n }\r\n\r\n if (getPhotoId() != null) {\r\n parameters.put(\"photo_id\", getPhotoId());\r\n }\r\n\r\n parameters.put(\"is_public\", isPublicFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_family\", isFamilyFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_friend\", isFriendFlag() ? \"1\" : \"0\");\r\n parameters.put(\"async\", isAsync() ? \"1\" : \"0\");\r\n\r\n return parameters;\r\n }",
"protected List<CRFDatum> extractDatumSequence(int[][][] allData, int beginPosition, int endPosition,\r\n List<IN> labeledWordInfos) {\r\n List<CRFDatum> result = new ArrayList<CRFDatum>();\r\n int beginContext = beginPosition - windowSize + 1;\r\n if (beginContext < 0) {\r\n beginContext = 0;\r\n }\r\n // for the beginning context, add some dummy datums with no features!\r\n // TODO: is there any better way to do this?\r\n for (int position = beginContext; position < beginPosition; position++) {\r\n List<Collection<String>> cliqueFeatures = new ArrayList<Collection<String>>();\r\n for (int i = 0; i < windowSize; i++) {\r\n // create a feature list\r\n cliqueFeatures.add(Collections.<String>emptyList());\r\n }\r\n CRFDatum<Collection<String>, String> datum = new CRFDatum<Collection<String>, String>(cliqueFeatures,\r\n labeledWordInfos.get(position).get(AnswerAnnotation.class));\r\n result.add(datum);\r\n }\r\n // now add the real datums\r\n for (int position = beginPosition; position <= endPosition; position++) {\r\n List<Collection<String>> cliqueFeatures = new ArrayList<Collection<String>>();\r\n for (int i = 0; i < windowSize; i++) {\r\n // create a feature list\r\n Collection<String> features = new ArrayList<String>();\r\n for (int j = 0; j < allData[position][i].length; j++) {\r\n features.add(featureIndex.get(allData[position][i][j]));\r\n }\r\n cliqueFeatures.add(features);\r\n }\r\n CRFDatum<Collection<String>,String> datum = new CRFDatum<Collection<String>,String>(cliqueFeatures,\r\n labeledWordInfos.get(position).get(AnswerAnnotation.class));\r\n result.add(datum);\r\n }\r\n return result;\r\n }",
"public void uploadFields(\n final Set<String> fields,\n final Function<Map<String, String>, Void> filenameCallback,\n final I_CmsErrorCallback errorCallback) {\n\n disableAllFileFieldsExcept(fields);\n final String id = CmsJsUtils.generateRandomId();\n updateFormAction(id);\n // Using an array here because we can only store the handler registration after it has been created , but\n final HandlerRegistration[] registration = {null};\n registration[0] = addSubmitCompleteHandler(new SubmitCompleteHandler() {\n\n @SuppressWarnings(\"synthetic-access\")\n public void onSubmitComplete(SubmitCompleteEvent event) {\n\n enableAllFileFields();\n registration[0].removeHandler();\n CmsUUID sessionId = m_formSession.internalGetSessionId();\n RequestBuilder requestBuilder = CmsXmlContentUgcApi.SERVICE.uploadFiles(\n sessionId,\n fields,\n id,\n new AsyncCallback<Map<String, String>>() {\n\n public void onFailure(Throwable caught) {\n\n m_formSession.getContentFormApi().handleError(caught, errorCallback);\n\n }\n\n public void onSuccess(Map<String, String> fileNames) {\n\n filenameCallback.apply(fileNames);\n\n }\n });\n m_formSession.getContentFormApi().getRpcHelper().executeRpc(requestBuilder);\n m_formSession.getContentFormApi().getRequestCounter().decrement();\n }\n });\n m_formSession.getContentFormApi().getRequestCounter().increment();\n submit();\n }",
"private static MonolingualTextValue toTerm(MonolingualTextValue term) {\n\t\treturn term instanceof TermImpl ? term : new TermImpl(term.getLanguageCode(), term.getText());\n\t}",
"public void setVariable(String name, Iterable<? extends WindupVertexFrame> frames)\n {\n Map<String, Iterable<? extends WindupVertexFrame>> frame = peek();\n if (!Iteration.DEFAULT_VARIABLE_LIST_STRING.equals(name) && findVariable(name) != null)\n {\n throw new IllegalArgumentException(\"Variable \\\"\" + name\n + \"\\\" has already been assigned and cannot be reassigned\");\n }\n\n frame.put(name, frames);\n }",
"public static void checkEigenvalues() {\n DoubleMatrix A = new DoubleMatrix(new double[][]{\n {3.0, 2.0, 0.0},\n {2.0, 3.0, 2.0},\n {0.0, 2.0, 3.0}\n });\n\n DoubleMatrix E = new DoubleMatrix(3, 1);\n\n NativeBlas.dsyev('N', 'U', 3, A.data, 0, 3, E.data, 0);\n check(\"checking existence of dsyev...\", true);\n }",
"private static int resolveDomainTimeoutAdder() {\n String propValue = WildFlySecurityManager.getPropertyPrivileged(DOMAIN_TEST_SYSTEM_PROPERTY, DEFAULT_DOMAIN_TIMEOUT_STRING);\n if (sysPropDomainValue == null || !sysPropDomainValue.equals(propValue)) {\n // First call or the system property changed\n sysPropDomainValue = propValue;\n int number = -1;\n try {\n number = Integer.valueOf(sysPropDomainValue);\n } catch (NumberFormatException nfe) {\n // ignored\n }\n\n if (number > 0) {\n defaultDomainValue = number; // this one is in ms\n } else {\n ControllerLogger.MGMT_OP_LOGGER.invalidDefaultBlockingTimeout(sysPropDomainValue, DOMAIN_TEST_SYSTEM_PROPERTY, DEFAULT_DOMAIN_TIMEOUT_ADDER);\n defaultDomainValue = DEFAULT_DOMAIN_TIMEOUT_ADDER;\n }\n }\n return defaultDomainValue;\n }",
"private static URI createSvg(\n final Dimension targetSize,\n final RasterReference rasterReference, final Double rotation,\n final Color backgroundColor, final File workingDir)\n throws IOException {\n // load SVG graphic\n final SVGElement svgRoot = parseSvg(rasterReference.inputStream);\n\n // create a new SVG graphic in which the existing graphic is embedded (scaled and rotated)\n DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();\n Document newDocument = impl.createDocument(SVG_NS, \"svg\", null);\n SVGElement newSvgRoot = (SVGElement) newDocument.getDocumentElement();\n newSvgRoot.setAttributeNS(null, \"width\", Integer.toString(targetSize.width));\n newSvgRoot.setAttributeNS(null, \"height\", Integer.toString(targetSize.height));\n\n setSvgBackground(backgroundColor, targetSize, newDocument, newSvgRoot);\n embedSvgGraphic(svgRoot, newSvgRoot, newDocument, targetSize, rotation);\n File path = writeSvgToFile(newDocument, workingDir);\n\n return path.toURI();\n }",
"public GVRAnimation setDuration(float start, float end)\n {\n if(start>end || start<0 || end>mDuration){\n throw new IllegalArgumentException(\"start and end values are wrong\");\n }\n animationOffset = start;\n mDuration = end-start;\n return this;\n }"
] |
Provisions a new app user in an enterprise using Box Developer Edition.
@param api the API connection to be used by the created user.
@param name the name of the user.
@return the created user's info. | [
"public static BoxUser.Info createAppUser(BoxAPIConnection api, String name) {\n return createAppUser(api, name, new CreateUserParams());\n }"
] | [
"private void deliverWaveformPreviewUpdate(final int player, final WaveformPreview preview) {\n final Set<WaveformListener> listeners = getWaveformListeners();\n if (!listeners.isEmpty()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n final WaveformPreviewUpdate update = new WaveformPreviewUpdate(player, preview);\n for (final WaveformListener listener : listeners) {\n try {\n listener.previewChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering waveform preview update to listener\", t);\n }\n }\n }\n });\n }\n }",
"public static synchronized void clearDaoCache() {\n\t\tif (classMap != null) {\n\t\t\tclassMap.clear();\n\t\t\tclassMap = null;\n\t\t}\n\t\tif (tableConfigMap != null) {\n\t\t\ttableConfigMap.clear();\n\t\t\ttableConfigMap = null;\n\t\t}\n\t}",
"private String formatPercentage(Number value)\n {\n return (value == null ? null : m_formats.getPercentageDecimalFormat().format(value) + \"%\");\n }",
"public void sendJsonToUser(Object data, String username) {\n sendToUser(JSON.toJSONString(data), username);\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 }",
"private void checkUndefinedNotification(Notification notification) {\n String type = notification.getType();\n PathAddress source = notification.getSource();\n Map<String, NotificationEntry> descriptions = getRootResourceRegistration().getNotificationDescriptions(source, true);\n if (!descriptions.keySet().contains(type)) {\n missingNotificationDescriptionWarnings.add(ControllerLogger.ROOT_LOGGER.notificationIsNotDescribed(type, source));\n }\n }",
"public Set<URI> collectOutgoingReferences(IResourceDescription description) {\n\t\tURI resourceURI = description.getURI();\n\t\tSet<URI> result = null;\n\t\tfor(IReferenceDescription reference: description.getReferenceDescriptions()) {\n\t\t\tURI targetResource = reference.getTargetEObjectUri().trimFragment();\n\t\t\tif (!resourceURI.equals(targetResource)) {\n\t\t\t\tif (result == null)\n\t\t\t\t\tresult = Sets.newHashSet(targetResource);\n\t\t\t\telse\n\t\t\t\t\tresult.add(targetResource);\n\t\t\t}\n\t\t}\n\t\tif (result != null)\n\t\t\treturn result;\n\t\treturn Collections.emptySet();\n\t}",
"public static String wordShape(String inStr, int wordShaper, Collection<String> knownLCWords) {\r\n // this first bit is for backwards compatibility with how things were first\r\n // implemented, where the word shaper name encodes whether to useLC.\r\n // If the shaper is in the old compatibility list, then a specified\r\n // list of knownLCwords is ignored\r\n if (knownLCWords != null && dontUseLC(wordShaper)) {\r\n knownLCWords = null;\r\n }\r\n switch (wordShaper) {\r\n case NOWORDSHAPE:\r\n return inStr;\r\n case WORDSHAPEDAN1:\r\n return wordShapeDan1(inStr);\r\n case WORDSHAPECHRIS1:\r\n return wordShapeChris1(inStr);\r\n case WORDSHAPEDAN2:\r\n return wordShapeDan2(inStr, knownLCWords);\r\n case WORDSHAPEDAN2USELC:\r\n return wordShapeDan2(inStr, knownLCWords);\r\n case WORDSHAPEDAN2BIO:\r\n return wordShapeDan2Bio(inStr, knownLCWords);\r\n case WORDSHAPEDAN2BIOUSELC:\r\n return wordShapeDan2Bio(inStr, knownLCWords);\r\n case WORDSHAPEJENNY1:\r\n return wordShapeJenny1(inStr, knownLCWords);\r\n case WORDSHAPEJENNY1USELC:\r\n return wordShapeJenny1(inStr, knownLCWords);\r\n case WORDSHAPECHRIS2:\r\n return wordShapeChris2(inStr, false, knownLCWords);\r\n case WORDSHAPECHRIS2USELC:\r\n return wordShapeChris2(inStr, false, knownLCWords);\r\n case WORDSHAPECHRIS3:\r\n return wordShapeChris2(inStr, true, knownLCWords);\r\n case WORDSHAPECHRIS3USELC:\r\n return wordShapeChris2(inStr, true, knownLCWords);\r\n case WORDSHAPECHRIS4:\r\n return wordShapeChris4(inStr, false, knownLCWords);\r\n case WORDSHAPEDIGITS:\r\n return wordShapeDigits(inStr);\r\n default:\r\n throw new IllegalStateException(\"Bad WordShapeClassifier\");\r\n }\r\n }",
"void close(Supplier<CentralDogmaException> failureCauseSupplier) {\n requireNonNull(failureCauseSupplier, \"failureCauseSupplier\");\n if (closePending.compareAndSet(null, failureCauseSupplier)) {\n repositoryWorker.execute(() -> {\n rwLock.writeLock().lock();\n try {\n if (commitIdDatabase != null) {\n try {\n commitIdDatabase.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a commitId database:\", e);\n }\n }\n\n if (jGitRepository != null) {\n try {\n jGitRepository.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a Git repository: {}\",\n jGitRepository.getDirectory(), e);\n }\n }\n } finally {\n rwLock.writeLock().unlock();\n commitWatchers.close(failureCauseSupplier);\n closeFuture.complete(null);\n }\n });\n }\n\n closeFuture.join();\n }"
] |
Notification that the server process finished. | [
"synchronized void processFinished() {\n final InternalState required = this.requiredState;\n final InternalState state = this.internalState;\n // If the server was not stopped\n if(required == InternalState.STOPPED && state == InternalState.PROCESS_STOPPING) {\n finishTransition(InternalState.PROCESS_STOPPING, InternalState.PROCESS_STOPPED);\n } else {\n this.requiredState = InternalState.STOPPED;\n if ( !(internalSetState(getTransitionTask(InternalState.PROCESS_STOPPING), internalState, InternalState.PROCESS_STOPPING)\n && internalSetState(getTransitionTask(InternalState.PROCESS_REMOVING), internalState, InternalState.PROCESS_REMOVING)\n && internalSetState(getTransitionTask(InternalState.STOPPED), internalState, InternalState.STOPPED)) ){\n this.requiredState = InternalState.FAILED;\n internalSetState(null, internalState, InternalState.PROCESS_STOPPED);\n }\n }\n }"
] | [
"public static DiscountCurve createDiscountCurveFromDiscountFactors(String name, double[] times, double[] givenDiscountFactors) {\n\t\tDiscountCurve discountFactors = new DiscountCurve(name);\n\n\t\tfor(int timeIndex=0; timeIndex<times.length;timeIndex++) {\n\t\t\tdiscountFactors.addDiscountFactor(times[timeIndex], givenDiscountFactors[timeIndex], times[timeIndex] > 0);\n\t\t}\n\n\t\treturn discountFactors;\n\t}",
"private void updateHostingEntityIfRequired() {\n\t\tif ( hostingEntity != null && hostingEntityRequiresReadAfterUpdate() ) {\n\t\t\tOgmEntityPersister entityPersister = getHostingEntityPersister();\n\n\t\t\tif ( GridDialects.hasFacet( gridDialect, GroupingByEntityDialect.class ) ) {\n\t\t\t\t( (GroupingByEntityDialect) gridDialect ).flushPendingOperations( getAssociationKey().getEntityKey(),\n\t\t\t\t\t\tentityPersister.getTupleContext( session ) );\n\t\t\t}\n\n\t\t\tentityPersister.processUpdateGeneratedProperties(\n\t\t\t\t\tentityPersister.getIdentifier( hostingEntity, session ),\n\t\t\t\t\thostingEntity,\n\t\t\t\t\tnew Object[entityPersister.getPropertyNames().length],\n\t\t\t\t\tsession\n\t\t\t);\n\t\t}\n\t}",
"public static appflowglobal_binding get(nitro_service service) throws Exception{\n\t\tappflowglobal_binding obj = new appflowglobal_binding();\n\t\tappflowglobal_binding response = (appflowglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static String getAt(CharSequence self, Collection indices) {\n StringBuilder answer = new StringBuilder();\n for (Object value : indices) {\n if (value instanceof Range) {\n answer.append(getAt(self, (Range) value));\n } else if (value instanceof Collection) {\n answer.append(getAt(self, (Collection) value));\n } else {\n int idx = DefaultTypeTransformation.intUnbox(value);\n answer.append(getAt(self, idx));\n }\n }\n return answer.toString();\n }",
"public static base_responses update(nitro_service client, bridgetable resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tbridgetable updateresources[] = new bridgetable[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new bridgetable();\n\t\t\t\tupdateresources[i].bridgeage = resources[i].bridgeage;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public void setManyToOneAttribute(String name, AssociationValue value) {\n\t\tensureAttributes();\n\t\tAttribute attribute = new ManyToOneAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetAllAttributes().put(name, attribute);\n\n\t}",
"private void stereotype(Options opt, Doc c, Align align) {\n\tfor (Tag tag : c.tags(\"stereotype\")) {\n\t String t[] = tokenize(tag.text());\n\t if (t.length != 1) {\n\t\tSystem.err.println(\"@stereotype expects one field: \" + tag.text());\n\t\tcontinue;\n\t }\n\t tableLine(align, guilWrap(opt, t[0]));\n\t}\n }",
"public static final double getDouble(String value)\n {\n return (value == null || value.length() == 0 ? 0 : Double.parseDouble(value));\n }",
"public GVRAnimator animate(int animIndex, float timeInSec)\n {\n if ((animIndex < 0) || (animIndex >= mAnimations.size()))\n {\n throw new IndexOutOfBoundsException(\"Animation index out of bounds\");\n }\n GVRAnimator anim = mAnimations.get(animIndex);\n anim.animate(timeInSec);\n return anim;\n }"
] |
Installs a path service.
@param name the name to use for the service
@param path the relative portion of the path
@param possiblyAbsolute {@code true} if {@code path} may be an {@link #isAbsoluteUnixOrWindowsPath(String) absolute path}
and should be {@link AbsolutePathService installed as such} if it is, with any
{@code relativeTo} parameter ignored
@param relativeTo the name of the path that {@code path} may be relative to
@param serviceTarget the {@link ServiceTarget} to use to install the service
@return the ServiceController for the path service | [
"public static ServiceController<String> addService(final ServiceName name, final String path,\n boolean possiblyAbsolute, final String relativeTo, final ServiceTarget serviceTarget) {\n\n if (possiblyAbsolute && isAbsoluteUnixOrWindowsPath(path)) {\n return AbsolutePathService.addService(name, path, serviceTarget);\n }\n\n RelativePathService service = new RelativePathService(path);\n ServiceBuilder<String> builder = serviceTarget.addService(name, service)\n .addDependency(pathNameOf(relativeTo), String.class, service.injectedPath);\n ServiceController<String> svc = builder.install();\n return svc;\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}",
"static ChangeEvent<BsonDocument> changeEventForLocalInsert(\n final MongoNamespace namespace,\n final BsonDocument document,\n final boolean writePending\n ) {\n final BsonValue docId = BsonUtils.getDocumentId(document);\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.INSERT,\n document,\n namespace,\n new BsonDocument(\"_id\", docId),\n null,\n writePending);\n }",
"public GVRAnimation setOnFinish(GVROnFinish callback) {\n mOnFinish = callback;\n\n // Do the instance-of test at set-time, not at use-time\n mOnRepeat = callback instanceof GVROnRepeat ? (GVROnRepeat) callback\n : null;\n if (mOnRepeat != null) {\n mRepeatCount = -1; // loop until iterate() returns false\n }\n return this;\n }",
"public BoxFolder.Info getFolderInfo(String folderID, String... fields) {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", fields).toString();\n URL url = FOLDER_INFO_URL_TEMPLATE.buildWithQuery(this.api.getBaseURL(), queryString, folderID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFolder folder = new BoxFolder(this.api, jsonObject.get(\"id\").asString());\n return folder.new Info(response.getJSON());\n }",
"public void open(File versionDir) {\n /* acquire modification lock */\n fileModificationLock.writeLock().lock();\n try {\n /* check that the store is currently closed */\n if(isOpen)\n throw new IllegalStateException(\"Attempt to open already open store.\");\n\n // Find version directory from symbolic link or max version id\n if(versionDir == null) {\n versionDir = ReadOnlyUtils.getCurrentVersion(storeDir);\n\n if(versionDir == null)\n versionDir = new File(storeDir, \"version-0\");\n }\n\n // Set the max version id\n long versionId = ReadOnlyUtils.getVersionId(versionDir);\n if(versionId == -1) {\n throw new VoldemortException(\"Unable to parse id from version directory \"\n + versionDir.getAbsolutePath());\n }\n Utils.mkdirs(versionDir);\n\n // Validate symbolic link, and create it if it doesn't already exist\n Utils.symlink(versionDir.getAbsolutePath(), storeDir.getAbsolutePath() + File.separator + \"latest\");\n this.fileSet = new ChunkedFileSet(versionDir, routingStrategy, nodeId, maxValueBufferAllocationSize);\n storeVersionManager.syncInternalStateFromFileSystem(false);\n this.lastSwapped = System.currentTimeMillis();\n this.isOpen = true;\n } catch(IOException e) {\n logger.error(\"Error in opening store\", e);\n } finally {\n fileModificationLock.writeLock().unlock();\n }\n }",
"protected void refresh()\r\n {\r\n if (log.isDebugEnabled())\r\n log.debug(\"Refresh this transaction for reuse: \" + this);\r\n try\r\n {\r\n // we reuse ObjectEnvelopeTable instance\r\n objectEnvelopeTable.refresh();\r\n }\r\n catch (Exception e)\r\n {\r\n if (log.isDebugEnabled())\r\n {\r\n log.debug(\"error closing object envelope table : \" + e.getMessage());\r\n e.printStackTrace();\r\n }\r\n }\r\n cleanupBroker();\r\n // clear the temporary used named roots map\r\n // we should do that, because same tx instance\r\n // could be used several times\r\n broker = null;\r\n clearRegistrationList();\r\n unmaterializedLocks.clear();\r\n txStatus = Status.STATUS_NO_TRANSACTION;\r\n }",
"public static CmsPair<String, Map<String, String>> parseEmbeddedGalleryOptions(String configuration) {\n\n final Map<String, String> galleryOptions = Maps.newHashMap();\n String resultConfig = CmsStringUtil.substitute(\n PATTERN_EMBEDDED_GALLERY_CONFIG,\n configuration,\n new I_CmsRegexSubstitution() {\n\n public String substituteMatch(String string, Matcher matcher) {\n\n String galleryName = string.substring(matcher.start(1), matcher.end(1));\n String embeddedConfig = string.substring(matcher.start(2), matcher.end(2));\n galleryOptions.put(galleryName, embeddedConfig);\n return galleryName;\n }\n });\n return CmsPair.create(resultConfig, galleryOptions);\n }",
"public static Duration getVariance(Task task, Date date1, Date date2, TimeUnit format)\n {\n Duration variance = null;\n\n if (date1 != null && date2 != null)\n {\n ProjectCalendar calendar = task.getEffectiveCalendar();\n if (calendar != null)\n {\n variance = calendar.getWork(date1, date2, format);\n }\n }\n\n if (variance == null)\n {\n variance = Duration.getInstance(0, format);\n }\n\n return (variance);\n }",
"private String filterTag(String tag) {\r\n\t AttributeValues answerAV = TagSet.getTagSet().fromTag(tag);\r\n\t answerAV.removeNonlexicalAttributes();\r\n\t return TagSet.getTagSet().toTag(answerAV);\r\n }"
] |
Provides the scrollableList implementation for page scrolling
@return {@link LayoutScroller.ScrollableList} implementation, passed to {@link LayoutScroller}
for the processing the scrolling | [
"public LayoutScroller.ScrollableList getPageScrollable() {\n return new LayoutScroller.ScrollableList() {\n\n @Override\n public int getScrollingItemsCount() {\n return MultiPageWidget.super.getScrollingItemsCount();\n }\n\n @Override\n public float getViewPortWidth() {\n return MultiPageWidget.super.getViewPortWidth();\n }\n\n @Override\n public float getViewPortHeight() {\n return MultiPageWidget.super.getViewPortHeight();\n }\n\n @Override\n public float getViewPortDepth() {\n return MultiPageWidget.super.getViewPortDepth();\n }\n\n @Override\n public boolean scrollToPosition(int pos, final LayoutScroller.OnScrollListener listener) {\n return MultiPageWidget.super.scrollToPosition(pos, listener);\n }\n\n @Override\n public boolean scrollByOffset(float xOffset, float yOffset, float zOffset,\n final LayoutScroller.OnScrollListener listener) {\n return MultiPageWidget.super.scrollByOffset(xOffset, yOffset, zOffset, listener);\n }\n\n @Override\n public void registerDataSetObserver(DataSetObserver observer) {\n MultiPageWidget.super.registerDataSetObserver(observer);\n }\n\n @Override\n public void unregisterDataSetObserver(DataSetObserver observer) {\n MultiPageWidget.super.unregisterDataSetObserver(observer);\n }\n\n @Override\n public int getCurrentPosition() {\n return MultiPageWidget.super.getCurrentPosition();\n }\n\n };\n }"
] | [
"public Metadata getMetadata(String templateName) {\n String scope = Metadata.scopeBasedOnType(templateName);\n return this.getMetadata(templateName, scope);\n }",
"public static lbmonitor_binding[] get(nitro_service service, String monitorname[]) throws Exception{\n\t\tif (monitorname !=null && monitorname.length>0) {\n\t\t\tlbmonitor_binding response[] = new lbmonitor_binding[monitorname.length];\n\t\t\tlbmonitor_binding obj[] = new lbmonitor_binding[monitorname.length];\n\t\t\tfor (int i=0;i<monitorname.length;i++) {\n\t\t\t\tobj[i] = new lbmonitor_binding();\n\t\t\t\tobj[i].set_monitorname(monitorname[i]);\n\t\t\t\tresponse[i] = (lbmonitor_binding) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"private String formatDateTimeNull(Date value)\n {\n return (value == null ? m_formats.getNullText() : m_formats.getDateTimeFormat().format(value));\n }",
"public static String renderJson(Object o) {\n\n Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting()\n .create();\n return gson.toJson(o);\n }",
"public static sslcertkey_sslocspresponder_binding[] get(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_sslocspresponder_binding obj = new sslcertkey_sslocspresponder_binding();\n\t\tobj.set_certkey(certkey);\n\t\tsslcertkey_sslocspresponder_binding response[] = (sslcertkey_sslocspresponder_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static boolean isPackageOrClassName(String s) {\n if (S.blank(s)) {\n return false;\n }\n S.List parts = S.fastSplit(s, \".\");\n if (parts.size() < 2) {\n return false;\n }\n for (String part: parts) {\n if (!Character.isJavaIdentifierStart(part.charAt(0))) {\n return false;\n }\n for (int i = 1, len = part.length(); i < len; ++i) {\n if (!Character.isJavaIdentifierPart(part.charAt(i))) {\n return false;\n }\n }\n }\n return true;\n }",
"public static String keyVersionToString(ByteArray key,\n Map<Value, Set<ClusterNode>> versionMap,\n String storeName,\n Integer partitionId) {\n StringBuilder record = new StringBuilder();\n for (Map.Entry<Value, Set<ClusterNode>> versionSet : versionMap.entrySet()) {\n Value value = versionSet.getKey();\n Set<ClusterNode> nodeSet = versionSet.getValue();\n\n record.append(\"BAD_KEY,\");\n record.append(storeName + \",\");\n record.append(partitionId + \",\");\n record.append(ByteUtils.toHexString(key.get()) + \",\");\n record.append(nodeSet.toString().replace(\", \", \";\") + \",\");\n record.append(value.toString());\n }\n return record.toString();\n }",
"public static Authentication build(String crypt) throws IllegalArgumentException {\n if(crypt == null) {\n return new PlainAuth(null);\n }\n String[] value = crypt.split(\":\");\n \n if(value.length == 2 ) {\n String type = value[0].trim();\n String password = value[1].trim();\n if(password!=null&&password.length()>0) {\n if(\"plain\".equals(type)) {\n return new PlainAuth(password);\n }\n if(\"md5\".equals(type)) {\n return new Md5Auth(password);\n }\n if(\"crc32\".equals(type)) {\n return new Crc32Auth(Long.parseLong(password));\n }\n }\n }\n throw new IllegalArgumentException(\"error password: \"+crypt);\n }",
"@VisibleForTesting\n protected static int getBarSize(final ScaleBarRenderSettings settings) {\n if (settings.getParams().barSize != null) {\n return settings.getParams().barSize;\n } else {\n if (settings.getParams().getOrientation().isHorizontal()) {\n return settings.getMaxSize().height / 4;\n } else {\n return settings.getMaxSize().width / 4;\n }\n }\n }"
] |
end class SAXErrorHandler | [
"public static Document readDocumentFromString(String s) throws Exception {\r\n InputSource in = new InputSource(new StringReader(s));\r\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r\n factory.setNamespaceAware(false);\r\n return factory.newDocumentBuilder().parse(in);\r\n }"
] | [
"public void disableAllOverrides(int pathID, String clientUUID, int overrideType) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n ArrayList<Integer> enabledOverrides = new ArrayList<Integer>();\n enabledOverrides.add(Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_ADD);\n enabledOverrides.add(Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_REMOVE);\n enabledOverrides.add(Constants.PLUGIN_REQUEST_OVERRIDE_CUSTOM);\n enabledOverrides.add(Constants.PLUGIN_REQUEST_OVERRIDE_CUSTOM_POST_BODY);\n\n String overridePlaceholders = preparePlaceHolders(enabledOverrides.size());\n\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ? \" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \" = ? \" +\n \" AND \" + Constants.ENABLED_OVERRIDES_OVERRIDE_ID +\n (overrideType == Constants.OVERRIDE_TYPE_RESPONSE ? \" NOT\" : \"\") +\n \" IN ( \" + overridePlaceholders + \" )\"\n );\n statement.setInt(1, pathID);\n statement.setString(2, clientUUID);\n for (int i = 3; i <= enabledOverrides.size() + 2; ++i) {\n statement.setInt(i, enabledOverrides.get(i - 3));\n }\n statement.execute();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"public static int getChunkId(String fileName) {\n Pattern pattern = Pattern.compile(\"_[\\\\d]+\\\\.\");\n Matcher matcher = pattern.matcher(fileName);\n\n if(matcher.find()) {\n return new Integer(fileName.substring(matcher.start() + 1, matcher.end() - 1));\n } else {\n throw new VoldemortException(\"Could not extract out chunk id from \" + fileName);\n }\n }",
"public static String getTokenText(INode node) {\n\t\tif (node instanceof ILeafNode)\n\t\t\treturn ((ILeafNode) node).getText();\n\t\telse {\n\t\t\tStringBuilder builder = new StringBuilder(Math.max(node.getTotalLength(), 1));\n\t\t\tboolean hiddenSeen = false;\n\t\t\tfor (ILeafNode leaf : node.getLeafNodes()) {\n\t\t\t\tif (!leaf.isHidden()) {\n\t\t\t\t\tif (hiddenSeen && builder.length() > 0)\n\t\t\t\t\t\tbuilder.append(' ');\n\t\t\t\t\tbuilder.append(leaf.getText());\n\t\t\t\t\thiddenSeen = false;\n\t\t\t\t} else {\n\t\t\t\t\thiddenSeen = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn builder.toString();\n\t\t}\n\t}",
"public void scale(double v){\n\t\tfor(int i = 0; i < this.size(); i++){\n\t\t\tthis.get(i).scale(v);;\n\t\t}\n\t}",
"public static List<String> getLayersDigests(String manifestContent) throws IOException {\n List<String> dockerLayersDependencies = new ArrayList<String>();\n\n JsonNode manifest = Utils.mapper().readTree(manifestContent);\n JsonNode schemaVersion = manifest.get(\"schemaVersion\");\n if (schemaVersion == null) {\n throw new IllegalStateException(\"Could not find 'schemaVersion' in manifest\");\n }\n\n boolean isSchemeVersion1 = schemaVersion.asInt() == 1;\n JsonNode fsLayers = getFsLayers(manifest, isSchemeVersion1);\n for (JsonNode fsLayer : fsLayers) {\n JsonNode blobSum = getBlobSum(isSchemeVersion1, fsLayer);\n dockerLayersDependencies.add(blobSum.asText());\n }\n dockerLayersDependencies.add(getConfigDigest(manifestContent));\n\n //Add manifest sha1\n String manifestSha1 = Hashing.sha1().hashString(manifestContent, Charsets.UTF_8).toString();\n dockerLayersDependencies.add(\"sha1:\" + manifestSha1);\n\n return dockerLayersDependencies;\n }",
"public ProjectCalendarWeek getWorkWeek(Date date)\n {\n ProjectCalendarWeek week = null;\n if (!m_workWeeks.isEmpty())\n {\n sortWorkWeeks();\n\n int low = 0;\n int high = m_workWeeks.size() - 1;\n long targetDate = date.getTime();\n\n while (low <= high)\n {\n int mid = (low + high) >>> 1;\n ProjectCalendarWeek midVal = m_workWeeks.get(mid);\n int cmp = 0 - DateHelper.compare(midVal.getDateRange().getStart(), midVal.getDateRange().getEnd(), targetDate);\n\n if (cmp < 0)\n {\n low = mid + 1;\n }\n else\n {\n if (cmp > 0)\n {\n high = mid - 1;\n }\n else\n {\n week = midVal;\n break;\n }\n }\n }\n }\n\n if (week == null && getParent() != null)\n {\n // Check base calendar as well for a work week.\n week = getParent().getWorkWeek(date);\n }\n return (week);\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 }",
"private String formatConstraintType(ConstraintType type)\n {\n return (type == null ? null : LocaleData.getStringArray(m_locale, LocaleData.CONSTRAINT_TYPES)[type.getValue()]);\n }",
"private void distributedProcessFinish(ResponseBuilder rb,\n ComponentFields mtasFields) throws IOException {\n // rewrite\n\n Object mtasResponseRaw;\n if ((mtasResponseRaw = rb.rsp.getValues().get(\"mtas\")) != null\n && mtasResponseRaw instanceof NamedList) {\n NamedList<Object> mtasResponse = (NamedList<Object>) mtasResponseRaw;\n Object mtasResponseTermvectorRaw;\n if ((mtasResponseTermvectorRaw = mtasResponse.get(NAME)) != null\n && mtasResponseTermvectorRaw instanceof ArrayList) {\n MtasSolrResultUtil.rewrite(\n (ArrayList<Object>) mtasResponseTermvectorRaw, searchComponent);\n }\n }\n }"
] |
Executes the API action "wbsearchentity" for the given parameters.
Searches for entities using labels and aliases. Returns a label and
description for the entity in the user language if possible. Returns
details of the matched term. The matched term text is also present in the
aliases key if different from the display label.
<p>
See the <a href=
"https://www.wikidata.org/w/api.php?action=help&modules=wbsearchentity"
>online API documentation</a> for further information.
<p>
@param search
(required) search for this text
@param language
(required) search in this language
@param strictLanguage
(optional) whether to disable language fallback
@param type
(optional) search for this type of entity
One of the following values: item, property
Default: item
@param limit
(optional) maximal number of results
no more than 50 (500 for bots) allowed
Default: 7
@param offset
(optional) offset where to continue a search
Default: 0
this parameter is called "continue" in the API (which is a Java keyword)
@return list of matching entities retrieved via the API URL
@throws MediaWikiApiErrorException
if the API returns an error
@throws IllegalArgumentException
if the given combination of parameters does not make sense | [
"public List<WbSearchEntitiesResult> wbSearchEntities(String search, String language,\n Boolean strictLanguage, String type, Long limit, Long offset)\n throws MediaWikiApiErrorException {\n\n Map<String, String> parameters = new HashMap<String, String>();\n parameters.put(ApiConnection.PARAM_ACTION, \"wbsearchentities\");\n\n if (search != null) {\n parameters.put(\"search\", search);\n } else {\n throw new IllegalArgumentException(\n \"Search parameter must be specified for this action.\");\n }\n\n if (language != null) {\n parameters.put(\"language\", language);\n } else {\n throw new IllegalArgumentException(\n \"Language parameter must be specified for this action.\");\n }\n if (strictLanguage != null) {\n parameters.put(\"strictlanguage\", Boolean.toString(strictLanguage));\n }\n\n if (type != null) {\n parameters.put(\"type\", type);\n }\n\n if (limit != null) {\n parameters.put(\"limit\", Long.toString(limit));\n }\n\n if (offset != null) {\n parameters.put(\"continue\", Long.toString(offset));\n }\n\n List<WbSearchEntitiesResult> results = new ArrayList<>();\n\n try {\n JsonNode root = this.connection.sendJsonRequest(\"POST\", parameters);\n JsonNode entities = root.path(\"search\");\n for (JsonNode entityNode : entities) {\n try {\n JacksonWbSearchEntitiesResult ed = mapper.treeToValue(entityNode,\n JacksonWbSearchEntitiesResult.class);\n results.add(ed);\n } catch (JsonProcessingException e) {\n LOGGER.error(\"Error when reading JSON for entity \"\n + entityNode.path(\"id\").asText(\"UNKNOWN\") + \": \"\n + e.toString());\n }\n }\n } catch (IOException e) {\n LOGGER.error(\"Could not retrive data: \" + e.toString());\n }\n\n return results;\n }"
] | [
"protected void processLink(Row row)\n {\n Task predecessorTask = m_project.getTaskByUniqueID(row.getInteger(\"LINK_PRED_UID\"));\n Task successorTask = m_project.getTaskByUniqueID(row.getInteger(\"LINK_SUCC_UID\"));\n if (predecessorTask != null && successorTask != null)\n {\n RelationType type = RelationType.getInstance(row.getInt(\"LINK_TYPE\"));\n TimeUnit durationUnits = MPDUtility.getDurationTimeUnits(row.getInt(\"LINK_LAG_FMT\"));\n Duration duration = MPDUtility.getDuration(row.getDouble(\"LINK_LAG\").doubleValue(), durationUnits);\n Relation relation = successorTask.addPredecessor(predecessorTask, type, duration);\n relation.setUniqueID(row.getInteger(\"LINK_UID\"));\n m_eventManager.fireRelationReadEvent(relation);\n }\n }",
"private void setPropertyFilters(String filters) {\n\t\tthis.filterProperties = new HashSet<>();\n\t\tif (!\"-\".equals(filters)) {\n\t\t\tfor (String pid : filters.split(\",\")) {\n\t\t\t\tthis.filterProperties.add(Datamodel\n\t\t\t\t\t\t.makeWikidataPropertyIdValue(pid));\n\t\t\t}\n\t\t}\n\t}",
"@Override\n public DMatrixRMaj getA() {\n if( A.data.length < numRows*numCols ) {\n A = new DMatrixRMaj(numRows,numCols);\n }\n A.reshape(numRows,numCols, false);\n CommonOps_DDRM.mult(Q,R,A);\n\n return A;\n }",
"public FindByIndexOptions useIndex(String designDocument, String indexName) {\r\n assertNotNull(designDocument, \"designDocument\");\r\n assertNotNull(indexName, \"indexName\");\r\n JsonArray index = new JsonArray();\r\n index.add(new JsonPrimitive(designDocument));\r\n index.add(new JsonPrimitive(indexName));\r\n this.useIndex = index;\r\n return this;\r\n }",
"public Future<String> sendRequest(final String path, final ReportingHandler reportingHandler) {\r\n return threadPool.submit(new Callable<String>() {\r\n @Override\r\n public String call() {\r\n String response = getResponse(path);\n\r\n if (reportingHandler != null) {\r\n reportingHandler.handleResponse(response);\r\n }\n\r\n return response;\r\n }\r\n });\r\n }",
"public static void touch(final File folder , final String fileName) throws IOException {\n if(!folder.exists()){\n folder.mkdirs();\n }\n\n final File touchedFile = new File(folder, fileName);\n\n // The JVM will only 'touch' the file if you instantiate a\n // FileOutputStream instance for the file in question.\n // You don't actually write any data to the file through\n // the FileOutputStream. Just instantiate it and close it.\n\n try (\n FileOutputStream doneFOS = new FileOutputStream(touchedFile);\n ) {\n // Touching the file\n }\n catch (FileNotFoundException e) {\n throw new FileNotFoundException(\"Failed to the find file.\" + e);\n }\n }",
"public boolean detectBlackBerryHigh() {\r\n\r\n //Disambiguate for BlackBerry OS 6 or 7 (WebKit) browser\r\n if (detectBlackBerryWebKit()) {\r\n return false;\r\n }\r\n if (detectBlackBerry()) {\r\n if (detectBlackBerryTouch()\r\n || (userAgent.indexOf(deviceBBBold) != -1)\r\n || (userAgent.indexOf(deviceBBTour) != -1)\r\n || (userAgent.indexOf(deviceBBCurve) != -1)) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n } else {\r\n return false;\r\n }\r\n }",
"private static QName getServiceName(Server server) {\n QName serviceName;\n String bindingId = getBindingId(server);\n EndpointInfo eInfo = server.getEndpoint().getEndpointInfo();\n \n if (JAXRS_BINDING_ID.equals(bindingId)) {\n serviceName = eInfo.getName();\n } else {\n ServiceInfo serviceInfo = eInfo.getService();\n serviceName = serviceInfo.getName();\n }\n return serviceName;\n }",
"void buildControl(BinaryPackageControlFile packageControlFile, File[] controlFiles, List<String> conffiles, StringBuilder checksums, File output) throws IOException, ParseException {\n final File dir = output.getParentFile();\n if (dir != null && (!dir.exists() || !dir.isDirectory())) {\n throw new IOException(\"Cannot write control file at '\" + output.getAbsolutePath() + \"'\");\n }\n\n final TarArchiveOutputStream outputStream = new TarArchiveOutputStream(new GZIPOutputStream(new FileOutputStream(output)));\n outputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);\n\n boolean foundConffiles = false;\n\n // create the final package control file out of the \"control\" file, copy all other files, ignore the directories\n for (File file : controlFiles) {\n if (file.isDirectory()) {\n // warn about the misplaced directory, except for directories ignored by default (.svn, cvs, etc)\n if (!isDefaultExcludes(file)) {\n console.warn(\"Found directory '\" + file + \"' in the control directory. Maybe you are pointing to wrong dir?\");\n }\n continue;\n }\n\n if (\"conffiles\".equals(file.getName())) {\n foundConffiles = true;\n }\n\n if (CONFIGURATION_FILENAMES.contains(file.getName()) || MAINTAINER_SCRIPTS.contains(file.getName())) {\n FilteredFile configurationFile = new FilteredFile(new FileInputStream(file), resolver);\n configurationFile.setOpenToken(openReplaceToken);\n configurationFile.setCloseToken(closeReplaceToken);\n addControlEntry(file.getName(), configurationFile.toString(), outputStream);\n\n } else if (!\"control\".equals(file.getName())) {\n // initialize the information stream to guess the type of the file\n InformationInputStream infoStream = new InformationInputStream(new FileInputStream(file));\n Utils.copy(infoStream, NullOutputStream.NULL_OUTPUT_STREAM);\n infoStream.close();\n\n // fix line endings for shell scripts\n InputStream in = new FileInputStream(file);\n if (infoStream.isShell() && !infoStream.hasUnixLineEndings()) {\n byte[] buf = Utils.toUnixLineEndings(in);\n in = new ByteArrayInputStream(buf);\n }\n\n addControlEntry(file.getName(), IOUtils.toString(in), outputStream);\n\n in.close();\n }\n }\n\n if (foundConffiles) {\n console.info(\"Found file 'conffiles' in the control directory. Skipping conffiles generation.\");\n } else if ((conffiles != null) && (conffiles.size() > 0)) {\n addControlEntry(\"conffiles\", createPackageConffilesFile(conffiles), outputStream);\n } else {\n console.info(\"Skipping 'conffiles' generation. No entries defined in maven/pom or ant/build.xml.\");\n }\n\n if (packageControlFile == null) {\n throw new FileNotFoundException(\"No 'control' file found in \" + controlFiles.toString());\n }\n\n addControlEntry(\"control\", packageControlFile.toString(), outputStream);\n addControlEntry(\"md5sums\", checksums.toString(), outputStream);\n\n outputStream.close();\n }"
] |
Adds folders to perform the search in.
@param folders Folders to search in. | [
"private void addFoldersToSearchIn(final List<String> folders) {\n\n if (null == folders) {\n return;\n }\n\n for (String folder : folders) {\n if (!CmsResource.isFolder(folder)) {\n folder += \"/\";\n }\n\n m_foldersToSearchIn.add(folder);\n }\n }"
] | [
"protected String getExtraSolrParams() {\n\n try {\n return m_configObject.getString(JSON_KEY_EXTRASOLRPARAMS);\n } catch (JSONException e) {\n if (null == m_baseConfig) {\n if (LOG.isInfoEnabled()) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_EXTRA_PARAMETERS_0), e);\n }\n return \"\";\n } else {\n return m_baseConfig.getGeneralConfig().getExtraSolrParams();\n }\n }\n }",
"public void writeNameValuePair(String name, int value) throws IOException\n {\n internalWriteNameValuePair(name, Integer.toString(value));\n }",
"static <T, ID> Dao<T, ID> createDao(ConnectionSource connectionSource, Class<T> clazz) throws SQLException {\n\t\treturn new BaseDaoImpl<T, ID>(connectionSource, clazz) {\n\t\t};\n\t}",
"private void init(AttributeSet attrs) {\n inflate(getContext(), R.layout.intl_phone_input, this);\n\n /**+\n * Country spinner\n */\n mCountrySpinner = (Spinner) findViewById(R.id.intl_phone_edit__country);\n mCountrySpinnerAdapter = new CountrySpinnerAdapter(getContext());\n mCountrySpinner.setAdapter(mCountrySpinnerAdapter);\n\n mCountries = CountriesFetcher.getCountries(getContext());\n mCountrySpinnerAdapter.addAll(mCountries);\n mCountrySpinner.setOnItemSelectedListener(mCountrySpinnerListener);\n\n setFlagDefaults(attrs);\n\n /**\n * Phone text field\n */\n mPhoneEdit = (EditText) findViewById(R.id.intl_phone_edit__phone);\n mPhoneEdit.addTextChangedListener(mPhoneNumberWatcher);\n\n setDefault();\n setEditTextDefaults(attrs);\n }",
"private void rotatorPushRight( int m )\n {\n double b11 = off[m];\n double b21 = diag[m+1];\n\n computeRotator(b21,-b11);\n\n // apply rotator on the right\n off[m] = 0;\n diag[m+1] = b21*c-b11*s;\n\n if( m+2 < N) {\n double b22 = off[m+1];\n off[m+1] = b22*c;\n bulge = b22*s;\n } else {\n bulge = 0;\n }\n\n// SimpleMatrix Q = createQ(m,m+1, c, s, true);\n// B=Q.mult(B);\n//\n// B.print();\n// printMatrix();\n// System.out.println(\" bulge = \"+bulge);\n// System.out.println();\n\n if( Ut != null ) {\n updateRotator(Ut,m,m+1,c,s);\n\n// SimpleMatrix.wrap(Ut).mult(B).mult(SimpleMatrix.wrap(Vt).transpose()).print();\n// printMatrix();\n// System.out.println(\"bulge = \"+bulge);\n// System.out.println();\n }\n }",
"protected boolean closeAtomically() {\n if (isClosed.compareAndSet(false, true)) {\n Closeable.closeQuietly(networkStatsListener);\n return true;\n } else {\n //was already closed.\n return false;\n }\n }",
"public SelectStatement getPreparedSelectByPkStatement(ClassDescriptor cld)\r\n {\r\n SelectStatement sql;\r\n SqlForClass sfc = getSqlForClass(cld);\r\n sql = sfc.getSelectByPKSql();\r\n if(sql == null)\r\n {\r\n sql = new SqlSelectByPkStatement(m_platform, cld, logger);\r\n\r\n // set the sql string\r\n sfc.setSelectByPKSql(sql);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n }\r\n return sql;\r\n }",
"public static void rebuild(final MODE newMode) {\n if (mode != newMode) {\n mode = newMode;\n TYPE type;\n switch (mode) {\n case DEBUG:\n type = TYPE.ANDROID;\n Log.startFullLog();\n break;\n case DEVELOPER:\n type = TYPE.PERSISTENT;\n Log.stopFullLog();\n break;\n case USER:\n type = TYPE.ANDROID;\n break;\n default:\n type = DEFAULT_TYPE;\n Log.stopFullLog();\n break;\n }\n currentLog = getLog(type);\n }\n }",
"public static boolean hasPermission(Permission permission) {\n SecurityManager security = System.getSecurityManager();\n if (security != null) {\n try {\n security.checkPermission(permission);\n } catch (java.security.AccessControlException e) {\n return false;\n }\n }\n return true;\n }"
] |
Creates the style definition used for a rectangle element based on the given properties of the rectangle
@param x The X coordinate of the rectangle.
@param y The Y coordinate of the rectangle.
@param width The width of the rectangle.
@param height The height of the rectangle.
@param stroke Should there be a stroke around?
@param fill Should the rectangle be filled?
@return The resulting element style definition. | [
"protected NodeData createRectangleStyle(float x, float y, float width, float height, boolean stroke, boolean fill)\n {\n float lineWidth = transformLength((float) getGraphicsState().getLineWidth());\n float lw = (lineWidth < 1f) ? 1f : lineWidth;\n float wcor = stroke ? lw : 0.0f;\n \n NodeData ret = CSSFactory.createNodeData();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"position\", tf.createIdent(\"absolute\")));\n ret.push(createDeclaration(\"left\", tf.createLength(x, unit)));\n ret.push(createDeclaration(\"top\", tf.createLength(y, unit)));\n ret.push(createDeclaration(\"width\", tf.createLength(width - wcor, unit)));\n ret.push(createDeclaration(\"height\", tf.createLength(height - wcor, unit)));\n \n if (stroke)\n {\n ret.push(createDeclaration(\"border-width\", tf.createLength(lw, unit)));\n ret.push(createDeclaration(\"border-style\", tf.createIdent(\"solid\")));\n String color = colorString(getGraphicsState().getStrokingColor());\n ret.push(createDeclaration(\"border-color\", tf.createColor(color)));\n }\n \n if (fill)\n {\n String color = colorString(getGraphicsState().getNonStrokingColor());\n if (color != null)\n ret.push(createDeclaration(\"background-color\", tf.createColor(color)));\n }\n\n return ret;\n }"
] | [
"public static final Bytes of(String s) {\n Objects.requireNonNull(s);\n if (s.isEmpty()) {\n return EMPTY;\n }\n byte[] data = s.getBytes(StandardCharsets.UTF_8);\n return new Bytes(data, s);\n }",
"public Info getInfo(String ... fields) {\r\n QueryStringBuilder builder = new QueryStringBuilder();\r\n if (fields.length > 0) {\r\n builder.appendParam(\"fields\", fields);\r\n }\r\n URL url = DEVICE_PIN_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\r\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\r\n BoxJSONResponse response = (BoxJSONResponse) request.send();\r\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\r\n return new Info(responseJSON);\r\n }",
"protected void readUUID(StreamReader stream, Map<String, Object> map) throws IOException\n {\n int unknown0Size = stream.getMajorVersion() > 5 ? 8 : 16;\n map.put(\"UNKNOWN0\", stream.readBytes(unknown0Size));\n map.put(\"UUID\", stream.readUUID()); \n }",
"public Stamp allocateTimestamp() {\n\n synchronized (this) {\n Preconditions.checkState(!closed, \"tracker closed \");\n\n if (node == null) {\n Preconditions.checkState(allocationsInProgress == 0,\n \"expected allocationsInProgress == 0 when node == null\");\n Preconditions.checkState(!updatingZk, \"unexpected concurrent ZK update\");\n\n createZkNode(getTimestamp().getTxTimestamp());\n }\n\n allocationsInProgress++;\n }\n\n try {\n Stamp ts = getTimestamp();\n\n synchronized (this) {\n timestamps.add(ts.getTxTimestamp());\n }\n\n return ts;\n } catch (RuntimeException re) {\n synchronized (this) {\n allocationsInProgress--;\n }\n throw re;\n }\n }",
"public BUILDER setAttributeGroup(String attributeGroup) {\n assert attributeGroup == null || attributeGroup.length() > 0;\n //noinspection deprecation\n this.attributeGroup = attributeGroup;\n return (BUILDER) this;\n }",
"public void setHighlightStrength(float _highlightStrength) {\n mHighlightStrength = _highlightStrength;\n for (PieModel model : mPieData) {\n highlightSlice(model);\n }\n invalidateGlobal();\n }",
"public Bundler put(String key, Serializable value) {\n delegate.putSerializable(key, value);\n return this;\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 static AppDescriptor deserializeFrom(byte[] bytes) {\n try {\n ByteArrayInputStream bais = new ByteArrayInputStream(bytes);\n ObjectInputStream ois = new ObjectInputStream(bais);\n return (AppDescriptor) ois.readObject();\n } catch (IOException e) {\n throw E.ioException(e);\n } catch (ClassNotFoundException e) {\n throw E.unexpected(e);\n }\n }"
] |
Creates a Profile object from a SQL resultset
@param result resultset containing the profile
@return Profile
@throws Exception exception | [
"private Profile getProfileFromResultSet(ResultSet result) throws Exception {\n Profile profile = new Profile();\n profile.setId(result.getInt(Constants.GENERIC_ID));\n Clob clobProfileName = result.getClob(Constants.PROFILE_PROFILE_NAME);\n String profileName = clobProfileName.getSubString(1, (int) clobProfileName.length());\n profile.setName(profileName);\n return profile;\n }"
] | [
"public static void cache(XmlFileModel key, Document document)\n {\n String cacheKey = getKey(key);\n map.put(cacheKey, new CacheDocument(false, document));\n }",
"public static appfwlearningsettings[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tappfwlearningsettings obj = new appfwlearningsettings();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tappfwlearningsettings[] response = (appfwlearningsettings[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"public void addDependency(final Dependency dependency) {\n if(dependency != null && !dependencies.contains(dependency)){\n this.dependencies.add(dependency);\n }\n }",
"public static List<DockerImage> getDockerImagesFromAgents(final int buildInfoId, TaskListener listener) throws IOException, InterruptedException {\n List<DockerImage> dockerImages = new ArrayList<DockerImage>();\n\n // Collect images from the master:\n dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));\n\n // Collect images from all the agents:\n List<Node> nodes = Jenkins.getInstance().getNodes();\n for (Node node : nodes) {\n if (node == null || node.getChannel() == null) {\n continue;\n }\n try {\n List<DockerImage> partialDockerImages = node.getChannel().call(new MasterToSlaveCallable<List<DockerImage>, IOException>() {\n public List<DockerImage> call() throws IOException {\n List<DockerImage> dockerImages = new ArrayList<DockerImage>();\n dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));\n return dockerImages;\n }\n });\n dockerImages.addAll(partialDockerImages);\n } catch (Exception e) {\n listener.getLogger().println(\"Could not collect docker images from Jenkins node '\" + node.getDisplayName() + \"' due to: \" + e.getMessage());\n }\n }\n return dockerImages;\n }",
"protected List<CRFDatum> extractDatumSequence(int[][][] allData, int beginPosition, int endPosition,\r\n List<IN> labeledWordInfos) {\r\n List<CRFDatum> result = new ArrayList<CRFDatum>();\r\n int beginContext = beginPosition - windowSize + 1;\r\n if (beginContext < 0) {\r\n beginContext = 0;\r\n }\r\n // for the beginning context, add some dummy datums with no features!\r\n // TODO: is there any better way to do this?\r\n for (int position = beginContext; position < beginPosition; position++) {\r\n List<Collection<String>> cliqueFeatures = new ArrayList<Collection<String>>();\r\n for (int i = 0; i < windowSize; i++) {\r\n // create a feature list\r\n cliqueFeatures.add(Collections.<String>emptyList());\r\n }\r\n CRFDatum<Collection<String>, String> datum = new CRFDatum<Collection<String>, String>(cliqueFeatures,\r\n labeledWordInfos.get(position).get(AnswerAnnotation.class));\r\n result.add(datum);\r\n }\r\n // now add the real datums\r\n for (int position = beginPosition; position <= endPosition; position++) {\r\n List<Collection<String>> cliqueFeatures = new ArrayList<Collection<String>>();\r\n for (int i = 0; i < windowSize; i++) {\r\n // create a feature list\r\n Collection<String> features = new ArrayList<String>();\r\n for (int j = 0; j < allData[position][i].length; j++) {\r\n features.add(featureIndex.get(allData[position][i][j]));\r\n }\r\n cliqueFeatures.add(features);\r\n }\r\n CRFDatum<Collection<String>,String> datum = new CRFDatum<Collection<String>,String>(cliqueFeatures,\r\n labeledWordInfos.get(position).get(AnswerAnnotation.class));\r\n result.add(datum);\r\n }\r\n return result;\r\n }",
"public static <T> List<T> toList(Iterator<? extends T> iterator) {\n\t\treturn Lists.newArrayList(iterator);\n\t}",
"public static DatabaseFieldConfig fromReader(BufferedReader reader) throws SQLException {\n\t\tDatabaseFieldConfig config = new DatabaseFieldConfig();\n\t\tboolean anything = false;\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read DatabaseFieldConfig from stream\", e);\n\t\t\t}\n\t\t\tif (line == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_END_MARKER)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// skip empty lines or comments\n\t\t\tif (line.length() == 0 || line.startsWith(\"#\") || line.equals(CONFIG_FILE_START_MARKER)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString[] parts = line.split(\"=\", -2);\n\t\t\tif (parts.length != 2) {\n\t\t\t\tthrow new SQLException(\"DatabaseFieldConfig reading from stream cannot parse line: \" + line);\n\t\t\t}\n\t\t\treadField(config, parts[0], parts[1]);\n\t\t\tanything = true;\n\t\t}\n\t\t// if we got any config lines then we return the config\n\t\tif (anything) {\n\t\t\treturn config;\n\t\t} else {\n\t\t\t// otherwise we return null for none\n\t\t\treturn null;\n\t\t}\n\t}",
"public static void validateAllAvroSchemas(SerializerDefinition avroSerDef) {\n Map<Integer, String> schemaVersions = avroSerDef.getAllSchemaInfoVersions();\n if(schemaVersions.size() < 1) {\n throw new VoldemortException(\"No schema specified\");\n }\n for(Map.Entry<Integer, String> entry: schemaVersions.entrySet()) {\n Integer schemaVersionNumber = entry.getKey();\n String schemaStr = entry.getValue();\n try {\n Schema.parse(schemaStr);\n } catch(Exception e) {\n throw new VoldemortException(\"Unable to parse Avro schema version :\"\n + schemaVersionNumber + \", schema string :\"\n + schemaStr);\n }\n }\n }",
"public static boolean isAvroSchema(String serializerName) {\n if(serializerName.equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)\n || serializerName.equals(AVRO_GENERIC_TYPE_NAME)\n || serializerName.equals(AVRO_REFLECTIVE_TYPE_NAME)\n || serializerName.equals(AVRO_SPECIFIC_TYPE_NAME)) {\n return true;\n } else {\n return false;\n }\n }"
] |
Get the features collection from a GeoJson URL.
@param template the template
@param geoJsonUrl what to parse
@return the feature collection | [
"public final SimpleFeatureCollection treatStringAsURL(final Template template, final String geoJsonUrl)\n throws IOException {\n URL url;\n try {\n url = FileUtils.testForLegalFileUrl(template.getConfiguration(), new URL(geoJsonUrl));\n } catch (MalformedURLException e) {\n return null;\n }\n\n final String geojsonString;\n if (url.getProtocol().equalsIgnoreCase(\"file\")) {\n geojsonString = IOUtils.toString(url, Constants.DEFAULT_CHARSET.name());\n } else {\n geojsonString = URIUtils.toString(this.httpRequestFactory, url);\n }\n\n return treatStringAsGeoJson(geojsonString);\n }"
] | [
"static JDOClass getJDOClass(Class c)\r\n\t{\r\n\t\tJDOClass rc = null;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tJavaModelFactory javaModelFactory = RuntimeJavaModelFactory.getInstance();\r\n\t\t\tJavaModel javaModel = javaModelFactory.getJavaModel(c.getClassLoader());\r\n\t\t\tJDOModel m = JDOModelFactoryImpl.getInstance().getJDOModel(javaModel);\r\n\t\t\trc = m.getJDOClass(c.getName());\r\n\t\t}\r\n\t\tcatch (RuntimeException ex)\r\n\t\t{\r\n\t\t\tthrow new JDOFatalInternalException(\"Not a JDO class: \" + c.getName()); \r\n\t\t}\r\n\t\treturn rc;\r\n\t}",
"public int[] sampleBatchWithReplacement() {\n // Sample the indices with replacement.\n int[] batch = new int[batchSize];\n for (int i=0; i<batch.length; i++) {\n batch[i] = Prng.nextInt(numExamples);\n }\n return batch;\n }",
"public int[] indices(Collection<E> elems) {\r\n int[] indices = new int[elems.size()];\r\n int i = 0;\r\n for (E elem : elems) {\r\n indices[i++] = indexOf(elem);\r\n }\r\n return indices;\r\n }",
"String getDefaultReturnFields() {\n\n StringBuffer fields = new StringBuffer(\"\");\n fields.append(CmsSearchField.FIELD_PATH);\n fields.append(',');\n fields.append(CmsSearchField.FIELD_INSTANCEDATE).append('_').append(getSearchLocale().toString()).append(\"_dt\");\n fields.append(',');\n fields.append(CmsSearchField.FIELD_INSTANCEDATE_END).append('_').append(getSearchLocale().toString()).append(\n \"_dt\");\n fields.append(',');\n fields.append(CmsSearchField.FIELD_INSTANCEDATE_CURRENT_TILL).append('_').append(\n getSearchLocale().toString()).append(\"_dt\");\n fields.append(',');\n fields.append(CmsSearchField.FIELD_ID);\n fields.append(',');\n fields.append(CmsSearchField.FIELD_SOLR_ID);\n fields.append(',');\n fields.append(CmsSearchField.FIELD_DISPTITLE).append('_').append(getSearchLocale().toString()).append(\"_sort\");\n fields.append(',');\n fields.append(CmsSearchField.FIELD_LINK);\n return fields.toString();\n }",
"public void addUIEventHandler(JavascriptObject obj, UIEventType type, UIEventHandler h) {\n String key = registerEventHandler(h);\n String mcall = \"google.maps.event.addListener(\" + obj.getVariableName() + \", '\" + type.name() + \"', \"\n + \"function(event) {document.jsHandlers.handleUIEvent('\" + key + \"', event);});\";//.latLng\n //System.out.println(\"addUIEventHandler mcall: \" + mcall);\n runtime.execute(mcall);\n }",
"public static boolean isAllWhitespace(CharSequence self) {\n String s = self.toString();\n for (int i = 0; i < s.length(); i++) {\n if (!Character.isWhitespace(s.charAt(i)))\n return false;\n }\n return true;\n }",
"public static DMatrixSparseCSC diag(double... values ) {\n int N = values.length;\n return diag(new DMatrixSparseCSC(N,N,N),values,0,N);\n }",
"public B importContext(AbstractContext context){\n Objects.requireNonNull(context);\n return importContext(context, false);\n }",
"@SuppressWarnings(\"unchecked\")\n\tpublic static Type getSuperclassTypeParameter(Class<?> subclass) {\n\t\tType superclass = subclass.getGenericSuperclass();\n\t\tif (superclass instanceof Class) {\n\t\t\tthrow new RuntimeException(\"Missing type parameter.\");\n\t\t}\n\t\treturn ((ParameterizedType) superclass).getActualTypeArguments()[0];\n\t}"
] |
sets the row reader class name for thie class descriptor | [
"public void setRowReader(String newReaderClassName)\r\n {\r\n try\r\n {\r\n m_rowReader =\r\n (RowReader) ClassHelper.newInstance(\r\n newReaderClassName,\r\n ClassDescriptor.class,\r\n this);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\"Instantiating of current set RowReader failed\", e);\r\n }\r\n }"
] | [
"private static boolean validateEndRecord(File file, FileChannel channel, long startEndRecord, long endSig) throws IOException {\n\n try {\n channel.position(startEndRecord);\n\n final ByteBuffer endDirHeader = getByteBuffer(ENDLEN);\n read(endDirHeader, channel);\n if (endDirHeader.limit() < ENDLEN) {\n // Couldn't read the full end of central directory record header\n return false;\n } else if (getUnsignedInt(endDirHeader, 0) != endSig) {\n return false;\n }\n\n long pos = getUnsignedInt(endDirHeader, END_CENSTART);\n // TODO deal with Zip64\n if (pos == ZIP64_MARKER) {\n return false;\n }\n\n ByteBuffer cdfhBuffer = getByteBuffer(CENLEN);\n read(cdfhBuffer, channel, pos);\n long header = getUnsignedInt(cdfhBuffer, 0);\n if (header == CENSIG) {\n long firstLoc = getUnsignedInt(cdfhBuffer, CEN_LOC_OFFSET);\n long firstSize = getUnsignedInt(cdfhBuffer, CENSIZ);\n if (firstLoc == 0) {\n // normal case -- first bytes are the first local file\n if (!validateLocalFileRecord(channel, 0, firstSize)) {\n return false;\n }\n } else {\n // confirm that firstLoc is indeed the first local file\n long fileFirstLoc = scanForLocSig(channel);\n if (firstLoc != fileFirstLoc) {\n if (fileFirstLoc == 0) {\n return false;\n } else {\n // scanForLocSig() found a LOCSIG, but not at position zero and not\n // at the expected position.\n // With a file like this, we can't tell if we're in a nested zip\n // or we're in an outer zip and had the bad luck to find random bytes\n // that look like LOCSIG.\n return false;\n }\n }\n }\n\n // At this point, endDirHeader points to the correct end of central dir record.\n // Just need to validate the record is complete, including any comment\n int commentLen = getUnsignedShort(endDirHeader, END_COMMENTLEN);\n long commentEnd = startEndRecord + ENDLEN + commentLen;\n return commentEnd <= channel.size();\n }\n\n return false;\n } catch (EOFException eof) {\n // pos or firstLoc weren't really positions and moved us to an invalid location\n return false;\n }\n }",
"public static void showErrorDialog(String message, String details) {\n\n Window window = prepareWindow(DialogWidth.wide);\n window.setCaption(\"Error\");\n window.setContent(new CmsSetupErrorDialog(message, details, null, window));\n A_CmsUI.get().addWindow(window);\n\n }",
"@Override\n protected void updateState(final String name, final InstallationModificationImpl modification, final InstallationModificationImpl.InstallationState state) {\n final PatchableTarget.TargetInfo identityInfo = modification.getModifiedState();\n this.identity = new Identity() {\n @Override\n public String getVersion() {\n return modification.getVersion();\n }\n\n @Override\n public String getName() {\n return name;\n }\n\n @Override\n public TargetInfo loadTargetInfo() throws IOException {\n return identityInfo;\n }\n\n @Override\n public DirectoryStructure getDirectoryStructure() {\n return modification.getDirectoryStructure();\n }\n };\n\n this.allPatches = Collections.unmodifiableList(modification.getAllPatches());\n this.layers.clear();\n for (final Map.Entry<String, MutableTargetImpl> entry : state.getLayers().entrySet()) {\n final String layerName = entry.getKey();\n final MutableTargetImpl target = entry.getValue();\n putLayer(layerName, new LayerInfo(layerName, target.getModifiedState(), target.getDirectoryStructure()));\n }\n this.addOns.clear();\n for (final Map.Entry<String, MutableTargetImpl> entry : state.getAddOns().entrySet()) {\n final String addOnName = entry.getKey();\n final MutableTargetImpl target = entry.getValue();\n putAddOn(addOnName, new LayerInfo(addOnName, target.getModifiedState(), target.getDirectoryStructure()));\n }\n }",
"public void fire(TestCaseFinishedEvent event) {\n TestCaseResult testCase = testCaseStorage.get();\n event.process(testCase);\n\n Step root = stepStorage.pollLast();\n\n if (Status.PASSED.equals(testCase.getStatus())) {\n new RemoveAttachmentsEvent(AllureConfig.newInstance().getRemoveAttachments()).process(root);\n }\n\n testCase.getSteps().addAll(root.getSteps());\n testCase.getAttachments().addAll(root.getAttachments());\n\n stepStorage.remove();\n testCaseStorage.remove();\n\n notifier.fire(event);\n }",
"private void readRelationship(Link link)\n {\n Task sourceTask = m_taskIdMap.get(link.getSourceTaskID());\n Task destinationTask = m_taskIdMap.get(link.getDestinationTaskID());\n if (sourceTask != null && destinationTask != null)\n {\n Duration lag = getDuration(link.getLagUnit(), link.getLag());\n RelationType type = link.getType();\n Relation relation = destinationTask.addPredecessor(sourceTask, type, lag);\n relation.setUniqueID(link.getID());\n }\n }",
"public void setVolume(float volume)\n {\n // Save this in case this audio source is not being played yet\n mVolume = volume;\n if (isPlaying() && (getSourceId() != GvrAudioEngine.INVALID_ID))\n {\n // This will actually work only if the sound file is being played\n mAudioListener.getAudioEngine().setSoundVolume(getSourceId(), getVolume());\n }\n }",
"public static <T> List<T> copyOf(Collection<T> source) {\n Preconditions.checkNotNull(source);\n if (source instanceof ImmutableList<?>) {\n return (ImmutableList<T>) source;\n }\n if (source.isEmpty()) {\n return Collections.emptyList();\n }\n return ofInternal(source.toArray());\n }",
"public void postArtifact(final Artifact artifact, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.artifactResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, artifact);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST artifact\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }",
"private static DataHandler getDataHandlerForString(Event event) {\n try {\n return new DataHandler(new ByteDataSource(event.getContent().getBytes(\"UTF-8\")));\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n }"
] |
add a FK column pointing to This Class | [
"public void addFkToThisClass(String column)\r\n {\r\n if (fksToThisClass == null)\r\n {\r\n fksToThisClass = new Vector();\r\n }\r\n fksToThisClass.add(column);\r\n fksToThisClassAry = null;\r\n }"
] | [
"public static final Date parseExtendedAttributeDate(String value)\n {\n Date result = null;\n\n if (value != null)\n {\n try\n {\n result = DATE_FORMAT.get().parse(value);\n }\n\n catch (ParseException ex)\n {\n // ignore exceptions\n }\n }\n\n return (result);\n }",
"public void associateTypeJndiResource(JNDIResourceModel resource, String type)\n {\n if (type == null || resource == null)\n {\n return;\n }\n\n if (StringUtils.equals(type, \"javax.sql.DataSource\") && !(resource instanceof DataSourceModel))\n {\n DataSourceModel ds = GraphService.addTypeToModel(this.getGraphContext(), resource, DataSourceModel.class);\n }\n else if (StringUtils.equals(type, \"javax.jms.Queue\") && !(resource instanceof JmsDestinationModel))\n {\n JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class);\n jms.setDestinationType(JmsDestinationType.QUEUE);\n }\n else if (StringUtils.equals(type, \"javax.jms.QueueConnectionFactory\") && !(resource instanceof JmsConnectionFactoryModel))\n {\n JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class);\n jms.setConnectionFactoryType(JmsDestinationType.QUEUE);\n }\n else if (StringUtils.equals(type, \"javax.jms.Topic\") && !(resource instanceof JmsDestinationModel))\n {\n JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class);\n jms.setDestinationType(JmsDestinationType.TOPIC);\n }\n else if (StringUtils.equals(type, \"javax.jms.TopicConnectionFactory\") && !(resource instanceof JmsConnectionFactoryModel))\n {\n JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class);\n jms.setConnectionFactoryType(JmsDestinationType.TOPIC);\n }\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<AccountingDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<AccountingDate>) super.localDateTime(temporal);\n }",
"public void setContentType(String photoId, String contentType) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_CONTENTTYPE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"content_type\", contentType);\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 }",
"private boolean hasMultipleCostRates()\n {\n boolean result = false;\n CostRateTable table = getCostRateTable();\n if (table != null)\n {\n //\n // We assume here that if there is just one entry in the cost rate\n // table, this is an open ended rate which covers any work, it won't\n // have specific dates attached to it.\n //\n if (table.size() > 1)\n {\n //\n // If we have multiple rates in the table, see if the same rate\n // is in force at the start and the end of the aaaignment.\n //\n CostRateTableEntry startEntry = table.getEntryByDate(getStart());\n CostRateTableEntry finishEntry = table.getEntryByDate(getFinish());\n result = (startEntry != finishEntry);\n }\n }\n return result;\n }",
"private static JSONArray parseOutgoings(ArrayList<Shape> outgoings) throws JSONException {\n if (outgoings != null) {\n JSONArray outgoingsArray = new JSONArray();\n\n for (Shape outgoing : outgoings) {\n JSONObject outgoingObject = new JSONObject();\n\n outgoingObject.put(\"resourceId\",\n outgoing.getResourceId().toString());\n outgoingsArray.put(outgoingObject);\n }\n\n return outgoingsArray;\n }\n\n return new JSONArray();\n }",
"public String getModulePaths() {\n final StringBuilder result = new StringBuilder();\n if (addDefaultModuleDir) {\n result.append(wildflyHome.resolve(\"modules\").toString());\n }\n if (!modulesDirs.isEmpty()) {\n if (addDefaultModuleDir) result.append(File.pathSeparator);\n for (Iterator<String> iterator = modulesDirs.iterator(); iterator.hasNext(); ) {\n result.append(iterator.next());\n if (iterator.hasNext()) {\n result.append(File.pathSeparator);\n }\n }\n }\n return result.toString();\n }",
"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}",
"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 }"
] |
Truncated power function.
@param value Value.
@param degree Degree.
@return Result. | [
"public static double TruncatedPower(double value, double degree) {\r\n double x = Math.pow(value, degree);\r\n return (x > 0) ? x : 0.0;\r\n }"
] | [
"public void setValue(String constantValue)\r\n {\r\n this.fieldSource = SOURCE_VALUE;\r\n this.fieldRefName = null;\r\n this.returnedByProcedure = false;\r\n this.constantValue = constantValue;\r\n }",
"public static void moveBandsElemnts(int yOffset, JRDesignBand band) {\n\t\tif (band == null)\n\t\t\treturn;\n\n\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\tJRDesignElement elem = (JRDesignElement) jrChild;\n\t\t\telem.setY(elem.getY() + yOffset);\n\t\t}\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 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 }",
"public Set<Tag> getAncestorTags(Tag tag)\n {\n Set<Tag> ancestors = new HashSet<>();\n getAncestorTags(tag, ancestors);\n return ancestors;\n }",
"private void addModuleToTree(final DbModule module, final TreeNode tree) {\n final TreeNode subTree = new TreeNode();\n subTree.setName(module.getName());\n tree.addChild(subTree);\n\n // Add SubsubModules\n for (final DbModule subsubmodule : module.getSubmodules()) {\n addModuleToTree(subsubmodule, subTree);\n }\n }",
"public static base_responses restore(nitro_service client, appfwprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwprofile restoreresources[] = new appfwprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\trestoreresources[i] = new appfwprofile();\n\t\t\t\trestoreresources[i].archivename = resources[i].archivename;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, restoreresources,\"restore\");\n\t\t}\n\t\treturn result;\n\t}",
"protected final String computeId(\n final ITemplateContext context,\n final IProcessableElementTag tag,\n final String name, final boolean sequence) {\n\n String id = tag.getAttributeValue(this.idAttributeDefinition.getAttributeName());\n if (!org.thymeleaf.util.StringUtils.isEmptyOrWhitespace(id)) {\n return (StringUtils.hasText(id) ? id : null);\n }\n\n id = FieldUtils.idFromName(name);\n if (sequence) {\n final Integer count = context.getIdentifierSequences().getAndIncrementIDSeq(id);\n return id + count.toString();\n }\n return id;\n\n }",
"@POST\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response addCorporateGroupIdPrefix(@Auth final DbCredential credential, @PathParam(\"name\") final String organizationId, final String corporateGroupId){\n LOG.info(\"Got an add a corporate groupId prefix request for organization \" + organizationId +\".\");\n if(!credential.getRoles().contains(DbCredential.AvailableRoles.DATA_UPDATER)){\n throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build());\n }\n\n if(corporateGroupId == null || corporateGroupId.isEmpty()){\n LOG.error(\"No corporate GroupId to add!\");\n throw new WebApplicationException(Response.serverError().status(HttpStatus.BAD_REQUEST_400)\n .entity(\"CorporateGroupId to add should be in the query content.\").build());\n }\n\n getOrganizationHandler().addCorporateGroupId(organizationId, corporateGroupId);\n return Response.ok().status(HttpStatus.CREATED_201).build();\n }"
] |
Delegates file rolling to composed objects.
@see FileRollable#roll(org.apache.log4j.spi.LoggingEvent) | [
"public final boolean roll(final LoggingEvent loggingEvent) {\n for (int i = 0; i < this.fileRollables.length; i++) {\n if (this.fileRollables[i].roll(loggingEvent)) {\n return true;\n }\n }\n return false;\n }"
] | [
"protected void createNewFile(final File file) {\n try {\n file.createNewFile();\n setFileNotWorldReadablePermissions(file);\n } catch (IOException e){\n throw new RuntimeException(e);\n }\n }",
"private static void registerImage(String imageId, String imageTag, String targetRepo,\n ArrayListMultimap<String, String> artifactsProps, int buildInfoId) throws IOException {\n DockerImage image = new DockerImage(imageId, imageTag, targetRepo, buildInfoId, artifactsProps);\n images.add(image);\n }",
"private void onClickAdd() {\n\n if (m_currentLocation.isPresent()) {\n CmsFavoriteEntry entry = m_currentLocation.get();\n List<CmsFavoriteEntry> entries = getEntries();\n entries.add(entry);\n try {\n m_favDao.saveFavorites(entries);\n } catch (Exception e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n m_context.close();\n }\n }",
"public Integer getVarDataKey(FieldType type)\n {\n Integer result = null;\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getVarDataKey();\n }\n return result;\n }",
"boolean openStream() throws InterruptedException, IOException {\n logger.info(\"stream START\");\n final boolean isOpen;\n final Set<BsonValue> idsToWatch = nsConfig.getSynchronizedDocumentIds();\n\n if (!networkMonitor.isConnected()) {\n logger.info(\"stream END - Network disconnected\");\n return false;\n }\n\n if (idsToWatch.isEmpty()) {\n logger.info(\"stream END - No synchronized documents\");\n return false;\n }\n\n nsLock.writeLock().lockInterruptibly();\n try {\n if (!authMonitor.isLoggedIn()) {\n logger.info(\"stream END - Logged out\");\n return false;\n }\n\n final Document args = new Document();\n args.put(\"database\", namespace.getDatabaseName());\n args.put(\"collection\", namespace.getCollectionName());\n args.put(\"ids\", idsToWatch);\n\n currentStream =\n service.streamFunction(\n \"watch\",\n Collections.singletonList(args),\n ResultDecoders.changeEventDecoder(BSON_DOCUMENT_CODEC));\n\n if (currentStream != null && currentStream.isOpen()) {\n this.nsConfig.setStale(true);\n isOpen = true;\n } else {\n isOpen = false;\n }\n } finally {\n nsLock.writeLock().unlock();\n }\n return isOpen;\n }",
"private void precheckStateAllNull() throws IllegalStateException {\n if ((doubleValue != null) || (doubleArray != null)\n || (longValue != null) || (longArray != null)\n || (stringValue != null) || (stringArray != null)\n || (map != null)) {\n throw new IllegalStateException(\"Expected all properties to be empty: \" + this);\n }\n }",
"@RequestMapping(value = \"/scripts\", method = RequestMethod.GET)\n public String scriptView(Model model) throws Exception {\n return \"script\";\n }",
"private static void tryWritePreferenceOnDisk(Preferences preference) throws BackingStoreException {\n final String DUMMY_PROP=\"dummywrite\";\n instance.put(DUMMY_PROP,\"test\");\n instance.flush();\n instance.remove(DUMMY_PROP);\n instance.flush();\n }",
"private void createResultSubClassesMultipleJoinedTables(List result, ClassDescriptor cld, boolean wholeTree)\r\n {\r\n List tmp = (List) superClassMultipleJoinedTablesMap.get(cld.getClassOfObject());\r\n if(tmp != null)\r\n {\r\n result.addAll(tmp);\r\n if(wholeTree)\r\n {\r\n for(int i = 0; i < tmp.size(); i++)\r\n {\r\n Class subClass = (Class) tmp.get(i);\r\n ClassDescriptor subCld = getDescriptorFor(subClass);\r\n createResultSubClassesMultipleJoinedTables(result, subCld, wholeTree);\r\n }\r\n }\r\n }\r\n }"
] |
Append the given path segments to the existing path of this builder.
Each given path segment may contain URI template variables.
@param pathSegments the URI path segments
@return this UriComponentsBuilder | [
"public UriComponentsBuilder pathSegment(String... pathSegments) throws IllegalArgumentException {\n\t\tAssert.notNull(pathSegments, \"'segments' must not be null\");\n\t\tthis.pathBuilder.addPathSegments(pathSegments);\n\t\tresetSchemeSpecificPart();\n\t\treturn this;\n\t}"
] | [
"private void validationRelations(Task task)\n {\n List<Relation> predecessors = task.getPredecessors();\n if (!predecessors.isEmpty())\n {\n ArrayList<Relation> invalid = new ArrayList<Relation>();\n for (Relation relation : predecessors)\n {\n Task sourceTask = relation.getSourceTask();\n Task targetTask = relation.getTargetTask();\n\n String sourceOutlineNumber = sourceTask.getOutlineNumber();\n String targetOutlineNumber = targetTask.getOutlineNumber();\n\n if (sourceOutlineNumber != null && targetOutlineNumber != null && sourceOutlineNumber.startsWith(targetOutlineNumber + '.'))\n {\n invalid.add(relation);\n }\n }\n\n for (Relation relation : invalid)\n {\n relation.getSourceTask().removePredecessor(relation.getTargetTask(), relation.getType(), relation.getLag());\n }\n }\n }",
"@Override\n public void close() {\n // unregister MBeans\n if(stats != null) {\n try {\n if(this.jmxEnabled)\n JmxUtils.unregisterMbean(getAggregateMetricName());\n } catch(Exception e) {}\n stats.close();\n }\n factory.close();\n queuedPool.close();\n }",
"public GVRRenderData setDrawMode(int drawMode) {\n if (drawMode != GL_POINTS && drawMode != GL_LINES\n && drawMode != GL_LINE_STRIP && drawMode != GL_LINE_LOOP\n && drawMode != GL_TRIANGLES && drawMode != GL_TRIANGLE_STRIP\n && drawMode != GL_TRIANGLE_FAN) {\n throw new IllegalArgumentException(\n \"drawMode must be one of GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP, GL_TRIANGLES, GL_TRIANGLE_FAN, GL_TRIANGLE_STRIP.\");\n }\n NativeRenderData.setDrawMode(getNative(), drawMode);\n return this;\n }",
"public Bundler put(String key, Bundle value) {\n delegate.putBundle(key, value);\n return this;\n }",
"public void openBlockingInterruptable()\n throws InterruptedException {\n // We need to thread this call in order to interrupt it (when Ctrl-C occurs).\n connectionThread = new Thread(() -> {\n // This thread can't be interrupted from another thread.\n // Will stay alive until System.exit is called.\n Thread thr = new Thread(() -> super.openBlocking(),\n \"CLI Terminal Connection (uninterruptable)\");\n thr.start();\n try {\n thr.join();\n } catch (InterruptedException ex) {\n // XXX OK, interrupted, just leaving.\n }\n }, \"CLI Terminal Connection (interruptable)\");\n connectionThread.start();\n connectionThread.join();\n }",
"public static String readCorrelationId(Message message) {\n String correlationId = null;\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n List<String> correlationIds = headers.get(CORRELATION_ID_KEY);\n if (correlationIds != null && correlationIds.size() > 0) {\n correlationId = correlationIds.get(0);\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + CORRELATION_ID_KEY + \"' found: \" + correlationId);\n }\n } else {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"No HTTP header '\" + CORRELATION_ID_KEY + \"' found\");\n }\n }\n\n return correlationId;\n }",
"protected void prepareForwardedRequestHeaders(RequestData request, ForwardDestination destination) {\n HttpHeaders headers = request.getHeaders();\n headers.set(HOST, destination.getUri().getAuthority());\n headers.remove(TE);\n }",
"private void unmarshalDescriptor() throws CmsXmlException, CmsException {\n\n if (null != m_desc) {\n\n // unmarshal descriptor\n m_descContent = CmsXmlContentFactory.unmarshal(m_cms, m_cms.readFile(m_desc));\n\n // configure messages if wanted\n CmsProperty bundleProp = m_cms.readPropertyObject(m_desc, PROPERTY_BUNDLE_DESCRIPTOR_LOCALIZATION, true);\n if (!(bundleProp.isNullProperty() || bundleProp.getValue().trim().isEmpty())) {\n m_configuredBundle = bundleProp.getValue();\n }\n }\n\n }",
"protected void addNeighbor(Queue<ColorPoint> queue, int px, int py, int color, Feature component) {\n if (!inBoundary(px, py, component)) {\n return;\n }\n\n if (!mask.isTouched(px, py)) {\n queue.add(new ColorPoint(px, py, color));\n }\n }"
] |
Start a process using the given parameters.
@param processId
@param parameters
@return | [
"public static Command newStartProcess(String processId,\n Map<String, Object> parameters) {\n return getCommandFactoryProvider().newStartProcess( processId,\n parameters );\n }"
] | [
"public void dispatchKeyEvent(int code, int action) {\n int keyCode = 0;\n int keyAction = 0;\n if (code == BUTTON_1) {\n keyCode = KeyEvent.KEYCODE_BUTTON_1;\n } else if (code == BUTTON_2) {\n keyCode = KeyEvent.KEYCODE_BUTTON_2;\n }\n\n if (action == ACTION_DOWN) {\n keyAction = KeyEvent.ACTION_DOWN;\n } else if (action == ACTION_UP) {\n keyAction = KeyEvent.ACTION_UP;\n }\n\n KeyEvent keyEvent = new KeyEvent(keyAction, keyCode);\n setKeyEvent(keyEvent);\n }",
"public static void dumpRow(Map<String, Object> row)\n {\n for (Entry<String, Object> entry : row.entrySet())\n {\n Object value = entry.getValue();\n System.out.println(entry.getKey() + \" = \" + value + \" ( \" + (value == null ? \"\" : value.getClass().getName()) + \")\");\n }\n }",
"protected List<String> splitLinesAndNewLines(String text) {\n\t\tif (text == null)\n\t\t\treturn Collections.emptyList();\n\t\tint idx = initialSegmentSize(text);\n\t\tif (idx == text.length()) {\n\t\t\treturn Collections.singletonList(text);\n\t\t}\n\n\t\treturn continueSplitting(text, idx);\n\t}",
"public static void dumpMaterialProperty(AiMaterial.Property property) {\n System.out.print(property.getKey() + \" \" + property.getSemantic() + \n \" \" + property.getIndex() + \": \");\n Object data = property.getData();\n \n if (data instanceof ByteBuffer) {\n ByteBuffer buf = (ByteBuffer) data;\n for (int i = 0; i < buf.capacity(); i++) {\n System.out.print(Integer.toHexString(buf.get(i) & 0xFF) + \" \");\n }\n \n System.out.println();\n }\n else {\n System.out.println(data.toString());\n }\n }",
"public ItemRequest<Story> delete(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"DELETE\");\n }",
"public static NodeCache startAppIdWatcher(Environment env) {\n try {\n CuratorFramework curator = env.getSharedResources().getCurator();\n\n byte[] uuidBytes = curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);\n if (uuidBytes == null) {\n Halt.halt(\"Fluo Application UUID not found\");\n throw new RuntimeException(); // make findbugs happy\n }\n\n final String uuid = new String(uuidBytes, StandardCharsets.UTF_8);\n\n final NodeCache nodeCache = new NodeCache(curator, ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);\n nodeCache.getListenable().addListener(() -> {\n ChildData node = nodeCache.getCurrentData();\n if (node == null || !uuid.equals(new String(node.getData(), StandardCharsets.UTF_8))) {\n Halt.halt(\"Fluo Application UUID has changed or disappeared\");\n }\n });\n nodeCache.start();\n return nodeCache;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"public boolean add(final String member, final double score) {\n return doWithJedis(new JedisCallable<Boolean>() {\n @Override\n public Boolean call(Jedis jedis) {\n return jedis.zadd(getKey(), score, member) > 0;\n }\n });\n }",
"public static Object readObject(File file) throws IOException,\n ClassNotFoundException {\n FileInputStream fileIn = new FileInputStream(file);\n ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(fileIn));\n try {\n return in.readObject();\n } finally {\n IoUtils.safeClose(in);\n }\n }",
"private void flushOutput() throws IOException {\n outStream.flush();\n outWriter.completeLine();\n errStream.flush();\n errWriter.completeLine();\n }"
] |
Creates a ServiceCall from a paging operation that returns a header response.
@param first the observable to the first page
@param next the observable to poll subsequent pages
@param callback the client-side callback
@param <E> the element type
@param <V> the header object type
@return the future based ServiceCall | [
"public static <E, V> ServiceFuture<List<E>> fromHeaderPageResponse(Observable<ServiceResponseWithHeaders<Page<E>, V>> first, final Func1<String, Observable<ServiceResponseWithHeaders<Page<E>, V>>> next, final ListOperationCallback<E> callback) {\n final AzureServiceFuture<List<E>> serviceCall = new AzureServiceFuture<>();\n final PagingSubscriber<E> subscriber = new PagingSubscriber<>(serviceCall, new Func1<String, Observable<ServiceResponse<Page<E>>>>() {\n @Override\n public Observable<ServiceResponse<Page<E>>> call(String s) {\n return next.call(s)\n .map(new Func1<ServiceResponseWithHeaders<Page<E>, V>, ServiceResponse<Page<E>>>() {\n @Override\n public ServiceResponse<Page<E>> call(ServiceResponseWithHeaders<Page<E>, V> pageVServiceResponseWithHeaders) {\n return pageVServiceResponseWithHeaders;\n }\n });\n }\n }, callback);\n serviceCall.setSubscription(first\n .single()\n .subscribe(subscriber));\n return serviceCall;\n }"
] | [
"public static ModelMBean createModelMBean(Object o) {\n try {\n ModelMBean mbean = new RequiredModelMBean();\n JmxManaged annotation = o.getClass().getAnnotation(JmxManaged.class);\n String description = annotation == null ? \"\" : annotation.description();\n ModelMBeanInfo info = new ModelMBeanInfoSupport(o.getClass().getName(),\n description,\n extractAttributeInfo(o),\n new ModelMBeanConstructorInfo[0],\n extractOperationInfo(o),\n new ModelMBeanNotificationInfo[0]);\n mbean.setModelMBeanInfo(info);\n mbean.setManagedResource(o, \"ObjectReference\");\n\n return mbean;\n } catch(MBeanException e) {\n throw new VoldemortException(e);\n } catch(InvalidTargetObjectTypeException e) {\n throw new VoldemortException(e);\n } catch(InstanceNotFoundException e) {\n throw new VoldemortException(e);\n }\n }",
"public void postDoNotUseArtifact(final String gavc, final Boolean doNotUse, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getDoNotUseArtifact(gavc));\n final ClientResponse response = resource.queryParam(ServerAPI.DO_NOT_USE, doNotUse.toString())\n .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to post do not use artifact\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }",
"public void updateMetadataVersions() {\n Properties versionProps = MetadataVersionStoreUtils.getProperties(this.systemStoreRepository.getMetadataVersionStore());\n Long newVersion = fetchNewVersion(SystemStoreConstants.CLUSTER_VERSION_KEY,\n null,\n versionProps);\n if(newVersion != null) {\n this.currentClusterVersion = newVersion;\n }\n }",
"public Reply getReplyInfo(String topicId, String replyId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_REPLIES_GET_INFO);\r\n parameters.put(\"topic_id\", topicId);\r\n parameters.put(\"reply_id\", replyId);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element replyElement = response.getPayload();\r\n\r\n return parseReply(replyElement);\r\n }",
"private ColorItem buildColorItem(int colorId, String label) {\n Color color;\n String colorName;\n switch (colorId) {\n case 0:\n color = new Color(0, 0, 0, 0);\n colorName = \"No Color\";\n break;\n case 1:\n color = Color.PINK;\n colorName = \"Pink\";\n break;\n case 2:\n color = Color.RED;\n colorName = \"Red\";\n break;\n case 3:\n color = Color.ORANGE;\n colorName = \"Orange\";\n break;\n case 4:\n color = Color.YELLOW;\n colorName = \"Yellow\";\n break;\n case 5:\n color = Color.GREEN;\n colorName = \"Green\";\n break;\n case 6:\n color = Color.CYAN;\n colorName = \"Aqua\";\n break;\n case 7:\n color = Color.BLUE;\n colorName = \"Blue\";\n break;\n case 8:\n color = new Color(128, 0, 128);\n colorName = \"Purple\";\n break;\n default:\n color = new Color(0, 0, 0, 0);\n colorName = \"Unknown Color\";\n }\n return new ColorItem(colorId, label, color, colorName);\n }",
"@Override\r\n public String upload(File file, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(file);\r\n return sendUploadRequest(metaData, payload);\r\n }",
"public static base_responses save(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 saveresources[] = new cacheobject[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tsaveresources[i] = new cacheobject();\n\t\t\t\tsaveresources[i].locator = resources[i].locator;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, saveresources,\"save\");\n\t\t}\n\t\treturn result;\n\t}",
"public void fillFromToWith(int from, int to, Object val) {\r\n\tcheckRangeFromTo(from,to,this.size);\r\n\tfor (int i=from; i<=to;) setQuick(i++,val); \r\n}",
"public static boolean isPartOfRegularEmbedded(String[] keyColumnNames, String column) {\n\t\treturn isPartOfEmbedded( column ) && !ArrayHelper.contains( keyColumnNames, column );\n\t}"
] |
Check, if all values used for calculating the series for a specific pattern are valid.
@return <code>null</code> if the pattern is valid, a suitable error message otherwise. | [
"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 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}",
"public Node createEmbedded(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\tResult result = executionEngine.execute( getCreateEmbeddedNodeQuery(), params );\n\t\treturn singleResult( result );\n\t}",
"public static int getHostSegmentIndex(int networkPrefixLength, int bytesPerSegment, int bitsPerSegment) {\n\t\tif(bytesPerSegment > 1) {\n\t\t\tif(bytesPerSegment == 2) {\n\t\t\t\treturn networkPrefixLength >> 4;\n\t\t\t}\n\t\t\treturn networkPrefixLength / bitsPerSegment;\n\t\t}\n\t\treturn networkPrefixLength >> 3;\n\t}",
"private String buildAliasKey(String aPath, List hintClasses)\r\n {\r\n if (hintClasses == null || hintClasses.isEmpty())\r\n {\r\n return aPath;\r\n }\r\n \r\n StringBuffer buf = new StringBuffer(aPath);\r\n for (Iterator iter = hintClasses.iterator(); iter.hasNext();)\r\n {\r\n Class hint = (Class) iter.next();\r\n buf.append(\" \");\r\n buf.append(hint.getName());\r\n }\r\n return buf.toString();\r\n }",
"public static Enum castToEnum(Object object, Class<? extends Enum> type) {\n if (object==null) return null;\n if (type.isInstance(object)) return (Enum) object;\n if (object instanceof String || object instanceof GString) {\n return Enum.valueOf(type, object.toString());\n }\n throw new GroovyCastException(object, type);\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 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 LocalDateTime getDateFromFloatingPointDate(LocalDateTime referenceDate, double floatingPointDate) {\n\t\tif(referenceDate == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tDuration duration = Duration.ofSeconds(Math.round(floatingPointDate * SECONDS_PER_DAY));\n\t\treturn referenceDate.plus(duration);\n\t}",
"public synchronized void addShutdownListener(ShutdownListener listener) {\n if (state == CLOSED) {\n listener.handleCompleted();\n } else {\n listeners.add(listener);\n }\n }"
] |
Sets the value for the API's "sitefilter" parameter based on the current
settings.
@param properties
current setting of parameters | [
"private void setRequestSitefilter(WbGetEntitiesActionData properties) {\n\t\tif (this.filter.excludeAllSiteLinks()\n\t\t\t\t|| this.filter.getSiteLinkFilter() == null) {\n\t\t\treturn;\n\t\t}\n\t\tproperties.sitefilter = ApiConnection.implodeObjects(this.filter\n\t\t\t\t.getSiteLinkFilter());\n\t}"
] | [
"public static String join(Collection<String> s, String delimiter) {\r\n return join(s, delimiter, false);\r\n }",
"private String jsonifyData(Map<String, ? extends Object> data) {\n JSONObject jsonData = new JSONObject(data);\n\n return jsonData.toString();\n }",
"public synchronized void insert(long data) {\n resetIfNeeded();\n long index = 0;\n if(data >= this.upperBound) {\n index = nBuckets - 1;\n } else if(data < 0) {\n logger.error(data + \" can't be bucketed because it is negative!\");\n return;\n } else {\n index = data / step;\n }\n if(index < 0 || index >= nBuckets) {\n // This should be dead code. Defending against code changes in\n // future.\n logger.error(data + \" can't be bucketed because index is not in range [0,nBuckets).\");\n return;\n }\n buckets[(int) index]++;\n sum += data;\n size++;\n }",
"public static <T> void finish(T query, long correlationId, EventBus bus, String... labels) {\n for (String type : labels) {\n RemoveLabelledQuery<T> next = finish(query, correlationId, type);\n bus.post(next);\n }\n }",
"public GVRShader getTemplate(GVRContext ctx)\n {\n if (mShaderTemplate == null)\n {\n mShaderTemplate = makeTemplate(ID, ctx);\n ctx.getShaderManager().addShaderID(this);\n }\n return mShaderTemplate;\n }",
"public static int wavelengthToRGB(float wavelength) {\n\t\tfloat gamma = 0.80f;\n\t\tfloat r, g, b, factor;\n\n\t\tint w = (int)wavelength;\n\t\tif (w < 380) {\n\t\t\tr = 0.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t} else if (w < 440) {\n\t\t\tr = -(wavelength - 440) / (440 - 380);\n\t\t\tg = 0.0f;\n\t\t\tb = 1.0f;\n\t\t} else if (w < 490) {\n\t\t\tr = 0.0f;\n\t\t\tg = (wavelength - 440) / (490 - 440);\n\t\t\tb = 1.0f;\n\t\t} else if (w < 510) {\n\t\t\tr = 0.0f;\n\t\t\tg = 1.0f;\n\t\t\tb = -(wavelength - 510) / (510 - 490);\n\t\t} else if (w < 580) {\n\t\t\tr = (wavelength - 510) / (580 - 510);\n\t\t\tg = 1.0f;\n\t\t\tb = 0.0f;\n\t\t} else if (w < 645) {\n\t\t\tr = 1.0f;\n\t\t\tg = -(wavelength - 645) / (645 - 580);\n\t\t\tb = 0.0f;\n\t\t} else if (w <= 780) {\n\t\t\tr = 1.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t} else {\n\t\t\tr = 0.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t}\n\n\t\t// Let the intensity fall off near the vision limits\n\t\tif (380 <= w && w <= 419)\n\t\t\tfactor = 0.3f + 0.7f*(wavelength - 380) / (420 - 380);\n\t\telse if (420 <= w && w <= 700)\n\t\t\tfactor = 1.0f;\n\t\telse if (701 <= w && w <= 780)\n\t\t\tfactor = 0.3f + 0.7f*(780 - wavelength) / (780 - 700);\n\t\telse\n\t\t\tfactor = 0.0f;\n\n\t\tint ir = adjust(r, factor, gamma);\n\t\tint ig = adjust(g, factor, gamma);\n\t\tint ib = adjust(b, factor, gamma);\n\n\t\treturn 0xff000000 | (ir << 16) | (ig << 8) | ib;\n\t}",
"public DbLicense getLicense(final String name) {\n final DbLicense license = repoHandler.getLicense(name);\n\n if (license == null) {\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"License \" + name + \" does not exist.\").build());\n }\n\n return license;\n }",
"public ResponseOnSingeRequest genErrorResponse(Exception t) {\n ResponseOnSingeRequest sshResponse = new ResponseOnSingeRequest();\n String displayError = PcErrorMsgUtils.replaceErrorMsg(t.toString());\n\n sshResponse.setStackTrace(PcStringUtils.printStackTrace(t));\n sshResponse.setErrorMessage(displayError);\n sshResponse.setFailObtainResponse(true);\n\n logger.error(\"error in exec SSH. \\nIf exection is JSchException: \"\n + \"Auth cancel and using public key. \"\n + \"\\nMake sure 1. private key full path is right (try sshMeta.getPrivKeyAbsPath()). \"\n + \"\\n2. the user name and key matches \" + t);\n\n return sshResponse;\n }",
"private Component createAddKeyButton() {\n\n // the \"+\" button\n Button addKeyButton = new Button();\n addKeyButton.addStyleName(\"icon-only\");\n addKeyButton.addStyleName(\"borderless-colored\");\n addKeyButton.setDescription(m_messages.key(Messages.GUI_ADD_KEY_0));\n addKeyButton.setIcon(FontOpenCms.CIRCLE_PLUS, m_messages.key(Messages.GUI_ADD_KEY_0));\n addKeyButton.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n handleAddKey();\n\n }\n });\n return addKeyButton;\n }"
] |
Given a string with the scenario or story name, creates a Class Name with
no spaces and first letter capital
@param String
- The name of the scenario/story. It should be in lower case.
@returns String - The class name | [
"public static String createClassName(String scenarioDescription) {\n String[] words = scenarioDescription.trim().split(\" \");\n String name = \"\";\n for (int i = 0; i < words.length; i++) {\n name += changeFirstLetterToCapital(words[i]);\n }\n return name;\n }"
] | [
"public void forAllIndices(String template, Properties attributes) throws XDocletException\r\n {\r\n boolean processUnique = TypeConversionUtil.stringToBoolean(attributes.getProperty(ATTRIBUTE_UNIQUE), false);\r\n\r\n // first the default index\r\n _curIndexDef = _curTableDef.getIndex(null);\r\n if ((_curIndexDef != null) && (processUnique == _curIndexDef.isUnique()))\r\n {\r\n generate(template);\r\n }\r\n for (Iterator it = _curTableDef.getIndices(); it.hasNext(); )\r\n {\r\n _curIndexDef = (IndexDef)it.next();\r\n if (!_curIndexDef.isDefault() && (processUnique == _curIndexDef.isUnique()))\r\n { \r\n generate(template);\r\n }\r\n }\r\n _curIndexDef = null;\r\n }",
"@GwtIncompatible(\"Class.getDeclaredFields\")\n\tpublic ToStringBuilder addDeclaredFields() {\n\t\tField[] fields = instance.getClass().getDeclaredFields();\n\t\tfor(Field field : fields) {\n\t\t\taddField(field);\n\t\t}\n\t\treturn this;\n\t}",
"public void restartDyno(String appName, String dynoId) {\n connection.execute(new DynoRestart(appName, dynoId), apiKey);\n }",
"private byte[] assembleValues(List<Versioned<byte[]>> values) throws IOException {\n\n ByteArrayOutputStream stream = new ByteArrayOutputStream();\n DataOutputStream dataStream = new DataOutputStream(stream);\n\n for(Versioned<byte[]> value: values) {\n byte[] object = value.getValue();\n dataStream.writeInt(object.length);\n dataStream.write(object);\n\n VectorClock clock = (VectorClock) value.getVersion();\n dataStream.writeInt(clock.sizeInBytes());\n dataStream.write(clock.toBytes());\n }\n\n return stream.toByteArray();\n }",
"private Path getPath(PropertyWriter writer, JsonStreamContext sc) {\n LinkedList<PathElement> elements = new LinkedList<>();\n\n if (sc != null) {\n elements.add(new PathElement(writer.getName(), sc.getCurrentValue()));\n sc = sc.getParent();\n }\n\n while (sc != null) {\n if (sc.getCurrentName() != null && sc.getCurrentValue() != null) {\n elements.addFirst(new PathElement(sc.getCurrentName(), sc.getCurrentValue()));\n }\n sc = sc.getParent();\n }\n\n return new Path(elements);\n }",
"public boolean isFinished(final ProcessorGraphNode processorGraphNode) {\n this.processorLock.lock();\n try {\n return this.executedProcessors.containsKey(processorGraphNode.getProcessor());\n } finally {\n this.processorLock.unlock();\n }\n }",
"@Override\n public void join(final long millis) throws InterruptedException {\n for (final Thread thread : this.threads) {\n thread.join(millis);\n }\n }",
"private void getYearlyDates(Calendar calendar, List<Date> dates)\n {\n if (m_relative)\n {\n getYearlyRelativeDates(calendar, dates);\n }\n else\n {\n getYearlyAbsoluteDates(calendar, dates);\n }\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 }"
] |
Gets a list of any tasks on this file with requested fields.
@param fields optional fields to retrieve for this task.
@return a list of tasks on this file. | [
"public List<BoxTask.Info> getTasks(String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n URL url = GET_TASKS_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n List<BoxTask.Info> tasks = new ArrayList<BoxTask.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject taskJSON = value.asObject();\n BoxTask task = new BoxTask(this.getAPI(), taskJSON.get(\"id\").asString());\n BoxTask.Info info = task.new Info(taskJSON);\n tasks.add(info);\n }\n\n return tasks;\n }"
] | [
"public List<Index<Field>> allIndexes() {\n List<Index<Field>> indexesOfAnyType = new ArrayList<Index<Field>>();\n indexesOfAnyType.addAll(listIndexType(null, ListableIndex.class));\n return indexesOfAnyType;\n }",
"public com.groupon.odo.proxylib.models.Method getMethodForOverrideId(int overrideId) {\n com.groupon.odo.proxylib.models.Method method = null;\n\n // special case for IDs < 0\n if (overrideId < 0) {\n method = new com.groupon.odo.proxylib.models.Method();\n method.setId(overrideId);\n\n if (method.getId() == Constants.PLUGIN_RESPONSE_OVERRIDE_CUSTOM ||\n method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_ADD ||\n method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_REMOVE) {\n method.setMethodType(Constants.PLUGIN_TYPE_RESPONSE_OVERRIDE);\n } else {\n method.setMethodType(Constants.PLUGIN_TYPE_REQUEST_OVERRIDE);\n }\n } else {\n // get method information from the database\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, overrideId);\n results = queryStatement.executeQuery();\n\n if (results.next()) {\n method = new com.groupon.odo.proxylib.models.Method();\n method.setClassName(results.getString(Constants.OVERRIDE_CLASS_NAME));\n method.setMethodName(results.getString(Constants.OVERRIDE_METHOD_NAME));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n return null;\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 // if method is still null then just return\n if (method == null) {\n return method;\n }\n\n // now get the rest of the data from the plugin manager\n // this gets all of the actual method data\n try {\n method = PluginManager.getInstance().getMethod(method.getClassName(), method.getMethodName());\n method.setId(overrideId);\n } catch (Exception e) {\n // there was some problem.. return null\n return null;\n }\n }\n\n return method;\n }",
"public void close()\t{\n\t\tif (watchdog != null) {\n\t\t\twatchdog.cancel();\n\t\t\twatchdog = null;\n\t\t}\n\t\t\n\t\tdisconnect();\n\t\t\n\t\t// clear nodes collection and send queue\n\t\tfor (Object listener : this.zwaveEventListeners.toArray()) {\n\t\t\tif (!(listener instanceof ZWaveNode))\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tthis.zwaveEventListeners.remove(listener);\n\t\t}\n\t\t\n\t\tthis.zwaveNodes.clear();\n\t\tthis.sendQueue.clear();\n\t\t\n\t\tlogger.info(\"Stopped Z-Wave controller\");\n\t}",
"protected void removeEmptyDirectories(File outputDirectory)\n {\n if (outputDirectory.exists())\n {\n for (File file : outputDirectory.listFiles(new EmptyDirectoryFilter()))\n {\n file.delete();\n }\n }\n }",
"public T transitInt(int propertyId, int... vals) {\n String property = getPropertyName(propertyId);\n mHolders.put(propertyId, PropertyValuesHolder.ofInt(property, vals));\n mShadowHolders.put(propertyId, ShadowValuesHolder.ofInt(property, vals));\n return self();\n }",
"private void readTasks(Project gpProject)\n {\n Tasks tasks = gpProject.getTasks();\n readTaskCustomPropertyDefinitions(tasks);\n for (net.sf.mpxj.ganttproject.schema.Task task : tasks.getTask())\n {\n readTask(m_projectFile, task);\n }\n }",
"public IdRange[] parseIdRange(ImapRequestLineReader request)\n throws ProtocolException {\n CharacterValidator validator = new MessageSetCharValidator();\n String nextWord = consumeWord(request, validator);\n\n int commaPos = nextWord.indexOf(',');\n if (commaPos == -1) {\n return new IdRange[]{IdRange.parseRange(nextWord)};\n }\n\n List<IdRange> rangeList = new ArrayList<>();\n int pos = 0;\n while (commaPos != -1) {\n String range = nextWord.substring(pos, commaPos);\n IdRange set = IdRange.parseRange(range);\n rangeList.add(set);\n\n pos = commaPos + 1;\n commaPos = nextWord.indexOf(',', pos);\n }\n String range = nextWord.substring(pos);\n rangeList.add(IdRange.parseRange(range));\n return rangeList.toArray(new IdRange[rangeList.size()]);\n }",
"public void retrieveEngine() throws GeneralSecurityException, IOException {\n if (serverEngineFactory == null) {\n return;\n }\n engine = serverEngineFactory.retrieveHTTPServerEngine(nurl.getPort());\n if (engine == null) {\n engine = serverEngineFactory.getHTTPServerEngine(nurl.getHost(), nurl.getPort(), nurl.getProtocol());\n }\n\n assert engine != null;\n TLSServerParameters serverParameters = engine.getTlsServerParameters();\n if (serverParameters != null && serverParameters.getCertConstraints() != null) {\n CertificateConstraintsType constraints = serverParameters.getCertConstraints();\n if (constraints != null) {\n certConstraints = CertConstraintsJaxBUtils.createCertConstraints(constraints);\n }\n }\n\n // When configuring for \"http\", however, it is still possible that\n // Spring configuration has configured the port for https.\n if (!nurl.getProtocol().equals(engine.getProtocol())) {\n throw new IllegalStateException(\"Port \" + engine.getPort() + \" is configured with wrong protocol \\\"\" + engine.getProtocol() + \"\\\" for \\\"\" + nurl + \"\\\"\");\n }\n }",
"public PartialCollection<BoxItem.Info> getItemsRange(long offset, long limit, String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder()\n .appendParam(\"offset\", offset)\n .appendParam(\"limit\", limit);\n\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n\n URL url = GET_COLLECTION_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), builder.toString(), getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n String totalCountString = responseJSON.get(\"total_count\").toString();\n long fullSize = Double.valueOf(totalCountString).longValue();\n PartialCollection<BoxItem.Info> items = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue entry : entries) {\n BoxItem.Info entryInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), entry.asObject());\n if (entryInfo != null) {\n items.add(entryInfo);\n }\n }\n return items;\n }"
] |
removes an Object from the cache.
@param oid the Identity of the object to be removed. | [
"public void remove(Identity oid)\r\n {\r\n try\r\n {\r\n jcsCache.remove(oid.toString());\r\n }\r\n catch (CacheException e)\r\n {\r\n throw new RuntimeCacheException(e.getMessage());\r\n }\r\n }"
] | [
"public void sendSyncModeCommand(int deviceNumber, boolean synced) throws IOException {\n final DeviceUpdate update = getLatestStatusFor(deviceNumber);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + deviceNumber + \" not found on network.\");\n }\n sendSyncModeCommand(update, synced);\n }",
"public static String getFilename(String path) throws IllegalArgumentException {\n if (Pattern.matches(sPatternUrl, path))\n return getURLFilename(path);\n\n return new File(path).getName();\n }",
"public static long makeReasonable(long expectedTimeoutMillis, long bufferMillis) {\n checkArgument(expectedTimeoutMillis > 0,\n \"expectedTimeoutMillis: %s (expected: > 0)\", expectedTimeoutMillis);\n checkArgument(bufferMillis >= 0,\n \"bufferMillis: %s (expected: > 0)\", bufferMillis);\n\n final long timeout = Math.min(expectedTimeoutMillis, MAX_MILLIS);\n if (bufferMillis == 0) {\n return timeout;\n }\n\n if (timeout > MAX_MILLIS - bufferMillis) {\n return MAX_MILLIS;\n } else {\n return bufferMillis + timeout;\n }\n }",
"synchronized void removeUserProfile(String id) {\n\n if (id == null) return;\n final String tableName = Table.USER_PROFILES.getName();\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n db.delete(tableName, \"_id = ?\", new String[]{id});\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error removing user profile from \" + tableName + \" Recreating DB\");\n dbHelper.deleteDatabase();\n } finally {\n dbHelper.close();\n }\n }",
"public HttpRequestFactory makeClient(DatastoreOptions options) {\n Credential credential = options.getCredential();\n HttpTransport transport = options.getTransport();\n if (transport == null) {\n transport = credential == null ? new NetHttpTransport() : credential.getTransport();\n transport = transport == null ? new NetHttpTransport() : transport;\n }\n return transport.createRequestFactory(credential);\n }",
"protected void closeServerSocket() {\n // Close server socket, we do not accept new requests anymore.\n // This also terminates the server thread if blocking on socket.accept.\n if (null != serverSocket) {\n try {\n if (!serverSocket.isClosed()) {\n serverSocket.close();\n if (log.isTraceEnabled()) {\n log.trace(\"Closed server socket \" + serverSocket + \"/ref=\"\n + Integer.toHexString(System.identityHashCode(serverSocket))\n + \" for \" + getName());\n }\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Failed to successfully quit server \" + getName(), e);\n }\n }\n }",
"private void processChildTasks(Task parentTask) throws SQLException\n {\n List<Row> rows = getRows(\"select * from zscheduleitem where zparentactivity_=? and z_ent=? order by zorderinparentactivity\", parentTask.getUniqueID(), m_entityMap.get(\"Activity\"));\n for (Row row : rows)\n {\n Task task = parentTask.addTask();\n populateTask(row, task);\n processChildTasks(task);\n }\n }",
"private boolean processQueue(K key) {\n Queue<AsyncResourceRequest<V>> requestQueue = getRequestQueueForKey(key);\n if(requestQueue.isEmpty()) {\n return false;\n }\n\n // Attempt to get a resource.\n Pool<V> resourcePool = getResourcePoolForKey(key);\n V resource = null;\n Exception ex = null;\n try {\n // Must attempt non-blocking checkout to ensure resources are\n // created for the pool.\n resource = attemptNonBlockingCheckout(key, resourcePool);\n } catch(Exception e) {\n destroyResource(key, resourcePool, resource);\n ex = e;\n resource = null;\n }\n // Neither we got a resource, nor an exception. So no requests can be\n // processed return\n if(resource == null && ex == null) {\n return false;\n }\n\n // With resource in hand, process the resource requests\n AsyncResourceRequest<V> resourceRequest = getNextUnexpiredResourceRequest(requestQueue);\n if(resourceRequest == null) {\n if(resource != null) {\n // Did not use the resource! Directly check in via super to\n // avoid\n // circular call to processQueue().\n try {\n super.checkin(key, resource);\n } catch(Exception e) {\n logger.error(\"Exception checking in resource: \", e);\n }\n } else {\n // Poor exception, no request to tag this exception onto\n // drop it on the floor and continue as usual.\n }\n return false;\n } else {\n // We have a request here.\n if(resource != null) {\n resourceRequest.useResource(resource);\n } else {\n resourceRequest.handleException(ex);\n }\n return true;\n }\n }",
"private String type(Options opt, Type t, boolean generics) {\n\treturn ((generics ? opt.showQualifiedGenerics : opt.showQualified) ? //\n\t\tt.qualifiedTypeName() : t.typeName()) //\n\t\t+ (opt.hideGenerics ? \"\" : typeParameters(opt, t.asParameterizedType()));\n }"
] |
Creates the HikariCP configuration based on the configuration of a pool defined in opencms.properties.
@param config the configuration object with the properties
@param key the pool name (without the opencms prefix)
@return the HikariCP configuration for the pool | [
"public static HikariConfig createHikariConfig(CmsParameterConfiguration config, String key) {\n\n Map<String, String> poolMap = Maps.newHashMap();\n for (Map.Entry<String, String> entry : config.entrySet()) {\n String suffix = getPropertyRelativeSuffix(KEY_DATABASE_POOL + \".\" + key, entry.getKey());\n if ((suffix != null) && !CmsStringUtil.isEmptyOrWhitespaceOnly(entry.getValue())) {\n String value = entry.getValue().trim();\n poolMap.put(suffix, value);\n }\n }\n\n // these are for backwards compatibility , all other properties not of the form db.pool.poolname.v11..... are ignored\n String jdbcUrl = poolMap.get(KEY_JDBC_URL);\n String params = poolMap.get(KEY_JDBC_URL_PARAMS);\n String driver = poolMap.get(KEY_JDBC_DRIVER);\n String user = poolMap.get(KEY_USERNAME);\n String password = poolMap.get(KEY_PASSWORD);\n String poolName = OPENCMS_URL_PREFIX + key;\n\n if ((params != null) && (jdbcUrl != null)) {\n jdbcUrl += params;\n }\n\n Properties hikariProps = new Properties();\n\n if (jdbcUrl != null) {\n hikariProps.put(\"jdbcUrl\", jdbcUrl);\n }\n if (driver != null) {\n hikariProps.put(\"driverClassName\", driver);\n }\n if (user != null) {\n user = OpenCms.getCredentialsResolver().resolveCredential(I_CmsCredentialsResolver.DB_USER, user);\n hikariProps.put(\"username\", user);\n }\n if (password != null) {\n password = OpenCms.getCredentialsResolver().resolveCredential(\n I_CmsCredentialsResolver.DB_PASSWORD,\n password);\n hikariProps.put(\"password\", password);\n }\n\n hikariProps.put(\"maximumPoolSize\", \"30\");\n\n // Properties of the form db.pool.poolname.v11.<foo> are directly passed to HikariCP as <foo>\n for (Map.Entry<String, String> entry : poolMap.entrySet()) {\n String suffix = getPropertyRelativeSuffix(\"v11\", entry.getKey());\n if (suffix != null) {\n hikariProps.put(suffix, entry.getValue());\n }\n }\n\n String configuredTestQuery = (String)(hikariProps.get(\"connectionTestQuery\"));\n String testQueryForDriver = testQueries.get(driver);\n if ((testQueryForDriver != null) && CmsStringUtil.isEmptyOrWhitespaceOnly(configuredTestQuery)) {\n hikariProps.put(\"connectionTestQuery\", testQueryForDriver);\n }\n hikariProps.put(\"registerMbeans\", \"true\");\n HikariConfig result = new HikariConfig(hikariProps);\n\n result.setPoolName(poolName.replace(\":\", \"_\"));\n return result;\n }"
] | [
"private void ensureElementClassRef(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String arrayElementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ARRAY_ELEMENT_CLASS_REF);\r\n\r\n if (!collDef.hasProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF))\r\n {\r\n if (arrayElementClassName != null)\r\n {\r\n // we use the array element type\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF, arrayElementClassName);\r\n }\r\n else\r\n {\r\n throw new ConstraintException(\"Collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" does not specify its element class\");\r\n }\r\n }\r\n\r\n // now checking the element type\r\n ModelDef model = (ModelDef)collDef.getOwner().getOwner();\r\n String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);\r\n ClassDescriptorDef elementClassDef = model.getClass(elementClassName);\r\n\r\n if (elementClassDef == null)\r\n {\r\n throw new ConstraintException(\"Collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" references an unknown class \"+elementClassName);\r\n }\r\n if (!elementClassDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_OJB_PERSISTENT, false))\r\n {\r\n throw new ConstraintException(\"The element class \"+elementClassName+\" of the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" is not persistent\");\r\n }\r\n if (CHECKLEVEL_STRICT.equals(checkLevel) && (arrayElementClassName != null))\r\n {\r\n // specified element class must be a subtype of the element type\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(elementClassDef, arrayElementClassName, true))\r\n {\r\n throw new ConstraintException(\"The element class \"+elementClassName+\" of the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" is not the same or a subtype of the array base type \"+arrayElementClassName);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName());\r\n }\r\n }\r\n // we're adjusting the property to use the classloader-compatible form\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF, elementClassDef.getName());\r\n }",
"static Style get(final GridParam params) {\n final StyleBuilder builder = new StyleBuilder();\n\n final Symbolizer pointSymbolizer = crossSymbolizer(\"shape://plus\", builder, CROSS_SIZE,\n params.gridColor);\n final Style style = builder.createStyle(pointSymbolizer);\n final List<Symbolizer> symbolizers = style.featureTypeStyles().get(0).rules().get(0).symbolizers();\n\n if (params.haloRadius > 0.0) {\n Symbolizer halo = crossSymbolizer(\"cross\", builder, CROSS_SIZE + params.haloRadius * 2.0,\n params.haloColor);\n symbolizers.add(0, halo);\n }\n\n return style;\n }",
"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 }",
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher deleteFacet(String... attributes) {\n for (String attribute : attributes) {\n facetRequestCount.put(attribute, 0);\n facets.remove(attribute);\n }\n rebuildQueryFacets();\n return this;\n }",
"private byte[] createErrorImage(int width, int height, Exception e) throws IOException {\n\t\tString error = e.getMessage();\n\t\tif (null == error) {\n\t\t\tWriter result = new StringWriter();\n\t\t\tPrintWriter printWriter = new PrintWriter(result);\n\t\t\te.printStackTrace(printWriter);\n\t\t\terror = result.toString();\n\t\t}\n\n\t\tBufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);\n\t\tGraphics2D g = (Graphics2D) image.getGraphics();\n\n\t\tg.setColor(Color.RED);\n\t\tg.drawString(error, ERROR_MESSAGE_X, height / 2);\n\n\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\t\tImageIO.write(image, \"PNG\", out);\n\t\tout.flush();\n\t\tbyte[] result = out.toByteArray();\n\t\tout.close();\n\n\t\treturn result;\n\t}",
"public CollectionRequest<ProjectStatus> findByProject(String project) {\n\n String path = String.format(\"/projects/%s/project_statuses\", project);\n return new CollectionRequest<ProjectStatus>(this, ProjectStatus.class, path, \"GET\");\n }",
"public static void enableHost(String hostName) throws Exception {\n Registry myRegistry = LocateRegistry.getRegistry(\"127.0.0.1\", port);\n com.groupon.odo.proxylib.hostsedit.rmi.Message impl = (com.groupon.odo.proxylib.hostsedit.rmi.Message) myRegistry.lookup(SERVICE_NAME);\n\n impl.enableHost(hostName);\n }",
"public int createPartitions(String topic, int partitionNum, boolean enlarge) throws IOException {\n KV<Receive, ErrorMapping> response = send(new CreaterRequest(topic, partitionNum, enlarge));\n return Utils.deserializeIntArray(response.k.buffer())[0];\n }",
"protected void checkProducerMethod(EnhancedAnnotatedMethod<T, ? super X> method) {\n if (method.getEnhancedParameters(Observes.class).size() > 0) {\n throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, \"@Observes\", this.method,\n Formats.formatAsStackTraceElement(method.getJavaMember()));\n } else if (method.getEnhancedParameters(ObservesAsync.class).size() > 0) {\n throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, \"@ObservesAsync\", this.method,\n Formats.formatAsStackTraceElement(method.getJavaMember()));\n } else if (method.getEnhancedParameters(Disposes.class).size() > 0) {\n throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, \"@Disposes\", this.method,\n Formats.formatAsStackTraceElement(method.getJavaMember()));\n } else if (getDeclaringBean() instanceof SessionBean<?> && !Modifier.isStatic(method.slim().getJavaMember().getModifiers())) {\n boolean methodDeclaredOnTypes = false;\n for (Type type : getDeclaringBean().getTypes()) {\n Class<?> clazz = Reflections.getRawType(type);\n try {\n AccessController.doPrivileged(new GetMethodAction(clazz, method.getName(), method.getParameterTypesAsArray()));\n methodDeclaredOnTypes = true;\n break;\n } catch (PrivilegedActionException ignored) {\n }\n }\n if (!methodDeclaredOnTypes) {\n throw BeanLogger.LOG.methodNotBusinessMethod(\"Producer\", this, getDeclaringBean(), Formats.formatAsStackTraceElement(method.getJavaMember()));\n }\n }\n }"
] |
Subtract two complex numbers.
@param z1 Complex Number.
@param z2 Complex Number.
@return Returns new ComplexNumber instance containing the subtract of specified complex numbers. | [
"public static ComplexNumber Subtract(ComplexNumber z1, ComplexNumber z2) {\r\n return new ComplexNumber(z1.real - z2.real, z1.imaginary - z2.imaginary);\r\n }"
] | [
"public String toNormalizedString(boolean keepMixed, IPv6StringOptions params) {\n\t\tif(keepMixed && fromString != null && getAddressfromString().isMixedIPv6() && !params.makeMixed()) {\n\t\t\tparams = new IPv6StringOptions(\n\t\t\t\t\tparams.base,\n\t\t\t\t\tparams.expandSegments,\n\t\t\t\t\tparams.wildcardOption,\n\t\t\t\t\tparams.wildcards,\n\t\t\t\t\tparams.segmentStrPrefix,\n\t\t\t\t\ttrue,\n\t\t\t\t\tparams.ipv4Opts,\n\t\t\t\t\tparams.compressOptions,\n\t\t\t\t\tparams.separator,\n\t\t\t\t\tparams.zoneSeparator,\n\t\t\t\t\tparams.addrLabel,\n\t\t\t\t\tparams.addrSuffix,\n\t\t\t\t\tparams.reverse,\n\t\t\t\t\tparams.splitDigits,\n\t\t\t\t\tparams.uppercase);\n\t\t}\n\t\treturn toNormalizedString(params);\n\t}",
"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}",
"public Build createBuild(String appName, Build build) {\n return connection.execute(new BuildCreate(appName, build), apiKey);\n }",
"private boolean checkAndSetManifestAndImagePathCandidates(String manifestPath, String candidateImagePath, ArtifactoryDependenciesClient dependenciesClient, TaskListener listener) throws IOException {\n String candidateManifest = getManifestFromArtifactory(dependenciesClient, manifestPath);\n if (candidateManifest == null) {\n return false;\n }\n\n String imageDigest = DockerUtils.getConfigDigest(candidateManifest);\n if (imageDigest.equals(imageId)) {\n manifest = candidateManifest;\n imagePath = candidateImagePath;\n return true;\n }\n\n listener.getLogger().println(String.format(\"Found incorrect manifest.json file in Artifactory in the following path: %s\\nExpecting: %s got: %s\", manifestPath, imageId, imageDigest));\n return false;\n }",
"public 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 String getTemplateAsString(String fileName) throws IOException {\n // in .jar file\n String fNameJar = getFileNameInPath(fileName);\n InputStream inStream = DomUtils.class.getResourceAsStream(\"/\"\n + fNameJar);\n if (inStream == null) {\n // try to find file normally\n File f = new File(fileName);\n if (f.exists()) {\n inStream = new FileInputStream(f);\n } else {\n throw new IOException(\"Cannot find \" + fileName + \" or \"\n + fNameJar);\n }\n }\n\n BufferedReader bufferedReader = new BufferedReader(\n new InputStreamReader(inStream));\n String line;\n StringBuilder stringBuilder = new StringBuilder();\n\n while ((line = bufferedReader.readLine()) != null) {\n stringBuilder.append(line).append(\"\\n\");\n }\n\n bufferedReader.close();\n return stringBuilder.toString();\n }",
"public HashMap<String, String> getProperties() {\n if (this.properties == null) {\n this.properties = new HashMap<String, String>();\n }\n return properties;\n }",
"public void add(final String source, final T destination) {\n\n // replace multiple slashes with a single slash.\n String path = source.replaceAll(\"/+\", \"/\");\n\n path = (path.endsWith(\"/\") && path.length() > 1)\n ? path.substring(0, path.length() - 1) : path;\n\n\n String[] parts = path.split(\"/\", maxPathParts + 2);\n if (parts.length - 1 > maxPathParts) {\n throw new IllegalArgumentException(String.format(\"Number of parts of path %s exceeds allowed limit %s\",\n source, maxPathParts));\n }\n StringBuilder sb = new StringBuilder();\n List<String> groupNames = new ArrayList<>();\n\n for (String part : parts) {\n Matcher groupMatcher = GROUP_PATTERN.matcher(part);\n if (groupMatcher.matches()) {\n groupNames.add(groupMatcher.group(1));\n sb.append(\"([^/]+?)\");\n } else if (WILD_CARD_PATTERN.matcher(part).matches()) {\n sb.append(\".*?\");\n } else {\n sb.append(part);\n }\n sb.append(\"/\");\n }\n\n //Ignore the last \"/\"\n sb.setLength(sb.length() - 1);\n\n Pattern pattern = Pattern.compile(sb.toString());\n patternRouteList.add(ImmutablePair.of(pattern, new RouteDestinationWithGroups(destination, groupNames)));\n }",
"public Tuple get(RowKey key) {\n\t\tAssociationOperation result = currentState.get( key );\n\t\tif ( result == null ) {\n\t\t\treturn cleared ? null : snapshot.get( key );\n\t\t}\n\t\telse if ( result.getType() == REMOVE ) {\n\t\t\treturn null;\n\t\t}\n\t\treturn result.getValue();\n\t}"
] |
Concatenate all the arrays in the list into a vector.
@param arrays List of arrays.
@return Vector. | [
"public static int[] ConcatenateInt(List<int[]> arrays) {\n\n int size = 0;\n for (int i = 0; i < arrays.size(); i++) {\n size += arrays.get(i).length;\n }\n\n int[] all = new int[size];\n int idx = 0;\n\n for (int i = 0; i < arrays.size(); i++) {\n int[] v = arrays.get(i);\n for (int j = 0; j < v.length; j++) {\n all[idx++] = v[i];\n }\n }\n\n return all;\n }"
] | [
"public ParallelTask getTaskFromInProgressMap(String jobId) {\n if (!inprogressTaskMap.containsKey(jobId))\n return null;\n return inprogressTaskMap.get(jobId);\n }",
"public boolean getFlag(int index)\n {\n return BooleanHelper.getBoolean((Boolean) getCachedValue(selectField(ResourceFieldLists.CUSTOM_FLAG, index)));\n }",
"public static double blackScholesATMOptionValue(\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble forward,\n\t\t\tdouble payoffUnit)\n\t{\n\t\tif(optionMaturity < 0) {\n\t\t\treturn 0.0;\n\t\t}\n\n\t\t// Calculate analytic value\n\t\tdouble dPlus = 0.5 * volatility * Math.sqrt(optionMaturity);\n\t\tdouble dMinus = -dPlus;\n\n\t\tdouble valueAnalytic = (NormalDistribution.cumulativeDistribution(dPlus) - NormalDistribution.cumulativeDistribution(dMinus)) * forward * payoffUnit;\n\n\t\treturn valueAnalytic;\n\t}",
"private void generateWrappingPart(WrappingHint.Builder builder) {\n builder.setWrappingMethodOwnerName(configuration.UNMODIFIABLE_METHOD_OWNER)\n .setWrappingMethodName(configuration.FIELD_TYPE_TO_UNMODIFIABLE_METHOD.get(typeAssignedToField));\n }",
"public boolean addMethodToResponseOverride(String pathName, String methodName) {\n // need to find out the ID for the method\n // TODO: change api for adding methods to take the name instead of ID\n try {\n Integer overrideId = getOverrideIdForMethodName(methodName);\n\n // now post to path api to add this is a selected override\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"addOverride\", overrideId.toString()),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName), params));\n // check enabled endpoints array to see if this overrideID exists\n JSONArray enabled = response.getJSONArray(\"enabledEndpoints\");\n for (int x = 0; x < enabled.length(); x++) {\n if (enabled.getJSONObject(x).getInt(\"overrideId\") == overrideId) {\n return true;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return false;\n }",
"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 void seekToDayOfWeek(String direction, String seekType, String seekAmount, String dayOfWeek) {\n int dayOfWeekInt = Integer.parseInt(dayOfWeek);\n int seekAmountInt = Integer.parseInt(seekAmount);\n assert(direction.equals(DIR_LEFT) || direction.equals(DIR_RIGHT));\n assert(seekType.equals(SEEK_BY_DAY) || seekType.equals(SEEK_BY_WEEK));\n assert(dayOfWeekInt >= 1 && dayOfWeekInt <= 7);\n \n markDateInvocation();\n \n int sign = direction.equals(DIR_RIGHT) ? 1 : -1;\n if(seekType.equals(SEEK_BY_WEEK)) {\n // set our calendar to this weeks requested day of the week,\n // then add or subtract the week(s)\n _calendar.set(Calendar.DAY_OF_WEEK, dayOfWeekInt);\n _calendar.add(Calendar.DAY_OF_YEAR, seekAmountInt * 7 * sign);\n }\n \n else if(seekType.equals(SEEK_BY_DAY)) {\n // find the closest day\n do {\n _calendar.add(Calendar.DAY_OF_YEAR, sign);\n } while(_calendar.get(Calendar.DAY_OF_WEEK) != dayOfWeekInt);\n \n // now add/subtract any additional days\n if(seekAmountInt > 0) {\n _calendar.add(Calendar.WEEK_OF_YEAR, (seekAmountInt - 1) * sign);\n }\n }\n }",
"private String getActivityStatus(Task mpxj)\n {\n String result;\n if (mpxj.getActualStart() == null)\n {\n result = \"Not Started\";\n }\n else\n {\n if (mpxj.getActualFinish() == null)\n {\n result = \"In Progress\";\n }\n else\n {\n result = \"Completed\";\n }\n }\n return result;\n }",
"private void allInput(List<FileModel> vertices, GraphRewrite event, ParameterStore store)\n {\n if (StringUtils.isBlank(getInputVariablesName()) && this.filenamePattern == null)\n {\n FileService fileModelService = new FileService(event.getGraphContext());\n for (FileModel fileModel : fileModelService.findAll())\n {\n vertices.add(fileModel);\n }\n }\n }"
] |
Returns the size of the shadow element | [
"@Override\n public int getShadowSize() {\n\tElement shadowElement = shadow.getElement();\n\tshadowElement.setScrollTop(10000);\n\treturn shadowElement.getScrollTop();\n }"
] | [
"public void setRegistrationConfig(RegistrationConfig registrationConfig) {\n this.registrationConfig = registrationConfig;\n\n if (registrationConfig.getDefaultConfig()!=null) {\n for (String key : registrationConfig.getDefaultConfig().keySet()) {\n dynamicConfig.put(key, registrationConfig.getDefaultConfig().get(key));\n }\n }\n }",
"public void setRightTableModel(TableModel model)\n {\n TableModel old = m_rightTable.getModel();\n m_rightTable.setModel(model);\n firePropertyChange(\"rightTableModel\", old, model);\n }",
"@Deprecated\n public static TraceContextHolder wrap(TraceContext traceContext) {\n return (traceContext != null) ? new TraceContextHolder(traceContext) : TraceContextHolder.EMPTY;\n }",
"public Story storyOfPath(Configuration configuration, String storyPath) {\n String storyAsText = configuration.storyLoader().loadStoryAsText(storyPath);\n return configuration.storyParser().parseStory(storyAsText, storyPath);\n }",
"private Resource readResource(net.sf.mpxj.phoenix.schema.Project.Storepoints.Storepoint.Resources.Resource phoenixResource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n\n TimeUnit rateUnits = phoenixResource.getMonetarybase();\n if (rateUnits == null)\n {\n rateUnits = TimeUnit.HOURS;\n }\n\n // phoenixResource.getMaximum()\n mpxjResource.setCostPerUse(phoenixResource.getMonetarycostperuse());\n mpxjResource.setStandardRate(new Rate(phoenixResource.getMonetaryrate(), rateUnits));\n mpxjResource.setStandardRateUnits(rateUnits);\n mpxjResource.setName(phoenixResource.getName());\n mpxjResource.setType(phoenixResource.getType());\n mpxjResource.setMaterialLabel(phoenixResource.getUnitslabel());\n //phoenixResource.getUnitsperbase()\n mpxjResource.setGUID(phoenixResource.getUuid());\n\n m_eventManager.fireResourceReadEvent(mpxjResource);\n\n return mpxjResource;\n }",
"public static base_responses add(nitro_service client, dnstxtrec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnstxtrec addresources[] = new dnstxtrec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnstxtrec();\n\t\t\t\taddresources[i].domain = resources[i].domain;\n\t\t\t\taddresources[i].String = resources[i].String;\n\t\t\t\taddresources[i].ttl = resources[i].ttl;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"@Override\n public void process(Step context) {\n Iterator<Attachment> iterator = context.getAttachments().listIterator();\n while (iterator.hasNext()) {\n Attachment attachment = iterator.next();\n if (pattern.matcher(attachment.getSource()).matches()) {\n deleteAttachment(attachment);\n iterator.remove();\n }\n }\n\n for (Step step : context.getSteps()) {\n process(step);\n }\n }",
"public Collection<BoxGroupMembership.Info> getMemberships() {\n BoxAPIConnection api = this.getAPI();\n URL url = USER_MEMBERSHIPS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int entriesCount = responseJSON.get(\"total_count\").asInt();\n Collection<BoxGroupMembership.Info> memberships = new ArrayList<BoxGroupMembership.Info>(entriesCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue entry : entries) {\n JsonObject entryObject = entry.asObject();\n BoxGroupMembership membership = new BoxGroupMembership(api, entryObject.get(\"id\").asString());\n BoxGroupMembership.Info info = membership.new Info(entryObject);\n memberships.add(info);\n }\n\n return memberships;\n }",
"private synchronized void freeClient(Client client) {\n int current = useCounts.get(client);\n if (current > 0) {\n timestamps.put(client, System.currentTimeMillis()); // Mark that it was used until now.\n useCounts.put(client, current - 1);\n if ((current == 1) && (idleLimit.get() == 0)) {\n closeClient(client); // This was the last use, and we are supposed to immediately close idle clients.\n }\n } else {\n logger.error(\"Ignoring attempt to free a client that is not allocated: {}\", client);\n }\n }"
] |
Default settings set type loader to ClasspathTypeLoader if not set before. | [
"private DecompilerSettings getDefaultSettings(File outputDir)\n {\n DecompilerSettings settings = new DecompilerSettings();\n procyonConf.setDecompilerSettings(settings);\n settings.setOutputDirectory(outputDir.getPath());\n settings.setShowSyntheticMembers(false);\n settings.setForceExplicitImports(true);\n\n if (settings.getTypeLoader() == null)\n settings.setTypeLoader(new ClasspathTypeLoader());\n return settings;\n }"
] | [
"public String getToken() {\n String id = null == answer ? text : answer;\n return Act.app().crypto().generateToken(id);\n }",
"private <T> void requestAsync(ClientRequest<T> delegate,\n NonblockingStoreCallback callback,\n long timeoutMs,\n String operationName) {\n pool.submitAsync(this.destination, delegate, callback, timeoutMs, operationName);\n }",
"protected void removeSequence(String sequenceName)\r\n {\r\n // lookup the sequence map for calling DB\r\n Map mapForDB = (Map) sequencesDBMap.get(getBrokerForClass()\r\n .serviceConnectionManager().getConnectionDescriptor().getJcdAlias());\r\n if(mapForDB != null)\r\n {\r\n synchronized(SequenceManagerHighLowImpl.class)\r\n {\r\n mapForDB.remove(sequenceName);\r\n }\r\n }\r\n }",
"public static nssimpleacl[] get(nitro_service service) throws Exception{\n\t\tnssimpleacl obj = new nssimpleacl();\n\t\tnssimpleacl[] response = (nssimpleacl[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"@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 }",
"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 }",
"static void processFile(final IdentityPatchContext context, final File file, final PatchingTaskContext.Mode mode) throws IOException {\n if (mode == PatchingTaskContext.Mode.APPLY) {\n if (ENABLE_INVALIDATION) {\n updateJar(file, GOOD_ENDSIG_PATTERN, BAD_BYTE_SKIP, CRIPPLED_ENDSIG, GOOD_ENDSIG);\n backup(context, file);\n }\n } else if (mode == PatchingTaskContext.Mode.ROLLBACK) {\n updateJar(file, CRIPPLED_ENDSIG_PATTERN, BAD_BYTE_SKIP, GOOD_ENDSIG, CRIPPLED_ENDSIG);\n restore(context, file);\n } else {\n throw new IllegalStateException();\n }\n }",
"public double nonNormalizedTreeDist(LblTree t1, LblTree t2) {\n\t\tinit(t1, t2);\n\t\tSTR = new int[size1][size2];\n\t\tcomputeOptimalStrategy();\n\t\treturn computeDistUsingStrArray(it1, it2);\n\t}",
"public StandaloneCommandBuilder setDebug(final boolean suspend, final int port) {\n debugArg = String.format(DEBUG_FORMAT, (suspend ? \"y\" : \"n\"), port);\n return this;\n }"
] |
Shuts down a standalone server.
@param client the client used to communicate with the server
@param timeout the graceful shutdown timeout, a value of {@code -1} will wait indefinitely and a value of
{@code 0} will not attempt a graceful shutdown
@throws IOException if an error occurs communicating with the server | [
"public static void shutdownStandalone(final ModelControllerClient client, final int timeout) throws IOException {\n final ModelNode op = Operations.createOperation(\"shutdown\");\n op.get(\"timeout\").set(timeout);\n final ModelNode response = client.execute(op);\n if (Operations.isSuccessfulOutcome(response)) {\n while (true) {\n if (isStandaloneRunning(client)) {\n try {\n TimeUnit.MILLISECONDS.sleep(20L);\n } catch (InterruptedException e) {\n LOGGER.trace(\"Interrupted during sleep\", e);\n }\n } else {\n break;\n }\n }\n } else {\n throw new OperationExecutionException(op, response);\n }\n }"
] | [
"public static float noise2(float x, float y) {\n int bx0, bx1, by0, by1, b00, b10, b01, b11;\n float rx0, rx1, ry0, ry1, q[], sx, sy, a, b, t, u, v;\n int i, j;\n\n if (start) {\n start = false;\n init();\n }\n\n t = x + N;\n bx0 = ((int)t) & BM;\n bx1 = (bx0+1) & BM;\n rx0 = t - (int)t;\n rx1 = rx0 - 1.0f;\n\n t = y + N;\n by0 = ((int)t) & BM;\n by1 = (by0+1) & BM;\n ry0 = t - (int)t;\n ry1 = ry0 - 1.0f;\n\n i = p[bx0];\n j = p[bx1];\n\n b00 = p[i + by0];\n b10 = p[j + by0];\n b01 = p[i + by1];\n b11 = p[j + by1];\n\n sx = sCurve(rx0);\n sy = sCurve(ry0);\n\n q = g2[b00]; u = rx0 * q[0] + ry0 * q[1];\n q = g2[b10]; v = rx1 * q[0] + ry0 * q[1];\n a = lerp(sx, u, v);\n\n q = g2[b01]; u = rx0 * q[0] + ry1 * q[1];\n q = g2[b11]; v = rx1 * q[0] + ry1 * q[1];\n b = lerp(sx, u, v);\n\n return 1.5f*lerp(sy, a, b);\n }",
"public void syncInternalStateFromFileSystem(boolean alsoSyncRemoteState) {\n // Make sure versions missing from the file-system are cleaned up from the internal state\n for (Long version: versionToEnabledMap.keySet()) {\n File[] existingVersionDirs = ReadOnlyUtils.getVersionDirs(rootDir, version, version);\n if (existingVersionDirs.length == 0) {\n removeVersion(version, alsoSyncRemoteState);\n }\n }\n\n // Make sure we have all versions on the file-system in the internal state\n File[] versionDirs = ReadOnlyUtils.getVersionDirs(rootDir);\n if (versionDirs != null) {\n for (File versionDir: versionDirs) {\n long versionNumber = ReadOnlyUtils.getVersionId(versionDir);\n boolean versionEnabled = isVersionEnabled(versionDir);\n versionToEnabledMap.put(versionNumber, versionEnabled);\n }\n }\n\n // Identify the current version (based on a symlink in the file-system)\n File currentVersionDir = ReadOnlyUtils.getCurrentVersion(rootDir);\n if (currentVersionDir != null) {\n currentVersion = ReadOnlyUtils.getVersionId(currentVersionDir);\n } else {\n currentVersion = -1; // Should we throw instead?\n }\n\n logger.info(\"Successfully synced internal state from local file-system: \" + this.toString());\n }",
"private PlayState3 findPlayState3() {\n PlayState3 result = PLAY_STATE_3_MAP.get(packetBytes[157]);\n if (result == null) {\n return PlayState3.UNKNOWN;\n }\n return result;\n }",
"public static base_responses update(nitro_service client, snmpmanager resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpmanager updateresources[] = new snmpmanager[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new snmpmanager();\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].netmask = resources[i].netmask;\n\t\t\t\tupdateresources[i].domainresolveretry = resources[i].domainresolveretry;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public boolean isMaskCompatibleWithRange(int maskValue, Integer segmentPrefixLength) throws PrefixLenException {\r\n\t\tif(!isMultiple()) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn super.isMaskCompatibleWithRange(maskValue, segmentPrefixLength, getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets());\r\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}",
"public ItemRequest<Workspace> removeUser(String workspace) {\n \n String path = String.format(\"/workspaces/%s/removeUser\", workspace);\n return new ItemRequest<Workspace>(this, Workspace.class, path, \"POST\");\n }",
"private void initModeSwitch(final EditMode current) {\n\n FormLayout modes = new FormLayout();\n modes.setHeight(\"100%\");\n modes.setDefaultComponentAlignment(Alignment.MIDDLE_LEFT);\n\n m_modeSelect = new ComboBox();\n m_modeSelect.setCaption(m_messages.key(Messages.GUI_VIEW_SWITCHER_LABEL_0));\n\n // add Modes\n m_modeSelect.addItem(CmsMessageBundleEditorTypes.EditMode.DEFAULT);\n m_modeSelect.setItemCaption(\n CmsMessageBundleEditorTypes.EditMode.DEFAULT,\n m_messages.key(Messages.GUI_VIEW_SWITCHER_EDITMODE_DEFAULT_0));\n m_modeSelect.addItem(CmsMessageBundleEditorTypes.EditMode.MASTER);\n m_modeSelect.setItemCaption(\n CmsMessageBundleEditorTypes.EditMode.MASTER,\n m_messages.key(Messages.GUI_VIEW_SWITCHER_EDITMODE_MASTER_0));\n\n // set current mode as selected\n m_modeSelect.setValue(current);\n\n m_modeSelect.setNewItemsAllowed(false);\n m_modeSelect.setTextInputAllowed(false);\n m_modeSelect.setNullSelectionAllowed(false);\n\n m_modeSelect.addValueChangeListener(new ValueChangeListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void valueChange(ValueChangeEvent event) {\n\n m_listener.handleModeChange((EditMode)event.getProperty().getValue());\n\n }\n });\n\n modes.addComponent(m_modeSelect);\n m_modeSwitch = modes;\n }",
"public static TransactionalProtocolClient.PreparedOperation<TransactionalProtocolClient.Operation> executeBlocking(final ModelNode operation, TransactionalProtocolClient client) throws IOException, InterruptedException {\n final BlockingQueueOperationListener<TransactionalProtocolClient.Operation> listener = new BlockingQueueOperationListener<>();\n client.execute(listener, operation, OperationMessageHandler.DISCARD, OperationAttachments.EMPTY);\n return listener.retrievePreparedOperation();\n }"
] |
Method to get the file writer required for the .story files
@param scenarioName
@param aux_package_path
@param dest_dir
@return The file writer that generates the .story files for each test
@throws BeastException | [
"protected static FileWriter createFileWriter(String scenarioName,\n String aux_package_path, String dest_dir) throws BeastException {\n try {\n return new FileWriter(new File(createFolder(aux_package_path,\n dest_dir), scenarioName + \".story\"));\n } catch (IOException e) {\n String message = \"ERROR writing the \" + scenarioName\n + \".story file: \" + e.toString();\n logger.severe(message);\n throw new BeastException(message, e);\n }\n }"
] | [
"private void checkRowReader(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n String rowReaderName = classDef.getProperty(PropertyHelper.OJB_PROPERTY_ROW_READER);\r\n\r\n if (rowReaderName == null)\r\n {\r\n return;\r\n }\r\n\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(rowReaderName, ROW_READER_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The class \"+rowReaderName+\" specified as row-reader of class \"+classDef.getName()+\" does not implement the interface \"+ROW_READER_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the row-reader class \"+rowReaderName+\" of class \"+classDef.getName());\r\n }\r\n }",
"public static CmsPair<String, Map<String, String>> parseEmbeddedGalleryOptions(String configuration) {\n\n final Map<String, String> galleryOptions = Maps.newHashMap();\n String resultConfig = CmsStringUtil.substitute(\n PATTERN_EMBEDDED_GALLERY_CONFIG,\n configuration,\n new I_CmsRegexSubstitution() {\n\n public String substituteMatch(String string, Matcher matcher) {\n\n String galleryName = string.substring(matcher.start(1), matcher.end(1));\n String embeddedConfig = string.substring(matcher.start(2), matcher.end(2));\n galleryOptions.put(galleryName, embeddedConfig);\n return galleryName;\n }\n });\n return CmsPair.create(resultConfig, galleryOptions);\n }",
"public static Map<FieldType, String> getDefaultAssignmentFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(AssignmentField.UNIQUE_ID, \"taskrsrc_id\");\n map.put(AssignmentField.GUID, \"guid\");\n map.put(AssignmentField.REMAINING_WORK, \"remain_qty\");\n map.put(AssignmentField.BASELINE_WORK, \"target_qty\");\n map.put(AssignmentField.ACTUAL_OVERTIME_WORK, \"act_ot_qty\");\n map.put(AssignmentField.BASELINE_COST, \"target_cost\");\n map.put(AssignmentField.ACTUAL_OVERTIME_COST, \"act_ot_cost\");\n map.put(AssignmentField.REMAINING_COST, \"remain_cost\");\n map.put(AssignmentField.ACTUAL_START, \"act_start_date\");\n map.put(AssignmentField.ACTUAL_FINISH, \"act_end_date\");\n map.put(AssignmentField.BASELINE_START, \"target_start_date\");\n map.put(AssignmentField.BASELINE_FINISH, \"target_end_date\");\n map.put(AssignmentField.ASSIGNMENT_DELAY, \"target_lag_drtn_hr_cnt\");\n\n return map;\n }",
"public static List<List<RTFEmbeddedObject>> getEmbeddedObjects(String text)\n {\n List<List<RTFEmbeddedObject>> objects = null;\n List<RTFEmbeddedObject> objectData;\n\n int offset = text.indexOf(OBJDATA);\n if (offset != -1)\n {\n objects = new LinkedList<List<RTFEmbeddedObject>>();\n\n while (offset != -1)\n {\n objectData = new LinkedList<RTFEmbeddedObject>();\n objects.add(objectData);\n offset = readObjectData(offset, text, objectData);\n offset = text.indexOf(OBJDATA, offset);\n }\n }\n\n return (objects);\n }",
"private void checkUndefinedNotification(Notification notification) {\n String type = notification.getType();\n PathAddress source = notification.getSource();\n Map<String, NotificationEntry> descriptions = getRootResourceRegistration().getNotificationDescriptions(source, true);\n if (!descriptions.keySet().contains(type)) {\n missingNotificationDescriptionWarnings.add(ControllerLogger.ROOT_LOGGER.notificationIsNotDescribed(type, source));\n }\n }",
"public void setWeekDays(SortedSet<WeekDay> weekDays) {\n\n final SortedSet<WeekDay> newWeekDays = null == weekDays ? new TreeSet<WeekDay>() : weekDays;\n SortedSet<WeekDay> currentWeekDays = m_model.getWeekDays();\n if (!currentWeekDays.equals(newWeekDays)) {\n conditionallyRemoveExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDays(newWeekDays);\n onValueChange();\n }\n }, !newWeekDays.containsAll(m_model.getWeekDays()));\n }\n }",
"static <T extends GridDialect> T getDialectFacetOrNull(GridDialect gridDialect, Class<T> facetType) {\n\t\tif ( hasFacet( gridDialect, facetType ) ) {\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tT asFacet = (T) gridDialect;\n\t\t\treturn asFacet;\n\t\t}\n\n\t\treturn null;\n\t}",
"private IndexedContainer createContainerForDescriptorEditing() {\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\n // add entries\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 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 item.getItemProperty(TableProperty.DESCRIPTION).setValue(\n m_descContent.getValue(prefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).getStringValue(m_cms));\n item.getItemProperty(TableProperty.DEFAULT).setValue(\n m_descContent.getValue(prefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).getStringValue(m_cms));\n }\n\n return container;\n\n }",
"public static void validateInterimFinalCluster(final Cluster interimCluster,\n final Cluster finalCluster) {\n validateClusterPartitionCounts(interimCluster, finalCluster);\n validateClusterZonesSame(interimCluster, finalCluster);\n validateClusterNodeCounts(interimCluster, finalCluster);\n validateClusterNodeState(interimCluster, finalCluster);\n return;\n }"
] |
Adds the given property and value to the constructed reference.
@param propertyIdValue
the property to add
@param value
the value to add
@return builder object to continue construction | [
"public ReferenceBuilder withPropertyValue(PropertyIdValue propertyIdValue,\n\t\t\tValue value) {\n\t\tgetSnakList(propertyIdValue).add(\n\t\t\t\tfactory.getValueSnak(propertyIdValue, value));\n\t\treturn getThis();\n\t}"
] | [
"public static policydataset get(nitro_service service, String name) throws Exception{\n\t\tpolicydataset obj = new policydataset();\n\t\tobj.set_name(name);\n\t\tpolicydataset response = (policydataset) obj.get_resource(service);\n\t\treturn response;\n\t}",
"@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)\n public static synchronized void register(android.app.Application application) {\n if (application == null) {\n Logger.i(\"Application instance is null/system API is too old\");\n return;\n }\n\n if (registered) {\n Logger.v(\"Lifecycle callbacks have already been registered\");\n return;\n }\n\n registered = true;\n application.registerActivityLifecycleCallbacks(\n new android.app.Application.ActivityLifecycleCallbacks() {\n\n @Override\n public void onActivityCreated(Activity activity, Bundle bundle) {\n CleverTapAPI.onActivityCreated(activity);\n }\n\n @Override\n public void onActivityStarted(Activity activity) {}\n\n @Override\n public void onActivityResumed(Activity activity) {\n CleverTapAPI.onActivityResumed(activity);\n }\n\n @Override\n public void onActivityPaused(Activity activity) {\n CleverTapAPI.onActivityPaused();\n }\n\n @Override\n public void onActivityStopped(Activity activity) {}\n\n @Override\n public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {}\n\n @Override\n public void onActivityDestroyed(Activity activity) {}\n }\n\n );\n Logger.i(\"Activity Lifecycle Callback successfully registered\");\n }",
"private ProductDescriptor getSwapProductDescriptor(Element trade) {\r\n\r\n\t\tInterestRateSwapLegProductDescriptor legReceiver = null;\r\n\t\tInterestRateSwapLegProductDescriptor legPayer = null;\r\n\r\n\t\tNodeList legs = trade.getElementsByTagName(\"swapStream\");\r\n\t\tfor(int legIndex = 0; legIndex < legs.getLength(); legIndex++) {\r\n\t\t\tElement leg = (Element) legs.item(legIndex);\r\n\r\n\t\t\tboolean isPayer = leg.getElementsByTagName(\"payerPartyReference\").item(0).getAttributes().getNamedItem(\"href\").getNodeValue().equals(homePartyId);\r\n\r\n\t\t\tif(isPayer) {\r\n\t\t\t\tlegPayer = getSwapLegProductDescriptor(leg);\r\n\t\t\t} else {\r\n\t\t\t\tlegReceiver = getSwapLegProductDescriptor(leg);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn new InterestRateSwapProductDescriptor(legReceiver, legPayer);\r\n\t}",
"public static double volatilityConversionLognormalATMtoNormalATM(double forward, double displacement, double maturity, double lognormalVolatiltiy) {\n\t\tdouble x = lognormalVolatiltiy * Math.sqrt(maturity / 8);\n\t\tdouble y = org.apache.commons.math3.special.Erf.erf(x);\n\t\tdouble normalVol = Math.sqrt(2*Math.PI / maturity) * (forward+displacement) * y;\n\n\t\treturn normalVol;\n\t}",
"public static int removeDuplicateNodeList(List<String> list) {\n\n int originCount = list.size();\n // add elements to all, including duplicates\n HashSet<String> hs = new LinkedHashSet<String>();\n hs.addAll(list);\n list.clear();\n list.addAll(hs);\n\n return originCount - list.size();\n }",
"public SimplifySpanBuild appendMultiClickable(SpecialClickableUnit specialClickableUnit, Object... specialUnitOrStrings) {\n processMultiClickableSpecialUnit(false, specialClickableUnit, specialUnitOrStrings);\n return this;\n }",
"public Map<Integer, TableDefinition> tableDefinitions()\n {\n Map<Integer, TableDefinition> result = new HashMap<Integer, TableDefinition>();\n\n result.put(Integer.valueOf(2), new TableDefinition(\"PROJECT_SUMMARY\", columnDefinitions(PROJECT_SUMMARY_COLUMNS, projectSummaryColumnsOrder())));\n result.put(Integer.valueOf(7), new TableDefinition(\"BAR\", columnDefinitions(BAR_COLUMNS, barColumnsOrder())));\n result.put(Integer.valueOf(11), new TableDefinition(\"CALENDAR\", columnDefinitions(CALENDAR_COLUMNS, calendarColumnsOrder())));\n result.put(Integer.valueOf(12), new TableDefinition(\"EXCEPTIONN\", columnDefinitions(EXCEPTIONN_COLUMNS, exceptionColumnsOrder())));\n result.put(Integer.valueOf(14), new TableDefinition(\"EXCEPTION_ASSIGNMENT\", columnDefinitions(EXCEPTION_ASSIGNMENT_COLUMNS, exceptionAssignmentColumnsOrder())));\n result.put(Integer.valueOf(15), new TableDefinition(\"TIME_ENTRY\", columnDefinitions(TIME_ENTRY_COLUMNS, timeEntryColumnsOrder())));\n result.put(Integer.valueOf(17), new TableDefinition(\"WORK_PATTERN\", columnDefinitions(WORK_PATTERN_COLUMNS, workPatternColumnsOrder()))); \n result.put(Integer.valueOf(18), new TableDefinition(\"TASK_COMPLETED_SECTION\", columnDefinitions(TASK_COMPLETED_SECTION_COLUMNS, taskCompletedSectionColumnsOrder()))); \n result.put(Integer.valueOf(21), new TableDefinition(\"TASK\", columnDefinitions(TASK_COLUMNS, taskColumnsOrder())));\n result.put(Integer.valueOf(22), new TableDefinition(\"MILESTONE\", columnDefinitions(MILESTONE_COLUMNS, milestoneColumnsOrder())));\n result.put(Integer.valueOf(23), new TableDefinition(\"EXPANDED_TASK\", columnDefinitions(EXPANDED_TASK_COLUMNS, expandedTaskColumnsOrder())));\n result.put(Integer.valueOf(25), new TableDefinition(\"LINK\", columnDefinitions(LINK_COLUMNS, linkColumnsOrder())));\n result.put(Integer.valueOf(61), new TableDefinition(\"CONSUMABLE_RESOURCE\", columnDefinitions(CONSUMABLE_RESOURCE_COLUMNS, consumableResourceColumnsOrder())));\n result.put(Integer.valueOf(62), new TableDefinition(\"PERMANENT_RESOURCE\", columnDefinitions(PERMANENT_RESOURCE_COLUMNS, permanentResourceColumnsOrder())));\n result.put(Integer.valueOf(63), new TableDefinition(\"PERM_RESOURCE_SKILL\", columnDefinitions(PERMANENT_RESOURCE_SKILL_COLUMNS, permanentResourceSkillColumnsOrder())));\n result.put(Integer.valueOf(67), new TableDefinition(\"PERMANENT_SCHEDUL_ALLOCATION\", columnDefinitions(PERMANENT_SCHEDULE_ALLOCATION_COLUMNS, permanentScheduleAllocationColumnsOrder())));\n result.put(Integer.valueOf(190), new TableDefinition(\"WBS_ENTRY\", columnDefinitions(WBS_ENTRY_COLUMNS, wbsEntryColumnsOrder())));\n\n return result;\n }",
"@SuppressWarnings(\"unchecked\")\n public <V3, M4, C, N, Q> N getSceneRoot(AiWrapperProvider<V3, M4, C, N, Q> \n wrapperProvider) {\n\n return (N) m_sceneRoot;\n }",
"public AT_Row setPaddingBottom(int paddingBottom) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingBottom(paddingBottom);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}"
] |
Returns a BSON version document representing a new version with a new instance ID, and
version counter of zero.
@return a BsonDocument representing a synchronization version | [
"static BsonDocument getFreshVersionDocument() {\n final BsonDocument versionDoc = new BsonDocument();\n\n versionDoc.append(Fields.SYNC_PROTOCOL_VERSION_FIELD, new BsonInt32(1));\n versionDoc.append(Fields.INSTANCE_ID_FIELD, new BsonString(UUID.randomUUID().toString()));\n versionDoc.append(Fields.VERSION_COUNTER_FIELD, new BsonInt64(0L));\n\n return versionDoc;\n }"
] | [
"public void addProperty(String name, String... values) {\n List<String> valueList = new ArrayList<String>();\n for (String value : values) {\n valueList.add(value.trim());\n }\n properties.put(name.trim(), valueList);\n }",
"public static boolean isFloat(CharSequence self) {\n try {\n Float.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }",
"private void checkUndefinedNotification(Notification notification) {\n String type = notification.getType();\n PathAddress source = notification.getSource();\n Map<String, NotificationEntry> descriptions = getRootResourceRegistration().getNotificationDescriptions(source, true);\n if (!descriptions.keySet().contains(type)) {\n missingNotificationDescriptionWarnings.add(ControllerLogger.ROOT_LOGGER.notificationIsNotDescribed(type, source));\n }\n }",
"public Permissions getPerms(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PERMS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element permissionsElement = response.getPayload();\r\n Permissions permissions = new Permissions();\r\n permissions.setId(permissionsElement.getAttribute(\"id\"));\r\n permissions.setPublicFlag(\"1\".equals(permissionsElement.getAttribute(\"ispublic\")));\r\n permissions.setFamilyFlag(\"1\".equals(permissionsElement.getAttribute(\"isfamily\")));\r\n permissions.setFriendFlag(\"1\".equals(permissionsElement.getAttribute(\"isfriend\")));\r\n permissions.setComment(permissionsElement.getAttribute(\"permcomment\"));\r\n permissions.setAddmeta(permissionsElement.getAttribute(\"permaddmeta\"));\r\n return permissions;\r\n }",
"public List<BuildpackInstallation> listBuildpackInstallations(String appName) {\n return connection.execute(new BuildpackInstallationList(appName), apiKey);\n }",
"private void addBlock(List<GenericCriteria> list, byte[] block, TestOperator operator)\n {\n GenericCriteria result = new GenericCriteria(m_properties);\n result.setOperator(operator);\n list.add(result);\n processBlock(result.getCriteriaList(), getChildBlock(block));\n processBlock(list, getListNextBlock(block));\n }",
"@Override\n public void postCrawling(CrawlSession session, ExitStatus exitStatus) {\n LOG.debug(\"postCrawling\");\n StateFlowGraph sfg = session.getStateFlowGraph();\n checkSFG(sfg);\n // TODO: call state abstraction function to get distance matrix and run rscript on it to\n // create clusters\n String[][] clusters = null;\n // generateClusters(session);\n\n result = outModelCache.close(session, exitStatus, clusters);\n\n outputBuilder.write(result, session.getConfig(), clusters);\n StateWriter writer =\n new StateWriter(outputBuilder, sfg, ImmutableMap.copyOf(visitedStates));\n for (State state : result.getStates().values()) {\n try {\n writer.writeHtmlForState(state);\n } catch (Exception Ex) {\n LOG.info(\"couldn't write state :\" + state.getName());\n }\n }\n LOG.info(\"Crawl overview plugin has finished\");\n }",
"@SuppressWarnings(\"deprecation\")\n private void cancelRequestAndWorkerOnHost(List<String> targetHosts) {\n\n List<String> validTargetHosts = new ArrayList<String>(workers.keySet());\n validTargetHosts.retainAll(targetHosts);\n logger.info(\"targetHosts for cancel: Total: {}\"\n + \" Valid in current manager with worker threads: {}\",\n targetHosts.size(), validTargetHosts.size());\n\n for (String targetHost : validTargetHosts) {\n\n ActorRef worker = workers.get(targetHost);\n\n if (worker != null && !worker.isTerminated()) {\n worker.tell(OperationWorkerMsgType.CANCEL, getSelf());\n logger.info(\"Submitted CANCEL request on Host {}\", targetHost);\n } else {\n logger.info(\n \"Did NOT Submitted \"\n + \"CANCEL request on Host {} as worker on this host is null or already killed\",\n targetHost);\n }\n\n }\n\n }",
"private void processClassMethods(XMLStreamWriter writer, Class<?> aClass, Set<Method> methodSet) throws XMLStreamException\n {\n Method[] methods = aClass.getDeclaredMethods();\n for (Method method : methods)\n {\n if (!methodSet.contains(method) && Modifier.isPublic(method.getModifiers()) && !Modifier.isInterface(method.getModifiers()))\n {\n if (Modifier.isStatic(method.getModifiers()))\n {\n // TODO Handle static methods here\n }\n else\n {\n String name = method.getName();\n String methodSignature = createMethodSignature(method);\n String fullJavaName = aClass.getCanonicalName() + \".\" + name + methodSignature;\n\n if (!ignoreMethod(fullJavaName))\n {\n //\n // Hide the original method\n //\n writer.writeStartElement(\"method\");\n writer.writeAttribute(\"name\", name);\n writer.writeAttribute(\"sig\", methodSignature);\n\n writer.writeStartElement(\"attribute\");\n writer.writeAttribute(\"type\", \"System.ComponentModel.EditorBrowsableAttribute\");\n writer.writeAttribute(\"sig\", \"(Lcli.System.ComponentModel.EditorBrowsableState;)V\");\n writer.writeStartElement(\"parameter\");\n writer.writeCharacters(\"Never\");\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeEndElement();\n\n //\n // Create a wrapper method\n //\n name = name.toUpperCase().charAt(0) + name.substring(1);\n\n writer.writeStartElement(\"method\");\n writer.writeAttribute(\"name\", name);\n writer.writeAttribute(\"sig\", methodSignature);\n writer.writeAttribute(\"modifiers\", \"public\");\n\n writer.writeStartElement(\"body\");\n\n for (int index = 0; index <= method.getParameterTypes().length; index++)\n {\n if (index < 4)\n {\n writer.writeEmptyElement(\"ldarg_\" + index);\n }\n else\n {\n writer.writeStartElement(\"ldarg_s\");\n writer.writeAttribute(\"argNum\", Integer.toString(index));\n writer.writeEndElement();\n }\n }\n\n writer.writeStartElement(\"callvirt\");\n writer.writeAttribute(\"class\", aClass.getName());\n writer.writeAttribute(\"name\", method.getName());\n writer.writeAttribute(\"sig\", methodSignature);\n writer.writeEndElement();\n\n if (!method.getReturnType().getName().equals(\"void\"))\n {\n writer.writeEmptyElement(\"ldnull\");\n writer.writeEmptyElement(\"pop\");\n }\n writer.writeEmptyElement(\"ret\");\n writer.writeEndElement();\n writer.writeEndElement();\n\n /*\n * The private method approach doesn't work... so\n * 3. Add EditorBrowsableAttribute (Never) to original methods\n * 4. Generate C Sharp and VB variants of the DLL to avid case-sensitivity issues\n * 5. Implement static method support?\n <attribute type=\"System.ComponentModel.EditorBrowsableAttribute\" sig=\"(Lcli.System.ComponentModel.EditorBrowsableState;)V\">\n 914 <parameter>Never</parameter>\n 915 </attribute>\n */\n\n m_responseList.add(fullJavaName);\n }\n }\n }\n }\n }"
] |
This method writes data for an individual calendar to a PM XML file.
@param mpxj ProjectCalander instance | [
"private void writeCalendar(ProjectCalendar mpxj)\n {\n CalendarType xml = m_factory.createCalendarType();\n m_apibo.getCalendar().add(xml);\n String type = mpxj.getResource() == null ? \"Global\" : \"Resource\";\n\n xml.setBaseCalendarObjectId(getCalendarUniqueID(mpxj.getParent()));\n xml.setIsPersonal(mpxj.getResource() == null ? Boolean.FALSE : Boolean.TRUE);\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setType(type);\n\n StandardWorkWeek xmlStandardWorkWeek = m_factory.createCalendarTypeStandardWorkWeek();\n xml.setStandardWorkWeek(xmlStandardWorkWeek);\n\n for (Day day : EnumSet.allOf(Day.class))\n {\n StandardWorkHours xmlHours = m_factory.createCalendarTypeStandardWorkWeekStandardWorkHours();\n xmlStandardWorkWeek.getStandardWorkHours().add(xmlHours);\n xmlHours.setDayOfWeek(getDayName(day));\n\n for (DateRange range : mpxj.getHours(day))\n {\n WorkTimeType xmlWorkTime = m_factory.createWorkTimeType();\n xmlHours.getWorkTime().add(xmlWorkTime);\n\n xmlWorkTime.setStart(range.getStart());\n xmlWorkTime.setFinish(getEndTime(range.getEnd()));\n }\n }\n\n HolidayOrExceptions xmlExceptions = m_factory.createCalendarTypeHolidayOrExceptions();\n xml.setHolidayOrExceptions(xmlExceptions);\n\n if (!mpxj.getCalendarExceptions().isEmpty())\n {\n Calendar calendar = DateHelper.popCalendar();\n for (ProjectCalendarException mpxjException : mpxj.getCalendarExceptions())\n {\n calendar.setTime(mpxjException.getFromDate());\n while (calendar.getTimeInMillis() < mpxjException.getToDate().getTime())\n {\n HolidayOrException xmlException = m_factory.createCalendarTypeHolidayOrExceptionsHolidayOrException();\n xmlExceptions.getHolidayOrException().add(xmlException);\n\n xmlException.setDate(calendar.getTime());\n\n for (DateRange range : mpxjException)\n {\n WorkTimeType xmlHours = m_factory.createWorkTimeType();\n xmlException.getWorkTime().add(xmlHours);\n\n xmlHours.setStart(range.getStart());\n\n if (range.getEnd() != null)\n {\n xmlHours.setFinish(getEndTime(range.getEnd()));\n }\n }\n calendar.add(Calendar.DAY_OF_YEAR, 1);\n }\n }\n DateHelper.pushCalendar(calendar);\n }\n }"
] | [
"public void addRequest(long timeNS,\n long numEmptyResponses,\n long valueBytes,\n long keyBytes,\n long getAllAggregatedCount) {\n // timing instrumentation (trace only)\n long startTimeNs = 0;\n if(logger.isTraceEnabled()) {\n startTimeNs = System.nanoTime();\n }\n\n long currentTime = time.milliseconds();\n\n timeSensor.record((double) timeNS / voldemort.utils.Time.NS_PER_MS, currentTime);\n emptyResponseKeysSensor.record(numEmptyResponses, currentTime);\n valueBytesSensor.record(valueBytes, currentTime);\n keyBytesSensor.record(keyBytes, currentTime);\n getAllKeysCountSensor.record(getAllAggregatedCount, currentTime);\n\n // timing instrumentation (trace only)\n if(logger.isTraceEnabled()) {\n logger.trace(\"addRequest took \" + (System.nanoTime() - startTimeNs) + \" ns.\");\n }\n }",
"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 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 }",
"public void setTexCoord(String texName, String texCoordAttr, String shaderVarName)\n {\n synchronized (textures)\n {\n GVRTexture tex = textures.get(texName);\n\n if (tex != null)\n {\n tex.setTexCoord(texCoordAttr, shaderVarName);\n }\n else\n {\n throw new UnsupportedOperationException(\"Texture must be set before updating texture coordinate information\");\n }\n }\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void markReadInboxMessage(final CTInboxMessage message){\n postAsyncSafely(\"markReadInboxMessage\", new Runnable() {\n @Override\n public void run() {\n synchronized (inboxControllerLock) {\n if(ctInboxController != null){\n boolean read = ctInboxController.markReadForMessageWithId(message.getMessageId());\n if (read) {\n _notifyInboxMessagesDidUpdate();\n }\n } else {\n getConfigLogger().debug(getAccountId(),\"Notification Inbox not initialized\");\n }\n }\n }\n });\n }",
"public static void acceptsHex(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_X, OPT_HEX), \"fetch key/entry by key value of hex type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\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 }",
"public void registerServices(boolean force) {\n\t\tInjector injector = Guice.createInjector(getGuiceModule());\n\t\tinjector.injectMembers(this);\n\t\tregisterInRegistry(force);\n\t}",
"@PostConstruct\n public void init() {\n this.metricRegistry.register(name(\"gc\"), new GarbageCollectorMetricSet());\n this.metricRegistry.register(name(\"memory\"), new MemoryUsageGaugeSet());\n this.metricRegistry.register(name(\"thread-states\"), new ThreadStatesGaugeSet());\n this.metricRegistry.register(name(\"fd-usage\"), new FileDescriptorRatioGauge());\n }"
] |
Returns a name for the principal based upon one of the attributes
of the main CommonProfile. The attribute name used to query the CommonProfile
is specified in the constructor.
@return a name for the Principal or null if the attribute is not populated. | [
"@Override\n public String getName() {\n CommonProfile profile = this.getProfile();\n if(null == principalNameAttribute) {\n return profile.getId();\n }\n Object attrValue = profile.getAttribute(principalNameAttribute);\n return (null == attrValue) ? null : String.valueOf(attrValue);\n }"
] | [
"private static int checkResult(int result)\n {\n if (exceptionsEnabled && result !=\n cudnnStatus.CUDNN_STATUS_SUCCESS)\n {\n throw new CudaException(cudnnStatus.stringFor(result));\n }\n return result;\n }",
"@SuppressWarnings(\"unchecked\")\n public static <E> E getObject(String className) {\n if (className == null) {\n return (E) null;\n }\n try {\n return (E) Class.forName(className).newInstance();\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }",
"public static ServiceName moduleSpecServiceName(ModuleIdentifier identifier) {\n if (!isDynamicModule(identifier)) {\n throw ServerLogger.ROOT_LOGGER.missingModulePrefix(identifier, MODULE_PREFIX);\n }\n return MODULE_SPEC_SERVICE_PREFIX.append(identifier.getName()).append(identifier.getSlot());\n }",
"public void drawImage(Image img, Rectangle rect, Rectangle clipRect) {\n\t\tdrawImage(img, rect, clipRect, 1);\n\t}",
"public static nsdiameter get(nitro_service service) throws Exception{\n\t\tnsdiameter obj = new nsdiameter();\n\t\tnsdiameter[] response = (nsdiameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public ItemRequest<Section> delete(String section) {\n \n String path = String.format(\"/sections/%s\", section);\n return new ItemRequest<Section>(this, Section.class, path, \"DELETE\");\n }",
"private void createResults(List<ISuite> suites,\n File outputDirectory,\n boolean onlyShowFailures) throws Exception\n {\n int index = 1;\n for (ISuite suite : suites)\n {\n int index2 = 1;\n for (ISuiteResult result : suite.getResults().values())\n {\n boolean failuresExist = result.getTestContext().getFailedTests().size() > 0\n || result.getTestContext().getFailedConfigurations().size() > 0;\n if (!onlyShowFailures || failuresExist)\n {\n VelocityContext context = createContext();\n context.put(RESULT_KEY, result);\n context.put(FAILED_CONFIG_KEY, sortByTestClass(result.getTestContext().getFailedConfigurations()));\n context.put(SKIPPED_CONFIG_KEY, sortByTestClass(result.getTestContext().getSkippedConfigurations()));\n context.put(FAILED_TESTS_KEY, sortByTestClass(result.getTestContext().getFailedTests()));\n context.put(SKIPPED_TESTS_KEY, sortByTestClass(result.getTestContext().getSkippedTests()));\n context.put(PASSED_TESTS_KEY, sortByTestClass(result.getTestContext().getPassedTests()));\n String fileName = String.format(\"suite%d_test%d_%s\", index, index2, RESULTS_FILE);\n generateFile(new File(outputDirectory, fileName),\n RESULTS_FILE + TEMPLATE_EXTENSION,\n context);\n }\n ++index2;\n }\n ++index;\n }\n }",
"private void debugLogEnd(String operationType,\n Long OriginTimeInMs,\n Long RequestStartTimeInMs,\n Long ResponseReceivedTimeInMs,\n String keyString,\n int numVectorClockEntries) {\n long durationInMs = ResponseReceivedTimeInMs - RequestStartTimeInMs;\n logger.debug(\"Received a response from voldemort server for Operation Type: \"\n + operationType\n + \" , For key(s): \"\n + keyString\n + \" , Store: \"\n + this.storeName\n + \" , Origin time of request (in ms): \"\n + OriginTimeInMs\n + \" , Response received at time (in ms): \"\n + ResponseReceivedTimeInMs\n + \" . Request sent at(in ms): \"\n + RequestStartTimeInMs\n + \" , Num vector clock entries: \"\n + numVectorClockEntries\n + \" , Duration from CoordinatorFatClient back to CoordinatorFatClient(in ms): \"\n + durationInMs);\n }",
"protected TransformationDescription buildDefault(final DiscardPolicy discardPolicy, boolean inherited, final AttributeTransformationDescriptionBuilderImpl.AttributeTransformationDescriptionBuilderRegistry registry, List<String> discardedOperations) {\n // Build attribute rules\n final Map<String, AttributeTransformationDescription> attributes = registry.buildAttributes();\n // Create operation transformers\n final Map<String, OperationTransformer> operations = buildOperationTransformers(registry);\n // Process children\n final List<TransformationDescription> children = buildChildren();\n\n if (discardPolicy == DiscardPolicy.NEVER) {\n // TODO override more global operations?\n if(! operations.containsKey(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION)) {\n operations.put(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION, OperationTransformationRules.createWriteOperation(attributes));\n }\n if(! operations.containsKey(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION)) {\n operations.put(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION, OperationTransformationRules.createUndefinedOperation(attributes));\n }\n }\n // Create the description\n Set<String> discarded = new HashSet<>();\n discarded.addAll(discardedOperations);\n return new TransformingDescription(pathElement, pathAddressTransformer, discardPolicy, inherited,\n resourceTransformer, attributes, operations, children, discarded, dynamicDiscardPolicy);\n }"
] |
Add a IN clause so the column must be equal-to one of the objects from the list passed in. | [
"public Where<T, ID> in(String columnName, Iterable<?> objects) throws SQLException {\n\t\taddClause(new In(columnName, findColumnFieldType(columnName), objects, true));\n\t\treturn this;\n\t}"
] | [
"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 }",
"private void computeGradientAndHessian(DMatrixRMaj param )\n {\n // residuals = f(x) - y\n function.compute(param, residuals);\n\n computeNumericalJacobian(param,jacobian);\n\n CommonOps_DDRM.multTransA(jacobian, residuals, g);\n CommonOps_DDRM.multTransA(jacobian, jacobian, H);\n\n CommonOps_DDRM.extractDiag(H,Hdiag);\n }",
"ResultAction executeOperation() {\n\n assert isControllingThread();\n try {\n /** Execution has begun */\n executing = true;\n\n processStages();\n\n if (resultAction == ResultAction.KEEP) {\n report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationSucceeded());\n } else {\n report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationRollingBack());\n }\n } catch (RuntimeException e) {\n handleUncaughtException(e);\n ControllerLogger.MGMT_OP_LOGGER.unexpectedOperationExecutionException(e, controllerOperations);\n } finally {\n // On failure close any attached response streams\n if (resultAction != ResultAction.KEEP && !isBooting()) {\n synchronized (this) {\n if (responseStreams != null) {\n int i = 0;\n for (OperationResponse.StreamEntry is : responseStreams.values()) {\n try {\n is.getStream().close();\n } catch (Exception e) {\n ControllerLogger.MGMT_OP_LOGGER.debugf(e, \"Failed closing stream at index %d\", i);\n }\n i++;\n }\n responseStreams.clear();\n }\n }\n }\n }\n\n\n return resultAction;\n }",
"public static AiScene importFile(String filename) throws IOException {\n \n return importFile(filename, EnumSet.noneOf(AiPostProcessSteps.class));\n }",
"public void postDoNotUseArtifact(final String gavc, final Boolean doNotUse, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getDoNotUseArtifact(gavc));\n final ClientResponse response = resource.queryParam(ServerAPI.DO_NOT_USE, doNotUse.toString())\n .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to post do not use artifact\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }",
"public static SimpleMatrix wrap( Matrix internalMat ) {\n SimpleMatrix ret = new SimpleMatrix();\n ret.setMatrix(internalMat);\n return ret;\n }",
"private InputStream tryPath(String path) {\r\n Logger.getLogger().debug(\"Trying path \\\"\" + path + \"\\\".\");\r\n return getClass().getResourceAsStream(path);\r\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<BritishCutoverDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<BritishCutoverDate>) super.localDateTime(temporal);\n }",
"public static DMatrixRMaj elements(DMatrixRMaj A , BMatrixRMaj marked , DMatrixRMaj output ) {\n if( A.numRows != marked.numRows || A.numCols != marked.numCols )\n throw new MatrixDimensionException(\"Input matrices must have the same shape\");\n if( output == null )\n output = new DMatrixRMaj(1,1);\n\n output.reshape(countTrue(marked),1);\n\n int N = A.getNumElements();\n\n int index = 0;\n for (int i = 0; i < N; i++) {\n if( marked.data[i] ) {\n output.data[index++] = A.data[i];\n }\n }\n\n return output;\n }"
] |
Constraint that ensures that the field has a column property. If none is specified, then
the name of the field is used.
@param fieldDef The field descriptor
@param checkLevel The current check level (this constraint is checked in all levels) | [
"private void ensureColumn(FieldDescriptorDef fieldDef, String checkLevel)\r\n {\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLUMN))\r\n {\r\n String javaname = fieldDef.getName();\r\n\r\n if (fieldDef.isNested())\r\n { \r\n int pos = javaname.indexOf(\"::\");\r\n\r\n // we convert nested names ('_' for '::')\r\n if (pos > 0)\r\n {\r\n StringBuffer newJavaname = new StringBuffer(javaname.substring(0, pos));\r\n int lastPos = pos + 2;\r\n\r\n do\r\n {\r\n pos = javaname.indexOf(\"::\", lastPos);\r\n newJavaname.append(\"_\");\r\n if (pos > 0)\r\n { \r\n newJavaname.append(javaname.substring(lastPos, pos));\r\n lastPos = pos + 2;\r\n }\r\n else\r\n {\r\n newJavaname.append(javaname.substring(lastPos));\r\n }\r\n }\r\n while (pos > 0);\r\n javaname = newJavaname.toString();\r\n }\r\n }\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_COLUMN, javaname);\r\n }\r\n }"
] | [
"private void writeUserFieldDefinitions()\n {\n for (CustomField cf : m_sortedCustomFieldsList)\n {\n if (cf.getFieldType() != null && cf.getFieldType().getDataType() != null)\n {\n UDFTypeType udf = m_factory.createUDFTypeType();\n udf.setObjectId(Integer.valueOf(FieldTypeHelper.getFieldID(cf.getFieldType())));\n\n udf.setDataType(UserFieldDataType.inferUserFieldDataType(cf.getFieldType().getDataType()));\n udf.setSubjectArea(UserFieldDataType.inferUserFieldSubjectArea(cf.getFieldType()));\n udf.setTitle(cf.getAlias());\n m_apibo.getUDFType().add(udf);\n }\n }\n }",
"protected void addConstructors(ClassFile proxyClassType, List<DeferredBytecode> initialValueBytecode) {\n try {\n if (getBeanType().isInterface()) {\n ConstructorUtils.addDefaultConstructor(proxyClassType, initialValueBytecode, !useConstructedFlag());\n } else {\n boolean constructorFound = false;\n for (Constructor<?> constructor : AccessController.doPrivileged(new GetDeclaredConstructorsAction(getBeanType()))) {\n if ((constructor.getModifiers() & Modifier.PRIVATE) == 0) {\n constructorFound = true;\n String[] exceptions = new String[constructor.getExceptionTypes().length];\n for (int i = 0; i < exceptions.length; ++i) {\n exceptions[i] = constructor.getExceptionTypes()[i].getName();\n }\n ConstructorUtils.addConstructor(BytecodeUtils.VOID_CLASS_DESCRIPTOR, DescriptorUtils.parameterDescriptors(constructor.getParameterTypes()), exceptions, proxyClassType, initialValueBytecode, !useConstructedFlag());\n }\n }\n if (!constructorFound) {\n // the bean only has private constructors, we need to generate\n // two fake constructors that call each other\n addConstructorsForBeanWithPrivateConstructors(proxyClassType);\n }\n }\n } catch (Exception e) {\n throw new WeldException(e);\n }\n }",
"public static base_response update(nitro_service client, lbsipparameters resource) throws Exception {\n\t\tlbsipparameters updateresource = new lbsipparameters();\n\t\tupdateresource.rnatsrcport = resource.rnatsrcport;\n\t\tupdateresource.rnatdstport = resource.rnatdstport;\n\t\tupdateresource.retrydur = resource.retrydur;\n\t\tupdateresource.addrportvip = resource.addrportvip;\n\t\tupdateresource.sip503ratethreshold = resource.sip503ratethreshold;\n\t\treturn updateresource.update_resource(client);\n\t}",
"protected Method resolveTargetMethod(Message message,\n FieldDescriptor payloadField) {\n Method targetMethod = fieldToMethod.get(payloadField);\n\n if (targetMethod == null) {\n // look up and cache target method; this block is called only once\n // per target method, so synchronized is ok\n synchronized (this) {\n targetMethod = fieldToMethod.get(payloadField);\n if (targetMethod == null) {\n String name = payloadField.getName();\n for (Method method : service.getClass().getMethods()) {\n if (method.getName().equals(name)) {\n try {\n method.setAccessible(true);\n } catch (Exception ex) {\n log.log(Level.SEVERE,\"Error accessing RPC method\",ex);\n }\n\n targetMethod = method;\n fieldToMethod.put(payloadField, targetMethod);\n break;\n }\n }\n }\n }\n }\n\n if (targetMethod != null) {\n return targetMethod;\n } else {\n throw new RuntimeException(\"No matching method found by the name '\"\n + payloadField.getName() + \"'\");\n }\n }",
"private byte[] getBytes(String value, boolean unicode)\n {\n byte[] result;\n if (unicode)\n {\n int start = 0;\n // Get the bytes in UTF-16\n byte[] bytes;\n\n try\n {\n bytes = value.getBytes(\"UTF-16\");\n }\n catch (UnsupportedEncodingException e)\n {\n bytes = value.getBytes();\n }\n\n if (bytes.length > 2 && bytes[0] == -2 && bytes[1] == -1)\n {\n // Skip the unicode identifier\n start = 2;\n }\n result = new byte[bytes.length - start];\n for (int loop = start; loop < bytes.length - 1; loop += 2)\n {\n // Swap the order here\n result[loop - start] = bytes[loop + 1];\n result[loop + 1 - start] = bytes[loop];\n }\n }\n else\n {\n result = new byte[value.length() + 1];\n System.arraycopy(value.getBytes(), 0, result, 0, value.length());\n }\n return (result);\n }",
"public static ModelMBean createModelMBean(Object o) {\n try {\n ModelMBean mbean = new RequiredModelMBean();\n JmxManaged annotation = o.getClass().getAnnotation(JmxManaged.class);\n String description = annotation == null ? \"\" : annotation.description();\n ModelMBeanInfo info = new ModelMBeanInfoSupport(o.getClass().getName(),\n description,\n extractAttributeInfo(o),\n new ModelMBeanConstructorInfo[0],\n extractOperationInfo(o),\n new ModelMBeanNotificationInfo[0]);\n mbean.setModelMBeanInfo(info);\n mbean.setManagedResource(o, \"ObjectReference\");\n\n return mbean;\n } catch(MBeanException e) {\n throw new VoldemortException(e);\n } catch(InvalidTargetObjectTypeException e) {\n throw new VoldemortException(e);\n } catch(InstanceNotFoundException e) {\n throw new VoldemortException(e);\n }\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 }",
"public List<GetLocationResult> search(String q, int maxRows, Locale locale)\n\t\t\tthrows Exception {\n\t\tList<GetLocationResult> searchResult = new ArrayList<GetLocationResult>();\n\n\t\tString url = URLEncoder.encode(q, \"UTF8\");\n\t\turl = \"q=select%20*%20from%20geo.placefinder%20where%20text%3D%22\"\n\t\t\t\t+ url + \"%22\";\n\t\tif (maxRows > 0) {\n\t\t\turl = url + \"&count=\" + maxRows;\n\t\t}\n\t\turl = url + \"&flags=GX\";\n\t\tif (null != locale) {\n\t\t\turl = url + \"&locale=\" + locale;\n\t\t}\n\t\tif (appId != null) {\n\t\t\turl = url + \"&appid=\" + appId;\n\t\t}\n\n\t\tInputStream inputStream = connect(url);\n\t\tif (null != inputStream) {\n\t\t\tSAXBuilder parser = new SAXBuilder();\n\t\t\tDocument doc = parser.build(inputStream);\n\n\t\t\tElement root = doc.getRootElement();\n\n\t\t\t// check code for exception\n\t\t\tString message = root.getChildText(\"Error\");\n\t\t\t// Integer errorCode = Integer.parseInt(message);\n\t\t\tif (message != null && Integer.parseInt(message) != 0) {\n\t\t\t\tthrow new Exception(root.getChildText(\"ErrorMessage\"));\n\t\t\t}\n\t\t\tElement results = root.getChild(\"results\");\n\t\t\tfor (Object obj : results.getChildren(\"Result\")) {\n\t\t\t\tElement toponymElement = (Element) obj;\n\t\t\t\tGetLocationResult location = getLocationFromElement(toponymElement);\n\t\t\t\tsearchResult.add(location);\n\t\t\t}\n\t\t}\n\t\treturn searchResult;\n\t}",
"private void addUDFValue(FieldTypeClass fieldType, FieldContainer container, Row row)\n {\n Integer fieldId = row.getInteger(\"udf_type_id\");\n String fieldName = m_udfFields.get(fieldId);\n\n Object value = null;\n FieldType field = m_project.getCustomFields().getFieldByAlias(fieldType, fieldName);\n if (field != null)\n {\n DataType fieldDataType = field.getDataType();\n\n switch (fieldDataType)\n {\n case DATE:\n {\n value = row.getDate(\"udf_date\");\n break;\n }\n\n case CURRENCY:\n case NUMERIC:\n {\n value = row.getDouble(\"udf_number\");\n break;\n }\n\n case GUID:\n case INTEGER:\n {\n value = row.getInteger(\"udf_code_id\");\n break;\n }\n\n case BOOLEAN:\n {\n String text = row.getString(\"udf_text\");\n if (text != null)\n {\n // before a normal boolean parse, we try to lookup the text as a P6 static type indicator UDF\n value = STATICTYPE_UDF_MAP.get(text);\n if (value == null)\n {\n value = Boolean.valueOf(row.getBoolean(\"udf_text\"));\n }\n }\n else\n {\n value = Boolean.valueOf(row.getBoolean(\"udf_number\"));\n }\n break;\n }\n\n default:\n {\n value = row.getString(\"udf_text\");\n break;\n }\n }\n\n container.set(field, value);\n }\n }"
] |
This method removes all RTF formatting from a given piece of text.
@param text Text from which the RTF formatting is to be removed.
@return Plain text | [
"public static String strip(String text)\n {\n String result = text;\n if (text != null && !text.isEmpty())\n {\n try\n {\n boolean formalRTF = isFormalRTF(text);\n StringTextConverter stc = new StringTextConverter();\n stc.convert(new RtfStringSource(text));\n result = stripExtraLineEnd(stc.getText(), formalRTF);\n }\n catch (IOException ex)\n {\n result = \"\";\n }\n }\n\n return result;\n }"
] | [
"public static boolean xpathExists(Node document, String xpathExpression, Map<String, String> namespaceMapping) throws XPathException,\n MarshallingException\n {\n Boolean result = (Boolean) executeXPath(document, xpathExpression, namespaceMapping, XPathConstants.BOOLEAN);\n return result != null && result;\n }",
"public void removeLinks(ServiceReference<S> declarationBinderRef) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n if (declaration.getStatus().getServiceReferencesBounded().contains(declarationBinderRef)) {\n linkerManagement.unlink(declaration, declarationBinderRef);\n }\n }\n }",
"public static boolean containsOnlyNotNull(Object... values){\t\n\t\tfor(Object o : values){\n\t\t\tif(o== null){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}",
"private Query getQueryByCriteriaCount(QueryByCriteria aQuery)\r\n {\r\n Class searchClass = aQuery.getSearchClass();\r\n ReportQueryByCriteria countQuery = null;\r\n Criteria countCrit = null;\r\n String[] columns = new String[1];\r\n\r\n // BRJ: copied Criteria without groupby, orderby, and prefetched relationships\r\n if (aQuery.getCriteria() != null)\r\n {\r\n countCrit = aQuery.getCriteria().copy(false, false, false);\r\n }\r\n\r\n if (aQuery.isDistinct())\r\n {\r\n // BRJ: Count distinct is dbms dependent\r\n // hsql/sapdb: select count (distinct(person_id || project_id)) from person_project\r\n // mysql: select count (distinct person_id,project_id) from person_project\r\n // [tomdz]\r\n // Some databases have no support for multi-column count distinct (e.g. Derby)\r\n // Here we use a SELECT count(*) FROM (SELECT DISTINCT ...) instead \r\n //\r\n // concatenation of pk-columns is a simple way to obtain a single column\r\n // but concatenation is also dbms dependent:\r\n //\r\n // SELECT count(distinct concat(row1, row2, row3)) mysql\r\n // SELECT count(distinct (row1 || row2 || row3)) ansi\r\n // SELECT count(distinct (row1 + row2 + row3)) ms sql-server\r\n\r\n FieldDescriptor[] pkFields = m_broker.getClassDescriptor(searchClass).getPkFields();\r\n String[] keyColumns = new String[pkFields.length];\r\n\r\n if (pkFields.length > 1)\r\n {\r\n // TODO: Use ColumnName. This is a temporary solution because\r\n // we cannot yet resolve multiple columns in the same attribute.\r\n for (int idx = 0; idx < pkFields.length; idx++)\r\n {\r\n keyColumns[idx] = pkFields[idx].getColumnName();\r\n }\r\n }\r\n else\r\n {\r\n for (int idx = 0; idx < pkFields.length; idx++)\r\n {\r\n keyColumns[idx] = pkFields[idx].getAttributeName();\r\n }\r\n }\r\n // [tomdz]\r\n // TODO: Add support for databases that do not support COUNT DISTINCT over multiple columns\r\n// if (getPlatform().supportsMultiColumnCountDistinct())\r\n// {\r\n// columns[0] = \"count(distinct \" + getPlatform().concatenate(keyColumns) + \")\";\r\n// }\r\n// else\r\n// {\r\n// columns = keyColumns;\r\n// }\r\n\r\n columns[0] = \"count(distinct \" + getPlatform().concatenate(keyColumns) + \")\";\r\n }\r\n else\r\n {\r\n columns[0] = \"count(*)\";\r\n }\r\n\r\n // BRJ: we have to preserve indirection table !\r\n if (aQuery instanceof MtoNQuery)\r\n {\r\n MtoNQuery mnQuery = (MtoNQuery)aQuery;\r\n ReportQueryByMtoNCriteria mnReportQuery = new ReportQueryByMtoNCriteria(searchClass, columns, countCrit);\r\n\r\n mnReportQuery.setIndirectionTable(mnQuery.getIndirectionTable());\r\n countQuery = mnReportQuery;\r\n }\r\n else\r\n {\r\n countQuery = new ReportQueryByCriteria(searchClass, columns, countCrit);\r\n }\r\n\r\n // BRJ: we have to preserve outer-join-settings (by André Markwalder)\r\n for (Iterator outerJoinPath = aQuery.getOuterJoinPaths().iterator(); outerJoinPath.hasNext();)\r\n {\r\n String path = (String) outerJoinPath.next();\r\n\r\n if (aQuery.isPathOuterJoin(path))\r\n {\r\n countQuery.setPathOuterJoin(path);\r\n }\r\n }\r\n\r\n //BRJ: add orderBy Columns asJoinAttributes\r\n List orderBy = aQuery.getOrderBy();\r\n\r\n if ((orderBy != null) && !orderBy.isEmpty())\r\n {\r\n String[] joinAttributes = new String[orderBy.size()];\r\n\r\n for (int idx = 0; idx < orderBy.size(); idx++)\r\n {\r\n joinAttributes[idx] = ((FieldHelper)orderBy.get(idx)).name;\r\n }\r\n countQuery.setJoinAttributes(joinAttributes);\r\n }\r\n\r\n // [tomdz]\r\n // TODO:\r\n // For those databases that do not support COUNT DISTINCT over multiple columns\r\n // we wrap the normal SELECT DISTINCT that we just created, into a SELECT count(*)\r\n // For this however we need a report query that gets its data from a sub query instead\r\n // of a table (target class)\r\n// if (aQuery.isDistinct() && !getPlatform().supportsMultiColumnCountDistinct())\r\n// {\r\n// }\r\n\r\n return countQuery;\r\n }",
"public static String taskListToString(List<RebalanceTaskInfo> infos) {\n StringBuffer sb = new StringBuffer();\n for (RebalanceTaskInfo info : infos) {\n sb.append(\"\\t\").append(info.getDonorId()).append(\" -> \").append(info.getStealerId()).append(\" : [\");\n for (String storeName : info.getPartitionStores()) {\n sb.append(\"{\").append(storeName).append(\" : \").append(info.getPartitionIds(storeName)).append(\"}\");\n }\n sb.append(\"]\").append(Utils.NEWLINE);\n }\n return sb.toString();\n }",
"public static final String printTaskUID(Integer value)\n {\n ProjectFile file = PARENT_FILE.get();\n if (file != null)\n {\n file.getEventManager().fireTaskWrittenEvent(file.getTaskByUniqueID(value));\n }\n return (value.toString());\n }",
"private String parseMandatoryStringValue(final String path) throws Exception {\n\n final String value = parseOptionalStringValue(path);\n if (value == null) {\n throw new Exception();\n }\n return value;\n }",
"public Bundler put(String key, Parcelable value) {\n delegate.putParcelable(key, value);\n return this;\n }",
"@SuppressWarnings(\"unchecked\")\n public void setHeaders(final Map<String, Object> headers) {\n this.headers.clear();\n for (Map.Entry<String, Object> entry: headers.entrySet()) {\n if (entry.getValue() instanceof List) {\n List value = (List) entry.getValue();\n // verify they are all strings\n for (Object o: value) {\n Assert.isTrue(o instanceof String, o + \" is not a string it is a: '\" +\n o.getClass() + \"'\");\n }\n this.headers.put(entry.getKey(), (List<String>) entry.getValue());\n } else if (entry.getValue() instanceof String) {\n final List<String> value = Collections.singletonList((String) entry.getValue());\n this.headers.put(entry.getKey(), value);\n } else {\n throw new IllegalArgumentException(\"Only strings and list of strings may be headers\");\n }\n }\n }"
] |
Reports that a node is resolved hence other nodes depends on it can consume it.
@param completed the node ready to be consumed | [
"public void reportCompletion(NodeT completed) {\n completed.setPreparer(true);\n String dependency = completed.key();\n for (String dependentKey : nodeTable.get(dependency).dependentKeys()) {\n DAGNode<DataT, NodeT> dependent = nodeTable.get(dependentKey);\n dependent.lock().lock();\n try {\n dependent.onSuccessfulResolution(dependency);\n if (dependent.hasAllResolved()) {\n queue.add(dependent.key());\n }\n } finally {\n dependent.lock().unlock();\n }\n }\n }"
] | [
"protected static <T, A> ManagementRequestHandler<T, A> getFallbackHandler(final ManagementRequestHeader header) {\n return new ManagementRequestHandler<T, A>() {\n @Override\n public void handleRequest(final DataInput input, ActiveOperation.ResultHandler<T> resultHandler, ManagementRequestContext<A> context) throws IOException {\n final Exception error = ProtocolLogger.ROOT_LOGGER.noSuchResponseHandler(Integer.toHexString(header.getRequestId()));\n if(resultHandler.failed(error)) {\n safeWriteErrorResponse(context.getChannel(), context.getRequestHeader(), error);\n }\n }\n };\n }",
"public static appflowglobal_binding get(nitro_service service) throws Exception{\n\t\tappflowglobal_binding obj = new appflowglobal_binding();\n\t\tappflowglobal_binding response = (appflowglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private RelationType getRelationType(int type)\n {\n RelationType result;\n if (type > 0 && type < RELATION_TYPES.length)\n {\n result = RELATION_TYPES[type];\n }\n else\n {\n result = RelationType.FINISH_START;\n }\n return result;\n }",
"public static gslbservice_stats[] get(nitro_service service) throws Exception{\n\t\tgslbservice_stats obj = new gslbservice_stats();\n\t\tgslbservice_stats[] response = (gslbservice_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"public static BoxCollaborationWhitelist.Info create(final BoxAPIConnection api, String domain,\n WhitelistDirection direction) {\n\n URL url = COLLABORATION_WHITELIST_ENTRIES_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST);\n JsonObject requestJSON = new JsonObject()\n .add(\"domain\", domain)\n .add(\"direction\", direction.toString());\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxCollaborationWhitelist domainWhitelist =\n new BoxCollaborationWhitelist(api, responseJSON.get(\"id\").asString());\n\n return domainWhitelist.new Info(responseJSON);\n }",
"public void deleteModule(final String name, final String version, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getModulePath(name, version));\n final ClientResponse response = resource.delete(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"to delete module\", name, version);\n\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }",
"public static double getFloatingPointDateFromDate(LocalDateTime referenceDate, LocalDateTime date) {\n\t\tDuration duration = Duration.between(referenceDate, date);\n\t\treturn ((double)duration.getSeconds()) / SECONDS_PER_DAY;\n\t}",
"public static appfwlearningdata[] get(nitro_service service, appfwlearningdata_args args) throws Exception{\n\t\tappfwlearningdata obj = new appfwlearningdata();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tappfwlearningdata[] response = (appfwlearningdata[])obj.get_resources(service, option);\n\t\treturn response;\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}"
] |
Initialize; cached threadpool is safe as it is releasing resources automatically if idle | [
"public synchronized void init() {\n channelFactory = new NioClientSocketChannelFactory(\n Executors.newCachedThreadPool(),\n Executors.newCachedThreadPool());\n\n datagramChannelFactory = new NioDatagramChannelFactory(\n Executors.newCachedThreadPool());\n\n timer = new HashedWheelTimer();\n }"
] | [
"public static final int getShort(InputStream is) throws IOException\n {\n byte[] data = new byte[2];\n is.read(data);\n return getShort(data, 0);\n }",
"public static BsonDocument copyOfDocument(final BsonDocument document) {\n final BsonDocument newDocument = new BsonDocument();\n for (final Map.Entry<String, BsonValue> kv : document.entrySet()) {\n newDocument.put(kv.getKey(), kv.getValue());\n }\n return newDocument;\n }",
"private static String getScheme(Service service, Annotation... qualifiers) {\n for (Annotation q : qualifiers) {\n if (q instanceof Scheme) {\n return ((Scheme) q).value();\n }\n }\n\n if (service.getMetadata() != null && service.getMetadata().getAnnotations() != null) {\n String s = service.getMetadata().getAnnotations().get(SERVICE_SCHEME);\n if (s != null && s.isEmpty()) {\n return s;\n }\n }\n\n return DEFAULT_SCHEME;\n }",
"public static String removeOpenCmsContext(final String path) {\n\n String context = OpenCms.getSystemInfo().getOpenCmsContext();\n if (path.startsWith(context + \"/\")) {\n return path.substring(context.length());\n }\n String renderPrefix = OpenCms.getStaticExportManager().getVfsPrefix();\n if (path.startsWith(renderPrefix + \"/\")) {\n return path.substring(renderPrefix.length());\n }\n return path;\n }",
"private void readNetscapeExt() {\n do {\n readBlock();\n if (block[0] == 1) {\n // Loop count sub-block.\n int b1 = ((int) block[1]) & 0xff;\n int b2 = ((int) block[2]) & 0xff;\n header.loopCount = (b2 << 8) | b1;\n if(header.loopCount == 0) {\n header.loopCount = GifDecoder.LOOP_FOREVER;\n }\n }\n } while ((blockSize > 0) && !err());\n }",
"private Query getReportQueryByCriteriaCount(ReportQueryByCriteria aQuery)\r\n {\r\n ReportQueryByCriteria countQuery = (ReportQueryByCriteria) getQueryByCriteriaCount(aQuery);\r\n\r\n // BRJ: keep the original columns to build the Join\r\n countQuery.setJoinAttributes(aQuery.getAttributes());\r\n\r\n // BRJ: we have to preserve groupby information\r\n Iterator iter = aQuery.getGroupBy().iterator();\r\n while(iter.hasNext())\r\n {\r\n countQuery.addGroupBy((FieldHelper) iter.next());\r\n }\r\n\r\n return countQuery;\r\n }",
"public ArrayList<IntPoint> process(ImageSource fastBitmap) {\r\n //FastBitmap l = new FastBitmap(fastBitmap);\r\n if (points == null) {\r\n apply(fastBitmap);\r\n }\r\n\r\n int width = fastBitmap.getWidth();\r\n int height = fastBitmap.getHeight();\r\n points = new ArrayList<IntPoint>();\r\n\r\n if (fastBitmap.isGrayscale()) {\r\n for (int x = 0; x < height; x++) {\r\n for (int y = 0; y < width; y++) {\r\n if (fastBitmap.getRGB(y, x) == 255) points.add(new IntPoint(y, x));\r\n }\r\n }\r\n } else {\r\n for (int x = 0; x < height; x++) {\r\n for (int y = 0; y < width; y++) {\r\n // TODO Check for green and blue?\r\n if (fastBitmap.getR(y, x) == 255) points.add(new IntPoint(y, x));\r\n }\r\n }\r\n }\r\n\r\n return points;\r\n }",
"public Collection getReaders(Object obj)\r\n\t{\r\n\t\tCollection result = null;\r\n try\r\n {\r\n Identity oid = new Identity(obj, getBroker());\r\n byte selector = (byte) 'r';\r\n byte[] requestBarr = buildRequestArray(oid, selector);\r\n \r\n HttpURLConnection conn = getHttpUrlConnection();\r\n \r\n //post request\r\n BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());\r\n out.write(requestBarr,0,requestBarr.length);\r\n out.flush();\t\t\r\n \r\n // read result from \r\n InputStream in = conn.getInputStream();\r\n ObjectInputStream ois = new ObjectInputStream(in);\r\n result = (Collection) ois.readObject();\r\n \r\n // cleanup\r\n ois.close();\r\n out.close();\r\n conn.disconnect();\t\t\r\n }\r\n catch (Throwable t)\r\n {\r\n throw new PersistenceBrokerException(t);\r\n }\r\n return result;\r\n\t}",
"public static int cudnnSoftmaxForward(\n cudnnHandle handle, \n int algo, \n int mode, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnSoftmaxForwardNative(handle, algo, mode, alpha, xDesc, x, beta, yDesc, y));\n }"
] |
Find the animation associated with this avatar with the given name.
@param name name of animation to look for
@return {@link GVRAnimator} animation found or null if none with that name | [
"public GVRAnimator findAnimation(String name)\n {\n for (GVRAnimator anim : mAnimations)\n {\n if (name.equals(anim.getName()))\n {\n return anim;\n }\n }\n return null;\n }"
] | [
"protected synchronized void streamingSlopPut(ByteArray key,\n Versioned<byte[]> value,\n String storeName,\n int failedNodeId) throws IOException {\n\n Slop slop = new Slop(storeName,\n Slop.Operation.PUT,\n key,\n value.getValue(),\n null,\n failedNodeId,\n new Date());\n\n ByteArray slopKey = slop.makeKey();\n Versioned<byte[]> slopValue = new Versioned<byte[]>(slopSerializer.toBytes(slop),\n value.getVersion());\n\n Node failedNode = adminClient.getAdminClientCluster().getNodeById(failedNodeId);\n HandoffToAnyStrategy slopRoutingStrategy = new HandoffToAnyStrategy(adminClient.getAdminClientCluster(),\n true,\n failedNode.getZoneId());\n // node Id which will receive the slop\n int slopDestination = slopRoutingStrategy.routeHint(failedNode).get(0).getId();\n\n VAdminProto.PartitionEntry partitionEntry = VAdminProto.PartitionEntry.newBuilder()\n .setKey(ProtoUtils.encodeBytes(slopKey))\n .setVersioned(ProtoUtils.encodeVersioned(slopValue))\n .build();\n\n VAdminProto.UpdatePartitionEntriesRequest.Builder updateRequest = VAdminProto.UpdatePartitionEntriesRequest.newBuilder()\n .setStore(SLOP_STORE)\n .setPartitionEntry(partitionEntry);\n\n DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair<String, Integer>(SLOP_STORE,\n slopDestination));\n\n if(nodeIdStoreInitialized.get(new Pair<String, Integer>(SLOP_STORE, slopDestination))) {\n ProtoUtils.writeMessage(outputStream, updateRequest.build());\n } else {\n ProtoUtils.writeMessage(outputStream,\n VAdminProto.VoldemortAdminRequest.newBuilder()\n .setType(VAdminProto.AdminRequestType.UPDATE_PARTITION_ENTRIES)\n .setUpdatePartitionEntries(updateRequest)\n .build());\n outputStream.flush();\n nodeIdStoreInitialized.put(new Pair<String, Integer>(SLOP_STORE, slopDestination), true);\n\n }\n\n throttler.maybeThrottle(1);\n\n }",
"public void setKnotBlend(int n, int type) {\n\t\tknotTypes[n] = (byte)((knotTypes[n] & ~BLEND_MASK) | type);\n\t\trebuildGradient();\n\t}",
"public static <T extends Spin<?>> T S(Object input, DataFormat<T> format) {\n return SpinFactory.INSTANCE.createSpin(input, format);\n }",
"public TimephasedCostContainer getBaselineCost(ProjectCalendar calendar, TimephasedCostNormaliser normaliser, byte[] data, boolean raw)\n {\n TimephasedCostContainer result = null;\n\n if (data != null && data.length > 0)\n {\n LinkedList<TimephasedCost> list = null;\n\n //System.out.println(ByteArrayHelper.hexdump(data, false));\n int index = 16; // 16 byte header\n int blockSize = 20;\n double previousTotalCost = 0;\n\n Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 16);\n index += blockSize;\n\n while (index + blockSize <= data.length)\n {\n Date blockEndDate = MPPUtility.getTimestampFromTenths(data, index + 16);\n double currentTotalCost = (double) ((long) MPPUtility.getDouble(data, index + 8)) / 100;\n if (!costEquals(previousTotalCost, currentTotalCost))\n {\n TimephasedCost cost = new TimephasedCost();\n cost.setStart(blockStartDate);\n cost.setFinish(blockEndDate);\n cost.setTotalAmount(Double.valueOf(currentTotalCost - previousTotalCost));\n\n if (list == null)\n {\n list = new LinkedList<TimephasedCost>();\n }\n list.add(cost);\n //System.out.println(cost);\n\n previousTotalCost = currentTotalCost;\n }\n\n blockStartDate = blockEndDate;\n index += blockSize;\n }\n\n if (list != null)\n {\n result = new DefaultTimephasedCostContainer(calendar, normaliser, list, raw);\n }\n }\n\n return result;\n }",
"public static boolean isAlternative(EnhancedAnnotated<?, ?> annotated, MergedStereotypes<?, ?> mergedStereotypes) {\n return annotated.isAnnotationPresent(Alternative.class) || mergedStereotypes.isAlternative();\n }",
"public static TestSuiteResult unmarshal(File testSuite) throws IOException {\n try (InputStream stream = new FileInputStream(testSuite)) {\n return unmarshal(stream);\n }\n }",
"private static Data loadLeapSeconds(URL url) throws ClassNotFoundException, IOException {\n List<String> lines;\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) {\n lines = reader.lines().collect(Collectors.toList());\n }\n List<Long> dates = new ArrayList<>();\n List<Integer> offsets = new ArrayList<>();\n for (String line : lines) {\n line = line.trim();\n if (line.isEmpty() || line.startsWith(\"#\")) {\n continue;\n }\n Matcher matcher = LEAP_FILE_FORMAT.matcher(line);\n if (matcher.matches() == false) {\n throw new StreamCorruptedException(\"Invalid leap second file\");\n }\n dates.add(LocalDate.parse(matcher.group(1)).getLong(JulianFields.MODIFIED_JULIAN_DAY));\n offsets.add(Integer.valueOf(matcher.group(2)));\n }\n long[] datesData = new long[dates.size()];\n int[] offsetsData = new int[dates.size()];\n long[] taiData = new long[dates.size()];\n for (int i = 0; i < datesData.length; i++) {\n datesData[i] = dates.get(i);\n offsetsData[i] = offsets.get(i);\n taiData[i] = tai(datesData[i], offsetsData[i]);\n }\n return new Data(datesData, offsetsData, taiData);\n }",
"public static vlan get(nitro_service service, Long id) throws Exception{\n\t\tvlan obj = new vlan();\n\t\tobj.set_id(id);\n\t\tvlan response = (vlan) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public Photoset getInfo(String photosetId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\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 photosetElement = response.getPayload();\r\n Photoset photoset = new Photoset();\r\n photoset.setId(photosetElement.getAttribute(\"id\"));\r\n\r\n User owner = new User();\r\n owner.setId(photosetElement.getAttribute(\"owner\"));\r\n photoset.setOwner(owner);\r\n\r\n Photo primaryPhoto = new Photo();\r\n primaryPhoto.setId(photosetElement.getAttribute(\"primary\"));\r\n primaryPhoto.setSecret(photosetElement.getAttribute(\"secret\")); // TODO verify that this is the secret for the photo\r\n primaryPhoto.setServer(photosetElement.getAttribute(\"server\")); // TODO verify that this is the server for the photo\r\n primaryPhoto.setFarm(photosetElement.getAttribute(\"farm\"));\r\n photoset.setPrimaryPhoto(primaryPhoto);\r\n\r\n // TODO remove secret/server/farm from photoset?\r\n // It's rather related to the primaryPhoto, then to the photoset itself.\r\n photoset.setSecret(photosetElement.getAttribute(\"secret\"));\r\n photoset.setServer(photosetElement.getAttribute(\"server\"));\r\n photoset.setFarm(photosetElement.getAttribute(\"farm\"));\r\n photoset.setPhotoCount(photosetElement.getAttribute(\"count_photos\"));\r\n photoset.setVideoCount(Integer.parseInt(photosetElement.getAttribute(\"count_videos\")));\r\n photoset.setViewCount(Integer.parseInt(photosetElement.getAttribute(\"count_views\")));\r\n photoset.setCommentCount(Integer.parseInt(photosetElement.getAttribute(\"count_comments\")));\r\n photoset.setDateCreate(photosetElement.getAttribute(\"date_create\"));\r\n photoset.setDateUpdate(photosetElement.getAttribute(\"date_update\"));\r\n\r\n photoset.setIsCanComment(\"1\".equals(photosetElement.getAttribute(\"can_comment\")));\r\n\r\n photoset.setTitle(XMLUtilities.getChildValue(photosetElement, \"title\"));\r\n photoset.setDescription(XMLUtilities.getChildValue(photosetElement, \"description\"));\r\n photoset.setPrimaryPhoto(primaryPhoto);\r\n\r\n return photoset;\r\n }"
] |
Add data for a column to this table.
@param column column data | [
"public void addColumn(FastTrackColumn column)\n {\n FastTrackField type = column.getType();\n Object[] data = column.getData();\n for (int index = 0; index < data.length; index++)\n {\n MapRow row = getRow(index);\n row.getMap().put(type, data[index]);\n }\n }"
] | [
"private boolean addonDependsOnReporting(Addon addon)\n {\n for (AddonDependency dep : addon.getDependencies())\n {\n if (dep.getDependency().equals(this.addon))\n {\n return true;\n }\n boolean subDep = addonDependsOnReporting(dep.getDependency());\n if (subDep)\n {\n return true;\n }\n }\n return false;\n }",
"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 }",
"private Collection parseTreeCollection(Element collectionElement) {\n\n Collection collection = new Collection();\n parseCommonFields(collectionElement, collection);\n collection.setTitle(collectionElement.getAttribute(\"title\"));\n collection.setDescription(collectionElement.getAttribute(\"description\"));\n\n // Collections can contain either sets or collections (but not both)\n NodeList childCollectionElements = collectionElement.getElementsByTagName(\"collection\");\n for (int i = 0; i < childCollectionElements.getLength(); i++) {\n Element childCollectionElement = (Element) childCollectionElements.item(i);\n collection.addCollection(parseTreeCollection(childCollectionElement));\n }\n\n NodeList childPhotosetElements = collectionElement.getElementsByTagName(\"set\");\n for (int i = 0; i < childPhotosetElements.getLength(); i++) {\n Element childPhotosetElement = (Element) childPhotosetElements.item(i);\n collection.addPhotoset(createPhotoset(childPhotosetElement));\n }\n\n return collection;\n }",
"public static BatchASTFuture analyze(final BatchASTListener listener, final WildcardImportResolver importResolver,\n final Set<String> libraryPaths,\n final Set<String> sourcePaths, Set<Path> sourceFiles)\n {\n\n final String[] encodings = null;\n final String[] bindingKeys = new String[0];\n final ExecutorService executor = WindupExecutors.newFixedThreadPool(WindupExecutors.getDefaultThreadCount());\n final FileASTRequestor requestor = new FileASTRequestor()\n {\n @Override\n public void acceptAST(String sourcePath, CompilationUnit ast)\n {\n try\n {\n /*\n * This super() call doesn't do anything, but we call it just to be nice, in case that ever changes.\n */\n super.acceptAST(sourcePath, ast);\n ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, ast, sourcePath);\n ast.accept(visitor);\n listener.processed(Paths.get(sourcePath), visitor.getJavaClassReferences());\n }\n catch (WindupStopException ex)\n {\n throw ex;\n }\n catch (Throwable t)\n {\n listener.failed(Paths.get(sourcePath), t);\n }\n }\n };\n\n List<List<String>> batches = createBatches(sourceFiles);\n\n for (final List<String> batch : batches)\n {\n executor.submit(new Callable<Void>()\n {\n @Override\n public Void call() throws Exception\n {\n ASTParser parser = ASTParser.newParser(AST.JLS8);\n parser.setBindingsRecovery(false);\n parser.setResolveBindings(true);\n Map<String, String> options = JavaCore.getOptions();\n JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);\n // these options seem to slightly reduce the number of times that JDT aborts on compilation errors\n options.put(JavaCore.CORE_INCOMPLETE_CLASSPATH, \"warning\");\n options.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, \"warning\");\n options.put(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, \"warning\");\n options.put(JavaCore.CORE_CIRCULAR_CLASSPATH, \"warning\");\n options.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, \"warning\");\n options.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION, \"warning\");\n options.put(JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, \"ignore\");\n options.put(JavaCore.COMPILER_PB_NULL_ANNOTATION_INFERENCE_CONFLICT, \"warning\");\n options.put(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, \"warning\");\n options.put(JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, \"warning\");\n\n parser.setCompilerOptions(options);\n parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]),\n sourcePaths.toArray(new String[sourcePaths.size()]),\n null,\n true);\n\n parser.createASTs(batch.toArray(new String[batch.size()]), encodings, bindingKeys, requestor, null);\n return null;\n }\n });\n }\n\n executor.shutdown();\n\n return new BatchASTFuture()\n {\n @Override\n public boolean isDone()\n {\n return executor.isTerminated();\n }\n };\n }",
"public static base_response update(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager updateresource = new snmpmanager();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.netmask = resource.netmask;\n\t\tupdateresource.domainresolveretry = resource.domainresolveretry;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public InputStream call(String methodName, MessageLite request) throws DatastoreException {\n logger.fine(\"remote datastore call \" + methodName);\n\n long startTime = System.currentTimeMillis();\n try {\n HttpResponse httpResponse;\n try {\n rpcCount.incrementAndGet();\n ProtoHttpContent payload = new ProtoHttpContent(request);\n HttpRequest httpRequest = client.buildPostRequest(resolveURL(methodName), payload);\n httpRequest.getHeaders().put(API_FORMAT_VERSION_HEADER, API_FORMAT_VERSION);\n // Don't throw an HTTPResponseException on error. It converts the response to a String and\n // throws away the original, whereas we need the raw bytes to parse it as a proto.\n httpRequest.setThrowExceptionOnExecuteError(false);\n // Datastore requests typically time out after 60s; set the read timeout to slightly longer\n // than that by default (can be overridden via the HttpRequestInitializer).\n httpRequest.setReadTimeout(65 * 1000);\n if (initializer != null) {\n initializer.initialize(httpRequest);\n }\n httpResponse = httpRequest.execute();\n if (!httpResponse.isSuccessStatusCode()) {\n try (InputStream content = GzipFixingInputStream.maybeWrap(httpResponse.getContent())) {\n throw makeException(url, methodName, content,\n httpResponse.getContentType(), httpResponse.getContentCharset(), null,\n httpResponse.getStatusCode());\n }\n }\n return GzipFixingInputStream.maybeWrap(httpResponse.getContent());\n } catch (SocketTimeoutException e) {\n throw makeException(url, methodName, Code.DEADLINE_EXCEEDED, \"Deadline exceeded\", e);\n } catch (IOException e) {\n throw makeException(url, methodName, Code.UNAVAILABLE, \"I/O error\", e);\n }\n } finally {\n long elapsedTime = System.currentTimeMillis() - startTime;\n logger.fine(\"remote datastore call \" + methodName + \" took \" + elapsedTime + \" ms\");\n }\n }",
"private String filterAttributes(String html) {\n\t\tString filteredHtml = html;\n\t\tfor (String attribute : this.filterAttributes) {\n\t\t\tString regex = \"\\\\s\" + attribute + \"=\\\"[^\\\"]*\\\"\";\n\t\t\tPattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);\n\t\t\tMatcher m = p.matcher(html);\n\t\t\tfilteredHtml = m.replaceAll(\"\");\n\t\t}\n\t\treturn filteredHtml;\n\t}",
"public void fire(StepEvent event) {\n Step step = stepStorage.getLast();\n event.process(step);\n\n notifier.fire(event);\n }",
"public static boolean isSameStructure(DMatrixSparseCSC a , DMatrixSparseCSC b) {\n if( a.numRows == b.numRows && a.numCols == b.numCols && a.nz_length == b.nz_length) {\n for (int i = 0; i <= a.numCols; i++) {\n if( a.col_idx[i] != b.col_idx[i] )\n return false;\n }\n for (int i = 0; i < a.nz_length; i++) {\n if( a.nz_rows[i] != b.nz_rows[i] )\n return false;\n }\n return true;\n }\n return false;\n }"
] |
Write a priority field to the JSON file.
@param fieldName field name
@param value field value | [
"private void writePriorityField(String fieldName, Object value) throws IOException\n {\n m_writer.writeNameValuePair(fieldName, ((Priority) value).getValue());\n }"
] | [
"public void serializeTimingData(Path outputPath)\n {\n //merge subThreads instances into the main instance\n merge();\n\n try (FileWriter fw = new FileWriter(outputPath.toFile()))\n {\n fw.write(\"Number Of Executions, Total Milliseconds, Milliseconds per execution, Type\\n\");\n for (Map.Entry<String, TimingData> timing : executionInfo.entrySet())\n {\n TimingData data = timing.getValue();\n long totalMillis = (data.totalNanos / 1000000);\n double millisPerExecution = (double) totalMillis / (double) data.numberOfExecutions;\n fw.write(String.format(\"%6d, %6d, %8.2f, %s\\n\",\n data.numberOfExecutions, totalMillis, millisPerExecution,\n StringEscapeUtils.escapeCsv(timing.getKey())\n ));\n }\n }\n catch (Exception e)\n {\n e.printStackTrace();\n }\n }",
"public static double elementSumSq( DMatrixD1 m ) {\n\n // minimize round off error\n double maxAbs = CommonOps_DDRM.elementMaxAbs(m);\n if( maxAbs == 0)\n return 0;\n\n double total = 0;\n \n int N = m.getNumElements();\n for( int i = 0; i < N; i++ ) {\n double d = m.data[i]/maxAbs;\n total += d*d;\n }\n\n return maxAbs*total*maxAbs;\n }",
"protected boolean isChangedByMask(int maskValue, Integer segmentPrefixLength) throws IncompatibleAddressException {\r\n\t\tboolean hasBits = (segmentPrefixLength != null);\r\n\t\tif(hasBits && (segmentPrefixLength < 0 || segmentPrefixLength > getBitCount())) {\r\n\t\t\tthrow new PrefixLenException(this, segmentPrefixLength);\r\n\t\t}\r\n\t\t\r\n\t\t//note that the mask can represent a range (for example a CIDR mask), \r\n\t\t//but we use the lowest value (maskSegment.value) in the range when masking (ie we discard the range)\r\n\t\tint value = getSegmentValue();\r\n\t\tint upperValue = getUpperSegmentValue();\r\n\t\treturn value != (value & maskValue) ||\r\n\t\t\t\tupperValue != (upperValue & maskValue) ||\r\n\t\t\t\t\t\t(isPrefixed() ? !getSegmentPrefixLength().equals(segmentPrefixLength) : hasBits);\r\n\t}",
"void sendError(HttpResponseStatus status, Throwable ex) {\n String msg;\n\n if (ex instanceof InvocationTargetException) {\n msg = String.format(\"Exception Encountered while processing request : %s\", ex.getCause().getMessage());\n } else {\n msg = String.format(\"Exception Encountered while processing request: %s\", ex.getMessage());\n }\n\n // Send the status and message, followed by closing of the connection.\n responder.sendString(status, msg, new DefaultHttpHeaders().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE));\n if (bodyConsumer != null) {\n bodyConsumerError(ex);\n }\n }",
"private PersistentResourceXMLDescription getSimpleMapperParser() {\n if (version.equals(Version.VERSION_1_0)) {\n return simpleMapperParser_1_0;\n } else if (version.equals(Version.VERSION_1_1)) {\n return simpleMapperParser_1_1;\n }\n return simpleMapperParser;\n }",
"public void registerDatatype(Class<? extends GVRHybridObject> textureClass,\n AsyncLoaderFactory<? extends GVRHybridObject, ?> asyncLoaderFactory) {\n mFactories.put(textureClass, asyncLoaderFactory);\n }",
"protected void addSpecialMethods(ClassFile proxyClassType, ClassMethod staticConstructor) {\n try {\n // Add special methods for interceptors\n for (Method method : LifecycleMixin.class.getMethods()) {\n BeanLogger.LOG.addingMethodToProxy(method);\n MethodInformation methodInfo = new RuntimeMethodInformation(method);\n createInterceptorBody(proxyClassType.addMethod(method), methodInfo, false, staticConstructor);\n }\n Method getInstanceMethod = TargetInstanceProxy.class.getMethod(\"weld_getTargetInstance\");\n Method getInstanceClassMethod = TargetInstanceProxy.class.getMethod(\"weld_getTargetClass\");\n generateGetTargetInstanceBody(proxyClassType.addMethod(getInstanceMethod));\n generateGetTargetClassBody(proxyClassType.addMethod(getInstanceClassMethod));\n\n Method setMethodHandlerMethod = ProxyObject.class.getMethod(\"weld_setHandler\", MethodHandler.class);\n generateSetMethodHandlerBody(proxyClassType.addMethod(setMethodHandlerMethod));\n\n Method getMethodHandlerMethod = ProxyObject.class.getMethod(\"weld_getHandler\");\n generateGetMethodHandlerBody(proxyClassType.addMethod(getMethodHandlerMethod));\n } catch (Exception e) {\n throw new WeldException(e);\n }\n }",
"public static <K, V> Map<K, V> copyOf(Map<K, V> map) {\n Preconditions.checkNotNull(map);\n return ImmutableMap.<K, V> builder().putAll(map).build();\n }",
"private void processResource(MapRow row) throws IOException\n {\n Resource resource = m_project.addResource();\n resource.setName(row.getString(\"NAME\"));\n resource.setGUID(row.getUUID(\"UUID\"));\n resource.setEmailAddress(row.getString(\"EMAIL\"));\n resource.setHyperlink(row.getString(\"URL\"));\n resource.setNotes(getNotes(row.getRows(\"COMMENTARY\")));\n resource.setText(1, row.getString(\"DESCRIPTION\"));\n resource.setText(2, row.getString(\"SUPPLY_REFERENCE\"));\n resource.setActive(true);\n\n List<MapRow> resources = row.getRows(\"RESOURCES\");\n if (resources != null)\n {\n for (MapRow childResource : sort(resources, \"NAME\"))\n {\n processResource(childResource);\n }\n }\n\n m_resourceMap.put(resource.getGUID(), resource);\n }"
] |
Reset the internal state of this object back to what it originally was.
Used then reloading a server or in a slave host controller following a post-boot reconnect
to the master. | [
"public synchronized void reset() {\n this.authorizerDescription = StandardRBACAuthorizer.AUTHORIZER_DESCRIPTION;\n this.useIdentityRoles = this.nonFacadeMBeansSensitive = false;\n this.roleMappings = new HashMap<String, RoleMappingImpl>();\n RoleMaps oldRoleMaps = this.roleMaps;\n this.roleMaps = new RoleMaps(authorizerDescription.getStandardRoles(), Collections.<String, ScopedRole>emptyMap());\n for (ScopedRole role : oldRoleMaps.scopedRoles.values()) {\n for (ScopedRoleListener listener : scopedRoleListeners) {\n try {\n listener.scopedRoleRemoved(role);\n } catch (Exception ignored) {\n // TODO log an ERROR\n }\n }\n }\n }"
] | [
"public void processAnonymousReference(Properties attributes) throws XDocletException\r\n {\r\n ReferenceDescriptorDef refDef = _curClassDef.getReference(\"super\");\r\n String attrName;\r\n\r\n if (refDef == null)\r\n {\r\n refDef = new ReferenceDescriptorDef(\"super\");\r\n _curClassDef.addReference(refDef);\r\n }\r\n refDef.setAnonymous();\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processAnonymousReference\", \" Processing anonymous reference\");\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n refDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n }",
"void setFilters(Map<Object, Object> filters) {\n\n for (Object column : filters.keySet()) {\n Object filterValue = filters.get(column);\n if ((filterValue != null) && !filterValue.toString().isEmpty() && !m_table.isColumnCollapsed(column)) {\n m_table.setFilterFieldValue(column, filterValue);\n }\n }\n }",
"public String calculateCacheKey(String sql, int[] columnIndexes) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+4);\r\n\t\ttmp.append(sql);\r\n\t\tfor (int i=0; i < columnIndexes.length; i++){\r\n\t\t\ttmp.append(columnIndexes[i]);\r\n\t\t\ttmp.append(\"CI,\");\r\n\t\t}\r\n\t\treturn tmp.toString();\r\n\t}",
"private void proxyPause() {\n logger.info(\"Pausing after cluster state has changed to allow proxy bridges to be established. \"\n + \"Will start rebalancing work on servers in \"\n + proxyPauseSec\n + \" seconds.\");\n try {\n Thread.sleep(TimeUnit.SECONDS.toMillis(proxyPauseSec));\n } catch(InterruptedException e) {\n logger.warn(\"Sleep interrupted in proxy pause.\");\n }\n }",
"public SqlStatement getPreparedDeleteStatement(ClassDescriptor cld)\r\n {\r\n SqlForClass sfc = getSqlForClass(cld);\r\n SqlStatement sql = sfc.getDeleteSql();\r\n if(sql == null)\r\n {\r\n ProcedureDescriptor pd = cld.getDeleteProcedure();\r\n\r\n if(pd == null)\r\n {\r\n sql = new SqlDeleteByPkStatement(cld, logger);\r\n }\r\n else\r\n {\r\n sql = new SqlProcedureStatement(pd, logger);\r\n }\r\n // set the sql string\r\n sfc.setDeleteSql(sql);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n }\r\n return sql;\r\n }",
"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 Indexes listIndexes() {\n URI uri = new DatabaseURIHelper(db.getDBUri()).path(\"_index\").build();\n return client.couchDbClient.get(uri, Indexes.class);\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 }",
"public static String getPrettyMapOfContiguousPartitionRunLengths(final Cluster cluster,\n int zoneId) {\n Map<Integer, Integer> runLengthToCount = getMapOfContiguousPartitionRunLengths(cluster,\n zoneId);\n String prettyHistogram = \"[\";\n boolean first = true;\n Set<Integer> runLengths = new TreeSet<Integer>(runLengthToCount.keySet());\n for(int runLength: runLengths) {\n if(first) {\n first = false;\n } else {\n prettyHistogram += \", \";\n }\n prettyHistogram += \"{\" + runLength + \" : \" + runLengthToCount.get(runLength) + \"}\";\n }\n prettyHistogram += \"]\";\n return prettyHistogram;\n }"
] |
Append a SubQuery the SQL-Clause
@param subQuery the subQuery value of SelectionCriteria | [
"private void appendSubQuery(Query subQuery, StringBuffer buf)\r\n {\r\n buf.append(\" (\");\r\n buf.append(getSubQuerySQL(subQuery));\r\n buf.append(\") \");\r\n }"
] | [
"public static int timezoneOffset(H.Session session) {\n String s = null != session ? session.get(SESSION_KEY) : null;\n return S.notBlank(s) ? Integer.parseInt(s) : serverTimezoneOffset();\n }",
"void persist(final String key, final String value, final boolean enableDisableMode, final boolean disable, final File file, final String realm) throws IOException, StartException {\n final PropertiesFileLoader propertiesHandler = realm == null ? new PropertiesFileLoader(file.getAbsolutePath(), null) :\n new UserPropertiesFileLoader(file.getAbsolutePath(), null);\n try {\n propertiesHandler.start(null);\n if (realm != null) {\n ((UserPropertiesFileLoader) propertiesHandler).setRealmName(realm);\n }\n Properties prob = propertiesHandler.getProperties();\n if (value != null) {\n prob.setProperty(key, value);\n }\n if (enableDisableMode) {\n prob.setProperty(key + \"!disable\", String.valueOf(disable));\n }\n propertiesHandler.persistProperties();\n } finally {\n propertiesHandler.stop(null);\n }\n }",
"@NonNull\n @Override\n public Loader<SortedList<FtpFile>> getLoader() {\n return new AsyncTaskLoader<SortedList<FtpFile>>(getContext()) {\n @Override\n public SortedList<FtpFile> loadInBackground() {\n SortedList<FtpFile> sortedList = new SortedList<>(FtpFile.class, new SortedListAdapterCallback<FtpFile>(getDummyAdapter()) {\n @Override\n public int compare(FtpFile lhs, FtpFile rhs) {\n if (lhs.isDirectory() && !rhs.isDirectory()) {\n return -1;\n } else if (rhs.isDirectory() && !lhs.isDirectory()) {\n return 1;\n } else {\n return lhs.getName().compareToIgnoreCase(rhs.getName());\n }\n }\n\n @Override\n public boolean areContentsTheSame(FtpFile oldItem, FtpFile newItem) {\n return oldItem.getName().equals(newItem.getName());\n }\n\n @Override\n public boolean areItemsTheSame(FtpFile item1, FtpFile item2) {\n return item1.getName().equals(item2.getName());\n }\n });\n\n\n if (!ftp.isConnected()) {\n // Connect\n try {\n ftp.connect(server, port);\n\n ftp.setFileType(FTP.ASCII_FILE_TYPE);\n ftp.enterLocalPassiveMode();\n ftp.setUseEPSVwithIPv4(false);\n\n if (!(loggedIn = ftp.login(username, password))) {\n ftp.logout();\n Log.e(TAG, \"Login failed\");\n }\n } catch (IOException e) {\n if (ftp.isConnected()) {\n try {\n ftp.disconnect();\n } catch (IOException ignored) {\n }\n }\n Log.e(TAG, \"Could not connect to server.\");\n }\n }\n\n if (loggedIn) {\n try {\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n sortedList.beginBatchedUpdates();\n for (FTPFile f : ftp.listFiles(mCurrentPath.getPath())) {\n FtpFile file;\n if (f.isDirectory()) {\n file = new FtpDir(mCurrentPath, f.getName());\n } else {\n file = new FtpFile(mCurrentPath, f.getName());\n }\n if (isItemVisible(file)) {\n sortedList.add(file);\n }\n }\n sortedList.endBatchedUpdates();\n } catch (IOException e) {\n Log.e(TAG, \"IOException: \" + e.getMessage());\n }\n }\n\n return sortedList;\n }\n\n /**\n * Handles a request to start the Loader.\n */\n @Override\n protected void onStartLoading() {\n super.onStartLoading();\n\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n forceLoad();\n }\n };\n }",
"public Metadata createMetadata(String templateName, String scope, Metadata metadata) {\n URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, templateName);\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"POST\");\n request.addHeader(\"Content-Type\", \"application/json\");\n request.setBody(metadata.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new Metadata(JsonObject.readFrom(response.getJSON()));\n }",
"protected String addDependency(TaskGroup.HasTaskGroup dependency) {\n Objects.requireNonNull(dependency);\n this.taskGroup().addDependencyTaskGroup(dependency.taskGroup());\n return dependency.taskGroup().key();\n }",
"@SuppressWarnings(\"unchecked\")\n private void setProxyRequestHeaders(HttpServletRequest httpServletRequest,\n HttpMethod httpMethodProxyRequest) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n String hostName = HttpUtilities.getHostNameFromURL(httpServletRequest.getRequestURL().toString());\n // Get an Enumeration of all of the header names sent by the client\n Boolean stripTransferEncoding = false;\n Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames();\n while (enumerationOfHeaderNames.hasMoreElements()) {\n String stringHeaderName = enumerationOfHeaderNames.nextElement();\n if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)) {\n // don't add this header\n continue;\n }\n\n // The forwarding proxy may supply a POST encoding hint in ODO-POST-TYPE\n if (stringHeaderName.equalsIgnoreCase(\"ODO-POST-TYPE\") &&\n httpServletRequest.getHeader(\"ODO-POST-TYPE\").startsWith(\"content-length:\")) {\n stripTransferEncoding = true;\n }\n\n logger.info(\"Current header: {}\", stringHeaderName);\n // As per the Java Servlet API 2.5 documentation:\n // Some headers, such as Accept-Language can be sent by clients\n // as several headers each with a different value rather than\n // sending the header as a comma separated list.\n // Thus, we get an Enumeration of the header values sent by the\n // client\n Enumeration<String> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);\n\n while (enumerationOfHeaderValues.hasMoreElements()) {\n String stringHeaderValue = enumerationOfHeaderValues.nextElement();\n // In case the proxy host is running multiple virtual servers,\n // rewrite the Host header to ensure that we get content from\n // the correct virtual server\n if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME) &&\n requestInfo.handle) {\n String hostValue = getHostHeaderForHost(hostName);\n if (hostValue != null) {\n stringHeaderValue = hostValue;\n }\n }\n\n Header header = new Header(stringHeaderName, stringHeaderValue);\n // Set the same header on the proxy request\n httpMethodProxyRequest.addRequestHeader(header);\n }\n }\n\n // this strips transfer encoding headers and adds in the appropriate content-length header\n // based on the hint provided in the ODO-POST-TYPE header(sent from BrowserMobProxyHandler)\n if (stripTransferEncoding) {\n httpMethodProxyRequest.removeRequestHeader(\"transfer-encoding\");\n\n // add content length back in based on the ODO information\n String contentLengthHint = httpServletRequest.getHeader(\"ODO-POST-TYPE\");\n String[] contentLengthParts = contentLengthHint.split(\":\");\n httpMethodProxyRequest.addRequestHeader(\"content-length\", contentLengthParts[1]);\n\n // remove the odo-post-type header\n httpMethodProxyRequest.removeRequestHeader(\"ODO-POST-TYPE\");\n }\n\n // bail if we aren't fully handling this request\n if (!requestInfo.handle) {\n return;\n }\n\n // deal with header overrides for the request\n processRequestHeaderOverrides(httpMethodProxyRequest);\n }",
"public static String encodeUserInfo(String userInfo, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(userInfo, encoding, HierarchicalUriComponents.Type.USER_INFO);\n\t}",
"public static int removeDuplicateNodeList(List<String> list) {\n\n int originCount = list.size();\n // add elements to all, including duplicates\n HashSet<String> hs = new LinkedHashSet<String>();\n hs.addAll(list);\n list.clear();\n list.addAll(hs);\n\n return originCount - list.size();\n }",
"public static<T> SessionVar<T> vendSessionVar(T defValue) {\n\treturn (new VarsJBridge()).vendSessionVar(defValue, new Exception());\n }"
] |
Creates a new RgbaColor from the specified HSL components.
<p>
<i>Implementation based on <a
href="http://en.wikipedia.org/wiki/HSL_and_HSV">wikipedia</a>
and <a
href="http://www.w3.org/TR/css3-color/#hsl-color">w3c</a></i>
@param H
Hue [0,360)
@param S
Saturation [0,100]
@param L
Lightness [0,100] | [
"public static RgbaColor fromHsl(float H, float S, float L) {\n\n // convert to [0-1]\n H /= 360f;\n S /= 100f;\n L /= 100f;\n\n float R, G, B;\n\n if (S == 0) {\n // grey\n R = G = B = L;\n }\n else {\n float m2 = L <= 0.5 ? L * (S + 1f) : L + S - L * S;\n float m1 = 2f * L - m2;\n R = hue2rgb(m1, m2, H + 1 / 3f);\n G = hue2rgb(m1, m2, H);\n B = hue2rgb(m1, m2, H - 1 / 3f);\n }\n\n // convert [0-1] to [0-255]\n int r = Math.round(R * 255f);\n int g = Math.round(G * 255f);\n int b = Math.round(B * 255f);\n\n return new RgbaColor(r, g, b, 1);\n }"
] | [
"public static int[] arrayFromStringOfIntegers(String str) throws IllegalArgumentException {\n StringTokenizer tokenizer = new StringTokenizer(str, \",\");\n int n = tokenizer.countTokens();\n int[] list = new int[n];\n for (int i = 0; i < n; i++) {\n String token = tokenizer.nextToken();\n list[i] = Integer.parseInt(token);\n }\n return list;\n }",
"boolean deleteEntity(@NotNull final PersistentStoreTransaction txn, @NotNull final PersistentEntity entity) {\n clearProperties(txn, entity);\n clearBlobs(txn, entity);\n deleteLinks(txn, entity);\n final PersistentEntityId id = entity.getId();\n final int entityTypeId = id.getTypeId();\n final long entityLocalId = id.getLocalId();\n final ByteIterable key = LongBinding.longToCompressedEntry(entityLocalId);\n if (config.isDebugSearchForIncomingLinksOnDelete()) {\n // search for incoming links\n final List<String> allLinkNames = getAllLinkNames(txn);\n for (final String entityType : txn.getEntityTypes()) {\n for (final String linkName : allLinkNames) {\n //noinspection LoopStatementThatDoesntLoop\n for (final Entity referrer : txn.findLinks(entityType, entity, linkName)) {\n throw new EntityStoreException(entity +\n \" is about to be deleted, but it is referenced by \" + referrer + \", link name: \" + linkName);\n }\n }\n }\n }\n if (getEntitiesTable(txn, entityTypeId).delete(txn.getEnvironmentTransaction(), key)) {\n txn.entityDeleted(id);\n return true;\n }\n return false;\n }",
"@Subscribe\n public void onEnd(AggregatedQuitEvent e) {\n try {\n writeHints(hintsFile, hints);\n } catch (IOException exception) {\n outer.log(\"Could not write back the hints file.\", exception, Project.MSG_ERR);\n }\n }",
"public void setSchema(String schema)\n {\n if (schema == null)\n {\n schema = \"\";\n }\n else\n {\n if (!schema.isEmpty() && !schema.endsWith(\".\"))\n {\n schema = schema + '.';\n }\n }\n m_schema = schema;\n }",
"private RandomVariableInterface getDrift(int timeIndex, int componentIndex, RandomVariableInterface[] realizationAtTimeIndex, RandomVariableInterface[] realizationPredictor) {\n\n\t\t// Check if this LIBOR is already fixed\n\t\tif(getTime(timeIndex) >= this.getLiborPeriod(componentIndex)) {\n\t\t\treturn null;\n\t\t}\n\n\t\t/*\n\t\t * We implemented several different methods to calculate the drift\n\t\t */\n\t\tif(driftApproximationMethod == Driftapproximation.PREDICTOR_CORRECTOR && realizationPredictor != null) {\n\t\t\tRandomVariableInterface drift\t\t\t\t\t= getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex);\n\t\t\tRandomVariableInterface driftEulerWithPredictor\t= getDriftEuler(timeIndex, componentIndex, realizationPredictor);\n\t\t\tdrift = drift.add(driftEulerWithPredictor).div(2.0);\n\n\t\t\treturn drift;\n\t\t}\n\t\telse if(driftApproximationMethod == Driftapproximation.LINE_INTEGRAL && realizationPredictor != null) {\n\t\t\treturn getDriftLineIntegral(timeIndex, componentIndex, realizationAtTimeIndex, realizationPredictor);\n\t\t}\n\t\telse {\n\t\t\treturn getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex);\n\t\t}\n\t}",
"public static ServiceName channelServiceName(final ServiceName endpointName, final String channelName) {\n return endpointName.append(\"channel\").append(channelName);\n }",
"@SuppressWarnings(\"unchecked\")\n public <V3, M4, C, N, Q> V3 getUp(AiWrapperProvider<V3, M4, C, N, Q> \n wrapperProvider) {\n \n return (V3) m_up;\n }",
"public final void setHost(final String host) throws UnknownHostException {\n this.host = host;\n final InetAddress[] inetAddresses = InetAddress.getAllByName(host);\n\n for (InetAddress address: inetAddresses) {\n final AddressHostMatcher matcher = new AddressHostMatcher();\n matcher.setIp(address.getHostAddress());\n this.matchersForHost.add(matcher);\n }\n }",
"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 }"
] |
Creates custom Http Client connection pool to be used by Http Client
@return {@link PoolingHttpClientConnectionManager} | [
"private PoolingHttpClientConnectionManager createConnectionMgr() {\n PoolingHttpClientConnectionManager connectionMgr;\n\n // prepare SSLContext\n SSLContext sslContext = buildSslContext();\n ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();\n // we allow to disable host name verification against CA certificate,\n // notice: in general this is insecure and should be avoided in production,\n // (this type of configuration is useful for development purposes)\n boolean noHostVerification = false;\n LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(\n sslContext,\n noHostVerification ? NoopHostnameVerifier.INSTANCE : new DefaultHostnameVerifier()\n );\n Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()\n .register(\"http\", plainsf)\n .register(\"https\", sslsf)\n .build();\n connectionMgr = new PoolingHttpClientConnectionManager(r, null, null,\n null, connectionPoolTimeToLive, TimeUnit.SECONDS);\n\n connectionMgr.setMaxTotal(maxConnectionsTotal);\n connectionMgr.setDefaultMaxPerRoute(maxConnectionsPerRoute);\n HttpHost localhost = new HttpHost(\"localhost\", 80);\n connectionMgr.setMaxPerRoute(new HttpRoute(localhost), maxConnectionsPerRoute);\n return connectionMgr;\n }"
] | [
"public void addOrder(String columnName, boolean ascending) {\n if (columnName == null) {\n return;\n }\n for (int i = 0; i < columns.size(); i++) {\n if (!columnName.equals(columns.get(i).getData())) {\n continue;\n }\n order.add(new Order(i, ascending ? \"asc\" : \"desc\"));\n }\n }",
"public void addNamespace(final MongoNamespace namespace) {\n this.instanceLock.writeLock().lock();\n try {\n if (this.nsStreamers.containsKey(namespace)) {\n return;\n }\n final NamespaceChangeStreamListener streamer =\n new NamespaceChangeStreamListener(\n namespace,\n instanceConfig.getNamespaceConfig(namespace),\n service,\n networkMonitor,\n authMonitor,\n getLockForNamespace(namespace));\n this.nsStreamers.put(namespace, streamer);\n } finally {\n this.instanceLock.writeLock().unlock();\n }\n }",
"public static void addOverrideToPath() throws Exception {\n Client client = new Client(\"ProfileName\", false);\n\n // Use the fully qualified name for a plugin override.\n client.addMethodToResponseOverride(\"Test Path\", \"com.groupon.odo.sample.Common.delay\");\n\n // The third argument is the ordinal - the nth instance of this override added to this path\n // The final arguments count and type are determined by the override. \"delay\" used in this sample\n // has a single int argument - # of milliseconds delay to simulate\n client.setMethodArguments(\"Test Path\", \"com.groupon.odo.sample.Common.delay\", 1, \"100\");\n }",
"public void setValue(T value)\n {\n try\n {\n lock.writeLock().lock();\n this.value = value;\n }\n finally\n {\n lock.writeLock().unlock();\n }\n }",
"protected boolean setChannel(final Channel newChannel) {\n if(newChannel == null) {\n return false;\n }\n synchronized (lock) {\n if(state != State.OPEN || channel != null) {\n return false;\n }\n this.channel = newChannel;\n this.channel.addCloseHandler(new CloseHandler<Channel>() {\n @Override\n public void handleClose(final Channel closed, final IOException exception) {\n synchronized (lock) {\n if(FutureManagementChannel.this.channel == closed) {\n FutureManagementChannel.this.channel = null;\n }\n lock.notifyAll();\n }\n }\n });\n lock.notifyAll();\n return true;\n }\n }",
"public final void warn(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.WARN, pObject, null);\r\n\t}",
"public static int getNavigationBarHeight(Context context) {\n Resources resources = context.getResources();\n int id = resources.getIdentifier(context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ? \"navigation_bar_height\" : \"navigation_bar_height_landscape\", \"dimen\", \"android\");\n if (id > 0) {\n return resources.getDimensionPixelSize(id);\n }\n return 0;\n }",
"public Snackbar actionLabel(CharSequence actionButtonLabel) {\n mActionLabel = actionButtonLabel;\n if (snackbarAction != null) {\n snackbarAction.setText(mActionLabel);\n }\n return this;\n }",
"public static void acceptsJson(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_J, OPT_JSON),\n \"fetch key/entry by key value of json type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }"
] |
An internal method, public only so that GVRContext can make cross-package
calls.
A synchronous (blocking) wrapper around
{@link android.graphics.BitmapFactory#decodeStream(InputStream)
BitmapFactory.decodeStream} that uses an
{@link android.graphics.BitmapFactory.Options} <code>inTempStorage</code>
decode buffer. On low memory, returns half (quarter, eighth, ...) size
images.
<p>
If {@code stream} is a {@link FileInputStream} and is at offset 0 (zero),
uses
{@link android.graphics.BitmapFactory#decodeFileDescriptor(FileDescriptor)
BitmapFactory.decodeFileDescriptor()} instead of
{@link android.graphics.BitmapFactory#decodeStream(InputStream)
BitmapFactory.decodeStream()}.
@param stream
Bitmap stream
@param closeStream
If {@code true}, closes {@code stream}
@return Bitmap, or null if cannot be decoded into a bitmap | [
"public static Bitmap decodeStream(InputStream stream, boolean closeStream) {\n return AsyncBitmapTexture.decodeStream(stream,\n AsyncBitmapTexture.glMaxTextureSize,\n AsyncBitmapTexture.glMaxTextureSize, true, null, closeStream);\n }"
] | [
"public static String getVcsUrl(Map<String, String> env) {\n String url = env.get(\"SVN_URL\");\n if (StringUtils.isBlank(url)) {\n url = publicGitUrl(env.get(\"GIT_URL\"));\n }\n if (StringUtils.isBlank(url)) {\n url = env.get(\"P4PORT\");\n }\n return url;\n }",
"public Object extractJavaFieldValue(Object object) throws SQLException {\n\n\t\tObject val = extractRawJavaFieldValue(object);\n\n\t\t// if this is a foreign object then we want its reference field\n\t\tif (foreignRefField != null && val != null) {\n\t\t\tval = foreignRefField.extractRawJavaFieldValue(val);\n\t\t}\n\n\t\treturn val;\n\t}",
"public static String encodeUrlIso(String stringToEncode) {\n try {\n return URLEncoder.encode(stringToEncode, \"ISO-8859-1\");\n } catch (UnsupportedEncodingException e1) {\n throw new RuntimeException(e1);\n }\n }",
"public void writeNameValuePair(String name, Date value) throws IOException\n {\n internalWriteNameValuePair(name, m_format.format(value));\n }",
"public static String digestToFileName(String digest) {\n if (StringUtils.startsWith(digest, \"sha1\")) {\n return \"manifest.json\";\n }\n return getShaVersion(digest) + \"__\" + getShaValue(digest);\n }",
"public static Object formatL(final String template, final Object... args) {\n return new Object() {\n @Override\n public String toString() {\n return format(template, args);\n }\n };\n }",
"private static File getUserDirectory(final String prefix, final String suffix, final File parent) {\n final String dirname = formatDirName(prefix, suffix);\n return new File(parent, dirname);\n }",
"@Override\n protected boolean changeDirection(int currentIndex, int centerIndex, boolean inBounds) {\n boolean changed = false;\n if (getGravityInternal() == Gravity.CENTER &&\n currentIndex <= centerIndex &&\n currentIndex == 0 || !inBounds) {\n\n changed = true;\n }\n return changed;\n }",
"public boolean hasRequiredClientProps() {\n boolean valid = true;\n valid &= verifyStringPropSet(CONNECTION_APPLICATION_NAME_PROP, CLIENT_APPLICATION_NAME_PROP);\n valid &= verifyStringPropSet(ACCUMULO_USER_PROP, CLIENT_ACCUMULO_USER_PROP);\n valid &= verifyStringPropSet(ACCUMULO_PASSWORD_PROP, CLIENT_ACCUMULO_PASSWORD_PROP);\n valid &= verifyStringPropSet(ACCUMULO_INSTANCE_PROP, CLIENT_ACCUMULO_INSTANCE_PROP);\n return valid;\n }"
] |
Returns the context menu for the table item.
@param itemId the table item.
@return the context menu for the given item. | [
"public CmsContextMenu getContextMenuForItem(Object itemId) {\n\n CmsContextMenu result = null;\n try {\n final Item item = m_container.getItem(itemId);\n Property<?> keyProp = item.getItemProperty(TableProperty.KEY);\n String key = (String)keyProp.getValue();\n if ((null != key) && !key.isEmpty()) {\n loadAllRemainingLocalizations();\n final Map<Locale, String> localesWithEntries = new HashMap<Locale, String>();\n for (Locale l : m_localizations.keySet()) {\n if (l != m_locale) {\n String value = m_localizations.get(l).getProperty(key);\n if ((null != value) && !value.isEmpty()) {\n localesWithEntries.put(l, value);\n }\n }\n }\n if (!localesWithEntries.isEmpty()) {\n result = new CmsContextMenu();\n ContextMenuItem mainItem = result.addItem(\n Messages.get().getBundle(UI.getCurrent().getLocale()).key(\n Messages.GUI_BUNDLE_EDITOR_CONTEXT_COPY_LOCALE_0));\n for (final Locale l : localesWithEntries.keySet()) {\n\n ContextMenuItem menuItem = mainItem.addItem(l.getDisplayName(UI.getCurrent().getLocale()));\n menuItem.addItemClickListener(new ContextMenuItemClickListener() {\n\n public void contextMenuItemClicked(ContextMenuItemClickEvent event) {\n\n item.getItemProperty(TableProperty.TRANSLATION).setValue(localesWithEntries.get(l));\n\n }\n });\n }\n }\n }\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n //TODO: Improve\n }\n return result;\n }"
] | [
"@Override\n public DMatrixRMaj getU(DMatrixRMaj U , boolean transpose , boolean compact ) {\n U = handleU(U, transpose, compact,m,n,min);\n CommonOps_DDRM.setIdentity(U);\n\n for( int i = 0; i < m; i++ ) u[i] = 0;\n\n for( int j = min-1; j >= 0; j-- ) {\n u[j] = 1;\n for( int i = j+1; i < m; i++ ) {\n u[i] = UBV.get(i,j);\n }\n if( transpose )\n QrHelperFunctions_DDRM.rank1UpdateMultL(U, u, gammasU[j], j, j, m);\n else\n QrHelperFunctions_DDRM.rank1UpdateMultR(U, u, gammasU[j], j, j, m, this.b);\n }\n\n return U;\n }",
"public Stats getCollectionStats(String collectionId, Date date) throws FlickrException {\n return getStats(METHOD_GET_COLLECTION_STATS, \"collection_id\", collectionId, date);\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 }",
"public static base_response Import(nitro_service client, sslfipskey resource) throws Exception {\n\t\tsslfipskey Importresource = new sslfipskey();\n\t\tImportresource.fipskeyname = resource.fipskeyname;\n\t\tImportresource.key = resource.key;\n\t\tImportresource.inform = resource.inform;\n\t\tImportresource.wrapkeyname = resource.wrapkeyname;\n\t\tImportresource.iv = resource.iv;\n\t\tImportresource.exponent = resource.exponent;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}",
"public final Jar setAttribute(String section, String name, String value) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Manifest cannot be modified after entries are added.\");\n Attributes attr = getManifest().getAttributes(section);\n if (attr == null) {\n attr = new Attributes();\n getManifest().getEntries().put(section, attr);\n }\n attr.putValue(name, value);\n return this;\n }",
"static int excessArgumentsMatchesVargsParameter(Parameter[] params, ClassNode[] args) {\n // we already know parameter length is bigger zero and last is a vargs\n // the excess arguments are all put in an array for the vargs call\n // so check against the component type\n int dist = 0;\n ClassNode vargsBase = params[params.length - 1].getType().getComponentType();\n for (int i = params.length; i < args.length; i++) {\n if (!isAssignableTo(args[i],vargsBase)) return -1;\n else if (!args[i].equals(vargsBase)) dist+=getDistance(args[i], vargsBase);\n }\n return dist;\n }",
"private void clearDeck(TrackMetadataUpdate update) {\n if (hotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) {\n deliverBeatGridUpdate(update.player, null);\n }\n }",
"protected int getCenterChild(CacheDataSet cache) {\n if (cache.count() == 0)\n return -1;\n\n int id = cache.getId(0);\n switch (getGravityInternal()) {\n case TOP:\n case LEFT:\n case FRONT:\n case FILL:\n break;\n case BOTTOM:\n case RIGHT:\n case BACK:\n id = cache.getId(cache.count() - 1);\n break;\n case CENTER:\n int i = cache.count() / 2;\n while (i < cache.count() && i >= 0) {\n id = cache.getId(i);\n if (cache.getStartDataOffset(id) <= 0) {\n if (cache.getEndDataOffset(id) >= 0) {\n break;\n } else {\n i++;\n }\n } else {\n i--;\n }\n }\n break;\n default:\n break;\n }\n\n Log.d(LAYOUT, TAG, \"getCenterChild = %d \", id);\n return id;\n }",
"public boolean fling(float velocityX, float velocityY, float velocityZ) {\n boolean scrolled = true;\n float viewportX = mScrollable.getViewPortWidth();\n if (Float.isNaN(viewportX)) {\n viewportX = 0;\n }\n float maxX = Math.min(MAX_SCROLLING_DISTANCE,\n viewportX * MAX_VIEWPORT_LENGTHS);\n\n float viewportY = mScrollable.getViewPortHeight();\n if (Float.isNaN(viewportY)) {\n viewportY = 0;\n }\n float maxY = Math.min(MAX_SCROLLING_DISTANCE,\n viewportY * MAX_VIEWPORT_LENGTHS);\n\n float xOffset = (maxX * velocityX)/VELOCITY_MAX;\n float yOffset = (maxY * velocityY)/VELOCITY_MAX;\n\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"fling() velocity = [%f, %f, %f] offset = [%f, %f]\",\n velocityX, velocityY, velocityZ,\n xOffset, yOffset);\n\n if (equal(xOffset, 0)) {\n xOffset = Float.NaN;\n }\n\n if (equal(yOffset, 0)) {\n yOffset = Float.NaN;\n }\n\n// TODO: Think about Z-scrolling\n mScrollable.scrollByOffset(xOffset, yOffset, Float.NaN, mInternalScrollListener);\n\n return scrolled;\n }"
] |
Get components list for current instance
@return components | [
"public static Collection<Component> getComponentsList() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.components.values();\n }"
] | [
"public static final double round(double value, double precision)\n {\n precision = Math.pow(10, precision);\n return Math.round(value * precision) / precision;\n }",
"public static boolean isArray(Type type) {\n return (type instanceof GenericArrayType) || (type instanceof Class<?> && ((Class<?>) type).isArray());\n }",
"public Stamp allocateTimestamp() {\n\n synchronized (this) {\n Preconditions.checkState(!closed, \"tracker closed \");\n\n if (node == null) {\n Preconditions.checkState(allocationsInProgress == 0,\n \"expected allocationsInProgress == 0 when node == null\");\n Preconditions.checkState(!updatingZk, \"unexpected concurrent ZK update\");\n\n createZkNode(getTimestamp().getTxTimestamp());\n }\n\n allocationsInProgress++;\n }\n\n try {\n Stamp ts = getTimestamp();\n\n synchronized (this) {\n timestamps.add(ts.getTxTimestamp());\n }\n\n return ts;\n } catch (RuntimeException re) {\n synchronized (this) {\n allocationsInProgress--;\n }\n throw re;\n }\n }",
"public String convert(BufferedImage image, boolean favicon) {\n // Reset statistics before anything\n statsArray = new int[12];\n // Begin the timer\n dStart = System.nanoTime();\n // Scale the image\n image = scale(image, favicon);\n // The +1 is for the newline characters\n StringBuilder sb = new StringBuilder((image.getWidth() + 1) * image.getHeight());\n\n for (int y = 0; y < image.getHeight(); y++) {\n // At the end of each line, add a newline character\n if (sb.length() != 0) sb.append(\"\\n\");\n for (int x = 0; x < image.getWidth(); x++) {\n //\n Color pixelColor = new Color(image.getRGB(x, y), true);\n int alpha = pixelColor.getAlpha();\n boolean isTransient = alpha < 0.1;\n double gValue = isTransient ? 250 : ((double) pixelColor.getRed() * 0.2989 + (double) pixelColor.getBlue() * 0.5870 + (double) pixelColor.getGreen() * 0.1140) / ((double)alpha / (double)250);\n final char s = gValue < 130 ? darkGrayScaleMap(gValue) : lightGrayScaleMap(gValue);\n sb.append(s);\n }\n }\n imgArray = sb.toString().toCharArray();\n dEnd = System.nanoTime();\n return sb.toString();\n }",
"SimpleJsonEncoder appendToJSONUnquoted(final String key, final Object value) {\n if (closed) {\n throw new IllegalStateException(\"Encoder already closed\");\n }\n if (value != null) {\n appendKey(key);\n sb.append(value);\n }\n return this;\n }",
"public static void unregisterMbean(MBeanServer server, ObjectName name) {\n try {\n server.unregisterMBean(name);\n } catch(Exception e) {\n logger.error(\"Error unregistering mbean\", e);\n }\n }",
"protected CmsAccessControlEntry getImportAccessControlEntry(\n CmsResource res,\n String id,\n String allowed,\n String denied,\n String flags) {\n\n return new CmsAccessControlEntry(\n res.getResourceId(),\n new CmsUUID(id),\n Integer.parseInt(allowed),\n Integer.parseInt(denied),\n Integer.parseInt(flags));\n }",
"private boolean checkDeploymentDir(File directory) {\n if (!directory.exists()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.directoryIsNonexistent(deploymentDir.getAbsolutePath());\n }\n }\n else if (!directory.isDirectory()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.isNotADirectory(deploymentDir.getAbsolutePath());\n }\n }\n else if (!directory.canRead()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.directoryIsNotReadable(deploymentDir.getAbsolutePath());\n }\n }\n else if (!directory.canWrite()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.directoryIsNotWritable(deploymentDir.getAbsolutePath());\n }\n } else {\n deploymentDirAccessible = true;\n }\n\n return deploymentDirAccessible;\n }",
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> addClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @RequestParam(required = false) String friendlyName) throws Exception {\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n // make sure client with this name does not already exist\n if (null != clientService.findClientFromFriendlyName(profileId, friendlyName)) {\n \tthrow new Exception(\"Cannot add client. Friendly name already in use.\");\n }\n \n Client client = clientService.add(profileId);\n\n // set friendly name if it was specified\n if (friendlyName != null) {\n clientService.setFriendlyName(profileId, client.getUUID(), friendlyName);\n client.setFriendlyName(friendlyName);\n }\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"client\", client);\n return valueHash;\n }"
] |
Splits up value into multiple versioned values
@param value
@return
@throws IOException | [
"private List<Versioned<byte[]>> disassembleValues(byte[] values) throws IOException {\n\n if(values == null)\n return new ArrayList<Versioned<byte[]>>(0);\n\n List<Versioned<byte[]>> returnList = new ArrayList<Versioned<byte[]>>();\n ByteArrayInputStream stream = new ByteArrayInputStream(values);\n DataInputStream dataStream = new DataInputStream(stream);\n\n while(dataStream.available() > 0) {\n byte[] object = new byte[dataStream.readInt()];\n dataStream.read(object);\n\n byte[] clockBytes = new byte[dataStream.readInt()];\n dataStream.read(clockBytes);\n VectorClock clock = new VectorClock(clockBytes);\n\n returnList.add(new Versioned<byte[]>(object, clock));\n }\n\n return returnList;\n }"
] | [
"private boolean includeDocument(ItemDocument itemDocument) {\n\t\tfor (StatementGroup sg : itemDocument.getStatementGroups()) {\n\t\t\t// \"P19\" is \"place of birth\" on Wikidata\n\t\t\tif (!\"P19\".equals(sg.getProperty().getId())) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tif (s.getMainSnak() instanceof ValueSnak) {\n\t\t\t\t\tValue v = s.getValue();\n\t\t\t\t\t// \"Q1731\" is \"Dresden\" on Wikidata\n\t\t\t\t\tif (v instanceof ItemIdValue\n\t\t\t\t\t\t\t&& \"Q1731\".equals(((ItemIdValue) v).getId())) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public Archetype parse(String adl) {\n try {\n return parse(new StringReader(adl));\n } catch (IOException e) {\n // StringReader should never throw an IOException\n throw new AssertionError(e);\n }\n }",
"@Nullable\n public ByteIterable get(@NotNull final Transaction txn, @NotNull final ByteIterable first) {\n return this.first.get(txn, first);\n }",
"public ItemRequest<Task> update(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"PUT\");\n }",
"public RuleEnvelope getRule(String ruleId) throws ApiException {\n ApiResponse<RuleEnvelope> resp = getRuleWithHttpInfo(ruleId);\n return resp.getData();\n }",
"@Override\n public boolean isTempoMaster() {\n DeviceUpdate master = VirtualCdj.getInstance().getTempoMaster();\n return (master != null) && master.getAddress().equals(address);\n }",
"public static authenticationvserver_authenticationlocalpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_authenticationlocalpolicy_binding obj = new authenticationvserver_authenticationlocalpolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_authenticationlocalpolicy_binding response[] = (authenticationvserver_authenticationlocalpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"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 final Integer getInteger(Number value)\n {\n Integer result = null;\n if (value != null)\n {\n if (value instanceof Integer)\n {\n result = (Integer) value;\n }\n else\n {\n result = Integer.valueOf((int) Math.round(value.doubleValue()));\n }\n }\n return (result);\n }"
] |
Is invoked on the leaf deletion only.
@param left left page.
@param right right page.
@return true if the left page ought to be merged with the right one. | [
"public boolean needMerge(@NotNull final BasePage left, @NotNull final BasePage right) {\n final int leftSize = left.getSize();\n final int rightSize = right.getSize();\n return leftSize == 0 || rightSize == 0 ||\n leftSize + rightSize <= (((isDupTree(left) ? getDupPageMaxSize() : getPageMaxSize()) * 7) >> 3);\n }"
] | [
"public synchronized static SQLiteDatabase getConnection(Context context) {\n\t\tif (database == null) {\n\t\t\t// Construct the single helper and open the unique(!) db connection for the app\n\t\t\tdatabase = new CupboardDbHelper(context.getApplicationContext()).getWritableDatabase();\n\t\t}\n\t\treturn database;\n\t}",
"private void writeAssignments()\n {\n Allocations allocations = m_factory.createAllocations();\n m_plannerProject.setAllocations(allocations);\n\n List<Allocation> allocationList = allocations.getAllocation();\n for (ResourceAssignment mpxjAssignment : m_projectFile.getResourceAssignments())\n {\n Allocation plannerAllocation = m_factory.createAllocation();\n allocationList.add(plannerAllocation);\n\n plannerAllocation.setTaskId(getIntegerString(mpxjAssignment.getTask().getUniqueID()));\n plannerAllocation.setResourceId(getIntegerString(mpxjAssignment.getResourceUniqueID()));\n plannerAllocation.setUnits(getIntegerString(mpxjAssignment.getUnits()));\n\n m_eventManager.fireAssignmentWrittenEvent(mpxjAssignment);\n }\n }",
"public ParallelTaskBuilder setResponseContext(\n Map<String, Object> responseContext) {\n if (responseContext != null)\n this.responseContext = responseContext;\n else\n logger.error(\"context cannot be null. skip set.\");\n return this;\n }",
"private void countGender(EntityIdValue gender, SiteRecord siteRecord) {\n\t\tInteger curValue = siteRecord.genderCounts.get(gender);\n\t\tif (curValue == null) {\n\t\t\tsiteRecord.genderCounts.put(gender, 1);\n\t\t} else {\n\t\t\tsiteRecord.genderCounts.put(gender, curValue + 1);\n\t\t}\n\t}",
"private void checkProcedures(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n ProcedureDef procDef;\r\n String type;\r\n String name;\r\n String fieldName;\r\n String argName;\r\n \r\n for (Iterator it = classDef.getProcedures(); it.hasNext();)\r\n {\r\n procDef = (ProcedureDef)it.next();\r\n type = procDef.getName();\r\n name = procDef.getProperty(PropertyHelper.OJB_PROPERTY_NAME);\r\n if ((name == null) || (name.length() == 0))\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-procedure in class \"+classDef.getName()+\" doesn't have a name\");\r\n }\r\n fieldName = procDef.getProperty(PropertyHelper.OJB_PROPERTY_RETURN_FIELD_REF);\r\n if ((fieldName != null) && (fieldName.length() > 0))\r\n {\r\n if (classDef.getField(fieldName) == null)\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-procedure \"+name+\" in class \"+classDef.getName()+\" references an unknown or non-persistent return field \"+fieldName);\r\n }\r\n }\r\n for (CommaListIterator argIt = new CommaListIterator(procDef.getProperty(PropertyHelper.OJB_PROPERTY_ARGUMENTS)); argIt.hasNext();)\r\n {\r\n argName = argIt.getNext();\r\n if (classDef.getProcedureArgument(argName) == null)\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-procedure \"+name+\" in class \"+classDef.getName()+\" references an unknown argument \"+argName);\r\n }\r\n }\r\n }\r\n\r\n ProcedureArgumentDef argDef;\r\n\r\n for (Iterator it = classDef.getProcedureArguments(); it.hasNext();)\r\n {\r\n argDef = (ProcedureArgumentDef)it.next();\r\n type = argDef.getProperty(PropertyHelper.OJB_PROPERTY_TYPE);\r\n if (\"runtime\".equals(type))\r\n {\r\n fieldName = argDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELD_REF);\r\n if ((fieldName != null) && (fieldName.length() > 0))\r\n {\r\n if (classDef.getField(fieldName) == null)\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-argument \"+argDef.getName()+\" in class \"+classDef.getName()+\" references an unknown or non-persistent return field \"+fieldName);\r\n }\r\n }\r\n }\r\n }\r\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 base_response sync(nitro_service client, gslbconfig resource) throws Exception {\n\t\tgslbconfig syncresource = new gslbconfig();\n\t\tsyncresource.preview = resource.preview;\n\t\tsyncresource.debug = resource.debug;\n\t\tsyncresource.forcesync = resource.forcesync;\n\t\tsyncresource.nowarn = resource.nowarn;\n\t\tsyncresource.saveconfig = resource.saveconfig;\n\t\tsyncresource.command = resource.command;\n\t\treturn syncresource.perform_operation(client,\"sync\");\n\t}",
"public static boolean uniform(Color color, Pixel[] pixels) {\n return Arrays.stream(pixels).allMatch(p -> p.toInt() == color.toRGB().toInt());\n }",
"public double distanceFrom(LatLong end) {\n\n double dLat = (end.getLatitude() - getLatitude()) * Math.PI / 180;\n double dLon = (end.getLongitude() - getLongitude()) * Math.PI / 180;\n\n double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)\n + Math.cos(getLatitude() * Math.PI / 180)\n * Math.cos(end.getLatitude() * Math.PI / 180)\n * Math.sin(dLon / 2) * Math.sin(dLon / 2);\n\n double c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n double d = EarthRadiusMeters * c;\n return d;\n }"
] |
Determines if the version should be incremented based on the module resources' modification dates.
@param cms the CMS context
@return true if the version number should be incremented
@throws CmsException if something goes wrong | [
"public boolean shouldIncrementVersionBasedOnResources(CmsObject cms) throws CmsException {\n\n if (m_checkpointTime == 0) {\n return true;\n }\n\n // adjust the site root, if necessary\n CmsObject cmsClone = adjustSiteRootIfNecessary(cms, this);\n\n // calculate the module resources\n List<CmsResource> moduleResources = calculateModuleResources(cmsClone, this);\n\n for (CmsResource resource : moduleResources) {\n try {\n List<CmsResource> resourcesToCheck = Lists.newArrayList();\n resourcesToCheck.add(resource);\n if (resource.isFolder()) {\n resourcesToCheck.addAll(cms.readResources(resource, CmsResourceFilter.IGNORE_EXPIRATION, true));\n }\n for (CmsResource resourceToCheck : resourcesToCheck) {\n if (resourceToCheck.getDateLastModified() > m_checkpointTime) {\n return true;\n }\n }\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n continue;\n }\n }\n return false;\n }"
] | [
"private FieldType getFieldType(byte[] data, int offset)\n {\n int fieldIndex = MPPUtility.getInt(data, offset);\n return FieldTypeHelper.mapTextFields(FieldTypeHelper.getInstance14(fieldIndex));\n }",
"public final void info(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.INFO, pObject, null);\r\n\t}",
"final void waitForSizeQueue(final int queueSize) {\n synchronized (this.queue) {\n while (this.queue.size() > queueSize) {\n try {\n this.queue.wait(250L);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n try {\n Thread.sleep(500L);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n this.queue.notifyAll();\n }\n }",
"public void setHostName(String hostName) {\n if (hostName == null || hostName.contains(\":\")) {\n return;\n }\n ODO_HOST = hostName;\n BASE_URL = \"http://\" + ODO_HOST + \":\" + API_PORT + \"/\" + API_BASE + \"/\";\n }",
"private void set(FieldType field, boolean value)\n {\n set(field, (value ? Boolean.TRUE : Boolean.FALSE));\n }",
"private ReferenceDescriptorDef cloneReference(ReferenceDescriptorDef refDef, String prefix)\r\n {\r\n ReferenceDescriptorDef copyRefDef = new ReferenceDescriptorDef(refDef, prefix);\r\n\r\n copyRefDef.setOwner(this);\r\n // we remove properties that are only relevant to the class the features are declared in\r\n copyRefDef.setProperty(PropertyHelper.OJB_PROPERTY_IGNORE, null);\r\n \r\n Properties mod = getModification(copyRefDef.getName());\r\n\r\n if (mod != null)\r\n {\r\n if (!PropertyHelper.toBoolean(mod.getProperty(PropertyHelper.OJB_PROPERTY_IGNORE), false) &&\r\n hasFeature(copyRefDef.getName()))\r\n {\r\n LogHelper.warn(true,\r\n ClassDescriptorDef.class,\r\n \"process\",\r\n \"Class \"+getName()+\" has a feature that has the same name as its included reference \"+\r\n copyRefDef.getName()+\" from class \"+refDef.getOwner().getName()); \r\n }\r\n copyRefDef.applyModifications(mod);\r\n }\r\n return copyRefDef;\r\n }",
"protected Object transformEntity(Entity entity) {\n\t\tPropertyColumn propertyColumn = (PropertyColumn) entity;\n\t\tJRDesignField field = new JRDesignField();\n\t\tColumnProperty columnProperty = propertyColumn.getColumnProperty();\n\t\tfield.setName(columnProperty.getProperty());\n\t\tfield.setValueClassName(columnProperty.getValueClassName());\n\t\t\n\t\tlog.debug(\"Transforming column: \" + propertyColumn.getName() + \", property: \" + columnProperty.getProperty() + \" (\" + columnProperty.getValueClassName() +\") \" );\n\n\t\tfield.setDescription(propertyColumn.getFieldDescription()); //hack for XML data source\n\t\tfor (String key : columnProperty.getFieldProperties().keySet()) {\n\t\t\tfield.getPropertiesMap().setProperty(key, columnProperty.getFieldProperties().get(key));\n\t\t}\n\t\treturn field;\n\t}",
"public static boolean zipFolder(File folder, String fileName){\n\t\tboolean success = false;\n\t\tif(!folder.isDirectory()){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif(fileName == null){\n\t\t\tfileName = folder.getAbsolutePath()+ZIP_EXT;\n\t\t}\n\t\t\n\t\tZipArchiveOutputStream zipOutput = null;\n\t\ttry {\n\t\t\tzipOutput = new ZipArchiveOutputStream(new File(fileName));\n\t\t\t\n\t\t\tsuccess = addFolderContentToZip(folder,zipOutput,\"\");\n\n\t\t\tzipOutput.close();\n\t\t\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t\tfinally{\n\t\t\ttry {\n\t\t\t\tif(zipOutput != null){\n\t\t\t\t\tzipOutput.close();\n\t\t\t\t}\n\t\t\t} catch (IOException e) {}\n\t\t}\n\t\treturn success;\n\t}",
"public static <T> List<T> asImmutable(List<? extends T> self) {\n return Collections.unmodifiableList(self);\n }"
] |
Maps the text representation of column data to Java types.
@param table table name
@param column column name
@param data text representation of column data
@param type column data type
@param epochDateFormat true if date is represented as an offset from an epoch
@return Java representation of column data
@throws MPXJException | [
"private Object getColumnValue(String table, String column, String data, int type, boolean epochDateFormat) throws MPXJException\n {\n try\n {\n Object value = null;\n\n switch (type)\n {\n case Types.BIT:\n {\n value = DatatypeConverter.parseBoolean(data);\n break;\n }\n\n case Types.VARCHAR:\n case Types.LONGVARCHAR:\n {\n value = DatatypeConverter.parseString(data);\n break;\n }\n\n case Types.TIME:\n {\n value = DatatypeConverter.parseBasicTime(data);\n break;\n }\n\n case Types.TIMESTAMP:\n {\n if (epochDateFormat)\n {\n value = DatatypeConverter.parseEpochTimestamp(data);\n }\n else\n {\n value = DatatypeConverter.parseBasicTimestamp(data);\n }\n break;\n }\n\n case Types.DOUBLE:\n {\n value = DatatypeConverter.parseDouble(data);\n break;\n }\n\n case Types.INTEGER:\n {\n value = DatatypeConverter.parseInteger(data);\n break;\n }\n\n default:\n {\n throw new IllegalArgumentException(\"Unsupported SQL type: \" + type);\n }\n }\n\n return value;\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to parse \" + table + \".\" + column + \" (data=\" + data + \", type=\" + type + \")\", ex);\n }\n }"
] | [
"public static void main(String[] args) throws Exception {\r\n StringUtils.printErrInvocationString(\"CMMClassifier\", args);\r\n\r\n Properties props = StringUtils.argsToProperties(args);\r\n CMMClassifier cmm = new CMMClassifier<CoreLabel>(props);\r\n String testFile = cmm.flags.testFile;\r\n String textFile = cmm.flags.textFile;\r\n String loadPath = cmm.flags.loadClassifier;\r\n String serializeTo = cmm.flags.serializeTo;\r\n\r\n // cmm.crossValidateTrainAndTest(trainFile);\r\n if (loadPath != null) {\r\n cmm.loadClassifierNoExceptions(loadPath, props);\r\n } else if (cmm.flags.loadJarClassifier != null) {\r\n cmm.loadJarClassifier(cmm.flags.loadJarClassifier, props);\r\n } else if (cmm.flags.trainFile != null) {\r\n if (cmm.flags.biasedTrainFile != null) {\r\n cmm.trainSemiSup();\r\n } else {\r\n cmm.train();\r\n }\r\n } else {\r\n cmm.loadDefaultClassifier();\r\n }\r\n\r\n if (serializeTo != null) {\r\n cmm.serializeClassifier(serializeTo);\r\n }\r\n\r\n if (testFile != null) {\r\n cmm.classifyAndWriteAnswers(testFile, cmm.makeReaderAndWriter());\r\n } else if (cmm.flags.testFiles != null) {\r\n cmm.classifyAndWriteAnswers(cmm.flags.baseTestDir, cmm.flags.testFiles,\r\n cmm.makeReaderAndWriter());\r\n }\r\n\r\n if (textFile != null) {\r\n DocumentReaderAndWriter readerAndWriter =\r\n new PlainTextDocumentReaderAndWriter();\r\n cmm.classifyAndWriteAnswers(textFile, readerAndWriter);\r\n }\r\n }",
"public static final Integer getInteger(String value)\n {\n Integer result;\n\n try\n {\n result = Integer.valueOf(Integer.parseInt(value));\n }\n\n catch (Exception ex)\n {\n result = null;\n }\n\n return (result);\n }",
"public synchronized static void registerImagOnAgents(Launcher launcher, final String imageTag,\n final String host, final String targetRepo, final ArrayListMultimap<String, String> artifactsProps,\n final int buildInfoId) throws IOException, InterruptedException {\n // Master\n final String imageId = getImageIdFromAgent(launcher, imageTag, host);\n registerImage(imageId, imageTag, targetRepo, artifactsProps, buildInfoId);\n\n // Agents\n List<Node> nodes = Jenkins.getInstance().getNodes();\n for (Node node : nodes) {\n if (node == null || node.getChannel() == null) {\n continue;\n }\n try {\n node.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {\n public Boolean call() throws IOException {\n registerImage(imageId, imageTag, targetRepo, artifactsProps, buildInfoId);\n return true;\n }\n });\n } catch (Exception e) {\n launcher.getListener().getLogger().println(\"Could not register docker image \" + imageTag +\n \" on Jenkins node '\" + node.getDisplayName() + \"' due to: \" + e.getMessage() +\n \" This could be because this node is now offline.\"\n );\n }\n }\n }",
"public static Map<String, Automaton> createAutomatonMap(String prefix,\n List<String> valueList, Boolean filter) {\n HashMap<String, Automaton> automatonMap = new HashMap<>();\n if (valueList != null) {\n for (String item : valueList) {\n if (filter) {\n item = item.replaceAll(\"([\\\\\\\"\\\\)\\\\(\\\\<\\\\>\\\\.\\\\@\\\\#\\\\]\\\\[\\\\{\\\\}])\",\n \"\\\\\\\\$1\");\n }\n automatonMap.put(item,\n new RegExp(prefix + MtasToken.DELIMITER + item + \"\\u0000*\")\n .toAutomaton());\n }\n }\n return automatonMap;\n }",
"public void createPdfLayout(Dimension dim)\n {\n if (pdfdocument != null) //processing a PDF document\n {\n try {\n if (createImage)\n img = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_RGB);\n Graphics2D ig = img.createGraphics();\n \n log.info(\"Creating PDF boxes\");\n VisualContext ctx = new VisualContext(null, null);\n \n boxtree = new CSSBoxTree(ig, ctx, dim, baseurl);\n boxtree.setConfig(config);\n boxtree.processDocument(pdfdocument, startPage, endPage);\n viewport = boxtree.getViewport();\n root = boxtree.getDocument().getDocumentElement();\n log.info(\"We have \" + boxtree.getLastId() + \" boxes\");\n viewport.initSubtree();\n \n log.info(\"Layout for \"+dim.width+\"px\");\n viewport.doLayout(dim.width, true, true);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n log.info(\"Updating viewport size\");\n viewport.updateBounds(dim);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n if (createImage && (viewport.getWidth() > dim.width || viewport.getHeight() > dim.height))\n {\n img = new BufferedImage(Math.max(viewport.getWidth(), dim.width),\n Math.max(viewport.getHeight(), dim.height),\n BufferedImage.TYPE_INT_RGB);\n ig = img.createGraphics();\n }\n \n log.info(\"Positioning for \"+img.getWidth()+\"x\"+img.getHeight()+\"px\");\n viewport.absolutePositions();\n \n clearCanvas();\n viewport.draw(new GraphicsRenderer(ig));\n setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));\n revalidate();\n } catch (ParserConfigurationException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n else if (root != null) //processing a DOM tree\n {\n super.createLayout(dim);\n }\n }",
"public NodeT getNext() {\n String nextItemKey = queue.poll();\n if (nextItemKey == null) {\n return null;\n }\n return nodeTable.get(nextItemKey);\n }",
"static ModelNode createOperation(final ModelNode operationToValidate) {\n PathAddress pa = PathAddress.pathAddress(operationToValidate.require(ModelDescriptionConstants.OP_ADDR));\n PathAddress realmPA = null;\n for (int i = pa.size() - 1; i > 0; i--) {\n PathElement pe = pa.getElement(i);\n if (SECURITY_REALM.equals(pe.getKey())) {\n realmPA = pa.subAddress(0, i + 1);\n break;\n }\n }\n assert realmPA != null : \"operationToValidate did not have an address that included a \" + SECURITY_REALM;\n return Util.getEmptyOperation(\"validate-authentication\", realmPA.toModelNode());\n }",
"private File getWorkDir() throws IOException\r\n {\r\n if (_workDir == null)\r\n { \r\n File dummy = File.createTempFile(\"dummy\", \".log\");\r\n String workDir = dummy.getPath().substring(0, dummy.getPath().lastIndexOf(File.separatorChar));\r\n \r\n if ((workDir == null) || (workDir.length() == 0))\r\n {\r\n workDir = \".\";\r\n }\r\n dummy.delete();\r\n _workDir = new File(workDir);\r\n }\r\n return _workDir;\r\n }",
"public static nspbr6_stats[] get(nitro_service service, options option) throws Exception{\n\t\tnspbr6_stats obj = new nspbr6_stats();\n\t\tnspbr6_stats[] response = (nspbr6_stats[])obj.stat_resources(service,option);\n\t\treturn response;\n\t}"
] |
Output method that sends a subscription confirmation for the subscriber to avoid DoS attacks, or false subscription.
@param sr
@return True case the subscription was confirmed, or False otherwise
@throws org.ow2.chameleon.fuchsia.push.base.hub.exception.SubscriptionOriginVerificationException | [
"public Boolean verifySubscriberRequestedSubscription(SubscriptionRequest sr) throws SubscriptionOriginVerificationException {\n\n LOG.info(\"(Hub) -> Subscriber, sending notification to verify the origin of the subscription {}.\", sr.getCallback());\n\n SubscriptionConfirmationRequest sc = new SubscriptionConfirmationRequest(sr.getMode(),\n sr.getTopic(), \"challenge\", \"0\");\n\n URI uri;\n try {\n uri = new URIBuilder(sr.getCallback()).setParameters(sc.toRequestParameters()).build();\n } catch (URISyntaxException e) {\n throw new SubscriptionOriginVerificationException(\"URISyntaxException while sending a confirmation of subscription\", e);\n }\n\n HttpGet httpGet = new HttpGet(uri);\n\n CloseableHttpClient httpclient = HttpClients.createDefault();\n\n CloseableHttpResponse response;\n try {\n response = httpclient.execute(httpGet);\n } catch (IOException e) {\n throw new SubscriptionOriginVerificationException(\"IOException while sending a confirmation of subscription\", e);\n }\n\n LOG.info(\"Subscriber replied with the http code {}.\", response.getStatusLine().getStatusCode());\n\n Integer returnedCode = response.getStatusLine().getStatusCode();\n\n // if code is a success code return true, else false\n return (199 < returnedCode) && (returnedCode < 300);\n }"
] | [
"public boolean hasRequiredClientProps() {\n boolean valid = true;\n valid &= verifyStringPropSet(CONNECTION_APPLICATION_NAME_PROP, CLIENT_APPLICATION_NAME_PROP);\n valid &= verifyStringPropSet(ACCUMULO_USER_PROP, CLIENT_ACCUMULO_USER_PROP);\n valid &= verifyStringPropSet(ACCUMULO_PASSWORD_PROP, CLIENT_ACCUMULO_PASSWORD_PROP);\n valid &= verifyStringPropSet(ACCUMULO_INSTANCE_PROP, CLIENT_ACCUMULO_INSTANCE_PROP);\n return valid;\n }",
"public Boolean invoke(File pomFile, VirtualChannel channel) throws IOException, InterruptedException {\n\n org.jfrog.build.extractor.maven.reader.ModuleName current = new org.jfrog.build.extractor.maven.reader.ModuleName(\n currentModule.groupId, currentModule.artifactId);\n\n Map<org.jfrog.build.extractor.maven.reader.ModuleName, String> modules = Maps.newLinkedHashMap();\n for (Map.Entry<ModuleName, String> entry : versionsByModule.entrySet()) {\n modules.put(new org.jfrog.build.extractor.maven.reader.ModuleName(\n entry.getKey().groupId, entry.getKey().artifactId), entry.getValue());\n }\n\n org.jfrog.build.extractor.maven.transformer.PomTransformer transformer =\n new org.jfrog.build.extractor.maven.transformer.PomTransformer(current, modules, scmUrl,\n failOnSnapshot);\n\n return transformer.transform(pomFile);\n }",
"public ValueContainer[] getKeyValues(ClassDescriptor cld, Object objectOrProxy, boolean convertToSql) throws PersistenceBrokerException\r\n {\r\n IndirectionHandler handler = ProxyHelper.getIndirectionHandler(objectOrProxy);\r\n\r\n if(handler != null)\r\n {\r\n return getKeyValues(cld, handler.getIdentity(), convertToSql); //BRJ: convert Identity\r\n }\r\n else\r\n {\r\n ClassDescriptor realCld = getRealClassDescriptor(cld, objectOrProxy);\r\n return getValuesForObject(realCld.getPkFields(), objectOrProxy, convertToSql);\r\n }\r\n }",
"public static Class<?>[] toClassArray(Collection<Class<?>> collection) {\n\t\tif (collection == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn collection.toArray(new Class<?>[collection.size()]);\n\t}",
"private void executeBatch(int batchId, final RebalanceBatchPlan batchPlan) {\n final Cluster batchCurrentCluster = batchPlan.getCurrentCluster();\n final List<StoreDefinition> batchCurrentStoreDefs = batchPlan.getCurrentStoreDefs();\n final Cluster batchFinalCluster = batchPlan.getFinalCluster();\n final List<StoreDefinition> batchFinalStoreDefs = batchPlan.getFinalStoreDefs();\n\n try {\n final List<RebalanceTaskInfo> rebalanceTaskInfoList = batchPlan.getBatchPlan();\n\n if(rebalanceTaskInfoList.isEmpty()) {\n RebalanceUtils.printBatchLog(batchId, logger, \"Skipping batch \"\n + batchId + \" since it is empty.\");\n // Even though there is no rebalancing work to do, cluster\n // metadata must be updated so that the server is aware of the\n // new cluster xml.\n adminClient.rebalanceOps.rebalanceStateChange(batchCurrentCluster,\n batchFinalCluster,\n batchCurrentStoreDefs,\n batchFinalStoreDefs,\n rebalanceTaskInfoList,\n false,\n true,\n false,\n false,\n true);\n return;\n }\n\n RebalanceUtils.printBatchLog(batchId, logger, \"Starting batch \"\n + batchId + \".\");\n\n // Split the store definitions\n List<StoreDefinition> readOnlyStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs,\n true);\n List<StoreDefinition> readWriteStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs,\n false);\n boolean hasReadOnlyStores = readOnlyStoreDefs != null\n && readOnlyStoreDefs.size() > 0;\n boolean hasReadWriteStores = readWriteStoreDefs != null\n && readWriteStoreDefs.size() > 0;\n\n // STEP 1 - Cluster state change\n boolean finishedReadOnlyPhase = false;\n List<RebalanceTaskInfo> filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList,\n readOnlyStoreDefs);\n\n rebalanceStateChange(batchId,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n\n // STEP 2 - Move RO data\n if(hasReadOnlyStores) {\n RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId);\n executeSubBatch(batchId,\n progressBar,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n }\n\n // STEP 3 - Cluster change state\n finishedReadOnlyPhase = true;\n filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList,\n readWriteStoreDefs);\n\n rebalanceStateChange(batchId,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n\n // STEP 4 - Move RW data\n if(hasReadWriteStores) {\n proxyPause();\n RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId);\n executeSubBatch(batchId,\n progressBar,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n }\n\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"Successfully terminated batch \"\n + batchId + \".\");\n\n } catch(Exception e) {\n RebalanceUtils.printErrorLog(batchId, logger, \"Error in batch \"\n + batchId + \" - \" + e.getMessage(), e);\n throw new VoldemortException(\"Rebalance failed on batch \" + batchId,\n e);\n }\n }",
"public ConverterServerBuilder baseUri(String baseUri) {\n checkNotNull(baseUri);\n this.baseUri = URI.create(baseUri);\n return this;\n }",
"@Deprecated\n public static OptionMap create(final ExpressionResolver resolver, final ModelNode model, final OptionMap defaults) throws OperationFailedException {\n final OptionMap map = OptionMap.builder()\n .addAll(defaults)\n .set(Options.WORKER_READ_THREADS, RemotingSubsystemRootResource.WORKER_READ_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_CORE_THREADS, RemotingSubsystemRootResource.WORKER_TASK_CORE_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_KEEPALIVE, RemotingSubsystemRootResource.WORKER_TASK_KEEPALIVE.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_LIMIT, RemotingSubsystemRootResource.WORKER_TASK_LIMIT.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_MAX_THREADS, RemotingSubsystemRootResource.WORKER_TASK_MAX_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_WRITE_THREADS, RemotingSubsystemRootResource.WORKER_WRITE_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_READ_THREADS, RemotingSubsystemRootResource.WORKER_READ_THREADS.resolveModelAttribute(resolver, model).asInt())\n .getMap();\n return map;\n }",
"public static boolean hasAnnotation(Method method, Class<? extends Annotation> annotation) {\n return !searchForAnnotation(method, annotation).isEmpty();\n }",
"public synchronized void addRange(final float range, final GVRSceneObject sceneObject)\n {\n if (null == sceneObject) {\n throw new IllegalArgumentException(\"sceneObject must be specified!\");\n }\n if (range < 0) {\n throw new IllegalArgumentException(\"range cannot be negative\");\n }\n\n final int size = mRanges.size();\n final float rangePow2 = range*range;\n final Object[] newElement = new Object[] {rangePow2, sceneObject};\n\n for (int i = 0; i < size; ++i) {\n final Object[] el = mRanges.get(i);\n final Float r = (Float)el[0];\n if (r > rangePow2) {\n mRanges.add(i, newElement);\n break;\n }\n }\n\n if (mRanges.size() == size) {\n mRanges.add(newElement);\n }\n\n final GVRSceneObject owner = getOwnerObject();\n if (null != owner) {\n owner.addChildObject(sceneObject);\n }\n }"
] |
This method is called to ensure that after a project file has been
read, the cached unique ID values used to generate new unique IDs
start after the end of the existing set of unique IDs. | [
"public void updateUniqueCounters()\n {\n //\n // Update task unique IDs\n //\n for (Task task : m_parent.getTasks())\n {\n int uniqueID = NumberHelper.getInt(task.getUniqueID());\n if (uniqueID > m_taskUniqueID)\n {\n m_taskUniqueID = uniqueID;\n }\n }\n\n //\n // Update resource unique IDs\n //\n for (Resource resource : m_parent.getResources())\n {\n int uniqueID = NumberHelper.getInt(resource.getUniqueID());\n if (uniqueID > m_resourceUniqueID)\n {\n m_resourceUniqueID = uniqueID;\n }\n }\n\n //\n // Update calendar unique IDs\n //\n for (ProjectCalendar calendar : m_parent.getCalendars())\n {\n int uniqueID = NumberHelper.getInt(calendar.getUniqueID());\n if (uniqueID > m_calendarUniqueID)\n {\n m_calendarUniqueID = uniqueID;\n }\n }\n\n //\n // Update assignment unique IDs\n //\n for (ResourceAssignment assignment : m_parent.getResourceAssignments())\n {\n int uniqueID = NumberHelper.getInt(assignment.getUniqueID());\n if (uniqueID > m_assignmentUniqueID)\n {\n m_assignmentUniqueID = uniqueID;\n }\n }\n }"
] | [
"public void commandContinuationRequest()\r\n throws ProtocolException {\r\n try {\r\n output.write('+');\r\n output.write(' ');\r\n output.write('O');\r\n output.write('K');\r\n output.write('\\r');\r\n output.write('\\n');\r\n output.flush();\r\n } catch (IOException e) {\r\n throw new ProtocolException(\"Unexpected exception in sending command continuation request.\", e);\r\n }\r\n }",
"public static <T> void addAll(Collection<T> collection, Iterable<? extends T> items) {\r\n for (T item : items) {\r\n collection.add(item);\r\n }\r\n }",
"public static String serialize(final Object obj) throws IOException {\n\t\tfinal ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n\t\treturn mapper.writeValueAsString(obj);\n\t\t\n\t}",
"public void setBufferedImage(BufferedImage img) {\n image = img;\n width = img.getWidth();\n height = img.getHeight();\n updateColorArray();\n }",
"public FieldType getField()\n {\n FieldType result = null;\n if (m_index < m_fields.length)\n {\n result = m_fields[m_index++];\n }\n\n return result;\n }",
"@Override\r\n public void putAll(Map<? extends K, ? extends V> in) {\r\n if (fast) {\r\n synchronized (this) {\r\n Map<K, V> temp = cloneMap(map);\r\n temp.putAll(in);\r\n map = temp;\r\n }\r\n } else {\r\n synchronized (map) {\r\n map.putAll(in);\r\n }\r\n }\r\n }",
"public static List<String> getParameterNames(MethodNode node) {\r\n ArrayList<String> result = new ArrayList<String>();\r\n\r\n if (node.getParameters() != null) {\r\n for (Parameter parameter : node.getParameters()) {\r\n result.add(parameter.getName());\r\n }\r\n }\r\n return result;\r\n }",
"public void logError(String message, Object sender) {\n getEventManager().sendEvent(this, IErrorEvents.class, \"onError\", new Object[] { message, sender });\n }",
"private void addTasks(MpxjTreeNode parentNode, ChildTaskContainer parent)\n {\n for (Task task : parent.getChildTasks())\n {\n final Task t = task;\n MpxjTreeNode childNode = new MpxjTreeNode(task, TASK_EXCLUDED_METHODS)\n {\n @Override public String toString()\n {\n return t.getName();\n }\n };\n parentNode.add(childNode);\n addTasks(childNode, task);\n }\n }"
] |
Re-Tag the websocket connection hold by this context with label specified.
This method will remove all previous tags on the websocket connection and then
tag it with the new label.
@param label the label.
@return this websocket conext. | [
"public WebSocketContext reTag(String label) {\n WebSocketConnectionRegistry registry = manager.tagRegistry();\n registry.signOff(connection);\n registry.signIn(label, connection);\n return this;\n }"
] | [
"int getItemViewType(T content) {\n Class prototypeClass = getPrototypeClass(content);\n validatePrototypeClass(prototypeClass);\n return getItemViewType(prototypeClass);\n }",
"public static Properties loadProperties(String[] filesToLoad)\n {\n Properties p = new Properties();\n InputStream fis = null;\n for (String path : filesToLoad)\n {\n try\n {\n fis = Db.class.getClassLoader().getResourceAsStream(path);\n if (fis != null)\n {\n p.load(fis);\n jqmlogger.info(\"A jqm.properties file was found at {}\", path);\n }\n }\n catch (IOException e)\n {\n // We allow no configuration files, but not an unreadable configuration file.\n throw new DatabaseException(\"META-INF/jqm.properties file is invalid\", e);\n }\n finally\n {\n closeQuietly(fis);\n }\n }\n\n // Overload the datasource name from environment variable if any (tests only).\n String dbName = System.getenv(\"DB\");\n if (dbName != null)\n {\n p.put(\"com.enioka.jqm.jdbc.datasource\", \"jdbc/\" + dbName);\n }\n\n // Done\n return p;\n }",
"public static DiscountCurveInterface createDiscountCurveFromMonteCarloLiborModel(String forwardCurveName, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{\n\t\t// Check if the LMM uses a discount curve which is created from a forward curve\n\t\tif(model.getModel().getDiscountCurve()==null || model.getModel().getDiscountCurve().getName().toLowerCase().contains(\"DiscountCurveFromForwardCurve\".toLowerCase())){\n\t\t\treturn new DiscountCurveFromForwardCurve(ForwardCurveInterpolation.createForwardCurveFromMonteCarloLiborModel(forwardCurveName, model, startTime));\n\t\t}\n\t\telse {\n\t\t\t// i.e. forward curve of Libor Model not OIS. In this case return the OIS curve.\n\t\t\t// Only at startTime 0!\n\t\t\treturn (DiscountCurveInterface) model.getModel().getDiscountCurve();\n\t\t}\n\n\t}",
"private static QName convertString(String str) {\n if (str != null) {\n return QName.valueOf(str);\n } else {\n return null;\n }\n }",
"public byte[] getThumbnail(ThumbnailFileType fileType, int minWidth, int minHeight, int maxWidth, int maxHeight) {\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(\"min_width\", minWidth);\n builder.appendParam(\"min_height\", minHeight);\n builder.appendParam(\"max_width\", maxWidth);\n builder.appendParam(\"max_height\", maxHeight);\n\n URLTemplate template;\n if (fileType == ThumbnailFileType.PNG) {\n template = GET_THUMBNAIL_PNG_TEMPLATE;\n } else if (fileType == ThumbnailFileType.JPG) {\n template = GET_THUMBNAIL_JPG_TEMPLATE;\n } else {\n throw new BoxAPIException(\"Unsupported thumbnail file type\");\n }\n URL url = template.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxAPIResponse response = request.send();\n\n ByteArrayOutputStream thumbOut = new ByteArrayOutputStream();\n InputStream body = response.getBody();\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = body.read(buffer);\n while (n != -1) {\n thumbOut.write(buffer, 0, n);\n n = body.read(buffer);\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Error reading thumbnail bytes from response body\", e);\n } finally {\n response.disconnect();\n }\n\n return thumbOut.toByteArray();\n }",
"protected void removeWatermark(URLTemplate itemUrl) {\n URL watermarkUrl = itemUrl.build(this.getAPI().getBaseURL(), this.getID());\n URL url = WATERMARK_URL_TEMPLATE.build(watermarkUrl.toString());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }",
"private void recurseAndAddFiles(GraphRewrite event, EvaluationContext context,\n Path tempFolder,\n FileService fileService, ArchiveModel archiveModel,\n FileModel parentFileModel, boolean subArchivesOnly)\n {\n checkCancelled(event);\n\n int numberAdded = 0;\n\n FileFilter filter = TrueFileFilter.TRUE;\n if (archiveModel instanceof IdentifiedArchiveModel)\n {\n filter = new IdentifiedArchiveFileFilter(archiveModel);\n }\n\n File fileReference;\n if (parentFileModel instanceof ArchiveModel)\n fileReference = new File(((ArchiveModel) parentFileModel).getUnzippedDirectory());\n else\n fileReference = parentFileModel.asFile();\n\n WindupJavaConfigurationService windupJavaConfigurationService = new WindupJavaConfigurationService(event.getGraphContext());\n File[] subFiles = fileReference.listFiles();\n if (subFiles == null)\n return;\n\n for (File subFile : subFiles)\n {\n if (!filter.accept(subFile))\n continue;\n\n if (subArchivesOnly && !ZipUtil.endsWithZipExtension(subFile.getAbsolutePath()))\n continue;\n\n FileModel subFileModel = fileService.createByFilePath(parentFileModel, subFile.getAbsolutePath());\n\n // check if this file should be ignored\n if (windupJavaConfigurationService.checkIfIgnored(event, subFileModel))\n continue;\n\n numberAdded++;\n if (numberAdded % 250 == 0)\n event.getGraphContext().commit();\n\n if (subFile.isFile() && ZipUtil.endsWithZipExtension(subFileModel.getFilePath()))\n {\n File newZipFile = subFileModel.asFile();\n ArchiveModel newArchiveModel = GraphService.addTypeToModel(event.getGraphContext(), subFileModel, ArchiveModel.class);\n newArchiveModel.setParentArchive(archiveModel);\n newArchiveModel.setArchiveName(newZipFile.getName());\n\n /*\n * New archive must be reloaded in case the archive should be ignored\n */\n newArchiveModel = GraphService.refresh(event.getGraphContext(), newArchiveModel);\n\n ArchiveModel canonicalArchiveModel = null;\n for (FileModel otherMatches : fileService.findAllByProperty(FileModel.SHA1_HASH, newArchiveModel.getSHA1Hash()))\n {\n if (otherMatches instanceof ArchiveModel && !otherMatches.equals(newArchiveModel) && !(otherMatches instanceof DuplicateArchiveModel))\n {\n canonicalArchiveModel = (ArchiveModel)otherMatches;\n break;\n }\n }\n\n if (canonicalArchiveModel != null)\n {\n // handle as duplicate\n DuplicateArchiveModel duplicateArchive = GraphService.addTypeToModel(event.getGraphContext(), newArchiveModel, DuplicateArchiveModel.class);\n duplicateArchive.setCanonicalArchive(canonicalArchiveModel);\n\n // create dupes for child archives\n unzipToTempDirectory(event, context, tempFolder, newZipFile, duplicateArchive, true);\n } else\n {\n unzipToTempDirectory(event, context, tempFolder, newZipFile, newArchiveModel, false);\n }\n } else if (subFile.isDirectory())\n {\n recurseAndAddFiles(event, context, tempFolder, fileService, archiveModel, subFileModel, false);\n }\n }\n }",
"public double[][] getU() {\n double[][] X = new double[n][n];\n double[][] U = X;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n if (i <= j) {\n U[i][j] = LU[i][j];\n } else {\n U[i][j] = 0.0;\n }\n }\n }\n return X;\n }",
"private Calendar cleanHistCalendar(Calendar cal) {\n cal.set(Calendar.MILLISECOND, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MINUTE, 0);\n cal.set(Calendar.HOUR, 0);\n return cal;\n }"
] |
Use this API to fetch aaapreauthenticationpolicy_aaaglobal_binding resources of given name . | [
"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 synchronized void stop() {\n if (isRunning()) {\n running.set(false);\n DeviceFinder.getInstance().removeDeviceAnnouncementListener(announcementListener);\n dbServerPorts.clear();\n for (Client client : openClients.values()) {\n try {\n client.close();\n } catch (Exception e) {\n logger.warn(\"Problem closing \" + client + \" when stopping\", e);\n }\n }\n openClients.clear();\n useCounts.clear();\n deliverLifecycleAnnouncement(logger, false);\n }\n }",
"public void localRollback()\r\n {\r\n log.info(\"Rollback was called, do rollback on current connection \" + con);\r\n if (!this.isInLocalTransaction)\r\n {\r\n throw new PersistenceBrokerException(\"Not in transaction, cannot abort\");\r\n }\r\n try\r\n {\r\n //truncate the local transaction\r\n this.isInLocalTransaction = false;\r\n if(!broker.isManaged())\r\n {\r\n if (batchCon != null)\r\n {\r\n batchCon.rollback();\r\n }\r\n else if (con != null && !con.isClosed())\r\n {\r\n con.rollback();\r\n }\r\n }\r\n else\r\n {\r\n if(log.isEnabledFor(Logger.INFO)) log.info(\r\n \"Found managed environment setting in PB, will ignore rollback call on connection, this should be done by JTA\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n log.error(\"Rollback on the underlying connection failed\", e);\r\n }\r\n finally\r\n {\r\n try\r\n {\r\n \trestoreAutoCommitState();\r\n\t\t }\r\n catch(OJBRuntimeException ignore)\r\n {\r\n\t\t\t // Ignore or log exception\r\n\t\t }\r\n releaseConnection();\r\n }\r\n }",
"public Record getChild(String key)\n {\n Record result = null;\n if (key != null)\n {\n for (Record record : m_records)\n {\n if (key.equals(record.getField()))\n {\n result = record;\n break;\n }\n }\n }\n return result;\n }",
"public static String read(final File file) throws IOException {\n final StringBuilder sb = new StringBuilder();\n\n try (\n final FileReader fr = new FileReader(file);\n final BufferedReader br = new BufferedReader(fr);\n ) {\n\n String sCurrentLine;\n\n while ((sCurrentLine = br.readLine()) != null) {\n sb.append(sCurrentLine);\n }\n }\n\n return sb.toString();\n }",
"public boolean merge(AbstractTransition another) {\n if (!isCompatible(another)) {\n return false;\n }\n if (another.mId != null) {\n if (mId == null) {\n mId = another.mId;\n } else {\n StringBuilder sb = new StringBuilder(mId.length() + another.mId.length());\n sb.append(mId);\n sb.append(\"_MERGED_\");\n sb.append(another.mId);\n mId = sb.toString();\n }\n }\n mUpdateStateAfterUpdateProgress |= another.mUpdateStateAfterUpdateProgress;\n mSetupList.addAll(another.mSetupList);\n Collections.sort(mSetupList, new Comparator<S>() {\n @Override\n public int compare(S lhs, S rhs) {\n if (lhs instanceof AbstractTransitionBuilder && rhs instanceof AbstractTransitionBuilder) {\n AbstractTransitionBuilder left = (AbstractTransitionBuilder) lhs;\n AbstractTransitionBuilder right = (AbstractTransitionBuilder) rhs;\n float startLeft = left.mReverse ? left.mEnd : left.mStart;\n float startRight = right.mReverse ? right.mEnd : right.mStart;\n return (int) ((startRight - startLeft) * 1000);\n }\n return 0;\n }\n });\n\n return true;\n }",
"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 }",
"private long getTime(Date start, Date end, long target, boolean after)\n {\n long total = 0;\n if (start != null && end != null)\n {\n Date startTime = DateHelper.getCanonicalTime(start);\n Date endTime = DateHelper.getCanonicalTime(end);\n\n Date startDay = DateHelper.getDayStartDate(start);\n Date finishDay = DateHelper.getDayStartDate(end);\n\n //\n // Handle the case where the end of the range is at midnight -\n // this will show up as the start and end days not matching\n //\n if (startDay.getTime() != finishDay.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n int diff = DateHelper.compare(startTime, endTime, target);\n if (diff == 0)\n {\n if (after == true)\n {\n total = (endTime.getTime() - target);\n }\n else\n {\n total = (target - startTime.getTime());\n }\n }\n else\n {\n if ((after == true && diff < 0) || (after == false && diff > 0))\n {\n total = (endTime.getTime() - startTime.getTime());\n }\n }\n }\n return (total);\n }",
"public static String resolveProxyUrl(String relativeUrl, TileMap tileMap, String baseTmsUrl) {\n\t\tTileCode tc = parseTileCode(relativeUrl);\n\t\treturn buildUrl(tc, tileMap, baseTmsUrl);\n\t}",
"private void writeAssignments()\n {\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n Resource resource = assignment.getResource();\n if (resource != null)\n {\n Task task = assignment.getTask();\n if (task != null && task.getUniqueID().intValue() != 0 && !task.getSummary())\n {\n writeAssignment(assignment);\n }\n }\n }\n }"
] |
Sets a property on this Javascript object for which the value is a
Javascript object itself.
@param propertyName The name of the property.
@param propertyValue The value of the property. | [
"protected void setProperty(String propertyName, JavascriptObject propertyValue) {\n jsObject.setMember(propertyName, propertyValue.getJSObject());\n }"
] | [
"public static int getHostSegmentIndex(int networkPrefixLength, int bytesPerSegment, int bitsPerSegment) {\n\t\tif(bytesPerSegment > 1) {\n\t\t\tif(bytesPerSegment == 2) {\n\t\t\t\treturn networkPrefixLength >> 4;\n\t\t\t}\n\t\t\treturn networkPrefixLength / bitsPerSegment;\n\t\t}\n\t\treturn networkPrefixLength >> 3;\n\t}",
"public static String readUntilTag(Reader r) throws IOException {\r\n if (!r.ready()) {\r\n return \"\";\r\n }\r\n StringBuilder b = new StringBuilder();\r\n int c = r.read();\r\n while (c >= 0 && c != '<') {\r\n b.append((char) c);\r\n c = r.read();\r\n }\r\n return b.toString();\r\n }",
"private void readTasks(Project phoenixProject, Storepoint storepoint)\n {\n processLayouts(phoenixProject);\n processActivityCodes(storepoint);\n processActivities(storepoint);\n updateDates();\n }",
"private void writePropertyStatisticsToFile(UsageStatistics usageStatistics,\n\t\t\tString fileName) {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(fileName))) {\n\n\t\t\tout.println(\"Property id,in statements,in qualifiers,in references,total\");\n\n\t\t\tfor (Entry<PropertyIdValue, Integer> entry : usageStatistics.propertyCountsMain\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tint qCount = usageStatistics.propertyCountsQualifier.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tint rCount = usageStatistics.propertyCountsReferences.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tint total = entry.getValue() + qCount + rCount;\n\t\t\t\tout.println(entry.getKey().getId() + \",\" + entry.getValue()\n\t\t\t\t\t\t+ \",\" + qCount + \",\" + rCount + \",\" + total);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"@Override public void setID(Integer val)\n {\n ProjectFile parent = getParentFile();\n Integer previous = getID();\n\n if (previous != null)\n {\n parent.getTasks().unmapID(previous);\n }\n\n parent.getTasks().mapID(val, this);\n\n set(TaskField.ID, val);\n }",
"public Duration getWork(FastTrackField type)\n {\n Double value = (Double) getObject(type);\n return value == null ? null : Duration.getInstance(value.doubleValue(), m_table.getWorkTimeUnit());\n }",
"public static ObjectName createObjectName(String domain, String type) {\n try {\n return new ObjectName(domain + \":type=\" + type);\n } catch(MalformedObjectNameException e) {\n throw new VoldemortException(e);\n }\n }",
"public static base_response update(nitro_service client, route6 resource) throws Exception {\n\t\troute6 updateresource = new route6();\n\t\tupdateresource.network = resource.network;\n\t\tupdateresource.gateway = resource.gateway;\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.weight = resource.weight;\n\t\tupdateresource.distance = resource.distance;\n\t\tupdateresource.cost = resource.cost;\n\t\tupdateresource.advertise = resource.advertise;\n\t\tupdateresource.msr = resource.msr;\n\t\tupdateresource.monitor = resource.monitor;\n\t\tupdateresource.td = resource.td;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public boolean isHomeKeyPresent() {\n final GVRApplication application = mApplication.get();\n if (null != application) {\n final String model = getHmtModel();\n if (null != model && model.contains(\"R323\")) {\n return true;\n }\n }\n return false;\n }"
] |
Use this API to unset the properties of systemuser resources.
Properties that need to be unset are specified in args array. | [
"public static base_responses unset(nitro_service client, String username[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (username != null && username.length > 0) {\n\t\t\tsystemuser unsetresources[] = new systemuser[username.length];\n\t\t\tfor (int i=0;i<username.length;i++){\n\t\t\t\tunsetresources[i] = new systemuser();\n\t\t\t\tunsetresources[i].username = username[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"void handleAddKey() {\n\n String key = m_addKeyInput.getValue();\n if (m_listener.handleAddKey(key)) {\n Notification.show(\n key.isEmpty()\n ? m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_EMPTY_KEY_SUCCESSFULLY_ADDED_0)\n : m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_SUCCESSFULLY_ADDED_1, key));\n } else {\n CmsMessageBundleEditorTypes.showWarning(\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_CAPTION_0),\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_DESCRIPTION_1, key));\n\n }\n m_addKeyInput.focus();\n m_addKeyInput.selectAll();\n }",
"public final void setFindDetails(boolean findDetails) {\n this.findDetails.set(findDetails);\n if (findDetails) {\n primeCache(); // Get details for any tracks that were already loaded on players.\n } else {\n // Inform our listeners, on the proper thread, that the detailed waveforms are no longer available\n final Set<DeckReference> dyingCache = new HashSet<DeckReference>(detailHotCache.keySet());\n detailHotCache.clear();\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (DeckReference deck : dyingCache) {\n deliverWaveformDetailUpdate(deck.player, null);\n }\n }\n });\n }\n }",
"public boolean hasNodeWithId(int nodeId) {\n Node node = nodesById.get(nodeId);\n if(node == null) {\n return false;\n }\n return true;\n }",
"public static final String printTimestamp(Date value)\n {\n return (value == null ? null : TIMESTAMP_FORMAT.get().format(value));\n }",
"public void recordSyncOpTimeNs(SocketDestination dest, long opTimeNs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordSyncOpTimeNs(null, opTimeNs);\n recordSyncOpTimeNs(null, opTimeNs);\n } else {\n this.syncOpTimeRequestCounter.addRequest(opTimeNs);\n }\n }",
"public void setLabel(String label) {\n\n int ix = lstSizes.indexOf(label);\n if (ix != -1) {\n setLabel(ix);\n }\n }",
"public Map<K, List<Versioned<V>>> getAllWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) {\n validateTimeout(requestWrapper.getRoutingTimeoutInMs());\n Map<K, List<Versioned<V>>> items = null;\n for(int attempts = 0;; attempts++) {\n if(attempts >= this.metadataRefreshAttempts)\n throw new VoldemortException(this.metadataRefreshAttempts\n + \" metadata refresh attempts failed.\");\n try {\n String KeysHexString = \"\";\n long startTimeInMs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n Iterable<ByteArray> keys = (Iterable<ByteArray>) requestWrapper.getIterableKeys();\n KeysHexString = getKeysHexString(keys);\n debugLogStart(\"GET_ALL\",\n requestWrapper.getRequestOriginTimeInMs(),\n startTimeInMs,\n KeysHexString);\n }\n items = store.getAll(requestWrapper);\n if(logger.isDebugEnabled()) {\n int vcEntrySize = 0;\n\n for(List<Versioned<V>> item: items.values()) {\n for(Versioned<V> vc: item) {\n vcEntrySize += ((VectorClock) vc.getVersion()).getVersionMap().size();\n }\n }\n\n debugLogEnd(\"GET_ALL\",\n requestWrapper.getRequestOriginTimeInMs(),\n startTimeInMs,\n System.currentTimeMillis(),\n KeysHexString,\n vcEntrySize);\n }\n return items;\n } catch(InvalidMetadataException e) {\n logger.info(\"Received invalid metadata exception during getAll [ \"\n + e.getMessage() + \" ] on store '\" + storeName + \"'. Rebootstrapping\");\n bootStrap();\n }\n }\n }",
"public int getHistoryCount(int profileId, String clientUUID, HashMap<String, String[]> searchFilter) {\n int count = 0;\n Statement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n\n String sqlQuery = \"SELECT COUNT(\" + Constants.GENERIC_ID + \") FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is set or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId + \" \";\n }\n\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \"AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"' \";\n }\n\n sqlQuery += \";\";\n\n logger.info(\"Query: {}\", sqlQuery);\n\n query = sqlConnection.createStatement();\n results = query.executeQuery(sqlQuery);\n if (results.next()) {\n count = results.getInt(1);\n }\n query.close();\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 (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n return count;\n }",
"public String getUnicodeString(Integer type)\n {\n String result = null;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = MPPUtility.getUnicodeString(item, 0);\n }\n\n return (result);\n }"
] |
Creates a unique name, suitable for use with Resque.
@return a unique name for this worker | [
"protected String createName() {\n final StringBuilder buf = new StringBuilder(128);\n try {\n buf.append(InetAddress.getLocalHost().getHostName()).append(COLON)\n .append(ManagementFactory.getRuntimeMXBean().getName().split(\"@\")[0]) // PID\n .append('-').append(this.workerId).append(COLON).append(JAVA_DYNAMIC_QUEUES);\n for (final String queueName : this.queueNames) {\n buf.append(',').append(queueName);\n }\n } catch (UnknownHostException uhe) {\n throw new RuntimeException(uhe);\n }\n return buf.toString();\n }"
] | [
"public void BuildInteractiveObjectFromAnchor(Sensor anchorSensor, String anchorDestination) {\n InteractiveObject interactiveObject = new InteractiveObject();\n interactiveObject.setSensor(anchorSensor, anchorDestination);\n interactiveObjects.add(interactiveObject);\n }",
"public static Interface[] get(nitro_service service) throws Exception{\n\t\tInterface obj = new Interface();\n\t\tInterface[] response = (Interface[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Set<Class> entityClasses() {\n EntityMetaInfoRepo repo = app().entityMetaInfoRepo().forDb(id);\n return null == repo ? C.<Class>set() : repo.entityClasses();\n }",
"private void verifyXopResponse(XopBean xopOriginal, XopBean xopResponse) {\n if (!Arrays.equals(xopResponse.getBytes(), xopOriginal.getBytes())) {\n throw new RuntimeException(\"Received XOP attachment is corrupted\");\n }\n System.out.println();\n System.out.println(\"XOP attachment has been successfully received\");\n }",
"private static void parseChildShapes(ArrayList<Shape> shapes,\n JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"childShapes\")) {\n ArrayList<Shape> childShapes = new ArrayList<Shape>();\n\n JSONArray childShapeObject = modelJSON.getJSONArray(\"childShapes\");\n for (int i = 0; i < childShapeObject.length(); i++) {\n childShapes.add(getShapeWithId(childShapeObject.getJSONObject(i).getString(\"resourceId\"),\n shapes));\n }\n if (childShapes.size() > 0) {\n for (Shape each : childShapes) {\n each.setParent(current);\n }\n current.setChildShapes(childShapes);\n }\n ;\n }\n }",
"public static String getGroupId(final String gavc) {\n final int splitter = gavc.indexOf(':');\n if(splitter == -1){\n return gavc;\n }\n return gavc.substring(0, splitter);\n }",
"public void editCoords(String photoId, String userId, Rectangle bounds) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_COORDS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"user_id\", userId);\r\n parameters.put(\"person_x\", bounds.x);\r\n parameters.put(\"person_y\", bounds.y);\r\n parameters.put(\"person_w\", bounds.width);\r\n parameters.put(\"person_h\", bounds.height);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public static responderhtmlpage get(nitro_service service, String name) throws Exception{\n\t\tresponderhtmlpage obj = new responderhtmlpage();\n\t\tobj.set_name(name);\n\t\tresponderhtmlpage response = (responderhtmlpage) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public void eol() throws ProtocolException {\r\n char next = nextChar();\r\n\r\n // Ignore trailing spaces.\r\n while (next == ' ') {\r\n consume();\r\n next = nextChar();\r\n }\r\n\r\n // handle DOS and unix end-of-lines\r\n if (next == '\\r') {\r\n consume();\r\n next = nextChar();\r\n }\r\n\r\n // Check if we found extra characters.\r\n if (next != '\\n') {\r\n throw new ProtocolException(\"Expected end-of-line, found more character(s): \"+next);\r\n }\r\n dumpLine();\r\n }"
] |
Processes the template for all index columns for the current index descriptor.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException if an error occurs
@doc.tag type="block" | [
"public void forAllIndexDescriptorColumns(String template, Properties attributes) throws XDocletException\r\n {\r\n String fields = _curIndexDescriptorDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELDS);\r\n FieldDescriptorDef fieldDef;\r\n String name;\r\n\r\n for (CommaListIterator it = new CommaListIterator(fields); it.hasNext();)\r\n {\r\n name = it.getNext();\r\n fieldDef = _curClassDef.getField(name);\r\n if (fieldDef == null)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.INDEX_FIELD_MISSING,\r\n new String[]{name, _curIndexDescriptorDef.getName(), _curClassDef.getName()}));\r\n }\r\n _curIndexColumn = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN);\r\n generate(template);\r\n }\r\n _curIndexColumn = null;\r\n }"
] | [
"public static base_responses delete(nitro_service client, String serverip[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (serverip != null && serverip.length > 0) {\n\t\t\tntpserver deleteresources[] = new ntpserver[serverip.length];\n\t\t\tfor (int i=0;i<serverip.length;i++){\n\t\t\t\tdeleteresources[i] = new ntpserver();\n\t\t\t\tdeleteresources[i].serverip = serverip[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"private String getInverseOneToOneProperty(String property, OgmEntityPersister otherSidePersister) {\n\t\tfor ( String candidate : otherSidePersister.getPropertyNames() ) {\n\t\t\tType candidateType = otherSidePersister.getPropertyType( candidate );\n\t\t\tif ( candidateType.isEntityType()\n\t\t\t\t\t&& ( ( (EntityType) candidateType ).isOneToOne()\n\t\t\t\t\t&& isOneToOneMatching( this, property, (OneToOneType) candidateType ) ) ) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"public void forAllReferenceDefinitions(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getReferences(); it.hasNext(); )\r\n {\r\n _curReferenceDef = (ReferenceDescriptorDef)it.next();\r\n // first we check whether it is an inherited anonymous reference\r\n if (_curReferenceDef.isAnonymous() && (_curReferenceDef.getOwner() != _curClassDef))\r\n {\r\n continue;\r\n }\r\n if (!isFeatureIgnored(LEVEL_REFERENCE) &&\r\n !_curReferenceDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n generate(template);\r\n }\r\n }\r\n _curReferenceDef = null;\r\n }",
"public void populateFromAttributes(\n @Nonnull final Template template,\n @Nonnull final Map<String, Attribute> attributes,\n @Nonnull final PObject requestJsonAttributes) {\n if (requestJsonAttributes.has(JSON_REQUEST_HEADERS) &&\n requestJsonAttributes.getObject(JSON_REQUEST_HEADERS).has(JSON_REQUEST_HEADERS) &&\n !attributes.containsKey(JSON_REQUEST_HEADERS)) {\n attributes.put(JSON_REQUEST_HEADERS, new HttpRequestHeadersAttribute());\n }\n for (Map.Entry<String, Attribute> attribute: attributes.entrySet()) {\n try {\n put(attribute.getKey(),\n attribute.getValue().getValue(template, attribute.getKey(), requestJsonAttributes));\n } catch (ObjectMissingException | IllegalArgumentException e) {\n throw e;\n } catch (Throwable e) {\n String templateName = \"unknown\";\n for (Map.Entry<String, Template> entry: template.getConfiguration().getTemplates()\n .entrySet()) {\n if (entry.getValue() == template) {\n templateName = entry.getKey();\n break;\n }\n }\n\n String defaults = \"\";\n\n if (attribute instanceof ReflectiveAttribute<?>) {\n ReflectiveAttribute<?> reflectiveAttribute = (ReflectiveAttribute<?>) attribute;\n defaults = \"\\n\\n The attribute defaults are: \" + reflectiveAttribute.getDefaultValue();\n }\n\n String errorMsg = \"An error occurred when creating a value from the '\" + attribute.getKey() +\n \"' attribute for the '\" +\n templateName + \"' template.\\n\\nThe JSON is: \\n\" + requestJsonAttributes + defaults +\n \"\\n\" +\n e.toString();\n\n throw new AttributeParsingException(errorMsg, e);\n }\n }\n\n if (template.getConfiguration().isThrowErrorOnExtraParameters()) {\n final List<String> extraProperties = new ArrayList<>();\n for (Iterator<String> it = requestJsonAttributes.keys(); it.hasNext(); ) {\n final String attributeName = it.next();\n if (!attributes.containsKey(attributeName)) {\n extraProperties.add(attributeName);\n }\n }\n\n if (!extraProperties.isEmpty()) {\n throw new ExtraPropertyException(\"Extra properties found in the request attributes\",\n extraProperties, attributes.keySet());\n }\n }\n }",
"private static void logVersionWarnings(String label1, String version1, String label2, String version2) {\n\t\tif (version1 == null) {\n\t\t\tif (version2 != null) {\n\t\t\t\twarning(null, \"Unknown version\", \" for {}, version for {} is '{}'\", new Object[] { label1, label2,\n\t\t\t\t\t\tversion2 });\n\t\t\t}\n\t\t} else {\n\t\t\tif (version2 == null) {\n\t\t\t\twarning(null, \"Unknown version\", \" for {}, version for {} is '{}'\", new Object[] { label2, label1,\n\t\t\t\t\t\tversion1 });\n\t\t\t} else if (!version1.equals(version2)) {\n\t\t\t\twarning(null, \"Mismatched versions\", \": {} is '{}', while {} is '{}'\", new Object[] { label1, version1,\n\t\t\t\t\t\tlabel2, version2 });\n\t\t\t}\n\t\t}\n\t}",
"public static ComponentsMultiThread getComponentsMultiThread() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.componentsMultiThread;\n }",
"public void setValueSelected(T value, boolean selected) {\n int idx = getIndex(value);\n if (idx >= 0) {\n setItemSelectedInternal(idx, selected);\n }\n }",
"public ResponseOnSingeRequest genErrorResponse(Exception t) {\n ResponseOnSingeRequest sshResponse = new ResponseOnSingeRequest();\n String displayError = PcErrorMsgUtils.replaceErrorMsg(t.toString());\n\n sshResponse.setStackTrace(PcStringUtils.printStackTrace(t));\n sshResponse.setErrorMessage(displayError);\n sshResponse.setFailObtainResponse(true);\n\n logger.error(\"error in exec SSH. \\nIf exection is JSchException: \"\n + \"Auth cancel and using public key. \"\n + \"\\nMake sure 1. private key full path is right (try sshMeta.getPrivKeyAbsPath()). \"\n + \"\\n2. the user name and key matches \" + t);\n\n return sshResponse;\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 }"
] |
Write a comma to the output stream if required. | [
"private void writeComma() throws IOException\n {\n if (m_firstNameValuePair.peek().booleanValue())\n {\n m_firstNameValuePair.pop();\n m_firstNameValuePair.push(Boolean.FALSE);\n }\n else\n {\n m_writer.write(',');\n }\n }"
] | [
"public Search groupField(String fieldName, boolean isNumber) {\r\n assertNotEmpty(fieldName, \"fieldName\");\r\n if (isNumber) {\r\n databaseHelper.query(\"group_field\", fieldName + \"<number>\");\r\n } else {\r\n databaseHelper.query(\"group_field\", fieldName);\r\n }\r\n return this;\r\n }",
"public void processStencilSet() throws IOException {\n StringBuilder stencilSetFileContents = new StringBuilder();\n\n Scanner scanner = null;\n try {\n scanner = new Scanner(new File(ssInFile),\n \"UTF-8\");\n String currentLine = \"\";\n String prevLine = \"\";\n while (scanner.hasNextLine()) {\n prevLine = currentLine;\n currentLine = scanner.nextLine();\n\n String trimmedPrevLine = prevLine.trim();\n String trimmedCurrentLine = currentLine.trim();\n\n // First time processing - replace view=\"<file>.svg\" with _view_file=\"<file>.svg\" + view=\"<svg_xml>\"\n if (trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN) && trimmedCurrentLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX)) {\n String newLines = processViewPropertySvgReference(currentLine);\n stencilSetFileContents.append(newLines);\n }\n // Second time processing - replace view=\"<svg_xml>\" with refreshed contents of file referenced by previous line\n else if (trimmedPrevLine.matches(VIEW_FILE_PROPERTY_NAME_PATTERN) && trimmedPrevLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX)\n && trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN)) {\n String newLines = processViewFilePropertySvgReference(prevLine,\n currentLine);\n stencilSetFileContents.append(newLines);\n } else {\n stencilSetFileContents.append(currentLine + LINE_SEPARATOR);\n }\n }\n } finally {\n if (scanner != null) {\n scanner.close();\n }\n }\n\n Writer out = null;\n try {\n out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ssOutFile),\n \"UTF-8\"));\n out.write(stencilSetFileContents.toString());\n } catch (FileNotFoundException e) {\n\n } catch (UnsupportedEncodingException e) {\n } catch (IOException e) {\n } finally {\n if (out != null) {\n try {\n out.close();\n } catch (IOException e) {\n }\n }\n }\n\n System.out.println(\"SVG files referenced more than once:\");\n for (Map.Entry<String, Integer> stringIntegerEntry : mapSVGCounts.entrySet()) {\n if (stringIntegerEntry.getValue() > 1) {\n System.out.println(\"\\t\" + stringIntegerEntry.getKey() + \"\\t = \" + stringIntegerEntry.getValue());\n }\n }\n }",
"public void setBaselineFinishText(int baselineNumber, String value)\n {\n set(selectField(TaskFieldLists.BASELINE_FINISHES, baselineNumber), value);\n }",
"public static Session getSession(final ServerSetup setup, Properties mailProps) {\r\n Properties props = setup.configureJavaMailSessionProperties(mailProps, false);\r\n\r\n log.debug(\"Mail session properties are {}\", props);\r\n\r\n return Session.getInstance(props, null);\r\n }",
"private String getRequestBody(ServletRequest request) throws IOException {\n\n final StringBuilder sb = new StringBuilder();\n\n String line = request.getReader().readLine();\n while (null != line) {\n sb.append(line);\n line = request.getReader().readLine();\n }\n\n return sb.toString();\n }",
"public static final BigInteger printWorkUnits(TimeUnit value)\n {\n int result;\n\n if (value == null)\n {\n value = TimeUnit.HOURS;\n }\n\n switch (value)\n {\n case MINUTES:\n {\n result = 1;\n break;\n }\n\n case DAYS:\n {\n result = 3;\n break;\n }\n\n case WEEKS:\n {\n result = 4;\n break;\n }\n\n case MONTHS:\n {\n result = 5;\n break;\n }\n\n case YEARS:\n {\n result = 7;\n break;\n }\n\n default:\n case HOURS:\n {\n result = 2;\n break;\n }\n }\n\n return (BigInteger.valueOf(result));\n }",
"private Integer getKeyPartitionId(byte[] key) {\n Integer keyPartitionId = storeInstance.getNodesPartitionIdForKey(nodeId, key);\n\n Utils.notNull(keyPartitionId);\n return keyPartitionId;\n }",
"public static StitchAppClient getAppClient(\n @Nonnull final String clientAppId\n ) {\n ensureInitialized();\n\n synchronized (Stitch.class) {\n if (!appClients.containsKey(clientAppId)) {\n throw new IllegalStateException(\n String.format(\"client for app '%s' has not yet been initialized\", clientAppId));\n }\n return appClients.get(clientAppId);\n }\n }",
"private List<String> getCommandLines(File file) {\n List<String> lines = new ArrayList<>();\n try (BufferedReader reader = new BufferedReader(new FileReader(file))) {\n String line = reader.readLine();\n while (line != null) {\n lines.add(line);\n line = reader.readLine();\n }\n } catch (Throwable e) {\n throw new IllegalStateException(\"Failed to process file \" + file.getAbsolutePath(), e);\n }\n return lines;\n }"
] |
Prepare our statement for the subclasses.
@param limit
Limit for queries. Can be null if none. | [
"protected MappedPreparedStmt<T, ID> prepareStatement(Long limit, boolean cacheStore) throws SQLException {\n\t\tList<ArgumentHolder> argList = new ArrayList<ArgumentHolder>();\n\t\tString statement = buildStatementString(argList);\n\t\tArgumentHolder[] selectArgs = argList.toArray(new ArgumentHolder[argList.size()]);\n\t\tFieldType[] resultFieldTypes = getResultFieldTypes();\n\t\tFieldType[] argFieldTypes = new FieldType[argList.size()];\n\t\tfor (int selectC = 0; selectC < selectArgs.length; selectC++) {\n\t\t\targFieldTypes[selectC] = selectArgs[selectC].getFieldType();\n\t\t}\n\t\tif (!type.isOkForStatementBuilder()) {\n\t\t\tthrow new IllegalStateException(\"Building a statement from a \" + type + \" statement is not allowed\");\n\t\t}\n\t\treturn new MappedPreparedStmt<T, ID>(dao, tableInfo, statement, argFieldTypes, resultFieldTypes, selectArgs,\n\t\t\t\t(databaseType.isLimitSqlSupported() ? null : limit), type, cacheStore);\n\t}"
] | [
"public static Date getTimestampFromLong(long timestamp)\n {\n TimeZone tz = TimeZone.getDefault();\n Date result = new Date(timestamp - tz.getRawOffset());\n\n if (tz.inDaylightTime(result) == true)\n {\n int savings;\n\n if (HAS_DST_SAVINGS == true)\n {\n savings = tz.getDSTSavings();\n }\n else\n {\n savings = DEFAULT_DST_SAVINGS;\n }\n\n result = new Date(result.getTime() - savings);\n }\n return (result);\n }",
"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 int getTrailingBitCount(boolean network) {\n\t\tint count = getDivisionCount();\n\t\tif(count == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tlong back = network ? 0 : getDivision(0).getMaxValue();\n\t\tint bitLen = 0;\n\t\tfor(int i = count - 1; i >= 0; i--) {\n\t\t\tIPAddressDivision seg = getDivision(i);\n\t\t\tlong value = seg.getDivisionValue();\n\t\t\tif(value != back) {\n\t\t\t\treturn bitLen + seg.getTrailingBitCount(network);\n\t\t\t}\n\t\t\tbitLen += seg.getBitCount();\n\t\t}\n\t\treturn bitLen;\n\t}",
"public ApnsServiceBuilder withSocksProxy(String host, int port) {\n Proxy proxy = new Proxy(Proxy.Type.SOCKS,\n new InetSocketAddress(host, port));\n return withProxy(proxy);\n }",
"private void readResource(net.sf.mpxj.ganttproject.schema.Resource gpResource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n mpxjResource.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpResource.getId()) + 1));\n mpxjResource.setName(gpResource.getName());\n mpxjResource.setEmailAddress(gpResource.getContacts());\n mpxjResource.setText(1, gpResource.getPhone());\n mpxjResource.setGroup(m_roleDefinitions.get(gpResource.getFunction()));\n\n net.sf.mpxj.ganttproject.schema.Rate gpRate = gpResource.getRate();\n if (gpRate != null)\n {\n mpxjResource.setStandardRate(new Rate(gpRate.getValueAttribute(), TimeUnit.DAYS));\n }\n readResourceCustomFields(gpResource, mpxjResource);\n m_eventManager.fireResourceReadEvent(mpxjResource);\n }",
"protected void beginDragging(MouseDownEvent event) {\n\n m_dragging = true;\n m_windowWidth = Window.getClientWidth();\n m_clientLeft = Document.get().getBodyOffsetLeft();\n m_clientTop = Document.get().getBodyOffsetTop();\n DOM.setCapture(getElement());\n m_dragStartX = event.getX();\n m_dragStartY = event.getY();\n addStyleName(I_CmsLayoutBundle.INSTANCE.dialogCss().dragging());\n }",
"public static sslciphersuite[] get(nitro_service service, options option) throws Exception{\n\t\tsslciphersuite obj = new sslciphersuite();\n\t\tsslciphersuite[] response = (sslciphersuite[])obj.get_resources(service,option);\n\t\treturn response;\n\t}",
"public static base_responses add(nitro_service client, sslcipher resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcipher addresources[] = new sslcipher[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new sslcipher();\n\t\t\t\taddresources[i].ciphergroupname = resources[i].ciphergroupname;\n\t\t\t\taddresources[i].ciphgrpalias = resources[i].ciphgrpalias;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public T removeBundle(final String moduleName, final String slot, final byte[] existingHash) {\n final ContentItem item = createBundleItem(moduleName, slot, NO_CONTENT);\n addContentModification(createContentModification(item, ModificationType.REMOVE, existingHash));\n return returnThis();\n }"
] |
Resize the given mesh keeping its aspect ration.
@param mesh Mesh to be resized.
@param size Max size for the axis. | [
"public static void resize(GVRMesh mesh, float size) {\n float dim[] = getBoundingSize(mesh);\n float maxsize = 0.0f;\n\n if (dim[0] > maxsize) maxsize = dim[0];\n if (dim[1] > maxsize) maxsize = dim[1];\n if (dim[2] > maxsize) maxsize = dim[2];\n\n scale(mesh, size / maxsize);\n }"
] | [
"private boolean runQueuedTask(boolean hasPermit) {\n if (!hasPermit && beginRequest(paused) == RunResult.REJECTED) {\n return false;\n }\n QueuedTask task = null;\n if (!paused) {\n task = taskQueue.poll();\n } else {\n //the container is suspended, but we still need to run any force queued tasks\n task = findForcedTask();\n }\n if (task != null) {\n if(!task.runRequest()) {\n decrementRequestCount();\n }\n return true;\n } else {\n decrementRequestCount();\n return false;\n }\n }",
"public static InternetPrintWriter createForEncoding(OutputStream outputStream, boolean autoFlush, Charset charset) {\r\n return new InternetPrintWriter(new OutputStreamWriter(outputStream, charset), autoFlush);\r\n }",
"protected void mergeHardcodedResultsFrom(Configuration otherConfiguration) {\r\n Map<Dotted, AnalysisResult> resultsMap = hardcodedResults.build().stream()\r\n .collect(Collectors.toMap(r -> r.className, r -> r));\r\n resultsMap.putAll(otherConfiguration.hardcodedResults());\r\n hardcodedResults = ImmutableSet.<AnalysisResult>builder().addAll(resultsMap.values());\r\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 }",
"private static void checkPreconditions(List<String> requiredSubStrings) {\n\t\tif( requiredSubStrings == null ) {\n\t\t\tthrow new NullPointerException(\"requiredSubStrings List should not be null\");\n\t\t} else if( requiredSubStrings.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"requiredSubStrings List should not be empty\");\n\t\t}\n\t}",
"public int[] argb(int x, int y) {\n Pixel p = pixel(x, y);\n return new int[]{p.alpha(), p.red(), p.green(), p.blue()};\n }",
"public String calculateCacheKey(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability){\r\n\t\tStringBuilder tmp = calculateCacheKeyInternal(sql, resultSetType,\r\n\t\t\t\tresultSetConcurrency);\r\n\r\n\t\ttmp.append(\", H:\");\r\n\t\ttmp.append(resultSetHoldability);\r\n\r\n\t\treturn tmp.toString();\r\n\t}",
"private JarFile loadJar(File archive) throws DecompilationException\n {\n try\n {\n return new JarFile(archive);\n }\n catch (IOException ex)\n {\n throw new DecompilationException(\"Can't load .jar: \" + archive.getPath(), ex);\n }\n }",
"public String urlDecode(String s) {\n if (s == null || s.isEmpty()) {\n return s;\n }\n return URL.decodeQueryString(s);\n }"
] |
Get a property as a json array or throw exception.
@param key the property name | [
"public final PJsonArray getJSONArray(final String key) {\n final JSONArray val = this.obj.optJSONArray(key);\n if (val == null) {\n throw new ObjectMissingException(this, key);\n }\n return new PJsonArray(this, val, key);\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 }",
"public V get(K key) {\n ManagedReference<V> ref = internalMap.get(key);\n if (ref!=null) return ref.get();\n return null;\n }",
"public void process(DirectoryEntry projectDir, ProjectFile file, DocumentInputStreamFactory inputStreamFactory) throws IOException\n {\n DirectoryEntry consDir;\n try\n {\n consDir = (DirectoryEntry) projectDir.getEntry(\"TBkndCons\");\n }\n\n catch (FileNotFoundException ex)\n {\n consDir = null;\n }\n\n if (consDir != null)\n {\n FixedMeta consFixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) consDir.getEntry(\"FixedMeta\"))), 10);\n FixedData consFixedData = new FixedData(consFixedMeta, 20, inputStreamFactory.getInstance(consDir, \"FixedData\"));\n // FixedMeta consFixed2Meta = new FixedMeta(new DocumentInputStream(((DocumentEntry) consDir.getEntry(\"Fixed2Meta\"))), 9);\n // FixedData consFixed2Data = new FixedData(consFixed2Meta, 48, getEncryptableInputStream(consDir, \"Fixed2Data\"));\n\n int count = consFixedMeta.getAdjustedItemCount();\n int lastConstraintID = -1;\n\n ProjectProperties properties = file.getProjectProperties();\n EventManager eventManager = file.getEventManager();\n\n boolean project15 = NumberHelper.getInt(properties.getMppFileType()) == 14 && NumberHelper.getInt(properties.getApplicationVersion()) > ApplicationVersion.PROJECT_2010;\n int durationUnitsOffset = project15 ? 18 : 14;\n int durationOffset = project15 ? 14 : 16;\n\n for (int loop = 0; loop < count; loop++)\n {\n byte[] metaData = consFixedMeta.getByteArrayValue(loop);\n\n //\n // SourceForge bug 2209477: we were reading an int here, but\n // it looks like the deleted flag is just a short.\n //\n if (MPPUtility.getShort(metaData, 0) != 0)\n {\n continue;\n }\n\n int index = consFixedData.getIndexFromOffset(MPPUtility.getInt(metaData, 4));\n if (index == -1)\n {\n continue;\n }\n\n //\n // Do we have enough data?\n //\n byte[] data = consFixedData.getByteArrayValue(index);\n if (data.length < 14)\n {\n continue;\n }\n\n int constraintID = MPPUtility.getInt(data, 0);\n if (constraintID <= lastConstraintID)\n {\n continue;\n }\n\n lastConstraintID = constraintID;\n int taskID1 = MPPUtility.getInt(data, 4);\n int taskID2 = MPPUtility.getInt(data, 8);\n\n if (taskID1 == taskID2)\n {\n continue;\n }\n\n // byte[] metaData2 = consFixed2Meta.getByteArrayValue(loop);\n // int index2 = consFixed2Data.getIndexFromOffset(MPPUtility.getInt(metaData2, 4));\n // byte[] data2 = consFixed2Data.getByteArrayValue(index2);\n\n Task task1 = file.getTaskByUniqueID(Integer.valueOf(taskID1));\n Task task2 = file.getTaskByUniqueID(Integer.valueOf(taskID2));\n if (task1 != null && task2 != null)\n {\n RelationType type = RelationType.getInstance(MPPUtility.getShort(data, 12));\n TimeUnit durationUnits = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(data, durationUnitsOffset));\n Duration lag = MPPUtility.getAdjustedDuration(properties, MPPUtility.getInt(data, durationOffset), durationUnits);\n Relation relation = task2.addPredecessor(task1, type, lag);\n relation.setUniqueID(Integer.valueOf(constraintID));\n eventManager.fireRelationReadEvent(relation);\n }\n }\n }\n }",
"public final static String process(final String input, final Configuration configuration)\n {\n try\n {\n return process(new StringReader(input), configuration);\n }\n catch (final IOException e)\n {\n // This _can never_ happen\n return null;\n }\n }",
"public static Processor<DataSourceTask> source(DataSource source, int parallelism, String description, UserConfig taskConf, ActorSystem system) {\n io.gearpump.streaming.Processor<DataSourceTask<Object, Object>> p =\n DataSourceProcessor.apply(source, parallelism, description, taskConf, system);\n return new Processor(p);\n }",
"private long doMemoryManagementAndPerFrameCallbacks() {\n long currentTime = GVRTime.getCurrentTime();\n mFrameTime = (currentTime - mPreviousTimeNanos) / 1e9f;\n mPreviousTimeNanos = currentTime;\n\n /*\n * Without the sensor data, can't draw a scene properly.\n */\n if (!(mSensoredScene == null || !mMainScene.equals(mSensoredScene))) {\n Runnable runnable;\n while ((runnable = mRunnables.poll()) != null) {\n try {\n runnable.run();\n } catch (final Exception exc) {\n Log.e(TAG, \"Runnable-on-GL %s threw %s\", runnable, exc.toString());\n exc.printStackTrace();\n }\n }\n\n final List<GVRDrawFrameListener> frameListeners = mFrameListeners;\n for (GVRDrawFrameListener listener : frameListeners) {\n try {\n listener.onDrawFrame(mFrameTime);\n } catch (final Exception exc) {\n Log.e(TAG, \"DrawFrameListener %s threw %s\", listener, exc.toString());\n exc.printStackTrace();\n }\n }\n }\n\n return currentTime;\n }",
"@SuppressWarnings(\"unchecked\")\n\t/* @Nullable */\n\tpublic <T> T get(Object receiver, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {\n\t\tPreconditions.checkNotNull(receiver,\"receiver\");\n\t\tPreconditions.checkNotNull(fieldName,\"fieldName\");\n\t\t\n\t\tClass<? extends Object> clazz = receiver.getClass();\n\t\tField f = getDeclaredField(clazz, fieldName);\n\t\tif (!f.isAccessible())\n\t\t\tf.setAccessible(true);\n\t\treturn (T) f.get(receiver);\n\t}",
"private void updateHostingEntityIfRequired() {\n\t\tif ( hostingEntity != null && hostingEntityRequiresReadAfterUpdate() ) {\n\t\t\tOgmEntityPersister entityPersister = getHostingEntityPersister();\n\n\t\t\tif ( GridDialects.hasFacet( gridDialect, GroupingByEntityDialect.class ) ) {\n\t\t\t\t( (GroupingByEntityDialect) gridDialect ).flushPendingOperations( getAssociationKey().getEntityKey(),\n\t\t\t\t\t\tentityPersister.getTupleContext( session ) );\n\t\t\t}\n\n\t\t\tentityPersister.processUpdateGeneratedProperties(\n\t\t\t\t\tentityPersister.getIdentifier( hostingEntity, session ),\n\t\t\t\t\thostingEntity,\n\t\t\t\t\tnew Object[entityPersister.getPropertyNames().length],\n\t\t\t\t\tsession\n\t\t\t);\n\t\t}\n\t}",
"public byte[] keyToStorageFormat(byte[] key) {\n\n switch(getReadOnlyStorageFormat()) {\n case READONLY_V0:\n case READONLY_V1:\n return ByteUtils.md5(key);\n case READONLY_V2:\n return ByteUtils.copy(ByteUtils.md5(key), 0, 2 * ByteUtils.SIZE_OF_INT);\n default:\n throw new VoldemortException(\"Unknown read-only storage format\");\n }\n }"
] |
Write a date field to the JSON file.
@param fieldName field name
@param value field value | [
"private void writeDateField(String fieldName, Object value) throws IOException\n {\n if (value instanceof String)\n {\n m_writer.writeNameValuePair(fieldName + \"_text\", (String) value);\n }\n else\n {\n Date val = (Date) value;\n m_writer.writeNameValuePair(fieldName, val);\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 }",
"protected Map getAllVariables(){\n try{\n Iterator names = FreeMarkerTL.getEnvironment().getKnownVariableNames().iterator();\n Map vars = new HashMap();\n while (names.hasNext()) {\n Object name =names.next();\n vars.put(name, get(name.toString()));\n }\n return vars;\n }catch(Exception e){\n throw new ViewException(e);\n }\n }",
"private JSONArray getApplicablePathNames (String requestUrl, Integer requestType) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n List<EndpointOverride> applicablePaths;\n JSONArray pathNames = new JSONArray();\n // Get all paths that match the request\n applicablePaths = PathOverrideService.getInstance().getSelectedPaths(Constants.OVERRIDE_TYPE_REQUEST, requestInfo.client,\n requestInfo.profile,\n requestUrl + \"?\" + requestInfo.originalRequestInfo.getQueryString(),\n requestType, true);\n // Extract just the path name from each path\n for (EndpointOverride path : applicablePaths) {\n JSONObject pathName = new JSONObject();\n pathName.put(\"name\", path.getPathName());\n pathNames.put(pathName);\n }\n\n return pathNames;\n }",
"public SerialMessage getMultiChannelCapabilityGetMessage(ZWaveEndpoint endpoint) {\r\n\t\tlogger.debug(\"Creating new message for application command MULTI_CHANNEL_CAPABILITY_GET for node {} and endpoint {}\", this.getNode().getNodeId(), endpoint.getEndpointId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t3, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) MULTI_CHANNEL_CAPABILITY_GET,\r\n\t\t\t\t\t\t\t\t(byte) endpoint.getEndpointId() };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\r\n\t}",
"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}",
"private void deleteUnusedCaseSteps( ReportModel model ) {\n\n for( ScenarioModel scenarioModel : model.getScenarios() ) {\n if( scenarioModel.isCasesAsTable() && !hasAttachment( scenarioModel ) ) {\n List<ScenarioCaseModel> cases = scenarioModel.getScenarioCases();\n for( int i = 1; i < cases.size(); i++ ) {\n ScenarioCaseModel caseModel = cases.get( i );\n caseModel.setSteps( Collections.<StepModel>emptyList() );\n }\n }\n }\n }",
"private void readUnread(CommitData cd, Consumer<Entry<Key, Value>> locksSeen) {\n // TODO make async\n // TODO need to keep track of ranges read (not ranges passed in, but actual data read... user\n // may not iterate over entire range\n Map<Bytes, Set<Column>> columnsToRead = new HashMap<>();\n\n for (Entry<Bytes, Set<Column>> entry : cd.getRejected().entrySet()) {\n Set<Column> rowColsRead = columnsRead.get(entry.getKey());\n if (rowColsRead == null) {\n columnsToRead.put(entry.getKey(), entry.getValue());\n } else {\n HashSet<Column> colsToRead = new HashSet<>(entry.getValue());\n colsToRead.removeAll(rowColsRead);\n if (!colsToRead.isEmpty()) {\n columnsToRead.put(entry.getKey(), colsToRead);\n }\n }\n }\n\n for (Entry<Bytes, Set<Column>> entry : columnsToRead.entrySet()) {\n getImpl(entry.getKey(), entry.getValue(), locksSeen);\n }\n }",
"public List<Client> findAllClients(int profileId) throws Exception {\n ArrayList<Client> clients = new ArrayList<Client>();\n\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\"\n );\n query.setInt(1, profileId);\n results = query.executeQuery();\n while (results.next()) {\n clients.add(this.getClientFromResultSet(results));\n }\n } catch (Exception e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n return clients;\n }",
"protected boolean isNetworkSection(int networkPrefixLength, boolean withPrefixLength) {\n\t\tint segmentCount = getSegmentCount();\n\t\tif(segmentCount == 0) {\n\t\t\treturn true;\n\t\t}\n\t\tint bitsPerSegment = getBitsPerSegment();\n\t\tint prefixedSegmentIndex = getNetworkSegmentIndex(networkPrefixLength, getBytesPerSegment(), bitsPerSegment);\n\t\tif(prefixedSegmentIndex + 1 < segmentCount) {\n\t\t\treturn false; //not the right number of segments\n\t\t}\n\t\t//the segment count matches, now compare the prefixed segment\n\t\tint segPrefLength = getPrefixedSegmentPrefixLength(bitsPerSegment, networkPrefixLength, prefixedSegmentIndex);\n\t\treturn !getSegment(segmentCount - 1).isNetworkChangedByPrefix(segPrefLength, withPrefixLength);\n\t}"
] |
Validates aliases.
@param uuid The structure id for which the aliases should be valid
@param aliasPaths a map from id strings to alias paths
@param callback the callback which should be called with the validation results | [
"public void validateAliases(\r\n final CmsUUID uuid,\r\n final Map<String, String> aliasPaths,\r\n final AsyncCallback<Map<String, String>> callback) {\r\n\r\n CmsRpcAction<Map<String, String>> action = new CmsRpcAction<Map<String, String>>() {\r\n\r\n /**\r\n * @see org.opencms.gwt.client.rpc.CmsRpcAction#execute()\r\n */\r\n @Override\r\n public void execute() {\r\n\r\n start(200, true);\r\n CmsCoreProvider.getVfsService().validateAliases(uuid, aliasPaths, this);\r\n }\r\n\r\n /**\r\n * @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object)\r\n */\r\n @Override\r\n protected void onResponse(Map<String, String> result) {\r\n\r\n stop(false);\r\n callback.onSuccess(result);\r\n }\r\n\r\n };\r\n action.execute();\r\n }"
] | [
"private byte[] readStreamCompressed(InputStream stream) throws IOException\r\n {\r\n ByteArrayOutputStream bao = new ByteArrayOutputStream();\r\n GZIPOutputStream gos = new GZIPOutputStream(bao);\r\n OutputStreamWriter output = new OutputStreamWriter(gos);\r\n BufferedReader input = new BufferedReader(new InputStreamReader(stream));\r\n String line;\r\n\r\n while ((line = input.readLine()) != null)\r\n {\r\n output.write(line);\r\n output.write('\\n');\r\n }\r\n input.close();\r\n stream.close();\r\n output.close();\r\n gos.close();\r\n bao.close();\r\n return bao.toByteArray();\r\n }",
"public void delete(Object obj, boolean ignoreReferences) throws PersistenceBrokerException\n {\n if(isTxCheck() && !isInTransaction())\n {\n if(logger.isEnabledFor(Logger.ERROR))\n {\n String msg = \"No running PB-tx found. Please, only delete objects in context of a PB-transaction\" +\n \" to avoid side-effects - e.g. when rollback of complex objects.\";\n try\n {\n throw new Exception(\"** Delete object without active PersistenceBroker transaction **\");\n }\n catch(Exception e)\n {\n logger.error(msg, e);\n }\n }\n }\n try\n {\n doDelete(obj, ignoreReferences);\n }\n finally\n {\n markedForDelete.clear();\n }\n }",
"public static base_response update(nitro_service client, responderparam resource) throws Exception {\n\t\tresponderparam updateresource = new responderparam();\n\t\tupdateresource.undefaction = resource.undefaction;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public GVRCursorController findCursorController(GVRControllerType type) {\n for (int index = 0, size = cache.size(); index < size; index++)\n {\n int key = cache.keyAt(index);\n GVRCursorController controller = cache.get(key);\n if (controller.getControllerType().equals(type)) {\n return controller;\n }\n }\n return null;\n }",
"private JSONArray readOptionalArray(JSONObject json, String key) {\n\n try {\n return json.getJSONArray(key);\n } catch (JSONException e) {\n LOG.debug(\"Reading optional JSON array failed. Default to provided default value.\", e);\n }\n return null;\n }",
"public boolean deleteExisting(final File file) {\n if (!file.exists()) {\n return true;\n }\n boolean deleted = false;\n if (file.canWrite()) {\n deleted = file.delete();\n } else {\n LogLog.debug(file + \" is not writeable for delete (retrying)\");\n }\n if (!deleted) {\n if (!file.exists()) {\n deleted = true;\n } else {\n file.delete();\n deleted = (!file.exists());\n }\n }\n return deleted;\n }",
"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 void fireEvent(final WorkerEvent event, final Worker worker, final String queue, final Job job, \n final Object runner, final Object result, final Throwable t) {\n final ConcurrentSet<WorkerListener> listeners = this.eventListenerMap.get(event);\n if (listeners != null) {\n for (final WorkerListener listener : listeners) {\n if (listener != null) {\n try {\n listener.onEvent(event, worker, queue, job, runner, result, t);\n } catch (Exception e) {\n log.error(\"Failure executing listener \" + listener + \" for event \" + event \n + \" from queue \" + queue + \" on worker \" + worker, e);\n }\n }\n }\n }\n }",
"public ClassNode addInterface(String name) {\n ClassNode intf = infoBase.node(name);\n addInterface(intf);\n return this;\n }"
] |
Creates a new section in a project.
Returns the full record of the newly created section.
@param project The project to create the section in
@return Request object | [
"public ItemRequest<Section> createInProject(String project) {\n \n String path = String.format(\"/projects/%s/sections\", project);\n return new ItemRequest<Section>(this, Section.class, path, \"POST\");\n }"
] | [
"public boolean containsNonZeroHosts(IPAddressSection other) {\n\t\tif(!other.isPrefixed()) {\n\t\t\treturn contains(other);\n\t\t}\n\t\tint otherPrefixLength = other.getNetworkPrefixLength();\n\t\tif(otherPrefixLength == other.getBitCount()) {\n\t\t\treturn contains(other);\n\t\t}\n\t\treturn containsNonZeroHostsImpl(other, otherPrefixLength);\n\t}",
"synchronized boolean doReConnect() throws IOException {\n\n // In case we are still connected, test the connection and see if we can reuse it\n if(connectionManager.isConnected()) {\n try {\n final Future<Long> result = channelHandler.executeRequest(ManagementPingRequest.INSTANCE, null).getResult();\n result.get(15, TimeUnit.SECONDS); // Hmm, perhaps 15 is already too much\n return true;\n } catch (Exception e) {\n ServerLogger.AS_ROOT_LOGGER.debugf(e, \"failed to ping the host-controller, going to reconnect\");\n }\n // Disconnect - the HC might have closed the connection without us noticing and is asking for a reconnect\n final Connection connection = connectionManager.getConnection();\n StreamUtils.safeClose(connection);\n if(connection != null) {\n try {\n // Wait for the connection to be closed\n connection.awaitClosed();\n } catch (InterruptedException e) {\n throw new InterruptedIOException();\n }\n }\n }\n\n boolean ok = false;\n final Connection connection = connectionManager.connect();\n try {\n // Reconnect to the host-controller\n final ActiveOperation<Boolean, Void> result = channelHandler.executeRequest(new ServerReconnectRequest(), null);\n try {\n boolean inSync = result.getResult().get();\n ok = true;\n reconnectRunner = null;\n return inSync;\n } catch (ExecutionException e) {\n throw new IOException(e);\n } catch (InterruptedException e) {\n throw new InterruptedIOException();\n }\n } finally {\n if(!ok) {\n StreamUtils.safeClose(connection);\n }\n }\n }",
"public void fireResourceReadEvent(Resource resource)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.resourceRead(resource);\n }\n }\n }",
"public <K, V> MultipleRequestBuilder<K, V> newMultipleRequest(Key.Type<K> keyType,\n Class<V> valueType) {\n return new MultipleRequestBuilderImpl<K, V>(newViewRequestParameters(keyType.getType(),\n valueType));\n }",
"public static ComplexNumber Add(ComplexNumber z1, ComplexNumber z2) {\r\n return new ComplexNumber(z1.real + z2.real, z1.imaginary + z2.imaginary);\r\n }",
"public static JMXServiceURL getLocalConnectorAddress(Process p, boolean startAgent) {\n return getLocalConnectorAddress(Integer.toString(getPid(p)), startAgent);\n }",
"private void processProject(PrimaveraDatabaseReader reader, int projectID, String outputFile) throws Exception\n {\n long start = System.currentTimeMillis();\n reader.setProjectID(projectID);\n ProjectFile projectFile = reader.read();\n long elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Reading database 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 }",
"private void updateCursorsInScene(GVRScene scene, boolean add) {\n synchronized (mCursors) {\n for (Cursor cursor : mCursors) {\n if (cursor.isActive()) {\n if (add) {\n addCursorToScene(cursor);\n } else {\n removeCursorFromScene(cursor);\n }\n }\n }\n }\n }",
"public static List<Number> findIndexValues(Object self, Closure closure) {\n return findIndexValues(self, 0, closure);\n }"
] |
Loops over cluster and repeatedly tries to break up contiguous runs of
partitions. After each phase of breaking up contiguous partitions, random
partitions are selected to move between zones to balance the number of
partitions in each zone. The second phase may re-introduce contiguous
partition runs in another zone. Therefore, this overall process is
repeated multiple times.
@param nextCandidateCluster
@param maxContiguousPartitionsPerZone See RebalanceCLI.
@return updated cluster | [
"public static Cluster\n repeatedlyBalanceContiguousPartitionsPerZone(final Cluster nextCandidateCluster,\n final int maxContiguousPartitionsPerZone) {\n System.out.println(\"Looping to evenly balance partitions across zones while limiting contiguous partitions\");\n // This loop is hard to make definitive. I.e., there are corner cases\n // for small clusters and/or clusters with few partitions for which it\n // may be impossible to achieve tight limits on contiguous run lenghts.\n // Therefore, a constant number of loops are run. Note that once the\n // goal is reached, the loop becomes a no-op.\n int repeatContigBalance = 10;\n Cluster returnCluster = nextCandidateCluster;\n for(int i = 0; i < repeatContigBalance; i++) {\n returnCluster = balanceContiguousPartitionsPerZone(returnCluster,\n maxContiguousPartitionsPerZone);\n\n returnCluster = balancePrimaryPartitions(returnCluster, false);\n System.out.println(\"Completed round of balancing contiguous partitions: round \"\n + (i + 1) + \" of \" + repeatContigBalance);\n }\n\n return returnCluster;\n }"
] | [
"private Object getLiteralValue(Expression expression) {\n\t\tif (!(expression instanceof Literal)) {\n\t\t\tthrow new IllegalArgumentException(\"Expression \" + expression + \" is not a Literal.\");\n\t\t}\n\t\treturn ((Literal) expression).getValue();\n\t}",
"public static long decodeLong(byte[] ba, int offset) {\n return ((((long) ba[offset + 0] << 56) + ((long) (ba[offset + 1] & 255) << 48)\n + ((long) (ba[offset + 2] & 255) << 40) + ((long) (ba[offset + 3] & 255) << 32)\n + ((long) (ba[offset + 4] & 255) << 24) + ((ba[offset + 5] & 255) << 16)\n + ((ba[offset + 6] & 255) << 8) + ((ba[offset + 7] & 255) << 0)));\n }",
"public boolean detectOperaMobile() {\r\n\r\n if ((userAgent.indexOf(engineOpera) != -1)\r\n && ((userAgent.indexOf(mini) != -1) || (userAgent.indexOf(mobi) != -1))) {\r\n return true;\r\n }\r\n return false;\r\n }",
"protected Patch createProcessedPatch(final Patch original) {\n\n // Process elements\n final List<PatchElement> elements = new ArrayList<PatchElement>();\n // Process layers\n for (final PatchEntry entry : getLayers()) {\n final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications);\n elements.add(element);\n }\n // Process add-ons\n for (final PatchEntry entry : getAddOns()) {\n final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications);\n elements.add(element);\n }\n\n // Swap the patch element modifications, keep the identity ones since we don't need to fix the misc modifications\n return new PatchImpl(original.getPatchId(), original.getDescription(), original.getLink(), original.getIdentity(), elements, identityEntry.modifications);\n }",
"public PhotoList<Photo> getContactsPublicPhotos(String userId, int count, boolean justFriends, boolean singlePhoto, boolean includeSelf)\r\n throws FlickrException {\r\n return getContactsPublicPhotos(userId, Extras.MIN_EXTRAS, count, justFriends, singlePhoto, includeSelf);\r\n }",
"public static String getColumnSharedPrefix(String[] associationKeyColumns) {\n\t\tString prefix = null;\n\t\tfor ( String column : associationKeyColumns ) {\n\t\t\tString newPrefix = getPrefix( column );\n\t\t\tif ( prefix == null ) { // first iteration\n\t\t\t\tprefix = newPrefix;\n\t\t\t\tif ( prefix == null ) { // no prefix, quit\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse { // subsequent iterations\n\t\t\t\tif ( ! equals( prefix, newPrefix ) ) { // different prefixes\n\t\t\t\t\tprefix = null;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn prefix;\n\t}",
"static Object getLCState(StateManagerInternal sm)\r\n\t{\r\n\t\t// unfortunately the LifeCycleState classes are package private.\r\n\t\t// so we have to do some dirty reflection hack to access them\r\n\t\ttry\r\n\t\t{\r\n\t\t\tField myLC = sm.getClass().getDeclaredField(\"myLC\");\r\n\t\t\tmyLC.setAccessible(true);\r\n\t\t\treturn myLC.get(sm);\r\n\t\t}\r\n\t\tcatch (NoSuchFieldException e)\r\n\t\t{\r\n\t\t\treturn e;\r\n\t\t}\r\n\t\tcatch (IllegalAccessException e)\r\n\t\t{\r\n\t\t\treturn e;\r\n\t\t}\t\r\n\t}",
"public Response executeToResponse(HttpConnection connection) {\n InputStream is = null;\n try {\n is = this.executeToInputStream(connection);\n Response response = getResponse(is, Response.class, getGson());\n response.setStatusCode(connection.getConnection().getResponseCode());\n response.setReason(connection.getConnection().getResponseMessage());\n return response;\n } catch (IOException e) {\n throw new CouchDbException(\"Error retrieving response code or message.\", e);\n } finally {\n close(is);\n }\n }",
"private void printKeySet() {\r\n Set<?> keys = keySet();\r\n System.out.println(\"printing keyset:\");\r\n for (Object o: keys) {\r\n //System.out.println(Arrays.asList((Object[]) i.next()));\r\n System.out.println(o);\r\n }\r\n }"
] |
Creates a tar file entry with defaults parameters.
@param fileName the entry name
@return file entry with reasonable defaults | [
"static TarArchiveEntry defaultFileEntryWithName( final String fileName ) {\n TarArchiveEntry entry = new TarArchiveEntry(fileName, true);\n entry.setUserId(ROOT_UID);\n entry.setUserName(ROOT_NAME);\n entry.setGroupId(ROOT_UID);\n entry.setGroupName(ROOT_NAME);\n entry.setMode(TarArchiveEntry.DEFAULT_FILE_MODE);\n return entry;\n }"
] | [
"public List depthFirst() {\n List answer = new NodeList();\n answer.add(this);\n answer.addAll(depthFirstRest());\n return answer;\n }",
"public static void setCurrentPersistenceBroker(PBKey key, PersistenceBrokerInternal broker)\r\n throws PBFactoryException\r\n {\r\n HashMap map = (HashMap) currentBrokerMap.get();\r\n WeakHashMap set = null;\r\n if(map == null)\r\n {\r\n map = new HashMap();\r\n currentBrokerMap.set(map);\r\n\r\n synchronized(lock) {\r\n loadedHMs.add(map);\r\n }\r\n }\r\n else\r\n {\r\n set = (WeakHashMap) map.get(key);\r\n }\r\n\r\n if(set == null)\r\n {\r\n // We emulate weak HashSet using WeakHashMap\r\n set = new WeakHashMap();\r\n map.put(key, set);\r\n }\r\n set.put(broker, null);\r\n }",
"@PrefMetadata(type = CmsHiddenBuiltinPreference.class)\n public String getExplorerFileEntryOptions() {\n\n if (m_settings.getExplorerFileEntryOptions() == null) {\n return \"\";\n } else {\n return \"\" + m_settings.getExplorerFileEntryOptions();\n }\n }",
"public void clear() {\n\t\tfor (Bean bean : beans.values()) {\n\t\t\tif (null != bean.destructionCallback) {\n\t\t\t\tbean.destructionCallback.run();\n\t\t\t}\n\t\t}\n\t\tbeans.clear();\n\t}",
"public void loadClassifier(File file, Properties props) throws ClassCastException, IOException,\r\n ClassNotFoundException {\r\n Timing.startDoing(\"Loading classifier from \" + file.getAbsolutePath());\r\n BufferedInputStream bis;\r\n if (file.getName().endsWith(\".gz\")) {\r\n bis = new BufferedInputStream(new GZIPInputStream(new FileInputStream(file)));\r\n } else {\r\n bis = new BufferedInputStream(new FileInputStream(file));\r\n }\r\n loadClassifier(bis, props);\r\n bis.close();\r\n Timing.endDoing();\r\n }",
"public static void assertValidMetadata(ByteArray key,\n RoutingStrategy routingStrategy,\n Node currentNode) {\n List<Node> nodes = routingStrategy.routeRequest(key.get());\n for(Node node: nodes) {\n if(node.getId() == currentNode.getId()) {\n return;\n }\n }\n\n throw new InvalidMetadataException(\"Client accessing key belonging to partitions \"\n + routingStrategy.getPartitionList(key.get())\n + \" not present at \" + currentNode);\n }",
"public static String makePropertyName(String name) {\n char[] buf = new char[name.length() + 3];\n int pos = 0;\n buf[pos++] = 's';\n buf[pos++] = 'e';\n buf[pos++] = 't';\n\n for (int ix = 0; ix < name.length(); ix++) {\n char ch = name.charAt(ix);\n if (ix == 0)\n ch = Character.toUpperCase(ch);\n else if (ch == '-') {\n ix++;\n if (ix == name.length())\n break;\n ch = Character.toUpperCase(name.charAt(ix));\n }\n\n buf[pos++] = ch;\n }\n\n return new String(buf, 0, pos);\n }",
"private String getInitials(String name)\n {\n String result = null;\n\n if (name != null && name.length() != 0)\n {\n StringBuilder sb = new StringBuilder();\n sb.append(name.charAt(0));\n int index = 1;\n while (true)\n {\n index = name.indexOf(' ', index);\n if (index == -1)\n {\n break;\n }\n\n ++index;\n if (index < name.length() && name.charAt(index) != ' ')\n {\n sb.append(name.charAt(index));\n }\n\n ++index;\n }\n\n result = sb.toString();\n }\n\n return result;\n }",
"@Override\n\tpublic Iterator<? extends IPAddressSeqRange> prefixIterator(int prefixLength) {\n\t\tif(!isMultiple()) {\n\t\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\t\tIPAddressSeqRange orig = IPAddressSeqRange.this;\n\n\t\t\t\t@Override\n\t\t\t\tpublic boolean hasNext() {\n\t\t\t\t\treturn orig != null;\n\t\t\t\t}\n\n\t\t\t @Override\n\t\t\t\tpublic IPAddressSeqRange next() {\n\t\t\t \tif(orig == null) {\n\t\t\t \t\tthrow new NoSuchElementException();\n\t\t\t \t}\n\t\t\t \tIPAddressSeqRange result = orig;\n\t\t\t \torig = null;\n\t\t\t \treturn result;\n\t\t\t }\n\t\t\t\n\t\t\t @Override\n\t\t\t\tpublic void remove() {\n\t\t\t \tthrow new UnsupportedOperationException();\n\t\t\t }\n\t\t\t};\n\t\t}\n\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\tIterator<? extends IPAddress> prefixBlockIterator = prefixBlockIterator(prefixLength);\n\t\t\tprivate boolean first = true;\n\n\t\t\t@Override\n\t\t\tpublic boolean hasNext() {\n\t\t\t\treturn prefixBlockIterator.hasNext();\n\t\t\t}\n\n\t\t @Override\n\t\t\tpublic IPAddressSeqRange next() {\n\t\t \tIPAddress next = prefixBlockIterator.next();\n\t\t \tif(first) {\n\t\t \t\tfirst = false;\n\t\t \t\t// next is a prefix block\n\t\t \t\tIPAddress lower = getLower();\n\t\t \t\tif(hasNext()) {\n\t\t\t \t\tif(!lower.includesZeroHost(prefixLength)) {\n\t\t\t \t\t\treturn create(lower, next.getUpper());\n\t\t\t \t\t}\n\t\t \t\t} else {\n\t\t \t\t\tIPAddress upper = getUpper();\n\t\t \t\t\tif(!lower.includesZeroHost(prefixLength) || !upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\t\treturn create(lower, upper);\n\t\t \t\t\t}\n\t\t \t\t}\n\t\t \t} else if(!hasNext()) {\n\t\t \t\tIPAddress upper = getUpper();\n\t\t \t\tif(!upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\treturn create(next.getLower(), upper);\n\t\t \t\t}\n\t\t \t}\n\t\t \treturn next.toSequentialRange();\n\t\t }\n\t\t\n\t\t @Override\n\t\t\tpublic void remove() {\n\t\t \tthrow new UnsupportedOperationException();\n\t\t }\n\t\t};\n\t}"
] |
Delete by id.
@param id the id | [
"public void deleteById(String id) {\n if (idToVersion.containsKey(id)) {\n String version = idToVersion.remove(id);\n expirationVersion.remove(version);\n versionToItem.remove(version);\n if (collectionCachePath != null\n && !collectionCachePath.resolve(version).toFile().delete()) {\n log.debug(\"couldn't delete \" + version);\n }\n }\n }"
] | [
"public static boolean matches(Map<String, Object> nodeProperties, String[] keyColumnNames, Object[] keyColumnValues) {\n\t\tfor ( int i = 0; i < keyColumnNames.length; i++ ) {\n\t\t\tString property = keyColumnNames[i];\n\t\t\tObject expectedValue = keyColumnValues[i];\n\t\t\tboolean containsProperty = nodeProperties.containsKey( property );\n\t\t\tif ( containsProperty ) {\n\t\t\t\tObject actualValue = nodeProperties.get( property );\n\t\t\t\tif ( !sameValue( expectedValue, actualValue ) ) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ( expectedValue != null ) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}",
"public Map<String, Table> process(File directory, String prefix) throws IOException\n {\n String filePrefix = prefix.toUpperCase();\n Map<String, Table> tables = new HashMap<String, Table>();\n File[] files = directory.listFiles();\n if (files != null)\n {\n for (File file : files)\n {\n String name = file.getName().toUpperCase();\n if (!name.startsWith(filePrefix))\n {\n continue;\n }\n\n int typeIndex = name.lastIndexOf('.') - 3;\n String type = name.substring(typeIndex, typeIndex + 3);\n TableDefinition definition = TABLE_DEFINITIONS.get(type);\n if (definition != null)\n {\n Table table = new Table();\n TableReader reader = new TableReader(definition);\n reader.read(file, table);\n tables.put(type, table);\n //dumpCSV(type, definition, table);\n }\n }\n }\n return tables;\n }",
"public static ModelMBean createModelMBean(Object o) {\n try {\n ModelMBean mbean = new RequiredModelMBean();\n JmxManaged annotation = o.getClass().getAnnotation(JmxManaged.class);\n String description = annotation == null ? \"\" : annotation.description();\n ModelMBeanInfo info = new ModelMBeanInfoSupport(o.getClass().getName(),\n description,\n extractAttributeInfo(o),\n new ModelMBeanConstructorInfo[0],\n extractOperationInfo(o),\n new ModelMBeanNotificationInfo[0]);\n mbean.setModelMBeanInfo(info);\n mbean.setManagedResource(o, \"ObjectReference\");\n\n return mbean;\n } catch(MBeanException e) {\n throw new VoldemortException(e);\n } catch(InvalidTargetObjectTypeException e) {\n throw new VoldemortException(e);\n } catch(InstanceNotFoundException e) {\n throw new VoldemortException(e);\n }\n }",
"private void useSearchService() throws Exception {\n\n System.out.println(\"Searching...\");\n\n WebClient wc = WebClient.create(\"http://localhost:\" + port + \"/services/personservice/search\");\n WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(10000000L);\n wc.accept(MediaType.APPLICATION_XML);\n \n // Moves to \"/services/personservice/search\"\n wc.path(\"person\");\n \n SearchConditionBuilder builder = SearchConditionBuilder.instance(); \n \n System.out.println(\"Find people with the name Fred or Lorraine:\");\n \n String query = builder.is(\"name\").equalTo(\"Fred\").or()\n .is(\"name\").equalTo(\"Lorraine\")\n .query();\n findPersons(wc, query);\n \n System.out.println(\"Find all people who are no more than 30 years old\");\n query = builder.is(\"age\").lessOrEqualTo(30)\n \t\t.query();\n \n findPersons(wc, query);\n \n System.out.println(\"Find all people who are older than 28 and whose father name is John\");\n query = builder.is(\"age\").greaterThan(28)\n \t\t.and(\"fatherName\").equalTo(\"John\")\n \t\t.query();\n \n findPersons(wc, query);\n\n System.out.println(\"Find all people who have children with name Fred\");\n query = builder.is(\"childName\").equalTo(\"Fred\")\n \t\t.query();\n \n findPersons(wc, query);\n \n //Moves to \"/services/personservice/personinfo\"\n wc.reset().accept(MediaType.APPLICATION_XML);\n wc.path(\"personinfo\");\n \n System.out.println(\"Find all people younger than 40 using JPA2 Tuples\");\n query = builder.is(\"age\").lessThan(40).query();\n \n // Use URI path component to capture the query expression\n wc.path(query);\n \n \n Collection<? extends PersonInfo> personInfos = wc.getCollection(PersonInfo.class);\n for (PersonInfo pi : personInfos) {\n \tSystem.out.println(\"ID : \" + pi.getId());\n }\n\n wc.close();\n }",
"static AbstractLazyPatchableTarget createPatchableTarget(final String name, final LayerPathConfig layer, final File metadata, final InstalledImage image) throws IOException {\n // patchable target\n return new AbstractLazyPatchableTarget() {\n\n @Override\n public InstalledImage getInstalledImage() {\n return image;\n }\n\n @Override\n public File getModuleRoot() {\n return layer.modulePath;\n }\n\n @Override\n public File getBundleRepositoryRoot() {\n return layer.bundlePath;\n }\n\n public File getPatchesMetadata() {\n return metadata;\n }\n\n @Override\n public String getName() {\n return name;\n }\n };\n }",
"public static sslcipher_individualcipher_binding[] get(nitro_service service, String ciphergroupname) throws Exception{\n\t\tsslcipher_individualcipher_binding obj = new sslcipher_individualcipher_binding();\n\t\tobj.set_ciphergroupname(ciphergroupname);\n\t\tsslcipher_individualcipher_binding response[] = (sslcipher_individualcipher_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static String createOdataFilterForTags(String tagName, String tagValue) {\n if (tagName == null) {\n return null;\n } else if (tagValue == null) {\n return String.format(\"tagname eq '%s'\", tagName);\n } else {\n return String.format(\"tagname eq '%s' and tagvalue eq '%s'\", tagName, tagValue);\n }\n }",
"static Shell createTelnetConsoleShell(String prompt, String appName,\n ShellCommandHandler mainHandler, InputStream input, OutputStream output) {\n try {\n // Set up nvt4j; ignore the initial clear & reposition\n final nvt4j.impl.Terminal nvt4jTerminal = new nvt4j.impl.Terminal(input, output) {\n private boolean cleared;\n private boolean moved;\n\n @Override\n public void clear() throws IOException {\n if (this.cleared)\n super.clear();\n this.cleared = true;\n }\n\n @Override\n public void move(int row, int col) throws IOException {\n if (this.moved)\n super.move(row, col);\n this.moved = true;\n }\n };\n nvt4jTerminal.put(nvt4j.impl.Terminal.AUTO_WRAP_ON);\n nvt4jTerminal.setCursor(true);\n\n // Have JLine do input & output through telnet terminal\n final InputStream jlineInput = new InputStream() {\n @Override\n public int read() throws IOException {\n return nvt4jTerminal.get();\n }\n };\n final OutputStream jlineOutput = new OutputStream() {\n @Override\n public void write(int value) throws IOException {\n nvt4jTerminal.put(value);\n }\n };\n\n return createTerminalConsoleShell(prompt, appName, mainHandler, jlineInput, jlineOutput);\n } catch (Exception e) {\n // Failover: use default shell\n BufferedReader in = new BufferedReader(new InputStreamReader(input));\n PrintStream out = new PrintStream(output);\n\n return createConsoleShell(prompt, appName, mainHandler, in, out, out, null);\n }\n }",
"public static final Date parseExtendedAttributeDate(String value)\n {\n Date result = null;\n\n if (value != null)\n {\n try\n {\n result = DATE_FORMAT.get().parse(value);\n }\n\n catch (ParseException ex)\n {\n // ignore exceptions\n }\n }\n\n return (result);\n }"
] |
Constructs a valid request and passes it on to the next handler. It also
creates the 'Store' object corresponding to the store name specified in
the REST request.
@param requestValidator The Validator object used to construct the
request object
@param ctx Context of the Netty channel
@param messageEvent Message Event used to write the response / exception | [
"@Override\n protected void registerRequest(RestRequestValidator requestValidator,\n ChannelHandlerContext ctx,\n MessageEvent messageEvent) {\n // At this point we know the request is valid and we have a\n // error handler. So we construct the composite Voldemort\n // request object.\n CompositeVoldemortRequest<ByteArray, byte[]> requestObject = requestValidator.constructCompositeVoldemortRequestObject();\n if(requestObject != null) {\n\n // Dropping dead requests from going to next handler\n long now = System.currentTimeMillis();\n if(requestObject.getRequestOriginTimeInMs() + requestObject.getRoutingTimeoutInMs() <= now) {\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.REQUEST_TIMEOUT,\n \"current time: \"\n + now\n + \"\\torigin time: \"\n + requestObject.getRequestOriginTimeInMs()\n + \"\\ttimeout in ms: \"\n + requestObject.getRoutingTimeoutInMs());\n return;\n } else {\n Store store = getStore(requestValidator.getStoreName(),\n requestValidator.getParsedRoutingType());\n if(store != null) {\n VoldemortStoreRequest voldemortStoreRequest = new VoldemortStoreRequest(requestObject,\n store,\n parseZoneId());\n Channels.fireMessageReceived(ctx, voldemortStoreRequest);\n } else {\n logger.error(\"Error when getting store. Non Existing store name.\");\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Non Existing store name. Critical error.\");\n return;\n\n }\n }\n }\n }"
] | [
"public static boolean hasPermission(Permission permission) {\n SecurityManager security = System.getSecurityManager();\n if (security != null) {\n try {\n security.checkPermission(permission);\n } catch (java.security.AccessControlException e) {\n return false;\n }\n }\n return true;\n }",
"public static Collection<Info> getPendingCollaborations(BoxAPIConnection api) {\n URL url = PENDING_COLLABORATIONS_URL.build(api.getBaseURL());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int entriesCount = responseJSON.get(\"total_count\").asInt();\n Collection<BoxCollaboration.Info> collaborations = new ArrayList<BoxCollaboration.Info>(entriesCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue entry : entries) {\n JsonObject entryObject = entry.asObject();\n BoxCollaboration collaboration = new BoxCollaboration(api, entryObject.get(\"id\").asString());\n BoxCollaboration.Info info = collaboration.new Info(entryObject);\n collaborations.add(info);\n }\n\n return collaborations;\n }",
"public static int[] randomSubset(int k, int n) {\n assert(0 < k && k <= n);\n Random r = new Random();\n int t = 0, m = 0;\n int[] result = new int[k];\n\n while (m < k) {\n double u = r.nextDouble();\n if ( (n - t) * u < k - m ) {\n result[m] = t;\n m++;\n }\n t++;\n }\n return result;\n }",
"public CollectionDescriptorDef getCollection(String name)\r\n {\r\n CollectionDescriptorDef collDef = null;\r\n\r\n for (Iterator it = _collections.iterator(); it.hasNext(); )\r\n {\r\n collDef = (CollectionDescriptorDef)it.next();\r\n if (collDef.getName().equals(name))\r\n {\r\n return collDef;\r\n }\r\n }\r\n return null;\r\n }",
"private void calculateMenuItemPosition() {\n\n float itemRadius = (expandedRadius + collapsedRadius) / 2, f;\n RectF area = new RectF(\n center.x - itemRadius,\n center.y - itemRadius,\n center.x + itemRadius,\n center.y + itemRadius);\n Path path = new Path();\n path.addArc(area, (float) fromAngle, (float) (toAngle - fromAngle));\n PathMeasure measure = new PathMeasure(path, false);\n float len = measure.getLength();\n int divisor = getChildCount();\n float divider = len / divisor;\n\n for (int i = 0; i < getChildCount(); i++) {\n float[] coords = new float[2];\n measure.getPosTan(i * divider + divider * .5f, coords, null);\n FilterMenu.Item item = (FilterMenu.Item) getChildAt(i).getTag();\n item.setX((int) coords[0] - item.getView().getMeasuredWidth() / 2);\n item.setY((int) coords[1] - item.getView().getMeasuredHeight() / 2);\n }\n }",
"private void processKnownType(FieldType type)\n {\n //System.out.println(\"Header: \" + type);\n //System.out.println(ByteArrayHelper.hexdump(m_data, m_dataOffset, 36, false, 16, \"\"));\n\n GraphicalIndicator indicator = m_container.getCustomField(type).getGraphicalIndicator();\n indicator.setFieldType(type);\n int flags = m_data[m_dataOffset];\n indicator.setProjectSummaryInheritsFromSummaryRows((flags & 0x08) != 0);\n indicator.setSummaryRowsInheritFromNonSummaryRows((flags & 0x04) != 0);\n indicator.setDisplayGraphicalIndicators((flags & 0x02) != 0);\n indicator.setShowDataValuesInToolTips((flags & 0x01) != 0);\n m_dataOffset += 20;\n\n int nonSummaryRowOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int summaryRowOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int projectSummaryOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int dataSize = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n //System.out.println(\"Data\");\n //System.out.println(ByteArrayHelper.hexdump(m_data, m_dataOffset, dataSize, false, 16, \"\"));\n\n int maxNonSummaryRowOffset = m_dataOffset + summaryRowOffset;\n int maxSummaryRowOffset = m_dataOffset + projectSummaryOffset;\n int maxProjectSummaryOffset = m_dataOffset + dataSize;\n\n m_dataOffset += nonSummaryRowOffset;\n\n while (m_dataOffset + 2 < maxNonSummaryRowOffset)\n {\n indicator.addNonSummaryRowCriteria(processCriteria(type));\n }\n\n while (m_dataOffset + 2 < maxSummaryRowOffset)\n {\n indicator.addSummaryRowCriteria(processCriteria(type));\n }\n\n while (m_dataOffset + 2 < maxProjectSummaryOffset)\n {\n indicator.addProjectSummaryCriteria(processCriteria(type));\n }\n }",
"private static int abs(int a) {\n if(a >= 0)\n return a;\n else if(a != Integer.MIN_VALUE)\n return -a;\n return Integer.MAX_VALUE;\n }",
"public void recordServerGroupResult(final String serverGroup, final boolean failed) {\n\n synchronized (this) {\n if (groups.contains(serverGroup)) {\n responseCount++;\n if (failed) {\n this.failed = true;\n }\n DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef(\"Recorded group result for '%s': failed = %s\",\n serverGroup, failed);\n notifyAll();\n }\n else {\n throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServerGroup(serverGroup);\n }\n }\n }",
"public void characters(char ch[], int start, int length)\r\n {\r\n if (m_CurrentString == null)\r\n m_CurrentString = new String(ch, start, length);\r\n else\r\n m_CurrentString += new String(ch, start, length);\r\n }"
] |
Converts the bytes that make up an internet address into the corresponding integer value to make
it easier to perform bit-masking operations on them.
@param address an address whose integer equivalent is desired
@return the integer corresponding to that address | [
"public static long addressToLong(InetAddress address) {\n long result = 0;\n for (byte element : address.getAddress()) {\n result = (result << 8) + unsign(element);\n }\n return result;\n }"
] | [
"public AsciiTable setPaddingTop(int paddingTop) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingTop(paddingTop);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static HttpResponse getResponse(String urls, HttpRequest request,\n HttpMethod method, int connectTimeoutMillis, int readTimeoutMillis) throws IOException {\n OutputStream out = null;\n InputStream content = null;\n HttpResponse response = null;\n HttpURLConnection httpConn = request\n .getHttpConnection(urls, method.name());\n httpConn.setConnectTimeout(connectTimeoutMillis);\n httpConn.setReadTimeout(readTimeoutMillis);\n\n try {\n httpConn.connect();\n if (null != request.getPayload() && request.getPayload().length > 0) {\n out = httpConn.getOutputStream();\n out.write(request.getPayload());\n }\n content = httpConn.getInputStream();\n response = new HttpResponse();\n parseHttpConn(response, httpConn, content);\n return response;\n } catch (SocketTimeoutException e) {\n throw e;\n } catch (IOException e) {\n content = httpConn.getErrorStream();\n response = new HttpResponse();\n parseHttpConn(response, httpConn, content);\n return response;\n } finally {\n if (content != null) {\n content.close();\n }\n httpConn.disconnect();\n }\n }",
"private List<Row> getTable(String name)\n {\n List<Row> result = m_tables.get(name);\n if (result == null)\n {\n result = Collections.emptyList();\n }\n return result;\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 String toDecodedString(final java.net.URI uri) {\n final String scheme = uri.getScheme();\n final String part = uri.getSchemeSpecificPart();\n if ((scheme == null)) {\n return part;\n }\n return ((scheme + \":\") + part);\n }",
"public Map<String, ImplT> convertToUnmodifiableMap(List<InnerT> innerList) {\n Map<String, ImplT> result = new HashMap<>();\n for (InnerT inner : innerList) {\n result.put(name(inner), impl(inner));\n }\n\n return Collections.unmodifiableMap(result);\n }",
"ProtectionDomain getProtectionDomainForProxy(ProtectionDomain domain) {\n if (domain.getCodeSource() == null) {\n // no codesource to cache on\n return create(domain);\n }\n ProtectionDomain proxyProtectionDomain = proxyProtectionDomains.get(domain.getCodeSource());\n if (proxyProtectionDomain == null) {\n // as this is not atomic create() may be called multiple times for the same domain\n // we ignore that\n proxyProtectionDomain = create(domain);\n ProtectionDomain existing = proxyProtectionDomains.putIfAbsent(domain.getCodeSource(), proxyProtectionDomain);\n if (existing != null) {\n proxyProtectionDomain = existing;\n }\n }\n return proxyProtectionDomain;\n }",
"private Client getClientFromResultSet(ResultSet result) throws Exception {\n Client client = new Client();\n client.setId(result.getInt(Constants.GENERIC_ID));\n client.setUUID(result.getString(Constants.CLIENT_CLIENT_UUID));\n client.setFriendlyName(result.getString(Constants.CLIENT_FRIENDLY_NAME));\n client.setProfile(ProfileService.getInstance().findProfile(result.getInt(Constants.GENERIC_PROFILE_ID)));\n client.setIsActive(result.getBoolean(Constants.CLIENT_IS_ACTIVE));\n client.setActiveServerGroup(result.getInt(Constants.CLIENT_ACTIVESERVERGROUP));\n return client;\n }",
"public void finished() throws Throwable {\n if( state == FINISHED ) {\n return;\n }\n\n State previousState = state;\n\n state = FINISHED;\n methodInterceptor.enableMethodInterception( false );\n\n try {\n if( previousState == STARTED ) {\n callFinishLifeCycleMethods();\n }\n } finally {\n listener.scenarioFinished();\n }\n }"
] |
This method is used to recreate the hierarchical structure of the
project file from scratch. The method sorts the list of all tasks,
then iterates through it creating the parent-child structure defined
by the outline level field. | [
"public void updateStructure()\n {\n if (size() > 1)\n {\n Collections.sort(this);\n m_projectFile.getChildTasks().clear();\n\n Task lastTask = null;\n int lastLevel = -1;\n boolean autoWbs = m_projectFile.getProjectConfig().getAutoWBS();\n boolean autoOutlineNumber = m_projectFile.getProjectConfig().getAutoOutlineNumber();\n\n for (Task task : this)\n {\n task.clearChildTasks();\n Task parent = null;\n if (!task.getNull())\n {\n int level = NumberHelper.getInt(task.getOutlineLevel());\n\n if (lastTask != null)\n {\n if (level == lastLevel || task.getNull())\n {\n parent = lastTask.getParentTask();\n level = lastLevel;\n }\n else\n {\n if (level > lastLevel)\n {\n parent = lastTask;\n }\n else\n {\n while (level <= lastLevel)\n {\n parent = lastTask.getParentTask();\n\n if (parent == null)\n {\n break;\n }\n\n lastLevel = NumberHelper.getInt(parent.getOutlineLevel());\n lastTask = parent;\n }\n }\n }\n }\n\n lastTask = task;\n lastLevel = level;\n\n if (autoWbs || task.getWBS() == null)\n {\n task.generateWBS(parent);\n }\n\n if (autoOutlineNumber)\n {\n task.generateOutlineNumber(parent);\n }\n }\n\n if (parent == null)\n {\n m_projectFile.getChildTasks().add(task);\n }\n else\n {\n parent.addChildTask(task);\n }\n }\n }\n }"
] | [
"private CmsSpellcheckingRequest parseJsonRequest(JSONObject jsonRequest) {\n\n final String id = jsonRequest.optString(JSON_ID);\n\n final JSONObject params = jsonRequest.optJSONObject(JSON_PARAMS);\n\n if (null == params) {\n LOG.debug(\"Invalid JSON request: No field \\\"params\\\" defined. \");\n return null;\n }\n final JSONArray words = params.optJSONArray(JSON_WORDS);\n final String lang = params.optString(JSON_LANG, LANG_DEFAULT);\n if (null == words) {\n LOG.debug(\"Invalid JSON request: No field \\\"words\\\" defined. \");\n return null;\n }\n\n // Convert JSON array to array of type String\n final List<String> wordsToCheck = new LinkedList<String>();\n for (int i = 0; i < words.length(); i++) {\n final String word = words.opt(i).toString();\n wordsToCheck.add(word);\n\n if (Character.isUpperCase(word.codePointAt(0))) {\n wordsToCheck.add(word.toLowerCase());\n }\n }\n\n return new CmsSpellcheckingRequest(wordsToCheck.toArray(new String[wordsToCheck.size()]), lang, id);\n }",
"public static void mergeReports(File reportOverall, File... reports) {\n SessionInfoStore infoStore = new SessionInfoStore();\n ExecutionDataStore dataStore = new ExecutionDataStore();\n boolean isCurrentVersionFormat = loadSourceFiles(infoStore, dataStore, reports);\n\n try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(reportOverall))) {\n Object visitor;\n if (isCurrentVersionFormat) {\n visitor = new ExecutionDataWriter(outputStream);\n } else {\n visitor = new org.jacoco.previous.core.data.ExecutionDataWriter(outputStream);\n }\n infoStore.accept((ISessionInfoVisitor) visitor);\n dataStore.accept((IExecutionDataVisitor) visitor);\n } catch (IOException e) {\n throw new IllegalStateException(String.format(\"Unable to write overall coverage report %s\", reportOverall.getAbsolutePath()), e);\n }\n }",
"public static double computeHouseholder(double []x , int xStart , int xEnd , double max , DScalar gamma ) {\n double tau = 0;\n for (int i = xStart; i < xEnd ; i++) {\n double val = x[i] /= max;\n tau += val*val;\n }\n tau = Math.sqrt(tau);\n if( x[xStart] < 0 ) {\n tau = -tau;\n }\n double u_0 = x[xStart] + tau;\n gamma.value = u_0/tau;\n x[xStart] = 1;\n for (int i = xStart+1; i < xEnd ; i++) {\n x[i] /= u_0;\n }\n\n return -tau*max;\n }",
"private long getTime(Date start1, Date end1, Date start2, Date end2)\n {\n long total = 0;\n\n if (start1 != null && end1 != null && start2 != null && end2 != null)\n {\n long start;\n long end;\n\n if (start1.getTime() < start2.getTime())\n {\n start = start2.getTime();\n }\n else\n {\n start = start1.getTime();\n }\n\n if (end1.getTime() < end2.getTime())\n {\n end = end1.getTime();\n }\n else\n {\n end = end2.getTime();\n }\n\n if (start < end)\n {\n total = end - start;\n }\n }\n\n return (total);\n }",
"public Set<String> getAttributeNames() {\n if (attributes == null) {\n return Collections.emptySet();\n } else {\n return Collections.unmodifiableSet(attributes.keySet());\n }\n }",
"public static final BigInteger printTimeUnit(TimeUnit value)\n {\n return (BigInteger.valueOf(value == null ? TimeUnit.DAYS.getValue() + 1 : value.getValue() + 1));\n }",
"public void setNewCenterColor(int color) {\n\t\tmCenterNewColor = color;\n\t\tmCenterNewPaint.setColor(color);\n\t\tif (mCenterOldColor == 0) {\n\t\t\tmCenterOldColor = color;\n\t\t\tmCenterOldPaint.setColor(color);\n\t\t}\n\t\tif (onColorChangedListener != null && color != oldChangedListenerColor ) {\n\t\t\tonColorChangedListener.onColorChanged(color);\n\t\t\toldChangedListenerColor = color;\n\t\t}\n\t\tinvalidate();\n\t}",
"private static void defineField(Map<String, FieldType> container, String name, FieldType type)\n {\n defineField(container, name, type, null);\n }",
"private static String getFileName(@Nullable final MapPrinter mapPrinter, final PJsonObject spec) {\n String fileName = spec.optString(Constants.OUTPUT_FILENAME_KEY);\n if (fileName != null) {\n return fileName;\n }\n\n if (mapPrinter != null) {\n final Configuration config = mapPrinter.getConfiguration();\n final String templateName = spec.getString(Constants.JSON_LAYOUT_KEY);\n\n final Template template = config.getTemplate(templateName);\n\n if (template.getOutputFilename() != null) {\n return template.getOutputFilename();\n }\n\n if (config.getOutputFilename() != null) {\n return config.getOutputFilename();\n }\n }\n return \"mapfish-print-report\";\n }"
] |
Stores all entries contained in the given map in the cache. | [
"public void putAll(Map<KEY, VALUE> mapDataToPut) {\n int targetSize = maxSize - mapDataToPut.size();\n if (maxSize > 0 && values.size() > targetSize) {\n evictToTargetSize(targetSize);\n }\n Set<Entry<KEY, VALUE>> entries = mapDataToPut.entrySet();\n for (Entry<KEY, VALUE> entry : entries) {\n put(entry.getKey(), entry.getValue());\n }\n }"
] | [
"public static base_response update(nitro_service client, nsip6 resource) throws Exception {\n\t\tnsip6 updateresource = new nsip6();\n\t\tupdateresource.ipv6address = resource.ipv6address;\n\t\tupdateresource.td = resource.td;\n\t\tupdateresource.nd = resource.nd;\n\t\tupdateresource.icmp = resource.icmp;\n\t\tupdateresource.vserver = resource.vserver;\n\t\tupdateresource.telnet = resource.telnet;\n\t\tupdateresource.ftp = resource.ftp;\n\t\tupdateresource.gui = resource.gui;\n\t\tupdateresource.ssh = resource.ssh;\n\t\tupdateresource.snmp = resource.snmp;\n\t\tupdateresource.mgmtaccess = resource.mgmtaccess;\n\t\tupdateresource.restrictaccess = resource.restrictaccess;\n\t\tupdateresource.state = resource.state;\n\t\tupdateresource.map = resource.map;\n\t\tupdateresource.dynamicrouting = resource.dynamicrouting;\n\t\tupdateresource.hostroute = resource.hostroute;\n\t\tupdateresource.ip6hostrtgw = resource.ip6hostrtgw;\n\t\tupdateresource.metric = resource.metric;\n\t\tupdateresource.vserverrhilevel = resource.vserverrhilevel;\n\t\tupdateresource.ospf6lsatype = resource.ospf6lsatype;\n\t\tupdateresource.ospfarea = resource.ospfarea;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static Class<?> loadClass(String classname, DataFormat<?> dataFormat) {\n\n // first try context classoader\n ClassLoader cl = Thread.currentThread().getContextClassLoader();\n if(cl != null) {\n LOG.tryLoadingClass(classname, cl);\n try {\n return cl.loadClass(classname);\n }\n catch(Exception e) {\n // ignore\n }\n }\n\n // else try the classloader which loaded the dataformat\n cl = dataFormat.getClass().getClassLoader();\n try {\n LOG.tryLoadingClass(classname, cl);\n return cl.loadClass(classname);\n }\n catch (ClassNotFoundException e) {\n throw LOG.classNotFound(classname, e);\n }\n\n }",
"protected String createGlobalStyle()\n {\n StringBuilder ret = new StringBuilder();\n ret.append(createFontFaces());\n ret.append(\"\\n\");\n ret.append(defaultStyle);\n return ret.toString();\n }",
"public static Result generate(@Nonnull final String code, @Nonnull final ImmutableSettings settings) {\n\t\tCheck.notNull(code, \"code\");\n\t\tfinal ImmutableSettings.Builder settingsBuilder = new ImmutableSettings.Builder(Check.notNull(settings, \"settings\"));\n\n\t\tfinal InterfaceAnalysis analysis = InterfaceAnalyzer.analyze(code);\n\t\tfinal Clazz clazz = scaffoldClazz(analysis, settings);\n\n\t\t// immutable settings\n\t\tsettingsBuilder.fields(clazz.getFields());\n\t\tsettingsBuilder.immutableName(clazz.getName());\n\t\tsettingsBuilder.imports(clazz.getImports());\n\t\tfinal Interface definition = new Interface(new Type(clazz.getPackage(), analysis.getInterfaceName(), GenericDeclaration.UNDEFINED));\n\t\tsettingsBuilder.mainInterface(definition);\n\t\tsettingsBuilder.interfaces(clazz.getInterfaces());\n\t\tsettingsBuilder.packageDeclaration(clazz.getPackage());\n\n\t\tfinal String implementationCode = SourceCodeFormatter.format(ImmutableObjectRenderer.toString(clazz, settingsBuilder.build()));\n\t\tfinal String testCode = SourceCodeFormatter.format(ImmutableObjectTestRenderer.toString(clazz, settingsBuilder.build()));\n\t\treturn new Result(implementationCode, testCode);\n\t}",
"@PostConstruct\n public final void init() {\n this.cleanUpTimer = Executors.newScheduledThreadPool(1, timerTask -> {\n final Thread thread = new Thread(timerTask, \"Clean up old job records\");\n thread.setDaemon(true);\n return thread;\n });\n this.cleanUpTimer.scheduleAtFixedRate(this::cleanup, this.cleanupInterval, this.cleanupInterval,\n TimeUnit.SECONDS);\n }",
"private FieldType getFieldType(byte[] data, int offset)\n {\n int fieldIndex = MPPUtility.getInt(data, offset);\n return FieldTypeHelper.mapTextFields(FieldTypeHelper.getInstance14(fieldIndex));\n }",
"private static String getHostname() {\n if (Hostname == null) {\n try {\n Hostname = InetAddress.getLocalHost().getHostName();\n } catch (Exception e) {\n Hostname = \"default\";\n LOGGER.warn(\"Can not get current hostname\", e);\n }\n }\n return Hostname;\n }",
"public static double JaccardDistance(double[] p, double[] q) {\n double distance = 0;\n int intersection = 0, union = 0;\n\n for (int x = 0; x < p.length; x++) {\n if ((p[x] != 0) || (q[x] != 0)) {\n if (p[x] == q[x]) {\n intersection++;\n }\n\n union++;\n }\n }\n\n if (union != 0)\n distance = 1.0 - ((double) intersection / (double) union);\n else\n distance = 0;\n\n return distance;\n }",
"private boolean isEqual(FieldDescriptorDef first, FieldDescriptorDef second)\r\n {\r\n return first.getName().equals(second.getName()) &&\r\n first.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN).equals(second.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN)) &&\r\n first.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE).equals(second.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n }"
] |
Get the domain controller data from the given byte buffer.
@param buffer the byte buffer
@return the domain controller data
@throws Exception | [
"public static List<DomainControllerData> domainControllerDataFromByteBuffer(byte[] buffer) throws Exception {\n List<DomainControllerData> retval = new ArrayList<DomainControllerData>();\n if (buffer == null) {\n return retval;\n }\n ByteArrayInputStream in_stream = new ByteArrayInputStream(buffer);\n DataInputStream in = new DataInputStream(in_stream);\n String content = SEPARATOR;\n while (SEPARATOR.equals(content)) {\n DomainControllerData data = new DomainControllerData();\n data.readFrom(in);\n retval.add(data);\n try {\n content = readString(in);\n } catch (EOFException ex) {\n content = null;\n }\n }\n in.close();\n return retval;\n }"
] | [
"public Bundler put(String key, CharSequence value) {\n delegate.putCharSequence(key, value);\n return this;\n }",
"public static base_response add(nitro_service client, policydataset resource) throws Exception {\n\t\tpolicydataset addresource = new policydataset();\n\t\taddresource.name = resource.name;\n\t\taddresource.type = resource.type;\n\t\taddresource.indextype = resource.indextype;\n\t\treturn addresource.add_resource(client);\n\t}",
"private String getClassNameFromPath(String path) {\n String className = path.replace(\".class\", \"\");\n\n // for *nix\n if (className.startsWith(\"/\")) {\n className = className.substring(1, className.length());\n }\n className = className.replace(\"/\", \".\");\n\n // for windows\n if (className.startsWith(\"\\\\\")) {\n className = className.substring(1, className.length());\n }\n className = className.replace(\"\\\\\", \".\");\n\n return className;\n }",
"private void processCalendarHours(ProjectCalendar calendar, Record dayRecord)\n {\n // ... for each day of the week\n Day day = Day.getInstance(Integer.parseInt(dayRecord.getField()));\n // Get hours\n List<Record> recHours = dayRecord.getChildren();\n if (recHours.size() == 0)\n {\n // No data -> not working\n calendar.setWorkingDay(day, false);\n }\n else\n {\n calendar.setWorkingDay(day, true);\n // Read hours\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n for (Record recWorkingHours : recHours)\n {\n addHours(hours, recWorkingHours);\n }\n }\n }",
"public ContentAssistEntry createProposal(final String proposal, final String prefix, final ContentAssistContext context, final String kind, final Procedure1<? super ContentAssistEntry> init) {\n boolean _isValidProposal = this.isValidProposal(proposal, prefix, context);\n if (_isValidProposal) {\n final ContentAssistEntry result = new ContentAssistEntry();\n result.setProposal(proposal);\n result.setPrefix(prefix);\n if ((kind != null)) {\n result.setKind(kind);\n }\n if ((init != null)) {\n init.apply(result);\n }\n return result;\n }\n return null;\n }",
"@Override\n public Object[] getAgentPlans(String agent_name, Connector connector) {\n // Not supported in JADE\n connector.getLogger().warning(\"Non suported method for Jade Platform. There is no plans in Jade platform.\");\n throw new java.lang.UnsupportedOperationException(\"Non suported method for Jade Platform. There is no extra properties.\");\n }",
"public BufferedImage toNewBufferedImage(int type) {\n BufferedImage target = new BufferedImage(width, height, type);\n Graphics2D g2 = (Graphics2D) target.getGraphics();\n g2.drawImage(awt, 0, 0, null);\n g2.dispose();\n return target;\n }",
"public static base_response update(nitro_service client, inat resource) throws Exception {\n\t\tinat updateresource = new inat();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.privateip = resource.privateip;\n\t\tupdateresource.tcpproxy = resource.tcpproxy;\n\t\tupdateresource.ftp = resource.ftp;\n\t\tupdateresource.tftp = resource.tftp;\n\t\tupdateresource.usip = resource.usip;\n\t\tupdateresource.usnip = resource.usnip;\n\t\tupdateresource.proxyip = resource.proxyip;\n\t\tupdateresource.mode = resource.mode;\n\t\treturn updateresource.update_resource(client);\n\t}",
"int add(DownloadRequest request) {\n\t\tint downloadId = getDownloadId();\n\t\t// Tag the request as belonging to this queue and add it to the set of current requests.\n\t\trequest.setDownloadRequestQueue(this);\n\n\t\tsynchronized (mCurrentRequests) {\n\t\t\tmCurrentRequests.add(request);\n\t\t}\n\n\t\t// Process requests in the order they are added.\n\t\trequest.setDownloadId(downloadId);\n\t\tmDownloadQueue.add(request);\n\n\t\treturn downloadId;\n\t}"
] |
Convert an Object to a Time. | [
"public static java.sql.Time toTime(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.sql.Time) {\n return (java.sql.Time) value;\n }\n if (value instanceof String) {\n if (\"\".equals((String) value)) {\n return null;\n }\n return new java.sql.Time(IN_TIME_FORMAT.parse((String) value).getTime());\n }\n\n return new java.sql.Time(IN_TIME_FORMAT.parse(value.toString()).getTime());\n }"
] | [
"@SuppressWarnings(\"SameParameterValue\")\n public static long bytesToNumberLittleEndian(byte[] buffer, int start, int length) {\n long result = 0;\n for (int index = start + length - 1; index >= start; index--) {\n result = (result << 8) + unsign(buffer[index]);\n }\n return result;\n }",
"public static Cluster vacateZone(Cluster currentCluster, int dropZoneId) {\n Cluster returnCluster = Cluster.cloneCluster(currentCluster);\n // Go over each node in the zone being dropped\n for(Integer nodeId: currentCluster.getNodeIdsInZone(dropZoneId)) {\n // For each node grab all the partitions it hosts\n for(Integer partitionId: currentCluster.getNodeById(nodeId).getPartitionIds()) {\n // Now for each partition find a new home..which would be a node\n // in one of the existing zones\n int finalZoneId = -1;\n int finalNodeId = -1;\n int adjacentPartitionId = partitionId;\n do {\n adjacentPartitionId = (adjacentPartitionId + 1)\n % currentCluster.getNumberOfPartitions();\n finalNodeId = currentCluster.getNodeForPartitionId(adjacentPartitionId).getId();\n finalZoneId = currentCluster.getZoneForPartitionId(adjacentPartitionId).getId();\n if(adjacentPartitionId == partitionId) {\n logger.error(\"PartitionId \" + partitionId + \"stays unchanged \\n\");\n } else {\n logger.info(\"PartitionId \" + partitionId\n + \" goes together with partition \" + adjacentPartitionId\n + \" on node \" + finalNodeId + \" in zone \" + finalZoneId);\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n finalNodeId,\n Lists.newArrayList(partitionId));\n }\n } while(finalZoneId == dropZoneId);\n }\n }\n return returnCluster;\n }",
"public void setCategoryDisplayOptions(\n String displayCategoriesByRepository,\n String displayCategorySelectionCollapsed) {\n\n m_displayCategoriesByRepository = Boolean.parseBoolean(displayCategoriesByRepository);\n m_displayCategorySelectionCollapsed = Boolean.parseBoolean(displayCategorySelectionCollapsed);\n }",
"public VectorClock incremented(int nodeId, long time) {\n VectorClock copyClock = this.clone();\n copyClock.incrementVersion(nodeId, time);\n return copyClock;\n }",
"public static int cudnnReduceTensor(\n cudnnHandle handle, \n cudnnReduceTensorDescriptor reduceTensorDesc, \n Pointer indices, \n long indicesSizeInBytes, \n Pointer workspace, \n long workspaceSizeInBytes, \n Pointer alpha, \n cudnnTensorDescriptor aDesc, \n Pointer A, \n Pointer beta, \n cudnnTensorDescriptor cDesc, \n Pointer C)\n {\n return checkResult(cudnnReduceTensorNative(handle, reduceTensorDesc, indices, indicesSizeInBytes, workspace, workspaceSizeInBytes, alpha, aDesc, A, beta, cDesc, C));\n }",
"public static void initialize(final Context context) {\n if (!initialized.compareAndSet(false, true)) {\n return;\n }\n\n applicationContext = context.getApplicationContext();\n\n final String packageName = applicationContext.getPackageName();\n localAppName = packageName;\n\n final PackageManager manager = applicationContext.getPackageManager();\n try {\n final PackageInfo pkgInfo = manager.getPackageInfo(packageName, 0);\n localAppVersion = pkgInfo.versionName;\n } catch (final NameNotFoundException e) {\n Log.d(TAG, \"Failed to get version of application, will not send in device info.\");\n }\n\n Log.d(TAG, \"Initialized android SDK\");\n }",
"@Override\n public void process(Step step) {\n step.setName(getName());\n step.setStatus(Status.PASSED);\n step.setStart(System.currentTimeMillis());\n step.setTitle(getTitle());\n }",
"public FormAction setValuesInForm(Form form) {\r\n\t\tFormAction formAction = new FormAction();\r\n\t\tform.setFormAction(formAction);\r\n\t\tthis.forms.add(form);\r\n\t\treturn formAction;\r\n\t}",
"@SuppressWarnings(\"unused\")\n public void selectItem(int position, boolean invokeListeners) {\n IOperationItem item = mOuterAdapter.getItem(position);\n IOperationItem oldHidedItem = mOuterAdapter.getItem(mRealHidedPosition);\n\n int realPosition = mOuterAdapter.normalizePosition(position);\n //do nothing if position not changed\n if (realPosition == mCurrentItemPosition) {\n return;\n }\n int itemToShowAdapterPosition = position - realPosition + mRealHidedPosition;\n\n item.setVisible(false);\n\n startSelectedViewOutAnimation(position);\n\n mOuterAdapter.notifyRealItemChanged(position);\n mRealHidedPosition = realPosition;\n\n oldHidedItem.setVisible(true);\n mFlContainerSelected.requestLayout();\n mOuterAdapter.notifyRealItemChanged(itemToShowAdapterPosition);\n mCurrentItemPosition = realPosition;\n\n if (invokeListeners) {\n notifyItemClickListeners(realPosition);\n }\n\n if (BuildConfig.DEBUG) {\n Log.i(TAG, \"clicked on position =\" + position);\n }\n\n }"
] |
Read the set of property files. Keys and Values are automatically validated and converted.
@param resourceLoader
@return all the properties from the weld.properties file | [
"@SuppressFBWarnings(value = \"DMI_COLLECTION_OF_URLS\", justification = \"Only local URLs involved\")\n private Map<ConfigurationKey, Object> readFileProperties(Set<URL> files) {\n Map<ConfigurationKey, Object> found = new EnumMap<ConfigurationKey, Object>(ConfigurationKey.class);\n for (URL file : files) {\n ConfigurationLogger.LOG.readingPropertiesFile(file);\n Properties fileProperties = loadProperties(file);\n for (String name : fileProperties.stringPropertyNames()) {\n processKeyValue(found, name, fileProperties.getProperty(name));\n }\n }\n return found;\n }"
] | [
"public static String readTag(Reader r) throws IOException {\r\n if ( ! r.ready()) {\r\n return null;\r\n }\r\n StringBuilder b = new StringBuilder(\"<\");\r\n int c = r.read();\r\n while (c >= 0) {\r\n b.append((char) c);\r\n if (c == '>') {\r\n break;\r\n }\r\n c = r.read();\r\n }\r\n if (b.length() == 1) {\r\n return null;\r\n }\r\n return b.toString();\r\n }",
"public static String insertDumpInformation(String pattern,\n\t\t\tString dateStamp, String project) {\n\t\tif (pattern == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn pattern.replace(\"{DATE}\", dateStamp).replace(\"{PROJECT}\",\n\t\t\t\t\tproject);\n\t\t}\n\t}",
"PollingState<T> withStatus(String status, int statusCode) throws IllegalArgumentException {\n if (status == null) {\n throw new IllegalArgumentException(\"Status is null.\");\n }\n this.status = status;\n this.statusCode = statusCode;\n return this;\n }",
"@SuppressWarnings(\"deprecation\")\n public ResponseFromManager sendTaskToExecutionManager(ParallelTask task) {\n\n ResponseFromManager commandResponseFromManager = null;\n ActorRef executionManager = null;\n try {\n // Start new job\n logger.info(\"!!STARTED sendAgentCommandToManager : \"\n + task.getTaskId() + \" at \"\n + PcDateUtils.getNowDateTimeStr());\n\n executionManager = ActorConfig.createAndGetActorSystem().actorOf(\n Props.create(ExecutionManager.class, task),\n \"ExecutionManager-\" + task.getTaskId());\n\n final FiniteDuration duration = Duration.create(task.getConfig()\n .getTimeoutAskManagerSec(), TimeUnit.SECONDS);\n // Timeout timeout = new\n // Timeout(FiniteDuration.parse(\"300 seconds\"));\n Future<Object> future = Patterns.ask(executionManager,\n new InitialRequestToManager(task), new Timeout(duration));\n\n // set ref\n task.executionManager = executionManager;\n\n commandResponseFromManager = (ResponseFromManager) Await.result(\n future, duration);\n\n logger.info(\"!!COMPLETED sendTaskToExecutionManager : \"\n + task.getTaskId() + \" at \"\n + PcDateUtils.getNowDateTimeStr()\n + \" \\t\\t GenericResponseMap in future size: \"\n + commandResponseFromManager.getResponseCount());\n\n } catch (Exception ex) {\n logger.error(\"Exception in sendTaskToExecutionManager {} details {}: \",\n ex, ex);\n\n } finally {\n // stop the manager\n if (executionManager != null && !executionManager.isTerminated()) {\n ActorConfig.createAndGetActorSystem().stop(executionManager);\n }\n\n if (task.getConfig().isAutoSaveLogToLocal()) {\n task.saveLogToLocal();\n }\n\n }\n\n return commandResponseFromManager;\n\n }",
"public static service_dospolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tservice_dospolicy_binding obj = new service_dospolicy_binding();\n\t\tobj.set_name(name);\n\t\tservice_dospolicy_binding response[] = (service_dospolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public DescriptorRepository readDescriptorRepository(InputStream inst)\r\n {\r\n try\r\n {\r\n RepositoryPersistor persistor = new RepositoryPersistor();\r\n return persistor.readDescriptorRepository(inst);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\"Can not read repository \" + inst, e);\r\n }\r\n }",
"@Value(\"${locator.strategy}\")\n public void setDefaultLocatorSelectionStrategy(String defaultLocatorSelectionStrategy) {\n this.defaultLocatorSelectionStrategy = defaultLocatorSelectionStrategy;\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Default strategy \" + defaultLocatorSelectionStrategy\n + \" was set for LocatorClientRegistrar.\");\n }\n }",
"public void readFrom(IIMReader reader, int recover) throws IOException, InvalidDataSetException {\r\n\t\tfinal boolean doLog = log != null;\r\n\t\tfor (;;) {\r\n\t\t\ttry {\r\n\t\t\t\tDataSet ds = reader.read();\r\n\t\t\t\tif (ds == null) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (doLog) {\r\n\t\t\t\t\tlog.debug(\"Read data set \" + ds);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tDataSetInfo info = ds.getInfo();\r\n\t\t\t\tSerializer s = info.getSerializer();\r\n\t\t\t\tif (s != null) {\r\n\t\t\t\t\tif (info.getDataSetNumber() == IIM.DS(1, 90)) {\r\n\t\t\t\t\t\tsetCharacterSet((String) s.deserialize(ds.getData(), activeSerializationContext));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tdataSets.add(ds);\r\n\r\n\t\t\t\tif (stopAfter9_10 && info.getDataSetNumber() == IIM.DS(9, 10))\r\n\t\t\t\t\tbreak;\r\n\t\t\t} catch (IIMFormatException e) {\r\n\t\t\t\tif (recoverFromIIMFormat && recover-- > 0) {\r\n\t\t\t\t\tboolean r = reader.recover();\r\n\t\t\t\t\tif (doLog) {\r\n\t\t\t\t\t\tlog.debug(r ? \"Recoved from \" + e : \"Failed to recover from \" + e);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (!r)\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t} catch (UnsupportedDataSetException e) {\r\n\t\t\t\tif (recoverFromUnsupportedDataSet && recover-- > 0) {\r\n\t\t\t\t\tboolean r = reader.recover();\r\n\t\t\t\t\tif (doLog) {\r\n\t\t\t\t\t\tlog.debug(r ? \"Recoved from \" + e : \"Failed to recover from \" + e);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (!r)\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t} catch (InvalidDataSetException e) {\r\n\t\t\t\tif (recoverFromInvalidDataSet && recover-- > 0) {\r\n\t\t\t\t\tboolean r = reader.recover();\r\n\t\t\t\t\tif (doLog) {\r\n\t\t\t\t\t\tlog.debug(r ? \"Recoved from \" + e : \"Failed to recover from \" + e);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (!r)\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\tif (recover-- > 0 && !dataSets.isEmpty()) {\r\n\t\t\t\t\tif (doLog) {\r\n\t\t\t\t\t\tlog.error(\"IOException while reading, however some data sets where recovered, \" + e);\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"public void setCastShadow(boolean enableFlag)\n {\n GVRSceneObject owner = getOwnerObject();\n\n if (owner != null)\n {\n GVRShadowMap shadowMap = (GVRShadowMap) getComponent(GVRRenderTarget.getComponentType());\n if (enableFlag)\n {\n if (shadowMap != null)\n {\n shadowMap.setEnable(true);\n }\n else\n {\n GVRCamera shadowCam = GVRShadowMap.makeOrthoShadowCamera(\n getGVRContext().getMainScene().getMainCameraRig().getCenterCamera());\n shadowMap = new GVRShadowMap(getGVRContext(), shadowCam);\n owner.attachComponent(shadowMap);\n }\n }\n else if (shadowMap != null)\n {\n shadowMap.setEnable(false);\n }\n }\n mCastShadow = enableFlag;\n }"
] |
Formats event output by key, usually equal to the method name.
@param key the event key
@param defaultPattern the default pattern to return if a custom pattern
is not found
@param args the args used to format output
@return A formatted event output | [
"protected String format(String key, String defaultPattern, Object... args) {\n String escape = escape(defaultPattern);\n String s = lookupPattern(key, escape);\n Object[] objects = escapeAll(args);\n return MessageFormat.format(s, objects);\n }"
] | [
"public synchronized int get(byte[] dst, int off, int len) {\n if (available == 0) {\n return 0;\n }\n\n // limit is last index to read + 1\n int limit = idxGet < idxPut ? idxPut : capacity;\n int count = Math.min(limit - idxGet, len);\n System.arraycopy(buffer, idxGet, dst, off, count);\n idxGet += count;\n\n if (idxGet == capacity) {\n // Array end reached, check if we have more\n int count2 = Math.min(len - count, idxPut);\n if (count2 > 0) {\n System.arraycopy(buffer, 0, dst, off + count, count2);\n idxGet = count2;\n count += count2;\n } else {\n idxGet = 0;\n }\n }\n available -= count;\n return count;\n }",
"private Client getClient(){\n final ClientConfig cfg = new DefaultClientConfig();\n cfg.getClasses().add(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider.class);\n cfg.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, timeout);\n\n return Client.create(cfg);\n }",
"private void populateExpandedExceptions()\n {\n if (!m_exceptions.isEmpty() && m_expandedExceptions.isEmpty())\n {\n for (ProjectCalendarException exception : m_exceptions)\n {\n RecurringData recurring = exception.getRecurring();\n if (recurring == null)\n {\n m_expandedExceptions.add(exception);\n }\n else\n {\n for (Date date : recurring.getDates())\n {\n Date startDate = DateHelper.getDayStartDate(date);\n Date endDate = DateHelper.getDayEndDate(date);\n ProjectCalendarException newException = new ProjectCalendarException(startDate, endDate);\n int rangeCount = exception.getRangeCount();\n for (int rangeIndex = 0; rangeIndex < rangeCount; rangeIndex++)\n {\n newException.addRange(exception.getRange(rangeIndex));\n }\n m_expandedExceptions.add(newException);\n }\n }\n }\n Collections.sort(m_expandedExceptions);\n }\n }",
"@Override\n public CopticDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"public static double StdDev( int[] values, double mean ){\n double stddev = 0;\n double diff;\n int hits;\n int total = 0;\n\n // for all values\n for ( int i = 0, n = values.length; i < n; i++ )\n {\n hits = values[i];\n diff = (double) i - mean;\n // accumulate std.dev.\n stddev += diff * diff * hits;\n // accumalate total\n total += hits;\n }\n\n return ( total == 0 ) ? 0 : Math.sqrt( stddev / (total - 1) );\n }",
"public static boolean check(String passwd, String hashed) {\n try {\n String[] parts = hashed.split(\"\\\\$\");\n\n if (parts.length != 5 || !parts[1].equals(\"s0\")) {\n throw new IllegalArgumentException(\"Invalid hashed value\");\n }\n\n long params = Long.parseLong(parts[2], 16);\n byte[] salt = decode(parts[3].toCharArray());\n byte[] derived0 = decode(parts[4].toCharArray());\n\n int N = (int) Math.pow(2, params >> 16 & 0xffff);\n int r = (int) params >> 8 & 0xff;\n int p = (int) params & 0xff;\n\n byte[] derived1 = SCrypt.scrypt(passwd.getBytes(\"UTF-8\"), salt, N, r, p, 32);\n\n if (derived0.length != derived1.length) return false;\n\n int result = 0;\n for (int i = 0; i < derived0.length; i++) {\n result |= derived0[i] ^ derived1[i];\n }\n return result == 0;\n } catch (UnsupportedEncodingException e) {\n throw new IllegalStateException(\"JVM doesn't support UTF-8?\");\n } catch (GeneralSecurityException e) {\n throw new IllegalStateException(\"JVM doesn't support SHA1PRNG or HMAC_SHA256?\");\n }\n }",
"private String getTypeString(Class<?> c)\n {\n String result = TYPE_MAP.get(c);\n if (result == null)\n {\n result = c.getName();\n if (!result.endsWith(\";\") && !result.startsWith(\"[\"))\n {\n result = \"L\" + result + \";\";\n }\n }\n return result;\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}",
"private static String decode(String s) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n for (int i = 0; i < s.length(); i++) {\n char ch = s.charAt(i);\n if (ch == '%') {\n baos.write(hexToInt(s.charAt(i + 1)) * 16 + hexToInt(s.charAt(i + 2)));\n i += 2;\n continue;\n }\n baos.write(ch);\n }\n try {\n return new String(baos.toByteArray(), \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw new Error(e); // impossible\n }\n }"
] |
Returns all ApplicationProjectModels. | [
"private static Set<ProjectModel> getAllApplications(GraphContext graphContext)\n {\n Set<ProjectModel> apps = new HashSet<>();\n Iterable<ProjectModel> appProjects = graphContext.findAll(ProjectModel.class);\n for (ProjectModel appProject : appProjects)\n apps.add(appProject);\n return apps;\n }"
] | [
"public static boolean check(String passwd, String hashed) {\n try {\n String[] parts = hashed.split(\"\\\\$\");\n\n if (parts.length != 5 || !parts[1].equals(\"s0\")) {\n throw new IllegalArgumentException(\"Invalid hashed value\");\n }\n\n long params = Long.parseLong(parts[2], 16);\n byte[] salt = decode(parts[3].toCharArray());\n byte[] derived0 = decode(parts[4].toCharArray());\n\n int N = (int) Math.pow(2, params >> 16 & 0xffff);\n int r = (int) params >> 8 & 0xff;\n int p = (int) params & 0xff;\n\n byte[] derived1 = SCrypt.scrypt(passwd.getBytes(\"UTF-8\"), salt, N, r, p, 32);\n\n if (derived0.length != derived1.length) return false;\n\n int result = 0;\n for (int i = 0; i < derived0.length; i++) {\n result |= derived0[i] ^ derived1[i];\n }\n return result == 0;\n } catch (UnsupportedEncodingException e) {\n throw new IllegalStateException(\"JVM doesn't support UTF-8?\");\n } catch (GeneralSecurityException e) {\n throw new IllegalStateException(\"JVM doesn't support SHA1PRNG or HMAC_SHA256?\");\n }\n }",
"public static final Duration parseDuration(String value)\n {\n return value == null ? null : Duration.getInstance(Double.parseDouble(value), TimeUnit.DAYS);\n }",
"private CmsMessageBundleEditorTypes.BundleType initBundleType() {\n\n String resourceTypeName = OpenCms.getResourceManager().getResourceType(m_resource).getTypeName();\n return CmsMessageBundleEditorTypes.BundleType.toBundleType(resourceTypeName);\n }",
"protected void animateOffsetTo(int position, int velocity, boolean animate) {\n endDrag();\n endPeek();\n\n final int startX = (int) mOffsetPixels;\n final int dx = position - startX;\n if (dx == 0 || !animate) {\n setOffsetPixels(position);\n setDrawerState(position == 0 ? STATE_CLOSED : STATE_OPEN);\n stopLayerTranslation();\n return;\n }\n\n int duration;\n\n velocity = Math.abs(velocity);\n if (velocity > 0) {\n duration = 4 * Math.round(1000.f * Math.abs((float) dx / velocity));\n } else {\n duration = (int) (600.f * Math.abs((float) dx / mMenuSize));\n }\n\n duration = Math.min(duration, mMaxAnimationDuration);\n animateOffsetTo(position, duration);\n }",
"public static base_responses update(nitro_service client, snmpuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpuser updateresources[] = new snmpuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new snmpuser();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].group = resources[i].group;\n\t\t\t\tupdateresources[i].authtype = resources[i].authtype;\n\t\t\t\tupdateresources[i].authpasswd = resources[i].authpasswd;\n\t\t\t\tupdateresources[i].privtype = resources[i].privtype;\n\t\t\t\tupdateresources[i].privpasswd = resources[i].privpasswd;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public Integer getNodesPartitionIdForKey(int nodeId, final byte[] key) {\n // this is all the partitions the key replicates to.\n List<Integer> partitionIds = getReplicatingPartitionList(key);\n for(Integer partitionId: partitionIds) {\n // check which of the replicating partitions belongs to the node in\n // question\n if(getNodeIdForPartitionId(partitionId) == nodeId) {\n return partitionId;\n }\n }\n return null;\n }",
"public boolean removeChildObjectByName(final String name) {\n if (null != name && !name.isEmpty()) {\n GVRSceneObject found = null;\n for (GVRSceneObject child : mChildren) {\n GVRSceneObject object = child.getSceneObjectByName(name);\n if (object != null) {\n found = object;\n break;\n }\n }\n if (found != null) {\n removeChildObject(found);\n return true;\n }\n }\n return false;\n }",
"public ResponseOnSingeRequest genErrorResponse(Exception t) {\n ResponseOnSingeRequest sshResponse = new ResponseOnSingeRequest();\n String displayError = PcErrorMsgUtils.replaceErrorMsg(t.toString());\n\n sshResponse.setStackTrace(PcStringUtils.printStackTrace(t));\n sshResponse.setErrorMessage(displayError);\n sshResponse.setFailObtainResponse(true);\n\n logger.error(\"error in exec SSH. \\nIf exection is JSchException: \"\n + \"Auth cancel and using public key. \"\n + \"\\nMake sure 1. private key full path is right (try sshMeta.getPrivKeyAbsPath()). \"\n + \"\\n2. the user name and key matches \" + t);\n\n return sshResponse;\n }",
"public void setSpecificDeviceClass(Specific specificDeviceClass) throws IllegalArgumentException {\r\n\t\t\r\n\t\t// The specific Device class does not match the generic device class.\r\n\t\tif (specificDeviceClass.genericDeviceClass != Generic.NOT_KNOWN && \r\n\t\t\t\tspecificDeviceClass.genericDeviceClass != this.genericDeviceClass)\r\n\t\t\tthrow new IllegalArgumentException(\"specificDeviceClass\");\r\n\t\t\r\n\t\tthis.specificDeviceClass = specificDeviceClass;\r\n\t}"
] |
we have only one implementation on classpath. | [
"private static Constraint loadConstraint(Annotation context) {\n Constraint constraint = null;\n final ServiceLoader<Constraint> constraints = ServiceLoader.load(Constraint.class);\n\n for (Constraint aConstraint : constraints) {\n try {\n aConstraint.getClass().getDeclaredMethod(\"check\", context.annotationType());\n constraint = aConstraint;\n break;\n } catch (NoSuchMethodException e) {\n // Look for next implementation if method not found with required signature.\n }\n }\n\n if (constraint == null) {\n throw new IllegalStateException(\"Couldn't found any implementation of \" + Constraint.class.getName());\n }\n return constraint;\n }"
] | [
"public float getPositionX(int vertex) {\n if (!hasPositions()) {\n throw new IllegalStateException(\"mesh has no positions\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_vertices.getFloat(vertex * 3 * SIZEOF_FLOAT);\n }",
"public static void setTranslucentStatusFlag(Activity activity, boolean on) {\n if (Build.VERSION.SDK_INT >= 19) {\n setFlag(activity, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, on);\n }\n }",
"public void sendFaderStartCommand(Set<Integer> deviceNumbersToStart, Set<Integer> deviceNumbersToStop) throws IOException {\n ensureRunning();\n byte[] payload = new byte[FADER_START_PAYLOAD.length];\n System.arraycopy(FADER_START_PAYLOAD, 0, payload, 0, FADER_START_PAYLOAD.length);\n payload[2] = getDeviceNumber();\n\n for (int i = 1; i <= 4; i++) {\n if (deviceNumbersToStart.contains(i)) {\n payload[i + 4] = 0;\n }\n if (deviceNumbersToStop.contains(i)) {\n payload[i + 4] = 1;\n }\n }\n\n assembleAndSendPacket(Util.PacketType.FADER_START_COMMAND, payload, getBroadcastAddress(), BeatFinder.BEAT_PORT);\n }",
"public void addProcedure(ProcedureDef procDef)\r\n {\r\n procDef.setOwner(this);\r\n _procedures.put(procDef.getName(), procDef);\r\n }",
"public T addFile(final String name, final List<String> path, final byte[] newHash, final boolean isDirectory) {\n return addFile(name, path, newHash, isDirectory, null);\n }",
"public Map<AssociationKey, Map<RowKey, Map<String, Object>>> getAssociationsMap() {\n\t\treturn Collections.unmodifiableMap( associationsKeyValueStorage );\n\t}",
"public synchronized int get() {\n if (available == 0) {\n return -1;\n }\n byte value = buffer[idxGet];\n idxGet = (idxGet + 1) % capacity;\n available--;\n return value;\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 float getLayoutSize(final Layout.Axis axis) {\n float size = 0;\n for (Layout layout : mLayouts) {\n size = Math.max(size, layout.getSize(axis));\n }\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"getLayoutSize [%s] axis [%s] size [%f]\", getName(), axis, size);\n return size;\n }"
] |
Returns a string describing 'time' as a time relative to 'now'.
See {@link android.text.format.DateUtils#getRelativeTimeSpanString} for full docs.
@param context the context
@param time the time to describe
@param flags a bit mask for formatting options, usually FORMAT_ABBREV_RELATIVE
@return a string describing 'time' as a time relative to 'now'. | [
"public static CharSequence getRelativeTimeSpanString(Context context, ReadableInstant time, int flags) {\n boolean abbrevRelative = (flags & (FORMAT_ABBREV_RELATIVE | FORMAT_ABBREV_ALL)) != 0;\n\n // We set the millis to 0 so we aren't off by a fraction of a second when counting intervals\n DateTime now = DateTime.now(time.getZone()).withMillisOfSecond(0);\n DateTime timeDt = new DateTime(time).withMillisOfSecond(0);\n boolean past = !now.isBefore(timeDt);\n Interval interval = past ? new Interval(timeDt, now) : new Interval(now, timeDt);\n\n int resId;\n long count;\n if (Minutes.minutesIn(interval).isLessThan(Minutes.ONE)) {\n count = Seconds.secondsIn(interval).getSeconds();\n if (past) {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_num_seconds_ago;\n }\n else {\n resId = R.plurals.joda_time_android_num_seconds_ago;\n }\n }\n else {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_in_num_seconds;\n }\n else {\n resId = R.plurals.joda_time_android_in_num_seconds;\n }\n }\n }\n else if (Hours.hoursIn(interval).isLessThan(Hours.ONE)) {\n count = Minutes.minutesIn(interval).getMinutes();\n if (past) {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_num_minutes_ago;\n }\n else {\n resId = R.plurals.joda_time_android_num_minutes_ago;\n }\n }\n else {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_in_num_minutes;\n }\n else {\n resId = R.plurals.joda_time_android_in_num_minutes;\n }\n }\n }\n else if (Days.daysIn(interval).isLessThan(Days.ONE)) {\n count = Hours.hoursIn(interval).getHours();\n if (past) {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_num_hours_ago;\n }\n else {\n resId = R.plurals.joda_time_android_num_hours_ago;\n }\n }\n else {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_in_num_hours;\n }\n else {\n resId = R.plurals.joda_time_android_in_num_hours;\n }\n }\n }\n else if (Weeks.weeksIn(interval).isLessThan(Weeks.ONE)) {\n count = Days.daysIn(interval).getDays();\n if (past) {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_num_days_ago;\n }\n else {\n resId = R.plurals.joda_time_android_num_days_ago;\n }\n }\n else {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_in_num_days;\n }\n else {\n resId = R.plurals.joda_time_android_in_num_days;\n }\n }\n }\n else {\n return formatDateRange(context, time, time, flags);\n }\n\n String format = context.getResources().getQuantityString(resId, (int) count);\n return String.format(format, count);\n }"
] | [
"public static base_response add(nitro_service client, nspbr6 resource) throws Exception {\n\t\tnspbr6 addresource = new nspbr6();\n\t\taddresource.name = resource.name;\n\t\taddresource.td = resource.td;\n\t\taddresource.action = resource.action;\n\t\taddresource.srcipv6 = resource.srcipv6;\n\t\taddresource.srcipop = resource.srcipop;\n\t\taddresource.srcipv6val = resource.srcipv6val;\n\t\taddresource.srcport = resource.srcport;\n\t\taddresource.srcportop = resource.srcportop;\n\t\taddresource.srcportval = resource.srcportval;\n\t\taddresource.destipv6 = resource.destipv6;\n\t\taddresource.destipop = resource.destipop;\n\t\taddresource.destipv6val = resource.destipv6val;\n\t\taddresource.destport = resource.destport;\n\t\taddresource.destportop = resource.destportop;\n\t\taddresource.destportval = resource.destportval;\n\t\taddresource.srcmac = resource.srcmac;\n\t\taddresource.protocol = resource.protocol;\n\t\taddresource.protocolnumber = resource.protocolnumber;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.Interface = resource.Interface;\n\t\taddresource.priority = resource.priority;\n\t\taddresource.state = resource.state;\n\t\taddresource.msr = resource.msr;\n\t\taddresource.monitor = resource.monitor;\n\t\taddresource.nexthop = resource.nexthop;\n\t\taddresource.nexthopval = resource.nexthopval;\n\t\taddresource.nexthopvlan = resource.nexthopvlan;\n\t\treturn addresource.add_resource(client);\n\t}",
"public void setDefaults(Annotation[] defaultAnnotations) {\n if (defaultAnnotations == null) {\n return;\n }\n for (Annotation each : defaultAnnotations) {\n Class<? extends Annotation> key = each.annotationType();\n if (Title.class.equals(key) || Description.class.equals(key)) {\n continue;\n }\n if (!annotations.containsKey(key)) {\n annotations.put(key, each);\n }\n }\n }",
"private void openBrowser(URI url) throws IOException {\n if (Desktop.isDesktopSupported()) {\n Desktop.getDesktop().browse(url);\n } else {\n LOGGER.error(\"Can not open browser because this capability is not supported on \" +\n \"your platform. You can use the link below to open the report manually.\");\n }\n }",
"@JsonProperty(\"paging\")\n void paging(String paging) {\n builder.paging(IndexPagingState.fromByteBuffer(ByteBufferUtils.byteBuffer(paging)));\n }",
"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 void replaceItem(@NonNull final T oldObject, @NonNull final T newObject) {\n synchronized (mLock) {\n final int position = getPosition(oldObject);\n if (position == -1) {\n // not found, don't replace\n return;\n }\n\n mObjects.remove(position);\n mObjects.add(position, newObject);\n\n if (isItemTheSame(oldObject, newObject)) {\n if (isContentTheSame(oldObject, newObject)) {\n // visible content hasn't changed, don't notify\n return;\n }\n\n // item with same stable id has changed\n notifyItemChanged(position, newObject);\n } else {\n // item replaced with another one with a different id\n notifyItemRemoved(position);\n notifyItemInserted(position);\n }\n }\n }",
"public synchronized void start() throws SocketException {\n\n if (!isRunning()) {\n socket.set(new DatagramSocket(ANNOUNCEMENT_PORT));\n startTime.set(System.currentTimeMillis());\n deliverLifecycleAnnouncement(logger, true);\n\n final byte[] buffer = new byte[512];\n final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);\n Thread receiver = new Thread(null, new Runnable() {\n @Override\n public void run() {\n boolean received;\n while (isRunning()) {\n try {\n if (getCurrentDevices().isEmpty()) {\n socket.get().setSoTimeout(60000); // We have no devices to check for timeout; block for a whole minute to check for shutdown\n } else {\n socket.get().setSoTimeout(1000); // Check every second to see if a device has vanished\n }\n socket.get().receive(packet);\n received = !ignoredAddresses.contains(packet.getAddress());\n } catch (SocketTimeoutException ste) {\n received = false;\n } catch (IOException e) {\n // Don't log a warning if the exception was due to the socket closing at shutdown.\n if (isRunning()) {\n // We did not expect to have a problem; log a warning and shut down.\n logger.warn(\"Problem reading from DeviceAnnouncement socket, stopping\", e);\n stop();\n }\n received = false;\n }\n try {\n if (received && (packet.getLength() == 54)) {\n final Util.PacketType kind = Util.validateHeader(packet, ANNOUNCEMENT_PORT);\n if (kind == Util.PacketType.DEVICE_KEEP_ALIVE) {\n // Looks like the kind of packet we need\n if (packet.getLength() < 54) {\n logger.warn(\"Ignoring too-short \" + kind.name + \" packet; expected 54 bytes, but only got \" +\n packet.getLength() + \".\");\n } else {\n if (packet.getLength() > 54) {\n logger.warn(\"Processing too-long \" + kind.name + \" packet; expected 54 bytes, but got \" +\n packet.getLength() + \".\");\n }\n DeviceAnnouncement announcement = new DeviceAnnouncement(packet);\n final boolean foundNewDevice = isDeviceNew(announcement);\n updateDevices(announcement);\n if (foundNewDevice) {\n deliverFoundAnnouncement(announcement);\n }\n }\n }\n }\n expireDevices();\n } catch (Throwable t) {\n logger.warn(\"Problem processing DeviceAnnouncement packet\", t);\n }\n }\n }\n }, \"beat-link DeviceFinder receiver\");\n receiver.setDaemon(true);\n receiver.start();\n }\n }",
"public List<ResourceRequestType.ResourceRequestCriterion> getResourceRequestCriterion()\n {\n if (resourceRequestCriterion == null)\n {\n resourceRequestCriterion = new ArrayList<ResourceRequestType.ResourceRequestCriterion>();\n }\n return this.resourceRequestCriterion;\n }",
"private ClassDescriptor discoverDescriptor(Class clazz)\r\n {\r\n ClassDescriptor result = (ClassDescriptor) descriptorTable.get(clazz.getName());\r\n\r\n if (result == null)\r\n {\r\n Class superClass = clazz.getSuperclass();\r\n // only recurse if the superClass is not java.lang.Object\r\n if (superClass != null)\r\n {\r\n result = discoverDescriptor(superClass);\r\n }\r\n if (result == null)\r\n {\r\n // we're also checking the interfaces as there could be normal\r\n // mappings for them in the repository (using factory-class,\r\n // factory-method, and the property field accessor)\r\n Class[] interfaces = clazz.getInterfaces();\r\n\r\n if ((interfaces != null) && (interfaces.length > 0))\r\n {\r\n for (int idx = 0; (idx < interfaces.length) && (result == null); idx++)\r\n {\r\n result = discoverDescriptor(interfaces[idx]);\r\n }\r\n }\r\n }\r\n\r\n if (result != null)\r\n {\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \tsynchronized (descriptorTable) {\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n \t\tdescriptorTable.put(clazz.getName(), result);\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \t}\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n }\r\n }\r\n return result;\r\n }"
] |
Checks that native primarykey fields have readonly access, and warns if not.
@param fieldDef The field descriptor
@param checkLevel The current check level (this constraint is checked in basic and strict) | [
"private void checkReadonlyAccessForNativePKs(FieldDescriptorDef fieldDef, String checkLevel)\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String access = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ACCESS);\r\n String autoInc = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_AUTOINCREMENT);\r\n\r\n if (\"database\".equals(autoInc) && !\"readonly\".equals(access))\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"checkAccess\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" is set to database auto-increment. Therefore the field's access is set to 'readonly'.\");\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_ACCESS, \"readonly\");\r\n }\r\n }"
] | [
"@PostConstruct\n public final void init() {\n this.cleanUpTimer = Executors.newScheduledThreadPool(1, timerTask -> {\n final Thread thread = new Thread(timerTask, \"Clean up old job records\");\n thread.setDaemon(true);\n return thread;\n });\n this.cleanUpTimer.scheduleAtFixedRate(this::cleanup, this.cleanupInterval, this.cleanupInterval,\n TimeUnit.SECONDS);\n }",
"public static <T> Observable<T> delayedEmitAsync(T event, int milliseconds) {\n return delayProvider.delayedEmitAsync(event, milliseconds);\n }",
"private void removeListener(CmsUUID listenerId) {\n\n getRequest().getSession().removeAttribute(SESSION_ATTRIBUTE_LISTENER_ID);\n m_listeners.remove(listenerId);\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 static base_responses save(nitro_service client, cachecontentgroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcachecontentgroup saveresources[] = new cachecontentgroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tsaveresources[i] = new cachecontentgroup();\n\t\t\t\tsaveresources[i].name = resources[i].name;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, saveresources,\"save\");\n\t\t}\n\t\treturn result;\n\t}",
"protected int[] getPatternAsCodewords(int size) {\n if (size >= 10) {\n throw new IllegalArgumentException(\"Pattern groups of 10 or more digits are likely to be too large to parse as integers.\");\n }\n if (pattern == null || pattern.length == 0) {\n return new int[0];\n } else {\n int count = (int) Math.ceil(pattern[0].length() / (double) size);\n int[] codewords = new int[pattern.length * count];\n for (int i = 0; i < pattern.length; i++) {\n String row = pattern[i];\n for (int j = 0; j < count; j++) {\n int substringStart = j * size;\n int substringEnd = Math.min((j + 1) * size, row.length());\n codewords[(i * count) + j] = Integer.parseInt(row.substring(substringStart, substringEnd));\n }\n }\n return codewords;\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 }",
"public void setValue(Quaternionf rot) {\n mX = rot.x;\n mY = rot.y;\n mZ = rot.z;\n mW = rot.w;\n }",
"private void readExceptionDay(ProjectCalendar calendar, Project.Calendars.Calendar.WeekDays.WeekDay day)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay.TimePeriod timePeriod = day.getTimePeriod();\n Date fromDate = timePeriod.getFromDate();\n Date toDate = timePeriod.getToDate();\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = day.getWorkingTimes();\n ProjectCalendarException exception = calendar.addCalendarException(fromDate, toDate);\n\n if (times != null)\n {\n List<Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime> time = times.getWorkingTime();\n for (Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime period : time)\n {\n Date startTime = period.getFromTime();\n Date endTime = period.getToTime();\n\n if (startTime != null && endTime != null)\n {\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n exception.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }"
] |
Feeds input stream to data consumer using metadata from tar entry.
@param consumer the consumer
@param inputStream the stream to feed
@param entry the entry to use for metadata
@throws IOException on consume error | [
"static void produceInputStreamWithEntry( final DataConsumer consumer,\n final InputStream inputStream,\n final TarArchiveEntry entry ) throws IOException {\n try {\n consumer.onEachFile(inputStream, entry);\n } finally {\n IOUtils.closeQuietly(inputStream);\n }\n }"
] | [
"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 }",
"public List<String> invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {\n MavenProject mavenProject = getMavenProject(f.getAbsolutePath());\n return mavenProject.getModel().getModules();\n }",
"public static locationfile get(nitro_service service) throws Exception{\n\t\tlocationfile obj = new locationfile();\n\t\tlocationfile[] response = (locationfile[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"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 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 HashMap<String, JSONObject> flatRessources(JSONObject object) throws JSONException {\n HashMap<String, JSONObject> result = new HashMap<String, JSONObject>();\n\n // no cycle in hierarchies!!\n if (object.has(\"resourceId\") && object.has(\"childShapes\")) {\n result.put(object.getString(\"resourceId\"),\n object);\n JSONArray childShapes = object.getJSONArray(\"childShapes\");\n for (int i = 0; i < childShapes.length(); i++) {\n result.putAll(flatRessources(childShapes.getJSONObject(i)));\n }\n }\n ;\n\n return result;\n }",
"public static final String printWorkContour(WorkContour value)\n {\n return (Integer.toString(value == null ? WorkContour.FLAT.getValue() : value.getValue()));\n }",
"@Override\n public boolean isTempoMaster() {\n DeviceUpdate master = VirtualCdj.getInstance().getTempoMaster();\n return (master != null) && master.getAddress().equals(address);\n }",
"private void plan() {\n // Mapping of stealer node to list of primary partitions being moved\n final TreeMultimap<Integer, Integer> stealerToStolenPrimaryPartitions = TreeMultimap.create();\n\n // Output initial and final cluster\n if(outputDir != null)\n RebalanceUtils.dumpClusters(currentCluster, finalCluster, outputDir);\n\n // Determine which partitions must be stolen\n for(Node stealerNode: finalCluster.getNodes()) {\n List<Integer> stolenPrimaryPartitions = RebalanceUtils.getStolenPrimaryPartitions(currentCluster,\n finalCluster,\n stealerNode.getId());\n if(stolenPrimaryPartitions.size() > 0) {\n numPrimaryPartitionMoves += stolenPrimaryPartitions.size();\n stealerToStolenPrimaryPartitions.putAll(stealerNode.getId(),\n stolenPrimaryPartitions);\n }\n }\n\n // Determine plan batch-by-batch\n int batches = 0;\n Cluster batchCurrentCluster = Cluster.cloneCluster(currentCluster);\n List<StoreDefinition> batchCurrentStoreDefs = this.currentStoreDefs;\n List<StoreDefinition> batchFinalStoreDefs = this.finalStoreDefs;\n Cluster batchFinalCluster = RebalanceUtils.getInterimCluster(this.currentCluster,\n this.finalCluster);\n\n while(!stealerToStolenPrimaryPartitions.isEmpty()) {\n\n int partitions = 0;\n List<Entry<Integer, Integer>> partitionsMoved = Lists.newArrayList();\n for(Entry<Integer, Integer> stealerToPartition: stealerToStolenPrimaryPartitions.entries()) {\n partitionsMoved.add(stealerToPartition);\n batchFinalCluster = UpdateClusterUtils.createUpdatedCluster(batchFinalCluster,\n stealerToPartition.getKey(),\n Lists.newArrayList(stealerToPartition.getValue()));\n partitions++;\n if(partitions == batchSize)\n break;\n }\n\n // Remove the partitions moved\n for(Iterator<Entry<Integer, Integer>> partitionMoved = partitionsMoved.iterator(); partitionMoved.hasNext();) {\n Entry<Integer, Integer> entry = partitionMoved.next();\n stealerToStolenPrimaryPartitions.remove(entry.getKey(), entry.getValue());\n }\n\n if(outputDir != null)\n RebalanceUtils.dumpClusters(batchCurrentCluster,\n batchFinalCluster,\n outputDir,\n \"batch-\" + Integer.toString(batches) + \".\");\n\n // Generate a plan to compute the tasks\n final RebalanceBatchPlan RebalanceBatchPlan = new RebalanceBatchPlan(batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs);\n batchPlans.add(RebalanceBatchPlan);\n\n numXZonePartitionStoreMoves += RebalanceBatchPlan.getCrossZonePartitionStoreMoves();\n numPartitionStoreMoves += RebalanceBatchPlan.getPartitionStoreMoves();\n nodeMoveMap.add(RebalanceBatchPlan.getNodeMoveMap());\n zoneMoveMap.add(RebalanceBatchPlan.getZoneMoveMap());\n\n batches++;\n batchCurrentCluster = Cluster.cloneCluster(batchFinalCluster);\n // batchCurrentStoreDefs can only be different from\n // batchFinalStoreDefs for the initial batch.\n batchCurrentStoreDefs = batchFinalStoreDefs;\n }\n\n logger.info(this);\n }"
] |
Write the summary file, if requested. | [
"@Subscribe\n public void onQuit(AggregatedQuitEvent e) {\n if (summaryFile != null) {\n try {\n Persister persister = new Persister();\n persister.write(new MavenFailsafeSummaryModel(summaryListener.getResult()), summaryFile);\n } catch (Exception x) {\n junit4.log(\"Could not serialize summary report.\", x, Project.MSG_WARN);\n }\n }\n }"
] | [
"@Deprecated\n public ClientConfig setNodeBannagePeriod(int nodeBannagePeriod, TimeUnit unit) {\n this.failureDetectorBannagePeriod = unit.toMillis(nodeBannagePeriod);\n return this;\n }",
"private int[] readTypeAnnotations(final MethodVisitor mv,\n final Context context, int u, boolean visible) {\n char[] c = context.buffer;\n int[] offsets = new int[readUnsignedShort(u)];\n u += 2;\n for (int i = 0; i < offsets.length; ++i) {\n offsets[i] = u;\n int target = readInt(u);\n switch (target >>> 24) {\n case 0x00: // CLASS_TYPE_PARAMETER\n case 0x01: // METHOD_TYPE_PARAMETER\n case 0x16: // METHOD_FORMAL_PARAMETER\n u += 2;\n break;\n case 0x13: // FIELD\n case 0x14: // METHOD_RETURN\n case 0x15: // METHOD_RECEIVER\n u += 1;\n break;\n case 0x40: // LOCAL_VARIABLE\n case 0x41: // RESOURCE_VARIABLE\n for (int j = readUnsignedShort(u + 1); j > 0; --j) {\n int start = readUnsignedShort(u + 3);\n int length = readUnsignedShort(u + 5);\n createLabel(start, context.labels);\n createLabel(start + length, context.labels);\n u += 6;\n }\n u += 3;\n break;\n case 0x47: // CAST\n case 0x48: // CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT\n case 0x49: // METHOD_INVOCATION_TYPE_ARGUMENT\n case 0x4A: // CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT\n case 0x4B: // METHOD_REFERENCE_TYPE_ARGUMENT\n u += 4;\n break;\n // case 0x10: // CLASS_EXTENDS\n // case 0x11: // CLASS_TYPE_PARAMETER_BOUND\n // case 0x12: // METHOD_TYPE_PARAMETER_BOUND\n // case 0x17: // THROWS\n // case 0x42: // EXCEPTION_PARAMETER\n // case 0x43: // INSTANCEOF\n // case 0x44: // NEW\n // case 0x45: // CONSTRUCTOR_REFERENCE\n // case 0x46: // METHOD_REFERENCE\n default:\n u += 3;\n break;\n }\n int pathLength = readByte(u);\n if ((target >>> 24) == 0x42) {\n TypePath path = pathLength == 0 ? null : new TypePath(b, u);\n u += 1 + 2 * pathLength;\n u = readAnnotationValues(u + 2, c, true,\n mv.visitTryCatchAnnotation(target, path,\n readUTF8(u, c), visible));\n } else {\n u = readAnnotationValues(u + 3 + 2 * pathLength, c, true, null);\n }\n }\n return offsets;\n }",
"public AT_Context setFrameTopBottomMargin(int frameTop, int frameBottom){\r\n\t\tif(frameTop>-1 && frameBottom>-1){\r\n\t\t\tthis.frameTopMargin = frameTop;\r\n\t\t\tthis.frameBottomMargin = frameBottom;\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"synchronized int read(byte[] data) {\n this.header = getHeaderParser().setData(data).parseHeader();\n if (data != null) {\n setData(header, data);\n }\n\n return status;\n }",
"private Object initializeLazyPropertiesFromCache(\n\t\t\tfinal String fieldName,\n\t\t\tfinal Object entity,\n\t\t\tfinal SharedSessionContractImplementor session,\n\t\t\tfinal EntityEntry entry,\n\t\t\tfinal CacheEntry cacheEntry\n\t) {\n\t\tthrow new NotSupportedException( \"OGM-9\", \"Lazy properties not supported in OGM\" );\n\t}",
"void processSiteRow(String siteRow) {\n\t\tString[] row = getSiteRowFields(siteRow);\n\n\t\tString filePath = \"\";\n\t\tString pagePath = \"\";\n\n\t\tString dataArray = row[8].substring(row[8].indexOf('{'),\n\t\t\t\trow[8].length() - 2);\n\n\t\t// Explanation for the regular expression below:\n\t\t// \"'{' or ';'\" followed by either\n\t\t// \"NOT: ';', '{', or '}'\" repeated one or more times; or\n\t\t// \"a single '}'\"\n\t\t// The first case matches \";s:5:\\\"paths\\\"\"\n\t\t// but also \";a:2:\" in \"{s:5:\\\"paths\\\";a:2:{s:9:\\ ...\".\n\t\t// The second case matches \";}\" which terminates (sub)arrays.\n\t\tMatcher matcher = Pattern.compile(\"[{;](([^;}{][^;}{]*)|[}])\").matcher(\n\t\t\t\tdataArray);\n\t\tString prevString = \"\";\n\t\tString curString = \"\";\n\t\tString path = \"\";\n\t\tboolean valuePosition = false;\n\n\t\twhile (matcher.find()) {\n\t\t\tString match = matcher.group().substring(1);\n\t\t\tif (match.length() == 0) {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (match.charAt(0) == 's') {\n\t\t\t\tvaluePosition = !valuePosition && !\"\".equals(prevString);\n\t\t\t\tcurString = match.substring(match.indexOf('\"') + 1,\n\t\t\t\t\t\tmatch.length() - 2);\n\t\t\t} else if (match.charAt(0) == 'a') {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tpath = path + \"/\" + prevString;\n\t\t\t} else if (\"}\".equals(match)) {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tpath = path.substring(0, path.lastIndexOf('/'));\n\t\t\t}\n\n\t\t\tif (valuePosition && \"file_path\".equals(prevString)\n\t\t\t\t\t&& \"/paths\".equals(path)) {\n\t\t\t\tfilePath = curString;\n\t\t\t} else if (valuePosition && \"page_path\".equals(prevString)\n\t\t\t\t\t&& \"/paths\".equals(path)) {\n\t\t\t\tpagePath = curString;\n\t\t\t}\n\n\t\t\tprevString = curString;\n\t\t\tcurString = \"\";\n\t\t}\n\n\t\tMwSitesDumpFileProcessor.logger.debug(\"Found site data \\\"\" + row[1]\n\t\t\t\t+ \"\\\" (group \\\"\" + row[3] + \"\\\", language \\\"\" + row[5]\n\t\t\t\t+ \"\\\", type \\\"\" + row[2] + \"\\\")\");\n\t\tthis.sites.setSiteInformation(row[1], row[3], row[5], row[2], filePath,\n\t\t\t\tpagePath);\n\t}",
"private Map<Integer, Integer> getNodeIdToPrimaryCount(Cluster cluster) {\n Map<Integer, Integer> nodeIdToPrimaryCount = Maps.newHashMap();\n for(Node node: cluster.getNodes()) {\n nodeIdToPrimaryCount.put(node.getId(), node.getPartitionIds().size());\n }\n\n return nodeIdToPrimaryCount;\n }",
"public Collection<Group> getGroups() throws FlickrException {\r\n GroupList<Group> groups = new GroupList<Group>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_GROUPS);\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 groupsElement = response.getPayload();\r\n groups.setPage(groupsElement.getAttribute(\"page\"));\r\n groups.setPages(groupsElement.getAttribute(\"pages\"));\r\n groups.setPerPage(groupsElement.getAttribute(\"perpage\"));\r\n groups.setTotal(groupsElement.getAttribute(\"total\"));\r\n NodeList groupNodes = groupsElement.getElementsByTagName(\"group\");\r\n for (int i = 0; i < groupNodes.getLength(); i++) {\r\n Element groupElement = (Element) groupNodes.item(i);\r\n Group group = new Group();\r\n group.setId(groupElement.getAttribute(\"id\"));\r\n group.setName(groupElement.getAttribute(\"name\"));\r\n group.setAdmin(\"1\".equals(groupElement.getAttribute(\"admin\")));\r\n group.setPrivacy(groupElement.getAttribute(\"privacy\"));\r\n group.setIconServer(groupElement.getAttribute(\"iconserver\"));\r\n group.setIconFarm(groupElement.getAttribute(\"iconfarm\"));\r\n group.setPhotoCount(groupElement.getAttribute(\"photos\"));\r\n groups.add(group);\r\n }\r\n return groups;\r\n }",
"public boolean removeHandlerFor(final GVRSceneObject sceneObject) {\n sceneObject.detachComponent(GVRCollider.getComponentType());\n return null != touchHandlers.remove(sceneObject);\n }"
] |
Retrieves the path using the endpoint value
@param pathValue - path (endpoint) value
@param requestType - "GET", "POST", etc
@return Path or null
@throws Exception exception | [
"public JSONObject getPathFromEndpoint(String pathValue, String requestType) throws Exception {\n int type = getRequestTypeFromString(requestType);\n String url = BASE_PATH;\n JSONObject response = new JSONObject(doGet(url, null));\n JSONArray paths = response.getJSONArray(\"paths\");\n for (int i = 0; i < paths.length(); i++) {\n JSONObject path = paths.getJSONObject(i);\n if (path.getString(\"path\").equals(pathValue) && path.getInt(\"requestType\") == type) {\n return path;\n }\n }\n return null;\n }"
] | [
"public GroovyClassDoc[] innerClasses() {\n Collections.sort(nested);\n return nested.toArray(new GroovyClassDoc[nested.size()]);\n }",
"public List<EndpointOverride> getSelectedPaths(int overrideType, Client client, Profile profile, String uri,\n Integer requestType, boolean pathTest) throws Exception {\n List<EndpointOverride> selectPaths = new ArrayList<EndpointOverride>();\n\n // get the paths for the current active client profile\n // this returns paths in priority order\n List<EndpointOverride> paths = new ArrayList<EndpointOverride>();\n\n if (client.getIsActive()) {\n paths = getPaths(\n profile.getId(),\n client.getUUID(), null);\n }\n\n boolean foundRealPath = false;\n logger.info(\"Checking uri: {}\", uri);\n\n // it should now be ordered by priority, i updated tableOverrides to\n // return the paths in priority order\n for (EndpointOverride path : paths) {\n // first see if the request types match..\n // and if the path request type is not ALL\n // if they do not then skip this path\n // If requestType is -1 we evaluate all(probably called by the path tester)\n if (requestType != -1 && path.getRequestType() != requestType && path.getRequestType() != Constants.REQUEST_TYPE_ALL) {\n continue;\n }\n\n // first see if we get a match\n try {\n Pattern pattern = Pattern.compile(path.getPath());\n Matcher matcher = pattern.matcher(uri);\n\n // we won't select the path if there aren't any enabled endpoints in it\n // this works since the paths are returned in priority order\n if (matcher.find()) {\n // now see if this path has anything enabled in it\n // Only go into the if:\n // 1. There are enabled items in this path\n // 2. Caller was looking for ResponseOverride and Response is enabled OR looking for RequestOverride\n // 3. If pathTest is true then the rest of the conditions are not evaluated. The path tester ignores enabled states so everything is returned.\n // and request is enabled\n if (pathTest ||\n (path.getEnabledEndpoints().size() > 0 &&\n ((overrideType == Constants.OVERRIDE_TYPE_RESPONSE && path.getResponseEnabled()) ||\n (overrideType == Constants.OVERRIDE_TYPE_REQUEST && path.getRequestEnabled())))) {\n // if we haven't already seen a non global path\n // or if this is a global path\n // then add it to the list\n if (!foundRealPath || path.getGlobal()) {\n selectPaths.add(path);\n }\n }\n\n // we set this no matter what if a path matched and it was not the global path\n // this stops us from adding further non global matches to the list\n if (!path.getGlobal()) {\n foundRealPath = true;\n }\n }\n } catch (PatternSyntaxException pse) {\n // nothing to do but keep iterating over the list\n // this indicates an invalid regex\n }\n }\n\n return selectPaths;\n }",
"private void removeXmlBundleFile() throws CmsException {\n\n lockLocalization(null);\n m_cms.deleteResource(m_resource, CmsResource.DELETE_PRESERVE_SIBLINGS);\n m_resource = null;\n\n }",
"private String visibility(Options opt, ProgramElementDoc e) {\n\treturn opt.showVisibility ? Visibility.get(e).symbol : \" \";\n }",
"@Inject(\"struts.json.action.fileProtocols\")\n\tpublic void setFileProtocols(String fileProtocols) {\n\t\tif (StringUtils.isNotBlank(fileProtocols)) {\n\t\t\tthis.fileProtocols = TextParseUtil.commaDelimitedStringToSet(fileProtocols);\n\t\t}\n\t}",
"protected static int getIntInitParameter(ServletContext servletContext, String parameterName, int defaultValue) {\n final String parameterString = servletContext.getInitParameter(parameterName);\n if(parameterString != null && parameterString.trim().length() > 0) {\n try {\n return Integer.parseInt(parameterString);\n }\n catch (NumberFormatException e) {\n // Do nothing, return default value\n }\n }\n return defaultValue;\n }",
"@Pure\n\tpublic static <P1, P2, RESULT> Function1<P2, RESULT> curry(final Function2<? super P1, ? super P2, ? extends RESULT> function,\n\t\t\tfinal P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function1<P2, RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply(P2 p) {\n\t\t\t\treturn function.apply(argument, p);\n\t\t\t}\n\t\t};\n\t}",
"private void recordTime(Tracked op,\n long timeNS,\n long numEmptyResponses,\n long valueSize,\n long keySize,\n long getAllAggregateRequests) {\n counters.get(op).addRequest(timeNS,\n numEmptyResponses,\n valueSize,\n keySize,\n getAllAggregateRequests);\n\n if (logger.isTraceEnabled() && !storeName.contains(\"aggregate\") && !storeName.contains(\"voldsys$\"))\n logger.trace(\"Store '\" + storeName + \"' logged a \" + op.toString() + \" request taking \" +\n ((double) timeNS / voldemort.utils.Time.NS_PER_MS) + \" ms\");\n }",
"public ArrayList<Double> segmentCost(ProjectCalendar projectCalendar, List<TimephasedCost> cost, TimescaleUnits rangeUnits, ArrayList<DateRange> dateList)\n {\n ArrayList<Double> result = new ArrayList<Double>(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, cost, lastStartIndex);\n if (startIndex == -1)\n {\n result.add(NumberHelper.DOUBLE_ZERO);\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(getRangeCost(projectCalendar, rangeUnits, range, cost, startIndex));\n lastStartIndex = startIndex;\n }\n }\n\n return result;\n }"
] |
Returns the Euclidean distance between this vector and vector v.
@return distance between this vector and v | [
"public double distance(Vector3d v) {\n double dx = x - v.x;\n double dy = y - v.y;\n double dz = z - v.z;\n\n return Math.sqrt(dx * dx + dy * dy + dz * dz);\n }"
] | [
"private JSONValue toJsonStringList(Collection<? extends Object> list) {\n\n if (null != list) {\n JSONArray array = new JSONArray();\n for (Object o : list) {\n array.set(array.size(), new JSONString(o.toString()));\n }\n return array;\n } else {\n return null;\n }\n }",
"public int getIndexMin() {\n int indexMin = 0;\n double min = getEigenvalue(0).getMagnitude2();\n\n final int N = getNumberOfEigenvalues();\n for( int i = 1; i < N; i++ ) {\n double m = getEigenvalue(i).getMagnitude2();\n if( m < min ) {\n min = m;\n indexMin = i;\n }\n }\n\n return indexMin;\n }",
"@Override\n public ArtifactoryResponse restCall(ArtifactoryRequest artifactoryRequest) throws IOException {\n HttpRequestBase httpRequest;\n\n String requestPath = \"/\" + artifactoryRequest.getApiUrl();\n ContentType contentType = Util.getContentType(artifactoryRequest.getRequestType());\n\n String queryPath = \"\";\n if (!artifactoryRequest.getQueryParams().isEmpty()) {\n queryPath = Util.getQueryPath(\"?\", artifactoryRequest.getQueryParams());\n }\n\n switch (artifactoryRequest.getMethod()) {\n case GET:\n httpRequest = new HttpGet();\n\n break;\n\n case POST:\n httpRequest = new HttpPost();\n setEntity((HttpPost)httpRequest, artifactoryRequest.getBody(), contentType);\n\n break;\n\n case PUT:\n httpRequest = new HttpPut();\n setEntity((HttpPut)httpRequest, artifactoryRequest.getBody(), contentType);\n\n break;\n\n case DELETE:\n httpRequest = new HttpDelete();\n\n break;\n\n case PATCH:\n httpRequest = new HttpPatch();\n setEntity((HttpPatch)httpRequest, artifactoryRequest.getBody(), contentType);\n break;\n\n case OPTIONS:\n httpRequest = new HttpOptions();\n break;\n\n default:\n throw new IllegalArgumentException(\"Unsupported request method.\");\n }\n\n httpRequest.setURI(URI.create(url + requestPath + queryPath));\n addAccessTokenHeaderIfNeeded(httpRequest);\n\n if (contentType != null) {\n httpRequest.setHeader(\"Content-type\", contentType.getMimeType());\n }\n\n Map<String, String> headers = artifactoryRequest.getHeaders();\n for (String key : headers.keySet()) {\n httpRequest.setHeader(key, headers.get(key));\n }\n\n HttpResponse httpResponse = httpClient.execute(httpRequest);\n return new ArtifactoryResponseImpl(httpResponse);\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 void unregisterComponent(java.awt.Component c)\r\n {\r\n java.awt.dnd.DragGestureRecognizer recognizer = \r\n (java.awt.dnd.DragGestureRecognizer)this.hmDragGestureRecognizers.remove(c);\r\n if (recognizer != null)\r\n recognizer.setComponent(null);\r\n }",
"private static Iterable<String> splitAndOmitEmpty(final String str, final char splitChar) {\n return new Iterable<String>() {\n @Override\n public Iterator<String> iterator() {\n return new Iterator<String>() {\n\n int startIdx = 0;\n String next = null;\n\n @Override\n public boolean hasNext() {\n while (next == null && startIdx < str.length()) {\n int idx = str.indexOf(splitChar, startIdx);\n if (idx == startIdx) {\n // Omit empty string\n startIdx++;\n continue;\n }\n if (idx >= 0) {\n // Found the next part\n next = str.substring(startIdx, idx);\n startIdx = idx;\n } else {\n // The last part\n if (startIdx < str.length()) {\n next = str.substring(startIdx);\n startIdx = str.length();\n }\n break;\n }\n }\n return next != null;\n }\n\n @Override\n public String next() {\n if (hasNext()) {\n String next = this.next;\n this.next = null;\n return next;\n }\n throw new NoSuchElementException(\"No more element\");\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException(\"Remove not supported\");\n }\n };\n }\n };\n }",
"@GwtIncompatible(\"Class.getDeclaredFields\")\n\tpublic ToStringBuilder addDeclaredFields() {\n\t\tField[] fields = instance.getClass().getDeclaredFields();\n\t\tfor(Field field : fields) {\n\t\t\taddField(field);\n\t\t}\n\t\treturn this;\n\t}",
"public static void log(String label, byte[] data)\n {\n if (LOG != null)\n {\n LOG.write(label);\n LOG.write(\": \");\n LOG.println(ByteArrayHelper.hexdump(data, true));\n LOG.flush();\n }\n }",
"public String name(Properties attributes) throws XDocletException\r\n {\r\n return getDefForLevel(attributes.getProperty(ATTRIBUTE_LEVEL)).getName();\r\n }"
] |
Set the week of the month the events should occur.
@param weekOfMonth the week of month to set (first to fifth, where fifth means last). | [
"public final void setWeekOfMonth(WeekOfMonth weekOfMonth) {\n\n SortedSet<WeekOfMonth> woms = new TreeSet<>();\n if (null != weekOfMonth) {\n woms.add(weekOfMonth);\n }\n setWeeksOfMonth(woms);\n }"
] | [
"public void setControllerModel(GVRSceneObject controllerModel)\n {\n if (mControllerModel != null)\n {\n mControllerGroup.removeChildObject(mControllerModel);\n }\n mControllerModel = controllerModel;\n mControllerGroup.addChildObject(mControllerModel);\n mControllerModel.setEnable(mShowControllerModel);\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 }",
"public Response save() throws RequestException, LocalOperationException {\n Map<String, Object> templateData = new HashMap<String, Object>();\n templateData.put(\"name\", name);\n\n options.put(\"steps\", steps.toMap());\n\n templateData.put(\"template\", options);\n Request request = new Request(transloadit);\n return new Response(request.post(\"/templates\", templateData));\n }",
"public static double[][] invert(double[][] matrix) {\n\n\t\tif(isSolverUseApacheCommonsMath) {\n\t\t\t// Use LU from common math\n\t\t\tLUDecomposition lu = new LUDecomposition(new Array2DRowRealMatrix(matrix));\n\t\t\tdouble[][] matrixInverse = lu.getSolver().getInverse().getData();\n\n\t\t\treturn matrixInverse;\n\t\t}\n\t\telse {\n\t\t\treturn org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2();\n\t\t}\n\t}",
"@Override\n public boolean setA(DMatrixRBlock A) {\n if( A.numRows < A.numCols )\n throw new IllegalArgumentException(\"Number of rows must be more than or equal to the number of columns. \" +\n \"Can't solve an underdetermined system.\");\n\n if( !decomposer.decompose(A))\n return false;\n\n this.QR = decomposer.getQR();\n\n return true;\n }",
"public static final PhotoList<Photo> createPhotoList(Element photosElement) {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\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 photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }",
"public static dnsaaaarec[] get(nitro_service service) throws Exception{\n\t\tdnsaaaarec obj = new dnsaaaarec();\n\t\tdnsaaaarec[] response = (dnsaaaarec[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public boolean removeKey(long key) {\r\n\tint i = indexOfKey(key);\r\n\tif (i<0) return false; // key not contained\r\n\r\n\tthis.state[i]=REMOVED;\r\n\tthis.values[i]=0; // delta\r\n\tthis.distinct--;\r\n\r\n\tif (this.distinct < this.lowWaterMark) {\r\n\t\tint newCapacity = chooseShrinkCapacity(this.distinct,this.minLoadFactor, this.maxLoadFactor);\r\n\t\trehash(newCapacity);\r\n\t}\r\n\t\r\n\treturn true;\t\r\n}",
"public static CurrencySymbolPosition getSymbolPosition(int value)\n {\n CurrencySymbolPosition result;\n\n switch (value)\n {\n case 1:\n {\n result = CurrencySymbolPosition.AFTER;\n break;\n }\n\n case 2:\n {\n result = CurrencySymbolPosition.BEFORE_WITH_SPACE;\n break;\n }\n\n case 3:\n {\n result = CurrencySymbolPosition.AFTER_WITH_SPACE;\n break;\n }\n\n case 0:\n default:\n {\n result = CurrencySymbolPosition.BEFORE;\n break;\n }\n }\n\n return (result);\n }"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.