query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
This snapshot is meant to be used when updating data. | [
"@Override\n\tpublic Object[] getDatabaseSnapshot(Serializable id, SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\n\t\tif ( log.isTraceEnabled() ) {\n\t\t\tlog.trace( \"Getting current persistent state for: \" + MessageHelper.infoString( this, id, getFactory() ) );\n\t\t}\n\n\t\t//snapshot is a Map in the end\n\t\tfinal Tuple resultset = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );\n\n\t\t//if there is no resulting row, return null\n\t\tif ( resultset == null || resultset.getSnapshot().isEmpty() ) {\n\t\t\treturn null;\n\t\t}\n\t\t//otherwise return the \"hydrated\" state (ie. associations are not resolved)\n\t\tGridType[] types = gridPropertyTypes;\n\t\tObject[] values = new Object[types.length];\n\t\tboolean[] includeProperty = getPropertyUpdateability();\n\t\tfor ( int i = 0; i < types.length; i++ ) {\n\t\t\tif ( includeProperty[i] ) {\n\t\t\t\tvalues[i] = types[i].hydrate( resultset, getPropertyAliases( \"\", i ), session, null ); //null owner ok??\n\t\t\t}\n\t\t}\n\t\treturn values;\n\t}"
] | [
"public void setPatternScheme(final boolean isByWeekDay, final boolean fireChange) {\n\n if (isByWeekDay ^ (null != m_model.getWeekDay())) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n if (isByWeekDay) {\n m_model.setWeekOfMonth(getPatternDefaultValues().getWeekOfMonth());\n m_model.setWeekDay(getPatternDefaultValues().getWeekDay());\n } else {\n m_model.clearWeekDays();\n m_model.clearWeeksOfMonth();\n m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth());\n }\n m_model.setInterval(getPatternDefaultValues().getInterval());\n if (fireChange) {\n onValueChange();\n }\n }\n });\n }\n\n }",
"public DiscreteInterval plus(DiscreteInterval other) {\n return new DiscreteInterval(this.min + other.min, this.max + other.max);\n }",
"@SuppressWarnings(\"unchecked\") public Map<String, Object> getCustomProperties()\n {\n return (Map<String, Object>) getCachedValue(ProjectField.CUSTOM_PROPERTIES);\n }",
"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 static I_CmsMacroResolver newWorkplaceLocaleResolver(final CmsObject cms) {\n\n // Resolve macros in the property configuration\n CmsMacroResolver resolver = new CmsMacroResolver();\n resolver.setCmsObject(cms);\n CmsUserSettings userSettings = new CmsUserSettings(cms.getRequestContext().getCurrentUser());\n CmsMultiMessages multimessages = new CmsMultiMessages(userSettings.getLocale());\n multimessages.addMessages(OpenCms.getWorkplaceManager().getMessages(userSettings.getLocale()));\n resolver.setMessages(multimessages);\n resolver.setKeepEmptyMacros(true);\n\n return resolver;\n }",
"public static final String printDuration(Duration value)\n {\n return value == null ? null : Double.toString(value.getDuration());\n }",
"@Override\n synchronized public V put(K key, V value) {\n V oldValue = this.get(key);\n try {\n super.put(key, value);\n writeBack(key, value);\n return oldValue;\n } catch(Exception e) {\n super.put(key, oldValue);\n writeBack(key, oldValue);\n throw new VoldemortException(\"Failed to put(\" + key + \", \" + value\n + \") in write through cache\", e);\n }\n }",
"protected void handleResponseOut(T message) throws Fault {\n Message reqMsg = message.getExchange().getInMessage();\n if (reqMsg == null) {\n LOG.warning(\"InMessage is null!\");\n return;\n }\n\n // No flowId for oneway message\n Exchange ex = reqMsg.getExchange();\n if (ex.isOneWay()) {\n return;\n }\n\n String reqFid = FlowIdHelper.getFlowId(reqMsg);\n\n // if some interceptor throws fault before FlowIdProducerIn fired\n if (reqFid == null) {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Some interceptor throws fault.Setting FlowId in response.\");\n }\n reqFid = FlowIdProtocolHeaderCodec.readFlowId(message);\n }\n\n // write IN message to SAM repo in case fault\n if (reqFid == null) {\n Message inMsg = ex.getInMessage();\n\n reqFid = FlowIdProtocolHeaderCodec.readFlowId(inMsg);\n if (null != reqFid) {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"FlowId '\" + reqFid\n + \"' found in message of fault incoming exchange.\");\n LOG.fine(\"Calling EventProducerInterceptor to log IN message\");\n }\n handleINEvent(ex, reqFid);\n }\n }\n\n if (reqFid == null) {\n reqFid = FlowIdSoapCodec.readFlowId(message);\n }\n\n if (reqFid != null) {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"FlowId '\" + reqFid + \"' found in incoming message.\");\n }\n } else {\n reqFid = ContextUtils.generateUUID();\n // write IN message to SAM repo in case fault\n if (null != ex.getOutFaultMessage()) {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"FlowId '\" + reqFid\n + \"' generated for fault message.\");\n LOG.fine(\"Calling EventProducerInterceptor to log IN message\");\n }\n handleINEvent(ex, reqFid);\n }\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"No flowId found in incoming message! Generate new flowId \"\n + reqFid);\n }\n }\n\n FlowIdHelper.setFlowId(message, reqFid);\n\n }",
"public ItemRequest<Task> addTag(String task) {\n \n String path = String.format(\"/tasks/%s/addTag\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }"
] |
Parses command-line and verifies metadata versions on all the cluster
nodes
@param args Command-line input
@param printHelp Tells whether to print help only or execute command
actually
@throws IOException | [
"public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n String url = null;\n\n // parse command-line input\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n\n // load parameters\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n\n // execute command\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n doMetaCheckVersion(adminClient);\n }"
] | [
"public ServerGroup updateServerGroupName(int serverGroupId, String name) {\n ServerGroup serverGroup = null;\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"name\", name),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n try {\n JSONObject response = new JSONObject(doPost(BASE_SERVERGROUP + \"/\" + serverGroupId, params));\n serverGroup = getServerGroupFromJSON(response);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return serverGroup;\n }",
"private void tryToSetParsedValue(String value) throws Exception {\n\n JSONObject json = JSONParser.parseStrict(value).isObject();\n JSONValue val = json.get(JsonKey.START);\n setStart(readOptionalDate(val));\n val = json.get(JsonKey.END);\n setEnd(readOptionalDate(val));\n setWholeDay(readOptionalBoolean(json.get(JsonKey.WHOLE_DAY)));\n JSONObject patternJson = json.get(JsonKey.PATTERN).isObject();\n readPattern(patternJson);\n setExceptions(readDates(json.get(JsonKey.EXCEPTIONS)));\n setSeriesEndDate(readOptionalDate(json.get(JsonKey.SERIES_ENDDATE)));\n setOccurrences(readOptionalInt(json.get(JsonKey.SERIES_OCCURRENCES)));\n setDerivedEndType();\n setCurrentTillEnd(readOptionalBoolean(json.get(JsonKey.CURRENT_TILL_END)));\n setParentSeriesId(readOptionalUUID(json.get(JsonKey.PARENT_SERIES)));\n\n }",
"public ResourceIterator<Node> findEntities(GraphDatabaseService executionEngine) {\n\t\tResult result = executionEngine.execute( getFindEntitiesQuery() );\n\t\treturn result.columnAs( BaseNeo4jEntityQueries.ENTITY_ALIAS );\n\t}",
"public void initLocator() throws InterruptedException,\n ServiceLocatorException {\n if (locatorClient == null) {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Instantiate locatorClient client for Locator Server \"\n + locatorEndpoints + \"...\");\n }\n ServiceLocatorImpl client = new ServiceLocatorImpl();\n client.setLocatorEndpoints(locatorEndpoints);\n client.setConnectionTimeout(connectionTimeout);\n client.setSessionTimeout(sessionTimeout);\n if (null != authenticationName)\n client.setName(authenticationName);\n if (null != authenticationPassword)\n client.setPassword(authenticationPassword);\n locatorClient = client;\n locatorClient.connect();\n }\n }",
"public void addAuxHandler(Object handler, String prefix) {\n if (handler == null) {\n throw new NullPointerException();\n }\n auxHandlers.put(prefix, handler);\n allHandlers.add(handler);\n\n addDeclaredMethods(handler, prefix);\n inputConverter.addDeclaredConverters(handler);\n outputConverter.addDeclaredConverters(handler);\n\n if (handler instanceof ShellDependent) {\n ((ShellDependent)handler).cliSetShell(this);\n }\n }",
"private void readRecurringData(ProjectCalendarException bce, Project.Calendars.Calendar.Exceptions.Exception exception)\n {\n RecurrenceType rt = getRecurrenceType(NumberHelper.getInt(exception.getType()));\n if (rt != null)\n {\n RecurringData rd = new RecurringData();\n rd.setStartDate(bce.getFromDate());\n rd.setFinishDate(bce.getToDate());\n rd.setRecurrenceType(rt);\n rd.setRelative(getRelative(NumberHelper.getInt(exception.getType())));\n rd.setOccurrences(NumberHelper.getInteger(exception.getOccurrences()));\n\n switch (rd.getRecurrenceType())\n {\n case DAILY:\n {\n rd.setFrequency(getFrequency(exception));\n break;\n }\n\n case WEEKLY:\n {\n rd.setWeeklyDaysFromBitmap(NumberHelper.getInteger(exception.getDaysOfWeek()), DAY_MASKS);\n rd.setFrequency(getFrequency(exception));\n break;\n }\n\n case MONTHLY:\n {\n if (rd.getRelative())\n {\n rd.setDayOfWeek(Day.getInstance(NumberHelper.getInt(exception.getMonthItem()) - 2));\n rd.setDayNumber(Integer.valueOf(NumberHelper.getInt(exception.getMonthPosition()) + 1));\n }\n else\n {\n rd.setDayNumber(NumberHelper.getInteger(exception.getMonthDay()));\n }\n rd.setFrequency(getFrequency(exception));\n break;\n }\n\n case YEARLY:\n {\n if (rd.getRelative())\n {\n rd.setDayOfWeek(Day.getInstance(NumberHelper.getInt(exception.getMonthItem()) - 2));\n rd.setDayNumber(Integer.valueOf(NumberHelper.getInt(exception.getMonthPosition()) + 1));\n }\n else\n {\n rd.setDayNumber(NumberHelper.getInteger(exception.getMonthDay()));\n }\n rd.setMonthNumber(Integer.valueOf(NumberHelper.getInt(exception.getMonth()) + 1));\n break;\n }\n }\n\n if (rd.getRecurrenceType() != RecurrenceType.DAILY || rd.getDates().length > 1)\n {\n bce.setRecurring(rd);\n }\n }\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public static synchronized SlotReference getSlotReference(int player, CdjStatus.TrackSourceSlot slot) {\n Map<CdjStatus.TrackSourceSlot, SlotReference> playerMap = instances.get(player);\n if (playerMap == null) {\n playerMap = new HashMap<CdjStatus.TrackSourceSlot, SlotReference>();\n instances.put(player, playerMap);\n }\n SlotReference result = playerMap.get(slot);\n if (result == null) {\n result = new SlotReference(player, slot);\n playerMap.put(slot, result);\n }\n return result;\n }",
"public String getBaselineDurationText(int baselineNumber)\n {\n Object result = getCachedValue(selectField(TaskFieldLists.BASELINE_DURATIONS, baselineNumber));\n if (result == null)\n {\n result = getCachedValue(selectField(TaskFieldLists.BASELINE_ESTIMATED_DURATIONS, baselineNumber));\n }\n\n if (!(result instanceof String))\n {\n result = null;\n }\n return (String) result;\n }",
"public void setPublishQueueShutdowntime(String publishQueueShutdowntime) {\n\n if (m_frozen) {\n throw new CmsRuntimeException(Messages.get().container(Messages.ERR_CONFIG_FROZEN_0));\n }\n m_publishQueueShutdowntime = Integer.parseInt(publishQueueShutdowntime);\n }"
] |
compute Sin using Taylor Series.
@param x An angle, in radians.
@param nTerms Number of terms.
@return Result. | [
"public static double Sin(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return x - (x * x * x) / 6D;\r\n } else {\r\n\r\n double mult = x * x * x;\r\n double fact = 6;\r\n double sign = 1;\r\n int factS = 5;\r\n double result = x - mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += sign * (mult / fact);\r\n sign *= -1;\r\n }\r\n\r\n return result;\r\n }\r\n }"
] | [
"private 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 ItemRequest<Task> removeFollowers(String task) {\n \n String path = String.format(\"/tasks/%s/removeFollowers\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }",
"public final void loadCollection(\n\t\tfinal SharedSessionContractImplementor session,\n\t\tfinal Serializable id,\n\t\tfinal Type type) throws HibernateException {\n\n\t\tif ( log.isDebugEnabled() ) {\n\t\t\tlog.debug(\n\t\t\t\t\t\"loading collection: \" +\n\t\t\t\t\tMessageHelper.collectionInfoString( getCollectionPersisters()[0], id, getFactory() )\n\t\t\t\t);\n\t\t}\n\n\t\tSerializable[] ids = new Serializable[]{id};\n\t\tQueryParameters qp = new QueryParameters( new Type[]{type}, ids, ids );\n\t\tdoQueryAndInitializeNonLazyCollections(\n\t\t\t\tsession,\n\t\t\t\tqp,\n\t\t\t\tOgmLoadingContext.EMPTY_CONTEXT,\n\t\t\t\ttrue\n\t\t\t);\n\n\t\tlog.debug( \"done loading collection\" );\n\n\t}",
"private static void transposeBlock(DMatrixRBlock A , DMatrixRBlock A_tran,\n int indexA , int indexC ,\n int width , int height )\n {\n for( int i = 0; i < height; i++ ) {\n int rowIndexC = indexC + i;\n int rowIndexA = indexA + width*i;\n int end = rowIndexA + width;\n for( ; rowIndexA < end; rowIndexC += height, rowIndexA++ ) {\n A_tran.data[ rowIndexC ] = A.data[ rowIndexA ];\n }\n }\n }",
"public boolean containsIteratorForTable(String aTable)\r\n {\r\n boolean result = false;\r\n\r\n if (m_rsIterators != null)\r\n {\r\n for (int i = 0; i < m_rsIterators.size(); i++)\r\n {\r\n OJBIterator it = (OJBIterator) m_rsIterators.get(i);\r\n if (it instanceof RsIterator)\r\n {\r\n if (((RsIterator) it).getClassDescriptor().getFullTableName().equals(aTable))\r\n {\r\n result = true;\r\n break;\r\n }\r\n }\r\n else if (it instanceof ChainingIterator)\r\n {\r\n result = ((ChainingIterator) it).containsIteratorForTable(aTable);\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n }",
"public List<Pair<int[][][], int[]>> documentsToDataAndLabelsList(Collection<List<IN>> documents) {\r\n int numDatums = 0;\r\n\r\n List<Pair<int[][][], int[]>> docList = new ArrayList<Pair<int[][][], int[]>>();\r\n for (List<IN> doc : documents) {\r\n Pair<int[][][], int[]> docPair = documentToDataAndLabels(doc);\r\n docList.add(docPair);\r\n numDatums += doc.size();\r\n }\r\n\r\n System.err.println(\"numClasses: \" + classIndex.size() + ' ' + classIndex);\r\n System.err.println(\"numDocuments: \" + docList.size());\r\n System.err.println(\"numDatums: \" + numDatums);\r\n System.err.println(\"numFeatures: \" + featureIndex.size());\r\n return docList;\r\n }",
"public static String format(String pattern, Object... arguments) {\n String msg = pattern;\n if (arguments != null) {\n for (int index = 0; index < arguments.length; index++) {\n msg = msg.replaceAll(\"\\\\{\" + (index + 1) + \"\\\\}\", String.valueOf(arguments[index]));\n }\n }\n return msg;\n }",
"public byte getByte(Integer type)\n {\n byte result = 0;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = item[0];\n }\n\n return (result);\n }",
"@JsonProperty(\"descriptions\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, TermImpl> getDescriptionUpdates() {\n \treturn getMonolingualUpdatedValues(newDescriptions);\n }"
] |
By default uses InputStream as the type of the image
@param title
@param property
@param width
@param fixedWidth
@param imageScaleMode
@param style
@return
@throws ColumnBuilderException
@throws ClassNotFoundException | [
"public FastReportBuilder addBarcodeColumn(String title, String property,String className, int barcodeType,boolean showText, int width, boolean fixedWidth,ImageScaleMode imageScaleMode, Style style) throws ColumnBuilderException, ClassNotFoundException {\n\t\tAbstractColumn column = ColumnBuilder.getNew()\n\t\t.setColumnProperty(property, className)\n\t\t.setWidth(width)\n\t\t.setTitle(title)\n\t\t.setFixedWidth(fixedWidth)\n\t\t.setColumnType(ColumnBuilder.COLUMN_TYPE_BARCODE)\n\t\t.setStyle(style)\n\t\t.setBarcodeType(barcodeType)\n\t\t.setShowText(showText)\n\t\t.build();\n\n\t\tif (style == null)\n\t\t\tguessStyle(className, column);\n\n\t\taddColumn(column);\n\n\t\treturn this;\n\t}"
] | [
"public void setCategoryDisplayOptions(\n String displayCategoriesByRepository,\n String displayCategorySelectionCollapsed) {\n\n m_displayCategoriesByRepository = Boolean.parseBoolean(displayCategoriesByRepository);\n m_displayCategorySelectionCollapsed = Boolean.parseBoolean(displayCategorySelectionCollapsed);\n }",
"public final static void codeEncode(final StringBuilder out, final String value, final int offset)\n {\n for (int i = offset; i < value.length(); i++)\n {\n final char c = value.charAt(i);\n switch (c)\n {\n case '&':\n out.append(\"&\");\n break;\n case '<':\n out.append(\"<\");\n break;\n case '>':\n out.append(\">\");\n break;\n default:\n out.append(c);\n }\n }\n }",
"public static Info eye( final Variable A , ManagerTempVariables manager) {\n Info ret = new Info();\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n\n if( A instanceof VariableMatrix ) {\n ret.op = new Operation(\"eye-m\") {\n @Override\n public void process() {\n DMatrixRMaj mA = ((VariableMatrix)A).matrix;\n output.matrix.reshape(mA.numRows,mA.numCols);\n CommonOps_DDRM.setIdentity(output.matrix);\n }\n };\n } else if( A instanceof VariableInteger ) {\n ret.op = new Operation(\"eye-i\") {\n @Override\n public void process() {\n int N = ((VariableInteger)A).value;\n output.matrix.reshape(N,N);\n CommonOps_DDRM.setIdentity(output.matrix);\n }\n };\n } else {\n throw new RuntimeException(\"Unsupported variable type \"+A);\n }\n\n return ret;\n }",
"private void addCustomFields(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (CustomField field : file.getCustomFields())\n {\n final CustomField c = field;\n MpxjTreeNode childNode = new MpxjTreeNode(field)\n {\n @Override public String toString()\n {\n FieldType type = c.getFieldType();\n \n return type == null ? \"(unknown)\" : type.getFieldTypeClass() + \".\" + type.toString();\n }\n };\n parentNode.add(childNode);\n }\n }",
"public Iterator getAllExtentClasses()\r\n {\r\n ArrayList subTypes = new ArrayList();\r\n\r\n subTypes.addAll(_extents);\r\n\r\n for (int idx = 0; idx < subTypes.size(); idx++)\r\n {\r\n ClassDescriptorDef curClassDef = (ClassDescriptorDef)subTypes.get(idx);\r\n\r\n for (Iterator it = curClassDef.getExtentClasses(); it.hasNext();)\r\n {\r\n ClassDescriptorDef curSubTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n if (!subTypes.contains(curSubTypeDef))\r\n {\r\n subTypes.add(curSubTypeDef);\r\n }\r\n }\r\n }\r\n return subTypes.iterator();\r\n }",
"public static DMatrixRBlock initializeQ(DMatrixRBlock Q,\n int numRows , int numCols , int blockLength ,\n boolean compact) {\n int minLength = Math.min(numRows,numCols);\n if( compact ) {\n if( Q == null ) {\n Q = new DMatrixRBlock(numRows,minLength,blockLength);\n MatrixOps_DDRB.setIdentity(Q);\n } else {\n if( Q.numRows != numRows || Q.numCols != minLength ) {\n throw new IllegalArgumentException(\"Unexpected matrix dimension. Found \"+Q.numRows+\" \"+Q.numCols);\n } else {\n MatrixOps_DDRB.setIdentity(Q);\n }\n }\n } else {\n if( Q == null ) {\n Q = new DMatrixRBlock(numRows,numRows,blockLength);\n MatrixOps_DDRB.setIdentity(Q);\n } else {\n if( Q.numRows != numRows || Q.numCols != numRows ) {\n throw new IllegalArgumentException(\"Unexpected matrix dimension. Found \"+Q.numRows+\" \"+Q.numCols);\n } else {\n MatrixOps_DDRB.setIdentity(Q);\n }\n }\n }\n return Q;\n }",
"private boolean isBundleProperty(Object property) {\n\n return (property.equals(TableProperty.KEY) || property.equals(TableProperty.TRANSLATION));\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 }",
"public String[] getAttributeNames()\r\n {\r\n Set keys = (attributeMap == null ? new HashSet() : attributeMap.keySet());\r\n String[] result = new String[keys.size()];\r\n\r\n keys.toArray(result);\r\n return result;\r\n }"
] |
The parameter 'project' is not used at the moment, but will be used once schema and plugin support lands. | [
"static Project convert(\n String name, com.linecorp.centraldogma.server.storage.project.Project project) {\n return new Project(name);\n }"
] | [
"public static MediaType binary( MediaType.Type type, String subType ) {\n return new MediaType( type, subType, true );\n }",
"protected boolean inViewPort(final int dataIndex) {\n boolean inViewPort = true;\n\n for (Layout layout: mLayouts) {\n inViewPort = inViewPort && (layout.inViewPort(dataIndex) || !layout.isClippingEnabled());\n }\n return inViewPort;\n }",
"public static Enum castToEnum(Object object, Class<? extends Enum> type) {\n if (object==null) return null;\n if (type.isInstance(object)) return (Enum) object;\n if (object instanceof String || object instanceof GString) {\n return Enum.valueOf(type, object.toString());\n }\n throw new GroovyCastException(object, type);\n }",
"@UiThread\n public void expandParentRange(int startParentPosition, int parentCount) {\n int endParentPosition = startParentPosition + parentCount;\n for (int i = startParentPosition; i < endParentPosition; i++) {\n expandParent(i);\n }\n }",
"public static FileStatus[] getDataChunkFiles(FileSystem fs,\n Path path,\n final int partitionId,\n final int replicaType) throws IOException {\n return fs.listStatus(path, new PathFilter() {\n\n public boolean accept(Path input) {\n if(input.getName().matches(\"^\" + Integer.toString(partitionId) + \"_\"\n + Integer.toString(replicaType) + \"_[\\\\d]+\\\\.data\")) {\n return true;\n } else {\n return false;\n }\n }\n });\n }",
"public static FreeMarkerOperation create(Furnace furnace, String templatePath, String outputFilename,\n String... varNames)\n {\n return new FreeMarkerOperation(furnace, templatePath, outputFilename, varNames);\n }",
"private static int[] getMode2PrimaryCodewords(String postcode, int country, int service) {\r\n\r\n for (int i = 0; i < postcode.length(); i++) {\r\n if (postcode.charAt(i) < '0' || postcode.charAt(i) > '9') {\r\n postcode = postcode.substring(0, i);\r\n break;\r\n }\r\n }\r\n\r\n int postcodeNum = Integer.parseInt(postcode);\r\n\r\n int[] primary = new int[10];\r\n primary[0] = ((postcodeNum & 0x03) << 4) | 2;\r\n primary[1] = ((postcodeNum & 0xfc) >> 2);\r\n primary[2] = ((postcodeNum & 0x3f00) >> 8);\r\n primary[3] = ((postcodeNum & 0xfc000) >> 14);\r\n primary[4] = ((postcodeNum & 0x3f00000) >> 20);\r\n primary[5] = ((postcodeNum & 0x3c000000) >> 26) | ((postcode.length() & 0x3) << 4);\r\n primary[6] = ((postcode.length() & 0x3c) >> 2) | ((country & 0x3) << 4);\r\n primary[7] = (country & 0xfc) >> 2;\r\n primary[8] = ((country & 0x300) >> 8) | ((service & 0xf) << 2);\r\n primary[9] = ((service & 0x3f0) >> 4);\r\n\r\n return primary;\r\n }",
"private void writeUserFieldDefinitions()\n {\n for (CustomField cf : m_sortedCustomFieldsList)\n {\n if (cf.getFieldType() != null && cf.getFieldType().getDataType() != null)\n {\n UDFTypeType udf = m_factory.createUDFTypeType();\n udf.setObjectId(Integer.valueOf(FieldTypeHelper.getFieldID(cf.getFieldType())));\n\n udf.setDataType(UserFieldDataType.inferUserFieldDataType(cf.getFieldType().getDataType()));\n udf.setSubjectArea(UserFieldDataType.inferUserFieldSubjectArea(cf.getFieldType()));\n udf.setTitle(cf.getAlias());\n m_apibo.getUDFType().add(udf);\n }\n }\n }",
"private ModelNode buildAddOperation(final ModelNode address, final Map<String, String> properties) {\n final ModelNode op = ServerOperations.createAddOperation(address);\n for (Map.Entry<String, String> prop : properties.entrySet()) {\n final String[] props = prop.getKey().split(\",\");\n if (props.length == 0) {\n throw new RuntimeException(\"Invalid property \" + prop);\n }\n ModelNode node = op;\n for (int i = 0; i < props.length - 1; ++i) {\n node = node.get(props[i]);\n }\n final String value = prop.getValue() == null ? \"\" : prop.getValue();\n if (value.startsWith(\"!!\")) {\n handleDmrString(node, props[props.length - 1], value);\n } else {\n node.get(props[props.length - 1]).set(value);\n }\n }\n return op;\n }"
] |
get the converted object corresponding to sourceObject as converted to
destination type by converter
@param converter
@param sourceObject
@param destinationType
@return | [
"public Object get(IConverter converter, Object sourceObject,\n\t\t\tTypeReference<?> destinationType) {\n\t\treturn convertedObjects.get(new ConvertedObjectsKey(converter,\n\t\t\t\tsourceObject, destinationType));\n\t}"
] | [
"protected boolean isFiltered(AbstractElement canddiate, Param param) {\n\t\tif (canddiate instanceof Group) {\n\t\t\tGroup group = (Group) canddiate;\n\t\t\tif (group.getGuardCondition() != null) {\n\t\t\t\tSet<Parameter> context = param.getAssignedParametes();\n\t\t\t\tConditionEvaluator evaluator = new ConditionEvaluator(context);\n\t\t\t\tif (!evaluator.evaluate(group.getGuardCondition())) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public static Shell createConsoleShell(String prompt, String appName, Object mainHandler) {\n return createConsoleShell(prompt, appName, mainHandler, new EmptyMultiMap<String, Object>());\n }",
"protected Object getObjectFromResultSet() throws PersistenceBrokerException\r\n {\r\n\r\n try\r\n {\r\n // if all primitive attributes of the object are contained in the ResultSet\r\n // the fast direct mapping can be used\r\n return super.getObjectFromResultSet();\r\n }\r\n // if the full loading failed we assume that at least PK attributes are contained\r\n // in the ResultSet and perform a slower Identity based loading...\r\n // This may of course also fail and can throw another PersistenceBrokerException\r\n catch (PersistenceBrokerException e)\r\n {\r\n Identity oid = getIdentityFromResultSet();\r\n return getBroker().getObjectByIdentity(oid);\r\n }\r\n\r\n }",
"public static base_responses Import(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 Importresources[] = new sslfipskey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tImportresources[i] = new sslfipskey();\n\t\t\t\tImportresources[i].fipskeyname = resources[i].fipskeyname;\n\t\t\t\tImportresources[i].key = resources[i].key;\n\t\t\t\tImportresources[i].inform = resources[i].inform;\n\t\t\t\tImportresources[i].wrapkeyname = resources[i].wrapkeyname;\n\t\t\t\tImportresources[i].iv = resources[i].iv;\n\t\t\t\tImportresources[i].exponent = resources[i].exponent;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, Importresources,\"Import\");\n\t\t}\n\t\treturn result;\n\t}",
"public void addForeignKeyField(int newId)\r\n {\r\n if (m_ForeignKeyFields == null)\r\n {\r\n m_ForeignKeyFields = new Vector();\r\n }\r\n m_ForeignKeyFields.add(new Integer(newId));\r\n }",
"private void checkOrMarkPrivateAccess(Expression source, MethodNode mn) {\n if (mn==null) {\n return;\n }\n ClassNode declaringClass = mn.getDeclaringClass();\n ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode();\n if (declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) {\n int mods = mn.getModifiers();\n boolean sameModule = declaringClass.getModule() == enclosingClassNode.getModule();\n String packageName = declaringClass.getPackageName();\n if (packageName==null) {\n packageName = \"\";\n }\n if ((Modifier.isPrivate(mods) && sameModule)\n || (Modifier.isProtected(mods) && !packageName.equals(enclosingClassNode.getPackageName()))) {\n addPrivateFieldOrMethodAccess(source, sameModule? declaringClass : enclosingClassNode, StaticTypesMarker.PV_METHODS_ACCESS, mn);\n }\n }\n }",
"public void addForeignKeyField(String newField)\r\n {\r\n if (m_ForeignKeyFields == null)\r\n {\r\n m_ForeignKeyFields = new Vector();\r\n }\r\n m_ForeignKeyFields.add(newField);\r\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 }",
"@Override\n protected void runUnsafe() throws Exception {\n Path reportDirectory = getReportDirectoryPath();\n Files.walkFileTree(reportDirectory, new DeleteVisitor());\n LOGGER.info(\"Report directory <{}> was successfully cleaned.\", reportDirectory);\n }"
] |
This continuously tries to reconnect in a separate thread and will only stop if the connection was established
successfully or the server gets shutdown. If there is currently a reconnect task active the connection paramaters
and callback will get updated.
@param reconnectUri the updated connection uri
@param authKey the updated authentication key
@param callback the current callback | [
"synchronized void asyncReconnect(final URI reconnectUri, String authKey, final ReconnectCallback callback) {\n if (getState() != State.OPEN) {\n return;\n }\n // Update the configuration with the new credentials\n final ProtocolConnectionConfiguration config = ProtocolConnectionConfiguration.copy(configuration);\n config.setCallbackHandler(createClientCallbackHandler(userName, authKey));\n config.setUri(reconnectUri);\n this.configuration = config;\n\n final ReconnectRunner reconnectTask = this.reconnectRunner;\n if (reconnectTask == null) {\n final ReconnectRunner task = new ReconnectRunner();\n task.callback = callback;\n task.future = executorService.submit(task);\n } else {\n reconnectTask.callback = callback;\n }\n }"
] | [
"protected boolean isPrefixBlock(long divisionValue, long upperValue, int divisionPrefixLen) {\n\t\tif(divisionPrefixLen == 0) {\n\t\t\treturn divisionValue == 0 && upperValue == getMaxValue();\n\t\t}\n\t\tlong ones = ~0L;\n\t\tlong divisionBitMask = ~(ones << getBitCount());\n\t\tlong divisionPrefixMask = ones << (getBitCount() - divisionPrefixLen);\n\t\tlong divisionNonPrefixMask = ~divisionPrefixMask;\n\t\treturn testRange(divisionValue,\n\t\t\t\tupperValue,\n\t\t\t\tupperValue,\n\t\t\t\tdivisionPrefixMask & divisionBitMask,\n\t\t\t\tdivisionNonPrefixMask);\n\t}",
"public PhotoList<Photo> getPopularPhotos(Date date, StatsSort sort, int perPage, int page) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_POPULAR_PHOTOS);\n if (date != null) {\n parameters.put(\"date\", String.valueOf(date.getTime() / 1000L));\n }\n if (sort != null) {\n parameters.put(\"sort\", sort.name());\n }\n addPaginationParameters(parameters, perPage, page);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n return parsePopularPhotos(response);\n }",
"@SuppressForbidden(\"legitimate sysstreams.\")\n private Execute forkProcess(ForkedJvmInfo slaveInfo, EventBus eventBus, \n CommandlineJava commandline, \n TailInputStream eventStream, OutputStream sysout, OutputStream syserr, RandomAccessFile streamsBuffer) {\n try {\n String tempDir = commandline.getSystemProperties().getVariablesVector().stream()\n .filter(v -> v.getKey().equals(\"java.io.tmpdir\"))\n .map(v -> v.getValue())\n .findAny()\n .orElse(null);\n\n final LocalSlaveStreamHandler streamHandler = \n new LocalSlaveStreamHandler(\n eventBus, testsClassLoader, System.err, eventStream, \n sysout, syserr, heartbeat, streamsBuffer);\n\n // Add certain properties to allow identification of the forked JVM from within\n // the subprocess. This can be used for policy files etc.\n final Path cwd = getWorkingDirectory(slaveInfo, tempDir);\n\n Variable v = new Variable();\n v.setKey(CHILDVM_SYSPROP_CWD);\n v.setFile(cwd.toAbsolutePath().normalize().toFile());\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SYSPROP_TEMPDIR);\n v.setFile(getTempDir().toAbsolutePath().normalize().toFile());\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SysGlobals.CHILDVM_SYSPROP_JVM_ID);\n v.setValue(Integer.toString(slaveInfo.id));\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SysGlobals.CHILDVM_SYSPROP_JVM_COUNT);\n v.setValue(Integer.toString(slaveInfo.slaves));\n commandline.addSysproperty(v);\n\n // Emit command line before -stdin to avoid confusion.\n slaveInfo.slaveCommandLine = escapeAndJoin(commandline.getCommandline());\n log(\"Forked child JVM at '\" + cwd.toAbsolutePath().normalize() + \n \"', command (may need escape sequences for your shell):\\n\" + \n slaveInfo.slaveCommandLine, Project.MSG_VERBOSE);\n\n final Execute execute = new Execute();\n execute.setCommandline(commandline.getCommandline());\n execute.setVMLauncher(true);\n execute.setWorkingDirectory(cwd.toFile());\n execute.setStreamHandler(streamHandler);\n execute.setNewenvironment(newEnvironment);\n if (env.getVariables() != null)\n execute.setEnvironment(env.getVariables());\n log(\"Starting JVM J\" + slaveInfo.id, Project.MSG_DEBUG);\n execute.execute();\n return execute;\n } catch (IOException e) {\n throw new BuildException(\"Could not start the child process. Run ant with -verbose to get\" +\n \t\t\" the execution details.\", e);\n }\n }",
"private void parseLdapAuthorization_1_5(final XMLExtendedStreamReader reader,\n final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {\n ModelNode addr = realmAddress.clone().add(AUTHORIZATION, LDAP);\n ModelNode ldapAuthorization = Util.getEmptyOperation(ADD, addr);\n\n list.add(ldapAuthorization);\n\n Set<Attribute> required = EnumSet.of(Attribute.CONNECTION);\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n final String value = reader.getAttributeValue(i);\n if (!isNoNamespaceAttribute(reader, i)) {\n throw unexpectedAttribute(reader, i);\n } else {\n final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));\n required.remove(attribute);\n switch (attribute) {\n case CONNECTION: {\n LdapAuthorizationResourceDefinition.CONNECTION.parseAndSetParameter(value, ldapAuthorization, reader);\n break;\n }\n default: {\n throw unexpectedAttribute(reader, i);\n }\n }\n }\n }\n\n if (required.isEmpty() == false) {\n throw missingRequired(reader, required);\n }\n\n Set<Element> foundElements = new HashSet<Element>();\n while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {\n requireNamespace(reader, namespace);\n final Element element = Element.forName(reader.getLocalName());\n if (foundElements.add(element) == false) {\n throw unexpectedElement(reader); // Only one of each allowed.\n }\n switch (element) {\n case USERNAME_TO_DN: {\n switch (namespace.getMajorVersion()) {\n case 1: // 1.5 up to but not including 2.0\n parseUsernameToDn_1_5(reader, addr, list);\n break;\n default: // 2.0 and onwards\n parseUsernameToDn_2_0(reader, addr, list);\n break;\n }\n\n break;\n }\n case GROUP_SEARCH: {\n switch (namespace) {\n case DOMAIN_1_5:\n case DOMAIN_1_6:\n parseGroupSearch_1_5(reader, addr, list);\n break;\n default:\n parseGroupSearch_1_7_and_2_0(reader, addr, list);\n break;\n }\n break;\n }\n default: {\n throw unexpectedElement(reader);\n }\n }\n }\n }",
"public void sendJsonToUser(Object data, String username) {\n sendToUser(JSON.toJSONString(data), username);\n }",
"protected static Connection memorize(final Connection target, final ConnectionHandle connectionHandle) {\n\n\t\treturn (Connection) Proxy.newProxyInstance(\n\t\t\t\tConnectionProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {ConnectionProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}",
"public void invalidate(final int dataIndex) {\n synchronized (mMeasuredChildren) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"invalidate [%d]\", dataIndex);\n mMeasuredChildren.remove(dataIndex);\n }\n }",
"public ItemDocumentBuilder withSiteLink(String title, String siteKey,\n\t\t\tItemIdValue... badges) {\n\t\twithSiteLink(factory.getSiteLink(title, siteKey, Arrays.asList(badges)));\n\t\treturn this;\n\t}",
"private boolean isAcceptingNewJobs() {\n if (this.requestedToStop) {\n return false;\n } else if (new File(this.workingDirectories.getWorking(), \"stop\").exists()) {\n LOGGER.info(\"The print has been requested to stop\");\n this.requestedToStop = true;\n notifyIfStopped();\n return false;\n } else {\n return true;\n }\n }"
] |
Installs the given set of URIs as the source level URIs. Does not copy the given
set but uses it directly. | [
"public static void setSourceLevelUrisWithoutCopy(final ResourceSet resourceSet, final Set<URI> uris) {\n final SourceLevelURIsAdapter adapter = SourceLevelURIsAdapter.findOrCreateAdapter(resourceSet);\n adapter.sourceLevelURIs = uris;\n }"
] | [
"public Metadata remove(String path) {\n this.values.remove(this.pathToProperty(path));\n this.addOp(\"remove\", path, (String) null);\n return this;\n }",
"private String escapeString(String value)\n {\n m_buffer.setLength(0);\n m_buffer.append('\"');\n for (int index = 0; index < value.length(); index++)\n {\n char c = value.charAt(index);\n switch (c)\n {\n case '\"':\n {\n m_buffer.append(\"\\\\\\\"\");\n break;\n }\n\n case '\\\\':\n {\n m_buffer.append(\"\\\\\\\\\");\n break;\n }\n\n case '/':\n {\n m_buffer.append(\"\\\\/\");\n break;\n }\n\n case '\\b':\n {\n m_buffer.append(\"\\\\b\");\n break;\n }\n\n case '\\f':\n {\n m_buffer.append(\"\\\\f\");\n break;\n }\n\n case '\\n':\n {\n m_buffer.append(\"\\\\n\");\n break;\n }\n\n case '\\r':\n {\n m_buffer.append(\"\\\\r\");\n break;\n }\n\n case '\\t':\n {\n m_buffer.append(\"\\\\t\");\n break;\n }\n\n default:\n {\n // Append if it's not a control character (0x00 to 0x1f)\n if (c > 0x1f)\n {\n m_buffer.append(c);\n }\n break;\n }\n }\n }\n m_buffer.append('\"');\n return m_buffer.toString();\n }",
"public static String unexpandLine(CharSequence self, int tabStop) {\n StringBuilder builder = new StringBuilder(self.toString());\n int index = 0;\n while (index + tabStop < builder.length()) {\n // cut original string in tabstop-length pieces\n String piece = builder.substring(index, index + tabStop);\n // count trailing whitespace characters\n int count = 0;\n while ((count < tabStop) && (Character.isWhitespace(piece.charAt(tabStop - (count + 1)))))\n count++;\n // replace if whitespace was found\n if (count > 0) {\n piece = piece.substring(0, tabStop - count) + '\\t';\n builder.replace(index, index + tabStop, piece);\n index = index + tabStop - (count - 1);\n } else\n index = index + tabStop;\n }\n return builder.toString();\n }",
"public boolean isValidStore(String name) {\n readLock.lock();\n try {\n if(this.storeNames.contains(name)) {\n return true;\n }\n return false;\n } finally {\n readLock.unlock();\n }\n }",
"private String getBearerToken(HttpConnectionInterceptorContext context) {\n final AtomicReference<String> iamTokenResponse = new AtomicReference<String>();\n boolean result = super.requestCookie(context, iamServerUrl, iamTokenRequestBody,\n \"application/x-www-form-urlencoded\", \"application/json\",\n new StoreBearerCallable(iamTokenResponse));\n if (result) {\n return iamTokenResponse.get();\n } else {\n return null;\n }\n }",
"public static String getURLParentDirectory(String urlString) throws IllegalArgumentException {\n URL url = null;\n try {\n url = new URL(urlString);\n } catch (MalformedURLException e) {\n throw Exceptions.IllegalArgument(\"Malformed URL: %s\", url);\n }\n\n String path = url.getPath();\n int lastSlashIndex = path.lastIndexOf(\"/\");\n String directory = lastSlashIndex == -1 ? \"\" : path.substring(0, lastSlashIndex);\n return String.format(\"%s://%s%s%s%s\", url.getProtocol(),\n url.getUserInfo() == null ? \"\" : url.getUserInfo() + \"@\",\n url.getHost(),\n url.getPort() == -1 ? \"\" : \":\" + Integer.toString(url.getPort()),\n directory);\n }",
"public static bridgegroup_nsip_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_nsip_binding obj = new bridgegroup_nsip_binding();\n\t\tobj.set_id(id);\n\t\tbridgegroup_nsip_binding response[] = (bridgegroup_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void processWorkingHours(ProjectCalendar mpxjCalendar, Sequence uniqueID, Day day, List<OverriddenDayType> typeList)\n {\n if (isWorkingDay(mpxjCalendar, day))\n {\n ProjectCalendarHours mpxjHours = mpxjCalendar.getCalendarHours(day);\n if (mpxjHours != null)\n {\n OverriddenDayType odt = m_factory.createOverriddenDayType();\n typeList.add(odt);\n odt.setId(getIntegerString(uniqueID.next()));\n List<Interval> intervalList = odt.getInterval();\n for (DateRange mpxjRange : mpxjHours)\n {\n Date rangeStart = mpxjRange.getStart();\n Date rangeEnd = mpxjRange.getEnd();\n\n if (rangeStart != null && rangeEnd != null)\n {\n Interval interval = m_factory.createInterval();\n intervalList.add(interval);\n interval.setStart(getTimeString(rangeStart));\n interval.setEnd(getTimeString(rangeEnd));\n }\n }\n }\n }\n }",
"public static Date getYearlyAbsoluteAsDate(RecurringData data)\n {\n Date result;\n Integer yearlyAbsoluteDay = data.getDayNumber();\n Integer yearlyAbsoluteMonth = data.getMonthNumber();\n Date startDate = data.getStartDate();\n\n if (yearlyAbsoluteDay == null || yearlyAbsoluteMonth == null || startDate == null)\n {\n result = null;\n }\n else\n {\n Calendar cal = DateHelper.popCalendar(startDate);\n cal.set(Calendar.MONTH, yearlyAbsoluteMonth.intValue() - 1);\n cal.set(Calendar.DAY_OF_MONTH, yearlyAbsoluteDay.intValue());\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n return result;\n }"
] |
Sets the alias. By default the entire attribute path participates in the alias
@param alias The name of the alias to set | [
"public void setAlias(String alias)\r\n\t{\r\n\t\tm_alias = alias;\r\n\t\tString attributePath = (String)getAttribute();\r\n\t\tboolean allPathsAliased = true;\r\n\t\tm_userAlias = new UserAlias(alias, attributePath, allPathsAliased);\r\n\t\t\r\n\t}"
] | [
"public static boolean isBadXmlCharacter(char c) {\n boolean cDataCharacter = c < '\\u0020' && c != '\\t' && c != '\\r' && c != '\\n';\n cDataCharacter |= (c >= '\\uD800' && c < '\\uE000');\n cDataCharacter |= (c == '\\uFFFE' || c == '\\uFFFF');\n return cDataCharacter;\n }",
"public static int findSpace(String haystack, int begin) {\r\n int space = haystack.indexOf(' ', begin);\r\n int nbsp = haystack.indexOf('\\u00A0', begin);\r\n if (space == -1 && nbsp == -1) {\r\n return -1;\r\n } else if (space >= 0 && nbsp >= 0) {\r\n return Math.min(space, nbsp);\r\n } else {\r\n // eg one is -1, and the other is >= 0\r\n return Math.max(space, nbsp);\r\n }\r\n }",
"protected byte[] readByteArray(InputStream is, int size) throws IOException\n {\n byte[] buffer = new byte[size];\n if (is.read(buffer) != buffer.length)\n {\n throw new EOFException();\n }\n return (buffer);\n }",
"@Override\r\n public ImageSource apply(ImageSource source) {\r\n if (radius != 0) {\r\n if (source.isGrayscale()) {\r\n return applyGrayscale(source, radius);\r\n } else {\r\n return applyRGB(source, radius);\r\n }\r\n } else {\r\n if (source.isGrayscale()) {\r\n return applyGrayscale(source, kernel);\r\n } else {\r\n return applyRGB(source, kernel);\r\n }\r\n }\r\n }",
"public static base_response add(nitro_service client, snmpuser resource) throws Exception {\n\t\tsnmpuser addresource = new snmpuser();\n\t\taddresource.name = resource.name;\n\t\taddresource.group = resource.group;\n\t\taddresource.authtype = resource.authtype;\n\t\taddresource.authpasswd = resource.authpasswd;\n\t\taddresource.privtype = resource.privtype;\n\t\taddresource.privpasswd = resource.privpasswd;\n\t\treturn addresource.add_resource(client);\n\t}",
"public static List<String> createBacktrace(final Throwable t) {\n final List<String> bTrace = new LinkedList<String>();\n for (final StackTraceElement ste : t.getStackTrace()) {\n bTrace.add(BT_PREFIX + ste.toString());\n }\n if (t.getCause() != null) {\n addCauseToBacktrace(t.getCause(), bTrace);\n }\n return bTrace;\n }",
"public static boolean isMessageContentToBeLogged(final Message message, final boolean logMessageContent,\n boolean logMessageContentOverride) {\n\n /*\n * If controlling of logging behavior is not allowed externally\n * then log according to global property value\n */\n if (!logMessageContentOverride) {\n return logMessageContent;\n }\n\n Object logMessageContentExtObj = message.getContextualProperty(EXTERNAL_PROPERTY_NAME);\n\n if (null == logMessageContentExtObj) {\n\n return logMessageContent;\n\n } else if (logMessageContentExtObj instanceof Boolean) {\n\n return ((Boolean) logMessageContentExtObj).booleanValue();\n\n } else if (logMessageContentExtObj instanceof String) {\n\n String logMessageContentExtVal = (String) logMessageContentExtObj;\n\n if (logMessageContentExtVal.equalsIgnoreCase(\"true\")) {\n\n return true;\n\n } else if (logMessageContentExtVal.equalsIgnoreCase(\"false\")) {\n\n return false;\n\n } else {\n\n return logMessageContent;\n }\n } else {\n\n return logMessageContent;\n }\n }",
"public static List<ContentRepositoryElement> listFiles(final Path rootPath, Path tempDir, final ContentFilter filter) throws IOException {\n List<ContentRepositoryElement> result = new ArrayList<>();\n if (Files.exists(rootPath)) {\n if(isArchive(rootPath)) {\n return listZipContent(rootPath, filter);\n }\n Files.walkFileTree(rootPath, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n if (filter.acceptFile(rootPath, file)) {\n result.add(ContentRepositoryElement.createFile(formatPath(rootPath.relativize(file)), Files.size(file)));\n }\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n if (filter.acceptDirectory(rootPath, dir)) {\n String directoryPath = formatDirectoryPath(rootPath.relativize(dir));\n if(! \"/\".equals(directoryPath)) {\n result.add(ContentRepositoryElement.createFolder(directoryPath));\n }\n }\n return FileVisitResult.CONTINUE;\n }\n\n private String formatDirectoryPath(Path path) {\n return formatPath(path) + '/';\n }\n\n private String formatPath(Path path) {\n return path.toString().replace(File.separatorChar, '/');\n }\n });\n } else {\n Path file = getFile(rootPath);\n if(isArchive(file)) {\n Path relativePath = file.relativize(rootPath);\n Path target = createTempDirectory(tempDir, \"unarchive\");\n unzip(file, target);\n return listFiles(target.resolve(relativePath), tempDir, filter);\n } else {\n throw new FileNotFoundException(rootPath.toString());\n }\n }\n return result;\n }",
"public Relationship createRelationshipForEmbeddedAssociation(GraphDatabaseService executionEngine, AssociationKey associationKey, EntityKey embeddedKey) {\n\t\tString query = initCreateEmbeddedAssociationQuery( associationKey, embeddedKey );\n\t\tObject[] queryValues = createRelationshipForEmbeddedQueryValues( associationKey, embeddedKey );\n\t\treturn executeQuery( executionEngine, query, queryValues );\n\t}"
] |
Choose from three numbers based on version. | [
"private static int tribus(int version, int a, int b, int c) {\n if (version < 10) {\n return a;\n } else if (version >= 10 && version <= 26) {\n return b;\n } else {\n return c;\n }\n }"
] | [
"public static dnsnsecrec[] get(nitro_service service) throws Exception{\n\t\tdnsnsecrec obj = new dnsnsecrec();\n\t\tdnsnsecrec[] response = (dnsnsecrec[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Method getGetMethod(final Object object, final String fieldName) {\n\t\tif( object == null ) {\n\t\t\tthrow new NullPointerException(\"object should not be null\");\n\t\t} else if( fieldName == null ) {\n\t\t\tthrow new NullPointerException(\"fieldName should not be null\");\n\t\t}\n\t\t\n\t\tMethod method = getCache.get(object.getClass().getName(), fieldName);\n\t\tif( method == null ) {\n\t\t\tmethod = ReflectionUtils.findGetter(object, fieldName);\n\t\t\tgetCache.set(object.getClass().getName(), fieldName, method);\n\t\t}\n\t\treturn method;\n\t}",
"public static CurrencySymbolPosition getSymbolPosition(int value)\n {\n CurrencySymbolPosition result;\n\n switch (value)\n {\n case 1:\n {\n result = CurrencySymbolPosition.AFTER;\n break;\n }\n\n case 2:\n {\n result = CurrencySymbolPosition.BEFORE_WITH_SPACE;\n break;\n }\n\n case 3:\n {\n result = CurrencySymbolPosition.AFTER_WITH_SPACE;\n break;\n }\n\n case 0:\n default:\n {\n result = CurrencySymbolPosition.BEFORE;\n break;\n }\n }\n\n return (result);\n }",
"public List<Set<String>> makeNWiseTuples(String[] variables, int nWise) {\r\n List<Set<String>> completeTuples = new ArrayList<>();\r\n makeNWiseTuplesHelper(completeTuples, variables, 0, new HashSet<String>(), nWise);\n\r\n return completeTuples;\r\n }",
"public static Object newInstance(String className, Class[] types, Object[] args) throws InstantiationException,\r\n IllegalAccessException,\r\n IllegalArgumentException,\r\n InvocationTargetException,\r\n NoSuchMethodException,\r\n SecurityException,\r\n ClassNotFoundException\r\n {\r\n return newInstance(getClass(className), types, args);\r\n }",
"public static String getModuleName(final String moduleId) {\n final int splitter = moduleId.indexOf(':');\n if(splitter == -1){\n return moduleId;\n }\n return moduleId.substring(0, splitter);\n }",
"public ParallelTaskBuilder setReplaceVarMapToSingleTargetFromMap(\n Map<String, StrStrMap> replacementVarMapNodeSpecific,\n String uniformTargetHost) {\n setReplacementVarMapNodeSpecific(replacementVarMapNodeSpecific);\n\n if (Strings.isNullOrEmpty(uniformTargetHost)) {\n logger.error(\"uniform target host is empty or null. skip setting.\");\n return this;\n }\n for (Entry<String, StrStrMap> entry : replacementVarMapNodeSpecific\n .entrySet()) {\n\n if (entry.getValue() != null) {\n entry.getValue().addPair(PcConstants.UNIFORM_TARGET_HOST_VAR,\n uniformTargetHost);\n }\n }\n return this;\n }",
"public Map getPathClasses()\r\n\t{\r\n\t\tif (m_pathClasses.isEmpty())\r\n\t\t{\r\n\t\t\tif (m_parentCriteria == null)\r\n\t\t\t{\r\n\t\t\t\tif (m_query == null)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_pathClasses;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_query.getPathClasses();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\treturn m_parentCriteria.getPathClasses();\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn m_pathClasses;\r\n\t\t}\r\n\t}",
"private org.apache.tools.ant.types.Path addSlaveClasspath() {\n org.apache.tools.ant.types.Path path = new org.apache.tools.ant.types.Path(getProject());\n\n String [] REQUIRED_SLAVE_CLASSES = {\n SlaveMain.class.getName(),\n Strings.class.getName(),\n MethodGlobFilter.class.getName(),\n TeeOutputStream.class.getName()\n };\n\n for (String clazz : Arrays.asList(REQUIRED_SLAVE_CLASSES)) {\n String resource = clazz.replace(\".\", \"/\") + \".class\";\n File f = LoaderUtils.getResourceSource(getClass().getClassLoader(), resource);\n if (f != null) {\n path.createPath().setLocation(f);\n } else {\n throw new BuildException(\"Could not locate classpath for resource: \" + resource);\n }\n }\n return path;\n }"
] |
Search for rectangles which have the same width and x position, and
which join together vertically and merge them together to reduce the
number of rectangles needed to describe a symbol. | [
"protected void mergeVerticalBlocks() {\n for(int i = 0; i < rectangles.size() - 1; i++) {\n for(int j = i + 1; j < rectangles.size(); j++) {\n Rectangle2D.Double firstRect = rectangles.get(i);\n Rectangle2D.Double secondRect = rectangles.get(j);\n if (roughlyEqual(firstRect.x, secondRect.x) && roughlyEqual(firstRect.width, secondRect.width)) {\n if (roughlyEqual(firstRect.y + firstRect.height, secondRect.y)) {\n firstRect.height += secondRect.height;\n rectangles.set(i, firstRect);\n rectangles.remove(j);\n }\n }\n }\n }\n }"
] | [
"protected void processTusFiles(String assemblyUrl) throws IOException, ProtocolException {\n tusClient.setUploadCreationURL(new URL(getClient().getHostUrl() + \"/resumable/files/\"));\n tusClient.enableResuming(tusURLStore);\n\n for (Map.Entry<String, File> entry : files.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n\n for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n }",
"public static void addItemsHandled(String handledItemsType, int handledItemsNumber) {\n \tJobLogger jobLogger = (JobLogger) getInstance();\n if (jobLogger == null) {\n return;\n }\n\n jobLogger.addItemsHandledInstance(handledItemsType, handledItemsNumber);\n }",
"@Deprecated\n\t@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tpublic Map<String, PrimitiveAttribute<?>> getAttributes() {\n\t\tif (!isPrimitiveOnly()) {\n\t\t\tthrow new UnsupportedOperationException(\"Primitive API not supported for nested association values\");\n\t\t}\n\t\treturn (Map) attributes;\n\t}",
"public static void validateClusterNodeCounts(final Cluster lhs, final Cluster rhs) {\n if(!lhs.getNodeIds().equals(rhs.getNodeIds())) {\n throw new VoldemortException(\"Node ids are not the same [ lhs cluster node ids (\"\n + lhs.getNodeIds()\n + \") not equal to rhs cluster node ids (\"\n + rhs.getNodeIds() + \") ]\");\n }\n }",
"public static String[] sortStringArray(String[] array) {\n if (isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }",
"public static void read(InputStream stream, byte[] buffer) throws IOException {\n int read = 0;\n while(read < buffer.length) {\n int newlyRead = stream.read(buffer, read, buffer.length - read);\n if(newlyRead == -1)\n throw new EOFException(\"Attempt to read \" + buffer.length\n + \" bytes failed due to EOF.\");\n read += newlyRead;\n }\n }",
"@SuppressWarnings(\"unchecked\")\n public static <E> E getObject(String className) {\n if (className == null) {\n return (E) null;\n }\n try {\n return (E) Class.forName(className).newInstance();\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }",
"private void recordMount(SlotReference slot) {\n if (mediaMounts.add(slot)) {\n deliverMountUpdate(slot, true);\n }\n if (!mediaDetails.containsKey(slot)) {\n try {\n VirtualCdj.getInstance().sendMediaQuery(slot);\n } catch (Exception e) {\n logger.warn(\"Problem trying to request media details for \" + slot, e);\n }\n }\n }",
"private <T> void deferNotification(T event, final EventMetadata metadata, final ObserverMethod<? super T> observer,\n final List<DeferredEventNotification<?>> notifications) {\n TransactionPhase transactionPhase = observer.getTransactionPhase();\n boolean before = transactionPhase.equals(TransactionPhase.BEFORE_COMPLETION);\n Status status = Status.valueOf(transactionPhase);\n notifications.add(new DeferredEventNotification<T>(contextId, event, metadata, observer, currentEventMetadata, status, before));\n }"
] |
append normal text
@param text normal text
@return SimplifySpanBuild | [
"public SimplifySpanBuild append(String text) {\n if (TextUtils.isEmpty(text)) return this;\n\n mNormalSizeText.append(text);\n mStringBuilder.append(text);\n return this;\n }"
] | [
"protected String getUniqueString(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n ResultSetAndStatement rsStmt = null;\r\n String returnValue = null;\r\n try\r\n {\r\n rsStmt = getBrokerForClass().serviceJdbcAccess().executeSQL(\r\n \"select newid()\", field.getClassDescriptor(), Query.NOT_SCROLLABLE);\r\n if (rsStmt.m_rs.next())\r\n {\r\n returnValue = rsStmt.m_rs.getString(1);\r\n }\r\n else\r\n {\r\n LoggerFactory.getDefaultLogger().error(this.getClass()\r\n + \": Can't lookup new oid for field \" + field);\r\n }\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n throw new SequenceManagerException(e);\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new SequenceManagerException(e);\r\n }\r\n\r\n finally\r\n {\r\n // close the used resources\r\n if (rsStmt != null) rsStmt.close();\r\n }\r\n return returnValue;\r\n }",
"public String[] getAttributeNames()\r\n {\r\n Set keys = (attributeMap == null ? new HashSet() : attributeMap.keySet());\r\n String[] result = new String[keys.size()];\r\n\r\n keys.toArray(result);\r\n return result;\r\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 }",
"List<List<Word>> getDifferentArguments( List<List<Word>> argumentWords ) {\n List<List<Word>> result = Lists.newArrayList();\n for( int i = 0; i < argumentWords.size(); i++ ) {\n result.add( Lists.<Word>newArrayList() );\n }\n\n int nWords = argumentWords.get( 0 ).size();\n\n for( int iWord = 0; iWord < nWords; iWord++ ) {\n Word wordOfFirstCase = argumentWords.get( 0 ).get( iWord );\n\n // data tables have equal here, otherwise\n // the cases would be structurally different\n if( wordOfFirstCase.isDataTable() ) {\n continue;\n }\n\n boolean different = false;\n for( int iCase = 1; iCase < argumentWords.size(); iCase++ ) {\n Word wordOfCase = argumentWords.get( iCase ).get( iWord );\n if( !wordOfCase.getFormattedValue().equals( wordOfFirstCase.getFormattedValue() ) ) {\n different = true;\n break;\n }\n\n }\n if( different ) {\n for( int iCase = 0; iCase < argumentWords.size(); iCase++ ) {\n result.get( iCase ).add( argumentWords.get( iCase ).get( iWord ) );\n }\n }\n }\n\n return result;\n }",
"public static MapBounds adjustBoundsToScaleAndMapSize(\n final GenericMapAttributeValues mapValues,\n final Rectangle paintArea,\n final MapBounds bounds,\n final double dpi) {\n MapBounds newBounds = bounds;\n if (mapValues.isUseNearestScale()) {\n newBounds = newBounds.adjustBoundsToNearestScale(\n mapValues.getZoomLevels(),\n mapValues.getZoomSnapTolerance(),\n mapValues.getZoomLevelSnapStrategy(),\n mapValues.getZoomSnapGeodetic(),\n paintArea, dpi);\n }\n\n newBounds = new BBoxMapBounds(newBounds.toReferencedEnvelope(paintArea));\n\n if (mapValues.isUseAdjustBounds()) {\n newBounds = newBounds.adjustedEnvelope(paintArea);\n }\n return newBounds;\n }",
"public ItemRequest<Workspace> findById(String workspace) {\n \n String path = String.format(\"/workspaces/%s\", workspace);\n return new ItemRequest<Workspace>(this, Workspace.class, path, \"GET\");\n }",
"private void doBatchWork(BatchBackend backend) throws InterruptedException {\n\t\tExecutorService executor = Executors.newFixedThreadPool( typesToIndexInParallel, \"BatchIndexingWorkspace\" );\n\t\tfor ( IndexedTypeIdentifier indexedTypeIdentifier : rootIndexedTypes ) {\n\t\t\texecutor.execute( new BatchIndexingWorkspace( gridDialect, searchFactoryImplementor, sessionFactory, indexedTypeIdentifier,\n\t\t\t\t\tcacheMode, endAllSignal, monitor, backend, tenantId ) );\n\t\t}\n\t\texecutor.shutdown();\n\t\tendAllSignal.await(); // waits for the executor to finish\n\t}",
"private ArrayTypeSignature getArrayTypeSignature(\r\n\t\t\tGenericArrayType genericArrayType) {\r\n\t\tFullTypeSignature componentTypeSignature = getFullTypeSignature(genericArrayType\r\n\t\t\t\t.getGenericComponentType());\r\n\t\tArrayTypeSignature arrayTypeSignature = new ArrayTypeSignature(\r\n\t\t\t\tcomponentTypeSignature);\r\n\t\treturn arrayTypeSignature;\r\n\t}",
"public static final PolylineOptions buildOpenArc(LatLong center, LatLong start, LatLong end) {\n MVCArray res = buildArcPoints(center, start, end);\n return new PolylineOptions().path(res);\n }"
] |
Returns the screen width in pixels
@param context is the context to get the resources
@return the screen width in pixels | [
"public static int getScreenWidth(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n return metrics.widthPixels;\n }"
] | [
"public static tmsessionparameter get(nitro_service service) throws Exception{\n\t\ttmsessionparameter obj = new tmsessionparameter();\n\t\ttmsessionparameter[] response = (tmsessionparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"final public Boolean checkPositionType(String type) {\n if (tokenPosition == null) {\n return false;\n } else {\n return tokenPosition.checkType(type);\n }\n }",
"private static void mergeBlocks(List< Block > blocks) {\r\n for (int i = 1; i < blocks.size(); i++) {\r\n Block b1 = blocks.get(i - 1);\r\n Block b2 = blocks.get(i);\r\n if ((b1.mode == b2.mode) &&\r\n (b1.mode != EncodingMode.NUM || b1.length + b2.length <= MAX_NUMERIC_COMPACTION_BLOCK_SIZE)) {\r\n b1.length += b2.length;\r\n blocks.remove(i);\r\n i--;\r\n }\r\n }\r\n }",
"public RowColumn following() {\n if (row.equals(Bytes.EMPTY)) {\n return RowColumn.EMPTY;\n } else if (col.equals(Column.EMPTY)) {\n return new RowColumn(followingBytes(row));\n } else if (!col.isQualifierSet()) {\n return new RowColumn(row, new Column(followingBytes(col.getFamily())));\n } else if (!col.isVisibilitySet()) {\n return new RowColumn(row, new Column(col.getFamily(), followingBytes(col.getQualifier())));\n } else {\n return new RowColumn(row,\n new Column(col.getFamily(), col.getQualifier(), followingBytes(col.getVisibility())));\n }\n }",
"public String getBaselineDurationText(int baselineNumber)\n {\n Object result = getCachedValue(selectField(TaskFieldLists.BASELINE_DURATIONS, baselineNumber));\n if (result == null)\n {\n result = getCachedValue(selectField(TaskFieldLists.BASELINE_ESTIMATED_DURATIONS, baselineNumber));\n }\n\n if (!(result instanceof String))\n {\n result = null;\n }\n return (String) result;\n }",
"public static dnstxtrec[] get(nitro_service service, String domain[]) throws Exception{\n\t\tif (domain !=null && domain.length>0) {\n\t\t\tdnstxtrec response[] = new dnstxtrec[domain.length];\n\t\t\tdnstxtrec obj[] = new dnstxtrec[domain.length];\n\t\t\tfor (int i=0;i<domain.length;i++) {\n\t\t\t\tobj[i] = new dnstxtrec();\n\t\t\t\tobj[i].set_domain(domain[i]);\n\t\t\t\tresponse[i] = (dnstxtrec) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"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 }",
"public static URL getKubernetesConfigurationUrl(Map<String, String> map) throws MalformedURLException {\n if (Strings.isNotNullOrEmpty(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_URL, \"\"))) {\n return new URL(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_URL, \"\"));\n } else if (Strings.isNotNullOrEmpty(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_RESOURCE_NAME, \"\"))) {\n String resourceName = Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_RESOURCE_NAME, \"\");\n return findConfigResource(resourceName);\n } else if (map.containsKey(ENVIRONMENT_CONFIG_URL)) {\n return new URL(map.get(ENVIRONMENT_CONFIG_URL));\n } else if (map.containsKey(ENVIRONMENT_CONFIG_RESOURCE_NAME)) {\n String resourceName = map.get(ENVIRONMENT_CONFIG_RESOURCE_NAME);\n return findConfigResource(resourceName);\n } else {\n // Let the resource locator find the resource\n return null;\n }\n }",
"private void readHours(ProjectCalendar calendar, Day day, Integer hours)\n {\n int value = hours.intValue();\n int startHour = 0;\n ProjectCalendarHours calendarHours = null;\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, 0);\n cal.set(Calendar.MINUTE, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n\n calendar.setWorkingDay(day, false);\n\n while (value != 0)\n {\n // Move forward until we find a working hour\n while (startHour < 24 && (value & 0x1) == 0)\n {\n value = value >> 1;\n ++startHour;\n }\n\n // No more working hours, bail out\n if (startHour >= 24)\n {\n break;\n }\n\n // Move forward until we find the end of the working hours\n int endHour = startHour;\n while (endHour < 24 && (value & 0x1) != 0)\n {\n value = value >> 1;\n ++endHour;\n }\n\n cal.set(Calendar.HOUR_OF_DAY, startHour);\n Date startDate = cal.getTime();\n cal.set(Calendar.HOUR_OF_DAY, endHour);\n Date endDate = cal.getTime();\n\n if (calendarHours == null)\n {\n calendarHours = calendar.addCalendarHours(day);\n calendar.setWorkingDay(day, true);\n }\n calendarHours.addRange(new DateRange(startDate, endDate));\n startHour = endHour;\n }\n \n DateHelper.pushCalendar(cal);\n }"
] |
Retrieve the field location for a specific field.
@param type field type
@return field location | [
"public FieldLocation getFieldLocation(FieldType type)\n {\n FieldLocation result = null;\n\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getFieldLocation();\n }\n return result;\n }"
] | [
"@Override\n public void stopTransition() {\n //call listeners so they can perform their actions first, like modifying this adapter's transitions\n for (int i = 0, size = mListenerList.size(); i < size; i++) {\n mListenerList.get(i).onTransitionEnd(this);\n }\n\n for (int i = 0, size = mTransitionList.size(); i < size; i++) {\n mTransitionList.get(i).stopTransition();\n }\n }",
"public void loadModel(GVRAndroidResource avatarResource)\n {\n EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_ANIMATION));\n GVRContext ctx = mAvatarRoot.getGVRContext();\n GVRResourceVolume volume = new GVRResourceVolume(ctx, avatarResource);\n GVRSceneObject modelRoot = new GVRSceneObject(ctx);\n\n mAvatarRoot.addChildObject(modelRoot);\n ctx.getAssetLoader().loadModel(volume, modelRoot, settings, false, mLoadModelHandler);\n }",
"public static <T> T columnStringToObject(Class objClass, String str, String delimiterRegex, String[] fieldNames)\r\n throws InstantiationException, IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException\r\n {\r\n Pattern delimiterPattern = Pattern.compile(delimiterRegex);\r\n return StringUtils.<T>columnStringToObject(objClass, str, delimiterPattern, fieldNames);\r\n }",
"public List<Message> requestTrackMenuFrom(final SlotReference slotReference, final int sortOrder)\n throws Exception {\n\n ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {\n @Override\n public List<Message> useClient(Client client) throws Exception {\n return MetadataFinder.getInstance().getFullTrackList(slotReference.slot, client, sortOrder);\n }\n };\n\n return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, \"requesting track menu\");\n }",
"public boolean checkSuffixes(String uri, String[] patterns) {\n\t\tfor (String pattern : patterns) {\n\t\t\tif (pattern.length() > 0) {\n\t\t\t\tif (uri.endsWith(pattern)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public void checkAllRequirementsSatisfied(final String currentPath) {\n StringBuilder errors = new StringBuilder();\n\n for (Field field: this.dependantsInJson) {\n final Collection<String> requirements = this.dependantToRequirementsMap.get(field);\n if (!requirements.isEmpty()) {\n errors.append(\"\\n\");\n String type = field.getType().getName();\n if (field.getType().isArray()) {\n type = field.getType().getComponentType().getName() + \"[]\";\n }\n errors.append(\"\\t* \").append(type).append(' ').append(field.getName()).append(\" depends on \")\n .append(requirements);\n }\n }\n Assert.equals(0, errors.length(),\n \"\\nErrors were detected when analysing the @Requires dependencies of '\" +\n currentPath + \"': \" + errors);\n }",
"private GVRCursorController addDevice(int deviceId) {\n InputDevice device = inputManager.getInputDevice(deviceId);\n GVRControllerType controllerType = getGVRInputDeviceType(device);\n\n if (mEnabledControllerTypes == null)\n {\n return null;\n }\n if (controllerType == GVRControllerType.GAZE && !mEnabledControllerTypes.contains(GVRControllerType.GAZE))\n {\n return null;\n }\n\n int key;\n if (controllerType == GVRControllerType.GAZE) {\n // create the controller if there isn't one. \n if (gazeCursorController == null) {\n gazeCursorController = new GVRGazeCursorController(context, GVRControllerType.GAZE,\n GVRDeviceConstants.OCULUS_GEARVR_DEVICE_NAME,\n GVRDeviceConstants.OCULUS_GEARVR_TOUCHPAD_VENDOR_ID,\n GVRDeviceConstants.OCULUS_GEARVR_TOUCHPAD_PRODUCT_ID);\n }\n // use the cached gaze key\n key = GAZE_CACHED_KEY;\n } else {\n key = getCacheKey(device, controllerType);\n }\n\n if (key != -1)\n {\n GVRCursorController controller = cache.get(key);\n if (controller == null)\n {\n if ((mEnabledControllerTypes == null) || !mEnabledControllerTypes.contains(controllerType))\n {\n return null;\n }\n if (controllerType == GVRControllerType.MOUSE)\n {\n controller = mouseDeviceManager.getCursorController(context, device.getName(), device.getVendorId(), device.getProductId());\n }\n else if (controllerType == GVRControllerType.GAMEPAD)\n {\n controller = gamepadDeviceManager.getCursorController(context, device.getName(), device.getVendorId(), device.getProductId());\n }\n else if (controllerType == GVRControllerType.GAZE)\n {\n controller = gazeCursorController;\n }\n cache.put(key, controller);\n controllerIds.put(device.getId(), controller);\n return controller;\n }\n else\n {\n controllerIds.put(device.getId(), controller);\n }\n }\n return null;\n }",
"public void setWorkingDay(Day day, DayType working)\n {\n DayType value;\n\n if (working == null)\n {\n if (isDerived())\n {\n value = DayType.DEFAULT;\n }\n else\n {\n value = DayType.WORKING;\n }\n }\n else\n {\n value = working;\n }\n\n m_days[day.getValue() - 1] = value;\n }",
"public String getUnicodeString(Integer id, Integer type)\n {\n return (getUnicodeString(m_meta.getOffset(id, type)));\n }"
] |
Creates a map between a calendar ID and a list of
work pattern assignment rows.
@param rows work pattern assignment rows
@return work pattern assignment map | [
"public Map<Integer, List<Row>> createWorkPatternAssignmentMap(List<Row> rows)\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer calendarID = row.getInteger(\"WORK_PATTERN_ASSIGNMENTID\");\n List<Row> list = map.get(calendarID);\n if (list == null)\n {\n list = new LinkedList<Row>();\n map.put(calendarID, list);\n }\n list.add(row);\n }\n return map;\n }"
] | [
"public void afterLoading(CollectionProxyDefaultImpl colProxy)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"loading a proxied collection a collection: \" + colProxy);\r\n Collection data = colProxy.getData();\r\n for (Iterator iterator = data.iterator(); iterator.hasNext();)\r\n {\r\n Object o = iterator.next();\r\n if(!isOpen())\r\n {\r\n log.error(\"Collection proxy materialization outside of a running tx, obj=\" + o);\r\n try{throw new Exception(\"Collection proxy materialization outside of a running tx, obj=\" + o);}\r\n catch(Exception e)\r\n {e.printStackTrace();}\r\n }\r\n else\r\n {\r\n Identity oid = getBroker().serviceIdentity().buildIdentity(o);\r\n ClassDescriptor cld = getBroker().getClassDescriptor(ProxyHelper.getRealClass(o));\r\n RuntimeObject rt = new RuntimeObject(o, oid, cld, false, ProxyHelper.isProxy(o));\r\n lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList());\r\n }\r\n }\r\n unregisterFromCollectionProxy(colProxy);\r\n }",
"public ItemRequest<Section> insertInProject(String project) {\n \n String path = String.format(\"/projects/%s/sections/insert\", project);\n return new ItemRequest<Section>(this, Section.class, path, \"POST\");\n }",
"public static final boolean setSelectedValue(ListBox list, String value, boolean addMissingValues) {\n\tif (value == null) {\n\t list.setSelectedIndex(0);\n\t return false;\n\t}\n\telse {\n\t int index = findValueInListBox(list, value);\n\t if (index >= 0) {\n\t\tlist.setSelectedIndex(index);\n\t\treturn true;\n\t }\n\n\t if (addMissingValues) {\n\t\tlist.addItem(value, value);\n\n\t\t// now that it's there, search again\n\t\tindex = findValueInListBox(list, value);\n\t\tlist.setSelectedIndex(index);\n\t\treturn true;\n\t }\n\n\t return false;\n\t}\n }",
"private void updateDefaultTimeAndSizeRollingAppender(final FoundationFileRollingAppender appender) {\n\n\t\tif (appender.getDatePattern().trim().length() == 0) {\n\t\t\tappender.setDatePattern(FoundationLoggerConstants.DEFAULT_DATE_PATTERN.toString());\n\t\t}\n\t\t\n\t\tString maxFileSizeKey = \"log4j.appender.\"+appender.getName()+\".MaxFileSize\";\n\t\tappender.setMaxFileSize(FoundationLogger.log4jConfigProps.getProperty(maxFileSizeKey, FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString()));\n\n//\t\tif (appender.getMaxFileSize() == null || appender.getMaxFileSize().equals(FoundationLoggerConstants.DEFAULT_FILE_SIZE.toString())) {\n//\t\t\tappender.setMaxFileSize(FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString());\n//\t\t}\n\n\t\tString maxRollCountKey = \"log4j.appender.\"+appender.getName()+\".MaxRollFileCount\";\n\t\tappender.setMaxRollFileCount(Integer.parseInt(FoundationLogger.log4jConfigProps.getProperty(maxRollCountKey,\"100\")));\n\t}",
"public boolean hasUser(String userId) {\r\n String normalized = normalizerUserName(userId);\r\n return loginToUser.containsKey(normalized) || emailToUser.containsKey(normalized);\r\n }",
"public static int lookupShaper(String name) {\r\n if (name == null) {\r\n return NOWORDSHAPE;\r\n } else if (name.equalsIgnoreCase(\"dan1\")) {\r\n return WORDSHAPEDAN1;\r\n } else if (name.equalsIgnoreCase(\"chris1\")) {\r\n return WORDSHAPECHRIS1;\r\n } else if (name.equalsIgnoreCase(\"dan2\")) {\r\n return WORDSHAPEDAN2;\r\n } else if (name.equalsIgnoreCase(\"dan2useLC\")) {\r\n return WORDSHAPEDAN2USELC;\r\n } else if (name.equalsIgnoreCase(\"dan2bio\")) {\r\n return WORDSHAPEDAN2BIO;\r\n } else if (name.equalsIgnoreCase(\"dan2bioUseLC\")) {\r\n return WORDSHAPEDAN2BIOUSELC;\r\n } else if (name.equalsIgnoreCase(\"jenny1\")) {\r\n return WORDSHAPEJENNY1;\r\n } else if (name.equalsIgnoreCase(\"jenny1useLC\")) {\r\n return WORDSHAPEJENNY1USELC;\r\n } else if (name.equalsIgnoreCase(\"chris2\")) {\r\n return WORDSHAPECHRIS2;\r\n } else if (name.equalsIgnoreCase(\"chris2useLC\")) {\r\n return WORDSHAPECHRIS2USELC;\r\n } else if (name.equalsIgnoreCase(\"chris3\")) {\r\n return WORDSHAPECHRIS3;\r\n } else if (name.equalsIgnoreCase(\"chris3useLC\")) {\r\n return WORDSHAPECHRIS3USELC;\r\n } else if (name.equalsIgnoreCase(\"chris4\")) {\r\n return WORDSHAPECHRIS4;\r\n } else if (name.equalsIgnoreCase(\"digits\")) {\r\n return WORDSHAPEDIGITS;\r\n } else {\r\n return NOWORDSHAPE;\r\n }\r\n }",
"private void updateDates(Task parentTask)\n {\n if (parentTask.hasChildTasks())\n {\n Date plannedStartDate = null;\n Date plannedFinishDate = null;\n\n for (Task task : parentTask.getChildTasks())\n {\n updateDates(task);\n plannedStartDate = DateHelper.min(plannedStartDate, task.getStart());\n plannedFinishDate = DateHelper.max(plannedFinishDate, task.getFinish());\n }\n\n parentTask.setStart(plannedStartDate);\n parentTask.setFinish(plannedFinishDate);\n }\n }",
"private void readRelationships(Storepoint phoenixProject)\n {\n for (Relationship relation : phoenixProject.getRelationships().getRelationship())\n {\n readRelation(relation);\n }\n }",
"public static String encodeAuthority(String authority, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(authority, encoding, HierarchicalUriComponents.Type.AUTHORITY);\n\t}"
] |
Remove attachments matches pattern from step and all step substeps
@param context from which attachments will be removed | [
"@Override\n public void process(Step context) {\n Iterator<Attachment> iterator = context.getAttachments().listIterator();\n while (iterator.hasNext()) {\n Attachment attachment = iterator.next();\n if (pattern.matcher(attachment.getSource()).matches()) {\n deleteAttachment(attachment);\n iterator.remove();\n }\n }\n\n for (Step step : context.getSteps()) {\n process(step);\n }\n }"
] | [
"private void init() {\n logger.info(\"metadata init().\");\n\n writeLock.lock();\n try {\n // Required keys\n initCache(CLUSTER_KEY);\n\n // If stores definition storage engine is not null, initialize metadata\n // Add the mapping from key to the storage engine used\n if(this.storeDefinitionsStorageEngine != null) {\n initStoreDefinitions(null);\n } else {\n initCache(STORES_KEY);\n }\n\n // Initialize system store in the metadata cache\n initSystemCache();\n initSystemRoutingStrategies(getCluster());\n\n // Initialize with default if not present\n initCache(SLOP_STREAMING_ENABLED_KEY, true);\n initCache(PARTITION_STREAMING_ENABLED_KEY, true);\n initCache(READONLY_FETCH_ENABLED_KEY, true);\n initCache(QUOTA_ENFORCEMENT_ENABLED_KEY, true);\n initCache(REBALANCING_STEAL_INFO, new RebalancerState(new ArrayList<RebalanceTaskInfo>()));\n initCache(SERVER_STATE_KEY, VoldemortState.NORMAL_SERVER.toString());\n initCache(REBALANCING_SOURCE_CLUSTER_XML, null);\n initCache(REBALANCING_SOURCE_STORES_XML, null);\n\n\n } finally {\n writeLock.unlock();\n }\n }",
"public int compare(Object objA, Object objB)\r\n {\r\n String idAStr = _table.getColumn((String)objA).getProperty(\"id\");\r\n String idBStr = _table.getColumn((String)objB).getProperty(\"id\");\r\n int idA;\r\n int idB;\r\n\r\n try {\r\n idA = Integer.parseInt(idAStr);\r\n }\r\n catch (Exception ex) {\r\n return 1;\r\n }\r\n try {\r\n idB = Integer.parseInt(idBStr);\r\n }\r\n catch (Exception ex) {\r\n return -1;\r\n }\r\n return idA < idB ? -1 : (idA > idB ? 1 : 0);\r\n }",
"public boolean perform(Run<?, ?> build, Launcher launcher, TaskListener listener, EnvVars env, FilePath workDir, FilePath tempDir)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.getLogger().println(\"Couldn't find Maven home at \" + mavenHome.getRemote() + \" on agent \" + Utils.getAgentName(workDir) +\n \". This could be because this build is running inside a Docker container.\");\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, workDir, tempDir);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }",
"public List<ModelNode> getAllowedValues() {\n if (allowedValues == null) {\n return Collections.emptyList();\n }\n return Arrays.asList(this.allowedValues);\n }",
"private String formatTime(Date value)\n {\n return (value == null ? null : m_formats.getTimeFormat().format(value));\n }",
"public double getDouble(Integer id, Integer type)\n {\n double result = Double.longBitsToDouble(getLong(id, type));\n if (Double.isNaN(result))\n {\n result = 0;\n }\n return result;\n }",
"private void checkTexRange(AiTextureType type, int index) {\n if (index < 0 || index > m_numTextures.get(type)) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Size: \" +\n m_numTextures.get(type));\n }\n }",
"public <V> V detach(final AttachmentKey<V> key) {\n assert key != null;\n return key.cast(contextAttachments.remove(key));\n }",
"public static BoxAPIConnection getTransactionConnection(String accessToken, String scope) {\n return BoxTransactionalAPIConnection.getTransactionConnection(accessToken, scope, null);\n }"
] |
This method takes a calendar of MPXJ library type, then returns a String of the
general working days USACE format. For example, the regular 5-day work week is
NYYYYYN
If you get Fridays off work, then the String becomes NYYYYNN
@param input ProjectCalendar instance
@return work days string | [
"public static String workDays(ProjectCalendar input)\n {\n StringBuilder result = new StringBuilder();\n DayType[] test = input.getDays(); // get the array from MPXJ ProjectCalendar\n for (DayType i : test)\n { // go through every day in the given array\n if (i == DayType.NON_WORKING)\n {\n result.append(\"N\"); // only put N for non-working day of the week\n }\n else\n {\n result.append(\"Y\"); // Assume WORKING day unless NON_WORKING\n }\n }\n return result.toString(); // According to USACE specs., exceptions will be specified in HOLI records\n }"
] | [
"public void randomize() {\n\t\tnumKnots = 4 + (int)(6*Math.random());\n\t\txKnots = new int[numKnots];\n\t\tyKnots = new int[numKnots];\n\t\tknotTypes = new byte[numKnots];\n\t\tfor (int i = 0; i < numKnots; i++) {\n\t\t\txKnots[i] = (int)(255 * Math.random());\n\t\t\tyKnots[i] = 0xff000000 | ((int)(255 * Math.random()) << 16) | ((int)(255 * Math.random()) << 8) | (int)(255 * Math.random());\n\t\t\tknotTypes[i] = RGB|SPLINE;\n\t\t}\n\t\txKnots[0] = -1;\n\t\txKnots[1] = 0;\n\t\txKnots[numKnots-2] = 255;\n\t\txKnots[numKnots-1] = 256;\n\t\tsortKnots();\n\t\trebuildGradient();\n\t}",
"public void delete(Object obj, boolean ignoreReferences) throws PersistenceBrokerException\n {\n if(isTxCheck() && !isInTransaction())\n {\n if(logger.isEnabledFor(Logger.ERROR))\n {\n String msg = \"No running PB-tx found. Please, only delete objects in context of a PB-transaction\" +\n \" to avoid side-effects - e.g. when rollback of complex objects.\";\n try\n {\n throw new Exception(\"** Delete object without active PersistenceBroker transaction **\");\n }\n catch(Exception e)\n {\n logger.error(msg, e);\n }\n }\n }\n try\n {\n doDelete(obj, ignoreReferences);\n }\n finally\n {\n markedForDelete.clear();\n }\n }",
"public static nsip6[] get(nitro_service service) throws Exception{\n\t\tnsip6 obj = new nsip6();\n\t\tnsip6[] response = (nsip6[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void removeMount(SlotReference slot) {\n mediaDetails.remove(slot);\n if (mediaMounts.remove(slot)) {\n deliverMountUpdate(slot, false);\n }\n }",
"private static String convertPathToResource(String path) {\n File file = new File(path);\n List<String> parts = new ArrayList<String>();\n do {\n parts.add(file.getName());\n file = file.getParentFile();\n }\n while (file != null);\n\n StringBuffer sb = new StringBuffer();\n int size = parts.size();\n for (int a = size - 1; a >= 0; a--) {\n if (sb.length() > 0) {\n sb.append(\"_\");\n }\n sb.append(parts.get(a));\n }\n\n // TODO: Better regex replacement\n return sb.toString().replace('-', '_').replace(\"+\", \"plus\").toLowerCase(Locale.US);\n }",
"private void logBinaryStringInfo(StringBuilder binaryString) {\n\n encodeInfo += \"Binary Length: \" + binaryString.length() + \"\\n\";\n encodeInfo += \"Binary String: \";\n\n int nibble = 0;\n for (int i = 0; i < binaryString.length(); i++) {\n switch (i % 4) {\n case 0:\n if (binaryString.charAt(i) == '1') {\n nibble += 8;\n }\n break;\n case 1:\n if (binaryString.charAt(i) == '1') {\n nibble += 4;\n }\n break;\n case 2:\n if (binaryString.charAt(i) == '1') {\n nibble += 2;\n }\n break;\n case 3:\n if (binaryString.charAt(i) == '1') {\n nibble += 1;\n }\n encodeInfo += Integer.toHexString(nibble);\n nibble = 0;\n break;\n }\n }\n\n if ((binaryString.length() % 4) != 0) {\n encodeInfo += Integer.toHexString(nibble);\n }\n\n encodeInfo += \"\\n\";\n }",
"public static I_CmsMacroResolver newWorkplaceLocaleResolver(final CmsObject cms) {\n\n // Resolve macros in the property configuration\n CmsMacroResolver resolver = new CmsMacroResolver();\n resolver.setCmsObject(cms);\n CmsUserSettings userSettings = new CmsUserSettings(cms.getRequestContext().getCurrentUser());\n CmsMultiMessages multimessages = new CmsMultiMessages(userSettings.getLocale());\n multimessages.addMessages(OpenCms.getWorkplaceManager().getMessages(userSettings.getLocale()));\n resolver.setMessages(multimessages);\n resolver.setKeepEmptyMacros(true);\n\n return resolver;\n }",
"@PostConstruct\n\tprotected void postConstruct() {\n\t\tif (null == authenticationServices) {\n\t\t\tauthenticationServices = new ArrayList<AuthenticationService>();\n\t\t}\n\t\tif (!excludeDefault) {\n\t\t\tauthenticationServices.add(staticAuthenticationService);\n\t\t}\n\t}",
"public void finalizeConfig() {\n assert !configFinalized;\n\n try {\n retrieveEngine();\n } catch (Exception e) {\n throw new RuntimeException(e.getMessage(), e);\n }\n configFinalized = true;\n }"
] |
interceptors, decorators and observers go first | [
"protected AbstractBeanDeployer<E> deploySpecialized() {\n // ensure that all decorators are initialized before initializing\n // the rest of the beans\n for (DecoratorImpl<?> bean : getEnvironment().getDecorators()) {\n bean.initialize(getEnvironment());\n containerLifecycleEvents.fireProcessBean(getManager(), bean);\n manager.addDecorator(bean);\n BootstrapLogger.LOG.foundDecorator(bean);\n }\n for (InterceptorImpl<?> bean : getEnvironment().getInterceptors()) {\n bean.initialize(getEnvironment());\n containerLifecycleEvents.fireProcessBean(getManager(), bean);\n manager.addInterceptor(bean);\n BootstrapLogger.LOG.foundInterceptor(bean);\n }\n return this;\n }"
] | [
"private static long switchValue8(long currentHexValue, int digitCount) {\n\t\tlong result = 0x7 & currentHexValue;\n\t\tint shift = 0;\n\t\twhile(--digitCount > 0) {\n\t\t\tshift += 3;\n\t\t\tcurrentHexValue >>>= 4;\n\t\t\tresult |= (0x7 & currentHexValue) << shift;\n\t\t}\n\t\treturn result;\n\t}",
"protected Boolean getSearchForEmptyQuery() {\n\n Boolean isSearchForEmptyQuery = parseOptionalBooleanValue(m_configObject, JSON_KEY_SEARCH_FOR_EMPTY_QUERY);\n return (isSearchForEmptyQuery == null) && (null != m_baseConfig)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getSearchForEmptyQueryParam())\n : isSearchForEmptyQuery;\n }",
"public void setColorSchemeResources(int... colorResIds) {\n final Resources res = getResources();\n int[] colorRes = new int[colorResIds.length];\n for (int i = 0; i < colorResIds.length; i++) {\n colorRes[i] = res.getColor(colorResIds[i]);\n }\n setColorSchemeColors(colorRes);\n }",
"public static String rset(String input, int width)\n {\n String result; // result to return\n StringBuilder pad = new StringBuilder();\n if (input == null)\n {\n for (int i = 0; i < width - 1; i++)\n {\n pad.append(' '); // put blanks into buffer\n }\n result = \" \" + pad; // one short to use + overload\n }\n else\n {\n if (input.length() >= width)\n {\n result = input.substring(0, width); // when input is too long, truncate\n }\n else\n {\n int padLength = width - input.length(); // number of blanks to add\n for (int i = 0; i < padLength; i++)\n {\n pad.append(' '); // actually put blanks into buffer\n }\n result = pad + input; // concatenate\n }\n }\n return result;\n }",
"private void readVersion(InputStream is) throws IOException\n {\n BytesReadInputStream bytesReadStream = new BytesReadInputStream(is);\n String version = DatatypeConverter.getString(bytesReadStream);\n m_offset += bytesReadStream.getBytesRead();\n SynchroLogger.log(\"VERSION\", version);\n \n String[] versionArray = version.split(\"\\\\.\");\n m_majorVersion = Integer.parseInt(versionArray[0]);\n }",
"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}",
"public Collection<Contact> getList() throws FlickrException {\r\n \t ContactList<Contact> contacts = new ContactList<Contact>();\r\n \r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element contactsElement = response.getPayload();\r\n contacts.setPage(contactsElement.getAttribute(\"page\"));\r\n contacts.setPages(contactsElement.getAttribute(\"pages\"));\r\n contacts.setPerPage(contactsElement.getAttribute(\"perpage\"));\r\n contacts.setTotal(contactsElement.getAttribute(\"total\"));\r\n NodeList contactNodes = contactsElement.getElementsByTagName(\"contact\");\r\n for (int i = 0; i < contactNodes.getLength(); i++) {\r\n Element contactElement = (Element) contactNodes.item(i);\r\n Contact contact = new Contact();\r\n contact.setId(contactElement.getAttribute(\"nsid\"));\r\n contact.setUsername(contactElement.getAttribute(\"username\"));\r\n contact.setRealName(contactElement.getAttribute(\"realname\"));\r\n contact.setFriend(\"1\".equals(contactElement.getAttribute(\"friend\")));\r\n contact.setFamily(\"1\".equals(contactElement.getAttribute(\"family\")));\r\n contact.setIgnored(\"1\".equals(contactElement.getAttribute(\"ignored\")));\r\n String lPathAlias = contactElement.getAttribute(\"path_alias\");\r\n contact.setPathAlias(lPathAlias == null || \"\".equals(lPathAlias) ? null : lPathAlias);\r\n contact.setOnline(OnlineStatus.fromType(contactElement.getAttribute(\"online\")));\r\n contact.setIconFarm(contactElement.getAttribute(\"iconfarm\"));\r\n contact.setIconServer(contactElement.getAttribute(\"iconserver\"));\r\n if (contact.getOnline() == OnlineStatus.AWAY) {\r\n contactElement.normalize();\r\n contact.setAwayMessage(XMLUtilities.getValue(contactElement));\r\n }\r\n contacts.add(contact);\r\n }\r\n return contacts;\r\n }",
"private void handleMultiChannelEncapResponse(\r\n\t\t\tSerialMessage serialMessage, int offset) {\r\n\t\tlogger.trace(\"Process Multi-channel Encapsulation\");\r\n\t\tCommandClass commandClass;\r\n\t\tZWaveCommandClass zwaveCommandClass;\r\n\t\tint endpointId = serialMessage.getMessagePayloadByte(offset);\r\n\t\tint commandClassCode = serialMessage.getMessagePayloadByte(offset + 2);\r\n\t\tcommandClass = CommandClass.getCommandClass(commandClassCode);\r\n\t\t\r\n\t\tif (commandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d Requested Command Class = %s (0x%02x)\", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));\r\n\t\tZWaveEndpoint endpoint = this.endpoints.get(endpointId);\r\n\t\t\r\n\t\tif (endpoint == null){\r\n\t\t\tlogger.error(\"Endpoint {} not found on node {}. Cannot set command classes.\", endpoint, this.getNode().getNodeId());\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tzwaveCommandClass = endpoint.getCommandClass(commandClass);\r\n\t\t\r\n\t\tif (zwaveCommandClass == null) {\r\n\t\t\tlogger.warn(String.format(\"CommandClass %s (0x%02x) not implemented by endpoint %d, fallback to main node.\", commandClass.getLabel(), commandClassCode, endpointId));\r\n\t\t\tzwaveCommandClass = this.getNode().getCommandClass(commandClass);\r\n\t\t}\r\n\t\t\r\n\t\tif (zwaveCommandClass == null) {\r\n\t\t\tlogger.error(String.format(\"CommandClass %s (0x%02x) not implemented by node %d.\", commandClass.getLabel(), commandClassCode, this.getNode().getNodeId()));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d, Endpoint = %d, calling handleApplicationCommandRequest.\", this.getNode().getNodeId(), endpointId));\r\n\t\tzwaveCommandClass.handleApplicationCommandRequest(serialMessage, offset + 3, endpointId);\r\n\t}",
"private OJBIterator getRsIteratorFromQuery(Query query, ClassDescriptor cld, RsIteratorFactory factory)\n throws PersistenceBrokerException\n {\n query.setFetchSize(1);\n if (query instanceof QueryBySQL)\n {\n if(logger.isDebugEnabled()) logger.debug(\"Creating SQL-RsIterator for class [\"+cld.getClassNameOfObject()+\"]\");\n return factory.createRsIterator((QueryBySQL) query, cld, this);\n }\n\n if (!cld.isExtent() || !query.getWithExtents())\n {\n // no extents just use the plain vanilla RsIterator\n if(logger.isDebugEnabled()) logger.debug(\"Creating RsIterator for class [\"+cld.getClassNameOfObject()+\"]\");\n\n return factory.createRsIterator(query, cld, this);\n }\n\n if(logger.isDebugEnabled()) logger.debug(\"Creating ChainingIterator for class [\"+cld.getClassNameOfObject()+\"]\");\n\n ChainingIterator chainingIter = new ChainingIterator();\n\n // BRJ: add base class iterator\n if (!cld.isInterface())\n {\n if(logger.isDebugEnabled()) logger.debug(\"Adding RsIterator for class [\"+cld.getClassNameOfObject()+\"] to ChainingIterator\");\n\n chainingIter.addIterator(factory.createRsIterator(query, cld, this));\n }\n\n Iterator extents = getDescriptorRepository().getAllConcreteSubclassDescriptors(cld).iterator();\n while (extents.hasNext())\n {\n ClassDescriptor extCld = (ClassDescriptor) extents.next();\n\n // read same table only once\n if (chainingIter.containsIteratorForTable(extCld.getFullTableName()))\n {\n if(logger.isDebugEnabled()) logger.debug(\"Skipping class [\"+extCld.getClassNameOfObject()+\"]\");\n }\n else\n {\n if(logger.isDebugEnabled()) logger.debug(\"Adding RsIterator of class [\"+extCld.getClassNameOfObject()+\"] to ChainingIterator\");\n\n // add the iterator to the chaining iterator.\n chainingIter.addIterator(factory.createRsIterator(query, extCld, this));\n }\n }\n\n return chainingIter;\n }"
] |
Sets the yearly absolute date.
@param date yearly absolute date | [
"public void setYearlyAbsoluteFromDate(Date date)\n {\n if (date != null)\n {\n Calendar cal = DateHelper.popCalendar(date);\n m_dayNumber = Integer.valueOf(cal.get(Calendar.DAY_OF_MONTH));\n m_monthNumber = Integer.valueOf(cal.get(Calendar.MONTH) + 1);\n DateHelper.pushCalendar(cal);\n }\n }"
] | [
"private boolean hidden(String className) {\n\tclassName = removeTemplate(className);\n\tClassInfo ci = classnames.get(className);\n\treturn ci != null ? ci.hidden : optionProvider.getOptionsFor(className).matchesHideExpression(className);\n }",
"private void readRoleDefinitions(Project gpProject)\n {\n m_roleDefinitions.put(\"Default:1\", \"project manager\");\n\n for (Roles roles : gpProject.getRoles())\n {\n if (\"Default\".equals(roles.getRolesetName()))\n {\n continue;\n }\n\n for (Role role : roles.getRole())\n {\n m_roleDefinitions.put(role.getId(), role.getName());\n }\n }\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 }",
"private void updateDetail(TrackMetadataUpdate update, WaveformDetail detail) {\n detailHotCache.put(DeckReference.getDeckReference(update.player, 0), detail); // Main deck\n if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well\n for (CueList.Entry entry : update.metadata.getCueList().entries) {\n if (entry.hotCueNumber != 0) {\n detailHotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), detail);\n }\n }\n }\n deliverWaveformDetailUpdate(update.player, detail);\n }",
"public void addCollaborator(String appName, String collaborator) {\n connection.execute(new SharingAdd(appName, collaborator), apiKey);\n }",
"public static String getGalleryNotFoundKey(String gallery) {\n\n StringBuffer sb = new StringBuffer(ERROR_REASON_NO_PREFIX);\n sb.append(gallery.toUpperCase());\n sb.append(GUI_TITLE_POSTFIX);\n return sb.toString();\n }",
"private boolean isInInnerCircle(float x, float y) {\n return GearWearableUtility.isInCircle(x, y, CENTER_X, CENTER_Y, INNER_RADIUS);\n }",
"public static ConsistencyLevel determineConsistency(Map<Value, Set<ClusterNode>> versionNodeSetMap,\n int replicationFactor) {\n boolean fullyConsistent = true;\n Value latestVersion = null;\n for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : versionNodeSetMap.entrySet()) {\n Value value = versionNodeSetEntry.getKey();\n if (latestVersion == null) {\n latestVersion = value;\n } else if (value.isTimeStampLaterThan(latestVersion)) {\n latestVersion = value;\n }\n Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue();\n fullyConsistent = fullyConsistent && (nodeSet.size() == replicationFactor);\n }\n if (fullyConsistent) {\n return ConsistencyLevel.FULL;\n } else {\n // latest write consistent, effectively consistent\n if (latestVersion != null && versionNodeSetMap.get(latestVersion).size() == replicationFactor) {\n return ConsistencyLevel.LATEST_CONSISTENT;\n }\n // all other states inconsistent\n return ConsistencyLevel.INCONSISTENT;\n }\n }",
"synchronized void stop(Integer timeout) {\n final InternalState required = this.requiredState;\n if(required != InternalState.STOPPED) {\n this.requiredState = InternalState.STOPPED;\n ROOT_LOGGER.stoppingServer(serverName);\n // Only send the stop operation if the server is started\n if (internalState == InternalState.SERVER_STARTED) {\n internalSetState(new ServerStopTask(timeout), internalState, InternalState.PROCESS_STOPPING);\n } else {\n transition(false);\n }\n }\n }"
] |
Read data for an individual task from the tables in a PEP file.
@param parent parent task
@param id task ID
@return task instance | [
"private Task readTask(ChildTaskContainer parent, Integer id)\n {\n Table a0 = getTable(\"A0TAB\");\n Table a1 = getTable(\"A1TAB\");\n Table a2 = getTable(\"A2TAB\");\n Table a3 = getTable(\"A3TAB\");\n Table a4 = getTable(\"A4TAB\");\n\n Task task = parent.addTask();\n MapRow a1Row = a1.find(id);\n MapRow a2Row = a2.find(id);\n\n setFields(A0TAB_FIELDS, a0.find(id), task);\n setFields(A1TAB_FIELDS, a1Row, task);\n setFields(A2TAB_FIELDS, a2Row, task);\n setFields(A3TAB_FIELDS, a3.find(id), task);\n setFields(A5TAB_FIELDS, a4.find(id), task);\n\n task.setStart(task.getEarlyStart());\n task.setFinish(task.getEarlyFinish());\n if (task.getName() == null)\n {\n task.setName(task.getText(1));\n }\n\n m_eventManager.fireTaskReadEvent(task);\n\n return task;\n }"
] | [
"void lockInterruptibly(final Integer permit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n sync.acquireInterruptibly(permit);\n }",
"@PrefMetadata(type = CmsElementViewPreference.class)\n public String getElementView() {\n\n return m_settings.getAdditionalPreference(CmsElementViewPreference.PREFERENCE_NAME, false);\n }",
"public static boolean removeDefaultCustomResponse(String pathValue, String requestType) {\n try {\n JSONObject profile = getDefaultProfile();\n String profileName = profile.getString(\"name\");\n PathValueClient client = new PathValueClient(profileName, false);\n return client.removeCustomResponse(pathValue, requestType);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"public Date getDate(String path) throws ParseException {\n return BoxDateFormat.parse(this.getValue(path).asString());\n }",
"public void updatePathOrder(int profileId, int[] pathOrder) {\n for (int i = 0; i < pathOrder.length; i++) {\n EditService.updatePathTable(Constants.PATH_PROFILE_PATH_ORDER, (i + 1), pathOrder[i]);\n }\n }",
"@Subscribe\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n long millis = e.getExecutionTime();\n String suiteName = e.getDescription().getDisplayName();\n \n List<Long> values = hints.get(suiteName);\n if (values == null) {\n hints.put(suiteName, values = new ArrayList<>());\n }\n values.add(millis);\n while (values.size() > historyLength)\n values.remove(0);\n }",
"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 int getSegmentForX(int x) {\n if (autoScroll.get()) {\n int playHead = (x - (getWidth() / 2));\n int offset = Util.timeToHalfFrame(getFurthestPlaybackPosition()) / scale.get();\n return (playHead + offset) * scale.get();\n }\n return x * scale.get();\n }",
"public int getLeadingBitCount(boolean network) {\n\t\tint count = getDivisionCount();\n\t\tif(count == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tlong front = network ? getDivision(0).getMaxValue() : 0;\n\t\tint prefixLen = 0;\n\t\tfor(int i = 0; i < count; i++) {\n\t\t\tIPAddressDivision seg = getDivision(i);\n\t\t\tlong value = seg.getDivisionValue();\n\t\t\tif(value != front) {\n\t\t\t\treturn prefixLen + seg.getLeadingBitCount(network);\n\t\t\t}\n\t\t\tprefixLen += seg.getBitCount();\n\t\t}\n\t\treturn prefixLen;\n\t}"
] |
Wait for exclusive permit during a timeout in milliseconds.
@return number of acquired permits if > 0 | [
"private int tryAcquireExclusiveTransaction(@NotNull final Thread thread, final int timeout) {\n long nanos = TimeUnit.MILLISECONDS.toNanos(timeout);\n try (CriticalSection ignored = criticalSection.enter()) {\n if (getThreadPermits(thread) > 0) {\n throw new ExodusException(\"Exclusive transaction can't be nested\");\n }\n final Condition condition = criticalSection.newCondition();\n final long currentOrder = acquireOrder++;\n regularQueue.put(currentOrder, condition);\n while (acquiredPermits > 0 || regularQueue.firstKey() != currentOrder) {\n try {\n nanos = condition.awaitNanos(nanos);\n if (nanos < 0) {\n break;\n }\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n break;\n }\n }\n if (acquiredPermits == 0 && regularQueue.firstKey() == currentOrder) {\n regularQueue.pollFirstEntry();\n acquiredPermits = availablePermits;\n threadPermits.put(thread, availablePermits);\n return availablePermits;\n }\n regularQueue.remove(currentOrder);\n notifyNextWaiters();\n }\n return 0;\n }"
] | [
"public void setDividerPadding(float padding, final Axis axis) {\n if (axis == getOrientationAxis()) {\n super.setDividerPadding(padding, axis);\n } else {\n Log.w(TAG, \"Cannot apply divider padding for wrong axis [%s], orientation = %s\",\n axis, getOrientation());\n }\n }",
"public static aaagroup_vpntrafficpolicy_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_vpntrafficpolicy_binding obj = new aaagroup_vpntrafficpolicy_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_vpntrafficpolicy_binding response[] = (aaagroup_vpntrafficpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"@Override\n protected void stopInner() throws VoldemortException {\n List<VoldemortException> exceptions = new ArrayList<VoldemortException>();\n\n logger.info(\"Stopping services:\" + getIdentityNode().getId());\n /* Stop in reverse order */\n exceptions.addAll(stopOnlineServices());\n for(VoldemortService service: Utils.reversed(basicServices)) {\n try {\n service.stop();\n } catch(VoldemortException e) {\n exceptions.add(e);\n logger.error(e);\n }\n }\n logger.info(\"All services stopped for Node:\" + getIdentityNode().getId());\n\n if(exceptions.size() > 0)\n throw exceptions.get(0);\n // release lock of jvm heap\n JNAUtils.tryMunlockall();\n }",
"private int getFixedDataFieldSize(FieldType type)\n {\n int result = 0;\n DataType dataType = type.getDataType();\n if (dataType != null)\n {\n switch (dataType)\n {\n case DATE:\n case INTEGER:\n case DURATION:\n {\n result = 4;\n break;\n }\n\n case TIME_UNITS:\n case CONSTRAINT:\n case PRIORITY:\n case PERCENTAGE:\n case TASK_TYPE:\n case ACCRUE:\n case SHORT:\n case BOOLEAN:\n case DELAY:\n case WORKGROUP:\n case RATE_UNITS:\n case EARNED_VALUE_METHOD:\n case RESOURCE_REQUEST_TYPE:\n {\n result = 2;\n break;\n }\n\n case CURRENCY:\n case UNITS:\n case RATE:\n case WORK:\n {\n result = 8;\n break;\n }\n\n case WORK_UNITS:\n {\n result = 1;\n break;\n }\n\n case GUID:\n {\n result = 16;\n break;\n }\n\n default:\n {\n result = 0;\n break;\n }\n }\n }\n\n return result;\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 }",
"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 startTrack(final Object... args){\r\n if(isClosed){ return; }\r\n //--Create Record\r\n final int len = args.length == 0 ? 0 : args.length-1;\r\n final Object content = args.length == 0 ? \"\" : args[len];\r\n final Object[] tags = new Object[len];\r\n final StackTraceElement ste = getStackTrace();\r\n final long timestamp = System.currentTimeMillis();\r\n System.arraycopy(args,0,tags,0,len);\r\n //--Create Task\r\n final long threadID = Thread.currentThread().getId();\r\n final Runnable startTrack = new Runnable(){\r\n public void run(){\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n Record toPass = new Record(content,tags,depth,ste,timestamp);\r\n depth += 1;\r\n titleStack.push(args.length == 0 ? \"\" : args[len].toString());\r\n handlers.process(toPass, MessageType.START_TRACK, depth, toPass.timesstamp);\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n }\r\n };\r\n //--Run Task\r\n if(isThreaded){\r\n //(case: multithreaded)\r\n long threadId = Thread.currentThread().getId();\r\n attemptThreadControl( threadId, startTrack );\r\n } else {\r\n //(case: no threading)\r\n startTrack.run();\r\n }\r\n }",
"private RowKeyAndTuple createAndPutAssociationRowForInsert(Serializable key, PersistentCollection collection,\n\t\t\tAssociationPersister associationPersister, SharedSessionContractImplementor session, int i, Object entry) {\n\t\tRowKeyBuilder rowKeyBuilder = initializeRowKeyBuilder();\n\t\tTuple associationRow = new Tuple();\n\n\t\t// the collection has a surrogate key (see @CollectionId)\n\t\tif ( hasIdentifier ) {\n\t\t\tfinal Object identifier = collection.getIdentifier( entry, i );\n\t\t\tString[] names = { getIdentifierColumnName() };\n\t\t\tidentifierGridType.nullSafeSet( associationRow, identifier, names, session );\n\t\t}\n\n\t\tgetKeyGridType().nullSafeSet( associationRow, key, getKeyColumnNames(), session );\n\t\t// No need to write to where as we don't do where clauses in OGM :)\n\t\tif ( hasIndex ) {\n\t\t\tObject index = collection.getIndex( entry, i, this );\n\t\t\tindexGridType.nullSafeSet( associationRow, incrementIndexByBase( index ), getIndexColumnNames(), session );\n\t\t}\n\n\t\t// columns of referenced key\n\t\tfinal Object element = collection.getElement( entry );\n\t\tgetElementGridType().nullSafeSet( associationRow, element, getElementColumnNames(), session );\n\n\t\tRowKeyAndTuple result = new RowKeyAndTuple();\n\t\tresult.key = rowKeyBuilder.values( associationRow ).build();\n\t\tresult.tuple = associationRow;\n\n\t\tassociationPersister.getAssociation().put( result.key, result.tuple );\n\n\t\treturn result;\n\t}",
"public static String md5sum(InputStream input) throws IOException {\r\n InputStream in = new BufferedInputStream(input);\r\n try {\r\n MessageDigest digest = java.security.MessageDigest.getInstance(\"MD5\");\r\n DigestInputStream digestInputStream = new DigestInputStream(in, digest);\r\n while(digestInputStream.read() >= 0) {\r\n }\r\n OutputStream md5out = new ByteArrayOutputStream();\r\n md5out.write(digest.digest());\r\n return md5out.toString();\r\n }\r\n catch(NoSuchAlgorithmException e) {\r\n throw new IllegalStateException(\"MD5 algorithm is not available: \" + e.getMessage());\r\n }\r\n finally {\r\n in.close();\r\n }\r\n }"
] |
This method takes an array of data and uses this to populate the
field map.
@param defaultData field map default data | [
"private void populateDefaultData(FieldItem[] defaultData)\n {\n for (FieldItem item : defaultData)\n {\n m_map.put(item.getType(), item);\n }\n }"
] | [
"public static int[] binaryToRgb(boolean[] binaryArray) {\n int[] rgbArray = new int[binaryArray.length];\n\n for (int i = 0; i < binaryArray.length; i++) {\n if (binaryArray[i]) {\n rgbArray[i] = 0x00000000;\n } else {\n rgbArray[i] = 0x00FFFFFF;\n }\n }\n return rgbArray;\n }",
"public List<Integer> getPathOrder(int profileId) {\n ArrayList<Integer> pathOrder = new ArrayList<Integer>();\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \"\n + Constants.DB_TABLE_PATH + \" WHERE \"\n + Constants.GENERIC_PROFILE_ID + \" = ? \"\n + \" ORDER BY \" + Constants.PATH_PROFILE_PATH_ORDER + \" ASC\"\n );\n queryStatement.setInt(1, profileId);\n results = queryStatement.executeQuery();\n while (results.next()) {\n pathOrder.add(results.getInt(Constants.GENERIC_ID));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n logger.info(\"pathOrder = {}\", pathOrder);\n return pathOrder;\n }",
"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 }",
"private ProjectFile handleDirectory(File directory) throws Exception\n {\n ProjectFile result = handleDatabaseInDirectory(directory);\n if (result == null)\n {\n result = handleFileInDirectory(directory);\n }\n return result;\n }",
"private static int[] getMode2PrimaryCodewords(String postcode, int country, int service) {\r\n\r\n for (int i = 0; i < postcode.length(); i++) {\r\n if (postcode.charAt(i) < '0' || postcode.charAt(i) > '9') {\r\n postcode = postcode.substring(0, i);\r\n break;\r\n }\r\n }\r\n\r\n int postcodeNum = Integer.parseInt(postcode);\r\n\r\n int[] primary = new int[10];\r\n primary[0] = ((postcodeNum & 0x03) << 4) | 2;\r\n primary[1] = ((postcodeNum & 0xfc) >> 2);\r\n primary[2] = ((postcodeNum & 0x3f00) >> 8);\r\n primary[3] = ((postcodeNum & 0xfc000) >> 14);\r\n primary[4] = ((postcodeNum & 0x3f00000) >> 20);\r\n primary[5] = ((postcodeNum & 0x3c000000) >> 26) | ((postcode.length() & 0x3) << 4);\r\n primary[6] = ((postcode.length() & 0x3c) >> 2) | ((country & 0x3) << 4);\r\n primary[7] = (country & 0xfc) >> 2;\r\n primary[8] = ((country & 0x300) >> 8) | ((service & 0xf) << 2);\r\n primary[9] = ((service & 0x3f0) >> 4);\r\n\r\n return primary;\r\n }",
"private I_CmsSearchResultWrapper getSearchResults() {\n\n // The second parameter is just ignored - so it does not matter\n m_searchController.updateFromRequestParameters(pageContext.getRequest().getParameterMap(), false);\n I_CmsSearchControllerCommon common = m_searchController.getCommon();\n // Do not search for empty query, if configured\n if (common.getState().getQuery().isEmpty()\n && (!common.getConfig().getIgnoreQueryParam() && !common.getConfig().getSearchForEmptyQueryParam())) {\n return new CmsSearchResultWrapper(m_searchController, null, null, m_cms, null);\n }\n Map<String, String[]> queryParams = null;\n boolean isEditMode = CmsJspTagEditable.isEditableRequest(pageContext.getRequest());\n if (isEditMode) {\n String params = \"\";\n if (common.getConfig().getIgnoreReleaseDate()) {\n params += \"&fq=released:[* TO *]\";\n }\n if (common.getConfig().getIgnoreExpirationDate()) {\n params += \"&fq=expired:[* TO *]\";\n }\n if (!params.isEmpty()) {\n queryParams = CmsRequestUtil.createParameterMap(params.substring(1));\n }\n }\n CmsSolrQuery query = new CmsSolrQuery(null, queryParams);\n m_searchController.addQueryParts(query, m_cms);\n try {\n // use \"complicated\" constructor to allow more than 50 results -> set ignoreMaxResults to true\n // also set resource filter to allow for returning unreleased/expired resources if necessary.\n CmsSolrResultList solrResultList = m_index.search(\n m_cms,\n query.clone(), // use a clone of the query, since the search function manipulates the query (removes highlighting parts), but we want to keep the original one.\n true,\n isEditMode ? CmsResourceFilter.IGNORE_EXPIRATION : null);\n return new CmsSearchResultWrapper(m_searchController, solrResultList, query, m_cms, null);\n } catch (CmsSearchException e) {\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_TAG_SEARCH_SEARCH_FAILED_0), e);\n return new CmsSearchResultWrapper(m_searchController, null, query, m_cms, e);\n }\n }",
"public static sslfipskey[] get(nitro_service service, String fipskeyname[]) throws Exception{\n\t\tif (fipskeyname !=null && fipskeyname.length>0) {\n\t\t\tsslfipskey response[] = new sslfipskey[fipskeyname.length];\n\t\t\tsslfipskey obj[] = new sslfipskey[fipskeyname.length];\n\t\t\tfor (int i=0;i<fipskeyname.length;i++) {\n\t\t\t\tobj[i] = new sslfipskey();\n\t\t\t\tobj[i].set_fipskeyname(fipskeyname[i]);\n\t\t\t\tresponse[i] = (sslfipskey) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"@SuppressWarnings(\"unchecked\")\n public static <E> E getObject(String className) {\n if (className == null) {\n return (E) null;\n }\n try {\n return (E) Class.forName(className).newInstance();\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }",
"public Operation.Info create( char op , Variable input ) {\n switch( op ) {\n case '\\'':\n return Operation.transpose(input, managerTemp);\n\n default:\n throw new RuntimeException(\"Unknown operation \" + op);\n }\n }"
] |
add a join between two aliases
TODO BRJ : This needs refactoring, it looks kind of weird
no extents
A1 -> A2
extents on the right
A1 -> A2
A1 -> A2E0
extents on the left : copy alias on right, extents point to copies
A1 -> A2
A1E0 -> A2C0
extents on the left and right
A1 -> A2
A1 -> A2E0
A1E0 -> A2C0
A1E0 -> A2E0C0
@param left
@param leftKeys
@param right
@param rightKeys
@param outer
@param name | [
"private void addJoin(TableAlias left, Object[] leftKeys, TableAlias right, Object[] rightKeys, boolean outer,\r\n String name)\r\n {\r\n TableAlias extAlias, rightCopy;\r\n\r\n left.addJoin(new Join(left, leftKeys, right, rightKeys, outer, name));\r\n\r\n // build join between left and extents of right\r\n if (right.hasExtents())\r\n {\r\n for (int i = 0; i < right.extents.size(); i++)\r\n {\r\n extAlias = (TableAlias) right.extents.get(i);\r\n FieldDescriptor[] extKeys = getExtentFieldDescriptors(extAlias, (FieldDescriptor[]) rightKeys);\r\n\r\n left.addJoin(new Join(left, leftKeys, extAlias, extKeys, true, name));\r\n }\r\n }\r\n\r\n // we need to copy the alias on the right for each extent on the left\r\n if (left.hasExtents())\r\n {\r\n for (int i = 0; i < left.extents.size(); i++)\r\n {\r\n extAlias = (TableAlias) left.extents.get(i);\r\n FieldDescriptor[] extKeys = getExtentFieldDescriptors(extAlias, (FieldDescriptor[]) leftKeys);\r\n rightCopy = right.copy(\"C\" + i);\r\n\r\n // copies are treated like normal extents\r\n right.extents.add(rightCopy);\r\n right.extents.addAll(rightCopy.extents);\r\n\r\n addJoin(extAlias, extKeys, rightCopy, rightKeys, true, name);\r\n }\r\n }\r\n }"
] | [
"public static BoxRetentionPolicyAssignment.Info createAssignmentToFolder(BoxAPIConnection api, String policyID,\r\n String folderID) {\r\n return createAssignment(api, policyID, new JsonObject().add(\"type\", TYPE_FOLDER).add(\"id\", folderID), null);\r\n }",
"public static <T> T objectify(ObjectMapper mapper, Object source, JavaType targetType) {\n try {\n return mapper.readValue(mapper.writeValueAsBytes(source), targetType);\n } catch (RuntimeException e) {\n throw e;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"private void setVerticalScrollbar(final CmsScrollBar scrollbar, int width) {\r\n\r\n // Validate.\r\n if ((scrollbar == m_scrollbar) || (scrollbar == null)) {\r\n return;\r\n }\r\n // Detach new child.\r\n\r\n scrollbar.asWidget().removeFromParent();\r\n // Remove old child.\r\n if (m_scrollbar != null) {\r\n if (m_verticalScrollbarHandlerRegistration != null) {\r\n m_verticalScrollbarHandlerRegistration.removeHandler();\r\n m_verticalScrollbarHandlerRegistration = null;\r\n }\r\n remove(m_scrollbar);\r\n }\r\n m_scrollLayer.appendChild(scrollbar.asWidget().getElement());\r\n adopt(scrollbar.asWidget());\r\n\r\n // Logical attach.\r\n m_scrollbar = scrollbar;\r\n m_verticalScrollbarWidth = width;\r\n\r\n // Initialize the new scrollbar.\r\n m_verticalScrollbarHandlerRegistration = scrollbar.addValueChangeHandler(new ValueChangeHandler<Integer>() {\r\n\r\n public void onValueChange(ValueChangeEvent<Integer> event) {\r\n\r\n int vPos = scrollbar.getVerticalScrollPosition();\r\n int v = getVerticalScrollPosition();\r\n if (v != vPos) {\r\n setVerticalScrollPosition(vPos);\r\n }\r\n\r\n }\r\n });\r\n maybeUpdateScrollbars();\r\n }",
"protected void processAssignmentBaseline(Row row)\n {\n Integer id = row.getInteger(\"ASSN_UID\");\n ResourceAssignment assignment = m_assignmentMap.get(id);\n if (assignment != null)\n {\n int index = row.getInt(\"AB_BASE_NUM\");\n\n assignment.setBaselineStart(index, row.getDate(\"AB_BASE_START\"));\n assignment.setBaselineFinish(index, row.getDate(\"AB_BASE_FINISH\"));\n assignment.setBaselineWork(index, row.getDuration(\"AB_BASE_WORK\"));\n assignment.setBaselineCost(index, row.getCurrency(\"AB_BASE_COST\"));\n }\n }",
"public static PackageType resolve(final MavenProject project) {\n final String packaging = project.getPackaging().toLowerCase(Locale.ROOT);\n if (DEFAULT_TYPES.containsKey(packaging)) {\n return DEFAULT_TYPES.get(packaging);\n }\n return new PackageType(packaging);\n }",
"@PrefMetadata(type = CmsElementViewPreference.class)\n public String getElementView() {\n\n return m_settings.getAdditionalPreference(CmsElementViewPreference.PREFERENCE_NAME, false);\n }",
"public base_response clear_config(Boolean force, String level) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsconfig resource = new nsconfig();\n\t\tif (force)\n\t\t\tresource.set_force(force);\n\n\t\tresource.set_level(level);\n\t\toptions option = new options();\n\t\toption.set_action(\"clear\");\n\t\tresult = resource.perform_operation(this, option);\n\t\treturn result;\n\t}",
"public int tally() {\n long currentTimeMillis = clock.currentTimeMillis();\n\n // calculates time for which we remove any errors before\n final long removeTimesBeforeMillis = currentTimeMillis - windowMillis;\n\n synchronized (queue) {\n // drain out any expired timestamps but don't drain past empty\n while (!queue.isEmpty() && queue.peek() < removeTimesBeforeMillis) {\n queue.removeFirst();\n }\n return queue.size();\n }\n }",
"@RequestMapping(value = \"/profiles\", method = RequestMethod.GET)\n public String list(Model model) {\n Profile profiles = new Profile();\n model.addAttribute(\"addNewProfile\", profiles);\n model.addAttribute(\"version\", Constants.VERSION);\n logger.info(\"Loading initial page\");\n\n return \"profiles\";\n }"
] |
Update the installed identity using the modified state from the modification.
@param name the identity name
@param modification the modification
@param state the installation state
@return the installed identity | [
"@Override\n protected void updateState(final String name, final InstallationModificationImpl modification, final InstallationModificationImpl.InstallationState state) {\n final PatchableTarget.TargetInfo identityInfo = modification.getModifiedState();\n this.identity = new Identity() {\n @Override\n public String getVersion() {\n return modification.getVersion();\n }\n\n @Override\n public String getName() {\n return name;\n }\n\n @Override\n public TargetInfo loadTargetInfo() throws IOException {\n return identityInfo;\n }\n\n @Override\n public DirectoryStructure getDirectoryStructure() {\n return modification.getDirectoryStructure();\n }\n };\n\n this.allPatches = Collections.unmodifiableList(modification.getAllPatches());\n this.layers.clear();\n for (final Map.Entry<String, MutableTargetImpl> entry : state.getLayers().entrySet()) {\n final String layerName = entry.getKey();\n final MutableTargetImpl target = entry.getValue();\n putLayer(layerName, new LayerInfo(layerName, target.getModifiedState(), target.getDirectoryStructure()));\n }\n this.addOns.clear();\n for (final Map.Entry<String, MutableTargetImpl> entry : state.getAddOns().entrySet()) {\n final String addOnName = entry.getKey();\n final MutableTargetImpl target = entry.getValue();\n putAddOn(addOnName, new LayerInfo(addOnName, target.getModifiedState(), target.getDirectoryStructure()));\n }\n }"
] | [
"void register(long mjDay, int leapAdjustment) {\n if (leapAdjustment != -1 && leapAdjustment != 1) {\n throw new IllegalArgumentException(\"Leap adjustment must be -1 or 1\");\n }\n Data data = dataRef.get();\n int pos = Arrays.binarySearch(data.dates, mjDay);\n int currentAdj = pos > 0 ? data.offsets[pos] - data.offsets[pos - 1] : 0;\n if (currentAdj == leapAdjustment) {\n return; // matches previous definition\n }\n if (mjDay <= data.dates[data.dates.length - 1]) {\n throw new IllegalArgumentException(\"Date must be after the last configured leap second date\");\n }\n long[] dates = Arrays.copyOf(data.dates, data.dates.length + 1);\n int[] offsets = Arrays.copyOf(data.offsets, data.offsets.length + 1);\n long[] taiSeconds = Arrays.copyOf(data.taiSeconds, data.taiSeconds.length + 1);\n int offset = offsets[offsets.length - 2] + leapAdjustment;\n dates[dates.length - 1] = mjDay;\n offsets[offsets.length - 1] = offset;\n taiSeconds[taiSeconds.length - 1] = tai(mjDay, offset);\n Data newData = new Data(dates, offsets, taiSeconds);\n if (dataRef.compareAndSet(data, newData) == false) {\n throw new ConcurrentModificationException(\"Unable to update leap second rules as they have already been updated\");\n }\n }",
"public ProjectCalendarWeek getWorkWeek(Date date)\n {\n ProjectCalendarWeek week = null;\n if (!m_workWeeks.isEmpty())\n {\n sortWorkWeeks();\n\n int low = 0;\n int high = m_workWeeks.size() - 1;\n long targetDate = date.getTime();\n\n while (low <= high)\n {\n int mid = (low + high) >>> 1;\n ProjectCalendarWeek midVal = m_workWeeks.get(mid);\n int cmp = 0 - DateHelper.compare(midVal.getDateRange().getStart(), midVal.getDateRange().getEnd(), targetDate);\n\n if (cmp < 0)\n {\n low = mid + 1;\n }\n else\n {\n if (cmp > 0)\n {\n high = mid - 1;\n }\n else\n {\n week = midVal;\n break;\n }\n }\n }\n }\n\n if (week == null && getParent() != null)\n {\n // Check base calendar as well for a work week.\n week = getParent().getWorkWeek(date);\n }\n return (week);\n }",
"public static Interface get(nitro_service service, String id) throws Exception{\n\t\tInterface obj = new Interface();\n\t\tobj.set_id(id);\n\t\tInterface response = (Interface) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private String getInitials(String name)\n {\n String result = null;\n\n if (name != null && name.length() != 0)\n {\n StringBuilder sb = new StringBuilder();\n sb.append(name.charAt(0));\n int index = 1;\n while (true)\n {\n index = name.indexOf(' ', index);\n if (index == -1)\n {\n break;\n }\n\n ++index;\n if (index < name.length() && name.charAt(index) != ' ')\n {\n sb.append(name.charAt(index));\n }\n\n ++index;\n }\n\n result = sb.toString();\n }\n\n return result;\n }",
"public void setSchema(String schema)\n {\n if (schema.charAt(schema.length() - 1) != '.')\n {\n schema = schema + '.';\n }\n m_schema = schema;\n }",
"public static float[][] toFloat(int[][] array) {\n float[][] n = new float[array.length][array[0].length];\n for (int i = 0; i < array.length; i++) {\n for (int j = 0; j < array[0].length; j++) {\n n[i][j] = (float) array[i][j];\n }\n }\n return n;\n }",
"@SuppressWarnings(\"unchecked\")\n public HttpMethodInfo handle(HttpRequest request,\n HttpResponder responder, Map<String, String> groupValues) throws Exception {\n //TODO: Refactor group values.\n try {\n if (httpMethods.contains(request.method())) {\n //Setup args for reflection call\n Object [] args = new Object[paramsInfo.size()];\n\n int idx = 0;\n for (Map<Class<? extends Annotation>, ParameterInfo<?>> info : paramsInfo) {\n if (info.containsKey(PathParam.class)) {\n args[idx] = getPathParamValue(info, groupValues);\n }\n if (info.containsKey(QueryParam.class)) {\n args[idx] = getQueryParamValue(info, request.uri());\n }\n if (info.containsKey(HeaderParam.class)) {\n args[idx] = getHeaderParamValue(info, request);\n }\n idx++;\n }\n\n return new HttpMethodInfo(method, handler, responder, args, exceptionHandler);\n } else {\n //Found a matching resource but could not find the right HttpMethod so return 405\n throw new HandlerException(HttpResponseStatus.METHOD_NOT_ALLOWED, String.format\n (\"Problem accessing: %s. Reason: Method Not Allowed\", request.uri()));\n }\n } catch (Throwable e) {\n throw new HandlerException(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Error in executing request: %s %s\", request.method(),\n request.uri()), e);\n }\n }",
"public void saveFile(File file, String type)\n {\n if (file != null)\n {\n m_treeController.saveFile(file, type);\n }\n }",
"public static <GROUP extends Serializable> ExecutorConfig<GROUP> basicGroupable() {\n return new ExecutorConfig<GROUP>()\n .withTaskIdAdapter((TaskIdAdapter<Groupable<GROUP>, GROUP, ?>) new DefaultGroupableTaskIdAdapter<GROUP>());\n }"
] |
Converts from a bitmap to individual day flags for a weekly recurrence,
using the array of masks.
@param days bitmap
@param masks array of mask values | [
"public void setWeeklyDaysFromBitmap(Integer days, int[] masks)\n {\n if (days != null)\n {\n int value = days.intValue();\n for (Day day : Day.values())\n {\n setWeeklyDay(day, ((value & masks[day.getValue()]) != 0));\n }\n }\n }"
] | [
"protected Object getProxyFromResultSet() throws PersistenceBrokerException\r\n {\r\n // 1. get Identity of current row:\r\n Identity oid = getIdentityFromResultSet();\r\n\r\n // 2. return a Proxy instance:\r\n return getBroker().createProxy(getItemProxyClass(), oid);\r\n }",
"public Set<S> getMatchedDeclarationBinder() {\n Set<S> bindedSet = new HashSet<S>();\n for (Map.Entry<ServiceReference<S>, BinderDescriptor> e : declarationBinders.entrySet()) {\n if (e.getValue().match) {\n bindedSet.add(getDeclarationBinder(e.getKey()));\n }\n }\n return bindedSet;\n }",
"public static Iterable<BoxUser.Info> getAllEnterpriseUsers(final BoxAPIConnection api, final String filterTerm,\n final String... fields) {\n return getUsersInfoForType(api, filterTerm, null, null, fields);\n }",
"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 }",
"public AT_Row setTargetTranslator(TargetTranslator targetTranslator) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setTargetTranslator(targetTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"protected void swapColumns( int j ) {\n\n // find the column with the largest norm\n int largestIndex = j;\n double largestNorm = normsCol[j];\n for( int col = j+1; col < numCols; col++ ) {\n double n = normsCol[col];\n if( n > largestNorm ) {\n largestNorm = n;\n largestIndex = col;\n }\n }\n // swap the columns\n double []tempC = dataQR[j];\n dataQR[j] = dataQR[largestIndex];\n dataQR[largestIndex] = tempC;\n double tempN = normsCol[j];\n normsCol[j] = normsCol[largestIndex];\n normsCol[largestIndex] = tempN;\n int tempP = pivots[j];\n pivots[j] = pivots[largestIndex];\n pivots[largestIndex] = tempP;\n }",
"public TimephasedWorkContainer getBaselineWork(ResourceAssignment assignment, ProjectCalendar calendar, TimephasedWorkNormaliser normaliser, byte[] data, boolean raw)\n {\n TimephasedWorkContainer result = null;\n\n if (data != null && data.length > 0)\n {\n LinkedList<TimephasedWork> list = null;\n\n //System.out.println(ByteArrayHelper.hexdump(data, false));\n int index = 8; // 8 byte header\n int blockSize = 40;\n double previousCumulativeWorkPerformedInMinutes = 0;\n\n Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 36);\n index += blockSize;\n TimephasedWork work = null;\n\n while (index + blockSize <= data.length)\n {\n double cumulativeWorkInMinutes = (double) ((long) MPPUtility.getDouble(data, index + 20)) / 1000;\n if (!Duration.durationValueEquals(cumulativeWorkInMinutes, previousCumulativeWorkPerformedInMinutes))\n {\n //double unknownWorkThisPeriodInMinutes = ((long) MPPUtility.getDouble(data, index + 0)) / 1000;\n double normalActualWorkThisPeriodInMinutes = ((double) MPPUtility.getInt(data, index + 8)) / 10;\n double normalRemainingWorkThisPeriodInMinutes = ((double) MPPUtility.getInt(data, index + 28)) / 10;\n double workThisPeriodInMinutes = cumulativeWorkInMinutes - previousCumulativeWorkPerformedInMinutes;\n double overtimeWorkThisPeriodInMinutes = workThisPeriodInMinutes - (normalActualWorkThisPeriodInMinutes + normalRemainingWorkThisPeriodInMinutes);\n double overtimeFactor = overtimeWorkThisPeriodInMinutes / (normalActualWorkThisPeriodInMinutes + normalRemainingWorkThisPeriodInMinutes);\n\n double normalWorkPerDayInMinutes = 480;\n double overtimeWorkPerDayInMinutes = normalWorkPerDayInMinutes * overtimeFactor;\n\n work = new TimephasedWork();\n work.setFinish(MPPUtility.getTimestampFromTenths(data, index + 16));\n work.setStart(blockStartDate);\n work.setTotalAmount(Duration.getInstance(workThisPeriodInMinutes, TimeUnit.MINUTES));\n work.setAmountPerDay(Duration.getInstance(normalWorkPerDayInMinutes + overtimeWorkPerDayInMinutes, TimeUnit.MINUTES));\n\n previousCumulativeWorkPerformedInMinutes = cumulativeWorkInMinutes;\n\n if (list == null)\n {\n list = new LinkedList<TimephasedWork>();\n }\n list.add(work);\n //System.out.println(work);\n }\n blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 36);\n index += blockSize;\n }\n\n if (list != null)\n {\n if (work != null)\n {\n work.setFinish(assignment.getFinish());\n }\n result = new DefaultTimephasedWorkContainer(calendar, normaliser, list, raw);\n }\n }\n\n return result;\n }",
"private void deliverMountUpdate(SlotReference slot, boolean mounted) {\n if (mounted) {\n logger.info(\"Reporting media mounted in \" + slot);\n\n } else {\n logger.info(\"Reporting media removed from \" + slot);\n }\n for (final MountListener listener : getMountListeners()) {\n try {\n if (mounted) {\n listener.mediaMounted(slot);\n } else {\n listener.mediaUnmounted(slot);\n }\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering mount update to listener\", t);\n }\n }\n if (mounted) {\n MetadataCache.tryAutoAttaching(slot);\n }\n }",
"public static void mergeReports(File reportOverall, File... reports) {\n SessionInfoStore infoStore = new SessionInfoStore();\n ExecutionDataStore dataStore = new ExecutionDataStore();\n boolean isCurrentVersionFormat = loadSourceFiles(infoStore, dataStore, reports);\n\n try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(reportOverall))) {\n Object visitor;\n if (isCurrentVersionFormat) {\n visitor = new ExecutionDataWriter(outputStream);\n } else {\n visitor = new org.jacoco.previous.core.data.ExecutionDataWriter(outputStream);\n }\n infoStore.accept((ISessionInfoVisitor) visitor);\n dataStore.accept((IExecutionDataVisitor) visitor);\n } catch (IOException e) {\n throw new IllegalStateException(String.format(\"Unable to write overall coverage report %s\", reportOverall.getAbsolutePath()), e);\n }\n }"
] |
Returns the secret key matching the specified identifier.
@param input the input stream containing the keyring collection
@param keyId the 4 bytes identifier of the key | [
"private PGPSecretKey getSecretKey(InputStream input, String keyId) throws IOException, PGPException {\n PGPSecretKeyRingCollection keyrings = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator());\n\n Iterator rIt = keyrings.getKeyRings();\n\n while (rIt.hasNext()) {\n PGPSecretKeyRing kRing = (PGPSecretKeyRing) rIt.next();\n Iterator kIt = kRing.getSecretKeys();\n\n while (kIt.hasNext()) {\n PGPSecretKey key = (PGPSecretKey) kIt.next();\n\n if (key.isSigningKey() && String.format(\"%08x\", key.getKeyID() & 0xFFFFFFFFL).equals(keyId.toLowerCase())) {\n return key;\n }\n }\n }\n\n return null;\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 }",
"public void checkpoint(ObjectEnvelope mod) throws PersistenceBrokerException\r\n {\r\n mod.doInsert();\r\n mod.setModificationState(StateOldClean.getInstance());\r\n }",
"public static base_response add(nitro_service client, nspbr6 resource) throws Exception {\n\t\tnspbr6 addresource = new nspbr6();\n\t\taddresource.name = resource.name;\n\t\taddresource.td = resource.td;\n\t\taddresource.action = resource.action;\n\t\taddresource.srcipv6 = resource.srcipv6;\n\t\taddresource.srcipop = resource.srcipop;\n\t\taddresource.srcipv6val = resource.srcipv6val;\n\t\taddresource.srcport = resource.srcport;\n\t\taddresource.srcportop = resource.srcportop;\n\t\taddresource.srcportval = resource.srcportval;\n\t\taddresource.destipv6 = resource.destipv6;\n\t\taddresource.destipop = resource.destipop;\n\t\taddresource.destipv6val = resource.destipv6val;\n\t\taddresource.destport = resource.destport;\n\t\taddresource.destportop = resource.destportop;\n\t\taddresource.destportval = resource.destportval;\n\t\taddresource.srcmac = resource.srcmac;\n\t\taddresource.protocol = resource.protocol;\n\t\taddresource.protocolnumber = resource.protocolnumber;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.Interface = resource.Interface;\n\t\taddresource.priority = resource.priority;\n\t\taddresource.state = resource.state;\n\t\taddresource.msr = resource.msr;\n\t\taddresource.monitor = resource.monitor;\n\t\taddresource.nexthop = resource.nexthop;\n\t\taddresource.nexthopval = resource.nexthopval;\n\t\taddresource.nexthopvlan = resource.nexthopvlan;\n\t\treturn addresource.add_resource(client);\n\t}",
"static DefaultContainerDescription lookup(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadResourceOperation(new ModelNode().setEmptyList());\n op.get(ClientConstants.INCLUDE_RUNTIME).set(true);\n final ModelNode result = client.execute(op);\n if (Operations.isSuccessfulOutcome(result)) {\n final ModelNode model = Operations.readResult(result);\n final String productName = getValue(model, \"product-name\", \"WildFly\");\n final String productVersion = getValue(model, \"product-version\");\n final String releaseVersion = getValue(model, \"release-version\");\n final String launchType = getValue(model, \"launch-type\");\n return new DefaultContainerDescription(productName, productVersion, releaseVersion, launchType, \"DOMAIN\".equalsIgnoreCase(launchType));\n }\n throw new OperationExecutionException(op, result);\n }",
"public static String plus(CharSequence left, Object value) {\n return left + DefaultGroovyMethods.toString(value);\n }",
"private void processRanges(List<DateRange> ranges, ProjectCalendarDateRanges container)\n {\n if (ranges != null)\n {\n for (DateRange range : ranges)\n {\n container.addRange(range);\n }\n }\n }",
"public static Method getStaticMethod(Class<?> clazz, String methodName, Class<?>... args) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\tAssert.notNull(methodName, \"Method name must not be null\");\n\t\ttry {\n\t\t\tMethod method = clazz.getMethod(methodName, args);\n\t\t\treturn Modifier.isStatic(method.getModifiers()) ? method : null;\n\t\t}\n\t\tcatch (NoSuchMethodException ex) {\n\t\t\treturn null;\n\t\t}\n\t}",
"@Override\n public void removeCapabilityRequirement(RuntimeRequirementRegistration requirementRegistration) {\n // We don't know if this got registered as an runtime-only requirement or a hard one\n // so clean it from both maps\n writeLock.lock();\n try {\n removeRequirement(requirementRegistration, false);\n removeRequirement(requirementRegistration, true);\n } finally {\n writeLock.unlock();\n }\n }",
"public static final Date getTime(byte[] data, int offset)\n {\n int time = getShort(data, offset) / 10;\n Calendar cal = DateHelper.popCalendar(EPOCH_DATE);\n cal.set(Calendar.HOUR_OF_DAY, (time / 60));\n cal.set(Calendar.MINUTE, (time % 60));\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n DateHelper.pushCalendar(cal);\n return (cal.getTime());\n }"
] |
Returns the orthogonal U matrix.
@param U If not null then the results will be stored here. Otherwise a new matrix will be created.
@return The extracted Q matrix. | [
"@Override\n public DMatrixRMaj getU(DMatrixRMaj U , boolean transpose , boolean compact ) {\n U = handleU(U, transpose, compact,m,n,min);\n CommonOps_DDRM.setIdentity(U);\n\n for( int i = 0; i < m; i++ ) u[i] = 0;\n\n for( int j = min-1; j >= 0; j-- ) {\n u[j] = 1;\n for( int i = j+1; i < m; i++ ) {\n u[i] = UBV.get(i,j);\n }\n if( transpose )\n QrHelperFunctions_DDRM.rank1UpdateMultL(U, u, gammasU[j], j, j, m);\n else\n QrHelperFunctions_DDRM.rank1UpdateMultR(U, u, gammasU[j], j, j, m, this.b);\n }\n\n return U;\n }"
] | [
"@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 String processIndexDescriptor(Properties attributes) throws XDocletException\r\n {\r\n String name = attributes.getProperty(ATTRIBUTE_NAME);\r\n IndexDescriptorDef indexDef = _curClassDef.getIndexDescriptor(name);\r\n String attrName;\r\n \r\n if (indexDef == null)\r\n { \r\n indexDef = new IndexDescriptorDef(name);\r\n _curClassDef.addIndexDescriptor(indexDef);\r\n }\r\n\r\n if ((indexDef.getName() == null) || (indexDef.getName().length() == 0))\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.INDEX_NAME_MISSING,\r\n new String[]{_curClassDef.getName()}));\r\n }\r\n attributes.remove(ATTRIBUTE_NAME);\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n indexDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }",
"private void fireTreeStructureChanged()\n {\n // Guaranteed to return a non-null array\n Object[] listeners = m_listenerList.getListenerList();\n TreeModelEvent e = null;\n // Process the listeners last to first, notifying\n // those that are interested in this event\n for (int i = listeners.length - 2; i >= 0; i -= 2)\n {\n if (listeners[i] == TreeModelListener.class)\n {\n // Lazily create the event:\n if (e == null)\n {\n e = new TreeModelEvent(getRoot(), new Object[]\n {\n getRoot()\n }, null, null);\n }\n ((TreeModelListener) listeners[i + 1]).treeStructureChanged(e);\n }\n }\n }",
"public static void unregisterMbean(ObjectName name) {\n try {\n ManagementFactory.getPlatformMBeanServer().unregisterMBean(name);\n } catch(Exception e) {\n logger.error(\"Error unregistering mbean\", e);\n }\n }",
"protected synchronized int loadSize() throws PersistenceBrokerException\r\n {\r\n PersistenceBroker broker = getBroker();\r\n try\r\n {\r\n return broker.getCount(getQuery());\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(ex);\r\n }\r\n finally\r\n {\r\n releaseBroker(broker);\r\n }\r\n }",
"public static void endRequest() {\n final List<RequestScopedItem> result = CACHE.get();\n if (result != null) {\n CACHE.remove();\n for (final RequestScopedItem item : result) {\n item.invalidate();\n }\n }\n }",
"public void setTexCoord(String texName, String texCoordAttr, String shaderVarName)\n {\n synchronized (textures)\n {\n GVRTexture tex = textures.get(texName);\n\n if (tex != null)\n {\n tex.setTexCoord(texCoordAttr, shaderVarName);\n }\n else\n {\n throw new UnsupportedOperationException(\"Texture must be set before updating texture coordinate information\");\n }\n }\n }",
"public Map<String, MBeanOperationInfo> getOperationMetadata() {\n\n MBeanOperationInfo[] operations = mBeanInfo.getOperations();\n\n Map<String, MBeanOperationInfo> operationMap = new TreeMap<String, MBeanOperationInfo>();\n for (MBeanOperationInfo operation: operations) {\n operationMap.put(operation.getName(), operation);\n }\n return operationMap;\n }",
"public List<Release> listReleases(String appName) {\n return connection.execute(new ReleaseList(appName), apiKey);\n }"
] |
Returns the finish date for this resource assignment.
@return finish date | [
"public Date getFinish()\n {\n Date result = (Date) getCachedValue(AssignmentField.FINISH);\n if (result == null)\n {\n result = getTask().getFinish();\n }\n return result;\n }"
] | [
"public PathElement getElement(int index) {\n final List<PathElement> list = pathAddressList;\n return list.get(index);\n }",
"public void strokeRoundRectangle(Rectangle rect, Color color, float linewidth, float r) {\n\t\ttemplate.saveState();\n\t\tsetStroke(color, linewidth, null);\n\t\ttemplate.roundRectangle(origX + rect.getLeft(), origY + rect.getBottom(), rect.getWidth(), rect.getHeight(), r);\n\t\ttemplate.stroke();\n\t\ttemplate.restoreState();\n\t}",
"public List<Integer> getConnectionRetries() {\n List<Integer> items = new ArrayList<Integer>();\n for (int i = 0; i < 10; i++) {\n items.add(i);\n }\n return items;\n }",
"@Override\n public InstalledIdentity getInstalledIdentity(String productName, String productVersion) throws PatchingException {\n final String defaultIdentityName = defaultIdentity.getIdentity().getName();\n if(productName == null) {\n productName = defaultIdentityName;\n }\n\n final File productConf = new File(installedImage.getInstallationMetadata(), productName + Constants.DOT_CONF);\n final String recordedProductVersion;\n if(!productConf.exists()) {\n recordedProductVersion = null;\n } else {\n final Properties props = loadProductConf(productConf);\n recordedProductVersion = props.getProperty(Constants.CURRENT_VERSION);\n }\n\n if(defaultIdentityName.equals(productName)) {\n if(recordedProductVersion != null && !recordedProductVersion.equals(defaultIdentity.getIdentity().getVersion())) {\n // this means the patching history indicates that the current version is different from the one specified in the server's version module,\n // which could happen in case:\n // - the last applied CP didn't include the new version module or\n // - the version module version included in the last CP didn't match the version specified in the CP's metadata, or\n // - the version module was updated from a one-off, or\n // - the patching history was edited somehow\n // In any case, here I decided to rely on the patching history.\n defaultIdentity = loadIdentity(productName, recordedProductVersion);\n }\n if(productVersion != null && !defaultIdentity.getIdentity().getVersion().equals(productVersion)) {\n throw new PatchingException(PatchLogger.ROOT_LOGGER.productVersionDidNotMatchInstalled(\n productName, productVersion, defaultIdentity.getIdentity().getVersion()));\n }\n return defaultIdentity;\n }\n\n if(recordedProductVersion != null && !Constants.UNKNOWN.equals(recordedProductVersion)) {\n if(productVersion != null) {\n if (!productVersion.equals(recordedProductVersion)) {\n throw new PatchingException(PatchLogger.ROOT_LOGGER.productVersionDidNotMatchInstalled(productName, productVersion, recordedProductVersion));\n }\n } else {\n productVersion = recordedProductVersion;\n }\n }\n\n return loadIdentity(productName, productVersion);\n }",
"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 String escapeString(String value)\n {\n m_buffer.setLength(0);\n m_buffer.append('\"');\n for (int index = 0; index < value.length(); index++)\n {\n char c = value.charAt(index);\n switch (c)\n {\n case '\"':\n {\n m_buffer.append(\"\\\\\\\"\");\n break;\n }\n\n case '\\\\':\n {\n m_buffer.append(\"\\\\\\\\\");\n break;\n }\n\n case '/':\n {\n m_buffer.append(\"\\\\/\");\n break;\n }\n\n case '\\b':\n {\n m_buffer.append(\"\\\\b\");\n break;\n }\n\n case '\\f':\n {\n m_buffer.append(\"\\\\f\");\n break;\n }\n\n case '\\n':\n {\n m_buffer.append(\"\\\\n\");\n break;\n }\n\n case '\\r':\n {\n m_buffer.append(\"\\\\r\");\n break;\n }\n\n case '\\t':\n {\n m_buffer.append(\"\\\\t\");\n break;\n }\n\n default:\n {\n // Append if it's not a control character (0x00 to 0x1f)\n if (c > 0x1f)\n {\n m_buffer.append(c);\n }\n break;\n }\n }\n }\n m_buffer.append('\"');\n return m_buffer.toString();\n }",
"protected String calculateNextVersion(String fromVersion) {\n // first turn it to release version\n fromVersion = calculateReleaseVersion(fromVersion);\n String nextVersion;\n int lastDotIndex = fromVersion.lastIndexOf('.');\n try {\n if (lastDotIndex != -1) {\n // probably a major minor version e.g., 2.1.1\n String minorVersionToken = fromVersion.substring(lastDotIndex + 1);\n String nextMinorVersion;\n int lastDashIndex = minorVersionToken.lastIndexOf('-');\n if (lastDashIndex != -1) {\n // probably a minor-buildNum e.g., 2.1.1-4 (should change to 2.1.1-5)\n String buildNumber = minorVersionToken.substring(lastDashIndex + 1);\n int nextBuildNumber = Integer.parseInt(buildNumber) + 1;\n nextMinorVersion = minorVersionToken.substring(0, lastDashIndex + 1) + nextBuildNumber;\n } else {\n nextMinorVersion = Integer.parseInt(minorVersionToken) + 1 + \"\";\n }\n nextVersion = fromVersion.substring(0, lastDotIndex + 1) + nextMinorVersion;\n } else {\n // maybe it's just a major version; try to parse as an int\n int nextMajorVersion = Integer.parseInt(fromVersion) + 1;\n nextVersion = nextMajorVersion + \"\";\n }\n } catch (NumberFormatException e) {\n return fromVersion;\n }\n return nextVersion + \"-SNAPSHOT\";\n }",
"private static String wordShapeDan1(String s) {\r\n boolean digit = true;\r\n boolean upper = true;\r\n boolean lower = true;\r\n boolean mixed = true;\r\n for (int i = 0; i < s.length(); i++) {\r\n char c = s.charAt(i);\r\n if (!Character.isDigit(c)) {\r\n digit = false;\r\n }\r\n if (!Character.isLowerCase(c)) {\r\n lower = false;\r\n }\r\n if (!Character.isUpperCase(c)) {\r\n upper = false;\r\n }\r\n if ((i == 0 && !Character.isUpperCase(c)) || (i >= 1 && !Character.isLowerCase(c))) {\r\n mixed = false;\r\n }\r\n }\r\n if (digit) {\r\n return \"ALL-DIGITS\";\r\n }\r\n if (upper) {\r\n return \"ALL-UPPER\";\r\n }\r\n if (lower) {\r\n return \"ALL-LOWER\";\r\n }\r\n if (mixed) {\r\n return \"MIXED-CASE\";\r\n }\r\n return \"OTHER\";\r\n }",
"public static String changeFirstLetterToLowerCase(String word) {\n char[] letras = word.toCharArray();\n char a = letras[0];\n letras[0] = Character.toLowerCase(a);\n return new String(letras);\n }"
] |
Print the String features generated from a IN | [
"protected void printFeatures(IN wi, Collection<String> features) {\r\n if (flags.printFeatures == null || writtenNum > flags.printFeaturesUpto) {\r\n return;\r\n }\r\n try {\r\n if (cliqueWriter == null) {\r\n cliqueWriter = new PrintWriter(new FileOutputStream(\"feats\" + flags.printFeatures + \".txt\"), true);\r\n writtenNum = 0;\r\n }\r\n } catch (Exception ioe) {\r\n throw new RuntimeException(ioe);\r\n }\r\n if (writtenNum >= flags.printFeaturesUpto) {\r\n return;\r\n }\r\n if (wi instanceof CoreLabel) {\r\n cliqueWriter.print(wi.get(TextAnnotation.class) + ' ' + wi.get(PartOfSpeechAnnotation.class) + ' '\r\n + wi.get(CoreAnnotations.GoldAnswerAnnotation.class) + '\\t');\r\n } else {\r\n cliqueWriter.print(wi.get(CoreAnnotations.TextAnnotation.class)\r\n + wi.get(CoreAnnotations.GoldAnswerAnnotation.class) + '\\t');\r\n }\r\n boolean first = true;\r\n for (Object feat : features) {\r\n if (first) {\r\n first = false;\r\n } else {\r\n cliqueWriter.print(\" \");\r\n }\r\n cliqueWriter.print(feat);\r\n }\r\n cliqueWriter.println();\r\n writtenNum++;\r\n }"
] | [
"public static Map<String, IDiagramPlugin>\n getLocalPluginsRegistry(ServletContext context) {\n if (LOCAL == null) {\n LOCAL = initializeLocalPlugins(context);\n }\n return LOCAL;\n }",
"public void setFirstOccurence(int min, int max) throws ParseException {\n if (fullCondition == null) {\n if ((min < 0) || (min > max) || (max < 1)) {\n throw new ParseException(\"Illegal number {\" + min + \",\" + max + \"}\");\n }\n if (min == 0) {\n firstOptional = true;\n }\n firstMinimumOccurence = Math.max(1, min);\n firstMaximumOccurence = max;\n } else {\n throw new ParseException(\"fullCondition already generated\");\n }\n }",
"public void deleteProduct(final String name) {\n final DbProduct dbProduct = getProduct(name);\n repositoryHandler.deleteProduct(dbProduct.getName());\n }",
"public void updateProvider(final String gavc, final String provider) {\n final DbArtifact artifact = getArtifact(gavc);\n repositoryHandler.updateProvider(artifact, provider);\n }",
"public static long count(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslciphersuite_binding obj = new sslvserver_sslciphersuite_binding();\n\t\tobj.set_vservername(vservername);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tsslvserver_sslciphersuite_binding response[] = (sslvserver_sslciphersuite_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}",
"public Collection<Blog> getList() throws FlickrException {\r\n List<Blog> blogs = new ArrayList<Blog>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n\r\n Response response = transportAPI.post(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 blogsElement = response.getPayload();\r\n NodeList blogNodes = blogsElement.getElementsByTagName(\"blog\");\r\n for (int i = 0; i < blogNodes.getLength(); i++) {\r\n Element blogElement = (Element) blogNodes.item(i);\r\n Blog blog = new Blog();\r\n blog.setId(blogElement.getAttribute(\"id\"));\r\n blog.setName(blogElement.getAttribute(\"name\"));\r\n blog.setNeedPassword(\"1\".equals(blogElement.getAttribute(\"needspassword\")));\r\n blog.setUrl(blogElement.getAttribute(\"url\"));\r\n blogs.add(blog);\r\n }\r\n return blogs;\r\n }",
"@Nonnull\n\tpublic static InterfaceAnalysis analyze(@Nonnull final String code) {\n\t\tCheck.notNull(code, \"code\");\n\n\t\tfinal CompilationUnit unit = Check.notNull(SourceCodeReader.parse(code), \"compilationUnit\");\n\t\tfinal List<TypeDeclaration> types = Check.notEmpty(unit.getTypes(), \"typeDeclarations\");\n\t\tCheck.stateIsTrue(types.size() == 1, \"only one interface declaration per analysis is supported\");\n\n\t\tfinal ClassOrInterfaceDeclaration type = (ClassOrInterfaceDeclaration) types.get(0);\n\n\t\tfinal Imports imports = SourceCodeReader.findImports(unit.getImports());\n\t\tfinal Package pkg = unit.getPackage() != null ? new Package(unit.getPackage().getName().toString()) : Package.UNDEFINED;\n\t\tfinal List<Annotation> annotations = SourceCodeReader.findAnnotations(type.getAnnotations(), imports);\n\t\tfinal List<Method> methods = SourceCodeReader.findMethods(type.getMembers(), imports);\n\t\tCheck.stateIsTrue(!hasPossibleMutatingMethods(methods), \"The passed interface '%s' seems to have mutating methods\", type.getName());\n\t\tfinal List<Interface> extendsInterfaces = SourceCodeReader.findExtends(type);\n\t\tfinal String interfaceName = type.getName();\n\t\treturn new ImmutableInterfaceAnalysis(annotations, extendsInterfaces, imports.asList(), interfaceName, methods, pkg);\n\t}",
"public void fetchUninitializedAttributes() {\n for (String prefixedId : getPrefixedAttributeNames()) {\n BeanIdentifier id = getNamingScheme().deprefix(prefixedId);\n if (!beanStore.contains(id)) {\n ContextualInstance<?> instance = (ContextualInstance<?>) getAttribute(prefixedId);\n beanStore.put(id, instance);\n ContextLogger.LOG.addingDetachedContextualUnderId(instance, id);\n }\n }\n }",
"private void addGroup(List<Token> group, List<List<Token>> groups) {\n\n if(group.isEmpty()) return;\n\n // remove trailing tokens that should be ignored\n while(!group.isEmpty() && IGNORED_TRAILING_TOKENS.contains(\n group.get(group.size() - 1).getType())) {\n group.remove(group.size() - 1);\n }\n\n // if the group still has some tokens left, we'll add it to our list of groups\n if(!group.isEmpty()) {\n groups.add(group);\n }\n }"
] |
PUT and POST are identical calls except for the header specifying the method | [
"private Response sendJsonPostOrPut(OauthToken token, String url, String json,\n int connectTimeout, int readTimeout, String method) throws IOException {\n LOG.debug(\"Sending JSON \" + method + \" to URL: \" + url);\n Response response = new Response();\n\n HttpClient httpClient = createHttpClient(connectTimeout, readTimeout);\n HttpEntityEnclosingRequestBase action;\n if(\"POST\".equals(method)) {\n action = new HttpPost(url);\n } else if(\"PUT\".equals(method)) {\n action = new HttpPut(url);\n } else {\n throw new IllegalArgumentException(\"Method must be either POST or PUT\");\n }\n Long beginTime = System.currentTimeMillis();\n action.setHeader(\"Authorization\", \"Bearer\" + \" \" + token.getAccessToken());\n\n StringEntity requestBody = new StringEntity(json, ContentType.APPLICATION_JSON);\n action.setEntity(requestBody);\n try {\n HttpResponse httpResponse = httpClient.execute(action);\n\n String content = handleResponse(httpResponse, action);\n\n response.setContent(content);\n response.setResponseCode(httpResponse.getStatusLine().getStatusCode());\n Long endTime = System.currentTimeMillis();\n LOG.debug(\"POST call took: \" + (endTime - beginTime) + \"ms\");\n } finally {\n action.releaseConnection();\n }\n\n return response;\n }"
] | [
"synchronized ArrayList<CTMessageDAO> getMessages(String userId){\n final String tName = Table.INBOX_MESSAGES.getName();\n Cursor cursor;\n ArrayList<CTMessageDAO> messageDAOArrayList = new ArrayList<>();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n cursor= db.rawQuery(\"SELECT * FROM \"+tName+\" WHERE \" + USER_ID + \" = ? ORDER BY \" + KEY_CREATED_AT+ \" DESC\", new String[]{userId});\n if(cursor != null) {\n while(cursor.moveToNext()){\n CTMessageDAO ctMessageDAO = new CTMessageDAO();\n ctMessageDAO.setId(cursor.getString(cursor.getColumnIndex(_ID)));\n ctMessageDAO.setJsonData(new JSONObject(cursor.getString(cursor.getColumnIndex(KEY_DATA))));\n ctMessageDAO.setWzrkParams(new JSONObject(cursor.getString(cursor.getColumnIndex(WZRKPARAMS))));\n ctMessageDAO.setDate(cursor.getLong(cursor.getColumnIndex(KEY_CREATED_AT)));\n ctMessageDAO.setExpires(cursor.getLong(cursor.getColumnIndex(EXPIRES)));\n ctMessageDAO.setRead(cursor.getInt(cursor.getColumnIndex(IS_READ)));\n ctMessageDAO.setUserId(cursor.getString(cursor.getColumnIndex(USER_ID)));\n ctMessageDAO.setTags(cursor.getString(cursor.getColumnIndex(TAGS)));\n ctMessageDAO.setCampaignId(cursor.getString(cursor.getColumnIndex(CAMPAIGN)));\n messageDAOArrayList.add(ctMessageDAO);\n }\n cursor.close();\n }\n return messageDAOArrayList;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e);\n return null;\n } catch (JSONException e) {\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e.getMessage());\n return null;\n } finally {\n dbHelper.close();\n }\n }",
"public static boolean isVariable(ASTNode expression, String pattern) {\r\n return (expression instanceof VariableExpression && ((VariableExpression) expression).getName().matches(pattern));\r\n }",
"public static cacheselector[] get(nitro_service service, options option) throws Exception{\n\t\tcacheselector obj = new cacheselector();\n\t\tcacheselector[] response = (cacheselector[])obj.get_resources(service,option);\n\t\treturn response;\n\t}",
"public final void setValue(String value) {\n\n if ((null == value) || value.isEmpty()) {\n setDefaultValue();\n } else {\n try {\n tryToSetParsedValue(value);\n } catch (@SuppressWarnings(\"unused\") Exception e) {\n CmsDebugLog.consoleLog(\"Could not set invalid serial date value: \" + value);\n setDefaultValue();\n }\n }\n notifyOnValueChange();\n }",
"public static String readTextFile(Context context, int resourceId) {\n InputStream inputStream = context.getResources().openRawResource(\n resourceId);\n return readTextFile(inputStream);\n }",
"private void checkPrimaryKey(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) &&\r\n classDef.getPrimaryKeys().isEmpty())\r\n {\r\n LogHelper.warn(true,\r\n getClass(),\r\n \"checkPrimaryKey\",\r\n \"The class \"+classDef.getName()+\" has no primary key\");\r\n }\r\n }",
"protected StreamRequestHandlerState determineRequestHandlerState(String itemTag) {\n\n if (keyIterator.hasNext() && !fetchedEnoughForAllPartitions()) {\n return StreamRequestHandlerState.WRITING;\n } else {\n logger.info(\"Finished fetch \" + itemTag + \" for store '\" + storageEngine.getName()\n + \"' with partitions \" + partitionIds);\n progressInfoMessage(\"Fetch \" + itemTag + \" (end of scan)\");\n\n return StreamRequestHandlerState.COMPLETE;\n }\n }",
"public static aaagroup_aaauser_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_aaauser_binding obj = new aaagroup_aaauser_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_aaauser_binding response[] = (aaagroup_aaauser_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public AsciiTable setCharTranslator(CharacterTranslator charTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setCharTranslator(charTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}"
] |
Handles a complete record at a time, stores it in a form ready for
further processing.
@param record record to be processed
@return flag indicating if this is the last record in the file to be processed
@throws MPXJException | [
"private boolean processRecord(List<String> record) throws MPXJException\n {\n boolean done = false;\n\n XerRecordType type = RECORD_TYPE_MAP.get(record.get(0));\n if (type == null)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT);\n }\n\n switch (type)\n {\n case HEADER:\n {\n processHeader(record);\n break;\n }\n\n case TABLE:\n {\n m_currentTableName = record.get(1).toLowerCase();\n m_skipTable = !REQUIRED_TABLES.contains(m_currentTableName);\n if (m_skipTable)\n {\n m_currentTable = null;\n }\n else\n {\n m_currentTable = new LinkedList<Row>();\n m_tables.put(m_currentTableName, m_currentTable);\n }\n break;\n }\n\n case FIELDS:\n {\n if (m_skipTable)\n {\n m_currentFieldNames = null;\n }\n else\n {\n m_currentFieldNames = record.toArray(new String[record.size()]);\n for (int loop = 0; loop < m_currentFieldNames.length; loop++)\n {\n m_currentFieldNames[loop] = m_currentFieldNames[loop].toLowerCase();\n }\n }\n break;\n }\n\n case DATA:\n {\n if (!m_skipTable)\n {\n Map<String, Object> map = new HashMap<String, Object>();\n for (int loop = 1; loop < record.size(); loop++)\n {\n String fieldName = m_currentFieldNames[loop];\n String fieldValue = record.get(loop);\n XerFieldType fieldType = FIELD_TYPE_MAP.get(fieldName);\n if (fieldType == null)\n {\n fieldType = XerFieldType.STRING;\n }\n\n Object objectValue;\n if (fieldValue.length() == 0)\n {\n objectValue = null;\n }\n else\n {\n switch (fieldType)\n {\n case DATE:\n {\n try\n {\n objectValue = m_df.parseObject(fieldValue);\n }\n\n catch (ParseException ex)\n {\n objectValue = fieldValue;\n }\n\n break;\n }\n\n case CURRENCY:\n case DOUBLE:\n case DURATION:\n {\n try\n {\n objectValue = Double.valueOf(m_numberFormat.parse(fieldValue.trim()).doubleValue());\n }\n\n catch (ParseException ex)\n {\n objectValue = fieldValue;\n }\n break;\n }\n\n case INTEGER:\n {\n objectValue = Integer.valueOf(fieldValue.trim());\n break;\n }\n\n default:\n {\n objectValue = fieldValue;\n break;\n }\n }\n }\n\n map.put(fieldName, objectValue);\n }\n\n Row currentRow = new MapRow(map);\n m_currentTable.add(currentRow);\n\n //\n // Special case - we need to know the default currency format\n // ahead of time, so process each row as we get it so that\n // we can correctly parse currency values in later tables.\n //\n if (m_currentTableName.equals(\"currtype\"))\n {\n processCurrency(currentRow);\n }\n }\n break;\n }\n\n case END:\n {\n done = true;\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return done;\n }"
] | [
"public static TestSpecification generateSpecification(@Nonnull final TestDefinition testDefinition) {\n final TestSpecification testSpecification = new TestSpecification();\n // Sort buckets by value ascending\n final Map<String,Integer> buckets = Maps.newLinkedHashMap();\n final List<TestBucket> testDefinitionBuckets = Ordering.from(new Comparator<TestBucket>() {\n @Override\n public int compare(final TestBucket lhs, final TestBucket rhs) {\n return Ints.compare(lhs.getValue(), rhs.getValue());\n }\n }).immutableSortedCopy(testDefinition.getBuckets());\n int fallbackValue = -1;\n if(testDefinitionBuckets.size() > 0) {\n final TestBucket firstBucket = testDefinitionBuckets.get(0);\n fallbackValue = firstBucket.getValue(); // buckets are sorted, choose smallest value as the fallback value\n\n final PayloadSpecification payloadSpecification = new PayloadSpecification();\n if(firstBucket.getPayload() != null && !firstBucket.getPayload().equals(Payload.EMPTY_PAYLOAD)) {\n final PayloadType payloadType = PayloadType.payloadTypeForName(firstBucket.getPayload().fetchType());\n payloadSpecification.setType(payloadType.payloadTypeName);\n if (payloadType == PayloadType.MAP) {\n final Map<String, String> payloadSpecificationSchema = new HashMap<String, String>();\n for (Map.Entry<String, Object> entry : firstBucket.getPayload().getMap().entrySet()) {\n payloadSpecificationSchema.put(entry.getKey(), PayloadType.payloadTypeForValue(entry.getValue()).payloadTypeName);\n }\n payloadSpecification.setSchema(payloadSpecificationSchema);\n }\n testSpecification.setPayload(payloadSpecification);\n }\n\n for (int i = 0; i < testDefinitionBuckets.size(); i++) {\n final TestBucket bucket = testDefinitionBuckets.get(i);\n buckets.put(bucket.getName(), bucket.getValue());\n }\n }\n testSpecification.setBuckets(buckets);\n testSpecification.setDescription(testDefinition.getDescription());\n testSpecification.setFallbackValue(fallbackValue);\n return testSpecification;\n }",
"private void writeResource(Resource mpxj)\n {\n ResourceType xml = m_factory.createResourceType();\n m_apibo.getResource().add(xml);\n\n xml.setAutoComputeActuals(Boolean.TRUE);\n xml.setCalculateCostFromUnits(Boolean.TRUE);\n xml.setCalendarObjectId(getCalendarUniqueID(mpxj.getResourceCalendar()));\n xml.setCurrencyObjectId(DEFAULT_CURRENCY_ID);\n xml.setDefaultUnitsPerTime(Double.valueOf(1.0));\n xml.setEmailAddress(mpxj.getEmailAddress());\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setId(RESOURCE_ID_PREFIX + mpxj.getUniqueID());\n xml.setIsActive(Boolean.TRUE);\n xml.setMaxUnitsPerTime(getPercentage(mpxj.getMaxUnits()));\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setParentObjectId(mpxj.getParentID());\n xml.setResourceNotes(mpxj.getNotes());\n xml.setResourceType(getResourceType(mpxj));\n xml.getUDF().addAll(writeUDFType(FieldTypeClass.RESOURCE, mpxj));\n }",
"public static boolean isValidFqcn(String str) {\n if (isNullOrEmpty(str)) {\n return false;\n }\n final String[] parts = str.split(\"\\\\.\");\n if (parts.length < 2) {\n return false;\n }\n for (String part : parts) {\n if (!isValidJavaIdentifier(part)) {\n return false;\n }\n }\n return true;\n }",
"public String toNormalizedString(boolean keepMixed, IPv6StringOptions params) {\n\t\tif(keepMixed && fromString != null && getAddressfromString().isMixedIPv6() && !params.makeMixed()) {\n\t\t\tparams = new IPv6StringOptions(\n\t\t\t\t\tparams.base,\n\t\t\t\t\tparams.expandSegments,\n\t\t\t\t\tparams.wildcardOption,\n\t\t\t\t\tparams.wildcards,\n\t\t\t\t\tparams.segmentStrPrefix,\n\t\t\t\t\ttrue,\n\t\t\t\t\tparams.ipv4Opts,\n\t\t\t\t\tparams.compressOptions,\n\t\t\t\t\tparams.separator,\n\t\t\t\t\tparams.zoneSeparator,\n\t\t\t\t\tparams.addrLabel,\n\t\t\t\t\tparams.addrSuffix,\n\t\t\t\t\tparams.reverse,\n\t\t\t\t\tparams.splitDigits,\n\t\t\t\t\tparams.uppercase);\n\t\t}\n\t\treturn toNormalizedString(params);\n\t}",
"public void evictCache(String key) {\n H.Session sess = session();\n if (null != sess) {\n sess.evict(key);\n } else {\n app().cache().evict(key);\n }\n }",
"public static base_responses update(nitro_service client, gslbservice resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbservice updateresources[] = new gslbservice[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new gslbservice();\n\t\t\t\tupdateresources[i].servicename = resources[i].servicename;\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].publicip = resources[i].publicip;\n\t\t\t\tupdateresources[i].publicport = resources[i].publicport;\n\t\t\t\tupdateresources[i].cip = resources[i].cip;\n\t\t\t\tupdateresources[i].cipheader = resources[i].cipheader;\n\t\t\t\tupdateresources[i].sitepersistence = resources[i].sitepersistence;\n\t\t\t\tupdateresources[i].siteprefix = resources[i].siteprefix;\n\t\t\t\tupdateresources[i].maxclient = resources[i].maxclient;\n\t\t\t\tupdateresources[i].healthmonitor = resources[i].healthmonitor;\n\t\t\t\tupdateresources[i].maxbandwidth = resources[i].maxbandwidth;\n\t\t\t\tupdateresources[i].downstateflush = resources[i].downstateflush;\n\t\t\t\tupdateresources[i].maxaaausers = resources[i].maxaaausers;\n\t\t\t\tupdateresources[i].viewname = resources[i].viewname;\n\t\t\t\tupdateresources[i].viewip = resources[i].viewip;\n\t\t\t\tupdateresources[i].monthreshold = resources[i].monthreshold;\n\t\t\t\tupdateresources[i].weight = resources[i].weight;\n\t\t\t\tupdateresources[i].monitor_name_svc = resources[i].monitor_name_svc;\n\t\t\t\tupdateresources[i].hashid = resources[i].hashid;\n\t\t\t\tupdateresources[i].comment = resources[i].comment;\n\t\t\t\tupdateresources[i].appflowlog = resources[i].appflowlog;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"@Override\n public void run() {\n for (Map.Entry<String, TestSuiteResult> entry : testSuites) {\n for (TestCaseResult testCase : entry.getValue().getTestCases()) {\n markTestcaseAsInterruptedIfNotFinishedYet(testCase);\n }\n entry.getValue().getTestCases().add(createFakeTestcaseWithWarning(entry.getValue()));\n\n Allure.LIFECYCLE.fire(new TestSuiteFinishedEvent(entry.getKey()));\n }\n }",
"public void set(int numRows, int numCols, boolean rowMajor, double ...data)\n {\n reshape(numRows,numCols);\n int length = numRows*numCols;\n\n if( length > this.data.length )\n throw new IllegalArgumentException(\"The length of this matrix's data array is too small.\");\n\n if( rowMajor ) {\n System.arraycopy(data,0,this.data,0,length);\n } else {\n int index = 0;\n for( int i = 0; i < numRows; i++ ) {\n for( int j = 0; j < numCols; j++ ) {\n this.data[index++] = data[j*numRows+i];\n }\n }\n }\n }",
"private TimeUnit getFormat(int format)\n {\n TimeUnit result;\n if (format == 0xFFFF)\n {\n result = TimeUnit.HOURS;\n }\n else\n {\n result = MPPUtility.getWorkTimeUnits(format);\n }\n return result;\n }"
] |
Get a default style. If null a simple black line style will be returned.
@param geometryType the name of the geometry type (point, line, polygon) | [
"@Nonnull\n public final Style getDefaultStyle(@Nonnull final String geometryType) {\n String normalizedGeomName = GEOMETRY_NAME_ALIASES.get(geometryType.toLowerCase());\n if (normalizedGeomName == null) {\n normalizedGeomName = geometryType.toLowerCase();\n }\n Style style = this.defaultStyle.get(normalizedGeomName.toLowerCase());\n if (style == null) {\n style = this.namedStyles.get(normalizedGeomName.toLowerCase());\n }\n\n if (style == null) {\n StyleBuilder builder = new StyleBuilder();\n final Symbolizer symbolizer;\n if (isPointType(normalizedGeomName)) {\n symbolizer = builder.createPointSymbolizer();\n } else if (isLineType(normalizedGeomName)) {\n symbolizer = builder.createLineSymbolizer(Color.black, 2);\n } else if (isPolygonType(normalizedGeomName)) {\n symbolizer = builder.createPolygonSymbolizer(Color.lightGray, Color.black, 2);\n } else if (normalizedGeomName.equalsIgnoreCase(Constants.Style.Raster.NAME)) {\n symbolizer = builder.createRasterSymbolizer();\n } else if (normalizedGeomName.startsWith(Constants.Style.OverviewMap.NAME)) {\n symbolizer = createMapOverviewStyle(normalizedGeomName, builder);\n } else {\n final Style geomStyle = this.defaultStyle.get(Geometry.class.getSimpleName().toLowerCase());\n if (geomStyle != null) {\n return geomStyle;\n } else {\n symbolizer = builder.createPointSymbolizer();\n }\n }\n style = builder.createStyle(symbolizer);\n }\n return style;\n }"
] | [
"public DateTimeZone getZone(String id) {\n if (id == null) {\n return null;\n }\n\n Object obj = iZoneInfoMap.get(id);\n if (obj == null) {\n return null;\n }\n\n if (id.equals(obj)) {\n // Load zone data for the first time.\n return loadZoneData(id);\n }\n\n if (obj instanceof SoftReference<?>) {\n @SuppressWarnings(\"unchecked\")\n SoftReference<DateTimeZone> ref = (SoftReference<DateTimeZone>) obj;\n DateTimeZone tz = ref.get();\n if (tz != null) {\n return tz;\n }\n // Reference cleared; load data again.\n return loadZoneData(id);\n }\n\n // If this point is reached, mapping must link to another.\n return getZone((String) obj);\n }",
"public void convertToDense() {\n switch ( mat.getType() ) {\n case DSCC: {\n DMatrix m = new DMatrixRMaj(mat.getNumRows(), mat.getNumCols());\n ConvertDMatrixStruct.convert((DMatrix) mat, m);\n setMatrix(m);\n } break;\n case FSCC: {\n FMatrix m = new FMatrixRMaj(mat.getNumRows(), mat.getNumCols());\n ConvertFMatrixStruct.convert((FMatrix) mat, m);\n setMatrix(m);\n } break;\n case DDRM:\n case FDRM:\n case ZDRM:\n case CDRM:\n break;\n default:\n throw new RuntimeException(\"Not a sparse matrix!\");\n }\n }",
"protected Boolean getIgnoreExpirationDate() {\n\n Boolean isIgnoreExpirationDate = parseOptionalBooleanValue(m_configObject, JSON_KEY_IGNORE_EXPIRATION_DATE);\n return (null == isIgnoreExpirationDate) && (m_baseConfig != null)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getIgnoreExpirationDate())\n : isIgnoreExpirationDate;\n }",
"public static Span toSpan(Range range) {\n return new Span(toRowColumn(range.getStartKey()), range.isStartKeyInclusive(),\n toRowColumn(range.getEndKey()), range.isEndKeyInclusive());\n }",
"private void uncheckAll(CmsList<? extends I_CmsListItem> list) {\r\n\r\n for (Widget it : list) {\r\n CmsTreeItem treeItem = (CmsTreeItem)it;\r\n treeItem.getCheckBox().setChecked(false);\r\n uncheckAll(treeItem.getChildren());\r\n }\r\n }",
"public Iterable<V> sorted(Iterator<V> input) {\n ExecutorService executor = new ThreadPoolExecutor(this.numThreads,\n this.numThreads,\n 1000L,\n TimeUnit.MILLISECONDS,\n new SynchronousQueue<Runnable>(),\n new CallerRunsPolicy());\n final AtomicInteger count = new AtomicInteger(0);\n final List<File> tempFiles = Collections.synchronizedList(new ArrayList<File>());\n while(input.hasNext()) {\n final int segmentId = count.getAndIncrement();\n final long segmentStartMs = System.currentTimeMillis();\n logger.info(\"Segment \" + segmentId + \": filling sort buffer for segment...\");\n @SuppressWarnings(\"unchecked\")\n final V[] buffer = (V[]) new Object[internalSortSize];\n int segmentSizeIter = 0;\n for(; segmentSizeIter < internalSortSize && input.hasNext(); segmentSizeIter++)\n buffer[segmentSizeIter] = input.next();\n final int segmentSize = segmentSizeIter;\n logger.info(\"Segment \" + segmentId + \": sort buffer filled...adding to sort queue.\");\n\n // sort and write out asynchronously\n executor.execute(new Runnable() {\n\n public void run() {\n logger.info(\"Segment \" + segmentId + \": sorting buffer.\");\n long start = System.currentTimeMillis();\n Arrays.sort(buffer, 0, segmentSize, comparator);\n long elapsed = System.currentTimeMillis() - start;\n logger.info(\"Segment \" + segmentId + \": sort completed in \" + elapsed\n + \" ms, writing to temp file.\");\n\n // write out values to a temp file\n try {\n File tempFile = File.createTempFile(\"segment-\", \".dat\", tempDir);\n tempFile.deleteOnExit();\n tempFiles.add(tempFile);\n OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile),\n bufferSize);\n if(gzip)\n os = new GZIPOutputStream(os);\n DataOutputStream output = new DataOutputStream(os);\n for(int i = 0; i < segmentSize; i++)\n writeValue(output, buffer[i]);\n output.close();\n } catch(IOException e) {\n throw new VoldemortException(e);\n }\n long segmentElapsed = System.currentTimeMillis() - segmentStartMs;\n logger.info(\"Segment \" + segmentId + \": completed processing of segment in \"\n + segmentElapsed + \" ms.\");\n }\n });\n }\n\n // wait for all sorting to complete\n executor.shutdown();\n try {\n executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);\n // create iterator over sorted values\n return new DefaultIterable<V>(new ExternalSorterIterator(tempFiles, bufferSize\n / tempFiles.size()));\n } catch(InterruptedException e) {\n throw new RuntimeException(e);\n }\n }",
"public static InterceptionContext forConstructorInterception(InterceptionModel interceptionModel, CreationalContext<?> ctx, BeanManagerImpl manager, SlimAnnotatedType<?> type) {\n return of(interceptionModel, ctx, manager, null, type);\n }",
"public static void openFavoriteDialog(CmsFileExplorer explorer) {\n\n try {\n CmsExplorerFavoriteContext context = new CmsExplorerFavoriteContext(A_CmsUI.getCmsObject(), explorer);\n CmsFavoriteDialog dialog = new CmsFavoriteDialog(context, new CmsFavoriteDAO(A_CmsUI.getCmsObject()));\n Window window = CmsBasicDialog.prepareWindow(DialogWidth.max);\n window.setContent(dialog);\n window.setCaption(CmsVaadinUtils.getMessageText(org.opencms.ui.Messages.GUI_FAVORITES_DIALOG_TITLE_0));\n A_CmsUI.get().addWindow(window);\n window.center();\n } catch (CmsException e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n }",
"public final void notifyContentItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newContentItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for content items [0 - \"\n + (newContentItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart + newHeaderItemCount, itemCount);\n }"
] |
Turn json string into map
@param json
@return | [
"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 void postConstruct(GeoService geoService, DtoConverterService converterService) throws GeomajasException {\n\t\tif (null == layerInfo) {\n\t\t\tlayerInfo = new RasterLayerInfo();\n\t\t}\n\t\tlayerInfo.setCrs(TiledRasterLayerService.MERCATOR);\n\t\tcrs = geoService.getCrs2(TiledRasterLayerService.MERCATOR);\n\t\tlayerInfo.setTileWidth(tileSize);\n\t\tlayerInfo.setTileHeight(tileSize);\n\t\tBbox bbox = new Bbox(-TiledRasterLayerService.HALF_EQUATOR_IN_METERS,\n\t\t\t\t-TiledRasterLayerService.HALF_EQUATOR_IN_METERS, TiledRasterLayerService.EQUATOR_IN_METERS,\n\t\t\t\tTiledRasterLayerService.EQUATOR_IN_METERS);\n\t\tlayerInfo.setMaxExtent(bbox);\n\t\tmaxBounds = converterService.toInternal(bbox);\n\n\t\tresolutions = new double[maxZoomLevel + 1];\n\t\tdouble powerOfTwo = 1;\n\t\tfor (int zoomLevel = 0; zoomLevel <= maxZoomLevel; zoomLevel++) {\n\t\t\tdouble resolution = (TiledRasterLayerService.EQUATOR_IN_METERS) / (tileSize * powerOfTwo);\n\t\t\tresolutions[zoomLevel] = resolution;\n\t\t\tpowerOfTwo *= 2;\n\t\t}\n\t}",
"void killAll()\n {\n for (RjiRegistration reg : this.instancesById.values().toArray(new RjiRegistration[] {}))\n {\n reg.rji.handleInstruction(Instruction.KILL);\n }\n }",
"public void addValue(double value)\n {\n if (dataSetSize == dataSet.length)\n {\n // Increase the capacity of the array.\n int newLength = (int) (GROWTH_RATE * dataSetSize);\n double[] newDataSet = new double[newLength];\n System.arraycopy(dataSet, 0, newDataSet, 0, dataSetSize);\n dataSet = newDataSet;\n }\n dataSet[dataSetSize] = value;\n updateStatsWithNewValue(value);\n ++dataSetSize;\n }",
"public static double huntKennedyCMSFloorValue(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble swapAnnuity,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble swapMaturity,\n\t\t\tdouble payoffUnit,\n\t\t\tdouble optionStrike)\n\t{\n\t\tdouble huntKennedyCMSOptionValue = huntKennedyCMSOptionValue(forwardSwaprate, volatility, swapAnnuity, optionMaturity, swapMaturity, payoffUnit, optionStrike);\n\n\t\t// A floor is an option plus the strike (max(X,K) = max(X-K,0) + K)\n\t\treturn huntKennedyCMSOptionValue + optionStrike * payoffUnit;\n\t}",
"private FieldType findForeignFieldType(Class<?> clazz, Class<?> foreignClass, Dao<?, ?> foreignDao)\n\t\t\tthrows SQLException {\n\t\tString foreignColumnName = fieldConfig.getForeignCollectionForeignFieldName();\n\t\tfor (FieldType fieldType : foreignDao.getTableInfo().getFieldTypes()) {\n\t\t\tif (fieldType.getType() == foreignClass\n\t\t\t\t\t&& (foreignColumnName == null || fieldType.getField().getName().equals(foreignColumnName))) {\n\t\t\t\tif (!fieldType.fieldConfig.isForeign() && !fieldType.fieldConfig.isForeignAutoRefresh()) {\n\t\t\t\t\t// this may never be reached\n\t\t\t\t\tthrow new SQLException(\"Foreign collection object \" + clazz + \" for field '\" + field.getName()\n\t\t\t\t\t\t\t+ \"' contains a field of class \" + foreignClass + \" but it's not foreign\");\n\t\t\t\t}\n\t\t\t\treturn fieldType;\n\t\t\t}\n\t\t}\n\t\t// build our complex error message\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"Foreign collection class \").append(clazz.getName());\n\t\tsb.append(\" for field '\").append(field.getName()).append(\"' column-name does not contain a foreign field\");\n\t\tif (foreignColumnName != null) {\n\t\t\tsb.append(\" named '\").append(foreignColumnName).append('\\'');\n\t\t}\n\t\tsb.append(\" of class \").append(foreignClass.getName());\n\t\tthrow new SQLException(sb.toString());\n\t}",
"public static void acceptsPartition(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_P, OPT_PARTITION), \"partition id list\")\n .withRequiredArg()\n .describedAs(\"partition-id-list\")\n .withValuesSeparatedBy(',')\n .ofType(Integer.class);\n }",
"private void deliverDatabaseUpdate(SlotReference slot, Database database, boolean available) {\n for (final DatabaseListener listener : getDatabaseListeners()) {\n try {\n if (available) {\n listener.databaseMounted(slot, database);\n } else {\n listener.databaseUnmounted(slot, database);\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering rekordbox database availability update to listener\", t);\n }\n }\n }",
"public void process(Resource resource, int index, byte[] data)\n {\n CostRateTable result = new CostRateTable();\n\n if (data != null)\n {\n for (int i = 16; i + 44 <= data.length; i += 44)\n {\n Rate standardRate = new Rate(MPPUtility.getDouble(data, i), TimeUnit.HOURS);\n TimeUnit standardRateFormat = getFormat(MPPUtility.getShort(data, i + 8));\n Rate overtimeRate = new Rate(MPPUtility.getDouble(data, i + 16), TimeUnit.HOURS);\n TimeUnit overtimeRateFormat = getFormat(MPPUtility.getShort(data, i + 24));\n Double costPerUse = NumberHelper.getDouble(MPPUtility.getDouble(data, i + 32) / 100.0);\n Date endDate = MPPUtility.getTimestampFromTenths(data, i + 40);\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate);\n result.add(entry);\n }\n Collections.sort(result);\n }\n else\n {\n //\n // MS Project economises by not actually storing the first cost rate\n // table if it doesn't need to, so we take this into account here.\n //\n if (index == 0)\n {\n Rate standardRate = resource.getStandardRate();\n Rate overtimeRate = resource.getOvertimeRate();\n Number costPerUse = resource.getCostPerUse();\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRate.getUnits(), overtimeRate, overtimeRate.getUnits(), costPerUse, CostRateTableEntry.DEFAULT_ENTRY.getEndDate());\n result.add(entry);\n }\n else\n {\n result.add(CostRateTableEntry.DEFAULT_ENTRY);\n }\n }\n\n resource.setCostRateTable(index, result);\n }",
"private static Dimension adaptTileDimensions(\n final Dimension pixels, final int maxWidth, final int maxHeight) {\n return new Dimension(adaptTileDimension(pixels.width, maxWidth),\n adaptTileDimension(pixels.height, maxHeight));\n }"
] |
Create a ModelNode representing the JVM the instance is running on.
@return a ModelNode representing the JVM the instance is running on.
@throws OperationFailedException | [
"private ModelNode createJVMNode() throws OperationFailedException {\n ModelNode jvm = new ModelNode().setEmptyObject();\n jvm.get(NAME).set(getProperty(\"java.vm.name\"));\n jvm.get(JAVA_VERSION).set(getProperty(\"java.vm.specification.version\"));\n jvm.get(JVM_VERSION).set(getProperty(\"java.version\"));\n jvm.get(JVM_VENDOR).set(getProperty(\"java.vm.vendor\"));\n jvm.get(JVM_HOME).set(getProperty(\"java.home\"));\n return jvm;\n }"
] | [
"public static base_responses flush(nitro_service client, cachecontentgroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcachecontentgroup flushresources[] = new cachecontentgroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tflushresources[i] = new cachecontentgroup();\n\t\t\t\tflushresources[i].name = resources[i].name;\n\t\t\t\tflushresources[i].query = resources[i].query;\n\t\t\t\tflushresources[i].host = resources[i].host;\n\t\t\t\tflushresources[i].selectorvalue = resources[i].selectorvalue;\n\t\t\t\tflushresources[i].force = resources[i].force;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, flushresources,\"flush\");\n\t\t}\n\t\treturn result;\n\t}",
"public String getBaselineDurationText()\n {\n Object result = getCachedValue(TaskField.BASELINE_DURATION);\n if (result == null)\n {\n result = getCachedValue(TaskField.BASELINE_ESTIMATED_DURATION);\n }\n\n if (!(result instanceof String))\n {\n result = null;\n }\n return (String) result;\n }",
"private void retrieveNextPage() {\n if (this.pageSize < Long.MAX_VALUE || this.itemLimit < Long.MAX_VALUE) {\n this.request.query(\"limit\", Math.min(this.pageSize, this.itemLimit - this.count));\n } else {\n this.request.query(\"limit\", null);\n }\n ResultBodyCollection<T> page = null;\n try {\n page = this.getNext();\n } catch (IOException exception) {\n // See comments in hasNext().\n this.ioException = exception;\n }\n if (page != null) {\n this.continuation = this.getContinuation(page);\n if (page.data != null && !page.data.isEmpty()) {\n this.count += page.data.size();\n this.nextData = page.data;\n } else {\n this.nextData = null;\n }\n } else {\n this.continuation = null;\n this.nextData = null;\n }\n }",
"public void resetResendCount() {\n\t\tthis.resendCount = 0;\n\t\tif (this.initializationComplete)\n\t\t\tthis.nodeStage = NodeStage.NODEBUILDINFO_DONE;\n\t\tthis.lastUpdated = Calendar.getInstance().getTime();\n\t}",
"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 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 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 }",
"public void combine(CRFClassifier<IN> crf, double weight) {\r\n Timing timer = new Timing();\r\n\r\n // Check the CRFClassifiers are compatible\r\n if (!this.pad.equals(crf.pad)) {\r\n throw new RuntimeException(\"Incompatible CRFClassifier: pad does not match\");\r\n }\r\n if (this.windowSize != crf.windowSize) {\r\n throw new RuntimeException(\"Incompatible CRFClassifier: windowSize does not match\");\r\n }\r\n if (this.labelIndices.length != crf.labelIndices.length) {\r\n // Should match since this should be same as the windowSize\r\n throw new RuntimeException(\"Incompatible CRFClassifier: labelIndices length does not match\");\r\n }\r\n this.classIndex.addAll(crf.classIndex.objectsList());\r\n\r\n // Combine weights of the other classifier with this classifier,\r\n // weighing the other classifier's weights by weight\r\n // First merge the feature indicies\r\n int oldNumFeatures1 = this.featureIndex.size();\r\n int oldNumFeatures2 = crf.featureIndex.size();\r\n int oldNumWeights1 = this.getNumWeights();\r\n int oldNumWeights2 = crf.getNumWeights();\r\n this.featureIndex.addAll(crf.featureIndex.objectsList());\r\n this.knownLCWords.addAll(crf.knownLCWords);\r\n assert (weights.length == oldNumFeatures1);\r\n\r\n // Combine weights of this classifier with other classifier\r\n for (int i = 0; i < labelIndices.length; i++) {\r\n this.labelIndices[i].addAll(crf.labelIndices[i].objectsList());\r\n }\r\n System.err.println(\"Combining weights: will automatically match labelIndices\");\r\n combineWeights(crf, weight);\r\n\r\n int numFeatures = featureIndex.size();\r\n int numWeights = getNumWeights();\r\n long elapsedMs = timer.stop();\r\n System.err.println(\"numFeatures: orig1=\" + oldNumFeatures1 + \", orig2=\" + oldNumFeatures2 + \", combined=\"\r\n + numFeatures);\r\n System.err\r\n .println(\"numWeights: orig1=\" + oldNumWeights1 + \", orig2=\" + oldNumWeights2 + \", combined=\" + numWeights);\r\n System.err.println(\"Time to combine CRFClassifier: \" + Timing.toSecondsString(elapsedMs) + \" seconds\");\r\n }",
"public IPv4AddressSection getEmbeddedIPv4AddressSection(int startIndex, int endIndex) {\n\t\tif(startIndex == ((IPv6Address.MIXED_ORIGINAL_SEGMENT_COUNT - this.addressSegmentIndex) << 1) && endIndex == (getSegmentCount() << 1)) {\n\t\t\treturn getEmbeddedIPv4AddressSection();\n\t\t}\n\t\tIPv4AddressCreator creator = getIPv4Network().getAddressCreator();\n\t\tIPv4AddressSegment[] segments = creator.createSegmentArray((endIndex - startIndex) >> 1);\n\t\tint i = startIndex, j = 0;\n\t\tif(i % IPv6Address.BYTES_PER_SEGMENT == 1) {\n\t\t\tIPv6AddressSegment ipv6Segment = getSegment(i >> 1);\n\t\t\ti++;\n\t\t\tipv6Segment.getSplitSegments(segments, j - 1, creator);\n\t\t\tj++;\n\t\t}\n\t\tfor(; i < endIndex; i <<= 1, j <<= 1) {\n\t\t\tIPv6AddressSegment ipv6Segment = getSegment(i >> 1);\n\t\t\tipv6Segment.getSplitSegments(segments, j, creator);\n\t\t}\n\t\treturn createEmbeddedSection(creator, segments, this);\n\t}"
] |
Returns the list of nodes which match the expression xpathExpr in the String domStr.
@return the list of nodes which match the query
@throws XPathExpressionException
@throws IOException | [
"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 void createNodeMappings(MtasTokenIdFactory mtasTokenIdFactory,\n Level level, Level parentLevel) {\n MtasToken nodeToken;\n if (level.node != null && level.positionStart != null\n && level.positionEnd != null) {\n nodeToken = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n level.node, \"\");\n nodeToken.setOffset(level.offsetStart, level.offsetEnd);\n nodeToken.setRealOffset(level.realOffsetStart, level.realOffsetEnd);\n nodeToken.addPositionRange(level.positionStart, level.positionEnd);\n tokenCollection.add(nodeToken);\n if (parentLevel != null) {\n parentLevel.tokens.add(nodeToken);\n }\n // only for first mapping(?)\n for (MtasToken token : level.tokens) {\n token.setParentId(nodeToken.getId());\n }\n }\n }",
"public void setBeliefValue(String agent_name, final String belief_name,\n final Object new_value, Connector connector) {\n\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Integer>() {\n\n public IFuture<Integer> execute(IInternalAccess ia) {\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n bia.getBeliefbase().getBelief(belief_name)\n .setFact(new_value);\n return null;\n }\n }).get(new ThreadSuspendable());\n }",
"public static void validateCurrentFinalCluster(final Cluster currentCluster,\n final Cluster finalCluster) {\n validateClusterPartitionCounts(currentCluster, finalCluster);\n validateClusterNodeState(currentCluster, finalCluster);\n\n return;\n }",
"protected void copyFile(File outputDirectory,\n File sourceFile,\n String targetFileName) throws IOException\n {\n InputStream fileStream = new FileInputStream(sourceFile);\n try\n {\n copyStream(outputDirectory, fileStream, targetFileName);\n }\n finally\n {\n fileStream.close();\n }\n }",
"protected void prepareForwardedResponseHeaders(ResponseData response) {\n HttpHeaders headers = response.getHeaders();\n headers.remove(TRANSFER_ENCODING);\n headers.remove(CONNECTION);\n headers.remove(\"Public-Key-Pins\");\n headers.remove(SERVER);\n headers.remove(\"Strict-Transport-Security\");\n }",
"public static SVGGraphics2D createSvgGraphics(final Dimension size)\n throws ParserConfigurationException {\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n DocumentBuilder db = dbf.newDocumentBuilder();\n Document document = db.getDOMImplementation().createDocument(null, \"svg\", null);\n\n SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);\n ctx.setStyleHandler(new OpacityAdjustingStyleHandler());\n ctx.setComment(\"Generated by GeoTools2 with Batik SVG Generator\");\n\n SVGGraphics2D g2d = new SVGGraphics2D(ctx, true);\n g2d.setSVGCanvasSize(size);\n\n return g2d;\n }",
"public static String[] sortStringArray(String[] array) {\n if (isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }",
"public void beforeCompletion()\r\n {\r\n // avoid redundant calls\r\n if(beforeCompletionCall) return;\r\n\r\n log.info(\"Method beforeCompletion was called\");\r\n int status = Status.STATUS_UNKNOWN;\r\n try\r\n {\r\n JTATxManager mgr = (JTATxManager) getImplementation().getTxManager();\r\n status = mgr.getJTATransaction().getStatus();\r\n // ensure proper work, check all possible status\r\n // normally only check for 'STATUS_MARKED_ROLLBACK' is necessary\r\n if(status == Status.STATUS_MARKED_ROLLBACK\r\n || status == Status.STATUS_ROLLEDBACK\r\n || status == Status.STATUS_ROLLING_BACK\r\n || status == Status.STATUS_UNKNOWN\r\n || status == Status.STATUS_NO_TRANSACTION)\r\n {\r\n log.error(\"Synchronization#beforeCompletion: Can't prepare for commit, because tx status was \"\r\n + TxUtil.getStatusString(status) + \". Do internal cleanup only.\");\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Synchronization#beforeCompletion: Prepare for commit\");\r\n }\r\n // write objects to database\r\n prepareCommit();\r\n }\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Synchronization#beforeCompletion: Error while prepare for commit\", e);\r\n if(e instanceof LockNotGrantedException)\r\n {\r\n throw (LockNotGrantedException) e;\r\n }\r\n else if(e instanceof TransactionAbortedException)\r\n {\r\n throw (TransactionAbortedException) e;\r\n }\r\n else if(e instanceof ODMGRuntimeException)\r\n {\r\n throw (ODMGRuntimeException) e;\r\n }\r\n else\r\n { \r\n throw new ODMGRuntimeException(\"Method beforeCompletion() fails, status of JTA-tx was \"\r\n + TxUtil.getStatusString(status) + \", message: \" + e.getMessage());\r\n }\r\n\r\n }\r\n finally\r\n {\r\n beforeCompletionCall = true;\r\n setInExternTransaction(false);\r\n internalCleanup();\r\n }\r\n }",
"private boolean contains(ArrayList defs, DefBase obj)\r\n {\r\n for (Iterator it = defs.iterator(); it.hasNext();)\r\n {\r\n if (obj.getName().equals(((DefBase)it.next()).getName()))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }"
] |
Use this API to fetch a tmglobal_tmsessionpolicy_binding resources. | [
"public static tmglobal_tmsessionpolicy_binding[] get(nitro_service service) throws Exception{\n\t\ttmglobal_tmsessionpolicy_binding obj = new tmglobal_tmsessionpolicy_binding();\n\t\ttmglobal_tmsessionpolicy_binding response[] = (tmglobal_tmsessionpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public void recordCheckoutTimeUs(SocketDestination dest, long checkoutTimeUs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordCheckoutTimeUs(null, checkoutTimeUs);\n recordCheckoutTimeUs(null, checkoutTimeUs);\n } else {\n this.checkoutTimeRequestCounter.addRequest(checkoutTimeUs * Time.NS_PER_US);\n }\n }",
"public double Function2D(double x, double y) {\n return Math.exp(-(x * x + y * y) / (2 * sqrSigma)) / (2 * Math.PI * sqrSigma);\n }",
"public static base_responses update(nitro_service client, nsacl6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsacl6 updateresources[] = new nsacl6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsacl6();\n\t\t\t\tupdateresources[i].acl6name = resources[i].acl6name;\n\t\t\t\tupdateresources[i].aclaction = resources[i].aclaction;\n\t\t\t\tupdateresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\tupdateresources[i].srcipop = resources[i].srcipop;\n\t\t\t\tupdateresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\tupdateresources[i].srcport = resources[i].srcport;\n\t\t\t\tupdateresources[i].srcportop = resources[i].srcportop;\n\t\t\t\tupdateresources[i].srcportval = resources[i].srcportval;\n\t\t\t\tupdateresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\tupdateresources[i].destipop = resources[i].destipop;\n\t\t\t\tupdateresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\tupdateresources[i].destport = resources[i].destport;\n\t\t\t\tupdateresources[i].destportop = resources[i].destportop;\n\t\t\t\tupdateresources[i].destportval = resources[i].destportval;\n\t\t\t\tupdateresources[i].srcmac = resources[i].srcmac;\n\t\t\t\tupdateresources[i].protocol = resources[i].protocol;\n\t\t\t\tupdateresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\tupdateresources[i].icmptype = resources[i].icmptype;\n\t\t\t\tupdateresources[i].icmpcode = resources[i].icmpcode;\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].Interface = resources[i].Interface;\n\t\t\t\tupdateresources[i].priority = resources[i].priority;\n\t\t\t\tupdateresources[i].established = resources[i].established;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public T findById(Object id) throws RowNotFoundException, TooManyRowsException {\n return findWhere(eq(idColumn.getColumnName(), id)).getSingleResult();\n }",
"public Map<String, CmsJspCategoryAccessBean> getReadAllSubCategories() {\n\n if (null == m_allSubCategories) {\n m_allSubCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n @Override\n public Object transform(Object categoryPath) {\n\n try {\n List<CmsCategory> categories = CmsCategoryService.getInstance().readCategories(\n m_cms,\n (String)categoryPath,\n true,\n m_cms.getRequestContext().getUri());\n CmsJspCategoryAccessBean result = new CmsJspCategoryAccessBean(\n m_cms,\n categories,\n (String)categoryPath);\n return result;\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n\n });\n }\n return m_allSubCategories;\n }",
"public void migrate() {\n if (databaseIsUpToDate()) {\n LOGGER.info(format(\"Keyspace %s is already up to date at version %d\", database.getKeyspaceName(),\n database.getVersion()));\n return;\n }\n\n List<DbMigration> migrations = repository.getMigrationsSinceVersion(database.getVersion());\n migrations.forEach(database::execute);\n LOGGER.info(format(\"Migrated keyspace %s to version %d\", database.getKeyspaceName(), database.getVersion()));\n database.close();\n }",
"protected void addArguments(FieldDescriptor field[])\r\n {\r\n for (int i = 0; i < field.length; i++)\r\n {\r\n ArgumentDescriptor arg = new ArgumentDescriptor(this);\r\n arg.setValue(field[i].getAttributeName(), false);\r\n this.addArgument(arg);\r\n }\r\n }",
"public int addPathnameToProfile(int id, String pathname, String actualPath) throws Exception {\n int pathOrder = getPathOrder(id).size() + 1;\n int pathId = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"INSERT INTO \" + Constants.DB_TABLE_PATH\n + \"(\" + Constants.PATH_PROFILE_PATHNAME + \",\"\n + Constants.PATH_PROFILE_ACTUAL_PATH + \",\"\n + Constants.PATH_PROFILE_GROUP_IDS + \",\"\n + Constants.PATH_PROFILE_PROFILE_ID + \",\"\n + Constants.PATH_PROFILE_PATH_ORDER + \",\"\n + Constants.PATH_PROFILE_CONTENT_TYPE + \",\"\n + Constants.PATH_PROFILE_REQUEST_TYPE + \",\"\n + Constants.PATH_PROFILE_GLOBAL + \")\"\n + \" VALUES (?, ?, ?, ?, ?, ?, ?, ?);\",\n PreparedStatement.RETURN_GENERATED_KEYS\n );\n statement.setString(1, pathname);\n statement.setString(2, actualPath);\n statement.setString(3, \"\");\n statement.setInt(4, id);\n statement.setInt(5, pathOrder);\n statement.setString(6, Constants.PATH_PROFILE_DEFAULT_CONTENT_TYPE); // should be set by UI/API\n statement.setInt(7, Constants.REQUEST_TYPE_GET); // should be set by UI/API\n statement.setBoolean(8, false);\n statement.executeUpdate();\n\n // execute statement and get resultSet which will have the generated path ID as the first field\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n pathId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add path\");\n }\n } catch (SQLException e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n // need to add to request response table for all clients\n for (Client client : ClientService.getInstance().findAllClients(id)) {\n this.addPathToRequestResponseTable(id, client.getUUID(), pathId);\n }\n\n return pathId;\n }",
"public static base_responses update(nitro_service client, nsip6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsip6 updateresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsip6();\n\t\t\t\tupdateresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\tupdateresources[i].td = resources[i].td;\n\t\t\t\tupdateresources[i].nd = resources[i].nd;\n\t\t\t\tupdateresources[i].icmp = resources[i].icmp;\n\t\t\t\tupdateresources[i].vserver = resources[i].vserver;\n\t\t\t\tupdateresources[i].telnet = resources[i].telnet;\n\t\t\t\tupdateresources[i].ftp = resources[i].ftp;\n\t\t\t\tupdateresources[i].gui = resources[i].gui;\n\t\t\t\tupdateresources[i].ssh = resources[i].ssh;\n\t\t\t\tupdateresources[i].snmp = resources[i].snmp;\n\t\t\t\tupdateresources[i].mgmtaccess = resources[i].mgmtaccess;\n\t\t\t\tupdateresources[i].restrictaccess = resources[i].restrictaccess;\n\t\t\t\tupdateresources[i].state = resources[i].state;\n\t\t\t\tupdateresources[i].map = resources[i].map;\n\t\t\t\tupdateresources[i].dynamicrouting = resources[i].dynamicrouting;\n\t\t\t\tupdateresources[i].hostroute = resources[i].hostroute;\n\t\t\t\tupdateresources[i].ip6hostrtgw = resources[i].ip6hostrtgw;\n\t\t\t\tupdateresources[i].metric = resources[i].metric;\n\t\t\t\tupdateresources[i].vserverrhilevel = resources[i].vserverrhilevel;\n\t\t\t\tupdateresources[i].ospf6lsatype = resources[i].ospf6lsatype;\n\t\t\t\tupdateresources[i].ospfarea = resources[i].ospfarea;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}"
] |
Use this API to update nd6ravariables resources. | [
"public static base_responses update(nitro_service client, nd6ravariables resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnd6ravariables updateresources[] = new nd6ravariables[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nd6ravariables();\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].ceaserouteradv = resources[i].ceaserouteradv;\n\t\t\t\tupdateresources[i].sendrouteradv = resources[i].sendrouteradv;\n\t\t\t\tupdateresources[i].srclinklayeraddroption = resources[i].srclinklayeraddroption;\n\t\t\t\tupdateresources[i].onlyunicastrtadvresponse = resources[i].onlyunicastrtadvresponse;\n\t\t\t\tupdateresources[i].managedaddrconfig = resources[i].managedaddrconfig;\n\t\t\t\tupdateresources[i].otheraddrconfig = resources[i].otheraddrconfig;\n\t\t\t\tupdateresources[i].currhoplimit = resources[i].currhoplimit;\n\t\t\t\tupdateresources[i].maxrtadvinterval = resources[i].maxrtadvinterval;\n\t\t\t\tupdateresources[i].minrtadvinterval = resources[i].minrtadvinterval;\n\t\t\t\tupdateresources[i].linkmtu = resources[i].linkmtu;\n\t\t\t\tupdateresources[i].reachabletime = resources[i].reachabletime;\n\t\t\t\tupdateresources[i].retranstime = resources[i].retranstime;\n\t\t\t\tupdateresources[i].defaultlifetime = resources[i].defaultlifetime;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"private GVRCursorController addDevice(int deviceId) {\n InputDevice device = inputManager.getInputDevice(deviceId);\n GVRControllerType controllerType = getGVRInputDeviceType(device);\n\n if (mEnabledControllerTypes == null)\n {\n return null;\n }\n if (controllerType == GVRControllerType.GAZE && !mEnabledControllerTypes.contains(GVRControllerType.GAZE))\n {\n return null;\n }\n\n int key;\n if (controllerType == GVRControllerType.GAZE) {\n // create the controller if there isn't one. \n if (gazeCursorController == null) {\n gazeCursorController = new GVRGazeCursorController(context, GVRControllerType.GAZE,\n GVRDeviceConstants.OCULUS_GEARVR_DEVICE_NAME,\n GVRDeviceConstants.OCULUS_GEARVR_TOUCHPAD_VENDOR_ID,\n GVRDeviceConstants.OCULUS_GEARVR_TOUCHPAD_PRODUCT_ID);\n }\n // use the cached gaze key\n key = GAZE_CACHED_KEY;\n } else {\n key = getCacheKey(device, controllerType);\n }\n\n if (key != -1)\n {\n GVRCursorController controller = cache.get(key);\n if (controller == null)\n {\n if ((mEnabledControllerTypes == null) || !mEnabledControllerTypes.contains(controllerType))\n {\n return null;\n }\n if (controllerType == GVRControllerType.MOUSE)\n {\n controller = mouseDeviceManager.getCursorController(context, device.getName(), device.getVendorId(), device.getProductId());\n }\n else if (controllerType == GVRControllerType.GAMEPAD)\n {\n controller = gamepadDeviceManager.getCursorController(context, device.getName(), device.getVendorId(), device.getProductId());\n }\n else if (controllerType == GVRControllerType.GAZE)\n {\n controller = gazeCursorController;\n }\n cache.put(key, controller);\n controllerIds.put(device.getId(), controller);\n return controller;\n }\n else\n {\n controllerIds.put(device.getId(), controller);\n }\n }\n return null;\n }",
"private void parseMetadataItem(Message item) {\n switch (item.getMenuItemType()) {\n case TRACK_TITLE:\n title = ((StringField) item.arguments.get(3)).getValue();\n artworkId = (int) ((NumberField) item.arguments.get(8)).getValue();\n break;\n\n case ARTIST:\n artist = buildSearchableItem(item);\n break;\n\n case ORIGINAL_ARTIST:\n originalArtist = buildSearchableItem(item);\n break;\n\n case REMIXER:\n remixer = buildSearchableItem(item);\n\n case ALBUM_TITLE:\n album = buildSearchableItem(item);\n break;\n\n case LABEL:\n label = buildSearchableItem(item);\n break;\n\n case DURATION:\n duration = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case TEMPO:\n tempo = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case COMMENT:\n comment = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case KEY:\n key = buildSearchableItem(item);\n break;\n\n case RATING:\n rating = (int) ((NumberField)item.arguments.get(1)).getValue();\n break;\n\n case COLOR_NONE:\n case COLOR_AQUA:\n case COLOR_BLUE:\n case COLOR_GREEN:\n case COLOR_ORANGE:\n case COLOR_PINK:\n case COLOR_PURPLE:\n case COLOR_RED:\n case COLOR_YELLOW:\n color = buildColorItem(item);\n break;\n\n case GENRE:\n genre = buildSearchableItem(item);\n break;\n\n case DATE_ADDED:\n dateAdded = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case YEAR:\n year = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case BIT_RATE:\n bitRate = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n default:\n logger.warn(\"Ignoring track metadata item with unknown type: {}\", item);\n }\n }",
"String getStatus(CmsUser user, boolean disabled, boolean newUser) {\n\n if (disabled) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_DISABLED_0);\n }\n if (newUser) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_INACTIVE_0);\n }\n if (OpenCms.getLoginManager().isUserTempDisabled(user.getName())) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_UNLOCK_USER_STATUS_0);\n }\n if (isUserPasswordReset(user)) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_PASSWORT_RESET_0);\n }\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_ACTIVE_0);\n }",
"public void delete() {\n URL url = STORAGE_POLICY_ASSIGNMENT_WITH_ID_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, HttpMethod.DELETE);\n\n request.send();\n }",
"public static ModelNode validateRequest(CommandContext ctx, ModelNode request) throws CommandFormatException {\n\n final Set<String> keys = request.keys();\n if (keys.size() == 2) { // no props\n return null;\n }\n ModelNode outcome = (ModelNode) ctx.get(Scope.REQUEST, DESCRIPTION_RESPONSE);\n if (outcome == null) {\n outcome = retrieveDescription(ctx, request, true);\n if (outcome == null) {\n return null;\n } else {\n ctx.set(Scope.REQUEST, DESCRIPTION_RESPONSE, outcome);\n }\n }\n if(!outcome.has(Util.RESULT)) {\n throw new CommandFormatException(\"Failed to perform \" + Util.READ_OPERATION_DESCRIPTION + \" to validate the request: result is not available.\");\n }\n\n final String operationName = request.get(Util.OPERATION).asString();\n\n final ModelNode result = outcome.get(Util.RESULT);\n final Set<String> definedProps = result.hasDefined(Util.REQUEST_PROPERTIES) ? result.get(Util.REQUEST_PROPERTIES).keys() : Collections.emptySet();\n if(definedProps.isEmpty()) {\n if(!(keys.size() == 3 && keys.contains(Util.OPERATION_HEADERS))) {\n throw new CommandFormatException(\"Operation '\" + operationName + \"' does not expect any property.\");\n }\n } else {\n int skipped = 0;\n for(String prop : keys) {\n if(skipped < 2 && (prop.equals(Util.ADDRESS) || prop.equals(Util.OPERATION))) {\n ++skipped;\n continue;\n }\n if(!definedProps.contains(prop)) {\n if(!Util.OPERATION_HEADERS.equals(prop)) {\n throw new CommandFormatException(\"'\" + prop + \"' is not found among the supported properties: \" + definedProps);\n }\n }\n }\n }\n return outcome;\n }",
"private void processGraphicalIndicators()\n {\n GraphicalIndicatorReader graphicalIndicatorReader = new GraphicalIndicatorReader();\n graphicalIndicatorReader.process(m_file.getCustomFields(), m_file.getProjectProperties(), m_projectProps);\n }",
"public static List<Integer> toIntegerList(List<String> strList, boolean failOnException){\n\t\tList<Integer> intList = new ArrayList<Integer>();\n\t\tfor(String str : strList){\n\t\t\ttry{\n\t\t\t\tintList.add(Integer.parseInt(str));\n\t\t\t}\n\t\t\tcatch(NumberFormatException nfe){\n\t\t\t\tif(failOnException){\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tintList.add(null);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn intList;\n\t}",
"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}",
"public static Method findSetMethod(Field field, DatabaseType databaseType, boolean throwExceptions)\n\t\t\tthrows IllegalArgumentException {\n\t\tMethod fieldSetMethod = findMethodFromNames(field, false, throwExceptions,\n\t\t\t\tmethodFromField(field, \"set\", databaseType, true), methodFromField(field, \"set\", databaseType, false));\n\t\tif (fieldSetMethod == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (fieldSetMethod.getReturnType() != void.class) {\n\t\t\tif (throwExceptions) {\n\t\t\t\tthrow new IllegalArgumentException(\"Return type of set method \" + fieldSetMethod.getName() + \" returns \"\n\t\t\t\t\t\t+ fieldSetMethod.getReturnType() + \" instead of void\");\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn fieldSetMethod;\n\t}"
] |
Adds each required length, ensuring it isn't negative.
@param requiredLengths
one or more required lengths
@throws IllegalArgumentException
if a supplied length is negative | [
"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}"
] | [
"public Widget addControl(String name, int resId, Widget.OnTouchListener listener) {\n return addControl(name, resId, null, listener, -1);\n }",
"public void setWorkConnection(CmsSetupDb db) {\n\n db.setConnection(\n m_setupBean.getDbDriver(),\n m_setupBean.getDbWorkConStr(),\n m_setupBean.getDbConStrParams(),\n m_setupBean.getDbWorkUser(),\n m_setupBean.getDbWorkPwd());\n }",
"public String toMixedString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.mixedString) == null) {\n\t\t\tif(hasZone()) {\n\t\t\t\tstringCache.mixedString = result = toNormalizedString(IPv6StringCache.mixedParams);\n\t\t\t} else {\n\t\t\t\tresult = getSection().toMixedString();//the cache is shared so no need to update it here\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}",
"public String getTitle(Locale locale)\n {\n String result = null;\n\n if (m_title != null)\n {\n result = m_title;\n }\n else\n {\n if (m_fieldType != null)\n {\n result = m_project.getCustomFields().getCustomField(m_fieldType).getAlias();\n if (result == null)\n {\n result = m_fieldType.getName(locale);\n }\n }\n }\n\n return (result);\n }",
"public static cacheselector[] get(nitro_service service, options option) throws Exception{\n\t\tcacheselector obj = new cacheselector();\n\t\tcacheselector[] response = (cacheselector[])obj.get_resources(service,option);\n\t\treturn response;\n\t}",
"private static void unpackFace(File outputDirectory) throws IOException {\n ClassLoader loader = AllureMain.class.getClassLoader();\n for (ClassPath.ResourceInfo info : ClassPath.from(loader).getResources()) {\n Matcher matcher = REPORT_RESOURCE_PATTERN.matcher(info.getResourceName());\n if (matcher.find()) {\n String resourcePath = matcher.group(1);\n File dest = new File(outputDirectory, resourcePath);\n Files.createParentDirs(dest);\n try (FileOutputStream output = new FileOutputStream(dest);\n InputStream input = info.url().openStream()) {\n IOUtils.copy(input, output);\n LOGGER.debug(\"{} successfully copied.\", resourcePath);\n }\n }\n }\n }",
"public List<CmsCategory> getLeafItems() {\n\n List<CmsCategory> result = new ArrayList<CmsCategory>();\n if (m_categories.isEmpty()) {\n return result;\n }\n Iterator<CmsCategory> it = m_categories.iterator();\n CmsCategory current = it.next();\n while (it.hasNext()) {\n CmsCategory next = it.next();\n if (!next.getPath().startsWith(current.getPath())) {\n result.add(current);\n }\n current = next;\n }\n result.add(current);\n return result;\n }",
"public List<Message> requestTrackMenuFrom(final SlotReference slotReference, final int sortOrder)\n throws Exception {\n\n ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {\n @Override\n public List<Message> useClient(Client client) throws Exception {\n return MetadataFinder.getInstance().getFullTrackList(slotReference.slot, client, sortOrder);\n }\n };\n\n return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, \"requesting track menu\");\n }",
"@Deprecated\n public ClientConfig setNodeBannagePeriod(int nodeBannagePeriod, TimeUnit unit) {\n this.failureDetectorBannagePeriod = unit.toMillis(nodeBannagePeriod);\n return this;\n }"
] |
Disconnects from the serial interface and stops
send and receive threads. | [
"public void disconnect() {\n\t\tif (sendThread != null) {\n\t\t\tsendThread.interrupt();\n\t\t\ttry {\n\t\t\t\tsendThread.join();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t\tsendThread = null;\n\t\t}\n\t\tif (receiveThread != null) {\n\t\t\treceiveThread.interrupt();\n\t\t\ttry {\n\t\t\t\treceiveThread.join();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t\treceiveThread = null;\n\t\t}\n\t\tif(transactionCompleted.availablePermits() < 0)\n\t\t\ttransactionCompleted.release(transactionCompleted.availablePermits());\n\t\t\n\t\ttransactionCompleted.drainPermits();\n\t\tlogger.trace(\"Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\tif (this.serialPort != null) {\n\t\t\tthis.serialPort.close();\n\t\t\tthis.serialPort = null;\n\t\t}\n\t\tlogger.info(\"Disconnected from serial port\");\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 }",
"public static Object unmarshal(String message, Class<?> childClass) {\n try {\n Class<?>[] reverseAndToArray = Iterables.toArray(Lists.reverse(getAllSuperTypes(childClass)), Class.class);\n JAXBContext jaxbCtx = JAXBContext.newInstance(reverseAndToArray);\n Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();\n\n return unmarshaller.unmarshal(new StringReader(message));\n } catch (Exception e) {\n }\n\n return null;\n }",
"public static Object newInstance(Class target, Class type, Object arg) throws InstantiationException,\r\n IllegalAccessException,\r\n IllegalArgumentException,\r\n InvocationTargetException,\r\n NoSuchMethodException,\r\n SecurityException\r\n {\r\n return newInstance(target, new Class[]{ type }, new Object[]{ arg });\r\n }",
"public static String readFileContentToString(String filePath)\n throws IOException {\n String content = \"\";\n content = Files.toString(new File(filePath), Charsets.UTF_8);\n return content;\n }",
"public static void main(String[] args) throws Exception {\n if(args.length < 1)\n Utils.croak(\"USAGE: java \" + HdfsFetcher.class.getName()\n + \" url [keytab-location kerberos-username hadoop-config-path [destDir]]\");\n String url = args[0];\n\n VoldemortConfig config = new VoldemortConfig(-1, \"\");\n\n HdfsFetcher fetcher = new HdfsFetcher(config);\n\n String destDir = null;\n Long diskQuotaSizeInKB;\n if(args.length >= 4) {\n fetcher.voldemortConfig.setReadOnlyKeytabPath(args[1]);\n fetcher.voldemortConfig.setReadOnlyKerberosUser(args[2]);\n fetcher.voldemortConfig.setHadoopConfigPath(args[3]);\n }\n if(args.length >= 5)\n destDir = args[4];\n\n if(args.length >= 6)\n diskQuotaSizeInKB = Long.parseLong(args[5]);\n else\n diskQuotaSizeInKB = null;\n\n // for testing we want to be able to download a single file\n allowFetchingOfSingleFile = true;\n\n FileSystem fs = HadoopUtils.getHadoopFileSystem(fetcher.voldemortConfig, url);\n Path p = new Path(url);\n\n FileStatus status = fs.listStatus(p)[0];\n long size = status.getLen();\n long start = System.currentTimeMillis();\n if(destDir == null)\n destDir = System.getProperty(\"java.io.tmpdir\") + File.separator + start;\n\n File location = fetcher.fetch(url, destDir, null, null, -1, null, diskQuotaSizeInKB);\n\n double rate = size * Time.MS_PER_SECOND / (double) (System.currentTimeMillis() - start);\n NumberFormat nf = NumberFormat.getInstance();\n nf.setMaximumFractionDigits(2);\n System.out.println(\"Fetch to \" + location + \" completed: \"\n + nf.format(rate / (1024.0 * 1024.0)) + \" MB/sec.\");\n fs.close();\n }",
"public boolean checkXpathStartsWithXpathEventableCondition(Document dom,\n\t\t\tEventableCondition eventableCondition, String xpath) throws XPathExpressionException {\n\t\tif (eventableCondition == null || Strings\n\t\t\t\t.isNullOrEmpty(eventableCondition.getInXPath())) {\n\t\t\tthrow new CrawljaxException(\"Eventable has no XPath condition\");\n\t\t}\n\t\tList<String> expressions =\n\t\t\t\tXPathHelper.getXpathForXPathExpressions(dom, eventableCondition.getInXPath());\n\n\t\treturn checkXPathUnderXPaths(xpath, expressions);\n\t}",
"protected void parseCombineIntegerLists(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n if( t == null || t.next == null )\n return;\n\n int numFound = 0;\n\n TokenList.Token start = null;\n TokenList.Token end = null;\n\n while( t != null ) {\n if( t.getType() == Type.VARIABLE && (isVariableInteger(t) ||\n t.getVariable().getType() == VariableType.INTEGER_SEQUENCE )) {\n if( numFound == 0 ) {\n numFound = 1;\n start = end = t;\n } else {\n numFound++;\n end = t;\n }\n } else if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n numFound = 0;\n } else {\n numFound = 0;\n }\n t = t.next;\n }\n\n if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n }\n }",
"private static ModelNode createOperation(final ModelNode operationToValidate) {\n PathAddress pa = PathAddress.pathAddress(operationToValidate.require(OP_ADDR));\n PathAddress validationAddress = pa.subAddress(0, pa.size() - 1);\n\n return Util.getEmptyOperation(\"validate-cache\", validationAddress.toModelNode());\n }",
"protected Object[] escape(final Format format, Object... args) {\n // Transformer that escapes HTML,XML,JSON strings\n Transformer<Object, Object> escapingTransformer = new Transformer<Object, Object>() {\n @Override\n public Object transform(Object object) {\n return format.escapeValue(object);\n }\n };\n List<Object> list = Arrays.asList(ArrayUtils.clone(args));\n CollectionUtils.transform(list, escapingTransformer);\n return list.toArray();\n }"
] |
Remove a variable in the top variables layer. | [
"public void removeVariable(String name)\n {\n Map<String, Iterable<? extends WindupVertexFrame>> frame = peek();\n frame.remove(name);\n }"
] | [
"public static void recursiveAddZip(File parent, ZipOutputStream zout, File fileSource)\n throws IOException {\n\n File[] files = fileSource.listFiles();\n\n for (int i = 0; i < files.length; i++) {\n if (files[i].isDirectory()) {\n recursiveAddZip(parent, zout, files[i]);\n continue;\n }\n\n byte[] buffer = new byte[1024];\n\n FileInputStream fin = new FileInputStream(files[i]);\n\n ZipEntry zipEntry =\n new ZipEntry(files[i].getAbsolutePath()\n .replace(parent.getAbsolutePath(), \"\").substring(1)); //$NON-NLS-1$\n zout.putNextEntry(zipEntry);\n\n int length;\n while ((length = fin.read(buffer)) > 0) {\n zout.write(buffer, 0, length);\n }\n\n zout.closeEntry();\n\n fin.close();\n\n }\n\n }",
"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 }",
"public static base_response delete(nitro_service client, String serverip) throws Exception {\n\t\tntpserver deleteresource = new ntpserver();\n\t\tdeleteresource.serverip = serverip;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public ProjectCalendarException addCalendarException(Date fromDate, Date toDate)\n {\n ProjectCalendarException bce = new ProjectCalendarException(fromDate, toDate);\n m_exceptions.add(bce);\n m_expandedExceptions.clear();\n m_exceptionsSorted = false;\n clearWorkingDateCache();\n return bce;\n }",
"private void toNextDate(Calendar date, int interval) {\n\n long previousDate = date.getTimeInMillis();\n if (!m_weekOfMonthIterator.hasNext()) {\n date.add(Calendar.MONTH, interval);\n m_weekOfMonthIterator = m_weeksOfMonth.iterator();\n }\n toCorrectDateWithDay(date, m_weekOfMonthIterator.next());\n if (previousDate == date.getTimeInMillis()) { // this can happen if the fourth and the last week are checked.\n toNextDate(date);\n }\n\n }",
"public static final String printFinishDateTime(Date value)\n {\n if (value != null)\n {\n value = DateHelper.addDays(value, 1);\n }\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }",
"protected DatabaseConnection getSavedConnection() {\n\t\tNestedConnection nested = specialConnection.get();\n\t\tif (nested == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn nested.connection;\n\t\t}\n\t}",
"private void deliverMasterChangedAnnouncement(final DeviceUpdate update) {\n for (final MasterListener listener : getMasterListeners()) {\n try {\n listener.masterChanged(update);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master changed announcement to listener\", t);\n }\n }\n }",
"private void setUserFieldValue(UDFAssignmentType udf, DataType dataType, Object value)\n {\n switch (dataType)\n {\n case DURATION:\n {\n udf.setTextValue(((Duration) value).toString());\n break;\n }\n\n case CURRENCY:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setCostValue((Double) value);\n break;\n }\n\n case BINARY:\n {\n udf.setTextValue(\"\");\n break;\n }\n\n case STRING:\n {\n udf.setTextValue((String) value);\n break;\n }\n\n case DATE:\n {\n udf.setStartDateValue((Date) value);\n break;\n }\n\n case NUMERIC:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setDoubleValue((Double) value);\n break;\n }\n\n case BOOLEAN:\n {\n udf.setIntegerValue(BooleanHelper.getBoolean((Boolean) value) ? Integer.valueOf(1) : Integer.valueOf(0));\n break;\n }\n\n case INTEGER:\n case SHORT:\n {\n udf.setIntegerValue(NumberHelper.getInteger((Number) value));\n break;\n }\n\n default:\n {\n throw new RuntimeException(\"Unconvertible data type: \" + dataType);\n }\n }\n }"
] |
determinates if this triangle contains the point p.
@param p the query point
@return true iff p is not null and is inside this triangle (Note: on boundary is considered inside!!). | [
"public boolean contains(Vector3 p) {\n\t\tboolean ans = false;\n\t\tif(this.halfplane || p== null) return false;\n\n\t\tif (isCorner(p)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tPointLinePosition a12 = PointLineTest.pointLineTest(a,b,p);\n\t\tPointLinePosition a23 = PointLineTest.pointLineTest(b,c,p);\n\t\tPointLinePosition a31 = PointLineTest.pointLineTest(c,a,p);\n\n\t\tif ((a12 == PointLinePosition.LEFT && a23 == PointLinePosition.LEFT && a31 == PointLinePosition.LEFT ) ||\n\t\t\t\t(a12 == PointLinePosition.RIGHT && a23 == PointLinePosition.RIGHT && a31 == PointLinePosition.RIGHT ) ||\n\t\t\t\t(a12 == PointLinePosition.ON_SEGMENT ||a23 == PointLinePosition.ON_SEGMENT || a31 == PointLinePosition.ON_SEGMENT)) {\n\t\t\tans = true;\n\t\t}\n\n\t\treturn ans;\n\t}"
] | [
"public TransformersSubRegistration getServerRegistration(final ModelVersionRange range) {\n final PathAddress address = PathAddress.EMPTY_ADDRESS.append(HOST, SERVER);\n return new TransformersSubRegistrationImpl(range, domain, address);\n }",
"public void deleteObject(Object object)\r\n {\r\n PersistenceBroker broker = null;\r\n try\r\n {\r\n broker = getBroker();\r\n broker.delete(object);\r\n }\r\n finally\r\n {\r\n if (broker != null) broker.close();\r\n }\r\n }",
"protected boolean checkForAndHandleZeros() {\n // check for zeros along off diagonal\n for( int i = x2-1; i >= x1; i-- ) {\n if( isOffZero(i) ) {\n// System.out.println(\"steps at split = \"+steps);\n resetSteps();\n splits[numSplits++] = i;\n x1 = i+1;\n return true;\n }\n }\n\n // check for zeros along diagonal\n for( int i = x2-1; i >= x1; i-- ) {\n if( isDiagonalZero(i)) {\n// System.out.println(\"steps at split = \"+steps);\n pushRight(i);\n resetSteps();\n splits[numSplits++] = i;\n x1 = i+1;\n return true;\n }\n }\n return false;\n }",
"public static final ProjectFile setProjectNameAndRead(File directory) throws MPXJException\n {\n List<String> projects = listProjectNames(directory);\n\n if (!projects.isEmpty())\n {\n P3DatabaseReader reader = new P3DatabaseReader();\n reader.setProjectName(projects.get(0));\n return reader.read(directory);\n }\n\n return null;\n }",
"public double[][] getU() {\n double[][] X = new double[n][n];\n double[][] U = X;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n if (i <= j) {\n U[i][j] = LU[i][j];\n } else {\n U[i][j] = 0.0;\n }\n }\n }\n return X;\n }",
"public static ComplexNumber Multiply(ComplexNumber z1, ComplexNumber z2) {\r\n double z1R = z1.real, z1I = z1.imaginary;\r\n double z2R = z2.real, z2I = z2.imaginary;\r\n\r\n return new ComplexNumber(z1R * z2R - z1I * z2I, z1R * z2I + z1I * z2R);\r\n }",
"public static vpnclientlessaccesspolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tvpnclientlessaccesspolicy_binding obj = new vpnclientlessaccesspolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnclientlessaccesspolicy_binding response = (vpnclientlessaccesspolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"static Shell createTelnetConsoleShell(String prompt, String appName,\n ShellCommandHandler mainHandler, InputStream input, OutputStream output) {\n try {\n // Set up nvt4j; ignore the initial clear & reposition\n final nvt4j.impl.Terminal nvt4jTerminal = new nvt4j.impl.Terminal(input, output) {\n private boolean cleared;\n private boolean moved;\n\n @Override\n public void clear() throws IOException {\n if (this.cleared)\n super.clear();\n this.cleared = true;\n }\n\n @Override\n public void move(int row, int col) throws IOException {\n if (this.moved)\n super.move(row, col);\n this.moved = true;\n }\n };\n nvt4jTerminal.put(nvt4j.impl.Terminal.AUTO_WRAP_ON);\n nvt4jTerminal.setCursor(true);\n\n // Have JLine do input & output through telnet terminal\n final InputStream jlineInput = new InputStream() {\n @Override\n public int read() throws IOException {\n return nvt4jTerminal.get();\n }\n };\n final OutputStream jlineOutput = new OutputStream() {\n @Override\n public void write(int value) throws IOException {\n nvt4jTerminal.put(value);\n }\n };\n\n return createTerminalConsoleShell(prompt, appName, mainHandler, jlineInput, jlineOutput);\n } catch (Exception e) {\n // Failover: use default shell\n BufferedReader in = new BufferedReader(new InputStreamReader(input));\n PrintStream out = new PrintStream(output);\n\n return createConsoleShell(prompt, appName, mainHandler, in, out, out, null);\n }\n }",
"public static final Bytes of(byte[] data, int offset, int length) {\n Objects.requireNonNull(data);\n if (length == 0) {\n return EMPTY;\n }\n byte[] copy = new byte[length];\n System.arraycopy(data, offset, copy, 0, length);\n return new Bytes(copy);\n }"
] |
Calculate the first argument raised to the power of the second.
This method only supports non-negative powers.
@param value The number to be raised.
@param power The exponent (must be positive).
@return {@code value} raised to {@code power}. | [
"public static long raiseToPower(int value, int power)\n {\n if (power < 0)\n {\n throw new IllegalArgumentException(\"This method does not support negative powers.\");\n }\n long result = 1;\n for (int i = 0; i < power; i++)\n {\n result *= value;\n }\n return result;\n }"
] | [
"public ItemRequest<Task> removeProject(String task) {\n \n String path = String.format(\"/tasks/%s/removeProject\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }",
"public static base_responses add(nitro_service client, autoscaleprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleprofile addresources[] = new autoscaleprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new autoscaleprofile();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t\taddresources[i].url = resources[i].url;\n\t\t\t\taddresources[i].apikey = resources[i].apikey;\n\t\t\t\taddresources[i].sharedsecret = resources[i].sharedsecret;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\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 }",
"public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection(String enterpriseId, String clientId,\n String clientSecret, JWTEncryptionPreferences encryptionPref, IAccessTokenCache accessTokenCache) {\n\n BoxDeveloperEditionAPIConnection connection = new BoxDeveloperEditionAPIConnection(enterpriseId,\n DeveloperEditionEntityType.ENTERPRISE, clientId, clientSecret, encryptionPref, accessTokenCache);\n\n connection.tryRestoreUsingAccessTokenCache();\n\n return connection;\n }",
"private 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 }",
"public final static int readXMLUntil(final StringBuilder out, final String in, final int start, final char... end)\n {\n int pos = start;\n boolean inString = false;\n char stringChar = 0;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (inString)\n {\n if (ch == '\\\\')\n {\n out.append(ch);\n pos++;\n if (pos < in.length())\n {\n out.append(ch);\n pos++;\n }\n continue;\n }\n if (ch == stringChar)\n {\n inString = false;\n out.append(ch);\n pos++;\n continue;\n }\n }\n switch (ch)\n {\n case '\"':\n case '\\'':\n inString = true;\n stringChar = ch;\n break;\n }\n if (!inString)\n {\n boolean endReached = false;\n for (int n = 0; n < end.length; n++)\n {\n if (ch == end[n])\n {\n endReached = true;\n break;\n }\n }\n if (endReached)\n {\n break;\n }\n }\n out.append(ch);\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }",
"public AT_Row setPaddingLeftChar(Character paddingLeftChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingLeftChar(paddingLeftChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public boolean isAssociation(String targetTypeName, List<String> pathWithoutAlias) {\n\t\tOgmEntityPersister persister = getPersister( targetTypeName );\n\t\tType propertyType = persister.getPropertyType( pathWithoutAlias.get( 0 ) );\n\t\treturn propertyType.isAssociationType();\n\t}",
"public List<Integer> getTrackIds() {\n ArrayList<Integer> results = new ArrayList<Integer>(trackCount);\n Enumeration<? extends ZipEntry> entries = zipFile.entries();\n while (entries.hasMoreElements()) {\n ZipEntry entry = entries.nextElement();\n if (entry.getName().startsWith(CACHE_METADATA_ENTRY_PREFIX)) {\n String idPart = entry.getName().substring(CACHE_METADATA_ENTRY_PREFIX.length());\n if (idPart.length() > 0) {\n results.add(Integer.valueOf(idPart));\n }\n }\n }\n\n return Collections.unmodifiableList(results);\n }"
] |
Records the result of updating a server group.
@param serverGroup the server group's name. Cannot be <code>null</code>
@param failed <code>true</code> if the server group update failed;
<code>false</code> if it succeeded | [
"public void recordServerGroupResult(final String serverGroup, final boolean failed) {\n\n synchronized (this) {\n if (groups.contains(serverGroup)) {\n responseCount++;\n if (failed) {\n this.failed = true;\n }\n DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef(\"Recorded group result for '%s': failed = %s\",\n serverGroup, failed);\n notifyAll();\n }\n else {\n throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServerGroup(serverGroup);\n }\n }\n }"
] | [
"public void synchronizeTaskIDToHierarchy()\n {\n clear();\n\n int currentID = (getByID(Integer.valueOf(0)) == null ? 1 : 0);\n for (Task task : m_projectFile.getChildTasks())\n {\n task.setID(Integer.valueOf(currentID++));\n add(task);\n currentID = synchroizeTaskIDToHierarchy(task, currentID);\n }\n }",
"protected PreparedStatement prepareStatement(Connection con,\r\n String sql,\r\n boolean scrollable,\r\n boolean createPreparedStatement,\r\n int explicitFetchSizeHint)\r\n throws SQLException\r\n {\r\n PreparedStatement result;\r\n\r\n // if a JDBC1.0 driver is used the signature\r\n // prepareStatement(String, int, int) is not defined.\r\n // we then call the JDBC1.0 variant prepareStatement(String)\r\n try\r\n {\r\n // if necessary use JDB1.0 methods\r\n if (!FORCEJDBC1_0)\r\n {\r\n if (createPreparedStatement)\r\n {\r\n result =\r\n con.prepareStatement(\r\n sql,\r\n scrollable\r\n ? ResultSet.TYPE_SCROLL_INSENSITIVE\r\n : ResultSet.TYPE_FORWARD_ONLY,\r\n ResultSet.CONCUR_READ_ONLY);\r\n afterJdbc2CapableStatementCreate(result, explicitFetchSizeHint);\r\n }\r\n else\r\n {\r\n result =\r\n con.prepareCall(\r\n sql,\r\n scrollable\r\n ? ResultSet.TYPE_SCROLL_INSENSITIVE\r\n : ResultSet.TYPE_FORWARD_ONLY,\r\n ResultSet.CONCUR_READ_ONLY);\r\n }\r\n }\r\n else\r\n {\r\n if (createPreparedStatement)\r\n {\r\n result = con.prepareStatement(sql);\r\n }\r\n else\r\n {\r\n result = con.prepareCall(sql);\r\n }\r\n }\r\n }\r\n catch (AbstractMethodError err)\r\n {\r\n // this exception is raised if Driver is not JDBC 2.0 compliant\r\n log.warn(\"Used driver seems not JDBC 2.0 compatible, use the JDBC 1.0 mode\", err);\r\n if (createPreparedStatement)\r\n {\r\n result = con.prepareStatement(sql);\r\n }\r\n else\r\n {\r\n result = con.prepareCall(sql);\r\n }\r\n FORCEJDBC1_0 = true;\r\n }\r\n catch (SQLException eSql)\r\n {\r\n // there are JDBC Driver that nominally implement JDBC 2.0, but\r\n // throw DriverNotCapableExceptions. If we catch one of these\r\n // we force usage of JDBC 1.0\r\n if (eSql\r\n .getClass()\r\n .getName()\r\n .equals(\"interbase.interclient.DriverNotCapableException\"))\r\n {\r\n log.warn(\"JDBC 2.0 problems with this interbase driver, we use the JDBC 1.0 mode\");\r\n if (createPreparedStatement)\r\n {\r\n result = con.prepareStatement(sql);\r\n }\r\n else\r\n {\r\n result = con.prepareCall(sql);\r\n }\r\n FORCEJDBC1_0 = true;\r\n }\r\n else\r\n {\r\n throw eSql;\r\n }\r\n }\r\n try\r\n {\r\n if (!ProxyHelper.isNormalOjbProxy(result)) // tomdz: What about VirtualProxy\r\n {\r\n platform.afterStatementCreate(result);\r\n }\r\n }\r\n catch (PlatformException e)\r\n {\r\n log.error(\"Platform dependend failure\", e);\r\n }\r\n return result;\r\n }",
"public static String getParentDirectory(String filePath) throws IllegalArgumentException {\n if (Pattern.matches(sPatternUrl, filePath))\n return getURLParentDirectory(filePath);\n\n return new File(filePath).getParent();\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 }",
"private static String formatDirName(final String prefix, final String suffix) {\n // Replace all invalid characters with '-'\n final CharMatcher invalidCharacters = VALID_SUFFIX_CHARS.negate();\n return String.format(\"%s-%s\", prefix, invalidCharacters.trimAndCollapseFrom(suffix.toLowerCase(), '-'));\n }",
"public void initializePersistenceStrategy(CacheMappingType cacheMappingType, Set<EntityKeyMetadata> entityTypes, Set<AssociationKeyMetadata> associationTypes, Set<IdSourceKeyMetadata> idSourceTypes, Iterable<Namespace> namespaces) {\n\t\tpersistenceStrategy = PersistenceStrategy.getInstance(\n\t\t\t\tcacheMappingType,\n\t\t\t\texternalCacheManager,\n\t\t\t\tconfig.getConfigurationUrl(),\n\t\t\t\tjtaPlatform,\n\t\t\t\tentityTypes,\n\t\t\t\tassociationTypes,\n\t\t\t\tidSourceTypes\n\t\t);\n\n\t\t// creates handler for TableGenerator Id sources\n\t\tboolean requiresCounter = hasIdGeneration( idSourceTypes );\n\t\tif ( requiresCounter ) {\n\t\t\tthis.tableClusterHandler = new TableClusteredCounterHandler( persistenceStrategy.getCacheManager().getCacheManager() );\n\t\t}\n\n\t\t// creates handlers for SequenceGenerator Id sources\n\t\tfor ( Namespace namespace : namespaces ) {\n\t\t\tfor ( Sequence seq : namespace.getSequences() ) {\n\t\t\t\tthis.sequenceCounterHandlers.put( seq.getExportIdentifier(),\n\t\t\t\t\t\tnew SequenceClusteredCounterHandler( persistenceStrategy.getCacheManager().getCacheManager(), seq ) );\n\t\t\t}\n\t\t}\n\n\t\t// clear resources\n\t\tthis.externalCacheManager = null;\n\t\tthis.jtaPlatform = null;\n\t}",
"public double[] getScaleDenominators() {\n double[] dest = new double[this.scaleDenominators.length];\n System.arraycopy(this.scaleDenominators, 0, dest, 0, this.scaleDenominators.length);\n return dest;\n }",
"public DbOrganization getOrganization(final DbArtifact dbArtifact) {\n final DbModule module = getModule(dbArtifact);\n\n if(module == null || module.getOrganization() == null){\n return null;\n }\n\n return repositoryHandler.getOrganization(module.getOrganization());\n }",
"public static base_response unset(nitro_service client, systemcollectionparam resource, String[] args) throws Exception{\n\t\tsystemcollectionparam unsetresource = new systemcollectionparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}"
] |
Determine if a task field contains data.
@param task task instance
@param field target field
@return true if the field contains data | [
"@SuppressWarnings(\"unchecked\") private boolean isFieldPopulated(Task task, TaskField field)\n {\n boolean result = false;\n if (field != null)\n {\n Object value = task.getCachedValue(field);\n switch (field)\n {\n case PREDECESSORS:\n case SUCCESSORS:\n {\n result = value != null && !((List<Relation>) value).isEmpty();\n break;\n }\n\n default:\n {\n result = value != null;\n break;\n }\n }\n }\n return result;\n }"
] | [
"public DomainList getCollectionDomains(Date date, String collectionId, int perPage, int page) throws FlickrException {\n return getDomains(METHOD_GET_COLLECTION_DOMAINS, \"collection_id\", collectionId, date, perPage, page);\n }",
"public static base_response add(nitro_service client, appfwjsoncontenttype resource) throws Exception {\n\t\tappfwjsoncontenttype addresource = new appfwjsoncontenttype();\n\t\taddresource.jsoncontenttypevalue = resource.jsoncontenttypevalue;\n\t\taddresource.isregex = resource.isregex;\n\t\treturn addresource.add_resource(client);\n\t}",
"private void updateDateTimeFormats(ProjectProperties properties)\n {\n String[] timePatterns = getTimePatterns(properties);\n String[] datePatterns = getDatePatterns(properties);\n String[] dateTimePatterns = getDateTimePatterns(properties, timePatterns);\n\n m_dateTimeFormat.applyPatterns(dateTimePatterns);\n m_dateFormat.applyPatterns(datePatterns);\n m_timeFormat.applyPatterns(timePatterns);\n\n m_dateTimeFormat.setLocale(m_locale);\n m_dateFormat.setLocale(m_locale);\n\n m_dateTimeFormat.setNullText(m_nullText);\n m_dateFormat.setNullText(m_nullText);\n m_timeFormat.setNullText(m_nullText);\n\n m_dateTimeFormat.setAmPmText(properties.getAMText(), properties.getPMText());\n m_timeFormat.setAmPmText(properties.getAMText(), properties.getPMText());\n }",
"@Override\n public boolean decompose(DMatrixRBlock A) {\n if( A.numCols != A.numRows )\n throw new IllegalArgumentException(\"A must be square\");\n\n this.T = A;\n\n if( lower )\n return decomposeLower();\n else\n return decomposeUpper();\n }",
"private void clearMetadata(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(hotCache.keySet())) {\n if (deck.player == player) {\n hotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverTrackMetadataUpdate(player, null); // Inform listeners the metadata is gone.\n }\n }\n }\n }",
"private static EventTypeEnum mapEventTypeEnum(EventEnumType eventType) {\n if (eventType != null) {\n return EventTypeEnum.valueOf(eventType.name());\n }\n return EventTypeEnum.UNKNOWN;\n }",
"public static List<String> getBuildNumbersNotToBeDeleted(Run build) {\n List<String> notToDelete = Lists.newArrayList();\n List<? extends Run<?, ?>> builds = build.getParent().getBuilds();\n for (Run<?, ?> run : builds) {\n if (run.isKeepLog()) {\n notToDelete.add(String.valueOf(run.getNumber()));\n }\n }\n return notToDelete;\n }",
"public void addRow(String primaryKeyColumnName, Map<String, Object> map)\n {\n Integer rowNumber = Integer.valueOf(m_rowNumber++);\n map.put(\"ROW_NUMBER\", rowNumber);\n Object primaryKey = null;\n if (primaryKeyColumnName != null)\n {\n primaryKey = map.get(primaryKeyColumnName);\n }\n\n if (primaryKey == null)\n {\n primaryKey = rowNumber;\n }\n\n MapRow newRow = new MapRow(map);\n MapRow oldRow = m_rows.get(primaryKey);\n if (oldRow == null)\n {\n m_rows.put(primaryKey, newRow);\n }\n else\n {\n int oldVersion = oldRow.getInteger(\"ROW_VERSION\").intValue();\n int newVersion = newRow.getInteger(\"ROW_VERSION\").intValue();\n if (newVersion > oldVersion)\n {\n m_rows.put(primaryKey, newRow);\n }\n }\n }",
"public static Diagram parseJson(JSONObject json,\n Boolean keepGlossaryLink) throws JSONException {\n ArrayList<Shape> shapes = new ArrayList<Shape>();\n HashMap<String, JSONObject> flatJSON = flatRessources(json);\n for (String resourceId : flatJSON.keySet()) {\n parseRessource(shapes,\n flatJSON,\n resourceId,\n keepGlossaryLink);\n }\n String id = \"canvas\";\n\n if (json.has(\"resourceId\")) {\n id = json.getString(\"resourceId\");\n shapes.remove(new Shape(id));\n }\n ;\n Diagram diagram = new Diagram(id);\n\n // remove Diagram\n // (Diagram)getShapeWithId(json.getString(\"resourceId\"), shapes);\n parseStencilSet(json,\n diagram);\n parseSsextensions(json,\n diagram);\n parseStencil(json,\n diagram);\n parseProperties(json,\n diagram,\n keepGlossaryLink);\n parseChildShapes(shapes,\n json,\n diagram);\n parseBounds(json,\n diagram);\n diagram.setShapes(shapes);\n return diagram;\n }"
] |
creates a scope using the passed function to compute the names and sets the passed scope as the parent scope | [
"public static <T extends EObject> IScope scopeFor(Iterable<? extends T> elements,\n\t\t\tfinal Function<T, QualifiedName> nameComputation, IScope outer) {\n\t\treturn new SimpleScope(outer,scopedElementsFor(elements, nameComputation));\n\t}"
] | [
"public void combine(CRFClassifier<IN> crf, double weight) {\r\n Timing timer = new Timing();\r\n\r\n // Check the CRFClassifiers are compatible\r\n if (!this.pad.equals(crf.pad)) {\r\n throw new RuntimeException(\"Incompatible CRFClassifier: pad does not match\");\r\n }\r\n if (this.windowSize != crf.windowSize) {\r\n throw new RuntimeException(\"Incompatible CRFClassifier: windowSize does not match\");\r\n }\r\n if (this.labelIndices.length != crf.labelIndices.length) {\r\n // Should match since this should be same as the windowSize\r\n throw new RuntimeException(\"Incompatible CRFClassifier: labelIndices length does not match\");\r\n }\r\n this.classIndex.addAll(crf.classIndex.objectsList());\r\n\r\n // Combine weights of the other classifier with this classifier,\r\n // weighing the other classifier's weights by weight\r\n // First merge the feature indicies\r\n int oldNumFeatures1 = this.featureIndex.size();\r\n int oldNumFeatures2 = crf.featureIndex.size();\r\n int oldNumWeights1 = this.getNumWeights();\r\n int oldNumWeights2 = crf.getNumWeights();\r\n this.featureIndex.addAll(crf.featureIndex.objectsList());\r\n this.knownLCWords.addAll(crf.knownLCWords);\r\n assert (weights.length == oldNumFeatures1);\r\n\r\n // Combine weights of this classifier with other classifier\r\n for (int i = 0; i < labelIndices.length; i++) {\r\n this.labelIndices[i].addAll(crf.labelIndices[i].objectsList());\r\n }\r\n System.err.println(\"Combining weights: will automatically match labelIndices\");\r\n combineWeights(crf, weight);\r\n\r\n int numFeatures = featureIndex.size();\r\n int numWeights = getNumWeights();\r\n long elapsedMs = timer.stop();\r\n System.err.println(\"numFeatures: orig1=\" + oldNumFeatures1 + \", orig2=\" + oldNumFeatures2 + \", combined=\"\r\n + numFeatures);\r\n System.err\r\n .println(\"numWeights: orig1=\" + oldNumWeights1 + \", orig2=\" + oldNumWeights2 + \", combined=\" + numWeights);\r\n System.err.println(\"Time to combine CRFClassifier: \" + Timing.toSecondsString(elapsedMs) + \" seconds\");\r\n }",
"public void removeHoursFromDay(ProjectCalendarHours hours)\n {\n if (hours.getParentCalendar() != this)\n {\n throw new IllegalArgumentException();\n }\n m_hours[hours.getDay().getValue() - 1] = null;\n }",
"public static DeploymentUnit getTopDeploymentUnit(DeploymentUnit unit) {\n Assert.checkNotNullParam(\"unit\", unit);\n\n DeploymentUnit parent = unit.getParent();\n while (parent != null) {\n unit = parent;\n parent = unit.getParent();\n }\n return unit;\n }",
"protected void createDocument() throws ParserConfigurationException\n {\n DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder builder = builderFactory.newDocumentBuilder();\n DocumentType doctype = builder.getDOMImplementation().createDocumentType(\"html\", \"-//W3C//DTD XHTML 1.1//EN\", \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\");\n doc = builder.getDOMImplementation().createDocument(\"http://www.w3.org/1999/xhtml\", \"html\", doctype);\n \n head = doc.createElement(\"head\");\n Element meta = doc.createElement(\"meta\");\n meta.setAttribute(\"http-equiv\", \"content-type\");\n meta.setAttribute(\"content\", \"text/html;charset=utf-8\");\n head.appendChild(meta);\n title = doc.createElement(\"title\");\n title.setTextContent(\"PDF Document\");\n head.appendChild(title);\n globalStyle = doc.createElement(\"style\");\n globalStyle.setAttribute(\"type\", \"text/css\");\n //globalStyle.setTextContent(createGlobalStyle());\n head.appendChild(globalStyle);\n \n body = doc.createElement(\"body\");\n \n Element root = doc.getDocumentElement();\n root.appendChild(head);\n root.appendChild(body);\n }",
"public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax,\n\t\t\tAbstractMeanSquaredDisplacmentEvaluator msdeval) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}",
"public static authenticationvserver_authenticationcertpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_authenticationcertpolicy_binding obj = new authenticationvserver_authenticationcertpolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_authenticationcertpolicy_binding response[] = (authenticationvserver_authenticationcertpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static base_responses delete(nitro_service client, String sitename[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (sitename != null && sitename.length > 0) {\n\t\t\tgslbsite deleteresources[] = new gslbsite[sitename.length];\n\t\t\tfor (int i=0;i<sitename.length;i++){\n\t\t\t\tdeleteresources[i] = new gslbsite();\n\t\t\t\tdeleteresources[i].sitename = sitename[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static Iterable<BoxGroup.Info> getAllGroupsByName(final BoxAPIConnection api, String name) {\n final QueryStringBuilder builder = new QueryStringBuilder();\n if (name == null || name.trim().isEmpty()) {\n throw new BoxAPIException(\"Searching groups by name requires a non NULL or non empty name\");\n } else {\n builder.appendParam(\"name\", name);\n }\n\n return new Iterable<BoxGroup.Info>() {\n public Iterator<BoxGroup.Info> iterator() {\n URL url = GROUPS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n return new BoxGroupIterator(api, url);\n }\n };\n }",
"public void visitOpen(String packaze, int access, String... modules) {\n if (mv != null) {\n mv.visitOpen(packaze, access, modules);\n }\n }"
] |
Attempts to retrieves ResourceReport until maxWaitMs time is reached. Set maxWaitMs to -1 to
retry forever. | [
"private ResourceReport getResourceReport(TwillController controller, int maxWaitMs) {\n ResourceReport report = controller.getResourceReport();\n int elapsed = 0;\n while (report == null) {\n report = controller.getResourceReport();\n try {\n Thread.sleep(500);\n } catch (InterruptedException e) {\n throw new IllegalStateException(e);\n }\n elapsed += 500;\n if ((maxWaitMs != -1) && (elapsed > maxWaitMs)) {\n String msg = String.format(\"Exceeded max wait time to retrieve ResourceReport from Twill.\"\n + \" Elapsed time = %s ms\", elapsed);\n log.error(msg);\n throw new IllegalStateException(msg);\n }\n if ((elapsed % 10000) == 0) {\n log.info(\"Waiting for ResourceReport from Twill. Elapsed time = {} ms\", elapsed);\n }\n }\n return report;\n }"
] | [
"@Override\n\tprotected void doLinking() {\n\t\tIParseResult parseResult = getParseResult();\n\t\tif (parseResult == null || parseResult.getRootASTElement() == null)\n\t\t\treturn;\n\n\t\tXtextLinker castedLinker = (XtextLinker) getLinker();\n\t\tcastedLinker.discardGeneratedPackages(parseResult.getRootASTElement());\n\t}",
"@Override\n protected URL getDefinitionsURL() {\n try {\n URL url = CustomEPSGCodes.class.getResource(CUSTOM_EPSG_CODES_FILE);\n // quickly test url\n try (InputStream stream = url.openStream()) {\n //noinspection ResultOfMethodCallIgnored\n stream.read();\n }\n return url;\n } catch (Throwable e) {\n throw new AssertionError(\"Unable to load /epsg.properties file from root of classpath.\");\n }\n }",
"public static Field getDeclaredFieldWithPath(Class<?> clazz, String path) {\n\n int lastDot = path.lastIndexOf('.');\n\n if (lastDot > -1) {\n String parentPath = path.substring(0, lastDot);\n String fieldName = path.substring(lastDot + 1);\n Field parentField = getDeclaredFieldWithPath(clazz, parentPath);\n return getDeclaredFieldInHierarchy(parentField.getType(), fieldName);\n } else {\n return getDeclaredFieldInHierarchy(clazz, path);\n }\n }",
"String escapeValue(Object value) {\n return HtmlUtils.htmlEscape(value != null ? value.toString() : \"<null>\");\n }",
"public static int secondsDiff(Date earlierDate, Date laterDate) {\n if (earlierDate == null || laterDate == null) {\n return 0;\n }\n\n return (int) ((laterDate.getTime() / SECOND_MILLIS) - (earlierDate.getTime() / SECOND_MILLIS));\n }",
"private void writeResourceExtendedAttributes(Project.Resources.Resource xml, Resource mpx)\n {\n Project.Resources.Resource.ExtendedAttribute attrib;\n List<Project.Resources.Resource.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute();\n\n for (ResourceField mpxFieldID : getAllResourceExtendedAttributes())\n {\n Object value = mpx.getCachedValue(mpxFieldID);\n\n if (FieldTypeHelper.valueIsNotDefault(mpxFieldID, value))\n {\n m_extendedAttributesInUse.add(mpxFieldID);\n\n Integer xmlFieldID = Integer.valueOf(MPPResourceField.getID(mpxFieldID) | MPPResourceField.RESOURCE_FIELD_BASE);\n\n attrib = m_factory.createProjectResourcesResourceExtendedAttribute();\n extendedAttributes.add(attrib);\n attrib.setFieldID(xmlFieldID.toString());\n attrib.setValue(DatatypeConverter.printExtendedAttribute(this, value, mpxFieldID.getDataType()));\n attrib.setDurationFormat(printExtendedAttributeDurationFormat(value));\n }\n }\n }",
"public static appfwprofile_safeobject_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_safeobject_binding obj = new appfwprofile_safeobject_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_safeobject_binding response[] = (appfwprofile_safeobject_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void doDelete(Object obj, boolean ignoreReferences) throws PersistenceBrokerException\n {\n //logger.info(\"DELETING \" + obj);\n // object is not null\n if (obj != null)\n {\n obj = getProxyFactory().getRealObject(obj);\n /**\n * Kuali Foundation modification -- 8/24/2007\n */\n if ( obj == null ) return;\n /**\n * End of Kuali Foundation modification\n */\n /**\n * MBAIRD\n * 1. if we are marked for delete already, avoid recursing on this object\n *\n * arminw:\n * use object instead Identity object in markedForDelete List,\n * because using objects we get a better performance. I can't find\n * side-effects in doing so.\n */\n if (markedForDelete.contains(obj))\n {\n return;\n }\n \n ClassDescriptor cld = getClassDescriptor(obj.getClass());\n //BRJ: check for valid pk\n if (!serviceBrokerHelper().assertValidPkForDelete(cld, obj))\n {\n String msg = \"Cannot delete object without valid PKs. \" + obj;\n logger.error(msg);\n return;\n }\n \n /**\n * MBAIRD\n * 2. register object in markedForDelete map.\n */\n markedForDelete.add(obj);\n Identity oid = serviceIdentity().buildIdentity(cld, obj);\n\n // Invoke events on PersistenceBrokerAware instances and listeners\n BEFORE_DELETE_EVENT.setTarget(obj);\n fireBrokerEvent(BEFORE_DELETE_EVENT);\n BEFORE_DELETE_EVENT.setTarget(null);\n\n // now perform deletion\n performDeletion(cld, obj, oid, ignoreReferences);\n \t \t \n // Invoke events on PersistenceBrokerAware instances and listeners\n AFTER_DELETE_EVENT.setTarget(obj);\n fireBrokerEvent(AFTER_DELETE_EVENT);\n AFTER_DELETE_EVENT.setTarget(null);\n \t \t \t\n // let the connection manager to execute batch\n connectionManager.executeBatchIfNecessary();\n }\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 }"
] |
Send a lifecycle announcement to all registered listeners.
@param logger the logger to use, so the log entry shows as belonging to the proper subclass.
@param starting will be {@code true} if the DeviceFinder is starting, {@code false} if it is stopping. | [
"protected void deliverLifecycleAnnouncement(final Logger logger, final boolean starting) {\n new Thread(new Runnable() {\n @Override\n public void run() {\n for (final LifecycleListener listener : getLifecycleListeners()) {\n try {\n if (starting) {\n listener.started(LifecycleParticipant.this);\n } else {\n listener.stopped(LifecycleParticipant.this);\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering lifecycle announcement to listener\", t);\n }\n }\n }\n }, \"Lifecycle announcement delivery\").start();\n }"
] | [
"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 }",
"@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 }",
"static VaultConfig readVaultElement_3_0(XMLExtendedStreamReader reader, Namespace expectedNs) throws XMLStreamException {\n final VaultConfig config = new VaultConfig();\n\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n final String value = reader.getAttributeValue(i);\n String name = reader.getAttributeLocalName(i);\n if (name.equals(CODE)){\n config.code = value;\n } else if (name.equals(MODULE)){\n config.module = value;\n } else {\n unexpectedVaultAttribute(reader.getAttributeLocalName(i), reader);\n }\n }\n if (config.code == null && config.module != null){\n throw new XMLStreamException(\"Attribute 'module' was specified without an attribute\"\n + \" 'code' for element '\" + VAULT + \"' at \" + reader.getLocation());\n }\n readVaultOptions(reader, config);\n return config;\n }",
"private void addContentInfo() {\n\n if (!m_cms.getRequestContext().getCurrentProject().isOnlineProject()\n && (null == m_searchController.getCommon().getConfig().getSolrIndex())\n && (null != m_addContentInfoForEntries)) {\n CmsSolrQuery query = new CmsSolrQuery();\n m_searchController.addQueryParts(query, m_cms);\n query.setStart(Integer.valueOf(0));\n query.setRows(m_addContentInfoForEntries);\n CmsContentLoadCollectorInfo info = new CmsContentLoadCollectorInfo();\n info.setCollectorClass(this.getClass().getName());\n info.setCollectorParams(query.getQuery());\n info.setId((new CmsUUID()).getStringValue());\n if (CmsJspTagEditable.getDirectEditProvider(pageContext) != null) {\n try {\n CmsJspTagEditable.getDirectEditProvider(pageContext).insertDirectEditListMetadata(\n pageContext,\n info);\n } catch (JspException e) {\n LOG.error(\"Could not write content info.\", e);\n }\n }\n }\n }",
"public int addPathnameToProfile(int id, String pathname, String actualPath) throws Exception {\n int pathOrder = getPathOrder(id).size() + 1;\n int pathId = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"INSERT INTO \" + Constants.DB_TABLE_PATH\n + \"(\" + Constants.PATH_PROFILE_PATHNAME + \",\"\n + Constants.PATH_PROFILE_ACTUAL_PATH + \",\"\n + Constants.PATH_PROFILE_GROUP_IDS + \",\"\n + Constants.PATH_PROFILE_PROFILE_ID + \",\"\n + Constants.PATH_PROFILE_PATH_ORDER + \",\"\n + Constants.PATH_PROFILE_CONTENT_TYPE + \",\"\n + Constants.PATH_PROFILE_REQUEST_TYPE + \",\"\n + Constants.PATH_PROFILE_GLOBAL + \")\"\n + \" VALUES (?, ?, ?, ?, ?, ?, ?, ?);\",\n PreparedStatement.RETURN_GENERATED_KEYS\n );\n statement.setString(1, pathname);\n statement.setString(2, actualPath);\n statement.setString(3, \"\");\n statement.setInt(4, id);\n statement.setInt(5, pathOrder);\n statement.setString(6, Constants.PATH_PROFILE_DEFAULT_CONTENT_TYPE); // should be set by UI/API\n statement.setInt(7, Constants.REQUEST_TYPE_GET); // should be set by UI/API\n statement.setBoolean(8, false);\n statement.executeUpdate();\n\n // execute statement and get resultSet which will have the generated path ID as the first field\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n pathId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add path\");\n }\n } catch (SQLException e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n // need to add to request response table for all clients\n for (Client client : ClientService.getInstance().findAllClients(id)) {\n this.addPathToRequestResponseTable(id, client.getUUID(), pathId);\n }\n\n return pathId;\n }",
"public static void acceptsHex(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_X, OPT_HEX), \"fetch key/entry by key value of hex type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }",
"public <Ex extends Throwable> Try<R,Ex> execute(T input,Class<Ex> classes){\n\t\t\n\t\treturn Try.withCatch( ()->transactionTemplate.execute(status-> transaction.apply(input)),classes);\n\t\t \n\t}",
"protected void capture3DScreenShot(GVRRenderTarget renderTarget, boolean isMultiview) {\n if (mScreenshot3DCallback == null) {\n return;\n }\n final Bitmap[] bitmaps = new Bitmap[6];\n renderSixCamerasAndReadback(mMainScene.getMainCameraRig(), bitmaps, renderTarget, isMultiview);\n returnScreenshot3DToCaller(mScreenshot3DCallback, bitmaps, mReadbackBufferWidth, mReadbackBufferHeight);\n\n mScreenshot3DCallback = null;\n }",
"private static void registerImage(String imageId, String imageTag, String targetRepo,\n ArrayListMultimap<String, String> artifactsProps, int buildInfoId) throws IOException {\n DockerImage image = new DockerImage(imageId, imageTag, targetRepo, buildInfoId, artifactsProps);\n images.add(image);\n }"
] |
Use this API to fetch dnspolicylabel resource of given name . | [
"public static dnspolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tdnspolicylabel obj = new dnspolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tdnspolicylabel response = (dnspolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"public UriComponentsBuilder queryParams(MultiValueMap<String, String> params) {\n\t\tAssert.notNull(params, \"'params' must not be null\");\n\t\tthis.queryParams.putAll(params);\n\t\treturn this;\n\t}",
"public Object selectElement(String predicate) throws org.odmg.QueryInvalidException\r\n {\r\n return ((DList) this.query(predicate)).get(0);\r\n }",
"public static void registerConverters(Set<?> converters, ConverterRegistry registry) {\n\t\tif (converters != null) {\n\t\t\tfor (Object converter : converters) {\n\t\t\t\tif (converter instanceof GenericConverter) {\n\t\t\t\t\tregistry.addConverter((GenericConverter) converter);\n\t\t\t\t}\n\t\t\t\telse if (converter instanceof Converter<?, ?>) {\n\t\t\t\t\tregistry.addConverter((Converter<?, ?>) converter);\n\t\t\t\t}\n\t\t\t\telse if (converter instanceof ConverterFactory<?, ?>) {\n\t\t\t\t\tregistry.addConverterFactory((ConverterFactory<?, ?>) converter);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Each converter object must implement one of the \" +\n\t\t\t\t\t\t\t\"Converter, ConverterFactory, or GenericConverter interfaces\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"private void writePropertyData() {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"properties.csv\"))) {\n\n\t\t\tout.println(\"Id\" + \",Label\" + \",Description\" + \",URL\" + \",Datatype\"\n\t\t\t\t\t+ \",Uses in statements\" + \",Items with such statements\"\n\t\t\t\t\t+ \",Uses in statements with qualifiers\"\n\t\t\t\t\t+ \",Uses in qualifiers\" + \",Uses in references\"\n\t\t\t\t\t+ \",Uses total\" + \",Related properties\");\n\n\t\t\tList<Entry<PropertyIdValue, PropertyRecord>> list = new ArrayList<Entry<PropertyIdValue, PropertyRecord>>(\n\t\t\t\t\tthis.propertyRecords.entrySet());\n\t\t\tCollections.sort(list, new UsageRecordComparator());\n\t\t\tfor (Entry<PropertyIdValue, PropertyRecord> entry : list) {\n\t\t\t\tprintPropertyRecord(out, entry.getValue(), entry.getKey());\n\t\t\t}\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"public 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 java.sql.Time toTime(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.sql.Time) {\n return (java.sql.Time) value;\n }\n if (value instanceof String) {\n if (\"\".equals((String) value)) {\n return null;\n }\n return new java.sql.Time(IN_TIME_FORMAT.parse((String) value).getTime());\n }\n\n return new java.sql.Time(IN_TIME_FORMAT.parse(value.toString()).getTime());\n }",
"public String getPermalink(CmsObject cms, String resourceName, CmsUUID detailContentId) {\n\n String permalink = \"\";\n try {\n permalink = substituteLink(cms, CmsPermalinkResourceHandler.PERMALINK_HANDLER);\n String id = cms.readResource(resourceName, CmsResourceFilter.ALL).getStructureId().toString();\n permalink += id;\n if (detailContentId != null) {\n permalink += \":\" + detailContentId;\n }\n String ext = CmsFileUtil.getExtension(resourceName);\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(ext)) {\n permalink += ext;\n }\n CmsSite currentSite = OpenCms.getSiteManager().getCurrentSite(cms);\n String serverPrefix = null;\n if (currentSite == OpenCms.getSiteManager().getDefaultSite()) {\n Optional<CmsSite> siteForDefaultUri = OpenCms.getSiteManager().getSiteForDefaultUri();\n if (siteForDefaultUri.isPresent()) {\n serverPrefix = siteForDefaultUri.get().getServerPrefix(cms, resourceName);\n } else {\n serverPrefix = OpenCms.getSiteManager().getWorkplaceServer();\n }\n } else {\n serverPrefix = currentSite.getServerPrefix(cms, resourceName);\n }\n\n if (!permalink.startsWith(serverPrefix)) {\n permalink = serverPrefix + permalink;\n }\n } catch (CmsException e) {\n // if something wrong\n permalink = e.getLocalizedMessage();\n if (LOG.isErrorEnabled()) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n return permalink;\n }",
"private static void checkPreconditions(final Set<Object> possibleValues) {\n\t\tif( possibleValues == null ) {\n\t\t\tthrow new NullPointerException(\"possibleValues Set should not be null\");\n\t\t} else if( possibleValues.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"possibleValues Set should not be empty\");\n\t\t}\n\t}",
"@Deprecated\n public FluoConfiguration addObservers(Iterable<ObserverSpecification> observers) {\n int next = getNextObserverId();\n for (ObserverSpecification oconf : observers) {\n addObserver(oconf, next++);\n }\n return this;\n }"
] |
Add a BETWEEN clause so the column must be between the low and high parameters. | [
"public Where<T, ID> between(String columnName, Object low, Object high) throws SQLException {\n\t\taddClause(new Between(columnName, findColumnFieldType(columnName), low, high));\n\t\treturn this;\n\t}"
] | [
"public void setAttributeEditable(Attribute attribute, boolean editable) {\n\t\tattribute.setEditable(editable);\n\t\tif (!(attribute instanceof LazyAttribute)) { // should not instantiate lazy attributes!\n\t\t\tif (attribute instanceof ManyToOneAttribute) {\n\t\t\t\tsetAttributeEditable(((ManyToOneAttribute) attribute).getValue(), editable);\n\t\t\t} else if (attribute instanceof OneToManyAttribute) {\n\t\t\t\tList<AssociationValue> values = ((OneToManyAttribute) attribute).getValue();\n\t\t\t\tfor (AssociationValue value : values) {\n\t\t\t\t\tsetAttributeEditable(value, editable);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public void hideKeyboard() {\n InputMethodManager inputMethodManager = (InputMethodManager) getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);\n inputMethodManager.hideSoftInputFromWindow(mPhoneEdit.getWindowToken(), 0);\n }",
"public static double Y0(double x) {\r\n if (x < 8.0) {\r\n double y = x * x;\r\n\r\n double ans1 = -2957821389.0 + y * (7062834065.0 + y * (-512359803.6\r\n + y * (10879881.29 + y * (-86327.92757 + y * 228.4622733))));\r\n double ans2 = 40076544269.0 + y * (745249964.8 + y * (7189466.438\r\n + y * (47447.26470 + y * (226.1030244 + y * 1.0))));\r\n\r\n return (ans1 / ans2) + 0.636619772 * J0(x) * Math.log(x);\r\n } else {\r\n double z = 8.0 / x;\r\n double y = z * z;\r\n double xx = x - 0.785398164;\r\n\r\n double ans1 = 1.0 + y * (-0.1098628627e-2 + y * (0.2734510407e-4\r\n + y * (-0.2073370639e-5 + y * 0.2093887211e-6)));\r\n double ans2 = -0.1562499995e-1 + y * (0.1430488765e-3\r\n + y * (-0.6911147651e-5 + y * (0.7621095161e-6\r\n + y * (-0.934945152e-7))));\r\n return Math.sqrt(0.636619772 / x) *\r\n (Math.sin(xx) * ans1 + z * Math.cos(xx) * ans2);\r\n }\r\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 }",
"private List<DomainControllerData> readFromFile(String directoryName) {\n List<DomainControllerData> data = new ArrayList<DomainControllerData>();\n if (directoryName == null) {\n return data;\n }\n\n if (conn == null) {\n init();\n }\n\n try {\n if (usingPreSignedUrls()) {\n PreSignedUrlParser parsedPut = new PreSignedUrlParser(pre_signed_put_url);\n directoryName = parsedPut.getPrefix();\n }\n String key = S3Util.sanitize(directoryName) + \"/\" + S3Util.sanitize(DC_FILE_NAME);\n GetResponse val = conn.get(location, key, null);\n if (val.object != null) {\n byte[] buf = val.object.data;\n if (buf != null && buf.length > 0) {\n try {\n data = S3Util.domainControllerDataFromByteBuffer(buf);\n } catch (Exception e) {\n throw HostControllerLogger.ROOT_LOGGER.failedMarshallingDomainControllerData();\n }\n }\n }\n return data;\n } catch (IOException e) {\n throw HostControllerLogger.ROOT_LOGGER.cannotAccessS3File(e.getLocalizedMessage());\n }\n }",
"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 static SimpleFeatureType createGridFeatureType(\n @Nonnull final MapfishMapContext mapContext,\n @Nonnull final Class<? extends Geometry> geomClass) {\n final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();\n CoordinateReferenceSystem projection = mapContext.getBounds().getProjection();\n typeBuilder.add(Constants.Style.Grid.ATT_GEOM, geomClass, projection);\n typeBuilder.setName(Constants.Style.Grid.NAME_LINES);\n\n return typeBuilder.buildFeatureType();\n }",
"protected NodeData createPageStyle()\n {\n NodeData ret = createBlockStyle();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"position\", tf.createIdent(\"relative\")));\n\t\tret.push(createDeclaration(\"border-width\", tf.createLength(1f, Unit.px)));\n\t\tret.push(createDeclaration(\"border-style\", tf.createIdent(\"solid\")));\n\t\tret.push(createDeclaration(\"border-color\", tf.createColor(0, 0, 255)));\n\t\tret.push(createDeclaration(\"margin\", tf.createLength(0.5f, Unit.em)));\n\t\t\n PDRectangle layout = getCurrentMediaBox();\n if (layout != null)\n {\n float w = layout.getWidth();\n float h = layout.getHeight();\n final int rot = pdpage.getRotation();\n if (rot == 90 || rot == 270)\n {\n float x = w; w = h; h = x;\n }\n \n ret.push(createDeclaration(\"width\", tf.createLength(w, unit)));\n ret.push(createDeclaration(\"height\", tf.createLength(h, unit)));\n }\n else\n log.warn(\"No media box found\");\n \n return ret;\n }",
"private String getPropertyValue(String level, String name)\r\n {\r\n return getDefForLevel(level).getProperty(name);\r\n }"
] |
Maps a duration unit value from a recurring task record in an MPX file
to a TimeUnit instance. Defaults to days if any problems are encountered.
@param value integer duration units value
@return TimeUnit instance | [
"private static TimeUnit getDurationUnits(Integer value)\n {\n TimeUnit result = null;\n\n if (value != null)\n {\n int index = value.intValue();\n if (index >= 0 && index < DURATION_UNITS.length)\n {\n result = DURATION_UNITS[index];\n }\n }\n\n if (result == null)\n {\n result = TimeUnit.DAYS;\n }\n\n return (result);\n }"
] | [
"public static aaauser_auditsyslogpolicy_binding[] get(nitro_service service, String username) throws Exception{\n\t\taaauser_auditsyslogpolicy_binding obj = new aaauser_auditsyslogpolicy_binding();\n\t\tobj.set_username(username);\n\t\taaauser_auditsyslogpolicy_binding response[] = (aaauser_auditsyslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static base_response add(nitro_service client, clusternodegroup resource) throws Exception {\n\t\tclusternodegroup addresource = new clusternodegroup();\n\t\taddresource.name = resource.name;\n\t\taddresource.strict = resource.strict;\n\t\treturn addresource.add_resource(client);\n\t}",
"private void readBlock(int blockIndex, int startIndex, int blockLength) throws Exception\n {\n logBlock(blockIndex, startIndex, blockLength);\n\n if (blockLength < 128)\n {\n readTableBlock(startIndex, blockLength);\n }\n else\n {\n readColumnBlock(startIndex, blockLength);\n }\n }",
"public Rate getRate(int field) throws MPXJException\n {\n Rate result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n try\n {\n String rate = m_fields[field];\n int index = rate.indexOf('/');\n double amount;\n TimeUnit units;\n\n if (index == -1)\n {\n amount = m_formats.getCurrencyFormat().parse(rate).doubleValue();\n units = TimeUnit.HOURS;\n }\n else\n {\n amount = m_formats.getCurrencyFormat().parse(rate.substring(0, index)).doubleValue();\n units = TimeUnitUtility.getInstance(rate.substring(index + 1), m_locale);\n }\n\n result = new Rate(amount, units);\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse rate\", ex);\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }",
"public static synchronized void registerDao(ConnectionSource connectionSource, Dao<?, ?> dao) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\taddDaoToClassMap(new ClassConnectionSource(connectionSource, dao.getDataClass()), dao);\n\t}",
"private void setUserFieldValue(UDFAssignmentType udf, DataType dataType, Object value)\n {\n switch (dataType)\n {\n case DURATION:\n {\n udf.setTextValue(((Duration) value).toString());\n break;\n }\n\n case CURRENCY:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setCostValue((Double) value);\n break;\n }\n\n case BINARY:\n {\n udf.setTextValue(\"\");\n break;\n }\n\n case STRING:\n {\n udf.setTextValue((String) value);\n break;\n }\n\n case DATE:\n {\n udf.setStartDateValue((Date) value);\n break;\n }\n\n case NUMERIC:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setDoubleValue((Double) value);\n break;\n }\n\n case BOOLEAN:\n {\n udf.setIntegerValue(BooleanHelper.getBoolean((Boolean) value) ? Integer.valueOf(1) : Integer.valueOf(0));\n break;\n }\n\n case INTEGER:\n case SHORT:\n {\n udf.setIntegerValue(NumberHelper.getInteger((Number) value));\n break;\n }\n\n default:\n {\n throw new RuntimeException(\"Unconvertible data type: \" + dataType);\n }\n }\n }",
"private static boolean hasSelfPermissions(Context context, String... permissions) {\n for (String permission : permissions) {\n if (checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) {\n return true;\n }\n }\n return false;\n }",
"@Override\n public final int getInt(final int i) {\n int val = this.array.optInt(i, Integer.MIN_VALUE);\n if (val == Integer.MIN_VALUE) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return val;\n }",
"public static base_responses unset(nitro_service client, String trapname[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (trapname != null && trapname.length > 0) {\n\t\t\tsnmpalarm unsetresources[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++){\n\t\t\t\tunsetresources[i] = new snmpalarm();\n\t\t\t\tunsetresources[i].trapname = trapname[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}"
] |
Seeks to the given season within the given year
@param seasonString
@param yearString | [
"public void seekToSeasonYear(String seasonString, String yearString) {\n Season season = Season.valueOf(seasonString);\n assert(season != null);\n \n seekToIcsEventYear(SEASON_ICS_FILE, yearString, season.getSummary());\n }"
] | [
"public void setNearClippingDistance(float near) {\n if(leftCamera instanceof GVRCameraClippingDistanceInterface &&\n centerCamera instanceof GVRCameraClippingDistanceInterface &&\n rightCamera instanceof GVRCameraClippingDistanceInterface) {\n ((GVRCameraClippingDistanceInterface)leftCamera).setNearClippingDistance(near);\n centerCamera.setNearClippingDistance(near);\n ((GVRCameraClippingDistanceInterface)rightCamera).setNearClippingDistance(near);\n }\n }",
"public static base_response restart(nitro_service client) throws Exception {\n\t\tdbsmonitors restartresource = new dbsmonitors();\n\t\treturn restartresource.perform_operation(client,\"restart\");\n\t}",
"public byte[] getPacketBytes() {\n byte[] result = new byte[packetBytes.length];\n System.arraycopy(packetBytes, 0, result, 0, packetBytes.length);\n return result;\n }",
"public float DistanceTo(IntPoint anotherPoint) {\r\n float dx = this.x - anotherPoint.x;\r\n float dy = this.y - anotherPoint.y;\r\n\r\n return (float) Math.sqrt(dx * dx + dy * dy);\r\n }",
"private static boolean scanForEndSig(File file, FileChannel channel) throws IOException, NonScannableZipException {\n\n // TODO Consider just reading in MAX_REVERSE_SCAN bytes -- increased peak memory cost but less complex\n\n ByteBuffer bb = getByteBuffer(CHUNK_SIZE);\n long start = channel.size();\n long end = Math.max(0, start - MAX_REVERSE_SCAN);\n long channelPos = Math.max(0, start - CHUNK_SIZE);\n long lastChannelPos = channelPos;\n boolean firstRead = true;\n while (lastChannelPos >= end) {\n\n read(bb, channel, channelPos);\n\n int actualRead = bb.limit();\n if (firstRead) {\n long expectedRead = Math.min(CHUNK_SIZE, start);\n if (actualRead > expectedRead) {\n // File is still growing\n return false;\n }\n firstRead = false;\n }\n\n int bufferPos = actualRead -1;\n while (bufferPos >= SIG_PATTERN_LENGTH) {\n\n // Following is based on the Boyer Moore algorithm but simplified to reflect\n // a) the pattern is static\n // b) the pattern has no repeating bytes\n\n int patternPos;\n for (patternPos = SIG_PATTERN_LENGTH - 1;\n patternPos >= 0 && ENDSIG_PATTERN[patternPos] == bb.get(bufferPos - patternPos);\n --patternPos) {\n // empty loop while bytes match\n }\n\n // Switch gives same results as checking the \"good suffix array\" in the Boyer Moore algorithm\n switch (patternPos) {\n case -1: {\n // Pattern matched. Confirm is this is the start of a valid end of central dir record\n long startEndRecord = channelPos + bufferPos - SIG_PATTERN_LENGTH + 1;\n if (validateEndRecord(file, channel, startEndRecord)) {\n return true;\n }\n // wasn't a valid end record; continue scan\n bufferPos -= 4;\n break;\n }\n case 3: {\n // No bytes matched; the common case.\n // With our pattern, this is the only case where the Boyer Moore algorithm's \"bad char array\" may\n // produce a shift greater than the \"good suffix array\" (which would shift 1 byte)\n int idx = bb.get(bufferPos - patternPos) - Byte.MIN_VALUE;\n bufferPos -= END_BAD_BYTE_SKIP[idx];\n break;\n }\n default:\n // 1 or more bytes matched\n bufferPos -= 4;\n }\n }\n\n // Move back a full chunk. If we didn't read a full chunk, that's ok,\n // it means we read all data and the outer while loop will terminate\n if (channelPos <= bufferPos) {\n break;\n }\n lastChannelPos = channelPos;\n channelPos -= Math.min(channelPos - bufferPos, CHUNK_SIZE - bufferPos);\n }\n\n return false;\n }",
"private String[] getFksToThisClass()\r\n {\r\n String indTable = getCollectionDescriptor().getIndirectionTable();\r\n String[] fks = getCollectionDescriptor().getFksToThisClass();\r\n String[] result = new String[fks.length];\r\n\r\n for (int i = 0; i < result.length; i++)\r\n {\r\n result[i] = indTable + \".\" + fks[i];\r\n }\r\n\r\n return result;\r\n }",
"private synchronized void closeIdleClients() {\n List<Client> candidates = new LinkedList<Client>(openClients.values());\n logger.debug(\"Scanning for idle clients; \" + candidates.size() + \" candidates.\");\n for (Client client : candidates) {\n if ((useCounts.get(client) < 1) &&\n ((timestamps.get(client) + idleLimit.get() * 1000) <= System.currentTimeMillis())) {\n logger.debug(\"Idle time reached for unused client {}\", client);\n closeClient(client);\n }\n }\n }",
"private int tryAcquireExclusiveTransaction(@NotNull final Thread thread, final int timeout) {\n long nanos = TimeUnit.MILLISECONDS.toNanos(timeout);\n try (CriticalSection ignored = criticalSection.enter()) {\n if (getThreadPermits(thread) > 0) {\n throw new ExodusException(\"Exclusive transaction can't be nested\");\n }\n final Condition condition = criticalSection.newCondition();\n final long currentOrder = acquireOrder++;\n regularQueue.put(currentOrder, condition);\n while (acquiredPermits > 0 || regularQueue.firstKey() != currentOrder) {\n try {\n nanos = condition.awaitNanos(nanos);\n if (nanos < 0) {\n break;\n }\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n break;\n }\n }\n if (acquiredPermits == 0 && regularQueue.firstKey() == currentOrder) {\n regularQueue.pollFirstEntry();\n acquiredPermits = availablePermits;\n threadPermits.put(thread, availablePermits);\n return availablePermits;\n }\n regularQueue.remove(currentOrder);\n notifyNextWaiters();\n }\n return 0;\n }",
"public boolean hasDeploymentSubsystemModel(final String subsystemName) {\n final Resource root = deploymentUnit.getAttachment(DEPLOYMENT_RESOURCE);\n final PathElement subsystem = PathElement.pathElement(SUBSYSTEM, subsystemName);\n return root.hasChild(subsystem);\n }"
] |
Get a discount curve from the model, if not existing create a discount curve.
@param discountCurveName The name of the discount curve to create.
@return The discount factor curve associated with the given name. | [
"private DiscountCurve createDiscountCurve(String discountCurveName) {\n\t\tDiscountCurve discountCurve\t= model.getDiscountCurve(discountCurveName);\n\t\tif(discountCurve == null) {\n\t\t\tdiscountCurve = DiscountCurveInterpolation.createDiscountCurveFromDiscountFactors(discountCurveName, new double[] { 0.0 }, new double[] { 1.0 });\n\t\t\tmodel = model.addCurves(discountCurve);\n\t\t}\n\n\t\treturn discountCurve;\n\t}"
] | [
"private static boolean equalAsInts(Vec2d a, Vec2d b) {\n return ((int) a.x) == ((int) b.x) && ((int) a.y) == ((int) b.y);\n }",
"public File curDir() {\n File file = session().attribute(ATTR_PWD);\n if (null == file) {\n file = new File(System.getProperty(\"user.dir\"));\n session().attribute(ATTR_PWD, file);\n }\n return file;\n }",
"public DockerContainerObjectBuilder<T> withContainerObjectClass(Class<T> containerObjectClass) {\n if (containerObjectClass == null) {\n throw new IllegalArgumentException(\"container object class cannot be null\");\n }\n this.containerObjectClass = containerObjectClass;\n\n //First we check if this ContainerObject is defining a @CubeDockerFile in static method\n final List<Method> methodsWithCubeDockerFile =\n ReflectionUtil.getMethodsWithAnnotation(containerObjectClass, CubeDockerFile.class);\n\n if (methodsWithCubeDockerFile.size() > 1) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Methods where annotation was found are: %s\",\n CubeDockerFile.class.getSimpleName(), methodsWithCubeDockerFile));\n }\n\n classHasMethodWithCubeDockerFile = !methodsWithCubeDockerFile.isEmpty();\n classDefinesCubeDockerFile = containerObjectClass.isAnnotationPresent(CubeDockerFile.class);\n classDefinesImage = containerObjectClass.isAnnotationPresent(Image.class);\n\n if (classHasMethodWithCubeDockerFile) {\n methodWithCubeDockerFile = methodsWithCubeDockerFile.get(0);\n boolean isMethodStatic = Modifier.isStatic(methodWithCubeDockerFile.getModifiers());\n boolean methodHasNoArguments = methodWithCubeDockerFile.getParameterCount() == 0;\n boolean methodReturnsAnArchive = Archive.class.isAssignableFrom(methodWithCubeDockerFile.getReturnType());\n if (!isMethodStatic || !methodHasNoArguments || !methodReturnsAnArchive) {\n throw new IllegalArgumentException(\n String.format(\"Method %s annotated with %s is expected to be static, no args and return %s.\",\n methodWithCubeDockerFile, CubeDockerFile.class.getSimpleName(), Archive.class.getSimpleName()));\n }\n }\n\n // User has defined @CubeDockerfile on the class and a method\n if (classHasMethodWithCubeDockerFile && classDefinesCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Both class and method %s has the annotation.\",\n CubeDockerFile.class.getSimpleName(), methodWithCubeDockerFile));\n }\n\n // User has defined @CubeDockerfile and @Image\n if ((classHasMethodWithCubeDockerFile || classDefinesCubeDockerFile) && classDefinesImage) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s has defined %s annotation and %s annotation together.\",\n containerObjectClass.getSimpleName(), Image.class.getSimpleName(),\n CubeDockerFile.class.getSimpleName()));\n }\n\n // User has not defined either @CubeDockerfile or @Image\n if (!classDefinesCubeDockerFile && !classDefinesImage && !classHasMethodWithCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s is not annotated with either %s or %s annotations.\",\n containerObjectClass.getName(), CubeDockerFile.class.getSimpleName(), Image.class.getSimpleName()));\n }\n\n return this;\n }",
"private void onConnectionClose(final Connection closed) {\n synchronized (this) {\n if(connection == closed) {\n connection = null;\n if(shutdown) {\n connectTask = DISCONNECTED;\n return;\n }\n final ConnectTask previous = connectTask;\n connectTask = previous.connectionClosed();\n }\n }\n }",
"@Override\n public void run()\n {\n try {\n startBarrier.await();\n\n int idleCount = 0;\n while (!isRunning.compareAndSet(idleCount > LINGER_ITERATIONS && deadPool.isEmpty() && completionKeyToProcessMap.isEmpty(), false)) {\n idleCount = (!shutdown && process()) ? 0 : (idleCount + 1);\n }\n }\n catch (Exception e) {\n // TODO: how to handle this error?\n e.printStackTrace();\n isRunning.set(false);\n }\n }",
"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 }",
"private void addTraceForFrame(WebSocketFrame frame, String type) {\n\t\tMap<String, Object> trace = new LinkedHashMap<>();\n\t\ttrace.put(\"type\", type);\n\t\ttrace.put(\"direction\", \"in\");\n\t\tif (frame instanceof TextWebSocketFrame) {\n\t\t\ttrace.put(\"payload\", ((TextWebSocketFrame) frame).text());\n\t\t}\n\n\t\tif (traceEnabled) {\n\t\t\twebsocketTraceRepository.add(trace);\n\t\t}\n\t}",
"public User getLimits() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIMITS);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element userElement = response.getPayload();\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"nsid\"));\r\n NodeList photoNodes = userElement.getElementsByTagName(\"photos\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element plElement = (Element) photoNodes.item(i);\r\n PhotoLimits pl = new PhotoLimits();\r\n user.setPhotoLimits(pl);\r\n pl.setMaxDisplay(plElement.getAttribute(\"maxdisplaypx\"));\r\n pl.setMaxUpload(plElement.getAttribute(\"maxupload\"));\r\n }\r\n NodeList videoNodes = userElement.getElementsByTagName(\"videos\");\r\n for (int i = 0; i < videoNodes.getLength(); i++) {\r\n Element vlElement = (Element) videoNodes.item(i);\r\n VideoLimits vl = new VideoLimits();\r\n user.setPhotoLimits(vl);\r\n vl.setMaxDuration(vlElement.getAttribute(\"maxduration\"));\r\n vl.setMaxUpload(vlElement.getAttribute(\"maxupload\"));\r\n }\r\n return user;\r\n }",
"@Override\n public AccountingDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }"
] |
Answer true if an Iterator for a Table is already available
@param aTable
@return | [
"public boolean containsIteratorForTable(String aTable)\r\n {\r\n boolean result = false;\r\n\r\n if (m_rsIterators != null)\r\n {\r\n for (int i = 0; i < m_rsIterators.size(); i++)\r\n {\r\n OJBIterator it = (OJBIterator) m_rsIterators.get(i);\r\n if (it instanceof RsIterator)\r\n {\r\n if (((RsIterator) it).getClassDescriptor().getFullTableName().equals(aTable))\r\n {\r\n result = true;\r\n break;\r\n }\r\n }\r\n else if (it instanceof ChainingIterator)\r\n {\r\n result = ((ChainingIterator) it).containsIteratorForTable(aTable);\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n }"
] | [
"public void processReference(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n XClass type = OjbMemberTagsHandler.getMemberType();\r\n int dim = OjbMemberTagsHandler.getMemberDimension();\r\n ReferenceDescriptorDef refDef = _curClassDef.getReference(name);\r\n String attrName;\r\n\r\n if (refDef == null)\r\n {\r\n refDef = new ReferenceDescriptorDef(name);\r\n _curClassDef.addReference(refDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processReference\", \" Processing reference \"+refDef.getName());\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n refDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n // storing default info for later use\r\n if (type == null)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_DETERMINE_TYPE_OF_MEMBER,\r\n new String[]{name}));\r\n }\r\n if (dim > 0)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.MEMBER_CANNOT_BE_A_REFERENCE,\r\n new String[]{name, _curClassDef.getName()}));\r\n }\r\n\r\n refDef.setProperty(PropertyHelper.OJB_PROPERTY_VARIABLE_TYPE, type.getQualifiedName());\r\n\r\n // searching for default type\r\n String typeName = searchForPersistentSubType(type);\r\n\r\n if (typeName != null)\r\n {\r\n refDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CLASS_REF, typeName);\r\n }\r\n\r\n _curReferenceDef = refDef;\r\n generate(template);\r\n _curReferenceDef = null;\r\n }",
"public Where<T, ID> gt(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.GREATER_THAN_OPERATION));\n\t\treturn this;\n\t}",
"public static sslservice get(nitro_service service, String servicename) throws Exception{\n\t\tsslservice obj = new sslservice();\n\t\tobj.set_servicename(servicename);\n\t\tsslservice response = (sslservice) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static File createTempDirectory(String prefix) {\n\tFile temp = null;\n\t\n\ttry {\n\t temp = File.createTempFile(prefix != null ? prefix : \"temp\", Long.toString(System.nanoTime()));\n\t\n\t if (!(temp.delete())) {\n\t throw new IOException(\"Could not delete temp file: \"\n\t\t + temp.getAbsolutePath());\n\t }\n\t\n\t if (!(temp.mkdir())) {\n\t throw new IOException(\"Could not create temp directory: \"\n\t + temp.getAbsolutePath());\n\t }\n\t} catch (IOException e) {\n\t throw new DukeException(\"Unable to create temporary directory with prefix \" + prefix, e);\n\t}\n\t\n\treturn temp;\n }",
"private void processAnalytics() throws SQLException\n {\n allocateConnection();\n\n try\n {\n DatabaseMetaData meta = m_connection.getMetaData();\n String productName = meta.getDatabaseProductName();\n if (productName == null || productName.isEmpty())\n {\n productName = \"DATABASE\";\n }\n else\n {\n productName = productName.toUpperCase();\n }\n\n ProjectProperties properties = m_reader.getProject().getProjectProperties();\n properties.setFileApplication(\"Primavera\");\n properties.setFileType(productName);\n }\n\n finally\n {\n releaseConnection();\n }\n }",
"public static Integer convertProfileIdentifier(String profileIdentifier) throws Exception {\n Integer profileId = -1;\n if (profileIdentifier == null) {\n throw new Exception(\"A profileIdentifier must be specified\");\n } else {\n try {\n profileId = Integer.parseInt(profileIdentifier);\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n // try to get it by name instead\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n\n }\n }\n logger.info(\"Profile id is {}\", profileId);\n return profileId;\n }",
"public void process()\n {\n if (m_data != null)\n {\n int index = 0;\n int offset = 0;\n // First the length (repeated twice)\n int length = MPPUtility.getInt(m_data, offset);\n offset += 8;\n // Then the number of custom columns\n int numberOfAliases = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n // Then the aliases themselves\n while (index < numberOfAliases && offset < length)\n {\n // Each item consists of the Field ID (2 bytes), 40 0B marker (2 bytes), and the\n // offset to the string (4 bytes)\n\n // Get the Field ID\n int fieldID = MPPUtility.getInt(m_data, offset);\n offset += 4;\n // Get the alias offset (offset + 4 for some reason).\n int aliasOffset = MPPUtility.getInt(m_data, offset) + 4;\n offset += 4;\n // Read the alias itself\n if (aliasOffset < m_data.length)\n {\n String alias = MPPUtility.getUnicodeString(m_data, aliasOffset);\n m_fields.getCustomField(FieldTypeHelper.getInstance(fieldID)).setAlias(alias);\n }\n index++;\n }\n }\n }",
"public Style createStyle(final List<Rule> styleRules) {\n final Rule[] rulesArray = styleRules.toArray(new Rule[0]);\n final FeatureTypeStyle featureTypeStyle = this.styleBuilder.createFeatureTypeStyle(null, rulesArray);\n final Style style = this.styleBuilder.createStyle();\n style.featureTypeStyles().add(featureTypeStyle);\n return style;\n }",
"public ItemDocumentBuilder withSiteLink(String title, String siteKey,\n\t\t\tItemIdValue... badges) {\n\t\twithSiteLink(factory.getSiteLink(title, siteKey, Arrays.asList(badges)));\n\t\treturn this;\n\t}"
] |
Return true if the class name is associated to an hidden class or matches a hide expression | [
"private boolean hidden(String className) {\n\tclassName = removeTemplate(className);\n\tClassInfo ci = classnames.get(className);\n\treturn ci != null ? ci.hidden : optionProvider.getOptionsFor(className).matchesHideExpression(className);\n }"
] | [
"protected Renderer build() {\n validateAttributes();\n\n Renderer renderer;\n if (isRecyclable(convertView, content)) {\n renderer = recycle(convertView, content);\n } else {\n renderer = createRenderer(content, parent);\n }\n return renderer;\n }",
"public static boolean hasAnnotation(Method method, Class<? extends Annotation> annotation) {\n return !searchForAnnotation(method, annotation).isEmpty();\n }",
"public InputStream getStream(String url, RasterLayer layer) throws IOException {\n\t\tif (layer instanceof ProxyLayerSupport) {\n\t\t\tProxyLayerSupport proxyLayer = (ProxyLayerSupport) layer;\n\t\t\tif (proxyLayer.isUseCache() && null != cacheManagerService) {\n\t\t\t\tObject cachedObject = cacheManagerService.get(proxyLayer, CacheCategory.RASTER, url);\n\t\t\t\tif (null != cachedObject) {\n\t\t\t\t\ttestRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_GET_FROM_CACHE);\n\t\t\t\t\treturn new ByteArrayInputStream((byte[]) cachedObject);\n\t\t\t\t} else {\n\t\t\t\t\ttestRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_PUT_IN_CACHE);\n\t\t\t\t\tInputStream stream = super.getStream(url, proxyLayer);\n\t\t\t\t\tByteArrayOutputStream os = new ByteArrayOutputStream();\n\t\t\t\t\tint b;\n\t\t\t\t\twhile ((b = stream.read()) >= 0) {\n\t\t\t\t\t\tos.write(b);\n\t\t\t\t\t}\n\t\t\t\t\tcacheManagerService.put(proxyLayer, CacheCategory.RASTER, url, os.toByteArray(),\n\t\t\t\t\t\t\tgetLayerEnvelope(proxyLayer));\n\t\t\t\t\treturn new ByteArrayInputStream((byte[]) os.toByteArray());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn super.getStream(url, layer);\n\t}",
"private void initPatternButtonGroup() {\n\n m_groupPattern = new CmsRadioButtonGroup();\n m_patternButtons = new HashMap<>();\n\n createAndAddButton(PatternType.DAILY, Messages.GUI_SERIALDATE_TYPE_DAILY_0);\n m_patternButtons.put(PatternType.NONE, m_patternButtons.get(PatternType.DAILY));\n createAndAddButton(PatternType.WEEKLY, Messages.GUI_SERIALDATE_TYPE_WEEKLY_0);\n createAndAddButton(PatternType.MONTHLY, Messages.GUI_SERIALDATE_TYPE_MONTHLY_0);\n createAndAddButton(PatternType.YEARLY, Messages.GUI_SERIALDATE_TYPE_YEARLY_0);\n // createAndAddButton(PatternType.INDIVIDUAL, Messages.GUI_SERIALDATE_TYPE_INDIVIDUAL_0);\n\n m_groupPattern.addValueChangeHandler(new ValueChangeHandler<String>() {\n\n public void onValueChange(ValueChangeEvent<String> event) {\n\n if (handleChange()) {\n String value = event.getValue();\n if (value != null) {\n m_controller.setPattern(value);\n }\n }\n }\n });\n\n }",
"private Class getDynamicProxyClass(Class baseClass) {\r\n Class[] m_dynamicProxyClassInterfaces;\r\n if (foundInterfaces.containsKey(baseClass)) {\r\n m_dynamicProxyClassInterfaces = (Class[])foundInterfaces.get(baseClass);\r\n } else {\r\n m_dynamicProxyClassInterfaces = getInterfaces(baseClass);\r\n foundInterfaces.put(baseClass, m_dynamicProxyClassInterfaces);\r\n }\r\n\r\n // return dynymic Proxy Class implementing all interfaces\r\n Class proxyClazz = Proxy.getProxyClass(baseClass.getClassLoader(), m_dynamicProxyClassInterfaces);\r\n return proxyClazz;\r\n }",
"@Override\n protected void initBuilderSpecific() throws Exception {\n reset();\n FilePath workspace = getModuleRoot(EnvVars.masterEnvVars);\n FilePath gradlePropertiesPath = new FilePath(workspace, \"gradle.properties\");\n if (releaseProps == null) {\n releaseProps = PropertyUtils.getModulesPropertiesFromPropFile(gradlePropertiesPath, getReleaseProperties());\n }\n if (nextIntegProps == null) {\n nextIntegProps =\n PropertyUtils.getModulesPropertiesFromPropFile(gradlePropertiesPath, getNextIntegProperties());\n }\n }",
"private void loadAllRemainingLocalizations() throws CmsException, UnsupportedEncodingException, IOException {\n\n if (!m_alreadyLoadedAllLocalizations) {\n // is only necessary for property bundles\n if (m_bundleType.equals(BundleType.PROPERTY)) {\n for (Locale l : m_locales) {\n if (null == m_localizations.get(l)) {\n CmsResource resource = m_bundleFiles.get(l);\n if (resource != null) {\n CmsFile file = m_cms.readFile(resource);\n m_bundleFiles.put(l, file);\n SortedProperties props = new SortedProperties();\n props.load(\n new InputStreamReader(\n new ByteArrayInputStream(file.getContents()),\n CmsFileUtil.getEncoding(m_cms, file)));\n m_localizations.put(l, props);\n }\n }\n }\n }\n if (m_bundleType.equals(BundleType.XML)) {\n for (Locale l : m_locales) {\n if (null == m_localizations.get(l)) {\n loadLocalizationFromXmlBundle(l);\n }\n }\n }\n m_alreadyLoadedAllLocalizations = true;\n }\n\n }",
"@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static int checkInteger(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInIntegerRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), INTEGER_MIN, INTEGER_MAX);\n\t\t}\n\n\t\treturn number.intValue();\n\t}",
"public SourceBuilder add(String fmt, Object... args) {\n TemplateApplier.withParams(args).onText(source::append).onParam(this::add).parse(fmt);\n return this;\n }"
] |
Sets the matrix 'inv' equal to the inverse of the matrix that was decomposed.
@param inv Where the value of the inverse will be stored. Modified. | [
"@Override\n public void invert( ZMatrixRMaj inv ) {\n if( inv.numRows != n || inv.numCols != n ) {\n throw new RuntimeException(\"Unexpected matrix dimension\");\n }\n if( inv.data == t ) {\n throw new IllegalArgumentException(\"Passing in the same matrix that was decomposed.\");\n }\n\n if(decomposer.isLower()) {\n setToInverseL(inv.data);\n } else {\n throw new RuntimeException(\"Implement\");\n }\n }"
] | [
"public void initSize(Rectangle rectangle) {\n\t\ttemplate = writer.getDirectContent().createTemplate(rectangle.getWidth(), rectangle.getHeight());\n\t}",
"private void buildTransformers_3_0(ResourceTransformationDescriptionBuilder builder) {\n /*\n ====== Resource root address: [\"subsystem\" => \"remoting\"] - Current version: 4.0.0; legacy version: 3.0.0 =======\n --- Problems for relative address to root [\"configuration\" => \"endpoint\"]:\n Different 'default' for attribute 'sasl-protocol'. Current: \"remote\"; legacy: \"remoting\" ## both are valid also for legacy servers\n --- Problems for relative address to root [\"connector\" => \"*\"]:\n Missing attributes in current: []; missing in legacy [sasl-authentication-factory, ssl-context]\n Missing parameters for operation 'add' in current: []; missing in legacy [sasl-authentication-factory, ssl-context]\n --- Problems for relative address to root [\"http-connector\" => \"*\"]:\n Missing attributes in current: []; missing in legacy [sasl-authentication-factory]\n Missing parameters for operation 'add' in current: []; missing in legacy [sasl-authentication-factory]\n --- Problems for relative address to root [\"remote-outbound-connection\" => \"*\"]:\n Missing attributes in current: []; missing in legacy [authentication-context]\n Different 'alternatives' for attribute 'protocol'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for attribute 'security-realm'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for attribute 'username'. Current: [\"authentication-context\"]; legacy: undefined\n Missing parameters for operation 'add' in current: []; missing in legacy [authentication-context]\n Different 'alternatives' for parameter 'protocol' of operation 'add'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for parameter 'security-realm' of operation 'add'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for parameter 'username' of operation 'add'. Current: [\"authentication-context\"]; legacy: undefined\n */\n\n builder.addChildResource(ConnectorResource.PATH).getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY, ConnectorResource.SSL_CONTEXT)\n .addRejectCheck(RejectAttributeChecker.DEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY, ConnectorResource.SSL_CONTEXT);\n\n builder.addChildResource(RemotingEndpointResource.ENDPOINT_PATH).getAttributeBuilder()\n .setValueConverter(new AttributeConverter.DefaultAttributeConverter() {\n @Override\n protected void convertAttribute(PathAddress address, String attributeName, ModelNode attributeValue, TransformationContext context) {\n if (!attributeValue.isDefined()) {\n attributeValue.set(\"remoting\"); //if value is not defined, set it to EAP 7.0 default valueRemotingSubsystemTransformersTestCase\n }\n }\n }, RemotingSubsystemRootResource.SASL_PROTOCOL);\n\n builder.addChildResource(HttpConnectorResource.PATH).getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY)\n .addRejectCheck(RejectAttributeChecker.DEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY);\n\n builder.addChildResource(RemoteOutboundConnectionResourceDefinition.ADDRESS).getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY)\n .addRejectCheck(RejectAttributeChecker.DEFINED, RemoteOutboundConnectionResourceDefinition.AUTHENTICATION_CONTEXT);\n }",
"public static String marshal(Object object) {\n if (object == null) {\n return null;\n }\n\n try {\n JAXBContext jaxbCtx = JAXBContext.newInstance(object.getClass());\n\n Marshaller marshaller = jaxbCtx.createMarshaller();\n marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);\n\n StringWriter sw = new StringWriter();\n marshaller.marshal(object, sw);\n\n return sw.toString();\n } catch (Exception e) {\n }\n\n return null;\n }",
"public void addOrderedChildResourceTypes(PathAddress resourceAddress, Resource resource) {\n Set<String> orderedChildTypes = resource.getOrderedChildTypes();\n if (orderedChildTypes.size() > 0) {\n orderedChildren.put(resourceAddress, resource.getOrderedChildTypes());\n }\n }",
"public synchronized Response doCommandFullResponse(String command) throws CommandFormatException, IOException {\n ModelNode request = cmdCtx.buildRequest(command);\n boolean replacedBytes = replaceFilePathsWithBytes(request);\n OperationResponse response = execute(request, isSlowCommand(command) || replacedBytes);\n return new Response(command, request, response);\n }",
"private Serializable doWorkInIsolationTransaction(final SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\t\tclass Work extends AbstractReturningWork<IntegralDataTypeHolder> {\n\t\t\tprivate final SharedSessionContractImplementor localSession = session;\n\n\t\t\t@Override\n\t\t\tpublic IntegralDataTypeHolder execute(Connection connection) throws SQLException {\n\t\t\t\ttry {\n\t\t\t\t\treturn doWorkInCurrentTransactionIfAny( localSession );\n\t\t\t\t}\n\t\t\t\tcatch ( RuntimeException sqle ) {\n\t\t\t\t\tthrow new HibernateException( \"Could not get or update next value\", sqle );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//we want to work out of transaction\n\t\tboolean workInTransaction = false;\n\t\tWork work = new Work();\n\t\tSerializable generatedValue = session.getTransactionCoordinator().createIsolationDelegate().delegateWork( work, workInTransaction );\n\t\treturn generatedValue;\n\t}",
"public String addDependency(FunctionalTaskItem dependencyTaskItem) {\n IndexableTaskItem dependency = IndexableTaskItem.create(dependencyTaskItem);\n this.addDependency(dependency);\n return dependency.key();\n }",
"@SuppressWarnings(\"deprecation\")\n\tpublic static boolean isTimeInRange(java.sql.Time start, java.sql.Time end, java.util.Date d) {\n d = new java.sql.Time(d.getHours(), d.getMinutes(), d.getSeconds());\n\n if (start == null || end == null) {\n return false;\n }\n\n if (start.before(end) && (!(d.after(start) && d.before(end)))) {\n return false;\n }\n\n if (end.before(start) && (!(d.after(end) || d.before(start)))) {\n return false;\n }\n return true;\n }",
"private static Set<String> imageOrientationsOf(ImageMetadata metadata) {\n\n String exifIFD0DirName = new ExifIFD0Directory().getName();\n\n Tag[] tags = Arrays.stream(metadata.getDirectories())\n .filter(dir -> dir.getName().equals(exifIFD0DirName))\n .findFirst()\n .map(Directory::getTags)\n .orElseGet(() -> new Tag[0]);\n\n return Arrays.stream(tags)\n .filter(tag -> tag.getType() == 274)\n .map(Tag::getRawValue)\n .collect(Collectors.toSet());\n }"
] |
Facade method for operating the Unix-like terminal supporting line editing and command
history.
@param prompt Prompt to be displayed
@param appName The app name string
@param mainHandler Main command handler
@param input Input stream.
@param output Output stream.
@return Shell that can be either further customized or run directly by calling commandLoop(). | [
"static Shell createTerminalConsoleShell(String prompt, String appName,\n ShellCommandHandler mainHandler, InputStream input, OutputStream output) {\n try {\n PrintStream out = new PrintStream(output);\n\n // Build jline terminal\n jline.Terminal term = TerminalFactory.get();\n final ConsoleReader console = new ConsoleReader(input, output, term);\n console.setBellEnabled(true);\n console.setHistoryEnabled(true);\n\n // Build console\n BufferedReader in = new BufferedReader(new InputStreamReader(\n new ConsoleReaderInputStream(console)));\n\n ConsoleIO.PromptListener promptListener = new ConsoleIO.PromptListener() {\n @Override\n public boolean onPrompt(String prompt) {\n console.setPrompt(prompt);\n return true; // suppress normal prompt\n }\n };\n\n return createConsoleShell(prompt, appName, mainHandler, in, out, out, promptListener);\n } catch (Exception e) {\n // Failover: use default shell\n BufferedReader in = new BufferedReader(new InputStreamReader(input));\n PrintStream out = new PrintStream(output);\n\n return createConsoleShell(prompt, appName, mainHandler, in, out, out, null);\n }\n }"
] | [
"public void handleChange(Object propertyId) {\n\n try {\n lockOnChange(propertyId);\n } catch (CmsException e) {\n LOG.debug(e);\n }\n if (isDescriptorProperty(propertyId)) {\n m_descriptorHasChanges = true;\n }\n if (isBundleProperty(propertyId)) {\n m_changedTranslations.add(getLocale());\n }\n\n }",
"public void addNamespace(final MongoNamespace namespace) {\n this.instanceLock.writeLock().lock();\n try {\n if (this.nsStreamers.containsKey(namespace)) {\n return;\n }\n final NamespaceChangeStreamListener streamer =\n new NamespaceChangeStreamListener(\n namespace,\n instanceConfig.getNamespaceConfig(namespace),\n service,\n networkMonitor,\n authMonitor,\n getLockForNamespace(namespace));\n this.nsStreamers.put(namespace, streamer);\n } finally {\n this.instanceLock.writeLock().unlock();\n }\n }",
"public static 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 }",
"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 static dnstxtrec[] get(nitro_service service) throws Exception{\n\t\tdnstxtrec obj = new dnstxtrec();\n\t\tdnstxtrec[] response = (dnstxtrec[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static String toBinaryString(byte[] bytes) {\n StringBuilder buffer = new StringBuilder();\n for(byte b: bytes) {\n String bin = Integer.toBinaryString(0xFF & b);\n bin = bin.substring(0, Math.min(bin.length(), 8));\n\n for(int j = 0; j < 8 - bin.length(); j++) {\n buffer.append('0');\n }\n\n buffer.append(bin);\n }\n return buffer.toString();\n }",
"public boolean getBooleanProperty(String name, boolean defaultValue)\r\n {\r\n return PropertyHelper.toBoolean(_properties.getProperty(name), defaultValue);\r\n }",
"public static String constructUrl(final HttpServerExchange exchange, final String path) {\n final HeaderMap headers = exchange.getRequestHeaders();\n String host = headers.getFirst(HOST);\n String protocol = exchange.getConnection().getSslSessionInfo() != null ? \"https\" : \"http\";\n\n return protocol + \"://\" + host + path;\n }",
"private boolean isAllNumeric(TokenStream stream) {\n List<Token> tokens = ((NattyTokenSource) stream.getTokenSource()).getTokens();\n for(Token token:tokens) {\n try {\n Integer.parseInt(token.getText());\n } catch(NumberFormatException e) {\n return false;\n }\n }\n return true;\n }"
] |
Retrieve a boolean value.
@param name column name
@return boolean value | [
"public final boolean getBoolean(String name)\n {\n boolean result = false;\n Boolean value = (Boolean) getObject(name);\n if (value != null)\n {\n result = BooleanHelper.getBoolean(value);\n }\n return result;\n }"
] | [
"protected void updateStep(int stepNo) {\n\n if ((0 <= stepNo) && (stepNo < m_steps.size())) {\n Class<? extends A_CmsSetupStep> cls = m_steps.get(stepNo);\n A_CmsSetupStep step;\n try {\n step = cls.getConstructor(I_SetupUiContext.class).newInstance(this);\n showStep(step);\n m_stepNo = stepNo; // Only update step number if no exceptions\n } catch (Exception e) {\n CmsSetupErrorDialog.showErrorDialog(e);\n }\n\n }\n }",
"private void writeDateField(String fieldName, Object value) throws IOException\n {\n if (value instanceof String)\n {\n m_writer.writeNameValuePair(fieldName + \"_text\", (String) value);\n }\n else\n {\n Date val = (Date) value;\n m_writer.writeNameValuePair(fieldName, val);\n }\n }",
"protected void associateBatched(Collection owners, Collection children)\r\n {\r\n ObjectReferenceDescriptor ord = getObjectReferenceDescriptor();\r\n ClassDescriptor cld = getOwnerClassDescriptor();\r\n Object owner;\r\n Object relatedObject;\r\n Object fkValues[];\r\n Identity id;\r\n PersistenceBroker pb = getBroker();\r\n PersistentField field = ord.getPersistentField();\r\n Class topLevelClass = pb.getTopLevelClass(ord.getItemClass());\r\n HashMap childrenMap = new HashMap(children.size());\r\n\r\n\r\n for (Iterator it = children.iterator(); it.hasNext(); )\r\n {\r\n relatedObject = it.next();\r\n childrenMap.put(pb.serviceIdentity().buildIdentity(relatedObject), relatedObject);\r\n }\r\n\r\n for (Iterator it = owners.iterator(); it.hasNext(); )\r\n {\r\n owner = it.next();\r\n fkValues = ord.getForeignKeyValues(owner,cld);\r\n if (isNull(fkValues))\r\n {\r\n field.set(owner, null);\r\n continue;\r\n }\r\n id = pb.serviceIdentity().buildIdentity(null, topLevelClass, fkValues);\r\n relatedObject = childrenMap.get(id);\r\n field.set(owner, relatedObject);\r\n }\r\n }",
"public static gslbsite[] get(nitro_service service, String sitename[]) throws Exception{\n\t\tif (sitename !=null && sitename.length>0) {\n\t\t\tgslbsite response[] = new gslbsite[sitename.length];\n\t\t\tgslbsite obj[] = new gslbsite[sitename.length];\n\t\t\tfor (int i=0;i<sitename.length;i++) {\n\t\t\t\tobj[i] = new gslbsite();\n\t\t\t\tobj[i].set_sitename(sitename[i]);\n\t\t\t\tresponse[i] = (gslbsite) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"public static base_responses reset(nitro_service client, Interface resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tInterface resetresources[] = new Interface[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tresetresources[i] = new Interface();\n\t\t\t\tresetresources[i].id = resources[i].id;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, resetresources,\"reset\");\n\t\t}\n\t\treturn result;\n\t}",
"public boolean setUpCameraForVrMode(final int fpsMode) {\n\n cameraSetUpStatus = false;\n this.fpsMode = fpsMode;\n\n if (!isCameraOpen) {\n Log.e(TAG, \"Camera is not open\");\n return false;\n }\n if (fpsMode < 0 || fpsMode > 2) {\n Log.e(TAG,\n \"Invalid fpsMode: %d. It can only take values 0, 1, or 2.\", fpsMode);\n } else {\n Parameters params = camera.getParameters();\n\n // check if the device supports vr mode preview\n if (\"true\".equalsIgnoreCase(params.get(\"vrmode-supported\"))) {\n\n Log.v(TAG, \"VR Mode supported!\");\n\n // set vr mode\n params.set(\"vrmode\", 1);\n\n // true if the apps intend to record videos using\n // MediaRecorder\n params.setRecordingHint(true);\n\n // set preview size\n // params.setPreviewSize(640, 480);\n\n // set fast-fps-mode: 0 for 30fps, 1 for 60 fps,\n // 2 for 120 fps\n params.set(\"fast-fps-mode\", fpsMode);\n\n switch (fpsMode) {\n case 0: // 30 fps\n params.setPreviewFpsRange(30000, 30000);\n break;\n case 1: // 60 fps\n params.setPreviewFpsRange(60000, 60000);\n break;\n case 2: // 120 fps\n params.setPreviewFpsRange(120000, 120000);\n break;\n default:\n }\n\n // for auto focus\n params.set(\"focus-mode\", \"continuous-video\");\n\n params.setVideoStabilization(false);\n if (\"true\".equalsIgnoreCase(params.get(\"ois-supported\"))) {\n params.set(\"ois\", \"center\");\n }\n\n camera.setParameters(params);\n cameraSetUpStatus = true;\n }\n }\n\n return cameraSetUpStatus;\n }",
"public String findPlatformFor(String jdbcSubProtocol, String jdbcDriver)\r\n {\r\n String platform = (String)jdbcSubProtocolToPlatform.get(jdbcSubProtocol);\r\n\r\n if (platform == null)\r\n {\r\n platform = (String)jdbcDriverToPlatform.get(jdbcDriver);\r\n }\r\n return platform;\r\n }",
"@Override\n public final PArray getArray(final String key) {\n PArray result = optArray(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }",
"public static <T> void injectEEFields(Iterable<Set<ResourceInjection<?>>> resourceInjectionsHierarchy,\n T beanInstance, CreationalContext<T> ctx) {\n for (Set<ResourceInjection<?>> resourceInjections : resourceInjectionsHierarchy) {\n for (ResourceInjection<?> resourceInjection : resourceInjections) {\n resourceInjection.injectResourceReference(beanInstance, ctx);\n }\n }\n }"
] |
Use this API to unlink sslcertkey resources. | [
"public static base_responses unlink(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey unlinkresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunlinkresources[i] = new sslcertkey();\n\t\t\t\tunlinkresources[i].certkey = resources[i].certkey;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, unlinkresources,\"unlink\");\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public void each(int offset, int maxRows, Closure closure) throws SQLException {\n eachRow(getSql(), getParameters(), offset, maxRows, closure);\n }",
"public Query getCountQuery(Query aQuery)\r\n {\r\n if(aQuery instanceof QueryBySQL)\r\n {\r\n return getQueryBySqlCount((QueryBySQL) aQuery);\r\n }\r\n else if(aQuery instanceof ReportQueryByCriteria)\r\n {\r\n return getReportQueryByCriteriaCount((ReportQueryByCriteria) aQuery);\r\n }\r\n else\r\n {\r\n return getQueryByCriteriaCount((QueryByCriteria) aQuery);\r\n }\r\n }",
"public static String httpRequest(String stringUrl, String method, Map<String, String> parameters,\n String input, String charset) throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setDoOutput(true);\n conn.setRequestMethod(method);\n\n if (parameters != null) {\n for (Entry<String, String> entry : parameters.entrySet()) {\n conn.addRequestProperty(entry.getKey(), entry.getValue());\n }\n }\n\n if (input != null) {\n OutputStream output = null;\n try {\n output = conn.getOutputStream();\n output.write(input.getBytes(charset));\n } finally {\n if (output != null) {\n output.close();\n }\n }\n }\n\n return MyStreamUtils.readContent(conn.getInputStream());\n }",
"public static String getParentDirectory(String filePath) throws IllegalArgumentException {\n if (Pattern.matches(sPatternUrl, filePath))\n return getURLParentDirectory(filePath);\n\n return new File(filePath).getParent();\n }",
"public FormAction setValuesInForm(Form form) {\r\n\t\tFormAction formAction = new FormAction();\r\n\t\tform.setFormAction(formAction);\r\n\t\tthis.forms.add(form);\r\n\t\treturn formAction;\r\n\t}",
"public void transform(DataPipe cr) {\n for (Map.Entry<String, String> entry : cr.getDataMap().entrySet()) {\n String value = entry.getValue();\n\n if (value.equals(\"#{customplaceholder}\")) {\n // Generate a random number\n int ran = rand.nextInt();\n entry.setValue(String.valueOf(ran));\n }\n }\n }",
"public List<Widget> getAllViews() {\n List<Widget> views = new ArrayList<>();\n for (Widget child: mContent.getChildren()) {\n Widget item = ((ListItemHostWidget) child).getGuest();\n if (item != null) {\n views.add(item);\n }\n }\n return views;\n }",
"public T removeFile(final String name, final List<String> path, final byte[] existingHash, final boolean isDirectory) {\n return removeFile(name, path, existingHash, isDirectory, null);\n }",
"public void postConstruct() {\n parseGeometry();\n\n Assert.isTrue(this.polygon != null, \"Polygon is null. 'area' string is: '\" + this.area + \"'\");\n Assert.isTrue(this.display != null, \"'display' is null\");\n\n Assert.isTrue(this.style == null || this.display == AoiDisplay.RENDER,\n \"'style' does not make sense unless 'display' == RENDER. In this case 'display' == \" +\n this.display);\n }"
] |
Sets Idle max age.
The time, for a connection to remain unused before it is closed off. Do not use aggressive values here!
@param idleMaxAge time after which a connection is closed off
@param timeUnit idleMaxAge time granularity. | [
"public void setIdleMaxAge(long idleMaxAge, TimeUnit timeUnit) {\n\t\tthis.idleMaxAgeInSeconds = TimeUnit.SECONDS.convert(idleMaxAge, checkNotNull(timeUnit)); \n\t}"
] | [
"public static nsspparams get(nitro_service service) throws Exception{\n\t\tnsspparams obj = new nsspparams();\n\t\tnsspparams[] response = (nsspparams[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public Jar setJarPrefix(String value) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Really executable cannot be set after entries are added.\");\n if (value != null && jarPrefixFile != null)\n throw new IllegalStateException(\"A prefix has already been set (\" + jarPrefixFile + \")\");\n this.jarPrefixStr = value;\n return this;\n }",
"public static dnssuffix[] get(nitro_service service, String Dnssuffix[]) throws Exception{\n\t\tif (Dnssuffix !=null && Dnssuffix.length>0) {\n\t\t\tdnssuffix response[] = new dnssuffix[Dnssuffix.length];\n\t\t\tdnssuffix obj[] = new dnssuffix[Dnssuffix.length];\n\t\t\tfor (int i=0;i<Dnssuffix.length;i++) {\n\t\t\t\tobj[i] = new dnssuffix();\n\t\t\t\tobj[i].set_Dnssuffix(Dnssuffix[i]);\n\t\t\t\tresponse[i] = (dnssuffix) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"public void set( int index , double value ) {\n if( mat.getType() == MatrixType.DDRM ) {\n ((DMatrixRMaj) mat).set(index, value);\n } else if( mat.getType() == MatrixType.FDRM ) {\n ((FMatrixRMaj) mat).set(index, (float)value);\n } else {\n throw new RuntimeException(\"Not supported yet for this matrix type\");\n }\n }",
"public static DMatrixSparseTriplet uniform(int numRows , int numCols , int nz_total ,\n double min , double max , Random rand ) {\n // Create a list of all the possible element values\n int N = numCols*numRows;\n if( N < 0 )\n throw new IllegalArgumentException(\"matrix size is too large\");\n nz_total = Math.min(N,nz_total);\n\n int selected[] = new int[N];\n for (int i = 0; i < N; i++) {\n selected[i] = i;\n }\n\n for (int i = 0; i < nz_total; i++) {\n int s = rand.nextInt(N);\n int tmp = selected[s];\n selected[s] = selected[i];\n selected[i] = tmp;\n }\n\n // Create a sparse matrix\n DMatrixSparseTriplet ret = new DMatrixSparseTriplet(numRows,numCols,nz_total);\n\n for (int i = 0; i < nz_total; i++) {\n int row = selected[i]/numCols;\n int col = selected[i]%numCols;\n\n double value = rand.nextDouble()*(max-min)+min;\n\n ret.addItem(row,col, value);\n }\n\n return ret;\n }",
"public void deleteRedirect(int id) {\n try {\n sqlService.executeUpdate(\"DELETE FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_ID + \" = \" + id + \";\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }",
"public GroovyFieldDoc[] enumConstants() {\n Collections.sort(enumConstants);\n return enumConstants.toArray(new GroovyFieldDoc[enumConstants.size()]);\n }",
"public static base_response unset(nitro_service client, onlinkipv6prefix resource, String[] args) throws Exception{\n\t\tonlinkipv6prefix unsetresource = new onlinkipv6prefix();\n\t\tunsetresource.ipv6prefix = resource.ipv6prefix;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"private String addPathProperty(final List<String> command, final String typeName, final String propertyName, final Map<String, String> properties, final DirectoryGrouping directoryGrouping,\n final File typeDir, File serverDir) {\n final String result;\n final String value = properties.get(propertyName);\n if (value == null) {\n switch (directoryGrouping) {\n case BY_TYPE:\n result = getAbsolutePath(typeDir, \"servers\", serverName);\n break;\n case BY_SERVER:\n default:\n result = getAbsolutePath(serverDir, typeName);\n break;\n }\n properties.put(propertyName, result);\n } else {\n final File dir = new File(value);\n switch (directoryGrouping) {\n case BY_TYPE:\n result = getAbsolutePath(dir, \"servers\", serverName);\n break;\n case BY_SERVER:\n default:\n result = getAbsolutePath(dir, serverName);\n break;\n }\n }\n command.add(String.format(\"-D%s=%s\", propertyName, result));\n return result;\n }"
] |
Helper to get locale specific properties.
@return the locale specific properties map. | [
"private Map<String, String> getLocaleProperties() {\n\n if (m_localeProperties == null) {\n m_localeProperties = CmsCollectionsGenericWrapper.createLazyMap(\n new CmsProperty.CmsPropertyLocaleTransformer(m_properties, m_locale));\n }\n return m_localeProperties;\n }"
] | [
"protected boolean check(String value, String regex) {\n\t\tPattern pattern = Pattern.compile(regex);\n\t\treturn pattern.matcher(value).matches();\n\t}",
"public static String getExtension(String language) {\n language = language.toLowerCase();\n if(\"ecmascript\".equals(language)) {\n language = \"javascript\";\n }\n return extensions.get(language);\n }",
"public static void downloadUrl(String stringUrl, Map<String, String> parameters, File fileToSave)\n throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setFollowRedirects(true);\n \n if (parameters != null) {\n for (Entry<String, String> entry : parameters.entrySet()) {\n conn.addRequestProperty(entry.getKey(), entry.getValue());\n }\n }\n\n\n boolean redirect = false;\n\n // normally, 3xx is redirect\n int status = conn.getResponseCode();\n if (status != HttpURLConnection.HTTP_OK) {\n if (status == HttpURLConnection.HTTP_MOVED_TEMP\n || status == HttpURLConnection.HTTP_MOVED_PERM\n || status == HttpURLConnection.HTTP_SEE_OTHER)\n redirect = true;\n }\n\n if (redirect) {\n\n // get redirect url from \"location\" header field\n String newUrl = conn.getHeaderField(\"Location\");\n\n // get the cookie if need, for login\n String cookies = conn.getHeaderField(\"Set-Cookie\");\n\n // open the new connnection again\n conn = (HttpURLConnection) new URL(newUrl).openConnection();\n conn.setRequestProperty(\"Cookie\", cookies);\n\n }\n \n byte[] data = MyStreamUtils.readContentBytes(conn.getInputStream());\n FileOutputStream fos = new FileOutputStream(fileToSave);\n fos.write(data);\n fos.close();\n }",
"public void setDateMin(Date dateMin) {\n this.dateMin = dateMin;\n\n if (isAttached() && dateMin != null) {\n getPicker().set(\"min\", JsDate.create((double) dateMin.getTime()));\n }\n }",
"protected void processTusFiles(String assemblyUrl) throws IOException, ProtocolException {\n tusClient.setUploadCreationURL(new URL(getClient().getHostUrl() + \"/resumable/files/\"));\n tusClient.enableResuming(tusURLStore);\n\n for (Map.Entry<String, File> entry : files.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n\n for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n }",
"public String getHostName() {\n if( addr instanceof NbtAddress ) {\n return ((NbtAddress)addr).getHostName();\n }\n return ((InetAddress)addr).getHostName();\n }",
"public void prepareStatus() {\n globalLineCounter = new AtomicLong(0);\n time = new AtomicLong(System.currentTimeMillis());\n startTime = System.currentTimeMillis();\n lastCount = 0;\n\n // Status thread regularly reports on what is happening\n Thread statusThread = new Thread() {\n public void run() {\n while (true) {\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n System.out.println(\"Status thread interrupted\");\n }\n\n long thisTime = System.currentTimeMillis();\n long currentCount = globalLineCounter.get();\n\n if (thisTime - time.get() > 1000) {\n long oldTime = time.get();\n time.set(thisTime);\n double avgRate = 1000.0 * currentCount / (thisTime - startTime);\n double instRate = 1000.0 * (currentCount - lastCount) / (thisTime - oldTime);\n lastCount = currentCount;\n System.out.println(currentCount + \" AvgRage:\" + ((int) avgRate) + \" lines/sec instRate:\"\n + ((int) instRate) + \" lines/sec Unassigned Work: \"\n + remainingBlocks.get() + \" blocks\");\n }\n }\n }\n };\n statusThread.start();\n }",
"public static auditsyslogpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_lbvserver_binding obj = new auditsyslogpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_lbvserver_binding response[] = (auditsyslogpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static authenticationradiusaction get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\tobj.set_name(name);\n\t\tauthenticationradiusaction response = (authenticationradiusaction) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Determine whether or not a given serializedr is "AVRO" based
@param serializerName
@return | [
"public static boolean isAvroSchema(String serializerName) {\n if(serializerName.equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)\n || serializerName.equals(AVRO_GENERIC_TYPE_NAME)\n || serializerName.equals(AVRO_REFLECTIVE_TYPE_NAME)\n || serializerName.equals(AVRO_SPECIFIC_TYPE_NAME)) {\n return true;\n } else {\n return false;\n }\n }"
] | [
"public static systemuser get(nitro_service service, String username) throws Exception{\n\t\tsystemuser obj = new systemuser();\n\t\tobj.set_username(username);\n\t\tsystemuser response = (systemuser) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private AssignmentField selectField(AssignmentField[] fields, int index)\n {\n if (index < 1 || index > fields.length)\n {\n throw new IllegalArgumentException(index + \" is not a valid field index\");\n }\n return (fields[index - 1]);\n }",
"public void addForeignKeyField(String newField)\r\n {\r\n if (m_ForeignKeyFields == null)\r\n {\r\n m_ForeignKeyFields = new Vector();\r\n }\r\n m_ForeignKeyFields.add(newField);\r\n }",
"public static String getPrettyMapOfContiguousPartitionRunLengths(final Cluster cluster,\n int zoneId) {\n Map<Integer, Integer> runLengthToCount = getMapOfContiguousPartitionRunLengths(cluster,\n zoneId);\n String prettyHistogram = \"[\";\n boolean first = true;\n Set<Integer> runLengths = new TreeSet<Integer>(runLengthToCount.keySet());\n for(int runLength: runLengths) {\n if(first) {\n first = false;\n } else {\n prettyHistogram += \", \";\n }\n prettyHistogram += \"{\" + runLength + \" : \" + runLengthToCount.get(runLength) + \"}\";\n }\n prettyHistogram += \"]\";\n return prettyHistogram;\n }",
"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 }",
"private void loadLibraryFromStream(String libname, InputStream is) {\r\n try {\r\n File tempfile = createTempFile(libname);\r\n OutputStream os = new FileOutputStream(tempfile);\r\n\r\n logger.debug(\"tempfile.getPath() = \" + tempfile.getPath());\r\n\r\n long savedTime = System.currentTimeMillis();\r\n\r\n // Leo says 8k block size is STANDARD ;)\r\n byte buf[] = new byte[8192];\r\n int len;\r\n while ((len = is.read(buf)) > 0) {\r\n os.write(buf, 0, len);\r\n }\r\n\r\n os.flush();\r\n InputStream lock = new FileInputStream(tempfile);\r\n os.close();\r\n\r\n double seconds = (double) (System.currentTimeMillis() - savedTime) / 1e3;\r\n logger.debug(\"Copying took \" + seconds + \" seconds.\");\r\n\r\n logger.debug(\"Loading library from \" + tempfile.getPath() + \".\");\r\n System.load(tempfile.getPath());\r\n\r\n lock.close();\r\n } catch (IOException io) {\r\n logger.error(\"Could not create the temp file: \" + io.toString() + \".\\n\");\r\n } catch (UnsatisfiedLinkError ule) {\r\n logger.error(\"Couldn't load copied link file: \" + ule.toString() + \".\\n\");\r\n throw ule;\r\n }\r\n }",
"public static ComponentsMultiThread getComponentsMultiThread() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.componentsMultiThread;\n }",
"public String getDependencyJsonModel() throws IOException {\n final Artifact artifact = DataModelFactory.createArtifact(\"\",\"\",\"\",\"\",\"\",\"\",\"\");\n return JsonUtils.serialize(DataModelFactory.createDependency(artifact, Scope.COMPILE));\n }",
"@Override\n\tpublic void validate() throws HostNameException {\n\t\tif(parsedHost != null) {\n\t\t\treturn;\n\t\t}\n\t\tif(validationException != null) {\n\t\t\tthrow validationException;\n\t\t}\n\t\tsynchronized(this) {\n\t\t\tif(parsedHost != null) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif(validationException != null) {\n\t\t\t\tthrow validationException;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tparsedHost = getValidator().validateHost(this);\n\t\t\t} catch(HostNameException e) {\n\t\t\t\tvalidationException = e;\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t}"
] |
Handle exceptions thrown by the storage. Exceptions specific to DELETE go
here. Pass other exceptions to the parent class.
TODO REST-Server Add a new exception for this condition - server busy
with pending requests. queue is full | [
"@Override\n public void handleExceptions(MessageEvent messageEvent, Exception exception) {\n\n if(exception instanceof InvalidMetadataException) {\n logger.error(\"Exception when deleting. The requested key does not exist in this partition\",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE,\n \"The requested key does not exist in this partition\");\n } else if(exception instanceof PersistenceFailureException) {\n logger.error(\"Exception when deleting. Operation failed\", exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n \"Operation failed\");\n } else if(exception instanceof UnsupportedOperationException) {\n logger.error(\"Exception when deleting. Operation not supported in read-only store \",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.METHOD_NOT_ALLOWED,\n \"Operation not supported in read-only store\");\n } else if(exception instanceof StoreTimeoutException) {\n String errorDescription = \"DELETE Request timed out: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent, HttpResponseStatus.REQUEST_TIMEOUT, errorDescription);\n } else if(exception instanceof InsufficientOperationalNodesException) {\n String errorDescription = \"DELETE Request failed: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n errorDescription);\n } else {\n super.handleExceptions(messageEvent, exception);\n }\n }"
] | [
"@SuppressWarnings(\"unchecked\")\n public <V3, M4, C, N, Q> N getSceneRoot(AiWrapperProvider<V3, M4, C, N, Q> \n wrapperProvider) {\n\n return (N) m_sceneRoot;\n }",
"@SuppressWarnings(\"unchecked\")\n public static Map<String, List<Path>> findJavaHomes() {\n try {\n return (Map<String, List<Path>>) accessible(Class.forName(CAPSULE_CLASS_NAME).getDeclaredMethod(\"getJavaHomes\")).invoke(null);\n } catch (ReflectiveOperationException e) {\n throw new AssertionError(e);\n }\n }",
"public ThumborUrlBuilder trim(TrimPixelColor value, int colorTolerance) {\n if (colorTolerance < 0 || colorTolerance > 442) {\n throw new IllegalArgumentException(\"Color tolerance must be between 0 and 442.\");\n }\n if (colorTolerance > 0 && value == null) {\n throw new IllegalArgumentException(\"Trim pixel color value must not be null.\");\n }\n isTrim = true;\n trimPixelColor = value;\n trimColorTolerance = colorTolerance;\n return this;\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 }",
"public static base_response delete(nitro_service client, String Dnssuffix) throws Exception {\n\t\tdnssuffix deleteresource = new dnssuffix();\n\t\tdeleteresource.Dnssuffix = Dnssuffix;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public void generateOutlineNumber(Task parent)\n {\n String outline;\n\n if (parent == null)\n {\n if (NumberHelper.getInt(getUniqueID()) == 0)\n {\n outline = \"0\";\n }\n else\n {\n outline = Integer.toString(getParentFile().getChildTasks().size() + 1);\n }\n }\n else\n {\n outline = parent.getOutlineNumber();\n\n int index = outline.lastIndexOf(\".0\");\n\n if (index != -1)\n {\n outline = outline.substring(0, index);\n }\n\n int childTaskCount = parent.getChildTasks().size() + 1;\n if (outline.equals(\"0\"))\n {\n outline = Integer.toString(childTaskCount);\n }\n else\n {\n outline += (\".\" + childTaskCount);\n }\n }\n\n setOutlineNumber(outline);\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 <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable) {\n \treturn executeOptimistic(execSvc, members, callable, 60, TimeUnit.SECONDS);\n }",
"private void setNsid() throws FlickrException {\n\n if (username != null && !username.equals(\"\")) {\n Auth auth = null;\n if (authStore != null) {\n auth = authStore.retrieve(username); // assuming FileAuthStore is enhanced else need to\n // keep in user-level files.\n\n if (auth != null) {\n nsid = auth.getUser().getId();\n }\n }\n if (auth != null)\n return;\n\n Auth[] allAuths = authStore.retrieveAll();\n for (int i = 0; i < allAuths.length; i++) {\n if (username.equals(allAuths[i].getUser().getUsername())) {\n nsid = allAuths[i].getUser().getId();\n return;\n }\n }\n\n // For this to work: REST.java or PeopleInterface needs to change to pass apiKey\n // as the parameter to the call which is not authenticated.\n\n // Get nsid using flickr.people.findByUsername\n PeopleInterface peopleInterf = flickr.getPeopleInterface();\n User u = peopleInterf.findByUsername(username);\n if (u != null) {\n nsid = u.getId();\n }\n }\n }"
] |
Returns a configured transformer to write XML.
@return the XML configured transformer
@throws SpinXmlElementException if no new transformer can be created | [
"protected Transformer getTransformer() {\n TransformerFactory transformerFactory = domXmlDataFormat.getTransformerFactory();\n try {\n Transformer transformer = transformerFactory.newTransformer();\n transformer.setOutputProperty(OutputKeys.ENCODING, \"UTF-8\");\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n return transformer;\n }\n catch (TransformerConfigurationException e) {\n throw LOG.unableToCreateTransformer(e);\n }\n }"
] | [
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<AccountingDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<AccountingDate>) super.zonedDateTime(temporal);\n }",
"@SuppressWarnings({})\n public synchronized void removeStoreFromSession(List<String> storeNameToRemove) {\n\n logger.info(\"closing the Streaming session for a few stores\");\n\n commitToVoldemort(storeNameToRemove);\n cleanupSessions(storeNameToRemove);\n\n }",
"private static int tribus(int version, int a, int b, int c) {\n if (version < 10) {\n return a;\n } else if (version >= 10 && version <= 26) {\n return b;\n } else {\n return c;\n }\n }",
"public void recordServerResult(ServerIdentity server, ModelNode response) {\n\n if (!serverGroupName.equals(server.getServerGroupName()) || !servers.contains(server)) {\n throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServer(server);\n }\n\n boolean serverFailed = response.has(FAILURE_DESCRIPTION);\n\n\n DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef(\"Recording server result for '%s': failed = %s\",\n server, server);\n\n synchronized (this) {\n int previousFailed = failureCount;\n if (serverFailed) {\n failureCount++;\n }\n else {\n successCount++;\n }\n if (previousFailed <= maxFailed) {\n if (!serverFailed && (successCount + failureCount) == servers.size()) {\n // All results are in; notify parent of success\n parent.recordServerGroupResult(serverGroupName, false);\n }\n else if (serverFailed && failureCount > maxFailed) {\n parent.recordServerGroupResult(serverGroupName, true);\n }\n }\n }\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 }",
"protected boolean cannotInstantiate(Class<?> actionClass) {\n\t\treturn actionClass.isAnnotation() || actionClass.isInterface() || actionClass.isEnum()\n\t\t\t\t|| (actionClass.getModifiers() & Modifier.ABSTRACT) != 0 || actionClass.isAnonymousClass();\n\t}",
"void registerAlias(FieldType type, String alias)\n {\n m_aliasMap.put(new Pair<FieldTypeClass, String>(type.getFieldTypeClass(), alias), type);\n }",
"public void updateFrontFacingRotation(float rotation) {\n if (!Float.isNaN(rotation) && !equal(rotation, frontFacingRotation)) {\n final float oldRotation = frontFacingRotation;\n frontFacingRotation = rotation % 360;\n for (OnFrontRotationChangedListener listener : mOnFrontRotationChangedListeners) {\n try {\n listener.onFrontRotationChanged(this, frontFacingRotation, oldRotation);\n } catch (Exception e) {\n e.printStackTrace();\n Log.e(TAG, e, \"updateFrontFacingRotation()\");\n }\n }\n }\n }",
"public void deleteComment(String commentId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_DELETE_COMMENT);\r\n\r\n parameters.put(\"comment_id\", commentId);\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // This method has no specific response - It returns an empty\r\n // sucess response if it completes without error.\r\n }"
] |
Mark the given child resource as the post run dependent of the parent of this collection.
@param childResource the child resource | [
"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 void registerDataPersisters(DataPersister... dataPersisters) {\n\t\t// we build the map and replace it to lower the chance of concurrency issues\n\t\tList<DataPersister> newList = new ArrayList<DataPersister>();\n\t\tif (registeredPersisters != null) {\n\t\t\tnewList.addAll(registeredPersisters);\n\t\t}\n\t\tfor (DataPersister persister : dataPersisters) {\n\t\t\tnewList.add(persister);\n\t\t}\n\t\tregisteredPersisters = newList;\n\t}",
"public AssemblyResponse cancelAssembly(String url)\n throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new AssemblyResponse(request.delete(url, new HashMap<String, Object>()));\n }",
"public QueryBuilder<T, ID> groupBy(String columnName) {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new IllegalArgumentException(\"Can't groupBy foreign collection field: \" + columnName);\n\t\t}\n\t\taddGroupBy(ColumnNameOrRawSql.withColumnName(columnName));\n\t\treturn this;\n\t}",
"public static ModelNode determineHostAddress(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadAttributeOperation(EMPTY_ADDRESS, \"local-host-name\");\n ModelNode response = client.execute(op);\n if (Operations.isSuccessfulOutcome(response)) {\n return DeploymentOperations.createAddress(\"host\", Operations.readResult(response).asString());\n }\n throw new OperationExecutionException(op, response);\n }",
"private void rebalanceStore(String storeName,\n final AdminClient adminClient,\n RebalanceTaskInfo stealInfo,\n boolean isReadOnlyStore) {\n // Move partitions\n if (stealInfo.getPartitionIds(storeName) != null && stealInfo.getPartitionIds(storeName).size() > 0) {\n\n logger.info(getHeader(stealInfo) + \"Starting partitions migration for store \"\n + storeName + \" from donor node \" + stealInfo.getDonorId());\n\n int asyncId = adminClient.storeMntOps.migratePartitions(stealInfo.getDonorId(),\n metadataStore.getNodeId(),\n storeName,\n stealInfo.getPartitionIds(storeName),\n null,\n stealInfo.getInitialCluster());\n rebalanceStatusList.add(asyncId);\n\n if(logger.isDebugEnabled()) {\n logger.debug(getHeader(stealInfo) + \"Waiting for completion for \" + storeName\n + \" with async id \" + asyncId);\n }\n adminClient.rpcOps.waitForCompletion(metadataStore.getNodeId(),\n asyncId,\n voldemortConfig.getRebalancingTimeoutSec(),\n TimeUnit.SECONDS,\n getStatus());\n\n rebalanceStatusList.remove((Object) asyncId);\n\n logger.info(getHeader(stealInfo) + \"Completed partition migration for store \"\n + storeName + \" from donor node \" + stealInfo.getDonorId());\n }\n\n logger.info(getHeader(stealInfo) + \"Finished all migration for store \" + storeName);\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 }",
"protected void restoreAutoCommitState()\r\n {\r\n try\r\n {\r\n if(!broker.isManaged())\r\n {\r\n if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE\r\n && originalAutoCommitState == true && con != null && !con.isClosed())\r\n {\r\n platform.changeAutoCommitState(jcd, con, true);\r\n }\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled()) log.debug(\r\n \"Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n // should never be reached\r\n throw new OJBRuntimeException(\"Restore of connection autocommit state failed\", e);\r\n }\r\n }",
"public T withStatement(Statement statement) {\n\t\tPropertyIdValue pid = statement.getMainSnak()\n\t\t\t\t.getPropertyId();\n\t\tArrayList<Statement> pidStatements = this.statements.get(pid);\n\t\tif (pidStatements == null) {\n\t\t\tpidStatements = new ArrayList<Statement>();\n\t\t\tthis.statements.put(pid, pidStatements);\n\t\t}\n\n\t\tpidStatements.add(statement);\n\t\treturn getThis();\n\t}",
"public Set<URI> collectOutgoingReferences(IResourceDescription description) {\n\t\tURI resourceURI = description.getURI();\n\t\tSet<URI> result = null;\n\t\tfor(IReferenceDescription reference: description.getReferenceDescriptions()) {\n\t\t\tURI targetResource = reference.getTargetEObjectUri().trimFragment();\n\t\t\tif (!resourceURI.equals(targetResource)) {\n\t\t\t\tif (result == null)\n\t\t\t\t\tresult = Sets.newHashSet(targetResource);\n\t\t\t\telse\n\t\t\t\t\tresult.add(targetResource);\n\t\t\t}\n\t\t}\n\t\tif (result != null)\n\t\t\treturn result;\n\t\treturn Collections.emptySet();\n\t}"
] |
Compute the offset for the item in the layout cache
@return true if the item fits the container, false otherwise | [
"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 }"
] | [
"private void processCalendarHours(ProjectCalendar calendar, Row row, int dayIndex)\n {\n Day day = Day.getInstance(dayIndex);\n boolean working = row.getInt(\"CD_WORKING\") != 0;\n calendar.setWorkingDay(day, working);\n if (working == true)\n {\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n\n Date start = row.getDate(\"CD_FROM_TIME1\");\n Date end = row.getDate(\"CD_TO_TIME1\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME2\");\n end = row.getDate(\"CD_TO_TIME2\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME3\");\n end = row.getDate(\"CD_TO_TIME3\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME4\");\n end = row.getDate(\"CD_TO_TIME4\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME5\");\n end = row.getDate(\"CD_TO_TIME5\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n }\n }",
"public void setValue(Vector3f scale) {\n mX = scale.x;\n mY = scale.y;\n mZ = scale.z;\n }",
"@SuppressWarnings(\"deprecation\")\n\tpublic static boolean dateTimeEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getDate() == d2.getDate()\n && d1.getMonth() == d2.getMonth()\n && d1.getYear() == d2.getYear()\n && d1.getHours() == d2.getHours()\n && d1.getMinutes() == d2.getMinutes()\n && d1.getSeconds() == d2.getSeconds();\n }",
"private void releaseConnection()\n {\n if (m_rs != null)\n {\n try\n {\n m_rs.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore errors on close\n }\n\n m_rs = null;\n }\n\n if (m_ps != null)\n {\n try\n {\n m_ps.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore errors on close\n }\n\n m_ps = null;\n }\n }",
"public static Integer getDurationValue(ProjectProperties properties, Duration duration)\n {\n Integer result;\n if (duration == null)\n {\n result = null;\n }\n else\n {\n if (duration.getUnits() != TimeUnit.MINUTES)\n {\n duration = duration.convertUnits(TimeUnit.MINUTES, properties);\n }\n result = Integer.valueOf((int) duration.getDuration());\n }\n return (result);\n }",
"public void load(File file) {\n try {\n PropertiesConfiguration config = new PropertiesConfiguration();\n // disabled to prevent accumulo classpath value from being shortened\n config.setDelimiterParsingDisabled(true);\n config.load(file);\n ((CompositeConfiguration) internalConfig).addConfiguration(config);\n } catch (ConfigurationException e) {\n throw new IllegalArgumentException(e);\n }\n }",
"public ParallelTask getTaskFromInProgressMap(String jobId) {\n if (!inprogressTaskMap.containsKey(jobId))\n return null;\n return inprogressTaskMap.get(jobId);\n }",
"private static Class<?> getGenericReturnType(Method method, Class<?> source, int typeIndex, int nestingLevel) {\n\t\treturn extractType(method.getGenericReturnType(), source, typeIndex, null, null, nestingLevel, 1);\n\t}",
"static ModelNode createOperation(final ModelNode operationToValidate) {\n PathAddress pa = PathAddress.pathAddress(operationToValidate.require(ModelDescriptionConstants.OP_ADDR));\n PathAddress realmPA = null;\n for (int i = pa.size() - 1; i > 0; i--) {\n PathElement pe = pa.getElement(i);\n if (SECURITY_REALM.equals(pe.getKey())) {\n realmPA = pa.subAddress(0, i + 1);\n break;\n }\n }\n assert realmPA != null : \"operationToValidate did not have an address that included a \" + SECURITY_REALM;\n return Util.getEmptyOperation(\"validate-authentication\", realmPA.toModelNode());\n }"
] |
Use this API to fetch the statistics of all spilloverpolicy_stats resources that are configured on netscaler. | [
"public static spilloverpolicy_stats[] get(nitro_service service) throws Exception{\n\t\tspilloverpolicy_stats obj = new spilloverpolicy_stats();\n\t\tspilloverpolicy_stats[] response = (spilloverpolicy_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}"
] | [
"public static Map<String, String[]> mapUrlEncodedParameters(byte[] dataArray) throws Exception {\n Map<String, String[]> mapPostParameters = new HashMap<String, String[]>();\n\n try {\n ByteArrayOutputStream byteout = new ByteArrayOutputStream();\n for (int x = 0; x < dataArray.length; x++) {\n // split the data up by & to get the parts\n if (dataArray[x] == '&' || x == (dataArray.length - 1)) {\n if (x == (dataArray.length - 1)) {\n byteout.write(dataArray[x]);\n }\n // find '=' and split the data up into key value pairs\n int equalsPos = -1;\n ByteArrayOutputStream key = new ByteArrayOutputStream();\n ByteArrayOutputStream value = new ByteArrayOutputStream();\n byte[] byteArray = byteout.toByteArray();\n for (int xx = 0; xx < byteArray.length; xx++) {\n if (byteArray[xx] == '=') {\n equalsPos = xx;\n } else {\n if (equalsPos == -1) {\n key.write(byteArray[xx]);\n } else {\n value.write(byteArray[xx]);\n }\n }\n }\n\n ArrayList<String> values = new ArrayList<String>();\n\n if (mapPostParameters.containsKey(key.toString())) {\n values = new ArrayList<String>(Arrays.asList(mapPostParameters.get(key.toString())));\n mapPostParameters.remove(key.toString());\n }\n\n values.add(value.toString());\n /**\n * If equalsPos is not -1, then there was a '=' for the key\n * If value.size is 0, then there is no value so want to add in the '='\n * Since it will not be added later like params with keys and valued\n */\n if (equalsPos != -1 && value.size() == 0) {\n key.write((byte) '=');\n }\n\n mapPostParameters.put(key.toString(), values.toArray(new String[values.size()]));\n\n byteout = new ByteArrayOutputStream();\n } else {\n byteout.write(dataArray[x]);\n }\n }\n } catch (Exception e) {\n throw new Exception(\"Could not parse request data: \" + e.getMessage());\n }\n\n return mapPostParameters;\n }",
"@NotNull\n private String getFQName(@NotNull final String localName, Object... params) {\n final StringBuilder builder = new StringBuilder();\n builder.append(storeName);\n builder.append('.');\n builder.append(localName);\n for (final Object param : params) {\n builder.append('#');\n builder.append(param);\n }\n //noinspection ConstantConditions\n return StringInterner.intern(builder.toString());\n }",
"public synchronized void addCertAndPrivateKey(String hostname, final X509Certificate cert, final PrivateKey privKey)\n\tthrows KeyStoreException, CertificateException, NoSuchAlgorithmException\n\t{\n//\t\tString alias = ThumbprintUtil.getThumbprint(cert);\n\n\t\t_ks.deleteEntry(hostname);\n\n _ks.setCertificateEntry(hostname, cert);\n\t\t_ks.setKeyEntry(hostname, privKey, _keypassword, new java.security.cert.Certificate[] {cert});\n\n\t\tif(persistImmediately)\n\t\t{\n\t\t\tpersist();\n\t\t}\n\n\t}",
"public static double blackScholesDigitalOptionValue(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 1.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate analytic value\n\t\t\tdouble dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\t\t\tdouble dMinus = dPlus - volatility * Math.sqrt(optionMaturity);\n\n\t\t\tdouble valueAnalytic = Math.exp(- riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);\n\n\t\t\treturn valueAnalytic;\n\t\t}\n\t}",
"public float[] getFloatArray(String attributeName)\n {\n float[] array = NativeVertexBuffer.getFloatArray(getNative(), attributeName);\n if (array == null)\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return array;\n }",
"protected org.apache.log4j.helpers.PatternParser createPatternParser(final String pattern) {\n\t\treturn new FoundationLoggingPatternParser(pattern);\n\t}",
"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 }",
"public static appfwjsoncontenttype[] get(nitro_service service, options option) throws Exception{\n\t\tappfwjsoncontenttype obj = new appfwjsoncontenttype();\n\t\tappfwjsoncontenttype[] response = (appfwjsoncontenttype[])obj.get_resources(service,option);\n\t\treturn response;\n\t}",
"private static void checkPreconditions(final int maxSize, final String suffix) {\n\t\tif( maxSize <= 0 ) {\n\t\t\tthrow new IllegalArgumentException(String.format(\"maxSize should be > 0 but was %d\", maxSize));\n\t\t}\n\t\tif( suffix == null ) {\n\t\t\tthrow new NullPointerException(\"suffix should not be null\");\n\t\t}\n\t}"
] |
Extract resource data. | [
"private void processResources() throws IOException\n {\n CompanyReader reader = new CompanyReader(m_data.getTableData(\"Companies\"));\n reader.read();\n for (MapRow companyRow : reader.getRows())\n {\n // TODO: need to sort by type as well as by name!\n for (MapRow resourceRow : sort(companyRow.getRows(\"RESOURCES\"), \"NAME\"))\n {\n processResource(resourceRow);\n }\n }\n }"
] | [
"public void add(Vector3d v1) {\n x += v1.x;\n y += v1.y;\n z += v1.z;\n }",
"public static MediaType nonBinaryUtf8( MediaType.Type type, String subType ) {\n return new MediaType( type, subType, UTF_8 );\n }",
"public Map<String, String> decompose(Frontier frontier, String modelText) {\r\n if (!(frontier instanceof SCXMLFrontier)) {\r\n return null;\r\n }\n\r\n TransitionTarget target = ((SCXMLFrontier) frontier).getRoot().nextState;\r\n Map<String, String> variables = ((SCXMLFrontier) frontier).getRoot().variables;\n\r\n Map<String, String> decomposition = new HashMap<String, String>();\r\n decomposition.put(\"target\", target.getId());\n\r\n StringBuilder packedVariables = new StringBuilder();\r\n for (Map.Entry<String, String> variable : variables.entrySet()) {\r\n packedVariables.append(variable.getKey());\r\n packedVariables.append(\"::\");\r\n packedVariables.append(variable.getValue());\r\n packedVariables.append(\";\");\r\n }\n\r\n decomposition.put(\"variables\", packedVariables.toString());\r\n decomposition.put(\"model\", modelText);\n\r\n return decomposition;\r\n }",
"private static void initInstance(final TransactionLogger instance, final Logger logger, final Logger auditor) {\n instance.logger = logger;\n instance.auditor = auditor;\n instance.components = new LinkedHashMap<>();\n instance.properties = new LinkedHashMap<>();\n instance.total = new Component(TOTAL_COMPONENT);\n instance.total.startTimer();\n instance.componentsMultiThread = new ComponentsMultiThread();\n instance.flowContext = FlowContextFactory.serializeNativeFlowContext();\n }",
"protected AssemblyResponse watchStatus() throws LocalOperationException, RequestException {\n AssemblyResponse response;\n do {\n response = getClient().getAssemblyByUrl(url);\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n throw new LocalOperationException(e);\n }\n } while (!response.isFinished());\n\n setState(State.FINISHED);\n return response;\n }",
"private static void defineField(Map<String, FieldType> container, String name, FieldType type)\n {\n defineField(container, name, type, null);\n }",
"private CmsMessageBundleEditorTypes.BundleType initBundleType() {\n\n String resourceTypeName = OpenCms.getResourceManager().getResourceType(m_resource).getTypeName();\n return CmsMessageBundleEditorTypes.BundleType.toBundleType(resourceTypeName);\n }",
"@VisibleForTesting\n protected TextSymbolizer createTextSymbolizer(final PJsonObject styleJson) {\n final TextSymbolizer textSymbolizer = this.styleBuilder.createTextSymbolizer();\n\n // make sure that labels are also rendered if a part of the text would be outside\n // the view context, see http://docs.geoserver.org/stable/en/user/styling/sld-reference/labeling\n // .html#partials\n textSymbolizer.getOptions().put(\"partials\", \"true\");\n\n if (styleJson.has(JSON_LABEL)) {\n final Expression label =\n parseExpression(null, styleJson, JSON_LABEL,\n (final String labelValue) -> labelValue.replace(\"${\", \"\")\n .replace(\"}\", \"\"));\n\n textSymbolizer.setLabel(label);\n } else {\n return null;\n }\n\n textSymbolizer.setFont(createFont(textSymbolizer.getFont(), styleJson));\n\n if (styleJson.has(JSON_LABEL_ANCHOR_POINT_X) ||\n styleJson.has(JSON_LABEL_ANCHOR_POINT_Y) ||\n styleJson.has(JSON_LABEL_ALIGN) ||\n styleJson.has(JSON_LABEL_X_OFFSET) ||\n styleJson.has(JSON_LABEL_Y_OFFSET) ||\n styleJson.has(JSON_LABEL_ROTATION) ||\n styleJson.has(JSON_LABEL_PERPENDICULAR_OFFSET)) {\n textSymbolizer.setLabelPlacement(createLabelPlacement(styleJson));\n }\n\n if (!StringUtils.isEmpty(styleJson.optString(JSON_HALO_RADIUS)) ||\n !StringUtils.isEmpty(styleJson.optString(JSON_HALO_COLOR)) ||\n !StringUtils.isEmpty(styleJson.optString(JSON_HALO_OPACITY)) ||\n !StringUtils.isEmpty(styleJson.optString(JSON_LABEL_OUTLINE_WIDTH)) ||\n !StringUtils.isEmpty(styleJson.optString(JSON_LABEL_OUTLINE_COLOR))) {\n textSymbolizer.setHalo(createHalo(styleJson));\n }\n\n if (!StringUtils.isEmpty(styleJson.optString(JSON_FONT_COLOR)) ||\n !StringUtils.isEmpty(styleJson.optString(JSON_FONT_OPACITY))) {\n textSymbolizer.setFill(addFill(\n styleJson.optString(JSON_FONT_COLOR, \"black\"),\n styleJson.optString(JSON_FONT_OPACITY, \"1.0\")));\n }\n\n this.addVendorOptions(JSON_LABEL_ALLOW_OVERRUNS, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_AUTO_WRAP, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_CONFLICT_RESOLUTION, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_FOLLOW_LINE, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_GOODNESS_OF_FIT, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_GROUP, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_MAX_DISPLACEMENT, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_SPACE_AROUND, styleJson, textSymbolizer);\n\n return textSymbolizer;\n }",
"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 }"
] |
Gets or creates the a resource for the sub-deployment on the parent deployments resource.
@param deploymentName the name of the deployment
@param parent the parent deployment used to find the parent resource
@return the already registered resource or a newly created resource | [
"static Resource getOrCreateSubDeployment(final String deploymentName, final DeploymentUnit parent) {\n final Resource root = parent.getAttachment(DEPLOYMENT_RESOURCE);\n return getOrCreate(root, PathElement.pathElement(SUBDEPLOYMENT, deploymentName));\n }"
] | [
"public @Nullable String build() {\n StringBuilder queryString = new StringBuilder();\n\n for (NameValuePair param : params) {\n if (queryString.length() > 0) {\n queryString.append(PARAM_SEPARATOR);\n }\n queryString.append(Escape.urlEncode(param.getName()));\n queryString.append(VALUE_SEPARATOR);\n queryString.append(Escape.urlEncode(param.getValue()));\n }\n\n if (queryString.length() > 0) {\n return queryString.toString();\n }\n else {\n return null;\n }\n }",
"public static Map<String, StoreDefinition> getUserStoreDefMapOnNode(AdminClient adminClient,\n Integer nodeId) {\n List<StoreDefinition> storeDefinitionList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId)\n .getValue();\n Map<String, StoreDefinition> storeDefinitionMap = Maps.newHashMap();\n for(StoreDefinition storeDefinition: storeDefinitionList) {\n storeDefinitionMap.put(storeDefinition.getName(), storeDefinition);\n }\n return storeDefinitionMap;\n }",
"public void checkVersion(ZWaveCommandClass commandClass) {\r\n\t\tZWaveVersionCommandClass versionCommandClass = (ZWaveVersionCommandClass)this.getNode().getCommandClass(CommandClass.VERSION);\r\n\t\t\r\n\t\tif (versionCommandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Version command class not supported on node %d,\" +\r\n\t\t\t\t\t\"reverting to version 1 for command class %s (0x%02x)\", \r\n\t\t\t\t\tthis.getNode().getNodeId(), \r\n\t\t\t\t\tcommandClass.getCommandClass().getLabel(), \r\n\t\t\t\t\tcommandClass.getCommandClass().getKey()));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tthis.getController().sendData(versionCommandClass.getCommandClassVersionMessage(commandClass.getCommandClass()));\r\n\t}",
"private static LogType findLogType() {\n\n\t\t// see if the log-type was specified as a system property\n\t\tString logTypeString = System.getProperty(LOG_TYPE_SYSTEM_PROPERTY);\n\t\tif (logTypeString != null) {\n\t\t\ttry {\n\t\t\t\treturn LogType.valueOf(logTypeString);\n\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\tLog log = new LocalLog(LoggerFactory.class.getName());\n\t\t\t\tlog.log(Level.WARNING, \"Could not find valid log-type from system property '\" + LOG_TYPE_SYSTEM_PROPERTY\n\t\t\t\t\t\t+ \"', value '\" + logTypeString + \"'\");\n\t\t\t}\n\t\t}\n\n\t\tfor (LogType logType : LogType.values()) {\n\t\t\tif (logType.isAvailable()) {\n\t\t\t\treturn logType;\n\t\t\t}\n\t\t}\n\t\t// fall back is always LOCAL, never reached\n\t\treturn LogType.LOCAL;\n\t}",
"private void writeBooleanField(String fieldName, Object value) throws IOException\n {\n boolean val = ((Boolean) value).booleanValue();\n if (val)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }",
"public void addProperty(String name, String... values) {\n List<String> valueList = new ArrayList<String>();\n for (String value : values) {\n valueList.add(value.trim());\n }\n properties.put(name.trim(), valueList);\n }",
"public static appfwlearningsettings get(nitro_service service, String profilename) throws Exception{\n\t\tappfwlearningsettings obj = new appfwlearningsettings();\n\t\tobj.set_profilename(profilename);\n\t\tappfwlearningsettings response = (appfwlearningsettings) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static boolean isClosureDeclaration(ASTNode expression) {\r\n if (expression instanceof DeclarationExpression) {\r\n if (((DeclarationExpression) expression).getRightExpression() instanceof ClosureExpression) {\r\n return true;\r\n }\r\n }\r\n if (expression instanceof FieldNode) {\r\n ClassNode type = ((FieldNode) expression).getType();\r\n if (AstUtil.classNodeImplementsType(type, Closure.class)) {\r\n return true;\r\n } else if (((FieldNode) expression).getInitialValueExpression() instanceof ClosureExpression) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"public static String find(CharSequence self, CharSequence regex, @ClosureParams(value=SimpleType.class, options=\"java.lang.String[]\") Closure closure) {\n return find(self.toString(), Pattern.compile(regex.toString()), closure);\n }"
] |
Copy all of the mappings from the specified map to this one, replacing
any mappings with the same keys.
@param in the map whose mappings are to be copied | [
"@Override\r\n public void putAll(Map<? extends K, ? extends V> in) {\r\n if (fast) {\r\n synchronized (this) {\r\n Map<K, V> temp = cloneMap(map);\r\n temp.putAll(in);\r\n map = temp;\r\n }\r\n } else {\r\n synchronized (map) {\r\n map.putAll(in);\r\n }\r\n }\r\n }"
] | [
"private void addCalendars(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (ProjectCalendar calendar : file.getCalendars())\n {\n addCalendar(parentNode, calendar);\n }\n }",
"private void checkAndAddNodeStore() {\n for(Node node: metadata.getCluster().getNodes()) {\n if(!routedStore.getInnerStores().containsKey(node.getId())) {\n if(!storeRepository.hasNodeStore(getName(), node.getId())) {\n storeRepository.addNodeStore(node.getId(), createNodeStore(node));\n }\n routedStore.getInnerStores().put(node.getId(),\n storeRepository.getNodeStore(getName(),\n node.getId()));\n }\n }\n }",
"public static int cudnnPoolingBackward(\n cudnnHandle handle, \n cudnnPoolingDescriptor poolingDesc, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnPoolingBackwardNative(handle, poolingDesc, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }",
"private void readUDFTypes(FieldContainer mpxj, List<UDFAssignmentType> udfs)\n {\n for (UDFAssignmentType udf : udfs)\n {\n FieldType fieldType = m_fieldTypeMap.get(Integer.valueOf(udf.getTypeObjectId()));\n if (fieldType != null)\n {\n mpxj.set(fieldType, getUdfValue(udf));\n }\n }\n }",
"public static void writeProcessorOutputToValues(\n final Object output,\n final Processor<?, ?> processor,\n final Values values) {\n Map<String, String> mapper = processor.getOutputMapperBiMap();\n if (mapper == null) {\n mapper = Collections.emptyMap();\n }\n\n final Collection<Field> fields = getAllAttributes(output.getClass());\n for (Field field: fields) {\n String name = getOutputValueName(processor.getOutputPrefix(), mapper, field);\n try {\n final Object value = field.get(output);\n if (value != null) {\n values.put(name, value);\n } else {\n values.remove(name);\n }\n } catch (IllegalAccessException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }\n }",
"static String guessEntityTypeFromId(String id) {\n\t\tif(id.isEmpty()) {\n\t\t\tthrow new IllegalArgumentException(\"Entity ids should not be empty.\");\n\t\t}\n\t\tswitch (id.charAt(0)) {\n\t\t\tcase 'L':\n\t\t\t\tif(id.contains(\"-F\")) {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_FORM;\n\t\t\t\t} else if(id.contains(\"-S\")) {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_SENSE;\n\t\t\t\t} else {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_LEXEME;\n\t\t\t\t}\n\t\t\tcase 'P':\n\t\t\t\treturn JSON_ENTITY_TYPE_PROPERTY;\n\t\t\tcase 'Q':\n\t\t\t\treturn JSON_ENTITY_TYPE_ITEM;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Entity id \\\"\" + id + \"\\\" is not supported.\");\n\t\t}\n\t}",
"@RequestMapping(value = \"/api/plugins\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getPluginInformation() {\n return pluginInformation();\n }",
"private String formatRelation(Relation relation)\n {\n String result = null;\n\n if (relation != null)\n {\n StringBuilder sb = new StringBuilder(relation.getTargetTask().getID().toString());\n\n Duration duration = relation.getLag();\n RelationType type = relation.getType();\n double durationValue = duration.getDuration();\n\n if ((durationValue != 0) || (type != RelationType.FINISH_START))\n {\n String[] typeNames = LocaleData.getStringArray(m_locale, LocaleData.RELATION_TYPES);\n sb.append(typeNames[type.getValue()]);\n }\n\n if (durationValue != 0)\n {\n if (durationValue > 0)\n {\n sb.append('+');\n }\n\n sb.append(formatDuration(duration));\n }\n\n result = sb.toString();\n }\n\n m_eventManager.fireRelationWrittenEvent(relation);\n return (result);\n }",
"public static base_responses update(nitro_service client, onlinkipv6prefix resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tonlinkipv6prefix updateresources[] = new onlinkipv6prefix[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new onlinkipv6prefix();\n\t\t\t\tupdateresources[i].ipv6prefix = resources[i].ipv6prefix;\n\t\t\t\tupdateresources[i].onlinkprefix = resources[i].onlinkprefix;\n\t\t\t\tupdateresources[i].autonomusprefix = resources[i].autonomusprefix;\n\t\t\t\tupdateresources[i].depricateprefix = resources[i].depricateprefix;\n\t\t\t\tupdateresources[i].decrementprefixlifetimes = resources[i].decrementprefixlifetimes;\n\t\t\t\tupdateresources[i].prefixvalidelifetime = resources[i].prefixvalidelifetime;\n\t\t\t\tupdateresources[i].prefixpreferredlifetime = resources[i].prefixpreferredlifetime;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}"
] |
Remove any protocol-level headers from the clients request that
do not apply to the new request we are sending to the remote server.
@param request
@param destination | [
"protected void prepareForwardedRequestHeaders(RequestData request, ForwardDestination destination) {\n HttpHeaders headers = request.getHeaders();\n headers.set(HOST, destination.getUri().getAuthority());\n headers.remove(TE);\n }"
] | [
"private PersistentResourceXMLDescription getSimpleMapperParser() {\n if (version.equals(Version.VERSION_1_0)) {\n return simpleMapperParser_1_0;\n } else if (version.equals(Version.VERSION_1_1)) {\n return simpleMapperParser_1_1;\n }\n return simpleMapperParser;\n }",
"protected boolean isZero( int index ) {\n double bottom = Math.abs(diag[index])+Math.abs(diag[index+1]);\n\n return( Math.abs(off[index]) <= bottom*UtilEjml.EPS);\n }",
"public static Session getSession(final ServerSetup setup, Properties mailProps) {\r\n Properties props = setup.configureJavaMailSessionProperties(mailProps, false);\r\n\r\n log.debug(\"Mail session properties are {}\", props);\r\n\r\n return Session.getInstance(props, null);\r\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public boolean isPlaying() {\n if (packetBytes.length >= 212) {\n return (packetBytes[STATUS_FLAGS] & PLAYING_FLAG) > 0;\n } else {\n final PlayState1 state = getPlayState1();\n return state == PlayState1.PLAYING || state == PlayState1.LOOPING ||\n (state == PlayState1.SEARCHING && getPlayState2() == PlayState2.MOVING);\n }\n }",
"public static Object invoke(Object object, String methodName, Object[] parameters) {\n try {\n Class[] classTypes = new Class[parameters.length];\n for (int i = 0; i < classTypes.length; i++) {\n classTypes[i] = parameters[i].getClass();\n }\n Method method = object.getClass().getMethod(methodName, classTypes);\n return method.invoke(object, parameters);\n } catch (Throwable t) {\n return InvokerHelper.invokeMethod(object, methodName, parameters);\n }\n }",
"private <T> T request(ClientRequest<T> delegate, String operationName) {\n long startTimeMs = -1;\n long startTimeNs = -1;\n\n if(logger.isDebugEnabled()) {\n startTimeMs = System.currentTimeMillis();\n }\n ClientRequestExecutor clientRequestExecutor = pool.checkout(destination);\n String debugMsgStr = \"\";\n\n startTimeNs = System.nanoTime();\n\n BlockingClientRequest<T> blockingClientRequest = null;\n try {\n blockingClientRequest = new BlockingClientRequest<T>(delegate, timeoutMs);\n clientRequestExecutor.addClientRequest(blockingClientRequest,\n timeoutMs,\n System.nanoTime() - startTimeNs);\n\n boolean awaitResult = blockingClientRequest.await();\n\n if(awaitResult == false) {\n blockingClientRequest.timeOut();\n }\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"success\";\n\n return blockingClientRequest.getResult();\n } catch(InterruptedException e) {\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"unreachable: \" + e.getMessage();\n\n throw new UnreachableStoreException(\"Failure in \" + operationName + \" on \"\n + destination + \": \" + e.getMessage(), e);\n } catch(UnreachableStoreException e) {\n clientRequestExecutor.close();\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"failure: \" + e.getMessage();\n\n throw new UnreachableStoreException(\"Failure in \" + operationName + \" on \"\n + destination + \": \" + e.getMessage(), e.getCause());\n } finally {\n if(blockingClientRequest != null && !blockingClientRequest.isComplete()) {\n // close the executor if we timed out\n clientRequestExecutor.close();\n }\n // Record operation time\n long opTimeNs = Utils.elapsedTimeNs(startTimeNs, System.nanoTime());\n if(stats != null) {\n stats.recordSyncOpTimeNs(destination, opTimeNs);\n }\n if(logger.isDebugEnabled()) {\n logger.debug(\"Sync request end, type: \"\n + operationName\n + \" requestRef: \"\n + System.identityHashCode(delegate)\n + \" totalTimeNs: \"\n + opTimeNs\n + \" start time: \"\n + startTimeMs\n + \" end time: \"\n + System.currentTimeMillis()\n + \" client:\"\n + clientRequestExecutor.getSocketChannel().socket().getLocalAddress()\n + \":\"\n + clientRequestExecutor.getSocketChannel().socket().getLocalPort()\n + \" server: \"\n + clientRequestExecutor.getSocketChannel()\n .socket()\n .getRemoteSocketAddress() + \" outcome: \"\n + debugMsgStr);\n }\n\n pool.checkin(destination, clientRequestExecutor);\n }\n }",
"@SuppressWarnings(\"deprecation\")\n @RequestMapping(value = \"/api/backup\", method = RequestMethod.GET)\n public\n @ResponseBody\n String getBackup(Model model, HttpServletResponse response) throws Exception {\n response.addHeader(\"Content-Disposition\", \"attachment; filename=backup.json\");\n response.setContentType(\"application/json\");\n\n Backup backup = BackupService.getInstance().getBackupData();\n ObjectMapper objectMapper = new ObjectMapper();\n ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();\n\n return writer.withView(ViewFilters.Default.class).writeValueAsString(backup);\n }",
"protected String addPostRunDependent(TaskGroup.HasTaskGroup dependent) {\n Objects.requireNonNull(dependent);\n this.taskGroup.addPostRunDependentTaskGroup(dependent.taskGroup());\n return dependent.taskGroup().key();\n }",
"public static void generateJavaFiles(String requirementsFolder,\n String platformName, String src_test_dir, String tests_package,\n String casemanager_package, String loggingPropFile)\n throws Exception {\n\n File reqFolder = new File(requirementsFolder);\n if (reqFolder.isDirectory()) {\n for (File f : reqFolder.listFiles()) {\n if (f.getName().endsWith(\".story\")) {\n try {\n SystemReader.generateJavaFilesForOneStory(\n f.getCanonicalPath(), platformName,\n src_test_dir, tests_package,\n casemanager_package, loggingPropFile);\n } catch (IOException e) {\n String message = \"ERROR: \" + e.getMessage();\n logger.severe(message);\n throw new BeastException(message, e);\n }\n }\n }\n for (File f : reqFolder.listFiles()) {\n if (f.isDirectory()) {\n SystemReader.generateJavaFiles(requirementsFolder\n + File.separator + f.getName(), platformName,\n src_test_dir, tests_package + \".\" + f.getName(),\n casemanager_package, loggingPropFile);\n }\n }\n } else if (reqFolder.getName().endsWith(\".story\")) {\n SystemReader.generateJavaFilesForOneStory(requirementsFolder,\n platformName, src_test_dir, tests_package,\n casemanager_package, loggingPropFile);\n } else {\n String message = \"No story file found in \" + requirementsFolder;\n logger.severe(message);\n throw new BeastException(message);\n }\n\n }"
] |
Creates an immutable list that consists of the elements in the given array. A copy of the given array is used which means
that any modifications to the given array will not affect the immutable list.
@param elements the given array of elements
@return an immutable list | [
"public static <T> List<T> copyOf(T[] elements) {\n Preconditions.checkNotNull(elements);\n return ofInternal(elements.clone());\n }"
] | [
"public <T extends CanvasReader> T getReader(Class<T> type, OauthToken oauthToken) {\n return getReader(type, oauthToken, null);\n }",
"public void link(Object targetObject, ClassDescriptor cld, ObjectReferenceDescriptor rds, Object referencedObject, boolean insert)\n {\n // MBAIRD: we have 'disassociated' this object from the referenced object,\n // the object represented by the reference descriptor is now null, so set\n // the fk in the target object to null.\n // arminw: if an insert was done and ref object was null, we should allow\n // to pass FK fields of main object (maybe only the FK fields are set)\n if (referencedObject == null)\n {\n /*\n arminw:\n if update we set FK fields to 'null', because reference was disassociated\n We do nothing on insert, maybe only the FK fields of main object (without\n materialization of the reference object) are set by the user\n */\n if(!insert)\n {\n unlinkFK(targetObject, cld, rds);\n }\n }\n else\n {\n setFKField(targetObject, cld, rds, referencedObject);\n }\n }",
"public int sum() {\n int total = 0;\n int N = getNumElements();\n for (int i = 0; i < N; i++) {\n if( data[i] )\n total += 1;\n }\n return total;\n }",
"public void setDuration(float start, float end)\n {\n for (GVRAnimation anim : mAnimations)\n {\n anim.setDuration(start,end);\n }\n }",
"public static String unexpand(CharSequence self, int tabStop) {\n String s = self.toString();\n if (s.length() == 0) return s;\n try {\n StringBuilder builder = new StringBuilder();\n for (String line : readLines((CharSequence) s)) {\n builder.append(unexpandLine(line, tabStop));\n builder.append(\"\\n\");\n }\n // remove the normalized ending line ending if it was not present\n if (!s.endsWith(\"\\n\")) {\n builder.deleteCharAt(builder.length() - 1);\n }\n return builder.toString();\n } catch (IOException e) {\n /* ignore */\n }\n return s;\n }",
"private void updatePreview(TrackMetadataUpdate update, WaveformPreview preview) {\n previewHotCache.put(DeckReference.getDeckReference(update.player, 0), preview); // Main deck\n if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well\n for (CueList.Entry entry : update.metadata.getCueList().entries) {\n if (entry.hotCueNumber != 0) {\n previewHotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), preview);\n }\n }\n }\n deliverWaveformPreviewUpdate(update.player, preview);\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 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 stripTrailingDelimiters(StringBuilder buffer)\n {\n int index = buffer.length() - 1;\n\n while (index > 0 && buffer.charAt(index) == m_delimiter)\n {\n --index;\n }\n\n buffer.setLength(index + 1);\n }"
] |
Tells you if an expression is the expected constant.
@param expression
any expression
@param expected
the expected int or String
@return
as described | [
"public static boolean isConstant(Expression expression, Object expected) {\r\n return expression instanceof ConstantExpression && expected.equals(((ConstantExpression) expression).getValue());\r\n }"
] | [
"private ModelNode resolveSubsystems(final List<ModelNode> extensions) {\n\n HostControllerLogger.ROOT_LOGGER.debug(\"Applying extensions provided by master\");\n final ModelNode result = operationExecutor.installSlaveExtensions(extensions);\n if (!SUCCESS.equals(result.get(OUTCOME).asString())) {\n throw HostControllerLogger.ROOT_LOGGER.failedToAddExtensions(result.get(FAILURE_DESCRIPTION));\n }\n final ModelNode subsystems = new ModelNode();\n for (final ModelNode extension : extensions) {\n extensionRegistry.recordSubsystemVersions(extension.asString(), subsystems);\n }\n return subsystems;\n }",
"private static long getVersionId(String versionDir) {\n try {\n return Long.parseLong(versionDir.replace(\"version-\", \"\"));\n } catch(NumberFormatException e) {\n logger.trace(\"Cannot parse version directory to obtain id \" + versionDir);\n return -1;\n }\n }",
"@NonNull\n @UiThread\n private HashMap<Integer, Boolean> generateExpandedStateMap() {\n HashMap<Integer, Boolean> parentHashMap = new HashMap<>();\n int childCount = 0;\n\n int listItemCount = mFlatItemList.size();\n for (int i = 0; i < listItemCount; i++) {\n if (mFlatItemList.get(i) != null) {\n ExpandableWrapper<P, C> listItem = mFlatItemList.get(i);\n if (listItem.isParent()) {\n parentHashMap.put(i - childCount, listItem.isExpanded());\n } else {\n childCount++;\n }\n }\n }\n\n return parentHashMap;\n }",
"public int[][] argb() {\n return Arrays.stream(points()).map(p -> argb(p.x, p.y)).toArray(int[][]::new);\n }",
"public static final UUID getUUID(InputStream is) throws IOException\n {\n byte[] data = new byte[16];\n is.read(data);\n\n long long1 = 0;\n long1 |= ((long) (data[3] & 0xFF)) << 56;\n long1 |= ((long) (data[2] & 0xFF)) << 48;\n long1 |= ((long) (data[1] & 0xFF)) << 40;\n long1 |= ((long) (data[0] & 0xFF)) << 32;\n long1 |= ((long) (data[5] & 0xFF)) << 24;\n long1 |= ((long) (data[4] & 0xFF)) << 16;\n long1 |= ((long) (data[7] & 0xFF)) << 8;\n long1 |= ((long) (data[6] & 0xFF)) << 0;\n\n long long2 = 0;\n long2 |= ((long) (data[8] & 0xFF)) << 56;\n long2 |= ((long) (data[9] & 0xFF)) << 48;\n long2 |= ((long) (data[10] & 0xFF)) << 40;\n long2 |= ((long) (data[11] & 0xFF)) << 32;\n long2 |= ((long) (data[12] & 0xFF)) << 24;\n long2 |= ((long) (data[13] & 0xFF)) << 16;\n long2 |= ((long) (data[14] & 0xFF)) << 8;\n long2 |= ((long) (data[15] & 0xFF)) << 0;\n\n return new UUID(long1, long2);\n }",
"private void writeAssignments()\n {\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n Resource resource = assignment.getResource();\n if (resource != null)\n {\n Task task = assignment.getTask();\n if (task != null && task.getUniqueID().intValue() != 0 && !task.getSummary())\n {\n writeAssignment(assignment);\n }\n }\n }\n }",
"public float getPositionZ(int vertex) {\n if (!hasPositions()) {\n throw new IllegalStateException(\"mesh has no positions\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_vertices.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT);\n }",
"private ProjectFile handleXerFile(InputStream stream) throws Exception\n {\n PrimaveraXERFileReader reader = new PrimaveraXERFileReader();\n reader.setCharset(m_charset);\n List<ProjectFile> projects = reader.readAll(stream);\n ProjectFile project = null;\n for (ProjectFile file : projects)\n {\n if (file.getProjectProperties().getExportFlag())\n {\n project = file;\n break;\n }\n }\n if (project == null && !projects.isEmpty())\n {\n project = projects.get(0);\n }\n return project;\n }",
"public static base_responses update(nitro_service client, autoscaleaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleaction updateresources[] = new autoscaleaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new autoscaleaction();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].profilename = resources[i].profilename;\n\t\t\t\tupdateresources[i].parameters = resources[i].parameters;\n\t\t\t\tupdateresources[i].vmdestroygraceperiod = resources[i].vmdestroygraceperiod;\n\t\t\t\tupdateresources[i].quiettime = resources[i].quiettime;\n\t\t\t\tupdateresources[i].vserver = resources[i].vserver;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}"
] |
Return the structured backup data
@return Backup of current configuration
@throws Exception exception | [
"public Backup getBackupData() throws Exception {\n Backup backupData = new Backup();\n\n backupData.setGroups(getGroups());\n backupData.setProfiles(getProfiles());\n ArrayList<Script> scripts = new ArrayList<Script>();\n Collections.addAll(scripts, ScriptService.getInstance().getScripts());\n backupData.setScripts(scripts);\n\n return backupData;\n }"
] | [
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getCount(String event) {\n EventDetail eventDetail = getLocalDataStore().getEventDetail(event);\n if (eventDetail != null) return eventDetail.getCount();\n\n return -1;\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 }",
"public String getAttributeValue(String attributeName)\n throws JMException, UnsupportedEncodingException {\n String decodedAttributeName = sanitizer.urlDecode(attributeName, encoding);\n return sanitizer.escapeValue(mBeanServer.getAttribute(objectName, decodedAttributeName));\n }",
"@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}",
"private static Predicate join(final String joinWord, final List<Predicate> preds) {\n return new Predicate() {\n public void init(AbstractSqlCreator creator) {\n for (Predicate p : preds) {\n p.init(creator);\n }\n }\n public String toSql() {\n StringBuilder sb = new StringBuilder()\n .append(\"(\");\n boolean first = true;\n for (Predicate p : preds) {\n if (!first) {\n sb.append(\" \").append(joinWord).append(\" \");\n }\n sb.append(p.toSql());\n first = false;\n }\n return sb.append(\")\").toString();\n }\n };\n }",
"protected AssemblyResponse watchStatus() throws LocalOperationException, RequestException {\n AssemblyResponse response;\n do {\n response = getClient().getAssemblyByUrl(url);\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n throw new LocalOperationException(e);\n }\n } while (!response.isFinished());\n\n setState(State.FINISHED);\n return response;\n }",
"@SafeVarargs\n public static void registerFilterTypes(final Class<? extends DynamicFilter>... types) {\n FILTER_TYPES.addAll(Arrays.asList(types));\n }",
"final public void addPositionRange(int start, int end) {\n if (tokenPosition == null) {\n tokenPosition = new MtasPosition(start, end);\n } else {\n int[] positions = new int[end - start + 1];\n for (int i = start; i <= end; i++) {\n positions[i - start] = i;\n }\n tokenPosition.add(positions);\n }\n }",
"public static void compress(File dir, File zipFile) throws IOException {\n\n FileOutputStream fos = new FileOutputStream(zipFile);\n ZipOutputStream zos = new ZipOutputStream(fos);\n\n recursiveAddZip(dir, zos, dir);\n\n zos.finish();\n zos.close();\n\n }"
] |
Get the photo or ticket id from the response.
@param async
@param response
@return | [
"private String getResponseString(boolean async, UploaderResponse response) {\r\n return async ? response.getTicketId() : response.getPhotoId();\r\n }"
] | [
"@SuppressWarnings({\"UnusedDeclaration\"})\n protected void doApi(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException {\n try {\n log.log(Level.INFO, \"Initiating Artifactory Release Staging using API\");\n // Enforce release permissions\n project.checkPermission(ArtifactoryPlugin.RELEASE);\n // In case a staging user plugin is configured, the init() method invoke it:\n init();\n // Read the values provided by the staging user plugin and assign them to data members in this class.\n // Those values can be overriden by URL arguments sent with the API:\n readStagingPluginValues();\n // Read values from the request and override the staging plugin values:\n overrideStagingPluginParams(req);\n // Schedule the release build:\n Queue.WaitingItem item = Jenkins.getInstance().getQueue().schedule(\n project, 0,\n new Action[]{this, new CauseAction(new Cause.UserIdCause())}\n );\n if (item == null) {\n log.log(Level.SEVERE, \"Failed to schedule a release build following a Release API invocation\");\n resp.setStatus(StaplerResponse.SC_INTERNAL_SERVER_ERROR);\n } else {\n String url = req.getContextPath() + '/' + item.getUrl();\n JSONObject json = new JSONObject();\n json.element(\"queueItem\", item.getId());\n json.element(\"releaseVersion\", getReleaseVersion());\n json.element(\"nextVersion\", getNextVersion());\n json.element(\"releaseBranch\", getReleaseBranch());\n // Must use getOutputStream as sendRedirect uses getOutputStream (and closes it)\n resp.getOutputStream().print(json.toString());\n resp.sendRedirect(201, url);\n }\n } catch (Exception e) {\n log.log(Level.SEVERE, \"Artifactory Release Staging API invocation failed: \" + e.getMessage(), e);\n resp.setStatus(StaplerResponse.SC_INTERNAL_SERVER_ERROR);\n ErrorResponse errorResponse = new ErrorResponse(StaplerResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());\n ObjectMapper mapper = new ObjectMapper();\n mapper.enable(SerializationFeature.INDENT_OUTPUT);\n resp.getWriter().write(mapper.writeValueAsString(errorResponse));\n }\n }",
"@Nullable\n private static Object valueOf(String value, Class<?> cls) {\n if (cls == Boolean.TYPE) {\n return Boolean.valueOf(value);\n }\n if (cls == Character.TYPE) {\n return value.length() >= 1 ? value.charAt(0) : defaultValue(char.class);\n }\n if (cls == Byte.TYPE) {\n return Byte.valueOf(value);\n }\n if (cls == Short.TYPE) {\n return Short.valueOf(value);\n }\n if (cls == Integer.TYPE) {\n return Integer.valueOf(value);\n }\n if (cls == Long.TYPE) {\n return Long.valueOf(value);\n }\n if (cls == Float.TYPE) {\n return Float.valueOf(value);\n }\n if (cls == Double.TYPE) {\n return Double.valueOf(value);\n }\n return null;\n }",
"public static void fillHermitian(ZMatrixRMaj A, double min, double max, Random rand) {\n if( A.numRows != A.numCols )\n throw new IllegalArgumentException(\"A must be a square matrix\");\n\n double range = max-min;\n\n int length = A.numRows;\n\n for( int i = 0; i < length; i++ ) {\n A.set(i,i,rand.nextDouble()*range + min,0);\n\n for( int j = i+1; j < length; j++ ) {\n double real = rand.nextDouble()*range + min;\n double imaginary = rand.nextDouble()*range + min;\n A.set(i,j,real,imaginary);\n A.set(j,i,real,-imaginary);\n }\n }\n }",
"@UiThread\n protected void parentExpandedFromViewHolder(int flatParentPosition) {\n ExpandableWrapper<P, C> parentWrapper = mFlatItemList.get(flatParentPosition);\n updateExpandedParent(parentWrapper, flatParentPosition, true);\n }",
"public static <InnerT> PagedList<InnerT> convertToPagedList(List<InnerT> list) {\n PageImpl<InnerT> page = new PageImpl<>();\n page.setItems(list);\n page.setNextPageLink(null);\n return new PagedList<InnerT>(page) {\n @Override\n public Page<InnerT> nextPage(String nextPageLink) {\n return null;\n }\n };\n }",
"public static boolean isFileExist(String filePath) {\r\n if (StringUtils.isEmpty(filePath)) {\r\n return false;\r\n }\r\n\r\n File file = new File(filePath);\r\n return (file.exists() && file.isFile());\r\n }",
"public String get(final String key) {\n final Collection<Argument> args = map.get(key);\n if (args != null) {\n return args.iterator().hasNext() ? args.iterator().next().getValue() : null;\n }\n return null;\n }",
"public static void outputString(final HttpServletResponse response, final Object obj) {\n try {\n response.setContentType(\"text/javascript\");\n response.setCharacterEncoding(\"utf-8\");\n disableCache(response);\n response.getWriter().write(obj.toString());\n response.getWriter().flush();\n response.getWriter().close();\n } catch (IOException e) {\n }\n }",
"public static double JensenShannonDivergence(double[] p, double[] q) {\n double[] m = new double[p.length];\n for (int i = 0; i < m.length; i++) {\n m[i] = (p[i] + q[i]) / 2;\n }\n\n return (KullbackLeiblerDivergence(p, m) + KullbackLeiblerDivergence(q, m)) / 2;\n }"
] |
Use this API to delete gslbsite resources of given names. | [
"public static base_responses delete(nitro_service client, String sitename[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (sitename != null && sitename.length > 0) {\n\t\t\tgslbsite deleteresources[] = new gslbsite[sitename.length];\n\t\t\tfor (int i=0;i<sitename.length;i++){\n\t\t\t\tdeleteresources[i] = new gslbsite();\n\t\t\t\tdeleteresources[i].sitename = sitename[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public List<String> subList(final long fromIndex, final long toIndex) {\n return doWithJedis(new JedisCallable<List<String>>() {\n @Override\n public List<String> call(Jedis jedis) {\n return jedis.lrange(getKey(), fromIndex, toIndex);\n }\n });\n }",
"private static boolean waitTillNoNotifications(Environment env, TableRange range)\n throws TableNotFoundException {\n boolean sawNotifications = false;\n long retryTime = MIN_SLEEP_MS;\n\n log.debug(\"Scanning tablet {} for notifications\", range);\n\n long start = System.currentTimeMillis();\n while (hasNotifications(env, range)) {\n sawNotifications = true;\n long sleepTime = Math.max(System.currentTimeMillis() - start, retryTime);\n log.debug(\"Tablet {} had notfications, will rescan in {}ms\", range, sleepTime);\n UtilWaitThread.sleep(sleepTime);\n retryTime = Math.min(MAX_SLEEP_MS, (long) (retryTime * 1.5));\n start = System.currentTimeMillis();\n }\n\n return sawNotifications;\n }",
"public static void writeHints(File file, Map<String,List<Long>> hints) throws IOException {\n Closer closer = Closer.create();\n try {\n BufferedWriter w = closer.register(Files.newWriter(file, Charsets.UTF_8));\n if (!(hints instanceof SortedMap)) {\n hints = new TreeMap<String,List<Long>>(hints);\n }\n \n Joiner joiner = Joiner.on(',');\n for (Map.Entry<String,List<Long>> e : hints.entrySet()) {\n w.write(e.getKey());\n w.write(\"=\");\n joiner.appendTo(w, e.getValue());\n w.write(\"\\n\");\n }\n } catch (Throwable t) {\n throw closer.rethrow(t);\n } finally {\n closer.close();\n }\n }",
"protected <T, A> ActiveOperation<T, A> getActiveOperation(final ManagementRequestHeader header) {\n return getActiveOperation(header.getBatchId());\n }",
"private static String[] readArgsFile(String argsFile) throws IOException {\n final ArrayList<String> lines = new ArrayList<String>();\n final BufferedReader reader = new BufferedReader(\n new InputStreamReader(\n new FileInputStream(argsFile), \"UTF-8\"));\n try {\n String line;\n while ((line = reader.readLine()) != null) {\n line = line.trim();\n if (!line.isEmpty() && !line.startsWith(\"#\")) {\n lines.add(line);\n }\n }\n } finally {\n reader.close();\n }\n return lines.toArray(new String [lines.size()]);\n }",
"@UiHandler(\"m_wholeDayCheckBox\")\n void onWholeDayChange(ValueChangeEvent<Boolean> event) {\n\n //TODO: Improve - adjust time selections?\n if (handleChange()) {\n m_controller.setWholeDay(event.getValue());\n }\n }",
"public static float calculateMaxTextHeight(Paint _Paint, String _Text) {\n Rect height = new Rect();\n String text = _Text == null ? \"MgHITasger\" : _Text;\n _Paint.getTextBounds(text, 0, text.length(), height);\n return height.height();\n }",
"private static TechReportPlacement processPlaceLabels(GraphContext graphContext, Set<String> tagNames)\n {\n TagGraphService tagService = new TagGraphService(graphContext);\n\n if (tagNames.size() < 3)\n throw new WindupException(\"There should always be exactly 3 placement labels - row, sector, column/box. It was: \" + tagNames);\n if (tagNames.size() > 3)\n LOG.severe(\"There should always be exactly 3 placement labels - row, sector, column/box. It was: \" + tagNames);\n\n TechReportPlacement placement = new TechReportPlacement();\n\n final TagModel placeSectorsTag = tagService.getTagByName(\"techReport:placeSectors\");\n final TagModel placeBoxesTag = tagService.getTagByName(\"techReport:placeBoxes\");\n final TagModel placeRowsTag = tagService.getTagByName(\"techReport:placeRows\");\n\n Set<String> unknownTags = new HashSet<>();\n for (String name : tagNames)\n {\n final TagModel tag = tagService.getTagByName(name);\n if (null == tag)\n continue;\n\n if (TagGraphService.isTagUnderTagOrSame(tag, placeSectorsTag))\n {\n placement.sector = tag;\n }\n else if (TagGraphService.isTagUnderTagOrSame(tag, placeBoxesTag))\n {\n placement.box = tag;\n }\n else if (TagGraphService.isTagUnderTagOrSame(tag, placeRowsTag))\n {\n placement.row = tag;\n }\n else\n {\n unknownTags.add(name);\n }\n }\n placement.unknown = unknownTags;\n\n LOG.fine(String.format(\"\\t\\tLabels %s identified as: sector: %s, box: %s, row: %s\", tagNames, placement.sector, placement.box,\n placement.row));\n if (placement.box == null || placement.row == null)\n {\n LOG.severe(String.format(\n \"There should always be exactly 3 placement labels - row, sector, column/box. Found: %s, of which box: %s, row: %s\", tagNames,\n placement.box, placement.row));\n }\n return placement;\n }",
"public List<DbComment> getComments(String entityId, String entityType) {\n return repositoryHandler.getComments(entityId, entityType);\n }"
] |
Internal utility to dump relationship lists in a structured format
that can easily be compared with the tabular data in MS Project.
@param relations relation list | [
"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 }"
] | [
"private void renderThumbnail(Video video) {\n Picasso.with(getContext()).cancelRequest(thumbnail);\n Picasso.with(getContext())\n .load(video.getThumbnail())\n .placeholder(R.drawable.placeholder)\n .into(thumbnail);\n }",
"public String toIPTC(SubjectReferenceSystem srs) {\r\n\t\tStringBuffer b = new StringBuffer();\r\n\t\tb.append(\"IPTC:\");\r\n\t\tb.append(getNumber());\r\n\t\tb.append(\":\");\r\n\t\tif (getNumber().endsWith(\"000000\")) {\r\n\t\t\tb.append(toIPTCHelper(srs.getName(this)));\r\n\t\t\tb.append(\"::\");\r\n\t\t} else if (getNumber().endsWith(\"000\")) {\r\n\t\t\tb.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 2) + \"000000\"))));\r\n\t\t\tb.append(\":\");\r\n\t\t\tb.append(toIPTCHelper(srs.getName(this)));\r\n\t\t\tb.append(\":\");\r\n\t\t} else {\r\n\t\t\tb.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 2) + \"000000\"))));\r\n\t\t\tb.append(\":\");\r\n\t\t\tb.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 5) + \"000\"))));\r\n\t\t\tb.append(\":\");\r\n\t\t\tb.append(toIPTCHelper(srs.getName(this)));\r\n\t\t}\r\n\t\treturn b.toString();\r\n\t}",
"public static final boolean valueIsNotDefault(FieldType type, Object value)\n {\n boolean result = true;\n\n if (value == null)\n {\n result = false;\n }\n else\n {\n DataType dataType = type.getDataType();\n switch (dataType)\n {\n case BOOLEAN:\n {\n result = ((Boolean) value).booleanValue();\n break;\n }\n\n case CURRENCY:\n case NUMERIC:\n {\n result = !NumberHelper.equals(((Number) value).doubleValue(), 0.0, 0.00001);\n break;\n }\n\n case DURATION:\n {\n result = (((Duration) value).getDuration() != 0);\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n return result;\n }",
"@Deprecated\n\t@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tpublic Map<String, PrimitiveAttribute<?>> getAttributes() {\n\t\tif (!isPrimitiveOnly()) {\n\t\t\tthrow new UnsupportedOperationException(\"Primitive API not supported for nested association values\");\n\t\t}\n\t\treturn (Map) attributes;\n\t}",
"public synchronized boolean tryDelegateSlop(Node node) {\n if(asyncCallbackShouldSendhint) {\n return false;\n } else {\n slopDestinations.put(node, true);\n return true;\n }\n }",
"public static Event map(EventType eventType) {\n Event event = new Event();\n event.setEventType(mapEventTypeEnum(eventType.getEventType()));\n Date date = (eventType.getTimestamp() == null)\n ? new Date() : eventType.getTimestamp().toGregorianCalendar().getTime();\n event.setTimestamp(date);\n event.setOriginator(mapOriginatorType(eventType.getOriginator()));\n MessageInfo messageInfo = mapMessageInfo(eventType.getMessageInfo());\n event.setMessageInfo(messageInfo);\n String content = mapContent(eventType.getContent());\n event.setContent(content);\n event.getCustomInfo().clear();\n event.getCustomInfo().putAll(mapCustomInfo(eventType.getCustomInfo()));\n return event;\n }",
"static Object getLCState(StateManagerInternal sm)\r\n\t{\r\n\t\t// unfortunately the LifeCycleState classes are package private.\r\n\t\t// so we have to do some dirty reflection hack to access them\r\n\t\ttry\r\n\t\t{\r\n\t\t\tField myLC = sm.getClass().getDeclaredField(\"myLC\");\r\n\t\t\tmyLC.setAccessible(true);\r\n\t\t\treturn myLC.get(sm);\r\n\t\t}\r\n\t\tcatch (NoSuchFieldException e)\r\n\t\t{\r\n\t\t\treturn e;\r\n\t\t}\r\n\t\tcatch (IllegalAccessException e)\r\n\t\t{\r\n\t\t\treturn e;\r\n\t\t}\t\r\n\t}",
"public static Object buildNewObjectInstance(ClassDescriptor cld)\r\n {\r\n Object result = null;\r\n\r\n // If either the factory class and/or factory method is null,\r\n // just follow the normal code path and create via constructor\r\n if ((cld.getFactoryClass() == null) || (cld.getFactoryMethod() == null))\r\n {\r\n try\r\n {\r\n // 1. create an empty Object (persistent classes need a public default constructor)\r\n Constructor con = cld.getZeroArgumentConstructor();\r\n if(con == null)\r\n {\r\n throw new ClassNotPersistenceCapableException(\r\n \"A zero argument constructor was not provided! Class was '\" + cld.getClassNameOfObject() + \"'\");\r\n }\r\n result = ConstructorHelper.instantiate(con);\r\n }\r\n catch (InstantiationException e)\r\n {\r\n throw new ClassNotPersistenceCapableException(\r\n \"Can't instantiate class '\" + cld.getClassNameOfObject()+\"'\");\r\n }\r\n }\r\n else\r\n {\r\n try\r\n {\r\n // 1. create an empty Object by calling the no-parms factory method\r\n Method method = cld.getFactoryMethod();\r\n\r\n if (Modifier.isStatic(method.getModifiers()))\r\n {\r\n // method is static so call it directly\r\n result = method.invoke(null, null);\r\n }\r\n else\r\n {\r\n // method is not static, so create an object of the factory first\r\n // note that this requires a public no-parameter (default) constructor\r\n Object factoryInstance = cld.getFactoryClass().newInstance();\r\n\r\n result = method.invoke(factoryInstance, null);\r\n }\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(\"Unable to build object instance of class '\"\r\n + cld.getClassNameOfObject() + \"' from factory:\" + cld.getFactoryClass()\r\n + \".\" + cld.getFactoryMethod(), ex);\r\n }\r\n }\r\n return result;\r\n }",
"private void populateMetaData() throws SQLException\n {\n m_meta.clear();\n\n ResultSetMetaData meta = m_rs.getMetaData();\n int columnCount = meta.getColumnCount() + 1;\n for (int loop = 1; loop < columnCount; loop++)\n {\n String name = meta.getColumnName(loop);\n Integer type = Integer.valueOf(meta.getColumnType(loop));\n m_meta.put(name, type);\n }\n }"
] |
Get http response | [
"public static HttpResponse getResponse(String urls, HttpRequest request,\n HttpMethod method, int connectTimeoutMillis, int readTimeoutMillis) throws IOException {\n OutputStream out = null;\n InputStream content = null;\n HttpResponse response = null;\n HttpURLConnection httpConn = request\n .getHttpConnection(urls, method.name());\n httpConn.setConnectTimeout(connectTimeoutMillis);\n httpConn.setReadTimeout(readTimeoutMillis);\n\n try {\n httpConn.connect();\n if (null != request.getPayload() && request.getPayload().length > 0) {\n out = httpConn.getOutputStream();\n out.write(request.getPayload());\n }\n content = httpConn.getInputStream();\n response = new HttpResponse();\n parseHttpConn(response, httpConn, content);\n return response;\n } catch (SocketTimeoutException e) {\n throw e;\n } catch (IOException e) {\n content = httpConn.getErrorStream();\n response = new HttpResponse();\n parseHttpConn(response, httpConn, content);\n return response;\n } finally {\n if (content != null) {\n content.close();\n }\n httpConn.disconnect();\n }\n }"
] | [
"private ArrayList handleDependentReferences(Identity oid, Object userObject,\r\n Object[] origFields, Object[] newFields, Object[] newRefs)\r\n throws LockingException\r\n {\r\n ClassDescriptor mif = _pb.getClassDescriptor(userObject.getClass());\r\n FieldDescriptor[] fieldDescs = mif.getFieldDescriptions();\r\n Collection refDescs = mif.getObjectReferenceDescriptors();\r\n int count = 1 + fieldDescs.length;\r\n ArrayList newObjects = new ArrayList();\r\n int countRefs = 0;\r\n\r\n for (Iterator it = refDescs.iterator(); it.hasNext(); count++, countRefs++)\r\n {\r\n ObjectReferenceDescriptor rds = (ObjectReferenceDescriptor) it.next();\r\n Identity origOid = (origFields == null ? null : (Identity) origFields[count]);\r\n Identity newOid = (Identity) newFields[count];\r\n\r\n if (rds.getOtmDependent())\r\n {\r\n if ((origOid == null) && (newOid != null))\r\n {\r\n ContextEntry entry = (ContextEntry) _objects.get(newOid);\r\n\r\n if (entry == null)\r\n {\r\n Object relObj = newRefs[countRefs];\r\n insertInternal(newOid, relObj, LockType.WRITE_LOCK,\r\n true, oid, new Stack());\r\n newObjects.add(newOid);\r\n }\r\n }\r\n else if ((origOid != null) &&\r\n ((newOid == null) || !newOid.equals(origOid)))\r\n {\r\n markDelete(origOid, oid, false);\r\n }\r\n }\r\n }\r\n\r\n return newObjects;\r\n }",
"private String getPropertyName(Method method)\n {\n String result = method.getName();\n if (result.startsWith(\"get\"))\n {\n result = result.substring(3);\n }\n return result;\n }",
"public void setYearlyAbsoluteFromDate(Date date)\n {\n if (date != null)\n {\n Calendar cal = DateHelper.popCalendar(date);\n m_dayNumber = Integer.valueOf(cal.get(Calendar.DAY_OF_MONTH));\n m_monthNumber = Integer.valueOf(cal.get(Calendar.MONTH) + 1);\n DateHelper.pushCalendar(cal);\n }\n }",
"public void updateConfig(String appName, Map<String, String> config) {\n connection.execute(new ConfigUpdate(appName, config), apiKey);\n }",
"public static void block(DMatrix1Row A , DMatrix1Row A_tran ,\n final int blockLength )\n {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int blockHeight = Math.min( blockLength , A.numRows - i);\n\n int indexSrc = i*A.numCols;\n int indexDst = i;\n\n for( int j = 0; j < A.numCols; j += blockLength ) {\n int blockWidth = Math.min( blockLength , A.numCols - j);\n\n// int indexSrc = i*A.numCols + j;\n// int indexDst = j*A_tran.numCols + i;\n\n int indexSrcEnd = indexSrc + blockWidth;\n// for( int l = 0; l < blockWidth; l++ , indexSrc++ ) {\n for( ; indexSrc < indexSrcEnd; indexSrc++ ) {\n int rowSrc = indexSrc;\n int rowDst = indexDst;\n int end = rowDst + blockHeight;\n// for( int k = 0; k < blockHeight; k++ , rowSrc += A.numCols ) {\n for( ; rowDst < end; rowSrc += A.numCols ) {\n // faster to write in sequence than to read in sequence\n A_tran.data[ rowDst++ ] = A.data[ rowSrc ];\n }\n indexDst += A_tran.numCols;\n }\n }\n }\n }",
"public static java.sql.Timestamp getTimestamp(Object value) {\n try {\n return toTimestamp(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }",
"synchronized void processFinished() {\n final InternalState required = this.requiredState;\n final InternalState state = this.internalState;\n // If the server was not stopped\n if(required == InternalState.STOPPED && state == InternalState.PROCESS_STOPPING) {\n finishTransition(InternalState.PROCESS_STOPPING, InternalState.PROCESS_STOPPED);\n } else {\n this.requiredState = InternalState.STOPPED;\n if ( !(internalSetState(getTransitionTask(InternalState.PROCESS_STOPPING), internalState, InternalState.PROCESS_STOPPING)\n && internalSetState(getTransitionTask(InternalState.PROCESS_REMOVING), internalState, InternalState.PROCESS_REMOVING)\n && internalSetState(getTransitionTask(InternalState.STOPPED), internalState, InternalState.STOPPED)) ){\n this.requiredState = InternalState.FAILED;\n internalSetState(null, internalState, InternalState.PROCESS_STOPPED);\n }\n }\n }",
"static void rethrowIrrecoverableConnectionFailures(IOException e) throws SlaveRegistrationException {\n Throwable cause = e;\n while ((cause = cause.getCause()) != null) {\n if (cause instanceof SaslException) {\n throw HostControllerLogger.ROOT_LOGGER.authenticationFailureUnableToConnect(cause);\n } else if (cause instanceof SSLHandshakeException) {\n throw HostControllerLogger.ROOT_LOGGER.sslFailureUnableToConnect(cause);\n } else if (cause instanceof SlaveRegistrationException) {\n throw (SlaveRegistrationException) cause;\n }\n }\n }",
"private void store(final PrintJobStatus printJobStatus) throws JSONException {\n JSONObject metadata = new JSONObject();\n metadata.put(JSON_REQUEST_DATA, printJobStatus.getEntry().getRequestData().getInternalObj());\n metadata.put(JSON_STATUS, printJobStatus.getStatus().toString());\n metadata.put(JSON_START_DATE, printJobStatus.getStartTime());\n metadata.put(JSON_REQUEST_COUNT, printJobStatus.getRequestCount());\n if (printJobStatus.getCompletionDate() != null) {\n metadata.put(JSON_COMPLETION_DATE, printJobStatus.getCompletionTime());\n }\n metadata.put(JSON_ACCESS_ASSERTION, this.assertionPersister.marshal(printJobStatus.getAccess()));\n if (printJobStatus.getError() != null) {\n metadata.put(JSON_ERROR, printJobStatus.getError());\n }\n if (printJobStatus.getResult() != null) {\n metadata.put(JSON_REPORT_URI, printJobStatus.getResult().getReportURIString());\n metadata.put(JSON_FILENAME, printJobStatus.getResult().getFileName());\n metadata.put(JSON_FILE_EXT, printJobStatus.getResult().getFileExtension());\n metadata.put(JSON_MIME_TYPE, printJobStatus.getResult().getMimeType());\n }\n this.registry.put(RESULT_METADATA + printJobStatus.getReferenceId(), metadata);\n }"
] |
Creates a new SimpleMatrix with the specified DMatrixRMaj used as its internal matrix. This means
that the reference is saved and calls made to the returned SimpleMatrix will modify the passed in DMatrixRMaj.
@param internalMat The internal DMatrixRMaj of the returned SimpleMatrix. Will be modified. | [
"public static SimpleMatrix wrap( Matrix internalMat ) {\n SimpleMatrix ret = new SimpleMatrix();\n ret.setMatrix(internalMat);\n return ret;\n }"
] | [
"public static Integer convertProfileIdentifier(String profileIdentifier) throws Exception {\n Integer profileId = -1;\n if (profileIdentifier == null) {\n throw new Exception(\"A profileIdentifier must be specified\");\n } else {\n try {\n profileId = Integer.parseInt(profileIdentifier);\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n // try to get it by name instead\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n\n }\n }\n logger.info(\"Profile id is {}\", profileId);\n return profileId;\n }",
"public int getIndex(T value) {\n int count = getItemCount();\n for (int i = 0; i < count; i++) {\n if (Objects.equals(getValue(i), value)) {\n return i;\n }\n }\n return -1;\n }",
"private void performTeardownExchange() throws IOException {\n Message teardownRequest = new Message(0xfffffffeL, Message.KnownType.TEARDOWN_REQ);\n sendMessage(teardownRequest);\n // At this point, the server closes the connection from its end, so we can’t read any more.\n }",
"public List<DbLicense> getArtifactLicenses(final String gavc, final FiltersHolder filters) {\n final DbArtifact artifact = getArtifact(gavc);\n final List<DbLicense> licenses = new ArrayList<>();\n\n for(final String name: artifact.getLicenses()){\n final Set<DbLicense> matchingLicenses = licenseMatcher.getMatchingLicenses(name);\n\n // Here is a license to identify\n if(matchingLicenses.isEmpty()){\n final DbLicense notIdentifiedLicense = new DbLicense();\n notIdentifiedLicense.setName(name);\n licenses.add(notIdentifiedLicense);\n } else {\n matchingLicenses.stream()\n .filter(filters::shouldBeInReport)\n .forEach(licenses::add);\n }\n }\n\n return licenses;\n }",
"public CrosstabBuilder useMainReportDatasource(boolean preSorted) {\r\n\t\tDJDataSource datasource = new DJDataSource(\"ds\",DJConstants.DATA_SOURCE_ORIGIN_REPORT_DATASOURCE,DJConstants.DATA_SOURCE_TYPE_JRDATASOURCE);\r\n\t\tdatasource.setPreSorted(preSorted);\r\n\t\tcrosstab.setDatasource(datasource);\r\n\t\treturn this;\r\n\t}",
"private Integer getOutlineLevel(Task task)\n {\n String value = task.getWBS();\n Integer result = Integer.valueOf(1);\n if (value != null && value.length() > 0)\n {\n String[] path = WBS_SPLIT_REGEX.split(value);\n result = Integer.valueOf(path.length);\n }\n return result;\n }",
"private void writePropertyData() {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"properties.csv\"))) {\n\n\t\t\tout.println(\"Id\" + \",Label\" + \",Description\" + \",URL\" + \",Datatype\"\n\t\t\t\t\t+ \",Uses in statements\" + \",Items with such statements\"\n\t\t\t\t\t+ \",Uses in statements with qualifiers\"\n\t\t\t\t\t+ \",Uses in qualifiers\" + \",Uses in references\"\n\t\t\t\t\t+ \",Uses total\" + \",Related properties\");\n\n\t\t\tList<Entry<PropertyIdValue, PropertyRecord>> list = new ArrayList<Entry<PropertyIdValue, PropertyRecord>>(\n\t\t\t\t\tthis.propertyRecords.entrySet());\n\t\t\tCollections.sort(list, new UsageRecordComparator());\n\t\t\tfor (Entry<PropertyIdValue, PropertyRecord> entry : list) {\n\t\t\t\tprintPropertyRecord(out, entry.getValue(), entry.getKey());\n\t\t\t}\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"private void captureEye(GVRScreenshotCallback callback, GVRRenderTarget renderTarget, GVRViewManager.EYE eye, boolean useMultiview) {\n if (null == callback) {\n return;\n }\n readRenderResult(renderTarget,eye,useMultiview);\n returnScreenshotToCaller(callback, mReadbackBufferWidth, mReadbackBufferHeight);\n }",
"protected void rehash(int newCapacity) {\r\n\tint oldCapacity = table.length;\r\n\t//if (oldCapacity == newCapacity) return;\r\n\t\r\n\tlong oldTable[] = table;\r\n\tint oldValues[] = values;\r\n\tbyte oldState[] = state;\r\n\r\n\tlong newTable[] = new long[newCapacity];\r\n\tint newValues[] = new int[newCapacity];\r\n\tbyte newState[] = new byte[newCapacity];\r\n\r\n\tthis.lowWaterMark = chooseLowWaterMark(newCapacity,this.minLoadFactor);\r\n\tthis.highWaterMark = chooseHighWaterMark(newCapacity,this.maxLoadFactor);\r\n\r\n\tthis.table = newTable;\r\n\tthis.values = newValues;\r\n\tthis.state = newState;\r\n\tthis.freeEntries = newCapacity-this.distinct; // delta\r\n\t\r\n\tfor (int i = oldCapacity ; i-- > 0 ;) {\r\n\t\tif (oldState[i]==FULL) {\r\n\t\t\tlong element = oldTable[i];\r\n\t\t\tint index = indexOfInsertion(element);\r\n\t\t\tnewTable[index]=element;\r\n\t\t\tnewValues[index]=oldValues[i];\r\n\t\t\tnewState[index]=FULL;\r\n\t\t}\r\n\t}\r\n}"
] |
Removes a design document using DesignDocument object from the database.
@param designDocument the design document object to be removed
@return {@link DesignDocument} | [
"public Response remove(DesignDocument designDocument) {\r\n assertNotEmpty(designDocument, \"DesignDocument\");\r\n ensureDesignPrefixObject(designDocument);\r\n return db.remove(designDocument);\r\n }"
] | [
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<CopticDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<CopticDate>) super.zonedDateTime(temporal);\n }",
"protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n \r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n \r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading schemas for catalog \" \r\n + this.getAttribute(ATT_CATALOG_NAME));\r\n rs = getDbMeta().getSchemas();\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n int count = 0;\r\n while (rs.next())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Creating schema \" + getCatalogName() + \".\" + rs.getString(\"TABLE_SCHEM\"));\r\n alNew.add(new DBMetaSchemaNode(getDbMeta(),\r\n getDbMetaTreeModel(),\r\n DBMetaCatalogNode.this, \r\n rs.getString(\"TABLE_SCHEM\")));\r\n count++;\r\n }\r\n if (count == 0) \r\n alNew.add(new DBMetaSchemaNode(getDbMeta(), \r\n getDbMetaTreeModel(),\r\n DBMetaCatalogNode.this, null));\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaCatalogNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n getDbMetaTreeModel().reportSqlError(\"Error retrieving schemas\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving schemas\", sqlEx2);\r\n } \r\n return false;\r\n }\r\n return true;\r\n }",
"@SuppressWarnings({\"OverlyLongMethod\"})\n public void clearProperties(@NotNull final PersistentStoreTransaction txn, @NotNull final Entity entity) {\n final Transaction envTxn = txn.getEnvironmentTransaction();\n final PersistentEntityId id = (PersistentEntityId) entity.getId();\n final int entityTypeId = id.getTypeId();\n final long entityLocalId = id.getLocalId();\n final PropertiesTable properties = getPropertiesTable(txn, entityTypeId);\n final PropertyKey propertyKey = new PropertyKey(entityLocalId, 0);\n try (Cursor cursor = getPrimaryPropertyIndexCursor(txn, properties)) {\n for (boolean success = cursor.getSearchKeyRange(PropertyKey.propertyKeyToEntry(propertyKey)) != null;\n success; success = cursor.getNext()) {\n ByteIterable keyEntry = cursor.getKey();\n final PropertyKey key = PropertyKey.entryToPropertyKey(keyEntry);\n if (key.getEntityLocalId() != entityLocalId) {\n break;\n }\n final int propertyId = key.getPropertyId();\n final ByteIterable value = cursor.getValue();\n final PropertyValue propValue = propertyTypes.entryToPropertyValue(value);\n txn.propertyChanged(id, propertyId, propValue.getData(), null);\n properties.deleteNoFail(txn, entityLocalId, value, propertyId, propValue.getType());\n }\n }\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 static CharSequence convertReverseDNSIPv4(String str, int suffixStartIndex) throws AddressStringException {\n\t\tStringBuilder builder = new StringBuilder(suffixStartIndex);\n\t\tint segCount = 0;\n\t\tint j = suffixStartIndex;\n\t\tfor(int i = suffixStartIndex - 1; i > 0; i--) {\n\t\t\tchar c1 = str.charAt(i);\n\t\t\tif(c1 == IPv4Address.SEGMENT_SEPARATOR) {\n\t\t\t\tif(j - i <= 1) {\n\t\t\t\t\tthrow new AddressStringException(str, i);\n\t\t\t\t}\n\t\t\t\tfor(int k = i + 1; k < j; k++) {\n\t\t\t\t\tbuilder.append(str.charAt(k));\n\t\t\t\t}\n\t\t\t\tbuilder.append(c1);\n\t\t\t\tj = i;\n\t\t\t\tsegCount++;\n\t\t\t}\n\t\t}\n\t\tfor(int k = 0; k < j; k++) {\n\t\t\tbuilder.append(str.charAt(k));\n\t\t}\n\t\tif(segCount + 1 != IPv4Address.SEGMENT_COUNT) {\n\t\t\tthrow new AddressStringException(str, 0);\n\t\t}\n\t\treturn builder;\n\t}",
"public BoxCollaborationWhitelistExemptTarget.Info getInfo() {\n URL url = COLLABORATION_WHITELIST_EXEMPT_TARGET_ENTRY_URL_TEMPLATE.build(this.getAPI().getBaseURL(),\n this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n return new Info(JsonObject.readFrom(response.getJSON()));\n }",
"public synchronized List<String> propertyListOf(Class<?> c) {\n String cn = c.getName();\n List<String> ls = repo.get(cn);\n if (ls != null) {\n return ls;\n }\n Set<Class<?>> circularReferenceDetector = new HashSet<>();\n ls = propertyListOf(c, circularReferenceDetector, null);\n repo.put(c.getName(), ls);\n return ls;\n }",
"public static double blackScholesATMOptionValue(\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble forward,\n\t\t\tdouble payoffUnit)\n\t{\n\t\tif(optionMaturity < 0) {\n\t\t\treturn 0.0;\n\t\t}\n\n\t\t// Calculate analytic value\n\t\tdouble dPlus = 0.5 * volatility * Math.sqrt(optionMaturity);\n\t\tdouble dMinus = -dPlus;\n\n\t\tdouble valueAnalytic = (NormalDistribution.cumulativeDistribution(dPlus) - NormalDistribution.cumulativeDistribution(dMinus)) * forward * payoffUnit;\n\n\t\treturn valueAnalytic;\n\t}",
"public static <K, V, T> Map<K, List<Versioned<V>>> getAll(Store<K, V, T> storageEngine,\n Iterable<K> keys,\n Map<K, T> transforms) {\n Map<K, List<Versioned<V>>> result = newEmptyHashMap(keys);\n for(K key: keys) {\n List<Versioned<V>> value = storageEngine.get(key,\n transforms != null ? transforms.get(key)\n : null);\n if(!value.isEmpty())\n result.put(key, value);\n }\n return result;\n }"
] |
Use this API to fetch all the nsdiameter resources that are configured on netscaler. | [
"public static nsdiameter get(nitro_service service) throws Exception{\n\t\tnsdiameter obj = new nsdiameter();\n\t\tnsdiameter[] response = (nsdiameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}"
] | [
"private void readPredecessors(Project.Tasks.Task task)\n {\n Integer uid = task.getUID();\n if (uid != null)\n {\n Task currTask = m_projectFile.getTaskByUniqueID(uid);\n if (currTask != null)\n {\n for (Project.Tasks.Task.PredecessorLink link : task.getPredecessorLink())\n {\n readPredecessor(currTask, link);\n }\n }\n }\n }",
"public static Date getDateFromLong(long date)\n {\n TimeZone tz = TimeZone.getDefault();\n return (new Date(date - tz.getRawOffset()));\n }",
"public static Method getGetterPropertyMethod(Class<?> type,\r\n\t\t\tString propertyName) {\r\n\t\tString sourceMethodName = \"get\"\r\n\t\t\t\t+ BeanUtils.capitalizePropertyName(propertyName);\r\n\r\n\t\tMethod sourceMethod = BeanUtils.getMethod(type, sourceMethodName);\r\n\r\n\t\tif (sourceMethod == null) {\r\n\t\t\tsourceMethodName = \"is\"\r\n\t\t\t\t\t+ BeanUtils.capitalizePropertyName(propertyName);\r\n\t\t\tsourceMethod = BeanUtils.getMethod(type, sourceMethodName);\r\n\t\t\tif (sourceMethod != null\r\n\t\t\t\t\t&& sourceMethod.getReturnType() != Boolean.TYPE) {\r\n\t\t\t\tsourceMethod = null;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn sourceMethod;\r\n\t}",
"public static ipset get(nitro_service service, String name) throws Exception{\n\t\tipset obj = new ipset();\n\t\tobj.set_name(name);\n\t\tipset response = (ipset) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public void fire(TestCaseEvent event) {\n TestCaseResult testCase = testCaseStorage.get();\n event.process(testCase);\n\n notifier.fire(event);\n }",
"public Quaternionf ConvertDirectionalVectorToQuaternion(Vector3f d) {\n d.negate();\n Quaternionf q = new Quaternionf();\n // check for exception condition\n if ((d.x == 0) && (d.z == 0)) {\n // exception condition if direction is (0,y,0):\n // straight up, straight down or all zero's.\n if (d.y > 0) { // direction straight up\n AxisAngle4f angleAxis = new AxisAngle4f(-(float) Math.PI / 2, 1, 0,\n 0);\n q.set(angleAxis);\n } else if (d.y < 0) { // direction straight down\n AxisAngle4f angleAxis = new AxisAngle4f((float) Math.PI / 2, 1, 0, 0);\n q.set(angleAxis);\n } else { // All zero's. Just set to identity quaternion\n q.identity();\n }\n } else {\n d.normalize();\n Vector3f up = new Vector3f(0, 1, 0);\n Vector3f s = new Vector3f();\n d.cross(up, s);\n s.normalize();\n Vector3f u = new Vector3f();\n d.cross(s, u);\n u.normalize();\n Matrix4f matrix = new Matrix4f(s.x, s.y, s.z, 0, u.x, u.y, u.z, 0, d.x,\n d.y, d.z, 0, 0, 0, 0, 1);\n q.setFromNormalized(matrix);\n }\n return q;\n }",
"public void addColumnIsNull(String column)\r\n {\r\n\t\t// PAW\r\n\t\t//SelectionCriteria c = ValueCriteria.buildNullCriteria(column, getAlias());\r\n\t\tSelectionCriteria c = ValueCriteria.buildNullCriteria(column, getUserAlias(column));\r\n c.setTranslateAttribute(false);\r\n addSelectionCriteria(c);\r\n }",
"public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n String url = null;\n\n // parse command-line input\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n\n // load parameters\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n\n // execute command\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n doMetaCheckVersion(adminClient);\n }",
"public List<ResourceRequestType.ResourceRequestCriterion> getResourceRequestCriterion()\n {\n if (resourceRequestCriterion == null)\n {\n resourceRequestCriterion = new ArrayList<ResourceRequestType.ResourceRequestCriterion>();\n }\n return this.resourceRequestCriterion;\n }"
] |
Parses a string of space delimited command line parameters and returns a
list of parameters which doesn't contain any special quoting either for
values or whole parameter.
@param param string containing a list
@return the list | [
"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 static boolean isExclusivelyKnownArchive(GraphRewrite event, String filePath)\n {\n String extension = StringUtils.substringAfterLast(filePath, \".\");\n\n if (!StringUtils.equalsIgnoreCase(extension, \"jar\"))\n return false;\n\n ZipFile archive;\n try\n {\n archive = new ZipFile(filePath);\n } catch (IOException e)\n {\n return false;\n }\n\n WindupJavaConfigurationService javaConfigurationService = new WindupJavaConfigurationService(event.getGraphContext());\n WindupJavaConfigurationModel javaConfigurationModel = WindupJavaConfigurationService.getJavaConfigurationModel(event.getGraphContext());\n\n // indicates that the user did specify some packages to scan explicitly (as opposed to scanning everything)\n boolean customerPackagesSpecified = javaConfigurationModel.getScanJavaPackages().iterator().hasNext();\n\n // this should only be true if:\n // 1) the package does not contain *any* customer packages.\n // 2) the package contains \"known\" vendor packages.\n boolean exclusivelyKnown = false;\n\n String organization = null;\n Enumeration<?> e = archive.entries();\n\n // go through all entries...\n ZipEntry entry;\n while (e.hasMoreElements())\n {\n entry = (ZipEntry) e.nextElement();\n String entryName = entry.getName();\n\n if (entry.isDirectory() || !StringUtils.endsWith(entryName, \".class\"))\n continue;\n\n String classname = PathUtil.classFilePathToClassname(entryName);\n // if the package isn't current \"known\", try to match against known packages for this entry.\n if (!exclusivelyKnown)\n {\n organization = getOrganizationForPackage(event, classname);\n if (organization != null)\n {\n exclusivelyKnown = true;\n } else\n {\n // we couldn't find a package definitively, so ignore the archive\n exclusivelyKnown = false;\n break;\n }\n }\n\n // If the user specified package names and this is in those package names, then scan it anyway\n if (customerPackagesSpecified && javaConfigurationService.shouldScanPackage(classname))\n {\n return false;\n }\n }\n\n if (exclusivelyKnown)\n LOG.info(\"Known Package: \" + archive.getName() + \"; Organization: \" + organization);\n\n // Return the evaluated exclusively known value.\n return exclusivelyKnown;\n }",
"public static Cluster swapRandomPartitionsWithinZone(final Cluster nextCandidateCluster,\n final int zoneId) {\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n Random r = new Random();\n\n List<Integer> nodeIdsInZone = new ArrayList<Integer>(nextCandidateCluster.getNodeIdsInZone(zoneId));\n\n if(nodeIdsInZone.size() == 0) {\n return returnCluster;\n }\n\n // Select random stealer node\n int stealerNodeOffset = r.nextInt(nodeIdsInZone.size());\n Integer stealerNodeId = nodeIdsInZone.get(stealerNodeOffset);\n\n // Select random stealer partition\n List<Integer> stealerPartitions = returnCluster.getNodeById(stealerNodeId)\n .getPartitionIds();\n if(stealerPartitions.size() == 0) {\n return nextCandidateCluster;\n }\n int stealerPartitionOffset = r.nextInt(stealerPartitions.size());\n int stealerPartitionId = stealerPartitions.get(stealerPartitionOffset);\n\n // Select random donor node\n List<Integer> donorNodeIds = new ArrayList<Integer>();\n donorNodeIds.addAll(nodeIdsInZone);\n donorNodeIds.remove(stealerNodeId);\n\n if(donorNodeIds.isEmpty()) { // No donor nodes!\n return returnCluster;\n }\n int donorIdOffset = r.nextInt(donorNodeIds.size());\n Integer donorNodeId = donorNodeIds.get(donorIdOffset);\n\n // Select random donor partition\n List<Integer> donorPartitions = returnCluster.getNodeById(donorNodeId).getPartitionIds();\n int donorPartitionOffset = r.nextInt(donorPartitions.size());\n int donorPartitionId = donorPartitions.get(donorPartitionOffset);\n\n return swapPartitions(returnCluster,\n stealerNodeId,\n stealerPartitionId,\n donorNodeId,\n donorPartitionId);\n }",
"public static void log(String label, String data)\n {\n if (LOG != null)\n {\n LOG.write(label);\n LOG.write(\": \");\n LOG.println(data);\n LOG.flush();\n }\n }",
"public static String getPrefixFromValue(String value) {\n if (value == null) {\n return null;\n } else if (value.contains(DELIMITER)) {\n String[] list = value.split(DELIMITER);\n if (list != null && list.length > 0) {\n return list[0].replaceAll(\"\\u0000\", \"\");\n } else {\n return null;\n }\n } else {\n return value.replaceAll(\"\\u0000\", \"\");\n }\n }",
"public static double TruncatedPower(double value, double degree) {\r\n double x = Math.pow(value, degree);\r\n return (x > 0) ? x : 0.0;\r\n }",
"private void reInitLayoutElements() {\n\n m_panel.clear();\n for (CmsCheckBox cb : m_checkBoxes) {\n m_panel.add(setStyle(m_onlyLabels ? new Label(cb.getText()) : cb));\n }\n }",
"public ItemRequest<Section> insertInProject(String project) {\n \n String path = String.format(\"/projects/%s/sections/insert\", project);\n return new ItemRequest<Section>(this, Section.class, path, \"POST\");\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<PaxDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<PaxDate>) super.zonedDateTime(temporal);\n }",
"public PathElement getElement(int index) {\n final List<PathElement> list = pathAddressList;\n return list.get(index);\n }"
] |
Adds mappings for each declared field in the mapped class. Any fields
already mapped by addColumn are skipped. | [
"public Mapping<T> addFields() {\n\n if (idColumn == null) {\n throw new RuntimeException(\"Map ID column before adding class fields\");\n }\n\n for (Field f : ReflectionUtils.getDeclaredFieldsInHierarchy(clazz)) {\n if (!Modifier.isStatic(f.getModifiers())\n && !isFieldMapped(f.getName())\n && !ignoredFields.contains(f.getName())) {\n addColumn(f.getName());\n }\n }\n\n return this;\n }"
] | [
"public static clusterinstance[] get(nitro_service service) throws Exception{\n\t\tclusterinstance obj = new clusterinstance();\n\t\tclusterinstance[] response = (clusterinstance[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void setContentType(String photoId, String contentType) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_CONTENTTYPE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"content_type\", contentType);\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"private static Map<String, ServerGroupDeploymentPlanResult> buildServerGroupResults(Map<UUID, DeploymentActionResult> deploymentActionResults) {\n Map<String, ServerGroupDeploymentPlanResult> serverGroupResults = new HashMap<String, ServerGroupDeploymentPlanResult>();\n\n for (Map.Entry<UUID, DeploymentActionResult> entry : deploymentActionResults.entrySet()) {\n\n UUID actionId = entry.getKey();\n DeploymentActionResult actionResult = entry.getValue();\n\n Map<String, ServerGroupDeploymentActionResult> actionResultsByServerGroup = actionResult.getResultsByServerGroup();\n for (ServerGroupDeploymentActionResult serverGroupActionResult : actionResultsByServerGroup.values()) {\n String serverGroupName = serverGroupActionResult.getServerGroupName();\n\n ServerGroupDeploymentPlanResultImpl sgdpr = (ServerGroupDeploymentPlanResultImpl) serverGroupResults.get(serverGroupName);\n if (sgdpr == null) {\n sgdpr = new ServerGroupDeploymentPlanResultImpl(serverGroupName);\n serverGroupResults.put(serverGroupName, sgdpr);\n }\n\n for (Map.Entry<String, ServerUpdateResult> serverEntry : serverGroupActionResult.getResultByServer().entrySet()) {\n String serverName = serverEntry.getKey();\n ServerUpdateResult sud = serverEntry.getValue();\n ServerDeploymentPlanResultImpl sdpr = (ServerDeploymentPlanResultImpl) sgdpr.getServerResult(serverName);\n if (sdpr == null) {\n sdpr = new ServerDeploymentPlanResultImpl(serverName);\n sgdpr.storeServerResult(serverName, sdpr);\n }\n sdpr.storeServerUpdateResult(actionId, sud);\n }\n }\n }\n return serverGroupResults;\n }",
"@Override\n public Map<String, Set<String>> cleanObsoleteContent() {\n if(!readWrite) {\n return Collections.emptyMap();\n }\n Map<String, Set<String>> cleanedContents = new HashMap<>(2);\n cleanedContents.put(MARKED_CONTENT, new HashSet<>());\n cleanedContents.put(DELETED_CONTENT, new HashSet<>());\n synchronized (contentHashReferences) {\n for (ContentReference fsContent : listLocalContents()) {\n if (!readWrite) {\n return Collections.emptyMap();\n }\n if (!contentHashReferences.containsKey(fsContent.getHexHash())) { //We have no reference to this content\n if (markAsObsolete(fsContent)) {\n cleanedContents.get(DELETED_CONTENT).add(fsContent.getContentIdentifier());\n } else {\n cleanedContents.get(MARKED_CONTENT).add(fsContent.getContentIdentifier());\n }\n } else {\n obsoleteContents.remove(fsContent.getHexHash()); //Remove existing references from obsoleteContents\n }\n }\n }\n return cleanedContents;\n }",
"protected Query buildPrefetchQuery(Collection ids)\r\n {\r\n CollectionDescriptor cds = getCollectionDescriptor();\r\n QueryByCriteria query = buildPrefetchQuery(ids, cds.getForeignKeyFieldDescriptors(getItemClassDescriptor()));\r\n\r\n // check if collection must be ordered\r\n if (!cds.getOrderBy().isEmpty())\r\n {\r\n Iterator iter = cds.getOrderBy().iterator();\r\n while (iter.hasNext())\r\n {\r\n query.addOrderBy((FieldHelper) iter.next());\r\n }\r\n }\r\n\r\n return query;\r\n }",
"private void addDownloadButton(final CmsLogFileView view) {\n\n Button button = CmsToolBar.createButton(\n FontOpenCms.DOWNLOAD,\n CmsVaadinUtils.getMessageText(Messages.GUI_LOGFILE_DOWNLOAD_0));\n button.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n Window window = CmsBasicDialog.prepareWindow(CmsBasicDialog.DialogWidth.wide);\n window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_LOGFILE_DOWNLOAD_0));\n window.setContent(new CmsLogDownloadDialog(window, view.getCurrentFile()));\n A_CmsUI.get().addWindow(window);\n }\n });\n m_uiContext.addToolbarButton(button);\n }",
"@Override\n public void setValue(String value, boolean fireEvents) {\n\tboolean added = setSelectedValue(this, value, addMissingValue);\n\tif (added && fireEvents) {\n\t ValueChangeEvent.fire(this, getValue());\n\t}\n }",
"private static void verifyJUnit4Present() {\n try {\n Class<?> clazz = Class.forName(\"org.junit.runner.Description\");\n if (!Serializable.class.isAssignableFrom(clazz)) {\n JvmExit.halt(SlaveMain.ERR_OLD_JUNIT);\n }\n } catch (ClassNotFoundException e) {\n JvmExit.halt(SlaveMain.ERR_NO_JUNIT);\n }\n }",
"@NonNull\n @Override\n public File getParent(@NonNull final File from) {\n if (from.getPath().equals(getRoot().getPath())) {\n // Already at root, we can't go higher\n return from;\n } else if (from.getParentFile() != null) {\n return from.getParentFile();\n } else {\n return from;\n }\n }"
] |
Sets the maximum time to wait before a call to getConnection is timed out.
Setting this to zero is similar to setting it to Long.MAX_VALUE
@param connectionTimeout
@param timeUnit the unit of the connectionTimeout argument | [
"public void setConnectionTimeout(long connectionTimeout, TimeUnit timeUnit) {\n\t\tthis.connectionTimeoutInMs = TimeUnit.MILLISECONDS.convert(connectionTimeout, timeUnit);\n\t}"
] | [
"public Optional<URL> getServiceUrl(String name) {\n Service service = client.services().inNamespace(namespace).withName(name).get();\n return service != null ? createUrlForService(service) : Optional.empty();\n }",
"public static base_response delete(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager deleteresource = new snmpmanager();\n\t\tdeleteresource.ipaddress = resource.ipaddress;\n\t\tdeleteresource.netmask = resource.netmask;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"protected BlockBox createBlock(BlockBox parent, Element n, boolean replaced)\n {\n BlockBox root;\n if (replaced)\n {\n BlockReplacedBox rbox = new BlockReplacedBox((Element) n, (Graphics2D) parent.getGraphics().create(), parent.getVisualContext().create());\n rbox.setViewport(viewport);\n rbox.setContentObj(new ReplacedImage(rbox, rbox.getVisualContext(), baseurl, n.getAttribute(\"src\")));\n root = rbox;\n }\n else\n {\n root = new BlockBox((Element) n, (Graphics2D) parent.getGraphics().create(), parent.getVisualContext().create());\n root.setViewport(viewport);\n }\n root.setBase(baseurl);\n root.setParent(parent);\n root.setContainingBlockBox(parent);\n root.setClipBlock(viewport);\n root.setOrder(next_order++);\n return root;\n }",
"public EventsRequest<Event> get(String resource, String sync) {\n return new EventsRequest<Event>(this, Event.class, \"/events\", \"GET\")\n .query(\"resource\", resource)\n .query(\"sync\", sync);\n }",
"protected String sourceLine(ASTNode node) {\r\n return sourceCode.getLines().get(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1);\r\n }",
"public static systemuser[] get(nitro_service service) throws Exception{\n\t\tsystemuser obj = new systemuser();\n\t\tsystemuser[] response = (systemuser[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public InetAddress getRemoteAddress() {\n final Channel channel;\n try {\n channel = strategy.getChannel();\n } catch (IOException e) {\n return null;\n }\n final Connection connection = channel.getConnection();\n final InetSocketAddress peerAddress = connection.getPeerAddress(InetSocketAddress.class);\n return peerAddress == null ? null : peerAddress.getAddress();\n }",
"public static int validateGeohashMaxLevels(Integer userMaxLevels, int defaultMaxLevels) {\n int maxLevels = userMaxLevels == null ? defaultMaxLevels : userMaxLevels;\n if (maxLevels < 1 || maxLevels > GeohashPrefixTree.getMaxLevelsPossible()) {\n throw new IndexException(\"max_levels must be in range [1, {}], but found {}\",\n GeohashPrefixTree.getMaxLevelsPossible(),\n maxLevels);\n }\n return maxLevels;\n }",
"public void setStartTime(final Date date) {\r\n\r\n if (!Objects.equals(m_model.getStart(), date)) {\r\n removeExceptionsOnChange(new Command() {\r\n\r\n public void execute() {\r\n\r\n m_model.setStart(date);\r\n setPatternDefaultValues(date);\r\n valueChanged();\r\n }\r\n });\r\n }\r\n\r\n }"
] |
Adds a child to this node and sets this node as its parent node.
@param node The node to add. | [
"public void addChild(final DiffNode node)\n\t{\n\t\tif (node == this)\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Detected attempt to add a node to itself. \" +\n\t\t\t\t\t\"This would cause inifite loops and must never happen.\");\n\t\t}\n\t\telse if (node.isRootNode())\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Detected attempt to add root node as child. \" +\n\t\t\t\t\t\"This is not allowed and must be a mistake.\");\n\t\t}\n\t\telse if (node.getParentNode() != null && node.getParentNode() != this)\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Detected attempt to add child node that is already the \" +\n\t\t\t\t\t\"child of another node. Adding nodes multiple times is not allowed, since it could \" +\n\t\t\t\t\t\"cause infinite loops.\");\n\t\t}\n\t\tif (node.getParentNode() == null)\n\t\t{\n\t\t\tnode.setParentNode(this);\n\t\t}\n\t\tchildren.put(node.getElementSelector(), node);\n\t\tif (state == State.UNTOUCHED && node.hasChanges())\n\t\t{\n\t\t\tstate = State.CHANGED;\n\t\t}\n\t}"
] | [
"public static base_response unset(nitro_service client, snmpoption resource, String[] args) throws Exception{\n\t\tsnmpoption unsetresource = new snmpoption();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public CompositeGeneratorNode appendTemplate(final CompositeGeneratorNode parent, final StringConcatenationClient templateString) {\n final TemplateNode proc = new TemplateNode(templateString, this);\n List<IGeneratorNode> _children = parent.getChildren();\n _children.add(proc);\n return parent;\n }",
"public String renameApp(String appName, String newName) {\n return connection.execute(new AppRename(appName, newName), apiKey).getName();\n }",
"@RequestMapping(value = \"/api/profile\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> addProfile(Model model, String name) throws Exception {\n logger.info(\"Should be adding the profile name when I hit the enter button={}\", name);\n return Utils.getJQGridJSON(profileService.add(name), \"profile\");\n }",
"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 copyTo(Gradient g) {\n\t\tg.numKnots = numKnots;\n\t\tg.map = (int[])map.clone();\n\t\tg.xKnots = (int[])xKnots.clone();\n\t\tg.yKnots = (int[])yKnots.clone();\n\t\tg.knotTypes = (byte[])knotTypes.clone();\n\t}",
"@SuppressWarnings(\"unchecked\")\n public HttpMethodInfo handle(HttpRequest request,\n HttpResponder responder, Map<String, String> groupValues) throws Exception {\n //TODO: Refactor group values.\n try {\n if (httpMethods.contains(request.method())) {\n //Setup args for reflection call\n Object [] args = new Object[paramsInfo.size()];\n\n int idx = 0;\n for (Map<Class<? extends Annotation>, ParameterInfo<?>> info : paramsInfo) {\n if (info.containsKey(PathParam.class)) {\n args[idx] = getPathParamValue(info, groupValues);\n }\n if (info.containsKey(QueryParam.class)) {\n args[idx] = getQueryParamValue(info, request.uri());\n }\n if (info.containsKey(HeaderParam.class)) {\n args[idx] = getHeaderParamValue(info, request);\n }\n idx++;\n }\n\n return new HttpMethodInfo(method, handler, responder, args, exceptionHandler);\n } else {\n //Found a matching resource but could not find the right HttpMethod so return 405\n throw new HandlerException(HttpResponseStatus.METHOD_NOT_ALLOWED, String.format\n (\"Problem accessing: %s. Reason: Method Not Allowed\", request.uri()));\n }\n } catch (Throwable e) {\n throw new HandlerException(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Error in executing request: %s %s\", request.method(),\n request.uri()), e);\n }\n }",
"public void postModule(final Module module, 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.moduleResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, module);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST module\";\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 }",
"@Deprecated\n\tpublic void setResolutions(List<Double> resolutions) {\n\t\tgetZoomLevels().clear();\n\t\tfor (Double resolution : resolutions) {\n\t\t\tgetZoomLevels().add(new ScaleInfo(1. / resolution));\n\t\t}\n\t}"
] |
Throws an exception if the request can for security reasons not be performed.
Security restrictions can be set via parameters of the index.
@param cms the current context.
@param query the query.
@param isSpell flag, indicating if the spellcheck handler is requested.
@throws CmsSearchException thrown if the query cannot be executed due to security reasons. | [
"private void throwExceptionIfSafetyRestrictionsAreViolated(CmsObject cms, CmsSolrQuery query, boolean isSpell)\r\n throws CmsSearchException {\r\n\r\n if (!isDebug(cms, query)) {\r\n if (isSpell) {\r\n if (m_handlerSpellDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n } else {\r\n if (m_handlerSelectDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n int start = null != query.getStart() ? query.getStart().intValue() : 0;\r\n int rows = null != query.getRows() ? query.getRows().intValue() : CmsSolrQuery.DEFAULT_ROWS.intValue();\r\n if ((m_handlerMaxAllowedResultsAtAll >= 0) && ((rows + start) > m_handlerMaxAllowedResultsAtAll)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_AT_ALL_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsAtAll),\r\n Integer.valueOf(rows + start)));\r\n }\r\n if ((m_handlerMaxAllowedResultsPerPage >= 0) && (rows > m_handlerMaxAllowedResultsPerPage)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_PER_PAGE_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsPerPage),\r\n Integer.valueOf(rows)));\r\n }\r\n if ((null != m_handlerAllowedFields) && (Stream.of(m_handlerAllowedFields).anyMatch(x -> true))) {\r\n if (query.getFields().equals(CmsSolrQuery.ALL_RETURN_FIELDS)) {\r\n query.setFields(m_handlerAllowedFields);\r\n } else {\r\n for (String requestedField : query.getFields().split(\",\")) {\r\n if (Stream.of(m_handlerAllowedFields).noneMatch(\r\n allowedField -> allowedField.equals(requestedField))) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_REQUESTED_FIELD_NOT_ALLOWED_2,\r\n requestedField,\r\n Stream.of(m_handlerAllowedFields).reduce(\"\", (a, b) -> a + \",\" + b)));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }"
] | [
"public static void deleteFilePath(FilePath workspace, String path) throws IOException {\n if (StringUtils.isNotBlank(path)) {\n try {\n FilePath propertiesFile = new FilePath(workspace, path);\n propertiesFile.delete();\n } catch (Exception e) {\n throw new IOException(\"Could not delete temp file: \" + path);\n }\n }\n }",
"public DbConn getConn()\n {\n Connection cnx = null;\n try\n {\n Thread.interrupted(); // this is VERY sad. Needed for Oracle driver which otherwise fails spectacularly.\n cnx = _ds.getConnection();\n if (cnx.getAutoCommit())\n {\n cnx.setAutoCommit(false);\n cnx.rollback(); // To ensure no open transaction created by the pool before changing TX mode\n }\n\n if (cnx.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED)\n {\n cnx.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);\n }\n\n return new DbConn(this, cnx);\n }\n catch (SQLException e)\n {\n DbHelper.closeQuietly(cnx); // May have been left open when the pool has given us a failed connection.\n throw new DatabaseException(e);\n }\n }",
"private ServerDetails createInitialDeployDetailsFromOldDeployDetails(ServerDetails oldDeployerDetails) {\n RepositoryConf oldDeployRepositoryConfig = oldDeployerDetails.getDeployReleaseRepository();\n RepositoryConf oldSnapshotDeployRepositoryConfig = oldDeployerDetails.getDeploySnapshotRepository();\n RepositoryConf deployReleaseRepos = oldDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldDeployRepositoryConfig;\n RepositoryConf deploySnapshotRepos = oldSnapshotDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldSnapshotDeployRepositoryConfig;\n return new ServerDetails(oldDeployerDetails.getArtifactoryName(), oldDeployerDetails.getArtifactoryUrl(),\n deployReleaseRepos, deploySnapshotRepos, null, null, null, null);\n }",
"public static Object lookup(String jndiName)\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"lookup(\"+jndiName+\") was called\");\r\n try\r\n {\r\n return getContext().lookup(jndiName);\r\n }\r\n catch (NamingException e)\r\n {\r\n throw new OJBRuntimeException(\"Lookup failed for: \" + jndiName, e);\r\n }\r\n catch(OJBRuntimeException e)\r\n {\r\n throw e;\r\n }\r\n }",
"public Schedule generateSchedule(LocalDate referenceDate, LocalDate startDate, LocalDate endDate) {\r\n\t\treturn ScheduleGenerator.createScheduleFromConventions(referenceDate, startDate, endDate, getFrequency(), getDaycountConvention(),\r\n\t\t\t\tgetShortPeriodConvention(), getDateRollConvention(), getBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), isUseEndOfMonth());\r\n\t}",
"private void deliverTempoChangedAnnouncement(final double tempo) {\n for (final MasterListener listener : getMasterListeners()) {\n try {\n listener.tempoChanged(tempo);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering tempo changed announcement to listener\", t);\n }\n }\n }",
"public static int getPercentage(String percentage) {\n if (isNotEmpty(percentage) && isNumeric(percentage)) {\n int p = Integer.parseInt(percentage);\n return p;\n } else {\n return 0;\n }\n }",
"private FieldType getActivityIDField(Map<FieldType, String> map)\n {\n FieldType result = null;\n for (Map.Entry<FieldType, String> entry : map.entrySet())\n {\n if (entry.getValue().equals(\"task_code\"))\n {\n result = entry.getKey();\n break;\n }\n }\n return result;\n }",
"public CrosstabBuilder addInvisibleMeasure(String property, String className, String title) {\r\n DJCrosstabMeasure measure = new DJCrosstabMeasure(property, className, DJCalculation.NOTHING, title);\r\n measure.setVisible(false);\r\n crosstab.getMeasures().add(measure);\r\n return this;\r\n }"
] |
Sets the replacement var map node specific.
@param replacementVarMapNodeSpecific
the replacement var map node specific
@return the parallel task builder | [
"public ParallelTaskBuilder setReplacementVarMapNodeSpecific(\n Map<String, StrStrMap> replacementVarMapNodeSpecific) {\n this.replacementVarMapNodeSpecific.clear();\n this.replacementVarMapNodeSpecific\n .putAll(replacementVarMapNodeSpecific);\n\n this.requestReplacementType = RequestReplacementType.TARGET_HOST_SPECIFIC_VAR_REPLACEMENT;\n logger.info(\"Set requestReplacementType as {}\"\n + requestReplacementType.toString());\n return this;\n }"
] | [
"private ColorItem buildColorItem(int colorId, String label) {\n Color color;\n String colorName;\n switch (colorId) {\n case 0:\n color = new Color(0, 0, 0, 0);\n colorName = \"No Color\";\n break;\n case 1:\n color = Color.PINK;\n colorName = \"Pink\";\n break;\n case 2:\n color = Color.RED;\n colorName = \"Red\";\n break;\n case 3:\n color = Color.ORANGE;\n colorName = \"Orange\";\n break;\n case 4:\n color = Color.YELLOW;\n colorName = \"Yellow\";\n break;\n case 5:\n color = Color.GREEN;\n colorName = \"Green\";\n break;\n case 6:\n color = Color.CYAN;\n colorName = \"Aqua\";\n break;\n case 7:\n color = Color.BLUE;\n colorName = \"Blue\";\n break;\n case 8:\n color = new Color(128, 0, 128);\n colorName = \"Purple\";\n break;\n default:\n color = new Color(0, 0, 0, 0);\n colorName = \"Unknown Color\";\n }\n return new ColorItem(colorId, label, color, colorName);\n }",
"public String renameApp(String appName, String newName) {\n return connection.execute(new AppRename(appName, newName), apiKey).getName();\n }",
"public int blast(InputStream input, OutputStream output) throws IOException\n {\n m_input = input;\n m_output = output;\n\n int lit; /* true if literals are coded */\n int dict; /* log2(dictionary size) - 6 */\n int symbol; /* decoded symbol, extra bits for distance */\n int len; /* length for copy */\n int dist; /* distance for copy */\n int copy; /* copy counter */\n //unsigned char *from, *to; /* copy pointers */\n\n /* read header */\n lit = bits(8);\n if (lit > 1)\n {\n return -1;\n }\n dict = bits(8);\n if (dict < 4 || dict > 6)\n {\n return -2;\n }\n\n /* decode literals and length/distance pairs */\n do\n {\n if (bits(1) != 0)\n {\n /* get length */\n symbol = decode(LENCODE);\n len = BASE[symbol] + bits(EXTRA[symbol]);\n if (len == 519)\n {\n break; /* end code */\n }\n\n /* get distance */\n symbol = len == 2 ? 2 : dict;\n dist = decode(DISTCODE) << symbol;\n dist += bits(symbol);\n dist++;\n if (m_first != 0 && dist > m_next)\n {\n return -3; /* distance too far back */\n }\n\n /* copy length bytes from distance bytes back */\n do\n {\n //to = m_out + m_next;\n int to = m_next;\n int from = to - dist;\n copy = MAXWIN;\n if (m_next < dist)\n {\n from += copy;\n copy = dist;\n }\n copy -= m_next;\n if (copy > len)\n {\n copy = len;\n }\n len -= copy;\n m_next += copy;\n do\n {\n //*to++ = *from++;\n m_out[to++] = m_out[from++];\n }\n while (--copy != 0);\n if (m_next == MAXWIN)\n {\n //if (s->outfun(s->outhow, s->out, s->next)) return 1;\n m_output.write(m_out, 0, m_next);\n m_next = 0;\n m_first = 0;\n }\n }\n while (len != 0);\n }\n else\n {\n /* get literal and write it */\n symbol = lit != 0 ? decode(LITCODE) : bits(8);\n m_out[m_next++] = (byte) symbol;\n if (m_next == MAXWIN)\n {\n //if (s->outfun(s->outhow, s->out, s->next)) return 1;\n m_output.write(m_out, 0, m_next);\n m_next = 0;\n m_first = 0;\n }\n }\n }\n while (true);\n\n if (m_next != 0)\n {\n m_output.write(m_out, 0, m_next);\n }\n\n return 0;\n }",
"public static final Date parseDateTime(String value)\n {\n Date result = null;\n\n try\n {\n if (value != null && !value.isEmpty())\n {\n result = DATE_TIME_FORMAT.get().parse(value);\n }\n }\n catch (ParseException ex)\n {\n // Ignore\n }\n\n return result;\n }",
"public Rectangle toRelative(Rectangle rect) {\n\t\treturn new Rectangle(rect.getLeft() - origX, rect.getBottom() - origY, rect.getRight() - origX, rect.getTop()\n\t\t\t\t- origY);\n\t}",
"synchronized boolean markReadMessageForId(String messageId, String userId){\n if(messageId == null || userId == null) return false;\n\n final String tName = Table.INBOX_MESSAGES.getName();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n ContentValues cv = new ContentValues();\n cv.put(IS_READ,1);\n db.update(Table.INBOX_MESSAGES.getName(), cv,_ID + \" = ? AND \" + USER_ID + \" = ?\",new String[]{messageId,userId});\n return true;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error removing stale records from \" + tName, e);\n return false;\n } finally {\n dbHelper.close();\n }\n }",
"public void removeWorstFit() {\n // find the observation with the most error\n int worstIndex=-1;\n double worstError = -1;\n\n for( int i = 0; i < y.numRows; i++ ) {\n double predictedObs = 0;\n\n for( int j = 0; j < coef.numRows; j++ ) {\n predictedObs += A.get(i,j)*coef.get(j,0);\n }\n\n double error = Math.abs(predictedObs- y.get(i,0));\n\n if( error > worstError ) {\n worstError = error;\n worstIndex = i;\n }\n }\n\n // nothing left to remove, so just return\n if( worstIndex == -1 )\n return;\n\n // remove that observation\n removeObservation(worstIndex);\n\n // update A\n solver.removeRowFromA(worstIndex);\n\n // solve for the parameters again\n solver.solve(y,coef);\n }",
"private List<Pair<Integer, Double>> integerPixelCoordinatesAndWeights(double d, int numPixels) {\n if (d <= 0.5) return Collections.singletonList(new Pair<>(0, 1.0));\n else if (d >= numPixels - 0.5) return Collections.singletonList(new Pair<>(numPixels - 1, 1.0));\n else {\n double shifted = d - 0.5;\n double floor = Math.floor(shifted);\n double floorWeight = 1 - (shifted - floor);\n double ceil = Math.ceil(shifted);\n double ceilWeight = 1 - floorWeight;\n assert (floorWeight + ceilWeight == 1);\n return Arrays.asList(new Pair<>((int) floor, floorWeight), new Pair<>((int) ceil, ceilWeight));\n }\n }",
"private int findIndexForName(String[] fieldNames, String searchName)\r\n {\r\n for(int i = 0; i < fieldNames.length; i++)\r\n {\r\n if(searchName.equals(fieldNames[i]))\r\n {\r\n return i;\r\n }\r\n }\r\n throw new PersistenceBrokerException(\"Can't find field name '\" + searchName +\r\n \"' in given array of field names\");\r\n }"
] |
Add join info to the query. This can be called multiple times to join with more than one table. | [
"private void addJoinInfo(JoinType type, String localColumnName, String joinedColumnName,\n\t\t\tQueryBuilder<?, ?> joinedQueryBuilder, JoinWhereOperation operation) throws SQLException {\n\t\tJoinInfo joinInfo = new JoinInfo(type, joinedQueryBuilder, operation);\n\t\tif (localColumnName == null) {\n\t\t\tmatchJoinedFields(joinInfo, joinedQueryBuilder);\n\t\t} else {\n\t\t\tmatchJoinedFieldsByName(joinInfo, localColumnName, joinedColumnName, joinedQueryBuilder);\n\t\t}\n\t\tif (joinList == null) {\n\t\t\tjoinList = new ArrayList<JoinInfo>();\n\t\t}\n\t\tjoinList.add(joinInfo);\n\t}"
] | [
"public static base_response delete(nitro_service client, String jsoncontenttypevalue) throws Exception {\n\t\tappfwjsoncontenttype deleteresource = new appfwjsoncontenttype();\n\t\tdeleteresource.jsoncontenttypevalue = jsoncontenttypevalue;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public static lbmonitor_binding get(nitro_service service, String monitorname) throws Exception{\n\t\tlbmonitor_binding obj = new lbmonitor_binding();\n\t\tobj.set_monitorname(monitorname);\n\t\tlbmonitor_binding response = (lbmonitor_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void tryToSetParsedValue(String value) throws Exception {\n\n JSONObject json = JSONParser.parseStrict(value).isObject();\n JSONValue val = json.get(JsonKey.START);\n setStart(readOptionalDate(val));\n val = json.get(JsonKey.END);\n setEnd(readOptionalDate(val));\n setWholeDay(readOptionalBoolean(json.get(JsonKey.WHOLE_DAY)));\n JSONObject patternJson = json.get(JsonKey.PATTERN).isObject();\n readPattern(patternJson);\n setExceptions(readDates(json.get(JsonKey.EXCEPTIONS)));\n setSeriesEndDate(readOptionalDate(json.get(JsonKey.SERIES_ENDDATE)));\n setOccurrences(readOptionalInt(json.get(JsonKey.SERIES_OCCURRENCES)));\n setDerivedEndType();\n setCurrentTillEnd(readOptionalBoolean(json.get(JsonKey.CURRENT_TILL_END)));\n setParentSeriesId(readOptionalUUID(json.get(JsonKey.PARENT_SERIES)));\n\n }",
"private boolean removeRelation(List<Relation> relationList, Task targetTask, RelationType type, Duration lag)\n {\n boolean matchFound = false;\n for (Relation relation : relationList)\n {\n if (relation.getTargetTask() == targetTask)\n {\n if (relation.getType() == type && relation.getLag().compareTo(lag) == 0)\n {\n matchFound = relationList.remove(relation);\n break;\n }\n }\n }\n return matchFound;\n }",
"public static vpnvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_cachepolicy_binding obj = new vpnvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_cachepolicy_binding response[] = (vpnvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private static String guessPackaging(ProjectModel projectModel)\n {\n String projectType = projectModel.getProjectType();\n if (projectType != null)\n return projectType;\n\n LOG.warning(\"WINDUP-983 getProjectType() returned null for: \" + projectModel.getRootFileModel().getPrettyPath());\n\n String suffix = StringUtils.substringAfterLast(projectModel.getRootFileModel().getFileName(), \".\");\n if (\"jar war ear sar har \".contains(suffix+\" \")){\n projectModel.setProjectType(suffix); // FIXME: Remove when WINDUP-983 is fixed.\n return suffix;\n }\n\n // Should we try something more? Used APIs? What if it's a source?\n\n return \"unknown\";\n }",
"@SafeVarargs\n public static <K> Set<K> set(final K... keys) {\n return new LinkedHashSet<K>(Arrays.asList(keys));\n }",
"public static <T> String listToString(List<T> list, final boolean justValue,\r\n final String separator) {\r\n StringBuilder s = new StringBuilder();\r\n for (Iterator<T> wordIterator = list.iterator(); wordIterator.hasNext();) {\r\n T o = wordIterator.next();\r\n s.append(wordToString(o, justValue, separator));\r\n if (wordIterator.hasNext()) {\r\n s.append(' ');\r\n }\r\n }\r\n return s.toString();\r\n }",
"public static String createUnquotedConstant(String str) {\n if (str == null || str.isEmpty()) {\n return str;\n }\n if (str.startsWith(\"\\\"\")) {\n str = str.substring(1);\n }\n if (str.endsWith(\"\\\"\")) {\n str = str.substring(0,\n str.length() - 1);\n }\n return str;\n }"
] |
Return a new instance of the BufferedImage
@return BufferedImage | [
"public BufferedImage getNewImageInstance() {\n BufferedImage buf = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());\n buf.setData(image.getData());\n return buf;\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 double ratioSmallestOverLargest( double []sv ) {\n if( sv.length == 0 )\n return Double.NaN;\n\n double min = sv[0];\n double max = min;\n\n for (int i = 1; i < sv.length; i++) {\n double v = sv[i];\n if( v > max )\n max = v;\n else if( v < min )\n min = v;\n }\n\n return min/max;\n }",
"public Jar setMapAttribute(String name, Map<String, ?> values) {\n return setAttribute(name, join(values));\n }",
"public static tmsessionparameter get(nitro_service service) throws Exception{\n\t\ttmsessionparameter obj = new tmsessionparameter();\n\t\ttmsessionparameter[] response = (tmsessionparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static ComplexNumber Subtract(ComplexNumber z1, double scalar) {\r\n return new ComplexNumber(z1.real - scalar, z1.imaginary);\r\n }",
"public static ModelNode createRemoveOperation(final ModelNode address, final boolean recursive) {\n final ModelNode op = createRemoveOperation(address);\n op.get(RECURSIVE).set(recursive);\n return op;\n }",
"protected TransformationDescription buildDefault(final DiscardPolicy discardPolicy, boolean inherited, final AttributeTransformationDescriptionBuilderImpl.AttributeTransformationDescriptionBuilderRegistry registry, List<String> discardedOperations) {\n // Build attribute rules\n final Map<String, AttributeTransformationDescription> attributes = registry.buildAttributes();\n // Create operation transformers\n final Map<String, OperationTransformer> operations = buildOperationTransformers(registry);\n // Process children\n final List<TransformationDescription> children = buildChildren();\n\n if (discardPolicy == DiscardPolicy.NEVER) {\n // TODO override more global operations?\n if(! operations.containsKey(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION)) {\n operations.put(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION, OperationTransformationRules.createWriteOperation(attributes));\n }\n if(! operations.containsKey(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION)) {\n operations.put(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION, OperationTransformationRules.createUndefinedOperation(attributes));\n }\n }\n // Create the description\n Set<String> discarded = new HashSet<>();\n discarded.addAll(discardedOperations);\n return new TransformingDescription(pathElement, pathAddressTransformer, discardPolicy, inherited,\n resourceTransformer, attributes, operations, children, discarded, dynamicDiscardPolicy);\n }",
"public static Cluster randomShufflePartitions(final Cluster nextCandidateCluster,\n final int randomSwapAttempts,\n final int randomSwapSuccesses,\n final List<Integer> randomSwapZoneIds,\n List<StoreDefinition> storeDefs) {\n List<Integer> zoneIds = null;\n if(randomSwapZoneIds.isEmpty()) {\n zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds());\n } else {\n zoneIds = new ArrayList<Integer>(randomSwapZoneIds);\n }\n\n List<Integer> nodeIds = new ArrayList<Integer>();\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n\n int successes = 0;\n for(int i = 0; i < randomSwapAttempts; i++) {\n\n // Iterate over zone ids to decide which node ids to include for\n // intra-zone swapping.\n // In future, if there is a need to support inter-zone swapping,\n // then just remove the\n // zone specific logic that populates nodeIdSet and add all nodes\n // from across all zones.\n\n int zoneIdOffset = i % zoneIds.size();\n\n Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset));\n nodeIds = new ArrayList<Integer>(nodeIdSet);\n\n Collections.shuffle(zoneIds, new Random(System.currentTimeMillis()));\n Cluster shuffleResults = swapRandomPartitionsAmongNodes(returnCluster, nodeIds);\n\n double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility();\n if(nextUtility < currentUtility) {\n System.out.println(\"Swap improved max-min ratio: \" + currentUtility + \" -> \"\n + nextUtility + \" (improvement \" + successes\n + \" on swap attempt \" + i + \")\");\n successes++;\n returnCluster = shuffleResults;\n currentUtility = nextUtility;\n }\n if(successes >= randomSwapSuccesses) {\n // Enough successes, move on.\n break;\n }\n }\n return returnCluster;\n }",
"public void afterDeploymentValidation(@Observes @Priority(1) AfterDeploymentValidation event, BeanManager beanManager) {\n BeanManagerImpl manager = BeanManagerProxy.unwrap(beanManager);\n probe.init(manager);\n if (isJMXSupportEnabled(manager)) {\n try {\n MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();\n mbs.registerMBean(new ProbeDynamicMBean(jsonDataProvider, JsonDataProvider.class), constructProbeJsonDataMBeanName(manager, probe));\n } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {\n event.addDeploymentProblem(ProbeLogger.LOG.unableToRegisterMBean(JsonDataProvider.class, manager.getContextId(), e));\n }\n }\n addContainerLifecycleEvent(event, null, beanManager);\n exportDataIfNeeded(manager);\n }"
] |
Sets the bytecode compatibility mode
@param version the bytecode compatibility mode | [
"public void setTargetBytecode(String version) {\n if (CompilerConfiguration.PRE_JDK5.equals(version) || CompilerConfiguration.POST_JDK5.equals(version)) {\n this.targetBytecode = version;\n }\n }"
] | [
"public static base_response delete(nitro_service client, appfwlearningdata resource) throws Exception {\n\t\tappfwlearningdata deleteresource = new appfwlearningdata();\n\t\tdeleteresource.profilename = resource.profilename;\n\t\tdeleteresource.starturl = resource.starturl;\n\t\tdeleteresource.cookieconsistency = resource.cookieconsistency;\n\t\tdeleteresource.fieldconsistency = resource.fieldconsistency;\n\t\tdeleteresource.formactionurl_ffc = resource.formactionurl_ffc;\n\t\tdeleteresource.crosssitescripting = resource.crosssitescripting;\n\t\tdeleteresource.formactionurl_xss = resource.formactionurl_xss;\n\t\tdeleteresource.sqlinjection = resource.sqlinjection;\n\t\tdeleteresource.formactionurl_sql = resource.formactionurl_sql;\n\t\tdeleteresource.fieldformat = resource.fieldformat;\n\t\tdeleteresource.formactionurl_ff = resource.formactionurl_ff;\n\t\tdeleteresource.csrftag = resource.csrftag;\n\t\tdeleteresource.csrfformoriginurl = resource.csrfformoriginurl;\n\t\tdeleteresource.xmldoscheck = resource.xmldoscheck;\n\t\tdeleteresource.xmlwsicheck = resource.xmlwsicheck;\n\t\tdeleteresource.xmlattachmentcheck = resource.xmlattachmentcheck;\n\t\tdeleteresource.totalxmlrequests = resource.totalxmlrequests;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public static cmppolicylabel[] get(nitro_service service) throws Exception{\n\t\tcmppolicylabel obj = new cmppolicylabel();\n\t\tcmppolicylabel[] response = (cmppolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void setActiveView(View v, int position) {\n final View oldView = mActiveView;\n mActiveView = v;\n mActivePosition = position;\n\n if (mAllowIndicatorAnimation && oldView != null) {\n startAnimatingIndicator();\n }\n\n invalidate();\n }",
"public static double normP(DMatrixRMaj A , double p ) {\n if( p == 1 ) {\n return normP1(A);\n } else if( p == 2 ) {\n return normP2(A);\n } else if( Double.isInfinite(p)) {\n return normPInf(A);\n }\n if( MatrixFeatures_DDRM.isVector(A) ) {\n return elementP(A,p);\n } else {\n throw new IllegalArgumentException(\"Doesn't support induced norms yet.\");\n }\n }",
"protected void _format(EObject obj, IFormattableDocument document) {\n\t\tfor (EObject child : obj.eContents())\n\t\t\tdocument.format(child);\n\t}",
"public static double huntKennedyCMSFloorValue(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble swapAnnuity,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble swapMaturity,\n\t\t\tdouble payoffUnit,\n\t\t\tdouble optionStrike)\n\t{\n\t\tdouble huntKennedyCMSOptionValue = huntKennedyCMSOptionValue(forwardSwaprate, volatility, swapAnnuity, optionMaturity, swapMaturity, payoffUnit, optionStrike);\n\n\t\t// A floor is an option plus the strike (max(X,K) = max(X-K,0) + K)\n\t\treturn huntKennedyCMSOptionValue + optionStrike * payoffUnit;\n\t}",
"@Override\n protected Deque<Step> childValue(Deque<Step> parentValue) {\n Deque<Step> queue = new LinkedList<>();\n queue.add(parentValue.getFirst());\n return queue;\n }",
"private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList, Map<P, Boolean> savedLastExpansionState) {\n List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>();\n\n int parentCount = parentList.size();\n for (int i = 0; i < parentCount; i++) {\n P parent = parentList.get(i);\n Boolean lastExpandedState = savedLastExpansionState.get(parent);\n boolean shouldExpand = lastExpandedState == null ? parent.isInitiallyExpanded() : lastExpandedState;\n\n generateParentWrapper(flatItemList, parent, shouldExpand);\n }\n\n return flatItemList;\n }",
"public void 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 }"
] |
Generates the Base64 encoded SHA-1 hash for content available in the stream.
It can be used to calculate the hash of a file.
@param stream the input stream of the file or data.
@return the Base64 encoded hash string. | [
"public String generateDigest(InputStream stream) {\n MessageDigest digest = null;\n try {\n digest = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1);\n } catch (NoSuchAlgorithmException ae) {\n throw new BoxAPIException(\"Digest algorithm not found\", ae);\n }\n\n //Calcuate the digest using the stream.\n DigestInputStream dis = new DigestInputStream(stream, digest);\n try {\n int value = dis.read();\n while (value != -1) {\n value = dis.read();\n }\n } catch (IOException ioe) {\n throw new BoxAPIException(\"Reading the stream failed.\", ioe);\n }\n\n //Get the calculated digest for the stream\n byte[] digestBytes = digest.digest();\n return Base64.encode(digestBytes);\n }"
] | [
"public static int longestCommonContiguousSubstring(String s, String t) {\r\n if (s.length() == 0 || t.length() == 0) {\r\n return 0;\r\n }\r\n int M = s.length();\r\n int N = t.length();\r\n int[][] d = new int[M + 1][N + 1];\r\n for (int j = 0; j <= N; j++) {\r\n d[0][j] = 0;\r\n }\r\n for (int i = 0; i <= M; i++) {\r\n d[i][0] = 0;\r\n }\r\n\r\n int max = 0;\r\n for (int i = 1; i <= M; i++) {\r\n for (int j = 1; j <= N; j++) {\r\n if (s.charAt(i - 1) == t.charAt(j - 1)) {\r\n d[i][j] = d[i - 1][j - 1] + 1;\r\n } else {\r\n d[i][j] = 0;\r\n }\r\n\r\n if (d[i][j] > max) {\r\n max = d[i][j];\r\n }\r\n }\r\n }\r\n // System.err.println(\"LCCS(\" + s + \",\" + t + \") = \" + max);\r\n return max;\r\n }",
"public String computeTrackSignature(final String title, final SearchableItem artist, final int duration,\n final WaveformDetail waveformDetail, final BeatGrid beatGrid) {\n final String safeTitle = (title == null)? \"\" : title;\n final String artistName = (artist == null)? \"[no artist]\" : artist.label;\n try {\n // Compute the SHA-1 hash of our fields\n MessageDigest digest = MessageDigest.getInstance(\"SHA1\");\n digest.update(safeTitle.getBytes(\"UTF-8\"));\n digest.update((byte) 0);\n digest.update(artistName.getBytes(\"UTF-8\"));\n digest.update((byte) 0);\n digestInteger(digest, duration);\n digest.update(waveformDetail.getData());\n for (int i = 1; i <= beatGrid.beatCount; i++) {\n digestInteger(digest, beatGrid.getBeatWithinBar(i));\n digestInteger(digest, (int)beatGrid.getTimeWithinTrack(i));\n }\n byte[] result = digest.digest();\n\n // Create a hex string representation of the hash\n StringBuilder hex = new StringBuilder(result.length * 2);\n for (byte aResult : result) {\n hex.append(Integer.toString((aResult & 0xff) + 0x100, 16).substring(1));\n }\n\n return hex.toString();\n\n } catch (NullPointerException e) {\n logger.info(\"Returning null track signature because an input element was null.\", e);\n } catch (NoSuchAlgorithmException e) {\n logger.error(\"Unable to obtain SHA-1 MessageDigest instance for computing track signatures.\", e);\n } catch (UnsupportedEncodingException e) {\n logger.error(\"Unable to work with UTF-8 string encoding for computing track signatures.\", e);\n }\n return null; // We were unable to compute a signature\n }",
"private void initDefaultScopeType(EnhancedAnnotation<T> annotatedAnnotation) {\n Set<Annotation> scopeTypes = new HashSet<Annotation>();\n scopeTypes.addAll(annotatedAnnotation.getMetaAnnotations(Scope.class));\n scopeTypes.addAll(annotatedAnnotation.getMetaAnnotations(NormalScope.class));\n if (scopeTypes.size() > 1) {\n throw MetadataLogger.LOG.multipleScopes(annotatedAnnotation);\n } else if (scopeTypes.size() == 1) {\n this.defaultScopeType = scopeTypes.iterator().next();\n }\n }",
"protected void refresh()\r\n {\r\n if (log.isDebugEnabled())\r\n log.debug(\"Refresh this transaction for reuse: \" + this);\r\n try\r\n {\r\n // we reuse ObjectEnvelopeTable instance\r\n objectEnvelopeTable.refresh();\r\n }\r\n catch (Exception e)\r\n {\r\n if (log.isDebugEnabled())\r\n {\r\n log.debug(\"error closing object envelope table : \" + e.getMessage());\r\n e.printStackTrace();\r\n }\r\n }\r\n cleanupBroker();\r\n // clear the temporary used named roots map\r\n // we should do that, because same tx instance\r\n // could be used several times\r\n broker = null;\r\n clearRegistrationList();\r\n unmaterializedLocks.clear();\r\n txStatus = Status.STATUS_NO_TRANSACTION;\r\n }",
"private IndexedContainer createContainerForDescriptorEditing() {\n\n IndexedContainer container = new IndexedContainer();\n\n // create properties\n container.addContainerProperty(TableProperty.KEY, String.class, \"\");\n container.addContainerProperty(TableProperty.DESCRIPTION, String.class, \"\");\n container.addContainerProperty(TableProperty.DEFAULT, String.class, \"\");\n\n // add entries\n CmsXmlContentValueSequence messages = m_descContent.getValueSequence(\n \"/\" + Descriptor.N_MESSAGE,\n Descriptor.LOCALE);\n for (int i = 0; i < messages.getElementCount(); i++) {\n\n String prefix = messages.getValue(i).getPath() + \"/\";\n Object itemId = container.addItem();\n Item item = container.getItem(itemId);\n String key = m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).getStringValue(m_cms);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n item.getItemProperty(TableProperty.DESCRIPTION).setValue(\n m_descContent.getValue(prefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).getStringValue(m_cms));\n item.getItemProperty(TableProperty.DEFAULT).setValue(\n m_descContent.getValue(prefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).getStringValue(m_cms));\n }\n\n return container;\n\n }",
"private void addAssignments(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (ResourceAssignment assignment : file.getResourceAssignments())\n {\n final ResourceAssignment a = assignment;\n MpxjTreeNode childNode = new MpxjTreeNode(a)\n {\n @Override public String toString()\n {\n Resource resource = a.getResource();\n String resourceName = resource == null ? \"(unknown resource)\" : resource.getName();\n Task task = a.getTask();\n String taskName = task == null ? \"(unknown task)\" : task.getName();\n return resourceName + \"->\" + taskName;\n }\n };\n parentNode.add(childNode);\n }\n }",
"@Override\n public Scenario<GIVEN, WHEN, THEN> startScenario( String description ) {\n super.startScenario( description );\n return this;\n\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}",
"public final File getBuildFileFor(\n final Configuration configuration, final File jasperFileXml,\n final String extension, final Logger logger) {\n final String configurationAbsolutePath = configuration.getDirectory().getPath();\n final int prefixToConfiguration = configurationAbsolutePath.length() + 1;\n final String parentDir = jasperFileXml.getAbsoluteFile().getParent();\n final String relativePathToFile;\n if (configurationAbsolutePath.equals(parentDir)) {\n relativePathToFile = FilenameUtils.getBaseName(jasperFileXml.getName());\n } else {\n final String relativePathToContainingDirectory = parentDir.substring(prefixToConfiguration);\n relativePathToFile = relativePathToContainingDirectory + File.separator +\n FilenameUtils.getBaseName(jasperFileXml.getName());\n }\n\n final File buildFile = new File(getJasperCompilation(configuration), relativePathToFile + extension);\n\n if (!buildFile.getParentFile().exists() && !buildFile.getParentFile().mkdirs()) {\n logger.error(\"Unable to create directory for containing compiled jasper report templates: {}\",\n buildFile.getParentFile());\n }\n return buildFile;\n }"
] |
Interim and final clusters ought to have same partition counts, same
zones, and same node state. Partitions per node may of course differ.
@param interimCluster
@param finalCluster | [
"public static void validateInterimFinalCluster(final Cluster interimCluster,\n final Cluster finalCluster) {\n validateClusterPartitionCounts(interimCluster, finalCluster);\n validateClusterZonesSame(interimCluster, finalCluster);\n validateClusterNodeCounts(interimCluster, finalCluster);\n validateClusterNodeState(interimCluster, finalCluster);\n return;\n }"
] | [
"public InputStream getAvatar() {\n URL url = USER_AVATAR_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxAPIResponse response = request.send();\n\n return response.getBody();\n }",
"public static <T> T createObject(final Class<T> clazz, final Object... args) throws NoSuchConstructorException,\n AmbiguousConstructorException, ReflectiveOperationException {\n return findConstructor(clazz, args).newInstance(args);\n }",
"private void updateMaxMin(IntervalRBTreeNode<T> n, IntervalRBTreeNode<T> c) {\n if (c != null) {\n if (n.max < c.max) {\n n.max = c.max;\n }\n if (n.min > c.min) {\n n.min = c.min;\n }\n }\n }",
"public void stop()\n {\n synchronized (mAnimQueue)\n {\n if (mIsRunning && (mAnimQueue.size() > 0))\n {\n mIsRunning = false;\n GVRAnimator animator = mAnimQueue.get(0);\n mAnimQueue.clear();\n animator.stop();\n }\n }\n }",
"public static systemuser[] get(nitro_service service) throws Exception{\n\t\tsystemuser obj = new systemuser();\n\t\tsystemuser[] response = (systemuser[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void resizeKeys(int numKeys)\n {\n int n = numKeys * mFloatsPerKey;\n if (mKeys.length == n)\n {\n return;\n }\n float[] newKeys = new float[n];\n n = Math.min(n, mKeys.length);\n\n System.arraycopy(mKeys, 0, newKeys, 0, n);\n mKeys = newKeys;\n mFloatInterpolator.setKeyData(mKeys);\n }",
"@JmxGetter(name = \"getChunkIdToNumChunks\", description = \"Returns a string representation of the map of chunk id to number of chunks\")\n public String getChunkIdToNumChunks() {\n StringBuilder builder = new StringBuilder();\n for(Entry<Object, Integer> entry: fileSet.getChunkIdToNumChunks().entrySet()) {\n builder.append(entry.getKey().toString() + \" - \" + entry.getValue().toString() + \", \");\n }\n return builder.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 String formatTime(Date value)\n {\n return (value == null ? null : m_formats.getTimeFormat().format(value));\n }"
] |
Create the work pattern assignment map.
@param rows calendar rows
@return work pattern assignment map | [
"private Map<Integer, List<Row>> createWorkPatternAssignmentMap(List<Row> rows) throws ParseException\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer calendarID = row.getInteger(\"ID\");\n String workPatterns = row.getString(\"WORK_PATTERNS\");\n map.put(calendarID, createWorkPatternAssignmentRowList(workPatterns));\n }\n return map;\n }"
] | [
"private void writeCustomInfo(Event event) {\n // insert customInfo (key/value) into DB\n for (Map.Entry<String, String> customInfo : event.getCustomInfo().entrySet()) {\n long cust_id = dbDialect.getIncrementer().nextLongValue();\n getJdbcTemplate()\n .update(\"insert into EVENTS_CUSTOMINFO (ID, EVENT_ID, CUST_KEY, CUST_VALUE)\"\n + \" values (?,?,?,?)\",\n cust_id, event.getPersistedId(), customInfo.getKey(), customInfo.getValue());\n }\n }",
"public 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 static MethodNode findSAM(ClassNode type) {\n if (!Modifier.isAbstract(type.getModifiers())) return null;\n if (type.isInterface()) {\n List<MethodNode> methods = type.getMethods();\n MethodNode found=null;\n for (MethodNode mi : methods) {\n // ignore methods, that are not abstract and from Object\n if (!Modifier.isAbstract(mi.getModifiers())) continue;\n // ignore trait methods which have a default implementation\n if (Traits.hasDefaultImplementation(mi)) continue;\n if (mi.getDeclaringClass().equals(OBJECT_TYPE)) continue;\n if (OBJECT_TYPE.getDeclaredMethod(mi.getName(), mi.getParameters())!=null) continue;\n\n // we have two methods, so no SAM\n if (found!=null) return null;\n found = mi;\n }\n return found;\n\n } else {\n\n List<MethodNode> methods = type.getAbstractMethods();\n MethodNode found = null;\n if (methods!=null) {\n for (MethodNode mi : methods) {\n if (!hasUsableImplementation(type, mi)) {\n if (found!=null) return null;\n found = mi;\n }\n }\n }\n return found;\n }\n }",
"private void deliverMasterYieldCommand(int toPlayer) {\n for (final MasterHandoffListener listener : getMasterHandoffListeners()) {\n try {\n listener.yieldMasterTo(toPlayer);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master yield command to listener\", t);\n }\n }\n }",
"public static callhome get(nitro_service service) throws Exception{\n\t\tcallhome obj = new callhome();\n\t\tcallhome[] response = (callhome[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static cachepolicylabel[] get(nitro_service service) throws Exception{\n\t\tcachepolicylabel obj = new cachepolicylabel();\n\t\tcachepolicylabel[] response = (cachepolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"@Override\n public ConfigurableRequest createRequest(\n @Nonnull final URI uri,\n @Nonnull final HttpMethod httpMethod) throws IOException {\n HttpRequestBase httpRequest = (HttpRequestBase) createHttpUriRequest(httpMethod, uri);\n return new Request(getHttpClient(), httpRequest, createHttpContext(httpMethod, uri));\n }",
"I_CmsSerialDateServiceAsync getService() {\r\n\r\n if (SERVICE == null) {\r\n SERVICE = GWT.create(I_CmsSerialDateService.class);\r\n String serviceUrl = CmsCoreProvider.get().link(\"org.opencms.ade.contenteditor.CmsSerialDateService.gwt\");\r\n ((ServiceDefTarget)SERVICE).setServiceEntryPoint(serviceUrl);\r\n }\r\n return SERVICE;\r\n }",
"private void merge(Map<String, NodeT> source, Map<String, NodeT> target) {\n for (Map.Entry<String, NodeT> entry : source.entrySet()) {\n String key = entry.getKey();\n if (!target.containsKey(key)) {\n target.put(key, entry.getValue());\n }\n }\n }"
] |
Stops the HTTP service gracefully and release all resources.
@param quietPeriod the quiet period as described in the documentation of {@link EventExecutorGroup}
@param timeout the maximum amount of time to wait until the executor is
{@linkplain EventExecutorGroup#shutdown()}
regardless if a task was submitted during the quiet period
@param unit the unit of {@code quietPeriod} and {@code timeout}
@throws Exception if there is exception raised during shutdown. | [
"public synchronized void stop(long quietPeriod, long timeout, TimeUnit unit) throws Exception {\n if (state == State.STOPPED) {\n LOG.debug(\"Ignore stop() call on HTTP service {} since it has already been stopped.\", serviceName);\n return;\n }\n\n LOG.info(\"Stopping HTTP Service {}\", serviceName);\n\n try {\n try {\n channelGroup.close().awaitUninterruptibly();\n } finally {\n try {\n shutdownExecutorGroups(quietPeriod, timeout, unit,\n bootstrap.config().group(), bootstrap.config().childGroup(), eventExecutorGroup);\n } finally {\n resourceHandler.destroy(handlerContext);\n }\n }\n } catch (Throwable t) {\n state = State.FAILED;\n throw t;\n }\n state = State.STOPPED;\n LOG.debug(\"Stopped HTTP Service {} on address {}\", serviceName, bindAddress);\n }"
] | [
"public void createAgent(String agent_name, String path) {\n IComponentIdentifier agent = cmsService.createComponent(agent_name,\n path, null, null).get(new ThreadSuspendable());\n createdAgents.put(agent_name, agent);\n }",
"public ItemRequest<ProjectMembership> findById(String projectMembership) {\n \n String path = String.format(\"/project_memberships/%s\", projectMembership);\n return new ItemRequest<ProjectMembership>(this, ProjectMembership.class, path, \"GET\");\n }",
"public void setInRGB(IntRange inRGB) {\r\n this.inRed = inRGB;\r\n this.inGreen = inRGB;\r\n this.inBlue = inRGB;\r\n\r\n CalculateMap(inRGB, outRed, mapRed);\r\n CalculateMap(inRGB, outGreen, mapGreen);\r\n CalculateMap(inRGB, outBlue, mapBlue);\r\n }",
"public static CmsShell getTopShell() {\n\n ArrayList<CmsShell> shells = SHELL_STACK.get();\n if (shells.isEmpty()) {\n return null;\n }\n return shells.get(shells.size() - 1);\n\n }",
"private void validateSameDay(ProjectCalendar calendar, LinkedList<TimephasedWork> list)\n {\n for (TimephasedWork assignment : list)\n {\n Date assignmentStart = assignment.getStart();\n Date calendarStartTime = calendar.getStartTime(assignmentStart);\n Date assignmentStartTime = DateHelper.getCanonicalTime(assignmentStart);\n Date assignmentFinish = assignment.getFinish();\n Date calendarFinishTime = calendar.getFinishTime(assignmentFinish);\n Date assignmentFinishTime = DateHelper.getCanonicalTime(assignmentFinish);\n double totalWork = assignment.getTotalAmount().getDuration();\n\n if (assignmentStartTime != null && calendarStartTime != null)\n {\n if ((totalWork == 0 && assignmentStartTime.getTime() != calendarStartTime.getTime()) || (assignmentStartTime.getTime() < calendarStartTime.getTime()))\n {\n assignmentStart = DateHelper.setTime(assignmentStart, calendarStartTime);\n assignment.setStart(assignmentStart);\n }\n }\n\n if (assignmentFinishTime != null && calendarFinishTime != null)\n {\n if ((totalWork == 0 && assignmentFinishTime.getTime() != calendarFinishTime.getTime()) || (assignmentFinishTime.getTime() > calendarFinishTime.getTime()))\n {\n assignmentFinish = DateHelper.setTime(assignmentFinish, calendarFinishTime);\n assignment.setFinish(assignmentFinish);\n }\n }\n }\n }",
"public Curve getRegressionCurve(){\n\t\t// @TODO Add threadsafe lazy init.\n\t\tif(regressionCurve !=null) {\n\t\t\treturn regressionCurve;\n\t\t}\n\t\tDoubleMatrix a = solveEquationSystem();\n\t\tdouble[] curvePoints=new double[partition.getLength()];\n\t\tcurvePoints[0]=a.get(0);\n\t\tfor(int i=1;i<curvePoints.length;i++) {\n\t\t\tcurvePoints[i]=curvePoints[i-1]+a.get(i)*(partition.getIntervalLength(i-1));\n\t\t}\n\t\treturn new CurveInterpolation(\n\t\t\t\t\"RegressionCurve\",\n\t\t\t\treferenceDate,\n\t\t\t\tCurveInterpolation.InterpolationMethod.LINEAR,\n\t\t\t\tCurveInterpolation.ExtrapolationMethod.CONSTANT,\n\t\t\t\tCurveInterpolation.InterpolationEntity.VALUE,\n\t\t\t\tpartition.getPoints(),\n\t\t\t\tcurvePoints);\n\t}",
"protected static boolean numericEquals(Field vector1, Field vector2) {\n\t\tif (vector1.size() != vector2.size())\n\t\t\treturn false;\n\t\tif (vector1.isEmpty())\n\t\t\treturn true;\n\n\t\tIterator<Object> it1 = vector1.iterator();\n\t\tIterator<Object> it2 = vector2.iterator();\n\n\t\twhile (it1.hasNext()) {\n\t\t\tObject obj1 = it1.next();\n\t\t\tObject obj2 = it2.next();\n\n\t\t\tif (!(obj1 instanceof Number && obj2 instanceof Number))\n\t\t\t\treturn false;\n\n\t\t\tif (((Number) obj1).doubleValue() != ((Number) obj2).doubleValue())\n\t\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}",
"public void close()\n {\n inputManager.unregisterInputDeviceListener(inputDeviceListener);\n mouseDeviceManager.forceStopThread();\n gamepadDeviceManager.forceStopThread();\n controllerIds.clear();\n cache.clear();\n controllers.clear();\n }",
"public final boolean getBoolean(String name)\n {\n boolean result = false;\n Boolean value = (Boolean) getObject(name);\n if (value != null)\n {\n result = BooleanHelper.getBoolean(value);\n }\n return result;\n }"
] |
Send a waveform detail update announcement to all registered listeners.
@param player the player whose waveform detail has changed
@param detail the new waveform detail, if any | [
"private void deliverWaveformDetailUpdate(final int player, final WaveformDetail detail) {\n if (!getWaveformListeners().isEmpty()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n final WaveformDetailUpdate update = new WaveformDetailUpdate(player, detail);\n for (final WaveformListener listener : getWaveformListeners()) {\n try {\n listener.detailChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering waveform detail update to listener\", t);\n }\n }\n }\n });\n }\n }"
] | [
"protected void writeRow(final String... columns) throws IOException {\n\t\t\n\t\tif( columns == null ) {\n\t\t\tthrow new NullPointerException(String.format(\"columns to write should not be null on line %d\", lineNumber));\n\t\t} else if( columns.length == 0 ) {\n\t\t\tthrow new IllegalArgumentException(String.format(\"columns to write should not be empty on line %d\",\n\t\t\t\tlineNumber));\n\t\t}\n\t\t\n\t\tStringBuilder builder = new StringBuilder();\n\t\tfor( int i = 0; i < columns.length; i++ ) {\n\t\t\t\n\t\t\tcolumnNumber = i + 1; // column no used by CsvEncoder\n\t\t\t\n\t\t\tif( i > 0 ) {\n\t\t\t\tbuilder.append((char) preference.getDelimiterChar()); // delimiter\n\t\t\t}\n\t\t\t\n\t\t\tfinal String csvElement = columns[i];\n\t\t\tif( csvElement != null ) {\n\t\t\t\tfinal CsvContext context = new CsvContext(lineNumber, rowNumber, columnNumber);\n\t\t\t\tfinal String escapedCsv = encoder.encode(csvElement, context, preference);\n\t\t\t\tbuilder.append(escapedCsv);\n\t\t\t\tlineNumber = context.getLineNumber(); // line number can increment when encoding multi-line columns\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tbuilder.append(preference.getEndOfLineSymbols()); // EOL\n\t\twriter.write(builder.toString());\n\t}",
"public void add(Vector3d v1, Vector3d v2) {\n x = v1.x + v2.x;\n y = v1.y + v2.y;\n z = v1.z + v2.z;\n }",
"protected PreparedStatement prepareStatement(Connection con,\r\n String sql,\r\n boolean scrollable,\r\n boolean createPreparedStatement,\r\n int explicitFetchSizeHint)\r\n throws SQLException\r\n {\r\n PreparedStatement result;\r\n\r\n // if a JDBC1.0 driver is used the signature\r\n // prepareStatement(String, int, int) is not defined.\r\n // we then call the JDBC1.0 variant prepareStatement(String)\r\n try\r\n {\r\n // if necessary use JDB1.0 methods\r\n if (!FORCEJDBC1_0)\r\n {\r\n if (createPreparedStatement)\r\n {\r\n result =\r\n con.prepareStatement(\r\n sql,\r\n scrollable\r\n ? ResultSet.TYPE_SCROLL_INSENSITIVE\r\n : ResultSet.TYPE_FORWARD_ONLY,\r\n ResultSet.CONCUR_READ_ONLY);\r\n afterJdbc2CapableStatementCreate(result, explicitFetchSizeHint);\r\n }\r\n else\r\n {\r\n result =\r\n con.prepareCall(\r\n sql,\r\n scrollable\r\n ? ResultSet.TYPE_SCROLL_INSENSITIVE\r\n : ResultSet.TYPE_FORWARD_ONLY,\r\n ResultSet.CONCUR_READ_ONLY);\r\n }\r\n }\r\n else\r\n {\r\n if (createPreparedStatement)\r\n {\r\n result = con.prepareStatement(sql);\r\n }\r\n else\r\n {\r\n result = con.prepareCall(sql);\r\n }\r\n }\r\n }\r\n catch (AbstractMethodError err)\r\n {\r\n // this exception is raised if Driver is not JDBC 2.0 compliant\r\n log.warn(\"Used driver seems not JDBC 2.0 compatible, use the JDBC 1.0 mode\", err);\r\n if (createPreparedStatement)\r\n {\r\n result = con.prepareStatement(sql);\r\n }\r\n else\r\n {\r\n result = con.prepareCall(sql);\r\n }\r\n FORCEJDBC1_0 = true;\r\n }\r\n catch (SQLException eSql)\r\n {\r\n // there are JDBC Driver that nominally implement JDBC 2.0, but\r\n // throw DriverNotCapableExceptions. If we catch one of these\r\n // we force usage of JDBC 1.0\r\n if (eSql\r\n .getClass()\r\n .getName()\r\n .equals(\"interbase.interclient.DriverNotCapableException\"))\r\n {\r\n log.warn(\"JDBC 2.0 problems with this interbase driver, we use the JDBC 1.0 mode\");\r\n if (createPreparedStatement)\r\n {\r\n result = con.prepareStatement(sql);\r\n }\r\n else\r\n {\r\n result = con.prepareCall(sql);\r\n }\r\n FORCEJDBC1_0 = true;\r\n }\r\n else\r\n {\r\n throw eSql;\r\n }\r\n }\r\n try\r\n {\r\n if (!ProxyHelper.isNormalOjbProxy(result)) // tomdz: What about VirtualProxy\r\n {\r\n platform.afterStatementCreate(result);\r\n }\r\n }\r\n catch (PlatformException e)\r\n {\r\n log.error(\"Platform dependend failure\", e);\r\n }\r\n return result;\r\n }",
"private static I_CmsResourceBundle tryBundle(String localizedName) {\n\n I_CmsResourceBundle result = null;\n\n try {\n\n String resourceName = localizedName.replace('.', '/') + \".properties\";\n URL url = CmsResourceBundleLoader.class.getClassLoader().getResource(resourceName);\n\n I_CmsResourceBundle additionalBundle = m_permanentCache.get(localizedName);\n if (additionalBundle != null) {\n result = additionalBundle.getClone();\n } else if (url != null) {\n // the resource was found on the file system\n InputStream is = null;\n String path = CmsFileUtil.normalizePath(url);\n File file = new File(path);\n try {\n // try to load the resource bundle from a file, NOT with the resource loader first\n // this is important since using #getResourceAsStream() may return cached results,\n // for example Tomcat by default does cache all resources loaded by the class loader\n // this means a changed resource bundle file is not loaded\n is = new FileInputStream(file);\n } catch (IOException ex) {\n // this will happen if the resource is contained for example in a .jar file\n is = CmsResourceBundleLoader.class.getClassLoader().getResourceAsStream(resourceName);\n } catch (AccessControlException acex) {\n // fixed bug #1550\n // this will happen if the resource is contained for example in a .jar file\n // and security manager is turned on.\n is = CmsResourceBundleLoader.class.getClassLoader().getResourceAsStream(resourceName);\n }\n if (is != null) {\n result = new CmsPropertyResourceBundle(is);\n }\n }\n } catch (IOException ex) {\n // can't localized these message since this may lead to a chicken-egg problem\n MissingResourceException mre = new MissingResourceException(\n \"Failed to load bundle '\" + localizedName + \"'\",\n localizedName,\n \"\");\n mre.initCause(ex);\n throw mre;\n }\n\n return result;\n }",
"MACAddressSegment[] toEUISegments(boolean extended) {\n\t\tIPv6AddressSegment seg0, seg1, seg2, seg3;\n\t\tint start = addressSegmentIndex;\n\t\tint segmentCount = getSegmentCount();\n\t\tint segmentIndex;\n\t\tif(start < 4) {\n\t\t\tstart = 0;\n\t\t\tsegmentIndex = 4 - start;\n\t\t} else {\n\t\t\tstart -= 4;\n\t\t\tsegmentIndex = 0;\n\t\t}\n\t\tint originalSegmentIndex = segmentIndex;\n\t\tseg0 = (start == 0 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tseg1 = (start <= 1 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tseg2 = (start <= 2 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tseg3 = (start <= 3 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tint macSegCount = (segmentIndex - originalSegmentIndex) << 1;\n\t\tif(!extended) {\n\t\t\tmacSegCount -= 2;\n\t\t}\n\t\tif((seg1 != null && !seg1.matchesWithMask(0xff, 0xff)) || (seg2 != null && !seg2.matchesWithMask(0xfe00, 0xff00)) || macSegCount == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tMACAddressCreator creator = getMACNetwork().getAddressCreator();\n\t\tMACAddressSegment ZERO_SEGMENT = creator.createSegment(0);\n\t\tMACAddressSegment newSegs[] = creator.createSegmentArray(macSegCount);\n\t\tint macStartIndex = 0;\n\t\tif(seg0 != null) {\n\t\t\tseg0.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t//toggle the u/l bit\n\t\t\tMACAddressSegment macSegment0 = newSegs[0];\n\t\t\tint lower0 = macSegment0.getSegmentValue();\n\t\t\tint upper0 = macSegment0.getUpperSegmentValue();\n\t\t\tint mask2ndBit = 0x2;\n\t\t\tif(!macSegment0.matchesWithMask(mask2ndBit & lower0, mask2ndBit)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t//you can use matches with mask\n\t\t\tlower0 ^= mask2ndBit;//flip the universal/local bit\n\t\t\tupper0 ^= mask2ndBit;\n\t\t\tnewSegs[0] = creator.createSegment(lower0, upper0, null);\n\t\t\tmacStartIndex += 2;\n\t\t}\n\t\tif(seg1 != null) {\n\t\t\tseg1.getSplitSegments(newSegs, macStartIndex, creator); //a ff fe b\n\t\t\tif(!extended) {\n\t\t\t\tnewSegs[macStartIndex + 1] = ZERO_SEGMENT;\n\t\t\t}\n\t\t\tmacStartIndex += 2;\n\t\t}\n\t\tif(seg2 != null) {\n\t\t\tif(!extended) {\n\t\t\t\tif(seg1 != null) {\n\t\t\t\t\tmacStartIndex -= 2;\n\t\t\t\t\tMACAddressSegment first = newSegs[macStartIndex];\n\t\t\t\t\tseg2.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t\t\tnewSegs[macStartIndex] = first;\n\t\t\t\t} else {\n\t\t\t\t\tseg2.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t\t\tnewSegs[macStartIndex] = ZERO_SEGMENT;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tseg2.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t}\n\t\t\tmacStartIndex += 2;\n\t\t}\n\t\tif(seg3 != null) {\n\t\t\tseg3.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t}\n\t\treturn newSegs;\n\t}",
"SimpleJsonEncoder appendToJSONUnquoted(final String key, final Object value) {\n if (closed) {\n throw new IllegalStateException(\"Encoder already closed\");\n }\n if (value != null) {\n appendKey(key);\n sb.append(value);\n }\n return this;\n }",
"public void reportSqlError(String message, java.sql.SQLException sqlEx)\r\n {\r\n StringBuffer strBufMessages = new StringBuffer();\r\n java.sql.SQLException currentSqlEx = sqlEx;\r\n do\r\n {\r\n strBufMessages.append(\"\\n\" + sqlEx.getErrorCode() + \":\" + sqlEx.getMessage());\r\n currentSqlEx = currentSqlEx.getNextException();\r\n } while (currentSqlEx != null); \r\n System.err.println(message + strBufMessages.toString());\r\n sqlEx.printStackTrace();\r\n }",
"private FieldType getFieldType(byte[] data, int offset)\n {\n int fieldIndex = MPPUtility.getInt(data, offset);\n return FieldTypeHelper.mapTextFields(FieldTypeHelper.getInstance14(fieldIndex));\n }",
"@SafeVarargs\n\tpublic static <T> Set<T> asSet(T... ts) {\n\t\tif ( ts == null ) {\n\t\t\treturn null;\n\t\t}\n\t\telse if ( ts.length == 0 ) {\n\t\t\treturn Collections.emptySet();\n\t\t}\n\t\telse {\n\t\t\tSet<T> set = new HashSet<T>( getInitialCapacityFromExpectedSize( ts.length ) );\n\t\t\tCollections.addAll( set, ts );\n\t\t\treturn Collections.unmodifiableSet( set );\n\t\t}\n\t}"
] |
Populate the container, converting raw data into Java types.
@param field custom field to which these values belong
@param values raw value data
@param descriptions raw description data | [
"private void populateContainer(FieldType field, byte[] values, byte[] descriptions)\n {\n CustomField config = m_container.getCustomField(field);\n CustomFieldLookupTable table = config.getLookupTable();\n\n List<Object> descriptionList = convertType(DataType.STRING, descriptions);\n List<Object> valueList = convertType(field.getDataType(), values);\n for (int index = 0; index < descriptionList.size(); index++)\n {\n CustomFieldValueItem item = new CustomFieldValueItem(Integer.valueOf(0));\n item.setDescription((String) descriptionList.get(index));\n if (index < valueList.size())\n {\n item.setValue(valueList.get(index));\n }\n table.add(item);\n }\n }"
] | [
"public void swapSubstring(BitString other, int start, int length)\n {\n assertValidIndex(start);\n other.assertValidIndex(start);\n \n int word = start / WORD_LENGTH;\n\n int partialWordSize = (WORD_LENGTH - start) % WORD_LENGTH;\n if (partialWordSize > 0)\n {\n swapBits(other, word, 0xFFFFFFFF << (WORD_LENGTH - partialWordSize));\n ++word;\n }\n\n int remainingBits = length - partialWordSize;\n int stop = remainingBits / WORD_LENGTH;\n for (int i = word; i < stop; i++)\n {\n int temp = data[i];\n data[i] = other.data[i];\n other.data[i] = temp;\n }\n\n remainingBits %= WORD_LENGTH;\n if (remainingBits > 0)\n {\n swapBits(other, word, 0xFFFFFFFF >>> (WORD_LENGTH - remainingBits));\n }\n }",
"public boolean setCurrentPage(final int page) {\n Log.d(TAG, \"setPageId pageId = %d\", page);\n return (page >= 0 && page < getCheckableCount()) && check(page);\n }",
"void scan() {\n if (acquireScanLock()) {\n boolean scheduleRescan = false;\n try {\n scheduleRescan = scan(false, deploymentOperations);\n } finally {\n try {\n if (scheduleRescan) {\n synchronized (this) {\n if (scanEnabled) {\n rescanIncompleteTask = scheduledExecutor.schedule(scanRunnable, 200, TimeUnit.MILLISECONDS);\n }\n }\n }\n } finally {\n releaseScanLock();\n }\n }\n }\n }",
"public static XMLStreamException unexpectedEndElement(final XMLExtendedStreamReader reader) {\n return ControllerLogger.ROOT_LOGGER.unexpectedEndElement(reader.getName(), reader.getLocation());\n }",
"public void associateTypeJndiResource(JNDIResourceModel resource, String type)\n {\n if (type == null || resource == null)\n {\n return;\n }\n\n if (StringUtils.equals(type, \"javax.sql.DataSource\") && !(resource instanceof DataSourceModel))\n {\n DataSourceModel ds = GraphService.addTypeToModel(this.getGraphContext(), resource, DataSourceModel.class);\n }\n else if (StringUtils.equals(type, \"javax.jms.Queue\") && !(resource instanceof JmsDestinationModel))\n {\n JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class);\n jms.setDestinationType(JmsDestinationType.QUEUE);\n }\n else if (StringUtils.equals(type, \"javax.jms.QueueConnectionFactory\") && !(resource instanceof JmsConnectionFactoryModel))\n {\n JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class);\n jms.setConnectionFactoryType(JmsDestinationType.QUEUE);\n }\n else if (StringUtils.equals(type, \"javax.jms.Topic\") && !(resource instanceof JmsDestinationModel))\n {\n JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class);\n jms.setDestinationType(JmsDestinationType.TOPIC);\n }\n else if (StringUtils.equals(type, \"javax.jms.TopicConnectionFactory\") && !(resource instanceof JmsConnectionFactoryModel))\n {\n JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class);\n jms.setConnectionFactoryType(JmsDestinationType.TOPIC);\n }\n }",
"private ClassDescriptor[] getMultiJoinedClassDescriptors(ClassDescriptor cld)\r\n {\r\n DescriptorRepository repository = cld.getRepository();\r\n Class[] multiJoinedClasses = repository.getSubClassesMultipleJoinedTables(cld, true);\r\n ClassDescriptor[] result = new ClassDescriptor[multiJoinedClasses.length];\r\n\r\n for (int i = 0 ; i < multiJoinedClasses.length; i++)\r\n {\r\n result[i] = repository.getDescriptorFor(multiJoinedClasses[i]);\r\n }\r\n\r\n return result;\r\n }",
"public static LayersConfig getLayersConfig(final File repoRoot) throws IOException {\n final File layersList = new File(repoRoot, LAYERS_CONF);\n if (!layersList.exists()) {\n return new LayersConfig();\n }\n final Properties properties = PatchUtils.loadProperties(layersList);\n return new LayersConfig(properties);\n }",
"@PostConstruct\n public final void init() throws URISyntaxException {\n final String address = getConfig(ADDRESS, null);\n if (address != null) {\n final URI uri = new URI(\"udp://\" + address);\n final String prefix = getConfig(PREFIX, \"mapfish-print\").replace(\"%h\", getHostname());\n final int period = Integer.parseInt(getConfig(PERIOD, \"10\"));\n LOGGER.info(\"Starting a StatsD reporter targeting {} with prefix {} and period {}s\",\n uri, prefix, period);\n this.reporter = StatsDReporter.forRegistry(this.metricRegistry)\n .prefixedWith(prefix)\n .build(uri.getHost(), uri.getPort());\n this.reporter.start(period, TimeUnit.SECONDS);\n }\n }",
"private boolean isAllNumeric(TokenStream stream) {\n List<Token> tokens = ((NattyTokenSource) stream.getTokenSource()).getTokens();\n for(Token token:tokens) {\n try {\n Integer.parseInt(token.getText());\n } catch(NumberFormatException e) {\n return false;\n }\n }\n return true;\n }"
] |
EAP 7.0 | [
"private void buildTransformers_3_0(ResourceTransformationDescriptionBuilder builder) {\n /*\n ====== Resource root address: [\"subsystem\" => \"remoting\"] - Current version: 4.0.0; legacy version: 3.0.0 =======\n --- Problems for relative address to root [\"configuration\" => \"endpoint\"]:\n Different 'default' for attribute 'sasl-protocol'. Current: \"remote\"; legacy: \"remoting\" ## both are valid also for legacy servers\n --- Problems for relative address to root [\"connector\" => \"*\"]:\n Missing attributes in current: []; missing in legacy [sasl-authentication-factory, ssl-context]\n Missing parameters for operation 'add' in current: []; missing in legacy [sasl-authentication-factory, ssl-context]\n --- Problems for relative address to root [\"http-connector\" => \"*\"]:\n Missing attributes in current: []; missing in legacy [sasl-authentication-factory]\n Missing parameters for operation 'add' in current: []; missing in legacy [sasl-authentication-factory]\n --- Problems for relative address to root [\"remote-outbound-connection\" => \"*\"]:\n Missing attributes in current: []; missing in legacy [authentication-context]\n Different 'alternatives' for attribute 'protocol'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for attribute 'security-realm'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for attribute 'username'. Current: [\"authentication-context\"]; legacy: undefined\n Missing parameters for operation 'add' in current: []; missing in legacy [authentication-context]\n Different 'alternatives' for parameter 'protocol' of operation 'add'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for parameter 'security-realm' of operation 'add'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for parameter 'username' of operation 'add'. Current: [\"authentication-context\"]; legacy: undefined\n */\n\n builder.addChildResource(ConnectorResource.PATH).getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY, ConnectorResource.SSL_CONTEXT)\n .addRejectCheck(RejectAttributeChecker.DEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY, ConnectorResource.SSL_CONTEXT);\n\n builder.addChildResource(RemotingEndpointResource.ENDPOINT_PATH).getAttributeBuilder()\n .setValueConverter(new AttributeConverter.DefaultAttributeConverter() {\n @Override\n protected void convertAttribute(PathAddress address, String attributeName, ModelNode attributeValue, TransformationContext context) {\n if (!attributeValue.isDefined()) {\n attributeValue.set(\"remoting\"); //if value is not defined, set it to EAP 7.0 default valueRemotingSubsystemTransformersTestCase\n }\n }\n }, RemotingSubsystemRootResource.SASL_PROTOCOL);\n\n builder.addChildResource(HttpConnectorResource.PATH).getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY)\n .addRejectCheck(RejectAttributeChecker.DEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY);\n\n builder.addChildResource(RemoteOutboundConnectionResourceDefinition.ADDRESS).getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY)\n .addRejectCheck(RejectAttributeChecker.DEFINED, RemoteOutboundConnectionResourceDefinition.AUTHENTICATION_CONTEXT);\n }"
] | [
"public static int numberAwareCompareTo(Comparable self, Comparable other) {\n NumberAwareComparator<Comparable> numberAwareComparator = new NumberAwareComparator<Comparable>();\n return numberAwareComparator.compare(self, other);\n }",
"public static boolean isPrimitiveWrapperArray(Class<?> clazz) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\treturn (clazz.isArray() && isPrimitiveWrapper(clazz.getComponentType()));\n\t}",
"public <FV> FV getFieldValueIfNotDefault(Object object) throws SQLException {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tFV fieldValue = (FV) extractJavaFieldValue(object);\n\t\tif (isFieldValueDefault(fieldValue)) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn fieldValue;\n\t\t}\n\t}",
"public void writeNameValuePair(String name, Date value) throws IOException\n {\n internalWriteNameValuePair(name, m_format.format(value));\n }",
"public Collection<Photocount> getCounts(Date[] dates, Date[] takenDates) throws FlickrException {\r\n List<Photocount> photocounts = new ArrayList<Photocount>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_COUNTS);\r\n\r\n if (dates == null && takenDates == null) {\r\n throw new IllegalArgumentException(\"You must provide a value for either dates or takenDates\");\r\n }\r\n\r\n if (dates != null) {\r\n List<String> dateList = new ArrayList<String>();\r\n for (int i = 0; i < dates.length; i++) {\r\n dateList.add(String.valueOf(dates[i].getTime() / 1000L));\r\n }\r\n parameters.put(\"dates\", StringUtilities.join(dateList, \",\"));\r\n }\r\n\r\n if (takenDates != null) {\r\n List<String> takenDateList = new ArrayList<String>();\r\n for (int i = 0; i < takenDates.length; i++) {\r\n takenDateList.add(String.valueOf(takenDates[i].getTime() / 1000L));\r\n }\r\n parameters.put(\"taken_dates\", StringUtilities.join(takenDateList, \",\"));\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 photocountsElement = response.getPayload();\r\n NodeList photocountNodes = photocountsElement.getElementsByTagName(\"photocount\");\r\n for (int i = 0; i < photocountNodes.getLength(); i++) {\r\n Element photocountElement = (Element) photocountNodes.item(i);\r\n Photocount photocount = new Photocount();\r\n photocount.setCount(photocountElement.getAttribute(\"count\"));\r\n photocount.setFromDate(photocountElement.getAttribute(\"fromdate\"));\r\n photocount.setToDate(photocountElement.getAttribute(\"todate\"));\r\n photocounts.add(photocount);\r\n }\r\n return photocounts;\r\n }",
"public static base_response convert(nitro_service client, sslpkcs12 resource) throws Exception {\n\t\tsslpkcs12 convertresource = new sslpkcs12();\n\t\tconvertresource.outfile = resource.outfile;\n\t\tconvertresource.Import = resource.Import;\n\t\tconvertresource.pkcs12file = resource.pkcs12file;\n\t\tconvertresource.des = resource.des;\n\t\tconvertresource.des3 = resource.des3;\n\t\tconvertresource.export = resource.export;\n\t\tconvertresource.certfile = resource.certfile;\n\t\tconvertresource.keyfile = resource.keyfile;\n\t\tconvertresource.password = resource.password;\n\t\tconvertresource.pempassphrase = resource.pempassphrase;\n\t\treturn convertresource.perform_operation(client,\"convert\");\n\t}",
"public List<String> findAssociationPath(String targetTypeName, List<String> pathWithoutAlias) {\n\t\tList<String> subPath = new ArrayList<String>( pathWithoutAlias.size() );\n\t\tfor ( String name : pathWithoutAlias ) {\n\t\t\tsubPath.add( name );\n\t\t\tif ( isAssociation( targetTypeName, subPath ) ) {\n\t\t\t\treturn subPath;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"@Api\n\tpublic void setFeatureModel(FeatureModel featureModel) throws LayerException {\n\t\tthis.featureModel = featureModel;\n\t\tif (null != getLayerInfo()) {\n\t\t\tfeatureModel.setLayerInfo(getLayerInfo());\n\t\t}\n\t\tfilterService.registerFeatureModel(featureModel);\n\t}",
"@Override\n public void perform(GraphRewrite event, EvaluationContext context)\n {\n checkVariableName(event, context);\n WindupVertexFrame payload = resolveVariable(event, getVariableName());\n if (payload instanceof FileReferenceModel)\n {\n FileModel file = ((FileReferenceModel) payload).getFile();\n perform(event, context, (XmlFileModel) file);\n }\n else\n {\n super.perform(event, context);\n }\n\n }"
] |
Two stage distribution, dry run and actual promotion to verify correctness.
@param distributionBuilder
@param client
@param listener
@param buildName
@param buildNumber
@throws IOException | [
"public static boolean distributeAndCheckResponse(DistributionBuilder distributionBuilder, ArtifactoryBuildInfoClient client, TaskListener listener,\n String buildName, String buildNumber, boolean dryRun) throws IOException {\n // do a dry run first\n listener.getLogger().println(\"Performing dry run distribution (no changes are made during dry run) ...\");\n if (!distribute(distributionBuilder, client, listener, buildName, buildNumber, true)) {\n return false;\n }\n listener.getLogger().println(\"Dry run finished successfully\");\n if (!dryRun) {\n listener.getLogger().println(\"Performing distribution ...\");\n if (!distribute(distributionBuilder, client, listener, buildName, buildNumber, false)) {\n return false;\n }\n listener.getLogger().println(\"Distribution completed successfully!\");\n }\n return true;\n }"
] | [
"public static synchronized void addCachedDatabaseConfigs(Collection<DatabaseTableConfig<?>> configs) {\n\t\tMap<Class<?>, DatabaseTableConfig<?>> newMap;\n\t\tif (configMap == null) {\n\t\t\tnewMap = new HashMap<Class<?>, DatabaseTableConfig<?>>();\n\t\t} else {\n\t\t\tnewMap = new HashMap<Class<?>, DatabaseTableConfig<?>>(configMap);\n\t\t}\n\t\tfor (DatabaseTableConfig<?> config : configs) {\n\t\t\tnewMap.put(config.getDataClass(), config);\n\t\t\tlogger.info(\"Loaded configuration for {}\", config.getDataClass());\n\t\t}\n\t\tconfigMap = newMap;\n\t}",
"public synchronized String requestBlock(String name) {\n if (blocks.isEmpty()) {\n return \"exit\";\n }\n\n remainingBlocks.decrementAndGet();\n return blocks.poll().createResponse();\n }",
"private EventType createEventType(EventEnumType type) {\n EventType eventType = new EventType();\n eventType.setTimestamp(Converter.convertDate(new Date()));\n eventType.setEventType(type);\n\n OriginatorType origType = new OriginatorType();\n origType.setProcessId(Converter.getPID());\n try {\n InetAddress inetAddress = InetAddress.getLocalHost();\n origType.setIp(inetAddress.getHostAddress());\n origType.setHostname(inetAddress.getHostName());\n } catch (UnknownHostException e) {\n origType.setHostname(\"Unknown hostname\");\n origType.setIp(\"Unknown ip address\");\n }\n eventType.setOriginator(origType);\n\n String path = System.getProperty(\"karaf.home\");\n CustomInfoType ciType = new CustomInfoType();\n CustomInfoType.Item cItem = new CustomInfoType.Item();\n cItem.setKey(\"path\");\n cItem.setValue(path);\n ciType.getItem().add(cItem);\n eventType.setCustomInfo(ciType);\n\n return eventType;\n }",
"private String getInitials(String name)\n {\n String result = null;\n\n if (name != null && name.length() != 0)\n {\n StringBuilder sb = new StringBuilder();\n sb.append(name.charAt(0));\n int index = 1;\n while (true)\n {\n index = name.indexOf(' ', index);\n if (index == -1)\n {\n break;\n }\n\n ++index;\n if (index < name.length() && name.charAt(index) != ' ')\n {\n sb.append(name.charAt(index));\n }\n\n ++index;\n }\n\n result = sb.toString();\n }\n\n return result;\n }",
"public String generateTaskId() {\n final String uuid = UUID.randomUUID().toString().substring(0, 12);\n int size = this.targetHostMeta == null ? 0 : this.targetHostMeta\n .getHosts().size();\n return \"PT_\" + size + \"_\"\n + PcDateUtils.getNowDateTimeStrConciseNoZone() + \"_\" + uuid;\n }",
"protected boolean hasTimeOutHeader() {\n\n boolean result = false;\n String timeoutValStr = this.request.getHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS);\n if(timeoutValStr != null) {\n try {\n this.parsedTimeoutInMs = Long.parseLong(timeoutValStr);\n if(this.parsedTimeoutInMs < 0) {\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Time out cannot be negative \");\n\n } else {\n result = true;\n }\n } catch(NumberFormatException nfe) {\n logger.error(\"Exception when validating request. Incorrect timeout parameter. Cannot parse this to long: \"\n + timeoutValStr,\n nfe);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Incorrect timeout parameter. Cannot parse this to long: \"\n + timeoutValStr);\n }\n } else {\n logger.error(\"Error when validating request. Missing timeout parameter.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing timeout parameter.\");\n }\n return result;\n }",
"public void setVariable(String name, Object value) {\n if (variables == null)\n variables = new LinkedHashMap();\n variables.put(name, value);\n }",
"public void setDateMin(Date dateMin) {\n this.dateMin = dateMin;\n\n if (isAttached() && dateMin != null) {\n getPicker().set(\"min\", JsDate.create((double) dateMin.getTime()));\n }\n }",
"public void linkMtoN(Object obj, CollectionDescriptor cod, boolean insert)\n {\n Object referencedObjects = cod.getPersistentField().get(obj);\n storeAndLinkMtoN(true, obj, cod, referencedObjects, insert);\n }"
] |
For test purposes only. | [
"final void waitForSizeQueue(final int queueSize) {\n synchronized (this.queue) {\n while (this.queue.size() > queueSize) {\n try {\n this.queue.wait(250L);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n try {\n Thread.sleep(500L);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n this.queue.notifyAll();\n }\n }"
] | [
"public 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 }",
"@SuppressWarnings(\"deprecation\")\n @Deprecated\n public final void validateAndSet(ModelNode operationObject, final ModelNode model) throws OperationFailedException {\n validateOperation(operationObject);\n for (AttributeDefinition ad : this.parameters) {\n ad.validateAndSet(operationObject, model);\n }\n }",
"public void startup() {\n if (config.getEnableZookeeper()) {\n serverRegister.registerBrokerInZk();\n for (String topic : getAllTopics()) {\n serverRegister.processTask(new TopicTask(TopicTask.TaskType.CREATE, topic));\n }\n startupLatch.countDown();\n }\n logger.debug(\"Starting log flusher every {} ms with the following overrides {}\", config.getFlushSchedulerThreadRate(), logFlushIntervalMap);\n logFlusherScheduler.scheduleWithRate(new Runnable() {\n\n public void run() {\n flushAllLogs(false);\n }\n }, config.getFlushSchedulerThreadRate(), config.getFlushSchedulerThreadRate());\n }",
"public static CoordinateReferenceSystem parseProjection(\n final String projection, final Boolean longitudeFirst) {\n try {\n if (longitudeFirst == null) {\n return CRS.decode(projection);\n } else {\n return CRS.decode(projection, longitudeFirst);\n }\n } catch (NoSuchAuthorityCodeException e) {\n throw new RuntimeException(projection + \" was not recognized as a crs code\", e);\n } catch (FactoryException e) {\n throw new RuntimeException(\"Error occurred while parsing: \" + projection, e);\n }\n }",
"public float getPositionZ(int vertex) {\n if (!hasPositions()) {\n throw new IllegalStateException(\"mesh has no positions\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_vertices.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT);\n }",
"protected void init(EnhancedAnnotation<T> annotatedAnnotation) {\n initType(annotatedAnnotation);\n initValid(annotatedAnnotation);\n check(annotatedAnnotation);\n }",
"public void merge() {\n Thread currentThread = Thread.currentThread();\n if(!stats.get(currentThread).equals(this) || currentThread instanceof WindupChildThread) {\n throw new IllegalArgumentException(\"Trying to merge executionstatistics from a \"\n + \"different thread that is not registered as main thread of application run\");\n }\n\n for (Thread thread : stats.keySet())\n {\n if(thread instanceof WindupChildThread && ((WindupChildThread) thread).getParentThread().equals(currentThread)) {\n merge(stats.get(thread));\n }\n }\n }",
"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}",
"protected void parseIntegerLists(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n if( t == null || t.next == null )\n return;\n\n int state = 0;\n\n TokenList.Token start = null;\n TokenList.Token prev = t;\n\n boolean last = false;\n while( true ) {\n if( state == 0 ) {\n if( isVariableInteger(t) ) {\n start = t;\n state = 1;\n }\n } else if( state == 1 ) {\n // var ?\n if( isVariableInteger(t)) { // see if its explicit number sequence\n state = 2;\n } else { // just scalar integer, skip\n state = 0;\n }\n } else if ( state == 2 ) {\n // var var ....\n if( !isVariableInteger(t) ) {\n // create explicit list sequence\n IntegerSequence sequence = new IntegerSequence.Explicit(start,prev);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, prev);\n state = 0;\n }\n }\n\n if( last ) {\n break;\n } else if( t.next == null ) {\n // handle the case where it is the last token in the sequence\n last = true;\n }\n prev = t;\n t = t.next;\n }\n }"
] |
This method is designed to be called from the diverse subclasses | [
"protected final String computeId(\n final ITemplateContext context,\n final IProcessableElementTag tag,\n final String name, final boolean sequence) {\n\n String id = tag.getAttributeValue(this.idAttributeDefinition.getAttributeName());\n if (!org.thymeleaf.util.StringUtils.isEmptyOrWhitespace(id)) {\n return (StringUtils.hasText(id) ? id : null);\n }\n\n id = FieldUtils.idFromName(name);\n if (sequence) {\n final Integer count = context.getIdentifierSequences().getAndIncrementIDSeq(id);\n return id + count.toString();\n }\n return id;\n\n }"
] | [
"private int read() {\n int curByte = 0;\n try {\n curByte = rawData.get() & 0xFF;\n } catch (Exception e) {\n header.status = GifDecoder.STATUS_FORMAT_ERROR;\n }\n return curByte;\n }",
"private static Class<?> extractTypeFromClass(Class<?> clazz, Class<?> source, int typeIndex,\n\t\t\tMap<TypeVariable, Type> typeVariableMap, Map<Integer, Integer> typeIndexesPerLevel,\n\t\t\tint nestingLevel, int currentLevel) {\n\n\t\tif (clazz.getName().startsWith(\"java.util.\")) {\n\t\t\treturn null;\n\t\t}\n\t\tif (clazz.getSuperclass() != null && isIntrospectionCandidate(clazz.getSuperclass())) {\n\t\t\ttry {\n\t\t\t\treturn extractType(clazz.getGenericSuperclass(), source, typeIndex, typeVariableMap,\n\t\t\t\t\t\ttypeIndexesPerLevel, nestingLevel, currentLevel);\n\t\t\t}\n\t\t\tcatch (MalformedParameterizedTypeException ex) {\n\t\t\t\t// from getGenericSuperclass() - ignore and continue with interface introspection\n\t\t\t}\n\t\t}\n\t\tType[] ifcs = clazz.getGenericInterfaces();\n\t\tif (ifcs != null) {\n\t\t\tfor (Type ifc : ifcs) {\n\t\t\t\tType rawType = ifc;\n\t\t\t\tif (ifc instanceof ParameterizedType) {\n\t\t\t\t\trawType = ((ParameterizedType) ifc).getRawType();\n\t\t\t\t}\n\t\t\t\tif (rawType instanceof Class && isIntrospectionCandidate((Class) rawType)) {\n\t\t\t\t\treturn extractType(ifc, source, typeIndex, typeVariableMap, typeIndexesPerLevel, nestingLevel, currentLevel);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public int getIntegerBelief(String name){\n Object belief = introspector.getBeliefBase(this).get(name);\n int count = 0;\n if (belief!=null) {\n count = (Integer) belief;\n }\n return (Integer) count;\n }",
"public static boolean isOperationDefined(final ModelNode operation) {\n for (final AttributeDefinition def : ROOT_ATTRIBUTES) {\n if (operation.hasDefined(def.getName())) {\n return true;\n }\n }\n return false;\n }",
"public void clear() {\n\t\tfor (Bean bean : beans.values()) {\n\t\t\tif (null != bean.destructionCallback) {\n\t\t\t\tbean.destructionCallback.run();\n\t\t\t}\n\t\t}\n\t\tbeans.clear();\n\t}",
"public static ZMatrixRMaj householderVector(ZMatrixRMaj x ) {\n ZMatrixRMaj u = x.copy();\n\n double max = CommonOps_ZDRM.elementMaxAbs(u);\n\n CommonOps_ZDRM.elementDivide(u, max, 0, u);\n\n double nx = NormOps_ZDRM.normF(u);\n Complex_F64 c = new Complex_F64();\n u.get(0,0,c);\n\n double realTau,imagTau;\n\n if( c.getMagnitude() == 0 ) {\n realTau = nx;\n imagTau = 0;\n } else {\n realTau = c.real/c.getMagnitude()*nx;\n imagTau = c.imaginary/c.getMagnitude()*nx;\n }\n\n u.set(0,0,c.real + realTau,c.imaginary + imagTau);\n CommonOps_ZDRM.elementDivide(u,u.getReal(0,0),u.getImag(0,0),u);\n\n return u;\n }",
"public HttpConnection setRequestBody(final String input) {\n try {\n final byte[] inputBytes = input.getBytes(\"UTF-8\");\n return setRequestBody(inputBytes);\n } catch (UnsupportedEncodingException e) {\n // This should never happen as every implementation of the java platform is required\n // to support UTF-8.\n throw new RuntimeException(e);\n }\n }",
"protected static boolean fileDoesNotExist(String file, String path,\n String dest_dir) {\n\n File f = new File(dest_dir);\n if (!f.isDirectory())\n return false;\n\n String folderPath = createFolderPath(path);\n\n f = new File(f, folderPath);\n\n File javaFile = new File(f, file);\n boolean result = !javaFile.exists();\n\n return result;\n }",
"@UiHandler(\"m_wholeDayCheckBox\")\n void onWholeDayChange(ValueChangeEvent<Boolean> event) {\n\n //TODO: Improve - adjust time selections?\n if (handleChange()) {\n m_controller.setWholeDay(event.getValue());\n }\n }"
] |
Adds parameters contained in the annotation into the annotation type reference
@param typeRef
@param node | [
"private void addAnnotationValues(ClassReference annotatedReference, AnnotationClassReference typeRef, Annotation node)\n {\n Map<String, AnnotationValue> annotationValueMap = new HashMap<>();\n if (node instanceof SingleMemberAnnotation)\n {\n SingleMemberAnnotation singleMemberAnnotation = (SingleMemberAnnotation) node;\n AnnotationValue value = getAnnotationValueForExpression(annotatedReference, singleMemberAnnotation.getValue());\n annotationValueMap.put(\"value\", value);\n }\n else if (node instanceof NormalAnnotation)\n {\n @SuppressWarnings(\"unchecked\")\n List<MemberValuePair> annotationValues = ((NormalAnnotation) node).values();\n for (MemberValuePair annotationValue : annotationValues)\n {\n String key = annotationValue.getName().toString();\n Expression expression = annotationValue.getValue();\n AnnotationValue value = getAnnotationValueForExpression(annotatedReference, expression);\n annotationValueMap.put(key, value);\n }\n }\n typeRef.setAnnotationValues(annotationValueMap);\n }"
] | [
"public HostName toHostName() {\n\t\tHostName host = fromHost;\n\t\tif(host == null) {\n\t\t\tfromHost = host = toCanonicalHostName();\n\t\t}\n\t\treturn host;\n\t}",
"public static base_responses flush(nitro_service client, cacheobject resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheobject flushresources[] = new cacheobject[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tflushresources[i] = new cacheobject();\n\t\t\t\tflushresources[i].locator = resources[i].locator;\n\t\t\t\tflushresources[i].url = resources[i].url;\n\t\t\t\tflushresources[i].host = resources[i].host;\n\t\t\t\tflushresources[i].port = resources[i].port;\n\t\t\t\tflushresources[i].groupname = resources[i].groupname;\n\t\t\t\tflushresources[i].httpmethod = resources[i].httpmethod;\n\t\t\t\tflushresources[i].force = resources[i].force;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, flushresources,\"flush\");\n\t\t}\n\t\treturn result;\n\t}",
"protected boolean check(String id, List<String> includes, List<String> excludes) {\n\t\treturn check(id, includes) && !check(id, excludes);\n\t}",
"public Query customizeQuery(Object anObject, PersistenceBroker aBroker, CollectionDescriptor aCod, QueryByCriteria aQuery)\r\n {\r\n return aQuery;\r\n }",
"private boolean computeEigenValues() {\n // make a copy of the internal tridiagonal matrix data for later use\n diagSaved = helper.copyDiag(diagSaved);\n offSaved = helper.copyOff(offSaved);\n\n vector.setQ(null);\n vector.setFastEigenvalues(true);\n\n // extract the eigenvalues\n if( !vector.process(-1,null,null) )\n return false;\n\n // save a copy of them since this data structure will be recycled next\n values = helper.copyEigenvalues(values);\n return true;\n }",
"public static Region fromName(String name) {\n if (name == null) {\n return null;\n }\n\n Region region = VALUES_BY_NAME.get(name.toLowerCase().replace(\" \", \"\"));\n if (region != null) {\n return region;\n } else {\n return Region.create(name.toLowerCase().replace(\" \", \"\"), name);\n }\n }",
"private String getCacheFormatEntry() throws IOException {\n ZipEntry zipEntry = zipFile.getEntry(CACHE_FORMAT_ENTRY);\n InputStream is = zipFile.getInputStream(zipEntry);\n try {\n Scanner s = new Scanner(is, \"UTF-8\").useDelimiter(\"\\\\A\");\n String tag = null;\n if (s.hasNext()) tag = s.next();\n return tag;\n } finally {\n is.close();\n }\n }",
"public Where<T, ID> exists(QueryBuilder<?, ?> subQueryBuilder) {\n\t\t// we do this to turn off the automatic addition of the ID column in the select column list\n\t\tsubQueryBuilder.enableInnerQuery();\n\t\taddClause(new Exists(new InternalQueryBuilderWrapper(subQueryBuilder)));\n\t\treturn this;\n\t}",
"public void postConstruct(GeoService geoService, DtoConverterService converterService) throws GeomajasException {\n\t\tif (null == layerInfo) {\n\t\t\tlayerInfo = new RasterLayerInfo();\n\t\t}\n\t\tlayerInfo.setCrs(TiledRasterLayerService.MERCATOR);\n\t\tcrs = geoService.getCrs2(TiledRasterLayerService.MERCATOR);\n\t\tlayerInfo.setTileWidth(tileSize);\n\t\tlayerInfo.setTileHeight(tileSize);\n\t\tBbox bbox = new Bbox(-TiledRasterLayerService.HALF_EQUATOR_IN_METERS,\n\t\t\t\t-TiledRasterLayerService.HALF_EQUATOR_IN_METERS, TiledRasterLayerService.EQUATOR_IN_METERS,\n\t\t\t\tTiledRasterLayerService.EQUATOR_IN_METERS);\n\t\tlayerInfo.setMaxExtent(bbox);\n\t\tmaxBounds = converterService.toInternal(bbox);\n\n\t\tresolutions = new double[maxZoomLevel + 1];\n\t\tdouble powerOfTwo = 1;\n\t\tfor (int zoomLevel = 0; zoomLevel <= maxZoomLevel; zoomLevel++) {\n\t\t\tdouble resolution = (TiledRasterLayerService.EQUATOR_IN_METERS) / (tileSize * powerOfTwo);\n\t\t\tresolutions[zoomLevel] = resolution;\n\t\t\tpowerOfTwo *= 2;\n\t\t}\n\t}"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.