query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Attempt to resolve the given expression string, recursing if resolution of one string produces another expression. @param expressionString the expression string from a node of {@link ModelType#EXPRESSION} @param ignoreDMRResolutionFailure {@code false} if {@link org.jboss.dmr.ModelNode#resolve() basic DMR resolution} failures should be ignored, and {@code new ModelNode(expressionType.asString())} returned @param initial {@code true} if this call originated outside this method; {@code false} if it is a recursive call @return a node of {@link ModelType#STRING} where the encapsulated string is the resolved expression, or a node of {@link ModelType#EXPRESSION} if {@code ignoreDMRResolutionFailure} and {@code initial} are {@code true} and the string could not be resolved. @throws OperationFailedException if the expression cannot be resolved
[ "private ModelNode resolveExpressionStringRecursively(final String expressionString, final boolean ignoreDMRResolutionFailure,\n final boolean initial) throws OperationFailedException {\n ParseAndResolveResult resolved = parseAndResolve(expressionString, ignoreDMRResolutionFailure);\n if (resolved.recursive) {\n // Some part of expressionString resolved into a different expression.\n // So, start over, ignoring failures. Ignore failures because we don't require\n // that expressions must not resolve to something that *looks like* an expression but isn't\n return resolveExpressionStringRecursively(resolved.result, true, false);\n } else if (resolved.modified) {\n // Typical case\n return new ModelNode(resolved.result);\n } else if (initial && EXPRESSION_PATTERN.matcher(expressionString).matches()) {\n // We should only get an unmodified expression string back if there was a resolution\n // failure that we ignored.\n assert ignoreDMRResolutionFailure;\n // expressionString came from a node of type expression, so since we did nothing send it back in the same type\n return new ModelNode(new ValueExpression(expressionString));\n } else {\n // The string wasn't really an expression. Two possible cases:\n // 1) if initial == true, someone created a expression node with a non-expression string, which is legal\n // 2) if initial == false, we resolved from an ModelType.EXPRESSION to a string that looked like an\n // expression but can't be resolved. We don't require that expressions must not resolve to something that\n // *looks like* an expression but isn't, so we'll just treat this as a string\n return new ModelNode(expressionString);\n }\n }" ]
[ "private void checkCollectionForeignkeys(ModelDef modelDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n ClassDescriptorDef classDef;\r\n CollectionDescriptorDef collDef;\r\n\r\n for (Iterator it = modelDef.getClasses(); it.hasNext();)\r\n {\r\n classDef = (ClassDescriptorDef)it.next();\r\n for (Iterator collIt = classDef.getCollections(); collIt.hasNext();)\r\n {\r\n collDef = (CollectionDescriptorDef)collIt.next();\r\n if (!collDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE))\r\n {\r\n checkIndirectionTable(modelDef, collDef);\r\n }\r\n else\r\n { \r\n checkCollectionForeignkeys(modelDef, collDef);\r\n }\r\n }\r\n }\r\n }\r\n }", "public ResponseOnSingeRequest genErrorResponse(Exception t) {\n ResponseOnSingeRequest sshResponse = new ResponseOnSingeRequest();\n String displayError = PcErrorMsgUtils.replaceErrorMsg(t.toString());\n\n sshResponse.setStackTrace(PcStringUtils.printStackTrace(t));\n sshResponse.setErrorMessage(displayError);\n sshResponse.setFailObtainResponse(true);\n\n logger.error(\"error in exec SSH. \\nIf exection is JSchException: \"\n + \"Auth cancel and using public key. \"\n + \"\\nMake sure 1. private key full path is right (try sshMeta.getPrivKeyAbsPath()). \"\n + \"\\n2. the user name and key matches \" + t);\n\n return sshResponse;\n }", "public void downloadRange(OutputStream output, long rangeStart, long rangeEnd, ProgressListener listener) {\n URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n if (rangeEnd > 0) {\n request.addHeader(\"Range\", String.format(\"bytes=%s-%s\", Long.toString(rangeStart),\n Long.toString(rangeEnd)));\n } else {\n request.addHeader(\"Range\", String.format(\"bytes=%s-\", Long.toString(rangeStart)));\n }\n\n BoxAPIResponse response = request.send();\n InputStream input = response.getBody(listener);\n\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = input.read(buffer);\n while (n != -1) {\n output.write(buffer, 0, n);\n n = input.read(buffer);\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Couldn't connect to the Box API due to a network error.\", e);\n } finally {\n response.disconnect();\n }\n }", "public void setProxy(String proxyHost, int proxyPort, String username, String password) {\n setProxy(proxyHost, proxyPort);\n proxyAuth = true;\n proxyUser = username;\n proxyPassword = password;\n }", "private void populateExpandedExceptions()\n {\n if (!m_exceptions.isEmpty() && m_expandedExceptions.isEmpty())\n {\n for (ProjectCalendarException exception : m_exceptions)\n {\n RecurringData recurring = exception.getRecurring();\n if (recurring == null)\n {\n m_expandedExceptions.add(exception);\n }\n else\n {\n for (Date date : recurring.getDates())\n {\n Date startDate = DateHelper.getDayStartDate(date);\n Date endDate = DateHelper.getDayEndDate(date);\n ProjectCalendarException newException = new ProjectCalendarException(startDate, endDate);\n int rangeCount = exception.getRangeCount();\n for (int rangeIndex = 0; rangeIndex < rangeCount; rangeIndex++)\n {\n newException.addRange(exception.getRange(rangeIndex));\n }\n m_expandedExceptions.add(newException);\n }\n }\n }\n Collections.sort(m_expandedExceptions);\n }\n }", "public boolean merge(AbstractTransition another) {\n if (!isCompatible(another)) {\n return false;\n }\n if (another.mId != null) {\n if (mId == null) {\n mId = another.mId;\n } else {\n StringBuilder sb = new StringBuilder(mId.length() + another.mId.length());\n sb.append(mId);\n sb.append(\"_MERGED_\");\n sb.append(another.mId);\n mId = sb.toString();\n }\n }\n mUpdateStateAfterUpdateProgress |= another.mUpdateStateAfterUpdateProgress;\n mSetupList.addAll(another.mSetupList);\n Collections.sort(mSetupList, new Comparator<S>() {\n @Override\n public int compare(S lhs, S rhs) {\n if (lhs instanceof AbstractTransitionBuilder && rhs instanceof AbstractTransitionBuilder) {\n AbstractTransitionBuilder left = (AbstractTransitionBuilder) lhs;\n AbstractTransitionBuilder right = (AbstractTransitionBuilder) rhs;\n float startLeft = left.mReverse ? left.mEnd : left.mStart;\n float startRight = right.mReverse ? right.mEnd : right.mStart;\n return (int) ((startRight - startLeft) * 1000);\n }\n return 0;\n }\n });\n\n return true;\n }", "private void createSimpleCubeSixMeshes(GVRContext gvrContext,\n boolean facingOut, String vertexDesc, ArrayList<GVRTexture> textureList)\n {\n GVRSceneObject[] children = new GVRSceneObject[6];\n GVRMesh[] meshes = new GVRMesh[6];\n GVRVertexBuffer vbuf = new GVRVertexBuffer(gvrContext, vertexDesc, SIMPLE_VERTICES.length / 3);\n\n if (facingOut)\n {\n vbuf.setFloatArray(\"a_position\", SIMPLE_VERTICES, 3, 0);\n vbuf.setFloatArray(\"a_normal\", SIMPLE_OUTWARD_NORMALS, 3, 0);\n vbuf.setFloatArray(\"a_texcoord\", SIMPLE_OUTWARD_TEXCOORDS, 2, 0);\n meshes[0] = createMesh(vbuf, SIMPLE_OUTWARD_FRONT_INDICES);\n meshes[1] = createMesh(vbuf, SIMPLE_OUTWARD_RIGHT_INDICES);\n meshes[2] = createMesh(vbuf, SIMPLE_OUTWARD_BACK_INDICES);\n meshes[3] = createMesh(vbuf, SIMPLE_OUTWARD_LEFT_INDICES);\n meshes[4] = createMesh(vbuf, SIMPLE_OUTWARD_TOP_INDICES);\n meshes[5] = createMesh(vbuf, SIMPLE_OUTWARD_BOTTOM_INDICES);\n }\n else\n {\n vbuf.setFloatArray(\"a_position\", SIMPLE_VERTICES, 3, 0);\n vbuf.setFloatArray(\"a_normal\", SIMPLE_INWARD_NORMALS, 3, 0);\n vbuf.setFloatArray(\"a_texcoord\", SIMPLE_INWARD_TEXCOORDS, 2, 0);\n meshes[0] = createMesh(vbuf, SIMPLE_INWARD_FRONT_INDICES);\n meshes[1] = createMesh(vbuf, SIMPLE_INWARD_RIGHT_INDICES);\n meshes[2] = createMesh(vbuf, SIMPLE_INWARD_BACK_INDICES);\n meshes[3] = createMesh(vbuf, SIMPLE_INWARD_LEFT_INDICES);\n meshes[4] = createMesh(vbuf, SIMPLE_INWARD_TOP_INDICES);\n meshes[5] = createMesh(vbuf, SIMPLE_INWARD_BOTTOM_INDICES);\n }\n\n for (int i = 0; i < 6; i++)\n {\n children[i] = new GVRSceneObject(gvrContext, meshes[i], textureList.get(i));\n addChildObject(children[i]);\n }\n\n // attached an empty renderData for parent object, so that we can set some common properties\n GVRRenderData renderData = new GVRRenderData(gvrContext);\n attachRenderData(renderData);\n }", "@Override\n public void removeCapabilityRequirement(RuntimeRequirementRegistration requirementRegistration) {\n // We don't know if this got registered as an runtime-only requirement or a hard one\n // so clean it from both maps\n writeLock.lock();\n try {\n removeRequirement(requirementRegistration, false);\n removeRequirement(requirementRegistration, true);\n } finally {\n writeLock.unlock();\n }\n }", "public void addFile(File file) {\n String name = \"file\";\n files.put(normalizeDuplicateName(name), file);\n }" ]
Copy the contents of this buffer to the destination LBuffer @param srcOffset @param dest @param destOffset @param size
[ "public void copyTo(long srcOffset, LBufferAPI dest, long destOffset, long size) {\n unsafe.copyMemory(address() + srcOffset, dest.address() + destOffset, size);\n }" ]
[ "@SuppressWarnings(\"unchecked\")\n public static Map<String, Properties> readMultipleClientConfigAvro(String configAvro) {\n Map<String, Properties> mapStoreToProps = Maps.newHashMap();\n try {\n JsonDecoder decoder = new JsonDecoder(CLIENT_CONFIGS_AVRO_SCHEMA, configAvro);\n GenericDatumReader<Object> datumReader = new GenericDatumReader<Object>(CLIENT_CONFIGS_AVRO_SCHEMA);\n\n Map<Utf8, Map<Utf8, Utf8>> storeConfigs = (Map<Utf8, Map<Utf8, Utf8>>) datumReader.read(null,\n decoder);\n // Store config props to return back\n for(Utf8 storeName: storeConfigs.keySet()) {\n Properties props = new Properties();\n Map<Utf8, Utf8> singleConfig = storeConfigs.get(storeName);\n\n for(Utf8 key: singleConfig.keySet()) {\n props.put(key.toString(), singleConfig.get(key).toString());\n }\n\n if(storeName == null || storeName.length() == 0) {\n throw new Exception(\"Invalid store name found!\");\n }\n\n mapStoreToProps.put(storeName.toString(), props);\n }\n } catch(Exception e) {\n e.printStackTrace();\n }\n return mapStoreToProps;\n }", "public static base_response add(nitro_service client, nsip6 resource) throws Exception {\n\t\tnsip6 addresource = new nsip6();\n\t\taddresource.ipv6address = resource.ipv6address;\n\t\taddresource.scope = resource.scope;\n\t\taddresource.type = resource.type;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.nd = resource.nd;\n\t\taddresource.icmp = resource.icmp;\n\t\taddresource.vserver = resource.vserver;\n\t\taddresource.telnet = resource.telnet;\n\t\taddresource.ftp = resource.ftp;\n\t\taddresource.gui = resource.gui;\n\t\taddresource.ssh = resource.ssh;\n\t\taddresource.snmp = resource.snmp;\n\t\taddresource.mgmtaccess = resource.mgmtaccess;\n\t\taddresource.restrictaccess = resource.restrictaccess;\n\t\taddresource.dynamicrouting = resource.dynamicrouting;\n\t\taddresource.hostroute = resource.hostroute;\n\t\taddresource.ip6hostrtgw = resource.ip6hostrtgw;\n\t\taddresource.metric = resource.metric;\n\t\taddresource.vserverrhilevel = resource.vserverrhilevel;\n\t\taddresource.ospf6lsatype = resource.ospf6lsatype;\n\t\taddresource.ospfarea = resource.ospfarea;\n\t\taddresource.state = resource.state;\n\t\taddresource.map = resource.map;\n\t\taddresource.ownernode = resource.ownernode;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}", "public ParallelTaskBuilder prepareHttpDelete(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n\n cb.getHttpMeta().setHttpMethod(HttpMethod.DELETE);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }", "public void setOffset(float offset, final Axis axis) {\n if (!equal(mOffset.get(axis), offset)) {\n mOffset.set(offset, axis);\n if (mContainer != null) {\n mContainer.onLayoutChanged(this);\n }\n }\n }", "protected String sp_createSequenceQuery(String sequenceName, long maxKey)\r\n {\r\n return \"insert into \" + SEQ_TABLE_NAME + \" (\"\r\n + SEQ_NAME_STRING + \",\" + SEQ_ID_STRING +\r\n \") values ('\" + sequenceName + \"',\" + maxKey + \")\";\r\n }", "public static IndexedContainer getGroupsOfUser(\n CmsObject cms,\n CmsUser user,\n String caption,\n String iconProp,\n String ou,\n String propStatus,\n Function<CmsGroup, CmsCssIcon> iconProvider) {\n\n IndexedContainer container = new IndexedContainer();\n container.addContainerProperty(caption, String.class, \"\");\n container.addContainerProperty(ou, String.class, \"\");\n container.addContainerProperty(propStatus, Boolean.class, new Boolean(true));\n if (iconProvider != null) {\n container.addContainerProperty(iconProp, CmsCssIcon.class, null);\n }\n try {\n for (CmsGroup group : cms.getGroupsOfUser(user.getName(), true)) {\n Item item = container.addItem(group);\n item.getItemProperty(caption).setValue(group.getSimpleName());\n item.getItemProperty(ou).setValue(group.getOuFqn());\n if (iconProvider != null) {\n item.getItemProperty(iconProp).setValue(iconProvider.apply(group));\n }\n }\n } catch (CmsException e) {\n LOG.error(\"Unable to read groups from user\", e);\n }\n return container;\n }", "static void setSingleParam(String key, String value, DbConn cnx)\n {\n QueryResult r = cnx.runUpdate(\"globalprm_update_value_by_key\", value, key);\n if (r.nbUpdated == 0)\n {\n cnx.runUpdate(\"globalprm_insert\", key, value);\n }\n cnx.commit();\n }", "public List<Throwable> getCauses(Throwable t)\n {\n List<Throwable> causes = new LinkedList<Throwable>();\n Throwable next = t;\n while (next.getCause() != null)\n {\n next = next.getCause();\n causes.add(next);\n }\n return causes;\n }", "public BoneCP getPool() {\r\n\t\tFinalWrapper<BoneCP> wrapper = this.pool;\r\n\t\treturn wrapper == null ? null : wrapper.value;\r\n\t}" ]
Checks the preconditions for creating a new Truncate processor. @param maxSize the maximum size of the String @param suffix the String to append if the input is truncated (e.g. "...") @throws IllegalArgumentException if {@code maxSize <= 0} @throws NullPointerException if suffix is null
[ "private static void checkPreconditions(final int maxSize, final String suffix) {\n\t\tif( maxSize <= 0 ) {\n\t\t\tthrow new IllegalArgumentException(String.format(\"maxSize should be > 0 but was %d\", maxSize));\n\t\t}\n\t\tif( suffix == null ) {\n\t\t\tthrow new NullPointerException(\"suffix should not be null\");\n\t\t}\n\t}" ]
[ "public String getName() {\n if (name == null && securityIdentity != null) {\n name = securityIdentity.getPrincipal().getName();\n }\n\n return name;\n }", "private String safeToString(Object obj)\r\n\t{\r\n\t\tString toString = null;\r\n\t\tif (obj != null)\r\n\t\t{\r\n\t\t try\r\n\t\t {\r\n\t\t toString = obj.toString();\r\n\t\t }\r\n\t\t catch (Throwable ex)\r\n\t\t {\r\n\t\t toString = \"BAD toString() impl for \" + obj.getClass().getName();\r\n\t\t }\r\n\t\t}\r\n\t\treturn toString;\r\n\t}", "public static ComplexNumber Function2D(int x, int y, double wavelength, double orientation, double phaseOffset, double gaussVariance, double aspectRatio) {\n\n double X = x * Math.cos(orientation) + y * Math.sin(orientation);\n double Y = -x * Math.sin(orientation) + y * Math.cos(orientation);\n\n double envelope = Math.exp(-((X * X + aspectRatio * aspectRatio * Y * Y) / (2 * gaussVariance * gaussVariance)));\n double real = Math.cos(2 * Math.PI * (X / wavelength) + phaseOffset);\n double imaginary = Math.sin(2 * Math.PI * (X / wavelength) + phaseOffset);\n\n return new ComplexNumber(envelope * real, envelope * imaginary);\n }", "public com.cloudant.client.api.model.ReplicationResult trigger() {\r\n ReplicationResult couchDbReplicationResult = replication.trigger();\r\n com.cloudant.client.api.model.ReplicationResult replicationResult = new com.cloudant\r\n .client.api.model.ReplicationResult(couchDbReplicationResult);\r\n return replicationResult;\r\n }", "public boolean verify(String signatureVersion, String signatureAlgorithm, String primarySignature,\n String secondarySignature, String webHookPayload, String deliveryTimestamp) {\n\n // enforce versions supported by this implementation\n if (!SUPPORTED_VERSIONS.contains(signatureVersion)) {\n return false;\n }\n\n // enforce algorithms supported by this implementation\n BoxSignatureAlgorithm algorithm = BoxSignatureAlgorithm.byName(signatureAlgorithm);\n if (!SUPPORTED_ALGORITHMS.contains(algorithm)) {\n return false;\n }\n\n // check primary key signature if primary key exists\n if (this.primarySignatureKey != null && this.verify(this.primarySignatureKey, algorithm, primarySignature,\n webHookPayload, deliveryTimestamp)) {\n return true;\n }\n\n // check secondary key signature if secondary key exists\n if (this.secondarySignatureKey != null && this.verify(this.secondarySignatureKey, algorithm, secondarySignature,\n webHookPayload, deliveryTimestamp)) {\n return true;\n }\n\n // default strategy is false, to minimize security issues\n return false;\n }", "public static int rank(SingularValueDecomposition_F64 svd , double threshold ) {\n int numRank=0;\n\n double w[]= svd.getSingularValues();\n\n int N = svd.numberOfSingularValues();\n\n for( int j = 0; j < N; j++ ) {\n if( w[j] > threshold)\n numRank++;\n }\n\n return numRank;\n }", "protected void mergeSameWork(LinkedList<TimephasedWork> list)\n {\n LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();\n\n TimephasedWork previousAssignment = null;\n for (TimephasedWork assignment : list)\n {\n if (previousAssignment == null)\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n result.add(assignment);\n }\n else\n {\n Duration previousAssignmentWork = previousAssignment.getAmountPerDay();\n Duration assignmentWork = assignment.getTotalAmount();\n\n if (NumberHelper.equals(previousAssignmentWork.getDuration(), assignmentWork.getDuration(), 0.01))\n {\n Date assignmentStart = previousAssignment.getStart();\n Date assignmentFinish = assignment.getFinish();\n double total = previousAssignment.getTotalAmount().getDuration();\n total += assignmentWork.getDuration();\n Duration totalWork = Duration.getInstance(total, TimeUnit.MINUTES);\n\n TimephasedWork merged = new TimephasedWork();\n merged.setStart(assignmentStart);\n merged.setFinish(assignmentFinish);\n merged.setAmountPerDay(assignmentWork);\n merged.setTotalAmount(totalWork);\n\n result.removeLast();\n assignment = merged;\n }\n else\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n }\n result.add(assignment);\n }\n\n previousAssignment = assignment;\n }\n\n list.clear();\n list.addAll(result);\n }", "public CollectionRequest<Project> findByTeam(String team) {\n \n String path = String.format(\"/teams/%s/projects\", team);\n return new CollectionRequest<Project>(this, Project.class, path, \"GET\");\n }", "public static String getCountryCodeAndCheckDigit(final String iban) {\n return iban.substring(COUNTRY_CODE_INDEX,\n COUNTRY_CODE_INDEX + COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH);\n }" ]
Map the currency separator character to a symbol name. @param c currency separator character @return symbol name
[ "private String getSymbolName(char c)\n {\n String result = null;\n\n switch (c)\n {\n case ',':\n {\n result = \"Comma\";\n break;\n }\n\n case '.':\n {\n result = \"Period\";\n break;\n }\n }\n\n return result;\n }" ]
[ "@Override\n\tpublic void Invoke(final String method, JSONArray args,\n\t\t\tHubInvokeCallback callback) {\n\n\t\tif (method == null)\n {\n throw new IllegalArgumentException(\"method\");\n }\n\n if (args == null)\n {\n throw new IllegalArgumentException(\"args\");\n }\n\n final String callbackId = mConnection.RegisterCallback(callback);\n\n HubInvocation hubData = new HubInvocation(mHubName, method, args, callbackId);\n\n String value = hubData.Serialize();\n\n mConnection.Send(value, new SendCallback() \n {\n\t\t\t@Override\n\t\t\tpublic void OnSent(CharSequence messageSent) {\n\t\t\t\tLog.v(TAG, \"Invoke of \" + method + \"sent to \" + mHubName);\n\t\t\t\t// callback.OnSent() ??!?!?\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void OnError(Exception ex) {\n\t\t\t\t// TODO Cancel the callback\n\t\t\t\tLog.e(TAG, \"Failed to invoke \" + method + \"on \" + mHubName);\n\t\t\t\tmConnection.RemoveCallback(callbackId);\n\t\t\t\t// callback.OnError() ?!?!?\n\t\t\t}\n });\n }", "public synchronized Message simpleRequest(Message.KnownType requestType, Message.KnownType responseType,\n Field... arguments)\n throws IOException {\n final NumberField transaction = assignTransactionNumber();\n final Message request = new Message(transaction, new NumberField(requestType.protocolValue, 2), arguments);\n sendMessage(request);\n final Message response = Message.read(is);\n if (response.transaction.getValue() != transaction.getValue()) {\n throw new IOException(\"Received response with wrong transaction ID. Expected: \" + transaction.getValue() +\n \", got: \" + response);\n }\n if (responseType != null && response.knownType != responseType) {\n throw new IOException(\"Received response with wrong type. Expected: \" + responseType +\n \", got: \" + response);\n }\n return response;\n }", "List<W3CEndpointReference> lookupEndpoints(QName serviceName,\n MatcherDataType matcherData) throws ServiceLocatorFault,\n InterruptedExceptionFault {\n SLPropertiesMatcher matcher = createMatcher(matcherData);\n List<String> names = null;\n List<W3CEndpointReference> result = new ArrayList<W3CEndpointReference>();\n String adress;\n try {\n initLocator();\n if (matcher == null) {\n names = locatorClient.lookup(serviceName);\n } else {\n names = locatorClient.lookup(serviceName, matcher);\n }\n } catch (ServiceLocatorException e) {\n ServiceLocatorFaultDetail serviceFaultDetail = new ServiceLocatorFaultDetail();\n serviceFaultDetail.setLocatorFaultDetail(serviceName.toString()\n + \"throws ServiceLocatorFault\");\n throw new ServiceLocatorFault(e.getMessage(), serviceFaultDetail);\n } catch (InterruptedException e) {\n InterruptionFaultDetail interruptionFaultDetail = new InterruptionFaultDetail();\n interruptionFaultDetail.setInterruptionDetail(serviceName\n .toString() + \"throws InterruptionFault\");\n throw new InterruptedExceptionFault(e.getMessage(),\n interruptionFaultDetail);\n }\n if (names != null && !names.isEmpty()) {\n for (int i = 0; i < names.size(); i++) {\n adress = names.get(i);\n result.add(buildEndpoint(serviceName, adress));\n }\n } else {\n if (LOG.isLoggable(Level.WARNING)) {\n LOG.log(Level.WARNING, \"lookup Endpoints for \" + serviceName\n + \" failed, service is not known.\");\n }\n ServiceLocatorFaultDetail serviceFaultDetail = new ServiceLocatorFaultDetail();\n serviceFaultDetail.setLocatorFaultDetail(\"lookup Endpoint for \"\n + serviceName + \" failed, service is not known.\");\n throw new ServiceLocatorFault(\"Can not find Endpoint\",\n serviceFaultDetail);\n }\n return result;\n }", "private int getCostRateTableEntryIndex(Date date)\n {\n int result = -1;\n\n CostRateTable table = getCostRateTable();\n if (table != null)\n {\n if (table.size() == 1)\n {\n result = 0;\n }\n else\n {\n result = table.getIndexByDate(date);\n }\n }\n\n return result;\n }", "public void linkOneToMany(Object obj, CollectionDescriptor cod, boolean insert)\n {\n Object referencedObjects = cod.getPersistentField().get(obj);\n storeAndLinkOneToMany(true, obj, cod,referencedObjects, insert);\n }", "public static boolean isPostJDK5(String bytecodeVersion) {\n return JDK5.equals(bytecodeVersion)\n || JDK6.equals(bytecodeVersion)\n || JDK7.equals(bytecodeVersion)\n || JDK8.equals(bytecodeVersion);\n }", "public List<String> getCorporateGroupIds(final String organizationId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n return dbOrganization.getCorporateGroupIdPrefixes();\n }", "public static Shell createSubshell(String pathElement, Shell parent, String appName, Object mainHandler) {\n return createSubshell(pathElement, parent, appName, mainHandler, new EmptyMultiMap<String, Object>());\n }", "private void readZookeeperConfig() {\n\n try (CuratorFramework curator = CuratorUtil.newAppCurator(config)) {\n curator.start();\n\n accumuloInstance =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_NAME),\n StandardCharsets.UTF_8);\n accumuloInstanceID =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_ID),\n StandardCharsets.UTF_8);\n fluoApplicationID =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID),\n StandardCharsets.UTF_8);\n\n table = new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_TABLE),\n StandardCharsets.UTF_8);\n\n observers = ObserverUtil.load(curator);\n\n config = FluoAdminImpl.mergeZookeeperConfig(config);\n\n // make sure not to include config passed to env, only want config from zookeeper\n appConfig = config.getAppConfiguration();\n } catch (Exception e) {\n throw new IllegalStateException(e);\n }\n }" ]
Returns the parsed story from the given text @param configuration the Configuration used to run story @param storyAsText the story text @param storyId the story Id, which will be returned as story path @return The parsed Story
[ "public Story storyOfText(Configuration configuration, String storyAsText, String storyId) {\n return configuration.storyParser().parseStory(storyAsText, storyId);\n }" ]
[ "public void writeFinalResults() {\n\t\tprintStatus();\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"gender-ratios.csv\"))) {\n\n\t\t\tout.print(\"Site key,pages total,pages on humans,pages on humans with gender\");\n\t\t\tfor (EntityIdValue gender : this.genderNamesList) {\n\t\t\t\tout.print(\",\" + this.genderNames.get(gender) + \" (\"\n\t\t\t\t\t\t+ gender.getId() + \")\");\n\t\t\t}\n\t\t\tout.println();\n\n\t\t\tList<SiteRecord> siteRecords = new ArrayList<>(\n\t\t\t\t\tthis.siteRecords.values());\n\t\t\tCollections.sort(siteRecords, new SiteRecordComparator());\n\t\t\tfor (SiteRecord siteRecord : siteRecords) {\n\t\t\t\tout.print(siteRecord.siteKey + \",\" + siteRecord.pageCount + \",\"\n\t\t\t\t\t\t+ siteRecord.humanPageCount + \",\"\n\t\t\t\t\t\t+ siteRecord.humanGenderPageCount);\n\n\t\t\t\tfor (EntityIdValue gender : this.genderNamesList) {\n\t\t\t\t\tif (siteRecord.genderCounts.containsKey(gender)) {\n\t\t\t\t\t\tout.print(\",\" + siteRecord.genderCounts.get(gender));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tout.print(\",0\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tout.println();\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "@Deprecated\n public synchronized FailureDetectorConfig setNodes(Collection<Node> nodes) {\n Utils.notNull(nodes);\n this.nodes = new HashSet<Node>(nodes);\n return this;\n }", "public static String getAt(CharSequence self, Collection indices) {\n StringBuilder answer = new StringBuilder();\n for (Object value : indices) {\n if (value instanceof Range) {\n answer.append(getAt(self, (Range) value));\n } else if (value instanceof Collection) {\n answer.append(getAt(self, (Collection) value));\n } else {\n int idx = DefaultTypeTransformation.intUnbox(value);\n answer.append(getAt(self, idx));\n }\n }\n return answer.toString();\n }", "protected Map getAllVariables(){\n try{\n Iterator names = FreeMarkerTL.getEnvironment().getKnownVariableNames().iterator();\n Map vars = new HashMap();\n while (names.hasNext()) {\n Object name =names.next();\n vars.put(name, get(name.toString()));\n }\n return vars;\n }catch(Exception e){\n throw new ViewException(e);\n }\n }", "public static vpnvserver_rewritepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_rewritepolicy_binding obj = new vpnvserver_rewritepolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_rewritepolicy_binding response[] = (vpnvserver_rewritepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public ClientLayerInfo securityClone(ClientLayerInfo original) {\n\t\t// the data is explicitly copied as this assures the security is considered when copying.\n\t\tif (null == original) {\n\t\t\treturn null;\n\t\t}\n\t\tClientLayerInfo client = null;\n\t\tString layerId = original.getServerLayerId();\n\t\tif (securityContext.isLayerVisible(layerId)) {\n\t\t\tclient = (ClientLayerInfo) SerializationUtils.clone(original);\n\t\t\tclient.setWidgetInfo(securityClone(original.getWidgetInfo()));\n\t\t\tclient.getLayerInfo().setExtraInfo(securityCloneLayerExtraInfo(original.getLayerInfo().getExtraInfo()));\n\t\t\tif (client instanceof ClientVectorLayerInfo) {\n\t\t\t\tClientVectorLayerInfo vectorLayer = (ClientVectorLayerInfo) client;\n\t\t\t\t// set statuses\n\t\t\t\tvectorLayer.setCreatable(securityContext.isLayerCreateAuthorized(layerId));\n\t\t\t\tvectorLayer.setUpdatable(securityContext.isLayerUpdateAuthorized(layerId));\n\t\t\t\tvectorLayer.setDeletable(securityContext.isLayerDeleteAuthorized(layerId));\n\t\t\t\t// filter feature info\n\t\t\t\tFeatureInfo featureInfo = vectorLayer.getFeatureInfo();\n\t\t\t\tList<AttributeInfo> originalAttr = featureInfo.getAttributes();\n\t\t\t\tList<AttributeInfo> filteredAttr = new ArrayList<AttributeInfo>();\n\t\t\t\tfeatureInfo.setAttributes(filteredAttr);\n\t\t\t\tfor (AttributeInfo ai : originalAttr) {\n\t\t\t\t\tif (securityContext.isAttributeReadable(layerId, null, ai.getName())) {\n\t\t\t\t\t\tfilteredAttr.add(ai);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn client;\n\t}", "public static void downloadUrl(String stringUrl, Map<String, String> parameters, File fileToSave)\n throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setFollowRedirects(true);\n \n if (parameters != null) {\n for (Entry<String, String> entry : parameters.entrySet()) {\n conn.addRequestProperty(entry.getKey(), entry.getValue());\n }\n }\n\n\n boolean redirect = false;\n\n // normally, 3xx is redirect\n int status = conn.getResponseCode();\n if (status != HttpURLConnection.HTTP_OK) {\n if (status == HttpURLConnection.HTTP_MOVED_TEMP\n || status == HttpURLConnection.HTTP_MOVED_PERM\n || status == HttpURLConnection.HTTP_SEE_OTHER)\n redirect = true;\n }\n\n if (redirect) {\n\n // get redirect url from \"location\" header field\n String newUrl = conn.getHeaderField(\"Location\");\n\n // get the cookie if need, for login\n String cookies = conn.getHeaderField(\"Set-Cookie\");\n\n // open the new connnection again\n conn = (HttpURLConnection) new URL(newUrl).openConnection();\n conn.setRequestProperty(\"Cookie\", cookies);\n\n }\n \n byte[] data = MyStreamUtils.readContentBytes(conn.getInputStream());\n FileOutputStream fos = new FileOutputStream(fileToSave);\n fos.write(data);\n fos.close();\n }", "public ManageableCollection createCollectionProxy(PBKey brokerKey, Query query, Class collectionClass)\r\n {\r\n Object args[] = {brokerKey, collectionClass, query};\r\n\r\n try\r\n {\r\n return (ManageableCollection) getCollectionProxyConstructor(collectionClass).newInstance(args);\r\n }\r\n catch(InstantiationException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new collection proxy instance\", ex);\r\n }\r\n catch(InvocationTargetException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new collection proxy instance\", ex);\r\n }\r\n catch(IllegalAccessException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new collection proxy instance\", ex);\r\n }\r\n }", "@SuppressWarnings(\"deprecation\")\n\tpublic static boolean dateTimeEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getDate() == d2.getDate()\n && d1.getMonth() == d2.getMonth()\n && d1.getYear() == d2.getYear()\n && d1.getHours() == d2.getHours()\n && d1.getMinutes() == d2.getMinutes()\n && d1.getSeconds() == d2.getSeconds();\n }" ]
rollback the transaction
[ "public void checkpoint(ObjectEnvelope mod)\r\n throws org.apache.ojb.broker.PersistenceBrokerException\r\n {\r\n mod.doDelete();\r\n mod.setModificationState(StateTransient.getInstance());\r\n }" ]
[ "public static String getTokenText(INode node) {\n\t\tif (node instanceof ILeafNode)\n\t\t\treturn ((ILeafNode) node).getText();\n\t\telse {\n\t\t\tStringBuilder builder = new StringBuilder(Math.max(node.getTotalLength(), 1));\n\t\t\tboolean hiddenSeen = false;\n\t\t\tfor (ILeafNode leaf : node.getLeafNodes()) {\n\t\t\t\tif (!leaf.isHidden()) {\n\t\t\t\t\tif (hiddenSeen && builder.length() > 0)\n\t\t\t\t\t\tbuilder.append(' ');\n\t\t\t\t\tbuilder.append(leaf.getText());\n\t\t\t\t\thiddenSeen = false;\n\t\t\t\t} else {\n\t\t\t\t\thiddenSeen = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn builder.toString();\n\t\t}\n\t}", "public List<NodeInfo> getNodes() {\n final URI uri = uriWithPath(\"./nodes/\");\n return Arrays.asList(this.rt.getForObject(uri, NodeInfo[].class));\n }", "public double[] getScaleDenominators() {\n double[] dest = new double[this.scaleDenominators.length];\n System.arraycopy(this.scaleDenominators, 0, dest, 0, this.scaleDenominators.length);\n return dest;\n }", "public Object selectElement(String predicate) throws org.odmg.QueryInvalidException\r\n {\r\n return ((DList) this.query(predicate)).get(0);\r\n }", "public void mutate(float amount) {\n\t\tfor (int i = 0; i < numKnots; i++) {\n\t\t\tint rgb = yKnots[i];\n\t\t\tint r = ((rgb >> 16) & 0xff);\n\t\t\tint g = ((rgb >> 8) & 0xff);\n\t\t\tint b = (rgb & 0xff);\n\t\t\tr = PixelUtils.clamp( (int)(r + amount * 255 * (Math.random()-0.5)) );\n\t\t\tg = PixelUtils.clamp( (int)(g + amount * 255 * (Math.random()-0.5)) );\n\t\t\tb = PixelUtils.clamp( (int)(b + amount * 255 * (Math.random()-0.5)) );\n\t\t\tyKnots[i] = 0xff000000 | (r << 16) | (g << 8) | b;\n\t\t\tknotTypes[i] = RGB|SPLINE;\n\t\t}\n\t\tsortKnots();\n\t\trebuildGradient();\n\t}", "public void add(String photoId, String userId, Rectangle bounds) throws FlickrException {\r\n\r\n // Delegating this to photos.people.PeopleInterface - Naming standard would be to use PeopleInterface but having 2 the same name can cause issues\r\n com.flickr4java.flickr.photos.people.PeopleInterface pi = new com.flickr4java.flickr.photos.people.PeopleInterface(apiKey, sharedSecret, transportAPI);\r\n pi.add(photoId, userId, bounds);\r\n }", "public 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 }", "public String getString(String fieldName) {\n\t\treturn hasValue(fieldName) ? String.valueOf(resultMap.get(fieldName)) : null;\n\t}", "private static void listRelationships(ProjectFile file)\n {\n for (Task task : file.getTasks())\n {\n System.out.print(task.getID());\n System.out.print('\\t');\n System.out.print(task.getName());\n System.out.print('\\t');\n\n dumpRelationList(task.getPredecessors());\n System.out.print('\\t');\n dumpRelationList(task.getSuccessors());\n System.out.println();\n }\n }" ]
Converts a batch indexing into the sample, to a batch indexing into the original function. @param batch The batch indexing into the sample. @return A new batch indexing into the original function, containing only the indices from the sample.
[ "private int[] convertBatch(int[] batch) {\n int[] conv = new int[batch.length];\n for (int i=0; i<batch.length; i++) {\n conv[i] = sample[batch[i]];\n }\n return conv;\n }" ]
[ "public static dnspolicy_dnspolicylabel_binding[] get(nitro_service service, String name) throws Exception{\n\t\tdnspolicy_dnspolicylabel_binding obj = new dnspolicy_dnspolicylabel_binding();\n\t\tobj.set_name(name);\n\t\tdnspolicy_dnspolicylabel_binding response[] = (dnspolicy_dnspolicylabel_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@SuppressWarnings(\"unchecked\")\n public static <E> String serialize(E object, ParameterizedType<E> parameterizedType) throws IOException {\n return mapperFor(parameterizedType).serialize(object);\n }", "public List<File> getInactiveOverlays() throws PatchingException {\n if (referencedOverlayDirectories == null) {\n walk();\n }\n List<File> inactiveDirs = null;\n for (Layer layer : installedIdentity.getLayers()) {\n final File overlaysDir = new File(layer.getDirectoryStructure().getModuleRoot(), Constants.OVERLAYS);\n final File[] inactiveLayerDirs = overlaysDir.listFiles(new FileFilter() {\n @Override\n public boolean accept(File pathname) {\n return pathname.isDirectory() && !referencedOverlayDirectories.contains(pathname);\n }\n });\n if (inactiveLayerDirs != null && inactiveLayerDirs.length > 0) {\n if (inactiveDirs == null) {\n inactiveDirs = new ArrayList<File>();\n }\n inactiveDirs.addAll(Arrays.asList(inactiveLayerDirs));\n }\n }\n return inactiveDirs == null ? Collections.<File>emptyList() : inactiveDirs;\n }", "@Inline(value = \"$1.remove($2.getKey(), $2.getValue())\", statementExpression = true)\n\tpublic static <K, V> boolean operator_remove(Map<K, V> map, Pair<? extends K, ? extends V> entry) {\n\t\t//TODO use the JRE 1.8 API: map.remove(entry.getKey(), entry.getValue());\n\t\tfinal K key = entry.getKey();\n\t\tfinal V storedValue = map.get(entry.getKey());\n\t if (!Objects.equal(storedValue, entry.getValue())\n\t\t\t|| (storedValue == null && !map.containsKey(key))) {\n\t return false;\n \t}\n \tmap.remove(key);\n\t return true;\n\t}", "protected boolean inViewPort(final int dataIndex) {\n boolean inViewPort = true;\n\n for (Layout layout: mLayouts) {\n inViewPort = inViewPort && (layout.inViewPort(dataIndex) || !layout.isClippingEnabled());\n }\n return inViewPort;\n }", "private static boolean checkModifiers(Class<? extends AbstractPlugin> pluginClass) {\n int modifiers = pluginClass.getModifiers();\n return !Modifier.isAbstract(modifiers) &&\n !Modifier.isInterface(modifiers) &&\n !Modifier.isPrivate(modifiers);\n }", "public void info(Throwable throwable, String msg, Object[] argArray) {\n\t\tlogIfEnabled(Level.INFO, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);\n\t}", "private void checkUndefinedNotification(Notification notification) {\n String type = notification.getType();\n PathAddress source = notification.getSource();\n Map<String, NotificationEntry> descriptions = getRootResourceRegistration().getNotificationDescriptions(source, true);\n if (!descriptions.keySet().contains(type)) {\n missingNotificationDescriptionWarnings.add(ControllerLogger.ROOT_LOGGER.notificationIsNotDescribed(type, source));\n }\n }", "@PostConstruct\n public final void addMetricsAppenderToLogback() {\n final LoggerContext factory = (LoggerContext) LoggerFactory.getILoggerFactory();\n final Logger root = factory.getLogger(Logger.ROOT_LOGGER_NAME);\n\n final InstrumentedAppender metrics = new InstrumentedAppender(this.metricRegistry);\n metrics.setContext(root.getLoggerContext());\n metrics.start();\n root.addAppender(metrics);\n }" ]
Builds a instance of the class for a map containing the values, without specifying the handler for differences @param clazz The class to build instance @param values The values map @return The instance @throws InstantiationException Error instantiating @throws IllegalAccessException Access error @throws IntrospectionException Introspection error @throws IllegalArgumentException Argument invalid @throws InvocationTargetException Invalid target
[ "public static <T> T buildInstanceForMap(Class<T> clazz, Map<String, Object> values)\n throws InstantiationException, IllegalAccessException, IntrospectionException,\n IllegalArgumentException, InvocationTargetException {\n return buildInstanceForMap(clazz, values, new MyDefaultReflectionDifferenceHandler());\n }" ]
[ "public static bridgetable[] get(nitro_service service) throws Exception{\n\t\tbridgetable obj = new bridgetable();\n\t\tbridgetable[] response = (bridgetable[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public int scrollToPage(int pageNumber) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToPage pageNumber = %d mPageCount = %d\",\n pageNumber, mPageCount);\n\n if (mSupportScrollByPage &&\n (mScrollOver || (pageNumber >= 0 && pageNumber <= mPageCount - 1))) {\n scrollToItem(getFirstItemIndexOnPage(pageNumber));\n } else {\n Log.w(TAG, \"Pagination is not enabled!\");\n }\n return mCurrentItemIndex;\n\t}", "public static List<ClassReference> analyze(WildcardImportResolver importResolver, Set<String> libraryPaths, Set<String> sourcePaths,\n Path sourceFile)\n {\n ASTParser parser = ASTParser.newParser(AST.JLS11);\n parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]), sourcePaths.toArray(new String[sourcePaths.size()]), null, true);\n parser.setBindingsRecovery(false);\n parser.setResolveBindings(true);\n Map options = JavaCore.getOptions();\n JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);\n parser.setCompilerOptions(options);\n String fileName = sourceFile.getFileName().toString();\n parser.setUnitName(fileName);\n try\n {\n parser.setSource(FileUtils.readFileToString(sourceFile.toFile()).toCharArray());\n }\n catch (IOException e)\n {\n throw new ASTException(\"Failed to get source for file: \" + sourceFile.toString() + \" due to: \" + e.getMessage(), e);\n }\n parser.setKind(ASTParser.K_COMPILATION_UNIT);\n CompilationUnit cu = (CompilationUnit) parser.createAST(null);\n ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, cu, sourceFile.toString());\n cu.accept(visitor);\n return visitor.getJavaClassReferences();\n }", "public static void acceptsUrl(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), \"bootstrap url\")\n .withRequiredArg()\n .describedAs(\"url\")\n .ofType(String.class);\n }", "private void configureCustomFields()\n {\n CustomFieldContainer customFields = m_projectFile.getCustomFields();\n\n // If the caller hasn't already supplied a value for this field\n if (m_activityIDField == null)\n {\n m_activityIDField = (TaskField) customFields.getFieldByAlias(FieldTypeClass.TASK, \"Code\");\n if (m_activityIDField == null)\n {\n m_activityIDField = TaskField.WBS;\n }\n }\n\n // If the caller hasn't already supplied a value for this field\n if (m_activityTypeField == null)\n {\n m_activityTypeField = (TaskField) customFields.getFieldByAlias(FieldTypeClass.TASK, \"Activity Type\");\n }\n }", "public static appfwprofile_stats[] get(nitro_service service) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tappfwprofile_stats[] response = (appfwprofile_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "@Pure\n\tpublic static <P1, RESULT> Function0<RESULT> curry(final Function1<? super P1, ? extends RESULT> function, final P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function0<RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply() {\n\t\t\t\treturn function.apply(argument);\n\t\t\t}\n\t\t};\n\t}", "protected void append(Object object, String indentation, int index) {\n\t\tif (indentation.length() == 0) {\n\t\t\tappend(object, index);\n\t\t\treturn;\n\t\t}\n\t\tif (object == null)\n\t\t\treturn;\n\t\tif (object instanceof String) {\n\t\t\tappend(indentation, (String)object, index);\n\t\t} else if (object instanceof StringConcatenation) {\n\t\t\tStringConcatenation other = (StringConcatenation) object;\n\t\t\tList<String> otherSegments = other.getSignificantContent();\n\t\t\tappendSegments(indentation, index, otherSegments, other.lineDelimiter);\n\t\t} else if (object instanceof StringConcatenationClient) {\n\t\t\tStringConcatenationClient other = (StringConcatenationClient) object;\n\t\t\tother.appendTo(new IndentedTarget(this, indentation, index));\n\t\t} else {\n\t\t\tfinal String text = getStringRepresentation(object);\n\t\t\tif (text != null) {\n\t\t\t\tappend(indentation, text, index);\n\t\t\t}\n\t\t}\n\t}", "protected boolean executeOperation(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, TransactionalProtocolClient client, final ServerIdentity identity, final ModelNode operation, final OperationResultTransformer transformer) {\n if(client == null) {\n return false;\n }\n final OperationMessageHandler messageHandler = new DelegatingMessageHandler(context);\n final OperationAttachments operationAttachments = new DelegatingOperationAttachments(context);\n final ServerOperation serverOperation = new ServerOperation(identity, operation, messageHandler, operationAttachments, transformer);\n try {\n DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef(\"Sending %s to %s\", operation, identity);\n final Future<OperationResponse> result = client.execute(listener, serverOperation);\n recordExecutedRequest(new ExecutedServerRequest(identity, result, transformer));\n } catch (IOException e) {\n final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e);\n listener.operationPrepared(result);\n recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), transformer));\n }\n return true;\n }" ]
Gets the appropriate cache dir @param ctx @return
[ "public static String getCacheDir(Context ctx) {\n return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || (!Environment.isExternalStorageRemovable() && ctx.getExternalCacheDir() != null) ?\n ctx.getExternalCacheDir().getPath() : ctx.getCacheDir().getPath();\n }" ]
[ "public final void setWeekOfMonth(WeekOfMonth weekOfMonth) {\n\n SortedSet<WeekOfMonth> woms = new TreeSet<>();\n if (null != weekOfMonth) {\n woms.add(weekOfMonth);\n }\n setWeeksOfMonth(woms);\n }", "public DbInfo info() {\n return client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).getDatabaseUri(),\n DbInfo.class);\n }", "public static byte[] synchronizeSlaveHostController(ModelNode operation, final PathAddress address, HostFileRepository fileRepository, ContentRepository contentRepository, boolean backup, byte[] oldHash) {\n ModelNode operationContentItem = operation.get(DeploymentAttributes.CONTENT_RESOURCE_ALL.getName()).get(0);\n byte[] newHash = operationContentItem.require(CONTENT_HASH.getName()).asBytes();\n if (needRemoteContent(fileRepository, contentRepository, backup, oldHash)) { // backup DC needs to pull the content\n fileRepository.getDeploymentFiles(ModelContentReference.fromModelAddress(address, newHash));\n }\n return newHash;\n }", "public com.groupon.odo.proxylib.models.Method getMethodForOverrideId(int overrideId) {\n com.groupon.odo.proxylib.models.Method method = null;\n\n // special case for IDs < 0\n if (overrideId < 0) {\n method = new com.groupon.odo.proxylib.models.Method();\n method.setId(overrideId);\n\n if (method.getId() == Constants.PLUGIN_RESPONSE_OVERRIDE_CUSTOM ||\n method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_ADD ||\n method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_REMOVE) {\n method.setMethodType(Constants.PLUGIN_TYPE_RESPONSE_OVERRIDE);\n } else {\n method.setMethodType(Constants.PLUGIN_TYPE_REQUEST_OVERRIDE);\n }\n } else {\n // get method information from the database\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, overrideId);\n results = queryStatement.executeQuery();\n\n if (results.next()) {\n method = new com.groupon.odo.proxylib.models.Method();\n method.setClassName(results.getString(Constants.OVERRIDE_CLASS_NAME));\n method.setMethodName(results.getString(Constants.OVERRIDE_METHOD_NAME));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n return null;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n // if method is still null then just return\n if (method == null) {\n return method;\n }\n\n // now get the rest of the data from the plugin manager\n // this gets all of the actual method data\n try {\n method = PluginManager.getInstance().getMethod(method.getClassName(), method.getMethodName());\n method.setId(overrideId);\n } catch (Exception e) {\n // there was some problem.. return null\n return null;\n }\n }\n\n return method;\n }", "public static double blackModelDgitialCapletValue(\n\t\t\tdouble forward,\n\t\t\tdouble volatility,\n\t\t\tdouble periodLength,\n\t\t\tdouble discountFactor,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\t// May be interpreted as a special version of the Black-Scholes Formula\n\t\treturn AnalyticFormulas.blackScholesDigitalOptionValue(forward, 0.0, volatility, optionMaturity, optionStrike) * periodLength * discountFactor;\n\t}", "public static GVRSceneObject loadModel(final GVRContext gvrContext,\n final String modelFile) throws IOException {\n return loadModel(gvrContext, modelFile, new HashMap<String, Integer>());\n }", "private static void parseRessource(ArrayList<Shape> shapes,\n HashMap<String, JSONObject> flatJSON,\n String resourceId,\n Boolean keepGlossaryLink)\n throws JSONException {\n JSONObject modelJSON = flatJSON.get(resourceId);\n Shape current = getShapeWithId(modelJSON.getString(\"resourceId\"),\n shapes);\n\n parseStencil(modelJSON,\n current);\n\n parseProperties(modelJSON,\n current,\n keepGlossaryLink);\n parseOutgoings(shapes,\n modelJSON,\n current);\n parseChildShapes(shapes,\n modelJSON,\n current);\n parseDockers(modelJSON,\n current);\n parseBounds(modelJSON,\n current);\n parseTarget(shapes,\n modelJSON,\n current);\n }", "public double[] getRegressionCoefficients(RandomVariable value) {\n\t\tif(basisFunctions.length == 0) {\n\t\t\treturn new double[] { };\n\t\t}\n\t\telse if(basisFunctions.length == 1) {\n\t\t\t/*\n\t\t\t * Regression with one basis function is just a projection on that vector. <b,x>/<b,b>\n\t\t\t */\n\t\t\treturn new double[] { value.mult(basisFunctions[0]).getAverage() / basisFunctions[0].squared().getAverage() };\n\t\t}\n\t\telse if(basisFunctions.length == 2) {\n\t\t\t/*\n\t\t\t * Regression with two basis functions can be solved explicitly if determinant != 0 (otherwise we will fallback to SVD)\n\t\t\t */\n\t\t\tdouble a = basisFunctions[0].squared().getAverage();\n\t\t\tdouble b = basisFunctions[0].mult(basisFunctions[1]).average().squared().doubleValue();\n\t\t\tdouble c = b;\n\t\t\tdouble d = basisFunctions[1].squared().getAverage();\n\n\t\t\tdouble determinant = (a * d - b * c);\n\t\t\tif(determinant != 0) {\n\t\t\t\tdouble x = value.mult(basisFunctions[0]).getAverage();\n\t\t\t\tdouble y = value.mult(basisFunctions[1]).getAverage();\n\n\t\t\t\tdouble alpha0 = (d * x - b * y) / determinant;\n\t\t\t\tdouble alpha1 = (a * y - c * x) / determinant;\n\n\t\t\t\treturn new double[] { alpha0, alpha1 };\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * General case\n\t\t */\n\n\t\t// Build regression matrix\n\t\tdouble[][] BTB = new double[basisFunctions.length][basisFunctions.length];\n\t\tfor(int i=0; i<basisFunctions.length; i++) {\n\t\t\tfor(int j=0; j<=i; j++) {\n\t\t\t\tdouble covariance = basisFunctions[i].mult(basisFunctions[j]).getAverage();\n\t\t\t\tBTB[i][j] = covariance;\n\t\t\t\tBTB[j][i] = covariance;\n\t\t\t}\n\t\t}\n\n\t\tdouble[] BTX = new double[basisFunctions.length];\n\t\tfor(int i=0; i<basisFunctions.length; i++) {\n\t\t\tdouble covariance = basisFunctions[i].mult(value).getAverage();\n\t\t\tBTX[i] = covariance;\n\t\t}\n\n\t\treturn LinearAlgebra.solveLinearEquationLeastSquare(BTB, BTX);\n\t}", "public static void fillProcessorAttributes(\n final List<Processor> processors,\n final Map<String, Attribute> initialAttributes) {\n Map<String, Attribute> currentAttributes = new HashMap<>(initialAttributes);\n for (Processor processor: processors) {\n if (processor instanceof RequireAttributes) {\n for (ProcessorDependencyGraphFactory.InputValue inputValue:\n ProcessorDependencyGraphFactory.getInputs(processor)) {\n if (inputValue.type == Values.class) {\n if (processor instanceof CustomDependencies) {\n for (String attributeName: ((CustomDependencies) processor).getDependencies()) {\n Attribute attribute = currentAttributes.get(attributeName);\n if (attribute != null) {\n ((RequireAttributes) processor).setAttribute(\n attributeName, currentAttributes.get(attributeName));\n }\n }\n\n } else {\n for (Map.Entry<String, Attribute> attribute: currentAttributes.entrySet()) {\n ((RequireAttributes) processor).setAttribute(\n attribute.getKey(), attribute.getValue());\n }\n }\n } else {\n try {\n ((RequireAttributes) processor).setAttribute(\n inputValue.internalName,\n currentAttributes.get(inputValue.name));\n } catch (ClassCastException e) {\n throw new IllegalArgumentException(String.format(\"The processor '%s' requires \" +\n \"the attribute '%s' \" +\n \"(%s) but he has the \" +\n \"wrong type:\\n%s\",\n processor, inputValue.name,\n inputValue.internalName,\n e.getMessage()), e);\n }\n }\n }\n }\n if (processor instanceof ProvideAttributes) {\n Map<String, Attribute> newAttributes = ((ProvideAttributes) processor).getAttributes();\n for (ProcessorDependencyGraphFactory.OutputValue ouputValue:\n ProcessorDependencyGraphFactory.getOutputValues(processor)) {\n currentAttributes.put(\n ouputValue.name, newAttributes.get(ouputValue.internalName));\n }\n }\n }\n }" ]
Look-up the results data for a particular test class.
[ "private TestClassResults getResultsForClass(Map<IClass, TestClassResults> flattenedResults,\n ITestResult testResult)\n {\n TestClassResults resultsForClass = flattenedResults.get(testResult.getTestClass());\n if (resultsForClass == null)\n {\n resultsForClass = new TestClassResults(testResult.getTestClass());\n flattenedResults.put(testResult.getTestClass(), resultsForClass);\n }\n return resultsForClass;\n }" ]
[ "protected static void writeErrorResponse(final Channel channel, final ManagementRequestHeader header, final Throwable error) throws IOException {\n final ManagementResponseHeader response = ManagementResponseHeader.create(header, error);\n final MessageOutputStream output = channel.writeMessage();\n try {\n writeHeader(response, output);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }", "public static int positionOf(char value, char[] array) {\n for (int i = 0; i < array.length; i++) {\n if (value == array[i]) {\n return i;\n }\n }\n throw new OkapiException(\"Unable to find character '\" + value + \"' in character array.\");\n }", "public static void addHeaders(BoundRequestBuilder builder,\n Map<String, String> headerMap) {\n for (Entry<String, String> entry : headerMap.entrySet()) {\n String name = entry.getKey();\n String value = entry.getValue();\n builder.addHeader(name, value);\n }\n\n }", "private static void listTasks(ProjectFile file)\n {\n SimpleDateFormat df = new SimpleDateFormat(\"dd/MM/yyyy HH:mm z\");\n\n for (Task task : file.getTasks())\n {\n Date date = task.getStart();\n String text = task.getStartText();\n String startDate = text != null ? text : (date != null ? df.format(date) : \"(no start date supplied)\");\n\n date = task.getFinish();\n text = task.getFinishText();\n String finishDate = text != null ? text : (date != null ? df.format(date) : \"(no finish date supplied)\");\n\n Duration dur = task.getDuration();\n text = task.getDurationText();\n String duration = text != null ? text : (dur != null ? dur.toString() : \"(no duration supplied)\");\n\n dur = task.getActualDuration();\n String actualDuration = dur != null ? dur.toString() : \"(no actual duration supplied)\";\n\n String baselineDuration = task.getBaselineDurationText();\n if (baselineDuration == null)\n {\n dur = task.getBaselineDuration();\n if (dur != null)\n {\n baselineDuration = dur.toString();\n }\n else\n {\n baselineDuration = \"(no duration supplied)\";\n }\n }\n\n System.out.println(\"Task: \" + task.getName() + \" ID=\" + task.getID() + \" Unique ID=\" + task.getUniqueID() + \" (Start Date=\" + startDate + \" Finish Date=\" + finishDate + \" Duration=\" + duration + \" Actual Duration\" + actualDuration + \" Baseline Duration=\" + baselineDuration + \" Outline Level=\" + task.getOutlineLevel() + \" Outline Number=\" + task.getOutlineNumber() + \" Recurring=\" + task.getRecurring() + \")\");\n }\n System.out.println();\n }", "public void sendData(SerialMessage serialMessage)\n\t{\n \tif (serialMessage.getMessageClass() != SerialMessage.SerialMessageClass.SendData) {\n \t\tlogger.error(String.format(\"Invalid message class %s (0x%02X) for sendData\", serialMessage.getMessageClass().getLabel(), serialMessage.getMessageClass().getKey()));\n \t\treturn;\n \t}\n \tif (serialMessage.getMessageType() != SerialMessage.SerialMessageType.Request) {\n \t\tlogger.error(\"Only request messages can be sent\");\n \t\treturn;\n \t}\n \t\n \tZWaveNode node = this.getNode(serialMessage.getMessageNode());\n \t\t\t\n \tif (node.getNodeStage() == NodeStage.NODEBUILDINFO_DEAD) {\n \t\tlogger.debug(\"Node {} is dead, not sending message.\", node.getNodeId());\n\t\t\treturn;\n \t}\n\t\t\n \tif (!node.isListening() && serialMessage.getPriority() != SerialMessage.SerialMessagePriority.Low) {\n\t\t\tZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass)node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP);\n\t\t\t\n\t\t\tif (wakeUpCommandClass != null && !wakeUpCommandClass.isAwake()) {\n\t\t\t\twakeUpCommandClass.putInWakeUpQueue(serialMessage); //it's a battery operated device, place in wake-up queue.\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n \t\n \tserialMessage.setTransmitOptions(TRANSMIT_OPTION_ACK | TRANSMIT_OPTION_AUTO_ROUTE | TRANSMIT_OPTION_EXPLORE);\n \tif (++sentDataPointer > 0xFF)\n \t\tsentDataPointer = 1;\n \tserialMessage.setCallbackId(sentDataPointer);\n \tlogger.debug(\"Callback ID = {}\", sentDataPointer);\n \tthis.enqueue(serialMessage);\n\t}", "private void init(final List<DbLicense> licenses) {\n licensesRegexp.clear();\n\n for (final DbLicense license : licenses) {\n if (license.getRegexp() == null ||\n license.getRegexp().isEmpty()) {\n licensesRegexp.put(license.getName(), license);\n } else {\n licensesRegexp.put(license.getRegexp(), license);\n }\n }\n }", "private void addOp(String op, String path, String value) {\n if (this.operations == null) {\n this.operations = new JsonArray();\n }\n\n this.operations.add(new JsonObject()\n .add(\"op\", op)\n .add(\"path\", path)\n .add(\"value\", value));\n }", "public int sharedSegments(Triangle t2) {\n\t\tint counter = 0;\n\n\t\tif(a.equals(t2.a)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(a.equals(t2.b)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(a.equals(t2.c)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(b.equals(t2.a)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(b.equals(t2.b)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(b.equals(t2.c)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(c.equals(t2.a)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(c.equals(t2.b)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(c.equals(t2.c)) {\n\t\t\tcounter++;\n\t\t}\n\n\t\treturn counter;\n\t}", "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 }" ]
Determines the encoding block groups for the specified data.
[ "private static List< Block > createBlocks(int[] data, boolean debug) {\r\n\r\n List< Block > blocks = new ArrayList<>();\r\n Block current = null;\r\n\r\n for (int i = 0; i < data.length; i++) {\r\n EncodingMode mode = chooseMode(data[i]);\r\n if ((current != null && current.mode == mode) &&\r\n (mode != EncodingMode.NUM || current.length < MAX_NUMERIC_COMPACTION_BLOCK_SIZE)) {\r\n current.length++;\r\n } else {\r\n current = new Block(mode);\r\n blocks.add(current);\r\n }\r\n }\r\n\r\n if (debug) {\r\n System.out.println(\"Initial block pattern: \" + blocks);\r\n }\r\n\r\n smoothBlocks(blocks);\r\n\r\n if (debug) {\r\n System.out.println(\"Final block pattern: \" + blocks);\r\n }\r\n\r\n return blocks;\r\n }" ]
[ "public static ClassLoader resolveClassLoaderForBeanProxy(String contextId, Class<?> proxiedType, TypeInfo typeInfo, ProxyServices proxyServices) {\n Class<?> superClass = typeInfo.getSuperClass();\n if (superClass.getName().startsWith(JAVA)) {\n ClassLoader cl = proxyServices.getClassLoader(proxiedType);\n if (cl == null) {\n cl = Thread.currentThread().getContextClassLoader();\n }\n return cl;\n }\n return Container.instance(contextId).services().get(ProxyServices.class).getClassLoader(superClass);\n }", "public ItemRequest<Webhook> getById(String webhook) {\n \n String path = String.format(\"/webhooks/%s\", webhook);\n return new ItemRequest<Webhook>(this, Webhook.class, path, \"GET\");\n }", "public final void visit(final Visitor visitor)\n\t{\n\t\tfinal Visit visit = new Visit();\n\t\ttry\n\t\t{\n\t\t\tvisit(visitor, visit);\n\t\t}\n\t\tcatch (final StopVisitationException ignored)\n\t\t{\n\t\t}\n\t}", "protected void addPoint(double time, RandomVariable value, boolean isParameter) {\n\t\tsynchronized (rationalFunctionInterpolationLazyInitLock) {\n\t\t\tif(interpolationEntity == InterpolationEntity.LOG_OF_VALUE_PER_TIME && time == 0) {\n\t\t\t\tboolean containsOne = false; int index=0;\n\t\t\t\tfor(int i = 0; i< value.size(); i++){if(value.get(i)==1.0) {containsOne = true; index=i; break;}}\n\t\t\t\tif(containsOne && isParameter == false) {\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new IllegalArgumentException(\"The interpolation method LOG_OF_VALUE_PER_TIME does not allow to add a value at time = 0 other than 1.0 (received 1 at index\" + index + \").\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tRandomVariable interpolationEntityValue = interpolationEntityFromValue(value, time);\n\n\t\t\tint index = getTimeIndex(time);\n\t\t\tif(index >= 0) {\n\t\t\t\tif(points.get(index).value == interpolationEntityValue) {\n\t\t\t\t\treturn;\t\t\t// Already in list\n\t\t\t\t} else if(isParameter) {\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new RuntimeException(\"Trying to add a value for a time for which another value already exists.\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Insert the new point, retain ordering.\n\t\t\t\tPoint point = new Point(time, interpolationEntityValue, isParameter);\n\t\t\t\tpoints.add(-index-1, point);\n\n\t\t\t\tif(isParameter) {\n\t\t\t\t\t// Add this point also to the list of parameters\n\t\t\t\t\tint parameterIndex = getParameterIndex(time);\n\t\t\t\t\tif(parameterIndex >= 0) {\n\t\t\t\t\t\tnew RuntimeException(\"CurveFromInterpolationPoints inconsistent.\");\n\t\t\t\t\t}\n\t\t\t\t\tpointsBeingParameters.add(-parameterIndex-1, point);\n\t\t\t\t}\n\t\t\t}\n\t\t\trationalFunctionInterpolation = null;\n\t\t\tcurveCacheReference = null;\n\t\t}\n\t}", "public static Constructor<?> getConstructor(final Class<?> clazz,\n final Class<?>... argumentTypes) throws NoSuchMethodException {\n try {\n return AccessController\n .doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {\n public Constructor<?> run()\n throws NoSuchMethodException {\n return clazz.getConstructor(argumentTypes);\n }\n });\n }\n // Unwrap\n catch (final PrivilegedActionException pae) {\n final Throwable t = pae.getCause();\n // Rethrow\n if (t instanceof NoSuchMethodException) {\n throw (NoSuchMethodException) t;\n } else {\n // No other checked Exception thrown by Class.getConstructor\n try {\n throw (RuntimeException) t;\n }\n // Just in case we've really messed up\n catch (final ClassCastException cce) {\n throw new RuntimeException(\n \"Obtained unchecked Exception; this code should never be reached\",\n t);\n }\n }\n }\n }", "public static boolean isAlternative(EnhancedAnnotated<?, ?> annotated, MergedStereotypes<?, ?> mergedStereotypes) {\n return annotated.isAnnotationPresent(Alternative.class) || mergedStereotypes.isAlternative();\n }", "private List<EnrollmentTerm> parseEnrollmentTermList(final List<Response> responses) {\n return responses.stream().\n map(this::parseEnrollmentTermList).\n flatMap(Collection::stream).\n collect(Collectors.toList());\n }", "public String getPermalinkForCurrentPage(CmsObject cms) {\n\n return getPermalink(cms, cms.getRequestContext().getUri(), cms.getRequestContext().getDetailContentId());\n }", "public static base_responses add(nitro_service client, dnsview resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnsview addresources[] = new dnsview[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnsview();\n\t\t\t\taddresources[i].viewname = resources[i].viewname;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}" ]
This is a convenience method which reads the first project from the named MPD file using the JDBC-ODBC bridge driver. @param accessDatabaseFileName access database file name @return ProjectFile instance @throws MPXJException
[ "@Override public ProjectFile read(String accessDatabaseFileName) throws MPXJException\n {\n try\n {\n Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\");\n String url = \"jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb);DBQ=\" + accessDatabaseFileName;\n m_connection = DriverManager.getConnection(url);\n m_projectID = Integer.valueOf(1);\n return (read());\n }\n\n catch (ClassNotFoundException ex)\n {\n throw new MPXJException(\"Failed to load JDBC driver\", ex);\n }\n\n catch (SQLException ex)\n {\n throw new MPXJException(\"Failed to create connection\", ex);\n }\n\n finally\n {\n if (m_connection != null)\n {\n try\n {\n m_connection.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore exceptions when closing connection\n }\n }\n }\n }" ]
[ "public void resize(int w, int h) {\n\n // using the new approach of Java 2D API\n BufferedImage buf = new BufferedImage(w, h, image.getType());\n Graphics2D g2d = (Graphics2D) buf.getGraphics();\n g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n g2d.drawImage(image, 0, 0, w, h, null);\n g2d.dispose();\n image = buf;\n width = w;\n height = h;\n updateColorArray();\n }", "public static Date parseEpochTimestamp(String value)\n {\n Date result = null;\n\n if (value.length() > 0)\n {\n if (!value.equals(\"-1 -1\"))\n {\n Calendar cal = DateHelper.popCalendar(JAVA_EPOCH);\n\n int index = value.indexOf(' ');\n if (index == -1)\n {\n if (value.length() < 6)\n {\n value = \"000000\" + value;\n value = value.substring(value.length() - 6);\n }\n\n int hours = Integer.parseInt(value.substring(0, 2));\n int minutes = Integer.parseInt(value.substring(2, 4));\n int seconds = Integer.parseInt(value.substring(4));\n\n cal.set(Calendar.HOUR, hours);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.SECOND, seconds);\n }\n else\n {\n long astaDays = Long.parseLong(value.substring(0, index));\n int astaSeconds = Integer.parseInt(value.substring(index + 1));\n\n cal.add(Calendar.DAY_OF_YEAR, (int) (astaDays - ASTA_EPOCH));\n cal.set(Calendar.MILLISECOND, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.HOUR, 0);\n cal.add(Calendar.SECOND, astaSeconds);\n }\n\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n }\n\n return result;\n }", "protected NodeData createPageStyle()\n {\n NodeData ret = createBlockStyle();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"position\", tf.createIdent(\"relative\")));\n\t\tret.push(createDeclaration(\"border-width\", tf.createLength(1f, Unit.px)));\n\t\tret.push(createDeclaration(\"border-style\", tf.createIdent(\"solid\")));\n\t\tret.push(createDeclaration(\"border-color\", tf.createColor(0, 0, 255)));\n\t\tret.push(createDeclaration(\"margin\", tf.createLength(0.5f, Unit.em)));\n\t\t\n PDRectangle layout = getCurrentMediaBox();\n if (layout != null)\n {\n float w = layout.getWidth();\n float h = layout.getHeight();\n final int rot = pdpage.getRotation();\n if (rot == 90 || rot == 270)\n {\n float x = w; w = h; h = x;\n }\n \n ret.push(createDeclaration(\"width\", tf.createLength(w, unit)));\n ret.push(createDeclaration(\"height\", tf.createLength(h, unit)));\n }\n else\n log.warn(\"No media box found\");\n \n return ret;\n }", "public Date getFinish()\n {\n Date result = (Date) getCachedValue(AssignmentField.FINISH);\n if (result == null)\n {\n result = getTask().getFinish();\n }\n return result;\n }", "protected Map<String, AbstractServer> createServices(ServerSetup[] config, Managers mgr) {\r\n Map<String, AbstractServer> srvc = new HashMap<>();\r\n for (ServerSetup setup : config) {\r\n if (srvc.containsKey(setup.getProtocol())) {\r\n throw new IllegalArgumentException(\"Server '\" + setup.getProtocol() + \"' was found at least twice in the array\");\r\n }\r\n final String protocol = setup.getProtocol();\r\n if (protocol.startsWith(ServerSetup.PROTOCOL_SMTP)) {\r\n srvc.put(protocol, new SmtpServer(setup, mgr));\r\n } else if (protocol.startsWith(ServerSetup.PROTOCOL_POP3)) {\r\n srvc.put(protocol, new Pop3Server(setup, mgr));\r\n } else if (protocol.startsWith(ServerSetup.PROTOCOL_IMAP)) {\r\n srvc.put(protocol, new ImapServer(setup, mgr));\r\n }\r\n }\r\n return srvc;\r\n }", "private boolean hasMultipleCostRates()\n {\n boolean result = false;\n CostRateTable table = getCostRateTable();\n if (table != null)\n {\n //\n // We assume here that if there is just one entry in the cost rate\n // table, this is an open ended rate which covers any work, it won't\n // have specific dates attached to it.\n //\n if (table.size() > 1)\n {\n //\n // If we have multiple rates in the table, see if the same rate\n // is in force at the start and the end of the aaaignment.\n //\n CostRateTableEntry startEntry = table.getEntryByDate(getStart());\n CostRateTableEntry finishEntry = table.getEntryByDate(getFinish());\n result = (startEntry != finishEntry);\n }\n }\n return result;\n }", "@NonNull\n @SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher reset() {\n lastResponsePage = 0;\n lastRequestPage = 0;\n lastResponseId = 0;\n endReached = false;\n clearFacetRefinements();\n cancelPendingRequests();\n numericRefinements.clear();\n return this;\n }", "private String mountPath(CdjStatus.TrackSourceSlot slot) {\n switch (slot) {\n case SD_SLOT: return \"/B/\";\n case USB_SLOT: return \"/C/\";\n }\n throw new IllegalArgumentException(\"Don't know how to NFS mount filesystem for slot \" + slot);\n }", "private void processDumpFileContentsRecovery(InputStream inputStream)\n\t\t\tthrows IOException {\n\t\tJsonDumpFileProcessor.logger\n\t\t\t\t.warn(\"Entering recovery mode to parse rest of file. This might be slightly slower.\");\n\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(\n\t\t\t\tinputStream));\n\n\t\tString line = br.readLine();\n\t\tif (line == null) { // can happen if iterator already has consumed all\n\t\t\t\t\t\t\t// the stream\n\t\t\treturn;\n\t\t}\n\t\tif (line.length() >= 100) {\n\t\t\tline = line.substring(0, 100) + \"[...]\"\n\t\t\t\t\t+ line.substring(line.length() - 50);\n\t\t}\n\t\tJsonDumpFileProcessor.logger.warn(\"Skipping rest of current line: \"\n\t\t\t\t+ line);\n\n\t\tline = br.readLine();\n\t\twhile (line != null && line.length() > 1) {\n\t\t\ttry {\n\t\t\t\tEntityDocument document;\n\t\t\t\tif (line.charAt(line.length() - 1) == ',') {\n\t\t\t\t\tdocument = documentReader.readValue(line.substring(0,\n\t\t\t\t\t\t\tline.length() - 1));\n\t\t\t\t} else {\n\t\t\t\t\tdocument = documentReader.readValue(line);\n\t\t\t\t}\n\t\t\t\thandleDocument(document);\n\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\tlogJsonProcessingException(e);\n\t\t\t\tJsonDumpFileProcessor.logger.error(\"Problematic line was: \"\n\t\t\t\t\t\t+ line.substring(0, Math.min(50, line.length()))\n\t\t\t\t\t\t+ \"...\");\n\t\t\t}\n\n\t\t\tline = br.readLine();\n\t\t}\n\t}" ]
Adds a new metadata value. @param path the path that designates the key. Must be prefixed with a "/". @param value the value. @return this metadata object.
[ "public Metadata add(String path, String value) {\n this.values.add(this.pathToProperty(path), value);\n this.addOp(\"add\", path, value);\n return this;\n }" ]
[ "public static Configuration getDefaultFreemarkerConfiguration()\n {\n freemarker.template.Configuration configuration = new freemarker.template.Configuration(Configuration.VERSION_2_3_26);\n DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_26);\n objectWrapperBuilder.setUseAdaptersForContainers(true);\n objectWrapperBuilder.setIterableSupport(true);\n configuration.setObjectWrapper(objectWrapperBuilder.build());\n configuration.setAPIBuiltinEnabled(true);\n\n configuration.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader());\n configuration.setTemplateUpdateDelayMilliseconds(3600);\n return configuration;\n }", "public Results analyze(RuleSet ruleSet) {\r\n long startTime = System.currentTimeMillis();\r\n DirectoryResults reportResults = new DirectoryResults();\r\n\r\n int numThreads = Runtime.getRuntime().availableProcessors() - 1;\r\n numThreads = numThreads > 0 ? numThreads : 1;\r\n\r\n ExecutorService pool = Executors.newFixedThreadPool(numThreads);\r\n\r\n for (FileSet fileSet : fileSets) {\r\n processFileSet(fileSet, ruleSet, pool);\r\n }\r\n\r\n pool.shutdown();\r\n\r\n try {\r\n boolean completed = pool.awaitTermination(POOL_TIMEOUT_SECONDS, TimeUnit.SECONDS);\r\n if (!completed) {\r\n throw new IllegalStateException(\"Thread Pool terminated before comp<FileResults>letion\");\r\n }\r\n } catch (InterruptedException e) {\r\n throw new IllegalStateException(\"Thread Pool interrupted before completion\");\r\n }\r\n\r\n addDirectoryResults(reportResults);\r\n LOG.info(\"Analysis time=\" + (System.currentTimeMillis() - startTime) + \"ms\");\r\n return reportResults;\r\n }", "private ResourceAssignment getExistingResourceAssignment(Resource resource)\n {\n ResourceAssignment assignment = null;\n Integer resourceUniqueID = null;\n\n if (resource != null)\n {\n Iterator<ResourceAssignment> iter = m_assignments.iterator();\n resourceUniqueID = resource.getUniqueID();\n\n while (iter.hasNext() == true)\n {\n assignment = iter.next();\n Integer uniqueID = assignment.getResourceUniqueID();\n if (uniqueID != null && uniqueID.equals(resourceUniqueID) == true)\n {\n break;\n }\n assignment = null;\n }\n }\n\n return assignment;\n }", "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 }", "@SuppressWarnings(\"unchecked\")\n protected String addPostRunDependent(Appliable<? extends Indexable> appliable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) appliable;\n return this.addPostRunDependent(dependency);\n }", "public ItemRequest<Task> addFollowers(String task) {\n \n String path = String.format(\"/tasks/%s/addFollowers\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "public HttpConnection setRequestBody(final String input) {\n try {\n final byte[] inputBytes = input.getBytes(\"UTF-8\");\n return setRequestBody(inputBytes);\n } catch (UnsupportedEncodingException e) {\n // This should never happen as every implementation of the java platform is required\n // to support UTF-8.\n throw new RuntimeException(e);\n }\n }", "public Date getStartDate()\n {\n Date result = (Date) getCachedValue(ProjectField.START_DATE);\n if (result == null)\n {\n result = getParentFile().getStartDate();\n }\n return (result);\n }", "private static boolean matches(@Nonnull final Pattern pattern, @Nonnull final CharSequence chars) {\n\t\treturn pattern.matcher(chars).matches();\n\t}" ]
Set the value of one or more fields based on the contents of a database row. @param map column to field map @param row database row @param container field container
[ "private void setFields(Map<String, FieldType> map, MapRow row, FieldContainer container)\n {\n if (row != null)\n {\n for (Map.Entry<String, FieldType> entry : map.entrySet())\n {\n container.set(entry.getValue(), row.getObject(entry.getKey()));\n }\n }\n }" ]
[ "public static base_response delete(nitro_service client, String servicename) throws Exception {\n\t\tgslbservice deleteresource = new gslbservice();\n\t\tdeleteresource.servicename = servicename;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static ServiceActivator create(final ModelNode endpointConfig, final URI managementURI, final String serverName, final String serverProcessName,\n final String authKey, final boolean managementSubsystemEndpoint, final Supplier<SSLContext> sslContextSupplier) {\n\n return new DomainServerCommunicationServices(endpointConfig, managementURI, serverName, serverProcessName, authKey, managementSubsystemEndpoint, sslContextSupplier);\n }", "private void appendJoinSQL92(Join join, StringBuffer where, StringBuffer buf)\r\n {\r\n if (join.isOuter)\r\n {\r\n buf.append(\" LEFT OUTER JOIN \");\r\n }\r\n else\r\n {\r\n buf.append(\" INNER JOIN \");\r\n }\r\n if (join.right.hasJoins())\r\n {\r\n buf.append(\"(\");\r\n appendTableWithJoins(join.right, where, buf);\r\n buf.append(\")\");\r\n }\r\n else\r\n {\r\n appendTableWithJoins(join.right, where, buf);\r\n }\r\n buf.append(\" ON \");\r\n join.appendJoinEqualities(buf);\r\n }", "public static InstalledIdentity load(final InstalledImage installedImage, final ProductConfig productConfig, List<File> moduleRoots, final List<File> bundleRoots) throws IOException {\n return LayersFactory.load(installedImage, productConfig, moduleRoots, bundleRoots);\n }", "@SuppressWarnings(\"unchecked\")\n\tpublic <S extends IPAddressPartConfiguredString<T, P>> SQLStringMatcher<T, P, S> getNetworkStringMatcher(boolean isEntireAddress, IPAddressSQLTranslator translator) {\n\t\treturn new SQLStringMatcher<T, P, S>((S) this, isEntireAddress, translator);\n\t}", "private <T> CoreRemoteMongoCollection<T> getRemoteCollection(\n final MongoNamespace namespace,\n final Class<T> resultClass\n ) {\n return remoteClient\n .getDatabase(namespace.getDatabaseName())\n .getCollection(namespace.getCollectionName(), resultClass);\n }", "public void removeHoursFromDay(ProjectCalendarHours hours)\n {\n if (hours.getParentCalendar() != this)\n {\n throw new IllegalArgumentException();\n }\n m_hours[hours.getDay().getValue() - 1] = null;\n }", "public synchronized void shutdown() {\n checkIsRunning();\n try {\n beanManager().fireEvent(new ContainerBeforeShutdown(id), BeforeDestroyed.Literal.APPLICATION);\n } finally {\n discard(id);\n // Destroy all the dependent beans correctly\n creationalContext.release();\n beanManager().fireEvent(new ContainerShutdown(id), Destroyed.Literal.APPLICATION);\n bootstrap.shutdown();\n WeldSELogger.LOG.weldContainerShutdown(id);\n }\n }", "private boolean detectWSAddressingFeature(InterceptorProvider provider, Bus bus) {\n //detect on the bus level\n if (bus.getFeatures() != null) {\n Iterator<Feature> busFeatures = bus.getFeatures().iterator();\n while (busFeatures.hasNext()) {\n Feature busFeature = busFeatures.next();\n if (busFeature instanceof WSAddressingFeature) {\n return true;\n }\n }\n }\n\n //detect on the endpoint/client level\n Iterator<Interceptor<? extends Message>> interceptors = provider.getInInterceptors().iterator();\n while (interceptors.hasNext()) {\n Interceptor<? extends Message> ic = interceptors.next();\n if (ic instanceof MAPAggregator) {\n return true;\n }\n }\n\n return false;\n }" ]
Returns the name from the inverse side if the given property de-notes a one-to-one association.
[ "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 static String toJson(Calendar cal) {\n if (cal == null) {\n return NULL_VALUE;\n }\n\n CharBuf buffer = CharBuf.create(26);\n writeDate(cal.getTime(), buffer);\n\n return buffer.toString();\n }", "private void setBelief(String bName, Object value) {\n introspector.setBeliefValue(this.getLocalName(), bName, value, null);\n }", "public static void checkOperatorIsValid(int operatorCode) {\n switch (operatorCode) {\n case OPERATOR_LT:\n case OPERATOR_LE:\n case OPERATOR_EQ:\n case OPERATOR_NE:\n case OPERATOR_GE:\n case OPERATOR_GT:\n case OPERATOR_UNKNOWN:\n return;\n default:\n throw new IllegalStateException(String.format(Locale.US, ERROR_INVALID_CODE, operatorCode));\n }\n }", "public static base_response unset(nitro_service client, nsconfig resource, String[] args) throws Exception{\n\t\tnsconfig unsetresource = new nsconfig();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public static RebalanceTaskInfo decodeRebalanceTaskInfoMap(VAdminProto.RebalanceTaskInfoMap rebalanceTaskInfoMap) {\n RebalanceTaskInfo rebalanceTaskInfo = new RebalanceTaskInfo(\n rebalanceTaskInfoMap.getStealerId(),\n rebalanceTaskInfoMap.getDonorId(),\n decodeStoreToPartitionIds(rebalanceTaskInfoMap.getPerStorePartitionIdsList()),\n new ClusterMapper().readCluster(new StringReader(rebalanceTaskInfoMap.getInitialCluster())));\n return rebalanceTaskInfo;\n }", "public GVRSceneObject startDrag(GVRSceneObject dragMe, float relX, float relY, float relZ) {\n synchronized (mLock) {\n if (mCursorController == null) {\n Log.w(TAG, \"Physics drag failed: Cursor controller not found!\");\n return null;\n }\n\n if (mDragMe != null) {\n Log.w(TAG, \"Physics drag failed: Previous drag wasn't finished!\");\n return null;\n }\n\n if (mPivotObject == null) {\n mPivotObject = onCreatePivotObject(mContext);\n }\n\n mDragMe = dragMe;\n\n GVRTransform t = dragMe.getTransform();\n\n /* It is not possible to drag a rigid body directly, we need a pivot object.\n We are using the pivot object's position as pivot of the dragging's physics constraint.\n */\n mPivotObject.getTransform().setPosition(t.getPositionX() + relX,\n t.getPositionY() + relY, t.getPositionZ() + relZ);\n\n mCursorController.startDrag(mPivotObject);\n }\n\n return mPivotObject;\n }", "public void start(GVRAccessibilitySpeechListener speechListener) {\n mTts.setSpeechListener(speechListener);\n mTts.getSpeechRecognizer().startListening(mTts.getSpeechRecognizerIntent());\n }", "protected void updateRotator(DMatrixRMaj Q , int m, int n, double c, double s) {\n int rowA = m*Q.numCols;\n int rowB = n*Q.numCols;\n\n// for( int i = 0; i < Q.numCols; i++ ) {\n// double a = Q.get(rowA+i);\n// double b = Q.get(rowB+i);\n// Q.set( rowA+i, c*a + s*b);\n// Q.set( rowB+i, -s*a + c*b);\n// }\n// System.out.println(\"------ AFter Update Rotator \"+m+\" \"+n);\n// Q.print();\n// System.out.println();\n int endA = rowA + Q.numCols;\n for( ; rowA != endA; rowA++ , rowB++ ) {\n double a = Q.get(rowA);\n double b = Q.get(rowB);\n Q.set(rowA, c*a + s*b);\n Q.set(rowB, -s*a + c*b);\n }\n }", "public GroovyMethodDoc[] methods() {\n Collections.sort(methods);\n return methods.toArray(new GroovyMethodDoc[methods.size()]);\n }" ]
Sends all events to the web service. Events will be transformed with mapper before sending. @param events the events
[ "public void putEvents(List<Event> events) {\n Exception lastException;\n List<EventType> eventTypes = new ArrayList<EventType>();\n for (Event event : events) {\n EventType eventType = EventMapper.map(event);\n eventTypes.add(eventType);\n }\n\n int i = 0;\n lastException = null;\n while (i < numberOfRetries) {\n try {\n monitoringService.putEvents(eventTypes);\n break;\n } catch (Exception e) {\n lastException = e;\n i++;\n }\n if(i < numberOfRetries) {\n try {\n Thread.sleep(delayBetweenRetry);\n } catch (InterruptedException e) {\n break;\n }\n }\n }\n\n if (i == numberOfRetries) {\n throw new MonitoringException(\"1104\", \"Could not send events to monitoring service after \"\n + numberOfRetries + \" retries.\", lastException, events);\n }\n }" ]
[ "public static base_responses add(nitro_service client, clusternodegroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusternodegroup addresources[] = new clusternodegroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new clusternodegroup();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].strict = resources[i].strict;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static authenticationtacacspolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationtacacspolicy_authenticationvserver_binding obj = new authenticationtacacspolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationtacacspolicy_authenticationvserver_binding response[] = (authenticationtacacspolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void sendMessageToAgents(String[] agent_name, String msgtype,\n Object message_content, Connector connector) {\n HashMap<String, Object> hm = new HashMap<String, Object>();\n hm.put(\"performative\", msgtype);\n hm.put(SFipa.CONTENT, message_content);\n IComponentIdentifier[] ici = new IComponentIdentifier[agent_name.length];\n for (int i = 0; i < agent_name.length; i++) {\n ici[i] = (IComponentIdentifier) connector.getAgentID(agent_name[i]);\n }\n ((IMessageService) connector.getMessageService()).deliverMessage(hm,\n \"fipa\", ici);\n }", "public void setCurrencyDigits(Integer currDigs)\n {\n if (currDigs == null)\n {\n currDigs = DEFAULT_CURRENCY_DIGITS;\n }\n set(ProjectField.CURRENCY_DIGITS, currDigs);\n }", "@NonNull\n @UiThread\n private HashMap<Integer, Boolean> generateExpandedStateMap() {\n HashMap<Integer, Boolean> parentHashMap = new HashMap<>();\n int childCount = 0;\n\n int listItemCount = mFlatItemList.size();\n for (int i = 0; i < listItemCount; i++) {\n if (mFlatItemList.get(i) != null) {\n ExpandableWrapper<P, C> listItem = mFlatItemList.get(i);\n if (listItem.isParent()) {\n parentHashMap.put(i - childCount, listItem.isExpanded());\n } else {\n childCount++;\n }\n }\n }\n\n return parentHashMap;\n }", "public Iterator getAllExtentClasses()\r\n {\r\n ArrayList subTypes = new ArrayList();\r\n\r\n subTypes.addAll(_extents);\r\n\r\n for (int idx = 0; idx < subTypes.size(); idx++)\r\n {\r\n ClassDescriptorDef curClassDef = (ClassDescriptorDef)subTypes.get(idx);\r\n\r\n for (Iterator it = curClassDef.getExtentClasses(); it.hasNext();)\r\n {\r\n ClassDescriptorDef curSubTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n if (!subTypes.contains(curSubTypeDef))\r\n {\r\n subTypes.add(curSubTypeDef);\r\n }\r\n }\r\n }\r\n return subTypes.iterator();\r\n }", "private void writeAssignmentTimephasedData(ResourceAssignment mpx, Project.Assignments.Assignment xml)\n {\n if (m_writeTimphasedData && mpx.getHasTimephasedData())\n {\n List<TimephasedDataType> list = xml.getTimephasedData();\n ProjectCalendar calendar = mpx.getCalendar();\n BigInteger assignmentID = xml.getUID();\n\n List<TimephasedWork> complete = mpx.getTimephasedActualWork();\n List<TimephasedWork> planned = mpx.getTimephasedWork();\n\n if (m_splitTimephasedAsDays)\n {\n TimephasedWork lastComplete = null;\n if (complete != null && !complete.isEmpty())\n {\n lastComplete = complete.get(complete.size() - 1);\n }\n\n TimephasedWork firstPlanned = null;\n if (planned != null && !planned.isEmpty())\n {\n firstPlanned = planned.get(0);\n }\n\n if (planned != null)\n {\n planned = splitDays(calendar, mpx.getTimephasedWork(), null, lastComplete);\n }\n\n if (complete != null)\n {\n complete = splitDays(calendar, complete, firstPlanned, null);\n }\n }\n\n if (planned != null)\n {\n writeAssignmentTimephasedData(assignmentID, list, planned, 1);\n }\n\n if (complete != null)\n {\n writeAssignmentTimephasedData(assignmentID, list, complete, 2);\n }\n }\n }", "public int executeTask(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, final ServerUpdateTask task) {\n try {\n return execute(listener, task.getServerIdentity(), task.getOperation());\n } catch (OperationFailedException e) {\n // Handle failures operation transformation failures\n final ServerIdentity identity = task.getServerIdentity();\n final ServerOperation serverOperation = new ServerOperation(identity, task.getOperation(), null, null, OperationResultTransformer.ORIGINAL_RESULT);\n final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e);\n listener.operationPrepared(result);\n recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), OperationResultTransformer.ORIGINAL_RESULT));\n return 1; // 1 ms timeout since there is no reason to wait for the locally stored result\n }\n\n }", "public static configstatus[] get(nitro_service service) throws Exception{\n\t\tconfigstatus obj = new configstatus();\n\t\tconfigstatus[] response = (configstatus[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Logs binary string as hexadecimal
[ "private void logBinaryStringInfo(StringBuilder binaryString) {\n\n encodeInfo += \"Binary Length: \" + binaryString.length() + \"\\n\";\n encodeInfo += \"Binary String: \";\n\n int nibble = 0;\n for (int i = 0; i < binaryString.length(); i++) {\n switch (i % 4) {\n case 0:\n if (binaryString.charAt(i) == '1') {\n nibble += 8;\n }\n break;\n case 1:\n if (binaryString.charAt(i) == '1') {\n nibble += 4;\n }\n break;\n case 2:\n if (binaryString.charAt(i) == '1') {\n nibble += 2;\n }\n break;\n case 3:\n if (binaryString.charAt(i) == '1') {\n nibble += 1;\n }\n encodeInfo += Integer.toHexString(nibble);\n nibble = 0;\n break;\n }\n }\n\n if ((binaryString.length() % 4) != 0) {\n encodeInfo += Integer.toHexString(nibble);\n }\n\n encodeInfo += \"\\n\";\n }" ]
[ "public void setFieldConversionClassName(String fieldConversionClassName)\r\n {\r\n try\r\n {\r\n this.fieldConversion = (FieldConversion) ClassHelper.newInstance(fieldConversionClassName);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\r\n \"Could not instantiate FieldConversion class using default constructor\", e);\r\n }\r\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 }", "void backupConfiguration() throws IOException {\n\n final String configuration = Constants.CONFIGURATION;\n\n final File a = new File(installedImage.getAppClientDir(), configuration);\n final File d = new File(installedImage.getDomainDir(), configuration);\n final File s = new File(installedImage.getStandaloneDir(), configuration);\n\n if (a.exists()) {\n final File ab = new File(configBackup, Constants.APP_CLIENT);\n backupDirectory(a, ab);\n }\n if (d.exists()) {\n final File db = new File(configBackup, Constants.DOMAIN);\n backupDirectory(d, db);\n }\n if (s.exists()) {\n final File sb = new File(configBackup, Constants.STANDALONE);\n backupDirectory(s, sb);\n }\n\n }", "private String getClassNameFromPath(String path) {\n String className = path.replace(\".class\", \"\");\n\n // for *nix\n if (className.startsWith(\"/\")) {\n className = className.substring(1, className.length());\n }\n className = className.replace(\"/\", \".\");\n\n // for windows\n if (className.startsWith(\"\\\\\")) {\n className = className.substring(1, className.length());\n }\n className = className.replace(\"\\\\\", \".\");\n\n return className;\n }", "protected boolean isFirstVisit(Object expression) {\r\n if (visited.contains(expression)) {\r\n return false;\r\n }\r\n visited.add(expression);\r\n return true;\r\n }", "private void updateMax(MtasRBTreeNode n, MtasRBTreeNode c) {\n if (c != null) {\n if (n.max < c.max) {\n n.max = c.max;\n }\n }\n }", "protected <T> T getProperty(String key, Class<T> type) {\n Object returnValue = getProperty(key);\n if (returnValue != null) {\n return (T) returnValue;\n } else {\n return null;\n }\n }", "private static Object checkComponentType(Object array, Class<?> expectedComponentType) {\n\t\tClass<?> actualComponentType = array.getClass().getComponentType();\n\t\tif (!expectedComponentType.isAssignableFrom(actualComponentType)) {\n\t\t\tthrow new ArrayStoreException(\n\t\t\t\t\tString.format(\"The expected component type %s is not assignable from the actual type %s\",\n\t\t\t\t\t\t\texpectedComponentType.getCanonicalName(), actualComponentType.getCanonicalName()));\n\t\t}\n\t\treturn array;\n\t}", "private int getMaxHeight() {\n int result = 0;\n for (int i = 0; i < segmentCount; i++) {\n result = Math.max(result, segmentHeight(i, false));\n }\n return result;\n }" ]
Consumes the next character in the request, checking that it matches the expected one. This method should be used when the
[ "protected void consumeChar(ImapRequestLineReader request, char expected)\n throws ProtocolException {\n char consumed = request.consume();\n if (consumed != expected) {\n throw new ProtocolException(\"Expected:'\" + expected + \"' found:'\" + consumed + '\\'');\n }\n }" ]
[ "public void seek(final int position) throws IOException {\n if (position < 0) {\n throw new IllegalArgumentException(\"position < 0: \" + position);\n }\n if (position > size) {\n throw new EOFException();\n }\n this.pointer = position;\n }", "@UiHandler({\"m_atMonth\", \"m_everyMonth\"})\r\n void onMonthChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setMonth(event.getValue());\r\n }\r\n }", "protected <E> E read(Supplier<E> sup) {\n try {\n this.lock.readLock().lock();\n return sup.get();\n } finally {\n this.lock.readLock().unlock();\n }\n }", "public static Object toObject(Class<?> clazz, Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (clazz == null) {\n return value;\n }\n\n if (java.sql.Date.class.isAssignableFrom(clazz)) {\n return toDate(value);\n }\n if (java.sql.Time.class.isAssignableFrom(clazz)) {\n return toTime(value);\n }\n if (java.sql.Timestamp.class.isAssignableFrom(clazz)) {\n return toTimestamp(value);\n }\n if (java.util.Date.class.isAssignableFrom(clazz)) {\n return toDateTime(value);\n }\n\n return value;\n }", "protected static JRDesignExpression getExpressionFromVariable(JRDesignVariable var){\n\t\tJRDesignExpression exp = new JRDesignExpression();\n\t\texp.setText(\"$V{\" + var.getName() + \"}\");\n\t\texp.setValueClass(var.getValueClass());\n\t\treturn exp;\n\t}", "@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 }", "public static dnsaaaarec[] get(nitro_service service) throws Exception{\n\t\tdnsaaaarec obj = new dnsaaaarec();\n\t\tdnsaaaarec[] response = (dnsaaaarec[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static double[] toDouble(int[] array) {\n double[] n = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n n[i] = (double) array[i];\n }\n return n;\n }", "public void remove(Identity oid)\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"Remove object \" + oid);\r\n sessionCache.remove(oid);\r\n getApplicationCache().remove(oid);\r\n }" ]
helper method to activate or deactivate a specific flag @param bits @param on
[ "public static void setFlag(Activity activity, final int bits, boolean on) {\n Window win = activity.getWindow();\n WindowManager.LayoutParams winParams = win.getAttributes();\n if (on) {\n winParams.flags |= bits;\n } else {\n winParams.flags &= ~bits;\n }\n win.setAttributes(winParams);\n }" ]
[ "protected void processStart(Endpoint endpoint, EventTypeEnum eventType) {\n if (!sendLifecycleEvent) {\n return;\n }\n\n Event event = createEvent(endpoint, eventType);\n queue.add(event);\n }", "public DynamicReportBuilder setProperty(String name, String value) {\n this.report.setProperty(name, value);\n return this;\n }", "@SuppressWarnings(\"unchecked\")\n public T toObject(byte[] bytes) {\n try {\n return (T) new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject();\n } catch(IOException e) {\n throw new SerializationException(e);\n } catch(ClassNotFoundException c) {\n throw new SerializationException(c);\n }\n }", "public static appflowpolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tappflowpolicylabel obj = new appflowpolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tappflowpolicylabel response = (appflowpolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}", "@SuppressWarnings(\"deprecation\")\n\tpublic static boolean dateEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getDate() == d2.getDate()\n && d1.getMonth() == d2.getMonth()\n && d1.getYear() == d2.getYear();\n }", "public static base_response delete(nitro_service client, String jsoncontenttypevalue) throws Exception {\n\t\tappfwjsoncontenttype deleteresource = new appfwjsoncontenttype();\n\t\tdeleteresource.jsoncontenttypevalue = jsoncontenttypevalue;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "private static Class getClassForClassNode(ClassNode type) {\r\n // todo hamlet - move to a different \"InferenceUtil\" object\r\n Class primitiveType = getPrimitiveType(type);\r\n if (primitiveType != null) {\r\n return primitiveType;\r\n } else if (classNodeImplementsType(type, String.class)) {\r\n return String.class;\r\n } else if (classNodeImplementsType(type, ReentrantLock.class)) {\r\n return ReentrantLock.class;\r\n } else if (type.getName() != null && type.getName().endsWith(\"[]\")) {\r\n return Object[].class; // better type inference could be done, but oh well\r\n }\r\n return null;\r\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 }", "private ModelNode parseAddress(final String profileName, final String inputAddress) {\n final ModelNode result = new ModelNode();\n if (profileName != null) {\n result.add(ServerOperations.PROFILE, profileName);\n }\n String[] parts = inputAddress.split(\",\");\n for (String part : parts) {\n String[] address = part.split(\"=\");\n if (address.length != 2) {\n throw new RuntimeException(part + \" is not a valid address segment\");\n }\n result.add(address[0], address[1]);\n }\n return result;\n }" ]
Removes from this set all of its elements that are contained in the specified members array @param members the members to remove @return the number of members actually removed
[ "public long removeAll(final String... members) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.srem(getKey(), members);\n }\n });\n }" ]
[ "public List<T> nextPermutationAsList()\n {\n List<T> permutation = new ArrayList<T>(elements.length);\n return nextPermutationAsList(permutation);\n }", "private void checkReadonlyAccessForNativePKs(FieldDescriptorDef fieldDef, String checkLevel)\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String access = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ACCESS);\r\n String autoInc = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_AUTOINCREMENT);\r\n\r\n if (\"database\".equals(autoInc) && !\"readonly\".equals(access))\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"checkAccess\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" is set to database auto-increment. Therefore the field's access is set to 'readonly'.\");\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_ACCESS, \"readonly\");\r\n }\r\n }", "public static Class<?> loadClass(String className) {\n try {\n return Class.forName(className);\n } catch(ClassNotFoundException e) {\n throw new IllegalArgumentException(e);\n }\n }", "void parseWorkerThreadPool(final XMLExtendedStreamReader reader, final ModelNode subsystemAdd) throws XMLStreamException {\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n requireNoNamespaceAttribute(reader, i);\n final String value = reader.getAttributeValue(i);\n final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));\n switch (attribute) {\n case WORKER_READ_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_READ_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_READ_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_READ_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_CORE_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_CORE_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_CORE_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_TASK_CORE_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_KEEPALIVE:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_KEEPALIVE)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_KEEPALIVE);\n }\n RemotingSubsystemRootResource.WORKER_TASK_KEEPALIVE.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_LIMIT:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_LIMIT)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_LIMIT);\n }\n RemotingSubsystemRootResource.WORKER_TASK_LIMIT.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_MAX_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_MAX_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_MAX_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_TASK_MAX_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_WRITE_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_WRITE_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_WRITE_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_WRITE_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n default:\n throw unexpectedAttribute(reader, i);\n }\n }\n requireNoContent(reader);\n }", "private BigInteger getTaskCalendarID(Task mpx)\n {\n BigInteger result = null;\n ProjectCalendar cal = mpx.getCalendar();\n if (cal != null)\n {\n result = NumberHelper.getBigInteger(cal.getUniqueID());\n }\n else\n {\n result = NULL_CALENDAR_ID;\n }\n return (result);\n }", "public String getStatement() throws SQLException {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tappendSql(null, sb, new ArrayList<ArgumentHolder>());\n\t\treturn sb.toString();\n\t}", "public boolean putAtomic(C instance, K key, V value, Map<K, V> snapshot) {\n Assert.checkNotNullParam(\"key\", key);\n final Map<K, V> newMap;\n final int oldSize = snapshot.size();\n if (oldSize == 0) {\n newMap = Collections.singletonMap(key, value);\n } else if (oldSize == 1) {\n final Map.Entry<K, V> entry = snapshot.entrySet().iterator().next();\n final K oldKey = entry.getKey();\n if (oldKey.equals(key)) {\n return false;\n } else {\n newMap = new FastCopyHashMap<K, V>(snapshot);\n newMap.put(key, value);\n }\n } else {\n newMap = new FastCopyHashMap<K, V>(snapshot);\n newMap.put(key, value);\n }\n return updater.compareAndSet(instance, snapshot, newMap);\n }", "private static void reverse(int first, int last, Swapper swapper) {\r\n\t// no more needed since manually inlined\r\n\twhile (first < --last) {\r\n\t\tswapper.swap(first++,last);\r\n\t}\r\n}", "static void cleanup(final Resource resource) {\n synchronized (resource) {\n for (final Resource.ResourceEntry entry : resource.getChildren(SUBSYSTEM)) {\n resource.removeChild(entry.getPathElement());\n }\n for (final Resource.ResourceEntry entry : resource.getChildren(SUBDEPLOYMENT)) {\n resource.removeChild(entry.getPathElement());\n }\n }\n }" ]
Harvest a single value that was returned by a callable statement. @param obj the object that will receive the value that is harvested. @param callable the CallableStatement that contains the value to harvest @param fmd the FieldDescriptor that identifies the field where the harvested value will be stord. @param index the parameter index. @throws PersistenceBrokerSQLException if a problem occurs.
[ "private void harvestReturnValue(\r\n Object obj,\r\n CallableStatement callable,\r\n FieldDescriptor fmd,\r\n int index)\r\n throws PersistenceBrokerSQLException\r\n {\r\n\r\n try\r\n {\r\n // If we have a field descriptor, then we can harvest\r\n // the return value.\r\n if ((callable != null) && (fmd != null) && (obj != null))\r\n {\r\n // Get the value and convert it to it's appropriate\r\n // java type.\r\n Object value = fmd.getJdbcType().getObjectFromColumn(callable, index);\r\n\r\n // Set the value of the persistent field.\r\n fmd.getPersistentField().set(obj, fmd.getFieldConversion().sqlToJava(value));\r\n\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n String msg = \"SQLException during the execution of harvestReturnValue\"\r\n + \" class=\"\r\n + obj.getClass().getName()\r\n + \",\"\r\n + \" field=\"\r\n + fmd.getAttributeName()\r\n + \" : \"\r\n + e.getMessage();\r\n logger.error(msg,e);\r\n throw new PersistenceBrokerSQLException(msg, e);\r\n }\r\n }" ]
[ "private File getWorkDir() throws IOException\r\n {\r\n if (_workDir == null)\r\n { \r\n File dummy = File.createTempFile(\"dummy\", \".log\");\r\n String workDir = dummy.getPath().substring(0, dummy.getPath().lastIndexOf(File.separatorChar));\r\n \r\n if ((workDir == null) || (workDir.length() == 0))\r\n {\r\n workDir = \".\";\r\n }\r\n dummy.delete();\r\n _workDir = new File(workDir);\r\n }\r\n return _workDir;\r\n }", "public static 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 }", "private Profile getProfileFromResultSet(ResultSet result) throws Exception {\n Profile profile = new Profile();\n profile.setId(result.getInt(Constants.GENERIC_ID));\n Clob clobProfileName = result.getClob(Constants.PROFILE_PROFILE_NAME);\n String profileName = clobProfileName.getSubString(1, (int) clobProfileName.length());\n profile.setName(profileName);\n return profile;\n }", "@SuppressWarnings(\"WeakerAccess\")\n public static synchronized SlotReference getSlotReference(int player, CdjStatus.TrackSourceSlot slot) {\n Map<CdjStatus.TrackSourceSlot, SlotReference> playerMap = instances.get(player);\n if (playerMap == null) {\n playerMap = new HashMap<CdjStatus.TrackSourceSlot, SlotReference>();\n instances.put(player, playerMap);\n }\n SlotReference result = playerMap.get(slot);\n if (result == null) {\n result = new SlotReference(player, slot);\n playerMap.put(slot, result);\n }\n return result;\n }", "public Build createBuild(String appName, Build build) {\n return connection.execute(new BuildCreate(appName, build), apiKey);\n }", "protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading columns for table \" + getSchema().getCatalog().getCatalogName() + \".\" + getSchema().getSchemaName() + \".\" + getTableName());\r\n rs = getDbMeta().getColumns(getSchema().getCatalog().getCatalogName(), \r\n getSchema().getSchemaName(),\r\n getTableName(), \"%\");\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n while (rs.next())\r\n {\r\n alNew.add(new DBMetaColumnNode(getDbMeta(), getDbMetaTreeModel(), DBMetaTableNode.this, rs.getString(\"COLUMN_NAME\")));\r\n }\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaTableNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx2);\r\n }\r\n return false;\r\n }\r\n return true;\r\n }", "private void adjustOptionsColumn(\n CmsMessageBundleEditorTypes.EditMode oldMode,\n CmsMessageBundleEditorTypes.EditMode newMode) {\n\n if (m_model.isShowOptionsColumn(oldMode) != m_model.isShowOptionsColumn(newMode)) {\n m_table.removeGeneratedColumn(TableProperty.OPTIONS);\n if (m_model.isShowOptionsColumn(newMode)) {\n // Don't know why exactly setting the filter field invisible is necessary here,\n // it should be already set invisible - but apparently not setting it invisible again\n // will result in the field being visible.\n m_table.setFilterFieldVisible(TableProperty.OPTIONS, false);\n m_table.addGeneratedColumn(TableProperty.OPTIONS, m_optionsColumn);\n }\n }\n }", "public static Path createTempDirectory(Path dir, String prefix) throws IOException {\n try {\n return Files.createTempDirectory(dir, prefix);\n } catch (UnsupportedOperationException ex) {\n }\n return Files.createTempDirectory(dir, prefix);\n }", "protected void convertToHours(LinkedList<TimephasedWork> list)\n {\n for (TimephasedWork assignment : list)\n {\n Duration totalWork = assignment.getTotalAmount();\n Duration workPerDay = assignment.getAmountPerDay();\n totalWork = Duration.getInstance(totalWork.getDuration() / 60, TimeUnit.HOURS);\n workPerDay = Duration.getInstance(workPerDay.getDuration() / 60, TimeUnit.HOURS);\n assignment.setTotalAmount(totalWork);\n assignment.setAmountPerDay(workPerDay);\n }\n }" ]
Returns the output path specified on the javadoc options
[ "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 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 }", "private Integer getOutlineLevel(Task task)\n {\n String value = task.getWBS();\n Integer result = Integer.valueOf(1);\n if (value != null && value.length() > 0)\n {\n String[] path = WBS_SPLIT_REGEX.split(value);\n result = Integer.valueOf(path.length);\n }\n return result;\n }", "public static base_response unset(nitro_service client, ipv6 resource, String[] args) throws Exception{\n\t\tipv6 unsetresource = new ipv6();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "protected synchronized int loadSize() throws PersistenceBrokerException\r\n {\r\n PersistenceBroker broker = getBroker();\r\n try\r\n {\r\n return broker.getCount(getQuery());\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(ex);\r\n }\r\n finally\r\n {\r\n releaseBroker(broker);\r\n }\r\n }", "protected void internalClose() throws SQLException {\r\n\t\ttry {\r\n\t\t\tclearStatementCaches(true);\r\n\t\t\tif (this.connection != null){ // safety!\r\n\t\t\t\tthis.connection.close();\r\n\r\n\t\t\t\tif (!this.connectionTrackingDisabled && this.finalizableRefs != null){\r\n\t\t\t\t\tthis.finalizableRefs.remove(this.connection);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tthis.logicallyClosed.set(true);\r\n\t\t} catch (SQLException e) {\r\n\t\t\tthrow markPossiblyBroken(e);\r\n\t\t}\r\n\t}", "public static Method getBridgeMethodTarget(Method someMethod) {\n TraitBridge annotation = someMethod.getAnnotation(TraitBridge.class);\n if (annotation==null) {\n return null;\n }\n Class aClass = annotation.traitClass();\n String desc = annotation.desc();\n for (Method method : aClass.getDeclaredMethods()) {\n String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameterTypes());\n if (desc.equals(methodDescriptor)) {\n return method;\n }\n }\n return null;\n }", "private YearWeek with(int newYear, int newWeek) {\n if (year == newYear && week == newWeek) {\n return this;\n }\n return of(newYear, newWeek);\n }", "public static TransactionalProtocolClient.PreparedOperation<TransactionalProtocolClient.Operation> executeBlocking(final ModelNode operation, TransactionalProtocolClient client) throws IOException, InterruptedException {\n final BlockingQueueOperationListener<TransactionalProtocolClient.Operation> listener = new BlockingQueueOperationListener<>();\n client.execute(listener, operation, OperationMessageHandler.DISCARD, OperationAttachments.EMPTY);\n return listener.retrievePreparedOperation();\n }", "void recordOperationPrepareTimeout(final BlockingQueueOperationListener.FailedOperation<ServerOperation> failedOperation) {\n recordPreparedTask(new ServerTaskExecutor.ServerPreparedResponse(failedOperation));\n // Swap out the submitted task so we don't wait for the final result. Use a future the returns\n // prepared response\n ServerIdentity identity = failedOperation.getOperation().getIdentity();\n AsyncFuture<OperationResponse> finalResult = failedOperation.getFinalResult();\n synchronized (submittedTasks) {\n submittedTasks.put(identity, new ServerTaskExecutor.ExecutedServerRequest(identity, finalResult));\n }\n }" ]
Remove the S3 file that contains the domain controller data. @param directoryName the name of the directory that contains the S3 file
[ "private void remove(String directoryName) {\n if ((directoryName == null) || (conn == null))\n return;\n\n String key = S3Util.sanitize(directoryName) + \"/\" + S3Util.sanitize(DC_FILE_NAME);\n try {\n Map headers = new TreeMap();\n headers.put(\"Content-Type\", Arrays.asList(\"text/plain\"));\n if (usingPreSignedUrls()) {\n conn.delete(pre_signed_delete_url).connection.getResponseMessage();\n } else {\n conn.delete(location, key, headers).connection.getResponseMessage();\n }\n }\n catch(Exception e) {\n ROOT_LOGGER.cannotRemoveS3File(e);\n }\n }" ]
[ "public boolean setOverrideRepeatCount(String pathName, String methodName, Integer ordinal, Integer repeatCount) {\n try {\n String methodId = getOverrideIdForMethodName(methodName).toString();\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"profileIdentifier\", this._profileName),\n new BasicNameValuePair(\"ordinal\", ordinal.toString()),\n new BasicNameValuePair(\"repeatNumber\", repeatCount.toString())\n };\n\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName) + \"/\" + methodId, params));\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "public Headers getAllHeaders() {\n Headers requestHeaders = getHeaders();\n requestHeaders = hasPayload() ? requestHeaders.withContentType(getPayload().get().getMimeType()) : requestHeaders;\n //We don't want to add headers more than once.\n return requestHeaders;\n }", "protected void parseNegOp(TokenList tokens, Sequence sequence) {\n if( tokens.size == 0 )\n return;\n\n TokenList.Token token = tokens.first;\n\n while( token != null ) {\n TokenList.Token next = token.next;\n escape:\n if( token.getSymbol() == Symbol.MINUS ) {\n if( token.previous != null && token.previous.getType() != Type.SYMBOL)\n break escape;\n if( token.previous != null && token.previous.getType() == Type.SYMBOL &&\n (token.previous.symbol == Symbol.TRANSPOSE))\n break escape;\n if( token.next == null || token.next.getType() == Type.SYMBOL)\n break escape;\n\n if( token.next.getType() != Type.VARIABLE )\n throw new RuntimeException(\"Crap bug rethink this function\");\n\n // create the operation\n Operation.Info info = Operation.neg(token.next.getVariable(),functions.getManagerTemp());\n // add the operation to the sequence\n sequence.addOperation(info.op);\n // update the token list\n TokenList.Token t = new TokenList.Token(info.output);\n tokens.insert(token.next,t);\n tokens.remove(token.next);\n tokens.remove(token);\n next = t;\n }\n token = next;\n }\n }", "public String tag(ImapRequestLineReader request) throws ProtocolException {\n CharacterValidator validator = new TagCharValidator();\n return consumeWord(request, validator);\n }", "public TaskMode getTaskMode()\n {\n return BooleanHelper.getBoolean((Boolean) getCachedValue(TaskField.TASK_MODE)) ? TaskMode.MANUALLY_SCHEDULED : TaskMode.AUTO_SCHEDULED;\n }", "public com.cloudant.client.api.model.ReplicationResult trigger() {\r\n ReplicationResult couchDbReplicationResult = replication.trigger();\r\n com.cloudant.client.api.model.ReplicationResult replicationResult = new com.cloudant\r\n .client.api.model.ReplicationResult(couchDbReplicationResult);\r\n return replicationResult;\r\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 static List<DockerImage> getDockerImagesFromAgents(final int buildInfoId, TaskListener listener) throws IOException, InterruptedException {\n List<DockerImage> dockerImages = new ArrayList<DockerImage>();\n\n // Collect images from the master:\n dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));\n\n // Collect images from all the agents:\n List<Node> nodes = Jenkins.getInstance().getNodes();\n for (Node node : nodes) {\n if (node == null || node.getChannel() == null) {\n continue;\n }\n try {\n List<DockerImage> partialDockerImages = node.getChannel().call(new MasterToSlaveCallable<List<DockerImage>, IOException>() {\n public List<DockerImage> call() throws IOException {\n List<DockerImage> dockerImages = new ArrayList<DockerImage>();\n dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));\n return dockerImages;\n }\n });\n dockerImages.addAll(partialDockerImages);\n } catch (Exception e) {\n listener.getLogger().println(\"Could not collect docker images from Jenkins node '\" + node.getDisplayName() + \"' due to: \" + e.getMessage());\n }\n }\n return dockerImages;\n }", "public void putEvents(List<Event> events) {\n List<Event> filteredEvents = filterEvents(events);\n executeHandlers(filteredEvents);\n for (Event event : filteredEvents) {\n persistenceHandler.writeEvent(event);\n }\n }" ]
Use this API to fetch nstrafficdomain_binding resource of given name .
[ "public static nstrafficdomain_binding get(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_binding obj = new nstrafficdomain_binding();\n\t\tobj.set_td(td);\n\t\tnstrafficdomain_binding response = (nstrafficdomain_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "private static Map<String, Object> processConf(Map<String, ?> conf) {\n Map<String, Object> m = new HashMap<String, Object>(conf.size());\n for (String s : conf.keySet()) {\n Object o = conf.get(s);\n if (s.startsWith(\"act.\")) s = s.substring(4);\n m.put(s, o);\n m.put(Config.canonical(s), o);\n }\n return m;\n }", "public static void applyMultiIconTo(Drawable icon, int iconColor, Drawable selectedIcon, int selectedIconColor, boolean tinted, ImageView imageView) {\n //if we have an icon then we want to set it\n if (icon != null) {\n //if we got a different color for the selectedIcon we need a StateList\n if (selectedIcon != null) {\n if (tinted) {\n imageView.setImageDrawable(new PressedEffectStateListDrawable(icon, selectedIcon, iconColor, selectedIconColor));\n } else {\n imageView.setImageDrawable(UIUtils.getIconStateList(icon, selectedIcon));\n }\n } else if (tinted) {\n imageView.setImageDrawable(new PressedEffectStateListDrawable(icon, iconColor, selectedIconColor));\n } else {\n imageView.setImageDrawable(icon);\n }\n //make sure we display the icon\n imageView.setVisibility(View.VISIBLE);\n } else {\n //hide the icon\n imageView.setVisibility(View.GONE);\n }\n }", "public static Module unserializeModule(final String module) throws IOException {\n final ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n return mapper.readValue(module, Module.class);\n }", "protected final void setParentNode(final DiffNode parentNode)\n\t{\n\t\tif (this.parentNode != null && this.parentNode != parentNode)\n\t\t{\n\t\t\tthrow new IllegalStateException(\"The parent of a node cannot be changed, once it's set.\");\n\t\t}\n\t\tthis.parentNode = parentNode;\n\t}", "public int getVertices(double[] coords) {\n for (int i = 0; i < numVertices; i++) {\n Point3d pnt = pointBuffer[vertexPointIndices[i]].pnt;\n coords[i * 3 + 0] = pnt.x;\n coords[i * 3 + 1] = pnt.y;\n coords[i * 3 + 2] = pnt.z;\n }\n return numVertices;\n }", "public Map<String, CmsJspCategoryAccessBean> getReadResourceCategories() {\n\n if (null == m_resourceCategories) {\n m_resourceCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object resourceName) {\n\n try {\n CmsResource resource = m_cms.readResource(\n getRequestContext().removeSiteRoot((String)resourceName));\n return new CmsJspCategoryAccessBean(m_cms, resource);\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n });\n }\n return m_resourceCategories;\n }", "public ModelNode getDeploymentSubsystemModel(final String subsystemName) {\n assert subsystemName != null : \"The subsystemName cannot be null\";\n return getDeploymentSubModel(subsystemName, PathAddress.EMPTY_ADDRESS, null, deploymentUnit);\n }", "public void readLock(EntityKey key, int timeout) {\n\t\tReadWriteLock lock = getLock( key );\n\t\tLock readLock = lock.readLock();\n\t\tacquireLock( key, timeout, readLock );\n\t}", "public static Object findResult(Object self, Object defaultResult, Closure closure) {\n Object result = findResult(self, closure);\n if (result == null) return defaultResult;\n return result;\n }" ]
2-D Forward Discrete Cosine Transform. @param data Data.
[ "public static void Forward(double[][] data) {\n int rows = data.length;\n int cols = data[0].length;\n\n double[] row = new double[cols];\n double[] col = new double[rows];\n\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < row.length; j++)\n row[j] = data[i][j];\n\n Forward(row);\n\n for (int j = 0; j < row.length; j++)\n data[i][j] = row[j];\n }\n\n for (int j = 0; j < cols; j++) {\n for (int i = 0; i < col.length; i++)\n col[i] = data[i][j];\n\n Forward(col);\n\n for (int i = 0; i < col.length; i++)\n data[i][j] = col[i];\n }\n }" ]
[ "protected void createBulge( int x1 , double p , boolean byAngle ) {\n double a11 = diag[x1];\n double a22 = diag[x1+1];\n double a12 = off[x1];\n double a23 = off[x1+1];\n\n if( byAngle ) {\n c = Math.cos(p);\n s = Math.sin(p);\n\n c2 = c*c;\n s2 = s*s;\n cs = c*s;\n } else {\n computeRotation(a11-p, a12);\n }\n\n // multiply the rotator on the top left.\n diag[x1] = c2*a11 + 2.0*cs*a12 + s2*a22;\n diag[x1+1] = c2*a22 - 2.0*cs*a12 + s2*a11;\n off[x1] = a12*(c2-s2) + cs*(a22 - a11);\n off[x1+1] = c*a23;\n bulge = s*a23;\n\n if( Q != null )\n updateQ(x1,x1+1,c,s);\n }", "public static tunnelip_stats[] get(nitro_service service) throws Exception{\n\t\ttunnelip_stats obj = new tunnelip_stats();\n\t\ttunnelip_stats[] response = (tunnelip_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "private void reply(final String response, final boolean error,\n final String errorMessage, final String stackTrace,\n final String statusCode, final int statusCodeInt) {\n\n \n if (!sentReply) {\n \n //must update sentReply first to avoid duplicated msg.\n sentReply = true;\n // Close the connection. Make sure the close operation ends because\n // all I/O operations are asynchronous in Netty.\n if(channel!=null && channel.isOpen())\n channel.close().awaitUninterruptibly();\n final ResponseOnSingeRequest res = new ResponseOnSingeRequest(\n response, error, errorMessage, stackTrace, statusCode,\n statusCodeInt, PcDateUtils.getNowDateTimeStrStandard(), null);\n if (!getContext().system().deadLetters().equals(sender)) {\n sender.tell(res, getSelf());\n }\n if (getContext() != null) {\n getContext().stop(getSelf());\n }\n }\n\n }", "public void loadAnimation(GVRAndroidResource animResource, String boneMap)\n {\n String filePath = animResource.getResourcePath();\n GVRContext ctx = mAvatarRoot.getGVRContext();\n GVRResourceVolume volume = new GVRResourceVolume(ctx, animResource);\n\n if (filePath.endsWith(\".bvh\"))\n {\n GVRAnimator animator = new GVRAnimator(ctx);\n animator.setName(filePath);\n try\n {\n BVHImporter importer = new BVHImporter(ctx);\n GVRSkeletonAnimation skelAnim;\n\n if (boneMap != null)\n {\n GVRSkeleton skel = importer.importSkeleton(animResource);\n skelAnim = importer.readMotion(skel);\n animator.addAnimation(skelAnim);\n\n GVRPoseMapper retargeter = new GVRPoseMapper(mSkeleton, skel, skelAnim.getDuration());\n retargeter.setBoneMap(boneMap);\n animator.addAnimation(retargeter);\n }\n else\n {\n skelAnim = importer.importAnimation(animResource, mSkeleton);\n animator.addAnimation(skelAnim);\n }\n addAnimation(animator);\n ctx.getEventManager().sendEvent(this,\n IAvatarEvents.class,\n \"onAnimationLoaded\",\n GVRAvatar.this,\n animator,\n filePath,\n null);\n }\n catch (IOException ex)\n {\n ctx.getEventManager().sendEvent(this,\n IAvatarEvents.class,\n \"onAnimationLoaded\",\n GVRAvatar.this,\n null,\n filePath,\n ex.getMessage());\n }\n }\n else\n {\n EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_TEXTURING));\n\n GVRSceneObject animRoot = new GVRSceneObject(ctx);\n ctx.getAssetLoader().loadModel(volume, animRoot, settings, false, mLoadAnimHandler);\n }\n }", "public static DMatrixSparseCSC diag(double... values ) {\n int N = values.length;\n return diag(new DMatrixSparseCSC(N,N,N),values,0,N);\n }", "protected boolean appendWhereStatement(StringBuilder sb, List<ArgumentHolder> argList, WhereOperation operation)\n\t\t\tthrows SQLException {\n\t\tif (where == null) {\n\t\t\treturn operation == WhereOperation.FIRST;\n\t\t}\n\t\toperation.appendBefore(sb);\n\t\twhere.appendSql((addTableName ? getTableName() : null), sb, argList);\n\t\toperation.appendAfter(sb);\n\t\treturn false;\n\t}", "@SuppressWarnings(\"deprecation\")\n\tpublic static boolean isTimeInRange(java.sql.Time start, java.sql.Time end, java.util.Date d) {\n d = new java.sql.Time(d.getHours(), d.getMinutes(), d.getSeconds());\n\n if (start == null || end == null) {\n return false;\n }\n\n if (start.before(end) && (!(d.after(start) && d.before(end)))) {\n return false;\n }\n\n if (end.before(start) && (!(d.after(end) || d.before(start)))) {\n return false;\n }\n return true;\n }", "public static IBlur getIBlurAlgorithm(EBlurAlgorithm algorithm, ContextWrapper contextWrapper) {\n RenderScript rs = contextWrapper.getRenderScript();\n Context ctx = contextWrapper.getContext();\n\n switch (algorithm) {\n case RS_GAUSS_FAST:\n return new RenderScriptGaussianBlur(rs);\n case RS_BOX_5x5:\n return new RenderScriptBox5x5Blur(rs);\n case RS_GAUSS_5x5:\n return new RenderScriptGaussian5x5Blur(rs);\n case RS_STACKBLUR:\n return new RenderScriptStackBlur(rs, ctx);\n case STACKBLUR:\n return new StackBlur();\n case GAUSS_FAST:\n return new GaussianFastBlur();\n case BOX_BLUR:\n return new BoxBlur();\n default:\n return new IgnoreBlur();\n }\n }", "static void processFile(final IdentityPatchContext context, final File file, final PatchingTaskContext.Mode mode) throws IOException {\n if (mode == PatchingTaskContext.Mode.APPLY) {\n if (ENABLE_INVALIDATION) {\n updateJar(file, GOOD_ENDSIG_PATTERN, BAD_BYTE_SKIP, CRIPPLED_ENDSIG, GOOD_ENDSIG);\n backup(context, file);\n }\n } else if (mode == PatchingTaskContext.Mode.ROLLBACK) {\n updateJar(file, CRIPPLED_ENDSIG_PATTERN, BAD_BYTE_SKIP, GOOD_ENDSIG, CRIPPLED_ENDSIG);\n restore(context, file);\n } else {\n throw new IllegalStateException();\n }\n }" ]
Get top deployment unit. @param unit the current deployment unit @return top deployment unit
[ "public static DeploymentUnit getTopDeploymentUnit(DeploymentUnit unit) {\n Assert.checkNotNullParam(\"unit\", unit);\n\n DeploymentUnit parent = unit.getParent();\n while (parent != null) {\n unit = parent;\n parent = unit.getParent();\n }\n return unit;\n }" ]
[ "@NonNull\n @SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher reset() {\n lastResponsePage = 0;\n lastRequestPage = 0;\n lastResponseId = 0;\n endReached = false;\n clearFacetRefinements();\n cancelPendingRequests();\n numericRefinements.clear();\n return this;\n }", "private static BundleCapability getExportedPackage(BundleContext context, String packageName) {\n List<BundleCapability> packages = new ArrayList<BundleCapability>();\n for (Bundle bundle : context.getBundles()) {\n BundleRevision bundleRevision = bundle.adapt(BundleRevision.class);\n for (BundleCapability packageCapability : bundleRevision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE)) {\n String pName = (String) packageCapability.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE);\n if (pName.equalsIgnoreCase(packageName)) {\n packages.add(packageCapability);\n }\n }\n }\n\n Version max = Version.emptyVersion;\n BundleCapability maxVersion = null;\n for (BundleCapability aPackage : packages) {\n Version version = (Version) aPackage.getAttributes().get(\"version\");\n if (max.compareTo(version) <= 0) {\n max = version;\n maxVersion = aPackage;\n }\n }\n\n return maxVersion;\n }", "private void readWBS()\n {\n Map<Integer, List<MapRow>> levelMap = new HashMap<Integer, List<MapRow>>();\n for (MapRow row : m_tables.get(\"STR\"))\n {\n Integer level = row.getInteger(\"LEVEL_NUMBER\");\n List<MapRow> items = levelMap.get(level);\n if (items == null)\n {\n items = new ArrayList<MapRow>();\n levelMap.put(level, items);\n }\n items.add(row);\n }\n\n int level = 1;\n while (true)\n {\n List<MapRow> items = levelMap.get(Integer.valueOf(level++));\n if (items == null)\n {\n break;\n }\n\n for (MapRow row : items)\n {\n m_wbsFormat.parseRawValue(row.getString(\"CODE_VALUE\"));\n String parentWbsValue = m_wbsFormat.getFormattedParentValue();\n String wbsValue = m_wbsFormat.getFormattedValue();\n row.setObject(\"WBS\", wbsValue);\n row.setObject(\"PARENT_WBS\", parentWbsValue);\n }\n\n final AlphanumComparator comparator = new AlphanumComparator();\n Collections.sort(items, new Comparator<MapRow>()\n {\n @Override public int compare(MapRow o1, MapRow o2)\n {\n return comparator.compare(o1.getString(\"WBS\"), o2.getString(\"WBS\"));\n }\n });\n\n for (MapRow row : items)\n {\n String wbs = row.getString(\"WBS\");\n if (wbs != null && !wbs.isEmpty())\n {\n ChildTaskContainer parent = m_wbsMap.get(row.getString(\"PARENT_WBS\"));\n if (parent == null)\n {\n parent = m_projectFile;\n }\n\n Task task = parent.addTask();\n String name = row.getString(\"CODE_TITLE\");\n if (name == null || name.isEmpty())\n {\n name = wbs;\n }\n task.setName(name);\n task.setWBS(wbs);\n task.setSummary(true);\n m_wbsMap.put(wbs, task);\n }\n }\n }\n }", "private void checkAllEnvelopes(PersistenceBroker broker)\r\n {\r\n Iterator iter = ((List) mvOrderOfIds.clone()).iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n // only non transient objects should be performed\r\n if(!mod.getModificationState().isTransient())\r\n {\r\n mod.markReferenceElements(broker);\r\n }\r\n }\r\n }", "protected void merge(Set<Annotation> stereotypeAnnotations) {\n final MetaAnnotationStore store = manager.getServices().get(MetaAnnotationStore.class);\n for (Annotation stereotypeAnnotation : stereotypeAnnotations) {\n // Retrieve and merge all metadata from stereotypes\n StereotypeModel<?> stereotype = store.getStereotype(stereotypeAnnotation.annotationType());\n if (stereotype == null) {\n throw MetadataLogger.LOG.stereotypeNotRegistered(stereotypeAnnotation);\n }\n if (stereotype.isAlternative()) {\n alternative = true;\n }\n if (stereotype.getDefaultScopeType() != null) {\n possibleScopeTypes.add(stereotype.getDefaultScopeType());\n }\n if (stereotype.isBeanNameDefaulted()) {\n beanNameDefaulted = true;\n }\n this.stereotypes.add(stereotypeAnnotation.annotationType());\n // Merge in inherited stereotypes\n merge(stereotype.getInheritedStereotypes());\n }\n }", "public double[] Kernel1D(int size) {\n if (((size % 2) == 0) || (size < 3) || (size > 101)) {\n try {\n throw new Exception(\"Wrong size\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n int r = size / 2;\n // kernel\n double[] kernel = new double[size];\n\n // compute kernel\n for (int x = -r, i = 0; i < size; x++, i++) {\n kernel[i] = Function1D(x);\n }\n\n return kernel;\n }", "public void subscriptionRequestReceived(SubscriptionRequest sr) throws SubscriptionException {\n\n LOG.info(\"Subscriber -> (Hub), new subscription request received.\", sr.getCallback());\n\n try {\n\n verifySubscriberRequestedSubscription(sr);\n\n if (\"subscribe\".equals(sr.getMode())) {\n LOG.info(\"Adding callback {} to the topic {}\", sr.getCallback(), sr.getTopic());\n addCallbackToTopic(sr.getCallback(), sr.getTopic());\n } else if (\"unsubscribe\".equals(sr.getMode())) {\n LOG.info(\"Removing callback {} from the topic {}\", sr.getCallback(), sr.getTopic());\n removeCallbackToTopic(sr.getCallback(), sr.getTopic());\n }\n\n } catch (Exception e) {\n throw new SubscriptionException(e);\n }\n\n }", "public static String encodeScheme(String scheme, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(scheme, encoding, HierarchicalUriComponents.Type.SCHEME);\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 }" ]
This utility displays a list of available task filters, and a list of available resource filters. @param project project file
[ "private static void displayAvailableFilters(ProjectFile project)\n {\n System.out.println(\"Unknown filter name supplied.\");\n System.out.println(\"Available task filters:\");\n for (Filter filter : project.getFilters().getTaskFilters())\n {\n System.out.println(\" \" + filter.getName());\n }\n\n System.out.println(\"Available resource filters:\");\n for (Filter filter : project.getFilters().getResourceFilters())\n {\n System.out.println(\" \" + filter.getName());\n }\n\n }" ]
[ "public static boolean hasAnnotation(AnnotatedNode node, String name) {\r\n return AstUtil.getAnnotation(node, name) != null;\r\n }", "public static cmppolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tcmppolicy_stats obj = new cmppolicy_stats();\n\t\tobj.set_name(name);\n\t\tcmppolicy_stats response = (cmppolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "List<List<Word>> getDifferentArguments( List<List<Word>> argumentWords ) {\n List<List<Word>> result = Lists.newArrayList();\n for( int i = 0; i < argumentWords.size(); i++ ) {\n result.add( Lists.<Word>newArrayList() );\n }\n\n int nWords = argumentWords.get( 0 ).size();\n\n for( int iWord = 0; iWord < nWords; iWord++ ) {\n Word wordOfFirstCase = argumentWords.get( 0 ).get( iWord );\n\n // data tables have equal here, otherwise\n // the cases would be structurally different\n if( wordOfFirstCase.isDataTable() ) {\n continue;\n }\n\n boolean different = false;\n for( int iCase = 1; iCase < argumentWords.size(); iCase++ ) {\n Word wordOfCase = argumentWords.get( iCase ).get( iWord );\n if( !wordOfCase.getFormattedValue().equals( wordOfFirstCase.getFormattedValue() ) ) {\n different = true;\n break;\n }\n\n }\n if( different ) {\n for( int iCase = 0; iCase < argumentWords.size(); iCase++ ) {\n result.get( iCase ).add( argumentWords.get( iCase ).get( iWord ) );\n }\n }\n }\n\n return result;\n }", "public static void applyMultiIconTo(Drawable icon, int iconColor, Drawable selectedIcon, int selectedIconColor, boolean tinted, ImageView imageView) {\n //if we have an icon then we want to set it\n if (icon != null) {\n //if we got a different color for the selectedIcon we need a StateList\n if (selectedIcon != null) {\n if (tinted) {\n imageView.setImageDrawable(new PressedEffectStateListDrawable(icon, selectedIcon, iconColor, selectedIconColor));\n } else {\n imageView.setImageDrawable(UIUtils.getIconStateList(icon, selectedIcon));\n }\n } else if (tinted) {\n imageView.setImageDrawable(new PressedEffectStateListDrawable(icon, iconColor, selectedIconColor));\n } else {\n imageView.setImageDrawable(icon);\n }\n //make sure we display the icon\n imageView.setVisibility(View.VISIBLE);\n } else {\n //hide the icon\n imageView.setVisibility(View.GONE);\n }\n }", "public static CharSequence getAt(CharSequence text, Range range) {\n RangeInfo info = subListBorders(text.length(), range);\n CharSequence sequence = text.subSequence(info.from, info.to);\n return info.reverse ? reverse(sequence) : sequence;\n }", "public static Iterable<BoxUser.Info> getAppUsersByExternalAppUserID(final BoxAPIConnection api,\n final String externalAppUserId, final String... fields) {\n return getUsersInfoForType(api, null, null, externalAppUserId, fields);\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}", "boolean awaitState(final InternalState expected) {\n synchronized (this) {\n final InternalState initialRequired = this.requiredState;\n for(;;) {\n final InternalState required = this.requiredState;\n // Stop in case the server failed to reach the state\n if(required == InternalState.FAILED) {\n return false;\n // Stop in case the required state changed\n } else if (initialRequired != required) {\n return false;\n }\n final InternalState current = this.internalState;\n if(expected == current) {\n return true;\n }\n try {\n wait();\n } catch(InterruptedException e) {\n Thread.currentThread().interrupt();\n return false;\n }\n }\n }\n }", "public ConnectionRepository readConnectionRepository(InputStream inst)\r\n {\r\n try\r\n {\r\n RepositoryPersistor persistor = new RepositoryPersistor();\r\n return persistor.readConnectionRepository(inst);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\"Can not read repository from \" + inst, e);\r\n }\r\n }" ]
Term prefix. @param term the term @return the string
[ "public static String termPrefix(String term) {\n int i = term.indexOf(MtasToken.DELIMITER);\n String prefix = term;\n if (i >= 0) {\n prefix = term.substring(0, i);\n }\n return prefix.replace(\"\\u0000\", \"\");\n }" ]
[ "public String convert(BufferedImage image, boolean favicon) {\n // Reset statistics before anything\n statsArray = new int[12];\n // Begin the timer\n dStart = System.nanoTime();\n // Scale the image\n image = scale(image, favicon);\n // The +1 is for the newline characters\n StringBuilder sb = new StringBuilder((image.getWidth() + 1) * image.getHeight());\n\n for (int y = 0; y < image.getHeight(); y++) {\n // At the end of each line, add a newline character\n if (sb.length() != 0) sb.append(\"\\n\");\n for (int x = 0; x < image.getWidth(); x++) {\n //\n Color pixelColor = new Color(image.getRGB(x, y), true);\n int alpha = pixelColor.getAlpha();\n boolean isTransient = alpha < 0.1;\n double gValue = isTransient ? 250 : ((double) pixelColor.getRed() * 0.2989 + (double) pixelColor.getBlue() * 0.5870 + (double) pixelColor.getGreen() * 0.1140) / ((double)alpha / (double)250);\n final char s = gValue < 130 ? darkGrayScaleMap(gValue) : lightGrayScaleMap(gValue);\n sb.append(s);\n }\n }\n imgArray = sb.toString().toCharArray();\n dEnd = System.nanoTime();\n return sb.toString();\n }", "private void makeSingularPositive() {\n numSingular = qralg.getNumberOfSingularValues();\n singularValues = qralg.getSingularValues();\n\n for( int i = 0; i < numSingular; i++ ) {\n double val = singularValues[i];\n\n if( val < 0 ) {\n singularValues[i] = -val;\n\n if( computeU ) {\n // compute the results of multiplying it by an element of -1 at this location in\n // a diagonal matrix.\n int start = i* Ut.numCols;\n int stop = start+ Ut.numCols;\n\n for( int j = start; j < stop; j++ ) {\n Ut.data[j] = -Ut.data[j];\n }\n }\n }\n }\n }", "private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList, Map<P, Boolean> savedLastExpansionState) {\n List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>();\n\n int parentCount = parentList.size();\n for (int i = 0; i < parentCount; i++) {\n P parent = parentList.get(i);\n Boolean lastExpandedState = savedLastExpansionState.get(parent);\n boolean shouldExpand = lastExpandedState == null ? parent.isInitiallyExpanded() : lastExpandedState;\n\n generateParentWrapper(flatItemList, parent, shouldExpand);\n }\n\n return flatItemList;\n }", "public void editComment(String commentId, String commentText) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_COMMENT);\r\n\r\n parameters.put(\"comment_id\", commentId);\r\n parameters.put(\"comment_text\", commentText);\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // This method has no specific response - It returns an empty\r\n // sucess response if it completes without error.\r\n }", "protected Iterator<MACAddress> iterator(MACAddress original) {\r\n\t\tMACAddressCreator creator = getAddressCreator();\r\n\t\tboolean isSingle = !isMultiple();\r\n\t\treturn iterator(\r\n\t\t\t\tisSingle ? original : null, \r\n\t\t\t\tcreator,//using a lambda for this one results in a big performance hit\r\n\t\t\t\tisSingle ? null : segmentsIterator(),\r\n\t\t\t\tgetNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets() ? null : getPrefixLength());\r\n\t}", "public MetaClassRegistryChangeEventListener[] getMetaClassRegistryChangeEventListeners() {\n synchronized (changeListenerList) {\n ArrayList<MetaClassRegistryChangeEventListener> ret =\n new ArrayList<MetaClassRegistryChangeEventListener>(changeListenerList.size()+nonRemoveableChangeListenerList.size());\n ret.addAll(nonRemoveableChangeListenerList);\n ret.addAll(changeListenerList);\n return ret.toArray(new MetaClassRegistryChangeEventListener[ret.size()]);\n }\n }", "public static Command newInsertElements(Collection objects, String outIdentifier, boolean returnObject, String entryPoint) {\n return getCommandFactoryProvider().newInsertElements( objects, outIdentifier, returnObject, entryPoint );\n }", "public static authenticationvserver_authenticationtacacspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_authenticationtacacspolicy_binding obj = new authenticationvserver_authenticationtacacspolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_authenticationtacacspolicy_binding response[] = (authenticationvserver_authenticationtacacspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@SuppressWarnings(\"unused\")\n public Phonenumber.PhoneNumber getPhoneNumber() {\n try {\n String iso = null;\n if (mSelectedCountry != null) {\n iso = mSelectedCountry.getIso();\n }\n return mPhoneUtil.parse(mPhoneEdit.getText().toString(), iso);\n } catch (NumberParseException ignored) {\n return null;\n }\n }" ]
Ask the specified player for an Artist menu. @param slotReference the player and slot for which the menu is desired @param sortOrder the order in which responses should be sorted, 0 for default, see Section 6.11.1 of the <a href="https://github.com/Deep-Symmetry/dysentery/blob/master/doc/Analysis.pdf">Packet Analysis document</a> for details @return the entries in the artist menu @throws Exception if there is a problem obtaining the menu
[ "public List<Message> requestArtistMenuFrom(final SlotReference slotReference, final int sortOrder)\n throws Exception {\n\n ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {\n @Override\n public List<Message> useClient(Client client) throws Exception {\n if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {\n try {\n logger.debug(\"Requesting Artist menu.\");\n Message response = client.menuRequest(Message.KnownType.ARTIST_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,\n new NumberField(sortOrder));\n return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);\n } finally {\n client.unlockForMenuOperations();\n }\n } else {\n throw new TimeoutException(\"Unable to lock player for menu operations.\");\n }\n }\n };\n\n return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, \"requesting artist menu\");\n }" ]
[ "public void addConverter(int index, IConverter converter) {\r\n\t\tconverterList.add(index, converter);\r\n\t\tif (converter instanceof IContainerConverter) {\r\n\t\t\tIContainerConverter containerConverter = (IContainerConverter) converter;\r\n\t\t\tif (containerConverter.getElementConverter() == null) {\r\n\t\t\t\tcontainerConverter.setElementConverter(elementConverter);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "static <T> boolean syncInstantiation(T objectType) {\n List<Template> templates = new ArrayList<>();\n Templates tr = TEMP_FINDER.findAnnotations(templates, objectType);\n if (tr == null) {\n /* Default to synchronous instantiation */\n return true;\n } else {\n return tr.syncInstantiation();\n }\n }", "private void setMax(MtasRBTreeNode n) {\n n.max = n.right;\n if (n.leftChild != null) {\n n.max = Math.max(n.max, n.leftChild.max);\n }\n if (n.rightChild != null) {\n n.max = Math.max(n.max, n.rightChild.max);\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 }", "private void addTasks(MpxjTreeNode parentNode, ChildTaskContainer parent)\n {\n for (Task task : parent.getChildTasks())\n {\n final Task t = task;\n MpxjTreeNode childNode = new MpxjTreeNode(task, TASK_EXCLUDED_METHODS)\n {\n @Override public String toString()\n {\n return t.getName();\n }\n };\n parentNode.add(childNode);\n addTasks(childNode, task);\n }\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<DiscordianDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<DiscordianDate>) super.localDateTime(temporal);\n }", "public static<T> Vendor<T> vendor(Callable<T> f) {\n\treturn j.vendor(f);\n }", "public static final String printResourceUID(Integer value)\n {\n ProjectFile file = PARENT_FILE.get();\n if (file != null)\n {\n file.getEventManager().fireResourceWrittenEvent(file.getResourceByUniqueID(value));\n }\n return (value.toString());\n }", "public ConnectionRepository readConnectionRepository(String fileName)\r\n {\r\n try\r\n {\r\n RepositoryPersistor persistor = new RepositoryPersistor();\r\n return persistor.readConnectionRepository(fileName);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\"Can not read repository \" + fileName, e);\r\n }\r\n }" ]
Compares the StoreVersionManager's internal state with the content on the file-system of the rootDir provided at construction time. TODO: If the StoreVersionManager supports non-RO stores in the future, we should move some of the ReadOnlyUtils functions below to another Utils class.
[ "public void syncInternalStateFromFileSystem(boolean alsoSyncRemoteState) {\n // Make sure versions missing from the file-system are cleaned up from the internal state\n for (Long version: versionToEnabledMap.keySet()) {\n File[] existingVersionDirs = ReadOnlyUtils.getVersionDirs(rootDir, version, version);\n if (existingVersionDirs.length == 0) {\n removeVersion(version, alsoSyncRemoteState);\n }\n }\n\n // Make sure we have all versions on the file-system in the internal state\n File[] versionDirs = ReadOnlyUtils.getVersionDirs(rootDir);\n if (versionDirs != null) {\n for (File versionDir: versionDirs) {\n long versionNumber = ReadOnlyUtils.getVersionId(versionDir);\n boolean versionEnabled = isVersionEnabled(versionDir);\n versionToEnabledMap.put(versionNumber, versionEnabled);\n }\n }\n\n // Identify the current version (based on a symlink in the file-system)\n File currentVersionDir = ReadOnlyUtils.getCurrentVersion(rootDir);\n if (currentVersionDir != null) {\n currentVersion = ReadOnlyUtils.getVersionId(currentVersionDir);\n } else {\n currentVersion = -1; // Should we throw instead?\n }\n\n logger.info(\"Successfully synced internal state from local file-system: \" + this.toString());\n }" ]
[ "private List<I_CmsSearchConfigurationSortOption> getSortOptions() {\n\n final List<I_CmsSearchConfigurationSortOption> options = new ArrayList<I_CmsSearchConfigurationSortOption>();\n final CmsXmlContentValueSequence sortOptions = m_xml.getValueSequence(XML_ELEMENT_SORTOPTIONS, m_locale);\n if (sortOptions == null) {\n return null;\n } else {\n for (int i = 0; i < sortOptions.getElementCount(); i++) {\n final I_CmsSearchConfigurationSortOption option = parseSortOption(\n sortOptions.getValue(i).getPath() + \"/\");\n if (option != null) {\n options.add(option);\n }\n }\n return options;\n }\n }", "public TransactionImpl getCurrentTransaction()\r\n {\r\n TransactionImpl tx = tx_table.get(Thread.currentThread());\r\n if(tx == null)\r\n {\r\n throw new TransactionNotInProgressException(\"Calling method needed transaction, but no transaction found for current thread :-(\");\r\n }\r\n return tx;\r\n }", "protected void checkActiveState(Widget child) {\n // Check if this widget has a valid href\n String href = child.getElement().getAttribute(\"href\");\n String url = Window.Location.getHref();\n int pos = url.indexOf(\"#\");\n String location = pos >= 0 ? url.substring(pos, url.length()) : \"\";\n\n if (!href.isEmpty() && location.startsWith(href)) {\n ListItem li = findListItemParent(child);\n if (li != null) {\n makeActive(li);\n }\n } else if (child instanceof HasWidgets) {\n // Recursive check\n for (Widget w : (HasWidgets) child) {\n checkActiveState(w);\n }\n }\n }", "public static base_responses add(nitro_service client, sslocspresponder resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslocspresponder addresources[] = new sslocspresponder[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new sslocspresponder();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].url = resources[i].url;\n\t\t\t\taddresources[i].cache = resources[i].cache;\n\t\t\t\taddresources[i].cachetimeout = resources[i].cachetimeout;\n\t\t\t\taddresources[i].batchingdepth = resources[i].batchingdepth;\n\t\t\t\taddresources[i].batchingdelay = resources[i].batchingdelay;\n\t\t\t\taddresources[i].resptimeout = resources[i].resptimeout;\n\t\t\t\taddresources[i].respondercert = resources[i].respondercert;\n\t\t\t\taddresources[i].trustresponder = resources[i].trustresponder;\n\t\t\t\taddresources[i].producedattimeskew = resources[i].producedattimeskew;\n\t\t\t\taddresources[i].signingcert = resources[i].signingcert;\n\t\t\t\taddresources[i].usenonce = resources[i].usenonce;\n\t\t\t\taddresources[i].insertclientcert = resources[i].insertclientcert;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static String getTypeValue(Class<? extends WindupFrame> clazz)\n {\n TypeValue typeValueAnnotation = clazz.getAnnotation(TypeValue.class);\n if (typeValueAnnotation == null)\n throw new IllegalArgumentException(\"Class \" + clazz.getCanonicalName() + \" lacks a @TypeValue annotation\");\n\n return typeValueAnnotation.value();\n }", "private void stereotype(Options opt, Doc c, Align align) {\n\tfor (Tag tag : c.tags(\"stereotype\")) {\n\t String t[] = tokenize(tag.text());\n\t if (t.length != 1) {\n\t\tSystem.err.println(\"@stereotype expects one field: \" + tag.text());\n\t\tcontinue;\n\t }\n\t tableLine(align, guilWrap(opt, t[0]));\n\t}\n }", "public void addAppenderEvent(final Category cat, final Appender appender) {\n\n\t\tupdateDefaultLayout(appender);\n\n\t\tif (appender instanceof FoundationFileRollingAppender) {\n\t\t\tfinal FoundationFileRollingAppender timeSizeRollingAppender = (FoundationFileRollingAppender) appender;\n\n\t\t\t// update the appender with default vales such as logging pattern, file size etc.\n\t\t\t//updateDefaultTimeAndSizeRollingAppender(timeSizeRollingAppender);\n\n\t\t\t// read teh proeprties and determine if archiving should be enabled.\n\t\t\tupdateArchivingSupport(timeSizeRollingAppender);\n\n\t\t\t// by default add the rolling file listener to enable application\n\t\t\t// state.\n\t\t\ttimeSizeRollingAppender.setFileRollEventListener(FoundationRollEventListener.class.getName());\n\n\t\t\tboolean rollOnStartup = true;\n\n\t\t\tif (FoundationLogger.log4jConfigProps != null && FoundationLogger.log4jConfigProps.containsKey(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString())) {\n\t\t\t\trollOnStartup = Boolean.valueOf(FoundationLogger.log4jConfigProps.getProperty(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString()));\n\t\t\t}\n\n\t\t\ttimeSizeRollingAppender.setRollOnStartup(rollOnStartup);\n\n\t\t\t// refresh the appender\n\t\t\ttimeSizeRollingAppender.activateOptions();\n\n\t\t\t\n\t\t//\ttimeSizeRollingAppender.setOriginalLayout(); //So application state will not make any problems\n\n\t\t}else if(!(appender instanceof FoundationFileRollingAppender) && (appender instanceof TimeAndSizeRollingAppender)){ //TimeAndSizeRollingAppender\n\t\t\tfinal TimeAndSizeRollingAppender timeSizeRollingAppender = (TimeAndSizeRollingAppender) appender;\n\n\t\t\t// update the appender with default vales such as logging pattern, file size etc.\n\t\t\tupdateDefaultTimeAndSizeRollingAppender(timeSizeRollingAppender);\n\n\t\t\t// read teh proeprties and determine if archiving should be enabled.\n\t\t\tupdateArchivingSupport(timeSizeRollingAppender);\n\n\t\t\t// by default add the rolling file listener to enable application\n\t\t\t// state.\n\t\t\ttimeSizeRollingAppender.setFileRollEventListener(FoundationRollEventListener.class.getName());\n\n\t\t\tboolean rollOnStartup = true;\n\n\t\t\tif (FoundationLogger.log4jConfigProps != null && FoundationLogger.log4jConfigProps.containsKey(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString())) {\n\t\t\t\trollOnStartup = Boolean.valueOf(FoundationLogger.log4jConfigProps.getProperty(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString()));\n\t\t\t}\n\n\t\t\ttimeSizeRollingAppender.setRollOnStartup(rollOnStartup);\n\n\t\t\t// refresh the appender\n\t\t\ttimeSizeRollingAppender.activateOptions();\n\n\t\t\t\n\t\t//\ttimeSizeRollingAppender.setOriginalLayout();\n\t\t}\n\t\tif ( ! (appender instanceof org.apache.log4j.AsyncAppender))\n initiateAsyncSupport(appender);\n\n\t}", "public static base_response add(nitro_service client, authenticationradiusaction resource) throws Exception {\n\t\tauthenticationradiusaction addresource = new authenticationradiusaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.serverip = resource.serverip;\n\t\taddresource.serverport = resource.serverport;\n\t\taddresource.authtimeout = resource.authtimeout;\n\t\taddresource.radkey = resource.radkey;\n\t\taddresource.radnasip = resource.radnasip;\n\t\taddresource.radnasid = resource.radnasid;\n\t\taddresource.radvendorid = resource.radvendorid;\n\t\taddresource.radattributetype = resource.radattributetype;\n\t\taddresource.radgroupsprefix = resource.radgroupsprefix;\n\t\taddresource.radgroupseparator = resource.radgroupseparator;\n\t\taddresource.passencoding = resource.passencoding;\n\t\taddresource.ipvendorid = resource.ipvendorid;\n\t\taddresource.ipattributetype = resource.ipattributetype;\n\t\taddresource.accounting = resource.accounting;\n\t\taddresource.pwdvendorid = resource.pwdvendorid;\n\t\taddresource.pwdattributetype = resource.pwdattributetype;\n\t\taddresource.defaultauthenticationgroup = resource.defaultauthenticationgroup;\n\t\taddresource.callingstationid = resource.callingstationid;\n\t\treturn addresource.add_resource(client);\n\t}", "private static boolean isCollectionMatching(Joinable mainSideJoinable, OgmCollectionPersister inverseSidePersister) {\n\t\tboolean isSameTable = mainSideJoinable.getTableName().equals( inverseSidePersister.getTableName() );\n\n\t\tif ( !isSameTable ) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn Arrays.equals( mainSideJoinable.getKeyColumnNames(), inverseSidePersister.getElementColumnNames() );\n\t}" ]
Used by dataformats if they need to load a class @param classname the name of the @param dataFormat @return
[ "public static Class<?> loadClass(String classname, DataFormat<?> dataFormat) {\n\n // first try context classoader\n ClassLoader cl = Thread.currentThread().getContextClassLoader();\n if(cl != null) {\n LOG.tryLoadingClass(classname, cl);\n try {\n return cl.loadClass(classname);\n }\n catch(Exception e) {\n // ignore\n }\n }\n\n // else try the classloader which loaded the dataformat\n cl = dataFormat.getClass().getClassLoader();\n try {\n LOG.tryLoadingClass(classname, cl);\n return cl.loadClass(classname);\n }\n catch (ClassNotFoundException e) {\n throw LOG.classNotFound(classname, e);\n }\n\n }" ]
[ "protected synchronized void streamingSlopPut(ByteArray key,\n Versioned<byte[]> value,\n String storeName,\n int failedNodeId) throws IOException {\n\n Slop slop = new Slop(storeName,\n Slop.Operation.PUT,\n key,\n value.getValue(),\n null,\n failedNodeId,\n new Date());\n\n ByteArray slopKey = slop.makeKey();\n Versioned<byte[]> slopValue = new Versioned<byte[]>(slopSerializer.toBytes(slop),\n value.getVersion());\n\n Node failedNode = adminClient.getAdminClientCluster().getNodeById(failedNodeId);\n HandoffToAnyStrategy slopRoutingStrategy = new HandoffToAnyStrategy(adminClient.getAdminClientCluster(),\n true,\n failedNode.getZoneId());\n // node Id which will receive the slop\n int slopDestination = slopRoutingStrategy.routeHint(failedNode).get(0).getId();\n\n VAdminProto.PartitionEntry partitionEntry = VAdminProto.PartitionEntry.newBuilder()\n .setKey(ProtoUtils.encodeBytes(slopKey))\n .setVersioned(ProtoUtils.encodeVersioned(slopValue))\n .build();\n\n VAdminProto.UpdatePartitionEntriesRequest.Builder updateRequest = VAdminProto.UpdatePartitionEntriesRequest.newBuilder()\n .setStore(SLOP_STORE)\n .setPartitionEntry(partitionEntry);\n\n DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair<String, Integer>(SLOP_STORE,\n slopDestination));\n\n if(nodeIdStoreInitialized.get(new Pair<String, Integer>(SLOP_STORE, slopDestination))) {\n ProtoUtils.writeMessage(outputStream, updateRequest.build());\n } else {\n ProtoUtils.writeMessage(outputStream,\n VAdminProto.VoldemortAdminRequest.newBuilder()\n .setType(VAdminProto.AdminRequestType.UPDATE_PARTITION_ENTRIES)\n .setUpdatePartitionEntries(updateRequest)\n .build());\n outputStream.flush();\n nodeIdStoreInitialized.put(new Pair<String, Integer>(SLOP_STORE, slopDestination), true);\n\n }\n\n throttler.maybeThrottle(1);\n\n }", "public final void notifyFooterItemChanged(int position) {\n if (position < 0 || position >= footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position\n + \" is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemChanged(position + headerItemCount + contentItemCount);\n }", "public static base_response delete(nitro_service client, String ipv6prefix) throws Exception {\n\t\tonlinkipv6prefix deleteresource = new onlinkipv6prefix();\n\t\tdeleteresource.ipv6prefix = ipv6prefix;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static Date setTime(Date date, Date canonicalTime)\n {\n Date result;\n if (canonicalTime == null)\n {\n result = date;\n }\n else\n {\n //\n // The original naive implementation of this method generated\n // the \"start of day\" date (midnight) for the required day\n // then added the milliseconds from the canonical time\n // to move the time forward to the required point. Unfortunately\n // if the date we'e trying to do this for is the entry or\n // exit from DST, the result is wrong, hence I've switched to\n // the approach below.\n //\n Calendar cal = popCalendar(canonicalTime);\n int dayOffset = cal.get(Calendar.DAY_OF_YEAR) - 1;\n int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);\n int minute = cal.get(Calendar.MINUTE);\n int second = cal.get(Calendar.SECOND);\n int millisecond = cal.get(Calendar.MILLISECOND);\n\n cal.setTime(date);\n\n if (dayOffset != 0)\n {\n // The canonical time can be +1 day.\n // It's to do with the way we've historically\n // managed time ranges and midnight.\n cal.add(Calendar.DAY_OF_YEAR, dayOffset);\n }\n\n cal.set(Calendar.MILLISECOND, millisecond);\n cal.set(Calendar.SECOND, second);\n cal.set(Calendar.MINUTE, minute);\n cal.set(Calendar.HOUR_OF_DAY, hourOfDay);\n\n result = cal.getTime();\n pushCalendar(cal);\n }\n return result;\n }", "public JsonNode apply(final JsonNode node) {\n requireNonNull(node, \"node\");\n JsonNode ret = node.deepCopy();\n for (final JsonPatchOperation operation : operations) {\n ret = operation.apply(ret);\n }\n\n return ret;\n }", "private ProjectFile read() throws Exception\n {\n m_project = new ProjectFile();\n m_eventManager = m_project.getEventManager();\n\n m_project.getProjectProperties().setFileApplication(\"Synchro\");\n m_project.getProjectProperties().setFileType(\"SP\");\n\n CustomFieldContainer fields = m_project.getCustomFields();\n fields.getCustomField(TaskField.TEXT1).setAlias(\"Code\");\n\n m_eventManager.addProjectListeners(m_projectListeners);\n\n processCalendars();\n processResources();\n processTasks();\n processPredecessors();\n\n return m_project;\n }", "protected Boolean parseOptionalBooleanValue(final String path) {\n\n final I_CmsXmlContentValue value = m_xml.getValue(path, m_locale);\n if (value == null) {\n return null;\n } else {\n final String stringValue = value.getStringValue(null);\n try {\n final Boolean boolValue = Boolean.valueOf(stringValue);\n return boolValue;\n } catch (final NumberFormatException e) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_OPTIONAL_BOOLEAN_MISSING_1, path), e);\n return null;\n }\n }\n }", "Map<String, EntityDocument> getEntityDocumentMap(int numOfEntities,\n\t\t\tWbGetEntitiesActionData properties)\n\t\t\tthrows MediaWikiApiErrorException, IOException {\n\t\tif (numOfEntities == 0) {\n\t\t\treturn Collections.emptyMap();\n\t\t}\n\t\tconfigureProperties(properties);\n\t\treturn this.wbGetEntitiesAction.wbGetEntities(properties);\n\t}", "public Map getPathClasses()\r\n\t{\r\n\t\tif (m_pathClasses.isEmpty())\r\n\t\t{\r\n\t\t\tif (m_parentCriteria == null)\r\n\t\t\t{\r\n\t\t\t\tif (m_query == null)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_pathClasses;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_query.getPathClasses();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\treturn m_parentCriteria.getPathClasses();\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn m_pathClasses;\r\n\t\t}\r\n\t}" ]
Returns whether the division grouping range matches the block of values for its prefix length. In other words, returns true if and only if it has a prefix length and it has just a single prefix.
[ "@Override\n\tpublic boolean isSinglePrefixBlock() {\n\t\tInteger networkPrefixLength = getNetworkPrefixLength();\n\t\tif(networkPrefixLength == null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn containsSinglePrefixBlock(networkPrefixLength);\n\t}" ]
[ "public static Class<?> resolveReturnType(Method method, Class<?> clazz) {\n\t\tAssert.notNull(method, \"Method must not be null\");\n\t\tType genericType = method.getGenericReturnType();\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\tMap<TypeVariable, Type> typeVariableMap = getTypeVariableMap(clazz);\n\t\tType rawType = getRawType(genericType, typeVariableMap);\n\t\treturn (rawType instanceof Class ? (Class<?>) rawType : method.getReturnType());\n\t}", "@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 }", "private void beginInternTransaction()\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"beginInternTransaction was called\");\r\n J2EETransactionImpl tx = (J2EETransactionImpl) super.currentTransaction();\r\n if (tx == null) tx = newInternTransaction();\r\n if (!tx.isOpen())\r\n {\r\n // start the transaction\r\n tx.begin();\r\n tx.setInExternTransaction(true);\r\n }\r\n }", "public static XMLStreamException unexpectedEndElement(final XMLExtendedStreamReader reader) {\n return ControllerLogger.ROOT_LOGGER.unexpectedEndElement(reader.getName(), reader.getLocation());\n }", "public String getRepoKey() {\n String repoKey;\n if (isDynamicMode()) {\n repoKey = keyFromText;\n } else {\n repoKey = keyFromSelect;\n }\n return repoKey;\n }", "public String format(final LoggingEvent event) {\n\t\tfinal StringBuffer buf = new StringBuffer();\n\t\tfor (PatternConverter c = head; c != null; c = c.next) {\n\t\t\tc.format(buf, event);\n\t\t}\n\t\treturn buf.toString();\n\t}", "public static List<String> getBuildNumbersNotToBeDeleted(Run build) {\n List<String> notToDelete = Lists.newArrayList();\n List<? extends Run<?, ?>> builds = build.getParent().getBuilds();\n for (Run<?, ?> run : builds) {\n if (run.isKeepLog()) {\n notToDelete.add(String.valueOf(run.getNumber()));\n }\n }\n return notToDelete;\n }", "protected static BufferedReader createFileReader(String file_name)\n throws BeastException {\n try {\n return new BufferedReader(new FileReader(file_name));\n } catch (FileNotFoundException e) {\n Logger logger = Logger.getLogger(MASReader.class.getName());\n logger.severe(\"ERROR: \" + e.toString());\n throw new BeastException(\"ERROR: \" + e.toString(), e);\n }\n }", "private void verifiedCopyFile(File sourceFile, File destFile) throws IOException {\n if(!destFile.exists()) {\n destFile.createNewFile();\n }\n\n FileInputStream source = null;\n FileOutputStream destination = null;\n LogVerificationInputStream verifyStream = null;\n try {\n source = new FileInputStream(sourceFile);\n destination = new FileOutputStream(destFile);\n verifyStream = new LogVerificationInputStream(env, source, sourceFile.getName());\n\n final byte[] buf = new byte[LOGVERIFY_BUFSIZE];\n\n while(true) {\n final int len = verifyStream.read(buf);\n if(len < 0) {\n break;\n }\n destination.write(buf, 0, len);\n }\n\n } finally {\n if(verifyStream != null) {\n verifyStream.close();\n }\n if(destination != null) {\n destination.close();\n }\n }\n }" ]
Calculates the Black-Scholes option value of an atm call option. @param volatility The Black-Scholes volatility. @param optionMaturity The option maturity T. @param forward The forward, i.e., the expectation of the index under the measure associated with payoff unit. @param payoffUnit The payoff unit, i.e., the discount factor or the anuity associated with the payoff. @return Returns the value of a European at-the-money call option under the Black-Scholes model
[ "public static double blackScholesATMOptionValue(\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble forward,\n\t\t\tdouble payoffUnit)\n\t{\n\t\tif(optionMaturity < 0) {\n\t\t\treturn 0.0;\n\t\t}\n\n\t\t// Calculate analytic value\n\t\tdouble dPlus = 0.5 * volatility * Math.sqrt(optionMaturity);\n\t\tdouble dMinus = -dPlus;\n\n\t\tdouble valueAnalytic = (NormalDistribution.cumulativeDistribution(dPlus) - NormalDistribution.cumulativeDistribution(dMinus)) * forward * payoffUnit;\n\n\t\treturn valueAnalytic;\n\t}" ]
[ "public static base_response unset(nitro_service client, coparameter resource, String[] args) throws Exception{\n\t\tcoparameter unsetresource = new coparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public final ProcessorDependencyGraph getProcessorGraph() {\n if (this.processorGraph == null) {\n synchronized (this) {\n if (this.processorGraph == null) {\n final Map<String, Class<?>> attcls = new HashMap<>();\n for (Map.Entry<String, Attribute> attribute: this.attributes.entrySet()) {\n attcls.put(attribute.getKey(), attribute.getValue().getValueType());\n }\n this.processorGraph = this.processorGraphFactory.build(this.processors, attcls);\n }\n }\n }\n return this.processorGraph;\n }", "@Override\n public HandlerRegistration addSearchNoResultHandler(final SearchNoResultEvent.SearchNoResultHandler handler) {\n return addHandler(handler, SearchNoResultEvent.TYPE);\n }", "private void writePredecessors(Task mpxjTask, net.sf.mpxj.planner.schema.Task plannerTask)\n {\n Predecessors plannerPredecessors = m_factory.createPredecessors();\n plannerTask.setPredecessors(plannerPredecessors);\n List<Predecessor> predecessorList = plannerPredecessors.getPredecessor();\n int id = 0;\n\n List<Relation> predecessors = mpxjTask.getPredecessors();\n for (Relation rel : predecessors)\n {\n Integer taskUniqueID = rel.getTargetTask().getUniqueID();\n Predecessor plannerPredecessor = m_factory.createPredecessor();\n plannerPredecessor.setId(getIntegerString(++id));\n plannerPredecessor.setPredecessorId(getIntegerString(taskUniqueID));\n plannerPredecessor.setLag(getDurationString(rel.getLag()));\n plannerPredecessor.setType(RELATIONSHIP_TYPES.get(rel.getType()));\n predecessorList.add(plannerPredecessor);\n m_eventManager.fireRelationWrittenEvent(rel);\n }\n }", "public Class<? extends MonetaryAmount> getAmountType() {\n Class<?> clazz = get(AMOUNT_TYPE, Class.class);\n return clazz.asSubclass(MonetaryAmount.class);\n }", "public ApnsServiceBuilder withAuthProxy(Proxy proxy, String proxyUsername, String proxyPassword) {\n this.proxy = proxy;\n this.proxyUsername = proxyUsername;\n this.proxyPassword = proxyPassword;\n return this;\n }", "public Optional<Project> findProject(String name) throws IllegalArgumentException {\n if (name == null || name.isEmpty()) {\n throw new IllegalArgumentException(\"Project name cannot be empty\");\n }\n return getProject(name);\n }", "public void revertWorkingCopy() throws IOException, InterruptedException {\n build.getWorkspace()\n .act(new RevertWorkingCopyCallable(getLocation(), getSvnAuthenticationProvider(build), buildListener));\n }", "public boolean matches(PathAddress address) {\n if (address == null) {\n return false;\n }\n if (equals(address)) {\n return true;\n }\n if (size() != address.size()) {\n return false;\n }\n for (int i = 0; i < size(); i++) {\n PathElement pe = getElement(i);\n PathElement other = address.getElement(i);\n if (!pe.matches(other)) {\n // Could be a multiTarget with segments\n if (pe.isMultiTarget() && !pe.isWildcard()) {\n boolean matched = false;\n for (String segment : pe.getSegments()) {\n if (segment.equals(other.getValue())) {\n matched = true;\n break;\n }\n }\n if (!matched) {\n return false;\n }\n } else {\n return false;\n }\n }\n }\n return true;\n }" ]
Add an URL to the given classloader @param loader ClassLoader @param url URL to add @throws IOException I/O Error @throws InvocationTargetException Invocation Error @throws IllegalArgumentException Illegal Argument @throws IllegalAccessException Illegal Access @throws SecurityException Security Constraint @throws NoSuchMethodException Method not found
[ "public static void addJarToClasspath(ClassLoader loader, URL url) throws IOException,\n IllegalAccessException, IllegalArgumentException, InvocationTargetException,\n NoSuchMethodException, SecurityException {\n URLClassLoader sysloader = (URLClassLoader) loader;\n Class<?> sysclass = URLClassLoader.class;\n\n Method method =\n sysclass.getDeclaredMethod(MyClasspathUtils.ADD_URL_METHOD, new Class[] {URL.class});\n method.setAccessible(true);\n method.invoke(sysloader, new Object[] {url});\n\n }" ]
[ "public T addContentModification(final ContentModification modification) {\n if (itemFilter.accepts(modification.getItem())) {\n internalAddModification(modification);\n }\n return returnThis();\n }", "protected byte[] getUpperBytesInternal() {\n\t\tbyte cached[];\n\t\tif(hasNoValueCache()) {\n\t\t\tValueCache cache = valueCache;\n\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\tif(!isMultiple()) {\n\t\t\t\tcache.lowerBytes = cached;\n\t\t\t}\n\t\t} else {\n\t\t\tValueCache cache = valueCache;\n\t\t\tif((cached = cache.upperBytes) == null) {\n\t\t\t\tif(!isMultiple()) {\n\t\t\t\t\tif((cached = cache.lowerBytes) != null) {\n\t\t\t\t\t\tcache.upperBytes = cached;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcache.lowerBytes = cache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn cached;\n\t}", "public static String getAt(String text, Range range) {\n RangeInfo info = subListBorders(text.length(), range);\n String answer = text.substring(info.from, info.to);\n if (info.reverse) {\n answer = reverse(answer);\n }\n return answer;\n }", "public static TestCaseStartedEvent withExecutorInfo(TestCaseStartedEvent event) {\n event.getLabels().add(createHostLabel(getHostname()));\n event.getLabels().add(createThreadLabel(format(\"%s.%s(%s)\",\n ManagementFactory.getRuntimeMXBean().getName(),\n Thread.currentThread().getName(),\n Thread.currentThread().getId())\n ));\n return event;\n }", "@Pure\n\tpublic static <K, V> Map<K, V> operator_minus(Map<K, V> map, final K key) {\n\t\treturn Maps.filterKeys(map, new Predicate<K>() {\n\t\t\t@Override\n\t\t\tpublic boolean apply(K input) {\n\t\t\t\treturn !Objects.equal(input, key);\n\t\t\t}\n\t\t});\n\t}", "public ItemRequest<Task> dependents(String task) {\n \n String path = String.format(\"/tasks/%s/dependents\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }", "public static boolean unzipFileOrFolder(File zipFile, String unzippedFolder){\n\t\tInputStream is;\n\t\tArchiveInputStream in = null;\n\t\tOutputStream out = null;\n\t\t\n\t\tif(!zipFile.isFile()){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif(unzippedFolder == null){\n\t\t\tunzippedFolder = FilenameUtils.removeExtension(zipFile.getAbsolutePath());\n\t\t}\n\t\ttry {\n\t\t\tis = new FileInputStream(zipFile);\n\t\t\tnew File(unzippedFolder).mkdir();\n\t\t\t\n\t\t\tin = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP, is);\n\t\t\t\n\t\t\tZipArchiveEntry entry = (ZipArchiveEntry)in.getNextEntry();\n\t\t\twhile(entry != null){\n\t\t\t\tif(entry.isDirectory()){\n\t\t\t\t\tnew File(unzippedFolder,entry.getName()).mkdir();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tout = new FileOutputStream(new File(unzippedFolder, entry.getName()));\n\t\t\t\t\tIOUtils.copy(in, out);\n\t\t\t\t\tout.close();\n\t\t\t\t\tout = null;\n\t\t\t\t}\n\t\t\t\tentry = (ZipArchiveEntry)in.getNextEntry();\n\t\t\t}\t\n\t\t} catch (FileNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t} catch (ArchiveException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t\tfinally{\n\t\t\tif(out != null){\n\t\t\t\ttry {\n\t\t\t\t\tout.close();\n\t\t\t\t} catch (IOException e) {}\n\t\t\t}\n\t\t\tif(in != null){\n\t\t\t\ttry {\n\t\t\t\t\tin.close();\n\t\t\t\t} catch (IOException e) {}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "public List<String> getMultiSelect(String path) {\n List<String> values = new ArrayList<String>();\n for (JsonValue val : this.getValue(path).asArray()) {\n values.add(val.asString());\n }\n\n return values;\n }", "public ResponseFromManager generateUpdateExecuteTask(ParallelTask task) {\n\n // add to map now; as can only pass final\n ParallelTaskManager.getInstance().addTaskToInProgressMap(\n task.getTaskId(), task);\n logger.info(\"Added task {} to the running inprogress map...\",\n task.getTaskId());\n\n boolean useReplacementVarMap = false;\n boolean useReplacementVarMapNodeSpecific = false;\n Map<String, StrStrMap> replacementVarMapNodeSpecific = null;\n Map<String, String> replacementVarMap = null;\n\n ResponseFromManager batchResponseFromManager = null;\n\n switch (task.getRequestReplacementType()) {\n case UNIFORM_VAR_REPLACEMENT:\n useReplacementVarMap = true;\n useReplacementVarMapNodeSpecific = false;\n replacementVarMap = task.getReplacementVarMap();\n break;\n case TARGET_HOST_SPECIFIC_VAR_REPLACEMENT:\n useReplacementVarMap = false;\n useReplacementVarMapNodeSpecific = true;\n replacementVarMapNodeSpecific = task\n .getReplacementVarMapNodeSpecific();\n break;\n case NO_REPLACEMENT:\n useReplacementVarMap = false;\n useReplacementVarMapNodeSpecific = false;\n break;\n default:\n logger.error(\"error request replacement type. default as no replacement\");\n }// end switch\n\n // generate content in nodedata\n InternalDataProvider dp = InternalDataProvider.getInstance();\n dp.genNodeDataMap(task);\n\n VarReplacementProvider.getInstance()\n .updateRequestWithReplacement(task, useReplacementVarMap,\n replacementVarMap, useReplacementVarMapNodeSpecific,\n replacementVarMapNodeSpecific);\n\n batchResponseFromManager = \n sendTaskToExecutionManager(task);\n\n removeTaskFromInProgressMap(task.getTaskId());\n logger.info(\n \"Removed task {} from the running inprogress map... \"\n + \". This task should be garbage collected if there are no other pointers.\",\n task.getTaskId());\n return batchResponseFromManager;\n\n }" ]
Sets the first occurence. @param min the min @param max the max @throws ParseException the parse exception
[ "public void setFirstOccurence(int min, int max) throws ParseException {\n if (fullCondition == null) {\n if ((min < 0) || (min > max) || (max < 1)) {\n throw new ParseException(\"Illegal number {\" + min + \",\" + max + \"}\");\n }\n if (min == 0) {\n firstOptional = true;\n }\n firstMinimumOccurence = Math.max(1, min);\n firstMaximumOccurence = max;\n } else {\n throw new ParseException(\"fullCondition already generated\");\n }\n }" ]
[ "public void add(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {\n BinderDescriptor binderDescriptor = new BinderDescriptor(declarationBinderRef);\n declarationBinders.put(declarationBinderRef, binderDescriptor);\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}", "public com.squareup.okhttp.Call postUiAutopilotWaypointCall(Boolean addToBeginning, Boolean clearOtherWaypoints,\n Long destinationId, String datasource, String token, final ApiCallback callback) throws ApiException {\n Object localVarPostBody = new Object();\n\n // create path and map variables\n String localVarPath = \"/v2/ui/autopilot/waypoint/\";\n\n List<Pair> localVarQueryParams = new ArrayList<Pair>();\n List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();\n if (addToBeginning != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"add_to_beginning\", addToBeginning));\n }\n\n if (clearOtherWaypoints != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"clear_other_waypoints\", clearOtherWaypoints));\n }\n\n if (datasource != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"datasource\", datasource));\n }\n\n if (destinationId != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"destination_id\", destinationId));\n }\n\n if (token != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"token\", token));\n }\n\n Map<String, String> localVarHeaderParams = new HashMap<String, String>();\n Map<String, Object> localVarFormParams = new HashMap<String, Object>();\n final String[] localVarAccepts = {\n\n };\n final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);\n if (localVarAccept != null) {\n localVarHeaderParams.put(\"Accept\", localVarAccept);\n }\n\n final String[] localVarContentTypes = {\n\n };\n final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);\n localVarHeaderParams.put(\"Content-Type\", localVarContentType);\n\n String[] localVarAuthNames = new String[] { \"evesso\" };\n return apiClient.buildCall(localVarPath, \"POST\", localVarQueryParams, localVarCollectionQueryParams,\n localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, callback);\n }", "public void updateActive(int profileId, String clientUUID, Boolean active) throws Exception {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_CLIENT +\n \" SET \" + Constants.CLIENT_IS_ACTIVE + \"= ?\" +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= ? \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ?\"\n );\n statement.setBoolean(1, active);\n statement.setString(2, clientUUID);\n statement.setInt(3, profileId);\n statement.executeUpdate();\n } catch (Exception e) {\n // ok to swallow this.. just means there wasn't any\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "private void executePlan(RebalancePlan rebalancePlan) {\n logger.info(\"Starting to execute rebalance Plan!\");\n\n int batchCount = 0;\n int partitionStoreCount = 0;\n long totalTimeMs = 0;\n\n List<RebalanceBatchPlan> entirePlan = rebalancePlan.getPlan();\n int numBatches = entirePlan.size();\n int numPartitionStores = rebalancePlan.getPartitionStoresMoved();\n\n for(RebalanceBatchPlan batchPlan: entirePlan) {\n logger.info(\"======== REBALANCING BATCH \" + (batchCount + 1)\n + \" ========\");\n RebalanceUtils.printBatchLog(batchCount,\n logger,\n batchPlan.toString());\n\n long startTimeMs = System.currentTimeMillis();\n // ACTUALLY DO A BATCH OF REBALANCING!\n executeBatch(batchCount, batchPlan);\n totalTimeMs += (System.currentTimeMillis() - startTimeMs);\n\n // Bump up the statistics\n batchCount++;\n partitionStoreCount += batchPlan.getPartitionStoreMoves();\n batchStatusLog(batchCount,\n numBatches,\n partitionStoreCount,\n numPartitionStores,\n totalTimeMs);\n }\n }", "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}", "public boolean hasForeignkey(String name)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n ForeignkeyDef def = null;\r\n\r\n for (Iterator it = getForeignkeys(); it.hasNext();)\r\n {\r\n def = (ForeignkeyDef)it.next();\r\n if (realName.equals(def.getName()))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "public static base_response delete(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey deleteresource = new sslcertkey();\n\t\tdeleteresource.certkey = resource.certkey;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public void addConverter(int index, IConverter converter) {\r\n\t\tconverterList.add(index, converter);\r\n\t\tif (converter instanceof IContainerConverter) {\r\n\t\t\tIContainerConverter containerConverter = (IContainerConverter) converter;\r\n\t\t\tif (containerConverter.getElementConverter() == null) {\r\n\t\t\t\tcontainerConverter.setElementConverter(elementConverter);\r\n\t\t\t}\r\n\t\t}\r\n\t}" ]
Creates a list of all permutations for a set with N elements. @param N Number of elements in the list being permuted. @return A list containing all the permutations.
[ "public static List<int[]> createList( int N )\n {\n int data[] = new int[ N ];\n for( int i = 0; i < data.length; i++ ) {\n data[i] = -1;\n }\n\n List<int[]> ret = new ArrayList<int[]>();\n\n createList(data,0,-1,ret);\n\n return ret;\n }" ]
[ "public VectorClock incremented(int nodeId, long time) {\n VectorClock copyClock = this.clone();\n copyClock.incrementVersion(nodeId, time);\n return copyClock;\n }", "private ModelNode parseAddress(final String profileName, final String inputAddress) {\n final ModelNode result = new ModelNode();\n if (profileName != null) {\n result.add(ServerOperations.PROFILE, profileName);\n }\n String[] parts = inputAddress.split(\",\");\n for (String part : parts) {\n String[] address = part.split(\"=\");\n if (address.length != 2) {\n throw new RuntimeException(part + \" is not a valid address segment\");\n }\n result.add(address[0], address[1]);\n }\n return result;\n }", "public String calculateCacheKey(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability){\r\n\t\tStringBuilder tmp = calculateCacheKeyInternal(sql, resultSetType,\r\n\t\t\t\tresultSetConcurrency);\r\n\r\n\t\ttmp.append(\", H:\");\r\n\t\ttmp.append(resultSetHoldability);\r\n\r\n\t\treturn tmp.toString();\r\n\t}", "private ResourceReport getResourceReport(TwillController controller, int maxWaitMs) {\n ResourceReport report = controller.getResourceReport();\n int elapsed = 0;\n while (report == null) {\n report = controller.getResourceReport();\n try {\n Thread.sleep(500);\n } catch (InterruptedException e) {\n throw new IllegalStateException(e);\n }\n elapsed += 500;\n if ((maxWaitMs != -1) && (elapsed > maxWaitMs)) {\n String msg = String.format(\"Exceeded max wait time to retrieve ResourceReport from Twill.\"\n + \" Elapsed time = %s ms\", elapsed);\n log.error(msg);\n throw new IllegalStateException(msg);\n }\n if ((elapsed % 10000) == 0) {\n log.info(\"Waiting for ResourceReport from Twill. Elapsed time = {} ms\", elapsed);\n }\n }\n return report;\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 }", "public List<BoxAPIResponse> execute(List<BoxAPIRequest> requests) {\n this.prepareRequest(requests);\n BoxJSONResponse batchResponse = (BoxJSONResponse) send();\n return this.parseResponse(batchResponse);\n }", "public void setOuterConeAngle(float angle)\n {\n setFloat(\"outer_cone_angle\", (float) Math.cos(Math.toRadians(angle)));\n mChanged.set(true);\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 static ZMatrixRMaj hermitian(int length, double min, double max, Random rand) {\n ZMatrixRMaj A = new ZMatrixRMaj(length,length);\n\n fillHermitian(A, min, max, rand);\n\n return A;\n }" ]
capture screenshot of an eye
[ "private void captureEye(GVRScreenshotCallback callback, GVRRenderTarget renderTarget, GVRViewManager.EYE eye, boolean useMultiview) {\n if (null == callback) {\n return;\n }\n readRenderResult(renderTarget,eye,useMultiview);\n returnScreenshotToCaller(callback, mReadbackBufferWidth, mReadbackBufferHeight);\n }" ]
[ "private boolean isWorkingDay(ProjectCalendar mpxjCalendar, Day day)\n {\n boolean result = false;\n net.sf.mpxj.DayType type = mpxjCalendar.getWorkingDay(day);\n if (type == null)\n {\n type = net.sf.mpxj.DayType.DEFAULT;\n }\n\n switch (type)\n {\n case WORKING:\n {\n result = true;\n break;\n }\n\n case NON_WORKING:\n {\n result = false;\n break;\n }\n\n case DEFAULT:\n {\n if (mpxjCalendar.getParent() == null)\n {\n result = false;\n }\n else\n {\n result = isWorkingDay(mpxjCalendar.getParent(), day);\n }\n break;\n }\n }\n\n return (result);\n }", "@Override\n public <E> DynamicType.Builder<E> processMethod(final DynamicType.Builder<E> builder, final Method method, final Annotation annotation)\n {\n String methodName = method.getName();\n if (ReflectionUtility.isGetMethod(method))\n return createInterceptor(builder, method);\n else if (ReflectionUtility.isSetMethod(method))\n return createInterceptor(builder, method);\n else if (methodName.startsWith(\"addAll\"))\n return createInterceptor(builder, method);\n else if (methodName.startsWith(\"add\"))\n return createInterceptor(builder, method);\n else\n throw new WindupException(\"Only get*, set*, add*, and addAll* method names are supported for @\"\n + SetInProperties.class.getSimpleName() + \", found at: \" + method.getName());\n }", "public void copyPageOnly(CmsResource originalPage, String targetPageRootPath)\n throws CmsException, NoCustomReplacementException {\n\n if ((null == originalPage)\n || !OpenCms.getResourceManager().getResourceType(originalPage).getTypeName().equals(\n CmsResourceTypeXmlContainerPage.getStaticTypeName())) {\n throw new CmsException(new CmsMessageContainer(Messages.get(), Messages.ERR_PAGECOPY_INVALID_PAGE_0));\n }\n m_originalPage = originalPage;\n CmsObject rootCms = getRootCms();\n rootCms.copyResource(originalPage.getRootPath(), targetPageRootPath);\n CmsResource copiedPage = rootCms.readResource(targetPageRootPath, CmsResourceFilter.IGNORE_EXPIRATION);\n m_targetFolder = rootCms.readResource(CmsResource.getFolderPath(copiedPage.getRootPath()));\n replaceElements(copiedPage);\n attachLocaleGroups(copiedPage);\n tryUnlock(copiedPage);\n\n }", "@Override public ProjectFile read(String accessDatabaseFileName) throws MPXJException\n {\n try\n {\n Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\");\n String url = \"jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb);DBQ=\" + accessDatabaseFileName;\n m_connection = DriverManager.getConnection(url);\n m_projectID = Integer.valueOf(1);\n return (read());\n }\n\n catch (ClassNotFoundException ex)\n {\n throw new MPXJException(\"Failed to load JDBC driver\", ex);\n }\n\n catch (SQLException ex)\n {\n throw new MPXJException(\"Failed to create connection\", ex);\n }\n\n finally\n {\n if (m_connection != null)\n {\n try\n {\n m_connection.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore exceptions when closing connection\n }\n }\n }\n }", "public CompositeGeneratorNode indent(final CompositeGeneratorNode parent, final String indentString) {\n final IndentNode indent = new IndentNode(indentString);\n List<IGeneratorNode> _children = parent.getChildren();\n _children.add(indent);\n return indent;\n }", "private void processQueue()\r\n {\r\n CacheEntry sv;\r\n while((sv = (CacheEntry) queue.poll()) != null)\r\n {\r\n sessionCache.remove(sv.oid);\r\n }\r\n }", "boolean advance() {\n if (header.frameCount <= 0) {\n return false;\n }\n\n if(framePointer == getFrameCount() - 1) {\n loopIndex++;\n }\n\n if(header.loopCount != LOOP_FOREVER && loopIndex > header.loopCount) {\n return false;\n }\n\n framePointer = (framePointer + 1) % header.frameCount;\n return true;\n }", "private static String resolveJavaCommand(final Path javaHome) {\n final String exe;\n if (javaHome == null) {\n exe = \"java\";\n } else {\n exe = javaHome.resolve(\"bin\").resolve(\"java\").toString();\n }\n if (exe.contains(\" \")) {\n return \"\\\"\" + exe + \"\\\"\";\n }\n return exe;\n }", "public static responderhtmlpage get(nitro_service service, String name) throws Exception{\n\t\tresponderhtmlpage obj = new responderhtmlpage();\n\t\tobj.set_name(name);\n\t\tresponderhtmlpage response = (responderhtmlpage) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Clean up the environment object for the given storage engine
[ "@Override\n public void removeStorageEngine(StorageEngine<ByteArray, byte[], byte[]> engine) {\n String storeName = engine.getName();\n BdbStorageEngine bdbEngine = (BdbStorageEngine) engine;\n\n synchronized(lock) {\n\n // Only cleanup the environment if it is per store. We cannot\n // cleanup a shared 'Environment' object\n if(useOneEnvPerStore) {\n\n Environment environment = this.environments.get(storeName);\n if(environment == null) {\n // Nothing to clean up.\n return;\n }\n\n // Remove from the set of unreserved stores if needed.\n if(this.unreservedStores.remove(environment)) {\n logger.info(\"Removed environment for store name: \" + storeName\n + \" from unreserved stores\");\n } else {\n logger.info(\"No environment found in unreserved stores for store name: \"\n + storeName);\n }\n\n // Try to delete the BDB directory associated\n File bdbDir = environment.getHome();\n if(bdbDir.exists() && bdbDir.isDirectory()) {\n String bdbDirPath = bdbDir.getPath();\n try {\n FileUtils.deleteDirectory(bdbDir);\n logger.info(\"Successfully deleted BDB directory : \" + bdbDirPath\n + \" for store name: \" + storeName);\n } catch(IOException e) {\n logger.error(\"Unable to delete BDB directory: \" + bdbDirPath\n + \" for store name: \" + storeName);\n }\n }\n\n // Remove the reference to BdbEnvironmentStats, which holds a\n // reference to the Environment\n BdbEnvironmentStats bdbEnvStats = bdbEngine.getBdbEnvironmentStats();\n this.aggBdbStats.unTrackEnvironment(bdbEnvStats);\n\n // Unregister the JMX bean for Environment\n if(voldemortConfig.isJmxEnabled()) {\n ObjectName name = JmxUtils.createObjectName(JmxUtils.getPackageName(bdbEnvStats.getClass()),\n storeName);\n // Un-register the environment stats mbean\n JmxUtils.unregisterMbean(name);\n }\n\n // Cleanup the environment\n environment.close();\n this.environments.remove(storeName);\n logger.info(\"Successfully closed the environment for store name : \" + storeName);\n\n }\n }\n }" ]
[ "@Override\n public boolean shouldRetry(int retryCount, Response response) {\n int code = response.code();\n //CHECKSTYLE IGNORE MagicNumber FOR NEXT 2 LINES\n return retryCount < this.retryCount\n && (code == 408 || (code >= 500 && code != 501 && code != 505));\n }", "public URI withEmptyAuthority(final URI uri) {\n URI _xifexpression = null;\n if ((uri.isFile() && (uri.authority() == null))) {\n _xifexpression = URI.createHierarchicalURI(uri.scheme(), \"\", uri.device(), uri.segments(), uri.query(), uri.fragment());\n } else {\n _xifexpression = uri;\n }\n return _xifexpression;\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}", "protected void setBeanDeploymentArchivesAccessibility() {\n for (WeldBeanDeploymentArchive beanDeploymentArchive : beanDeploymentArchives) {\n Set<WeldBeanDeploymentArchive> accessibleArchives = new HashSet<>();\n for (WeldBeanDeploymentArchive candidate : beanDeploymentArchives) {\n if (candidate.equals(beanDeploymentArchive)) {\n continue;\n }\n accessibleArchives.add(candidate);\n }\n beanDeploymentArchive.setAccessibleBeanDeploymentArchives(accessibleArchives);\n }\n }", "public static HikariConfig createHikariConfig(CmsParameterConfiguration config, String key) {\n\n Map<String, String> poolMap = Maps.newHashMap();\n for (Map.Entry<String, String> entry : config.entrySet()) {\n String suffix = getPropertyRelativeSuffix(KEY_DATABASE_POOL + \".\" + key, entry.getKey());\n if ((suffix != null) && !CmsStringUtil.isEmptyOrWhitespaceOnly(entry.getValue())) {\n String value = entry.getValue().trim();\n poolMap.put(suffix, value);\n }\n }\n\n // these are for backwards compatibility , all other properties not of the form db.pool.poolname.v11..... are ignored\n String jdbcUrl = poolMap.get(KEY_JDBC_URL);\n String params = poolMap.get(KEY_JDBC_URL_PARAMS);\n String driver = poolMap.get(KEY_JDBC_DRIVER);\n String user = poolMap.get(KEY_USERNAME);\n String password = poolMap.get(KEY_PASSWORD);\n String poolName = OPENCMS_URL_PREFIX + key;\n\n if ((params != null) && (jdbcUrl != null)) {\n jdbcUrl += params;\n }\n\n Properties hikariProps = new Properties();\n\n if (jdbcUrl != null) {\n hikariProps.put(\"jdbcUrl\", jdbcUrl);\n }\n if (driver != null) {\n hikariProps.put(\"driverClassName\", driver);\n }\n if (user != null) {\n user = OpenCms.getCredentialsResolver().resolveCredential(I_CmsCredentialsResolver.DB_USER, user);\n hikariProps.put(\"username\", user);\n }\n if (password != null) {\n password = OpenCms.getCredentialsResolver().resolveCredential(\n I_CmsCredentialsResolver.DB_PASSWORD,\n password);\n hikariProps.put(\"password\", password);\n }\n\n hikariProps.put(\"maximumPoolSize\", \"30\");\n\n // Properties of the form db.pool.poolname.v11.<foo> are directly passed to HikariCP as <foo>\n for (Map.Entry<String, String> entry : poolMap.entrySet()) {\n String suffix = getPropertyRelativeSuffix(\"v11\", entry.getKey());\n if (suffix != null) {\n hikariProps.put(suffix, entry.getValue());\n }\n }\n\n String configuredTestQuery = (String)(hikariProps.get(\"connectionTestQuery\"));\n String testQueryForDriver = testQueries.get(driver);\n if ((testQueryForDriver != null) && CmsStringUtil.isEmptyOrWhitespaceOnly(configuredTestQuery)) {\n hikariProps.put(\"connectionTestQuery\", testQueryForDriver);\n }\n hikariProps.put(\"registerMbeans\", \"true\");\n HikariConfig result = new HikariConfig(hikariProps);\n\n result.setPoolName(poolName.replace(\":\", \"_\"));\n return result;\n }", "protected String getQueryParam() {\n\n String param = parseOptionalStringValue(m_configObject, JSON_KEY_QUERYPARAM);\n if (param == null) {\n return null != m_baseConfig ? m_baseConfig.getGeneralConfig().getQueryParam() : DEFAULT_QUERY_PARAM;\n } else {\n return param;\n }\n }", "private static void listTaskNotes(ProjectFile file)\n {\n for (Task task : file.getTasks())\n {\n String notes = task.getNotes();\n\n if (notes.length() != 0)\n {\n System.out.println(\"Notes for \" + task.getName() + \": \" + notes);\n }\n }\n\n System.out.println();\n }", "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 }", "@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 }" ]
Writes data to delegate stream if it has been set. @param data the data to write
[ "private void writeToDelegate(byte[] data) {\n\n if (m_delegateStream != null) {\n try {\n m_delegateStream.write(data);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n }" ]
[ "private void sendEvents(final List<Event> events) {\n if (null != handlers) {\n for (EventHandler current : handlers) {\n for (Event event : events) {\n current.handleEvent(event);\n }\n }\n }\n\n LOG.info(\"Put events(\" + events.size() + \") to Monitoring Server.\");\n\n try {\n if (sendToEventadmin) {\n EventAdminPublisher.publish(events);\n } else {\n monitoringServiceClient.putEvents(events);\n }\n } catch (MonitoringException e) {\n throw e;\n } catch (Exception e) {\n throw new MonitoringException(\"002\",\n \"Unknown error while execute put events to Monitoring Server\", e);\n }\n\n }", "public static base_response unset(nitro_service client, tmsessionparameter resource, String[] args) throws Exception{\n\t\ttmsessionparameter unsetresource = new tmsessionparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public <V> V getObject(final String key, final Class<V> type) {\n final Object obj = this.values.get(key);\n return type.cast(obj);\n }", "public void printInferredDependencies(ClassDoc c) {\n\tif (hidden(c))\n\t return;\n\n\tOptions opt = optionProvider.getOptionsFor(c);\n\tSet<Type> types = new HashSet<Type>();\n\t// harvest method return and parameter types\n\tfor (MethodDoc method : filterByVisibility(c.methods(false), opt.inferDependencyVisibility)) {\n\t types.add(method.returnType());\n\t for (Parameter parameter : method.parameters()) {\n\t\ttypes.add(parameter.type());\n\t }\n\t}\n\t// and the field types\n\tif (!opt.inferRelationships) {\n\t for (FieldDoc field : filterByVisibility(c.fields(false), opt.inferDependencyVisibility)) {\n\t\ttypes.add(field.type());\n\t }\n\t}\n\t// see if there are some type parameters\n\tif (c.asParameterizedType() != null) {\n\t ParameterizedType pt = c.asParameterizedType();\n\t types.addAll(Arrays.asList(pt.typeArguments()));\n\t}\n\t// see if type parameters extend something\n\tfor(TypeVariable tv: c.typeParameters()) {\n\t if(tv.bounds().length > 0 )\n\t\ttypes.addAll(Arrays.asList(tv.bounds()));\n\t}\n\n\t// and finally check for explicitly imported classes (this\n\t// assumes there are no unused imports...)\n\tif (opt.useImports)\n\t types.addAll(Arrays.asList(importedClasses(c)));\n\n\t// compute dependencies\n\tfor (Type type : types) {\n\t // skip primitives and type variables, as well as dependencies\n\t // on the source class\n\t if (type.isPrimitive() || type instanceof WildcardType || type instanceof TypeVariable\n\t\t || c.toString().equals(type.asClassDoc().toString()))\n\t\tcontinue;\n\n\t // check if the destination is excluded from inference\n\t ClassDoc fc = type.asClassDoc();\n\t if (hidden(fc))\n\t\tcontinue;\n\t \n\t // check if source and destination are in the same package and if we are allowed\n\t // to infer dependencies between classes in the same package\n\t if(!opt.inferDepInPackage && c.containingPackage().equals(fc.containingPackage()))\n\t\tcontinue;\n\n\t // if source and dest are not already linked, add a dependency\n\t RelationPattern rp = getClassInfo(c, true).getRelation(fc.toString());\n\t if (rp == null || rp.matchesOne(new RelationPattern(RelationDirection.OUT))) {\n\t\trelation(opt, RelationType.DEPEND, c, fc, \"\", \"\", \"\");\n\t }\n\t \n\t}\n }", "protected Object getFieldData(Integer id, FieldType type, byte[][] fixedData, Var2Data varData)\n {\n Object result = null;\n\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.read(id, fixedData, varData);\n }\n\n return result;\n }", "@SafeVarargs\n public static <K> Set<K> set(final K... keys) {\n return new LinkedHashSet<K>(Arrays.asList(keys));\n }", "private static Iterable<BoxUser.Info> getUsersInfoForType(final BoxAPIConnection api,\n final String filterTerm, final String userType, final String externalAppUserId, final String... fields) {\n return new Iterable<BoxUser.Info>() {\n public Iterator<BoxUser.Info> iterator() {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (filterTerm != null) {\n builder.appendParam(\"filter_term\", filterTerm);\n }\n if (userType != null) {\n builder.appendParam(\"user_type\", userType);\n }\n if (externalAppUserId != null) {\n builder.appendParam(\"external_app_user_id\", externalAppUserId);\n }\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n URL url = USERS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n return new BoxUserIterator(api, url);\n }\n };\n }", "public <T extends CanvasWriter> T getWriter(Class<T> type, OauthToken oauthToken) {\n return getWriter(type, oauthToken, false);\n }", "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 }" ]
If the specified value is not greater than or equal to the specified minimum and less than or equal to the specified maximum, adjust it so that it is. @param value The value to check. @param min The minimum permitted value. @param max The maximum permitted value. @return {@code value} if it is between the specified limits, {@code min} if the value is too low, or {@code max} if the value is too high. @since 1.2
[ "public static int restrictRange(int value, int min, int max)\n {\n return Math.min((Math.max(value, min)), max);\n }" ]
[ "public static base_responses update(nitro_service client, dbdbprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdbdbprofile updateresources[] = new dbdbprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new dbdbprofile();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].interpretquery = resources[i].interpretquery;\n\t\t\t\tupdateresources[i].stickiness = resources[i].stickiness;\n\t\t\t\tupdateresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\tupdateresources[i].conmultiplex = resources[i].conmultiplex;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private boolean isForGerritHost(HttpRequest request) {\n if (!(request instanceof HttpRequestWrapper)) return false;\n HttpRequest originalRequest = ((HttpRequestWrapper) request).getOriginal();\n if (!(originalRequest instanceof HttpRequestBase)) return false;\n URI uri = ((HttpRequestBase) originalRequest).getURI();\n URI authDataUri = URI.create(authData.getHost());\n if (uri == null || uri.getHost() == null) return false;\n boolean hostEquals = uri.getHost().equals(authDataUri.getHost());\n boolean portEquals = uri.getPort() == authDataUri.getPort();\n return hostEquals && portEquals;\n }", "protected void createDocument() throws ParserConfigurationException\n {\n DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder builder = builderFactory.newDocumentBuilder();\n DocumentType doctype = builder.getDOMImplementation().createDocumentType(\"html\", \"-//W3C//DTD XHTML 1.1//EN\", \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\");\n doc = builder.getDOMImplementation().createDocument(\"http://www.w3.org/1999/xhtml\", \"html\", doctype);\n \n head = doc.createElement(\"head\");\n Element meta = doc.createElement(\"meta\");\n meta.setAttribute(\"http-equiv\", \"content-type\");\n meta.setAttribute(\"content\", \"text/html;charset=utf-8\");\n head.appendChild(meta);\n title = doc.createElement(\"title\");\n title.setTextContent(\"PDF Document\");\n head.appendChild(title);\n globalStyle = doc.createElement(\"style\");\n globalStyle.setAttribute(\"type\", \"text/css\");\n //globalStyle.setTextContent(createGlobalStyle());\n head.appendChild(globalStyle);\n \n body = doc.createElement(\"body\");\n \n Element root = doc.getDocumentElement();\n root.appendChild(head);\n root.appendChild(body);\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 static ResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) {\n StringBuilder prefix = new StringBuilder(SUBSYSTEM_NAME);\n for (String kp : keyPrefix) {\n prefix.append('.').append(kp);\n }\n return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, LoggingExtension.class.getClassLoader(), true, false) {\n @Override\n public String getOperationParameterDescription(final String operationName, final String paramName, final Locale locale, final ResourceBundle bundle) {\n if (DELEGATE_DESC_OPTS.contains(operationName)) {\n return getResourceAttributeDescription(paramName, locale, bundle);\n }\n return super.getOperationParameterDescription(operationName, paramName, locale, bundle);\n }\n\n @Override\n public String getOperationParameterValueTypeDescription(final String operationName, final String paramName, final Locale locale,\n final ResourceBundle bundle, final String... suffixes) {\n if (DELEGATE_DESC_OPTS.contains(operationName)) {\n return getResourceAttributeDescription(paramName, locale, bundle);\n }\n return super.getOperationParameterValueTypeDescription(operationName, paramName, locale, bundle, suffixes);\n }\n\n @Override\n public String getOperationParameterDeprecatedDescription(final String operationName, final String paramName, final Locale locale, final ResourceBundle bundle) {\n if (DELEGATE_DESC_OPTS.contains(operationName)) {\n return getResourceAttributeDeprecatedDescription(paramName, locale, bundle);\n }\n return super.getOperationParameterDeprecatedDescription(operationName, paramName, locale, bundle);\n }\n };\n }", "public List<String> getListAttribute(String section, String name) {\n return split(getAttribute(section, name));\n }", "public static Iterable<BoxRetentionPolicy.Info> getAll(final BoxAPIConnection api, String ... fields) {\r\n return getAll(null, null, null, DEFAULT_LIMIT, api, fields);\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 }", "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 }" ]
Create a JsonParser for a given json node. @param jsonNode the json node @return the json parser @throws IOException
[ "private static JsonParser newJsonParserForNode(JsonNode jsonNode) throws IOException {\n JsonParser parser = new JsonFactory().createParser(jsonNode.toString());\n parser.nextToken();\n return parser;\n }" ]
[ "public boolean doSyncPass() {\n if (!this.isConfigured || !syncLock.tryLock()) {\n return false;\n }\n try {\n if (logicalT == Long.MAX_VALUE) {\n if (logger.isInfoEnabled()) {\n logger.info(\"reached max logical time; resetting back to 0\");\n }\n logicalT = 0;\n }\n logicalT++;\n\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass START\",\n logicalT));\n }\n if (networkMonitor == null || !networkMonitor.isConnected()) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END - Network disconnected\",\n logicalT));\n }\n return false;\n }\n if (authMonitor == null || !authMonitor.tryIsLoggedIn()) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END - Logged out\",\n logicalT));\n }\n return false;\n }\n\n syncRemoteToLocal();\n syncLocalToRemote();\n\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END\",\n logicalT));\n }\n } catch (InterruptedException e) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass INTERRUPTED\",\n logicalT));\n }\n return false;\n } finally {\n syncLock.unlock();\n }\n return true;\n }", "@Override\n public Future<RawGcsCreationToken> continueObjectCreationAsync(final RawGcsCreationToken token,\n final ByteBuffer chunk, long timeoutMillis) {\n try {\n ensureInitialized();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n final Environment environment = ApiProxy.getCurrentEnvironment();\n return writePool.schedule(new Callable<RawGcsCreationToken>() {\n @Override\n public RawGcsCreationToken call() throws Exception {\n ApiProxy.setEnvironmentForCurrentThread(environment);\n return append(token, chunk);\n }\n }, 50, TimeUnit.MILLISECONDS);\n }", "private void processClassMethods(XMLStreamWriter writer, Class<?> aClass, Set<Method> methodSet) throws XMLStreamException\n {\n Method[] methods = aClass.getDeclaredMethods();\n for (Method method : methods)\n {\n if (!methodSet.contains(method) && Modifier.isPublic(method.getModifiers()) && !Modifier.isInterface(method.getModifiers()))\n {\n if (Modifier.isStatic(method.getModifiers()))\n {\n // TODO Handle static methods here\n }\n else\n {\n String name = method.getName();\n String methodSignature = createMethodSignature(method);\n String fullJavaName = aClass.getCanonicalName() + \".\" + name + methodSignature;\n\n if (!ignoreMethod(fullJavaName))\n {\n //\n // Hide the original method\n //\n writer.writeStartElement(\"method\");\n writer.writeAttribute(\"name\", name);\n writer.writeAttribute(\"sig\", methodSignature);\n\n writer.writeStartElement(\"attribute\");\n writer.writeAttribute(\"type\", \"System.ComponentModel.EditorBrowsableAttribute\");\n writer.writeAttribute(\"sig\", \"(Lcli.System.ComponentModel.EditorBrowsableState;)V\");\n writer.writeStartElement(\"parameter\");\n writer.writeCharacters(\"Never\");\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeEndElement();\n\n //\n // Create a wrapper method\n //\n name = name.toUpperCase().charAt(0) + name.substring(1);\n\n writer.writeStartElement(\"method\");\n writer.writeAttribute(\"name\", name);\n writer.writeAttribute(\"sig\", methodSignature);\n writer.writeAttribute(\"modifiers\", \"public\");\n\n writer.writeStartElement(\"body\");\n\n for (int index = 0; index <= method.getParameterTypes().length; index++)\n {\n if (index < 4)\n {\n writer.writeEmptyElement(\"ldarg_\" + index);\n }\n else\n {\n writer.writeStartElement(\"ldarg_s\");\n writer.writeAttribute(\"argNum\", Integer.toString(index));\n writer.writeEndElement();\n }\n }\n\n writer.writeStartElement(\"callvirt\");\n writer.writeAttribute(\"class\", aClass.getName());\n writer.writeAttribute(\"name\", method.getName());\n writer.writeAttribute(\"sig\", methodSignature);\n writer.writeEndElement();\n\n if (!method.getReturnType().getName().equals(\"void\"))\n {\n writer.writeEmptyElement(\"ldnull\");\n writer.writeEmptyElement(\"pop\");\n }\n writer.writeEmptyElement(\"ret\");\n writer.writeEndElement();\n writer.writeEndElement();\n\n /*\n * The private method approach doesn't work... so\n * 3. Add EditorBrowsableAttribute (Never) to original methods\n * 4. Generate C Sharp and VB variants of the DLL to avid case-sensitivity issues\n * 5. Implement static method support?\n <attribute type=\"System.ComponentModel.EditorBrowsableAttribute\" sig=\"(Lcli.System.ComponentModel.EditorBrowsableState;)V\">\n 914 <parameter>Never</parameter>\n 915 </attribute>\n */\n\n m_responseList.add(fullJavaName);\n }\n }\n }\n }\n }", "public void fireTaskWrittenEvent(Task task)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.taskWritten(task);\n }\n }\n }", "private void processRanges(List<DateRange> ranges, ProjectCalendarDateRanges container)\n {\n if (ranges != null)\n {\n for (DateRange range : ranges)\n {\n container.addRange(range);\n }\n }\n }", "public void appointTempoMaster(int deviceNumber) throws IOException {\n final DeviceUpdate update = getLatestStatusFor(deviceNumber);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + deviceNumber + \" not found on network.\");\n }\n appointTempoMaster(update);\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 }", "public RuleEnvelope getRule(String ruleId) throws ApiException {\n ApiResponse<RuleEnvelope> resp = getRuleWithHttpInfo(ruleId);\n return resp.getData();\n }", "public static aaa_stats get(nitro_service service) throws Exception{\n\t\taaa_stats obj = new aaa_stats();\n\t\taaa_stats[] response = (aaa_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}" ]
Extracts the nullity of a matrix using a preexisting decomposition. @see #singularThreshold(SingularValueDecomposition_F64) @param svd A precomputed decomposition. Not modified. @param threshold Tolerance used to determine of a singular value is singular. @return The nullity of the decomposed matrix.
[ "public static int nullity(SingularValueDecomposition_F64 svd , double threshold ) {\n int ret = 0;\n\n double w[]= svd.getSingularValues();\n\n int N = svd.numberOfSingularValues();\n\n int numCol = svd.numCols();\n\n for( int j = 0; j < N; j++ ) {\n if( w[j] <= threshold) ret++;\n }\n return ret + numCol-N;\n }" ]
[ "public Stamp allocateTimestamp() {\n\n synchronized (this) {\n Preconditions.checkState(!closed, \"tracker closed \");\n\n if (node == null) {\n Preconditions.checkState(allocationsInProgress == 0,\n \"expected allocationsInProgress == 0 when node == null\");\n Preconditions.checkState(!updatingZk, \"unexpected concurrent ZK update\");\n\n createZkNode(getTimestamp().getTxTimestamp());\n }\n\n allocationsInProgress++;\n }\n\n try {\n Stamp ts = getTimestamp();\n\n synchronized (this) {\n timestamps.add(ts.getTxTimestamp());\n }\n\n return ts;\n } catch (RuntimeException re) {\n synchronized (this) {\n allocationsInProgress--;\n }\n throw re;\n }\n }", "public 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 }", "public static long readBytes(byte[] bytes, int offset, int numBytes) {\n int shift = 0;\n long value = 0;\n for(int i = offset + numBytes - 1; i >= offset; i--) {\n value |= (bytes[i] & 0xFFL) << shift;\n shift += 8;\n }\n return value;\n }", "public static lbmonbindings_servicegroup_binding[] get(nitro_service service, String monitorname) throws Exception{\n\t\tlbmonbindings_servicegroup_binding obj = new lbmonbindings_servicegroup_binding();\n\t\tobj.set_monitorname(monitorname);\n\t\tlbmonbindings_servicegroup_binding response[] = (lbmonbindings_servicegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public boolean isMaintenanceModeEnabled(String appName) {\n App app = connection.execute(new AppInfo(appName), apiKey);\n return app.isMaintenance();\n }", "public ConditionalExpectationEstimator getConditionalExpectationEstimator(double exerciseTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException {\r\n\t\tRandomVariable[] regressionBasisFunctions = regressionBasisFunctionProvider.getBasisFunctions(exerciseTime, model);\r\n\t\treturn conditionalExpectationRegressionFactory.getConditionalExpectationEstimator(regressionBasisFunctions, regressionBasisFunctions);\r\n\t}", "public void sendFaderStartCommand(Set<Integer> deviceNumbersToStart, Set<Integer> deviceNumbersToStop) throws IOException {\n ensureRunning();\n byte[] payload = new byte[FADER_START_PAYLOAD.length];\n System.arraycopy(FADER_START_PAYLOAD, 0, payload, 0, FADER_START_PAYLOAD.length);\n payload[2] = getDeviceNumber();\n\n for (int i = 1; i <= 4; i++) {\n if (deviceNumbersToStart.contains(i)) {\n payload[i + 4] = 0;\n }\n if (deviceNumbersToStop.contains(i)) {\n payload[i + 4] = 1;\n }\n }\n\n assembleAndSendPacket(Util.PacketType.FADER_START_COMMAND, payload, getBroadcastAddress(), BeatFinder.BEAT_PORT);\n }", "public static base_response unset(nitro_service client, lbsipparameters resource, String[] args) throws Exception{\n\t\tlbsipparameters unsetresource = new lbsipparameters();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public synchronized boolean tryDelegateSlop(Node node) {\n if(asyncCallbackShouldSendhint) {\n return false;\n } else {\n slopDestinations.put(node, true);\n return true;\n }\n }" ]
Adds a class entry to this JAR. @param clazz the class to add to the JAR. @return {@code this}
[ "public Jar addClass(Class<?> clazz) throws IOException {\n final String resource = clazz.getName().replace('.', '/') + \".class\";\n return addEntry(resource, clazz.getClassLoader().getResourceAsStream(resource));\n }" ]
[ "public static Double getDistanceWithinThresholdOfCoordinates(\r\n Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) {\r\n throw new NotImplementedError();\r\n }", "public String getController() {\n final StringBuilder controller = new StringBuilder();\n if (getProtocol() != null) {\n controller.append(getProtocol()).append(\"://\");\n }\n if (getHost() != null) {\n controller.append(getHost());\n } else {\n controller.append(\"localhost\");\n }\n if (getPort() > 0) {\n controller.append(':').append(getPort());\n }\n return controller.toString();\n }", "@Override\n\tpublic ProxyAuthenticationMethod getMethod() {\n\t\tswitch (authenticationMethod) {\n\t\tcase BASIC:\n\t\t\treturn ProxyAuthenticationMethod.BASIC;\n\t\tcase DIGEST:\n\t\t\treturn ProxyAuthenticationMethod.DIGEST;\n\t\tcase URL:\n\t\t\treturn ProxyAuthenticationMethod.URL;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}", "public static void initialize(final Context context) {\n if (!initialized.compareAndSet(false, true)) {\n return;\n }\n\n applicationContext = context.getApplicationContext();\n\n final String packageName = applicationContext.getPackageName();\n localAppName = packageName;\n\n final PackageManager manager = applicationContext.getPackageManager();\n try {\n final PackageInfo pkgInfo = manager.getPackageInfo(packageName, 0);\n localAppVersion = pkgInfo.versionName;\n } catch (final NameNotFoundException e) {\n Log.d(TAG, \"Failed to get version of application, will not send in device info.\");\n }\n\n Log.d(TAG, \"Initialized android SDK\");\n }", "public Metadata remove(String path) {\n this.values.remove(this.pathToProperty(path));\n this.addOp(\"remove\", path, (String) null);\n return this;\n }", "public static Object newInstance(String className, Class type, Object arg) throws InstantiationException,\r\n IllegalAccessException,\r\n IllegalArgumentException,\r\n InvocationTargetException,\r\n NoSuchMethodException,\r\n SecurityException,\r\n ClassNotFoundException\r\n {\r\n return newInstance(className, new Class[]{type}, new Object[]{arg});\r\n }", "public static void main(String[] args) {\n if (args.length < 2) { // NOSONAR\n LOGGER.error(\"There must be at least two arguments\");\n return;\n }\n int lastIndex = args.length - 1;\n AllureReportGenerator reportGenerator = new AllureReportGenerator(\n getFiles(Arrays.copyOf(args, lastIndex))\n );\n reportGenerator.generate(new File(args[lastIndex]));\n }", "private void addAllProjectModels(ApplicationReportIndexModel navIdx, ProjectModel projectModel)\n {\n navIdx.addProjectModel(projectModel);\n for (ProjectModel childProject : projectModel.getChildProjects())\n {\n if (!Iterators.asSet(navIdx.getProjectModels()).contains(childProject))\n addAllProjectModels(navIdx, childProject);\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}" ]
Runs the print. @param args the cli arguments @throws Exception
[ "@VisibleForTesting\n public static void runMain(final String[] args) throws Exception {\n final CliHelpDefinition helpCli = new CliHelpDefinition();\n\n try {\n Args.parse(helpCli, args);\n if (helpCli.help) {\n printUsage(0);\n return;\n }\n } catch (IllegalArgumentException invalidOption) {\n // Ignore because it is probably one of the non-help options.\n }\n\n final CliDefinition cli = new CliDefinition();\n try {\n List<String> unusedArguments = Args.parse(cli, args);\n\n if (!unusedArguments.isEmpty()) {\n System.out.println(\"\\n\\nThe following arguments are not recognized: \" + unusedArguments);\n printUsage(1);\n return;\n }\n } catch (IllegalArgumentException invalidOption) {\n System.out.println(\"\\n\\n\" + invalidOption.getMessage());\n printUsage(1);\n return;\n }\n configureLogs(cli.verbose);\n\n AbstractXmlApplicationContext context = new ClassPathXmlApplicationContext(DEFAULT_SPRING_CONTEXT);\n\n if (cli.springConfig != null) {\n context = new ClassPathXmlApplicationContext(DEFAULT_SPRING_CONTEXT, cli.springConfig);\n }\n try {\n context.getBean(Main.class).run(cli);\n } finally {\n context.close();\n }\n }" ]
[ "public PhotoList<Photo> search(SearchParameters params, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SEARCH);\r\n\r\n parameters.putAll(params.getAsParameters());\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = 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 return photos;\r\n }", "private void populateCalendarHours(Record record, ProjectCalendarHours hours) throws MPXJException\n {\n hours.setDay(Day.getInstance(NumberHelper.getInt(record.getInteger(0))));\n addDateRange(hours, record.getTime(1), record.getTime(2));\n addDateRange(hours, record.getTime(3), record.getTime(4));\n addDateRange(hours, record.getTime(5), record.getTime(6));\n }", "protected synchronized void quit() {\n log.debug(\"Stopping {}\", getName());\n closeServerSocket();\n\n // Close all handlers. Handler threads terminate if run loop exits\n synchronized (handlers) {\n for (ProtocolHandler handler : handlers) {\n handler.close();\n }\n handlers.clear();\n }\n log.debug(\"Stopped {}\", getName());\n }", "public void recordAsyncOpTimeNs(SocketDestination dest, long opTimeNs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordAsyncOpTimeNs(null, opTimeNs);\n recordAsyncOpTimeNs(null, opTimeNs);\n } else {\n this.asynOpTimeRequestCounter.addRequest(opTimeNs);\n }\n }", "@SuppressWarnings(\"unchecked\")\n private static synchronized Map<String, Boolean> getCache(GraphRewrite event)\n {\n Map<String, Boolean> result = (Map<String, Boolean>)event.getRewriteContext().get(ClassificationServiceCache.class);\n if (result == null)\n {\n result = Collections.synchronizedMap(new LRUMap(30000));\n event.getRewriteContext().put(ClassificationServiceCache.class, result);\n }\n return result;\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 ItemRequest<Task> dependencies(String task) {\n \n String path = String.format(\"/tasks/%s/dependencies\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }", "private org.apache.log4j.Logger getLogger()\r\n\t{\r\n /*\r\n Logger interface extends Serializable, thus Log field is\r\n declared 'transient' and we have to null-check\r\n\t\t*/\r\n\t\tif (logger == null)\r\n\t\t{\r\n\t\t\tlogger = org.apache.log4j.Logger.getLogger(name);\r\n\t\t}\r\n\t\treturn logger;\r\n\t}", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void recordScreen(String screenName){\n if(screenName == null || (!currentScreenName.isEmpty() && currentScreenName.equals(screenName))) return;\n getConfigLogger().debug(getAccountId(), \"Screen changed to \" + screenName);\n currentScreenName = screenName;\n recordPageEventWithExtras(null);\n }" ]
Use this API to expire cachecontentgroup resources.
[ "public static base_responses expire(nitro_service client, cachecontentgroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcachecontentgroup expireresources[] = new cachecontentgroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\texpireresources[i] = new cachecontentgroup();\n\t\t\t\texpireresources[i].name = resources[i].name;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, expireresources,\"expire\");\n\t\t}\n\t\treturn result;\n\t}" ]
[ "public AT_Row setPaddingBottom(int paddingBottom) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingBottom(paddingBottom);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "private static MonetaryFormatsSingletonSpi loadMonetaryFormatsSingletonSpi() {\n try {\n return Optional.ofNullable(Bootstrap.getService(MonetaryFormatsSingletonSpi.class))\n .orElseGet(DefaultMonetaryFormatsSingletonSpi::new);\n } catch (Exception e) {\n Logger.getLogger(MonetaryFormats.class.getName())\n .log(Level.WARNING, \"Failed to load MonetaryFormatsSingletonSpi, using default.\", e);\n return new DefaultMonetaryFormatsSingletonSpi();\n }\n }", "public static double I(int n, double x) {\r\n if (n < 0)\r\n throw new IllegalArgumentException(\"the variable n out of range.\");\r\n else if (n == 0)\r\n return I0(x);\r\n else if (n == 1)\r\n return I(x);\r\n\r\n if (x == 0.0)\r\n return 0.0;\r\n\r\n double ACC = 40.0;\r\n double BIGNO = 1.0e+10;\r\n double BIGNI = 1.0e-10;\r\n\r\n double tox = 2.0 / Math.abs(x);\r\n double bip = 0, ans = 0.0;\r\n double bi = 1.0;\r\n\r\n for (int j = 2 * (n + (int) Math.sqrt(ACC * n)); j > 0; j--) {\r\n double bim = bip + j * tox * bi;\r\n bip = bi;\r\n bi = bim;\r\n\r\n if (Math.abs(bi) > BIGNO) {\r\n ans *= BIGNI;\r\n bi *= BIGNI;\r\n bip *= BIGNI;\r\n }\r\n\r\n if (j == n)\r\n ans = bip;\r\n }\r\n\r\n ans *= I0(x) / bi;\r\n return x < 0.0 && n % 2 == 1 ? -ans : ans;\r\n }", "private void updateDb(String dbName, String webapp) {\n\n m_mainLayout.removeAllComponents();\n m_setupBean.setDatabase(dbName);\n CmsDbSettingsPanel panel = new CmsDbSettingsPanel(m_setupBean);\n m_panel[0] = panel;\n panel.initFromSetupBean(webapp);\n m_mainLayout.addComponent(panel);\n }", "private String determineAndCacheOuterMostNullEmbeddable(String column, String[] path) {\n\t\tString embeddable = path[0];\n\t\t// process each embeddable from less specific to most specific\n\t\t// exclude path leaves as it's a column and not an embeddable\n\t\tfor ( int index = 0; index < path.length - 1; index++ ) {\n\t\t\tSet<String> columnsOfEmbeddable = getColumnsOfEmbeddableAndComputeEmbeddableNullness( embeddable );\n\n\t\t\tif ( nullEmbeddables.contains( embeddable ) ) {\n\t\t\t\t// the current embeddable only has null columns; cache that info for all the columns\n\t\t\t\tfor ( String columnOfEmbeddable : columnsOfEmbeddable ) {\n\t\t\t\t\tcolumnToOuterMostNullEmbeddableCache.put( columnOfEmbeddable, embeddable );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmaybeCacheOnNonNullEmbeddable( path, index, columnsOfEmbeddable );\n\t\t\t}\n\t\t\t// a more specific null embeddable might be present, carry on\n\t\t\tembeddable += \".\" + path[index + 1];\n\t\t}\n\t\treturn columnToOuterMostNullEmbeddableCache.get( column );\n\t}", "public static <T extends Range> T findRange(List<T> ranges, long value, int arraySize) {\n if (ranges.size() < 1) return null;\n T first = ranges.get(0);\n T last = ranges.get(arraySize - 1);\n // check out of bounds\n if (value < first.start() || value > last.start() + last.size()) {\n throw new OffsetOutOfRangeException(format(\"offset %s is out of range (%s, %s)\",//\n value,first.start(),last.start()+last.size()));\n }\n\n // check at the end\n if (value == last.start() + last.size()) return null;\n\n int low = 0;\n int high = arraySize - 1;\n while (low <= high) {\n int mid = (high + low) / 2;\n T found = ranges.get(mid);\n if (found.contains(value)) {\n return found;\n } else if (value < found.start()) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n }\n return null;\n }", "public static Iterable<BoxFileVersionRetention.Info> getRetentions(\n final BoxAPIConnection api, QueryFilter filter, String ... fields) {\n filter.addFields(fields);\n return new BoxResourceIterable<BoxFileVersionRetention.Info>(api,\n ALL_RETENTIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), filter.toString()),\n DEFAULT_LIMIT) {\n\n @Override\n protected BoxFileVersionRetention.Info factory(JsonObject jsonObject) {\n BoxFileVersionRetention retention = new BoxFileVersionRetention(api, jsonObject.get(\"id\").asString());\n return retention.new Info(jsonObject);\n }\n };\n }", "public final static int readMdLinkId(final StringBuilder out, final String in, final int start)\n {\n int pos = start;\n int counter = 1;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n boolean endReached = false;\n switch (ch)\n {\n case '\\n':\n out.append(' ');\n break;\n case '[':\n counter++;\n out.append(ch);\n break;\n case ']':\n counter--;\n if (counter == 0)\n {\n endReached = true;\n }\n else\n {\n out.append(ch);\n }\n break;\n default:\n out.append(ch);\n break;\n }\n if (endReached)\n {\n break;\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }", "private void parseResponse(InputStream inputStream) {\n\n try {\n DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\n Document doc = dBuilder.parse(inputStream);\n doc.getDocumentElement().normalize();\n\n NodeList nodes = doc.getElementsByTagName(\"place\");\n\n for (int i = 0; i < nodes.getLength(); i++) {\n Node node = nodes.item(i);\n\n if (node.getNodeType() == Node.ELEMENT_NODE) {\n Element element = (Element) node;\n _woeid = getValue(\"woeid\", element);\n }\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }" ]
Append the bounding volume particle positions, times and velocities to the existing mesh before creating a new scene object with this mesh attached to it. Also, append every created scene object and its creation time to corresponding array lists. @param particlePositions @param particleVelocities @param particleTimeStamps
[ "private void emit(float[] particlePositions, float[] particleVelocities,\n float[] particleTimeStamps)\n {\n float[] allParticlePositions = new float[particlePositions.length + particleBoundingVolume.length];\n System.arraycopy(particlePositions, 0, allParticlePositions, 0, particlePositions.length);\n System.arraycopy(particleBoundingVolume, 0, allParticlePositions,\n particlePositions.length, particleBoundingVolume.length);\n\n float[] allSpawnTimes = new float[particleTimeStamps.length + BVSpawnTimes.length];\n System.arraycopy(particleTimeStamps, 0, allSpawnTimes, 0, particleTimeStamps.length);\n System.arraycopy(BVSpawnTimes, 0, allSpawnTimes, particleTimeStamps.length, BVSpawnTimes.length);\n\n float[] allParticleVelocities = new float[particleVelocities.length + BVVelocities.length];\n System.arraycopy(particleVelocities, 0, allParticleVelocities, 0, particleVelocities.length);\n System.arraycopy(BVVelocities, 0, allParticleVelocities, particleVelocities.length, BVVelocities.length);\n\n\n Particles particleMesh = new Particles(mGVRContext, mMaxAge,\n mParticleSize, mEnvironmentAcceleration, mParticleSizeRate, mFadeWithAge,\n mParticleTexture, mColor, mNoiseFactor);\n\n\n GVRSceneObject particleObject = particleMesh.makeParticleMesh(allParticlePositions,\n allParticleVelocities, allSpawnTimes);\n\n this.addChildObject(particleObject);\n meshInfo.add(Pair.create(particleObject, currTime));\n }" ]
[ "public static String rgb(int r, int g, int b) {\n if (r < -100 || r > 100) {\n throw new IllegalArgumentException(\"Red value must be between -100 and 100, inclusive.\");\n }\n if (g < -100 || g > 100) {\n throw new IllegalArgumentException(\"Green value must be between -100 and 100, inclusive.\");\n }\n if (b < -100 || b > 100) {\n throw new IllegalArgumentException(\"Blue value must be between -100 and 100, inclusive.\");\n }\n return FILTER_RGB + \"(\" + r + \",\" + g + \",\" + b + \")\";\n }", "public static boolean organizeAssociationMapByRowKey(\n\t\t\torg.hibernate.ogm.model.spi.Association association,\n\t\t\tAssociationKey key,\n\t\t\tAssociationContext associationContext) {\n\n\t\tif ( association.isEmpty() ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif ( key.getMetadata().getRowKeyIndexColumnNames().length != 1 ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tObject valueOfFirstRow = association.get( association.getKeys().iterator().next() )\n\t\t\t\t.get( key.getMetadata().getRowKeyIndexColumnNames()[0] );\n\n\t\tif ( !( valueOfFirstRow instanceof String ) ) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// The list style may be explicitly enforced for compatibility reasons\n\t\treturn getMapStorage( associationContext ) == MapStorageType.BY_KEY;\n\t}", "public static int getScreenWidth(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n return metrics.widthPixels;\n }", "private org.apache.log4j.Logger getLogger()\r\n\t{\r\n /*\r\n Logger interface extends Serializable, thus Log field is\r\n declared 'transient' and we have to null-check\r\n\t\t*/\r\n\t\tif (logger == null)\r\n\t\t{\r\n\t\t\tlogger = org.apache.log4j.Logger.getLogger(name);\r\n\t\t}\r\n\t\treturn logger;\r\n\t}", "private int getCostRateTableEntryIndex(Date date)\n {\n int result = -1;\n\n CostRateTable table = getCostRateTable();\n if (table != null)\n {\n if (table.size() == 1)\n {\n result = 0;\n }\n else\n {\n result = table.getIndexByDate(date);\n }\n }\n\n return result;\n }", "public Set<ConstraintViolation> validate(DataSetInfo info) {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\ttry {\r\n\t\t\tif (info.isMandatory() && get(info.getDataSetNumber()) == null) {\r\n\t\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.MANDATORY_MISSING));\r\n\t\t\t}\r\n\t\t\tif (!info.isRepeatable() && getAll(info.getDataSetNumber()).size() > 1) {\r\n\t\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.REPEATABLE_REPEATED));\r\n\t\t\t}\r\n\t\t} catch (SerializationException e) {\r\n\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.INVALID_VALUE));\r\n\t\t}\r\n\t\treturn errors;\r\n\t}", "public void recordResourceRequestTimeUs(SocketDestination dest, long resourceRequestTimeUs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordResourceRequestTimeUs(null, resourceRequestTimeUs);\n recordResourceRequestTimeUs(null, resourceRequestTimeUs);\n } else {\n this.resourceRequestTimeRequestCounter.addRequest(resourceRequestTimeUs\n * Time.NS_PER_US);\n }\n }", "private boolean isAbandoned(final SubmittedPrintJob printJob) {\n final long duration = ThreadPoolJobManager.this.jobQueue.timeSinceLastStatusCheck(\n printJob.getEntry().getReferenceId());\n final boolean abandoned =\n duration > TimeUnit.SECONDS.toMillis(ThreadPoolJobManager.this.abandonedTimeout);\n if (abandoned) {\n LOGGER.info(\"Job {} is abandoned (no status check within the last {} seconds)\",\n printJob.getEntry().getReferenceId(), ThreadPoolJobManager.this.abandonedTimeout);\n }\n return abandoned;\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 }" ]
Describe the model as a list of resources with their address and model, which the HC can directly apply to create the model. Although the format might appear similar as the operations generated at boot-time this description is only useful to create the resource tree and cannot be used to invoke any operation. @param rootAddress the address of the root resource being described @param resource the root resource @return the list of resources
[ "private List<ModelNode> describeAsNodeList(PathAddress rootAddress, final Resource resource, boolean isRuntimeChange) {\n final List<ModelNode> list = new ArrayList<ModelNode>();\n\n describe(rootAddress, resource, list, isRuntimeChange);\n return list;\n }" ]
[ "@Override\n protected void stopInner() throws VoldemortException {\n List<VoldemortException> exceptions = new ArrayList<VoldemortException>();\n\n logger.info(\"Stopping services:\" + getIdentityNode().getId());\n /* Stop in reverse order */\n exceptions.addAll(stopOnlineServices());\n for(VoldemortService service: Utils.reversed(basicServices)) {\n try {\n service.stop();\n } catch(VoldemortException e) {\n exceptions.add(e);\n logger.error(e);\n }\n }\n logger.info(\"All services stopped for Node:\" + getIdentityNode().getId());\n\n if(exceptions.size() > 0)\n throw exceptions.get(0);\n // release lock of jvm heap\n JNAUtils.tryMunlockall();\n }", "public static List<Integer> checkKeyBelongsToPartition(byte[] key,\n Set<Pair<Integer, HashMap<Integer, List<Integer>>>> stealerNodeToMappingTuples,\n Cluster cluster,\n StoreDefinition storeDef) {\n List<Integer> keyPartitions = new RoutingStrategyFactory().updateRoutingStrategy(storeDef,\n cluster)\n .getPartitionList(key);\n List<Integer> nodesToPush = Lists.newArrayList();\n for(Pair<Integer, HashMap<Integer, List<Integer>>> stealNodeToMap: stealerNodeToMappingTuples) {\n List<Integer> nodePartitions = cluster.getNodeById(stealNodeToMap.getFirst())\n .getPartitionIds();\n if(StoreRoutingPlan.checkKeyBelongsToPartition(keyPartitions,\n nodePartitions,\n stealNodeToMap.getSecond())) {\n nodesToPush.add(stealNodeToMap.getFirst());\n }\n }\n return nodesToPush;\n }", "public ActionContext applyContentType(Result result) {\n if (!result.status().isError()) {\n return applyContentType();\n }\n return applyContentType(contentTypeForErrorResult(req()));\n }", "public AbstractGraph getModuleGraph(final String moduleId) {\n final ModuleHandler moduleHandler = new ModuleHandler(repoHandler);\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n final AbstractGraph graph = new ModuleGraph();\n addModuleToGraph(module, graph, 0);\n\n return graph;\n }", "public static wisite_binding get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_binding obj = new wisite_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_binding response = (wisite_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static final String printDuration(Duration duration)\n {\n String result = null;\n if (duration != null)\n {\n result = duration.getDuration() + \" \" + printTimeUnits(duration.getUnits());\n }\n return result;\n }", "public void writeTo(DataOutput outstream) throws Exception {\n S3Util.writeString(host, outstream);\n outstream.writeInt(port);\n S3Util.writeString(protocol, outstream);\n }", "public void setBaselineStartText(int baselineNumber, String value)\n {\n set(selectField(TaskFieldLists.BASELINE_STARTS, baselineNumber), value);\n }", "private static void freeTempLOB(ClobWrapper clob, BlobWrapper blob)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tif (clob != null)\r\n\t\t\t{\r\n\t\t\t\t// If the CLOB is open, close it\r\n\t\t\t\tif (clob.isOpen())\r\n\t\t\t\t{\r\n\t\t\t\t\tclob.close();\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Free the memory used by this CLOB\r\n\t\t\t\tclob.freeTemporary();\r\n\t\t\t}\r\n\r\n\t\t\tif (blob != null)\r\n\t\t\t{\r\n\t\t\t\t// If the BLOB is open, close it\r\n\t\t\t\tif (blob.isOpen())\r\n\t\t\t\t{\r\n\t\t\t\t\tblob.close();\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Free the memory used by this BLOB\r\n\t\t\t\tblob.freeTemporary();\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n logger.error(\"Error during temporary LOB release\", e);\r\n\t\t}\r\n\t}" ]
Parses operations where the input comes from variables to its left and right @param ops List of operations which should be parsed @param tokens List of all the tokens @param sequence List of operation sequence
[ "protected void parseOperationsLR(Symbol ops[], 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 boolean hasLeft = false;\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.VARIABLE ) {\n if( hasLeft ) {\n if( isTargetOp(token.previous,ops)) {\n token = createOp(token.previous.previous,token.previous,token,tokens,sequence);\n }\n } else {\n hasLeft = true;\n }\n } else {\n if( token.previous.getType() == Type.SYMBOL ) {\n throw new ParseError(\"Two symbols next to each other. \"+token.previous+\" and \"+token);\n }\n }\n token = token.next;\n }\n }" ]
[ "public static void main(String[] args) throws IOException {\n\t\tExampleHelpers.configureLogging();\n\t\tJsonSerializationProcessor.printDocumentation();\n\n\t\tJsonSerializationProcessor jsonSerializationProcessor = new JsonSerializationProcessor();\n\t\tExampleHelpers.processEntitiesFromWikidataDump(jsonSerializationProcessor);\n\t\tjsonSerializationProcessor.close();\n\t}", "private void setExceptions(ProjectCalendar mpxjCalendar, Calendars gpCalendar)\n {\n List<net.sf.mpxj.ganttproject.schema.Date> dates = gpCalendar.getDate();\n for (net.sf.mpxj.ganttproject.schema.Date date : dates)\n {\n addException(mpxjCalendar, date);\n }\n }", "public void setLinearLowerLimits(float limitX, float limitY, float limitZ) {\n Native3DGenericConstraint.setLinearLowerLimits(getNative(), limitX, limitY, limitZ);\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public Stream<ChangeEvent<DocumentT>> watch(final BsonValue... ids)\n throws InterruptedException, IOException {\n return operations.watch(\n new HashSet<>(Arrays.asList(ids)),\n false,\n documentClass\n ).execute(service);\n }", "static ChangeEvent<BsonDocument> changeEventForLocalInsert(\n final MongoNamespace namespace,\n final BsonDocument document,\n final boolean writePending\n ) {\n final BsonValue docId = BsonUtils.getDocumentId(document);\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.INSERT,\n document,\n namespace,\n new BsonDocument(\"_id\", docId),\n null,\n writePending);\n }", "public ListActiveCoursesInAccountOptions searchTerm(String searchTerm) {\n if(searchTerm == null || searchTerm.length() < 3) {\n throw new IllegalArgumentException(\"Search term must be at least 3 characters\");\n }\n addSingleItem(\"search_term\", searchTerm);\n return this;\n }", "public void setHomeAsUpIndicator(Drawable indicator) {\n if(!deviceSupportMultiPane()) {\n pulsante.setHomeAsUpIndicator(indicator);\n }\n else {\n actionBar.setHomeAsUpIndicator(indicator);\n }\n }", "public CmsJspDateSeriesBean getToDateSeries() {\n\n if (m_dateSeries == null) {\n m_dateSeries = new CmsJspDateSeriesBean(this, m_cms.getRequestContext().getLocale());\n }\n return m_dateSeries;\n }", "public void sendSyncModeCommand(int deviceNumber, boolean synced) throws IOException {\n final DeviceUpdate update = getLatestStatusFor(deviceNumber);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + deviceNumber + \" not found on network.\");\n }\n sendSyncModeCommand(update, synced);\n }" ]
Removes the value from the Collection mapped to by this key, leaving the rest of the collection intact. @param key the key to the Collection to remove the value from @param value the value to remove
[ "public void removeMapping(K key, V value) {\r\n if (treatCollectionsAsImmutable) {\r\n Collection<V> c = map.get(key);\r\n if (c != null) {\r\n Collection<V> newC = cf.newCollection();\r\n newC.addAll(c);\r\n newC.remove(value);\r\n map.put(key, newC);\r\n }\r\n\r\n } else {\r\n Collection<V> c = get(key);\r\n c.remove(value);\r\n }\r\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 static AssociationKeyMetadata getInverseAssociationKeyMetadata(OgmEntityPersister mainSidePersister, int propertyIndex) {\n\t\tType propertyType = mainSidePersister.getPropertyTypes()[propertyIndex];\n\t\tSessionFactoryImplementor factory = mainSidePersister.getFactory();\n\n\t\t// property represents no association, so no inverse meta-data can exist\n\t\tif ( !propertyType.isAssociationType() ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tJoinable mainSideJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( factory );\n\t\tOgmEntityPersister inverseSidePersister = null;\n\n\t\t// to-many association\n\t\tif ( mainSideJoinable.isCollection() ) {\n\t\t\tinverseSidePersister = (OgmEntityPersister) ( (OgmCollectionPersister) mainSideJoinable ).getElementPersister();\n\t\t}\n\t\t// to-one\n\t\telse {\n\t\t\tinverseSidePersister = (OgmEntityPersister) mainSideJoinable;\n\t\t\tmainSideJoinable = mainSidePersister;\n\t\t}\n\n\t\tString mainSideProperty = mainSidePersister.getPropertyNames()[propertyIndex];\n\n\t\t// property is a one-to-one association (a many-to-one cannot be on the inverse side) -> get the meta-data\n\t\t// straight from the main-side persister\n\t\tAssociationKeyMetadata inverseOneToOneMetadata = mainSidePersister.getInverseOneToOneAssociationKeyMetadata( mainSideProperty );\n\t\tif ( inverseOneToOneMetadata != null ) {\n\t\t\treturn inverseOneToOneMetadata;\n\t\t}\n\n\t\t// process properties of inverse side and try to find association back to main side\n\t\tfor ( String candidateProperty : inverseSidePersister.getPropertyNames() ) {\n\t\t\tType type = inverseSidePersister.getPropertyType( candidateProperty );\n\n\t\t\t// candidate is a *-to-many association\n\t\t\tif ( type.isCollectionType() ) {\n\t\t\t\tOgmCollectionPersister inverseCollectionPersister = getPersister( factory, (CollectionType) type );\n\t\t\t\tString mappedByProperty = inverseCollectionPersister.getMappedByProperty();\n\t\t\t\tif ( mainSideProperty.equals( mappedByProperty ) ) {\n\t\t\t\t\tif ( isCollectionMatching( mainSideJoinable, inverseCollectionPersister ) ) {\n\t\t\t\t\t\treturn inverseCollectionPersister.getAssociationKeyMetadata();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}", "public static int cudnnPoolingBackward(\n cudnnHandle handle, \n cudnnPoolingDescriptor poolingDesc, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnPoolingBackwardNative(handle, poolingDesc, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }", "private AlbumArt findArtInMemoryCaches(DataReference artReference) {\n // First see if we can find the new track in the hot cache as a hot cue\n for (AlbumArt cached : hotCache.values()) {\n if (cached.artReference.equals(artReference)) { // Found a hot cue hit, use it.\n return cached;\n }\n }\n\n // Not in the hot cache, see if it is in our LRU cache\n return artCache.get(artReference);\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}", "public void setKnots(int[] x, int[] rgb, byte[] types) {\n\t\tnumKnots = rgb.length+2;\n\t\txKnots = new int[numKnots];\n\t\tyKnots = new int[numKnots];\n\t\tknotTypes = new byte[numKnots];\n\t\tif (x != null)\n\t\t\tSystem.arraycopy(x, 0, xKnots, 1, numKnots-2);\n\t\telse\n\t\t\tfor (int i = 1; i > numKnots-1; i++)\n\t\t\t\txKnots[i] = 255*i/(numKnots-2);\n\t\tSystem.arraycopy(rgb, 0, yKnots, 1, numKnots-2);\n\t\tif (types != null)\n\t\t\tSystem.arraycopy(types, 0, knotTypes, 1, numKnots-2);\n\t\telse\n\t\t\tfor (int i = 0; i > numKnots; i++)\n\t\t\t\tknotTypes[i] = RGB|SPLINE;\n\t\tsortKnots();\n\t\trebuildGradient();\n\t}", "private String validateDuration() {\n\n if (!isValidEndTypeForPattern()) {\n return Messages.ERR_SERIALDATE_INVALID_END_TYPE_FOR_PATTERN_0;\n }\n switch (getEndType()) {\n case DATE:\n return (getStart().getTime() < (getSeriesEndDate().getTime() + DAY_IN_MILLIS))\n ? null\n : Messages.ERR_SERIALDATE_SERIES_END_BEFORE_START_0;\n case TIMES:\n return getOccurrences() > 0 ? null : Messages.ERR_SERIALDATE_INVALID_OCCURRENCES_0;\n default:\n return null;\n }\n\n }", "public PreparedStatement getDeleteStatement(ClassDescriptor cld) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cld.getStatementsForClass(m_conMan).getDeleteStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }", "public List<Integer> getAsyncOperationList(boolean showCompleted) {\n /**\n * Create a copy using an immutable set to avoid a\n * {@link java.util.ConcurrentModificationException}\n */\n Set<Integer> keySet = ImmutableSet.copyOf(operations.keySet());\n\n if(showCompleted)\n return new ArrayList<Integer>(keySet);\n\n List<Integer> keyList = new ArrayList<Integer>();\n for(int key: keySet) {\n AsyncOperation operation = operations.get(key);\n if(operation != null && !operation.getStatus().isComplete())\n keyList.add(key);\n }\n return keyList;\n }" ]
Check to see whether a packet starts with the standard header bytes, followed by a known byte identifying it. If so, return the kind of packet that has been recognized. @param packet a packet that has just been received @param port the port on which the packet has been received @return the type of packet that was recognized, or {@code null} if the packet was not recognized
[ "public static PacketType validateHeader(DatagramPacket packet, int port) {\n byte[] data = packet.getData();\n\n if (data.length < PACKET_TYPE_OFFSET) {\n logger.warn(\"Packet is too short to be a Pro DJ Link packet; must be at least \" + PACKET_TYPE_OFFSET +\n \" bytes long, was only \" + data.length + \".\");\n return null;\n }\n\n if (!getMagicHeader().equals(ByteBuffer.wrap(data, 0, MAGIC_HEADER.length))) {\n logger.warn(\"Packet did not have correct nine-byte header for the Pro DJ Link protocol.\");\n return null;\n }\n\n final Map<Byte, PacketType> portMap = PACKET_TYPE_MAP.get(port);\n if (portMap == null) {\n logger.warn(\"Do not know any Pro DJ Link packets that are received on port \" + port + \".\");\n return null;\n }\n\n final PacketType result = portMap.get(data[PACKET_TYPE_OFFSET]);\n if (result == null) {\n logger.warn(\"Do not know any Pro DJ Link packets received on port \" + port + \" with type \" +\n String.format(\"0x%02x\", data[PACKET_TYPE_OFFSET]) + \".\");\n }\n\n return result;\n }" ]
[ "public static Date getYearlyAbsoluteAsDate(RecurringData data)\n {\n Date result;\n Integer yearlyAbsoluteDay = data.getDayNumber();\n Integer yearlyAbsoluteMonth = data.getMonthNumber();\n Date startDate = data.getStartDate();\n\n if (yearlyAbsoluteDay == null || yearlyAbsoluteMonth == null || startDate == null)\n {\n result = null;\n }\n else\n {\n Calendar cal = DateHelper.popCalendar(startDate);\n cal.set(Calendar.MONTH, yearlyAbsoluteMonth.intValue() - 1);\n cal.set(Calendar.DAY_OF_MONTH, yearlyAbsoluteDay.intValue());\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n return result;\n }", "private List<File> getConfigFiles() {\n\n String[] filenames = {\n \"opencms-modules.xml\",\n \"opencms-system.xml\",\n \"opencms-vfs.xml\",\n \"opencms-importexport.xml\",\n \"opencms-sites.xml\",\n \"opencms-variables.xml\",\n \"opencms-scheduler.xml\",\n \"opencms-workplace.xml\",\n \"opencms-search.xml\"};\n List<File> result = new ArrayList<>();\n for (String fn : filenames) {\n File file = new File(m_configDir, fn);\n if (file.exists()) {\n result.add(file);\n }\n }\n return result;\n }", "public Query customizeQuery(Object anObject, PersistenceBroker aBroker, CollectionDescriptor aCod, QueryByCriteria aQuery)\r\n {\r\n return aQuery;\r\n }", "private void writeCostRateTables(Project.Resources.Resource xml, Resource mpx)\n {\n //Rates rates = m_factory.createProjectResourcesResourceRates();\n //xml.setRates(rates);\n //List<Project.Resources.Resource.Rates.Rate> ratesList = rates.getRate();\n\n List<Project.Resources.Resource.Rates.Rate> ratesList = null;\n\n for (int tableIndex = 0; tableIndex < 5; tableIndex++)\n {\n CostRateTable table = mpx.getCostRateTable(tableIndex);\n if (table != null)\n {\n Date from = DateHelper.FIRST_DATE;\n for (CostRateTableEntry entry : table)\n {\n if (costRateTableWriteRequired(entry, from))\n {\n if (ratesList == null)\n {\n Rates rates = m_factory.createProjectResourcesResourceRates();\n xml.setRates(rates);\n ratesList = rates.getRate();\n }\n\n Project.Resources.Resource.Rates.Rate rate = m_factory.createProjectResourcesResourceRatesRate();\n ratesList.add(rate);\n\n rate.setCostPerUse(DatatypeConverter.printCurrency(entry.getCostPerUse()));\n rate.setOvertimeRate(DatatypeConverter.printRate(entry.getOvertimeRate()));\n rate.setOvertimeRateFormat(DatatypeConverter.printTimeUnit(entry.getOvertimeRateFormat()));\n rate.setRatesFrom(from);\n from = entry.getEndDate();\n rate.setRatesTo(from);\n rate.setRateTable(BigInteger.valueOf(tableIndex));\n rate.setStandardRate(DatatypeConverter.printRate(entry.getStandardRate()));\n rate.setStandardRateFormat(DatatypeConverter.printTimeUnit(entry.getStandardRateFormat()));\n }\n }\n }\n }\n }", "public static List<KoreanPhraseExtractor.KoreanPhrase> extractPhrases(Seq<KoreanToken> tokens, boolean filterSpam, boolean includeHashtags) {\n return JavaConversions.seqAsJavaList(\n TwitterKoreanProcessor.extractPhrases(tokens, filterSpam, includeHashtags)\n );\n }", "@SuppressWarnings(\"unchecked\")\n\t/* @Nullable */\n\tpublic <T> T get(Object receiver, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {\n\t\tPreconditions.checkNotNull(receiver,\"receiver\");\n\t\tPreconditions.checkNotNull(fieldName,\"fieldName\");\n\t\t\n\t\tClass<? extends Object> clazz = receiver.getClass();\n\t\tField f = getDeclaredField(clazz, fieldName);\n\t\tif (!f.isAccessible())\n\t\t\tf.setAccessible(true);\n\t\treturn (T) f.get(receiver);\n\t}", "private static int readObjectData(int offset, String text, List<RTFEmbeddedObject> objects)\n {\n LinkedList<byte[]> blocks = new LinkedList<byte[]>();\n\n offset += (OBJDATA.length());\n offset = skipEndOfLine(text, offset);\n int length;\n int lastOffset = offset;\n\n while (offset != -1)\n {\n length = getBlockLength(text, offset);\n lastOffset = readDataBlock(text, offset, length, blocks);\n offset = skipEndOfLine(text, lastOffset);\n }\n\n RTFEmbeddedObject headerObject;\n RTFEmbeddedObject dataObject;\n\n while (blocks.isEmpty() == false)\n {\n headerObject = new RTFEmbeddedObject(blocks, 2);\n objects.add(headerObject);\n\n if (blocks.isEmpty() == false)\n {\n dataObject = new RTFEmbeddedObject(blocks, headerObject.getTypeFlag2());\n objects.add(dataObject);\n }\n }\n\n return (lastOffset);\n }", "@Override\n\tpublic String toCanonicalString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.canonicalString) == null) {\n\t\t\tstringCache.canonicalString = result = toNormalizedString(IPv6StringCache.canonicalParams);\n\t\t}\n\t\treturn result;\n\t}", "void addValue(V value, Resource resource) {\n\t\tthis.valueQueue.add(value);\n\t\tthis.valueSubjectQueue.add(resource);\n\t}" ]
Sets the value to a default.
[ "protected final void setDefaultValue() {\n\n m_start = null;\n m_end = null;\n m_patterntype = PatternType.NONE;\n m_dayOfMonth = 0;\n m_exceptions.clear();\n m_individualDates.clear();\n m_interval = 0;\n m_isEveryWorkingDay = false;\n m_isWholeDay = false;\n m_month = Month.JANUARY;\n m_seriesEndDate = null;\n m_seriesOccurrences = 0;\n m_weekDays.clear();\n m_weeksOfMonth.clear();\n m_endType = EndType.SINGLE;\n m_parentSeriesId = null;\n }" ]
[ "public void addTags(String photoId, String[] tags) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD_TAGS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"tags\", StringUtilities.join(tags, \" \", true));\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "public int size() {\n\t\tint size = cleared ? 0 : snapshot.size();\n\t\tfor ( Map.Entry<RowKey,AssociationOperation> op : currentState.entrySet() ) {\n\t\t\tswitch ( op.getValue().getType() ) {\n\t\t\t\tcase PUT:\n\t\t\t\t\tif ( cleared || !snapshot.containsKey( op.getKey() ) ) {\n\t\t\t\t\t\tsize++;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase REMOVE:\n\t\t\t\t\tif ( !cleared && snapshot.containsKey( op.getKey() ) ) {\n\t\t\t\t\t\tsize--;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn size;\n\t}", "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 }", "public void fire(TestCaseEvent event) {\n TestCaseResult testCase = testCaseStorage.get();\n event.process(testCase);\n\n notifier.fire(event);\n }", "public static base_responses update(nitro_service client, onlinkipv6prefix resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tonlinkipv6prefix updateresources[] = new onlinkipv6prefix[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new onlinkipv6prefix();\n\t\t\t\tupdateresources[i].ipv6prefix = resources[i].ipv6prefix;\n\t\t\t\tupdateresources[i].onlinkprefix = resources[i].onlinkprefix;\n\t\t\t\tupdateresources[i].autonomusprefix = resources[i].autonomusprefix;\n\t\t\t\tupdateresources[i].depricateprefix = resources[i].depricateprefix;\n\t\t\t\tupdateresources[i].decrementprefixlifetimes = resources[i].decrementprefixlifetimes;\n\t\t\t\tupdateresources[i].prefixvalidelifetime = resources[i].prefixvalidelifetime;\n\t\t\t\tupdateresources[i].prefixpreferredlifetime = resources[i].prefixpreferredlifetime;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "final protected void putChar(char c) {\n final int clen = _internalBuffer.length;\n if (clen == _bufferPosition) {\n final char[] next = new char[2 * clen + 1];\n\n System.arraycopy(_internalBuffer, 0, next, 0, _bufferPosition);\n _internalBuffer = next;\n }\n\n _internalBuffer[_bufferPosition++] = c;\n }", "public boolean destroyDependentInstance(T instance) {\n synchronized (dependentInstances) {\n for (Iterator<ContextualInstance<?>> iterator = dependentInstances.iterator(); iterator.hasNext();) {\n ContextualInstance<?> contextualInstance = iterator.next();\n if (contextualInstance.getInstance() == instance) {\n iterator.remove();\n destroy(contextualInstance);\n return true;\n }\n }\n }\n return false;\n }", "public Collection<EmailAlias> getEmailAliases() {\n URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n Collection<EmailAlias> emailAliases = new ArrayList<EmailAlias>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject emailAliasJSON = value.asObject();\n emailAliases.add(new EmailAlias(emailAliasJSON));\n }\n\n return emailAliases;\n }", "public ItemDocument updateTermsStatements(ItemIdValue itemIdValue,\n\t\t\tList<MonolingualTextValue> addLabels,\n\t\t\tList<MonolingualTextValue> addDescriptions,\n\t\t\tList<MonolingualTextValue> addAliases,\n\t\t\tList<MonolingualTextValue> deleteAliases,\n\t\t\tList<Statement> addStatements,\n\t\t\tList<Statement> deleteStatements,\n\t\t\tString summary) throws MediaWikiApiErrorException, IOException {\n\t\tItemDocument currentDocument = (ItemDocument) this.wikibaseDataFetcher\n\t\t\t\t.getEntityDocument(itemIdValue.getId());\n\t\t\n\t\treturn updateTermsStatements(currentDocument, addLabels,\n\t\t\t\taddDescriptions, addAliases, deleteAliases,\n\t\t\t\taddStatements, deleteStatements, summary);\n\t}" ]
Internal method which is called when the user has finished editing the title. @param box the text box which has been edited
[ "protected void onEditTitleTextBox(TextBox box) {\n\n if (m_titleEditHandler != null) {\n m_titleEditHandler.handleEdit(m_title, box);\n return;\n }\n\n String text = box.getText();\n box.removeFromParent();\n m_title.setText(text);\n m_title.setVisible(true);\n\n }" ]
[ "private <T> List<Class<?>> filter(List<Class<?>> enabledClasses, List<Class<?>> globallyEnabledClasses, LogMessageCallback logMessageCallback,\n BeanDeployment deployment) {\n for (Iterator<Class<?>> iterator = enabledClasses.iterator(); iterator.hasNext(); ) {\n Class<?> enabledClass = iterator.next();\n if (globallyEnabledClasses.contains(enabledClass)) {\n logMessageCallback.log(enabledClass, deployment.getBeanDeploymentArchive().getId());\n iterator.remove();\n }\n }\n return enabledClasses;\n }", "private Query getQueryBySqlCount(QueryBySQL aQuery)\r\n {\r\n String countSql = aQuery.getSql();\r\n\r\n int fromPos = countSql.toUpperCase().indexOf(\" FROM \");\r\n if(fromPos >= 0)\r\n {\r\n countSql = \"select count(*)\" + countSql.substring(fromPos);\r\n }\r\n\r\n int orderPos = countSql.toUpperCase().indexOf(\" ORDER BY \");\r\n if(orderPos >= 0)\r\n {\r\n countSql = countSql.substring(0, orderPos);\r\n }\r\n\r\n return new QueryBySQL(aQuery.getSearchClass(), countSql);\r\n }", "public void createLinks(ServiceReference<S> declarationBinderRef) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n if (linkerManagement.canBeLinked(declaration, declarationBinderRef)) {\n linkerManagement.link(declaration, declarationBinderRef);\n }\n }\n }", "@Override\n public List<JobInstance> getJobs(Query query)\n {\n return JqmClientFactory.getClient().getJobs(query);\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 void ensureFields(ClassDescriptorDef classDef, Collection fields) throws ConstraintException\r\n {\r\n boolean forceVirtual = !classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true);\r\n\r\n for (Iterator it = fields.iterator(); it.hasNext();)\r\n {\r\n FieldDescriptorDef fieldDef = (FieldDescriptorDef)it.next();\r\n\r\n // First we check whether this field is already present in the class\r\n FieldDescriptorDef foundFieldDef = classDef.getField(fieldDef.getName());\r\n\r\n if (foundFieldDef != null)\r\n {\r\n if (isEqual(fieldDef, foundFieldDef))\r\n {\r\n if (forceVirtual)\r\n {\r\n foundFieldDef.setProperty(PropertyHelper.OJB_PROPERTY_VIRTUAL_FIELD, \"true\");\r\n }\r\n continue;\r\n }\r\n else\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a different field of the same name\");\r\n }\r\n }\r\n\r\n // perhaps a reference or collection ?\r\n if (classDef.getCollection(fieldDef.getName()) != null)\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a collection of the same name\");\r\n }\r\n if (classDef.getReference(fieldDef.getName()) != null)\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a reference of the same name\");\r\n }\r\n classDef.addFieldClone(fieldDef);\r\n classDef.getField(fieldDef.getName()).setProperty(PropertyHelper.OJB_PROPERTY_VIRTUAL_FIELD, \"true\");\r\n }\r\n }", "private void readVersion(InputStream is) throws IOException\n {\n BytesReadInputStream bytesReadStream = new BytesReadInputStream(is);\n String version = DatatypeConverter.getString(bytesReadStream);\n m_offset += bytesReadStream.getBytesRead();\n SynchroLogger.log(\"VERSION\", version);\n \n String[] versionArray = version.split(\"\\\\.\");\n m_majorVersion = Integer.parseInt(versionArray[0]);\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 }", "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}" ]
Send a master handoff yield command to all registered listeners. @param toPlayer the device number to which we are being instructed to yield the tempo master role
[ "private void deliverMasterYieldCommand(int toPlayer) {\n for (final MasterHandoffListener listener : getMasterHandoffListeners()) {\n try {\n listener.yieldMasterTo(toPlayer);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master yield command to listener\", t);\n }\n }\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 }", "protected void parseBracketCreateMatrix(TokenList tokens, Sequence sequence) {\n List<TokenList.Token> left = new ArrayList<TokenList.Token>();\n\n TokenList.Token t = tokens.getFirst();\n\n while( t != null ) {\n TokenList.Token next = t.next;\n if( t.getSymbol() == Symbol.BRACKET_LEFT ) {\n left.add(t);\n } else if( t.getSymbol() == Symbol.BRACKET_RIGHT ) {\n if( left.isEmpty() )\n throw new RuntimeException(\"No matching left bracket for right\");\n\n TokenList.Token start = left.remove(left.size() - 1);\n\n // Compute everything inside the [ ], this will leave a\n // series of variables and semi-colons hopefully\n TokenList bracketLet = tokens.extractSubList(start.next,t.previous);\n parseBlockNoParentheses(bracketLet, sequence, true);\n MatrixConstructor constructor = constructMatrix(bracketLet);\n\n // define the matrix op and inject into token list\n Operation.Info info = Operation.matrixConstructor(constructor);\n sequence.addOperation(info.op);\n\n tokens.insert(start.previous, new TokenList.Token(info.output));\n\n // remove the brackets\n tokens.remove(start);\n tokens.remove(t);\n }\n\n t = next;\n }\n\n if( !left.isEmpty() )\n throw new RuntimeException(\"Dangling [\");\n }", "protected int getCenterChild(CacheDataSet cache) {\n if (cache.count() == 0)\n return -1;\n\n int id = cache.getId(0);\n switch (getGravityInternal()) {\n case TOP:\n case LEFT:\n case FRONT:\n case FILL:\n break;\n case BOTTOM:\n case RIGHT:\n case BACK:\n id = cache.getId(cache.count() - 1);\n break;\n case CENTER:\n int i = cache.count() / 2;\n while (i < cache.count() && i >= 0) {\n id = cache.getId(i);\n if (cache.getStartDataOffset(id) <= 0) {\n if (cache.getEndDataOffset(id) >= 0) {\n break;\n } else {\n i++;\n }\n } else {\n i--;\n }\n }\n break;\n default:\n break;\n }\n\n Log.d(LAYOUT, TAG, \"getCenterChild = %d \", id);\n return id;\n }", "public static JasperPrint generateJasperPrint(DynamicReport dr, LayoutManager layoutManager, JRDataSource ds, Map<String, Object> _parameters) throws JRException {\n log.info(\"generating JasperPrint\");\n JasperPrint jp;\n\n\n JasperReport jr = DynamicJasperHelper.generateJasperReport(dr, layoutManager, _parameters);\n jp = JasperFillManager.fillReport(jr, _parameters, ds);\n\n return jp;\n }", "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 }", "@Override public Task addTask()\n {\n ProjectFile parent = getParentFile();\n\n Task task = new Task(parent, this);\n\n m_children.add(task);\n\n parent.getTasks().add(task);\n\n setSummary(true);\n\n return (task);\n }", "public Collection<Method> getAllMethods(String name, int paramCount) {\n final Map<ParamList, Map<Class<?>, Method>> nameMap = methods.get(name);\n if (nameMap == null) {\n return Collections.emptySet();\n }\n final Collection<Method> methods = new ArrayList<Method>();\n for (Map<Class<?>, Method> map : nameMap.values()) {\n for (Method method : map.values()) {\n if (method.getParameterTypes().length == paramCount) {\n methods.add(method);\n }\n }\n }\n return methods;\n }", "public void removeMetadataProvider(MetadataProvider provider) {\n for (Set<MetadataProvider> providers : metadataProviders.values()) {\n providers.remove(provider);\n }\n }", "void throwCloudExceptionIfInFailedState() {\n if (this.isStatusFailed()) {\n if (this.errorBody() != null) {\n throw new CloudException(\"Async operation failed with provisioning state: \" + this.status(), this.response(), this.errorBody());\n } else {\n throw new CloudException(\"Async operation failed with provisioning state: \" + this.status(), this.response());\n }\n }\n }" ]
Returns an text table containing the matrix of Strings passed in. The first dimension of the matrix should represent the rows, and the second dimension the columns.
[ "public static String makeAsciiTable(Object[][] table, Object[] rowLabels, Object[] colLabels, int padLeft, int padRight, boolean tsv) {\r\n StringBuilder buff = new StringBuilder();\r\n // top row\r\n buff.append(makeAsciiTableCell(\"\", padLeft, padRight, tsv)); // the top left cell\r\n for (int j = 0; j < table[0].length; j++) { // assume table is a rectangular matrix\r\n buff.append(makeAsciiTableCell(colLabels[j], padLeft, padRight, (j != table[0].length - 1) && tsv));\r\n }\r\n buff.append('\\n');\r\n // all other rows\r\n for (int i = 0; i < table.length; i++) {\r\n // one row\r\n buff.append(makeAsciiTableCell(rowLabels[i], padLeft, padRight, tsv));\r\n for (int j = 0; j < table[i].length; j++) {\r\n buff.append(makeAsciiTableCell(table[i][j], padLeft, padRight, (j != table[0].length - 1) && tsv));\r\n }\r\n buff.append('\\n');\r\n }\r\n return buff.toString();\r\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 AT_Row setPadding(int padding){\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPadding(padding);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public static java.sql.Date toDate(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.sql.Date) {\n return (java.sql.Date) value;\n }\n if (value instanceof String) {\n if (\"\".equals((String) value)) {\n return null;\n }\n return new java.sql.Date(IN_DATE_FORMAT.parse((String) value).getTime());\n }\n\n return new java.sql.Date(IN_DATE_FORMAT.parse(value.toString()).getTime());\n }", "public List<CRFCliqueTree> getCliqueTrees(String filename, DocumentReaderAndWriter<IN> readerAndWriter) {\r\n // only for the OCR data does this matter\r\n flags.ocrTrain = false;\r\n\r\n List<CRFCliqueTree> cts = new ArrayList<CRFCliqueTree>();\r\n ObjectBank<List<IN>> docs = makeObjectBankFromFile(filename, readerAndWriter);\r\n for (List<IN> doc : docs) {\r\n cts.add(getCliqueTree(doc));\r\n }\r\n\r\n return cts;\r\n }", "public boolean needsRefresh() {\n boolean needsRefresh;\n\n this.refreshLock.readLock().lock();\n long now = System.currentTimeMillis();\n long tokenDuration = (now - this.lastRefresh);\n needsRefresh = (tokenDuration >= this.expires - REFRESH_EPSILON);\n this.refreshLock.readLock().unlock();\n\n return needsRefresh;\n }", "@Override\r\n\tpublic Token recoverInline(Parser recognizer) throws RecognitionException\r\n\t{\r\n\t\t// SINGLE TOKEN DELETION\r\n\t\tToken matchedSymbol = singleTokenDeletion(recognizer);\r\n\t\tif (matchedSymbol != null)\r\n\t\t{\r\n\t\t\t// we have deleted the extra token.\r\n\t\t\t// now, move past ttype token as if all were ok\r\n\t\t\trecognizer.consume();\r\n\t\t\treturn matchedSymbol;\r\n\t\t}\r\n\r\n\t\t// SINGLE TOKEN INSERTION\r\n\t\tif (singleTokenInsertion(recognizer))\r\n\t\t{\r\n\t\t\treturn getMissingSymbol(recognizer);\r\n\t\t}\r\n\t\t\r\n//\t\tBeetlException exception = new BeetlParserException(BeetlException.PARSER_MISS_ERROR);\r\n//\t\texception.pushToken(this.getGrammarToken(recognizer.getCurrentToken()));\r\n//\t\tthrow exception;\r\n\t\tthrow new InputMismatchException(recognizer);\r\n\t}", "public static int getScreenHeight(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n return metrics.heightPixels;\n }", "public void updateColor(TestColor color) {\n\n switch (color) {\n case green:\n m_forwardButton.setEnabled(true);\n m_confirmCheckbox.setVisible(false);\n m_status.setValue(STATUS_GREEN);\n break;\n case yellow:\n m_forwardButton.setEnabled(false);\n m_confirmCheckbox.setVisible(true);\n m_status.setValue(STATUS_YELLOW);\n break;\n case red:\n m_forwardButton.setEnabled(false);\n m_confirmCheckbox.setVisible(true);\n m_status.setValue(STATUS_RED);\n break;\n default:\n break;\n }\n }", "public List<Message> requestFolderMenuFrom(final SlotReference slotReference, final int sortOrder, final int folderId)\n throws Exception {\n\n ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {\n @Override\n public List<Message> useClient(Client client) throws Exception {\n if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {\n try {\n logger.debug(\"Requesting Key menu.\");\n Message response = client.menuRequestTyped(Message.KnownType.FOLDER_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,\n CdjStatus.TrackType.UNANALYZED, new NumberField(sortOrder), new NumberField(folderId), new NumberField(0xffffff));\n return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.UNANALYZED, response);\n } finally {\n client.unlockForMenuOperations();\n }\n } else {\n throw new TimeoutException(\"Unable to lock player for menu operations.\");\n }\n }\n };\n\n return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, \"requesting folder menu\");\n }" ]
Retrieves the timephased breakdown of the planned overtime work for this resource assignment. @return timephased planned work
[ "public List<TimephasedWork> getTimephasedOvertimeWork()\n {\n if (m_timephasedOvertimeWork == null && m_timephasedWork != null && getOvertimeWork() != null)\n {\n double perDayFactor = getRemainingOvertimeWork().getDuration() / (getRemainingWork().getDuration() - getRemainingOvertimeWork().getDuration());\n double totalFactor = getRemainingOvertimeWork().getDuration() / getRemainingWork().getDuration();\n\n perDayFactor = Double.isNaN(perDayFactor) ? 0 : perDayFactor;\n totalFactor = Double.isNaN(totalFactor) ? 0 : totalFactor;\n\n m_timephasedOvertimeWork = new DefaultTimephasedWorkContainer(m_timephasedWork, perDayFactor, totalFactor);\n }\n return m_timephasedOvertimeWork == null ? null : m_timephasedOvertimeWork.getData();\n }" ]
[ "public Class<T> getProxyClass() {\n String suffix = \"_$$_Weld\" + getProxyNameSuffix();\n String proxyClassName = getBaseProxyName();\n if (!proxyClassName.endsWith(suffix)) {\n proxyClassName = proxyClassName + suffix;\n }\n if (proxyClassName.startsWith(JAVA)) {\n proxyClassName = proxyClassName.replaceFirst(JAVA, \"org.jboss.weld\");\n }\n Class<T> proxyClass = null;\n Class<?> originalClass = bean != null ? bean.getBeanClass() : proxiedBeanType;\n BeanLogger.LOG.generatingProxyClass(proxyClassName);\n try {\n // First check to see if we already have this proxy class\n proxyClass = cast(classLoader == null? proxyServices.loadClass(originalClass, proxyClassName) : classLoader.loadClass(proxyClassName));\n } catch (ClassNotFoundException e) {\n // Create the proxy class for this instance\n try {\n proxyClass = createProxyClass(originalClass, proxyClassName);\n } catch (Throwable e1) {\n //attempt to load the class again, just in case another thread\n //defined it between the check and the create method\n try {\n proxyClass = cast(classLoader == null? proxyServices.loadClass(originalClass, proxyClassName) : classLoader.loadClass(proxyClassName));\n } catch (ClassNotFoundException e2) {\n BeanLogger.LOG.catchingDebug(e1);\n throw BeanLogger.LOG.unableToLoadProxyClass(bean, proxiedBeanType, e1);\n }\n }\n }\n return proxyClass;\n }", "@Override\n public final Float optFloat(final String key, final Float defaultValue) {\n Float result = optFloat(key);\n return result == null ? defaultValue : result;\n }", "protected void updateNorms( int j ) {\n boolean foundNegative = false;\n for( int col = j; col < numCols; col++ ) {\n double e = dataQR[col][j-1];\n double v = normsCol[col] -= e*e;\n\n if( v < 0 ) {\n foundNegative = true;\n break;\n }\n }\n\n // if a negative sum has been found then clearly too much precision has been lost\n // and it should recompute the column norms from scratch\n if( foundNegative ) {\n for( int col = j; col < numCols; col++ ) {\n double u[] = dataQR[col];\n double actual = 0;\n for( int i=j; i < numRows; i++ ) {\n double v = u[i];\n actual += v*v;\n }\n normsCol[col] = actual;\n }\n }\n }", "private void addDependencyToGraph(final DbDependency dependency, final AbstractGraph graph, final int depth, final String parentId) {\n // In that case of Axway artifact we will add a module to the graph\n if (filters.getCorporateFilter().filter(dependency)) {\n final DbModule dbTarget = repoHandler.getModuleOf(dependency.getTarget());\n\n // if there is no module, add the artifact to the graph\n if(dbTarget == null){\n LOG.error(\"Got missing reference: \" + dependency.getTarget());\n final DbArtifact dbArtifact = DataUtils.createDbArtifact(dependency.getTarget());\n final String targetElementId = graph.getId(dbArtifact);\n graph.addElement(targetElementId, dbArtifact.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n return;\n }\n\n // Add the element to the graph\n addModuleToGraph(dbTarget, graph, depth + 1);\n\n //Add the dependency to the graph\n final String moduleElementId = graph.getId(dbTarget);\n graph.addDependency(parentId, moduleElementId, dependency.getScope());\n }\n // In case a third-party we will add an artifact\n else {\n final DbArtifact dbTarget = repoHandler.getArtifact(dependency.getTarget());\n if(dbTarget == null){\n LOG.error(\"Got missing artifact: \" + dependency.getTarget());\n return;\n }\n\n if(!graph.isTreated(graph.getId(dbTarget))){\n final ModelMapper modelMapper = new ModelMapper(repoHandler);\n final Artifact target = modelMapper.getArtifact(dbTarget);\n final String targetElementId = graph.getId(target);\n graph.addElement(targetElementId, target.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n }\n }\n }", "public void close() throws IOException {\n\t\tSystem.out.println(\"Serialized \"\n\t\t\t\t+ this.jsonSerializer.getEntityDocumentCount()\n\t\t\t\t+ \" item documents to JSON file \" + OUTPUT_FILE_NAME + \".\");\n\t\tthis.jsonSerializer.close();\n\t}", "public static List<String> getNodeListFromStringLineSeperateOrSpaceSeperate(\n String listStr, boolean removeDuplicate) {\n\n List<String> nodes = new ArrayList<String>();\n\n for (String token : listStr.split(\"[\\\\r?\\\\n| +]+\")) {\n\n // 20131025: fix if fqdn has space in the end.\n if (token != null && !token.trim().isEmpty()) {\n nodes.add(token.trim());\n\n }\n }\n\n if (removeDuplicate) {\n removeDuplicateNodeList(nodes);\n }\n logger.info(\"Target hosts size : \" + nodes.size());\n\n return nodes;\n\n }", "private UserAlias getUserAlias(Object attribute)\r\n\t{\r\n\t\tif (m_userAlias != null)\r\n\t\t{\r\n\t\t\treturn m_userAlias;\r\n\t\t}\r\n\t\tif (!(attribute instanceof String))\r\n\t\t{\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tif (m_alias == null)\r\n\t\t{\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tif (m_aliasPath == null)\r\n\t\t{\r\n\t\t\tboolean allPathsAliased = true;\r\n\t\t\treturn new UserAlias(m_alias, (String)attribute, allPathsAliased);\r\n\t\t}\r\n\t\treturn new UserAlias(m_alias, (String)attribute, m_aliasPath);\r\n\t}", "public Profile add(String profileName) throws Exception {\n Profile profile = new Profile();\n int id = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n Clob clobProfileName = sqlService.toClob(profileName, sqlConnection);\n\n statement = sqlConnection.prepareStatement(\n \"INSERT INTO \" + Constants.DB_TABLE_PROFILE\n + \"(\" + Constants.PROFILE_PROFILE_NAME + \") \" +\n \" VALUES (?)\", PreparedStatement.RETURN_GENERATED_KEYS\n );\n\n statement.setClob(1, clobProfileName);\n statement.executeUpdate();\n results = statement.getGeneratedKeys();\n if (results.next()) {\n id = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add client\");\n }\n results.close();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_CLIENT +\n \"(\" + Constants.CLIENT_CLIENT_UUID + \",\" + Constants.CLIENT_IS_ACTIVE + \",\"\n + Constants.CLIENT_PROFILE_ID + \") \" +\n \" VALUES (?, ?, ?)\");\n statement.setString(1, Constants.PROFILE_CLIENT_DEFAULT_ID);\n statement.setBoolean(2, false);\n statement.setInt(3, id);\n statement.executeUpdate();\n\n profile.setName(profileName);\n profile.setId(id);\n } catch (SQLException e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return profile;\n }", "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 }" ]
Use this API to unset the properties of sslservice resource. Properties that need to be unset are specified in args array.
[ "public static base_response unset(nitro_service client, sslservice resource, String[] args) throws Exception{\n\t\tsslservice unsetresource = new sslservice();\n\t\tunsetresource.servicename = resource.servicename;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
[ "public CurrencyQueryBuilder setCountries(Locale... countries) {\n return set(CurrencyQuery.KEY_QUERY_COUNTRIES, Arrays.asList(countries));\n }", "@Override\r\n @SuppressWarnings(\"unchecked\")\r\n public V put(K key, V value) {\r\n if (value == null) {\r\n return put(key, (V)nullValue);\r\n }\r\n // key could be not in original or in deltaMap\r\n // key could be not in original but in deltaMap\r\n // key could be in original but removed from deltaMap\r\n // key could be in original but mapped to something else in deltaMap\r\n V result = deltaMap.put(key, value);\r\n if (result == null) {\r\n return originalMap.get(key);\r\n }\r\n if (result == nullValue) {\r\n return null;\r\n }\r\n if (result == removedValue) {\r\n return null;\r\n }\r\n return result;\r\n }", "public void attachMetadataCache(SlotReference slot, File file)\n throws IOException {\n ensureRunning();\n if (slot.player < 1 || slot.player > 4 || DeviceFinder.getInstance().getLatestAnnouncementFrom(slot.player) == null) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for player \" + slot.player);\n }\n if ((slot.slot != CdjStatus.TrackSourceSlot.USB_SLOT) && (slot.slot != CdjStatus.TrackSourceSlot.SD_SLOT)) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for slot \" + slot.slot);\n }\n\n MetadataCache cache = new MetadataCache(file);\n final MediaDetails slotDetails = getMediaDetailsFor(slot);\n if (cache.sourceMedia != null && slotDetails != null) {\n if (!slotDetails.hashKey().equals(cache.sourceMedia.hashKey())) {\n throw new IllegalArgumentException(\"Cache was created for different media (\" + cache.sourceMedia.hashKey() +\n \") than is in the slot (\" + slotDetails.hashKey() + \").\");\n }\n if (slotDetails.hasChanged(cache.sourceMedia)) {\n logger.warn(\"Media has changed (\" + slotDetails + \") since cache was created (\" + cache.sourceMedia +\n \"). Attaching anyway as instructed.\");\n }\n }\n attachMetadataCacheInternal(slot, cache);\n }", "private void processDays(ProjectCalendar calendar) throws Exception\n {\n // Default all days to non-working\n for (Day day : Day.values())\n {\n calendar.setWorkingDay(day, false);\n }\n\n List<Row> rows = getRows(\"select * from zcalendarrule where zcalendar1=? and z_ent=?\", calendar.getUniqueID(), m_entityMap.get(\"CalendarWeekDayRule\"));\n for (Row row : rows)\n {\n Day day = row.getDay(\"ZWEEKDAY\");\n String timeIntervals = row.getString(\"ZTIMEINTERVALS\");\n if (timeIntervals == null)\n {\n calendar.setWorkingDay(day, false);\n }\n else\n {\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n NodeList nodes = getNodeList(timeIntervals, m_dayTimeIntervals);\n calendar.setWorkingDay(day, nodes.getLength() > 0);\n\n for (int loop = 0; loop < nodes.getLength(); loop++)\n {\n NamedNodeMap attributes = nodes.item(loop).getAttributes();\n Date startTime = m_calendarTimeFormat.parse(attributes.getNamedItem(\"startTime\").getTextContent());\n Date endTime = m_calendarTimeFormat.parse(attributes.getNamedItem(\"endTime\").getTextContent());\n\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n hours.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }", "public static responderpolicylabel_responderpolicy_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tresponderpolicylabel_responderpolicy_binding obj = new responderpolicylabel_responderpolicy_binding();\n\t\tobj.set_labelname(labelname);\n\t\tresponderpolicylabel_responderpolicy_binding response[] = (responderpolicylabel_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void update(StoreDefinition storeDef) {\n if(!useOneEnvPerStore)\n throw new VoldemortException(\"Memory foot print can be set only when using different environments per store\");\n\n String storeName = storeDef.getName();\n Environment environment = environments.get(storeName);\n // change reservation amount of reserved store\n if(!unreservedStores.contains(environment) && storeDef.hasMemoryFootprint()) {\n EnvironmentMutableConfig mConfig = environment.getMutableConfig();\n long currentCacheSize = mConfig.getCacheSize();\n long newCacheSize = storeDef.getMemoryFootprintMB() * ByteUtils.BYTES_PER_MB;\n if(currentCacheSize != newCacheSize) {\n long newReservedCacheSize = this.reservedCacheSize - currentCacheSize\n + newCacheSize;\n\n // check that we leave a 'minimum' shared cache\n if((voldemortConfig.getBdbCacheSize() - newReservedCacheSize) < voldemortConfig.getBdbMinimumSharedCache()) {\n throw new StorageInitializationException(\"Reservation of \"\n + storeDef.getMemoryFootprintMB()\n + \" MB for store \"\n + storeName\n + \" violates minimum shared cache size of \"\n + voldemortConfig.getBdbMinimumSharedCache());\n }\n\n this.reservedCacheSize = newReservedCacheSize;\n adjustCacheSizes();\n mConfig.setCacheSize(newCacheSize);\n environment.setMutableConfig(mConfig);\n logger.info(\"Setting private cache for store \" + storeDef.getName() + \" to \"\n + newCacheSize);\n }\n } else {\n // we cannot support changing a reserved store to unreserved or vice\n // versa since the sharedCache param is not mutable\n throw new VoldemortException(\"Cannot switch between shared and private cache dynamically\");\n }\n }", "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 }", "public VALUE get(KEY key) {\n CacheEntry<VALUE> entry;\n synchronized (this) {\n entry = values.get(key);\n }\n VALUE value;\n if (entry != null) {\n if (isExpiring) {\n long age = System.currentTimeMillis() - entry.timeCreated;\n if (age < expirationMillis) {\n value = getValue(key, entry);\n } else {\n countExpired++;\n synchronized (this) {\n values.remove(key);\n }\n value = null;\n }\n } else {\n value = getValue(key, entry);\n }\n } else {\n value = null;\n }\n if (value != null) {\n countHit++;\n } else {\n countMiss++;\n }\n return value;\n }", "private void handleGlobalArguments(CommandLine cmd) {\n\t\tif (cmd.hasOption(CMD_OPTION_DUMP_LOCATION)) {\n\t\t\tthis.dumpDirectoryLocation = cmd\n\t\t\t\t\t.getOptionValue(CMD_OPTION_DUMP_LOCATION);\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_OFFLINE_MODE)) {\n\t\t\tthis.offlineMode = true;\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_QUIET)) {\n\t\t\tthis.quiet = true;\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_CREATE_REPORT)) {\n\t\t\tthis.reportFilename = cmd.getOptionValue(CMD_OPTION_CREATE_REPORT);\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_LANGUAGES)) {\n\t\t\tsetLanguageFilters(cmd.getOptionValue(OPTION_FILTER_LANGUAGES));\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_SITES)) {\n\t\t\tsetSiteFilters(cmd.getOptionValue(OPTION_FILTER_SITES));\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_PROPERTIES)) {\n\t\t\tsetPropertyFilters(cmd.getOptionValue(OPTION_FILTER_PROPERTIES));\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_LOCAL_DUMPFILE)) {\n\t\t\tthis.inputDumpLocation = cmd.getOptionValue(OPTION_LOCAL_DUMPFILE);\n\t\t}\n\t}" ]
Decode a code from the stream s using huffman table h. Return the symbol or a negative value if there is an error. If all of the lengths are zero, i.e. an empty code, or if the code is incomplete and an invalid code is received, then -9 is returned after reading MAXBITS bits. Format notes: - The codes as stored in the compressed data are bit-reversed relative to a simple integer ordering of codes of the same lengths. Hence below the bits are pulled from the compressed data one at a time and used to build the code value reversed from what is in the stream in order to permit simple integer comparisons for decoding. - The first code for the shortest length is all ones. Subsequent codes of the same length are simply integer decrements of the previous code. When moving up a length, a one bit is appended to the code. For a complete code, the last code of the longest length will be all zeros. To support this ordering, the bits pulled during decoding are inverted to apply the more "natural" ordering starting with all zeros and incrementing. @param h Huffman table @return status code
[ "private int decode(Huffman h) throws IOException\n {\n int len; /* current number of bits in code */\n int code; /* len bits being decoded */\n int first; /* first code of length len */\n int count; /* number of codes of length len */\n int index; /* index of first code of length len in symbol table */\n int bitbuf; /* bits from stream */\n int left; /* bits left in next or left to process */\n //short *next; /* next number of codes */\n\n bitbuf = m_bitbuf;\n left = m_bitcnt;\n code = first = index = 0;\n len = 1;\n int nextIndex = 1; // next = h->count + 1;\n while (true)\n {\n while (left-- != 0)\n {\n code |= (bitbuf & 1) ^ 1; /* invert code */\n bitbuf >>= 1;\n //count = *next++;\n count = h.m_count[nextIndex++];\n if (code < first + count)\n { /* if length len, return symbol */\n m_bitbuf = bitbuf;\n m_bitcnt = (m_bitcnt - len) & 7;\n return h.m_symbol[index + (code - first)];\n }\n index += count; /* else update for next length */\n first += count;\n first <<= 1;\n code <<= 1;\n len++;\n }\n left = (MAXBITS + 1) - len;\n if (left == 0)\n {\n break;\n }\n if (m_left == 0)\n {\n m_in = m_input.read();\n m_left = m_in == -1 ? 0 : 1;\n if (m_left == 0)\n {\n throw new IOException(\"out of input\"); /* out of input */\n }\n }\n bitbuf = m_in;\n m_left--;\n if (left > 8)\n {\n left = 8;\n }\n }\n return -9; /* ran out of codes */\n }" ]
[ "public static appfwprofile_crosssitescripting_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_crosssitescripting_binding obj = new appfwprofile_crosssitescripting_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_crosssitescripting_binding response[] = (appfwprofile_crosssitescripting_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void setFrustum(float[] frustum)\n {\n Matrix4f projMatrix = new Matrix4f();\n projMatrix.setFrustum(frustum[0], frustum[3], frustum[1], frustum[4], frustum[2], frustum[5]);\n setFrustum(projMatrix);\n }", "public void installApp(Functions.Func callback) {\n if (isPwaSupported()) {\n appInstaller = new AppInstaller(callback);\n appInstaller.prompt();\n }\n }", "public Iterable<V> sorted(Iterator<V> input) {\n ExecutorService executor = new ThreadPoolExecutor(this.numThreads,\n this.numThreads,\n 1000L,\n TimeUnit.MILLISECONDS,\n new SynchronousQueue<Runnable>(),\n new CallerRunsPolicy());\n final AtomicInteger count = new AtomicInteger(0);\n final List<File> tempFiles = Collections.synchronizedList(new ArrayList<File>());\n while(input.hasNext()) {\n final int segmentId = count.getAndIncrement();\n final long segmentStartMs = System.currentTimeMillis();\n logger.info(\"Segment \" + segmentId + \": filling sort buffer for segment...\");\n @SuppressWarnings(\"unchecked\")\n final V[] buffer = (V[]) new Object[internalSortSize];\n int segmentSizeIter = 0;\n for(; segmentSizeIter < internalSortSize && input.hasNext(); segmentSizeIter++)\n buffer[segmentSizeIter] = input.next();\n final int segmentSize = segmentSizeIter;\n logger.info(\"Segment \" + segmentId + \": sort buffer filled...adding to sort queue.\");\n\n // sort and write out asynchronously\n executor.execute(new Runnable() {\n\n public void run() {\n logger.info(\"Segment \" + segmentId + \": sorting buffer.\");\n long start = System.currentTimeMillis();\n Arrays.sort(buffer, 0, segmentSize, comparator);\n long elapsed = System.currentTimeMillis() - start;\n logger.info(\"Segment \" + segmentId + \": sort completed in \" + elapsed\n + \" ms, writing to temp file.\");\n\n // write out values to a temp file\n try {\n File tempFile = File.createTempFile(\"segment-\", \".dat\", tempDir);\n tempFile.deleteOnExit();\n tempFiles.add(tempFile);\n OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile),\n bufferSize);\n if(gzip)\n os = new GZIPOutputStream(os);\n DataOutputStream output = new DataOutputStream(os);\n for(int i = 0; i < segmentSize; i++)\n writeValue(output, buffer[i]);\n output.close();\n } catch(IOException e) {\n throw new VoldemortException(e);\n }\n long segmentElapsed = System.currentTimeMillis() - segmentStartMs;\n logger.info(\"Segment \" + segmentId + \": completed processing of segment in \"\n + segmentElapsed + \" ms.\");\n }\n });\n }\n\n // wait for all sorting to complete\n executor.shutdown();\n try {\n executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);\n // create iterator over sorted values\n return new DefaultIterable<V>(new ExternalSorterIterator(tempFiles, bufferSize\n / tempFiles.size()));\n } catch(InterruptedException e) {\n throw new RuntimeException(e);\n }\n }", "protected boolean hasContentLength() {\n boolean result = false;\n String contentLength = this.request.getHeader(RestMessageHeaders.CONTENT_LENGTH);\n if(contentLength != null) {\n try {\n Long.parseLong(contentLength);\n result = true;\n } catch(NumberFormatException nfe) {\n logger.error(\"Exception when validating put request. Incorrect content length parameter. Cannot parse this to long: \"\n + contentLength + \". Details: \" + nfe.getMessage(),\n nfe);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Incorrect content length parameter. Cannot parse this to long: \"\n + contentLength + \". Details: \"\n + nfe.getMessage());\n }\n } else {\n logger.error(\"Error when validating put request. Missing Content-Length header.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing Content-Length header\");\n }\n\n return result;\n }", "public void setMeta(String photoId, String title, String description) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_META);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"title\", title);\r\n parameters.put(\"description\", description);\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "private static String getLogManagerLoggerName(final String name) {\n return (name.equals(RESOURCE_NAME) ? CommonAttributes.ROOT_LOGGER_NAME : name);\n }", "public boolean accept(String str) {\r\n int k = str.length() - 1;\r\n char c = str.charAt(k);\r\n while (k >= 0 && !Character.isDigit(c)) {\r\n k--;\r\n if (k >= 0) {\r\n c = str.charAt(k);\r\n }\r\n }\r\n if (k < 0) {\r\n return false;\r\n }\r\n int j = k;\r\n c = str.charAt(j);\r\n while (j >= 0 && Character.isDigit(c)) {\r\n j--;\r\n if (j >= 0) {\r\n c = str.charAt(j);\r\n }\r\n }\r\n j++;\r\n k++;\r\n String theNumber = str.substring(j, k);\r\n int number = Integer.parseInt(theNumber);\r\n for (Pair<Integer,Integer> p : ranges) {\r\n int low = p.first().intValue();\r\n int high = p.second().intValue();\r\n if (number >= low && number <= high) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "public static FilePath createAndGetTempDir(final FilePath ws) throws IOException, InterruptedException {\n // The token that combines the project name and unique number to create unique workspace directory.\n String workspaceList = System.getProperty(\"hudson.slaves.WorkspaceList\");\n return ws.act(new MasterToSlaveCallable<FilePath, IOException>() {\n @Override\n public FilePath call() {\n final FilePath tempDir = ws.sibling(ws.getName() + Objects.toString(workspaceList, \"@\") + \"tmp\").child(\"artifactory\");\n File tempDirFile = new File(tempDir.getRemote());\n tempDirFile.mkdirs();\n tempDirFile.deleteOnExit();\n return tempDir;\n }\n });\n }" ]
Removes 'original' and places 'target' at the same location
[ "public void replace( Token original , Token target ) {\n if( first == original )\n first = target;\n if( last == original )\n last = target;\n\n target.next = original.next;\n target.previous = original.previous;\n\n if( original.next != null )\n original.next.previous = target;\n if( original.previous != null )\n original.previous.next = target;\n\n original.next = original.previous = null;\n }" ]
[ "public void addChildTask(Task child, int childOutlineLevel)\n {\n int outlineLevel = NumberHelper.getInt(getOutlineLevel());\n\n if ((outlineLevel + 1) == childOutlineLevel)\n {\n m_children.add(child);\n setSummary(true);\n }\n else\n {\n if (m_children.isEmpty() == false)\n {\n (m_children.get(m_children.size() - 1)).addChildTask(child, childOutlineLevel);\n }\n }\n }", "public static ResourceResolutionContext context(ResourceResolutionComponent[] components,\n Map<String, Object> messageParams) {\n return new ResourceResolutionContext(components, messageParams);\n }", "public static nslimitidentifier_binding get(nitro_service service, String limitidentifier) throws Exception{\n\t\tnslimitidentifier_binding obj = new nslimitidentifier_binding();\n\t\tobj.set_limitidentifier(limitidentifier);\n\t\tnslimitidentifier_binding response = (nslimitidentifier_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static base_response Force(nitro_service client, clustersync resource) throws Exception {\n\t\tclustersync Forceresource = new clustersync();\n\t\treturn Forceresource.perform_operation(client,\"Force\");\n\t}", "public static AnalysisResult fakeSuccess() {\n return new AnalysisResult(null, new Extensions(Collections.emptyMap(), Collections.emptyMap(),\n Collections.emptyMap(), Collections.emptyMap()));\n }", "private String getTypeString(Class<?> c)\n {\n String result = TYPE_MAP.get(c);\n if (result == null)\n {\n result = c.getName();\n if (!result.endsWith(\";\") && !result.startsWith(\"[\"))\n {\n result = \"L\" + result + \";\";\n }\n }\n return result;\n }", "static InjectionProvider<?>[] toArray(final Set<InjectionProvider<?>> injectionProviders) {\n return injectionProviders.toArray(new InjectionProvider<?>[injectionProviders.size()]);\n }", "public static BoxStoragePolicyAssignment.Info create(BoxAPIConnection api, String policyID, String userID) {\n URL url = STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST);\n JsonObject requestJSON = new JsonObject()\n .add(\"storage_policy\", new JsonObject()\n .add(\"type\", \"storage_policy\")\n .add(\"id\", policyID))\n .add(\"assigned_to\", new JsonObject()\n .add(\"type\", \"user\")\n .add(\"id\", userID));\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment(api,\n responseJSON.get(\"id\").asString());\n\n return storagePolicyAssignment.new Info(responseJSON);\n }", "public static double elementSumSq( DMatrixD1 m ) {\n\n // minimize round off error\n double maxAbs = CommonOps_DDRM.elementMaxAbs(m);\n if( maxAbs == 0)\n return 0;\n\n double total = 0;\n \n int N = m.getNumElements();\n for( int i = 0; i < N; i++ ) {\n double d = m.data[i]/maxAbs;\n total += d*d;\n }\n\n return maxAbs*total*maxAbs;\n }" ]
Set the value for a floating point vector of length 4. @param key name of uniform to set. @param x new X value @param y new Y value @param z new Z value @param w new W value @see #getVec4 @see #getFloatVec(String)
[ "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 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 BoxFile.Info restoreFile(String fileID) {\n URL url = RESTORE_FILE_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"\", \"\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFile restoredFile = new BoxFile(this.api, responseJSON.get(\"id\").asString());\n return restoredFile.new Info(responseJSON);\n }", "public int getIndexFromOffset(int offset)\n {\n int result = -1;\n\n for (int loop = 0; loop < m_offset.length; loop++)\n {\n if (m_offset[loop] == offset)\n {\n result = loop;\n break;\n }\n }\n\n return (result);\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 }", "static void checkUpgradeConditions(final UpgradeCondition condition, final InstallationManager.MutablePatchingTarget target) throws PatchingException {\n // See if the prerequisites are met\n for (final String required : condition.getRequires()) {\n if (!target.isApplied(required)) {\n throw PatchLogger.ROOT_LOGGER.requiresPatch(required);\n }\n }\n // Check for incompatibilities\n for (final String incompatible : condition.getIncompatibleWith()) {\n if (target.isApplied(incompatible)) {\n throw PatchLogger.ROOT_LOGGER.incompatiblePatch(incompatible);\n }\n }\n }", "public double stdev() {\n double m = mean();\n\n double total = 0;\n\n final int N = getNumElements();\n if( N <= 1 )\n throw new IllegalArgumentException(\"There must be more than one element to compute stdev\");\n\n\n for( int i = 0; i < N; i++ ) {\n double x = get(i);\n\n total += (x - m)*(x - m);\n }\n\n total /= (N-1);\n\n return Math.sqrt(total);\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}", "private void processKeyValue(Map<ConfigurationKey, Object> properties, ConfigurationKey key, Object value) {\n if (value instanceof String) {\n value = key.convertValue((String) value);\n }\n if (key.isValidValue(value)) {\n Object previous = properties.put(key, value);\n if (previous != null && !previous.equals(value)) {\n throw ConfigurationLogger.LOG.configurationKeyHasDifferentValues(key.get(), previous, value);\n }\n } else {\n throw ConfigurationLogger.LOG.invalidConfigurationPropertyValue(value, key.get());\n }\n }", "protected float getSizeArcLength(float angle) {\n if (mRadius <= 0) {\n throw new IllegalArgumentException(\"mRadius is not specified!\");\n }\n return angle == Float.MAX_VALUE ? Float.MAX_VALUE :\n LayoutHelpers.lengthOfArc(angle, mRadius);\n }" ]
Given a class configures the binding between a class and a Renderer class. @param clazz to bind. @param prototype used as Renderer. @return the current RendererBuilder instance.
[ "public <G extends T> RendererBuilder<T> bind(Class<G> clazz, Renderer<? extends G> prototype) {\n if (clazz == null || prototype == null) {\n throw new IllegalArgumentException(\n \"The binding RecyclerView binding can't be configured using null instances\");\n }\n prototypes.add(prototype);\n binding.put(clazz, prototype.getClass());\n return this;\n }" ]
[ "public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException {\n final List<Method> methods = new ArrayList<Method>(32);\n doWithMethods(leafClass, new MethodCallback() {\n @Override\n public void doWith(Method method) {\n boolean knownSignature = false;\n Method methodBeingOverriddenWithCovariantReturnType = null;\n for (Method existingMethod : methods) {\n if (method.getName().equals(existingMethod.getName()) &&\n Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {\n // Is this a covariant return type situation?\n if (existingMethod.getReturnType() != method.getReturnType() &&\n existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {\n methodBeingOverriddenWithCovariantReturnType = existingMethod;\n } else {\n knownSignature = true;\n }\n break;\n }\n }\n if (methodBeingOverriddenWithCovariantReturnType != null) {\n methods.remove(methodBeingOverriddenWithCovariantReturnType);\n }\n if (!knownSignature) {\n methods.add(method);\n }\n }\n });\n return methods.toArray(new Method[methods.size()]);\n }", "private boolean isAcceptingNewJobs() {\n if (this.requestedToStop) {\n return false;\n } else if (new File(this.workingDirectories.getWorking(), \"stop\").exists()) {\n LOGGER.info(\"The print has been requested to stop\");\n this.requestedToStop = true;\n notifyIfStopped();\n return false;\n } else {\n return true;\n }\n }", "public <T> T getNodeMetaData(Object key) {\n if (metaDataMap == null) {\n return (T) null;\n }\n return (T) metaDataMap.get(key);\n }", "@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tprivate IntegrationFlowBuilder getFlowBuilder() {\n\n\t\tIntegrationFlowBuilder flowBuilder;\n\t\tURLName urlName = this.properties.getUrl();\n\n\t\tif (this.properties.isIdleImap()) {\n\t\t\tflowBuilder = getIdleImapFlow(urlName);\n\t\t}\n\t\telse {\n\n\t\t\tMailInboundChannelAdapterSpec adapterSpec;\n\t\t\tswitch (urlName.getProtocol().toUpperCase()) {\n\t\t\t\tcase \"IMAP\":\n\t\t\t\tcase \"IMAPS\":\n\t\t\t\t\tadapterSpec = getImapFlowBuilder(urlName);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"POP3\":\n\t\t\t\tcase \"POP3S\":\n\t\t\t\t\tadapterSpec = getPop3FlowBuilder(urlName);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\t\"Unsupported mail protocol: \" + urlName.getProtocol());\n\t\t\t}\n\t\t\tflowBuilder = IntegrationFlows.from(\n\t\t\t\t\tadapterSpec.javaMailProperties(getJavaMailProperties(urlName))\n\t\t\t\t\t\t\t.selectorExpression(this.properties.getExpression())\n\t\t\t\t\t\t\t.shouldDeleteMessages(this.properties.isDelete()),\n\t\t\t\t\tnew Consumer<SourcePollingChannelAdapterSpec>() {\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void accept(\n\t\t\t\t\t\t\t\tSourcePollingChannelAdapterSpec sourcePollingChannelAdapterSpec) {\n\t\t\t\t\t\t\tsourcePollingChannelAdapterSpec.poller(MailSourceConfiguration.this.defaultPoller);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t});\n\n\t\t}\n\t\treturn flowBuilder;\n\t}", "protected Element createPageElement()\n {\n String pstyle = \"\";\n PDRectangle layout = getCurrentMediaBox();\n if (layout != null)\n {\n /*System.out.println(\"x1 \" + layout.getLowerLeftX());\n System.out.println(\"y1 \" + layout.getLowerLeftY());\n System.out.println(\"x2 \" + layout.getUpperRightX());\n System.out.println(\"y2 \" + layout.getUpperRightY());\n System.out.println(\"rot \" + pdpage.findRotation());*/\n \n float w = layout.getWidth();\n float h = layout.getHeight();\n final int rot = pdpage.getRotation();\n if (rot == 90 || rot == 270)\n {\n float x = w; w = h; h = x;\n }\n \n pstyle = \"width:\" + w + UNIT + \";\" + \"height:\" + h + UNIT + \";\";\n pstyle += \"overflow:hidden;\";\n }\n else\n log.warn(\"No media box found\");\n \n Element el = doc.createElement(\"div\");\n el.setAttribute(\"id\", \"page_\" + (pagecnt++));\n el.setAttribute(\"class\", \"page\");\n el.setAttribute(\"style\", pstyle);\n return el;\n }", "protected void maybeSignalForMoreConnections(ConnectionPartition connectionPartition) {\r\n\r\n\t\tif (!connectionPartition.isUnableToCreateMoreTransactions() \r\n\t\t\t\t&& !this.poolShuttingDown &&\r\n\t\t\t\tconnectionPartition.getAvailableConnections()*100/connectionPartition.getMaxConnections() <= this.poolAvailabilityThreshold){\r\n\t\t\tconnectionPartition.getPoolWatchThreadSignalQueue().offer(new Object()); // item being pushed is not important.\r\n\t\t}\r\n\t}", "@TargetApi(VERSION_CODES.KITKAT)\n public static void hideSystemUI(Activity activity) {\n // Set the IMMERSIVE flag.\n // Set the content to appear under the system bars so that the content\n // doesn't resize when the system bars hideSelf and show.\n View decorView = activity.getWindow().getDecorView();\n decorView.setSystemUiVisibility(\n View.SYSTEM_UI_FLAG_LAYOUT_STABLE\n | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION\n | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN\n | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hideSelf nav bar\n | View.SYSTEM_UI_FLAG_FULLSCREEN // hideSelf status bar\n | View.SYSTEM_UI_FLAG_IMMERSIVE\n );\n }", "private Map<String, ColumnDefinition> makeColumnMap(ColumnDefinition[] columns)\n {\n Map<String, ColumnDefinition> map = new HashMap<String, ColumnDefinition>();\n for (ColumnDefinition def : columns)\n {\n map.put(def.getName(), def);\n }\n return map;\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}" ]
Invoke the operation. @param parameterMap the {@link Map} of parameter names to value arrays. @return the {@link Object} return value from the operation. @throws JMException Java Management Exception
[ "public Object invokeOperation(Map<String, String[]> parameterMap) throws JMException {\n MBeanParameterInfo[] parameterInfoArray = operationInfo.getSignature();\n\n Object[] values = new Object[parameterInfoArray.length];\n String[] types = new String[parameterInfoArray.length];\n\n MBeanValueConverter valueConverter = createMBeanValueConverter(parameterMap);\n\n for (int parameterNum = 0; parameterNum < parameterInfoArray.length; parameterNum++) {\n MBeanParameterInfo parameterInfo = parameterInfoArray[parameterNum];\n String type = parameterInfo.getType();\n types[parameterNum] = type;\n values[parameterNum] = valueConverter.convertParameterValue(parameterInfo.getName(), type);\n }\n\n return mBeanServer.invoke(objectName, operationInfo.getName(), values, types);\n }" ]
[ "protected TypeReference<?> getBeanPropertyType(Class<?> clazz,\r\n\t\t\tString propertyName, TypeReference<?> originalType) {\r\n\t\tTypeReference<?> propertyDestinationType = null;\r\n\t\tif (beanDestinationPropertyTypeProvider != null) {\r\n\t\t\tpropertyDestinationType = beanDestinationPropertyTypeProvider\r\n\t\t\t\t\t.getPropertyType(clazz, propertyName, originalType);\r\n\t\t}\r\n\t\tif (propertyDestinationType == null) {\r\n\t\t\tpropertyDestinationType = originalType;\r\n\t\t}\r\n\t\treturn propertyDestinationType;\r\n\t}", "protected Connection newConnectionFromDriverManager(JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n Connection retval = null;\r\n // use JDBC DriverManager\r\n final String driver = jcd.getDriver();\r\n final String url = getDbURL(jcd);\r\n try\r\n {\r\n // loads the driver - NB call to newInstance() added to force initialisation\r\n ClassHelper.getClass(driver, true);\r\n final String user = jcd.getUserName();\r\n final String password = jcd.getPassWord();\r\n final Properties properties = getJdbcProperties(jcd, user, password);\r\n if (properties.isEmpty())\r\n {\r\n if (user == null)\r\n {\r\n retval = DriverManager.getConnection(url);\r\n }\r\n else\r\n {\r\n retval = DriverManager.getConnection(url, user, password);\r\n }\r\n }\r\n else\r\n {\r\n retval = DriverManager.getConnection(url, properties);\r\n }\r\n }\r\n catch (SQLException sqlEx)\r\n {\r\n log.error(\"Error getting Connection from DriverManager with url (\" + url + \") and driver (\" + driver + \")\", sqlEx);\r\n throw new LookupException(\"Error getting Connection from DriverManager with url (\" + url + \") and driver (\" + driver + \")\", sqlEx);\r\n }\r\n catch (ClassNotFoundException cnfEx)\r\n {\r\n log.error(cnfEx);\r\n throw new LookupException(\"A class was not found\", cnfEx);\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Instantiation of jdbc driver failed\", e);\r\n throw new LookupException(\"Instantiation of jdbc driver failed\", e);\r\n }\r\n // initialize connection\r\n initializeJdbcConnection(retval, jcd);\r\n if(log.isDebugEnabled()) log.debug(\"Create new connection using DriverManager: \"+retval);\r\n return retval;\r\n }", "public PayloadBuilder resizeAlertBody(final int payloadLength, final String postfix) {\n int currLength = length();\n if (currLength <= payloadLength) {\n return this;\n }\n\n // now we are sure that truncation is required\n String body = (String)customAlert.get(\"body\");\n\n final int acceptableSize = Utilities.toUTF8Bytes(body).length\n - (currLength - payloadLength\n + Utilities.toUTF8Bytes(postfix).length);\n body = Utilities.truncateWhenUTF8(body, acceptableSize) + postfix;\n\n // set it back\n customAlert.put(\"body\", body);\n\n // calculate the length again\n currLength = length();\n\n if(currLength > payloadLength) {\n // string is still too long, just remove the body as the body is\n // anyway not the cause OR the postfix might be too long\n customAlert.remove(\"body\");\n }\n\n return this;\n }", "public boolean clearParameters() {\n this.query = null;\n this.fields = null;\n this.scope = null;\n this.fileExtensions = null;\n this.createdRange = null;\n this.updatedRange = null;\n this.sizeRange = null;\n this.ownerUserIds = null;\n this.ancestorFolderIds = null;\n this.contentTypes = null;\n this.type = null;\n this.trashContent = null;\n this.metadataFilter = null;\n this.sort = null;\n this.direction = null;\n return true;\n }", "protected void init(String configString, I_CmsSearchConfiguration baseConfig) throws JSONException {\n\n m_configObject = new JSONObject(configString);\n m_baseConfig = baseConfig;\n }", "Map<String, String> packageNameMap() {\n if (packageNames == null) {\n return emptyMap();\n }\n\n Map<String, String> names = new LinkedHashMap<String, String>();\n for (PackageName name : packageNames) {\n names.put(name.getUri(), name.getPackage());\n }\n return names;\n }", "public static csvserver_cmppolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cmppolicy_binding obj = new csvserver_cmppolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cmppolicy_binding response[] = (csvserver_cmppolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void printRelations(ClassDoc c) {\n\tOptions opt = optionProvider.getOptionsFor(c);\n\tif (hidden(c) || c.name().equals(\"\")) // avoid phantom classes, they may pop up when the source uses annotations\n\t return;\n\t// Print generalization (through the Java superclass)\n\tType s = c.superclassType();\n\tClassDoc sc = s != null && !s.qualifiedTypeName().equals(Object.class.getName()) ? s.asClassDoc() : null;\n\tif (sc != null && !c.isEnum() && !hidden(sc))\n\t relation(opt, RelationType.EXTENDS, c, sc, null, null, null);\n\t// Print generalizations (through @extends tags)\n\tfor (Tag tag : c.tags(\"extends\"))\n\t if (!hidden(tag.text()))\n\t\trelation(opt, RelationType.EXTENDS, c, c.findClass(tag.text()), null, null, null);\n\t// Print realizations (Java interfaces)\n\tfor (Type iface : c.interfaceTypes()) {\n\t ClassDoc ic = iface.asClassDoc();\n\t if (!hidden(ic))\n\t\trelation(opt, RelationType.IMPLEMENTS, c, ic, null, null, null);\n\t}\n\t// Print other associations\n\tallRelation(opt, RelationType.COMPOSED, c);\n\tallRelation(opt, RelationType.NAVCOMPOSED, c);\n\tallRelation(opt, RelationType.HAS, c);\n\tallRelation(opt, RelationType.NAVHAS, c);\n\tallRelation(opt, RelationType.ASSOC, c);\n\tallRelation(opt, RelationType.NAVASSOC, c);\n\tallRelation(opt, RelationType.DEPEND, c);\n }", "protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading columns for table \" + getSchema().getCatalog().getCatalogName() + \".\" + getSchema().getSchemaName() + \".\" + getTableName());\r\n rs = getDbMeta().getColumns(getSchema().getCatalog().getCatalogName(), \r\n getSchema().getSchemaName(),\r\n getTableName(), \"%\");\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n while (rs.next())\r\n {\r\n alNew.add(new DBMetaColumnNode(getDbMeta(), getDbMetaTreeModel(), DBMetaTableNode.this, rs.getString(\"COLUMN_NAME\")));\r\n }\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaTableNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx2);\r\n }\r\n return false;\r\n }\r\n return true;\r\n }" ]
Returns the configured extra parameters that should be given to Solr, or the empty string if no parameters are configured. @return The configured extra parameters that should be given to Solr, or the empty string if no parameters are configured.
[ "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 }" ]
[ "protected void addLineContent(BufferedReader bufferedFileReader, List<String> content, String line) throws IOException {\n content.add(line);\n }", "@Deprecated\n @SuppressWarnings(\"deprecation\")\n protected void registerAddOperation(final ManagementResourceRegistration registration, final OperationStepHandler handler, OperationEntry.Flag... flags) {\n if (handler instanceof DescriptionProvider) {\n registration.registerOperationHandler(getOperationDefinition(ModelDescriptionConstants.ADD,\n (DescriptionProvider) handler, OperationEntry.EntryType.PUBLIC,flags)\n , handler);\n\n } else {\n registration.registerOperationHandler(getOperationDefinition(ModelDescriptionConstants.ADD,\n new DefaultResourceAddDescriptionProvider(registration, descriptionResolver, orderedChild),\n OperationEntry.EntryType.PUBLIC,\n flags)\n , handler);\n }\n }", "public static base_response reset(nitro_service client, Interface resource) throws Exception {\n\t\tInterface resetresource = new Interface();\n\t\tresetresource.id = resource.id;\n\t\treturn resetresource.perform_operation(client,\"reset\");\n\t}", "private void extractFile(InputStream stream, File dir) throws IOException\n {\n byte[] header = new byte[8];\n byte[] fileName = new byte[13];\n byte[] dataSize = new byte[4];\n\n stream.read(header);\n stream.read(fileName);\n stream.read(dataSize);\n\n int dataSizeValue = getInt(dataSize, 0);\n String fileNameValue = getString(fileName, 0);\n File file = new File(dir, fileNameValue);\n\n if (dataSizeValue == 0)\n {\n FileHelper.createNewFile(file);\n }\n else\n {\n OutputStream os = new FileOutputStream(file);\n FixedLengthInputStream inputStream = new FixedLengthInputStream(stream, dataSizeValue);\n Blast blast = new Blast();\n blast.blast(inputStream, os);\n os.close();\n }\n }", "public void clearTmpData() {\n\t\tfor (Enumeration<?> e = breadthFirstEnumeration(); e.hasMoreElements(); ) {\n\t\t\t((LblTree) e.nextElement()).setTmpData(null);\n\t\t}\n\t}", "public int[] getTenors(int moneynessBP, int maturityInMonths) {\r\n\r\n\t\ttry {\r\n\t\t\tList<Integer> ret = new ArrayList<>();\r\n\t\t\tfor(int tenor : getGridNodesPerMoneyness().get(moneynessBP)[1]) {\r\n\t\t\t\tif(containsEntryFor(maturityInMonths, tenor, moneynessBP)) {\r\n\t\t\t\t\tret.add(tenor);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn ret.stream().mapToInt(Integer::intValue).toArray();\r\n\t\t} catch (NullPointerException e) {\r\n\t\t\treturn new int[0];\r\n\t\t}\r\n\t}", "private String generatedBuilderSimpleName(TypeElement type) {\n String packageName = elements.getPackageOf(type).getQualifiedName().toString();\n String originalName = type.getQualifiedName().toString();\n checkState(originalName.startsWith(packageName + \".\"));\n String nameWithoutPackage = originalName.substring(packageName.length() + 1);\n return String.format(BUILDER_SIMPLE_NAME_TEMPLATE, nameWithoutPackage.replaceAll(\"\\\\.\", \"_\"));\n }", "private void readAssignment(Resource resource, Assignment assignment)\n {\n Task task = m_activityMap.get(assignment.getActivity());\n if (task != null)\n {\n task.addResourceAssignment(resource);\n }\n }", "public Iterable<BoxMetadataCascadePolicy.Info> getMetadataCascadePolicies(String... fields) {\n Iterable<BoxMetadataCascadePolicy.Info> cascadePoliciesInfo =\n BoxMetadataCascadePolicy.getAll(this.getAPI(), this.getID(), fields);\n\n return cascadePoliciesInfo;\n }" ]
Add the buildInfo to step variables if missing and set its cps script. @param cpsScript the cps script @param stepVariables step variables map @return the build info
[ "public static BuildInfo appendBuildInfo(CpsScript cpsScript, Map<String, Object> stepVariables) {\n BuildInfo buildInfo = (BuildInfo) stepVariables.get(BUILD_INFO);\n if (buildInfo == null) {\n buildInfo = (BuildInfo) cpsScript.invokeMethod(\"newBuildInfo\", Maps.newLinkedHashMap());\n stepVariables.put(BUILD_INFO, buildInfo);\n }\n buildInfo.setCpsScript(cpsScript);\n return buildInfo;\n }" ]
[ "@Override\n public Response doRequest(final StitchRequest stitchReq) {\n initAppMetadata(clientAppId);\n\n return super.doRequestUrl(stitchReq, getHostname());\n }", "public void logAttributeWarning(PathAddress address, String message, String attribute) {\n logAttributeWarning(address, null, message, attribute);\n }", "public void processTasks(List<Row> bars, List<Row> expandedTasks, List<Row> tasks, List<Row> milestones)\n {\n List<Row> parentBars = buildRowHierarchy(bars, expandedTasks, tasks, milestones);\n createTasks(m_project, \"\", parentBars);\n deriveProjectCalendar();\n updateStructure();\n }", "public static Shell createConsoleShell(String prompt, String appName, Object... handlers) {\n ConsoleIO io = new ConsoleIO();\n\n List<String> path = new ArrayList<String>(1);\n path.add(prompt);\n\n MultiMap<String, Object> modifAuxHandlers = new ArrayHashMultiMap<String, Object>();\n modifAuxHandlers.put(\"!\", io);\n\n Shell theShell = new Shell(new Shell.Settings(io, io, modifAuxHandlers, false),\n new CommandTable(new DashJoinedNamer(true)), path);\n theShell.setAppName(appName);\n\n theShell.addMainHandler(theShell, \"!\");\n theShell.addMainHandler(new HelpCommandHandler(), \"?\");\n for (Object h : handlers) {\n theShell.addMainHandler(h, \"\");\n }\n\n return theShell;\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 String copyToString(InputStream in, Charset charset) throws IOException {\n\t\tAssert.notNull(in, \"No InputStream specified\");\n\t\tStringBuilder out = new StringBuilder();\n\t\tInputStreamReader reader = new InputStreamReader(in, charset);\n\t\tchar[] buffer = new char[BUFFER_SIZE];\n\t\tint bytesRead = -1;\n\t\twhile ((bytesRead = reader.read(buffer)) != -1) {\n\t\t\tout.append(buffer, 0, bytesRead);\n\t\t}\n\t\treturn out.toString();\n\t}", "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 QueryBuilder<T, ID> join(QueryBuilder<?, ?> joinedQueryBuilder) throws SQLException {\n\t\taddJoinInfo(JoinType.INNER, null, null, joinedQueryBuilder, JoinWhereOperation.AND);\n\t\treturn this;\n\t}", "public static final CurrencySymbolPosition parseCurrencySymbolPosition(String value)\n {\n CurrencySymbolPosition result = MAP_TO_CURRENCY_SYMBOL_POSITION.get(value);\n result = result == null ? CurrencySymbolPosition.BEFORE_WITH_SPACE : result;\n return result;\n }" ]
Notification that boot has completed successfully and the configuration history should be updated
[ "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 }" ]
[ "public static lbmonitor_binding get(nitro_service service, String monitorname) throws Exception{\n\t\tlbmonitor_binding obj = new lbmonitor_binding();\n\t\tobj.set_monitorname(monitorname);\n\t\tlbmonitor_binding response = (lbmonitor_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static appfwpolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_binding obj = new appfwpolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_binding response = (appfwpolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "@Api\n\tpublic static void configureNoCaching(HttpServletResponse response) {\n\t\t// HTTP 1.0 header:\n\t\tresponse.setHeader(HTTP_EXPIRES_HEADER, HTTP_EXPIRES_HEADER_NOCACHE_VALUE);\n\t\tresponse.setHeader(HTTP_CACHE_PRAGMA, HTTP_CACHE_PRAGMA_VALUE);\n\n\t\t// HTTP 1.1 header:\n\t\tresponse.setHeader(HTTP_CACHE_CONTROL_HEADER, HTTP_CACHE_CONTROL_HEADER_NOCACHE_VALUE);\n\t}", "@Override\r\n public synchronized long skip(final long length) throws IOException {\r\n final long skip = super.skip(length);\r\n this.count += skip;\r\n return skip;\r\n }", "public E get(int i) {\r\n if (i < 0 || i >= objects.size())\r\n throw new ArrayIndexOutOfBoundsException(\"Index \" + i + \r\n \" outside the bounds [0,\" + \r\n size() + \")\");\r\n return objects.get(i);\r\n }", "public static String getPrefix(String column) {\n\t\treturn column.contains( \".\" ) ? DOT_SEPARATOR_PATTERN.split( column )[0] : null;\n\t}", "public int getChunkForKey(byte[] key) throws IllegalStateException {\n if(numChunks == 0) {\n throw new IllegalStateException(\"The ChunkedFileSet is closed.\");\n }\n\n switch(storageFormat) {\n case READONLY_V0: {\n return ReadOnlyUtils.chunk(ByteUtils.md5(key), numChunks);\n }\n case READONLY_V1: {\n if(nodePartitionIds == null) {\n throw new IllegalStateException(\"nodePartitionIds is null.\");\n }\n List<Integer> routingPartitionList = routingStrategy.getPartitionList(key);\n routingPartitionList.retainAll(nodePartitionIds);\n\n if(routingPartitionList.size() != 1) {\n throw new IllegalStateException(\"The key does not belong on this node.\");\n }\n\n return chunkIdToChunkStart.get(routingPartitionList.get(0))\n + ReadOnlyUtils.chunk(ByteUtils.md5(key),\n chunkIdToNumChunks.get(routingPartitionList.get(0)));\n }\n case READONLY_V2: {\n List<Integer> routingPartitionList = routingStrategy.getPartitionList(key);\n\n Pair<Integer, Integer> bucket = null;\n for(int replicaType = 0; replicaType < routingPartitionList.size(); replicaType++) {\n if(nodePartitionIds == null) {\n throw new IllegalStateException(\"nodePartitionIds is null.\");\n }\n if(nodePartitionIds.contains(routingPartitionList.get(replicaType))) {\n if(bucket == null) {\n bucket = Pair.create(routingPartitionList.get(0), replicaType);\n } else {\n throw new IllegalStateException(\"Found more than one replica for a given partition on the current node!\");\n }\n }\n }\n\n if(bucket == null) {\n throw new IllegalStateException(\"The key does not belong on this node.\");\n }\n\n Integer chunkStart = chunkIdToChunkStart.get(bucket);\n\n if (chunkStart == null) {\n throw new IllegalStateException(\"chunkStart is null.\");\n }\n\n return chunkStart + ReadOnlyUtils.chunk(ByteUtils.md5(key), chunkIdToNumChunks.get(bucket));\n }\n default: {\n throw new IllegalStateException(\"Unsupported storageFormat: \" + storageFormat);\n }\n }\n\n }", "public static <T> void addAll(Collection<T> collection, Iterable<? extends T> items) {\r\n for (T item : items) {\r\n collection.add(item);\r\n }\r\n }", "public ProductFactoryCascade<T> addFactoryBefore(ProductFactory<? extends T> factory) {\n\t\tArrayList<ProductFactory<? extends T>> factories = new ArrayList<ProductFactory<? extends T>>(this.factories.size()+1);\n\t\tfactories.addAll(this.factories);\n\t\tfactories.add(0, factory);\n\t\treturn new ProductFactoryCascade<>(factories);\n\t}" ]
This method extracts data for a normal working day from an MSPDI file. @param calendar Calendar data @param weekDay Day data
[ "private void readNormalDay(ProjectCalendar calendar, Project.Calendars.Calendar.WeekDays.WeekDay weekDay)\n {\n int dayNumber = weekDay.getDayType().intValue();\n Day day = Day.getInstance(dayNumber);\n calendar.setWorkingDay(day, BooleanHelper.getBoolean(weekDay.isDayWorking()));\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = weekDay.getWorkingTimes();\n if (times != null)\n {\n for (Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime period : times.getWorkingTime())\n {\n Date startTime = period.getFromTime();\n Date endTime = period.getToTime();\n\n if (startTime != null && endTime != null)\n {\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n hours.addRange(new DateRange(startTime, endTime));\n }\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 static base_response delete(nitro_service client, String selectorname) throws Exception {\n\t\tcacheselector deleteresource = new cacheselector();\n\t\tdeleteresource.selectorname = selectorname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static long count(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_crldistribution_binding obj = new sslcertkey_crldistribution_binding();\n\t\tobj.set_certkey(certkey);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tsslcertkey_crldistribution_binding response[] = (sslcertkey_crldistribution_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}", "public static String toSafeFileName(String name) {\n int size = name.length();\n StringBuilder builder = new StringBuilder(size * 2);\n for (int i = 0; i < size; i++) {\n char c = name.charAt(i);\n boolean valid = c >= 'a' && c <= 'z';\n valid = valid || (c >= 'A' && c <= 'Z');\n valid = valid || (c >= '0' && c <= '9');\n valid = valid || (c == '_') || (c == '-') || (c == '.');\n\n if (valid) {\n builder.append(c);\n } else {\n // Encode the character using hex notation\n builder.append('x');\n builder.append(Integer.toHexString(i));\n }\n }\n return builder.toString();\n }", "public static Class<?> resolvePrimitiveIfNecessary(Class<?> clazz) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\treturn (clazz.isPrimitive() && clazz != void.class? primitiveTypeToWrapperMap.get(clazz) : clazz);\n\t}", "public static CentralDogma forConfig(File configFile) throws IOException {\n requireNonNull(configFile, \"configFile\");\n return new CentralDogma(Jackson.readValue(configFile, CentralDogmaConfig.class));\n }", "private boolean operations(Options opt, MethodDoc m[]) {\n\tboolean printed = false;\n\tfor (MethodDoc md : m) {\n\t if (hidden(md))\n\t\tcontinue;\n\t // Filter-out static initializer method\n\t if (md.name().equals(\"<clinit>\") && md.isStatic() && md.isPackagePrivate())\n\t\tcontinue;\n\t stereotype(opt, md, Align.LEFT);\n\t String op = visibility(opt, md) + md.name() + //\n\t\t (opt.showType ? \"(\" + parameter(opt, md.parameters()) + \")\" + typeAnnotation(opt, md.returnType())\n\t\t\t : \"()\");\n\t tableLine(Align.LEFT, (md.isAbstract() ? Font.ABSTRACT : Font.NORMAL).wrap(opt, op));\n\t printed = true;\n\n\t tagvalue(opt, md);\n\t}\n\treturn printed;\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 }", "public double response( double[] sample ) {\n if( sample.length != A.numCols )\n throw new IllegalArgumentException(\"Expected input vector to be in sample space\");\n\n DMatrixRMaj dots = new DMatrixRMaj(numComponents,1);\n DMatrixRMaj s = DMatrixRMaj.wrap(A.numCols,1,sample);\n\n CommonOps_DDRM.mult(V_t,s,dots);\n\n return NormOps_DDRM.normF(dots);\n }" ]
This method merges together assignment data for the same cost. @param list assignment data
[ "protected void mergeSameCost(LinkedList<TimephasedCost> list)\n {\n LinkedList<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n TimephasedCost previousAssignment = null;\n for (TimephasedCost assignment : list)\n {\n if (previousAssignment == null)\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n result.add(assignment);\n }\n else\n {\n Number previousAssignmentCost = previousAssignment.getAmountPerDay();\n Number assignmentCost = assignment.getTotalAmount();\n\n if (NumberHelper.equals(previousAssignmentCost.doubleValue(), assignmentCost.doubleValue(), 0.01))\n {\n Date assignmentStart = previousAssignment.getStart();\n Date assignmentFinish = assignment.getFinish();\n double total = previousAssignment.getTotalAmount().doubleValue();\n total += assignmentCost.doubleValue();\n\n TimephasedCost merged = new TimephasedCost();\n merged.setStart(assignmentStart);\n merged.setFinish(assignmentFinish);\n merged.setAmountPerDay(assignmentCost);\n merged.setTotalAmount(Double.valueOf(total));\n\n result.removeLast();\n assignment = merged;\n }\n else\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n }\n result.add(assignment);\n }\n\n previousAssignment = assignment;\n }\n\n list.clear();\n list.addAll(result);\n }" ]
[ "public static policydataset get(nitro_service service, String name) throws Exception{\n\t\tpolicydataset obj = new policydataset();\n\t\tobj.set_name(name);\n\t\tpolicydataset response = (policydataset) obj.get_resource(service);\n\t\treturn response;\n\t}", "public ItemRequest<Project> delete(String project) {\n \n String path = String.format(\"/projects/%s\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"DELETE\");\n }", "public Collection<Tag> getListUser(String userId) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_LIST_USER);\n\n parameters.put(\"user_id\", userId);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element whoElement = response.getPayload();\n\n List<Tag> tags = new ArrayList<Tag>();\n Element tagsElement = (Element) whoElement.getElementsByTagName(\"tags\").item(0);\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag tag = new Tag();\n tag.setValue(((Text) tagElement.getFirstChild()).getData());\n tags.add(tag);\n }\n return tags;\n }", "private void processKnownType(FieldType type)\n {\n //System.out.println(\"Header: \" + type);\n //System.out.println(ByteArrayHelper.hexdump(m_data, m_dataOffset, 36, false, 16, \"\"));\n\n GraphicalIndicator indicator = m_container.getCustomField(type).getGraphicalIndicator();\n indicator.setFieldType(type);\n int flags = m_data[m_dataOffset];\n indicator.setProjectSummaryInheritsFromSummaryRows((flags & 0x08) != 0);\n indicator.setSummaryRowsInheritFromNonSummaryRows((flags & 0x04) != 0);\n indicator.setDisplayGraphicalIndicators((flags & 0x02) != 0);\n indicator.setShowDataValuesInToolTips((flags & 0x01) != 0);\n m_dataOffset += 20;\n\n int nonSummaryRowOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int summaryRowOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int projectSummaryOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int dataSize = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n //System.out.println(\"Data\");\n //System.out.println(ByteArrayHelper.hexdump(m_data, m_dataOffset, dataSize, false, 16, \"\"));\n\n int maxNonSummaryRowOffset = m_dataOffset + summaryRowOffset;\n int maxSummaryRowOffset = m_dataOffset + projectSummaryOffset;\n int maxProjectSummaryOffset = m_dataOffset + dataSize;\n\n m_dataOffset += nonSummaryRowOffset;\n\n while (m_dataOffset + 2 < maxNonSummaryRowOffset)\n {\n indicator.addNonSummaryRowCriteria(processCriteria(type));\n }\n\n while (m_dataOffset + 2 < maxSummaryRowOffset)\n {\n indicator.addSummaryRowCriteria(processCriteria(type));\n }\n\n while (m_dataOffset + 2 < maxProjectSummaryOffset)\n {\n indicator.addProjectSummaryCriteria(processCriteria(type));\n }\n }", "public synchronized void removeControlPoint(ControlPoint controlPoint) {\n if (controlPoint.decreaseReferenceCount() == 0) {\n ControlPointIdentifier id = new ControlPointIdentifier(controlPoint.getDeployment(), controlPoint.getEntryPoint());\n entryPoints.remove(id);\n }\n }", "public ItemRequest<Team> addUser(String team) {\n \n String path = String.format(\"/teams/%s/addUser\", team);\n return new ItemRequest<Team>(this, Team.class, path, \"POST\");\n }", "private static void writeCharSequence(CharSequence seq, CharBuf buffer) {\n if (seq.length() > 0) {\n buffer.addJsonEscapedString(seq.toString());\n } else {\n buffer.addChars(EMPTY_STRING_CHARS);\n }\n }", "private void setNsid() throws FlickrException {\n\n if (username != null && !username.equals(\"\")) {\n Auth auth = null;\n if (authStore != null) {\n auth = authStore.retrieve(username); // assuming FileAuthStore is enhanced else need to\n // keep in user-level files.\n\n if (auth != null) {\n nsid = auth.getUser().getId();\n }\n }\n if (auth != null)\n return;\n\n Auth[] allAuths = authStore.retrieveAll();\n for (int i = 0; i < allAuths.length; i++) {\n if (username.equals(allAuths[i].getUser().getUsername())) {\n nsid = allAuths[i].getUser().getId();\n return;\n }\n }\n\n // For this to work: REST.java or PeopleInterface needs to change to pass apiKey\n // as the parameter to the call which is not authenticated.\n\n // Get nsid using flickr.people.findByUsername\n PeopleInterface peopleInterf = flickr.getPeopleInterface();\n User u = peopleInterf.findByUsername(username);\n if (u != null) {\n nsid = u.getId();\n }\n }\n }", "public static void showOnlyChannels(Object... channels){\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n visHandler.hideAll();\r\n for (Object channel : channels) {\r\n visHandler.alsoShow(channel);\r\n }\r\n }\r\n }\r\n }" ]
Fire an event and notify observers that belong to this module. @param eventType @param event @param qualifiers
[ "public void fireEvent(Type eventType, Object event, Annotation... qualifiers) {\n final EventMetadata metadata = new EventMetadataImpl(eventType, null, qualifiers);\n notifier.fireEvent(eventType, event, metadata, qualifiers);\n }" ]
[ "public boolean exists() {\n\t\t// Try file existence: can we find the file in the file system?\n\t\ttry {\n\t\t\treturn getFile().exists();\n\t\t}\n\t\tcatch (IOException ex) {\n\t\t\t// Fall back to stream existence: can we open the stream?\n\t\t\ttry {\n\t\t\t\tInputStream is = getInputStream();\n\t\t\t\tis.close();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tcatch (Throwable isEx) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}", "private void initXmlBundle() throws CmsException {\n\n CmsFile file = m_cms.readFile(m_resource);\n m_bundleFiles.put(null, m_resource);\n m_xmlBundle = CmsXmlContentFactory.unmarshal(m_cms, file);\n initKeySetForXmlBundle();\n\n }", "public BoxFolder.Info getFolderInfo(String folderID, String... fields) {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", fields).toString();\n URL url = FOLDER_INFO_URL_TEMPLATE.buildWithQuery(this.api.getBaseURL(), queryString, folderID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFolder folder = new BoxFolder(this.api, jsonObject.get(\"id\").asString());\n return folder.new Info(response.getJSON());\n }", "public static base_response update(nitro_service client, nsconfig resource) throws Exception {\n\t\tnsconfig updateresource = new nsconfig();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.netmask = resource.netmask;\n\t\tupdateresource.nsvlan = resource.nsvlan;\n\t\tupdateresource.ifnum = resource.ifnum;\n\t\tupdateresource.tagged = resource.tagged;\n\t\tupdateresource.httpport = resource.httpport;\n\t\tupdateresource.maxconn = resource.maxconn;\n\t\tupdateresource.maxreq = resource.maxreq;\n\t\tupdateresource.cip = resource.cip;\n\t\tupdateresource.cipheader = resource.cipheader;\n\t\tupdateresource.cookieversion = resource.cookieversion;\n\t\tupdateresource.securecookie = resource.securecookie;\n\t\tupdateresource.pmtumin = resource.pmtumin;\n\t\tupdateresource.pmtutimeout = resource.pmtutimeout;\n\t\tupdateresource.ftpportrange = resource.ftpportrange;\n\t\tupdateresource.crportrange = resource.crportrange;\n\t\tupdateresource.timezone = resource.timezone;\n\t\tupdateresource.grantquotamaxclient = resource.grantquotamaxclient;\n\t\tupdateresource.exclusivequotamaxclient = resource.exclusivequotamaxclient;\n\t\tupdateresource.grantquotaspillover = resource.grantquotaspillover;\n\t\tupdateresource.exclusivequotaspillover = resource.exclusivequotaspillover;\n\t\tupdateresource.nwfwmode = resource.nwfwmode;\n\t\treturn updateresource.update_resource(client);\n\t}", "private void handleSendDataRequest(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Send Data Request\");\n\t\t\n\t\tint callbackId = incomingMessage.getMessagePayloadByte(0);\n\t\tTransmissionState status = TransmissionState.getTransmissionState(incomingMessage.getMessagePayloadByte(1));\n\t\tSerialMessage originalMessage = this.lastSentMessage;\n\t\t\n\t\tif (status == null) {\n\t\t\tlogger.warn(\"Transmission state not found, ignoring.\");\n\t\t\treturn;\n\t\t}\n\n\t\tlogger.debug(\"CallBack ID = {}\", callbackId);\n\t\tlogger.debug(String.format(\"Status = %s (0x%02x)\", status.getLabel(), status.getKey()));\n\t\t\n\t\tif (originalMessage == null || originalMessage.getCallbackId() != callbackId) {\n\t\t\tlogger.warn(\"Already processed another send data request for this callback Id, ignoring.\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tswitch (status) {\n\t\t\tcase COMPLETE_OK:\n\t\t\t\tZWaveNode node = this.getNode(originalMessage.getMessageNode());\n\t\t\t\tnode.resetResendCount();\n\t\t\t\t\n\t\t\t\t// in case we received a ping response and the node is alive, we proceed with the next node stage for this node.\n\t\t\t\tif (node != null && node.getNodeStage() == NodeStage.NODEBUILDINFO_PING) {\n\t\t\t\t\tnode.advanceNodeStage();\n\t\t\t\t}\n\t\t\t\tif (incomingMessage.getMessageClass() == originalMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {\n\t\t\t\t\tnotifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));\n\t\t\t\t\ttransactionCompleted.release();\n\t\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\tcase COMPLETE_NO_ACK:\n\t\t\tcase COMPLETE_FAIL:\n\t\t\tcase COMPLETE_NOT_IDLE:\n\t\t\tcase COMPLETE_NOROUTE:\n\t\t\t\ttry {\n\t\t\t\t\thandleFailedSendDataRequest(originalMessage);\n\t\t\t\t} finally {\n\t\t\t\t\ttransactionCompleted.release();\n\t\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t\t\t}\n\t\t\tdefault:\n\t\t}\n\t}", "public void addColumn(ColumnDef columnDef)\r\n {\r\n columnDef.setOwner(this);\r\n _columns.put(columnDef.getName(), columnDef);\r\n }", "public void addWord(MtasCQLParserWordFullCondition w) throws ParseException {\n assert w.getCondition()\n .not() == false : \"condition word should be positive in sentence definition\";\n if (!simplified) {\n partList.add(w);\n } else {\n throw new ParseException(\"already simplified\");\n }\n }", "public static void acceptsZone(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_Z, OPT_ZONE), \"zone id\")\n .withRequiredArg()\n .describedAs(\"zone-id\")\n .ofType(Integer.class);\n }", "public static String dump(final int displayOffset, final byte[] data, final int offset, final int len)\n {\n StringBuilder sb = new StringBuilder();\n Formatter formatter = new Formatter(sb);\n StringBuilder ascii = new StringBuilder();\n\n int dataNdx = offset;\n final int maxDataNdx = offset + len;\n final int lines = (len + 16) / 16;\n for (int i = 0; i < lines; i++) {\n ascii.append(\" |\");\n formatter.format(\"%08x \", displayOffset + (i * 16));\n\n for (int j = 0; j < 16; j++) {\n if (dataNdx < maxDataNdx) {\n byte b = data[dataNdx++];\n formatter.format(\"%02x \", b);\n ascii.append((b > MIN_VISIBLE && b < MAX_VISIBLE) ? (char) b : ' ');\n }\n else {\n sb.append(\" \");\n }\n\n if (j == 7) {\n sb.append(' ');\n }\n }\n\n ascii.append('|');\n sb.append(ascii).append('\\n');\n ascii.setLength(0);\n }\n\n formatter.close();\n return sb.toString();\n }" ]
Resolves the gav using the resolver. If the gav corresponds to the project artifact and is an unresolved version for a RELEASE or LATEST, the gav is resolved such it a release not newer than the project version is found that optionally corresponds to the provided version regex, if provided. <p>If the gav exactly matches the current project, the file of the artifact is found on the filesystem in target directory and the resolver is ignored. @param project the project to restrict by, if applicable @param gav the gav to resolve @param versionRegex the optional regex the version must match to be considered. @param resolver the version resolver to use @return the resolved artifact matching the criteria. @throws VersionRangeResolutionException on error @throws ArtifactResolutionException on error
[ "static Artifact resolveConstrained(MavenProject project, String gav, Pattern versionRegex,\n ArtifactResolver resolver)\n throws VersionRangeResolutionException, ArtifactResolutionException {\n boolean latest = gav.endsWith(\":LATEST\");\n if (latest || gav.endsWith(\":RELEASE\")) {\n Artifact a = new DefaultArtifact(gav);\n\n if (latest) {\n versionRegex = versionRegex == null ? ANY : versionRegex;\n } else {\n versionRegex = versionRegex == null ? ANY_NON_SNAPSHOT : versionRegex;\n }\n\n String upTo = project.getGroupId().equals(a.getGroupId()) && project.getArtifactId().equals(a.getArtifactId())\n ? project.getVersion()\n : null;\n\n return resolver.resolveNewestMatching(gav, upTo, versionRegex, latest, latest);\n } else {\n String projectGav = getProjectArtifactCoordinates(project, null);\n Artifact ret = null;\n\n if (projectGav.equals(gav)) {\n ret = findProjectArtifact(project);\n }\n\n return ret == null ? resolver.resolveArtifact(gav) : ret;\n }\n }" ]
[ "public static DMatrixRMaj symmetric(int length, double min, double max, Random rand) {\n DMatrixRMaj A = new DMatrixRMaj(length,length);\n\n symmetric(A,min,max,rand);\n\n return A;\n }", "public void visitOpen(String packaze, int access, String... modules) {\n if (mv != null) {\n mv.visitOpen(packaze, access, modules);\n }\n }", "public DynamicReportBuilder addStyle(Style style) throws DJBuilderException {\n if (style.getName() == null) {\n throw new DJBuilderException(\"Invalid style. The style must have a name\");\n }\n\n report.addStyle(style);\n\n return this;\n }", "private static void transposeBlock(DMatrixRBlock A , DMatrixRBlock A_tran,\n int indexA , int indexC ,\n int width , int height )\n {\n for( int i = 0; i < height; i++ ) {\n int rowIndexC = indexC + i;\n int rowIndexA = indexA + width*i;\n int end = rowIndexA + width;\n for( ; rowIndexA < end; rowIndexC += height, rowIndexA++ ) {\n A_tran.data[ rowIndexC ] = A.data[ rowIndexA ];\n }\n }\n }", "protected void addLineContent(BufferedReader bufferedFileReader, List<String> content, String line) throws IOException {\n content.add(line);\n }", "public static Type boxedType(Type type) {\n if (type instanceof Class<?>) {\n return boxedClass((Class<?>) type);\n } else {\n return type;\n }\n }", "public static service_stats get(nitro_service service, String name) throws Exception{\n\t\tservice_stats obj = new service_stats();\n\t\tobj.set_name(name);\n\t\tservice_stats response = (service_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public Iterator<K> tailIterator(@NotNull final K key) {\n return new Iterator<K>() {\n\n private Stack<TreePos<K>> stack;\n private boolean hasNext;\n private boolean hasNextValid;\n\n @Override\n public boolean hasNext() {\n if (hasNextValid) {\n return hasNext;\n }\n hasNextValid = true;\n if (stack == null) {\n Node<K> root = getRoot();\n if (root == null) {\n hasNext = false;\n return hasNext;\n }\n stack = new Stack<>();\n if (!root.getLess(key, stack)) {\n stack.push(new TreePos<>(root));\n }\n }\n TreePos<K> treePos = stack.peek();\n if (treePos.node.isLeaf()) {\n while (treePos.pos >= (treePos.node.isTernary() ? 2 : 1)) {\n stack.pop();\n if (stack.isEmpty()) {\n hasNext = false;\n return hasNext;\n }\n treePos = stack.peek();\n }\n } else {\n if (treePos.pos == 0) {\n treePos = new TreePos<>(treePos.node.getFirstChild());\n } else if (treePos.pos == 1) {\n treePos = new TreePos<>(treePos.node.getSecondChild());\n } else {\n treePos = new TreePos<>(treePos.node.getThirdChild());\n }\n stack.push(treePos);\n while (!treePos.node.isLeaf()) {\n treePos = new TreePos<>(treePos.node.getFirstChild());\n stack.push(treePos);\n }\n }\n treePos.pos++;\n hasNext = true;\n return hasNext;\n }\n\n @Override\n public K next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n hasNextValid = false;\n TreePos<K> treePos = stack.peek();\n // treePos.pos must be 1 or 2 here\n return treePos.pos == 1 ? treePos.node.getFirstKey() : treePos.node.getSecondKey();\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n };\n }", "public Point measureImage(Resources resources) {\n BitmapFactory.Options justBoundsOptions = new BitmapFactory.Options();\n justBoundsOptions.inJustDecodeBounds = true;\n\n if (bitmap != null) {\n return new Point(bitmap.getWidth(), bitmap.getHeight());\n } else if (resId != null) {\n BitmapFactory.decodeResource(resources, resId, justBoundsOptions);\n float scale = (float) justBoundsOptions.inTargetDensity / justBoundsOptions.inDensity;\n return new Point((int) (justBoundsOptions.outWidth * scale + 0.5f), (int) (justBoundsOptions.outHeight * scale + 0.5f));\n } else if (fileToBitmap != null) {\n BitmapFactory.decodeFile(fileToBitmap.getAbsolutePath(), justBoundsOptions);\n } else if (inputStream != null) {\n BitmapFactory.decodeStream(inputStream, null, justBoundsOptions);\n try {\n inputStream.reset();\n } catch (IOException ignored) {\n }\n } else if (view != null) {\n return new Point(view.getWidth(), view.getHeight());\n }\n return new Point(justBoundsOptions.outWidth, justBoundsOptions.outHeight);\n }" ]
Parse an extended attribute value. @param file parent file @param mpx parent entity @param value string value @param mpxFieldID field ID @param durationFormat duration format associated with the extended attribute
[ "public static final void parseExtendedAttribute(ProjectFile file, FieldContainer mpx, String value, FieldType mpxFieldID, TimeUnit durationFormat)\n {\n if (mpxFieldID != null)\n {\n switch (mpxFieldID.getDataType())\n {\n case STRING:\n {\n mpx.set(mpxFieldID, value);\n break;\n }\n\n case DATE:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeDate(value));\n break;\n }\n\n case CURRENCY:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeCurrency(value));\n break;\n }\n\n case BOOLEAN:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeBoolean(value));\n break;\n }\n\n case NUMERIC:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeNumber(value));\n break;\n }\n\n case DURATION:\n {\n mpx.set(mpxFieldID, parseDuration(file, durationFormat, value));\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n }" ]
[ "public void adjustLinks(String sourceFolder, String targetFolder) throws CmsException {\n\n String rootSourceFolder = addSiteRoot(sourceFolder);\n String rootTargetFolder = addSiteRoot(targetFolder);\n String siteRoot = getRequestContext().getSiteRoot();\n getRequestContext().setSiteRoot(\"\");\n try {\n CmsLinkRewriter linkRewriter = new CmsLinkRewriter(this, rootSourceFolder, rootTargetFolder);\n linkRewriter.rewriteLinks();\n } finally {\n getRequestContext().setSiteRoot(siteRoot);\n }\n }", "public static base_response delete(nitro_service client, nssimpleacl resource) throws Exception {\n\t\tnssimpleacl deleteresource = new nssimpleacl();\n\t\tdeleteresource.aclname = resource.aclname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "private Map<ConfigurationKey, Object> getObsoleteSystemProperties() {\n Map<ConfigurationKey, Object> found = new EnumMap<ConfigurationKey, Object>(ConfigurationKey.class);\n String concurrentDeployment = getSystemProperty(\"org.jboss.weld.bootstrap.properties.concurrentDeployment\");\n if (concurrentDeployment != null) {\n processKeyValue(found, ConfigurationKey.CONCURRENT_DEPLOYMENT, concurrentDeployment);\n found.put(ConfigurationKey.CONCURRENT_DEPLOYMENT, ConfigurationKey.CONCURRENT_DEPLOYMENT.convertValue(concurrentDeployment));\n }\n String preloaderThreadPoolSize = getSystemProperty(\"org.jboss.weld.bootstrap.properties.preloaderThreadPoolSize\");\n if (preloaderThreadPoolSize != null) {\n found.put(ConfigurationKey.PRELOADER_THREAD_POOL_SIZE, ConfigurationKey.PRELOADER_THREAD_POOL_SIZE.convertValue(preloaderThreadPoolSize));\n }\n return found;\n }", "public static service_stats[] get(nitro_service service) throws Exception{\n\t\tservice_stats obj = new service_stats();\n\t\tservice_stats[] response = (service_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public Map<String, Object> getModuleFieldsFilters() {\n final Map<String, Object> params = new HashMap<String, Object>();\n\n for(final Filter filter: filters){\n params.putAll(filter.moduleFilterFields());\n }\n\n return params;\n }", "private void prepareModel(DescriptorRepository model)\r\n {\r\n TreeMap result = new TreeMap();\r\n\r\n for (Iterator it = model.getDescriptorTable().values().iterator(); it.hasNext();)\r\n {\r\n ClassDescriptor classDesc = (ClassDescriptor)it.next();\r\n\r\n if (classDesc.getFullTableName() == null)\r\n {\r\n // not mapped to a database table\r\n continue;\r\n }\r\n\r\n String elementName = getElementName(classDesc);\r\n Table mappedTable = getTableFor(elementName);\r\n Map columnsMap = getColumnsFor(elementName);\r\n Map requiredAttributes = getRequiredAttributes(elementName);\r\n List classDescs = getClassDescriptorsMappingTo(elementName);\r\n\r\n if (mappedTable == null)\r\n {\r\n mappedTable = _schema.findTable(classDesc.getFullTableName());\r\n if (mappedTable == null)\r\n {\r\n continue;\r\n }\r\n columnsMap = new TreeMap();\r\n requiredAttributes = new HashMap();\r\n classDescs = new ArrayList();\r\n _elementToTable.put(elementName, mappedTable);\r\n _elementToClassDescriptors.put(elementName, classDescs);\r\n _elementToColumnMap.put(elementName, columnsMap);\r\n _elementToRequiredAttributesMap.put(elementName, requiredAttributes);\r\n }\r\n classDescs.add(classDesc);\r\n extractAttributes(classDesc, mappedTable, columnsMap, requiredAttributes);\r\n }\r\n extractIndirectionTables(model, _schema);\r\n }", "public static base_responses add(nitro_service client, dbdbprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdbdbprofile addresources[] = new dbdbprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dbdbprofile();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].interpretquery = resources[i].interpretquery;\n\t\t\t\taddresources[i].stickiness = resources[i].stickiness;\n\t\t\t\taddresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\taddresources[i].conmultiplex = resources[i].conmultiplex;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public int compare(final Version other) throws IncomparableException{\n\t\t// Cannot compare branch versions and others \n\t\tif(!isBranch().equals(other.isBranch())){\n\t\t\tthrow new IncomparableException();\n\t\t}\n\t\t\n\t\t// Compare digits\n\t\tfinal int minDigitSize = getDigitsSize() < other.getDigitsSize()? getDigitsSize(): other.getDigitsSize();\n\t\t\n\t\tfor(int i = 0; i < minDigitSize ; i++){\n\t\t\tif(!getDigit(i).equals(other.getDigit(i))){\n\t\t\t\treturn getDigit(i).compareTo(other.getDigit(i));\n\t\t\t}\n\t\t}\n\t\t\n\t\t// If not the same number of digits and the first digits are equals, the longest is the newer\n\t\tif(!getDigitsSize().equals(other.getDigitsSize())){\n\t\t\treturn getDigitsSize() > other.getDigitsSize()? 1: -1;\n\t\t}\n\n if(isBranch() && !getBranchId().equals(other.getBranchId())){\n\t\t\treturn getBranchId().compareTo(other.getBranchId());\n\t\t}\n\t\t\n\t\t// if the digits are the same, a snapshot is newer than a release\n\t\tif(isSnapshot() && other.isRelease()){\n\t\t\treturn 1;\n\t\t}\n\t\t\n\t\tif(isRelease() && other.isSnapshot()){\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\t// if both versions are releases, compare the releaseID\n\t\tif(isRelease() && other.isRelease()){\n\t\t\treturn getReleaseId().compareTo(other.getReleaseId());\n\t\t}\n\t\t\n\t\treturn 0;\n\t}", "private RandomVariable getValueUnderlyingNumeraireRelative(LIBORModelMonteCarloSimulationModel model, Schedule legSchedule, boolean paysFloat, double swaprate, double notional) throws CalculationException {\r\n\t\tRandomVariable value\t= model.getRandomVariableForConstant(0.0);\r\n\r\n\t\tfor(int periodIndex = legSchedule.getNumberOfPeriods() - 1; periodIndex >= 0; periodIndex--) {\r\n\r\n\t\t\tdouble fixingTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getFixing());\r\n\t\t\tdouble paymentTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getPayment());\r\n\t\t\tdouble periodLength\t= legSchedule.getPeriodLength(periodIndex);\r\n\r\n\t\t\tRandomVariable\tnumeraireAtPayment = model.getNumeraire(paymentTime);\r\n\t\t\tRandomVariable\tmonteCarloProbabilitiesAtPayment = model.getMonteCarloWeights(paymentTime);\r\n\t\t\tif(swaprate != 0.0) {\r\n\t\t\t\tRandomVariable periodCashFlowFix = model.getRandomVariableForConstant(swaprate * periodLength * notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment);\r\n\t\t\t\tvalue = value.add(periodCashFlowFix);\r\n\t\t\t}\r\n\t\t\tif(paysFloat) {\r\n\t\t\t\tRandomVariable libor = model.getLIBOR(fixingTime, fixingTime, paymentTime);\r\n\t\t\t\tRandomVariable periodCashFlowFloat = libor.mult(periodLength).mult(notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment);\r\n\t\t\t\tvalue = value.add(periodCashFlowFloat);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn value;\r\n\t}" ]
Retrieve the Activity ID value for this task. @param task Task instance @return Activity ID value
[ "private String getActivityID(Task task)\n {\n String result = null;\n if (m_activityIDField != null)\n {\n Object value = task.getCachedValue(m_activityIDField);\n if (value != null)\n {\n result = value.toString();\n }\n }\n return result;\n }" ]
[ "static BsonDocument sanitizeDocument(final BsonDocument document) {\n if (document == null) {\n return null;\n }\n if (document.containsKey(DOCUMENT_VERSION_FIELD)) {\n final BsonDocument clonedDoc = document.clone();\n clonedDoc.remove(DOCUMENT_VERSION_FIELD);\n\n return clonedDoc;\n }\n return document;\n }", "public Range<App> listApps(String range) {\n return connection.execute(new AppList(range), apiKey);\n }", "private void setCrosstabOptions() {\n\t\tif (djcross.isUseFullWidth()){\n\t\t\tjrcross.setWidth(layoutManager.getReport().getOptions().getPrintableWidth());\n\t\t} else {\n\t\t\tjrcross.setWidth(djcross.getWidth());\n\t\t}\n\t\tjrcross.setHeight(djcross.getHeight());\n\n\t\tjrcross.setColumnBreakOffset(djcross.getColumnBreakOffset());\n\n jrcross.setIgnoreWidth(djcross.isIgnoreWidth());\n\t}", "private InputStream runSparqlQuery(String query) throws IOException {\n\t\ttry {\n\t\t\tString queryString = \"query=\" + URLEncoder.encode(query, \"UTF-8\")\n\t\t\t\t\t+ \"&format=json\";\n\t\t\tURL url = new URL(\"https://query.wikidata.org/sparql?\"\n\t\t\t\t\t+ queryString);\n\t\t\tHttpURLConnection connection = (HttpURLConnection) url\n\t\t\t\t\t.openConnection();\n\t\t\tconnection.setRequestMethod(\"GET\");\n\n\t\t\treturn connection.getInputStream();\n\t\t} catch (UnsupportedEncodingException | MalformedURLException e) {\n\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t}\n\t}", "public List<CmsFavoriteEntry> loadFavorites() throws CmsException {\n\n List<CmsFavoriteEntry> result = new ArrayList<>();\n try {\n CmsUser user = readUser();\n String data = (String)user.getAdditionalInfo(ADDINFO_KEY);\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(data)) {\n return new ArrayList<>();\n }\n JSONObject json = new JSONObject(data);\n JSONArray array = json.getJSONArray(BASE_KEY);\n for (int i = 0; i < array.length(); i++) {\n JSONObject fav = array.getJSONObject(i);\n try {\n CmsFavoriteEntry entry = new CmsFavoriteEntry(fav);\n if (validate(entry)) {\n result.add(entry);\n }\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n\n }\n } catch (JSONException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n return result;\n }", "private static JsonParser newJsonParserForNode(JsonNode jsonNode) throws IOException {\n JsonParser parser = new JsonFactory().createParser(jsonNode.toString());\n parser.nextToken();\n return parser;\n }", "protected void queryTimerEnd(String sql, long queryStartTime) {\r\n\t\tif ((this.queryExecuteTimeLimit != 0) \r\n\t\t\t\t&& (this.connectionHook != null)){\r\n\t\t\tlong timeElapsed = (System.nanoTime() - queryStartTime);\r\n\t\t\t\r\n\t\t\tif (timeElapsed > this.queryExecuteTimeLimit){\r\n\t\t\t\tthis.connectionHook.onQueryExecuteTimeLimitExceeded(this.connectionHandle, this, sql, this.logParams, timeElapsed);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif (this.statisticsEnabled){\r\n\t\t\tthis.statistics.incrementStatementsExecuted();\r\n\t\t\tthis.statistics.addStatementExecuteTime(System.nanoTime() - queryStartTime);\r\n\t\t\t\r\n\t\t}\r\n\r\n\t}", "public static Class getClass(String className, boolean initialize) throws ClassNotFoundException\r\n {\r\n return Class.forName(className, initialize, getClassLoader());\r\n }", "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 }" ]
Merges two lists of references, eliminating duplicates in the process. @param references1 @param references2 @return merged list
[ "protected List<Reference> mergeReferences(\n\t\t\tList<? extends Reference> references1,\n\t\t\tList<? extends Reference> references2) {\n\t\tList<Reference> result = new ArrayList<>();\n\t\tfor (Reference reference : references1) {\n\t\t\taddBestReferenceToList(reference, result);\n\t\t}\n\t\tfor (Reference reference : references2) {\n\t\t\taddBestReferenceToList(reference, result);\n\t\t}\n\t\treturn result;\n\t}" ]
[ "private void countKey(Map<String, Integer> map, String key, int count) {\n\t\tif (map.containsKey(key)) {\n\t\t\tmap.put(key, map.get(key) + count);\n\t\t} else {\n\t\t\tmap.put(key, count);\n\t\t}\n\t}", "public static int[] toInt(double[] array) {\n int[] n = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n n[i] = (int) array[i];\n }\n return n;\n }", "protected boolean hasTimeOutHeader() {\n\n boolean result = false;\n String timeoutValStr = this.request.getHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS);\n if(timeoutValStr != null) {\n try {\n this.parsedTimeoutInMs = Long.parseLong(timeoutValStr);\n if(this.parsedTimeoutInMs < 0) {\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Time out cannot be negative \");\n\n } else {\n result = true;\n }\n } catch(NumberFormatException nfe) {\n logger.error(\"Exception when validating request. Incorrect timeout parameter. Cannot parse this to long: \"\n + timeoutValStr,\n nfe);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Incorrect timeout parameter. Cannot parse this to long: \"\n + timeoutValStr);\n }\n } else {\n logger.error(\"Error when validating request. Missing timeout parameter.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing timeout parameter.\");\n }\n return result;\n }", "public static <K> Map<K, Integer> rankMapOnIntegerValue(Map<K, Integer> inputMap) {\n Map<K, Integer> newMap = new TreeMap<K, Integer>(new IntegerValueComparator(inputMap));\n newMap.putAll(inputMap);\n\n Map<K, Integer> linkedMap = new LinkedHashMap<K, Integer>(newMap);\n return linkedMap;\n }", "public VectorClock incremented(int nodeId, long time) {\n VectorClock copyClock = this.clone();\n copyClock.incrementVersion(nodeId, time);\n return copyClock;\n }", "private void setLanguageFilters(String filters) {\n\t\tthis.filterLanguages = new HashSet<>();\n\t\tif (!\"-\".equals(filters)) {\n\t\t\tCollections.addAll(this.filterLanguages, filters.split(\",\"));\n\t\t}\n\t}", "public static void addToListIfNotExists(List<String> list, String value) {\n boolean found = false;\n for (String item : list) {\n if (item.equalsIgnoreCase(value)) {\n found = true;\n break;\n }\n }\n if (!found) {\n list.add(value);\n }\n }", "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 }", "protected int readShort(int offset, byte[] data)\n {\n int result = 0;\n int i = offset + m_offset;\n for (int shiftBy = 0; shiftBy < 16; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }" ]
Read one collection element from the current row of the JDBC result set @param optionalOwner the collection owner @param optionalKey the collection key @param persister the collection persister @param descriptor the collection aliases @param rs the result set @param session the session @throws HibernateException if an error occurs @throws SQLException if an error occurs during the query execution
[ "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 static final Color getColor(byte[] data, int offset)\n {\n Color result = null;\n\n if (getByte(data, offset + 3) == 0)\n {\n int r = getByte(data, offset);\n int g = getByte(data, offset + 1);\n int b = getByte(data, offset + 2);\n result = new Color(r, g, b);\n }\n\n return result;\n }", "public static boolean isMessageContentToBeLogged(final Message message, final boolean logMessageContent,\n boolean logMessageContentOverride) {\n\n /*\n * If controlling of logging behavior is not allowed externally\n * then log according to global property value\n */\n if (!logMessageContentOverride) {\n return logMessageContent;\n }\n\n Object logMessageContentExtObj = message.getContextualProperty(EXTERNAL_PROPERTY_NAME);\n\n if (null == logMessageContentExtObj) {\n\n return logMessageContent;\n\n } else if (logMessageContentExtObj instanceof Boolean) {\n\n return ((Boolean) logMessageContentExtObj).booleanValue();\n\n } else if (logMessageContentExtObj instanceof String) {\n\n String logMessageContentExtVal = (String) logMessageContentExtObj;\n\n if (logMessageContentExtVal.equalsIgnoreCase(\"true\")) {\n\n return true;\n\n } else if (logMessageContentExtVal.equalsIgnoreCase(\"false\")) {\n\n return false;\n\n } else {\n\n return logMessageContent;\n }\n } else {\n\n return logMessageContent;\n }\n }", "@SafeVarargs\n public static <K> Set<K> set(final K... keys) {\n return new LinkedHashSet<K>(Arrays.asList(keys));\n }", "public static lbvserver_stats get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_stats obj = new lbvserver_stats();\n\t\tobj.set_name(name);\n\t\tlbvserver_stats response = (lbvserver_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public static int[] randomPermutation(int size) {\n Random r = new Random();\n int[] result = new int[size];\n\n for (int j = 0; j < size; j++) {\n result[j] = j;\n }\n \n for (int j = size - 1; j > 0; j--) {\n int k = r.nextInt(j);\n int temp = result[j];\n result[j] = result[k];\n result[k] = temp;\n }\n\n return result;\n }", "public static final Integer parseInteger(String value)\n {\n return (value == null || value.length() == 0 ? null : Integer.valueOf(Integer.parseInt(value)));\n }", "ResultAction executeOperation() {\n\n assert isControllingThread();\n try {\n /** Execution has begun */\n executing = true;\n\n processStages();\n\n if (resultAction == ResultAction.KEEP) {\n report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationSucceeded());\n } else {\n report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationRollingBack());\n }\n } catch (RuntimeException e) {\n handleUncaughtException(e);\n ControllerLogger.MGMT_OP_LOGGER.unexpectedOperationExecutionException(e, controllerOperations);\n } finally {\n // On failure close any attached response streams\n if (resultAction != ResultAction.KEEP && !isBooting()) {\n synchronized (this) {\n if (responseStreams != null) {\n int i = 0;\n for (OperationResponse.StreamEntry is : responseStreams.values()) {\n try {\n is.getStream().close();\n } catch (Exception e) {\n ControllerLogger.MGMT_OP_LOGGER.debugf(e, \"Failed closing stream at index %d\", i);\n }\n i++;\n }\n responseStreams.clear();\n }\n }\n }\n }\n\n\n return resultAction;\n }", "public void purge(String cacheKey) {\n try {\n if (useMemoryCache) {\n if (memoryCache != null) {\n memoryCache.remove(cacheKey);\n }\n }\n\n if (useDiskCache) {\n if (diskLruCache != null) {\n diskLruCache.remove(cacheKey);\n }\n }\n } catch (Exception e) {\n Log.w(TAG, \"Could not remove entry in cache purge\", e);\n }\n }", "public static int[] randomSubset(int k, int n) {\n assert(0 < k && k <= n);\n Random r = new Random();\n int t = 0, m = 0;\n int[] result = new int[k];\n\n while (m < k) {\n double u = r.nextDouble();\n if ( (n - t) * u < k - m ) {\n result[m] = t;\n m++;\n }\n t++;\n }\n return result;\n }" ]
Get a list of modules regarding filters @param filters Map<String,String> @return List<Module> @throws GrapesCommunicationException
[ "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 }" ]
[ "@Override\n public boolean postBuild(MavenBuildProxy build, MavenProject pom, BuildListener listener)\n throws InterruptedException, IOException {\n build.executeAsync(new BuildCallable<Void, IOException>() {\n // record is transient, so needs to make a copy first\n private final Set<MavenDependency> d = dependencies;\n\n public Void call(MavenBuild build) throws IOException, InterruptedException {\n // add the action\n //TODO: [by yl] These actions are persisted into the build.xml of each build run - we need another\n //context to store these actions\n build.getActions().add(new MavenDependenciesRecord(build, d));\n return null;\n }\n });\n return true;\n }", "public Where<T, ID> not() {\n\t\t/*\n\t\t * Special circumstance here when we have a needs future with a not. Something like and().not().like(...). In\n\t\t * this case we satisfy the and()'s future as the not() but the not() becomes the new needs-future.\n\t\t */\n\t\tNot not = new Not();\n\t\taddClause(not);\n\t\taddNeedsFuture(not);\n\t\treturn this;\n\t}", "@SuppressWarnings(\"unchecked\")\n public Set<RateType> getRateTypes() {\n Set<RateType> result = get(KEY_RATE_TYPES, Set.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "private boolean fireEventWait(WebElement webElement, Eventable eventable)\n\t\t\tthrows ElementNotVisibleException, InterruptedException {\n\t\tswitch (eventable.getEventType()) {\n\t\t\tcase click:\n\t\t\t\ttry {\n\t\t\t\t\twebElement.click();\n\t\t\t\t} catch (ElementNotVisibleException e) {\n\t\t\t\t\tthrow e;\n\t\t\t\t} catch (WebDriverException e) {\n\t\t\t\t\tthrowIfConnectionException(e);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase hover:\n\t\t\t\tLOGGER.info(\"EventType hover called but this isn't implemented yet\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tLOGGER.info(\"EventType {} not supported in WebDriver.\", eventable.getEventType());\n\t\t\t\treturn false;\n\t\t}\n\n\t\tThread.sleep(this.crawlWaitEvent);\n\t\treturn true;\n\t}", "public CredentialsConfig getResolvingCredentialsConfig() {\n if (resolverCredentialsConfig != null && resolverCredentialsConfig.isCredentialsProvided()) {\n return getResolverCredentialsConfig();\n }\n if (deployerCredentialsConfig != null) {\n return getDeployerCredentialsConfig();\n }\n\n return CredentialsConfig.EMPTY_CREDENTIALS_CONFIG;\n }", "public Map<String, Table> process(File directory, String prefix) throws IOException\n {\n String filePrefix = prefix.toUpperCase();\n Map<String, Table> tables = new HashMap<String, Table>();\n File[] files = directory.listFiles();\n if (files != null)\n {\n for (File file : files)\n {\n String name = file.getName().toUpperCase();\n if (!name.startsWith(filePrefix))\n {\n continue;\n }\n\n int typeIndex = name.lastIndexOf('.') - 3;\n String type = name.substring(typeIndex, typeIndex + 3);\n TableDefinition definition = TABLE_DEFINITIONS.get(type);\n if (definition != null)\n {\n Table table = new Table();\n TableReader reader = new TableReader(definition);\n reader.read(file, table);\n tables.put(type, table);\n //dumpCSV(type, definition, table);\n }\n }\n }\n return tables;\n }", "public ProjectFile read() throws MPXJException\n {\n MPD9DatabaseReader reader = new MPD9DatabaseReader();\n reader.setProjectID(m_projectID);\n reader.setPreserveNoteFormatting(m_preserveNoteFormatting);\n reader.setDataSource(m_dataSource);\n reader.setConnection(m_connection);\n ProjectFile project = reader.read();\n return (project);\n }", "public static ContainerDescription getContainerDescription(final ModelControllerClient client) throws IOException, OperationExecutionException {\n return DefaultContainerDescription.lookup(Assert.checkNotNullParam(\"client\", client));\n }", "public Channel sessionConnectGenerateChannel(Session session)\n throws JSchException {\n \t// set timeout\n session.connect(sshMeta.getSshConnectionTimeoutMillis());\n \n ChannelExec channel = (ChannelExec) session.openChannel(\"exec\");\n channel.setCommand(sshMeta.getCommandLine());\n\n // if run as super user, assuming the input stream expecting a password\n if (sshMeta.isRunAsSuperUser()) {\n \ttry {\n channel.setInputStream(null, true);\n\n OutputStream out = channel.getOutputStream();\n channel.setOutputStream(System.out, true);\n channel.setExtOutputStream(System.err, true);\n channel.setPty(true);\n channel.connect();\n \n\t out.write((sshMeta.getPassword()+\"\\n\").getBytes());\n\t out.flush();\n\t\t\t} catch (IOException e) {\n\t\t\t\tlogger.error(\"error in sessionConnectGenerateChannel for super user\", e);\n\t\t\t}\n } else {\n \tchannel.setInputStream(null);\n \tchannel.connect();\n }\n\n return channel;\n\n }" ]
Generate query parameters for a forward page with the specified start key. @param initialQueryParameters page 1 query parameters @param startkey the startkey for the forward page @param startkey_docid the doc id for the startkey (in case of duplicate keys) @param <K> the view key type @param <V> the view value type @return the query parameters for the forward page
[ "static <K, V> ViewQueryParameters<K, V> forwardPaginationQueryParameters\n (ViewQueryParameters<K, V> initialQueryParameters, K startkey, String startkey_docid) {\n\n // Copy the initial query parameters\n ViewQueryParameters<K, V> pageParameters = initialQueryParameters.copy();\n\n // Now override with the start keys provided\n pageParameters.setStartKey(startkey);\n pageParameters.setStartKeyDocId(startkey_docid);\n\n return pageParameters;\n }" ]
[ "private void getMonthlyRelativeDates(Calendar calendar, int frequency, List<Date> dates)\n {\n long startDate = calendar.getTimeInMillis();\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n int dayNumber = NumberHelper.getInt(m_dayNumber);\n\n while (moreDates(calendar, dates))\n {\n if (dayNumber > 4)\n {\n setCalendarToLastRelativeDay(calendar);\n }\n else\n {\n setCalendarToOrdinalRelativeDay(calendar, dayNumber);\n }\n\n if (calendar.getTimeInMillis() > startDate)\n {\n dates.add(calendar.getTime());\n if (!moreDates(calendar, dates))\n {\n break;\n }\n }\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.add(Calendar.MONTH, frequency);\n }\n }", "public void addProfile(Object key, DescriptorRepository repository)\r\n {\r\n if (metadataProfiles.contains(key))\r\n {\r\n throw new MetadataException(\"Duplicate profile key. Key '\" + key + \"' already exists.\");\r\n }\r\n metadataProfiles.put(key, repository);\r\n }", "public static void registerTinyTypes(Class<?> head, Class<?>... tail) {\n final Set<HeaderDelegateProvider> systemRegisteredHeaderProviders = stealAcquireRefToHeaderDelegateProviders();\n register(head, systemRegisteredHeaderProviders);\n for (Class<?> tt : tail) {\n register(tt, systemRegisteredHeaderProviders);\n }\n }", "public final void draw() {\n AffineTransform transform = new AffineTransform(this.transform);\n transform.concatenate(getAlignmentTransform());\n\n // draw the background box\n this.graphics2d.setTransform(transform);\n this.graphics2d.setColor(this.params.getBackgroundColor());\n this.graphics2d.fillRect(0, 0, this.settings.getSize().width, this.settings.getSize().height);\n\n //draw the labels\n this.graphics2d.setColor(this.params.getFontColor());\n drawLabels(transform, this.params.getOrientation(), this.params.getLabelRotation());\n\n //sets the transformation for drawing the bar and do it\n final AffineTransform lineTransform = new AffineTransform(transform);\n setLineTranslate(lineTransform);\n\n if (this.params.getOrientation() == Orientation.VERTICAL_LABELS_LEFT ||\n this.params.getOrientation() == Orientation.VERTICAL_LABELS_RIGHT) {\n final AffineTransform rotate = AffineTransform.getQuadrantRotateInstance(1);\n lineTransform.concatenate(rotate);\n }\n\n this.graphics2d.setTransform(lineTransform);\n this.graphics2d.setStroke(new BasicStroke(this.settings.getLineWidth()));\n this.graphics2d.setColor(this.params.getColor());\n drawBar();\n }", "private InputStream runSparqlQuery(String query) throws IOException {\n\t\ttry {\n\t\t\tString queryString = \"query=\" + URLEncoder.encode(query, \"UTF-8\")\n\t\t\t\t\t+ \"&format=json\";\n\t\t\tURL url = new URL(\"https://query.wikidata.org/sparql?\"\n\t\t\t\t\t+ queryString);\n\t\t\tHttpURLConnection connection = (HttpURLConnection) url\n\t\t\t\t\t.openConnection();\n\t\t\tconnection.setRequestMethod(\"GET\");\n\n\t\t\treturn connection.getInputStream();\n\t\t} catch (UnsupportedEncodingException | MalformedURLException e) {\n\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t}\n\t}", "private static Predicate join(final String joinWord, final List<Predicate> preds) {\n return new Predicate() {\n public void init(AbstractSqlCreator creator) {\n for (Predicate p : preds) {\n p.init(creator);\n }\n }\n public String toSql() {\n StringBuilder sb = new StringBuilder()\n .append(\"(\");\n boolean first = true;\n for (Predicate p : preds) {\n if (!first) {\n sb.append(\" \").append(joinWord).append(\" \");\n }\n sb.append(p.toSql());\n first = false;\n }\n return sb.append(\")\").toString();\n }\n };\n }", "public static void fillHermitian(ZMatrixRMaj A, double min, double max, Random rand) {\n if( A.numRows != A.numCols )\n throw new IllegalArgumentException(\"A must be a square matrix\");\n\n double range = max-min;\n\n int length = A.numRows;\n\n for( int i = 0; i < length; i++ ) {\n A.set(i,i,rand.nextDouble()*range + min,0);\n\n for( int j = i+1; j < length; j++ ) {\n double real = rand.nextDouble()*range + min;\n double imaginary = rand.nextDouble()*range + min;\n A.set(i,j,real,imaginary);\n A.set(j,i,real,-imaginary);\n }\n }\n }", "public void setDuration(float start, float end)\n {\n for (GVRAnimation anim : mAnimations)\n {\n anim.setDuration(start,end);\n }\n }", "private void logShort(CharSequence message, boolean trim) throws IOException {\n int length = message.length();\n if (trim) {\n while (length > 0 && Character.isWhitespace(message.charAt(length - 1))) {\n length--;\n }\n }\n\n char [] chars = new char [length + 1];\n for (int i = 0; i < length; i++) {\n chars[i] = message.charAt(i);\n }\n chars[length] = '\\n';\n\n output.write(chars);\n }" ]
Use this API to update appfwlearningsettings.
[ "public static base_response update(nitro_service client, appfwlearningsettings resource) throws Exception {\n\t\tappfwlearningsettings updateresource = new appfwlearningsettings();\n\t\tupdateresource.profilename = resource.profilename;\n\t\tupdateresource.starturlminthreshold = resource.starturlminthreshold;\n\t\tupdateresource.starturlpercentthreshold = resource.starturlpercentthreshold;\n\t\tupdateresource.cookieconsistencyminthreshold = resource.cookieconsistencyminthreshold;\n\t\tupdateresource.cookieconsistencypercentthreshold = resource.cookieconsistencypercentthreshold;\n\t\tupdateresource.csrftagminthreshold = resource.csrftagminthreshold;\n\t\tupdateresource.csrftagpercentthreshold = resource.csrftagpercentthreshold;\n\t\tupdateresource.fieldconsistencyminthreshold = resource.fieldconsistencyminthreshold;\n\t\tupdateresource.fieldconsistencypercentthreshold = resource.fieldconsistencypercentthreshold;\n\t\tupdateresource.crosssitescriptingminthreshold = resource.crosssitescriptingminthreshold;\n\t\tupdateresource.crosssitescriptingpercentthreshold = resource.crosssitescriptingpercentthreshold;\n\t\tupdateresource.sqlinjectionminthreshold = resource.sqlinjectionminthreshold;\n\t\tupdateresource.sqlinjectionpercentthreshold = resource.sqlinjectionpercentthreshold;\n\t\tupdateresource.fieldformatminthreshold = resource.fieldformatminthreshold;\n\t\tupdateresource.fieldformatpercentthreshold = resource.fieldformatpercentthreshold;\n\t\tupdateresource.xmlwsiminthreshold = resource.xmlwsiminthreshold;\n\t\tupdateresource.xmlwsipercentthreshold = resource.xmlwsipercentthreshold;\n\t\tupdateresource.xmlattachmentminthreshold = resource.xmlattachmentminthreshold;\n\t\tupdateresource.xmlattachmentpercentthreshold = resource.xmlattachmentpercentthreshold;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
[ "public void setSomePendingWritesAndSave(\n final long atTime,\n final ChangeEvent<BsonDocument> changeEvent\n ) {\n docLock.writeLock().lock();\n try {\n // if we were frozen\n if (isPaused) {\n // unfreeze the document due to the local write\n setPaused(false);\n // and now the unfrozen document is now stale\n setStale(true);\n }\n\n this.lastUncommittedChangeEvent =\n coalesceChangeEvents(this.lastUncommittedChangeEvent, changeEvent);\n this.lastResolution = atTime;\n docsColl.replaceOne(\n getDocFilter(namespace, documentId),\n this);\n } finally {\n docLock.writeLock().unlock();\n }\n }", "public static double getDaycount(LocalDate startDate, LocalDate endDate, String convention) {\n\t\tDayCountConventionInterface daycountConvention = getDayCountConvention(convention);\n\t\treturn daycountConvention.getDaycount(startDate, endDate);\n\t}", "public static bridgegroup_nsip_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_nsip_binding obj = new bridgegroup_nsip_binding();\n\t\tobj.set_id(id);\n\t\tbridgegroup_nsip_binding response[] = (bridgegroup_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static boolean matches(Map<String, Object> nodeProperties, String[] keyColumnNames, Object[] keyColumnValues) {\n\t\tfor ( int i = 0; i < keyColumnNames.length; i++ ) {\n\t\t\tString property = keyColumnNames[i];\n\t\t\tObject expectedValue = keyColumnValues[i];\n\t\t\tboolean containsProperty = nodeProperties.containsKey( property );\n\t\t\tif ( containsProperty ) {\n\t\t\t\tObject actualValue = nodeProperties.get( property );\n\t\t\t\tif ( !sameValue( expectedValue, actualValue ) ) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ( expectedValue != null ) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "private void setWorkingDays(ProjectCalendar mpxjCalendar, Calendars gpCalendar)\n {\n DayTypes dayTypes = gpCalendar.getDayTypes();\n DefaultWeek defaultWeek = dayTypes.getDefaultWeek();\n if (defaultWeek == null)\n {\n mpxjCalendar.setWorkingDay(Day.SUNDAY, false);\n mpxjCalendar.setWorkingDay(Day.MONDAY, true);\n mpxjCalendar.setWorkingDay(Day.TUESDAY, true);\n mpxjCalendar.setWorkingDay(Day.WEDNESDAY, true);\n mpxjCalendar.setWorkingDay(Day.THURSDAY, true);\n mpxjCalendar.setWorkingDay(Day.FRIDAY, true);\n mpxjCalendar.setWorkingDay(Day.SATURDAY, false);\n }\n else\n {\n mpxjCalendar.setWorkingDay(Day.MONDAY, isWorkingDay(defaultWeek.getMon()));\n mpxjCalendar.setWorkingDay(Day.TUESDAY, isWorkingDay(defaultWeek.getTue()));\n mpxjCalendar.setWorkingDay(Day.WEDNESDAY, isWorkingDay(defaultWeek.getWed()));\n mpxjCalendar.setWorkingDay(Day.THURSDAY, isWorkingDay(defaultWeek.getThu()));\n mpxjCalendar.setWorkingDay(Day.FRIDAY, isWorkingDay(defaultWeek.getFri()));\n mpxjCalendar.setWorkingDay(Day.SATURDAY, isWorkingDay(defaultWeek.getSat()));\n mpxjCalendar.setWorkingDay(Day.SUNDAY, isWorkingDay(defaultWeek.getSun()));\n }\n\n for (Day day : Day.values())\n {\n if (mpxjCalendar.isWorkingDay(day))\n {\n ProjectCalendarHours hours = mpxjCalendar.addCalendarHours(day);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n }", "protected void updateFontTable()\n {\n PDResources resources = pdpage.getResources();\n if (resources != null)\n {\n try\n {\n processFontResources(resources, fontTable);\n } catch (IOException e) {\n log.error(\"Error processing font resources: \"\n + \"Exception: {} {}\", e.getMessage(), e.getClass());\n }\n }\n }", "public boolean setVisibility(final Visibility visibility) {\n if (visibility != mVisibility) {\n Log.d(Log.SUBSYSTEM.WIDGET, TAG, \"setVisibility(%s) for %s\", visibility, getName());\n updateVisibility(visibility);\n mVisibility = visibility;\n return true;\n }\n return false;\n }", "private Auth constructAuth(String authToken, String tokenSecret, String username) throws IOException {\n\n Auth auth = new Auth();\n auth.setToken(authToken);\n auth.setTokenSecret(tokenSecret);\n\n // Prompt to ask what permission is needed: read, update or delete.\n auth.setPermission(Permission.fromString(\"delete\"));\n\n User user = new User();\n // Later change the following 3. Either ask user to pass on command line or read\n // from saved file.\n user.setId(nsid);\n user.setUsername((username));\n user.setRealName(\"\");\n auth.setUser(user);\n this.authStore.store(auth);\n return auth;\n }", "public void setKnots(int[] x, int[] y, byte[] types, int offset, int count) {\n\t\tnumKnots = count;\n\t\txKnots = new int[numKnots];\n\t\tyKnots = new int[numKnots];\n\t\tknotTypes = new byte[numKnots];\n\t\tSystem.arraycopy(x, offset, xKnots, 0, numKnots);\n\t\tSystem.arraycopy(y, offset, yKnots, 0, numKnots);\n\t\tSystem.arraycopy(types, offset, knotTypes, 0, numKnots);\n\t\tsortKnots();\n\t\trebuildGradient();\n\t}" ]
Adds all fields declared in the object's class and its superclasses to the output. @return this
[ "@GwtIncompatible(\"Class.getDeclaredFields\")\n\tpublic ToStringBuilder addAllFields() {\n\t\tList<Field> fields = getAllDeclaredFields(instance.getClass());\n\t\tfor(Field field : fields) {\n\t\t\taddField(field);\n\t\t}\n\t\treturn this;\n\t}" ]
[ "private void performDownload(HttpResponse response, File destFile)\n throws IOException {\n HttpEntity entity = response.getEntity();\n if (entity == null) {\n return;\n }\n \n //get content length\n long contentLength = entity.getContentLength();\n if (contentLength >= 0) {\n size = toLengthText(contentLength);\n }\n \n processedBytes = 0;\n loggedKb = 0;\n \n //open stream and start downloading\n InputStream is = entity.getContent();\n streamAndMove(is, destFile);\n }", "public static boolean compareAnnotatedTypes(AnnotatedType<?> t1, AnnotatedType<?> t2) {\n if (!t1.getJavaClass().equals(t2.getJavaClass())) {\n return false;\n }\n if (!compareAnnotated(t1, t2)) {\n return false;\n }\n\n if (t1.getFields().size() != t2.getFields().size()) {\n return false;\n }\n Map<Field, AnnotatedField<?>> fields = new HashMap<Field, AnnotatedField<?>>();\n for (AnnotatedField<?> f : t2.getFields()) {\n fields.put(f.getJavaMember(), f);\n }\n for (AnnotatedField<?> f : t1.getFields()) {\n if (fields.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedField(f, fields.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n\n if (t1.getMethods().size() != t2.getMethods().size()) {\n return false;\n }\n Map<Method, AnnotatedMethod<?>> methods = new HashMap<Method, AnnotatedMethod<?>>();\n for (AnnotatedMethod<?> f : t2.getMethods()) {\n methods.put(f.getJavaMember(), f);\n }\n for (AnnotatedMethod<?> f : t1.getMethods()) {\n if (methods.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, methods.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n if (t1.getConstructors().size() != t2.getConstructors().size()) {\n return false;\n }\n Map<Constructor<?>, AnnotatedConstructor<?>> constructors = new HashMap<Constructor<?>, AnnotatedConstructor<?>>();\n for (AnnotatedConstructor<?> f : t2.getConstructors()) {\n constructors.put(f.getJavaMember(), f);\n }\n for (AnnotatedConstructor<?> f : t1.getConstructors()) {\n if (constructors.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, constructors.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n return true;\n\n }", "public void setBody(String body) {\n byte[] bytes = body.getBytes(StandardCharsets.UTF_8);\n this.bodyLength = bytes.length;\n this.body = new ByteArrayInputStream(bytes);\n }", "private void readZookeeperConfig() {\n\n try (CuratorFramework curator = CuratorUtil.newAppCurator(config)) {\n curator.start();\n\n accumuloInstance =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_NAME),\n StandardCharsets.UTF_8);\n accumuloInstanceID =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_ID),\n StandardCharsets.UTF_8);\n fluoApplicationID =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID),\n StandardCharsets.UTF_8);\n\n table = new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_TABLE),\n StandardCharsets.UTF_8);\n\n observers = ObserverUtil.load(curator);\n\n config = FluoAdminImpl.mergeZookeeperConfig(config);\n\n // make sure not to include config passed to env, only want config from zookeeper\n appConfig = config.getAppConfiguration();\n } catch (Exception e) {\n throw new IllegalStateException(e);\n }\n }", "public Association getAssociation(String collectionRole) {\n\t\tif ( associations == null ) {\n\t\t\treturn null;\n\t\t}\n\t\treturn associations.get( collectionRole );\n\t}", "public CurrencyQueryBuilder setCurrencyCodes(String... codes) {\n return set(CurrencyQuery.KEY_QUERY_CURRENCY_CODES, Arrays.asList(codes));\n }", "public BoxCollaborationWhitelistExemptTarget.Info getInfo() {\n URL url = COLLABORATION_WHITELIST_EXEMPT_TARGET_ENTRY_URL_TEMPLATE.build(this.getAPI().getBaseURL(),\n this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n return new Info(JsonObject.readFrom(response.getJSON()));\n }", "public static java.sql.Time toTime(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.sql.Time) {\n return (java.sql.Time) value;\n }\n if (value instanceof String) {\n if (\"\".equals((String) value)) {\n return null;\n }\n return new java.sql.Time(IN_TIME_FORMAT.parse((String) value).getTime());\n }\n\n return new java.sql.Time(IN_TIME_FORMAT.parse(value.toString()).getTime());\n }", "private static void listHierarchy(Task task, String indent)\n {\n for (Task child : task.getChildTasks())\n {\n System.out.println(indent + \"Task: \" + child.getName() + \"\\t\" + child.getStart() + \"\\t\" + child.getFinish());\n listHierarchy(child, indent + \" \");\n }\n }" ]
Gets axis dimension @param axis Axis. It might be either {@link Layout.Axis#X X} or {@link Layout.Axis#Y Y} or {@link Layout.Axis#Z Z} @return axis dimension
[ "public float get(Layout.Axis axis) {\n switch (axis) {\n case X:\n return x;\n case Y:\n return y;\n case Z:\n return z;\n default:\n throw new RuntimeAssertion(\"Bad axis specified: %s\", axis);\n }\n }" ]
[ "public static base_responses link(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey linkresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tlinkresources[i] = new sslcertkey();\n\t\t\t\tlinkresources[i].certkey = resources[i].certkey;\n\t\t\t\tlinkresources[i].linkcertkeyname = resources[i].linkcertkeyname;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, linkresources,\"link\");\n\t\t}\n\t\treturn result;\n\t}", "public User getLimits() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIMITS);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element userElement = response.getPayload();\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"nsid\"));\r\n NodeList photoNodes = userElement.getElementsByTagName(\"photos\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element plElement = (Element) photoNodes.item(i);\r\n PhotoLimits pl = new PhotoLimits();\r\n user.setPhotoLimits(pl);\r\n pl.setMaxDisplay(plElement.getAttribute(\"maxdisplaypx\"));\r\n pl.setMaxUpload(plElement.getAttribute(\"maxupload\"));\r\n }\r\n NodeList videoNodes = userElement.getElementsByTagName(\"videos\");\r\n for (int i = 0; i < videoNodes.getLength(); i++) {\r\n Element vlElement = (Element) videoNodes.item(i);\r\n VideoLimits vl = new VideoLimits();\r\n user.setPhotoLimits(vl);\r\n vl.setMaxDuration(vlElement.getAttribute(\"maxduration\"));\r\n vl.setMaxUpload(vlElement.getAttribute(\"maxupload\"));\r\n }\r\n return user;\r\n }", "public List<Object> stepsInstances(List<CandidateSteps> candidateSteps) {\n List<Object> instances = new ArrayList<>();\n for (CandidateSteps steps : candidateSteps) {\n if (steps instanceof Steps) {\n instances.add(((Steps) steps).instance());\n }\n }\n return instances;\n }", "@Override\n\tpublic void processItemDocument(ItemDocument itemDocument) {\n\t\tthis.countItems++;\n\n\t\t// Do some printing for demonstration/debugging.\n\t\t// Only print at most 50 items (or it would get too slow).\n\t\tif (this.countItems < 10) {\n\t\t\tSystem.out.println(itemDocument);\n\t\t} else if (this.countItems == 10) {\n\t\t\tSystem.out.println(\"*** I won't print any further items.\\n\"\n\t\t\t\t\t+ \"*** We will never finish if we print all the items.\\n\"\n\t\t\t\t\t+ \"*** Maybe remove this debug output altogether.\");\n\t\t}\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 final void info(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.INFO, pObject, null);\r\n\t}", "public static void writeUnsignedShort(byte[] bytes, int value, int offset) {\n bytes[offset] = (byte) (0xFF & (value >> 8));\n bytes[offset + 1] = (byte) (0xFF & value);\n }", "protected void writeBody(HttpURLConnection connection, ProgressListener listener) {\n if (this.body == null) {\n return;\n }\n\n connection.setDoOutput(true);\n try {\n OutputStream output = connection.getOutputStream();\n if (listener != null) {\n output = new ProgressOutputStream(output, listener, this.bodyLength);\n }\n int b = this.body.read();\n while (b != -1) {\n output.write(b);\n b = this.body.read();\n }\n output.close();\n } catch (IOException e) {\n throw new BoxAPIException(\"Couldn't connect to the Box API due to a network error.\", e);\n }\n }", "private void validateAsMongoDBFieldName(String fieldName) {\n\t\tif ( fieldName.startsWith( \"$\" ) ) {\n\t\t\tthrow log.fieldNameHasInvalidDollarPrefix( fieldName );\n\t\t}\n\t\telse if ( fieldName.contains( \"\\u0000\" ) ) {\n\t\t\tthrow log.fieldNameContainsNULCharacter( fieldName );\n\t\t}\n\t}" ]
Read all resource assignments from a GanttProject project. @param gpProject GanttProject project
[ "private void readResourceAssignments(Project gpProject)\n {\n Allocations allocations = gpProject.getAllocations();\n if (allocations != null)\n {\n for (Allocation allocation : allocations.getAllocation())\n {\n readResourceAssignment(allocation);\n }\n }\n }" ]
[ "public static sslservice[] get(nitro_service service, sslservice_args args) throws Exception{\n\t\tsslservice obj = new sslservice();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tsslservice[] response = (sslservice[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public static void openLogFile() throws IOException\n {\n if (LOG_FILE != null)\n {\n System.out.println(\"SynchroLogger Configured\");\n LOG = new PrintWriter(new FileWriter(LOG_FILE));\n }\n }", "@SuppressWarnings(\"unchecked\") public Relation addPredecessor(Task targetTask, RelationType type, Duration lag)\n {\n //\n // Ensure that we have a valid lag duration\n //\n if (lag == null)\n {\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n\n //\n // Retrieve the list of predecessors\n //\n List<Relation> predecessorList = (List<Relation>) getCachedValue(TaskField.PREDECESSORS);\n\n //\n // Ensure that there is only one predecessor relationship between\n // these two tasks.\n //\n Relation predecessorRelation = null;\n Iterator<Relation> iter = predecessorList.iterator();\n while (iter.hasNext() == true)\n {\n predecessorRelation = iter.next();\n if (predecessorRelation.getTargetTask() == targetTask)\n {\n if (predecessorRelation.getType() != type || predecessorRelation.getLag().compareTo(lag) != 0)\n {\n predecessorRelation = null;\n }\n break;\n }\n predecessorRelation = null;\n }\n\n //\n // If necessary, create a new predecessor relationship\n //\n if (predecessorRelation == null)\n {\n predecessorRelation = new Relation(this, targetTask, type, lag);\n predecessorList.add(predecessorRelation);\n }\n\n //\n // Retrieve the list of successors\n //\n List<Relation> successorList = (List<Relation>) targetTask.getCachedValue(TaskField.SUCCESSORS);\n\n //\n // Ensure that there is only one successor relationship between\n // these two tasks.\n //\n Relation successorRelation = null;\n iter = successorList.iterator();\n while (iter.hasNext() == true)\n {\n successorRelation = iter.next();\n if (successorRelation.getTargetTask() == this)\n {\n if (successorRelation.getType() != type || successorRelation.getLag().compareTo(lag) != 0)\n {\n successorRelation = null;\n }\n break;\n }\n successorRelation = null;\n }\n\n //\n // If necessary, create a new successor relationship\n //\n if (successorRelation == null)\n {\n successorRelation = new Relation(targetTask, this, type, lag);\n successorList.add(successorRelation);\n }\n\n return (predecessorRelation);\n }", "public void setGamma(float rGamma, float gGamma, float bGamma) {\n\t\tthis.rGamma = rGamma;\n\t\tthis.gGamma = gGamma;\n\t\tthis.bGamma = bGamma;\n\t\tinitialized = false;\n\t}", "private void readPredecessors(net.sf.mpxj.planner.schema.Task plannerTask)\n {\n Task mpxjTask = m_projectFile.getTaskByUniqueID(getInteger(plannerTask.getId()));\n\n Predecessors predecessors = plannerTask.getPredecessors();\n if (predecessors != null)\n {\n List<Predecessor> predecessorList = predecessors.getPredecessor();\n for (Predecessor predecessor : predecessorList)\n {\n Integer predecessorID = getInteger(predecessor.getPredecessorId());\n Task predecessorTask = m_projectFile.getTaskByUniqueID(predecessorID);\n if (predecessorTask != null)\n {\n Duration lag = getDuration(predecessor.getLag());\n if (lag == null)\n {\n lag = Duration.getInstance(0, TimeUnit.HOURS);\n }\n Relation relation = mpxjTask.addPredecessor(predecessorTask, RELATIONSHIP_TYPES.get(predecessor.getType()), lag);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }\n\n //\n // Process child tasks\n //\n List<net.sf.mpxj.planner.schema.Task> childTasks = plannerTask.getTask();\n for (net.sf.mpxj.planner.schema.Task childTask : childTasks)\n {\n readPredecessors(childTask);\n }\n }", "private boolean checkConverged(DMatrixRMaj A) {\n double worst = 0;\n double worst2 = 0;\n for( int j = 0; j < A.numRows; j++ ) {\n double val = Math.abs(q2.data[j] - q0.data[j]);\n if( val > worst ) worst = val;\n val = Math.abs(q2.data[j] + q0.data[j]);\n if( val > worst2 ) worst2 = val;\n }\n\n // swap vectors\n DMatrixRMaj temp = q0;\n q0 = q2;\n q2 = temp;\n\n if( worst < tol )\n return true;\n else if( worst2 < tol )\n return true;\n else\n return false;\n }", "public static ModelNode getParentAddress(final ModelNode address) {\n if (address.getType() != ModelType.LIST) {\n throw new IllegalArgumentException(\"The address type must be a list.\");\n }\n final ModelNode result = new ModelNode();\n final List<Property> addressParts = address.asPropertyList();\n if (addressParts.isEmpty()) {\n throw new IllegalArgumentException(\"The address is empty.\");\n }\n for (int i = 0; i < addressParts.size() - 1; ++i) {\n final Property property = addressParts.get(i);\n result.add(property.getName(), property.getValue());\n }\n return result;\n }", "public static Boolean compareSingleClientConfigAvro(String configAvro1, String configAvro2) {\n Properties props1 = readSingleClientConfigAvro(configAvro1);\n Properties props2 = readSingleClientConfigAvro(configAvro2);\n if(props1.equals(props2)) {\n return true;\n } else {\n return false;\n }\n }", "private <Y> void checkObserverMethod(EnhancedAnnotatedMethod<T, Y> annotated) {\n // Make sure exactly one and only one parameter is annotated with Observes or ObservesAsync\n List<EnhancedAnnotatedParameter<?, Y>> eventObjects = annotated.getEnhancedParameters(Observes.class);\n eventObjects.addAll(annotated.getEnhancedParameters(ObservesAsync.class));\n if (this.reception.equals(Reception.IF_EXISTS) && declaringBean.getScope().equals(Dependent.class)) {\n throw EventLogger.LOG.invalidScopedConditionalObserver(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n if (eventObjects.size() > 1) {\n throw EventLogger.LOG.multipleEventParameters(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n EnhancedAnnotatedParameter<?, Y> eventParameter = eventObjects.iterator().next();\n checkRequiredTypeAnnotations(eventParameter);\n // Check for parameters annotated with @Disposes\n List<?> disposeParams = annotated.getEnhancedParameters(Disposes.class);\n if (disposeParams.size() > 0) {\n throw EventLogger.LOG.invalidDisposesParameter(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n // Check annotations on the method to make sure this is not a producer\n // method, initializer method, or destructor method.\n if (this.observerMethod.getAnnotated().isAnnotationPresent(Produces.class)) {\n throw EventLogger.LOG.invalidProducer(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n if (this.observerMethod.getAnnotated().isAnnotationPresent(Inject.class)) {\n throw EventLogger.LOG.invalidInitializer(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n boolean containerLifecycleObserverMethod = Observers.isContainerLifecycleObserverMethod(this);\n for (EnhancedAnnotatedParameter<?, ?> parameter : annotated.getEnhancedParameters()) {\n // if this is an observer method for container lifecycle event, it must not inject anything besides BeanManager\n if (containerLifecycleObserverMethod && !parameter.isAnnotationPresent(Observes.class) && !parameter.isAnnotationPresent(ObservesAsync.class) && !BeanManager.class.equals(parameter.getBaseType())) {\n throw EventLogger.LOG.invalidInjectionPoint(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n }\n\n }" ]
Transform the root bone of the pose by the given matrix. @param trans matrix to transform the pose by.
[ "public void transformPose(Matrix4f trans)\n {\n Bone bone = mBones[0];\n\n bone.LocalMatrix.set(trans);\n bone.WorldMatrix.set(trans);\n bone.Changed = WORLD_POS | WORLD_ROT;\n mNeedSync = true;\n sync();\n }" ]
[ "public void removeHoursFromDay(ProjectCalendarHours hours)\n {\n if (hours.getParentCalendar() != this)\n {\n throw new IllegalArgumentException();\n }\n m_hours[hours.getDay().getValue() - 1] = null;\n }", "private Duration getDuration(TimeUnit units, Double duration)\n {\n Duration result = null;\n if (duration != null)\n {\n double durationValue = duration.doubleValue() * 100.0;\n\n switch (units)\n {\n case MINUTES:\n {\n durationValue *= MINUTES_PER_DAY;\n break;\n }\n\n case HOURS:\n {\n durationValue *= HOURS_PER_DAY;\n break;\n }\n\n case DAYS:\n {\n durationValue *= 3.0;\n break;\n }\n\n case WEEKS:\n {\n durationValue *= 0.6;\n break;\n }\n\n case MONTHS:\n {\n durationValue *= 0.15;\n break;\n }\n\n default:\n {\n throw new IllegalArgumentException(\"Unsupported time units \" + units);\n }\n }\n\n durationValue = Math.round(durationValue) / 100.0;\n\n result = Duration.getInstance(durationValue, units);\n }\n\n return result;\n }", "public static base_responses kill(nitro_service client, systemsession resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsystemsession killresources[] = new systemsession[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tkillresources[i] = new systemsession();\n\t\t\t\tkillresources[i].sid = resources[i].sid;\n\t\t\t\tkillresources[i].all = resources[i].all;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, killresources,\"kill\");\n\t\t}\n\t\treturn result;\n\t}", "public void sendMessageToAgentsWithExtraProperties(String[] agent_name,\n String msgtype, Object message_content,\n ArrayList<Object> properties, Connector connector) {\n HashMap<String, Object> hm = new HashMap<String, Object>();\n hm.put(\"performative\", msgtype);\n hm.put(SFipa.CONTENT, message_content);\n\n for (Object property : properties) {\n // Logger logger = Logger.getLogger(\"JadexMessenger\");\n // logger.info(\"Sending message with extra property: \"+property.get(0)+\", with value \"+property.get(1));\n hm.put((String) ((Tuple) property).get(0), ((Tuple) property).get(1));\n }\n\n IComponentIdentifier[] ici = new IComponentIdentifier[agent_name.length];\n for (int i = 0; i < agent_name.length; i++) {\n ici[i] = (IComponentIdentifier) connector.getAgentID(agent_name[i]);\n }\n ((IMessageService) connector.getMessageService()).deliverMessage(hm,\n \"fipa\", ici);\n }", "public void createEnvironment(@Observes(precedence = 10) BeforeClass event, OpenShiftAdapter client,\n CubeOpenShiftConfiguration cubeOpenShiftConfiguration) {\n final TestClass testClass = event.getTestClass();\n log.info(String.format(\"Creating environment for %s\", testClass.getName()));\n OpenShiftResourceFactory.createResources(testClass.getName(), client, testClass.getJavaClass(),\n cubeOpenShiftConfiguration.getProperties());\n classTemplateProcessor = new ClassTemplateProcessor(client, cubeOpenShiftConfiguration, testClass);\n final List<? extends OpenShiftResource> templateResources = classTemplateProcessor.processTemplateResources();\n templateDetailsProducer.set(() -> templateResources);\n }", "private void getWeeklyDates(Calendar calendar, int frequency, List<Date> dates)\n {\n int currentDay = calendar.get(Calendar.DAY_OF_WEEK);\n\n while (moreDates(calendar, dates))\n {\n int offset = 0;\n for (int dayIndex = 0; dayIndex < 7; dayIndex++)\n {\n if (getWeeklyDay(Day.getInstance(currentDay)))\n {\n if (offset != 0)\n {\n calendar.add(Calendar.DAY_OF_YEAR, offset);\n offset = 0;\n }\n if (!moreDates(calendar, dates))\n {\n break;\n }\n dates.add(calendar.getTime());\n }\n\n ++offset;\n ++currentDay;\n\n if (currentDay > 7)\n {\n currentDay = 1;\n }\n }\n\n if (frequency > 1)\n {\n offset += (7 * (frequency - 1));\n }\n calendar.add(Calendar.DAY_OF_YEAR, offset);\n }\n }", "private int getCacheKey(InputDevice device, GVRControllerType controllerType) {\n if (controllerType != GVRControllerType.UNKNOWN &&\n controllerType != GVRControllerType.EXTERNAL) {\n // Sometimes a device shows up using two device ids\n // here we try to show both devices as one using the\n // product and vendor id\n\n int key = device.getVendorId();\n key = 31 * key + device.getProductId();\n key = 31 * key + controllerType.hashCode();\n\n return key;\n }\n return -1; // invalid key\n }", "Map<Object, Object> getFilters() {\n\n Map<Object, Object> result = new HashMap<Object, Object>(4);\n result.put(TableProperty.KEY, m_table.getFilterFieldValue(TableProperty.KEY));\n result.put(TableProperty.DEFAULT, m_table.getFilterFieldValue(TableProperty.DEFAULT));\n result.put(TableProperty.DESCRIPTION, m_table.getFilterFieldValue(TableProperty.DESCRIPTION));\n result.put(TableProperty.TRANSLATION, m_table.getFilterFieldValue(TableProperty.TRANSLATION));\n return result;\n }", "private void processUpdate(DeviceUpdate update) {\n updates.put(update.getAddress(), update);\n\n // Keep track of the largest sync number we see.\n if (update instanceof CdjStatus) {\n int syncNumber = ((CdjStatus)update).getSyncNumber();\n if (syncNumber > this.largestSyncCounter.get()) {\n this.largestSyncCounter.set(syncNumber);\n }\n }\n\n // Deal with the tempo master complexities, including handoff to/from us.\n if (update.isTempoMaster()) {\n final Integer packetYieldingTo = update.getDeviceMasterIsBeingYieldedTo();\n if (packetYieldingTo == null) {\n // This is a normal, non-yielding master packet. Update our notion of the current master, and,\n // if we were yielding, finish that process, updating our sync number appropriately.\n if (master.get()) {\n if (nextMaster.get() == update.deviceNumber) {\n syncCounter.set(largestSyncCounter.get() + 1);\n } else {\n if (nextMaster.get() == 0xff) {\n logger.warn(\"Saw master asserted by player \" + update.deviceNumber +\n \" when we were not yielding it.\");\n } else {\n logger.warn(\"Expected to yield master role to player \" + nextMaster.get() +\n \" but saw master asserted by player \" + update.deviceNumber);\n }\n }\n }\n master.set(false);\n nextMaster.set(0xff);\n setTempoMaster(update);\n setMasterTempo(update.getEffectiveTempo());\n } else {\n // This is a yielding master packet. If it is us that is being yielded to, take over master.\n // Log a message if it was unsolicited, and a warning if it's coming from a different player than\n // we asked.\n if (packetYieldingTo == getDeviceNumber()) {\n if (update.deviceNumber != masterYieldedFrom.get()) {\n if (masterYieldedFrom.get() == 0) {\n logger.info(\"Accepting unsolicited Master yield; we must be the only synced device playing.\");\n } else {\n logger.warn(\"Expected player \" + masterYieldedFrom.get() + \" to yield master to us, but player \" +\n update.deviceNumber + \" did.\");\n }\n }\n master.set(true);\n masterYieldedFrom.set(0);\n setTempoMaster(null);\n setMasterTempo(getTempo());\n }\n }\n } else {\n // This update was not acting as a tempo master; if we thought it should be, update our records.\n DeviceUpdate oldMaster = getTempoMaster();\n if (oldMaster != null && oldMaster.getAddress().equals(update.getAddress())) {\n // This device has resigned master status, and nobody else has claimed it so far\n setTempoMaster(null);\n }\n }\n deliverDeviceUpdate(update);\n }" ]
removes all timed out lock entries from the persistent storage. The timeout value can be set in the OJB properties file.
[ "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 }" ]
[ "public FastReportBuilder addBarcodeColumn(String title, String property,String className, int barcodeType,boolean showText, int width, boolean fixedWidth,ImageScaleMode imageScaleMode, Style style) throws ColumnBuilderException, ClassNotFoundException {\n\t\tAbstractColumn column = ColumnBuilder.getNew()\n\t\t.setColumnProperty(property, className)\n\t\t.setWidth(width)\n\t\t.setTitle(title)\n\t\t.setFixedWidth(fixedWidth)\n\t\t.setColumnType(ColumnBuilder.COLUMN_TYPE_BARCODE)\n\t\t.setStyle(style)\n\t\t.setBarcodeType(barcodeType)\n\t\t.setShowText(showText)\n\t\t.build();\n\n\t\tif (style == null)\n\t\t\tguessStyle(className, column);\n\n\t\taddColumn(column);\n\n\t\treturn this;\n\t}", "public MaterializeBuilder withActivity(Activity activity) {\n this.mRootView = (ViewGroup) activity.findViewById(android.R.id.content);\n this.mActivity = activity;\n return this;\n }", "public static cachepolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tcachepolicylabel_binding obj = new cachepolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcachepolicylabel_binding response = (cachepolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "static Date parseDate(String dateString) {\n try {\n return DATE_FORMAT.parseDateTime(dateString).toDate();\n } catch (IllegalArgumentException e) {\n return null;\n }\n }", "public static <T> T[] concat(T firstElement, T... array) {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT[] result = (T[]) Array.newInstance( firstElement.getClass(), 1 + array.length );\n\t\tresult[0] = firstElement;\n\t\tSystem.arraycopy( array, 0, result, 1, array.length );\n\n\t\treturn result;\n\t}", "private Date readOptionalDate(JSONValue val) {\n\n JSONString str = null == val ? null : val.isString();\n if (str != null) {\n try {\n return new Date(Long.parseLong(str.stringValue()));\n } catch (@SuppressWarnings(\"unused\") NumberFormatException e) {\n // do nothing - return the default value\n }\n }\n return null;\n }", "public static <E> Set<E> intersection(Set<E> s1, Set<E> s2) {\r\n Set<E> s = new HashSet<E>();\r\n s.addAll(s1);\r\n s.retainAll(s2);\r\n return s;\r\n }", "public void set(int i, double value) {\n switch (i) {\n case 0: {\n x = value;\n break;\n }\n case 1: {\n y = value;\n break;\n }\n case 2: {\n z = value;\n break;\n }\n default: {\n throw new ArrayIndexOutOfBoundsException(i);\n }\n }\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 }" ]
Send a get module request @param name @param version @return the targeted module @throws GrapesCommunicationException
[ "public Module getModule(final String name, final String version) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getModulePath(name, version));\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 = String.format(FAILED_TO_GET_MODULE, \"get module details\", name, version);\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(Module.class);\n }" ]
[ "@UiThread\n public int getParentAdapterPosition() {\n int flatPosition = getAdapterPosition();\n if (mExpandableAdapter == null || flatPosition == RecyclerView.NO_POSITION) {\n return RecyclerView.NO_POSITION;\n }\n\n return mExpandableAdapter.getNearestParentPosition(flatPosition);\n }", "public static dnspolicy_dnsglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tdnspolicy_dnsglobal_binding obj = new dnspolicy_dnsglobal_binding();\n\t\tobj.set_name(name);\n\t\tdnspolicy_dnsglobal_binding response[] = (dnspolicy_dnsglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private String getDurationString(Duration value)\n {\n String result = null;\n\n if (value != null)\n {\n double seconds = 0;\n\n switch (value.getUnits())\n {\n case MINUTES:\n case ELAPSED_MINUTES:\n {\n seconds = value.getDuration() * 60;\n break;\n }\n\n case HOURS:\n case ELAPSED_HOURS:\n {\n seconds = value.getDuration() * (60 * 60);\n break;\n }\n\n case DAYS:\n {\n double minutesPerDay = m_projectFile.getProjectProperties().getMinutesPerDay().doubleValue();\n seconds = value.getDuration() * (minutesPerDay * 60);\n break;\n }\n\n case ELAPSED_DAYS:\n {\n seconds = value.getDuration() * (24 * 60 * 60);\n break;\n }\n\n case WEEKS:\n {\n double minutesPerWeek = m_projectFile.getProjectProperties().getMinutesPerWeek().doubleValue();\n seconds = value.getDuration() * (minutesPerWeek * 60);\n break;\n }\n\n case ELAPSED_WEEKS:\n {\n seconds = value.getDuration() * (7 * 24 * 60 * 60);\n break;\n }\n\n case MONTHS:\n {\n double minutesPerDay = m_projectFile.getProjectProperties().getMinutesPerDay().doubleValue();\n double daysPerMonth = m_projectFile.getProjectProperties().getDaysPerMonth().doubleValue();\n seconds = value.getDuration() * (daysPerMonth * minutesPerDay * 60);\n break;\n }\n\n case ELAPSED_MONTHS:\n {\n seconds = value.getDuration() * (30 * 24 * 60 * 60);\n break;\n }\n\n case YEARS:\n {\n double minutesPerDay = m_projectFile.getProjectProperties().getMinutesPerDay().doubleValue();\n double daysPerMonth = m_projectFile.getProjectProperties().getDaysPerMonth().doubleValue();\n seconds = value.getDuration() * (12 * daysPerMonth * minutesPerDay * 60);\n break;\n }\n\n case ELAPSED_YEARS:\n {\n seconds = value.getDuration() * (365 * 24 * 60 * 60);\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n result = Long.toString((long) seconds);\n }\n\n return (result);\n }", "public List<DbLicense> getModuleLicenses(final String moduleId,\n final LicenseMatcher licenseMatcher) {\n final DbModule module = getModule(moduleId);\n\n final List<DbLicense> licenses = new ArrayList<>();\n final FiltersHolder filters = new FiltersHolder();\n final ArtifactHandler artifactHandler = new ArtifactHandler(repositoryHandler, licenseMatcher);\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n licenses.addAll(artifactHandler.getArtifactLicenses(gavc, filters));\n }\n\n return licenses;\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 }", "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 synchronized LogContext configureLogContext(final File logDir, final File configDir, final String defaultLogFileName, final CommandContext ctx) {\n final LogContext embeddedLogContext = Holder.LOG_CONTEXT;\n final Path bootLog = logDir.toPath().resolve(Paths.get(defaultLogFileName));\n final Path loggingProperties = configDir.toPath().resolve(Paths.get(\"logging.properties\"));\n if (Files.exists(loggingProperties)) {\n WildFlySecurityManager.setPropertyPrivileged(\"org.jboss.boot.log.file\", bootLog.toAbsolutePath().toString());\n\n try (final InputStream in = Files.newInputStream(loggingProperties)) {\n // Attempt to get the configurator from the root logger\n Configurator configurator = embeddedLogContext.getAttachment(\"\", Configurator.ATTACHMENT_KEY);\n if (configurator == null) {\n configurator = new PropertyConfigurator(embeddedLogContext);\n final Configurator existing = embeddedLogContext.getLogger(\"\").attachIfAbsent(Configurator.ATTACHMENT_KEY, configurator);\n if (existing != null) {\n configurator = existing;\n }\n }\n configurator.configure(in);\n } catch (IOException e) {\n ctx.printLine(String.format(\"Unable to configure logging from configuration file %s. Reason: %s\", loggingProperties, e.getLocalizedMessage()));\n }\n }\n return embeddedLogContext;\n }", "public void setSessionTimeout(int timeout) {\n ((ZKBackend) getBackend()).setSessionTimeout(timeout);\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Locator session timeout set to: \" + timeout);\n }\n }", "public final Object getValue(final String id, final String property) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaQuery<Object> criteria = builder.createQuery(Object.class);\n final Root<PrintJobStatusExtImpl> root = criteria.from(PrintJobStatusExtImpl.class);\n criteria.select(root.get(property));\n criteria.where(builder.equal(root.get(\"referenceId\"), id));\n return getSession().createQuery(criteria).uniqueResult();\n }" ]
Return the set of synchronized document _ids in a namespace that have been paused due to an irrecoverable error. @param namespace the namespace to get paused document _ids for. @return the set of paused document _ids in a namespace
[ "public Set<BsonValue> getPausedDocumentIds(final MongoNamespace namespace) {\n this.waitUntilInitialized();\n\n try {\n ongoingOperationsGroup.enter();\n final Set<BsonValue> pausedDocumentIds = new HashSet<>();\n\n for (final CoreDocumentSynchronizationConfig config :\n this.syncConfig.getSynchronizedDocuments(namespace)) {\n if (config.isPaused()) {\n pausedDocumentIds.add(config.getDocumentId());\n }\n }\n\n return pausedDocumentIds;\n } finally {\n ongoingOperationsGroup.exit();\n }\n }" ]
[ "public int getModifiers() {\n MetaMethod getter = getGetter();\n MetaMethod setter = getSetter();\n if (setter != null && getter == null) return setter.getModifiers();\n if (getter != null && setter == null) return getter.getModifiers();\n int modifiers = getter.getModifiers() | setter.getModifiers();\n int visibility = 0;\n if (Modifier.isPublic(modifiers)) visibility = Modifier.PUBLIC;\n if (Modifier.isProtected(modifiers)) visibility = Modifier.PROTECTED;\n if (Modifier.isPrivate(modifiers)) visibility = Modifier.PRIVATE;\n int states = getter.getModifiers() & setter.getModifiers();\n states &= ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE);\n states |= visibility;\n return states;\n }", "public static void dumpRow(Map<String, Object> row)\n {\n for (Entry<String, Object> entry : row.entrySet())\n {\n Object value = entry.getValue();\n System.out.println(entry.getKey() + \" = \" + value + \" ( \" + (value == null ? \"\" : value.getClass().getName()) + \")\");\n }\n }", "public static NodeCache startAppIdWatcher(Environment env) {\n try {\n CuratorFramework curator = env.getSharedResources().getCurator();\n\n byte[] uuidBytes = curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);\n if (uuidBytes == null) {\n Halt.halt(\"Fluo Application UUID not found\");\n throw new RuntimeException(); // make findbugs happy\n }\n\n final String uuid = new String(uuidBytes, StandardCharsets.UTF_8);\n\n final NodeCache nodeCache = new NodeCache(curator, ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);\n nodeCache.getListenable().addListener(() -> {\n ChildData node = nodeCache.getCurrentData();\n if (node == null || !uuid.equals(new String(node.getData(), StandardCharsets.UTF_8))) {\n Halt.halt(\"Fluo Application UUID has changed or disappeared\");\n }\n });\n nodeCache.start();\n return nodeCache;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "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 }", "@Override\n public Configuration configuration() {\n return new MostUsefulConfiguration()\n // where to find the stories\n .useStoryLoader(new LoadFromClasspath(this.getClass())) \n // CONSOLE and TXT reporting\n .useStoryReporterBuilder(new StoryReporterBuilder().withDefaultFormats().withFormats(Format.CONSOLE, Format.TXT)); \n }", "public static ConsistencyLevel determineConsistency(Map<Value, Set<ClusterNode>> versionNodeSetMap,\n int replicationFactor) {\n boolean fullyConsistent = true;\n Value latestVersion = null;\n for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : versionNodeSetMap.entrySet()) {\n Value value = versionNodeSetEntry.getKey();\n if (latestVersion == null) {\n latestVersion = value;\n } else if (value.isTimeStampLaterThan(latestVersion)) {\n latestVersion = value;\n }\n Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue();\n fullyConsistent = fullyConsistent && (nodeSet.size() == replicationFactor);\n }\n if (fullyConsistent) {\n return ConsistencyLevel.FULL;\n } else {\n // latest write consistent, effectively consistent\n if (latestVersion != null && versionNodeSetMap.get(latestVersion).size() == replicationFactor) {\n return ConsistencyLevel.LATEST_CONSISTENT;\n }\n // all other states inconsistent\n return ConsistencyLevel.INCONSISTENT;\n }\n }", "public static void resize(GVRMesh mesh, float size) {\n float dim[] = getBoundingSize(mesh);\n float maxsize = 0.0f;\n\n if (dim[0] > maxsize) maxsize = dim[0];\n if (dim[1] > maxsize) maxsize = dim[1];\n if (dim[2] > maxsize) maxsize = dim[2];\n\n scale(mesh, size / maxsize);\n }", "private void writeCalendars(List<ProjectCalendar> records)\n {\n\n //\n // Write project calendars\n //\n for (ProjectCalendar record : records)\n {\n m_buffer.setLength(0);\n m_buffer.append(\"CLDR \");\n m_buffer.append(SDEFmethods.lset(record.getUniqueID().toString(), 2)); // 2 character used, USACE allows 1\n String workDays = SDEFmethods.workDays(record); // custom line, like NYYYYYN for a week\n m_buffer.append(SDEFmethods.lset(workDays, 8));\n m_buffer.append(SDEFmethods.lset(record.getName(), 30));\n m_writer.println(m_buffer);\n }\n }", "public static base_responses update(nitro_service client, gslbsite resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbsite updateresources[] = new gslbsite[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new gslbsite();\n\t\t\t\tupdateresources[i].sitename = resources[i].sitename;\n\t\t\t\tupdateresources[i].metricexchange = resources[i].metricexchange;\n\t\t\t\tupdateresources[i].nwmetricexchange = resources[i].nwmetricexchange;\n\t\t\t\tupdateresources[i].sessionexchange = resources[i].sessionexchange;\n\t\t\t\tupdateresources[i].triggermonitor = resources[i].triggermonitor;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Filter unsafe or unnecessary request. @param nodeDataMapValidSource the node data map valid source @param nodeDataMapValidSafe the node data map valid safe
[ "public void filterUnsafeOrUnnecessaryRequest(\n Map<String, NodeReqResponse> nodeDataMapValidSource,\n Map<String, NodeReqResponse> nodeDataMapValidSafe) {\n\n for (Entry<String, NodeReqResponse> entry : nodeDataMapValidSource\n .entrySet()) {\n\n String hostName = entry.getKey();\n NodeReqResponse nrr = entry.getValue();\n\n Map<String, String> map = nrr.getRequestParameters();\n\n /**\n * 20130507: will generally apply to all requests: if have this\n * field and this field is false\n */\n if (map.containsKey(PcConstants.NODE_REQUEST_WILL_EXECUTE)) {\n Boolean willExecute = Boolean.parseBoolean(map\n .get(PcConstants.NODE_REQUEST_WILL_EXECUTE));\n\n if (!willExecute) {\n logger.info(\"NOT_EXECUTE_COMMAND \" + \" on target: \"\n + hostName + \" at \"\n + PcDateUtils.getNowDateTimeStrStandard());\n continue;\n }\n }\n\n // now safely to add this node in.\n nodeDataMapValidSafe.put(hostName, nrr);\n }// end for loop\n\n }" ]
[ "private ModelNode createOSNode() throws OperationFailedException {\n String osName = getProperty(\"os.name\");\n final ModelNode os = new ModelNode();\n if (osName != null && osName.toLowerCase().contains(\"linux\")) {\n try {\n os.set(GnuLinuxDistribution.discover());\n } catch (IOException ex) {\n throw new OperationFailedException(ex);\n }\n } else {\n os.set(osName);\n }\n return os;\n }", "private Map<Integer, Integer> getNodeIdToNaryCount(Cluster cluster,\n StoreRoutingPlan storeRoutingPlan) {\n Map<Integer, Integer> nodeIdToNaryCount = Maps.newHashMap();\n\n for(int nodeId: cluster.getNodeIds()) {\n nodeIdToNaryCount.put(nodeId, storeRoutingPlan.getZoneNAryPartitionIds(nodeId).size());\n }\n\n return nodeIdToNaryCount;\n }", "public void scrollOnce() {\n PagerAdapter adapter = getAdapter();\n int currentItem = getCurrentItem();\n int totalCount;\n if (adapter == null || (totalCount = adapter.getCount()) <= 1) {\n return;\n }\n\n int nextItem = (direction == LEFT) ? --currentItem : ++currentItem;\n if (nextItem < 0) {\n if (isCycle) {\n setCurrentItem(totalCount - 1, isBorderAnimation);\n }\n } else if (nextItem == totalCount) {\n if (isCycle) {\n setCurrentItem(0, isBorderAnimation);\n }\n } else {\n setCurrentItem(nextItem, true);\n }\n }", "public static synchronized void clearDaoCache() {\n\t\tif (classMap != null) {\n\t\t\tclassMap.clear();\n\t\t\tclassMap = null;\n\t\t}\n\t\tif (tableConfigMap != null) {\n\t\t\ttableConfigMap.clear();\n\t\t\ttableConfigMap = null;\n\t\t}\n\t}", "public Metadata replace(String path, String value) {\n this.values.set(this.pathToProperty(path), value);\n this.addOp(\"replace\", path, value);\n return this;\n }", "public void 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 }", "public static Comment createComment(final String entityId,\n\t\t\t\t\t\t\t\t\t\tfinal String entityType,\n\t\t\t\t\t\t\t\t\t\tfinal String action,\n\t\t\t\t\t\t\t\t\t\tfinal String commentedText,\n\t\t\t\t\t\t\t\t\t\tfinal String user,\n\t\t\t\t\t\t\t\t\t\tfinal Date date) {\n\n\t\tfinal Comment comment = new Comment();\n\t\tcomment.setEntityId(entityId);\n\t\tcomment.setEntityType(entityType);\n\t\tcomment.setAction(action);\n\t\tcomment.setCommentText(commentedText);\n\t\tcomment.setCommentedBy(user);\n\t\tcomment.setCreatedDateTime(date);\n\t\treturn comment;\n\t}", "public static base_response update(nitro_service client, nd6ravariables resource) throws Exception {\n\t\tnd6ravariables updateresource = new nd6ravariables();\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.ceaserouteradv = resource.ceaserouteradv;\n\t\tupdateresource.sendrouteradv = resource.sendrouteradv;\n\t\tupdateresource.srclinklayeraddroption = resource.srclinklayeraddroption;\n\t\tupdateresource.onlyunicastrtadvresponse = resource.onlyunicastrtadvresponse;\n\t\tupdateresource.managedaddrconfig = resource.managedaddrconfig;\n\t\tupdateresource.otheraddrconfig = resource.otheraddrconfig;\n\t\tupdateresource.currhoplimit = resource.currhoplimit;\n\t\tupdateresource.maxrtadvinterval = resource.maxrtadvinterval;\n\t\tupdateresource.minrtadvinterval = resource.minrtadvinterval;\n\t\tupdateresource.linkmtu = resource.linkmtu;\n\t\tupdateresource.reachabletime = resource.reachabletime;\n\t\tupdateresource.retranstime = resource.retranstime;\n\t\tupdateresource.defaultlifetime = resource.defaultlifetime;\n\t\treturn updateresource.update_resource(client);\n\t}", "public Duration getFinishVariance()\n {\n Duration variance = (Duration) getCachedValue(AssignmentField.FINISH_VARIANCE);\n if (variance == null)\n {\n TimeUnit format = getParentFile().getProjectProperties().getDefaultDurationUnits();\n variance = DateHelper.getVariance(getTask(), getBaselineFinish(), getFinish(), format);\n set(AssignmentField.FINISH_VARIANCE, variance);\n }\n return (variance);\n }" ]
return a prepared Insert Statement fitting for the given ClassDescriptor
[ "public PreparedStatement getInsertStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getInsertStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }" ]
[ "private T getWrappedPublisher(Publisher flexiblePublisher, Class<T> type) {\n if (!(flexiblePublisher instanceof FlexiblePublisher)) {\n throw new IllegalArgumentException(String.format(\"Publisher should be of type: '%s'. Found type: '%s'\",\n FlexiblePublisher.class, flexiblePublisher.getClass()));\n }\n\n List<ConditionalPublisher> conditions = ((FlexiblePublisher) flexiblePublisher).getPublishers();\n for (ConditionalPublisher condition : conditions) {\n if (type.isInstance(condition.getPublisher())) {\n return type.cast(condition.getPublisher());\n }\n }\n\n return null;\n }", "public static Class<?>[] toClassArray(Collection<Class<?>> collection) {\n\t\tif (collection == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn collection.toArray(new Class<?>[collection.size()]);\n\t}", "private void parseMacro( TokenList tokens , Sequence sequence ) {\n Macro macro = new Macro();\n\n TokenList.Token t = tokens.getFirst().next;\n\n if( t.word == null ) {\n throw new ParseError(\"Expected the macro's name after \"+tokens.getFirst().word);\n }\n List<TokenList.Token> variableTokens = new ArrayList<TokenList.Token>();\n\n macro.name = t.word;\n t = t.next;\n t = parseMacroInput(variableTokens, t);\n for( TokenList.Token a : variableTokens ) {\n if( a.word == null) throw new ParseError(\"expected word in macro header\");\n macro.inputs.add(a.word);\n }\n t = t.next;\n if( t == null || t.getSymbol() != Symbol.ASSIGN)\n throw new ParseError(\"Expected assignment\");\n t = t.next;\n macro.tokens = new TokenList(t,tokens.last);\n\n sequence.addOperation(macro.createOperation(macros));\n }", "public static @Nullable CleverTapAPI getInstance(Context context) throws CleverTapMetaDataNotFoundException, CleverTapPermissionsNotSatisfied {\n // For Google Play Store/Android Studio tracking\n sdkVersion = BuildConfig.SDK_VERSION_STRING;\n return getDefaultInstance(context);\n }", "private void processHyperlinkData(Resource resource, byte[] data)\n {\n if (data != null)\n {\n int offset = 12;\n String hyperlink;\n String address;\n String subaddress;\n\n offset += 12;\n hyperlink = MPPUtility.getUnicodeString(data, offset);\n offset += ((hyperlink.length() + 1) * 2);\n\n offset += 12;\n address = MPPUtility.getUnicodeString(data, offset);\n offset += ((address.length() + 1) * 2);\n\n offset += 12;\n subaddress = MPPUtility.getUnicodeString(data, offset);\n\n resource.setHyperlink(hyperlink);\n resource.setHyperlinkAddress(address);\n resource.setHyperlinkSubAddress(subaddress);\n }\n }", "public String[] getReportSamples() {\n final Map<String, String> sampleValues = new HashMap<>();\n sampleValues.put(\"name1\", \"Secure Transpiler Mars\");\n sampleValues.put(\"version1\", \"4.7.0\");\n sampleValues.put(\"name2\", \"Secure Transpiler Bounty\");\n sampleValues.put(\"version2\", \"5.0.0\");\n sampleValues.put(\"license\", \"CDDL-1.1\");\n sampleValues.put(\"name\", \"Secure Pretender\");\n sampleValues.put(\"version\", \"2.7.0\");\n sampleValues.put(\"organization\", \"Axway\");\n\n return ReportsRegistry.allReports()\n .stream()\n .map(report -> ReportUtils.generateSampleRequest(report, sampleValues))\n .map(request -> {\n try {\n String desc = \"\";\n final Optional<Report> byId = ReportsRegistry.findById(request.getReportId());\n\n if(byId.isPresent()) {\n desc = byId.get().getDescription() + \"<br/><br/>\";\n }\n\n return String.format(TWO_PLACES, desc, JsonUtils.serialize(request));\n } catch(IOException e) {\n return \"Error \" + e.getMessage();\n }\n })\n .collect(Collectors.toList())\n .toArray(new String[] {});\n }", "public static servicegroup_lbmonitor_binding[] get(nitro_service service, String servicegroupname) throws Exception{\n\t\tservicegroup_lbmonitor_binding obj = new servicegroup_lbmonitor_binding();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tservicegroup_lbmonitor_binding response[] = (servicegroup_lbmonitor_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static final Bytes of(String s) {\n Objects.requireNonNull(s);\n if (s.isEmpty()) {\n return EMPTY;\n }\n byte[] data = s.getBytes(StandardCharsets.UTF_8);\n return new Bytes(data, s);\n }", "public static authenticationtacacspolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationtacacspolicy_systemglobal_binding obj = new authenticationtacacspolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationtacacspolicy_systemglobal_binding response[] = (authenticationtacacspolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
The context returned by this method may be later reused for other interception types. @param interceptionModel @param ctx @param manager @param type @return the interception context to be used for the AroundConstruct chain
[ "public static InterceptionContext forConstructorInterception(InterceptionModel interceptionModel, CreationalContext<?> ctx, BeanManagerImpl manager, SlimAnnotatedType<?> type) {\n return of(interceptionModel, ctx, manager, null, type);\n }" ]
[ "public void detect(final String... packageNames) throws IOException {\n final String[] pkgNameFilter = new String[packageNames.length];\n for (int i = 0; i < pkgNameFilter.length; ++i) {\n pkgNameFilter[i] = packageNames[i].replace('.', '/');\n if (!pkgNameFilter[i].endsWith(\"/\")) {\n pkgNameFilter[i] = pkgNameFilter[i].concat(\"/\");\n }\n }\n final Set<File> files = new HashSet<>();\n final ClassLoader loader = Thread.currentThread().getContextClassLoader();\n for (final String packageName : pkgNameFilter) {\n final Enumeration<URL> resourceEnum = loader.getResources(packageName);\n while (resourceEnum.hasMoreElements()) {\n final URL url = resourceEnum.nextElement();\n if (\"file\".equals(url.getProtocol())) {\n final File dir = toFile(url);\n if (dir.isDirectory()) {\n files.add(dir);\n } else {\n throw new AssertionError(\"Not a recognized file URL: \" + url);\n }\n } else {\n final File jarFile = toFile(openJarURLConnection(url).getJarFileURL());\n if (jarFile.isFile()) {\n files.add(jarFile);\n } else {\n throw new AssertionError(\"Not a File: \" + jarFile);\n }\n }\n }\n }\n if (DEBUG) {\n print(\"Files to scan: %s\", files);\n }\n if (!files.isEmpty()) {\n // see http://shipilev.net/blog/2016/arrays-wisdom-ancients/#_conclusion\n detect(new ClassFileIterator(files.toArray(new File[0]), pkgNameFilter));\n }\n }", "public static cacheobject[] get(nitro_service service) throws Exception{\n\t\tcacheobject obj = new cacheobject();\n\t\tcacheobject[] response = (cacheobject[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private void handleGetVersionResponse(SerialMessage incomingMessage) {\n\t\tthis.ZWaveLibraryType = incomingMessage.getMessagePayloadByte(12);\n\t\tthis.zWaveVersion = new String(ArrayUtils.subarray(incomingMessage.getMessagePayload(), 0, 11));\n\t\tlogger.debug(String.format(\"Got MessageGetVersion response. Version = %s, Library Type = 0x%02X\", zWaveVersion, ZWaveLibraryType));\n\t}", "public boolean runOnMainThreadNext(Runnable r) {\n assert handler != null;\n\n if (!sanityCheck(\"runOnMainThreadNext \" + r)) {\n return false;\n }\n return handler.post(r);\n }", "public void drawText(String text, Font font, Rectangle box, Color fontColor) {\n\t\ttemplate.saveState();\n\t\t// get the font\n\t\tDefaultFontMapper mapper = new DefaultFontMapper();\n\t\tBaseFont bf = mapper.awtToPdf(font);\n\t\ttemplate.setFontAndSize(bf, font.getSize());\n\n\t\t// calculate descent\n\t\tfloat descent = 0;\n\t\tif (text != null) {\n\t\t\tdescent = bf.getDescentPoint(text, font.getSize());\n\t\t}\n\n\t\t// calculate the fitting size\n\t\tRectangle fit = getTextSize(text, font);\n\n\t\t// draw text if necessary\n\t\ttemplate.setColorFill(fontColor);\n\t\ttemplate.beginText();\n\t\ttemplate.showTextAligned(PdfContentByte.ALIGN_LEFT, text, origX + box.getLeft() + 0.5f\n\t\t\t\t* (box.getWidth() - fit.getWidth()), origY + box.getBottom() + 0.5f\n\t\t\t\t* (box.getHeight() - fit.getHeight()) - descent, 0);\n\t\ttemplate.endText();\n\t\ttemplate.restoreState();\n\t}", "public static String getHeaders(HttpServletResponse response) {\n String headerString = \"\";\n Collection<String> headerNames = response.getHeaderNames();\n for (String headerName : headerNames) {\n // there may be multiple headers per header name\n for (String headerValue : response.getHeaders(headerName)) {\n if (headerString.length() != 0) {\n headerString += \"\\n\";\n }\n\n headerString += headerName + \": \" + headerValue;\n }\n }\n\n return headerString;\n }", "public ManageableCollection getCollectionByQuery(Class collectionClass, Query query)\n throws PersistenceBrokerException\n {\n return referencesBroker.getCollectionByQuery(collectionClass, query, false);\n }", "public void createProposals(final Collection<ContentAssistContext> contexts, final IIdeContentProposalAcceptor acceptor) {\n Iterable<ContentAssistContext> _filteredContexts = this.getFilteredContexts(contexts);\n for (final ContentAssistContext context : _filteredContexts) {\n ImmutableList<AbstractElement> _firstSetGrammarElements = context.getFirstSetGrammarElements();\n for (final AbstractElement element : _firstSetGrammarElements) {\n {\n boolean _canAcceptMoreProposals = acceptor.canAcceptMoreProposals();\n boolean _not = (!_canAcceptMoreProposals);\n if (_not) {\n return;\n }\n this.createProposals(element, context, acceptor);\n }\n }\n }\n }", "public static void ensureNotSingular( DMatrixSparseCSC A , Random rand ) {\n// if( A.numRows < A.numCols ) {\n// throw new IllegalArgumentException(\"Fewer equations than variables\");\n// }\n\n int []s = UtilEjml.shuffled(A.numRows,rand);\n Arrays.sort(s);\n\n int N = Math.min(A.numCols,A.numRows);\n for (int col = 0; col < N; col++) {\n A.set(s[col],col,rand.nextDouble()+0.5);\n }\n }" ]
read messages beginning from offset @param offset next message offset @param length the max package size @return a MessageSet object with length data or empty @see MessageSet#Empty @throws IOException any exception
[ "public MessageSet read(long offset, int length) throws IOException {\n List<LogSegment> views = segments.getView();\n LogSegment found = findRange(views, offset, views.size());\n if (found == null) {\n if (logger.isTraceEnabled()) {\n logger.trace(format(\"NOT FOUND MessageSet from Log[%s], offset=%d, length=%d\", name, offset, length));\n }\n return MessageSet.Empty;\n }\n return found.getMessageSet().read(offset - found.start(), length);\n }" ]
[ "private static void computeBadByteSkipArray(byte[] pattern, int[] badByteArray) {\n for (int a = 0; a < ALPHABET_SIZE; a++) {\n badByteArray[a] = pattern.length;\n }\n\n for (int j = 0; j < pattern.length - 1; j++) {\n badByteArray[pattern[j] - Byte.MIN_VALUE] = pattern.length - j - 1;\n }\n }", "boolean advance() {\n if (header.frameCount <= 0) {\n return false;\n }\n\n if(framePointer == getFrameCount() - 1) {\n loopIndex++;\n }\n\n if(header.loopCount != LOOP_FOREVER && loopIndex > header.loopCount) {\n return false;\n }\n\n framePointer = (framePointer + 1) % header.frameCount;\n return true;\n }", "public static Map<String, Map<String, Metadata>> parseAndPopulateMetadataMap(JsonObject jsonObject) {\n Map<String, Map<String, Metadata>> metadataMap = new HashMap<String, Map<String, Metadata>>();\n //Parse all templates\n for (JsonObject.Member templateMember : jsonObject) {\n if (templateMember.getValue().isNull()) {\n continue;\n } else {\n String templateName = templateMember.getName();\n Map<String, Metadata> scopeMap = metadataMap.get(templateName);\n //If templateName doesn't yet exist then create an entry with empty scope map\n if (scopeMap == null) {\n scopeMap = new HashMap<String, Metadata>();\n metadataMap.put(templateName, scopeMap);\n }\n //Parse all scopes in a template\n for (JsonObject.Member scopeMember : templateMember.getValue().asObject()) {\n String scope = scopeMember.getName();\n Metadata metadataObject = new Metadata(scopeMember.getValue().asObject());\n scopeMap.put(scope, metadataObject);\n }\n }\n\n }\n return metadataMap;\n }", "public InsertIntoTable addRowsFrom(File file, FileParser fileParser) {\n builder.addRowsFrom(file, fileParser);\n return this;\n }", "protected void appendHavingClause(StringBuffer having, Criteria crit, StringBuffer stmt)\r\n {\r\n if (having.length() == 0)\r\n {\r\n having = null;\r\n }\r\n\r\n if (having != null || crit != null)\r\n {\r\n stmt.append(\" HAVING \");\r\n appendClause(having, crit, stmt);\r\n }\r\n }", "@Deprecated\n public ModelNode navigate(ModelNode model, boolean create) throws NoSuchElementException {\n final Iterator<PathElement> i = pathAddressList.iterator();\n while (i.hasNext()) {\n final PathElement element = i.next();\n if (create && !i.hasNext()) {\n if (element.isMultiTarget()) {\n throw new IllegalStateException();\n }\n model = model.require(element.getKey()).get(element.getValue());\n } else {\n model = model.require(element.getKey()).require(element.getValue());\n }\n }\n return model;\n }", "protected Boolean getIgnoreReleaseDate() {\n\n Boolean isIgnoreReleaseDate = parseOptionalBooleanValue(m_configObject, JSON_KEY_IGNORE_RELEASE_DATE);\n return (null == isIgnoreReleaseDate) && (m_baseConfig != null)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getIgnoreReleaseDate())\n : isIgnoreReleaseDate;\n }", "public byte[] toArray() {\n if (size() > Integer.MAX_VALUE)\n throw new IllegalStateException(\"Cannot create byte array of more than 2GB\");\n\n int len = (int) size();\n ByteBuffer bb = toDirectByteBuffer(0L, len);\n byte[] b = new byte[len];\n // Copy data to the array\n bb.get(b, 0, len);\n return b;\n }", "public synchronized void becomeTempoMaster() throws IOException {\n logger.debug(\"Trying to become master.\");\n if (!isSendingStatus()) {\n throw new IllegalStateException(\"Must be sending status updates to become the tempo master.\");\n }\n\n // Is there someone we need to ask to yield to us?\n final DeviceUpdate currentMaster = getTempoMaster();\n if (currentMaster != null) {\n // Send the yield request; we will become master when we get a successful response.\n byte[] payload = new byte[MASTER_HANDOFF_REQUEST_PAYLOAD.length];\n System.arraycopy(MASTER_HANDOFF_REQUEST_PAYLOAD, 0, payload, 0, MASTER_HANDOFF_REQUEST_PAYLOAD.length);\n payload[2] = getDeviceNumber();\n payload[8] = getDeviceNumber();\n if (logger.isDebugEnabled()) {\n logger.debug(\"Sending master yield request to player \" + currentMaster);\n }\n requestingMasterRoleFromPlayer.set(currentMaster.deviceNumber);\n assembleAndSendPacket(Util.PacketType.MASTER_HANDOFF_REQUEST, payload, currentMaster.address, BeatFinder.BEAT_PORT);\n } else if (!master.get()) {\n // There is no other master, we can just become it immediately.\n requestingMasterRoleFromPlayer.set(0);\n setMasterTempo(getTempo());\n master.set(true);\n }\n }" ]
Print an accrue type. @param value AccrueType instance @return accrue type value
[ "public static final String printAccrueType(AccrueType value)\n {\n return (Integer.toString(value == null ? AccrueType.PRORATED.getValue() : value.getValue()));\n }" ]
[ "private void fillToolBar(final I_CmsAppUIContext context) {\n\n context.setAppTitle(m_messages.key(Messages.GUI_APP_TITLE_0));\n\n // create components\n Component publishBtn = createPublishButton();\n m_saveBtn = createSaveButton();\n m_saveExitBtn = createSaveExitButton();\n Component closeBtn = createCloseButton();\n\n context.enableDefaultToolbarButtons(false);\n context.addToolbarButtonRight(closeBtn);\n context.addToolbarButton(publishBtn);\n context.addToolbarButton(m_saveExitBtn);\n context.addToolbarButton(m_saveBtn);\n\n Component addDescriptorBtn = createAddDescriptorButton();\n if (m_model.hasDescriptor() || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {\n addDescriptorBtn.setEnabled(false);\n }\n context.addToolbarButton(addDescriptorBtn);\n if (m_model.getBundleType().equals(BundleType.XML)) {\n Component convertToPropertyBundleBtn = createConvertToPropertyBundleButton();\n context.addToolbarButton(convertToPropertyBundleBtn);\n }\n }", "public static <X, T> ProducerMethod<X, T> of(BeanAttributes<T> attributes, EnhancedAnnotatedMethod<T, ? super X> method, AbstractClassBean<X> declaringBean, DisposalMethod<X, ?> disposalMethod, BeanManagerImpl beanManager, ServiceRegistry services) {\n return new ProducerMethod<X, T>(createId(attributes, method, declaringBean), attributes, method, declaringBean, disposalMethod, beanManager, services);\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getTimeElapsed() {\n int currentSession = getCurrentSession();\n if (currentSession == 0) return -1;\n\n int now = (int) (System.currentTimeMillis() / 1000);\n return now - currentSession;\n }", "public Excerpt typeParameters() {\n if (getTypeParameters().isEmpty()) {\n return Excerpts.EMPTY;\n } else {\n return Excerpts.add(\"<%s>\", Excerpts.join(\", \", getTypeParameters()));\n }\n }", "protected static Statement memorize(final Statement target, final ConnectionHandle connectionHandle) {\n\t\treturn (Statement) Proxy.newProxyInstance(\n\t\t\t\tStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {StatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}", "public void setProjectionMatrix(float x1, float y1, float z1, float w1,\n float x2, float y2, float z2, float w2, float x3, float y3,\n float z3, float w3, float x4, float y4, float z4, float w4) {\n NativeCustomCamera.setProjectionMatrix(getNative(), x1, y1, z1, w1, x2,\n y2, z2, w2, x3, y3, z3, w3, x4, y4, z4, w4);\n }", "public String isChecked(String value1, String value2) {\n\n if ((value1 == null) || (value2 == null)) {\n return \"\";\n }\n\n if (value1.trim().equalsIgnoreCase(value2.trim())) {\n return \"checked\";\n }\n\n return \"\";\n }", "public ParallelTaskBuilder prepareHttpDelete(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n\n cb.getHttpMeta().setHttpMethod(HttpMethod.DELETE);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }", "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 }" ]
Configure properties needed to connect to a Fluo application @param conf Job configuration @param config use {@link FluoConfiguration} to configure programmatically
[ "public static void configure(Job conf, SimpleConfiguration config) {\n try {\n FluoConfiguration fconfig = new FluoConfiguration(config);\n try (Environment env = new Environment(fconfig)) {\n long ts =\n env.getSharedResources().getTimestampTracker().allocateTimestamp().getTxTimestamp();\n conf.getConfiguration().setLong(TIMESTAMP_CONF_KEY, ts);\n\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n config.save(baos);\n conf.getConfiguration().set(PROPS_CONF_KEY,\n new String(baos.toByteArray(), StandardCharsets.UTF_8));\n\n AccumuloInputFormat.setZooKeeperInstance(conf, fconfig.getAccumuloInstance(),\n fconfig.getAccumuloZookeepers());\n AccumuloInputFormat.setConnectorInfo(conf, fconfig.getAccumuloUser(),\n new PasswordToken(fconfig.getAccumuloPassword()));\n AccumuloInputFormat.setInputTableName(conf, env.getTable());\n AccumuloInputFormat.setScanAuthorizations(conf, env.getAuthorizations());\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }" ]
[ "private void addOp(String op, String path, String value) {\n if (this.operations == null) {\n this.operations = new JsonArray();\n }\n\n this.operations.add(new JsonObject()\n .add(\"op\", op)\n .add(\"path\", path)\n .add(\"value\", value));\n }", "public static Object formatL(final String template, final Object... args) {\n return new Object() {\n @Override\n public String toString() {\n return format(template, args);\n }\n };\n }", "public static void writeFlowId(Message message, String flowId) {\n if (!(message instanceof SoapMessage)) {\n return;\n }\n SoapMessage soapMessage = (SoapMessage)message;\n Header hdFlowId = soapMessage.getHeader(FLOW_ID_QNAME);\n if (hdFlowId != null) {\n LOG.warning(\"FlowId already existing in soap header, need not to write FlowId header.\");\n return;\n }\n\n try {\n soapMessage.getHeaders().add(\n new Header(FLOW_ID_QNAME, flowId, new JAXBDataBinding(String.class)));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Stored flowId '\" + flowId + \"' in soap header: \" + FLOW_ID_QNAME);\n }\n } catch (JAXBException e) {\n LOG.log(Level.SEVERE, \"Couldn't create flowId header.\", e);\n }\n\n }", "private int getLiteralId(String literal) throws PersistenceBrokerException\r\n {\r\n ////logger.debug(\"lookup: \" + literal);\r\n try\r\n {\r\n return tags.getIdByTag(literal);\r\n }\r\n catch (NullPointerException t)\r\n {\r\n throw new MetadataException(\"unknown literal: '\" + literal + \"'\",t);\r\n }\r\n\r\n }", "public Tree determineHead(Tree t, Tree parent) {\r\n if (nonTerminalInfo == null) {\r\n throw new RuntimeException(\"Classes derived from AbstractCollinsHeadFinder must\" + \" create and fill HashMap nonTerminalInfo.\");\r\n }\r\n if (t == null || t.isLeaf()) {\r\n return null;\r\n }\r\n if (DEBUG) {\r\n System.err.println(\"determineHead for \" + t.value());\r\n }\r\n \r\n Tree[] kids = t.children();\r\n\r\n Tree theHead;\r\n // first check if subclass found explicitly marked head\r\n if ((theHead = findMarkedHead(t)) != null) {\r\n if (DEBUG) {\r\n System.err.println(\"Find marked head method returned \" +\r\n theHead.label() + \" as head of \" + t.label());\r\n }\r\n return theHead;\r\n }\r\n\r\n // if the node is a unary, then that kid must be the head\r\n // it used to special case preterminal and ROOT/TOP case\r\n // but that seemed bad (especially hardcoding string \"ROOT\")\r\n if (kids.length == 1) {\r\n if (DEBUG) {\r\n System.err.println(\"Only one child determines \" +\r\n kids[0].label() + \" as head of \" + t.label());\r\n }\r\n return kids[0];\r\n }\r\n\r\n return determineNonTrivialHead(t, parent);\r\n }", "protected void processAliases(List<MonolingualTextValue> addAliases, List<MonolingualTextValue> deleteAliases) {\n for(MonolingualTextValue val : addAliases) {\n addAlias(val);\n }\n for(MonolingualTextValue val : deleteAliases) {\n deleteAlias(val);\n }\n }", "protected boolean isSecureLink(CmsObject cms, String vfsName, CmsSite targetSite, boolean secureRequest) {\n\n return OpenCms.getStaticExportManager().isSecureLink(cms, vfsName, targetSite.getSiteRoot(), secureRequest);\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 }", "private void harvestReturnValues(\r\n ProcedureDescriptor proc,\r\n Object obj,\r\n PreparedStatement stmt)\r\n throws PersistenceBrokerSQLException\r\n {\r\n // If the procedure descriptor is null or has no return values or\r\n // if the statement is not a callable statment, then we're done.\r\n if ((proc == null) || (!proc.hasReturnValues()))\r\n {\r\n return;\r\n }\r\n\r\n // Set up the callable statement\r\n CallableStatement callable = (CallableStatement) stmt;\r\n\r\n // This is the index that we'll use to harvest the return value(s).\r\n int index = 0;\r\n\r\n // If the proc has a return value, then try to harvest it.\r\n if (proc.hasReturnValue())\r\n {\r\n\r\n // Increment the index\r\n index++;\r\n\r\n // Harvest the value.\r\n this.harvestReturnValue(obj, callable, proc.getReturnValueFieldRef(), index);\r\n }\r\n\r\n // Check each argument. If it's returned by the procedure,\r\n // then harvest the value.\r\n Iterator iter = proc.getArguments().iterator();\r\n while (iter.hasNext())\r\n {\r\n index++;\r\n ArgumentDescriptor arg = (ArgumentDescriptor) iter.next();\r\n if (arg.getIsReturnedByProcedure())\r\n {\r\n this.harvestReturnValue(obj, callable, arg.getFieldRef(), index);\r\n }\r\n }\r\n }" ]
Method to be implemented by the RendererBuilder subtypes. In this method the library user will define the mapping between content and renderer class. @param content used to map object to Renderers. @return the class associated to the renderer.
[ "protected Class getPrototypeClass(T content) {\n if (prototypes.size() == 1) {\n return prototypes.get(0).getClass();\n } else {\n return binding.get(content.getClass());\n }\n }" ]
[ "public static boolean isTypeManagedBeanOrDecoratorOrInterceptor(AnnotatedType<?> annotatedType) {\n Class<?> javaClass = annotatedType.getJavaClass();\n return !javaClass.isEnum() && !Extension.class.isAssignableFrom(javaClass)\n && Reflections.isTopLevelOrStaticNestedClass(javaClass) && !Reflections.isParameterizedTypeWithWildcard(javaClass)\n && hasSimpleCdiConstructor(annotatedType);\n }", "public static base_response add(nitro_service client, systemuser resource) throws Exception {\n\t\tsystemuser addresource = new systemuser();\n\t\taddresource.username = resource.username;\n\t\taddresource.password = resource.password;\n\t\taddresource.externalauth = resource.externalauth;\n\t\taddresource.promptstring = resource.promptstring;\n\t\taddresource.timeout = resource.timeout;\n\t\treturn addresource.add_resource(client);\n\t}", "public List<CmsJspNavElement> getSubNavigation() {\n\n if (m_subNavigation == null) {\n if (m_resource.isFile()) {\n m_subNavigation = Collections.emptyList();\n } else if (m_navContext == null) {\n try {\n throw new Exception(\"Can not get subnavigation because navigation context is not set.\");\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n m_subNavigation = Collections.emptyList();\n }\n } else {\n CmsJspNavBuilder navBuilder = m_navContext.getNavBuilder();\n m_subNavigation = navBuilder.getNavigationForFolder(\n navBuilder.getCmsObject().getSitePath(m_resource),\n m_navContext.getVisibility(),\n m_navContext.getFilter());\n }\n\n }\n return m_subNavigation;\n\n }", "@RequestMapping(value = \"/api/scripts\", method = RequestMethod.POST)\n public\n @ResponseBody\n Script addScript(Model model,\n @RequestParam(required = true) String name,\n @RequestParam(required = true) String script) throws Exception {\n\n return ScriptService.getInstance().addScript(name, script);\n }", "protected void runQuery() {\n\n String pool = m_pool.getValue();\n String stmt = m_script.getValue();\n if (stmt.trim().isEmpty()) {\n return;\n }\n CmsStringBufferReport report = new CmsStringBufferReport(Locale.ENGLISH);\n List<Throwable> errors = new ArrayList<>();\n CmsSqlConsoleResults result = m_console.execute(stmt, pool, report, errors);\n if (errors.size() > 0) {\n CmsErrorDialog.showErrorDialog(report.toString() + errors.get(0).getMessage(), errors.get(0));\n } else {\n Window window = CmsBasicDialog.prepareWindow(DialogWidth.max);\n window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_SQLCONSOLE_QUERY_RESULTS_0));\n window.setContent(new CmsSqlConsoleResultsForm(result, report.toString()));\n A_CmsUI.get().addWindow(window);\n window.center();\n }\n\n }", "@Override\n public void solve(DMatrixRMaj B, DMatrixRMaj X) {\n X.reshape(blockA.numCols,B.numCols);\n blockB.reshape(B.numRows,B.numCols,false);\n blockX.reshape(X.numRows,X.numCols,false);\n MatrixOps_DDRB.convert(B,blockB);\n\n alg.solve(blockB,blockX);\n\n MatrixOps_DDRB.convert(blockX,X);\n }", "private void logColumn(FastTrackColumn column)\n {\n if (m_log != null)\n {\n m_log.println(\"TABLE: \" + m_currentTable.getType());\n m_log.println(column.toString());\n m_log.flush();\n }\n }", "protected TokenList.Token parseSubmatrixToExtract(TokenList.Token variableTarget,\n TokenList tokens, Sequence sequence) {\n\n\n List<TokenList.Token> inputs = parseParameterCommaBlock(tokens, sequence);\n\n List<Variable> variables = new ArrayList<Variable>();\n\n // for the operation, the first variable must be the matrix which is being manipulated\n variables.add(variableTarget.getVariable());\n\n addSubMatrixVariables(inputs, variables);\n if( variables.size() != 2 && variables.size() != 3 ) {\n throw new ParseError(\"Unexpected number of variables. 1 or 2 expected\");\n }\n\n // first parameter is the matrix it will be extracted from. rest specify range\n Operation.Info info;\n\n // only one variable means its referencing elements\n // two variables means its referencing a sub matrix\n if( inputs.size() == 1 ) {\n Variable varA = variables.get(1);\n if( varA.getType() == VariableType.SCALAR ) {\n info = functions.create(\"extractScalar\", variables);\n } else {\n info = functions.create(\"extract\", variables);\n }\n } else if( inputs.size() == 2 ) {\n Variable varA = variables.get(1);\n Variable varB = variables.get(2);\n\n if( varA.getType() == VariableType.SCALAR && varB.getType() == VariableType.SCALAR) {\n info = functions.create(\"extractScalar\", variables);\n } else {\n info = functions.create(\"extract\", variables);\n }\n } else {\n throw new ParseError(\"Expected 2 inputs to sub-matrix\");\n }\n\n sequence.addOperation(info.op);\n\n return new TokenList.Token(info.output);\n }", "public BufferedImage toNewBufferedImage(int type) {\n BufferedImage target = new BufferedImage(width, height, type);\n Graphics2D g2 = (Graphics2D) target.getGraphics();\n g2.drawImage(awt, 0, 0, null);\n g2.dispose();\n return target;\n }" ]
Merge another AbstractTransition's states into this object, such that the other AbstractTransition can be discarded. @param another @return true if the merge is successful.
[ "public boolean merge(AbstractTransition another) {\n if (!isCompatible(another)) {\n return false;\n }\n if (another.mId != null) {\n if (mId == null) {\n mId = another.mId;\n } else {\n StringBuilder sb = new StringBuilder(mId.length() + another.mId.length());\n sb.append(mId);\n sb.append(\"_MERGED_\");\n sb.append(another.mId);\n mId = sb.toString();\n }\n }\n mUpdateStateAfterUpdateProgress |= another.mUpdateStateAfterUpdateProgress;\n mSetupList.addAll(another.mSetupList);\n Collections.sort(mSetupList, new Comparator<S>() {\n @Override\n public int compare(S lhs, S rhs) {\n if (lhs instanceof AbstractTransitionBuilder && rhs instanceof AbstractTransitionBuilder) {\n AbstractTransitionBuilder left = (AbstractTransitionBuilder) lhs;\n AbstractTransitionBuilder right = (AbstractTransitionBuilder) rhs;\n float startLeft = left.mReverse ? left.mEnd : left.mStart;\n float startRight = right.mReverse ? right.mEnd : right.mStart;\n return (int) ((startRight - startLeft) * 1000);\n }\n return 0;\n }\n });\n\n return true;\n }" ]
[ "public static MediaType nonBinary( MediaType.Type type, String subType, Charset charSet ) {\n ApiUtil.notNull( charSet, \"charset must not be null\" );\n return new MediaType( type, subType, charSet );\n }", "public static String getString(Properties props, String name, String defaultValue) {\n return props.containsKey(name) ? props.getProperty(name) : defaultValue;\n }", "public static JRDesignExpression getDataSourceExpression(DJDataSource ds) {\n JRDesignExpression exp = new JRDesignExpression();\n exp.setValueClass(JRDataSource.class);\n\n String dsType = getDataSourceTypeStr(ds.getDataSourceType());\n String expText = null;\n if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_ORIGIN_FIELD) {\n expText = dsType + \"$F{\" + ds.getDataSourceExpression() + \"})\";\n } else if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_ORIGIN_PARAMETER) {\n expText = dsType + REPORT_PARAMETERS_MAP + \".get( \\\"\" + ds.getDataSourceExpression() + \"\\\" ) )\";\n } else if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_TYPE_SQL_CONNECTION) {\n expText = dsType + REPORT_PARAMETERS_MAP + \".get( \\\"\" + ds.getDataSourceExpression() + \"\\\" ) )\";\n } else if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_ORIGIN_REPORT_DATASOURCE) {\n expText = \"((\" + JRDataSource.class.getName() + \") $P{REPORT_DATA_SOURCE})\";\n }\n\n exp.setText(expText);\n\n return exp;\n }", "public void afterLoading(CollectionProxyDefaultImpl colProxy)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"loading a proxied collection a collection: \" + colProxy);\r\n Collection data = colProxy.getData();\r\n for (Iterator iterator = data.iterator(); iterator.hasNext();)\r\n {\r\n Object o = iterator.next();\r\n if(!isOpen())\r\n {\r\n log.error(\"Collection proxy materialization outside of a running tx, obj=\" + o);\r\n try{throw new Exception(\"Collection proxy materialization outside of a running tx, obj=\" + o);}\r\n catch(Exception e)\r\n {e.printStackTrace();}\r\n }\r\n else\r\n {\r\n Identity oid = getBroker().serviceIdentity().buildIdentity(o);\r\n ClassDescriptor cld = getBroker().getClassDescriptor(ProxyHelper.getRealClass(o));\r\n RuntimeObject rt = new RuntimeObject(o, oid, cld, false, ProxyHelper.isProxy(o));\r\n lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList());\r\n }\r\n }\r\n unregisterFromCollectionProxy(colProxy);\r\n }", "public void setReadTimeout(int readTimeout) {\n\t\tthis.client = this.client.newBuilder()\n\t\t\t\t.readTimeout(readTimeout, TimeUnit.MILLISECONDS)\n\t\t\t\t.build();\n\t}", "public Iterable<BoxRetentionPolicyAssignment.Info> getAllAssignments(int limit, String ... fields) {\r\n return this.getAssignments(null, limit, fields);\r\n }", "public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n String url = null;\n\n // parse command-line input\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n\n // load parameters\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n\n // execute command\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n doMetaCheckVersion(adminClient);\n }", "private PersistenceBroker obtainBroker()\r\n {\r\n PersistenceBroker _broker;\r\n try\r\n {\r\n if (pbKey == null)\r\n {\r\n //throw new OJBRuntimeException(\"Not possible to do action, cause no tx runnning and no PBKey is set\");\r\n log.warn(\"No tx runnning and PBKey is null, try to use the default PB\");\r\n _broker = PersistenceBrokerFactory.defaultPersistenceBroker();\r\n }\r\n else\r\n {\r\n _broker = PersistenceBrokerFactory.createPersistenceBroker(pbKey);\r\n }\r\n }\r\n catch (PBFactoryException e)\r\n {\r\n log.error(\"Could not obtain PB for PBKey \" + pbKey, e);\r\n throw new OJBRuntimeException(\"Unexpected micro-kernel exception\", e);\r\n }\r\n return _broker;\r\n }", "public Collection getReaders(Object obj)\r\n\t{\r\n\t\tCollection result = null;\r\n try\r\n {\r\n Identity oid = new Identity(obj, getBroker());\r\n byte selector = (byte) 'r';\r\n byte[] requestBarr = buildRequestArray(oid, selector);\r\n \r\n HttpURLConnection conn = getHttpUrlConnection();\r\n \r\n //post request\r\n BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());\r\n out.write(requestBarr,0,requestBarr.length);\r\n out.flush();\t\t\r\n \r\n // read result from \r\n InputStream in = conn.getInputStream();\r\n ObjectInputStream ois = new ObjectInputStream(in);\r\n result = (Collection) ois.readObject();\r\n \r\n // cleanup\r\n ois.close();\r\n out.close();\r\n conn.disconnect();\t\t\r\n }\r\n catch (Throwable t)\r\n {\r\n throw new PersistenceBrokerException(t);\r\n }\r\n return result;\r\n\t}" ]
Determines if the queue identified by the given key can be used as a delayed queue. @param jedis connection to Redis @param key the key that identifies a queue @return true if the key already is a delayed queue or is not currently used, false otherwise
[ "public static boolean canUseAsDelayedQueue(final Jedis jedis, final String key) {\n final String type = jedis.type(key);\n return (ZSET.equalsIgnoreCase(type) || NONE.equalsIgnoreCase(type));\n }" ]
[ "public static Pool<Jedis> createJedisPool(final Config jesqueConfig, final GenericObjectPoolConfig poolConfig) {\n if (jesqueConfig == null) {\n throw new IllegalArgumentException(\"jesqueConfig must not be null\");\n }\n if (poolConfig == null) {\n throw new IllegalArgumentException(\"poolConfig must not be null\");\n }\n if (jesqueConfig.getMasterName() != null && !\"\".equals(jesqueConfig.getMasterName()) \n && jesqueConfig.getSentinels() != null && jesqueConfig.getSentinels().size() > 0) {\n return new JedisSentinelPool(jesqueConfig.getMasterName(), jesqueConfig.getSentinels(), poolConfig, \n jesqueConfig.getTimeout(), jesqueConfig.getPassword(), jesqueConfig.getDatabase());\n } else {\n return new JedisPool(poolConfig, jesqueConfig.getHost(), jesqueConfig.getPort(), \n jesqueConfig.getTimeout(), jesqueConfig.getPassword(), jesqueConfig.getDatabase());\n }\n }", "private <T> RequestBuilder doPrepareRequestBuilderImpl(\n ResponseReader responseReader, String methodName, RpcStatsContext statsContext,\n String requestData, AsyncCallback<T> callback) {\n\n if (getServiceEntryPoint() == null) {\n throw new NoServiceEntryPointSpecifiedException();\n }\n\n RequestCallback responseHandler = doCreateRequestCallback(responseReader,\n methodName, statsContext, callback);\n\n ensureRpcRequestBuilder();\n\n rpcRequestBuilder.create(getServiceEntryPoint());\n rpcRequestBuilder.setCallback(responseHandler);\n \n // changed code\n rpcRequestBuilder.setSync(isSync(methodName));\n // changed code\n \n rpcRequestBuilder.setContentType(RPC_CONTENT_TYPE);\n rpcRequestBuilder.setRequestData(requestData);\n rpcRequestBuilder.setRequestId(statsContext.getRequestId());\n return rpcRequestBuilder.finish();\n }", "public boolean isValidStore(String name) {\n readLock.lock();\n try {\n if(this.storeNames.contains(name)) {\n return true;\n }\n return false;\n } finally {\n readLock.unlock();\n }\n }", "private License getLicense(final String licenseId) {\n License result = null;\n final Set<DbLicense> matchingLicenses = licenseMatcher.getMatchingLicenses(licenseId);\n\n if (matchingLicenses.isEmpty()) {\n result = DataModelFactory.createLicense(\"#\" + licenseId + \"# (to be identified)\", NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET);\n result.setUnknown(true);\n } else {\n if (matchingLicenses.size() > 1 && LOG.isWarnEnabled()) {\n LOG.warn(String.format(\"%s matches multiple licenses %s. \" +\n \"Please run the report showing multiple matching on licenses\",\n licenseId, matchingLicenses.toString()));\n }\n result = mapper.getLicense(matchingLicenses.iterator().next());\n\n }\n\n return result;\n }", "public static int getActionBarHeight(Context context) {\n int actionBarHeight = UIUtils.getThemeAttributeDimensionSize(context, R.attr.actionBarSize);\n if (actionBarHeight == 0) {\n actionBarHeight = context.getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height_material);\n }\n return actionBarHeight;\n }", "@Override\n\tpublic void Invoke(final String method, JSONArray args,\n\t\t\tHubInvokeCallback callback) {\n\n\t\tif (method == null)\n {\n throw new IllegalArgumentException(\"method\");\n }\n\n if (args == null)\n {\n throw new IllegalArgumentException(\"args\");\n }\n\n final String callbackId = mConnection.RegisterCallback(callback);\n\n HubInvocation hubData = new HubInvocation(mHubName, method, args, callbackId);\n\n String value = hubData.Serialize();\n\n mConnection.Send(value, new SendCallback() \n {\n\t\t\t@Override\n\t\t\tpublic void OnSent(CharSequence messageSent) {\n\t\t\t\tLog.v(TAG, \"Invoke of \" + method + \"sent to \" + mHubName);\n\t\t\t\t// callback.OnSent() ??!?!?\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void OnError(Exception ex) {\n\t\t\t\t// TODO Cancel the callback\n\t\t\t\tLog.e(TAG, \"Failed to invoke \" + method + \"on \" + mHubName);\n\t\t\t\tmConnection.RemoveCallback(callbackId);\n\t\t\t\t// callback.OnError() ?!?!?\n\t\t\t}\n });\n }", "public static RouteInfo of(ActionContext context) {\n H.Method m = context.req().method();\n String path = context.req().url();\n RequestHandler handler = context.handler();\n if (null == handler) {\n handler = UNKNOWN_HANDLER;\n }\n return new RouteInfo(m, path, handler);\n }", "public void copyCategories(CmsObject cms, CmsResource fromResource, String toResourceSitePath) throws CmsException {\n\n List<CmsCategory> categories = readResourceCategories(cms, fromResource);\n for (CmsCategory category : categories) {\n addResourceToCategory(cms, toResourceSitePath, category);\n }\n }", "public static String defaultString(final String str, final String fallback) {\n return isNullOrEmpty(str) ? fallback : str;\n }" ]
See if there is an auto-attach cache file that seems to match the media in the specified slot, and if so, attach it. @param slot the player slot that is under consideration for automatic cache attachment
[ "static void tryAutoAttaching(final SlotReference slot) {\n if (!MetadataFinder.getInstance().getMountedMediaSlots().contains(slot)) {\n logger.error(\"Unable to auto-attach cache to empty slot {}\", slot);\n return;\n }\n if (MetadataFinder.getInstance().getMetadataCache(slot) != null) {\n logger.info(\"Not auto-attaching to slot {}; already has a cache attached.\", slot);\n return;\n }\n if (MetadataFinder.getInstance().getAutoAttachCacheFiles().isEmpty()) {\n logger.debug(\"No auto-attach files configured.\");\n return;\n }\n\n new Thread(new Runnable() {\n @Override\n public void run() {\n try {\n Thread.sleep(5); // Give us a chance to find out what type of media is in the new mount.\n final MediaDetails details = MetadataFinder.getInstance().getMediaDetailsFor(slot);\n if (details != null && details.mediaType == CdjStatus.TrackType.REKORDBOX) {\n // First stage attempt: See if we can match based on stored media details, which is both more reliable and\n // less disruptive than trying to sample the player database to compare entries.\n boolean attached = false;\n for (File file : MetadataFinder.getInstance().getAutoAttachCacheFiles()) {\n final MetadataCache cache = new MetadataCache(file);\n try {\n if (cache.sourceMedia != null && cache.sourceMedia.hashKey().equals(details.hashKey())) {\n // We found a solid match, no need to probe tracks.\n final boolean changed = cache.sourceMedia.hasChanged(details);\n logger.info(\"Auto-attaching metadata cache \" + cache.getName() + \" to slot \" + slot +\n \" based on media details \" + (changed? \"(changed since created)!\" : \"(unchanged).\"));\n MetadataFinder.getInstance().attachMetadataCacheInternal(slot, cache);\n attached = true;\n return;\n }\n } finally {\n if (!attached) {\n cache.close();\n }\n }\n }\n\n // Could not match based on media details; fall back to older method based on probing track metadata.\n ConnectionManager.ClientTask<Object> task = new ConnectionManager.ClientTask<Object>() {\n @Override\n public Object useClient(Client client) throws Exception {\n tryAutoAttachingWithConnection(slot, client);\n return null;\n }\n };\n ConnectionManager.getInstance().invokeWithClientSession(slot.player, task, \"trying to auto-attach metadata cache\");\n }\n } catch (Exception e) {\n logger.error(\"Problem trying to auto-attach metadata cache for slot \" + slot, e);\n }\n\n }\n }, \"Metadata cache file auto-attachment attempt\").start();\n }" ]
[ "@Deprecated\n\tpublic void setResolutions(List<Double> resolutions) {\n\t\tgetZoomLevels().clear();\n\t\tfor (Double resolution : resolutions) {\n\t\t\tgetZoomLevels().add(new ScaleInfo(1. / resolution));\n\t\t}\n\t}", "void releaseTransaction(@NotNull final Thread thread, final int permits) {\n try (CriticalSection ignored = criticalSection.enter()) {\n int currentThreadPermits = getThreadPermits(thread);\n if (permits > currentThreadPermits) {\n throw new ExodusException(\"Can't release more permits than it was acquired\");\n }\n acquiredPermits -= permits;\n currentThreadPermits -= permits;\n if (currentThreadPermits == 0) {\n threadPermits.remove(thread);\n } else {\n threadPermits.put(thread, currentThreadPermits);\n }\n notifyNextWaiters();\n }\n }", "public static <T> void finish(T query, long correlationId, EventBus bus, String... types) {\n for (String type : types) {\n RemoveQuery<T> next = finish(query, correlationId, type);\n bus.post(next);\n }\n }", "public static EffectiveAssignmentInsnFinder newInstance(final FieldNode targetVariable,\n final Collection<ControlFlowBlock> controlFlowBlocks) {\n return new EffectiveAssignmentInsnFinder(checkNotNull(targetVariable), checkNotNull(controlFlowBlocks));\n }", "public void handleChange(Object propertyId) {\n\n try {\n lockOnChange(propertyId);\n } catch (CmsException e) {\n LOG.debug(e);\n }\n if (isDescriptorProperty(propertyId)) {\n m_descriptorHasChanges = true;\n }\n if (isBundleProperty(propertyId)) {\n m_changedTranslations.add(getLocale());\n }\n\n }", "@SuppressWarnings(\"unchecked\")\n public Set<RateType> getRateTypes() {\n Set<RateType> result = get(KEY_RATE_TYPES, Set.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "public BoxFile.Info upload(BoxAPIConnection boxApi, String folderId, InputStream stream, URL url,\n String fileName, long fileSize) throws InterruptedException, IOException {\n //Create a upload session\n BoxFileUploadSession.Info session = this.createUploadSession(boxApi, folderId, url, fileName, fileSize);\n return this.uploadHelper(session, stream, fileSize);\n }", "public void setContentType(String photoId, String contentType) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_CONTENTTYPE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"content_type\", contentType);\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "public static String getStatusText(int nHttpStatusCode) {\n\n Integer intKey = new Integer(nHttpStatusCode);\n\n if (!mapStatusCodes.containsKey(intKey)) {\n return \"\";\n } else {\n return mapStatusCodes.get(intKey);\n }\n }" ]
Should use as destroy method. Disconnects from a Service Locator server. All endpoints that were registered before are removed from the server. Set property locatorClient to null. @throws InterruptedException @throws ServiceLocatorException
[ "@PreDestroy\n public void disconnectLocator() throws InterruptedException,\n ServiceLocatorException {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Destroy Locator client\");\n }\n\n if (endpointCollector != null) {\n endpointCollector.stopScheduledCollection();\n }\n \n if (locatorClient != null) {\n locatorClient.disconnect();\n locatorClient = null;\n }\n }" ]
[ "@Override\n public QueryBuilderFind excludingType(final Class<? extends WindupVertexFrame> type)\n {\n pipelineCriteria.add(new QueryGremlinCriterion()\n {\n @Override\n public void query(GraphRewrite event, GraphTraversal<?, Vertex> pipeline)\n {\n pipeline.filter(it -> !GraphTypeManager.hasType(type, it.get()));\n }\n });\n return this;\n }", "public static void registerOgmExternalizers(SerializationConfigurationBuilder cfg) {\n\t\tfor ( AdvancedExternalizer<?> advancedExternalizer : ogmExternalizers.values() ) {\n\t\t\tcfg.addAdvancedExternalizer( advancedExternalizer );\n\t\t}\n\t}", "public static base_response delete(nitro_service client) throws Exception {\n\t\tlocationfile deleteresource = new locationfile();\n\t\treturn deleteresource.delete_resource(client);\n\t}", "private String getProjectName() {\n String pName = Strings.emptyToNull(projectName);\n if (pName == null) { \n pName = Strings.emptyToNull(junit4.getProject().getName());\n }\n if (pName == null) {\n pName = \"(unnamed project)\"; \n }\n return pName;\n }", "private static BsonDocument withNewVersion(\n final BsonDocument document,\n final BsonDocument newVersion\n ) {\n final BsonDocument newDocument = BsonUtils.copyOfDocument(document);\n newDocument.put(DOCUMENT_VERSION_FIELD, newVersion);\n return newDocument;\n }", "@Deprecated\n public static PersistentResourceXMLBuilder decorator(final String elementName) {\n return new PersistentResourceXMLBuilder(PathElement.pathElement(elementName), null).setDecoratorGroup(elementName);\n }", "public static base_responses update(nitro_service client, clusternodegroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusternodegroup updateresources[] = new clusternodegroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new clusternodegroup();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].strict = resources[i].strict;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public static double getRadiusToBoundedness(double D, int N, double timelag, double B){\n\t\tdouble cov_area = a(N)*D*timelag;\n\t\tdouble radius = Math.sqrt(cov_area/(4*B));\n\t\treturn radius;\n\t}", "public Set<Action.ActionEffect> getActionEffects() {\n switch(getImpact()) {\n case CLASSLOADING:\n case WRITE:\n return WRITES;\n case READ_ONLY:\n return READS;\n default:\n throw new IllegalStateException();\n }\n\n }" ]
Establish a new tempo master, and if it is a change from the existing one, report it to the listeners. @param newMaster the packet which caused the change of masters, or {@code null} if there is now no master.
[ "private void setTempoMaster(DeviceUpdate newMaster) {\n DeviceUpdate oldMaster = tempoMaster.getAndSet(newMaster);\n if ((newMaster == null && oldMaster != null) ||\n (newMaster != null && ((oldMaster == null) || !newMaster.getAddress().equals(oldMaster.getAddress())))) {\n // This is a change in master, so report it to any registered listeners\n deliverMasterChangedAnnouncement(newMaster);\n }\n }" ]
[ "protected final boolean isValidEndTypeForPattern() {\n\n if (getEndType() == null) {\n return false;\n }\n switch (getPatternType()) {\n case DAILY:\n case WEEKLY:\n case MONTHLY:\n case YEARLY:\n return (getEndType().equals(EndType.DATE) || getEndType().equals(EndType.TIMES));\n case INDIVIDUAL:\n case NONE:\n return getEndType().equals(EndType.SINGLE);\n default:\n return false;\n }\n }", "public TransactionImpl getCurrentTransaction()\r\n {\r\n TransactionImpl tx = tx_table.get(Thread.currentThread());\r\n if(tx == null)\r\n {\r\n throw new TransactionNotInProgressException(\"Calling method needed transaction, but no transaction found for current thread :-(\");\r\n }\r\n return tx;\r\n }", "public URI build() {\n try {\n String uriString = String.format(\"%s%s\", baseUri.toASCIIString(),\n (path.isEmpty() ? \"\" : path));\n if(qParams != null && qParams.size() > 0) {\n //Add queries together if both exist\n if(!completeQuery.isEmpty()) {\n uriString = String.format(\"%s?%s&%s\", uriString,\n getJoinedQuery(qParams.getParams()),\n completeQuery);\n } else {\n uriString = String.format(\"%s?%s\", uriString,\n getJoinedQuery(qParams.getParams()));\n }\n } else if(!completeQuery.isEmpty()) {\n uriString = String.format(\"%s?%s\", uriString, completeQuery);\n }\n\n return new URI(uriString);\n } catch (URISyntaxException e) {\n throw new IllegalArgumentException(e);\n }\n }", "public static List<Integer> getStolenPrimaryPartitions(final Cluster currentCluster,\n final Cluster finalCluster,\n final int stealNodeId) {\n List<Integer> finalList = new ArrayList<Integer>(finalCluster.getNodeById(stealNodeId)\n .getPartitionIds());\n\n List<Integer> currentList = new ArrayList<Integer>();\n if(currentCluster.hasNodeWithId(stealNodeId)) {\n currentList = currentCluster.getNodeById(stealNodeId).getPartitionIds();\n } else {\n if(logger.isDebugEnabled()) {\n logger.debug(\"Current cluster does not contain stealer node (cluster : [[[\"\n + currentCluster + \"]]], node id \" + stealNodeId + \")\");\n }\n }\n finalList.removeAll(currentList);\n\n return finalList;\n }", "public static dbdbprofile[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tdbdbprofile obj = new dbdbprofile();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tdbdbprofile[] response = (dbdbprofile[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "private Server setUpServer() {\n Server server = new Server(port);\n ResourceHandler handler = new ResourceHandler();\n handler.setDirectoriesListed(true);\n handler.setWelcomeFiles(new String[]{\"index.html\"});\n handler.setResourceBase(getReportDirectoryPath().toAbsolutePath().toString());\n HandlerList handlers = new HandlerList();\n handlers.setHandlers(new Handler[]{handler, new DefaultHandler()});\n server.setStopAtShutdown(true);\n server.setHandler(handlers);\n return server;\n }", "static String guessEntityTypeFromId(String id) {\n\t\tif(id.isEmpty()) {\n\t\t\tthrow new IllegalArgumentException(\"Entity ids should not be empty.\");\n\t\t}\n\t\tswitch (id.charAt(0)) {\n\t\t\tcase 'L':\n\t\t\t\tif(id.contains(\"-F\")) {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_FORM;\n\t\t\t\t} else if(id.contains(\"-S\")) {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_SENSE;\n\t\t\t\t} else {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_LEXEME;\n\t\t\t\t}\n\t\t\tcase 'P':\n\t\t\t\treturn JSON_ENTITY_TYPE_PROPERTY;\n\t\t\tcase 'Q':\n\t\t\t\treturn JSON_ENTITY_TYPE_ITEM;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Entity id \\\"\" + id + \"\\\" is not supported.\");\n\t\t}\n\t}", "public static double elementSumSq( DMatrixD1 m ) {\n\n // minimize round off error\n double maxAbs = CommonOps_DDRM.elementMaxAbs(m);\n if( maxAbs == 0)\n return 0;\n\n double total = 0;\n \n int N = m.getNumElements();\n for( int i = 0; i < N; i++ ) {\n double d = m.data[i]/maxAbs;\n total += d*d;\n }\n\n return maxAbs*total*maxAbs;\n }", "private static JsonObject getFieldJsonObject(Field field) {\n JsonObject fieldObj = new JsonObject();\n fieldObj.add(\"type\", field.getType());\n fieldObj.add(\"key\", field.getKey());\n fieldObj.add(\"displayName\", field.getDisplayName());\n\n String fieldDesc = field.getDescription();\n if (fieldDesc != null) {\n fieldObj.add(\"description\", field.getDescription());\n }\n\n Boolean fieldIsHidden = field.getIsHidden();\n if (fieldIsHidden != null) {\n fieldObj.add(\"hidden\", field.getIsHidden());\n }\n\n JsonArray array = new JsonArray();\n List<String> options = field.getOptions();\n if (options != null && !options.isEmpty()) {\n for (String option : options) {\n JsonObject optionObj = new JsonObject();\n optionObj.add(\"key\", option);\n\n array.add(optionObj);\n }\n fieldObj.add(\"options\", array);\n }\n\n return fieldObj;\n }" ]
Obtains a local date in Accounting calendar system from the era, year-of-era and day-of-year fields. @param era the Accounting era, not null @param yearOfEra the year-of-era @param dayOfYear the day-of-year @return the Accounting local date, not null @throws DateTimeException if unable to create the date @throws ClassCastException if the {@code era} is not a {@code AccountingEra}
[ "@Override\n public AccountingDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }" ]
[ "public void fireCalendarReadEvent(ProjectCalendar calendar)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.calendarRead(calendar);\n }\n }\n }", "protected final <T> StyleSupplier<T> createStyleSupplier(\n final Template template,\n final String styleRef) {\n return new StyleSupplier<T>() {\n @Override\n public Style load(\n final MfClientHttpRequestFactory requestFactory,\n final T featureSource) {\n final StyleParser parser = AbstractGridCoverageLayerPlugin.this.styleParser;\n return OptionalUtils.or(\n () -> template.getStyle(styleRef),\n () -> parser.loadStyle(template.getConfiguration(), requestFactory, styleRef))\n .orElse(template.getConfiguration().getDefaultStyle(NAME));\n }\n };\n }", "protected String generateCacheKey(\n CmsObject cms,\n String targetSiteRoot,\n String detailPagePart,\n String absoluteLink) {\n\n return cms.getRequestContext().getSiteRoot() + \":\" + targetSiteRoot + \":\" + detailPagePart + absoluteLink;\n }", "protected SingleBusLocatorRegistrar getRegistrar(Bus bus) {\n SingleBusLocatorRegistrar registrar = busRegistrars.get(bus);\n if (registrar == null) {\n check(locatorClient, \"serviceLocator\", \"registerService\");\n registrar = new SingleBusLocatorRegistrar(bus);\n registrar.setServiceLocator(locatorClient);\n registrar.setEndpointPrefix(endpointPrefix);\n Map<String, String> endpointPrefixes = new HashMap<String, String>();\n endpointPrefixes.put(\"HTTP\", endpointPrefixHttp);\n endpointPrefixes.put(\"HTTPS\", endpointPrefixHttps);\n registrar.setEndpointPrefixes(endpointPrefixes);\n busRegistrars.put(bus, registrar);\n addLifeCycleListener(bus);\n }\n return registrar;\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 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 }", "public static authenticationtacacspolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationtacacspolicy_systemglobal_binding obj = new authenticationtacacspolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationtacacspolicy_systemglobal_binding response[] = (authenticationtacacspolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void writeAuxiliaryTriples() throws RDFHandlerException {\n\t\tfor (PropertyRestriction pr : this.someValuesQueue) {\n\t\t\twriteSomeValueRestriction(pr.propertyUri, pr.rangeUri, pr.subject);\n\t\t}\n\t\tthis.someValuesQueue.clear();\n\n\t\tthis.valueRdfConverter.writeAuxiliaryTriples();\n\t}", "private void writeToFile(List<DomainControllerData> data, String domainName) throws IOException {\n if(domainName == null || data == null) {\n return;\n }\n\n if (conn == null) {\n init();\n }\n\n try {\n String key = S3Util.sanitize(domainName) + \"/\" + S3Util.sanitize(DC_FILE_NAME);\n byte[] buf = S3Util.domainControllerDataToByteBuffer(data);\n S3Object val = new S3Object(buf, null);\n if (usingPreSignedUrls()) {\n Map headers = new TreeMap();\n headers.put(\"x-amz-acl\", Arrays.asList(\"public-read\"));\n conn.put(pre_signed_put_url, val, headers).connection.getResponseMessage();\n } else {\n Map headers = new TreeMap();\n headers.put(\"Content-Type\", Arrays.asList(\"text/plain\"));\n conn.put(location, key, val, headers).connection.getResponseMessage();\n }\n }\n catch(Exception e) {\n throw HostControllerLogger.ROOT_LOGGER.cannotWriteToS3File(e.getLocalizedMessage());\n }\n }" ]
Get parent digest of an image. @param digest @param host @return
[ "public static String getParentId(String digest, String host) throws IOException {\n DockerClient dockerClient = null;\n try {\n dockerClient = getDockerClient(host);\n return dockerClient.inspectImageCmd(digest).exec().getParent();\n } finally {\n closeQuietly(dockerClient);\n }\n }" ]
[ "@Override\n\tpublic String toFullString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.fullString) == null) {\n\t\t\tstringCache.fullString = result = toNormalizedString(IPv4StringCache.fullParams);\n\t\t}\n\t\treturn result;\n\t}", "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 boolean getOverAllocated()\n {\n Boolean overallocated = (Boolean) getCachedValue(ResourceField.OVERALLOCATED);\n if (overallocated == null)\n {\n Number peakUnits = getPeakUnits();\n Number maxUnits = getMaxUnits();\n overallocated = Boolean.valueOf(NumberHelper.getDouble(peakUnits) > NumberHelper.getDouble(maxUnits));\n set(ResourceField.OVERALLOCATED, overallocated);\n }\n return (overallocated.booleanValue());\n }", "@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 String formatTimeISO8601(TimeValue value) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tDecimalFormat yearForm = new DecimalFormat(FORMAT_YEAR);\n\t\tDecimalFormat timeForm = new DecimalFormat(FORMAT_OTHER);\n\t\tif (value.getYear() > 0) {\n\t\t\tbuilder.append(\"+\");\n\t\t}\n\t\tbuilder.append(yearForm.format(value.getYear()));\n\t\tbuilder.append(\"-\");\n\t\tbuilder.append(timeForm.format(value.getMonth()));\n\t\tbuilder.append(\"-\");\n\t\tbuilder.append(timeForm.format(value.getDay()));\n\t\tbuilder.append(\"T\");\n\t\tbuilder.append(timeForm.format(value.getHour()));\n\t\tbuilder.append(\":\");\n\t\tbuilder.append(timeForm.format(value.getMinute()));\n\t\tbuilder.append(\":\");\n\t\tbuilder.append(timeForm.format(value.getSecond()));\n\t\tbuilder.append(\"Z\");\n\t\treturn builder.toString();\n\t}", "private void updateDateTimeFormats(ProjectProperties properties)\n {\n String[] timePatterns = getTimePatterns(properties);\n String[] datePatterns = getDatePatterns(properties);\n String[] dateTimePatterns = getDateTimePatterns(properties, timePatterns);\n\n m_dateTimeFormat.applyPatterns(dateTimePatterns);\n m_dateFormat.applyPatterns(datePatterns);\n m_timeFormat.applyPatterns(timePatterns);\n\n m_dateTimeFormat.setLocale(m_locale);\n m_dateFormat.setLocale(m_locale);\n\n m_dateTimeFormat.setNullText(m_nullText);\n m_dateFormat.setNullText(m_nullText);\n m_timeFormat.setNullText(m_nullText);\n\n m_dateTimeFormat.setAmPmText(properties.getAMText(), properties.getPMText());\n m_timeFormat.setAmPmText(properties.getAMText(), properties.getPMText());\n }", "public void setWorkingDay(Day day, DayType working)\n {\n DayType value;\n\n if (working == null)\n {\n if (isDerived())\n {\n value = DayType.DEFAULT;\n }\n else\n {\n value = DayType.WORKING;\n }\n }\n else\n {\n value = working;\n }\n\n m_days[day.getValue() - 1] = value;\n }", "public boolean needsRefresh() {\n boolean needsRefresh;\n\n this.refreshLock.readLock().lock();\n long now = System.currentTimeMillis();\n long tokenDuration = (now - this.lastRefresh);\n needsRefresh = (tokenDuration >= this.expires - REFRESH_EPSILON);\n this.refreshLock.readLock().unlock();\n\n return needsRefresh;\n }", "@Override\n public EditMode editMode() {\n if(readInputrc) {\n try {\n return EditModeBuilder.builder().parseInputrc(new FileInputStream(inputrc())).create();\n }\n catch(FileNotFoundException e) {\n return EditModeBuilder.builder(mode()).create();\n }\n }\n else\n return EditModeBuilder.builder(mode()).create();\n }" ]
get TypeSignature given the signature @param typeSignature @param useInternalFormFullyQualifiedName if true, fqn in parameterizedTypeSignature must be in the form 'java/lang/Thread'. If false fqn must be of the form 'java.lang.Thread' @return
[ "public static FullTypeSignature getTypeSignature(String typeSignatureString,\n\t\t\tboolean useInternalFormFullyQualifiedName) {\n\t\tString key;\n\t\tif (!useInternalFormFullyQualifiedName) {\n\t\t\tkey = typeSignatureString.replace('.', '/')\n\t\t\t\t\t.replace('$', '.');\n\t\t} else {\n\t\t\tkey = typeSignatureString;\n\t\t}\n\n\t\t// we always use the internal form as a key for cache\n\t\tFullTypeSignature typeSignature = typeSignatureCache\n\t\t\t\t.get(key);\n\t\tif (typeSignature == null) {\n\t\t\tClassFileTypeSignatureParser typeSignatureParser = new ClassFileTypeSignatureParser(\n\t\t\t\t\ttypeSignatureString);\n\t\t\ttypeSignatureParser.setUseInternalFormFullyQualifiedName(useInternalFormFullyQualifiedName);\n\t\t\ttypeSignature = typeSignatureParser.parseTypeSignature();\n\t\t\ttypeSignatureCache.put(typeSignatureString, typeSignature);\n\t\t}\n\t\treturn typeSignature;\n\t}" ]
[ "public void setReadTimeout(int readTimeout) {\n\t\tthis.client = this.client.newBuilder()\n\t\t\t\t.readTimeout(readTimeout, TimeUnit.MILLISECONDS)\n\t\t\t\t.build();\n\t}", "public static void doExtendTraits(final ClassNode cNode, final SourceUnit unit, final CompilationUnit cu) {\n if (cNode.isInterface()) return;\n boolean isItselfTrait = Traits.isTrait(cNode);\n SuperCallTraitTransformer superCallTransformer = new SuperCallTraitTransformer(unit);\n if (isItselfTrait) {\n checkTraitAllowed(cNode, unit);\n return;\n }\n if (!cNode.getNameWithoutPackage().endsWith(Traits.TRAIT_HELPER)) {\n List<ClassNode> traits = findTraits(cNode);\n for (ClassNode trait : traits) {\n TraitHelpersTuple helpers = Traits.findHelpers(trait);\n applyTrait(trait, cNode, helpers);\n superCallTransformer.visitClass(cNode);\n if (unit!=null) {\n ASTTransformationCollectorCodeVisitor collector = new ASTTransformationCollectorCodeVisitor(unit, cu.getTransformLoader());\n collector.visitClass(cNode);\n }\n }\n }\n }", "public ImmutableList<CandidateElement> extract(StateVertex currentState)\n\t\t\tthrows CrawljaxException {\n\t\tLinkedList<CandidateElement> results = new LinkedList<>();\n\n\t\tif (!checkedElements.checkCrawlCondition(browser)) {\n\t\t\tLOG.info(\"State {} did not satisfy the CrawlConditions.\", currentState.getName());\n\t\t\treturn ImmutableList.of();\n\t\t}\n\t\tLOG.debug(\"Looking in state: {} for candidate elements\", currentState.getName());\n\n\t\ttry {\n\t\t\tDocument dom = DomUtils.asDocument(browser.getStrippedDomWithoutIframeContent());\n\t\t\textractElements(dom, results, \"\");\n\t\t} catch (IOException e) {\n\t\t\tLOG.error(e.getMessage(), e);\n\t\t\tthrow new CrawljaxException(e);\n\t\t}\n\t\tif (randomizeElementsOrder) {\n\t\t\tCollections.shuffle(results);\n\t\t}\n\t\tcurrentState.setElementsFound(results);\n\t\tLOG.debug(\"Found {} new candidate elements to analyze!\", results.size());\n\t\treturn ImmutableList.copyOf(results);\n\t}", "public 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 }", "private void initializeSignProperties() {\n if (!signPackage && !signChanges) {\n return;\n }\n\n if (key != null && keyring != null && passphrase != null) {\n return;\n }\n\n Map<String, String> properties =\n readPropertiesFromActiveProfiles(signCfgPrefix, KEY, KEYRING, PASSPHRASE);\n\n key = lookupIfEmpty(key, properties, KEY);\n keyring = lookupIfEmpty(keyring, properties, KEYRING);\n passphrase = decrypt(lookupIfEmpty(passphrase, properties, PASSPHRASE));\n\n if (keyring == null) {\n try {\n keyring = Utils.guessKeyRingFile().getAbsolutePath();\n console.info(\"Located keyring at \" + keyring);\n } catch (FileNotFoundException e) {\n console.warn(e.getMessage());\n }\n }\n }", "private void updateArt(TrackMetadataUpdate update, AlbumArt art) {\n hotCache.put(DeckReference.getDeckReference(update.player, 0), art); // Main deck\n if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well\n for (CueList.Entry entry : update.metadata.getCueList().entries) {\n if (entry.hotCueNumber != 0) {\n hotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), art);\n }\n }\n }\n deliverAlbumArtUpdate(update.player, art);\n }", "public void setWorkConnection(CmsSetupDb db) {\n\n db.setConnection(\n m_setupBean.getDbDriver(),\n m_setupBean.getDbWorkConStr(),\n m_setupBean.getDbConStrParams(),\n m_setupBean.getDbWorkUser(),\n m_setupBean.getDbWorkPwd());\n }", "public static base_response delete(nitro_service client, String Dnssuffix) throws Exception {\n\t\tdnssuffix deleteresource = new dnssuffix();\n\t\tdeleteresource.Dnssuffix = Dnssuffix;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static String matchOrigin(HttpServerExchange exchange, Collection<String> allowedOrigins) throws Exception {\n HeaderMap headers = exchange.getRequestHeaders();\n String[] origins = headers.get(Headers.ORIGIN).toArray();\n if (allowedOrigins != null && !allowedOrigins.isEmpty()) {\n for (String allowedOrigin : allowedOrigins) {\n for (String origin : origins) {\n if (allowedOrigin.equalsIgnoreCase(sanitizeDefaultPort(origin))) {\n return allowedOrigin;\n }\n }\n }\n }\n String allowedOrigin = defaultOrigin(exchange);\n for (String origin : origins) {\n if (allowedOrigin.equalsIgnoreCase(sanitizeDefaultPort(origin))) {\n return allowedOrigin;\n }\n }\n ROOT_LOGGER.debug(\"Request rejected due to HOST/ORIGIN mis-match.\");\n ResponseCodeHandler.HANDLE_403.handleRequest(exchange);\n return null;\n }" ]
Attaches a morph to scene object with a base mesh @param sceneObj is the base mesh. @throws IllegalStateException if component is null @throws IllegalStateException if mesh is null @throws IllegalStateException if material is null
[ "public void onAttach(GVRSceneObject sceneObj)\n {\n super.onAttach(sceneObj);\n GVRComponent comp = getComponent(GVRRenderData.getComponentType());\n\n if (comp == null)\n {\n throw new IllegalStateException(\"Cannot attach a morph to a scene object without a base mesh\");\n }\n\n GVRMesh mesh = ((GVRRenderData) comp).getMesh();\n if (mesh == null)\n {\n throw new IllegalStateException(\"Cannot attach a morph to a scene object without a base mesh\");\n }\n GVRShaderData mtl = getMaterial();\n\n if ((mtl == null) ||\n !mtl.getTextureDescriptor().contains(\"blendshapeTexture\"))\n {\n throw new IllegalStateException(\"Scene object shader does not support morphing\");\n }\n copyBaseShape(mesh.getVertexBuffer());\n mtl.setInt(\"u_numblendshapes\", mNumBlendShapes);\n mtl.setFloatArray(\"u_blendweights\", mWeights);\n }" ]
[ "public void process(Resource resource, int index, byte[] data)\n {\n CostRateTable result = new CostRateTable();\n\n if (data != null)\n {\n for (int i = 16; i + 44 <= data.length; i += 44)\n {\n Rate standardRate = new Rate(MPPUtility.getDouble(data, i), TimeUnit.HOURS);\n TimeUnit standardRateFormat = getFormat(MPPUtility.getShort(data, i + 8));\n Rate overtimeRate = new Rate(MPPUtility.getDouble(data, i + 16), TimeUnit.HOURS);\n TimeUnit overtimeRateFormat = getFormat(MPPUtility.getShort(data, i + 24));\n Double costPerUse = NumberHelper.getDouble(MPPUtility.getDouble(data, i + 32) / 100.0);\n Date endDate = MPPUtility.getTimestampFromTenths(data, i + 40);\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate);\n result.add(entry);\n }\n Collections.sort(result);\n }\n else\n {\n //\n // MS Project economises by not actually storing the first cost rate\n // table if it doesn't need to, so we take this into account here.\n //\n if (index == 0)\n {\n Rate standardRate = resource.getStandardRate();\n Rate overtimeRate = resource.getOvertimeRate();\n Number costPerUse = resource.getCostPerUse();\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRate.getUnits(), overtimeRate, overtimeRate.getUnits(), costPerUse, CostRateTableEntry.DEFAULT_ENTRY.getEndDate());\n result.add(entry);\n }\n else\n {\n result.add(CostRateTableEntry.DEFAULT_ENTRY);\n }\n }\n\n resource.setCostRateTable(index, result);\n }", "public static double[] computeSeasonalAdjustments(double[] realizedCPIValues, int lastMonth, int numberOfYearsToAverage) {\n\n\t\t/*\n\t\t * Cacluate average log returns\n\t\t */\n\t\tdouble[] averageLogReturn = new double[12];\n\t\tArrays.fill(averageLogReturn, 0.0);\n\t\tfor(int arrayIndex = 0; arrayIndex < 12*numberOfYearsToAverage; arrayIndex++){\n\n\t\t\tint month = (((((lastMonth-1 - arrayIndex) % 12) + 12) % 12));\n\n\t\t\tdouble logReturn = Math.log(realizedCPIValues[realizedCPIValues.length - 1 - arrayIndex] / realizedCPIValues[realizedCPIValues.length - 2 - arrayIndex]);\n\t\t\taverageLogReturn[month] += logReturn/numberOfYearsToAverage;\n\t\t}\n\n\t\t/*\n\t\t * Normalize\n\t\t */\n\t\tdouble sum = 0.0;\n\t\tfor(int index = 0; index < averageLogReturn.length; index++){\n\t\t\tsum += averageLogReturn[index];\n\t\t}\n\t\tdouble averageSeasonal = sum / averageLogReturn.length;\n\n\t\tdouble[] seasonalAdjustments = new double[averageLogReturn.length];\n\t\tfor(int index = 0; index < seasonalAdjustments.length; index++){\n\t\t\tseasonalAdjustments[index] = averageLogReturn[index] - averageSeasonal;\n\t\t}\n\n\t\t// Annualize seasonal adjustments\n\t\tfor(int index = 0; index < seasonalAdjustments.length; index++){\n\t\t\tseasonalAdjustments[index] = seasonalAdjustments[index] * 12;\n\t\t}\n\n\t\treturn seasonalAdjustments;\n\t}", "String getQuery(String key)\n {\n String res = this.adapter.getSqlText(key);\n if (res == null)\n {\n throw new DatabaseException(\"Query \" + key + \" does not exist\");\n }\n return res;\n }", "public static void checkArrayLength(String parameterName, int actualLength,\n int expectedLength) {\n if (actualLength != expectedLength) {\n throw Exceptions.IllegalArgument(\n \"Array %s should have %d elements, not %d\", parameterName,\n expectedLength, actualLength);\n }\n }", "@SuppressWarnings({\"deprecation\", \"WeakerAccess\"})\n protected void removeShutdownHook(ClassLoaderLeakPreventor preventor, Thread shutdownHook) {\n final String displayString = \"'\" + shutdownHook + \"' of type \" + shutdownHook.getClass().getName();\n preventor.error(\"Removing shutdown hook: \" + displayString);\n Runtime.getRuntime().removeShutdownHook(shutdownHook);\n\n if(executeShutdownHooks) { // Shutdown hooks should be executed\n \n preventor.info(\"Executing shutdown hook now: \" + displayString);\n // Make sure it's from protected ClassLoader\n shutdownHook.start(); // Run cleanup immediately\n \n if(shutdownHookWaitMs > 0) { // Wait for shutdown hook to finish\n try {\n shutdownHook.join(shutdownHookWaitMs); // Wait for thread to run\n }\n catch (InterruptedException e) {\n // Do nothing\n }\n if(shutdownHook.isAlive()) {\n preventor.warn(shutdownHook + \"still running after \" + shutdownHookWaitMs + \" ms - Stopping!\");\n shutdownHook.stop();\n }\n }\n }\n }", "public StandaloneCommandBuilder addSecurityProperty(final String key, final String value) {\n securityProperties.put(key, value);\n return this;\n }", "protected void sendPageBreakToBottom(JRDesignBand band) {\n\t\tJRElement[] elems = band.getElements();\n\t\tJRElement aux = null;\n\t\tfor (JRElement elem : elems) {\n\t\t\tif ((\"\" + elem.getKey()).startsWith(PAGE_BREAK_FOR_)) {\n\t\t\t\taux = elem;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (aux != null)\n\t\t\t((JRDesignElement)aux).setY(band.getHeight());\n\t}", "public final boolean roll(final LoggingEvent loggingEvent) {\n for (int i = 0; i < this.fileRollables.length; i++) {\n if (this.fileRollables[i].roll(loggingEvent)) {\n return true;\n }\n }\n return false;\n }", "public static void addInterceptors(InterceptorProvider provider) {\n PhaseManager phases = BusFactory.getDefaultBus().getExtension(PhaseManager.class);\n for (Phase p : phases.getInPhases()) {\n provider.getInInterceptors().add(new DemoInterceptor(p.getName()));\n provider.getInFaultInterceptors().add(new DemoInterceptor(p.getName()));\n }\n for (Phase p : phases.getOutPhases()) {\n provider.getOutInterceptors().add(new DemoInterceptor(p.getName()));\n provider.getOutFaultInterceptors().add(new DemoInterceptor(p.getName()));\n }\n }" ]
Gets the Searcher for a given variant. @param variant an identifier to differentiate this Searcher from eventual others. @return the corresponding Searcher instance. @throws IllegalStateException if no searcher was {@link #create(Searchable) created} before for this {@code variant}.
[ "public static Searcher get(String variant) {\n final Searcher searcher = instances.get(variant);\n if (searcher == null) {\n throw new IllegalStateException(Errors.SEARCHER_GET_BEFORE_CREATE);\n }\n return searcher;\n }" ]
[ "public static final boolean valueIsNotDefault(FieldType type, Object value)\n {\n boolean result = true;\n\n if (value == null)\n {\n result = false;\n }\n else\n {\n DataType dataType = type.getDataType();\n switch (dataType)\n {\n case BOOLEAN:\n {\n result = ((Boolean) value).booleanValue();\n break;\n }\n\n case CURRENCY:\n case NUMERIC:\n {\n result = !NumberHelper.equals(((Number) value).doubleValue(), 0.0, 0.00001);\n break;\n }\n\n case DURATION:\n {\n result = (((Duration) value).getDuration() != 0);\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n return result;\n }", "public String interpolate( String input, RecursionInterceptor recursionInterceptor )\n\t throws InterpolationException\n\t {\n\t try\n\t {\n\t return interpolate( input, recursionInterceptor, new HashSet<String>() );\n\t }\n\t finally\n\t {\n\t if ( !cacheAnswers )\n\t {\n\t existingAnswers.clear();\n\t }\n\t }\n\t }", "public static nsrollbackcmd[] get(nitro_service service, nsrollbackcmd_args args) throws Exception{\n\t\tnsrollbackcmd obj = new nsrollbackcmd();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tnsrollbackcmd[] response = (nsrollbackcmd[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public Date[] getDates()\n {\n int frequency = NumberHelper.getInt(m_frequency);\n if (frequency < 1)\n {\n frequency = 1;\n }\n\n Calendar calendar = DateHelper.popCalendar(m_startDate);\n List<Date> dates = new ArrayList<Date>();\n\n switch (m_recurrenceType)\n {\n case DAILY:\n {\n getDailyDates(calendar, frequency, dates);\n break;\n }\n\n case WEEKLY:\n {\n getWeeklyDates(calendar, frequency, dates);\n break;\n }\n\n case MONTHLY:\n {\n getMonthlyDates(calendar, frequency, dates);\n break;\n }\n\n case YEARLY:\n {\n getYearlyDates(calendar, dates);\n break;\n }\n }\n\n DateHelper.pushCalendar(calendar);\n \n return dates.toArray(new Date[dates.size()]);\n }", "private Video generateRandomVideo() {\n Video video = new Video();\n configureFavoriteStatus(video);\n configureLikeStatus(video);\n configureLiveStatus(video);\n configureTitleAndThumbnail(video);\n return video;\n }", "@SuppressWarnings({ \"unchecked\", \"rawtypes\", \"unused\" })\n private void commitToVoldemort(List<String> storeNamesToCommit) {\n\n if(logger.isDebugEnabled()) {\n logger.debug(\"Trying to commit to Voldemort\");\n }\n\n boolean hasError = false;\n if(nodesToStream == null || nodesToStream.size() == 0) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"No nodes to stream to. Returning.\");\n }\n return;\n }\n\n for(Node node: nodesToStream) {\n\n for(String store: storeNamesToCommit) {\n if(!nodeIdStoreInitialized.get(new Pair(store, node.getId())))\n continue;\n\n nodeIdStoreInitialized.put(new Pair(store, node.getId()), false);\n\n DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair(store,\n node.getId()));\n\n try {\n ProtoUtils.writeEndOfStream(outputStream);\n outputStream.flush();\n DataInputStream inputStream = nodeIdStoreToInputStreamRequest.get(new Pair(store,\n node.getId()));\n VAdminProto.UpdatePartitionEntriesResponse.Builder updateResponse = ProtoUtils.readToBuilder(inputStream,\n VAdminProto.UpdatePartitionEntriesResponse.newBuilder());\n if(updateResponse.hasError()) {\n hasError = true;\n }\n\n } catch(IOException e) {\n logger.error(\"Exception during commit\", e);\n hasError = true;\n if(!faultyNodes.contains(node.getId()))\n faultyNodes.add(node.getId());\n }\n }\n\n }\n\n if(streamingresults == null) {\n logger.warn(\"StreamingSession may not have been initialized since Variable streamingresults is null. Skipping callback \");\n return;\n }\n\n // remove redundant callbacks\n if(hasError) {\n\n logger.info(\"Invoking the Recovery Callback\");\n Future future = streamingresults.submit(recoveryCallback);\n try {\n future.get();\n\n } catch(InterruptedException e1) {\n MARKED_BAD = true;\n logger.error(\"Recovery Callback failed\", e1);\n throw new VoldemortException(\"Recovery Callback failed\");\n } catch(ExecutionException e1) {\n MARKED_BAD = true;\n logger.error(\"Recovery Callback failed during execution\", e1);\n throw new VoldemortException(\"Recovery Callback failed during execution\");\n }\n } else {\n if(logger.isDebugEnabled()) {\n logger.debug(\"Commit successful\");\n logger.debug(\"calling checkpoint callback\");\n }\n Future future = streamingresults.submit(checkpointCallback);\n try {\n future.get();\n\n } catch(InterruptedException e1) {\n logger.warn(\"Checkpoint callback failed!\", e1);\n } catch(ExecutionException e1) {\n logger.warn(\"Checkpoint callback failed during execution!\", e1);\n }\n }\n\n }", "public Range<Dyno> listDynos(String appName) {\n return connection.execute(new DynoList(appName), apiKey);\n }", "protected void appendGroupByClause(List groupByFields, StringBuffer buf)\r\n {\r\n if (groupByFields == null || groupByFields.size() == 0)\r\n {\r\n return;\r\n }\r\n\r\n buf.append(\" GROUP BY \");\r\n for (int i = 0; i < groupByFields.size(); i++)\r\n {\r\n FieldHelper cf = (FieldHelper) groupByFields.get(i);\r\n \r\n if (i > 0)\r\n {\r\n buf.append(\",\");\r\n }\r\n\r\n appendColName(cf.name, false, null, buf);\r\n }\r\n }", "public Location getInfo(String placeId, String woeId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\r\n\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\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 }" ]
Get a handler based on its class @param clazz The class of the Handler to return. If multiple Handlers exist, the first one is returned. @param <E> The class of the handler to return. @return The handler matching the class name.
[ "@Deprecated\r\n @SuppressWarnings(\"unchecked\")\r\n private static <E extends LogRecordHandler> E getHandler(Class<E> clazz){\r\n for(LogRecordHandler cand : handlers){\r\n if(clazz == cand.getClass()){\r\n return (E) cand;\r\n }\r\n }\r\n return null;\r\n }" ]
[ "public static boolean isVariable(ASTNode expression, String pattern) {\r\n return (expression instanceof VariableExpression && ((VariableExpression) expression).getName().matches(pattern));\r\n }", "static Parameter createParameter(final String name, final String value) {\n if (value != null && isQuoted(value)) {\n return new QuotedParameter(name, value);\n }\n return new Parameter(name, value);\n }", "public static void removeFromList(List<String> list, String value) {\n int foundIndex = -1;\n int i = 0;\n for (String id : list) {\n if (id.equalsIgnoreCase(value)) {\n foundIndex = i;\n break;\n }\n i++;\n }\n if (foundIndex != -1) {\n list.remove(foundIndex);\n }\n }", "public void enableUniformSize(final boolean enable) {\n if (mUniformSize != enable) {\n mUniformSize = enable;\n if (mContainer != null) {\n mContainer.onLayoutChanged(this);\n }\n }\n }", "private BigInteger getTaskCalendarID(Task mpx)\n {\n BigInteger result = null;\n ProjectCalendar cal = mpx.getCalendar();\n if (cal != null)\n {\n result = NumberHelper.getBigInteger(cal.getUniqueID());\n }\n else\n {\n result = NULL_CALENDAR_ID;\n }\n return (result);\n }", "public Duration getStartVariance()\n {\n Duration variance = (Duration) getCachedValue(AssignmentField.START_VARIANCE);\n if (variance == null)\n {\n TimeUnit format = getParentFile().getProjectProperties().getDefaultDurationUnits();\n variance = DateHelper.getVariance(getTask(), getBaselineStart(), getStart(), format);\n set(AssignmentField.START_VARIANCE, variance);\n }\n return (variance);\n }", "protected Map getAllVariables(){\n try{\n Iterator names = FreeMarkerTL.getEnvironment().getKnownVariableNames().iterator();\n Map vars = new HashMap();\n while (names.hasNext()) {\n Object name =names.next();\n vars.put(name, get(name.toString()));\n }\n return vars;\n }catch(Exception e){\n throw new ViewException(e);\n }\n }", "private void handleGetVersionResponse(SerialMessage incomingMessage) {\n\t\tthis.ZWaveLibraryType = incomingMessage.getMessagePayloadByte(12);\n\t\tthis.zWaveVersion = new String(ArrayUtils.subarray(incomingMessage.getMessagePayload(), 0, 11));\n\t\tlogger.debug(String.format(\"Got MessageGetVersion response. Version = %s, Library Type = 0x%02X\", zWaveVersion, ZWaveLibraryType));\n\t}", "public List<BindingInfo> getQueueBindings(String vhost, String queue) {\n final URI uri = uriWithPath(\"./queues/\" + encodePathSegment(vhost) +\n \"/\" + encodePathSegment(queue) + \"/bindings\");\n final BindingInfo[] result = this.rt.getForObject(uri, BindingInfo[].class);\n return asListOrNull(result);\n }" ]