query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Returns the resource bundle for current Locale, i.e. locale set in the PageComponent.
Always create a new instance, this avoids getting the incorrect locale information.
@return resourcebundle for internationalized messages | [
"public static ResourceBundle getCurrentResourceBundle(String locale) {\n\t\ttry {\n\t\t\tif (null != locale && !locale.isEmpty()) {\n\t\t\t\treturn getCurrentResourceBundle(LocaleUtils.toLocale(locale));\n\t\t\t}\n\t\t} catch (IllegalArgumentException ex) {\n\t\t\t// do nothing\n\t\t}\n\t\treturn getCurrentResourceBundle((Locale) null);\n\t}"
] | [
"public static dnstxtrec[] get(nitro_service service, String domain[]) throws Exception{\n\t\tif (domain !=null && domain.length>0) {\n\t\t\tdnstxtrec response[] = new dnstxtrec[domain.length];\n\t\t\tdnstxtrec obj[] = new dnstxtrec[domain.length];\n\t\t\tfor (int i=0;i<domain.length;i++) {\n\t\t\t\tobj[i] = new dnstxtrec();\n\t\t\t\tobj[i].set_domain(domain[i]);\n\t\t\t\tresponse[i] = (dnstxtrec) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"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 }",
"private static byte calculateChecksum(byte[] buffer) {\n\t\tbyte checkSum = (byte)0xFF;\n\t\tfor (int i=1; i<buffer.length-1; i++) {\n\t\t\tcheckSum = (byte) (checkSum ^ buffer[i]);\n\t\t}\n\t\tlogger.trace(String.format(\"Calculated checksum = 0x%02X\", checkSum));\n\t\treturn checkSum;\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 }",
"public static base_response update(nitro_service client, rnatparam resource) throws Exception {\n\t\trnatparam updateresource = new rnatparam();\n\t\tupdateresource.tcpproxy = resource.tcpproxy;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public void enableCustomResponse(String custom, int path_id, String client_uuid) throws Exception {\n\n updateRequestResponseTables(\"custom_response\", custom, getProfileIdFromPathID(path_id), client_uuid, path_id);\n }",
"protected static Map<String, List<Statement>> removeStatements(Set<String> statementIds, Map<String, List<Statement>> claims) {\n\t\tMap<String, List<Statement>> newClaims = new HashMap<>(claims.size());\n\t\tfor(Entry<String, List<Statement>> entry : claims.entrySet()) {\n\t\t\tList<Statement> filteredStatements = new ArrayList<>();\n\t\t\tfor(Statement s : entry.getValue()) {\n\t\t\t\tif(!statementIds.contains(s.getStatementId())) {\n\t\t\t\t\tfilteredStatements.add(s);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!filteredStatements.isEmpty()) {\n\t\t\t\tnewClaims.put(entry.getKey(),\n\t\t\t\t\tfilteredStatements);\n\t\t\t}\n\t\t}\n\t\treturn newClaims;\n\t}",
"public final Processor.ExecutionContext print(\n final String jobId, final PJsonObject specJson, final OutputStream out)\n throws Exception {\n final OutputFormat format = getOutputFormat(specJson);\n final File taskDirectory = this.workingDirectories.getTaskDirectory();\n\n try {\n return format.print(jobId, specJson, getConfiguration(), this.configFile.getParentFile(),\n taskDirectory, out);\n } finally {\n this.workingDirectories.removeDirectory(taskDirectory);\n }\n }",
"void recover() {\n final List<NamespaceSynchronizationConfig> nsConfigs = new ArrayList<>();\n for (final MongoNamespace ns : this.syncConfig.getSynchronizedNamespaces()) {\n nsConfigs.add(this.syncConfig.getNamespaceConfig(ns));\n }\n\n for (final NamespaceSynchronizationConfig nsConfig : nsConfigs) {\n nsConfig.getLock().writeLock().lock();\n }\n try {\n for (final NamespaceSynchronizationConfig nsConfig : nsConfigs) {\n nsConfig.getLock().writeLock().lock();\n try {\n recoverNamespace(nsConfig);\n } finally {\n nsConfig.getLock().writeLock().unlock();\n }\n }\n } finally {\n for (final NamespaceSynchronizationConfig nsConfig : nsConfigs) {\n nsConfig.getLock().writeLock().unlock();\n }\n }\n }"
] |
Use this API to add autoscaleaction. | [
"public static base_response add(nitro_service client, autoscaleaction resource) throws Exception {\n\t\tautoscaleaction addresource = new autoscaleaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.type = resource.type;\n\t\taddresource.profilename = resource.profilename;\n\t\taddresource.parameters = resource.parameters;\n\t\taddresource.vmdestroygraceperiod = resource.vmdestroygraceperiod;\n\t\taddresource.quiettime = resource.quiettime;\n\t\taddresource.vserver = resource.vserver;\n\t\treturn addresource.add_resource(client);\n\t}"
] | [
"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 }",
"@Override\n public void onKeyDown(KeyDownEvent event) {\n\tchar c = MiscUtils.getCharCode(event.getNativeEvent());\n\tonKeyCodeEvent(event, box.getValue()+c);\n }",
"public static final MVCArray buildArcPoints(LatLong center, double startBearing, double endBearing, double radius) {\n int points = DEFAULT_ARC_POINTS;\n\n MVCArray res = new MVCArray();\n\n if (startBearing > endBearing) {\n endBearing += 360.0;\n }\n double deltaBearing = endBearing - startBearing;\n deltaBearing = deltaBearing / points;\n for (int i = 0; (i < points + 1); i++) {\n res.push(center.getDestinationPoint(startBearing + i * deltaBearing, radius));\n }\n\n return res;\n\n }",
"public static void removeZeros( DMatrixSparseCSC input , DMatrixSparseCSC output , double tol ) {\n ImplCommonOps_DSCC.removeZeros(input,output,tol);\n }",
"private void writePropertyData() {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"properties.csv\"))) {\n\n\t\t\tout.println(\"Id\" + \",Label\" + \",Description\" + \",URL\" + \",Datatype\"\n\t\t\t\t\t+ \",Uses in statements\" + \",Items with such statements\"\n\t\t\t\t\t+ \",Uses in statements with qualifiers\"\n\t\t\t\t\t+ \",Uses in qualifiers\" + \",Uses in references\"\n\t\t\t\t\t+ \",Uses total\" + \",Related properties\");\n\n\t\t\tList<Entry<PropertyIdValue, PropertyRecord>> list = new ArrayList<Entry<PropertyIdValue, PropertyRecord>>(\n\t\t\t\t\tthis.propertyRecords.entrySet());\n\t\t\tCollections.sort(list, new UsageRecordComparator());\n\t\t\tfor (Entry<PropertyIdValue, PropertyRecord> entry : list) {\n\t\t\t\tprintPropertyRecord(out, entry.getValue(), entry.getKey());\n\t\t\t}\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"public int addServerGroup(String groupName, int profileId) throws Exception {\n int groupId = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_SERVER_GROUPS\n + \"(\" + Constants.GENERIC_NAME + \",\" +\n Constants.GENERIC_PROFILE_ID + \")\"\n + \" VALUES (?, ?);\", PreparedStatement.RETURN_GENERATED_KEYS);\n statement.setString(1, groupName);\n statement.setInt(2, profileId);\n statement.executeUpdate();\n\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n groupId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add group\");\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return groupId;\n }",
"protected boolean clearSpecial(DatabaseConnection connection, Logger logger) {\n\t\tNestedConnection currentSaved = specialConnection.get();\n\t\tboolean cleared = false;\n\t\tif (connection == null) {\n\t\t\t// ignored\n\t\t} else if (currentSaved == null) {\n\t\t\tlogger.error(\"no connection has been saved when clear() called\");\n\t\t} else if (currentSaved.connection == connection) {\n\t\t\tif (currentSaved.decrementAndGet() == 0) {\n\t\t\t\t// we only clear the connection if nested counter is 0\n\t\t\t\tspecialConnection.set(null);\n\t\t\t}\n\t\t\tcleared = true;\n\t\t} else {\n\t\t\tlogger.error(\"connection saved {} is not the one being cleared {}\", currentSaved.connection, connection);\n\t\t}\n\t\t// release should then be called after clear\n\t\treturn cleared;\n\t}",
"public void setValue(Quaternionf rot) {\n mX = rot.x;\n mY = rot.y;\n mZ = rot.z;\n mW = rot.w;\n }",
"protected void validate(final boolean isDomain) throws MojoDeploymentException {\n final boolean hasServerGroups = hasServerGroups();\n if (isDomain) {\n if (!hasServerGroups) {\n throw new MojoDeploymentException(\n \"Server is running in domain mode, but no server groups have been defined.\");\n }\n } else if (hasServerGroups) {\n throw new MojoDeploymentException(\"Server is running in standalone mode, but server groups have been defined.\");\n }\n }"
] |
Internally undo recorded changes we did so far.
@return whether the state required undo actions | [
"boolean undoChanges() {\n final State state = stateUpdater.getAndSet(this, State.ROLLBACK_ONLY);\n if (state == State.COMPLETED || state == State.ROLLBACK_ONLY) {\n // Was actually completed already\n return false;\n }\n PatchingTaskContext.Mode currentMode = this.mode;\n mode = PatchingTaskContext.Mode.UNDO;\n final PatchContentLoader loader = PatchContentLoader.create(miscBackup, null, null);\n // Undo changes for the identity\n undoChanges(identityEntry, loader);\n // TODO maybe check if we need to do something for the layers too !?\n if (state == State.INVALIDATE || currentMode == PatchingTaskContext.Mode.ROLLBACK) {\n // For apply the state needs to be invalidate\n // For rollback the files are invalidated as part of the tasks\n final PatchingTaskContext.Mode mode = currentMode == PatchingTaskContext.Mode.APPLY ? PatchingTaskContext.Mode.ROLLBACK : PatchingTaskContext.Mode.APPLY;\n for (final File file : moduleInvalidations) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, mode);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n if(!modulesToReenable.isEmpty()) {\n for (final File file : modulesToReenable) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.APPLY);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n }\n if(!modulesToDisable.isEmpty()) {\n for (final File file : modulesToDisable) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.ROLLBACK);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n }\n }\n return true;\n }"
] | [
"private void checkExactlyTheWeeksCheckBoxes(Collection<WeekOfMonth> weeksToCheck) {\r\n\r\n for (CmsCheckBox cb : m_checkboxes) {\r\n cb.setChecked(weeksToCheck.contains(WeekOfMonth.valueOf(cb.getInternalValue())));\r\n }\r\n }",
"public static cachepolicy_cacheglobal_binding[] get(nitro_service service, String policyname) throws Exception{\n\t\tcachepolicy_cacheglobal_binding obj = new cachepolicy_cacheglobal_binding();\n\t\tobj.set_policyname(policyname);\n\t\tcachepolicy_cacheglobal_binding response[] = (cachepolicy_cacheglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"@SuppressWarnings(\"WeakerAccess\")\n public Map<DeckReference, WaveformPreview> getLoadedPreviews() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, WaveformPreview>(previewHotCache));\n }",
"public static nsip6[] get(nitro_service service) throws Exception{\n\t\tnsip6 obj = new nsip6();\n\t\tnsip6[] response = (nsip6[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"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 }",
"private void internalWriteNameValuePair(String name, String value) throws IOException\n {\n writeComma();\n writeNewLineIndent();\n writeName(name);\n\n if (m_pretty)\n {\n m_writer.write(' ');\n }\n\n m_writer.write(value);\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 }",
"public void setBackgroundColor(int colorRes) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }",
"@SuppressWarnings(\"unchecked\")\n protected <T extends Indexable> T taskResult(String key) {\n Indexable result = this.taskGroup.taskResult(key);\n if (result == null) {\n return null;\n } else {\n T castedResult = (T) result;\n return castedResult;\n }\n }"
] |
Executes the API action "wbsetclaim" for the given parameters.
@param statement
the JSON serialization of claim to add or delete.
@param bot
if true, edits will be flagged as "bot edits" provided that
the logged in user is in the bot group; for regular users, the
flag will just be ignored
@param baserevid
the revision of the data that the edit refers to or 0 if this
should not be submitted; when used, the site will ensure that
no edit has happened since this revision to detect edit
conflicts; it is recommended to use this whenever in all
operations where the outcome depends on the state of the
online data
@param summary
summary for the edit; will be prepended by an automatically
generated comment; the length limit of the autocomment
together with the summary is 260 characters: everything above
that limit will be cut off
@return the JSON response from the API
@throws IOException
if there was an IO problem. such as missing network
connection
@throws MediaWikiApiErrorException
if the API returns an error
@throws IOException
@throws MediaWikiApiErrorException | [
"public JsonNode wbSetClaim(String statement,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(statement,\n\t\t\t\t\"Statement parameter cannot be null when adding or changing a statement\");\n\t\t\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"claim\", statement);\n\t\t\n\t\treturn performAPIAction(\"wbsetclaim\", null, null, null, null, parameters, summary, baserevid, bot);\n\t}"
] | [
"public void setAttribute(final String name, final Attribute attribute) {\n if (name.equals(MAP_KEY)) {\n this.mapAttribute = (MapAttribute) attribute;\n }\n }",
"public static boolean checkAddProperty(\r\n CmsCmisTypeManager typeManager,\r\n Properties properties,\r\n String typeId,\r\n Set<String> filter,\r\n String id) {\r\n\r\n if ((properties == null) || (properties.getProperties() == null)) {\r\n throw new IllegalArgumentException(\"Properties must not be null!\");\r\n }\r\n\r\n if (id == null) {\r\n throw new IllegalArgumentException(\"Id must not be null!\");\r\n }\r\n\r\n TypeDefinition type = typeManager.getType(typeId);\r\n if (type == null) {\r\n throw new IllegalArgumentException(\"Unknown type: \" + typeId);\r\n }\r\n if (!type.getPropertyDefinitions().containsKey(id)) {\r\n throw new IllegalArgumentException(\"Unknown property: \" + id);\r\n }\r\n\r\n String queryName = type.getPropertyDefinitions().get(id).getQueryName();\r\n\r\n if ((queryName != null) && (filter != null)) {\r\n if (!filter.contains(queryName)) {\r\n return false;\r\n } else {\r\n filter.remove(queryName);\r\n }\r\n }\r\n\r\n return true;\r\n }",
"public void setDatesWithCheckState(Collection<CmsPair<Date, Boolean>> datesWithCheckInfo) {\n\n SortedSet<Date> dates = new TreeSet<>();\n m_checkBoxes.clear();\n for (CmsPair<Date, Boolean> p : datesWithCheckInfo) {\n addCheckBox(p.getFirst(), p.getSecond().booleanValue());\n dates.add(p.getFirst());\n }\n reInitLayoutElements();\n setDatesInternal(dates);\n }",
"public void setStatusBarColor(int statusBarColor) {\n if (mBuilder.mScrimInsetsLayout != null) {\n mBuilder.mScrimInsetsLayout.setInsetForeground(statusBarColor);\n mBuilder.mScrimInsetsLayout.getView().invalidate();\n }\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 base_response clear_config(Boolean force, String level) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsconfig resource = new nsconfig();\n\t\tif (force)\n\t\t\tresource.set_force(force);\n\n\t\tresource.set_level(level);\n\t\toptions option = new options();\n\t\toption.set_action(\"clear\");\n\t\tresult = resource.perform_operation(this, option);\n\t\treturn result;\n\t}",
"public ParallelTaskBuilder setReplaceVarMapToSingleTargetFromMap(\n Map<String, StrStrMap> replacementVarMapNodeSpecific,\n String uniformTargetHost) {\n setReplacementVarMapNodeSpecific(replacementVarMapNodeSpecific);\n\n if (Strings.isNullOrEmpty(uniformTargetHost)) {\n logger.error(\"uniform target host is empty or null. skip setting.\");\n return this;\n }\n for (Entry<String, StrStrMap> entry : replacementVarMapNodeSpecific\n .entrySet()) {\n\n if (entry.getValue() != null) {\n entry.getValue().addPair(PcConstants.UNIFORM_TARGET_HOST_VAR,\n uniformTargetHost);\n }\n }\n return this;\n }",
"public Dataset<String, String> getDataset(Dataset<String, String> oldData, Index<String> goodFeatures) {\r\n //public Dataset getDataset(List data, Collection goodFeatures) {\r\n //makeAnswerArraysAndTagIndex(data);\r\n\r\n int[][] oldDataArray = oldData.getDataArray();\r\n int[] oldLabelArray = oldData.getLabelsArray();\r\n Index<String> oldFeatureIndex = oldData.featureIndex;\r\n\r\n int[] oldToNewFeatureMap = new int[oldFeatureIndex.size()];\r\n\r\n int[][] newDataArray = new int[oldDataArray.length][];\r\n\r\n System.err.print(\"Building reduced dataset...\");\r\n\r\n int size = oldFeatureIndex.size();\r\n int max = 0;\r\n for (int i = 0; i < size; i++) {\r\n oldToNewFeatureMap[i] = goodFeatures.indexOf(oldFeatureIndex.get(i));\r\n if (oldToNewFeatureMap[i] > max) {\r\n max = oldToNewFeatureMap[i];\r\n }\r\n }\r\n\r\n for (int i = 0; i < oldDataArray.length; i++) {\r\n int[] data = oldDataArray[i];\r\n size = 0;\r\n for (int j = 0; j < data.length; j++) {\r\n if (oldToNewFeatureMap[data[j]] > 0) {\r\n size++;\r\n }\r\n }\r\n int[] newData = new int[size];\r\n int index = 0;\r\n for (int j = 0; j < data.length; j++) {\r\n int f = oldToNewFeatureMap[data[j]];\r\n if (f > 0) {\r\n newData[index++] = f;\r\n }\r\n }\r\n newDataArray[i] = newData;\r\n }\r\n\r\n Dataset<String, String> train = new Dataset<String, String>(oldData.labelIndex, oldLabelArray, goodFeatures, newDataArray, newDataArray.length);\r\n\r\n System.err.println(\"done.\");\r\n if (flags.featThreshFile != null) {\r\n System.err.println(\"applying thresholds...\");\r\n List<Pair<Pattern,Integer>> thresh = getThresholds(flags.featThreshFile);\r\n train.applyFeatureCountThreshold(thresh);\r\n } else if (flags.featureThreshold > 1) {\r\n System.err.println(\"Removing Features with counts < \" + flags.featureThreshold);\r\n train.applyFeatureCountThreshold(flags.featureThreshold);\r\n }\r\n train.summaryStatistics();\r\n return train;\r\n }",
"@Override\n public PersistentResourceXMLDescription getParserDescription() {\n return PersistentResourceXMLDescription.builder(ElytronExtension.SUBSYSTEM_PATH, getNameSpace())\n .addAttribute(ElytronDefinition.DEFAULT_AUTHENTICATION_CONTEXT)\n .addAttribute(ElytronDefinition.INITIAL_PROVIDERS)\n .addAttribute(ElytronDefinition.FINAL_PROVIDERS)\n .addAttribute(ElytronDefinition.DISALLOWED_PROVIDERS)\n .addAttribute(ElytronDefinition.SECURITY_PROPERTIES, new AttributeParsers.PropertiesParser(null, SECURITY_PROPERTY, true), new AttributeMarshallers.PropertiesAttributeMarshaller(null, SECURITY_PROPERTY, true))\n .addChild(getAuthenticationClientParser())\n .addChild(getProviderParser())\n .addChild(getAuditLoggingParser())\n .addChild(getDomainParser())\n .addChild(getRealmParser())\n .addChild(getCredentialSecurityFactoryParser())\n .addChild(getMapperParser())\n .addChild(getHttpParser())\n .addChild(getSaslParser())\n .addChild(getTlsParser())\n .addChild(decorator(CREDENTIAL_STORES).addChild(new CredentialStoreParser().parser))\n .addChild(getDirContextParser())\n .addChild(getPolicyParser())\n .build();\n }"
] |
Provisions a new app user in an enterprise with additional user information using Box Developer Edition.
@param api the API connection to be used by the created user.
@param name the name of the user.
@param params additional user information.
@return the created user's info. | [
"public static BoxUser.Info createAppUser(BoxAPIConnection api, String name,\n CreateUserParams params) {\n\n params.setIsPlatformAccessOnly(true);\n return createEnterpriseUser(api, null, name, params);\n }"
] | [
"public static authenticationlocalpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationlocalpolicy_authenticationvserver_binding obj = new authenticationlocalpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationlocalpolicy_authenticationvserver_binding response[] = (authenticationlocalpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Iterable<BoxRetentionPolicyAssignment.Info> getEnterpriseAssignments(int limit, String ... fields) {\r\n return this.getAssignments(BoxRetentionPolicyAssignment.TYPE_ENTERPRISE, limit, fields);\r\n }",
"boolean attachmentsAreStructurallyDifferent( List<AttachmentModel> firstAttachments, List<AttachmentModel> otherAttachments ) {\n if( firstAttachments.size() != otherAttachments.size() ) {\n return true;\n }\n\n for( int i = 0; i < firstAttachments.size(); i++ ) {\n if( attachmentIsStructurallyDifferent( firstAttachments.get( i ), otherAttachments.get( i ) ) ) {\n return true;\n }\n }\n return false;\n }",
"private void updateLetsEncrypt() {\n\n getReport().println(Messages.get().container(Messages.RPT_STARTING_LETSENCRYPT_UPDATE_0));\n\n CmsLetsEncryptConfiguration config = OpenCms.getLetsEncryptConfig();\n if ((config == null) || !config.isValidAndEnabled()) {\n return;\n }\n CmsSiteConfigToLetsEncryptConfigConverter converter = new CmsSiteConfigToLetsEncryptConfigConverter(config);\n boolean ok = converter.run(getReport(), OpenCms.getSiteManager());\n if (ok) {\n getReport().println(\n org.opencms.ui.apps.Messages.get().container(org.opencms.ui.apps.Messages.RPT_LETSENCRYPT_FINISHED_0),\n I_CmsReport.FORMAT_OK);\n }\n\n }",
"private Revision uncachedHeadRevision() {\n try (RevWalk revWalk = new RevWalk(jGitRepository)) {\n final ObjectId headRevisionId = jGitRepository.resolve(R_HEADS_MASTER);\n if (headRevisionId != null) {\n final RevCommit revCommit = revWalk.parseCommit(headRevisionId);\n return CommitUtil.extractRevision(revCommit.getFullMessage());\n }\n } catch (CentralDogmaException e) {\n throw e;\n } catch (Exception e) {\n throw new StorageException(\"failed to get the current revision\", e);\n }\n\n throw new StorageException(\"failed to determine the HEAD: \" + jGitRepository.getDirectory());\n }",
"public static int cudnnGetReductionWorkspaceSize(\n cudnnHandle handle, \n cudnnReduceTensorDescriptor reduceTensorDesc, \n cudnnTensorDescriptor aDesc, \n cudnnTensorDescriptor cDesc, \n long[] sizeInBytes)\n {\n return checkResult(cudnnGetReductionWorkspaceSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes));\n }",
"private static void writeToLog(Logger logger, Level level, String pattern, Exception exception) {\n if (level == Level.ERROR) {\n logger.error(pattern, exception);\n } else if (level == Level.INFO) {\n logger.info(pattern);\n } else if (level == Level.DEBUG) {\n logger.debug(pattern);\n }\n }",
"public static Date getTime(int hour, int minutes)\n {\n Calendar cal = popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, hour);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.SECOND, 0);\n Date result = cal.getTime();\n pushCalendar(cal);\n return result;\n }",
"public SelectBuilder orderBy(String name, boolean ascending) {\n if (ascending) {\n orderBys.add(name + \" asc\");\n } else {\n orderBys.add(name + \" desc\");\n }\n return this;\n }"
] |
Use this API to fetch the statistics of all cmppolicylabel_stats resources that are configured on netscaler. | [
"public static cmppolicylabel_stats[] get(nitro_service service) throws Exception{\n\t\tcmppolicylabel_stats obj = new cmppolicylabel_stats();\n\t\tcmppolicylabel_stats[] response = (cmppolicylabel_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}"
] | [
"public RedwoodConfiguration stderr(){\r\n LogRecordHandler visibility = new VisibilityHandler();\r\n LogRecordHandler console = Redwood.ConsoleHandler.err();\r\n return this\r\n .rootHandler(visibility)\r\n .handler(visibility, console);\r\n }",
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/delete\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> deleteClient(Model model,\n @RequestParam(\"profileIdentifier\") String profileIdentifier,\n @RequestParam(\"clientUUID\") String[] clientUUID) throws Exception {\n\n logger.info(\"Attempting to remove clients from the profile: \", profileIdentifier);\n logger.info(\"Attempting to remove the following clients: {}\", Arrays.toString(clientUUID));\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n for( int i = 0; i < clientUUID.length; i++ )\n {\n if (clientUUID[i].compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) == 0)\n throw new Exception(\"Default client cannot be deleted\");\n\n clientService.remove(profileId, clientUUID[i]);\n }\n\n valueHash.put(\"clients\", clientService.findAllClients(profileId));\n return valueHash;\n }",
"public String join(List<String> list) {\n\n if (list == null) {\n return null;\n }\n\n StringBuilder sb = new StringBuilder();\n boolean first = true;\n for (String s : list) {\n\n if (s == null) {\n if (convertEmptyToNull) {\n s = \"\";\n } else {\n throw new IllegalArgumentException(\"StringListFlattener does not support null strings in the list. Consider calling setConvertEmptyToNull(true).\");\n }\n }\n\n if (!first) {\n sb.append(separator);\n }\n\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (c == escapeChar || c == separator) {\n sb.append(escapeChar);\n }\n sb.append(c);\n }\n\n first = false;\n }\n return sb.toString();\n }",
"public int getRegisteredResourceRequestCount(K key) {\n if(requestQueueMap.containsKey(key)) {\n Queue<AsyncResourceRequest<V>> requestQueue = getRequestQueueForExistingKey(key);\n // FYI: .size() is not constant time in the next call. ;)\n if(requestQueue != null) {\n return requestQueue.size();\n }\n }\n return 0;\n }",
"public void close() {\n Closer.closeQuietly(acceptor);\n for (Processor processor : processors) {\n Closer.closeQuietly(processor);\n }\n }",
"protected String getArgString(Object arg) {\n //if (arg instanceof LatLong) {\n // return ((LatLong) arg).getVariableName();\n //} else \n if (arg instanceof JavascriptObject) {\n return ((JavascriptObject) arg).getVariableName();\n // return ((JavascriptObject) arg).getPropertiesAsString();\n } else if( arg instanceof JavascriptEnum ) {\n return ((JavascriptEnum) arg).getEnumValue().toString();\n } else {\n return arg.toString();\n }\n }",
"private void setMasterTempo(double newTempo) {\n double oldTempo = Double.longBitsToDouble(masterTempo.getAndSet(Double.doubleToLongBits(newTempo)));\n if ((getTempoMaster() != null) && (Math.abs(newTempo - oldTempo) > getTempoEpsilon())) {\n // This is a change in tempo, so report it to any registered listeners, and update our metronome if we are synced.\n if (isSynced()) {\n metronome.setTempo(newTempo);\n notifyBeatSenderOfChange();\n }\n deliverTempoChangedAnnouncement(newTempo);\n }\n }",
"public ItemRequest<Project> removeFollowers(String project) {\n \n String path = String.format(\"/projects/%s/removeFollowers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }",
"@SuppressForbidden(\"legitimate sysstreams.\")\n private Execute forkProcess(ForkedJvmInfo slaveInfo, EventBus eventBus, \n CommandlineJava commandline, \n TailInputStream eventStream, OutputStream sysout, OutputStream syserr, RandomAccessFile streamsBuffer) {\n try {\n String tempDir = commandline.getSystemProperties().getVariablesVector().stream()\n .filter(v -> v.getKey().equals(\"java.io.tmpdir\"))\n .map(v -> v.getValue())\n .findAny()\n .orElse(null);\n\n final LocalSlaveStreamHandler streamHandler = \n new LocalSlaveStreamHandler(\n eventBus, testsClassLoader, System.err, eventStream, \n sysout, syserr, heartbeat, streamsBuffer);\n\n // Add certain properties to allow identification of the forked JVM from within\n // the subprocess. This can be used for policy files etc.\n final Path cwd = getWorkingDirectory(slaveInfo, tempDir);\n\n Variable v = new Variable();\n v.setKey(CHILDVM_SYSPROP_CWD);\n v.setFile(cwd.toAbsolutePath().normalize().toFile());\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SYSPROP_TEMPDIR);\n v.setFile(getTempDir().toAbsolutePath().normalize().toFile());\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SysGlobals.CHILDVM_SYSPROP_JVM_ID);\n v.setValue(Integer.toString(slaveInfo.id));\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SysGlobals.CHILDVM_SYSPROP_JVM_COUNT);\n v.setValue(Integer.toString(slaveInfo.slaves));\n commandline.addSysproperty(v);\n\n // Emit command line before -stdin to avoid confusion.\n slaveInfo.slaveCommandLine = escapeAndJoin(commandline.getCommandline());\n log(\"Forked child JVM at '\" + cwd.toAbsolutePath().normalize() + \n \"', command (may need escape sequences for your shell):\\n\" + \n slaveInfo.slaveCommandLine, Project.MSG_VERBOSE);\n\n final Execute execute = new Execute();\n execute.setCommandline(commandline.getCommandline());\n execute.setVMLauncher(true);\n execute.setWorkingDirectory(cwd.toFile());\n execute.setStreamHandler(streamHandler);\n execute.setNewenvironment(newEnvironment);\n if (env.getVariables() != null)\n execute.setEnvironment(env.getVariables());\n log(\"Starting JVM J\" + slaveInfo.id, Project.MSG_DEBUG);\n execute.execute();\n return execute;\n } catch (IOException e) {\n throw new BuildException(\"Could not start the child process. Run ant with -verbose to get\" +\n \t\t\" the execution details.\", e);\n }\n }"
] |
Solve the using the lower triangular matrix in LU. Diagonal elements are assumed
to be 1 | [
"protected void solveL(double[] vv) {\n\n int ii = 0;\n\n for( int i = 0; i < n; i++ ) {\n int ip = indx[i];\n double sumReal = vv[ip*2];\n double sumImg = vv[ip*2+1];\n\n vv[ip*2] = vv[i*2];\n vv[ip*2+1] = vv[i*2+1];\n\n if( ii != 0 ) {\n// for( int j = ii-1; j < i; j++ )\n// sum -= dataLU[i* n +j]*vv[j];\n int index = i*stride + (ii-1)*2;\n for( int j = ii-1; j < i; j++ ){\n double luReal = dataLU[index++];\n double luImg = dataLU[index++];\n\n double vvReal = vv[j*2];\n double vvImg = vv[j*2+1];\n\n sumReal -= luReal*vvReal - luImg*vvImg;\n sumImg -= luReal*vvImg + luImg*vvReal;\n }\n } else if( sumReal*sumReal + sumImg*sumImg != 0.0 ) {\n ii=i+1;\n }\n vv[i*2] = sumReal;\n vv[i*2+1] = sumImg;\n }\n }"
] | [
"public ItemRequest<Project> update(String project) {\n \n String path = String.format(\"/projects/%s\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"PUT\");\n }",
"@Override\n\tpublic RandomVariable getNumeraire(double time) throws CalculationException {\n\t\tint timeIndex = getLiborPeriodIndex(time);\n\n\t\tif(timeIndex < 0) {\n\t\t\t// Interpolation of Numeraire: linear interpolation of the reciprocal.\n\t\t\tint lowerIndex = -timeIndex -1;\n\t\t\tint upperIndex = -timeIndex;\n\t\t\tdouble alpha = (time-getLiborPeriod(lowerIndex)) / (getLiborPeriod(upperIndex) - getLiborPeriod(lowerIndex));\n\t\t\treturn getNumeraire(getLiborPeriod(upperIndex)).invert().mult(alpha).add(getNumeraire(getLiborPeriod(lowerIndex)).invert().mult(1.0-alpha)).invert();\n\t\t}\n\n\t\t// Calculate the numeraire, when time is part of liborPeriodDiscretization\n\n\t\t// Get the start of the product\n\t\tint firstLiborIndex\t\t= getLiborPeriodIndex(time);\n\t\tif(firstLiborIndex < 0) {\n\t\t\tthrow new CalculationException(\"Simulation time discretization not part of forward rate tenor discretization.\");\n\t\t}\n\n\t\t// Get the end of the product\n\t\tint lastLiborIndex \t= liborPeriodDiscretization.getNumberOfTimeSteps()-1;\n\n\t\tif(measure == Measure.SPOT) {\n\t\t\t// Spot measure\n\t\t\tfirstLiborIndex\t= 0;\n\t\t\tlastLiborIndex\t= getLiborPeriodIndex(time)-1;\n\t\t}\n\n\t\t/*\n\t\t * Calculation of the numeraire\n\t\t */\n\n\t\t// Initialize to 1.0\n\t\tRandomVariable numeraire = new RandomVariableFromDoubleArray(time, 1.0);\n\n\t\t// The product\n\t\tfor(int liborIndex = firstLiborIndex; liborIndex<=lastLiborIndex; liborIndex++) {\n\t\t\tRandomVariable libor = getLIBOR(getTimeIndex(Math.min(time,liborPeriodDiscretization.getTime(liborIndex))), liborIndex);\n\n\t\t\tdouble periodLength = liborPeriodDiscretization.getTimeStep(liborIndex);\n\n\t\t\tif(measure == Measure.SPOT) {\n\t\t\t\tnumeraire = numeraire.accrue(libor, periodLength);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tnumeraire = numeraire.discount(libor, periodLength);\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Adjust for discounting\n\t\t */\n\t\tif(discountCurve != null) {\n\t\t\tDiscountCurve discountcountCurveFromForwardPerformance = new DiscountCurveFromForwardCurve(forwardRateCurve);\n\t\t\tdouble deterministicNumeraireAdjustment = discountcountCurveFromForwardPerformance.getDiscountFactor(time) / discountCurve.getDiscountFactor(time);\n\t\t\tnumeraire = numeraire.mult(deterministicNumeraireAdjustment);\n\t\t}\n\t\treturn numeraire;\n\t}",
"public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax,\n\t\t\tAbstractMeanSquaredDisplacmentEvaluator msdeval) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}",
"void persist(final String key, final String value, final boolean enableDisableMode, final boolean disable, final File file) throws IOException, StartException {\n persist(key, value, enableDisableMode, disable, file, null);\n }",
"protected static void appendHandler(Class<? extends LogRecordHandler> parent, LogRecordHandler child){\r\n List<LogRecordHandler> toAdd = new LinkedList<LogRecordHandler>();\r\n //--Find Parents\r\n for(LogRecordHandler term : handlers){\r\n if(parent.isAssignableFrom(term.getClass())){\r\n toAdd.add(term);\r\n }\r\n }\r\n //--Add Handler\r\n for(LogRecordHandler p : toAdd){\r\n appendHandler(p, child);\r\n }\r\n }",
"@Override\n protected void reset() {\n super.reset();\n mapClassesToNamedBoundProviders.clear();\n mapClassesToUnNamedBoundProviders.clear();\n hasTestModules = false;\n installBindingForScope();\n }",
"private void removeObservation( int index ) {\n final int N = y.numRows-1;\n final double d[] = y.data;\n\n // shift\n for( int i = index; i < N; i++ ) {\n d[i] = d[i+1];\n }\n y.numRows--;\n }",
"public void register() {\n synchronized (loaders) {\n loaders.add(this);\n\n maximumHeaderLength = 0;\n for (GVRCompressedTextureLoader loader : loaders) {\n int headerLength = loader.headerLength();\n if (headerLength > maximumHeaderLength) {\n maximumHeaderLength = headerLength;\n }\n }\n }\n }",
"public static String constructSerializerInfoXml(StoreDefinition storeDefinition) {\n Element store = new Element(StoreDefinitionsMapper.STORE_ELMT);\n store.addContent(new Element(StoreDefinitionsMapper.STORE_NAME_ELMT).setText(storeDefinition.getName()));\n Element keySerializer = new Element(StoreDefinitionsMapper.STORE_KEY_SERIALIZER_ELMT);\n StoreDefinitionsMapper.addSerializer(keySerializer, storeDefinition.getKeySerializer());\n store.addContent(keySerializer);\n\n Element valueSerializer = new Element(StoreDefinitionsMapper.STORE_VALUE_SERIALIZER_ELMT);\n StoreDefinitionsMapper.addSerializer(valueSerializer, storeDefinition.getValueSerializer());\n store.addContent(valueSerializer);\n\n XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());\n return serializer.outputString(store);\n }"
] |
Export data base contents to a directory using supplied connection.
@param connection database connection
@param directory target directory
@throws Exception | [
"public void process(Connection connection, String directory) throws Exception\n {\n connection.setAutoCommit(true);\n\n //\n // Retrieve meta data about the connection\n //\n DatabaseMetaData dmd = connection.getMetaData();\n\n String[] types =\n {\n \"TABLE\"\n };\n\n FileWriter fw = new FileWriter(directory);\n PrintWriter pw = new PrintWriter(fw);\n\n pw.println(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\");\n pw.println();\n pw.println(\"<database>\");\n\n ResultSet tables = dmd.getTables(null, null, null, types);\n while (tables.next() == true)\n {\n processTable(pw, connection, tables.getString(\"TABLE_NAME\"));\n }\n\n pw.println(\"</database>\");\n\n pw.close();\n\n tables.close();\n }"
] | [
"private static List<String> parseAndCompare(List<String> fileNames, int masterPartitionId) {\n List<String> sourceFileNames = new ArrayList<String>();\n for(String fileName: fileNames) {\n String[] partitionIdReplicaChunk = fileName.split(SPLIT_LITERAL);\n if(Integer.parseInt(partitionIdReplicaChunk[0]) == masterPartitionId) {\n sourceFileNames.add(fileName);\n }\n }\n return sourceFileNames;\n }",
"private String getFullUrl(String url) {\n return url.startsWith(\"https://\") || url.startsWith(\"http://\") ? url : transloadit.getHostUrl() + url;\n }",
"public void setIdleMaxAge(long idleMaxAge, TimeUnit timeUnit) {\n\t\tthis.idleMaxAgeInSeconds = TimeUnit.SECONDS.convert(idleMaxAge, checkNotNull(timeUnit)); \n\t}",
"public static protocolip_stats get(nitro_service service) throws Exception{\n\t\tprotocolip_stats obj = new protocolip_stats();\n\t\tprotocolip_stats[] response = (protocolip_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}",
"private void addCustomFields(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (CustomField field : file.getCustomFields())\n {\n final CustomField c = field;\n MpxjTreeNode childNode = new MpxjTreeNode(field)\n {\n @Override public String toString()\n {\n FieldType type = c.getFieldType();\n \n return type == null ? \"(unknown)\" : type.getFieldTypeClass() + \".\" + type.toString();\n }\n };\n parentNode.add(childNode);\n }\n }",
"public static base_responses enable(nitro_service client, String acl6name[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 enableresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tenableresources[i] = new nsacl6();\n\t\t\t\tenableresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, enableresources,\"enable\");\n\t\t}\n\t\treturn result;\n\t}",
"public static boolean isValidFqcn(String str) {\n if (isNullOrEmpty(str)) {\n return false;\n }\n final String[] parts = str.split(\"\\\\.\");\n if (parts.length < 2) {\n return false;\n }\n for (String part : parts) {\n if (!isValidJavaIdentifier(part)) {\n return false;\n }\n }\n return true;\n }",
"public static int cudnnGetConvolutionNdDescriptor(\n cudnnConvolutionDescriptor convDesc, \n int arrayLengthRequested, \n int[] arrayLength, \n int[] padA, \n int[] strideA, \n int[] dilationA, \n int[] mode, \n int[] computeType)/** convolution data type */\n {\n return checkResult(cudnnGetConvolutionNdDescriptorNative(convDesc, arrayLengthRequested, arrayLength, padA, strideA, dilationA, mode, computeType));\n }",
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher addFacet(String... attributes) {\n for (String attribute : attributes) {\n final Integer value = facetRequestCount.get(attribute);\n facetRequestCount.put(attribute, value == null ? 1 : value + 1);\n if (value == null || value == 0) {\n facets.add(attribute);\n }\n }\n rebuildQueryFacets();\n return this;\n }"
] |
Filter the URI based on a regular expression.
Can be combined with an additional file-extension filter. | [
"public void setRegularExpression(String regularExpression) {\n\t\tif (regularExpression != null)\n\t\t\tthis.regularExpression = Pattern.compile(regularExpression);\n\t\telse\n\t\t\tthis.regularExpression = null;\n\t}"
] | [
"public CustomField getCustomField(FieldType field)\n {\n CustomField result = m_configMap.get(field);\n if (result == null)\n {\n result = new CustomField(field, this);\n m_configMap.put(field, result);\n }\n return result;\n }",
"private static CallSite realBootstrap(Lookup caller, String name, int callID, MethodType type, boolean safe, boolean thisCall, boolean spreadCall) {\n // since indy does not give us the runtime types\n // we produce first a dummy call site, which then changes the target to one,\n // that does the method selection including the the direct call to the \n // real method.\n MutableCallSite mc = new MutableCallSite(type);\n MethodHandle mh = makeFallBack(mc,caller.lookupClass(),name,callID,type,safe,thisCall,spreadCall);\n mc.setTarget(mh);\n return mc;\n }",
"public void collectVariables(EnvVars env, Run build, TaskListener listener) {\n EnvVars buildParameters = Utils.extractBuildParameters(build, listener);\n if (buildParameters != null) {\n env.putAll(buildParameters);\n }\n addAllWithFilter(envVars, env, filter.getPatternFilter());\n Map<String, String> sysEnv = new HashMap<>();\n Properties systemProperties = System.getProperties();\n Enumeration<?> enumeration = systemProperties.propertyNames();\n while (enumeration.hasMoreElements()) {\n String propertyKey = (String) enumeration.nextElement();\n sysEnv.put(propertyKey, systemProperties.getProperty(propertyKey));\n }\n addAllWithFilter(sysVars, sysEnv, filter.getPatternFilter());\n }",
"public static void unregisterMbean(ObjectName name) {\n try {\n ManagementFactory.getPlatformMBeanServer().unregisterMBean(name);\n } catch(Exception e) {\n logger.error(\"Error unregistering mbean\", e);\n }\n }",
"public Object remove(String name) {\n\t\tBean bean = beans.get(name);\n\t\tif (null != bean) {\n\t\t\tbeans.remove(name);\n\t\t\tbean.destructionCallback.run();\n\t\t\treturn bean.object;\n\t\t}\n\t\treturn null;\n\t}",
"public static List<Versioned<byte[]>> resolveVersions(List<Versioned<byte[]>> values) {\n List<Versioned<byte[]>> resolvedVersions = new ArrayList<Versioned<byte[]>>(values.size());\n // Go over all the values and determine whether the version is\n // acceptable\n for(Versioned<byte[]> value: values) {\n Iterator<Versioned<byte[]>> iter = resolvedVersions.iterator();\n boolean obsolete = false;\n // Compare the current version with a set of accepted versions\n while(iter.hasNext()) {\n Versioned<byte[]> curr = iter.next();\n Occurred occurred = value.getVersion().compare(curr.getVersion());\n if(occurred == Occurred.BEFORE) {\n obsolete = true;\n break;\n } else if(occurred == Occurred.AFTER) {\n iter.remove();\n }\n }\n if(!obsolete) {\n // else update the set of accepted versions\n resolvedVersions.add(value);\n }\n }\n\n return resolvedVersions;\n }",
"public ParallelTaskBuilder prepareHttpPut(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.PUT);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n\n }",
"@Override\n public CopticDate date(int prolepticYear, int month, int dayOfMonth) {\n return CopticDate.of(prolepticYear, month, dayOfMonth);\n }",
"public static ModelNode validateRequest(CommandContext ctx, ModelNode request) throws CommandFormatException {\n\n final Set<String> keys = request.keys();\n if (keys.size() == 2) { // no props\n return null;\n }\n ModelNode outcome = (ModelNode) ctx.get(Scope.REQUEST, DESCRIPTION_RESPONSE);\n if (outcome == null) {\n outcome = retrieveDescription(ctx, request, true);\n if (outcome == null) {\n return null;\n } else {\n ctx.set(Scope.REQUEST, DESCRIPTION_RESPONSE, outcome);\n }\n }\n if(!outcome.has(Util.RESULT)) {\n throw new CommandFormatException(\"Failed to perform \" + Util.READ_OPERATION_DESCRIPTION + \" to validate the request: result is not available.\");\n }\n\n final String operationName = request.get(Util.OPERATION).asString();\n\n final ModelNode result = outcome.get(Util.RESULT);\n final Set<String> definedProps = result.hasDefined(Util.REQUEST_PROPERTIES) ? result.get(Util.REQUEST_PROPERTIES).keys() : Collections.emptySet();\n if(definedProps.isEmpty()) {\n if(!(keys.size() == 3 && keys.contains(Util.OPERATION_HEADERS))) {\n throw new CommandFormatException(\"Operation '\" + operationName + \"' does not expect any property.\");\n }\n } else {\n int skipped = 0;\n for(String prop : keys) {\n if(skipped < 2 && (prop.equals(Util.ADDRESS) || prop.equals(Util.OPERATION))) {\n ++skipped;\n continue;\n }\n if(!definedProps.contains(prop)) {\n if(!Util.OPERATION_HEADERS.equals(prop)) {\n throw new CommandFormatException(\"'\" + prop + \"' is not found among the supported properties: \" + definedProps);\n }\n }\n }\n }\n return outcome;\n }"
] |
END ODO CHANGES | [
"private void startRelayWithPortTollerance(HttpServer server, SslListener relay, int tries) throws Exception {\n if (tries >= 5) {\n throw new BindException(\"Unable to bind to several ports, most recently \" + relay.getPort() + \". Giving up\");\n }\n try {\n if (server.isStarted()) {\n relay.start();\n } else {\n throw new RuntimeException(\"Can't start SslRelay: server is not started (perhaps it was just shut down?)\");\n }\n } catch (BindException e) {\n // doh - the port is being used up, let's pick a new port\n LOG.info(\"Unable to bind to port %d, going to try port %d now\", relay.getPort(), relay.getPort() + 1);\n relay.setPort(relay.getPort() + 1);\n startRelayWithPortTollerance(server, relay, tries + 1);\n }\n }"
] | [
"public List<Task> getActiveTasks() {\n InputStream response = null;\n URI uri = new URIBase(getBaseUri()).path(\"_active_tasks\").build();\n try {\n response = couchDbClient.get(uri);\n return getResponseList(response, couchDbClient.getGson(), DeserializationTypes.TASKS);\n } finally {\n close(response);\n }\n }",
"public void close() {\n this.waitUntilInitialized();\n\n this.ongoingOperationsGroup.blockAndWait();\n\n syncLock.lock();\n try {\n if (this.networkMonitor != null) {\n this.networkMonitor.removeNetworkStateListener(this);\n }\n this.dispatcher.close();\n stop();\n this.localClient.close();\n } finally {\n syncLock.unlock();\n }\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 MaterialAccount getAccountByTitle(String title) {\n for(MaterialAccount account : accountManager)\n if(currentAccount.getTitle().equals(title))\n return account;\n\n return null;\n }",
"public static long getMaxId(PersistenceBroker brokerForClass, Class topLevel, FieldDescriptor original) throws PersistenceBrokerException\r\n {\r\n long max = 0;\r\n long tmp;\r\n ClassDescriptor cld = brokerForClass.getClassDescriptor(topLevel);\r\n\r\n // if class is not an interface / not abstract we have to search its directly mapped table\r\n if (!cld.isInterface() && !cld.isAbstract())\r\n {\r\n tmp = getMaxIdForClass(brokerForClass, cld, original);\r\n if (tmp > max)\r\n {\r\n max = tmp;\r\n }\r\n }\r\n // if class is an extent we have to search through its subclasses\r\n if (cld.isExtent())\r\n {\r\n Vector extentClasses = cld.getExtentClasses();\r\n for (int i = 0; i < extentClasses.size(); i++)\r\n {\r\n Class extentClass = (Class) extentClasses.get(i);\r\n if (cld.getClassOfObject().equals(extentClass))\r\n {\r\n throw new PersistenceBrokerException(\"Circular extent in \" + extentClass +\r\n \", please check the repository\");\r\n }\r\n else\r\n {\r\n // fix by Mark Rowell\r\n // Call recursive\r\n tmp = getMaxId(brokerForClass, extentClass, original);\r\n }\r\n if (tmp > max)\r\n {\r\n max = tmp;\r\n }\r\n }\r\n }\r\n return max;\r\n }",
"public ParallelTaskBuilder setTargetHostsFromLineByLineText(\n String sourcePath, HostsSourceType sourceType)\n throws TargetHostsLoadException {\n\n this.targetHosts = targetHostBuilder.setTargetHostsFromLineByLineText(sourcePath,\n sourceType);\n return this;\n }",
"protected BoxWatermark applyWatermark(URLTemplate itemUrl, String imprint) {\n URL watermarkUrl = itemUrl.build(this.getAPI().getBaseURL(), this.getID());\n URL url = WATERMARK_URL_TEMPLATE.build(watermarkUrl.toString());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n JsonObject body = new JsonObject()\n .add(BoxWatermark.WATERMARK_JSON_KEY, new JsonObject()\n .add(BoxWatermark.WATERMARK_IMPRINT_JSON_KEY, imprint));\n request.setBody(body.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new BoxWatermark(response.getJSON());\n }",
"public void setDateAttribute(String name, Date value) {\n\t\tensureAttributes();\n\t\tAttribute attribute = new DateAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetAllAttributes().put(name, attribute);\n\t}",
"public String getPrefix(INode prefixNode) {\n\t\tif (prefixNode instanceof ILeafNode) {\n\t\t\tif (((ILeafNode) prefixNode).isHidden() && prefixNode.getGrammarElement() != null)\n\t\t\t\treturn \"\";\n\t\t\treturn getNodeTextUpToCompletionOffset(prefixNode);\n\t\t}\n\t\tStringBuilder result = new StringBuilder(prefixNode.getTotalLength());\n\t\tdoComputePrefix((ICompositeNode) prefixNode, result);\n\t\treturn result.toString();\n\t}"
] |
Set new point coordinates somewhere on screen and apply new direction
@param position the point position to apply new values to | [
"void applyFreshParticleOnScreen(\n @NonNull final Scene scene,\n final int position\n ) {\n final int w = scene.getWidth();\n final int h = scene.getHeight();\n if (w == 0 || h == 0) {\n throw new IllegalStateException(\n \"Cannot generate particles if scene width or height is 0\");\n }\n\n final double direction = Math.toRadians(random.nextInt(360));\n final float dCos = (float) Math.cos(direction);\n final float dSin = (float) Math.sin(direction);\n final float x = random.nextInt(w);\n final float y = random.nextInt(h);\n final float speedFactor = newRandomIndividualParticleSpeedFactor();\n final float radius = newRandomIndividualParticleRadius(scene);\n\n scene.setParticleData(\n position,\n x,\n y,\n dCos,\n dSin,\n radius,\n speedFactor);\n }"
] | [
"public synchronized void shutdownTaskScheduler(){\n if (scheduler != null && !scheduler.isShutdown()) {\n scheduler.shutdown();\n logger.info(\"shutdowned the task scheduler. No longer accepting new tasks\");\n scheduler = null;\n }\n }",
"public void validate(final List<Throwable> validationErrors) {\n if (this.matchers == null) {\n validationErrors.add(new IllegalArgumentException(\n \"Matchers cannot be null. There should be at least a !acceptAll matcher\"));\n }\n if (this.matchers != null && this.matchers.isEmpty()) {\n validationErrors.add(new IllegalArgumentException(\n \"There are no url matchers defined. There should be at least a \" +\n \"!acceptAll matcher\"));\n }\n }",
"private synchronized void finishTransition(final InternalState current, final InternalState next) {\n internalSetState(getTransitionTask(next), current, next);\n transition();\n }",
"public static List<Integer> toIntegerList(List<String> strList, boolean failOnException){\n\t\tList<Integer> intList = new ArrayList<Integer>();\n\t\tfor(String str : strList){\n\t\t\ttry{\n\t\t\t\tintList.add(Integer.parseInt(str));\n\t\t\t}\n\t\t\tcatch(NumberFormatException nfe){\n\t\t\t\tif(failOnException){\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tintList.add(null);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn intList;\n\t}",
"static int lastArgMatchesVarg(Parameter[] params, ClassNode... args) {\n if (!isVargs(params)) return -1;\n // case length ==0 handled already\n // we have now two cases,\n // the argument is wrapped in the vargs array or\n // the argument is an array that can be used for the vargs part directly\n // we test only the wrapping part, since the non wrapping is done already\n ClassNode lastParamType = params[params.length - 1].getType();\n ClassNode ptype = lastParamType.getComponentType();\n ClassNode arg = args[args.length - 1];\n if (isNumberType(ptype) && isNumberType(arg) && !ptype.equals(arg)) return -1;\n return isAssignableTo(arg, ptype)?Math.min(getDistance(arg, lastParamType), getDistance(arg, ptype)):-1;\n }",
"public void end() {\n if (TransitionConfig.isPrintDebug()) {\n getTransitionStateHolder().end();\n getTransitionStateHolder().print();\n }\n\n for (int i = 0, size = mTransitionControls.size(); i < size; i++) {\n mTransitionControls.get(i).end();\n }\n }",
"public static nsacl6[] get(nitro_service service) throws Exception{\n\t\tnsacl6 obj = new nsacl6();\n\t\tnsacl6[] response = (nsacl6[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static <T> String join(Collection<T> col, String delim) {\n StringBuilder sb = new StringBuilder();\n Iterator<T> iter = col.iterator();\n if (iter.hasNext())\n sb.append(iter.next().toString());\n while (iter.hasNext()) {\n sb.append(delim);\n sb.append(iter.next().toString());\n }\n return sb.toString();\n }",
"public void writeTagsToJavaScript(Writer writer) throws IOException\n {\n writer.append(\"function fillTagService(tagService) {\\n\");\n writer.append(\"\\t// (name, isPrime, isPseudo, color), [parent tags]\\n\");\n for (Tag tag : definedTags.values())\n {\n writer.append(\"\\ttagService.registerTag(new Tag(\");\n escapeOrNull(tag.getName(), writer);\n writer.append(\", \");\n escapeOrNull(tag.getTitle(), writer);\n writer.append(\", \").append(\"\" + tag.isPrime())\n .append(\", \").append(\"\" + tag.isPseudo())\n .append(\", \");\n escapeOrNull(tag.getColor(), writer);\n writer.append(\")\").append(\", [\");\n\n // We only have strings, not references, so we're letting registerTag() getOrCreate() the tag.\n for (Tag parentTag : tag.getParentTags())\n {\n writer.append(\"'\").append(StringEscapeUtils.escapeEcmaScript(parentTag.getName())).append(\"',\");\n }\n writer.append(\"]);\\n\");\n }\n writer.append(\"}\\n\");\n }"
] |
Set value for given object field.
@param object object to be updated
@param field field name
@param value field value
@throws NoSuchMethodException if property writer is not available
@throws InvocationTargetException if property writer throws an exception
@throws IllegalAccessException if property writer is inaccessible | [
"public static void setField(Object object, String field, Object value) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {\n\t\tClass<?> clazz = object.getClass();\n\t\tMethod m = clazz.getMethod( PROPERTY_ACCESSOR_PREFIX_SET + capitalize( field ), value.getClass() );\n\t\tm.invoke( object, value );\n\t}"
] | [
"private void destroySession() {\n currentSessionId = 0;\n setAppLaunchPushed(false);\n getConfigLogger().verbose(getAccountId(),\"Session destroyed; Session ID is now 0\");\n clearSource();\n clearMedium();\n clearCampaign();\n clearWzrkParams();\n }",
"public static ModelNode addCurrentServerGroupsToHostInfoModel(boolean ignoreUnaffectedServerGroups, Resource hostModel, ModelNode model) {\n if (!ignoreUnaffectedServerGroups) {\n return model;\n }\n model.get(IGNORE_UNUSED_CONFIG).set(ignoreUnaffectedServerGroups);\n addServerGroupsToModel(hostModel, model);\n return model;\n }",
"@Override\n\tpublic boolean exists() {\n\t\ttry {\n\t\t\tInputStream inputStream = this.assetManager.open(this.fileName);\n\t\t\tif (inputStream != null) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\treturn false;\n\t\t}\n\t}",
"public void init( double diag[] ,\n double off[],\n int numCols ) {\n reset(numCols);\n\n this.diag = diag;\n this.off = off;\n }",
"@Override\n public boolean decompose( ZMatrixRMaj A )\n {\n if( A.numRows != A.numCols )\n throw new IllegalArgumentException(\"A must be square.\");\n if( A.numRows <= 0 )\n return false;\n\n QH = A;\n\n N = A.numCols;\n\n if( b.length < N*2 ) {\n b = new double[ N*2 ];\n gammas = new double[ N ];\n u = new double[ N*2 ];\n }\n return _decompose();\n }",
"public List<ProjectFile> readAll(InputStream is, boolean linkCrossProjectRelations) throws MPXJException\n {\n try\n {\n m_tables = new HashMap<String, List<Row>>();\n m_numberFormat = new DecimalFormat();\n\n processFile(is);\n\n List<Row> rows = getRows(\"project\", null, null);\n List<ProjectFile> result = new ArrayList<ProjectFile>(rows.size());\n List<ExternalPredecessorRelation> externalPredecessors = new ArrayList<ExternalPredecessorRelation>();\n for (Row row : rows)\n {\n setProjectID(row.getInt(\"proj_id\"));\n\n m_reader = new PrimaveraReader(m_taskUdfCounters, m_resourceUdfCounters, m_assignmentUdfCounters, m_resourceFields, m_wbsFields, m_taskFields, m_assignmentFields, m_aliases, m_matchPrimaveraWBS);\n ProjectFile project = m_reader.getProject();\n project.getEventManager().addProjectListeners(m_projectListeners);\n\n processProjectProperties();\n processUserDefinedFields();\n processCalendars();\n processResources();\n processResourceRates();\n processTasks();\n processPredecessors();\n processAssignments();\n\n externalPredecessors.addAll(m_reader.getExternalPredecessors());\n\n m_reader = null;\n project.updateStructure();\n\n result.add(project);\n }\n\n if (linkCrossProjectRelations)\n {\n for (ExternalPredecessorRelation externalRelation : externalPredecessors)\n {\n Task predecessorTask;\n // we could aggregate the project task id maps but that's likely more work\n // than just looping through the projects\n for (ProjectFile proj : result)\n {\n predecessorTask = proj.getTaskByUniqueID(externalRelation.getSourceUniqueID());\n if (predecessorTask != null)\n {\n Relation relation = externalRelation.getTargetTask().addPredecessor(predecessorTask, externalRelation.getType(), externalRelation.getLag());\n relation.setUniqueID(externalRelation.getUniqueID());\n break;\n }\n }\n // if predecessorTask not found the external task is outside of the file so ignore\n }\n }\n\n return result;\n }\n\n finally\n {\n m_reader = null;\n m_tables = null;\n m_currentTableName = null;\n m_currentTable = null;\n m_currentFieldNames = null;\n m_defaultCurrencyName = null;\n m_currencyMap.clear();\n m_numberFormat = null;\n m_defaultCurrencyData = null;\n }\n }",
"public void unbind(T service, Map<String, Object> props) {\n synchronized (serviceMap) {\n serviceMap.remove(ServiceUtil.getComparableForServiceRanking(props));\n updateSortedServices();\n }\n }",
"public float getNormalX(int vertex) {\n if (!hasNormals()) {\n throw new IllegalStateException(\"mesh has no normals\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_normals.getFloat(vertex * 3 * SIZEOF_FLOAT);\n }",
"@Override\n public void onNewState(CrawlerContext context, StateVertex vertex) {\n LOG.debug(\"onNewState\");\n StateBuilder state = outModelCache.addStateIfAbsent(vertex);\n visitedStates.putIfAbsent(state.getName(), vertex);\n\n saveScreenshot(context.getBrowser(), state.getName(), vertex);\n\n outputBuilder.persistDom(state.getName(), context.getBrowser().getUnStrippedDom());\n }"
] |
Reads a single record from the table.
@param buffer record data
@param table parent table | [
"private void readRecord(byte[] buffer, Table table)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, true, 16, \"\"));\n int deletedFlag = getShort(buffer, 0);\n if (deletedFlag != 0)\n {\n Map<String, Object> row = new HashMap<String, Object>();\n for (ColumnDefinition column : m_definition.getColumns())\n {\n Object value = column.read(0, buffer);\n //System.out.println(column.getName() + \": \" + value);\n row.put(column.getName(), value);\n }\n\n table.addRow(m_definition.getPrimaryKeyColumnName(), row);\n }\n }"
] | [
"public Gallery lookupGallery(String galleryId) throws FlickrException {\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LOOKUP_GALLERY);\r\n parameters.put(\"url\", galleryId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element galleryElement = response.getPayload();\r\n Gallery gallery = new Gallery();\r\n gallery.setId(galleryElement.getAttribute(\"id\"));\r\n gallery.setUrl(galleryElement.getAttribute(\"url\"));\r\n\r\n User owner = new User();\r\n owner.setId(galleryElement.getAttribute(\"owner\"));\r\n gallery.setOwner(owner);\r\n gallery.setCreateDate(galleryElement.getAttribute(\"date_create\"));\r\n gallery.setUpdateDate(galleryElement.getAttribute(\"date_update\"));\r\n gallery.setPrimaryPhotoId(galleryElement.getAttribute(\"primary_photo_id\"));\r\n gallery.setPrimaryPhotoServer(galleryElement.getAttribute(\"primary_photo_server\"));\r\n gallery.setVideoCount(galleryElement.getAttribute(\"count_videos\"));\r\n gallery.setPhotoCount(galleryElement.getAttribute(\"count_photos\"));\r\n gallery.setPrimaryPhotoFarm(galleryElement.getAttribute(\"farm\"));\r\n gallery.setPrimaryPhotoSecret(galleryElement.getAttribute(\"secret\"));\r\n\r\n gallery.setTitle(XMLUtilities.getChildValue(galleryElement, \"title\"));\r\n gallery.setDesc(XMLUtilities.getChildValue(galleryElement, \"description\"));\r\n return gallery;\r\n }",
"public static vpnclientlessaccesspolicy[] get(nitro_service service) throws Exception{\n\t\tvpnclientlessaccesspolicy obj = new vpnclientlessaccesspolicy();\n\t\tvpnclientlessaccesspolicy[] response = (vpnclientlessaccesspolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static JRDesignGroup getJRDesignGroup(DynamicJasperDesign jd, LayoutManager layoutManager, DJGroup group) {\n\t\tMap references = layoutManager.getReferencesMap();\n\t\tfor (Object o : references.keySet()) {\n\t\t\tString groupName = (String) o;\n\t\t\tDJGroup djGroup = (DJGroup) references.get(groupName);\n\t\t\tif (group == djGroup) {\n\t\t\t\treturn (JRDesignGroup) jd.getGroupsMap().get(groupName);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public static String replaceAnyOf(String value, String chars,\n char replacement) {\n char[] tmp = new char[value.length()];\n int pos = 0;\n for (int ix = 0; ix < tmp.length; ix++) {\n char ch = value.charAt(ix);\n if (chars.indexOf(ch) != -1)\n tmp[pos++] = replacement;\n else\n tmp[pos++] = ch;\n }\n return new String(tmp, 0, tmp.length);\n }",
"public PayloadBuilder category(final String category) {\n if (category != null) {\n aps.put(\"category\", category);\n } else {\n aps.remove(\"category\");\n }\n return this;\n }",
"public static Map<String, IDiagramPlugin>\n getLocalPluginsRegistry(ServletContext context) {\n if (LOCAL == null) {\n LOCAL = initializeLocalPlugins(context);\n }\n return LOCAL;\n }",
"boolean callbackUnregistered(final TransactionalProtocolClient old, final boolean shuttingDown) {\n // Disconnect the remote connection.\n // WFCORE-196 Do this out of the sync block to avoid deadlocks where in-flight requests can't\n // be informed that the channel has closed\n protocolClient.disconnected(old);\n\n synchronized (this) {\n // If the connection dropped without us stopping the process ask for reconnection\n if (!shuttingDown && requiredState == InternalState.SERVER_STARTED) {\n final InternalState state = internalState;\n if (state == InternalState.PROCESS_STOPPED\n || state == InternalState.PROCESS_STOPPING\n || state == InternalState.STOPPED) {\n // In case it stopped we don't reconnect\n return true;\n }\n // In case we are reloading, it will reconnect automatically\n if (state == InternalState.RELOADING) {\n return true;\n }\n try {\n ROOT_LOGGER.logf(DEBUG_LEVEL, \"trying to reconnect to %s current-state (%s) required-state (%s)\", serverName, state, requiredState);\n internalSetState(new ReconnectTask(), state, InternalState.SEND_STDIN);\n } catch (Exception e) {\n ROOT_LOGGER.logf(DEBUG_LEVEL, e, \"failed to send reconnect task\");\n }\n return false;\n } else {\n return true;\n }\n }\n }",
"public void add(Vector3d v1, Vector3d v2) {\n x = v1.x + v2.x;\n y = v1.y + v2.y;\n z = v1.z + v2.z;\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 }"
] |
Adds all options from the passed container to this container.
@param container a container with options to add | [
"public void addAll(OptionsContainerBuilder container) {\n\t\tfor ( Entry<Class<? extends Option<?, ?>>, ValueContainerBuilder<?, ?>> entry : container.optionValues.entrySet() ) {\n\t\t\taddAll( entry.getKey(), entry.getValue().build() );\n\t\t}\n\t}"
] | [
"private void primeCache() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) {\n if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck\n handleUpdate(new TrackMetadataUpdate(entry.getKey().player, entry.getValue()));\n }\n }\n }\n });\n }",
"public Float getFloat(String fieldName) {\n\t\ttry {\n\t\t\treturn hasValue(fieldName) ? Float.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a number.\", e);\n\t\t}\n\t}",
"private boolean checkZoneRequirement(HashMap<Integer, Integer> requiredRepFactor, int zoneId) {\n if(requiredRepFactor.containsKey(zoneId)) {\n if(requiredRepFactor.get(zoneId) == 0) {\n return false;\n } else {\n requiredRepFactor.put(zoneId, requiredRepFactor.get(zoneId) - 1);\n return true;\n }\n }\n return false;\n\n }",
"protected void getBatch(int batchSize){\r\n\r\n// if (numCalls == 0) {\r\n// for (int i = 0; i < 1538*\\15; i++) {\r\n// randGenerator.nextInt(this.dataDimension());\r\n// }\r\n// }\r\n// numCalls++;\r\n\r\n if (thisBatch == null || thisBatch.length != batchSize){\r\n thisBatch = new int[batchSize];\r\n }\r\n\r\n //-----------------------------\r\n //RANDOM WITH REPLACEMENT\r\n //-----------------------------\r\n if (sampleMethod.equals(SamplingMethod.RandomWithReplacement)){\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = randGenerator.nextInt(this.dataDimension()); //Just generate a random index\r\n// System.err.println(\"numCalls = \"+(numCalls++));\r\n }\r\n //-----------------------------\r\n //ORDERED\r\n //-----------------------------\r\n }else if(sampleMethod.equals(SamplingMethod.Ordered)){\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = (curElement + i) % this.dataDimension() ; //Take the next batchSize points in order\r\n }\r\n curElement = (curElement + batchSize) % this.dataDimension(); //watch out for overflow\r\n\r\n //-----------------------------\r\n //RANDOM WITHOUT REPLACEMENT\r\n //-----------------------------\r\n }else if(sampleMethod.equals(SamplingMethod.RandomWithoutReplacement)){\r\n //Declare the indices array if needed.\r\n if (allIndices == null || allIndices.size()!= this.dataDimension()){\r\n\r\n allIndices = new ArrayList<Integer>();\r\n for(int i=0;i<this.dataDimension();i++){\r\n allIndices.add(i);\r\n }\r\n Collections.shuffle(allIndices,randGenerator);\r\n }\r\n\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = allIndices.get((curElement + i) % allIndices.size()); //Grab the next batchSize indices\r\n }\r\n\r\n if (curElement + batchSize > this.dataDimension()){\r\n Collections.shuffle(Arrays.asList(allIndices),randGenerator); //Shuffle if we got to the end of the list\r\n }\r\n\r\n //watch out for overflow\r\n curElement = (curElement + batchSize) % allIndices.size(); //Rollover\r\n\r\n\r\n }else{\r\n System.err.println(\"NO SAMPLING METHOD SELECTED\");\r\n System.exit(1);\r\n }\r\n\r\n\r\n }",
"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 modified(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {\n declarationBinders.get(declarationBinderRef).update(declarationBinderRef);\n }",
"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 }",
"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 }",
"public void start() {\n nsLock.writeLock().lock();\n try {\n if (runnerThread != null) {\n return;\n }\n runnerThread =\n new Thread(new NamespaceChangeStreamRunner(\n new WeakReference<>(this), networkMonitor, logger));\n runnerThread.start();\n } finally {\n nsLock.writeLock().unlock();\n }\n }"
] |
Returns a long between interval
@param min Minimum value
@param max Maximum value
@return long number | [
"public static long randomLongBetween(long min, long max) {\n Random rand = new Random();\n return min + (long) (rand.nextDouble() * (max - min));\n }"
] | [
"public boolean setCurrentPage(final int page) {\n Log.d(TAG, \"setPageId pageId = %d\", page);\n return (page >= 0 && page < getCheckableCount()) && check(page);\n }",
"public static base_response add(nitro_service client, cachepolicylabel resource) throws Exception {\n\t\tcachepolicylabel addresource = new cachepolicylabel();\n\t\taddresource.labelname = resource.labelname;\n\t\taddresource.evaluates = resource.evaluates;\n\t\treturn addresource.add_resource(client);\n\t}",
"private void populateConstraints(Row row, Task task)\n {\n Date endDateMax = row.getTimestamp(\"ZGIVENENDDATEMAX_\");\n Date endDateMin = row.getTimestamp(\"ZGIVENENDDATEMIN_\");\n Date startDateMax = row.getTimestamp(\"ZGIVENSTARTDATEMAX_\");\n Date startDateMin = row.getTimestamp(\"ZGIVENSTARTDATEMIN_\");\n\n ConstraintType constraintType = null;\n Date constraintDate = null;\n\n if (endDateMax != null)\n {\n constraintType = ConstraintType.FINISH_NO_LATER_THAN;\n constraintDate = endDateMax;\n }\n\n if (endDateMin != null)\n {\n constraintType = ConstraintType.FINISH_NO_EARLIER_THAN;\n constraintDate = endDateMin;\n }\n\n if (endDateMin != null && endDateMin == endDateMax)\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = endDateMin;\n }\n\n if (startDateMax != null)\n {\n constraintType = ConstraintType.START_NO_LATER_THAN;\n constraintDate = startDateMax;\n }\n\n if (startDateMin != null)\n {\n constraintType = ConstraintType.START_NO_EARLIER_THAN;\n constraintDate = startDateMin;\n }\n\n if (startDateMin != null && startDateMin == endDateMax)\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = endDateMin;\n }\n\n task.setConstraintType(constraintType);\n task.setConstraintDate(constraintDate);\n }",
"public static Priority getInstance(int priority)\n {\n Priority result;\n\n if (priority >= LOWEST && priority <= DO_NOT_LEVEL && (priority % 100 == 0))\n {\n result = VALUE[(priority / 100) - 1];\n }\n else\n {\n result = new Priority(priority);\n }\n\n return (result);\n }",
"private boolean computeUWV() {\n bidiag.getDiagonal(diag,off);\n qralg.setMatrix(numRowsT,numColsT,diag,off);\n\n// long pointA = System.currentTimeMillis();\n // compute U and V matrices\n if( computeU )\n Ut = bidiag.getU(Ut,true,compact);\n if( computeV )\n Vt = bidiag.getV(Vt,true,compact);\n\n qralg.setFastValues(false);\n if( computeU )\n qralg.setUt(Ut);\n else\n qralg.setUt(null);\n if( computeV )\n qralg.setVt(Vt);\n else\n qralg.setVt(null);\n\n// long pointB = System.currentTimeMillis();\n\n boolean ret = !qralg.process();\n\n// long pointC = System.currentTimeMillis();\n// System.out.println(\" compute UV \"+(pointB-pointA)+\" QR = \"+(pointC-pointB));\n\n return ret;\n }",
"protected void addLabelForNumbers(ItemIdValue itemIdValue) {\n\n\t\tString qid = itemIdValue.getId();\n\n\t\ttry {\n\t\t\t// Fetch the online version of the item to make sure we edit the\n\t\t\t// current version:\n\t\t\tItemDocument currentItemDocument = (ItemDocument) dataFetcher\n\t\t\t\t\t.getEntityDocument(qid);\n\t\t\tif (currentItemDocument == null) {\n\t\t\t\tSystem.out.println(\"*** \" + qid\n\t\t\t\t\t\t+ \" could not be fetched. Maybe it has been deleted.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if we still have exactly one numeric value:\n\t\t\tQuantityValue number = currentItemDocument\n\t\t\t\t\t.findStatementQuantityValue(\"P1181\");\n\t\t\tif (number == null) {\n\t\t\t\tSystem.out.println(\"*** No unique numeric value for \" + qid);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if the item is in a known numeric class:\n\t\t\tif (!currentItemDocument.hasStatementValue(\"P31\", numberClasses)) {\n\t\t\t\tSystem.out\n\t\t\t\t\t\t.println(\"*** \"\n\t\t\t\t\t\t\t\t+ qid\n\t\t\t\t\t\t\t\t+ \" is not in a known class of integer numbers. Skipping.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if the value is integer and build label string:\n\t\t\tString numberString;\n\t\t\ttry {\n\t\t\t\tBigInteger intValue = number.getNumericValue()\n\t\t\t\t\t\t.toBigIntegerExact();\n\t\t\t\tnumberString = intValue.toString();\n\t\t\t} catch (ArithmeticException e) {\n\t\t\t\tSystem.out.println(\"*** Numeric value for \" + qid\n\t\t\t\t\t\t+ \" is not an integer: \" + number.getNumericValue());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Construct data to write:\n\t\t\tItemDocumentBuilder itemDocumentBuilder = ItemDocumentBuilder\n\t\t\t\t\t.forItemId(itemIdValue).withRevisionId(\n\t\t\t\t\t\t\tcurrentItemDocument.getRevisionId());\n\t\t\tArrayList<String> languages = new ArrayList<>(\n\t\t\t\t\tarabicNumeralLanguages.length);\n\t\t\tfor (int i = 0; i < arabicNumeralLanguages.length; i++) {\n\t\t\t\tif (!currentItemDocument.getLabels().containsKey(\n\t\t\t\t\t\tarabicNumeralLanguages[i])) {\n\t\t\t\t\titemDocumentBuilder.withLabel(numberString,\n\t\t\t\t\t\t\tarabicNumeralLanguages[i]);\n\t\t\t\t\tlanguages.add(arabicNumeralLanguages[i]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (languages.size() == 0) {\n\t\t\t\tSystem.out.println(\"*** Labels already complete for \" + qid);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogEntityModification(currentItemDocument.getEntityId(),\n\t\t\t\t\tnumberString, languages);\n\n\t\t\tdataEditor.editItemDocument(itemDocumentBuilder.build(), false,\n\t\t\t\t\t\"Set labels to numeric value (Task MB1)\");\n\t\t} catch (MediaWikiApiErrorException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"protected String getExtraSolrParams() {\n\n try {\n return m_configObject.getString(JSON_KEY_EXTRASOLRPARAMS);\n } catch (JSONException e) {\n if (null == m_baseConfig) {\n if (LOG.isInfoEnabled()) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_EXTRA_PARAMETERS_0), e);\n }\n return \"\";\n } else {\n return m_baseConfig.getGeneralConfig().getExtraSolrParams();\n }\n }\n }",
"@Nonnull\n public BiMap<String, String> getOutputMapper() {\n final BiMap<String, String> outputMapper = this.processor.getOutputMapperBiMap();\n if (outputMapper == null) {\n return HashBiMap.create();\n }\n return outputMapper;\n }",
"public ItemRequest<Tag> createInWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/tags\", workspace);\n return new ItemRequest<Tag>(this, Tag.class, path, \"POST\");\n }"
] |
Gets Widget bounds depth
@return depth | [
"public float getBoundsDepth() {\n if (mSceneObject != null) {\n GVRSceneObject.BoundingVolume v = mSceneObject.getBoundingVolume();\n return v.maxCorner.z - v.minCorner.z;\n }\n return 0f;\n }"
] | [
"public static <T> OptionalValue<T> ofNullable(T value) {\n return new GenericOptionalValue<T>(RUNTIME_SOURCE, DEFAULT_KEY, value);\n }",
"public Replication targetOauth(String consumerSecret, String consumerKey, String tokenSecret,\n String token) {\n targetOauth = new JsonObject();\n this.consumerSecret = consumerSecret;\n this.consumerKey = consumerKey;\n this.tokenSecret = tokenSecret;\n this.token = token;\n return this;\n }",
"static void init() {// NOPMD\n\n\t\tdetermineIfNTEventLogIsSupported();\n\n\t\tURL resource = null;\n\n\t\tfinal String configurationOptionStr = OptionConverter.getSystemProperty(DEFAULT_CONFIGURATION_KEY, null);\n\n\t\tif (configurationOptionStr != null) {\n\t\t\ttry {\n\t\t\t\tresource = new URL(configurationOptionStr);\n\t\t\t} catch (MalformedURLException ex) {\n\t\t\t\t// so, resource is not a URL:\n\t\t\t\t// attempt to get the resource from the class path\n\t\t\t\tresource = Loader.getResource(configurationOptionStr);\n\t\t\t}\n\t\t}\n\t\tif (resource == null) {\n\t\t\tresource = Loader.getResource(DEFAULT_CONFIGURATION_FILE); // NOPMD\n\t\t}\n\n\t\tif (resource == null) {\n\t\t\tSystem.err.println(\"[FoundationLogger] Can not find resource: \" + DEFAULT_CONFIGURATION_FILE); // NOPMD\n\t\t\tthrow new FoundationIOException(\"Can not find resource: \" + DEFAULT_CONFIGURATION_FILE); // NOPMD\n\t\t}\n\n\t\t// update the log manager to use the Foundation repository.\n\t\tfinal RepositorySelector foundationRepositorySelector = new FoundationRepositorySelector(FoundationLogFactory.foundationLogHierarchy);\n\t\tLogManager.setRepositorySelector(foundationRepositorySelector, null);\n\n\t\t// set logger to info so we always want to see these logs even if root\n\t\t// is set to ERROR.\n\t\tfinal Logger logger = getLogger(FoundationLogger.class);\n\n\t\tfinal String logPropFile = resource.getPath();\n\t\tlog4jConfigProps = getLogProperties(resource);\n\t\t\n\t\t// select and configure again so the loggers are created with the right\n\t\t// level after the repository selector was updated.\n\t\tOptionConverter.selectAndConfigure(resource, null, FoundationLogFactory.foundationLogHierarchy);\n\n\t\t// start watching for property changes\n\t\tsetUpPropFileReloading(logger, logPropFile, log4jConfigProps);\n\n\t\t// add syslog appender or windows event viewer appender\n//\t\tsetupOSSystemLog(logger, log4jConfigProps);\n\n\t\t// parseMarkerPatterns(log4jConfigProps);\n\t\t// parseMarkerPurePattern(log4jConfigProps);\n//\t\tudpateMarkerStructuredLogOverrideMap(logger);\n\n AbstractFoundationLoggingMarker.init();\n\n\t\tupdateSniffingLoggersLevel(logger);\n\n setupJULSupport(resource);\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 void executeInsert(ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"executeInsert: \" + obj);\r\n }\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n PreparedStatement stmt = null;\r\n try\r\n {\r\n stmt = sm.getInsertStatement(cld);\r\n if (stmt == null)\r\n {\r\n logger.error(\"getInsertStatement returned a null statement\");\r\n throw new PersistenceBrokerException(\"getInsertStatement returned a null statement\");\r\n }\r\n // before bind values perform autoincrement sequence columns\r\n assignAutoincrementSequences(cld, obj);\r\n sm.bindInsert(stmt, cld, obj);\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeInsert: \" + stmt);\r\n stmt.executeUpdate();\r\n // after insert read and assign identity columns\r\n assignAutoincrementIdentityColumns(cld, obj);\r\n\r\n // Harvest any return values.\r\n harvestReturnValues(cld.getInsertProcedure(), obj, stmt);\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n logger.error(\"PersistenceBrokerException during the execution of the insert: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch(SequenceManagerException e)\r\n {\r\n throw new PersistenceBrokerException(\"Error while try to assign identity value\", e);\r\n }\r\n catch (SQLException e)\r\n {\r\n final String sql = broker.serviceSqlGenerator().getPreparedInsertStatement(cld).getStatement();\r\n throw ExceptionHelper.generateException(e, sql, cld, logger, obj);\r\n }\r\n finally\r\n {\r\n sm.closeResources(stmt, null);\r\n }\r\n }",
"private List<String> parseRssFeedForeCast(String feed) {\n String[] result = feed.split(\"<br />\");\n List<String> returnList = new ArrayList<String>();\n String[] result2 = result[2].split(\"<BR />\");\n\n returnList.add(result2[3] + \"\\n\");\n returnList.add(result[3] + \"\\n\");\n returnList.add(result[4] + \"\\n\");\n returnList.add(result[5] + \"\\n\");\n returnList.add(result[6] + \"\\n\");\n\n return returnList;\n }",
"public static String getChildValue(Element element, String name) {\r\n return getValue(getChild(element, name));\r\n }",
"public static String[] allLowerCase(String... strings){\n\t\tString[] tmp = new String[strings.length];\n\t\tfor(int idx=0;idx<strings.length;idx++){\n\t\t\tif(strings[idx] != null){\n\t\t\t\ttmp[idx] = strings[idx].toLowerCase();\n\t\t\t}\n\t\t}\n\t\treturn tmp;\n\t}",
"public void execute() throws MojoExecutionException, MojoFailureException {\n try {\n Set<File> thriftFiles = findThriftFiles();\n\n final File outputDirectory = getOutputDirectory();\n ImmutableSet<File> outputFiles = findGeneratedFilesInDirectory(getOutputDirectory());\n\n Set<String> compileRoots = new HashSet<String>();\n compileRoots.add(\"scrooge\");\n\n if (thriftFiles.isEmpty()) {\n getLog().info(\"No thrift files to compile.\");\n } else if (checkStaleness && ((lastModified(thriftFiles) + staleMillis) < lastModified(outputFiles))) {\n getLog().info(\"Generated thrift files up to date, skipping compile.\");\n attachFiles(compileRoots);\n } else {\n outputDirectory.mkdirs();\n\n // Quick fix to fix issues with two mvn installs in a row (ie no clean)\n cleanDirectory(outputDirectory);\n\n getLog().info(format(\"compiling thrift files %s with Scrooge\", thriftFiles));\n synchronized(lock) {\n ScroogeRunner runner = new ScroogeRunner();\n Map<String, String> thriftNamespaceMap = new HashMap<String, String>();\n for (ThriftNamespaceMapping mapping : thriftNamespaceMappings) {\n thriftNamespaceMap.put(mapping.getFrom(), mapping.getTo());\n }\n\n // Include thrifts from resource as well.\n Set<File> includes = thriftIncludes;\n includes.add(getResourcesOutputDirectory());\n\n // Include thrift root\n final File thriftSourceRoot = getThriftSourceRoot();\n if (thriftSourceRoot != null && thriftSourceRoot.exists()) {\n includes.add(thriftSourceRoot);\n }\n\n runner.compile(\n getLog(),\n includeOutputDirectoryNamespace ? new File(outputDirectory, \"scrooge\") : outputDirectory,\n thriftFiles,\n includes,\n thriftNamespaceMap,\n language,\n thriftOpts);\n }\n attachFiles(compileRoots);\n }\n } catch (IOException e) {\n throw new MojoExecutionException(\"An IO error occurred\", e);\n }\n }"
] |
I pulled this out of internal store so that when doing multiple table
inheritance, i can recurse this function.
@param obj
@param cld
@param oid BRJ: what is it good for ???
@param insert
@param ignoreReferences | [
"private void storeToDb(Object obj, ClassDescriptor cld, Identity oid, boolean insert, boolean ignoreReferences)\n {\n // 1. link and store 1:1 references\n storeReferences(obj, cld, insert, ignoreReferences);\n\n Object[] pkValues = oid.getPrimaryKeyValues();\n if (!serviceBrokerHelper().assertValidPksForStore(cld.getPkFields(), pkValues))\n {\n // BRJ: fk values may be part of pk, but the are not known during\n // creation of Identity. so we have to get them here\n pkValues = serviceBrokerHelper().getKeyValues(cld, obj);\n if (!serviceBrokerHelper().assertValidPksForStore(cld.getPkFields(), pkValues))\n {\n String append = insert ? \" on insert\" : \" on update\" ;\n throw new PersistenceBrokerException(\"assertValidPkFields failed for Object of type: \" + cld.getClassNameOfObject() + append);\n }\n }\n\n // get super class cld then store it with the object\n /*\n now for multiple table inheritance\n 1. store super classes, topmost parent first\n 2. go down through heirarchy until current class\n 3. todo: store to full extent?\n\n// arminw: TODO: The extend-attribute feature dosn't work, should we remove this stuff?\n This if-clause will go up the inheritance heirarchy to store all the super classes.\n The id for the top most super class will be the id for all the subclasses too\n */\n if(cld.getSuperClass() != null)\n {\n\n ClassDescriptor superCld = getDescriptorRepository().getDescriptorFor(cld.getSuperClass());\n storeToDb(obj, superCld, oid, insert);\n // arminw: why this?? I comment out this section\n // storeCollections(obj, cld.getCollectionDescriptors(), insert);\n }\n\n // 2. store primitive typed attributes (Or is THIS step 3 ?)\n // if obj not present in db use INSERT\n if (insert)\n {\n dbAccess.executeInsert(cld, obj);\n if(oid.isTransient())\n {\n // Create a new Identity based on the current set of primary key values.\n oid = serviceIdentity().buildIdentity(cld, obj);\n }\n }\n // else use UPDATE\n else\n {\n try\n {\n dbAccess.executeUpdate(cld, obj);\n }\n catch(OptimisticLockException e)\n {\n // ensure that the outdated object be removed from cache\n objectCache.remove(oid);\n throw e;\n }\n }\n // cache object for symmetry with getObjectByXXX()\n // Add the object to the cache.\n objectCache.doInternalCache(oid, obj, ObjectCacheInternal.TYPE_WRITE);\n // 3. store 1:n and m:n associations\n if(!ignoreReferences) storeCollections(obj, cld, insert);\n }"
] | [
"private long getTotalTime(ProjectCalendarDateRanges exception)\n {\n long total = 0;\n for (DateRange range : exception)\n {\n total += getTime(range.getStart(), range.getEnd());\n }\n return (total);\n }",
"public static void main(String[] args) {\n DirectoryIterator iter = new DirectoryIterator(args);\n while(iter.hasNext())\n System.out.println(iter.next().getAbsolutePath());\n }",
"protected Object getProxyFromResultSet() throws PersistenceBrokerException\r\n {\r\n // 1. get Identity of current row:\r\n Identity oid = getIdentityFromResultSet();\r\n\r\n // 2. return a Proxy instance:\r\n return getBroker().createProxy(getItemProxyClass(), oid);\r\n }",
"public void visitOpen(String packaze, int access, String... modules) {\n if (mv != null) {\n mv.visitOpen(packaze, access, modules);\n }\n }",
"private List<ResourceField> getAllResourceExtendedAttributes()\n {\n ArrayList<ResourceField> result = new ArrayList<ResourceField>();\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_TEXT));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_START));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_FINISH));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_COST));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_DATE));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_FLAG));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_NUMBER));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_DURATION));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_OUTLINE_CODE));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_COST));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_DATE));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_DURATION));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_FLAG));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_NUMBER));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_TEXT));\n return result;\n }",
"private void processResponse(Response<ByteArray, Object> response, Pipeline pipeline) {\n if(response == null) {\n logger.warn(\"RoutingTimedout on waiting for async ops; parallelResponseToWait: \"\n + numNodesPendingResponse + \"; preferred-1: \" + (preferred - 1)\n + \"; quorumOK: \" + quorumSatisfied + \"; zoneOK: \" + zonesSatisfied);\n } else {\n numNodesPendingResponse = numNodesPendingResponse - 1;\n numResponsesGot = numResponsesGot + 1;\n if(response.getValue() instanceof Exception\n && !(response.getValue() instanceof ObsoleteVersionException)) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key + \"} handling async put error\");\n }\n if(response.getValue() instanceof QuotaExceededException) {\n /**\n * TODO Not sure if we need to count this Exception for\n * stats or silently ignore and just log a warning. While\n * QuotaExceededException thrown from other places mean the\n * operation failed, this one does not fail the operation\n * but instead stores slops. Introduce a new Exception in\n * client side to just monitor how mamy Async writes fail on\n * exceeding Quota?\n * \n */\n if(logger.isDebugEnabled()) {\n logger.debug(\"Received quota exceeded exception after a successful \"\n + pipeline.getOperation().getSimpleName() + \" call on node \"\n + response.getNode().getId() + \", store '\"\n + pipelineData.getStoreName() + \"', master-node '\"\n + pipelineData.getMaster().getId() + \"'\");\n }\n } else if(handleResponseError(response, pipeline, failureDetector)) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key\n + \"} severe async put error, exiting parallel put stage\");\n }\n\n return;\n }\n if(PipelineRoutedStore.isSlopableFailure(response.getValue())\n || response.getValue() instanceof QuotaExceededException) {\n /**\n * We want to slop ParallelPuts which fail due to\n * QuotaExceededException.\n * \n * TODO Though this is not the right way of doing things, in\n * order to avoid inconsistencies and data loss, we chose to\n * slop the quota failed parallel puts.\n * \n * As a long term solution - 1) either Quota management\n * should be hidden completely in a routing layer like\n * Coordinator or 2) the Server should be able to\n * distinguish between serial and parallel puts and should\n * only quota for serial puts\n * \n */\n pipelineData.getSynchronizer().tryDelegateSlop(response.getNode());\n }\n\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key + \"} handled async put error\");\n }\n\n } else {\n pipelineData.incrementSuccesses();\n failureDetector.recordSuccess(response.getNode(), response.getRequestTime());\n pipelineData.getZoneResponses().add(response.getNode().getZoneId());\n }\n }\n }",
"public static nspbr6[] get(nitro_service service) throws Exception{\n\t\tnspbr6 obj = new nspbr6();\n\t\tnspbr6[] response = (nspbr6[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private List<Point2D> merge(final List<Point2D> one, final List<Point2D> two) {\n final Set<Point2D> oneSet = new HashSet<Point2D>(one);\n for (Point2D item : two) {\n if (!oneSet.contains(item)) {\n one.add(item);\n }\n }\n return one;\n }",
"public RandomVariable getValues(double evaluationTime, LIBORMarketModel model) {\n\t\tif(evaluationTime > 0) {\n\t\t\tthrow new RuntimeException(\"Forward start evaluation currently not supported.\");\n\t\t}\n\n\t\t// Fetch the covariance model of the model\n\t\tLIBORCovarianceModel covarianceModel = model.getCovarianceModel();\n\n\t\t// We sum over all forward rates\n\t\tint numberOfComponents = covarianceModel.getLiborPeriodDiscretization().getNumberOfTimeSteps();\n\n\t\t// Accumulator\n\t\tRandomVariable\tintegratedLIBORCurvature\t= new RandomVariableFromDoubleArray(0.0);\n\t\tfor(int componentIndex = 0; componentIndex < numberOfComponents; componentIndex++) {\n\n\t\t\t// Integrate from 0 up to the fixing of the rate\n\t\t\tdouble timeEnd\t\t= covarianceModel.getLiborPeriodDiscretization().getTime(componentIndex);\n\t\t\tint timeEndIndex\t= covarianceModel.getTimeDiscretization().getTimeIndex(timeEnd);\n\n\t\t\t// If timeEnd is not in the time discretization we get timeEndIndex = -insertionPoint-1. In that case, we use the index prior to the insertionPoint\n\t\t\tif(timeEndIndex < 0) {\n\t\t\t\ttimeEndIndex = -timeEndIndex - 2;\n\t\t\t}\n\n\t\t\t// Sum squared second derivative of the variance for all components at this time step\n\t\t\tRandomVariable integratedLIBORCurvatureCurrentRate = new RandomVariableFromDoubleArray(0.0);\n\t\t\tfor(int timeIndex = 0; timeIndex < timeEndIndex-2; timeIndex++) {\n\t\t\t\tdouble timeStep1\t= covarianceModel.getTimeDiscretization().getTimeStep(timeIndex);\n\t\t\t\tdouble timeStep2\t= covarianceModel.getTimeDiscretization().getTimeStep(timeIndex+1);\n\n\t\t\t\tRandomVariable covarianceLeft\t\t= covarianceModel.getCovariance(timeIndex+0, componentIndex, componentIndex, null);\n\t\t\t\tRandomVariable covarianceCenter\t= covarianceModel.getCovariance(timeIndex+1, componentIndex, componentIndex, null);\n\t\t\t\tRandomVariable covarianceRight\t\t= covarianceModel.getCovariance(timeIndex+2, componentIndex, componentIndex, null);\n\n\t\t\t\t// Calculate second derivative\n\t\t\t\tRandomVariable curvatureSquared = covarianceRight.sub(covarianceCenter.mult(2.0)).add(covarianceLeft);\n\t\t\t\tcurvatureSquared = curvatureSquared.div(timeStep1 * timeStep2);\n\n\t\t\t\t// Take square\n\t\t\t\tcurvatureSquared = curvatureSquared.squared();\n\n\t\t\t\t// Integrate over time\n\t\t\t\tintegratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.add(curvatureSquared.mult(timeStep1));\n\t\t\t}\n\n\t\t\t// Empty intervall - skip\n\t\t\tif(timeEnd == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Average over time\n\t\t\tintegratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.div(timeEnd);\n\n\t\t\t// Take square root\n\t\t\tintegratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.sqrt();\n\n\t\t\t// Take max over all forward rates\n\t\t\tintegratedLIBORCurvature = integratedLIBORCurvature.add(integratedLIBORCurvatureCurrentRate);\n\t\t}\n\n\t\tintegratedLIBORCurvature = integratedLIBORCurvature.div(numberOfComponents);\n\t\treturn integratedLIBORCurvature.sub(tolerance).floor(0.0);\n\t}"
] |
Method signature without "public void" prefix
@return The method signature in String format | [
"public String getMethodSignature() {\n if (method != null) {\n String methodSignature = method.toString();\n return methodSignature.replaceFirst(\"public void \", \"\");\n }\n return null;\n }"
] | [
"private void writeResourceBaselines(Project.Resources.Resource xmlResource, Resource mpxjResource)\n {\n Project.Resources.Resource.Baseline baseline = m_factory.createProjectResourcesResourceBaseline();\n boolean populated = false;\n\n Number cost = mpxjResource.getBaselineCost();\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printCurrency(cost));\n }\n\n Duration work = mpxjResource.getBaselineWork();\n if (work != null && work.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, work));\n }\n\n if (populated)\n {\n xmlResource.getBaseline().add(baseline);\n baseline.setNumber(BigInteger.ZERO);\n }\n\n for (int loop = 1; loop <= 10; loop++)\n {\n baseline = m_factory.createProjectResourcesResourceBaseline();\n populated = false;\n\n cost = mpxjResource.getBaselineCost(loop);\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printCurrency(cost));\n }\n\n work = mpxjResource.getBaselineWork(loop);\n if (work != null && work.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, work));\n }\n\n if (populated)\n {\n xmlResource.getBaseline().add(baseline);\n baseline.setNumber(BigInteger.valueOf(loop));\n }\n }\n }",
"private <FT, FID> FT createForeignShell(ConnectionSource connectionSource, Object val, ObjectCache objectCache)\n\t\t\tthrows SQLException {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tDao<FT, FID> castDao = (Dao<FT, FID>) foreignDao;\n\t\tFT foreignObject = castDao.createObjectInstance();\n\t\tforeignIdField.assignField(connectionSource, foreignObject, val, false, objectCache);\n\t\treturn foreignObject;\n\t}",
"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 }",
"private void initDescriptor() throws CmsXmlException, CmsException {\n\n if (m_bundleType.equals(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR)) {\n m_desc = m_resource;\n } else {\n //First try to read from same folder like resource, if it fails use CmsMessageBundleEditorTypes.getDescriptor()\n try {\n m_desc = m_cms.readResource(m_sitepath + m_basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX);\n } catch (CmsVfsResourceNotFoundException e) {\n m_desc = CmsMessageBundleEditorTypes.getDescriptor(m_cms, m_basename);\n }\n }\n unmarshalDescriptor();\n\n }",
"private Object getParameter(String name, String value) throws ParseException, NumberFormatException {\n\t\tObject result = null;\n\t\tif (name.length() > 0) {\n\n\t\t\tswitch (name.charAt(0)) {\n\t\t\t\tcase 'i':\n\t\t\t\t\tif (null == value || value.length() == 0) {\n\t\t\t\t\t\tvalue = \"0\";\n\t\t\t\t\t}\n\t\t\t\t\tresult = new Integer(value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'f':\n\t\t\t\t\tif (name.startsWith(\"form\")) {\n\t\t\t\t\t\tresult = value;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (null == value || value.length() == 0) {\n\t\t\t\t\t\t\tvalue = \"0.0\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresult = new Double(value);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'd':\n\t\t\t\t\tif (null == value || value.length() == 0) {\n\t\t\t\t\t\tresult = null;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tSimpleDateFormat dateParser = new SimpleDateFormat(\"yyyy-MM-dd\");\n\t\t\t\t\t\tresult = dateParser.parse(value);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 't':\n\t\t\t\t\tif (null == value || value.length() == 0) {\n\t\t\t\t\t\tresult = null;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tSimpleDateFormat timeParser = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\t\t\t\t\t\tresult = timeParser.parse(value);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'b':\n\t\t\t\t\tresult = \"true\".equalsIgnoreCase(value) ? Boolean.TRUE : Boolean.FALSE;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tresult = value;\n\t\t\t}\n\t\t\tif (log.isDebugEnabled()) {\n\t\t\t\tif (result != null) {\n\t\t\t\t\tlog.debug(\n\t\t\t\t\t\t\t\"parameter \" + name + \" value \" + result + \" class \" + result.getClass().getName());\n\t\t\t\t} else {\n\t\t\t\t\tlog.debug(\"parameter\" + name + \"is null\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}",
"public static int serialize(final File directory, String name, Object obj) {\n try (FileOutputStream stream = new FileOutputStream(new File(directory, name))) {\n return serialize(stream, obj);\n } catch (IOException e) {\n throw new ReportGenerationException(e);\n }\n }",
"public String getTexCoordAttr(String texName)\n {\n GVRTexture tex = textures.get(texName);\n if (tex != null)\n {\n return tex.getTexCoordAttr();\n }\n return null;\n }",
"private ClassLoaderInterface getClassLoader() {\n\t\tMap<String, Object> application = ActionContext.getContext().getApplication();\n\t\tif (application != null) {\n\t\t\treturn (ClassLoaderInterface) application.get(ClassLoaderInterface.CLASS_LOADER_INTERFACE);\n\t\t}\n\t\treturn null;\n\t}",
"private void processColumns()\n {\n int fieldID = MPPUtility.getInt(m_data, m_headerOffset);\n m_headerOffset += 4;\n\n m_dataOffset = MPPUtility.getInt(m_data, m_headerOffset);\n m_headerOffset += 4;\n\n FieldType type = FieldTypeHelper.getInstance(fieldID);\n if (type.getDataType() != null)\n {\n processKnownType(type);\n }\n }"
] |
Creates a map of work pattern rows indexed by the primary key.
@param rows work pattern rows
@return work pattern map | [
"public Map<Integer, Row> createWorkPatternMap(List<Row> rows)\n {\n Map<Integer, Row> map = new HashMap<Integer, Row>();\n for (Row row : rows)\n {\n map.put(row.getInteger(\"WORK_PATTERNID\"), row);\n }\n return map;\n }"
] | [
"protected Query buildPrefetchQuery(Collection ids)\r\n {\r\n CollectionDescriptor cds = getCollectionDescriptor();\r\n QueryByCriteria query = buildPrefetchQuery(ids, cds.getForeignKeyFieldDescriptors(getItemClassDescriptor()));\r\n\r\n // check if collection must be ordered\r\n if (!cds.getOrderBy().isEmpty())\r\n {\r\n Iterator iter = cds.getOrderBy().iterator();\r\n while (iter.hasNext())\r\n {\r\n query.addOrderBy((FieldHelper) iter.next());\r\n }\r\n }\r\n\r\n return query;\r\n }",
"private void updateBundleDescriptorContent() throws CmsXmlException {\n\n if (m_descContent.hasLocale(Descriptor.LOCALE)) {\n m_descContent.removeLocale(Descriptor.LOCALE);\n }\n m_descContent.addLocale(m_cms, Descriptor.LOCALE);\n\n int i = 0;\n Property<Object> descProp;\n String desc;\n Property<Object> defaultValueProp;\n String defaultValue;\n Map<String, Item> keyItemMap = getKeyItemMap();\n List<String> keys = new ArrayList<String>(keyItemMap.keySet());\n Collections.sort(keys, CmsCaseInsensitiveStringComparator.getInstance());\n for (Object key : keys) {\n if ((null != key) && !key.toString().isEmpty()) {\n\n m_descContent.addValue(m_cms, Descriptor.N_MESSAGE, Descriptor.LOCALE, i);\n i++;\n String messagePrefix = Descriptor.N_MESSAGE + \"[\" + i + \"]/\";\n\n m_descContent.getValue(messagePrefix + Descriptor.N_KEY, Descriptor.LOCALE).setStringValue(\n m_cms,\n (String)key);\n descProp = keyItemMap.get(key).getItemProperty(TableProperty.DESCRIPTION);\n if ((null != descProp) && (null != descProp.getValue())) {\n desc = descProp.getValue().toString();\n m_descContent.getValue(messagePrefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).setStringValue(\n m_cms,\n desc);\n }\n\n defaultValueProp = keyItemMap.get(key).getItemProperty(TableProperty.DEFAULT);\n if ((null != defaultValueProp) && (null != defaultValueProp.getValue())) {\n defaultValue = defaultValueProp.getValue().toString();\n m_descContent.getValue(messagePrefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).setStringValue(\n m_cms,\n defaultValue);\n }\n\n }\n }\n\n }",
"public void removeSource(GVRAudioSource audioSource)\n {\n synchronized (mAudioSources)\n {\n audioSource.setListener(null);\n mAudioSources.remove(audioSource);\n }\n }",
"public Where<T, ID> exists(QueryBuilder<?, ?> subQueryBuilder) {\n\t\t// we do this to turn off the automatic addition of the ID column in the select column list\n\t\tsubQueryBuilder.enableInnerQuery();\n\t\taddClause(new Exists(new InternalQueryBuilderWrapper(subQueryBuilder)));\n\t\treturn this;\n\t}",
"public BoxStoragePolicy.Info getInfo(String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n URL url = STORAGE_POLICY_WITH_ID_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(),\n this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new Info(response.getJSON());\n }",
"public static void addTTLIndex(DBCollection collection, String field, int ttl) {\n if (ttl <= 0) {\n throw new IllegalArgumentException(\"TTL must be positive\");\n }\n collection.createIndex(new BasicDBObject(field, 1), new BasicDBObject(\"expireAfterSeconds\", ttl));\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 }",
"public LatLong getDestinationPoint(double bearing, double distance) {\n\n double brng = Math.toRadians(bearing);\n\n double lat1 = latToRadians();\n double lon1 = longToRadians();\n\n double lat2 = Math.asin(Math.sin(lat1)\n * Math.cos(distance / EarthRadiusMeters)\n + Math.cos(lat1) * Math.sin(distance / EarthRadiusMeters)\n * Math.cos(brng));\n\n double lon2 = lon1 + Math.atan2(Math.sin(brng)\n * Math.sin(distance / EarthRadiusMeters) * Math.cos(lat1),\n Math.cos(distance / EarthRadiusMeters)\n - Math.sin(lat1) * Math.sin(lat2));\n\n return new LatLong(Math.toDegrees(lat2), Math.toDegrees(lon2));\n\n }",
"public void updateGroupName(String newGroupName, int id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_GROUPS +\n \" SET \" + Constants.GROUPS_GROUP_NAME + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, newGroupName);\n statement.setInt(2, id);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }"
] |
Propagate onMotionOutside events to listeners
@param MotionEvent Android MotionEvent when nothing is picked | [
"protected void propagateOnMotionOutside(MotionEvent event)\n {\n if (mEventOptions.contains(EventOptions.SEND_TOUCH_EVENTS))\n {\n if (mEventOptions.contains(EventOptions.SEND_TO_LISTENERS))\n {\n getGVRContext().getEventManager().sendEvent(this, ITouchEvents.class, \"onMotionOutside\", this, event);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_SCENE) && (mScene != null))\n {\n getGVRContext().getEventManager().sendEvent(mScene, ITouchEvents.class, \"onMotionOutside\", this, event);\n }\n }\n }"
] | [
"private void addApiDocRoots(String packageListUrl) {\n\tBufferedReader br = null;\n\tpackageListUrl = fixApiDocRoot(packageListUrl);\n\ttry {\n\t URL url = new URL(packageListUrl + \"/package-list\");\n\t br = new BufferedReader(new InputStreamReader(url.openStream()));\n\t String line;\n\t while((line = br.readLine()) != null) {\n\t\tline = line + \".\";\n\t\tPattern pattern = Pattern.compile(line.replace(\".\", \"\\\\.\") + \"[^\\\\.]*\");\n\t\tapiDocMap.put(pattern, packageListUrl);\n\t }\n\t} catch(IOException e) {\n\t System.err.println(\"Errors happened while accessing the package-list file at \"\n\t\t + packageListUrl);\n\t} finally {\n\t if(br != null)\n\t\ttry {\n\t\t br.close();\n\t\t} catch (IOException e) {}\n\t}\n\t\n }",
"public void createContainer(String container) {\n\n ContainerController controller = this.platformContainers.get(container);\n if (controller == null) {\n\n // TODO make this configurable\n Profile p = new ProfileImpl();\n p.setParameter(Profile.PLATFORM_ID, PLATFORM_ID);\n p.setParameter(Profile.MAIN_HOST, MAIN_HOST);\n p.setParameter(Profile.MAIN_PORT, MAIN_PORT);\n p.setParameter(Profile.LOCAL_HOST, MAIN_HOST);\n int port = Integer.parseInt(MAIN_PORT);\n port = port + 1 + this.platformContainers.size();\n p.setParameter(Profile.LOCAL_PORT, Integer.toString(port));\n p.setParameter(Profile.CONTAINER_NAME, container);\n logger.fine(\"Creating container \" + container + \"...\");\n ContainerController agentContainer = this.runtime\n .createAgentContainer(p);\n this.platformContainers.put(container, agentContainer);\n logger.fine(\"Container \" + container + \" created successfully.\");\n } else {\n logger.fine(\"Container \" + container + \" is already created.\");\n }\n\n }",
"public static void closeWindow(Component component) {\n\n Window window = getWindow(component);\n if (window != null) {\n window.close();\n }\n }",
"private I_CmsFacetQueryItem parseFacetQueryItem(final String prefix) {\n\n I_CmsXmlContentValue query = m_xml.getValue(prefix + XML_ELEMENT_QUERY_FACET_QUERY_QUERY, m_locale);\n if (null != query) {\n String queryString = query.getStringValue(null);\n I_CmsXmlContentValue label = m_xml.getValue(prefix + XML_ELEMENT_QUERY_FACET_QUERY_LABEL, m_locale);\n String labelString = null != label ? label.getStringValue(null) : null;\n return new CmsFacetQueryItem(queryString, labelString);\n } else {\n return null;\n }\n }",
"public static base_responses unset(nitro_service client, Long clid[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (clid != null && clid.length > 0) {\n\t\t\tclusterinstance unsetresources[] = new clusterinstance[clid.length];\n\t\t\tfor (int i=0;i<clid.length;i++){\n\t\t\t\tunsetresources[i] = new clusterinstance();\n\t\t\t\tunsetresources[i].clid = clid[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"private void populateResource(Resource resource, Record record) throws MPXJException\n {\n String falseText = LocaleData.getString(m_locale, LocaleData.NO);\n\n int length = record.getLength();\n int[] model = m_resourceModel.getModel();\n\n for (int i = 0; i < length; i++)\n {\n int mpxFieldType = model[i];\n if (mpxFieldType == -1)\n {\n break;\n }\n\n String field = record.getString(i);\n\n if (field == null || field.length() == 0)\n {\n continue;\n }\n\n ResourceField resourceField = MPXResourceField.getMpxjField(mpxFieldType);\n switch (resourceField)\n {\n case OBJECTS:\n {\n resource.set(resourceField, record.getInteger(i));\n break;\n }\n\n case ID:\n {\n resource.setID(record.getInteger(i));\n break;\n }\n\n case UNIQUE_ID:\n {\n resource.setUniqueID(record.getInteger(i));\n break;\n }\n\n case MAX_UNITS:\n {\n resource.set(resourceField, record.getUnits(i));\n break;\n }\n\n case PERCENT_WORK_COMPLETE:\n case PEAK:\n {\n resource.set(resourceField, record.getPercentage(i));\n break;\n }\n\n case COST:\n case COST_PER_USE:\n case COST_VARIANCE:\n case BASELINE_COST:\n case ACTUAL_COST:\n case REMAINING_COST:\n {\n resource.set(resourceField, record.getCurrency(i));\n break;\n }\n\n case OVERTIME_RATE:\n case STANDARD_RATE:\n {\n resource.set(resourceField, record.getRate(i));\n break;\n }\n\n case REMAINING_WORK:\n case OVERTIME_WORK:\n case BASELINE_WORK:\n case ACTUAL_WORK:\n case WORK:\n case WORK_VARIANCE:\n {\n resource.set(resourceField, record.getDuration(i));\n break;\n }\n\n case ACCRUE_AT:\n {\n resource.set(resourceField, record.getAccrueType(i));\n break;\n }\n\n case LINKED_FIELDS:\n case OVERALLOCATED:\n {\n resource.set(resourceField, record.getBoolean(i, falseText));\n break;\n }\n\n default:\n {\n resource.set(resourceField, field);\n break;\n }\n }\n }\n\n if (m_projectConfig.getAutoResourceUniqueID() == true)\n {\n resource.setUniqueID(Integer.valueOf(m_projectConfig.getNextResourceUniqueID()));\n }\n\n if (m_projectConfig.getAutoResourceID() == true)\n {\n resource.setID(Integer.valueOf(m_projectConfig.getNextResourceID()));\n }\n\n //\n // Handle malformed MPX files - ensure we have a unique ID\n //\n if (resource.getUniqueID() == null)\n {\n resource.setUniqueID(resource.getID());\n }\n }",
"public static RgbaColor fromRgba(String rgba) {\n if (rgba.length() == 0) return getDefaultColor();\n\n String[] parts = getRgbaParts(rgba).split(\",\");\n if (parts.length == 4) {\n return new RgbaColor(parseInt(parts[0]),\n parseInt(parts[1]),\n parseInt(parts[2]),\n parseFloat(parts[3]));\n }\n else {\n return getDefaultColor();\n }\n }",
"private void buildMultiJoinTree(TableAlias left, ClassDescriptor cld, String name, boolean useOuterJoin)\r\n {\r\n DescriptorRepository repository = cld.getRepository();\r\n Class[] multiJoinedClasses = repository.getSubClassesMultipleJoinedTables(cld, false);\r\n\r\n for (int i = 0; i < multiJoinedClasses.length; i++)\r\n {\r\n ClassDescriptor subCld = repository.getDescriptorFor(multiJoinedClasses[i]);\r\n SuperReferenceDescriptor srd = subCld.getSuperReference();\r\n if (srd != null)\r\n {\r\n FieldDescriptor[] leftFields = subCld.getPkFields();\r\n FieldDescriptor[] rightFields = srd.getForeignKeyFieldDescriptors(subCld);\r\n TableAlias base_alias = getTableAliasForPath(name, null, null);\r\n\r\n String aliasName = String.valueOf(getAliasChar()) + m_aliasCount++;\r\n TableAlias right = new TableAlias(subCld, aliasName, false, null);\r\n\r\n Join join1to1 = new Join(left, leftFields, right, rightFields, useOuterJoin, \"subClass\");\r\n base_alias.addJoin(join1to1);\r\n\r\n buildMultiJoinTree(right, subCld, name, useOuterJoin);\r\n }\r\n }\r\n }",
"public static void extract( DMatrix src,\n int srcY0, int srcY1,\n int srcX0, int srcX1,\n DMatrix dst ) {\n ((ReshapeMatrix)dst).reshape(srcY1-srcY0,srcX1-srcX0);\n extract(src,srcY0,srcY1,srcX0,srcX1,dst,0,0);\n }"
] |
Get a log file and last relevant date, and check if the log file is relevant
@param currentLogFile The log file
@param lastRelevantDate The last date which files should be keeping since
@return false if the file should be deleted, true if it does not. | [
"private boolean relevant(File currentLogFile, GregorianCalendar lastRelevantDate) {\n\t\tString fileName=currentLogFile.getName();\n\t\tPattern p = Pattern.compile(APPENER_DATE_DEFAULT_PATTERN);\n\t\tMatcher m = p.matcher(fileName);\n\t\tif(m.find()){\n\t\t\tint year=Integer.parseInt(m.group(1));\n\t\t\tint month=Integer.parseInt(m.group(2));\n\t\t\tint dayOfMonth=Integer.parseInt(m.group(3));\n\t\t\tGregorianCalendar fileDate=new GregorianCalendar(year, month, dayOfMonth);\n\t\t\tfileDate.add(Calendar.MONTH,-1); //Because of Calendar save the month such that January is 0\n\t\t\treturn fileDate.compareTo(lastRelevantDate)>0;\n\t\t}\n\t\telse{\n\t\t\treturn false;\n\t\t}\n\t}"
] | [
"private void writeBooleanField(String fieldName, Object value) throws IOException\n {\n boolean val = ((Boolean) value).booleanValue();\n if (val)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }",
"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 }",
"public LatLong getLocation() {\n if (location == null) {\n location = new LatLong((JSObject) (getJSObject().getMember(\"location\")));\n }\n return location;\n }",
"public static base_response update(nitro_service client, snmpoption resource) throws Exception {\n\t\tsnmpoption updateresource = new snmpoption();\n\t\tupdateresource.snmpset = resource.snmpset;\n\t\tupdateresource.snmptraplogging = resource.snmptraplogging;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static 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 static nsrpcnode[] get(nitro_service service) throws Exception{\n\t\tnsrpcnode obj = new nsrpcnode();\n\t\tnsrpcnode[] response = (nsrpcnode[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void disableAll(int profileId, String client_uuid) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.CLIENT_PROFILE_ID + \" = ?\" +\n \" AND \" + Constants.CLIENT_CLIENT_UUID + \" =? \"\n );\n statement.setInt(1, profileId);\n statement.setString(2, client_uuid);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"public static protocolip_stats get(nitro_service service) throws Exception{\n\t\tprotocolip_stats obj = new protocolip_stats();\n\t\tprotocolip_stats[] response = (protocolip_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}",
"protected void appendTableWithJoins(TableAlias alias, StringBuffer where, StringBuffer buf)\r\n {\r\n int stmtFromPos = 0;\r\n byte joinSyntax = getJoinSyntaxType();\r\n\r\n if (joinSyntax == SQL92_JOIN_SYNTAX)\r\n {\r\n stmtFromPos = buf.length(); // store position of join (by: Terry Dexter)\r\n }\r\n\r\n if (alias == getRoot())\r\n {\r\n // BRJ: also add indirection table to FROM-clause for MtoNQuery \r\n if (getQuery() instanceof MtoNQuery)\r\n {\r\n MtoNQuery mnQuery = (MtoNQuery)m_query; \r\n buf.append(getTableAliasForPath(mnQuery.getIndirectionTable(), null).getTableAndAlias());\r\n buf.append(\", \");\r\n } \r\n buf.append(alias.getTableAndAlias());\r\n }\r\n else if (joinSyntax != SQL92_NOPAREN_JOIN_SYNTAX)\r\n {\r\n buf.append(alias.getTableAndAlias());\r\n }\r\n\r\n if (!alias.hasJoins())\r\n {\r\n return;\r\n }\r\n\r\n for (Iterator it = alias.iterateJoins(); it.hasNext();)\r\n {\r\n Join join = (Join) it.next();\r\n\r\n if (joinSyntax == SQL92_JOIN_SYNTAX)\r\n {\r\n appendJoinSQL92(join, where, buf);\r\n if (it.hasNext())\r\n {\r\n buf.insert(stmtFromPos, \"(\");\r\n buf.append(\")\");\r\n }\r\n }\r\n else if (joinSyntax == SQL92_NOPAREN_JOIN_SYNTAX)\r\n {\r\n appendJoinSQL92NoParen(join, where, buf);\r\n }\r\n else\r\n {\r\n appendJoin(where, buf, join);\r\n }\r\n\r\n }\r\n }"
] |
Computes the tree edit distance between trees t1 and t2.
@param t1
@param t2
@return tree edit distance between trees t1 and t2 | [
"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 void setFrustum(float fovy, float aspect, float znear, float zfar)\n {\n Matrix4f projMatrix = new Matrix4f();\n projMatrix.perspective((float) Math.toRadians(fovy), aspect, znear, zfar);\n setFrustum(projMatrix);\n }",
"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 }",
"public static base_responses disable(nitro_service client, String acl6name[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 disableresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tdisableresources[i] = new nsacl6();\n\t\t\t\tdisableresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, disableresources,\"disable\");\n\t\t}\n\t\treturn result;\n\t}",
"public float rotateToFaceCamera(final Widget widget) {\n final float yaw = getMainCameraRigYaw();\n GVRTransform t = getMainCameraRig().getHeadTransform();\n widget.rotateWithPivot(t.getRotationW(), 0, t.getRotationY(), 0, 0, 0, 0);\n return yaw;\n }",
"public static Statement open(String jndiPath) {\n try {\n Context ctx = new InitialContext();\n DataSource ds = (DataSource) ctx.lookup(jndiPath);\n Connection conn = ds.getConnection();\n return conn.createStatement();\n } catch (NamingException e) {\n throw new DukeException(\"No database configuration found via JNDI at \" +\n jndiPath, e);\n } catch (SQLException e) {\n throw new DukeException(\"Error connecting to database via \" +\n jndiPath, e);\n }\n }",
"public void waitForDeployments(@Observes(precedence = -100) AfterStart event, OpenShiftAdapter client,\n CEEnvironmentProcessor.TemplateDetails details, TestClass testClass, CubeOpenShiftConfiguration configuration, OpenShiftClient openshiftClient)\n throws Exception {\n if (testClass == null) {\n // nothing to do, since we're not in ClassScoped context\n return;\n }\n if (details == null) {\n log.warning(String.format(\"No environment for %s\", testClass.getName()));\n return;\n }\n log.info(String.format(\"Waiting for environment for %s\", testClass.getName()));\n try {\n delay(client, details.getResources());\n } catch (Throwable t) {\n throw new IllegalArgumentException(\"Error waiting for template resources to deploy: \" + testClass.getName(), t);\n }\n }",
"private ClassMatcher buildMatcher(String tagText) {\n\t// check there are at least @match <type> and a parameter\n\tString[] strings = StringUtil.tokenize(tagText);\n\tif (strings.length < 2) {\n\t System.err.println(\"Skipping uncomplete @match tag, type missing: \" + tagText + \" in view \" + viewDoc);\n\t return null;\n\t}\n\t\n\ttry {\n\t if (strings[0].equals(\"class\")) {\n\t\treturn new PatternMatcher(Pattern.compile(strings[1]));\n\t } else if (strings[0].equals(\"context\")) {\n\t\treturn new ContextMatcher(root, Pattern.compile(strings[1]), getGlobalOptions(), \n\t\t\tfalse);\n\t } else if (strings[0].equals(\"outgoingContext\")) {\n\t\treturn new ContextMatcher(root, Pattern.compile(strings[1]), getGlobalOptions(), \n\t\t\tfalse);\n\t } else if (strings[0].equals(\"interface\")) {\n\t\treturn new InterfaceMatcher(root, Pattern.compile(strings[1]));\n\t } else if (strings[0].equals(\"subclass\")) {\n\t\treturn new SubclassMatcher(root, Pattern.compile(strings[1]));\n\t } else {\n\t\tSystem.err.println(\"Skipping @match tag, unknown match type, in view \" + viewDoc);\n\t }\n\t} catch (PatternSyntaxException pse) {\n\t System.err.println(\"Skipping @match tag due to invalid regular expression '\" + tagText\n\t\t + \"'\" + \" in view \" + viewDoc);\n\t} catch (Exception e) {\n\t System.err.println(\"Skipping @match tag due to an internal error '\" + tagText\n\t\t + \"'\" + \" in view \" + viewDoc);\n\t e.printStackTrace();\n\t}\n\treturn null;\n }",
"public static base_responses reset(nitro_service client, appfwlearningdata resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwlearningdata resetresources[] = new appfwlearningdata[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tresetresources[i] = new appfwlearningdata();\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, resetresources,\"reset\");\n\t\t}\n\t\treturn result;\n\t}",
"public static void acceptsDir(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_D, OPT_DIR), \"directory path for input/output\")\n .withRequiredArg()\n .describedAs(\"dir-path\")\n .ofType(String.class);\n }"
] |
Determines whether or not two axially aligned bounding boxes in
the same coordinate space intersect.
@param bv1 first bounding volume to test.
@param bv2 second bounding volume to test.
@return true if the boxes intersect, false if not. | [
"protected boolean intersect(GVRSceneObject.BoundingVolume bv1, GVRSceneObject.BoundingVolume bv2)\n {\n return (bv1.maxCorner.x >= bv2.minCorner.x) &&\n (bv1.maxCorner.y >= bv2.minCorner.y) &&\n (bv1.maxCorner.z >= bv2.minCorner.z) &&\n (bv1.minCorner.x <= bv2.maxCorner.x) &&\n (bv1.minCorner.y <= bv2.maxCorner.y) &&\n (bv1.minCorner.z <= bv2.maxCorner.z);\n }"
] | [
"public synchronized void stop() throws DatastoreEmulatorException {\n // We intentionally don't check the internal state. If people want to try and stop the server\n // multiple times that's fine.\n stopEmulatorInternal();\n if (state != State.STOPPED) {\n state = State.STOPPED;\n if (projectDirectory != null) {\n try {\n Process process =\n new ProcessBuilder(\"rm\", \"-r\", projectDirectory.getAbsolutePath()).start();\n if (process.waitFor() != 0) {\n throw new IOException(\n \"Temporary project directory deletion exited with \" + process.exitValue());\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Could not delete temporary project directory\", e);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new IllegalStateException(\"Could not delete temporary project directory\", e);\n }\n }\n }\n }",
"public static cmppolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel obj = new cmppolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel response = (cmppolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private I_CmsFacetQueryItem parseFacetQueryItem(final String prefix) {\n\n I_CmsXmlContentValue query = m_xml.getValue(prefix + XML_ELEMENT_QUERY_FACET_QUERY_QUERY, m_locale);\n if (null != query) {\n String queryString = query.getStringValue(null);\n I_CmsXmlContentValue label = m_xml.getValue(prefix + XML_ELEMENT_QUERY_FACET_QUERY_LABEL, m_locale);\n String labelString = null != label ? label.getStringValue(null) : null;\n return new CmsFacetQueryItem(queryString, labelString);\n } else {\n return null;\n }\n }",
"public synchronized void stop() {\n if (isRunning()) {\n socket.get().close();\n socket.set(null);\n deliverLifecycleAnnouncement(logger, false);\n }\n }",
"int cancel(int downloadId) {\n\t\tsynchronized (mCurrentRequests) {\n\t\t\tfor (DownloadRequest request : mCurrentRequests) {\n\t\t\t\tif (request.getDownloadId() == downloadId) {\n\t\t\t\t\trequest.cancel();\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn 0;\n\t}",
"private String getJSONFromMap(Map<String, Object> propMap) {\n try {\n return new JSONObject(propMap).toString();\n } catch (Exception e) {\n return \"{}\";\n }\n }",
"private void executeProxyRequest(HttpMethod httpMethodProxyRequest,\n HttpServletRequest httpServletRequest,\n HttpServletResponse httpServletResponse, History history) {\n try {\n RequestInformation requestInfo = requestInformation.get();\n\n // Execute the request\n\n // set virtual host so the server knows how to direct the request\n // If the host header exists then this uses that value\n // Otherwise the hostname from the URL is used\n processVirtualHostName(httpMethodProxyRequest, httpServletRequest);\n cullDisabledPaths();\n\n // check for existence of ODO_PROXY_HEADER\n // finding it indicates a bad loop back through the proxy\n if (httpServletRequest.getHeader(Constants.ODO_PROXY_HEADER) != null) {\n logger.error(\"Request has looped back into the proxy. This will not be executed: {}\", httpServletRequest.getRequestURL());\n return;\n }\n\n // set ODO_PROXY_HEADER\n httpMethodProxyRequest.addRequestHeader(Constants.ODO_PROXY_HEADER, \"proxied\");\n\n requestInfo.blockRequest = hasRequestBlock();\n PluginResponse responseWrapper = new PluginResponse(httpServletResponse);\n requestInfo.jsonpCallback = stripJSONPToOutstr(httpServletRequest, responseWrapper);\n\n if (!requestInfo.blockRequest) {\n logger.info(\"Sending request to server\");\n\n history.setModified(requestInfo.modified);\n history.setRequestSent(true);\n\n executeRequest(httpMethodProxyRequest,\n httpServletRequest,\n responseWrapper,\n history);\n } else {\n history.setRequestSent(false);\n }\n\n logOriginalResponseHistory(responseWrapper, history);\n applyResponseOverrides(responseWrapper, httpServletRequest, httpMethodProxyRequest, history);\n // store history\n history.setModified(requestInfo.modified);\n logRequestHistory(httpMethodProxyRequest, responseWrapper, history);\n\n writeResponseOutput(responseWrapper, requestInfo.jsonpCallback);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }",
"public void set(Vector3d v1) {\n x = v1.x;\n y = v1.y;\n z = v1.z;\n }",
"public static <E> Filter<E> switchedFilter(Filter<E> filter, boolean negated) {\r\n return (new NegatedFilter<E>(filter, negated));\r\n }"
] |
Converts the string representation of the days bit field into an integer.
@param days string bit field
@return integer bit field | [
"public static Integer getDays(String days)\n {\n Integer result = null;\n if (days != null)\n {\n result = Integer.valueOf(Integer.parseInt(days, 2));\n }\n return (result);\n }"
] | [
"@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 String workDays(ProjectCalendar input)\n {\n StringBuilder result = new StringBuilder();\n DayType[] test = input.getDays(); // get the array from MPXJ ProjectCalendar\n for (DayType i : test)\n { // go through every day in the given array\n if (i == DayType.NON_WORKING)\n {\n result.append(\"N\"); // only put N for non-working day of the week\n }\n else\n {\n result.append(\"Y\"); // Assume WORKING day unless NON_WORKING\n }\n }\n return result.toString(); // According to USACE specs., exceptions will be specified in HOLI records\n }",
"public synchronized Object[] getIds() {\n String[] keys = getAllKeys();\n int size = keys.length + indexedProps.size();\n Object[] res = new Object[size];\n System.arraycopy(keys, 0, res, 0, keys.length);\n int i = keys.length;\n // now add all indexed properties\n for (Object index : indexedProps.keySet()) {\n res[i++] = index;\n }\n return res;\n }",
"public Constructor getZeroArgumentConstructor()\r\n {\r\n if (zeroArgumentConstructor == null && !alreadyLookedupZeroArguments)\r\n {\r\n try\r\n {\r\n zeroArgumentConstructor = getClassOfObject().getConstructor(NO_PARAMS);\r\n }\r\n catch (NoSuchMethodException e)\r\n {\r\n //no public zero argument constructor available let's try for a private/protected one\r\n try\r\n {\r\n zeroArgumentConstructor = getClassOfObject().getDeclaredConstructor(NO_PARAMS);\r\n\r\n //we found one, now let's make it accessible\r\n zeroArgumentConstructor.setAccessible(true);\r\n }\r\n catch (NoSuchMethodException e2)\r\n {\r\n //out of options, log the fact and let the method return null\r\n LoggerFactory.getDefaultLogger().warn(\r\n this.getClass().getName()\r\n + \": \"\r\n + \"No zero argument constructor defined for \"\r\n + this.getClassOfObject());\r\n }\r\n }\r\n\r\n alreadyLookedupZeroArguments = true;\r\n }\r\n\r\n return zeroArgumentConstructor;\r\n }",
"protected AssemblyResponse watchStatus() throws LocalOperationException, RequestException {\n AssemblyResponse response;\n do {\n response = getClient().getAssemblyByUrl(url);\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n throw new LocalOperationException(e);\n }\n } while (!response.isFinished());\n\n setState(State.FINISHED);\n return response;\n }",
"public static final Double getDouble(InputStream is) throws IOException\n {\n double result = Double.longBitsToDouble(getLong(is));\n if (Double.isNaN(result))\n {\n result = 0;\n }\n return Double.valueOf(result);\n }",
"public static Object setProperty( String key, String value ) {\n return prp.setProperty( key, value );\n }",
"public static spilloverpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tspilloverpolicy_stats obj = new spilloverpolicy_stats();\n\t\tobj.set_name(name);\n\t\tspilloverpolicy_stats response = (spilloverpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public List<ServerRedirect> deleteServerMapping(int serverMappingId) {\n ArrayList<ServerRedirect> servers = new ArrayList<ServerRedirect>();\n try {\n JSONArray serverArray = new JSONArray(doDelete(BASE_SERVER + \"/\" + serverMappingId, null));\n for (int i = 0; i < serverArray.length(); i++) {\n JSONObject jsonServer = serverArray.getJSONObject(i);\n ServerRedirect server = getServerRedirectFromJSON(jsonServer);\n if (server != null) {\n servers.add(server);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n\n return servers;\n }"
] |
Convenience extension, to generate traced code. | [
"public void generateTracedFile(final IFileSystemAccess2 fsa, final String path, final EObject rootTrace, final StringConcatenationClient code) {\n final CompositeGeneratorNode node = this.trace(rootTrace, code);\n this.generateTracedFile(fsa, path, node);\n }"
] | [
"private static void filter(String filename, String filtername) throws Exception\n {\n ProjectFile project = new UniversalProjectReader().read(filename);\n Filter filter = project.getFilters().getFilterByName(filtername);\n\n if (filter == null)\n {\n displayAvailableFilters(project);\n }\n else\n {\n System.out.println(filter);\n System.out.println();\n\n if (filter.isTaskFilter())\n {\n processTaskFilter(project, filter);\n }\n else\n {\n processResourceFilter(project, filter);\n }\n }\n }",
"public String getPermalinkForCurrentPage(CmsObject cms) {\n\n return getPermalink(cms, cms.getRequestContext().getUri(), cms.getRequestContext().getDetailContentId());\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public Map<DeckReference, WaveformDetail> getLoadedDetails() {\n ensureRunning();\n if (!isFindingDetails()) {\n throw new IllegalStateException(\"WaveformFinder is not configured to find waveform details.\");\n }\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, WaveformDetail>(detailHotCache));\n }",
"@PostConstruct\n public void init() {\n //init Bus and LifeCycle listeners\n if (bus != null && sendLifecycleEvent ) {\n ServerLifeCycleManager slcm = bus.getExtension(ServerLifeCycleManager.class);\n if (null != slcm) {\n ServiceListenerImpl svrListener = new ServiceListenerImpl();\n svrListener.setSendLifecycleEvent(sendLifecycleEvent);\n svrListener.setQueue(queue);\n svrListener.setMonitoringServiceClient(monitoringServiceClient);\n slcm.registerListener(svrListener);\n }\n\n ClientLifeCycleManager clcm = bus.getExtension(ClientLifeCycleManager.class);\n if (null != clcm) {\n ClientListenerImpl cltListener = new ClientListenerImpl();\n cltListener.setSendLifecycleEvent(sendLifecycleEvent);\n cltListener.setQueue(queue);\n cltListener.setMonitoringServiceClient(monitoringServiceClient);\n clcm.registerListener(cltListener);\n }\n }\n\n if(executorQueueSize == 0) {\r\n \texecutor = Executors.newFixedThreadPool(this.executorPoolSize);\n }else{\r\n executor = new ThreadPoolExecutor(executorPoolSize, executorPoolSize, 0, TimeUnit.SECONDS, \r\n \t\tnew LinkedBlockingQueue<Runnable>(executorQueueSize), Executors.defaultThreadFactory(), \r\n \t\t\tnew RejectedExecutionHandlerImpl());\r\n }\r\n\n scheduler = new Timer();\n scheduler.scheduleAtFixedRate(new TimerTask() {\n public void run() {\n sendEventsFromQueue();\n }\n }, 0, getDefaultInterval());\n }",
"protected Integer parseOptionalIntValue(final String path) {\n\n final I_CmsXmlContentValue value = m_xml.getValue(path, m_locale);\n if (value == null) {\n return null;\n } else {\n final String stringValue = value.getStringValue(null);\n try {\n final Integer intValue = Integer.valueOf(stringValue);\n return intValue;\n } catch (final NumberFormatException e) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_OPTIONAL_INTEGER_MISSING_1, path), e);\n return null;\n }\n }\n }",
"protected void modify(Transaction t) {\n try {\n this.lock.writeLock().lock();\n t.perform();\n } finally {\n this.lock.writeLock().unlock();\n }\n }",
"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 static base_response rename(nitro_service client, cmppolicylabel resource, String new_labelname) throws Exception {\n\t\tcmppolicylabel renameresource = new cmppolicylabel();\n\t\trenameresource.labelname = resource.labelname;\n\t\treturn renameresource.rename_resource(client,new_labelname);\n\t}",
"public void modified(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {\n declarationBinders.get(declarationBinderRef).update(declarationBinderRef);\n }"
] |
Connect and register at the remote domain controller.
@return connection the established connection
@throws IOException | [
"protected Connection openConnection() throws IOException {\n // Perhaps this can just be done once?\n CallbackHandler callbackHandler = null;\n SSLContext sslContext = null;\n if (realm != null) {\n sslContext = realm.getSSLContext();\n CallbackHandlerFactory handlerFactory = realm.getSecretCallbackHandlerFactory();\n if (handlerFactory != null) {\n String username = this.username != null ? this.username : localHostName;\n callbackHandler = handlerFactory.getCallbackHandler(username);\n }\n }\n final ProtocolConnectionConfiguration config = ProtocolConnectionConfiguration.copy(configuration);\n config.setCallbackHandler(callbackHandler);\n config.setSslContext(sslContext);\n config.setUri(uri);\n\n AuthenticationContext authenticationContext = this.authenticationContext != null ? this.authenticationContext : AuthenticationContext.captureCurrent();\n\n // Connect\n try {\n return authenticationContext.run((PrivilegedExceptionAction<Connection>) () -> ProtocolConnectionUtils.connectSync(config));\n } catch (PrivilegedActionException e) {\n if (e.getCause() instanceof IOException) {\n throw (IOException) e.getCause();\n }\n throw new IOException(e);\n }\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 PlacesList<Place> placesForUser(int placeType, String woeId, String placeId, String threshold, Date minUploadDate, Date maxUploadDate,\r\n Date minTakenDate, Date maxTakenDate) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n PlacesList<Place> placesList = new PlacesList<Place>();\r\n parameters.put(\"method\", METHOD_PLACES_FOR_USER);\r\n\r\n parameters.put(\"place_type\", intPlaceTypeToString(placeType));\r\n if (placeId != null) {\r\n parameters.put(\"place_id\", placeId);\r\n }\r\n if (woeId != null) {\r\n parameters.put(\"woe_id\", woeId);\r\n }\r\n if (threshold != null) {\r\n parameters.put(\"threshold\", threshold);\r\n }\r\n if (minUploadDate != null) {\r\n parameters.put(\"min_upload_date\", Long.toString(minUploadDate.getTime() / 1000L));\r\n }\r\n if (maxUploadDate != null) {\r\n parameters.put(\"max_upload_date\", Long.toString(maxUploadDate.getTime() / 1000L));\r\n }\r\n if (minTakenDate != null) {\r\n parameters.put(\"min_taken_date\", ((DateFormat) SearchParameters.MYSQL_DATE_FORMATS.get()).format(minTakenDate));\r\n }\r\n if (maxTakenDate != null) {\r\n parameters.put(\"max_taken_date\", ((DateFormat) SearchParameters.MYSQL_DATE_FORMATS.get()).format(maxTakenDate));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element placesElement = response.getPayload();\r\n NodeList placesNodes = placesElement.getElementsByTagName(\"place\");\r\n placesList.setPage(\"1\");\r\n placesList.setPages(\"1\");\r\n placesList.setPerPage(\"\" + placesNodes.getLength());\r\n placesList.setTotal(\"\" + placesNodes.getLength());\r\n for (int i = 0; i < placesNodes.getLength(); i++) {\r\n Element placeElement = (Element) placesNodes.item(i);\r\n placesList.add(parsePlace(placeElement));\r\n }\r\n return placesList;\r\n }",
"public boolean isEmpty() {\n\t\tint snapshotSize = cleared ? 0 : snapshot.size();\n\t\t//nothing in both\n\t\tif ( snapshotSize == 0 && currentState.isEmpty() ) {\n\t\t\treturn true;\n\t\t}\n\t\t//snapshot bigger than changeset\n\t\tif ( snapshotSize > currentState.size() ) {\n\t\t\treturn false;\n\t\t}\n\t\treturn size() == 0;\n\t}",
"public static base_response add(nitro_service client, dnsaaaarec resource) throws Exception {\n\t\tdnsaaaarec addresource = new dnsaaaarec();\n\t\taddresource.hostname = resource.hostname;\n\t\taddresource.ipv6address = resource.ipv6address;\n\t\taddresource.ttl = resource.ttl;\n\t\treturn addresource.add_resource(client);\n\t}",
"public void createProductDelivery(final String productLogicalName, final Delivery delivery, final String user, final String password) throws GrapesCommunicationException, AuthenticationException { \n \tfinal Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getProductDelivery(productLogicalName));\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, delivery);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to create a delivery\";\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 }",
"Object readResolve() throws ObjectStreamException {\n Bean<?> bean = Container.instance(contextId).services().get(ContextualStore.class).<Bean<Object>, Object>getContextual(beanId);\n if (bean == null) {\n throw BeanLogger.LOG.proxyDeserializationFailure(beanId);\n }\n return Container.instance(contextId).deploymentManager().getClientProxyProvider().getClientProxy(bean);\n }",
"public static String createFirstLowCaseName(String scenarioDescription) {\n String[] words = scenarioDescription.trim().split(\" \");\n String name = \"\";\n for (int i = 0; i < words.length; i++) {\n name += changeFirstLetterToCapital(words[i]);\n }\n return changeFirstLetterToLowerCase(name);\n }",
"static AzureAsyncOperation fromResponse(SerializerAdapter<?> serializerAdapter, Response<ResponseBody> response) throws CloudException {\n AzureAsyncOperation asyncOperation = null;\n String rawString = null;\n if (response.body() != null) {\n try {\n rawString = response.body().string();\n asyncOperation = serializerAdapter.deserialize(rawString, AzureAsyncOperation.class);\n } catch (IOException exception) {\n // Exception will be handled below\n } finally {\n response.body().close();\n }\n }\n if (asyncOperation == null || asyncOperation.status() == null) {\n throw new CloudException(\"polling response does not contain a valid body: \" + rawString, response);\n }\n else {\n asyncOperation.rawString = rawString;\n }\n return asyncOperation;\n }",
"public static Cluster greedyShufflePartitions(final Cluster nextCandidateCluster,\n final int greedyAttempts,\n final int greedySwapMaxPartitionsPerNode,\n final int greedySwapMaxPartitionsPerZone,\n List<Integer> greedySwapZoneIds,\n List<StoreDefinition> storeDefs) {\n List<Integer> zoneIds = null;\n if(greedySwapZoneIds.isEmpty()) {\n zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds());\n } else {\n zoneIds = new ArrayList<Integer>(greedySwapZoneIds);\n }\n\n List<Integer> nodeIds = new ArrayList<Integer>();\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n\n for(int i = 0; i < greedyAttempts; i++) {\n\n // Iterate over zone ids to decide which node ids to include for\n // intra-zone swapping.\n // In future, if there is a need to support inter-zone swapping,\n // then just remove the\n // zone specific logic that populates nodeIdSet and add all nodes\n // from across all zones.\n\n int zoneIdOffset = i % zoneIds.size();\n Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset));\n nodeIds = new ArrayList<Integer>(nodeIdSet);\n\n Collections.shuffle(zoneIds, new Random(System.currentTimeMillis()));\n Cluster shuffleResults = swapGreedyRandomPartitions(returnCluster,\n nodeIds,\n greedySwapMaxPartitionsPerNode,\n greedySwapMaxPartitionsPerZone,\n storeDefs);\n\n double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility();\n System.out.println(\"Swap improved max-min ratio: \" + currentUtility + \" -> \"\n + nextUtility + \" (swap attempt \" + i + \" in zone \"\n + zoneIds.get(zoneIdOffset) + \")\");\n returnCluster = shuffleResults;\n currentUtility = nextUtility;\n }\n return returnCluster;\n }"
] |
Extract data for a single calendar.
@param row calendar data | [
"private void processCalendar(MapRow row)\n {\n ProjectCalendar calendar = m_project.addCalendar();\n\n Map<UUID, List<DateRange>> dayTypeMap = processDayTypes(row.getRows(\"DAY_TYPES\"));\n\n calendar.setName(row.getString(\"NAME\"));\n\n processRanges(dayTypeMap.get(row.getUUID(\"SUNDAY_DAY_TYPE\")), calendar.addCalendarHours(Day.SUNDAY));\n processRanges(dayTypeMap.get(row.getUUID(\"MONDAY_DAY_TYPE\")), calendar.addCalendarHours(Day.MONDAY));\n processRanges(dayTypeMap.get(row.getUUID(\"TUESDAY_DAY_TYPE\")), calendar.addCalendarHours(Day.TUESDAY));\n processRanges(dayTypeMap.get(row.getUUID(\"WEDNESDAY_DAY_TYPE\")), calendar.addCalendarHours(Day.WEDNESDAY));\n processRanges(dayTypeMap.get(row.getUUID(\"THURSDAY_DAY_TYPE\")), calendar.addCalendarHours(Day.THURSDAY));\n processRanges(dayTypeMap.get(row.getUUID(\"FRIDAY_DAY_TYPE\")), calendar.addCalendarHours(Day.FRIDAY));\n processRanges(dayTypeMap.get(row.getUUID(\"SATURDAY_DAY_TYPE\")), calendar.addCalendarHours(Day.SATURDAY));\n\n for (MapRow assignment : row.getRows(\"DAY_TYPE_ASSIGNMENTS\"))\n {\n Date date = assignment.getDate(\"DATE\");\n processRanges(dayTypeMap.get(assignment.getUUID(\"DAY_TYPE_UUID\")), calendar.addCalendarException(date, date));\n }\n\n m_calendarMap.put(row.getUUID(\"UUID\"), calendar);\n }"
] | [
"protected void createParentXmlElements(CmsXmlContent xmlContent, String xmlPath, Locale l) {\n\n if (CmsXmlUtils.isDeepXpath(xmlPath)) {\n String parentPath = CmsXmlUtils.removeLastXpathElement(xmlPath);\n if (null == xmlContent.getValue(parentPath, l)) {\n createParentXmlElements(xmlContent, parentPath, l);\n xmlContent.addValue(m_cms, parentPath, l, CmsXmlUtils.getXpathIndexInt(parentPath) - 1);\n }\n }\n\n }",
"public static Pair<String, String> stringIntern(Pair<String, String> p) {\r\n return new MutableInternedPair(p);\r\n }",
"static ParsedHost validateHostImpl(HostName fromHost) throws HostNameException {\n\t\tfinal String str = fromHost.toString();\n\t\tHostNameParameters validationOptions = fromHost.getValidationOptions();\n\t\treturn validateHost(fromHost, str, validationOptions);\n\t}",
"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 }",
"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}",
"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 }",
"public CollectionRequest<Task> findByProject(String projectId) {\n \n String path = String.format(\"/projects/%s/tasks\", projectId);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"public void strokeRoundRectangle(Rectangle rect, Color color, float linewidth, float r) {\n\t\ttemplate.saveState();\n\t\tsetStroke(color, linewidth, null);\n\t\ttemplate.roundRectangle(origX + rect.getLeft(), origY + rect.getBottom(), rect.getWidth(), rect.getHeight(), r);\n\t\ttemplate.stroke();\n\t\ttemplate.restoreState();\n\t}",
"public static final double round(double value, double precision)\n {\n precision = Math.pow(10, precision);\n return Math.round(value * precision) / precision;\n }"
] |
Merge two ExecutionStatistics into one. This method is private in order not to be synchronized (merging.
@param otherStatistics | [
"private void merge(ExecutionStatistics otherStatistics) {\n for (String s : otherStatistics.executionInfo.keySet())\n {\n TimingData thisStats = this.executionInfo.get(s);\n TimingData otherStats = otherStatistics.executionInfo.get(s);\n if(thisStats == null) {\n this.executionInfo.put(s,otherStats);\n } else {\n thisStats.merge(otherStats);\n }\n\n }\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 CssSel sel(String selector, String value) {\n\treturn j.sel(selector, value);\n }",
"private static AbstractIndex constructLiborIndex(String forwardCurveName, Schedule schedule) {\n\n\t\tif(forwardCurveName != null) {\n\n\t\t\t//determine average fixing offset and period length\n\t\t\tdouble fixingOffset = 0;\n\t\t\tdouble periodLength = 0;\n\n\t\t\tfor(int i = 0; i < schedule.getNumberOfPeriods(); i++) {\n\t\t\t\tfixingOffset *= ((double) i) / (i+1);\n\t\t\t\tfixingOffset += (schedule.getPeriodStart(i) - schedule.getFixing(i)) / (i+1);\n\n\t\t\t\tperiodLength *= ((double) i) / (i+1);\n\t\t\t\tperiodLength += schedule.getPeriodLength(i) / (i+1);\n\t\t\t}\n\n\t\t\treturn new LIBORIndex(forwardCurveName, fixingOffset, periodLength);\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}",
"protected static BoxCollaboration.Info create(BoxAPIConnection api, JsonObject accessibleBy, JsonObject item,\n BoxCollaboration.Role role, Boolean notify, Boolean canViewPath) {\n\n\n String queryString = \"\";\n if (notify != null) {\n queryString = new QueryStringBuilder().appendParam(\"notify\", notify.toString()).toString();\n }\n URL url;\n if (queryString.length() > 0) {\n url = COLLABORATIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString);\n } else {\n url = COLLABORATIONS_URL_TEMPLATE.build(api.getBaseURL());\n }\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"item\", item);\n requestJSON.add(\"accessible_by\", accessibleBy);\n requestJSON.add(\"role\", role.toJSONString());\n if (canViewPath != null) {\n requestJSON.add(\"can_view_path\", canViewPath.booleanValue());\n }\n\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxCollaboration newCollaboration = new BoxCollaboration(api, responseJSON.get(\"id\").asString());\n return newCollaboration.new Info(responseJSON);\n }",
"public String toUriString(final java.net.URI uri) {\n return this.toUriString(URI.createURI(uri.normalize().toString()));\n }",
"void onDrawEye(int eye, int swapChainIndex, boolean use_multiview) {\n mCurrentEye = eye;\n if (!(mSensoredScene == null || !mMainScene.equals(mSensoredScene))) {\n GVRCameraRig mainCameraRig = mMainScene.getMainCameraRig();\n\n if (use_multiview) {\n\n if (DEBUG_STATS) {\n mTracerDrawEyes1.enter(); // this eye is drawn first\n mTracerDrawEyes2.enter();\n }\n GVRRenderTarget renderTarget = mRenderBundle.getRenderTarget(EYE.MULTIVIEW, swapChainIndex);\n GVRCamera camera = mMainScene.getMainCameraRig().getCenterCamera();\n GVRCamera left_camera = mMainScene.getMainCameraRig().getLeftCamera();\n renderTarget.cullFromCamera(mMainScene, camera,mRenderBundle.getShaderManager());\n\n captureCenterEye(renderTarget, true);\n capture3DScreenShot(renderTarget, true);\n\n renderTarget.render(mMainScene, left_camera, mRenderBundle.getShaderManager(),mRenderBundle.getPostEffectRenderTextureA(),\n mRenderBundle.getPostEffectRenderTextureB());\n\n captureRightEye(renderTarget, true);\n captureLeftEye(renderTarget, true);\n\n captureFinish();\n\n if (DEBUG_STATS) {\n mTracerDrawEyes1.leave();\n mTracerDrawEyes2.leave();\n }\n\n\n } else {\n\n if (eye == 1) {\n if (DEBUG_STATS) {\n mTracerDrawEyes1.enter();\n }\n\n GVRCamera rightCamera = mainCameraRig.getRightCamera();\n GVRRenderTarget renderTarget = mRenderBundle.getRenderTarget(EYE.RIGHT, swapChainIndex);\n renderTarget.render(mMainScene, rightCamera, mRenderBundle.getShaderManager(), mRenderBundle.getPostEffectRenderTextureA(),\n mRenderBundle.getPostEffectRenderTextureB());\n captureRightEye(renderTarget, false);\n\n captureFinish();\n if (DEBUG_STATS) {\n mTracerDrawEyes1.leave();\n mTracerDrawEyes.leave();\n }\n } else {\n if (DEBUG_STATS) {\n mTracerDrawEyes1.leave();\n mTracerDrawEyes.leave();\n }\n\n\n GVRRenderTarget renderTarget = mRenderBundle.getRenderTarget(EYE.LEFT, swapChainIndex);\n GVRCamera leftCamera = mainCameraRig.getLeftCamera();\n\n capture3DScreenShot(renderTarget, false);\n\n renderTarget.cullFromCamera(mMainScene, mainCameraRig.getCenterCamera(), mRenderBundle.getShaderManager());\n captureCenterEye(renderTarget, false);\n renderTarget.render(mMainScene, leftCamera, mRenderBundle.getShaderManager(), mRenderBundle.getPostEffectRenderTextureA(), mRenderBundle.getPostEffectRenderTextureB());\n\n captureLeftEye(renderTarget, false);\n\n if (DEBUG_STATS) {\n mTracerDrawEyes2.leave();\n }\n }\n }\n }\n }",
"public void newLineIfNotEmpty() {\n\t\tfor (int i = segments.size() - 1; i >= 0; i--) {\n\t\t\tString segment = segments.get(i);\n\t\t\tif (lineDelimiter.equals(segment)) {\n\t\t\t\tsegments.subList(i + 1, segments.size()).clear();\n\t\t\t\tcachedToString = null;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (int j = 0; j < segment.length(); j++) {\n\t\t\t\tif (!WhitespaceMatcher.isWhitespace(segment.charAt(j))) {\n\t\t\t\t\tnewLine();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsegments.clear();\n\t\tcachedToString = null;\n\t}",
"public static auditmessages[] get(nitro_service service, auditmessages_args args) throws Exception{\n\t\tauditmessages obj = new auditmessages();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tauditmessages[] response = (auditmessages[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"private void disableTalkBack() {\n GVRSceneObject[] sceneObjects = mGvrContext.getMainScene().getWholeSceneObjects();\n for (GVRSceneObject sceneObject : sceneObjects) {\n if (sceneObject instanceof GVRAccessiblityObject)\n if (((GVRAccessiblityObject) sceneObject).getTalkBack() != null)\n ((GVRAccessiblityObject) sceneObject).getTalkBack().setActive(false);\n\n }\n }"
] |
replace the counter for K1-index o by new counter c | [
"public ClassicCounter<K2> setCounter(K1 o, Counter<K2> c) {\r\n ClassicCounter<K2> old = getCounter(o);\r\n total -= old.totalCount();\r\n if (c instanceof ClassicCounter) {\r\n map.put(o, (ClassicCounter<K2>) c);\r\n } else {\r\n map.put(o, new ClassicCounter<K2>(c));\r\n }\r\n total += c.totalCount();\r\n return old;\r\n }"
] | [
"public void fill(long offset, long length, byte value) {\n unsafe.setMemory(address() + offset, length, value);\n }",
"@PreDestroy\n public final void shutdown() {\n this.timer.shutdownNow();\n this.executor.shutdownNow();\n if (this.cleanUpTimer != null) {\n this.cleanUpTimer.shutdownNow();\n }\n }",
"public static Region create(String name, String label) {\n Region region = VALUES_BY_NAME.get(name.toLowerCase());\n if (region != null) {\n return region;\n } else {\n return new Region(name, label);\n }\n }",
"public Class<?> getColumnType(int c) {\n\n for (int r = 0; r < m_data.size(); r++) {\n Object val = m_data.get(r).get(c);\n if (val != null) {\n return val.getClass();\n }\n }\n return Object.class;\n }",
"@NonNull public Context getContext() {\n if (searchView != null) {\n return searchView.getContext();\n } else if (supportView != null) {\n return supportView.getContext();\n }\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }",
"public static MBeanParameterInfo[] extractParameterInfo(Method m) {\n Class<?>[] types = m.getParameterTypes();\n Annotation[][] annotations = m.getParameterAnnotations();\n MBeanParameterInfo[] params = new MBeanParameterInfo[types.length];\n for(int i = 0; i < params.length; i++) {\n boolean hasAnnotation = false;\n for(int j = 0; j < annotations[i].length; j++) {\n if(annotations[i][j] instanceof JmxParam) {\n JmxParam param = (JmxParam) annotations[i][j];\n params[i] = new MBeanParameterInfo(param.name(),\n types[i].getName(),\n param.description());\n hasAnnotation = true;\n break;\n }\n }\n if(!hasAnnotation) {\n params[i] = new MBeanParameterInfo(\"\", types[i].getName(), \"\");\n }\n }\n\n return params;\n }",
"private void readCalendars(Storepoint phoenixProject)\n {\n Calendars calendars = phoenixProject.getCalendars();\n if (calendars != null)\n {\n for (Calendar calendar : calendars.getCalendar())\n {\n readCalendar(calendar);\n }\n\n ProjectCalendar defaultCalendar = m_projectFile.getCalendarByName(phoenixProject.getDefaultCalendar());\n if (defaultCalendar != null)\n {\n m_projectFile.getProjectProperties().setDefaultCalendarName(defaultCalendar.getName());\n }\n }\n }",
"public void setMat4(String key, float x1, float y1, float z1, float w1,\n float x2, float y2, float z2, float w2, float x3, float y3,\n float z3, float w3, float x4, float y4, float z4, float w4)\n {\n checkKeyIsUniform(key);\n NativeLight.setMat4(getNative(), key, x1, y1, z1, w1, x2, y2,\n z2, w2, x3, y3, z3, w3, x4, y4, z4, w4);\n }",
"private void writePropertyData() {\n\t\ttry (PrintStream out = new PrintStream(openResultFileOuputStream(\n\t\t\t\tresultDirectory, \"properties.json\"))) {\n\t\t\tout.println(\"{\");\n\n\t\t\tint count = 0;\n\t\t\tfor (Entry<Integer, PropertyRecord> propertyEntry : this.propertyRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (count > 0) {\n\t\t\t\t\tout.println(\",\");\n\t\t\t\t}\n\t\t\t\tout.print(\"\\\"\" + propertyEntry.getKey() + \"\\\":\");\n\t\t\t\tmapper.writeValue(out, propertyEntry.getValue());\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tout.println(\"\\n}\");\n\n\t\t\tSystem.out.println(\" Serialized information for \" + count\n\t\t\t\t\t+ \" properties.\");\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}"
] |
Use this API to save cachecontentgroup. | [
"public static base_response save(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup saveresource = new cachecontentgroup();\n\t\tsaveresource.name = resource.name;\n\t\treturn saveresource.perform_operation(client,\"save\");\n\t}"
] | [
"public static final Date getTimestamp(byte[] data, int offset)\n {\n Date result;\n\n long days = getShort(data, offset + 2);\n if (days < 100)\n {\n // We are seeing some files which have very small values for the number of days.\n // When the relevant field is shown in MS Project it appears as NA.\n // We try to mimic this behaviour here.\n days = 0;\n }\n\n if (days == 0 || days == 65535)\n {\n result = null;\n }\n else\n {\n long time = getShort(data, offset);\n if (time == 65535)\n {\n time = 0;\n }\n result = DateHelper.getTimestampFromLong((EPOCH + (days * DateHelper.MS_PER_DAY) + ((time * DateHelper.MS_PER_MINUTE) / 10)));\n }\n\n return (result);\n }",
"public void postProcess() {\n\t\tif (foreignColumnName != null) {\n\t\t\tforeignAutoRefresh = true;\n\t\t}\n\t\tif (foreignAutoRefresh && maxForeignAutoRefreshLevel == NO_MAX_FOREIGN_AUTO_REFRESH_LEVEL_SPECIFIED) {\n\t\t\tmaxForeignAutoRefreshLevel = DatabaseField.DEFAULT_MAX_FOREIGN_AUTO_REFRESH_LEVEL;\n\t\t}\n\t}",
"private static void validatePseudoScopedBean(Bean<?> bean, BeanManagerImpl beanManager) {\n if (bean.getInjectionPoints().isEmpty()) {\n // Skip validation if there are no injection points (e.g. for classes which are not intended to be used as beans)\n return;\n }\n reallyValidatePseudoScopedBean(bean, beanManager, new LinkedHashSet<Object>(), new HashSet<Bean<?>>());\n }",
"public float getTangentY(int vertex) {\n if (!hasTangentsAndBitangents()) {\n throw new IllegalStateException(\"mesh has no bitangents\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_tangents.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\n }",
"public void setProductModules(final String name, final List<String> moduleNames) {\n final DbProduct dbProduct = getProduct(name);\n dbProduct.setModules(moduleNames);\n repositoryHandler.store(dbProduct);\n }",
"public 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 }",
"public void delete(Object element, boolean testForEquality) {\r\n\tint index = indexOfFromTo(element, 0, size-1, testForEquality);\r\n\tif (index>=0) removeFromTo(index,index);\r\n}",
"public ApiResponse<String> getPingWithHttpInfo() throws ApiException {\n com.squareup.okhttp.Call call = getPingValidateBeforeCall(null);\n Type localVarReturnType = new TypeToken<String>() {\n }.getType();\n return apiClient.execute(call, localVarReturnType);\n }",
"public Map<String, String> resolve(Map<String, String> config) {\n config = resolveSystemEnvironmentVariables(config);\n config = resolveSystemDefaultSetup(config);\n config = resolveDockerInsideDocker(config);\n config = resolveDownloadDockerMachine(config);\n config = resolveAutoStartDockerMachine(config);\n config = resolveDefaultDockerMachine(config);\n config = resolveServerUriByOperativeSystem(config);\n config = resolveServerIp(config);\n config = resolveTlsVerification(config);\n return config;\n }"
] |
Obtains a local date in Discordian calendar system from the
era, year-of-era and day-of-year fields.
@param era the Discordian era, not null
@param yearOfEra the year-of-era
@param dayOfYear the day-of-year
@return the Discordian local date, not null
@throws DateTimeException if unable to create the date
@throws ClassCastException if the {@code era} is not a {@code DiscordianEra} | [
"@Override\n public DiscordianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }"
] | [
"public String getResourcePath()\n {\n switch (resourceType)\n {\n case ANDROID_ASSETS: return assetPath;\n\n case ANDROID_RESOURCE: return resourceFilePath;\n\n case LINUX_FILESYSTEM: return filePath;\n\n case NETWORK: return url.getPath();\n\n case INPUT_STREAM: return inputStreamName;\n\n default: return null;\n }\n }",
"public String objectToString(T object) {\n\t\tStringBuilder sb = new StringBuilder(64);\n\t\tsb.append(object.getClass().getSimpleName());\n\t\tfor (FieldType fieldType : fieldTypes) {\n\t\t\tsb.append(' ').append(fieldType.getColumnName()).append('=');\n\t\t\ttry {\n\t\t\t\tsb.append(fieldType.extractJavaFieldValue(object));\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new IllegalStateException(\"Could not generate toString of field \" + fieldType, e);\n\t\t\t}\n\t\t}\n\t\treturn sb.toString();\n\t}",
"private void stop() {\n\t\tfor (int i = 0; i < mDownloadDispatchers.length; i++) {\n\t\t\tif (mDownloadDispatchers[i] != null) {\n\t\t\t\tmDownloadDispatchers[i].quit();\n\t\t\t}\n\t\t}\n\t}",
"public static <V> V doWorkInPool(final Pool<Jedis> pool, final PoolWork<Jedis, V> work) throws Exception {\n if (pool == null) {\n throw new IllegalArgumentException(\"pool must not be null\");\n }\n if (work == null) {\n throw new IllegalArgumentException(\"work must not be null\");\n }\n final V result;\n final Jedis poolResource = pool.getResource();\n try {\n result = work.doWork(poolResource);\n } finally {\n poolResource.close();\n }\n return result;\n }",
"public static List getAt(Matcher self, Collection indices) {\n List result = new ArrayList();\n for (Object value : indices) {\n if (value instanceof Range) {\n result.addAll(getAt(self, (Range) value));\n } else {\n int idx = DefaultTypeTransformation.intUnbox(value);\n result.add(getAt(self, idx));\n }\n }\n return result;\n }",
"private static AbstractIndex constructLiborIndex(String forwardCurveName, Schedule schedule) {\n\n\t\tif(forwardCurveName != null) {\n\n\t\t\t//determine average fixing offset and period length\n\t\t\tdouble fixingOffset = 0;\n\t\t\tdouble periodLength = 0;\n\n\t\t\tfor(int i = 0; i < schedule.getNumberOfPeriods(); i++) {\n\t\t\t\tfixingOffset *= ((double) i) / (i+1);\n\t\t\t\tfixingOffset += (schedule.getPeriodStart(i) - schedule.getFixing(i)) / (i+1);\n\n\t\t\t\tperiodLength *= ((double) i) / (i+1);\n\t\t\t\tperiodLength += schedule.getPeriodLength(i) / (i+1);\n\t\t\t}\n\n\t\t\treturn new LIBORIndex(forwardCurveName, fixingOffset, periodLength);\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}",
"@Inline(value = \"$1.put($2.getKey(), $2.getValue())\", statementExpression = true)\n\tpublic static <K, V> V operator_add(Map<K, V> map, Pair<? extends K, ? extends V> entry) {\n\t\treturn map.put(entry.getKey(), entry.getValue());\n\t}",
"public <T extends Widget & Checkable> void clearChecks() {\n List<T> children = getCheckableChildren();\n for (T c : children) {\n c.setChecked(false);\n }\n }",
"public static DMatrixRMaj stripReal(ZMatrixD1 input , DMatrixRMaj output ) {\n if( output == null ) {\n output = new DMatrixRMaj(input.numRows,input.numCols);\n } else if( input.numCols != output.numCols || input.numRows != output.numRows ) {\n throw new IllegalArgumentException(\"The matrices are not all the same dimension.\");\n }\n\n final int length = input.getDataLength();\n\n for( int i = 0; i < length; i += 2 ) {\n output.data[i/2] = input.data[i];\n }\n return output;\n }"
] |
Tells you if the expression is a null safe dereference.
@param expression
expression
@return
true if is null safe dereference. | [
"public static boolean isSafe(Expression expression) {\r\n if (expression instanceof MethodCallExpression) {\r\n return ((MethodCallExpression) expression).isSafe();\r\n }\r\n if (expression instanceof PropertyExpression) {\r\n return ((PropertyExpression) expression).isSafe();\r\n }\r\n return false;\r\n }"
] | [
"Renderer copy() {\n Renderer copy = null;\n try {\n copy = (Renderer) this.clone();\n } catch (CloneNotSupportedException e) {\n Log.e(\"Renderer\", \"All your renderers should be clonables.\");\n }\n return copy;\n }",
"public Map<String, String> getParams() {\n\n Map<String, String> params = new HashMap<>(1);\n params.put(PARAM_COLLAPSED, Boolean.TRUE.toString());\n return params;\n }",
"String getFacetParamKey(String facet) {\n\n I_CmsSearchControllerFacetField fieldFacet = m_result.getController().getFieldFacets().getFieldFacetController().get(\n facet);\n if (fieldFacet != null) {\n return fieldFacet.getConfig().getParamKey();\n }\n I_CmsSearchControllerFacetRange rangeFacet = m_result.getController().getRangeFacets().getRangeFacetController().get(\n facet);\n if (rangeFacet != null) {\n return rangeFacet.getConfig().getParamKey();\n }\n I_CmsSearchControllerFacetQuery queryFacet = m_result.getController().getQueryFacet();\n if ((queryFacet != null) && queryFacet.getConfig().getName().equals(facet)) {\n return queryFacet.getConfig().getParamKey();\n }\n\n // Facet did not exist\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_FACET_NOT_CONFIGURED_1, facet), new Throwable());\n\n return null;\n }",
"public static Cluster getCluster(ZkClient zkClient) {\n Cluster cluster = new Cluster();\n List<String> nodes = getChildrenParentMayNotExist(zkClient, BrokerIdsPath);\n for (String node : nodes) {\n final String brokerInfoString = readData(zkClient, BrokerIdsPath + \"/\" + node);\n cluster.add(Broker.createBroker(Integer.valueOf(node), brokerInfoString));\n }\n return cluster;\n }",
"@RequestMapping(value = \"api/edit/enable/custom\", method = RequestMethod.POST)\n public\n @ResponseBody\n String enableCustomResponse(Model model, String custom, int path_id,\n @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n if (custom.equals(\"undefined\"))\n return null;\n editService.enableCustomResponse(custom, path_id, clientUUID);\n return null;\n }",
"public static final int getShort(byte[] data, int offset)\n {\n int result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 16; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }",
"public static final Bytes of(byte[] data, int offset, int length) {\n Objects.requireNonNull(data);\n if (length == 0) {\n return EMPTY;\n }\n byte[] copy = new byte[length];\n System.arraycopy(data, offset, copy, 0, length);\n return new Bytes(copy);\n }",
"@RequestMapping(value = \"group\", method = RequestMethod.GET)\n public String newGroupGet(Model model) {\n model.addAttribute(\"groups\",\n pathOverrideService.findAllGroups());\n return \"groups\";\n }",
"public static PredicateExpression nin(Object... rhs) {\n PredicateExpression ex = new PredicateExpression(\"$nin\", rhs);\n if (rhs.length == 1) {\n ex.single = true;\n }\n return ex;\n }"
] |
Use this API to fetch all the appqoepolicy resources that are configured on netscaler. | [
"public static appqoepolicy[] get(nitro_service service) throws Exception{\n\t\tappqoepolicy obj = new appqoepolicy();\n\t\tappqoepolicy[] response = (appqoepolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"protected void load()\r\n {\r\n properties = new Properties();\r\n\r\n String filename = getFilename();\r\n \r\n try\r\n {\r\n URL url = ClassHelper.getResource(filename);\r\n\r\n if (url == null)\r\n {\r\n url = (new File(filename)).toURL();\r\n }\r\n\r\n logger.info(\"Loading OJB's properties: \" + url);\r\n\r\n URLConnection conn = url.openConnection();\r\n conn.setUseCaches(false);\r\n conn.connect();\r\n InputStream strIn = conn.getInputStream();\r\n properties.load(strIn);\r\n strIn.close();\r\n }\r\n catch (FileNotFoundException ex)\r\n {\r\n // [tomdz] If the filename is explicitly reset (null or empty string) then we'll\r\n // output an info message because the user did this on purpose\r\n // Otherwise, we'll output a warning\r\n if ((filename == null) || (filename.length() == 0))\r\n {\r\n logger.info(\"Starting OJB without a properties file. OJB is using default settings instead.\");\r\n }\r\n else\r\n {\r\n logger.warn(\"Could not load properties file '\"+filename+\"'. Using default settings!\", ex);\r\n }\r\n // [tomdz] There seems to be no use of this setting ?\r\n //properties.put(\"valid\", \"false\");\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new MetadataException(\"An error happend while loading the properties file '\"+filename+\"'\", ex);\r\n }\r\n }",
"public static void addLazyDefinitions(SourceBuilder code) {\n Set<Declaration> defined = new HashSet<>();\n\n // Definitions may lazily declare new names; ensure we add them all\n List<Declaration> declarations =\n code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList());\n while (!defined.containsAll(declarations)) {\n for (Declaration declaration : declarations) {\n if (defined.add(declaration)) {\n code.add(code.scope().get(declaration).definition);\n }\n }\n declarations = code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList());\n }\n }",
"public void addNotIn(String attribute, Query subQuery)\r\n {\r\n\t\t// PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildNotInCriteria(attribute, subQuery, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildNotInCriteria(attribute, subQuery, getUserAlias(attribute)));\r\n }",
"public static double Sinh(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return x + (x * x * x) / 6D;\r\n } else {\r\n\r\n double mult = x * x * x;\r\n double fact = 6;\r\n int factS = 5;\r\n double result = x + mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += mult / fact;\r\n }\r\n\r\n return result;\r\n }\r\n }",
"private void digestInteger(MessageDigest digest, int value) {\n byte[] valueBytes = new byte[4];\n Util.numberToBytes(value, valueBytes, 0, 4);\n digest.update(valueBytes);\n }",
"@Deprecated\r\n private BufferedImage getOriginalImage(String suffix) throws IOException, FlickrException {\r\n StringBuffer buffer = getOriginalBaseImageUrl();\r\n buffer.append(suffix);\r\n return _getImage(buffer.toString());\r\n }",
"public void check(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureElementClassRef(collDef, checkLevel);\r\n checkInheritedForeignkey(collDef, checkLevel);\r\n ensureCollectionClass(collDef, checkLevel);\r\n checkProxyPrefetchingLimit(collDef, checkLevel);\r\n checkOrderby(collDef, checkLevel);\r\n checkQueryCustomizer(collDef, checkLevel);\r\n }",
"public void reverse() {\n for (int i = 0, size = mTransitionControls.size(); i < size; i++) {\n mTransitionControls.get(i).reverse();\n }\n }",
"protected void prepareRequest(List<BoxAPIRequest> requests) {\n JsonObject body = new JsonObject();\n JsonArray requestsJSONArray = new JsonArray();\n for (BoxAPIRequest request: requests) {\n JsonObject batchRequest = new JsonObject();\n batchRequest.add(\"method\", request.getMethod());\n batchRequest.add(\"relative_url\", request.getUrl().toString().substring(this.api.getBaseURL().length() - 1));\n //If the actual request has a JSON body then add it to vatch request\n if (request instanceof BoxJSONRequest) {\n BoxJSONRequest jsonRequest = (BoxJSONRequest) request;\n batchRequest.add(\"body\", jsonRequest.getBodyAsJsonValue());\n }\n //Add any headers that are in the request, except Authorization\n if (request.getHeaders() != null) {\n JsonObject batchRequestHeaders = new JsonObject();\n for (RequestHeader header: request.getHeaders()) {\n if (header.getKey() != null && !header.getKey().isEmpty()\n && !HttpHeaders.AUTHORIZATION.equals(header.getKey())) {\n batchRequestHeaders.add(header.getKey(), header.getValue());\n }\n }\n batchRequest.add(\"headers\", batchRequestHeaders);\n }\n\n //Add the request to array\n requestsJSONArray.add(batchRequest);\n }\n //Add the requests array to body\n body.add(\"requests\", requestsJSONArray);\n super.setBody(body);\n }"
] |
Mark for creation all objects that were included into dependent collections.
Mark for deletion all objects that were excluded from dependent collections. | [
"private ArrayList handleDependentCollections(Identity oid, Object obj,\r\n Object[] origCollections, Object[] newCollections,\r\n Object[] newCollectionsOfObjects)\r\n throws LockingException\r\n {\r\n ClassDescriptor mif = _pb.getClassDescriptor(obj.getClass());\r\n Collection colDescs = mif.getCollectionDescriptors();\r\n ArrayList newObjects = new ArrayList();\r\n int count = 0;\r\n\r\n for (Iterator it = colDescs.iterator(); it.hasNext(); count++)\r\n {\r\n CollectionDescriptor cds = (CollectionDescriptor) it.next();\r\n\r\n if (cds.getOtmDependent())\r\n {\r\n ArrayList origList = (origCollections == null ? null\r\n : (ArrayList) origCollections[count]);\r\n ArrayList newList = (ArrayList) newCollections[count];\r\n\r\n if (origList != null)\r\n {\r\n for (Iterator it2 = origList.iterator(); it2.hasNext(); )\r\n {\r\n Identity origOid = (Identity) it2.next();\r\n\r\n if ((newList == null) || !newList.contains(origOid))\r\n {\r\n markDelete(origOid, oid, true);\r\n }\r\n }\r\n }\r\n\r\n if (newList != null)\r\n {\r\n int countElem = 0;\r\n for (Iterator it2 = newList.iterator(); it2.hasNext(); countElem++)\r\n {\r\n Identity newOid = (Identity) it2.next();\r\n\r\n if ((origList == null) || !origList.contains(newOid))\r\n {\r\n ContextEntry entry = (ContextEntry) _objects.get(newOid);\r\n\r\n if (entry == null)\r\n {\r\n ArrayList relCol = (ArrayList)\r\n newCollectionsOfObjects[count];\r\n Object relObj = relCol.get(countElem);\r\n insertInternal(newOid, relObj, LockType.WRITE_LOCK,\r\n true, null, new Stack());\r\n newObjects.add(newOid);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n return newObjects;\r\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 }",
"private void processActivityCodes(Storepoint storepoint)\n {\n for (Code code : storepoint.getActivityCodes().getCode())\n {\n int sequence = 0;\n for (Value value : code.getValue())\n {\n UUID uuid = getUUID(value.getUuid(), value.getName());\n m_activityCodeValues.put(uuid, value.getName());\n m_activityCodeSequence.put(uuid, Integer.valueOf(++sequence));\n }\n }\n }",
"private List<Long> collectLongMetric(String metricGetterName) {\n List<Long> vals = new ArrayList<Long>();\n for(BdbEnvironmentStats envStats: environmentStatsTracked) {\n vals.add((Long) ReflectUtils.callMethod(envStats,\n BdbEnvironmentStats.class,\n metricGetterName,\n new Class<?>[0],\n new Object[0]));\n }\n return vals;\n }",
"protected void propagateOnEnter(GVRPickedObject hit)\n {\n GVRSceneObject hitObject = hit.getHitObject();\n GVREventManager eventManager = getGVRContext().getEventManager();\n if (mEventOptions.contains(EventOptions.SEND_TOUCH_EVENTS))\n {\n if (mEventOptions.contains(EventOptions.SEND_TO_LISTENERS))\n {\n eventManager.sendEvent(this, ITouchEvents.class, \"onEnter\", hitObject, hit);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_HIT_OBJECT))\n {\n eventManager.sendEvent(hitObject, ITouchEvents.class, \"onEnter\", hitObject, hit);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_SCENE) && (mScene != null))\n {\n eventManager.sendEvent(mScene, ITouchEvents.class, \"onEnter\", hitObject, hit);\n }\n }\n if (mEventOptions.contains(EventOptions.SEND_PICK_EVENTS))\n {\n if (mEventOptions.contains(EventOptions.SEND_TO_LISTENERS))\n {\n eventManager.sendEvent(this, IPickEvents.class, \"onEnter\", hitObject, hit);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_HIT_OBJECT))\n {\n eventManager.sendEvent(hitObject, IPickEvents.class, \"onEnter\", hitObject, hit);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_SCENE) && (mScene != null))\n {\n eventManager.sendEvent(mScene, IPickEvents.class, \"onEnter\", hitObject, hit);\n }\n }\n }",
"protected float getViewPortSize(final Axis axis) {\n float size = mViewPort == null ? 0 : mViewPort.get(axis);\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"getViewPortSize for %s %f mViewPort = %s\", axis, size, mViewPort);\n return size;\n }",
"private String pathToProperty(String path) {\n if (path == null || !path.startsWith(\"/\")) {\n throw new IllegalArgumentException(\"Path must be prefixed with a \\\"/\\\".\");\n }\n return path.substring(1);\n }",
"public static void registerOgmExternalizers(GlobalConfiguration globalCfg) {\n\t\tMap<Integer, AdvancedExternalizer<?>> externalizerMap = globalCfg.serialization().advancedExternalizers();\n\t\texternalizerMap.putAll( ogmExternalizers );\n\t}",
"public static final long getLong(byte[] data, int offset)\n {\n if (data.length != 8)\n {\n throw new UnexpectedStructureException();\n }\n\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 64; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }",
"public static base_response update(nitro_service client, protocolhttpband resource) throws Exception {\n\t\tprotocolhttpband updateresource = new protocolhttpband();\n\t\tupdateresource.reqbandsize = resource.reqbandsize;\n\t\tupdateresource.respbandsize = resource.respbandsize;\n\t\treturn updateresource.update_resource(client);\n\t}"
] |
Converts string to UUID and returns it, or null if the conversion is not possible.
@param uuid the potential UUID string
@return the UUID, or null if conversion is not possible | [
"private static CmsUUID toUuid(String uuid) {\n\n if (\"null\".equals(uuid) || CmsStringUtil.isEmpty(uuid)) {\n return null;\n }\n return new CmsUUID(uuid);\n\n }"
] | [
"private static JSONObject parseProperties(HashMap<String, String> properties) throws JSONException {\n if (properties != null) {\n JSONObject propertiesObject = new JSONObject();\n\n for (String key : properties.keySet()) {\n String propertyValue = properties.get(key);\n\n /*\n * if(propertyValue.matches(\"true|false\")) {\n * \n * propertiesObject.put(key, propertyValue.equals(\"true\"));\n * \n * } else if(propertyValue.matches(\"[0-9]+\")) {\n * \n * Integer value = Integer.parseInt(propertyValue);\n * propertiesObject.put(key, value);\n * \n * } else\n */\n if (propertyValue.startsWith(\"{\") && propertyValue.endsWith(\"}\")) {\n propertiesObject.put(key,\n new JSONObject(propertyValue));\n } else {\n propertiesObject.put(key,\n propertyValue.toString());\n }\n }\n\n return propertiesObject;\n }\n\n return new JSONObject();\n }",
"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 setAcquireRetryDelay(long acquireRetryDelay, TimeUnit timeUnit) {\n\t\tthis.acquireRetryDelayInMs = TimeUnit.MILLISECONDS.convert(acquireRetryDelay, timeUnit);\n\t}",
"public boolean checkKeyBelongsToNode(byte[] key, int nodeId) {\n List<Integer> nodePartitions = cluster.getNodeById(nodeId).getPartitionIds();\n List<Integer> replicatingPartitions = getReplicatingPartitionList(key);\n // remove all partitions from the list, except those that belong to the\n // node\n replicatingPartitions.retainAll(nodePartitions);\n return replicatingPartitions.size() > 0;\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 }",
"public static Map<String, List<String>> getResponseHeaders(String stringUrl,\n boolean followRedirects) throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setInstanceFollowRedirects(followRedirects);\n \n InputStream is = conn.getInputStream();\n if (\"gzip\".equals(conn.getContentEncoding())) {\n is = new GZIPInputStream(is);\n }\n\n Map<String, List<String>> headers = new LinkedHashMap<String, List<String>>(conn.getHeaderFields());\n headers.put(\"X-Content\", Arrays.asList(MyStreamUtils.readContent(is)));\n headers.put(\"X-URL\", Arrays.asList(conn.getURL().toString()));\n headers.put(\"X-Status\", Arrays.asList(String.valueOf(conn.getResponseCode())));\n \n return headers;\n }",
"public static void setQuota(final GreenMailUser user, final Quota quota) {\r\n Session session = GreenMailUtil.getSession(ServerSetupTest.IMAP);\r\n try {\r\n Store store = session.getStore(\"imap\");\r\n store.connect(user.getEmail(), user.getPassword());\r\n try {\r\n ((QuotaAwareStore) store).setQuota(quota);\r\n } finally {\r\n store.close();\r\n }\r\n } catch (Exception ex) {\r\n throw new IllegalStateException(\"Can not set quota \" + quota\r\n + \" for user \" + user, ex);\r\n }\r\n }",
"private void processChildTasks(Task task, MapRow row) throws IOException\n {\n List<MapRow> tasks = row.getRows(\"TASKS\");\n if (tasks != null)\n {\n for (MapRow childTask : tasks)\n {\n processTask(task, childTask);\n }\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 }"
] |
Add an addon to the app.
@param appName App name. See {@link #listApps} for a list of apps that can be used.
@param addonName Addon name. See {@link #listAllAddons} to get a list of addons that can be used.
@return The request object | [
"public AddonChange addAddon(String appName, String addonName) {\n return connection.execute(new AddonInstall(appName, addonName), apiKey);\n }"
] | [
"public <T> T getNodeMetaData(Object key) {\n if (metaDataMap == null) {\n return (T) null;\n }\n return (T) metaDataMap.get(key);\n }",
"@SafeVarargs\n public static <K, V> Map<K, V> map(final Entry<? extends K, ? extends V>... entries) {\n final Map<K, V> map = new LinkedHashMap<K, V>(entries.length);\n for (final Entry<? extends K, ? extends V> entry : entries) {\n map.put(entry.getKey(), entry.getValue());\n }\n return map;\n }",
"private Date getTimeFromInteger(Integer time)\n {\n Date result = null;\n\n if (time != null)\n {\n int minutes = time.intValue();\n int hours = minutes / 60;\n minutes -= (hours * 60);\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.MILLISECOND, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.HOUR_OF_DAY, hours);\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n\n return (result);\n }",
"public static void writeInt(byte[] bytes, int value, int offset) {\n bytes[offset] = (byte) (0xFF & (value >> 24));\n bytes[offset + 1] = (byte) (0xFF & (value >> 16));\n bytes[offset + 2] = (byte) (0xFF & (value >> 8));\n bytes[offset + 3] = (byte) (0xFF & value);\n }",
"public static <T extends JsonRtn> T parseJsonRtn(String jsonRtn, Class<T> jsonRtnClazz) {\n T rtn = JSONObject.parseObject(jsonRtn, jsonRtnClazz);\n appendErrorHumanMsg(rtn);\n return rtn;\n }",
"public static int cudnnGetRNNWorkspaceSize(\n cudnnHandle handle, \n cudnnRNNDescriptor rnnDesc, \n int seqLength, \n cudnnTensorDescriptor[] xDesc, \n long[] sizeInBytes)\n {\n return checkResult(cudnnGetRNNWorkspaceSizeNative(handle, rnnDesc, seqLength, xDesc, sizeInBytes));\n }",
"public static streamidentifier_stats get(nitro_service service, String name) throws Exception{\n\t\tstreamidentifier_stats obj = new streamidentifier_stats();\n\t\tobj.set_name(name);\n\t\tstreamidentifier_stats response = (streamidentifier_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public double determinant() {\n if (m != n) {\n throw new IllegalArgumentException(\"Matrix must be square.\");\n }\n double d = (double) pivsign;\n for (int j = 0; j < n; j++) {\n d *= LU[j][j];\n }\n return d;\n }",
"private void addWSAddressingInterceptors(InterceptorProvider provider) {\n MAPAggregator mapAggregator = new MAPAggregator();\n MAPCodec mapCodec = new MAPCodec();\n\n provider.getInInterceptors().add(mapAggregator);\n provider.getInInterceptors().add(mapCodec);\n\n provider.getOutInterceptors().add(mapAggregator);\n provider.getOutInterceptors().add(mapCodec);\n\n provider.getInFaultInterceptors().add(mapAggregator);\n provider.getInFaultInterceptors().add(mapCodec);\n\n provider.getOutFaultInterceptors().add(mapAggregator);\n provider.getOutFaultInterceptors().add(mapCodec);\n }"
] |
Provides a nicely formatted string of the method definition. For simplicity, generic types on some of the elements
are not displayed.
@return
string form of node with some generic elements suppressed | [
"@Override\n public String getText() {\n String retType = AstToTextHelper.getClassText(returnType);\n String exceptionTypes = AstToTextHelper.getThrowsClauseText(exceptions);\n String parms = AstToTextHelper.getParametersText(parameters);\n return AstToTextHelper.getModifiersText(modifiers) + \" \" + retType + \" \" + name + \"(\" + parms + \") \" + exceptionTypes + \" { ... }\";\n }"
] | [
"private void addDateWithCheckState(Date date, boolean checkState) {\n\n addCheckBox(date, checkState);\n if (!m_dates.contains(date)) {\n m_dates.add(date);\n fireValueChange();\n }\n }",
"public static void startNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tgetNamedTimer(timerName, todoFlags, threadId).start();\n\t}",
"public static float smoothPulse(float a1, float a2, float b1, float b2, float x) {\n\t\tif (x < a1 || x >= b2)\n\t\t\treturn 0;\n\t\tif (x >= a2) {\n\t\t\tif (x < b1)\n\t\t\t\treturn 1.0f;\n\t\t\tx = (x - b1) / (b2 - b1);\n\t\t\treturn 1.0f - (x*x * (3.0f - 2.0f*x));\n\t\t}\n\t\tx = (x - a1) / (a2 - a1);\n\t\treturn x*x * (3.0f - 2.0f*x);\n\t}",
"public static boolean setCustomRequestForDefaultClient(String profileName, String pathName, String customData) {\n try {\n return setCustomForDefaultClient(profileName, pathName, false, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"public Set<Annotation> getPropertyAnnotations()\n\t{\n\t\tif (accessor instanceof PropertyAwareAccessor)\n\t\t{\n\t\t\treturn unmodifiableSet(((PropertyAwareAccessor) accessor).getReadMethodAnnotations());\n\t\t}\n\t\treturn unmodifiableSet(Collections.<Annotation>emptySet());\n\t}",
"protected FluentModelTImpl find(String key) {\n for (Map.Entry<String, FluentModelTImpl> entry : this.childCollection.entrySet()) {\n if (entry.getKey().equalsIgnoreCase(key)) {\n return entry.getValue();\n }\n }\n return null;\n }",
"private CollectionDescriptorDef cloneCollection(CollectionDescriptorDef collDef, String prefix)\r\n {\r\n CollectionDescriptorDef copyCollDef = new CollectionDescriptorDef(collDef, prefix);\r\n\r\n copyCollDef.setOwner(this);\r\n // we remove properties that are only relevant to the class the features are declared in\r\n copyCollDef.setProperty(PropertyHelper.OJB_PROPERTY_IGNORE, null);\r\n\r\n Properties mod = getModification(copyCollDef.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(copyCollDef.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 collection \"+\r\n copyCollDef.getName()+\" from class \"+collDef.getOwner().getName()); \r\n }\r\n copyCollDef.applyModifications(mod);\r\n }\r\n return copyCollDef;\r\n }",
"public TaskMode getTaskMode()\n {\n return BooleanHelper.getBoolean((Boolean) getCachedValue(TaskField.TASK_MODE)) ? TaskMode.MANUALLY_SCHEDULED : TaskMode.AUTO_SCHEDULED;\n }",
"public int compareTo(Rational other)\n {\n if (denominator == other.getDenominator())\n {\n return ((Long) numerator).compareTo(other.getNumerator());\n }\n else\n {\n Long adjustedNumerator = numerator * other.getDenominator();\n Long otherAdjustedNumerator = other.getNumerator() * denominator;\n return adjustedNumerator.compareTo(otherAdjustedNumerator);\n }\n }"
] |
URL-Decodes a given string using UTF-8. No UnsupportedEncodingException to handle as it is dealt with in this
method. | [
"public static String decodeUrl(String stringToDecode) {\n try {\n return URLDecoder.decode(stringToDecode, \"UTF-8\");\n } catch (UnsupportedEncodingException e1) {\n throw new RuntimeException(e1);\n }\n }"
] | [
"public static void registerParams(DynamicJasperDesign jd, Map _parameters) {\n for (Object key : _parameters.keySet()) {\n if (key instanceof String) {\n try {\n Object value = _parameters.get(key);\n if (jd.getParametersMap().get(key) != null) {\n log.warn(\"Parameter \\\"\" + key + \"\\\" already registered, skipping this one: \" + value);\n continue;\n }\n\n JRDesignParameter parameter = new JRDesignParameter();\n\n if (value == null) //There are some Map implementations that allows nulls values, just go on\n continue;\n\n//\t\t\t\t\tparameter.setValueClassName(value.getClass().getCanonicalName());\n Class clazz = value.getClass().getComponentType();\n if (clazz == null)\n clazz = value.getClass();\n parameter.setValueClass(clazz); //NOTE this is very strange\n //when using an array as subreport-data-source, I must pass the parameter class name like this: value.getClass().getComponentType()\n parameter.setName((String) key);\n jd.addParameter(parameter);\n } catch (JRException e) {\n //nothing to do\n }\n }\n\n }\n\n }",
"public <T> void cleanNullReferencesAll() {\n\t\tfor (Map<Object, Reference<Object>> objectMap : classMaps.values()) {\n\t\t\tcleanMap(objectMap);\n\t\t}\n\t}",
"public static <E> ServiceFuture<List<E>> fromPageResponse(Observable<ServiceResponse<Page<E>>> first, final Func1<String, Observable<ServiceResponse<Page<E>>>> next, final ListOperationCallback<E> callback) {\n final AzureServiceFuture<List<E>> serviceCall = new AzureServiceFuture<>();\n final PagingSubscriber<E> subscriber = new PagingSubscriber<>(serviceCall, next, callback);\n serviceCall.setSubscription(first\n .single()\n .subscribe(subscriber));\n return serviceCall;\n }",
"public Map<String, List<Locale>> getAvailableLocales() {\n\n if (m_availableLocales == null) {\n // create lazy map only on demand\n m_availableLocales = CmsCollectionsGenericWrapper.createLazyMap(new CmsAvailableLocaleLoaderTransformer());\n }\n return m_availableLocales;\n }",
"private void readTasks(Integer id)\n {\n Integer currentID = id;\n Table table = getTable(\"WBSTAB\");\n\n while (currentID.intValue() != 0)\n {\n MapRow row = table.find(currentID);\n Task task = m_projectFile.getTaskByUniqueID(row.getInteger(\"TASK_ID\"));\n readLeafTasks(task, row.getInteger(\"FIRST_CHILD_TASK_ID\"));\n Integer childID = row.getInteger(\"CHILD_ID\");\n if (childID.intValue() != 0)\n {\n readTasks(childID);\n }\n currentID = row.getInteger(\"NEXT_ID\");\n }\n }",
"private void setProperties(Properties properties) {\n Props props = new Props(properties);\n if(props.containsKey(BOOTSTRAP_URLS_PROPERTY)) {\n setBootstrapURLs(props.getList(BOOTSTRAP_URLS_PROPERTY));\n }\n\n if(props.containsKey(FAT_CLIENTS_CONFIG_SOURCE)) {\n setFatClientConfigSource(StoreClientConfigSource.get(props.getString(FAT_CLIENTS_CONFIG_SOURCE)));\n }\n\n if(props.containsKey(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY)) {\n setFatClientConfigPath(props.getString(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY));\n }\n\n if(props.containsKey(METADATA_CHECK_INTERVAL_IN_MS)) {\n setMetadataCheckIntervalInMs(props.getInt(METADATA_CHECK_INTERVAL_IN_MS));\n }\n\n if(props.containsKey(NETTY_SERVER_PORT)) {\n setServerPort(props.getInt(NETTY_SERVER_PORT));\n }\n\n if(props.containsKey(NETTY_SERVER_BACKLOG)) {\n setNettyServerBacklog(props.getInt(NETTY_SERVER_BACKLOG));\n }\n\n if(props.containsKey(COORDINATOR_CORE_THREADS)) {\n setCoordinatorCoreThreads(props.getInt(COORDINATOR_CORE_THREADS));\n }\n\n if(props.containsKey(COORDINATOR_MAX_THREADS)) {\n setCoordinatorMaxThreads(props.getInt(COORDINATOR_MAX_THREADS));\n }\n\n if(props.containsKey(COORDINATOR_QUEUED_REQUESTS)) {\n setCoordinatorQueuedRequestsSize(props.getInt(COORDINATOR_QUEUED_REQUESTS));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH)) {\n setHttpMessageDecoderMaxInitialLength(props.getInt(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE)) {\n setHttpMessageDecoderMaxHeaderSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE)) {\n setHttpMessageDecoderMaxChunkSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE));\n }\n\n if(props.containsKey(ADMIN_ENABLE)) {\n setAdminServiceEnabled(props.getBoolean(ADMIN_ENABLE));\n }\n\n if(props.containsKey(ADMIN_PORT)) {\n setAdminPort(props.getInt(ADMIN_PORT));\n }\n\n }",
"protected ValueContainer[] getNonKeyValues(PersistenceBroker broker, ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getNonKeyRwValues(cld, obj);\r\n }",
"public static responderglobal_responderpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tresponderglobal_responderpolicy_binding obj = new responderglobal_responderpolicy_binding();\n\t\tresponderglobal_responderpolicy_binding response[] = (responderglobal_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static void append(Path self, Object text) throws IOException {\n Writer writer = null;\n try {\n writer = new OutputStreamWriter(Files.newOutputStream(self, CREATE, APPEND), Charset.defaultCharset());\n InvokerHelper.write(writer, text);\n writer.flush();\n\n Writer temp = writer;\n writer = null;\n temp.close();\n } finally {\n closeWithWarning(writer);\n }\n }"
] |
callers of doLogin should be serialized before calling in. | [
"private StitchUserT doLogin(final StitchCredential credential, final boolean asLinkRequest) {\n final Response response = doLoginRequest(credential, asLinkRequest);\n\n final StitchUserT previousUser = activeUser;\n final StitchUserT user = processLoginResponse(credential, response, asLinkRequest);\n\n if (asLinkRequest) {\n onUserLinked(user);\n } else {\n onUserLoggedIn(user);\n onActiveUserChanged(activeUser, previousUser);\n }\n\n return user;\n }"
] | [
"public T withStatement(Statement statement) {\n\t\tPropertyIdValue pid = statement.getMainSnak()\n\t\t\t\t.getPropertyId();\n\t\tArrayList<Statement> pidStatements = this.statements.get(pid);\n\t\tif (pidStatements == null) {\n\t\t\tpidStatements = new ArrayList<Statement>();\n\t\t\tthis.statements.put(pid, pidStatements);\n\t\t}\n\n\t\tpidStatements.add(statement);\n\t\treturn getThis();\n\t}",
"protected void validateRIBean(CommonBean<?> bean, BeanManagerImpl beanManager, Collection<CommonBean<?>> specializedBeans) {\n validateGeneralBean(bean, beanManager);\n if (bean instanceof NewBean) {\n return;\n }\n if (bean instanceof DecorableBean) {\n validateDecorators(beanManager, (DecorableBean<?>) bean);\n }\n if ((bean instanceof AbstractClassBean<?>)) {\n AbstractClassBean<?> classBean = (AbstractClassBean<?>) bean;\n // validate CDI-defined interceptors\n if (classBean.hasInterceptors()) {\n validateInterceptors(beanManager, classBean);\n }\n }\n // for each producer bean validate its disposer method\n if (bean instanceof AbstractProducerBean<?, ?, ?>) {\n AbstractProducerBean<?, ?, ?> producerBean = Reflections.<AbstractProducerBean<?, ?, ?>> cast(bean);\n if (producerBean.getProducer() instanceof AbstractMemberProducer<?, ?>) {\n AbstractMemberProducer<?, ?> producer = Reflections.<AbstractMemberProducer<?, ?>> cast(producerBean\n .getProducer());\n if (producer.getDisposalMethod() != null) {\n for (InjectionPoint ip : producer.getDisposalMethod().getInjectionPoints()) {\n // pass the producer bean instead of the disposal method bean\n validateInjectionPointForDefinitionErrors(ip, null, beanManager);\n validateMetadataInjectionPoint(ip, null, ValidatorLogger.INJECTION_INTO_DISPOSER_METHOD);\n validateEventMetadataInjectionPoint(ip);\n validateInjectionPointForDeploymentProblems(ip, null, beanManager);\n }\n }\n }\n }\n }",
"private void updateScheduleSource(ProjectProperties properties)\n {\n // Rudimentary identification of schedule source\n if (properties.getCompany() != null && properties.getCompany().equals(\"Synchro Software Ltd\"))\n {\n properties.setFileApplication(\"Synchro\");\n }\n else\n {\n if (properties.getAuthor() != null && properties.getAuthor().equals(\"SG Project\"))\n {\n properties.setFileApplication(\"Simple Genius\");\n }\n else\n {\n properties.setFileApplication(\"Microsoft\");\n }\n }\n properties.setFileType(\"MSPDI\");\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 }",
"protected JRDesignGroup getParent(JRDesignGroup group) {\n int index = realGroups.indexOf(group);\n return (index > 0) ? (JRDesignGroup) realGroups.get(index - 1) : group;\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}",
"public static void checkXerbla() {\n double[] x = new double[9];\n System.out.println(\"Check whether we're catching XERBLA errors. If you see something like \\\"** On entry to DGEMM parameter number 4 had an illegal value\\\", it didn't work!\");\n try {\n NativeBlas.dgemm('N', 'N', 3, -1, 3, 1.0, x, 0, 3, x, 0, 3, 0.0, x, 0, 3);\n } catch (IllegalArgumentException e) {\n check(\"checking XERBLA\", e.getMessage().contains(\"XERBLA\"));\n return;\n }\n assert (false); // shouldn't happen\n }",
"public ItemRequest<CustomField> delete(String customField) {\n \n String path = String.format(\"/custom_fields/%s\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"DELETE\");\n }",
"@Nonnull\n public BiMap<String, String> getOutputMapper() {\n final BiMap<String, String> outputMapper = this.processor.getOutputMapperBiMap();\n if (outputMapper == null) {\n return HashBiMap.create();\n }\n return outputMapper;\n }"
] |
Sets this matrix equal to the matrix encoded in the array.
@param numRows The number of rows.
@param numCols The number of columns.
@param rowMajor If the array is encoded in a row-major or a column-major format.
@param data The formatted 1D array. Not modified. | [
"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 }"
] | [
"public static final CurrencySymbolPosition parseCurrencySymbolPosition(String value)\n {\n CurrencySymbolPosition result = CurrencySymbolPosition.BEFORE;\n\n switch (NumberHelper.getInt(value))\n {\n case 0:\n {\n result = CurrencySymbolPosition.BEFORE;\n break;\n }\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\n return (result);\n }",
"public static VectorTile.Tile.GeomType toGeomType(Geometry geometry) {\n VectorTile.Tile.GeomType result = VectorTile.Tile.GeomType.UNKNOWN;\n\n if(geometry instanceof Point\n || geometry instanceof MultiPoint) {\n result = VectorTile.Tile.GeomType.POINT;\n\n } else if(geometry instanceof LineString\n || geometry instanceof MultiLineString) {\n result = VectorTile.Tile.GeomType.LINESTRING;\n\n } else if(geometry instanceof Polygon\n || geometry instanceof MultiPolygon) {\n result = VectorTile.Tile.GeomType.POLYGON;\n }\n\n return result;\n }",
"protected int mapGanttBarHeight(int height)\n {\n switch (height)\n {\n case 0:\n {\n height = 6;\n break;\n }\n\n case 1:\n {\n height = 8;\n break;\n }\n\n case 2:\n {\n height = 10;\n break;\n }\n\n case 3:\n {\n height = 12;\n break;\n }\n\n case 4:\n {\n height = 14;\n break;\n }\n\n case 5:\n {\n height = 18;\n break;\n }\n\n case 6:\n {\n height = 24;\n break;\n }\n }\n\n return (height);\n }",
"public AT_Row setPaddingLeftChar(Character paddingLeftChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingLeftChar(paddingLeftChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"protected boolean isFiltered(Param param) {\n\t\tAbstractElement elementToParse = param.elementToParse;\n\t\twhile (elementToParse != null) {\n\t\t\tif (isFiltered(elementToParse, param)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telementToParse = getEnclosingSingleElementGroup(elementToParse);\n\t\t}\n\t\treturn false;\n\t}",
"public static 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 Result cmd(String cliCommand) {\n try {\n // The intent here is to return a Response when this is doable.\n if (ctx.isWorkflowMode() || ctx.isBatchMode()) {\n ctx.handle(cliCommand);\n return new Result(cliCommand, ctx.getExitCode());\n }\n handler.parse(ctx.getCurrentNodePath(), cliCommand, ctx);\n if (handler.getFormat() == OperationFormat.INSTANCE) {\n ModelNode request = ctx.buildRequest(cliCommand);\n ModelNode response = ctx.execute(request, cliCommand);\n return new Result(cliCommand, request, response);\n } else {\n ctx.handle(cliCommand);\n return new Result(cliCommand, ctx.getExitCode());\n }\n } catch (CommandLineException cfe) {\n throw new IllegalArgumentException(\"Error handling command: \"\n + cliCommand, cfe);\n } catch (IOException ioe) {\n throw new IllegalStateException(\"Unable to send command \"\n + cliCommand + \" to server.\", ioe);\n }\n }",
"private void addGroups(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (Group group : file.getGroups())\n {\n final Group g = group;\n MpxjTreeNode childNode = new MpxjTreeNode(group)\n {\n @Override public String toString()\n {\n return g.getName();\n }\n };\n parentNode.add(childNode);\n }\n }",
"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 }"
] |
This method is used to parse a string representation of a time
unit, and return the appropriate constant value.
@param units string representation of a time unit
@param locale target locale
@return numeric constant
@throws MPXJException normally thrown when parsing fails | [
"@SuppressWarnings(\"unchecked\") public static TimeUnit getInstance(String units, Locale locale) throws MPXJException\n {\n Map<String, Integer> map = LocaleData.getMap(locale, LocaleData.TIME_UNITS_MAP);\n Integer result = map.get(units.toLowerCase());\n if (result == null)\n {\n throw new MPXJException(MPXJException.INVALID_TIME_UNIT + \" \" + units);\n }\n return (TimeUnit.getInstance(result.intValue()));\n }"
] | [
"public Collection<Contact> getList() throws FlickrException {\r\n \t ContactList<Contact> contacts = new ContactList<Contact>();\r\n \r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element contactsElement = response.getPayload();\r\n contacts.setPage(contactsElement.getAttribute(\"page\"));\r\n contacts.setPages(contactsElement.getAttribute(\"pages\"));\r\n contacts.setPerPage(contactsElement.getAttribute(\"perpage\"));\r\n contacts.setTotal(contactsElement.getAttribute(\"total\"));\r\n NodeList contactNodes = contactsElement.getElementsByTagName(\"contact\");\r\n for (int i = 0; i < contactNodes.getLength(); i++) {\r\n Element contactElement = (Element) contactNodes.item(i);\r\n Contact contact = new Contact();\r\n contact.setId(contactElement.getAttribute(\"nsid\"));\r\n contact.setUsername(contactElement.getAttribute(\"username\"));\r\n contact.setRealName(contactElement.getAttribute(\"realname\"));\r\n contact.setFriend(\"1\".equals(contactElement.getAttribute(\"friend\")));\r\n contact.setFamily(\"1\".equals(contactElement.getAttribute(\"family\")));\r\n contact.setIgnored(\"1\".equals(contactElement.getAttribute(\"ignored\")));\r\n String lPathAlias = contactElement.getAttribute(\"path_alias\");\r\n contact.setPathAlias(lPathAlias == null || \"\".equals(lPathAlias) ? null : lPathAlias);\r\n contact.setOnline(OnlineStatus.fromType(contactElement.getAttribute(\"online\")));\r\n contact.setIconFarm(contactElement.getAttribute(\"iconfarm\"));\r\n contact.setIconServer(contactElement.getAttribute(\"iconserver\"));\r\n if (contact.getOnline() == OnlineStatus.AWAY) {\r\n contactElement.normalize();\r\n contact.setAwayMessage(XMLUtilities.getValue(contactElement));\r\n }\r\n contacts.add(contact);\r\n }\r\n return contacts;\r\n }",
"public String getAttributeValue(String attributeName)\n throws JMException, UnsupportedEncodingException {\n String decodedAttributeName = sanitizer.urlDecode(attributeName, encoding);\n return sanitizer.escapeValue(mBeanServer.getAttribute(objectName, decodedAttributeName));\n }",
"static Object getLCState(StateManagerInternal sm)\r\n\t{\r\n\t\t// unfortunately the LifeCycleState classes are package private.\r\n\t\t// so we have to do some dirty reflection hack to access them\r\n\t\ttry\r\n\t\t{\r\n\t\t\tField myLC = sm.getClass().getDeclaredField(\"myLC\");\r\n\t\t\tmyLC.setAccessible(true);\r\n\t\t\treturn myLC.get(sm);\r\n\t\t}\r\n\t\tcatch (NoSuchFieldException e)\r\n\t\t{\r\n\t\t\treturn e;\r\n\t\t}\r\n\t\tcatch (IllegalAccessException e)\r\n\t\t{\r\n\t\t\treturn e;\r\n\t\t}\t\r\n\t}",
"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 }",
"@SafeVarargs\n public static void registerFilterTypes(final Class<? extends DynamicFilter>... types) {\n FILTER_TYPES.addAll(Arrays.asList(types));\n }",
"public static appfwprofile[] get(nitro_service service) throws Exception{\n\t\tappfwprofile obj = new appfwprofile();\n\t\tappfwprofile[] response = (appfwprofile[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static base_response add(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager addresource = new snmpmanager();\n\t\taddresource.ipaddress = resource.ipaddress;\n\t\taddresource.netmask = resource.netmask;\n\t\taddresource.domainresolveretry = resource.domainresolveretry;\n\t\treturn addresource.add_resource(client);\n\t}",
"public Long getLong(String fieldName) {\n\t\ttry {\n\t\t\treturn hasValue(fieldName) ? Long.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a number.\", e);\n\t\t}\n\t}",
"private List<SynchroTable> readTableHeaders(InputStream is) throws IOException\n {\n // Read the headers\n List<SynchroTable> tables = new ArrayList<SynchroTable>();\n byte[] header = new byte[48];\n while (true)\n {\n is.read(header);\n m_offset += 48;\n SynchroTable table = readTableHeader(header);\n if (table == null)\n {\n break;\n }\n tables.add(table);\n }\n\n // Ensure sorted by offset\n Collections.sort(tables, new Comparator<SynchroTable>()\n {\n @Override public int compare(SynchroTable o1, SynchroTable o2)\n {\n return o1.getOffset() - o2.getOffset();\n }\n });\n\n // Calculate lengths\n SynchroTable previousTable = null;\n for (SynchroTable table : tables)\n {\n if (previousTable != null)\n {\n previousTable.setLength(table.getOffset() - previousTable.getOffset());\n }\n\n previousTable = table;\n }\n\n for (SynchroTable table : tables)\n {\n SynchroLogger.log(\"TABLE\", table);\n }\n\n return tables;\n }"
] |
Get the Avro Schema of the input path, assuming the path contains just one
schema version in all files under that path. | [
"private synchronized Schema getInputPathAvroSchema() throws IOException {\n if (inputPathAvroSchema == null) {\n // No need to query Hadoop more than once as this shouldn't change mid-run,\n // thus, we can lazily initialize and cache the result.\n inputPathAvroSchema = AvroUtils.getAvroSchemaFromPath(getInputPath());\n }\n return inputPathAvroSchema;\n }"
] | [
"public static List<BoxTermsOfService.Info> getAllTermsOfServices(final BoxAPIConnection api,\n BoxTermsOfService.TermsOfServiceType\n termsOfServiceType) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (termsOfServiceType != null) {\n builder.appendParam(\"tos_type\", termsOfServiceType.toString());\n }\n\n URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n BoxAPIRequest request = new BoxAPIRequest(api, 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<BoxTermsOfService.Info> termsOfServices = new ArrayList<BoxTermsOfService.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject termsOfServiceJSON = value.asObject();\n BoxTermsOfService termsOfService = new BoxTermsOfService(api, termsOfServiceJSON.get(\"id\").asString());\n BoxTermsOfService.Info info = termsOfService.new Info(termsOfServiceJSON);\n termsOfServices.add(info);\n }\n\n return termsOfServices;\n }",
"private void reportException(Exception e) {\n\t\tlogger.error(\"Failed to write JSON export: \" + e.toString());\n\t\tthrow new RuntimeException(e.toString(), e);\n\t}",
"public List<String> parseMethodList(String methods) {\n\n String[] methodArray = StringUtils.delimitedListToStringArray(methods, \",\");\n\n List<String> methodList = new ArrayList<String>();\n\n for (String methodName : methodArray) {\n methodList.add(methodName.trim());\n }\n return methodList;\n }",
"@Override\n\tpublic String toNormalizedString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.normalizedString) == null) {\n\t\t\tif(hasZone()) {\n\t\t\t\tstringCache.normalizedString = result = toNormalizedString(IPv6StringCache.normalizedParams);\n\t\t\t} else {\n\t\t\t\tresult = getSection().toNormalizedString();//the cache is shared so no need to update it here\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}",
"@RequestMapping(value=\"/{subscription}\", method=GET, params=\"hub.mode=subscribe\")\n\tpublic @ResponseBody String verifySubscription(\n\t\t\t@PathVariable(\"subscription\") String subscription,\n\t\t\t@RequestParam(\"hub.challenge\") String challenge,\n\t\t\t@RequestParam(\"hub.verify_token\") String verifyToken) {\n\t\tlogger.debug(\"Received subscription verification request for '\" + subscription + \"'.\");\n\t\treturn tokens.containsKey(subscription) && tokens.get(subscription).equals(verifyToken) ? challenge : \"\";\n\t}",
"public PhotoList<Photo> getPopularPhotos(Date date, StatsSort sort, int perPage, int page) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_POPULAR_PHOTOS);\n if (date != null) {\n parameters.put(\"date\", String.valueOf(date.getTime() / 1000L));\n }\n if (sort != null) {\n parameters.put(\"sort\", sort.name());\n }\n addPaginationParameters(parameters, perPage, page);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n return parsePopularPhotos(response);\n }",
"public static autoscalepolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tautoscalepolicy_binding obj = new autoscalepolicy_binding();\n\t\tobj.set_name(name);\n\t\tautoscalepolicy_binding response = (autoscalepolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static boolean containsOnlyNull(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}",
"protected InternalHttpResponse sendInternalRequest(HttpRequest request) {\n InternalHttpResponder responder = new InternalHttpResponder();\n httpResourceHandler.handle(request, responder);\n return responder.getResponse();\n }"
] |
Get the list of all nodes and the list of active nodes in the cluster.
@return Membership object encapsulating lists of all nodes and the cluster nodes
@see <a
href="https://console.bluemix.net/docs/services/Cloudant/api/advanced.html#-get-_membership-">
_membership</a> | [
"public Membership getMembership() {\n URI uri = new URIBase(getBaseUri()).path(\"_membership\").build();\n Membership membership = couchDbClient.get(uri,\n Membership.class);\n return membership;\n }"
] | [
"public static base_responses update(nitro_service client, inat resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tinat updateresources[] = new inat[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new inat();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].privateip = resources[i].privateip;\n\t\t\t\tupdateresources[i].tcpproxy = resources[i].tcpproxy;\n\t\t\t\tupdateresources[i].ftp = resources[i].ftp;\n\t\t\t\tupdateresources[i].tftp = resources[i].tftp;\n\t\t\t\tupdateresources[i].usip = resources[i].usip;\n\t\t\t\tupdateresources[i].usnip = resources[i].usnip;\n\t\t\t\tupdateresources[i].proxyip = resources[i].proxyip;\n\t\t\t\tupdateresources[i].mode = resources[i].mode;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public Set<? extends AbstractBean<?, ?>> resolveSpecializedBeans(Bean<?> specializingBean) {\n if (specializingBean instanceof AbstractClassBean<?>) {\n AbstractClassBean<?> abstractClassBean = (AbstractClassBean<?>) specializingBean;\n if (abstractClassBean.isSpecializing()) {\n return specializedBeans.getValue(specializingBean);\n }\n }\n if (specializingBean instanceof ProducerMethod<?, ?>) {\n ProducerMethod<?, ?> producerMethod = (ProducerMethod<?, ?>) specializingBean;\n if (producerMethod.isSpecializing()) {\n return specializedBeans.getValue(specializingBean);\n }\n }\n return Collections.emptySet();\n }",
"private FieldType addUserDefinedField(FieldTypeClass fieldType, UserFieldDataType dataType, String name)\n {\n FieldType field = null;\n \n try\n {\n switch (fieldType)\n {\n case TASK:\n {\n do\n {\n field = m_taskUdfCounters.nextField(TaskField.class, dataType);\n }\n while (RESERVED_TASK_FIELDS.contains(field));\n\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n\n break;\n }\n \n case RESOURCE:\n {\n field = m_resourceUdfCounters.nextField(ResourceField.class, dataType);\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n break;\n }\n \n case ASSIGNMENT:\n {\n field = m_assignmentUdfCounters.nextField(AssignmentField.class, dataType);\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n break;\n }\n \n default:\n {\n break;\n }\n } \n }\n\n catch (Exception ex)\n {\n //\n // SF#227: If we get an exception thrown here... it's likely that\n // we've run out of user defined fields, for example\n // there are only 30 TEXT fields. We'll ignore this: the user\n // defined field won't be mapped to an alias, so we'll\n // ignore it when we read in the values.\n //\n }\n \n return field;\n }",
"static Type parseType(String value, ResourceLoader resourceLoader) {\n value = value.trim();\n // Wildcards\n if (value.equals(WILDCARD)) {\n return WildcardTypeImpl.defaultInstance();\n }\n if (value.startsWith(WILDCARD_EXTENDS)) {\n Type upperBound = parseType(value.substring(WILDCARD_EXTENDS.length(), value.length()), resourceLoader);\n if (upperBound == null) {\n return null;\n }\n return WildcardTypeImpl.withUpperBound(upperBound);\n }\n if (value.startsWith(WILDCARD_SUPER)) {\n Type lowerBound = parseType(value.substring(WILDCARD_SUPER.length(), value.length()), resourceLoader);\n if (lowerBound == null) {\n return null;\n }\n return WildcardTypeImpl.withLowerBound(lowerBound);\n }\n // Array\n if (value.contains(ARRAY)) {\n Type componentType = parseType(value.substring(0, value.indexOf(ARRAY)), resourceLoader);\n if (componentType == null) {\n return null;\n }\n return new GenericArrayTypeImpl(componentType);\n }\n int chevLeft = value.indexOf(CHEVRONS_LEFT);\n String rawValue = chevLeft < 0 ? value : value.substring(0, chevLeft);\n Class<?> rawRequiredType = tryLoadClass(rawValue, resourceLoader);\n if (rawRequiredType == null) {\n return null;\n }\n if (rawRequiredType.getTypeParameters().length == 0) {\n return rawRequiredType;\n }\n // Parameterized type\n int chevRight = value.lastIndexOf(CHEVRONS_RIGHT);\n if (chevRight < 0) {\n return null;\n }\n List<String> parts = split(value.substring(chevLeft + 1, chevRight), ',', CHEVRONS_LEFT.charAt(0), CHEVRONS_RIGHT.charAt(0));\n Type[] typeParameters = new Type[parts.size()];\n for (int i = 0; i < typeParameters.length; i++) {\n Type typeParam = parseType(parts.get(i), resourceLoader);\n if (typeParam == null) {\n return null;\n }\n typeParameters[i] = typeParam;\n }\n return new ParameterizedTypeImpl(rawRequiredType, typeParameters);\n }",
"@Override\n public final long getLong(final String key) {\n Long result = optLong(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }",
"protected Violation createViolationForImport(SourceCode sourceCode, String className, String alias, String violationMessage) {\n Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, className, alias);\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine((String) importInfo.get(\"sourceLine\"));\n violation.setLineNumber((Integer) importInfo.get(\"lineNumber\"));\n violation.setMessage(violationMessage);\n return violation;\n }",
"public static boolean isStandaloneRunning(final ModelControllerClient client) {\n try {\n final ModelNode response = client.execute(Operations.createReadAttributeOperation(EMPTY_ADDRESS, \"server-state\"));\n if (Operations.isSuccessfulOutcome(response)) {\n final String state = Operations.readResult(response).asString();\n return !CONTROLLER_PROCESS_STATE_STARTING.equals(state)\n && !CONTROLLER_PROCESS_STATE_STOPPING.equals(state);\n }\n } catch (RuntimeException | IOException e) {\n LOGGER.trace(\"Interrupted determining if standalone is running\", e);\n }\n return false;\n }",
"@Override\n public <T extends ViewGroup.MarginLayoutParams> T setSelectionMargin(int marginPx, T layoutParams) {\n return mSelectionGravityState.setSelectionMargin(marginPx, layoutParams);\n }",
"public static boolean isTodoItem(final Document todoItemDoc) {\n return todoItemDoc.containsKey(ID_KEY)\n && todoItemDoc.containsKey(TASK_KEY)\n && todoItemDoc.containsKey(CHECKED_KEY);\n }"
] |
Rollback the last applied patch.
@param contentPolicy the content policy
@param resetConfiguration whether to reset the configuration
@param modification the installation modification
@return the patching result
@throws PatchingException | [
"public PatchingResult rollbackLast(final ContentVerificationPolicy contentPolicy, final boolean resetConfiguration, InstallationManager.InstallationModification modification) throws PatchingException {\n\n // Determine the patch id to rollback\n String patchId;\n final List<String> oneOffs = modification.getPatchIDs();\n if (oneOffs.isEmpty()) {\n patchId = modification.getCumulativePatchID();\n if (patchId == null || Constants.NOT_PATCHED.equals(patchId)) {\n throw PatchLogger.ROOT_LOGGER.noPatchesApplied();\n }\n } else {\n patchId = oneOffs.get(0);//oneOffs.get(oneOffs.size() - 1);\n }\n return rollbackPatch(patchId, contentPolicy, false, resetConfiguration, modification);\n }"
] | [
"public static base_responses add(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 addresources[] = new snmpuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new snmpuser();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].group = resources[i].group;\n\t\t\t\taddresources[i].authtype = resources[i].authtype;\n\t\t\t\taddresources[i].authpasswd = resources[i].authpasswd;\n\t\t\t\taddresources[i].privtype = resources[i].privtype;\n\t\t\t\taddresources[i].privpasswd = resources[i].privpasswd;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public Double score(final String member) {\n return doWithJedis(new JedisCallable<Double>() {\n @Override\n public Double call(Jedis jedis) {\n return jedis.zscore(getKey(), member);\n }\n });\n }",
"protected void setBeanStore(BoundBeanStore beanStore) {\n if (beanStore == null) {\n this.beanStore.remove();\n } else {\n this.beanStore.set(beanStore);\n }\n }",
"public void setWeekDay(String weekDayStr) {\n\n final WeekDay weekDay = WeekDay.valueOf(weekDayStr);\n if ((m_model.getWeekDay() != null) || !m_model.getWeekDay().equals(weekDay)) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDay(weekDay);\n onValueChange();\n }\n });\n\n }\n\n }",
"public static String getClassName(Class<?> c) {\n String name = c.getName();\n return name.substring(name.lastIndexOf('.') + 1, name.length());\n }",
"private void addErrorCorrection(StringBuilder adjustedString, int codewordSize, int dataBlocks, int eccBlocks) {\r\n\r\n int x, poly, startWeight;\r\n\r\n /* Split into codewords and calculate Reed-Solomon error correction codes */\r\n switch (codewordSize) {\r\n case 6:\r\n x = 32;\r\n poly = 0x43;\r\n startWeight = 0x20;\r\n break;\r\n case 8:\r\n x = 128;\r\n poly = 0x12d;\r\n startWeight = 0x80;\r\n break;\r\n case 10:\r\n x = 512;\r\n poly = 0x409;\r\n startWeight = 0x200;\r\n break;\r\n case 12:\r\n x = 2048;\r\n poly = 0x1069;\r\n startWeight = 0x800;\r\n break;\r\n default:\r\n throw new OkapiException(\"Unrecognized codeword size: \" + codewordSize);\r\n }\r\n\r\n ReedSolomon rs = new ReedSolomon();\r\n int[] data = new int[dataBlocks + 3];\r\n int[] ecc = new int[eccBlocks + 3];\r\n\r\n for (int i = 0; i < dataBlocks; i++) {\r\n for (int weight = 0; weight < codewordSize; weight++) {\r\n if (adjustedString.charAt((i * codewordSize) + weight) == '1') {\r\n data[i] += (x >> weight);\r\n }\r\n }\r\n }\r\n\r\n rs.init_gf(poly);\r\n rs.init_code(eccBlocks, 1);\r\n rs.encode(dataBlocks, data);\r\n\r\n for (int i = 0; i < eccBlocks; i++) {\r\n ecc[i] = rs.getResult(i);\r\n }\r\n\r\n for (int i = (eccBlocks - 1); i >= 0; i--) {\r\n for (int weight = startWeight; weight > 0; weight = weight >> 1) {\r\n if ((ecc[i] & weight) != 0) {\r\n adjustedString.append('1');\r\n } else {\r\n adjustedString.append('0');\r\n }\r\n }\r\n }\r\n }",
"public List<Artifact> getArtifacts(final Boolean hasLicense) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactsPath());\n final ClientResponse response = resource.queryParam(ServerAPI.HAS_LICENSE_PARAM, hasLicense.toString())\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to get artifacts\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(ArtifactList.class);\n }",
"@Override\n\tpublic CrawlSession call() {\n\t\tInjector injector = Guice.createInjector(new CoreModule(config));\n\t\tcontroller = injector.getInstance(CrawlController.class);\n\t\tCrawlSession session = controller.call();\n\t\treason = controller.getReason();\n\t\treturn session;\n\t}",
"public String getProfileIdFromClientId(int id) {\n return (String) sqlService.getFromTable(Constants.CLIENT_PROFILE_ID, Constants.GENERIC_ID, id, Constants.DB_TABLE_CLIENT);\n }"
] |
Apply the remote domain model to the local host controller.
@param bootOperations the result of the remote read-domain-model op
@return {@code true} if the model was applied successfully, {@code false} otherwise | [
"private boolean applyRemoteDomainModel(final List<ModelNode> bootOperations, final HostInfo hostInfo) {\n try {\n HostControllerLogger.ROOT_LOGGER.debug(\"Applying domain level boot operations provided by master\");\n SyncModelParameters parameters =\n new SyncModelParameters(domainController, ignoredDomainResourceRegistry,\n hostControllerEnvironment, extensionRegistry, operationExecutor, true, serverProxies, remoteFileRepository, contentRepository);\n final SyncDomainModelOperationHandler handler =\n new SyncDomainModelOperationHandler(hostInfo, parameters);\n final ModelNode operation = APPLY_DOMAIN_MODEL.clone();\n operation.get(DOMAIN_MODEL).set(bootOperations);\n\n final ModelNode result = operationExecutor.execute(OperationBuilder.create(operation).build(), OperationMessageHandler.DISCARD, ModelController.OperationTransactionControl.COMMIT, handler);\n\n final String outcome = result.get(OUTCOME).asString();\n final boolean success = SUCCESS.equals(outcome);\n\n // check if anything we synced triggered reload-required or restart-required.\n // if they did we log a warning on the synced slave.\n if (result.has(RESPONSE_HEADERS)) {\n final ModelNode headers = result.get(RESPONSE_HEADERS);\n if (headers.hasDefined(OPERATION_REQUIRES_RELOAD) && headers.get(OPERATION_REQUIRES_RELOAD).asBoolean()) {\n HostControllerLogger.ROOT_LOGGER.domainModelAppliedButReloadIsRequired();\n }\n if (headers.hasDefined(OPERATION_REQUIRES_RESTART) && headers.get(OPERATION_REQUIRES_RESTART).asBoolean()) {\n HostControllerLogger.ROOT_LOGGER.domainModelAppliedButRestartIsRequired();\n }\n }\n if (!success) {\n ModelNode failureDesc = result.hasDefined(FAILURE_DESCRIPTION) ? result.get(FAILURE_DESCRIPTION) : new ModelNode();\n HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(outcome, failureDesc);\n return false;\n } else {\n return true;\n }\n } catch (Exception e) {\n HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(e);\n return false;\n }\n }"
] | [
"private Double getPercentage(Number number)\n {\n Double result = null;\n\n if (number != null)\n {\n result = Double.valueOf(number.doubleValue() / 100);\n }\n\n return result;\n }",
"private JSONObject getARP(final Context context) {\n try {\n final String nameSpaceKey = getNamespaceARPKey();\n if (nameSpaceKey == null) return null;\n\n final SharedPreferences prefs = StorageHelper.getPreferences(context, nameSpaceKey);\n final Map<String, ?> all = prefs.getAll();\n final Iterator<? extends Map.Entry<String, ?>> iter = all.entrySet().iterator();\n\n while (iter.hasNext()) {\n final Map.Entry<String, ?> kv = iter.next();\n final Object o = kv.getValue();\n if (o instanceof Number && ((Number) o).intValue() == -1) {\n iter.remove();\n }\n }\n final JSONObject ret = new JSONObject(all);\n getConfigLogger().verbose(getAccountId(), \"Fetched ARP for namespace key: \" + nameSpaceKey + \" values: \" + all.toString());\n return ret;\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"Failed to construct ARP object\", t);\n return null;\n }\n }",
"@Deprecated\r\n public Location resolvePlaceURL(String flickrPlacesUrl) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_RESOLVE_PLACE_URL);\r\n\r\n parameters.put(\"url\", flickrPlacesUrl);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }",
"public static double Bhattacharyya(double[] histogram1, double[] histogram2) {\n int bins = histogram1.length; // histogram bins\n double b = 0; // Bhattacharyya's coefficient\n\n for (int i = 0; i < bins; i++)\n b += Math.sqrt(histogram1[i]) * Math.sqrt(histogram2[i]);\n\n // Bhattacharyya distance between the two distributions\n return Math.sqrt(1.0 - b);\n }",
"public static base_response rename(nitro_service client, gslbservice resource, String new_servicename) throws Exception {\n\t\tgslbservice renameresource = new gslbservice();\n\t\trenameresource.servicename = resource.servicename;\n\t\treturn renameresource.rename_resource(client,new_servicename);\n\t}",
"@SuppressWarnings(\"SameParameterValue\")\n private void sendField(Field field) throws IOException {\n if (isConnected()) {\n try {\n field.write(channel);\n } catch (IOException e) {\n logger.warn(\"Problem trying to write field to dbserver, closing connection\", e);\n close();\n throw e;\n }\n return;\n }\n throw new IOException(\"sendField() called after dbserver connection was closed\");\n }",
"private boolean validate(CmsFavoriteEntry entry) {\n\n try {\n String siteRoot = entry.getSiteRoot();\n if (!m_okSiteRoots.contains(siteRoot)) {\n m_rootCms.readResource(siteRoot);\n m_okSiteRoots.add(siteRoot);\n }\n CmsUUID project = entry.getProjectId();\n if (!m_okProjects.contains(project)) {\n m_cms.readProject(project);\n m_okProjects.add(project);\n }\n for (CmsUUID id : Arrays.asList(entry.getDetailId(), entry.getStructureId())) {\n if ((id != null) && !m_okStructureIds.contains(id)) {\n m_cms.readResource(id, CmsResourceFilter.IGNORE_EXPIRATION.addRequireVisible());\n m_okStructureIds.add(id);\n }\n }\n return true;\n\n } catch (Exception e) {\n LOG.info(\"Favorite entry validation failed: \" + e.getLocalizedMessage(), e);\n return false;\n }\n\n }",
"@Override\n\tpublic Set<String> getRoundingNames(String... providers) {\n Set<String> result = new HashSet<>();\n String[] providerNames = providers;\n if (providerNames.length == 0) {\n providerNames = Monetary.getDefaultRoundingProviderChain().toArray(new String[Monetary.getDefaultRoundingProviderChain().size()]);\n }\n for (String providerName : providerNames) {\n for (RoundingProviderSpi prov : Bootstrap.getServices(RoundingProviderSpi.class)) {\n try {\n if (prov.getProviderName().equals(providerName) || prov.getProviderName().matches(providerName)) {\n result.addAll(prov.getRoundingNames());\n }\n } catch (Exception e) {\n Logger.getLogger(DefaultMonetaryRoundingsSingletonSpi.class.getName())\n .log(Level.SEVERE, \"Error loading RoundingProviderSpi from provider: \" + prov, e);\n }\n }\n }\n return result;\n }",
"private void readColumn(int startIndex, int length) throws Exception\n {\n if (m_currentTable != null)\n {\n int value = FastTrackUtility.getByte(m_buffer, startIndex);\n Class<?> klass = COLUMN_MAP[value];\n if (klass == null)\n {\n klass = UnknownColumn.class;\n }\n\n FastTrackColumn column = (FastTrackColumn) klass.newInstance();\n m_currentColumn = column;\n\n logColumnData(startIndex, length);\n\n column.read(m_currentTable.getType(), m_buffer, startIndex, length);\n FastTrackField type = column.getType();\n\n //\n // Don't try to add this data if:\n // 1. We don't know what type it is\n // 2. We have seen the type already\n //\n if (type != null && !m_currentFields.contains(type))\n {\n m_currentFields.add(type);\n m_currentTable.addColumn(column);\n updateDurationTimeUnit(column);\n updateWorkTimeUnit(column);\n\n logColumn(column);\n }\n }\n }"
] |
Counts a single pair of coordinates in all datasets.
@param xCoord
@param yCoord
@param itemDocument | [
"private void countCoordinates(int xCoord, int yCoord,\n\t\t\tItemDocument itemDocument) {\n\n\t\tfor (String siteKey : itemDocument.getSiteLinks().keySet()) {\n\t\t\tInteger count = this.siteCounts.get(siteKey);\n\t\t\tif (count == null) {\n\t\t\t\tthis.siteCounts.put(siteKey, 1);\n\t\t\t} else {\n\t\t\t\tthis.siteCounts.put(siteKey, count + 1);\n\t\t\t}\n\t\t}\n\n\t\tfor (ValueMap vm : this.valueMaps) {\n\t\t\tvm.countCoordinates(xCoord, yCoord, itemDocument);\n\t\t}\n\t}"
] | [
"public Iterator select(String predicate) throws org.odmg.QueryInvalidException\r\n {\r\n return this.query(predicate).iterator();\r\n }",
"public void configure(Properties props) throws HibernateException {\r\n\t\ttry{\r\n\t\t\tthis.config = new BoneCPConfig(props);\r\n\r\n\t\t\t// old hibernate config\r\n\t\t\tString url = props.getProperty(CONFIG_CONNECTION_URL);\r\n\t\t\tString username = props.getProperty(CONFIG_CONNECTION_USERNAME);\r\n\t\t\tString password = props.getProperty(CONFIG_CONNECTION_PASSWORD);\r\n\t\t\tString driver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS);\r\n\t\t\tif (url == null){\r\n\t\t\t\turl = props.getProperty(CONFIG_CONNECTION_URL_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (username == null){\r\n\t\t\t\tusername = props.getProperty(CONFIG_CONNECTION_USERNAME_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (password == null){\r\n\t\t\t\tpassword = props.getProperty(CONFIG_CONNECTION_PASSWORD_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (driver == null){\r\n\t\t\t\tdriver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS_ALTERNATE);\r\n\t\t\t}\r\n\r\n\t\t\tif (url != null){\r\n\t\t\t\tthis.config.setJdbcUrl(url);\r\n\t\t\t}\r\n\t\t\tif (username != null){\r\n\t\t\t\tthis.config.setUsername(username);\r\n\t\t\t}\r\n\t\t\tif (password != null){\r\n\t\t\t\tthis.config.setPassword(password);\r\n\t\t\t}\r\n\r\n\r\n\t\t\t// Remember Isolation level\r\n\t\t\tthis.isolation = ConfigurationHelper.getInteger(AvailableSettings.ISOLATION, props);\r\n\t\t\tthis.autocommit = ConfigurationHelper.getBoolean(AvailableSettings.AUTOCOMMIT, props);\r\n\r\n\t\t\tlogger.debug(this.config.toString());\r\n\r\n\t\t\tif (driver != null && !driver.trim().equals(\"\")){\r\n\t\t\t\tloadClass(driver);\r\n\t\t\t}\r\n\t\t\tif (this.config.getConnectionHookClassName() != null){\r\n\t\t\t\tObject hookClass = loadClass(this.config.getConnectionHookClassName()).newInstance();\r\n\t\t\t\tthis.config.setConnectionHook((ConnectionHook) hookClass);\r\n\t\t\t}\r\n\t\t\t// create the connection pool\r\n\t\t\tthis.pool = createPool(this.config);\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new HibernateException(e);\r\n\t\t}\r\n\t}",
"private static void close(Closeable closeable) {\n\t\tif (closeable != null) {\n\t\t\ttry {\n\t\t\t\tcloseable.close();\n\t\t\t} catch (IOException ignored) {\n\t\t\t\tlogger.error(\"Failed to close output stream: \"\n\t\t\t\t\t\t+ ignored.getMessage());\n\t\t\t}\n\t\t}\n\t}",
"private 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 }",
"public static final Bytes of(String s, Charset c) {\n Objects.requireNonNull(s);\n Objects.requireNonNull(c);\n if (s.isEmpty()) {\n return EMPTY;\n }\n byte[] data = s.getBytes(c);\n return new Bytes(data);\n }",
"public void fireAssignmentWrittenEvent(ResourceAssignment resourceAssignment)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.assignmentWritten(resourceAssignment);\n }\n }\n }",
"public int[] executeBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final Method methodSendBatch = (Method) m_batchStatementsInProgress.remove(stmt);\r\n final boolean statementBatchingSupported = methodSendBatch != null;\r\n\r\n int[] retval = null;\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n // sendBatch() returns total row count as an Integer\r\n methodSendBatch.invoke(stmt, null);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new PlatformException(e.getLocalizedMessage(), e);\r\n }\r\n }\r\n else\r\n {\r\n retval = super.executeBatch(stmt);\r\n }\r\n return retval;\r\n }",
"public List<String> getListAttribute(String section, String name) {\n return split(getAttribute(section, name));\n }",
"public static Set<String> listLinks(OperationContext context, PathAddress overlayAddress) {\n Resource overlayResource = context.readResourceFromRoot(overlayAddress);\n if (overlayResource.hasChildren(DEPLOYMENT)) {\n return overlayResource.getChildrenNames(DEPLOYMENT);\n }\n return Collections.emptySet();\n }"
] |
Updates the options panel for a special configuration.
@param gitConfig the git configuration. | [
"protected void updateForNewConfiguration(CmsGitConfiguration gitConfig) {\n\n if (!m_checkinBean.setCurrentConfiguration(gitConfig)) {\n Notification.show(\n CmsVaadinUtils.getMessageText(Messages.GUI_GIT_CONFIGURATION_SWITCH_FAILED_0),\n CmsVaadinUtils.getMessageText(Messages.GUI_GIT_CONFIGURATION_SWITCH_FAILED_DESC_0),\n Type.ERROR_MESSAGE);\n m_configurationSelector.select(m_checkinBean.getCurrentConfiguration());\n return;\n }\n\n resetSelectableModules();\n for (final String moduleName : gitConfig.getConfiguredModules()) {\n addSelectableModule(moduleName);\n }\n updateNewModuleSelector();\n m_pullFirst.setValue(Boolean.valueOf(gitConfig.getDefaultAutoPullBefore()));\n m_pullAfterCommit.setValue(Boolean.valueOf(gitConfig.getDefaultAutoPullAfter()));\n m_addAndCommit.setValue(Boolean.valueOf(gitConfig.getDefaultAutoCommit()));\n m_pushAutomatically.setValue(Boolean.valueOf(gitConfig.getDefaultAutoPush()));\n m_commitMessage.setValue(Strings.nullToEmpty(gitConfig.getDefaultCommitMessage()));\n m_copyAndUnzip.setValue(Boolean.valueOf(gitConfig.getDefaultCopyAndUnzip()));\n m_excludeLib.setValue(Boolean.valueOf(gitConfig.getDefaultExcludeLibs()));\n m_ignoreUnclean.setValue(Boolean.valueOf(gitConfig.getDefaultIngoreUnclean()));\n m_userField.setValue(Strings.nullToEmpty(gitConfig.getDefaultGitUserName()));\n m_emailField.setValue(Strings.nullToEmpty(gitConfig.getDefaultGitUserEmail()));\n\n }"
] | [
"public int tally() {\n long currentTimeMillis = clock.currentTimeMillis();\n\n // calculates time for which we remove any errors before\n final long removeTimesBeforeMillis = currentTimeMillis - windowMillis;\n\n synchronized (queue) {\n // drain out any expired timestamps but don't drain past empty\n while (!queue.isEmpty() && queue.peek() < removeTimesBeforeMillis) {\n queue.removeFirst();\n }\n return queue.size();\n }\n }",
"public String getHealthMemory() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"Logging JVM Stats\\n\");\n MonitorProvider mp = MonitorProvider.getInstance();\n PerformUsage perf = mp.getJVMMemoryUsage();\n sb.append(perf.toString());\n\n if (perf.memoryUsagePercent >= THRESHOLD_PERCENT) {\n sb.append(\"========= WARNING: MEM USAGE > \" + THRESHOLD_PERCENT\n + \"!!\");\n sb.append(\" !! Live Threads List=============\\n\");\n sb.append(mp.getThreadUsage().toString());\n sb.append(\"========================================\\n\");\n sb.append(\"========================JVM Thread Dump====================\\n\");\n ThreadInfo[] threadDump = mp.getThreadDump();\n for (ThreadInfo threadInfo : threadDump) {\n sb.append(threadInfo.toString() + \"\\n\");\n }\n sb.append(\"===========================================================\\n\");\n }\n sb.append(\"Logged JVM Stats\\n\");\n\n return sb.toString();\n }",
"public boolean runOnMainThreadNext(Runnable r) {\n assert handler != null;\n\n if (!sanityCheck(\"runOnMainThreadNext \" + r)) {\n return false;\n }\n return handler.post(r);\n }",
"private String appendXmlStartTag(String value) {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"<\").append(value).append(\">\");\n\r\n return sb.toString();\r\n }",
"public void swapSubstring(BitString other, int start, int length)\n {\n assertValidIndex(start);\n other.assertValidIndex(start);\n \n int word = start / WORD_LENGTH;\n\n int partialWordSize = (WORD_LENGTH - start) % WORD_LENGTH;\n if (partialWordSize > 0)\n {\n swapBits(other, word, 0xFFFFFFFF << (WORD_LENGTH - partialWordSize));\n ++word;\n }\n\n int remainingBits = length - partialWordSize;\n int stop = remainingBits / WORD_LENGTH;\n for (int i = word; i < stop; i++)\n {\n int temp = data[i];\n data[i] = other.data[i];\n other.data[i] = temp;\n }\n\n remainingBits %= WORD_LENGTH;\n if (remainingBits > 0)\n {\n swapBits(other, word, 0xFFFFFFFF >>> (WORD_LENGTH - remainingBits));\n }\n }",
"protected void prepareRequest(List<BoxAPIRequest> requests) {\n JsonObject body = new JsonObject();\n JsonArray requestsJSONArray = new JsonArray();\n for (BoxAPIRequest request: requests) {\n JsonObject batchRequest = new JsonObject();\n batchRequest.add(\"method\", request.getMethod());\n batchRequest.add(\"relative_url\", request.getUrl().toString().substring(this.api.getBaseURL().length() - 1));\n //If the actual request has a JSON body then add it to vatch request\n if (request instanceof BoxJSONRequest) {\n BoxJSONRequest jsonRequest = (BoxJSONRequest) request;\n batchRequest.add(\"body\", jsonRequest.getBodyAsJsonValue());\n }\n //Add any headers that are in the request, except Authorization\n if (request.getHeaders() != null) {\n JsonObject batchRequestHeaders = new JsonObject();\n for (RequestHeader header: request.getHeaders()) {\n if (header.getKey() != null && !header.getKey().isEmpty()\n && !HttpHeaders.AUTHORIZATION.equals(header.getKey())) {\n batchRequestHeaders.add(header.getKey(), header.getValue());\n }\n }\n batchRequest.add(\"headers\", batchRequestHeaders);\n }\n\n //Add the request to array\n requestsJSONArray.add(batchRequest);\n }\n //Add the requests array to body\n body.add(\"requests\", requestsJSONArray);\n super.setBody(body);\n }",
"private String getPropertyLabel(PropertyIdValue propertyIdValue) {\n\t\tPropertyRecord propertyRecord = this.propertyRecords\n\t\t\t\t.get(propertyIdValue);\n\t\tif (propertyRecord == null || propertyRecord.propertyDocument == null) {\n\t\t\treturn propertyIdValue.getId();\n\t\t} else {\n\t\t\treturn getLabel(propertyIdValue, propertyRecord.propertyDocument);\n\t\t}\n\t}",
"static void handleNotificationClicked(Context context,Bundle notification) {\n if (notification == null) return;\n\n String _accountId = null;\n try {\n _accountId = notification.getString(Constants.WZRK_ACCT_ID_KEY);\n } catch (Throwable t) {\n // no-op\n }\n\n if (instances == null) {\n CleverTapAPI instance = createInstanceIfAvailable(context, _accountId);\n if (instance != null) {\n instance.pushNotificationClickedEvent(notification);\n }\n return;\n }\n\n for (String accountId: instances.keySet()) {\n CleverTapAPI instance = CleverTapAPI.instances.get(accountId);\n boolean shouldProcess = false;\n if (instance != null) {\n shouldProcess = (_accountId == null && instance.config.isDefaultInstance()) || instance.getAccountId().equals(_accountId);\n }\n if (shouldProcess) {\n instance.pushNotificationClickedEvent(notification);\n break;\n }\n }\n }",
"public double getValue(int[] batch) {\n double value = 0.0;\n for (int i=0; i<batch.length; i++) {\n value += getValue(i);\n }\n return value;\n }"
] |
Decompiles the given .class file and creates the specified output source file.
@param classFilePath the .class file to be decompiled.
@param outputDir The directory where decompiled .java files will be placed. | [
"@Override\n public DecompilationResult decompileClassFile(Path rootDir, Path classFilePath, Path outputDir)\n throws DecompilationException\n {\n Checks.checkDirectoryToBeRead(rootDir.toFile(), \"Classes root dir\");\n File classFile = classFilePath.toFile();\n Checks.checkFileToBeRead(classFile, \"Class file\");\n Checks.checkDirectoryToBeFilled(outputDir.toFile(), \"Output directory\");\n\n log.info(\"Decompiling .class '\" + classFilePath + \"' to '\" + outputDir + \"' from: '\" + rootDir + \"'\");\n\n String name = classFilePath.normalize().toAbsolutePath().toString().substring(rootDir.toAbsolutePath().toString().length() + 1);\n final String typeName = StringUtils.removeEnd(name, \".class\");// .replace('/', '.');\n\n DecompilationResult result = new DecompilationResult();\n try\n {\n DecompilerSettings settings = getDefaultSettings(outputDir.toFile());\n this.procyonConf.setDecompilerSettings(settings); // TODO: This is horrible mess.\n\n final ITypeLoader typeLoader = new CompositeTypeLoader(new WindupClasspathTypeLoader(rootDir.toString()), new ClasspathTypeLoader());\n WindupMetadataSystem metadataSystem = new WindupMetadataSystem(typeLoader);\n File outputFile = this.decompileType(settings, metadataSystem, typeName);\n result.addDecompiled(Collections.singletonList(classFilePath.toString()), outputFile.getAbsolutePath());\n }\n catch (Throwable e)\n {\n DecompilationFailure failure = new DecompilationFailure(\"Error during decompilation of \"\n + classFilePath.toString() + \":\\n \" + e.getMessage(), Collections.singletonList(name), e);\n log.severe(failure.getMessage());\n result.addFailure(failure);\n }\n\n return result;\n }"
] | [
"private String formatUnits(Number value)\n {\n return (value == null ? null : m_formats.getUnitsDecimalFormat().format(value.doubleValue() / 100));\n }",
"public ArrayList<String> getCarouselImages(){\n ArrayList<String> carouselImages = new ArrayList<>();\n for(CTInboxMessageContent ctInboxMessageContent: getInboxMessageContents()){\n carouselImages.add(ctInboxMessageContent.getMedia());\n }\n return carouselImages;\n }",
"public static List<Number> findIndexValues(Object self, Closure closure) {\n return findIndexValues(self, 0, closure);\n }",
"public static void dumpClusters(Cluster currentCluster,\n Cluster finalCluster,\n String outputDirName,\n String filePrefix) {\n dumpClusterToFile(outputDirName, filePrefix + currentClusterFileName, currentCluster);\n dumpClusterToFile(outputDirName, filePrefix + finalClusterFileName, finalCluster);\n }",
"private void processSubProjects()\n {\n int subprojectIndex = 1;\n for (Task task : m_project.getTasks())\n {\n String subProjectFileName = task.getSubprojectName();\n if (subProjectFileName != null)\n {\n String fileName = subProjectFileName;\n int offset = 0x01000000 + (subprojectIndex * 0x00400000);\n int index = subProjectFileName.lastIndexOf('\\\\');\n if (index != -1)\n {\n fileName = subProjectFileName.substring(index + 1);\n }\n\n SubProject sp = new SubProject();\n sp.setFileName(fileName);\n sp.setFullPath(subProjectFileName);\n sp.setUniqueIDOffset(Integer.valueOf(offset));\n sp.setTaskUniqueID(task.getUniqueID());\n task.setSubProject(sp);\n\n ++subprojectIndex;\n }\n }\n }",
"public void setVec4(String key, float x, float y, float z, float w)\n {\n checkKeyIsUniform(key);\n NativeLight.setVec4(getNative(), key, x, y, z, w);\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 }",
"private void processDefaultCurrency(Integer currencyID) throws SQLException\n {\n List<Row> rows = getRows(\"select * from \" + m_schema + \"currtype where curr_id=?\", currencyID);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n m_reader.processDefaultCurrency(row);\n }\n }",
"protected void restoreAutoCommitState()\r\n {\r\n try\r\n {\r\n if(!broker.isManaged())\r\n {\r\n if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE\r\n && originalAutoCommitState == true && con != null && !con.isClosed())\r\n {\r\n platform.changeAutoCommitState(jcd, con, true);\r\n }\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled()) log.debug(\r\n \"Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n // should never be reached\r\n throw new OJBRuntimeException(\"Restore of connection autocommit state failed\", e);\r\n }\r\n }"
] |
Creates a searchable item that represents a metadata field found for a track.
@param menuItem the rendered menu item containing the searchable metadata field
@return the searchable metadata field | [
"private SearchableItem buildSearchableItem(Message menuItem) {\n return new SearchableItem((int) ((NumberField) menuItem.arguments.get(1)).getValue(),\n ((StringField) menuItem.arguments.get(3)).getValue());\n }"
] | [
"public PortComponentMetaData getPortComponentByWsdlPort(String name)\n {\n ArrayList<String> pcNames = new ArrayList<String>();\n for (PortComponentMetaData pc : portComponents)\n {\n String wsdlPortName = pc.getWsdlPort().getLocalPart();\n if (wsdlPortName.equals(name))\n return pc;\n\n pcNames.add(wsdlPortName);\n }\n\n Loggers.METADATA_LOGGER.cannotGetPortComponentName(name, pcNames);\n return null;\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<PaxDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<PaxDate>) super.zonedDateTime(temporal);\n }",
"@Override\n\tpublic Object[] getDatabaseSnapshot(Serializable id, SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\n\t\tif ( log.isTraceEnabled() ) {\n\t\t\tlog.trace( \"Getting current persistent state for: \" + MessageHelper.infoString( this, id, getFactory() ) );\n\t\t}\n\n\t\t//snapshot is a Map in the end\n\t\tfinal Tuple resultset = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );\n\n\t\t//if there is no resulting row, return null\n\t\tif ( resultset == null || resultset.getSnapshot().isEmpty() ) {\n\t\t\treturn null;\n\t\t}\n\t\t//otherwise return the \"hydrated\" state (ie. associations are not resolved)\n\t\tGridType[] types = gridPropertyTypes;\n\t\tObject[] values = new Object[types.length];\n\t\tboolean[] includeProperty = getPropertyUpdateability();\n\t\tfor ( int i = 0; i < types.length; i++ ) {\n\t\t\tif ( includeProperty[i] ) {\n\t\t\t\tvalues[i] = types[i].hydrate( resultset, getPropertyAliases( \"\", i ), session, null ); //null owner ok??\n\t\t\t}\n\t\t}\n\t\treturn values;\n\t}",
"public static inat get(nitro_service service, String name) throws Exception{\n\t\tinat obj = new inat();\n\t\tobj.set_name(name);\n\t\tinat response = (inat) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static dnsview[] get(nitro_service service) throws Exception{\n\t\tdnsview obj = new dnsview();\n\t\tdnsview[] response = (dnsview[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void readCollectionElement(\n\t\tfinal Object optionalOwner,\n\t\tfinal Serializable optionalKey,\n\t\tfinal CollectionPersister persister,\n\t\tfinal CollectionAliases descriptor,\n\t\tfinal ResultSet rs,\n\t\tfinal SharedSessionContractImplementor session)\n\t\t\t\tthrows HibernateException, SQLException {\n\n\t\tfinal PersistenceContext persistenceContext = session.getPersistenceContext();\n\n\t\t//implement persister.readKey using the grid type (later)\n\t\tfinal Serializable collectionRowKey = (Serializable) persister.readKey(\n\t\t\t\trs,\n\t\t\t\tdescriptor.getSuffixedKeyAliases(),\n\t\t\t\tsession\n\t\t);\n\n\t\tif ( collectionRowKey != null ) {\n\t\t\t// we found a collection element in the result set\n\n\t\t\tif ( log.isDebugEnabled() ) {\n\t\t\t\tlog.debug(\n\t\t\t\t\t\t\"found row of collection: \" +\n\t\t\t\t\t\tMessageHelper.collectionInfoString( persister, collectionRowKey, getFactory() )\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tObject owner = optionalOwner;\n\t\t\tif ( owner == null ) {\n\t\t\t\towner = persistenceContext.getCollectionOwner( collectionRowKey, persister );\n\t\t\t\tif ( owner == null ) {\n\t\t\t\t\t//TODO: This is assertion is disabled because there is a bug that means the\n\t\t\t\t\t//\t original owner of a transient, uninitialized collection is not known\n\t\t\t\t\t//\t if the collection is re-referenced by a different object associated\n\t\t\t\t\t//\t with the current Session\n\t\t\t\t\t//throw new AssertionFailure(\"bug loading unowned collection\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tPersistentCollection rowCollection = persistenceContext.getLoadContexts()\n\t\t\t\t\t.getCollectionLoadContext( rs )\n\t\t\t\t\t.getLoadingCollection( persister, collectionRowKey );\n\n\t\t\tif ( rowCollection != null ) {\n\t\t\t\thydrateRowCollection( persister, descriptor, rs, owner, rowCollection );\n\t\t\t}\n\n\t\t}\n\t\telse if ( optionalKey != null ) {\n\t\t\t// we did not find a collection element in the result set, so we\n\t\t\t// ensure that a collection is created with the owner's identifier,\n\t\t\t// since what we have is an empty collection\n\n\t\t\tif ( log.isDebugEnabled() ) {\n\t\t\t\tlog.debug(\n\t\t\t\t\t\t\"result set contains (possibly empty) collection: \" +\n\t\t\t\t\t\tMessageHelper.collectionInfoString( persister, optionalKey, getFactory() )\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tpersistenceContext.getLoadContexts()\n\t\t\t\t\t.getCollectionLoadContext( rs )\n\t\t\t\t\t.getLoadingCollection( persister, optionalKey ); // handle empty collection\n\n\t\t}\n\n\t\t// else no collection element, but also no owner\n\n\t}",
"public PreparedStatementCreator count(final Dialect dialect) {\n return new PreparedStatementCreator() {\n public PreparedStatement createPreparedStatement(Connection con)\n throws SQLException {\n return getPreparedStatementCreator()\n .setSql(dialect.createCountSelect(builder.toString()))\n .createPreparedStatement(con);\n }\n };\n }",
"public static <T> String listToString(List<T> list, final boolean justValue,\r\n final String separator) {\r\n StringBuilder s = new StringBuilder();\r\n for (Iterator<T> wordIterator = list.iterator(); wordIterator.hasNext();) {\r\n T o = wordIterator.next();\r\n s.append(wordToString(o, justValue, separator));\r\n if (wordIterator.hasNext()) {\r\n s.append(' ');\r\n }\r\n }\r\n return s.toString();\r\n }",
"@Subscribe\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n long millis = e.getExecutionTime();\n String suiteName = e.getDescription().getDisplayName();\n \n List<Long> values = hints.get(suiteName);\n if (values == null) {\n hints.put(suiteName, values = new ArrayList<>());\n }\n values.add(millis);\n while (values.size() > historyLength)\n values.remove(0);\n }"
] |
returns an Array with an Objects NON-PK VALUES
@throws PersistenceBrokerException if there is an erros accessing o field values | [
"protected ValueContainer[] getNonKeyValues(PersistenceBroker broker, ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getNonKeyRwValues(cld, obj);\r\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 }",
"public static Operation createDeployOperation(final DeploymentDescription deployment) {\n Assert.checkNotNullParam(\"deployment\", deployment);\n final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true);\n addDeployOperationStep(builder, deployment);\n return builder.build();\n }",
"public Object newInstance(String className) {\n try {\n return classLoader.loadClass(className).newInstance();\n } catch (Exception e) {\n throw new ScalaInstanceNotFound(className);\n }\n }",
"private static void addEcc(int[] fullstream, int[] datastream, int version, int data_cw, int blocks) {\n\n int ecc_cw = QR_TOTAL_CODEWORDS[version - 1] - data_cw;\n int short_data_block_length = data_cw / blocks;\n int qty_long_blocks = data_cw % blocks;\n int qty_short_blocks = blocks - qty_long_blocks;\n int ecc_block_length = ecc_cw / blocks;\n int i, j, length_this_block, posn;\n\n int[] data_block = new int[short_data_block_length + 2];\n int[] ecc_block = new int[ecc_block_length + 2];\n int[] interleaved_data = new int[data_cw + 2];\n int[] interleaved_ecc = new int[ecc_cw + 2];\n\n posn = 0;\n\n for (i = 0; i < blocks; i++) {\n if (i < qty_short_blocks) {\n length_this_block = short_data_block_length;\n } else {\n length_this_block = short_data_block_length + 1;\n }\n\n for (j = 0; j < ecc_block_length; j++) {\n ecc_block[j] = 0;\n }\n\n for (j = 0; j < length_this_block; j++) {\n data_block[j] = datastream[posn + j];\n }\n\n ReedSolomon rs = new ReedSolomon();\n rs.init_gf(0x11d);\n rs.init_code(ecc_block_length, 0);\n rs.encode(length_this_block, data_block);\n\n for (j = 0; j < ecc_block_length; j++) {\n ecc_block[j] = rs.getResult(j);\n }\n\n for (j = 0; j < short_data_block_length; j++) {\n interleaved_data[(j * blocks) + i] = data_block[j];\n }\n\n if (i >= qty_short_blocks) {\n interleaved_data[(short_data_block_length * blocks) + (i - qty_short_blocks)] = data_block[short_data_block_length];\n }\n\n for (j = 0; j < ecc_block_length; j++) {\n interleaved_ecc[(j * blocks) + i] = ecc_block[ecc_block_length - j - 1];\n }\n\n posn += length_this_block;\n }\n\n for (j = 0; j < data_cw; j++) {\n fullstream[j] = interleaved_data[j];\n }\n for (j = 0; j < ecc_cw; j++) {\n fullstream[j + data_cw] = interleaved_ecc[j];\n }\n }",
"static void prepareTasks(final IdentityPatchContext.PatchEntry entry, final IdentityPatchContext context, final List<PreparedTask> tasks, final List<ContentItem> conflicts) throws PatchingException {\n for (final PatchingTasks.ContentTaskDefinition definition : entry.getTaskDefinitions()) {\n final PatchingTask task = createTask(definition, context, entry);\n if(!task.isRelevant(entry)) {\n continue;\n }\n try {\n // backup and validate content\n if (!task.prepare(entry) || definition.hasConflicts()) {\n // Unless it a content item was manually ignored (or excluded)\n final ContentItem item = task.getContentItem();\n if (!context.isIgnored(item)) {\n conflicts.add(item);\n }\n }\n tasks.add(new PreparedTask(task, entry));\n } catch (IOException e) {\n throw new PatchingException(e);\n }\n }\n }",
"protected void processTaskBaseline(Row row)\n {\n Integer id = row.getInteger(\"TASK_UID\");\n Task task = m_project.getTaskByUniqueID(id);\n if (task != null)\n {\n int index = row.getInt(\"TB_BASE_NUM\");\n\n task.setBaselineDuration(index, MPDUtility.getAdjustedDuration(m_project, row.getInt(\"TB_BASE_DUR\"), MPDUtility.getDurationTimeUnits(row.getInt(\"TB_BASE_DUR_FMT\"))));\n task.setBaselineStart(index, row.getDate(\"TB_BASE_START\"));\n task.setBaselineFinish(index, row.getDate(\"TB_BASE_FINISH\"));\n task.setBaselineWork(index, row.getDuration(\"TB_BASE_WORK\"));\n task.setBaselineCost(index, row.getCurrency(\"TB_BASE_COST\"));\n }\n }",
"private void pushRight( int row ) {\n if( isOffZero(row))\n return;\n\n// B = createB();\n// B.print();\n rotatorPushRight(row);\n int end = N-2-row;\n for( int i = 0; i < end && bulge != 0; i++ ) {\n rotatorPushRight2(row,i+2);\n }\n// }\n }",
"public static void shutdownDomain(final ModelControllerClient client, final int timeout) throws IOException, OperationExecutionException {\n // Note the following two operations used to shutdown a domain don't seem to work well in a composite operation.\n // The operation occasionally sees a java.util.concurrent.CancellationException because the operation client\n // is likely closed before the AsyncFuture.get() is complete. Using a non-composite operation doesn't seem to\n // have this issue.\n\n // First shutdown the servers\n final ModelNode stopServersOp = Operations.createOperation(\"stop-servers\");\n stopServersOp.get(\"blocking\").set(true);\n stopServersOp.get(\"timeout\").set(timeout);\n ModelNode response = client.execute(stopServersOp);\n if (!Operations.isSuccessfulOutcome(response)) {\n throw new OperationExecutionException(\"Failed to stop servers.\", stopServersOp, response);\n }\n\n // Now shutdown the host\n final ModelNode address = determineHostAddress(client);\n final ModelNode shutdownOp = Operations.createOperation(\"shutdown\", address);\n response = client.execute(shutdownOp);\n if (Operations.isSuccessfulOutcome(response)) {\n // Wait until the process has died\n while (true) {\n if (isDomainRunning(client, true)) {\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(\"Failed to shutdown host.\", shutdownOp, response);\n }\n }",
"private int getFlagResource(Country country) {\n return getContext().getResources().getIdentifier(\"country_\" + country.getIso().toLowerCase(), \"drawable\", getContext().getPackageName());\n }"
] |
Create a transformation which takes the alignment settings into account. | [
"private AffineTransform getAlignmentTransform() {\n final int offsetX;\n switch (this.settings.getParams().getAlign()) {\n case LEFT:\n offsetX = 0;\n break;\n case RIGHT:\n offsetX = this.settings.getMaxSize().width - this.settings.getSize().width;\n break;\n case CENTER:\n default:\n offsetX = (int) Math\n .floor(this.settings.getMaxSize().width / 2.0 - this.settings.getSize().width / 2.0);\n break;\n }\n\n final int offsetY;\n switch (this.settings.getParams().getVerticalAlign()) {\n case TOP:\n offsetY = 0;\n break;\n case BOTTOM:\n offsetY = this.settings.getMaxSize().height - this.settings.getSize().height;\n break;\n case MIDDLE:\n default:\n offsetY = (int) Math.floor(this.settings.getMaxSize().height / 2.0 -\n this.settings.getSize().height / 2.0);\n break;\n }\n\n return AffineTransform.getTranslateInstance(Math.round(offsetX), Math.round(offsetY));\n }"
] | [
"public static String getShortClassName(Object o) {\r\n String name = o.getClass().getName();\r\n int index = name.lastIndexOf('.');\r\n if (index >= 0) {\r\n name = name.substring(index + 1);\r\n }\r\n return name;\r\n }",
"public static autoscaleprofile[] get(nitro_service service) throws Exception{\n\t\tautoscaleprofile obj = new autoscaleprofile();\n\t\tautoscaleprofile[] response = (autoscaleprofile[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private boolean matchesFingerprint(byte[] buffer, Pattern fingerprint)\n {\n return fingerprint.matcher(m_charset == null ? new String(buffer) : new String(buffer, m_charset)).matches();\n }",
"public void finishFlow(final String code, final String state) throws ApiException {\n if (account == null)\n throw new IllegalArgumentException(\"Auth is not set\");\n if (codeVerifier == null)\n throw new IllegalArgumentException(\"code_verifier is not set\");\n if (account.getClientId() == null)\n throw new IllegalArgumentException(\"client_id is not set\");\n StringBuilder builder = new StringBuilder();\n builder.append(\"grant_type=\");\n builder.append(encode(\"authorization_code\"));\n builder.append(\"&client_id=\");\n builder.append(encode(account.getClientId()));\n builder.append(\"&code=\");\n builder.append(encode(code));\n builder.append(\"&code_verifier=\");\n builder.append(encode(codeVerifier));\n update(account, builder.toString());\n }",
"public AT_CellContext setPadding(int padding){\r\n\t\tif(padding>-1){\r\n\t\t\tthis.paddingTop = padding;\r\n\t\t\tthis.paddingBottom = padding;\r\n\t\t\tthis.paddingLeft = padding;\r\n\t\t\tthis.paddingRight = padding;\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"private void writeTimeUnitsField(String fieldName, Object value) throws IOException\n {\n TimeUnit val = (TimeUnit) value;\n if (val != m_projectFile.getProjectProperties().getDefaultDurationUnits())\n {\n m_writer.writeNameValuePair(fieldName, val.toString());\n }\n }",
"public static base_response update(nitro_service client, aaaparameter resource) throws Exception {\n\t\taaaparameter updateresource = new aaaparameter();\n\t\tupdateresource.enablestaticpagecaching = resource.enablestaticpagecaching;\n\t\tupdateresource.enableenhancedauthfeedback = resource.enableenhancedauthfeedback;\n\t\tupdateresource.defaultauthtype = resource.defaultauthtype;\n\t\tupdateresource.maxaaausers = resource.maxaaausers;\n\t\tupdateresource.maxloginattempts = resource.maxloginattempts;\n\t\tupdateresource.failedlogintimeout = resource.failedlogintimeout;\n\t\tupdateresource.aaadnatip = resource.aaadnatip;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public synchronized String requestBlock(String name) {\n if (blocks.isEmpty()) {\n return \"exit\";\n }\n\n remainingBlocks.decrementAndGet();\n return blocks.poll().createResponse();\n }",
"public static String createResource(\n CmsObject cmsObject,\n String newLink,\n Locale locale,\n String sitePath,\n String modelFileName,\n String mode,\n String postCreateHandler) {\n\n String[] newLinkParts = newLink.split(\"\\\\|\");\n String rootPath = newLinkParts[1];\n String typeName = newLinkParts[2];\n CmsFile modelFile = null;\n if (StringUtils.equalsIgnoreCase(mode, CmsEditorConstants.MODE_COPY)) {\n try {\n modelFile = cmsObject.readFile(sitePath);\n } catch (CmsException e) {\n LOG.warn(\n \"The resource at path\" + sitePath + \"could not be read. Thus it can not be used as model file.\",\n e);\n }\n }\n CmsADEConfigData adeConfig = OpenCms.getADEManager().lookupConfiguration(cmsObject, rootPath);\n CmsResourceTypeConfig typeConfig = adeConfig.getResourceType(typeName);\n CmsResource newElement = null;\n try {\n CmsObject cmsClone = cmsObject;\n if ((locale != null) && !cmsObject.getRequestContext().getLocale().equals(locale)) {\n // in case the content locale does not match the request context locale, use a clone cms with the appropriate locale\n cmsClone = OpenCms.initCmsObject(cmsObject);\n cmsClone.getRequestContext().setLocale(locale);\n }\n newElement = typeConfig.createNewElement(cmsClone, modelFile, rootPath);\n CmsPair<String, String> handlerParameter = I_CmsCollectorPostCreateHandler.splitClassAndConfig(\n postCreateHandler);\n I_CmsCollectorPostCreateHandler handler = A_CmsResourceCollector.getPostCreateHandler(\n handlerParameter.getFirst());\n handler.onCreate(cmsClone, cmsClone.readFile(newElement), modelFile != null, handlerParameter.getSecond());\n } catch (CmsException e) {\n LOG.error(\"Could not create resource.\", e);\n }\n return newElement == null ? null : cmsObject.getSitePath(newElement);\n }"
] |
Write a duration field to the JSON file.
@param fieldName field name
@param value field value | [
"private void writeDurationField(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 Duration val = (Duration) value;\n if (val.getDuration() != 0)\n {\n Duration minutes = val.convertUnits(TimeUnit.MINUTES, m_projectFile.getProjectProperties());\n long seconds = (long) (minutes.getDuration() * 60.0);\n m_writer.writeNameValuePair(fieldName, seconds);\n }\n }\n }"
] | [
"public static UserStub getStubWithRandomParams(UserTypeVal userType) {\r\n // Java coerces the return type as a Tuple2 of Objects -- but it's declared as a Tuple2 of Doubles!\r\n // Oh the joys of type erasure.\r\n Tuple2<Double, Double> tuple = SocialNetworkUtilities.getRandomGeographicalLocation();\r\n return new UserStub(userType, new Tuple2<>((Double) tuple._1(), (Double) tuple._2()),\r\n SocialNetworkUtilities.getRandomIsSecret());\r\n }",
"public String computeTrackSignature(final String title, final SearchableItem artist, final int duration,\n final WaveformDetail waveformDetail, final BeatGrid beatGrid) {\n final String safeTitle = (title == null)? \"\" : title;\n final String artistName = (artist == null)? \"[no artist]\" : artist.label;\n try {\n // Compute the SHA-1 hash of our fields\n MessageDigest digest = MessageDigest.getInstance(\"SHA1\");\n digest.update(safeTitle.getBytes(\"UTF-8\"));\n digest.update((byte) 0);\n digest.update(artistName.getBytes(\"UTF-8\"));\n digest.update((byte) 0);\n digestInteger(digest, duration);\n digest.update(waveformDetail.getData());\n for (int i = 1; i <= beatGrid.beatCount; i++) {\n digestInteger(digest, beatGrid.getBeatWithinBar(i));\n digestInteger(digest, (int)beatGrid.getTimeWithinTrack(i));\n }\n byte[] result = digest.digest();\n\n // Create a hex string representation of the hash\n StringBuilder hex = new StringBuilder(result.length * 2);\n for (byte aResult : result) {\n hex.append(Integer.toString((aResult & 0xff) + 0x100, 16).substring(1));\n }\n\n return hex.toString();\n\n } catch (NullPointerException e) {\n logger.info(\"Returning null track signature because an input element was null.\", e);\n } catch (NoSuchAlgorithmException e) {\n logger.error(\"Unable to obtain SHA-1 MessageDigest instance for computing track signatures.\", e);\n } catch (UnsupportedEncodingException e) {\n logger.error(\"Unable to work with UTF-8 string encoding for computing track signatures.\", e);\n }\n return null; // We were unable to compute a signature\n }",
"public static vpnvserver_auditnslogpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_auditnslogpolicy_binding obj = new vpnvserver_auditnslogpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_auditnslogpolicy_binding response[] = (vpnvserver_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private String swapStore(String storeName, String directory) throws VoldemortException {\n\n ReadOnlyStorageEngine store = getReadOnlyStorageEngine(metadataStore,\n storeRepository,\n storeName);\n\n if(!Utils.isReadableDir(directory))\n throw new VoldemortException(\"Store directory '\" + directory\n + \"' is not a readable directory.\");\n\n String currentDirPath = store.getCurrentDirPath();\n\n logger.info(\"Swapping RO store '\" + storeName + \"' to version directory '\" + directory\n + \"'\");\n store.swapFiles(directory);\n logger.info(\"Swapping swapped RO store '\" + storeName + \"' to version directory '\"\n + directory + \"'\");\n\n return currentDirPath;\n }",
"public int getMinutesPerMonth()\n {\n return m_minutesPerMonth == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerMonth()) : m_minutesPerMonth.intValue();\n }",
"public static Trajectory resample(Trajectory t, int n){\n\t\tTrajectory t1 = new Trajectory(2);\n\t\t\n\t\tfor(int i = 0; i < t.size(); i=i+n){\n\t\t\tt1.add(t.get(i));\n\t\t}\n\t\t\n\t\treturn t1;\n\t}",
"public static Set<String> listDeployments(Resource deploymentRootResource, Set<String> runtimeNames) {\n Set<Pattern> set = new HashSet<>();\n for (String wildcardExpr : runtimeNames) {\n Pattern pattern = DeploymentOverlayIndex.getPattern(wildcardExpr);\n set.add(pattern);\n }\n return listDeploymentNames(deploymentRootResource, set);\n }",
"public By getWebDriverBy() {\n\n\t\tswitch (how) {\n\t\t\tcase name:\n\t\t\t\treturn By.name(this.value);\n\n\t\t\tcase xpath:\n\t\t\t\t// Work around HLWK driver bug\n\t\t\t\treturn By.xpath(this.value.replaceAll(\"/BODY\\\\[1\\\\]/\", \"/BODY/\"));\n\n\t\t\tcase id:\n\t\t\t\treturn By.id(this.value);\n\n\t\t\tcase tag:\n\t\t\t\treturn By.tagName(this.value);\n\n\t\t\tcase text:\n\t\t\t\treturn By.linkText(this.value);\n\n\t\t\tcase partialText:\n\t\t\t\treturn By.partialLinkText(this.value);\n\n\t\t\tdefault:\n\t\t\t\treturn null;\n\n\t\t}\n\n\t}",
"public void splitSpan(int n) {\n\t\tint x = (xKnots[n] + xKnots[n+1])/2;\n\t\taddKnot(x, getColor(x/256.0f), knotTypes[n]);\n\t\trebuildGradient();\n\t}"
] |
Answer the foreign key query to retrieve the collection
defined by CollectionDescriptor | [
"private Query getFKQuery(Object obj, ClassDescriptor cld, CollectionDescriptor cds)\r\n {\r\n Query fkQuery;\r\n QueryByCriteria fkQueryCrit;\r\n\r\n if (cds.isMtoNRelation())\r\n {\r\n fkQueryCrit = getFKQueryMtoN(obj, cld, cds);\r\n }\r\n else\r\n {\r\n fkQueryCrit = getFKQuery1toN(obj, cld, cds);\r\n }\r\n\r\n // check if collection must be ordered\r\n if (!cds.getOrderBy().isEmpty())\r\n {\r\n Iterator iter = cds.getOrderBy().iterator();\r\n while (iter.hasNext())\r\n {\r\n fkQueryCrit.addOrderBy((FieldHelper)iter.next());\r\n }\r\n }\r\n\r\n // BRJ: customize the query\r\n if (cds.getQueryCustomizer() != null)\r\n {\r\n fkQuery = cds.getQueryCustomizer().customizeQuery(obj, pb, cds, fkQueryCrit);\r\n }\r\n else\r\n {\r\n fkQuery = fkQueryCrit;\r\n }\r\n\r\n return fkQuery;\r\n }"
] | [
"public static double J0(double x) {\r\n double ax;\r\n\r\n if ((ax = Math.abs(x)) < 8.0) {\r\n double y = x * x;\r\n double ans1 = 57568490574.0 + y * (-13362590354.0 + y * (651619640.7\r\n + y * (-11214424.18 + y * (77392.33017 + y * (-184.9052456)))));\r\n double ans2 = 57568490411.0 + y * (1029532985.0 + y * (9494680.718\r\n + y * (59272.64853 + y * (267.8532712 + y * 1.0))));\r\n\r\n return ans1 / ans2;\r\n } else {\r\n double z = 8.0 / ax;\r\n double y = z * z;\r\n double xx = ax - 0.785398164;\r\n double ans1 = 1.0 + y * (-0.1098628627e-2 + y * (0.2734510407e-4\r\n + y * (-0.2073370639e-5 + y * 0.2093887211e-6)));\r\n double ans2 = -0.1562499995e-1 + y * (0.1430488765e-3\r\n + y * (-0.6911147651e-5 + y * (0.7621095161e-6\r\n - y * 0.934935152e-7)));\r\n\r\n return Math.sqrt(0.636619772 / ax) *\r\n (Math.cos(xx) * ans1 - z * Math.sin(xx) * ans2);\r\n }\r\n }",
"public static servicegroup_stats[] get(nitro_service service, options option) throws Exception{\n\t\tservicegroup_stats obj = new servicegroup_stats();\n\t\tservicegroup_stats[] response = (servicegroup_stats[])obj.stat_resources(service,option);\n\t\treturn response;\n\t}",
"private void registerPackageInTypeInterestFactory(String pkg)\n {\n TypeInterestFactory.registerInterest(pkg + \"_pkg\", pkg.replace(\".\", \"\\\\.\"), pkg, TypeReferenceLocation.IMPORT);\n // TODO: Finish the implementation\n }",
"public static boolean isVector(DMatrixSparseCSC a) {\n return (a.numCols == 1 && a.numRows > 1) || (a.numRows == 1 && a.numCols>1);\n }",
"private void writeResourceExtendedAttributes(Project.Resources.Resource xml, Resource mpx)\n {\n Project.Resources.Resource.ExtendedAttribute attrib;\n List<Project.Resources.Resource.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute();\n\n for (ResourceField mpxFieldID : getAllResourceExtendedAttributes())\n {\n Object value = mpx.getCachedValue(mpxFieldID);\n\n if (FieldTypeHelper.valueIsNotDefault(mpxFieldID, value))\n {\n m_extendedAttributesInUse.add(mpxFieldID);\n\n Integer xmlFieldID = Integer.valueOf(MPPResourceField.getID(mpxFieldID) | MPPResourceField.RESOURCE_FIELD_BASE);\n\n attrib = m_factory.createProjectResourcesResourceExtendedAttribute();\n extendedAttributes.add(attrib);\n attrib.setFieldID(xmlFieldID.toString());\n attrib.setValue(DatatypeConverter.printExtendedAttribute(this, value, mpxFieldID.getDataType()));\n attrib.setDurationFormat(printExtendedAttributeDurationFormat(value));\n }\n }\n }",
"private void processConstraints(Row row, Task task)\n {\n ConstraintType constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n Date constraintDate = null;\n\n switch (row.getInt(\"CONSTRAINU\"))\n {\n case 0:\n {\n if (row.getInt(\"PLACEMENT\") == 0)\n {\n constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n }\n else\n {\n constraintType = ConstraintType.AS_LATE_AS_POSSIBLE;\n }\n break;\n }\n\n case 1:\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = row.getDate(\"START_CONSTRAINT_DATE\");\n break;\n }\n\n case 2:\n {\n constraintType = ConstraintType.START_NO_LATER_THAN;\n constraintDate = row.getDate(\"START_CONSTRAINT_DATE\");\n break;\n }\n\n case 3:\n {\n constraintType = ConstraintType.START_NO_EARLIER_THAN;\n constraintDate = row.getDate(\"START_CONSTRAINT_DATE\");\n break;\n }\n\n case 4:\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = row.getDate(\"END_CONSTRAINT_DATE\");\n break;\n }\n\n case 5:\n {\n constraintType = ConstraintType.FINISH_NO_LATER_THAN;\n constraintDate = row.getDate(\"END_CONSTRAINT_DATE\");\n break;\n }\n\n case 6:\n {\n constraintType = ConstraintType.FINISH_NO_EARLIER_THAN;\n constraintDate = row.getDate(\"END_CONSTRAINT_DATE\");\n break;\n }\n\n case 8:\n {\n task.setDeadline(row.getDate(\"END_CONSTRAINT_DATE\"));\n break;\n }\n }\n\n task.setConstraintType(constraintType);\n task.setConstraintDate(constraintDate);\n }",
"public static RgbaColor fromRgba(String rgba) {\n if (rgba.length() == 0) return getDefaultColor();\n\n String[] parts = getRgbaParts(rgba).split(\",\");\n if (parts.length == 4) {\n return new RgbaColor(parseInt(parts[0]),\n parseInt(parts[1]),\n parseInt(parts[2]),\n parseFloat(parts[3]));\n }\n else {\n return getDefaultColor();\n }\n }",
"@Override\n protected void onLoad() {\n\tsuper.onLoad();\n\n\t// these styles need to be the same for the box and shadow so\n\t// that we can measure properly\n\tmatchStyles(\"display\");\n\tmatchStyles(\"fontSize\");\n\tmatchStyles(\"fontFamily\");\n\tmatchStyles(\"fontWeight\");\n\tmatchStyles(\"lineHeight\");\n\tmatchStyles(\"paddingTop\");\n\tmatchStyles(\"paddingRight\");\n\tmatchStyles(\"paddingBottom\");\n\tmatchStyles(\"paddingLeft\");\n\n\tadjustSize();\n }",
"public static double Sin(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return x - (x * x * x) / 6D;\r\n } else {\r\n\r\n double mult = x * x * x;\r\n double fact = 6;\r\n double sign = 1;\r\n int factS = 5;\r\n double result = x - mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += sign * (mult / fact);\r\n sign *= -1;\r\n }\r\n\r\n return result;\r\n }\r\n }"
] |
Only meant to be called once
@throws Exception exception | [
"public void startServer() throws Exception {\n if (!externalDatabaseHost) {\n try {\n this.port = Utils.getSystemPort(Constants.SYS_DB_PORT);\n server = Server.createTcpServer(\"-tcpPort\", String.valueOf(port), \"-tcpAllowOthers\").start();\n } catch (SQLException e) {\n if (e.toString().contains(\"java.net.UnknownHostException\")) {\n logger.error(\"Startup failure. Potential bug in OSX & Java7. Workaround: add name of local machine to '/etc/hosts.'\");\n logger.error(\"Example: 127.0.0.1 MacBook\");\n throw e;\n }\n }\n }\n }"
] | [
"public static appfwwsdl get(nitro_service service, String name) throws Exception{\n\t\tappfwwsdl obj = new appfwwsdl();\n\t\tobj.set_name(name);\n\t\tappfwwsdl response = (appfwwsdl) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void checkOrMarkPrivateAccess(Expression source, FieldNode fn) {\n if (fn!=null && Modifier.isPrivate(fn.getModifiers()) &&\n (fn.getDeclaringClass() != typeCheckingContext.getEnclosingClassNode() || typeCheckingContext.getEnclosingClosure()!=null) &&\n fn.getDeclaringClass().getModule() == typeCheckingContext.getEnclosingClassNode().getModule()) {\n addPrivateFieldOrMethodAccess(source, fn.getDeclaringClass(), StaticTypesMarker.PV_FIELDS_ACCESS, fn);\n }\n }",
"protected CompletableFuture<JsonObjectBuilder> makeBuilder(int instanceId) {\n CompletableFuture<T> futureValue = getValue();\n\n if (futureValue == null) {\n logger.error(\"Could not retrieve value \" + this.getClass().getName());\n return null;\n }\n\n return futureValue\n .exceptionally(\n t -> {\n logger.error(\"Could not retrieve value \" + this.getClass().getName(), t);\n return null;\n })\n .thenApply(\n value -> {\n JsonArrayBuilder perms = Json.createArrayBuilder();\n if (isWritable) {\n perms.add(\"pw\");\n }\n if (isReadable) {\n perms.add(\"pr\");\n }\n if (isEventable) {\n perms.add(\"ev\");\n }\n JsonObjectBuilder builder =\n Json.createObjectBuilder()\n .add(\"iid\", instanceId)\n .add(\"type\", shortType)\n .add(\"perms\", perms.build())\n .add(\"format\", format)\n .add(\"ev\", false)\n .add(\"description\", description);\n setJsonValue(builder, value);\n return builder;\n });\n }",
"public void mergeSubsystem(final GlobalTransformerRegistry registry, String subsystemName, ModelVersion version) {\n final PathElement element = PathElement.pathElement(SUBSYSTEM, subsystemName);\n registry.mergeSubtree(this, PathAddress.EMPTY_ADDRESS.append(element), version);\n }",
"public static gslbdomain_stats[] get(nitro_service service) throws Exception{\n\t\tgslbdomain_stats obj = new gslbdomain_stats();\n\t\tgslbdomain_stats[] response = (gslbdomain_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"public static boolean organizeAssociationMapByRowKey(\n\t\t\torg.hibernate.ogm.model.spi.Association association,\n\t\t\tAssociationKey key,\n\t\t\tAssociationContext associationContext) {\n\n\t\tif ( association.isEmpty() ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif ( key.getMetadata().getRowKeyIndexColumnNames().length != 1 ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tObject valueOfFirstRow = association.get( association.getKeys().iterator().next() )\n\t\t\t\t.get( key.getMetadata().getRowKeyIndexColumnNames()[0] );\n\n\t\tif ( !( valueOfFirstRow instanceof String ) ) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// The list style may be explicitly enforced for compatibility reasons\n\t\treturn getMapStorage( associationContext ) == MapStorageType.BY_KEY;\n\t}",
"private void removeTimedOutLocks(long timeout)\r\n {\r\n int count = 0;\r\n long maxAge = System.currentTimeMillis() - timeout;\r\n boolean breakFromLoop = false;\r\n ObjectLocks temp = null;\r\n \tsynchronized (locktable)\r\n \t{\r\n\t Iterator it = locktable.values().iterator();\r\n\t /**\r\n\t * run this loop while:\r\n\t * - we have more in the iterator\r\n\t * - the breakFromLoop flag hasn't been set\r\n\t * - we haven't removed more than the limit for this cleaning iteration.\r\n\t */\r\n\t while (it.hasNext() && !breakFromLoop && (count <= MAX_LOCKS_TO_CLEAN))\r\n\t {\r\n\t \ttemp = (ObjectLocks) it.next();\r\n\t \tif (temp.getWriter() != null)\r\n\t \t{\r\n\t\t \tif (temp.getWriter().getTimestamp() < maxAge)\r\n\t\t \t{\r\n\t\t \t\t// writer has timed out, set it to null\r\n\t\t \t\ttemp.setWriter(null);\r\n\t\t \t}\r\n\t \t}\r\n\t \tif (temp.getYoungestReader() < maxAge)\r\n\t \t{\r\n\t \t\t// all readers are older than timeout.\r\n\t \t\ttemp.getReaders().clear();\r\n\t \t\tif (temp.getWriter() == null)\r\n\t \t\t{\r\n\t \t\t\t// all readers and writer are older than timeout,\r\n\t \t\t\t// remove the objectLock from the iterator (which\r\n\t \t\t\t// is backed by the map, so it will be removed.\r\n\t \t\t\tit.remove();\r\n\t \t\t}\r\n\t \t}\r\n\t \telse\r\n\t \t{\r\n\t \t\t// we need to walk each reader.\r\n\t \t\tIterator readerIt = temp.getReaders().values().iterator();\r\n\t \t\tLockEntry readerLock = null;\r\n\t \t\twhile (readerIt.hasNext())\r\n\t \t\t{\r\n\t \t\t\treaderLock = (LockEntry) readerIt.next();\r\n\t \t\t\tif (readerLock.getTimestamp() < maxAge)\r\n\t \t\t\t{\r\n\t \t\t\t\t// this read lock is old, remove it.\r\n\t \t\t\t\treaderIt.remove();\r\n\t \t\t\t}\r\n\t \t\t}\r\n\t \t}\r\n\t \tcount++;\r\n\t }\r\n \t}\r\n }",
"static List<List<String>> handleNewLines( List<List<String>> tableModel ) {\n List<List<String>> result = Lists.newArrayListWithExpectedSize( tableModel.size() );\n\n for( List<String> row : tableModel ) {\n if( hasNewline( row ) ) {\n result.addAll( splitRow( row ) );\n } else {\n result.add( row );\n }\n }\n\n return result;\n }",
"public AlbumArt requestArtworkFrom(final DataReference artReference, final CdjStatus.TrackType trackType) {\n ensureRunning();\n AlbumArt artwork = findArtInMemoryCaches(artReference); // First check the in-memory artwork caches.\n if (artwork == null) {\n artwork = requestArtworkInternal(artReference, trackType, false);\n }\n return artwork;\n }"
] |
Use this API to unset the properties of Interface resource.
Properties that need to be unset are specified in args array. | [
"public static base_response unset(nitro_service client, Interface resource, String[] args) throws Exception{\n\t\tInterface unsetresource = new Interface();\n\t\tunsetresource.id = resource.id;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}"
] | [
"public static Collection<String> getFormatProviderNames() {\n Collection<String> providers = Optional.ofNullable(getMonetaryFormatsSpi()).orElseThrow(\n () -> new MonetaryException(\n \"No MonetaryFormatsSingletonSpi loaded, query functionality is not available.\"))\n .getProviderNames();\n if (Objects.isNull(providers)) {\n Logger.getLogger(MonetaryFormats.class.getName()).warning(\n \"No supported rate/conversion providers returned by SPI: \" +\n getMonetaryFormatsSpi().getClass().getName());\n return Collections.emptySet();\n }\n return providers;\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 }",
"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 addJoin(TableAlias left, Object[] leftKeys, TableAlias right, Object[] rightKeys, boolean outer,\r\n String name)\r\n {\r\n TableAlias extAlias, rightCopy;\r\n\r\n left.addJoin(new Join(left, leftKeys, right, rightKeys, outer, name));\r\n\r\n // build join between left and extents of right\r\n if (right.hasExtents())\r\n {\r\n for (int i = 0; i < right.extents.size(); i++)\r\n {\r\n extAlias = (TableAlias) right.extents.get(i);\r\n FieldDescriptor[] extKeys = getExtentFieldDescriptors(extAlias, (FieldDescriptor[]) rightKeys);\r\n\r\n left.addJoin(new Join(left, leftKeys, extAlias, extKeys, true, name));\r\n }\r\n }\r\n\r\n // we need to copy the alias on the right for each extent on the left\r\n if (left.hasExtents())\r\n {\r\n for (int i = 0; i < left.extents.size(); i++)\r\n {\r\n extAlias = (TableAlias) left.extents.get(i);\r\n FieldDescriptor[] extKeys = getExtentFieldDescriptors(extAlias, (FieldDescriptor[]) leftKeys);\r\n rightCopy = right.copy(\"C\" + i);\r\n\r\n // copies are treated like normal extents\r\n right.extents.add(rightCopy);\r\n right.extents.addAll(rightCopy.extents);\r\n\r\n addJoin(extAlias, extKeys, rightCopy, rightKeys, true, name);\r\n }\r\n }\r\n }",
"private CoreLabel makeCoreLabel(String line) {\r\n CoreLabel wi = new CoreLabel();\r\n // wi.line = line;\r\n String[] bits = line.split(\"\\\\s+\");\r\n switch (bits.length) {\r\n case 0:\r\n case 1:\r\n wi.setWord(BOUNDARY);\r\n wi.set(AnswerAnnotation.class, OTHER);\r\n break;\r\n case 2:\r\n wi.setWord(bits[0]);\r\n wi.set(AnswerAnnotation.class, bits[1]);\r\n break;\r\n case 3:\r\n wi.setWord(bits[0]);\r\n wi.setTag(bits[1]);\r\n wi.set(AnswerAnnotation.class, bits[2]);\r\n break;\r\n case 4:\r\n wi.setWord(bits[0]);\r\n wi.setTag(bits[1]);\r\n wi.set(ChunkAnnotation.class, bits[2]);\r\n wi.set(AnswerAnnotation.class, bits[3]);\r\n break;\r\n case 5:\r\n if (flags.useLemmaAsWord) {\r\n wi.setWord(bits[1]);\r\n } else {\r\n wi.setWord(bits[0]);\r\n }\r\n wi.set(LemmaAnnotation.class, bits[1]);\r\n wi.setTag(bits[2]);\r\n wi.set(ChunkAnnotation.class, bits[3]);\r\n wi.set(AnswerAnnotation.class, bits[4]);\r\n break;\r\n default:\r\n throw new RuntimeIOException(\"Unexpected input (many fields): \" + line);\r\n }\r\n wi.set(OriginalAnswerAnnotation.class, wi.get(AnswerAnnotation.class));\r\n return wi;\r\n }",
"protected void addLabelForNumbers(ItemIdValue itemIdValue) {\n\n\t\tString qid = itemIdValue.getId();\n\n\t\ttry {\n\t\t\t// Fetch the online version of the item to make sure we edit the\n\t\t\t// current version:\n\t\t\tItemDocument currentItemDocument = (ItemDocument) dataFetcher\n\t\t\t\t\t.getEntityDocument(qid);\n\t\t\tif (currentItemDocument == null) {\n\t\t\t\tSystem.out.println(\"*** \" + qid\n\t\t\t\t\t\t+ \" could not be fetched. Maybe it has been deleted.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if we still have exactly one numeric value:\n\t\t\tQuantityValue number = currentItemDocument\n\t\t\t\t\t.findStatementQuantityValue(\"P1181\");\n\t\t\tif (number == null) {\n\t\t\t\tSystem.out.println(\"*** No unique numeric value for \" + qid);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if the item is in a known numeric class:\n\t\t\tif (!currentItemDocument.hasStatementValue(\"P31\", numberClasses)) {\n\t\t\t\tSystem.out\n\t\t\t\t\t\t.println(\"*** \"\n\t\t\t\t\t\t\t\t+ qid\n\t\t\t\t\t\t\t\t+ \" is not in a known class of integer numbers. Skipping.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if the value is integer and build label string:\n\t\t\tString numberString;\n\t\t\ttry {\n\t\t\t\tBigInteger intValue = number.getNumericValue()\n\t\t\t\t\t\t.toBigIntegerExact();\n\t\t\t\tnumberString = intValue.toString();\n\t\t\t} catch (ArithmeticException e) {\n\t\t\t\tSystem.out.println(\"*** Numeric value for \" + qid\n\t\t\t\t\t\t+ \" is not an integer: \" + number.getNumericValue());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Construct data to write:\n\t\t\tItemDocumentBuilder itemDocumentBuilder = ItemDocumentBuilder\n\t\t\t\t\t.forItemId(itemIdValue).withRevisionId(\n\t\t\t\t\t\t\tcurrentItemDocument.getRevisionId());\n\t\t\tArrayList<String> languages = new ArrayList<>(\n\t\t\t\t\tarabicNumeralLanguages.length);\n\t\t\tfor (int i = 0; i < arabicNumeralLanguages.length; i++) {\n\t\t\t\tif (!currentItemDocument.getLabels().containsKey(\n\t\t\t\t\t\tarabicNumeralLanguages[i])) {\n\t\t\t\t\titemDocumentBuilder.withLabel(numberString,\n\t\t\t\t\t\t\tarabicNumeralLanguages[i]);\n\t\t\t\t\tlanguages.add(arabicNumeralLanguages[i]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (languages.size() == 0) {\n\t\t\t\tSystem.out.println(\"*** Labels already complete for \" + qid);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogEntityModification(currentItemDocument.getEntityId(),\n\t\t\t\t\tnumberString, languages);\n\n\t\t\tdataEditor.editItemDocument(itemDocumentBuilder.build(), false,\n\t\t\t\t\t\"Set labels to numeric value (Task MB1)\");\n\t\t} catch (MediaWikiApiErrorException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"public static nstrafficdomain_bridgegroup_binding[] get(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_bridgegroup_binding obj = new nstrafficdomain_bridgegroup_binding();\n\t\tobj.set_td(td);\n\t\tnstrafficdomain_bridgegroup_binding response[] = (nstrafficdomain_bridgegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void applyPattern(String primaryPattern, String[] alternativePatterns, char decimalSeparator, char groupingSeparator)\n {\n m_symbols.setDecimalSeparator(decimalSeparator);\n m_symbols.setGroupingSeparator(groupingSeparator);\n\n setDecimalFormatSymbols(m_symbols);\n applyPattern(primaryPattern);\n\n if (alternativePatterns != null && alternativePatterns.length != 0)\n {\n int loop;\n if (m_alternativeFormats == null || m_alternativeFormats.length != alternativePatterns.length)\n {\n m_alternativeFormats = new DecimalFormat[alternativePatterns.length];\n for (loop = 0; loop < alternativePatterns.length; loop++)\n {\n m_alternativeFormats[loop] = new DecimalFormat();\n }\n }\n\n for (loop = 0; loop < alternativePatterns.length; loop++)\n {\n m_alternativeFormats[loop].setDecimalFormatSymbols(m_symbols);\n m_alternativeFormats[loop].applyPattern(alternativePatterns[loop]);\n }\n }\n }",
"private void primeCache() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) {\n if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck\n handleUpdate(new TrackMetadataUpdate(entry.getKey().player, entry.getValue()));\n }\n }\n }\n });\n }"
] |
Parse priority.
@param priority priority value
@return Priority instance | [
"public static final Priority parsePriority(BigInteger priority)\n {\n return (priority == null ? null : Priority.getInstance(priority.intValue()));\n }"
] | [
"private int determineForkedJvmCount(TestsCollection testCollection) {\n int cores = Runtime.getRuntime().availableProcessors();\n int jvmCount;\n if (this.parallelism.equals(PARALLELISM_AUTO)) {\n if (cores >= 8) {\n // Maximum parallel jvms is 4, conserve some memory and memory bandwidth.\n jvmCount = 4;\n } else if (cores >= 4) {\n // Make some space for the aggregator.\n jvmCount = 3;\n } else if (cores == 3) {\n // Yes, three-core chips are a thing.\n jvmCount = 2;\n } else {\n // even for dual cores it usually makes no sense to fork more than one\n // JVM.\n jvmCount = 1;\n }\n } else if (this.parallelism.equals(PARALLELISM_MAX)) {\n jvmCount = Runtime.getRuntime().availableProcessors();\n } else {\n try {\n jvmCount = Math.max(1, Integer.parseInt(parallelism));\n } catch (NumberFormatException e) {\n throw new BuildException(\"parallelism must be 'auto', 'max' or a valid integer: \"\n + parallelism);\n }\n }\n\n if (!testCollection.hasReplicatedSuites()) {\n jvmCount = Math.min(testCollection.testClasses.size(), jvmCount);\n }\n return jvmCount;\n }",
"private void checkGAs(List l)\r\n\t{\r\n\t\tfor (final Iterator i = l.iterator(); i.hasNext();)\r\n\t\t\tif (!(i.next() instanceof GroupAddress))\r\n\t\t\t\tthrow new KNXIllegalArgumentException(\"not a group address list\");\r\n\t}",
"public String getToken() {\n String id = null == answer ? text : answer;\n return Act.app().crypto().generateToken(id);\n }",
"private static JSONObject parseBounds(Bounds bounds) throws JSONException {\n if (bounds != null) {\n JSONObject boundsObject = new JSONObject();\n JSONObject lowerRight = new JSONObject();\n JSONObject upperLeft = new JSONObject();\n\n lowerRight.put(\"x\",\n bounds.getLowerRight().getX().doubleValue());\n lowerRight.put(\"y\",\n bounds.getLowerRight().getY().doubleValue());\n\n upperLeft.put(\"x\",\n bounds.getUpperLeft().getX().doubleValue());\n upperLeft.put(\"y\",\n bounds.getUpperLeft().getY().doubleValue());\n\n boundsObject.put(\"lowerRight\",\n lowerRight);\n boundsObject.put(\"upperLeft\",\n upperLeft);\n\n return boundsObject;\n }\n\n return new JSONObject();\n }",
"public Date getStartTime(Date date)\n {\n Date result = m_startTimeCache.get(date);\n if (result == null)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, null);\n if (ranges == null)\n {\n result = getParentFile().getProjectProperties().getDefaultStartTime();\n }\n else\n {\n result = ranges.getRange(0).getStart();\n }\n result = DateHelper.getCanonicalTime(result);\n m_startTimeCache.put(new Date(date.getTime()), result);\n }\n return result;\n }",
"public List<T> parseList(JsonParser jsonParser) throws IOException {\n List<T> list = new ArrayList<>();\n if (jsonParser.getCurrentToken() == JsonToken.START_ARRAY) {\n while (jsonParser.nextToken() != JsonToken.END_ARRAY) {\n list.add(parse(jsonParser));\n }\n }\n return list;\n }",
"public static gslbservice[] get(nitro_service service) throws Exception{\n\t\tgslbservice obj = new gslbservice();\n\t\tgslbservice[] response = (gslbservice[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void updateWaveform(WaveformPreview preview) {\n this.preview.set(preview);\n if (preview == null) {\n waveformImage.set(null);\n } else {\n BufferedImage image = new BufferedImage(preview.segmentCount, preview.maxHeight, BufferedImage.TYPE_INT_RGB);\n Graphics g = image.getGraphics();\n g.setColor(Color.BLACK);\n g.fillRect(0, 0, preview.segmentCount, preview.maxHeight);\n for (int segment = 0; segment < preview.segmentCount; segment++) {\n g.setColor(preview.segmentColor(segment, false));\n g.drawLine(segment, preview.maxHeight, segment, preview.maxHeight - preview.segmentHeight(segment, false));\n if (preview.isColor) { // We have a front color segment to draw on top.\n g.setColor(preview.segmentColor(segment, true));\n g.drawLine(segment, preview.maxHeight, segment, preview.maxHeight - preview.segmentHeight(segment, true));\n }\n }\n waveformImage.set(image);\n }\n }",
"public synchronized boolean removeTaskFromWaitQ(ParallelTask taskTobeRemoved) {\n boolean removed = false;\n for (ParallelTask task : waitQ) {\n if (task.getTaskId() == taskTobeRemoved.getTaskId()) {\n\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.USER_CANCELED, \"NA\"));\n logger.info(\n \"task {} removed from wait q. This task has been marked as USER CANCELED.\",\n task.getTaskId());\n removed = true;\n }\n }\n\n return removed;\n }"
] |
Parse a map of objects from a JsonParser.
@param jsonParser The JsonParser, preconfigured to be at the START_ARRAY token. | [
"public Map<String, T> parseMap(JsonParser jsonParser) throws IOException {\n HashMap<String, T> map = new HashMap<String, T>();\n while (jsonParser.nextToken() != JsonToken.END_OBJECT) {\n String key = jsonParser.getText();\n jsonParser.nextToken();\n if (jsonParser.getCurrentToken() == JsonToken.VALUE_NULL) {\n map.put(key, null);\n } else{\n map.put(key, parse(jsonParser));\n }\n }\n return map;\n }"
] | [
"public static Cluster swapPartitions(final Cluster nextCandidateCluster,\n final int nodeIdA,\n final int partitionIdA,\n final int nodeIdB,\n final int partitionIdB) {\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n\n // Swap partitions between nodes!\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n nodeIdA,\n Lists.newArrayList(partitionIdB));\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n nodeIdB,\n Lists.newArrayList(partitionIdA));\n\n return returnCluster;\n }",
"public static String getClassName(Class<?> c) {\n String name = c.getName();\n return name.substring(name.lastIndexOf('.') + 1, name.length());\n }",
"public BoxTaskAssignment.Info addAssignment(BoxUser assignTo) {\n JsonObject taskJSON = new JsonObject();\n taskJSON.add(\"type\", \"task\");\n taskJSON.add(\"id\", this.getID());\n\n JsonObject assignToJSON = new JsonObject();\n assignToJSON.add(\"id\", assignTo.getID());\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"task\", taskJSON);\n requestJSON.add(\"assign_to\", assignToJSON);\n\n URL url = ADD_TASK_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxTaskAssignment addedAssignment = new BoxTaskAssignment(this.getAPI(), responseJSON.get(\"id\").asString());\n return addedAssignment.new Info(responseJSON);\n }",
"protected void reportStorageOpTime(long startNs) {\n if(streamStats != null) {\n streamStats.reportStreamingScan(operation);\n streamStats.reportStorageTime(operation,\n Utils.elapsedTimeNs(startNs, System.nanoTime()));\n }\n }",
"public List<Module> getModules(final Map<String, String> filters) throws GrapesCommunicationException {\n final Client client = getClient();\n WebResource resource = client.resource(serverURL).path(RequestUtils.getAllModulesPath());\n for(final Map.Entry<String,String> queryParam: filters.entrySet()){\n resource = resource.queryParam(queryParam.getKey(), queryParam.getValue());\n }\n\n final ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to get filtered modules.\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(new GenericType<List<Module>>(){});\n }",
"public GridCoverage2D call() {\n try {\n BufferedImage coverageImage = this.tiledLayer.createBufferedImage(\n this.tilePreparationInfo.getImageWidth(),\n this.tilePreparationInfo.getImageHeight());\n Graphics2D graphics = coverageImage.createGraphics();\n try {\n for (SingleTilePreparationInfo tileInfo: this.tilePreparationInfo.getSingleTiles()) {\n final TileTask task;\n if (tileInfo.getTileRequest() != null) {\n task = new SingleTileLoaderTask(\n tileInfo.getTileRequest(), this.errorImage, tileInfo.getTileIndexX(),\n tileInfo.getTileIndexY(), this.failOnError, this.registry, this.context);\n } else {\n task = new PlaceHolderImageTask(this.tiledLayer.getMissingTileImage(),\n tileInfo.getTileIndexX(), tileInfo.getTileIndexY());\n }\n Tile tile = task.call();\n if (tile.getImage() != null) {\n graphics.drawImage(tile.getImage(),\n tile.getxIndex() * this.tiledLayer.getTileSize().width,\n tile.getyIndex() * this.tiledLayer.getTileSize().height, null);\n }\n }\n } finally {\n graphics.dispose();\n }\n\n GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null);\n GeneralEnvelope gridEnvelope = new GeneralEnvelope(this.tilePreparationInfo.getMapProjection());\n gridEnvelope.setEnvelope(this.tilePreparationInfo.getGridCoverageOrigin().x,\n this.tilePreparationInfo.getGridCoverageOrigin().y,\n this.tilePreparationInfo.getGridCoverageMaxX(),\n this.tilePreparationInfo.getGridCoverageMaxY());\n return factory.create(this.tiledLayer.createCommonUrl(), coverageImage, gridEnvelope,\n null, null, null);\n } catch (Exception e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }",
"public Set<String> findResourceNames(String location, URI locationUri) throws IOException {\n String filePath = toFilePath(locationUri);\n File folder = new File(filePath);\n if (!folder.isDirectory()) {\n LOGGER.debug(\"Skipping path as it is not a directory: \" + filePath);\n return new TreeSet<>();\n }\n\n String classPathRootOnDisk = filePath.substring(0, filePath.length() - location.length());\n if (!classPathRootOnDisk.endsWith(File.separator)) {\n classPathRootOnDisk = classPathRootOnDisk + File.separator;\n }\n LOGGER.debug(\"Scanning starting at classpath root in filesystem: \" + classPathRootOnDisk);\n return findResourceNamesFromFileSystem(classPathRootOnDisk, location, folder);\n }",
"@Nonnull\n public String getBody() {\n if (body == null) {\n return storage == null ? DEFAULT_BODY : DEFAULT_BODY_STORAGE;\n } else {\n return body;\n }\n }",
"public Object get(String name, ObjectFactory<?> factory) {\n\t\tThreadScopeContext context = ThreadScopeContextHolder.getContext();\n\n\t\tObject result = context.getBean(name);\n\t\tif (null == result) {\n\t\t\tresult = factory.getObject();\n\t\t\tcontext.setBean(name, result);\n\t\t}\n\t\treturn result;\n\t}"
] |
Uncompresses the textual contents in the given map and and writes them to the files
denoted by the keys of the map.
@param dir The base directory into which the files will be written
@param contents The map containing the contents indexed by the filename
@throws IOException If an error occurred | [
"private void writeCompressedTexts(File dir, HashMap contents) throws IOException\r\n {\r\n String filename;\r\n\r\n for (Iterator nameIt = contents.keySet().iterator(); nameIt.hasNext();)\r\n {\r\n filename = (String)nameIt.next();\r\n writeCompressedText(new File(dir, filename), (byte[])contents.get(filename));\r\n }\r\n }"
] | [
"public void applyToPrimaryClassNodes(PrimaryClassNodeOperation body) throws CompilationFailedException {\n Iterator classNodes = getPrimaryClassNodes(body.needSortedInput()).iterator();\n while (classNodes.hasNext()) {\n SourceUnit context = null;\n try {\n ClassNode classNode = (ClassNode) classNodes.next();\n context = classNode.getModule().getContext();\n if (context == null || context.phase < phase || (context.phase == phase && !context.phaseComplete)) {\n int offset = 1;\n Iterator<InnerClassNode> iterator = classNode.getInnerClasses();\n while (iterator.hasNext()) {\n iterator.next();\n offset++;\n }\n body.call(context, new GeneratorContext(this.ast, offset), classNode);\n }\n } catch (CompilationFailedException e) {\n // fall through, getErrorReporter().failIfErrors() will trigger\n } catch (NullPointerException npe) {\n GroovyBugError gbe = new GroovyBugError(\"unexpected NullpointerException\", npe);\n changeBugText(gbe, context);\n throw gbe;\n } catch (GroovyBugError e) {\n changeBugText(e, context);\n throw e;\n } catch (NoClassDefFoundError e) {\n // effort to get more logging in case a dependency of a class is loaded\n // although it shouldn't have\n convertUncaughtExceptionToCompilationError(e);\n } catch (Exception e) {\n convertUncaughtExceptionToCompilationError(e);\n }\n }\n\n getErrorCollector().failIfErrors();\n }",
"public String haikunate() {\n if (tokenHex) {\n tokenChars = \"0123456789abcdef\";\n }\n\n String adjective = randomString(adjectives);\n String noun = randomString(nouns);\n\n StringBuilder token = new StringBuilder();\n if (tokenChars != null && tokenChars.length() > 0) {\n for (int i = 0; i < tokenLength; i++) {\n token.append(tokenChars.charAt(random.nextInt(tokenChars.length())));\n }\n }\n\n return Stream.of(adjective, noun, token.toString())\n .filter(s -> s != null && !s.isEmpty())\n .collect(joining(delimiter));\n }",
"protected void registerUnregisterJMX(boolean doRegister) {\r\n\t\tif (this.mbs == null ){ // this way makes it easier for mocking.\r\n\t\t\tthis.mbs = ManagementFactory.getPlatformMBeanServer();\r\n\t\t}\r\n\t\ttry {\r\n\t\t\tString suffix = \"\";\r\n\r\n\t\t\tif (this.config.getPoolName()!=null){\r\n\t\t\t\tsuffix=\"-\"+this.config.getPoolName();\r\n\t\t\t}\r\n\r\n\t\t\tObjectName name = new ObjectName(MBEAN_BONECP +suffix);\r\n\t\t\tObjectName configname = new ObjectName(MBEAN_CONFIG + suffix);\r\n\r\n\r\n\t\t\tif (doRegister){\r\n\t\t\t\tif (!this.mbs.isRegistered(name)){\r\n\t\t\t\t\tthis.mbs.registerMBean(this.statistics, name);\r\n\t\t\t\t}\r\n\t\t\t\tif (!this.mbs.isRegistered(configname)){\r\n\t\t\t\t\tthis.mbs.registerMBean(this.config, configname);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tif (this.mbs.isRegistered(name)){\r\n\t\t\t\t\tthis.mbs.unregisterMBean(name);\r\n\t\t\t\t}\r\n\t\t\t\tif (this.mbs.isRegistered(configname)){\r\n\t\t\t\t\tthis.mbs.unregisterMBean(configname);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tlogger.error(\"Unable to start/stop JMX\", e);\r\n\t\t}\r\n\t}",
"public static float smoothPulse(float a1, float a2, float b1, float b2, float x) {\n\t\tif (x < a1 || x >= b2)\n\t\t\treturn 0;\n\t\tif (x >= a2) {\n\t\t\tif (x < b1)\n\t\t\t\treturn 1.0f;\n\t\t\tx = (x - b1) / (b2 - b1);\n\t\t\treturn 1.0f - (x*x * (3.0f - 2.0f*x));\n\t\t}\n\t\tx = (x - a1) / (a2 - a1);\n\t\treturn x*x * (3.0f - 2.0f*x);\n\t}",
"public static base_response unset(nitro_service client, snmpoption resource, String[] args) throws Exception{\n\t\tsnmpoption unsetresource = new snmpoption();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public Pixel[] pixels() {\n Pixel[] pixels = new Pixel[count()];\n Point[] points = points();\n for (int k = 0; k < points.length; k++) {\n pixels[k] = pixel(points[k]);\n }\n return pixels;\n }",
"public static ServiceController<DeploymentScanner> addService(final OperationContext context, final PathAddress resourceAddress, final String relativeTo, final String path,\n final int scanInterval, TimeUnit unit, final boolean autoDeployZip,\n final boolean autoDeployExploded, final boolean autoDeployXml, final boolean scanEnabled, final long deploymentTimeout, boolean rollbackOnRuntimeFailure,\n final FileSystemDeploymentService bootTimeService, final ScheduledExecutorService scheduledExecutorService) {\n final DeploymentScannerService service = new DeploymentScannerService(resourceAddress, relativeTo, path, scanInterval, unit, autoDeployZip,\n autoDeployExploded, autoDeployXml, scanEnabled, deploymentTimeout, rollbackOnRuntimeFailure, bootTimeService);\n final ServiceName serviceName = getServiceName(resourceAddress.getLastElement().getValue());\n service.scheduledExecutorValue.inject(scheduledExecutorService);\n final ServiceBuilder<DeploymentScanner> sb = context.getServiceTarget().addService(serviceName, service);\n sb.addDependency(context.getCapabilityServiceName(PATH_MANAGER_CAPABILITY, PathManager.class), PathManager.class, service.pathManagerValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.notification-handler-registry\", null),\n NotificationHandlerRegistry.class, service.notificationRegistryValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.model-controller-client-factory\", null),\n ModelControllerClientFactory.class, service.clientFactoryValue);\n sb.requires(org.jboss.as.server.deployment.Services.JBOSS_DEPLOYMENT_CHAINS);\n sb.addDependency(ControlledProcessStateService.SERVICE_NAME, ControlledProcessStateService.class, service.controlledProcessStateServiceValue);\n return sb.install();\n }",
"void update(Object feature) throws LayerException {\n\t\tSimpleFeatureSource source = getFeatureSource();\n\t\tif (source instanceof SimpleFeatureStore) {\n\t\t\tSimpleFeatureStore store = (SimpleFeatureStore) source;\n\t\t\tString featureId = getFeatureModel().getId(feature);\n\t\t\tFilter filter = filterService.createFidFilter(new String[] { featureId });\n\t\t\ttransactionSynchronization.synchTransaction(store);\n\t\t\tList<Name> names = new ArrayList<Name>();\n\t\t\tMap<String, Attribute> attrMap = getFeatureModel().getAttributes(feature);\n\t\t\tList<Object> values = new ArrayList<Object>();\n\t\t\tfor (Map.Entry<String, Attribute> entry : attrMap.entrySet()) {\n\t\t\t\tString name = entry.getKey();\n\t\t\t\tnames.add(store.getSchema().getDescriptor(name).getName());\n\t\t\t\tvalues.add(entry.getValue().getValue());\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tstore.modifyFeatures(names.toArray(new Name[names.size()]), values.toArray(), filter);\n\t\t\t\tstore.modifyFeatures(store.getSchema().getGeometryDescriptor().getName(), getFeatureModel()\n\t\t\t\t\t\t.getGeometry(feature), filter);\n\t\t\t\tlog.debug(\"Updated feature {} in {}\", featureId, getFeatureSourceName());\n\t\t\t} catch (IOException ioe) {\n\t\t\t\tfeatureModelUsable = false;\n\t\t\t\tthrow new LayerException(ioe, ExceptionCode.LAYER_MODEL_IO_EXCEPTION);\n\t\t\t}\n\t\t} else {\n\t\t\tlog.error(\"Don't know how to create or update \" + getFeatureSourceName() + \", class \"\n\t\t\t\t\t+ source.getClass().getName() + \" does not implement SimpleFeatureStore\");\n\t\t\tthrow new LayerException(ExceptionCode.CREATE_OR_UPDATE_NOT_IMPLEMENTED, getFeatureSourceName(), source\n\t\t\t\t\t.getClass().getName());\n\t\t}\n\t}",
"public void addWatcher(final MongoNamespace namespace,\n final Callback<ChangeEvent<BsonDocument>, Object> watcher) {\n instanceChangeStreamListener.addWatcher(namespace, watcher);\n }"
] |
convert selector used in an upsert statement into a document | [
"Document convertSelectorToDocument(Document selector) {\n Document document = new Document();\n for (String key : selector.keySet()) {\n if (key.startsWith(\"$\")) {\n continue;\n }\n\n Object value = selector.get(key);\n if (!Utils.containsQueryExpression(value)) {\n Utils.changeSubdocumentValue(document, key, value, (AtomicReference<Integer>) null);\n }\n }\n return document;\n }"
] | [
"private Duration getAssignmentWork(ProjectCalendar calendar, TimephasedWork assignment)\n {\n Date assignmentStart = assignment.getStart();\n\n Date splitStart = assignmentStart;\n Date splitFinishTime = calendar.getFinishTime(splitStart);\n Date splitFinish = DateHelper.setTime(splitStart, splitFinishTime);\n\n Duration calendarSplitWork = calendar.getWork(splitStart, splitFinish, TimeUnit.MINUTES);\n Duration assignmentWorkPerDay = assignment.getAmountPerDay();\n Duration splitWork;\n\n double splitMinutes = assignmentWorkPerDay.getDuration();\n splitMinutes *= calendarSplitWork.getDuration();\n splitMinutes /= (8 * 60); // this appears to be a fixed value\n splitWork = Duration.getInstance(splitMinutes, TimeUnit.MINUTES);\n return splitWork;\n }",
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/{clientUUID}\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> updateClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @PathVariable(\"clientUUID\") String clientUUID,\n @RequestParam(required = false) Boolean active,\n @RequestParam(required = false) String friendlyName,\n @RequestParam(required = false) Boolean reset) throws Exception {\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n if (active != null) {\n logger.info(\"Active: {}\", active);\n clientService.updateActive(profileId, clientUUID, active);\n }\n\n if (friendlyName != null) {\n clientService.setFriendlyName(profileId, clientUUID, friendlyName);\n }\n\n if (reset != null && reset) {\n clientService.reset(profileId, clientUUID);\n }\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"client\", clientService.findClient(clientUUID, profileId));\n return valueHash;\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public synchronized void pushInstallReferrer(String source, String medium, String campaign) {\n if (source == null && medium == null && campaign == null) return;\n try {\n // If already pushed, don't send it again\n int status = StorageHelper.getInt(context, \"app_install_status\", 0);\n if (status != 0) {\n Logger.d(\"Install referrer has already been set. Will not override it\");\n return;\n }\n StorageHelper.putInt(context, \"app_install_status\", 1);\n\n if (source != null) source = Uri.encode(source);\n if (medium != null) medium = Uri.encode(medium);\n if (campaign != null) campaign = Uri.encode(campaign);\n\n String uriStr = \"wzrk://track?install=true\";\n if (source != null) uriStr += \"&utm_source=\" + source;\n if (medium != null) uriStr += \"&utm_medium=\" + medium;\n if (campaign != null) uriStr += \"&utm_campaign=\" + campaign;\n\n Uri uri = Uri.parse(uriStr);\n pushDeepLink(uri, true);\n } catch (Throwable t) {\n Logger.v(\"Failed to push install referrer\", t);\n }\n }",
"public void setColorForTotal(int row, int column, Color color){\r\n\t\tint mapC = (colors.length-1) - column;\r\n\t\tint mapR = (colors[0].length-1) - row;\r\n\t\tcolors[mapC][mapR]=color;\t\t\r\n\t}",
"public static String getStateKey(CmsResourceState state) {\n\n StringBuffer sb = new StringBuffer(STATE_PREFIX);\n sb.append(state);\n sb.append(STATE_POSTFIX);\n return sb.toString();\n\n }",
"protected void removeSequence(String sequenceName)\r\n {\r\n // lookup the sequence map for calling DB\r\n Map mapForDB = (Map) sequencesDBMap.get(getBrokerForClass()\r\n .serviceConnectionManager().getConnectionDescriptor().getJcdAlias());\r\n if(mapForDB != null)\r\n {\r\n synchronized(SequenceManagerHighLowImpl.class)\r\n {\r\n mapForDB.remove(sequenceName);\r\n }\r\n }\r\n }",
"public static Region fromName(String name) {\n if (name == null) {\n return null;\n }\n\n Region region = VALUES_BY_NAME.get(name.toLowerCase().replace(\" \", \"\"));\n if (region != null) {\n return region;\n } else {\n return Region.create(name.toLowerCase().replace(\" \", \"\"), name);\n }\n }",
"public synchronized Object[] getIds() {\n String[] keys = getAllKeys();\n int size = keys.length + indexedProps.size();\n Object[] res = new Object[size];\n System.arraycopy(keys, 0, res, 0, keys.length);\n int i = keys.length;\n // now add all indexed properties\n for (Object index : indexedProps.keySet()) {\n res[i++] = index;\n }\n return res;\n }",
"public void drawGeometry(Geometry geometry, SymbolInfo symbol, Color fillColor, Color strokeColor, float lineWidth,\n\t\t\tfloat[] dashArray, Rectangle clipRect) {\n\t\ttemplate.saveState();\n\t\t// clipping code\n\t\tif (clipRect != null) {\n\t\t\ttemplate.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(), clipRect\n\t\t\t\t\t.getHeight());\n\t\t\ttemplate.clip();\n\t\t\ttemplate.newPath();\n\t\t}\n\t\tsetStroke(strokeColor, lineWidth, dashArray);\n\t\tsetFill(fillColor);\n\t\tdrawGeometry(geometry, symbol);\n\t\ttemplate.restoreState();\n\t}"
] |
Delete a path recursively.
@param path a Path pointing to a file or a directory that may not exists anymore.
@throws IOException | [
"public static void deleteRecursively(final Path path) throws IOException {\n DeploymentRepositoryLogger.ROOT_LOGGER.debugf(\"Deleting %s recursively\", path);\n if (Files.exists(path)) {\n Files.walkFileTree(path, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n Files.delete(file);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n DeploymentRepositoryLogger.ROOT_LOGGER.cannotDeleteFile(exc, path);\n throw exc;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n Files.delete(dir);\n return FileVisitResult.CONTINUE;\n }\n });\n }\n }"
] | [
"public boolean measureAll(List<Widget> measuredChildren) {\n boolean changed = false;\n for (int i = 0; i < mContainer.size(); ++i) {\n\n if (!isChildMeasured(i)) {\n Widget child = measureChild(i, false);\n if (child != null) {\n if (measuredChildren != null) {\n measuredChildren.add(child);\n }\n changed = true;\n }\n }\n }\n if (changed) {\n postMeasurement();\n }\n return changed;\n }",
"public static String load(LoadConfiguration config, String prefix) {\n\t\tif (config.getMode() == Mode.INSERT) {\n\t\t\treturn loadInsert(config, prefix);\n\t\t}\n\t\telse if (config.getMode() == Mode.UPDATE) {\n\t\t\treturn loadUpdate(config, prefix);\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Unsupported mode \" + config.getMode());\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 }",
"protected String getIsolationLevelAsString()\r\n {\r\n if (defaultIsolationLevel == IL_READ_UNCOMMITTED)\r\n {\r\n return LITERAL_IL_READ_UNCOMMITTED;\r\n }\r\n else if (defaultIsolationLevel == IL_READ_COMMITTED)\r\n {\r\n return LITERAL_IL_READ_COMMITTED;\r\n }\r\n else if (defaultIsolationLevel == IL_REPEATABLE_READ)\r\n {\r\n return LITERAL_IL_REPEATABLE_READ;\r\n }\r\n else if (defaultIsolationLevel == IL_SERIALIZABLE)\r\n {\r\n return LITERAL_IL_SERIALIZABLE;\r\n }\r\n else if (defaultIsolationLevel == IL_OPTIMISTIC)\r\n {\r\n return LITERAL_IL_OPTIMISTIC;\r\n }\r\n return LITERAL_IL_READ_UNCOMMITTED;\r\n }",
"public int[] getIntArray(String attributeName)\n {\n int[] array = NativeVertexBuffer.getIntArray(getNative(), attributeName);\n if (array == null)\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return array;\n }",
"public static vpnglobal_binding get(nitro_service service) throws Exception{\n\t\tvpnglobal_binding obj = new vpnglobal_binding();\n\t\tvpnglobal_binding response = (vpnglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"protected ManageableCollection createCollection(CollectionDescriptor desc, Class collectionClass)\r\n {\r\n Class fieldType = desc.getPersistentField().getType();\r\n ManageableCollection col;\r\n\r\n if (collectionClass == null)\r\n {\r\n if (ManageableCollection.class.isAssignableFrom(fieldType))\r\n {\r\n try\r\n {\r\n col = (ManageableCollection)fieldType.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n throw new OJBRuntimeException(\"Cannot instantiate the default collection type \"+fieldType.getName()+\" of collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareCollection.class))\r\n {\r\n col = new RemovalAwareCollection();\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareList.class))\r\n {\r\n col = new RemovalAwareList();\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareSet.class))\r\n {\r\n col = new RemovalAwareSet();\r\n }\r\n else\r\n {\r\n throw new MetadataException(\"Cannot determine a default collection type for collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n else\r\n {\r\n try\r\n {\r\n col = (ManageableCollection)collectionClass.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n throw new OJBRuntimeException(\"Cannot instantiate the collection class \"+collectionClass.getName()+\" of collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n return col;\r\n }",
"public List<String> parseMethodList(String methods) {\n\n String[] methodArray = StringUtils.delimitedListToStringArray(methods, \",\");\n\n List<String> methodList = new ArrayList<String>();\n\n for (String methodName : methodArray) {\n methodList.add(methodName.trim());\n }\n return methodList;\n }",
"@Override\n public int getShadowSize() {\n\tElement shadowElement = shadow.getElement();\n\tshadowElement.setScrollTop(10000);\n\treturn shadowElement.getScrollTop();\n }"
] |
Inserts the information about the dateStamp of a dump and the project
name into a pattern.
@param pattern
String with wildcards
@param dateStamp
@param project
@return String with injected information. | [
"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}"
] | [
"public static <T extends HasWord> TokenizerFactory<T> factory(LexedTokenFactory<T> factory, String options) {\r\n return new PTBTokenizerFactory<T>(factory, options);\r\n\r\n }",
"public static SimpleMatrix wrap( Matrix internalMat ) {\n SimpleMatrix ret = new SimpleMatrix();\n ret.setMatrix(internalMat);\n return ret;\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 }",
"@JmxGetter(name = \"avgUpdateEntriesNetworkTimeMs\", description = \"average time spent on network, for streaming operations\")\n public double getAvgUpdateEntriesNetworkTimeMs() {\n return networkTimeCounterMap.get(Operation.UPDATE_ENTRIES).getAvgEventValue()\n / Time.NS_PER_MS;\n }",
"@Override\n\tpublic void write(final char[] cbuf, final int off, final int len) throws IOException {\n\t\tint offset = off;\n\t\tint length = len;\n\t\twhile (suppressLineCount > 0 && length > 0) {\n\t\t\tlength = -1;\n\t\t\tfor (int i = 0; i < len && suppressLineCount > 0; i++) {\n\t\t\t\tif (cbuf[off + i] == '\\n') {\n\t\t\t\t\toffset = off + i + 1;\n\t\t\t\t\tlength = len - i - 1;\n\t\t\t\t\tsuppressLineCount--;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (length <= 0)\n\t\t\t\treturn;\n\t\t}\n\t\tdelegate.write(cbuf, offset, length);\n\t}",
"public final void notifyContentItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newContentItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for content items [0 - \"\n + (newContentItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart + newHeaderItemCount, itemCount);\n }",
"public void prepareServer() {\n try {\n server = new Server(0);\n jettyHandler = new AbstractHandler() {\n public void handle(String target, Request req, HttpServletRequest request,\n HttpServletResponse response) throws IOException, ServletException {\n response.setContentType(\"text/plain\");\n\n String[] operands = request.getRequestURI().split(\"/\");\n\n String name = \"\";\n String command = \"\";\n String value = \"\";\n\n //operands[0] = \"\", request starts with a \"/\"\n\n if (operands.length >= 2) {\n name = operands[1];\n }\n\n if (operands.length >= 3) {\n command = operands[2];\n }\n\n if (operands.length >= 4) {\n value = operands[3];\n }\n\n if (command.equals(\"report\")) { //report a number of lines written\n response.getWriter().write(makeReport(name, value));\n } else if (command.equals(\"request\") && value.equals(\"block\")) { //request a new block of work\n response.getWriter().write(requestBlock(name));\n } else if (command.equals(\"request\") && value.equals(\"name\")) { //request a new name to report with\n response.getWriter().write(requestName());\n } else { //non recognized response\n response.getWriter().write(\"exit\");\n }\n\n ((Request) request).setHandled(true);\n }\n };\n\n server.setHandler(jettyHandler);\n\n // Select any available port\n server.start();\n Connector[] connectors = server.getConnectors();\n NetworkConnector nc = (NetworkConnector) connectors[0];\n listeningPort = nc.getLocalPort();\n hostName = InetAddress.getLocalHost().getHostName();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }",
"public void write(WritableByteChannel channel) throws IOException {\n logger.debug(\"Writing> {}\", this);\n for (Field field : fields) {\n field.write(channel);\n }\n }",
"public static Dimension rectangleDoubleToDimension(final Rectangle2D.Double rectangle) {\n return new Dimension(\n (int) Math.round(rectangle.width),\n (int) Math.round(rectangle.height));\n }"
] |
Set the property on the given object to the new value.
@param object on which to set the property
@param newValue the new value of the property
@throws RuntimeException if the property could not be set | [
"public void setProperty(Object object, Object newValue) {\n MetaMethod setter = getSetter();\n if (setter == null) {\n if (field != null && !Modifier.isFinal(field.getModifiers())) {\n field.setProperty(object, newValue);\n return;\n }\n throw new GroovyRuntimeException(\"Cannot set read-only property: \" + name);\n }\n newValue = DefaultTypeTransformation.castToType(newValue, getType());\n setter.invoke(object, new Object[]{newValue});\n }"
] | [
"private void populateContainer(FieldType field, List<Pair<String, String>> items)\n {\n CustomField config = m_container.getCustomField(field);\n CustomFieldLookupTable table = config.getLookupTable();\n\n for (Pair<String, String> pair : items)\n {\n CustomFieldValueItem item = new CustomFieldValueItem(Integer.valueOf(0));\n item.setValue(pair.getFirst());\n item.setDescription(pair.getSecond());\n table.add(item);\n }\n }",
"private void sort()\n {\n DefaultDirectedWeightedGraph<RuleProvider, DefaultEdge> graph = new DefaultDirectedWeightedGraph<>(\n DefaultEdge.class);\n\n for (RuleProvider provider : providers)\n {\n graph.addVertex(provider);\n }\n\n addProviderRelationships(graph);\n\n checkForCycles(graph);\n\n List<RuleProvider> result = new ArrayList<>(this.providers.size());\n TopologicalOrderIterator<RuleProvider, DefaultEdge> iterator = new TopologicalOrderIterator<>(graph);\n while (iterator.hasNext())\n {\n RuleProvider provider = iterator.next();\n result.add(provider);\n }\n\n this.providers = Collections.unmodifiableList(result);\n\n int index = 0;\n for (RuleProvider provider : this.providers)\n {\n if (provider instanceof AbstractRuleProvider)\n ((AbstractRuleProvider) provider).setExecutionIndex(index++);\n }\n }",
"public static int cudnnLRNCrossChannelBackward(\n cudnnHandle handle, \n cudnnLRNDescriptor normDesc, \n int lrnMode, \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(cudnnLRNCrossChannelBackwardNative(handle, normDesc, lrnMode, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }",
"public static void main(String[] args) throws Exception {\n if(args.length < 1)\n Utils.croak(\"USAGE: java \" + HdfsFetcher.class.getName()\n + \" url [keytab-location kerberos-username hadoop-config-path [destDir]]\");\n String url = args[0];\n\n VoldemortConfig config = new VoldemortConfig(-1, \"\");\n\n HdfsFetcher fetcher = new HdfsFetcher(config);\n\n String destDir = null;\n Long diskQuotaSizeInKB;\n if(args.length >= 4) {\n fetcher.voldemortConfig.setReadOnlyKeytabPath(args[1]);\n fetcher.voldemortConfig.setReadOnlyKerberosUser(args[2]);\n fetcher.voldemortConfig.setHadoopConfigPath(args[3]);\n }\n if(args.length >= 5)\n destDir = args[4];\n\n if(args.length >= 6)\n diskQuotaSizeInKB = Long.parseLong(args[5]);\n else\n diskQuotaSizeInKB = null;\n\n // for testing we want to be able to download a single file\n allowFetchingOfSingleFile = true;\n\n FileSystem fs = HadoopUtils.getHadoopFileSystem(fetcher.voldemortConfig, url);\n Path p = new Path(url);\n\n FileStatus status = fs.listStatus(p)[0];\n long size = status.getLen();\n long start = System.currentTimeMillis();\n if(destDir == null)\n destDir = System.getProperty(\"java.io.tmpdir\") + File.separator + start;\n\n File location = fetcher.fetch(url, destDir, null, null, -1, null, diskQuotaSizeInKB);\n\n double rate = size * Time.MS_PER_SECOND / (double) (System.currentTimeMillis() - start);\n NumberFormat nf = NumberFormat.getInstance();\n nf.setMaximumFractionDigits(2);\n System.out.println(\"Fetch to \" + location + \" completed: \"\n + nf.format(rate / (1024.0 * 1024.0)) + \" MB/sec.\");\n fs.close();\n }",
"private void deleteBackups() {\n File[] storeDirList = ReadOnlyUtils.getVersionDirs(storeDir, 0L, getCurrentVersionId());\n if(storeDirList != null && storeDirList.length > (numBackups + 1)) {\n // delete ALL old directories asynchronously\n File[] extraBackups = ReadOnlyUtils.findKthVersionedDir(storeDirList,\n 0,\n storeDirList.length\n - (numBackups + 1) - 1);\n if(extraBackups != null) {\n for(File backUpFile: extraBackups) {\n deleteAsync(backUpFile);\n }\n }\n }\n }",
"public int[][] argb() {\n return Arrays.stream(points()).map(p -> argb(p.x, p.y)).toArray(int[][]::new);\n }",
"private String findLoggingProfile(final ResourceRoot resourceRoot) {\n final Manifest manifest = resourceRoot.getAttachment(Attachments.MANIFEST);\n if (manifest != null) {\n final String loggingProfile = manifest.getMainAttributes().getValue(LOGGING_PROFILE);\n if (loggingProfile != null) {\n LoggingLogger.ROOT_LOGGER.debugf(\"Logging profile '%s' found in '%s'.\", loggingProfile, resourceRoot);\n return loggingProfile;\n }\n }\n return null;\n }",
"public void recordCheckoutTimeUs(SocketDestination dest, long checkoutTimeUs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordCheckoutTimeUs(null, checkoutTimeUs);\n recordCheckoutTimeUs(null, checkoutTimeUs);\n } else {\n this.checkoutTimeRequestCounter.addRequest(checkoutTimeUs * Time.NS_PER_US);\n }\n }",
"public static base_response add(nitro_service client, gslbsite resource) throws Exception {\n\t\tgslbsite addresource = new gslbsite();\n\t\taddresource.sitename = resource.sitename;\n\t\taddresource.sitetype = resource.sitetype;\n\t\taddresource.siteipaddress = resource.siteipaddress;\n\t\taddresource.publicip = resource.publicip;\n\t\taddresource.metricexchange = resource.metricexchange;\n\t\taddresource.nwmetricexchange = resource.nwmetricexchange;\n\t\taddresource.sessionexchange = resource.sessionexchange;\n\t\taddresource.triggermonitor = resource.triggermonitor;\n\t\taddresource.parentsite = resource.parentsite;\n\t\treturn addresource.add_resource(client);\n\t}"
] |
Use this API to update vlan. | [
"public static base_response update(nitro_service client, vlan resource) throws Exception {\n\t\tvlan updateresource = new vlan();\n\t\tupdateresource.id = resource.id;\n\t\tupdateresource.aliasname = resource.aliasname;\n\t\tupdateresource.ipv6dynamicrouting = resource.ipv6dynamicrouting;\n\t\treturn updateresource.update_resource(client);\n\t}"
] | [
"private SynchroTable readTableHeader(byte[] header)\n {\n SynchroTable result = null;\n String tableName = DatatypeConverter.getSimpleString(header, 0);\n if (!tableName.isEmpty())\n {\n int offset = DatatypeConverter.getInt(header, 40);\n result = new SynchroTable(tableName, offset);\n }\n return result;\n }",
"public 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 PromotionEvaluationReport getModulePromotionReport(final String name, final String version) throws GrapesCommunicationException {\n return getModulePromotionReportRaw(name, version, false, PromotionEvaluationReport.class);\n }",
"public static DMatrixRMaj copyTriangle(DMatrixRMaj src , DMatrixRMaj dst , boolean upper ) {\n if( dst == null ) {\n dst = new DMatrixRMaj(src.numRows,src.numCols);\n } else if( src.numRows != dst.numRows || src.numCols != dst.numCols ) {\n throw new IllegalArgumentException(\"src and dst must have the same dimensions.\");\n }\n\n if( upper ) {\n int N = Math.min(src.numRows,src.numCols);\n for( int i = 0; i < N; i++ ) {\n int index = i*src.numCols+i;\n System.arraycopy(src.data,index,dst.data,index,src.numCols-i);\n }\n } else {\n for( int i = 0; i < src.numRows; i++ ) {\n int length = Math.min(i+1,src.numCols);\n int index = i*src.numCols;\n System.arraycopy(src.data,index,dst.data,index,length);\n }\n }\n\n return dst;\n }",
"public Response getBill(int month, int year)\n throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new Response(request.get(\"/bill/\" + year + String.format(\"-%02d\", month)));\n }",
"private ArrayList<RunListener> instantiateRunListeners() throws Exception {\n ArrayList<RunListener> instances = new ArrayList<>();\n\n if (runListeners != null) {\n for (String className : Arrays.asList(runListeners.split(\",\"))) {\n instances.add((RunListener) this.instantiate(className).newInstance());\n }\n }\n\n return instances;\n }",
"public static double blackModelCapletValue(\n\t\t\tdouble forward,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike,\n\t\t\tdouble periodLength,\n\t\t\tdouble discountFactor)\n\t{\n\t\t// May be interpreted as a special version of the Black-Scholes Formula\n\t\treturn AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, optionMaturity, optionStrike, periodLength * discountFactor);\n\t}",
"private static Class<?> getRawClass(Type type) {\n if (type instanceof Class) {\n return (Class<?>) type;\n }\n if (type instanceof ParameterizedType) {\n return getRawClass(((ParameterizedType) type).getRawType());\n }\n // For TypeVariable and WildcardType, returns the first upper bound.\n if (type instanceof TypeVariable) {\n return getRawClass(((TypeVariable) type).getBounds()[0]);\n }\n if (type instanceof WildcardType) {\n return getRawClass(((WildcardType) type).getUpperBounds()[0]);\n }\n if (type instanceof GenericArrayType) {\n Class<?> componentClass = getRawClass(((GenericArrayType) type).getGenericComponentType());\n return Array.newInstance(componentClass, 0).getClass();\n }\n // This shouldn't happen as we captured all implementations of Type above (as or Java 8)\n throw new IllegalArgumentException(\"Unsupported type \" + type + \" of type class \" + type.getClass());\n }",
"public void setGlobal(int pathId, Boolean global) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_GLOBAL + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setBoolean(1, global);\n statement.setInt(2, pathId);\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 }"
] |
Returns a matrix of StatisticsMatrix type so that SimpleMatrix functions create matrices
of the correct type. | [
"@Override\n protected StatisticsMatrix createMatrix(int numRows, int numCols, MatrixType type) {\n return new StatisticsMatrix(numRows,numCols);\n }"
] | [
"public final void setWeekDays(SortedSet<WeekDay> weekDays) {\n\n m_weekDays.clear();\n if (null != weekDays) {\n m_weekDays.addAll(weekDays);\n }\n }",
"private void setRequestProps(WbGetEntitiesActionData properties) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tbuilder.append(\"info|datatype\");\n\t\tif (!this.filter.excludeAllLanguages()) {\n\t\t\tbuilder.append(\"|labels|aliases|descriptions\");\n\t\t}\n\t\tif (!this.filter.excludeAllProperties()) {\n\t\t\tbuilder.append(\"|claims\");\n\t\t}\n\t\tif (!this.filter.excludeAllSiteLinks()) {\n\t\t\tbuilder.append(\"|sitelinks\");\n\t\t}\n\n\t\tproperties.props = builder.toString();\n\t}",
"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 final String getSelectedValue(ListBox list) {\n\tint index = list.getSelectedIndex();\n\treturn (index >= 0) ? list.getValue(index) : null;\n }",
"private void logUnexpectedStructure()\n {\n if (m_log != null)\n {\n m_log.println(\"ABORTED COLUMN - unexpected structure: \" + m_currentColumn.getClass().getSimpleName() + \" \" + m_currentColumn.getName());\n }\n }",
"public static wisite_accessmethod_binding[] get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_accessmethod_binding obj = new wisite_accessmethod_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_accessmethod_binding response[] = (wisite_accessmethod_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"@Override\n public boolean commit() {\n final CoreRemoteMongoCollection<DocumentT> collection = getCollection();\n final List<WriteModel<DocumentT>> writeModels = getBulkWriteModels();\n\n // define success as any one operation succeeding for now\n boolean success = true;\n for (final WriteModel<DocumentT> write : writeModels) {\n if (write instanceof ReplaceOneModel) {\n final ReplaceOneModel<DocumentT> replaceModel = ((ReplaceOneModel) write);\n final RemoteUpdateResult result =\n collection.updateOne(replaceModel.getFilter(), (Bson) replaceModel.getReplacement());\n success = success\n && (result != null && result.getModifiedCount() == result.getMatchedCount());\n } else if (write instanceof UpdateOneModel) {\n final UpdateOneModel<DocumentT> updateModel = ((UpdateOneModel) write);\n final RemoteUpdateResult result =\n collection.updateOne(updateModel.getFilter(), updateModel.getUpdate());\n success = success\n && (result != null && result.getModifiedCount() == result.getMatchedCount());\n } else if (write instanceof UpdateManyModel) {\n final UpdateManyModel<DocumentT> updateModel = ((UpdateManyModel) write);\n final RemoteUpdateResult result =\n collection.updateMany(updateModel.getFilter(), updateModel.getUpdate());\n success = success\n && (result != null && result.getModifiedCount() == result.getMatchedCount());\n }\n }\n return success;\n }",
"public void visitMethodInsn(int opcode, String owner, String name,\n String desc, boolean itf) {\n if (mv != null) {\n mv.visitMethodInsn(opcode, owner, name, desc, itf);\n }\n }",
"private String getProject(CmsObject cms, CmsFavoriteEntry entry) throws CmsException {\n\n String result = m_projectLabels.get(entry.getProjectId());\n if (result == null) {\n result = cms.readProject(entry.getProjectId()).getName();\n m_projectLabels.put(entry.getProjectId(), result);\n }\n return result;\n }"
] |
Creates a temporary folder using the given prefix to generate its name.
@param prefix the prefix string to be used in generating the directory's name; may be <i>null</i>
@return the <code>File</code> to the newly created folder
@throws IOException | [
"public static File createTempDirectory(String prefix) {\n\tFile temp = null;\n\t\n\ttry {\n\t temp = File.createTempFile(prefix != null ? prefix : \"temp\", Long.toString(System.nanoTime()));\n\t\n\t if (!(temp.delete())) {\n\t throw new IOException(\"Could not delete temp file: \"\n\t\t + temp.getAbsolutePath());\n\t }\n\t\n\t if (!(temp.mkdir())) {\n\t throw new IOException(\"Could not create temp directory: \"\n\t + temp.getAbsolutePath());\n\t }\n\t} catch (IOException e) {\n\t throw new DukeException(\"Unable to create temporary directory with prefix \" + prefix, e);\n\t}\n\t\n\treturn temp;\n }"
] | [
"private LoggingConfigurationService configure(final ResourceRoot root, final VirtualFile configFile, final ClassLoader classLoader, final LogContext logContext) throws DeploymentUnitProcessingException {\n InputStream configStream = null;\n try {\n LoggingLogger.ROOT_LOGGER.debugf(\"Found logging configuration file: %s\", configFile);\n\n // Get the filname and open the stream\n final String fileName = configFile.getName();\n configStream = configFile.openStream();\n\n // Check the type of the configuration file\n if (isLog4jConfiguration(fileName)) {\n final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();\n final LogContext old = logContextSelector.getAndSet(CONTEXT_LOCK, logContext);\n try {\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);\n if (LOG4J_XML.equals(fileName) || JBOSS_LOG4J_XML.equals(fileName)) {\n new DOMConfigurator().doConfigure(configStream, org.apache.log4j.JBossLogManagerFacade.getLoggerRepository(logContext));\n } else {\n final Properties properties = new Properties();\n properties.load(new InputStreamReader(configStream, ENCODING));\n new org.apache.log4j.PropertyConfigurator().doConfigure(properties, org.apache.log4j.JBossLogManagerFacade.getLoggerRepository(logContext));\n }\n } finally {\n logContextSelector.getAndSet(CONTEXT_LOCK, old);\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current);\n }\n return new LoggingConfigurationService(null, resolveRelativePath(root, configFile));\n } else {\n // Create a properties file\n final Properties properties = new Properties();\n properties.load(new InputStreamReader(configStream, ENCODING));\n // Attempt to see if this is a J.U.L. configuration file\n if (isJulConfiguration(properties)) {\n LoggingLogger.ROOT_LOGGER.julConfigurationFileFound(configFile.getName());\n } else {\n // Load non-log4j types\n final PropertyConfigurator propertyConfigurator = new PropertyConfigurator(logContext);\n propertyConfigurator.configure(properties);\n return new LoggingConfigurationService(propertyConfigurator.getLogContextConfiguration(), resolveRelativePath(root, configFile));\n }\n }\n } catch (Exception e) {\n throw LoggingLogger.ROOT_LOGGER.failedToConfigureLogging(e, configFile.getName());\n } finally {\n safeClose(configStream);\n }\n return null;\n }",
"private boolean containsCollectionAndMapsToDifferentTable(CollectionDescriptorDef origCollDef, TableDef origTableDef, ClassDescriptorDef classDef)\r\n {\r\n if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) &&\r\n !origTableDef.getName().equals(classDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE)))\r\n {\r\n CollectionDescriptorDef curCollDef = classDef.getCollection(origCollDef.getName());\r\n\r\n if ((curCollDef != null) &&\r\n !curCollDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"private static void listSlack(ProjectFile file)\n {\n for (Task task : file.getTasks())\n {\n System.out.println(task.getName() + \" Total Slack=\" + task.getTotalSlack() + \" Start Slack=\" + task.getStartSlack() + \" Finish Slack=\" + task.getFinishSlack());\n }\n }",
"@Override\n public Optional<String> hash(final Optional<URL> url) throws IOException {\n if (!url.isPresent()) {\n return Optional.absent();\n }\n logger.debug(\"Calculating md5 hash, url:{}\", url);\n if (isHotReloadModeOff()) {\n final String md5 = cache.getIfPresent(url.get());\n\n logger.debug(\"md5 hash:{}\", md5);\n\n if (md5 != null) {\n return Optional.of(md5);\n }\n }\n\n final InputStream is = url.get().openStream();\n final String md5 = getMD5Checksum(is);\n\n if (isHotReloadModeOff()) {\n logger.debug(\"caching url:{} with hash:{}\", url, md5);\n\n cache.put(url.get(), md5);\n }\n\n return Optional.fromNullable(md5);\n }",
"public static void main(String[] args) {\r\n Settings settings = new Settings();\r\n new JCommander(settings, args);\r\n\r\n if (!settings.isGuiSupressed()) {\r\n OkapiUI okapiUi = new OkapiUI();\r\n okapiUi.setVisible(true);\r\n } else {\r\n int returnValue;\r\n \r\n returnValue = commandLine(settings);\r\n \r\n if (returnValue != 0) {\r\n System.out.println(\"An error occurred\");\r\n }\r\n }\r\n }",
"public void attachHoursToDay(ProjectCalendarHours hours)\n {\n if (hours.getParentCalendar() != this)\n {\n throw new IllegalArgumentException();\n }\n m_hours[hours.getDay().getValue() - 1] = hours;\n }",
"public double totalCount() {\r\n if (depth() == 1) {\r\n return total; // I think this one is always OK. Not very principled here, though.\r\n } else {\r\n double result = 0.0;\r\n for (K o: topLevelKeySet()) {\r\n result += conditionalizeOnce(o).totalCount();\r\n }\r\n return result;\r\n }\r\n }",
"private void setFieldType(FastTrackTableType tableType)\n {\n switch (tableType)\n {\n case ACTBARS:\n {\n m_type = ActBarField.getInstance(m_header.getColumnType());\n break;\n }\n case ACTIVITIES:\n {\n m_type = ActivityField.getInstance(m_header.getColumnType());\n break;\n }\n case RESOURCES:\n {\n m_type = ResourceField.getInstance(m_header.getColumnType());\n break;\n }\n }\n }",
"public List<FailedEventInvocation> getFailedInvocations() {\n synchronized (this.mutex) {\n if (this.failedEvents == null) {\n return Collections.emptyList();\n }\n return Collections.unmodifiableList(this.failedEvents);\n }\n }"
] |
Get object by identity. First lookup among objects registered in the
transaction, then in persistent storage.
@param id The identity
@return The object
@throws PersistenceBrokerException | [
"public Object getObjectByIdentity(Identity id)\r\n throws PersistenceBrokerException\r\n {\r\n checkOpen();\r\n ObjectEnvelope envelope = objectEnvelopeTable.getByIdentity(id);\r\n if (envelope != null)\r\n {\r\n return (envelope.needsDelete() ? null : envelope.getObject());\r\n }\r\n else\r\n {\r\n return getBroker().getObjectByIdentity(id);\r\n }\r\n }"
] | [
"public RandomVariable[] getGradient(){\r\n\r\n\t\t// for now let us take the case for output-dimension equal to one!\r\n\t\tint numberOfVariables = getNumberOfVariablesInList();\r\n\t\tint numberOfCalculationSteps = factory.getNumberOfEntriesInList();\r\n\r\n\t\tRandomVariable[] omega_hat = new RandomVariable[numberOfCalculationSteps];\r\n\r\n\t\t// first entry gets initialized\r\n\t\tomega_hat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0);\r\n\r\n\t\t/*\r\n\t\t * TODO: Find way that calculations form here on are not 'recorded' by the factory\r\n\t\t * IDEA: Let the calculation below run on {@link RandomVariableFromDoubleArray}, ie cast everything down!\r\n\t\t * */\r\n\r\n\t\tfor(int functionIndex = numberOfCalculationSteps - 2; functionIndex > 0; functionIndex--){\r\n\t\t\t// apply chain rule\r\n\t\t\tomega_hat[functionIndex] = new RandomVariableFromDoubleArray(0.0);\r\n\r\n\t\t\t/*TODO: save all D_{i,j}*\\omega_j in vector and sum up later */\r\n\t\t\tfor(RandomVariableUniqueVariable parent:parentsVariables){\r\n\r\n\t\t\t\tint variableIndex = parent.getVariableID();\r\n\r\n\t\t\t\tomega_hat[functionIndex] = omega_hat[functionIndex].add(getPartialDerivative(functionIndex, variableIndex).mult(omega_hat[variableIndex]));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/* Due to the fact that we can still introduce 'new' true variables on the fly they are NOT the last couple of indices!\r\n\t\t * Thus save the indices of the true variables and recover them after finalizing all the calculations\r\n\t\t * IDEA: quit calculation after minimal true variable index is reached */\r\n\t\tRandomVariable[] gradient = new RandomVariable[numberOfVariables];\r\n\r\n\t\t/* TODO: sort array in correct manner! */\r\n\t\tint[] indicesOfVariables = getIDsOfVariablesInList();\r\n\r\n\t\tfor(int i = 0; i < numberOfVariables; i++){\r\n\t\t\tgradient[i] = omega_hat[numberOfCalculationSteps - numberOfVariables + indicesOfVariables[i]];\r\n\t\t}\r\n\r\n\t\treturn gradient;\r\n\t}",
"public static ci[] get(nitro_service service) throws Exception{\n\t\tci obj = new ci();\n\t\tci[] response = (ci[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static CRFClassifier getClassifier(InputStream in) throws IOException, ClassCastException,\r\n ClassNotFoundException {\r\n CRFClassifier crf = new CRFClassifier();\r\n crf.loadClassifier(in);\r\n return crf;\r\n }",
"public static BoxUser getCurrentUser(BoxAPIConnection api) {\n URL url = GET_ME_URL.build(api.getBaseURL());\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n return new BoxUser(api, jsonObject.get(\"id\").asString());\n }",
"private static Set<String> imageOrientationsOf(ImageMetadata metadata) {\n\n String exifIFD0DirName = new ExifIFD0Directory().getName();\n\n Tag[] tags = Arrays.stream(metadata.getDirectories())\n .filter(dir -> dir.getName().equals(exifIFD0DirName))\n .findFirst()\n .map(Directory::getTags)\n .orElseGet(() -> new Tag[0]);\n\n return Arrays.stream(tags)\n .filter(tag -> tag.getType() == 274)\n .map(Tag::getRawValue)\n .collect(Collectors.toSet());\n }",
"public void sendLoadTrackCommand(int targetPlayer, int rekordboxId,\n int sourcePlayer, CdjStatus.TrackSourceSlot sourceSlot, CdjStatus.TrackType sourceType)\n throws IOException {\n final DeviceUpdate update = getLatestStatusFor(targetPlayer);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + targetPlayer + \" not found on network.\");\n }\n sendLoadTrackCommand(update, rekordboxId, sourcePlayer, sourceSlot, sourceType);\n }",
"public final URI render(\n final MapfishMapContext mapContext,\n final ScalebarAttributeValues scalebarParams,\n final File tempFolder,\n final Template template)\n throws IOException, ParserConfigurationException {\n final double dpi = mapContext.getDPI();\n\n // get the map bounds\n final Rectangle paintArea = new Rectangle(mapContext.getMapSize());\n MapBounds bounds = mapContext.getBounds();\n\n final DistanceUnit mapUnit = getUnit(bounds);\n final Scale scale = bounds.getScale(paintArea, PDF_DPI);\n final double scaleDenominator = scale.getDenominator(scalebarParams.geodetic,\n bounds.getProjection(), dpi, bounds.getCenter());\n\n DistanceUnit scaleUnit = scalebarParams.getUnit();\n if (scaleUnit == null) {\n scaleUnit = mapUnit;\n }\n\n // adjust scalebar width and height to the DPI value\n final double maxLengthInPixel = (scalebarParams.getOrientation().isHorizontal()) ?\n scalebarParams.getSize().width : scalebarParams.getSize().height;\n\n final double maxIntervalLengthInWorldUnits = DistanceUnit.PX.convertTo(maxLengthInPixel, scaleUnit)\n * scaleDenominator / scalebarParams.intervals;\n final double niceIntervalLengthInWorldUnits =\n getNearestNiceValue(maxIntervalLengthInWorldUnits, scaleUnit, scalebarParams.lockUnits);\n\n final ScaleBarRenderSettings settings = new ScaleBarRenderSettings();\n settings.setParams(scalebarParams);\n settings.setMaxSize(scalebarParams.getSize());\n settings.setPadding(getPadding(settings));\n\n // start the rendering\n File path = null;\n if (template.getConfiguration().renderAsSvg(scalebarParams.renderAsSvg)) {\n // render scalebar as SVG\n final SVGGraphics2D graphics2D = CreateMapProcessor.createSvgGraphics(scalebarParams.getSize());\n\n try {\n tryLayout(\n graphics2D, scaleUnit, scaleDenominator,\n niceIntervalLengthInWorldUnits, settings, 0);\n\n path = File.createTempFile(\"scalebar-graphic-\", \".svg\", tempFolder);\n CreateMapProcessor.saveSvgFile(graphics2D, path);\n } finally {\n graphics2D.dispose();\n }\n } else {\n // render scalebar as raster graphic\n double dpiRatio = mapContext.getDPI() / PDF_DPI;\n final BufferedImage bufferedImage = new BufferedImage(\n (int) Math.round(scalebarParams.getSize().width * dpiRatio),\n (int) Math.round(scalebarParams.getSize().height * dpiRatio),\n TYPE_4BYTE_ABGR);\n final Graphics2D graphics2D = bufferedImage.createGraphics();\n\n try {\n AffineTransform saveAF = new AffineTransform(graphics2D.getTransform());\n graphics2D.scale(dpiRatio, dpiRatio);\n tryLayout(\n graphics2D, scaleUnit, scaleDenominator,\n niceIntervalLengthInWorldUnits, settings, 0);\n graphics2D.setTransform(saveAF);\n\n path = File.createTempFile(\"scalebar-graphic-\", \".png\", tempFolder);\n ImageUtils.writeImage(bufferedImage, \"png\", path);\n } finally {\n graphics2D.dispose();\n }\n }\n\n return path.toURI();\n }",
"void recover() {\n final List<NamespaceSynchronizationConfig> nsConfigs = new ArrayList<>();\n for (final MongoNamespace ns : this.syncConfig.getSynchronizedNamespaces()) {\n nsConfigs.add(this.syncConfig.getNamespaceConfig(ns));\n }\n\n for (final NamespaceSynchronizationConfig nsConfig : nsConfigs) {\n nsConfig.getLock().writeLock().lock();\n }\n try {\n for (final NamespaceSynchronizationConfig nsConfig : nsConfigs) {\n nsConfig.getLock().writeLock().lock();\n try {\n recoverNamespace(nsConfig);\n } finally {\n nsConfig.getLock().writeLock().unlock();\n }\n }\n } finally {\n for (final NamespaceSynchronizationConfig nsConfig : nsConfigs) {\n nsConfig.getLock().writeLock().unlock();\n }\n }\n }",
"public static Info rand( final Variable A , final Variable B , ManagerTempVariables manager) {\n Info ret = new Info();\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n\n if( A instanceof VariableInteger && B instanceof VariableInteger ) {\n ret.op = new Operation(\"rand-ii\") {\n @Override\n public void process() {\n int numRows = ((VariableInteger)A).value;\n int numCols = ((VariableInteger)B).value;\n output.matrix.reshape(numRows,numCols);\n RandomMatrices_DDRM.fillUniform(output.matrix, 0,1,manager.getRandom());\n }\n };\n } else {\n throw new RuntimeException(\"Expected two integers got \"+A+\" \"+B);\n }\n\n return ret;\n }"
] |
Performs a matrix multiplication between inner block matrices.
(m , o) += (m , n) * (n , o) | [
"private static void multBlockAdd( double []blockA, double []blockB, double []blockC,\n final int m, final int n, final int o,\n final int blockLength ) {\n// for( int i = 0; i < m; i++ ) {\n// for( int j = 0; j < o; j++ ) {\n// double val = 0;\n// for( int k = 0; k < n; k++ ) {\n// val += blockA[ i*blockLength + k]*blockB[ k*blockLength + j];\n// }\n//\n// blockC[ i*blockLength + j] += val;\n// }\n// }\n\n// int rowA = 0;\n// for( int i = 0; i < m; i++ , rowA += blockLength) {\n// for( int j = 0; j < o; j++ ) {\n// double val = 0;\n// int indexB = j;\n// int indexA = rowA;\n// int end = indexA + n;\n// for( ; indexA != end; indexA++ , indexB += blockLength ) {\n// val += blockA[ indexA ]*blockB[ indexB ];\n// }\n//\n// blockC[ rowA + j] += val;\n// }\n// }\n\n// for( int k = 0; k < n; k++ ) {\n// for( int i = 0; i < m; i++ ) {\n// for( int j = 0; j < o; j++ ) {\n// blockC[ i*blockLength + j] += blockA[ i*blockLength + k]*blockB[ k*blockLength + j];\n// }\n// }\n// }\n\n for( int k = 0; k < n; k++ ) {\n int rowB = k*blockLength;\n int endB = rowB+o;\n for( int i = 0; i < m; i++ ) {\n int indexC = i*blockLength;\n double valA = blockA[ indexC + k];\n int indexB = rowB;\n \n while( indexB != endB ) {\n blockC[ indexC++ ] += valA*blockB[ indexB++];\n }\n }\n }\n }"
] | [
"protected Element createRectangleElement(float x, float y, float width, float height, boolean stroke, boolean fill)\n {\n float lineWidth = transformWidth(getGraphicsState().getLineWidth());\n \tfloat wcor = stroke ? lineWidth : 0.0f;\n float strokeOffset = wcor == 0 ? 0 : wcor / 2;\n width = width - wcor < 0 ? 1 : width - wcor;\n height = height - wcor < 0 ? 1 : height - wcor;\n\n StringBuilder pstyle = new StringBuilder(50);\n \tpstyle.append(\"left:\").append(style.formatLength(x - strokeOffset)).append(';');\n pstyle.append(\"top:\").append(style.formatLength(y - strokeOffset)).append(';');\n pstyle.append(\"width:\").append(style.formatLength(width)).append(';');\n pstyle.append(\"height:\").append(style.formatLength(height)).append(';');\n \t \n \tif (stroke)\n \t{\n String color = colorString(getGraphicsState().getStrokingColor());\n \tpstyle.append(\"border:\").append(style.formatLength(lineWidth)).append(\" solid \").append(color).append(';');\n \t}\n \t\n \tif (fill)\n \t{\n String fcolor = colorString(getGraphicsState().getNonStrokingColor());\n \t pstyle.append(\"background-color:\").append(fcolor).append(';');\n \t}\n \t\n Element el = doc.createElement(\"div\");\n el.setAttribute(\"class\", \"r\");\n el.setAttribute(\"style\", pstyle.toString());\n el.appendChild(doc.createEntityReference(\"nbsp\"));\n return el;\n }",
"@SuppressWarnings(\"SameParameterValue\")\n private void sendField(Field field) throws IOException {\n if (isConnected()) {\n try {\n field.write(channel);\n } catch (IOException e) {\n logger.warn(\"Problem trying to write field to dbserver, closing connection\", e);\n close();\n throw e;\n }\n return;\n }\n throw new IOException(\"sendField() called after dbserver connection was closed\");\n }",
"protected void populateTasksByStealer(List<StealerBasedRebalanceTask> sbTaskList) {\n // Setup mapping of stealers to work for this run.\n for(StealerBasedRebalanceTask task: sbTaskList) {\n if(task.getStealInfos().size() != 1) {\n throw new VoldemortException(\"StealerBasedRebalanceTasks should have a list of RebalancePartitionsInfo of length 1.\");\n }\n\n RebalanceTaskInfo stealInfo = task.getStealInfos().get(0);\n int stealerId = stealInfo.getStealerId();\n if(!this.tasksByStealer.containsKey(stealerId)) {\n this.tasksByStealer.put(stealerId, new ArrayList<StealerBasedRebalanceTask>());\n }\n this.tasksByStealer.get(stealerId).add(task);\n }\n\n if(tasksByStealer.isEmpty()) {\n return;\n }\n // Shuffle order of each stealer's work list. This randomization\n // helps to get rid of any \"patterns\" in how rebalancing tasks were\n // added to the task list passed in.\n for(List<StealerBasedRebalanceTask> taskList: tasksByStealer.values()) {\n Collections.shuffle(taskList);\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 }",
"protected RollbackPatch createRollbackPatch(final String patchId, final Patch.PatchType patchType) {\n // Process elements\n final List<PatchElement> elements = new ArrayList<PatchElement>();\n // Process layers\n for (final PatchEntry entry : getLayers()) {\n final PatchElement element = createRollbackElement(entry);\n elements.add(element);\n }\n // Process add-ons\n for (final PatchEntry entry : getAddOns()) {\n final PatchElement element = createRollbackElement(entry);\n elements.add(element);\n }\n\n final InstalledIdentity installedIdentity = modification.getUnmodifiedInstallationState();\n final String name = installedIdentity.getIdentity().getName();\n final IdentityImpl identity = new IdentityImpl(name, modification.getVersion());\n if (patchType == Patch.PatchType.CUMULATIVE) {\n identity.setPatchType(Patch.PatchType.CUMULATIVE);\n identity.setResultingVersion(installedIdentity.getIdentity().getVersion());\n } else if (patchType == Patch.PatchType.ONE_OFF) {\n identity.setPatchType(Patch.PatchType.ONE_OFF);\n }\n final List<ContentModification> modifications = identityEntry.rollbackActions;\n final Patch delegate = new PatchImpl(patchId, \"rollback patch\", identity, elements, modifications);\n return new PatchImpl.RollbackPatchImpl(delegate, installedIdentity);\n }",
"public synchronized void bindShader(GVRScene scene, boolean isMultiview)\n {\n GVRRenderPass pass = mRenderPassList.get(0);\n GVRShaderId shader = pass.getMaterial().getShaderType();\n GVRShader template = shader.getTemplate(getGVRContext());\n if (template != null)\n {\n template.bindShader(getGVRContext(), this, scene, isMultiview);\n }\n for (int i = 1; i < mRenderPassList.size(); ++i)\n {\n pass = mRenderPassList.get(i);\n shader = pass.getMaterial().getShaderType();\n template = shader.getTemplate(getGVRContext());\n if (template != null)\n {\n template.bindShader(getGVRContext(), pass, scene, isMultiview);\n }\n }\n }",
"private Query.Builder createScatterQuery(Query query, int numSplits) {\n // TODO(pcostello): We can potentially support better splits with equality filters in our query\n // if there exists a composite index on property, __scatter__, __key__. Until an API for\n // metadata exists, this isn't possible. Note that ancestor and inequality queries fall into\n // the same category.\n Query.Builder scatterPointQuery = Query.newBuilder();\n scatterPointQuery.addAllKind(query.getKindList());\n scatterPointQuery.addOrder(DatastoreHelper.makeOrder(\n DatastoreHelper.SCATTER_PROPERTY_NAME, Direction.ASCENDING));\n // There is a split containing entities before and after each scatter entity:\n // ||---*------*------*------*------*------*------*---|| = scatter entity\n // If we represent each split as a region before a scatter entity, there is an extra region\n // following the last scatter point. Thus, we do not need the scatter entities for the last\n // region.\n scatterPointQuery.getLimitBuilder().setValue((numSplits - 1) * KEYS_PER_SPLIT);\n scatterPointQuery.addProjection(Projection.newBuilder().setProperty(\n PropertyReference.newBuilder().setName(\"__key__\")));\n return scatterPointQuery;\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 void diffUpdate(List<T> newList) {\n if (getCollection().size() == 0) {\n addAll(newList);\n notifyDataSetChanged();\n } else {\n DiffCallback diffCallback = new DiffCallback(collection, newList);\n DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);\n clear();\n addAll(newList);\n diffResult.dispatchUpdatesTo(this);\n }\n }"
] |
Retrieve the finish slack.
@return finish slack | [
"public Duration getFinishSlack()\n {\n Duration finishSlack = (Duration) getCachedValue(TaskField.FINISH_SLACK);\n if (finishSlack == null)\n {\n Duration duration = getDuration();\n if (duration != null)\n {\n finishSlack = DateHelper.getVariance(this, getEarlyFinish(), getLateFinish(), duration.getUnits());\n set(TaskField.FINISH_SLACK, finishSlack);\n }\n }\n return (finishSlack);\n }"
] | [
"public byte[] getPacketBytes() {\n byte[] result = new byte[packetBytes.length];\n System.arraycopy(packetBytes, 0, result, 0, packetBytes.length);\n return result;\n }",
"@Override\n\tpublic List<String> contentTypes() {\n\t\tList<String> contentTypes = null;\n\t\tfinal HttpServletRequest request = getHttpRequest();\n\n\t\tif (favorParameterOverAcceptHeader) {\n\t\t\tcontentTypes = getFavoredParameterValueAsList(request);\n\t\t} else {\n\t\t\tcontentTypes = getAcceptHeaderValues(request);\n\t\t}\n\n\t\tif (isEmpty(contentTypes)) {\n\t\t\tlogger.debug(\"Setting content types to default: {}.\", DEFAULT_SUPPORTED_CONTENT_TYPES);\n\n\t\t\tcontentTypes = DEFAULT_SUPPORTED_CONTENT_TYPES;\n\t\t}\n\n\t\treturn unmodifiableList(contentTypes);\n\t}",
"private void clearBeatGrids(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(hotCache.keySet())) {\n if (deck.player == player) {\n hotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverBeatGridUpdate(player, null); // Inform listeners the beat grid is gone.\n }\n }\n }\n }",
"public boolean shouldNotCache(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkContains(uri, noCacheIdentifiers) || checkSuffixes(uri, noCacheSuffixes);\n\t}",
"public static byte[] getDocumentToByteArray(Document dom) {\n try {\n TransformerFactory tFactory = TransformerFactory.newInstance();\n\n Transformer transformer = tFactory.newTransformer();\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer\n .setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, \"no\");\n transformer.setOutputProperty(OutputKeys.METHOD, \"html\");\n // TODO should be fixed to read doctype declaration\n transformer\n .setOutputProperty(\n OutputKeys.DOCTYPE_PUBLIC,\n \"-//W3C//DTD XHTML 1.0 Strict//EN\\\" \"\n + \"\\\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\");\n\n DOMSource source = new DOMSource(dom);\n\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n Result result = new StreamResult(out);\n transformer.transform(source, result);\n\n return out.toByteArray();\n } catch (TransformerException e) {\n LOGGER.error(\"Error while converting the document to a byte array\",\n e);\n }\n return null;\n\n }",
"public static base_responses add(nitro_service client, cmppolicylabel resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcmppolicylabel addresources[] = new cmppolicylabel[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new cmppolicylabel();\n\t\t\t\taddresources[i].labelname = resources[i].labelname;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"@Override\n public final synchronized void stopService(long millis) {\n running = false;\n try {\n if (keepRunning) {\n keepRunning = false;\n interrupt();\n quit();\n if (0L == millis) {\n join();\n } else {\n join(millis);\n }\n }\n } catch (InterruptedException e) {\n //its possible that the thread exits between the lines keepRunning=false and interrupt above\n log.warn(\"Got interrupted while stopping {}\", this, e);\n\n Thread.currentThread().interrupt();\n }\n }",
"private TreeMap<Integer, Integer> createTaskMap(FieldMap fieldMap, FixedMeta taskFixedMeta, FixedData taskFixedData, Var2Data taskVarData)\n {\n TreeMap<Integer, Integer> taskMap = new TreeMap<Integer, Integer>();\n int uniqueIdOffset = fieldMap.getFixedDataOffset(TaskField.UNIQUE_ID);\n Integer taskNameKey = fieldMap.getVarDataKey(TaskField.NAME);\n int itemCount = taskFixedMeta.getAdjustedItemCount();\n int uniqueID;\n Integer key;\n\n //\n // First three items are not tasks, so let's skip them\n //\n for (int loop = 3; loop < itemCount; loop++)\n {\n byte[] data = taskFixedData.getByteArrayValue(loop);\n if (data != null)\n {\n byte[] metaData = taskFixedMeta.getByteArrayValue(loop);\n\n //\n // Check for the deleted task flag\n //\n int flags = MPPUtility.getInt(metaData, 0);\n if ((flags & 0x02) != 0)\n {\n // Project stores the deleted tasks unique id's into the fixed data as well\n // and at least in one case the deleted task was listed twice in the list\n // the second time with data with it causing a phantom task to be shown.\n // See CalendarErrorPhantomTasks.mpp\n //\n // So let's add the unique id for the deleted task into the map so we don't\n // accidentally include the task later.\n //\n uniqueID = MPPUtility.getShort(data, TASK_UNIQUE_ID_FIXED_OFFSET); // Only a short stored for deleted tasks?\n key = Integer.valueOf(uniqueID);\n if (taskMap.containsKey(key) == false)\n {\n taskMap.put(key, null); // use null so we can easily ignore this later\n }\n }\n else\n {\n //\n // Do we have a null task?\n //\n if (data.length == NULL_TASK_BLOCK_SIZE)\n {\n uniqueID = MPPUtility.getInt(data, TASK_UNIQUE_ID_FIXED_OFFSET);\n key = Integer.valueOf(uniqueID);\n if (taskMap.containsKey(key) == false)\n {\n taskMap.put(key, Integer.valueOf(loop));\n }\n }\n else\n {\n //\n // We apply a heuristic here - if we have more than 75% of the data, we assume\n // the task is valid.\n //\n int maxSize = fieldMap.getMaxFixedDataSize(0);\n if (maxSize == 0 || ((data.length * 100) / maxSize) > 75)\n {\n uniqueID = MPPUtility.getInt(data, uniqueIdOffset);\n key = Integer.valueOf(uniqueID);\n\n // Accept this task if it does not have a deleted unique ID or it has a deleted unique ID but the name is not null\n if (!taskMap.containsKey(key) || taskVarData.getUnicodeString(key, taskNameKey) != null)\n {\n taskMap.put(key, Integer.valueOf(loop));\n }\n }\n }\n }\n }\n }\n\n return (taskMap);\n }",
"public double Function2D(double x, double y) {\n return Math.exp(-(x * x + y * y) / (2 * sqrSigma)) / (2 * Math.PI * sqrSigma);\n }"
] |
Get all Groups
@return
@throws Exception | [
"private List<Group> getGroups() throws Exception {\n List<Group> groups = new ArrayList<Group>();\n List<Group> sourceGroups = PathOverrideService.getInstance().findAllGroups();\n\n // loop through the groups\n for (Group sourceGroup : sourceGroups) {\n Group group = new Group();\n\n // add all methods\n ArrayList<Method> methods = new ArrayList<Method>();\n for (Method sourceMethod : EditService.getInstance().getMethodsFromGroupId(sourceGroup.getId(), null)) {\n Method method = new Method();\n method.setClassName(sourceMethod.getClassName());\n method.setMethodName(sourceMethod.getMethodName());\n methods.add(method);\n }\n\n group.setMethods(methods);\n group.setName(sourceGroup.getName());\n groups.add(group);\n }\n\n return groups;\n }"
] | [
"public static Stack getStack() {\n Stack stack = interceptionContexts.get();\n if (stack == null) {\n stack = new Stack(interceptionContexts);\n interceptionContexts.set(stack);\n }\n return stack;\n }",
"public float getPositionY(int vertex) {\n if (!hasPositions()) {\n throw new IllegalStateException(\"mesh has no positions\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_vertices.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\n }",
"public static base_response add(nitro_service client, transformpolicy resource) throws Exception {\n\t\ttransformpolicy addresource = new transformpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.profilename = resource.profilename;\n\t\taddresource.comment = resource.comment;\n\t\taddresource.logaction = resource.logaction;\n\t\treturn addresource.add_resource(client);\n\t}",
"public CollectionDescriptor getCollectionDescriptorByName(String name)\r\n {\r\n if (name == null)\r\n {\r\n return null;\r\n }\r\n\r\n CollectionDescriptor cod = (CollectionDescriptor) getCollectionDescriptorNameMap().get(name);\r\n\r\n //\r\n // BRJ: if the CollectionDescriptor is not found\r\n // look in the ClassDescriptor referenced by 'super' for it\r\n //\r\n if (cod == null)\r\n {\r\n ClassDescriptor superCld = getSuperClassDescriptor();\r\n if (superCld != null)\r\n {\r\n cod = superCld.getCollectionDescriptorByName(name);\r\n }\r\n }\r\n\r\n return cod;\r\n }",
"private String formatCurrency(Number value)\n {\n return (value == null ? null : m_formats.getCurrencyFormat().format(value));\n }",
"public void setWeeklyDay(Day day, boolean value)\n {\n if (value)\n {\n m_days.add(day);\n }\n else\n {\n m_days.remove(day);\n }\n }",
"public final void configureAccess(final Template template, final ApplicationContext context) {\n final Configuration configuration = template.getConfiguration();\n\n AndAccessAssertion accessAssertion = context.getBean(AndAccessAssertion.class);\n accessAssertion.setPredicates(configuration.getAccessAssertion(), template.getAccessAssertion());\n this.access = accessAssertion;\n }",
"public boolean checkWrite(TransactionImpl tx, Object obj)\r\n {\r\n LockEntry writer = getWriter(obj);\r\n if (writer == null)\r\n return false;\r\n else if (writer.isOwnedBy(tx))\r\n return true;\r\n else\r\n return false;\r\n }",
"public static vpnvserver_responderpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_responderpolicy_binding obj = new vpnvserver_responderpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_responderpolicy_binding response[] = (vpnvserver_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Sorts the fields. | [
"private void sortFields()\r\n {\r\n HashMap fields = new HashMap();\r\n ArrayList fieldsWithId = new ArrayList();\r\n ArrayList fieldsWithoutId = new ArrayList();\r\n FieldDescriptorDef fieldDef;\r\n\r\n for (Iterator it = getFields(); it.hasNext(); )\r\n {\r\n fieldDef = (FieldDescriptorDef)it.next();\r\n fields.put(fieldDef.getName(), fieldDef);\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_ID))\r\n {\r\n fieldsWithId.add(fieldDef.getName());\r\n }\r\n else\r\n {\r\n fieldsWithoutId.add(fieldDef.getName());\r\n }\r\n }\r\n\r\n Collections.sort(fieldsWithId, new FieldWithIdComparator(fields));\r\n\r\n ArrayList result = new ArrayList();\r\n\r\n for (Iterator it = fieldsWithId.iterator(); it.hasNext();)\r\n {\r\n result.add(getField((String)it.next()));\r\n }\r\n for (Iterator it = fieldsWithoutId.iterator(); it.hasNext();)\r\n {\r\n result.add(getField((String)it.next()));\r\n }\r\n\r\n _fields = result;\r\n }"
] | [
"public double mean() {\n double total = 0;\n\n final int N = getNumElements();\n for( int i = 0; i < N; i++ ) {\n total += get(i);\n }\n\n return total/N;\n }",
"private void stream(InputStream is, File destFile) throws IOException {\n try {\n startProgress();\n OutputStream os = new FileOutputStream(destFile);\n \n boolean finished = false;\n try {\n byte[] buf = new byte[1024 * 10];\n int read;\n while ((read = is.read(buf)) >= 0) {\n os.write(buf, 0, read);\n processedBytes += read;\n logProgress();\n }\n \n os.flush();\n finished = true;\n } finally {\n os.close();\n if (!finished) {\n destFile.delete();\n }\n }\n } finally {\n is.close();\n completeProgress();\n }\n }",
"public <T extends Widget & Checkable> boolean addOnCheckChangedListener\n (OnCheckChangedListener listener) {\n final boolean added;\n synchronized (mListeners) {\n added = mListeners.add(listener);\n }\n if (added) {\n List<T> c = getCheckableChildren();\n for (int i = 0; i < c.size(); ++i) {\n listener.onCheckChanged(this, c.get(i), i);\n }\n }\n return added;\n }",
"public boolean deleteWithCustomTimeout(CompositeVoldemortRequest<K, V> deleteRequestObject) {\n List<Versioned<V>> versionedValues;\n\n validateTimeout(deleteRequestObject.getRoutingTimeoutInMs());\n boolean hasVersion = deleteRequestObject.getVersion() == null ? false : true;\n String keyHexString = \"\";\n if(!hasVersion) {\n long startTimeInMs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) deleteRequestObject.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n logger.debug(\"DELETE without version requested for key: \" + keyHexString\n + \" , for store: \" + this.storeName + \" at time(in ms): \"\n + startTimeInMs + \" . Nested GET and DELETE requests to follow ---\");\n }\n // We use the full timeout for doing the Get. In this, we're being\n // optimistic that the subsequent delete might be faster all the\n // steps might finish within the allotted time\n deleteRequestObject.setResolveConflicts(true);\n versionedValues = getWithCustomTimeout(deleteRequestObject);\n Versioned<V> versioned = getItemOrThrow(deleteRequestObject.getKey(),\n null,\n versionedValues);\n\n if(versioned == null) {\n return false;\n }\n\n long timeLeft = deleteRequestObject.getRoutingTimeoutInMs()\n - (System.currentTimeMillis() - startTimeInMs);\n\n // This should not happen unless there's a bug in the\n // getWithCustomTimeout\n if(timeLeft < 0) {\n throw new StoreTimeoutException(\"DELETE request timed out\");\n }\n\n // Update the version and the new timeout\n deleteRequestObject.setVersion(versioned.getVersion());\n deleteRequestObject.setRoutingTimeoutInMs(timeLeft);\n\n }\n long deleteVersionStartTimeInNs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) deleteRequestObject.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n debugLogStart(\"DELETE\",\n deleteRequestObject.getRequestOriginTimeInMs(),\n deleteVersionStartTimeInNs,\n keyHexString);\n }\n boolean result = store.delete(deleteRequestObject);\n if(logger.isDebugEnabled()) {\n debugLogEnd(\"DELETE\",\n deleteRequestObject.getRequestOriginTimeInMs(),\n deleteVersionStartTimeInNs,\n System.currentTimeMillis(),\n keyHexString,\n 0);\n }\n if(!hasVersion && logger.isDebugEnabled()) {\n logger.debug(\"DELETE without version response received for key: \" + keyHexString\n + \", for store: \" + this.storeName + \" at time(in ms): \"\n + System.currentTimeMillis());\n }\n return result;\n }",
"@SuppressWarnings(\"unchecked\")\n\tpublic <T extends Annotation> T getAnnotation(Class<T> annotationType) {\n\t\tfor (Annotation annotation : this.annotations) {\n\t\t\tif (annotation.annotationType().equals(annotationType)) {\n\t\t\t\treturn (T) annotation;\n\t\t\t}\n\t\t}\n\t\tfor (Annotation metaAnn : this.annotations) {\n\t\t\tT ann = metaAnn.annotationType().getAnnotation(annotationType);\n\t\t\tif (ann != null) {\n\t\t\t\treturn ann;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"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 }",
"private Set<QualifierInstance> getRequiredQualifiers(EnhancedAnnotatedParameter<?, ? super X> enhancedDisposedParameter) {\n Set<Annotation> disposedParameterQualifiers = enhancedDisposedParameter.getMetaAnnotations(Qualifier.class);\n if (disposedParameterQualifiers.isEmpty()) {\n disposedParameterQualifiers = Collections.<Annotation> singleton(Default.Literal.INSTANCE);\n }\n return beanManager.getServices().get(MetaAnnotationStore.class).getQualifierInstances(disposedParameterQualifiers);\n }",
"public static spilloverpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tspilloverpolicy_stats obj = new spilloverpolicy_stats();\n\t\tobj.set_name(name);\n\t\tspilloverpolicy_stats response = (spilloverpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"static Date parseDate(String dateString) {\n try {\n return DATE_FORMAT.parseDateTime(dateString).toDate();\n } catch (IllegalArgumentException e) {\n return null;\n }\n }"
] |
Use this API to fetch a aaaglobal_binding resource . | [
"public static aaaglobal_binding get(nitro_service service) throws Exception{\n\t\taaaglobal_binding obj = new aaaglobal_binding();\n\t\taaaglobal_binding response = (aaaglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"@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 }",
"private void ensureCollectionClass(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_ARRAY_ELEMENT_CLASS_REF))\r\n {\r\n // an array cannot have a collection-class specified \r\n if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLLECTION_CLASS))\r\n {\r\n throw new ConstraintException(\"Collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" is an array but does specify collection-class\");\r\n }\r\n else\r\n {\r\n // no further processing necessary as its an array\r\n return;\r\n }\r\n }\r\n\r\n if (CHECKLEVEL_STRICT.equals(checkLevel))\r\n { \r\n InheritanceHelper helper = new InheritanceHelper();\r\n ModelDef model = (ModelDef)collDef.getOwner().getOwner();\r\n String specifiedClass = collDef.getProperty(PropertyHelper.OJB_PROPERTY_COLLECTION_CLASS);\r\n String variableType = collDef.getProperty(PropertyHelper.OJB_PROPERTY_VARIABLE_TYPE);\r\n \r\n try\r\n {\r\n if (specifiedClass != null)\r\n {\r\n // if we have a specified class then it has to implement the manageable collection and be a sub type of the variable type\r\n if (!helper.isSameOrSubTypeOf(specifiedClass, variableType))\r\n {\r\n throw new ConstraintException(\"The type \"+specifiedClass+\" specified as collection-class of the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" is not a sub type of the variable type \"+variableType);\r\n }\r\n if (!helper.isSameOrSubTypeOf(specifiedClass, MANAGEABLE_COLLECTION_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The type \"+specifiedClass+\" specified as collection-class of the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" does not implement \"+MANAGEABLE_COLLECTION_INTERFACE);\r\n }\r\n }\r\n else\r\n {\r\n // no collection class specified so the variable type has to be a collection type\r\n if (helper.isSameOrSubTypeOf(variableType, MANAGEABLE_COLLECTION_INTERFACE))\r\n {\r\n // we can specify it as a collection-class as it is an manageable collection\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_COLLECTION_CLASS, variableType);\r\n }\r\n else if (!helper.isSameOrSubTypeOf(variableType, JAVA_COLLECTION_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" needs the collection-class attribute as its variable type does not implement \"+JAVA_COLLECTION_INTERFACE);\r\n }\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName());\r\n }\r\n }\r\n }",
"private Object getUdfValue(UDFAssignmentType udf)\n {\n if (udf.getCostValue() != null)\n {\n return udf.getCostValue();\n }\n \n if (udf.getDoubleValue() != null)\n {\n return udf.getDoubleValue();\n }\n \n if (udf.getFinishDateValue() != null)\n {\n return udf.getFinishDateValue();\n }\n \n if (udf.getIndicatorValue() != null)\n {\n return udf.getIndicatorValue();\n }\n \n if (udf.getIntegerValue() != null)\n {\n return udf.getIntegerValue();\n }\n \n if (udf.getStartDateValue() != null)\n {\n return udf.getStartDateValue();\n }\n \n if (udf.getTextValue() != null)\n {\n return udf.getTextValue();\n }\n \n return null;\n }",
"protected AbsoluteURI getGeneratedLocation(PersistedTrace trace) {\n\t\tAbsoluteURI path = trace.getPath();\n\t\tString fileName = traceFileNameProvider.getJavaFromTrace(path.getURI().toString());\n\t\treturn new AbsoluteURI(fileName);\n\t}",
"public synchronized void maybeThrottle(int eventsSeen) {\n if (maxRatePerSecond > 0) {\n long now = time.milliseconds();\n try {\n rateSensor.record(eventsSeen, now);\n } catch (QuotaViolationException e) {\n // If we're over quota, we calculate how long to sleep to compensate.\n double currentRate = e.getValue();\n if (currentRate > this.maxRatePerSecond) {\n double excessRate = currentRate - this.maxRatePerSecond;\n long sleepTimeMs = Math.round(excessRate / this.maxRatePerSecond * voldemort.utils.Time.MS_PER_SECOND);\n if(logger.isDebugEnabled()) {\n logger.debug(\"Throttler quota exceeded:\\n\" +\n \"eventsSeen \\t= \" + eventsSeen + \" in this call of maybeThrotte(),\\n\" +\n \"currentRate \\t= \" + currentRate + \" events/sec,\\n\" +\n \"maxRatePerSecond \\t= \" + this.maxRatePerSecond + \" events/sec,\\n\" +\n \"excessRate \\t= \" + excessRate + \" events/sec,\\n\" +\n \"sleeping for \\t\" + sleepTimeMs + \" ms to compensate.\\n\" +\n \"rateConfig.timeWindowMs() = \" + rateConfig.timeWindowMs());\n }\n if (sleepTimeMs > rateConfig.timeWindowMs()) {\n logger.warn(\"Throttler sleep time (\" + sleepTimeMs + \" ms) exceeds \" +\n \"window size (\" + rateConfig.timeWindowMs() + \" ms). This will likely \" +\n \"result in not being able to honor the rate limit accurately.\");\n // When using the HDFS Fetcher, setting the hdfs.fetcher.buffer.size\n // too high could cause this problem.\n }\n time.sleep(sleepTimeMs);\n } else if (logger.isDebugEnabled()) {\n logger.debug(\"Weird. Got QuotaValidationException but measured rate not over rateLimit: \" +\n \"currentRate = \" + currentRate + \" , rateLimit = \" + this.maxRatePerSecond);\n }\n }\n }\n }",
"@Override\n public List<InstalledIdentity> getInstalledIdentities() throws PatchingException {\n\n List<InstalledIdentity> installedIdentities;\n\n final File metadataDir = installedImage.getInstallationMetadata();\n if(!metadataDir.exists()) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n final String defaultConf = defaultIdentity.getIdentity().getName() + Constants.DOT_CONF;\n final File[] identityConfs = metadataDir.listFiles(new FileFilter() {\n @Override\n public boolean accept(File pathname) {\n return pathname.isFile() &&\n pathname.getName().endsWith(Constants.DOT_CONF) &&\n !pathname.getName().equals(defaultConf);\n }\n });\n if(identityConfs == null || identityConfs.length == 0) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n installedIdentities = new ArrayList<InstalledIdentity>(identityConfs.length + 1);\n installedIdentities.add(defaultIdentity);\n for(File conf : identityConfs) {\n final Properties props = loadProductConf(conf);\n String productName = conf.getName();\n productName = productName.substring(0, productName.length() - Constants.DOT_CONF.length());\n final String productVersion = props.getProperty(Constants.CURRENT_VERSION);\n\n InstalledIdentity identity;\n try {\n identity = LayersFactory.load(installedImage, new ProductConfig(productName, productVersion, null), moduleRoots, bundleRoots);\n } catch (IOException e) {\n throw new PatchingException(PatchLogger.ROOT_LOGGER.failedToLoadInfo(productName), e);\n }\n installedIdentities.add(identity);\n }\n }\n }\n return installedIdentities;\n }",
"public <T extends Widget & Checkable> boolean check(int checkableIndex) {\n List<T> children = getCheckableChildren();\n T checkableWidget = children.get(checkableIndex);\n return checkInternal(checkableWidget, true);\n }",
"public void sendJsonToUser(Object data, String username) {\n sendToUser(JSON.toJSONString(data), username);\n }",
"public static long getMaxIdForClass(\r\n PersistenceBroker brokerForClass, ClassDescriptor cldForOriginalOrExtent, FieldDescriptor original)\r\n throws PersistenceBrokerException\r\n {\r\n FieldDescriptor field = null;\r\n if (!original.getClassDescriptor().equals(cldForOriginalOrExtent))\r\n {\r\n // check if extent match not the same table\r\n if (!original.getClassDescriptor().getFullTableName().equals(\r\n cldForOriginalOrExtent.getFullTableName()))\r\n {\r\n // we have to look for id's in extent class table\r\n field = cldForOriginalOrExtent.getFieldDescriptorByName(original.getAttributeName());\r\n }\r\n }\r\n else\r\n {\r\n field = original;\r\n }\r\n if (field == null)\r\n {\r\n // if null skip this call\r\n return 0;\r\n }\r\n\r\n String column = field.getColumnName();\r\n long result = 0;\r\n ResultSet rs = null;\r\n Statement stmt = null;\r\n StatementManagerIF sm = brokerForClass.serviceStatementManager();\r\n String table = cldForOriginalOrExtent.getFullTableName();\r\n // String column = cld.getFieldDescriptorByName(fieldName).getColumnName();\r\n String sql = SM_SELECT_MAX + column + SM_FROM + table;\r\n try\r\n {\r\n //lookup max id for the current class\r\n stmt = sm.getGenericStatement(cldForOriginalOrExtent, Query.NOT_SCROLLABLE);\r\n rs = stmt.executeQuery(sql);\r\n rs.next();\r\n result = rs.getLong(1);\r\n }\r\n catch (Exception e)\r\n {\r\n log.warn(\"Cannot lookup max value from table \" + table + \" for column \" + column +\r\n \", PB was \" + brokerForClass + \", using jdbc-descriptor \" +\r\n brokerForClass.serviceConnectionManager().getConnectionDescriptor(), e);\r\n }\r\n finally\r\n {\r\n try\r\n {\r\n sm.closeResources(stmt, rs);\r\n }\r\n catch (Exception ignore)\r\n {\r\n // ignore it\r\n }\r\n }\r\n return result;\r\n }"
] |
Creates a Sink Processor
@param dataSink the data sink itself
@param parallelism the parallelism of this processor
@param description the description for this processor
@param taskConf the configuration for this processor
@param system actor system
@return the new created sink processor | [
"public static Processor<DataSinkTask> sink(DataSink dataSink, int parallelism, String description, UserConfig taskConf, ActorSystem system) {\n io.gearpump.streaming.Processor<DataSinkTask> p = DataSinkProcessor.apply(dataSink, parallelism, description, taskConf, system);\n return new Processor(p);\n }"
] | [
"private void recordBackupSet(File backupDir) throws IOException {\n String[] filesInEnv = env.getHome().list();\n SimpleDateFormat format = new SimpleDateFormat(\"yyyy_MM_dd_kk_mm_ss\");\n String recordFileName = \"backupset-\" + format.format(new Date());\n File recordFile = new File(backupDir, recordFileName);\n if(recordFile.exists()) {\n recordFile.renameTo(new File(backupDir, recordFileName + \".old\"));\n }\n\n PrintStream backupRecord = new PrintStream(new FileOutputStream(recordFile));\n backupRecord.println(\"Lastfile:\" + Long.toHexString(backupHelper.getLastFileInBackupSet()));\n if(filesInEnv != null) {\n for(String file: filesInEnv) {\n if(file.endsWith(BDB_EXT))\n backupRecord.println(file);\n }\n }\n backupRecord.close();\n }",
"public static String getDays(RecurringTask task)\n {\n StringBuilder sb = new StringBuilder();\n for (Day day : Day.values())\n {\n sb.append(task.getWeeklyDay(day) ? \"1\" : \"0\");\n }\n return sb.toString();\n }",
"public EventBus emitAsync(EventObject event, Object... args) {\n return _emitWithOnceBus(eventContextAsync(event, args));\n }",
"private ModelNode buildAddOperation(final ModelNode address, final Map<String, String> properties) {\n final ModelNode op = ServerOperations.createAddOperation(address);\n for (Map.Entry<String, String> prop : properties.entrySet()) {\n final String[] props = prop.getKey().split(\",\");\n if (props.length == 0) {\n throw new RuntimeException(\"Invalid property \" + prop);\n }\n ModelNode node = op;\n for (int i = 0; i < props.length - 1; ++i) {\n node = node.get(props[i]);\n }\n final String value = prop.getValue() == null ? \"\" : prop.getValue();\n if (value.startsWith(\"!!\")) {\n handleDmrString(node, props[props.length - 1], value);\n } else {\n node.get(props[props.length - 1]).set(value);\n }\n }\n return op;\n }",
"public static DMatrixSparseCSC symmetric( int N , int nz_total ,\n double min , double max , Random rand) {\n\n // compute the number of elements in the triangle, including diagonal\n int Ntriagle = (N*N+N)/2;\n // create a list of open elements\n int open[] = new int[Ntriagle];\n for (int row = 0, index = 0; row < N; row++) {\n for (int col = row; col < N; col++, index++) {\n open[index] = row*N+col;\n }\n }\n\n // perform a random draw\n UtilEjml.shuffle(open,open.length,0,nz_total,rand);\n Arrays.sort(open,0,nz_total);\n\n // construct the matrix\n DMatrixSparseTriplet A = new DMatrixSparseTriplet(N,N,nz_total*2);\n for (int i = 0; i < nz_total; i++) {\n int index = open[i];\n int row = index/N;\n int col = index%N;\n\n double value = rand.nextDouble()*(max-min)+min;\n\n if( row == col ) {\n A.addItem(row,col,value);\n } else {\n A.addItem(row,col,value);\n A.addItem(col,row,value);\n }\n }\n\n DMatrixSparseCSC B = new DMatrixSparseCSC(N,N,A.nz_length);\n ConvertDMatrixStruct.convert(A,B);\n\n return B;\n }",
"public static Cluster swapGreedyRandomPartitions(final Cluster nextCandidateCluster,\n final List<Integer> nodeIds,\n final int greedySwapMaxPartitionsPerNode,\n final int greedySwapMaxPartitionsPerZone,\n List<StoreDefinition> storeDefs) {\n\n System.out.println(\"GreedyRandom : nodeIds:\" + nodeIds);\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n int nodeIdA = -1;\n int nodeIdB = -1;\n int partitionIdA = -1;\n int partitionIdB = -1;\n\n for(int nodeIdAPrime: nodeIds) {\n System.out.println(\"GreedyRandom : processing nodeId:\" + nodeIdAPrime);\n List<Integer> partitionIdsAPrime = new ArrayList<Integer>();\n partitionIdsAPrime.addAll(returnCluster.getNodeById(nodeIdAPrime).getPartitionIds());\n Collections.shuffle(partitionIdsAPrime);\n\n int maxPartitionsInAPrime = Math.min(greedySwapMaxPartitionsPerNode,\n partitionIdsAPrime.size());\n\n for(int offsetAPrime = 0; offsetAPrime < maxPartitionsInAPrime; offsetAPrime++) {\n Integer partitionIdAPrime = partitionIdsAPrime.get(offsetAPrime);\n List<Pair<Integer, Integer>> partitionIdsZone = new ArrayList<Pair<Integer, Integer>>();\n for(int nodeIdBPrime: nodeIds) {\n if(nodeIdBPrime == nodeIdAPrime)\n continue;\n for(Integer partitionIdBPrime: returnCluster.getNodeById(nodeIdBPrime)\n .getPartitionIds()) {\n partitionIdsZone.add(new Pair<Integer, Integer>(nodeIdBPrime,\n partitionIdBPrime));\n }\n }\n\n Collections.shuffle(partitionIdsZone);\n int maxPartitionsInZone = Math.min(greedySwapMaxPartitionsPerZone,\n partitionIdsZone.size());\n for(int offsetZone = 0; offsetZone < maxPartitionsInZone; offsetZone++) {\n Integer nodeIdBPrime = partitionIdsZone.get(offsetZone).getFirst();\n Integer partitionIdBPrime = partitionIdsZone.get(offsetZone).getSecond();\n Cluster swapResult = swapPartitions(returnCluster,\n nodeIdAPrime,\n partitionIdAPrime,\n nodeIdBPrime,\n partitionIdBPrime);\n double swapUtility = new PartitionBalance(swapResult, storeDefs).getUtility();\n if(swapUtility < currentUtility) {\n currentUtility = swapUtility;\n System.out.println(\" -> \" + currentUtility);\n nodeIdA = nodeIdAPrime;\n partitionIdA = partitionIdAPrime;\n nodeIdB = nodeIdBPrime;\n partitionIdB = partitionIdBPrime;\n }\n }\n }\n }\n\n if(nodeIdA == -1) {\n return returnCluster;\n }\n return swapPartitions(returnCluster, nodeIdA, partitionIdA, nodeIdB, partitionIdB);\n }",
"public static ExecutorService newSingleThreadDaemonExecutor() {\n return Executors.newSingleThreadExecutor(r -> {\n Thread t = Executors.defaultThreadFactory().newThread(r);\n t.setDaemon(true);\n return t;\n });\n }",
"public ForeignkeyDef getForeignkey(String name, String tableName)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n ForeignkeyDef def = null;\r\n\r\n for (Iterator it = getForeignkeys(); it.hasNext();)\r\n {\r\n def = (ForeignkeyDef)it.next();\r\n if (realName.equals(def.getName()) &&\r\n def.getTableName().equals(tableName))\r\n {\r\n return def;\r\n }\r\n }\r\n return null;\r\n }",
"private Database readSingleSchemaFile(DatabaseIO reader, File schemaFile)\r\n {\r\n Database model = null;\r\n\r\n if (!schemaFile.isFile())\r\n {\r\n log(\"Path \"+schemaFile.getAbsolutePath()+\" does not denote a schema file\", Project.MSG_ERR);\r\n }\r\n else if (!schemaFile.canRead())\r\n {\r\n log(\"Could not read schema file \"+schemaFile.getAbsolutePath(), Project.MSG_ERR);\r\n }\r\n else\r\n {\r\n try\r\n {\r\n model = reader.read(schemaFile);\r\n log(\"Read schema file \"+schemaFile.getAbsolutePath(), Project.MSG_INFO);\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new BuildException(\"Could not read schema file \"+schemaFile.getAbsolutePath()+\": \"+ex.getLocalizedMessage(), ex);\r\n }\r\n }\r\n return model;\r\n }"
] |
Acquire a permit for a particular node id so as to allow rebalancing
@param nodeId The id of the node for which we are acquiring a permit
@return Returns true if permit acquired, false if the permit is already
held by someone | [
"public synchronized boolean acquireRebalancingPermit(int nodeId) {\n boolean added = rebalancePermits.add(nodeId);\n logger.info(\"Acquiring rebalancing permit for node id \" + nodeId + \", returned: \" + added);\n\n return added;\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 vpnclientlessaccesspolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tvpnclientlessaccesspolicy_binding obj = new vpnclientlessaccesspolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnclientlessaccesspolicy_binding response = (vpnclientlessaccesspolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static <T> void injectEEFields(Iterable<Set<ResourceInjection<?>>> resourceInjectionsHierarchy,\n T beanInstance, CreationalContext<T> ctx) {\n for (Set<ResourceInjection<?>> resourceInjections : resourceInjectionsHierarchy) {\n for (ResourceInjection<?> resourceInjection : resourceInjections) {\n resourceInjection.injectResourceReference(beanInstance, ctx);\n }\n }\n }",
"public static void validateClusterZonesSame(final Cluster lhs, final Cluster rhs) {\n Set<Zone> lhsSet = new HashSet<Zone>(lhs.getZones());\n Set<Zone> rhsSet = new HashSet<Zone>(rhs.getZones());\n if(!lhsSet.equals(rhsSet))\n throw new VoldemortException(\"Zones are not the same [ lhs cluster zones (\"\n + lhs.getZones() + \") not equal to rhs cluster zones (\"\n + rhs.getZones() + \") ]\");\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 Map<String, CmsCategory> getReadCategory() {\n\n if (null == m_categories) {\n m_categories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object categoryPath) {\n\n try {\n CmsCategoryService catService = CmsCategoryService.getInstance();\n return catService.localizeCategory(\n m_cms,\n catService.readCategory(m_cms, (String)categoryPath, getRequestContext().getUri()),\n m_cms.getRequestContext().getLocale());\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n\n });\n }\n return m_categories;\n }",
"public static base_responses delete(nitro_service client, nsip6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsip6 deleteresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new nsip6();\n\t\t\t\tdeleteresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\tdeleteresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"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 }",
"void successfulBoot() throws ConfigurationPersistenceException {\n synchronized (this) {\n if (doneBootup.get()) {\n return;\n }\n final File copySource;\n if (!interactionPolicy.isReadOnly()) {\n copySource = mainFile;\n } else {\n\n if ( FilePersistenceUtils.isParentFolderWritable(mainFile) ) {\n copySource = new File(mainFile.getParentFile(), mainFile.getName() + \".boot\");\n } else{\n copySource = new File(configurationDir, mainFile.getName() + \".boot\");\n }\n\n FilePersistenceUtils.deleteFile(copySource);\n }\n\n try {\n if (!bootFile.equals(copySource)) {\n FilePersistenceUtils.copyFile(bootFile, copySource);\n }\n\n createHistoryDirectory();\n\n final File historyBase = new File(historyRoot, mainFile.getName());\n lastFile = addSuffixToFile(historyBase, LAST);\n final File boot = addSuffixToFile(historyBase, BOOT);\n final File initial = addSuffixToFile(historyBase, INITIAL);\n\n if (!initial.exists()) {\n FilePersistenceUtils.copyFile(copySource, initial);\n }\n\n FilePersistenceUtils.copyFile(copySource, lastFile);\n FilePersistenceUtils.copyFile(copySource, boot);\n } catch (IOException e) {\n throw ControllerLogger.ROOT_LOGGER.failedToCreateConfigurationBackup(e, bootFile);\n } finally {\n if (interactionPolicy.isReadOnly()) {\n //Delete the temporary file\n try {\n FilePersistenceUtils.deleteFile(copySource);\n } catch (Exception ignore) {\n }\n }\n }\n doneBootup.set(true);\n }\n }"
] |
Computes the best fit set of polynomial coefficients to the provided observations.
@param samplePoints where the observations were sampled.
@param observations A set of observations. | [
"public void fit( double samplePoints[] , double[] observations ) {\n // Create a copy of the observations and put it into a matrix\n y.reshape(observations.length,1,false);\n System.arraycopy(observations,0, y.data,0,observations.length);\n\n // reshape the matrix to avoid unnecessarily declaring new memory\n // save values is set to false since its old values don't matter\n A.reshape(y.numRows, coef.numRows,false);\n\n // set up the A matrix\n for( int i = 0; i < observations.length; i++ ) {\n\n double obs = 1;\n\n for( int j = 0; j < coef.numRows; j++ ) {\n A.set(i,j,obs);\n obs *= samplePoints[i];\n }\n }\n\n // process the A matrix and see if it failed\n if( !solver.setA(A) )\n throw new RuntimeException(\"Solver failed\");\n\n // solver the the coefficients\n solver.solve(y,coef);\n }"
] | [
"public static List<String> asListLines(String content) {\n List<String> retorno = new ArrayList<String>();\n content = content.replace(CARRIAGE_RETURN, RETURN);\n content = content.replace(RETURN, CARRIAGE_RETURN);\n for (String str : content.split(CARRIAGE_RETURN)) {\n retorno.add(str);\n }\n return retorno;\n }",
"public static base_response disable(nitro_service client, String name) throws Exception {\n\t\tvserver disableresource = new vserver();\n\t\tdisableresource.name = name;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}",
"public Where<T, ID> or() {\n\t\tManyClause clause = new ManyClause(pop(\"OR\"), ManyClause.OR_OPERATION);\n\t\tpush(clause);\n\t\taddNeedsFuture(clause);\n\t\treturn this;\n\t}",
"public 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 }",
"@Deprecated\r\n public void setViews(String views) {\r\n if (views != null) {\r\n try {\r\n setViews(Integer.parseInt(views));\r\n } catch (NumberFormatException e) {\r\n setViews(-1);\r\n }\r\n }\r\n }",
"private String formatRate(Rate value)\n {\n String result = null;\n if (value != null)\n {\n StringBuilder buffer = new StringBuilder(m_formats.getCurrencyFormat().format(value.getAmount()));\n buffer.append(\"/\");\n buffer.append(formatTimeUnit(value.getUnits()));\n result = buffer.toString();\n }\n return (result);\n }",
"public static String parseRoot(String zookeepers) {\n int slashIndex = zookeepers.indexOf(\"/\");\n if (slashIndex != -1) {\n return zookeepers.substring(slashIndex).trim();\n }\n return \"/\";\n }",
"private Storepoint getCurrentStorepoint(Project phoenixProject)\n {\n List<Storepoint> storepoints = phoenixProject.getStorepoints().getStorepoint();\n Collections.sort(storepoints, new Comparator<Storepoint>()\n {\n @Override public int compare(Storepoint o1, Storepoint o2)\n {\n return DateHelper.compare(o2.getCreationTime(), o1.getCreationTime());\n }\n });\n return storepoints.get(0);\n }",
"private int getDaysToNextMatch(WeekDay weekDay) {\n\n for (WeekDay wd : m_weekDays) {\n if (wd.compareTo(weekDay) > 0) {\n return wd.toInt() - weekDay.toInt();\n }\n }\n return (m_weekDays.iterator().next().toInt() + (m_interval * I_CmsSerialDateValue.NUM_OF_WEEKDAYS))\n - weekDay.toInt();\n }"
] |
Calculate the adjusted forward swaprate corresponding to a change of payoff unit from the given swapAnnuity to the given payoffUnit
using the Black-Scholes model for the swap rate together with the Hunt-Kennedy convexity adjustment.
@param forwardSwaprate The forward swap rate
@param volatility Volatility of the log of the swap rate
@param swapAnnuity The swap annuity
@param optionMaturity The option maturity
@param swapMaturity The swap maturity
@param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date
@return Convexity adjusted forward rate | [
"public static double huntKennedyCMSAdjustedRate(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble swapAnnuity,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble swapMaturity,\n\t\t\tdouble payoffUnit)\n\t{\n\t\tdouble a = 1.0/swapMaturity;\n\t\tdouble b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;\n\t\tdouble convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);\n\n\t\tdouble rateUnadjusted\t= forwardSwaprate;\n\t\tdouble rateAdjusted\t\t= forwardSwaprate * convexityAdjustment;\n\n\t\treturn (a * rateUnadjusted + b * forwardSwaprate * rateAdjusted) * swapAnnuity / payoffUnit;\n\t}"
] | [
"public static csvserver_cspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cspolicy_binding obj = new csvserver_cspolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cspolicy_binding response[] = (csvserver_cspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void setWholeDay(Boolean isWholeDay) {\r\n\r\n if (m_model.isWholeDay() ^ ((null != isWholeDay) && isWholeDay.booleanValue())) {\r\n m_model.setWholeDay(isWholeDay);\r\n valueChanged();\r\n }\r\n }",
"List<String> getRuleFlowNames(HttpServletRequest req) {\n final String[] projectAndBranch = getProjectAndBranchNames(req);\n\n // Query RuleFlowGroups for asset project and branch\n List<RefactoringPageRow> results = queryService.query(\n DesignerFindRuleFlowNamesQuery.NAME,\n new HashSet<ValueIndexTerm>() {{\n add(new ValueSharedPartIndexTerm(\"*\",\n PartType.RULEFLOW_GROUP,\n TermSearchType.WILDCARD));\n add(new ValueModuleNameIndexTerm(projectAndBranch[0]));\n if (projectAndBranch[1] != null) {\n add(new ValueBranchNameIndexTerm(projectAndBranch[1]));\n }\n }});\n\n final List<String> ruleFlowGroupNames = new ArrayList<String>();\n for (RefactoringPageRow row : results) {\n ruleFlowGroupNames.add((String) row.getValue());\n }\n Collections.sort(ruleFlowGroupNames);\n\n // Query RuleFlowGroups for all projects and branches\n results = queryService.query(\n DesignerFindRuleFlowNamesQuery.NAME,\n new HashSet<ValueIndexTerm>() {{\n add(new ValueSharedPartIndexTerm(\"*\",\n PartType.RULEFLOW_GROUP,\n TermSearchType.WILDCARD));\n }});\n final List<String> otherRuleFlowGroupNames = new LinkedList<String>();\n for (RefactoringPageRow row : results) {\n String ruleFlowGroupName = (String) row.getValue();\n if (!ruleFlowGroupNames.contains(ruleFlowGroupName)) {\n // but only add the new ones\n otherRuleFlowGroupNames.add(ruleFlowGroupName);\n }\n }\n Collections.sort(otherRuleFlowGroupNames);\n\n ruleFlowGroupNames.addAll(otherRuleFlowGroupNames);\n\n return ruleFlowGroupNames;\n }",
"@Override\n public ImageSource apply(ImageSource input) {\n final int[][] pixelMatrix = new int[3][3];\n\n int w = input.getWidth();\n int h = input.getHeight();\n\n int[][] output = new int[h][w];\n\n for (int j = 1; j < h - 1; j++) {\n for (int i = 1; i < w - 1; i++) {\n pixelMatrix[0][0] = input.getR(i - 1, j - 1);\n pixelMatrix[0][1] = input.getRGB(i - 1, j);\n pixelMatrix[0][2] = input.getRGB(i - 1, j + 1);\n pixelMatrix[1][0] = input.getRGB(i, j - 1);\n pixelMatrix[1][2] = input.getRGB(i, j + 1);\n pixelMatrix[2][0] = input.getRGB(i + 1, j - 1);\n pixelMatrix[2][1] = input.getRGB(i + 1, j);\n pixelMatrix[2][2] = input.getRGB(i + 1, j + 1);\n\n int edge = (int) convolution(pixelMatrix);\n int rgb = (edge << 16 | edge << 8 | edge);\n output[j][i] = rgb;\n }\n }\n\n MatrixSource source = new MatrixSource(output);\n return source;\n }",
"public Integer getGroupIdFromName(String groupName) {\n return (Integer) sqlService.getFromTable(Constants.GENERIC_ID, Constants.GROUPS_GROUP_NAME, groupName,\n Constants.DB_TABLE_GROUPS);\n }",
"public void requestNodeInfo(int nodeId) {\n\t\tSerialMessage newMessage = new SerialMessage(nodeId, SerialMessage.SerialMessageClass.RequestNodeInfo, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationUpdate, SerialMessage.SerialMessagePriority.High);\n \tbyte[] newPayload = { (byte) nodeId };\n \tnewMessage.setMessagePayload(newPayload);\n \tthis.enqueue(newMessage);\n\t}",
"public int[][] argb() {\n return Arrays.stream(points()).map(p -> argb(p.x, p.y)).toArray(int[][]::new);\n }",
"public synchronized void setSynced(boolean sync) {\n if (synced.get() != sync) {\n // We are changing sync state, so add or remove our master listener as appropriate.\n if (sync && isSendingStatus()) {\n addMasterListener(ourSyncMasterListener);\n } else {\n removeMasterListener(ourSyncMasterListener);\n }\n\n // Also, if there is a tempo master, and we just got synced, adopt its tempo.\n if (!isTempoMaster() && getTempoMaster() != null) {\n setTempo(getMasterTempo());\n }\n }\n synced.set(sync);\n }",
"public RedwoodConfiguration showOnlyChannels(final Object[] channels){\r\n tasks.add(new Runnable() { public void run() { Redwood.showOnlyChannels(channels); } });\r\n return this;\r\n }"
] |
Add a date with a certain check state.
@param date the date to add.
@param checkState the check state. | [
"private void addDateWithCheckState(Date date, boolean checkState) {\n\n addCheckBox(date, checkState);\n if (!m_dates.contains(date)) {\n m_dates.add(date);\n fireValueChange();\n }\n }"
] | [
"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 static int Mod(int x, int m) {\r\n if (m < 0) m = -m;\r\n int r = x % m;\r\n return r < 0 ? r + m : r;\r\n }",
"private void readAvailabilityTable(Resource resource, AvailabilityPeriods periods)\n {\n if (periods != null)\n {\n AvailabilityTable table = resource.getAvailability();\n List<AvailabilityPeriod> list = periods.getAvailabilityPeriod();\n for (AvailabilityPeriod period : list)\n {\n Date start = period.getAvailableFrom();\n Date end = period.getAvailableTo();\n Number units = DatatypeConverter.parseUnits(period.getAvailableUnits());\n Availability availability = new Availability(start, end, units);\n table.add(availability);\n }\n Collections.sort(table);\n }\n }",
"private void updateDefaultTimeAndSizeRollingAppender(final FoundationFileRollingAppender appender) {\n\n\t\tif (appender.getDatePattern().trim().length() == 0) {\n\t\t\tappender.setDatePattern(FoundationLoggerConstants.DEFAULT_DATE_PATTERN.toString());\n\t\t}\n\t\t\n\t\tString maxFileSizeKey = \"log4j.appender.\"+appender.getName()+\".MaxFileSize\";\n\t\tappender.setMaxFileSize(FoundationLogger.log4jConfigProps.getProperty(maxFileSizeKey, FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString()));\n\n//\t\tif (appender.getMaxFileSize() == null || appender.getMaxFileSize().equals(FoundationLoggerConstants.DEFAULT_FILE_SIZE.toString())) {\n//\t\t\tappender.setMaxFileSize(FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString());\n//\t\t}\n\n\t\tString maxRollCountKey = \"log4j.appender.\"+appender.getName()+\".MaxRollFileCount\";\n\t\tappender.setMaxRollFileCount(Integer.parseInt(FoundationLogger.log4jConfigProps.getProperty(maxRollCountKey,\"100\")));\n\t}",
"protected boolean showMoreEntries(Calendar nextDate, int previousOccurrences) {\n\n switch (getSerialEndType()) {\n case DATE:\n boolean moreByDate = nextDate.getTimeInMillis() < m_endMillis;\n boolean moreByOccurrences = previousOccurrences < CmsSerialDateUtil.getMaxEvents();\n if (moreByDate && !moreByOccurrences) {\n m_hasTooManyOccurrences = Boolean.TRUE;\n }\n return moreByDate && moreByOccurrences;\n case TIMES:\n case SINGLE:\n return previousOccurrences < getOccurrences();\n default:\n throw new IllegalArgumentException();\n }\n }",
"public String getMessage(Locale locale) {\n\t\tif (getCause() != null) {\n\t\t\tString message = getShortMessage(locale) + \", \" + translate(\"ROOT_CAUSE\", locale) + \" \";\n\t\t\tif (getCause() instanceof GeomajasException) {\n\t\t\t\treturn message + ((GeomajasException) getCause()).getMessage(locale);\n\t\t\t}\n\t\t\treturn message + getCause().getMessage();\n\t\t} else {\n\t\t\treturn getShortMessage(locale);\n\t\t}\n\t}",
"private void processProperties(XMLStreamWriter writer, Set<Method> methodSet, Class<?> aClass) throws IntrospectionException, XMLStreamException\n {\n BeanInfo beanInfo = Introspector.getBeanInfo(aClass, aClass.getSuperclass());\n PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();\n\n for (int i = 0; i < propertyDescriptors.length; i++)\n {\n PropertyDescriptor propertyDescriptor = propertyDescriptors[i];\n if (propertyDescriptor.getPropertyType() != null)\n {\n String name = propertyDescriptor.getName();\n Method readMethod = propertyDescriptor.getReadMethod();\n Method writeMethod = propertyDescriptor.getWriteMethod();\n\n String readMethodName = readMethod == null ? null : readMethod.getName();\n String writeMethodName = writeMethod == null ? null : writeMethod.getName();\n addProperty(writer, name, propertyDescriptor.getPropertyType(), readMethodName, writeMethodName);\n\n if (readMethod != null)\n {\n methodSet.add(readMethod);\n }\n\n if (writeMethod != null)\n {\n methodSet.add(writeMethod);\n }\n }\n else\n {\n processAmbiguousProperty(writer, methodSet, aClass, propertyDescriptor);\n }\n }\n }",
"private void configureCaching(HttpServletResponse response, int seconds) {\n\t\t// HTTP 1.0 header\n\t\tresponse.setDateHeader(HTTP_EXPIRES_HEADER, System.currentTimeMillis() + seconds * 1000L);\n\t\tif (seconds > 0) {\n\t\t\t// HTTP 1.1 header\n\t\t\tresponse.setHeader(HTTP_CACHE_CONTROL_HEADER, \"max-age=\" + seconds);\n\t\t} else {\n\t\t\t// HTTP 1.1 header\n\t\t\tresponse.setHeader(HTTP_CACHE_CONTROL_HEADER, \"no-cache\");\n\n\t\t}\n\t}",
"private void sendOneAsyncHint(final ByteArray slopKey,\n final Versioned<byte[]> slopVersioned,\n final List<Node> nodesToTry) {\n Node nodeToHostHint = null;\n boolean foundNode = false;\n while(nodesToTry.size() > 0) {\n nodeToHostHint = nodesToTry.remove(0);\n if(!failedNodes.contains(nodeToHostHint) && failureDetector.isAvailable(nodeToHostHint)) {\n foundNode = true;\n break;\n }\n }\n if(!foundNode) {\n Slop slop = slopSerializer.toObject(slopVersioned.getValue());\n logger.error(\"Trying to send an async hint but used up all nodes. key: \"\n + slop.getKey() + \" version: \" + slopVersioned.getVersion().toString());\n return;\n }\n final Node node = nodeToHostHint;\n int nodeId = node.getId();\n\n NonblockingStore nonblockingStore = nonblockingSlopStores.get(nodeId);\n Utils.notNull(nonblockingStore);\n\n final Long startNs = System.nanoTime();\n NonblockingStoreCallback callback = new NonblockingStoreCallback() {\n\n @Override\n public void requestComplete(Object result, long requestTime) {\n Slop slop = null;\n boolean loggerDebugEnabled = logger.isDebugEnabled();\n if(loggerDebugEnabled) {\n slop = slopSerializer.toObject(slopVersioned.getValue());\n }\n Response<ByteArray, Object> response = new Response<ByteArray, Object>(node,\n slopKey,\n result,\n requestTime);\n if(response.getValue() instanceof Exception\n && !(response.getValue() instanceof ObsoleteVersionException)) {\n if(!failedNodes.contains(node))\n failedNodes.add(node);\n if(response.getValue() instanceof UnreachableStoreException) {\n UnreachableStoreException use = (UnreachableStoreException) response.getValue();\n\n if(loggerDebugEnabled) {\n logger.debug(\"Write of key \" + slop.getKey() + \" for \"\n + slop.getNodeId() + \" to node \" + node\n + \" failed due to unreachable: \" + use.getMessage());\n }\n\n failureDetector.recordException(node, (System.nanoTime() - startNs)\n / Time.NS_PER_MS, use);\n }\n sendOneAsyncHint(slopKey, slopVersioned, nodesToTry);\n }\n\n if(loggerDebugEnabled)\n logger.debug(\"Slop write of key \" + slop.getKey() + \" for node \"\n + slop.getNodeId() + \" to node \" + node + \" succeeded in \"\n + (System.nanoTime() - startNs) + \" ns\");\n\n failureDetector.recordSuccess(node, (System.nanoTime() - startNs) / Time.NS_PER_MS);\n\n }\n };\n nonblockingStore.submitPutRequest(slopKey, slopVersioned, null, callback, timeoutMs);\n }"
] |
Use this API to link sslcertkey. | [
"public static base_response link(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey linkresource = new sslcertkey();\n\t\tlinkresource.certkey = resource.certkey;\n\t\tlinkresource.linkcertkeyname = resource.linkcertkeyname;\n\t\treturn linkresource.perform_operation(client,\"link\");\n\t}"
] | [
"public static <T> JacksonParser<T> json(Class<T> contentType) {\n return new JacksonParser<>(null, contentType);\n }",
"public boolean getEnterpriseFlag(int index)\n {\n return (BooleanHelper.getBoolean((Boolean) getCachedValue(selectField(TaskFieldLists.ENTERPRISE_FLAG, index))));\n }",
"public WebSocketContext reTag(String label) {\n WebSocketConnectionRegistry registry = manager.tagRegistry();\n registry.signOff(connection);\n registry.signIn(label, connection);\n return this;\n }",
"void rejectAttributes(RejectedAttributesLogContext rejectedAttributes, ModelNode attributeValue) {\n for (RejectAttributeChecker checker : checks) {\n rejectedAttributes.checkAttribute(checker, name, attributeValue);\n }\n }",
"public Integer getBlockMaskPrefixLength(boolean network) {\n\t\tInteger prefixLen;\n\t\tif(network) {\n\t\t\tif(hasNoPrefixCache() || (prefixLen = prefixCache.networkMaskPrefixLen) == null) {\n\t\t\t\tprefixLen = setNetworkMaskPrefix(checkForPrefixMask(network));\n\t\t\t}\n\t\t} else {\n\t\t\tif(hasNoPrefixCache() || (prefixLen = prefixCache.hostMaskPrefixLen) == null) {\n\t\t\t\tprefixLen = setHostMaskPrefix(checkForPrefixMask(network));\n\t\t\t}\n\t\t}\n\t\tif(prefixLen < 0) {\n\t\t\treturn null;\n\t\t}\n\t\treturn prefixLen;\n\t}",
"private <T extends ProgramElementDoc> List<T> filterByVisibility(T[] docs, Visibility visibility) {\n\tif (visibility == Visibility.PRIVATE)\n\t return Arrays.asList(docs);\n\n\tList<T> filtered = new ArrayList<T>();\n\tfor (T doc : docs) {\n\t if (Visibility.get(doc).compareTo(visibility) > 0)\n\t\tfiltered.add(doc);\n\t}\n\treturn filtered;\n }",
"public 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 }",
"public List<IssueCategory> getIssueCategories()\n {\n return this.issueCategories.values().stream()\n .sorted((category1, category2) -> category1.getPriority() - category2.getPriority())\n .collect(Collectors.toList());\n }",
"private ImmutableList<Element> getNodeListForTagElement(Document dom,\n\t\t\tCrawlElement crawlElement,\n\t\t\tEventableConditionChecker eventableConditionChecker) {\n\n\t\tBuilder<Element> result = ImmutableList.builder();\n\n\t\tif (crawlElement.getTagName() == null) {\n\t\t\treturn result.build();\n\t\t}\n\n\t\tEventableCondition eventableCondition =\n\t\t\t\teventableConditionChecker.getEventableCondition(crawlElement.getId());\n\t\t// TODO Stefan; this part of the code should be re-factored, Hack-ed it this way to prevent\n\t\t// performance problems.\n\t\tImmutableList<String> expressions = getFullXpathForGivenXpath(dom, eventableCondition);\n\n\t\tNodeList nodeList = dom.getElementsByTagName(crawlElement.getTagName());\n\n\t\tfor (int k = 0; k < nodeList.getLength(); k++) {\n\n\t\t\tElement element = (Element) nodeList.item(k);\n\t\t\tboolean matchesXpath =\n\t\t\t\t\telementMatchesXpath(eventableConditionChecker, eventableCondition,\n\t\t\t\t\t\t\texpressions, element);\n\t\t\tLOG.debug(\"Element {} matches Xpath={}\", DomUtils.getElementString(element),\n\t\t\t\t\tmatchesXpath);\n\t\t\t/*\n\t\t\t * TODO Stefan This is a possible Thread-Interleaving problem, as / isChecked can return\n\t\t\t * false and when needed to add it can return true. / check if element is a candidate\n\t\t\t */\n\t\t\tString id = element.getNodeName() + \": \" + DomUtils.getAllElementAttributes(element);\n\t\t\tif (matchesXpath && !checkedElements.isChecked(id)\n\t\t\t\t\t&& !isExcluded(dom, element, eventableConditionChecker)) {\n\t\t\t\taddElement(element, result, crawlElement);\n\t\t\t} else {\n\t\t\t\tLOG.debug(\"Element {} was not added\", element);\n\t\t\t}\n\t\t}\n\t\treturn result.build();\n\t}"
] |
Read remarks from a Gantt Designer file.
@param gantt Gantt Designer file | [
"private void processRemarks(Gantt gantt)\n {\n processRemarks(gantt.getRemarks());\n processRemarks(gantt.getRemarks1());\n processRemarks(gantt.getRemarks2());\n processRemarks(gantt.getRemarks3());\n processRemarks(gantt.getRemarks4());\n }"
] | [
"public void copyTo(ColumnBuffer dest, LongPredicate timestampTest) {\n dest.clear();\n\n if (key != null) {\n dest.key = new Key(key);\n }\n\n for (int i = 0; i < timeStamps.size(); i++) {\n long time = timeStamps.get(i);\n if (timestampTest.test(time)) {\n dest.add(time, values.get(i));\n }\n }\n }",
"private void processSubProjects()\n {\n int subprojectIndex = 1;\n for (Task task : m_project.getTasks())\n {\n String subProjectFileName = task.getSubprojectName();\n if (subProjectFileName != null)\n {\n String fileName = subProjectFileName;\n int offset = 0x01000000 + (subprojectIndex * 0x00400000);\n int index = subProjectFileName.lastIndexOf('\\\\');\n if (index != -1)\n {\n fileName = subProjectFileName.substring(index + 1);\n }\n\n SubProject sp = new SubProject();\n sp.setFileName(fileName);\n sp.setFullPath(subProjectFileName);\n sp.setUniqueIDOffset(Integer.valueOf(offset));\n sp.setTaskUniqueID(task.getUniqueID());\n task.setSubProject(sp);\n\n ++subprojectIndex;\n }\n }\n }",
"protected CmsProject createAndSetModuleImportProject(CmsObject cms, CmsModule module) throws CmsException {\n\n CmsProject importProject = cms.createProject(\n org.opencms.module.Messages.get().getBundle(cms.getRequestContext().getLocale()).key(\n org.opencms.module.Messages.GUI_IMPORT_MODULE_PROJECT_NAME_1,\n new Object[] {module.getName()}),\n org.opencms.module.Messages.get().getBundle(cms.getRequestContext().getLocale()).key(\n org.opencms.module.Messages.GUI_IMPORT_MODULE_PROJECT_DESC_1,\n new Object[] {module.getName()}),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n CmsProject.PROJECT_TYPE_TEMPORARY);\n cms.getRequestContext().setCurrentProject(importProject);\n cms.copyResourceToProject(\"/\");\n return importProject;\n }",
"@Nullable\n\tpublic Import find(@Nonnull final String typeName) {\n\t\tCheck.notEmpty(typeName, \"typeName\");\n\t\tImport ret = null;\n\t\tfinal Type type = new Type(typeName);\n\t\tfor (final Import imp : imports) {\n\t\t\tif (imp.getType().getName().equals(type.getName())) {\n\t\t\t\tret = imp;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (ret == null) {\n\t\t\tfinal Type javaLangType = Type.evaluateJavaLangType(typeName);\n\t\t\tif (javaLangType != null) {\n\t\t\t\tret = Import.of(javaLangType);\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}",
"public static Map<String, List<String>> getConsumersPerTopic(ZkClient zkClient, String group) {\n ZkGroupDirs dirs = new ZkGroupDirs(group);\n List<String> consumers = getChildrenParentMayNotExist(zkClient, dirs.consumerRegistryDir);\n //\n Map<String, List<String>> consumersPerTopicMap = new HashMap<String, List<String>>();\n for (String consumer : consumers) {\n TopicCount topicCount = getTopicCount(zkClient, group, consumer);\n for (Map.Entry<String, Set<String>> e : topicCount.getConsumerThreadIdsPerTopic().entrySet()) {\n final String topic = e.getKey();\n for (String consumerThreadId : e.getValue()) {\n List<String> list = consumersPerTopicMap.get(topic);\n if (list == null) {\n list = new ArrayList<String>();\n consumersPerTopicMap.put(topic, list);\n }\n //\n list.add(consumerThreadId);\n }\n }\n }\n //\n for (Map.Entry<String, List<String>> e : consumersPerTopicMap.entrySet()) {\n Collections.sort(e.getValue());\n }\n return consumersPerTopicMap;\n }",
"public String getBaselineDurationText(int baselineNumber)\n {\n Object result = getCachedValue(selectField(TaskFieldLists.BASELINE_DURATIONS, baselineNumber));\n if (result == null)\n {\n result = getCachedValue(selectField(TaskFieldLists.BASELINE_ESTIMATED_DURATIONS, baselineNumber));\n }\n\n if (!(result instanceof String))\n {\n result = null;\n }\n return (String) result;\n }",
"public static void generateJavaFiles(String requirementsFolder,\n String platformName, String src_test_dir, String tests_package,\n String casemanager_package, String loggingPropFile)\n throws Exception {\n\n File reqFolder = new File(requirementsFolder);\n if (reqFolder.isDirectory()) {\n for (File f : reqFolder.listFiles()) {\n if (f.getName().endsWith(\".story\")) {\n try {\n SystemReader.generateJavaFilesForOneStory(\n f.getCanonicalPath(), platformName,\n src_test_dir, tests_package,\n casemanager_package, loggingPropFile);\n } catch (IOException e) {\n String message = \"ERROR: \" + e.getMessage();\n logger.severe(message);\n throw new BeastException(message, e);\n }\n }\n }\n for (File f : reqFolder.listFiles()) {\n if (f.isDirectory()) {\n SystemReader.generateJavaFiles(requirementsFolder\n + File.separator + f.getName(), platformName,\n src_test_dir, tests_package + \".\" + f.getName(),\n casemanager_package, loggingPropFile);\n }\n }\n } else if (reqFolder.getName().endsWith(\".story\")) {\n SystemReader.generateJavaFilesForOneStory(requirementsFolder,\n platformName, src_test_dir, tests_package,\n casemanager_package, loggingPropFile);\n } else {\n String message = \"No story file found in \" + requirementsFolder;\n logger.severe(message);\n throw new BeastException(message);\n }\n\n }",
"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 }",
"public static autoscaleaction[] get(nitro_service service) throws Exception{\n\t\tautoscaleaction obj = new autoscaleaction();\n\t\tautoscaleaction[] response = (autoscaleaction[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Sets the position vector of the keyframe. | [
"public void setValue(Vector3f pos) {\n mX = pos.x;\n mY = pos.y;\n mZ = pos.z;\n }"
] | [
"@Override\n public Symmetry010Date date(int prolepticYear, int month, int dayOfMonth) {\n return Symmetry010Date.of(prolepticYear, month, dayOfMonth);\n }",
"public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection(String enterpriseId, String clientId,\n String clientSecret, JWTEncryptionPreferences encryptionPref, IAccessTokenCache accessTokenCache) {\n\n BoxDeveloperEditionAPIConnection connection = new BoxDeveloperEditionAPIConnection(enterpriseId,\n DeveloperEditionEntityType.ENTERPRISE, clientId, clientSecret, encryptionPref, accessTokenCache);\n\n connection.tryRestoreUsingAccessTokenCache();\n\n return connection;\n }",
"private void processCalendars() throws SQLException\n {\n for (ResultSetRow row : getRows(\"SELECT * FROM MSP_CALENDARS WHERE PROJ_ID=?\", m_projectID))\n {\n processCalendar(row);\n }\n\n updateBaseCalendarNames();\n\n processCalendarData(m_project.getCalendars());\n }",
"private boolean pathMatches(Path path, SquigglyContext context) {\n List<SquigglyNode> nodes = context.getNodes();\n Set<String> viewStack = null;\n SquigglyNode viewNode = null;\n\n int pathSize = path.getElements().size();\n int lastIdx = pathSize - 1;\n\n for (int i = 0; i < pathSize; i++) {\n PathElement element = path.getElements().get(i);\n\n if (viewNode != null && !viewNode.isSquiggly()) {\n Class beanClass = element.getBeanClass();\n\n if (beanClass != null && !Map.class.isAssignableFrom(beanClass)) {\n Set<String> propertyNames = getPropertyNamesFromViewStack(element, viewStack);\n\n if (!propertyNames.contains(element.getName())) {\n return false;\n }\n }\n\n } else if (nodes.isEmpty()) {\n return false;\n } else {\n\n SquigglyNode match = findBestSimpleNode(element, nodes);\n\n if (match == null) {\n match = findBestViewNode(element, nodes);\n\n if (match != null) {\n viewNode = match;\n viewStack = addToViewStack(viewStack, viewNode);\n }\n } else if (match.isAnyShallow()) {\n viewNode = match;\n } else if (match.isAnyDeep()) {\n return true;\n }\n\n if (match == null) {\n if (isJsonUnwrapped(element)) {\n continue;\n }\n\n return false;\n }\n\n if (match.isNegated()) {\n return false;\n }\n\n nodes = match.getChildren();\n\n if (i < lastIdx && nodes.isEmpty() && !match.isEmptyNested() && SquigglyConfig.isFilterImplicitlyIncludeBaseFields()) {\n nodes = BASE_VIEW_NODES;\n }\n }\n }\n\n return true;\n }",
"private static boolean isWideningPrimitive(Class<?> argumentClass, Class<?> targetClass) {\n return WIDENING_TABLE.containsKey(argumentClass) && WIDENING_TABLE.get(argumentClass).contains(targetClass);\n }",
"public void send(ProducerPoolData<V> ppd) {\n if (logger.isDebugEnabled()) {\n logger.debug(\"send message: \" + ppd);\n }\n if (sync) {\n Message[] messages = new Message[ppd.data.size()];\n int index = 0;\n for (V v : ppd.data) {\n messages[index] = serializer.toMessage(v);\n index++;\n }\n ByteBufferMessageSet bbms = new ByteBufferMessageSet(config.getCompressionCodec(), messages);\n ProducerRequest request = new ProducerRequest(ppd.topic, ppd.partition.partId, bbms);\n SyncProducer producer = syncProducers.get(ppd.partition.brokerId);\n if (producer == null) {\n throw new UnavailableProducerException(\"Producer pool has not been initialized correctly. \" + \"Sync Producer for broker \"\n + ppd.partition.brokerId + \" does not exist in the pool\");\n }\n producer.send(request.topic, request.partition, request.messages);\n } else {\n AsyncProducer<V> asyncProducer = asyncProducers.get(ppd.partition.brokerId);\n for (V v : ppd.data) {\n asyncProducer.send(ppd.topic, v, ppd.partition.partId);\n }\n }\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 }",
"private void processFields(Map<FieldType, String> map, Row row, FieldContainer container)\n {\n for (Map.Entry<FieldType, String> entry : map.entrySet())\n {\n FieldType field = entry.getKey();\n String name = entry.getValue();\n\n Object value;\n switch (field.getDataType())\n {\n case INTEGER:\n {\n value = row.getInteger(name);\n break;\n }\n\n case BOOLEAN:\n {\n value = Boolean.valueOf(row.getBoolean(name));\n break;\n }\n\n case DATE:\n {\n value = row.getDate(name);\n break;\n }\n\n case CURRENCY:\n case NUMERIC:\n case PERCENTAGE:\n {\n value = row.getDouble(name);\n break;\n }\n\n case DELAY:\n case WORK:\n case DURATION:\n {\n value = row.getDuration(name);\n break;\n }\n\n case RESOURCE_TYPE:\n {\n value = RESOURCE_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case TASK_TYPE:\n {\n value = TASK_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case CONSTRAINT:\n {\n value = CONSTRAINT_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case PRIORITY:\n {\n value = PRIORITY_MAP.get(row.getString(name));\n break;\n }\n\n case GUID:\n {\n value = row.getUUID(name);\n break;\n }\n\n default:\n {\n value = row.getString(name);\n break;\n }\n }\n\n container.set(field, value);\n }\n }",
"private void stream(InputStream is, File destFile) throws IOException {\n try {\n startProgress();\n OutputStream os = new FileOutputStream(destFile);\n \n boolean finished = false;\n try {\n byte[] buf = new byte[1024 * 10];\n int read;\n while ((read = is.read(buf)) >= 0) {\n os.write(buf, 0, read);\n processedBytes += read;\n logProgress();\n }\n \n os.flush();\n finished = true;\n } finally {\n os.close();\n if (!finished) {\n destFile.delete();\n }\n }\n } finally {\n is.close();\n completeProgress();\n }\n }"
] |
Reports that a node is faulted.
@param faulted the node faulted
@param throwable the reason for fault | [
"public void reportError(NodeT faulted, Throwable throwable) {\n faulted.setPreparer(true);\n String dependency = faulted.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.onFaultedResolution(dependency, throwable);\n if (dependent.hasAllResolved()) {\n queue.add(dependent.key());\n }\n } finally {\n dependent.lock().unlock();\n }\n }\n }"
] | [
"public static vrid_nsip6_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tvrid_nsip6_binding obj = new vrid_nsip6_binding();\n\t\tobj.set_id(id);\n\t\tvrid_nsip6_binding response[] = (vrid_nsip6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"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 static MediaType text( String subType, Charset charset ) {\n return nonBinary( TEXT, subType, charset );\n }",
"public static base_response unlink(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey unlinkresource = new sslcertkey();\n\t\tunlinkresource.certkey = resource.certkey;\n\t\treturn unlinkresource.perform_operation(client,\"unlink\");\n\t}",
"@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 boolean evaluate(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)\n {\n boolean result = true;\n if (m_criteria != null)\n {\n result = m_criteria.evaluate(container, promptValues);\n\n //\n // If this row has failed, but it is a summary row, and we are\n // including related summary rows, then we need to recursively test\n // its children\n //\n if (!result && m_showRelatedSummaryRows && container instanceof Task)\n {\n for (Task task : ((Task) container).getChildTasks())\n {\n if (evaluate(task, promptValues))\n {\n result = true;\n break;\n }\n }\n }\n }\n\n return (result);\n }",
"public static void setQuota(final GreenMailUser user, final Quota quota) {\r\n Session session = GreenMailUtil.getSession(ServerSetupTest.IMAP);\r\n try {\r\n Store store = session.getStore(\"imap\");\r\n store.connect(user.getEmail(), user.getPassword());\r\n try {\r\n ((QuotaAwareStore) store).setQuota(quota);\r\n } finally {\r\n store.close();\r\n }\r\n } catch (Exception ex) {\r\n throw new IllegalStateException(\"Can not set quota \" + quota\r\n + \" for user \" + user, ex);\r\n }\r\n }",
"private Double getDuration(Duration duration)\n {\n Double result;\n if (duration == null)\n {\n result = null;\n }\n else\n {\n if (duration.getUnits() != TimeUnit.HOURS)\n {\n duration = duration.convertUnits(TimeUnit.HOURS, m_projectFile.getProjectProperties());\n }\n\n result = Double.valueOf(duration.getDuration());\n }\n return result;\n }",
"private void processTasks() throws IOException\n {\n TaskReader reader = new TaskReader(m_data.getTableData(\"Tasks\"));\n reader.read();\n for (MapRow row : reader.getRows())\n {\n processTask(m_project, row);\n }\n updateDates();\n }"
] |
The location for this elevation.
@return | [
"public LatLong getLocation() {\n if (location == null) {\n location = new LatLong((JSObject) (getJSObject().getMember(\"location\")));\n }\n return location;\n }"
] | [
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<BritishCutoverDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<BritishCutoverDate>) super.localDateTime(temporal);\n }",
"static void export(String path, String queueName, DbConn cnx) throws JqmXmlException\n {\n // Argument tests\n if (queueName == null)\n {\n throw new IllegalArgumentException(\"queue name cannot be null\");\n }\n if (cnx == null)\n {\n throw new IllegalArgumentException(\"database connection cannot be null\");\n }\n Queue q = CommonXml.findQueue(queueName, cnx);\n if (q == null)\n {\n throw new IllegalArgumentException(\"there is no queue named \" + queueName);\n }\n\n List<Queue> l = new ArrayList<>();\n l.add(q);\n export(path, l, cnx);\n }",
"public EventBus emit(Enum<?> event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }",
"@ViewChanged\n\tpublic synchronized void onViewChangeEvent(ViewChangedEvent event) {\n\t\t\n\t\tif (logger.isDebugEnabled()) {\n\t\t\tlogger.debug(\"onViewChangeEvent : pre[\" + event.isPre() + \"] : event local address[\" + event.getCache().getLocalAddress() + \"]\");\n\t\t}\n\t\t\n\t\tfinal List<Address> oldView = currentView;\n\t\tcurrentView = new ArrayList<Address>(event.getNewView().getMembers());\n\t\tfinal Address localAddress = getLocalAddress();\n\t\t\n\t\t//just a precaution, it can be null!\n\t\tif (oldView != null) {\n\t\t\tfinal Cache jbossCache = mobicentsCache.getJBossCache();\n\t\t\tfinal Configuration config = jbossCache.getConfiguration();\t\t\n\n\t\t\tfinal boolean isBuddyReplicationEnabled = config.getBuddyReplicationConfig() != null && config.getBuddyReplicationConfig().isEnabled();\n\t\t\t// recover stuff from lost members\n\t\t\tRunnable runnable = new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tfor (Address oldMember : oldView) {\n\t\t\t\t\t\tif (!currentView.contains(oldMember)) {\n\t\t\t\t\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\t\t\t\t\tlogger.debug(\"onViewChangeEvent : processing lost member \" + oldMember);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfor (FailOverListener localListener : failOverListeners) {\n\t\t\t\t\t\t\t\tClientLocalListenerElector localListenerElector = localListener.getElector();\n\t\t\t\t\t\t\t\tif (localListenerElector != null && !isBuddyReplicationEnabled) {\n\t\t\t\t\t\t\t\t\t// going to use the local listener elector instead, which gives results based on data\n\t\t\t\t\t\t\t\t\tperformTakeOver(localListener,oldMember,localAddress, true, isBuddyReplicationEnabled);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tList<Address> electionView = getElectionView(oldMember);\n\t\t\t\t\t\t\t\t\tif(electionView!=null && elector.elect(electionView).equals(localAddress))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tperformTakeOver(localListener, oldMember, localAddress, false, isBuddyReplicationEnabled);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tcleanAfterTakeOver(localListener, oldMember);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tThread t = new Thread(runnable);\n\t\t\tt.start();\n\t\t}\n\t\t\n\t}",
"private static int determineBatchSize(boolean canGridDialectDoMultiget, int classBatchSize, int configuredDefaultBatchSize) {\n\t\t// if the dialect does not support it, don't batch so that we can avoid skewing the ORM fetch statistics\n\t\tif ( !canGridDialectDoMultiget ) {\n\t\t\treturn -1;\n\t\t}\n\t\telse if ( classBatchSize != -1 ) {\n\t\t\treturn classBatchSize;\n\t\t}\n\t\telse if ( configuredDefaultBatchSize != -1 ) {\n\t\t\treturn configuredDefaultBatchSize;\n\t\t}\n\t\telse {\n\t\t\treturn DEFAULT_MULTIGET_BATCH_SIZE;\n\t\t}\n\t}",
"public static base_responses add(nitro_service client, vlan resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tvlan addresources[] = new vlan[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new vlan();\n\t\t\t\taddresources[i].id = resources[i].id;\n\t\t\t\taddresources[i].aliasname = resources[i].aliasname;\n\t\t\t\taddresources[i].ipv6dynamicrouting = resources[i].ipv6dynamicrouting;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"private boolean initCheckTypeModifiers() {\n\n Class<?> classInfoclass = Reflections.loadClass(CLASSINFO_CLASS_NAME, new ClassLoaderResourceLoader(classFileServices.getClass().getClassLoader()));\n if (classInfoclass != null) {\n try {\n Method setFlags = AccessController.doPrivileged(GetDeclaredMethodAction.of(classInfoclass, \"setFlags\", short.class));\n return setFlags != null;\n } catch (Exception exceptionIgnored) {\n BootstrapLogger.LOG.usingOldJandexVersion();\n return false;\n }\n } else {\n return true;\n }\n }",
"public ByteBuffer payload() {\n ByteBuffer payload = buffer.duplicate();\n payload.position(headerSize(magic()));\n payload = payload.slice();\n payload.limit(payloadSize());\n payload.rewind();\n return payload;\n }",
"public int update(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\ttry {\n\t\t\t// there is always and id field as an argument so just return 0 lines updated\n\t\t\tif (argFieldTypes.length <= 1) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tObject[] args = getFieldObjects(data);\n\t\t\tObject newVersion = null;\n\t\t\tif (versionFieldType != null) {\n\t\t\t\tnewVersion = versionFieldType.extractJavaFieldValue(data);\n\t\t\t\tnewVersion = versionFieldType.moveToNextValue(newVersion);\n\t\t\t\targs[versionFieldTypeIndex] = versionFieldType.convertJavaFieldToSqlArgValue(newVersion);\n\t\t\t}\n\t\t\tint rowC = databaseConnection.update(statement, args, argFieldTypes);\n\t\t\tif (rowC > 0) {\n\t\t\t\tif (newVersion != null) {\n\t\t\t\t\t// if we have updated a row then update the version field in our object to the new value\n\t\t\t\t\tversionFieldType.assignField(connectionSource, data, newVersion, false, null);\n\t\t\t\t}\n\t\t\t\tif (objectCache != null) {\n\t\t\t\t\t// if we've changed something then see if we need to update our cache\n\t\t\t\t\tObject id = idField.extractJavaFieldValue(data);\n\t\t\t\t\tT cachedData = objectCache.get(clazz, id);\n\t\t\t\t\tif (cachedData != null && cachedData != data) {\n\t\t\t\t\t\t// copy each field from the updated data into the cached object\n\t\t\t\t\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\t\t\t\t\tif (fieldType != idField) {\n\t\t\t\t\t\t\t\tfieldType.assignField(connectionSource, cachedData,\n\t\t\t\t\t\t\t\t\t\tfieldType.extractJavaFieldValue(data), false, objectCache);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tlogger.debug(\"update data with statement '{}' and {} args, changed {} rows\", statement, args.length, rowC);\n\t\t\tif (args.length > 0) {\n\t\t\t\t// need to do the (Object) cast to force args to be a single object\n\t\t\t\tlogger.trace(\"update arguments: {}\", (Object) args);\n\t\t\t}\n\t\t\treturn rowC;\n\t\t} catch (SQLException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Unable to run update stmt on object \" + data + \": \" + statement, e);\n\t\t}\n\t}"
] |
Init after constructor | [
"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 }"
] | [
"static String replaceCheckDigit(final String iban, final String checkDigit) {\n return getCountryCode(iban) + checkDigit + getBban(iban);\n }",
"protected void initializeJdbcConnection(Connection con, JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n try\r\n {\r\n PlatformFactory.getPlatformFor(jcd).initializeJdbcConnection(jcd, con);\r\n }\r\n catch (PlatformException e)\r\n {\r\n throw new LookupException(\"Platform dependent initialization of connection failed\", e);\r\n }\r\n }",
"void rejectAttributes(RejectedAttributesLogContext rejectedAttributes, ModelNode attributeValue) {\n for (RejectAttributeChecker checker : checks) {\n rejectedAttributes.checkAttribute(checker, name, attributeValue);\n }\n }",
"public static boolean intersectsPointWithRectF(RectF _Rect, float _X, float _Y) {\n return _X > _Rect.left && _X < _Rect.right && _Y > _Rect.top && _Y < _Rect.bottom;\n }",
"private Iterable<PersistentNoSqlIdentifierGenerator> getPersistentGenerators() {\n\t\tMap<String, EntityPersister> entityPersisters = factory.getMetamodel().entityPersisters();\n\n\t\tSet<PersistentNoSqlIdentifierGenerator> persistentGenerators = new HashSet<PersistentNoSqlIdentifierGenerator>( entityPersisters.size() );\n\t\tfor ( EntityPersister persister : entityPersisters.values() ) {\n\t\t\tif ( persister.getIdentifierGenerator() instanceof PersistentNoSqlIdentifierGenerator ) {\n\t\t\t\tpersistentGenerators.add( (PersistentNoSqlIdentifierGenerator) persister.getIdentifierGenerator() );\n\t\t\t}\n\t\t}\n\n\t\treturn persistentGenerators;\n\t}",
"protected void parseOperationsL(TokenList tokens, Sequence sequence) {\n\n if( tokens.size == 0 )\n return;\n\n TokenList.Token token = tokens.first;\n\n if( token.getType() != Type.VARIABLE )\n throw new ParseError(\"The first token in an equation needs to be a variable and not \"+token);\n\n while( token != null ) {\n if( token.getType() == Type.FUNCTION ) {\n throw new ParseError(\"Function encountered with no parentheses\");\n } else if( token.getType() == Type.SYMBOL && token.getSymbol() == Symbol.TRANSPOSE) {\n if( token.previous.getType() == Type.VARIABLE )\n token = insertTranspose(token.previous,tokens,sequence);\n else\n throw new ParseError(\"Expected variable before transpose\");\n }\n token = token.next;\n }\n }",
"public void start() {\n instanceLock.writeLock().lock();\n try {\n for (final Map.Entry<MongoNamespace, NamespaceChangeStreamListener> streamerEntry :\n nsStreamers.entrySet()) {\n streamerEntry.getValue().start();\n }\n } finally {\n instanceLock.writeLock().unlock();\n }\n }",
"public static HorizontalBandAlignment buildAligment(byte aligment){\n\t\tif (aligment == RIGHT.getAlignment())\n\t\t\treturn RIGHT;\n\t\telse if (aligment == LEFT.getAlignment())\n\t\t\treturn LEFT;\n\t\telse if (aligment == CENTER.getAlignment())\n\t\t\treturn CENTER;\n\n\t\treturn LEFT;\n\t}",
"public void strokeRoundRectangle(Rectangle rect, Color color, float linewidth, float r) {\n\t\ttemplate.saveState();\n\t\tsetStroke(color, linewidth, null);\n\t\ttemplate.roundRectangle(origX + rect.getLeft(), origY + rect.getBottom(), rect.getWidth(), rect.getHeight(), r);\n\t\ttemplate.stroke();\n\t\ttemplate.restoreState();\n\t}"
] |
Returns the value of this product under the given model.
@param evaluationTime Evaluation time.
@param model The model.
@return Value of this product und the given model. | [
"public double getValueAsPrice(double evaluationTime, AnalyticModel model) {\n\t\tForwardCurve\tforwardCurve\t= model.getForwardCurve(forwardCurveName);\n\t\tDiscountCurve\tdiscountCurve\t= model.getDiscountCurve(discountCurveName);\n\n\t\tDiscountCurve\tdiscountCurveForForward = null;\n\t\tif(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {\n\t\t\t// User might like to get forward from discount curve.\n\t\t\tdiscountCurveForForward\t= model.getDiscountCurve(forwardCurveName);\n\n\t\t\tif(discountCurveForForward == null) {\n\t\t\t\t// User specified a name for the forward curve, but no curve was found.\n\t\t\t\tthrow new IllegalArgumentException(\"No curve of the name \" + forwardCurveName + \" was found in the model.\");\n\t\t\t}\n\t\t}\n\n\t\tdouble value = 0.0;\n\t\tfor(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) {\n\t\t\tdouble fixingDate\t= schedule.getFixing(periodIndex);\n\t\t\tdouble paymentDate\t= schedule.getPayment(periodIndex);\n\t\t\tdouble periodLength\t= schedule.getPeriodLength(periodIndex);\n\n\t\t\t/*\n\t\t\t * We do not count empty periods.\n\t\t\t * Since empty periods are an indication for a ill-specified product,\n\t\t\t * it might be reasonable to throw an illegal argument exception instead.\n\t\t\t */\n\t\t\tif(periodLength == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tdouble forward = 0.0;\n\t\t\tif(forwardCurve != null) {\n\t\t\t\tforward\t\t\t+= forwardCurve.getForward(model, fixingDate, paymentDate-fixingDate);\n\t\t\t}\n\t\t\telse if(discountCurveForForward != null) {\n\t\t\t\t/*\n\t\t\t\t * Classical single curve case: using a discount curve as a forward curve.\n\t\t\t\t * This is only implemented for demonstration purposes (an exception would also be appropriate :-)\n\t\t\t\t */\n\t\t\t\tif(fixingDate != paymentDate) {\n\t\t\t\t\tforward\t\t\t+= (discountCurveForForward.getDiscountFactor(fixingDate) / discountCurveForForward.getDiscountFactor(paymentDate) - 1.0) / (paymentDate-fixingDate);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdouble discountFactor\t= paymentDate > evaluationTime ? discountCurve.getDiscountFactor(model, paymentDate) : 0.0;\n\t\t\tdouble payoffUnit = discountFactor * periodLength;\n\n\t\t\tdouble effektiveStrike = strike;\n\t\t\tif(isStrikeMoneyness) {\n\t\t\t\teffektiveStrike += getATMForward(model, true);\n\t\t\t}\n\n\t\t\tVolatilitySurface volatilitySurface\t= model.getVolatilitySurface(volatiltiySufaceName);\n\t\t\tif(volatilitySurface == null) {\n\t\t\t\tthrow new IllegalArgumentException(\"Volatility surface not found in model: \" + volatiltiySufaceName);\n\t\t\t}\n\t\t\tif(volatilitySurface.getQuotingConvention() == QuotingConvention.VOLATILITYLOGNORMAL) {\n\t\t\t\tdouble volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYLOGNORMAL);\n\t\t\t\tvalue += AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Default to normal volatility as quoting convention\n\t\t\t\tdouble volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYNORMAL);\n\t\t\t\tvalue += AnalyticFormulas.bachelierOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit);\n\t\t\t}\n\t\t}\n\n\t\treturn value / discountCurve.getDiscountFactor(model, evaluationTime);\n\t}"
] | [
"public Set<Method> findAnnotatedMethods(String scanBase, Class<? extends Annotation> annotationClass) {\n Set<BeanDefinition> filteredComponents = findCandidateBeans(scanBase, annotationClass);\n return extractAnnotatedMethods(filteredComponents, annotationClass);\n }",
"public void check(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureColumn(fieldDef, checkLevel);\r\n ensureJdbcType(fieldDef, checkLevel);\r\n ensureConversion(fieldDef, checkLevel);\r\n ensureLength(fieldDef, checkLevel);\r\n ensurePrecisionAndScale(fieldDef, checkLevel);\r\n checkLocking(fieldDef, checkLevel);\r\n checkSequenceName(fieldDef, checkLevel);\r\n checkId(fieldDef, checkLevel);\r\n if (fieldDef.isAnonymous())\r\n {\r\n checkAnonymous(fieldDef, checkLevel);\r\n }\r\n else\r\n {\r\n checkReadonlyAccessForNativePKs(fieldDef, checkLevel);\r\n }\r\n }",
"public static base_response add(nitro_service client, inat resource) throws Exception {\n\t\tinat addresource = new inat();\n\t\taddresource.name = resource.name;\n\t\taddresource.publicip = resource.publicip;\n\t\taddresource.privateip = resource.privateip;\n\t\taddresource.tcpproxy = resource.tcpproxy;\n\t\taddresource.ftp = resource.ftp;\n\t\taddresource.tftp = resource.tftp;\n\t\taddresource.usip = resource.usip;\n\t\taddresource.usnip = resource.usnip;\n\t\taddresource.proxyip = resource.proxyip;\n\t\taddresource.mode = resource.mode;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}",
"private void tryToSetParsedValue(String value) throws Exception {\n\n JSONObject json = JSONParser.parseStrict(value).isObject();\n JSONValue val = json.get(JsonKey.START);\n setStart(readOptionalDate(val));\n val = json.get(JsonKey.END);\n setEnd(readOptionalDate(val));\n setWholeDay(readOptionalBoolean(json.get(JsonKey.WHOLE_DAY)));\n JSONObject patternJson = json.get(JsonKey.PATTERN).isObject();\n readPattern(patternJson);\n setExceptions(readDates(json.get(JsonKey.EXCEPTIONS)));\n setSeriesEndDate(readOptionalDate(json.get(JsonKey.SERIES_ENDDATE)));\n setOccurrences(readOptionalInt(json.get(JsonKey.SERIES_OCCURRENCES)));\n setDerivedEndType();\n setCurrentTillEnd(readOptionalBoolean(json.get(JsonKey.CURRENT_TILL_END)));\n setParentSeriesId(readOptionalUUID(json.get(JsonKey.PARENT_SERIES)));\n\n }",
"private void allRelation(Options opt, RelationType rt, ClassDoc from) {\n\tString tagname = rt.lower;\n\tfor (Tag tag : from.tags(tagname)) {\n\t String t[] = tokenize(tag.text()); // l-src label l-dst target\n\t t = t.length == 1 ? new String[] { \"-\", \"-\", \"-\", t[0] } : t; // Shorthand\n\t if (t.length != 4) {\n\t\tSystem.err.println(\"Error in \" + from + \"\\n\" + tagname + \" expects four fields (l-src label l-dst target): \" + tag.text());\n\t\treturn;\n\t }\n\t ClassDoc to = from.findClass(t[3]);\n\t if (to != null) {\n\t\tif(hidden(to))\n\t\t continue;\n\t\trelation(opt, rt, from, to, t[0], t[1], t[2]);\n\t } else {\n\t\tif(hidden(t[3]))\n\t\t continue;\n\t\trelation(opt, rt, from, from.toString(), to, t[3], t[0], t[1], t[2]);\n\t }\n\t}\n }",
"private void clearMetadata(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(hotCache.keySet())) {\n if (deck.player == player) {\n hotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverTrackMetadataUpdate(player, null); // Inform listeners the metadata is gone.\n }\n }\n }\n }",
"public String registerHandler(GFXEventHandler handler) {\n String uuid = UUID.randomUUID().toString();\n handlers.put(uuid, handler);\n return uuid;\n }",
"public void setColorSchemeResources(int... colorResIds) {\n final Resources res = getResources();\n int[] colorRes = new int[colorResIds.length];\n for (int i = 0; i < colorResIds.length; i++) {\n colorRes[i] = res.getColor(colorResIds[i]);\n }\n setColorSchemeColors(colorRes);\n }",
"public Request header(String key, String value) {\n this.headers.put(key, value);\n return this;\n }"
] |
If there is an unprocessed change event for a particular document ID, fetch it from the
change stream listener, and remove it. By reading the event here, we are assuming it will be
processed by the consumer.
@return the latest unprocessed change event for the given document ID, or null if none exists. | [
"public @Nullable ChangeEvent<BsonDocument> getUnprocessedEventForDocumentId(\n final BsonValue documentId\n ) {\n final ChangeEvent<BsonDocument> event;\n nsLock.readLock().lock();\n try {\n event = this.events.get(documentId);\n } finally {\n nsLock.readLock().unlock();\n }\n\n nsLock.writeLock().lock();\n try {\n this.events.remove(documentId);\n return event;\n } finally {\n nsLock.writeLock().unlock();\n }\n }"
] | [
"private void readBitFields(MppBitFlag[] flags, FieldContainer container, byte[] data)\n {\n for (MppBitFlag flag : flags)\n {\n flag.setValue(container, data);\n }\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}",
"private Boolean readOptionalBoolean(JSONObject json, String key) {\n\n try {\n return Boolean.valueOf(json.getBoolean(key));\n } catch (JSONException e) {\n LOG.debug(\"Reading optional JSON boolean failed. Default to provided default value.\", e);\n }\n return null;\n }",
"public static final Duration parseDuration(String value)\n {\n Duration result = null;\n if (value != null)\n {\n int split = value.indexOf(' ');\n if (split != -1)\n {\n double durationValue = Double.parseDouble(value.substring(0, split));\n TimeUnit durationUnits = parseTimeUnits(value.substring(split + 1));\n\n result = Duration.getInstance(durationValue, durationUnits);\n\n }\n }\n return result;\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 }",
"public static base_response disable(nitro_service client, nsacl6 resource) throws Exception {\n\t\tnsacl6 disableresource = new nsacl6();\n\t\tdisableresource.acl6name = resource.acl6name;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}",
"public void setWorkingDay(Day day, boolean working)\n {\n setWorkingDay(day, (working ? DayType.WORKING : DayType.NON_WORKING));\n }",
"public IGoal[] getAgentGoals(final String agent_name, Connector connector) {\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Plan>() {\n\n public IFuture<Plan> execute(IInternalAccess ia) {\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n\n goals = bia.getGoalbase().getGoals();\n return null;\n }\n }).get(new ThreadSuspendable());\n\n return goals;\n }",
"public boolean isBitwiseOrCompatibleWithRange(int maskValue, Integer segmentPrefixLength) throws PrefixLenException {\r\n\t\treturn super.isBitwiseOrCompatibleWithRange(maskValue, segmentPrefixLength, getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets());\r\n\t}"
] |
Checks the given reference descriptor.
@param refDef The reference descriptor
@param checkLevel The amount of checks to perform
@exception ConstraintException If a constraint has been violated | [
"public void check(ReferenceDescriptorDef refDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureClassRef(refDef, checkLevel);\r\n checkProxyPrefetchingLimit(refDef, checkLevel);\r\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 static void dumpClusterToFile(String outputDirName, String fileName, Cluster cluster) {\n\n if(outputDirName != null) {\n File outputDir = new File(outputDirName);\n if(!outputDir.exists()) {\n Utils.mkdirs(outputDir);\n }\n\n try {\n FileUtils.writeStringToFile(new File(outputDirName, fileName),\n new ClusterMapper().writeCluster(cluster));\n } catch(IOException e) {\n logger.error(\"IOException during dumpClusterToFile: \" + e);\n }\n }\n }",
"public int bindShader(GVRContext context, GVRShaderData material, String vertexDesc)\n {\n String signature = getClass().getSimpleName();\n GVRShaderManager shaderManager = context.getShaderManager();\n\n synchronized (shaderManager)\n {\n int nativeShader = shaderManager.getShader(signature);\n if (nativeShader == 0)\n {\n nativeShader = addShader(shaderManager, signature, material);\n }\n return nativeShader;\n }\n }",
"public void setVertexBuffer(GVRVertexBuffer vbuf)\n {\n if (vbuf == null)\n {\n throw new IllegalArgumentException(\"Vertex buffer cannot be null\");\n }\n mVertices = vbuf;\n NativeMesh.setVertexBuffer(getNative(), vbuf.getNative());\n }",
"public static base_responses delete(nitro_service client, String ciphergroupname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (ciphergroupname != null && ciphergroupname.length > 0) {\n\t\t\tsslcipher deleteresources[] = new sslcipher[ciphergroupname.length];\n\t\t\tfor (int i=0;i<ciphergroupname.length;i++){\n\t\t\t\tdeleteresources[i] = new sslcipher();\n\t\t\t\tdeleteresources[i].ciphergroupname = ciphergroupname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public CollectionRequest<Task> projects(String task) {\n \n String path = String.format(\"/tasks/%s/projects\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"static DefaultContainerDescription lookup(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadResourceOperation(new ModelNode().setEmptyList());\n op.get(ClientConstants.INCLUDE_RUNTIME).set(true);\n final ModelNode result = client.execute(op);\n if (Operations.isSuccessfulOutcome(result)) {\n final ModelNode model = Operations.readResult(result);\n final String productName = getValue(model, \"product-name\", \"WildFly\");\n final String productVersion = getValue(model, \"product-version\");\n final String releaseVersion = getValue(model, \"release-version\");\n final String launchType = getValue(model, \"launch-type\");\n return new DefaultContainerDescription(productName, productVersion, releaseVersion, launchType, \"DOMAIN\".equalsIgnoreCase(launchType));\n }\n throw new OperationExecutionException(op, result);\n }",
"public int size(final K1 firstKey) {\n\t\t// existence check on inner map\n\t\tfinal HashMap<K2, HashMap<K3, V>> innerMap = map.get(firstKey);\n\t\tif( innerMap == null ) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn innerMap.size();\n\t}",
"@Override\n public CopticDate date(int prolepticYear, int month, int dayOfMonth) {\n return CopticDate.of(prolepticYear, month, dayOfMonth);\n }"
] |
Function to perform backward softmax | [
"public static int cudnnSoftmaxBackward(\n cudnnHandle handle, \n int algo, \n int mode, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnSoftmaxBackwardNative(handle, algo, mode, alpha, yDesc, y, dyDesc, dy, beta, dxDesc, dx));\n }"
] | [
"public static final String getSelectedValue(ListBox list) {\n\tint index = list.getSelectedIndex();\n\treturn (index >= 0) ? list.getValue(index) : null;\n }",
"protected void getBatch(int batchSize){\r\n\r\n// if (numCalls == 0) {\r\n// for (int i = 0; i < 1538*\\15; i++) {\r\n// randGenerator.nextInt(this.dataDimension());\r\n// }\r\n// }\r\n// numCalls++;\r\n\r\n if (thisBatch == null || thisBatch.length != batchSize){\r\n thisBatch = new int[batchSize];\r\n }\r\n\r\n //-----------------------------\r\n //RANDOM WITH REPLACEMENT\r\n //-----------------------------\r\n if (sampleMethod.equals(SamplingMethod.RandomWithReplacement)){\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = randGenerator.nextInt(this.dataDimension()); //Just generate a random index\r\n// System.err.println(\"numCalls = \"+(numCalls++));\r\n }\r\n //-----------------------------\r\n //ORDERED\r\n //-----------------------------\r\n }else if(sampleMethod.equals(SamplingMethod.Ordered)){\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = (curElement + i) % this.dataDimension() ; //Take the next batchSize points in order\r\n }\r\n curElement = (curElement + batchSize) % this.dataDimension(); //watch out for overflow\r\n\r\n //-----------------------------\r\n //RANDOM WITHOUT REPLACEMENT\r\n //-----------------------------\r\n }else if(sampleMethod.equals(SamplingMethod.RandomWithoutReplacement)){\r\n //Declare the indices array if needed.\r\n if (allIndices == null || allIndices.size()!= this.dataDimension()){\r\n\r\n allIndices = new ArrayList<Integer>();\r\n for(int i=0;i<this.dataDimension();i++){\r\n allIndices.add(i);\r\n }\r\n Collections.shuffle(allIndices,randGenerator);\r\n }\r\n\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = allIndices.get((curElement + i) % allIndices.size()); //Grab the next batchSize indices\r\n }\r\n\r\n if (curElement + batchSize > this.dataDimension()){\r\n Collections.shuffle(Arrays.asList(allIndices),randGenerator); //Shuffle if we got to the end of the list\r\n }\r\n\r\n //watch out for overflow\r\n curElement = (curElement + batchSize) % allIndices.size(); //Rollover\r\n\r\n\r\n }else{\r\n System.err.println(\"NO SAMPLING METHOD SELECTED\");\r\n System.exit(1);\r\n }\r\n\r\n\r\n }",
"private void sendSyncControlCommand(DeviceUpdate target, byte command) throws IOException {\n ensureRunning();\n byte[] payload = new byte[SYNC_CONTROL_PAYLOAD.length];\n System.arraycopy(SYNC_CONTROL_PAYLOAD, 0, payload, 0, SYNC_CONTROL_PAYLOAD.length);\n payload[2] = getDeviceNumber();\n payload[8] = getDeviceNumber();\n payload[12] = command;\n assembleAndSendPacket(Util.PacketType.SYNC_CONTROL, payload, target.getAddress(), BeatFinder.BEAT_PORT);\n }",
"public static String getShortClassName(Object o) {\r\n String name = o.getClass().getName();\r\n int index = name.lastIndexOf('.');\r\n if (index >= 0) {\r\n name = name.substring(index + 1);\r\n }\r\n return name;\r\n }",
"protected static <K, T> void groupAnswer(final Map<K, List<T>> answer, T element, K value) {\n if (answer.containsKey(value)) {\n answer.get(value).add(element);\n } else {\n List<T> groupedElements = new ArrayList<T>();\n groupedElements.add(element);\n answer.put(value, groupedElements);\n }\n }",
"private FieldType addUserDefinedField(FieldTypeClass fieldType, UserFieldDataType dataType, String name)\n {\n FieldType field = null;\n \n try\n {\n switch (fieldType)\n {\n case TASK:\n {\n do\n {\n field = m_taskUdfCounters.nextField(TaskField.class, dataType);\n }\n while (RESERVED_TASK_FIELDS.contains(field));\n\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n\n break;\n }\n \n case RESOURCE:\n {\n field = m_resourceUdfCounters.nextField(ResourceField.class, dataType);\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n break;\n }\n \n case ASSIGNMENT:\n {\n field = m_assignmentUdfCounters.nextField(AssignmentField.class, dataType);\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n break;\n }\n \n default:\n {\n break;\n }\n } \n }\n\n catch (Exception ex)\n {\n //\n // SF#227: If we get an exception thrown here... it's likely that\n // we've run out of user defined fields, for example\n // there are only 30 TEXT fields. We'll ignore this: the user\n // defined field won't be mapped to an alias, so we'll\n // ignore it when we read in the values.\n //\n }\n \n return field;\n }",
"public void merge(GVRSkeleton newSkel)\n {\n int numBones = getNumBones();\n List<Integer> parentBoneIds = new ArrayList<Integer>(numBones + newSkel.getNumBones());\n List<String> newBoneNames = new ArrayList<String>(newSkel.getNumBones());\n List<Matrix4f> newMatrices = new ArrayList<Matrix4f>(newSkel.getNumBones());\n GVRPose oldBindPose = getBindPose();\n GVRPose curPose = getPose();\n\n for (int i = 0; i < numBones; ++i)\n {\n parentBoneIds.add(mParentBones[i]);\n }\n for (int j = 0; j < newSkel.getNumBones(); ++j)\n {\n String boneName = newSkel.getBoneName(j);\n int boneId = getBoneIndex(boneName);\n if (boneId < 0)\n {\n int parentId = newSkel.getParentBoneIndex(j);\n Matrix4f m = new Matrix4f();\n\n newSkel.getBindPose().getLocalMatrix(j, m);\n newMatrices.add(m);\n newBoneNames.add(boneName);\n if (parentId >= 0)\n {\n boneName = newSkel.getBoneName(parentId);\n parentId = getBoneIndex(boneName);\n }\n parentBoneIds.add(parentId);\n }\n }\n if (parentBoneIds.size() == numBones)\n {\n return;\n }\n int n = numBones + parentBoneIds.size();\n int[] parentIds = Arrays.copyOf(mParentBones, n);\n int[] boneOptions = Arrays.copyOf(mBoneOptions, n);\n String[] boneNames = Arrays.copyOf(mBoneNames, n);\n\n mBones = Arrays.copyOf(mBones, n);\n mPoseMatrices = new float[n * 16];\n for (int i = 0; i < parentBoneIds.size(); ++i)\n {\n n = numBones + i;\n parentIds[n] = parentBoneIds.get(i);\n boneNames[n] = newBoneNames.get(i);\n boneOptions[n] = BONE_ANIMATE;\n }\n mBoneOptions = boneOptions;\n mBoneNames = boneNames;\n mParentBones = parentIds;\n mPose = new GVRPose(this);\n mBindPose = new GVRPose(this);\n mBindPose.copy(oldBindPose);\n mPose.copy(curPose);\n mBindPose.sync();\n for (int j = 0; j < newSkel.getNumBones(); ++j)\n {\n mBindPose.setLocalMatrix(numBones + j, newMatrices.get(j));\n mPose.setLocalMatrix(numBones + j, newMatrices.get(j));\n }\n setBindPose(mBindPose);\n mPose.sync();\n updateBonePose();\n }",
"public <TYPE> TYPE get(String key, Class<TYPE> type) {\n\t\treturn cache.get(key, type);\n\t}",
"public void delete(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_DELETE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n // Note: This method requires an HTTP POST request.\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 // This method has no specific response - It returns an empty\r\n // sucess response if it completes without error.\r\n }"
] |
Round the size of a rectangle with double values.
@param rectangle The rectangle.
@return | [
"public static Dimension rectangleDoubleToDimension(final Rectangle2D.Double rectangle) {\n return new Dimension(\n (int) Math.round(rectangle.width),\n (int) Math.round(rectangle.height));\n }"
] | [
"public static void calculateLegendInformation(List<? extends BaseModel> _Models, float _StartX, float _EndX, Paint _Paint) {\n float textMargin = Utils.dpToPx(10.f);\n float lastX = _StartX;\n\n // calculate the legend label positions and check if there is enough space to display the label,\n // if not the label will not be shown\n for (BaseModel model : _Models) {\n if (!model.isIgnore()) {\n Rect textBounds = new Rect();\n RectF legendBounds = model.getLegendBounds();\n\n _Paint.getTextBounds(model.getLegendLabel(), 0, model.getLegendLabel().length(), textBounds);\n model.setTextBounds(textBounds);\n\n float centerX = legendBounds.centerX();\n float centeredTextPos = centerX - (textBounds.width() / 2);\n float textStartPos = centeredTextPos - textMargin;\n\n // check if the text is too big to fit on the screen\n if (centeredTextPos + textBounds.width() > _EndX - textMargin) {\n model.setShowLabel(false);\n } else {\n // check if the current legend label overrides the label before\n // if the label overrides the label before, the current label will not be shown.\n // If not the label will be shown and the label position is calculated\n if (textStartPos < lastX) {\n if (lastX + textMargin < legendBounds.left) {\n model.setLegendLabelPosition((int) (lastX + textMargin));\n model.setShowLabel(true);\n lastX = lastX + textMargin + textBounds.width();\n } else {\n model.setShowLabel(false);\n }\n } else {\n model.setShowLabel(true);\n model.setLegendLabelPosition((int) centeredTextPos);\n lastX = centerX + (textBounds.width() / 2);\n }\n }\n }\n }\n\n }",
"public void processCalendar(Row calendarRow, Map<Integer, Row> workPatternMap, Map<Integer, List<Row>> workPatternAssignmentMap, Map<Integer, List<Row>> exceptionAssignmentMap, Map<Integer, List<Row>> timeEntryMap, Map<Integer, DayType> exceptionTypeMap)\n {\n //\n // Create the calendar and add the default working hours\n //\n ProjectCalendar calendar = m_project.addCalendar();\n Integer dominantWorkPatternID = calendarRow.getInteger(\"DOMINANT_WORK_PATTERN\");\n calendar.setUniqueID(calendarRow.getInteger(\"CALENDARID\"));\n processWorkPattern(calendar, dominantWorkPatternID, workPatternMap, timeEntryMap, exceptionTypeMap);\n calendar.setName(calendarRow.getString(\"NAMK\"));\n\n //\n // Add any additional working weeks\n //\n List<Row> rows = workPatternAssignmentMap.get(calendar.getUniqueID());\n if (rows != null)\n {\n for (Row row : rows)\n {\n Integer workPatternID = row.getInteger(\"WORK_PATTERN\");\n if (!workPatternID.equals(dominantWorkPatternID))\n {\n ProjectCalendarWeek week = calendar.addWorkWeek();\n week.setDateRange(new DateRange(row.getDate(\"START_DATE\"), row.getDate(\"END_DATE\")));\n processWorkPattern(week, workPatternID, workPatternMap, timeEntryMap, exceptionTypeMap);\n }\n }\n }\n\n //\n // Add exceptions - not sure how exceptions which turn non-working days into working days are handled by Asta - if at all?\n //\n rows = exceptionAssignmentMap.get(calendar.getUniqueID());\n if (rows != null)\n {\n for (Row row : rows)\n {\n Date startDate = row.getDate(\"STARU_DATE\");\n Date endDate = row.getDate(\"ENE_DATE\");\n calendar.addCalendarException(startDate, endDate);\n }\n }\n\n m_eventManager.fireCalendarReadEvent(calendar);\n }",
"public static Node removePartitionFromNode(final Node node, Integer donatedPartition) {\n return UpdateClusterUtils.removePartitionsFromNode(node, Sets.newHashSet(donatedPartition));\n }",
"private void processWorkWeeks(byte[] data, int offset, ProjectCalendar cal)\n {\n // System.out.println(\"Calendar=\" + cal.getName());\n // System.out.println(\"Work week block start offset=\" + offset);\n // System.out.println(ByteArrayHelper.hexdump(data, true, 16, \"\"));\n\n // skip 4 byte header\n offset += 4;\n\n while (data.length >= offset + ((7 * 60) + 2 + 2 + 8 + 4))\n {\n //System.out.println(\"Week start offset=\" + offset);\n ProjectCalendarWeek week = cal.addWorkWeek();\n for (Day day : Day.values())\n {\n // 60 byte block per day\n processWorkWeekDay(data, offset, week, day);\n offset += 60;\n }\n\n Date startDate = DateHelper.getDayStartDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n Date finishDate = DateHelper.getDayEndDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n // skip unknown 8 bytes\n //System.out.println(ByteArrayHelper.hexdump(data, offset, 8, false));\n offset += 8;\n\n //\n // Extract the name length - ensure that it is aligned to a 4 byte boundary\n //\n int nameLength = MPPUtility.getInt(data, offset);\n if (nameLength % 4 != 0)\n {\n nameLength = ((nameLength / 4) + 1) * 4;\n }\n offset += 4;\n\n if (nameLength != 0)\n {\n String name = MPPUtility.getUnicodeString(data, offset, nameLength);\n offset += nameLength;\n week.setName(name);\n }\n\n week.setDateRange(new DateRange(startDate, finishDate));\n // System.out.println(week);\n }\n }",
"public static boolean hasAnyAnnotation(AnnotatedNode node, String... names) {\r\n for (String name : names) {\r\n if (hasAnnotation(node, name)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"public static CmsUUID readId(JSONObject obj, String key) {\n\n String strValue = obj.optString(key);\n if (!CmsUUID.isValidUUID(strValue)) {\n return null;\n }\n return new CmsUUID(strValue);\n }",
"protected void finishBox()\n {\n \tif (textLine.length() > 0)\n \t{\n String s;\n if (isReversed(Character.getDirectionality(textLine.charAt(0))))\n s = textLine.reverse().toString();\n else\n s = textLine.toString();\n\n curstyle.setLeft(textMetrics.getX());\n curstyle.setTop(textMetrics.getTop());\n curstyle.setLineHeight(textMetrics.getHeight());\n\n\t renderText(s, textMetrics);\n\t textLine = new StringBuilder();\n\t textMetrics = null;\n \t}\n }",
"private Point parsePoint(String point) {\n int comma = point.indexOf(',');\n if (comma == -1)\n return null;\n\n float lat = Float.valueOf(point.substring(0, comma));\n float lng = Float.valueOf(point.substring(comma + 1));\n return spatialctx.makePoint(lng, lat);\n }",
"public StreamReader getTableData(String name) throws IOException\n {\n InputStream stream = new ByteArrayInputStream(m_tableData.get(name));\n if (m_majorVersion > 5)\n { \n byte[] header = new byte[24];\n stream.read(header);\n SynchroLogger.log(\"TABLE HEADER\", header);\n }\n return new StreamReader(m_majorVersion, stream);\n }"
] |
The only difference between version 1.5 and 1.6 of the schema were to make is possible to define discovery options, this
resulted in the host and port attributes becoming optional -this method also indicates if discovery options are required
where the host and port were not supplied.
@param allowDiscoveryOptions i.e. are host and port potentially optional?
@return true if discovery options are required, i.e. no host and port set and the admin policy requires a config. | [
"private boolean parseRemoteDomainControllerAttributes_1_5(final XMLExtendedStreamReader reader, final ModelNode address,\n final List<ModelNode> list, boolean allowDiscoveryOptions) throws XMLStreamException {\n\n final ModelNode update = new ModelNode();\n update.get(OP_ADDR).set(address);\n update.get(OP).set(RemoteDomainControllerAddHandler.OPERATION_NAME);\n\n // Handle attributes\n AdminOnlyDomainConfigPolicy adminOnlyPolicy = AdminOnlyDomainConfigPolicy.DEFAULT;\n boolean requireDiscoveryOptions = false;\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n final String value = reader.getAttributeValue(i);\n if (!isNoNamespaceAttribute(reader, i)) {\n throw unexpectedAttribute(reader, i);\n } else {\n final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));\n switch (attribute) {\n case HOST: {\n DomainControllerWriteAttributeHandler.HOST.parseAndSetParameter(value, update, reader);\n break;\n }\n case PORT: {\n DomainControllerWriteAttributeHandler.PORT.parseAndSetParameter(value, update, reader);\n break;\n }\n case SECURITY_REALM: {\n DomainControllerWriteAttributeHandler.SECURITY_REALM.parseAndSetParameter(value, update, reader);\n break;\n }\n case USERNAME: {\n DomainControllerWriteAttributeHandler.USERNAME.parseAndSetParameter(value, update, reader);\n break;\n }\n case ADMIN_ONLY_POLICY: {\n DomainControllerWriteAttributeHandler.ADMIN_ONLY_POLICY.parseAndSetParameter(value, update, reader);\n ModelNode nodeValue = update.get(DomainControllerWriteAttributeHandler.ADMIN_ONLY_POLICY.getName());\n if (nodeValue.getType() != ModelType.EXPRESSION) {\n adminOnlyPolicy = AdminOnlyDomainConfigPolicy.getPolicy(nodeValue.asString());\n }\n break;\n }\n default:\n throw unexpectedAttribute(reader, i);\n }\n }\n }\n\n if (!update.hasDefined(DomainControllerWriteAttributeHandler.HOST.getName())) {\n if (allowDiscoveryOptions) {\n requireDiscoveryOptions = isRequireDiscoveryOptions(adminOnlyPolicy);\n } else {\n throw ParseUtils.missingRequired(reader, Collections.singleton(Attribute.HOST.getLocalName()));\n }\n }\n if (!update.hasDefined(DomainControllerWriteAttributeHandler.PORT.getName())) {\n if (allowDiscoveryOptions) {\n requireDiscoveryOptions = requireDiscoveryOptions || isRequireDiscoveryOptions(adminOnlyPolicy);\n } else {\n throw ParseUtils.missingRequired(reader, Collections.singleton(Attribute.PORT.getLocalName()));\n }\n }\n\n list.add(update);\n return requireDiscoveryOptions;\n }"
] | [
"private long getTotalTime(ProjectCalendarDateRanges exception, Date date, boolean after)\n {\n long currentTime = DateHelper.getCanonicalTime(date).getTime();\n long total = 0;\n for (DateRange range : exception)\n {\n total += getTime(range.getStart(), range.getEnd(), currentTime, after);\n }\n return (total);\n }",
"public static Message create( String text, Object data, ProcessingUnit owner )\n {\n return new SimpleMessage( text, data, owner);\n }",
"public void setAttributeEditable(Attribute attribute, boolean editable) {\n\t\tattribute.setEditable(editable);\n\t\tif (!(attribute instanceof LazyAttribute)) { // should not instantiate lazy attributes!\n\t\t\tif (attribute instanceof ManyToOneAttribute) {\n\t\t\t\tsetAttributeEditable(((ManyToOneAttribute) attribute).getValue(), editable);\n\t\t\t} else if (attribute instanceof OneToManyAttribute) {\n\t\t\t\tList<AssociationValue> values = ((OneToManyAttribute) attribute).getValue();\n\t\t\t\tfor (AssociationValue value : values) {\n\t\t\t\t\tsetAttributeEditable(value, editable);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public static XMLStreamException missingRequiredElement(final XMLExtendedStreamReader reader, final Set<?> required) {\n final StringBuilder b = new StringBuilder();\n Iterator<?> iterator = required.iterator();\n while (iterator.hasNext()) {\n final Object o = iterator.next();\n b.append(o.toString());\n if (iterator.hasNext()) {\n b.append(\", \");\n }\n }\n final XMLStreamException ex = ControllerLogger.ROOT_LOGGER.missingRequiredElements(b, reader.getLocation());\n\n Set<String> set = new HashSet<>();\n for (Object o : required) {\n String toString = o.toString();\n set.add(toString);\n }\n return new XMLStreamValidationException(ex.getMessage(),\n ValidationError.from(ex, ErrorType.REQUIRED_ELEMENTS_MISSING)\n .element(reader.getName())\n .alternatives(set),\n ex);\n }",
"public static ServiceController<DeploymentScanner> addService(final OperationContext context, final PathAddress resourceAddress, final String relativeTo, final String path,\n final int scanInterval, TimeUnit unit, final boolean autoDeployZip,\n final boolean autoDeployExploded, final boolean autoDeployXml, final boolean scanEnabled, final long deploymentTimeout, boolean rollbackOnRuntimeFailure,\n final FileSystemDeploymentService bootTimeService, final ScheduledExecutorService scheduledExecutorService) {\n final DeploymentScannerService service = new DeploymentScannerService(resourceAddress, relativeTo, path, scanInterval, unit, autoDeployZip,\n autoDeployExploded, autoDeployXml, scanEnabled, deploymentTimeout, rollbackOnRuntimeFailure, bootTimeService);\n final ServiceName serviceName = getServiceName(resourceAddress.getLastElement().getValue());\n service.scheduledExecutorValue.inject(scheduledExecutorService);\n final ServiceBuilder<DeploymentScanner> sb = context.getServiceTarget().addService(serviceName, service);\n sb.addDependency(context.getCapabilityServiceName(PATH_MANAGER_CAPABILITY, PathManager.class), PathManager.class, service.pathManagerValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.notification-handler-registry\", null),\n NotificationHandlerRegistry.class, service.notificationRegistryValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.model-controller-client-factory\", null),\n ModelControllerClientFactory.class, service.clientFactoryValue);\n sb.requires(org.jboss.as.server.deployment.Services.JBOSS_DEPLOYMENT_CHAINS);\n sb.addDependency(ControlledProcessStateService.SERVICE_NAME, ControlledProcessStateService.class, service.controlledProcessStateServiceValue);\n return sb.install();\n }",
"public Identity refreshIdentity()\r\n {\r\n Identity oldOid = getIdentity();\r\n this.oid = getBroker().serviceIdentity().buildIdentity(myObj);\r\n return oldOid;\r\n }",
"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 JSONObject toJSON() {\n try {\n return new JSONObject(properties).putOpt(\"name\", getName());\n } catch (JSONException e) {\n e.printStackTrace();\n Log.e(TAG, e, \"toJSON()\");\n throw new RuntimeAssertion(\"NodeEntry.toJSON() failed for '%s'\", this);\n }\n }",
"private void setConstraints(Task task, MapRow row)\n {\n ConstraintType constraintType = null;\n Date constraintDate = null;\n Date lateDate = row.getDate(\"CONSTRAINT_LATE_DATE\");\n Date earlyDate = row.getDate(\"CONSTRAINT_EARLY_DATE\");\n\n switch (row.getInteger(\"CONSTRAINT_TYPE\").intValue())\n {\n case 2: // Cannot Reschedule\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = task.getStart();\n break;\n }\n\n case 12: //Finish Between\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = lateDate;\n break;\n }\n\n case 10: // Finish On or After\n {\n constraintType = ConstraintType.FINISH_NO_EARLIER_THAN;\n constraintDate = earlyDate;\n break;\n }\n\n case 11: // Finish On or Before\n {\n constraintType = ConstraintType.FINISH_NO_LATER_THAN;\n constraintDate = lateDate;\n break;\n }\n\n case 13: // Mandatory Start\n case 5: // Start On\n case 9: // Finish On\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = earlyDate;\n break;\n }\n\n case 14: // Mandatory Finish\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = earlyDate;\n break;\n }\n\n case 4: // Start As Late As Possible\n {\n constraintType = ConstraintType.AS_LATE_AS_POSSIBLE;\n break;\n }\n\n case 3: // Start As Soon As Possible\n {\n constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n break;\n }\n\n case 8: // Start Between\n {\n constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n constraintDate = earlyDate;\n break;\n }\n\n case 6: // Start On or Before\n {\n constraintType = ConstraintType.START_NO_LATER_THAN;\n constraintDate = earlyDate;\n break;\n }\n\n case 15: // Work Between\n {\n constraintType = ConstraintType.START_NO_EARLIER_THAN;\n constraintDate = earlyDate;\n break;\n }\n }\n task.setConstraintType(constraintType);\n task.setConstraintDate(constraintDate);\n }"
] |
Reads a color value represented by three bytes, for R, G, and B
components, plus a flag byte indicating if this is an automatic color.
Returns null if the color type is "Automatic".
@param data byte array of data
@param offset offset into array
@return new Color instance | [
"public static final Color getColor(byte[] data, int offset)\n {\n Color result = null;\n\n if (getByte(data, offset + 3) == 0)\n {\n int r = getByte(data, offset);\n int g = getByte(data, offset + 1);\n int b = getByte(data, offset + 2);\n result = new Color(r, g, b);\n }\n\n return result;\n }"
] | [
"final void roll(final long timeForSuffix) {\n\n final File backupFile = this.prepareBackupFile(timeForSuffix);\n\n // close filename\n this.getAppender().closeFile();\n\n // rename filename on disk to filename+suffix(+number)\n this.doFileRoll(this.getAppender().getIoFile(), backupFile);\n\n // setup new file 'filename'\n this.getAppender().openFile();\n\n this.fireFileRollEvent(new FileRollEvent(this, backupFile));\n }",
"public static CmsSearchConfigurationSorting create(\n final String sortParam,\n final List<I_CmsSearchConfigurationSortOption> options,\n final I_CmsSearchConfigurationSortOption defaultOption) {\n\n return (null != sortParam) || ((null != options) && !options.isEmpty()) || (null != defaultOption)\n ? new CmsSearchConfigurationSorting(sortParam, options, defaultOption)\n : null;\n }",
"public Search counts(String[] countsfields) {\r\n assert (countsfields.length > 0);\r\n JsonArray countsJsonArray = new JsonArray();\r\n for(String countsfield : countsfields) {\r\n JsonPrimitive element = new JsonPrimitive(countsfield);\r\n countsJsonArray.add(element);\r\n }\r\n databaseHelper.query(\"counts\", countsJsonArray);\r\n return this;\r\n }",
"private JsonArray formatBoxMetadataFilterRequest() {\n JsonArray boxMetadataFilterRequestArray = new JsonArray();\n\n JsonObject boxMetadataFilter = new JsonObject()\n .add(\"templateKey\", this.metadataFilter.getTemplateKey())\n .add(\"scope\", this.metadataFilter.getScope())\n .add(\"filters\", this.metadataFilter.getFiltersList());\n boxMetadataFilterRequestArray.add(boxMetadataFilter);\n\n return boxMetadataFilterRequestArray;\n }",
"private List<T> computePagedList(List<T> result, HeaderAndBody httpResponse, JSONObject where, Pipe<T> requestingPipe) {\n ReadFilter previousRead = null;\n ReadFilter nextRead = null;\n\n if (PageConfig.MetadataLocations.WEB_LINKING.equals(pageConfig.getMetadataLocation())) {\n String webLinksRaw = \"\";\n final String relHeader = \"rel\";\n final String nextIdentifier = pageConfig.getNextIdentifier();\n final String prevIdentifier = pageConfig.getPreviousIdentifier();\n try {\n webLinksRaw = getWebLinkHeader(httpResponse);\n if (webLinksRaw == null) { // no paging, return result\n return result;\n }\n List<WebLink> webLinksParsed = WebLinkParser.parse(webLinksRaw);\n for (WebLink link : webLinksParsed) {\n if (nextIdentifier.equals(link.getParameters().get(relHeader))) {\n nextRead = new ReadFilter();\n nextRead.setLinkUri(new URI(link.getUri()));\n } else if (prevIdentifier.equals(link.getParameters().get(relHeader))) {\n previousRead = new ReadFilter();\n previousRead.setLinkUri(new URI(link.getUri()));\n }\n\n }\n } catch (URISyntaxException ex) {\n Log.e(TAG, webLinksRaw + \" did not contain a valid context URI\", ex);\n throw new RuntimeException(ex);\n } catch (ParseException ex) {\n Log.e(TAG, webLinksRaw + \" could not be parsed as a web link header\", ex);\n throw new RuntimeException(ex);\n }\n } else if (pageConfig.getMetadataLocation().equals(PageConfig.MetadataLocations.HEADERS)) {\n nextRead = pageConfig.getPageParameterExtractor().getNextFilter(httpResponse, RestAdapter.this.pageConfig);\n previousRead = pageConfig.getPageParameterExtractor().getPreviousFilter(httpResponse, RestAdapter.this.pageConfig);\n } else if (pageConfig.getMetadataLocation().equals(PageConfig.MetadataLocations.BODY)) {\n nextRead = pageConfig.getPageParameterExtractor().getNextFilter(httpResponse, RestAdapter.this.pageConfig);\n previousRead = pageConfig.getPageParameterExtractor().getPreviousFilter(httpResponse, RestAdapter.this.pageConfig);\n } else {\n throw new IllegalStateException(\"Not supported\");\n }\n if (nextRead != null) {\n nextRead.setWhere(where);\n }\n\n if (previousRead != null) {\n previousRead.setWhere(where);\n }\n\n return new WrappingPagedList<T>(requestingPipe, result, nextRead, previousRead);\n }",
"public static base_response enable(nitro_service client, String acl6name) throws Exception {\n\t\tnsacl6 enableresource = new nsacl6();\n\t\tenableresource.acl6name = acl6name;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}",
"public static Bitmap flip(Bitmap src) {\n Matrix m = new Matrix();\n m.preScale(-1, 1);\n return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), m, false);\n }",
"protected final Event processEvent() throws IOException {\n while (true) {\n String line;\n try {\n line = readLine();\n } catch (final EOFException ex) {\n if (doneOnce) {\n throw ex;\n }\n doneOnce = true;\n line = \"\";\n }\n\n // If the line is empty (a blank line), Dispatch the event, as defined below.\n if (line.isEmpty()) {\n // If the data buffer is an empty string, set the data buffer and the event name buffer to\n // the empty string and abort these steps.\n if (dataBuffer.length() == 0) {\n eventName = \"\";\n continue;\n }\n\n // If the event name buffer is not the empty string but is also not a valid NCName,\n // set the data buffer and the event name buffer to the empty string and abort these steps.\n // NOT IMPLEMENTED\n\n final Event.Builder eventBuilder = new Event.Builder();\n eventBuilder.withEventName(eventName.isEmpty() ? Event.MESSAGE_EVENT : eventName);\n eventBuilder.withData(dataBuffer.toString());\n\n // Set the data buffer and the event name buffer to the empty string.\n dataBuffer = new StringBuilder();\n eventName = \"\";\n\n return eventBuilder.build();\n // If the line starts with a U+003A COLON character (':')\n } else if (line.startsWith(\":\")) {\n // ignore the line\n // If the line contains a U+003A COLON character (':') character\n } else if (line.contains(\":\")) {\n // Collect the characters on the line before the first U+003A COLON character (':'),\n // and let field be that string.\n final int colonIdx = line.indexOf(\":\");\n final String field = line.substring(0, colonIdx);\n\n // Collect the characters on the line after the first U+003A COLON character (':'),\n // and let value be that string.\n // If value starts with a single U+0020 SPACE character, remove it from value.\n String value = line.substring(colonIdx + 1);\n value = value.startsWith(\" \") ? value.substring(1) : value;\n\n processField(field, value);\n // Otherwise, the string is not empty but does not contain a U+003A COLON character (':')\n // character\n } else {\n processField(line, \"\");\n }\n }\n }",
"@Nullable\n public ByteIterable get(@NotNull final Transaction txn, @NotNull final ByteIterable first) {\n return this.first.get(txn, first);\n }"
] |
QR decomposition.
Decomposes (m,n) matrix A into a (m,m) matrix Q and an (m,n) matrix R such that
Q is orthogonal, R is upper triangular and Q * R = A
Note that if A has more rows than columns, then the lower rows of R will contain
only zeros, such that the corresponding later columns of Q do not enter the computation
at all. For some reason, LAPACK does not properly normalize those columns.
@param A matrix
@return QR decomposition | [
"public static QRDecomposition<DoubleMatrix> qr(DoubleMatrix A) {\n int minmn = min(A.rows, A.columns);\n DoubleMatrix result = A.dup();\n DoubleMatrix tau = new DoubleMatrix(minmn);\n SimpleBlas.geqrf(result, tau);\n DoubleMatrix R = new DoubleMatrix(A.rows, A.columns);\n for (int i = 0; i < A.rows; i++) {\n for (int j = i; j < A.columns; j++) {\n R.put(i, j, result.get(i, j));\n }\n }\n DoubleMatrix Q = DoubleMatrix.eye(A.rows);\n SimpleBlas.ormqr('L', 'N', result, tau, Q);\n return new QRDecomposition<DoubleMatrix>(Q, R);\n }"
] | [
"@Override\n public ImageSource apply(ImageSource input) {\n int w = input.getWidth();\n int h = input.getHeight();\n\n MatrixSource output = new MatrixSource(input);\n\n Vector3 n = new Vector3(0, 0, 1);\n\n for (int y = 0; y < h; y++) {\n for (int x = 0; x < w; x++) {\n\n if (x < border || x == w - border || y < border || y == h - border) {\n output.setRGB(x, y, VectorHelper.Z_NORMAL);\n continue;\n }\n\n float s0 = input.getR(x - 1, y + 1);\n float s1 = input.getR(x, y + 1);\n float s2 = input.getR(x + 1, y + 1);\n float s3 = input.getR(x - 1, y);\n float s5 = input.getR(x + 1, y);\n float s6 = input.getR(x - 1, y - 1);\n float s7 = input.getR(x, y - 1);\n float s8 = input.getR(x + 1, y - 1);\n\n float nx = -(s2 - s0 + 2 * (s5 - s3) + s8 - s6);\n float ny = -(s6 - s0 + 2 * (s7 - s1) + s8 - s2);\n\n n.set(nx, ny, scale);\n n.nor();\n\n int rgb = VectorHelper.vectorToColor(n);\n output.setRGB(x, y, rgb);\n }\n }\n\n return new MatrixSource(output);\n }",
"private Map<String, Object> getMapFromJSON(String json) {\n Map<String, Object> propMap = new HashMap<String, Object>();\n ObjectMapper mapper = new ObjectMapper();\n\n // Initialize string if empty\n if (json == null || json.length() == 0) {\n json = \"{}\";\n }\n\n try {\n // Convert string\n propMap = mapper.readValue(json, new TypeReference<HashMap<String, Object>>(){});\n } catch (Exception e) {\n ;\n }\n return propMap;\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 }",
"public Weld addPackage(boolean scanRecursively, Class<?> packageClass) {\n packages.add(new PackInfo(packageClass, scanRecursively));\n return this;\n }",
"@SuppressWarnings(\"unchecked\")\n public final FluentModelImplT withTag(String key, String value) {\n if (this.inner().getTags() == null) {\n this.inner().withTags(new HashMap<String, String>());\n }\n this.inner().getTags().put(key, value);\n return (FluentModelImplT) this;\n }",
"public static List<Map<String, Object>> listify(ObjectMapper mapper, Object source) {\n return (List<Map<String, Object>>) collectify(mapper, source, List.class);\n }",
"@NotThreadsafe\n private void initFileStreams(int chunkId) {\n /**\n * {@link Set#add(Object)} returns false if the element already existed in the set.\n * This ensures we initialize the resources for each chunk only once.\n */\n if (chunksHandled.add(chunkId)) {\n try {\n this.indexFileSizeInBytes[chunkId] = 0L;\n this.valueFileSizeInBytes[chunkId] = 0L;\n this.checkSumDigestIndex[chunkId] = CheckSum.getInstance(checkSumType);\n this.checkSumDigestValue[chunkId] = CheckSum.getInstance(checkSumType);\n this.position[chunkId] = 0;\n this.taskIndexFileName[chunkId] = new Path(FileOutputFormat.getOutputPath(conf),\n getStoreName() + \".\"\n + Integer.toString(chunkId) + \"_\"\n + this.taskId + INDEX_FILE_EXTENSION\n + fileExtension);\n this.taskValueFileName[chunkId] = new Path(FileOutputFormat.getOutputPath(conf),\n getStoreName() + \".\"\n + Integer.toString(chunkId) + \"_\"\n + this.taskId + DATA_FILE_EXTENSION\n + fileExtension);\n if(this.fs == null)\n this.fs = this.taskIndexFileName[chunkId].getFileSystem(conf);\n if(isValidCompressionEnabled) {\n this.indexFileStream[chunkId] = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(fs.create(this.taskIndexFileName[chunkId]),\n DEFAULT_BUFFER_SIZE)));\n this.valueFileStream[chunkId] = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(fs.create(this.taskValueFileName[chunkId]),\n DEFAULT_BUFFER_SIZE)));\n\n } else {\n this.indexFileStream[chunkId] = fs.create(this.taskIndexFileName[chunkId]);\n this.valueFileStream[chunkId] = fs.create(this.taskValueFileName[chunkId]);\n\n }\n fs.setPermission(this.taskIndexFileName[chunkId],\n new FsPermission(HadoopStoreBuilder.HADOOP_FILE_PERMISSION));\n logger.info(\"Setting permission to 755 for \" + this.taskIndexFileName[chunkId]);\n fs.setPermission(this.taskValueFileName[chunkId],\n new FsPermission(HadoopStoreBuilder.HADOOP_FILE_PERMISSION));\n logger.info(\"Setting permission to 755 for \" + this.taskValueFileName[chunkId]);\n\n logger.info(\"Opening \" + this.taskIndexFileName[chunkId] + \" and \"\n + this.taskValueFileName[chunkId] + \" for writing.\");\n } catch(IOException e) {\n throw new RuntimeException(\"Failed to open Input/OutputStream\", e);\n }\n }\n }",
"private static void processTaskFilter(ProjectFile project, Filter filter)\n {\n for (Task task : project.getTasks())\n {\n if (filter.evaluate(task, null))\n {\n System.out.println(task.getID() + \",\" + task.getUniqueID() + \",\" + task.getName());\n }\n }\n }",
"public void removePathnameFromProfile(int path_id, int profileId) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_PATH +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }"
] |
Performs a query to retrieve all the design documents defined in the database.
@return a list of the design documents from the database
@throws IOException if there was an error communicating with the server
@since 2.5.0 | [
"public List<DesignDocument> list() throws IOException {\r\n return db.getAllDocsRequestBuilder()\r\n .startKey(\"_design/\")\r\n .endKey(\"_design0\")\r\n .inclusiveEnd(false)\r\n .includeDocs(true)\r\n .build()\r\n .getResponse().getDocsAs(DesignDocument.class);\r\n }"
] | [
"protected void checkVariableName(GraphRewrite event, EvaluationContext context)\n {\n if (getInputVariablesName() == null)\n {\n setInputVariablesName(Iteration.getPayloadVariableName(event, context));\n }\n }",
"private void onScrollImpl(final Vector3Axis offset, final LayoutScroller.OnScrollListener listener) {\n if (!isScrolling()) {\n mScroller = new ScrollingProcessor(offset, listener);\n mScroller.scroll();\n }\n }",
"public CollectionRequest<Task> tags(String task) {\n \n String path = String.format(\"/tasks/%s/tags\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"public boolean needToSetCategoryFolder() {\n\n if (m_adeModuleVersion == null) {\n return true;\n }\n CmsModuleVersion categoryFolderUpdateVersion = new CmsModuleVersion(\"9.0.0\");\n return (m_adeModuleVersion.compareTo(categoryFolderUpdateVersion) == -1);\n }",
"public static ResourceKey key(Enum<?> enumValue, String key) {\n return new ResourceKey(enumValue.getClass().getName(), enumValue.name()).child(key);\n }",
"@PostConstruct\n\tprotected void buildCopyrightMap() {\n\t\tif (null == declaredPlugins) {\n\t\t\treturn;\n\t\t}\n\t\t// go over all plug-ins, adding copyright info, avoiding duplicates (on object key)\n\t\tfor (PluginInfo plugin : declaredPlugins.values()) {\n\t\t\tfor (CopyrightInfo copyright : plugin.getCopyrightInfo()) {\n\t\t\t\tString key = copyright.getKey();\n\t\t\t\tString msg = copyright.getKey() + \": \" + copyright.getCopyright() + \" : licensed as \" +\n\t\t\t\t\t\tcopyright.getLicenseName() + \", see \" + copyright.getLicenseUrl();\n\t\t\t\tif (null != copyright.getSourceUrl()) {\n\t\t\t\t\tmsg += \" source \" + copyright.getSourceUrl();\n\t\t\t\t}\n\t\t\t\tif (!copyrightMap.containsKey(key)) {\n\t\t\t\t\tlog.info(msg);\n\t\t\t\t\tcopyrightMap.put(key, copyright);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"protected static PreparedStatement memorize(final PreparedStatement target, final ConnectionHandle connectionHandle) {\n\t\treturn (PreparedStatement) Proxy.newProxyInstance(\n\t\t\t\tPreparedStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {PreparedStatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}",
"private static String quoteSort(Sort[] sort) {\n LinkedList<String> sorts = new LinkedList<String>();\n for (Sort pair : sort) {\n sorts.add(String.format(\"{%s: %s}\", Helpers.quote(pair.getName()), Helpers.quote(pair.getOrder().toString())));\n }\n return sorts.toString();\n }",
"public static boolean canParseColor(final String colorString) {\n try {\n return ColorParser.toColor(colorString) != null;\n } catch (Exception exc) {\n return false;\n }\n }"
] |
The only indication that a task is a SubProject is the contents
of the subproject file name field. We test these here then add a skeleton
subproject structure to match the way we do things with MPP files. | [
"private void processSubProjects()\n {\n int subprojectIndex = 1;\n for (Task task : m_project.getTasks())\n {\n String subProjectFileName = task.getSubprojectName();\n if (subProjectFileName != null)\n {\n String fileName = subProjectFileName;\n int offset = 0x01000000 + (subprojectIndex * 0x00400000);\n int index = subProjectFileName.lastIndexOf('\\\\');\n if (index != -1)\n {\n fileName = subProjectFileName.substring(index + 1);\n }\n\n SubProject sp = new SubProject();\n sp.setFileName(fileName);\n sp.setFullPath(subProjectFileName);\n sp.setUniqueIDOffset(Integer.valueOf(offset));\n sp.setTaskUniqueID(task.getUniqueID());\n task.setSubProject(sp);\n\n ++subprojectIndex;\n }\n }\n }"
] | [
"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 }",
"public void setEnterpriseNumber(int index, Number value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_NUMBER, index), value);\n }",
"@RequestMapping(value = \"api/servergroup\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getServerGroups(Model model,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"search\", required = false) String search,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n\n List<ServerGroup> serverGroups = ServerRedirectService.getInstance().tableServerGroups(profileId);\n\n if (search != null) {\n Iterator<ServerGroup> iterator = serverGroups.iterator();\n while (iterator.hasNext()) {\n ServerGroup serverGroup = iterator.next();\n if (!serverGroup.getName().toLowerCase().contains(search.toLowerCase())) {\n iterator.remove();\n }\n }\n }\n HashMap<String, Object> returnJson = Utils.getJQGridJSON(serverGroups, \"servergroups\");\n return returnJson;\n }",
"public int getCurrentPage() {\n int currentPage = 1;\n int count = mScrollable.getScrollingItemsCount();\n if (mSupportScrollByPage && mCurrentItemIndex >= 0 &&\n mCurrentItemIndex < count) {\n currentPage = (Math.min(mCurrentItemIndex + mPageSize - 1, count - 1)/mPageSize);\n }\n return currentPage;\n }",
"public static byte[] toUnixLineEndings( InputStream input ) throws IOException {\n String encoding = \"ISO-8859-1\";\n FixCrLfFilter filter = new FixCrLfFilter(new InputStreamReader(input, encoding));\n filter.setEol(FixCrLfFilter.CrLf.newInstance(\"unix\"));\n\n ByteArrayOutputStream filteredFile = new ByteArrayOutputStream();\n Utils.copy(new ReaderInputStream(filter, encoding), filteredFile);\n\n return filteredFile.toByteArray();\n }",
"public AsciiTable setPaddingLeftRight(int padding){\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingLeftRight(padding);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"private void processDefaultCurrency(Integer currencyID) throws SQLException\n {\n List<Row> rows = getRows(\"select * from \" + m_schema + \"currtype where curr_id=?\", currencyID);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n m_reader.processDefaultCurrency(row);\n }\n }",
"static PathAddress toPathAddress(String domain, ImmutableManagementResourceRegistration registry, ObjectName name) {\n if (!name.getDomain().equals(domain)) {\n return PathAddress.EMPTY_ADDRESS;\n }\n if (name.equals(ModelControllerMBeanHelper.createRootObjectName(domain))) {\n return PathAddress.EMPTY_ADDRESS;\n }\n final Hashtable<String, String> properties = name.getKeyPropertyList();\n return searchPathAddress(PathAddress.EMPTY_ADDRESS, registry, properties);\n }",
"public T find(AbstractProject<?, ?> project, Class<T> type) {\n // First check that the Flexible Publish plugin is installed:\n if (Jenkins.getInstance().getPlugin(FLEXIBLE_PUBLISH_PLUGIN) != null) {\n // Iterate all the project's publishers and find the flexible publisher:\n for (Publisher publisher : project.getPublishersList()) {\n // Found the flexible publisher:\n if (publisher instanceof FlexiblePublisher) {\n // See if it wraps a publisher of the specified type and if it does, return it:\n T pub = getWrappedPublisher(publisher, type);\n if (pub != null) {\n return pub;\n }\n }\n }\n }\n\n return null;\n }"
] |
Builds the Join for columns if they are not found among the existingColumns.
@param columns the list of columns represented by Criteria.Field to ensure
@param existingColumns the list of column names (String) that are already appended | [
"protected void ensureColumns(List columns, List existingColumns)\r\n {\r\n if (columns == null || columns.isEmpty())\r\n {\r\n return;\r\n }\r\n \r\n Iterator iter = columns.iterator();\r\n\r\n while (iter.hasNext())\r\n {\r\n FieldHelper cf = (FieldHelper) iter.next();\r\n if (!existingColumns.contains(cf.name))\r\n {\r\n getAttributeInfo(cf.name, false, null, getQuery().getPathClasses());\r\n }\r\n }\r\n }"
] | [
"public MediaType copyQualityValue(MediaType mediaType) {\n\t\tif (!mediaType.parameters.containsKey(PARAM_QUALITY_FACTOR)) {\n\t\t\treturn this;\n\t\t}\n\t\tMap<String, String> params = new LinkedHashMap<String, String>(this.parameters);\n\t\tparams.put(PARAM_QUALITY_FACTOR, mediaType.parameters.get(PARAM_QUALITY_FACTOR));\n\t\treturn new MediaType(this, params);\n\t}",
"public Rate getRate(int field) throws MPXJException\n {\n Rate result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n try\n {\n String rate = m_fields[field];\n int index = rate.indexOf('/');\n double amount;\n TimeUnit units;\n\n if (index == -1)\n {\n amount = m_formats.getCurrencyFormat().parse(rate).doubleValue();\n units = TimeUnit.HOURS;\n }\n else\n {\n amount = m_formats.getCurrencyFormat().parse(rate.substring(0, index)).doubleValue();\n units = TimeUnitUtility.getInstance(rate.substring(index + 1), m_locale);\n }\n\n result = new Rate(amount, units);\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse rate\", ex);\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }",
"public float getTangentY(int vertex) {\n if (!hasTangentsAndBitangents()) {\n throw new IllegalStateException(\"mesh has no bitangents\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_tangents.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\n }",
"public RandomVariable getImpliedBachelierATMOptionVolatility(RandomVariable optionValue, double optionMaturity, double swapAnnuity){\n\t\treturn optionValue.average().mult(Math.sqrt(2.0 * Math.PI / optionMaturity) / swapAnnuity);\n\t}",
"@Subscribe\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n long millis = e.getExecutionTime();\n String suiteName = e.getDescription().getDisplayName();\n \n List<Long> values = hints.get(suiteName);\n if (values == null) {\n hints.put(suiteName, values = new ArrayList<>());\n }\n values.add(millis);\n while (values.size() > historyLength)\n values.remove(0);\n }",
"public static aaaglobal_binding get(nitro_service service) throws Exception{\n\t\taaaglobal_binding obj = new aaaglobal_binding();\n\t\taaaglobal_binding response = (aaaglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private boolean loadCustomErrorPage(\n CmsObject cms,\n HttpServletRequest req,\n HttpServletResponse res,\n String rootPath) {\n\n try {\n\n // get the site of the error page resource\n CmsSite errorSite = OpenCms.getSiteManager().getSiteForRootPath(rootPath);\n cms.getRequestContext().setSiteRoot(errorSite.getSiteRoot());\n String relPath = cms.getRequestContext().removeSiteRoot(rootPath);\n if (cms.existsResource(relPath)) {\n cms.getRequestContext().setUri(relPath);\n OpenCms.getResourceManager().loadResource(cms, cms.readResource(relPath), req, res);\n return true;\n } else {\n return false;\n }\n } catch (Throwable e) {\n // something went wrong log the exception and return false\n LOG.error(e.getMessage(), e);\n return false;\n }\n }",
"public static UriComponentsBuilder fromPath(String path) {\n\t\tUriComponentsBuilder builder = new UriComponentsBuilder();\n\t\tbuilder.path(path);\n\t\treturn builder;\n\t}",
"public boolean getFlag(int index)\n {\n return BooleanHelper.getBoolean((Boolean) getCachedValue(selectField(ResourceFieldLists.CUSTOM_FLAG, index)));\n }"
] |
Walk through the object graph of the specified insert object. Was used for
recursive object graph walk. | [
"private void cascadeInsertFor(ObjectEnvelope mod, List alreadyPrepared)\r\n {\r\n // avoid endless recursion, so use List for registration\r\n if(alreadyPrepared.contains(mod.getIdentity())) return;\r\n alreadyPrepared.add(mod.getIdentity());\r\n\r\n ClassDescriptor cld = getTransaction().getBroker().getClassDescriptor(mod.getObject().getClass());\r\n\r\n List refs = cld.getObjectReferenceDescriptors(true);\r\n cascadeInsertSingleReferences(mod, refs, alreadyPrepared);\r\n\r\n List colls = cld.getCollectionDescriptors(true);\r\n cascadeInsertCollectionReferences(mod, colls, alreadyPrepared);\r\n }"
] | [
"public String[] getNormalizedLabels() {\n\t\tif(isValid()) {\n\t\t\treturn parsedHost.getNormalizedLabels();\n\t\t}\n\t\tif(host.length() == 0) {\n\t\t\treturn new String[0];\n\t\t}\n\t\treturn new String[] {host};\n\t}",
"public void strokeRoundRectangle(Rectangle rect, Color color, float linewidth, float r) {\n\t\ttemplate.saveState();\n\t\tsetStroke(color, linewidth, null);\n\t\ttemplate.roundRectangle(origX + rect.getLeft(), origY + rect.getBottom(), rect.getWidth(), rect.getHeight(), r);\n\t\ttemplate.stroke();\n\t\ttemplate.restoreState();\n\t}",
"public static base_responses update(nitro_service client, systemuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsystemuser updateresources[] = new systemuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new systemuser();\n\t\t\t\tupdateresources[i].username = resources[i].username;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].externalauth = resources[i].externalauth;\n\t\t\t\tupdateresources[i].promptstring = resources[i].promptstring;\n\t\t\t\tupdateresources[i].timeout = resources[i].timeout;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static base_responses update(nitro_service client, nsrpcnode resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsrpcnode updateresources[] = new nsrpcnode[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsrpcnode();\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].srcip = resources[i].srcip;\n\t\t\t\tupdateresources[i].secure = resources[i].secure;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"private SynchroTable readTableHeader(byte[] header)\n {\n SynchroTable result = null;\n String tableName = DatatypeConverter.getSimpleString(header, 0);\n if (!tableName.isEmpty())\n {\n int offset = DatatypeConverter.getInt(header, 40);\n result = new SynchroTable(tableName, offset);\n }\n return result;\n }",
"public static dbdbprofile get(nitro_service service, String name) throws Exception{\n\t\tdbdbprofile obj = new dbdbprofile();\n\t\tobj.set_name(name);\n\t\tdbdbprofile response = (dbdbprofile) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public void push( Token token ) {\n size++;\n if( first == null ) {\n first = token;\n last = token;\n token.previous = null;\n token.next = null;\n } else {\n last.next = token;\n token.previous = last;\n token.next = null;\n last = token;\n }\n }",
"private static void parseDockers(JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"dockers\")) {\n ArrayList<Point> dockers = new ArrayList<Point>();\n\n JSONArray dockersObject = modelJSON.getJSONArray(\"dockers\");\n for (int i = 0; i < dockersObject.length(); i++) {\n Double x = dockersObject.getJSONObject(i).getDouble(\"x\");\n Double y = dockersObject.getJSONObject(i).getDouble(\"y\");\n dockers.add(new Point(x,\n y));\n }\n if (dockers.size() > 0) {\n current.setDockers(dockers);\n }\n }\n }",
"private boolean evaluateLogicalOperator(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)\n {\n boolean result = false;\n\n if (m_criteriaList.size() == 0)\n {\n result = true;\n }\n else\n {\n for (GenericCriteria criteria : m_criteriaList)\n {\n result = criteria.evaluate(container, promptValues);\n if ((m_operator == TestOperator.AND && !result) || (m_operator == TestOperator.OR && result))\n {\n break;\n }\n }\n }\n\n return result;\n }"
] |
Converts a parameter map to the parameter string.
@param parameters the parameter map.
@return the parameter string. | [
"public static String paramMapToString(final Map<String, String[]> parameters) {\n\n final StringBuffer result = new StringBuffer();\n for (final String key : parameters.keySet()) {\n String[] values = parameters.get(key);\n if (null == values) {\n result.append(key).append('&');\n } else {\n for (final String value : parameters.get(key)) {\n result.append(key).append('=').append(CmsEncoder.encode(value)).append('&');\n }\n }\n }\n // remove last '&'\n if (result.length() > 0) {\n result.setLength(result.length() - 1);\n }\n return result.toString();\n }"
] | [
"public 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 }",
"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 final void setConfigurationFiles(final Map<String, String> configurationFiles)\n throws URISyntaxException {\n this.configurationFiles.clear();\n this.configurationFileLastModifiedTimes.clear();\n for (Map.Entry<String, String> entry: configurationFiles.entrySet()) {\n if (!entry.getValue().contains(\":/\")) {\n // assume is a file\n this.configurationFiles.put(entry.getKey(), new File(entry.getValue()).toURI());\n } else {\n this.configurationFiles.put(entry.getKey(), new URI(entry.getValue()));\n }\n }\n\n if (this.configFileLoader != null) {\n this.validateConfigurationFiles();\n }\n }",
"public void download(OutputStream output, ProgressListener listener) {\n URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.fileID, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxAPIResponse response = request.send();\n InputStream input = response.getBody(listener);\n\n long totalRead = 0;\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = input.read(buffer);\n totalRead += n;\n while (n != -1) {\n output.write(buffer, 0, n);\n n = input.read(buffer);\n totalRead += n;\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Couldn't connect to the Box API due to a network error.\", e);\n }\n\n response.disconnect();\n }",
"private void processDestructionQueue(HttpServletRequest request) {\n Object contextsAttribute = request.getAttribute(DESTRUCTION_QUEUE_ATTRIBUTE_NAME);\n if (contextsAttribute instanceof Map) {\n Map<String, List<ContextualInstance<?>>> contexts = cast(contextsAttribute);\n synchronized (contexts) {\n FastEvent<String> beforeDestroyedEvent = FastEvent.of(String.class, beanManager, BeforeDestroyed.Literal.CONVERSATION);\n FastEvent<String> destroyedEvent = FastEvent.of(String.class, beanManager, Destroyed.Literal.CONVERSATION);\n for (Iterator<Entry<String, List<ContextualInstance<?>>>> iterator = contexts.entrySet().iterator(); iterator.hasNext();) {\n Entry<String, List<ContextualInstance<?>>> entry = iterator.next();\n beforeDestroyedEvent.fire(entry.getKey());\n for (ContextualInstance<?> contextualInstance : entry.getValue()) {\n destroyContextualInstance(contextualInstance);\n }\n // Note that for the attached/current conversation we fire the destroyed event twice because we can't reliably identify such a conversation\n destroyedEvent.fire(entry.getKey());\n iterator.remove();\n }\n }\n }\n }",
"@Override\n public DiscordianDate date(int prolepticYear, int month, int dayOfMonth) {\n return DiscordianDate.of(prolepticYear, month, dayOfMonth);\n }",
"public static ComplexNumber Multiply(ComplexNumber z1, double scalar) {\r\n return new ComplexNumber(z1.real * scalar, z1.imaginary * scalar);\r\n }",
"public ConfigBuilder withSentinels(final Set<String> sentinels) {\n if (sentinels == null || sentinels.size() < 1) {\n throw new IllegalArgumentException(\"sentinels is null or empty: \" + sentinels);\n }\n this.sentinels = sentinels;\n return this;\n }",
"public static ManagerFunctions.InputN createMultTransA() {\n return (inputs, manager) -> {\n if( inputs.size() != 2 )\n throw new RuntimeException(\"Two inputs required\");\n\n final Variable varA = inputs.get(0);\n final Variable varB = inputs.get(1);\n\n Operation.Info ret = new Operation.Info();\n\n if( varA instanceof VariableMatrix && varB instanceof VariableMatrix ) {\n\n // The output matrix or scalar variable must be created with the provided manager\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n ret.op = new Operation(\"multTransA-mm\") {\n @Override\n public void process() {\n DMatrixRMaj mA = ((VariableMatrix)varA).matrix;\n DMatrixRMaj mB = ((VariableMatrix)varB).matrix;\n\n CommonOps_DDRM.multTransA(mA,mB,output.matrix);\n }\n };\n } else {\n throw new IllegalArgumentException(\"Expected both inputs to be a matrix\");\n }\n\n return ret;\n };\n }"
] |
Validate the Combination filter field in Multi configuration jobs | [
"public static FormValidation validateArtifactoryCombinationFilter(String value)\n throws IOException, InterruptedException {\n String url = Util.fixEmptyAndTrim(value);\n if (url == null)\n return FormValidation.error(\"Mandatory field - You don`t have any deploy matches\");\n\n return FormValidation.ok();\n }"
] | [
"public static vpnclientlessaccesspolicy get(nitro_service service, String name) throws Exception{\n\t\tvpnclientlessaccesspolicy obj = new vpnclientlessaccesspolicy();\n\t\tobj.set_name(name);\n\t\tvpnclientlessaccesspolicy response = (vpnclientlessaccesspolicy) obj.get_resource(service);\n\t\treturn response;\n\t}",
"final protected String getTrimmedString() throws BadMessage {\n if (_bufferPosition == 0) return \"\";\n\n int start = 0;\n boolean quoted = false;\n // Look for start\n while (start < _bufferPosition) {\n final char ch = _internalBuffer[start];\n if (ch == '\"') {\n quoted = true;\n break;\n }\n else if (ch != HttpTokens.SPACE && ch != HttpTokens.TAB) {\n break;\n }\n start++;\n }\n\n int end = _bufferPosition; // Position is of next write\n\n // Look for end\n while(end > start) {\n final char ch = _internalBuffer[end - 1];\n\n if (quoted) {\n if (ch == '\"') break;\n else if (ch != HttpTokens.SPACE && ch != HttpTokens.TAB) {\n throw new BadMessage(\"String might not quoted correctly: '\" + getString() + \"'\");\n }\n }\n else if (ch != HttpTokens.SPACE && ch != HttpTokens.TAB) break;\n end--;\n }\n\n String str = new String(_internalBuffer, start, end - start);\n\n return str;\n }",
"public void applyTo(Context ctx, GradientDrawable drawable) {\n if (mColorInt != 0) {\n drawable.setColor(mColorInt);\n } else if (mColorRes != -1) {\n drawable.setColor(ContextCompat.getColor(ctx, mColorRes));\n }\n }",
"private void registerSynchronization(TransactionImpl odmgTrans, Transaction transaction)\r\n {\r\n // todo only need for development\r\n if (odmgTrans == null || transaction == null)\r\n {\r\n log.error(\"One of the given parameters was null --> cannot do synchronization!\" +\r\n \" omdg transaction was null: \" + (odmgTrans == null) +\r\n \", external transaction was null: \" + (transaction == null));\r\n return;\r\n }\r\n\r\n int status = -1; // default status.\r\n try\r\n {\r\n status = transaction.getStatus();\r\n if (status != Status.STATUS_ACTIVE)\r\n {\r\n throw new OJBRuntimeException(\r\n \"Transaction synchronization failed - wrong status of external container tx: \" +\r\n getStatusString(status));\r\n }\r\n }\r\n catch (SystemException e)\r\n {\r\n throw new OJBRuntimeException(\"Can't read status of external tx\", e);\r\n }\r\n\r\n try\r\n {\r\n //Sequence of the following method calls is significant\r\n // 1. register the synchronization with the ODMG notion of a transaction.\r\n transaction.registerSynchronization((J2EETransactionImpl) odmgTrans);\r\n // 2. mark the ODMG transaction as being in a JTA Transaction\r\n // Associate external transaction with the odmg transaction.\r\n txRepository.set(new TxBuffer(odmgTrans, transaction));\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Cannot associate PersistenceBroker with running Transaction\", e);\r\n throw new OJBRuntimeException(\r\n \"Transaction synchronization failed - wrong status of external container tx\", e);\r\n }\r\n }",
"private void initUpperLeftComponent() {\n\n m_upperLeftComponent = new HorizontalLayout();\n m_upperLeftComponent.setHeight(\"100%\");\n m_upperLeftComponent.setSpacing(true);\n m_upperLeftComponent.setDefaultComponentAlignment(Alignment.MIDDLE_RIGHT);\n m_upperLeftComponent.addComponent(m_languageSwitch);\n m_upperLeftComponent.addComponent(m_filePathLabel);\n\n }",
"private void writeResource(Resource mpxj)\n {\n ResourceType xml = m_factory.createResourceType();\n m_apibo.getResource().add(xml);\n\n xml.setAutoComputeActuals(Boolean.TRUE);\n xml.setCalculateCostFromUnits(Boolean.TRUE);\n xml.setCalendarObjectId(getCalendarUniqueID(mpxj.getResourceCalendar()));\n xml.setCurrencyObjectId(DEFAULT_CURRENCY_ID);\n xml.setDefaultUnitsPerTime(Double.valueOf(1.0));\n xml.setEmailAddress(mpxj.getEmailAddress());\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setId(RESOURCE_ID_PREFIX + mpxj.getUniqueID());\n xml.setIsActive(Boolean.TRUE);\n xml.setMaxUnitsPerTime(getPercentage(mpxj.getMaxUnits()));\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setParentObjectId(mpxj.getParentID());\n xml.setResourceNotes(mpxj.getNotes());\n xml.setResourceType(getResourceType(mpxj));\n xml.getUDF().addAll(writeUDFType(FieldTypeClass.RESOURCE, mpxj));\n }",
"public final void setColorPreferred(boolean preferColor) {\n if (this.preferColor.compareAndSet(!preferColor, preferColor) && isRunning()) {\n stop();\n try {\n start();\n } catch (Exception e) {\n logger.error(\"Unexplained exception restarting; we had been running already!\", e);\n }\n }\n }",
"public AbstractVolatilitySurfaceParametric getCloneCalibrated(final AnalyticModel calibrationModel, final Vector<AnalyticProduct> calibrationProducts, final List<Double> calibrationTargetValues, Map<String,Object> calibrationParameters, final ParameterTransformation parameterTransformation, OptimizerFactory optimizerFactory) throws SolverException {\n\t\tif(calibrationParameters == null) {\n\t\t\tcalibrationParameters = new HashMap<>();\n\t\t}\n\t\tInteger maxIterationsParameter\t= (Integer)calibrationParameters.get(\"maxIterations\");\n\t\tDouble\taccuracyParameter\t\t= (Double)calibrationParameters.get(\"accuracy\");\n\t\tDouble\tevaluationTimeParameter\t\t= (Double)calibrationParameters.get(\"evaluationTime\");\n\n\t\t// @TODO currently ignored, we use the setting form the OptimizerFactory\n\t\tint maxIterations\t\t= maxIterationsParameter != null ? maxIterationsParameter.intValue() : 600;\n\t\tdouble accuracy\t\t\t= accuracyParameter != null ? accuracyParameter.doubleValue() : 1E-8;\n\t\tdouble evaluationTime\t= evaluationTimeParameter != null ? evaluationTimeParameter.doubleValue() : 0.0;\n\n\t\tAnalyticModel model = calibrationModel.addVolatilitySurfaces(this);\n\t\tSolver solver = new Solver(model, calibrationProducts, calibrationTargetValues, parameterTransformation, evaluationTime, optimizerFactory);\n\n\t\tSet<ParameterObject> objectsToCalibrate = new HashSet<>();\n\t\tobjectsToCalibrate.add(this);\n\t\tAnalyticModel modelCalibrated = solver.getCalibratedModel(objectsToCalibrate);\n\n\t\t// Diagnostic output\n\t\tif (logger.isLoggable(Level.FINE)) {\n\t\t\tdouble lastAccuracy\t\t= solver.getAccuracy();\n\t\t\tint \tlastIterations\t= solver.getIterations();\n\n\t\t\tlogger.fine(\"The solver achieved an accuracy of \" + lastAccuracy + \" in \" + lastIterations + \".\");\n\t\t}\n\n\t\treturn (AbstractVolatilitySurfaceParametric)modelCalibrated.getVolatilitySurface(this.getName());\n\t}",
"public String getHeaderField(String fieldName) {\n // headers map is null for all regular response calls except when made as a batch request\n if (this.headers == null) {\n if (this.connection != null) {\n return this.connection.getHeaderField(fieldName);\n } else {\n return null;\n }\n } else {\n return this.headers.get(fieldName);\n }\n }"
] |
Add an additional compilation unit into the loop
-> build compilation unit declarations, their bindings and record their results. | [
"@Override\n public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) {\n // Switch the current policy and compilation result for this unit to the requested one.\n CompilationResult unitResult =\n new CompilationResult(sourceUnit, this.totalUnits, this.totalUnits, this.options.maxProblemsPerUnit);\n unitResult.checkSecondaryTypes = true;\n try {\n if (this.options.verbose) {\n String count = String.valueOf(this.totalUnits + 1);\n this.out.println(\n Messages.bind(Messages.compilation_request,\n new String[] {\n count,\n count,\n new String(sourceUnit.getFileName())\n }));\n }\n // diet parsing for large collection of unit\n CompilationUnitDeclaration parsedUnit;\n if (this.totalUnits < this.parseThreshold) {\n parsedUnit = this.parser.parse(sourceUnit, unitResult);\n } else {\n parsedUnit = this.parser.dietParse(sourceUnit, unitResult);\n }\n // initial type binding creation\n this.lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction);\n addCompilationUnit(sourceUnit, parsedUnit);\n\n // binding resolution\n this.lookupEnvironment.completeTypeBindings(parsedUnit);\n } catch (AbortCompilationUnit e) {\n // at this point, currentCompilationUnitResult may not be sourceUnit, but some other\n // one requested further along to resolve sourceUnit.\n if (unitResult.compilationUnit == sourceUnit) { // only report once\n this.requestor.acceptResult(unitResult.tagAsAccepted());\n } else {\n throw e; // want to abort enclosing request to compile\n }\n }\n }"
] | [
"private static X509Certificate getReqSigCert(Message message) {\n\t\tList<WSHandlerResult> results = \n CastUtils.cast((List<?>)\n message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS));\n\n if (results == null) {\n \treturn null;\n }\n \n /*\n\t\t * Scan the results for a matching actor. Use results only if the\n\t\t * receiving Actor and the sending Actor match.\n\t\t */\n\t\tfor (WSHandlerResult rResult : results) {\n\t\t\tList<WSSecurityEngineResult> wsSecEngineResults = rResult\n\t\t\t\t\t.getResults();\n\t\t\t/*\n\t\t\t * Scan the results for the first Signature action. Use the\n\t\t\t * certificate of this Signature to set the certificate for the\n\t\t\t * encryption action :-).\n\t\t\t */\n\t\t\tfor (WSSecurityEngineResult wser : wsSecEngineResults) {\n\t\t\t\tInteger actInt = (Integer) wser\n\t\t\t\t\t\t.get(WSSecurityEngineResult.TAG_ACTION);\n\t\t\t\tif (actInt.intValue() == WSConstants.SIGN) {\n\t\t\t\t\treturn (X509Certificate) wser\n\t\t\t\t\t\t\t.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public static Long getSize(final File file){\n if ( file!=null && file.exists() ){\n return file.length();\n }\n return null;\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 }",
"void checkRmModelConformance() {\n final AmVisitor<AmObject, AmConstraintContext> visitor = AmVisitors.preorder(new ConformanceVisitor());\n ArchetypeWalker.walkConstraints(visitor, archetype, new AmConstraintContext());\n }",
"private static String findOutputPath(String[][] options) {\n\tfor (int i = 0; i < options.length; i++) {\n\t if (options[i][0].equals(\"-d\"))\n\t\treturn options[i][1];\n\t}\n\treturn \".\";\n }",
"public static InputStream getContentStream(String stringUrl) throws MalformedURLException, IOException {\n URL url = new URL(stringUrl);\n \n URLConnection urlConnection = url.openConnection();\n \n InputStream is = urlConnection.getInputStream();\n if (\"gzip\".equals(urlConnection.getContentEncoding())) {\n is = new GZIPInputStream(is);\n }\n\n return is;\n }",
"public void setIntVec(IntBuffer data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input buffer for indices cannot be null\");\n }\n if (getIndexSize() != 4)\n {\n throw new UnsupportedOperationException(\"Cannot update integer indices with short array\");\n }\n if (data.isDirect())\n {\n if (!NativeIndexBuffer.setIntVec(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input array is wrong size\");\n }\n }\n else if (data.hasArray())\n {\n if (!NativeIndexBuffer.setIntArray(getNative(), data.array()))\n {\n throw new IllegalArgumentException(\"Data array incompatible with index buffer\");\n }\n }\n else\n {\n throw new UnsupportedOperationException(\"IntBuffer type not supported. Must be direct or have backing array\");\n }\n }",
"protected float getViewPortSize(final Axis axis) {\n float size = mViewPort == null ? 0 : mViewPort.get(axis);\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"getViewPortSize for %s %f mViewPort = %s\", axis, size, mViewPort);\n return size;\n }",
"public void rollback() throws GeomajasException {\n\t\ttry {\n\t\t\tsetConfigLocations(previousConfigLocations);\n\t\t\trefresh();\n\t\t} catch (Exception e) {\n\t\t\tthrow new GeomajasException(e, ExceptionCode.REFRESH_CONFIGURATION_FAILED);\n\t\t}\n\t}"
] |
Get the service implementations for a given type name.
@param serviceTypeName the type name
@return the possibly empty list of services | [
"public List<String> getServiceImplementations(String serviceTypeName) {\n final List<String> strings = services.get(serviceTypeName);\n return strings == null ? Collections.<String>emptyList() : Collections.unmodifiableList(strings);\n }"
] | [
"public void checkVersion(ZWaveCommandClass commandClass) {\r\n\t\tZWaveVersionCommandClass versionCommandClass = (ZWaveVersionCommandClass)this.getNode().getCommandClass(CommandClass.VERSION);\r\n\t\t\r\n\t\tif (versionCommandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Version command class not supported on node %d,\" +\r\n\t\t\t\t\t\"reverting to version 1 for command class %s (0x%02x)\", \r\n\t\t\t\t\tthis.getNode().getNodeId(), \r\n\t\t\t\t\tcommandClass.getCommandClass().getLabel(), \r\n\t\t\t\t\tcommandClass.getCommandClass().getKey()));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tthis.getController().sendData(versionCommandClass.getCommandClassVersionMessage(commandClass.getCommandClass()));\r\n\t}",
"public static void printDocumentation() {\n\t\tSystem.out\n\t\t\t\t.println(\"********************************************************************\");\n\t\tSystem.out.println(\"*** Wikidata Toolkit: GenderRatioProcessor\");\n\t\tSystem.out.println(\"*** \");\n\t\tSystem.out\n\t\t\t\t.println(\"*** This program will download and process dumps from Wikidata.\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** It will compute the numbers of articles about humans across\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** Wikimedia projects, and in particular it will count the articles\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** for each sex/gender. Results will be stored in a CSV file.\");\n\t\tSystem.out.println(\"*** See source code for further details.\");\n\t\tSystem.out\n\t\t\t\t.println(\"********************************************************************\");\n\t}",
"public void randomize() {\n\t\tnumKnots = 4 + (int)(6*Math.random());\n\t\txKnots = new int[numKnots];\n\t\tyKnots = new int[numKnots];\n\t\tknotTypes = new byte[numKnots];\n\t\tfor (int i = 0; i < numKnots; i++) {\n\t\t\txKnots[i] = (int)(255 * Math.random());\n\t\t\tyKnots[i] = 0xff000000 | ((int)(255 * Math.random()) << 16) | ((int)(255 * Math.random()) << 8) | (int)(255 * Math.random());\n\t\t\tknotTypes[i] = RGB|SPLINE;\n\t\t}\n\t\txKnots[0] = -1;\n\t\txKnots[1] = 0;\n\t\txKnots[numKnots-2] = 255;\n\t\txKnots[numKnots-1] = 256;\n\t\tsortKnots();\n\t\trebuildGradient();\n\t}",
"@Override\n protected void addLineContent(BufferedReader bufferedFileReader, List<String> content, String line) throws IOException {\n // Is the line an empty comment \"#\" ?\n if (line.startsWith(COMMENT_PREFIX) && line.length() == 1) {\n String nextLine = bufferedFileReader.readLine();\n if (nextLine != null) {\n // Is the next line the realm name \"#$REALM_NAME=\" ?\n if (nextLine.startsWith(COMMENT_PREFIX) && nextLine.contains(REALM_COMMENT_PREFIX)) {\n // Realm name block detected!\n // The next line must be and empty comment \"#\"\n bufferedFileReader.readLine();\n // Avoid adding the realm block\n } else {\n // It's a user comment...\n content.add(line);\n content.add(nextLine);\n }\n } else {\n super.addLineContent(bufferedFileReader, content, line);\n }\n } else {\n super.addLineContent(bufferedFileReader, content, line);\n }\n }",
"public static Platform detect() throws UnsupportedPlatformException {\n String osArch = getProperty(\"os.arch\");\n String osName = getProperty(\"os.name\");\n\n for (Arch arch : Arch.values()) {\n if (arch.pattern.matcher(osArch).matches()) {\n for (OS os : OS.values()) {\n if (os.pattern.matcher(osName).matches()) {\n return new Platform(arch, os);\n }\n }\n }\n }\n\n String msg = String.format(\"Unsupported platform %s %s\", osArch, osName);\n throw new UnsupportedPlatformException(msg);\n }",
"public static ModelNode createBootUpdates(final String serverName, final ModelNode domainModel, final ModelNode hostModel,\n final DomainController domainController, final ExpressionResolver expressionResolver) {\n final ManagedServerOperationsFactory factory = new ManagedServerOperationsFactory(serverName, domainModel,\n hostModel, domainController, expressionResolver);\n\n\n return factory.getBootUpdates();\n }",
"public String lookupUser(String url) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LOOKUP_USER);\r\n\r\n parameters.put(\"url\", url);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element payload = response.getPayload();\r\n Element groupnameElement = (Element) payload.getElementsByTagName(\"username\").item(0);\r\n return ((Text) groupnameElement.getFirstChild()).getData();\r\n }",
"public String updateClassification(String classificationType) {\n Metadata metadata = new Metadata(\"enterprise\", Metadata.CLASSIFICATION_TEMPLATE_KEY);\n metadata.add(\"/Box__Security__Classification__Key\", classificationType);\n Metadata classification = this.updateMetadata(metadata);\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }",
"public void release(Contextual<T> contextual, T instance) {\n synchronized (dependentInstances) {\n for (ContextualInstance<?> dependentInstance : dependentInstances) {\n // do not destroy contextual again, since it's just being destroyed\n if (contextual == null || !(dependentInstance.getContextual().equals(contextual))) {\n destroy(dependentInstance);\n }\n }\n }\n if (resourceReferences != null) {\n for (ResourceReference<?> reference : resourceReferences) {\n reference.release();\n }\n }\n }"
] |
of the unbound provider ( | [
"public synchronized T get(Scope scope) {\n if (instance != null) {\n return instance;\n }\n\n if (providerInstance != null) {\n if (isProvidingSingletonInScope) {\n instance = providerInstance.get();\n //gc\n providerInstance = null;\n return instance;\n }\n\n return providerInstance.get();\n }\n\n if (factoryClass != null && factory == null) {\n factory = FactoryLocator.getFactory(factoryClass);\n //gc\n factoryClass = null;\n }\n\n if (factory != null) {\n if (!factory.hasScopeAnnotation() && !isCreatingSingletonInScope) {\n return factory.createInstance(scope);\n }\n instance = factory.createInstance(scope);\n //gc\n factory = null;\n return instance;\n }\n\n if (providerFactoryClass != null && providerFactory == null) {\n providerFactory = FactoryLocator.getFactory(providerFactoryClass);\n //gc\n providerFactoryClass = null;\n }\n\n if (providerFactory != null) {\n if (providerFactory.hasProvidesSingletonInScopeAnnotation() || isProvidingSingletonInScope) {\n instance = providerFactory.createInstance(scope).get();\n //gc\n providerFactory = null;\n return instance;\n }\n if (providerFactory.hasScopeAnnotation() || isCreatingSingletonInScope) {\n providerInstance = providerFactory.createInstance(scope);\n //gc\n providerFactory = null;\n return providerInstance.get();\n }\n\n return providerFactory.createInstance(scope).get();\n }\n\n throw new IllegalStateException(\"A provider can only be used with an instance, a provider, a factory or a provider factory. Should not happen.\");\n }"
] | [
"synchronized ArrayList<CTMessageDAO> getMessages(String userId){\n final String tName = Table.INBOX_MESSAGES.getName();\n Cursor cursor;\n ArrayList<CTMessageDAO> messageDAOArrayList = new ArrayList<>();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n cursor= db.rawQuery(\"SELECT * FROM \"+tName+\" WHERE \" + USER_ID + \" = ? ORDER BY \" + KEY_CREATED_AT+ \" DESC\", new String[]{userId});\n if(cursor != null) {\n while(cursor.moveToNext()){\n CTMessageDAO ctMessageDAO = new CTMessageDAO();\n ctMessageDAO.setId(cursor.getString(cursor.getColumnIndex(_ID)));\n ctMessageDAO.setJsonData(new JSONObject(cursor.getString(cursor.getColumnIndex(KEY_DATA))));\n ctMessageDAO.setWzrkParams(new JSONObject(cursor.getString(cursor.getColumnIndex(WZRKPARAMS))));\n ctMessageDAO.setDate(cursor.getLong(cursor.getColumnIndex(KEY_CREATED_AT)));\n ctMessageDAO.setExpires(cursor.getLong(cursor.getColumnIndex(EXPIRES)));\n ctMessageDAO.setRead(cursor.getInt(cursor.getColumnIndex(IS_READ)));\n ctMessageDAO.setUserId(cursor.getString(cursor.getColumnIndex(USER_ID)));\n ctMessageDAO.setTags(cursor.getString(cursor.getColumnIndex(TAGS)));\n ctMessageDAO.setCampaignId(cursor.getString(cursor.getColumnIndex(CAMPAIGN)));\n messageDAOArrayList.add(ctMessageDAO);\n }\n cursor.close();\n }\n return messageDAOArrayList;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e);\n return null;\n } catch (JSONException e) {\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e.getMessage());\n return null;\n } finally {\n dbHelper.close();\n }\n }",
"public static appfwhtmlerrorpage get(nitro_service service, String name) throws Exception{\n\t\tappfwhtmlerrorpage obj = new appfwhtmlerrorpage();\n\t\tobj.set_name(name);\n\t\tappfwhtmlerrorpage response = (appfwhtmlerrorpage) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private String getCacheFormatEntry() throws IOException {\n ZipEntry zipEntry = zipFile.getEntry(CACHE_FORMAT_ENTRY);\n InputStream is = zipFile.getInputStream(zipEntry);\n try {\n Scanner s = new Scanner(is, \"UTF-8\").useDelimiter(\"\\\\A\");\n String tag = null;\n if (s.hasNext()) tag = s.next();\n return tag;\n } finally {\n is.close();\n }\n }",
"public static authenticationradiuspolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiuspolicy_vpnglobal_binding obj = new authenticationradiuspolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationradiuspolicy_vpnglobal_binding response[] = (authenticationradiuspolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public File getTargetFile(final MiscContentItem item) {\n final State state = this.state;\n if (state == State.NEW || state == State.ROLLBACK_ONLY) {\n return getTargetFile(miscTargetRoot, item);\n } else {\n throw new IllegalStateException(); // internal wrong usage, no i18n\n }\n }",
"public DJCrosstab build(){\r\n\t\tif (crosstab.getMeasures().isEmpty()){\r\n\t\t\tthrow new LayoutException(\"Crosstabs must have at least one measure\");\r\n\t\t}\r\n\t\tif (crosstab.getColumns().isEmpty()){\r\n\t\t\tthrow new LayoutException(\"Crosstabs must have at least one column\");\r\n\t\t}\r\n\t\tif (crosstab.getRows().isEmpty()){\r\n\t\t\tthrow new LayoutException(\"Crosstabs must have at least one row\");\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\t//Ensure default dimension values\r\n\t\tfor (DJCrosstabColumn col : crosstab.getColumns()) {\r\n\t\t\tif (col.getWidth() == -1 && cellWidth != -1)\r\n\t\t\t\tcol.setWidth(cellWidth);\r\n\r\n\t\t\tif (col.getWidth() == -1 )\r\n\t\t\t\tcol.setWidth(DEFAULT_CELL_WIDTH);\r\n\r\n\t\t\tif (col.getHeaderHeight() == -1 && columnHeaderHeight != -1)\r\n\t\t\t\tcol.setHeaderHeight(columnHeaderHeight);\r\n\r\n\t\t\tif (col.getHeaderHeight() == -1)\r\n\t\t\t\tcol.setHeaderHeight(DEFAULT_COLUMN_HEADER_HEIGHT);\r\n\t\t}\r\n\r\n\t\tfor (DJCrosstabRow row : crosstab.getRows()) {\r\n\t\t\tif (row.getHeight() == -1 && cellHeight != -1)\r\n\t\t\t\trow.setHeight(cellHeight);\r\n\r\n\t\t\tif (row.getHeight() == -1 )\r\n\t\t\t\trow.setHeight(DEFAULT_CELL_HEIGHT);\r\n\r\n\t\t\tif (row.getHeaderWidth() == -1 && rowHeaderWidth != -1)\r\n\t\t\t\trow.setHeaderWidth(rowHeaderWidth);\r\n\r\n\t\t\tif (row.getHeaderWidth() == -1)\r\n\t\t\t\trow.setHeaderWidth(DEFAULT_ROW_HEADER_WIDTH);\r\n\r\n\t\t}\r\n\t\treturn crosstab;\r\n\t}",
"@Override\n public void setJobQueue(int jobId, Queue queue)\n {\n JqmClientFactory.getClient().setJobQueue(jobId, queue);\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 PhotoList<Photo> getPhotos(String groupId, String userId, String[] tags, Set<String> extras, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PHOTOS);\r\n\r\n parameters.put(\"group_id\", groupId);\r\n if (userId != null) {\r\n parameters.put(\"user_id\", userId);\r\n }\r\n if (tags != null) {\r\n parameters.put(\"tags\", StringUtilities.join(tags, \" \"));\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", String.valueOf(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", String.valueOf(page));\r\n }\r\n\r\n if (extras != null) {\r\n StringBuffer sb = new StringBuffer();\r\n Iterator<String> it = extras.iterator();\r\n for (int i = 0; it.hasNext(); i++) {\r\n if (i > 0) {\r\n sb.append(\",\");\r\n }\r\n sb.append(it.next());\r\n }\r\n parameters.put(Extras.KEY_EXTRAS, sb.toString());\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n\r\n return photos;\r\n }"
] |
Set the permission for who may view the geo data associated with a photo.
This method requires authentication with 'write' permission.
@param photoId
The id of the photo to set permissions for.
@param perms
Permissions, who can see the geo data of this photo
@throws FlickrException | [
"public void setPerms(String photoId, GeoPermissions perms) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_PERMS);\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"is_public\", perms.isPublic() ? \"1\" : \"0\");\r\n parameters.put(\"is_contact\", perms.isContact() ? \"1\" : \"0\");\r\n parameters.put(\"is_friend\", perms.isFriend() ? \"1\" : \"0\");\r\n parameters.put(\"is_family\", perms.isFamily() ? \"1\" : \"0\");\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n // This method has no specific response - It returns an empty sucess response\r\n // if it completes without error.\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }"
] | [
"protected <T, A> ActiveOperation<T, A> removeActiveOperation(Integer id) {\n final ActiveOperation<T, A> removed = removeUnderLock(id);\n if(removed != null) {\n for(final Map.Entry<Integer, ActiveRequest<?, ?>> requestEntry : requests.entrySet()) {\n final ActiveRequest<?, ?> request = requestEntry.getValue();\n if(request.context == removed) {\n requests.remove(requestEntry.getKey());\n }\n }\n }\n return removed;\n }",
"@SafeVarargs\n\tpublic static <T> Set<T> asSet(T... ts) {\n\t\tif ( ts == null ) {\n\t\t\treturn null;\n\t\t}\n\t\telse if ( ts.length == 0 ) {\n\t\t\treturn Collections.emptySet();\n\t\t}\n\t\telse {\n\t\t\tSet<T> set = new HashSet<T>( getInitialCapacityFromExpectedSize( ts.length ) );\n\t\t\tCollections.addAll( set, ts );\n\t\t\treturn Collections.unmodifiableSet( set );\n\t\t}\n\t}",
"public static final TimeUnit getTimeUnit(int value)\n {\n TimeUnit result = null;\n\n switch (value)\n {\n case 1:\n {\n // Appears to mean \"use the document format\"\n result = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 2:\n {\n result = TimeUnit.HOURS;\n break;\n }\n\n case 4:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 6:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 8:\n case 10:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n {\n result = TimeUnit.YEARS;\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return result;\n }",
"public void adjustGlassSize() {\n if (isGlassEnabled()) {\n ResizeHandler handler = getGlassResizer();\n if (handler != null) handler.onResize(null);\n }\n }",
"public void setKnotType(int n, int type) {\n\t\tknotTypes[n] = (byte)((knotTypes[n] & ~COLOR_MASK) | type);\n\t\trebuildGradient();\n\t}",
"private static String makeAsciiTableCell(Object obj, int padLeft, int padRight, boolean tsv) {\r\n String result = obj.toString();\r\n if (padLeft > 0) {\r\n result = padLeft(result, padLeft);\r\n }\r\n if (padRight > 0) {\r\n result = pad(result, padRight);\r\n }\r\n if (tsv) {\r\n result = result + '\\t';\r\n }\r\n return result;\r\n }",
"public static void setEnabled(Element element, boolean enabled) {\n element.setPropertyBoolean(\"disabled\", !enabled);\n\tsetStyleName(element, \"disabled\", !enabled);\n }",
"public int getTotalLeased(){\r\n\t\tint total=0;\r\n\t\tfor (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){\r\n\t\t\ttotal+=this.partitions[i].getCreatedConnections()-this.partitions[i].getAvailableConnections();\r\n\t\t}\r\n\t\treturn total;\r\n\t}",
"private static void reallyValidatePseudoScopedBean(Bean<?> bean, BeanManagerImpl beanManager, Set<Object> dependencyPath, Set<Bean<?>> validatedBeans) {\n // see if we have already seen this bean in the dependency path\n if (dependencyPath.contains(bean)) {\n // create a list that shows the path to the bean\n List<Object> realDependencyPath = new ArrayList<Object>(dependencyPath);\n realDependencyPath.add(bean);\n throw ValidatorLogger.LOG.pseudoScopedBeanHasCircularReferences(WeldCollections.toMultiRowString(realDependencyPath));\n }\n if (validatedBeans.contains(bean)) {\n return;\n }\n dependencyPath.add(bean);\n for (InjectionPoint injectionPoint : bean.getInjectionPoints()) {\n if (!injectionPoint.isDelegate()) {\n dependencyPath.add(injectionPoint);\n validatePseudoScopedInjectionPoint(injectionPoint, beanManager, dependencyPath, validatedBeans);\n dependencyPath.remove(injectionPoint);\n }\n }\n if (bean instanceof DecorableBean<?>) {\n final List<Decorator<?>> decorators = Reflections.<DecorableBean<?>>cast(bean).getDecorators();\n if (!decorators.isEmpty()) {\n for (final Decorator<?> decorator : decorators) {\n reallyValidatePseudoScopedBean(decorator, beanManager, dependencyPath, validatedBeans);\n }\n }\n }\n if (bean instanceof AbstractProducerBean<?, ?, ?> && !(bean instanceof EEResourceProducerField<?, ?>)) {\n AbstractProducerBean<?, ?, ?> producer = (AbstractProducerBean<?, ?, ?>) bean;\n if (!beanManager.isNormalScope(producer.getDeclaringBean().getScope()) && !producer.getAnnotated().isStatic()) {\n reallyValidatePseudoScopedBean(producer.getDeclaringBean(), beanManager, dependencyPath, validatedBeans);\n }\n }\n validatedBeans.add(bean);\n dependencyPath.remove(bean);\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.