query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Returns the parameter key of the facet with the given name. @param facet the facet's name. @return the parameter key for the facet.
[ "String getFacetParamKey(String facet) {\n\n I_CmsSearchControllerFacetField fieldFacet = m_result.getController().getFieldFacets().getFieldFacetController().get(\n facet);\n if (fieldFacet != null) {\n return fieldFacet.getConfig().getParamKey();\n }\n I_CmsSearchControllerFacetRange rangeFacet = m_result.getController().getRangeFacets().getRangeFacetController().get(\n facet);\n if (rangeFacet != null) {\n return rangeFacet.getConfig().getParamKey();\n }\n I_CmsSearchControllerFacetQuery queryFacet = m_result.getController().getQueryFacet();\n if ((queryFacet != null) && queryFacet.getConfig().getName().equals(facet)) {\n return queryFacet.getConfig().getParamKey();\n }\n\n // Facet did not exist\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_FACET_NOT_CONFIGURED_1, facet), new Throwable());\n\n return null;\n }" ]
[ "public static AnnotationNode getAnnotation(AnnotatedNode node, String name) {\r\n List<AnnotationNode> annotations = node.getAnnotations();\r\n for (AnnotationNode annot : annotations) {\r\n if (annot.getClassNode().getName().equals(name)) {\r\n return annot;\r\n }\r\n }\r\n return null;\r\n }", "public ArtifactName build() {\n String groupId = this.groupId;\n String artifactId = this.artifactId;\n String classifier = this.classifier;\n String packaging = this.packaging;\n String version = this.version;\n if (artifact != null && !artifact.isEmpty()) {\n final String[] artifactSegments = artifact.split(\":\");\n // groupId:artifactId:version[:packaging][:classifier].\n String value;\n switch (artifactSegments.length) {\n case 5:\n value = artifactSegments[4].trim();\n if (!value.isEmpty()) {\n classifier = value;\n }\n case 4:\n value = artifactSegments[3].trim();\n if (!value.isEmpty()) {\n packaging = value;\n }\n case 3:\n value = artifactSegments[2].trim();\n if (!value.isEmpty()) {\n version = value;\n }\n case 2:\n value = artifactSegments[1].trim();\n if (!value.isEmpty()) {\n artifactId = value;\n }\n case 1:\n value = artifactSegments[0].trim();\n if (!value.isEmpty()) {\n groupId = value;\n }\n }\n }\n return new ArtifactNameImpl(groupId, artifactId, classifier, packaging, version);\n }", "public void onDrawFrame(float frameTime) {\n final GVRSceneObject owner = getOwnerObject();\n if (owner == null) {\n return;\n }\n\n final int size = mRanges.size();\n final GVRTransform t = getGVRContext().getMainScene().getMainCameraRig().getCenterCamera().getTransform();\n\n for (final Object[] range : mRanges) {\n ((GVRSceneObject)range[1]).setEnable(false);\n }\n\n for (int i = size - 1; i >= 0; --i) {\n final Object[] range = mRanges.get(i);\n final GVRSceneObject child = (GVRSceneObject) range[1];\n if (child.getParent() != owner) {\n Log.w(TAG, \"the scene object for distance greater than \" + range[0] + \" is not a child of the owner; skipping it\");\n continue;\n }\n\n final float[] values = child.getBoundingVolumeRawValues();\n mCenter.set(values[0], values[1], values[2], 1.0f);\n mVector.set(t.getPositionX(), t.getPositionY(), t.getPositionZ(), 1.0f);\n\n mVector.sub(mCenter);\n mVector.negate();\n\n float distance = mVector.dot(mVector);\n\n if (distance >= (Float) range[0]) {\n child.setEnable(true);\n break;\n }\n }\n }", "public void notifyEventListeners(ZWaveEvent event) {\n\t\tlogger.debug(\"Notifying event listeners\");\n\t\tfor (ZWaveEventListener listener : this.zwaveEventListeners) {\n\t\t\tlogger.trace(\"Notifying {}\", listener.toString());\n\t\t\tlistener.ZWaveIncomingEvent(event);\n\t\t}\n\t}", "private Integer getKeyPartitionId(byte[] key) {\n Integer keyPartitionId = storeInstance.getNodesPartitionIdForKey(nodeId, key);\n\n Utils.notNull(keyPartitionId);\n return keyPartitionId;\n }", "private String tail(String moduleName) {\n if (moduleName.indexOf(MODULE_NAME_SEPARATOR) > 0) {\n return moduleName.substring(moduleName.indexOf(MODULE_NAME_SEPARATOR) + 1);\n } else {\n return \"\";\n }\n }", "protected void handleINEvent(Exchange exchange, String reqFid) throws Fault {\n Message inMsg = exchange.getInMessage();\n\n EventProducerInterceptor epi = null;\n FlowIdHelper.setFlowId(inMsg, reqFid);\n\n ListIterator<Interceptor<? extends Message>> interceptors = inMsg\n .getInterceptorChain().getIterator();\n\n while (interceptors.hasNext() && epi == null) {\n Interceptor<? extends Message> interceptor = interceptors.next();\n\n if (interceptor instanceof EventProducerInterceptor) {\n epi = (EventProducerInterceptor) interceptor;\n epi.handleMessage(inMsg);\n }\n }\n }", "public void delete(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_DELETE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // This method has no specific response - It returns an empty\r\n // sucess response if it completes without error.\r\n }", "public static String[] allUpperCase(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].toUpperCase();\n\t\t\t}\n\t\t}\n\t\treturn tmp;\n\t}" ]
Creates a map of identifiers or page titles to documents retrieved via the APIs. @param numOfEntities number of entities that should be retrieved @param properties WbGetEntitiesProperties object that includes all relevant parameters for the wbgetentities action @return map of document identifiers or titles to documents retrieved via the API URL @throws MediaWikiApiErrorException @throws IOException
[ "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 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}", "public static boolean isAlternative(EnhancedAnnotated<?, ?> annotated, MergedStereotypes<?, ?> mergedStereotypes) {\n return annotated.isAnnotationPresent(Alternative.class) || mergedStereotypes.isAlternative();\n }", "public static lbvserver_servicegroup_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_servicegroup_binding obj = new lbvserver_servicegroup_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_servicegroup_binding response[] = (lbvserver_servicegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void setColorForTotal(int row, int column, Color color){\r\n\t\tint mapC = (colors.length-1) - column;\r\n\t\tint mapR = (colors[0].length-1) - row;\r\n\t\tcolors[mapC][mapR]=color;\t\t\r\n\t}", "private int getIndicatorStartPos() {\n switch (getPosition()) {\n case TOP:\n return mIndicatorClipRect.left;\n case RIGHT:\n return mIndicatorClipRect.top;\n case BOTTOM:\n return mIndicatorClipRect.left;\n default:\n return mIndicatorClipRect.top;\n }\n }", "public static vpnglobal_intranetip_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_intranetip_binding obj = new vpnglobal_intranetip_binding();\n\t\tvpnglobal_intranetip_binding response[] = (vpnglobal_intranetip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "BsonDocument getNextVersion() {\n if (!this.hasVersion() || this.getVersionDoc() == null) {\n return getFreshVersionDocument();\n }\n final BsonDocument nextVersion = BsonUtils.copyOfDocument(this.getVersionDoc());\n nextVersion.put(\n Fields.VERSION_COUNTER_FIELD,\n new BsonInt64(this.getVersion().getVersionCounter() + 1));\n return nextVersion;\n }", "private Duration assignmentDuration(Task task, Duration work)\n {\n Duration result = work;\n\n if (result != null)\n {\n if (result.getUnits() == TimeUnit.PERCENT)\n {\n Duration taskWork = task.getWork();\n if (taskWork != null)\n {\n result = Duration.getInstance(taskWork.getDuration() * result.getDuration(), taskWork.getUnits());\n }\n }\n }\n return result;\n }", "protected static String getTimePrecisionString(byte precision) {\n\t\tswitch (precision) {\n\t\tcase TimeValue.PREC_SECOND:\n\t\t\treturn \"sec\";\n\t\tcase TimeValue.PREC_MINUTE:\n\t\t\treturn \"min\";\n\t\tcase TimeValue.PREC_HOUR:\n\t\t\treturn \"hour\";\n\t\tcase TimeValue.PREC_DAY:\n\t\t\treturn \"day\";\n\t\tcase TimeValue.PREC_MONTH:\n\t\t\treturn \"month\";\n\t\tcase TimeValue.PREC_YEAR:\n\t\t\treturn \"year\";\n\t\tcase TimeValue.PREC_DECADE:\n\t\t\treturn \"decade\";\n\t\tcase TimeValue.PREC_100Y:\n\t\t\treturn \"100 years\";\n\t\tcase TimeValue.PREC_1KY:\n\t\t\treturn \"1000 years\";\n\t\tcase TimeValue.PREC_10KY:\n\t\t\treturn \"10K years\";\n\t\tcase TimeValue.PREC_100KY:\n\t\t\treturn \"100K years\";\n\t\tcase TimeValue.PREC_1MY:\n\t\t\treturn \"1 million years\";\n\t\tcase TimeValue.PREC_10MY:\n\t\t\treturn \"10 million years\";\n\t\tcase TimeValue.PREC_100MY:\n\t\t\treturn \"100 million years\";\n\t\tcase TimeValue.PREC_1GY:\n\t\t\treturn \"1000 million years\";\n\t\tdefault:\n\t\t\treturn \"Unsupported precision \" + precision;\n\t\t}\n\t}" ]
Returns the number of history entries for a client @param profileId ID of profile @param clientUUID UUID of client @param searchFilter unused @return number of history entries
[ "public int getHistoryCount(int profileId, String clientUUID, HashMap<String, String[]> searchFilter) {\n int count = 0;\n Statement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n\n String sqlQuery = \"SELECT COUNT(\" + Constants.GENERIC_ID + \") FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is set or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId + \" \";\n }\n\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \"AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"' \";\n }\n\n sqlQuery += \";\";\n\n logger.info(\"Query: {}\", sqlQuery);\n\n query = sqlConnection.createStatement();\n results = query.executeQuery(sqlQuery);\n if (results.next()) {\n count = results.getInt(1);\n }\n query.close();\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n return count;\n }" ]
[ "public void add(ResourceCollection rc) {\n if (rc instanceof FileSet) {\n FileSet fs = (FileSet) rc;\n fs.setProject(getProject());\n }\n resources.add(rc);\n }", "@Override\n\tpublic int compareTo(IPAddressString other) {\n\t\tif(this == other) {\n\t\t\treturn 0;\n\t\t}\n\t\tboolean isValid = isValid();\n\t\tboolean otherIsValid = other.isValid();\n\t\tif(!isValid && !otherIsValid) {\n\t\t\treturn toString().compareTo(other.toString());\n\t\t}\n\t\treturn addressProvider.providerCompare(other.addressProvider);\n\t}", "public void setup( int numSamples , int sampleSize ) {\n mean = new double[ sampleSize ];\n A.reshape(numSamples,sampleSize,false);\n sampleIndex = 0;\n numComponents = -1;\n }", "public static Map<FieldType, String> getDefaultAliases()\n {\n Map<FieldType, String> map = new HashMap<FieldType, String>();\n\n map.put(TaskField.DATE1, \"Suspend Date\");\n map.put(TaskField.DATE2, \"Resume Date\");\n map.put(TaskField.TEXT1, \"Code\");\n map.put(TaskField.TEXT2, \"Activity Type\");\n map.put(TaskField.TEXT3, \"Status\");\n map.put(TaskField.NUMBER1, \"Primary Resource Unique ID\");\n\n return map;\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 static byte[] decodeBase64(String value) {\n int byteShift = 4;\n int tmp = 0;\n boolean done = false;\n final StringBuilder buffer = new StringBuilder();\n\n for (int i = 0; i != value.length(); i++) {\n final char c = value.charAt(i);\n final int sixBit = (c < 123) ? EncodingGroovyMethodsSupport.TRANSLATE_TABLE[c] : 66;\n\n if (sixBit < 64) {\n if (done)\n throw new RuntimeException(\"= character not at end of base64 value\"); // TODO: change this exception type\n\n tmp = (tmp << 6) | sixBit;\n\n if (byteShift-- != 4) {\n buffer.append((char) ((tmp >> (byteShift * 2)) & 0XFF));\n }\n\n } else if (sixBit == 64) {\n\n byteShift--;\n done = true;\n\n } else if (sixBit == 66) {\n // RFC 2045 says that I'm allowed to take the presence of\n // these characters as evidence of data corruption\n // So I will\n throw new RuntimeException(\"bad character in base64 value\"); // TODO: change this exception type\n }\n\n if (byteShift == 0) byteShift = 4;\n }\n\n try {\n return buffer.toString().getBytes(\"ISO-8859-1\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"Base 64 decode produced byte values > 255\"); // TODO: change this exception type\n }\n }", "public void visitParameter(String name, int access) {\n if (mv != null) {\n mv.visitParameter(name, access);\n }\n }", "public Object[] getForeignKeyValues(Object obj, ClassDescriptor mif)\r\n throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] fks = getForeignKeyFieldDescriptors(mif);\r\n // materialize object only if FK fields are declared\r\n if(fks.length > 0) obj = ProxyHelper.getRealObject(obj);\r\n Object[] result = new Object[fks.length];\r\n for (int i = 0; i < result.length; i++)\r\n {\r\n FieldDescriptor fmd = fks[i];\r\n PersistentField f = fmd.getPersistentField();\r\n\r\n // BRJ: do NOT convert.\r\n // conversion is done when binding the sql-statement\r\n //\r\n // FieldConversion fc = fmd.getFieldConversion();\r\n // Object val = fc.javaToSql(f.get(obj));\r\n\r\n result[i] = f.get(obj);\r\n }\r\n return result;\r\n }", "protected String createGlobalStyle()\n {\n StringBuilder ret = new StringBuilder();\n ret.append(createFontFaces());\n ret.append(\"\\n\");\n ret.append(defaultStyle);\n return ret.toString();\n }" ]
Returns the Class object of the class specified in the OJB.properties file for the "PersistentFieldClass" property. @return Class The Class object of the "PersistentFieldClass" class specified in the OJB.properties file.
[ "public Class getPersistentFieldClass()\r\n {\r\n if (m_persistenceClass == null)\r\n {\r\n Properties properties = new Properties();\r\n try\r\n {\r\n this.logWarning(\"Loading properties file: \" + getPropertiesFile());\r\n properties.load(new FileInputStream(getPropertiesFile()));\r\n }\r\n catch (IOException e)\r\n {\r\n this.logWarning(\"Could not load properties file '\" + getPropertiesFile()\r\n + \"'. Using PersistentFieldDefaultImpl.\");\r\n e.printStackTrace();\r\n }\r\n try\r\n {\r\n String className = properties.getProperty(\"PersistentFieldClass\");\r\n\r\n m_persistenceClass = loadClass(className);\r\n }\r\n catch (ClassNotFoundException e)\r\n {\r\n e.printStackTrace();\r\n m_persistenceClass = PersistentFieldPrivilegedImpl.class;\r\n }\r\n logWarning(\"PersistentFieldClass: \" + m_persistenceClass.toString());\r\n }\r\n return m_persistenceClass;\r\n }" ]
[ "private void increaseBeliefCount(String bName) {\n Object belief = this.getBelief(bName);\n int count = 0;\n if (belief!=null) {\n count = (Integer) belief;\n }\n this.setBelief(bName, count + 1);\n }", "private Object[] convert(FieldConversion[] fcs, Object[] values)\r\n {\r\n Object[] convertedValues = new Object[values.length];\r\n \r\n for (int i= 0; i < values.length; i++)\r\n {\r\n convertedValues[i] = fcs[i].sqlToJava(values[i]);\r\n }\r\n\r\n return convertedValues;\r\n }", "private static XMLStreamException unexpectedAttribute(final XMLStreamReader reader, final int index) {\n return SecurityManagerLogger.ROOT_LOGGER.unexpectedAttribute(reader.getAttributeName(index), reader.getLocation());\n }", "public void deleteModule(final String moduleId) {\n final DbModule module = getModule(moduleId);\n repositoryHandler.deleteModule(module.getId());\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n repositoryHandler.deleteArtifact(gavc);\n }\n }", "private boolean findBinding(Injector injector, Class<?> type) {\n boolean found = false;\n for (Key<?> key : injector.getBindings().keySet()) {\n if (key.getTypeLiteral().getRawType().equals(type)) {\n found = true;\n break;\n }\n }\n if (!found && injector.getParent() != null) {\n return findBinding(injector.getParent(), type);\n }\n\n return found;\n }", "public static String normalize(final CharSequence self) {\n final String s = self.toString();\n int nx = s.indexOf('\\r');\n\n if (nx < 0) {\n return s;\n }\n\n final int len = s.length();\n final StringBuilder sb = new StringBuilder(len);\n\n int i = 0;\n\n do {\n sb.append(s, i, nx);\n sb.append('\\n');\n\n if ((i = nx + 1) >= len) break;\n\n if (s.charAt(i) == '\\n') {\n // skip the LF in CR LF\n if (++i >= len) break;\n }\n\n nx = s.indexOf('\\r', i);\n } while (nx > 0);\n\n sb.append(s, i, len);\n\n return sb.toString();\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}", "public Diff compare(File f1, File f2) throws Exception {\n\t\treturn this.compare(getCtType(f1), getCtType(f2));\n\t}", "public CancelIndicator newCancelIndicator(final ResourceSet rs) {\n CancelIndicator _xifexpression = null;\n if ((rs instanceof XtextResourceSet)) {\n final boolean cancelationAllowed = (this.cancelationAllowed.get()).booleanValue();\n final int current = ((XtextResourceSet)rs).getModificationStamp();\n final CancelIndicator _function = () -> {\n return (cancelationAllowed && (((XtextResourceSet)rs).isOutdated() || (current != ((XtextResourceSet)rs).getModificationStamp())));\n };\n return _function;\n } else {\n _xifexpression = CancelIndicator.NullImpl;\n }\n return _xifexpression;\n }" ]
create partitions in the broker @param topic topic name @param partitionNum partition numbers @param enlarge enlarge partition number if broker configuration has setted @return partition number in the broker @throws IOException if an I/O error occurs
[ "public int createPartitions(String topic, int partitionNum, boolean enlarge) throws IOException {\n KV<Receive, ErrorMapping> response = send(new CreaterRequest(topic, partitionNum, enlarge));\n return Utils.deserializeIntArray(response.k.buffer())[0];\n }" ]
[ "public Iterable<BoxLegalHoldAssignment.Info> getAssignments(String ... fields) {\n return this.getAssignments(null, null, DEFAULT_LIMIT, fields);\n }", "private int getMaxHeight() {\n int result = 0;\n for (int i = 0; i < segmentCount; i++) {\n result = Math.max(result, segmentHeight(i, false));\n }\n return result;\n }", "public static InputStream getContentStream(String stringUrl) throws MalformedURLException, IOException {\n URL url = new URL(stringUrl);\n \n URLConnection urlConnection = url.openConnection();\n \n InputStream is = urlConnection.getInputStream();\n if (\"gzip\".equals(urlConnection.getContentEncoding())) {\n is = new GZIPInputStream(is);\n }\n\n return is;\n }", "public static int cudnnCreatePersistentRNNPlan(\n cudnnRNNDescriptor rnnDesc, \n int minibatch, \n int dataType, \n cudnnPersistentRNNPlan plan)\n {\n return checkResult(cudnnCreatePersistentRNNPlanNative(rnnDesc, minibatch, dataType, plan));\n }", "public void setDuration(float start, float end)\n {\n for (GVRAnimation anim : mAnimations)\n {\n anim.setDuration(start,end);\n }\n }", "public Date getCompleteThrough()\n {\n Date value = (Date) getCachedValue(TaskField.COMPLETE_THROUGH);\n if (value == null)\n {\n int percentComplete = NumberHelper.getInt(getPercentageComplete());\n switch (percentComplete)\n {\n case 0:\n {\n break;\n }\n\n case 100:\n {\n value = getActualFinish();\n break;\n }\n\n default:\n {\n Date actualStart = getActualStart();\n Duration duration = getDuration();\n if (actualStart != null && duration != null)\n {\n double durationValue = (duration.getDuration() * percentComplete) / 100d;\n duration = Duration.getInstance(durationValue, duration.getUnits());\n ProjectCalendar calendar = getEffectiveCalendar();\n value = calendar.getDate(actualStart, duration, true);\n }\n break;\n }\n }\n\n set(TaskField.COMPLETE_THROUGH, value);\n }\n return value;\n }", "private static InterestRateSwapLegProductDescriptor getSwapLegProductDescriptor(Element leg, String forwardCurveName, String discountCurveName,\r\n\t\t\tDayCountConvention daycountConvention) {\r\n\r\n\t\tboolean isFixed = leg.getElementsByTagName(\"interestType\").item(0).getTextContent().equalsIgnoreCase(\"FIX\");\r\n\r\n\t\tArrayList<Period> periods \t\t= new ArrayList<>();\r\n\t\tArrayList<Double> notionalsList\t= new ArrayList<>();\r\n\t\tArrayList<Double> rates\t\t\t= new ArrayList<>();\r\n\r\n\t\t//extracting data for each period\r\n\t\tNodeList periodsXML = leg.getElementsByTagName(\"incomePayment\");\r\n\t\tfor(int periodIndex = 0; periodIndex < periodsXML.getLength(); periodIndex++) {\r\n\r\n\t\t\tElement periodXML = (Element) periodsXML.item(periodIndex);\r\n\r\n\t\t\tLocalDate startDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"startDate\").item(0).getTextContent());\r\n\t\t\tLocalDate endDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"endDate\").item(0).getTextContent());\r\n\r\n\t\t\tLocalDate fixingDate\t= startDate;\r\n\t\t\tLocalDate paymentDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"payDate\").item(0).getTextContent());\r\n\r\n\t\t\tif(! isFixed) {\r\n\t\t\t\tfixingDate = LocalDate.parse(periodXML.getElementsByTagName(\"fixingDate\").item(0).getTextContent());\r\n\t\t\t}\r\n\r\n\t\t\tperiods.add(new Period(fixingDate, paymentDate, startDate, endDate));\r\n\r\n\t\t\tdouble notional\t\t= Double.parseDouble(periodXML.getElementsByTagName(\"nominal\").item(0).getTextContent());\r\n\t\t\tnotionalsList.add(new Double(notional));\r\n\r\n\t\t\tif(isFixed) {\r\n\t\t\t\tdouble fixedRate\t= Double.parseDouble(periodXML.getElementsByTagName(\"fixedRate\").item(0).getTextContent());\r\n\t\t\t\trates.add(new Double(fixedRate));\r\n\t\t\t} else {\r\n\t\t\t\trates.add(new Double(0));\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\tScheduleDescriptor schedule = new ScheduleDescriptor(periods, daycountConvention);\r\n\t\tdouble[] notionals\t= notionalsList.stream().mapToDouble(Double::doubleValue).toArray();\r\n\t\tdouble[] spreads\t= rates.stream().mapToDouble(Double::doubleValue).toArray();\r\n\r\n\t\treturn new InterestRateSwapLegProductDescriptor(forwardCurveName, discountCurveName, schedule, notionals, spreads, false);\r\n\t}", "public ProjectCalendar addDefaultDerivedCalendar()\n {\n ProjectCalendar calendar = add();\n\n calendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n\n return (calendar);\n }", "public boolean accept(String str) {\r\n int k = str.length() - 1;\r\n char c = str.charAt(k);\r\n while (k >= 0 && !Character.isDigit(c)) {\r\n k--;\r\n if (k >= 0) {\r\n c = str.charAt(k);\r\n }\r\n }\r\n if (k < 0) {\r\n return false;\r\n }\r\n int j = k;\r\n c = str.charAt(j);\r\n while (j >= 0 && Character.isDigit(c)) {\r\n j--;\r\n if (j >= 0) {\r\n c = str.charAt(j);\r\n }\r\n }\r\n j++;\r\n k++;\r\n String theNumber = str.substring(j, k);\r\n int number = Integer.parseInt(theNumber);\r\n for (Pair<Integer,Integer> p : ranges) {\r\n int low = p.first().intValue();\r\n int high = p.second().intValue();\r\n if (number >= low && number <= high) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }" ]
Use this API to update aaaparameter.
[ "public static base_response update(nitro_service client, aaaparameter resource) throws Exception {\n\t\taaaparameter updateresource = new aaaparameter();\n\t\tupdateresource.enablestaticpagecaching = resource.enablestaticpagecaching;\n\t\tupdateresource.enableenhancedauthfeedback = resource.enableenhancedauthfeedback;\n\t\tupdateresource.defaultauthtype = resource.defaultauthtype;\n\t\tupdateresource.maxaaausers = resource.maxaaausers;\n\t\tupdateresource.maxloginattempts = resource.maxloginattempts;\n\t\tupdateresource.failedlogintimeout = resource.failedlogintimeout;\n\t\tupdateresource.aaadnatip = resource.aaadnatip;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
[ "protected void validateResultsDirectories() {\n for (String result : results) {\n if (Files.notExists(Paths.get(result))) {\n throw new AllureCommandException(String.format(\"Report directory <%s> not found.\", result));\n }\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 String addDependency(FunctionalTaskItem dependencyTaskItem) {\n IndexableTaskItem dependency = IndexableTaskItem.create(dependencyTaskItem);\n this.addDependency(dependency);\n return dependency.key();\n }", "public boolean forall(PixelPredicate predicate) {\n return Arrays.stream(points()).allMatch(p -> predicate.test(p.x, p.y, pixel(p)));\n }", "public ArrayList<Double> segmentCost(ProjectCalendar projectCalendar, List<TimephasedCost> cost, TimescaleUnits rangeUnits, ArrayList<DateRange> dateList)\n {\n ArrayList<Double> result = new ArrayList<Double>(dateList.size());\n int lastStartIndex = 0;\n\n //\n // Iterate through the list of dates range we are interested in.\n // Each date range in this list corresponds to a column\n // shown on the \"timescale\" view by MS Project\n //\n for (DateRange range : dateList)\n {\n //\n // If the current date range does not intersect with any of the\n // assignment date ranges in the list, then we show a zero\n // duration for this date range.\n //\n int startIndex = lastStartIndex == -1 ? -1 : getStartIndex(range, cost, lastStartIndex);\n if (startIndex == -1)\n {\n result.add(NumberHelper.DOUBLE_ZERO);\n }\n else\n {\n //\n // We have found an assignment which intersects with the current\n // date range, call the method below to determine how\n // much time from this resource assignment can be allocated\n // to the current date range.\n //\n result.add(getRangeCost(projectCalendar, rangeUnits, range, cost, startIndex));\n lastStartIndex = startIndex;\n }\n }\n\n return result;\n }", "public void unlink(Object obj, ObjectReferenceDescriptor ord, boolean insert)\r\n {\r\n linkOrUnlink(false, obj, ord, insert);\r\n }", "public static String readTextFile(InputStream inputStream) {\n InputStreamReader streamReader = new InputStreamReader(inputStream);\n return readTextFile(streamReader);\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 QueryBuilder<T, ID> orderBy(String columnName, boolean ascending) {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new IllegalArgumentException(\"Can't orderBy foreign collection field: \" + columnName);\n\t\t}\n\t\taddOrderBy(new OrderBy(columnName, ascending));\n\t\treturn this;\n\t}" ]
Use this API to fetch clusternodegroup_nslimitidentifier_binding resources of given name .
[ "public static clusternodegroup_nslimitidentifier_binding[] get(nitro_service service, String name) throws Exception{\n\t\tclusternodegroup_nslimitidentifier_binding obj = new clusternodegroup_nslimitidentifier_binding();\n\t\tobj.set_name(name);\n\t\tclusternodegroup_nslimitidentifier_binding response[] = (clusternodegroup_nslimitidentifier_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "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 void applyHyperLinkToElement(DynamicJasperDesign design, DJHyperLink djlink, JRDesignChart chart, String name) {\n\t\tJRDesignExpression hlpe = ExpressionUtils.createAndRegisterExpression(design, name, djlink.getExpression());\n\t\tchart.setHyperlinkReferenceExpression(hlpe);\n\t\tchart.setHyperlinkType( HyperlinkTypeEnum.REFERENCE ); //FIXME Should this be a parameter in the future?\n\t\t\t\t\n\t\tif (djlink.getTooltip() != null){\t\t\t\n\t\t\tJRDesignExpression tooltipExp = ExpressionUtils.createAndRegisterExpression(design, \"tooltip_\" + name, djlink.getTooltip());\n\t\t\tchart.setHyperlinkTooltipExpression(tooltipExp);\n\t\t}\n\t}", "private static void embedSvgGraphic(\n final SVGElement svgRoot,\n final SVGElement newSvgRoot, final Document newDocument,\n final Dimension targetSize, final Double rotation) {\n final String originalWidth = svgRoot.getAttributeNS(null, \"width\");\n final String originalHeight = svgRoot.getAttributeNS(null, \"height\");\n /*\n * To scale the SVG graphic and to apply the rotation, we distinguish two\n * cases: width and height is set on the original SVG or not.\n *\n * Case 1: Width and height is set\n * If width and height is set, we wrap the original SVG into 2 new SVG elements\n * and a container element.\n *\n * Example:\n * Original SVG:\n * <svg width=\"100\" height=\"100\"></svg>\n *\n * New SVG (scaled to 300x300 and rotated by 90 degree):\n * <svg width=\"300\" height=\"300\">\n * <g transform=\"rotate(90.0 150 150)\">\n * <svg width=\"100%\" height=\"100%\" viewBox=\"0 0 100 100\">\n * <svg width=\"100\" height=\"100\"></svg>\n * </svg>\n * </g>\n * </svg>\n *\n * The requested size is set on the outermost <svg>. Then, the rotation is applied to the\n * <g> container and the scaling is achieved with the viewBox parameter on the 2nd <svg>.\n *\n *\n * Case 2: Width and height is not set\n * In this case the original SVG is wrapped into just one container and one new SVG element.\n * The rotation is set on the container, and the scaling happens automatically.\n *\n * Example:\n * Original SVG:\n * <svg viewBox=\"0 0 61.06 91.83\"></svg>\n *\n * New SVG (scaled to 300x300 and rotated by 90 degree):\n * <svg width=\"300\" height=\"300\">\n * <g transform=\"rotate(90.0 150 150)\">\n * <svg viewBox=\"0 0 61.06 91.83\"></svg>\n * </g>\n * </svg>\n */\n if (!StringUtils.isEmpty(originalWidth) && !StringUtils.isEmpty(originalHeight)) {\n Element wrapperContainer = newDocument.createElementNS(SVG_NS, \"g\");\n wrapperContainer.setAttributeNS(\n null,\n SVGConstants.SVG_TRANSFORM_ATTRIBUTE,\n getRotateTransformation(targetSize, rotation));\n newSvgRoot.appendChild(wrapperContainer);\n\n Element wrapperSvg = newDocument.createElementNS(SVG_NS, \"svg\");\n wrapperSvg.setAttributeNS(null, \"width\", \"100%\");\n wrapperSvg.setAttributeNS(null, \"height\", \"100%\");\n wrapperSvg.setAttributeNS(null, \"viewBox\", \"0 0 \" + originalWidth\n + \" \" + originalHeight);\n wrapperContainer.appendChild(wrapperSvg);\n\n Node svgRootImported = newDocument.importNode(svgRoot, true);\n wrapperSvg.appendChild(svgRootImported);\n } else if (StringUtils.isEmpty(originalWidth) && StringUtils.isEmpty(originalHeight)) {\n Element wrapperContainer = newDocument.createElementNS(SVG_NS, \"g\");\n wrapperContainer.setAttributeNS(\n null,\n SVGConstants.SVG_TRANSFORM_ATTRIBUTE,\n getRotateTransformation(targetSize, rotation));\n newSvgRoot.appendChild(wrapperContainer);\n\n Node svgRootImported = newDocument.importNode(svgRoot, true);\n wrapperContainer.appendChild(svgRootImported);\n } else {\n throw new IllegalArgumentException(\n \"Unsupported or invalid north-arrow SVG graphic: The same unit (px, em, %, ...) must be\" +\n \" \" +\n \"used for `width` and `height`.\");\n }\n }", "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 static String rgb(int r, int g, int b) {\n if (r < -100 || r > 100) {\n throw new IllegalArgumentException(\"Red value must be between -100 and 100, inclusive.\");\n }\n if (g < -100 || g > 100) {\n throw new IllegalArgumentException(\"Green value must be between -100 and 100, inclusive.\");\n }\n if (b < -100 || b > 100) {\n throw new IllegalArgumentException(\"Blue value must be between -100 and 100, inclusive.\");\n }\n return FILTER_RGB + \"(\" + r + \",\" + g + \",\" + b + \")\";\n }", "public void rotateToFront() {\n GVRTransform transform = mSceneRootObject.getTransform();\n transform.setRotation(1, 0, 0, 0);\n transform.rotateByAxisWithPivot(-frontFacingRotation + 180, 0, 1, 0, 0, 0, 0);\n }", "private void setConstraints(Task task, MapRow row)\n {\n ConstraintType constraintType = null;\n Date constraintDate = null;\n Date lateDate = row.getDate(\"CONSTRAINT_LATE_DATE\");\n Date earlyDate = row.getDate(\"CONSTRAINT_EARLY_DATE\");\n\n switch (row.getInteger(\"CONSTRAINT_TYPE\").intValue())\n {\n case 2: // Cannot Reschedule\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = task.getStart();\n break;\n }\n\n case 12: //Finish Between\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = lateDate;\n break;\n }\n\n case 10: // Finish On or After\n {\n constraintType = ConstraintType.FINISH_NO_EARLIER_THAN;\n constraintDate = earlyDate;\n break;\n }\n\n case 11: // Finish On or Before\n {\n constraintType = ConstraintType.FINISH_NO_LATER_THAN;\n constraintDate = lateDate;\n break;\n }\n\n case 13: // Mandatory Start\n case 5: // Start On\n case 9: // Finish On\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = earlyDate;\n break;\n }\n\n case 14: // Mandatory Finish\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = earlyDate;\n break;\n }\n\n case 4: // Start As Late As Possible\n {\n constraintType = ConstraintType.AS_LATE_AS_POSSIBLE;\n break;\n }\n\n case 3: // Start As Soon As Possible\n {\n constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n break;\n }\n\n case 8: // Start Between\n {\n constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n constraintDate = earlyDate;\n break;\n }\n\n case 6: // Start On or Before\n {\n constraintType = ConstraintType.START_NO_LATER_THAN;\n constraintDate = earlyDate;\n break;\n }\n\n case 15: // Work Between\n {\n constraintType = ConstraintType.START_NO_EARLIER_THAN;\n constraintDate = earlyDate;\n break;\n }\n }\n task.setConstraintType(constraintType);\n task.setConstraintDate(constraintDate);\n }", "public WebSocketContext reTag(String label) {\n WebSocketConnectionRegistry registry = manager.tagRegistry();\n registry.signOff(connection);\n registry.signIn(label, connection);\n return this;\n }", "public static Drawable decideIcon(ImageHolder imageHolder, Context ctx, int iconColor, boolean tint) {\n if (imageHolder == null) {\n return null;\n } else {\n return imageHolder.decideIcon(ctx, iconColor, tint);\n }\n }" ]
Upcasts a Builder instance to the generated superclass, to allow access to private fields. <p>Reuses an existing upcast instance if one was already declared in this scope. @param code the {@link SourceBuilder} to add the declaration to @param datatype metadata about the user type the builder is being generated for @param builder the Builder instance to upcast @returns a variable holding the upcasted instance
[ "public static Variable upcastToGeneratedBuilder(\n SourceBuilder code, Datatype datatype, String builder) {\n return code.scope().computeIfAbsent(Declaration.UPCAST, () -> {\n Variable base = new Variable(\"base\");\n code.addLine(UPCAST_COMMENT)\n .addLine(\"%s %s = %s;\", datatype.getGeneratedBuilder(), base, builder);\n return base;\n });\n }" ]
[ "public static hanode_routemonitor_binding[] get(nitro_service service, Long id) throws Exception{\n\t\thanode_routemonitor_binding obj = new hanode_routemonitor_binding();\n\t\tobj.set_id(id);\n\t\thanode_routemonitor_binding response[] = (hanode_routemonitor_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static cacheselector[] get(nitro_service service, String selectorname[]) throws Exception{\n\t\tif (selectorname !=null && selectorname.length>0) {\n\t\t\tcacheselector response[] = new cacheselector[selectorname.length];\n\t\t\tcacheselector obj[] = new cacheselector[selectorname.length];\n\t\t\tfor (int i=0;i<selectorname.length;i++) {\n\t\t\t\tobj[i] = new cacheselector();\n\t\t\t\tobj[i].set_selectorname(selectorname[i]);\n\t\t\t\tresponse[i] = (cacheselector) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\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 }", "private void validationRelations(Task task)\n {\n List<Relation> predecessors = task.getPredecessors();\n if (!predecessors.isEmpty())\n {\n ArrayList<Relation> invalid = new ArrayList<Relation>();\n for (Relation relation : predecessors)\n {\n Task sourceTask = relation.getSourceTask();\n Task targetTask = relation.getTargetTask();\n\n String sourceOutlineNumber = sourceTask.getOutlineNumber();\n String targetOutlineNumber = targetTask.getOutlineNumber();\n\n if (sourceOutlineNumber != null && targetOutlineNumber != null && sourceOutlineNumber.startsWith(targetOutlineNumber + '.'))\n {\n invalid.add(relation);\n }\n }\n\n for (Relation relation : invalid)\n {\n relation.getSourceTask().removePredecessor(relation.getTargetTask(), relation.getType(), relation.getLag());\n }\n }\n }", "@Deprecated\n\tpublic static ScheduleInterface createScheduleFromConventions(\n\t\t\tLocalDate referenceDate,\n\t\t\tLocalDate startDate,\n\t\t\tString frequency,\n\t\t\tdouble maturity,\n\t\t\tString daycountConvention,\n\t\t\tString shortPeriodConvention\n\t\t\t)\n\t{\n\t\treturn createScheduleFromConventions(\n\t\t\t\treferenceDate,\n\t\t\t\tstartDate,\n\t\t\t\tfrequency,\n\t\t\t\tmaturity,\n\t\t\t\tdaycountConvention,\n\t\t\t\tshortPeriodConvention,\n\t\t\t\t\"UNADJUSTED\",\n\t\t\t\tnew BusinessdayCalendarAny(),\n\t\t\t\t0, 0);\n\t}", "public ConditionalExpectationEstimator getConditionalExpectationEstimator(double exerciseTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException {\r\n\t\tRandomVariable[] regressionBasisFunctions = regressionBasisFunctionProvider.getBasisFunctions(exerciseTime, model);\r\n\t\treturn conditionalExpectationRegressionFactory.getConditionalExpectationEstimator(regressionBasisFunctions, regressionBasisFunctions);\r\n\t}", "private void reply(final String response, final boolean error,\n final String errorMessage, final String stackTrace,\n final String statusCode, final int statusCodeInt) {\n\n \n if (!sentReply) {\n \n //must update sentReply first to avoid duplicated msg.\n sentReply = true;\n // Close the connection. Make sure the close operation ends because\n // all I/O operations are asynchronous in Netty.\n if(channel!=null && channel.isOpen())\n channel.close().awaitUninterruptibly();\n final ResponseOnSingeRequest res = new ResponseOnSingeRequest(\n response, error, errorMessage, stackTrace, statusCode,\n statusCodeInt, PcDateUtils.getNowDateTimeStrStandard(), null);\n if (!getContext().system().deadLetters().equals(sender)) {\n sender.tell(res, getSelf());\n }\n if (getContext() != null) {\n getContext().stop(getSelf());\n }\n }\n\n }", "int read(InputStream is, int contentLength) {\n if (is != null) {\n try {\n int capacity = (contentLength > 0) ? (contentLength + 4096) : 16384;\n ByteArrayOutputStream buffer = new ByteArrayOutputStream(capacity);\n int nRead;\n byte[] data = new byte[16384];\n while ((nRead = is.read(data, 0, data.length)) != -1) {\n buffer.write(data, 0, nRead);\n }\n buffer.flush();\n\n read(buffer.toByteArray());\n } catch (IOException e) {\n Logger.d(TAG, \"Error reading data from stream\", e);\n }\n } else {\n status = STATUS_OPEN_ERROR;\n }\n\n try {\n if (is != null) {\n is.close();\n }\n } catch (IOException e) {\n Logger.d(TAG, \"Error closing stream\", e);\n }\n\n return status;\n }", "public Duration getWork(Date date, TimeUnit format)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, null);\n long time = getTotalTime(ranges);\n return convertFormat(time, format);\n }" ]
returns true if the primary key fields are valid for delete, else false. PK fields are valid if each of them contains a valid non-null value @param cld the ClassDescriptor @param obj the object @return boolean
[ "public boolean assertValidPkForDelete(ClassDescriptor cld, Object obj)\r\n {\r\n if(!ProxyHelper.isProxy(obj))\r\n {\r\n FieldDescriptor fieldDescriptors[] = cld.getPkFields();\r\n int fieldDescriptorSize = fieldDescriptors.length;\r\n for(int i = 0; i < fieldDescriptorSize; i++)\r\n {\r\n FieldDescriptor fd = fieldDescriptors[i];\r\n Object pkValue = fd.getPersistentField().get(obj);\r\n if (representsNull(fd, pkValue))\r\n {\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n }" ]
[ "private void processKeyValue(Map<ConfigurationKey, Object> properties, ConfigurationKey key, Object value) {\n if (value instanceof String) {\n value = key.convertValue((String) value);\n }\n if (key.isValidValue(value)) {\n Object previous = properties.put(key, value);\n if (previous != null && !previous.equals(value)) {\n throw ConfigurationLogger.LOG.configurationKeyHasDifferentValues(key.get(), previous, value);\n }\n } else {\n throw ConfigurationLogger.LOG.invalidConfigurationPropertyValue(value, key.get());\n }\n }", "private void decreaseIndent() throws IOException\n {\n if (m_pretty)\n {\n m_writer.write('\\n');\n m_indent = m_indent.substring(0, m_indent.length() - INDENT.length());\n m_writer.write(m_indent);\n }\n m_firstNameValuePair.pop();\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<CopticDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<CopticDate>) super.localDateTime(temporal);\n }", "public void characters(char ch[], int start, int length)\r\n {\r\n if (m_CurrentString == null)\r\n m_CurrentString = new String(ch, start, length);\r\n else\r\n m_CurrentString += new String(ch, start, length);\r\n }", "public static String getEffortLevelDescription(Verbosity verbosity, int points)\n {\n EffortLevel level = EffortLevel.forPoints(points);\n\n switch (verbosity)\n {\n case ID:\n return level.name();\n case VERBOSE:\n return level.getVerboseDescription();\n case SHORT:\n default:\n return level.getShortDescription();\n }\n }", "public static void columnMaxAbs( DMatrixSparseCSC A , double []values ) {\n if( values.length < A.numCols )\n throw new IllegalArgumentException(\"Array is too small. \"+values.length+\" < \"+A.numCols);\n\n for (int i = 0; i < A.numCols; i++) {\n int idx0 = A.col_idx[i];\n int idx1 = A.col_idx[i+1];\n\n double maxabs = 0;\n for (int j = idx0; j < idx1; j++) {\n double v = Math.abs(A.nz_values[j]);\n if( v > maxabs )\n maxabs = v;\n }\n values[i] = maxabs;\n }\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 }", "@Deprecated\n public synchronized FailureDetectorConfig setNodes(Collection<Node> nodes) {\n Utils.notNull(nodes);\n this.nodes = new HashSet<Node>(nodes);\n return this;\n }", "static void writePatch(final Patch rollbackPatch, final File file) throws IOException {\n final File parent = file.getParentFile();\n if (!parent.isDirectory()) {\n if (!parent.mkdirs() && !parent.exists()) {\n throw PatchLogger.ROOT_LOGGER.cannotCreateDirectory(file.getAbsolutePath());\n }\n }\n try {\n try (final OutputStream os = new FileOutputStream(file)){\n PatchXml.marshal(os, rollbackPatch);\n }\n } catch (XMLStreamException e) {\n throw new IOException(e);\n }\n }" ]
Utility function that checks if store names are valid on a node. @param adminClient An instance of AdminClient points to given cluster @param nodeId Node id to fetch stores from @param storeNames Store names to check
[ "public static void validateUserStoreNamesOnNode(AdminClient adminClient,\n Integer nodeId,\n List<String> storeNames) {\n List<StoreDefinition> storeDefList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId)\n .getValue();\n Map<String, Boolean> existingStoreNames = new HashMap<String, Boolean>();\n for(StoreDefinition storeDef: storeDefList) {\n existingStoreNames.put(storeDef.getName(), true);\n }\n for(String storeName: storeNames) {\n if(!Boolean.TRUE.equals(existingStoreNames.get(storeName))) {\n Utils.croak(\"Store \" + storeName + \" does not exist!\");\n }\n }\n }" ]
[ "protected Connection openConnection() throws IOException {\n // Perhaps this can just be done once?\n CallbackHandler callbackHandler = null;\n SSLContext sslContext = null;\n if (realm != null) {\n sslContext = realm.getSSLContext();\n CallbackHandlerFactory handlerFactory = realm.getSecretCallbackHandlerFactory();\n if (handlerFactory != null) {\n String username = this.username != null ? this.username : localHostName;\n callbackHandler = handlerFactory.getCallbackHandler(username);\n }\n }\n final ProtocolConnectionConfiguration config = ProtocolConnectionConfiguration.copy(configuration);\n config.setCallbackHandler(callbackHandler);\n config.setSslContext(sslContext);\n config.setUri(uri);\n\n AuthenticationContext authenticationContext = this.authenticationContext != null ? this.authenticationContext : AuthenticationContext.captureCurrent();\n\n // Connect\n try {\n return authenticationContext.run((PrivilegedExceptionAction<Connection>) () -> ProtocolConnectionUtils.connectSync(config));\n } catch (PrivilegedActionException e) {\n if (e.getCause() instanceof IOException) {\n throw (IOException) e.getCause();\n }\n throw new IOException(e);\n }\n }", "private void logMigration(DbMigration migration, boolean wasSuccessful) {\n BoundStatement boundStatement = logMigrationStatement.bind(wasSuccessful, migration.getVersion(),\n migration.getScriptName(), migration.getMigrationScript(), new Date());\n session.execute(boundStatement);\n }", "public void createTaskFieldMap(Props props)\n {\n byte[] fieldMapData = null;\n for (Integer key : TASK_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData == null)\n {\n populateDefaultData(getDefaultTaskData());\n }\n else\n {\n createFieldMap(fieldMapData);\n }\n }", "public void writeLock(EntityKey key, int timeout) {\n\t\tReadWriteLock lock = getLock( key );\n\t\tLock writeLock = lock.writeLock();\n\t\tacquireLock( key, timeout, writeLock );\n\t}", "private List<File> getConfigFiles() {\n\n String[] filenames = {\n \"opencms-modules.xml\",\n \"opencms-system.xml\",\n \"opencms-vfs.xml\",\n \"opencms-importexport.xml\",\n \"opencms-sites.xml\",\n \"opencms-variables.xml\",\n \"opencms-scheduler.xml\",\n \"opencms-workplace.xml\",\n \"opencms-search.xml\"};\n List<File> result = new ArrayList<>();\n for (String fn : filenames) {\n File file = new File(m_configDir, fn);\n if (file.exists()) {\n result.add(file);\n }\n }\n return result;\n }", "public 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 }", "private static int determineBatchSize(boolean canGridDialectDoMultiget, int classBatchSize, int configuredDefaultBatchSize) {\n\t\t// if the dialect does not support it, don't batch so that we can avoid skewing the ORM fetch statistics\n\t\tif ( !canGridDialectDoMultiget ) {\n\t\t\treturn -1;\n\t\t}\n\t\telse if ( classBatchSize != -1 ) {\n\t\t\treturn classBatchSize;\n\t\t}\n\t\telse if ( configuredDefaultBatchSize != -1 ) {\n\t\t\treturn configuredDefaultBatchSize;\n\t\t}\n\t\telse {\n\t\t\treturn DEFAULT_MULTIGET_BATCH_SIZE;\n\t\t}\n\t}", "public String putDocument(Document document) {\n\t\tString key = UUID.randomUUID().toString();\n\t\tdocumentMap.put(key, document);\n\t\treturn key;\n\t}", "public void resume() {\n this.paused = false;\n ServerActivityCallback listener = listenerUpdater.get(this);\n if (listener != null) {\n listenerUpdater.compareAndSet(this, listener, null);\n }\n }" ]
Notifies that multiple footer items are changed. @param positionStart the position. @param itemCount the item count.
[ "public final void notifyFooterItemRangeChanged(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemRangeChanged(positionStart + headerItemCount + contentItemCount, itemCount);\n }" ]
[ "@PostConstruct\n public void checkUniqueSchemes() {\n Multimap<String, ConfigFileLoaderPlugin> schemeToPluginMap = HashMultimap.create();\n\n for (ConfigFileLoaderPlugin plugin: getLoaderPlugins()) {\n schemeToPluginMap.put(plugin.getUriScheme(), plugin);\n }\n\n StringBuilder violations = new StringBuilder();\n for (String scheme: schemeToPluginMap.keySet()) {\n final Collection<ConfigFileLoaderPlugin> plugins = schemeToPluginMap.get(scheme);\n if (plugins.size() > 1) {\n violations.append(\"\\n\\n* \").append(\"There are has multiple \")\n .append(ConfigFileLoaderPlugin.class.getSimpleName())\n .append(\" plugins that support the scheme: '\").append(scheme).append('\\'')\n .append(\":\\n\\t\").append(plugins);\n }\n }\n\n if (violations.length() > 0) {\n throw new IllegalStateException(violations.toString());\n }\n }", "static void createMessage(String textMessage, JobInstance jobInstance, DbConn cnx)\n {\n cnx.runUpdate(\"message_insert\", jobInstance.getId(), textMessage);\n }", "public static base_response update(nitro_service client, tmtrafficaction resource) throws Exception {\n\t\ttmtrafficaction updateresource = new tmtrafficaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.apptimeout = resource.apptimeout;\n\t\tupdateresource.sso = resource.sso;\n\t\tupdateresource.formssoaction = resource.formssoaction;\n\t\tupdateresource.persistentcookie = resource.persistentcookie;\n\t\tupdateresource.initiatelogout = resource.initiatelogout;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\tupdateresource.samlssoprofile = resource.samlssoprofile;\n\t\treturn updateresource.update_resource(client);\n\t}", "public void runOnInvariantViolationPlugins(Invariant invariant,\n\t\t\tCrawlerContext context) {\n\t\tLOGGER.debug(\"Running OnInvariantViolationPlugins...\");\n\t\tcounters.get(OnInvariantViolationPlugin.class).inc();\n\t\tfor (Plugin plugin : plugins.get(OnInvariantViolationPlugin.class)) {\n\t\t\tif (plugin instanceof OnInvariantViolationPlugin) {\n\t\t\t\ttry {\n\t\t\t\t\tLOGGER.debug(\"Calling plugin {}\", plugin);\n\t\t\t\t\t((OnInvariantViolationPlugin) plugin).onInvariantViolation(\n\t\t\t\t\t\t\tinvariant, context);\n\t\t\t\t} catch (RuntimeException e) {\n\t\t\t\t\treportFailingPlugin(plugin, e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "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 static IPAddressSeqRange[] join(IPAddressSeqRange... ranges) {\n\t\tint joinedCount = 0;\n\t\tArrays.sort(ranges, Address.ADDRESS_LOW_VALUE_COMPARATOR);\n\t\tfor(int i = 0; i < ranges.length; i++) {\n\t\t\tIPAddressSeqRange range = ranges[i];\n\t\t\tif(range == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor(int j = i + 1; j < ranges.length; j++) {\n\t\t\t\tIPAddressSeqRange range2 = ranges[j];\n\t\t\t\tif(range2 == null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tIPAddress upper = range.getUpper();\n\t\t\t\tIPAddress lower = range2.getLower();\n\t\t\t\tif(compareLowValues(upper, lower) >= 0\n\t\t\t\t\t\t|| upper.increment(1).equals(lower)) {\n\t\t\t\t\t//join them\n\t\t\t\t\tranges[i] = range = range.create(range.getLower(), range2.getUpper());\n\t\t\t\t\tranges[j] = null;\n\t\t\t\t\tjoinedCount++;\n\t\t\t\t} else break;\n\t\t\t}\n\t\t}\n\t\tif(joinedCount == 0) {\n\t\t\treturn ranges;\n\t\t}\n\t\tIPAddressSeqRange joined[] = new IPAddressSeqRange[ranges.length - joinedCount];\n\t\tfor(int i = 0, j = 0; i < ranges.length; i++) {\n\t\t\tIPAddressSeqRange range = ranges[i];\n\t\t\tif(range == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tjoined[j++] = range;\n\t\t\tif(j >= joined.length) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn joined;\n\t}", "public static aaapreauthenticationpolicy_aaaglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\taaapreauthenticationpolicy_aaaglobal_binding obj = new aaapreauthenticationpolicy_aaaglobal_binding();\n\t\tobj.set_name(name);\n\t\taaapreauthenticationpolicy_aaaglobal_binding response[] = (aaapreauthenticationpolicy_aaaglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static Artifact getIdlArtifact(Artifact artifact, ArtifactFactory artifactFactory,\n ArtifactResolver artifactResolver,\n ArtifactRepository localRepository,\n List<ArtifactRepository> remoteRepos,\n String classifier)\n throws MojoExecutionException {\n Artifact idlArtifact = artifactFactory.createArtifactWithClassifier(\n artifact.getGroupId(),\n artifact.getArtifactId(),\n artifact.getVersion(),\n \"jar\",\n classifier);\n try {\n artifactResolver.resolve(idlArtifact, remoteRepos, localRepository);\n return idlArtifact;\n } catch (final ArtifactResolutionException e) {\n throw new MojoExecutionException(\n \"Failed to resolve one or more idl artifacts:\\n\\n\" + e.getMessage(), e);\n } catch (final ArtifactNotFoundException e) {\n throw new MojoExecutionException(\n \"Failed to resolve one or more idl artifacts:\\n\\n\" + e.getMessage(), e);\n }\n }", "public ProjectCalendar getEffectiveCalendar()\n {\n ProjectCalendar result = getCalendar();\n if (result == null)\n {\n result = getParentFile().getDefaultCalendar();\n }\n return result;\n }" ]
Get the pickers date.
[ "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 CmsResource buildResource() {\n\n return new CmsResource(\n m_structureId,\n m_resourceId,\n m_rootPath,\n m_type,\n m_flags,\n m_projectLastModified,\n m_state,\n m_dateCreated,\n m_userCreated,\n m_dateLastModified,\n m_userLastModified,\n m_dateReleased,\n m_dateExpired,\n m_length,\n m_flags,\n m_dateContent,\n m_version);\n }", "private void recoverNamespace(final NamespaceSynchronizationConfig nsConfig) {\n final MongoCollection<BsonDocument> undoCollection =\n getUndoCollection(nsConfig.getNamespace());\n final MongoCollection<BsonDocument> localCollection =\n getLocalCollection(nsConfig.getNamespace());\n final List<BsonDocument> undoDocs = undoCollection.find().into(new ArrayList<>());\n final Set<BsonValue> recoveredIds = new HashSet<>();\n\n\n // Replace local docs with undo docs. Presence of an undo doc implies we had a system failure\n // during a write. This covers updates and deletes.\n for (final BsonDocument undoDoc : undoDocs) {\n final BsonValue documentId = BsonUtils.getDocumentId(undoDoc);\n final BsonDocument filter = getDocumentIdFilter(documentId);\n localCollection.findOneAndReplace(\n filter, undoDoc, new FindOneAndReplaceOptions().upsert(true));\n recoveredIds.add(documentId);\n }\n\n // If we recovered a document, but its pending writes are set to do something else, then the\n // failure occurred after the pending writes were set, but before the undo document was\n // deleted. In this case, we should restore the document to the state that the pending\n // write indicates. There is a possibility that the pending write is from before the failed\n // operation, but in that case, the findOneAndReplace or delete is a no-op since restoring\n // the document to the state of the change event would be the same as recovering the undo\n // document.\n for (final CoreDocumentSynchronizationConfig docConfig : nsConfig.getSynchronizedDocuments()) {\n final BsonValue documentId = docConfig.getDocumentId();\n final BsonDocument filter = getDocumentIdFilter(documentId);\n\n if (recoveredIds.contains(docConfig.getDocumentId())) {\n final ChangeEvent<BsonDocument> pendingWrite = docConfig.getLastUncommittedChangeEvent();\n if (pendingWrite != null) {\n switch (pendingWrite.getOperationType()) {\n case INSERT:\n case UPDATE:\n case REPLACE:\n localCollection.findOneAndReplace(\n filter,\n pendingWrite.getFullDocument(),\n new FindOneAndReplaceOptions().upsert(true)\n );\n break;\n case DELETE:\n localCollection.deleteOne(filter);\n break;\n default:\n // There should never be pending writes with an unknown event type, but if someone\n // is messing with the config collection we want to stop the synchronizer to prevent\n // further data corruption.\n throw new IllegalStateException(\n \"there should not be a pending write with an unknown event type\"\n );\n }\n }\n }\n }\n\n // Delete all of our undo documents. If we've reached this point, we've recovered the local\n // collection to the state we want with respect to all of our undo documents. If we fail before\n // these deletes or while carrying out the deletes, but after recovering the documents to\n // their desired state, that's okay because the next recovery pass will be effectively a no-op\n // up to this point.\n for (final BsonValue recoveredId : recoveredIds) {\n undoCollection.deleteOne(getDocumentIdFilter(recoveredId));\n }\n\n // Find local documents for which there are no document configs and delete them. This covers\n // inserts, upserts, and desync deletes. This will occur on any recovery pass regardless of\n // the documents in the undo collection, so it's fine that we do this after deleting the undo\n // documents.\n localCollection.deleteMany(new BsonDocument(\n \"_id\",\n new BsonDocument(\n \"$nin\",\n new BsonArray(new ArrayList<>(\n this.syncConfig.getSynchronizedDocumentIds(nsConfig.getNamespace()))))));\n }", "private static boolean matches(Type from, Type to, Map<String, Type> typeMap) {\n\t\tif (to.equals(from))\n\t\t\treturn true;\n\n\t\tif (from instanceof TypeVariable) {\n\t\t\treturn to.equals(typeMap.get(((TypeVariable<?>) from).getName()));\n\t\t}\n\n\t\treturn false;\n\t}", "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 void process(SearchDistributor distributor) {\r\n List<PossibleState> bootStrap;\r\n try {\r\n bootStrap = bfs(bootStrapMin);\r\n } catch (ModelException e) {\r\n bootStrap = new LinkedList<>();\r\n }\n\r\n List<Frontier> frontiers = new LinkedList<>();\r\n for (PossibleState p : bootStrap) {\r\n SCXMLFrontier dge = new SCXMLFrontier(p, model, tagExtensionList);\r\n frontiers.add(dge);\r\n }\n\r\n distributor.distribute(frontiers);\r\n }", "static void doDifference(\n Map<String, String> left,\n Map<String, String> right,\n Map<String, String> onlyOnLeft,\n Map<String, String> onlyOnRight,\n Map<String, String> updated\n ) {\n onlyOnRight.clear();\n onlyOnRight.putAll(right);\n for (Map.Entry<String, String> entry : left.entrySet()) {\n String leftKey = entry.getKey();\n String leftValue = entry.getValue();\n if (right.containsKey(leftKey)) {\n String rightValue = onlyOnRight.remove(leftKey);\n if (!leftValue.equals(rightValue)) {\n updated.put(leftKey, leftValue);\n }\n } else {\n onlyOnLeft.put(leftKey, leftValue);\n }\n }\n }", "static void sendFailedResponse(final ManagementRequestContext<RegistrationContext> context, final byte errorCode, final String message) throws IOException {\n final ManagementResponseHeader header = ManagementResponseHeader.create(context.getRequestHeader());\n final FlushableDataOutput output = context.writeMessage(header);\n try {\n // This is an error\n output.writeByte(DomainControllerProtocol.PARAM_ERROR);\n // send error code\n output.writeByte(errorCode);\n // error message\n if (message == null) {\n output.writeUTF(\"unknown error\");\n } else {\n output.writeUTF(message);\n }\n // response end\n output.writeByte(ManagementProtocol.RESPONSE_END);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }", "public static base_response unset(nitro_service client, inatparam resource, String[] args) throws Exception{\n\t\tinatparam unsetresource = new inatparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public boolean getHidden() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_HIDDEN);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element personElement = response.getPayload();\r\n return personElement.getAttribute(\"hidden\").equals(\"1\") ? true : false;\r\n }" ]
Operations to do after all subthreads finished their work on index @param backend
[ "private void afterBatch(BatchBackend backend) {\n\t\tIndexedTypeSet targetedTypes = searchFactoryImplementor.getIndexedTypesPolymorphic( rootIndexedTypes );\n\t\tif ( this.optimizeAtEnd ) {\n\t\t\tbackend.optimize( targetedTypes );\n\t\t}\n\t\tbackend.flush( targetedTypes );\n\t}" ]
[ "@Nonnull\n public BiMap<String, String> getInputMapper() {\n final BiMap<String, String> inputMapper = this.processor.getInputMapperBiMap();\n if (inputMapper == null) {\n return HashBiMap.create();\n }\n return inputMapper;\n }", "private void updateWorkTimeUnit(FastTrackColumn column)\n {\n if (m_workTimeUnit == null && isWorkColumn(column))\n {\n int value = ((DurationColumn) column).getTimeUnitValue();\n if (value != 1)\n {\n m_workTimeUnit = FastTrackUtility.getTimeUnit(value);\n }\n }\n }", "public static boolean isLong(CharSequence self) {\n try {\n Long.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "public void flipBit(int index)\n {\n assertValidIndex(index);\n int word = index / WORD_LENGTH;\n int offset = index % WORD_LENGTH;\n data[word] ^= (1 << offset);\n }", "public SimpleConfiguration getClientConfiguration() {\n SimpleConfiguration clientConfig = new SimpleConfiguration();\n Iterator<String> iter = getKeys();\n while (iter.hasNext()) {\n String key = iter.next();\n if (key.startsWith(CONNECTION_PREFIX) || key.startsWith(ACCUMULO_PREFIX)\n || key.startsWith(CLIENT_PREFIX)) {\n clientConfig.setProperty(key, getRawString(key));\n }\n }\n return clientConfig;\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 }", "@SuppressWarnings(\"unchecked\")\n @Nonnull\n public final java.util.Optional<Style> getStyle(final String styleName) {\n final String styleRef = this.styles.get(styleName);\n Optional<Style> style;\n if (styleRef != null) {\n style = (Optional<Style>) this.styleParser\n .loadStyle(getConfiguration(), this.httpRequestFactory, styleRef);\n } else {\n style = Optional.empty();\n }\n return or(style, this.configuration.getStyle(styleName));\n }", "public String lookupUser(String url) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LOOKUP_USER);\r\n\r\n parameters.put(\"url\", url);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element payload = response.getPayload();\r\n Element groupnameElement = (Element) payload.getElementsByTagName(\"username\").item(0);\r\n return ((Text) groupnameElement.getFirstChild()).getData();\r\n }", "public static void munlock(Pointer addr, long len) {\n\n if(Delegate.munlock(addr, new NativeLong(len)) != 0) {\n if(logger.isDebugEnabled())\n logger.debug(\"munlocking failed with errno:\" + errno.strerror());\n } else {\n if(logger.isDebugEnabled())\n logger.debug(\"munlocking region\");\n }\n }" ]
Saves a screenshot of every new state.
[ "@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 }" ]
[ "public boolean computeDirect( DMatrixRMaj A ) {\n\n initPower(A);\n\n boolean converged = false;\n\n for( int i = 0; i < maxIterations && !converged; i++ ) {\n// q0.print();\n \n CommonOps_DDRM.mult(A,q0,q1);\n double s = NormOps_DDRM.normPInf(q1);\n CommonOps_DDRM.divide(q1,s,q2);\n\n converged = checkConverged(A);\n }\n\n return converged;\n }", "private String swapStore(String storeName, String directory) throws VoldemortException {\n\n ReadOnlyStorageEngine store = getReadOnlyStorageEngine(metadataStore,\n storeRepository,\n storeName);\n\n if(!Utils.isReadableDir(directory))\n throw new VoldemortException(\"Store directory '\" + directory\n + \"' is not a readable directory.\");\n\n String currentDirPath = store.getCurrentDirPath();\n\n logger.info(\"Swapping RO store '\" + storeName + \"' to version directory '\" + directory\n + \"'\");\n store.swapFiles(directory);\n logger.info(\"Swapping swapped RO store '\" + storeName + \"' to version directory '\"\n + directory + \"'\");\n\n return currentDirPath;\n }", "public final Processor.ExecutionContext print(\n final String jobId, final PJsonObject specJson, final OutputStream out)\n throws Exception {\n final OutputFormat format = getOutputFormat(specJson);\n final File taskDirectory = this.workingDirectories.getTaskDirectory();\n\n try {\n return format.print(jobId, specJson, getConfiguration(), this.configFile.getParentFile(),\n taskDirectory, out);\n } finally {\n this.workingDirectories.removeDirectory(taskDirectory);\n }\n }", "public void setEnable(boolean flag)\n {\n if (mEnabled == flag)\n {\n return;\n }\n mEnabled = flag;\n if (flag)\n {\n mContext.registerDrawFrameListener(this);\n mContext.getApplication().getEventReceiver().addListener(this);\n mAudioEngine.resume();\n }\n else\n {\n mContext.unregisterDrawFrameListener(this);\n mContext.getApplication().getEventReceiver().removeListener(this);\n mAudioEngine.pause();\n }\n }", "public static base_response update(nitro_service client, lbsipparameters resource) throws Exception {\n\t\tlbsipparameters updateresource = new lbsipparameters();\n\t\tupdateresource.rnatsrcport = resource.rnatsrcport;\n\t\tupdateresource.rnatdstport = resource.rnatdstport;\n\t\tupdateresource.retrydur = resource.retrydur;\n\t\tupdateresource.addrportvip = resource.addrportvip;\n\t\tupdateresource.sip503ratethreshold = resource.sip503ratethreshold;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static final Bytes of(String s) {\n Objects.requireNonNull(s);\n if (s.isEmpty()) {\n return EMPTY;\n }\n byte[] data = s.getBytes(StandardCharsets.UTF_8);\n return new Bytes(data, s);\n }", "public ClosableIterator<Tuple> callStoredProcedure(EmbeddedCacheManager embeddedCacheManager, String storedProcedureName, ProcedureQueryParameters queryParameters, ClassLoaderService classLoaderService ) {\n\t\tvalidate( queryParameters );\n\t\tCache<String, String> cache = embeddedCacheManager.getCache( STORED_PROCEDURES_CACHE_NAME, true );\n\t\tString className = cache.getOrDefault( storedProcedureName, storedProcedureName );\n\t\tCallable<?> callable = instantiate( storedProcedureName, className, classLoaderService );\n\t\tsetParams( storedProcedureName, queryParameters, callable );\n\t\tObject res = execute( storedProcedureName, embeddedCacheManager, callable );\n\t\treturn extractResultSet( storedProcedureName, res );\n\t}", "public final Jar setAttribute(String name, String value) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Manifest cannot be modified after entries are added.\");\n getManifest().getMainAttributes().putValue(name, value);\n return this;\n }", "private String formatAccrueType(AccrueType type)\n {\n return (type == null ? null : LocaleData.getStringArray(m_locale, LocaleData.ACCRUE_TYPES)[type.getValue() - 1]);\n }" ]
Handles a failed SendData request. This can either be because of the stick actively reporting it or because of a time-out of the transaction in the send thread. @param originalMessage the original message that was sent
[ "private void handleFailedSendDataRequest(SerialMessage originalMessage) {\n\t\tZWaveNode node = this.getNode(originalMessage.getMessageNode());\n\t\t\n\t\tif (node.getNodeStage() == NodeStage.NODEBUILDINFO_DEAD)\n\t\t\treturn;\n\t\t\n\t\tif (!node.isListening() && originalMessage.getPriority() != SerialMessage.SerialMessagePriority.Low) {\n\t\t\tZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass)node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP);\n\t\t\t\n\t\t\tif (wakeUpCommandClass != null) {\n\t\t\t\twakeUpCommandClass.setAwake(false);\n\t\t\t\twakeUpCommandClass.putInWakeUpQueue(originalMessage); //it's a battery operated device, place in wake-up queue.\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else if (!node.isListening() && originalMessage.getPriority() == SerialMessage.SerialMessagePriority.Low)\n\t\t\treturn;\n\t\t\n\t\tnode.incrementResendCount();\n\t\t\n\t\tlogger.error(\"Got an error while sending data to node {}. Resending message.\", node.getNodeId());\n\t\tthis.sendData(originalMessage);\n\t}" ]
[ "private ChildTaskContainer getParentTask(Activity activity)\n {\n //\n // Make a map of activity codes and their values for this activity\n //\n Map<UUID, UUID> map = getActivityCodes(activity);\n\n //\n // Work through the activity codes in sequence\n //\n ChildTaskContainer parent = m_projectFile;\n StringBuilder uniqueIdentifier = new StringBuilder();\n for (UUID activityCode : m_codeSequence)\n {\n UUID activityCodeValue = map.get(activityCode);\n String activityCodeText = m_activityCodeValues.get(activityCodeValue);\n if (activityCodeText != null)\n {\n if (uniqueIdentifier.length() != 0)\n {\n uniqueIdentifier.append('>');\n }\n uniqueIdentifier.append(activityCodeValue.toString());\n UUID uuid = UUID.nameUUIDFromBytes(uniqueIdentifier.toString().getBytes());\n Task newParent = findChildTaskByUUID(parent, uuid);\n if (newParent == null)\n {\n newParent = parent.addTask();\n newParent.setGUID(uuid);\n newParent.setName(activityCodeText);\n }\n parent = newParent;\n }\n }\n return parent;\n }", "public DiscreteInterval minus(DiscreteInterval other) {\n return new DiscreteInterval(this.min - other.max, this.max - other.min);\n }", "public static String writeMultipleClientConfigAvro(Map<String, Properties> mapStoreToProps) {\n // TODO: Use a dedicated json lib. We shouldn't be manually manipulating json...\n String avroConfig = \"\";\n Boolean firstStore = true;\n for(String storeName: mapStoreToProps.keySet()) {\n if(firstStore) {\n firstStore = false;\n } else {\n avroConfig = avroConfig + \",\\n\";\n }\n Properties props = mapStoreToProps.get(storeName);\n avroConfig = avroConfig + \"\\t\\\"\" + storeName + \"\\\": \"\n + writeSingleClientConfigAvro(props);\n\n }\n return \"{\\n\" + avroConfig + \"\\n}\";\n }", "public int getCount(Class target)\r\n {\r\n PersistenceBroker broker = ((HasBroker) odmg.currentTransaction()).getBroker();\r\n int result = broker.getCount(new QueryByCriteria(target));\r\n return result;\r\n }", "public UriComponentsBuilder pathSegment(String... pathSegments) throws IllegalArgumentException {\n\t\tAssert.notNull(pathSegments, \"'segments' must not be null\");\n\t\tthis.pathBuilder.addPathSegments(pathSegments);\n\t\tresetSchemeSpecificPart();\n\t\treturn this;\n\t}", "public GreenMailConfiguration build(Properties properties) {\n GreenMailConfiguration configuration = new GreenMailConfiguration();\n String usersParam = properties.getProperty(GREENMAIL_USERS);\n if (null != usersParam) {\n String[] usersArray = usersParam.split(\",\");\n for (String user : usersArray) {\n extractAndAddUser(configuration, user);\n }\n }\n String disabledAuthentication = properties.getProperty(GREENMAIL_AUTH_DISABLED);\n if (null != disabledAuthentication) {\n configuration.withDisabledAuthentication();\n }\n return configuration;\n }", "private Duration getAssignmentWork(ProjectCalendar calendar, TimephasedWork assignment)\n {\n Date assignmentStart = assignment.getStart();\n\n Date splitStart = assignmentStart;\n Date splitFinishTime = calendar.getFinishTime(splitStart);\n Date splitFinish = DateHelper.setTime(splitStart, splitFinishTime);\n\n Duration calendarSplitWork = calendar.getWork(splitStart, splitFinish, TimeUnit.MINUTES);\n Duration assignmentWorkPerDay = assignment.getAmountPerDay();\n Duration splitWork;\n\n double splitMinutes = assignmentWorkPerDay.getDuration();\n splitMinutes *= calendarSplitWork.getDuration();\n splitMinutes /= (8 * 60); // this appears to be a fixed value\n splitWork = Duration.getInstance(splitMinutes, TimeUnit.MINUTES);\n return splitWork;\n }", "public static void initializeDomainRegistry(final TransformerRegistry registry) {\n\n //The chains for transforming will be as follows\n //For JBoss EAP: 8.0.0 -> 5.0.0 -> 4.0.0 -> 1.8.0 -> 1.7.0 -> 1.6.0 -> 1.5.0\n\n registerRootTransformers(registry);\n registerChainedManagementTransformers(registry);\n registerChainedServerGroupTransformers(registry);\n registerProfileTransformers(registry);\n registerSocketBindingGroupTransformers(registry);\n registerDeploymentTransformers(registry);\n }", "protected void postConnection(ConnectionHandle handle, long statsObtainTime){\r\n\r\n\t\thandle.renewConnection(); // mark it as being logically \"open\"\r\n\r\n\t\t// Give an application a chance to do something with it.\r\n\t\tif (handle.getConnectionHook() != null){\r\n\t\t\thandle.getConnectionHook().onCheckOut(handle);\r\n\t\t}\r\n\r\n\t\tif (this.pool.closeConnectionWatch){ // a debugging tool\r\n\t\t\tthis.pool.watchConnection(handle);\r\n\t\t}\r\n\r\n\t\tif (this.pool.statisticsEnabled){\r\n\t\t\tthis.pool.statistics.addCumulativeConnectionWaitTime(System.nanoTime()-statsObtainTime);\r\n\t\t}\r\n\t}" ]
Retrieve the calendar used internally for timephased baseline calculation. @return baseline calendar
[ "public ProjectCalendar getBaselineCalendar()\n {\n //\n // Attempt to locate the calendar normally used by baselines\n // If this isn't present, fall back to using the default\n // project calendar.\n //\n ProjectCalendar result = getCalendarByName(\"Used for Microsoft Project 98 Baseline Calendar\");\n if (result == null)\n {\n result = getDefaultCalendar();\n }\n return result;\n }" ]
[ "public void animate(GVRHybridObject object, float animationTime)\n {\n GVRMeshMorph morph = (GVRMeshMorph) mTarget;\n\n mKeyInterpolator.animate(animationTime * mDuration, mCurrentValues);\n morph.setWeights(mCurrentValues);\n\n }", "private StringBuilder calculateCacheKeyInternal(String sql,\r\n\t\t\tint resultSetType, int resultSetConcurrency) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+20);\r\n\t\ttmp.append(sql);\r\n\r\n\t\ttmp.append(\", T\");\r\n\t\ttmp.append(resultSetType);\r\n\t\ttmp.append(\", C\");\r\n\t\ttmp.append(resultSetConcurrency);\r\n\t\treturn tmp;\r\n\t}", "protected void append(Env env) {\n addAllWithFilter(this.envVars, env.envVars, filter.getPatternFilter());\n addAllWithFilter(this.sysVars, env.sysVars, filter.getPatternFilter());\n }", "public static ModelControllerClient createAndAdd(final ManagementChannelHandler handler) {\n final ExistingChannelModelControllerClient client = new ExistingChannelModelControllerClient(handler);\n handler.addHandlerFactory(client);\n return client;\n }", "public static csvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cachepolicy_binding obj = new csvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cachepolicy_binding response[] = (csvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void delete() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_WHITELIST_ENTRY_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, HttpMethod.DELETE);\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "private void harvestReturnValues(\r\n ProcedureDescriptor proc,\r\n Object obj,\r\n PreparedStatement stmt)\r\n throws PersistenceBrokerSQLException\r\n {\r\n // If the procedure descriptor is null or has no return values or\r\n // if the statement is not a callable statment, then we're done.\r\n if ((proc == null) || (!proc.hasReturnValues()))\r\n {\r\n return;\r\n }\r\n\r\n // Set up the callable statement\r\n CallableStatement callable = (CallableStatement) stmt;\r\n\r\n // This is the index that we'll use to harvest the return value(s).\r\n int index = 0;\r\n\r\n // If the proc has a return value, then try to harvest it.\r\n if (proc.hasReturnValue())\r\n {\r\n\r\n // Increment the index\r\n index++;\r\n\r\n // Harvest the value.\r\n this.harvestReturnValue(obj, callable, proc.getReturnValueFieldRef(), index);\r\n }\r\n\r\n // Check each argument. If it's returned by the procedure,\r\n // then harvest the value.\r\n Iterator iter = proc.getArguments().iterator();\r\n while (iter.hasNext())\r\n {\r\n index++;\r\n ArgumentDescriptor arg = (ArgumentDescriptor) iter.next();\r\n if (arg.getIsReturnedByProcedure())\r\n {\r\n this.harvestReturnValue(obj, callable, arg.getFieldRef(), index);\r\n }\r\n }\r\n }", "public void setWeekDays(SortedSet<WeekDay> weekDays) {\n\n final SortedSet<WeekDay> newWeekDays = null == weekDays ? new TreeSet<WeekDay>() : weekDays;\n SortedSet<WeekDay> currentWeekDays = m_model.getWeekDays();\n if (!currentWeekDays.equals(newWeekDays)) {\n conditionallyRemoveExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDays(newWeekDays);\n onValueChange();\n }\n }, !newWeekDays.containsAll(m_model.getWeekDays()));\n }\n }", "public void setBundleActivator(String bundleActivator) {\n\t\tString old = mainAttributes.get(BUNDLE_ACTIVATOR);\n\t\tif (!bundleActivator.equals(old)) {\n\t\t\tthis.mainAttributes.put(BUNDLE_ACTIVATOR, bundleActivator);\n\t\t\tthis.modified = true;\n\t\t\tthis.bundleActivator = bundleActivator;\n\t\t}\n\t}" ]
Register a new PerformanceMonitor with Spring if it does not already exist. @param beanName The name of the bean that this performance monitor is wrapped around @param registry The registry where all the spring beans are registered
[ "private void registerPerformanceMonitor(String beanName,\n BeanDefinitionRegistry registry) {\n\n String perfMonitorName = beanName + \"PerformanceMonitor\";\n if (!registry.containsBeanDefinition(perfMonitorName)) {\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(PerformanceMonitorBean.class);\n registry.registerBeanDefinition(perfMonitorName, initializer.getBeanDefinition());\n }\n }" ]
[ "public static <T> String join(Collection<T> col, String delim) {\n StringBuilder sb = new StringBuilder();\n Iterator<T> iter = col.iterator();\n if (iter.hasNext())\n sb.append(iter.next().toString());\n while (iter.hasNext()) {\n sb.append(delim);\n sb.append(iter.next().toString());\n }\n return sb.toString();\n }", "public static <K, V> HashMap<K, V> newEmptyHashMap(Iterable<?> iterable) {\n if(iterable instanceof Collection<?>)\n return Maps.newHashMapWithExpectedSize(((Collection<?>) iterable).size());\n return Maps.newHashMap();\n }", "private void writeImages() {\n\t\tfor (ValueMap gv : this.valueMaps) {\n\t\t\tgv.writeImage();\n\t\t}\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"map-site-count.csv\"))) {\n\t\t\tout.println(\"Site key,Number of geo items\");\n\t\t\tout.println(\"wikidata total,\" + this.count);\n\t\t\tfor (Entry<String, Integer> entry : this.siteCounts.entrySet()) {\n\t\t\t\tout.println(entry.getKey() + \",\" + entry.getValue());\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "public final void setAttributes(final Map<String, Attribute> attributes) {\n for (Map.Entry<String, Attribute> entry: attributes.entrySet()) {\n Object attribute = entry.getValue();\n if (!(attribute instanceof Attribute)) {\n final String msg =\n \"Attribute: '\" + entry.getKey() + \"' is not an attribute. It is a: \" + attribute;\n LOGGER.error(\"Error setting the Attributes: {}\", msg);\n throw new IllegalArgumentException(msg);\n } else {\n ((Attribute) attribute).setConfigName(entry.getKey());\n }\n }\n this.attributes = attributes;\n }", "private InputValue getInputValue(FormInput input) {\n\n\t\t/* Get the DOM element from Selenium. */\n\t\tWebElement inputElement = browser.getWebElement(input.getIdentification());\n\n\t\tswitch (input.getType()) {\n\t\t\tcase TEXT:\n\t\t\tcase PASSWORD:\n\t\t\tcase HIDDEN:\n\t\t\tcase SELECT:\n\t\t\tcase TEXTAREA:\n\t\t\t\treturn new InputValue(inputElement.getAttribute(\"value\"));\n\t\t\tcase RADIO:\n\t\t\tcase CHECKBOX:\n\t\t\tdefault:\n\t\t\t\tString value = inputElement.getAttribute(\"value\");\n\t\t\t\tBoolean checked = inputElement.isSelected();\n\t\t\t\treturn new InputValue(value, checked);\n\t\t}\n\n\t}", "void start(String monitoredDirectory, Long pollingTime) {\n this.monitoredDirectory = monitoredDirectory;\n String deployerKlassName;\n if (klass.equals(ImportDeclaration.class)) {\n deployerKlassName = ImporterDeployer.class.getName();\n } else if (klass.equals(ExportDeclaration.class)) {\n deployerKlassName = ExporterDeployer.class.getName();\n } else {\n throw new IllegalStateException(\"\");\n }\n\n this.dm = new DirectoryMonitor(monitoredDirectory, pollingTime, deployerKlassName);\n try {\n dm.start(getBundleContext());\n } catch (DirectoryMonitoringException e) {\n LOG.error(\"Failed to start \" + DirectoryMonitor.class.getName() + \" for the directory \" + monitoredDirectory + \" and polling time \" + pollingTime.toString(), e);\n }\n }", "public ProjectCalendar getDefaultCalendar()\n {\n String calendarName = m_properties.getDefaultCalendarName();\n ProjectCalendar calendar = getCalendarByName(calendarName);\n if (calendar == null)\n {\n if (m_calendars.isEmpty())\n {\n calendar = addDefaultBaseCalendar();\n }\n else\n {\n calendar = m_calendars.get(0);\n }\n }\n return calendar;\n }", "public void run(Configuration configuration, List<CandidateSteps> candidateSteps, Story story, MetaFilter filter)\n throws Throwable {\n run(configuration, candidateSteps, story, filter, null);\n }", "public static String digestToFileName(String digest) {\n if (StringUtils.startsWith(digest, \"sha1\")) {\n return \"manifest.json\";\n }\n return getShaVersion(digest) + \"__\" + getShaValue(digest);\n }" ]
Use this API to fetch all the appfwhtmlerrorpage resources that are configured on netscaler.
[ "public static appfwhtmlerrorpage get(nitro_service service, options option) throws Exception{\n\t\tappfwhtmlerrorpage obj = new appfwhtmlerrorpage();\n\t\tappfwhtmlerrorpage[] response = (appfwhtmlerrorpage[])obj.get_resources(service,option);\n\t\treturn response[0];\n\t}" ]
[ "public static final String getUnicodeString(byte[] data, int offset)\n {\n int length = getUnicodeStringLengthInBytes(data, offset);\n return length == 0 ? \"\" : new String(data, offset, length, CharsetHelper.UTF16LE);\n }", "@Override\n public Response doRequest(final StitchRequest stitchReq) {\n initAppMetadata(clientAppId);\n\n return super.doRequestUrl(stitchReq, getHostname());\n }", "public void copyCategories(CmsObject cms, CmsResource fromResource, String toResourceSitePath) throws CmsException {\n\n List<CmsCategory> categories = readResourceCategories(cms, fromResource);\n for (CmsCategory category : categories) {\n addResourceToCategory(cms, toResourceSitePath, category);\n }\n }", "public Matrix4f getFinalTransformMatrix()\n {\n final FloatBuffer fb = ByteBuffer.allocateDirect(4*4*4).order(ByteOrder.nativeOrder()).asFloatBuffer();\n NativeBone.getFinalTransformMatrix(getNative(), fb);\n return new Matrix4f(fb);\n }", "public static Info neg(final Variable A, ManagerTempVariables manager) {\n Info ret = new Info();\n\n if( A instanceof VariableInteger ) {\n final VariableInteger output = manager.createInteger();\n ret.output = output;\n ret.op = new Operation(\"neg-i\") {\n @Override\n public void process() {\n output.value = -((VariableInteger)A).value;\n }\n };\n } else if( A instanceof VariableScalar ) {\n final VariableDouble output = manager.createDouble();\n ret.output = output;\n ret.op = new Operation(\"neg-s\") {\n @Override\n public void process() {\n output.value = -((VariableScalar)A).getDouble();\n }\n };\n } else if( A instanceof VariableMatrix ) {\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n ret.op = new Operation(\"neg-m\") {\n @Override\n public void process() {\n DMatrixRMaj a = ((VariableMatrix)A).matrix;\n output.matrix.reshape(a.numRows, a.numCols);\n CommonOps_DDRM.changeSign(a, output.matrix);\n }\n };\n } else {\n throw new RuntimeException(\"Unsupported variable \"+A);\n }\n\n return ret;\n }", "public boolean isMaterialized(Object object)\r\n {\r\n IndirectionHandler handler = getIndirectionHandler(object);\r\n\r\n return handler == null || handler.alreadyMaterialized();\r\n }", "public void writeFinalResults() {\n\t\tprintStatus();\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers\n\t\t\t\t\t\t.openExampleFileOuputStream(\"life-expectancies.csv\"))) {\n\n\t\t\tfor (int i = 0; i < lifeSpans.length; i++) {\n\t\t\t\tif (peopleCount[i] != 0) {\n\t\t\t\t\tout.println(i + \",\" + (double) lifeSpans[i]\n\t\t\t\t\t\t\t/ peopleCount[i] + \",\" + peopleCount[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "public static ServiceName moduleServiceName(ModuleIdentifier identifier) {\n if (!identifier.getName().startsWith(MODULE_PREFIX)) {\n throw ServerLogger.ROOT_LOGGER.missingModulePrefix(identifier, MODULE_PREFIX);\n }\n return MODULE_SERVICE_PREFIX.append(identifier.getName()).append(identifier.getSlot());\n }", "public static <T, R extends Resource<T>> T getEntity(R resource) {\n return resource.getEntity();\n }" ]
Handles logging tasks related to a failure to connect to a remote HC. @param uri the URI at which the connection attempt was made. Can be {@code null} indicating a failure to discover the HC @param discoveryOption the {@code DiscoveryOption} used to determine {@code uri} @param moreOptions {@code true} if there are more untried discovery options @param e the exception
[ "static void logConnectionException(URI uri, DiscoveryOption discoveryOption, boolean moreOptions, Exception e) {\n if (uri == null) {\n HostControllerLogger.ROOT_LOGGER.failedDiscoveringMaster(discoveryOption, e);\n } else {\n HostControllerLogger.ROOT_LOGGER.cannotConnect(uri, e);\n }\n if (!moreOptions) {\n // All discovery options have been exhausted\n HostControllerLogger.ROOT_LOGGER.noDiscoveryOptionsLeft();\n }\n }" ]
[ "public static TestSuiteResult unmarshal(File testSuite) throws IOException {\n try (InputStream stream = new FileInputStream(testSuite)) {\n return unmarshal(stream);\n }\n }", "List<CmsResource> getBundleResources() {\n\n List<CmsResource> resources = new ArrayList<>(m_bundleFiles.values());\n if (m_desc != null) {\n resources.add(m_desc);\n }\n return resources;\n\n }", "public final void setWeekDay(WeekDay weekDay) {\n\n SortedSet<WeekDay> wds = new TreeSet<>();\n if (null != weekDay) {\n wds.add(weekDay);\n }\n setWeekDays(wds);\n\n }", "public boolean hasInstance(Scriptable instance) {\n // Default for JS objects (other than Function) is to do prototype\n // chasing.\n Scriptable proto = instance.getPrototype();\n while (proto != null) {\n if (proto.equals(this)) return true;\n proto = proto.getPrototype();\n }\n return false;\n }", "public static <T extends Annotation> List<T> searchForAnnotation(Method method, Class<T> annotation) {\n if (method == null) {\n return Lists.newArrayList();\n }\n return searchClasses(method, annotation, method.getDeclaringClass());\n }", "public List<Cluster> cluster(final Collection<Point2D> points) {\n \tfinal List<Cluster> clusters = new ArrayList<Cluster>();\n final Map<Point2D, PointStatus> visited = new HashMap<Point2D, DBScan.PointStatus>();\n\n KDTree<Point2D> tree = new KDTree<Point2D>(2);\n \n // Populate the kdTree\n for (final Point2D point : points) {\n \tdouble[] key = {point.x, point.y};\n \ttree.insert(key, point);\n }\n \n for (final Point2D point : points) {\n if (visited.get(point) != null) {\n continue;\n }\n final List<Point2D> neighbors = getNeighbors(point, tree);\n if (neighbors.size() >= minPoints) {\n // DBSCAN does not care about center points\n final Cluster cluster = new Cluster(clusters.size());\n clusters.add(expandCluster(cluster, point, neighbors, tree, visited));\n } else {\n visited.put(point, PointStatus.NOISE);\n }\n }\n\n for (Cluster cluster : clusters) {\n \tcluster.calculateCentroid();\n }\n \n return clusters;\n }", "public List<T> resolveConflicts(List<T> values) {\n if(values.size() > 1)\n return values;\n else\n return Collections.singletonList(values.get(0));\n }", "private static void deleteOldAndEmptyFiles() {\n File dir = LOG_FILE_DIR;\n if (dir.exists()) {\n File[] files = dir.listFiles();\n\n for (File f : files) {\n if (f.length() == 0 ||\n f.lastModified() + MAXFILEAGE < System.currentTimeMillis()) {\n f.delete();\n }\n }\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}" ]
select a use case.
[ "public UseCase selectUseCase()\r\n {\r\n displayUseCases();\r\n System.out.println(\"type in number to select a use case\");\r\n String in = readLine();\r\n int index = Integer.parseInt(in);\r\n return (UseCase) useCases.get(index);\r\n }" ]
[ "static Locale getLocale(PageContext pageContext, String name) {\r\n\r\n Locale loc = null;\r\n\r\n Object obj = javax.servlet.jsp.jstl.core.Config.find(pageContext, name);\r\n if (obj != null) {\r\n if (obj instanceof Locale) {\r\n loc = (Locale)obj;\r\n } else {\r\n loc = SetLocaleSupport.parseLocale((String)obj);\r\n }\r\n }\r\n\r\n return loc;\r\n }", "public void forAllExtents(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getExtentClasses(); it.hasNext(); )\r\n {\r\n _curExtent = (ClassDescriptorDef)it.next();\r\n generate(template);\r\n }\r\n _curExtent = null;\r\n }", "private GregorianCalendar getLastReleventDate(GregorianCalendar currentDate) {\n\t\tint age=this.getProperties().getMaxFileAge();\n\t\tGregorianCalendar result=new GregorianCalendar(currentDate.get(Calendar.YEAR),currentDate.get(Calendar.MONTH),currentDate.get(Calendar.DAY_OF_MONTH));\n\t\tresult.add(Calendar.DAY_OF_MONTH, -age);\n\t\treturn result;\n\t}", "private String toRfsName(String name, IconSize size) {\n\n return CmsStringUtil.joinPaths(m_cache.getRepositoryPath(), \"\" + name.hashCode()) + size.getSuffix();\n }", "public static void setFilterBoxStyle(TextField searchBox) {\n\n searchBox.setIcon(FontOpenCms.FILTER);\n\n searchBox.setPlaceholder(\n org.opencms.ui.apps.Messages.get().getBundle(UI.getCurrent().getLocale()).key(\n org.opencms.ui.apps.Messages.GUI_EXPLORER_FILTER_0));\n searchBox.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON);\n }", "public Metadata getMetadata(String templateName) {\n String scope = Metadata.scopeBasedOnType(templateName);\n return this.getMetadata(templateName, scope);\n }", "private void setObjectForStatement(PreparedStatement stmt, int index, Object value, int sqlType)\r\n throws SQLException\r\n {\r\n if (value == null)\r\n {\r\n m_platform.setNullForStatement(stmt, index, sqlType);\r\n }\r\n else\r\n {\r\n m_platform.setObjectForStatement(stmt, index, value, sqlType);\r\n }\r\n }", "public static Boolean assertTrue(Boolean value, String message) {\n if (!Boolean.valueOf(value))\n throw new IllegalStateException(message);\n\n return value;\n }", "public static ConstraintField getInstance(int value)\n {\n ConstraintField result = null;\n\n if (value >= 0 && value < FIELD_ARRAY.length)\n {\n result = FIELD_ARRAY[value];\n }\n\n return (result);\n }" ]
Retrieve configuration details for a given custom field. @param field required custom field @return configuration detail
[ "public CustomField getCustomField(FieldType field)\n {\n CustomField result = m_configMap.get(field);\n if (result == null)\n {\n result = new CustomField(field, this);\n m_configMap.put(field, result);\n }\n return result;\n }" ]
[ "@SafeVarargs\n public static <T> Set<T> of(T... elements) {\n Preconditions.checkNotNull(elements);\n return ImmutableSet.<T> builder().addAll(elements).build();\n }", "public void setProperty(Object object, Object newValue) {\n MetaMethod setter = getSetter();\n if (setter == null) {\n if (field != null && !Modifier.isFinal(field.getModifiers())) {\n field.setProperty(object, newValue);\n return;\n }\n throw new GroovyRuntimeException(\"Cannot set read-only property: \" + name);\n }\n newValue = DefaultTypeTransformation.castToType(newValue, getType());\n setter.invoke(object, new Object[]{newValue});\n }", "@OnClick(R.id.navigateToModule1Service)\n public void onNavigationServiceCTAClick() {\n Intent intentService = HensonNavigator.gotoModule1Service(this)\n .stringExtra(\"foo\")\n .build();\n\n startService(intentService);\n }", "public static GVRTexture loadFutureCubemapTexture(\n GVRContext gvrContext, ResourceCache<GVRImage> textureCache,\n GVRAndroidResource resource, int priority,\n Map<String, Integer> faceIndexMap) {\n GVRTexture tex = new GVRTexture(gvrContext);\n GVRImage cached = textureCache.get(resource);\n if (cached != null)\n {\n Log.v(\"ASSET\", \"Future Texture: %s loaded from cache\", cached.getFileName());\n tex.setImage(cached);\n }\n else\n {\n AsyncCubemapTexture.get().loadTexture(gvrContext,\n CancelableCallbackWrapper.wrap(GVRCubemapImage.class, tex),\n resource, priority, faceIndexMap);\n\n }\n return tex;\n }", "public double getValueAsPrice(double evaluationTime, AnalyticModel model) {\n\t\tForwardCurve\tforwardCurve\t= model.getForwardCurve(forwardCurveName);\n\t\tDiscountCurve\tdiscountCurve\t= model.getDiscountCurve(discountCurveName);\n\n\t\tDiscountCurve\tdiscountCurveForForward = null;\n\t\tif(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {\n\t\t\t// User might like to get forward from discount curve.\n\t\t\tdiscountCurveForForward\t= model.getDiscountCurve(forwardCurveName);\n\n\t\t\tif(discountCurveForForward == null) {\n\t\t\t\t// User specified a name for the forward curve, but no curve was found.\n\t\t\t\tthrow new IllegalArgumentException(\"No curve of the name \" + forwardCurveName + \" was found in the model.\");\n\t\t\t}\n\t\t}\n\n\t\tdouble value = 0.0;\n\t\tfor(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) {\n\t\t\tdouble fixingDate\t= schedule.getFixing(periodIndex);\n\t\t\tdouble paymentDate\t= schedule.getPayment(periodIndex);\n\t\t\tdouble periodLength\t= schedule.getPeriodLength(periodIndex);\n\n\t\t\t/*\n\t\t\t * We do not count empty periods.\n\t\t\t * Since empty periods are an indication for a ill-specified product,\n\t\t\t * it might be reasonable to throw an illegal argument exception instead.\n\t\t\t */\n\t\t\tif(periodLength == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tdouble forward = 0.0;\n\t\t\tif(forwardCurve != null) {\n\t\t\t\tforward\t\t\t+= forwardCurve.getForward(model, fixingDate, paymentDate-fixingDate);\n\t\t\t}\n\t\t\telse if(discountCurveForForward != null) {\n\t\t\t\t/*\n\t\t\t\t * Classical single curve case: using a discount curve as a forward curve.\n\t\t\t\t * This is only implemented for demonstration purposes (an exception would also be appropriate :-)\n\t\t\t\t */\n\t\t\t\tif(fixingDate != paymentDate) {\n\t\t\t\t\tforward\t\t\t+= (discountCurveForForward.getDiscountFactor(fixingDate) / discountCurveForForward.getDiscountFactor(paymentDate) - 1.0) / (paymentDate-fixingDate);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdouble discountFactor\t= paymentDate > evaluationTime ? discountCurve.getDiscountFactor(model, paymentDate) : 0.0;\n\t\t\tdouble payoffUnit = discountFactor * periodLength;\n\n\t\t\tdouble effektiveStrike = strike;\n\t\t\tif(isStrikeMoneyness) {\n\t\t\t\teffektiveStrike += getATMForward(model, true);\n\t\t\t}\n\n\t\t\tVolatilitySurface volatilitySurface\t= model.getVolatilitySurface(volatiltiySufaceName);\n\t\t\tif(volatilitySurface == null) {\n\t\t\t\tthrow new IllegalArgumentException(\"Volatility surface not found in model: \" + volatiltiySufaceName);\n\t\t\t}\n\t\t\tif(volatilitySurface.getQuotingConvention() == QuotingConvention.VOLATILITYLOGNORMAL) {\n\t\t\t\tdouble volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYLOGNORMAL);\n\t\t\t\tvalue += AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Default to normal volatility as quoting convention\n\t\t\t\tdouble volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYNORMAL);\n\t\t\t\tvalue += AnalyticFormulas.bachelierOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit);\n\t\t\t}\n\t\t}\n\n\t\treturn value / discountCurve.getDiscountFactor(model, evaluationTime);\n\t}", "private String registerEventHandler(GFXEventHandler h) {\n //checkInitialized();\n if (!registeredOnJS) {\n JSObject doc = (JSObject) runtime.execute(\"document\");\n doc.setMember(\"jsHandlers\", jsHandlers);\n registeredOnJS = true;\n }\n return jsHandlers.registerHandler(h);\n }", "public void setOnCloseListener(@NonNull final android.support.v7.widget.SearchView.OnCloseListener listener) {\n if (searchView != null) {\n searchView.setOnCloseListener(new SearchView.OnCloseListener() {\n @Override public boolean onClose() {\n return listener.onClose();\n }\n });\n } else if (supportView != null) {\n supportView.setOnCloseListener(listener);\n } else {\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }\n }", "protected List<String> parseWords(String line) {\n List<String> words = new ArrayList<String>();\n boolean insideWord = !isSpace(line.charAt(0));\n int last = 0;\n for( int i = 0; i < line.length(); i++) {\n char c = line.charAt(i);\n\n if( insideWord ) {\n // see if its at the end of a word\n if( isSpace(c)) {\n words.add( line.substring(last,i) );\n insideWord = false;\n }\n } else {\n if( !isSpace(c)) {\n last = i;\n insideWord = true;\n }\n }\n }\n\n // if the line ended add the final word\n if( insideWord ) {\n words.add( line.substring(last));\n }\n return words;\n }", "public void setBit(int index, boolean set)\n {\n assertValidIndex(index);\n int word = index / WORD_LENGTH;\n int offset = index % WORD_LENGTH;\n if (set)\n {\n data[word] |= (1 << offset);\n }\n else // Unset the bit.\n {\n data[word] &= ~(1 << offset);\n }\n }" ]
Compiles and fills the reports design. @param dr the DynamicReport @param layoutManager the object in charge of doing the layout @param ds The datasource @param _parameters Map with parameters that the report may need @return @throws JRException
[ "public static JasperPrint generateJasperPrint(DynamicReport dr, LayoutManager layoutManager, JRDataSource ds, Map<String, Object> _parameters) throws JRException {\n log.info(\"generating JasperPrint\");\n JasperPrint jp;\n\n\n JasperReport jr = DynamicJasperHelper.generateJasperReport(dr, layoutManager, _parameters);\n jp = JasperFillManager.fillReport(jr, _parameters, ds);\n\n return jp;\n }" ]
[ "public static double normP1( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return CommonOps_DDRM.elementSumAbs(A);\n } else {\n return inducedP1(A);\n }\n }", "public StandaloneCommandBuilder setDebug(final boolean suspend, final int port) {\n debugArg = String.format(DEBUG_FORMAT, (suspend ? \"y\" : \"n\"), port);\n return this;\n }", "public static vpnglobal_auditnslogpolicy_binding[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tvpnglobal_auditnslogpolicy_binding obj = new vpnglobal_auditnslogpolicy_binding();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tvpnglobal_auditnslogpolicy_binding[] response = (vpnglobal_auditnslogpolicy_binding[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "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 }", "synchronized void setServerProcessStopping() {\n this.requiredState = InternalState.STOPPED;\n internalSetState(null, InternalState.STOPPED, InternalState.PROCESS_STOPPING);\n }", "public void setContentType(int pathId, String contentType) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_CONTENT_TYPE + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, contentType);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "private static Map<String, Set<String>> expand(Map<String, Set<String>> viewToPropNames) {\n\n Set<String> baseProps = viewToPropNames.get(PropertyView.BASE_VIEW);\n\n if (baseProps == null) {\n baseProps = ImmutableSet.of();\n }\n\n if (!SquigglyConfig.isFilterImplicitlyIncludeBaseFieldsInView()) {\n\n // make an exception for full view\n Set<String> fullView = viewToPropNames.get(PropertyView.FULL_VIEW);\n\n if (fullView != null) {\n fullView.addAll(baseProps);\n }\n\n return viewToPropNames;\n }\n\n for (Map.Entry<String, Set<String>> entry : viewToPropNames.entrySet()) {\n String viewName = entry.getKey();\n Set<String> propNames = entry.getValue();\n\n if (!PropertyView.BASE_VIEW.equals(viewName)) {\n propNames.addAll(baseProps);\n }\n }\n\n return viewToPropNames;\n }", "public static dnsnsecrec get(nitro_service service, String hostname) throws Exception{\n\t\tdnsnsecrec obj = new dnsnsecrec();\n\t\tobj.set_hostname(hostname);\n\t\tdnsnsecrec response = (dnsnsecrec) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static base_responses update(nitro_service client, snmpmanager resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpmanager updateresources[] = new snmpmanager[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new snmpmanager();\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].netmask = resources[i].netmask;\n\t\t\t\tupdateresources[i].domainresolveretry = resources[i].domainresolveretry;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Try to get an attribute value from two elements. @param firstElement @param secondElement @return attribute value
[ "private static String getAttribute(String name, Element firstElement, Element secondElement) {\r\n String val = firstElement.getAttribute(name);\r\n if (val.length() == 0 && secondElement != null) {\r\n val = secondElement.getAttribute(name);\r\n }\r\n return val;\r\n }" ]
[ "protected boolean executeOperation(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, TransactionalProtocolClient client, final ServerIdentity identity, final ModelNode operation, final OperationResultTransformer transformer) {\n if(client == null) {\n return false;\n }\n final OperationMessageHandler messageHandler = new DelegatingMessageHandler(context);\n final OperationAttachments operationAttachments = new DelegatingOperationAttachments(context);\n final ServerOperation serverOperation = new ServerOperation(identity, operation, messageHandler, operationAttachments, transformer);\n try {\n DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef(\"Sending %s to %s\", operation, identity);\n final Future<OperationResponse> result = client.execute(listener, serverOperation);\n recordExecutedRequest(new ExecutedServerRequest(identity, result, transformer));\n } catch (IOException e) {\n final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e);\n listener.operationPrepared(result);\n recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), transformer));\n }\n return true;\n }", "public static Interface[] get(nitro_service service) throws Exception{\n\t\tInterface obj = new Interface();\n\t\tInterface[] response = (Interface[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private void addColumns(MpxjTreeNode parentNode, Table table)\n {\n for (Column column : table.getColumns())\n {\n final Column c = column;\n MpxjTreeNode childNode = new MpxjTreeNode(column)\n {\n @Override public String toString()\n {\n return c.getTitle();\n }\n };\n parentNode.add(childNode);\n }\n }", "@SuppressWarnings(\"WeakerAccess\")\n public static SlotReference getSlotReference(DataReference dataReference) {\n return getSlotReference(dataReference.player, dataReference.slot);\n }", "private String getSignature(String sharedSecret, Map<String, String> params) {\r\n StringBuffer buffer = new StringBuffer();\r\n buffer.append(sharedSecret);\r\n for (Map.Entry<String, String> entry : params.entrySet()) {\r\n buffer.append(entry.getKey());\r\n buffer.append(entry.getValue());\r\n }\r\n\r\n try {\r\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\r\n return ByteUtilities.toHexString(md.digest(buffer.toString().getBytes(\"UTF-8\")));\r\n } catch (NoSuchAlgorithmException e) {\r\n throw new RuntimeException(e);\r\n } catch (UnsupportedEncodingException u) {\r\n throw new RuntimeException(u);\r\n }\r\n }", "public static void mainInternal(String[] args) throws Exception {\n\n Options options = new Options();\n CmdLineParser parser = new CmdLineParser(options);\n try {\n parser.parseArgument(args);\n } catch (CmdLineException e) {\n helpScreen(parser);\n return;\n }\n\n try {\n List<String> configs = new ArrayList<>();\n if (options.configs != null) {\n configs.addAll(Arrays.asList(options.configs.split(\",\")));\n }\n ConfigSupport.applyConfigChange(ConfigSupport.getJBossHome(), configs, options.enable);\n } catch (ConfigException ex) {\n ConfigLogger.error(ex);\n throw ex;\n } catch (Throwable th) {\n ConfigLogger.error(th);\n throw th;\n }\n }", "private static Query buildQuery(ClassDescriptor cld)\r\n {\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n Criteria crit = new Criteria();\r\n\r\n for(int i = 0; i < pkFields.length; i++)\r\n {\r\n crit.addEqualTo(pkFields[i].getAttributeName(), null);\r\n }\r\n return new QueryByCriteria(cld.getClassOfObject(), crit);\r\n }", "public AnalyticProductInterface getCalibrationProductForSymbol(String symbol) {\n\n\t\t/*\n\t\t * The internal data structure is not optimal here (a map would make more sense here),\n\t\t * if the user does not require access to the products, we would allow non-unique symbols.\n\t\t * Hence we store both in two side by side vectors.\n\t\t */\n\t\tfor(int i=0; i<calibrationProductsSymbols.size(); i++) {\n\t\t\tString calibrationProductSymbol = calibrationProductsSymbols.get(i);\n\t\t\tif(calibrationProductSymbol.equals(symbol)) {\n\t\t\t\treturn calibrationProducts.get(i);\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}", "private Table getTable(String name)\n {\n Table table = m_tables.get(name);\n if (table == null)\n {\n table = EMPTY_TABLE;\n }\n return table;\n }" ]
Ensures that the given collection descriptor has a valid element-class-ref property. @param collDef The collection descriptor @param checkLevel The current check level (this constraint is checked in basic and strict) @exception ConstraintException If element-class-ref could not be determined or is invalid
[ "private void ensureElementClassRef(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String arrayElementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ARRAY_ELEMENT_CLASS_REF);\r\n\r\n if (!collDef.hasProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF))\r\n {\r\n if (arrayElementClassName != null)\r\n {\r\n // we use the array element type\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF, arrayElementClassName);\r\n }\r\n else\r\n {\r\n throw new ConstraintException(\"Collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" does not specify its element class\");\r\n }\r\n }\r\n\r\n // now checking the element type\r\n ModelDef model = (ModelDef)collDef.getOwner().getOwner();\r\n String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);\r\n ClassDescriptorDef elementClassDef = model.getClass(elementClassName);\r\n\r\n if (elementClassDef == null)\r\n {\r\n throw new ConstraintException(\"Collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" references an unknown class \"+elementClassName);\r\n }\r\n if (!elementClassDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_OJB_PERSISTENT, false))\r\n {\r\n throw new ConstraintException(\"The element class \"+elementClassName+\" of the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" is not persistent\");\r\n }\r\n if (CHECKLEVEL_STRICT.equals(checkLevel) && (arrayElementClassName != null))\r\n {\r\n // specified element class must be a subtype of the element type\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(elementClassDef, arrayElementClassName, true))\r\n {\r\n throw new ConstraintException(\"The element class \"+elementClassName+\" of the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" is not the same or a subtype of the array base type \"+arrayElementClassName);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName());\r\n }\r\n }\r\n // we're adjusting the property to use the classloader-compatible form\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF, elementClassDef.getName());\r\n }" ]
[ "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}", "private Envelope getMaxScreenEnvelope(InternalTile tile, Coordinate panOrigin) {\n\t\tint nrOfTilesX = Math.max(1, MAXIMUM_TILE_COORDINATE / tile.getScreenWidth());\n\t\tint nrOfTilesY = Math.max(1, MAXIMUM_TILE_COORDINATE / tile.getScreenHeight());\n\n\t\tdouble x1 = panOrigin.x - nrOfTilesX * tile.getTileWidth();\n\t\t// double x2 = x1 + (nrOfTilesX * tileWidth * 2);\n\t\tdouble x2 = panOrigin.x + nrOfTilesX * tile.getTileWidth();\n\t\tdouble y1 = panOrigin.y - nrOfTilesY * tile.getTileHeight();\n\t\t// double y2 = y1 + (nrOfTilesY * tileHeight * 2);\n\t\tdouble y2 = panOrigin.y + nrOfTilesY * tile.getTileHeight();\n\t\treturn new Envelope(x1, x2, y1, y2);\n\t}", "private static LblTree createTree(TreeWalker walker) {\n\t\tNode parent = walker.getCurrentNode();\n\t\tLblTree node = new LblTree(parent.getNodeName(), -1); // treeID = -1\n\t\tfor (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) {\n\t\t\tnode.add(createTree(walker));\n\t\t}\n\t\twalker.setCurrentNode(parent);\n\t\treturn node;\n\t}", "protected float[] transformPosition(float x, float y)\n {\n Point2D.Float point = super.transformedPoint(x, y);\n AffineTransform pageTransform = createCurrentPageTransformation();\n Point2D.Float transformedPoint = (Point2D.Float) pageTransform.transform(point, null);\n\n return new float[]{(float) transformedPoint.getX(), (float) transformedPoint.getY()};\n }", "public EventBus emit(String event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }", "public static appfwprofile_excluderescontenttype_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_excluderescontenttype_binding obj = new appfwprofile_excluderescontenttype_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_excluderescontenttype_binding response[] = (appfwprofile_excluderescontenttype_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static void startCheck(String extra) {\n startCheckTime = System.currentTimeMillis();\n nextCheckTime = startCheckTime;\n Log.d(Log.SUBSYSTEM.TRACING, \"FPSCounter\" , \"[%d] startCheck %s\", startCheckTime, extra);\n }", "static <T> List<Template> getTemplates(T objectType) {\n try {\n List<Template> templates = new ArrayList<>();\n TEMP_FINDER.findAnnotations(templates, objectType);\n return templates;\n } catch (Exception e) {\n throw new IllegalStateException(e);\n }\n }", "public String getSQL92LikePattern() throws IllegalArgumentException {\n\t\tif (escape.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> escape char should be of length exactly 1\");\n\t\t}\n\t\tif (wildcardSingle.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> wildcardSingle char should be of length exactly 1\");\n\t\t}\n\t\tif (wildcardMulti.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> wildcardMulti char should be of length exactly 1\");\n\t\t}\n\t\treturn LikeFilterImpl.convertToSQL92(escape.charAt(0), wildcardMulti.charAt(0), wildcardSingle.charAt(0),\n\t\t\t\tisMatchingCase(), pattern);\n\t}" ]
Notifies all listeners that the data is about to be loaded.
[ "protected void beforeLoading()\r\n {\r\n if (_listeners != null)\r\n {\r\n CollectionProxyListener listener;\r\n\r\n if (_perThreadDescriptorsEnabled) {\r\n loadProfileIfNeeded();\r\n }\r\n for (int idx = _listeners.size() - 1; idx >= 0; idx--)\r\n {\r\n listener = (CollectionProxyListener)_listeners.get(idx);\r\n listener.beforeLoading(this);\r\n }\r\n }\r\n }" ]
[ "private void verifyOrAddStore(String clusterURL,\n String keySchema,\n String valueSchema) {\n String newStoreDefXml = VoldemortUtils.getStoreDefXml(\n storeName,\n props.getInt(BUILD_REPLICATION_FACTOR, 2),\n props.getInt(BUILD_REQUIRED_READS, 1),\n props.getInt(BUILD_REQUIRED_WRITES, 1),\n props.getNullableInt(BUILD_PREFERRED_READS),\n props.getNullableInt(BUILD_PREFERRED_WRITES),\n props.getString(PUSH_FORCE_SCHEMA_KEY, keySchema),\n props.getString(PUSH_FORCE_SCHEMA_VALUE, valueSchema),\n description,\n owners);\n\n log.info(\"Verifying store against cluster URL: \" + clusterURL + \"\\n\" + newStoreDefXml.toString());\n StoreDefinition newStoreDef = VoldemortUtils.getStoreDef(newStoreDefXml);\n\n try {\n adminClientPerCluster.get(clusterURL).storeMgmtOps.verifyOrAddStore(newStoreDef, \"BnP config/data\",\n enableStoreCreation, this.storeVerificationExecutorService);\n } catch (UnreachableStoreException e) {\n log.info(\"verifyOrAddStore() failed on some nodes for clusterURL: \" + clusterURL + \" (this is harmless).\", e);\n // When we can't reach some node, we just skip it and won't create the store on it.\n // Next time BnP is run while the node is up, it will get the store created.\n } // Other exceptions need to bubble up!\n\n storeDef = newStoreDef;\n }", "public static Integer convertPathIdentifier(String identifier, Integer profileId) throws Exception {\n Integer pathId = -1;\n try {\n pathId = Integer.parseInt(identifier);\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n if (profileId == null)\n throw new Exception(\"A profileId must be specified\");\n\n pathId = PathOverrideService.getInstance().getPathId(identifier, profileId);\n }\n\n return pathId;\n }", "private void readCalendars(Document cdp)\n {\n for (Calendar calendar : cdp.getCalendars().getCalendar())\n {\n readCalendar(calendar);\n }\n\n for (Calendar calendar : cdp.getCalendars().getCalendar())\n {\n ProjectCalendar child = m_calendarMap.get(calendar.getID());\n ProjectCalendar parent = m_calendarMap.get(calendar.getBaseCalendarID());\n if (parent == null)\n {\n m_projectFile.setDefaultCalendar(child);\n }\n else\n {\n child.setParent(parent);\n }\n }\n }", "void countNonZeroInV( int []parent ) {\n int []w = gwork.data;\n findMinElementIndexInRows(leftmost);\n createRowElementLinkedLists(leftmost,w);\n countNonZeroUsingLinkedList(parent,w);\n }", "public String asString() throws IOException {\n long len = getContentLength();\n ByteArrayOutputStream buf;\n if (0 < len) {\n buf = new ByteArrayOutputStream((int) len);\n } else {\n buf = new ByteArrayOutputStream();\n }\n writeTo(buf);\n return decode(buf.toByteArray(), getCharacterEncoding());\n }", "public static String nameFromOffset(long offset) {\n NumberFormat nf = NumberFormat.getInstance();\n nf.setMinimumIntegerDigits(20);\n nf.setMaximumFractionDigits(0);\n nf.setGroupingUsed(false);\n return nf.format(offset) + Log.FileSuffix;\n }", "public static int cudnnActivationBackward(\n cudnnHandle handle, \n cudnnActivationDescriptor activationDesc, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnActivationBackwardNative(handle, activationDesc, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }", "@Nullable\n @SuppressWarnings(\"unchecked\")\n protected <T extends JavaElement> ActiveElements<T> popIfActive() {\n return (ActiveElements<T>) (!activations.isEmpty() && activations.peek().depth == depth ? activations.pop() :\n null);\n }", "public static ReportGenerator.Format getFormat( String... args ) {\n ConfigOptionParser configParser = new ConfigOptionParser();\n List<ConfigOption> configOptions = Arrays.asList( format, help );\n\n for( ConfigOption co : configOptions ) {\n if( co.hasDefault() ) {\n configParser.parsedOptions.put( co.getLongName(), co.getValue() );\n }\n }\n\n for( String arg : args ) {\n configParser.commandLineLookup( arg, format, configOptions );\n }\n\n // TODO properties\n // TODO environment\n\n if( !configParser.hasValue( format ) ) {\n configParser.printUsageAndExit( configOptions );\n }\n return (ReportGenerator.Format) configParser.getValue( format );\n }" ]
Support the subscript operator for GString. @param text a GString @param index the index of the Character to get @return the Character at the given index @since 2.3.7
[ "public static String getAt(GString text, int index) {\n return (String) getAt(text.toString(), index);\n }" ]
[ "public void runOnBrowserCreatedPlugins(EmbeddedBrowser newBrowser) {\n\t\tLOGGER.debug(\"Running OnBrowserCreatedPlugins...\");\n\t\tcounters.get(OnBrowserCreatedPlugin.class).inc();\n\t\tfor (Plugin plugin : plugins.get(OnBrowserCreatedPlugin.class)) {\n\t\t\tif (plugin instanceof OnBrowserCreatedPlugin) {\n\t\t\t\tLOGGER.debug(\"Calling plugin {}\", plugin);\n\t\t\t\ttry {\n\t\t\t\t\t((OnBrowserCreatedPlugin) plugin)\n\t\t\t\t\t\t\t.onBrowserCreated(newBrowser);\n\t\t\t\t} catch (RuntimeException e) {\n\t\t\t\t\treportFailingPlugin(plugin, e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "private static final String correctNumberFormat(String value)\n {\n String result;\n int index = value.indexOf(',');\n if (index == -1)\n {\n result = value;\n }\n else\n {\n char[] chars = value.toCharArray();\n chars[index] = '.';\n result = new String(chars);\n }\n return result;\n }", "@SuppressWarnings(\"WeakerAccess\")\n protected void clearRmiTargetsMap(ClassLoaderLeakPreventor preventor, Map<?, ?> rmiTargetsMap) {\n try {\n final Field cclField = preventor.findFieldOfClass(\"sun.rmi.transport.Target\", \"ccl\");\n preventor.debug(\"Looping \" + rmiTargetsMap.size() + \" RMI Targets to find leaks\");\n for(Iterator<?> iter = rmiTargetsMap.values().iterator(); iter.hasNext(); ) {\n Object target = iter.next(); // sun.rmi.transport.Target\n ClassLoader ccl = (ClassLoader) cclField.get(target);\n if(preventor.isClassLoaderOrChild(ccl)) {\n preventor.warn(\"Removing RMI Target: \" + target);\n iter.remove();\n }\n }\n }\n catch (Exception ex) {\n preventor.error(ex);\n }\n }", "protected void appendList(StringBuilder sql, List<?> list, String init, String sep) {\n\n boolean first = true;\n\n for (Object s : list) {\n if (first) {\n sql.append(init);\n } else {\n sql.append(sep);\n }\n sql.append(s);\n first = false;\n }\n }", "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 }", "private GeometryCoordinateSequenceTransformer getTransformer() {\n\t\tif (unitToPixel == null) {\n\t\t\tunitToPixel = new GeometryCoordinateSequenceTransformer();\n\t\t\tunitToPixel.setMathTransform(ProjectiveTransform.create(new AffineTransform(scale, 0, 0, -scale, -scale\n\t\t\t\t\t* panOrigin.x, scale * panOrigin.y)));\n\t\t}\n\t\treturn unitToPixel;\n\t}", "public JSONObject marshal(final AccessAssertion assertion) {\n final JSONObject jsonObject = assertion.marshal();\n if (jsonObject.has(JSON_CLASS_NAME)) {\n throw new AssertionError(\"The toJson method in AccessAssertion: '\" + assertion.getClass() +\n \"' defined a JSON field \" + JSON_CLASS_NAME +\n \" which is a reserved keyword and is not permitted to be used \" +\n \"in toJSON method\");\n }\n try {\n jsonObject.put(JSON_CLASS_NAME, assertion.getClass().getName());\n } catch (JSONException e) {\n throw new RuntimeException(e);\n }\n\n return jsonObject;\n }", "public InsertIntoTable addRowsFrom(File file, FileParser fileParser) {\n builder.addRowsFrom(file, fileParser);\n return this;\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 }" ]
Get container for principal. @param cms cmsobject @param list of principals @param captionID caption id @param descID description id @param iconID icon id @param ouID ou id @param icon icon @param iconList iconlist @return indexedcontainer
[ "public static IndexedContainer getPrincipalContainer(\n CmsObject cms,\n List<? extends I_CmsPrincipal> list,\n String captionID,\n String descID,\n String iconID,\n String ouID,\n String icon,\n List<FontIcon> iconList) {\n\n IndexedContainer res = new IndexedContainer();\n\n res.addContainerProperty(captionID, String.class, \"\");\n res.addContainerProperty(ouID, String.class, \"\");\n res.addContainerProperty(iconID, FontIcon.class, new CmsCssIcon(icon));\n if (descID != null) {\n res.addContainerProperty(descID, String.class, \"\");\n }\n\n for (I_CmsPrincipal group : list) {\n\n Item item = res.addItem(group);\n item.getItemProperty(captionID).setValue(group.getSimpleName());\n item.getItemProperty(ouID).setValue(group.getOuFqn());\n if (descID != null) {\n item.getItemProperty(descID).setValue(group.getDescription(A_CmsUI.get().getLocale()));\n }\n }\n\n for (int i = 0; i < iconList.size(); i++) {\n res.getItem(res.getIdByIndex(i)).getItemProperty(iconID).setValue(iconList.get(i));\n }\n\n return res;\n }" ]
[ "public AsciiTable setPaddingBottomChar(Character paddingBottomChar) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingBottomChar(paddingBottomChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public void validateAliases(\r\n final CmsUUID uuid,\r\n final Map<String, String> aliasPaths,\r\n final AsyncCallback<Map<String, String>> callback) {\r\n\r\n CmsRpcAction<Map<String, String>> action = new CmsRpcAction<Map<String, String>>() {\r\n\r\n /**\r\n * @see org.opencms.gwt.client.rpc.CmsRpcAction#execute()\r\n */\r\n @Override\r\n public void execute() {\r\n\r\n start(200, true);\r\n CmsCoreProvider.getVfsService().validateAliases(uuid, aliasPaths, this);\r\n }\r\n\r\n /**\r\n * @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object)\r\n */\r\n @Override\r\n protected void onResponse(Map<String, String> result) {\r\n\r\n stop(false);\r\n callback.onSuccess(result);\r\n }\r\n\r\n };\r\n action.execute();\r\n }", "public static void setTranslucentStatusFlag(Activity activity, boolean on) {\n if (Build.VERSION.SDK_INT >= 19) {\n setFlag(activity, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, on);\n }\n }", "public boolean classifyDocumentStdin(DocumentReaderAndWriter<IN> readerWriter)\r\n throws IOException\r\n {\r\n BufferedReader is = new BufferedReader(new InputStreamReader(System.in, flags.inputEncoding));\r\n String line;\r\n String text = \"\";\r\n String eol = \"\\n\";\r\n String sentence = \"<s>\";\r\n int blankLines = 0;\r\n while ((line = is.readLine()) != null) {\r\n if (line.trim().equals(\"\")) {\r\n \t ++blankLines;\r\n \t if (blankLines > 3) {\r\n \t\t return false;\r\n \t } else if (blankLines > 2) {\r\n\t\t\t ObjectBank<List<IN>> documents = makeObjectBankFromString(text, readerWriter);\r\n\t \t classifyAndWriteAnswers(documents, readerWriter);\r\n \t\t text = \"\";\r\n \t } else {\r\n \t\t text += sentence + eol;\r\n \t }\r\n } else {\r\n \t text += line + eol;\r\n \t blankLines = 0;\r\n }\r\n }\r\n // Classify last document before input stream end\r\n if (text.trim() != \"\") {\r\n ObjectBank<List<IN>> documents = makeObjectBankFromString(text, readerWriter);\r\n \t classifyAndWriteAnswers(documents, readerWriter);\r\n }\r\n return (line == null); // reached eol\r\n }", "public static vpnvserver_aaapreauthenticationpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_aaapreauthenticationpolicy_binding obj = new vpnvserver_aaapreauthenticationpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_aaapreauthenticationpolicy_binding response[] = (vpnvserver_aaapreauthenticationpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public StackTraceElement[] asStackTrace() {\n\t\tint i = 1;\n\t\tStackTraceElement[] list = new StackTraceElement[this.size()];\n\t\tfor (Eventable e : this) {\n\t\t\tlist[this.size() - i] =\n\t\t\t\t\tnew StackTraceElement(e.getEventType().toString(), e.getIdentification()\n\t\t\t\t\t\t\t.toString(), e.getElement().toString(), i);\n\t\t\ti++;\n\t\t}\n\t\treturn list;\n\t}", "private boolean hasReceivedHeartbeat() {\n long currentTimeMillis = System.currentTimeMillis();\n boolean result = lastTimeMessageReceived + heartbeatTimeoutMs >= currentTimeMillis;\n\n if (!result)\n Jvm.warn().on(getClass(), Integer.toHexString(hashCode()) + \" missed heartbeat, lastTimeMessageReceived=\" + lastTimeMessageReceived\n + \", currentTimeMillis=\" + currentTimeMillis);\n return result;\n }", "public PhotoList<Photo> search(SearchParameters params, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SEARCH);\r\n\r\n parameters.putAll(params.getAsParameters());\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }", "private List<TimephasedCost> getTimephasedActualCostFixedAmount()\n {\n List<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n double actualCost = getActualCost().doubleValue();\n\n if (actualCost > 0)\n {\n AccrueType accrueAt = getResource().getAccrueAt();\n\n if (accrueAt == AccrueType.START)\n {\n result.add(splitCostStart(getCalendar(), actualCost, getActualStart()));\n }\n else\n if (accrueAt == AccrueType.END)\n {\n result.add(splitCostEnd(getCalendar(), actualCost, getActualFinish()));\n }\n else\n {\n //for prorated, we have to deal with it differently; have to 'fill up' each\n //day with the standard amount before going to the next one\n double numWorkingDays = getCalendar().getWork(getStart(), getFinish(), TimeUnit.DAYS).getDuration();\n double standardAmountPerDay = getCost().doubleValue() / numWorkingDays;\n\n result.addAll(splitCostProrated(getCalendar(), actualCost, standardAmountPerDay, getActualStart()));\n }\n }\n\n return result;\n }" ]
Call with pathEntries lock taken
[ "private void getAllDependents(Set<PathEntry> result, String name) {\n Set<String> depNames = dependenctRelativePaths.get(name);\n if (depNames == null) {\n return;\n }\n for (String dep : depNames) {\n PathEntry entry = pathEntries.get(dep);\n if (entry != null) {\n result.add(entry);\n getAllDependents(result, dep);\n }\n }\n }" ]
[ "private void handleGetVersionResponse(SerialMessage incomingMessage) {\n\t\tthis.ZWaveLibraryType = incomingMessage.getMessagePayloadByte(12);\n\t\tthis.zWaveVersion = new String(ArrayUtils.subarray(incomingMessage.getMessagePayload(), 0, 11));\n\t\tlogger.debug(String.format(\"Got MessageGetVersion response. Version = %s, Library Type = 0x%02X\", zWaveVersion, ZWaveLibraryType));\n\t}", "public 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 }", "public void onSplashScreenCreated(GVRSceneObject splashScreen) {\n GVRTransform transform = splashScreen.getTransform();\n transform.setPosition(0, 0, DEFAULT_SPLASH_Z);\n }", "public double estimateExcludedVolumeFraction(){\n\t\t//Calculate volume/area of the of the scene without obstacles\n\t\tif(recalculateVolumeFraction){\n\t\t\tCentralRandomNumberGenerator r = CentralRandomNumberGenerator.getInstance();\n\t\t\tboolean firstRandomDraw = false;\n\t\t\tif(randomNumbers==null){\n\t\t\t\trandomNumbers = new double[nRandPoints*dimension];\n\t\t\t\tfirstRandomDraw = true;\n\t\t\t}\n\t\t\tint countCollision = 0;\n\t\t\tfor(int i = 0; i< nRandPoints; i++){\n\t\t\t\tdouble[] pos = new double[dimension];\n\t\t\t\tfor(int j = 0; j < dimension; j++){\n\t\t\t\t\tif(firstRandomDraw){\n\t\t\t\t\t\trandomNumbers[i*dimension + j] = r.nextDouble();\n\t\t\t\t\t}\n\t\t\t\t\tpos[j] = randomNumbers[i*dimension + j]*size[j];\n\t\t\t\t}\n\t\t\t\tif(checkCollision(pos)){\n\t\t\t\t\tcountCollision++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfraction = countCollision*1.0/nRandPoints;\n\t\t\trecalculateVolumeFraction = false;\n\t\t}\n\t\treturn fraction;\n\t}", "public static String fileNameClean(String s) {\r\n char[] chars = s.toCharArray();\r\n StringBuilder sb = new StringBuilder();\r\n for (char c : chars) {\r\n if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '_')) {\r\n sb.append(c);\r\n } else {\r\n if (c == ' ' || c == '-') {\r\n sb.append('_');\r\n } else {\r\n sb.append('x').append((int) c).append('x');\r\n }\r\n }\r\n }\r\n return sb.toString();\r\n }", "public void cache(Identity oid, Object obj)\r\n {\r\n try\r\n {\r\n jcsCache.put(oid.toString(), obj);\r\n }\r\n catch (CacheException e)\r\n {\r\n throw new RuntimeCacheException(e);\r\n }\r\n }", "protected void checkScopeAllowed() {\n if (ejbDescriptor.isStateless() && !isDependent()) {\n throw BeanLogger.LOG.scopeNotAllowedOnStatelessSessionBean(getScope(), getType());\n }\n if (ejbDescriptor.isSingleton() && !(isDependent() || getScope().equals(ApplicationScoped.class))) {\n throw BeanLogger.LOG.scopeNotAllowedOnSingletonBean(getScope(), getType());\n }\n }", "public final void setVolumeByIncrement(float level) throws IOException {\n Volume volume = this.getStatus().volume;\n float total = volume.level;\n\n if (volume.increment <= 0f) {\n throw new ChromeCastException(\"Volume.increment is <= 0\");\n }\n\n // With floating points we always have minor decimal variations, using the Math.min/max\n // works around this issue\n // Increase volume\n if (level > total) {\n while (total < level) {\n total = Math.min(total + volume.increment, level);\n setVolume(total);\n }\n // Decrease Volume\n } else if (level < total) {\n while (total > level) {\n total = Math.max(total - volume.increment, level);\n setVolume(total);\n }\n }\n }", "public void logAttributeWarning(PathAddress address, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, null, message, attributes));\n }" ]
Use this API to fetch snmpuser resource of given name .
[ "public static snmpuser get(nitro_service service, String name) throws Exception{\n\t\tsnmpuser obj = new snmpuser();\n\t\tobj.set_name(name);\n\t\tsnmpuser response = (snmpuser) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "public void setDefaults(Annotation[] defaultAnnotations) {\n if (defaultAnnotations == null) {\n return;\n }\n for (Annotation each : defaultAnnotations) {\n Class<? extends Annotation> key = each.annotationType();\n if (Title.class.equals(key) || Description.class.equals(key)) {\n continue;\n }\n if (!annotations.containsKey(key)) {\n annotations.put(key, each);\n }\n }\n }", "private void appendJoinSQL92(Join join, StringBuffer where, StringBuffer buf)\r\n {\r\n if (join.isOuter)\r\n {\r\n buf.append(\" LEFT OUTER JOIN \");\r\n }\r\n else\r\n {\r\n buf.append(\" INNER JOIN \");\r\n }\r\n if (join.right.hasJoins())\r\n {\r\n buf.append(\"(\");\r\n appendTableWithJoins(join.right, where, buf);\r\n buf.append(\")\");\r\n }\r\n else\r\n {\r\n appendTableWithJoins(join.right, where, buf);\r\n }\r\n buf.append(\" ON \");\r\n join.appendJoinEqualities(buf);\r\n }", "public DocumentReaderAndWriter<IN> makeReaderAndWriter() {\r\n DocumentReaderAndWriter<IN> readerAndWriter;\r\n try {\r\n readerAndWriter = ((DocumentReaderAndWriter<IN>)\r\n Class.forName(flags.readerAndWriter).newInstance());\r\n } catch (Exception e) {\r\n throw new RuntimeException(String.format(\"Error loading flags.readerAndWriter: '%s'\", flags.readerAndWriter), e);\r\n }\r\n readerAndWriter.init(flags);\r\n return readerAndWriter;\r\n }", "public static String formatAsStackTraceElement(InjectionPoint ij) {\n Member member;\n if (ij.getAnnotated() instanceof AnnotatedField) {\n AnnotatedField<?> annotatedField = (AnnotatedField<?>) ij.getAnnotated();\n member = annotatedField.getJavaMember();\n } else if (ij.getAnnotated() instanceof AnnotatedParameter<?>) {\n AnnotatedParameter<?> annotatedParameter = (AnnotatedParameter<?>) ij.getAnnotated();\n member = annotatedParameter.getDeclaringCallable().getJavaMember();\n } else {\n // Not throwing an exception, because this method is invoked when an exception is already being thrown.\n // Throwing an exception here would hide the original exception.\n return \"-\";\n }\n return formatAsStackTraceElement(member);\n }", "public JsonObject getJsonObject() {\n\n JsonObject obj = new JsonObject();\n obj.add(\"field\", this.field);\n\n obj.add(\"value\", this.value);\n\n return obj;\n }", "@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n protected void addStoreToSession(String store) {\n\n Exception initializationException = null;\n\n storeNames.add(store);\n\n for(Node node: nodesToStream) {\n\n SocketDestination destination = null;\n SocketAndStreams sands = null;\n\n try {\n destination = new SocketDestination(node.getHost(),\n node.getAdminPort(),\n RequestFormatType.ADMIN_PROTOCOL_BUFFERS);\n sands = streamingSocketPool.checkout(destination);\n DataOutputStream outputStream = sands.getOutputStream();\n DataInputStream inputStream = sands.getInputStream();\n\n nodeIdStoreToSocketRequest.put(new Pair(store, node.getId()), destination);\n nodeIdStoreToOutputStreamRequest.put(new Pair(store, node.getId()), outputStream);\n nodeIdStoreToInputStreamRequest.put(new Pair(store, node.getId()), inputStream);\n nodeIdStoreToSocketAndStreams.put(new Pair(store, node.getId()), sands);\n nodeIdStoreInitialized.put(new Pair(store, node.getId()), false);\n\n remoteStoreDefs = adminClient.metadataMgmtOps.getRemoteStoreDefList(node.getId())\n .getValue();\n\n } catch(Exception e) {\n logger.error(e);\n try {\n close(sands.getSocket());\n streamingSocketPool.checkin(destination, sands);\n } catch(Exception ioE) {\n logger.error(ioE);\n }\n\n if(!faultyNodes.contains(node.getId()))\n faultyNodes.add(node.getId());\n initializationException = e;\n }\n\n }\n\n if(initializationException != null)\n throw new VoldemortException(initializationException);\n\n if(store.equals(\"slop\"))\n return;\n\n boolean foundStore = false;\n\n for(StoreDefinition remoteStoreDef: remoteStoreDefs) {\n if(remoteStoreDef.getName().equals(store)) {\n RoutingStrategyFactory factory = new RoutingStrategyFactory();\n RoutingStrategy storeRoutingStrategy = factory.updateRoutingStrategy(remoteStoreDef,\n adminClient.getAdminClientCluster());\n\n storeToRoutingStrategy.put(store, storeRoutingStrategy);\n validateSufficientNodesAvailable(blackListedNodes, remoteStoreDef);\n foundStore = true;\n break;\n }\n }\n if(!foundStore) {\n logger.error(\"Store Name not found on the cluster\");\n throw new VoldemortException(\"Store Name not found on the cluster\");\n\n }\n\n }", "public void addFilter(Filter filter)\n {\n if (filter.isTaskFilter())\n {\n m_taskFilters.add(filter);\n }\n\n if (filter.isResourceFilter())\n {\n m_resourceFilters.add(filter);\n }\n\n m_filtersByName.put(filter.getName(), filter);\n m_filtersByID.put(filter.getID(), filter);\n }", "public void sendToTagged(String message, String ... labels) {\n for (String label : labels) {\n sendToTagged(message, label);\n }\n }", "private static String preparePlaceHolders(int length) {\n StringBuilder builder = new StringBuilder();\n for (int i = 0; i < length; ) {\n builder.append(\"?\");\n if (++i < length) {\n builder.append(\",\");\n }\n }\n return builder.toString();\n }" ]
Returns all methods for a specific group @param groupId group ID to remove methods from @param filters array of method types to filter by, null means no filter @return Collection of methods found @throws Exception exception
[ "public List<Method> getMethodsFromGroupId(int groupId, String[] filters) throws Exception {\n ArrayList<Method> methods = new ArrayList<Method>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_OVERRIDE +\n \" WHERE \" + Constants.OVERRIDE_GROUP_ID + \" = ?\"\n );\n statement.setInt(1, groupId);\n results = statement.executeQuery();\n while (results.next()) {\n Method method = PathOverrideService.getInstance().getMethodForOverrideId(results.getInt(\"id\"));\n if (method == null) {\n continue;\n }\n\n // decide whether or not to add this method based on the filters\n boolean add = true;\n if (filters != null) {\n add = false;\n for (String filter : filters) {\n if (method.getMethodType().endsWith(filter)) {\n add = true;\n break;\n }\n }\n }\n\n if (add && !methods.contains(method)) {\n methods.add(method);\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 (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return methods;\n }" ]
[ "public double computeLikelihoodP() {\n double ret = 1.0;\n\n for( int i = 0; i < r.numRows; i++ ) {\n double a = r.get(i,0);\n\n ret *= Math.exp(-a*a/2.0);\n }\n\n return ret;\n }", "private boolean evaluateLogicalOperator(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)\n {\n boolean result = false;\n\n if (m_criteriaList.size() == 0)\n {\n result = true;\n }\n else\n {\n for (GenericCriteria criteria : m_criteriaList)\n {\n result = criteria.evaluate(container, promptValues);\n if ((m_operator == TestOperator.AND && !result) || (m_operator == TestOperator.OR && result))\n {\n break;\n }\n }\n }\n\n return result;\n }", "public ServerSetup createCopy(String bindAddress) {\r\n ServerSetup setup = new ServerSetup(getPort(), bindAddress, getProtocol());\r\n setup.setServerStartupTimeout(getServerStartupTimeout());\r\n setup.setConnectionTimeout(getConnectionTimeout());\r\n setup.setReadTimeout(getReadTimeout());\r\n setup.setWriteTimeout(getWriteTimeout());\r\n setup.setVerbose(isVerbose());\r\n\r\n return setup;\r\n }", "@Override\n public Set<String> paramKeys() {\n Set<String> set = new HashSet<String>();\n set.addAll(C.<String>list(request.paramNames()));\n set.addAll(extraParams.keySet());\n set.addAll(bodyParams().keySet());\n set.remove(\"_method\");\n set.remove(\"_body\");\n return set;\n }", "public static base_response kill(nitro_service client, systemsession resource) throws Exception {\n\t\tsystemsession killresource = new systemsession();\n\t\tkillresource.sid = resource.sid;\n\t\tkillresource.all = resource.all;\n\t\treturn killresource.perform_operation(client,\"kill\");\n\t}", "private UserAlias getUserAlias(Object attribute)\r\n\t{\r\n\t\tif (m_userAlias != null)\r\n\t\t{\r\n\t\t\treturn m_userAlias;\r\n\t\t}\r\n\t\tif (!(attribute instanceof String))\r\n\t\t{\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tif (m_alias == null)\r\n\t\t{\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tif (m_aliasPath == null)\r\n\t\t{\r\n\t\t\tboolean allPathsAliased = true;\r\n\t\t\treturn new UserAlias(m_alias, (String)attribute, allPathsAliased);\r\n\t\t}\r\n\t\treturn new UserAlias(m_alias, (String)attribute, m_aliasPath);\r\n\t}", "private static void dumpRelationList(List<Relation> relations)\n {\n if (relations != null && relations.isEmpty() == false)\n {\n if (relations.size() > 1)\n {\n System.out.print('\"');\n }\n boolean first = true;\n for (Relation relation : relations)\n {\n if (!first)\n {\n System.out.print(',');\n }\n first = false;\n System.out.print(relation.getTargetTask().getID());\n Duration lag = relation.getLag();\n if (relation.getType() != RelationType.FINISH_START || lag.getDuration() != 0)\n {\n System.out.print(relation.getType());\n }\n\n if (lag.getDuration() != 0)\n {\n if (lag.getDuration() > 0)\n {\n System.out.print(\"+\");\n }\n System.out.print(lag);\n }\n }\n if (relations.size() > 1)\n {\n System.out.print('\"');\n }\n }\n }", "@Deprecated\n @SuppressWarnings(\"deprecation\")\n public void push(String eventName, HashMap<String, Object> chargeDetails,\n ArrayList<HashMap<String, Object>> items)\n throws InvalidEventNameException {\n // This method is for only charged events\n if (!eventName.equals(Constants.CHARGED_EVENT)) {\n throw new InvalidEventNameException(\"Not a charged event\");\n }\n CleverTapAPI cleverTapAPI = weakReference.get();\n if(cleverTapAPI == null){\n Logger.d(\"CleverTap Instance is null.\");\n } else {\n cleverTapAPI.pushChargedEvent(chargeDetails, items);\n }\n }", "public void applyTo(Context ctx, GradientDrawable drawable) {\n if (mColorInt != 0) {\n drawable.setColor(mColorInt);\n } else if (mColorRes != -1) {\n drawable.setColor(ContextCompat.getColor(ctx, mColorRes));\n }\n }" ]
we can't call this method 'of', cause it won't compile on JDK7
[ "public static <A extends Annotation> EnhancedAnnotation<A> create(SlimAnnotatedType<A> annotatedType, ClassTransformer classTransformer) {\n\n Class<A> annotationType = annotatedType.getJavaClass();\n\n Map<Class<? extends Annotation>, Annotation> annotationMap = new HashMap<Class<? extends Annotation>, Annotation>();\n annotationMap.putAll(buildAnnotationMap(annotatedType.getAnnotations()));\n annotationMap.putAll(buildAnnotationMap(classTransformer.getTypeStore().get(annotationType)));\n // Annotations and declared annotations are the same for annotation type\n return new EnhancedAnnotationImpl<A>(annotatedType, annotationMap, annotationMap, classTransformer);\n }" ]
[ "private String randomString(String[] s) {\n if (s == null || s.length <= 0) return \"\";\n return s[this.random.nextInt(s.length)];\n }", "public Token add( Symbol symbol ) {\n Token t = new Token(symbol);\n push( t );\n return t;\n }", "public static CuratorFramework newCurator(String zookeepers, int timeout, String secret) {\n\n final ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 10);\n if (secret.isEmpty()) {\n return CuratorFrameworkFactory.newClient(zookeepers, timeout, timeout, retry);\n } else {\n return CuratorFrameworkFactory.builder().connectString(zookeepers)\n .connectionTimeoutMs(timeout).sessionTimeoutMs(timeout).retryPolicy(retry)\n .authorization(\"digest\", (\"fluo:\" + secret).getBytes(StandardCharsets.UTF_8))\n .aclProvider(new ACLProvider() {\n @Override\n public List<ACL> getDefaultAcl() {\n return CREATOR_ALL_ACL;\n }\n\n @Override\n public List<ACL> getAclForPath(String path) {\n switch (path) {\n case ZookeeperPath.ORACLE_GC_TIMESTAMP:\n // The garbage collection iterator running in Accumulo tservers needs to read this\n // value w/o authenticating.\n return PUBLICLY_READABLE_ACL;\n default:\n return CREATOR_ALL_ACL;\n }\n }\n }).build();\n }\n }", "public static String getFailureDescriptionAsString(final ModelNode result) {\n if (isSuccessfulOutcome(result)) {\n return \"\";\n }\n final String msg;\n if (result.hasDefined(ClientConstants.FAILURE_DESCRIPTION)) {\n if (result.hasDefined(ClientConstants.OP)) {\n msg = String.format(\"Operation '%s' at address '%s' failed: %s\", result.get(ClientConstants.OP), result.get(ClientConstants.OP_ADDR), result\n .get(ClientConstants.FAILURE_DESCRIPTION));\n } else {\n msg = String.format(\"Operation failed: %s\", result.get(ClientConstants.FAILURE_DESCRIPTION));\n }\n } else {\n msg = String.format(\"An unexpected response was found checking the deployment. Result: %s\", result);\n }\n return msg;\n }", "public static void setFlag(Activity activity, final int bits, boolean on) {\n Window win = activity.getWindow();\n WindowManager.LayoutParams winParams = win.getAttributes();\n if (on) {\n winParams.flags |= bits;\n } else {\n winParams.flags &= ~bits;\n }\n win.setAttributes(winParams);\n }", "private synchronized Client allocateClient(int targetPlayer, String description) throws IOException {\n Client result = openClients.get(targetPlayer);\n if (result == null) {\n // We need to open a new connection.\n final DeviceAnnouncement deviceAnnouncement = DeviceFinder.getInstance().getLatestAnnouncementFrom(targetPlayer);\n if (deviceAnnouncement == null) {\n throw new IllegalStateException(\"Player \" + targetPlayer + \" could not be found \" + description);\n }\n final int dbServerPort = getPlayerDBServerPort(targetPlayer);\n if (dbServerPort < 0) {\n throw new IllegalStateException(\"Player \" + targetPlayer + \" does not have a db server \" + description);\n }\n\n final byte posingAsPlayerNumber = (byte) chooseAskingPlayerNumber(targetPlayer);\n\n Socket socket = null;\n try {\n InetSocketAddress address = new InetSocketAddress(deviceAnnouncement.getAddress(), dbServerPort);\n socket = new Socket();\n socket.connect(address, socketTimeout.get());\n socket.setSoTimeout(socketTimeout.get());\n result = new Client(socket, targetPlayer, posingAsPlayerNumber);\n } catch (IOException e) {\n try {\n socket.close();\n } catch (IOException e2) {\n logger.error(\"Problem closing socket for failed client creation attempt \" + description);\n }\n throw e;\n }\n openClients.put(targetPlayer, result);\n useCounts.put(result, 0);\n }\n useCounts.put(result, useCounts.get(result) + 1);\n return result;\n }", "@Override\n @Deprecated\n public List<CardWithActions> getBoardMemberActivity(String boardId, String memberId,\n String actionFilter, Argument... args) {\n if (actionFilter == null)\n actionFilter = \"all\";\n Argument[] argsAndFilter = Arrays.copyOf(args, args.length + 1);\n argsAndFilter[args.length] = new Argument(\"actions\", actionFilter);\n\n return asList(() -> get(createUrl(GET_BOARD_MEMBER_CARDS).params(argsAndFilter).asString(),\n CardWithActions[].class, boardId, memberId));\n }", "public void sendSyncModeCommand(int deviceNumber, boolean synced) throws IOException {\n final DeviceUpdate update = getLatestStatusFor(deviceNumber);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + deviceNumber + \" not found on network.\");\n }\n sendSyncModeCommand(update, synced);\n }", "@UiHandler(\"m_startTime\")\n void onStartTimeChange(CmsDateBoxEvent event) {\n\n if (handleChange() && !event.isUserTyping()) {\n m_controller.setStartTime(event.getDate());\n }\n }" ]
Sets a single element of this vector. Elements 0, 1, and 2 correspond to x, y, and z. @param i element index @param value element value @return element value throws ArrayIndexOutOfBoundsException if i is not in the range 0 to 2.
[ "public void set(int i, double value) {\n switch (i) {\n case 0: {\n x = value;\n break;\n }\n case 1: {\n y = value;\n break;\n }\n case 2: {\n z = value;\n break;\n }\n default: {\n throw new ArrayIndexOutOfBoundsException(i);\n }\n }\n }" ]
[ "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 static long addressToLong(InetAddress address) {\n long result = 0;\n for (byte element : address.getAddress()) {\n result = (result << 8) + unsign(element);\n }\n return result;\n }", "public static boolean isBigDecimal(CharSequence self) {\n try {\n new BigDecimal(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "public static HashMap<String, String> getMapFromJSONPath(JSONObject record, String path) {\n return getObjectFromJSONPath(record, path);\n }", "void applyFreshParticleOnScreen(\n @NonNull final Scene scene,\n final int position\n ) {\n final int w = scene.getWidth();\n final int h = scene.getHeight();\n if (w == 0 || h == 0) {\n throw new IllegalStateException(\n \"Cannot generate particles if scene width or height is 0\");\n }\n\n final double direction = Math.toRadians(random.nextInt(360));\n final float dCos = (float) Math.cos(direction);\n final float dSin = (float) Math.sin(direction);\n final float x = random.nextInt(w);\n final float y = random.nextInt(h);\n final float speedFactor = newRandomIndividualParticleSpeedFactor();\n final float radius = newRandomIndividualParticleRadius(scene);\n\n scene.setParticleData(\n position,\n x,\n y,\n dCos,\n dSin,\n radius,\n speedFactor);\n }", "public static Collection<String> getKnownPGPSecureRingLocations() {\n final LinkedHashSet<String> locations = new LinkedHashSet<String>();\n\n final String os = System.getProperty(\"os.name\");\n final boolean runOnWindows = os == null || os.toLowerCase().contains(\"win\");\n\n if (runOnWindows) {\n // The user's roaming profile on Windows, via environment\n final String windowsRoaming = System.getenv(\"APPDATA\");\n if (windowsRoaming != null) {\n locations.add(joinLocalPath(windowsRoaming, \"gnupg\", \"secring.gpg\"));\n }\n\n // The user's local profile on Windows, via environment\n final String windowsLocal = System.getenv(\"LOCALAPPDATA\");\n if (windowsLocal != null) {\n locations.add(joinLocalPath(windowsLocal, \"gnupg\", \"secring.gpg\"));\n }\n\n // The Windows installation directory\n final String windir = System.getProperty(\"WINDIR\");\n if (windir != null) {\n // Local Profile on Windows 98 and ME\n locations.add(joinLocalPath(windir, \"Application Data\", \"gnupg\", \"secring.gpg\"));\n }\n }\n\n final String home = System.getProperty(\"user.home\");\n\n if (home != null && runOnWindows) {\n // These are for various flavours of Windows\n // if the environment variables above have failed\n\n // Roaming profile on Vista and later\n locations.add(joinLocalPath(home, \"AppData\", \"Roaming\", \"gnupg\", \"secring.gpg\"));\n // Local profile on Vista and later\n locations.add(joinLocalPath(home, \"AppData\", \"Local\", \"gnupg\", \"secring.gpg\"));\n // Roaming profile on 2000 and XP\n locations.add(joinLocalPath(home, \"Application Data\", \"gnupg\", \"secring.gpg\"));\n // Local profile on 2000 and XP\n locations.add(joinLocalPath(home, \"Local Settings\", \"Application Data\", \"gnupg\", \"secring.gpg\"));\n }\n\n // *nix, including OS X\n if (home != null) {\n locations.add(joinLocalPath(home, \".gnupg\", \"secring.gpg\"));\n }\n\n return locations;\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 static AT_Row createContentRow(Object[] content, TableRowStyle style){\r\n\t\tValidate.notNull(content);\r\n\t\tValidate.notNull(style);\r\n\t\tValidate.validState(style!=TableRowStyle.UNKNOWN);\r\n\r\n\t\tLinkedList<AT_Cell> cells = new LinkedList<AT_Cell>();\r\n\t\tfor(Object o : content){\r\n\t\t\tcells.add(new AT_Cell(o));\r\n\t\t}\r\n\r\n\t\treturn new AT_Row(){\r\n\t\t\t@Override\r\n\t\t\tpublic TableRowType getType(){\r\n\t\t\t\treturn TableRowType.CONTENT;\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic TableRowStyle getStyle(){\r\n\t\t\t\treturn style;\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic LinkedList<AT_Cell> getCells(){\r\n\t\t\t\treturn cells;\r\n\t\t\t}\r\n\t\t};\r\n\t}", "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 }" ]
Invokes the ready tasks. @param context group level shared context that need be passed to {@link TaskGroupEntry#invokeTaskAsync(boolean, InvocationContext)} method of each entry in the group when it is selected for execution @return an observable that emits the result of tasks in the order they finishes.
[ "private Observable<Indexable> invokeReadyTasksAsync(final InvocationContext context) {\n TaskGroupEntry<TaskItem> readyTaskEntry = super.getNext();\n final List<Observable<Indexable>> observables = new ArrayList<>();\n // Enumerate the ready tasks (those with dependencies resolved) and kickoff them concurrently\n //\n while (readyTaskEntry != null) {\n final TaskGroupEntry<TaskItem> currentEntry = readyTaskEntry;\n final TaskItem currentTaskItem = currentEntry.data();\n if (currentTaskItem instanceof ProxyTaskItem) {\n observables.add(invokeAfterPostRunAsync(currentEntry, context));\n } else {\n observables.add(invokeTaskAsync(currentEntry, context));\n }\n readyTaskEntry = super.getNext();\n }\n return Observable.mergeDelayError(observables);\n }" ]
[ "public long queryForCountStar(DatabaseConnection databaseConnection) throws SQLException {\n\t\tif (countStarQuery == null) {\n\t\t\tStringBuilder sb = new StringBuilder(64);\n\t\t\tsb.append(\"SELECT COUNT(*) FROM \");\n\t\t\tdatabaseType.appendEscapedEntityName(sb, tableInfo.getTableName());\n\t\t\tcountStarQuery = sb.toString();\n\t\t}\n\t\tlong count = databaseConnection.queryForLong(countStarQuery);\n\t\tlogger.debug(\"query of '{}' returned {}\", countStarQuery, count);\n\t\treturn count;\n\t}", "public static ResourceKey key(Class<?> clazz, Enum<?> value) {\n return new ResourceKey(clazz.getName(), value.name());\n }", "public static Optional<Tag> parse(final String httpTag) {\r\n Tag result = null;\r\n boolean weak = false;\r\n String internal = httpTag;\r\n\r\n if (internal.startsWith(\"W/\")) {\r\n weak = true;\r\n internal = internal.substring(2);\r\n }\r\n\r\n if (internal.startsWith(\"\\\"\") && internal.endsWith(\"\\\"\")) {\r\n result = new Tag(\r\n internal.substring(1, internal.length() - 1), weak);\r\n }\r\n else if (internal.equals(\"*\")) {\r\n result = new Tag(\"*\", weak);\r\n }\r\n\r\n return Optional.ofNullable(result);\r\n }", "private void configureConfigurationSelector() {\n\n if (m_checkinBean.getConfigurations().size() < 2) {\n // Do not show the configuration selection at all.\n removeComponent(m_configurationSelectionPanel);\n } else {\n for (CmsGitConfiguration configuration : m_checkinBean.getConfigurations()) {\n m_configurationSelector.addItem(configuration);\n m_configurationSelector.setItemCaption(configuration, configuration.getName());\n }\n m_configurationSelector.setNullSelectionAllowed(false);\n m_configurationSelector.setNewItemsAllowed(false);\n m_configurationSelector.setWidth(\"350px\");\n m_configurationSelector.select(m_checkinBean.getCurrentConfiguration());\n\n // There is really a choice between configurations\n m_configurationSelector.addValueChangeListener(new ValueChangeListener() {\n\n private static final long serialVersionUID = 1L;\n\n @SuppressWarnings(\"synthetic-access\")\n public void valueChange(ValueChangeEvent event) {\n\n updateForNewConfiguration((CmsGitConfiguration)event.getProperty().getValue());\n restoreFieldsFromUserInfo();\n\n }\n });\n }\n }", "private void registerRequirement(RuntimeRequirementRegistration requirement) {\n assert writeLock.isHeldByCurrentThread();\n CapabilityId dependentId = requirement.getDependentId();\n if (!capabilities.containsKey(dependentId)) {\n throw ControllerLogger.MGMT_OP_LOGGER.unknownCapabilityInContext(dependentId.getName(),\n dependentId.getScope().getName());\n }\n Map<CapabilityId, Map<String, RuntimeRequirementRegistration>> requirementMap =\n requirement.isRuntimeOnly() ? runtimeOnlyRequirements : requirements;\n\n Map<String, RuntimeRequirementRegistration> dependents = requirementMap.get(dependentId);\n if (dependents == null) {\n dependents = new HashMap<>();\n requirementMap.put(dependentId, dependents);\n }\n RuntimeRequirementRegistration existing = dependents.get(requirement.getRequiredName());\n if (existing == null) {\n dependents.put(requirement.getRequiredName(), requirement);\n } else {\n existing.addRegistrationPoint(requirement.getOldestRegistrationPoint());\n }\n modified = true;\n }", "@Override\n public List<Revision> getMatrixHistory(final int start, final int limit) throws StoreException {\n return delegate.getMatrixHistory(start, limit);\n }", "private List<String> parseParams(String param) {\n\t\tAssert.hasText(param, \"param must not be empty nor null\");\n\t\tList<String> paramsToUse = new ArrayList<>();\n\t\tMatcher regexMatcher = DEPLOYMENT_PARAMS_PATTERN.matcher(param);\n\t\tint start = 0;\n\t\twhile (regexMatcher.find()) {\n\t\t\tString p = removeQuoting(param.substring(start, regexMatcher.start()).trim());\n\t\t\tif (StringUtils.hasText(p)) {\n\t\t\t\tparamsToUse.add(p);\n\t\t\t}\n\t\t\tstart = regexMatcher.start();\n\t\t}\n\t\tif (param != null && param.length() > 0) {\n\t\t\tString p = removeQuoting(param.substring(start, param.length()).trim());\n\t\t\tif (StringUtils.hasText(p)) {\n\t\t\t\tparamsToUse.add(p);\n\t\t\t}\n\t\t}\n\t\treturn paramsToUse;\n\t}", "public boolean isRunning(final ProcessorGraphNode processorGraphNode) {\n this.processorLock.lock();\n try {\n return this.runningProcessors.containsKey(processorGraphNode.getProcessor());\n } finally {\n this.processorLock.unlock();\n }\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}" ]
Use this API to add cmppolicylabel.
[ "public static base_response add(nitro_service client, cmppolicylabel resource) throws Exception {\n\t\tcmppolicylabel addresource = new cmppolicylabel();\n\t\taddresource.labelname = resource.labelname;\n\t\taddresource.type = resource.type;\n\t\treturn addresource.add_resource(client);\n\t}" ]
[ "public final B accessToken(String accessToken) {\n requireNonNull(accessToken, \"accessToken\");\n checkArgument(!accessToken.isEmpty(), \"accessToken is empty.\");\n this.accessToken = accessToken;\n return self();\n }", "public void run() {\r\n\t\tConnectionHandle connection = null;\r\n\t\tlong tmp;\r\n\t\tlong nextCheckInMs = this.maxAgeInMs;\r\n\r\n\t\tint partitionSize= this.partition.getAvailableConnections();\r\n\t\tlong currentTime = System.currentTimeMillis();\r\n\t\tfor (int i=0; i < partitionSize; i++){\r\n\t\t\ttry {\r\n\t\t\t\tconnection = this.partition.getFreeConnections().poll();\r\n\r\n\t\t\t\tif (connection != null){\r\n\t\t\t\t\tconnection.setOriginatingPartition(this.partition);\r\n\r\n\t\t\t\t\ttmp = this.maxAgeInMs - (currentTime - connection.getConnectionCreationTimeInMs()); \r\n\r\n\t\t\t\t\tif (tmp < nextCheckInMs){\r\n\t\t\t\t\t\tnextCheckInMs = tmp; \r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (connection.isExpired(currentTime)){\r\n\t\t\t\t\t\t// kill off this connection\r\n\t\t\t\t\t\tcloseConnection(connection);\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (this.lifoMode){\r\n\t\t\t\t\t\t// we can't put it back normally or it will end up in front again.\r\n\t\t\t\t\t\tif (!(connection.getOriginatingPartition().getFreeConnections().offer(connection))){\r\n\t\t\t\t\t\t\tconnection.internalClose();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tthis.pool.putConnectionBackInPartition(connection);\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\tThread.sleep(20L); // test slowly, this is not an operation that we're in a hurry to deal with (avoid CPU spikes)...\r\n\t\t\t\t}\r\n\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\tlogger.error(\"Connection max age thread exception.\", e);\r\n\t\t\t}\r\n\r\n\t\t} // throw it back on the queue\r\n\r\n\t}", "public void onDrawFrame(float frameTime)\n {\n if (!isEnabled() || (owner == null) || (getFloat(\"enabled\") <= 0.0f))\n {\n return;\n }\n float[] odir = getVec3(\"world_direction\");\n float[] opos = getVec3(\"world_position\");\n GVRSceneObject parent = owner;\n Matrix4f worldmtx = parent.getTransform().getModelMatrix4f();\n\n mOldDir.x = odir[0];\n mOldDir.y = odir[1];\n mOldDir.z = odir[2];\n mOldPos.x = opos[0];\n mOldPos.y = opos[1];\n mOldPos.z = opos[2];\n mNewDir.x = 0.0f;\n mNewDir.y = 0.0f;\n mNewDir.z = -1.0f;\n worldmtx.getTranslation(mNewPos);\n worldmtx.mul(mLightRot);\n worldmtx.transformDirection(mNewDir);\n if ((mOldDir.x != mNewDir.x) || (mOldDir.y != mNewDir.y) || (mOldDir.z != mNewDir.z))\n {\n setVec4(\"world_direction\", mNewDir.x, mNewDir.y, mNewDir.z, 0);\n }\n if ((mOldPos.x != mNewPos.x) || (mOldPos.y != mNewPos.y) || (mOldPos.z != mNewPos.z))\n {\n setPosition(mNewPos.x, mNewPos.y, mNewPos.z);\n }\n }", "public Response remove(DesignDocument designDocument) {\r\n assertNotEmpty(designDocument, \"DesignDocument\");\r\n ensureDesignPrefixObject(designDocument);\r\n return db.remove(designDocument);\r\n }", "public static List<String> getSelectOptionValues(CmsObject cms, String rootPath, boolean allRemoved) {\n\n try {\n cms = OpenCms.initCmsObject(cms);\n cms.getRequestContext().setSiteRoot(\"\");\n CmsADEConfigData adeConfig = OpenCms.getADEManager().lookupConfiguration(cms, rootPath);\n if (adeConfig.parent() != null) {\n adeConfig = adeConfig.parent();\n }\n\n List<CmsSelectWidgetOption> options = getFormatterOptionsStatic(cms, adeConfig, rootPath, allRemoved);\n List<CmsSelectWidgetOption> typeOptions = getTypeOptionsStatic(cms, adeConfig, allRemoved);\n options.addAll(typeOptions);\n List<String> result = new ArrayList<String>(options.size());\n for (CmsSelectWidgetOption o : options) {\n result.add(o.getValue());\n }\n return result;\n } catch (CmsException e) {\n // should never happen\n LOG.error(e.getLocalizedMessage(), e);\n return null;\n }\n\n }", "@Override\n\tpublic boolean isSinglePrefixBlock() {\n\t\tInteger networkPrefixLength = getNetworkPrefixLength();\n\t\tif(networkPrefixLength == null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn containsSinglePrefixBlock(networkPrefixLength);\n\t}", "public static void saveSvgFile(final SVGGraphics2D graphics2d, final File path) throws IOException {\n try (FileOutputStream fs = new FileOutputStream(path);\n OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fs, StandardCharsets.UTF_8);\n Writer osw = new BufferedWriter(outputStreamWriter)\n ) {\n graphics2d.stream(osw, true);\n }\n }", "public SqlStatement getPreparedUpdateStatement(ClassDescriptor cld)\r\n {\r\n SqlForClass sfc = getSqlForClass(cld);\r\n SqlStatement result = sfc.getUpdateSql();\r\n if(result == null)\r\n {\r\n ProcedureDescriptor pd = cld.getUpdateProcedure();\r\n\r\n if(pd == null)\r\n {\r\n result = new SqlUpdateStatement(cld, logger);\r\n }\r\n else\r\n {\r\n result = new SqlProcedureStatement(pd, logger);\r\n }\r\n // set the sql string\r\n sfc.setUpdateSql(result);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + result.getStatement());\r\n }\r\n }\r\n return result;\r\n }", "public Shard getShard(String docId) {\n assertNotEmpty(docId, \"docId\");\n return client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).path(\"_shards\")\n .path(docId).build(),\n Shard.class);\n }" ]
Computes the eigenvalue of the provided tridiagonal matrix. Note that only the upper portion needs to be tridiagonal. The bottom diagonal is assumed to be the same as the top. @param sideLength Number of rows and columns in the input matrix. @param diag Diagonal elements from tridiagonal matrix. Modified. @param off Off diagonal elements from tridiagonal matrix. Modified. @return true if it succeeds and false if it fails.
[ "public boolean process( int sideLength,\n double diag[] ,\n double off[] ,\n double eigenvalues[] ) {\n if( diag != null )\n helper.init(diag,off,sideLength);\n if( Q == null )\n Q = CommonOps_DDRM.identity(helper.N);\n helper.setQ(Q);\n\n this.followingScript = true;\n this.eigenvalues = eigenvalues;\n this.fastEigenvalues = false;\n\n return _process();\n }" ]
[ "public static List<Dependency> getCorporateDependencies(final Module module, final List<String> corporateFilters) {\n final List<Dependency> corporateDependencies = new ArrayList<Dependency>();\n final Pattern corporatePattern = generateCorporatePattern(corporateFilters);\n\n for(final Dependency dependency: getAllDependencies(module)){\n if(dependency.getTarget().getGavc().matches(corporatePattern.pattern())){\n corporateDependencies.add(dependency);\n }\n }\n\n return corporateDependencies;\n }", "public static String makePropertyName(String name) {\n char[] buf = new char[name.length() + 3];\n int pos = 0;\n buf[pos++] = 's';\n buf[pos++] = 'e';\n buf[pos++] = 't';\n\n for (int ix = 0; ix < name.length(); ix++) {\n char ch = name.charAt(ix);\n if (ix == 0)\n ch = Character.toUpperCase(ch);\n else if (ch == '-') {\n ix++;\n if (ix == name.length())\n break;\n ch = Character.toUpperCase(name.charAt(ix));\n }\n\n buf[pos++] = ch;\n }\n\n return new String(buf, 0, pos);\n }", "protected void recordPreparedOperation(final ServerIdentity identity, final TransactionalProtocolClient.PreparedOperation<ServerTaskExecutor.ServerOperation> prepared) {\n final ModelNode preparedResult = prepared.getPreparedResult();\n // Hmm do the server results need to get translated as well as the host one?\n // final ModelNode transformedResult = prepared.getOperation().transformResult(preparedResult);\n updatePolicy.recordServerResult(identity, preparedResult);\n executor.recordPreparedOperation(prepared);\n }", "public static int writeVint(byte[] dest, int offset, int i) {\n if (i >= -112 && i <= 127) {\n dest[offset++] = (byte) i;\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 dest[offset++] = (byte) len;\n\n len = (len < -120) ? -(len + 120) : -(len + 112);\n\n for (int idx = len; idx != 0; idx--) {\n int shiftbits = (idx - 1) * 8;\n long mask = 0xFFL << shiftbits;\n dest[offset++] = (byte) ((i & mask) >> shiftbits);\n }\n }\n\n return offset;\n }", "@Override\n public DiscordianDate date(int prolepticYear, int month, int dayOfMonth) {\n return DiscordianDate.of(prolepticYear, month, dayOfMonth);\n }", "public static String getDumpFileName(DumpContentType dumpContentType,\n\t\t\tString projectName, String dateStamp) {\n\t\tif (dumpContentType == DumpContentType.JSON) {\n\t\t\treturn dateStamp + WmfDumpFile.getDumpFilePostfix(dumpContentType);\n\t\t} else {\n\t\t\treturn projectName + \"-\" + dateStamp\n\t\t\t\t\t+ WmfDumpFile.getDumpFilePostfix(dumpContentType);\n\t\t}\n\t}", "@Override\n public final boolean has(final String key) {\n String result = this.obj.optString(key, null);\n return result != null;\n }", "private final void replyErrors(final String errorMessage,\n final String stackTrace, final String statusCode,\n final int statusCodeInt) {\n reply(true, errorMessage, stackTrace, statusCode, statusCodeInt,\n PcConstants.NA, null);\n\n }", "public void add(K key, V value) {\r\n if (treatCollectionsAsImmutable) {\r\n Collection<V> newC = cf.newCollection();\r\n Collection<V> c = map.get(key);\r\n if (c != null) {\r\n newC.addAll(c);\r\n }\r\n newC.add(value);\r\n map.put(key, newC); // replacing the old collection\r\n } else {\r\n Collection<V> c = map.get(key);\r\n if (c == null) {\r\n c = cf.newCollection();\r\n map.put(key, c);\r\n }\r\n c.add(value); // modifying the old collection\r\n }\r\n }" ]
Get the available sizes of a Photo. The boolean toggle allows to (api-)sign the call. This way the calling user can retrieve sizes for <b>his own</b> private photos. @param photoId The photo ID @param sign toggle to allow optionally signing the call (Authenticate) @return A collection of {@link Size} @throws FlickrException
[ "public Collection<Size> getSizes(String photoId, boolean sign) throws FlickrException {\r\n SizeList<Size> sizes = new SizeList<Size>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_SIZES);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element sizesElement = response.getPayload();\r\n sizes.setIsCanBlog(\"1\".equals(sizesElement.getAttribute(\"canblog\")));\r\n sizes.setIsCanDownload(\"1\".equals(sizesElement.getAttribute(\"candownload\")));\r\n sizes.setIsCanPrint(\"1\".equals(sizesElement.getAttribute(\"canprint\")));\r\n NodeList sizeNodes = sizesElement.getElementsByTagName(\"size\");\r\n for (int i = 0; i < sizeNodes.getLength(); i++) {\r\n Element sizeElement = (Element) sizeNodes.item(i);\r\n Size size = new Size();\r\n size.setLabel(sizeElement.getAttribute(\"label\"));\r\n size.setWidth(sizeElement.getAttribute(\"width\"));\r\n size.setHeight(sizeElement.getAttribute(\"height\"));\r\n size.setSource(sizeElement.getAttribute(\"source\"));\r\n size.setUrl(sizeElement.getAttribute(\"url\"));\r\n size.setMedia(sizeElement.getAttribute(\"media\"));\r\n sizes.add(size);\r\n }\r\n return sizes;\r\n }" ]
[ "private void addListeners(ProjectReader reader)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n reader.addProjectListener(listener);\n }\n }\n }", "public RandomVariable[] getValues(double[] times) {\n\t\tRandomVariable[] values = new RandomVariable[times.length];\n\n\t\tfor(int i=0; i<times.length; i++) {\n\t\t\tvalues[i] = getValue(null, times[i]);\n\t\t}\n\n\t\treturn values;\n\t}", "public static double Sinc(double x) {\r\n return Math.sin(Math.PI * x) / (Math.PI * x);\r\n }", "public void addRegexRoute(String urlPattern, Class<? extends Actor> actorClass) throws RouteAlreadyMappedException {\n addRoute(new Route(urlPattern, true), actorClass);\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 }", "public void forAllReferenceDefinitions(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getReferences(); it.hasNext(); )\r\n {\r\n _curReferenceDef = (ReferenceDescriptorDef)it.next();\r\n // first we check whether it is an inherited anonymous reference\r\n if (_curReferenceDef.isAnonymous() && (_curReferenceDef.getOwner() != _curClassDef))\r\n {\r\n continue;\r\n }\r\n if (!isFeatureIgnored(LEVEL_REFERENCE) &&\r\n !_curReferenceDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n generate(template);\r\n }\r\n }\r\n _curReferenceDef = null;\r\n }", "public App named(String name) {\n App newApp = copy();\n newApp.name = name;\n return newApp;\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<JulianDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<JulianDate>) super.zonedDateTime(temporal);\n }", "protected Model createFlattenedPom( File pomFile )\n throws MojoExecutionException, MojoFailureException\n {\n\n ModelBuildingRequest buildingRequest = createModelBuildingRequest( pomFile );\n Model effectivePom = createEffectivePom( buildingRequest, isEmbedBuildProfileDependencies(), this.flattenMode );\n\n Model flattenedPom = new Model();\n\n // keep original encoding (we could also normalize to UTF-8 here)\n String modelEncoding = effectivePom.getModelEncoding();\n if ( StringUtils.isEmpty( modelEncoding ) )\n {\n modelEncoding = \"UTF-8\";\n }\n flattenedPom.setModelEncoding( modelEncoding );\n\n Model cleanPom = createCleanPom( effectivePom );\n\n FlattenDescriptor descriptor = getFlattenDescriptor();\n Model originalPom = this.project.getOriginalModel();\n Model resolvedPom = this.project.getModel();\n Model interpolatedPom = createResolvedPom( buildingRequest );\n\n // copy the configured additional POM elements...\n\n for ( PomProperty<?> property : PomProperty.getPomProperties() )\n {\n if ( property.isElement() )\n {\n Model sourceModel = getSourceModel( descriptor, property, effectivePom, originalPom, resolvedPom,\n interpolatedPom, cleanPom );\n if ( sourceModel == null )\n {\n if ( property.isRequired() )\n {\n throw new MojoFailureException( \"Property \" + property.getName()\n + \" is required and can not be removed!\" );\n }\n }\n else\n {\n property.copy( sourceModel, flattenedPom );\n }\n }\n }\n\n return flattenedPom;\n }" ]
Calculate the name of the input value. @param inputPrefix a nullable prefix to prepend to the name if non-null and non-empty @param inputMapper the name mapper @param field the field containing the value
[ "public static String getInputValueName(\n @Nullable final String inputPrefix,\n @Nonnull final BiMap<String, String> inputMapper,\n @Nonnull final String field) {\n String name = inputMapper == null ? null : inputMapper.inverse().get(field);\n if (name == null) {\n if (inputMapper != null && inputMapper.containsKey(field)) {\n throw new RuntimeException(\"field in keys\");\n }\n final String[] defaultValues = {\n Values.TASK_DIRECTORY_KEY, Values.CLIENT_HTTP_REQUEST_FACTORY_KEY,\n Values.TEMPLATE_KEY, Values.PDF_CONFIG_KEY, Values.SUBREPORT_DIR_KEY,\n Values.OUTPUT_FORMAT_KEY, Values.JOB_ID_KEY\n };\n if (inputPrefix == null || Arrays.asList(defaultValues).contains(field)) {\n name = field;\n } else {\n name = inputPrefix.trim() +\n Character.toUpperCase(field.charAt(0)) +\n field.substring(1);\n }\n }\n return name;\n }" ]
[ "public void initialize() throws SQLException {\n\t\tif (initialized) {\n\t\t\t// just skip it if already initialized\n\t\t\treturn;\n\t\t}\n\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalStateException(\"connectionSource was never set on \" + getClass().getSimpleName());\n\t\t}\n\n\t\tdatabaseType = connectionSource.getDatabaseType();\n\t\tif (databaseType == null) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"connectionSource is getting a null DatabaseType in \" + getClass().getSimpleName());\n\t\t}\n\t\tif (tableConfig == null) {\n\t\t\ttableInfo = new TableInfo<T, ID>(databaseType, dataClass);\n\t\t} else {\n\t\t\ttableConfig.extractFieldTypes(databaseType);\n\t\t\ttableInfo = new TableInfo<T, ID>(databaseType, tableConfig);\n\t\t}\n\t\tstatementExecutor = new StatementExecutor<T, ID>(databaseType, tableInfo, this);\n\n\t\t/*\n\t\t * This is a bit complex. Initially, when we were configuring the field types, external DAO information would be\n\t\t * configured for auto-refresh, foreign BaseDaoEnabled classes, and foreign-collections. This would cause the\n\t\t * system to go recursive and for class loops, a stack overflow.\n\t\t * \n\t\t * Then we fixed this by putting a level counter in the FieldType constructor that would stop the configurations\n\t\t * when we reach some recursion level. But this created some bad problems because we were using the DaoManager\n\t\t * to cache the created DAOs that had been constructed already limited by the level.\n\t\t * \n\t\t * What we do now is have a 2 phase initialization. The constructor initializes most of the fields but then we\n\t\t * go back and call FieldType.configDaoInformation() after we are done. So for every DAO that is initialized\n\t\t * here, we have to see if it is the top DAO. If not we save it for dao configuration later.\n\t\t */\n\t\tList<BaseDaoImpl<?, ?>> daoConfigList = daoConfigLevelLocal.get();\n\t\tdaoConfigList.add(this);\n\t\tif (daoConfigList.size() > 1) {\n\t\t\t// if we have recursed then just save the dao for later configuration\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\t/*\n\t\t\t * WARNING: We do _not_ use an iterator here because we may be adding to the list as we process it and we'll\n\t\t\t * get exceptions otherwise. This is an ArrayList so the get(i) should be efficient.\n\t\t\t * \n\t\t\t * Also, do _not_ get a copy of daoConfigLevel.doArray because that array may be replaced by another, larger\n\t\t\t * one during the recursion.\n\t\t\t */\n\t\t\tfor (int i = 0; i < daoConfigList.size(); i++) {\n\t\t\t\tBaseDaoImpl<?, ?> dao = daoConfigList.get(i);\n\n\t\t\t\t/*\n\t\t\t\t * Here's another complex bit. The first DAO that is being constructed as part of a DAO chain is not yet\n\t\t\t\t * in the DaoManager cache. If we continue onward we might come back around and try to configure this\n\t\t\t\t * DAO again. Forcing it into the cache here makes sure it won't be configured twice. This will cause it\n\t\t\t\t * to be stuck in twice when it returns out to the DaoManager but that's a small price to pay. This also\n\t\t\t\t * applies to self-referencing classes.\n\t\t\t\t */\n\t\t\t\tDaoManager.registerDao(connectionSource, dao);\n\n\t\t\t\ttry {\n\t\t\t\t\t// config our fields which may go recursive\n\t\t\t\t\tfor (FieldType fieldType : dao.getTableInfo().getFieldTypes()) {\n\t\t\t\t\t\tfieldType.configDaoInformation(connectionSource, dao.getDataClass());\n\t\t\t\t\t}\n\t\t\t\t} catch (SQLException e) {\n\t\t\t\t\t// unregister the DAO we just pre-registered\n\t\t\t\t\tDaoManager.unregisterDao(connectionSource, dao);\n\t\t\t\t\tthrow e;\n\t\t\t\t}\n\n\t\t\t\t// it's now been fully initialized\n\t\t\t\tdao.initialized = true;\n\t\t\t}\n\t\t} finally {\n\t\t\t// if we throw we want to clear our class hierarchy here\n\t\t\tdaoConfigList.clear();\n\t\t\tdaoConfigLevelLocal.remove();\n\t\t}\n\t}", "public static base_responses enable(nitro_service client, String acl6name[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 enableresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tenableresources[i] = new nsacl6();\n\t\t\t\tenableresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, enableresources,\"enable\");\n\t\t}\n\t\treturn result;\n\t}", "public boolean isWorkingDay(Day day)\n {\n DayType value = getWorkingDay(day);\n boolean result;\n\n if (value == DayType.DEFAULT)\n {\n ProjectCalendar cal = getParent();\n if (cal != null)\n {\n result = cal.isWorkingDay(day);\n }\n else\n {\n result = (day != Day.SATURDAY && day != Day.SUNDAY);\n }\n }\n else\n {\n result = (value == DayType.WORKING);\n }\n\n return (result);\n }", "public void finished() throws Throwable {\n if( state == FINISHED ) {\n return;\n }\n\n State previousState = state;\n\n state = FINISHED;\n methodInterceptor.enableMethodInterception( false );\n\n try {\n if( previousState == STARTED ) {\n callFinishLifeCycleMethods();\n }\n } finally {\n listener.scenarioFinished();\n }\n }", "private void logOriginalResponseHistory(\n PluginResponse httpServletResponse, History history) throws URIException {\n RequestInformation requestInfo = requestInformation.get();\n if (requestInfo.handle && requestInfo.client.getIsActive()) {\n logger.info(\"Storing original response history\");\n history.setOriginalResponseHeaders(HttpUtilities.getHeaders(httpServletResponse));\n history.setOriginalResponseCode(Integer.toString(httpServletResponse.getStatus()));\n history.setOriginalResponseContentType(httpServletResponse.getContentType());\n history.setOriginalResponseData(httpServletResponse.getContentString());\n logger.info(\"Done storing\");\n }\n }", "@Override\n public boolean applyLayout(Layout itemLayout) {\n boolean applied = false;\n if (itemLayout != null && mItemLayouts.add(itemLayout)) {\n\n // apply the layout to all visible pages\n List<Widget> views = getAllViews();\n for (Widget view: views) {\n view.applyLayout(itemLayout.clone());\n }\n applied = true;\n }\n return applied;\n }", "private synchronized Response doAuthenticatedRequest(\n final StitchAuthRequest stitchReq,\n final AuthInfo authInfo\n ) {\n try {\n return requestClient.doRequest(prepareAuthRequest(stitchReq, authInfo));\n } catch (final StitchServiceException ex) {\n return handleAuthFailure(ex, stitchReq);\n }\n }", "public static base_response clear(nitro_service client, Interface resource) throws Exception {\n\t\tInterface clearresource = new Interface();\n\t\tclearresource.id = resource.id;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}", "static int[] toIntArray(List<Integer> integers) {\n\t\tint[] ints = new int[integers.size()];\n\t\tint i = 0;\n\t\tfor (Integer n : integers) {\n\t\t\tints[i++] = n;\n\t\t}\n\t\treturn ints;\n\t}" ]
Use this API to fetch all the cmpparameter resources that are configured on netscaler.
[ "public static cmpparameter get(nitro_service service) throws Exception{\n\t\tcmpparameter obj = new cmpparameter();\n\t\tcmpparameter[] response = (cmpparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}" ]
[ "private void handleArchiveByFile(Predicate<String> filter, File archive, List<String> discoveredFiles)\n {\n try\n {\n try (ZipFile zip = new ZipFile(archive))\n {\n Enumeration<? extends ZipEntry> entries = zip.entries();\n \n while (entries.hasMoreElements())\n {\n ZipEntry entry = entries.nextElement();\n String name = entry.getName();\n if (filter.accept(name))\n discoveredFiles.add(name);\n }\n }\n }\n catch (IOException e)\n {\n throw new RuntimeException(\"Error handling file \" + archive, e);\n }\n }", "public Object remove(String name) {\n\t\tBean bean = beans.get(name);\n\t\tif (null != bean) {\n\t\t\tbeans.remove(name);\n\t\t\tbean.destructionCallback.run();\n\t\t\treturn bean.object;\n\t\t}\n\t\treturn null;\n\t}", "public static spilloverpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tspilloverpolicy_stats obj = new spilloverpolicy_stats();\n\t\tobj.set_name(name);\n\t\tspilloverpolicy_stats response = (spilloverpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public static long getMaxIdForClass(\r\n PersistenceBroker brokerForClass, ClassDescriptor cldForOriginalOrExtent, FieldDescriptor original)\r\n throws PersistenceBrokerException\r\n {\r\n FieldDescriptor field = null;\r\n if (!original.getClassDescriptor().equals(cldForOriginalOrExtent))\r\n {\r\n // check if extent match not the same table\r\n if (!original.getClassDescriptor().getFullTableName().equals(\r\n cldForOriginalOrExtent.getFullTableName()))\r\n {\r\n // we have to look for id's in extent class table\r\n field = cldForOriginalOrExtent.getFieldDescriptorByName(original.getAttributeName());\r\n }\r\n }\r\n else\r\n {\r\n field = original;\r\n }\r\n if (field == null)\r\n {\r\n // if null skip this call\r\n return 0;\r\n }\r\n\r\n String column = field.getColumnName();\r\n long result = 0;\r\n ResultSet rs = null;\r\n Statement stmt = null;\r\n StatementManagerIF sm = brokerForClass.serviceStatementManager();\r\n String table = cldForOriginalOrExtent.getFullTableName();\r\n // String column = cld.getFieldDescriptorByName(fieldName).getColumnName();\r\n String sql = SM_SELECT_MAX + column + SM_FROM + table;\r\n try\r\n {\r\n //lookup max id for the current class\r\n stmt = sm.getGenericStatement(cldForOriginalOrExtent, Query.NOT_SCROLLABLE);\r\n rs = stmt.executeQuery(sql);\r\n rs.next();\r\n result = rs.getLong(1);\r\n }\r\n catch (Exception e)\r\n {\r\n log.warn(\"Cannot lookup max value from table \" + table + \" for column \" + column +\r\n \", PB was \" + brokerForClass + \", using jdbc-descriptor \" +\r\n brokerForClass.serviceConnectionManager().getConnectionDescriptor(), e);\r\n }\r\n finally\r\n {\r\n try\r\n {\r\n sm.closeResources(stmt, rs);\r\n }\r\n catch (Exception ignore)\r\n {\r\n // ignore it\r\n }\r\n }\r\n return result;\r\n }", "public void ifHasMemberWithTag(String template, Properties attributes) throws XDocletException\r\n {\r\n ArrayList allMemberNames = new ArrayList();\r\n HashMap allMembers = new HashMap();\r\n boolean hasTag = false;\r\n\r\n addMembers(allMemberNames, allMembers, getCurrentClass(), null, null, null);\r\n for (Iterator it = allMemberNames.iterator(); it.hasNext(); ) {\r\n XMember member = (XMember) allMembers.get(it.next());\r\n\r\n if (member instanceof XField) {\r\n setCurrentField((XField)member);\r\n if (hasTag(attributes, FOR_FIELD)) {\r\n hasTag = true;\r\n }\r\n setCurrentField(null);\r\n }\r\n else if (member instanceof XMethod) {\r\n setCurrentMethod((XMethod)member);\r\n if (hasTag(attributes, FOR_METHOD)) {\r\n hasTag = true;\r\n }\r\n setCurrentMethod(null);\r\n }\r\n if (hasTag) {\r\n generate(template);\r\n break;\r\n }\r\n }\r\n }", "public void setDefaults(Annotation[] defaultAnnotations) {\n if (defaultAnnotations == null) {\n return;\n }\n for (Annotation each : defaultAnnotations) {\n Class<? extends Annotation> key = each.annotationType();\n if (Title.class.equals(key) || Description.class.equals(key)) {\n continue;\n }\n if (!annotations.containsKey(key)) {\n annotations.put(key, each);\n }\n }\n }", "public static dnsview_binding get(nitro_service service, String viewname) throws Exception{\n\t\tdnsview_binding obj = new dnsview_binding();\n\t\tobj.set_viewname(viewname);\n\t\tdnsview_binding response = (dnsview_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void writeNotes(int recordNumber, String text) throws IOException\n {\n m_buffer.setLength(0);\n\n m_buffer.append(recordNumber);\n m_buffer.append(m_delimiter);\n\n if (text != null)\n {\n String note = stripLineBreaks(text, MPXConstants.EOL_PLACEHOLDER_STRING);\n boolean quote = (note.indexOf(m_delimiter) != -1 || note.indexOf('\"') != -1);\n int length = note.length();\n char c;\n\n if (quote == true)\n {\n m_buffer.append('\"');\n }\n\n for (int loop = 0; loop < length; loop++)\n {\n c = note.charAt(loop);\n\n switch (c)\n {\n case '\"':\n {\n m_buffer.append(\"\\\"\\\"\");\n break;\n }\n\n default:\n {\n m_buffer.append(c);\n break;\n }\n }\n }\n\n if (quote == true)\n {\n m_buffer.append('\"');\n }\n }\n\n m_buffer.append(MPXConstants.EOL);\n\n m_writer.write(m_buffer.toString());\n }", "private void readCalendars(Project ganttProject)\n {\n m_mpxjCalendar = m_projectFile.addCalendar();\n m_mpxjCalendar.setName(ProjectCalendar.DEFAULT_BASE_CALENDAR_NAME);\n\n Calendars gpCalendar = ganttProject.getCalendars();\n setWorkingDays(m_mpxjCalendar, gpCalendar);\n setExceptions(m_mpxjCalendar, gpCalendar);\n m_eventManager.fireCalendarReadEvent(m_mpxjCalendar);\n }" ]
Writes the buffer contents to the given byte channel. @param channel @throws IOException
[ "public void writeTo(WritableByteChannel channel) throws IOException {\n for (ByteBuffer buffer : toDirectByteBuffers()) {\n channel.write(buffer);\n }\n }" ]
[ "public void setBean(String name, Object object) {\n\t\tBean bean = beans.get(name);\n\t\tif (null == bean) {\n\t\t\tbean = new Bean();\n\t\t\tbeans.put(name, bean);\n\t\t}\n\t\tbean.object = object;\n\t}", "protected boolean computeOffset(CacheDataSet cache) {\n // offset computation: update offset for all items in the cache\n float startDataOffset = getStartingOffset((cache.getTotalSizeWithPadding()));\n float layoutOffset = getLayoutOffset();\n\n boolean inBounds = startDataOffset < -layoutOffset;\n\n for (int pos = 0; pos < cache.count(); ++pos) {\n int id = cache.getId(pos);\n if (id != -1) {\n float endDataOffset = cache.setDataAfter(id, startDataOffset);\n inBounds = inBounds &&\n endDataOffset > layoutOffset &&\n startDataOffset < -layoutOffset;\n startDataOffset = endDataOffset;\n Log.d(LAYOUT, TAG, \"computeOffset [%d] = %f\" , id, cache.getDataOffset(id));\n }\n }\n\n return inBounds;\n }", "public void startScenario( Class<?> testClass, Method method, List<NamedArgument> arguments ) {\n listener.scenarioStarted( testClass, method, arguments );\n\n if( method.isAnnotationPresent( Pending.class ) ) {\n Pending annotation = method.getAnnotation( Pending.class );\n\n if( annotation.failIfPass() ) {\n failIfPass();\n } else if( !annotation.executeSteps() ) {\n methodInterceptor.disableMethodExecution();\n executeLifeCycleMethods = false;\n }\n suppressExceptions = true;\n } else if( method.isAnnotationPresent( NotImplementedYet.class ) ) {\n NotImplementedYet annotation = method.getAnnotation( NotImplementedYet.class );\n\n if( annotation.failIfPass() ) {\n failIfPass();\n } else if( !annotation.executeSteps() ) {\n methodInterceptor.disableMethodExecution();\n executeLifeCycleMethods = false;\n }\n suppressExceptions = true;\n }\n\n }", "private void readPage(byte[] buffer, Table table)\n {\n int magicNumber = getShort(buffer, 0);\n if (magicNumber == 0x4400)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, 0, 6, true, 16, \"\"));\n int recordSize = m_definition.getRecordSize();\n RowValidator rowValidator = m_definition.getRowValidator();\n String primaryKeyColumnName = m_definition.getPrimaryKeyColumnName();\n\n int index = 6;\n while (index + recordSize <= buffer.length)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, index, recordSize, true, 16, \"\"));\n int btrieveValue = getShort(buffer, index);\n if (btrieveValue != 0)\n {\n Map<String, Object> row = new HashMap<String, Object>();\n row.put(\"ROW_VERSION\", Integer.valueOf(btrieveValue));\n for (ColumnDefinition column : m_definition.getColumns())\n {\n Object value = column.read(index, buffer);\n //System.out.println(column.getName() + \": \" + value);\n row.put(column.getName(), value);\n }\n\n if (rowValidator == null || rowValidator.validRow(row))\n {\n table.addRow(primaryKeyColumnName, row);\n }\n }\n index += recordSize;\n }\n }\n }", "public void addBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final boolean statementBatchingSupported = m_batchStatementsInProgress.containsKey(stmt);\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n stmt.executeUpdate();\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PlatformException(e.getLocalizedMessage(), e);\r\n }\r\n }\r\n else\r\n {\r\n super.addBatch(stmt);\r\n }\r\n }", "public URI withEmptyAuthority(final URI uri) {\n URI _xifexpression = null;\n if ((uri.isFile() && (uri.authority() == null))) {\n _xifexpression = URI.createHierarchicalURI(uri.scheme(), \"\", uri.device(), uri.segments(), uri.query(), uri.fragment());\n } else {\n _xifexpression = uri;\n }\n return _xifexpression;\n }", "private void initModeSwitch(final EditMode current) {\n\n FormLayout modes = new FormLayout();\n modes.setHeight(\"100%\");\n modes.setDefaultComponentAlignment(Alignment.MIDDLE_LEFT);\n\n m_modeSelect = new ComboBox();\n m_modeSelect.setCaption(m_messages.key(Messages.GUI_VIEW_SWITCHER_LABEL_0));\n\n // add Modes\n m_modeSelect.addItem(CmsMessageBundleEditorTypes.EditMode.DEFAULT);\n m_modeSelect.setItemCaption(\n CmsMessageBundleEditorTypes.EditMode.DEFAULT,\n m_messages.key(Messages.GUI_VIEW_SWITCHER_EDITMODE_DEFAULT_0));\n m_modeSelect.addItem(CmsMessageBundleEditorTypes.EditMode.MASTER);\n m_modeSelect.setItemCaption(\n CmsMessageBundleEditorTypes.EditMode.MASTER,\n m_messages.key(Messages.GUI_VIEW_SWITCHER_EDITMODE_MASTER_0));\n\n // set current mode as selected\n m_modeSelect.setValue(current);\n\n m_modeSelect.setNewItemsAllowed(false);\n m_modeSelect.setTextInputAllowed(false);\n m_modeSelect.setNullSelectionAllowed(false);\n\n m_modeSelect.addValueChangeListener(new ValueChangeListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void valueChange(ValueChangeEvent event) {\n\n m_listener.handleModeChange((EditMode)event.getProperty().getValue());\n\n }\n });\n\n modes.addComponent(m_modeSelect);\n m_modeSwitch = modes;\n }", "private void populateCalendarException(Record record, ProjectCalendar calendar) throws MPXJException\n {\n Date fromDate = record.getDate(0);\n Date toDate = record.getDate(1);\n boolean working = record.getNumericBoolean(2);\n\n // I have found an example MPX file where a single day exception is expressed with just the start date set.\n // If we find this for we assume that the end date is the same as the start date.\n if (fromDate != null && toDate == null)\n {\n toDate = fromDate;\n }\n\n ProjectCalendarException exception = calendar.addCalendarException(fromDate, toDate);\n if (working)\n {\n addExceptionRange(exception, record.getTime(3), record.getTime(4));\n addExceptionRange(exception, record.getTime(5), record.getTime(6));\n addExceptionRange(exception, record.getTime(7), record.getTime(8));\n }\n }", "private static Properties loadGradleProperties(FilePath gradlePropertiesFilePath)\n throws IOException, InterruptedException {\n return gradlePropertiesFilePath.act(new MasterToSlaveFileCallable<Properties>() {\n public Properties invoke(File gradlePropertiesFile, VirtualChannel channel) throws IOException, InterruptedException {\n Properties gradleProps = new Properties();\n if (gradlePropertiesFile.exists()) {\n debuggingLogger.fine(\"Gradle properties file exists at: \" + gradlePropertiesFile.getAbsolutePath());\n FileInputStream stream = null;\n try {\n stream = new FileInputStream(gradlePropertiesFile);\n gradleProps.load(stream);\n } catch (IOException e) {\n debuggingLogger.fine(\"IO exception occurred while trying to read properties file from: \" +\n gradlePropertiesFile.getAbsolutePath());\n throw new RuntimeException(e);\n } finally {\n IOUtils.closeQuietly(stream);\n }\n }\n return gradleProps;\n }\n });\n\n }" ]
Helper method to create a Dao object without having to define a class. Dao classes are supposed to be convenient but if you have a lot of classes, they can seem to be a pain. <p> <b>NOTE:</b> You should use {@link DaoManager#createDao(ConnectionSource, DatabaseTableConfig)} instead of this method so you won't have to create the DAO multiple times. </p>
[ "static <T, ID> Dao<T, ID> createDao(ConnectionSource connectionSource, Class<T> clazz) throws SQLException {\n\t\treturn new BaseDaoImpl<T, ID>(connectionSource, clazz) {\n\t\t};\n\t}" ]
[ "public void setAllowBlank(boolean allowBlank) {\n this.allowBlank = allowBlank;\n\n // Setup the allow blank validation\n if (!allowBlank) {\n if (blankValidator == null) {\n blankValidator = createBlankValidator();\n }\n setupBlurValidation();\n addValidator(blankValidator);\n } else {\n removeValidator(blankValidator);\n }\n }", "public AT_Row setCharTranslator(CharacterTranslator charTranslator) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setCharTranslator(charTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public int getCostRateTableIndex()\n {\n Integer value = (Integer) getCachedValue(AssignmentField.COST_RATE_TABLE);\n return value == null ? 0 : value.intValue();\n }", "public static base_response Shutdown(nitro_service client, shutdown resource) throws Exception {\n\t\tshutdown Shutdownresource = new shutdown();\n\t\treturn Shutdownresource.perform_operation(client);\n\t}", "public static base_responses clear(nitro_service client, route6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\troute6 clearresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tclearresources[i] = new route6();\n\t\t\t\tclearresources[i].routetype = resources[i].routetype;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, clearresources,\"clear\");\n\t\t}\n\t\treturn result;\n\t}", "private static URI createSvg(\n final Dimension targetSize,\n final RasterReference rasterReference, final Double rotation,\n final Color backgroundColor, final File workingDir)\n throws IOException {\n // load SVG graphic\n final SVGElement svgRoot = parseSvg(rasterReference.inputStream);\n\n // create a new SVG graphic in which the existing graphic is embedded (scaled and rotated)\n DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();\n Document newDocument = impl.createDocument(SVG_NS, \"svg\", null);\n SVGElement newSvgRoot = (SVGElement) newDocument.getDocumentElement();\n newSvgRoot.setAttributeNS(null, \"width\", Integer.toString(targetSize.width));\n newSvgRoot.setAttributeNS(null, \"height\", Integer.toString(targetSize.height));\n\n setSvgBackground(backgroundColor, targetSize, newDocument, newSvgRoot);\n embedSvgGraphic(svgRoot, newSvgRoot, newDocument, targetSize, rotation);\n File path = writeSvgToFile(newDocument, workingDir);\n\n return path.toURI();\n }", "public void appendImmediate(Object object, String indentation) {\n\t\tfor (int i = segments.size() - 1; i >= 0; i--) {\n\t\t\tString segment = segments.get(i);\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\tappend(object, indentation, i + 1);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tappend(object, indentation, 0);\n\t}", "public HttpServer build() {\n checkNotNull(baseUri);\n StandaloneWebConverterConfiguration configuration = makeConfiguration();\n // The configuration has to be configured both by a binder to make it injectable\n // and directly in order to trigger life cycle methods on the deployment container.\n ResourceConfig resourceConfig = ResourceConfig\n .forApplication(new WebConverterApplication(configuration))\n .register(configuration);\n if (sslContext == null) {\n return GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig);\n } else {\n return GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig, true, new SSLEngineConfigurator(sslContext));\n }\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 }" ]
Print formatted string in the center of 80 chars line, left and right padded. @param format The string format pattern @param args The string format arguments
[ "protected void printCenter(String format, Object... args) {\n String text = S.fmt(format, args);\n info(S.center(text, 80));\n }" ]
[ "public static NodeList evaluateXpathExpression(String domStr, String xpathExpr)\n\t\t\tthrows XPathExpressionException, IOException {\n\t\tDocument dom = DomUtils.asDocument(domStr);\n\t\treturn evaluateXpathExpression(dom, xpathExpr);\n\t}", "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 synchronized Message menuRequestTyped(Message.KnownType requestType, Message.MenuIdentifier targetMenu,\n CdjStatus.TrackSourceSlot slot, CdjStatus.TrackType trackType, Field... arguments)\n throws IOException {\n\n if (!menuLock.isHeldByCurrentThread()) {\n throw new IllegalStateException(\"renderMenuItems() cannot be called without first successfully calling tryLockingForMenuOperation()\");\n }\n\n Field[] combinedArguments = new Field[arguments.length + 1];\n combinedArguments[0] = buildRMST(targetMenu, slot, trackType);\n System.arraycopy(arguments, 0, combinedArguments, 1, arguments.length);\n final Message response = simpleRequest(requestType, Message.KnownType.MENU_AVAILABLE, combinedArguments);\n final NumberField reportedRequestType = (NumberField)response.arguments.get(0);\n if (reportedRequestType.getValue() != requestType.protocolValue) {\n throw new IOException(\"Menu request did not return result for same type as request; sent type: \" +\n requestType.protocolValue + \", received type: \" + reportedRequestType.getValue() +\n \", response: \" + response);\n }\n return response;\n }", "private void processBaseFonts(byte[] data)\n {\n int offset = 0;\n\n int blockCount = MPPUtility.getShort(data, 0);\n offset += 2;\n\n int size;\n String name;\n\n for (int loop = 0; loop < blockCount; loop++)\n {\n /*unknownAttribute = MPPUtility.getShort(data, offset);*/\n offset += 2;\n\n size = MPPUtility.getShort(data, offset);\n offset += 2;\n\n name = MPPUtility.getUnicodeString(data, offset);\n offset += 64;\n\n if (name.length() != 0)\n {\n FontBase fontBase = new FontBase(Integer.valueOf(loop), name, size);\n m_fontBases.put(fontBase.getIndex(), fontBase);\n }\n }\n }", "private OAuth1RequestToken constructToken(Response response) {\r\n Element authElement = response.getPayload();\r\n String oauthToken = XMLUtilities.getChildValue(authElement, \"oauth_token\");\r\n String oauthTokenSecret = XMLUtilities.getChildValue(authElement, \"oauth_token_secret\");\r\n\r\n OAuth1RequestToken token = new OAuth1RequestToken(oauthToken, oauthTokenSecret);\r\n return token;\r\n }", "public static String resolveProxyUrl(String relativeUrl, TileMap tileMap, String baseTmsUrl) {\n\t\tTileCode tc = parseTileCode(relativeUrl);\n\t\treturn buildUrl(tc, tileMap, baseTmsUrl);\n\t}", "public void setHomeAsUpIndicator(Drawable indicator) {\n if(!deviceSupportMultiPane()) {\n pulsante.setHomeAsUpIndicator(indicator);\n }\n else {\n actionBar.setHomeAsUpIndicator(indicator);\n }\n }", "private void addHours(ProjectCalendarDateRanges ranges, Record hoursRecord)\n {\n if (hoursRecord.getValue() != null)\n {\n String[] wh = hoursRecord.getValue().split(\"\\\\|\");\n try\n {\n String startText;\n String endText;\n\n if (wh[0].equals(\"s\"))\n {\n startText = wh[1];\n endText = wh[3];\n }\n else\n {\n startText = wh[3];\n endText = wh[1];\n }\n\n // for end time treat midnight as midnight next day\n if (endText.equals(\"00:00\"))\n {\n endText = \"24:00\";\n }\n Date start = m_calendarTimeFormat.parse(startText);\n Date end = m_calendarTimeFormat.parse(endText);\n\n ranges.addRange(new DateRange(start, end));\n }\n catch (ParseException e)\n {\n // silently ignore date parse exceptions\n }\n }\n }", "public void writeTagsToJavaScript(Writer writer) throws IOException\n {\n writer.append(\"function fillTagService(tagService) {\\n\");\n writer.append(\"\\t// (name, isPrime, isPseudo, color), [parent tags]\\n\");\n for (Tag tag : definedTags.values())\n {\n writer.append(\"\\ttagService.registerTag(new Tag(\");\n escapeOrNull(tag.getName(), writer);\n writer.append(\", \");\n escapeOrNull(tag.getTitle(), writer);\n writer.append(\", \").append(\"\" + tag.isPrime())\n .append(\", \").append(\"\" + tag.isPseudo())\n .append(\", \");\n escapeOrNull(tag.getColor(), writer);\n writer.append(\")\").append(\", [\");\n\n // We only have strings, not references, so we're letting registerTag() getOrCreate() the tag.\n for (Tag parentTag : tag.getParentTags())\n {\n writer.append(\"'\").append(StringEscapeUtils.escapeEcmaScript(parentTag.getName())).append(\"',\");\n }\n writer.append(\"]);\\n\");\n }\n writer.append(\"}\\n\");\n }" ]
Set cached value for the attribute. Used for dynamically loaded values in the Acacia content editor. @param attribute the attribute for which the value should be cached @param value the value to cache
[ "public void setDynamicValue(String attribute, String value) {\n\n if (null == m_dynamicValues) {\n m_dynamicValues = new ConcurrentHashMap<String, String>();\n }\n m_dynamicValues.put(attribute, value);\n }" ]
[ "private static void createDirectory(Path path) throws IOException {\n\t\ttry {\n\t\t\tFiles.createDirectory(path);\n\t\t} catch (FileAlreadyExistsException e) {\n\t\t\tif (!Files.isDirectory(path)) {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t}", "public base_response enable_features(String[] features) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsfeature resource = new nsfeature();\n\t\tresource.set_feature(features);\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}", "protected void closeServerSocket() {\n // Close server socket, we do not accept new requests anymore.\n // This also terminates the server thread if blocking on socket.accept.\n if (null != serverSocket) {\n try {\n if (!serverSocket.isClosed()) {\n serverSocket.close();\n if (log.isTraceEnabled()) {\n log.trace(\"Closed server socket \" + serverSocket + \"/ref=\"\n + Integer.toHexString(System.identityHashCode(serverSocket))\n + \" for \" + getName());\n }\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Failed to successfully quit server \" + getName(), e);\n }\n }\n }", "public static String frame(String imageUrl) {\n if (imageUrl == null || imageUrl.length() == 0) {\n throw new IllegalArgumentException(\"Image URL must not be blank.\");\n }\n return FILTER_FRAME + \"(\" + imageUrl + \")\";\n }", "public void createNamespace() {\n Map<String, String> namespaceAnnotations = annotationProvider.create(session.getId(), Constants.RUNNING_STATUS);\n if (namespaceService.exists(session.getNamespace())) {\n //namespace exists\n } else if (configuration.isNamespaceLazyCreateEnabled()) {\n namespaceService.create(session.getNamespace(), namespaceAnnotations);\n } else {\n throw new IllegalStateException(\"Namespace [\" + session.getNamespace() + \"] doesn't exist and lazily creation of namespaces is disabled. \"\n + \"Either use an existing one, or set `namespace.lazy.enabled` to true.\");\n }\n }", "protected void destroyConnection(ConnectionHandle conn) {\r\n\t\tpostDestroyConnection(conn);\r\n\t\tconn.setInReplayMode(true); // we're dead, stop attempting to replay anything\r\n\t\ttry {\r\n\t\t\t\tconn.internalClose();\r\n\t\t} catch (SQLException e) {\r\n\t\t\tlogger.error(\"Error in attempting to close connection\", e);\r\n\t\t}\r\n\t}", "private String getOrdinal(Integer value)\n {\n String result;\n int index = value.intValue();\n if (index >= ORDINAL.length)\n {\n result = \"every \" + index + \"th\";\n }\n else\n {\n result = ORDINAL[index];\n }\n return result;\n }", "public List<MapRow> readTableConditional(Class<? extends TableReader> readerClass) throws IOException\n {\n List<MapRow> result;\n if (DatatypeConverter.getBoolean(m_stream))\n {\n result = readTable(readerClass);\n }\n else\n {\n result = Collections.emptyList();\n }\n return result;\n }", "public void execute() throws MojoExecutionException, MojoFailureException {\n try {\n Set<File> thriftFiles = findThriftFiles();\n\n final File outputDirectory = getOutputDirectory();\n ImmutableSet<File> outputFiles = findGeneratedFilesInDirectory(getOutputDirectory());\n\n Set<String> compileRoots = new HashSet<String>();\n compileRoots.add(\"scrooge\");\n\n if (thriftFiles.isEmpty()) {\n getLog().info(\"No thrift files to compile.\");\n } else if (checkStaleness && ((lastModified(thriftFiles) + staleMillis) < lastModified(outputFiles))) {\n getLog().info(\"Generated thrift files up to date, skipping compile.\");\n attachFiles(compileRoots);\n } else {\n outputDirectory.mkdirs();\n\n // Quick fix to fix issues with two mvn installs in a row (ie no clean)\n cleanDirectory(outputDirectory);\n\n getLog().info(format(\"compiling thrift files %s with Scrooge\", thriftFiles));\n synchronized(lock) {\n ScroogeRunner runner = new ScroogeRunner();\n Map<String, String> thriftNamespaceMap = new HashMap<String, String>();\n for (ThriftNamespaceMapping mapping : thriftNamespaceMappings) {\n thriftNamespaceMap.put(mapping.getFrom(), mapping.getTo());\n }\n\n // Include thrifts from resource as well.\n Set<File> includes = thriftIncludes;\n includes.add(getResourcesOutputDirectory());\n\n // Include thrift root\n final File thriftSourceRoot = getThriftSourceRoot();\n if (thriftSourceRoot != null && thriftSourceRoot.exists()) {\n includes.add(thriftSourceRoot);\n }\n\n runner.compile(\n getLog(),\n includeOutputDirectoryNamespace ? new File(outputDirectory, \"scrooge\") : outputDirectory,\n thriftFiles,\n includes,\n thriftNamespaceMap,\n language,\n thriftOpts);\n }\n attachFiles(compileRoots);\n }\n } catch (IOException e) {\n throw new MojoExecutionException(\"An IO error occurred\", e);\n }\n }" ]
Initializes the information on an available master mode. @throws CmsException thrown if the write permission check on the bundle descriptor fails.
[ "private void initHasMasterMode() throws CmsException {\n\n if (hasDescriptor()\n && m_cms.hasPermissions(m_desc, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL)) {\n m_hasMasterMode = true;\n } else {\n m_hasMasterMode = false;\n }\n }" ]
[ "protected boolean checkExcludePackages(String classPackageName) {\n\t\tif (excludePackages != null && excludePackages.length > 0) {\n\t\t\tWildcardHelper wildcardHelper = new WildcardHelper();\n\n\t\t\t// we really don't care about the results, just the boolean\n\t\t\tMap<String, String> matchMap = new HashMap<String, String>();\n\n\t\t\tfor (String packageExclude : excludePackages) {\n\t\t\t\tint[] packagePattern = wildcardHelper.compilePattern(packageExclude);\n\t\t\t\tif (wildcardHelper.match(matchMap, classPackageName, packagePattern)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "private void updateWaveform(WaveformPreview preview) {\n this.preview.set(preview);\n if (preview == null) {\n waveformImage.set(null);\n } else {\n BufferedImage image = new BufferedImage(preview.segmentCount, preview.maxHeight, BufferedImage.TYPE_INT_RGB);\n Graphics g = image.getGraphics();\n g.setColor(Color.BLACK);\n g.fillRect(0, 0, preview.segmentCount, preview.maxHeight);\n for (int segment = 0; segment < preview.segmentCount; segment++) {\n g.setColor(preview.segmentColor(segment, false));\n g.drawLine(segment, preview.maxHeight, segment, preview.maxHeight - preview.segmentHeight(segment, false));\n if (preview.isColor) { // We have a front color segment to draw on top.\n g.setColor(preview.segmentColor(segment, true));\n g.drawLine(segment, preview.maxHeight, segment, preview.maxHeight - preview.segmentHeight(segment, true));\n }\n }\n waveformImage.set(image);\n }\n }", "public Map<String, ImplT> convertToUnmodifiableMap(List<InnerT> innerList) {\n Map<String, ImplT> result = new HashMap<>();\n for (InnerT inner : innerList) {\n result.put(name(inner), impl(inner));\n }\n\n return Collections.unmodifiableMap(result);\n }", "public Clob toClob(String stringName, Connection sqlConnection) {\n Clob clobName = null;\n try {\n clobName = sqlConnection.createClob();\n clobName.setString(1, stringName);\n } catch (SQLException e) {\n // TODO Auto-generated catch block\n logger.info(\"Unable to create clob object\");\n e.printStackTrace();\n }\n return clobName;\n }", "private void readPage(byte[] buffer, Table table)\n {\n int magicNumber = getShort(buffer, 0);\n if (magicNumber == 0x4400)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, 0, 6, true, 16, \"\"));\n int recordSize = m_definition.getRecordSize();\n RowValidator rowValidator = m_definition.getRowValidator();\n String primaryKeyColumnName = m_definition.getPrimaryKeyColumnName();\n\n int index = 6;\n while (index + recordSize <= buffer.length)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, index, recordSize, true, 16, \"\"));\n int btrieveValue = getShort(buffer, index);\n if (btrieveValue != 0)\n {\n Map<String, Object> row = new HashMap<String, Object>();\n row.put(\"ROW_VERSION\", Integer.valueOf(btrieveValue));\n for (ColumnDefinition column : m_definition.getColumns())\n {\n Object value = column.read(index, buffer);\n //System.out.println(column.getName() + \": \" + value);\n row.put(column.getName(), value);\n }\n\n if (rowValidator == null || rowValidator.validRow(row))\n {\n table.addRow(primaryKeyColumnName, row);\n }\n }\n index += recordSize;\n }\n }\n }", "private void updateSession(Session newSession) {\n if (this.currentSession == null) {\n this.currentSession = newSession;\n } else {\n synchronized (this.currentSession) {\n this.currentSession = newSession;\n }\n }\n }", "public String addressPath() {\n if (isLeaf) {\n ManagementModelNode parent = (ManagementModelNode)getParent();\n return parent.addressPath();\n }\n\n StringBuilder builder = new StringBuilder();\n for (Object pathElement : getUserObjectPath()) {\n UserObject userObj = (UserObject)pathElement;\n if (userObj.isRoot()) { // don't want to escape root\n builder.append(userObj.getName());\n continue;\n }\n\n builder.append(userObj.getName());\n builder.append(\"=\");\n builder.append(userObj.getEscapedValue());\n builder.append(\"/\");\n }\n\n return builder.toString();\n }", "public <X> X invokeOnInstance(Object instance, Object... parameters) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {\n final Map<Class<?>, Method> methods = this.methods;\n Method method = methods.get(instance.getClass());\n if (method == null) {\n // the same method may be written to the map twice, but that is ok\n // lookupMethod is very slow\n Method delegate = annotatedMethod.getJavaMember();\n method = SecurityActions.lookupMethod(instance.getClass(), delegate.getName(), delegate.getParameterTypes());\n SecurityActions.ensureAccessible(method);\n synchronized (this) {\n final Map<Class<?>, Method> newMethods = new HashMap<Class<?>, Method>(methods);\n newMethods.put(instance.getClass(), method);\n this.methods = WeldCollections.immutableMapView(newMethods);\n }\n }\n return cast(method.invoke(instance, parameters));\n }", "private void processResource(MapRow row) throws IOException\n {\n Resource resource = m_project.addResource();\n resource.setName(row.getString(\"NAME\"));\n resource.setGUID(row.getUUID(\"UUID\"));\n resource.setEmailAddress(row.getString(\"EMAIL\"));\n resource.setHyperlink(row.getString(\"URL\"));\n resource.setNotes(getNotes(row.getRows(\"COMMENTARY\")));\n resource.setText(1, row.getString(\"DESCRIPTION\"));\n resource.setText(2, row.getString(\"SUPPLY_REFERENCE\"));\n resource.setActive(true);\n\n List<MapRow> resources = row.getRows(\"RESOURCES\");\n if (resources != null)\n {\n for (MapRow childResource : sort(resources, \"NAME\"))\n {\n processResource(childResource);\n }\n }\n\n m_resourceMap.put(resource.getGUID(), resource);\n }" ]
Return the parent outline number, or an empty string if we have a root task. @param outlineNumber child outline number @return parent outline number
[ "private String getParentOutlineNumber(String outlineNumber)\n {\n String result;\n int index = outlineNumber.lastIndexOf('.');\n if (index == -1)\n {\n result = \"\";\n }\n else\n {\n result = outlineNumber.substring(0, index);\n }\n return result;\n }" ]
[ "public AddonChange addAddon(String appName, String addonName) {\n return connection.execute(new AddonInstall(appName, addonName), apiKey);\n }", "public static base_responses add(nitro_service client, dospolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdospolicy addresources[] = new dospolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dospolicy();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].qdepth = resources[i].qdepth;\n\t\t\t\taddresources[i].cltdetectrate = resources[i].cltdetectrate;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public void afterMaterialization(IndirectionHandler handler, Object materializedObject)\r\n {\r\n try\r\n {\r\n Identity oid = handler.getIdentity();\r\n if (log.isDebugEnabled())\r\n log.debug(\"deferred registration: \" + oid);\r\n if(!isOpen())\r\n {\r\n log.error(\"Proxy object materialization outside of a running tx, obj=\" + oid);\r\n try{throw new Exception(\"Proxy object materialization outside of a running tx, obj=\" + oid);}catch(Exception e)\r\n {\r\n e.printStackTrace();\r\n }\r\n }\r\n ClassDescriptor cld = getBroker().getClassDescriptor(materializedObject.getClass());\r\n RuntimeObject rt = new RuntimeObject(materializedObject, oid, cld, false, false);\r\n lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList());\r\n }\r\n catch (Throwable t)\r\n {\r\n log.error(\"Register materialized object with this tx failed\", t);\r\n throw new LockNotGrantedException(t.getMessage());\r\n }\r\n unregisterFromIndirectionHandler(handler);\r\n }", "public void deleteDescriptorIfNecessary() throws CmsException {\n\n if (m_removeDescriptorOnCancel && (m_desc != null)) {\n m_cms.deleteResource(m_desc, CmsResourceDeleteMode.valueOf(2));\n }\n\n }", "public IPv6Address toLinkLocalIPv6() {\r\n\t\tIPv6AddressNetwork network = getIPv6Network();\r\n\t\tIPv6AddressSection linkLocalPrefix = network.getLinkLocalPrefix();\r\n\t\tIPv6AddressCreator creator = network.getAddressCreator();\r\n\t\treturn creator.createAddress(linkLocalPrefix.append(toEUI64IPv6()));\r\n\t}", "public void signOff(WebSocketConnection connection) {\n for (ConcurrentMap<WebSocketConnection, WebSocketConnection> connections : registry.values()) {\n connections.remove(connection);\n }\n }", "public void abort() {\n URL abortURL = this.sessionInfo.getSessionEndpoints().getAbortEndpoint();\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), abortURL, HttpMethod.DELETE);\n request.send();\n }", "private static AbstractIndex constructLiborIndex(String forwardCurveName, Schedule schedule) {\n\n\t\tif(forwardCurveName != null) {\n\n\t\t\t//determine average fixing offset and period length\n\t\t\tdouble fixingOffset = 0;\n\t\t\tdouble periodLength = 0;\n\n\t\t\tfor(int i = 0; i < schedule.getNumberOfPeriods(); i++) {\n\t\t\t\tfixingOffset *= ((double) i) / (i+1);\n\t\t\t\tfixingOffset += (schedule.getPeriodStart(i) - schedule.getFixing(i)) / (i+1);\n\n\t\t\t\tperiodLength *= ((double) i) / (i+1);\n\t\t\t\tperiodLength += schedule.getPeriodLength(i) / (i+1);\n\t\t\t}\n\n\t\t\treturn new LIBORIndex(forwardCurveName, fixingOffset, periodLength);\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}", "public String convertToReadableDate(Holiday holiday) {\n DateTimeFormatter parser = ISODateTimeFormat.date();\n\n if (holiday.isInDateForm()) {\n String month = Integer.toString(holiday.getMonth()).length() < 2\n ? \"0\" + holiday.getMonth() : Integer.toString(holiday.getMonth());\n String day = Integer.toString(holiday.getDayOfMonth()).length() < 2\n ? \"0\" + holiday.getDayOfMonth() : Integer.toString(holiday.getDayOfMonth());\n return holiday.getYear() + \"-\" + month + \"-\" + day;\n } else {\n /*\n * 5 denotes the final occurrence of the day in the month. Need to find actual\n * number of occurrences\n */\n if (holiday.getOccurrence() == 5) {\n holiday.setOccurrence(numOccurrences(holiday.getYear(), holiday.getMonth(),\n holiday.getDayOfWeek()));\n }\n\n DateTime date = parser.parseDateTime(holiday.getYear() + \"-\"\n + holiday.getMonth() + \"-\" + \"01\");\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date.toDate());\n int count = 0;\n\n while (count < holiday.getOccurrence()) {\n if (calendar.get(Calendar.DAY_OF_WEEK) == holiday.getDayOfWeek()) {\n count++;\n if (count == holiday.getOccurrence()) {\n break;\n }\n }\n date = date.plusDays(1);\n calendar.setTime(date.toDate());\n }\n return date.toString().substring(0, 10);\n }\n }" ]
Parse the given file to obtains a Properties object. @param file @return a properties object containing all the properties present in the file. @throws InvalidDeclarationFileException
[ "private Properties parseFile(File file) throws InvalidDeclarationFileException {\n Properties properties = new Properties();\n InputStream is = null;\n try {\n is = new FileInputStream(file);\n properties.load(is);\n } catch (Exception e) {\n throw new InvalidDeclarationFileException(String.format(\"Error reading declaration file %s\", file.getAbsoluteFile()), e);\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n LOG.error(\"IOException thrown while trying to close the declaration file.\", e);\n }\n }\n }\n\n if (!properties.containsKey(Constants.ID)) {\n throw new InvalidDeclarationFileException(String.format(\"File %s is not a correct declaration, needs to contains an id property\", file.getAbsoluteFile()));\n }\n return properties;\n }" ]
[ "public static vpath_stats get(nitro_service service) throws Exception{\n\t\tvpath_stats obj = new vpath_stats();\n\t\tvpath_stats[] response = (vpath_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}", "private DBHandling createDBHandling() throws BuildException\r\n {\r\n if ((_handling == null) || (_handling.length() == 0))\r\n {\r\n throw new BuildException(\"No handling specified\");\r\n }\r\n try\r\n {\r\n String className = \"org.apache.ojb.broker.platforms.\"+\r\n \t\t\t\t\t Character.toTitleCase(_handling.charAt(0))+_handling.substring(1)+\r\n \t\t\t\t\t \"DBHandling\";\r\n Class handlingClass = ClassHelper.getClass(className);\r\n\r\n return (DBHandling)handlingClass.newInstance();\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new BuildException(\"Invalid handling '\"+_handling+\"' specified\");\r\n }\r\n }", "private Object readMetadataFromXML(InputSource source, Class target)\r\n throws MalformedURLException, ParserConfigurationException, SAXException, IOException\r\n {\r\n // TODO: make this configurable\r\n boolean validate = false;\r\n \r\n // get a xml reader instance:\r\n SAXParserFactory factory = SAXParserFactory.newInstance();\r\n log.info(\"RepositoryPersistor using SAXParserFactory : \" + factory.getClass().getName());\r\n if (validate)\r\n {\r\n factory.setValidating(true);\r\n }\r\n SAXParser p = factory.newSAXParser();\r\n XMLReader reader = p.getXMLReader();\r\n if (validate)\r\n {\r\n reader.setErrorHandler(new OJBErrorHandler());\r\n }\r\n\r\n Object result;\r\n if (DescriptorRepository.class.equals(target))\r\n {\r\n // create an empty repository:\r\n DescriptorRepository repository = new DescriptorRepository();\r\n // create handler for building the repository structure\r\n ContentHandler handler = new RepositoryXmlHandler(repository);\r\n // tell parser to use our handler:\r\n reader.setContentHandler(handler);\r\n reader.parse(source);\r\n result = repository;\r\n }\r\n else if (ConnectionRepository.class.equals(target))\r\n {\r\n // create an empty repository:\r\n ConnectionRepository repository = new ConnectionRepository();\r\n // create handler for building the repository structure\r\n ContentHandler handler = new ConnectionDescriptorXmlHandler(repository);\r\n // tell parser to use our handler:\r\n reader.setContentHandler(handler);\r\n reader.parse(source);\r\n //LoggerFactory.getBootLogger().info(\"loading XML took \" + (stop - start) + \" msecs\");\r\n result = repository;\r\n }\r\n else\r\n throw new MetadataException(\"Could not build a repository instance for '\" + target +\r\n \"', using source \" + source);\r\n return result;\r\n }", "public static authenticationradiusaction[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tauthenticationradiusaction[] response = (authenticationradiusaction[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "public String clean(String value) {\n String orig = value;\n \n // check if there's a + before the first digit\n boolean initialplus = findPlus(value);\n \n // remove everything but digits\n value = sub.clean(value);\n if (value == null)\n return null;\n\n // check for initial '00'\n boolean zerozero = !initialplus && value.startsWith(\"00\");\n if (zerozero)\n value = value.substring(2); // strip off the zeros\n\n // look for country code\n CountryCode ccode = findCountryCode(value);\n if (ccode == null) {\n // no country code, let's do what little we can\n if (initialplus || zerozero)\n return orig; // this number is messed up. dare not touch\n return value;\n\n } else {\n value = value.substring(ccode.getPrefix().length()); // strip off ccode\n if (ccode.getStripZero() && value.startsWith(\"0\"))\n value = value.substring(1); // strip the zero\n\n if (ccode.isRightFormat(value))\n return \"+\" + ccode.getPrefix() + \" \" + value;\n else\n return orig; // don't dare touch this\n }\n }", "public static void permutationVector( DMatrixSparseCSC P , int[] vector) {\n if( P.numCols != P.numRows ) {\n throw new MatrixDimensionException(\"Expected a square matrix\");\n } else if( P.nz_length != P.numCols ) {\n throw new IllegalArgumentException(\"Expected N non-zero elements in permutation matrix\");\n } else if( vector.length < P.numCols ) {\n throw new IllegalArgumentException(\"vector is too short\");\n }\n\n int M = P.numCols;\n\n for (int i = 0; i < M; i++) {\n if( P.col_idx[i+1] != i+1 )\n throw new IllegalArgumentException(\"Unexpected number of elements in a column\");\n\n vector[P.nz_rows[i]] = i;\n }\n }", "@Deprecated\n public static RemoteProxyController create(final ManagementChannelHandler channelAssociation, final PathAddress pathAddress, final ProxyOperationAddressTranslator addressTranslator) {\n final TransactionalProtocolClient client = TransactionalProtocolHandlers.createClient(channelAssociation);\n // the remote proxy\n return create(client, pathAddress, addressTranslator, ModelVersion.CURRENT);\n }", "public int getInt(Integer type)\n {\n int result = 0;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = MPPUtility.getInt(item, 0);\n }\n\n return (result);\n }", "@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public void enableKeyboardAutoHiding() {\n keyboardListener = new OnScrollListener() {\n @Override\n public void onScrolled(RecyclerView recyclerView, int dx, int dy) {\n if (dx != 0 || dy != 0) {\n imeManager.hideSoftInputFromWindow(\n Hits.this.getWindowToken(),\n InputMethodManager.HIDE_NOT_ALWAYS);\n }\n super.onScrolled(recyclerView, dx, dy);\n }\n };\n addOnScrollListener(keyboardListener);\n }" ]
Removes the specified list of users from following the project, this will not affect project membership status. Returns the updated project record. @param project The project to remove followers from. @return Request object
[ "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 int getFixedDataOffset(FieldType type)\n {\n int result;\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getFixedDataOffset();\n }\n else\n {\n result = -1;\n }\n return result;\n }", "public static int copyAllBytes(InputStream in, OutputStream out) throws IOException {\n int byteCount = 0;\n byte[] buffer = new byte[BUFFER_SIZE];\n while (true) {\n int read = in.read(buffer);\n if (read == -1) {\n break;\n }\n out.write(buffer, 0, read);\n byteCount += read;\n }\n return byteCount;\n }", "public boolean measureAll(List<Widget> measuredChildren) {\n boolean changed = false;\n for (int i = 0; i < mContainer.size(); ++i) {\n\n if (!isChildMeasured(i)) {\n Widget child = measureChild(i, false);\n if (child != null) {\n if (measuredChildren != null) {\n measuredChildren.add(child);\n }\n changed = true;\n }\n }\n }\n if (changed) {\n postMeasurement();\n }\n return changed;\n }", "List<MwDumpFile> mergeDumpLists(List<MwDumpFile> localDumps,\n\t\t\tList<MwDumpFile> onlineDumps) {\n\t\tList<MwDumpFile> result = new ArrayList<>(localDumps);\n\n\t\tHashSet<String> localDateStamps = new HashSet<>();\n\t\tfor (MwDumpFile dumpFile : localDumps) {\n\t\t\tlocalDateStamps.add(dumpFile.getDateStamp());\n\t\t}\n\t\tfor (MwDumpFile dumpFile : onlineDumps) {\n\t\t\tif (!localDateStamps.contains(dumpFile.getDateStamp())) {\n\t\t\t\tresult.add(dumpFile);\n\t\t\t}\n\t\t}\n\t\tresult.sort(Collections.reverseOrder(new MwDumpFile.DateComparator()));\n\t\treturn result;\n\t}", "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 nsrollbackcmd get(nitro_service service) throws Exception{\n\t\tnsrollbackcmd obj = new nsrollbackcmd();\n\t\tnsrollbackcmd[] response = (nsrollbackcmd[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public void reset(int profileId, String clientUUID) throws Exception {\n PreparedStatement statement = null;\n\n // TODO: need a better way to do this than brute force.. but the iterative approach is too slow\n try (Connection sqlConnection = sqlService.getConnection()) {\n\n // first remove all enabled overrides with this client uuid\n String queryString = \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= ? \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \" = ?\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n statement.setInt(2, profileId);\n statement.executeUpdate();\n statement.close();\n\n // clean up request response table for this uuid\n queryString = \"UPDATE \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \" SET \" + Constants.REQUEST_RESPONSE_CUSTOM_REQUEST + \"=?, \"\n + Constants.REQUEST_RESPONSE_CUSTOM_RESPONSE + \"=?, \"\n + Constants.REQUEST_RESPONSE_REPEAT_NUMBER + \"=-1, \"\n + Constants.REQUEST_RESPONSE_REQUEST_ENABLED + \"=0, \"\n + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED + \"=0 \"\n + \"WHERE \" + Constants.GENERIC_CLIENT_UUID + \"=? \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"=?\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, \"\");\n statement.setString(2, \"\");\n statement.setString(3, clientUUID);\n statement.setInt(4, profileId);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n this.updateActive(profileId, clientUUID, false);\n }", "protected void generateRoutes()\n {\n try {\n\n//\t\t\tOptional<io.sinistral.proteus.annotations.Chain> typeLevelWrapAnnotation = Optional.ofNullable(controllerClass.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\n//\t\t\ttypeLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t \n//\t\t\t\tio.sinistral.proteus.annotations.Chain w = typeLevelWrapAnnotation.get();\n//\n//\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\n//\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t{\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\n//\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\n//\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t}\n//\t\t\t\t\n//\t\t\t});\n//\t\t\t\n//\t\t\tfor(Method m : this.controllerClass.getDeclaredMethods())\n//\t\t\t{\n//\t\t\t\n//\t\t\t\tOptional<io.sinistral.proteus.annotations.Chain> methodLevelWrapAnnotation = Optional.ofNullable(m.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\t\n//\t\t\t\tmethodLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t\t \n//\t\t\t\t\tio.sinistral.proteus.annotations.Chain w = methodLevelWrapAnnotation.get();\n//\t\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\t\n//\t\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\t\n//\t\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\t\n//\t\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t\t}\n//\t\t\t\t\t\n//\t\t\t\t});\n//\n//\t\t\t}\n//\t\t\t\n//\t\t\tlog.info(\"handlerWrapperMap: \" + handlerWrapperMap);\n\n TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC)\n .addSuperinterface(ParameterizedTypeName.get(Supplier.class, RoutingHandler.class));\n\n ClassName extractorClass = ClassName.get(\"io.sinistral.proteus.server\", \"Extractors\");\n\n ClassName injectClass = ClassName.get(\"com.google.inject\", \"Inject\");\n\n\n MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addAnnotation(injectClass);\n\n String className = this.controllerClass.getSimpleName().toLowerCase() + \"Controller\";\n\n typeBuilder.addField(this.controllerClass, className, Modifier.PROTECTED, Modifier.FINAL);\n\n ClassName wrapperClass = ClassName.get(\"io.undertow.server\", \"HandlerWrapper\");\n ClassName stringClass = ClassName.get(\"java.lang\", \"String\");\n ClassName mapClass = ClassName.get(\"java.util\", \"Map\");\n\n TypeName mapOfWrappers = ParameterizedTypeName.get(mapClass, stringClass, wrapperClass);\n\n TypeName annotatedMapOfWrappers = mapOfWrappers\n .annotated(AnnotationSpec.builder(com.google.inject.name.Named.class).addMember(\"value\", \"$S\", \"registeredHandlerWrappers\").build());\n\n typeBuilder.addField(mapOfWrappers, \"registeredHandlerWrappers\", Modifier.PROTECTED, Modifier.FINAL);\n\n\n constructor.addParameter(this.controllerClass, className);\n constructor.addParameter(annotatedMapOfWrappers, \"registeredHandlerWrappers\");\n\n constructor.addStatement(\"this.$N = $N\", className, className);\n constructor.addStatement(\"this.$N = $N\", \"registeredHandlerWrappers\", \"registeredHandlerWrappers\");\n\n addClassMethodHandlers(typeBuilder, this.controllerClass);\n\n typeBuilder.addMethod(constructor.build());\n\n JavaFile javaFile = JavaFile.builder(packageName, typeBuilder.build()).addStaticImport(extractorClass, \"*\").build();\n\n StringBuilder sb = new StringBuilder();\n\n javaFile.writeTo(sb);\n\n this.sourceString = sb.toString();\n\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n }", "private static Map<String, String> mapCustomInfo(CustomInfoType ciType){\n Map<String, String> customInfo = new HashMap<String, String>();\n if (ciType != null){\n for (CustomInfoType.Item item : ciType.getItem()) {\n customInfo.put(item.getKey(), item.getValue());\n }\n }\n return customInfo;\n }" ]
Removes a tag from the resource. @param key the key of the tag to remove @return the next stage of the definition/update
[ "@SuppressWarnings(\"unchecked\")\n public final FluentModelImplT withoutTag(String key) {\n if (this.inner().getTags() != null) {\n this.inner().getTags().remove(key);\n }\n return (FluentModelImplT) this;\n }" ]
[ "public 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 void redeployDeployments(OperationContext context, PathAddress deploymentsRootAddress, Set<String> deploymentNames) throws OperationFailedException {\n for (String deploymentName : deploymentNames) {\n PathAddress address = deploymentsRootAddress.append(DEPLOYMENT, deploymentName);\n OperationStepHandler handler = context.getRootResourceRegistration().getOperationHandler(address, REDEPLOY);\n ModelNode operation = addRedeployStep(address);\n ServerLogger.AS_ROOT_LOGGER.debugf(\"Redeploying %s at address %s with handler %s\", deploymentName, address, handler);\n assert handler != null;\n assert operation.isDefined();\n context.addStep(operation, handler, OperationContext.Stage.MODEL);\n }\n }", "public static String getString(Properties props, String name, String defaultValue) {\n return props.containsKey(name) ? props.getProperty(name) : defaultValue;\n }", "public void set(Vector3d v1) {\n x = v1.x;\n y = v1.y;\n z = v1.z;\n }", "public static Map<String, Object> with(Object... params) {\n Map<String, Object> map = new HashMap<>();\n for (int i = 0; i < params.length; i++) {\n map.put(String.valueOf(i), params[i]);\n }\n return map;\n }", "synchronized JSONObject fetchEvents(Table table, final int limit) {\n final String tName = table.getName();\n Cursor cursor = null;\n String lastId = null;\n\n final JSONArray events = new JSONArray();\n\n //noinspection TryFinallyCanBeTryWithResources\n try {\n final SQLiteDatabase db = dbHelper.getReadableDatabase();\n cursor = db.rawQuery(\"SELECT * FROM \" + tName +\n \" ORDER BY \" + KEY_CREATED_AT + \" ASC LIMIT \" + limit, null);\n\n\n while (cursor.moveToNext()) {\n if (cursor.isLast()) {\n lastId = cursor.getString(cursor.getColumnIndex(\"_id\"));\n }\n try {\n final JSONObject j = new JSONObject(cursor.getString(cursor.getColumnIndex(KEY_DATA)));\n events.put(j);\n } catch (final JSONException e) {\n // Ignore\n }\n }\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Could not fetch records out of database \" + tName + \".\", e);\n lastId = null;\n } finally {\n dbHelper.close();\n if (cursor != null) {\n cursor.close();\n }\n }\n\n if (lastId != null) {\n try {\n final JSONObject ret = new JSONObject();\n ret.put(lastId, events);\n return ret;\n } catch (JSONException e) {\n // ignore\n }\n }\n\n return null;\n }", "private void verifyApplicationName(String name) {\n if (name == null) {\n throw new IllegalArgumentException(\"Application name cannot be null\");\n }\n if (name.isEmpty()) {\n throw new IllegalArgumentException(\"Application name length must be > 0\");\n }\n String reason = null;\n char[] chars = name.toCharArray();\n char c;\n for (int i = 0; i < chars.length; i++) {\n c = chars[i];\n if (c == 0) {\n reason = \"null character not allowed @\" + i;\n break;\n } else if (c == '/' || c == '.' || c == ':') {\n reason = \"invalid character '\" + c + \"'\";\n break;\n } else if (c > '\\u0000' && c <= '\\u001f' || c >= '\\u007f' && c <= '\\u009F'\n || c >= '\\ud800' && c <= '\\uf8ff' || c >= '\\ufff0' && c <= '\\uffff') {\n reason = \"invalid character @\" + i;\n break;\n }\n }\n if (reason != null) {\n throw new IllegalArgumentException(\n \"Invalid application name \\\"\" + name + \"\\\" caused by \" + reason);\n }\n }", "protected ValueContainer[] getAllValues(ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n return m_broker.serviceBrokerHelper().getAllRwValues(cld, obj);\r\n }", "public static base_response create(nitro_service client, ssldhparam resource) throws Exception {\n\t\tssldhparam createresource = new ssldhparam();\n\t\tcreateresource.dhfile = resource.dhfile;\n\t\tcreateresource.bits = resource.bits;\n\t\tcreateresource.gen = resource.gen;\n\t\treturn createresource.perform_operation(client,\"create\");\n\t}" ]
Create a new path address by appending more elements to the end of this address. @param additionalElements the elements to append @return the new path address
[ "public PathAddress append(List<PathElement> additionalElements) {\n final ArrayList<PathElement> newList = new ArrayList<PathElement>(pathAddressList.size() + additionalElements.size());\n newList.addAll(pathAddressList);\n newList.addAll(additionalElements);\n return pathAddress(newList);\n }" ]
[ "public static Date addDays(Date date, int days)\n {\n Calendar cal = popCalendar(date);\n cal.add(Calendar.DAY_OF_YEAR, days);\n Date result = cal.getTime();\n pushCalendar(cal);\n return result; \n }", "private void addException(ProjectCalendar mpxjCalendar, net.sf.mpxj.ganttproject.schema.Date date)\n {\n String year = date.getYear();\n if (year == null || year.isEmpty())\n {\n // In order to process recurring exceptions using MPXJ, we need a start and end date\n // to constrain the number of dates we generate.\n // May need to pre-process the tasks in order to calculate a start and finish date.\n // TODO: handle recurring exceptions\n }\n else\n {\n Calendar calendar = DateHelper.popCalendar();\n calendar.set(Calendar.YEAR, Integer.parseInt(year));\n calendar.set(Calendar.MONTH, NumberHelper.getInt(date.getMonth()));\n calendar.set(Calendar.DAY_OF_MONTH, NumberHelper.getInt(date.getDate()));\n Date exceptionDate = calendar.getTime();\n DateHelper.pushCalendar(calendar);\n ProjectCalendarException exception = mpxjCalendar.addCalendarException(exceptionDate, exceptionDate);\n\n // TODO: not sure how NEUTRAL should be handled\n if (\"WORKING_DAY\".equals(date.getType()))\n {\n exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n }", "static Type getRawType(Type genericType, Map<TypeVariable, Type> typeVariableMap) {\n\t\tType resolvedType = genericType;\n\t\tif (genericType instanceof TypeVariable) {\n\t\t\tTypeVariable tv = (TypeVariable) genericType;\n\t\t\tresolvedType = typeVariableMap.get(tv);\n\t\t\tif (resolvedType == null) {\n\t\t\t\tresolvedType = extractBoundForTypeVariable(tv);\n\t\t\t}\n\t\t}\n\t\tif (resolvedType instanceof ParameterizedType) {\n\t\t\treturn ((ParameterizedType) resolvedType).getRawType();\n\t\t}\n\t\telse {\n\t\t\treturn resolvedType;\n\t\t}\n\t}", "public static String getAt(GString text, Range range) {\n return getAt(text.toString(), range);\n }", "public static void addToListIfNotExists(List<String> list, String value) {\n boolean found = false;\n for (String item : list) {\n if (item.equalsIgnoreCase(value)) {\n found = true;\n break;\n }\n }\n if (!found) {\n list.add(value);\n }\n }", "@NotNull\n static MetaTreeImpl.Proto saveMetaTree(@NotNull final ITreeMutable metaTree,\n @NotNull final EnvironmentImpl env,\n @NotNull final ExpiredLoggableCollection expired) {\n final long newMetaTreeAddress = metaTree.save();\n final Log log = env.getLog();\n final int lastStructureId = env.getLastStructureId();\n final long dbRootAddress = log.write(DatabaseRoot.DATABASE_ROOT_TYPE, Loggable.NO_STRUCTURE_ID,\n DatabaseRoot.asByteIterable(newMetaTreeAddress, lastStructureId));\n expired.add(dbRootAddress, (int) (log.getWrittenHighAddress() - dbRootAddress));\n return new MetaTreeImpl.Proto(newMetaTreeAddress, dbRootAddress);\n }", "final public void addOffset(Integer start, Integer end) {\n if (tokenOffset == null) {\n setOffset(start, end);\n } else if ((start == null) || (end == null)) {\n // do nothing\n } else if (start > end) {\n throw new IllegalArgumentException(\"Start offset after end offset\");\n } else {\n tokenOffset.add(start, end);\n }\n }", "public static <T> Observable<T> map(Observable<?> fromObservable, final T toValue) {\n if (fromObservable != null) {\n return fromObservable.subscribeOn(Schedulers.io())\n .map(new RXMapper<T>(toValue));\n } else {\n return Observable.empty();\n }\n }", "@Override\n public HandlerRegistration addSearchNoResultHandler(final SearchNoResultEvent.SearchNoResultHandler handler) {\n return addHandler(handler, SearchNoResultEvent.TYPE);\n }" ]
Returns the DBCP DataSource for the specified connection descriptor, after creating a new DataSource if needed. @param jcd the descriptor for which to return a DataSource @return a DataSource, after creating a new pool if needed. Guaranteed to never be null. @throws LookupException if pool is not in cache and cannot be created
[ "protected DataSource getDataSource(JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n final PBKey key = jcd.getPBKey();\r\n DataSource ds = (DataSource) dsMap.get(key);\r\n if (ds == null)\r\n {\r\n // Found no pool for PBKey\r\n try\r\n {\r\n synchronized (poolSynch)\r\n {\r\n // Setup new object pool\r\n ObjectPool pool = setupPool(jcd);\r\n poolMap.put(key, pool);\r\n // Wrap the underlying object pool as DataSource\r\n ds = wrapAsDataSource(jcd, pool);\r\n dsMap.put(key, ds);\r\n }\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Could not setup DBCP DataSource for \" + jcd, e);\r\n throw new LookupException(e);\r\n }\r\n }\r\n return ds;\r\n }" ]
[ "public void applyToOr(TextView textView, ColorStateList colorDefault) {\n if (mColorInt != 0) {\n textView.setTextColor(mColorInt);\n } else if (mColorRes != -1) {\n textView.setTextColor(ContextCompat.getColor(textView.getContext(), mColorRes));\n } else if (colorDefault != null) {\n textView.setTextColor(colorDefault);\n }\n }", "public static String parseServers(String zookeepers) {\n int slashIndex = zookeepers.indexOf(\"/\");\n if (slashIndex != -1) {\n return zookeepers.substring(0, slashIndex);\n }\n return zookeepers;\n }", "public static boolean containsOnlyNotNull(Object... values){\t\n\t\tfor(Object o : values){\n\t\t\tif(o== null){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "public static AnnotationNode getAnnotation(AnnotatedNode node, String name) {\r\n List<AnnotationNode> annotations = node.getAnnotations();\r\n for (AnnotationNode annot : annotations) {\r\n if (annot.getClassNode().getName().equals(name)) {\r\n return annot;\r\n }\r\n }\r\n return null;\r\n }", "public static base_responses update(nitro_service client, systemuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsystemuser updateresources[] = new systemuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new systemuser();\n\t\t\t\tupdateresources[i].username = resources[i].username;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].externalauth = resources[i].externalauth;\n\t\t\t\tupdateresources[i].promptstring = resources[i].promptstring;\n\t\t\t\tupdateresources[i].timeout = resources[i].timeout;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private void checkQueryCustomizer(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n String queryCustomizerName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_QUERY_CUSTOMIZER);\r\n\r\n if (queryCustomizerName == null)\r\n {\r\n return;\r\n }\r\n\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(queryCustomizerName, QUERY_CUSTOMIZER_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The class \"+queryCustomizerName+\" specified as query-customizer of collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" does not implement the interface \"+QUERY_CUSTOMIZER_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"The class \"+ex.getMessage()+\" specified as query-customizer of collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" was not found on the classpath\");\r\n }\r\n }", "public static URI setPath(final URI initialUri, final String path) {\n String finalPath = path;\n if (!finalPath.startsWith(\"/\")) {\n finalPath = '/' + path;\n }\n try {\n if (initialUri.getHost() == null && initialUri.getAuthority() != null) {\n return new URI(initialUri.getScheme(), initialUri.getAuthority(), finalPath,\n initialUri.getQuery(),\n initialUri.getFragment());\n } else {\n return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),\n initialUri.getPort(),\n finalPath, initialUri.getQuery(), initialUri.getFragment());\n }\n } catch (URISyntaxException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }", "public static void dumpClusters(Cluster currentCluster,\n Cluster finalCluster,\n String outputDirName) {\n dumpClusters(currentCluster, finalCluster, outputDirName, \"\");\n }", "private static synchronized StreamHandler getStreamHandler() {\n if (methodHandler == null) {\n methodHandler = new ConsoleHandler();\n methodHandler.setFormatter(new Formatter() {\n @Override\n public String format(LogRecord record) {\n return record.getMessage() + \"\\n\";\n }\n });\n methodHandler.setLevel(Level.FINE);\n }\n return methodHandler;\n }" ]
Returns iban length for the specified country. @param countryCode {@link org.iban4j.CountryCode} @return the length of the iban for the specified country.
[ "public static int getIbanLength(final CountryCode countryCode) {\n final BbanStructure structure = getBbanStructure(countryCode);\n return COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH + structure.getBbanLength();\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 PhotoList<Photo> getClusterPhotos(String tag, String clusterId) throws FlickrException {\n\n PhotoList<Photo> photos = new PhotoList<Photo>();\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_CLUSTER_PHOTOS);\n\n parameters.put(\"tag\", tag);\n parameters.put(\"cluster_id\", clusterId);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element photosElement = response.getPayload();\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\n photos.setPage(\"1\");\n photos.setPages(\"1\");\n photos.setPerPage(\"\" + photoNodes.getLength());\n photos.setTotal(\"\" + photoNodes.getLength());\n for (int i = 0; i < photoNodes.getLength(); i++) {\n Element photoElement = (Element) photoNodes.item(i);\n photos.add(PhotoUtils.createPhoto(photoElement));\n }\n return photos;\n }", "public void visitMethodInsn(int opcode, String owner, String name,\n String desc, boolean itf) {\n if (mv != null) {\n mv.visitMethodInsn(opcode, owner, name, desc, itf);\n }\n }", "public double getValue(ForwardCurve forwardCurve, double swaprateVolatility) {\n\t\tdouble[] swapTenor = new double[fixingDates.length+1];\n\t\tSystem.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length);\n\t\tswapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1];\n\n\t\tTimeDiscretization fixTenor\t= new TimeDiscretizationFromArray(swapTenor);\n\t\tTimeDiscretization floatTenor\t= new TimeDiscretizationFromArray(swapTenor);\n\t\tdouble forwardSwapRate = Swap.getForwardSwapRate(fixTenor, floatTenor, forwardCurve);\n\t\tdouble swapAnnuity = SwapAnnuity.getSwapAnnuity(fixTenor, forwardCurve);\n\t\tdouble payoffUnit = SwapAnnuity.getSwapAnnuity(new TimeDiscretizationFromArray(swapTenor[0], swapTenor[1]), forwardCurve) / (swapTenor[1] - swapTenor[0]);\n\t\treturn AnalyticFormulas.huntKennedyCMSOptionValue(forwardSwapRate, swaprateVolatility, swapAnnuity, exerciseDate, swapTenor[swapTenor.length-1]-swapTenor[0], payoffUnit, strike) * (swapTenor[1] - swapTenor[0]);\n\t}", "private void addSequence(String sequenceName, HighLowSequence seq)\r\n {\r\n // lookup the sequence map for calling DB\r\n String jcdAlias = getBrokerForClass()\r\n .serviceConnectionManager().getConnectionDescriptor().getJcdAlias();\r\n Map mapForDB = (Map) sequencesDBMap.get(jcdAlias);\r\n if(mapForDB == null)\r\n {\r\n mapForDB = new HashMap();\r\n }\r\n mapForDB.put(sequenceName, seq);\r\n sequencesDBMap.put(jcdAlias, mapForDB);\r\n }", "public Range<Dyno> listDynos(String appName) {\n return connection.execute(new DynoList(appName), apiKey);\n }", "public void setPattern(String patternType) {\r\n\r\n final PatternType type = PatternType.valueOf(patternType);\r\n if (type != m_model.getPatternType()) {\r\n removeExceptionsOnChange(new Command() {\r\n\r\n public void execute() {\r\n\r\n EndType oldEndType = m_model.getEndType();\r\n m_model.setPatternType(type);\r\n m_model.setIndividualDates(null);\r\n m_model.setInterval(getPatternDefaultValues().getInterval());\r\n m_model.setEveryWorkingDay(Boolean.FALSE);\r\n m_model.clearWeekDays();\r\n m_model.clearIndividualDates();\r\n m_model.clearWeeksOfMonth();\r\n m_model.clearExceptions();\r\n if (type.equals(PatternType.NONE) || type.equals(PatternType.INDIVIDUAL)) {\r\n m_model.setEndType(EndType.SINGLE);\r\n } else if (oldEndType.equals(EndType.SINGLE)) {\r\n m_model.setEndType(EndType.TIMES);\r\n m_model.setOccurrences(10);\r\n m_model.setSeriesEndDate(null);\r\n }\r\n m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth());\r\n m_model.setMonth(getPatternDefaultValues().getMonth());\r\n if (type.equals(PatternType.WEEKLY)) {\r\n m_model.setWeekDay(getPatternDefaultValues().getWeekDay());\r\n }\r\n valueChanged();\r\n }\r\n });\r\n }\r\n\r\n }", "public static void setPropertySafely(Marshaller marshaller, String name, Object value) {\n try {\n marshaller.setProperty(name, value);\n } catch (PropertyException e) {\n LOGGER.warn(String.format(\"Can't set \\\"%s\\\" property to given marshaller\", name), e);\n }\n }", "private List<Row> getTable(String name)\n {\n List<Row> result = m_tables.get(name);\n if (result == null)\n {\n result = Collections.emptyList();\n }\n return result;\n }" ]
Pass a model object and return a SoyMapData if a model object happens to be a SoyMapData. An implementation will also check if a passed in object is a Map and return a SoyMapData wrapping that map
[ "@Override\n public Optional<SoyMapData> toSoyMap(@Nullable final Object model) throws Exception {\n if (model instanceof SoyMapData) {\n return Optional.of((SoyMapData) model);\n }\n if (model instanceof Map) {\n return Optional.of(new SoyMapData(model));\n }\n\n return Optional.of(new SoyMapData());\n }" ]
[ "public boolean detectNintendo() {\r\n\r\n if ((userAgent.indexOf(deviceNintendo) != -1)\r\n || (userAgent.indexOf(deviceWii) != -1)\r\n || (userAgent.indexOf(deviceNintendoDs) != -1)) {\r\n return true;\r\n }\r\n return false;\r\n }", "protected void appendHavingClause(StringBuffer having, Criteria crit, StringBuffer stmt)\r\n {\r\n if (having.length() == 0)\r\n {\r\n having = null;\r\n }\r\n\r\n if (having != null || crit != null)\r\n {\r\n stmt.append(\" HAVING \");\r\n appendClause(having, crit, stmt);\r\n }\r\n }", "private static Point getScreenSize(Context context, Point p) {\n if (p == null) {\n p = new Point();\n }\n WindowManager windowManager = (WindowManager) context\n .getSystemService(Context.WINDOW_SERVICE);\n Display display = windowManager.getDefaultDisplay();\n display.getSize(p);\n return p;\n }", "@JsonIgnore\n public void setUnknownFields(final Map<String,Object> unknownFields) {\n this.unknownFields.clear();\n this.unknownFields.putAll(unknownFields);\n }", "public static ProctorLoadResult verify(\n @Nonnull final TestMatrixArtifact testMatrix,\n final String matrixSource,\n @Nonnull final Map<String, TestSpecification> requiredTests,\n @Nonnull final FunctionMapper functionMapper,\n final ProvidedContext providedContext,\n @Nonnull final Set<String> dynamicTests\n ) {\n final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();\n\n final Map<String, Map<Integer, String>> allTestsKnownBuckets = Maps.newHashMapWithExpectedSize(requiredTests.size());\n for (final Entry<String, TestSpecification> entry : requiredTests.entrySet()) {\n final Map<Integer, String> bucketValueToName = Maps.newHashMap();\n for (final Entry<String, Integer> bucket : entry.getValue().getBuckets().entrySet()) {\n bucketValueToName.put(bucket.getValue(), bucket.getKey());\n }\n allTestsKnownBuckets.put(entry.getKey(), bucketValueToName);\n }\n\n final Map<String, ConsumableTestDefinition> definedTests = testMatrix.getTests();\n final SetView<String> missingTests = Sets.difference(requiredTests.keySet(), definedTests.keySet());\n resultBuilder.recordAllMissing(missingTests);\n for (final Entry<String, ConsumableTestDefinition> entry : definedTests.entrySet()) {\n final String testName = entry.getKey();\n\n final Map<Integer, String> knownBuckets;\n final TestSpecification specification;\n final boolean isRequired;\n if (allTestsKnownBuckets.containsKey(testName)) {\n // required in specification\n isRequired = true;\n knownBuckets = allTestsKnownBuckets.remove(testName);\n specification = requiredTests.get(testName);\n } else if (dynamicTests.contains(testName)) {\n // resolved by dynamic filter\n isRequired = false;\n knownBuckets = Collections.emptyMap();\n specification = new TestSpecification();\n } else {\n // we don't care about this test\n continue;\n }\n\n final ConsumableTestDefinition testDefinition = entry.getValue();\n\n try {\n verifyTest(testName, testDefinition, specification, knownBuckets, matrixSource, functionMapper, providedContext);\n\n } catch (IncompatibleTestMatrixException e) {\n if (isRequired) {\n LOGGER.error(String.format(\"Unable to load test matrix for a required test %s\", testName), e);\n resultBuilder.recordError(testName, e);\n } else {\n LOGGER.info(String.format(\"Unable to load test matrix for a dynamic test %s\", testName), e);\n resultBuilder.recordIncompatibleDynamicTest(testName, e);\n }\n }\n }\n\n // TODO mjs - is this check additive?\n resultBuilder.recordAllMissing(allTestsKnownBuckets.keySet());\n\n resultBuilder.recordVerifiedRules(providedContext.shouldEvaluate());\n\n final ProctorLoadResult loadResult = resultBuilder.build();\n\n return loadResult;\n }", "public static void normalizeF( DMatrixRMaj A ) {\n double val = normF(A);\n\n if( val == 0 )\n return;\n\n int size = A.getNumElements();\n\n for( int i = 0; i < size; i++) {\n A.div(i , val);\n }\n }", "public Weld addPackage(boolean scanRecursively, Class<?> packageClass) {\n packages.add(new PackInfo(packageClass, scanRecursively));\n return this;\n }", "protected void aliasGeneric( Object variable , String name ) {\n if( variable.getClass() == Integer.class ) {\n alias(((Integer)variable).intValue(),name);\n } else if( variable.getClass() == Double.class ) {\n alias(((Double)variable).doubleValue(),name);\n } else if( variable.getClass() == DMatrixRMaj.class ) {\n alias((DMatrixRMaj)variable,name);\n } else if( variable.getClass() == FMatrixRMaj.class ) {\n alias((FMatrixRMaj)variable,name);\n } else if( variable.getClass() == DMatrixSparseCSC.class ) {\n alias((DMatrixSparseCSC)variable,name);\n } else if( variable.getClass() == SimpleMatrix.class ) {\n alias((SimpleMatrix) variable, name);\n } else if( variable instanceof DMatrixFixed ) {\n DMatrixRMaj M = new DMatrixRMaj(1,1);\n ConvertDMatrixStruct.convert((DMatrixFixed)variable,M);\n alias(M,name);\n } else if( variable instanceof FMatrixFixed ) {\n FMatrixRMaj M = new FMatrixRMaj(1,1);\n ConvertFMatrixStruct.convert((FMatrixFixed)variable,M);\n alias(M,name);\n } else {\n throw new RuntimeException(\"Unknown value type of \"+\n (variable.getClass().getSimpleName())+\" for variable \"+name);\n }\n }", "public void removeChildTask(Task child)\n {\n if (m_children.remove(child))\n {\n child.m_parent = null;\n }\n setSummary(!m_children.isEmpty());\n }" ]
Copy values from the inserted config to this config. Note that if properties has not been explicitly set, the defaults will apply.
[ "public void override(HiveRunnerConfig hiveRunnerConfig) {\n config.putAll(hiveRunnerConfig.config);\n hiveConfSystemOverride.putAll(hiveRunnerConfig.hiveConfSystemOverride);\n }" ]
[ "public static <E> Set<E> setify(ObjectMapper mapper, Object source, Class<E> targetElementType) {\n return (Set<E>) collectify(mapper, source, Set.class, targetElementType);\n }", "public static URL codeLocationFromURL(String url) {\n try {\n return new URL(url);\n } catch (Exception e) {\n throw new InvalidCodeLocation(url);\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 }", "public static TransactionalProtocolClient.PreparedOperation<TransactionalProtocolClient.Operation> executeBlocking(final ModelNode operation, TransactionalProtocolClient client) throws IOException, InterruptedException {\n final BlockingQueueOperationListener<TransactionalProtocolClient.Operation> listener = new BlockingQueueOperationListener<>();\n client.execute(listener, operation, OperationMessageHandler.DISCARD, OperationAttachments.EMPTY);\n return listener.retrievePreparedOperation();\n }", "public static autoscaleprofile get(nitro_service service, String name) throws Exception{\n\t\tautoscaleprofile obj = new autoscaleprofile();\n\t\tobj.set_name(name);\n\t\tautoscaleprofile response = (autoscaleprofile) obj.get_resource(service);\n\t\treturn response;\n\t}", "@Override protected Class getPrototypeClass(Video content) {\n Class prototypeClass;\n if (content.isFavorite()) {\n prototypeClass = FavoriteVideoRenderer.class;\n } else if (content.isLive()) {\n prototypeClass = LiveVideoRenderer.class;\n } else {\n prototypeClass = LikeVideoRenderer.class;\n }\n return prototypeClass;\n }", "public String interpolate( String input, RecursionInterceptor recursionInterceptor )\n\t throws InterpolationException\n\t {\n\t try\n\t {\n\t return interpolate( input, recursionInterceptor, new HashSet<String>() );\n\t }\n\t finally\n\t {\n\t if ( !cacheAnswers )\n\t {\n\t existingAnswers.clear();\n\t }\n\t }\n\t }", "private static int getBlockLength(String text, int offset)\n {\n int startIndex = offset;\n boolean finished = false;\n char c;\n\n while (finished == false)\n {\n c = text.charAt(offset);\n switch (c)\n {\n case '\\r':\n case '\\n':\n case '}':\n {\n finished = true;\n break;\n }\n\n default:\n {\n ++offset;\n break;\n }\n }\n }\n\n int length = offset - startIndex;\n\n return (length);\n }", "public void forAllForeignkeyColumnPairs(String template, Properties attributes) throws XDocletException\r\n {\r\n for (int idx = 0; idx < _curForeignkeyDef.getNumColumnPairs(); idx++)\r\n {\r\n _curPairLeft = _curForeignkeyDef.getLocalColumn(idx);\r\n _curPairRight = _curForeignkeyDef.getRemoteColumn(idx);\r\n generate(template);\r\n }\r\n _curPairLeft = null;\r\n _curPairRight = null;\r\n }" ]
Flush this log file to the physical disk @throws IOException file read error
[ "public void flush() throws IOException {\n if (unflushed.get() == 0) return;\n\n synchronized (lock) {\n if (logger.isTraceEnabled()) {\n logger.debug(\"Flushing log '\" + name + \"' last flushed: \" + getLastFlushedTime() + \" current time: \" + System\n .currentTimeMillis());\n }\n segments.getLastView().getMessageSet().flush();\n unflushed.set(0);\n lastflushedTime.set(System.currentTimeMillis());\n }\n }" ]
[ "private void writeAssignmentTimephasedData(BigInteger assignmentID, List<TimephasedDataType> list, List<TimephasedWork> data, int type)\n {\n for (TimephasedWork mpx : data)\n {\n TimephasedDataType xml = m_factory.createTimephasedDataType();\n list.add(xml);\n\n xml.setStart(mpx.getStart());\n xml.setFinish(mpx.getFinish());\n xml.setType(BigInteger.valueOf(type));\n xml.setUID(assignmentID);\n xml.setUnit(DatatypeConverter.printDurationTimeUnits(mpx.getTotalAmount(), false));\n xml.setValue(DatatypeConverter.printDuration(this, mpx.getTotalAmount()));\n }\n }", "public long addAll(final String... members) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.sadd(getKey(), members);\n }\n });\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 Build createBuild(String appName, Build build) {\n return connection.execute(new BuildCreate(appName, build), apiKey);\n }", "@Deprecated\n public static <T> ServiceBuilder<T> addServerExecutorDependency(ServiceBuilder<T> builder, Injector<ExecutorService> injector) {\n return builder.addDependency(ServerService.MANAGEMENT_EXECUTOR, ExecutorService.class, injector);\n }", "public static void closeMASCaseManager(File caseManager) {\n\n FileWriter caseManagerWriter;\n try {\n caseManagerWriter = new FileWriter(caseManager, true);\n caseManagerWriter.write(\"}\\n\");\n caseManagerWriter.flush();\n caseManagerWriter.close();\n } catch (IOException e) {\n Logger logger = Logger\n .getLogger(\"CreateMASCaseManager.closeMASCaseManager\");\n logger.info(\"ERROR: There is a mistake closing caseManager file.\\n\");\n }\n\n }", "public void visitMethodInsn(int opcode, String owner, String name,\n String desc, boolean itf) {\n if (mv != null) {\n mv.visitMethodInsn(opcode, owner, name, desc, itf);\n }\n }", "private void checkAndAddLengths(final int... requiredLengths) {\n\t\tfor( final int length : requiredLengths ) {\n\t\t\tif( length < 0 ) {\n\t\t\t\tthrow new IllegalArgumentException(String.format(\"required length cannot be negative but was %d\",\n\t\t\t\t\tlength));\n\t\t\t}\n\t\t\tthis.requiredLengths.add(length);\n\t\t}\n\t}", "private boolean addonDependsOnReporting(Addon addon)\n {\n for (AddonDependency dep : addon.getDependencies())\n {\n if (dep.getDependency().equals(this.addon))\n {\n return true;\n }\n boolean subDep = addonDependsOnReporting(dep.getDependency());\n if (subDep)\n {\n return true;\n }\n }\n return false;\n }" ]
Call the Coverage Task.
[ "public GridCoverage2D call() {\n try {\n BufferedImage coverageImage = this.tiledLayer.createBufferedImage(\n this.tilePreparationInfo.getImageWidth(),\n this.tilePreparationInfo.getImageHeight());\n Graphics2D graphics = coverageImage.createGraphics();\n try {\n for (SingleTilePreparationInfo tileInfo: this.tilePreparationInfo.getSingleTiles()) {\n final TileTask task;\n if (tileInfo.getTileRequest() != null) {\n task = new SingleTileLoaderTask(\n tileInfo.getTileRequest(), this.errorImage, tileInfo.getTileIndexX(),\n tileInfo.getTileIndexY(), this.failOnError, this.registry, this.context);\n } else {\n task = new PlaceHolderImageTask(this.tiledLayer.getMissingTileImage(),\n tileInfo.getTileIndexX(), tileInfo.getTileIndexY());\n }\n Tile tile = task.call();\n if (tile.getImage() != null) {\n graphics.drawImage(tile.getImage(),\n tile.getxIndex() * this.tiledLayer.getTileSize().width,\n tile.getyIndex() * this.tiledLayer.getTileSize().height, null);\n }\n }\n } finally {\n graphics.dispose();\n }\n\n GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null);\n GeneralEnvelope gridEnvelope = new GeneralEnvelope(this.tilePreparationInfo.getMapProjection());\n gridEnvelope.setEnvelope(this.tilePreparationInfo.getGridCoverageOrigin().x,\n this.tilePreparationInfo.getGridCoverageOrigin().y,\n this.tilePreparationInfo.getGridCoverageMaxX(),\n this.tilePreparationInfo.getGridCoverageMaxY());\n return factory.create(this.tiledLayer.createCommonUrl(), coverageImage, gridEnvelope,\n null, null, null);\n } catch (Exception e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }" ]
[ "public static netbridge_vlan_binding[] get(nitro_service service, String name) throws Exception{\n\t\tnetbridge_vlan_binding obj = new netbridge_vlan_binding();\n\t\tobj.set_name(name);\n\t\tnetbridge_vlan_binding response[] = (netbridge_vlan_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void deliverTrackMetadataUpdate(int player, TrackMetadata metadata) {\n if (!getTrackMetadataListeners().isEmpty()) {\n final TrackMetadataUpdate update = new TrackMetadataUpdate(player, metadata);\n for (final TrackMetadataListener listener : getTrackMetadataListeners()) {\n try {\n listener.metadataChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering track metadata update to listener\", t);\n }\n }\n }\n }", "private void writeUserFieldDefinitions()\n {\n for (CustomField cf : m_sortedCustomFieldsList)\n {\n if (cf.getFieldType() != null && cf.getFieldType().getDataType() != null)\n {\n UDFTypeType udf = m_factory.createUDFTypeType();\n udf.setObjectId(Integer.valueOf(FieldTypeHelper.getFieldID(cf.getFieldType())));\n\n udf.setDataType(UserFieldDataType.inferUserFieldDataType(cf.getFieldType().getDataType()));\n udf.setSubjectArea(UserFieldDataType.inferUserFieldSubjectArea(cf.getFieldType()));\n udf.setTitle(cf.getAlias());\n m_apibo.getUDFType().add(udf);\n }\n }\n }", "@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 PhotoList<Photo> getUntagged(int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_UNTAGGED);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n PhotoList<Photo> photos = PhotoUtils.createPhotoList(photosElement);\r\n return photos;\r\n }", "@RequestMapping(value = \"/api/profile\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getList(Model model) throws Exception {\n logger.info(\"Using a GET request to list profiles\");\n return Utils.getJQGridJSON(profileService.findAllProfiles(), \"profiles\");\n }", "public synchronized void addRange(final float range, final GVRSceneObject sceneObject)\n {\n if (null == sceneObject) {\n throw new IllegalArgumentException(\"sceneObject must be specified!\");\n }\n if (range < 0) {\n throw new IllegalArgumentException(\"range cannot be negative\");\n }\n\n final int size = mRanges.size();\n final float rangePow2 = range*range;\n final Object[] newElement = new Object[] {rangePow2, sceneObject};\n\n for (int i = 0; i < size; ++i) {\n final Object[] el = mRanges.get(i);\n final Float r = (Float)el[0];\n if (r > rangePow2) {\n mRanges.add(i, newElement);\n break;\n }\n }\n\n if (mRanges.size() == size) {\n mRanges.add(newElement);\n }\n\n final GVRSceneObject owner = getOwnerObject();\n if (null != owner) {\n owner.addChildObject(sceneObject);\n }\n }", "public static DMatrixRMaj symmetric(int length, double min, double max, Random rand) {\n DMatrixRMaj A = new DMatrixRMaj(length,length);\n\n symmetric(A,min,max,rand);\n\n return A;\n }", "private void initXmlBundle() throws CmsException {\n\n CmsFile file = m_cms.readFile(m_resource);\n m_bundleFiles.put(null, m_resource);\n m_xmlBundle = CmsXmlContentFactory.unmarshal(m_cms, file);\n initKeySetForXmlBundle();\n\n }" ]
helper to calculate the navigationBar height @param context @return
[ "public static int getNavigationBarHeight(Context context) {\n Resources resources = context.getResources();\n int id = resources.getIdentifier(context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ? \"navigation_bar_height\" : \"navigation_bar_height_landscape\", \"dimen\", \"android\");\n if (id > 0) {\n return resources.getDimensionPixelSize(id);\n }\n return 0;\n }" ]
[ "public static Set<String> listAllLinks(OperationContext context, String overlay) {\n Set<String> serverGoupNames = listServerGroupsReferencingOverlay(context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS), overlay);\n Set<String> links = new HashSet<>();\n for (String serverGoupName : serverGoupNames) {\n links.addAll(listLinks(context, PathAddress.pathAddress(\n PathElement.pathElement(SERVER_GROUP, serverGoupName),\n PathElement.pathElement(DEPLOYMENT_OVERLAY, overlay))));\n }\n return links;\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 auditnslogpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditnslogpolicy_authenticationvserver_binding obj = new auditnslogpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauditnslogpolicy_authenticationvserver_binding response[] = (auditnslogpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public ContentAssistEntry createProposal(final String proposal, final ContentAssistContext context, final Procedure1<? super ContentAssistEntry> init) {\n return this.createProposal(proposal, context.getPrefix(), context, ContentAssistEntry.KIND_UNKNOWN, init);\n }", "public static String encodePath(String path, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(path, encoding, HierarchicalUriComponents.Type.PATH);\n\t}", "public static base_response update(nitro_service client, cacheselector resource) throws Exception {\n\t\tcacheselector updateresource = new cacheselector();\n\t\tupdateresource.selectorname = resource.selectorname;\n\t\tupdateresource.rule = resource.rule;\n\t\treturn updateresource.update_resource(client);\n\t}", "private static void checkPreconditions(final Map<Object, Object> mapping) {\n\t\tif( mapping == null ) {\n\t\t\tthrow new NullPointerException(\"mapping should not be null\");\n\t\t} else if( mapping.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"mapping should not be empty\");\n\t\t}\n\t}", "private static boolean typeEquals(ParameterizedType from,\n\t\t\tParameterizedType to, Map<String, Type> typeVarMap) {\n\t\tif (from.getRawType().equals(to.getRawType())) {\n\t\t\tType[] fromArgs = from.getActualTypeArguments();\n\t\t\tType[] toArgs = to.getActualTypeArguments();\n\t\t\tfor (int i = 0; i < fromArgs.length; i++) {\n\t\t\t\tif (!matches(fromArgs[i], toArgs[i], typeVarMap)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "public Integer getInteger(String fieldName) {\n\t\ttry {\n\t\t\treturn hasValue(fieldName) ? Integer.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a number.\", e);\n\t\t}\n\t}" ]
Return true if the DeclarationExpression represents a 'final' variable declaration. NOTE: THIS IS A WORKAROUND. There does not seem to be an easy way to determine whether the 'final' modifier has been specified for a variable declaration. Return true if the 'final' is present before the variable name.
[ "public static boolean isFinalVariable(DeclarationExpression declarationExpression, SourceCode sourceCode) {\r\n if (isFromGeneratedSourceCode(declarationExpression)) {\r\n return false;\r\n }\r\n List<Expression> variableExpressions = getVariableExpressions(declarationExpression);\r\n if (!variableExpressions.isEmpty()) {\r\n Expression variableExpression = variableExpressions.get(0);\r\n int startOfDeclaration = declarationExpression.getColumnNumber();\r\n int startOfVariableName = variableExpression.getColumnNumber();\r\n int sourceLineNumber = findFirstNonAnnotationLine(declarationExpression, sourceCode);\r\n String sourceLine = sourceCode.getLines().get(sourceLineNumber-1);\r\n\r\n String modifiers = (startOfDeclaration >= 0 && startOfVariableName >= 0 && sourceLine.length() >= startOfVariableName) ?\r\n sourceLine.substring(startOfDeclaration - 1, startOfVariableName - 1) : \"\";\r\n return modifiers.contains(\"final\");\r\n }\r\n return false;\r\n }" ]
[ "public BoxFile.Info upload(BoxAPIConnection boxApi, String folderId, InputStream stream, URL url,\n String fileName, long fileSize) throws InterruptedException, IOException {\n //Create a upload session\n BoxFileUploadSession.Info session = this.createUploadSession(boxApi, folderId, url, fileName, fileSize);\n return this.uploadHelper(session, stream, fileSize);\n }", "private SynchroTable readTableHeader(byte[] header)\n {\n SynchroTable result = null;\n String tableName = DatatypeConverter.getSimpleString(header, 0);\n if (!tableName.isEmpty())\n {\n int offset = DatatypeConverter.getInt(header, 40);\n result = new SynchroTable(tableName, offset);\n }\n return result;\n }", "private Integer mapTaskID(Integer id)\n {\n Integer mappedID = m_clashMap.get(id);\n if (mappedID == null)\n {\n mappedID = id;\n }\n return (mappedID);\n }", "public void writeTo(File file) throws IOException {\n FileChannel channel = new FileOutputStream(file).getChannel();\n try {\n writeTo(channel);\n } finally {\n channel.close();\n }\n }", "public static boolean isEasterSunday(LocalDate date) {\n\t\tint y = date.getYear();\n\t\tint a = y % 19;\n\t\tint b = y / 100;\n\t\tint c = y % 100;\n\t\tint d = b / 4;\n\t\tint e = b % 4;\n\t\tint f = (b + 8) / 25;\n\t\tint g = (b - f + 1) / 3;\n\t\tint h = (19 * a + b - d - g + 15) % 30;\n\t\tint i = c / 4;\n\t\tint k = c % 4;\n\t\tint l = (32 + 2 * e + 2 * i - h - k) % 7;\n\t\tint m = (a + 11 * h + 22 * l) / 451;\n\t\tint easterSundayMonth\t= (h + l - 7 * m + 114) / 31;\n\t\tint easterSundayDay\t\t= ((h + l - 7 * m + 114) % 31) + 1;\n\n\t\tint month = date.getMonthValue();\n\t\tint day = date.getDayOfMonth();\n\n\t\treturn (easterSundayMonth == month) && (easterSundayDay == day);\n\t}", "private static Point getScreenSize(Context context, Point p) {\n if (p == null) {\n p = new Point();\n }\n WindowManager windowManager = (WindowManager) context\n .getSystemService(Context.WINDOW_SERVICE);\n Display display = windowManager.getDefaultDisplay();\n display.getSize(p);\n return p;\n }", "@Override\n\tpublic Object getCurrentVersion(Serializable id, SharedSessionContractImplementor session) throws HibernateException {\n\n\t\tif ( log.isTraceEnabled() ) {\n\t\t\tlog.trace( \"Getting version: \" + MessageHelper.infoString( this, id, getFactory() ) );\n\t\t}\n\t\tfinal Tuple resultset = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );\n\n\t\tif ( resultset == null ) {\n\t\t\treturn null;\n\t\t}\n\t\telse {\n\t\t\treturn gridVersionType.nullSafeGet( resultset, getVersionColumnName(), session, null );\n\t\t}\n\t}", "@TargetApi(VERSION_CODES.KITKAT)\n public static void hideSystemUI(Activity activity) {\n // Set the IMMERSIVE flag.\n // Set the content to appear under the system bars so that the content\n // doesn't resize when the system bars hideSelf and show.\n View decorView = activity.getWindow().getDecorView();\n decorView.setSystemUiVisibility(\n View.SYSTEM_UI_FLAG_LAYOUT_STABLE\n | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION\n | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN\n | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hideSelf nav bar\n | View.SYSTEM_UI_FLAG_FULLSCREEN // hideSelf status bar\n | View.SYSTEM_UI_FLAG_IMMERSIVE\n );\n }", "public static DocumentBuilder getXmlParser() {\r\n DocumentBuilder db = null;\r\n try {\r\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\r\n dbf.setValidating(false);\r\n\r\n //Disable DTD loading and validation\r\n //See http://stackoverflow.com/questions/155101/make-documentbuilder-parse-ignore-dtd-references\r\n dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-dtd-grammar\", false);\r\n dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\r\n\r\n db = dbf.newDocumentBuilder();\r\n db.setErrorHandler(new SAXErrorHandler());\r\n\r\n } catch (ParserConfigurationException e) {\r\n System.err.printf(\"%s: Unable to create XML parser\\n\", XMLUtils.class.getName());\r\n e.printStackTrace();\r\n\r\n } catch(UnsupportedOperationException e) {\r\n System.err.printf(\"%s: API error while setting up XML parser. Check your JAXP version\\n\", XMLUtils.class.getName());\r\n e.printStackTrace();\r\n }\r\n\r\n return db;\r\n }" ]
Makes http GET request. @param url url to makes request to @param params data to add to params field @return {@link okhttp3.Response} @throws RequestException @throws LocalOperationException
[ "okhttp3.Response get(String url, Map<String, Object> params)\n throws RequestException, LocalOperationException {\n\n String fullUrl = getFullUrl(url);\n okhttp3.Request request = new okhttp3.Request.Builder()\n .url(addUrlParams(fullUrl, toPayload(params)))\n .addHeader(\"Transloadit-Client\", version)\n .build();\n\n try {\n return httpClient.newCall(request).execute();\n } catch (IOException e) {\n throw new RequestException(e);\n }\n }" ]
[ "private boolean operations(Options opt, ConstructorDoc m[]) {\n\tboolean printed = false;\n\tfor (ConstructorDoc cd : m) {\n\t if (hidden(cd))\n\t\tcontinue;\n\t stereotype(opt, cd, Align.LEFT);\n\t String cs = visibility(opt, cd) + cd.name() //\n\t\t + (opt.showType ? \"(\" + parameter(opt, cd.parameters()) + \")\" : \"()\");\n\t tableLine(Align.LEFT, cs);\n\t tagvalue(opt, cd);\n\t printed = true;\n\t}\n\treturn printed;\n }", "public static void symmetric(DMatrixRMaj A, double min, double max, Random rand) {\n if( A.numRows != A.numCols )\n throw new IllegalArgumentException(\"A must be a square matrix\");\n\n double range = max-min;\n\n int length = A.numRows;\n\n for( int i = 0; i < length; i++ ) {\n for( int j = i; j < length; j++ ) {\n double val = rand.nextDouble()*range + min;\n A.set(i,j,val);\n A.set(j,i,val);\n }\n }\n }", "public static int getNumberOfDependentLayers(String imageContent) throws IOException {\n JsonNode history = Utils.mapper().readTree(imageContent).get(\"history\");\n if (history == null) {\n throw new IllegalStateException(\"Could not find 'history' tag\");\n }\n\n int layersNum = history.size();\n boolean newImageLayers = true;\n for (int i = history.size() - 1; i >= 0; i--) {\n\n if (newImageLayers) {\n layersNum--;\n }\n\n JsonNode layer = history.get(i);\n JsonNode emptyLayer = layer.get(\"empty_layer\");\n if (!newImageLayers && emptyLayer != null) {\n layersNum--;\n }\n\n if (layer.get(\"created_by\") == null) {\n continue;\n }\n String createdBy = layer.get(\"created_by\").textValue();\n if (createdBy.contains(\"ENTRYPOINT\") || createdBy.contains(\"MAINTAINER\")) {\n newImageLayers = false;\n }\n }\n return layersNum;\n }", "@Override\n public View getDropDownView(int position, View convertView, ViewGroup parent) {\n final ViewHolder viewHolder;\n if (convertView == null) {\n convertView = mLayoutInflater.inflate(R.layout.item_country, parent, false);\n viewHolder = new ViewHolder();\n viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.intl_phone_edit__country__item_image);\n viewHolder.mNameView = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_name);\n viewHolder.mDialCode = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_dialcode);\n convertView.setTag(viewHolder);\n } else {\n viewHolder = (ViewHolder) convertView.getTag();\n }\n\n Country country = getItem(position);\n viewHolder.mImageView.setImageResource(getFlagResource(country));\n viewHolder.mNameView.setText(country.getName());\n viewHolder.mDialCode.setText(String.format(\"+%s\", country.getDialCode()));\n return convertView;\n }", "public boolean hasPossibleMethod(String name, Expression arguments) {\n int count = 0;\n\n if (arguments instanceof TupleExpression) {\n TupleExpression tuple = (TupleExpression) arguments;\n // TODO this won't strictly be true when using list expansion in argument calls\n count = tuple.getExpressions().size();\n }\n ClassNode node = this;\n do {\n for (MethodNode method : getMethods(name)) {\n if (method.getParameters().length == count && !method.isStatic()) {\n return true;\n }\n }\n node = node.getSuperClass();\n }\n while (node != null);\n return false;\n }", "public static Map<String, Map<String, Metadata>> parseAndPopulateMetadataMap(JsonObject jsonObject) {\n Map<String, Map<String, Metadata>> metadataMap = new HashMap<String, Map<String, Metadata>>();\n //Parse all templates\n for (JsonObject.Member templateMember : jsonObject) {\n if (templateMember.getValue().isNull()) {\n continue;\n } else {\n String templateName = templateMember.getName();\n Map<String, Metadata> scopeMap = metadataMap.get(templateName);\n //If templateName doesn't yet exist then create an entry with empty scope map\n if (scopeMap == null) {\n scopeMap = new HashMap<String, Metadata>();\n metadataMap.put(templateName, scopeMap);\n }\n //Parse all scopes in a template\n for (JsonObject.Member scopeMember : templateMember.getValue().asObject()) {\n String scope = scopeMember.getName();\n Metadata metadataObject = new Metadata(scopeMember.getValue().asObject());\n scopeMap.put(scope, metadataObject);\n }\n }\n\n }\n return metadataMap;\n }", "public 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 static <T> void write(BufferedWriter writer, DatabaseTableConfig<T> config) throws SQLException {\n\t\ttry {\n\t\t\twriteConfig(writer, config);\n\t\t} catch (IOException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Could not write config to writer\", e);\n\t\t}\n\t}", "public static base_response update(nitro_service client, vserver resource) throws Exception {\n\t\tvserver updateresource = new vserver();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.backupvserver = resource.backupvserver;\n\t\tupdateresource.redirecturl = resource.redirecturl;\n\t\tupdateresource.cacheable = resource.cacheable;\n\t\tupdateresource.clttimeout = resource.clttimeout;\n\t\tupdateresource.somethod = resource.somethod;\n\t\tupdateresource.sopersistence = resource.sopersistence;\n\t\tupdateresource.sopersistencetimeout = resource.sopersistencetimeout;\n\t\tupdateresource.sothreshold = resource.sothreshold;\n\t\tupdateresource.pushvserver = resource.pushvserver;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
A convenience method for creating an immutable list @param self a List @return an immutable List @see java.util.Collections#unmodifiableList(java.util.List) @since 1.0
[ "public static <T> List<T> asImmutable(List<? extends T> self) {\n return Collections.unmodifiableList(self);\n }" ]
[ "private boolean isToIgnore(CtElement element) {\n\t\tif (element instanceof CtStatementList && !(element instanceof CtCase)) {\n\t\t\tif (element.getRoleInParent() == CtRole.ELSE || element.getRoleInParent() == CtRole.THEN) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn element.isImplicit() || element instanceof CtReference;\n\t}", "protected List<Versioned<V>> resolveAndConstructVersionsToPersist(List<Versioned<V>> valuesInStorage,\n List<Versioned<V>> multiPutValues) {\n List<Versioned<V>> obsoleteVals = new ArrayList<Versioned<V>>(multiPutValues.size());\n // Go over all the values and determine whether the version is\n // acceptable\n for(Versioned<V> value: multiPutValues) {\n Iterator<Versioned<V>> iter = valuesInStorage.iterator();\n boolean obsolete = false;\n // Compare the current version with a set of accepted versions\n while(iter.hasNext()) {\n Versioned<V> curr = iter.next();\n Occurred occurred = value.getVersion().compare(curr.getVersion());\n if(occurred == Occurred.BEFORE) {\n obsolete = true;\n break;\n } else if(occurred == Occurred.AFTER) {\n iter.remove();\n }\n }\n if(obsolete) {\n // add to return value if obsolete\n obsoleteVals.add(value);\n } else {\n // else update the set of accepted versions\n valuesInStorage.add(value);\n }\n }\n\n return obsoleteVals;\n }", "protected void handleRequestOut(T message) throws Fault {\n String flowId = FlowIdHelper.getFlowId(message);\n if (flowId == null\n && message.containsKey(PhaseInterceptorChain.PREVIOUS_MESSAGE)) {\n // Web Service consumer is acting as an intermediary\n @SuppressWarnings(\"unchecked\")\n WeakReference<Message> wrPreviousMessage = (WeakReference<Message>) message\n .get(PhaseInterceptorChain.PREVIOUS_MESSAGE);\n Message previousMessage = (Message) wrPreviousMessage.get();\n flowId = FlowIdHelper.getFlowId(previousMessage);\n if (flowId != null && LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"flowId '\" + flowId + \"' found in previous message\");\n }\n }\n\n if (flowId == null) {\n // No flowId found. Generate one.\n flowId = ContextUtils.generateUUID();\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Generate new flowId '\" + flowId + \"'\");\n }\n }\n\n FlowIdHelper.setFlowId(message, flowId);\n }", "private int getColorWaveformBits(final ByteBuffer waveBytes, final int segment) {\n final int base = (segment * 2);\n final int big = Util.unsign(waveBytes.get(base));\n final int small = Util.unsign(waveBytes.get(base + 1));\n return big * 256 + small;\n }", "protected void recycleChildren() {\n for (ListItemHostWidget host: getAllHosts()) {\n recycle(host);\n }\n mContent.onTransformChanged();\n mContent.requestLayout();\n }", "public SimplifySpanBuild appendMultiClickable(SpecialClickableUnit specialClickableUnit, Object... specialUnitOrStrings) {\n processMultiClickableSpecialUnit(false, specialClickableUnit, specialUnitOrStrings);\n return this;\n }", "@Override\n public void detachScriptFile(IScriptable target) {\n IScriptFile scriptFile = mScriptMap.remove(target);\n if (scriptFile != null) {\n scriptFile.invokeFunction(\"onDetach\", new Object[] { target });\n }\n }", "public Diff compare(CtElement left, CtElement right) {\n\t\tfinal SpoonGumTreeBuilder scanner = new SpoonGumTreeBuilder();\n\t\treturn new DiffImpl(scanner.getTreeContext(), scanner.getTree(left), scanner.getTree(right));\n\t}", "public static void startTimer(final String type) {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return;\n }\n\n instance.components.putIfAbsent(type, new Component(type));\n instance.components.get(type).startTimer();\n }" ]
Convert the Phoenix representation of a duration into a Duration instance. @param value Phoenix duration @return Duration instance
[ "public static final Duration parseDuration(String value)\n {\n Duration result = null;\n if (value != null)\n {\n int split = value.indexOf(' ');\n if (split != -1)\n {\n double durationValue = Double.parseDouble(value.substring(0, split));\n TimeUnit durationUnits = parseTimeUnits(value.substring(split + 1));\n\n result = Duration.getInstance(durationValue, durationUnits);\n\n }\n }\n return result;\n }" ]
[ "public float rotateToFaceCamera(final Widget widget) {\n final float yaw = getMainCameraRigYaw();\n GVRTransform t = getMainCameraRig().getHeadTransform();\n widget.rotateWithPivot(t.getRotationW(), 0, t.getRotationY(), 0, 0, 0, 0);\n return yaw;\n }", "public static int getNumberOfDependentLayers(String imageContent) throws IOException {\n JsonNode history = Utils.mapper().readTree(imageContent).get(\"history\");\n if (history == null) {\n throw new IllegalStateException(\"Could not find 'history' tag\");\n }\n\n int layersNum = history.size();\n boolean newImageLayers = true;\n for (int i = history.size() - 1; i >= 0; i--) {\n\n if (newImageLayers) {\n layersNum--;\n }\n\n JsonNode layer = history.get(i);\n JsonNode emptyLayer = layer.get(\"empty_layer\");\n if (!newImageLayers && emptyLayer != null) {\n layersNum--;\n }\n\n if (layer.get(\"created_by\") == null) {\n continue;\n }\n String createdBy = layer.get(\"created_by\").textValue();\n if (createdBy.contains(\"ENTRYPOINT\") || createdBy.contains(\"MAINTAINER\")) {\n newImageLayers = false;\n }\n }\n return layersNum;\n }", "private Profile getProfileFromResultSet(ResultSet result) throws Exception {\n Profile profile = new Profile();\n profile.setId(result.getInt(Constants.GENERIC_ID));\n Clob clobProfileName = result.getClob(Constants.PROFILE_PROFILE_NAME);\n String profileName = clobProfileName.getSubString(1, (int) clobProfileName.length());\n profile.setName(profileName);\n return profile;\n }", "@Override\n\tpublic boolean isSinglePrefixBlock() {\n\t\tInteger networkPrefixLength = getNetworkPrefixLength();\n\t\tif(networkPrefixLength == null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn containsSinglePrefixBlock(networkPrefixLength);\n\t}", "public Set<? extends Processor<?, ?>> getAllProcessors() {\n IdentityHashMap<Processor<?, ?>, Void> all = new IdentityHashMap<>();\n all.put(this.getProcessor(), null);\n for (ProcessorGraphNode<?, ?> dependency: this.dependencies) {\n for (Processor<?, ?> p: dependency.getAllProcessors()) {\n all.put(p, null);\n }\n }\n return all.keySet();\n }", "public Where<T, ID> ge(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.GREATER_THAN_EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}", "public void setControllerModel(GVRSceneObject controllerModel)\n {\n if (mControllerModel != null)\n {\n mControllerGroup.removeChildObject(mControllerModel);\n }\n mControllerModel = controllerModel;\n mControllerGroup.addChildObject(mControllerModel);\n mControllerModel.setEnable(mShowControllerModel);\n }", "protected List<TransformationDescription> buildChildren() {\n if(children.isEmpty()) {\n return Collections.emptyList();\n }\n final List<TransformationDescription> children = new ArrayList<TransformationDescription>();\n for(final TransformationDescriptionBuilder builder : this.children) {\n children.add(builder.build());\n }\n return children;\n }", "public void removeHoursFromDay(ProjectCalendarHours hours)\n {\n if (hours.getParentCalendar() != this)\n {\n throw new IllegalArgumentException();\n }\n m_hours[hours.getDay().getValue() - 1] = null;\n }" ]
Parse a string representation of password spec. A password spec string should be `<trait spec><length spec>`. Where "trait spec" should be a composition of * `a` - indicate lowercase letter required * `A` - indicate uppercase letter required * `0` - indicate digit letter required * `#` - indicate special character required "length spec" should be `[min,max]` where `max` can be omitted. Here are examples of valid "length spec": * `[6,20]` // min length: 6, max length: 20 * `[8,]` // min length: 8, max length: unlimited And examples of invalid "length spec": * `[8]` // "," required after min part * `[a,f]` // min and max part needs to be decimal digit(s) * `[3,9)` // length spec must be started with `[` and end with `]` @param spec a string representation of password spec @return a {@link PasswordSpec} instance
[ "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 nssimpleacl[] get(nitro_service service) throws Exception{\n\t\tnssimpleacl obj = new nssimpleacl();\n\t\tnssimpleacl[] response = (nssimpleacl[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private Long string2long(String text, DateTimeFormat fmt) {\n \n // null or \"\" returns null\n if (text == null) return null;\n text = text.trim();\n if (text.length() == 0) return null;\n \n Date date = fmt.parse(text);\n return date != null ? UTCDateBox.date2utc(date) : null;\n }", "public static filterpolicy_csvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tfilterpolicy_csvserver_binding obj = new filterpolicy_csvserver_binding();\n\t\tobj.set_name(name);\n\t\tfilterpolicy_csvserver_binding response[] = (filterpolicy_csvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void scale(double v){\n\t\tfor(int i = 0; i < this.size(); i++){\n\t\t\tthis.get(i).scale(v);;\n\t\t}\n\t}", "public void setAmbientIntensity(float r, float g, float b, float a) {\n setVec4(\"ambient_intensity\", r, g, b, a);\n }", "private void readRelation(Relationship relation)\n {\n Task predecessor = m_activityMap.get(relation.getPredecessor());\n Task successor = m_activityMap.get(relation.getSuccessor());\n if (predecessor != null && successor != null)\n {\n Duration lag = relation.getLag();\n RelationType type = relation.getType();\n successor.addPredecessor(predecessor, type, lag);\n }\n }", "public CollectionRequest<Attachment> findByTask(String task) {\n \n String path = String.format(\"/tasks/%s/attachments\", task);\n return new CollectionRequest<Attachment>(this, Attachment.class, path, \"GET\");\n }", "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 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}" ]
Adopts an xml dom element to the owner document of this element if necessary. @param elementToAdopt the element to adopt
[ "protected void adoptElement(DomXmlElement elementToAdopt) {\n Document document = this.domElement.getOwnerDocument();\n Element element = elementToAdopt.domElement;\n\n if (!document.equals(element.getOwnerDocument())) {\n Node node = document.adoptNode(element);\n if (node == null) {\n throw LOG.unableToAdoptElement(elementToAdopt);\n }\n }\n }" ]
[ "public static DMatrixRMaj symmetric(int length, double min, double max, Random rand) {\n DMatrixRMaj A = new DMatrixRMaj(length,length);\n\n symmetric(A,min,max,rand);\n\n return A;\n }", "private synchronized Response doAuthenticatedRequest(\n final StitchAuthRequest stitchReq,\n final AuthInfo authInfo\n ) {\n try {\n return requestClient.doRequest(prepareAuthRequest(stitchReq, authInfo));\n } catch (final StitchServiceException ex) {\n return handleAuthFailure(ex, stitchReq);\n }\n }", "@Subscribe\n public void onQuit(AggregatedQuitEvent e) {\n if (jsonWriter == null)\n return;\n\n try {\n jsonWriter.endArray();\n\n jsonWriter.name(\"slaves\");\n jsonWriter.beginObject();\n for (Map.Entry<Integer, ForkedJvmInfo> entry : slaves.entrySet()) {\n jsonWriter.name(Integer.toString(entry.getKey()));\n entry.getValue().serialize(jsonWriter);\n }\n jsonWriter.endObject();\n\n jsonWriter.endObject();\n jsonWriter.flush();\n\n if (!Strings.isNullOrEmpty(jsonpMethod)) {\n writer.write(\");\");\n }\n\n jsonWriter.close();\n jsonWriter = null;\n writer = null;\n\n if (method == OutputMethod.HTML) {\n copyScaffolding(targetFile);\n }\n } catch (IOException x) {\n junit4.log(x, Project.MSG_ERR);\n }\n }", "private void processCalendarException(ProjectCalendar calendar, Row row)\n {\n Date fromDate = row.getDate(\"CD_FROM_DATE\");\n Date toDate = row.getDate(\"CD_TO_DATE\");\n boolean working = row.getInt(\"CD_WORKING\") != 0;\n ProjectCalendarException exception = calendar.addCalendarException(fromDate, toDate);\n if (working)\n {\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME1\"), row.getDate(\"CD_TO_TIME1\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME2\"), row.getDate(\"CD_TO_TIME2\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME3\"), row.getDate(\"CD_TO_TIME3\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME4\"), row.getDate(\"CD_TO_TIME4\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME5\"), row.getDate(\"CD_TO_TIME5\")));\n }\n }", "public static audit_stats get(nitro_service service, options option) throws Exception{\n\t\taudit_stats obj = new audit_stats();\n\t\taudit_stats[] response = (audit_stats[])obj.stat_resources(service,option);\n\t\treturn response[0];\n\t}", "public int getCount(Class target)\r\n {\r\n PersistenceBroker broker = ((HasBroker) odmg.currentTransaction()).getBroker();\r\n int result = broker.getCount(new QueryByCriteria(target));\r\n return result;\r\n }", "public static DeploymentReflectionIndex create() {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(ServerPermission.CREATE_DEPLOYMENT_REFLECTION_INDEX);\n }\n return new DeploymentReflectionIndex();\n }", "@GuardedBy(\"elementsLock\")\n\t@Override\n\tpublic boolean markChecked(CandidateElement element) {\n\t\tString generalString = element.getGeneralString();\n\t\tString uniqueString = element.getUniqueString();\n\t\tsynchronized (elementsLock) {\n\t\t\tif (elements.contains(uniqueString)) {\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\telements.add(generalString);\n\t\t\t\telements.add(uniqueString);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}", "private void purgeDeadJobInstances(DbConn cnx, Node node)\n {\n for (JobInstance ji : JobInstance.select(cnx, \"ji_select_by_node\", node.getId()))\n {\n try\n {\n cnx.runSelectSingle(\"history_select_state_by_id\", String.class, ji.getId());\n }\n catch (NoResultException e)\n {\n History.create(cnx, ji, State.CRASHED, Calendar.getInstance());\n Message.create(cnx,\n \"Job was supposed to be running at server startup - usually means it was killed along a server by an admin or a crash\",\n ji.getId());\n }\n\n cnx.runUpdate(\"ji_delete_by_id\", ji.getId());\n }\n cnx.commit();\n }" ]
Init the licenses cache @param licenses
[ "private void init(final List<DbLicense> licenses) {\n licensesRegexp.clear();\n\n for (final DbLicense license : licenses) {\n if (license.getRegexp() == null ||\n license.getRegexp().isEmpty()) {\n licensesRegexp.put(license.getName(), license);\n } else {\n licensesRegexp.put(license.getRegexp(), license);\n }\n }\n }" ]
[ "protected void animateOffsetTo(int position, int velocity, boolean animate) {\n endDrag();\n endPeek();\n\n final int startX = (int) mOffsetPixels;\n final int dx = position - startX;\n if (dx == 0 || !animate) {\n setOffsetPixels(position);\n setDrawerState(position == 0 ? STATE_CLOSED : STATE_OPEN);\n stopLayerTranslation();\n return;\n }\n\n int duration;\n\n velocity = Math.abs(velocity);\n if (velocity > 0) {\n duration = 4 * Math.round(1000.f * Math.abs((float) dx / velocity));\n } else {\n duration = (int) (600.f * Math.abs((float) dx / mMenuSize));\n }\n\n duration = Math.min(duration, mMaxAnimationDuration);\n animateOffsetTo(position, duration);\n }", "public 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}", "@SuppressWarnings(\"rawtypes\")\n\tprivate MailInboundChannelAdapterSpec getImapFlowBuilder(URLName urlName) {\n\t\treturn Mail.imapInboundAdapter(urlName.toString())\n\t\t\t\t.shouldMarkMessagesAsRead(this.properties.isMarkAsRead());\n\t}", "public static base_responses create(nitro_service client, sslfipskey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslfipskey createresources[] = new sslfipskey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tcreateresources[i] = new sslfipskey();\n\t\t\t\tcreateresources[i].fipskeyname = resources[i].fipskeyname;\n\t\t\t\tcreateresources[i].modulus = resources[i].modulus;\n\t\t\t\tcreateresources[i].exponent = resources[i].exponent;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, createresources,\"create\");\n\t\t}\n\t\treturn result;\n\t}", "public static long count(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_vlan_binding obj = new bridgegroup_vlan_binding();\n\t\tobj.set_id(id);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tbridgegroup_vlan_binding response[] = (bridgegroup_vlan_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}", "void writeInterPropertyLinks(PropertyDocument document)\n\t\t\tthrows RDFHandlerException {\n\t\tResource subject = this.rdfWriter.getUri(document.getEntityId()\n\t\t\t\t.getIri());\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_DIRECT_CLAIM_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.DIRECT));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_CLAIM_PROP), Vocabulary.getPropertyUri(\n\t\t\t\tdocument.getEntityId(), PropertyContext.STATEMENT));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_STATEMENT_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.VALUE_SIMPLE));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_STATEMENT_VALUE_PROP),\n\t\t\t\tVocabulary.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.VALUE));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_QUALIFIER_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.QUALIFIER_SIMPLE));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_QUALIFIER_VALUE_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.QUALIFIER));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_REFERENCE_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.REFERENCE_SIMPLE));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_REFERENCE_VALUE_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.REFERENCE));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_NO_VALUE_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.NO_VALUE));\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_NO_QUALIFIER_VALUE_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.NO_QUALIFIER_VALUE));\n\t\t// TODO something more with NO_VALUE\n\t}", "public static String normalizeWS(String value) {\n char[] tmp = new char[value.length()];\n int pos = 0;\n boolean prevws = false;\n for (int ix = 0; ix < tmp.length; ix++) {\n char ch = value.charAt(ix);\n if (ch != ' ' && ch != '\\t' && ch != '\\n' && ch != '\\r') {\n if (prevws && pos != 0)\n tmp[pos++] = ' ';\n\n tmp[pos++] = ch;\n prevws = false;\n } else\n prevws = true;\n }\n return new String(tmp, 0, pos);\n }", "public synchronized X509Certificate getMappedCertificate(final X509Certificate cert)\n\tthrows CertificateEncodingException,\n\tInvalidKeyException,\n\tCertificateException,\n\tCertificateNotYetValidException,\n\tNoSuchAlgorithmException,\n\tNoSuchProviderException,\n\tSignatureException,\n\tKeyStoreException,\n\tUnrecoverableKeyException\n\t{\n\n\t\tString thumbprint = ThumbprintUtil.getThumbprint(cert);\n\n\t\tString mappedCertThumbprint = _certMap.get(thumbprint);\n\n\t\tif(mappedCertThumbprint == null)\n\t\t{\n\n\t\t\t// Check if we've already mapped this public key from a KeyValue\n\t\t\tPublicKey mappedPk = getMappedPublicKey(cert.getPublicKey());\n\t\t\tPrivateKey privKey;\n\n\t\t\tif(mappedPk == null)\n\t\t\t{\n\t\t\t\tPublicKey pk = cert.getPublicKey();\n\n\t\t\t\tString algo = pk.getAlgorithm();\n\n\t\t\t\tKeyPair kp;\n\n\t\t\t\tif(algo.equals(\"RSA\")) {\n\t\t\t\t\tkp = getRSAKeyPair();\n\t\t\t\t}\n\t\t\t\telse if(algo.equals(\"DSA\")) {\n\t\t\t\t\tkp = getDSAKeyPair();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tthrow new InvalidKeyException(\"Key algorithm \" + algo + \" not supported.\");\n\t\t\t\t}\n\t\t\t\tmappedPk = kp.getPublic();\n\t\t\t\tprivKey = kp.getPrivate();\n\n\t\t\t\tmapPublicKeys(cert.getPublicKey(), mappedPk);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprivKey = getPrivateKey(mappedPk);\n\t\t\t}\n\n\n\t\t\tX509Certificate replacementCert =\n\t\t\t\tCertificateCreator.mitmDuplicateCertificate(\n\t\t\t\t\t\tcert,\n\t\t\t\t\t\tmappedPk,\n\t\t\t\t\t\tgetSigningCert(),\n\t\t\t\t\t\tgetSigningPrivateKey());\n\n\t\t\taddCertAndPrivateKey(null, replacementCert, privKey);\n\n\t\t\tmappedCertThumbprint = ThumbprintUtil.getThumbprint(replacementCert);\n\n\t\t\t_certMap.put(thumbprint, mappedCertThumbprint);\n\t\t\t_certMap.put(mappedCertThumbprint, thumbprint);\n\t\t\t_subjectMap.put(replacementCert.getSubjectX500Principal().getName(), thumbprint);\n\n\t\t\tif(persistImmediately) {\n\t\t\t\tpersist();\n\t\t\t}\n\t\t\treturn replacementCert;\n\t\t}\n return getCertificateByAlias(mappedCertThumbprint);\n\n\t}", "@SuppressWarnings(\"deprecation\")\n private final void operationTimeout() {\n\n /**\n * first kill async http worker; before suicide LESSON: MUST KILL AND\n * WAIT FOR CHILDREN to reply back before kill itself.\n */\n cancelCancellable();\n if (asyncWorker != null && !asyncWorker.isTerminated()) {\n asyncWorker\n .tell(RequestWorkerMsgType.PROCESS_ON_TIMEOUT, getSelf());\n\n } else {\n logger.info(\"asyncWorker has been killed or uninitialized (null). \"\n + \"Not send PROCESS ON TIMEOUT.\\nREQ: \"\n + request.toString());\n replyErrors(PcConstants.OPERATION_TIMEOUT,\n PcConstants.OPERATION_TIMEOUT, PcConstants.NA,\n PcConstants.NA_INT);\n }\n\n }" ]
Converts the suggestions from the Solrj format to JSON format. @param response The SpellCheckResponse object containing the spellcheck results. @return The spellcheck suggestions as JSON object or null if something goes wrong.
[ "private JSONObject getConvertedResponseAsJson(SpellCheckResponse response) {\n\n if (null == response) {\n return null;\n }\n\n final JSONObject suggestions = new JSONObject();\n final Map<String, Suggestion> solrSuggestions = response.getSuggestionMap();\n\n // Add suggestions to the response\n for (final String key : solrSuggestions.keySet()) {\n\n // Indicator to ignore words that are erroneously marked as misspelled.\n boolean ignoreWord = false;\n\n // Suggestions that are in the form \"Xxxx\" -> \"xxxx\" should be ignored.\n if (Character.isUpperCase(key.codePointAt(0))) {\n final String lowercaseKey = key.toLowerCase();\n // If the suggestion map doesn't contain the lowercased word, ignore this entry.\n if (!solrSuggestions.containsKey(lowercaseKey)) {\n ignoreWord = true;\n }\n }\n\n if (!ignoreWord) {\n try {\n // Get suggestions as List\n final List<String> l = solrSuggestions.get(key).getAlternatives();\n suggestions.put(key, l);\n } catch (JSONException e) {\n LOG.debug(\"Exception while converting Solr spellcheckresponse to JSON. \", e);\n }\n }\n }\n\n return suggestions;\n }" ]
[ "public static base_response change(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey updateresource = new sslcertkey();\n\t\tupdateresource.certkey = resource.certkey;\n\t\tupdateresource.cert = resource.cert;\n\t\tupdateresource.key = resource.key;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.fipskey = resource.fipskey;\n\t\tupdateresource.inform = resource.inform;\n\t\tupdateresource.passplain = resource.passplain;\n\t\tupdateresource.nodomaincheck = resource.nodomaincheck;\n\t\treturn updateresource.perform_operation(client,\"update\");\n\t}", "public void rollback() throws GitAPIException {\n try (Git git = getGit()) {\n git.reset().setMode(ResetCommand.ResetType.HARD).setRef(HEAD).call();\n }\n }", "@SuppressWarnings(\"unchecked\")\n public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n List<String> metaKeys = null;\n String url = null;\n\n // parse command-line input\n args = AdminToolUtils.copyArrayAddFirst(args, \"--\" + OPT_HEAD_META_CHECK);\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, OPT_HEAD_META_CHECK);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n\n // load parameters\n metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_CHECK);\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n\n\n // execute command\n if(metaKeys.size() == 0\n || (metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL))) {\n metaKeys = Lists.newArrayList();\n metaKeys.add(MetadataStore.CLUSTER_KEY);\n metaKeys.add(MetadataStore.STORES_KEY);\n metaKeys.add(MetadataStore.SERVER_STATE_KEY);\n }\n\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n doMetaCheck(adminClient, metaKeys);\n }", "private ProjectFile readProjectFile(ProjectReader reader, File file) throws MPXJException\n {\n addListeners(reader);\n return reader.read(file);\n }", "public void addOrder(String columnName, boolean ascending) {\n if (columnName == null) {\n return;\n }\n for (int i = 0; i < columns.size(); i++) {\n if (!columnName.equals(columns.get(i).getData())) {\n continue;\n }\n order.add(new Order(i, ascending ? \"asc\" : \"desc\"));\n }\n }", "public static servicegroup_stats[] get(nitro_service service, options option) throws Exception{\n\t\tservicegroup_stats obj = new servicegroup_stats();\n\t\tservicegroup_stats[] response = (servicegroup_stats[])obj.stat_resources(service,option);\n\t\treturn response;\n\t}", "private GeometryCoordinateSequenceTransformer getTransformer() {\n\t\tif (unitToPixel == null) {\n\t\t\tunitToPixel = new GeometryCoordinateSequenceTransformer();\n\t\t\tunitToPixel.setMathTransform(ProjectiveTransform.create(new AffineTransform(scale, 0, 0, -scale, -scale\n\t\t\t\t\t* panOrigin.x, scale * panOrigin.y)));\n\t\t}\n\t\treturn unitToPixel;\n\t}", "public FieldType getFieldTypeFromVarDataKey(Integer key)\n {\n FieldType result = null;\n for (Entry<FieldType, FieldMap.FieldItem> entry : m_map.entrySet())\n {\n if (entry.getValue().getFieldLocation() == FieldLocation.VAR_DATA && entry.getValue().getVarDataKey().equals(key))\n {\n result = entry.getKey();\n break;\n }\n }\n return result;\n }", "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}" ]
Creates a map of metadata from json. @param jsonObject metadata json object for metadata field in get /files?fileds=,etadata.scope.template response @return Map of String as key a value another Map with a String key and Metadata value
[ "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 void checkConstraints(String checkLevel) throws ConstraintException\r\n {\r\n // check constraints now after all classes have been processed\r\n for (Iterator it = getClasses(); it.hasNext();)\r\n {\r\n ((ClassDescriptorDef)it.next()).checkConstraints(checkLevel);\r\n }\r\n // additional model constraints that either deal with bigger parts of the model or\r\n // can only be checked after the individual classes have been checked (e.g. specific\r\n // attributes have been ensured)\r\n new ModelConstraints().check(this, checkLevel);\r\n }", "boolean applyDomainModel(ModelNode result) {\n if(! result.hasDefined(ModelDescriptionConstants.RESULT)) {\n return false;\n }\n final List<ModelNode> bootOperations= result.get(ModelDescriptionConstants.RESULT).asList();\n return callback.applyDomainModel(bootOperations);\n }", "private void readPage(byte[] buffer, Table table)\n {\n int magicNumber = getShort(buffer, 0);\n if (magicNumber == 0x4400)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, 0, 6, true, 16, \"\"));\n int recordSize = m_definition.getRecordSize();\n RowValidator rowValidator = m_definition.getRowValidator();\n String primaryKeyColumnName = m_definition.getPrimaryKeyColumnName();\n\n int index = 6;\n while (index + recordSize <= buffer.length)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, index, recordSize, true, 16, \"\"));\n int btrieveValue = getShort(buffer, index);\n if (btrieveValue != 0)\n {\n Map<String, Object> row = new HashMap<String, Object>();\n row.put(\"ROW_VERSION\", Integer.valueOf(btrieveValue));\n for (ColumnDefinition column : m_definition.getColumns())\n {\n Object value = column.read(index, buffer);\n //System.out.println(column.getName() + \": \" + value);\n row.put(column.getName(), value);\n }\n\n if (rowValidator == null || rowValidator.validRow(row))\n {\n table.addRow(primaryKeyColumnName, row);\n }\n }\n index += recordSize;\n }\n }\n }", "public Filter geoSearch(String value) {\n GeopositionComparator comp = (GeopositionComparator) prop.getComparator();\n double dist = comp.getMaxDistance();\n double degrees = DistanceUtils.dist2Degrees(dist, DistanceUtils.EARTH_MEAN_RADIUS_KM * 1000.0);\n Shape circle = spatialctx.makeCircle(parsePoint(value), degrees);\n SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);\n return strategy.makeFilter(args);\n }", "private boolean isPacketLongEnough(DatagramPacket packet, int expectedLength, String name) {\n final int length = packet.getLength();\n if (length < expectedLength) {\n logger.warn(\"Ignoring too-short \" + name + \" packet; expecting \" + expectedLength + \" bytes and got \" +\n length + \".\");\n return false;\n }\n\n if (length > expectedLength) {\n logger.warn(\"Processing too-long \" + name + \" packet; expecting \" + expectedLength +\n \" bytes and got \" + length + \".\");\n }\n\n return true;\n }", "public static List<DockerImage> getDockerImagesFromAgents(final int buildInfoId, TaskListener listener) throws IOException, InterruptedException {\n List<DockerImage> dockerImages = new ArrayList<DockerImage>();\n\n // Collect images from the master:\n dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));\n\n // Collect images from all the agents:\n List<Node> nodes = Jenkins.getInstance().getNodes();\n for (Node node : nodes) {\n if (node == null || node.getChannel() == null) {\n continue;\n }\n try {\n List<DockerImage> partialDockerImages = node.getChannel().call(new MasterToSlaveCallable<List<DockerImage>, IOException>() {\n public List<DockerImage> call() throws IOException {\n List<DockerImage> dockerImages = new ArrayList<DockerImage>();\n dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));\n return dockerImages;\n }\n });\n dockerImages.addAll(partialDockerImages);\n } catch (Exception e) {\n listener.getLogger().println(\"Could not collect docker images from Jenkins node '\" + node.getDisplayName() + \"' due to: \" + e.getMessage());\n }\n }\n return dockerImages;\n }", "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 void afterMaterialization(IndirectionHandler handler, Object materializedObject)\r\n {\r\n try\r\n {\r\n Identity oid = handler.getIdentity();\r\n if (log.isDebugEnabled())\r\n log.debug(\"deferred registration: \" + oid);\r\n if(!isOpen())\r\n {\r\n log.error(\"Proxy object materialization outside of a running tx, obj=\" + oid);\r\n try{throw new Exception(\"Proxy object materialization outside of a running tx, obj=\" + oid);}catch(Exception e)\r\n {\r\n e.printStackTrace();\r\n }\r\n }\r\n ClassDescriptor cld = getBroker().getClassDescriptor(materializedObject.getClass());\r\n RuntimeObject rt = new RuntimeObject(materializedObject, oid, cld, false, false);\r\n lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList());\r\n }\r\n catch (Throwable t)\r\n {\r\n log.error(\"Register materialized object with this tx failed\", t);\r\n throw new LockNotGrantedException(t.getMessage());\r\n }\r\n unregisterFromIndirectionHandler(handler);\r\n }", "public static csvserver_spilloverpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_spilloverpolicy_binding obj = new csvserver_spilloverpolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_spilloverpolicy_binding response[] = (csvserver_spilloverpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Updates the terms and statements of the current document. The updates are computed with respect to the current data in the document, making sure that no redundant deletions or duplicate insertions happen. The references of duplicate statements will be merged. The labels and aliases in a given language are kept distinct. @param currentDocument the document to be updated; needs to have a correct revision id and entity id @param addLabels labels to be set on the item. They will overwrite existing values in the same language. @param addDescriptions description to be set on the item. They will overwrite existing values in the same language. @param addAliases aliases to be added. Existing aliases will be kept. @param deleteAliases aliases to be deleted. @param addStatements the list of statements to be added or updated; statements with empty statement id will be added; statements with non-empty statement id will be updated (if such a statement exists) @param deleteStatements the list of statements to be deleted; statements will only be deleted if they are present in the current document (in exactly the same form, with the same id) @param summary short edit summary @return the updated document @throws MediaWikiApiErrorException if the API returns errors @throws IOException if there are any IO errors, such as missing network connection
[ "@SuppressWarnings(\"unchecked\")\n\tpublic <T extends TermedStatementDocument> T updateTermsStatements(T currentDocument,\n\t\t\tList<MonolingualTextValue> addLabels,\n\t\t\tList<MonolingualTextValue> addDescriptions,\n\t\t\tList<MonolingualTextValue> addAliases,\n\t\t\tList<MonolingualTextValue> deleteAliases,\n\t\t\tList<Statement> addStatements, List<Statement> deleteStatements,\n\t\t\tString summary) throws MediaWikiApiErrorException, IOException {\n\t\t\n\t\tTermStatementUpdate termStatementUpdate = new TermStatementUpdate(\n\t\t\t\tcurrentDocument,\n\t\t\t\taddStatements, deleteStatements,\n\t\t\t\taddLabels, addDescriptions, addAliases, deleteAliases);\n\t\ttermStatementUpdate.setGuidGenerator(guidGenerator);\n\t\t\n\t\treturn (T) termStatementUpdate.performEdit(wbEditingAction, editAsBot, summary);\n\t}" ]
[ "public static Artifact withVersion(Version v)\n {\n Artifact artifact = new Artifact();\n artifact.version = v;\n return artifact;\n }", "public void setHomeAsUpIndicator(Drawable indicator) {\n if(!deviceSupportMultiPane()) {\n pulsante.setHomeAsUpIndicator(indicator);\n }\n else {\n actionBar.setHomeAsUpIndicator(indicator);\n }\n }", "private boolean isNullOrEmpty(Object paramValue) {\n boolean isNullOrEmpty = false;\n if (paramValue == null) {\n isNullOrEmpty = true;\n }\n if (paramValue instanceof String) {\n if (((String) paramValue).trim().equalsIgnoreCase(\"\")) {\n isNullOrEmpty = true;\n }\n } else if (paramValue instanceof List) {\n return ((List) paramValue).isEmpty();\n }\n return isNullOrEmpty;\n }", "private void calculateSCL(double[] x) {\r\n //System.out.println(\"Checking at: \"+x[0]+\" \"+x[1]+\" \"+x[2]);\r\n value = 0.0;\r\n Arrays.fill(derivative, 0.0);\r\n double[] sums = new double[numClasses];\r\n double[] probs = new double[numClasses];\r\n double[] counts = new double[numClasses];\r\n Arrays.fill(counts, 0.0);\r\n for (int d = 0; d < data.length; d++) {\r\n // if (d == testMin) {\r\n // d = testMax - 1;\r\n // continue;\r\n // }\r\n int[] features = data[d];\r\n // activation\r\n Arrays.fill(sums, 0.0);\r\n for (int c = 0; c < numClasses; c++) {\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n sums[c] += x[i];\r\n }\r\n }\r\n // expectation (slower routine replaced by fast way)\r\n // double total = Double.NEGATIVE_INFINITY;\r\n // for (int c=0; c<numClasses; c++) {\r\n // total = SloppyMath.logAdd(total, sums[c]);\r\n // }\r\n double total = ArrayMath.logSum(sums);\r\n int ld = labels[d];\r\n for (int c = 0; c < numClasses; c++) {\r\n probs[c] = Math.exp(sums[c] - total);\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n derivative[i] += probs[ld] * probs[c];\r\n }\r\n }\r\n // observed\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], labels[d]);\r\n derivative[i] -= probs[ld];\r\n }\r\n value -= probs[ld];\r\n }\r\n // priors\r\n if (true) {\r\n for (int i = 0; i < x.length; i++) {\r\n double k = 1.0;\r\n double w = x[i];\r\n value += k * w * w / 2.0;\r\n derivative[i] += k * w;\r\n }\r\n }\r\n }", "public ConfigOptionBuilder setStringConverter( StringConverter converter ) {\n co.setConverter( converter );\n co.setHasArgument( true );\n return this;\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 }", "private void populateConstraints(Row row, Task task)\n {\n Date endDateMax = row.getTimestamp(\"ZGIVENENDDATEMAX_\");\n Date endDateMin = row.getTimestamp(\"ZGIVENENDDATEMIN_\");\n Date startDateMax = row.getTimestamp(\"ZGIVENSTARTDATEMAX_\");\n Date startDateMin = row.getTimestamp(\"ZGIVENSTARTDATEMIN_\");\n\n ConstraintType constraintType = null;\n Date constraintDate = null;\n\n if (endDateMax != null)\n {\n constraintType = ConstraintType.FINISH_NO_LATER_THAN;\n constraintDate = endDateMax;\n }\n\n if (endDateMin != null)\n {\n constraintType = ConstraintType.FINISH_NO_EARLIER_THAN;\n constraintDate = endDateMin;\n }\n\n if (endDateMin != null && endDateMin == endDateMax)\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = endDateMin;\n }\n\n if (startDateMax != null)\n {\n constraintType = ConstraintType.START_NO_LATER_THAN;\n constraintDate = startDateMax;\n }\n\n if (startDateMin != null)\n {\n constraintType = ConstraintType.START_NO_EARLIER_THAN;\n constraintDate = startDateMin;\n }\n\n if (startDateMin != null && startDateMin == endDateMax)\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = endDateMin;\n }\n\n task.setConstraintType(constraintType);\n task.setConstraintDate(constraintDate);\n }", "public boolean hasInstance(Scriptable instance) {\n // Default for JS objects (other than Function) is to do prototype\n // chasing.\n Scriptable proto = instance.getPrototype();\n while (proto != null) {\n if (proto.equals(this)) return true;\n proto = proto.getPrototype();\n }\n return false;\n }", "private static CustomInfoType convertCustomInfo(Map<String, String> customInfo) {\n if (customInfo == null) {\n return null;\n }\n\n CustomInfoType ciType = new CustomInfoType();\n for (Entry<String, String> entry : customInfo.entrySet()) {\n CustomInfoType.Item cItem = new CustomInfoType.Item();\n cItem.setKey(entry.getKey());\n cItem.setValue(entry.getValue());\n ciType.getItem().add(cItem);\n }\n\n return ciType;\n }" ]
Reopen the associated static logging stream. Set to null to redirect to System.out.
[ "public static void openLogFile(String logPath) {\n\t\tif (logPath == null) {\n\t\t\tprintStream = System.out;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tprintStream = new PrintStream(new File(logPath));\n\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\tthrow new IllegalArgumentException(\"Log file \" + logPath + \" was not found\", e);\n\t\t\t}\n\t\t}\n\t}" ]
[ "@Override\n public Future<GcsFileMetadata> readObjectAsync(final ByteBuffer dst, final GcsFilename filename,\n long startOffsetBytes, long timeoutMillis) {\n Preconditions.checkArgument(startOffsetBytes >= 0, \"%s: offset must be non-negative: %s\", this,\n startOffsetBytes);\n final int n = dst.remaining();\n Preconditions.checkArgument(n > 0, \"%s: dst full: %s\", this, dst);\n final int want = Math.min(READ_LIMIT_BYTES, n);\n\n final HTTPRequest req = makeRequest(filename, null, GET, timeoutMillis);\n req.setHeader(\n new HTTPHeader(RANGE, \"bytes=\" + startOffsetBytes + \"-\" + (startOffsetBytes + want - 1)));\n final HTTPRequestInfo info = new HTTPRequestInfo(req);\n return new FutureWrapper<HTTPResponse, GcsFileMetadata>(urlfetch.fetchAsync(req)) {\n @Override\n protected GcsFileMetadata wrap(HTTPResponse resp) throws IOException {\n long totalLength;\n switch (resp.getResponseCode()) {\n case 200:\n totalLength = getLengthFromHeader(resp, X_GOOG_CONTENT_LENGTH);\n break;\n case 206:\n totalLength = getLengthFromContentRange(resp);\n break;\n case 404:\n throw new FileNotFoundException(\"Could not find: \" + filename);\n case 416:\n throw new BadRangeException(\"Requested Range not satisfiable; perhaps read past EOF? \"\n + URLFetchUtils.describeRequestAndResponse(info, resp));\n default:\n throw HttpErrorHandler.error(info, resp);\n }\n byte[] content = resp.getContent();\n Preconditions.checkState(content.length <= want, \"%s: got %s > wanted %s\", this,\n content.length, want);\n dst.put(content);\n return getMetadataFromResponse(filename, resp, totalLength);\n }\n\n @Override\n protected Throwable convertException(Throwable e) {\n return OauthRawGcsService.convertException(info, e);\n }\n };\n }", "private boolean tryCustomErrorPage(CmsObject cms, HttpServletRequest req, HttpServletResponse res, int errorCode) {\n\n String siteRoot = OpenCms.getSiteManager().matchRequest(req).getSiteRoot();\n CmsSite site = OpenCms.getSiteManager().getSiteForSiteRoot(siteRoot);\n if (site != null) {\n // store current site root and URI\n String currentSiteRoot = cms.getRequestContext().getSiteRoot();\n String currentUri = cms.getRequestContext().getUri();\n try {\n if (site.getErrorPage() != null) {\n String rootPath = site.getErrorPage();\n if (loadCustomErrorPage(cms, req, res, rootPath)) {\n return true;\n }\n }\n String rootPath = CmsStringUtil.joinPaths(siteRoot, \"/.errorpages/handle\" + errorCode + \".html\");\n if (loadCustomErrorPage(cms, req, res, rootPath)) {\n return true;\n }\n } finally {\n cms.getRequestContext().setSiteRoot(currentSiteRoot);\n cms.getRequestContext().setUri(currentUri);\n }\n }\n return false;\n }", "@Override\n protected void stopInner() {\n /*\n * TODO REST-Server Need to handle inflight operations. What happens to\n * the existing async operations when a channel.close() is issued in\n * Netty?\n */\n if(this.nettyServerChannel != null) {\n this.nettyServerChannel.close();\n }\n\n if(allChannels != null) {\n allChannels.close().awaitUninterruptibly();\n }\n this.bootstrap.releaseExternalResources();\n }", "public static base_response convert(nitro_service client, sslpkcs8 resource) throws Exception {\n\t\tsslpkcs8 convertresource = new sslpkcs8();\n\t\tconvertresource.pkcs8file = resource.pkcs8file;\n\t\tconvertresource.keyfile = resource.keyfile;\n\t\tconvertresource.keyform = resource.keyform;\n\t\tconvertresource.password = resource.password;\n\t\treturn convertresource.perform_operation(client,\"convert\");\n\t}", "@Pure\n\tpublic static <K, V> Map<K, V> operator_minus(Map<K, V> map, final Iterable<?> keys) {\n\t\treturn Maps.filterKeys(map, new Predicate<K>() {\n\t\t\t@Override\n\t\t\tpublic boolean apply(K input) {\n\t\t\t\treturn !Iterables.contains(keys, input);\n\t\t\t}\n\t\t});\n\t}", "public BoxFolder.Info getFolderInfo(String folderID, String... fields) {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", fields).toString();\n URL url = FOLDER_INFO_URL_TEMPLATE.buildWithQuery(this.api.getBaseURL(), queryString, folderID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFolder folder = new BoxFolder(this.api, jsonObject.get(\"id\").asString());\n return folder.new Info(response.getJSON());\n }", "public void 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 }", "@RequestMapping(value = \"/legendgraphic\", method = RequestMethod.GET)\n\tpublic ModelAndView getGraphic(@RequestParam(\"layerId\") String layerId,\n\t\t\t@RequestParam(value = \"styleName\", required = false) String styleName,\n\t\t\t@RequestParam(value = \"ruleIndex\", required = false) Integer ruleIndex,\n\t\t\t@RequestParam(value = \"format\", required = false) String format,\n\t\t\t@RequestParam(value = \"width\", required = false) Integer width,\n\t\t\t@RequestParam(value = \"height\", required = false) Integer height,\n\t\t\t@RequestParam(value = \"scale\", required = false) Double scale,\n\t\t\t@RequestParam(value = \"allRules\", required = false) Boolean allRules, HttpServletRequest request)\n\t\t\tthrows GeomajasException {\n\t\tif (!allRules) {\n\t\t\treturn getGraphic(layerId, styleName, ruleIndex, format, width, height, scale);\n\t\t} else {\n\t\t\treturn getGraphics(layerId, styleName, format, width, height, scale);\n\t\t}\n\t}", "public static int cudnnSoftmaxForward(\n cudnnHandle handle, \n int algo, \n int mode, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnSoftmaxForwardNative(handle, algo, mode, alpha, xDesc, x, beta, yDesc, y));\n }" ]
Attempts to checkout a resource so that one queued request can be serviced. @param key The key for which to process the requestQueue @return true iff an item was processed from the Queue.
[ "private boolean processQueue(K key) {\n Queue<AsyncResourceRequest<V>> requestQueue = getRequestQueueForKey(key);\n if(requestQueue.isEmpty()) {\n return false;\n }\n\n // Attempt to get a resource.\n Pool<V> resourcePool = getResourcePoolForKey(key);\n V resource = null;\n Exception ex = null;\n try {\n // Must attempt non-blocking checkout to ensure resources are\n // created for the pool.\n resource = attemptNonBlockingCheckout(key, resourcePool);\n } catch(Exception e) {\n destroyResource(key, resourcePool, resource);\n ex = e;\n resource = null;\n }\n // Neither we got a resource, nor an exception. So no requests can be\n // processed return\n if(resource == null && ex == null) {\n return false;\n }\n\n // With resource in hand, process the resource requests\n AsyncResourceRequest<V> resourceRequest = getNextUnexpiredResourceRequest(requestQueue);\n if(resourceRequest == null) {\n if(resource != null) {\n // Did not use the resource! Directly check in via super to\n // avoid\n // circular call to processQueue().\n try {\n super.checkin(key, resource);\n } catch(Exception e) {\n logger.error(\"Exception checking in resource: \", e);\n }\n } else {\n // Poor exception, no request to tag this exception onto\n // drop it on the floor and continue as usual.\n }\n return false;\n } else {\n // We have a request here.\n if(resource != null) {\n resourceRequest.useResource(resource);\n } else {\n resourceRequest.handleException(ex);\n }\n return true;\n }\n }" ]
[ "public <T> DiffNode compare(final T working, final T base)\n\t{\n\t\tdispatcher.resetInstanceMemory();\n\t\ttry\n\t\t{\n\t\t\treturn dispatcher.dispatch(DiffNode.ROOT, Instances.of(working, base), RootAccessor.getInstance());\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tdispatcher.clearInstanceMemory();\n\t\t}\n\t}", "public List<PPVItemsType.PPVItem> getPPVItem()\n {\n if (ppvItem == null)\n {\n ppvItem = new ArrayList<PPVItemsType.PPVItem>();\n }\n return this.ppvItem;\n }", "public ParallelTaskBuilder setReplacementVarMap(\n Map<String, String> replacementVarMap) {\n this.replacementVarMap = replacementVarMap;\n\n // TODO Check and warning of overwriting\n // set as uniform\n this.requestReplacementType = RequestReplacementType.UNIFORM_VAR_REPLACEMENT;\n return this;\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 static base_responses update(nitro_service client, snmpalarm resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpalarm updateresources[] = new snmpalarm[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new snmpalarm();\n\t\t\t\tupdateresources[i].trapname = resources[i].trapname;\n\t\t\t\tupdateresources[i].thresholdvalue = resources[i].thresholdvalue;\n\t\t\t\tupdateresources[i].normalvalue = resources[i].normalvalue;\n\t\t\t\tupdateresources[i].time = resources[i].time;\n\t\t\t\tupdateresources[i].state = resources[i].state;\n\t\t\t\tupdateresources[i].severity = resources[i].severity;\n\t\t\t\tupdateresources[i].logging = resources[i].logging;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "static boolean uninstall() {\n boolean uninstalled = false;\n synchronized (lock) {\n if (locationCollectionClient != null) {\n locationCollectionClient.locationEngineController.onDestroy();\n locationCollectionClient.settingsChangeHandlerThread.quit();\n locationCollectionClient.sharedPreferences.unregisterOnSharedPreferenceChangeListener(locationCollectionClient);\n locationCollectionClient = null;\n uninstalled = true;\n }\n }\n return uninstalled;\n }", "public void printInferredRelations(ClassDoc c) {\n\t// check if the source is excluded from inference\n\tif (hidden(c))\n\t return;\n\n\tOptions opt = optionProvider.getOptionsFor(c);\n\n\tfor (FieldDoc field : c.fields(false)) {\n\t if(hidden(field))\n\t\tcontinue;\n\t // skip statics\n\t if(field.isStatic())\n\t\tcontinue;\n\t // skip primitives\n\t FieldRelationInfo fri = getFieldRelationInfo(field);\n\t if (fri == null)\n\t\tcontinue;\n\t // check if the destination is excluded from inference\n\t if (hidden(fri.cd))\n\t\tcontinue;\n\n\t // if source and dest are not already linked, add a dependency\n\t RelationPattern rp = getClassInfo(c, true).getRelation(fri.cd.toString());\n\t if (rp == null) {\n\t\tString destAdornment = fri.multiple ? \"*\" : \"\";\n\t\trelation(opt, opt.inferRelationshipType, c, fri.cd, \"\", \"\", destAdornment);\n }\n\t}\n }", "protected boolean checkActionPackages(String classPackageName) {\n\t\tif (actionPackages != null) {\n\t\t\tfor (String packageName : actionPackages) {\n\t\t\t\tString strictPackageName = packageName + \".\";\n\t\t\t\tif (classPackageName.equals(packageName) || classPackageName.startsWith(strictPackageName))\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "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 }" ]
Sets the columns width by reading some report options like the printableArea and useFullPageWidth. columns with fixedWidth property set in TRUE will not be modified
[ "protected void setColumnsFinalWidth() {\n log.debug(\"Setting columns final width.\");\n float factor;\n int printableArea = report.getOptions().getColumnWidth();\n\n //Create a list with only the visible columns.\n List visibleColums = getVisibleColumns();\n\n\n if (report.getOptions().isUseFullPageWidth()) {\n int columnsWidth = 0;\n int notRezisableWidth = 0;\n\n //Store in a variable the total with of all visible columns\n for (Object visibleColum : visibleColums) {\n AbstractColumn col = (AbstractColumn) visibleColum;\n columnsWidth += col.getWidth();\n if (col.isFixedWidth())\n notRezisableWidth += col.getWidth();\n }\n\n\n factor = (float) (printableArea - notRezisableWidth) / (float) (columnsWidth - notRezisableWidth);\n\n log.debug(\"printableArea = \" + printableArea\n + \", columnsWidth = \" + columnsWidth\n + \", columnsWidth = \" + columnsWidth\n + \", notRezisableWidth = \" + notRezisableWidth\n + \", factor = \" + factor);\n\n int acumulated = 0;\n int colFinalWidth;\n\n //Select the non-resizable columns\n Collection resizableColumns = CollectionUtils.select(visibleColums, new Predicate() {\n public boolean evaluate(Object arg0) {\n return !((AbstractColumn) arg0).isFixedWidth();\n }\n\n });\n\n //Finally, set the new width to the resizable columns\n for (Iterator iter = resizableColumns.iterator(); iter.hasNext(); ) {\n AbstractColumn col = (AbstractColumn) iter.next();\n\n if (!iter.hasNext()) {\n col.setWidth(printableArea - notRezisableWidth - acumulated);\n } else {\n colFinalWidth = (new Float(col.getWidth() * factor)).intValue();\n acumulated += colFinalWidth;\n col.setWidth(colFinalWidth);\n }\n }\n }\n\n // If the columns width changed, the X position must be setted again.\n int posx = 0;\n for (Object visibleColum : visibleColums) {\n AbstractColumn col = (AbstractColumn) visibleColum;\n col.setPosX(posx);\n posx += col.getWidth();\n }\n }" ]
[ "public Duration getDuration(Date startDate, Date endDate)\n {\n Calendar cal = DateHelper.popCalendar(startDate);\n int days = getDaysInRange(startDate, endDate);\n int duration = 0;\n Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n\n while (days > 0)\n {\n if (isWorkingDate(cal.getTime(), day) == true)\n {\n ++duration;\n }\n\n --days;\n day = day.getNextDay();\n cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 1);\n }\n DateHelper.pushCalendar(cal);\n \n return (Duration.getInstance(duration, TimeUnit.DAYS));\n }", "protected String consumeWord(ImapRequestLineReader request,\n CharacterValidator validator)\n throws ProtocolException {\n StringBuilder atom = new StringBuilder();\n\n char next = request.nextWordChar();\n while (!isWhitespace(next)) {\n if (validator.isValid(next)) {\n atom.append(next);\n request.consume();\n } else {\n throw new ProtocolException(\"Invalid character: '\" + next + '\\'');\n }\n next = request.nextChar();\n }\n return atom.toString();\n }", "public <T extends OutputStream> T write(T os) throws IOException {\n close();\n\n if (!(this.os instanceof ByteArrayOutputStream))\n throw new IllegalStateException(\"Cannot write to another target if setOutputStream has been called\");\n final byte[] content = ((ByteArrayOutputStream) this.os).toByteArray();\n\n if (packer != null)\n packer.pack(new JarInputStream(new ByteArrayInputStream(content)), os);\n else\n os.write(content);\n\n os.close();\n return os;\n }", "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 SpinJsonDataFormatException unableToParseValue(String expectedType, JsonNodeType type) {\n return new SpinJsonDataFormatException(exceptionMessage(\"002\", \"Expected '{}', got '{}'\", expectedType, type.toString()));\n }", "public Logger getLogger(String loggerName)\r\n {\r\n Logger logger;\r\n //lookup in the cache first\r\n logger = (Logger) cache.get(loggerName);\r\n\r\n if(logger == null)\r\n {\r\n try\r\n {\r\n // get the configuration (not from the configurator because this is independent)\r\n logger = createLoggerInstance(loggerName);\r\n if(getBootLogger().isDebugEnabled())\r\n {\r\n getBootLogger().debug(\"Using logger class '\"\r\n + (getConfiguration() != null ? getConfiguration().getLoggerClass() : null)\r\n + \"' for \" + loggerName);\r\n }\r\n // configure the logger\r\n getBootLogger().debug(\"Initializing logger instance \" + loggerName);\r\n logger.configure(conf);\r\n }\r\n catch(Throwable t)\r\n {\r\n // do reassign check and signal logger creation failure\r\n reassignBootLogger(true);\r\n logger = getBootLogger();\r\n getBootLogger().error(\"[\" + this.getClass().getName()\r\n + \"] Could not initialize logger \" + (conf != null ? conf.getLoggerClass() : null), t);\r\n }\r\n //cache it so we can get it faster the next time\r\n cache.put(loggerName, logger);\r\n // do reassign check\r\n reassignBootLogger(false);\r\n }\r\n return logger;\r\n }", "public static byte[] decodeBase64(String value) {\n int byteShift = 4;\n int tmp = 0;\n boolean done = false;\n final StringBuilder buffer = new StringBuilder();\n\n for (int i = 0; i != value.length(); i++) {\n final char c = value.charAt(i);\n final int sixBit = (c < 123) ? EncodingGroovyMethodsSupport.TRANSLATE_TABLE[c] : 66;\n\n if (sixBit < 64) {\n if (done)\n throw new RuntimeException(\"= character not at end of base64 value\"); // TODO: change this exception type\n\n tmp = (tmp << 6) | sixBit;\n\n if (byteShift-- != 4) {\n buffer.append((char) ((tmp >> (byteShift * 2)) & 0XFF));\n }\n\n } else if (sixBit == 64) {\n\n byteShift--;\n done = true;\n\n } else if (sixBit == 66) {\n // RFC 2045 says that I'm allowed to take the presence of\n // these characters as evidence of data corruption\n // So I will\n throw new RuntimeException(\"bad character in base64 value\"); // TODO: change this exception type\n }\n\n if (byteShift == 0) byteShift = 4;\n }\n\n try {\n return buffer.toString().getBytes(\"ISO-8859-1\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"Base 64 decode produced byte values > 255\"); // TODO: change this exception type\n }\n }", "private FilePath copyClassWorldsFile(FilePath ws, URL resource) {\n try {\n FilePath remoteClassworlds =\n ws.createTextTempFile(\"classworlds\", \"conf\", \"\");\n remoteClassworlds.copyFrom(resource);\n return remoteClassworlds;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "private void checkForUnknownVariables(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n while( t != null ) {\n if( t.getType() == Type.WORD )\n throw new ParseError(\"Unknown variable on right side. \"+t.getWord());\n t = t.next;\n }\n }" ]
Returns the result of the performed spellcheck formatted in JSON. @param request The CmsSpellcheckingRequest. @return JSONObject that contains the result of the performed spellcheck.
[ "private JSONObject getJsonFormattedSpellcheckResult(CmsSpellcheckingRequest request) {\n\n final JSONObject response = new JSONObject();\n\n try {\n if (null != request.m_id) {\n response.put(JSON_ID, request.m_id);\n }\n\n response.put(JSON_RESULT, request.m_wordSuggestions);\n\n } catch (Exception e) {\n try {\n response.put(JSON_ERROR, true);\n LOG.debug(\"Error while assembling spellcheck response in JSON format.\", e);\n } catch (JSONException ex) {\n LOG.debug(\"Error while assembling spellcheck response in JSON format.\", ex);\n }\n }\n\n return response;\n }" ]
[ "private static <T, ID> void addCreateTableStatements(DatabaseType databaseType, TableInfo<T, ID> tableInfo,\n\t\t\tList<String> statements, List<String> queriesAfter, boolean ifNotExists, boolean logDetails)\n\t\t\tthrows SQLException {\n\t\tStringBuilder sb = new StringBuilder(256);\n\t\tif (logDetails) {\n\t\t\tlogger.info(\"creating table '{}'\", tableInfo.getTableName());\n\t\t}\n\t\tsb.append(\"CREATE TABLE \");\n\t\tif (ifNotExists && databaseType.isCreateIfNotExistsSupported()) {\n\t\t\tsb.append(\"IF NOT EXISTS \");\n\t\t}\n\t\tdatabaseType.appendEscapedEntityName(sb, tableInfo.getTableName());\n\t\tsb.append(\" (\");\n\t\tList<String> additionalArgs = new ArrayList<String>();\n\t\tList<String> statementsBefore = new ArrayList<String>();\n\t\tList<String> statementsAfter = new ArrayList<String>();\n\t\t// our statement will be set here later\n\t\tboolean first = true;\n\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\t// skip foreign collections\n\t\t\tif (fieldType.isForeignCollection()) {\n\t\t\t\tcontinue;\n\t\t\t} else if (first) {\n\t\t\t\tfirst = false;\n\t\t\t} else {\n\t\t\t\tsb.append(\", \");\n\t\t\t}\n\t\t\tString columnDefinition = fieldType.getColumnDefinition();\n\t\t\tif (columnDefinition == null) {\n\t\t\t\t// we have to call back to the database type for the specific create syntax\n\t\t\t\tdatabaseType.appendColumnArg(tableInfo.getTableName(), sb, fieldType, additionalArgs, statementsBefore,\n\t\t\t\t\t\tstatementsAfter, queriesAfter);\n\t\t\t} else {\n\t\t\t\t// hand defined field\n\t\t\t\tdatabaseType.appendEscapedEntityName(sb, fieldType.getColumnName());\n\t\t\t\tsb.append(' ').append(columnDefinition).append(' ');\n\t\t\t}\n\t\t}\n\t\t// add any sql that sets any primary key fields\n\t\tdatabaseType.addPrimaryKeySql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, statementsAfter,\n\t\t\t\tqueriesAfter);\n\t\t// add any sql that sets any unique fields\n\t\tdatabaseType.addUniqueComboSql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, statementsAfter,\n\t\t\t\tqueriesAfter);\n\t\tfor (String arg : additionalArgs) {\n\t\t\t// we will have spat out one argument already so we don't have to do the first dance\n\t\t\tsb.append(\", \").append(arg);\n\t\t}\n\t\tsb.append(\") \");\n\t\tdatabaseType.appendCreateTableSuffix(sb);\n\t\tstatements.addAll(statementsBefore);\n\t\tstatements.add(sb.toString());\n\t\tstatements.addAll(statementsAfter);\n\t\taddCreateIndexStatements(databaseType, tableInfo, statements, ifNotExists, false, logDetails);\n\t\taddCreateIndexStatements(databaseType, tableInfo, statements, ifNotExists, true, logDetails);\n\t}", "public void cleanup() {\n synchronized (_sslMap) {\n for (SslRelayOdo relay : _sslMap.values()) {\n if (relay.getHttpServer() != null && relay.isStarted()) {\n relay.getHttpServer().removeListener(relay);\n }\n }\n\n sslRelays.clear();\n }\n }", "private static <T> void readTableField(DatabaseTableConfig<T> config, String field, String value) {\n\t\tif (field.equals(FIELD_NAME_DATA_CLASS)) {\n\t\t\ttry {\n\t\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\t\tClass<T> clazz = (Class<T>) Class.forName(value);\n\t\t\t\tconfig.setDataClass(clazz);\n\t\t\t} catch (ClassNotFoundException e) {\n\t\t\t\tthrow new IllegalArgumentException(\"Unknown class specified for dataClass: \" + value);\n\t\t\t}\n\t\t} else if (field.equals(FIELD_NAME_TABLE_NAME)) {\n\t\t\tconfig.setTableName(value);\n\t\t}\n\t}", "public static void paintCheckedBackground(Component c, Graphics g, int x, int y, int width, int height) {\n\t\tif ( backgroundImage == null ) {\n\t\t\tbackgroundImage = new BufferedImage( 64, 64, BufferedImage.TYPE_INT_ARGB );\n\t\t\tGraphics bg = backgroundImage.createGraphics();\n\t\t\tfor ( int by = 0; by < 64; by += 8 ) {\n\t\t\t\tfor ( int bx = 0; bx < 64; bx += 8 ) {\n\t\t\t\t\tbg.setColor( ((bx^by) & 8) != 0 ? Color.lightGray : Color.white );\n\t\t\t\t\tbg.fillRect( bx, by, 8, 8 );\n\t\t\t\t}\n\t\t\t}\n\t\t\tbg.dispose();\n\t\t}\n\n\t\tif ( backgroundImage != null ) {\n\t\t\tShape saveClip = g.getClip();\n\t\t\tRectangle r = g.getClipBounds();\n\t\t\tif (r == null)\n\t\t\t\tr = new Rectangle(c.getSize());\n\t\t\tr = r.intersection(new Rectangle(x, y, width, height));\n\t\t\tg.setClip(r);\n\t\t\tint w = backgroundImage.getWidth();\n\t\t\tint h = backgroundImage.getHeight();\n\t\t\tif (w != -1 && h != -1) {\n\t\t\t\tint x1 = (r.x / w) * w;\n\t\t\t\tint y1 = (r.y / h) * h;\n\t\t\t\tint x2 = ((r.x + r.width + w - 1) / w) * w;\n\t\t\t\tint y2 = ((r.y + r.height + h - 1) / h) * h;\n\t\t\t\tfor (y = y1; y < y2; y += h)\n\t\t\t\t\tfor (x = x1; x < x2; x += w)\n\t\t\t\t\t\tg.drawImage(backgroundImage, x, y, c);\n\t\t\t}\n\t\t\tg.setClip(saveClip);\n\t\t}\n\t}", "public void addUIEventHandler(JavascriptObject obj, UIEventType type, UIEventHandler h) {\n String key = registerEventHandler(h);\n String mcall = \"google.maps.event.addListener(\" + obj.getVariableName() + \", '\" + type.name() + \"', \"\n + \"function(event) {document.jsHandlers.handleUIEvent('\" + key + \"', event);});\";//.latLng\n //System.out.println(\"addUIEventHandler mcall: \" + mcall);\n runtime.execute(mcall);\n }", "public void writeReferences() throws RDFHandlerException {\n\t\tIterator<Reference> referenceIterator = this.referenceQueue.iterator();\n\t\tfor (Resource resource : this.referenceSubjectQueue) {\n\t\t\tfinal Reference reference = referenceIterator.next();\n\t\t\tif (this.declaredReferences.add(resource)) {\n\t\t\t\twriteReference(reference, resource);\n\t\t\t}\n\t\t}\n\t\tthis.referenceSubjectQueue.clear();\n\t\tthis.referenceQueue.clear();\n\n\t\tthis.snakRdfConverter.writeAuxiliaryTriples();\n\t}", "private void addClasses(XMLStreamWriter writer, File jarFile, boolean mapClassMethods) throws IOException, ClassNotFoundException, XMLStreamException, IntrospectionException\n {\n ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();\n\n URLClassLoader loader = new URLClassLoader(new URL[]\n {\n jarFile.toURI().toURL()\n }, currentThreadClassLoader);\n\n JarFile jar = new JarFile(jarFile);\n Enumeration<JarEntry> enumeration = jar.entries();\n while (enumeration.hasMoreElements())\n {\n JarEntry jarEntry = enumeration.nextElement();\n if (!jarEntry.isDirectory() && jarEntry.getName().endsWith(\".class\"))\n {\n addClass(loader, jarEntry, writer, mapClassMethods);\n }\n }\n jar.close();\n }", "public static linkset_interface_binding[] get(nitro_service service, String id) throws Exception{\n\t\tlinkset_interface_binding obj = new linkset_interface_binding();\n\t\tobj.set_id(id);\n\t\tlinkset_interface_binding response[] = (linkset_interface_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public String readSnippet(String name) {\n\n String path = CmsStringUtil.joinPaths(\n m_context.getSetupBean().getWebAppRfsPath(),\n CmsSetupBean.FOLDER_SETUP,\n \"html\",\n name);\n try (InputStream stream = new FileInputStream(path)) {\n byte[] data = CmsFileUtil.readFully(stream, false);\n String result = new String(data, \"UTF-8\");\n return result;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }" ]
Get DPI suggestions. @return DPI suggestions
[ "public final double[] getDpiSuggestions() {\n if (this.dpiSuggestions == null) {\n List<Double> list = new ArrayList<>();\n for (double suggestion: DEFAULT_DPI_VALUES) {\n if (suggestion <= this.maxDpi) {\n list.add(suggestion);\n }\n }\n double[] suggestions = new double[list.size()];\n for (int i = 0; i < suggestions.length; i++) {\n suggestions[i] = list.get(i);\n }\n return suggestions;\n }\n return this.dpiSuggestions;\n }" ]
[ "private boolean markAsObsolete(ContentReference ref) {\n if (obsoleteContents.containsKey(ref.getHexHash())) { //This content is already marked as obsolete\n if (obsoleteContents.get(ref.getHexHash()) + obsolescenceTimeout < System.currentTimeMillis()) {\n DeploymentRepositoryLogger.ROOT_LOGGER.obsoleteContentCleaned(ref.getContentIdentifier());\n removeContent(ref);\n return true;\n }\n } else {\n obsoleteContents.put(ref.getHexHash(), System.currentTimeMillis()); //Mark content as obsolete\n }\n return false;\n }", "public String getElementId() {\r\n\t\tfor (Entry<String, String> attribute : attributes.entrySet()) {\r\n\t\t\tif (attribute.getKey().equalsIgnoreCase(\"id\")) {\r\n\t\t\t\treturn attribute.getValue();\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}", "protected void updateStyle(BoxStyle bstyle, TextPosition text)\n {\n String font = text.getFont().getName();\n String family = null;\n String weight = null;\n String fstyle = null;\n\n bstyle.setFontSize(text.getFontSizeInPt());\n bstyle.setLineHeight(text.getHeight());\n\n if (font != null)\n {\n \t//font style and weight\n for (int i = 0; i < pdFontType.length; i++)\n {\n if (font.toLowerCase().lastIndexOf(pdFontType[i]) >= 0)\n {\n weight = cssFontWeight[i];\n fstyle = cssFontStyle[i];\n break;\n }\n }\n if (weight != null)\n \tbstyle.setFontWeight(weight);\n else\n \tbstyle.setFontWeight(cssFontWeight[0]);\n if (fstyle != null)\n \tbstyle.setFontStyle(fstyle);\n else\n \tbstyle.setFontStyle(cssFontStyle[0]);\n\n //font family\n //If it's a known common font don't embed in html output to save space\n String knownFontFamily = findKnownFontFamily(font);\n if (!knownFontFamily.equals(\"\"))\n family = knownFontFamily;\n else\n {\n family = fontTable.getUsedName(text.getFont());\n if (family == null)\n family = font;\n }\n\n if (family != null)\n \tbstyle.setFontFamily(family);\n }\n\n updateStyleForRenderingMode();\n }", "public List<String> uuids(long count) {\n final URI uri = new URIBase(clientUri).path(\"_uuids\").query(\"count\", count).build();\n final JsonObject json = get(uri, JsonObject.class);\n return getGson().fromJson(json.get(\"uuids\").toString(), DeserializationTypes.STRINGS);\n }", "private String getOrdinal(Integer value)\n {\n String result;\n int index = value.intValue();\n if (index >= ORDINAL.length)\n {\n result = \"every \" + index + \"th\";\n }\n else\n {\n result = ORDINAL[index];\n }\n return result;\n }", "public static int validateZone(CharSequence zone) {\n\t\tfor(int i = 0; i < zone.length(); i++) {\n\t\t\tchar c = zone.charAt(i);\n\t\t\tif (c == IPAddress.PREFIX_LEN_SEPARATOR) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t\tif (c == IPv6Address.SEGMENT_SEPARATOR) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}", "private void readAssignment(Resource resource, Assignment assignment)\n {\n Task task = m_activityMap.get(assignment.getActivity());\n if (task != null)\n {\n task.addResourceAssignment(resource);\n }\n }", "private int getClosingParenthesisPosition(String text, int opening)\n {\n if (text.charAt(opening) != '(')\n {\n return -1;\n }\n\n int count = 0;\n for (int i = opening; i < text.length(); i++)\n {\n char c = text.charAt(i);\n switch (c)\n {\n case '(':\n {\n ++count;\n break;\n }\n\n case ')':\n {\n --count;\n if (count == 0)\n {\n return i;\n }\n break;\n }\n }\n }\n\n return -1;\n }", "public B partialFilterSelector(Selector selector) {\n instance.def.selector = Helpers.getJsonObjectFromSelector(selector);\n return returnThis();\n }" ]
Called on mouse up in the caption area, ends dragging by ending event capture. @param event the mouse up event that ended dragging @see DOM#releaseCapture @see #beginDragging @see #endDragging
[ "protected void endDragging(MouseUpEvent event) {\n\n m_dragging = false;\n DOM.releaseCapture(getElement());\n removeStyleName(I_CmsLayoutBundle.INSTANCE.dialogCss().dragging());\n }" ]
[ "public Token add( Variable variable ) {\n Token t = new Token(variable);\n push( t );\n return t;\n }", "private boolean isWorkingDate(Date date, Day day)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, day);\n return ranges.getRangeCount() != 0;\n }", "public RedwoodConfiguration neatExit(){\r\n tasks.add(new Runnable() { public void run() {\r\n Runtime.getRuntime().addShutdownHook(new Thread(){\r\n @Override public void run(){ Redwood.stop(); }\r\n });\r\n }});\r\n return this;\r\n }", "public static List<String> getChildrenParentMayNotExist(ZkClient zkClient, String path) {\n try {\n return zkClient.getChildren(path);\n } catch (ZkNoNodeException e) {\n return null;\n }\n }", "public static String parseRoot(String zookeepers) {\n int slashIndex = zookeepers.indexOf(\"/\");\n if (slashIndex != -1) {\n return zookeepers.substring(slashIndex).trim();\n }\n return \"/\";\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<DiscordianDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<DiscordianDate>) super.localDateTime(temporal);\n }", "public void deleteShovel(String vhost, String shovelname) {\n\t this.deleteIgnoring404(uriWithPath(\"./parameters/shovel/\" + encodePathSegment(vhost) + \"/\" + encodePathSegment(shovelname)));\n }", "public static base_response delete(nitro_service client, String domain) throws Exception {\n\t\tdnstxtrec deleteresource = new dnstxtrec();\n\t\tdeleteresource.domain = domain;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static base_response add(nitro_service client, vpath resource) throws Exception {\n\t\tvpath addresource = new vpath();\n\t\taddresource.name = resource.name;\n\t\taddresource.destip = resource.destip;\n\t\taddresource.encapmode = resource.encapmode;\n\t\treturn addresource.add_resource(client);\n\t}" ]
Use this API to add spilloverpolicy.
[ "public static base_response add(nitro_service client, spilloverpolicy resource) throws Exception {\n\t\tspilloverpolicy addresource = new spilloverpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.action = resource.action;\n\t\taddresource.comment = resource.comment;\n\t\treturn addresource.add_resource(client);\n\t}" ]
[ "public static <T> Set<T> asSet(T[] o) {\r\n return new HashSet<T>(Arrays.asList(o));\r\n }", "public void addSite(String siteKey) {\n\t\tValueMap gv = new ValueMap(siteKey);\n\t\tif (!this.valueMaps.contains(gv)) {\n\t\t\tthis.valueMaps.add(gv);\n\t\t}\n\t}", "private String mountPath(CdjStatus.TrackSourceSlot slot) {\n switch (slot) {\n case SD_SLOT: return \"/B/\";\n case USB_SLOT: return \"/C/\";\n }\n throw new IllegalArgumentException(\"Don't know how to NFS mount filesystem for slot \" + slot);\n }", "public static gslbldnsentries[] get(nitro_service service) throws Exception{\n\t\tgslbldnsentries obj = new gslbldnsentries();\n\t\tgslbldnsentries[] response = (gslbldnsentries[])obj.get_resources(service);\n\t\treturn response;\n\t}", "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}", "void invoke(HttpRequest request) throws Exception {\n bodyConsumer = null;\n Object invokeResult;\n try {\n args[0] = this.request = request;\n invokeResult = method.invoke(handler, args);\n } catch (InvocationTargetException e) {\n exceptionHandler.handle(e.getTargetException(), request, responder);\n return;\n } catch (Throwable t) {\n exceptionHandler.handle(t, request, responder);\n return;\n }\n\n if (isStreaming) {\n // Casting guarantee to be succeeded.\n bodyConsumer = (BodyConsumer) invokeResult;\n }\n }", "@Override\n public boolean supportsNativeRotation() {\n return this.params.useNativeAngle &&\n (this.params.serverType == WmsLayerParam.ServerType.MAPSERVER ||\n this.params.serverType == WmsLayerParam.ServerType.GEOSERVER);\n }", "public void pushDryRun() throws Exception {\n if (releaseAction.isCreateVcsTag()) {\n if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), releaseAction.getTagUrl())) {\n throw new Exception(String.format(\"Tag with name '%s' already exists\", releaseAction.getTagUrl()));\n }\n }\n\n String testTagName = releaseAction.getTagUrl() + \"_test\";\n try {\n scmManager.testPush(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName);\n } catch (Exception e) {\n throw new Exception(String.format(\"Failed while attempting push dry-run: %s\", e.getMessage()), e);\n } finally {\n if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName)) {\n scmManager.deleteLocalTag(testTagName);\n }\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}" ]
Diagnostic method used to dump known field map data. @param props props block containing field map data
[ "public void dumpKnownFieldMaps(Props props)\n {\n //for (int key=131092; key < 131098; key++)\n for (int key = 50331668; key < 50331674; key++)\n {\n byte[] fieldMapData = props.getByteArray(Integer.valueOf(key));\n if (fieldMapData != null)\n {\n System.out.println(\"KEY: \" + key);\n createFieldMap(fieldMapData);\n System.out.println(toString());\n clear();\n }\n }\n }" ]
[ "public static TestCaseStartedEvent withExecutorInfo(TestCaseStartedEvent event) {\n event.getLabels().add(createHostLabel(getHostname()));\n event.getLabels().add(createThreadLabel(format(\"%s.%s(%s)\",\n ManagementFactory.getRuntimeMXBean().getName(),\n Thread.currentThread().getName(),\n Thread.currentThread().getId())\n ));\n return event;\n }", "protected boolean computeOffset(final int dataIndex, CacheDataSet cache) {\n float layoutOffset = getLayoutOffset();\n int pos = cache.getPos(dataIndex);\n float startDataOffset = Float.NaN;\n float endDataOffset = Float.NaN;\n if (pos > 0) {\n int id = cache.getId(pos - 1);\n if (id != -1) {\n startDataOffset = cache.getEndDataOffset(id);\n if (!Float.isNaN(startDataOffset)) {\n endDataOffset = cache.setDataAfter(dataIndex, startDataOffset);\n }\n }\n } else if (pos == 0) {\n int id = cache.getId(pos + 1);\n if (id != -1) {\n endDataOffset = cache.getStartDataOffset(id);\n if (!Float.isNaN(endDataOffset)) {\n startDataOffset = cache.setDataBefore(dataIndex, endDataOffset);\n }\n } else {\n startDataOffset = getStartingOffset((cache.getTotalSizeWithPadding()));\n endDataOffset = cache.setDataAfter(dataIndex, startDataOffset);\n }\n }\n\n Log.d(LAYOUT, TAG, \"computeOffset [%d, %d]: startDataOffset = %f endDataOffset = %f\",\n dataIndex, pos, startDataOffset, endDataOffset);\n\n boolean inBounds = !Float.isNaN(cache.getDataOffset(dataIndex)) &&\n endDataOffset > layoutOffset &&\n startDataOffset < -layoutOffset;\n\n return inBounds;\n }", "public void updateAnimation()\n {\n Date time = new Date();\n long currentTime = time.getTime() - this.beginAnimation;\n if (currentTime > animationTime)\n {\n this.currentQuaternion.set(endQuaternion);\n for (int i = 0; i < 3; i++)\n {\n\n this.currentPos[i] = this.endPos[i];\n }\n this.animate = false;\n }\n\n else\n {\n float t = (float) currentTime / animationTime;\n this.currentQuaternion = this.beginQuaternion.slerp(this.endQuaternion,\n t);\n for (int i = 0; i < 3; i++)\n {\n this.currentPos[i] = this.beginPos[i] + totalTranslation[i] * t;\n }\n\n }\n }", "@Override\n public void destroy(T instance, CreationalContext<T> creationalContext) {\n super.destroy(instance, creationalContext);\n try {\n getProducer().preDestroy(instance);\n // WELD-1010 hack?\n if (creationalContext instanceof CreationalContextImpl) {\n ((CreationalContextImpl<T>) creationalContext).release(this, instance);\n } else {\n creationalContext.release();\n }\n } catch (Exception e) {\n BeanLogger.LOG.errorDestroying(instance, this);\n BeanLogger.LOG.catchingDebug(e);\n }\n }", "public LuaPreparedScript endPreparedScriptReturn(LuaValue value, LuaScriptConfig config) {\n add(new LuaAstReturnStatement(argument(value)));\n return endPreparedScript(config);\n }", "protected AbstractColumn buildSimpleImageColumn() {\n\t\tImageColumn column = new ImageColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tpopulateExpressionAttributes(column);\n\t\t\n\t\tcolumn.setExpression(customExpression);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setExpressionForCalculation(customExpressionForCalculation);\n\t\t\n\t\tcolumn.setScaleMode(imageScaleMode);\n\t\treturn column;\n\t}", "public static final String getSelectedValue(ListBox list) {\n\tint index = list.getSelectedIndex();\n\treturn (index >= 0) ? list.getValue(index) : null;\n }", "public int[] sampleBatchWithoutReplacement() {\n int[] batch = new int[batchSize];\n for (int i=0; i<batch.length; i++) {\n if (cur == indices.length) {\n cur = 0;\n }\n if (cur == 0) {\n IntArrays.shuffle(indices);\n }\n batch[i] = indices[cur++];\n }\n return batch;\n }", "private static List<Segment> parseSegments(String origPathStr) {\n String pathStr = origPathStr;\n if (!pathStr.startsWith(\"/\")) {\n pathStr = pathStr + \"/\";\n }\n\n List<Segment> result = new ArrayList<>();\n for (String segmentStr : PATH_SPLITTER.split(pathStr)) {\n Matcher m = SEGMENT_PATTERN.matcher(segmentStr);\n if (!m.matches()) {\n throw new IllegalArgumentException(\"Bad aql path: \" + origPathStr);\n }\n Segment segment = new Segment();\n segment.attribute = m.group(1);\n segment.nodeId = m.groupCount() >= 3 ? m.group(3) : null;\n result.add(segment);\n }\n return result;\n }" ]
Remove a management request handler factory from this context. @param instance the request handler factory @return {@code true} if the instance was removed, {@code false} otherwise
[ "public boolean removeHandlerFactory(ManagementRequestHandlerFactory instance) {\n for(;;) {\n final ManagementRequestHandlerFactory[] snapshot = updater.get(this);\n final int length = snapshot.length;\n int index = -1;\n for(int i = 0; i < length; i++) {\n if(snapshot[i] == instance) {\n index = i;\n break;\n }\n }\n if(index == -1) {\n return false;\n }\n final ManagementRequestHandlerFactory[] newVal = new ManagementRequestHandlerFactory[length - 1];\n System.arraycopy(snapshot, 0, newVal, 0, index);\n System.arraycopy(snapshot, index + 1, newVal, index, length - index - 1);\n if (updater.compareAndSet(this, snapshot, newVal)) {\n return true;\n }\n }\n }" ]
[ "public Try<R,Throwable> execute(T input){\n\t\treturn Try.withCatch( ()->transactionTemplate.execute(status-> transaction.apply(input)));\n\t\t \n\t}", "private int decode(Huffman h) throws IOException\n {\n int len; /* current number of bits in code */\n int code; /* len bits being decoded */\n int first; /* first code of length len */\n int count; /* number of codes of length len */\n int index; /* index of first code of length len in symbol table */\n int bitbuf; /* bits from stream */\n int left; /* bits left in next or left to process */\n //short *next; /* next number of codes */\n\n bitbuf = m_bitbuf;\n left = m_bitcnt;\n code = first = index = 0;\n len = 1;\n int nextIndex = 1; // next = h->count + 1;\n while (true)\n {\n while (left-- != 0)\n {\n code |= (bitbuf & 1) ^ 1; /* invert code */\n bitbuf >>= 1;\n //count = *next++;\n count = h.m_count[nextIndex++];\n if (code < first + count)\n { /* if length len, return symbol */\n m_bitbuf = bitbuf;\n m_bitcnt = (m_bitcnt - len) & 7;\n return h.m_symbol[index + (code - first)];\n }\n index += count; /* else update for next length */\n first += count;\n first <<= 1;\n code <<= 1;\n len++;\n }\n left = (MAXBITS + 1) - len;\n if (left == 0)\n {\n break;\n }\n if (m_left == 0)\n {\n m_in = m_input.read();\n m_left = m_in == -1 ? 0 : 1;\n if (m_left == 0)\n {\n throw new IOException(\"out of input\"); /* out of input */\n }\n }\n bitbuf = m_in;\n m_left--;\n if (left > 8)\n {\n left = 8;\n }\n }\n return -9; /* ran out of codes */\n }", "private BigInteger getTaskCalendarID(Task mpx)\n {\n BigInteger result = null;\n ProjectCalendar cal = mpx.getCalendar();\n if (cal != null)\n {\n result = NumberHelper.getBigInteger(cal.getUniqueID());\n }\n else\n {\n result = NULL_CALENDAR_ID;\n }\n return (result);\n }", "public static LuaCondition isNull(LuaValue value) {\n LuaAstExpression expression;\n if (value instanceof LuaLocal) {\n expression = new LuaAstLocal(((LuaLocal) value).getName());\n } else {\n throw new IllegalArgumentException(\"Unexpected value type: \" + value.getClass().getName());\n }\n return new LuaCondition(new LuaAstNot(expression));\n }", "@Override\n public void populateObject(ProcessedCommand<Command<CI>, CI> processedCommand, InvocationProviders invocationProviders,\n AeshContext aeshContext, CommandLineParser.Mode mode)\n throws CommandLineParserException, OptionValidatorException {\n if(processedCommand.parserExceptions().size() > 0 && mode == CommandLineParser.Mode.VALIDATE)\n throw processedCommand.parserExceptions().get(0);\n for(ProcessedOption option : processedCommand.getOptions()) {\n if(option.getValues() != null && option.getValues().size() > 0)\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE );\n else if(option.getDefaultValues().size() > 0) {\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n }\n else if(option.getOptionType().equals(OptionType.GROUP) && option.getProperties().size() > 0)\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else\n resetField(getObject(), option.getFieldName(), option.hasValue());\n }\n //arguments\n if(processedCommand.getArguments() != null &&\n (processedCommand.getArguments().getValues().size() > 0 || processedCommand.getArguments().getDefaultValues().size() > 0))\n processedCommand.getArguments().injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else if(processedCommand.getArguments() != null)\n resetField(getObject(), processedCommand.getArguments().getFieldName(), true);\n //argument\n if(processedCommand.getArgument() != null &&\n (processedCommand.getArgument().getValues().size() > 0 || processedCommand.getArgument().getDefaultValues().size() > 0))\n processedCommand.getArgument().injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else if(processedCommand.getArgument() != null)\n resetField(getObject(), processedCommand.getArgument().getFieldName(), true);\n }", "public static base_response change(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey updateresource = new sslcertkey();\n\t\tupdateresource.certkey = resource.certkey;\n\t\tupdateresource.cert = resource.cert;\n\t\tupdateresource.key = resource.key;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.fipskey = resource.fipskey;\n\t\tupdateresource.inform = resource.inform;\n\t\tupdateresource.passplain = resource.passplain;\n\t\tupdateresource.nodomaincheck = resource.nodomaincheck;\n\t\treturn updateresource.perform_operation(client,\"update\");\n\t}", "public void deleteModule(final String name, final String version, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getModulePath(name, version));\n final ClientResponse response = resource.delete(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"to delete module\", name, version);\n\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }", "private void writeIntegerField(String fieldName, Object value) throws IOException\n {\n int val = ((Number) value).intValue();\n if (val != 0)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }", "public SelectStatement getPreparedSelectStatement(Query query, ClassDescriptor cld)\r\n {\r\n SelectStatement sql = new SqlSelectStatement(m_platform, cld, query, logger);\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n return sql;\r\n }" ]
Convert from Hadoop Text to Bytes
[ "public static Bytes toBytes(Text t) {\n return Bytes.of(t.getBytes(), 0, t.getLength());\n }" ]
[ "@Override\n\tpublic boolean isSinglePrefixBlock() {\n\t\tInteger networkPrefixLength = getNetworkPrefixLength();\n\t\tif(networkPrefixLength == null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn containsSinglePrefixBlock(networkPrefixLength);\n\t}", "protected void debugLog(String operationType, Long receivedTimeInMs) {\n long durationInMs = receivedTimeInMs - (this.parsedRequestOriginTimeInMs);\n int numVectorClockEntries = (this.parsedVectorClock == null ? 0\n : this.parsedVectorClock.getVersionMap()\n .size());\n logger.debug(\"Received a new request. Operation type: \" + operationType + \" , Key(s): \"\n + keysHexString(this.parsedKeys) + \" , Store: \" + this.storeName\n + \" , Origin time (in ms): \" + (this.parsedRequestOriginTimeInMs)\n + \" , Request received at time(in ms): \" + receivedTimeInMs\n + \" , Num vector clock entries: \" + numVectorClockEntries\n + \" , Duration from RESTClient to CoordinatorRestRequestValidator(in ms): \"\n + durationInMs);\n\n }", "@Override\n public ResourceStorageLoadable getOrCreateResourceStorageLoadable(final StorageAwareResource resource) {\n try {\n final ResourceStorageProviderAdapter stateProvider = IterableExtensions.<ResourceStorageProviderAdapter>head(Iterables.<ResourceStorageProviderAdapter>filter(resource.getResourceSet().eAdapters(), ResourceStorageProviderAdapter.class));\n if ((stateProvider != null)) {\n final ResourceStorageLoadable inputStream = stateProvider.getResourceStorageLoadable(resource);\n if ((inputStream != null)) {\n return inputStream;\n }\n }\n InputStream _xifexpression = null;\n boolean _exists = resource.getResourceSet().getURIConverter().exists(this.getBinaryStorageURI(resource.getURI()), CollectionLiterals.<Object, Object>emptyMap());\n if (_exists) {\n _xifexpression = resource.getResourceSet().getURIConverter().createInputStream(this.getBinaryStorageURI(resource.getURI()));\n } else {\n InputStream _xblockexpression = null;\n {\n final AbstractFileSystemAccess2 fsa = this.getFileSystemAccess(resource);\n final String outputRelativePath = this.computeOutputPath(resource);\n _xblockexpression = fsa.readBinaryFile(outputRelativePath);\n }\n _xifexpression = _xblockexpression;\n }\n final InputStream inputStream_1 = _xifexpression;\n return this.createResourceStorageLoadable(inputStream_1);\n } catch (Throwable _e) {\n throw Exceptions.sneakyThrow(_e);\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 }", "public static <X, T> ProducerMethod<X, T> of(BeanAttributes<T> attributes, EnhancedAnnotatedMethod<T, ? super X> method, AbstractClassBean<X> declaringBean, DisposalMethod<X, ?> disposalMethod, BeanManagerImpl beanManager, ServiceRegistry services) {\n return new ProducerMethod<X, T>(createId(attributes, method, declaringBean), attributes, method, declaringBean, disposalMethod, beanManager, services);\n }", "public Bundler put(String key, Parcelable[] value) {\n delegate.putParcelableArray(key, value);\n return this;\n }", "public static void validate(final Organization organization) {\n if(organization.getName() == null ||\n organization.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Organization name cannot be null or empty!\")\n .build());\n }\n }", "public ConverterServerBuilder workerPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) {\n assertNumericArgument(corePoolSize, true);\n assertNumericArgument(maximumPoolSize, true);\n assertNumericArgument(corePoolSize + maximumPoolSize, false);\n assertNumericArgument(keepAliveTime, true);\n this.corePoolSize = corePoolSize;\n this.maximumPoolSize = maximumPoolSize;\n this.keepAliveTime = unit.toMillis(keepAliveTime);\n return this;\n }", "protected boolean isSingleConnection(DatabaseConnection conn1, DatabaseConnection conn2) throws SQLException {\n\t\t// initialize the connections auto-commit flags\n\t\tconn1.setAutoCommit(true);\n\t\tconn2.setAutoCommit(true);\n\t\ttry {\n\t\t\t// change conn1's auto-commit to be false\n\t\t\tconn1.setAutoCommit(false);\n\t\t\tif (conn2.isAutoCommit()) {\n\t\t\t\t// if the 2nd connection's auto-commit is still true then we have multiple connections\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\t// if the 2nd connection's auto-commit is also false then we have a single connection\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} finally {\n\t\t\t// restore its auto-commit\n\t\t\tconn1.setAutoCommit(true);\n\t\t}\n\t}" ]
Emit information about a single suite and all of its tests.
[ "@Subscribe\n @SuppressForbidden(\"legitimate printStackTrace().\")\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n try {\n if (jsonWriter == null)\n return;\n\n slaves.put(e.getSlave().id, e.getSlave());\n e.serialize(jsonWriter, outputStreams);\n } catch (Exception ex) {\n ex.printStackTrace();\n junit4.log(\"Error serializing to JSON file: \"\n + Throwables.getStackTraceAsString(ex), Project.MSG_WARN);\n if (jsonWriter != null) {\n try {\n jsonWriter.close();\n } catch (Throwable ignored) {\n // Ignore.\n } finally {\n jsonWriter = null;\n }\n }\n }\n }" ]
[ "public void handleChannelClosed(final Channel closed, final IOException e) {\n for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) {\n if (activeOperation.getChannel() == closed) {\n // Only call cancel, to also interrupt still active threads\n activeOperation.getResultHandler().cancel();\n }\n }\n }", "public Number getFloat(int field) throws MPXJException\n {\n try\n {\n Number result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = m_formats.getDecimalFormat().parse(m_fields[field]);\n }\n else\n {\n result = null;\n }\n\n return (result);\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse float\", ex);\n }\n }", "private void processCalendars() throws SQLException\n {\n List<Row> rows = getTable(\"EXCEPTIONN\");\n Map<Integer, DayType> exceptionMap = m_reader.createExceptionTypeMap(rows);\n\n rows = getTable(\"WORK_PATTERN\");\n Map<Integer, Row> workPatternMap = m_reader.createWorkPatternMap(rows);\n\n rows = new LinkedList<Row>();// getTable(\"WORK_PATTERN_ASSIGNMENT\"); // Need to generate an example\n Map<Integer, List<Row>> workPatternAssignmentMap = m_reader.createWorkPatternAssignmentMap(rows);\n\n rows = getTable(\"EXCEPTION_ASSIGNMENT\");\n Map<Integer, List<Row>> exceptionAssignmentMap = m_reader.createExceptionAssignmentMap(rows);\n\n rows = getTable(\"TIME_ENTRY\");\n Map<Integer, List<Row>> timeEntryMap = m_reader.createTimeEntryMap(rows);\n\n rows = getTable(\"CALENDAR\");\n Collections.sort(rows, CALENDAR_COMPARATOR);\n for (Row row : rows)\n {\n m_reader.processCalendar(row, workPatternMap, workPatternAssignmentMap, exceptionAssignmentMap, timeEntryMap, exceptionMap);\n }\n\n //\n // Update unique counters at this point as we will be generating\n // resource calendars, and will need to auto generate IDs\n //\n m_reader.getProject().getProjectConfig().updateUniqueCounters();\n }", "private void saveLocalization() {\n\n SortedProperties localization = new SortedProperties();\n for (Object itemId : m_container.getItemIds()) {\n Item item = m_container.getItem(itemId);\n String key = item.getItemProperty(TableProperty.KEY).getValue().toString();\n String value = item.getItemProperty(TableProperty.TRANSLATION).getValue().toString();\n if (!(key.isEmpty() || value.isEmpty())) {\n localization.put(key, value);\n }\n }\n m_keyset.updateKeySet(m_localizations.get(m_locale).keySet(), localization.keySet());\n m_localizations.put(m_locale, localization);\n\n }", "public static TimeZone get(String suffix) {\n if(SUFFIX_TIMEZONES.containsKey(suffix)) {\n return SUFFIX_TIMEZONES.get(suffix);\n }\n log.warn(\"Cannot find time zone for exchange suffix: '{}'. Using default: America/New_York\", suffix);\n return SUFFIX_TIMEZONES.get(\"\");\n }", "public static Method getBridgeMethodTarget(Method someMethod) {\n TraitBridge annotation = someMethod.getAnnotation(TraitBridge.class);\n if (annotation==null) {\n return null;\n }\n Class aClass = annotation.traitClass();\n String desc = annotation.desc();\n for (Method method : aClass.getDeclaredMethods()) {\n String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameterTypes());\n if (desc.equals(methodDescriptor)) {\n return method;\n }\n }\n return null;\n }", "public void load(InputStream in) {\n try {\n PropertiesConfiguration config = new PropertiesConfiguration();\n // disabled to prevent accumulo classpath value from being shortened\n config.setDelimiterParsingDisabled(true);\n config.load(in);\n ((CompositeConfiguration) internalConfig).addConfiguration(config);\n } catch (ConfigurationException e) {\n throw new IllegalArgumentException(e);\n }\n }", "private void addCheckBox(final String internalValue, String labelMessageKey) {\r\n\r\n CmsCheckBox box = new CmsCheckBox(Messages.get().key(labelMessageKey));\r\n box.setInternalValue(internalValue);\r\n box.addValueChangeHandler(new ValueChangeHandler<Boolean>() {\r\n\r\n public void onValueChange(ValueChangeEvent<Boolean> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.weeksChange(internalValue, event.getValue());\r\n }\r\n }\r\n });\r\n m_weekPanel.add(box);\r\n m_checkboxes.add(box);\r\n\r\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 }" ]
Reset hard on HEAD. @throws GitAPIException
[ "public void rollback() throws GitAPIException {\n try (Git git = getGit()) {\n git.reset().setMode(ResetCommand.ResetType.HARD).setRef(HEAD).call();\n }\n }" ]
[ "public void setFinalTransformMatrix(Matrix4f finalTransform)\n {\n float[] mat = new float[16];\n finalTransform.get(mat);\n NativeBone.setFinalTransformMatrix(getNative(), mat);\n }", "private void processResourceAssignments(Task task, List<MapRow> assignments)\n {\n for (MapRow row : assignments)\n {\n processResourceAssignment(task, row);\n }\n }", "private static Document getProjection(List<String> fieldNames) {\n\t\tDocument projection = new Document();\n\t\tfor ( String column : fieldNames ) {\n\t\t\tprojection.put( column, 1 );\n\t\t}\n\n\t\treturn projection;\n\t}", "@Override public Integer[] getUniqueIdentifierArray()\n {\n Integer[] result = new Integer[m_table.size()];\n int index = 0;\n for (Integer value : m_table.keySet())\n {\n result[index] = value;\n ++index;\n }\n return (result);\n }", "public void updateExceptions(SortedSet<Date> exceptions) {\r\n\r\n SortedSet<Date> e = null == exceptions ? new TreeSet<Date>() : exceptions;\r\n if (!m_model.getExceptions().equals(e)) {\r\n m_model.setExceptions(e);\r\n m_view.updateExceptions();\r\n valueChanged();\r\n sizeChanged();\r\n }\r\n\r\n }", "private void readBitFields(MppBitFlag[] flags, FieldContainer container, byte[] data)\n {\n for (MppBitFlag flag : flags)\n {\n flag.setValue(container, data);\n }\n }", "public DependencyReport getDependencyReport(final String moduleId, final FiltersHolder filters) {\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n final DependencyReport report = new DependencyReport(moduleId);\n final List<String> done = new ArrayList<String>();\n for(final DbModule submodule: DataUtils.getAllSubmodules(module)){\n done.add(submodule.getId());\n }\n\n addModuleToReport(report, module, filters, done, 1);\n\n return report;\n }", "protected FluentModelTImpl prepareForFutureCommitOrPostRun(FluentModelTImpl childResource) {\n if (this.isPostRunMode) {\n if (!childResource.taskGroup().dependsOn(this.parentTaskGroup)) {\n this.parentTaskGroup.addPostRunDependentTaskGroup(childResource.taskGroup());\n }\n return childResource;\n } else {\n return childResource;\n }\n }", "public static base_responses update(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 updateresources[] = new tmtrafficaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new tmtrafficaction();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].apptimeout = resources[i].apptimeout;\n\t\t\t\tupdateresources[i].sso = resources[i].sso;\n\t\t\t\tupdateresources[i].formssoaction = resources[i].formssoaction;\n\t\t\t\tupdateresources[i].persistentcookie = resources[i].persistentcookie;\n\t\t\t\tupdateresources[i].initiatelogout = resources[i].initiatelogout;\n\t\t\t\tupdateresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\tupdateresources[i].samlssoprofile = resources[i].samlssoprofile;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Return all methods for a list of groupIds @param groupIds array of group IDs @param filters array of filters to apply to method selection @return collection of Methods found @throws Exception exception
[ "public List<Method> getMethodsFromGroupIds(int[] groupIds, String[] filters) throws Exception {\n ArrayList<Method> methods = new ArrayList<Method>();\n\n for (int groupId : groupIds) {\n methods.addAll(getMethodsFromGroupId(groupId, filters));\n }\n\n return methods;\n }" ]
[ "public void attachMetadataCache(SlotReference slot, File file)\n throws IOException {\n ensureRunning();\n if (slot.player < 1 || slot.player > 4 || DeviceFinder.getInstance().getLatestAnnouncementFrom(slot.player) == null) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for player \" + slot.player);\n }\n if ((slot.slot != CdjStatus.TrackSourceSlot.USB_SLOT) && (slot.slot != CdjStatus.TrackSourceSlot.SD_SLOT)) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for slot \" + slot.slot);\n }\n\n MetadataCache cache = new MetadataCache(file);\n final MediaDetails slotDetails = getMediaDetailsFor(slot);\n if (cache.sourceMedia != null && slotDetails != null) {\n if (!slotDetails.hashKey().equals(cache.sourceMedia.hashKey())) {\n throw new IllegalArgumentException(\"Cache was created for different media (\" + cache.sourceMedia.hashKey() +\n \") than is in the slot (\" + slotDetails.hashKey() + \").\");\n }\n if (slotDetails.hasChanged(cache.sourceMedia)) {\n logger.warn(\"Media has changed (\" + slotDetails + \") since cache was created (\" + cache.sourceMedia +\n \"). Attaching anyway as instructed.\");\n }\n }\n attachMetadataCacheInternal(slot, cache);\n }", "public DynamicReportBuilder setProperty(String name, String value) {\n this.report.setProperty(name, value);\n return this;\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 updateRoutingStrategies(Cluster cluster, List<StoreDefinition> storeDefs) {\n // acquire write lock\n writeLock.lock();\n try {\n VectorClock clock = new VectorClock();\n if(metadataCache.containsKey(ROUTING_STRATEGY_KEY))\n clock = (VectorClock) metadataCache.get(ROUTING_STRATEGY_KEY).getVersion();\n\n logger.info(\"Updating routing strategy for all stores\");\n HashMap<String, StoreDefinition> storeDefMap = makeStoreDefinitionMap(storeDefs);\n HashMap<String, RoutingStrategy> routingStrategyMap = createRoutingStrategyMap(cluster,\n storeDefMap);\n this.metadataCache.put(ROUTING_STRATEGY_KEY,\n new Versioned<Object>(routingStrategyMap,\n clock.incremented(getNodeId(),\n System.currentTimeMillis())));\n\n for(String storeName: storeNameTolisteners.keySet()) {\n RoutingStrategy updatedRoutingStrategy = routingStrategyMap.get(storeName);\n if(updatedRoutingStrategy != null) {\n try {\n for(MetadataStoreListener listener: storeNameTolisteners.get(storeName)) {\n listener.updateRoutingStrategy(updatedRoutingStrategy);\n listener.updateStoreDefinition(storeDefMap.get(storeName));\n }\n } catch(Exception e) {\n if(logger.isEnabledFor(Level.WARN))\n logger.warn(e, e);\n }\n }\n\n }\n } finally {\n writeLock.unlock();\n }\n }", "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 }", "public void addModuleDir(final String moduleDir) {\n if (moduleDir == null) {\n throw LauncherMessages.MESSAGES.nullParam(\"moduleDir\");\n }\n // Validate the path\n final Path path = Paths.get(moduleDir).normalize();\n modulesDirs.add(path.toString());\n }", "public static final Date getDate(InputStream is) throws IOException\n {\n long timeInSeconds = getInt(is);\n if (timeInSeconds == 0x93406FFF)\n {\n return null;\n }\n timeInSeconds -= 3600;\n timeInSeconds *= 1000;\n return DateHelper.getDateFromLong(timeInSeconds);\n }", "public static <T extends Range> T findRange(List<T> ranges, long value, int arraySize) {\n if (ranges.size() < 1) return null;\n T first = ranges.get(0);\n T last = ranges.get(arraySize - 1);\n // check out of bounds\n if (value < first.start() || value > last.start() + last.size()) {\n throw new OffsetOutOfRangeException(format(\"offset %s is out of range (%s, %s)\",//\n value,first.start(),last.start()+last.size()));\n }\n\n // check at the end\n if (value == last.start() + last.size()) return null;\n\n int low = 0;\n int high = arraySize - 1;\n while (low <= high) {\n int mid = (high + low) / 2;\n T found = ranges.get(mid);\n if (found.contains(value)) {\n return found;\n } else if (value < found.start()) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n }\n return null;\n }", "public static boolean unzipFileOrFolder(File zipFile, String unzippedFolder){\n\t\tInputStream is;\n\t\tArchiveInputStream in = null;\n\t\tOutputStream out = null;\n\t\t\n\t\tif(!zipFile.isFile()){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif(unzippedFolder == null){\n\t\t\tunzippedFolder = FilenameUtils.removeExtension(zipFile.getAbsolutePath());\n\t\t}\n\t\ttry {\n\t\t\tis = new FileInputStream(zipFile);\n\t\t\tnew File(unzippedFolder).mkdir();\n\t\t\t\n\t\t\tin = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP, is);\n\t\t\t\n\t\t\tZipArchiveEntry entry = (ZipArchiveEntry)in.getNextEntry();\n\t\t\twhile(entry != null){\n\t\t\t\tif(entry.isDirectory()){\n\t\t\t\t\tnew File(unzippedFolder,entry.getName()).mkdir();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tout = new FileOutputStream(new File(unzippedFolder, entry.getName()));\n\t\t\t\t\tIOUtils.copy(in, out);\n\t\t\t\t\tout.close();\n\t\t\t\t\tout = null;\n\t\t\t\t}\n\t\t\t\tentry = (ZipArchiveEntry)in.getNextEntry();\n\t\t\t}\t\n\t\t} catch (FileNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t} catch (ArchiveException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t\tfinally{\n\t\t\tif(out != null){\n\t\t\t\ttry {\n\t\t\t\t\tout.close();\n\t\t\t\t} catch (IOException e) {}\n\t\t\t}\n\t\t\tif(in != null){\n\t\t\t\ttry {\n\t\t\t\t\tin.close();\n\t\t\t\t} catch (IOException e) {}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}" ]
Sets the position of the currency symbol. @param posn currency symbol position.
[ "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 }" ]
[ "public static base_response update(nitro_service client, dbdbprofile resource) throws Exception {\n\t\tdbdbprofile updateresource = new dbdbprofile();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.interpretquery = resource.interpretquery;\n\t\tupdateresource.stickiness = resource.stickiness;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\tupdateresource.conmultiplex = resource.conmultiplex;\n\t\treturn updateresource.update_resource(client);\n\t}", "public BoxFileUploadSessionPart uploadPart(InputStream stream, long offset, int partSize,\n long totalSizeOfFile) {\n\n URL uploadPartURL = this.sessionInfo.getSessionEndpoints().getUploadPartEndpoint();\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), uploadPartURL, HttpMethod.PUT);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM);\n\n //Read the partSize bytes from the stream\n byte[] bytes = new byte[partSize];\n try {\n stream.read(bytes);\n } catch (IOException ioe) {\n throw new BoxAPIException(\"Reading data from stream failed.\", ioe);\n }\n\n return this.uploadPart(bytes, offset, partSize, totalSizeOfFile);\n }", "protected List<Integer> cancelAllActiveOperations() {\n final List<Integer> operations = new ArrayList<Integer>();\n for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) {\n activeOperation.asyncCancel(false);\n operations.add(activeOperation.getOperationId());\n }\n return operations;\n }", "public void clear() {\n if (arrMask != null) {\n for (int y = 0; y < height; y++) {\n for (int x = 0; x < width; x++) {\n arrMask[x][y] = false;\n }\n }\n }\n }", "@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 URL asUrlOrResource(String s) {\n if (Strings.isNullOrEmpty(s)) {\n return null;\n }\n\n try {\n return new URL(s);\n } catch (MalformedURLException e) {\n //If its not a valid URL try to treat it as a local resource.\n return findConfigResource(s);\n }\n }", "public <T> T callFunction(\n final String name,\n final List<?> args,\n final @Nullable Long requestTimeout,\n final Class<T> resultClass,\n final CodecRegistry codecRegistry\n ) {\n return this.functionService\n .withCodecRegistry(codecRegistry)\n .callFunction(name, args, requestTimeout, resultClass);\n }", "public void setFromJSON(Context context, JSONObject properties) {\n String backgroundResStr = optString(properties, Properties.background);\n if (backgroundResStr != null && !backgroundResStr.isEmpty()) {\n final int backgroundResId = getId(context, backgroundResStr, \"drawable\");\n setBackGround(context.getResources().getDrawable(backgroundResId, null));\n }\n\n setBackgroundColor(getJSONColor(properties, Properties.background_color, getBackgroundColor()));\n setGravity(optInt(properties, TextContainer.Properties.gravity, getGravity()));\n setRefreshFrequency(optEnum(properties, Properties.refresh_freq, getRefreshFrequency()));\n setTextColor(getJSONColor(properties, Properties.text_color, getTextColor()));\n setText(optString(properties, Properties.text, (String) getText()));\n setTextSize(optFloat(properties, Properties.text_size, getTextSize()));\n\n final JSONObject typefaceJson = optJSONObject(properties, Properties.typeface);\n\n if (typefaceJson != null) {\n try {\n Typeface typeface = WidgetLib.getTypefaceManager().getTypeface(typefaceJson);\n setTypeface(typeface);\n } catch (Throwable e) {\n Log.e(TAG, e, \"Couldn't set typeface from properties: %s\", typefaceJson);\n }\n }\n }", "private List<Object> doQuery(\n\t\t\tSharedSessionContractImplementor session,\n\t\t\tQueryParameters qp,\n\t\t\tOgmLoadingContext ogmLoadingContext,\n\t\t\tboolean returnProxies) {\n\t\t//TODO support lock timeout\n\n\t\tint entitySpan = entityPersisters.length;\n\t\tfinal List<Object> hydratedObjects = entitySpan == 0 ? null : new ArrayList<Object>( entitySpan * 10 );\n\t\t//TODO yuk! Is there a cleaner way to access the id?\n\t\tfinal Serializable id;\n\t\t// see if we use batching first\n\t\t// then look for direct id\n\t\t// then for a tuple based result set we could extract the id\n\t\t// otherwise that's a collection so we use the collection key\n\t\tboolean loadSeveralIds = loadSeveralIds( qp );\n\t\tboolean isCollectionLoader;\n\t\tif ( loadSeveralIds ) {\n\t\t\t// need to be set to null otherwise the optionalId has precedence\n\t\t\t// and is used for all tuples regardless of their actual ids\n\t\t\tid = null;\n\t\t\tisCollectionLoader = false;\n\t\t}\n\t\telse if ( qp.getOptionalId() != null ) {\n\t\t\tid = qp.getOptionalId();\n\t\t\tisCollectionLoader = false;\n\t\t}\n\t\telse if ( ogmLoadingContext.hasResultSet() ) {\n\t\t\t// extract the ids from the tuples directly\n\t\t\tid = null;\n\t\t\tisCollectionLoader = false;\n\t\t}\n\t\telse {\n\t\t\tid = qp.getCollectionKeys()[0];\n\t\t\tisCollectionLoader = true;\n\t\t}\n\t\tTupleAsMapResultSet resultset = getResultSet( id, qp, ogmLoadingContext, session );\n\n\t\t//Todo implement lockmode\n\t\t//final LockMode[] lockModesArray = getLockModes( queryParameters.getLockOptions() );\n\t\t//FIXME should we use subselects as it's closer to this process??\n\n\t\t//TODO is resultset a good marker, or should it be an ad-hoc marker??\n\t\t//It likely all depends on what resultset ends up being\n\t\thandleEmptyCollections( qp.getCollectionKeys(), resultset, session );\n\n\t\tfinal org.hibernate.engine.spi.EntityKey[] keys = new org.hibernate.engine.spi.EntityKey[entitySpan];\n\n\t\t//for each element in resultset\n\t\t//TODO should we collect List<Object> as result? Not necessary today\n\t\tObject result = null;\n\t\tList<Object> results = new ArrayList<Object>();\n\n\t\tif ( isCollectionLoader ) {\n\t\t\tpreLoadBatchFetchingQueue( session, resultset );\n\n\t\t}\n\n\t\ttry {\n\t\t\twhile ( resultset.next() ) {\n\t\t\t\tresult = getRowFromResultSet(\n\t\t\t\t\t\tresultset,\n\t\t\t\t\t\tsession,\n\t\t\t\t\t\tqp,\n\t\t\t\t\t\togmLoadingContext,\n\t\t\t\t\t\t//lockmodeArray,\n\t\t\t\t\t\tid,\n\t\t\t\t\t\thydratedObjects,\n\t\t\t\t\t\tkeys,\n\t\t\t\t\t\treturnProxies );\n\t\t\t\tresults.add( result );\n\t\t\t}\n\t\t\t//TODO collect subselect result key\n\t\t}\n\t\tcatch ( SQLException e ) {\n\t\t\t//never happens this is not a regular ResultSet\n\t\t}\n\n\t\t//end of for each element in resultset\n\n\t\tinitializeEntitiesAndCollections( hydratedObjects, resultset, session, qp.isReadOnly( session ) );\n\t\t//TODO create subselects\n\t\treturn results;\n\t}" ]
Returns the average event value in the current interval
[ "public Double getAvgEventValue() {\n resetIfNeeded();\n synchronized(this) {\n long eventsLastInterval = numEventsLastInterval - numEventsLastLastInterval;\n if(eventsLastInterval > 0)\n return ((totalEventValueLastInterval - totalEventValueLastLastInterval) * 1.0)\n / eventsLastInterval;\n else\n return 0.0;\n }\n }" ]
[ "public static void Forward(double[] data) {\n\n double[] result = new double[data.length];\n double sum;\n double scale = Math.sqrt(2.0 / data.length);\n for (int f = 0; f < data.length; f++) {\n sum = 0;\n for (int t = 0; t < data.length; t++) {\n double cos = Math.cos(((2.0 * t + 1.0) * f * Math.PI) / (2.0 * data.length));\n sum += data[t] * cos * alpha(f);\n }\n result[f] = scale * sum;\n }\n for (int i = 0; i < data.length; i++) {\n data[i] = result[i];\n }\n }", "public void setAngle(float angle) {\n this.angle = angle;\n float cos = (float) Math.cos(angle);\n float sin = (float) Math.sin(angle);\n m00 = cos;\n m01 = sin;\n m10 = -sin;\n m11 = cos;\n }", "private void addDirectSubTypes(XClass type, ArrayList subTypes)\r\n {\r\n if (type.isInterface())\r\n {\r\n if (type.getExtendingInterfaces() != null)\r\n {\r\n subTypes.addAll(type.getExtendingInterfaces());\r\n }\r\n // we have to traverse the implementing classes as these array contains all classes that\r\n // implement the interface, not only those who have an \"implement\" declaration\r\n // note that for whatever reason the declared interfaces are not exported via the XClass interface\r\n // so we have to get them via the underlying class which is hopefully a subclass of AbstractClass\r\n if (type.getImplementingClasses() != null)\r\n {\r\n Collection declaredInterfaces = null;\r\n XClass subType;\r\n\r\n for (Iterator it = type.getImplementingClasses().iterator(); it.hasNext(); )\r\n {\r\n subType = (XClass)it.next();\r\n if (subType instanceof AbstractClass)\r\n {\r\n declaredInterfaces = ((AbstractClass)subType).getDeclaredInterfaces();\r\n if ((declaredInterfaces != null) && declaredInterfaces.contains(type))\r\n {\r\n subTypes.add(subType);\r\n }\r\n }\r\n else\r\n {\r\n // Otherwise we have to live with the bug\r\n subTypes.add(subType);\r\n }\r\n }\r\n }\r\n }\r\n else\r\n {\r\n subTypes.addAll(type.getDirectSubclasses());\r\n }\r\n }", "public void reportCompletion(NodeT completed) {\n completed.setPreparer(true);\n String dependency = completed.key();\n for (String dependentKey : nodeTable.get(dependency).dependentKeys()) {\n DAGNode<DataT, NodeT> dependent = nodeTable.get(dependentKey);\n dependent.lock().lock();\n try {\n dependent.onSuccessfulResolution(dependency);\n if (dependent.hasAllResolved()) {\n queue.add(dependent.key());\n }\n } finally {\n dependent.lock().unlock();\n }\n }\n }", "public CompositeGeneratorNode indent(final CompositeGeneratorNode parent, final String indentString) {\n final IndentNode indent = new IndentNode(indentString);\n List<IGeneratorNode> _children = parent.getChildren();\n _children.add(indent);\n return indent;\n }", "private int combineSubsetBlocks(Mode[] mode_type, int[] mode_length, int index_point) {\n /* bring together same type blocks */\n if (index_point > 1) {\n for (int i = 1; i < index_point; i++) {\n if (mode_type[i - 1] == mode_type[i]) {\n /* bring together */\n mode_length[i - 1] = mode_length[i - 1] + mode_length[i];\n /* decrease the list */\n for (int j = i + 1; j < index_point; j++) {\n mode_length[j - 1] = mode_length[j];\n mode_type[j - 1] = mode_type[j];\n }\n index_point--;\n i--;\n }\n }\n }\n return index_point;\n }", "public static final long getLong(byte[] data, int offset)\n {\n if (data.length != 8)\n {\n throw new UnexpectedStructureException();\n }\n\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 64; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }", "public RuntimeParameter addParameter(String key, String value)\n {\n RuntimeParameter jp = new RuntimeParameter();\n jp.setJi(this.getId());\n jp.setKey(key);\n jp.setValue(value);\n return jp;\n }", "public static responderhtmlpage get(nitro_service service) throws Exception{\n\t\tresponderhtmlpage obj = new responderhtmlpage();\n\t\tresponderhtmlpage[] response = (responderhtmlpage[])obj.get_resources(service);\n\t\treturn response[0];\n\t}" ]
Get content for URL only @param stringUrl URL to get content @return the content @throws IOException I/O error happened
[ "public static String getContent(String stringUrl) throws IOException {\n InputStream stream = getContentStream(stringUrl);\n return MyStreamUtils.readContent(stream);\n }" ]
[ "public static boolean xpathExists(Node document, String xpathExpression, Map<String, String> namespaceMapping) throws XPathException,\n MarshallingException\n {\n Boolean result = (Boolean) executeXPath(document, xpathExpression, namespaceMapping, XPathConstants.BOOLEAN);\n return result != null && result;\n }", "protected List<Object> executeProcessors(final List<Object> processedColumns, final CellProcessor[] processors) {\n\t\tUtil.executeCellProcessors(processedColumns, getColumns(), processors, getLineNumber(), getRowNumber());\n\t\treturn processedColumns;\n\t}", "@Override\n\tpublic Set<String> getRoundingNames(String... providers) {\n Set<String> result = new HashSet<>();\n String[] providerNames = providers;\n if (providerNames.length == 0) {\n providerNames = Monetary.getDefaultRoundingProviderChain().toArray(new String[Monetary.getDefaultRoundingProviderChain().size()]);\n }\n for (String providerName : providerNames) {\n for (RoundingProviderSpi prov : Bootstrap.getServices(RoundingProviderSpi.class)) {\n try {\n if (prov.getProviderName().equals(providerName) || prov.getProviderName().matches(providerName)) {\n result.addAll(prov.getRoundingNames());\n }\n } catch (Exception e) {\n Logger.getLogger(DefaultMonetaryRoundingsSingletonSpi.class.getName())\n .log(Level.SEVERE, \"Error loading RoundingProviderSpi from provider: \" + prov, e);\n }\n }\n }\n return result;\n }", "public static Calendar popCalendar()\n {\n Calendar result;\n Deque<Calendar> calendars = CALENDARS.get();\n if (calendars.isEmpty())\n {\n result = Calendar.getInstance();\n }\n else\n {\n result = calendars.pop();\n }\n return result;\n }", "private void primeCache() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) {\n if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck\n handleUpdate(new TrackMetadataUpdate(entry.getKey().player, entry.getValue()));\n }\n }\n }\n });\n }", "private void processGeneratedProperties(\n\t\t\tSerializable id,\n\t\t\tObject entity,\n\t\t\tObject[] state,\n\t\t\tSharedSessionContractImplementor session,\n\t\t\tGenerationTiming matchTiming) {\n\n\t\tTuple tuple = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );\n\t\tsaveSharedTuple( entity, tuple, session );\n\n\t\tif ( tuple == null || tuple.getSnapshot().isEmpty() ) {\n\t\t\tthrow log.couldNotRetrieveEntityForRetrievalOfGeneratedProperties( getEntityName(), id );\n\t\t}\n\n\t\tint propertyIndex = -1;\n\t\tfor ( NonIdentifierAttribute attribute : getEntityMetamodel().getProperties() ) {\n\t\t\tpropertyIndex++;\n\t\t\tfinal ValueGeneration valueGeneration = attribute.getValueGenerationStrategy();\n\t\t\tif ( isReadRequired( valueGeneration, matchTiming ) ) {\n\t\t\t\tObject hydratedState = gridPropertyTypes[propertyIndex].hydrate( tuple, getPropertyAliases( \"\", propertyIndex ), session, entity );\n\t\t\t\tstate[propertyIndex] = gridPropertyTypes[propertyIndex].resolve( hydratedState, session, entity );\n\t\t\t\tsetPropertyValue( entity, propertyIndex, state[propertyIndex] );\n\t\t\t}\n\t\t}\n\t}", "public static String encodeFragment(String fragment, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(fragment, encoding, HierarchicalUriComponents.Type.FRAGMENT);\n\t}", "public static void setViewBackground(View v, Drawable d) {\n if (Build.VERSION.SDK_INT >= 16) {\n v.setBackground(d);\n } else {\n v.setBackgroundDrawable(d);\n }\n }", "public void clear() {\n\t\tfor (Bean bean : beans.values()) {\n\t\t\tif (null != bean.destructionCallback) {\n\t\t\t\tbean.destructionCallback.run();\n\t\t\t}\n\t\t}\n\t\tbeans.clear();\n\t}" ]
Readable yyyyMMdd representation of a day, which is also sortable.
[ "public static int getDayAsReadableInt(Calendar calendar) {\n int day = calendar.get(Calendar.DAY_OF_MONTH);\n int month = calendar.get(Calendar.MONTH) + 1;\n int year = calendar.get(Calendar.YEAR);\n return year * 10000 + month * 100 + day;\n }" ]
[ "public boolean removeCustomResponse(String pathValue, String requestType) {\n try {\n JSONObject path = getPathFromEndpoint(pathValue, requestType);\n if (path == null) {\n return false;\n }\n String pathId = path.getString(\"pathId\");\n return resetResponseOverride(pathId);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "public static Diagram parseJson(String json,\n Boolean keepGlossaryLink) throws JSONException {\n JSONObject modelJSON = new JSONObject(json);\n return parseJson(modelJSON,\n keepGlossaryLink);\n }", "public double totalCount() {\r\n if (depth() == 1) {\r\n return total; // I think this one is always OK. Not very principled here, though.\r\n } else {\r\n double result = 0.0;\r\n for (K o: topLevelKeySet()) {\r\n result += conditionalizeOnce(o).totalCount();\r\n }\r\n return result;\r\n }\r\n }", "public GVRShader getTemplate(GVRContext ctx)\n {\n if (mShaderTemplate == null)\n {\n mShaderTemplate = makeTemplate(ID, ctx);\n ctx.getShaderManager().addShaderID(this);\n }\n return mShaderTemplate;\n }", "private long getTime(Date start, Date end, long target, boolean after)\n {\n long total = 0;\n if (start != null && end != null)\n {\n Date startTime = DateHelper.getCanonicalTime(start);\n Date endTime = DateHelper.getCanonicalTime(end);\n\n Date startDay = DateHelper.getDayStartDate(start);\n Date finishDay = DateHelper.getDayStartDate(end);\n\n //\n // Handle the case where the end of the range is at midnight -\n // this will show up as the start and end days not matching\n //\n if (startDay.getTime() != finishDay.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n int diff = DateHelper.compare(startTime, endTime, target);\n if (diff == 0)\n {\n if (after == true)\n {\n total = (endTime.getTime() - target);\n }\n else\n {\n total = (target - startTime.getTime());\n }\n }\n else\n {\n if ((after == true && diff < 0) || (after == false && diff > 0))\n {\n total = (endTime.getTime() - startTime.getTime());\n }\n }\n }\n return (total);\n }", "public static sslvserver_sslcipher_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslcipher_binding obj = new sslvserver_sslcipher_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslcipher_binding response[] = (sslvserver_sslcipher_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static String getFlowContext() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.flowContext;\n }", "private void writeAllEnvelopes(boolean reuse)\r\n {\r\n // perform remove of m:n indirection table entries first\r\n performM2NUnlinkEntries();\r\n\r\n Iterator iter;\r\n // using clone to avoid ConcurentModificationException\r\n iter = ((List) mvOrderOfIds.clone()).iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n boolean insert = false;\r\n if(needsCommit)\r\n {\r\n insert = mod.needsInsert();\r\n mod.getModificationState().commit(mod);\r\n if(reuse && insert)\r\n {\r\n getTransaction().doSingleLock(mod.getClassDescriptor(), mod.getObject(), mod.getIdentity(), Transaction.WRITE);\r\n }\r\n }\r\n /*\r\n arminw: important to call this cleanup method for each registered\r\n ObjectEnvelope, because this method will e.g. remove proxy listener\r\n objects for registered objects.\r\n */\r\n mod.cleanup(reuse, insert);\r\n }\r\n // add m:n indirection table entries\r\n performM2NLinkEntries();\r\n }", "private void addModuleToGraph(final DbModule module, final AbstractGraph graph, final int depth) {\n if (graph.isTreated(graph.getId(module))) {\n return;\n }\n\n final String moduleElementId = graph.getId(module);\n graph.addElement(moduleElementId, module.getVersion(), depth == 0);\n\n if (filters.getDepthHandler().shouldGoDeeper(depth)) {\n for (final DbDependency dep : DataUtils.getAllDbDependencies(module)) {\n if(filters.shouldBeInReport(dep)){\n addDependencyToGraph(dep, graph, depth + 1, moduleElementId);\n }\n }\n }\n }" ]
Sets a quota for a users. @param user the user. @param quota the quota.
[ "public static void setQuota(final GreenMailUser user, final Quota quota) {\r\n Session session = GreenMailUtil.getSession(ServerSetupTest.IMAP);\r\n try {\r\n Store store = session.getStore(\"imap\");\r\n store.connect(user.getEmail(), user.getPassword());\r\n try {\r\n ((QuotaAwareStore) store).setQuota(quota);\r\n } finally {\r\n store.close();\r\n }\r\n } catch (Exception ex) {\r\n throw new IllegalStateException(\"Can not set quota \" + quota\r\n + \" for user \" + user, ex);\r\n }\r\n }" ]
[ "private void readCalendars(Storepoint phoenixProject)\n {\n Calendars calendars = phoenixProject.getCalendars();\n if (calendars != null)\n {\n for (Calendar calendar : calendars.getCalendar())\n {\n readCalendar(calendar);\n }\n\n ProjectCalendar defaultCalendar = m_projectFile.getCalendarByName(phoenixProject.getDefaultCalendar());\n if (defaultCalendar != null)\n {\n m_projectFile.getProjectProperties().setDefaultCalendarName(defaultCalendar.getName());\n }\n }\n }", "public static void writeShortString(ByteBuffer buffer, String s) {\n if (s == null) {\n buffer.putShort((short) -1);\n } else if (s.length() > Short.MAX_VALUE) {\n throw new IllegalArgumentException(\"String exceeds the maximum size of \" + Short.MAX_VALUE + \".\");\n } else {\n byte[] data = getBytes(s); //topic support non-ascii character\n buffer.putShort((short) data.length);\n buffer.put(data);\n }\n }", "@Override\n\tpublic int compareTo(IPAddressString other) {\n\t\tif(this == other) {\n\t\t\treturn 0;\n\t\t}\n\t\tboolean isValid = isValid();\n\t\tboolean otherIsValid = other.isValid();\n\t\tif(!isValid && !otherIsValid) {\n\t\t\treturn toString().compareTo(other.toString());\n\t\t}\n\t\treturn addressProvider.providerCompare(other.addressProvider);\n\t}", "protected void createKeystore() {\n\n\t\tjava.security.cert.Certificate signingCert = null;\n\t\tPrivateKey caPrivKey = null;\n\n\t\tif(_caCert == null || _caPrivKey == null)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tlog.debug(\"Keystore or signing cert & keypair not found. Generating...\");\n\n\t\t\t\tKeyPair caKeypair = getRSAKeyPair();\n\t\t\t\tcaPrivKey = caKeypair.getPrivate();\n\t\t\t\tsigningCert = CertificateCreator.createTypicalMasterCert(caKeypair);\n\n\t\t\t\tlog.debug(\"Done generating signing cert\");\n\t\t\t\tlog.debug(signingCert);\n\n\t\t\t\t_ks.load(null, _keystorepass);\n\n\t\t\t\t_ks.setCertificateEntry(_caCertAlias, signingCert);\n\t\t\t\t_ks.setKeyEntry(_caPrivKeyAlias, caPrivKey, _keypassword, new java.security.cert.Certificate[] {signingCert});\n\n\t\t\t\tFile caKsFile = new File(root, _caPrivateKeystore);\n\n\t\t\t\tOutputStream os = new FileOutputStream(caKsFile);\n\t\t\t\t_ks.store(os, _keystorepass);\n\n\t\t\t\tlog.debug(\"Wrote JKS keystore to: \" +\n\t\t\t\t\t\tcaKsFile.getAbsolutePath());\n\n\t\t\t\t// also export a .cer that can be imported as a trusted root\n\t\t\t\t// to disable all warning dialogs for interception\n\n\t\t\t\tFile signingCertFile = new File(root, EXPORTED_CERT_NAME);\n\n\t\t\t\tFileOutputStream cerOut = new FileOutputStream(signingCertFile);\n\n\t\t\t\tbyte[] buf = signingCert.getEncoded();\n\n\t\t\t\tlog.debug(\"Wrote signing cert to: \" + signingCertFile.getAbsolutePath());\n\n\t\t\t\tcerOut.write(buf);\n\t\t\t\tcerOut.flush();\n\t\t\t\tcerOut.close();\n\n\t\t\t\t_caCert = (X509Certificate)signingCert;\n\t\t\t\t_caPrivKey = caPrivKey;\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tlog.error(\"Fatal error creating/storing keystore or signing cert.\", e);\n\t\t\t\tthrow new Error(e);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlog.debug(\"Successfully loaded keystore.\");\n\t\t\tlog.debug(_caCert);\n\n\t\t}\n\n\t}", "public void setSize(int size) {\n if (size != MaterialProgressDrawable.LARGE && size != MaterialProgressDrawable.DEFAULT) {\n return;\n }\n final DisplayMetrics metrics = getResources().getDisplayMetrics();\n if (size == MaterialProgressDrawable.LARGE) {\n mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER_LARGE * metrics.density);\n } else {\n mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);\n }\n // force the bounds of the progress circle inside the circle view to\n // update by setting it to null before updating its size and then\n // re-setting it\n mCircleView.setImageDrawable(null);\n mProgress.updateSizes(size);\n mCircleView.setImageDrawable(mProgress);\n }", "private void addProgressInterceptor() {\n httpClient.networkInterceptors().add(new Interceptor() {\n @Override\n public Response intercept(Interceptor.Chain chain) throws IOException {\n final Request request = chain.request();\n final Response originalResponse = chain.proceed(request);\n if (request.tag() instanceof ApiCallback) {\n final ApiCallback callback = (ApiCallback) request.tag();\n return originalResponse.newBuilder()\n .body(new ProgressResponseBody(originalResponse.body(), callback)).build();\n }\n return originalResponse;\n }\n });\n }", "public void build(double[] coords, int nump) throws IllegalArgumentException {\n if (nump < 4) {\n throw new IllegalArgumentException(\"Less than four input points specified\");\n }\n if (coords.length / 3 < nump) {\n throw new IllegalArgumentException(\"Coordinate array too small for specified number of points\");\n }\n initBuffers(nump);\n setPoints(coords, nump);\n buildHull();\n }", "public Number getCostVariance()\n {\n Number variance = (Number) getCachedValue(TaskField.COST_VARIANCE);\n if (variance == null)\n {\n Number cost = getCost();\n Number baselineCost = getBaselineCost();\n if (cost != null && baselineCost != null)\n {\n variance = NumberHelper.getDouble(cost.doubleValue() - baselineCost.doubleValue());\n set(TaskField.COST_VARIANCE, variance);\n }\n }\n return (variance);\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 }" ]
Handles subscription verification callback from Facebook. @param subscription The subscription name. @param challenge A challenge that Facebook expects to be returned. @param verifyToken A verification token that must match with the subscription's token given when the controller was created. @return The challenge if the verification token matches; blank string otherwise.
[ "@RequestMapping(value=\"/{subscription}\", method=GET, params=\"hub.mode=subscribe\")\n\tpublic @ResponseBody String verifySubscription(\n\t\t\t@PathVariable(\"subscription\") String subscription,\n\t\t\t@RequestParam(\"hub.challenge\") String challenge,\n\t\t\t@RequestParam(\"hub.verify_token\") String verifyToken) {\n\t\tlogger.debug(\"Received subscription verification request for '\" + subscription + \"'.\");\n\t\treturn tokens.containsKey(subscription) && tokens.get(subscription).equals(verifyToken) ? challenge : \"\";\n\t}" ]
[ "public GVRShader getTemplate(GVRContext ctx)\n {\n if (mShaderTemplate == null)\n {\n mShaderTemplate = makeTemplate(ID, ctx);\n ctx.getShaderManager().addShaderID(this);\n }\n return mShaderTemplate;\n }", "public BoxRetentionPolicyAssignment.Info assignToMetadataTemplate(String templateID,\r\n MetadataFieldFilter... fieldFilters) {\r\n return BoxRetentionPolicyAssignment.createAssignmentToMetadata(this.getAPI(), this.getID(), templateID,\r\n fieldFilters);\r\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 }", "public Future<HazeltaskTask<GROUP>> addPendingTaskAsync(HazeltaskTask<GROUP> task) {\n return pendingTask.putAsync(task.getId(), task);\n }", "public String renameApp(String appName, String newName) {\n return connection.execute(new AppRename(appName, newName), apiKey).getName();\n }", "public void setPickingEnabled(boolean enabled) {\n if (enabled != getPickingEnabled()) {\n if (enabled) {\n attachComponent(new GVRSphereCollider(getGVRContext()));\n } else {\n detachComponent(GVRCollider.getComponentType());\n }\n }\n }", "public static inatparam get(nitro_service service) throws Exception{\n\t\tinatparam obj = new inatparam();\n\t\tinatparam[] response = (inatparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public void setOwner(Graph<DataT, NodeT> ownerGraph) {\n if (this.ownerGraph != null) {\n throw new RuntimeException(\"Changing owner graph is not allowed\");\n }\n this.ownerGraph = ownerGraph;\n }", "@Override\n\tpublic Object[] getDatabaseSnapshot(Serializable id, SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\n\t\tif ( log.isTraceEnabled() ) {\n\t\t\tlog.trace( \"Getting current persistent state for: \" + MessageHelper.infoString( this, id, getFactory() ) );\n\t\t}\n\n\t\t//snapshot is a Map in the end\n\t\tfinal Tuple resultset = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );\n\n\t\t//if there is no resulting row, return null\n\t\tif ( resultset == null || resultset.getSnapshot().isEmpty() ) {\n\t\t\treturn null;\n\t\t}\n\t\t//otherwise return the \"hydrated\" state (ie. associations are not resolved)\n\t\tGridType[] types = gridPropertyTypes;\n\t\tObject[] values = new Object[types.length];\n\t\tboolean[] includeProperty = getPropertyUpdateability();\n\t\tfor ( int i = 0; i < types.length; i++ ) {\n\t\t\tif ( includeProperty[i] ) {\n\t\t\t\tvalues[i] = types[i].hydrate( resultset, getPropertyAliases( \"\", i ), session, null ); //null owner ok??\n\t\t\t}\n\t\t}\n\t\treturn values;\n\t}" ]
Use this API to update dospolicy.
[ "public static base_response update(nitro_service client, dospolicy resource) throws Exception {\n\t\tdospolicy updateresource = new dospolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.qdepth = resource.qdepth;\n\t\tupdateresource.cltdetectrate = resource.cltdetectrate;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
[ "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 ItemRequest<Story> findById(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"GET\");\n }", "public void setVec4(String key, float x, float y, float z, float w)\n {\n checkKeyIsUniform(key);\n NativeLight.setVec4(getNative(), key, x, y, z, w);\n }", "public void addProjectListeners(List<ProjectListener> listeners)\n {\n if (listeners != null)\n {\n for (ProjectListener listener : listeners)\n {\n addProjectListener(listener);\n }\n }\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}", "public static final GVRPickedObject[] pickObjects(GVRScene scene, float ox, float oy, float oz, float dx,\n float dy, float dz) {\n sFindObjectsLock.lock();\n try {\n final GVRPickedObject[] result = NativePicker.pickObjects(scene.getNative(), 0L, ox, oy, oz, dx, dy, dz);\n return result;\n } finally {\n sFindObjectsLock.unlock();\n }\n }", "public synchronized void mapPublicKeys(final PublicKey original, final PublicKey substitute)\n\t{\n\t\t_mappedPublicKeys.put(original, substitute);\n\t\tif(persistImmediately) { persistPublicKeyMap(); }\n\t}", "public void addNode(NodeT node) {\n node.setOwner(this);\n nodeTable.put(node.key(), node);\n }", "public static int restrictRange(int value, int min, int max)\n {\n return Math.min((Math.max(value, min)), max);\n }" ]
Test for equality. @param obj1 the first object @param obj2 the second object @return true if both are null or the two objects are equal
[ "public static boolean nullSafeEquals(final Object obj1, final Object obj2) {\n return ((obj1 == null && obj2 == null)\n || (obj1 != null && obj2 != null && obj1.equals(obj2)));\n }" ]
[ "public MetaClassRegistryChangeEventListener[] getMetaClassRegistryChangeEventListeners() {\n synchronized (changeListenerList) {\n ArrayList<MetaClassRegistryChangeEventListener> ret =\n new ArrayList<MetaClassRegistryChangeEventListener>(changeListenerList.size()+nonRemoveableChangeListenerList.size());\n ret.addAll(nonRemoveableChangeListenerList);\n ret.addAll(changeListenerList);\n return ret.toArray(new MetaClassRegistryChangeEventListener[ret.size()]);\n }\n }", "private void executeResult() throws Exception {\n\t\tresult = createResult();\n\n\t\tString timerKey = \"executeResult: \" + getResultCode();\n\t\ttry {\n\t\t\tUtilTimerStack.push(timerKey);\n\t\t\tif (result != null) {\n\t\t\t\tresult.execute(this);\n\t\t\t} else if (resultCode != null && !Action.NONE.equals(resultCode)) {\n\t\t\t\tthrow new ConfigurationException(\"No result defined for action \" + getAction().getClass().getName()\n\t\t\t\t\t\t+ \" and result \" + getResultCode(), proxy.getConfig());\n\t\t\t} else {\n\t\t\t\tif (LOG.isDebugEnabled()) {\n\t\t\t\t\tLOG.debug(\"No result returned for action \" + getAction().getClass().getName() + \" at \"\n\t\t\t\t\t\t\t+ proxy.getConfig().getLocation());\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tUtilTimerStack.pop(timerKey);\n\t\t}\n\t}", "public String convertToReadableDate(Holiday holiday) {\n DateTimeFormatter parser = ISODateTimeFormat.date();\n\n if (holiday.isInDateForm()) {\n String month = Integer.toString(holiday.getMonth()).length() < 2\n ? \"0\" + holiday.getMonth() : Integer.toString(holiday.getMonth());\n String day = Integer.toString(holiday.getDayOfMonth()).length() < 2\n ? \"0\" + holiday.getDayOfMonth() : Integer.toString(holiday.getDayOfMonth());\n return holiday.getYear() + \"-\" + month + \"-\" + day;\n } else {\n /*\n * 5 denotes the final occurrence of the day in the month. Need to find actual\n * number of occurrences\n */\n if (holiday.getOccurrence() == 5) {\n holiday.setOccurrence(numOccurrences(holiday.getYear(), holiday.getMonth(),\n holiday.getDayOfWeek()));\n }\n\n DateTime date = parser.parseDateTime(holiday.getYear() + \"-\"\n + holiday.getMonth() + \"-\" + \"01\");\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date.toDate());\n int count = 0;\n\n while (count < holiday.getOccurrence()) {\n if (calendar.get(Calendar.DAY_OF_WEEK) == holiday.getDayOfWeek()) {\n count++;\n if (count == holiday.getOccurrence()) {\n break;\n }\n }\n date = date.plusDays(1);\n calendar.setTime(date.toDate());\n }\n return date.toString().substring(0, 10);\n }\n }", "private <T> Observable<PollingState<T>> updateStateFromLocationHeaderOnPutAsync(final PollingState<T> pollingState) {\n return pollAsync(pollingState.locationHeaderLink(), pollingState.loggingContext())\n .flatMap(new Func1<Response<ResponseBody>, Observable<PollingState<T>>>() {\n @Override\n public Observable<PollingState<T>> call(Response<ResponseBody> response) {\n int statusCode = response.code();\n if (statusCode == 202) {\n pollingState.withResponse(response);\n pollingState.withStatus(AzureAsyncOperation.IN_PROGRESS_STATUS, statusCode);\n } else if (statusCode == 200 || statusCode == 201) {\n try {\n pollingState.updateFromResponseOnPutPatch(response);\n } catch (CloudException | IOException e) {\n return Observable.error(e);\n }\n }\n return Observable.just(pollingState);\n }\n });\n }", "public static SpinXmlElement XML(Object input) {\n return SpinFactory.INSTANCE.createSpin(input, DataFormats.xml());\n }", "public static lbvserver get(nitro_service service, String name) throws Exception{\n\t\tlbvserver obj = new lbvserver();\n\t\tobj.set_name(name);\n\t\tlbvserver response = (lbvserver) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void log(Level level, String msg) {\n\t\tlogIfEnabled(level, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);\n\t}", "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}", "private void configureConfigurationSelector() {\n\n if (m_checkinBean.getConfigurations().size() < 2) {\n // Do not show the configuration selection at all.\n removeComponent(m_configurationSelectionPanel);\n } else {\n for (CmsGitConfiguration configuration : m_checkinBean.getConfigurations()) {\n m_configurationSelector.addItem(configuration);\n m_configurationSelector.setItemCaption(configuration, configuration.getName());\n }\n m_configurationSelector.setNullSelectionAllowed(false);\n m_configurationSelector.setNewItemsAllowed(false);\n m_configurationSelector.setWidth(\"350px\");\n m_configurationSelector.select(m_checkinBean.getCurrentConfiguration());\n\n // There is really a choice between configurations\n m_configurationSelector.addValueChangeListener(new ValueChangeListener() {\n\n private static final long serialVersionUID = 1L;\n\n @SuppressWarnings(\"synthetic-access\")\n public void valueChange(ValueChangeEvent event) {\n\n updateForNewConfiguration((CmsGitConfiguration)event.getProperty().getValue());\n restoreFieldsFromUserInfo();\n\n }\n });\n }\n }" ]
Parse an extended attribute currency value. @param value string representation @return currency value
[ "public static final Number parseExtendedAttributeCurrency(String value)\n {\n Number result;\n\n if (value == null)\n {\n result = null;\n }\n else\n {\n result = NumberHelper.getDouble(Double.parseDouble(correctNumberFormat(value)) / 100);\n }\n return result;\n }" ]
[ "@Override\n public final Double optDouble(final String key, final Double defaultValue) {\n Double result = optDouble(key);\n return result == null ? defaultValue : result;\n }", "public void symm2x2_fast( double a11 , double a12, double a22 )\n {\n// double p = (a11 - a22)*0.5;\n// double r = Math.sqrt(p*p + a12*a12);\n//\n// value0.real = a22 + a12*a12/(r-p);\n// value1.real = a22 - a12*a12/(r+p);\n// }\n//\n// public void symm2x2_std( double a11 , double a12, double a22 )\n// {\n double left = (a11+a22)*0.5;\n double b = (a11-a22)*0.5;\n double right = Math.sqrt(b*b+a12*a12);\n value0.real = left + right;\n value1.real = left - right;\n }", "public static Comparator getComparator()\r\n {\r\n return new Comparator()\r\n {\r\n public int compare(Object o1, Object o2)\r\n {\r\n FieldDescriptor fmd1 = (FieldDescriptor) o1;\r\n FieldDescriptor fmd2 = (FieldDescriptor) o2;\r\n if (fmd1.getColNo() < fmd2.getColNo())\r\n {\r\n return -1;\r\n }\r\n else if (fmd1.getColNo() > fmd2.getColNo())\r\n {\r\n return 1;\r\n }\r\n else\r\n {\r\n return 0;\r\n }\r\n }\r\n };\r\n }", "public void processStencilSet() throws IOException {\n StringBuilder stencilSetFileContents = new StringBuilder();\n\n Scanner scanner = null;\n try {\n scanner = new Scanner(new File(ssInFile),\n \"UTF-8\");\n String currentLine = \"\";\n String prevLine = \"\";\n while (scanner.hasNextLine()) {\n prevLine = currentLine;\n currentLine = scanner.nextLine();\n\n String trimmedPrevLine = prevLine.trim();\n String trimmedCurrentLine = currentLine.trim();\n\n // First time processing - replace view=\"<file>.svg\" with _view_file=\"<file>.svg\" + view=\"<svg_xml>\"\n if (trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN) && trimmedCurrentLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX)) {\n String newLines = processViewPropertySvgReference(currentLine);\n stencilSetFileContents.append(newLines);\n }\n // Second time processing - replace view=\"<svg_xml>\" with refreshed contents of file referenced by previous line\n else if (trimmedPrevLine.matches(VIEW_FILE_PROPERTY_NAME_PATTERN) && trimmedPrevLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX)\n && trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN)) {\n String newLines = processViewFilePropertySvgReference(prevLine,\n currentLine);\n stencilSetFileContents.append(newLines);\n } else {\n stencilSetFileContents.append(currentLine + LINE_SEPARATOR);\n }\n }\n } finally {\n if (scanner != null) {\n scanner.close();\n }\n }\n\n Writer out = null;\n try {\n out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ssOutFile),\n \"UTF-8\"));\n out.write(stencilSetFileContents.toString());\n } catch (FileNotFoundException e) {\n\n } catch (UnsupportedEncodingException e) {\n } catch (IOException e) {\n } finally {\n if (out != null) {\n try {\n out.close();\n } catch (IOException e) {\n }\n }\n }\n\n System.out.println(\"SVG files referenced more than once:\");\n for (Map.Entry<String, Integer> stringIntegerEntry : mapSVGCounts.entrySet()) {\n if (stringIntegerEntry.getValue() > 1) {\n System.out.println(\"\\t\" + stringIntegerEntry.getKey() + \"\\t = \" + stringIntegerEntry.getValue());\n }\n }\n }", "private String validatePattern() {\n\n String error = null;\n switch (getPatternType()) {\n case DAILY:\n error = isEveryWorkingDay() ? null : validateInterval();\n break;\n case WEEKLY:\n error = validateInterval();\n if (null == error) {\n error = validateWeekDaySet();\n }\n break;\n case MONTHLY:\n error = validateInterval();\n if (null == error) {\n error = validateMonthSet();\n if (null == error) {\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n }\n }\n break;\n case YEARLY:\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n break;\n case INDIVIDUAL:\n case NONE:\n default:\n }\n return error;\n }", "public long getTimeFor(int player) {\n TrackPositionUpdate update = positions.get(player);\n if (update != null) {\n return interpolateTimeSinceUpdate(update, System.nanoTime());\n }\n return -1; // We don't know.\n }", "private void addProgressInterceptor() {\n httpClient.networkInterceptors().add(new Interceptor() {\n @Override\n public Response intercept(Interceptor.Chain chain) throws IOException {\n final Request request = chain.request();\n final Response originalResponse = chain.proceed(request);\n if (request.tag() instanceof ApiCallback) {\n final ApiCallback callback = (ApiCallback) request.tag();\n return originalResponse.newBuilder()\n .body(new ProgressResponseBody(originalResponse.body(), callback)).build();\n }\n return originalResponse;\n }\n });\n }", "public static base_responses update(nitro_service client, snmpuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpuser updateresources[] = new snmpuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new snmpuser();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].group = resources[i].group;\n\t\t\t\tupdateresources[i].authtype = resources[i].authtype;\n\t\t\t\tupdateresources[i].authpasswd = resources[i].authpasswd;\n\t\t\t\tupdateresources[i].privtype = resources[i].privtype;\n\t\t\t\tupdateresources[i].privpasswd = resources[i].privpasswd;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public void setConnectionTimeout(long connectionTimeout, TimeUnit timeUnit) {\n\t\tthis.connectionTimeoutInMs = TimeUnit.MILLISECONDS.convert(connectionTimeout, timeUnit);\n\t}" ]
Invert by solving for against an identity matrix. @param A_inv Where the inverted matrix saved. Modified.
[ "@Override\n public void invert(DMatrixRBlock A_inv) {\n int M = Math.min(QR.numRows,QR.numCols);\n if( A_inv.numRows != M || A_inv.numCols != M )\n throw new IllegalArgumentException(\"A_inv must be square an have dimension \"+M);\n\n\n // Solve for A^-1\n // Q*R*A^-1 = I\n\n // Apply householder reflectors to the identity matrix\n // y = Q^T*I = Q^T\n MatrixOps_DDRB.setIdentity(A_inv);\n decomposer.applyQTran(A_inv);\n\n // Solve using upper triangular R matrix\n // R*A^-1 = y\n // A^-1 = R^-1*y\n TriangularSolver_DDRB.solve(QR.blockLength,true,\n new DSubmatrixD1(QR,0,M,0,M),new DSubmatrixD1(A_inv),false);\n }" ]
[ "public synchronized void initTaskSchedulerIfNot() {\n\n if (scheduler == null) {\n scheduler = Executors\n .newSingleThreadScheduledExecutor(DaemonThreadFactory\n .getInstance());\n CapacityAwareTaskScheduler runner = new CapacityAwareTaskScheduler();\n scheduler.scheduleAtFixedRate(runner,\n ParallecGlobalConfig.schedulerInitDelay,\n ParallecGlobalConfig.schedulerCheckInterval,\n TimeUnit.MILLISECONDS);\n logger.info(\"initialized daemon task scheduler to evaluate waitQ tasks.\");\n \n }\n }", "public static gslbservice_stats[] get(nitro_service service) throws Exception{\n\t\tgslbservice_stats obj = new gslbservice_stats();\n\t\tgslbservice_stats[] response = (gslbservice_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public void recordAsyncOpTimeNs(SocketDestination dest, long opTimeNs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordAsyncOpTimeNs(null, opTimeNs);\n recordAsyncOpTimeNs(null, opTimeNs);\n } else {\n this.asynOpTimeRequestCounter.addRequest(opTimeNs);\n }\n }", "public boolean mapsCell(String cell) {\n return mappedCells.stream().anyMatch(x -> x.equals(cell));\n }", "private void openBrowser(URI url) throws IOException {\n if (Desktop.isDesktopSupported()) {\n Desktop.getDesktop().browse(url);\n } else {\n LOGGER.error(\"Can not open browser because this capability is not supported on \" +\n \"your platform. You can use the link below to open the report manually.\");\n }\n }", "public void scale(double v){\n\t\tfor(int i = 0; i < this.size(); i++){\n\t\t\tthis.get(i).scale(v);;\n\t\t}\n\t}", "public IntervalFrequency getRefreshFrequency() {\n switch (mRefreshInterval) {\n case REALTIME_REFRESH_INTERVAL:\n return IntervalFrequency.REALTIME;\n case HIGH_REFRESH_INTERVAL:\n return IntervalFrequency.HIGH;\n case LOW_REFRESH_INTERVAL:\n return IntervalFrequency.LOW;\n case MEDIUM_REFRESH_INTERVAL:\n return IntervalFrequency.MEDIUM;\n default:\n return IntervalFrequency.NONE;\n }\n }", "private String parseAddress(String address) {\r\n try {\r\n StringBuilder buf = new StringBuilder();\r\n InternetAddress[] netAddrs = InternetAddress.parseHeader(address, false);\r\n for (InternetAddress netAddr : netAddrs) {\r\n if (buf.length() > 0) {\r\n buf.append(SP);\r\n }\r\n\r\n buf.append(LB);\r\n\r\n String personal = netAddr.getPersonal();\r\n if (personal != null && (personal.length() != 0)) {\r\n buf.append(Q).append(personal).append(Q);\r\n } else {\r\n buf.append(NIL);\r\n }\r\n buf.append(SP);\r\n buf.append(NIL); // should add route-addr\r\n buf.append(SP);\r\n try {\r\n // Remove quotes to avoid double quoting\r\n MailAddress mailAddr = new MailAddress(netAddr.getAddress().replaceAll(\"\\\"\", \"\\\\\\\\\\\"\"));\r\n buf.append(Q).append(mailAddr.getUser()).append(Q);\r\n buf.append(SP);\r\n buf.append(Q).append(mailAddr.getHost()).append(Q);\r\n } catch (Exception pe) {\r\n buf.append(NIL + SP + NIL);\r\n }\r\n buf.append(RB);\r\n }\r\n\r\n return buf.toString();\r\n } catch (AddressException e) {\r\n throw new RuntimeException(\"Failed to parse address: \" + address, e);\r\n }\r\n }", "public static JmsDestinationType getTypeFromClass(String aClass)\n {\n if (StringUtils.equals(aClass, \"javax.jms.Queue\") || StringUtils.equals(aClass, \"javax.jms.QueueConnectionFactory\"))\n {\n return JmsDestinationType.QUEUE;\n }\n else if (StringUtils.equals(aClass, \"javax.jms.Topic\") || StringUtils.equals(aClass, \"javax.jms.TopicConnectionFactory\"))\n {\n return JmsDestinationType.TOPIC;\n }\n else\n {\n return null;\n }\n }" ]
Deletes all outgoing links of specified entity. @param entity the entity.
[ "private void deleteLinks(@NotNull final PersistentStoreTransaction txn, @NotNull final PersistentEntity entity) {\n final PersistentEntityId id = entity.getId();\n final int entityTypeId = id.getTypeId();\n final long entityLocalId = id.getLocalId();\n final Transaction envTxn = txn.getEnvironmentTransaction();\n final LinksTable links = getLinksTable(txn, entityTypeId);\n final IntHashSet deletedLinks = new IntHashSet();\n try (Cursor cursor = links.getFirstIndexCursor(envTxn)) {\n for (boolean success = cursor.getSearchKeyRange(PropertyKey.propertyKeyToEntry(new PropertyKey(entityLocalId, 0))) != null;\n success; success = cursor.getNext()) {\n final ByteIterable keyEntry = cursor.getKey();\n final PropertyKey key = PropertyKey.entryToPropertyKey(keyEntry);\n if (key.getEntityLocalId() != entityLocalId) {\n break;\n }\n final ByteIterable valueEntry = cursor.getValue();\n if (links.delete(envTxn, keyEntry, valueEntry)) {\n int linkId = key.getPropertyId();\n if (getLinkName(txn, linkId) != null) {\n deletedLinks.add(linkId);\n final LinkValue linkValue = LinkValue.entryToLinkValue(valueEntry);\n txn.linkDeleted(entity.getId(), (PersistentEntityId) linkValue.getEntityId(), linkValue.getLinkId());\n }\n }\n }\n }\n for (Integer linkId : deletedLinks) {\n links.deleteAllIndex(envTxn, linkId, entityLocalId);\n }\n }" ]
[ "public static TextEncryptor queryableText(CharSequence password, CharSequence salt) {\n\t\treturn new HexEncodingTextEncryptor(new AndroidAesBytesEncryptor(password.toString(), salt, AndroidKeyGenerators.shared(16)));\n\t}", "private void populateDefaultSettings(Record record, ProjectProperties properties) throws MPXJException\n {\n properties.setDefaultDurationUnits(record.getTimeUnit(0));\n properties.setDefaultDurationIsFixed(record.getNumericBoolean(1));\n properties.setDefaultWorkUnits(record.getTimeUnit(2));\n properties.setMinutesPerDay(Double.valueOf(NumberHelper.getDouble(record.getFloat(3)) * 60));\n properties.setMinutesPerWeek(Double.valueOf(NumberHelper.getDouble(record.getFloat(4)) * 60));\n properties.setDefaultStandardRate(record.getRate(5));\n properties.setDefaultOvertimeRate(record.getRate(6));\n properties.setUpdatingTaskStatusUpdatesResourceStatus(record.getNumericBoolean(7));\n properties.setSplitInProgressTasks(record.getNumericBoolean(8));\n }", "public static <T, ID> int dropTable(ConnectionSource connectionSource, Class<T> dataClass, boolean ignoreErrors)\n\t\t\tthrows SQLException {\n\t\tDao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);\n\t\treturn dropTable(dao, ignoreErrors);\n\t}", "@Deprecated\n public static <T> T buildJsonResponse(Response response, Class<T> clazz) throws IOException, SlackApiException {\n if (response.code() == 200) {\n String body = response.body().string();\n DETAILED_LOGGER.accept(new HttpResponseListener.State(SlackConfig.DEFAULT, response, body));\n return GsonFactory.createSnakeCase().fromJson(body, clazz);\n } else {\n String body = response.body().string();\n throw new SlackApiException(response, body);\n }\n }", "private CmsFavInfo createFavInfo(CmsFavoriteEntry entry) throws CmsException {\n\n String title = \"\";\n String subtitle = \"\";\n CmsFavInfo result = new CmsFavInfo(entry);\n CmsObject cms = A_CmsUI.getCmsObject();\n String project = getProject(cms, entry);\n String site = getSite(cms, entry);\n try {\n CmsUUID idToLoad = entry.getDetailId() != null ? entry.getDetailId() : entry.getStructureId();\n CmsResource resource = cms.readResource(idToLoad, CmsResourceFilter.IGNORE_EXPIRATION.addRequireVisible());\n CmsResourceUtil resutil = new CmsResourceUtil(cms, resource);\n switch (entry.getType()) {\n case explorerFolder:\n title = CmsStringUtil.isEmpty(resutil.getTitle())\n ? CmsResource.getName(resource.getRootPath())\n : resutil.getTitle();\n break;\n case page:\n title = resutil.getTitle();\n break;\n }\n subtitle = resource.getRootPath();\n CmsResourceIcon icon = result.getResourceIcon();\n icon.initContent(resutil, CmsResource.STATE_UNCHANGED, false, false);\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n result.getTopLine().setValue(title);\n result.getBottomLine().setValue(subtitle);\n result.getProjectLabel().setValue(project);\n result.getSiteLabel().setValue(site);\n\n return result;\n\n }", "private Iterable<BoxRetentionPolicyAssignment.Info> getAssignments(String type, int limit, String ... fields) {\r\n QueryStringBuilder queryString = new QueryStringBuilder();\r\n if (type != null) {\r\n queryString.appendParam(\"type\", type);\r\n }\r\n if (fields.length > 0) {\r\n queryString.appendParam(\"fields\", fields);\r\n }\r\n URL url = ASSIGNMENTS_URL_TEMPLATE.buildWithQuery(getAPI().getBaseURL(), queryString.toString(), getID());\r\n return new BoxResourceIterable<BoxRetentionPolicyAssignment.Info>(getAPI(), url, limit) {\r\n\r\n @Override\r\n protected BoxRetentionPolicyAssignment.Info factory(JsonObject jsonObject) {\r\n BoxRetentionPolicyAssignment assignment\r\n = new BoxRetentionPolicyAssignment(getAPI(), jsonObject.get(\"id\").asString());\r\n return assignment.new Info(jsonObject);\r\n }\r\n\r\n };\r\n }", "protected Date parseNonNullDate(String str, ParsePosition pos)\n {\n Date result = null;\n for (int index = 0; index < m_formats.length; index++)\n {\n result = m_formats[index].parse(str, pos);\n if (pos.getIndex() != 0)\n {\n break;\n }\n result = null;\n }\n return result;\n }", "protected void handleParentheses( TokenList tokens, Sequence sequence ) {\n // have a list to handle embedded parentheses, e.g. (((((a)))))\n List<TokenList.Token> left = new ArrayList<TokenList.Token>();\n\n // find all of them\n TokenList.Token t = tokens.first;\n while( t != null ) {\n TokenList.Token next = t.next;\n if( t.getType() == Type.SYMBOL ) {\n if( t.getSymbol() == Symbol.PAREN_LEFT )\n left.add(t);\n else if( t.getSymbol() == Symbol.PAREN_RIGHT ) {\n if( left.isEmpty() )\n throw new ParseError(\") found with no matching (\");\n\n TokenList.Token a = left.remove(left.size()-1);\n\n // remember the element before so the new one can be inserted afterwards\n TokenList.Token before = a.previous;\n\n TokenList sublist = tokens.extractSubList(a,t);\n // remove parentheses\n sublist.remove(sublist.first);\n sublist.remove(sublist.last);\n\n // if its a function before () then the () indicates its an input to a function\n if( before != null && before.getType() == Type.FUNCTION ) {\n List<TokenList.Token> inputs = parseParameterCommaBlock(sublist, sequence);\n if (inputs.isEmpty())\n throw new ParseError(\"Empty function input parameters\");\n else {\n createFunction(before, inputs, tokens, sequence);\n }\n } else if( before != null && before.getType() == Type.VARIABLE &&\n before.getVariable().getType() == VariableType.MATRIX ) {\n // if it's a variable then that says it's a sub-matrix\n TokenList.Token extract = parseSubmatrixToExtract(before,sublist, sequence);\n // put in the extract operation\n tokens.insert(before,extract);\n tokens.remove(before);\n } else {\n // if null then it was empty inside\n TokenList.Token output = parseBlockNoParentheses(sublist,sequence, false);\n if (output != null)\n tokens.insert(before, output);\n }\n }\n }\n t = next;\n }\n\n if( !left.isEmpty())\n throw new ParseError(\"Dangling ( parentheses\");\n }", "public static boolean isFileExist(String filePath) {\n\n File f = new File(filePath);\n\n return f.exists() && !f.isDirectory();\n }" ]
Open the event stream @return true if successfully opened, false if not
[ "boolean openStream() throws InterruptedException, IOException {\n logger.info(\"stream START\");\n final boolean isOpen;\n final Set<BsonValue> idsToWatch = nsConfig.getSynchronizedDocumentIds();\n\n if (!networkMonitor.isConnected()) {\n logger.info(\"stream END - Network disconnected\");\n return false;\n }\n\n if (idsToWatch.isEmpty()) {\n logger.info(\"stream END - No synchronized documents\");\n return false;\n }\n\n nsLock.writeLock().lockInterruptibly();\n try {\n if (!authMonitor.isLoggedIn()) {\n logger.info(\"stream END - Logged out\");\n return false;\n }\n\n final Document args = new Document();\n args.put(\"database\", namespace.getDatabaseName());\n args.put(\"collection\", namespace.getCollectionName());\n args.put(\"ids\", idsToWatch);\n\n currentStream =\n service.streamFunction(\n \"watch\",\n Collections.singletonList(args),\n ResultDecoders.changeEventDecoder(BSON_DOCUMENT_CODEC));\n\n if (currentStream != null && currentStream.isOpen()) {\n this.nsConfig.setStale(true);\n isOpen = true;\n } else {\n isOpen = false;\n }\n } finally {\n nsLock.writeLock().unlock();\n }\n return isOpen;\n }" ]
[ "public void loadWithTimeout(int timeout) {\n\n for (String stylesheet : m_stylesheets) {\n boolean alreadyLoaded = checkStylesheet(stylesheet);\n if (alreadyLoaded) {\n m_loadCounter += 1;\n } else {\n appendStylesheet(stylesheet, m_jsCallback);\n }\n }\n checkAllLoaded();\n if (timeout > 0) {\n Timer timer = new Timer() {\n\n @SuppressWarnings(\"synthetic-access\")\n @Override\n public void run() {\n\n callCallback();\n }\n };\n\n timer.schedule(timeout);\n }\n }", "public static base_response update(nitro_service client, inat resource) throws Exception {\n\t\tinat updateresource = new inat();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.privateip = resource.privateip;\n\t\tupdateresource.tcpproxy = resource.tcpproxy;\n\t\tupdateresource.ftp = resource.ftp;\n\t\tupdateresource.tftp = resource.tftp;\n\t\tupdateresource.usip = resource.usip;\n\t\tupdateresource.usnip = resource.usnip;\n\t\tupdateresource.proxyip = resource.proxyip;\n\t\tupdateresource.mode = resource.mode;\n\t\treturn updateresource.update_resource(client);\n\t}", "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 }", "public void addBetween(Object attribute, Object value1, Object value2)\r\n {\r\n\t\t// PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildBeweenCriteria(attribute, value1, value2, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildBeweenCriteria(attribute, value1, value2, getUserAlias(attribute)));\r\n }", "int acquireTransaction(@NotNull final Thread thread) {\n try (CriticalSection ignored = criticalSection.enter()) {\n final int currentThreadPermits = getThreadPermitsToAcquire(thread);\n waitForPermits(thread, currentThreadPermits > 0 ? nestedQueue : regularQueue, 1, currentThreadPermits);\n }\n return 1;\n }", "private void readTaskCustomFields(net.sf.mpxj.ganttproject.schema.Task gpTask, Task mpxjTask)\n {\n //\n // Populate custom field default values\n //\n Map<FieldType, Object> customFields = new HashMap<FieldType, Object>();\n for (Pair<FieldType, String> definition : m_taskPropertyDefinitions.values())\n {\n customFields.put(definition.getFirst(), definition.getSecond());\n }\n\n //\n // Update with custom field actual values\n //\n for (CustomTaskProperty property : gpTask.getCustomproperty())\n {\n Pair<FieldType, String> definition = m_taskPropertyDefinitions.get(property.getTaskpropertyId());\n if (definition != null)\n {\n //\n // Retrieve the value. If it is empty, use the default.\n //\n String value = property.getValueAttribute();\n if (value.isEmpty())\n {\n value = null;\n }\n\n //\n // If we have a value,convert it to the correct type\n //\n if (value != null)\n {\n Object result;\n\n switch (definition.getFirst().getDataType())\n {\n case NUMERIC:\n {\n if (value.indexOf('.') == -1)\n {\n result = Integer.valueOf(value);\n }\n else\n {\n result = Double.valueOf(value);\n }\n break;\n }\n\n case DATE:\n {\n try\n {\n result = m_dateFormat.parse(value);\n }\n catch (ParseException ex)\n {\n result = null;\n }\n break;\n }\n\n case BOOLEAN:\n {\n result = Boolean.valueOf(value.equals(\"true\"));\n break;\n }\n\n default:\n {\n result = value;\n break;\n }\n }\n\n if (result != null)\n {\n customFields.put(definition.getFirst(), result);\n }\n }\n }\n }\n\n for (Map.Entry<FieldType, Object> item : customFields.entrySet())\n {\n if (item.getValue() != null)\n {\n mpxjTask.set(item.getKey(), item.getValue());\n }\n }\n }", "ArgumentsBuilder param(String param, Integer value) {\n if (value != null) {\n args.add(param);\n args.add(value.toString());\n }\n return this;\n }", "public ArrayList<Double> segmentBaselineCost(ProjectFile file, List<TimephasedCost> cost, TimescaleUnits rangeUnits, ArrayList<DateRange> dateList)\n {\n return segmentCost(file.getBaselineCalendar(), cost, rangeUnits, dateList);\n }", "private void maybeUpdateScrollbarPositions() {\r\n\r\n if (!isAttached()) {\r\n return;\r\n }\r\n\r\n if (m_scrollbar != null) {\r\n int vPos = getVerticalScrollPosition();\r\n if (m_scrollbar.getVerticalScrollPosition() != vPos) {\r\n m_scrollbar.setVerticalScrollPosition(vPos);\r\n }\r\n }\r\n }" ]
Writes task baseline data. @param xmlTask MSPDI task @param mpxjTask MPXJ task
[ "private void writeTaskBaselines(Project.Tasks.Task xmlTask, Task mpxjTask)\n {\n Project.Tasks.Task.Baseline baseline = m_factory.createProjectTasksTaskBaseline();\n boolean populated = false;\n\n Number cost = mpxjTask.getBaselineCost();\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printCurrency(cost));\n }\n\n Duration duration = mpxjTask.getBaselineDuration();\n if (duration != null && duration.getDuration() != 0)\n {\n populated = true;\n baseline.setDuration(DatatypeConverter.printDuration(this, duration));\n baseline.setDurationFormat(DatatypeConverter.printDurationTimeUnits(duration, false));\n }\n\n Date date = mpxjTask.getBaselineFinish();\n if (date != null)\n {\n populated = true;\n baseline.setFinish(date);\n }\n\n date = mpxjTask.getBaselineStart();\n if (date != null)\n {\n populated = true;\n baseline.setStart(date);\n }\n\n duration = mpxjTask.getBaselineWork();\n if (duration != null && duration.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, duration));\n }\n\n if (populated)\n {\n baseline.setNumber(BigInteger.ZERO);\n xmlTask.getBaseline().add(baseline);\n }\n\n for (int loop = 1; loop <= 10; loop++)\n {\n baseline = m_factory.createProjectTasksTaskBaseline();\n populated = false;\n\n cost = mpxjTask.getBaselineCost(loop);\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printCurrency(cost));\n }\n\n duration = mpxjTask.getBaselineDuration(loop);\n if (duration != null && duration.getDuration() != 0)\n {\n populated = true;\n baseline.setDuration(DatatypeConverter.printDuration(this, duration));\n baseline.setDurationFormat(DatatypeConverter.printDurationTimeUnits(duration, false));\n }\n\n date = mpxjTask.getBaselineFinish(loop);\n if (date != null)\n {\n populated = true;\n baseline.setFinish(date);\n }\n\n date = mpxjTask.getBaselineStart(loop);\n if (date != null)\n {\n populated = true;\n baseline.setStart(date);\n }\n\n duration = mpxjTask.getBaselineWork(loop);\n if (duration != null && duration.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, duration));\n }\n\n if (populated)\n {\n baseline.setNumber(BigInteger.valueOf(loop));\n xmlTask.getBaseline().add(baseline);\n }\n }\n }" ]
[ "public static File guessKeyRingFile() throws FileNotFoundException {\n final Collection<String> possibleLocations = getKnownPGPSecureRingLocations();\n for (final String location : possibleLocations) {\n final File candidate = new File(location);\n if (candidate.exists()) {\n return candidate;\n }\n }\n final StringBuilder message = new StringBuilder(\"Could not locate secure keyring, locations tried: \");\n final Iterator<String> it = possibleLocations.iterator();\n while (it.hasNext()) {\n message.append(it.next());\n if (it.hasNext()) {\n message.append(\", \");\n }\n }\n throw new FileNotFoundException(message.toString());\n }", "public void addCommandClass(ZWaveCommandClass commandClass) {\r\n\t\tZWaveCommandClass.CommandClass key = commandClass.getCommandClass();\r\n\t\tif (!supportedCommandClasses.containsKey(key)) {\r\n\t\t\tsupportedCommandClasses.put(key, commandClass);\r\n\t\t}\r\n\t}", "private void addJoin(TableAlias left, Object[] leftKeys, TableAlias right, Object[] rightKeys, boolean outer,\r\n String name)\r\n {\r\n TableAlias extAlias, rightCopy;\r\n\r\n left.addJoin(new Join(left, leftKeys, right, rightKeys, outer, name));\r\n\r\n // build join between left and extents of right\r\n if (right.hasExtents())\r\n {\r\n for (int i = 0; i < right.extents.size(); i++)\r\n {\r\n extAlias = (TableAlias) right.extents.get(i);\r\n FieldDescriptor[] extKeys = getExtentFieldDescriptors(extAlias, (FieldDescriptor[]) rightKeys);\r\n\r\n left.addJoin(new Join(left, leftKeys, extAlias, extKeys, true, name));\r\n }\r\n }\r\n\r\n // we need to copy the alias on the right for each extent on the left\r\n if (left.hasExtents())\r\n {\r\n for (int i = 0; i < left.extents.size(); i++)\r\n {\r\n extAlias = (TableAlias) left.extents.get(i);\r\n FieldDescriptor[] extKeys = getExtentFieldDescriptors(extAlias, (FieldDescriptor[]) leftKeys);\r\n rightCopy = right.copy(\"C\" + i);\r\n\r\n // copies are treated like normal extents\r\n right.extents.add(rightCopy);\r\n right.extents.addAll(rightCopy.extents);\r\n\r\n addJoin(extAlias, extKeys, rightCopy, rightKeys, true, name);\r\n }\r\n }\r\n }", "@Override\n public QueryBuilderFind excludingType(final Class<? extends WindupVertexFrame> type)\n {\n pipelineCriteria.add(new QueryGremlinCriterion()\n {\n @Override\n public void query(GraphRewrite event, GraphTraversal<?, Vertex> pipeline)\n {\n pipeline.filter(it -> !GraphTypeManager.hasType(type, it.get()));\n }\n });\n return this;\n }", "public GVRSceneObject startDrag(GVRSceneObject dragMe, float relX, float relY, float relZ) {\n synchronized (mLock) {\n if (mCursorController == null) {\n Log.w(TAG, \"Physics drag failed: Cursor controller not found!\");\n return null;\n }\n\n if (mDragMe != null) {\n Log.w(TAG, \"Physics drag failed: Previous drag wasn't finished!\");\n return null;\n }\n\n if (mPivotObject == null) {\n mPivotObject = onCreatePivotObject(mContext);\n }\n\n mDragMe = dragMe;\n\n GVRTransform t = dragMe.getTransform();\n\n /* It is not possible to drag a rigid body directly, we need a pivot object.\n We are using the pivot object's position as pivot of the dragging's physics constraint.\n */\n mPivotObject.getTransform().setPosition(t.getPositionX() + relX,\n t.getPositionY() + relY, t.getPositionZ() + relZ);\n\n mCursorController.startDrag(mPivotObject);\n }\n\n return mPivotObject;\n }", "@SuppressWarnings(\"unchecked\")\n public <V3, M4, C, N, Q> V3 getUp(AiWrapperProvider<V3, M4, C, N, Q> \n wrapperProvider) {\n \n return (V3) m_up;\n }", "public RandomVariable[]\tgetParameter() {\n\t\tdouble[] parameterAsDouble = this.getParameterAsDouble();\n\t\tRandomVariable[] parameter = new RandomVariable[parameterAsDouble.length];\n\t\tfor(int i=0; i<parameter.length; i++) {\n\t\t\tparameter[i] = new Scalar(parameterAsDouble[i]);\n\t\t}\n\t\treturn parameter;\n\t}", "public Iterable<BoxRetentionPolicyAssignment.Info> getEnterpriseAssignments(int limit, String ... fields) {\r\n return this.getAssignments(BoxRetentionPolicyAssignment.TYPE_ENTERPRISE, limit, fields);\r\n }", "@Override\n public void registerTransformers(SubsystemTransformerRegistration subsystemRegistration) {\n ResourceTransformationDescriptionBuilder builder = ResourceTransformationDescriptionBuilder.Factory.createSubsystemInstance();\n builder.addChildResource(DeploymentPermissionsResourceDefinition.DEPLOYMENT_PERMISSIONS_PATH).\n getAttributeBuilder().addRejectCheck(new RejectAttributeChecker.DefaultRejectAttributeChecker() {\n\n @Override\n protected boolean rejectAttribute(PathAddress address, String attributeName, ModelNode value, TransformationContext context) {\n // reject the maximum set if it is defined and empty as that would result in complete incompatible policies\n // being used in nodes running earlier versions of the subsystem.\n if (value.isDefined() && value.asList().isEmpty()) { return true; }\n return false;\n }\n\n @Override\n public String getRejectionLogMessage(Map<String, ModelNode> attributes) {\n return SecurityManagerLogger.ROOT_LOGGER.rejectedEmptyMaximumSet();\n }\n }, DeploymentPermissionsResourceDefinition.MAXIMUM_PERMISSIONS);\n TransformationDescription.Tools.register(builder.build(), subsystemRegistration, EAP_7_0_0_MODEL_VERSION);\n }" ]
Creates a curator built using the given zookeeper connection string and timeout
[ "public static CuratorFramework newCurator(String zookeepers, int timeout, String secret) {\n\n final ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 10);\n if (secret.isEmpty()) {\n return CuratorFrameworkFactory.newClient(zookeepers, timeout, timeout, retry);\n } else {\n return CuratorFrameworkFactory.builder().connectString(zookeepers)\n .connectionTimeoutMs(timeout).sessionTimeoutMs(timeout).retryPolicy(retry)\n .authorization(\"digest\", (\"fluo:\" + secret).getBytes(StandardCharsets.UTF_8))\n .aclProvider(new ACLProvider() {\n @Override\n public List<ACL> getDefaultAcl() {\n return CREATOR_ALL_ACL;\n }\n\n @Override\n public List<ACL> getAclForPath(String path) {\n switch (path) {\n case ZookeeperPath.ORACLE_GC_TIMESTAMP:\n // The garbage collection iterator running in Accumulo tservers needs to read this\n // value w/o authenticating.\n return PUBLICLY_READABLE_ACL;\n default:\n return CREATOR_ALL_ACL;\n }\n }\n }).build();\n }\n }" ]
[ "private Date readOptionalDate(JSONValue val) {\n\n JSONString str = null == val ? null : val.isString();\n if (str != null) {\n try {\n return new Date(Long.parseLong(str.stringValue()));\n } catch (@SuppressWarnings(\"unused\") NumberFormatException e) {\n // do nothing - return the default value\n }\n }\n return null;\n }", "@Deprecated\n public static PersistentResourceXMLBuilder decorator(final String elementName) {\n return new PersistentResourceXMLBuilder(PathElement.pathElement(elementName), null).setDecoratorGroup(elementName);\n }", "public String read(int numBytes) throws IOException {\n Preconditions.checkArgument(numBytes >= 0);\n Preconditions.checkArgument(numBytes <= MAX_ALLOWABLE_BUFFER_SIZE);\n int numBytesRemaining = numBytes;\n // first read whatever we need from our buffer\n if (!isReadBufferEmpty()) {\n int length = Math.min(end - offset, numBytesRemaining);\n copyToStrBuffer(buffer, offset, length);\n offset += length;\n numBytesRemaining -= length;\n }\n\n // next read the remaining chars directly into our strBuffer\n if (numBytesRemaining > 0) {\n readAmountToStrBuffer(numBytesRemaining);\n }\n\n if (strBufferIndex > 0 && strBuffer[strBufferIndex - 1] != LF) {\n // the last byte doesn't correspond to lf\n return readLine(false);\n }\n\n int strBufferLength = strBufferIndex;\n strBufferIndex = 0;\n return new String(strBuffer, 0, strBufferLength, charset);\n }", "private String parseEnvelope() {\r\n List<String> response = new ArrayList<>();\r\n //1. Date ---------------\r\n response.add(LB + Q + sentDateEnvelopeString + Q + SP);\r\n //2. Subject ---------------\r\n if (subject != null && (subject.length() != 0)) {\r\n response.add(Q + escapeHeader(subject) + Q + SP);\r\n } else {\r\n response.add(NIL + SP);\r\n }\r\n //3. From ---------------\r\n addAddressToEnvelopeIfAvailable(from, response);\r\n response.add(SP);\r\n //4. Sender ---------------\r\n addAddressToEnvelopeIfAvailableWithNetscapeFeature(sender, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailableWithNetscapeFeature(replyTo, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailable(to, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailable(cc, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailable(bcc, response);\r\n response.add(SP);\r\n if (inReplyTo != null && inReplyTo.length > 0) {\r\n response.add(inReplyTo[0]);\r\n } else {\r\n response.add(NIL);\r\n }\r\n response.add(SP);\r\n if (messageID != null && messageID.length > 0) {\r\n messageID[0] = escapeHeader(messageID[0]);\r\n response.add(Q + messageID[0] + Q);\r\n } else {\r\n response.add(NIL);\r\n }\r\n response.add(RB);\r\n\r\n StringBuilder buf = new StringBuilder(16 * response.size());\r\n for (String aResponse : response) {\r\n buf.append(aResponse);\r\n }\r\n\r\n return buf.toString();\r\n }", "public Module getModule(final String name, final String version) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getModulePath(name, version));\n final ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"get module details\", name, version);\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(Module.class);\n }", "HtmlTag attr(String name, String value) {\n if (attrs == null) {\n attrs = new HashMap<>();\n }\n attrs.put(name, value);\n return this;\n }", "@Api\n\tpublic void restoreSecurityContext(SavedAuthorization savedAuthorization) {\n\t\tList<Authentication> auths = new ArrayList<Authentication>();\n\t\tif (null != savedAuthorization) {\n\t\t\tfor (SavedAuthentication sa : savedAuthorization.getAuthentications()) {\n\t\t\t\tAuthentication auth = new Authentication();\n\t\t\t\tauth.setSecurityServiceId(sa.getSecurityServiceId());\n\t\t\t\tauth.setAuthorizations(sa.getAuthorizations());\n\t\t\t\tauths.add(auth);\n\t\t\t}\n\t\t}\n\t\tsetAuthentications(null, auths);\n\t\tuserInfoInit();\n\t}", "public Story storyOfText(Configuration configuration, String storyAsText, String storyId) {\n return configuration.storyParser().parseStory(storyAsText, storyId);\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 }" ]
Creates the row key of the given association row; columns present in the given association key will be obtained from there, all other columns from the given native association row.
[ "private static <R> RowKey buildRowKey(AssociationKey associationKey, R row, AssociationRowAccessor<R> accessor) {\n\t\tString[] columnNames = associationKey.getMetadata().getRowKeyColumnNames();\n\t\tObject[] columnValues = new Object[columnNames.length];\n\n\t\tfor ( int i = 0; i < columnNames.length; i++ ) {\n\t\t\tString columnName = columnNames[i];\n\t\t\tcolumnValues[i] = associationKey.getMetadata().isKeyColumn( columnName ) ? associationKey.getColumnValue( columnName ) : accessor.get( row, columnName );\n\t\t}\n\n\t\treturn new RowKey( columnNames, columnValues );\n\t}" ]
[ "public void deleteProduct(final String name) {\n final DbProduct dbProduct = getProduct(name);\n repositoryHandler.deleteProduct(dbProduct.getName());\n }", "static InstalledIdentity load(final InstalledImage image, final ProductConfig productConfig, final List<File> moduleRoots, final List<File> bundleRoots) throws IOException {\n\n // build the identity information\n final String productVersion = productConfig.resolveVersion();\n final String productName = productConfig.resolveName();\n final Identity identity = new AbstractLazyIdentity() {\n @Override\n public String getName() {\n return productName;\n }\n\n @Override\n public String getVersion() {\n return productVersion;\n }\n\n @Override\n public InstalledImage getInstalledImage() {\n return image;\n }\n };\n\n final Properties properties = PatchUtils.loadProperties(identity.getDirectoryStructure().getInstallationInfo());\n final List<String> allPatches = PatchUtils.readRefs(properties, Constants.ALL_PATCHES);\n\n // Step 1 - gather the installed layers data\n final InstalledConfiguration conf = createInstalledConfig(image);\n // Step 2 - process the actual module and bundle roots\n final ProcessedLayers processedLayers = process(conf, moduleRoots, bundleRoots);\n final InstalledConfiguration config = processedLayers.getConf();\n\n // Step 3 - create the actual config objects\n // Process layers\n final InstalledIdentityImpl installedIdentity = new InstalledIdentityImpl(identity, allPatches, image);\n for (final LayerPathConfig layer : processedLayers.getLayers().values()) {\n final String name = layer.name;\n installedIdentity.putLayer(name, createPatchableTarget(name, layer, config.getLayerMetadataDir(name), image));\n }\n // Process add-ons\n for (final LayerPathConfig addOn : processedLayers.getAddOns().values()) {\n final String name = addOn.name;\n installedIdentity.putAddOn(name, createPatchableTarget(name, addOn, config.getAddOnMetadataDir(name), image));\n }\n return installedIdentity;\n }", "private void recordBackupSet(File backupDir) throws IOException {\n String[] filesInEnv = env.getHome().list();\n SimpleDateFormat format = new SimpleDateFormat(\"yyyy_MM_dd_kk_mm_ss\");\n String recordFileName = \"backupset-\" + format.format(new Date());\n File recordFile = new File(backupDir, recordFileName);\n if(recordFile.exists()) {\n recordFile.renameTo(new File(backupDir, recordFileName + \".old\"));\n }\n\n PrintStream backupRecord = new PrintStream(new FileOutputStream(recordFile));\n backupRecord.println(\"Lastfile:\" + Long.toHexString(backupHelper.getLastFileInBackupSet()));\n if(filesInEnv != null) {\n for(String file: filesInEnv) {\n if(file.endsWith(BDB_EXT))\n backupRecord.println(file);\n }\n }\n backupRecord.close();\n }", "@SuppressWarnings(\"unchecked\")\n public static <T> Serializer<T> unsafeGetSerializer(SerializerFactory serializerFactory,\n SerializerDefinition serializerDefinition) {\n return (Serializer<T>) serializerFactory.getSerializer(serializerDefinition);\n }", "public static boolean isMapLiteralWithOnlyConstantValues(Expression expression) {\r\n if (expression instanceof MapExpression) {\r\n List<MapEntryExpression> entries = ((MapExpression) expression).getMapEntryExpressions();\r\n for (MapEntryExpression entry : entries) {\r\n if (!isConstantOrConstantLiteral(entry.getKeyExpression()) ||\r\n !isConstantOrConstantLiteral(entry.getValueExpression())) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n }", "@Override\n public void finish() {\n if (started.get() && !finished.getAndSet(true)) {\n waitUntilFinished();\n super.finish();\n // recreate thread (don't start) for processor reuse\n createProcessorThread();\n clearQueues();\n started.set(false);\n }\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 void forAllTables(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _torqueModel.getTables(); it.hasNext(); )\r\n {\r\n _curTableDef = (TableDef)it.next();\r\n generate(template);\r\n }\r\n _curTableDef = null;\r\n }", "protected Element createPageElement()\n {\n String pstyle = \"\";\n PDRectangle layout = getCurrentMediaBox();\n if (layout != null)\n {\n /*System.out.println(\"x1 \" + layout.getLowerLeftX());\n System.out.println(\"y1 \" + layout.getLowerLeftY());\n System.out.println(\"x2 \" + layout.getUpperRightX());\n System.out.println(\"y2 \" + layout.getUpperRightY());\n System.out.println(\"rot \" + pdpage.findRotation());*/\n \n float w = layout.getWidth();\n float h = layout.getHeight();\n final int rot = pdpage.getRotation();\n if (rot == 90 || rot == 270)\n {\n float x = w; w = h; h = x;\n }\n \n pstyle = \"width:\" + w + UNIT + \";\" + \"height:\" + h + UNIT + \";\";\n pstyle += \"overflow:hidden;\";\n }\n else\n log.warn(\"No media box found\");\n \n Element el = doc.createElement(\"div\");\n el.setAttribute(\"id\", \"page_\" + (pagecnt++));\n el.setAttribute(\"class\", \"page\");\n el.setAttribute(\"style\", pstyle);\n return el;\n }" ]
Gets information about the device pin. @param fields the fields to retrieve. @return info about the device pin.
[ "public Info getInfo(String ... fields) {\r\n QueryStringBuilder builder = new QueryStringBuilder();\r\n if (fields.length > 0) {\r\n builder.appendParam(\"fields\", fields);\r\n }\r\n URL url = DEVICE_PIN_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\r\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\r\n BoxJSONResponse response = (BoxJSONResponse) request.send();\r\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\r\n return new Info(responseJSON);\r\n }" ]
[ "public static String getSolrRangeString(String from, String to) {\n\n // If a parameter is not initialized, use the asterisk '*' operator\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(from)) {\n from = \"*\";\n }\n\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(to)) {\n to = \"*\";\n }\n\n return String.format(\"[%s TO %s]\", from, to);\n }", "private int[] readColorTable(int ncolors) {\n int nbytes = 3 * ncolors;\n int[] tab = null;\n byte[] c = new byte[nbytes];\n\n try {\n rawData.get(c);\n\n // Max size to avoid bounds checks.\n tab = new int[MAX_BLOCK_SIZE];\n int i = 0;\n int j = 0;\n while (i < ncolors) {\n int r = ((int) c[j++]) & 0xff;\n int g = ((int) c[j++]) & 0xff;\n int b = ((int) c[j++]) & 0xff;\n tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;\n }\n } catch (BufferUnderflowException e) {\n //if (Log.isLoggable(TAG, Log.DEBUG)) {\n Logger.d(TAG, \"Format Error Reading Color Table\", e);\n //}\n header.status = GifDecoder.STATUS_FORMAT_ERROR;\n }\n\n return tab;\n }", "public void unlink(Object obj, ObjectReferenceDescriptor ord, boolean insert)\r\n {\r\n linkOrUnlink(false, obj, ord, insert);\r\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 String updateClassification(String classificationType) {\n Metadata metadata = new Metadata(\"enterprise\", Metadata.CLASSIFICATION_TEMPLATE_KEY);\n metadata.add(\"/Box__Security__Classification__Key\", classificationType);\n Metadata classification = this.updateMetadata(metadata);\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }", "public void refreshCredentials() {\n if (this.credsProvider == null)\n return;\n\n try {\n AlibabaCloudCredentials creds = this.credsProvider.getCredentials();\n this.accessKeyID = creds.getAccessKeyId();\n this.accessKeySecret = creds.getAccessKeySecret();\n\n if (creds instanceof BasicSessionCredentials) {\n this.securityToken = ((BasicSessionCredentials) creds).getSessionToken();\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }", "@Override\n public void map(GenericData.Record record,\n AvroCollector<Pair<ByteBuffer, ByteBuffer>> collector,\n Reporter reporter) throws IOException {\n\n byte[] keyBytes = null;\n byte[] valBytes = null;\n Object keyRecord = null;\n Object valRecord = null;\n try {\n keyRecord = record.get(keyField);\n valRecord = record.get(valField);\n keyBytes = keySerializer.toBytes(keyRecord);\n valBytes = valueSerializer.toBytes(valRecord);\n\n this.collectorWrapper.setCollector(collector);\n this.mapper.map(keyBytes, valBytes, this.collectorWrapper);\n\n recordCounter++;\n } catch (OutOfMemoryError oom) {\n logger.error(oomErrorMessage(reporter));\n if (keyBytes == null) {\n logger.error(\"keyRecord caused OOM!\");\n } else {\n logger.error(\"keyRecord: \" + keyRecord);\n logger.error(\"valRecord: \" + (valBytes == null ? \"caused OOM\" : valRecord));\n }\n throw new VoldemortException(oomErrorMessage(reporter), oom);\n }\n }", "public void setAppender(final Appender appender) {\n if (this.appender != null) {\n close();\n }\n checkAccess(this);\n if (applyLayout && appender != null) {\n final Formatter formatter = getFormatter();\n appender.setLayout(formatter == null ? null : new FormatterLayout(formatter));\n }\n appenderUpdater.set(this, appender);\n }", "public static boolean bidiagOuterBlocks( final int blockLength ,\n final DSubmatrixD1 A ,\n final double gammasU[],\n final double gammasV[])\n {\n// System.out.println(\"---------- Orig\");\n// A.original.print();\n\n int width = Math.min(blockLength,A.col1-A.col0);\n int height = Math.min(blockLength,A.row1-A.row0);\n\n int min = Math.min(width,height);\n\n for( int i = 0; i < min; i++ ) {\n //--- Apply reflector to the column\n\n // compute the householder vector\n if (!computeHouseHolderCol(blockLength, A, gammasU, i))\n return false;\n\n // apply to rest of the columns in the column block\n rank1UpdateMultR_Col(blockLength,A,i,gammasU[A.col0+i]);\n\n // apply to the top row block\n rank1UpdateMultR_TopRow(blockLength,A,i,gammasU[A.col0+i]);\n\n System.out.println(\"After column stuff\");\n A.original.print();\n\n //-- Apply reflector to the row\n if(!computeHouseHolderRow(blockLength,A,gammasV,i))\n return false;\n \n // apply to rest of the rows in the row block\n rank1UpdateMultL_Row(blockLength,A,i,i+1,gammasV[A.row0+i]);\n\n System.out.println(\"After update row\");\n A.original.print();\n\n // apply to the left column block\n // TODO THIS WON'T WORK!!!!!!!!!!!!!\n // Needs the whole matrix to have been updated by the left reflector to compute the correct solution\n// rank1UpdateMultL_LeftCol(blockLength,A,i,i+1,gammasV[A.row0+i]);\n\n System.out.println(\"After row stuff\");\n A.original.print();\n }\n\n return true;\n }" ]
Print a a basic type t
[ "private String type(Options opt, Type t, boolean generics) {\n\treturn ((generics ? opt.showQualifiedGenerics : opt.showQualified) ? //\n\t\tt.qualifiedTypeName() : t.typeName()) //\n\t\t+ (opt.hideGenerics ? \"\" : typeParameters(opt, t.asParameterizedType()));\n }" ]
[ "protected T createInstance() {\n try {\n Constructor<T> ctor = clazz.getDeclaredConstructor();\n ctor.setAccessible(true);\n return ctor.newInstance();\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (SecurityException e) {\n throw new RuntimeException(e);\n } catch (NoSuchMethodException e) {\n throw new RuntimeException(e);\n } catch (IllegalArgumentException e) {\n throw new RuntimeException(e);\n } catch (InvocationTargetException e) {\n throw new RuntimeException(e);\n }\n }", "public SerialMessage getMessage(AlarmType alarmType) {\r\n\t\tlogger.debug(\"Creating new message for application command SENSOR_ALARM_GET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationCommandHandler, SerialMessage.SerialMessagePriority.Get);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t3, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) SENSOR_ALARM_GET,\r\n\t\t\t\t\t\t\t\t(byte) alarmType.getKey() };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}", "public static Command newInsert(Object object,\n String outIdentifier,\n boolean returnObject,\n String entryPoint ) {\n return getCommandFactoryProvider().newInsert( object,\n outIdentifier,\n returnObject,\n entryPoint );\n }", "public float getTexCoordU(int vertex, int coords) {\n if (!hasTexCoords(coords)) {\n throw new IllegalStateException(\n \"mesh has no texture coordinate set \" + coords);\n }\n \n checkVertexIndexBounds(vertex);\n /* bound checks for coords are done by java for us */\n \n return m_texcoords[coords].getFloat(\n vertex * m_numUVComponents[coords] * SIZEOF_FLOAT);\n }", "void setFilters(Map<Object, Object> filters) {\n\n for (Object column : filters.keySet()) {\n Object filterValue = filters.get(column);\n if ((filterValue != null) && !filterValue.toString().isEmpty() && !m_table.isColumnCollapsed(column)) {\n m_table.setFilterFieldValue(column, filterValue);\n }\n }\n }", "public Duration getFinishSlack()\n {\n Duration finishSlack = (Duration) getCachedValue(TaskField.FINISH_SLACK);\n if (finishSlack == null)\n {\n Duration duration = getDuration();\n if (duration != null)\n {\n finishSlack = DateHelper.getVariance(this, getEarlyFinish(), getLateFinish(), duration.getUnits());\n set(TaskField.FINISH_SLACK, finishSlack);\n }\n }\n return (finishSlack);\n }", "@SuppressWarnings(\"unchecked\")\n public <V3, M4, C, N, Q> V3 getUp(AiWrapperProvider<V3, M4, C, N, Q> \n wrapperProvider) {\n \n return (V3) m_up;\n }", "public static dnsaaaarec[] get(nitro_service service, dnsaaaarec_args args) throws Exception{\n\t\tdnsaaaarec obj = new dnsaaaarec();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tdnsaaaarec[] response = (dnsaaaarec[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public void startTask(int id, String taskName) {\n if (isActivated) {\n durations.add(new Duration(id, taskName, BenchmarkUtil.elapsedRealTimeNanos()));\n }\n }" ]
Send a metadata cache update announcement to all registered listeners. @param slot the media slot whose cache status has changed @param cache the cache which has been attached, or, if {@code null}, the previous cache has been detached
[ "private void deliverCacheUpdate(SlotReference slot, MetadataCache cache) {\n for (final MetadataCacheListener listener : getCacheListeners()) {\n try {\n if (cache == null) {\n listener.cacheDetached(slot);\n } else {\n listener.cacheAttached(slot, cache);\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering metadata cache update to listener\", t);\n }\n }\n }" ]
[ "private Set<T> findMatching(R resolvable) {\n Set<T> result = new HashSet<T>();\n for (T bean : getAllBeans(resolvable)) {\n if (matches(resolvable, bean)) {\n result.add(bean);\n }\n }\n return result;\n }", "protected String getBundleJarPath() throws MalformedURLException {\n Path path = PROPERTIES.getAllureHome().resolve(\"app/allure-bundle.jar\").toAbsolutePath();\n if (Files.notExists(path)) {\n throw new AllureCommandException(String.format(\"Bundle not found by path <%s>\", path));\n }\n return path.toUri().toURL().toString();\n }", "public static base_response change(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey updateresource = new sslcertkey();\n\t\tupdateresource.certkey = resource.certkey;\n\t\tupdateresource.cert = resource.cert;\n\t\tupdateresource.key = resource.key;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.fipskey = resource.fipskey;\n\t\tupdateresource.inform = resource.inform;\n\t\tupdateresource.passplain = resource.passplain;\n\t\tupdateresource.nodomaincheck = resource.nodomaincheck;\n\t\treturn updateresource.perform_operation(client,\"update\");\n\t}", "public static base_response delete(nitro_service client, ntpserver resource) throws Exception {\n\t\tntpserver deleteresource = new ntpserver();\n\t\tdeleteresource.serverip = resource.serverip;\n\t\tdeleteresource.servername = resource.servername;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "static String makeLayout(String descriptor, String blockName, boolean useUBO)\n {\n return NativeShaderManager.makeLayout(descriptor, blockName, useUBO);\n }", "public static Authentication build(String crypt) throws IllegalArgumentException {\n if(crypt == null) {\n return new PlainAuth(null);\n }\n String[] value = crypt.split(\":\");\n \n if(value.length == 2 ) {\n String type = value[0].trim();\n String password = value[1].trim();\n if(password!=null&&password.length()>0) {\n if(\"plain\".equals(type)) {\n return new PlainAuth(password);\n }\n if(\"md5\".equals(type)) {\n return new Md5Auth(password);\n }\n if(\"crc32\".equals(type)) {\n return new Crc32Auth(Long.parseLong(password));\n }\n }\n }\n throw new IllegalArgumentException(\"error password: \"+crypt);\n }", "public static vpnvserver_appcontroller_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_appcontroller_binding obj = new vpnvserver_appcontroller_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_appcontroller_binding response[] = (vpnvserver_appcontroller_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static List<Integer> checkKeyBelongsToPartition(byte[] key,\n Set<Pair<Integer, HashMap<Integer, List<Integer>>>> stealerNodeToMappingTuples,\n Cluster cluster,\n StoreDefinition storeDef) {\n List<Integer> keyPartitions = new RoutingStrategyFactory().updateRoutingStrategy(storeDef,\n cluster)\n .getPartitionList(key);\n List<Integer> nodesToPush = Lists.newArrayList();\n for(Pair<Integer, HashMap<Integer, List<Integer>>> stealNodeToMap: stealerNodeToMappingTuples) {\n List<Integer> nodePartitions = cluster.getNodeById(stealNodeToMap.getFirst())\n .getPartitionIds();\n if(StoreRoutingPlan.checkKeyBelongsToPartition(keyPartitions,\n nodePartitions,\n stealNodeToMap.getSecond())) {\n nodesToPush.add(stealNodeToMap.getFirst());\n }\n }\n return nodesToPush;\n }", "@Override\n public void fire(StepStartedEvent event) {\n for (LifecycleListener listener : listeners) {\n try {\n listener.fire(event);\n } catch (Exception e) {\n logError(listener, e);\n }\n }\n }" ]
Finds the beat in which the specified track position falls. @param milliseconds how long the track has been playing @return the beat number represented by that time, or -1 if the time is before the first beat
[ "@SuppressWarnings(\"WeakerAccess\")\n public int findBeatAtTime(long milliseconds) {\n int found = Arrays.binarySearch(timeWithinTrackValues, milliseconds);\n if (found >= 0) { // An exact match, just change 0-based array index to 1-based beat number\n return found + 1;\n } else if (found == -1) { // We are before the first beat\n return found;\n } else { // We are after some beat, report its beat number\n return -(found + 1);\n }\n }" ]
[ "public static void writeBytes(byte[] bytes, long value, int offset, int numBytes) {\n int shift = 0;\n for(int i = offset + numBytes - 1; i >= offset; i--) {\n bytes[i] = (byte) (0xFF & (value >> shift));\n shift += 8;\n }\n }", "public void setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tif(htmlElementTranslator!=null){\r\n\t\t\tthis.htmlElementTranslator = htmlElementTranslator;\r\n\t\t\tthis.charTranslator = null;\r\n\t\t\tthis.targetTranslator = null;\r\n\t\t}\r\n\t}", "@Override\n\tprotected void doProcessQueuedOps(PersistentCollection collection, Serializable key, int nextIndex, SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\t\t// nothing to do\n\t}", "public GroovyFieldDoc[] properties() {\n Collections.sort(properties);\n return properties.toArray(new GroovyFieldDoc[properties.size()]);\n }", "@Override\n public final PObject getObject(final String key) {\n PObject result = optObject(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }", "protected void setBandsFinalHeight() {\n log.debug(\"Setting bands final height...\");\n\n List<JRBand> bands = new ArrayList<JRBand>();\n\n Utils.addNotNull(bands, design.getPageHeader());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getColumnHeader());\n Utils.addNotNull(bands, design.getColumnFooter());\n Utils.addNotNull(bands, design.getSummary());\n Utils.addNotNull(bands, design.getBackground());\n bands.addAll(((JRDesignSection) design.getDetailSection()).getBandsList());\n Utils.addNotNull(bands, design.getLastPageFooter());\n Utils.addNotNull(bands, design.getTitle());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getNoData());\n\n for (JRGroup jrgroup : design.getGroupsList()) {\n DJGroup djGroup = (DJGroup) getReferencesMap().get(jrgroup.getName());\n JRDesignSection headerSection = (JRDesignSection) jrgroup.getGroupHeaderSection();\n JRDesignSection footerSection = (JRDesignSection) jrgroup.getGroupFooterSection();\n if (djGroup != null) {\n for (JRBand headerBand : headerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) headerBand, djGroup.getHeaderHeight(), djGroup.isFitHeaderHeightToContent());\n\n }\n for (JRBand footerBand : footerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) footerBand, djGroup.getFooterHeight(), djGroup.isFitFooterHeightToContent());\n\n }\n } else {\n bands.addAll(headerSection.getBandsList());\n bands.addAll(footerSection.getBandsList());\n }\n }\n\n for (JRBand jrDesignBand : bands) {\n setBandFinalHeight((JRDesignBand) jrDesignBand);\n }\n }", "public static void pushClassType(CodeAttribute b, String classType) {\n if (classType.length() != 1) {\n if (classType.startsWith(\"L\") && classType.endsWith(\";\")) {\n classType = classType.substring(1, classType.length() - 1);\n }\n b.loadClass(classType);\n } else {\n char type = classType.charAt(0);\n switch (type) {\n case 'I':\n b.getstatic(Integer.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'J':\n b.getstatic(Long.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'S':\n b.getstatic(Short.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'F':\n b.getstatic(Float.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'D':\n b.getstatic(Double.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'B':\n b.getstatic(Byte.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'C':\n b.getstatic(Character.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'Z':\n b.getstatic(Boolean.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n default:\n throw new RuntimeException(\"Cannot handle primitive type: \" + type);\n }\n }\n }", "private List<TimephasedCost> getTimephasedCostMultipleRates(List<TimephasedWork> standardWorkList, List<TimephasedWork> overtimeWorkList)\n {\n List<TimephasedWork> standardWorkResult = new LinkedList<TimephasedWork>();\n List<TimephasedWork> overtimeWorkResult = new LinkedList<TimephasedWork>();\n CostRateTable table = getCostRateTable();\n ProjectCalendar calendar = getCalendar();\n\n Iterator<TimephasedWork> iter = overtimeWorkList.iterator();\n for (TimephasedWork standardWork : standardWorkList)\n {\n TimephasedWork overtimeWork = iter.hasNext() ? iter.next() : null;\n\n int startIndex = getCostRateTableEntryIndex(standardWork.getStart());\n int finishIndex = getCostRateTableEntryIndex(standardWork.getFinish());\n\n if (startIndex == finishIndex)\n {\n standardWorkResult.add(standardWork);\n if (overtimeWork != null)\n {\n overtimeWorkResult.add(overtimeWork);\n }\n }\n else\n {\n standardWorkResult.addAll(splitWork(table, calendar, standardWork, startIndex));\n if (overtimeWork != null)\n {\n overtimeWorkResult.addAll(splitWork(table, calendar, overtimeWork, startIndex));\n }\n }\n }\n\n return getTimephasedCostSingleRate(standardWorkResult, overtimeWorkResult);\n }", "@Override\n public void detachScriptFile(IScriptable target) {\n IScriptFile scriptFile = mScriptMap.remove(target);\n if (scriptFile != null) {\n scriptFile.invokeFunction(\"onDetach\", new Object[] { target });\n }\n }" ]
Adds the supplied marker to the map. @param marker
[ "public void addMarker(Marker marker) {\n if (markers == null) {\n markers = new HashSet<>();\n }\n markers.add(marker);\n marker.setMap(this);\n }" ]
[ "public Integer getGroupIdFromName(String groupName) {\n return (Integer) sqlService.getFromTable(Constants.GENERIC_ID, Constants.GROUPS_GROUP_NAME, groupName,\n Constants.DB_TABLE_GROUPS);\n }", "public static String getSerializedVectorClocks(List<VectorClock> vectorClocks) {\n List<VectorClockWrapper> vectorClockWrappers = new ArrayList<VectorClockWrapper>();\n for(VectorClock vc: vectorClocks) {\n vectorClockWrappers.add(new VectorClockWrapper(vc));\n }\n String serializedVC = \"\";\n try {\n serializedVC = mapper.writeValueAsString(vectorClockWrappers);\n } catch(Exception e) {\n e.printStackTrace();\n }\n return serializedVC;\n }", "public String getDbProperty(String key) {\n\n // extract the database key out of the entire key\n String databaseKey = key.substring(0, key.indexOf('.'));\n Properties databaseProperties = getDatabaseProperties().get(databaseKey);\n\n return databaseProperties.getProperty(key, \"\");\n }", "public static RgbaColor fromRgba(String rgba) {\n if (rgba.length() == 0) return getDefaultColor();\n\n String[] parts = getRgbaParts(rgba).split(\",\");\n if (parts.length == 4) {\n return new RgbaColor(parseInt(parts[0]),\n parseInt(parts[1]),\n parseInt(parts[2]),\n parseFloat(parts[3]));\n }\n else {\n return getDefaultColor();\n }\n }", "private Map<String, Object> getMapFromJSON(String json) {\n Map<String, Object> propMap = new HashMap<String, Object>();\n ObjectMapper mapper = new ObjectMapper();\n\n // Initialize string if empty\n if (json == null || json.length() == 0) {\n json = \"{}\";\n }\n\n try {\n // Convert string\n propMap = mapper.readValue(json, new TypeReference<HashMap<String, Object>>(){});\n } catch (Exception e) {\n ;\n }\n return propMap;\n }", "public static Node removePartitionsFromNode(final Node node,\n final Set<Integer> donatedPartitions) {\n List<Integer> deepCopy = new ArrayList<Integer>(node.getPartitionIds());\n deepCopy.removeAll(donatedPartitions);\n return updateNode(node, deepCopy);\n }", "public static double elementMax( 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 max.\n // Otherwise zero needs to be considered\n double max = 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 > max ) {\n max = val;\n }\n }\n\n return max;\n }", "public void setFrustum(Matrix4f projMatrix)\n {\n if (projMatrix != null)\n {\n if (mProjMatrix == null)\n {\n mProjMatrix = new float[16];\n }\n mProjMatrix = projMatrix.get(mProjMatrix, 0);\n mScene.setPickVisible(false);\n if (mCuller != null)\n {\n mCuller.set(projMatrix);\n }\n else\n {\n mCuller = new FrustumIntersection(projMatrix);\n }\n }\n mProjection = projMatrix;\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 }" ]
Reads the table data from an input stream and breaks it down into rows. @param is input stream
[ "public void read(InputStream is) throws IOException\n {\n byte[] headerBlock = new byte[20];\n is.read(headerBlock);\n\n int headerLength = PEPUtility.getShort(headerBlock, 8);\n int recordCount = PEPUtility.getInt(headerBlock, 10);\n int recordLength = PEPUtility.getInt(headerBlock, 16);\n StreamHelper.skip(is, headerLength - headerBlock.length);\n\n byte[] record = new byte[recordLength];\n for (int recordIndex = 1; recordIndex <= recordCount; recordIndex++)\n {\n is.read(record);\n readRow(recordIndex, record);\n }\n }" ]
[ "protected void processProjectListItem(Map<Integer, String> result, Row row)\n {\n Integer id = row.getInteger(\"PROJ_ID\");\n String name = row.getString(\"PROJ_NAME\");\n result.put(id, name);\n }", "public void postArtifact(final Artifact artifact, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.artifactResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, artifact);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST artifact\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }", "private void connect() throws IOException, GeneralSecurityException {\n synchronized (closedSync) {\n if (socket == null || socket.isClosed()) {\n SSLContext sc = SSLContext.getInstance(\"SSL\");\n sc.init(null, new TrustManager[] { new X509TrustAllManager() }, new SecureRandom());\n socket = sc.getSocketFactory().createSocket();\n socket.connect(address);\n }\n /**\n * Authenticate\n */\n CastChannel.DeviceAuthMessage authMessage = CastChannel.DeviceAuthMessage.newBuilder()\n .setChallenge(CastChannel.AuthChallenge.newBuilder().build())\n .build();\n\n CastChannel.CastMessage msg = CastChannel.CastMessage.newBuilder()\n .setDestinationId(DEFAULT_RECEIVER_ID)\n .setNamespace(\"urn:x-cast:com.google.cast.tp.deviceauth\")\n .setPayloadType(CastChannel.CastMessage.PayloadType.BINARY)\n .setProtocolVersion(CastChannel.CastMessage.ProtocolVersion.CASTV2_1_0)\n .setSourceId(name)\n .setPayloadBinary(authMessage.toByteString())\n .build();\n\n write(msg);\n CastChannel.CastMessage response = read();\n CastChannel.DeviceAuthMessage authResponse = CastChannel.DeviceAuthMessage.parseFrom(response.getPayloadBinary());\n if (authResponse.hasError()) {\n throw new ChromeCastException(\"Authentication failed: \" + authResponse.getError().getErrorType().toString());\n }\n\n /**\n * Send 'PING' message\n */\n PingThread pingThread = new PingThread();\n pingThread.run();\n\n /**\n * Send 'CONNECT' message to start session\n */\n write(\"urn:x-cast:com.google.cast.tp.connection\", StandardMessage.connect(), DEFAULT_RECEIVER_ID);\n\n /**\n * Start ping/pong and reader thread\n */\n pingTimer = new Timer(name + \" PING\");\n pingTimer.schedule(pingThread, 1000, PING_PERIOD);\n\n reader = new ReadThread();\n reader.start();\n\n if (closed) {\n closed = false;\n notifyListenerOfConnectionEvent(true);\n }\n }\n }", "public static List getAt(Matcher self, Collection indices) {\n List result = new ArrayList();\n for (Object value : indices) {\n if (value instanceof Range) {\n result.addAll(getAt(self, (Range) value));\n } else {\n int idx = DefaultTypeTransformation.intUnbox(value);\n result.add(getAt(self, idx));\n }\n }\n return result;\n }", "private long getTotalTime(ProjectCalendarDateRanges exception)\n {\n long total = 0;\n for (DateRange range : exception)\n {\n total += getTime(range.getStart(), range.getEnd());\n }\n return (total);\n }", "private void readTasks(Document cdp)\n {\n //\n // Sort the projects into the correct order\n //\n List<Project> projects = new ArrayList<Project>(cdp.getProjects().getProject());\n final AlphanumComparator comparator = new AlphanumComparator();\n\n Collections.sort(projects, new Comparator<Project>()\n {\n @Override public int compare(Project o1, Project o2)\n {\n return comparator.compare(o1.getOutlineNumber(), o2.getOutlineNumber());\n }\n });\n\n for (Project project : cdp.getProjects().getProject())\n {\n readProject(project);\n }\n }", "private void batchStatusLog(int batchCount,\n int numBatches,\n int partitionStoreCount,\n int numPartitionStores,\n long totalTimeMs) {\n // Calculate the estimated end time and pretty print stats\n double rate = 1;\n long estimatedTimeMs = 0;\n if(numPartitionStores > 0) {\n rate = partitionStoreCount / numPartitionStores;\n estimatedTimeMs = (long) (totalTimeMs / rate) - totalTimeMs;\n }\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"Batch Complete!\")\n .append(Utils.NEWLINE)\n .append(\"\\tbatches moved: \")\n .append(batchCount)\n .append(\" out of \")\n .append(numBatches)\n .append(Utils.NEWLINE)\n .append(\"\\tPartition stores moved: \")\n .append(partitionStoreCount)\n .append(\" out of \")\n .append(numPartitionStores)\n .append(Utils.NEWLINE)\n .append(\"\\tPercent done: \")\n .append(decimalFormatter.format(rate * 100.0))\n .append(Utils.NEWLINE)\n .append(\"\\tEstimated time left: \")\n .append(estimatedTimeMs)\n .append(\" ms (\")\n .append(TimeUnit.MILLISECONDS.toHours(estimatedTimeMs))\n .append(\" hours)\");\n RebalanceUtils.printBatchLog(batchCount, logger, sb.toString());\n }", "public void sendValue(int nodeId, int endpoint, int value) {\n\t\tZWaveNode node = this.getNode(nodeId);\n\t\tZWaveSetCommands zwaveCommandClass = null;\n\t\tSerialMessage serialMessage = null;\n\t\t\n\t\tfor (ZWaveCommandClass.CommandClass commandClass : new ZWaveCommandClass.CommandClass[] { ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL, ZWaveCommandClass.CommandClass.SWITCH_BINARY, ZWaveCommandClass.CommandClass.BASIC }) {\n\t\t\tzwaveCommandClass = (ZWaveSetCommands)node.resolveCommandClass(commandClass, endpoint);\n\t\t\tif (zwaveCommandClass != null)\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\tif (zwaveCommandClass == null) {\n\t\t\tlogger.error(\"No Command Class found on node {}, instance/endpoint {} to request level.\", nodeId, endpoint);\n\t\t\treturn;\n\t\t}\n\t\t\t \n\t\tserialMessage = node.encapsulate(zwaveCommandClass.setValueMessage(value), (ZWaveCommandClass)zwaveCommandClass, endpoint);\n\t\t\n\t\tif (serialMessage != null)\n\t\t\tthis.sendData(serialMessage);\n\t\t\n\t\t// read back level on \"ON\" command\n\t\tif (((ZWaveCommandClass)zwaveCommandClass).getCommandClass() == ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL && value == 255)\n\t\t\tthis.requestValue(nodeId, endpoint);\n\t}", "public static Polygon calculateBounds(final MapfishMapContext context) {\n double rotation = context.getRootContext().getRotation();\n ReferencedEnvelope env = context.getRootContext().toReferencedEnvelope();\n\n Coordinate centre = env.centre();\n AffineTransform rotateInstance = AffineTransform.getRotateInstance(rotation, centre.x, centre.y);\n\n double[] dstPts = new double[8];\n double[] srcPts = {\n env.getMinX(), env.getMinY(), env.getMinX(), env.getMaxY(),\n env.getMaxX(), env.getMaxY(), env.getMaxX(), env.getMinY()\n };\n\n rotateInstance.transform(srcPts, 0, dstPts, 0, 4);\n\n return new GeometryFactory().createPolygon(new Coordinate[]{\n new Coordinate(dstPts[0], dstPts[1]), new Coordinate(dstPts[2], dstPts[3]),\n new Coordinate(dstPts[4], dstPts[5]), new Coordinate(dstPts[6], dstPts[7]),\n new Coordinate(dstPts[0], dstPts[1])\n });\n }" ]
Gets the estimated time remaining in milliseconds based upon the total number of work units, the start time, and how many units have been done so far. This should not be called before any work units have been done.
[ "public long getTimeRemainingInMillis()\n {\n long batchTime = System.currentTimeMillis() - startTime;\n double timePerIteration = (double) batchTime / (double) worked.get();\n return (long) (timePerIteration * (total - worked.get()));\n }" ]
[ "public final void visit(final Visitor visitor)\n\t{\n\t\tfinal Visit visit = new Visit();\n\t\ttry\n\t\t{\n\t\t\tvisit(visitor, visit);\n\t\t}\n\t\tcatch (final StopVisitationException ignored)\n\t\t{\n\t\t}\n\t}", "private List<I_CmsSearchFieldMapping> getMappings() {\n\n CmsSearchManager manager = OpenCms.getSearchManager();\n I_CmsSearchFieldConfiguration fieldConfig = manager.getFieldConfiguration(getParamFieldconfiguration());\n CmsLuceneField field;\n List<I_CmsSearchFieldMapping> result = null;\n Iterator<CmsSearchField> itFields;\n if (fieldConfig != null) {\n itFields = fieldConfig.getFields().iterator();\n while (itFields.hasNext()) {\n field = (CmsLuceneField)itFields.next();\n if (field.getName().equals(getParamField())) {\n result = field.getMappings();\n }\n }\n } else {\n result = Collections.emptyList();\n if (LOG.isErrorEnabled()) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_SEARCHINDEX_EDIT_MISSING_PARAM_1,\n A_CmsFieldConfigurationDialog.PARAM_FIELDCONFIGURATION));\n }\n }\n return result;\n }", "public double Function1D(double x) {\n double frequency = initFrequency;\n double amplitude = initAmplitude;\n double sum = 0;\n\n // octaves\n for (int i = 0; i < octaves; i++) {\n sum += SmoothedNoise(x * frequency) * amplitude;\n\n frequency *= 2;\n amplitude *= persistence;\n }\n return sum;\n }", "public void setObjectForStatement(PreparedStatement ps, int index,\r\n Object value, int sqlType) throws SQLException\r\n {\r\n if (sqlType == Types.TINYINT)\r\n {\r\n ps.setByte(index, ((Byte) value).byteValue());\r\n }\r\n else\r\n {\r\n super.setObjectForStatement(ps, index, value, sqlType);\r\n }\r\n }", "public void incrementVersion(int node, long time) {\n if(node < 0 || node > Short.MAX_VALUE)\n throw new IllegalArgumentException(node\n + \" is outside the acceptable range of node ids.\");\n\n this.timestamp = time;\n\n Long version = versionMap.get((short) node);\n if(version == null) {\n version = 1L;\n } else {\n version = version + 1L;\n }\n\n versionMap.put((short) node, version);\n if(versionMap.size() >= MAX_NUMBER_OF_VERSIONS) {\n throw new IllegalStateException(\"Vector clock is full!\");\n }\n\n }", "public BoxFile.Info uploadFile(FileUploadParams uploadParams) {\n URL uploadURL = UPLOAD_FILE_URL.build(this.getAPI().getBaseUploadURL());\n BoxMultipartRequest request = new BoxMultipartRequest(getAPI(), uploadURL);\n\n JsonObject fieldJSON = new JsonObject();\n JsonObject parentIdJSON = new JsonObject();\n parentIdJSON.add(\"id\", getID());\n fieldJSON.add(\"name\", uploadParams.getName());\n fieldJSON.add(\"parent\", parentIdJSON);\n\n if (uploadParams.getCreated() != null) {\n fieldJSON.add(\"content_created_at\", BoxDateFormat.format(uploadParams.getCreated()));\n }\n\n if (uploadParams.getModified() != null) {\n fieldJSON.add(\"content_modified_at\", BoxDateFormat.format(uploadParams.getModified()));\n }\n\n if (uploadParams.getSHA1() != null && !uploadParams.getSHA1().isEmpty()) {\n request.setContentSHA1(uploadParams.getSHA1());\n }\n\n if (uploadParams.getDescription() != null) {\n fieldJSON.add(\"description\", uploadParams.getDescription());\n }\n\n request.putField(\"attributes\", fieldJSON.toString());\n\n if (uploadParams.getSize() > 0) {\n request.setFile(uploadParams.getContent(), uploadParams.getName(), uploadParams.getSize());\n } else if (uploadParams.getContent() != null) {\n request.setFile(uploadParams.getContent(), uploadParams.getName());\n } else {\n request.setUploadFileCallback(uploadParams.getUploadFileCallback(), uploadParams.getName());\n }\n\n BoxJSONResponse response;\n if (uploadParams.getProgressListener() == null) {\n response = (BoxJSONResponse) request.send();\n } else {\n response = (BoxJSONResponse) request.send(uploadParams.getProgressListener());\n }\n JsonObject collection = JsonObject.readFrom(response.getJSON());\n JsonArray entries = collection.get(\"entries\").asArray();\n JsonObject fileInfoJSON = entries.get(0).asObject();\n String uploadedFileID = fileInfoJSON.get(\"id\").asString();\n\n BoxFile uploadedFile = new BoxFile(getAPI(), uploadedFileID);\n return uploadedFile.new Info(fileInfoJSON);\n }", "public static void initializeInternalProject(CommandExecutor executor) {\n final long creationTimeMillis = System.currentTimeMillis();\n try {\n executor.execute(createProject(creationTimeMillis, Author.SYSTEM, INTERNAL_PROJ))\n .get();\n } catch (Throwable cause) {\n cause = Exceptions.peel(cause);\n if (!(cause instanceof ProjectExistsException)) {\n throw new Error(\"failed to initialize an internal project\", cause);\n }\n }\n // These repositories might be created when creating an internal project, but we try to create them\n // again here in order to make sure them exist because sometimes their names are changed.\n for (final String repo : ImmutableList.of(Project.REPO_META, Project.REPO_DOGMA)) {\n try {\n executor.execute(createRepository(creationTimeMillis, Author.SYSTEM, INTERNAL_PROJ, repo))\n .get();\n } catch (Throwable cause) {\n cause = Exceptions.peel(cause);\n if (!(cause instanceof RepositoryExistsException)) {\n throw new Error(cause);\n }\n }\n }\n }", "public void invalidate() {\n synchronized (mMeasuredChildren) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"invalidate all [%d]\", mMeasuredChildren.size());\n mMeasuredChildren.clear();\n }\n }", "public void ifHasName(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = getDefForLevel(attributes.getProperty(ATTRIBUTE_LEVEL)).getName();\r\n\r\n if ((name != null) && (name.length() > 0))\r\n {\r\n generate(template);\r\n }\r\n }" ]