query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Use this API to fetch the statistics of all protocolip_stats resources that are configured on netscaler.
[ "public static protocolip_stats get(nitro_service service) throws Exception{\n\t\tprotocolip_stats obj = new protocolip_stats();\n\t\tprotocolip_stats[] response = (protocolip_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}" ]
[ "CapabilityRegistry createShadowCopy() {\n CapabilityRegistry result = new CapabilityRegistry(forServer, this);\n readLock.lock();\n try {\n try {\n result.writeLock.lock();\n copy(this, result);\n } finally {\n result.writeLock.unlock();\n }\n } finally {\n readLock.unlock();\n }\n return result;\n }", "public static void checkRequired(OptionSet options, String opt) throws VoldemortException {\n List<String> opts = Lists.newArrayList();\n opts.add(opt);\n checkRequired(options, opts);\n }", "String calculateDisplayTimestamp(long time){\n long now = System.currentTimeMillis()/1000;\n long diff = now-time;\n if(diff < 60){\n return \"Just Now\";\n }else if(diff > 60 && diff < 59*60){\n return (diff/(60)) + \" mins ago\";\n }else if(diff > 59*60 && diff < 23*59*60 ){\n return diff/(60*60) > 1 ? diff/(60*60) + \" hours ago\" : diff/(60*60) + \" hour ago\";\n }else if(diff > 24*60*60 && diff < 48*60*60){\n return \"Yesterday\";\n }else {\n @SuppressLint(\"SimpleDateFormat\")\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd MMM\");\n return sdf.format(new Date(time));\n }\n }", "public void setSegmentReject(String reject) {\n\t\tif (!StringUtils.hasText(reject)) {\n\t\t\treturn;\n\t\t}\n\t\tInteger parsedLimit = null;\n\t\ttry {\n\t\t\tparsedLimit = Integer.parseInt(reject);\n\t\t\tsegmentRejectType = SegmentRejectType.ROWS;\n\t\t} catch (NumberFormatException e) {\n\t\t}\n\t\tif (parsedLimit == null && reject.contains(\"%\")) {\n\t\t\ttry {\n\t\t\t\tparsedLimit = Integer.parseInt(reject.replace(\"%\", \"\").trim());\n\t\t\t\tsegmentRejectType = SegmentRejectType.PERCENT;\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t}\n\t\t}\n\t\tsegmentRejectLimit = parsedLimit;\n\t}", "@Override\n public CopticDate date(int prolepticYear, int month, int dayOfMonth) {\n return CopticDate.of(prolepticYear, month, dayOfMonth);\n }", "private static int getPort(Service service, Annotation... qualifiers) {\n for (Annotation q : qualifiers) {\n if (q instanceof Port) {\n Port port = (Port) q;\n if (port.value() > 0) {\n return port.value();\n }\n }\n }\n\n ServicePort servicePort = findQualifiedServicePort(service, qualifiers);\n if (servicePort != null) {\n return servicePort.getPort();\n }\n return 0;\n }", "public static transformpolicylabel[] get(nitro_service service) throws Exception{\n\t\ttransformpolicylabel obj = new transformpolicylabel();\n\t\ttransformpolicylabel[] response = (transformpolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static double Sin(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return x - (x * x * x) / 6D;\r\n } else {\r\n\r\n double mult = x * x * x;\r\n double fact = 6;\r\n double sign = 1;\r\n int factS = 5;\r\n double result = x - mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += sign * (mult / fact);\r\n sign *= -1;\r\n }\r\n\r\n return result;\r\n }\r\n }", "private void addMembers(Collection memberNames, HashMap members, XClass type, String tagName, String paramName, String paramValue) throws XDocletException\r\n {\r\n if (!type.isInterface() && (type.getFields() != null)) {\r\n XField field;\r\n\r\n for (Iterator it = type.getFields().iterator(); it.hasNext(); ) {\r\n field = (XField)it.next();\r\n if (!field.isFinal() && !field.isStatic() && !field.isTransient()) {\r\n if (checkTagAndParam(field.getDoc(), tagName, paramName, paramValue)) {\r\n // already processed ?\r\n if (!members.containsKey(field.getName())) {\r\n memberNames.add(field.getName());\r\n members.put(field.getName(), field);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (type.getMethods() != null) {\r\n XMethod method;\r\n String propertyName;\r\n\r\n for (Iterator it = type.getMethods().iterator(); it.hasNext(); ) {\r\n method = (XMethod)it.next();\r\n if (!method.isConstructor() && !method.isNative() && !method.isStatic()) {\r\n if (checkTagAndParam(method.getDoc(), tagName, paramName, paramValue)) {\r\n if (MethodTagsHandler.isGetterMethod(method) || MethodTagsHandler.isSetterMethod(method)) {\r\n propertyName = MethodTagsHandler.getPropertyNameFor(method);\r\n if (!members.containsKey(propertyName)) {\r\n memberNames.add(propertyName);\r\n members.put(propertyName, method);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }" ]
Use this API to clear nssimpleacl.
[ "public static base_response clear(nitro_service client) throws Exception {\n\t\tnssimpleacl clearresource = new nssimpleacl();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}" ]
[ "public Membership getMembership() {\n URI uri = new URIBase(getBaseUri()).path(\"_membership\").build();\n Membership membership = couchDbClient.get(uri,\n Membership.class);\n return membership;\n }", "public void addClass(ClassDescriptorDef classDef)\r\n {\r\n classDef.setOwner(this);\r\n // Regardless of the format of the class name, we're using the fully qualified format\r\n // This is safe because of the package & class naming constraints of the Java language\r\n _classDefs.put(classDef.getQualifiedName(), classDef);\r\n }", "private void addCustomFields(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (CustomField field : file.getCustomFields())\n {\n final CustomField c = field;\n MpxjTreeNode childNode = new MpxjTreeNode(field)\n {\n @Override public String toString()\n {\n FieldType type = c.getFieldType();\n \n return type == null ? \"(unknown)\" : type.getFieldTypeClass() + \".\" + type.toString();\n }\n };\n parentNode.add(childNode);\n }\n }", "private void processDependencies() throws SQLException\n {\n List<Row> rows = getRows(\"select * from zdependency where zproject=?\", m_projectID);\n for (Row row : rows)\n {\n Task nextTask = m_project.getTaskByUniqueID(row.getInteger(\"ZNEXTACTIVITY_\"));\n Task prevTask = m_project.getTaskByUniqueID(row.getInteger(\"ZPREVIOUSACTIVITY_\"));\n Duration lag = row.getDuration(\"ZLAG_\");\n RelationType type = row.getRelationType(\"ZTYPE\");\n Relation relation = nextTask.addPredecessor(prevTask, type, lag);\n relation.setUniqueID(row.getInteger(\"Z_PK\"));\n }\n }", "public Relationship createRelationshipForEmbeddedAssociation(GraphDatabaseService executionEngine, AssociationKey associationKey, EntityKey embeddedKey) {\n\t\tString query = initCreateEmbeddedAssociationQuery( associationKey, embeddedKey );\n\t\tObject[] queryValues = createRelationshipForEmbeddedQueryValues( associationKey, embeddedKey );\n\t\treturn executeQuery( executionEngine, query, queryValues );\n\t}", "private static Class<?> extractTypeFromClass(Class<?> clazz, Class<?> source, int typeIndex,\n\t\t\tMap<TypeVariable, Type> typeVariableMap, Map<Integer, Integer> typeIndexesPerLevel,\n\t\t\tint nestingLevel, int currentLevel) {\n\n\t\tif (clazz.getName().startsWith(\"java.util.\")) {\n\t\t\treturn null;\n\t\t}\n\t\tif (clazz.getSuperclass() != null && isIntrospectionCandidate(clazz.getSuperclass())) {\n\t\t\ttry {\n\t\t\t\treturn extractType(clazz.getGenericSuperclass(), source, typeIndex, typeVariableMap,\n\t\t\t\t\t\ttypeIndexesPerLevel, nestingLevel, currentLevel);\n\t\t\t}\n\t\t\tcatch (MalformedParameterizedTypeException ex) {\n\t\t\t\t// from getGenericSuperclass() - ignore and continue with interface introspection\n\t\t\t}\n\t\t}\n\t\tType[] ifcs = clazz.getGenericInterfaces();\n\t\tif (ifcs != null) {\n\t\t\tfor (Type ifc : ifcs) {\n\t\t\t\tType rawType = ifc;\n\t\t\t\tif (ifc instanceof ParameterizedType) {\n\t\t\t\t\trawType = ((ParameterizedType) ifc).getRawType();\n\t\t\t\t}\n\t\t\t\tif (rawType instanceof Class && isIntrospectionCandidate((Class) rawType)) {\n\t\t\t\t\treturn extractType(ifc, source, typeIndex, typeVariableMap, typeIndexesPerLevel, nestingLevel, currentLevel);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "private void populateUserDefinedFieldValues(String tableName, FieldTypeClass type, FieldContainer container, Integer uniqueID)\n {\n Map<Integer, List<Row>> tableData = m_udfValues.get(tableName);\n if (tableData != null)\n {\n List<Row> udf = tableData.get(uniqueID);\n if (udf != null)\n {\n for (Row r : udf)\n {\n addUDFValue(type, container, r);\n }\n }\n }\n }", "public JSONObject toJson() throws JSONException {\n\n JSONObject result = new JSONObject();\n if (m_detailId != null) {\n result.put(JSON_DETAIL, \"\" + m_detailId);\n }\n if (m_siteRoot != null) {\n result.put(JSON_SITEROOT, m_siteRoot);\n }\n if (m_structureId != null) {\n result.put(JSON_STRUCTUREID, \"\" + m_structureId);\n }\n if (m_projectId != null) {\n result.put(JSON_PROJECT, \"\" + m_projectId);\n }\n if (m_type != null) {\n result.put(JSON_TYPE, \"\" + m_type.getJsonId());\n }\n return result;\n }", "public Set<D> getMatchedDeclaration() {\n Set<D> bindedSet = new HashSet<D>();\n for (Map.Entry<ServiceReference<D>, Boolean> e : declarations.entrySet()) {\n if (e.getValue()) {\n bindedSet.add(getDeclaration(e.getKey()));\n }\n }\n return bindedSet;\n }" ]
Get the subsystem deployment model root. <p> If the subsystem resource does not exist one will be created. </p> @param subsystemName the subsystem name. @return the model
[ "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 }" ]
[ "protected Class getClassCacheEntry(String name) {\n if (name == null) return null;\n synchronized (classCache) {\n return classCache.get(name);\n }\n }", "public static <T, U extends Closeable> T withCloseable(U self, @ClosureParams(value=FirstParam.class) Closure<T> action) throws IOException {\n try {\n T result = action.call(self);\n\n Closeable temp = self;\n self = null;\n temp.close();\n\n return result;\n } finally {\n DefaultGroovyMethodsSupport.closeWithWarning(self);\n }\n }", "@Override public void setID(Integer val)\n {\n ProjectFile parent = getParentFile();\n Integer previous = getID();\n\n if (previous != null)\n {\n parent.getTasks().unmapID(previous);\n }\n\n parent.getTasks().mapID(val, this);\n\n set(TaskField.ID, val);\n }", "public boolean evaluate(Object feature) {\n\t\t// Checks to ensure that the attribute has been set\n\t\tif (attribute == null) {\n\t\t\treturn false;\n\t\t}\n\t\t// Note that this converts the attribute to a string\n\t\t// for comparison. Unlike the math or geometry filters, which\n\t\t// require specific types to function correctly, this filter\n\t\t// using the mandatory string representation in Java\n\t\t// Of course, this does not guarantee a meaningful result, but it\n\t\t// does guarantee a valid result.\n\t\t// LOGGER.finest(\"pattern: \" + pattern);\n\t\t// LOGGER.finest(\"string: \" + attribute.getValue(feature));\n\t\t// return attribute.getValue(feature).toString().matches(pattern);\n\t\tObject value = attribute.evaluate(feature);\n\n\t\tif (null == value) {\n\t\t\treturn false;\n\t\t}\n\n\t\tMatcher matcher = getMatcher();\n\t\tmatcher.reset(value.toString());\n\n\t\treturn matcher.matches();\n\t}", "private String formatRate(Rate value)\n {\n String result = null;\n if (value != null)\n {\n StringBuilder buffer = new StringBuilder(m_formats.getCurrencyFormat().format(value.getAmount()));\n buffer.append(\"/\");\n buffer.append(formatTimeUnit(value.getUnits()));\n result = buffer.toString();\n }\n return (result);\n }", "public static boolean isJavaLangType(String s) {\n\t\treturn getJavaDefaultTypes().contains(s) && Character.isUpperCase(s.charAt(0));\n\t}", "public static ObjectModelResolver get(String resolverId) {\n List<ObjectModelResolver> resolvers = getResolvers();\n\n for (ObjectModelResolver resolver : resolvers) {\n if (resolver.accept(resolverId)) {\n return resolver;\n }\n }\n\n return null;\n }", "public void setRefreshFrequency(IntervalFrequency frequency) {\n if (NONE_REFRESH_INTERVAL == mRefreshInterval && IntervalFrequency.NONE != frequency) {\n // Install draw-frame listener if frequency is no longer NONE\n getGVRContext().unregisterDrawFrameListener(mFrameListener);\n getGVRContext().registerDrawFrameListener(mFrameListener);\n }\n switch (frequency) {\n case REALTIME:\n mRefreshInterval = REALTIME_REFRESH_INTERVAL;\n break;\n case HIGH:\n mRefreshInterval = HIGH_REFRESH_INTERVAL;\n break;\n case MEDIUM:\n mRefreshInterval = MEDIUM_REFRESH_INTERVAL;\n break;\n case LOW:\n mRefreshInterval = LOW_REFRESH_INTERVAL;\n break;\n case NONE:\n mRefreshInterval = NONE_REFRESH_INTERVAL;\n break;\n default:\n break;\n }\n }", "public static BoxConfig readFrom(Reader reader) throws IOException {\n JsonObject config = JsonObject.readFrom(reader);\n JsonObject settings = (JsonObject) config.get(\"boxAppSettings\");\n String clientId = settings.get(\"clientID\").asString();\n String clientSecret = settings.get(\"clientSecret\").asString();\n JsonObject appAuth = (JsonObject) settings.get(\"appAuth\");\n String publicKeyId = appAuth.get(\"publicKeyID\").asString();\n String privateKey = appAuth.get(\"privateKey\").asString();\n String passphrase = appAuth.get(\"passphrase\").asString();\n String enterpriseId = config.get(\"enterpriseID\").asString();\n return new BoxConfig(clientId, clientSecret, enterpriseId, publicKeyId, privateKey, passphrase);\n }" ]
Perform the entire sort operation
[ "private void sort()\n {\n DefaultDirectedWeightedGraph<RuleProvider, DefaultEdge> graph = new DefaultDirectedWeightedGraph<>(\n DefaultEdge.class);\n\n for (RuleProvider provider : providers)\n {\n graph.addVertex(provider);\n }\n\n addProviderRelationships(graph);\n\n checkForCycles(graph);\n\n List<RuleProvider> result = new ArrayList<>(this.providers.size());\n TopologicalOrderIterator<RuleProvider, DefaultEdge> iterator = new TopologicalOrderIterator<>(graph);\n while (iterator.hasNext())\n {\n RuleProvider provider = iterator.next();\n result.add(provider);\n }\n\n this.providers = Collections.unmodifiableList(result);\n\n int index = 0;\n for (RuleProvider provider : this.providers)\n {\n if (provider instanceof AbstractRuleProvider)\n ((AbstractRuleProvider) provider).setExecutionIndex(index++);\n }\n }" ]
[ "public void setColorRange(int firstIndex, int lastIndex, int color) {\n\t\tfor (int i = firstIndex; i <= lastIndex; i++)\n\t\t\tmap[i] = color;\n\t}", "public void close() throws IOException {\n final ManagedBinding binding = this.socketBindingManager.getNamedRegistry().getManagedBinding(this.name);\n if (binding == null) {\n return;\n }\n binding.close();\n }", "public static void sqrt(Complex_F64 input, Complex_F64 root)\n {\n double r = input.getMagnitude();\n double a = input.real;\n\n root.real = Math.sqrt((r+a)/2.0);\n root.imaginary = Math.sqrt((r-a)/2.0);\n if( input.imaginary < 0 )\n root.imaginary = -root.imaginary;\n }", "private static int determineBatchSize(boolean canGridDialectDoMultiget, int classBatchSize, int configuredDefaultBatchSize) {\n\t\t// if the dialect does not support it, don't batch so that we can avoid skewing the ORM fetch statistics\n\t\tif ( !canGridDialectDoMultiget ) {\n\t\t\treturn -1;\n\t\t}\n\t\telse if ( classBatchSize != -1 ) {\n\t\t\treturn classBatchSize;\n\t\t}\n\t\telse if ( configuredDefaultBatchSize != -1 ) {\n\t\t\treturn configuredDefaultBatchSize;\n\t\t}\n\t\telse {\n\t\t\treturn DEFAULT_MULTIGET_BATCH_SIZE;\n\t\t}\n\t}", "private void setTableAliasForPath(String aPath, List hintClasses, TableAlias anAlias)\r\n {\r\n m_pathToAlias.put(buildAliasKey(aPath, hintClasses), anAlias);\r\n }", "private void readRelationship(Link link)\n {\n Task sourceTask = m_taskIdMap.get(link.getSourceTaskID());\n Task destinationTask = m_taskIdMap.get(link.getDestinationTaskID());\n if (sourceTask != null && destinationTask != null)\n {\n Duration lag = getDuration(link.getLagUnit(), link.getLag());\n RelationType type = link.getType();\n Relation relation = destinationTask.addPredecessor(sourceTask, type, lag);\n relation.setUniqueID(link.getID());\n }\n }", "public int getMinutesPerMonth()\n {\n return m_minutesPerMonth == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerMonth()) : m_minutesPerMonth.intValue();\n }", "public Jar setMapAttribute(String name, Map<String, ?> values) {\n return setAttribute(name, join(values));\n }", "public static boolean uniform(Color color, Pixel[] pixels) {\n return Arrays.stream(pixels).allMatch(p -> p.toInt() == color.toRGB().toInt());\n }" ]
Method generates abbreviated exception message. @param message Original log message @param throwable The attached throwable @return Abbreviated exception message
[ "private String generateAbbreviatedExceptionMessage(final Throwable throwable) {\n\n\t\tfinal StringBuilder builder = new StringBuilder();\n\t\tbuilder.append(\": \");\n\t\tbuilder.append(throwable.getClass().getCanonicalName());\n\t\tbuilder.append(\": \");\n\t\tbuilder.append(throwable.getMessage());\n\n\t\tThrowable cause = throwable.getCause();\n\t\twhile (cause != null) {\n\t\t\tbuilder.append('\\n');\n\t\t\tbuilder.append(\"Caused by: \");\n\t\t\tbuilder.append(cause.getClass().getCanonicalName());\n\t\t\tbuilder.append(\": \");\n\t\t\tbuilder.append(cause.getMessage());\n\t\t\t// make sure the exception cause is not itself to prevent infinite\n\t\t\t// looping\n\t\t\tassert (cause != cause.getCause());\n\t\t\tcause = (cause == cause.getCause() ? null : cause.getCause());\n\t\t}\n\t\treturn builder.toString();\n\t}" ]
[ "public void signOff(String key, Collection<WebSocketConnection> connections) {\n if (connections.isEmpty()) {\n return;\n }\n ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key);\n bag.keySet().removeAll(connections);\n }", "public String getKeyValue(String key){\n String keyName = keysMap.get(key);\n if (keyName != null){\n return keyName;\n }\n return \"\"; //key wasn't defined in keys properties file\n }", "public boolean equalId(Element otherElement) {\r\n\t\tif (getElementId() == null || otherElement.getElementId() == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn getElementId().equalsIgnoreCase(otherElement.getElementId());\r\n\t}", "public Set<AttributeAccess.Flag> getFlags() {\n if (attributeAccess == null) {\n return Collections.emptySet();\n }\n return attributeAccess.getFlags();\n }", "public static void ensureChildElement(DomXmlElement parentElement, DomXmlElement childElement) {\n Node parent = childElement.unwrap().getParentNode();\n if (parent == null || !parentElement.unwrap().isEqualNode(parent)) {\n throw LOG.elementIsNotChildOfThisElement(childElement, parentElement);\n }\n }", "static String from(Class<?> entryClass) {\n List<String> tokens = tokenOf(entryClass);\n return fromTokens(tokens);\n }", "public void logError(String message, Object sender) {\n getEventManager().sendEvent(this, IErrorEvents.class, \"onError\", new Object[] { message, sender });\n }", "public Conditionals ifModifiedSince(LocalDateTime time) {\n Preconditions.checkArgument(match.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_MATCH));\n Preconditions.checkArgument(!unModifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_UNMODIFIED_SINCE));\n time = time.withNano(0);\n return new Conditionals(empty(), noneMatch, Optional.of(time), Optional.empty());\n }", "public static void fillProcessorAttributes(\n final List<Processor> processors,\n final Map<String, Attribute> initialAttributes) {\n Map<String, Attribute> currentAttributes = new HashMap<>(initialAttributes);\n for (Processor processor: processors) {\n if (processor instanceof RequireAttributes) {\n for (ProcessorDependencyGraphFactory.InputValue inputValue:\n ProcessorDependencyGraphFactory.getInputs(processor)) {\n if (inputValue.type == Values.class) {\n if (processor instanceof CustomDependencies) {\n for (String attributeName: ((CustomDependencies) processor).getDependencies()) {\n Attribute attribute = currentAttributes.get(attributeName);\n if (attribute != null) {\n ((RequireAttributes) processor).setAttribute(\n attributeName, currentAttributes.get(attributeName));\n }\n }\n\n } else {\n for (Map.Entry<String, Attribute> attribute: currentAttributes.entrySet()) {\n ((RequireAttributes) processor).setAttribute(\n attribute.getKey(), attribute.getValue());\n }\n }\n } else {\n try {\n ((RequireAttributes) processor).setAttribute(\n inputValue.internalName,\n currentAttributes.get(inputValue.name));\n } catch (ClassCastException e) {\n throw new IllegalArgumentException(String.format(\"The processor '%s' requires \" +\n \"the attribute '%s' \" +\n \"(%s) but he has the \" +\n \"wrong type:\\n%s\",\n processor, inputValue.name,\n inputValue.internalName,\n e.getMessage()), e);\n }\n }\n }\n }\n if (processor instanceof ProvideAttributes) {\n Map<String, Attribute> newAttributes = ((ProvideAttributes) processor).getAttributes();\n for (ProcessorDependencyGraphFactory.OutputValue ouputValue:\n ProcessorDependencyGraphFactory.getOutputValues(processor)) {\n currentAttributes.put(\n ouputValue.name, newAttributes.get(ouputValue.internalName));\n }\n }\n }\n }" ]
Method must be invoked upon completion of a rebalancing task. It is the task's responsibility to do so. @param stealerId @param donorId
[ "public synchronized void doneTask(int stealerId, int donorId) {\n removeNodesFromWorkerList(Arrays.asList(stealerId, donorId));\n numTasksExecuting--;\n doneSignal.countDown();\n // Try and schedule more tasks now that resources may be available to do\n // so.\n scheduleMoreTasks();\n }" ]
[ "public static String md5(byte[] source) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(source);\n byte tmp[] = md.digest();\n char str[] = new char[32];\n int k = 0;\n for (byte b : tmp) {\n str[k++] = hexDigits[b >>> 4 & 0xf];\n str[k++] = hexDigits[b & 0xf];\n }\n return new String(str);\n\n } catch (Exception e) {\n throw new IllegalArgumentException(e);\n }\n }", "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 }", "public Collection<Contact> getListRecentlyUploaded(Date lastUpload, String filter) throws FlickrException {\r\n List<Contact> contacts = new ArrayList<Contact>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST_RECENTLY_UPLOADED);\r\n\r\n if (lastUpload != null) {\r\n parameters.put(\"date_lastupload\", String.valueOf(lastUpload.getTime() / 1000L));\r\n }\r\n if (filter != null) {\r\n parameters.put(\"filter\", filter);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element contactsElement = response.getPayload();\r\n NodeList contactNodes = contactsElement.getElementsByTagName(\"contact\");\r\n for (int i = 0; i < contactNodes.getLength(); i++) {\r\n Element contactElement = (Element) contactNodes.item(i);\r\n Contact contact = new Contact();\r\n contact.setId(contactElement.getAttribute(\"nsid\"));\r\n contact.setUsername(contactElement.getAttribute(\"username\"));\r\n contact.setRealName(contactElement.getAttribute(\"realname\"));\r\n contact.setFriend(\"1\".equals(contactElement.getAttribute(\"friend\")));\r\n contact.setFamily(\"1\".equals(contactElement.getAttribute(\"family\")));\r\n contact.setIgnored(\"1\".equals(contactElement.getAttribute(\"ignored\")));\r\n contact.setOnline(OnlineStatus.fromType(contactElement.getAttribute(\"online\")));\r\n contact.setIconFarm(contactElement.getAttribute(\"iconfarm\"));\r\n contact.setIconServer(contactElement.getAttribute(\"iconserver\"));\r\n if (contact.getOnline() == OnlineStatus.AWAY) {\r\n contactElement.normalize();\r\n contact.setAwayMessage(XMLUtilities.getValue(contactElement));\r\n }\r\n contacts.add(contact);\r\n }\r\n return contacts;\r\n }", "final public void setRealOffset(Integer start, Integer end) {\n if ((start == null) || (end == null)) {\n // do nothing\n } else if (start > end) {\n throw new IllegalArgumentException(\n \"Start real offset after end real offset\");\n } else {\n tokenRealOffset = new MtasOffset(start, end);\n }\n }", "public int getLeadingBitCount(boolean network) {\n\t\tint count = getDivisionCount();\n\t\tif(count == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tlong front = network ? getDivision(0).getMaxValue() : 0;\n\t\tint prefixLen = 0;\n\t\tfor(int i = 0; i < count; i++) {\n\t\t\tIPAddressDivision seg = getDivision(i);\n\t\t\tlong value = seg.getDivisionValue();\n\t\t\tif(value != front) {\n\t\t\t\treturn prefixLen + seg.getLeadingBitCount(network);\n\t\t\t}\n\t\t\tprefixLen += seg.getBitCount();\n\t\t}\n\t\treturn prefixLen;\n\t}", "@SuppressWarnings(\"deprecation\")\n public BUILDER addAccessConstraint(final AccessConstraintDefinition accessConstraint) {\n if (accessConstraints == null) {\n accessConstraints = new AccessConstraintDefinition[] {accessConstraint};\n } else {\n accessConstraints = Arrays.copyOf(accessConstraints, accessConstraints.length + 1);\n accessConstraints[accessConstraints.length - 1] = accessConstraint;\n }\n return (BUILDER) this;\n }", "@Override\n public EthiopicDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "public void setSymbolPosition(CurrencySymbolPosition posn)\n {\n if (posn == null)\n {\n posn = DEFAULT_CURRENCY_SYMBOL_POSITION;\n }\n set(ProjectField.CURRENCY_SYMBOL_POSITION, posn);\n }", "private void initDatesPanel() {\n\n m_startLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_TIME_STARTTIME_0));\n m_startTime.setAllowInvalidValue(true);\n m_startTime.setValue(m_model.getStart());\n m_endLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_TIME_ENDTIME_0));\n m_endTime.setAllowInvalidValue(true);\n m_endTime.setValue(m_model.getEnd());\n m_seriesCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_SERIES_CHECKBOX_0));\n m_wholeDayCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_WHOLE_DAY_CHECKBOX_0));\n m_currentTillEndCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_CURRENT_TILL_END_CHECKBOX_0));\n m_currentTillEndCheckBox.getButton().setTitle(\n Messages.get().key(Messages.GUI_SERIALDATE_CURRENT_TILL_END_CHECKBOX_HELP_0));\n }" ]
Create and return a SelectIterator for the class using the default mapped query for all statement.
[ "public SelectIterator<T, ID> buildIterator(BaseDaoImpl<T, ID> classDao, ConnectionSource connectionSource,\n\t\t\tint resultFlags, ObjectCache objectCache) throws SQLException {\n\t\tprepareQueryForAll();\n\t\treturn buildIterator(classDao, connectionSource, preparedQueryForAll, objectCache, resultFlags);\n\t}" ]
[ "private IndexedContainer createContainerForDescriptorEditing() {\n\n IndexedContainer container = new IndexedContainer();\n\n // create properties\n container.addContainerProperty(TableProperty.KEY, String.class, \"\");\n container.addContainerProperty(TableProperty.DESCRIPTION, String.class, \"\");\n container.addContainerProperty(TableProperty.DEFAULT, String.class, \"\");\n\n // add entries\n CmsXmlContentValueSequence messages = m_descContent.getValueSequence(\n \"/\" + Descriptor.N_MESSAGE,\n Descriptor.LOCALE);\n for (int i = 0; i < messages.getElementCount(); i++) {\n\n String prefix = messages.getValue(i).getPath() + \"/\";\n Object itemId = container.addItem();\n Item item = container.getItem(itemId);\n String key = m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).getStringValue(m_cms);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n item.getItemProperty(TableProperty.DESCRIPTION).setValue(\n m_descContent.getValue(prefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).getStringValue(m_cms));\n item.getItemProperty(TableProperty.DEFAULT).setValue(\n m_descContent.getValue(prefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).getStringValue(m_cms));\n }\n\n return container;\n\n }", "public E setById(final int id, final E element) {\n VListKey<K> key = new VListKey<K>(_key, id);\n UpdateElementById<K, E> updateElementAction = new UpdateElementById<K, E>(key, element);\n\n if(!_storeClient.applyUpdate(updateElementAction))\n throw new ObsoleteVersionException(\"update failed\");\n\n return updateElementAction.getResult();\n }", "public static void copy(String in, Writer out) throws IOException {\n\t\tAssert.notNull(in, \"No input String specified\");\n\t\tAssert.notNull(out, \"No Writer specified\");\n\t\ttry {\n\t\t\tout.write(in);\n\t\t}\n\t\tfinally {\n\t\t\ttry {\n\t\t\t\tout.close();\n\t\t\t}\n\t\t\tcatch (IOException ex) {\n\t\t\t}\n\t\t}\n\t}", "public ItemRequest<Story> delete(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"DELETE\");\n }", "protected static String jacksonObjectToString(Object object) {\n\t\ttry {\n\t\t\treturn mapper.writeValueAsString(object);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tlogger.error(\"Failed to serialize JSON data: \" + e.toString());\n\t\t\treturn null;\n\t\t}\n\t}", "public Swagger read(Class<?> cls) {\n SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);\n if (swaggerDefinition != null) {\n readSwaggerConfig(cls, swaggerDefinition);\n }\n\n return read(cls, \"\", null, false, new String[0], new String[0], new LinkedHashMap<>(), new ArrayList<>(), new HashSet<>());\n }", "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 }", "@Override public Object instantiateItem(ViewGroup parent, int position) {\n T content = getItem(position);\n rendererBuilder.withContent(content);\n rendererBuilder.withParent(parent);\n rendererBuilder.withLayoutInflater(LayoutInflater.from(parent.getContext()));\n Renderer<T> renderer = rendererBuilder.build();\n if (renderer == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null Renderer\");\n }\n updateRendererExtraValues(content, renderer, position);\n renderer.render();\n View view = renderer.getRootView();\n parent.addView(view);\n return view;\n }", "public void generateMapFile(File jarFile, String mapFileName, boolean mapClassMethods) throws XMLStreamException, IOException, ClassNotFoundException, IntrospectionException\n {\n m_responseList = new LinkedList<String>();\n writeMapFile(mapFileName, jarFile, mapClassMethods);\n }" ]
Use this API to add snmpuser.
[ "public static base_response add(nitro_service client, snmpuser resource) throws Exception {\n\t\tsnmpuser addresource = new snmpuser();\n\t\taddresource.name = resource.name;\n\t\taddresource.group = resource.group;\n\t\taddresource.authtype = resource.authtype;\n\t\taddresource.authpasswd = resource.authpasswd;\n\t\taddresource.privtype = resource.privtype;\n\t\taddresource.privpasswd = resource.privpasswd;\n\t\treturn addresource.add_resource(client);\n\t}" ]
[ "public void run(Configuration configuration, List<CandidateSteps> candidateSteps, Story story, MetaFilter filter)\n throws Throwable {\n run(configuration, candidateSteps, story, filter, null);\n }", "private void readCostRateTables(Resource resource, Rates rates)\n {\n if (rates == null)\n {\n CostRateTable table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(0, table);\n\n table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(1, table);\n\n table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(2, table);\n\n table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(3, table);\n\n table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(4, table);\n }\n else\n {\n Set<CostRateTable> tables = new HashSet<CostRateTable>();\n\n for (net.sf.mpxj.mspdi.schema.Project.Resources.Resource.Rates.Rate rate : rates.getRate())\n {\n Rate standardRate = DatatypeConverter.parseRate(rate.getStandardRate());\n TimeUnit standardRateFormat = DatatypeConverter.parseTimeUnit(rate.getStandardRateFormat());\n Rate overtimeRate = DatatypeConverter.parseRate(rate.getOvertimeRate());\n TimeUnit overtimeRateFormat = DatatypeConverter.parseTimeUnit(rate.getOvertimeRateFormat());\n Double costPerUse = DatatypeConverter.parseCurrency(rate.getCostPerUse());\n Date endDate = rate.getRatesTo();\n\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate);\n\n int tableIndex = rate.getRateTable().intValue();\n CostRateTable table = resource.getCostRateTable(tableIndex);\n if (table == null)\n {\n table = new CostRateTable();\n resource.setCostRateTable(tableIndex, table);\n }\n table.add(entry);\n tables.add(table);\n }\n\n for (CostRateTable table : tables)\n {\n Collections.sort(table);\n }\n }\n }", "public void renumberUniqueIDs()\n {\n int uid = firstUniqueID();\n for (T entity : this)\n {\n entity.setUniqueID(Integer.valueOf(uid++));\n }\n }", "public static BMatrixRMaj elementLessThan(DMatrixRMaj A , double value , BMatrixRMaj output )\n {\n if( output == null ) {\n output = new BMatrixRMaj(A.numRows,A.numCols);\n }\n\n output.reshape(A.numRows, A.numCols);\n\n int N = A.getNumElements();\n\n for (int i = 0; i < N; i++) {\n output.data[i] = A.data[i] < value;\n }\n\n return output;\n }", "public boolean isEmbeddedProperty(String targetTypeName, List<String> namesWithoutAlias) {\n\t\tOgmEntityPersister persister = getPersister( targetTypeName );\n\t\tType propertyType = persister.getPropertyType( namesWithoutAlias.get( 0 ) );\n\t\tif ( propertyType.isComponentType() ) {\n\t\t\t// Embedded\n\t\t\treturn true;\n\t\t}\n\t\telse if ( propertyType.isAssociationType() ) {\n\t\t\tJoinable associatedJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( persister.getFactory() );\n\t\t\tif ( associatedJoinable.isCollection() ) {\n\t\t\t\tOgmCollectionPersister collectionPersister = (OgmCollectionPersister) associatedJoinable;\n\t\t\t\treturn collectionPersister.getType().isComponentType();\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public List<ServerRedirect> tableServers(int clientId) {\n List<ServerRedirect> servers = new ArrayList<>();\n\n try {\n Client client = ClientService.getInstance().getClient(clientId);\n servers = tableServers(client.getProfile().getId(), client.getActiveServerGroup());\n } catch (SQLException e) {\n e.printStackTrace();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return servers;\n }", "public void addFile(File file) {\n String name = \"file\";\n files.put(normalizeDuplicateName(name), file);\n }", "public List<MapRow> read() throws IOException\n {\n List<MapRow> result = new ArrayList<MapRow>();\n int fileCount = m_stream.readInt();\n if (fileCount != 0)\n {\n for (int index = 0; index < fileCount; index++)\n {\n // We use a LinkedHashMap to preserve insertion order in iteration\n // Useful when debugging the file format.\n Map<String, Object> map = new LinkedHashMap<String, Object>();\n readBlock(map);\n result.add(new MapRow(map));\n }\n }\n return result;\n }", "protected boolean isSlopDead(Cluster cluster, Set<String> storeNames, Slop slop) {\n // destination node , no longer exists\n if(!cluster.getNodeIds().contains(slop.getNodeId())) {\n return true;\n }\n\n // destination store, no longer exists\n if(!storeNames.contains(slop.getStoreName())) {\n return true;\n }\n\n // else. slop is alive\n return false;\n }" ]
Parse an extended attribute date value. @param value string representation @return date value
[ "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 }" ]
[ "private void writeStringField(String fieldName, Object value) throws IOException\n {\n String val = value.toString();\n if (!val.isEmpty())\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }", "private static void updateJar(final File file, final byte[] searchPattern, final int[] badSkipBytes, final int newSig, final int endSig) throws IOException {\n final RandomAccessFile raf = new RandomAccessFile(file, \"rw\");\n try {\n final FileChannel channel = raf.getChannel();\n try {\n long pos = channel.size() - ENDLEN;\n final ScanContext context;\n if (newSig == CRIPPLED_ENDSIG) {\n context = new ScanContext(GOOD_ENDSIG_PATTERN, CRIPPLED_ENDSIG_PATTERN);\n } else if (newSig == GOOD_ENDSIG) {\n context = new ScanContext(CRIPPLED_ENDSIG_PATTERN, GOOD_ENDSIG_PATTERN);\n } else {\n context = null;\n }\n\n if (!validateEndRecord(file, channel, pos, endSig)) {\n pos = scanForEndSig(file, channel, context);\n }\n if (pos == -1) {\n if (context.state == State.NOT_FOUND) {\n // Don't fail patching if we cannot validate a valid zip\n PatchLogger.ROOT_LOGGER.cannotInvalidateZip(file.getAbsolutePath());\n }\n return;\n }\n // Update the central directory record\n channel.position(pos);\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(newSig);\n buffer.flip();\n while (buffer.hasRemaining()) {\n channel.write(buffer);\n }\n } finally {\n safeClose(channel);\n }\n } finally {\n safeClose(raf);\n }\n }", "public void remove(Identity oid)\r\n {\r\n //processQueue();\r\n if(oid != null)\r\n {\r\n removeTracedIdentity(oid);\r\n objectTable.remove(buildKey(oid));\r\n if(log.isDebugEnabled()) log.debug(\"Remove object \" + oid);\r\n }\r\n }", "public int length() {\n int length = 1 + 2 + deviceToken.length + 2 + payload.length;\n final int marshalledLength = marshall().length;\n assert marshalledLength == length;\n return length;\n }", "public int getRegisteredResourceRequestCount(K key) {\n if(requestQueueMap.containsKey(key)) {\n Queue<AsyncResourceRequest<V>> requestQueue = getRequestQueueForExistingKey(key);\n // FYI: .size() is not constant time in the next call. ;)\n if(requestQueue != null) {\n return requestQueue.size();\n }\n }\n return 0;\n }", "@SuppressWarnings(\"unchecked\")\n public <V3, M4, C, N, Q> N getSceneRoot(AiWrapperProvider<V3, M4, C, N, Q> \n wrapperProvider) {\n\n return (N) m_sceneRoot;\n }", "public static String getDefaultConversionFor(String javaType)\r\n {\r\n return _jdbcConversions.containsKey(javaType) ? (String)_jdbcConversions.get(javaType) : null;\r\n }", "public static int cudnnGetCTCLossWorkspaceSize(\n cudnnHandle handle, \n cudnnTensorDescriptor probsDesc, /** Tensor descriptor for probabilities, the dimensions are T,N,A (T is the\n timing steps, N is the mini batch size, A is the alphabet size) */\n cudnnTensorDescriptor gradientsDesc, /** Tensor descriptor for gradients, the\n dimensions are T,N,A. To compute costs\n only, set it to NULL */\n int[] labels, /** labels, in CPU memory */\n int[] labelLengths, /** the length of each label, in CPU memory */\n int[] inputLengths, /** the lengths of timing steps in each batch, in CPU memory */\n int algo, /** algorithm selected, supported now 0 and 1 */\n cudnnCTCLossDescriptor ctcLossDesc, \n long[] sizeInBytes)/** pointer to the returned workspace size */\n {\n return checkResult(cudnnGetCTCLossWorkspaceSizeNative(handle, probsDesc, gradientsDesc, labels, labelLengths, inputLengths, algo, ctcLossDesc, sizeInBytes));\n }", "public void addAliasToConfigSite(String alias, String redirect, String offset) {\n\n long timeOffset = 0;\n try {\n timeOffset = Long.parseLong(offset);\n } catch (Throwable e) {\n // ignore\n }\n CmsSiteMatcher siteMatcher = new CmsSiteMatcher(alias, timeOffset);\n boolean redirectVal = new Boolean(redirect).booleanValue();\n siteMatcher.setRedirect(redirectVal);\n m_aliases.add(siteMatcher);\n }" ]
Creates an Executor that is based on daemon threads. This allows the program to quit without explicitly calling shutdown on the pool @return the newly created single-threaded Executor
[ "public static ExecutorService newSingleThreadDaemonExecutor() {\n return Executors.newSingleThreadExecutor(r -> {\n Thread t = Executors.defaultThreadFactory().newThread(r);\n t.setDaemon(true);\n return t;\n });\n }" ]
[ "public 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 }", "public HalfEdge getEdge(int i) {\n HalfEdge he = he0;\n while (i > 0) {\n he = he.next;\n i--;\n }\n while (i < 0) {\n he = he.prev;\n i++;\n }\n return he;\n }", "private void writeActivity(Task mpxj)\n {\n ActivityType xml = m_factory.createActivityType();\n m_project.getActivity().add(xml);\n\n Task parentTask = mpxj.getParentTask();\n Integer parentObjectID = parentTask == null ? null : parentTask.getUniqueID();\n\n xml.setActualStartDate(mpxj.getActualStart());\n xml.setActualFinishDate(mpxj.getActualFinish());\n xml.setAtCompletionDuration(getDuration(mpxj.getDuration()));\n xml.setCalendarObjectId(getCalendarUniqueID(mpxj.getCalendar()));\n xml.setDurationPercentComplete(getPercentage(mpxj.getPercentageComplete()));\n xml.setDurationType(DURATION_TYPE_MAP.get(mpxj.getType()));\n xml.setFinishDate(mpxj.getFinish());\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setId(getActivityID(mpxj));\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setPercentComplete(getPercentage(mpxj.getPercentageComplete()));\n xml.setPercentCompleteType(\"Duration\");\n xml.setPrimaryConstraintType(CONSTRAINT_TYPE_MAP.get(mpxj.getConstraintType()));\n xml.setPrimaryConstraintDate(mpxj.getConstraintDate());\n xml.setPlannedDuration(getDuration(mpxj.getDuration()));\n xml.setPlannedFinishDate(mpxj.getFinish());\n xml.setPlannedStartDate(mpxj.getStart());\n xml.setProjectObjectId(PROJECT_OBJECT_ID);\n xml.setRemainingDuration(getDuration(mpxj.getRemainingDuration()));\n xml.setRemainingEarlyFinishDate(mpxj.getEarlyFinish());\n xml.setRemainingEarlyStartDate(mpxj.getResume());\n xml.setRemainingLaborCost(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingLaborUnits(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingNonLaborCost(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingNonLaborUnits(NumberHelper.DOUBLE_ZERO);\n xml.setStartDate(mpxj.getStart());\n xml.setStatus(getActivityStatus(mpxj));\n xml.setType(extractAndConvertTaskType(mpxj));\n xml.setWBSObjectId(parentObjectID);\n xml.getUDF().addAll(writeUDFType(FieldTypeClass.TASK, mpxj));\n\n writePredecessors(mpxj);\n }", "private String long2string(Long value, DateTimeFormat fmt) {\n // for html5 inputs, use \"\" for no value\n if (value == null) return \"\";\n Date date = UTCDateBox.utc2date(value);\n return date != null ? fmt.format(date) : null;\n }", "public static List<BoxTermsOfService.Info> getAllTermsOfServices(final BoxAPIConnection api,\n BoxTermsOfService.TermsOfServiceType\n termsOfServiceType) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (termsOfServiceType != null) {\n builder.appendParam(\"tos_type\", termsOfServiceType.toString());\n }\n\n URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n List<BoxTermsOfService.Info> termsOfServices = new ArrayList<BoxTermsOfService.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject termsOfServiceJSON = value.asObject();\n BoxTermsOfService termsOfService = new BoxTermsOfService(api, termsOfServiceJSON.get(\"id\").asString());\n BoxTermsOfService.Info info = termsOfService.new Info(termsOfServiceJSON);\n termsOfServices.add(info);\n }\n\n return termsOfServices;\n }", "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 PeriodicEvent runEvery(Runnable task, float delay, float period,\n int repetitions) {\n if (repetitions < 1) {\n return null;\n } else if (repetitions == 1) {\n // Better to burn a handful of CPU cycles than to churn memory by\n // creating a new callback\n return runAfter(task, delay);\n } else {\n return runEvery(task, delay, period, new RunFor(repetitions));\n }\n }", "public static java.util.Date getDateTime(Object value) {\n try {\n return toDateTime(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }", "private Set<String> checkModel(final ModelNode model, TransformationContext context) throws OperationFailedException {\n final Set<String> attributes = new HashSet<String>();\n AttributeTransformationRequirementChecker checker;\n for (final String attribute : attributeNames) {\n if (model.hasDefined(attribute)) {\n if (attributeCheckers != null && (checker = attributeCheckers.get(attribute)) != null) {\n if (checker.isAttributeTransformationRequired(attribute, model.get(attribute), context)) {\n attributes.add(attribute);\n }\n } else if (SIMPLE_EXPRESSIONS.isAttributeTransformationRequired(attribute, model.get(attribute), context)) {\n attributes.add(attribute);\n }\n }\n }\n return attributes;\n }" ]
Returns the value of the element with the minimum value @param A (Input) Matrix. Not modified. @return scalar
[ "public static double elementMin( DMatrixSparseCSC A ) {\n if( A.nz_length == 0)\n return 0;\n\n // if every element is assigned a value then the first element can be a minimum.\n // Otherwise zero needs to be considered\n double min = A.isFull() ? A.nz_values[0] : 0;\n for(int i = 0; i < A.nz_length; i++ ) {\n double val = A.nz_values[i];\n if( val < min ) {\n min = val;\n }\n }\n\n return min;\n }" ]
[ "public ContentAssistEntry createProposal(final String proposal, final ContentAssistContext context) {\n return this.createProposal(proposal, context.getPrefix(), context, ContentAssistEntry.KIND_UNKNOWN, null);\n }", "private static int calculateBeginLine(RuleViolation pmdViolation) {\n int minLine = Math.min(pmdViolation.getBeginLine(), pmdViolation.getEndLine());\n return minLine > 0 ? minLine : calculateEndLine(pmdViolation);\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}", "public static void checkSvdMatrixSize(DMatrixRMaj U, boolean tranU, DMatrixRMaj W, DMatrixRMaj V, boolean tranV ) {\n int numSingular = Math.min(W.numRows,W.numCols);\n boolean compact = W.numRows == W.numCols;\n\n if( compact ) {\n if( U != null ) {\n if( tranU && U.numRows != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n else if( !tranU && U.numCols != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n }\n\n if( V != null ) {\n if( tranV && V.numRows != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n else if( !tranV && V.numCols != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n }\n } else {\n if( U != null && U.numRows != U.numCols )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n if( V != null && V.numRows != V.numCols )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n if( U != null && U.numRows != W.numRows )\n throw new IllegalArgumentException(\"Unexpected size of W\");\n if( V != null && V.numRows != W.numCols )\n throw new IllegalArgumentException(\"Unexpected size of W\");\n }\n }", "public static int getPercentage(String percentage) {\n if (isNotEmpty(percentage) && isNumeric(percentage)) {\n int p = Integer.parseInt(percentage);\n return p;\n } else {\n return 0;\n }\n }", "protected final void _onConnect(WebSocketContext context) {\n if (null != connectionListener) {\n connectionListener.onConnect(context);\n }\n connectionListenerManager.notifyFreeListeners(context, false);\n Act.eventBus().emit(new WebSocketConnectEvent(context));\n }", "public void moveDown(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if ((index >= 0) && (index < (m_container.getComponentCount() - 1))) {\n m_container.removeComponent(row);\n m_container.addComponent(row, index + 1);\n }\n updateButtonBars();\n }", "protected void markStatementsForDeletion(StatementDocument currentDocument,\n\t\t\tList<Statement> deleteStatements) {\n\t\tfor (Statement statement : deleteStatements) {\n\t\t\tboolean found = false;\n\t\t\tfor (StatementGroup sg : currentDocument.getStatementGroups()) {\n\t\t\t\tif (!sg.getProperty().equals(statement.getMainSnak().getPropertyId())) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tStatement changedStatement = null;\n\t\t\t\tfor (Statement existingStatement : sg) {\n\t\t\t\t\tif (existingStatement.equals(statement)) {\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\ttoDelete.add(statement.getStatementId());\n\t\t\t\t\t} else if (existingStatement.getStatementId().equals(\n\t\t\t\t\t\t\tstatement.getStatementId())) {\n\t\t\t\t\t\t// (we assume all existing statement ids to be nonempty\n\t\t\t\t\t\t// here)\n\t\t\t\t\t\tchangedStatement = existingStatement;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!found) {\n\t\t\t\t\tStringBuilder warning = new StringBuilder();\n\t\t\t\t\twarning.append(\"Cannot delete statement (id \")\n\t\t\t\t\t\t\t.append(statement.getStatementId())\n\t\t\t\t\t\t\t.append(\") since it is not present in data. Statement was:\\n\")\n\t\t\t\t\t\t\t.append(statement);\n\n\t\t\t\t\tif (changedStatement != null) {\n\t\t\t\t\t\twarning.append(\n\t\t\t\t\t\t\t\t\"\\nThe data contains another statement with the same id: maybe it has been edited? Other statement was:\\n\")\n\t\t\t\t\t\t\t\t.append(changedStatement);\n\t\t\t\t\t}\n\t\t\t\t\tlogger.warn(warning.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public static void sqrt(Complex_F64 input, Complex_F64 root)\n {\n double r = input.getMagnitude();\n double a = input.real;\n\n root.real = Math.sqrt((r+a)/2.0);\n root.imaginary = Math.sqrt((r-a)/2.0);\n if( input.imaginary < 0 )\n root.imaginary = -root.imaginary;\n }" ]
Returns the index of the eigenvalue which has the smallest magnitude. @return index of the smallest magnitude eigen value.
[ "public int getIndexMin() {\n int indexMin = 0;\n double min = getEigenvalue(0).getMagnitude2();\n\n final int N = getNumberOfEigenvalues();\n for( int i = 1; i < N; i++ ) {\n double m = getEigenvalue(i).getMagnitude2();\n if( m < min ) {\n min = m;\n indexMin = i;\n }\n }\n\n return indexMin;\n }" ]
[ "public static base_response unset(nitro_service client, onlinkipv6prefix resource, String[] args) throws Exception{\n\t\tonlinkipv6prefix unsetresource = new onlinkipv6prefix();\n\t\tunsetresource.ipv6prefix = resource.ipv6prefix;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public static <T> int createTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig)\n\t\t\tthrows SQLException {\n\t\tDao<T, ?> dao = DaoManager.createDao(connectionSource, tableConfig);\n\t\treturn doCreateTable(dao, false);\n\t}", "public static Field read(DataInputStream is) throws IOException {\n final byte tag = is.readByte();\n final Field result;\n switch (tag) {\n case 0x0f:\n case 0x10:\n case 0x11:\n result = new NumberField(tag, is);\n break;\n\n case 0x14:\n result = new BinaryField(is);\n break;\n\n case 0x26:\n result = new StringField(is);\n break;\n\n default:\n throw new IOException(\"Unable to read a field with type tag \" + tag);\n }\n\n logger.debug(\"..received> {}\", result);\n return result;\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 }", "@Override\n public boolean awaitCompletion(long timeout, TimeUnit unit) throws InterruptedException {\n long deadline = unit.toMillis(timeout) + System.currentTimeMillis();\n lock.lock(); try {\n assert shutdown;\n while(activeCount != 0) {\n long remaining = deadline - System.currentTimeMillis();\n if (remaining <= 0) {\n break;\n }\n condition.await(remaining, TimeUnit.MILLISECONDS);\n }\n boolean allComplete = activeCount == 0;\n if (!allComplete) {\n ProtocolLogger.ROOT_LOGGER.debugf(\"ActiveOperation(s) %s have not completed within %d %s\", activeRequests.keySet(), timeout, unit);\n }\n return allComplete;\n } finally {\n lock.unlock();\n }\n }", "public static Button createPublishButton(final I_CmsUpdateListener<String> updateListener) {\n\n Button publishButton = CmsToolBar.createButton(\n FontOpenCms.PUBLISH,\n CmsVaadinUtils.getMessageText(Messages.GUI_PUBLISH_BUTTON_TITLE_0));\n if (CmsAppWorkplaceUi.isOnlineProject()) {\n // disable publishing in online project\n publishButton.setEnabled(false);\n publishButton.setDescription(CmsVaadinUtils.getMessageText(Messages.GUI_TOOLBAR_NOT_AVAILABLE_ONLINE_0));\n }\n publishButton.addClickListener(new ClickListener() {\n\n /** Serial version id. */\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n CmsAppWorkplaceUi.get().disableGlobalShortcuts();\n CmsGwtDialogExtension extension = new CmsGwtDialogExtension(A_CmsUI.get(), updateListener);\n extension.openPublishDialog();\n }\n });\n return publishButton;\n }", "static boolean killProcess(final String processName, int id) {\n int pid;\n try {\n pid = processUtils.resolveProcessId(processName, id);\n if(pid > 0) {\n try {\n Runtime.getRuntime().exec(processUtils.getKillCommand(pid));\n return true;\n } catch (Throwable t) {\n ProcessLogger.ROOT_LOGGER.debugf(t, \"failed to kill process '%s' with pid '%s'\", processName, pid);\n }\n }\n } catch (Throwable t) {\n ProcessLogger.ROOT_LOGGER.debugf(t, \"failed to resolve pid of process '%s'\", processName);\n }\n return false;\n }", "private Month readOptionalMonth(JSONValue val) {\n\n String str = readOptionalString(val);\n if (null != str) {\n try {\n return Month.valueOf(str);\n } catch (@SuppressWarnings(\"unused\") IllegalArgumentException e) {\n // Do nothing -return the default value\n }\n }\n return null;\n }", "public static base_responses add(nitro_service client, inat resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tinat addresources[] = new inat[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new inat();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].publicip = resources[i].publicip;\n\t\t\t\taddresources[i].privateip = resources[i].privateip;\n\t\t\t\taddresources[i].tcpproxy = resources[i].tcpproxy;\n\t\t\t\taddresources[i].ftp = resources[i].ftp;\n\t\t\t\taddresources[i].tftp = resources[i].tftp;\n\t\t\t\taddresources[i].usip = resources[i].usip;\n\t\t\t\taddresources[i].usnip = resources[i].usnip;\n\t\t\t\taddresources[i].proxyip = resources[i].proxyip;\n\t\t\t\taddresources[i].mode = resources[i].mode;\n\t\t\t\taddresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Determines the number of elements that the query would return. Override this method if the size shall be determined in a specific way. @return The number of elements
[ "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 }" ]
[ "private static void listProjectProperties(ProjectFile file)\n {\n SimpleDateFormat df = new SimpleDateFormat(\"dd/MM/yyyy HH:mm z\");\n ProjectProperties properties = file.getProjectProperties();\n Date startDate = properties.getStartDate();\n Date finishDate = properties.getFinishDate();\n String formattedStartDate = startDate == null ? \"(none)\" : df.format(startDate);\n String formattedFinishDate = finishDate == null ? \"(none)\" : df.format(finishDate);\n\n System.out.println(\"MPP file type: \" + properties.getMppFileType());\n System.out.println(\"Project Properties: StartDate=\" + formattedStartDate + \" FinishDate=\" + formattedFinishDate);\n System.out.println();\n }", "public static FileStatus[] getDataChunkFiles(FileSystem fs,\n Path path,\n final int partitionId,\n final int replicaType) throws IOException {\n return fs.listStatus(path, new PathFilter() {\n\n public boolean accept(Path input) {\n if(input.getName().matches(\"^\" + Integer.toString(partitionId) + \"_\"\n + Integer.toString(replicaType) + \"_[\\\\d]+\\\\.data\")) {\n return true;\n } else {\n return false;\n }\n }\n });\n }", "private void sendResponse(final HttpServletResponse res, final CmsSpellcheckingRequest request) throws IOException {\n\n final PrintWriter pw = res.getWriter();\n final JSONObject response = getJsonFormattedSpellcheckResult(request);\n pw.println(response.toString());\n pw.close();\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 static Map<Integer, Integer>\n getMapOfContiguousPartitionRunLengths(final Cluster cluster, int zoneId) {\n Map<Integer, Integer> idToRunLength = getMapOfContiguousPartitions(cluster, zoneId);\n Map<Integer, Integer> runLengthToCount = Maps.newHashMap();\n\n if(idToRunLength.isEmpty()) {\n return runLengthToCount;\n }\n\n for(int runLength: idToRunLength.values()) {\n if(!runLengthToCount.containsKey(runLength)) {\n runLengthToCount.put(runLength, 0);\n }\n runLengthToCount.put(runLength, runLengthToCount.get(runLength) + 1);\n }\n\n return runLengthToCount;\n }", "List<File> getRecursiveThriftFiles(MavenProject project, String outputDirectory, List<File> files) throws IOException {\n HashFunction hashFun = Hashing.md5();\n File dir = new File(new File(project.getFile().getParent(), \"target\"), outputDirectory);\n if (dir.exists()) {\n URI baseDir = getFileURI(dir);\n for (File f : findThriftFilesInDirectory(dir)) {\n URI fileURI = getFileURI(f);\n String relPath = baseDir.relativize(fileURI).getPath();\n File destFolder = getResourcesOutputDirectory();\n destFolder.mkdirs();\n File destFile = new File(destFolder, relPath);\n if (!destFile.exists() || (destFile.isFile() && !Files.hash(f, hashFun).equals(Files.hash(destFile, hashFun)))) {\n getLog().info(format(\"copying %s to %s\", f.getCanonicalPath(), destFile.getCanonicalPath()));\n copyFile(f, destFile);\n }\n files.add(destFile);\n }\n }\n Map<String, MavenProject> refs = project.getProjectReferences();\n for (String name : refs.keySet()) {\n getRecursiveThriftFiles(refs.get(name), outputDirectory, files);\n }\n return files;\n }", "protected void processLink(Row row)\n {\n Task predecessorTask = m_project.getTaskByUniqueID(row.getInteger(\"LINK_PRED_UID\"));\n Task successorTask = m_project.getTaskByUniqueID(row.getInteger(\"LINK_SUCC_UID\"));\n if (predecessorTask != null && successorTask != null)\n {\n RelationType type = RelationType.getInstance(row.getInt(\"LINK_TYPE\"));\n TimeUnit durationUnits = MPDUtility.getDurationTimeUnits(row.getInt(\"LINK_LAG_FMT\"));\n Duration duration = MPDUtility.getDuration(row.getDouble(\"LINK_LAG\").doubleValue(), durationUnits);\n Relation relation = successorTask.addPredecessor(predecessorTask, type, duration);\n relation.setUniqueID(row.getInteger(\"LINK_UID\"));\n m_eventManager.fireRelationReadEvent(relation);\n }\n }", "public boolean setMethodArguments(String pathName, String methodName, Integer ordinal, Object... arguments) {\n try {\n BasicNameValuePair[] params = new BasicNameValuePair[arguments.length + 2];\n int x = 0;\n for (Object argument : arguments) {\n params[x] = new BasicNameValuePair(\"arguments[]\", argument.toString());\n x++;\n }\n params[x] = new BasicNameValuePair(\"profileIdentifier\", this._profileName);\n params[x + 1] = new BasicNameValuePair(\"ordinal\", ordinal.toString());\n\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName) + \"/\" + methodName, params));\n\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return false;\n }", "public static String nameFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).name() : null;\n }" ]
Return all scripts of a given type @param type integer value of type @return Array of scripts of the given type
[ "public Script[] getScripts(Integer type) {\n ArrayList<Script> returnData = new ArrayList<>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" ORDER BY \" + Constants.GENERIC_ID);\n if (type != null) {\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE \" + Constants.SCRIPT_TYPE + \"= ?\" +\n \" ORDER BY \" + Constants.GENERIC_ID);\n statement.setInt(1, type);\n }\n\n logger.info(\"Query: {}\", statement);\n\n results = statement.executeQuery();\n while (results.next()) {\n returnData.add(scriptFromSQLResult(results));\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return returnData.toArray(new Script[0]);\n }" ]
[ "private void ensureReferencedPKs(ModelDef modelDef, ReferenceDescriptorDef refDef) throws ConstraintException\r\n {\r\n String targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF);\r\n ClassDescriptorDef targetClassDef = modelDef.getClass(targetClassName);\r\n\r\n ensurePKsFromHierarchy(targetClassDef);\r\n }", "public void set(Object receiver, String fieldName, /* @Nullable */ Object value) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {\n\t\tPreconditions.checkNotNull(receiver,\"receiver\");\n\t\tPreconditions.checkNotNull(fieldName,\"fieldName\");\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\tf.set(receiver, value);\n\t}", "protected void clearStatementCaches(boolean internalClose) {\r\n\r\n\t\tif (this.statementCachingEnabled){ // safety\r\n\r\n\t\t\tif (internalClose){\r\n\t\t\t\tthis.callableStatementCache.clear();\r\n\t\t\t\tthis.preparedStatementCache.clear();\r\n\t\t\t} else {\r\n\t\t\t\tif (this.pool.closeConnectionWatch){ // debugging enabled?\r\n\t\t\t\t\tthis.callableStatementCache.checkForProperClosure();\r\n\t\t\t\t\tthis.preparedStatementCache.checkForProperClosure();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}", "@Override\n\tpublic String toNormalizedString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = getStringCache().normalizedString) == null) {\n\t\t\tgetStringCache().normalizedString = result = toNormalizedString(IPv6StringCache.normalizedParams);\n\t\t}\n\t\treturn result;\n\t}", "public void setOutlineCode(int index, String value)\n {\n set(selectField(TaskFieldLists.CUSTOM_OUTLINE_CODE, index), value);\n }", "public void setStatusBarMessage(final String message)\r\n {\r\n // Guaranteed to return a non-null array\r\n Object[] listeners = listenerList.getListenerList();\r\n // Process the listeners last to first, notifying\r\n // those that are interested in this event\r\n for (int i = listeners.length-2; i>=0; i-=2) {\r\n if (listeners[i]==StatusMessageListener.class) \r\n {\r\n ((StatusMessageListener)listeners[i+1]).statusMessageReceived(message);\r\n } \r\n } \r\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 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 }", "public static Boolean askConfirm(Boolean confirm, String opDesc) throws IOException {\n if(confirm) {\n System.out.println(\"Confirmed \" + opDesc + \" in command-line.\");\n return true;\n } else {\n System.out.println(\"Are you sure you want to \" + opDesc + \"? (yes/no)\");\n BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));\n String text = buffer.readLine().toLowerCase(Locale.ENGLISH);\n boolean go = text.equals(\"yes\") || text.equals(\"y\");\n if (!go) {\n System.out.println(\"Did not confirm; \" + opDesc + \" aborted.\");\n }\n return go;\n }\n }" ]
Writes the timephased data for a resource assignment. @param mpx MPXJ assignment @param xml MSDPI assignment
[ "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 }" ]
[ "private ServerDetails createInitialDeployDetailsFromOldDeployDetails(ServerDetails oldDeployerDetails) {\n RepositoryConf oldDeployRepositoryConfig = oldDeployerDetails.getDeployReleaseRepository();\n RepositoryConf oldSnapshotDeployRepositoryConfig = oldDeployerDetails.getDeploySnapshotRepository();\n RepositoryConf deployReleaseRepos = oldDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldDeployRepositoryConfig;\n RepositoryConf deploySnapshotRepos = oldSnapshotDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldSnapshotDeployRepositoryConfig;\n return new ServerDetails(oldDeployerDetails.getArtifactoryName(), oldDeployerDetails.getArtifactoryUrl(),\n deployReleaseRepos, deploySnapshotRepos, null, null, null, null);\n }", "public <CT> CT callBatchTasks(ConnectionSource connectionSource, Callable<CT> callable) throws SQLException {\n\t\tif (connectionSource.isSingleConnection(tableInfo.getTableName())) {\n\t\t\tsynchronized (this) {\n\t\t\t\treturn doCallBatchTasks(connectionSource, callable);\n\t\t\t}\n\t\t} else {\n\t\t\treturn doCallBatchTasks(connectionSource, callable);\n\t\t}\n\t}", "public void forAllCollectionDefinitions(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getCollections(); it.hasNext(); )\r\n {\r\n _curCollectionDef = (CollectionDescriptorDef)it.next();\r\n if (!isFeatureIgnored(LEVEL_COLLECTION) &&\r\n !_curCollectionDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n generate(template);\r\n }\r\n }\r\n _curCollectionDef = null;\r\n }", "public UniqueEntityLoader buildLoader(\n\t\t\tOuterJoinLoadable persister,\n\t\t\tint batchSize,\n\t\t\tLockMode lockMode,\n\t\t\tSessionFactoryImplementor factory,\n\t\t\tLoadQueryInfluencers influencers,\n\t\t\tBatchableEntityLoaderBuilder innerEntityLoaderBuilder) {\n\t\tif ( batchSize <= 1 ) {\n\t\t\t// no batching\n\t\t\treturn buildNonBatchingLoader( persister, lockMode, factory, influencers, innerEntityLoaderBuilder );\n\t\t}\n\t\treturn buildBatchingLoader( persister, batchSize, lockMode, factory, influencers, innerEntityLoaderBuilder );\n\t}", "private void logUnexpectedStructure()\n {\n if (m_log != null)\n {\n m_log.println(\"ABORTED COLUMN - unexpected structure: \" + m_currentColumn.getClass().getSimpleName() + \" \" + m_currentColumn.getName());\n }\n }", "public T removeFile(final String name, final List<String> path, final byte[] existingHash, final boolean isDirectory) {\n return removeFile(name, path, existingHash, isDirectory, null);\n }", "@Override\n public ArtifactoryResponse restCall(ArtifactoryRequest artifactoryRequest) throws IOException {\n HttpRequestBase httpRequest;\n\n String requestPath = \"/\" + artifactoryRequest.getApiUrl();\n ContentType contentType = Util.getContentType(artifactoryRequest.getRequestType());\n\n String queryPath = \"\";\n if (!artifactoryRequest.getQueryParams().isEmpty()) {\n queryPath = Util.getQueryPath(\"?\", artifactoryRequest.getQueryParams());\n }\n\n switch (artifactoryRequest.getMethod()) {\n case GET:\n httpRequest = new HttpGet();\n\n break;\n\n case POST:\n httpRequest = new HttpPost();\n setEntity((HttpPost)httpRequest, artifactoryRequest.getBody(), contentType);\n\n break;\n\n case PUT:\n httpRequest = new HttpPut();\n setEntity((HttpPut)httpRequest, artifactoryRequest.getBody(), contentType);\n\n break;\n\n case DELETE:\n httpRequest = new HttpDelete();\n\n break;\n\n case PATCH:\n httpRequest = new HttpPatch();\n setEntity((HttpPatch)httpRequest, artifactoryRequest.getBody(), contentType);\n break;\n\n case OPTIONS:\n httpRequest = new HttpOptions();\n break;\n\n default:\n throw new IllegalArgumentException(\"Unsupported request method.\");\n }\n\n httpRequest.setURI(URI.create(url + requestPath + queryPath));\n addAccessTokenHeaderIfNeeded(httpRequest);\n\n if (contentType != null) {\n httpRequest.setHeader(\"Content-type\", contentType.getMimeType());\n }\n\n Map<String, String> headers = artifactoryRequest.getHeaders();\n for (String key : headers.keySet()) {\n httpRequest.setHeader(key, headers.get(key));\n }\n\n HttpResponse httpResponse = httpClient.execute(httpRequest);\n return new ArtifactoryResponseImpl(httpResponse);\n }", "protected Object checkUndefined(Object val) {\n if (val instanceof String && ((String) val).equals(\"undefined\")) {\n return null;\n }\n return val;\n }", "public float getBoundsDepth() {\n if (mSceneObject != null) {\n GVRSceneObject.BoundingVolume v = mSceneObject.getBoundingVolume();\n return v.maxCorner.z - v.minCorner.z;\n }\n return 0f;\n }" ]
Get the configuration for a TMS layer by retrieving and parsing it's XML description file. The parsing is done using JaxB. @param layer the tms layer to get capabilities for. @return Returns the description as a Java configuration object. @throws TmsLayerException In case something went wrong trying to find or parse the XML description file.
[ "public TileMap getCapabilities(TmsLayer layer) throws TmsLayerException {\n\t\ttry {\n\t\t\t// Create a JaxB unmarshaller:\n\t\t\tJAXBContext context = JAXBContext.newInstance(TileMap.class);\n\t\t\tUnmarshaller um = context.createUnmarshaller();\n\n\t\t\t// Find out where to retrieve the capabilities and unmarshall:\n\t\t\tif (layer.getBaseTmsUrl().startsWith(CLASSPATH)) {\n\t\t\t\tString location = layer.getBaseTmsUrl().substring(CLASSPATH.length());\n\t\t\t\tif (location.length() > 0 && location.charAt(0) == '/') {\n\t\t\t\t\t// classpath resources should not start with a slash, but they often do\n\t\t\t\t\tlocation = location.substring(1);\n\t\t\t\t}\n\t\t\t\tClassLoader cl = Thread.currentThread().getContextClassLoader();\n\t\t\t\tif (null == cl) {\n\t\t\t\t\tcl = getClass().getClassLoader(); // NOSONAR fallback from proper behaviour for some environments\n\t\t\t\t}\n\t\t\t\tInputStream is = cl.getResourceAsStream(location);\n\t\t\t\tif (null != is) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn (TileMap) um.unmarshal(is);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tis.close();\n\t\t\t\t\t\t} catch (IOException ioe) {\n\t\t\t\t\t\t\t// ignore, just closing the stream\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrow new TmsLayerException(TmsLayerException.COULD_NOT_FIND_FILE, layer.getBaseTmsUrl());\n\t\t\t}\n\n\t\t\t// Normal case, find the URL and unmarshal:\n\t\t\treturn (TileMap) um.unmarshal(httpService.getStream(layer.getBaseTmsUrl(), layer));\n\t\t} catch (JAXBException e) {\n\t\t\tthrow new TmsLayerException(e, TmsLayerException.COULD_NOT_READ_FILE, layer.getBaseTmsUrl());\n\t\t} catch (IOException e) {\n\t\t\tthrow new TmsLayerException(e, TmsLayerException.COULD_NOT_READ_FILE, layer.getBaseTmsUrl());\n\t\t}\n\t}" ]
[ "public Set<String> rangeByLexReverse(final LexRange lexRange) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n if (lexRange.hasLimit()) {\n return jedis.zrevrangeByLex(getKey(), lexRange.fromReverse(), lexRange.toReverse(), lexRange.offset(), lexRange.count());\n } else {\n return jedis.zrevrangeByLex(getKey(), lexRange.fromReverse(), lexRange.toReverse());\n }\n }\n });\n }", "public static <T> T objectify(ObjectMapper mapper, Object source, JavaType targetType) {\n try {\n return mapper.readValue(mapper.writeValueAsBytes(source), targetType);\n } catch (RuntimeException e) {\n throw e;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "public Metadata remove(String path) {\n this.values.remove(this.pathToProperty(path));\n this.addOp(\"remove\", path, (String) null);\n return this;\n }", "public void configure(@Observes(precedence = -10) ArquillianDescriptor arquillianDescriptor) {\n Map<String, String> config = arquillianDescriptor.extension(EXTENSION_NAME).getExtensionProperties();\n CubeConfiguration cubeConfiguration = CubeConfiguration.fromMap(config);\n configurationProducer.set(cubeConfiguration);\n }", "public static base_responses update(nitro_service client, autoscaleaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleaction updateresources[] = new autoscaleaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new autoscaleaction();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].profilename = resources[i].profilename;\n\t\t\t\tupdateresources[i].parameters = resources[i].parameters;\n\t\t\t\tupdateresources[i].vmdestroygraceperiod = resources[i].vmdestroygraceperiod;\n\t\t\t\tupdateresources[i].quiettime = resources[i].quiettime;\n\t\t\t\tupdateresources[i].vserver = resources[i].vserver;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public static base_response add(nitro_service client, linkset resource) throws Exception {\n\t\tlinkset addresource = new linkset();\n\t\taddresource.id = resource.id;\n\t\treturn addresource.add_resource(client);\n\t}", "private InterfaceAddress findMatchingAddress(DeviceAnnouncement aDevice, NetworkInterface networkInterface) {\n for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {\n if ((address.getBroadcast() != null) &&\n Util.sameNetwork(address.getNetworkPrefixLength(), aDevice.getAddress(), address.getAddress())) {\n return address;\n }\n }\n return null;\n }", "public Reply getReplyInfo(String topicId, String replyId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_REPLIES_GET_INFO);\r\n parameters.put(\"topic_id\", topicId);\r\n parameters.put(\"reply_id\", replyId);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element replyElement = response.getPayload();\r\n\r\n return parseReply(replyElement);\r\n }", "public String urlDecode(String s) {\n if (s == null || s.isEmpty()) {\n return s;\n }\n return URL.decodeQueryString(s);\n }" ]
Unicast addresses allocated for private use @see java.net.InetAddress#isSiteLocalAddress()
[ "public boolean isPrivate() {\n\t\t// refer to RFC 1918\n // 10/8 prefix\n // 172.16/12 prefix (172.16.0.0 – 172.31.255.255)\n // 192.168/16 prefix\n\t\tIPv4AddressSegment seg0 = getSegment(0);\n\t\tIPv4AddressSegment seg1 = getSegment(1);\n\t\treturn seg0.matches(10)\n\t\t\t|| seg0.matches(172) && seg1.matchesWithPrefixMask(16, 4)\n\t\t\t|| seg0.matches(192) && seg1.matches(168);\n\t}" ]
[ "public CollectionRequest<Team> findByOrganization(String organization) {\n \n String path = String.format(\"/organizations/%s/teams\", organization);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }", "@JmxGetter(name = \"lastSwapped\", description = \"Time in milliseconds since the store was swapped\")\n public long getLastSwapped() {\n long timeSinceLastSwap = System.currentTimeMillis() - lastSwapped;\n return timeSinceLastSwap > 0 ? timeSinceLastSwap : 0;\n }", "private Double zeroIsNull(Double value)\n {\n if (value != null && value.doubleValue() == 0)\n {\n value = null;\n }\n return value;\n }", "private void processBlock(List<GenericCriteria> list, byte[] block)\n {\n if (block != null)\n {\n if (MPPUtility.getShort(block, 0) > 0x3E6)\n {\n addCriteria(list, block);\n }\n else\n {\n switch (block[0])\n {\n case (byte) 0x0B:\n {\n processBlock(list, getChildBlock(block));\n break;\n }\n\n case (byte) 0x06:\n {\n processBlock(list, getListNextBlock(block));\n break;\n }\n\n case (byte) 0xED: // EQUALS\n {\n addCriteria(list, block);\n break;\n }\n\n case (byte) 0x19: // AND\n case (byte) 0x1B:\n {\n addBlock(list, block, TestOperator.AND);\n break;\n }\n\n case (byte) 0x1A: // OR\n case (byte) 0x1C:\n {\n addBlock(list, block, TestOperator.OR);\n break;\n }\n }\n }\n }\n }", "public static void addLazyDefinitions(SourceBuilder code) {\n Set<Declaration> defined = new HashSet<>();\n\n // Definitions may lazily declare new names; ensure we add them all\n List<Declaration> declarations =\n code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList());\n while (!defined.containsAll(declarations)) {\n for (Declaration declaration : declarations) {\n if (defined.add(declaration)) {\n code.add(code.scope().get(declaration).definition);\n }\n }\n declarations = code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList());\n }\n }", "public static boolean changeHost(String hostName,\n boolean enable,\n boolean disable,\n boolean remove,\n boolean isEnabled,\n boolean exists) throws Exception {\n\n // Open the file that is the first\n // command line parameter\n File hostsFile = new File(\"/etc/hosts\");\n FileInputStream fstream = new FileInputStream(\"/etc/hosts\");\n\n File outFile = null;\n BufferedWriter bw = null;\n // only do file output for destructive operations\n if (!exists && !isEnabled) {\n outFile = File.createTempFile(\"HostsEdit\", \".tmp\");\n bw = new BufferedWriter(new FileWriter(outFile));\n System.out.println(\"File name: \" + outFile.getPath());\n }\n\n // Get the object of DataInputStream\n DataInputStream in = new DataInputStream(fstream);\n BufferedReader br = new BufferedReader(new InputStreamReader(in));\n String strLine;\n boolean foundHost = false;\n boolean hostEnabled = false;\n\n\t\t/*\n * Group 1 - possible commented out host entry\n\t\t * Group 2 - destination address\n\t\t * Group 3 - host name\n\t\t * Group 4 - everything else\n\t\t */\n Pattern pattern = Pattern.compile(\"\\\\s*(#?)\\\\s*([^\\\\s]+)\\\\s*([^\\\\s]+)(.*)\");\n while ((strLine = br.readLine()) != null) {\n\n Matcher matcher = pattern.matcher(strLine);\n\n // if there is a match to the pattern and the host name is the same as the one we want to set\n if (matcher.find() &&\n matcher.group(3).toLowerCase().compareTo(hostName.toLowerCase()) == 0) {\n foundHost = true;\n if (remove) {\n // skip this line altogether\n continue;\n } else if (enable) {\n // we will disregard group 2 and just set it to 127.0.0.1\n if (!exists && !isEnabled)\n bw.write(\"127.0.0.1 \" + matcher.group(3) + matcher.group(4));\n } else if (disable) {\n if (!exists && !isEnabled)\n bw.write(\"# \" + matcher.group(2) + \" \" + matcher.group(3) + matcher.group(4));\n } else if (isEnabled && matcher.group(1).compareTo(\"\") == 0) {\n // host exists and there is no # before it\n hostEnabled = true;\n }\n } else {\n // just write the line back out\n if (!exists && !isEnabled)\n bw.write(strLine);\n }\n\n if (!exists && !isEnabled)\n bw.write('\\n');\n }\n\n // if we didn't find the host in the file but need to enable it\n if (!foundHost && enable) {\n // write a new host entry\n if (!exists && !isEnabled)\n bw.write(\"127.0.0.1 \" + hostName + '\\n');\n }\n // Close the input stream\n in.close();\n\n if (!exists && !isEnabled) {\n bw.close();\n outFile.renameTo(hostsFile);\n }\n\n // return false if the host wasn't found\n if (exists && !foundHost)\n return false;\n\n // return false if the host wasn't enabled\n if (isEnabled && !hostEnabled)\n return false;\n\n return true;\n }", "public int refresh(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedRefresh == null) {\n\t\t\tmappedRefresh = MappedRefresh.build(dao, tableInfo);\n\t\t}\n\t\treturn mappedRefresh.executeRefresh(databaseConnection, data, objectCache);\n\t}", "public ReferrerList getPhotostreamReferrers(Date date, String domain, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_PHOTOSTREAM_REFERRERS, domain, null, null, date, perPage, page);\n }", "public void beforeClose(PBStateEvent event)\r\n {\r\n /*\r\n arminw:\r\n this is a workaround for use in managed environments. When a PB instance is used\r\n within a container a PB.close call is done when leave the container method. This close\r\n the PB handle (but the real instance is still in use) and the PB listener are notified.\r\n But the JTA tx was not committed at\r\n this point in time and the session cache should not be cleared, because the updated/new\r\n objects will be pushed to the real cache on commit call (if we clear, nothing to push).\r\n So we check if the real broker is in a local tx (in this case we are in a JTA tx and the handle\r\n is closed), if true we don't reset the session cache.\r\n */\r\n if(!broker.isInTransaction())\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"Clearing the session cache\");\r\n resetSessionCache();\r\n }\r\n }" ]
Use this API to fetch all the cachepolicylabel resources that are configured on netscaler.
[ "public static cachepolicylabel[] get(nitro_service service) throws Exception{\n\t\tcachepolicylabel obj = new cachepolicylabel();\n\t\tcachepolicylabel[] response = (cachepolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public static void applyDecidedIconOrSetGone(ImageHolder imageHolder, ImageView imageView, int iconColor, boolean tint) {\n if (imageHolder != null && imageView != null) {\n Drawable drawable = ImageHolder.decideIcon(imageHolder, imageView.getContext(), iconColor, tint);\n if (drawable != null) {\n imageView.setImageDrawable(drawable);\n imageView.setVisibility(View.VISIBLE);\n } else if (imageHolder.getBitmap() != null) {\n imageView.setImageBitmap(imageHolder.getBitmap());\n imageView.setVisibility(View.VISIBLE);\n } else {\n imageView.setVisibility(View.GONE);\n }\n } else if (imageView != null) {\n imageView.setVisibility(View.GONE);\n }\n }", "public static BufferedImage resizeToWidth(BufferedImage originalImage, int widthOut) {\n \n int width = originalImage.getWidth();\n \n int height = originalImage.getHeight();\n \n int widthPercent = (widthOut * 100) / width;\n \n int newHeight = (height * widthPercent) / 100;\n \n BufferedImage resizedImage =\n new BufferedImage(widthOut, newHeight, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g = resizedImage.createGraphics();\n g.drawImage(originalImage, 0, 0, widthOut, newHeight, null);\n g.dispose();\n \n return resizedImage;\n }", "public static URI makeWmsGetLayerRequest(\n final WmsLayerParam wmsLayerParam,\n final URI commonURI,\n final Dimension imageSize,\n final double dpi,\n final double angle,\n final ReferencedEnvelope bounds) throws FactoryException, URISyntaxException, IOException {\n if (commonURI == null || commonURI.getAuthority() == null) {\n throw new RuntimeException(\"Invalid WMS URI: \" + commonURI);\n }\n String[] authority = commonURI.getAuthority().split(\":\");\n URL url;\n if (authority.length == 2) {\n url = new URL(\n commonURI.getScheme(),\n authority[0],\n Integer.parseInt(authority[1]),\n commonURI.getPath()\n );\n } else {\n url = new URL(\n commonURI.getScheme(),\n authority[0],\n commonURI.getPath()\n );\n }\n final GetMapRequest getMapRequest = WmsVersion.lookup(wmsLayerParam.version).\n getGetMapRequest(url);\n getMapRequest.setBBox(bounds);\n getMapRequest.setDimensions(imageSize.width, imageSize.height);\n getMapRequest.setFormat(wmsLayerParam.imageFormat);\n getMapRequest.setSRS(CRS.lookupIdentifier(bounds.getCoordinateReferenceSystem(), false));\n\n for (int i = wmsLayerParam.layers.length - 1; i > -1; i--) {\n String layer = wmsLayerParam.layers[i];\n String style = \"\";\n if (wmsLayerParam.styles != null) {\n style = wmsLayerParam.styles[i];\n }\n getMapRequest.addLayer(layer, style);\n }\n final URI getMapUri = getMapRequest.getFinalURL().toURI();\n\n Multimap<String, String> extraParams = HashMultimap.create();\n if (commonURI.getQuery() != null) {\n for (NameValuePair pair: URLEncodedUtils.parse(commonURI, Charset.forName(\"UTF-8\"))) {\n extraParams.put(pair.getName(), pair.getValue());\n }\n }\n extraParams.putAll(wmsLayerParam.getMergeableParams());\n extraParams.putAll(wmsLayerParam.getCustomParams());\n\n if (wmsLayerParam.serverType != null) {\n addDpiParam(extraParams, (int) Math.round(dpi), wmsLayerParam.serverType);\n if (wmsLayerParam.useNativeAngle && angle != 0.0) {\n addAngleParam(extraParams, angle, wmsLayerParam.serverType);\n }\n }\n return URIUtils.addParams(getMapUri, extraParams, Collections.emptySet());\n\n }", "public MaterializeBuilder withActivity(Activity activity) {\n this.mRootView = (ViewGroup) activity.findViewById(android.R.id.content);\n this.mActivity = activity;\n return this;\n }", "public void removeLinks(ServiceReference<D> declarationSRef) {\n D declaration = getDeclaration(declarationSRef);\n for (ServiceReference serviceReference : declaration.getStatus().getServiceReferencesBounded()) {\n // FIXME : In case of multiples Linker, we will remove the link of all the ServiceReference\n // FIXME : event the ones which dun know nothing about\n linkerManagement.unlink(declaration, serviceReference);\n }\n }", "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 }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<EthiopicDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<EthiopicDate>) super.localDateTime(temporal);\n }", "public static base_responses add(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 addresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new sslcertkey();\n\t\t\t\taddresources[i].certkey = resources[i].certkey;\n\t\t\t\taddresources[i].cert = resources[i].cert;\n\t\t\t\taddresources[i].key = resources[i].key;\n\t\t\t\taddresources[i].password = resources[i].password;\n\t\t\t\taddresources[i].fipskey = resources[i].fipskey;\n\t\t\t\taddresources[i].inform = resources[i].inform;\n\t\t\t\taddresources[i].passplain = resources[i].passplain;\n\t\t\t\taddresources[i].expirymonitor = resources[i].expirymonitor;\n\t\t\t\taddresources[i].notificationperiod = resources[i].notificationperiod;\n\t\t\t\taddresources[i].bundle = resources[i].bundle;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static void mergeHints(InputStream is, Map<String,List<Long>> hints) throws IOException {\n final BufferedReader reader = new BufferedReader(\n new InputStreamReader(is, Charsets.UTF_8));\n \n String line;\n while ((line = reader.readLine()) != null) {\n line = line.trim();\n if (line.isEmpty() || line.startsWith(\"#\"))\n continue;\n\n final int equals = line.indexOf('=');\n if (equals <= 0) {\n throw new IOException(\"No '=' character on a non-comment line?: \" + line);\n } else {\n String key = line.substring(0, equals);\n List<Long> values = hints.get(key);\n if (values == null) {\n hints.put(key, values = new ArrayList<>());\n }\n for (String v : line.substring(equals + 1).split(\"[\\\\,]\")) {\n if (!v.isEmpty()) values.add(Long.parseLong(v));\n }\n }\n }\n }" ]
Gets all rows. @return the list of all rows
[ "public List<I_CmsEditableGroupRow> getRows() {\n\n List<I_CmsEditableGroupRow> result = Lists.newArrayList();\n for (Component component : m_container) {\n if (component instanceof I_CmsEditableGroupRow) {\n result.add((I_CmsEditableGroupRow)component);\n }\n }\n return result;\n }" ]
[ "public String getFullContentType() {\n final String url = this.url.toExternalForm().substring(\"data:\".length());\n final int endIndex = url.indexOf(',');\n if (endIndex >= 0) {\n final String contentType = url.substring(0, endIndex);\n if (!contentType.isEmpty()) {\n return contentType;\n }\n }\n return \"text/plain;charset=US-ASCII\";\n }", "private void sortFileList() {\n if (this.size() > 1) {\n Collections.sort(this.fileList, new Comparator() {\n\n public final int compare(final Object o1, final Object o2) {\n final File f1 = (File) o1;\n final File f2 = (File) o2;\n final Object[] f1TimeAndCount = backupSuffixHelper\n .backupTimeAndCount(f1.getName(), baseFile);\n final Object[] f2TimeAndCount = backupSuffixHelper\n .backupTimeAndCount(f2.getName(), baseFile);\n final long f1TimeSuffix = ((Long) f1TimeAndCount[0]).longValue();\n final long f2TimeSuffix = ((Long) f2TimeAndCount[0]).longValue();\n if ((0L == f1TimeSuffix) && (0L == f2TimeSuffix)) {\n final long f1Time = f1.lastModified();\n final long f2Time = f2.lastModified();\n if (f1Time < f2Time) {\n return -1;\n }\n if (f1Time > f2Time) {\n return 1;\n }\n return 0;\n }\n if (f1TimeSuffix < f2TimeSuffix) {\n return -1;\n }\n if (f1TimeSuffix > f2TimeSuffix) {\n return 1;\n }\n final int f1Count = ((Integer) f1TimeAndCount[1]).intValue();\n final int f2Count = ((Integer) f2TimeAndCount[1]).intValue();\n if (f1Count < f2Count) {\n return -1;\n }\n if (f1Count > f2Count) {\n return 1;\n }\n if (f1Count == f2Count) {\n if (fileHelper.isCompressed(f1)) {\n return -1;\n }\n if (fileHelper.isCompressed(f2)) {\n return 1;\n }\n }\n return 0;\n }\n });\n }\n }", "public static lbmonitor_binding[] get(nitro_service service, String monitorname[]) throws Exception{\n\t\tif (monitorname !=null && monitorname.length>0) {\n\t\t\tlbmonitor_binding response[] = new lbmonitor_binding[monitorname.length];\n\t\t\tlbmonitor_binding obj[] = new lbmonitor_binding[monitorname.length];\n\t\t\tfor (int i=0;i<monitorname.length;i++) {\n\t\t\t\tobj[i] = new lbmonitor_binding();\n\t\t\t\tobj[i].set_monitorname(monitorname[i]);\n\t\t\t\tresponse[i] = (lbmonitor_binding) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "private Duration getDuration(String value)\n {\n Duration result = null;\n\n if (value != null && value.length() != 0)\n {\n double seconds = getLong(value);\n double hours = seconds / (60 * 60);\n double days = hours / 8;\n\n if (days < 1)\n {\n result = Duration.getInstance(hours, TimeUnit.HOURS);\n }\n else\n {\n double durationDays = hours / 8;\n result = Duration.getInstance(durationDays, TimeUnit.DAYS);\n }\n }\n\n return (result);\n }", "public static void main(String[] args) throws Exception {\n Logger logger = Logger.getLogger(\"MASReader.main\");\n\n Properties beastConfigProperties = new Properties();\n String beastConfigPropertiesFile = null;\n if (args.length > 0) {\n beastConfigPropertiesFile = args[0];\n beastConfigProperties.load(new FileInputStream(\n beastConfigPropertiesFile));\n logger.info(\"Properties file selected -> \"\n + beastConfigPropertiesFile);\n } else {\n logger.severe(\"No properties file found. Set the path of properties file as argument.\");\n throw new BeastException(\n \"No properties file found. Set the path of properties file as argument.\");\n }\n String loggerConfigPropertiesFile;\n if (args.length > 1) {\n Properties loggerConfigProperties = new Properties();\n loggerConfigPropertiesFile = args[1];\n try {\n FileInputStream loggerConfigFile = new FileInputStream(\n loggerConfigPropertiesFile);\n loggerConfigProperties.load(loggerConfigFile);\n LogManager.getLogManager().readConfiguration(loggerConfigFile);\n logger.info(\"Logging properties configured successfully. Logger config file: \"\n + loggerConfigPropertiesFile);\n } catch (IOException ex) {\n logger.warning(\"WARNING: Could not open configuration file\");\n logger.warning(\"WARNING: Logging not configured (console output only)\");\n }\n } else {\n loggerConfigPropertiesFile = null;\n }\n\n MASReader.generateJavaFiles(\n beastConfigProperties.getProperty(\"requirementsFolder\"), \"\\\"\"\n + beastConfigProperties.getProperty(\"MASPlatform\")\n + \"\\\"\",\n beastConfigProperties.getProperty(\"srcTestRootFolder\"),\n beastConfigProperties.getProperty(\"storiesPackage\"),\n beastConfigProperties.getProperty(\"caseManagerPackage\"),\n loggerConfigPropertiesFile,\n beastConfigProperties.getProperty(\"specificationPhase\"));\n\n }", "public static Map<String, String> mapStringToMap(String map) {\r\n String[] m = map.split(\"[,;]\");\r\n Map<String, String> res = new HashMap<String, String>();\r\n for (String str : m) {\r\n int index = str.lastIndexOf('=');\r\n String key = str.substring(0, index);\r\n String val = str.substring(index + 1);\r\n res.put(key.trim(), val.trim());\r\n }\r\n return res;\r\n }", "public AT_Row setPaddingLeftChar(Character paddingLeftChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingLeftChar(paddingLeftChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "protected static Map<String, List<Statement>> addStatementToGroups(Statement statement, Map<String, List<Statement>> claims) {\n\t\tMap<String, List<Statement>> newGroups = new HashMap<>(claims);\n\t\tString pid = statement.getMainSnak().getPropertyId().getId();\n\t\tif(newGroups.containsKey(pid)) {\n\t\t\tList<Statement> newGroup = new ArrayList<>(newGroups.get(pid).size());\n\t\t\tboolean statementReplaced = false;\n\t\t\tfor(Statement existingStatement : newGroups.get(pid)) {\n\t\t\t\tif(existingStatement.getStatementId().equals(statement.getStatementId()) &&\n\t\t\t\t\t\t!existingStatement.getStatementId().isEmpty()) {\n\t\t\t\t\tstatementReplaced = true;\n\t\t\t\t\tnewGroup.add(statement);\n\t\t\t\t} else {\n\t\t\t\t\tnewGroup.add(existingStatement);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!statementReplaced) {\n\t\t\t\tnewGroup.add(statement);\n\t\t\t}\n\t\t\tnewGroups.put(pid, newGroup);\n\t\t} else {\n\t\t\tnewGroups.put(pid, Collections.singletonList(statement));\n\t\t}\n\t\treturn newGroups;\n\t}", "private void readProjectProperties(Project ganttProject)\n {\n ProjectProperties mpxjProperties = m_projectFile.getProjectProperties();\n mpxjProperties.setName(ganttProject.getName());\n mpxjProperties.setCompany(ganttProject.getCompany());\n mpxjProperties.setDefaultDurationUnits(TimeUnit.DAYS);\n\n String locale = ganttProject.getLocale();\n if (locale == null)\n {\n locale = \"en_US\";\n }\n m_localeDateFormat = DateFormat.getDateInstance(DateFormat.SHORT, new Locale(locale));\n }" ]
Saves changes in properties file. It reads the property file into memory, modifies it and saves it back to the file. @throws IOException
[ "public synchronized void persistProperties() throws IOException {\n beginPersistence();\n\n // Read the properties file into memory\n // Shouldn't be so bad - it's a small file\n List<String> content = readFile(propertiesFile);\n\n BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(propertiesFile), StandardCharsets.UTF_8));\n\n try {\n for (String line : content) {\n String trimmed = line.trim();\n if (trimmed.length() == 0) {\n bw.newLine();\n } else {\n Matcher matcher = PROPERTY_PATTERN.matcher(trimmed);\n if (matcher.matches()) {\n final String key = cleanKey(matcher.group(1));\n if (toSave.containsKey(key) || toSave.containsKey(key + DISABLE_SUFFIX_KEY)) {\n writeProperty(bw, key, matcher.group(2));\n toSave.remove(key);\n toSave.remove(key + DISABLE_SUFFIX_KEY);\n } else if (trimmed.startsWith(COMMENT_PREFIX)) {\n // disabled user\n write(bw, line, true);\n }\n } else {\n write(bw, line, true);\n }\n }\n }\n\n endPersistence(bw);\n } finally {\n safeClose(bw);\n }\n }" ]
[ "public static base_response add(nitro_service client, dnsaaaarec resource) throws Exception {\n\t\tdnsaaaarec addresource = new dnsaaaarec();\n\t\taddresource.hostname = resource.hostname;\n\t\taddresource.ipv6address = resource.ipv6address;\n\t\taddresource.ttl = resource.ttl;\n\t\treturn addresource.add_resource(client);\n\t}", "public static final String printWorkGroup(WorkGroup value)\n {\n return (Integer.toString(value == null ? WorkGroup.DEFAULT.getValue() : value.getValue()));\n }", "public RandomVariableInterface[] getBasisFunctions(double exerciseDate, LIBORModelMonteCarloSimulationInterface model) throws CalculationException {\n\n\t\tArrayList<RandomVariableInterface> basisFunctions = new ArrayList<RandomVariableInterface>();\n\n\t\tRandomVariableInterface basisFunction;\n\n\t\t// Constant\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tbasisFunctions.add(basisFunction);\n\n\t\t// LIBORs\n\t\tint liborPeriodIndex, liborPeriodIndexEnd;\n\t\tRandomVariableInterface rate;\n\n\t\t// 1 Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = liborPeriodIndex+1;\n\t\tdouble periodLength1 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\tbasisFunction = basisFunction.discount(rate, periodLength1);\n\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\tbasisFunction = basisFunction.discount(rate, periodLength1);\n\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t// n/2 Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = (liborPeriodIndex + model.getNumberOfLibors())/2;\n\n\t\tdouble periodLength2 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\tif(periodLength2 != periodLength1) {\n\t\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\t\t}\n\n\n\t\t// n Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = model.getNumberOfLibors();\n\t\tdouble periodLength3 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\tif(periodLength3 != periodLength1 && periodLength3 != periodLength2) {\n\t\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength3);\n\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength3);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\t\t}\n\n\t\treturn basisFunctions.toArray(new RandomVariableInterface[0]);\n\t}", "@NotNull\n private String getFQName(@NotNull final String localName, Object... params) {\n final StringBuilder builder = new StringBuilder();\n builder.append(storeName);\n builder.append('.');\n builder.append(localName);\n for (final Object param : params) {\n builder.append('#');\n builder.append(param);\n }\n //noinspection ConstantConditions\n return StringInterner.intern(builder.toString());\n }", "public static Span exact(CharSequence row) {\n Objects.requireNonNull(row);\n return exact(Bytes.of(row));\n }", "public String get(final long index) {\n return doWithJedis(new JedisCallable<String>() {\n @Override\n public String call(Jedis jedis) {\n return jedis.lindex(getKey(), index);\n }\n });\n }", "private void processCalendarDays(ProjectCalendar calendar, Record root)\n {\n // Retrieve working hours ...\n Record daysOfWeek = root.getChild(\"DaysOfWeek\");\n if (daysOfWeek != null)\n {\n for (Record dayRecord : daysOfWeek.getChildren())\n {\n processCalendarHours(calendar, dayRecord);\n }\n }\n }", "private boolean isRedeployAfterRemoval(ModelNode operation) {\n return operation.hasDefined(DEPLOYMENT_OVERLAY_LINK_REMOVAL) &&\n operation.get(DEPLOYMENT_OVERLAY_LINK_REMOVAL).asBoolean();\n }", "public static Color cueColor(CueList.Entry entry) {\n if (entry.hotCueNumber > 0) {\n return Color.GREEN;\n }\n if (entry.isLoop) {\n return Color.ORANGE;\n }\n return Color.RED;\n }" ]
Assign arguments to the statement. @return The statement passed in or null if it had to be closed on error.
[ "private CompiledStatement assignStatementArguments(CompiledStatement stmt) throws SQLException {\n\t\tboolean ok = false;\n\t\ttry {\n\t\t\tif (limit != null) {\n\t\t\t\t// we use this if SQL statement LIMITs are not supported by this database type\n\t\t\t\tstmt.setMaxRows(limit.intValue());\n\t\t\t}\n\t\t\t// set any arguments if we are logging our object\n\t\t\tObject[] argValues = null;\n\t\t\tif (logger.isLevelEnabled(Level.TRACE) && argHolders.length > 0) {\n\t\t\t\targValues = new Object[argHolders.length];\n\t\t\t}\n\t\t\tfor (int i = 0; i < argHolders.length; i++) {\n\t\t\t\tObject argValue = argHolders[i].getSqlArgValue();\n\t\t\t\tFieldType fieldType = argFieldTypes[i];\n\t\t\t\tSqlType sqlType;\n\t\t\t\tif (fieldType == null) {\n\t\t\t\t\tsqlType = argHolders[i].getSqlType();\n\t\t\t\t} else {\n\t\t\t\t\tsqlType = fieldType.getSqlType();\n\t\t\t\t}\n\t\t\t\tstmt.setObject(i, argValue, sqlType);\n\t\t\t\tif (argValues != null) {\n\t\t\t\t\targValues[i] = argValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlogger.debug(\"prepared statement '{}' with {} args\", statement, argHolders.length);\n\t\t\tif (argValues != null) {\n\t\t\t\t// need to do the (Object) cast to force args to be a single object\n\t\t\t\tlogger.trace(\"prepared statement arguments: {}\", (Object) argValues);\n\t\t\t}\n\t\t\tok = true;\n\t\t\treturn stmt;\n\t\t} finally {\n\t\t\tif (!ok) {\n\t\t\t\tIOUtils.closeThrowSqlException(stmt, \"statement\");\n\t\t\t}\n\t\t}\n\t}" ]
[ "public ItemRequest<Task> addSubtask(String task) {\n \n String path = String.format(\"/tasks/%s/subtasks\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "public List<TimephasedCost> getTimephasedCost()\n {\n if (m_timephasedCost == null)\n {\n Resource r = getResource();\n ResourceType type = r != null ? r.getType() : ResourceType.WORK;\n\n //for Work and Material resources, we will calculate in the normal way\n if (type != ResourceType.COST)\n {\n if (m_timephasedWork != null && m_timephasedWork.hasData())\n {\n if (hasMultipleCostRates())\n {\n m_timephasedCost = getTimephasedCostMultipleRates(getTimephasedWork(), getTimephasedOvertimeWork());\n }\n else\n {\n m_timephasedCost = getTimephasedCostSingleRate(getTimephasedWork(), getTimephasedOvertimeWork());\n }\n }\n }\n else\n {\n m_timephasedCost = getTimephasedCostFixedAmount();\n }\n\n }\n return m_timephasedCost;\n }", "public List<Dependency> getModuleDependencies(final String moduleName, final String moduleVersion, final Boolean fullRecursive, final Boolean corporate, final Boolean thirdParty) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactDependencies(moduleName, moduleVersion));\n final ClientResponse response = resource.queryParam(ServerAPI.SCOPE_COMPILE_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_PROVIDED_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_RUNTIME_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_TEST_PARAM, \"true\")\n .queryParam(ServerAPI.RECURSIVE_PARAM, fullRecursive.toString())\n .queryParam(ServerAPI.SHOW_CORPORATE_PARAM, corporate.toString())\n .queryParam(ServerAPI.SHOW_THIRPARTY_PARAM, thirdParty.toString())\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"get module ancestors \", moduleName, moduleVersion);\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<Dependency>>(){});\n }", "private static List<String> parseAndCompare(List<String> fileNames, int masterPartitionId) {\n List<String> sourceFileNames = new ArrayList<String>();\n for(String fileName: fileNames) {\n String[] partitionIdReplicaChunk = fileName.split(SPLIT_LITERAL);\n if(Integer.parseInt(partitionIdReplicaChunk[0]) == masterPartitionId) {\n sourceFileNames.add(fileName);\n }\n }\n return sourceFileNames;\n }", "private AssignmentField selectField(AssignmentField[] fields, int index)\n {\n if (index < 1 || index > fields.length)\n {\n throw new IllegalArgumentException(index + \" is not a valid field index\");\n }\n return (fields[index - 1]);\n }", "private ProjectFile handleDirectory(File directory) throws Exception\n {\n ProjectFile result = handleDatabaseInDirectory(directory);\n if (result == null)\n {\n result = handleFileInDirectory(directory);\n }\n return result;\n }", "public void contextInitialized(ServletContextEvent event) {\n this.context = event.getServletContext();\n\n // Output a simple message to the server's console\n System.out.println(\"The Simple Web App. Is Ready\");\n\n ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(\n \"/client.xml\");\n LocatorService client = (LocatorService) context\n .getBean(\"locatorService\");\n\n String serviceHost = this.context.getInitParameter(\"serviceHost\");\n\n try {\n client.registerEndpoint(new QName(\n \"http://talend.org/esb/examples/\", \"GreeterService\"),\n serviceHost, BindingType.SOAP_11, TransportType.HTTP, null);\n } catch (InterruptedExceptionFault e) {\n e.printStackTrace();\n } catch (ServiceLocatorFault e) {\n e.printStackTrace();\n }\n }", "public static double getRobustTreeEditDistance(String dom1, String dom2) {\n\n\t\tLblTree domTree1 = null, domTree2 = null;\n\t\ttry {\n\t\t\tdomTree1 = getDomTree(dom1);\n\t\t\tdomTree2 = getDomTree(dom2);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\tdouble DD = 0.0;\n\t\tRTED_InfoTree_Opt rted;\n\t\tdouble ted;\n\n\t\trted = new RTED_InfoTree_Opt(1, 1, 1);\n\n\t\t// compute tree edit distance\n\t\trted.init(domTree1, domTree2);\n\n\t\tint maxSize = Math.max(domTree1.getNodeCount(), domTree2.getNodeCount());\n\n\t\trted.computeOptimalStrategy();\n\t\tted = rted.nonNormalizedTreeDist();\n\t\tted /= (double) maxSize;\n\n\t\tDD = ted;\n\t\treturn DD;\n\t}", "String urlDecode(String name, String encoding) throws UnsupportedEncodingException {\n return URLDecoder.decode(name, encoding);\n }" ]
Add a module. @param moduleName the module name @param slot the module slot @param newHash the new hash of the added content @return the builder
[ "public T addModule(final String moduleName, final String slot, final byte[] newHash) {\n final ContentItem item = createModuleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.ADD, NO_CONTENT));\n return returnThis();\n }" ]
[ "public static String getTabularData(String[] labels, String[][] data, int padding) {\n int[] size = new int[labels.length];\n \n for (int i = 0; i < labels.length; i++) {\n size[i] = labels[i].length() + padding;\n }\n \n for (String[] row : data) {\n for (int i = 0; i < labels.length; i++) {\n if (row[i].length() >= size[i]) {\n size[i] = row[i].length() + padding;\n }\n }\n }\n \n StringBuffer tabularData = new StringBuffer();\n \n for (int i = 0; i < labels.length; i++) {\n tabularData.append(labels[i]);\n tabularData.append(fill(' ', size[i] - labels[i].length()));\n }\n \n tabularData.append(\"\\n\");\n \n for (int i = 0; i < labels.length; i++) {\n tabularData.append(fill('=', size[i] - 1)).append(\" \");\n }\n \n tabularData.append(\"\\n\");\n \n \n for (String[] row : data) {\n for (int i = 0; i < labels.length; i++) {\n tabularData.append(row[i]);\n tabularData.append(fill(' ', size[i] - row[i].length()));\n }\n \n tabularData.append(\"\\n\");\n }\n \n return tabularData.toString();\n }", "private Object getConstantValue(FieldType type, byte[] block)\n {\n Object value;\n DataType dataType = type.getDataType();\n\n if (dataType == null)\n {\n value = null;\n }\n else\n {\n switch (dataType)\n {\n case DURATION:\n {\n value = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(block, getValueOffset()), MPPUtility.getDurationTimeUnits(MPPUtility.getShort(block, getTimeUnitsOffset())));\n break;\n }\n\n case NUMERIC:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()));\n break;\n }\n\n case PERCENTAGE:\n {\n value = Double.valueOf(MPPUtility.getShort(block, getValueOffset()));\n break;\n }\n\n case CURRENCY:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()) / 100);\n break;\n }\n\n case STRING:\n {\n int textOffset = getTextOffset(block);\n value = MPPUtility.getUnicodeString(m_criteriaData, m_dataOffset + m_criteriaTextStart + textOffset);\n break;\n }\n\n case BOOLEAN:\n {\n int intValue = MPPUtility.getShort(block, getValueOffset());\n value = (intValue == 1 ? Boolean.TRUE : Boolean.FALSE);\n break;\n }\n\n case DATE:\n {\n value = MPPUtility.getTimestamp(block, getValueOffset());\n break;\n }\n\n default:\n {\n value = null;\n break;\n }\n }\n }\n\n return value;\n }", "static void showWarning(final String caption, final String description) {\n\n Notification warning = new Notification(caption, description, Type.WARNING_MESSAGE, true);\n warning.setDelayMsec(-1);\n warning.show(UI.getCurrent().getPage());\n\n }", "protected boolean isFiltered(AbstractElement canddiate, Param param) {\n\t\tif (canddiate instanceof Group) {\n\t\t\tGroup group = (Group) canddiate;\n\t\t\tif (group.getGuardCondition() != null) {\n\t\t\t\tSet<Parameter> context = param.getAssignedParametes();\n\t\t\t\tConditionEvaluator evaluator = new ConditionEvaluator(context);\n\t\t\t\tif (!evaluator.evaluate(group.getGuardCondition())) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "protected void appendList(StringBuilder sql, List<?> list, String init, String sep) {\n\n boolean first = true;\n\n for (Object s : list) {\n if (first) {\n sql.append(init);\n } else {\n sql.append(sep);\n }\n sql.append(s);\n first = false;\n }\n }", "private byte[] getBytes(String value, boolean unicode)\n {\n byte[] result;\n if (unicode)\n {\n int start = 0;\n // Get the bytes in UTF-16\n byte[] bytes;\n\n try\n {\n bytes = value.getBytes(\"UTF-16\");\n }\n catch (UnsupportedEncodingException e)\n {\n bytes = value.getBytes();\n }\n\n if (bytes.length > 2 && bytes[0] == -2 && bytes[1] == -1)\n {\n // Skip the unicode identifier\n start = 2;\n }\n result = new byte[bytes.length - start];\n for (int loop = start; loop < bytes.length - 1; loop += 2)\n {\n // Swap the order here\n result[loop - start] = bytes[loop + 1];\n result[loop + 1 - start] = bytes[loop];\n }\n }\n else\n {\n result = new byte[value.length() + 1];\n System.arraycopy(value.getBytes(), 0, result, 0, value.length());\n }\n return (result);\n }", "public static Node addPartitionsToNode(final Node node, final Set<Integer> donatedPartitions) {\n List<Integer> deepCopy = new ArrayList<Integer>(node.getPartitionIds());\n deepCopy.addAll(donatedPartitions);\n Collections.sort(deepCopy);\n return updateNode(node, deepCopy);\n }", "public String generateInitScript(EnvVars env) throws IOException, InterruptedException {\n StringBuilder initScript = new StringBuilder();\n InputStream templateStream = getClass().getResourceAsStream(\"/initscripttemplate.gradle\");\n String templateAsString = IOUtils.toString(templateStream, Charsets.UTF_8.name());\n File extractorJar = PluginDependencyHelper.getExtractorJar(env);\n FilePath dependencyDir = PluginDependencyHelper.getActualDependencyDirectory(extractorJar, rootPath);\n String absoluteDependencyDirPath = dependencyDir.getRemote();\n absoluteDependencyDirPath = absoluteDependencyDirPath.replace(\"\\\\\", \"/\");\n String str = templateAsString.replace(\"${pluginLibDir}\", absoluteDependencyDirPath);\n initScript.append(str);\n return initScript.toString();\n }", "protected String getUserDefinedFieldName(String field) {\n int index = field.indexOf('-');\n char letter = getUserDefinedFieldLetter();\n\n for (int i = 0; i < index; ++i) {\n if (field.charAt(i) == letter) {\n return field.substring(index + 1);\n }\n }\n\n return null;\n }" ]
Read the table headers. This allows us to break the file into chunks representing the individual tables. @param is input stream @return list of tables in the file
[ "private List<SynchroTable> readTableHeaders(InputStream is) throws IOException\n {\n // Read the headers\n List<SynchroTable> tables = new ArrayList<SynchroTable>();\n byte[] header = new byte[48];\n while (true)\n {\n is.read(header);\n m_offset += 48;\n SynchroTable table = readTableHeader(header);\n if (table == null)\n {\n break;\n }\n tables.add(table);\n }\n\n // Ensure sorted by offset\n Collections.sort(tables, new Comparator<SynchroTable>()\n {\n @Override public int compare(SynchroTable o1, SynchroTable o2)\n {\n return o1.getOffset() - o2.getOffset();\n }\n });\n\n // Calculate lengths\n SynchroTable previousTable = null;\n for (SynchroTable table : tables)\n {\n if (previousTable != null)\n {\n previousTable.setLength(table.getOffset() - previousTable.getOffset());\n }\n\n previousTable = table;\n }\n\n for (SynchroTable table : tables)\n {\n SynchroLogger.log(\"TABLE\", table);\n }\n\n return tables;\n }" ]
[ "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 }", "public static base_response add(nitro_service client, dnsaaaarec resource) throws Exception {\n\t\tdnsaaaarec addresource = new dnsaaaarec();\n\t\taddresource.hostname = resource.hostname;\n\t\taddresource.ipv6address = resource.ipv6address;\n\t\taddresource.ttl = resource.ttl;\n\t\treturn addresource.add_resource(client);\n\t}", "protected void checkProxyPrefetchingLimit(DefBase def, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n if (def.hasProperty(PropertyHelper.OJB_PROPERTY_PROXY_PREFETCHING_LIMIT))\r\n {\r\n if (!def.hasProperty(PropertyHelper.OJB_PROPERTY_PROXY))\r\n {\r\n if (def instanceof ClassDescriptorDef)\r\n {\r\n LogHelper.warn(true,\r\n ConstraintsBase.class,\r\n \"checkProxyPrefetchingLimit\",\r\n \"The class \"+def.getName()+\" has a proxy-prefetching-limit property but no proxy property\");\r\n }\r\n else\r\n { \r\n LogHelper.warn(true,\r\n ConstraintsBase.class,\r\n \"checkProxyPrefetchingLimit\",\r\n \"The feature \"+def.getName()+\" in class \"+def.getOwner().getName()+\" has a proxy-prefetching-limit property but no proxy property\");\r\n }\r\n }\r\n \r\n String propValue = def.getProperty(PropertyHelper.OJB_PROPERTY_PROXY_PREFETCHING_LIMIT);\r\n \r\n try\r\n {\r\n int value = Integer.parseInt(propValue);\r\n \r\n if (value < 0)\r\n {\r\n if (def instanceof ClassDescriptorDef)\r\n {\r\n throw new ConstraintException(\"The proxy-prefetching-limit value of class \"+def.getName()+\" must be a non-negative number\");\r\n }\r\n else\r\n { \r\n throw new ConstraintException(\"The proxy-prefetching-limit value of the feature \"+def.getName()+\" in class \"+def.getOwner().getName()+\" must be a non-negative number\");\r\n }\r\n }\r\n }\r\n catch (NumberFormatException ex)\r\n {\r\n if (def instanceof ClassDescriptorDef)\r\n {\r\n throw new ConstraintException(\"The proxy-prefetching-limit value of the class \"+def.getName()+\" is not a number\");\r\n }\r\n else\r\n { \r\n throw new ConstraintException(\"The proxy-prefetching-limit value of the feature \"+def.getName()+\" in class \"+def.getOwner().getName()+\" is not a number\");\r\n }\r\n }\r\n }\r\n }", "public <T extends Widget & Checkable> List<Integer> getCheckedWidgetIndexes() {\n List<Integer> checked = new ArrayList<>();\n List<Widget> children = getChildren();\n\n final int size = children.size();\n for (int i = 0, j = -1; i < size; ++i) {\n Widget c = children.get(i);\n if (c instanceof Checkable) {\n ++j;\n if (((Checkable) c).isChecked()) {\n checked.add(j);\n }\n }\n }\n\n return checked;\n }", "public static void dumpClusters(Cluster currentCluster,\n Cluster finalCluster,\n String outputDirName) {\n dumpClusters(currentCluster, finalCluster, outputDirName, \"\");\n }", "private void adjustVisibleColumns() {\n\n if (m_table.isColumnCollapsingAllowed()) {\n if ((m_model.hasDefaultValues()) || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {\n m_table.setColumnCollapsed(TableProperty.DEFAULT, false);\n } else {\n m_table.setColumnCollapsed(TableProperty.DEFAULT, true);\n }\n\n if (((m_model.getEditMode().equals(EditMode.MASTER) || m_model.hasDescriptionValues()))\n || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {\n m_table.setColumnCollapsed(TableProperty.DESCRIPTION, false);\n } else {\n m_table.setColumnCollapsed(TableProperty.DESCRIPTION, true);\n }\n }\n }", "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 }", "@SuppressWarnings(\"resource\")\n public static FileChannel openChannel(File file, boolean mutable) throws IOException {\n if (mutable) {\n return new RandomAccessFile(file, \"rw\").getChannel();\n }\n return new FileInputStream(file).getChannel();\n }", "public Map<Integer, String> getSignatures() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<Integer, String>(signatures));\n }" ]
Retrieves a list of Terms of Service that belong to your Enterprise as an Iterable. @param api api the API connection to be used by the resource. @param termsOfServiceType the type of terms of service to be retrieved. Can be set to "managed" or "external" @return the Iterable of Terms of Service in an Enterprise that match the filter parameters.
[ "public static List<BoxTermsOfService.Info> getAllTermsOfServices(final BoxAPIConnection api,\n BoxTermsOfService.TermsOfServiceType\n termsOfServiceType) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (termsOfServiceType != null) {\n builder.appendParam(\"tos_type\", termsOfServiceType.toString());\n }\n\n URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n List<BoxTermsOfService.Info> termsOfServices = new ArrayList<BoxTermsOfService.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject termsOfServiceJSON = value.asObject();\n BoxTermsOfService termsOfService = new BoxTermsOfService(api, termsOfServiceJSON.get(\"id\").asString());\n BoxTermsOfService.Info info = termsOfService.new Info(termsOfServiceJSON);\n termsOfServices.add(info);\n }\n\n return termsOfServices;\n }" ]
[ "@Override\n public void onLoadFinished(final Loader<SortedList<T>> loader,\n final SortedList<T> data) {\n isLoading = false;\n mCheckedItems.clear();\n mCheckedVisibleViewHolders.clear();\n mFiles = data;\n mAdapter.setList(data);\n if (mCurrentDirView != null) {\n mCurrentDirView.setText(getFullPath(mCurrentPath));\n }\n // Stop loading now to avoid a refresh clearing the user's selections\n getLoaderManager().destroyLoader( 0 );\n }", "public Collection<Locale> getCountries() {\n Collection<Locale> result = get(KEY_QUERY_COUNTRIES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "protected static FileWriter createFileWriter(String scenarioName,\n String aux_package_path, String dest_dir) throws BeastException {\n try {\n return new FileWriter(new File(createFolder(aux_package_path,\n dest_dir), scenarioName + \".story\"));\n } catch (IOException e) {\n String message = \"ERROR writing the \" + scenarioName\n + \".story file: \" + e.toString();\n logger.severe(message);\n throw new BeastException(message, e);\n }\n }", "@SuppressWarnings(\"unchecked\")\n protected String addPostRunDependent(Appliable<? extends Indexable> appliable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) appliable;\n return this.addPostRunDependent(dependency);\n }", "public void createAgent(String agent_name, String path) {\n IComponentIdentifier agent = cmsService.createComponent(agent_name,\n path, null, null).get(new ThreadSuspendable());\n createdAgents.put(agent_name, agent);\n }", "public static Map<String, Object> introspect(Object obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {\n\t\tMap<String, Object> result = new HashMap<>();\n\t\tBeanInfo info = Introspector.getBeanInfo( obj.getClass() );\n\t\tfor ( PropertyDescriptor pd : info.getPropertyDescriptors() ) {\n\t\t\tMethod reader = pd.getReadMethod();\n\t\t\tString name = pd.getName();\n\t\t\tif ( reader != null && !\"class\".equals( name ) ) {\n\t\t\t\tresult.put( name, reader.invoke( obj ) );\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}", "public static double JensenShannonDivergence(double[] p, double[] q) {\n double[] m = new double[p.length];\n for (int i = 0; i < m.length; i++) {\n m[i] = (p[i] + q[i]) / 2;\n }\n\n return (KullbackLeiblerDivergence(p, m) + KullbackLeiblerDivergence(q, m)) / 2;\n }", "private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList) {\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 generateParentWrapper(flatItemList, parent, parent.isInitiallyExpanded());\n }\n\n return flatItemList;\n }", "public static Span prefix(CharSequence rowPrefix) {\n Objects.requireNonNull(rowPrefix);\n return prefix(Bytes.of(rowPrefix));\n }" ]
Configure file logging and stop console logging. @param filename Log to this file.
[ "@SuppressWarnings(\"unchecked\")\n\tstatic void logToFile(String filename) {\n\t\tLogger rootLogger = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);\n\n\t\tFileAppender<ILoggingEvent> fileappender = new FileAppender<>();\n\t\tfileappender.setContext(rootLogger.getLoggerContext());\n\t\tfileappender.setFile(filename);\n\t\tfileappender.setName(\"FILE\");\n\n\t\tConsoleAppender<?> console = (ConsoleAppender<?>) rootLogger.getAppender(\"STDOUT\");\n\t\tfileappender.setEncoder((Encoder<ILoggingEvent>) console.getEncoder());\n\n\t\tfileappender.start();\n\n\t\trootLogger.addAppender(fileappender);\n\n\t\tconsole.stop();\n\t}" ]
[ "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 }", "public int executeUpdateSQL(\r\n String sqlStatement,\r\n ClassDescriptor cld,\r\n ValueContainer[] values1,\r\n ValueContainer[] values2)\r\n throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeUpdateSQL: \" + sqlStatement);\r\n\r\n int result;\r\n int index;\r\n PreparedStatement stmt = null;\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n try\r\n {\r\n stmt = sm.getPreparedStatement(cld, sqlStatement,\r\n Query.NOT_SCROLLABLE, StatementManagerIF.FETCH_SIZE_NOT_APPLICABLE, isStoredProcedure(sqlStatement));\r\n index = sm.bindValues(stmt, values1, 1);\r\n sm.bindValues(stmt, values2, index);\r\n result = stmt.executeUpdate();\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n logger.error(\"PersistenceBrokerException during the execution of the Update SQL query: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n ValueContainer[] tmp = addValues(values1, values2);\r\n throw ExceptionHelper.generateException(e, sqlStatement, cld, tmp, logger, null);\r\n }\r\n finally\r\n {\r\n sm.closeResources(stmt, null);\r\n }\r\n return result;\r\n }", "public static Chart getMSDLineWithActiveTransportModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double diffusionCoefficient, double velocity) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tdouble[] modelData = new double[lagMax - lagMin + 1];\n\t\tMeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(\n\t\t\t\tt, lagMin);\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t\tmodelData[i - lagMin] = Math.pow(velocity*(i*timelag), 2) + 4*diffusionCoefficient*(i*timelag);//4 * D * Math.pow(i * timelag, a);\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\t\tchart.addSeries(\"y=4*D*t + (v*t)^2\", xData, modelData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}", "protected boolean closeAtomically() {\n if (isClosed.compareAndSet(false, true)) {\n Closeable.closeQuietly(networkStatsListener);\n return true;\n } else {\n //was already closed.\n return false;\n }\n }", "public 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 }", "public static base_response update(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey updateresource = new sslcertkey();\n\t\tupdateresource.certkey = resource.certkey;\n\t\tupdateresource.expirymonitor = resource.expirymonitor;\n\t\tupdateresource.notificationperiod = resource.notificationperiod;\n\t\treturn updateresource.update_resource(client);\n\t}", "private void deliverTempoChangedAnnouncement(final double tempo) {\n for (final MasterListener listener : getMasterListeners()) {\n try {\n listener.tempoChanged(tempo);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering tempo changed announcement to listener\", t);\n }\n }\n }", "public void setCycleInterval(float newCycleInterval) {\n if ( (this.cycleInterval != newCycleInterval) && (newCycleInterval > 0) ) {\n for (GVRNodeAnimation gvrKeyFrameAnimation : gvrKeyFrameAnimations) {\n //TODO Cannot easily change the GVRAnimation's GVRChannel once set.\n }\n this.cycleInterval = newCycleInterval;\n }\n }", "public void addFile(File file) {\n String name = \"file\";\n files.put(normalizeDuplicateName(name), file);\n }" ]
parse the outgoings form an json object and add all shape references to the current shapes, add new shapes to the shape array @param shapes @param modelJSON @param current @throws org.json.JSONException
[ "private static void parseOutgoings(ArrayList<Shape> shapes,\n JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"outgoing\")) {\n ArrayList<Shape> outgoings = new ArrayList<Shape>();\n JSONArray outgoingObject = modelJSON.getJSONArray(\"outgoing\");\n for (int i = 0; i < outgoingObject.length(); i++) {\n Shape out = getShapeWithId(outgoingObject.getJSONObject(i).getString(\"resourceId\"),\n shapes);\n outgoings.add(out);\n out.addIncoming(current);\n }\n if (outgoings.size() > 0) {\n current.setOutgoings(outgoings);\n }\n }\n }" ]
[ "public CollectionRequest<Section> findByProject(String project) {\n \n String path = String.format(\"/projects/%s/sections\", project);\n return new CollectionRequest<Section>(this, Section.class, path, \"GET\");\n }", "protected void initValid(EnhancedAnnotation<T> annotatedAnnotation) {\n this.valid = false;\n for (Class<? extends Annotation> annotationType : getMetaAnnotationTypes()) {\n if (annotatedAnnotation.isAnnotationPresent(annotationType)) {\n this.valid = true;\n }\n }\n }", "public static <T> DatabaseTableConfig<T> fromReader(BufferedReader reader) throws SQLException {\n\t\tDatabaseTableConfig<T> config = new DatabaseTableConfig<T>();\n\t\tboolean anything = false;\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read DatabaseTableConfig from stream\", e);\n\t\t\t}\n\t\t\tif (line == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_END_MARKER)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_FIELDS_START)) {\n\t\t\t\treadFields(reader, config);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// skip empty lines or comments\n\t\t\tif (line.length() == 0 || line.startsWith(\"#\") || line.equals(CONFIG_FILE_START_MARKER)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString[] parts = line.split(\"=\", -2);\n\t\t\tif (parts.length != 2) {\n\t\t\t\tthrow new SQLException(\"DatabaseTableConfig reading from stream cannot parse line: \" + line);\n\t\t\t}\n\t\t\treadTableField(config, parts[0], parts[1]);\n\t\t\tanything = true;\n\t\t}\n\t\t// if we got any config lines then we return the config\n\t\tif (anything) {\n\t\t\treturn config;\n\t\t} else {\n\t\t\t// otherwise we return null for none\n\t\t\treturn null;\n\t\t}\n\t}", "public QueryBuilder<T, ID> selectColumns(String... columns) {\n\t\tfor (String column : columns) {\n\t\t\taddSelectColumnToList(column);\n\t\t}\n\t\treturn this;\n\t}", "public Script updateName(int id, String name) throws Exception {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SCRIPT +\n \" SET \" + Constants.SCRIPT_NAME + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, name);\n statement.setInt(2, id);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return this.getScript(id);\n }", "public static TagModel getSingleParent(TagModel tag)\n {\n final Iterator<TagModel> parents = tag.getDesignatedByTags().iterator();\n if (!parents.hasNext())\n throw new WindupException(\"Tag is not designated by any tags: \" + tag);\n\n final TagModel maybeOnlyParent = parents.next();\n\n if (parents.hasNext()) {\n StringBuilder sb = new StringBuilder();\n tag.getDesignatedByTags().iterator().forEachRemaining(x -> sb.append(x).append(\", \"));\n throw new WindupException(String.format(\"Tag %s is designated by multiple tags: %s\", tag, sb.toString()));\n }\n\n return maybeOnlyParent;\n }", "protected Date getPickerDate() {\n try {\n JsDate pickerDate = getPicker().get(\"select\").obj;\n return new Date((long) pickerDate.getTime());\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }", "private static void setDpiValue(final Multimap<String, String> extraParams, final int dpi) {\n String searchKey = \"FORMAT_OPTIONS\";\n for (String key: extraParams.keys()) {\n if (key.equalsIgnoreCase(searchKey)) {\n Collection<String> values = extraParams.removeAll(key);\n List<String> newValues = new ArrayList<>();\n for (String value: values) {\n if (!StringUtils.isEmpty(value)) {\n value += \";dpi:\" + Integer.toString(dpi);\n newValues.add(value);\n }\n }\n extraParams.putAll(key, newValues);\n return;\n }\n }\n }", "public void addDateTimeHelper(int ds, Date date) throws SerializationException, InvalidDataSetException {\r\n\t\tif (date == null) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tDataSetInfo dsi = dsiFactory.create(ds);\r\n\r\n\t\tSimpleDateFormat df = new SimpleDateFormat(dsi.getSerializer().toString());\r\n\t\tString value = df.format(date);\r\n\t\tbyte[] data = dsi.getSerializer().serialize(value, activeSerializationContext);\r\n\t\tDataSet dataSet = new DefaultDataSet(dsi, data);\r\n\t\tadd(dataSet);\r\n\t}" ]
Set the scrollbar used for vertical scrolling. @param scrollbar the scrollbar, or null to clear it @param width the width of the scrollbar in pixels
[ "private void setVerticalScrollbar(final CmsScrollBar scrollbar, int width) {\r\n\r\n // Validate.\r\n if ((scrollbar == m_scrollbar) || (scrollbar == null)) {\r\n return;\r\n }\r\n // Detach new child.\r\n\r\n scrollbar.asWidget().removeFromParent();\r\n // Remove old child.\r\n if (m_scrollbar != null) {\r\n if (m_verticalScrollbarHandlerRegistration != null) {\r\n m_verticalScrollbarHandlerRegistration.removeHandler();\r\n m_verticalScrollbarHandlerRegistration = null;\r\n }\r\n remove(m_scrollbar);\r\n }\r\n m_scrollLayer.appendChild(scrollbar.asWidget().getElement());\r\n adopt(scrollbar.asWidget());\r\n\r\n // Logical attach.\r\n m_scrollbar = scrollbar;\r\n m_verticalScrollbarWidth = width;\r\n\r\n // Initialize the new scrollbar.\r\n m_verticalScrollbarHandlerRegistration = scrollbar.addValueChangeHandler(new ValueChangeHandler<Integer>() {\r\n\r\n public void onValueChange(ValueChangeEvent<Integer> event) {\r\n\r\n int vPos = scrollbar.getVerticalScrollPosition();\r\n int v = getVerticalScrollPosition();\r\n if (v != vPos) {\r\n setVerticalScrollPosition(vPos);\r\n }\r\n\r\n }\r\n });\r\n maybeUpdateScrollbars();\r\n }" ]
[ "public static PasswordSpec parse(String spec) {\n char[] ca = spec.toCharArray();\n int len = ca.length;\n illegalIf(0 == len, spec);\n Builder builder = new Builder();\n StringBuilder minBuf = new StringBuilder();\n StringBuilder maxBuf = new StringBuilder();\n boolean lenSpecStart = false;\n boolean minPart = false;\n for (int i = 0; i < len; ++i) {\n char c = ca[i];\n switch (c) {\n case SPEC_LOWERCASE:\n illegalIf(lenSpecStart, spec);\n builder.requireLowercase();\n break;\n case SPEC_UPPERCASE:\n illegalIf(lenSpecStart, spec);\n builder.requireUppercase();\n break;\n case SPEC_SPECIAL_CHAR:\n illegalIf(lenSpecStart, spec);\n builder.requireSpecialChar();\n break;\n case SPEC_LENSPEC_START:\n lenSpecStart = true;\n minPart = true;\n break;\n case SPEC_LENSPEC_CLOSE:\n illegalIf(minPart, spec);\n lenSpecStart = false;\n break;\n case SPEC_LENSPEC_SEP:\n minPart = false;\n break;\n case SPEC_DIGIT:\n if (!lenSpecStart) {\n builder.requireDigit();\n } else {\n if (minPart) {\n minBuf.append(c);\n } else {\n maxBuf.append(c);\n }\n }\n break;\n default:\n illegalIf(!lenSpecStart || !isDigit(c), spec);\n if (minPart) {\n minBuf.append(c);\n } else {\n maxBuf.append(c);\n }\n }\n }\n illegalIf(lenSpecStart, spec);\n if (minBuf.length() != 0) {\n builder.minLength(Integer.parseInt(minBuf.toString()));\n }\n if (maxBuf.length() != 0) {\n builder.maxLength(Integer.parseInt(maxBuf.toString()));\n }\n return builder;\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}", "private void addDependent(String pathName, String relativeTo) {\n if (relativeTo != null) {\n Set<String> dependents = dependenctRelativePaths.get(relativeTo);\n if (dependents == null) {\n dependents = new HashSet<String>();\n dependenctRelativePaths.put(relativeTo, dependents);\n }\n dependents.add(pathName);\n }\n }", "public static RebalanceTaskInfoMap encodeRebalanceTaskInfoMap(RebalanceTaskInfo stealInfo) {\n return RebalanceTaskInfoMap.newBuilder()\n .setStealerId(stealInfo.getStealerId())\n .setDonorId(stealInfo.getDonorId())\n .addAllPerStorePartitionIds(ProtoUtils.encodeStoreToPartitionsTuple(stealInfo.getStoreToPartitionIds()))\n .setInitialCluster(new ClusterMapper().writeCluster(stealInfo.getInitialCluster()))\n .build();\n }", "public UniqueEntityLoader buildLoader(\n\t\t\tOuterJoinLoadable persister,\n\t\t\tint batchSize,\n\t\t\tLockMode lockMode,\n\t\t\tSessionFactoryImplementor factory,\n\t\t\tLoadQueryInfluencers influencers,\n\t\t\tBatchableEntityLoaderBuilder innerEntityLoaderBuilder) {\n\t\tif ( batchSize <= 1 ) {\n\t\t\t// no batching\n\t\t\treturn buildNonBatchingLoader( persister, lockMode, factory, influencers, innerEntityLoaderBuilder );\n\t\t}\n\t\treturn buildBatchingLoader( persister, batchSize, lockMode, factory, influencers, innerEntityLoaderBuilder );\n\t}", "public String toUriString(final java.net.URI uri) {\n return this.toUriString(URI.createURI(uri.normalize().toString()));\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}", "public HostName toHostName() {\n\t\tHostName host = fromHost;\n\t\tif(host == null) {\n\t\t\tfromHost = host = toCanonicalHostName();\n\t\t}\n\t\treturn host;\n\t}", "@PrefMetadata(type = CmsHiddenBuiltinPreference.class)\n public String getExplorerFileEntryOptions() {\n\n if (m_settings.getExplorerFileEntryOptions() == null) {\n return \"\";\n } else {\n return \"\" + m_settings.getExplorerFileEntryOptions();\n }\n }" ]
Visits a parameter of this method. @param name parameter name or null if none is provided. @param access the parameter's access flags, only <tt>ACC_FINAL</tt>, <tt>ACC_SYNTHETIC</tt> or/and <tt>ACC_MANDATED</tt> are allowed (see {@link Opcodes}).
[ "public void visitParameter(String name, int access) {\n if (mv != null) {\n mv.visitParameter(name, access);\n }\n }" ]
[ "protected void threadWatch(final ConnectionHandle c) {\r\n\t\tthis.threadFinalizableRefs.put(c, new FinalizableWeakReference<Thread>(Thread.currentThread(), this.finalizableRefQueue) {\r\n\t\t\tpublic void finalizeReferent() {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tif (!CachedConnectionStrategy.this.pool.poolShuttingDown){\r\n\t\t\t\t\t\t\tlogger.debug(\"Monitored thread is dead, closing off allocated connection.\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tc.internalClose();\r\n\t\t\t\t\t} catch (SQLException e) {\r\n\t\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tCachedConnectionStrategy.this.threadFinalizableRefs.remove(c);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "public static void endRequest() {\n final List<RequestScopedItem> result = CACHE.get();\n if (result != null) {\n CACHE.remove();\n for (final RequestScopedItem item : result) {\n item.invalidate();\n }\n }\n }", "public T transitInt(int propertyId, int... vals) {\n String property = getPropertyName(propertyId);\n mHolders.put(propertyId, PropertyValuesHolder.ofInt(property, vals));\n mShadowHolders.put(propertyId, ShadowValuesHolder.ofInt(property, vals));\n return self();\n }", "public static String readTextFile(File file) {\n try {\n return readTextFile(new FileReader(file));\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n return null;\n }\n }", "public @Nullable ChangeEvent<BsonDocument> getUnprocessedEventForDocumentId(\n final MongoNamespace namespace,\n final BsonValue documentId\n ) {\n this.instanceLock.readLock().lock();\n final NamespaceChangeStreamListener streamer;\n try {\n streamer = nsStreamers.get(namespace);\n } finally {\n this.instanceLock.readLock().unlock();\n }\n\n if (streamer == null) {\n return null;\n }\n\n return streamer.getUnprocessedEventForDocumentId(documentId);\n }", "@SuppressWarnings(\"unchecked\")\n public static <T> T getJlsDefaultValue(Class<T> type) {\n if(!type.isPrimitive()) {\n return null;\n }\n return (T) JLS_PRIMITIVE_DEFAULT_VALUES.get(type);\n }", "public Iterable<BoxLegalHoldAssignment.Info> getAssignments(String ... fields) {\n return this.getAssignments(null, null, DEFAULT_LIMIT, fields);\n }", "public static <T> T callConstructor(Class<T> klass) {\n return callConstructor(klass, new Class<?>[0], new Object[0]);\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 }" ]
Compute Cholesky decomposition of A @param A symmetric, positive definite matrix (only upper half is used) @return upper triangular matrix U such that A = U' * U
[ "public static DoubleMatrix cholesky(DoubleMatrix A) {\n DoubleMatrix result = A.dup();\n int info = NativeBlas.dpotrf('U', A.rows, result.data, 0, A.rows);\n if (info < 0) {\n throw new LapackArgumentException(\"DPOTRF\", -info);\n } else if (info > 0) {\n throw new LapackPositivityException(\"DPOTRF\", \"Minor \" + info + \" was negative. Matrix must be positive definite.\");\n }\n clearLower(result);\n return result;\n }" ]
[ "public ClassificationModel attachLink(ClassificationModel classificationModel, LinkModel linkModel)\n {\n for (LinkModel existing : classificationModel.getLinks())\n {\n if (StringUtils.equals(existing.getLink(), linkModel.getLink()))\n {\n return classificationModel;\n }\n }\n classificationModel.addLink(linkModel);\n return classificationModel;\n }", "public Collection<BoxGroupMembership.Info> getMemberships() {\n BoxAPIConnection api = this.getAPI();\n URL url = USER_MEMBERSHIPS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int entriesCount = responseJSON.get(\"total_count\").asInt();\n Collection<BoxGroupMembership.Info> memberships = new ArrayList<BoxGroupMembership.Info>(entriesCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue entry : entries) {\n JsonObject entryObject = entry.asObject();\n BoxGroupMembership membership = new BoxGroupMembership(api, entryObject.get(\"id\").asString());\n BoxGroupMembership.Info info = membership.new Info(entryObject);\n memberships.add(info);\n }\n\n return memberships;\n }", "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 }", "@PostConstruct\n\tprotected void buildCopyrightMap() {\n\t\tif (null == declaredPlugins) {\n\t\t\treturn;\n\t\t}\n\t\t// go over all plug-ins, adding copyright info, avoiding duplicates (on object key)\n\t\tfor (PluginInfo plugin : declaredPlugins.values()) {\n\t\t\tfor (CopyrightInfo copyright : plugin.getCopyrightInfo()) {\n\t\t\t\tString key = copyright.getKey();\n\t\t\t\tString msg = copyright.getKey() + \": \" + copyright.getCopyright() + \" : licensed as \" +\n\t\t\t\t\t\tcopyright.getLicenseName() + \", see \" + copyright.getLicenseUrl();\n\t\t\t\tif (null != copyright.getSourceUrl()) {\n\t\t\t\t\tmsg += \" source \" + copyright.getSourceUrl();\n\t\t\t\t}\n\t\t\t\tif (!copyrightMap.containsKey(key)) {\n\t\t\t\t\tlog.info(msg);\n\t\t\t\t\tcopyrightMap.put(key, copyright);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "@Override public void onBindViewHolder(RendererViewHolder viewHolder, int position) {\n T content = getItem(position);\n Renderer<T> renderer = viewHolder.getRenderer();\n if (renderer == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null renderer\");\n }\n renderer.setContent(content);\n updateRendererExtraValues(content, renderer, position);\n renderer.render();\n }", "private String long2string(Long value, DateTimeFormat fmt) {\n // for html5 inputs, use \"\" for no value\n if (value == null) return \"\";\n Date date = UTCDateBox.utc2date(value);\n return date != null ? fmt.format(date) : null;\n }", "public final void notifyContentItemRangeRemoved(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for content items [0 - \"\n + (contentItemCount - 1) + \"].\");\n }\n notifyItemRangeRemoved(positionStart + headerItemCount, itemCount);\n }", "public IPv6AddressSegment join(IPv6AddressCreator creator, IPv4AddressSegment low) throws IncompatibleAddressException {\r\n\t\tint shift = IPv4Address.BITS_PER_SEGMENT;\r\n\t\tInteger prefix = getJoinedSegmentPrefixLength(shift, getSegmentPrefixLength(), low.getSegmentPrefixLength());\r\n\t\tif(isMultiple()) {\r\n\t\t\t//if the high segment has a range, the low segment must match the full range, \r\n\t\t\t//otherwise it is not possible to create an equivalent range when joining\r\n\t\t\tif(!low.isFullRange()) {\r\n\t\t\t\tthrow new IncompatibleAddressException(this, low, \"ipaddress.error.invalidMixedRange\");\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn creator.createSegment(\r\n\t\t\t\t(getSegmentValue() << shift) | low.getSegmentValue(), \r\n\t\t\t\t(getUpperSegmentValue() << shift) | low.getUpperSegmentValue(),\r\n\t\t\t\tprefix);\r\n\t}", "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 }" ]
helper method to set the TranslucentNavigationFlag @param on
[ "public static void setTranslucentNavigationFlag(Activity activity, boolean on) {\n if (Build.VERSION.SDK_INT >= 19) {\n setFlag(activity, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, on);\n }\n }" ]
[ "private synchronized JsonSchema getInputPathJsonSchema() throws IOException {\n if (inputPathJsonSchema == null) {\n // No need to query Hadoop more than once as this shouldn't change mid-run,\n // thus, we can lazily initialize and cache the result.\n inputPathJsonSchema = HadoopUtils.getSchemaFromPath(getInputPath());\n }\n return inputPathJsonSchema;\n }", "private void processProject(PrimaveraDatabaseReader reader, int projectID, String outputFile) throws Exception\n {\n long start = System.currentTimeMillis();\n reader.setProjectID(projectID);\n ProjectFile projectFile = reader.read();\n long elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Reading database completed in \" + elapsed + \"ms.\");\n\n System.out.println(\"Writing output file started.\");\n start = System.currentTimeMillis();\n ProjectWriter writer = ProjectWriterUtility.getProjectWriter(outputFile);\n writer.write(projectFile, outputFile);\n elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Writing output completed in \" + elapsed + \"ms.\");\n }", "public Where<T, ID> and() {\n\t\tManyClause clause = new ManyClause(pop(\"AND\"), ManyClause.AND_OPERATION);\n\t\tpush(clause);\n\t\taddNeedsFuture(clause);\n\t\treturn this;\n\t}", "public DockerContainerObjectBuilder<T> withContainerObjectClass(Class<T> containerObjectClass) {\n if (containerObjectClass == null) {\n throw new IllegalArgumentException(\"container object class cannot be null\");\n }\n this.containerObjectClass = containerObjectClass;\n\n //First we check if this ContainerObject is defining a @CubeDockerFile in static method\n final List<Method> methodsWithCubeDockerFile =\n ReflectionUtil.getMethodsWithAnnotation(containerObjectClass, CubeDockerFile.class);\n\n if (methodsWithCubeDockerFile.size() > 1) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Methods where annotation was found are: %s\",\n CubeDockerFile.class.getSimpleName(), methodsWithCubeDockerFile));\n }\n\n classHasMethodWithCubeDockerFile = !methodsWithCubeDockerFile.isEmpty();\n classDefinesCubeDockerFile = containerObjectClass.isAnnotationPresent(CubeDockerFile.class);\n classDefinesImage = containerObjectClass.isAnnotationPresent(Image.class);\n\n if (classHasMethodWithCubeDockerFile) {\n methodWithCubeDockerFile = methodsWithCubeDockerFile.get(0);\n boolean isMethodStatic = Modifier.isStatic(methodWithCubeDockerFile.getModifiers());\n boolean methodHasNoArguments = methodWithCubeDockerFile.getParameterCount() == 0;\n boolean methodReturnsAnArchive = Archive.class.isAssignableFrom(methodWithCubeDockerFile.getReturnType());\n if (!isMethodStatic || !methodHasNoArguments || !methodReturnsAnArchive) {\n throw new IllegalArgumentException(\n String.format(\"Method %s annotated with %s is expected to be static, no args and return %s.\",\n methodWithCubeDockerFile, CubeDockerFile.class.getSimpleName(), Archive.class.getSimpleName()));\n }\n }\n\n // User has defined @CubeDockerfile on the class and a method\n if (classHasMethodWithCubeDockerFile && classDefinesCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Both class and method %s has the annotation.\",\n CubeDockerFile.class.getSimpleName(), methodWithCubeDockerFile));\n }\n\n // User has defined @CubeDockerfile and @Image\n if ((classHasMethodWithCubeDockerFile || classDefinesCubeDockerFile) && classDefinesImage) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s has defined %s annotation and %s annotation together.\",\n containerObjectClass.getSimpleName(), Image.class.getSimpleName(),\n CubeDockerFile.class.getSimpleName()));\n }\n\n // User has not defined either @CubeDockerfile or @Image\n if (!classDefinesCubeDockerFile && !classDefinesImage && !classHasMethodWithCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s is not annotated with either %s or %s annotations.\",\n containerObjectClass.getName(), CubeDockerFile.class.getSimpleName(), Image.class.getSimpleName()));\n }\n\n return this;\n }", "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 String get(final String key) {\n final Collection<Argument> args = map.get(key);\n if (args != null) {\n return args.iterator().hasNext() ? args.iterator().next().getValue() : null;\n }\n return null;\n }", "@Override\n\tpublic Iterator<? extends IPAddressSeqRange> prefixIterator(int prefixLength) {\n\t\tif(!isMultiple()) {\n\t\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\t\tIPAddressSeqRange orig = IPAddressSeqRange.this;\n\n\t\t\t\t@Override\n\t\t\t\tpublic boolean hasNext() {\n\t\t\t\t\treturn orig != null;\n\t\t\t\t}\n\n\t\t\t @Override\n\t\t\t\tpublic IPAddressSeqRange next() {\n\t\t\t \tif(orig == null) {\n\t\t\t \t\tthrow new NoSuchElementException();\n\t\t\t \t}\n\t\t\t \tIPAddressSeqRange result = orig;\n\t\t\t \torig = null;\n\t\t\t \treturn result;\n\t\t\t }\n\t\t\t\n\t\t\t @Override\n\t\t\t\tpublic void remove() {\n\t\t\t \tthrow new UnsupportedOperationException();\n\t\t\t }\n\t\t\t};\n\t\t}\n\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\tIterator<? extends IPAddress> prefixBlockIterator = prefixBlockIterator(prefixLength);\n\t\t\tprivate boolean first = true;\n\n\t\t\t@Override\n\t\t\tpublic boolean hasNext() {\n\t\t\t\treturn prefixBlockIterator.hasNext();\n\t\t\t}\n\n\t\t @Override\n\t\t\tpublic IPAddressSeqRange next() {\n\t\t \tIPAddress next = prefixBlockIterator.next();\n\t\t \tif(first) {\n\t\t \t\tfirst = false;\n\t\t \t\t// next is a prefix block\n\t\t \t\tIPAddress lower = getLower();\n\t\t \t\tif(hasNext()) {\n\t\t\t \t\tif(!lower.includesZeroHost(prefixLength)) {\n\t\t\t \t\t\treturn create(lower, next.getUpper());\n\t\t\t \t\t}\n\t\t \t\t} else {\n\t\t \t\t\tIPAddress upper = getUpper();\n\t\t \t\t\tif(!lower.includesZeroHost(prefixLength) || !upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\t\treturn create(lower, upper);\n\t\t \t\t\t}\n\t\t \t\t}\n\t\t \t} else if(!hasNext()) {\n\t\t \t\tIPAddress upper = getUpper();\n\t\t \t\tif(!upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\treturn create(next.getLower(), upper);\n\t\t \t\t}\n\t\t \t}\n\t\t \treturn next.toSequentialRange();\n\t\t }\n\t\t\n\t\t @Override\n\t\t\tpublic void remove() {\n\t\t \tthrow new UnsupportedOperationException();\n\t\t }\n\t\t};\n\t}", "protected void addLineContent(BufferedReader bufferedFileReader, List<String> content, String line) throws IOException {\n content.add(line);\n }", "private int slopSize(Versioned<Slop> slopVersioned) {\n int nBytes = 0;\n Slop slop = slopVersioned.getValue();\n nBytes += slop.getKey().length();\n nBytes += ((VectorClock) slopVersioned.getVersion()).sizeInBytes();\n switch(slop.getOperation()) {\n case PUT: {\n nBytes += slop.getValue().length;\n break;\n }\n case DELETE: {\n break;\n }\n default:\n logger.error(\"Unknown slop operation: \" + slop.getOperation());\n }\n return nBytes;\n }" ]
Log a free-form warning @param message the warning message. Cannot be {@code null}
[ "public void logWarning(final String message) {\n messageQueue.add(new LogEntry() {\n @Override\n public String getMessage() {\n return message;\n }\n });\n }" ]
[ "private static long asciidump(InputStream is, PrintWriter pw) throws Exception\n {\n byte[] buffer = new byte[BUFFER_SIZE];\n long byteCount = 0;\n\n char c;\n int loop;\n int count;\n StringBuilder sb = new StringBuilder();\n\n while (true)\n {\n count = is.read(buffer);\n if (count == -1)\n {\n break;\n }\n\n byteCount += count;\n\n sb.setLength(0);\n for (loop = 0; loop < count; loop++)\n {\n c = (char) buffer[loop];\n if (c > 200 || c < 27)\n {\n c = ' ';\n }\n\n sb.append(c);\n }\n\n pw.print(sb.toString());\n }\n\n return (byteCount);\n }", "@NonNull\n @Override\n public Loader<SortedList<File>> getLoader() {\n return new AsyncTaskLoader<SortedList<File>>(getActivity()) {\n\n FileObserver fileObserver;\n\n @Override\n public SortedList<File> loadInBackground() {\n File[] listFiles = mCurrentPath.listFiles();\n final int initCap = listFiles == null ? 0 : listFiles.length;\n\n SortedList<File> files = new SortedList<>(File.class, new SortedListAdapterCallback<File>(getDummyAdapter()) {\n @Override\n public int compare(File lhs, File rhs) {\n return compareFiles(lhs, rhs);\n }\n\n @Override\n public boolean areContentsTheSame(File file, File file2) {\n return file.getAbsolutePath().equals(file2.getAbsolutePath()) && (file.isFile() == file2.isFile());\n }\n\n @Override\n public boolean areItemsTheSame(File file, File file2) {\n return areContentsTheSame(file, file2);\n }\n }, initCap);\n\n\n files.beginBatchedUpdates();\n if (listFiles != null) {\n for (java.io.File f : listFiles) {\n if (isItemVisible(f)) {\n files.add(f);\n }\n }\n }\n files.endBatchedUpdates();\n\n return files;\n }\n\n /**\n * Handles a request to start the Loader.\n */\n @Override\n protected void onStartLoading() {\n super.onStartLoading();\n\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n // Start watching for changes\n fileObserver = new FileObserver(mCurrentPath.getPath(),\n FileObserver.CREATE |\n FileObserver.DELETE\n | FileObserver.MOVED_FROM | FileObserver.MOVED_TO\n ) {\n\n @Override\n public void onEvent(int event, String path) {\n // Reload\n onContentChanged();\n }\n };\n fileObserver.startWatching();\n\n forceLoad();\n }\n\n /**\n * Handles a request to completely reset the Loader.\n */\n @Override\n protected void onReset() {\n super.onReset();\n\n // Stop watching\n if (fileObserver != null) {\n fileObserver.stopWatching();\n fileObserver = null;\n }\n }\n };\n }", "private Query.Builder createScatterQuery(Query query, int numSplits) {\n // TODO(pcostello): We can potentially support better splits with equality filters in our query\n // if there exists a composite index on property, __scatter__, __key__. Until an API for\n // metadata exists, this isn't possible. Note that ancestor and inequality queries fall into\n // the same category.\n Query.Builder scatterPointQuery = Query.newBuilder();\n scatterPointQuery.addAllKind(query.getKindList());\n scatterPointQuery.addOrder(DatastoreHelper.makeOrder(\n DatastoreHelper.SCATTER_PROPERTY_NAME, Direction.ASCENDING));\n // There is a split containing entities before and after each scatter entity:\n // ||---*------*------*------*------*------*------*---|| = scatter entity\n // If we represent each split as a region before a scatter entity, there is an extra region\n // following the last scatter point. Thus, we do not need the scatter entities for the last\n // region.\n scatterPointQuery.getLimitBuilder().setValue((numSplits - 1) * KEYS_PER_SPLIT);\n scatterPointQuery.addProjection(Projection.newBuilder().setProperty(\n PropertyReference.newBuilder().setName(\"__key__\")));\n return scatterPointQuery;\n }", "public <K, V> MultipleRequestBuilder<K, V> newMultipleRequest(Key.Type<K> keyType,\n Class<V> valueType) {\n return new MultipleRequestBuilderImpl<K, V>(newViewRequestParameters(keyType.getType(),\n valueType));\n }", "private CmsTemplateMapperConfiguration getConfiguration(final CmsObject cms) {\n\n if (!m_enabled) {\n return CmsTemplateMapperConfiguration.EMPTY_CONFIG;\n }\n\n if (m_configPath == null) {\n m_configPath = OpenCms.getSystemInfo().getConfigFilePath(cms, \"template-mapping.xml\");\n }\n\n return (CmsTemplateMapperConfiguration)(CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().loadVfsObject(\n cms,\n m_configPath,\n new Transformer() {\n\n @Override\n public Object transform(Object input) {\n\n try {\n CmsFile file = cms.readFile(m_configPath, CmsResourceFilter.IGNORE_EXPIRATION);\n SAXReader saxBuilder = new SAXReader();\n try (ByteArrayInputStream stream = new ByteArrayInputStream(file.getContents())) {\n Document document = saxBuilder.read(stream);\n CmsTemplateMapperConfiguration config = new CmsTemplateMapperConfiguration(cms, document);\n return config;\n }\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return new CmsTemplateMapperConfiguration(); // empty configuration, does not do anything\n }\n\n }\n }));\n }", "public void removeCorporateGroupId(final String organizationId, final String corporateGroupId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n\n if(dbOrganization.getCorporateGroupIdPrefixes().contains(corporateGroupId)){\n dbOrganization.getCorporateGroupIdPrefixes().remove(corporateGroupId);\n repositoryHandler.store(dbOrganization);\n }\n\n repositoryHandler.removeModulesOrganization(corporateGroupId, dbOrganization);\n }", "protected ValueContainer[] getNonKeyValues(PersistenceBroker broker, ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getNonKeyRwValues(cld, obj);\r\n }", "private void setRequestSitefilter(WbGetEntitiesActionData properties) {\n\t\tif (this.filter.excludeAllSiteLinks()\n\t\t\t\t|| this.filter.getSiteLinkFilter() == null) {\n\t\t\treturn;\n\t\t}\n\t\tproperties.sitefilter = ApiConnection.implodeObjects(this.filter\n\t\t\t\t.getSiteLinkFilter());\n\t}", "public static LBuffer loadFrom(File file) throws IOException {\n FileChannel fin = new FileInputStream(file).getChannel();\n long fileSize = fin.size();\n if (fileSize > Integer.MAX_VALUE)\n throw new IllegalArgumentException(\"Cannot load from file more than 2GB: \" + file);\n LBuffer b = new LBuffer((int) fileSize);\n long pos = 0L;\n WritableChannelWrap ch = new WritableChannelWrap(b);\n while (pos < fileSize) {\n pos += fin.transferTo(0, fileSize, ch);\n }\n return b;\n }" ]
Convenience method to escape any character that is special to the regex system. @param inString the string to fix @return the fixed string
[ "private String fixSpecials(final String inString) {\n\t\tStringBuilder tmp = new StringBuilder();\n\n\t\tfor (int i = 0; i < inString.length(); i++) {\n\t\t\tchar chr = inString.charAt(i);\n\n\t\t\tif (isSpecial(chr)) {\n\t\t\t\ttmp.append(this.escape);\n\t\t\t\ttmp.append(chr);\n\t\t\t} else {\n\t\t\t\ttmp.append(chr);\n\t\t\t}\n\t\t}\n\n\t\treturn tmp.toString();\n\t}" ]
[ "private static void addVersionInfo(byte[] grid, int size, int version) {\n // TODO: Zint masks with 0x41 instead of 0x01; which is correct? https://sourceforge.net/p/zint/tickets/110/\n long version_data = QR_ANNEX_D[version - 7];\n for (int i = 0; i < 6; i++) {\n grid[((size - 11) * size) + i] += (version_data >> (i * 3)) & 0x01;\n grid[((size - 10) * size) + i] += (version_data >> ((i * 3) + 1)) & 0x01;\n grid[((size - 9) * size) + i] += (version_data >> ((i * 3) + 2)) & 0x01;\n grid[(i * size) + (size - 11)] += (version_data >> (i * 3)) & 0x01;\n grid[(i * size) + (size - 10)] += (version_data >> ((i * 3) + 1)) & 0x01;\n grid[(i * size) + (size - 9)] += (version_data >> ((i * 3) + 2)) & 0x01;\n }\n }", "public static void validateInterimFinalCluster(final Cluster interimCluster,\n final Cluster finalCluster) {\n validateClusterPartitionCounts(interimCluster, finalCluster);\n validateClusterZonesSame(interimCluster, finalCluster);\n validateClusterNodeCounts(interimCluster, finalCluster);\n validateClusterNodeState(interimCluster, finalCluster);\n return;\n }", "private void recordRollbackLoader(final String patchId, PatchableTarget.TargetInfo target) {\n // setup the content loader paths\n final DirectoryStructure structure = target.getDirectoryStructure();\n final InstalledImage image = structure.getInstalledImage();\n final File historyDir = image.getPatchHistoryDir(patchId);\n final File miscRoot = new File(historyDir, PatchContentLoader.MISC);\n final File modulesRoot = structure.getModulePatchDirectory(patchId);\n final File bundlesRoot = structure.getBundlesPatchDirectory(patchId);\n final PatchContentLoader loader = PatchContentLoader.create(miscRoot, bundlesRoot, modulesRoot);\n //\n recordContentLoader(patchId, loader);\n }", "public static <T> T assertNull(T value, String message) {\n if (value != null)\n throw new IllegalStateException(message);\n return value;\n }", "public static snmpalarm get(nitro_service service, String trapname) throws Exception{\n\t\tsnmpalarm obj = new snmpalarm();\n\t\tobj.set_trapname(trapname);\n\t\tsnmpalarm response = (snmpalarm) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static Field[] getDeclaredFieldsInHierarchy(Class<?> clazz) {\n\n if (clazz.isPrimitive()) {\n throw new IllegalArgumentException(\"Primitive types not supported.\");\n }\n\n List<Field> result = new ArrayList<Field>();\n\n while (true) {\n\n if (clazz == Object.class) {\n break;\n }\n\n result.addAll(Arrays.asList(clazz.getDeclaredFields()));\n clazz = clazz.getSuperclass();\n }\n\n return result.toArray(new Field[result.size()]);\n }", "public static List<String> toList(CharSequence self) {\n String s = self.toString();\n int size = s.length();\n List<String> answer = new ArrayList<String>(size);\n for (int i = 0; i < size; i++) {\n answer.add(s.substring(i, i + 1));\n }\n return answer;\n }", "private boolean isOrdered(FieldDescriptor[] flds, String[] pkFieldNames)\r\n {\r\n if((flds.length > 1 && pkFieldNames == null) || flds.length != pkFieldNames.length)\r\n {\r\n throw new PersistenceBrokerException(\"pkFieldName length does not match number of defined PK fields.\" +\r\n \" Expected number of PK fields is \" + flds.length + \", given number was \" +\r\n (pkFieldNames != null ? pkFieldNames.length : 0));\r\n }\r\n boolean result = true;\r\n for(int i = 0; i < flds.length; i++)\r\n {\r\n FieldDescriptor fld = flds[i];\r\n result = result && fld.getPersistentField().getName().equals(pkFieldNames[i]);\r\n }\r\n return result;\r\n }", "public Story storyOfText(Configuration configuration, String storyAsText, String storyId) {\n return configuration.storyParser().parseStory(storyAsText, storyId);\n }" ]
Process task dependencies.
[ "private void processDependencies()\n {\n Set<Task> tasksWithBars = new HashSet<Task>();\n FastTrackTable table = m_data.getTable(FastTrackTableType.ACTBARS);\n for (MapRow row : table)\n {\n Task task = m_project.getTaskByUniqueID(row.getInteger(ActBarField._ACTIVITY));\n if (task == null || tasksWithBars.contains(task))\n {\n continue;\n }\n tasksWithBars.add(task);\n\n String predecessors = row.getString(ActBarField.PREDECESSORS);\n if (predecessors == null || predecessors.isEmpty())\n {\n continue;\n }\n\n for (String predecessor : predecessors.split(\", \"))\n {\n Matcher matcher = RELATION_REGEX.matcher(predecessor);\n matcher.matches();\n\n Integer id = Integer.valueOf(matcher.group(1));\n RelationType type = RELATION_TYPE_MAP.get(matcher.group(3));\n if (type == null)\n {\n type = RelationType.FINISH_START;\n }\n\n String sign = matcher.group(4);\n double lag = NumberHelper.getDouble(matcher.group(5));\n if (\"-\".equals(sign))\n {\n lag = -lag;\n }\n\n Task targetTask = m_project.getTaskByID(id);\n if (targetTask != null)\n {\n Duration lagDuration = Duration.getInstance(lag, m_data.getDurationTimeUnit());\n Relation relation = task.addPredecessor(targetTask, type, lagDuration);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }\n }" ]
[ "public String processNested(Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n XClass type = OjbMemberTagsHandler.getMemberType();\r\n int dim = OjbMemberTagsHandler.getMemberDimension();\r\n NestedDef nestedDef = _curClassDef.getNested(name);\r\n\r\n if (type == null)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_DETERMINE_TYPE_OF_MEMBER,\r\n new String[]{name}));\r\n }\r\n if (dim > 0)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.MEMBER_CANNOT_BE_NESTED,\r\n new String[]{name, _curClassDef.getName()}));\r\n }\r\n\r\n ClassDescriptorDef nestedTypeDef = _model.getClass(type.getQualifiedName());\r\n\r\n if (nestedTypeDef == null)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_DETERMINE_TYPE_OF_MEMBER,\r\n new String[]{name}));\r\n }\r\n if (nestedDef == null)\r\n {\r\n nestedDef = new NestedDef(name, nestedTypeDef);\r\n _curClassDef.addNested(nestedDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processNested\", \" Processing nested object \"+nestedDef.getName()+\" of type \"+nestedTypeDef.getName());\r\n\r\n String attrName;\r\n \r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n nestedDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }", "public void setBaselineFinishText(int baselineNumber, String value)\n {\n set(selectField(TaskFieldLists.BASELINE_FINISHES, baselineNumber), value);\n }", "@Value(\"${locator.strategy}\")\n public void setDefaultLocatorSelectionStrategy(String defaultLocatorSelectionStrategy) {\n this.defaultLocatorSelectionStrategy = defaultLocatorSelectionStrategy;\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Default strategy \" + defaultLocatorSelectionStrategy\n + \" was set for LocatorClientRegistrar.\");\n }\n }", "@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher addFacet(String... attributes) {\n for (String attribute : attributes) {\n final Integer value = facetRequestCount.get(attribute);\n facetRequestCount.put(attribute, value == null ? 1 : value + 1);\n if (value == null || value == 0) {\n facets.add(attribute);\n }\n }\n rebuildQueryFacets();\n return this;\n }", "public boolean detectTierRichCss() {\r\n\r\n boolean result = false;\r\n //The following devices are explicitly ok.\r\n //Note: 'High' BlackBerry devices ONLY\r\n if (detectMobileQuick()) {\r\n\r\n //Exclude iPhone Tier and e-Ink Kindle devices.\r\n if (!detectTierIphone() && !detectKindle()) {\r\n\r\n //The following devices are explicitly ok.\r\n //Note: 'High' BlackBerry devices ONLY\r\n //Older Windows 'Mobile' isn't good enough for iPhone Tier.\r\n if (detectWebkit()\r\n || detectS60OssBrowser()\r\n || detectBlackBerryHigh()\r\n || detectWindowsMobile()\r\n || (userAgent.indexOf(engineTelecaQ) != -1)) {\r\n result = true;\r\n } // if detectWebkit()\r\n } //if !detectTierIphone()\r\n } //if detectMobileQuick()\r\n return result;\r\n }", "protected static void printValuesSorted(String message, Set<String> values)\n {\n System.out.println();\n System.out.println(message + \":\");\n List<String> sorted = new ArrayList<>(values);\n Collections.sort(sorted);\n for (String value : sorted)\n {\n System.out.println(\"\\t\" + value);\n }\n }", "public static DMatrixRBlock transpose(DMatrixRBlock A , DMatrixRBlock A_tran )\n {\n if( A_tran != null ) {\n if( A.numRows != A_tran.numCols || A.numCols != A_tran.numRows )\n throw new IllegalArgumentException(\"Incompatible dimensions.\");\n if( A.blockLength != A_tran.blockLength )\n throw new IllegalArgumentException(\"Incompatible block size.\");\n } else {\n A_tran = new DMatrixRBlock(A.numCols,A.numRows,A.blockLength);\n\n }\n\n for( int i = 0; i < A.numRows; i += A.blockLength ) {\n int blockHeight = Math.min( A.blockLength , A.numRows - i);\n\n for( int j = 0; j < A.numCols; j += A.blockLength ) {\n int blockWidth = Math.min( A.blockLength , A.numCols - j);\n\n int indexA = i*A.numCols + blockHeight*j;\n int indexC = j*A_tran.numCols + blockWidth*i;\n\n transposeBlock( A , A_tran , indexA , indexC , blockWidth , blockHeight );\n }\n }\n\n return A_tran;\n }", "public static RgbaColor fromHsl(float H, float S, float L) {\n\n // convert to [0-1]\n H /= 360f;\n S /= 100f;\n L /= 100f;\n\n float R, G, B;\n\n if (S == 0) {\n // grey\n R = G = B = L;\n }\n else {\n float m2 = L <= 0.5 ? L * (S + 1f) : L + S - L * S;\n float m1 = 2f * L - m2;\n R = hue2rgb(m1, m2, H + 1 / 3f);\n G = hue2rgb(m1, m2, H);\n B = hue2rgb(m1, m2, H - 1 / 3f);\n }\n\n // convert [0-1] to [0-255]\n int r = Math.round(R * 255f);\n int g = Math.round(G * 255f);\n int b = Math.round(B * 255f);\n\n return new RgbaColor(r, g, b, 1);\n }", "synchronized void removeServerProcess() {\n this.requiredState = InternalState.STOPPED;\n internalSetState(new ProcessRemoveTask(), InternalState.STOPPED, InternalState.PROCESS_REMOVING);\n }" ]
Write the text to the File, using the specified encoding. @param file a File @param text the text to write to the File @param charset the charset used @throws IOException if an IOException occurs. @since 1.0
[ "public static void write(File file, String text, String charset) throws IOException {\n Writer writer = null;\n try {\n FileOutputStream out = new FileOutputStream(file);\n writeUTF16BomIfRequired(charset, out);\n writer = new OutputStreamWriter(out, charset);\n writer.write(text);\n writer.flush();\n\n Writer temp = writer;\n writer = null;\n temp.close();\n } finally {\n closeWithWarning(writer);\n }\n }" ]
[ "public static base_response add(nitro_service client, linkset resource) throws Exception {\n\t\tlinkset addresource = new linkset();\n\t\taddresource.id = resource.id;\n\t\treturn addresource.add_resource(client);\n\t}", "private void checkModifications(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n HashMap features = new HashMap();\r\n FeatureDescriptorDef def;\r\n\r\n for (Iterator it = classDef.getFields(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getReferences(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getCollections(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n\r\n // now checking the modifications\r\n Properties mods;\r\n String modName;\r\n String propName;\r\n\r\n for (Iterator it = classDef.getModificationNames(); it.hasNext();)\r\n {\r\n modName = (String)it.next();\r\n if (!features.containsKey(modName))\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for an unknown feature \"+modName);\r\n }\r\n def = (FeatureDescriptorDef)features.get(modName);\r\n if (def.getOriginal() == null)\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for a feature \"+modName+\" that is not inherited but defined in the same class\");\r\n }\r\n // checking modification\r\n mods = classDef.getModification(modName);\r\n for (Iterator propIt = mods.keySet().iterator(); propIt.hasNext();)\r\n {\r\n propName = (String)propIt.next();\r\n if (!PropertyHelper.isPropertyAllowed(def.getClass(), propName))\r\n {\r\n throw new ConstraintException(\"The modification of attribute \"+propName+\" in class \"+classDef.getName()+\" is not applicable to the feature \"+modName);\r\n }\r\n }\r\n }\r\n }", "public LuaPreparedScript endPreparedScript(LuaScriptConfig config) {\n if (!endsWithReturnStatement()) {\n add(new LuaAstReturnStatement());\n }\n String scriptText = buildScriptText();\n ArrayList<LuaKeyArgument> keyList = new ArrayList<>(keyArg2AstArg.keySet());\n ArrayList<LuaValueArgument> argvList = new ArrayList<>(valueArg2AstArg.keySet());\n if (config.isThreadSafe()) {\n return new ThreadSafeLuaPreparedScript(scriptText, keyList, argvList, config);\n } else {\n return new BasicLuaPreparedScript(scriptText, keyList, argvList, config);\n }\n }", "public static void applyWsdlExtensions(Bus bus) {\n\n ExtensionRegistry registry = bus.getExtension(WSDLManager.class).getExtensionRegistry();\n\n try {\n\n JAXBExtensionHelper.addExtensions(registry,\n javax.wsdl.Definition.class,\n org.talend.esb.mep.requestcallback.impl.wsdl.PLType.class);\n\n JAXBExtensionHelper.addExtensions(registry,\n javax.wsdl.Binding.class,\n org.talend.esb.mep.requestcallback.impl.wsdl.CallbackExtension.class);\n\n } catch (JAXBException e) {\n throw new RuntimeException(\"Failed to add WSDL JAXB extensions\", e);\n }\n }", "public synchronized void pauseDeployment(final String deployment, ServerActivityCallback listener) {\n final List<ControlPoint> eps = new ArrayList<ControlPoint>();\n for (ControlPoint ep : entryPoints.values()) {\n if (ep.getDeployment().equals(deployment)) {\n if(!ep.isPaused()) {\n eps.add(ep);\n }\n }\n }\n CountingRequestCountCallback realListener = new CountingRequestCountCallback(eps.size(), listener);\n for (ControlPoint ep : eps) {\n ep.pause(realListener);\n }\n }", "public static void objectToXML(Object object, String fileName) throws FileNotFoundException {\r\n\t\tFileOutputStream fo = new FileOutputStream(fileName);\r\n\t\tXMLEncoder encoder = new XMLEncoder(fo);\r\n\t\tencoder.writeObject(object);\r\n\t\tencoder.close();\r\n\t}", "private static String handleRichError(final Response response, final String body) {\n if (!response.getHeaders().containsKey(Headers.CONTENT_TYPE)\n || !response.getHeaders().get(Headers.CONTENT_TYPE).equals(ContentTypes.APPLICATION_JSON)) {\n return body;\n }\n\n final Document doc;\n try {\n doc = BsonUtils.parseValue(body, Document.class);\n } catch (Exception e) {\n return body;\n }\n\n if (!doc.containsKey(Fields.ERROR)) {\n return body;\n }\n final String errorMsg = doc.getString(Fields.ERROR);\n if (!doc.containsKey(Fields.ERROR_CODE)) {\n return errorMsg;\n }\n\n final String errorCode = doc.getString(Fields.ERROR_CODE);\n throw new StitchServiceException(errorMsg, StitchServiceErrorCode.fromCodeName(errorCode));\n }", "public static PropertyResourceBundle getBundle(String baseName, Locale locale) throws UnsupportedEncodingException, IOException{\n\t\tInputStream is = UTF8PropertyResourceBundle.class.getResourceAsStream(\"/\"+baseName + \"_\"+locale.toString()+PROPERTIES_EXT);\n\t\tif(is != null){\n\t\t\treturn new PropertyResourceBundle(new InputStreamReader(is, \"UTF-8\"));\n\t\t}\n\t\treturn null;\n\t}", "private String getTimeString(Date value)\n {\n Calendar cal = DateHelper.popCalendar(value);\n int hours = cal.get(Calendar.HOUR_OF_DAY);\n int minutes = cal.get(Calendar.MINUTE);\n DateHelper.pushCalendar(cal);\n \n StringBuilder sb = new StringBuilder(4);\n sb.append(m_twoDigitFormat.format(hours));\n sb.append(m_twoDigitFormat.format(minutes));\n\n return (sb.toString());\n }" ]
returns a new segment masked by the given mask This method applies the mask first to every address in the range, and it does not preserve any existing prefix. The given prefix will be applied to the range of addresses after the mask. If the combination of the two does not result in a contiguous range, then {@link IncompatibleAddressException} is thrown.
[ "protected boolean isChangedByMask(int maskValue, Integer segmentPrefixLength) throws IncompatibleAddressException {\r\n\t\tboolean hasBits = (segmentPrefixLength != null);\r\n\t\tif(hasBits && (segmentPrefixLength < 0 || segmentPrefixLength > getBitCount())) {\r\n\t\t\tthrow new PrefixLenException(this, segmentPrefixLength);\r\n\t\t}\r\n\t\t\r\n\t\t//note that the mask can represent a range (for example a CIDR mask), \r\n\t\t//but we use the lowest value (maskSegment.value) in the range when masking (ie we discard the range)\r\n\t\tint value = getSegmentValue();\r\n\t\tint upperValue = getUpperSegmentValue();\r\n\t\treturn value != (value & maskValue) ||\r\n\t\t\t\tupperValue != (upperValue & maskValue) ||\r\n\t\t\t\t\t\t(isPrefixed() ? !getSegmentPrefixLength().equals(segmentPrefixLength) : hasBits);\r\n\t}" ]
[ "public BlockHeader read(byte[] buffer, int offset, int postHeaderSkipBytes)\n {\n m_offset = offset;\n\n System.arraycopy(buffer, m_offset, m_header, 0, 8);\n m_offset += 8;\n\n int nameLength = FastTrackUtility.getInt(buffer, m_offset);\n m_offset += 4;\n\n if (nameLength < 1 || nameLength > 255)\n {\n throw new UnexpectedStructureException();\n }\n\n m_name = new String(buffer, m_offset, nameLength, CharsetHelper.UTF16LE);\n m_offset += nameLength;\n\n m_columnType = FastTrackUtility.getShort(buffer, m_offset);\n m_offset += 2;\n\n m_flags = FastTrackUtility.getShort(buffer, m_offset);\n m_offset += 2;\n\n m_skip = new byte[postHeaderSkipBytes];\n System.arraycopy(buffer, m_offset, m_skip, 0, postHeaderSkipBytes);\n m_offset += postHeaderSkipBytes;\n\n return this;\n }", "public void remove(Identity oid)\r\n {\r\n if (oid == null) return;\r\n\r\n ObjectCache cache = getCache(oid, null, METHOD_REMOVE);\r\n if (cache != null)\r\n {\r\n cache.remove(oid);\r\n }\r\n }", "public void performImplicitDoubleStep(int x1, int x2 , double real , double img ) {\n double a11 = A.get(x1,x1);\n double a21 = A.get(x1+1,x1);\n double a12 = A.get(x1,x1+1);\n double a22 = A.get(x1+1,x1+1);\n double a32 = A.get(x1+2,x1+1);\n\n double p_plus_t = 2.0*real;\n double p_times_t = real*real + img*img;\n\n double b11,b21,b31;\n if( useStandardEq ) {\n b11 = (a11*a11 - p_plus_t*a11+p_times_t)/a21 + a12;\n b21 = a11+a22-p_plus_t;\n b31 = a32;\n } else {\n // this is different from the version in the book and seems in my testing to be more resilient to\n // over flow issues\n b11 = (a11*a11 - p_plus_t*a11+p_times_t) + a12*a21;\n b21 = (a11+a22-p_plus_t)*a21;\n b31 = a32*a21;\n }\n\n performImplicitDoubleStep(x1, x2, b11, b21, b31);\n }", "public SimplifySpanBuild append(String text) {\n if (TextUtils.isEmpty(text)) return this;\n\n mNormalSizeText.append(text);\n mStringBuilder.append(text);\n return this;\n }", "public void logAttributeWarning(PathAddress address, Set<String> attributes) {\n logAttributeWarning(address, null, null, attributes);\n }", "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}", "public static void generateOutputFile(Random rng,\n File outputFile) throws IOException\n {\n DataOutputStream dataOutput = null;\n try\n {\n dataOutput = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));\n for (int i = 0; i < INT_COUNT; i++)\n {\n dataOutput.writeInt(rng.nextInt());\n }\n dataOutput.flush();\n }\n finally\n {\n if (dataOutput != null)\n {\n dataOutput.close();\n }\n }\n }", "public 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}", "public ModelNode translateOperationForProxy(final ModelNode op) {\n return translateOperationForProxy(op, PathAddress.pathAddress(op.get(OP_ADDR)));\n }" ]
Initializes an annotation class @param name The name of the annotation class @return The instance of the annotation. Returns a dummy if the class was not found
[ "@SuppressWarnings(\"unchecked\")\n protected Class<? extends Annotation> annotationTypeForName(String name) {\n try {\n return (Class<? extends Annotation>) resourceLoader.classForName(name);\n } catch (ResourceLoadingException cnfe) {\n return DUMMY_ANNOTATION;\n }\n }" ]
[ "public static void log(final String templateName, final Template template, final Values values) {\n new ValuesLogger().doLog(templateName, template, values);\n }", "public void shutdown() {\n final Connection connection;\n synchronized (this) {\n if(shutdown) return;\n shutdown = true;\n connection = this.connection;\n if(connectTask != null) {\n connectTask.shutdown();\n }\n }\n if (connection != null) {\n connection.closeAsync();\n }\n }", "public void forceApply(String conflictResolution) {\n\n URL url = FORCE_METADATA_CASCADE_POLICIES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"conflict_resolution\", conflictResolution);\n request.setBody(requestJSON.toString());\n request.send();\n }", "@Override\n\tpublic CrawlSession call() {\n\t\tInjector injector = Guice.createInjector(new CoreModule(config));\n\t\tcontroller = injector.getInstance(CrawlController.class);\n\t\tCrawlSession session = controller.call();\n\t\treason = controller.getReason();\n\t\treturn session;\n\t}", "private void stream(InputStream is, File destFile) throws IOException {\n try {\n startProgress();\n OutputStream os = new FileOutputStream(destFile);\n \n boolean finished = false;\n try {\n byte[] buf = new byte[1024 * 10];\n int read;\n while ((read = is.read(buf)) >= 0) {\n os.write(buf, 0, read);\n processedBytes += read;\n logProgress();\n }\n \n os.flush();\n finished = true;\n } finally {\n os.close();\n if (!finished) {\n destFile.delete();\n }\n }\n } finally {\n is.close();\n completeProgress();\n }\n }", "public static String plus(Number value, String right) {\n return DefaultGroovyMethods.toString(value) + right;\n }", "public void addInterface(Class<?> newInterface) {\n if (!newInterface.isInterface()) {\n throw new IllegalArgumentException(newInterface + \" is not an interface\");\n }\n additionalInterfaces.add(newInterface);\n }", "private static boolean isDpiSet(final Multimap<String, String> extraParams) {\n String searchKey = \"FORMAT_OPTIONS\";\n for (String key: extraParams.keys()) {\n if (key.equalsIgnoreCase(searchKey)) {\n for (String value: extraParams.get(key)) {\n if (value.toLowerCase().contains(\"dpi:\")) {\n return true;\n }\n }\n }\n }\n return false;\n }", "public String getScopes() {\n final StringBuilder sb = new StringBuilder();\n for (final Scope scope : Scope.values()) {\n sb.append(scope);\n sb.append(\", \");\n }\n final String scopes = sb.toString().trim();\n return scopes.substring(0, scopes.length() - 1);\n }" ]
Returns the complete tag record for a single tag. @param tag The tag to get. @return Request object
[ "public ItemRequest<Tag> findById(String tag) {\n \n String path = String.format(\"/tags/%s\", tag);\n return new ItemRequest<Tag>(this, Tag.class, path, \"GET\");\n }" ]
[ "public ModelSource resolveModel( Parent parent )\r\n throws UnresolvableModelException {\r\n\r\n Dependency parentDependency = new Dependency();\r\n parentDependency.setGroupId(parent.getGroupId());\r\n parentDependency.setArtifactId(parent.getArtifactId());\r\n parentDependency.setVersion(parent.getVersion());\r\n parentDependency.setClassifier(\"\");\r\n parentDependency.setType(\"pom\");\r\n\r\n Artifact parentArtifact = null;\r\n try\r\n {\r\n Iterable<ArtifactResult> artifactResults = depencencyResolver.resolveDependencies(\r\n projectBuildingRequest, singleton(parentDependency), null, null );\r\n Iterator<ArtifactResult> iterator = artifactResults.iterator();\r\n if (iterator.hasNext()) {\r\n parentArtifact = iterator.next().getArtifact();\r\n }\r\n } catch (DependencyResolverException e) {\r\n throw new UnresolvableModelException( e.getMessage(), parent.getGroupId(), parent.getArtifactId(),\r\n parent.getVersion(), e );\r\n }\r\n\r\n return resolveModel( parentArtifact.getGroupId(), parentArtifact.getArtifactId(), parentArtifact.getVersion() );\r\n }", "public void setDialect(String dialect) {\n String[] scripts = createScripts.get(dialect);\n createSql = scripts[0];\n createSqlInd = scripts[1];\n }", "private List<TimephasedWork> splitWork(CostRateTable table, ProjectCalendar calendar, TimephasedWork work, int rateIndex)\n {\n List<TimephasedWork> result = new LinkedList<TimephasedWork>();\n work.setTotalAmount(Duration.getInstance(0, work.getAmountPerDay().getUnits()));\n\n while (true)\n {\n CostRateTableEntry rate = table.get(rateIndex);\n Date splitDate = rate.getEndDate();\n if (splitDate.getTime() >= work.getFinish().getTime())\n {\n result.add(work);\n break;\n }\n\n Date currentPeriodEnd = calendar.getPreviousWorkFinish(splitDate);\n\n TimephasedWork currentPeriod = new TimephasedWork(work);\n currentPeriod.setFinish(currentPeriodEnd);\n result.add(currentPeriod);\n\n Date nextPeriodStart = calendar.getNextWorkStart(splitDate);\n work.setStart(nextPeriodStart);\n\n ++rateIndex;\n }\n\n return result;\n }", "public static ModelMBeanOperationInfo[] extractOperationInfo(Object object) {\n ArrayList<ModelMBeanOperationInfo> infos = new ArrayList<ModelMBeanOperationInfo>();\n for(Method m: object.getClass().getMethods()) {\n JmxOperation jmxOperation = m.getAnnotation(JmxOperation.class);\n JmxGetter jmxGetter = m.getAnnotation(JmxGetter.class);\n JmxSetter jmxSetter = m.getAnnotation(JmxSetter.class);\n if(jmxOperation != null || jmxGetter != null || jmxSetter != null) {\n String description = \"\";\n int visibility = 1;\n int impact = MBeanOperationInfo.UNKNOWN;\n if(jmxOperation != null) {\n description = jmxOperation.description();\n impact = jmxOperation.impact();\n } else if(jmxGetter != null) {\n description = jmxGetter.description();\n impact = MBeanOperationInfo.INFO;\n visibility = 4;\n } else if(jmxSetter != null) {\n description = jmxSetter.description();\n impact = MBeanOperationInfo.ACTION;\n visibility = 4;\n }\n ModelMBeanOperationInfo info = new ModelMBeanOperationInfo(m.getName(),\n description,\n extractParameterInfo(m),\n m.getReturnType()\n .getName(), impact);\n info.getDescriptor().setField(\"visibility\", Integer.toString(visibility));\n infos.add(info);\n }\n }\n\n return infos.toArray(new ModelMBeanOperationInfo[infos.size()]);\n }", "public static String resolveOrOriginal(String input) {\n try {\n return resolve(input, true);\n } catch (UnresolvedExpressionException e) {\n return input;\n }\n }", "public void setCanvasWidthHeight(int width, int height) {\n hudWidth = width;\n hudHeight = height;\n HUD = Bitmap.createBitmap(width, height, Config.ARGB_8888);\n canvas = new Canvas(HUD);\n texture = null;\n }", "public void setOutlineCode(int index, String value)\n {\n set(selectField(TaskFieldLists.CUSTOM_OUTLINE_CODE, index), value);\n }", "private JSONArray readOptionalArray(JSONObject json, String key) {\n\n try {\n return json.getJSONArray(key);\n } catch (JSONException e) {\n LOG.debug(\"Reading optional JSON array failed. Default to provided default value.\", e);\n }\n return null;\n }", "private void recordMount(SlotReference slot) {\n if (mediaMounts.add(slot)) {\n deliverMountUpdate(slot, true);\n }\n if (!mediaDetails.containsKey(slot)) {\n try {\n VirtualCdj.getInstance().sendMediaQuery(slot);\n } catch (Exception e) {\n logger.warn(\"Problem trying to request media details for \" + slot, e);\n }\n }\n }" ]
Add a '&lt;&gt;' clause so the column must be not-equal-to the value.
[ "public Where<T, ID> ne(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.NOT_EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}" ]
[ "public PlanarImage toDirectColorModel(RenderedImage img) {\n\t\tBufferedImage dest = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);\n\t\tBufferedImage source = new BufferedImage(img.getColorModel(), (WritableRaster) img.getData(), img\n\t\t\t\t.getColorModel().isAlphaPremultiplied(), null);\n\t\tColorConvertOp op = new ColorConvertOp(null);\n\t\top.filter(source, dest);\n\t\treturn PlanarImage.wrapRenderedImage(dest);\n\t}", "public void scaleWeights(double scale) {\r\n for (int i = 0; i < weights.length; i++) {\r\n for (int j = 0; j < weights[i].length; j++) {\r\n weights[i][j] *= scale;\r\n }\r\n }\r\n }", "public ItemRequest<Project> removeFollowers(String project) {\n \n String path = String.format(\"/projects/%s/removeFollowers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }", "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}", "@Nullable\n public StitchUserT getUser() {\n authLock.readLock().lock();\n try {\n return activeUser;\n } finally {\n authLock.readLock().unlock();\n }\n }", "public void process(ProjectProperties properties, FilterContainer filters, FixedData fixedData, Var2Data varData)\n {\n int filterCount = fixedData.getItemCount();\n boolean[] criteriaType = new boolean[2];\n CriteriaReader criteriaReader = getCriteriaReader();\n\n for (int filterLoop = 0; filterLoop < filterCount; filterLoop++)\n {\n byte[] filterFixedData = fixedData.getByteArrayValue(filterLoop);\n if (filterFixedData == null || filterFixedData.length < 4)\n {\n continue;\n }\n\n Filter filter = new Filter();\n filter.setID(Integer.valueOf(MPPUtility.getInt(filterFixedData, 0)));\n filter.setName(MPPUtility.removeAmpersands(MPPUtility.getUnicodeString(filterFixedData, 4)));\n byte[] filterVarData = varData.getByteArray(filter.getID(), getVarDataType());\n if (filterVarData == null)\n {\n continue;\n }\n\n //System.out.println(ByteArrayHelper.hexdump(filterVarData, true, 16, \"\"));\n List<GenericCriteriaPrompt> prompts = new LinkedList<GenericCriteriaPrompt>();\n\n filter.setShowRelatedSummaryRows(MPPUtility.getByte(filterVarData, 4) != 0);\n filter.setCriteria(criteriaReader.process(properties, filterVarData, 0, -1, prompts, null, criteriaType));\n\n filter.setIsTaskFilter(criteriaType[0]);\n filter.setIsResourceFilter(criteriaType[1]);\n filter.setPrompts(prompts);\n\n filters.addFilter(filter);\n //System.out.println(filter);\n }\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}", "public ArrayList<Double> segmentCost(ProjectCalendar projectCalendar, List<TimephasedCost> cost, TimescaleUnits rangeUnits, ArrayList<DateRange> dateList)\n {\n ArrayList<Double> result = new ArrayList<Double>(dateList.size());\n int lastStartIndex = 0;\n\n //\n // Iterate through the list of dates range we are interested in.\n // Each date range in this list corresponds to a column\n // shown on the \"timescale\" view by MS Project\n //\n for (DateRange range : dateList)\n {\n //\n // If the current date range does not intersect with any of the\n // assignment date ranges in the list, then we show a zero\n // duration for this date range.\n //\n int startIndex = lastStartIndex == -1 ? -1 : getStartIndex(range, cost, lastStartIndex);\n if (startIndex == -1)\n {\n result.add(NumberHelper.DOUBLE_ZERO);\n }\n else\n {\n //\n // We have found an assignment which intersects with the current\n // date range, call the method below to determine how\n // much time from this resource assignment can be allocated\n // to the current date range.\n //\n result.add(getRangeCost(projectCalendar, rangeUnits, range, cost, startIndex));\n lastStartIndex = startIndex;\n }\n }\n\n return result;\n }", "@Pure\n\tpublic static <T> Iterable<T> filterNull(Iterable<T> unfiltered) {\n\t\treturn Iterables.filter(unfiltered, Predicates.notNull());\n\t}" ]
Open a new content stream. @param item the content item @return the content stream
[ "InputStream openContentStream(final ContentItem item) throws IOException {\n final File file = getFile(item);\n if (file == null) {\n throw new IllegalStateException();\n }\n return new FileInputStream(file);\n }" ]
[ "public static base_response restore(nitro_service client, appfwprofile resource) throws Exception {\n\t\tappfwprofile restoreresource = new appfwprofile();\n\t\trestoreresource.archivename = resource.archivename;\n\t\treturn restoreresource.perform_operation(client,\"restore\");\n\t}", "public static Value.Builder makeValue(Date date) {\n return Value.newBuilder().setTimestampValue(toTimestamp(date.getTime() * 1000L));\n }", "private ArrayList handleDependentCollections(Identity oid, Object obj,\r\n Object[] origCollections, Object[] newCollections,\r\n Object[] newCollectionsOfObjects)\r\n throws LockingException\r\n {\r\n ClassDescriptor mif = _pb.getClassDescriptor(obj.getClass());\r\n Collection colDescs = mif.getCollectionDescriptors();\r\n ArrayList newObjects = new ArrayList();\r\n int count = 0;\r\n\r\n for (Iterator it = colDescs.iterator(); it.hasNext(); count++)\r\n {\r\n CollectionDescriptor cds = (CollectionDescriptor) it.next();\r\n\r\n if (cds.getOtmDependent())\r\n {\r\n ArrayList origList = (origCollections == null ? null\r\n : (ArrayList) origCollections[count]);\r\n ArrayList newList = (ArrayList) newCollections[count];\r\n\r\n if (origList != null)\r\n {\r\n for (Iterator it2 = origList.iterator(); it2.hasNext(); )\r\n {\r\n Identity origOid = (Identity) it2.next();\r\n\r\n if ((newList == null) || !newList.contains(origOid))\r\n {\r\n markDelete(origOid, oid, true);\r\n }\r\n }\r\n }\r\n\r\n if (newList != null)\r\n {\r\n int countElem = 0;\r\n for (Iterator it2 = newList.iterator(); it2.hasNext(); countElem++)\r\n {\r\n Identity newOid = (Identity) it2.next();\r\n\r\n if ((origList == null) || !origList.contains(newOid))\r\n {\r\n ContextEntry entry = (ContextEntry) _objects.get(newOid);\r\n\r\n if (entry == null)\r\n {\r\n ArrayList relCol = (ArrayList)\r\n newCollectionsOfObjects[count];\r\n Object relObj = relCol.get(countElem);\r\n insertInternal(newOid, relObj, LockType.WRITE_LOCK,\r\n true, null, new Stack());\r\n newObjects.add(newOid);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n return newObjects;\r\n }", "public CustomHeadersInterceptor addHeader(String name, String value) {\n if (!this.headers.containsKey(name)) {\n this.headers.put(name, new ArrayList<String>());\n }\n this.headers.get(name).add(value);\n return this;\n }", "public List<File> getAutoAttachCacheFiles() {\n ArrayList<File> currentFiles = new ArrayList<File>(autoAttachCacheFiles);\n Collections.sort(currentFiles, new Comparator<File>() {\n @Override\n public int compare(File o1, File o2) {\n return o1.getName().compareTo(o2.getName());\n }\n });\n return Collections.unmodifiableList(currentFiles);\n }", "public void setWriteTimeout(int writeTimeout) {\n\t\tthis.client = this.client.newBuilder()\n\t\t\t\t.writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)\n\t\t\t\t.build();\n\t}", "@Override\n public void run() {\n try {\n threadContext.activate();\n // run the original thread\n runnable.run();\n } finally {\n threadContext.invalidate();\n threadContext.deactivate();\n }\n\n }", "@Override\n public PmdRuleSet create() {\n final SAXBuilder parser = new SAXBuilder();\n final Document dom;\n try {\n dom = parser.build(source);\n } catch (JDOMException | IOException e) {\n if (messages != null) {\n messages.addErrorText(INVALID_INPUT + \" : \" + e.getMessage());\n }\n LOG.error(INVALID_INPUT, e);\n return new PmdRuleSet();\n }\n\n final Element eltResultset = dom.getRootElement();\n final Namespace namespace = eltResultset.getNamespace();\n final PmdRuleSet result = new PmdRuleSet();\n\n final String name = eltResultset.getAttributeValue(\"name\");\n final Element descriptionElement = getChild(eltResultset, namespace);\n\n result.setName(name);\n\n if (descriptionElement != null) {\n result.setDescription(descriptionElement.getValue());\n }\n\n for (Element eltRule : getChildren(eltResultset, \"rule\", namespace)) {\n PmdRule pmdRule = new PmdRule(eltRule.getAttributeValue(\"ref\"));\n pmdRule.setClazz(eltRule.getAttributeValue(\"class\"));\n pmdRule.setName(eltRule.getAttributeValue(\"name\"));\n pmdRule.setMessage(eltRule.getAttributeValue(\"message\"));\n parsePmdPriority(eltRule, pmdRule, namespace);\n parsePmdProperties(eltRule, pmdRule, namespace);\n result.addRule(pmdRule);\n }\n return result;\n }", "public void setSessionFactory(SessionFactory sessionFactory) throws HibernateLayerException {\n\t\ttry {\n\t\t\tthis.sessionFactory = sessionFactory;\n\t\t\tif (null != layerInfo) {\n\t\t\t\tentityMetadata = sessionFactory.getClassMetadata(layerInfo.getFeatureInfo().getDataSourceName());\n\t\t\t}\n\t\t} catch (Exception e) { // NOSONAR\n\t\t\tthrow new HibernateLayerException(e, ExceptionCode.HIBERNATE_NO_SESSION_FACTORY);\n\t\t}\n\t}" ]
Used to create a new retention policy. @param api the API connection to be used by the created user. @param name the name of the retention policy. @param type the type of the retention policy. Can be "finite" or "indefinite". @param length the duration in days that the retention policy will be active for after being assigned to content. @param action the disposition action can be "permanently_delete" or "remove_retention". @return the created retention policy's info.
[ "private static BoxRetentionPolicy.Info createRetentionPolicy(BoxAPIConnection api, String name, String type,\r\n int length, String action) {\r\n return createRetentionPolicy(api, name, type, length, action, null);\r\n }" ]
[ "public void sendLoadTrackCommand(int targetPlayer, int rekordboxId,\n int sourcePlayer, CdjStatus.TrackSourceSlot sourceSlot, CdjStatus.TrackType sourceType)\n throws IOException {\n final DeviceUpdate update = getLatestStatusFor(targetPlayer);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + targetPlayer + \" not found on network.\");\n }\n sendLoadTrackCommand(update, rekordboxId, sourcePlayer, sourceSlot, sourceType);\n }", "public void addSerie(AbstractColumn column, StringExpression labelExpression) {\r\n\t\tseries.add(column);\r\n\t\tseriesLabels.put(column, labelExpression);\r\n\t}", "public static Object newInstance(Class target, Class[] types, Object[] args) throws InstantiationException,\r\n IllegalAccessException,\r\n IllegalArgumentException,\r\n InvocationTargetException,\r\n NoSuchMethodException,\r\n SecurityException\r\n {\r\n return newInstance(target, types, args, false);\r\n }", "public static CompressionType getDumpFileCompressionType(String fileName) {\n\t\tif (fileName.endsWith(\".gz\")) {\n\t\t\treturn CompressionType.GZIP;\n\t\t} else if (fileName.endsWith(\".bz2\")) {\n\t\t\treturn CompressionType.BZ2;\n\t\t} else {\n\t\t\treturn CompressionType.NONE;\n\t\t}\n\t}", "protected void setBandsFinalHeight() {\n log.debug(\"Setting bands final height...\");\n\n List<JRBand> bands = new ArrayList<JRBand>();\n\n Utils.addNotNull(bands, design.getPageHeader());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getColumnHeader());\n Utils.addNotNull(bands, design.getColumnFooter());\n Utils.addNotNull(bands, design.getSummary());\n Utils.addNotNull(bands, design.getBackground());\n bands.addAll(((JRDesignSection) design.getDetailSection()).getBandsList());\n Utils.addNotNull(bands, design.getLastPageFooter());\n Utils.addNotNull(bands, design.getTitle());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getNoData());\n\n for (JRGroup jrgroup : design.getGroupsList()) {\n DJGroup djGroup = (DJGroup) getReferencesMap().get(jrgroup.getName());\n JRDesignSection headerSection = (JRDesignSection) jrgroup.getGroupHeaderSection();\n JRDesignSection footerSection = (JRDesignSection) jrgroup.getGroupFooterSection();\n if (djGroup != null) {\n for (JRBand headerBand : headerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) headerBand, djGroup.getHeaderHeight(), djGroup.isFitHeaderHeightToContent());\n\n }\n for (JRBand footerBand : footerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) footerBand, djGroup.getFooterHeight(), djGroup.isFitFooterHeightToContent());\n\n }\n } else {\n bands.addAll(headerSection.getBandsList());\n bands.addAll(footerSection.getBandsList());\n }\n }\n\n for (JRBand jrDesignBand : bands) {\n setBandFinalHeight((JRDesignBand) jrDesignBand);\n }\n }", "void endIfStarted(CodeAttribute b, ClassMethod method) {\n b.aload(getLocalVariableIndex(0));\n b.dup();\n final BranchEnd ifnotnull = b.ifnull();\n b.checkcast(Stack.class);\n b.invokevirtual(Stack.class.getName(), END_INTERCEPTOR_CONTEXT_METHOD_NAME, EMPTY_PARENTHESES + VOID_CLASS_DESCRIPTOR);\n BranchEnd ifnull = b.gotoInstruction();\n b.branchEnd(ifnotnull);\n b.pop(); // remove null Stack\n b.branchEnd(ifnull);\n }", "private float newRandomIndividualParticleRadius(@NonNull final SceneConfiguration scene) {\n return scene.getParticleRadiusMin() == scene.getParticleRadiusMax() ?\n scene.getParticleRadiusMin() : scene.getParticleRadiusMin() + (random.nextInt(\n (int) ((scene.getParticleRadiusMax() - scene.getParticleRadiusMin()) * 100f)))\n / 100f;\n }", "protected void parseSequencesWithColons(TokenList tokens , Sequence sequence ) {\n\n TokenList.Token t = tokens.getFirst();\n if( t == null )\n return;\n\n int state = 0;\n\n TokenList.Token start = null;\n TokenList.Token middle = null;\n TokenList.Token prev = t;\n\n boolean last = false;\n while( true ) {\n if( state == 0 ) {\n if( isVariableInteger(t) && (t.next != null && t.next.getSymbol() == Symbol.COLON) ) {\n start = t;\n state = 1;\n t = t.next;\n } else if( t != null && t.getSymbol() == Symbol.COLON ) {\n // If it starts with a colon then it must be 'all' or a type-o\n IntegerSequence range = new IntegerSequence.Range(null,null);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(range);\n TokenList.Token n = new TokenList.Token(varSequence);\n tokens.insert(t.previous, n);\n tokens.remove(t);\n t = n;\n }\n } else if( state == 1 ) {\n // var : ?\n if (isVariableInteger(t)) {\n state = 2;\n } else {\n // array range\n IntegerSequence range = new IntegerSequence.Range(start,null);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(range);\n replaceSequence(tokens, varSequence, start, prev);\n state = 0;\n }\n } else if ( state == 2 ) {\n // var:var ?\n if( t != null && t.getSymbol() == Symbol.COLON ) {\n middle = prev;\n state = 3;\n } else {\n // create for sequence with start and stop elements only\n IntegerSequence numbers = new IntegerSequence.For(start,null,prev);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n replaceSequence(tokens, varSequence, start, prev );\n if( t != null )\n t = t.previous;\n state = 0;\n }\n } else if ( state == 3 ) {\n // var:var: ?\n if( isVariableInteger(t) ) {\n // create 'for' sequence with three variables\n IntegerSequence numbers = new IntegerSequence.For(start,middle,t);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n t = replaceSequence(tokens, varSequence, start, t);\n } else {\n // array range with 2 elements\n IntegerSequence numbers = new IntegerSequence.Range(start,middle);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n replaceSequence(tokens, varSequence, start, prev);\n }\n state = 0;\n }\n\n if( last ) {\n break;\n } else if( t.next == null ) {\n // handle the case where it is the last token in the sequence\n last = true;\n }\n prev = t;\n t = t.next;\n }\n }", "protected void generateMopCalls(LinkedList<MethodNode> mopCalls, boolean useThis) {\n for (MethodNode method : mopCalls) {\n String name = getMopMethodName(method, useThis);\n Parameter[] parameters = method.getParameters();\n String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameters());\n MethodVisitor mv = controller.getClassVisitor().visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, name, methodDescriptor, null, null);\n controller.setMethodVisitor(mv);\n mv.visitVarInsn(ALOAD, 0);\n int newRegister = 1;\n OperandStack operandStack = controller.getOperandStack();\n for (Parameter parameter : parameters) {\n ClassNode type = parameter.getType();\n operandStack.load(parameter.getType(), newRegister);\n // increment to next register, double/long are using two places\n newRegister++;\n if (type == ClassHelper.double_TYPE || type == ClassHelper.long_TYPE) newRegister++;\n }\n operandStack.remove(parameters.length);\n ClassNode declaringClass = method.getDeclaringClass();\n // JDK 8 support for default methods in interfaces\n // this should probably be strenghtened when we support the A.super.foo() syntax\n int opcode = declaringClass.isInterface()?INVOKEINTERFACE:INVOKESPECIAL;\n mv.visitMethodInsn(opcode, BytecodeHelper.getClassInternalName(declaringClass), method.getName(), methodDescriptor, opcode == INVOKEINTERFACE);\n BytecodeHelper.doReturn(mv, method.getReturnType());\n mv.visitMaxs(0, 0);\n mv.visitEnd();\n controller.getClassNode().addMethod(name, ACC_PUBLIC | ACC_SYNTHETIC, method.getReturnType(), parameters, null, null);\n }\n }" ]
Converts a row major block matrix into a row major matrix. @param src Original DMatrixRBlock.. Not modified. @param dst Equivalent DMatrixRMaj. Modified.
[ "public static DMatrixRMaj convert(DMatrixRBlock src , DMatrixRMaj dst )\n {\n return ConvertDMatrixStruct.convert(src,dst);\n }" ]
[ "private float getQuaternionW(float x, float y, float z) {\n return (float) Math.cos(Math.asin(Math.sqrt(x * x + y * y + z * z)));\n }", "public static void doPublish(final Jedis jedis, final String namespace, final String channel, final String jobJson) {\n jedis.publish(JesqueUtils.createKey(namespace, CHANNEL, channel), jobJson);\n }", "protected boolean hasKey() {\n boolean result = false;\n String requestURI = this.request.getUri();\n parseKeys(requestURI);\n\n if(this.parsedKeys != null) {\n result = true;\n } else {\n logger.error(\"Error when validating request. No key specified.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Error: No key specified !\");\n }\n return result;\n }", "public static void configureLogging() {\n\t\t// Create the appender that will write log messages to the console.\n\t\tConsoleAppender consoleAppender = new ConsoleAppender();\n\t\t// Define the pattern of log messages.\n\t\t// Insert the string \"%c{1}:%L\" to also show class name and line.\n\t\tString pattern = \"%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n\";\n\t\tconsoleAppender.setLayout(new PatternLayout(pattern));\n\t\t// Change to Level.ERROR for fewer messages:\n\t\tconsoleAppender.setThreshold(Level.INFO);\n\n\t\tconsoleAppender.activateOptions();\n\t\tLogger.getRootLogger().addAppender(consoleAppender);\n\t}", "public 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 static ModelMBean createModelMBean(Object o) {\n try {\n ModelMBean mbean = new RequiredModelMBean();\n JmxManaged annotation = o.getClass().getAnnotation(JmxManaged.class);\n String description = annotation == null ? \"\" : annotation.description();\n ModelMBeanInfo info = new ModelMBeanInfoSupport(o.getClass().getName(),\n description,\n extractAttributeInfo(o),\n new ModelMBeanConstructorInfo[0],\n extractOperationInfo(o),\n new ModelMBeanNotificationInfo[0]);\n mbean.setModelMBeanInfo(info);\n mbean.setManagedResource(o, \"ObjectReference\");\n\n return mbean;\n } catch(MBeanException e) {\n throw new VoldemortException(e);\n } catch(InvalidTargetObjectTypeException e) {\n throw new VoldemortException(e);\n } catch(InstanceNotFoundException e) {\n throw new VoldemortException(e);\n }\n }", "public synchronized void addCertAndPrivateKey(String hostname, final X509Certificate cert, final PrivateKey privKey)\n\tthrows KeyStoreException, CertificateException, NoSuchAlgorithmException\n\t{\n//\t\tString alias = ThumbprintUtil.getThumbprint(cert);\n\n\t\t_ks.deleteEntry(hostname);\n\n _ks.setCertificateEntry(hostname, cert);\n\t\t_ks.setKeyEntry(hostname, privKey, _keypassword, new java.security.cert.Certificate[] {cert});\n\n\t\tif(persistImmediately)\n\t\t{\n\t\t\tpersist();\n\t\t}\n\n\t}", "private void readRelationships(Document cdp)\n {\n for (Link link : cdp.getLinks().getLink())\n {\n readRelationship(link);\n }\n }", "private void exportModules() {\n\n // avoid to export modules if unnecessary\n if (((null != m_copyAndUnzip) && !m_copyAndUnzip.booleanValue())\n || ((null == m_copyAndUnzip) && !m_currentConfiguration.getDefaultCopyAndUnzip())) {\n m_logStream.println();\n m_logStream.println(\"NOT EXPORTING MODULES - you disabled copy and unzip.\");\n m_logStream.println();\n return;\n }\n CmsModuleManager moduleManager = OpenCms.getModuleManager();\n\n Collection<String> modulesToExport = ((m_modulesToExport == null) || m_modulesToExport.isEmpty())\n ? m_currentConfiguration.getConfiguredModules()\n : m_modulesToExport;\n\n for (String moduleName : modulesToExport) {\n CmsModule module = moduleManager.getModule(moduleName);\n if (module != null) {\n CmsModuleImportExportHandler handler = CmsModuleImportExportHandler.getExportHandler(\n getCmsObject(),\n module,\n \"Git export handler\");\n try {\n handler.exportData(\n getCmsObject(),\n new CmsPrintStreamReport(\n m_logStream,\n OpenCms.getWorkplaceManager().getWorkplaceLocale(getCmsObject()),\n false));\n } catch (CmsRoleViolationException | CmsConfigurationException | CmsImportExportException e) {\n e.printStackTrace(m_logStream);\n }\n }\n }\n }" ]
Remove the given pair into the map. <p> If the given key is inside the map, but is not mapped to the given value, the map will not be changed. </p> @param <K> type of the map keys. @param <V> type of the map values. @param map the map to update. @param entry the entry (key, value) to remove from the map. @return {@code true} if the pair was removed. @since 2.15
[ "@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}" ]
[ "public static int[] convertBytesToInts(byte[] bytes)\n {\n if (bytes.length % 4 != 0)\n {\n throw new IllegalArgumentException(\"Number of input bytes must be a multiple of 4.\");\n }\n int[] ints = new int[bytes.length / 4];\n for (int i = 0; i < ints.length; i++)\n {\n ints[i] = convertBytesToInt(bytes, i * 4);\n }\n return ints;\n }", "protected static FlushableDataOutput writeHeader(final ManagementProtocolHeader header, final OutputStream os) throws IOException {\n final FlushableDataOutput output = FlushableDataOutputImpl.create(os);\n header.write(output);\n return output;\n }", "public static base_response enable(nitro_service client, nsfeature resource) throws Exception {\n\t\tnsfeature enableresource = new nsfeature();\n\t\tenableresource.feature = resource.feature;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}", "public void writeFinalResults() {\n\t\tprintStatus();\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"gender-ratios.csv\"))) {\n\n\t\t\tout.print(\"Site key,pages total,pages on humans,pages on humans with gender\");\n\t\t\tfor (EntityIdValue gender : this.genderNamesList) {\n\t\t\t\tout.print(\",\" + this.genderNames.get(gender) + \" (\"\n\t\t\t\t\t\t+ gender.getId() + \")\");\n\t\t\t}\n\t\t\tout.println();\n\n\t\t\tList<SiteRecord> siteRecords = new ArrayList<>(\n\t\t\t\t\tthis.siteRecords.values());\n\t\t\tCollections.sort(siteRecords, new SiteRecordComparator());\n\t\t\tfor (SiteRecord siteRecord : siteRecords) {\n\t\t\t\tout.print(siteRecord.siteKey + \",\" + siteRecord.pageCount + \",\"\n\t\t\t\t\t\t+ siteRecord.humanPageCount + \",\"\n\t\t\t\t\t\t+ siteRecord.humanGenderPageCount);\n\n\t\t\t\tfor (EntityIdValue gender : this.genderNamesList) {\n\t\t\t\t\tif (siteRecord.genderCounts.containsKey(gender)) {\n\t\t\t\t\t\tout.print(\",\" + siteRecord.genderCounts.get(gender));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tout.print(\",0\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tout.println();\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "@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}", "public static void moveBandsElemnts(int yOffset, JRDesignBand band) {\n\t\tif (band == null)\n\t\t\treturn;\n\n\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\tJRDesignElement elem = (JRDesignElement) jrChild;\n\t\t\telem.setY(elem.getY() + yOffset);\n\t\t}\n\t}", "private void writeCustomFields() throws IOException\n {\n m_writer.writeStartList(\"custom_fields\");\n for (CustomField field : m_projectFile.getCustomFields())\n {\n writeCustomField(field);\n }\n m_writer.writeEndList();\n }", "public void storeIfNew(final DbArtifact fromClient) {\n final DbArtifact existing = repositoryHandler.getArtifact(fromClient.getGavc());\n\n if(existing != null){\n existing.setLicenses(fromClient.getLicenses());\n store(existing);\n }\n\n if(existing == null){\n\t store(fromClient);\n }\n }", "public static Set<Dependency> getAllDependencies(final Module module, final List<String> producedArtifacts) {\n final Set<Dependency> dependencies = new HashSet<Dependency>();\n\n for(final Dependency dependency: module.getDependencies()){\n if(!producedArtifacts.contains(dependency.getTarget().getGavc())){\n dependencies.add(dependency);\n }\n }\n\n for(final Module subModule: module.getSubmodules()){\n dependencies.addAll(getAllDependencies(subModule, producedArtifacts));\n }\n\n return dependencies;\n }" ]
at this point definition below is not really needed as it is the same as for 1.1, but it is here as place holder when subsystem parser evolves.
[ "@Override\n public PersistentResourceXMLDescription getParserDescription() {\n return PersistentResourceXMLDescription.builder(ElytronExtension.SUBSYSTEM_PATH, getNameSpace())\n .addAttribute(ElytronDefinition.DEFAULT_AUTHENTICATION_CONTEXT)\n .addAttribute(ElytronDefinition.INITIAL_PROVIDERS)\n .addAttribute(ElytronDefinition.FINAL_PROVIDERS)\n .addAttribute(ElytronDefinition.DISALLOWED_PROVIDERS)\n .addAttribute(ElytronDefinition.SECURITY_PROPERTIES, new AttributeParsers.PropertiesParser(null, SECURITY_PROPERTY, true), new AttributeMarshallers.PropertiesAttributeMarshaller(null, SECURITY_PROPERTY, true))\n .addChild(getAuthenticationClientParser())\n .addChild(getProviderParser())\n .addChild(getAuditLoggingParser())\n .addChild(getDomainParser())\n .addChild(getRealmParser())\n .addChild(getCredentialSecurityFactoryParser())\n .addChild(getMapperParser())\n .addChild(getHttpParser())\n .addChild(getSaslParser())\n .addChild(getTlsParser())\n .addChild(decorator(CREDENTIAL_STORES).addChild(new CredentialStoreParser().parser))\n .addChild(getDirContextParser())\n .addChild(getPolicyParser())\n .build();\n }" ]
[ "public static void acceptsUrlMultiple(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), \"coordinator bootstrap urls\")\n .withRequiredArg()\n .describedAs(\"url-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }", "public static String groupFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null;\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 }", "public static final BigInteger printTimeUnit(TimeUnit value)\n {\n return (BigInteger.valueOf(value == null ? TimeUnit.DAYS.getValue() + 1 : value.getValue() + 1));\n }", "public static int findLastIndexOf(Object self, int startIndex, Closure closure) {\n int result = -1;\n int i = 0;\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); i++) {\n Object value = iter.next();\n if (i < startIndex) {\n continue;\n }\n if (bcw.call(value)) {\n result = i;\n }\n }\n return result;\n }", "private WaveformPreview requestPreviewInternal(final DataReference trackReference, final boolean failIfPassive) {\n\n // First check if we are using cached data for this slot\n MetadataCache cache = MetadataFinder.getInstance().getMetadataCache(SlotReference.getSlotReference(trackReference));\n if (cache != null) {\n return cache.getWaveformPreview(null, trackReference);\n }\n\n // Then see if any registered metadata providers can offer it for us.\n final MediaDetails sourceDetails = MetadataFinder.getInstance().getMediaDetailsFor(trackReference.getSlotReference());\n if (sourceDetails != null) {\n final WaveformPreview provided = MetadataFinder.getInstance().allMetadataProviders.getWaveformPreview(sourceDetails, trackReference);\n if (provided != null) {\n return provided;\n }\n }\n\n // At this point, unless we are allowed to actively request the data, we are done. We can always actively\n // request tracks from rekordbox.\n if (MetadataFinder.getInstance().isPassive() && failIfPassive && trackReference.slot != CdjStatus.TrackSourceSlot.COLLECTION) {\n return null;\n }\n\n // We have to actually request the preview using the dbserver protocol.\n ConnectionManager.ClientTask<WaveformPreview> task = new ConnectionManager.ClientTask<WaveformPreview>() {\n @Override\n public WaveformPreview useClient(Client client) throws Exception {\n return getWaveformPreview(trackReference.rekordboxId, SlotReference.getSlotReference(trackReference), client);\n }\n };\n\n try {\n return ConnectionManager.getInstance().invokeWithClientSession(trackReference.player, task, \"requesting waveform preview\");\n } catch (Exception e) {\n logger.error(\"Problem requesting waveform preview, returning null\", e);\n }\n return null;\n }", "@JmxGetter(name = \"lastSwapped\", description = \"Time in milliseconds since the store was swapped\")\n public long getLastSwapped() {\n long timeSinceLastSwap = System.currentTimeMillis() - lastSwapped;\n return timeSinceLastSwap > 0 ? timeSinceLastSwap : 0;\n }", "public Scale get(final int index, final DistanceUnit unit) {\n return new Scale(this.scaleDenominators[index], unit, PDF_DPI);\n }", "public InputStream getInstance(DirectoryEntry directory, String name) throws IOException\n {\n DocumentEntry entry = (DocumentEntry) directory.getEntry(name);\n InputStream stream;\n if (m_encrypted)\n {\n stream = new EncryptedDocumentInputStream(entry, m_encryptionCode);\n }\n else\n {\n stream = new DocumentInputStream(entry);\n }\n\n return stream;\n }" ]
Obtains a local date in Pax calendar system from the era, year-of-era and day-of-year fields. @param era the Pax era, not null @param yearOfEra the year-of-era @param dayOfYear the day-of-year @return the Pax local date, not null @throws DateTimeException if unable to create the date @throws ClassCastException if the {@code era} is not a {@code PaxEra}
[ "@Override\n public PaxDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }" ]
[ "public ItemRequest<ProjectStatus> createInProject(String project) {\n\n String path = String.format(\"/projects/%s/project_statuses\", project);\n return new ItemRequest<ProjectStatus>(this, ProjectStatus.class, path, \"POST\");\n }", "public void setOfflineState(boolean setToOffline) {\n // acquire write lock\n writeLock.lock();\n try {\n String currentState = ByteUtils.getString(get(SERVER_STATE_KEY, null).get(0).getValue(),\n \"UTF-8\");\n if(setToOffline) {\n // from NORMAL_SERVER to OFFLINE_SERVER\n if(currentState.equals(VoldemortState.NORMAL_SERVER.toString())) {\n put(SERVER_STATE_KEY, VoldemortState.OFFLINE_SERVER);\n initCache(SERVER_STATE_KEY);\n put(SLOP_STREAMING_ENABLED_KEY, false);\n initCache(SLOP_STREAMING_ENABLED_KEY);\n put(PARTITION_STREAMING_ENABLED_KEY, false);\n initCache(PARTITION_STREAMING_ENABLED_KEY);\n put(READONLY_FETCH_ENABLED_KEY, false);\n initCache(READONLY_FETCH_ENABLED_KEY);\n } else if(currentState.equals(VoldemortState.OFFLINE_SERVER.toString())) {\n logger.warn(\"Already in OFFLINE_SERVER state.\");\n return;\n } else {\n logger.error(\"Cannot enter OFFLINE_SERVER state from \" + currentState);\n throw new VoldemortException(\"Cannot enter OFFLINE_SERVER state from \"\n + currentState);\n }\n } else {\n // from OFFLINE_SERVER to NORMAL_SERVER\n if(currentState.equals(VoldemortState.NORMAL_SERVER.toString())) {\n logger.warn(\"Already in NORMAL_SERVER state.\");\n return;\n } else if(currentState.equals(VoldemortState.OFFLINE_SERVER.toString())) {\n put(SERVER_STATE_KEY, VoldemortState.NORMAL_SERVER);\n initCache(SERVER_STATE_KEY);\n put(SLOP_STREAMING_ENABLED_KEY, true);\n initCache(SLOP_STREAMING_ENABLED_KEY);\n put(PARTITION_STREAMING_ENABLED_KEY, true);\n initCache(PARTITION_STREAMING_ENABLED_KEY);\n put(READONLY_FETCH_ENABLED_KEY, true);\n initCache(READONLY_FETCH_ENABLED_KEY);\n init();\n initNodeId(getNodeIdNoLock());\n } else {\n logger.error(\"Cannot enter NORMAL_SERVER state from \" + currentState);\n throw new VoldemortException(\"Cannot enter NORMAL_SERVER state from \"\n + currentState);\n }\n }\n } finally {\n writeLock.unlock();\n }\n }", "public static <T> T assertNull(T value, String message) {\n if (value != null)\n throw new IllegalStateException(message);\n return value;\n }", "protected void setProperty(String propertyName, JavascriptObject propertyValue) {\n jsObject.setMember(propertyName, propertyValue.getJSObject());\n }", "private void cullDisabledPaths() throws Exception {\n\n ArrayList<EndpointOverride> removePaths = new ArrayList<EndpointOverride>();\n RequestInformation requestInfo = requestInformation.get();\n for (EndpointOverride selectedPath : requestInfo.selectedResponsePaths) {\n\n // check repeat count on selectedPath\n // -1 is unlimited\n if (selectedPath != null && selectedPath.getRepeatNumber() == 0) {\n // skip\n removePaths.add(selectedPath);\n } else if (selectedPath != null && selectedPath.getRepeatNumber() != -1) {\n // need to decrement the #\n selectedPath.updateRepeatNumber(selectedPath.getRepeatNumber() - 1);\n }\n }\n\n // remove paths if we need to\n for (EndpointOverride removePath : removePaths) {\n requestInfo.selectedResponsePaths.remove(removePath);\n }\n }", "public final void removeDirectory(final File directory) {\n try {\n FileUtils.deleteDirectory(directory);\n } catch (IOException e) {\n LOGGER.error(\"Unable to delete directory '{}'\", directory);\n }\n }", "public boolean hasUppercaseVariations(int base, boolean lowerOnly) {\n\t\tif(base > 10) {\n\t\t\tint count = getSegmentCount();\n\t\t\tfor(int i = 0; i < count; i++) {\n\t\t\t\tIPv6AddressSegment seg = getSegment(i);\n\t\t\t\tif(seg.hasUppercaseVariations(base, lowerOnly)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public static DoubleMatrix expm(DoubleMatrix A) {\n // constants for pade approximation\n final double c0 = 1.0;\n final double c1 = 0.5;\n final double c2 = 0.12;\n final double c3 = 0.01833333333333333;\n final double c4 = 0.0019927536231884053;\n final double c5 = 1.630434782608695E-4;\n final double c6 = 1.0351966873706E-5;\n final double c7 = 5.175983436853E-7;\n final double c8 = 2.0431513566525E-8;\n final double c9 = 6.306022705717593E-10;\n final double c10 = 1.4837700484041396E-11;\n final double c11 = 2.5291534915979653E-13;\n final double c12 = 2.8101705462199615E-15;\n final double c13 = 1.5440497506703084E-17;\n\n int j = Math.max(0, 1 + (int) Math.floor(Math.log(A.normmax()) / Math.log(2)));\n DoubleMatrix As = A.div((double) Math.pow(2, j)); // scaled version of A\n int n = A.getRows();\n\n // calculate D and N using special Horner techniques\n DoubleMatrix As_2 = As.mmul(As);\n DoubleMatrix As_4 = As_2.mmul(As_2);\n DoubleMatrix As_6 = As_4.mmul(As_2);\n // U = c0*I + c2*A^2 + c4*A^4 + (c6*I + c8*A^2 + c10*A^4 + c12*A^6)*A^6\n DoubleMatrix U = DoubleMatrix.eye(n).muli(c0).addi(As_2.mul(c2)).addi(As_4.mul(c4)).addi(\n DoubleMatrix.eye(n).muli(c6).addi(As_2.mul(c8)).addi(As_4.mul(c10)).addi(As_6.mul(c12)).mmuli(As_6));\n // V = c1*I + c3*A^2 + c5*A^4 + (c7*I + c9*A^2 + c11*A^4 + c13*A^6)*A^6\n DoubleMatrix V = DoubleMatrix.eye(n).muli(c1).addi(As_2.mul(c3)).addi(As_4.mul(c5)).addi(\n DoubleMatrix.eye(n).muli(c7).addi(As_2.mul(c9)).addi(As_4.mul(c11)).addi(As_6.mul(c13)).mmuli(As_6));\n\n DoubleMatrix AV = As.mmuli(V);\n DoubleMatrix N = U.add(AV);\n DoubleMatrix D = U.subi(AV);\n\n // solve DF = N for F\n DoubleMatrix F = Solve.solve(D, N);\n\n // now square j times\n for (int k = 0; k < j; k++) {\n F.mmuli(F);\n }\n\n return F;\n }", "private void checkPrimaryKey(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) &&\r\n classDef.getPrimaryKeys().isEmpty())\r\n {\r\n LogHelper.warn(true,\r\n getClass(),\r\n \"checkPrimaryKey\",\r\n \"The class \"+classDef.getName()+\" has no primary key\");\r\n }\r\n }" ]
Detects if the current browser is a BlackBerry device AND has a more capable recent browser. Excludes the Playbook. Examples, Storm, Bold, Tour, Curve2 Excludes the new BlackBerry OS 6 and 7 browser!! @return detection of a Blackberry device with a better browser
[ "public boolean detectBlackBerryHigh() {\r\n\r\n //Disambiguate for BlackBerry OS 6 or 7 (WebKit) browser\r\n if (detectBlackBerryWebKit()) {\r\n return false;\r\n }\r\n if (detectBlackBerry()) {\r\n if (detectBlackBerryTouch()\r\n || (userAgent.indexOf(deviceBBBold) != -1)\r\n || (userAgent.indexOf(deviceBBTour) != -1)\r\n || (userAgent.indexOf(deviceBBCurve) != -1)) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n } else {\r\n return false;\r\n }\r\n }" ]
[ "public void onDrawerOpened(View drawerView) {\n super.onDrawerOpened(drawerView);\n if (listener != null) listener.onDrawerClosed(drawerView);\n }", "private int[] getCompressIndexAndCount(CompressOptions options, boolean createMixed) {\n\t\tif(options != null) {\n\t\t\tCompressionChoiceOptions rangeSelection = options.rangeSelection;\n\t\t\tRangeList compressibleSegs = rangeSelection.compressHost() ? getZeroRangeSegments() : getZeroSegments();\n\t\t\tint maxIndex = -1, maxCount = 0;\n\t\t\tint segmentCount = getSegmentCount();\n\t\t\t\n\t\t\tboolean compressMixed = createMixed && options.compressMixedOptions.compressMixed(this);\n\t\t\tboolean preferHost = (rangeSelection == CompressOptions.CompressionChoiceOptions.HOST_PREFERRED);\n\t\t\tboolean preferMixed = createMixed && (rangeSelection == CompressOptions.CompressionChoiceOptions.MIXED_PREFERRED);\n\t\t\tfor(int i = compressibleSegs.size() - 1; i >= 0 ; i--) {\n\t\t\t\tRange range = compressibleSegs.getRange(i);\n\t\t\t\tint index = range.index;\n\t\t\t\tint count = range.length;\n\t\t\t\tif(createMixed) {\n\t\t\t\t\t//so here we shorten the range to exclude the mixed part if necessary\n\t\t\t\t\tint mixedIndex = IPv6Address.MIXED_ORIGINAL_SEGMENT_COUNT - addressSegmentIndex;\n\t\t\t\t\tif(!compressMixed ||\n\t\t\t\t\t\t\tindex > mixedIndex || index + count < segmentCount) { //range does not include entire mixed part. We never compress only part of a mixed part.\n\t\t\t\t\t\t//the compressible range must stop at the mixed part\n\t\t\t\t\t\tcount = Math.min(count, mixedIndex - index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//select this range if is the longest\n\t\t\t\tif(count > 0 && count >= maxCount && (options.compressSingle || count > 1)) {\n\t\t\t\t\tmaxIndex = index;\n\t\t\t\t\tmaxCount = count;\n\t\t\t\t}\n\t\t\t\tif(preferHost && isPrefixed() &&\n\t\t\t\t\t\t((index + count) * IPv6Address.BITS_PER_SEGMENT) > getNetworkPrefixLength()) { //this range contains the host\n\t\t\t\t\t//Since we are going backwards, this means we select as the maximum any zero segment that includes the host\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(preferMixed && index + count >= segmentCount) { //this range contains the mixed section\n\t\t\t\t\t//Since we are going backwards, this means we select to compress the mixed segment\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(maxIndex >= 0) {\n\t\t\t\treturn new int[] {maxIndex, maxCount};\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "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 }", "private void cleanupLogs() throws IOException {\n logger.trace(\"Beginning log cleanup...\");\n int total = 0;\n Iterator<Log> iter = getLogIterator();\n long startMs = System.currentTimeMillis();\n while (iter.hasNext()) {\n Log log = iter.next();\n total += cleanupExpiredSegments(log) + cleanupSegmentsToMaintainSize(log);\n }\n if (total > 0) {\n logger.warn(\"Log cleanup completed. \" + total + \" files deleted in \" + (System.currentTimeMillis() - startMs) / 1000 + \" seconds\");\n } else {\n logger.trace(\"Log cleanup completed. \" + total + \" files deleted in \" + (System.currentTimeMillis() - startMs) / 1000 + \" seconds\");\n }\n }", "public void storeIfNew(final DbArtifact fromClient) {\n final DbArtifact existing = repositoryHandler.getArtifact(fromClient.getGavc());\n\n if(existing != null){\n existing.setLicenses(fromClient.getLicenses());\n store(existing);\n }\n\n if(existing == null){\n\t store(fromClient);\n }\n }", "public static boolean classNodeImplementsType(ClassNode node, Class target) {\r\n ClassNode targetNode = ClassHelper.make(target);\r\n if (node.implementsInterface(targetNode)) {\r\n return true;\r\n }\r\n if (node.isDerivedFrom(targetNode)) {\r\n return true;\r\n }\r\n if (node.getName().equals(target.getName())) {\r\n return true;\r\n }\r\n if (node.getName().equals(target.getSimpleName())) {\r\n return true;\r\n }\r\n if (node.getSuperClass() != null && node.getSuperClass().getName().equals(target.getName())) {\r\n return true;\r\n }\r\n if (node.getSuperClass() != null && node.getSuperClass().getName().equals(target.getSimpleName())) {\r\n return true;\r\n }\r\n if (node.getInterfaces() != null) {\r\n for (ClassNode declaredInterface : node.getInterfaces()) {\r\n if (classNodeImplementsType(declaredInterface, target)) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\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 static String[] removeDuplicateStrings(String[] array) {\n if (isEmpty(array)) {\n return array;\n }\n Set<String> set = new TreeSet<String>();\n Collections.addAll(set, array);\n return toStringArray(set);\n }", "public static <T> int createTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig)\n\t\t\tthrows SQLException {\n\t\tDao<T, ?> dao = DaoManager.createDao(connectionSource, tableConfig);\n\t\treturn doCreateTable(dao, false);\n\t}" ]
Gets the default options to be passed when no custom properties are given. @return properties with formatter options
[ "@Nonnull\n\tprivate static Properties findDefaultProperties() {\n\t\tfinal InputStream in = SourceCodeFormatter.class.getClassLoader().getResourceAsStream(DEFAULT_PROPERTIES_PATH);\n\t\tfinal Properties p = new Properties();\n\t\ttry {\n\t\t\tp.load(in);\n\t\t} catch (final IOException e) {\n\t\t\tthrow new RuntimeException(String.format(\"Can not load resource %s\", DEFAULT_PROPERTIES_PATH));\n\t\t}\n\t\treturn p;\n\t}" ]
[ "private void showGlobalContextActionBar() {\n ActionBar actionBar = getActionBar();\n actionBar.setDisplayShowTitleEnabled(true);\n actionBar.setTitle(R.string.app_name);\n }", "public static void writeDocumentToFile(Document document,\n String filePathname, String method, int indent)\n throws TransformerException, IOException {\n\n Transformer transformer = TransformerFactory.newInstance()\n .newTransformer();\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, \"no\");\n transformer.setOutputProperty(OutputKeys.METHOD, method);\n\n transformer.transform(new DOMSource(document), new StreamResult(\n new FileOutputStream(filePathname)));\n }", "private boolean absoluteBasic(int row)\r\n {\r\n boolean retval = false;\r\n \r\n if (row > m_current_row)\r\n {\r\n try\r\n {\r\n while (m_current_row < row && getRsAndStmt().m_rs.next())\r\n {\r\n m_current_row++;\r\n }\r\n if (m_current_row == row)\r\n {\r\n retval = true;\r\n }\r\n else\r\n {\r\n setHasCalledCheck(true);\r\n setHasNext(false);\r\n retval = false;\r\n autoReleaseDbResources();\r\n }\r\n }\r\n catch (Exception ex)\r\n {\r\n setHasCalledCheck(true);\r\n setHasNext(false);\r\n retval = false;\r\n }\r\n }\r\n else\r\n {\r\n logger.info(\"Your driver does not support advanced JDBC Functionality, \" +\r\n \"you cannot call absolute() with a position < current\");\r\n }\r\n return retval;\r\n }", "@SuppressWarnings(\"SameParameterValue\")\n private void sendField(Field field) throws IOException {\n if (isConnected()) {\n try {\n field.write(channel);\n } catch (IOException e) {\n logger.warn(\"Problem trying to write field to dbserver, closing connection\", e);\n close();\n throw e;\n }\n return;\n }\n throw new IOException(\"sendField() called after dbserver connection was closed\");\n }", "public static vlan get(nitro_service service, Long id) throws Exception{\n\t\tvlan obj = new vlan();\n\t\tobj.set_id(id);\n\t\tvlan response = (vlan) obj.get_resource(service);\n\t\treturn response;\n\t}", "protected void runStatements(Reader reader, PrintStream out)\n throws IOException {\n log.debug(\"runStatements()\");\n StringBuilder txt = new StringBuilder();\n String line = \"\";\n BufferedReader in = new BufferedReader(reader);\n\n while ((line = in.readLine()) != null) {\n line = getProject().replaceProperties(line);\n if (line.indexOf(\"--\") >= 0) {\n txt.append(\"\\n\");\n }\n }\n // Catch any statements not followed by ;\n if (!txt.toString().equals(\"\")) {\n execGroovy(txt.toString(), out);\n }\n }", "public static BoxConfig readFrom(Reader reader) throws IOException {\n JsonObject config = JsonObject.readFrom(reader);\n JsonObject settings = (JsonObject) config.get(\"boxAppSettings\");\n String clientId = settings.get(\"clientID\").asString();\n String clientSecret = settings.get(\"clientSecret\").asString();\n JsonObject appAuth = (JsonObject) settings.get(\"appAuth\");\n String publicKeyId = appAuth.get(\"publicKeyID\").asString();\n String privateKey = appAuth.get(\"privateKey\").asString();\n String passphrase = appAuth.get(\"passphrase\").asString();\n String enterpriseId = config.get(\"enterpriseID\").asString();\n return new BoxConfig(clientId, clientSecret, enterpriseId, publicKeyId, privateKey, passphrase);\n }", "public static base_responses add(nitro_service client, tmtrafficaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\ttmtrafficaction addresources[] = new tmtrafficaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new tmtrafficaction();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].apptimeout = resources[i].apptimeout;\n\t\t\t\taddresources[i].sso = resources[i].sso;\n\t\t\t\taddresources[i].formssoaction = resources[i].formssoaction;\n\t\t\t\taddresources[i].persistentcookie = resources[i].persistentcookie;\n\t\t\t\taddresources[i].initiatelogout = resources[i].initiatelogout;\n\t\t\t\taddresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\taddresources[i].samlssoprofile = resources[i].samlssoprofile;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection(BoxConfig boxConfig) {\n\n BoxDeveloperEditionAPIConnection connection = getAppEnterpriseConnection(boxConfig.getEnterpriseId(),\n boxConfig.getClientId(), boxConfig.getClientSecret(), boxConfig.getJWTEncryptionPreferences());\n\n return connection;\n }" ]
Check that the parameter array has at least as many elements as it should. @param parameterName The name of the user-supplied parameter that we are validating so that the user can easily find the error in their code. @param actualLength The actual array length @param minimumLength The minimum array length
[ "public static void checkMinimumArrayLength(String parameterName,\n int actualLength, int minimumLength) {\n if (actualLength < minimumLength) {\n throw Exceptions\n .IllegalArgument(\n \"Array %s should have at least %d elements, but it only has %d\",\n parameterName, minimumLength, actualLength);\n }\n }" ]
[ "public static base_response convert(nitro_service client, sslpkcs12 resource) throws Exception {\n\t\tsslpkcs12 convertresource = new sslpkcs12();\n\t\tconvertresource.outfile = resource.outfile;\n\t\tconvertresource.Import = resource.Import;\n\t\tconvertresource.pkcs12file = resource.pkcs12file;\n\t\tconvertresource.des = resource.des;\n\t\tconvertresource.des3 = resource.des3;\n\t\tconvertresource.export = resource.export;\n\t\tconvertresource.certfile = resource.certfile;\n\t\tconvertresource.keyfile = resource.keyfile;\n\t\tconvertresource.password = resource.password;\n\t\tconvertresource.pempassphrase = resource.pempassphrase;\n\t\treturn convertresource.perform_operation(client,\"convert\");\n\t}", "protected void appendTableWithJoins(TableAlias alias, StringBuffer where, StringBuffer buf)\r\n {\r\n int stmtFromPos = 0;\r\n byte joinSyntax = getJoinSyntaxType();\r\n\r\n if (joinSyntax == SQL92_JOIN_SYNTAX)\r\n {\r\n stmtFromPos = buf.length(); // store position of join (by: Terry Dexter)\r\n }\r\n\r\n if (alias == getRoot())\r\n {\r\n // BRJ: also add indirection table to FROM-clause for MtoNQuery \r\n if (getQuery() instanceof MtoNQuery)\r\n {\r\n MtoNQuery mnQuery = (MtoNQuery)m_query; \r\n buf.append(getTableAliasForPath(mnQuery.getIndirectionTable(), null).getTableAndAlias());\r\n buf.append(\", \");\r\n } \r\n buf.append(alias.getTableAndAlias());\r\n }\r\n else if (joinSyntax != SQL92_NOPAREN_JOIN_SYNTAX)\r\n {\r\n buf.append(alias.getTableAndAlias());\r\n }\r\n\r\n if (!alias.hasJoins())\r\n {\r\n return;\r\n }\r\n\r\n for (Iterator it = alias.iterateJoins(); it.hasNext();)\r\n {\r\n Join join = (Join) it.next();\r\n\r\n if (joinSyntax == SQL92_JOIN_SYNTAX)\r\n {\r\n appendJoinSQL92(join, where, buf);\r\n if (it.hasNext())\r\n {\r\n buf.insert(stmtFromPos, \"(\");\r\n buf.append(\")\");\r\n }\r\n }\r\n else if (joinSyntax == SQL92_NOPAREN_JOIN_SYNTAX)\r\n {\r\n appendJoinSQL92NoParen(join, where, buf);\r\n }\r\n else\r\n {\r\n appendJoin(where, buf, join);\r\n }\r\n\r\n }\r\n }", "protected boolean intersect(GVRSceneObject.BoundingVolume bv1, GVRSceneObject.BoundingVolume bv2)\n {\n return (bv1.maxCorner.x >= bv2.minCorner.x) &&\n (bv1.maxCorner.y >= bv2.minCorner.y) &&\n (bv1.maxCorner.z >= bv2.minCorner.z) &&\n (bv1.minCorner.x <= bv2.maxCorner.x) &&\n (bv1.minCorner.y <= bv2.maxCorner.y) &&\n (bv1.minCorner.z <= bv2.maxCorner.z);\n }", "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 }", "private void loadResourceFile(URL configurationResourceUrl, Properties hotRodConfiguration) {\n\t\tif ( configurationResourceUrl != null ) {\n\t\t\ttry ( InputStream openStream = configurationResourceUrl.openStream() ) {\n\t\t\t\thotRodConfiguration.load( openStream );\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\tthrow log.failedLoadingHotRodConfigurationProperties( e );\n\t\t\t}\n\t\t}\n\t}", "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 static boolean isFormatCorrect(String fileName, ReadOnlyStorageFormat format) {\n switch(format) {\n case READONLY_V0:\n case READONLY_V1:\n if(fileName.matches(\"^[\\\\d]+_[\\\\d]+\\\\.(data|index)\")) {\n return true;\n } else {\n return false;\n }\n\n case READONLY_V2:\n if(fileName.matches(\"^[\\\\d]+_[\\\\d]+_[\\\\d]+\\\\.(data|index)\")) {\n return true;\n } else {\n return false;\n }\n\n default:\n throw new VoldemortException(\"Format type not supported\");\n }\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 }", "public static boolean isArray(Type type) {\n return (type instanceof GenericArrayType) || (type instanceof Class<?> && ((Class<?>) type).isArray());\n }" ]
Use this API to fetch authenticationlocalpolicy_authenticationvserver_binding resources of given name .
[ "public static authenticationlocalpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationlocalpolicy_authenticationvserver_binding obj = new authenticationlocalpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationlocalpolicy_authenticationvserver_binding response[] = (authenticationlocalpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "protected void printCenterWithLead(String lead, String format, Object ... args) {\n String text = S.fmt(format, args);\n int len = 80 - lead.length();\n info(S.concat(lead, S.center(text, len)));\n }", "private void doBatchWork(BatchBackend backend) throws InterruptedException {\n\t\tExecutorService executor = Executors.newFixedThreadPool( typesToIndexInParallel, \"BatchIndexingWorkspace\" );\n\t\tfor ( IndexedTypeIdentifier indexedTypeIdentifier : rootIndexedTypes ) {\n\t\t\texecutor.execute( new BatchIndexingWorkspace( gridDialect, searchFactoryImplementor, sessionFactory, indexedTypeIdentifier,\n\t\t\t\t\tcacheMode, endAllSignal, monitor, backend, tenantId ) );\n\t\t}\n\t\texecutor.shutdown();\n\t\tendAllSignal.await(); // waits for the executor to finish\n\t}", "static Map<String, Set<String>> getChildAddresses(final OperationContext context, final PathAddress addr, final ImmutableManagementResourceRegistration registry, Resource resource, final String validChildType) {\n\n Map<String, Set<String>> result = new HashMap<>();\n Predicate<String> validChildTypeFilter = childType -> (validChildType == null) || validChildType.equals(childType);\n\n if (resource != null) {\n for (String childType : registry.getChildNames(PathAddress.EMPTY_ADDRESS)) {\n if (validChildTypeFilter.test(childType)) {\n List<String> list = new ArrayList<>();\n for (String child : resource.getChildrenNames(childType)) {\n if (registry.getSubModel(PathAddress.pathAddress(PathElement.pathElement(childType, child))) != null) {\n list.add(child);\n }\n }\n result.put(childType, new LinkedHashSet<>(list));\n }\n }\n }\n\n Set<PathElement> paths = registry.getChildAddresses(PathAddress.EMPTY_ADDRESS);\n for (PathElement path : paths) {\n String childType = path.getKey();\n if (validChildTypeFilter.test(childType)) {\n Set<String> children = result.get(childType);\n if (children == null) {\n // WFLY-3306 Ensure we have an entry for any valid child type\n children = new LinkedHashSet<>();\n result.put(childType, children);\n }\n ImmutableManagementResourceRegistration childRegistration = registry.getSubModel(PathAddress.pathAddress(path));\n if (childRegistration != null) {\n AliasEntry aliasEntry = childRegistration.getAliasEntry();\n if (aliasEntry != null) {\n PathAddress childAddr = addr.append(path);\n PathAddress target = aliasEntry.convertToTargetAddress(childAddr, AliasContext.create(childAddr, context));\n assert !childAddr.equals(target) : \"Alias was not translated\";\n PathAddress targetParent = target.getParent();\n Resource parentResource = context.readResourceFromRoot(targetParent, false);\n if (parentResource != null) {\n PathElement targetElement = target.getLastElement();\n if (targetElement.isWildcard()) {\n children.addAll(parentResource.getChildrenNames(targetElement.getKey()));\n } else if (parentResource.hasChild(targetElement)) {\n children.add(path.getValue());\n }\n }\n }\n if (!path.isWildcard() && childRegistration.isRemote()) {\n children.add(path.getValue());\n }\n }\n }\n }\n\n return result;\n }", "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 <T> void cleanNullReferencesAll() {\n\t\tfor (Map<Object, Reference<Object>> objectMap : classMaps.values()) {\n\t\t\tcleanMap(objectMap);\n\t\t}\n\t}", "private synchronized HostServerGroupEffect getMappableDomainEffect(PathAddress address, String key,\n Map<String, Set<String>> map, Resource root) {\n if (requiresMapping) {\n map(root);\n requiresMapping = false;\n }\n Set<String> mapped = map.get(key);\n return mapped != null ? HostServerGroupEffect.forDomain(address, mapped)\n : HostServerGroupEffect.forUnassignedDomain(address);\n }", "public static SpinXmlElement XML(Object input) {\n return SpinFactory.INSTANCE.createSpin(input, DataFormats.xml());\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 }", "public static base_responses unset(nitro_service client, String sitename[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (sitename != null && sitename.length > 0) {\n\t\t\tgslbsite unsetresources[] = new gslbsite[sitename.length];\n\t\t\tfor (int i=0;i<sitename.length;i++){\n\t\t\t\tunsetresources[i] = new gslbsite();\n\t\t\t\tunsetresources[i].sitename = sitename[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}" ]
Applies the &gt; operator to each element in A. Results are stored in a boolean matrix. @param A Input matrx @param value value each element is compared against @param output (Optional) Storage for results. Can be null. Is reshaped. @return Boolean matrix with results
[ "public static BMatrixRMaj elementLessThan(DMatrixRMaj A , double value , BMatrixRMaj output )\n {\n if( output == null ) {\n output = new BMatrixRMaj(A.numRows,A.numCols);\n }\n\n output.reshape(A.numRows, A.numCols);\n\n int N = A.getNumElements();\n\n for (int i = 0; i < N; i++) {\n output.data[i] = A.data[i] < value;\n }\n\n return output;\n }" ]
[ "public Collection getReaders(Object obj)\r\n\t{\r\n\t\tCollection result = null;\r\n try\r\n {\r\n Identity oid = new Identity(obj, getBroker());\r\n byte selector = (byte) 'r';\r\n byte[] requestBarr = buildRequestArray(oid, selector);\r\n \r\n HttpURLConnection conn = getHttpUrlConnection();\r\n \r\n //post request\r\n BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());\r\n out.write(requestBarr,0,requestBarr.length);\r\n out.flush();\t\t\r\n \r\n // read result from \r\n InputStream in = conn.getInputStream();\r\n ObjectInputStream ois = new ObjectInputStream(in);\r\n result = (Collection) ois.readObject();\r\n \r\n // cleanup\r\n ois.close();\r\n out.close();\r\n conn.disconnect();\t\t\r\n }\r\n catch (Throwable t)\r\n {\r\n throw new PersistenceBrokerException(t);\r\n }\r\n return result;\r\n\t}", "public static float calculateMaxTextHeight(Paint _Paint, String _Text) {\n Rect height = new Rect();\n String text = _Text == null ? \"MgHITasger\" : _Text;\n _Paint.getTextBounds(text, 0, text.length(), height);\n return height.height();\n }", "public static String paramMapToString(final Map<String, String[]> parameters) {\n\n final StringBuffer result = new StringBuffer();\n for (final String key : parameters.keySet()) {\n String[] values = parameters.get(key);\n if (null == values) {\n result.append(key).append('&');\n } else {\n for (final String value : parameters.get(key)) {\n result.append(key).append('=').append(CmsEncoder.encode(value)).append('&');\n }\n }\n }\n // remove last '&'\n if (result.length() > 0) {\n result.setLength(result.length() - 1);\n }\n return result.toString();\n }", "public static void main(String[] args) {\n String modelFile = \"\";\n String outputFile = \"\";\n int numberOfRows = 0;\n try {\n modelFile = args[0];\n outputFile = args[1];\n numberOfRows = Integer.valueOf(args[2]);\n } catch (IndexOutOfBoundsException | NumberFormatException e) {\n System.out.println(\"ERROR! Invalid command line arguments, expecting: <scxml model file> \"\n + \"<desired csv output file> <desired number of output rows>\");\n return;\n }\n\n FileInputStream model = null;\n try {\n model = new FileInputStream(modelFile);\n } catch (FileNotFoundException e) {\n System.out.println(\"ERROR! Model file not found\");\n return;\n }\n\n SCXMLEngine engine = new SCXMLEngine();\n engine.setModelByInputFileStream(model);\n engine.setBootstrapMin(5);\n\n DataConsumer consumer = new DataConsumer();\n CSVFileWriter writer;\n try {\n writer = new CSVFileWriter(outputFile);\n } catch (IOException e) {\n System.out.println(\"ERROR! Can not write to output csv file\");\n return;\n }\n consumer.addDataWriter(writer);\n\n DefaultDistributor dist = new DefaultDistributor();\n dist.setThreadCount(5);\n dist.setMaxNumberOfLines(numberOfRows);\n dist.setDataConsumer(consumer);\n\n engine.process(dist);\n writer.closeCSVFile();\n\n System.out.println(\"COMPLETE!\");\n }", "public Object convertJavaFieldToSqlArgValue(Object fieldVal) throws SQLException {\n\t\t/*\n\t\t * Limitation here. Some people may want to override the null with their own value in the converter but we\n\t\t * currently don't allow that. Specifying a default value I guess is a better mechanism.\n\t\t */\n\t\tif (fieldVal == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn fieldConverter.javaToSqlArg(this, fieldVal);\n\t\t}\n\t}", "public static void calculateLegendInformation(List<? extends BaseModel> _Models, float _StartX, float _EndX, Paint _Paint) {\n float textMargin = Utils.dpToPx(10.f);\n float lastX = _StartX;\n\n // calculate the legend label positions and check if there is enough space to display the label,\n // if not the label will not be shown\n for (BaseModel model : _Models) {\n if (!model.isIgnore()) {\n Rect textBounds = new Rect();\n RectF legendBounds = model.getLegendBounds();\n\n _Paint.getTextBounds(model.getLegendLabel(), 0, model.getLegendLabel().length(), textBounds);\n model.setTextBounds(textBounds);\n\n float centerX = legendBounds.centerX();\n float centeredTextPos = centerX - (textBounds.width() / 2);\n float textStartPos = centeredTextPos - textMargin;\n\n // check if the text is too big to fit on the screen\n if (centeredTextPos + textBounds.width() > _EndX - textMargin) {\n model.setShowLabel(false);\n } else {\n // check if the current legend label overrides the label before\n // if the label overrides the label before, the current label will not be shown.\n // If not the label will be shown and the label position is calculated\n if (textStartPos < lastX) {\n if (lastX + textMargin < legendBounds.left) {\n model.setLegendLabelPosition((int) (lastX + textMargin));\n model.setShowLabel(true);\n lastX = lastX + textMargin + textBounds.width();\n } else {\n model.setShowLabel(false);\n }\n } else {\n model.setShowLabel(true);\n model.setLegendLabelPosition((int) centeredTextPos);\n lastX = centerX + (textBounds.width() / 2);\n }\n }\n }\n }\n\n }", "public static DMatrixRMaj nullspaceSVD( DMatrixRMaj A , int totalSingular ) {\n SolveNullSpace<DMatrixRMaj> solver = new SolveNullSpaceSvd_DDRM();\n\n DMatrixRMaj nullspace = new DMatrixRMaj(1,1);\n\n if( !solver.process(A,totalSingular,nullspace))\n throw new RuntimeException(\"Solver failed. try SVD based method instead?\");\n\n return nullspace;\n }", "public static Path getRootFolderForSource(Path sourceFilePath, String packageName)\n {\n if (packageName == null || packageName.trim().isEmpty())\n {\n return sourceFilePath.getParent();\n }\n String[] packageNameComponents = packageName.split(\"\\\\.\");\n Path currentPath = sourceFilePath.getParent();\n for (int i = packageNameComponents.length; i > 0; i--)\n {\n String packageComponent = packageNameComponents[i - 1];\n if (!StringUtils.equals(packageComponent, currentPath.getFileName().toString()))\n {\n return null;\n }\n currentPath = currentPath.getParent();\n }\n return currentPath;\n }", "public List<EnabledEndpoint> getEnabledEndpoints(int pathId, String clientUUID, String[] filters) throws Exception {\n ArrayList<EnabledEndpoint> enabledOverrides = new ArrayList<EnabledEndpoint>();\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \"=?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \"=?\" +\n \" ORDER BY \" + Constants.ENABLED_OVERRIDES_PRIORITY\n );\n query.setInt(1, pathId);\n query.setString(2, clientUUID);\n results = query.executeQuery();\n\n while (results.next()) {\n EnabledEndpoint endpoint = this.getPartialEnabledEndpointFromResultset(results);\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n\n // this is an errant entry.. perhaps a method got deleted from a plugin\n // we'll also remove it from the endpoint\n if (m == null) {\n PathOverrideService.getInstance().removeOverride(endpoint.getOverrideId());\n continue;\n }\n\n // check filters and see if any match\n boolean addOverride = false;\n if (filters != null) {\n for (String filter : filters) {\n if (m.getMethodType().endsWith(filter)) {\n addOverride = true;\n break;\n }\n }\n } else {\n // if there are no filters then we assume that the requester wants all enabled overrides\n addOverride = true;\n }\n\n if (addOverride) {\n enabledOverrides.add(endpoint);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n // now go through the ArrayList and get the method for all of the endpoints\n // have to do this so we don't have overlapping SQL queries\n ArrayList<EnabledEndpoint> enabledOverridesWithMethods = new ArrayList<EnabledEndpoint>();\n for (EnabledEndpoint endpoint : enabledOverrides) {\n if (endpoint.getOverrideId() >= 0) {\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n endpoint.setMethodInformation(m);\n }\n enabledOverridesWithMethods.add(endpoint);\n }\n\n return enabledOverridesWithMethods;\n }" ]
Update max. @param n the n @param c the c
[ "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 }" ]
[ "public void clearHandlers() {\r\n\r\n for (Map<String, CmsAttributeHandler> handlers : m_handlers) {\r\n for (CmsAttributeHandler handler : handlers.values()) {\r\n handler.clearHandlers();\r\n }\r\n handlers.clear();\r\n }\r\n m_handlers.clear();\r\n m_handlers.add(new HashMap<String, CmsAttributeHandler>());\r\n m_handlerById.clear();\r\n }", "private boolean isClockwise(Point center, Point a, Point b) {\n double cross = (a.x - center.x) * (b.y - center.y) - (b.x - center.x) * (a.y - center.y);\n return cross > 0;\n }", "public ViewGroup getContentContainer() {\n if (mDragMode == MENU_DRAG_CONTENT) {\n return mContentContainer;\n } else {\n return (ViewGroup) findViewById(android.R.id.content);\n }\n }", "@Override\n\tpublic void writeValue(TimeValue value, Resource resource)\n\t\t\tthrows RDFHandlerException {\n\t\tthis.rdfWriter.writeTripleValueObject(resource, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.WB_TIME_VALUE);\n\n\t\tthis.rdfWriter.writeTripleValueObject(resource, RdfWriter.WB_TIME,\n\t\t\t\tTimeValueConverter.getTimeLiteral(value, this.rdfWriter));\n\n\t\tthis.rdfWriter.writeTripleIntegerObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_PRECISION, value.getPrecision());\n\t\tthis.rdfWriter.writeTripleIntegerObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_TIMEZONE,\n\t\t\t\tvalue.getTimezoneOffset());\n\t\tthis.rdfWriter.writeTripleUriObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_CALENDAR_MODEL,\n\t\t\t\tvalue.getPreferredCalendarModel());\n\t}", "static void processRoot(final File root, final ProcessedLayers layers, final LayerPathSetter setter) throws IOException {\n final LayersConfig layersConfig = LayersConfig.getLayersConfig(root);\n // Process layers\n final File layersDir = new File(root, layersConfig.getLayersPath());\n if (!layersDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationNoLayersConfigFound(layersDir.getAbsolutePath());\n }\n // else this isn't a root that has layers and add-ons\n } else {\n // check for a valid layer configuration\n for (final String layer : layersConfig.getLayers()) {\n File layerDir = new File(layersDir, layer);\n if (!layerDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationMissingLayer(layer, layersDir.getAbsolutePath());\n }\n // else this isn't a standard layers and add-ons structure\n return;\n }\n layers.addLayer(layer, layerDir, setter);\n }\n }\n // Finally process the add-ons\n final File addOnsDir = new File(root, layersConfig.getAddOnsPath());\n final File[] addOnsList = addOnsDir.listFiles();\n if (addOnsList != null) {\n for (final File addOn : addOnsList) {\n layers.addAddOn(addOn.getName(), addOn, setter);\n }\n }\n }", "public static ipset[] get(nitro_service service) throws Exception{\n\t\tipset obj = new ipset();\n\t\tipset[] response = (ipset[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private InputValue getInputValue(FormInput input) {\n\n\t\t/* Get the DOM element from Selenium. */\n\t\tWebElement inputElement = browser.getWebElement(input.getIdentification());\n\n\t\tswitch (input.getType()) {\n\t\t\tcase TEXT:\n\t\t\tcase PASSWORD:\n\t\t\tcase HIDDEN:\n\t\t\tcase SELECT:\n\t\t\tcase TEXTAREA:\n\t\t\t\treturn new InputValue(inputElement.getAttribute(\"value\"));\n\t\t\tcase RADIO:\n\t\t\tcase CHECKBOX:\n\t\t\tdefault:\n\t\t\t\tString value = inputElement.getAttribute(\"value\");\n\t\t\t\tBoolean checked = inputElement.isSelected();\n\t\t\t\treturn new InputValue(value, checked);\n\t\t}\n\n\t}", "@SuppressWarnings(\"unchecked\")\n protected String addPostRunDependent(Creatable<? extends Indexable> creatable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) creatable;\n return this.addPostRunDependent(dependency);\n }", "public static lbvserver_scpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_scpolicy_binding obj = new lbvserver_scpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_scpolicy_binding response[] = (lbvserver_scpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Convert this object to a json object.
[ "public final PJsonObject toJSON() {\n try {\n JSONObject json = new JSONObject();\n for (String key: this.obj.keySet()) {\n Object opt = opt(key);\n if (opt instanceof PYamlObject) {\n opt = ((PYamlObject) opt).toJSON().getInternalObj();\n } else if (opt instanceof PYamlArray) {\n opt = ((PYamlArray) opt).toJSON().getInternalArray();\n }\n json.put(key, opt);\n }\n return new PJsonObject(json, this.getContextName());\n } catch (Throwable e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }" ]
[ "public static boolean setCustomRequestForDefaultClient(String profileName, String pathName, String customData) {\n try {\n return setCustomForDefaultClient(profileName, pathName, false, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "private void registerProxyCreator(Node source,\n BeanDefinitionHolder holder,\n ParserContext context) {\n\n String beanName = holder.getBeanName();\n String proxyName = beanName + \"Proxy\";\n String interceptorName = beanName + \"PerformanceMonitorInterceptor\";\n\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(BeanNameAutoProxyCreator.class);\n\n initializer.addPropertyValue(\"beanNames\", beanName);\n initializer.addPropertyValue(\"interceptorNames\", interceptorName);\n\n BeanDefinitionRegistry registry = context.getRegistry();\n registry.registerBeanDefinition(proxyName, initializer.getBeanDefinition());\n }", "public static MimeMultipart createMultipartWithAttachment(String msg, final byte[] attachment, final String contentType,\r\n final String filename, String description) {\r\n try {\r\n MimeMultipart multiPart = new MimeMultipart();\r\n\r\n MimeBodyPart textPart = new MimeBodyPart();\r\n multiPart.addBodyPart(textPart);\r\n textPart.setText(msg);\r\n\r\n MimeBodyPart binaryPart = new MimeBodyPart();\r\n multiPart.addBodyPart(binaryPart);\r\n\r\n DataSource ds = new DataSource() {\r\n @Override\r\n public InputStream getInputStream() throws IOException {\r\n return new ByteArrayInputStream(attachment);\r\n }\r\n\r\n @Override\r\n public OutputStream getOutputStream() throws IOException {\r\n ByteArrayOutputStream byteStream = new ByteArrayOutputStream();\r\n byteStream.write(attachment);\r\n return byteStream;\r\n }\r\n\r\n @Override\r\n public String getContentType() {\r\n return contentType;\r\n }\r\n\r\n @Override\r\n public String getName() {\r\n return filename;\r\n }\r\n };\r\n binaryPart.setDataHandler(new DataHandler(ds));\r\n binaryPart.setFileName(filename);\r\n binaryPart.setDescription(description);\r\n return multiPart;\r\n } catch (MessagingException e) {\r\n throw new IllegalArgumentException(\"Can not create multipart message with attachment\", e);\r\n }\r\n }", "public synchronized void addMapStats(\n final MapfishMapContext mapContext, final MapAttribute.MapAttributeValues mapValues) {\n this.mapStats.add(new MapStats(mapContext, mapValues));\n }", "public void createResourceFieldMap(Props props)\n {\n byte[] fieldMapData = null;\n for (Integer key : RESOURCE_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData == null)\n {\n populateDefaultData(getDefaultResourceData());\n }\n else\n {\n createFieldMap(fieldMapData);\n }\n }", "public static int getDayAsReadableInt(long time) {\n Calendar cal = calendarThreadLocal.get();\n cal.setTimeInMillis(time);\n return getDayAsReadableInt(cal);\n }", "public void configure(Properties props) throws HibernateException {\r\n\t\ttry{\r\n\t\t\tthis.config = new BoneCPConfig(props);\r\n\r\n\t\t\t// old hibernate config\r\n\t\t\tString url = props.getProperty(CONFIG_CONNECTION_URL);\r\n\t\t\tString username = props.getProperty(CONFIG_CONNECTION_USERNAME);\r\n\t\t\tString password = props.getProperty(CONFIG_CONNECTION_PASSWORD);\r\n\t\t\tString driver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS);\r\n\t\t\tif (url == null){\r\n\t\t\t\turl = props.getProperty(CONFIG_CONNECTION_URL_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (username == null){\r\n\t\t\t\tusername = props.getProperty(CONFIG_CONNECTION_USERNAME_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (password == null){\r\n\t\t\t\tpassword = props.getProperty(CONFIG_CONNECTION_PASSWORD_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (driver == null){\r\n\t\t\t\tdriver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS_ALTERNATE);\r\n\t\t\t}\r\n\r\n\t\t\tif (url != null){\r\n\t\t\t\tthis.config.setJdbcUrl(url);\r\n\t\t\t}\r\n\t\t\tif (username != null){\r\n\t\t\t\tthis.config.setUsername(username);\r\n\t\t\t}\r\n\t\t\tif (password != null){\r\n\t\t\t\tthis.config.setPassword(password);\r\n\t\t\t}\r\n\r\n\r\n\t\t\t// Remember Isolation level\r\n\t\t\tthis.isolation = ConfigurationHelper.getInteger(AvailableSettings.ISOLATION, props);\r\n\t\t\tthis.autocommit = ConfigurationHelper.getBoolean(AvailableSettings.AUTOCOMMIT, props);\r\n\r\n\t\t\tlogger.debug(this.config.toString());\r\n\r\n\t\t\tif (driver != null && !driver.trim().equals(\"\")){\r\n\t\t\t\tloadClass(driver);\r\n\t\t\t}\r\n\t\t\tif (this.config.getConnectionHookClassName() != null){\r\n\t\t\t\tObject hookClass = loadClass(this.config.getConnectionHookClassName()).newInstance();\r\n\t\t\t\tthis.config.setConnectionHook((ConnectionHook) hookClass);\r\n\t\t\t}\r\n\t\t\t// create the connection pool\r\n\t\t\tthis.pool = createPool(this.config);\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new HibernateException(e);\r\n\t\t}\r\n\t}", "public int addServerGroup(String groupName, int profileId) throws Exception {\n int groupId = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_SERVER_GROUPS\n + \"(\" + Constants.GENERIC_NAME + \",\" +\n Constants.GENERIC_PROFILE_ID + \")\"\n + \" VALUES (?, ?);\", PreparedStatement.RETURN_GENERATED_KEYS);\n statement.setString(1, groupName);\n statement.setInt(2, profileId);\n statement.executeUpdate();\n\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n groupId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add group\");\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return groupId;\n }", "private static Map<String, ServerGroupDeploymentPlanResult> buildServerGroupResults(Map<UUID, DeploymentActionResult> deploymentActionResults) {\n Map<String, ServerGroupDeploymentPlanResult> serverGroupResults = new HashMap<String, ServerGroupDeploymentPlanResult>();\n\n for (Map.Entry<UUID, DeploymentActionResult> entry : deploymentActionResults.entrySet()) {\n\n UUID actionId = entry.getKey();\n DeploymentActionResult actionResult = entry.getValue();\n\n Map<String, ServerGroupDeploymentActionResult> actionResultsByServerGroup = actionResult.getResultsByServerGroup();\n for (ServerGroupDeploymentActionResult serverGroupActionResult : actionResultsByServerGroup.values()) {\n String serverGroupName = serverGroupActionResult.getServerGroupName();\n\n ServerGroupDeploymentPlanResultImpl sgdpr = (ServerGroupDeploymentPlanResultImpl) serverGroupResults.get(serverGroupName);\n if (sgdpr == null) {\n sgdpr = new ServerGroupDeploymentPlanResultImpl(serverGroupName);\n serverGroupResults.put(serverGroupName, sgdpr);\n }\n\n for (Map.Entry<String, ServerUpdateResult> serverEntry : serverGroupActionResult.getResultByServer().entrySet()) {\n String serverName = serverEntry.getKey();\n ServerUpdateResult sud = serverEntry.getValue();\n ServerDeploymentPlanResultImpl sdpr = (ServerDeploymentPlanResultImpl) sgdpr.getServerResult(serverName);\n if (sdpr == null) {\n sdpr = new ServerDeploymentPlanResultImpl(serverName);\n sgdpr.storeServerResult(serverName, sdpr);\n }\n sdpr.storeServerUpdateResult(actionId, sud);\n }\n }\n }\n return serverGroupResults;\n }" ]
Processes the most recent dump of the given type using the given dump processor. @see DumpProcessingController#processMostRecentMainDump() @see DumpProcessingController#processAllRecentRevisionDumps() @param dumpContentType the type of dump to process @param dumpFileProcessor the processor to use @deprecated Use {@link #getMostRecentDump(DumpContentType)} and {@link #processDump(MwDumpFile)} instead; method will vanish in WDTK 0.5
[ "@Deprecated\n\tpublic void processMostRecentDump(DumpContentType dumpContentType,\n\t\t\tMwDumpFileProcessor dumpFileProcessor) {\n\t\tMwDumpFile dumpFile = getMostRecentDump(dumpContentType);\n\t\tif (dumpFile != null) {\n\t\t\tprocessDumpFile(dumpFile, dumpFileProcessor);\n\t\t}\n\t}" ]
[ "public CmsContextMenu getContextMenuForItem(Object itemId) {\n\n CmsContextMenu result = null;\n try {\n final Item item = m_container.getItem(itemId);\n Property<?> keyProp = item.getItemProperty(TableProperty.KEY);\n String key = (String)keyProp.getValue();\n if ((null != key) && !key.isEmpty()) {\n loadAllRemainingLocalizations();\n final Map<Locale, String> localesWithEntries = new HashMap<Locale, String>();\n for (Locale l : m_localizations.keySet()) {\n if (l != m_locale) {\n String value = m_localizations.get(l).getProperty(key);\n if ((null != value) && !value.isEmpty()) {\n localesWithEntries.put(l, value);\n }\n }\n }\n if (!localesWithEntries.isEmpty()) {\n result = new CmsContextMenu();\n ContextMenuItem mainItem = result.addItem(\n Messages.get().getBundle(UI.getCurrent().getLocale()).key(\n Messages.GUI_BUNDLE_EDITOR_CONTEXT_COPY_LOCALE_0));\n for (final Locale l : localesWithEntries.keySet()) {\n\n ContextMenuItem menuItem = mainItem.addItem(l.getDisplayName(UI.getCurrent().getLocale()));\n menuItem.addItemClickListener(new ContextMenuItemClickListener() {\n\n public void contextMenuItemClicked(ContextMenuItemClickEvent event) {\n\n item.getItemProperty(TableProperty.TRANSLATION).setValue(localesWithEntries.get(l));\n\n }\n });\n }\n }\n }\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n //TODO: Improve\n }\n return result;\n }", "public static appflowglobal_binding get(nitro_service service) throws Exception{\n\t\tappflowglobal_binding obj = new appflowglobal_binding();\n\t\tappflowglobal_binding response = (appflowglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "String escapeValue(Object value) {\n return HtmlUtils.htmlEscape(value != null ? value.toString() : \"<null>\");\n }", "public Node findEntity(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\tResult result = executionEngine.execute( getFindEntityQuery(), params );\n\t\treturn singleResult( result );\n\t}", "public boolean hasRequiredClientProps() {\n boolean valid = true;\n valid &= verifyStringPropSet(CONNECTION_APPLICATION_NAME_PROP, CLIENT_APPLICATION_NAME_PROP);\n valid &= verifyStringPropSet(ACCUMULO_USER_PROP, CLIENT_ACCUMULO_USER_PROP);\n valid &= verifyStringPropSet(ACCUMULO_PASSWORD_PROP, CLIENT_ACCUMULO_PASSWORD_PROP);\n valid &= verifyStringPropSet(ACCUMULO_INSTANCE_PROP, CLIENT_ACCUMULO_INSTANCE_PROP);\n return valid;\n }", "protected void checkVariableName(GraphRewrite event, EvaluationContext context)\n {\n if (variableName == null)\n {\n setVariableName(Iteration.getPayloadVariableName(event, context));\n }\n }", "public void deleteLicense(final String licName) {\n final DbLicense dbLicense = getLicense(licName);\n\n repoHandler.deleteLicense(dbLicense.getName());\n\n final FiltersHolder filters = new FiltersHolder();\n final LicenseIdFilter licenseIdFilter = new LicenseIdFilter(licName);\n filters.addFilter(licenseIdFilter);\n\n for (final DbArtifact artifact : repoHandler.getArtifacts(filters)) {\n repoHandler.removeLicenseFromArtifact(artifact, licName, this);\n }\n }", "public double nonNormalizedTreeDist(LblTree t1, LblTree t2) {\n\t\tinit(t1, t2);\n\t\tSTR = new int[size1][size2];\n\t\tcomputeOptimalStrategy();\n\t\treturn computeDistUsingStrArray(it1, it2);\n\t}", "@SuppressWarnings(\"unchecked\")\n public <T extends GVRComponent> ArrayList<T> getAllComponents(long type) {\n ArrayList<T> list = new ArrayList<T>();\n GVRComponent component = getComponent(type);\n if (component != null)\n list.add((T) component);\n for (GVRSceneObject child : mChildren) {\n ArrayList<T> temp = child.getAllComponents(type);\n list.addAll(temp);\n }\n return list;\n }" ]
Gets information about a trashed folder that's limited to a list of specified fields. @param folderID the ID of the trashed folder. @param fields the fields to retrieve. @return info about the trashed folder containing only the specified fields.
[ "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 NRShape makeShape(Date from, Date to) {\n UnitNRShape fromShape = tree.toUnitShape(from);\n UnitNRShape toShape = tree.toUnitShape(to);\n return tree.toRangeShape(fromShape, toShape);\n }", "private void forward() {\n\n Set<String> selected = new HashSet<>();\n\n for (CheckBox checkbox : m_componentCheckboxes) {\n CmsSetupComponent component = (CmsSetupComponent)(checkbox.getData());\n if (checkbox.getValue().booleanValue()) {\n selected.add(component.getId());\n }\n }\n String error = null;\n for (String compId : selected) {\n CmsSetupComponent component = m_componentMap.get(compId);\n for (String dep : component.getDependencies()) {\n if (!selected.contains(dep)) {\n error = \"Unfulfilled dependency: The component \"\n + component.getName()\n + \" can not be installed because its dependency \"\n + m_componentMap.get(dep).getName()\n + \" is not selected\";\n break;\n }\n }\n }\n if (error == null) {\n Set<String> modules = new HashSet<>();\n\n for (CmsSetupComponent component : m_componentMap.values()) {\n\n if (selected.contains(component.getId())) {\n\n for (CmsModule module : m_context.getSetupBean().getAvailableModules().values()) {\n if (component.match(module.getName())) {\n modules.add(module.getName());\n }\n }\n }\n }\n List<String> moduleList = new ArrayList<>(modules);\n m_context.getSetupBean().setInstallModules(CmsStringUtil.listAsString(moduleList, \"|\"));\n m_context.stepForward();\n } else {\n CmsSetupErrorDialog.showErrorDialog(error, error);\n }\n }", "void setPatternDefaultValues(Date startDate) {\r\n\r\n if ((m_patternDefaultValues == null) || !Objects.equals(m_patternDefaultValues.getDate(), startDate)) {\r\n m_patternDefaultValues = new PatternDefaultValues(startDate);\r\n }\r\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}", "public static StringTemplateGroup readStringTemplateGroup(InputStream stream) {\n\n try {\n return new StringTemplateGroup(\n new InputStreamReader(stream, \"UTF-8\"),\n DefaultTemplateLexer.class,\n new StringTemplateErrorListener() {\n\n @SuppressWarnings(\"synthetic-access\")\n public void error(String arg0, Throwable arg1) {\n\n LOG.error(arg0 + \": \" + arg1.getMessage(), arg1);\n }\n\n @SuppressWarnings(\"synthetic-access\")\n public void warning(String arg0) {\n\n LOG.warn(arg0);\n\n }\n });\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n return new StringTemplateGroup(\"dummy\");\n }\n }", "public String getShortMessage(Locale locale) {\n\t\tString message;\n\t\tmessage = translate(Integer.toString(exceptionCode), locale);\n\t\tif (message != null && msgParameters != null && msgParameters.length > 0) {\n\t\t\tfor (int i = 0; i < msgParameters.length; i++) {\n\t\t\t\tboolean isIncluded = false;\n\t\t\t\tString needTranslationParam = \"$${\" + i + \"}\";\n\t\t\t\tif (message.contains(needTranslationParam)) {\n\t\t\t\t\tString translation = translate(msgParameters[i], locale);\n\t\t\t\t\tif (null == translation && null != msgParameters[i]) {\n\t\t\t\t\t\ttranslation = msgParameters[i].toString();\n\t\t\t\t\t}\n\t\t\t\t\tif (null == translation) {\n\t\t\t\t\t\ttranslation = \"[null]\";\n\t\t\t\t\t}\n\t\t\t\t\tmessage = message.replace(needTranslationParam, translation);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tString verbatimParam = \"${\" + i + \"}\";\n\t\t\t\tString rs = null == msgParameters[i] ? \"[null]\" : msgParameters[i].toString();\n\t\t\t\tif (message.contains(verbatimParam)) {\n\t\t\t\t\tmessage = message.replace(verbatimParam, rs);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tif (!isIncluded) {\n\t\t\t\t\tmessage = message + \" (\" + rs + \")\"; // NOSONAR replace/contains makes StringBuilder use difficult\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn message;\n\t}", "public DocumentReaderAndWriter<IN> makePlainTextReaderAndWriter() {\r\n String readerClassName = flags.plainTextDocumentReaderAndWriter;\r\n // We set this default here if needed because there may be models\r\n // which don't have the reader flag set\r\n if (readerClassName == null) {\r\n readerClassName = SeqClassifierFlags.DEFAULT_PLAIN_TEXT_READER;\r\n }\r\n DocumentReaderAndWriter<IN> readerAndWriter;\r\n try {\r\n readerAndWriter = ((DocumentReaderAndWriter<IN>) Class.forName(readerClassName).newInstance());\r\n } catch (Exception e) {\r\n throw new RuntimeException(String.format(\"Error loading flags.plainTextDocumentReaderAndWriter: '%s'\", flags.plainTextDocumentReaderAndWriter), e);\r\n }\r\n readerAndWriter.init(flags);\r\n return readerAndWriter;\r\n }", "public static sslcipher_individualcipher_binding[] get(nitro_service service, String ciphergroupname) throws Exception{\n\t\tsslcipher_individualcipher_binding obj = new sslcipher_individualcipher_binding();\n\t\tobj.set_ciphergroupname(ciphergroupname);\n\t\tsslcipher_individualcipher_binding response[] = (sslcipher_individualcipher_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static base_responses add(nitro_service client, nsacl6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsacl6 addresources[] = new nsacl6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new nsacl6();\n\t\t\t\taddresources[i].acl6name = resources[i].acl6name;\n\t\t\t\taddresources[i].acl6action = resources[i].acl6action;\n\t\t\t\taddresources[i].td = resources[i].td;\n\t\t\t\taddresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\taddresources[i].srcipop = resources[i].srcipop;\n\t\t\t\taddresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\taddresources[i].srcport = resources[i].srcport;\n\t\t\t\taddresources[i].srcportop = resources[i].srcportop;\n\t\t\t\taddresources[i].srcportval = resources[i].srcportval;\n\t\t\t\taddresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\taddresources[i].destipop = resources[i].destipop;\n\t\t\t\taddresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\taddresources[i].destport = resources[i].destport;\n\t\t\t\taddresources[i].destportop = resources[i].destportop;\n\t\t\t\taddresources[i].destportval = resources[i].destportval;\n\t\t\t\taddresources[i].ttl = resources[i].ttl;\n\t\t\t\taddresources[i].srcmac = resources[i].srcmac;\n\t\t\t\taddresources[i].protocol = resources[i].protocol;\n\t\t\t\taddresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\taddresources[i].vlan = resources[i].vlan;\n\t\t\t\taddresources[i].Interface = resources[i].Interface;\n\t\t\t\taddresources[i].established = resources[i].established;\n\t\t\t\taddresources[i].icmptype = resources[i].icmptype;\n\t\t\t\taddresources[i].icmpcode = resources[i].icmpcode;\n\t\t\t\taddresources[i].priority = resources[i].priority;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Private function to allow looking for the field recursively up the superclasses. @param clazz @return
[ "private Set<Annotation> getFieldAnnotations(final Class<?> clazz)\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn new LinkedHashSet<Annotation>(asList(clazz.getDeclaredField(propertyName).getAnnotations()));\n\t\t}\n\t\tcatch (final NoSuchFieldException e)\n\t\t{\n\t\t\tif (clazz.getSuperclass() != null)\n\t\t\t{\n\t\t\t\treturn getFieldAnnotations(clazz.getSuperclass());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlogger.debug(\"Cannot find propertyName: {}, declaring class: {}\", propertyName, clazz);\n\t\t\t\treturn new LinkedHashSet<Annotation>(0);\n\t\t\t}\n\t\t}\n\t}" ]
[ "public synchronized void shutdownTaskScheduler(){\n if (scheduler != null && !scheduler.isShutdown()) {\n scheduler.shutdown();\n logger.info(\"shutdowned the task scheduler. No longer accepting new tasks\");\n scheduler = null;\n }\n }", "public 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}", "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 double getSpread(double bondPrice, Curve referenceCurve, AnalyticModel model) {\n\t\tGoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0);\n\t\twhile(search.getAccuracy() > 1E-11 && !search.isDone()) {\n\t\t\tdouble x = search.getNextPoint();\n\t\t\tdouble fx=getValueWithGivenSpreadOverCurve(0.0,referenceCurve,x,model);\n\t\t\tdouble y = (bondPrice-fx)*(bondPrice-fx);\n\n\t\t\tsearch.setValue(y);\n\t\t}\n\t\treturn search.getBestPoint();\n\t}", "public final PJsonArray toJSON() {\n JSONArray jsonArray = new JSONArray();\n final int size = this.array.size();\n for (int i = 0; i < size; i++) {\n final Object o = get(i);\n if (o instanceof PYamlObject) {\n PYamlObject pYamlObject = (PYamlObject) o;\n jsonArray.put(pYamlObject.toJSON().getInternalObj());\n } else if (o instanceof PYamlArray) {\n PYamlArray pYamlArray = (PYamlArray) o;\n jsonArray.put(pYamlArray.toJSON().getInternalArray());\n } else {\n jsonArray.put(o);\n }\n\n }\n return new PJsonArray(null, jsonArray, getContextName());\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 }", "public float getLayoutSize(final Layout.Axis axis) {\n float size = 0;\n for (Layout layout : mLayouts) {\n size = Math.max(size, layout.getSize(axis));\n }\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"getLayoutSize [%s] axis [%s] size [%f]\", getName(), axis, size);\n return size;\n }", "public static String resolveDataSourceTypeFromDialect(String dialect)\n {\n if (StringUtils.contains(dialect, \"Oracle\"))\n {\n return \"Oracle\";\n }\n else if (StringUtils.contains(dialect, \"MySQL\"))\n {\n return \"MySQL\";\n }\n else if (StringUtils.contains(dialect, \"DB2390Dialect\"))\n {\n return \"DB2/390\";\n }\n else if (StringUtils.contains(dialect, \"DB2400Dialect\"))\n {\n return \"DB2/400\";\n }\n else if (StringUtils.contains(dialect, \"DB2\"))\n {\n return \"DB2\";\n }\n else if (StringUtils.contains(dialect, \"Ingres\"))\n {\n return \"Ingres\";\n }\n else if (StringUtils.contains(dialect, \"Derby\"))\n {\n return \"Derby\";\n }\n else if (StringUtils.contains(dialect, \"Pointbase\"))\n {\n return \"Pointbase\";\n }\n else if (StringUtils.contains(dialect, \"Postgres\"))\n {\n return \"Postgres\";\n }\n else if (StringUtils.contains(dialect, \"SQLServer\"))\n {\n return \"SQLServer\";\n }\n else if (StringUtils.contains(dialect, \"Sybase\"))\n {\n return \"Sybase\";\n }\n else if (StringUtils.contains(dialect, \"HSQLDialect\"))\n {\n return \"HyperSQL\";\n }\n else if (StringUtils.contains(dialect, \"H2Dialect\"))\n {\n return \"H2\";\n }\n \n return dialect;\n\n }", "public void leave(String groupId, Boolean deletePhotos) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LEAVE);\r\n parameters.put(\"group_id\", groupId);\r\n parameters.put(\"delete_photos\", deletePhotos);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }" ]
Transforms an input String into HTML using the given Configuration. @param input The String to process. @param configuration The Configuration. @return The processed String. @since 0.7 @see Configuration
[ "public final static String process(final String input, final Configuration configuration)\n {\n try\n {\n return process(new StringReader(input), configuration);\n }\n catch (final IOException e)\n {\n // This _can never_ happen\n return null;\n }\n }" ]
[ "public long addAll(final Map<String, Double> scoredMember) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.zadd(getKey(), scoredMember);\n }\n });\n }", "protected ValueContainer[] getKeyValues(PersistenceBroker broker, ClassDescriptor cld, Identity oid) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getKeyValues(cld, oid);\r\n }", "public boolean forall(PixelPredicate predicate) {\n return Arrays.stream(points()).allMatch(p -> predicate.test(p.x, p.y, pixel(p)));\n }", "public static boolean strictCheckMatchingTags(Collection<String> tags, Set<String> includeTags, Set<String> excludeTags)\n {\n boolean includeTagsEnabled = !includeTags.isEmpty();\n\n for (String tag : tags)\n {\n boolean isIncluded = includeTags.contains(tag);\n boolean isExcluded = excludeTags.contains(tag);\n\n if ((includeTagsEnabled && isIncluded) || (!includeTagsEnabled && !isExcluded))\n {\n return true;\n }\n }\n\n return false;\n }", "public String getHealthMemory() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"Logging JVM Stats\\n\");\n MonitorProvider mp = MonitorProvider.getInstance();\n PerformUsage perf = mp.getJVMMemoryUsage();\n sb.append(perf.toString());\n\n if (perf.memoryUsagePercent >= THRESHOLD_PERCENT) {\n sb.append(\"========= WARNING: MEM USAGE > \" + THRESHOLD_PERCENT\n + \"!!\");\n sb.append(\" !! Live Threads List=============\\n\");\n sb.append(mp.getThreadUsage().toString());\n sb.append(\"========================================\\n\");\n sb.append(\"========================JVM Thread Dump====================\\n\");\n ThreadInfo[] threadDump = mp.getThreadDump();\n for (ThreadInfo threadInfo : threadDump) {\n sb.append(threadInfo.toString() + \"\\n\");\n }\n sb.append(\"===========================================================\\n\");\n }\n sb.append(\"Logged JVM Stats\\n\");\n\n return sb.toString();\n }", "public GetSingleConversationOptions filters(List<String> filters) {\n if(filters.size() == 1) { //Canvas API doesn't want the [] if it is only one value\n addSingleItem(\"filter\", filters.get(0));\n } else {\n optionsMap.put(\"filter[]\", filters);\n }\n return this;\n }", "private D createAndRegisterDeclaration(Map<String, Object> metadata) {\n D declaration;\n if (klass.equals(ImportDeclaration.class)) {\n declaration = (D) ImportDeclarationBuilder.fromMetadata(metadata).build();\n } else if (klass.equals(ExportDeclaration.class)) {\n declaration = (D) ExportDeclarationBuilder.fromMetadata(metadata).build();\n } else {\n throw new IllegalStateException(\"\");\n }\n declarationRegistrationManager.registerDeclaration(declaration);\n return declaration;\n }", "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}", "String generateSynopsis() {\n synopsisOptions = buildSynopsisOptions(opts, arg, domain);\n StringBuilder synopsisBuilder = new StringBuilder();\n if (parentName != null) {\n synopsisBuilder.append(parentName).append(\" \");\n }\n synopsisBuilder.append(commandName);\n if (isOperation && !opts.isEmpty()) {\n synopsisBuilder.append(\"(\");\n } else {\n synopsisBuilder.append(\" \");\n }\n boolean hasOptions = arg != null || !opts.isEmpty();\n if (hasActions && hasOptions) {\n synopsisBuilder.append(\" [\");\n }\n if (hasActions) {\n synopsisBuilder.append(\" <action>\");\n }\n if (hasActions && hasOptions) {\n synopsisBuilder.append(\" ] || [\");\n }\n SynopsisOption opt;\n while ((opt = retrieveNextOption(synopsisOptions, false)) != null) {\n String content = addSynopsisOption(opt);\n if (content != null) {\n synopsisBuilder.append(content.trim());\n if (isOperation) {\n if (!synopsisOptions.isEmpty()) {\n synopsisBuilder.append(\",\");\n } else {\n synopsisBuilder.append(\")\");\n }\n }\n synopsisBuilder.append(\" \");\n }\n }\n if (hasActions && hasOptions) {\n synopsisBuilder.append(\" ]\");\n }\n return synopsisBuilder.toString();\n }" ]
Parses btch api response to create a list of BoxAPIResponse objects. @param batchResponse response of a batch api request @return list of BoxAPIResponses
[ "protected List<BoxAPIResponse> parseResponse(BoxJSONResponse batchResponse) {\n JsonObject responseJSON = JsonObject.readFrom(batchResponse.getJSON());\n List<BoxAPIResponse> responses = new ArrayList<BoxAPIResponse>();\n Iterator<JsonValue> responseIterator = responseJSON.get(\"responses\").asArray().iterator();\n while (responseIterator.hasNext()) {\n JsonObject jsonResponse = responseIterator.next().asObject();\n BoxAPIResponse response = null;\n\n //Gather headers\n Map<String, String> responseHeaders = new HashMap<String, String>();\n\n if (jsonResponse.get(\"headers\") != null) {\n JsonObject batchResponseHeadersObject = jsonResponse.get(\"headers\").asObject();\n for (JsonObject.Member member : batchResponseHeadersObject) {\n String headerName = member.getName();\n String headerValue = member.getValue().asString();\n responseHeaders.put(headerName, headerValue);\n }\n }\n\n // Construct a BoxAPIResponse when response is null, or a BoxJSONResponse when there's a response\n // (not anticipating any other response as per current APIs.\n // Ideally we should do it based on response header)\n if (jsonResponse.get(\"response\") == null || jsonResponse.get(\"response\").isNull()) {\n response =\n new BoxAPIResponse(jsonResponse.get(\"status\").asInt(), responseHeaders);\n } else {\n response =\n new BoxJSONResponse(jsonResponse.get(\"status\").asInt(), responseHeaders,\n jsonResponse.get(\"response\").asObject());\n }\n responses.add(response);\n }\n return responses;\n }" ]
[ "void markReferenceElements(PersistenceBroker broker)\r\n {\r\n // these cases will be handled by ObjectEnvelopeTable#cascadingDependents()\r\n // if(getModificationState().needsInsert() || getModificationState().needsDelete()) return;\r\n\r\n Map oldImage = getBeforeImage();\r\n Map newImage = getCurrentImage();\r\n\r\n Iterator iter = newImage.entrySet().iterator();\r\n while (iter.hasNext())\r\n {\r\n Map.Entry entry = (Map.Entry) iter.next();\r\n Object key = entry.getKey();\r\n // we only interested in references\r\n if(key instanceof ObjectReferenceDescriptor)\r\n {\r\n Image oldRefImage = (Image) oldImage.get(key);\r\n Image newRefImage = (Image) entry.getValue();\r\n newRefImage.performReferenceDetection(oldRefImage);\r\n }\r\n }\r\n }", "private String parseMandatoryStringValue(final String path) throws Exception {\n\n final String value = parseOptionalStringValue(path);\n if (value == null) {\n throw new Exception();\n }\n return value;\n }", "public static String[] slice(String[] strings, int begin, int length) {\n\t\tString[] result = new String[length];\n\t\tSystem.arraycopy( strings, begin, result, 0, length );\n\t\treturn result;\n\t}", "public Where<T, ID> ne(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.NOT_EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}", "public void setFrustum(float fovy, float aspect, float znear, float zfar)\n {\n Matrix4f projMatrix = new Matrix4f();\n projMatrix.perspective((float) Math.toRadians(fovy), aspect, znear, zfar);\n setFrustum(projMatrix);\n }", "public static base_response unset(nitro_service client, snmpalarm resource, String[] args) throws Exception{\n\t\tsnmpalarm unsetresource = new snmpalarm();\n\t\tunsetresource.trapname = resource.trapname;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "@RequestMapping(value = \"api/servergroup\", method = RequestMethod.POST)\n public\n @ResponseBody\n ServerGroup createServerGroup(Model model,\n @RequestParam(value = \"name\") String name,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n int groupId = ServerRedirectService.getInstance().addServerGroup(name, profileId);\n return ServerRedirectService.getInstance().getServerGroup(groupId, profileId);\n }", "public static tunneltrafficpolicy get(nitro_service service, String name) throws Exception{\n\t\ttunneltrafficpolicy obj = new tunneltrafficpolicy();\n\t\tobj.set_name(name);\n\t\ttunneltrafficpolicy response = (tunneltrafficpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}", "protected Class getClassCacheEntry(String name) {\n if (name == null) return null;\n synchronized (classCache) {\n return classCache.get(name);\n }\n }" ]
Gets as many of the requested bytes as available from this buffer. @return number of bytes actually got from this buffer (0 if no bytes are available)
[ "public synchronized int get(byte[] dst, int off, int len) {\n if (available == 0) {\n return 0;\n }\n\n // limit is last index to read + 1\n int limit = idxGet < idxPut ? idxPut : capacity;\n int count = Math.min(limit - idxGet, len);\n System.arraycopy(buffer, idxGet, dst, off, count);\n idxGet += count;\n\n if (idxGet == capacity) {\n // Array end reached, check if we have more\n int count2 = Math.min(len - count, idxPut);\n if (count2 > 0) {\n System.arraycopy(buffer, 0, dst, off + count, count2);\n idxGet = count2;\n count += count2;\n } else {\n idxGet = 0;\n }\n }\n available -= count;\n return count;\n }" ]
[ "public void writeNameValuePair(String name, String value) throws IOException\n {\n internalWriteNameValuePair(name, escapeString(value));\n }", "private static void bodyWithBuilderAndSeparator(\n SourceBuilder code,\n Datatype datatype,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n String typename) {\n Variable result = new Variable(\"result\");\n Variable separator = new Variable(\"separator\");\n\n code.addLine(\" %1$s %2$s = new %1$s(\\\"%3$s{\\\");\", StringBuilder.class, result, typename);\n if (generatorsByProperty.size() > 1) {\n // If there's a single property, we don't actually use the separator variable\n code.addLine(\" %s %s = \\\"\\\";\", String.class, separator);\n }\n\n Property first = generatorsByProperty.keySet().iterator().next();\n Property last = getLast(generatorsByProperty.keySet());\n for (Property property : generatorsByProperty.keySet()) {\n PropertyCodeGenerator generator = generatorsByProperty.get(property);\n switch (generator.initialState()) {\n case HAS_DEFAULT:\n throw new RuntimeException(\"Internal error: unexpected default field\");\n\n case OPTIONAL:\n code.addLine(\" if (%s) {\", (Excerpt) generator::addToStringCondition);\n break;\n\n case REQUIRED:\n code.addLine(\" if (!%s.contains(%s.%s)) {\",\n UNSET_PROPERTIES, datatype.getPropertyEnum(), property.getAllCapsName());\n break;\n }\n code.add(\" \").add(result);\n if (property != first) {\n code.add(\".append(%s)\", separator);\n }\n code.add(\".append(\\\"%s=\\\").append(%s)\",\n property.getName(), (Excerpt) generator::addToStringValue);\n if (property != last) {\n code.add(\";%n %s = \\\", \\\"\", separator);\n }\n code.add(\";%n }%n\");\n }\n code.addLine(\" return %s.append(\\\"}\\\").toString();\", result);\n }", "public static MediaType nonBinaryUtf8( MediaType.Type type, String subType ) {\n return new MediaType( type, subType, UTF_8 );\n }", "private Method getPropertySourceMethod(Object sourceObject,\r\n\t\t\tObject destinationObject, String destinationProperty) {\r\n\t\tBeanToBeanMapping beanToBeanMapping = beanToBeanMappings.get(ClassPair\r\n\t\t\t\t.get(sourceObject.getClass(), destinationObject\r\n\t\t\t\t\t\t.getClass()));\r\n\t\tString sourceProperty = null;\r\n\t\tif (beanToBeanMapping != null) {\r\n\t\t\tsourceProperty = beanToBeanMapping\r\n\t\t\t\t\t.getSourceProperty(destinationProperty);\r\n\t\t}\r\n\t\tif (sourceProperty == null) {\r\n\t\t\tsourceProperty = destinationProperty;\r\n\t\t}\r\n\r\n\t\treturn BeanUtils.getGetterPropertyMethod(sourceObject.getClass(),\r\n\t\t\t\tsourceProperty);\r\n\t}", "public GVRComponent detachComponent(long type) {\n NativeSceneObject.detachComponent(getNative(), type);\n synchronized (mComponents) {\n GVRComponent component = mComponents.remove(type);\n if (component != null) {\n component.setOwnerObject(null);\n }\n return component;\n }\n }", "private void populateMap(byte[] data, Integer previousItemOffset, Integer previousItemKey, Integer itemOffset)\n {\n if (previousItemOffset != null)\n {\n int itemSize = itemOffset.intValue() - previousItemOffset.intValue();\n byte[] itemData = new byte[itemSize];\n System.arraycopy(data, previousItemOffset.intValue(), itemData, 0, itemSize);\n m_map.put(previousItemKey, itemData);\n }\n }", "private void writeExceptions12(Project.Calendars.Calendar calendar, List<ProjectCalendarException> exceptions)\n {\n Exceptions ce = m_factory.createProjectCalendarsCalendarExceptions();\n calendar.setExceptions(ce);\n List<Exceptions.Exception> el = ce.getException();\n\n for (ProjectCalendarException exception : exceptions)\n {\n Exceptions.Exception ex = m_factory.createProjectCalendarsCalendarExceptionsException();\n el.add(ex);\n\n ex.setName(exception.getName());\n boolean working = exception.getWorking();\n ex.setDayWorking(Boolean.valueOf(working));\n\n if (exception.getRecurring() == null)\n {\n ex.setEnteredByOccurrences(Boolean.FALSE);\n ex.setOccurrences(BigInteger.ONE);\n ex.setType(BigInteger.ONE);\n }\n else\n {\n populateRecurringException(exception, ex);\n }\n\n Project.Calendars.Calendar.Exceptions.Exception.TimePeriod period = m_factory.createProjectCalendarsCalendarExceptionsExceptionTimePeriod();\n ex.setTimePeriod(period);\n period.setFromDate(exception.getFromDate());\n period.setToDate(exception.getToDate());\n\n if (working)\n {\n Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes times = m_factory.createProjectCalendarsCalendarExceptionsExceptionWorkingTimes();\n ex.setWorkingTimes(times);\n List<Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime> timesList = times.getWorkingTime();\n\n for (DateRange range : exception)\n {\n Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime time = m_factory.createProjectCalendarsCalendarExceptionsExceptionWorkingTimesWorkingTime();\n timesList.add(time);\n\n time.setFromTime(range.getStart());\n time.setToTime(range.getEnd());\n }\n }\n }\n }", "public static <T> T[] concat(T[] first, T... second) {\n\t\tint firstLength = first.length;\n\t\tint secondLength = second.length;\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT[] result = (T[]) Array.newInstance( first.getClass().getComponentType(), firstLength + secondLength );\n\t\tSystem.arraycopy( first, 0, result, 0, firstLength );\n\t\tSystem.arraycopy( second, 0, result, firstLength, secondLength );\n\n\t\treturn result;\n\t}", "public RuleEnvelope getRule(String ruleId) throws ApiException {\n ApiResponse<RuleEnvelope> resp = getRuleWithHttpInfo(ruleId);\n return resp.getData();\n }" ]
This method extracts resource data from a Phoenix file. @param phoenixProject parent node for resources
[ "private void readResources(Storepoint phoenixProject)\n {\n Resources resources = phoenixProject.getResources();\n if (resources != null)\n {\n for (net.sf.mpxj.phoenix.schema.Project.Storepoints.Storepoint.Resources.Resource res : resources.getResource())\n {\n Resource resource = readResource(res);\n readAssignments(resource, res);\n }\n }\n }" ]
[ "private void buildTransformers_4_0(ResourceTransformationDescriptionBuilder builder) {\n\n // We need to do custom transformation of the attribute in the root resource\n // related to endpoint configs, as these were moved to the root from a previous child resource\n EndPointWriteTransformer endPointWriteTransformer = new EndPointWriteTransformer();\n builder.getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.ALWAYS, endpointAttrArray)\n .end()\n .addOperationTransformationOverride(\"add\")\n //.inheritResourceAttributeDefinitions() // don't inherit as we discard\n .setCustomOperationTransformer(new EndPointAddTransformer())\n .end()\n .addOperationTransformationOverride(\"write-attribute\")\n //.inheritResourceAttributeDefinitions() // don't inherit as we discard\n .setCustomOperationTransformer(endPointWriteTransformer)\n .end()\n .addOperationTransformationOverride(\"undefine-attribute\")\n //.inheritResourceAttributeDefinitions() // don't inherit as we discard\n .setCustomOperationTransformer(endPointWriteTransformer)\n .end();\n }", "public static base_responses delete(nitro_service client, appfwlearningdata resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwlearningdata deleteresources[] = new appfwlearningdata[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new appfwlearningdata();\n\t\t\t\tdeleteresources[i].profilename = resources[i].profilename;\n\t\t\t\tdeleteresources[i].starturl = resources[i].starturl;\n\t\t\t\tdeleteresources[i].cookieconsistency = resources[i].cookieconsistency;\n\t\t\t\tdeleteresources[i].fieldconsistency = resources[i].fieldconsistency;\n\t\t\t\tdeleteresources[i].formactionurl_ffc = resources[i].formactionurl_ffc;\n\t\t\t\tdeleteresources[i].crosssitescripting = resources[i].crosssitescripting;\n\t\t\t\tdeleteresources[i].formactionurl_xss = resources[i].formactionurl_xss;\n\t\t\t\tdeleteresources[i].sqlinjection = resources[i].sqlinjection;\n\t\t\t\tdeleteresources[i].formactionurl_sql = resources[i].formactionurl_sql;\n\t\t\t\tdeleteresources[i].fieldformat = resources[i].fieldformat;\n\t\t\t\tdeleteresources[i].formactionurl_ff = resources[i].formactionurl_ff;\n\t\t\t\tdeleteresources[i].csrftag = resources[i].csrftag;\n\t\t\t\tdeleteresources[i].csrfformoriginurl = resources[i].csrfformoriginurl;\n\t\t\t\tdeleteresources[i].xmldoscheck = resources[i].xmldoscheck;\n\t\t\t\tdeleteresources[i].xmlwsicheck = resources[i].xmlwsicheck;\n\t\t\t\tdeleteresources[i].xmlattachmentcheck = resources[i].xmlattachmentcheck;\n\t\t\t\tdeleteresources[i].totalxmlrequests = resources[i].totalxmlrequests;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "@Override\n\tpublic CrawlSession call() {\n\t\tInjector injector = Guice.createInjector(new CoreModule(config));\n\t\tcontroller = injector.getInstance(CrawlController.class);\n\t\tCrawlSession session = controller.call();\n\t\treason = controller.getReason();\n\t\treturn session;\n\t}", "private String parseRssFeed(String feed) {\n String[] result = feed.split(\"<br />\");\n String[] result2 = result[2].split(\"<BR />\");\n\n return result2[0];\n }", "private ClassNode getGenericsResolvedTypeOfFieldOrProperty(AnnotatedNode an, ClassNode type) {\n if (!type.isUsingGenerics()) return type;\n Map<String, GenericsType> connections = new HashMap();\n //TODO: inner classes mean a different this-type. This is ignored here!\n extractGenericsConnections(connections, typeCheckingContext.getEnclosingClassNode(), an.getDeclaringClass());\n type= applyGenericsContext(connections, type);\n return type;\n }", "public Iterator<BoxItem.Info> iterator() {\n URL url = GET_ITEMS_URL.build(this.api.getBaseURL());\n return new BoxItemIterator(this.api, url);\n }", "public static aaapreauthenticationpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\taaapreauthenticationpolicy_binding obj = new aaapreauthenticationpolicy_binding();\n\t\tobj.set_name(name);\n\t\taaapreauthenticationpolicy_binding response = (aaapreauthenticationpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "private static void verifyJUnit4Present() {\n try {\n Class<?> clazz = Class.forName(\"org.junit.runner.Description\");\n if (!Serializable.class.isAssignableFrom(clazz)) {\n JvmExit.halt(SlaveMain.ERR_OLD_JUNIT);\n }\n } catch (ClassNotFoundException e) {\n JvmExit.halt(SlaveMain.ERR_NO_JUNIT);\n }\n }", "private void putEvent(EventType eventType) throws Exception {\n List<EventType> eventTypes = Collections.singletonList(eventType);\n\n int i;\n for (i = 0; i < retryNum; ++i) {\n try {\n monitoringService.putEvents(eventTypes);\n break;\n } catch (Exception e) {\n LOG.log(Level.SEVERE, e.getMessage(), e);\n }\n Thread.sleep(retryDelay);\n }\n\n if (i == retryNum) {\n LOG.warning(\"Could not send events to monitoring service after \" + retryNum + \" retries.\");\n throw new Exception(\"Send SERVER_START/SERVER_STOP event to SAM Server failed\");\n }\n\n }" ]
Animate de-selection of visible views and clear selected set.
[ "public void clearSelections() {\n for (CheckableViewHolder vh : mCheckedVisibleViewHolders) {\n vh.checkbox.setChecked(false);\n }\n mCheckedVisibleViewHolders.clear();\n mCheckedItems.clear();\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 }", "private void processCurrency(Row row)\n {\n String currencyName = row.getString(\"curr_short_name\");\n DecimalFormatSymbols symbols = new DecimalFormatSymbols();\n symbols.setDecimalSeparator(row.getString(\"decimal_symbol\").charAt(0));\n symbols.setGroupingSeparator(row.getString(\"digit_group_symbol\").charAt(0));\n DecimalFormat nf = new DecimalFormat();\n nf.setDecimalFormatSymbols(symbols);\n nf.applyPattern(\"#.#\");\n m_currencyMap.put(currencyName, nf);\n\n if (currencyName.equalsIgnoreCase(m_defaultCurrencyName))\n {\n m_numberFormat = nf;\n m_defaultCurrencyData = row;\n }\n }", "public void setRegExp(final String pattern,\n final String invalidCharactersInNameErrorMessage,\n final String invalidCharacterTypedMessage) {\n regExp = RegExp.compile(pattern);\n this.invalidCharactersInNameErrorMessage = invalidCharactersInNameErrorMessage;\n this.invalidCharacterTypedMessage = invalidCharacterTypedMessage;\n }", "public Date toDate(Object date) {\n\n Date d = null;\n if (null != date) {\n if (date instanceof Date) {\n d = (Date)date;\n } else if (date instanceof Long) {\n d = new Date(((Long)date).longValue());\n } else {\n try {\n long l = Long.parseLong(date.toString());\n d = new Date(l);\n } catch (Exception e) {\n // do nothing, just let d remain null\n }\n }\n }\n return d;\n }", "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 String join(int[] array, String separator) {\n if (array != null) {\n StringBuilder buf = new StringBuilder(Math.max(16, (separator.length() + 1) * array.length));\n char singleChar = separator.length() == 1 ? separator.charAt(0) : 0;\n for (int i = 0; i < array.length; i++) {\n if (i != 0) {\n if (singleChar != 0) {\n // More efficient\n buf.append(singleChar);\n } else {\n buf.append(separator);\n }\n }\n buf.append(array[i]);\n }\n return buf.toString();\n } else {\n return \"\";\n }\n }", "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 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 <T extends Spin<?>> T S(Object input, DataFormat<T> format) {\n return SpinFactory.INSTANCE.createSpin(input, format);\n }" ]
Creates and caches dataset info object. Subsequent invocations will return same instance. @see IIM#DS(int, int) @param dataSet dataset record number @return dataset info instace
[ "public DataSetInfo create(int dataSet) throws InvalidDataSetException {\r\n\t\tDataSetInfo info = dataSets.get(createKey(dataSet));\r\n\t\tif (info == null) {\r\n\t\t\tint recordNumber = (dataSet >> 8) & 0xFF;\r\n\t\t\tint dataSetNumber = dataSet & 0xFF;\r\n\t\t\tthrow new UnsupportedDataSetException(recordNumber + \":\" + dataSetNumber);\r\n\t\t\t// info = super.create(dataSet);\r\n\t\t}\r\n\t\treturn info;\r\n\t}" ]
[ "public static double Sinh(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return x + (x * x * x) / 6D;\r\n } else {\r\n\r\n double mult = x * x * x;\r\n double fact = 6;\r\n int factS = 5;\r\n double result = x + mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += mult / fact;\r\n }\r\n\r\n return result;\r\n }\r\n }", "public static final BigDecimal printUnits(Number value)\n {\n return (value == null ? BIGDECIMAL_ONE : new BigDecimal(value.doubleValue() / 100));\n }", "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}", "public void ifPropertyValueEquals(String template, Properties attributes) throws XDocletException\r\n {\r\n String value = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), attributes.getProperty(ATTRIBUTE_NAME));\r\n String expected = attributes.getProperty(ATTRIBUTE_VALUE);\r\n\r\n if (value == null)\r\n {\r\n value = attributes.getProperty(ATTRIBUTE_DEFAULT);\r\n }\r\n if (expected.equals(value))\r\n {\r\n generate(template);\r\n }\r\n }", "public void notifyHeaderItemRangeRemoved(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \" + (positionStart + itemCount - 1) + \"] is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemRangeRemoved(positionStart, itemCount);\n }", "public void waitForAsyncFlush() {\n long numAdded = asyncBatchesAdded.get();\n\n synchronized (this) {\n while (numAdded > asyncBatchesProcessed) {\n try {\n wait();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n }\n }", "public Request option(String key, Object value) {\n this.options.put(key, value);\n return this;\n }", "public static byte[] getContentBytes(String stringUrl) throws IOException {\n URL url = new URL(stringUrl);\n byte[] data = MyStreamUtils.readContentBytes(url.openStream());\n return data;\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 }" ]
We have received notification that a device is no longer on the network, so clear out its artwork. @param announcement the packet which reported the device’s disappearance
[ "private void clearArt(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(hotCache.keySet())) {\n if (deck.player == player) {\n hotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverAlbumArtUpdate(player, null); // Inform listeners that the artwork is gone.\n }\n }\n }\n // Again iterate over a copy to avoid concurrent modification issues\n for (DataReference art : new HashSet<DataReference>(artCache.keySet())) {\n if (art.player == player) {\n artCache.remove(art);\n }\n }\n }" ]
[ "public boolean contains(String id) {\n assertNotEmpty(id, \"id\");\n InputStream response = null;\n try {\n response = couchDbClient.head(new DatabaseURIHelper(dbUri).documentUri(id));\n } catch (NoDocumentException e) {\n return false;\n } finally {\n close(response);\n }\n return true;\n }", "public static ForwardCurveInterpolation createForwardCurveFromDiscountFactors(String name, double[] times, RandomVariable[] givenDiscountFactors, double paymentOffset) {\n\t\tForwardCurveInterpolation forwardCurveInterpolation = new ForwardCurveInterpolation(name, paymentOffset, InterpolationEntityForward.FORWARD, null);\n\n\t\tif(times.length == 0) {\n\t\t\tthrow new IllegalArgumentException(\"Vector of times must not be empty.\");\n\t\t}\n\n\t\tif(times[0] > 0) {\n\t\t\t// Add first forward\n\t\t\tRandomVariable forward = givenDiscountFactors[0].sub(1.0).pow(-1.0).div(times[0]);\n\t\t\tforwardCurveInterpolation.addForward(null, 0.0, forward, true);\n\t\t}\n\n\t\tfor(int timeIndex=0; timeIndex<times.length-1;timeIndex++) {\n\t\t\tRandomVariable \tforward\t\t= givenDiscountFactors[timeIndex].div(givenDiscountFactors[timeIndex+1].sub(1.0)).div(times[timeIndex+1] - times[timeIndex]);\n\t\t\tdouble\tfixingTime\t= times[timeIndex];\n\t\t\tboolean\tisParameter\t= (fixingTime > 0);\n\t\t\tforwardCurveInterpolation.addForward(null, fixingTime, forward, isParameter);\n\t\t}\n\n\t\treturn forwardCurveInterpolation;\n\t}", "@Deprecated\r\n private InputStream getImageAsStream(String suffix) throws IOException {\r\n StringBuffer buffer = getBaseImageUrl();\r\n buffer.append(suffix);\r\n return _getImageAsStream(buffer.toString());\r\n }", "private static void listAssignmentsByTask(ProjectFile file)\n {\n for (Task task : file.getTasks())\n {\n System.out.println(\"Assignments for task \" + task.getName() + \":\");\n\n for (ResourceAssignment assignment : task.getResourceAssignments())\n {\n Resource resource = assignment.getResource();\n String resourceName;\n\n if (resource == null)\n {\n resourceName = \"(null resource)\";\n }\n else\n {\n resourceName = resource.getName();\n }\n\n System.out.println(\" \" + resourceName);\n }\n }\n\n System.out.println();\n }", "private void remove() {\n if (removing) {\n return;\n }\n if (deactiveNotifications.size() == 0) {\n return;\n }\n removing = true;\n final NotificationPopupView view = deactiveNotifications.get(0);\n final LinearFadeOutAnimation fadeOutAnimation = new LinearFadeOutAnimation(view) {\n\n @Override\n public void onUpdate(double progress) {\n super.onUpdate(progress);\n for (int i = 0; i < activeNotifications.size(); i++) {\n NotificationPopupView v = activeNotifications.get(i);\n final int left = v.getPopupLeft();\n final int top = (int) (((i + 1) * SPACING) - (progress * SPACING));\n v.setPopupPosition(left,\n top);\n }\n }\n\n @Override\n public void onComplete() {\n super.onComplete();\n view.hide();\n deactiveNotifications.remove(view);\n activeNotifications.remove(view);\n removing = false;\n remove();\n }\n };\n fadeOutAnimation.run(500);\n }", "public static List<Object> filterMapToList(final Map<String, ?> map, final String[] nameMapping) {\n\t\tif( map == null ) {\n\t\t\tthrow new NullPointerException(\"map should not be null\");\n\t\t} else if( nameMapping == null ) {\n\t\t\tthrow new NullPointerException(\"nameMapping should not be null\");\n\t\t}\n\t\t\n\t\tfinal List<Object> result = new ArrayList<Object>(nameMapping.length);\n\t\tfor( final String key : nameMapping ) {\n\t\t\tresult.add(map.get(key));\n\t\t}\n\t\treturn result;\n\t}", "public static auditsyslogpolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_systemglobal_binding obj = new auditsyslogpolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_systemglobal_binding response[] = (auditsyslogpolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private static BoxRetentionPolicyAssignment.Info createAssignment(BoxAPIConnection api, String policyID,\r\n JsonObject assignTo, JsonArray filter) {\r\n URL url = ASSIGNMENTS_URL_TEMPLATE.build(api.getBaseURL());\r\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\r\n\r\n JsonObject requestJSON = new JsonObject()\r\n .add(\"policy_id\", policyID)\r\n .add(\"assign_to\", assignTo);\r\n\r\n if (filter != null) {\r\n requestJSON.add(\"filter_fields\", filter);\r\n }\r\n\r\n request.setBody(requestJSON.toString());\r\n BoxJSONResponse response = (BoxJSONResponse) request.send();\r\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\r\n BoxRetentionPolicyAssignment createdAssignment\r\n = new BoxRetentionPolicyAssignment(api, responseJSON.get(\"id\").asString());\r\n return createdAssignment.new Info(responseJSON);\r\n }", "public Path getReportDirectory()\n {\n WindupConfigurationModel cfg = WindupConfigurationService.getConfigurationModel(getGraphContext());\n Path path = cfg.getOutputPath().asFile().toPath().resolve(REPORTS_DIR);\n createDirectoryIfNeeded(path);\n return path.toAbsolutePath();\n }" ]
Remove paths with no active overrides @throws Exception
[ "private void cullDisabledPaths() throws Exception {\n\n ArrayList<EndpointOverride> removePaths = new ArrayList<EndpointOverride>();\n RequestInformation requestInfo = requestInformation.get();\n for (EndpointOverride selectedPath : requestInfo.selectedResponsePaths) {\n\n // check repeat count on selectedPath\n // -1 is unlimited\n if (selectedPath != null && selectedPath.getRepeatNumber() == 0) {\n // skip\n removePaths.add(selectedPath);\n } else if (selectedPath != null && selectedPath.getRepeatNumber() != -1) {\n // need to decrement the #\n selectedPath.updateRepeatNumber(selectedPath.getRepeatNumber() - 1);\n }\n }\n\n // remove paths if we need to\n for (EndpointOverride removePath : removePaths) {\n requestInfo.selectedResponsePaths.remove(removePath);\n }\n }" ]
[ "void flushLogQueue() {\n Set<String> problems = new LinkedHashSet<String>();\n synchronized (messageQueue) {\n Iterator<LogEntry> i = messageQueue.iterator();\n while (i.hasNext()) {\n problems.add(\"\\t\\t\" + i.next().getMessage() + \"\\n\");\n i.remove();\n }\n }\n if (!problems.isEmpty()) {\n logger.transformationWarnings(target.getHostName(), problems);\n }\n }", "public void rotateWithPivot(float quatW, float quatX, float quatY,\n float quatZ, float pivotX, float pivotY, float pivotZ) {\n NativeTransform.rotateWithPivot(getNative(), quatW, quatX, quatY,\n quatZ, pivotX, pivotY, pivotZ);\n }", "public static ExtensibleConfigurationPersister createHostXmlConfigurationPersister(final ConfigurationFile file, final HostControllerEnvironment environment,\n final ExecutorService executorService, final ExtensionRegistry hostExtensionRegistry,\n final LocalHostControllerInfo localHostControllerInfo) {\n String defaultHostname = localHostControllerInfo.getLocalHostName();\n if (environment.getRunningModeControl().isReloaded()) {\n if (environment.getRunningModeControl().getReloadHostName() != null) {\n defaultHostname = environment.getRunningModeControl().getReloadHostName();\n }\n }\n HostXml hostXml = new HostXml(defaultHostname, environment.getRunningModeControl().getRunningMode(),\n environment.isUseCachedDc(), Module.getBootModuleLoader(), executorService, hostExtensionRegistry);\n BackupXmlConfigurationPersister persister = new BackupXmlConfigurationPersister(file, new QName(Namespace.CURRENT.getUriString(), \"host\"), hostXml, hostXml, false);\n for (Namespace namespace : Namespace.domainValues()) {\n if (!namespace.equals(Namespace.CURRENT)) {\n persister.registerAdditionalRootElement(new QName(namespace.getUriString(), \"host\"), hostXml);\n }\n }\n hostExtensionRegistry.setWriterRegistry(persister);\n return persister;\n }", "public static GraphTraversal<Vertex, Vertex> addPipeFor(GraphTraversal<Vertex, Vertex> pipeline,\n Class<? extends WindupVertexFrame> clazz)\n {\n pipeline.has(WindupVertexFrame.TYPE_PROP, GraphTypeManager.getTypeValue(clazz));\n return pipeline;\n }", "private void writeCustomInfo(Event event) {\n // insert customInfo (key/value) into DB\n for (Map.Entry<String, String> customInfo : event.getCustomInfo().entrySet()) {\n long cust_id = dbDialect.getIncrementer().nextLongValue();\n getJdbcTemplate()\n .update(\"insert into EVENTS_CUSTOMINFO (ID, EVENT_ID, CUST_KEY, CUST_VALUE)\"\n + \" values (?,?,?,?)\",\n cust_id, event.getPersistedId(), customInfo.getKey(), customInfo.getValue());\n }\n }", "public List<Profile> findAllProfiles() throws Exception {\n ArrayList<Profile> allProfiles = new ArrayList<>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_PROFILE);\n results = statement.executeQuery();\n while (results.next()) {\n allProfiles.add(this.getProfileFromResultSet(results));\n }\n } catch (Exception e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n return allProfiles;\n }", "private void readTextsCompressed(File dir, HashMap results) throws IOException\r\n {\r\n if (dir.exists() && dir.isDirectory())\r\n {\r\n File[] files = dir.listFiles();\r\n\r\n for (int idx = 0; idx < files.length; idx++)\r\n {\r\n if (files[idx].isDirectory())\r\n {\r\n continue;\r\n }\r\n results.put(files[idx].getName(), readTextCompressed(files[idx]));\r\n }\r\n }\r\n }", "public KeyChangeResult handleKeyChange(EntryChangeEvent event, boolean allLanguages) {\n\n if (m_keyset.getKeySet().contains(event.getNewValue())) {\n m_container.getItem(event.getItemId()).getItemProperty(TableProperty.KEY).setValue(event.getOldValue());\n return KeyChangeResult.FAILED_DUPLICATED_KEY;\n }\n if (allLanguages && !renameKeyForAllLanguages(event.getOldValue(), event.getNewValue())) {\n m_container.getItem(event.getItemId()).getItemProperty(TableProperty.KEY).setValue(event.getOldValue());\n return KeyChangeResult.FAILED_FOR_OTHER_LANGUAGE;\n }\n return KeyChangeResult.SUCCESS;\n }", "protected void afterMaterialization()\r\n\t{\r\n\t\tif (_listeners != null)\r\n\t\t{\r\n\t\t\tMaterializationListener listener;\r\n\r\n\t\t\t// listeners may remove themselves during the afterMaterialization\r\n\t\t\t// callback.\r\n\t\t\t// thus we must iterate through the listeners vector from back to\r\n\t\t\t// front\r\n\t\t\t// to avoid index problems.\r\n\t\t\tfor (int idx = _listeners.size() - 1; idx >= 0; idx--)\r\n\t\t\t{\r\n\t\t\t\tlistener = (MaterializationListener) _listeners.get(idx);\r\n\t\t\t\tlistener.afterMaterialization(this, _realSubject);\r\n\t\t\t}\r\n\t\t}\r\n\t}" ]
Sets the specified date attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
[ "public void setDateAttribute(String name, Date value) {\n\t\tensureAttributes();\n\t\tAttribute attribute = new DateAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetAllAttributes().put(name, attribute);\n\t}" ]
[ "public SerialMessage setValueMessage(int level) {\r\n\t\tlogger.debug(\"Creating new message for application command BASIC_SET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.Set);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t3, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) BASIC_SET,\r\n\t\t\t\t\t\t\t\t(byte) level\r\n\t\t\t\t\t\t\t\t};\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}", "public void fire(TestCaseStartedEvent event) {\n //init root step in parent thread if needed\n stepStorage.get();\n\n TestCaseResult testCase = testCaseStorage.get();\n event.process(testCase);\n\n synchronized (TEST_SUITE_ADD_CHILD_LOCK) {\n testSuiteStorage.get(event.getSuiteUid()).getTestCases().add(testCase);\n }\n\n notifier.fire(event);\n }", "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 static String getString(byte[] bytes, String encoding) {\n try {\n return new String(bytes, encoding);\n } catch(UnsupportedEncodingException e) {\n throw new IllegalArgumentException(encoding + \" is not a known encoding name.\", e);\n }\n }", "public void printAnswers(List<CoreLabel> doc, PrintWriter out) {\r\n // boolean tagsMerged = flags.mergeTags;\r\n // boolean useHead = flags.splitOnHead;\r\n\r\n if ( ! \"iob1\".equalsIgnoreCase(flags.entitySubclassification)) {\r\n deEndify(doc);\r\n }\r\n\r\n for (CoreLabel fl : doc) {\r\n String word = fl.word();\r\n if (word == BOUNDARY) { // Using == is okay, because it is set to constant\r\n out.println();\r\n } else {\r\n String gold = fl.get(OriginalAnswerAnnotation.class);\r\n if(gold == null) gold = \"\";\r\n String guess = fl.get(AnswerAnnotation.class);\r\n // System.err.println(fl.word() + \"\\t\" + fl.get(AnswerAnnotation.class) + \"\\t\" + fl.get(AnswerAnnotation.class));\r\n String pos = fl.tag();\r\n String chunk = (fl.get(ChunkAnnotation.class) == null ? \"\" : fl.get(ChunkAnnotation.class));\r\n out.println(fl.word() + '\\t' + pos + '\\t' + chunk + '\\t' +\r\n gold + '\\t' + guess);\r\n }\r\n }\r\n }", "public static String createOdataFilterForTags(String tagName, String tagValue) {\n if (tagName == null) {\n return null;\n } else if (tagValue == null) {\n return String.format(\"tagname eq '%s'\", tagName);\n } else {\n return String.format(\"tagname eq '%s' and tagvalue eq '%s'\", tagName, tagValue);\n }\n }", "public boolean checkXpathStartsWithXpathEventableCondition(Document dom,\n\t\t\tEventableCondition eventableCondition, String xpath) throws XPathExpressionException {\n\t\tif (eventableCondition == null || Strings\n\t\t\t\t.isNullOrEmpty(eventableCondition.getInXPath())) {\n\t\t\tthrow new CrawljaxException(\"Eventable has no XPath condition\");\n\t\t}\n\t\tList<String> expressions =\n\t\t\t\tXPathHelper.getXpathForXPathExpressions(dom, eventableCondition.getInXPath());\n\n\t\treturn checkXPathUnderXPaths(xpath, expressions);\n\t}", "public static vpnvserver_authenticationradiuspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_authenticationradiuspolicy_binding obj = new vpnvserver_authenticationradiuspolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_authenticationradiuspolicy_binding response[] = (vpnvserver_authenticationradiuspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "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 }" ]
Retrieve and validate store name from the REST request. @return true if valid, false otherwise
[ "protected boolean isStoreValid() {\n boolean result = false;\n String requestURI = this.request.getUri();\n this.storeName = parseStoreName(requestURI);\n if(storeName != null) {\n result = true;\n } else {\n logger.error(\"Error when validating request. Missing store name.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing store name. Critical error.\");\n }\n return result;\n }" ]
[ "static public String bb2hex(byte[] bb) {\n\t\tString result = \"\";\n\t\tfor (int i=0; i<bb.length; i++) {\n\t\t\tresult = result + String.format(\"%02X \", bb[i]);\n\t\t}\n\t\treturn result;\n\t}", "public String getUrl(){\n\t\tfinal StringBuilder sb = new StringBuilder();\n\t\tsb.append(\"http://\");\n\t\tsb.append(getHttpConfiguration().getBindHost().get());\n\t\tsb.append(\":\");\n\t\tsb.append(getHttpConfiguration().getPort());\n\t\t\n\t\treturn sb.toString();\n\t}", "public static String groupFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null;\n }", "public base_response login(String username, String password, Long timeout) throws Exception\n\t{\n\t\tthis.set_credential(username, password);\n\t\tthis.set_timeout(timeout);\n\t\treturn this.login();\n\t}", "public Object moveToNextValue(Object val) throws SQLException {\n\t\tif (dataPersister == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn dataPersister.moveToNextValue(val);\n\t\t}\n\t}", "@Override\n public void setValue(String value, boolean fireEvents) {\n\tboolean added = setSelectedValue(this, value, addMissingValue);\n\tif (added && fireEvents) {\n\t ValueChangeEvent.fire(this, getValue());\n\t}\n }", "public static boolean isKeyUsed(final Jedis jedis, final String key) {\n return !NONE.equalsIgnoreCase(jedis.type(key));\n }", "private Collection parseCollection(Element collectionElement) {\n\n Collection collection = new Collection();\n collection.setId(collectionElement.getAttribute(\"id\"));\n collection.setServer(collectionElement.getAttribute(\"server\"));\n collection.setSecret(collectionElement.getAttribute(\"secret\"));\n collection.setChildCount(collectionElement.getAttribute(\"child_count\"));\n collection.setIconLarge(collectionElement.getAttribute(\"iconlarge\"));\n collection.setIconSmall(collectionElement.getAttribute(\"iconsmall\"));\n collection.setDateCreated(collectionElement.getAttribute(\"datecreate\"));\n collection.setTitle(XMLUtilities.getChildValue(collectionElement, \"title\"));\n collection.setDescription(XMLUtilities.getChildValue(collectionElement, \"description\"));\n\n Element iconPhotos = XMLUtilities.getChild(collectionElement, \"iconphotos\");\n if (iconPhotos != null) {\n NodeList photoElements = iconPhotos.getElementsByTagName(\"photo\");\n for (int i = 0; i < photoElements.getLength(); i++) {\n Element photoElement = (Element) photoElements.item(i);\n collection.addPhoto(PhotoUtils.createPhoto(photoElement));\n }\n }\n\n return collection;\n }", "public static WebDriverBackedEmbeddedBrowser withDriver(WebDriver driver,\n\t\t\tImmutableSortedSet<String> filterAttributes, long crawlWaitEvent,\n\t\t\tlong crawlWaitReload) {\n\t\treturn new WebDriverBackedEmbeddedBrowser(driver, filterAttributes, crawlWaitEvent,\n\t\t\t\tcrawlWaitReload);\n\t}" ]
Make all elements of a String array lower case. @param strings string array, may contain null item but can't be null @return array containing all provided elements lower case
[ "public static String[] allLowerCase(String... strings){\n\t\tString[] tmp = new String[strings.length];\n\t\tfor(int idx=0;idx<strings.length;idx++){\n\t\t\tif(strings[idx] != null){\n\t\t\t\ttmp[idx] = strings[idx].toLowerCase();\n\t\t\t}\n\t\t}\n\t\treturn tmp;\n\t}" ]
[ "public String validationErrors() {\n\n List<String> errors = new ArrayList<>();\n for (File config : getConfigFiles()) {\n String filename = config.getName();\n try (FileInputStream stream = new FileInputStream(config)) {\n CmsXmlUtils.unmarshalHelper(CmsFileUtil.readFully(stream, false), new CmsXmlEntityResolver(null), true);\n } catch (CmsXmlException e) {\n errors.add(filename + \":\" + e.getCause().getMessage());\n } catch (Exception e) {\n errors.add(filename + \":\" + e.getMessage());\n }\n }\n if (errors.size() == 0) {\n return null;\n }\n String errString = CmsStringUtil.listAsString(errors, \"\\n\");\n JSONObject obj = new JSONObject();\n try {\n obj.put(\"err\", errString);\n } catch (JSONException e) {\n\n }\n return obj.toString();\n }", "@Override\n public void run()\n {\n try {\n startBarrier.await();\n\n int idleCount = 0;\n while (!isRunning.compareAndSet(idleCount > LINGER_ITERATIONS && deadPool.isEmpty() && completionKeyToProcessMap.isEmpty(), false)) {\n idleCount = (!shutdown && process()) ? 0 : (idleCount + 1);\n }\n }\n catch (Exception e) {\n // TODO: how to handle this error?\n e.printStackTrace();\n isRunning.set(false);\n }\n }", "public void declareShovel(String vhost, ShovelInfo info) {\n Map<String, Object> props = info.getDetails().getPublishProperties();\n if(props != null && props.isEmpty()) {\n throw new IllegalArgumentException(\"Shovel publish properties must be a non-empty map or null\");\n }\n final URI uri = uriWithPath(\"./parameters/shovel/\" + encodePathSegment(vhost) + \"/\" + encodePathSegment(info.getName()));\n this.rt.put(uri, info);\n }", "public void print( String equation ) {\n // first assume it's just a variable\n Variable v = lookupVariable(equation);\n if( v == null ) {\n Sequence sequence = compile(equation,false,false);\n sequence.perform();\n v = sequence.output;\n }\n\n if( v instanceof VariableMatrix ) {\n ((VariableMatrix)v).matrix.print();\n } else if(v instanceof VariableScalar ) {\n System.out.println(\"Scalar = \"+((VariableScalar)v).getDouble() );\n } else {\n System.out.println(\"Add support for \"+v.getClass().getSimpleName());\n }\n }", "public void dispatchKeyEvent(int code, int action) {\n int keyCode = 0;\n int keyAction = 0;\n if (code == BUTTON_1) {\n keyCode = KeyEvent.KEYCODE_BUTTON_1;\n } else if (code == BUTTON_2) {\n keyCode = KeyEvent.KEYCODE_BUTTON_2;\n }\n\n if (action == ACTION_DOWN) {\n keyAction = KeyEvent.ACTION_DOWN;\n } else if (action == ACTION_UP) {\n keyAction = KeyEvent.ACTION_UP;\n }\n\n KeyEvent keyEvent = new KeyEvent(keyAction, keyCode);\n setKeyEvent(keyEvent);\n }", "public static 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 }", "public static void registerConverters(Set<?> converters, ConverterRegistry registry) {\n\t\tif (converters != null) {\n\t\t\tfor (Object converter : converters) {\n\t\t\t\tif (converter instanceof GenericConverter) {\n\t\t\t\t\tregistry.addConverter((GenericConverter) converter);\n\t\t\t\t}\n\t\t\t\telse if (converter instanceof Converter<?, ?>) {\n\t\t\t\t\tregistry.addConverter((Converter<?, ?>) converter);\n\t\t\t\t}\n\t\t\t\telse if (converter instanceof ConverterFactory<?, ?>) {\n\t\t\t\t\tregistry.addConverterFactory((ConverterFactory<?, ?>) converter);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Each converter object must implement one of the \" +\n\t\t\t\t\t\t\t\"Converter, ConverterFactory, or GenericConverter interfaces\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "@Override\n\tpublic String toFullString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = getStringCache().fullString) == null) {\n\t\t\tgetStringCache().fullString = result = toNormalizedString(IPv6StringCache.fullParams);\n\t\t}\n\t\treturn result;\n\t}", "public static String getTemplateMapperConfig(ServletRequest request) {\n\n String result = null;\n CmsTemplateContext templateContext = (CmsTemplateContext)request.getAttribute(\n CmsTemplateContextManager.ATTR_TEMPLATE_CONTEXT);\n if (templateContext != null) {\n I_CmsTemplateContextProvider provider = templateContext.getProvider();\n if (provider instanceof I_CmsTemplateMappingContextProvider) {\n result = ((I_CmsTemplateMappingContextProvider)provider).getMappingConfigurationPath(\n templateContext.getKey());\n }\n }\n return result;\n }" ]
Extract a list of time entries. @param shiftData string representation of time entries @return list of time entry rows
[ "private List<Row> createTimeEntryRowList(String shiftData) throws ParseException\n {\n List<Row> list = new ArrayList<Row>();\n String[] shifts = shiftData.split(\",|:\");\n int index = 1;\n while (index < shifts.length)\n {\n index += 2;\n int entryCount = Integer.parseInt(shifts[index]);\n index++;\n\n for (int entryIndex = 0; entryIndex < entryCount; entryIndex++)\n {\n Integer exceptionTypeID = Integer.valueOf(shifts[index + 0]);\n Date startTime = DatatypeConverter.parseBasicTime(shifts[index + 1]);\n Date endTime = DatatypeConverter.parseBasicTime(shifts[index + 2]);\n\n Map<String, Object> map = new HashMap<String, Object>();\n map.put(\"START_TIME\", startTime);\n map.put(\"END_TIME\", endTime);\n map.put(\"EXCEPTIOP\", exceptionTypeID);\n\n list.add(new MapRow(map));\n\n index += 3;\n }\n }\n\n return list;\n }" ]
[ "public 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 static void finishThread(){\r\n //--Create Task\r\n final long threadId = Thread.currentThread().getId();\r\n Runnable finish = new Runnable(){\r\n public void run(){\r\n releaseThreadControl(threadId);\r\n }\r\n };\r\n //--Run Task\r\n if(isThreaded){\r\n //(case: multithreaded)\r\n attemptThreadControl( threadId, finish );\r\n } else {\r\n //(case: no threading)\r\n throw new IllegalStateException(\"finishThreads() called outside of threaded environment\");\r\n }\r\n }", "public boolean ignoreOperation(final Resource domainResource, final Collection<ServerConfigInfo> serverConfigs, final PathAddress pathAddress) {\n if (pathAddress.size() == 0) {\n return false;\n }\n boolean ignore = ignoreResourceInternal(domainResource, serverConfigs, pathAddress);\n return ignore;\n }", "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}", "public void fire(StepEvent event) {\n Step step = stepStorage.getLast();\n event.process(step);\n\n notifier.fire(event);\n }", "public void render(OutputStream outputStream, Format format, int dpi) throws PrintingException {\n\t\ttry {\n\t\t\tif (baos == null) {\n\t\t\t\tprepare();\n\t\t\t}\n\t\t\twriteDocument(outputStream, format, dpi);\n\t\t} catch (Exception e) { // NOSONAR\n\t\t\tthrow new PrintingException(e, PrintingException.DOCUMENT_RENDER_PROBLEM);\n\t\t}\n\t}", "private Event createEvent(Endpoint endpoint, EventTypeEnum type) {\n\n Event event = new Event();\n MessageInfo messageInfo = new MessageInfo();\n Originator originator = new Originator();\n event.setMessageInfo(messageInfo);\n event.setOriginator(originator);\n\n Date date = new Date();\n event.setTimestamp(date);\n event.setEventType(type);\n\n messageInfo.setPortType(\n endpoint.getBinding().getBindingInfo().getService().getInterface().getName().toString());\n\n String transportType = null;\n if (endpoint.getBinding() instanceof SoapBinding) {\n SoapBinding soapBinding = (SoapBinding)endpoint.getBinding();\n if (soapBinding.getBindingInfo() instanceof SoapBindingInfo) {\n SoapBindingInfo soapBindingInfo = (SoapBindingInfo)soapBinding.getBindingInfo();\n transportType = soapBindingInfo.getTransportURI();\n }\n }\n messageInfo.setTransportType((transportType != null) ? transportType : \"Unknown transport type\");\n\n originator.setProcessId(Converter.getPID());\n try {\n InetAddress inetAddress = InetAddress.getLocalHost();\n originator.setIp(inetAddress.getHostAddress());\n originator.setHostname(inetAddress.getHostName());\n } catch (UnknownHostException e) {\n originator.setHostname(\"Unknown hostname\");\n originator.setIp(\"Unknown ip address\");\n }\n\n String address = endpoint.getEndpointInfo().getAddress();\n event.getCustomInfo().put(\"address\", address);\n\n return event;\n }", "private void updateDefaultTimeAndSizeRollingAppender(final FoundationFileRollingAppender appender) {\n\n\t\tif (appender.getDatePattern().trim().length() == 0) {\n\t\t\tappender.setDatePattern(FoundationLoggerConstants.DEFAULT_DATE_PATTERN.toString());\n\t\t}\n\t\t\n\t\tString maxFileSizeKey = \"log4j.appender.\"+appender.getName()+\".MaxFileSize\";\n\t\tappender.setMaxFileSize(FoundationLogger.log4jConfigProps.getProperty(maxFileSizeKey, FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString()));\n\n//\t\tif (appender.getMaxFileSize() == null || appender.getMaxFileSize().equals(FoundationLoggerConstants.DEFAULT_FILE_SIZE.toString())) {\n//\t\t\tappender.setMaxFileSize(FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString());\n//\t\t}\n\n\t\tString maxRollCountKey = \"log4j.appender.\"+appender.getName()+\".MaxRollFileCount\";\n\t\tappender.setMaxRollFileCount(Integer.parseInt(FoundationLogger.log4jConfigProps.getProperty(maxRollCountKey,\"100\")));\n\t}", "public static void writeCorrelationId(Message message, String correlationId) {\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n headers.put(CORRELATIONID_HTTP_HEADER_NAME, Collections.singletonList(correlationId));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + CORRELATIONID_HTTP_HEADER_NAME + \"' set to: \" + correlationId);\n }\n }" ]
Create the ResourceIgnoredTransformationRegistry when fetching missing content, only including relevant pieces to a server-config. @param rc the resolution context @param delegate the delegate ignored resource transformation registry for manually ignored resources @return
[ "public static Transformers.ResourceIgnoredTransformationRegistry createServerIgnoredRegistry(final RequiredConfigurationHolder rc, final Transformers.ResourceIgnoredTransformationRegistry delegate) {\n return new Transformers.ResourceIgnoredTransformationRegistry() {\n @Override\n public boolean isResourceTransformationIgnored(PathAddress address) {\n final int length = address.size();\n if (length == 0) {\n return false;\n } else if (length >= 1) {\n if (delegate.isResourceTransformationIgnored(address)) {\n return true;\n }\n\n final PathElement element = address.getElement(0);\n final String type = element.getKey();\n switch (type) {\n case ModelDescriptionConstants.EXTENSION:\n // Don't ignore extensions for now\n return false;\n// if (local) {\n// return false; // Always include all local extensions\n// } else if (rc.getExtensions().contains(element.getValue())) {\n// return false;\n// }\n// break;\n case ModelDescriptionConstants.PROFILE:\n if (rc.getProfiles().contains(element.getValue())) {\n return false;\n }\n break;\n case ModelDescriptionConstants.SERVER_GROUP:\n if (rc.getServerGroups().contains(element.getValue())) {\n return false;\n }\n break;\n case ModelDescriptionConstants.SOCKET_BINDING_GROUP:\n if (rc.getSocketBindings().contains(element.getValue())) {\n return false;\n }\n break;\n }\n }\n return true;\n }\n };\n }" ]
[ "public void setColorInterpolated(int index, int firstIndex, int lastIndex, int color) {\n\t\tint firstColor = map[firstIndex];\n\t\tint lastColor = map[lastIndex];\n\t\tfor (int i = firstIndex; i <= index; i++)\n\t\t\tmap[i] = ImageMath.mixColors((float)(i-firstIndex)/(index-firstIndex), firstColor, color);\n\t\tfor (int i = index; i < lastIndex; i++)\n\t\t\tmap[i] = ImageMath.mixColors((float)(i-index)/(lastIndex-index), color, lastColor);\n\t}", "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 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 byte[] concat(Bytes... listOfBytes) {\n int offset = 0;\n int size = 0;\n\n for (Bytes b : listOfBytes) {\n size += b.length() + checkVlen(b.length());\n }\n\n byte[] data = new byte[size];\n for (Bytes b : listOfBytes) {\n offset = writeVint(data, offset, b.length());\n b.copyTo(0, b.length(), data, offset);\n offset += b.length();\n }\n return data;\n }", "public IExternalAccess getAgentsExternalAccess(String agent_name) {\n\n return cmsService.getExternalAccess(getAgentID(agent_name)).get(\n new ThreadSuspendable());\n }", "private static Version getDockerVersion(String serverUrl) {\n try {\n DockerClient client = DockerClientBuilder.getInstance(serverUrl).build();\n return client.versionCmd().exec();\n } catch (Exception e) {\n return null;\n }\n }", "public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax,\n\t\t\tAbstractMeanSquaredDisplacmentEvaluator msdeval) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}", "public static ResourceResolutionContext context(ResourceResolutionComponent[] components,\n Map<String, Object> messageParams) {\n return new ResourceResolutionContext(components, messageParams);\n }", "public List<Addon> listAppAddons(String appName) {\n return connection.execute(new AppAddonsList(appName), apiKey);\n }" ]
Called just before the thread finishes, regardless of status, to take any necessary action on the downloaded file with mDownloadedCacheSize file. @param forceClean - It will delete downloaded cache, Even streaming is enabled, If user intentionally cancelled.
[ "private void cleanupDestination(DownloadRequest request, boolean forceClean) {\n if (!request.isResumable() || forceClean) {\n Log.d(\"cleanupDestination() deleting \" + request.getDestinationURI().getPath());\n File destinationFile = new File(request.getDestinationURI().getPath());\n if (destinationFile.exists()) {\n destinationFile.delete();\n }\n }\n }" ]
[ "public static AliasOperationTransformer replaceLastElement(final PathElement element) {\n return create(new AddressTransformer() {\n @Override\n public PathAddress transformAddress(final PathAddress original) {\n final PathAddress address = original.subAddress(0, original.size() -1);\n return address.append(element);\n }\n });\n }", "public static LayersConfig getLayersConfig(final File repoRoot) throws IOException {\n final File layersList = new File(repoRoot, LAYERS_CONF);\n if (!layersList.exists()) {\n return new LayersConfig();\n }\n final Properties properties = PatchUtils.loadProperties(layersList);\n return new LayersConfig(properties);\n }", "void close() {\n try {\n performTeardownExchange();\n } catch (IOException e) {\n logger.warn(\"Problem reporting our intention to close the dbserver connection\", e);\n }\n try {\n channel.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client output channel\", e);\n }\n try {\n os.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client output stream\", e);\n }\n try {\n is.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client input stream\", e);\n }\n try {\n socket.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client socket\", e);\n }\n }", "public static vlan[] get(nitro_service service) throws Exception{\n\t\tvlan obj = new vlan();\n\t\tvlan[] response = (vlan[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private int[] getPrimaryCodewords() {\r\n\r\n assert mode == 2 || mode == 3;\r\n\r\n if (primaryData.length() != 15) {\r\n throw new OkapiException(\"Invalid Primary String\");\r\n }\r\n\r\n for (int i = 9; i < 15; i++) { /* check that country code and service are numeric */\r\n if (primaryData.charAt(i) < '0' || primaryData.charAt(i) > '9') {\r\n throw new OkapiException(\"Invalid Primary String\");\r\n }\r\n }\r\n\r\n String postcode;\r\n if (mode == 2) {\r\n postcode = primaryData.substring(0, 9);\r\n int index = postcode.indexOf(' ');\r\n if (index != -1) {\r\n postcode = postcode.substring(0, index);\r\n }\r\n } else {\r\n // if (mode == 3)\r\n postcode = primaryData.substring(0, 6);\r\n }\r\n\r\n int country = Integer.parseInt(primaryData.substring(9, 12));\r\n int service = Integer.parseInt(primaryData.substring(12, 15));\r\n\r\n if (debug) {\r\n System.out.println(\"Using mode \" + mode);\r\n System.out.println(\" Postcode: \" + postcode);\r\n System.out.println(\" Country Code: \" + country);\r\n System.out.println(\" Service: \" + service);\r\n }\r\n\r\n if (mode == 2) {\r\n return getMode2PrimaryCodewords(postcode, country, service);\r\n } else { // mode == 3\r\n return getMode3PrimaryCodewords(postcode, country, service);\r\n }\r\n }", "@Override\n\tpublic boolean containsPrefixBlock(int prefixLength) {\n\t\tcheckSubnet(this, prefixLength);\n\t\tint divisionCount = getDivisionCount();\n\t\tint prevBitCount = 0;\n\t\tfor(int i = 0; i < divisionCount; i++) {\n\t\t\tAddressDivision division = getDivision(i);\n\t\t\tint bitCount = division.getBitCount();\n\t\t\tint totalBitCount = bitCount + prevBitCount;\n\t\t\tif(prefixLength < totalBitCount) {\n\t\t\t\tint divPrefixLen = Math.max(0, prefixLength - prevBitCount);\n\t\t\t\tif(!division.isPrefixBlock(division.getDivisionValue(), division.getUpperDivisionValue(), divPrefixLen)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tfor(++i; i < divisionCount; i++) {\n\t\t\t\t\tdivision = getDivision(i);\n\t\t\t\t\tif(!division.isFullRange()) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tprevBitCount = totalBitCount;\n\t\t}\n\t\treturn true;\n\t}", "public void setEnd(Date endDate) {\n\n if ((null == endDate) || getStart().after(endDate)) {\n m_explicitEnd = null;\n } else {\n m_explicitEnd = endDate;\n }\n }", "public void enqueue(SerialMessage serialMessage) {\n\t\tthis.sendQueue.add(serialMessage);\n\t\tlogger.debug(\"Enqueueing message. Queue length = {}\", this.sendQueue.size());\n\t}", "private RandomVariable getShortRate(int timeIndex) throws CalculationException {\n\t\tdouble time = getProcess().getTime(timeIndex);\n\t\tdouble timePrev = timeIndex > 0 ? getProcess().getTime(timeIndex-1) : time;\n\t\tdouble timeNext = getProcess().getTime(timeIndex+1);\n\n\t\tRandomVariable zeroRate = getZeroRateFromForwardCurve(time); //getDiscountFactorFromForwardCurve(time).div(getDiscountFactorFromForwardCurve(timeNext)).log().div(timeNext-time);\n\n\t\tRandomVariable alpha = getDV(0, time);\n\n\t\tRandomVariable value = getProcess().getProcessValue(timeIndex, 0);\n\t\tvalue = value.add(alpha);\n\t\t//\t\tvalue = value.sub(Math.log(value.exp().getAverage()));\n\n\t\tvalue = value.add(zeroRate);\n\n\t\treturn value;\n\t}" ]
Load a JSON file from the application's "asset" directory. @param context Valid {@link Context} @param asset Name of the JSON file @return New instance of {@link JSONObject}
[ "public static JSONObject loadJSONAsset(Context context, final String asset) {\n if (asset == null) {\n return new JSONObject();\n }\n return getJsonObject(org.gearvrf.widgetlib.main.Utility.readTextFile(context, asset));\n }" ]
[ "public MIMEType addParameter(String name, String value) {\n Map<String, String> copy = new LinkedHashMap<>(this.parameters);\n copy.put(name, value);\n return new MIMEType(type, subType, copy);\n }", "private boolean matchesFingerprint(byte[] buffer, Pattern fingerprint)\n {\n return fingerprint.matcher(m_charset == null ? new String(buffer) : new String(buffer, m_charset)).matches();\n }", "public void newLineIfNotEmpty() {\n\t\tfor (int i = segments.size() - 1; i >= 0; i--) {\n\t\t\tString segment = segments.get(i);\n\t\t\tif (lineDelimiter.equals(segment)) {\n\t\t\t\tsegments.subList(i + 1, segments.size()).clear();\n\t\t\t\tcachedToString = null;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (int j = 0; j < segment.length(); j++) {\n\t\t\t\tif (!WhitespaceMatcher.isWhitespace(segment.charAt(j))) {\n\t\t\t\t\tnewLine();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsegments.clear();\n\t\tcachedToString = null;\n\t}", "@NonNull\n private List<String> mapObsoleteElements(List<String> names) {\n List<String> elementsToRemove = new ArrayList<>(names.size());\n for (String name : names) {\n if (name.startsWith(\"android\")) continue;\n elementsToRemove.add(name);\n }\n return elementsToRemove;\n }", "private void addAnnotationValues(ClassReference annotatedReference, AnnotationClassReference typeRef, Annotation node)\n {\n Map<String, AnnotationValue> annotationValueMap = new HashMap<>();\n if (node instanceof SingleMemberAnnotation)\n {\n SingleMemberAnnotation singleMemberAnnotation = (SingleMemberAnnotation) node;\n AnnotationValue value = getAnnotationValueForExpression(annotatedReference, singleMemberAnnotation.getValue());\n annotationValueMap.put(\"value\", value);\n }\n else if (node instanceof NormalAnnotation)\n {\n @SuppressWarnings(\"unchecked\")\n List<MemberValuePair> annotationValues = ((NormalAnnotation) node).values();\n for (MemberValuePair annotationValue : annotationValues)\n {\n String key = annotationValue.getName().toString();\n Expression expression = annotationValue.getValue();\n AnnotationValue value = getAnnotationValueForExpression(annotatedReference, expression);\n annotationValueMap.put(key, value);\n }\n }\n typeRef.setAnnotationValues(annotationValueMap);\n }", "public static boolean uniform(Color color, Pixel[] pixels) {\n return Arrays.stream(pixels).allMatch(p -> p.toInt() == color.toRGB().toInt());\n }", "public ParallelTaskBuilder setSshPassword(String password) {\n this.sshMeta.setPassword(password);\n this.sshMeta.setSshLoginType(SshLoginType.PASSWORD);\n return this;\n }", "public static URL buildUrl(String scheme, String host, int port, String path, Map<String, String> parameters) throws MalformedURLException {\r\n checkSchemeAndPort(scheme, port);\r\n StringBuilder buffer = new StringBuilder();\r\n if (!host.startsWith(scheme + \"://\")) {\r\n buffer.append(scheme).append(\"://\");\r\n }\r\n buffer.append(host);\r\n if (port > 0) {\r\n buffer.append(':');\r\n buffer.append(port);\r\n }\r\n if (path == null) {\r\n path = \"/\";\r\n }\r\n buffer.append(path);\r\n\r\n if (!parameters.isEmpty()) {\r\n buffer.append('?');\r\n }\r\n int size = parameters.size();\r\n for (Map.Entry<String, String> entry : parameters.entrySet()) {\r\n buffer.append(entry.getKey());\r\n buffer.append('=');\r\n Object value = entry.getValue();\r\n if (value != null) {\r\n String string = value.toString();\r\n try {\r\n string = URLEncoder.encode(string, UTF8);\r\n } catch (UnsupportedEncodingException e) {\r\n // Should never happen, but just in case\r\n }\r\n buffer.append(string);\r\n }\r\n if (--size != 0) {\r\n buffer.append('&');\r\n }\r\n }\r\n\r\n /*\r\n * RequestContext requestContext = RequestContext.getRequestContext(); Auth auth = requestContext.getAuth(); if (auth != null &&\r\n * !ignoreMethod(getMethod(parameters))) { buffer.append(\"&api_sig=\"); buffer.append(AuthUtilities.getSignature(sharedSecret, parameters)); }\r\n */\r\n\r\n return new URL(buffer.toString());\r\n }", "public int getIntegerBelief(String name){\n Object belief = introspector.getBeliefBase(this).get(name);\n int count = 0;\n if (belief!=null) {\n count = (Integer) belief;\n }\n return (Integer) count;\n }" ]
Processes a runtime procedure argument tag. @param template The template @param attributes The attributes of the tag @exception XDocletException If an error occurs @doc.tag type="content" @doc.param name="attributes" optional="true" description="Attributes of the procedure as name-value pairs 'name=value', separated by commas" @doc.param name="documentation" optional="true" description="Documentation on the procedure" @doc.param name="field-ref" optional="true" description="Identifies the field that provides the value if a runtime argument; if not set, then null is used" @doc.param name="name" optional="false" description="The identifier of the argument tag" @doc.param name="return" optional="true" description="Whether this is a return value (if a runtime argument)" values="true,false" @doc.param name="value" optional="false" description="The value if a constant argument"
[ "public String processProcedureArgument(Properties attributes) throws XDocletException\r\n {\r\n String id = attributes.getProperty(ATTRIBUTE_NAME);\r\n ProcedureArgumentDef argDef = _curClassDef.getProcedureArgument(id);\r\n String attrName;\r\n \r\n if (argDef == null)\r\n { \r\n argDef = new ProcedureArgumentDef(id);\r\n _curClassDef.addProcedureArgument(argDef);\r\n }\r\n\r\n attributes.remove(ATTRIBUTE_NAME);\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n argDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }" ]
[ "public B set(String key, int value) {\n this.data.put(key, value);\n return (B) this;\n }", "public Boolean invoke(File pomFile, VirtualChannel channel) throws IOException, InterruptedException {\n\n org.jfrog.build.extractor.maven.reader.ModuleName current = new org.jfrog.build.extractor.maven.reader.ModuleName(\n currentModule.groupId, currentModule.artifactId);\n\n Map<org.jfrog.build.extractor.maven.reader.ModuleName, String> modules = Maps.newLinkedHashMap();\n for (Map.Entry<ModuleName, String> entry : versionsByModule.entrySet()) {\n modules.put(new org.jfrog.build.extractor.maven.reader.ModuleName(\n entry.getKey().groupId, entry.getKey().artifactId), entry.getValue());\n }\n\n org.jfrog.build.extractor.maven.transformer.PomTransformer transformer =\n new org.jfrog.build.extractor.maven.transformer.PomTransformer(current, modules, scmUrl,\n failOnSnapshot);\n\n return transformer.transform(pomFile);\n }", "public boolean overrides(Link other) {\n if (other.getStatus() == LinkStatus.ASSERTED &&\n status != LinkStatus.ASSERTED)\n return false;\n else if (status == LinkStatus.ASSERTED &&\n other.getStatus() != LinkStatus.ASSERTED)\n return true;\n\n // the two links are from equivalent sources of information, so we\n // believe the most recent\n\n return timestamp > other.getTimestamp();\n }", "public static final Long date2utc(Date date) {\n\n // use null for a null date\n if (date == null) return null;\n \n long time = date.getTime();\n \n // remove the timezone offset \n time -= timezoneOffsetMillis(date);\n \n return time;\n }", "private void highlightSlice(PieModel _Slice) {\n\n int color = _Slice.getColor();\n _Slice.setHighlightedColor(Color.argb(\n 0xff,\n Math.min((int) (mHighlightStrength * (float) Color.red(color)), 0xff),\n Math.min((int) (mHighlightStrength * (float) Color.green(color)), 0xff),\n Math.min((int) (mHighlightStrength * (float) Color.blue(color)), 0xff)\n ));\n }", "protected I_CmsSearchDocument createDefaultIndexDocument() {\n\n try {\n return m_index.getFieldConfiguration().createDocument(m_cms, m_res, m_index, null);\n } catch (CmsException e) {\n LOG.error(\n \"Default document for \"\n + m_res.getRootPath()\n + \" and index \"\n + m_index.getName()\n + \" could not be created.\",\n e);\n return null;\n }\n }", "private void writeResources()\n {\n for (Resource resource : m_projectFile.getResources())\n {\n if (resource.getUniqueID().intValue() != 0)\n {\n writeResource(resource);\n }\n }\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 }", "protected Element createLineElement(float x1, float y1, float x2, float y2)\n {\n HtmlDivLine line = new HtmlDivLine(x1, y1, x2, y2);\n String color = colorString(getGraphicsState().getStrokingColor());\n\n StringBuilder pstyle = new StringBuilder(50);\n pstyle.append(\"left:\").append(style.formatLength(line.getLeft())).append(';');\n pstyle.append(\"top:\").append(style.formatLength(line.getTop())).append(';');\n pstyle.append(\"width:\").append(style.formatLength(line.getWidth())).append(';');\n pstyle.append(\"height:\").append(style.formatLength(line.getHeight())).append(';');\n pstyle.append(line.getBorderSide()).append(':').append(style.formatLength(line.getLineStrokeWidth())).append(\" solid \").append(color).append(';');\n if (line.getAngleDegrees() != 0)\n pstyle.append(\"transform:\").append(\"rotate(\").append(line.getAngleDegrees()).append(\"deg);\");\n\n Element el = doc.createElement(\"div\");\n el.setAttribute(\"class\", \"r\");\n el.setAttribute(\"style\", pstyle.toString());\n el.appendChild(doc.createEntityReference(\"nbsp\"));\n return el;\n }" ]
Inserts the currently contained data objects into the database. @param platform The (connected) database platform for inserting data @param model The database model @param batchSize The batch size; use 1 for not using batch mode
[ "public void insert(Platform platform, Database model, int batchSize) throws SQLException\r\n {\r\n if (batchSize <= 1)\r\n {\r\n for (Iterator it = _beans.iterator(); it.hasNext();)\r\n {\r\n platform.insert(model, (DynaBean)it.next());\r\n }\r\n }\r\n else\r\n {\r\n for (int startIdx = 0; startIdx < _beans.size(); startIdx += batchSize)\r\n {\r\n platform.insert(model, _beans.subList(startIdx, startIdx + batchSize));\r\n }\r\n }\r\n }" ]
[ "public int color(Context ctx) {\n if (mColorInt == 0 && mColorRes != -1) {\n mColorInt = ContextCompat.getColor(ctx, mColorRes);\n }\n return mColorInt;\n }", "public static tmtrafficpolicy_tmglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\ttmtrafficpolicy_tmglobal_binding obj = new tmtrafficpolicy_tmglobal_binding();\n\t\tobj.set_name(name);\n\t\ttmtrafficpolicy_tmglobal_binding response[] = (tmtrafficpolicy_tmglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static systemsession[] get(nitro_service service) throws Exception{\n\t\tsystemsession obj = new systemsession();\n\t\tsystemsession[] response = (systemsession[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static boolean isRegularQueue(final Jedis jedis, final String key) {\n return LIST.equalsIgnoreCase(jedis.type(key));\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 Collection<Contact> getList() throws FlickrException {\r\n \t ContactList<Contact> contacts = new ContactList<Contact>();\r\n \r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element contactsElement = response.getPayload();\r\n contacts.setPage(contactsElement.getAttribute(\"page\"));\r\n contacts.setPages(contactsElement.getAttribute(\"pages\"));\r\n contacts.setPerPage(contactsElement.getAttribute(\"perpage\"));\r\n contacts.setTotal(contactsElement.getAttribute(\"total\"));\r\n NodeList contactNodes = contactsElement.getElementsByTagName(\"contact\");\r\n for (int i = 0; i < contactNodes.getLength(); i++) {\r\n Element contactElement = (Element) contactNodes.item(i);\r\n Contact contact = new Contact();\r\n contact.setId(contactElement.getAttribute(\"nsid\"));\r\n contact.setUsername(contactElement.getAttribute(\"username\"));\r\n contact.setRealName(contactElement.getAttribute(\"realname\"));\r\n contact.setFriend(\"1\".equals(contactElement.getAttribute(\"friend\")));\r\n contact.setFamily(\"1\".equals(contactElement.getAttribute(\"family\")));\r\n contact.setIgnored(\"1\".equals(contactElement.getAttribute(\"ignored\")));\r\n String lPathAlias = contactElement.getAttribute(\"path_alias\");\r\n contact.setPathAlias(lPathAlias == null || \"\".equals(lPathAlias) ? null : lPathAlias);\r\n contact.setOnline(OnlineStatus.fromType(contactElement.getAttribute(\"online\")));\r\n contact.setIconFarm(contactElement.getAttribute(\"iconfarm\"));\r\n contact.setIconServer(contactElement.getAttribute(\"iconserver\"));\r\n if (contact.getOnline() == OnlineStatus.AWAY) {\r\n contactElement.normalize();\r\n contact.setAwayMessage(XMLUtilities.getValue(contactElement));\r\n }\r\n contacts.add(contact);\r\n }\r\n return contacts;\r\n }", "public final Jar setAttribute(String section, String name, String value) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Manifest cannot be modified after entries are added.\");\n Attributes attr = getManifest().getAttributes(section);\n if (attr == null) {\n attr = new Attributes();\n getManifest().getEntries().put(section, attr);\n }\n attr.putValue(name, value);\n return this;\n }", "@Override\n public void handleExceptions(MessageEvent messageEvent, Exception exception) {\n\n if(exception instanceof InvalidMetadataException) {\n logger.error(\"Exception when deleting. The requested key does not exist in this partition\",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE,\n \"The requested key does not exist in this partition\");\n } else if(exception instanceof PersistenceFailureException) {\n logger.error(\"Exception when deleting. Operation failed\", exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n \"Operation failed\");\n } else if(exception instanceof UnsupportedOperationException) {\n logger.error(\"Exception when deleting. Operation not supported in read-only store \",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.METHOD_NOT_ALLOWED,\n \"Operation not supported in read-only store\");\n } else if(exception instanceof StoreTimeoutException) {\n String errorDescription = \"DELETE Request timed out: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent, HttpResponseStatus.REQUEST_TIMEOUT, errorDescription);\n } else if(exception instanceof InsufficientOperationalNodesException) {\n String errorDescription = \"DELETE Request failed: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n errorDescription);\n } else {\n super.handleExceptions(messageEvent, exception);\n }\n }", "public Bundler put(String key, String[] value) {\n delegate.putStringArray(key, value);\n return this;\n }" ]
Set virtual host so the server can direct the request. Value is the host header if it is set, otherwise use the hostname from the original request. @param httpMethodProxyRequest @param httpServletRequest
[ "private void processVirtualHostName(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest) {\n String virtualHostName;\n if (httpMethodProxyRequest.getRequestHeader(STRING_HOST_HEADER_NAME) != null) {\n virtualHostName = HttpUtilities.removePortFromHostHeaderString(httpMethodProxyRequest.getRequestHeader(STRING_HOST_HEADER_NAME).getValue());\n } else {\n virtualHostName = HttpUtilities.getHostNameFromURL(httpServletRequest.getRequestURL().toString());\n }\n httpMethodProxyRequest.getParams().setVirtualHost(virtualHostName);\n }" ]
[ "public Archetype parse(String adl) {\n try {\n return parse(new StringReader(adl));\n } catch (IOException e) {\n // StringReader should never throw an IOException\n throw new AssertionError(e);\n }\n }", "protected void associateBatched(Collection owners, Collection children)\r\n {\r\n ObjectReferenceDescriptor ord = getObjectReferenceDescriptor();\r\n ClassDescriptor cld = getOwnerClassDescriptor();\r\n Object owner;\r\n Object relatedObject;\r\n Object fkValues[];\r\n Identity id;\r\n PersistenceBroker pb = getBroker();\r\n PersistentField field = ord.getPersistentField();\r\n Class topLevelClass = pb.getTopLevelClass(ord.getItemClass());\r\n HashMap childrenMap = new HashMap(children.size());\r\n\r\n\r\n for (Iterator it = children.iterator(); it.hasNext(); )\r\n {\r\n relatedObject = it.next();\r\n childrenMap.put(pb.serviceIdentity().buildIdentity(relatedObject), relatedObject);\r\n }\r\n\r\n for (Iterator it = owners.iterator(); it.hasNext(); )\r\n {\r\n owner = it.next();\r\n fkValues = ord.getForeignKeyValues(owner,cld);\r\n if (isNull(fkValues))\r\n {\r\n field.set(owner, null);\r\n continue;\r\n }\r\n id = pb.serviceIdentity().buildIdentity(null, topLevelClass, fkValues);\r\n relatedObject = childrenMap.get(id);\r\n field.set(owner, relatedObject);\r\n }\r\n }", "protected PatchEntry resolveForElement(final PatchElement element) throws PatchingException {\n assert state == State.NEW;\n final PatchElementProvider provider = element.getProvider();\n final String layerName = provider.getName();\n final LayerType layerType = provider.getLayerType();\n\n final Map<String, PatchEntry> map;\n if (layerType == LayerType.Layer) {\n map = layers;\n } else {\n map = addOns;\n }\n PatchEntry entry = map.get(layerName);\n if (entry == null) {\n final InstallationManager.MutablePatchingTarget target = modification.resolve(layerName, layerType);\n if (target == null) {\n throw PatchLogger.ROOT_LOGGER.noSuchLayer(layerName);\n }\n entry = new PatchEntry(target, element);\n map.put(layerName, entry);\n }\n // Maintain the most recent element\n entry.updateElement(element);\n return entry;\n }", "public CollectionRequest<Task> getTasksWithTag(String tag) {\n \n String path = String.format(\"/tags/%s/tasks\", tag);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }", "public static systemuser[] get(nitro_service service) throws Exception{\n\t\tsystemuser obj = new systemuser();\n\t\tsystemuser[] response = (systemuser[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private void revisitGateways(Definitions def) {\n List<RootElement> rootElements = def.getRootElements();\n for (RootElement root : rootElements) {\n if (root instanceof Process) {\n setGatewayInfo((Process) root);\n }\n }\n }", "protected static boolean isOperatorLR( Symbol s ) {\n if( s == null )\n return false;\n\n switch( s ) {\n case ELEMENT_DIVIDE:\n case ELEMENT_TIMES:\n case ELEMENT_POWER:\n case RDIVIDE:\n case LDIVIDE:\n case TIMES:\n case POWER:\n case PLUS:\n case MINUS:\n case ASSIGN:\n return true;\n }\n return false;\n }", "public static <S extends Matrix, D extends Matrix> LinearSolver<S,D> safe(LinearSolver<S,D> solver ) {\n if( solver.modifiesA() || solver.modifiesB() ) {\n if( solver instanceof LinearSolverDense ) {\n return new LinearSolverSafe((LinearSolverDense)solver);\n } else if( solver instanceof LinearSolverSparse ) {\n return new LinearSolverSparseSafe((LinearSolverSparse)solver);\n } else {\n throw new IllegalArgumentException(\"Unknown solver type\");\n }\n } else {\n return solver;\n }\n }", "@UiThread\n public void collapseParentRange(int startParentPosition, int parentCount) {\n int endParentPosition = startParentPosition + parentCount;\n for (int i = startParentPosition; i < endParentPosition; i++) {\n collapseParent(i);\n }\n }" ]
Get the real Object for already materialized Handler @param objectOrProxy @return Object or null if the Handel is not materialized
[ "public Object getRealObjectIfMaterialized(Object objectOrProxy)\r\n {\r\n if(isNormalOjbProxy(objectOrProxy))\r\n {\r\n String msg;\r\n\r\n try\r\n {\r\n IndirectionHandler handler = getIndirectionHandler(objectOrProxy);\r\n\r\n return handler.alreadyMaterialized() ? handler.getRealSubject() : null;\r\n }\r\n catch(ClassCastException e)\r\n {\r\n // shouldn't happen but still ...\r\n msg = \"The InvocationHandler for the provided Proxy was not an instance of \" + IndirectionHandler.class.getName();\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(IllegalArgumentException e)\r\n {\r\n msg = \"Could not retrieve real object for given Proxy: \" + objectOrProxy;\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for given Proxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else if(isVirtualOjbProxy(objectOrProxy))\r\n {\r\n try\r\n {\r\n VirtualProxy proxy = (VirtualProxy) objectOrProxy;\r\n\r\n return proxy.alreadyMaterialized() ? proxy.getRealSubject() : null;\r\n }\r\n catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for VirtualProxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else\r\n {\r\n return objectOrProxy;\r\n }\r\n }" ]
[ "public static boolean reconnectContext(RedirectException re, CommandContext ctx) {\n boolean reconnected = false;\n try {\n ConnectionInfo info = ctx.getConnectionInfo();\n ControllerAddress address = null;\n if (info != null) {\n address = info.getControllerAddress();\n }\n if (address != null && isHttpsRedirect(re, address.getProtocol())) {\n LOG.debug(\"Trying to reconnect an http to http upgrade\");\n try {\n ctx.connectController();\n reconnected = true;\n } catch (Exception ex) {\n LOG.warn(\"Exception reconnecting\", ex);\n // Proper https redirect but error.\n // Ignoring it.\n }\n }\n } catch (URISyntaxException ex) {\n LOG.warn(\"Invalid URI: \", ex);\n // OK, invalid redirect.\n }\n return reconnected;\n }", "public void waitAndRetry() {\n ContinueToSendToBatchSenderAsstManager continueToSendToBatchSenderAsstManager = new ContinueToSendToBatchSenderAsstManager(\n processedWorkerCount);\n\n logger.debug(\"NOW WAIT Another \" + asstManagerRetryIntervalMillis\n + \" MS. at \" + PcDateUtils.getNowDateTimeStrStandard());\n getContext()\n .system()\n .scheduler()\n .scheduleOnce(\n Duration.create(asstManagerRetryIntervalMillis,\n TimeUnit.MILLISECONDS), getSelf(),\n continueToSendToBatchSenderAsstManager,\n getContext().system().dispatcher(), getSelf());\n return;\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 }", "protected Object getObjectFromResultSet() throws PersistenceBrokerException\r\n {\r\n\r\n try\r\n {\r\n // if all primitive attributes of the object are contained in the ResultSet\r\n // the fast direct mapping can be used\r\n return super.getObjectFromResultSet();\r\n }\r\n // if the full loading failed we assume that at least PK attributes are contained\r\n // in the ResultSet and perform a slower Identity based loading...\r\n // This may of course also fail and can throw another PersistenceBrokerException\r\n catch (PersistenceBrokerException e)\r\n {\r\n Identity oid = getIdentityFromResultSet();\r\n return getBroker().getObjectByIdentity(oid);\r\n }\r\n\r\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 }", "public String getAccuracyDescription(int numDigits) {\r\n NumberFormat nf = NumberFormat.getNumberInstance();\r\n nf.setMaximumFractionDigits(numDigits);\r\n Triple<Double, Integer, Integer> accu = getAccuracyInfo();\r\n return nf.format(accu.first()) + \" (\" + accu.second() + \"/\" + (accu.second() + accu.third()) + \")\";\r\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 }", "public void finalizeConfig() {\n assert !configFinalized;\n\n try {\n retrieveEngine();\n } catch (Exception e) {\n throw new RuntimeException(e.getMessage(), e);\n }\n configFinalized = true;\n }", "public void init( double diag[] ,\n double off[],\n int numCols ) {\n reset(numCols);\n\n this.diag = diag;\n this.off = off;\n }" ]
Get the root path where the build is located, the project may be checked out to a sub-directory from the root workspace location. @param globalEnv EnvVars to take the workspace from, if workspace is not found then it is take from project.getSomeWorkspace() @return The location of the root of the Gradle build. @throws IOException @throws InterruptedException
[ "public FilePath getModuleRoot(Map<String, String> globalEnv) throws IOException, InterruptedException {\n FilePath someWorkspace = project.getSomeWorkspace();\n if (someWorkspace == null) {\n throw new IllegalStateException(\"Couldn't find workspace\");\n }\n\n Map<String, String> workspaceEnv = Maps.newHashMap();\n workspaceEnv.put(\"WORKSPACE\", someWorkspace.getRemote());\n\n for (Builder builder : getBuilders()) {\n if (builder instanceof Gradle) {\n Gradle gradleBuilder = (Gradle) builder;\n String rootBuildScriptDir = gradleBuilder.getRootBuildScriptDir();\n if (rootBuildScriptDir != null && rootBuildScriptDir.trim().length() != 0) {\n String rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptDir.trim(), workspaceEnv);\n rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptNormalized, globalEnv);\n return new FilePath(someWorkspace, rootBuildScriptNormalized);\n } else {\n return someWorkspace;\n }\n }\n }\n\n throw new IllegalArgumentException(\"Couldn't find Gradle builder in the current builders list\");\n }" ]
[ "public static base_response delete(nitro_service client, String sitename) throws Exception {\n\t\tgslbsite deleteresource = new gslbsite();\n\t\tdeleteresource.sitename = sitename;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public double getDouble(Integer id, Integer type)\n {\n double result = Double.longBitsToDouble(getLong(id, type));\n if (Double.isNaN(result))\n {\n result = 0;\n }\n return result;\n }", "private void lockLocalization(Locale l) throws CmsException {\n\n if (null == m_lockedBundleFiles.get(l)) {\n LockedFile lf = LockedFile.lockResource(m_cms, m_bundleFiles.get(l));\n m_lockedBundleFiles.put(l, lf);\n }\n\n }", "@SafeVarargs\n\tpublic static <T> Set<T> asSet(T... ts) {\n\t\tif ( ts == null ) {\n\t\t\treturn null;\n\t\t}\n\t\telse if ( ts.length == 0 ) {\n\t\t\treturn Collections.emptySet();\n\t\t}\n\t\telse {\n\t\t\tSet<T> set = new HashSet<T>( getInitialCapacityFromExpectedSize( ts.length ) );\n\t\t\tCollections.addAll( set, ts );\n\t\t\treturn Collections.unmodifiableSet( set );\n\t\t}\n\t}", "@SuppressWarnings(\"deprecation\")\n public ResponseFromManager sendTaskToExecutionManager(ParallelTask task) {\n\n ResponseFromManager commandResponseFromManager = null;\n ActorRef executionManager = null;\n try {\n // Start new job\n logger.info(\"!!STARTED sendAgentCommandToManager : \"\n + task.getTaskId() + \" at \"\n + PcDateUtils.getNowDateTimeStr());\n\n executionManager = ActorConfig.createAndGetActorSystem().actorOf(\n Props.create(ExecutionManager.class, task),\n \"ExecutionManager-\" + task.getTaskId());\n\n final FiniteDuration duration = Duration.create(task.getConfig()\n .getTimeoutAskManagerSec(), TimeUnit.SECONDS);\n // Timeout timeout = new\n // Timeout(FiniteDuration.parse(\"300 seconds\"));\n Future<Object> future = Patterns.ask(executionManager,\n new InitialRequestToManager(task), new Timeout(duration));\n\n // set ref\n task.executionManager = executionManager;\n\n commandResponseFromManager = (ResponseFromManager) Await.result(\n future, duration);\n\n logger.info(\"!!COMPLETED sendTaskToExecutionManager : \"\n + task.getTaskId() + \" at \"\n + PcDateUtils.getNowDateTimeStr()\n + \" \\t\\t GenericResponseMap in future size: \"\n + commandResponseFromManager.getResponseCount());\n\n } catch (Exception ex) {\n logger.error(\"Exception in sendTaskToExecutionManager {} details {}: \",\n ex, ex);\n\n } finally {\n // stop the manager\n if (executionManager != null && !executionManager.isTerminated()) {\n ActorConfig.createAndGetActorSystem().stop(executionManager);\n }\n\n if (task.getConfig().isAutoSaveLogToLocal()) {\n task.saveLogToLocal();\n }\n\n }\n\n return commandResponseFromManager;\n\n }", "public static boolean isAvailable() throws Exception {\n try {\n Registry myRegistry = LocateRegistry.getRegistry(\"127.0.0.1\", port);\n com.groupon.odo.proxylib.hostsedit.rmi.Message impl = (com.groupon.odo.proxylib.hostsedit.rmi.Message) myRegistry.lookup(SERVICE_NAME);\n return true;\n } catch (Exception e) {\n return false;\n }\n }", "static void backupDirectory(final File source, final File target) throws IOException {\n if (!target.exists()) {\n if (!target.mkdirs()) {\n throw PatchLogger.ROOT_LOGGER.cannotCreateDirectory(target.getAbsolutePath());\n }\n }\n final File[] files = source.listFiles(CONFIG_FILTER);\n for (final File file : files) {\n final File t = new File(target, file.getName());\n IoUtils.copyFile(file, t);\n }\n }", "public Set<PlaybackState> getPlaybackState() {\n Set<PlaybackState> result = new HashSet<PlaybackState>(playbackStateMap.values());\n return Collections.unmodifiableSet(result);\n }", "public base_response enable_modes(String[] modes) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsmode resource = new nsmode();\n\t\tresource.set_mode(modes);\n\t\toptions option = new options();\n\t\toption.set_action(\"enable\");\n\t\tresult = resource.perform_operation(this, option);\n\t\treturn result;\n\t}" ]
Handles the deletion of a key. @param key the deleted key. @return <code>true</code> if the deletion was successful, <code>false</code> otherwise.
[ "public boolean handleKeyDeletion(final String key) {\n\n if (m_keyset.getKeySet().contains(key)) {\n if (removeKeyForAllLanguages(key)) {\n m_keyset.removeKey(key);\n return true;\n } else {\n return false;\n }\n }\n return true;\n }" ]
[ "public static Duration getVariance(Task task, Date date1, Date date2, TimeUnit format)\n {\n Duration variance = null;\n\n if (date1 != null && date2 != null)\n {\n ProjectCalendar calendar = task.getEffectiveCalendar();\n if (calendar != null)\n {\n variance = calendar.getWork(date1, date2, format);\n }\n }\n\n if (variance == null)\n {\n variance = Duration.getInstance(0, format);\n }\n\n return (variance);\n }", "public DownloadRequest addCustomHeader(String key, String value) {\n mCustomHeader.put(key, value);\n return this;\n }", "@Pure\n\tpublic static <P1, P2, P3> Procedure2<P2, P3> curry(final Procedure3<? super P1, ? super P2, ? super P3> procedure, final P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure2<P2, P3>() {\n\t\t\t@Override\n\t\t\tpublic void apply(P2 p2, P3 p3) {\n\t\t\t\tprocedure.apply(argument, p2, p3);\n\t\t\t}\n\t\t};\n\t}", "private D createAndRegisterDeclaration(Map<String, Object> metadata) {\n D declaration;\n if (klass.equals(ImportDeclaration.class)) {\n declaration = (D) ImportDeclarationBuilder.fromMetadata(metadata).build();\n } else if (klass.equals(ExportDeclaration.class)) {\n declaration = (D) ExportDeclarationBuilder.fromMetadata(metadata).build();\n } else {\n throw new IllegalStateException(\"\");\n }\n declarationRegistrationManager.registerDeclaration(declaration);\n return declaration;\n }", "public Photo getListPhoto(String photoId) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_LIST_PHOTO);\n\n parameters.put(\"photo_id\", photoId);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element photoElement = response.getPayload();\n Photo photo = new Photo();\n photo.setId(photoElement.getAttribute(\"id\"));\n\n List<Tag> tags = new ArrayList<Tag>();\n Element tagsElement = (Element) photoElement.getElementsByTagName(\"tags\").item(0);\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag tag = new Tag();\n tag.setId(tagElement.getAttribute(\"id\"));\n tag.setAuthor(tagElement.getAttribute(\"author\"));\n tag.setAuthorName(tagElement.getAttribute(\"authorname\"));\n tag.setRaw(tagElement.getAttribute(\"raw\"));\n tag.setValue(((Text) tagElement.getFirstChild()).getData());\n tags.add(tag);\n }\n photo.setTags(tags);\n return photo;\n }", "public void logWarning(final String message) {\n messageQueue.add(new LogEntry() {\n @Override\n public String getMessage() {\n return message;\n }\n });\n }", "public ReferrerList getCollectionReferrers(Date date, String domain, String collectionId, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_COLLECTION_REFERRERS, domain, \"collection_id\", collectionId, date, perPage, page);\n }", "public static boolean decomposeQR_block_col( final int blockLength ,\n final DSubmatrixD1 Y ,\n final double gamma[] )\n {\n int width = Y.col1-Y.col0;\n int height = Y.row1-Y.row0;\n int min = Math.min(width,height);\n for( int i = 0; i < min; i++ ) {\n // compute the householder vector\n if (!computeHouseHolderCol(blockLength, Y, gamma, i))\n return false;\n\n // apply to rest of the columns in the block\n rank1UpdateMultR_Col(blockLength,Y,i,gamma[Y.col0+i]);\n }\n\n return true;\n }", "public void load(List<E> result) {\n ++pageCount;\n if (this.result == null || this.result.isEmpty()) {\n this.result = result;\n } else {\n this.result.addAll(result);\n }\n }" ]
List the slack values for each task. @param file ProjectFile instance
[ "private static void listSlack(ProjectFile file)\n {\n for (Task task : file.getTasks())\n {\n System.out.println(task.getName() + \" Total Slack=\" + task.getTotalSlack() + \" Start Slack=\" + task.getStartSlack() + \" Finish Slack=\" + task.getFinishSlack());\n }\n }" ]
[ "public static BufferedImage createImage(ImageProducer producer) {\n\t\tPixelGrabber pg = new PixelGrabber(producer, 0, 0, -1, -1, null, 0, 0);\n\t\ttry {\n\t\t\tpg.grabPixels();\n\t\t} catch (InterruptedException e) {\n\t\t\tthrow new RuntimeException(\"Image fetch interrupted\");\n\t\t}\n\t\tif ((pg.status() & ImageObserver.ABORT) != 0)\n\t\t\tthrow new RuntimeException(\"Image fetch aborted\");\n\t\tif ((pg.status() & ImageObserver.ERROR) != 0)\n\t\t\tthrow new RuntimeException(\"Image fetch error\");\n\t\tBufferedImage p = new BufferedImage(pg.getWidth(), pg.getHeight(), BufferedImage.TYPE_INT_ARGB);\n\t\tp.setRGB(0, 0, pg.getWidth(), pg.getHeight(), (int[])pg.getPixels(), 0, pg.getWidth());\n\t\treturn p;\n\t}", "public static final Integer parseMinutesFromHours(String value)\n {\n Integer result = null;\n if (value != null)\n {\n result = Integer.valueOf(Integer.parseInt(value) * 60);\n }\n return result;\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 }", "public static void deleteRecursively(final Path path) throws IOException {\n DeploymentRepositoryLogger.ROOT_LOGGER.debugf(\"Deleting %s recursively\", path);\n if (Files.exists(path)) {\n Files.walkFileTree(path, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n Files.delete(file);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n DeploymentRepositoryLogger.ROOT_LOGGER.cannotDeleteFile(exc, path);\n throw exc;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n Files.delete(dir);\n return FileVisitResult.CONTINUE;\n }\n });\n }\n }", "public void signOff(String key, WebSocketConnection connection) {\n ConcurrentMap<WebSocketConnection, WebSocketConnection> connections = registry.get(key);\n if (null == connections) {\n return;\n }\n connections.remove(connection);\n }", "public void add(String photoId, String userId, Rectangle bounds) throws FlickrException {\r\n\r\n // Delegating this to photos.people.PeopleInterface - Naming standard would be to use PeopleInterface but having 2 the same name can cause issues\r\n com.flickr4java.flickr.photos.people.PeopleInterface pi = new com.flickr4java.flickr.photos.people.PeopleInterface(apiKey, sharedSecret, transportAPI);\r\n pi.add(photoId, userId, bounds);\r\n }", "public void process(ProjectProperties properties, FilterContainer filters, FixedData fixedData, Var2Data varData)\n {\n int filterCount = fixedData.getItemCount();\n boolean[] criteriaType = new boolean[2];\n CriteriaReader criteriaReader = getCriteriaReader();\n\n for (int filterLoop = 0; filterLoop < filterCount; filterLoop++)\n {\n byte[] filterFixedData = fixedData.getByteArrayValue(filterLoop);\n if (filterFixedData == null || filterFixedData.length < 4)\n {\n continue;\n }\n\n Filter filter = new Filter();\n filter.setID(Integer.valueOf(MPPUtility.getInt(filterFixedData, 0)));\n filter.setName(MPPUtility.removeAmpersands(MPPUtility.getUnicodeString(filterFixedData, 4)));\n byte[] filterVarData = varData.getByteArray(filter.getID(), getVarDataType());\n if (filterVarData == null)\n {\n continue;\n }\n\n //System.out.println(ByteArrayHelper.hexdump(filterVarData, true, 16, \"\"));\n List<GenericCriteriaPrompt> prompts = new LinkedList<GenericCriteriaPrompt>();\n\n filter.setShowRelatedSummaryRows(MPPUtility.getByte(filterVarData, 4) != 0);\n filter.setCriteria(criteriaReader.process(properties, filterVarData, 0, -1, prompts, null, criteriaType));\n\n filter.setIsTaskFilter(criteriaType[0]);\n filter.setIsResourceFilter(criteriaType[1]);\n filter.setPrompts(prompts);\n\n filters.addFilter(filter);\n //System.out.println(filter);\n }\n }", "public boolean isConnectionHandleAlive(ConnectionHandle connection) {\r\n\t\tStatement stmt = null;\r\n\t\tboolean result = false;\r\n\t\tboolean logicallyClosed = connection.logicallyClosed.get();\r\n\t\ttry {\r\n\t\t\tconnection.logicallyClosed.compareAndSet(true, false); // avoid checks later on if it's marked as closed.\r\n\t\t\tString testStatement = this.config.getConnectionTestStatement();\r\n\t\t\tResultSet rs = null;\r\n\r\n\t\t\tif (testStatement == null) {\r\n\t\t\t\t// Make a call to fetch the metadata instead of a dummy query.\r\n\t\t\t\trs = connection.getMetaData().getTables( null, null, KEEPALIVEMETADATA, METADATATABLE );\r\n\t\t\t} else {\r\n\t\t\t\tstmt = connection.createStatement();\r\n\t\t\t\tstmt.execute(testStatement);\r\n\t\t\t}\r\n\r\n\r\n\t\t\tif (rs != null) {\r\n\t\t\t\trs.close();\r\n\t\t\t}\r\n\r\n\t\t\tresult = true;\r\n\t\t} catch (SQLException e) {\r\n\t\t\t// connection must be broken!\r\n\t\t\tresult = false;\r\n\t\t} finally {\r\n\t\t\tconnection.logicallyClosed.set(logicallyClosed);\r\n\t\t\tconnection.setConnectionLastResetInMs(System.currentTimeMillis());\r\n\t\t\tresult = closeStatement(stmt, result);\r\n\t\t}\r\n\t\treturn result;\r\n\t}", "private String extractNumericVersion(Collection<String> versionStrings) {\n if (versionStrings == null) {\n return \"\";\n }\n for (String value : versionStrings) {\n String releaseValue = calculateReleaseVersion(value);\n if (!releaseValue.equals(value)) {\n return releaseValue;\n }\n }\n return \"\";\n }" ]
add an Extent class to the current descriptor @param newExtentClassName name of the class to add
[ "public void addExtentClass(String newExtentClassName)\r\n {\r\n extentClassNames.add(newExtentClassName);\r\n if(m_repository != null) m_repository.addExtent(newExtentClassName, this);\r\n }" ]
[ "public Where<T, ID> reset() {\n\t\tfor (int i = 0; i < clauseStackLevel; i++) {\n\t\t\t// help with gc\n\t\t\tclauseStack[i] = null;\n\t\t}\n\t\tclauseStackLevel = 0;\n\t\treturn this;\n\t}", "public static final Integer getInteger(Number value)\n {\n Integer result = null;\n if (value != null)\n {\n if (value instanceof Integer)\n {\n result = (Integer) value;\n }\n else\n {\n result = Integer.valueOf((int) Math.round(value.doubleValue()));\n }\n }\n return (result);\n }", "public ResponseOnSingeRequest genErrorResponse(Exception t) {\n ResponseOnSingeRequest sshResponse = new ResponseOnSingeRequest();\n String displayError = PcErrorMsgUtils.replaceErrorMsg(t.toString());\n\n sshResponse.setStackTrace(PcStringUtils.printStackTrace(t));\n sshResponse.setErrorMessage(displayError);\n sshResponse.setFailObtainResponse(true);\n\n logger.error(\"error in exec SSH. \\nIf exection is JSchException: \"\n + \"Auth cancel and using public key. \"\n + \"\\nMake sure 1. private key full path is right (try sshMeta.getPrivKeyAbsPath()). \"\n + \"\\n2. the user name and key matches \" + t);\n\n return sshResponse;\n }", "private static DataHandler getDataHandlerForString(Event event) {\n try {\n return new DataHandler(new ByteDataSource(event.getContent().getBytes(\"UTF-8\")));\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n }", "@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 }", "synchronized public String getPrettyProgressBar() {\n StringBuilder sb = new StringBuilder();\n\n double taskRate = numTasksCompleted / (double) totalTaskCount;\n double partitionStoreRate = numPartitionStoresMigrated / (double) totalPartitionStoreCount;\n\n long deltaTimeMs = System.currentTimeMillis() - startTimeMs;\n long taskTimeRemainingMs = Long.MAX_VALUE;\n if(taskRate > 0) {\n taskTimeRemainingMs = (long) (deltaTimeMs * ((1.0 / taskRate) - 1.0));\n }\n long partitionStoreTimeRemainingMs = Long.MAX_VALUE;\n if(partitionStoreRate > 0) {\n partitionStoreTimeRemainingMs = (long) (deltaTimeMs * ((1.0 / partitionStoreRate) - 1.0));\n }\n\n // Title line\n sb.append(\"Progress update on rebalancing batch \" + batchId).append(Utils.NEWLINE);\n // Tasks in flight update\n sb.append(\"There are currently \" + tasksInFlight.size() + \" rebalance tasks executing: \")\n .append(tasksInFlight)\n .append(\".\")\n .append(Utils.NEWLINE);\n // Tasks completed update\n sb.append(\"\\t\" + numTasksCompleted + \" out of \" + totalTaskCount\n + \" rebalance tasks complete.\")\n .append(Utils.NEWLINE)\n .append(\"\\t\")\n .append(decimalFormatter.format(taskRate * 100.0))\n .append(\"% done, estimate \")\n .append(taskTimeRemainingMs)\n .append(\" ms (\")\n .append(TimeUnit.MILLISECONDS.toMinutes(taskTimeRemainingMs))\n .append(\" minutes) remaining.\")\n .append(Utils.NEWLINE);\n // Partition-stores migrated update\n sb.append(\"\\t\" + numPartitionStoresMigrated + \" out of \" + totalPartitionStoreCount\n + \" partition-stores migrated.\")\n .append(Utils.NEWLINE)\n .append(\"\\t\")\n .append(decimalFormatter.format(partitionStoreRate * 100.0))\n .append(\"% done, estimate \")\n .append(partitionStoreTimeRemainingMs)\n .append(\" ms (\")\n .append(TimeUnit.MILLISECONDS.toMinutes(partitionStoreTimeRemainingMs))\n .append(\" minutes) remaining.\")\n .append(Utils.NEWLINE);\n return sb.toString();\n }", "public void check(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureNoTableInfoIfNoRepositoryInfo(classDef, checkLevel);\r\n checkModifications(classDef, checkLevel);\r\n checkExtents(classDef, checkLevel);\r\n ensureTableIfNecessary(classDef, checkLevel);\r\n checkFactoryClassAndMethod(classDef, checkLevel);\r\n checkInitializationMethod(classDef, checkLevel);\r\n checkPrimaryKey(classDef, checkLevel);\r\n checkProxyPrefetchingLimit(classDef, checkLevel);\r\n checkRowReader(classDef, checkLevel);\r\n checkObjectCache(classDef, checkLevel);\r\n checkProcedures(classDef, checkLevel);\r\n }", "private void modifyBeliefCount(int count){\n introspector.setBeliefValue(getLocalName(), Definitions.RECEIVED_MESSAGE_COUNT, getBeliefCount()+count, null);\n }", "private Component createAddKeyButton() {\n\n // the \"+\" button\n Button addKeyButton = new Button();\n addKeyButton.addStyleName(\"icon-only\");\n addKeyButton.addStyleName(\"borderless-colored\");\n addKeyButton.setDescription(m_messages.key(Messages.GUI_ADD_KEY_0));\n addKeyButton.setIcon(FontOpenCms.CIRCLE_PLUS, m_messages.key(Messages.GUI_ADD_KEY_0));\n addKeyButton.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n handleAddKey();\n\n }\n });\n return addKeyButton;\n }" ]
Converts this address to a prefix length @return the prefix of the indicated IP type represented by this address or null if this address is valid but cannot be represented by a network prefix length @throws AddressStringException if the address is invalid
[ "public String convertToPrefixLength() throws AddressStringException {\n\t\tIPAddress address = toAddress();\n\t\tInteger prefix;\n\t\tif(address == null) {\n\t\t\tif(isPrefixOnly()) {\n\t\t\t\tprefix = getNetworkPrefixLength();\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} else {\n\t\t\tprefix = address.getBlockMaskPrefixLength(true);\n\t\t\tif(prefix == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn IPAddressSegment.toUnsignedString(prefix, 10, \n\t\t\t\tnew StringBuilder(IPAddressSegment.toUnsignedStringLength(prefix, 10) + 1).append(IPAddress.PREFIX_LEN_SEPARATOR)).toString();\n\t}" ]
[ "public static <T extends Number> int[] asArray(final T... array) {\n int[] b = new int[array.length];\n for (int i = 0; i < b.length; i++) {\n b[i] = array[i].intValue();\n }\n return b;\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 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 CustomHeadersInterceptor addHeaderMultimap(Map<String, List<String>> headers) {\n this.headers.putAll(headers);\n return this;\n }", "public boolean isIdentical(T a, double tol) {\n if( a.getType() != getType() )\n return false;\n return ops.isIdentical(mat,a.mat,tol);\n }", "private boolean isDepOfIdlArtifact(Artifact artifact, Map<String, Artifact> depsMap) {\n List<String> depTrail = artifact.getDependencyTrail();\n // depTrail can be null sometimes, which seems like a maven bug\n if (depTrail != null) {\n for (String name : depTrail) {\n Artifact dep = depsMap.get(name);\n if (dep != null && isIdlCalssifier(dep, classifier)) {\n return true;\n }\n }\n }\n return false;\n }", "protected void capture3DScreenShot(GVRRenderTarget renderTarget, boolean isMultiview) {\n if (mScreenshot3DCallback == null) {\n return;\n }\n final Bitmap[] bitmaps = new Bitmap[6];\n renderSixCamerasAndReadback(mMainScene.getMainCameraRig(), bitmaps, renderTarget, isMultiview);\n returnScreenshot3DToCaller(mScreenshot3DCallback, bitmaps, mReadbackBufferWidth, mReadbackBufferHeight);\n\n mScreenshot3DCallback = null;\n }", "@UiThread\n public int getParentAdapterPosition() {\n int flatPosition = getAdapterPosition();\n if (flatPosition == RecyclerView.NO_POSITION) {\n return flatPosition;\n }\n\n return mExpandableAdapter.getNearestParentPosition(flatPosition);\n }", "protected void updateModel(final OperationContext context, final ModelNode operation) throws OperationFailedException {\n // verify that the resource exist before removing it\n context.readResource(PathAddress.EMPTY_ADDRESS, false);\n Resource resource = context.removeResource(PathAddress.EMPTY_ADDRESS);\n recordCapabilitiesAndRequirements(context, operation, resource);\n }" ]
compute Cosh using Taylor Series. @param x An angle, in radians. @param nTerms Number of terms. @return Result.
[ "public static double Cosh(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return 1 + (x * x) / 2D;\r\n } else {\r\n\r\n double mult = x * x;\r\n double fact = 2;\r\n int factS = 4;\r\n double result = 1 + mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += mult / fact;\r\n }\r\n\r\n return result;\r\n }\r\n }" ]
[ "public void notifyHeaderItemRangeRemoved(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \" + (positionStart + itemCount - 1) + \"] is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemRangeRemoved(positionStart, itemCount);\n }", "protected EntityKey getEntityKey(Tuple tuple, AssociatedEntityKeyMetadata associatedEntityKeyMetadata) {\n\t\tObject[] columnValues = new Object[ associatedEntityKeyMetadata.getAssociationKeyColumns().length];\n\t\tint i = 0;\n\n\t\tfor ( String associationKeyColumn : associatedEntityKeyMetadata.getAssociationKeyColumns() ) {\n\t\t\tcolumnValues[i] = tuple.get( associationKeyColumn );\n\t\t\ti++;\n\t\t}\n\n\t\treturn new EntityKey( associatedEntityKeyMetadata.getEntityKeyMetadata(), columnValues );\n\t}", "public void setShortAttribute(String name, Short value) {\n\t\tensureValue();\n\t\tAttribute attribute = new ShortAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}", "protected void runScript(File script) {\n if (!script.exists()) {\n JOptionPane.showMessageDialog(cliGuiCtx.getMainPanel(), script.getAbsolutePath() + \" does not exist.\",\n \"Unable to run script.\", JOptionPane.ERROR_MESSAGE);\n return;\n }\n\n int choice = JOptionPane.showConfirmDialog(cliGuiCtx.getMainPanel(), \"Run CLI script \" + script.getName() + \"?\",\n \"Confirm run script\", JOptionPane.YES_NO_OPTION);\n if (choice != JOptionPane.YES_OPTION) return;\n\n menu.addScript(script);\n\n cliGuiCtx.getTabs().setSelectedIndex(1); // set to Output tab to view the output\n output.post(\"\\n\");\n\n SwingWorker scriptRunner = new ScriptRunner(script);\n scriptRunner.execute();\n }", "private List getColumns(List fields)\r\n {\r\n ArrayList columns = new ArrayList();\r\n\r\n for (Iterator it = fields.iterator(); it.hasNext();)\r\n {\r\n FieldDescriptorDef fieldDef = (FieldDescriptorDef)it.next();\r\n\r\n columns.add(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN));\r\n }\r\n return columns;\r\n }", "public Iterable<? extends WindupVertexFrame> findVariable(String name, int maxDepth)\n {\n int currentDepth = 0;\n Iterable<? extends WindupVertexFrame> result = null;\n for (Map<String, Iterable<? extends WindupVertexFrame>> frame : deque)\n {\n result = frame.get(name);\n if (result != null)\n {\n break;\n }\n currentDepth++;\n if (currentDepth >= maxDepth)\n break;\n }\n return result;\n }", "private TableAlias getTableAliasForPath(String aPath, List hintClasses)\r\n {\r\n return (TableAlias) m_pathToAlias.get(buildAliasKey(aPath, hintClasses));\r\n }", "private String computeMorse(BytesRef term) {\n StringBuilder stringBuilder = new StringBuilder();\n int i = term.offset + prefixOffset;\n for (; i < term.length; i++) {\n if (ALPHABET_MORSE.containsKey(term.bytes[i])) {\n stringBuilder.append(ALPHABET_MORSE.get(term.bytes[i]) + \" \");\n } else if(term.bytes[i]!=0x00){\n return null;\n } else {\n break;\n }\n }\n return stringBuilder.toString();\n }", "public static void checkDelegateType(Decorator<?> decorator) {\n\n Set<Type> types = new HierarchyDiscovery(decorator.getDelegateType()).getTypeClosure();\n\n for (Type decoratedType : decorator.getDecoratedTypes()) {\n if(!types.contains(decoratedType)) {\n throw BeanLogger.LOG.delegateMustSupportEveryDecoratedType(decoratedType, decorator);\n }\n }\n }" ]
Use this API to fetch authenticationldappolicy_authenticationvserver_binding resources of given name .
[ "public static authenticationldappolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationldappolicy_authenticationvserver_binding obj = new authenticationldappolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationldappolicy_authenticationvserver_binding response[] = (authenticationldappolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public static base_responses unset(nitro_service client, String ipaddress[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (ipaddress != null && ipaddress.length > 0) {\n\t\t\tnsrpcnode unsetresources[] = new nsrpcnode[ipaddress.length];\n\t\t\tfor (int i=0;i<ipaddress.length;i++){\n\t\t\t\tunsetresources[i] = new nsrpcnode();\n\t\t\t\tunsetresources[i].ipaddress = ipaddress[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "protected void failedToCleanupDir(final File file) {\n checkForGarbageOnRestart = true;\n PatchLogger.ROOT_LOGGER.cannotDeleteFile(file.getAbsolutePath());\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 }", "public FieldLocation getFieldLocation(FieldType type)\n {\n FieldLocation result = null;\n\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getFieldLocation();\n }\n return result;\n }", "public boolean load(GVRScene scene)\n {\n GVRAssetLoader loader = getGVRContext().getAssetLoader();\n\n if (scene == null)\n {\n scene = getGVRContext().getMainScene();\n }\n if (mReplaceScene)\n {\n loader.loadScene(getOwnerObject(), mVolume, mImportSettings, scene, null);\n }\n else\n {\n loader.loadModel(getOwnerObject(), mVolume, mImportSettings, scene);\n }\n return true;\n }", "public ObjectReferenceDescriptor getObjectReferenceDescriptorByName(String name)\r\n {\r\n ObjectReferenceDescriptor ord = (ObjectReferenceDescriptor)\r\n getObjectReferenceDescriptorsNameMap().get(name);\r\n\r\n //\r\n // BRJ: if the ReferenceDescriptor is not found\r\n // look in the ClassDescriptor referenced by 'super' for it\r\n //\r\n if (ord == null)\r\n {\r\n ClassDescriptor superCld = getSuperClassDescriptor();\r\n if (superCld != null)\r\n {\r\n ord = superCld.getObjectReferenceDescriptorByName(name);\r\n }\r\n }\r\n return ord;\r\n }", "public static int[] arrayFromStringOfIntegers(String str) throws IllegalArgumentException {\n StringTokenizer tokenizer = new StringTokenizer(str, \",\");\n int n = tokenizer.countTokens();\n int[] list = new int[n];\n for (int i = 0; i < n; i++) {\n String token = tokenizer.nextToken();\n list[i] = Integer.parseInt(token);\n }\n return list;\n }", "public RedwoodConfiguration hideChannels(final Object[] channels){\r\n tasks.add(new Runnable() { public void run() { Redwood.hideChannels(channels); } });\r\n return this;\r\n }", "public static GraphTraversal<Vertex, Vertex> addPipeFor(GraphTraversal<Vertex, Vertex> pipeline,\n Class<? extends WindupVertexFrame> clazz)\n {\n pipeline.has(WindupVertexFrame.TYPE_PROP, GraphTypeManager.getTypeValue(clazz));\n return pipeline;\n }" ]
Start with specifying the artifact version
[ "public static Artifact withVersion(Version v)\n {\n Artifact artifact = new Artifact();\n artifact.version = v;\n return artifact;\n }" ]
[ "private static String removeLastDot(final String pkgName) {\n\t\treturn pkgName.charAt(pkgName.length() - 1) == Characters.DOT ? pkgName.substring(0, pkgName.length() - 1) : pkgName;\n\t}", "public static void logLong(String TAG, String longString) {\n InputStream is = new ByteArrayInputStream( longString.getBytes() );\n @SuppressWarnings(\"resource\")\n Scanner scan = new Scanner(is);\n while (scan.hasNextLine()) {\n Log.v(TAG, scan.nextLine());\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 }", "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 }", "private static int tribus(int version, int a, int b, int c) {\n if (version < 10) {\n return a;\n } else if (version >= 10 && version <= 26) {\n return b;\n } else {\n return c;\n }\n }", "public static appfwprofile_stats get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tobj.set_name(name);\n\t\tappfwprofile_stats response = (appfwprofile_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public void process(File file) throws Exception\n {\n openLogFile();\n\n int blockIndex = 0;\n int length = (int) file.length();\n m_buffer = new byte[length];\n FileInputStream is = new FileInputStream(file);\n try\n {\n int bytesRead = is.read(m_buffer);\n if (bytesRead != length)\n {\n throw new RuntimeException(\"Read count different\");\n }\n }\n finally\n {\n is.close();\n }\n\n List<Integer> blocks = new ArrayList<Integer>();\n for (int index = 64; index < m_buffer.length - 11; index++)\n {\n if (matchPattern(PARENT_BLOCK_PATTERNS, index))\n {\n blocks.add(Integer.valueOf(index));\n }\n }\n\n int startIndex = 0;\n for (int endIndex : blocks)\n {\n int blockLength = endIndex - startIndex;\n readBlock(blockIndex, startIndex, blockLength);\n startIndex = endIndex;\n ++blockIndex;\n }\n\n int blockLength = m_buffer.length - startIndex;\n readBlock(blockIndex, startIndex, blockLength);\n\n closeLogFile();\n }", "private String getTimeString(Date value)\n {\n Calendar cal = DateHelper.popCalendar(value);\n int hours = cal.get(Calendar.HOUR_OF_DAY);\n int minutes = cal.get(Calendar.MINUTE);\n DateHelper.pushCalendar(cal);\n \n StringBuilder sb = new StringBuilder(4);\n sb.append(m_twoDigitFormat.format(hours));\n sb.append(m_twoDigitFormat.format(minutes));\n\n return (sb.toString());\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}" ]
Log a byte array as a hex dump. @param data byte array
[ "public static void log(byte[] data)\n {\n if (LOG != null)\n {\n LOG.println(ByteArrayHelper.hexdump(data, true, 16, \"\"));\n LOG.flush();\n }\n }" ]
[ "public void sort(ChildTaskContainer container)\n {\n // Do we have any tasks?\n List<Task> tasks = container.getChildTasks();\n if (!tasks.isEmpty())\n {\n for (Task task : tasks)\n {\n //\n // Sort child activities\n //\n sort(task);\n\n //\n // Sort Order:\n // 1. Activities come first\n // 2. WBS come last\n // 3. Activities ordered by activity ID\n // 4. WBS ordered by ID\n //\n Collections.sort(tasks, new Comparator<Task>()\n {\n @Override public int compare(Task t1, Task t2)\n {\n boolean t1IsWbs = m_wbsTasks.contains(t1);\n boolean t2IsWbs = m_wbsTasks.contains(t2);\n\n // Both are WBS\n if (t1IsWbs && t2IsWbs)\n {\n return t1.getID().compareTo(t2.getID());\n }\n\n // Both are activities\n if (!t1IsWbs && !t2IsWbs)\n {\n String activityID1 = (String) t1.getCurrentValue(m_activityIDField);\n String activityID2 = (String) t2.getCurrentValue(m_activityIDField);\n\n if (activityID1 == null || activityID2 == null)\n {\n return (activityID1 == null && activityID2 == null ? 0 : (activityID1 == null ? 1 : -1));\n }\n\n return activityID1.compareTo(activityID2);\n }\n\n // One activity one WBS\n return t1IsWbs ? 1 : -1;\n }\n });\n }\n }\n }", "public ItemRequest<Section> delete(String section) {\n \n String path = String.format(\"/sections/%s\", section);\n return new ItemRequest<Section>(this, Section.class, path, \"DELETE\");\n }", "public int getVersion() {\n ResultSet resultSet = session.execute(format(VERSION_QUERY, getTableName()));\n Row result = resultSet.one();\n if (result == null) {\n return 0;\n }\n return result.getInt(0);\n }", "public static double SquaredEuclidean(double[] x, double[] y) {\n double d = 0.0, u;\n\n for (int i = 0; i < x.length; i++) {\n u = x[i] - y[i];\n d += u * u;\n }\n\n return d;\n }", "public static base_response add(nitro_service client, vpnsessionaction resource) throws Exception {\n\t\tvpnsessionaction addresource = new vpnsessionaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.httpport = resource.httpport;\n\t\taddresource.winsip = resource.winsip;\n\t\taddresource.dnsvservername = resource.dnsvservername;\n\t\taddresource.splitdns = resource.splitdns;\n\t\taddresource.sesstimeout = resource.sesstimeout;\n\t\taddresource.clientsecurity = resource.clientsecurity;\n\t\taddresource.clientsecuritygroup = resource.clientsecuritygroup;\n\t\taddresource.clientsecuritymessage = resource.clientsecuritymessage;\n\t\taddresource.clientsecuritylog = resource.clientsecuritylog;\n\t\taddresource.splittunnel = resource.splittunnel;\n\t\taddresource.locallanaccess = resource.locallanaccess;\n\t\taddresource.rfc1918 = resource.rfc1918;\n\t\taddresource.spoofiip = resource.spoofiip;\n\t\taddresource.killconnections = resource.killconnections;\n\t\taddresource.transparentinterception = resource.transparentinterception;\n\t\taddresource.windowsclienttype = resource.windowsclienttype;\n\t\taddresource.defaultauthorizationaction = resource.defaultauthorizationaction;\n\t\taddresource.authorizationgroup = resource.authorizationgroup;\n\t\taddresource.clientidletimeout = resource.clientidletimeout;\n\t\taddresource.proxy = resource.proxy;\n\t\taddresource.allprotocolproxy = resource.allprotocolproxy;\n\t\taddresource.httpproxy = resource.httpproxy;\n\t\taddresource.ftpproxy = resource.ftpproxy;\n\t\taddresource.socksproxy = resource.socksproxy;\n\t\taddresource.gopherproxy = resource.gopherproxy;\n\t\taddresource.sslproxy = resource.sslproxy;\n\t\taddresource.proxyexception = resource.proxyexception;\n\t\taddresource.proxylocalbypass = resource.proxylocalbypass;\n\t\taddresource.clientcleanupprompt = resource.clientcleanupprompt;\n\t\taddresource.forcecleanup = resource.forcecleanup;\n\t\taddresource.clientoptions = resource.clientoptions;\n\t\taddresource.clientconfiguration = resource.clientconfiguration;\n\t\taddresource.sso = resource.sso;\n\t\taddresource.ssocredential = resource.ssocredential;\n\t\taddresource.windowsautologon = resource.windowsautologon;\n\t\taddresource.usemip = resource.usemip;\n\t\taddresource.useiip = resource.useiip;\n\t\taddresource.clientdebug = resource.clientdebug;\n\t\taddresource.loginscript = resource.loginscript;\n\t\taddresource.logoutscript = resource.logoutscript;\n\t\taddresource.homepage = resource.homepage;\n\t\taddresource.icaproxy = resource.icaproxy;\n\t\taddresource.wihome = resource.wihome;\n\t\taddresource.citrixreceiverhome = resource.citrixreceiverhome;\n\t\taddresource.wiportalmode = resource.wiportalmode;\n\t\taddresource.clientchoices = resource.clientchoices;\n\t\taddresource.epaclienttype = resource.epaclienttype;\n\t\taddresource.iipdnssuffix = resource.iipdnssuffix;\n\t\taddresource.forcedtimeout = resource.forcedtimeout;\n\t\taddresource.forcedtimeoutwarning = resource.forcedtimeoutwarning;\n\t\taddresource.ntdomain = resource.ntdomain;\n\t\taddresource.clientlessvpnmode = resource.clientlessvpnmode;\n\t\taddresource.emailhome = resource.emailhome;\n\t\taddresource.clientlessmodeurlencoding = resource.clientlessmodeurlencoding;\n\t\taddresource.clientlesspersistentcookie = resource.clientlesspersistentcookie;\n\t\taddresource.allowedlogingroups = resource.allowedlogingroups;\n\t\taddresource.securebrowse = resource.securebrowse;\n\t\taddresource.storefronturl = resource.storefronturl;\n\t\taddresource.kcdaccount = resource.kcdaccount;\n\t\treturn addresource.add_resource(client);\n\t}", "@Pure\n\t@Inline(value = \"$3.union($1, $4.singletonMap($2.getKey(), $2.getValue()))\",\n\t\t\timported = { MapExtensions.class, Collections.class })\n\tpublic static <K, V> Map<K, V> operator_plus(Map<K, V> left, final Pair<? extends K, ? extends V> right) {\n\t\treturn union(left, Collections.singletonMap(right.getKey(), right.getValue()));\n\t}", "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 }", "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 }", "@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 }" ]
Writes a resource assignment to a PM XML file. @param mpxj MPXJ ResourceAssignment instance
[ "private void writeAssignment(ResourceAssignment mpxj)\n {\n ResourceAssignmentType xml = m_factory.createResourceAssignmentType();\n m_project.getResourceAssignment().add(xml);\n Task task = mpxj.getTask();\n Task parentTask = task.getParentTask();\n Integer parentTaskUniqueID = parentTask == null ? null : parentTask.getUniqueID();\n\n xml.setActivityObjectId(mpxj.getTaskUniqueID());\n xml.setActualCost(getDouble(mpxj.getActualCost()));\n xml.setActualFinishDate(mpxj.getActualFinish());\n xml.setActualOvertimeUnits(getDuration(mpxj.getActualOvertimeWork()));\n xml.setActualRegularUnits(getDuration(mpxj.getActualWork()));\n xml.setActualStartDate(mpxj.getActualStart());\n xml.setActualUnits(getDuration(mpxj.getActualWork()));\n xml.setAtCompletionUnits(getDuration(mpxj.getRemainingWork()));\n xml.setPlannedCost(getDouble(mpxj.getActualCost()));\n xml.setFinishDate(mpxj.getFinish());\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setObjectId(mpxj.getUniqueID());\n xml.setPlannedDuration(getDuration(mpxj.getWork()));\n xml.setPlannedFinishDate(mpxj.getFinish());\n xml.setPlannedStartDate(mpxj.getStart());\n xml.setPlannedUnits(getDuration(mpxj.getWork()));\n xml.setPlannedUnitsPerTime(getPercentage(mpxj.getUnits()));\n xml.setProjectObjectId(PROJECT_OBJECT_ID);\n xml.setRateSource(\"Resource\");\n xml.setRemainingCost(getDouble(mpxj.getActualCost()));\n xml.setRemainingDuration(getDuration(mpxj.getRemainingWork()));\n xml.setRemainingFinishDate(mpxj.getFinish());\n xml.setRemainingStartDate(mpxj.getStart());\n xml.setRemainingUnits(getDuration(mpxj.getRemainingWork()));\n xml.setRemainingUnitsPerTime(getPercentage(mpxj.getUnits()));\n xml.setResourceObjectId(mpxj.getResourceUniqueID());\n xml.setStartDate(mpxj.getStart());\n xml.setWBSObjectId(parentTaskUniqueID);\n xml.getUDF().addAll(writeUDFType(FieldTypeClass.ASSIGNMENT, mpxj));\n }" ]
[ "public static String getStringProperty(String name, Map<String, String> map, String defaultValue) {\n if (map.containsKey(name) && Strings.isNotNullOrEmpty(map.get(name))) {\n defaultValue = map.get(name);\n }\n return getPropertyOrEnvironmentVariable(name, defaultValue);\n }", "public boolean contains(Date date)\n {\n boolean result = false;\n\n if (date != null)\n {\n result = (DateHelper.compare(getFromDate(), getToDate(), date) == 0);\n }\n\n return (result);\n }", "public static base_response add(nitro_service client, appfwjsoncontenttype resource) throws Exception {\n\t\tappfwjsoncontenttype addresource = new appfwjsoncontenttype();\n\t\taddresource.jsoncontenttypevalue = resource.jsoncontenttypevalue;\n\t\taddresource.isregex = resource.isregex;\n\t\treturn addresource.add_resource(client);\n\t}", "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 }", "public static <T> List<T> asImmutable(List<? extends T> self) {\n return Collections.unmodifiableList(self);\n }", "public static boolean hasAnnotation(AnnotatedNode node, String name) {\r\n return AstUtil.getAnnotation(node, name) != null;\r\n }", "public static sslpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tsslpolicy_lbvserver_binding obj = new sslpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\tsslpolicy_lbvserver_binding response[] = (sslpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static final CurrencySymbolPosition parseCurrencySymbolPosition(String value)\n {\n CurrencySymbolPosition result = CurrencySymbolPosition.BEFORE;\n\n switch (NumberHelper.getInt(value))\n {\n case 0:\n {\n result = CurrencySymbolPosition.BEFORE;\n break;\n }\n\n case 1:\n {\n result = CurrencySymbolPosition.AFTER;\n break;\n }\n\n case 2:\n {\n result = CurrencySymbolPosition.BEFORE_WITH_SPACE;\n break;\n }\n\n case 3:\n {\n result = CurrencySymbolPosition.AFTER_WITH_SPACE;\n break;\n }\n }\n\n return (result);\n }", "public static String plus(CharSequence left, Object value) {\n return left + DefaultGroovyMethods.toString(value);\n }" ]
Dump raw data as hex. @param buffer buffer @param offset offset into buffer @param length length of data to dump @param ascii true if ASCII should also be printed @param columns number of columns @param prefix prefix when printing @return hex dump
[ "public static final String hexdump(byte[] buffer, int offset, int length, boolean ascii, int columns, String prefix)\n {\n StringBuilder sb = new StringBuilder();\n if (buffer != null)\n {\n int index = offset;\n DecimalFormat df = new DecimalFormat(\"00000\");\n\n while (index < (offset + length))\n {\n if (index + columns > (offset + length))\n {\n columns = (offset + length) - index;\n }\n\n sb.append(prefix);\n sb.append(df.format(index - offset));\n sb.append(\":\");\n sb.append(hexdump(buffer, index, columns, ascii));\n sb.append('\\n');\n\n index += columns;\n }\n }\n\n return (sb.toString());\n }" ]
[ "@UiHandler(\"m_addButton\")\r\n void addButtonClick(ClickEvent e) {\r\n\r\n if (null != m_newDate.getValue()) {\r\n m_dateList.addDate(m_newDate.getValue());\r\n m_newDate.setValue(null);\r\n if (handleChange()) {\r\n m_controller.setDates(m_dateList.getDates());\r\n }\r\n }\r\n }", "public GenericCriteria process(ProjectProperties properties, byte[] data, int dataOffset, int entryOffset, List<GenericCriteriaPrompt> prompts, List<FieldType> fields, boolean[] criteriaType)\n {\n m_properties = properties;\n m_prompts = prompts;\n m_fields = fields;\n m_criteriaType = criteriaType;\n m_dataOffset = dataOffset;\n if (m_criteriaType != null)\n {\n m_criteriaType[0] = true;\n m_criteriaType[1] = true;\n }\n\n m_criteriaBlockMap.clear();\n\n m_criteriaData = data;\n m_criteriaTextStart = MPPUtility.getShort(m_criteriaData, m_dataOffset + getCriteriaTextStartOffset());\n\n //\n // Populate the map\n //\n int criteriaStartOffset = getCriteriaStartOffset();\n int criteriaBlockSize = getCriteriaBlockSize();\n\n //System.out.println();\n //System.out.println(ByteArrayHelper.hexdump(data, dataOffset, criteriaStartOffset, false));\n\n if (m_criteriaData.length <= m_criteriaTextStart)\n {\n return null; // bad data\n }\n\n while (criteriaStartOffset + criteriaBlockSize <= m_criteriaTextStart)\n {\n byte[] block = new byte[criteriaBlockSize];\n System.arraycopy(m_criteriaData, m_dataOffset + criteriaStartOffset, block, 0, criteriaBlockSize);\n m_criteriaBlockMap.put(Integer.valueOf(criteriaStartOffset), block);\n //System.out.println(Integer.toHexString(criteriaStartOffset) + \": \" + ByteArrayHelper.hexdump(block, false));\n criteriaStartOffset += criteriaBlockSize;\n }\n\n if (entryOffset == -1)\n {\n entryOffset = getCriteriaStartOffset();\n }\n\n List<GenericCriteria> list = new LinkedList<GenericCriteria>();\n processBlock(list, m_criteriaBlockMap.get(Integer.valueOf(entryOffset)));\n GenericCriteria criteria;\n if (list.isEmpty())\n {\n criteria = null;\n }\n else\n {\n criteria = list.get(0);\n }\n return criteria;\n }", "public double getBearing(LatLong end) {\n if (this.equals(end)) {\n return 0;\n }\n\n double lat1 = latToRadians();\n double lon1 = longToRadians();\n double lat2 = end.latToRadians();\n double lon2 = end.longToRadians();\n\n double angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2),\n Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)\n * Math.cos(lat2) * Math.cos(lon1 - lon2));\n\n if (angle < 0.0) {\n angle += Math.PI * 2.0;\n }\n if (angle > Math.PI) {\n angle -= Math.PI * 2.0;\n }\n\n return Math.toDegrees(angle);\n }", "public static Path getRootFolderForSource(Path sourceFilePath, String packageName)\n {\n if (packageName == null || packageName.trim().isEmpty())\n {\n return sourceFilePath.getParent();\n }\n String[] packageNameComponents = packageName.split(\"\\\\.\");\n Path currentPath = sourceFilePath.getParent();\n for (int i = packageNameComponents.length; i > 0; i--)\n {\n String packageComponent = packageNameComponents[i - 1];\n if (!StringUtils.equals(packageComponent, currentPath.getFileName().toString()))\n {\n return null;\n }\n currentPath = currentPath.getParent();\n }\n return currentPath;\n }", "@SuppressWarnings(\"unchecked\")\n public static <E> TypeConverter<E> typeConverterFor(Class<E> cls) throws NoSuchTypeConverterException {\n TypeConverter<E> typeConverter = TYPE_CONVERTERS.get(cls);\n if (typeConverter == null) {\n throw new NoSuchTypeConverterException(cls);\n }\n return typeConverter;\n }", "public void writeTo(WritableByteChannel channel) throws IOException {\n for (ByteBuffer buffer : toDirectByteBuffers()) {\n channel.write(buffer);\n }\n }", "public static String getCorrelationId(Message message) {\n String correlationId = (String) message.get(CORRELATION_ID_KEY);\n if(null == correlationId) {\n correlationId = readCorrelationId(message);\n }\n if(null == correlationId) {\n correlationId = readCorrelationIdSoap(message);\n }\n return correlationId;\n }", "private void normalizeSelectedCategories() {\r\n\r\n Collection<String> normalizedCategories = new ArrayList<String>(m_selectedCategories.size());\r\n for (CmsTreeItem item : m_categories.values()) {\r\n if (item.getCheckBox().isChecked()) {\r\n normalizedCategories.add(item.getId());\r\n }\r\n }\r\n m_selectedCategories = normalizedCategories;\r\n\r\n }", "ProtectionDomain getProtectionDomainForProxy(ProtectionDomain domain) {\n if (domain.getCodeSource() == null) {\n // no codesource to cache on\n return create(domain);\n }\n ProtectionDomain proxyProtectionDomain = proxyProtectionDomains.get(domain.getCodeSource());\n if (proxyProtectionDomain == null) {\n // as this is not atomic create() may be called multiple times for the same domain\n // we ignore that\n proxyProtectionDomain = create(domain);\n ProtectionDomain existing = proxyProtectionDomains.putIfAbsent(domain.getCodeSource(), proxyProtectionDomain);\n if (existing != null) {\n proxyProtectionDomain = existing;\n }\n }\n return proxyProtectionDomain;\n }" ]
Writes the JavaScript code describing the tags as Tag classes to given writer.
[ "public void writeTagsToJavaScript(Writer writer) throws IOException\n {\n writer.append(\"function fillTagService(tagService) {\\n\");\n writer.append(\"\\t// (name, isPrime, isPseudo, color), [parent tags]\\n\");\n for (Tag tag : definedTags.values())\n {\n writer.append(\"\\ttagService.registerTag(new Tag(\");\n escapeOrNull(tag.getName(), writer);\n writer.append(\", \");\n escapeOrNull(tag.getTitle(), writer);\n writer.append(\", \").append(\"\" + tag.isPrime())\n .append(\", \").append(\"\" + tag.isPseudo())\n .append(\", \");\n escapeOrNull(tag.getColor(), writer);\n writer.append(\")\").append(\", [\");\n\n // We only have strings, not references, so we're letting registerTag() getOrCreate() the tag.\n for (Tag parentTag : tag.getParentTags())\n {\n writer.append(\"'\").append(StringEscapeUtils.escapeEcmaScript(parentTag.getName())).append(\"',\");\n }\n writer.append(\"]);\\n\");\n }\n writer.append(\"}\\n\");\n }" ]
[ "private static List<Node> difference(List<Node> listA, List<Node> listB) {\n if(listA != null && listB != null)\n listA.removeAll(listB);\n return listA;\n }", "public static base_responses unset(nitro_service client, String trapname[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (trapname != null && trapname.length > 0) {\n\t\t\tsnmpalarm unsetresources[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++){\n\t\t\t\tunsetresources[i] = new snmpalarm();\n\t\t\t\tunsetresources[i].trapname = trapname[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "private String getPropertyName(Method method)\n {\n String result = method.getName();\n if (result.startsWith(\"get\"))\n {\n result = result.substring(3);\n }\n return result;\n }", "public double d(double x){\n\t\tint intervalNumber =getIntervalNumber(x);\n\t\tif (intervalNumber==0 || intervalNumber==points.length) {\n\t\t\treturn x;\n\t\t}\n\t\treturn getIntervalReferencePoint(intervalNumber-1);\n\t}", "protected Date getPickerDate() {\n try {\n JsDate pickerDate = getPicker().get(\"select\").obj;\n return new Date((long) pickerDate.getTime());\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }", "public int color(Context ctx) {\n if (mColorInt == 0 && mColorRes != -1) {\n mColorInt = ContextCompat.getColor(ctx, mColorRes);\n }\n return mColorInt;\n }", "protected long getRevisionIdFromResponse(JsonNode response) throws JsonMappingException {\n\t\tif(response == null) {\n\t\t\tthrow new JsonMappingException(\"API response is null\");\n\t\t}\n\t\tJsonNode entity = null;\n\t\tif(response.has(\"entity\")) {\n\t\t\tentity = response.path(\"entity\");\n\t\t} else if(response.has(\"pageinfo\")) {\n\t\t\tentity = response.path(\"pageinfo\");\n\t\t} \n\t\tif(entity != null && entity.has(\"lastrevid\")) {\n\t\t\treturn entity.path(\"lastrevid\").asLong();\n\t\t}\n\t\tthrow new JsonMappingException(\"The last revision id could not be found in API response\");\n\t}", "public float getPositionY(int vertex) {\n if (!hasPositions()) {\n throw new IllegalStateException(\"mesh has no positions\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_vertices.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\n }", "public static ipv6 get(nitro_service service) throws Exception{\n\t\tipv6 obj = new ipv6();\n\t\tipv6[] response = (ipv6[])obj.get_resources(service);\n\t\treturn response[0];\n\t}" ]
Use this API to fetch dnssuffix resources of given names .
[ "public static dnssuffix[] get(nitro_service service, String Dnssuffix[]) throws Exception{\n\t\tif (Dnssuffix !=null && Dnssuffix.length>0) {\n\t\t\tdnssuffix response[] = new dnssuffix[Dnssuffix.length];\n\t\t\tdnssuffix obj[] = new dnssuffix[Dnssuffix.length];\n\t\t\tfor (int i=0;i<Dnssuffix.length;i++) {\n\t\t\t\tobj[i] = new dnssuffix();\n\t\t\t\tobj[i].set_Dnssuffix(Dnssuffix[i]);\n\t\t\t\tresponse[i] = (dnssuffix) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}" ]
[ "public ListExternalToolsOptions 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 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 }", "private void emitSuiteStart(Description description, long startTimestamp) throws IOException {\n String suiteName = description.getDisplayName();\n if (useSimpleNames) {\n if (suiteName.lastIndexOf('.') >= 0) {\n suiteName = suiteName.substring(suiteName.lastIndexOf('.') + 1);\n }\n }\n logShort(shortTimestamp(startTimestamp) +\n \"Suite: \" +\n FormattingUtils.padTo(maxClassNameColumns, suiteName, \"[...]\"));\n }", "public static int[] Argsort(final float[] array, final boolean ascending) {\n Integer[] indexes = new Integer[array.length];\n for (int i = 0; i < indexes.length; i++) {\n indexes[i] = i;\n }\n Arrays.sort(indexes, new Comparator<Integer>() {\n @Override\n public int compare(final Integer i1, final Integer i2) {\n return (ascending ? 1 : -1) * Float.compare(array[i1], array[i2]);\n }\n });\n return asArray(indexes);\n }", "public static lbmonitor_binding[] get(nitro_service service, String monitorname[]) throws Exception{\n\t\tif (monitorname !=null && monitorname.length>0) {\n\t\t\tlbmonitor_binding response[] = new lbmonitor_binding[monitorname.length];\n\t\t\tlbmonitor_binding obj[] = new lbmonitor_binding[monitorname.length];\n\t\t\tfor (int i=0;i<monitorname.length;i++) {\n\t\t\t\tobj[i] = new lbmonitor_binding();\n\t\t\t\tobj[i].set_monitorname(monitorname[i]);\n\t\t\t\tresponse[i] = (lbmonitor_binding) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public static String changeFirstLetterToLowerCase(String word) {\n char[] letras = word.toCharArray();\n char a = letras[0];\n letras[0] = Character.toLowerCase(a);\n return new String(letras);\n }", "public static final Rate parseRate(BigDecimal value)\n {\n Rate result = null;\n\n if (value != null)\n {\n result = new Rate(value, TimeUnit.HOURS);\n }\n\n return (result);\n }", "public static Object instantiate(Constructor constructor) throws InstantiationException\r\n {\r\n if(constructor == null)\r\n {\r\n throw new ClassNotPersistenceCapableException(\r\n \"A zero argument constructor was not provided!\");\r\n }\r\n\r\n Object result = null;\r\n try\r\n {\r\n result = constructor.newInstance(NO_ARGS);\r\n }\r\n catch(InstantiationException e)\r\n {\r\n throw e;\r\n }\r\n catch(Exception e)\r\n {\r\n throw new ClassNotPersistenceCapableException(\"Can't instantiate class '\"\r\n + (constructor != null ? constructor.getDeclaringClass().getName() : \"null\")\r\n + \"' with given constructor: \" + e.getMessage(), e);\r\n }\r\n return result;\r\n }", "private void deliverLostAnnouncement(final DeviceAnnouncement announcement) {\n for (final DeviceAnnouncementListener listener : getDeviceAnnouncementListeners()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n try {\n listener.deviceLost(announcement);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering device lost announcement to listener\", t);\n }\n }\n });\n }\n }" ]
A factory method for users that need to report success without actually running any analysis. The returned result will be successful, but will not contain the actual configurations of extensions. @return a "fake" successful analysis result
[ "public static AnalysisResult fakeSuccess() {\n return new AnalysisResult(null, new Extensions(Collections.emptyMap(), Collections.emptyMap(),\n Collections.emptyMap(), Collections.emptyMap()));\n }" ]
[ "public String addExtent(Properties attributes) throws XDocletException\r\n {\r\n String name = attributes.getProperty(ATTRIBUTE_NAME);\r\n\r\n if (!_model.hasClass(name))\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_FIND_TYPE,\r\n new String[]{name}));\r\n }\r\n _curClassDef.addExtentClass(_model.getClass(name));\r\n return \"\";\r\n }", "private String parseMandatoryStringValue(final String path) throws Exception {\n\n final String value = parseOptionalStringValue(path);\n if (value == null) {\n throw new Exception();\n }\n return value;\n }", "public 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 ProjectFile handleDosExeFile(InputStream stream) throws Exception\n {\n File file = InputStreamHelper.writeStreamToTempFile(stream, \".tmp\");\n InputStream is = null;\n\n try\n {\n is = new FileInputStream(file);\n if (is.available() > 1350)\n {\n StreamHelper.skip(is, 1024);\n\n // Bytes at offset 1024\n byte[] data = new byte[2];\n is.read(data);\n\n if (matchesFingerprint(data, WINDOWS_NE_EXE_FINGERPRINT))\n {\n StreamHelper.skip(is, 286);\n\n // Bytes at offset 1312\n data = new byte[34];\n is.read(data);\n if (matchesFingerprint(data, PRX_FINGERPRINT))\n {\n is.close();\n is = null;\n return readProjectFile(new P3PRXFileReader(), file);\n }\n }\n\n if (matchesFingerprint(data, STX_FINGERPRINT))\n {\n StreamHelper.skip(is, 31742);\n // Bytes at offset 32768\n data = new byte[4];\n is.read(data);\n if (matchesFingerprint(data, PRX3_FINGERPRINT))\n {\n is.close();\n is = null;\n return readProjectFile(new SureTrakSTXFileReader(), file);\n }\n }\n }\n return null;\n }\n\n finally\n {\n StreamHelper.closeQuietly(is);\n FileHelper.deleteQuietly(file);\n }\n }", "public void finished(final ProcessorGraphNode processorGraphNode) {\n this.processorLock.lock();\n try {\n this.runningProcessors.remove(processorGraphNode.getProcessor());\n this.executedProcessors.put(processorGraphNode.getProcessor(), null);\n } finally {\n this.processorLock.unlock();\n }\n }", "@Override public int getItemViewType(int position) {\n T content = getItem(position);\n return rendererBuilder.getItemViewType(content);\n }", "public void cleanup() {\n managers.clear();\n for (BeanManagerImpl beanManager : beanDeploymentArchives.values()) {\n beanManager.cleanup();\n }\n beanDeploymentArchives.clear();\n deploymentServices.cleanup();\n deploymentManager.cleanup();\n instance.clear(contextId);\n }", "@UiHandler(\"m_seriesCheckBox\")\n void onSeriesChange(ValueChangeEvent<Boolean> event) {\n\n if (handleChange()) {\n m_controller.setIsSeries(event.getValue());\n }\n }", "public static protocoludp_stats get(nitro_service service) throws Exception{\n\t\tprotocoludp_stats obj = new protocoludp_stats();\n\t\tprotocoludp_stats[] response = (protocoludp_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}" ]
Gets the actual key - will create a new row with the max key of table if it does not exist. @param field @return @throws SequenceManagerException
[ "protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n boolean needsCommit = false;\r\n long result = 0;\r\n /*\r\n arminw:\r\n use the associated broker instance, check if broker was in tx or\r\n we need to commit used connection.\r\n */\r\n PersistenceBroker targetBroker = getBrokerForClass();\r\n if(!targetBroker.isInTransaction())\r\n {\r\n targetBroker.beginTransaction();\r\n needsCommit = true;\r\n }\r\n try\r\n {\r\n // lookup sequence name\r\n String sequenceName = calculateSequenceName(field);\r\n try\r\n {\r\n result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);\r\n /*\r\n if 0 was returned we assume that the stored procedure\r\n did not work properly.\r\n */\r\n if (result == 0)\r\n {\r\n throw new SequenceManagerException(\"No incremented value retrieved\");\r\n }\r\n }\r\n catch (Exception e)\r\n {\r\n // maybe the sequence was not created\r\n log.info(\"Could not grab next key, message was \" + e.getMessage() +\r\n \" - try to write a new sequence entry to database\");\r\n try\r\n {\r\n // on create, make sure to get the max key for the table first\r\n long maxKey = SequenceManagerHelper.getMaxForExtent(targetBroker, field);\r\n createSequence(targetBroker, field, sequenceName, maxKey);\r\n }\r\n catch (Exception e1)\r\n {\r\n String eol = SystemUtils.LINE_SEPARATOR;\r\n throw new SequenceManagerException(eol + \"Could not grab next id, failed with \" + eol +\r\n e.getMessage() + eol + \"Creation of new sequence failed with \" +\r\n eol + e1.getMessage() + eol, e1);\r\n }\r\n try\r\n {\r\n result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);\r\n }\r\n catch (Exception e1)\r\n {\r\n throw new SequenceManagerException(\"Could not grab next id although a sequence seems to exist\", e);\r\n }\r\n }\r\n }\r\n finally\r\n {\r\n if(targetBroker != null && needsCommit)\r\n {\r\n targetBroker.commitTransaction();\r\n }\r\n }\r\n return result;\r\n }" ]
[ "private IndexedContainer createContainerForDescriptorEditing() {\n\n IndexedContainer container = new IndexedContainer();\n\n // create properties\n container.addContainerProperty(TableProperty.KEY, String.class, \"\");\n container.addContainerProperty(TableProperty.DESCRIPTION, String.class, \"\");\n container.addContainerProperty(TableProperty.DEFAULT, String.class, \"\");\n\n // add entries\n CmsXmlContentValueSequence messages = m_descContent.getValueSequence(\n \"/\" + Descriptor.N_MESSAGE,\n Descriptor.LOCALE);\n for (int i = 0; i < messages.getElementCount(); i++) {\n\n String prefix = messages.getValue(i).getPath() + \"/\";\n Object itemId = container.addItem();\n Item item = container.getItem(itemId);\n String key = m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).getStringValue(m_cms);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n item.getItemProperty(TableProperty.DESCRIPTION).setValue(\n m_descContent.getValue(prefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).getStringValue(m_cms));\n item.getItemProperty(TableProperty.DEFAULT).setValue(\n m_descContent.getValue(prefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).getStringValue(m_cms));\n }\n\n return container;\n\n }", "public static String getAggregatedResultHuman(Map<String, LinkedHashSet<String>> aggregateResultMap){\n\n StringBuilder res = new StringBuilder();\n\n for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap\n .entrySet()) {\n LinkedHashSet<String> valueSet = entry.getValue(); \n res.append(\"[\" + entry.getKey() + \" COUNT: \" +valueSet.size() + \" ]:\\n\");\n for(String str: valueSet){\n res.append(\"\\t\" + str + \"\\n\");\n }\n res.append(\"###################################\\n\\n\");\n }\n \n return res.toString();\n \n }", "private static <D, T> D createDaoFromConfig(ConnectionSource connectionSource, Class<T> clazz) throws SQLException {\n\t\t// no loaded configs\n\t\tif (configMap == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tDatabaseTableConfig<T> config = (DatabaseTableConfig<T>) configMap.get(clazz);\n\t\t// if we don't config information cached return null\n\t\tif (config == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// else create a DAO using configuration\n\t\tDao<T, ?> configedDao = doCreateDao(connectionSource, config);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tD castDao = (D) configedDao;\n\t\treturn castDao;\n\t}", "public MediaType copyQualityValue(MediaType mediaType) {\n\t\tif (!mediaType.parameters.containsKey(PARAM_QUALITY_FACTOR)) {\n\t\t\treturn this;\n\t\t}\n\t\tMap<String, String> params = new LinkedHashMap<String, String>(this.parameters);\n\t\tparams.put(PARAM_QUALITY_FACTOR, mediaType.parameters.get(PARAM_QUALITY_FACTOR));\n\t\treturn new MediaType(this, params);\n\t}", "public static List<Integer> getAllPartitions(AdminClient adminClient) {\n List<Integer> partIds = Lists.newArrayList();\n partIds = Lists.newArrayList();\n for(Node node: adminClient.getAdminClientCluster().getNodes()) {\n partIds.addAll(node.getPartitionIds());\n }\n return partIds;\n }", "public static void dumpTexCoords(AiMesh mesh, int coords) {\n if (!mesh.hasTexCoords(coords)) {\n System.out.println(\"mesh has no texture coordinate set \" + coords);\n return;\n }\n \n for (int i = 0; i < mesh.getNumVertices(); i++) {\n int numComponents = mesh.getNumUVComponents(coords);\n System.out.print(\"[\" + mesh.getTexCoordU(i, coords));\n \n if (numComponents > 1) {\n System.out.print(\", \" + mesh.getTexCoordV(i, coords));\n }\n \n if (numComponents > 2) {\n System.out.print(\", \" + mesh.getTexCoordW(i, coords));\n }\n \n System.out.println(\"]\");\n }\n }", "protected TableFontStyle getColumnFontStyle(byte[] data, int offset, Map<Integer, FontBase> fontBases)\n {\n int uniqueID = MPPUtility.getInt(data, offset);\n FieldType fieldType = MPPTaskField.getInstance(MPPUtility.getShort(data, offset + 4));\n Integer index = Integer.valueOf(MPPUtility.getByte(data, offset + 8));\n int style = MPPUtility.getByte(data, offset + 9);\n ColorType color = ColorType.getInstance(MPPUtility.getByte(data, offset + 10));\n int change = MPPUtility.getByte(data, offset + 12);\n\n FontBase fontBase = fontBases.get(index);\n\n boolean bold = ((style & 0x01) != 0);\n boolean italic = ((style & 0x02) != 0);\n boolean underline = ((style & 0x04) != 0);\n\n boolean boldChanged = ((change & 0x01) != 0);\n boolean underlineChanged = ((change & 0x02) != 0);\n boolean italicChanged = ((change & 0x04) != 0);\n boolean colorChanged = ((change & 0x08) != 0);\n boolean fontChanged = ((change & 0x10) != 0);\n boolean backgroundColorChanged = (uniqueID == -1);\n boolean backgroundPatternChanged = (uniqueID == -1);\n\n return (new TableFontStyle(uniqueID, fieldType, fontBase, italic, bold, underline, false, color.getColor(), Color.BLACK, BackgroundPattern.TRANSPARENT, italicChanged, boldChanged, underlineChanged, false, colorChanged, fontChanged, backgroundColorChanged, backgroundPatternChanged));\n }", "public static List<String> getValueList(List<String> valuePairs, String delim) {\n List<String> valueList = Lists.newArrayList();\n for(String valuePair: valuePairs) {\n String[] value = valuePair.split(delim, 2);\n if(value.length != 2)\n throw new VoldemortException(\"Invalid argument pair: \" + valuePair);\n valueList.add(value[0]);\n valueList.add(value[1]);\n }\n return valueList;\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public static void changeCredentials(String accountID, String token, String region) {\n if(defaultConfig != null){\n Logger.i(\"CleverTap SDK already initialized with accountID:\"+defaultConfig.getAccountId()\n +\" and token:\"+defaultConfig.getAccountToken()+\". Cannot change credentials to \"\n + accountID + \" and \" + token);\n return;\n }\n\n ManifestInfo.changeCredentials(accountID,token,region);\n }" ]
Determines the number bytes required to store a variable length @param i length of Bytes @return number of bytes needed
[ "public static int checkVlen(int i) {\n int count = 0;\n if (i >= -112 && i <= 127) {\n return 1;\n } else {\n int len = -112;\n if (i < 0) {\n i ^= -1L; // take one's complement'\n len = -120;\n }\n\n long tmp = i;\n while (tmp != 0) {\n tmp = tmp >> 8;\n len--;\n }\n\n count++;\n\n len = (len < -120) ? -(len + 120) : -(len + 112);\n\n while (len != 0) {\n count++;\n len--;\n }\n\n return count;\n }\n }" ]
[ "protected String format(String key, String defaultPattern, Object... args) {\n String escape = escape(defaultPattern);\n String s = lookupPattern(key, escape);\n Object[] objects = escapeAll(args);\n return MessageFormat.format(s, objects);\n }", "public static Region fromName(String name) {\n if (name == null) {\n return null;\n }\n\n Region region = VALUES_BY_NAME.get(name.toLowerCase().replace(\" \", \"\"));\n if (region != null) {\n return region;\n } else {\n return Region.create(name.toLowerCase().replace(\" \", \"\"), name);\n }\n }", "public static void main(String[] args) throws ParseException, IOException {\n\t\tClient client = new Client(\n\t\t\t\tnew DumpProcessingController(\"wikidatawiki\"), args);\n\t\tclient.performActions();\n\t}", "public final static void appendCode(final StringBuilder out, final String in, final int start, final int end)\n {\n for (int i = start; i < end; i++)\n {\n final char c;\n switch (c = in.charAt(i))\n {\n case '&':\n out.append(\"&amp;\");\n break;\n case '<':\n out.append(\"&lt;\");\n break;\n case '>':\n out.append(\"&gt;\");\n break;\n default:\n out.append(c);\n break;\n }\n }\n }", "public T modifyBundle(final String moduleName, final String slot, final byte[] existingHash, final byte[] newHash) {\n final ContentItem item = createBundleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.MODIFY, existingHash));\n return returnThis();\n }", "public int color(Context ctx) {\n if (mColorInt == 0 && mColorRes != -1) {\n mColorInt = ContextCompat.getColor(ctx, mColorRes);\n }\n return mColorInt;\n }", "@Override\n\tpublic List<Object> loadEntitiesFromTuples(SharedSessionContractImplementor session, LockOptions lockOptions, OgmLoadingContext ogmContext) {\n\t\treturn loadEntity( null, null, session, lockOptions, ogmContext );\n\t}", "private String getDestinationHostName(String hostName) {\n List<ServerRedirect> servers = serverRedirectService\n .tableServers(requestInformation.get().client.getId());\n for (ServerRedirect server : servers) {\n if (server.getSrcUrl().compareTo(hostName) == 0) {\n if (server.getDestUrl() != null && server.getDestUrl().compareTo(\"\") != 0) {\n return server.getDestUrl();\n } else {\n logger.warn(\"Using source URL as destination URL since no destination was specified for: {}\",\n server.getSrcUrl());\n }\n\n // only want to apply the first host name change found\n break;\n }\n }\n\n return hostName;\n }", "public void setDateMin(Date dateMin) {\n this.dateMin = dateMin;\n\n if (isAttached() && dateMin != null) {\n getPicker().set(\"min\", JsDate.create((double) dateMin.getTime()));\n }\n }" ]
Gen job id. @return the string
[ "public String generateTaskId() {\n final String uuid = UUID.randomUUID().toString().substring(0, 12);\n int size = this.targetHostMeta == null ? 0 : this.targetHostMeta\n .getHosts().size();\n return \"PT_\" + size + \"_\"\n + PcDateUtils.getNowDateTimeStrConciseNoZone() + \"_\" + uuid;\n }" ]
[ "public StochasticPathwiseLevenbergMarquardt getCloneWithModifiedTargetValues(List<RandomVariable> newTargetVaues, List<RandomVariable> newWeights, boolean isUseBestParametersAsInitialParameters) throws CloneNotSupportedException {\n\t\tStochasticPathwiseLevenbergMarquardt clonedOptimizer = clone();\n\t\tclonedOptimizer.targetValues = numberListToDoubleArray(newTargetVaues);\n\t\tclonedOptimizer.weights = numberListToDoubleArray(newWeights);\n\n\t\tif(isUseBestParametersAsInitialParameters && this.done()) {\n\t\t\tclonedOptimizer.initialParameters = this.getBestFitParameters();\n\t\t}\n\n\t\treturn clonedOptimizer;\n\t}", "public static Map<String, List<String>> getConsumersPerTopic(ZkClient zkClient, String group) {\n ZkGroupDirs dirs = new ZkGroupDirs(group);\n List<String> consumers = getChildrenParentMayNotExist(zkClient, dirs.consumerRegistryDir);\n //\n Map<String, List<String>> consumersPerTopicMap = new HashMap<String, List<String>>();\n for (String consumer : consumers) {\n TopicCount topicCount = getTopicCount(zkClient, group, consumer);\n for (Map.Entry<String, Set<String>> e : topicCount.getConsumerThreadIdsPerTopic().entrySet()) {\n final String topic = e.getKey();\n for (String consumerThreadId : e.getValue()) {\n List<String> list = consumersPerTopicMap.get(topic);\n if (list == null) {\n list = new ArrayList<String>();\n consumersPerTopicMap.put(topic, list);\n }\n //\n list.add(consumerThreadId);\n }\n }\n }\n //\n for (Map.Entry<String, List<String>> e : consumersPerTopicMap.entrySet()) {\n Collections.sort(e.getValue());\n }\n return consumersPerTopicMap;\n }", "public ItemRequest<Attachment> findById(String attachment) {\n \n String path = String.format(\"/attachments/%s\", attachment);\n return new ItemRequest<Attachment>(this, Attachment.class, path, \"GET\");\n }", "public void setColorRange(int firstIndex, int lastIndex, int color) {\n\t\tfor (int i = firstIndex; i <= lastIndex; i++)\n\t\t\tmap[i] = color;\n\t}", "public void processActivityCodes(List<Row> types, List<Row> typeValues, List<Row> assignments)\n {\n ActivityCodeContainer container = m_project.getActivityCodes();\n Map<Integer, ActivityCode> map = new HashMap<Integer, ActivityCode>();\n\n for (Row row : types)\n {\n ActivityCode code = new ActivityCode(row.getInteger(\"actv_code_type_id\"), row.getString(\"actv_code_type\"));\n container.add(code);\n map.put(code.getUniqueID(), code);\n }\n\n for (Row row : typeValues)\n {\n ActivityCode code = map.get(row.getInteger(\"actv_code_type_id\"));\n if (code != null)\n {\n ActivityCodeValue value = code.addValue(row.getInteger(\"actv_code_id\"), row.getString(\"short_name\"), row.getString(\"actv_code_name\"));\n m_activityCodeMap.put(value.getUniqueID(), value);\n }\n }\n\n for (Row row : assignments)\n {\n Integer taskID = row.getInteger(\"task_id\");\n List<Integer> list = m_activityCodeAssignments.get(taskID);\n if (list == null)\n {\n list = new ArrayList<Integer>();\n m_activityCodeAssignments.put(taskID, list);\n }\n list.add(row.getInteger(\"actv_code_id\"));\n }\n }", "public static <T> Object callMethod(Object obj,\n Class<T> c,\n String name,\n Class<?>[] classes,\n Object[] args) {\n try {\n Method m = getMethod(c, name, classes);\n return m.invoke(obj, args);\n } catch(InvocationTargetException e) {\n throw getCause(e);\n } catch(IllegalAccessException e) {\n throw new IllegalStateException(e);\n }\n }", "public String getResourceFilename() {\n switch (resourceType) {\n case ANDROID_ASSETS:\n return assetPath\n .substring(assetPath.lastIndexOf(File.separator) + 1);\n\n case ANDROID_RESOURCE:\n return resourceFilePath.substring(\n resourceFilePath.lastIndexOf(File.separator) + 1);\n\n case LINUX_FILESYSTEM:\n return filePath.substring(filePath.lastIndexOf(File.separator) + 1);\n\n case NETWORK:\n return url.getPath().substring(url.getPath().lastIndexOf(\"/\") + 1);\n\n case INPUT_STREAM:\n return inputStreamName;\n\n default:\n return null;\n }\n }", "public DiscreteInterval minus(DiscreteInterval other) {\n return new DiscreteInterval(this.min - other.max, this.max - other.min);\n }", "public void reportError(NodeT faulted, Throwable throwable) {\n faulted.setPreparer(true);\n String dependency = faulted.key();\n for (String dependentKey : nodeTable.get(dependency).dependentKeys()) {\n DAGNode<DataT, NodeT> dependent = nodeTable.get(dependentKey);\n dependent.lock().lock();\n try {\n dependent.onFaultedResolution(dependency, throwable);\n if (dependent.hasAllResolved()) {\n queue.add(dependent.key());\n }\n } finally {\n dependent.lock().unlock();\n }\n }\n }" ]
Handles DMR strings in the configuration @param node the node to create. @param name the name for the node. @param value the value for the node.
[ "private void handleDmrString(final ModelNode node, final String name, final String value) {\n final String realValue = value.substring(2);\n node.get(name).set(ModelNode.fromString(realValue));\n }" ]
[ "@Override\n public void onDismiss(DialogInterface dialog) {\n if (mOldDialog != null && mOldDialog == dialog) {\n // This is the callback from the old progress dialog that was already dismissed before\n // the device orientation change, so just ignore it.\n return;\n }\n super.onDismiss(dialog);\n }", "public static CmsResourceTypeStatResultList init(CmsResourceTypeStatResultList resList) {\n\n if (resList == null) {\n return new CmsResourceTypeStatResultList();\n }\n\n resList.deleteOld();\n return resList;\n }", "public String toDottedString() {\r\n\t\tString result = null;\r\n\t\tif(hasNoStringCache() || (result = getStringCache().dottedString) == null) {\r\n\t\t\tAddressDivisionGrouping dottedGrouping = getDottedGrouping();\r\n\t\t\tgetStringCache().dottedString = result = toNormalizedString(MACStringCache.dottedParams, dottedGrouping);\r\n\t\t}\r\n\t\treturn result;\r\n\t}", "private Level getLogLevel() {\n return isQuiet() ? Level.OFF : isVerbose() ? Level.DEBUG : Level.INFO;\n }", "@SuppressWarnings(\"deprecation\")\n public boolean cancelOnTargetHosts(List<String> targetHosts) {\n\n boolean success = false;\n\n try {\n\n switch (state) {\n\n case IN_PROGRESS:\n if (executionManager != null\n && !executionManager.isTerminated()) {\n executionManager.tell(new CancelTaskOnHostRequest(\n targetHosts), executionManager);\n logger.info(\n \"asked task to stop from running on target hosts with count {}...\",\n targetHosts.size());\n } else {\n logger.info(\"manager already killed or not exist.. NO OP\");\n }\n success = true;\n break;\n case COMPLETED_WITHOUT_ERROR:\n case COMPLETED_WITH_ERROR:\n case WAITING:\n logger.info(\"will NO OP for cancelOnTargetHost as it is not in IN_PROGRESS state\");\n success = true;\n break;\n default:\n break;\n\n }\n\n } catch (Exception e) {\n logger.error(\n \"cancel task {} on hosts with count {} error with exception details \",\n this.getTaskId(), targetHosts.size(), e);\n }\n\n return success;\n }", "@SafeVarargs\n private final <T> Set<T> join(Set<T>... sets)\n {\n Set<T> result = new HashSet<>();\n if (sets == null)\n return result;\n\n for (Set<T> set : sets)\n {\n if (set != null)\n result.addAll(set);\n }\n return result;\n }", "private boolean activityIsStartMilestone(Activity activity)\n {\n String type = activity.getType();\n return type != null && type.indexOf(\"StartMilestone\") != -1;\n }", "public static Map<Integer, Integer> getMapOfContiguousPartitions(final Cluster cluster,\n int zoneId) {\n List<Integer> partitionIds = new ArrayList<Integer>(cluster.getPartitionIdsInZone(zoneId));\n Map<Integer, Integer> partitionIdToRunLength = Maps.newHashMap();\n\n if(partitionIds.isEmpty()) {\n return partitionIdToRunLength;\n }\n\n int lastPartitionId = partitionIds.get(0);\n int initPartitionId = lastPartitionId;\n\n for(int offset = 1; offset < partitionIds.size(); offset++) {\n int partitionId = partitionIds.get(offset);\n if(partitionId == lastPartitionId + 1) {\n lastPartitionId = partitionId;\n continue;\n }\n int runLength = lastPartitionId - initPartitionId + 1;\n\n partitionIdToRunLength.put(initPartitionId, runLength);\n\n initPartitionId = partitionId;\n lastPartitionId = initPartitionId;\n }\n\n int runLength = lastPartitionId - initPartitionId + 1;\n if(lastPartitionId == cluster.getNumberOfPartitions() - 1\n && partitionIdToRunLength.containsKey(0)) {\n // special case of contiguity that wraps around the ring.\n partitionIdToRunLength.put(initPartitionId, runLength + partitionIdToRunLength.get(0));\n partitionIdToRunLength.remove(0);\n } else {\n partitionIdToRunLength.put(initPartitionId, runLength);\n }\n\n return partitionIdToRunLength;\n }", "public static RgbaColor fromRgba(String rgba) {\n if (rgba.length() == 0) return getDefaultColor();\n\n String[] parts = getRgbaParts(rgba).split(\",\");\n if (parts.length == 4) {\n return new RgbaColor(parseInt(parts[0]),\n parseInt(parts[1]),\n parseInt(parts[2]),\n parseFloat(parts[3]));\n }\n else {\n return getDefaultColor();\n }\n }" ]
Returns true if the lattice contains an entry at the specified location. @param maturityInMonths The maturity in months to check. @param tenorInMonths The tenor in months to check. @param moneynessBP The moneyness in bp to check. @return True iff there is an entry at the specified location.
[ "public boolean containsEntryFor(int maturityInMonths, int tenorInMonths, int moneynessBP) {\r\n\t\treturn entryMap.containsKey(new DataKey(maturityInMonths, tenorInMonths, moneynessBP));\r\n\t}" ]
[ "public Object selectElement(String predicate) throws org.odmg.QueryInvalidException\r\n {\r\n return ((DList) this.query(predicate)).get(0);\r\n }", "private void putEvent(EventType eventType) throws Exception {\n List<EventType> eventTypes = Collections.singletonList(eventType);\n\n int i;\n for (i = 0; i < retryNum; ++i) {\n try {\n monitoringService.putEvents(eventTypes);\n break;\n } catch (Exception e) {\n LOG.log(Level.SEVERE, e.getMessage(), e);\n }\n Thread.sleep(retryDelay);\n }\n\n if (i == retryNum) {\n LOG.warning(\"Could not send events to monitoring service after \" + retryNum + \" retries.\");\n throw new Exception(\"Send SERVER_START/SERVER_STOP event to SAM Server failed\");\n }\n\n }", "public static final Integer parseMinutesFromHours(String value)\n {\n Integer result = null;\n if (value != null)\n {\n result = Integer.valueOf(Integer.parseInt(value) * 60);\n }\n return result;\n }", "private static Date getSentDate(MimeMessage msg, Date defaultVal) {\r\n if (msg == null) {\r\n return defaultVal;\r\n }\r\n try {\r\n Date sentDate = msg.getSentDate();\r\n if (sentDate == null) {\r\n return defaultVal;\r\n } else {\r\n return sentDate;\r\n }\r\n } catch (MessagingException me) {\r\n return new Date();\r\n }\r\n }", "@Override\n protected void updateState(final String name, final InstallationModificationImpl modification, final InstallationModificationImpl.InstallationState state) {\n final PatchableTarget.TargetInfo identityInfo = modification.getModifiedState();\n this.identity = new Identity() {\n @Override\n public String getVersion() {\n return modification.getVersion();\n }\n\n @Override\n public String getName() {\n return name;\n }\n\n @Override\n public TargetInfo loadTargetInfo() throws IOException {\n return identityInfo;\n }\n\n @Override\n public DirectoryStructure getDirectoryStructure() {\n return modification.getDirectoryStructure();\n }\n };\n\n this.allPatches = Collections.unmodifiableList(modification.getAllPatches());\n this.layers.clear();\n for (final Map.Entry<String, MutableTargetImpl> entry : state.getLayers().entrySet()) {\n final String layerName = entry.getKey();\n final MutableTargetImpl target = entry.getValue();\n putLayer(layerName, new LayerInfo(layerName, target.getModifiedState(), target.getDirectoryStructure()));\n }\n this.addOns.clear();\n for (final Map.Entry<String, MutableTargetImpl> entry : state.getAddOns().entrySet()) {\n final String addOnName = entry.getKey();\n final MutableTargetImpl target = entry.getValue();\n putAddOn(addOnName, new LayerInfo(addOnName, target.getModifiedState(), target.getDirectoryStructure()));\n }\n }", "public 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}", "public static base_response update(nitro_service client, autoscaleprofile resource) throws Exception {\n\t\tautoscaleprofile updateresource = new autoscaleprofile();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.url = resource.url;\n\t\tupdateresource.apikey = resource.apikey;\n\t\tupdateresource.sharedsecret = resource.sharedsecret;\n\t\treturn updateresource.update_resource(client);\n\t}", "private ArrayList<RunListener> instantiateRunListeners() throws Exception {\n ArrayList<RunListener> instances = new ArrayList<>();\n\n if (runListeners != null) {\n for (String className : Arrays.asList(runListeners.split(\",\"))) {\n instances.add((RunListener) this.instantiate(className).newInstance());\n }\n }\n\n return instances;\n }", "public static byte[] getDocumentToByteArray(Document dom) {\n try {\n TransformerFactory tFactory = TransformerFactory.newInstance();\n\n Transformer transformer = tFactory.newTransformer();\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer\n .setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, \"no\");\n transformer.setOutputProperty(OutputKeys.METHOD, \"html\");\n // TODO should be fixed to read doctype declaration\n transformer\n .setOutputProperty(\n OutputKeys.DOCTYPE_PUBLIC,\n \"-//W3C//DTD XHTML 1.0 Strict//EN\\\" \"\n + \"\\\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\");\n\n DOMSource source = new DOMSource(dom);\n\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n Result result = new StreamResult(out);\n transformer.transform(source, result);\n\n return out.toByteArray();\n } catch (TransformerException e) {\n LOGGER.error(\"Error while converting the document to a byte array\",\n e);\n }\n return null;\n\n }" ]
Remove any overrides for an endpoint on the default profile, client @param pathValue path (endpoint) value @param requestType path request type. "GET", "POST", etc @return true if success, false otherwise
[ "public static boolean removeDefaultCustomResponse(String pathValue, String requestType) {\n try {\n JSONObject profile = getDefaultProfile();\n String profileName = profile.getString(\"name\");\n PathValueClient client = new PathValueClient(profileName, false);\n return client.removeCustomResponse(pathValue, requestType);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }" ]
[ "public static void parse(Reader src, StatementHandler handler)\n throws IOException {\n new NTriplesParser(src, handler).parse();\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 UndeployDescription of(final DeploymentDescription deploymentDescription) {\n Assert.checkNotNullParam(\"deploymentDescription\", deploymentDescription);\n return of(deploymentDescription.getName()).addServerGroups(deploymentDescription.getServerGroups());\n }", "public EventBus emitAsync(Enum<?> event, Object... args) {\n return _emitWithOnceBus(eventContextAsync(event, args));\n }", "public void moveDown(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if ((index >= 0) && (index < (m_container.getComponentCount() - 1))) {\n m_container.removeComponent(row);\n m_container.addComponent(row, index + 1);\n }\n updateButtonBars();\n }", "protected void cacheCollection() {\n this.clear();\n for (FluentModelTImpl childResource : this.listChildResources()) {\n this.childCollection.put(childResource.childResourceKey(), childResource);\n }\n }", "public void makePickable(GVRSceneObject sceneObject) {\n try {\n GVRMeshCollider collider = new GVRMeshCollider(sceneObject.getGVRContext(), false);\n sceneObject.attachComponent(collider);\n } catch (Exception e) {\n // Possible that some objects (X3D panel nodes) are without mesh\n Log.e(Log.SUBSYSTEM.INPUT, TAG, \"makePickable(): possible that some objects (X3D panel nodes) are without mesh!\");\n }\n }", "public static List<Node> getSiblings(Node parent, Node element) {\n\t\tList<Node> result = new ArrayList<>();\n\t\tNodeList list = parent.getChildNodes();\n\n\t\tfor (int i = 0; i < list.getLength(); i++) {\n\t\t\tNode el = list.item(i);\n\n\t\t\tif (el.getNodeName().equals(element.getNodeName())) {\n\t\t\t\tresult.add(el);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}", "private Renderer createRenderer(T content, ViewGroup parent) {\n int prototypeIndex = getPrototypeIndex(content);\n Renderer renderer = getPrototypeByIndex(prototypeIndex).copy();\n renderer.onCreate(content, layoutInflater, parent);\n return renderer;\n }" ]
Construct an InterestRateSwapProductDescriptor from a node in a FpML file. @param trade The node containing the swap. @return Descriptor of the swap.
[ "private ProductDescriptor getSwapProductDescriptor(Element trade) {\r\n\r\n\t\tInterestRateSwapLegProductDescriptor legReceiver = null;\r\n\t\tInterestRateSwapLegProductDescriptor legPayer = null;\r\n\r\n\t\tNodeList legs = trade.getElementsByTagName(\"swapStream\");\r\n\t\tfor(int legIndex = 0; legIndex < legs.getLength(); legIndex++) {\r\n\t\t\tElement leg = (Element) legs.item(legIndex);\r\n\r\n\t\t\tboolean isPayer = leg.getElementsByTagName(\"payerPartyReference\").item(0).getAttributes().getNamedItem(\"href\").getNodeValue().equals(homePartyId);\r\n\r\n\t\t\tif(isPayer) {\r\n\t\t\t\tlegPayer = getSwapLegProductDescriptor(leg);\r\n\t\t\t} else {\r\n\t\t\t\tlegReceiver = getSwapLegProductDescriptor(leg);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn new InterestRateSwapProductDescriptor(legReceiver, legPayer);\r\n\t}" ]
[ "public void saveFile(File file, String type)\n {\n if (file != null)\n {\n m_treeController.saveFile(file, type);\n }\n }", "private TransactionManager getTransactionManager()\r\n {\r\n TransactionManager retval = null;\r\n try\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"getTransactionManager called\");\r\n retval = TransactionManagerFactoryFactory.instance().getTransactionManager();\r\n }\r\n catch (TransactionManagerFactoryException e)\r\n {\r\n log.warn(\"Exception trying to obtain TransactionManager from Factory\", e);\r\n e.printStackTrace();\r\n }\r\n return retval;\r\n }", "public static final PatchOperationTarget createLocal(final File jbossHome, List<File> moduleRoots, List<File> bundlesRoots) throws IOException {\n final PatchTool tool = PatchTool.Factory.createLocalTool(jbossHome, moduleRoots, bundlesRoots);\n return new LocalPatchOperationTarget(tool);\n }", "public void generateTracedFile(final IFileSystemAccess2 fsa, final String path, final EObject rootTrace, final StringConcatenationClient code) {\n final CompositeGeneratorNode node = this.trace(rootTrace, code);\n this.generateTracedFile(fsa, path, node);\n }", "protected Path createTempDirectory(String prefix) {\n try {\n return Files.createTempDirectory(tempDirectory, prefix);\n } catch (IOException e) {\n throw new AllureCommandException(e);\n }\n }", "private String getApiKey(CmsObject cms, String sitePath) throws CmsException {\n\n String res = cms.readPropertyObject(\n sitePath,\n CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY_WORKPLACE,\n true).getValue();\n\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(res)) {\n res = cms.readPropertyObject(sitePath, CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY, true).getValue();\n }\n return res;\n\n }", "public Duration getDuration(int field) throws MPXJException\n {\n Duration result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = DurationUtility.getInstance(m_fields[field], m_formats.getDurationDecimalFormat(), m_locale);\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "public static base_response add(nitro_service client, linkset resource) throws Exception {\n\t\tlinkset addresource = new linkset();\n\t\taddresource.id = resource.id;\n\t\treturn addresource.add_resource(client);\n\t}", "public static DMatrixRMaj convert(DMatrixRBlock src , DMatrixRMaj dst )\n {\n return ConvertDMatrixStruct.convert(src,dst);\n }" ]
Set the week day. @param weekDayStr the week day to set.
[ "public void setWeekDay(String weekDayStr) {\n\n final WeekDay weekDay = WeekDay.valueOf(weekDayStr);\n if ((m_model.getWeekDay() != null) || !m_model.getWeekDay().equals(weekDay)) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDay(weekDay);\n onValueChange();\n }\n });\n\n }\n\n }" ]
[ "public String getUserProfile(String userId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_USER_PROFILE);\r\n\r\n parameters.put(\"user_id\", userId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element payload = response.getPayload();\r\n return payload.getAttribute(\"url\");\r\n }", "public double[][] Kernel2D(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\n int r = size / 2;\n double[][] kernel = new double[size][size];\n\n // compute kernel\n double sum = 0;\n for (int y = -r, i = 0; i < size; y++, i++) {\n for (int x = -r, j = 0; j < size; x++, j++) {\n kernel[i][j] = Function2D(x, y);\n sum += kernel[i][j];\n }\n }\n\n for (int i = 0; i < kernel.length; i++) {\n for (int j = 0; j < kernel[0].length; j++) {\n kernel[i][j] /= sum;\n }\n }\n\n return kernel;\n }", "@Override\n public ConditionBuilder as(String variable)\n {\n Assert.notNull(variable, \"Variable name must not be null.\");\n this.setOutputVariablesName(variable);\n return this;\n }", "private Properties parseXML(Document doc, String sectionName) {\n\t\tint found = -1;\n\t\tProperties results = new Properties();\n\t\tNodeList config = null;\n\t\tif (sectionName == null){\n\t\t\tconfig = doc.getElementsByTagName(\"default-config\");\n\t\t\tfound = 0;\n\t\t} else {\n\t\t\tconfig = doc.getElementsByTagName(\"named-config\");\n\t\t\tif(config != null && config.getLength() > 0) {\n\t\t\t\tfor (int i = 0; i < config.getLength(); i++) {\n\t\t\t\t\tNode node = config.item(i);\n\t\t\t\t\tif(node.getNodeType() == Node.ELEMENT_NODE ){\n\t\t\t\t\t\tNamedNodeMap attributes = node.getAttributes();\n\t\t\t\t\t\tif (attributes != null && attributes.getLength() > 0){\n\t\t\t\t\t\t\tNode name = attributes.getNamedItem(\"name\");\n\t\t\t\t\t\t\tif (name.getNodeValue().equalsIgnoreCase(sectionName)){\n\t\t\t\t\t\t\t\tfound = i;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (found == -1){\n\t\t\t\tconfig = null;\n\t\t\t\tlogger.warn(\"Did not find \"+sectionName+\" section in config file. Reverting to defaults.\");\n\t\t\t}\n\t\t}\n\n\t\tif(config != null && config.getLength() > 0) {\n\t\t\tNode node = config.item(found);\n\t\t\tif(node.getNodeType() == Node.ELEMENT_NODE){\n\t\t\t\tElement elementEntry = (Element)node;\n\t\t\t\tNodeList childNodeList = elementEntry.getChildNodes();\n\t\t\t\tfor (int j = 0; j < childNodeList.getLength(); j++) {\n\t\t\t\t\tNode node_j = childNodeList.item(j);\n\t\t\t\t\tif (node_j.getNodeType() == Node.ELEMENT_NODE) {\n\t\t\t\t\t\tElement piece = (Element) node_j;\n\t\t\t\t\t\tNamedNodeMap attributes = piece.getAttributes();\n\t\t\t\t\t\tif (attributes != null && attributes.getLength() > 0){\n\t\t\t\t\t\t\tresults.put(attributes.item(0).getNodeValue(), piece.getTextContent());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}", "public boolean matches(String uri) {\n\t\tif (uri == null) {\n\t\t\treturn false;\n\t\t}\n\t\tMatcher matcher = this.matchPattern.matcher(uri);\n\t\treturn matcher.matches();\n\t}", "private boolean replaceValues(Locale locale) {\n\n try {\n SortedProperties localization = getLocalization(locale);\n if (hasDescriptor()) {\n for (Object itemId : m_container.getItemIds()) {\n Item item = m_container.getItem(itemId);\n String key = item.getItemProperty(TableProperty.KEY).getValue().toString();\n Object value = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == value ? \"\" : value);\n }\n } else {\n m_container.removeAllItems();\n Set<Object> keyset = m_keyset.getKeySet();\n for (Object key : keyset) {\n Object itemId = m_container.addItem();\n Item item = m_container.getItem(itemId);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n Object value = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == value ? \"\" : value);\n }\n if (m_container.getItemIds().isEmpty()) {\n m_container.addItem();\n }\n }\n return true;\n } catch (IOException | CmsException e) {\n // The problem should typically be a problem with locking or reading the file containing the translation.\n // This should be reported in the editor, if false is returned here.\n return false;\n }\n }", "public static void timeCheck(String extra) {\n if (startCheckTime > 0) {\n long now = System.currentTimeMillis();\n long diff = now - nextCheckTime;\n nextCheckTime = now;\n Log.d(Log.SUBSYSTEM.TRACING, \"FPSCounter\", \"[%d, %d] timeCheck: %s\", now, diff, extra);\n }\n }", "public static String getURL(String sourceURI) {\n String retval = sourceURI;\n int qPos = sourceURI.indexOf(\"?\");\n if (qPos != -1) {\n retval = retval.substring(0, qPos);\n }\n\n return retval;\n }", "public double compare(String v1, String v2) {\n // FIXME: it should be possible here to say that, actually, we\n // didn't learn anything from comparing these two values, so that\n // probability is set to 0.5.\n\n if (comparator == null)\n return 0.5; // we ignore properties with no comparator\n\n // first, we call the comparator, to get a measure of how similar\n // these two values are. note that this is not the same as what we\n // are going to return, which is a probability.\n double sim = comparator.compare(v1, v2);\n\n // we have been configured with a high probability (for equal\n // values) and a low probability (for different values). given\n // sim, which is a measure of the similarity somewhere in between\n // equal and different, we now compute our estimate of the\n // probability.\n\n // if sim = 1.0, we return high. if sim = 0.0, we return low. for\n // values in between we need to compute a little. the obvious\n // formula to use would be (sim * (high - low)) + low, which\n // spreads the values out equally spaced between high and low.\n\n // however, if the similarity is higher than 0.5 we don't want to\n // consider this negative evidence, and so there's a threshold\n // there. also, users felt Duke was too eager to merge records,\n // and wanted probabilities to fall off faster with lower\n // probabilities, and so we square sim in order to achieve this.\n\n if (sim >= 0.5)\n return ((high - 0.5) * (sim * sim)) + 0.5;\n else\n return low;\n }" ]
Store the given data and return a uuid for later retrieval of the data @param data @return unique id for the stored data
[ "public String checkIn(byte[] data) {\n String id = UUID.randomUUID().toString();\n dataMap.put(id, data);\n return id;\n }" ]
[ "public List<ServerRedirect> tableServers(int profileId, int serverGroupId) {\n ArrayList<ServerRedirect> servers = new ArrayList<>();\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\" +\n \" AND \" + Constants.SERVER_REDIRECT_GROUP_ID + \" = ?\"\n );\n queryStatement.setInt(1, profileId);\n queryStatement.setInt(2, serverGroupId);\n results = queryStatement.executeQuery();\n while (results.next()) {\n ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.SERVER_REDIRECT_REGION),\n results.getString(Constants.SERVER_REDIRECT_SRC_URL),\n results.getString(Constants.SERVER_REDIRECT_DEST_URL),\n results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));\n curServer.setProfileId(profileId);\n servers.add(curServer);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return servers;\n }", "public static double TopsoeDivergence(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n double den = p[i] + q[i];\n r += p[i] * Math.log(2 * p[i] / den) + q[i] * Math.log(2 * q[i] / den);\n }\n }\n return r;\n }", "public Rectangle getTextSize(String text, Font font) {\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\t\t// calculate text width and height\n\t\tfloat textWidth = template.getEffectiveStringWidth(text, false);\n\t\tfloat ascent = bf.getAscentPoint(text, font.getSize());\n\t\tfloat descent = bf.getDescentPoint(text, font.getSize());\n\t\tfloat textHeight = ascent - descent;\n\t\ttemplate.restoreState();\n\t\treturn new Rectangle(0, 0, textWidth, textHeight);\n\t}", "public void updateIteratorPosition(int length) {\n if(length > 0) {\n //make sure we dont go OB\n if((length + character) > parsedLine.line().length())\n length = parsedLine.line().length() - character;\n\n //move word counter to the correct word\n while(hasNextWord() &&\n (length + character) >= parsedLine.words().get(word).lineIndex() +\n parsedLine.words().get(word).word().length())\n word++;\n\n character = length + character;\n }\n else\n throw new IllegalArgumentException(\"The length given must be > 0 and not exceed the boundary of the line (including the current position)\");\n }", "private void addMetadataProviderForMedia(String key, MetadataProvider provider) {\n if (!metadataProviders.containsKey(key)) {\n metadataProviders.put(key, Collections.newSetFromMap(new ConcurrentHashMap<MetadataProvider, Boolean>()));\n }\n Set<MetadataProvider> providers = metadataProviders.get(key);\n providers.add(provider);\n }", "public static double getRobustTreeEditDistance(String dom1, String dom2) {\n\n\t\tLblTree domTree1 = null, domTree2 = null;\n\t\ttry {\n\t\t\tdomTree1 = getDomTree(dom1);\n\t\t\tdomTree2 = getDomTree(dom2);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\tdouble DD = 0.0;\n\t\tRTED_InfoTree_Opt rted;\n\t\tdouble ted;\n\n\t\trted = new RTED_InfoTree_Opt(1, 1, 1);\n\n\t\t// compute tree edit distance\n\t\trted.init(domTree1, domTree2);\n\n\t\tint maxSize = Math.max(domTree1.getNodeCount(), domTree2.getNodeCount());\n\n\t\trted.computeOptimalStrategy();\n\t\tted = rted.nonNormalizedTreeDist();\n\t\tted /= (double) maxSize;\n\n\t\tDD = ted;\n\t\treturn DD;\n\t}", "public static locationfile get(nitro_service service) throws Exception{\n\t\tlocationfile obj = new locationfile();\n\t\tlocationfile[] response = (locationfile[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public static sslcertkey[] get(nitro_service service, String certkey[]) throws Exception{\n\t\tif (certkey !=null && certkey.length>0) {\n\t\t\tsslcertkey response[] = new sslcertkey[certkey.length];\n\t\t\tsslcertkey obj[] = new sslcertkey[certkey.length];\n\t\t\tfor (int i=0;i<certkey.length;i++) {\n\t\t\t\tobj[i] = new sslcertkey();\n\t\t\t\tobj[i].set_certkey(certkey[i]);\n\t\t\t\tresponse[i] = (sslcertkey) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "private Object initializeLazyPropertiesFromCache(\n\t\t\tfinal String fieldName,\n\t\t\tfinal Object entity,\n\t\t\tfinal SharedSessionContractImplementor session,\n\t\t\tfinal EntityEntry entry,\n\t\t\tfinal CacheEntry cacheEntry\n\t) {\n\t\tthrow new NotSupportedException( \"OGM-9\", \"Lazy properties not supported in OGM\" );\n\t}" ]
Calculates the column width according to its type. @param _property the property. @return the column width.
[ "private static int getColumnWidth(final PropertyDescriptor _property) {\n final Class type = _property.getPropertyType();\n if (Float.class.isAssignableFrom(type) || Double.class.isAssignableFrom(type)) {\n return 70;\n } else if (type == Boolean.class) {\n return 10;\n } else if (Number.class.isAssignableFrom(type)) {\n return 60;\n } else if (type == String.class) {\n return 100;\n } else if (Date.class.isAssignableFrom(type)) {\n return 50;\n } else {\n return 50;\n }\n }" ]
[ "@Override\n public void onNewState(CrawlerContext context, StateVertex vertex) {\n LOG.debug(\"onNewState\");\n StateBuilder state = outModelCache.addStateIfAbsent(vertex);\n visitedStates.putIfAbsent(state.getName(), vertex);\n\n saveScreenshot(context.getBrowser(), state.getName(), vertex);\n\n outputBuilder.persistDom(state.getName(), context.getBrowser().getUnStrippedDom());\n }", "private void setHex() {\r\n\r\n String hRed = Integer.toHexString(getRed());\r\n String hGreen = Integer.toHexString(getGreen());\r\n String hBlue = Integer.toHexString(getBlue());\r\n\r\n if (hRed.length() == 0) {\r\n hRed = \"00\";\r\n }\r\n if (hRed.length() == 1) {\r\n hRed = \"0\" + hRed;\r\n }\r\n if (hGreen.length() == 0) {\r\n hGreen = \"00\";\r\n }\r\n if (hGreen.length() == 1) {\r\n hGreen = \"0\" + hGreen;\r\n }\r\n if (hBlue.length() == 0) {\r\n hBlue = \"00\";\r\n }\r\n if (hBlue.length() == 1) {\r\n hBlue = \"0\" + hBlue;\r\n }\r\n\r\n m_hex = hRed + hGreen + hBlue;\r\n }", "public static MediaType text( String subType, Charset charset ) {\n return nonBinary( TEXT, subType, charset );\n }", "public void setTargetDirectory(String directory) {\n if (directory != null && directory.length() > 0) {\n this.targetDirectory = new File(directory);\n } else {\n this.targetDirectory = null;\n }\n }", "public void setPerms(String photoId, Permissions permissions) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_PERMS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"is_public\", permissions.isPublicFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_friend\", permissions.isFriendFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_family\", permissions.isFamilyFlag() ? \"1\" : \"0\");\r\n parameters.put(\"perm_comment\", Integer.toString(permissions.getComment()));\r\n parameters.put(\"perm_addmeta\", Integer.toString(permissions.getAddmeta()));\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 T findById(Object id) throws RowNotFoundException, TooManyRowsException {\n return findWhere(eq(idColumn.getColumnName(), id)).getSingleResult();\n }", "public static boolean isInverse(DMatrixRMaj a , DMatrixRMaj b , double tol ) {\n if( a.numRows != b.numRows || a.numCols != b.numCols ) {\n return false;\n }\n\n int numRows = a.numRows;\n int numCols = a.numCols;\n\n for( int i = 0; i < numRows; i++ ) {\n for( int j = 0; j < numCols; j++ ) {\n double total = 0;\n for( int k = 0; k < numCols; k++ ) {\n total += a.get(i,k)*b.get(k,j);\n }\n\n if( i == j ) {\n if( !(Math.abs(total-1) <= tol) )\n return false;\n } else if( !(Math.abs(total) <= tol) )\n return false;\n }\n }\n\n return true;\n }", "public static final ProjectFile setProjectNameAndRead(File directory) throws MPXJException\n {\n List<String> projects = listProjectNames(directory);\n\n if (!projects.isEmpty())\n {\n P3DatabaseReader reader = new P3DatabaseReader();\n reader.setProjectName(projects.get(0));\n return reader.read(directory);\n }\n\n return null;\n }", "public void addRowAfter(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if (index >= 0) {\n Component component = m_newComponentFactory.get();\n I_CmsEditableGroupRow newRow = m_rowBuilder.buildRow(this, component);\n m_container.addComponent(newRow, index + 1);\n }\n updatePlaceholder();\n updateButtonBars();\n updateGroupValidation();\n }" ]
Looks up a variable given its name. If none is found then return null.
[ "public <T extends Variable> T lookupVariable(String token) {\n Variable result = variables.get(token);\n return (T)result;\n }" ]
[ "@Override\n public boolean deleteObject(GcsFilename filename, long timeoutMillis) throws IOException {\n HTTPRequest req = makeRequest(filename, null, DELETE, timeoutMillis);\n HTTPResponse resp;\n try {\n resp = urlfetch.fetch(req);\n } catch (IOException e) {\n throw createIOException(new HTTPRequestInfo(req), e);\n }\n switch (resp.getResponseCode()) {\n case 204:\n return true;\n case 404:\n return false;\n default:\n throw HttpErrorHandler.error(new HTTPRequestInfo(req), resp);\n }\n }", "private static byte calculateChecksum(byte[] buffer) {\n\t\tbyte checkSum = (byte)0xFF;\n\t\tfor (int i=1; i<buffer.length-1; i++) {\n\t\t\tcheckSum = (byte) (checkSum ^ buffer[i]);\n\t\t}\n\t\tlogger.trace(String.format(\"Calculated checksum = 0x%02X\", checkSum));\n\t\treturn checkSum;\n\t}", "public static <T> List<T> toList(Iterable<T> items) {\r\n List<T> list = new ArrayList<T>();\r\n addAll(list, items);\r\n return list;\r\n }", "public IndirectionHandler getIndirectionHandler(Object obj)\r\n {\r\n if(obj == null)\r\n {\r\n return null;\r\n }\r\n else if(isNormalOjbProxy(obj))\r\n {\r\n return getDynamicIndirectionHandler(obj);\r\n }\r\n else if(isVirtualOjbProxy(obj))\r\n {\r\n return VirtualProxy.getIndirectionHandler((VirtualProxy) obj);\r\n }\r\n else\r\n {\r\n return null;\r\n }\r\n\r\n }", "public void setRegularExpression(String regularExpression) {\n\t\tif (regularExpression != null)\n\t\t\tthis.regularExpression = Pattern.compile(regularExpression);\n\t\telse\n\t\t\tthis.regularExpression = null;\n\t}", "@PostConstruct\n public void init() {\n this.metricRegistry.register(name(\"gc\"), new GarbageCollectorMetricSet());\n this.metricRegistry.register(name(\"memory\"), new MemoryUsageGaugeSet());\n this.metricRegistry.register(name(\"thread-states\"), new ThreadStatesGaugeSet());\n this.metricRegistry.register(name(\"fd-usage\"), new FileDescriptorRatioGauge());\n }", "public static void writeInt(byte[] bytes, int value, int offset) {\n bytes[offset] = (byte) (0xFF & (value >> 24));\n bytes[offset + 1] = (byte) (0xFF & (value >> 16));\n bytes[offset + 2] = (byte) (0xFF & (value >> 8));\n bytes[offset + 3] = (byte) (0xFF & value);\n }", "private void readDefinitions()\n {\n for (MapRow row : m_tables.get(\"TTL\"))\n {\n Integer id = row.getInteger(\"DEFINITION_ID\");\n List<MapRow> list = m_definitions.get(id);\n if (list == null)\n {\n list = new ArrayList<MapRow>();\n m_definitions.put(id, list);\n }\n list.add(row);\n }\n\n List<MapRow> rows = m_definitions.get(WBS_FORMAT_ID);\n if (rows != null)\n {\n m_wbsFormat = new SureTrakWbsFormat(rows.get(0));\n }\n }", "public Integer getEnd() {\n if (mtasPositionType.equals(POSITION_RANGE)\n || mtasPositionType.equals(POSITION_SET)) {\n return mtasPositionEnd;\n } else if (mtasPositionType.equals(POSITION_SINGLE)) {\n return mtasPositionStart;\n } else {\n return null;\n }\n }" ]
Emits a change event for the given document id. @param nsConfig the configuration for the namespace to which the document referred to by the change event belongs. @param event the change event.
[ "public void emitEvent(\n final NamespaceSynchronizationConfig nsConfig,\n final ChangeEvent<BsonDocument> event) {\n listenersLock.lock();\n try {\n if (nsConfig.getNamespaceListenerConfig() == null) {\n return;\n }\n final NamespaceListenerConfig namespaceListener =\n nsConfig.getNamespaceListenerConfig();\n eventDispatcher.dispatch(() -> {\n try {\n if (namespaceListener.getEventListener() != null) {\n namespaceListener.getEventListener().onEvent(\n BsonUtils.getDocumentId(event.getDocumentKey()),\n ChangeEvents.transformChangeEventForUser(\n event, namespaceListener.getDocumentCodec()));\n }\n } catch (final Exception ex) {\n logger.error(String.format(\n Locale.US,\n \"emitEvent ns=%s documentId=%s emit exception: %s\",\n event.getNamespace(),\n BsonUtils.getDocumentId(event.getDocumentKey()),\n ex), ex);\n }\n return null;\n });\n } finally {\n listenersLock.unlock();\n }\n }" ]
[ "public Node createEmbedded(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\tResult result = executionEngine.execute( getCreateEmbeddedNodeQuery(), params );\n\t\treturn singleResult( result );\n\t}", "public CurrencyQueryBuilder setNumericCodes(int... codes) {\n return set(CurrencyQuery.KEY_QUERY_NUMERIC_CODES,\n Arrays.stream(codes).boxed().collect(Collectors.toList()));\n }", "private Long fetchServiceId(ServiceReference serviceReference) {\n return (Long) serviceReference.getProperty(org.osgi.framework.Constants.SERVICE_ID);\n }", "public static String ruleToRuleContentsString(Rule originalRule, int indentLevel)\n {\n if (originalRule instanceof Context && ((Context) originalRule).containsKey(RuleMetadataType.RULE_XML))\n {\n return (String) ((Context) originalRule).get(RuleMetadataType.RULE_XML);\n }\n\n if (!(originalRule instanceof RuleBuilder))\n {\n return wrap(originalRule.toString(), MAX_WIDTH, indentLevel);\n }\n final RuleBuilder rule = (RuleBuilder) originalRule;\n StringBuilder result = new StringBuilder();\n if (indentLevel == 0)\n result.append(\"addRule()\");\n\n for (Condition condition : rule.getConditions())\n {\n String conditionToString = conditionToString(condition, indentLevel + 1);\n if (!conditionToString.isEmpty())\n {\n result.append(System.lineSeparator());\n insertPadding(result, indentLevel + 1);\n result.append(\".when(\").append(wrap(conditionToString, MAX_WIDTH, indentLevel + 2)).append(\")\");\n }\n\n }\n for (Operation operation : rule.getOperations())\n {\n String operationToString = operationToString(operation, indentLevel + 1);\n if (!operationToString.isEmpty())\n {\n result.append(System.lineSeparator());\n insertPadding(result, indentLevel + 1);\n result.append(\".perform(\").append(wrap(operationToString, MAX_WIDTH, indentLevel + 2)).append(\")\");\n }\n }\n if (rule.getId() != null && !rule.getId().isEmpty())\n {\n result.append(System.lineSeparator());\n insertPadding(result, indentLevel);\n result.append(\"withId(\\\"\").append(rule.getId()).append(\"\\\")\");\n }\n\n if (rule.priority() != 0)\n {\n result.append(System.lineSeparator());\n insertPadding(result, indentLevel);\n result.append(\".withPriority(\").append(rule.priority()).append(\")\");\n }\n\n return result.toString();\n }", "List getOrderby()\r\n {\r\n List result = _getOrderby();\r\n Iterator iter = getCriteria().iterator();\r\n Object crit;\r\n\r\n while (iter.hasNext())\r\n {\r\n crit = iter.next();\r\n if (crit instanceof Criteria)\r\n {\r\n result.addAll(((Criteria) crit).getOrderby());\r\n }\r\n }\r\n\r\n return result;\r\n }", "public static vpnclientlessaccesspolicy[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tvpnclientlessaccesspolicy obj = new vpnclientlessaccesspolicy();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tvpnclientlessaccesspolicy[] response = (vpnclientlessaccesspolicy[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "public void save() throws CmsException {\n\n if (hasChanges()) {\n switch (m_bundleType) {\n case PROPERTY:\n saveLocalization();\n saveToPropertyVfsBundle();\n break;\n\n case XML:\n saveLocalization();\n saveToXmlVfsBundle();\n\n break;\n\n case DESCRIPTOR:\n break;\n default:\n throw new IllegalArgumentException();\n }\n if (null != m_descFile) {\n saveToBundleDescriptor();\n }\n\n resetChanges();\n }\n\n }", "public void setDefaultInterval(long defaultInterval) {\n \tif(defaultInterval <= 0) {\n \t\tLOG.severe(\"collector.scheduler.interval must be greater than 0. Recommended value is 500-1000. Current value is \" + defaultInterval);\n \t\tthrow new IllegalArgumentException(\"collector.scheduler.interval must be greater than 0. Recommended value is 500-1000. Current value is \" + defaultInterval);\n \t}\n this.defaultInterval = defaultInterval;\n }", "public boolean matches(String uri) {\n\t\tif (uri == null) {\n\t\t\treturn false;\n\t\t}\n\t\tMatcher matcher = this.matchPattern.matcher(uri);\n\t\treturn matcher.matches();\n\t}" ]
Curries a function that takes one argument. @param function the original function. May not be <code>null</code>. @param argument the fixed argument. @return a function that takes no arguments. Never <code>null</code>.
[ "@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}" ]
[ "private void processCalendars() throws SQLException\n {\n for (ResultSetRow row : getRows(\"SELECT * FROM MSP_CALENDARS WHERE PROJ_ID=?\", m_projectID))\n {\n processCalendar(row);\n }\n\n updateBaseCalendarNames();\n\n processCalendarData(m_project.getCalendars());\n }", "@RequestMapping(value = \"group\", method = RequestMethod.GET)\n public String newGroupGet(Model model) {\n model.addAttribute(\"groups\",\n pathOverrideService.findAllGroups());\n return \"groups\";\n }", "public void update(int width, int height, float[] data)\n throws IllegalArgumentException\n {\n if ((width <= 0) || (height <= 0) ||\n (data == null) || (data.length < height * width * mFloatsPerPixel))\n {\n throw new IllegalArgumentException();\n }\n NativeFloatImage.update(getNative(), width, height, 0, data);\n }", "public static GVRCameraRig makeInstance(GVRContext gvrContext) {\n final GVRCameraRig result = gvrContext.getApplication().getDelegate().makeCameraRig(gvrContext);\n result.init(gvrContext);\n return result;\n }", "public static Optimizer<DifferentiableFunction> getRegularizedOptimizer(final Optimizer<DifferentiableFunction> opt,\n final double l1Lambda, final double l2Lambda) {\n if (l1Lambda == 0 && l2Lambda == 0) {\n return opt;\n }\n return new Optimizer<DifferentiableFunction>() {\n \n @Override\n public boolean minimize(DifferentiableFunction objective, IntDoubleVector point) {\n DifferentiableFunction fn = getRegularizedFn(objective, false, l1Lambda, l2Lambda);\n return opt.minimize(fn, point);\n }\n \n };\n }", "private void recordTime(Tracked op,\n long timeNS,\n long numEmptyResponses,\n long valueSize,\n long keySize,\n long getAllAggregateRequests) {\n counters.get(op).addRequest(timeNS,\n numEmptyResponses,\n valueSize,\n keySize,\n getAllAggregateRequests);\n\n if (logger.isTraceEnabled() && !storeName.contains(\"aggregate\") && !storeName.contains(\"voldsys$\"))\n logger.trace(\"Store '\" + storeName + \"' logged a \" + op.toString() + \" request taking \" +\n ((double) timeNS / voldemort.utils.Time.NS_PER_MS) + \" ms\");\n }", "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 }", "private Video generateRandomVideo() {\n Video video = new Video();\n configureFavoriteStatus(video);\n configureLikeStatus(video);\n configureLiveStatus(video);\n configureTitleAndThumbnail(video);\n return video;\n }", "public AwsServiceClient withCodecRegistry(@Nonnull final CodecRegistry codecRegistry) {\n return new AwsServiceClientImpl(proxy.withCodecRegistry(codecRegistry), dispatcher);\n }" ]