query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
read the file as a list of text lines
[ "private List<String> getCommandLines(File file) {\n List<String> lines = new ArrayList<>();\n try (BufferedReader reader = new BufferedReader(new FileReader(file))) {\n String line = reader.readLine();\n while (line != null) {\n lines.add(line);\n line = reader.readLine();\n }\n } catch (Throwable e) {\n throw new IllegalStateException(\"Failed to process file \" + file.getAbsolutePath(), e);\n }\n return lines;\n }" ]
[ "private Map<String, String> toPayload(Map<String, Object> data) throws LocalOperationException {\n Map<String, Object> dataClone = new HashMap<String, Object>(data);\n dataClone.put(\"auth\", getAuthData());\n\n Map<String, String> payload = new HashMap<String, String>();\n payload.put(\"params\", jsonifyData(dataClone));\n\n if (transloadit.shouldSignRequest) {\n payload.put(\"signature\", getSignature(jsonifyData(dataClone)));\n }\n return payload;\n }", "public Object remove(String name) {\n\t\tThreadScopeContext context = ThreadScopeContextHolder.getContext();\n\t\treturn context.remove(name);\n\t}", "public void create(final DbProduct dbProduct) {\n if(repositoryHandler.getProduct(dbProduct.getName()) != null){\n throw new WebApplicationException(Response.status(Response.Status.CONFLICT).entity(\"Product already exist!\").build());\n }\n\n repositoryHandler.store(dbProduct);\n }", "public static base_responses disable(nitro_service client, Long clid[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (clid != null && clid.length > 0) {\n\t\t\tclusterinstance disableresources[] = new clusterinstance[clid.length];\n\t\t\tfor (int i=0;i<clid.length;i++){\n\t\t\t\tdisableresources[i] = new clusterinstance();\n\t\t\t\tdisableresources[i].clid = clid[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, disableresources,\"disable\");\n\t\t}\n\t\treturn result;\n\t}", "public static void writeObject(File file, Object object) throws IOException {\n FileOutputStream fileOut = new FileOutputStream(file);\n ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fileOut));\n try {\n out.writeObject(object);\n out.flush();\n // Force sync\n fileOut.getFD().sync();\n } finally {\n IoUtils.safeClose(out);\n }\n }", "private void processCalendars() throws Exception\n {\n List<Row> rows = getRows(\"select * from zcalendar where zproject=?\", m_projectID);\n for (Row row : rows)\n {\n ProjectCalendar calendar = m_project.addCalendar();\n calendar.setUniqueID(row.getInteger(\"Z_PK\"));\n calendar.setName(row.getString(\"ZTITLE\"));\n processDays(calendar);\n processExceptions(calendar);\n m_eventManager.fireCalendarReadEvent(calendar);\n }\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<Symmetry010Date> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<Symmetry010Date>) super.localDateTime(temporal);\n }", "private void updateDb(String dbName, String webapp) {\n\n m_mainLayout.removeAllComponents();\n m_setupBean.setDatabase(dbName);\n CmsDbSettingsPanel panel = new CmsDbSettingsPanel(m_setupBean);\n m_panel[0] = panel;\n panel.initFromSetupBean(webapp);\n m_mainLayout.addComponent(panel);\n }", "public CollectionRequest<Task> subtasks(String task) {\n \n String path = String.format(\"/tasks/%s/subtasks\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }" ]
Pause the current entry point, and invoke the provided listener when all current requests have finished. If individual control point tracking is not enabled then the listener will be invoked straight away @param requestCountListener The listener to invoke
[ "public void pause(ServerActivityCallback requestCountListener) {\n if (paused) {\n throw ServerLogger.ROOT_LOGGER.serverAlreadyPaused();\n }\n this.paused = true;\n listenerUpdater.set(this, requestCountListener);\n if (activeRequestCountUpdater.get(this) == 0) {\n if (listenerUpdater.compareAndSet(this, requestCountListener, null)) {\n requestCountListener.done();\n }\n }\n }" ]
[ "public void createDB() throws PlatformException\r\n {\r\n if (_creationScript == null)\r\n {\r\n createCreationScript();\r\n }\r\n\r\n Project project = new Project();\r\n TorqueDataModelTask modelTask = new TorqueDataModelTask();\r\n File tmpDir = null;\r\n File scriptFile = null;\r\n \r\n try\r\n {\r\n tmpDir = new File(getWorkDir(), \"schemas\");\r\n tmpDir.mkdir();\r\n\r\n scriptFile = new File(tmpDir, CREATION_SCRIPT_NAME);\r\n\r\n writeCompressedText(scriptFile, _creationScript);\r\n\r\n project.setBasedir(tmpDir.getAbsolutePath());\r\n\r\n // we use the ant task 'sql' to perform the creation script\r\n\t SQLExec sqlTask = new SQLExec();\r\n\t SQLExec.OnError onError = new SQLExec.OnError();\r\n\t\r\n\t onError.setValue(\"continue\");\r\n\t sqlTask.setProject(project);\r\n\t sqlTask.setAutocommit(true);\r\n\t sqlTask.setDriver(_jcd.getDriver());\r\n\t sqlTask.setOnerror(onError);\r\n\t sqlTask.setUserid(_jcd.getUserName());\r\n\t sqlTask.setPassword(_jcd.getPassWord() == null ? \"\" : _jcd.getPassWord());\r\n\t sqlTask.setUrl(getDBCreationUrl());\r\n\t sqlTask.setSrc(scriptFile);\r\n\t sqlTask.execute();\r\n\r\n\t deleteDir(tmpDir);\r\n }\r\n catch (Exception ex)\r\n {\r\n // clean-up\r\n if ((tmpDir != null) && tmpDir.exists())\r\n {\r\n try\r\n {\r\n scriptFile.delete();\r\n }\r\n catch (NullPointerException e) \r\n {\r\n LoggerFactory.getLogger(this.getClass()).error(\"NPE While deleting scriptFile [\" + scriptFile.getName() + \"]\", e);\r\n }\r\n }\r\n throw new PlatformException(ex);\r\n }\r\n }", "public static Class<?> getRawType(Type type) {\n\t\tif (type instanceof Class) {\n\t\t\treturn (Class<?>) type;\n\t\t} else if (type instanceof ParameterizedType) {\n\t\t\tParameterizedType actualType = (ParameterizedType) type;\n\t\t\treturn getRawType(actualType.getRawType());\n\t\t} else if (type instanceof GenericArrayType) {\n\t\t\tGenericArrayType genericArrayType = (GenericArrayType) type;\n\t\t\tObject rawArrayType = Array.newInstance(getRawType(genericArrayType\n\t\t\t\t\t.getGenericComponentType()), 0);\n\t\t\treturn rawArrayType.getClass();\n\t\t} else if (type instanceof WildcardType) {\n\t\t\tWildcardType castedType = (WildcardType) type;\n\t\t\treturn getRawType(castedType.getUpperBounds()[0]);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Type \\'\"\n\t\t\t\t\t\t\t+ type\n\t\t\t\t\t\t\t+ \"\\' is not a Class, \"\n\t\t\t\t\t\t\t+ \"ParameterizedType, or GenericArrayType. Can't extract class.\");\n\t\t}\n\t}", "private String FCMGetFreshToken(final String senderID) {\n String token = null;\n try {\n if(senderID != null){\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Requesting a FCM token with Sender Id - \"+senderID);\n token = FirebaseInstanceId.getInstance().getToken(senderID, FirebaseMessaging.INSTANCE_ID_SCOPE);\n }else {\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Requesting a FCM token\");\n token = FirebaseInstanceId.getInstance().getToken();\n }\n getConfigLogger().info(getAccountId(),\"FCM token: \"+token);\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Error requesting FCM token\", t);\n }\n return token;\n }", "protected View postDeclineView() {\n\t\treturn new TopLevelWindowRedirect() {\n\t\t\t@Override\n\t\t\tprotected String getRedirectUrl(Map<String, ?> model) {\n\t\t\t\treturn postDeclineUrl;\n\t\t\t}\n\t\t};\n\t}", "private static <T, ID> MappedDeleteCollection<T, ID> build(Dao<T, ID> dao, TableInfo<T, ID> tableInfo, int dataSize)\n\t\t\tthrows SQLException {\n\t\tFieldType idField = tableInfo.getIdField();\n\t\tif (idField == null) {\n\t\t\tthrow new SQLException(\n\t\t\t\t\t\"Cannot delete \" + tableInfo.getDataClass() + \" because it doesn't have an id field defined\");\n\t\t}\n\t\tStringBuilder sb = new StringBuilder(128);\n\t\tDatabaseType databaseType = dao.getConnectionSource().getDatabaseType();\n\t\tappendTableName(databaseType, sb, \"DELETE FROM \", tableInfo.getTableName());\n\t\tFieldType[] argFieldTypes = new FieldType[dataSize];\n\t\tappendWhereIds(databaseType, idField, sb, dataSize, argFieldTypes);\n\t\treturn new MappedDeleteCollection<T, ID>(dao, tableInfo, sb.toString(), argFieldTypes);\n\t}", "public byte[] getByteArrayValue(int index)\n {\n byte[] result = null;\n\n if (m_array[index] != null)\n {\n result = (byte[]) m_array[index];\n }\n\n return (result);\n }", "private static EventEnumType convertEventType(org.talend.esb.sam.common.event.EventTypeEnum eventType) {\n if (eventType == null) {\n return null;\n }\n return EventEnumType.valueOf(eventType.name());\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 static void scaleCol( double alpha , DMatrixRMaj A , int col ) {\n int idx = col;\n for (int row = 0; row < A.numRows; row++, idx += A.numCols) {\n A.data[idx] *= alpha;\n }\n }" ]
Generate the next available field for a user defined field. @param <E> field type class @param clazz class of the desired field enum @param type user defined field type. @return field of specified type
[ "public <E extends Enum<E> & FieldType> E nextField(Class<E> clazz, UserFieldDataType type)\n {\n for (String name : m_names[type.ordinal()])\n {\n int i = NumberHelper.getInt(m_counters.get(name)) + 1;\n try\n {\n E e = Enum.valueOf(clazz, name + i);\n m_counters.put(name, Integer.valueOf(i));\n return e;\n }\n catch (IllegalArgumentException ex)\n {\n // try the next name\n }\n }\n\n // no more fields available\n throw new IllegalArgumentException(\"No fields for type \" + type + \" available\");\n }" ]
[ "private void configureCaching(HttpServletResponse response, int seconds) {\n\t\t// HTTP 1.0 header\n\t\tresponse.setDateHeader(HTTP_EXPIRES_HEADER, System.currentTimeMillis() + seconds * 1000L);\n\t\tif (seconds > 0) {\n\t\t\t// HTTP 1.1 header\n\t\t\tresponse.setHeader(HTTP_CACHE_CONTROL_HEADER, \"max-age=\" + seconds);\n\t\t} else {\n\t\t\t// HTTP 1.1 header\n\t\t\tresponse.setHeader(HTTP_CACHE_CONTROL_HEADER, \"no-cache\");\n\n\t\t}\n\t}", "static void processRoot(final File root, final ProcessedLayers layers, final LayerPathSetter setter) throws IOException {\n final LayersConfig layersConfig = LayersConfig.getLayersConfig(root);\n // Process layers\n final File layersDir = new File(root, layersConfig.getLayersPath());\n if (!layersDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationNoLayersConfigFound(layersDir.getAbsolutePath());\n }\n // else this isn't a root that has layers and add-ons\n } else {\n // check for a valid layer configuration\n for (final String layer : layersConfig.getLayers()) {\n File layerDir = new File(layersDir, layer);\n if (!layerDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationMissingLayer(layer, layersDir.getAbsolutePath());\n }\n // else this isn't a standard layers and add-ons structure\n return;\n }\n layers.addLayer(layer, layerDir, setter);\n }\n }\n // Finally process the add-ons\n final File addOnsDir = new File(root, layersConfig.getAddOnsPath());\n final File[] addOnsList = addOnsDir.listFiles();\n if (addOnsList != null) {\n for (final File addOn : addOnsList) {\n layers.addAddOn(addOn.getName(), addOn, setter);\n }\n }\n }", "public synchronized int skip(int count) {\n if (count > available) {\n count = available;\n }\n idxGet = (idxGet + count) % capacity;\n available -= count;\n return count;\n }", "public static gslbrunningconfig get(nitro_service service) throws Exception{\n\t\tgslbrunningconfig obj = new gslbrunningconfig();\n\t\tgslbrunningconfig[] response = (gslbrunningconfig[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public Bundler put(String key, Parcelable value) {\n delegate.putParcelable(key, value);\n return this;\n }", "public Where<T, ID> or(Where<T, ID> left, Where<T, ID> right, Where<T, ID>... others) {\n\t\tClause[] clauses = buildClauseArray(others, \"OR\");\n\t\tClause secondClause = pop(\"OR\");\n\t\tClause firstClause = pop(\"OR\");\n\t\taddClause(new ManyClause(firstClause, secondClause, clauses, ManyClause.OR_OPERATION));\n\t\treturn this;\n\t}", "public int getIndexByDate(Date date)\n {\n int result = -1;\n int index = 0;\n\n for (CostRateTableEntry entry : this)\n {\n if (DateHelper.compare(date, entry.getEndDate()) < 0)\n {\n result = index;\n break;\n }\n ++index;\n }\n\n return result;\n }", "public String name(Properties attributes) throws XDocletException\r\n {\r\n return getDefForLevel(attributes.getProperty(ATTRIBUTE_LEVEL)).getName();\r\n }", "private Object getConstantValue(FieldType type, byte[] block)\n {\n Object value;\n DataType dataType = type.getDataType();\n\n if (dataType == null)\n {\n value = null;\n }\n else\n {\n switch (dataType)\n {\n case DURATION:\n {\n value = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(block, getValueOffset()), MPPUtility.getDurationTimeUnits(MPPUtility.getShort(block, getTimeUnitsOffset())));\n break;\n }\n\n case NUMERIC:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()));\n break;\n }\n\n case PERCENTAGE:\n {\n value = Double.valueOf(MPPUtility.getShort(block, getValueOffset()));\n break;\n }\n\n case CURRENCY:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()) / 100);\n break;\n }\n\n case STRING:\n {\n int textOffset = getTextOffset(block);\n value = MPPUtility.getUnicodeString(m_criteriaData, m_dataOffset + m_criteriaTextStart + textOffset);\n break;\n }\n\n case BOOLEAN:\n {\n int intValue = MPPUtility.getShort(block, getValueOffset());\n value = (intValue == 1 ? Boolean.TRUE : Boolean.FALSE);\n break;\n }\n\n case DATE:\n {\n value = MPPUtility.getTimestamp(block, getValueOffset());\n break;\n }\n\n default:\n {\n value = null;\n break;\n }\n }\n }\n\n return value;\n }" ]
Use this API to fetch spilloverpolicy resource of given name .
[ "public static spilloverpolicy get(nitro_service service, String name) throws Exception{\n\t\tspilloverpolicy obj = new spilloverpolicy();\n\t\tobj.set_name(name);\n\t\tspilloverpolicy response = (spilloverpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "public static CmsUUID readId(JSONObject obj, String key) {\n\n String strValue = obj.optString(key);\n if (!CmsUUID.isValidUUID(strValue)) {\n return null;\n }\n return new CmsUUID(strValue);\n }", "private void getMonthlyAbsoluteDates(Calendar calendar, int frequency, List<Date> dates)\n {\n int currentDayNumber = calendar.get(Calendar.DAY_OF_MONTH);\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n int requiredDayNumber = NumberHelper.getInt(m_dayNumber);\n if (requiredDayNumber < currentDayNumber)\n {\n calendar.add(Calendar.MONTH, 1);\n }\n\n while (moreDates(calendar, dates))\n {\n int useDayNumber = requiredDayNumber;\n int maxDayNumber = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);\n if (useDayNumber > maxDayNumber)\n {\n useDayNumber = maxDayNumber;\n }\n calendar.set(Calendar.DAY_OF_MONTH, useDayNumber);\n dates.add(calendar.getTime());\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.add(Calendar.MONTH, frequency);\n }\n }", "public String getNotes()\n {\n String notes = (String) getCachedValue(ResourceField.NOTES);\n return (notes == null ? \"\" : notes);\n }", "public static double[][] diag(double[] vector){\n\n\t\t// Note: According to the Java Language spec, an array is initialized with the default value, here 0.\n\t\tdouble[][] diagonalMatrix = new double[vector.length][vector.length];\n\n\t\tfor(int index = 0; index < vector.length; index++) {\n\t\t\tdiagonalMatrix[index][index] = vector[index];\n\t\t}\n\n\t\treturn diagonalMatrix;\n\t}", "public Number getPercentageWorkComplete()\n {\n Number pct = (Number) getCachedValue(AssignmentField.PERCENT_WORK_COMPLETE);\n if (pct == null)\n {\n Duration actualWork = getActualWork();\n Duration work = getWork();\n if (actualWork != null && work != null && work.getDuration() != 0)\n {\n pct = Double.valueOf((actualWork.getDuration() * 100) / work.convertUnits(actualWork.getUnits(), getParentFile().getProjectProperties()).getDuration());\n set(AssignmentField.PERCENT_WORK_COMPLETE, pct);\n }\n }\n return pct;\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 }", "private StringBuilder calculateCacheKeyInternal(String sql,\r\n\t\t\tint resultSetType, int resultSetConcurrency) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+20);\r\n\t\ttmp.append(sql);\r\n\r\n\t\ttmp.append(\", T\");\r\n\t\ttmp.append(resultSetType);\r\n\t\ttmp.append(\", C\");\r\n\t\ttmp.append(resultSetConcurrency);\r\n\t\treturn tmp;\r\n\t}", "private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList) {\n List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>();\n\n int parentCount = parentList.size();\n for (int i = 0; i < parentCount; i++) {\n P parent = parentList.get(i);\n generateParentWrapper(flatItemList, parent, parent.isInitiallyExpanded());\n }\n\n return flatItemList;\n }", "public void run()\r\n { \t\r\n \tSystem.out.println(AsciiSplash.getSplashArt());\r\n System.out.println(\"Welcome to the OJB PB tutorial application\");\r\n System.out.println();\r\n // never stop (there is a special use case to quit the application)\r\n while (true)\r\n {\r\n try\r\n {\r\n // select a use case and perform it\r\n UseCase uc = selectUseCase();\r\n uc.apply();\r\n }\r\n catch (Throwable t)\r\n {\r\n broker.close();\r\n System.out.println(t.getMessage());\r\n }\r\n }\r\n }" ]
Trim and append a file separator to the string
[ "private String fixApiDocRoot(String str) {\n\tif (str == null)\n\t return null;\n\tString fixed = str.trim();\n\tif (fixed.isEmpty())\n\t return \"\";\n\tif (File.separatorChar != '/')\n\t fixed = fixed.replace(File.separatorChar, '/');\n\tif (!fixed.endsWith(\"/\"))\n\t fixed = fixed + \"/\";\n\treturn fixed;\n }" ]
[ "public static base_response sync(nitro_service client, gslbconfig resource) throws Exception {\n\t\tgslbconfig syncresource = new gslbconfig();\n\t\tsyncresource.preview = resource.preview;\n\t\tsyncresource.debug = resource.debug;\n\t\tsyncresource.forcesync = resource.forcesync;\n\t\tsyncresource.nowarn = resource.nowarn;\n\t\tsyncresource.saveconfig = resource.saveconfig;\n\t\tsyncresource.command = resource.command;\n\t\treturn syncresource.perform_operation(client,\"sync\");\n\t}", "public String getStatement()\r\n {\r\n if(sql == null)\r\n {\r\n StringBuffer stmt = new StringBuffer(128);\r\n ClassDescriptor cld = getClassDescriptor();\r\n\r\n FieldDescriptor[] fieldDescriptors = cld.getPkFields();\r\n if(fieldDescriptors == null || fieldDescriptors.length == 0)\r\n {\r\n throw new OJBRuntimeException(\"No PK fields defined in metadata for \" + cld.getClassNameOfObject());\r\n }\r\n FieldDescriptor field = fieldDescriptors[0];\r\n\r\n stmt.append(SELECT);\r\n stmt.append(field.getColumnName());\r\n stmt.append(FROM);\r\n stmt.append(cld.getFullTableName());\r\n appendWhereClause(cld, false, stmt);\r\n\r\n sql = stmt.toString();\r\n }\r\n return sql;\r\n }", "public static final Rate parseRate(BigDecimal value)\n {\n Rate result = null;\n\n if (value != null)\n {\n result = new Rate(value, TimeUnit.HOURS);\n }\n\n return (result);\n }", "public long removeRangeByScore(final ScoreRange scoreRange) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.zremrangeByScore(getKey(), scoreRange.from(), scoreRange.to());\n }\n });\n }", "public void setWeeklyDay(Day day, boolean value)\n {\n if (value)\n {\n m_days.add(day);\n }\n else\n {\n m_days.remove(day);\n }\n }", "public static Type boxedType(Type type) {\n if (type instanceof Class<?>) {\n return boxedClass((Class<?>) type);\n } else {\n return type;\n }\n }", "private MapRow getRow(int index)\n {\n MapRow result;\n\n if (index == m_rows.size())\n {\n result = new MapRow(this, new HashMap<FastTrackField, Object>());\n m_rows.add(result);\n }\n else\n {\n result = m_rows.get(index);\n }\n\n return result;\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 void addDefaultCalendarHours(Day day)\n {\n ProjectCalendarHours hours = addCalendarHours(day);\n\n if (day != Day.SATURDAY && day != Day.SUNDAY)\n {\n hours.addRange(DEFAULT_WORKING_MORNING);\n hours.addRange(DEFAULT_WORKING_AFTERNOON);\n }\n }" ]
Initializes the queue that tracks the next set of nodes with no dependencies or whose dependencies are resolved.
[ "private void initializeQueue() {\n this.queue.clear();\n for (Map.Entry<String, NodeT> entry: nodeTable.entrySet()) {\n if (!entry.getValue().hasDependencies()) {\n this.queue.add(entry.getKey());\n }\n }\n if (queue.isEmpty()) {\n throw new IllegalStateException(\"Detected circular dependency\");\n }\n }" ]
[ "public void writeFinalResults() {\n\t\tprintStatus();\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers\n\t\t\t\t\t\t.openExampleFileOuputStream(\"life-expectancies.csv\"))) {\n\n\t\t\tfor (int i = 0; i < lifeSpans.length; i++) {\n\t\t\t\tif (peopleCount[i] != 0) {\n\t\t\t\t\tout.println(i + \",\" + (double) lifeSpans[i]\n\t\t\t\t\t\t\t/ peopleCount[i] + \",\" + peopleCount[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "protected void captureCenterEye(GVRRenderTarget renderTarget, boolean isMultiview) {\n if (mScreenshotCenterCallback == null) {\n return;\n }\n\n // TODO: when we will use multithreading, create new camera using centercamera as we are adding posteffects into it\n final GVRCamera centerCamera = mMainScene.getMainCameraRig().getCenterCamera();\n final GVRMaterial postEffect = new GVRMaterial(this, GVRMaterial.GVRShaderType.VerticalFlip.ID);\n\n centerCamera.addPostEffect(postEffect);\n\n GVRRenderTexture posteffectRenderTextureB = null;\n GVRRenderTexture posteffectRenderTextureA = null;\n\n if(isMultiview) {\n posteffectRenderTextureA = mRenderBundle.getEyeCapturePostEffectRenderTextureA();\n posteffectRenderTextureB = mRenderBundle.getEyeCapturePostEffectRenderTextureB();\n renderTarget = mRenderBundle.getEyeCaptureRenderTarget();\n renderTarget.cullFromCamera(mMainScene, centerCamera ,mRenderBundle.getShaderManager());\n renderTarget.beginRendering(centerCamera);\n }\n else {\n posteffectRenderTextureA = mRenderBundle.getPostEffectRenderTextureA();\n posteffectRenderTextureB = mRenderBundle.getPostEffectRenderTextureB();\n }\n\n renderTarget.render(mMainScene,centerCamera, mRenderBundle.getShaderManager(), posteffectRenderTextureA, posteffectRenderTextureB);\n centerCamera.removePostEffect(postEffect);\n readRenderResult(renderTarget, EYE.MULTIVIEW, false);\n\n if(isMultiview)\n renderTarget.endRendering();\n\n final Bitmap bitmap = Bitmap.createBitmap(mReadbackBufferWidth, mReadbackBufferHeight, Bitmap.Config.ARGB_8888);\n mReadbackBuffer.rewind();\n bitmap.copyPixelsFromBuffer(mReadbackBuffer);\n final GVRScreenshotCallback callback = mScreenshotCenterCallback;\n Threads.spawn(new Runnable() {\n public void run() {\n callback.onScreenCaptured(bitmap);\n }\n });\n\n mScreenshotCenterCallback = null;\n }", "private String filterTag(String tag) {\r\n\t AttributeValues answerAV = TagSet.getTagSet().fromTag(tag);\r\n\t answerAV.removeNonlexicalAttributes();\r\n\t return TagSet.getTagSet().toTag(answerAV);\r\n }", "public List<NodeValue<K, V>> getRepairs(List<NodeValue<K, V>> nodeValues) {\n int size = nodeValues.size();\n if(size <= 1)\n return Collections.emptyList();\n\n Map<K, List<NodeValue<K, V>>> keyToNodeValues = Maps.newHashMap();\n for(NodeValue<K, V> nodeValue: nodeValues) {\n List<NodeValue<K, V>> keyNodeValues = keyToNodeValues.get(nodeValue.getKey());\n if(keyNodeValues == null) {\n keyNodeValues = Lists.newArrayListWithCapacity(5);\n keyToNodeValues.put(nodeValue.getKey(), keyNodeValues);\n }\n keyNodeValues.add(nodeValue);\n }\n\n List<NodeValue<K, V>> result = Lists.newArrayList();\n for(List<NodeValue<K, V>> keyNodeValues: keyToNodeValues.values())\n result.addAll(singleKeyGetRepairs(keyNodeValues));\n return result;\n }", "public static <T> String extractTableName(DatabaseType databaseType, Class<T> clazz) {\n\t\tDatabaseTable databaseTable = clazz.getAnnotation(DatabaseTable.class);\n\t\tString name = null;\n\t\tif (databaseTable != null && databaseTable.tableName() != null && databaseTable.tableName().length() > 0) {\n\t\t\tname = databaseTable.tableName();\n\t\t}\n\t\tif (name == null && javaxPersistenceConfigurer != null) {\n\t\t\tname = javaxPersistenceConfigurer.getEntityName(clazz);\n\t\t}\n\t\tif (name == null) {\n\t\t\t// if the name isn't specified, it is the class name lowercased\n\t\t\tif (databaseType == null) {\n\t\t\t\t// database-type is optional so if it is not specified we just use english\n\t\t\t\tname = clazz.getSimpleName().toLowerCase(Locale.ENGLISH);\n\t\t\t} else {\n\t\t\t\tname = databaseType.downCaseString(clazz.getSimpleName(), true);\n\t\t\t}\n\t\t}\n\t\treturn name;\n\t}", "private void ensureReferencedPKs(ModelDef modelDef, CollectionDescriptorDef collDef) throws ConstraintException\r\n {\r\n String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);\r\n ClassDescriptorDef elementClassDef = modelDef.getClass(elementClassName);\r\n String indirTable = collDef.getProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE);\r\n String localKey = collDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);\r\n String remoteKey = collDef.getProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY);\r\n boolean hasRemoteKey = remoteKey != null;\r\n ArrayList fittingCollections = new ArrayList();\r\n\r\n // we're checking for the fitting remote collection(s) and also\r\n // use their foreignkey as remote-foreignkey in the original collection definition\r\n for (Iterator it = elementClassDef.getAllExtentClasses(); it.hasNext();)\r\n {\r\n ClassDescriptorDef subTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n // find the collection in the element class that has the same indirection table\r\n for (Iterator collIt = subTypeDef.getCollections(); collIt.hasNext();)\r\n {\r\n CollectionDescriptorDef curCollDef = (CollectionDescriptorDef)collIt.next();\r\n\r\n if (indirTable.equals(curCollDef.getProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE)) &&\r\n (collDef != curCollDef) &&\r\n (!hasRemoteKey || CommaListIterator.sameLists(remoteKey, curCollDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY))) &&\r\n (!curCollDef.hasProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY) ||\r\n CommaListIterator.sameLists(localKey, curCollDef.getProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY))))\r\n {\r\n fittingCollections.add(curCollDef);\r\n }\r\n }\r\n }\r\n if (!fittingCollections.isEmpty())\r\n {\r\n // if there is more than one, check that they match, i.e. that they all have the same foreignkeys\r\n if (!hasRemoteKey && (fittingCollections.size() > 1))\r\n {\r\n CollectionDescriptorDef firstCollDef = (CollectionDescriptorDef)fittingCollections.get(0);\r\n String foreignKey = firstCollDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);\r\n\r\n for (int idx = 1; idx < fittingCollections.size(); idx++)\r\n {\r\n CollectionDescriptorDef curCollDef = (CollectionDescriptorDef)fittingCollections.get(idx);\r\n\r\n if (!CommaListIterator.sameLists(foreignKey, curCollDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY)))\r\n {\r\n throw new ConstraintException(\"Cannot determine the element-side collection that corresponds to the collection \"+\r\n collDef.getName()+\" in type \"+collDef.getOwner().getName()+\r\n \" because there are at least two different collections that would fit.\"+\r\n \" Specifying remote-foreignkey in the original collection \"+collDef.getName()+\r\n \" will perhaps help\");\r\n }\r\n }\r\n // store the found keys at the collections\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY, foreignKey);\r\n for (int idx = 0; idx < fittingCollections.size(); idx++)\r\n {\r\n CollectionDescriptorDef curCollDef = (CollectionDescriptorDef)fittingCollections.get(idx);\r\n\r\n curCollDef.setProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY, localKey);\r\n }\r\n }\r\n }\r\n\r\n // copy subclass pk fields into target class (if not already present)\r\n ensurePKsFromHierarchy(elementClassDef);\r\n }", "public ModelNode buildRequest() throws OperationFormatException {\n\n ModelNode address = request.get(Util.ADDRESS);\n if(prefix.isEmpty()) {\n address.setEmptyList();\n } else {\n Iterator<Node> iterator = prefix.iterator();\n while (iterator.hasNext()) {\n OperationRequestAddress.Node node = iterator.next();\n if (node.getName() != null) {\n address.add(node.getType(), node.getName());\n } else if (iterator.hasNext()) {\n throw new OperationFormatException(\n \"The node name is not specified for type '\"\n + node.getType() + \"'\");\n }\n }\n }\n\n if(!request.hasDefined(Util.OPERATION)) {\n throw new OperationFormatException(\"The operation name is missing or the format of the operation request is wrong.\");\n }\n\n return request;\n }", "private void writeDoubleField(String fieldName, Object value) throws IOException\n {\n double val = ((Number) value).doubleValue();\n if (val != 0)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }", "private void initializeSignProperties() {\n if (!signPackage && !signChanges) {\n return;\n }\n\n if (key != null && keyring != null && passphrase != null) {\n return;\n }\n\n Map<String, String> properties =\n readPropertiesFromActiveProfiles(signCfgPrefix, KEY, KEYRING, PASSPHRASE);\n\n key = lookupIfEmpty(key, properties, KEY);\n keyring = lookupIfEmpty(keyring, properties, KEYRING);\n passphrase = decrypt(lookupIfEmpty(passphrase, properties, PASSPHRASE));\n\n if (keyring == null) {\n try {\n keyring = Utils.guessKeyRingFile().getAbsolutePath();\n console.info(\"Located keyring at \" + keyring);\n } catch (FileNotFoundException e) {\n console.warn(e.getMessage());\n }\n }\n }" ]
Populates data in this Options from the character stream. @param in The Reader @throws IOException If there is a problem reading data
[ "public void readData(BufferedReader in) throws IOException {\r\n String line, value;\r\n // skip old variables if still present\r\n lexOptions.readData(in);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n try {\r\n tlpParams = (TreebankLangParserParams) Class.forName(value).newInstance();\r\n } catch (Exception e) {\r\n IOException ioe = new IOException(\"Problem instantiating parserParams: \" + line);\r\n ioe.initCause(e);\r\n throw ioe;\r\n }\r\n line = in.readLine();\r\n // ensure backwards compatibility\r\n if (line.matches(\"^forceCNF.*\")) {\r\n value = line.substring(line.indexOf(' ') + 1);\r\n forceCNF = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n }\r\n value = line.substring(line.indexOf(' ') + 1);\r\n doPCFG = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n doDep = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n freeDependencies = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n directional = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n genStop = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n distance = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n coarseDistance = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n dcTags = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n if ( ! line.matches(\"^nPrune.*\")) {\r\n throw new RuntimeException(\"Expected nPrune, found: \" + line);\r\n }\r\n value = line.substring(line.indexOf(' ') + 1);\r\n nodePrune = Boolean.parseBoolean(value);\r\n line = in.readLine(); // get rid of last line\r\n if (line.length() != 0) {\r\n throw new RuntimeException(\"Expected blank line, found: \" + line);\r\n }\r\n }" ]
[ "AlbumArt getArtwork(int artworkId, SlotReference slot, CdjStatus.TrackType trackType, Client client)\n throws IOException {\n\n // Send the artwork request\n Message response = client.simpleRequest(Message.KnownType.ALBUM_ART_REQ, Message.KnownType.ALBUM_ART,\n client.buildRMST(Message.MenuIdentifier.DATA, slot.slot, trackType), new NumberField((long)artworkId));\n\n // Create an image from the response bytes\n return new AlbumArt(new DataReference(slot, artworkId), ((BinaryField)response.arguments.get(3)).getValue());\n }", "public Day getDayOfWeek()\n {\n Day result = null;\n if (!m_days.isEmpty())\n {\n result = m_days.iterator().next();\n }\n return result;\n }", "@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/{clientUUID}\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @PathVariable(\"clientUUID\") String clientUUID) throws Exception {\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"client\", clientService.findClient(clientUUID, profileId));\n return valueHash;\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 }", "void reset()\n {\n if (!hasStopped)\n {\n throw new IllegalStateException(\"cannot reset a non stopped queue poller\");\n }\n hasStopped = false;\n run = true;\n lastLoop = null;\n loop = new Semaphore(0);\n }", "public void buttonClick(View v) {\n switch (v.getId()) {\n case R.id.show:\n showAppMsg();\n break;\n case R.id.cancel_all:\n AppMsg.cancelAll(this);\n break;\n default:\n return;\n }\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 void setSelectionType(MaterialDatePickerType selectionType) {\n this.selectionType = selectionType;\n switch (selectionType) {\n case MONTH_DAY:\n options.selectMonths = true;\n break;\n case YEAR_MONTH_DAY:\n options.selectYears = yearsToDisplay;\n options.selectMonths = true;\n break;\n case YEAR:\n options.selectYears = yearsToDisplay;\n options.selectMonths = false;\n break;\n }\n }", "private List<Row> buildRowHierarchy(List<Row> bars, List<Row> expandedTasks, List<Row> tasks, List<Row> milestones)\n {\n //\n // Create a list of leaf nodes by merging the task and milestone lists\n //\n List<Row> leaves = new ArrayList<Row>();\n leaves.addAll(tasks);\n leaves.addAll(milestones);\n\n //\n // Sort the bars and the leaves\n //\n Collections.sort(bars, BAR_COMPARATOR);\n Collections.sort(leaves, LEAF_COMPARATOR);\n\n //\n // Map bar IDs to bars\n //\n Map<Integer, Row> barIdToBarMap = new HashMap<Integer, Row>();\n for (Row bar : bars)\n {\n barIdToBarMap.put(bar.getInteger(\"BARID\"), bar);\n }\n\n //\n // Merge expanded task attributes with parent bars\n // and create an expanded task ID to bar map.\n //\n Map<Integer, Row> expandedTaskIdToBarMap = new HashMap<Integer, Row>();\n for (Row expandedTask : expandedTasks)\n {\n Row bar = barIdToBarMap.get(expandedTask.getInteger(\"BAR\"));\n bar.merge(expandedTask, \"_\");\n Integer expandedTaskID = bar.getInteger(\"_EXPANDED_TASKID\");\n expandedTaskIdToBarMap.put(expandedTaskID, bar);\n }\n\n //\n // Build the hierarchy\n //\n List<Row> parentBars = new ArrayList<Row>();\n for (Row bar : bars)\n {\n Integer expandedTaskID = bar.getInteger(\"EXPANDED_TASK\");\n Row parentBar = expandedTaskIdToBarMap.get(expandedTaskID);\n if (parentBar == null)\n {\n parentBars.add(bar);\n }\n else\n {\n parentBar.addChild(bar);\n }\n }\n\n //\n // Attach the leaves\n //\n for (Row leaf : leaves)\n {\n Integer barID = leaf.getInteger(\"BAR\");\n Row bar = barIdToBarMap.get(barID);\n bar.addChild(leaf);\n }\n\n //\n // Prune any \"displaced items\" from the top level.\n // We're using a heuristic here as this is the only thing I\n // can see which differs between bars that we want to include\n // and bars that we want to exclude.\n //\n Iterator<Row> iter = parentBars.iterator();\n while (iter.hasNext())\n {\n Row bar = iter.next();\n String barName = bar.getString(\"NAMH\");\n if (barName == null || barName.isEmpty() || barName.equals(\"Displaced Items\"))\n {\n iter.remove();\n }\n }\n\n //\n // If we only have a single top level node (effectively a summary task) prune that too.\n //\n if (parentBars.size() == 1)\n {\n parentBars = parentBars.get(0).getChildRows();\n }\n\n return parentBars;\n }" ]
This method extracts project properties from a Planner file. @param project Root node of the Planner file
[ "private void readProjectProperties(Project project) throws MPXJException\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n\n properties.setCompany(project.getCompany());\n properties.setManager(project.getManager());\n properties.setName(project.getName());\n properties.setStartDate(getDateTime(project.getProjectStart()));\n }" ]
[ "protected int countedSize() throws PersistenceBrokerException\r\n {\r\n Query countQuery = getBroker().serviceBrokerHelper().getCountQuery(getQueryObject().getQuery());\r\n ResultSetAndStatement rsStmt;\r\n ClassDescriptor cld = getQueryObject().getClassDescriptor();\r\n int count = 0;\r\n\r\n // BRJ: do not use broker.getCount() because it's extent-aware\r\n // the count we need here must not include extents !\r\n if (countQuery instanceof QueryBySQL)\r\n {\r\n String countSql = ((QueryBySQL) countQuery).getSql();\r\n rsStmt = getBroker().serviceJdbcAccess().executeSQL(countSql, cld, Query.NOT_SCROLLABLE);\r\n }\r\n else\r\n {\r\n rsStmt = getBroker().serviceJdbcAccess().executeQuery(countQuery, cld);\r\n }\r\n\r\n try\r\n {\r\n if (rsStmt.m_rs.next())\r\n {\r\n count = rsStmt.m_rs.getInt(1);\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerException(e);\r\n }\r\n finally\r\n {\r\n rsStmt.close();\r\n }\r\n\r\n return count;\r\n }", "public String getKeyValue(String key){\n String keyName = keysMap.get(key);\n if (keyName != null){\n return keyName;\n }\n return \"\"; //key wasn't defined in keys properties file\n }", "@Override\n public final float getFloat(final String key) {\n Float result = optFloat(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }", "public final int getJdbcType()\r\n {\r\n switch (this.fieldSource)\r\n {\r\n case SOURCE_FIELD :\r\n return this.getFieldRef().getJdbcType().getType();\r\n case SOURCE_NULL :\r\n return java.sql.Types.NULL;\r\n case SOURCE_VALUE :\r\n return java.sql.Types.VARCHAR;\r\n default :\r\n return java.sql.Types.NULL;\r\n }\r\n }", "public static void startNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tgetNamedTimer(timerName, todoFlags, threadId).start();\n\t}", "public static String packageNameOf(Class<?> clazz) {\n String name = clazz.getName();\n int pos = name.lastIndexOf('.');\n E.unexpectedIf(pos < 0, \"Class does not have package: \" + name);\n return name.substring(0, pos);\n }", "public void set( int row , int col , double real , double imaginary ) {\n if( imaginary == 0 ) {\n set(row,col,real);\n } else {\n ops.set(mat,row,col, real, imaginary);\n }\n }", "public Result cmd(String cliCommand) {\n try {\n // The intent here is to return a Response when this is doable.\n if (ctx.isWorkflowMode() || ctx.isBatchMode()) {\n ctx.handle(cliCommand);\n return new Result(cliCommand, ctx.getExitCode());\n }\n handler.parse(ctx.getCurrentNodePath(), cliCommand, ctx);\n if (handler.getFormat() == OperationFormat.INSTANCE) {\n ModelNode request = ctx.buildRequest(cliCommand);\n ModelNode response = ctx.execute(request, cliCommand);\n return new Result(cliCommand, request, response);\n } else {\n ctx.handle(cliCommand);\n return new Result(cliCommand, ctx.getExitCode());\n }\n } catch (CommandLineException cfe) {\n throw new IllegalArgumentException(\"Error handling command: \"\n + cliCommand, cfe);\n } catch (IOException ioe) {\n throw new IllegalStateException(\"Unable to send command \"\n + cliCommand + \" to server.\", ioe);\n }\n }", "public static <E> List<E> listify(ObjectMapper mapper, Object source, Class<E> targetElementType) {\n return (List<E>) collectify(mapper, source, List.class, targetElementType);\n }" ]
Perform construction. @param callbackHandler
[ "private void initialize(Handler callbackHandler) {\n\t\tint processors = Runtime.getRuntime().availableProcessors();\n\t\tmDownloadDispatchers = new DownloadDispatcher[processors];\n\t\tmDelivery = new CallBackDelivery(callbackHandler);\n\t}" ]
[ "public void clipTile(InternalTile tile, double scale, Coordinate panOrigin) throws GeomajasException {\n\t\tlog.debug(\"clipTile before {}\", tile);\n\t\tList<InternalFeature> orgFeatures = tile.getFeatures();\n\t\ttile.setFeatures(new ArrayList<InternalFeature>());\n\t\tGeometry maxScreenBbox = null; // The tile's maximum bounds in screen space. Used for clipping.\n\t\tfor (InternalFeature feature : orgFeatures) {\n\t\t\t// clip feature if necessary\n\t\t\tif (exceedsScreenDimensions(feature, scale)) {\n\t\t\t\tlog.debug(\"feature {} exceeds screen dimensions\", feature);\n\t\t\t\tInternalFeatureImpl vectorFeature = (InternalFeatureImpl) feature.clone();\n\t\t\t\ttile.setClipped(true);\n\t\t\t\tvectorFeature.setClipped(true);\n\t\t\t\tif (null == maxScreenBbox) {\n\t\t\t\t\tmaxScreenBbox = JTS.toGeometry(getMaxScreenEnvelope(tile, panOrigin));\n\t\t\t\t}\n\t\t\t\tGeometry clipped = maxScreenBbox.intersection(feature.getGeometry());\n\t\t\t\tvectorFeature.setClippedGeometry(clipped);\n\t\t\t\ttile.addFeature(vectorFeature);\n\t\t\t} else {\n\t\t\t\ttile.addFeature(feature);\n\t\t\t}\n\t\t}\n\t\tlog.debug(\"clipTile after {}\", tile);\n\t}", "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 }", "public int consume(Map<String, String> initialVars) {\r\n this.dataPipe = new DataPipe(this);\n\r\n // Set initial variables\r\n for (Map.Entry<String, String> ent : initialVars.entrySet()) {\r\n dataPipe.getDataMap().put(ent.getKey(), ent.getValue());\r\n }\n\r\n // Call transformers\r\n for (DataTransformer dc : dataTransformers) {\r\n dc.transform(dataPipe);\r\n }\n\r\n // Call writers\r\n for (DataWriter oneOw : dataWriters) {\r\n try {\r\n oneOw.writeOutput(dataPipe);\r\n } catch (Exception e) { //NOPMD\r\n log.error(\"Exception in DataWriter\", e);\r\n }\r\n }\n\r\n return 1;\r\n }", "protected BufferedImage fetchImage(\n @Nonnull final ClientHttpRequest request, @Nonnull final MapfishMapContext transformer)\n throws IOException {\n final String baseMetricName = getClass().getName() + \".read.\" +\n StatsUtils.quotePart(request.getURI().getHost());\n final Timer.Context timerDownload = this.registry.timer(baseMetricName).time();\n try (ClientHttpResponse httpResponse = request.execute()) {\n if (httpResponse.getStatusCode() != HttpStatus.OK) {\n final String message = String.format(\n \"Invalid status code for %s (%d!=%d). The response was: '%s'\",\n request.getURI(), httpResponse.getStatusCode().value(),\n HttpStatus.OK.value(), httpResponse.getStatusText());\n this.registry.counter(baseMetricName + \".error\").inc();\n if (getFailOnError()) {\n throw new RuntimeException(message);\n } else {\n LOGGER.info(message);\n return createErrorImage(transformer.getPaintArea());\n }\n }\n\n final List<String> contentType = httpResponse.getHeaders().get(\"Content-Type\");\n if (contentType == null || contentType.size() != 1) {\n LOGGER.debug(\"The image {} didn't return a valid content type header.\",\n request.getURI());\n } else if (!contentType.get(0).startsWith(\"image/\")) {\n final byte[] data;\n try (InputStream body = httpResponse.getBody()) {\n data = IOUtils.toByteArray(body);\n }\n LOGGER.debug(\"We get a wrong image for {}, content type: {}\\nresult:\\n{}\",\n request.getURI(), contentType.get(0),\n new String(data, StandardCharsets.UTF_8));\n this.registry.counter(baseMetricName + \".error\").inc();\n return createErrorImage(transformer.getPaintArea());\n }\n\n final BufferedImage image = ImageIO.read(httpResponse.getBody());\n if (image == null) {\n LOGGER.warn(\"Cannot read image from %a\", request.getURI());\n this.registry.counter(baseMetricName + \".error\").inc();\n if (getFailOnError()) {\n throw new RuntimeException(\"Cannot read image from \" + request.getURI());\n } else {\n return createErrorImage(transformer.getPaintArea());\n }\n }\n timerDownload.stop();\n return image;\n } catch (Throwable e) {\n this.registry.counter(baseMetricName + \".error\").inc();\n throw e;\n }\n }", "public static DMatrixRMaj symmetricWithEigenvalues(int num, Random rand , double ...eigenvalues ) {\n DMatrixRMaj V = RandomMatrices_DDRM.orthogonal(num,num,rand);\n DMatrixRMaj D = CommonOps_DDRM.diag(eigenvalues);\n\n DMatrixRMaj temp = new DMatrixRMaj(num,num);\n\n CommonOps_DDRM.mult(V,D,temp);\n CommonOps_DDRM.multTransB(temp,V,D);\n\n return D;\n }", "public static dnsview_binding get(nitro_service service, String viewname) throws Exception{\n\t\tdnsview_binding obj = new dnsview_binding();\n\t\tobj.set_viewname(viewname);\n\t\tdnsview_binding response = (dnsview_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public final static String process(final File file, final Configuration configuration) throws IOException\n {\n final FileInputStream input = new FileInputStream(file);\n final String ret = process(input, configuration);\n input.close();\n return ret;\n }", "@Override\n protected <T> CompletableFuture<T> doExecute(Command<T> command) throws Exception {\n final CompletableFuture<T> future = new CompletableFuture<>();\n executor.execute(() -> {\n try {\n future.complete(blockingExecute(command));\n } catch (Throwable t) {\n future.completeExceptionally(t);\n }\n });\n return future;\n }", "@RequestMapping(value = \"api/edit/server\", method = RequestMethod.POST)\n public\n @ResponseBody\n ServerRedirect addRedirectToProfile(Model model,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier,\n @RequestParam(value = \"srcUrl\", required = true) String srcUrl,\n @RequestParam(value = \"destUrl\", required = true) String destUrl,\n @RequestParam(value = \"clientUUID\", required = true) String clientUUID,\n @RequestParam(value = \"hostHeader\", required = false) String hostHeader) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n\n int clientId = ClientService.getInstance().findClient(clientUUID, profileId).getId();\n\n int redirectId = ServerRedirectService.getInstance().addServerRedirectToProfile(\"\", srcUrl, destUrl, hostHeader,\n profileId, clientId);\n return ServerRedirectService.getInstance().getRedirect(redirectId);\n }" ]
Print an extended attribute date value. @param value date value @return string representation
[ "public static final String printExtendedAttributeDate(Date value)\n {\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }" ]
[ "public static Constructor<?> getConstructor(final Class<?> clazz,\n final Class<?>... argumentTypes) throws NoSuchMethodException {\n try {\n return AccessController\n .doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {\n public Constructor<?> run()\n throws NoSuchMethodException {\n return clazz.getConstructor(argumentTypes);\n }\n });\n }\n // Unwrap\n catch (final PrivilegedActionException pae) {\n final Throwable t = pae.getCause();\n // Rethrow\n if (t instanceof NoSuchMethodException) {\n throw (NoSuchMethodException) t;\n } else {\n // No other checked Exception thrown by Class.getConstructor\n try {\n throw (RuntimeException) t;\n }\n // Just in case we've really messed up\n catch (final ClassCastException cce) {\n throw new RuntimeException(\n \"Obtained unchecked Exception; this code should never be reached\",\n t);\n }\n }\n }\n }", "public Integer getTextureMagFilter(AiTextureType type, int index) {\n checkTexRange(type, index);\n\n Property p = getProperty(PropertyKey.TEX_MAG_FILTER.m_key);\n\n if (null == p || null == p.getData()) {\n return (Integer) m_defaults.get(PropertyKey.TEX_MAG_FILTER);\n }\n Object rawValue = p.getData();\n if (rawValue instanceof java.nio.ByteBuffer)\n {\n java.nio.IntBuffer ibuf = ((java.nio.ByteBuffer) rawValue).asIntBuffer();\n return ibuf.get();\n }\n else\n {\n return (Integer) rawValue;\n }\n }", "public static <T> Set<T> asImmutable(Set<? extends T> self) {\n return Collections.unmodifiableSet(self);\n }", "private boolean isSatisfied() {\n if(pipelineData.getZonesRequired() != null) {\n return ((pipelineData.getSuccesses() >= required) && (pipelineData.getZoneResponses()\n .size() >= (pipelineData.getZonesRequired() + 1)));\n } else {\n return pipelineData.getSuccesses() >= required;\n }\n }", "public static String getOffsetCodeFromCurveName(String curveName) {\r\n\t\tif(curveName == null || curveName.length() == 0) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tString[] splits = curveName.split(\"(?<=\\\\D)(?=\\\\d)\");\r\n\t\tString offsetCode = splits[splits.length-1];\r\n\t\tif(!Character.isDigit(offsetCode.charAt(0))) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\toffsetCode = offsetCode.split(\"(?<=[A-Za-z])(?=.)\", 2)[0];\r\n\t\toffsetCode = offsetCode.replaceAll( \"[\\\\W_]\", \"\" );\r\n\t\treturn offsetCode;\r\n\t}", "private void doSend(byte[] msg, boolean wait, KNXAddress dst)\r\n\t\tthrows KNXAckTimeoutException, KNXLinkClosedException\r\n\t{\r\n\t\tif (closed)\r\n\t\t\tthrow new KNXLinkClosedException(\"link closed\");\r\n\t\ttry {\r\n\t\t\tlogger.info(\"send message to \" + dst + (wait ? \", wait for ack\" : \"\"));\r\n\t\t\tlogger.trace(\"EMI \" + DataUnitBuilder.toHex(msg, \" \"));\r\n\t\t\tconn.send(msg, wait);\r\n\t\t\tlogger.trace(\"send to \" + dst + \" succeeded\");\r\n\t\t}\r\n\t\tcatch (final KNXPortClosedException e) {\r\n\t\t\tlogger.error(\"send error, closing link\", e);\r\n\t\t\tclose();\r\n\t\t\tthrow new KNXLinkClosedException(\"link closed, \" + e.getMessage());\r\n\t\t}\r\n\t}", "private <T> RequestBuilder doPrepareRequestBuilderImpl(\n ResponseReader responseReader, String methodName, RpcStatsContext statsContext,\n String requestData, AsyncCallback<T> callback) {\n\n if (getServiceEntryPoint() == null) {\n throw new NoServiceEntryPointSpecifiedException();\n }\n\n RequestCallback responseHandler = doCreateRequestCallback(responseReader,\n methodName, statsContext, callback);\n\n ensureRpcRequestBuilder();\n\n rpcRequestBuilder.create(getServiceEntryPoint());\n rpcRequestBuilder.setCallback(responseHandler);\n \n // changed code\n rpcRequestBuilder.setSync(isSync(methodName));\n // changed code\n \n rpcRequestBuilder.setContentType(RPC_CONTENT_TYPE);\n rpcRequestBuilder.setRequestData(requestData);\n rpcRequestBuilder.setRequestId(statsContext.getRequestId());\n return rpcRequestBuilder.finish();\n }", "public static String replaceFullRequestContent(\n String requestContentTemplate, String replacementString) {\n return (requestContentTemplate.replace(\n PcConstants.COMMAND_VAR_DEFAULT_REQUEST_CONTENT,\n replacementString));\n }", "public static PackageNameMappingWithPackagePattern fromPackage(String packagePattern)\n {\n PackageNameMapping packageNameMapping = new PackageNameMapping();\n packageNameMapping.setPackagePattern(packagePattern);\n return packageNameMapping;\n }" ]
Computes the blend weights for the given time and updates them in the target.
[ "public void animate(GVRHybridObject object, float animationTime)\n {\n GVRMeshMorph morph = (GVRMeshMorph) mTarget;\n\n mKeyInterpolator.animate(animationTime * mDuration, mCurrentValues);\n morph.setWeights(mCurrentValues);\n\n }" ]
[ "private void readResourceAssignment(Allocation gpAllocation)\n {\n Integer taskID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getTaskId()) + 1);\n Integer resourceID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getResourceId()) + 1);\n Task task = m_projectFile.getTaskByUniqueID(taskID);\n Resource resource = m_projectFile.getResourceByUniqueID(resourceID);\n if (task != null && resource != null)\n {\n ResourceAssignment mpxjAssignment = task.addResourceAssignment(resource);\n mpxjAssignment.setUnits(gpAllocation.getLoad());\n m_eventManager.fireAssignmentReadEvent(mpxjAssignment);\n }\n }", "protected void setBandsFinalHeight() {\n log.debug(\"Setting bands final height...\");\n\n List<JRBand> bands = new ArrayList<JRBand>();\n\n Utils.addNotNull(bands, design.getPageHeader());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getColumnHeader());\n Utils.addNotNull(bands, design.getColumnFooter());\n Utils.addNotNull(bands, design.getSummary());\n Utils.addNotNull(bands, design.getBackground());\n bands.addAll(((JRDesignSection) design.getDetailSection()).getBandsList());\n Utils.addNotNull(bands, design.getLastPageFooter());\n Utils.addNotNull(bands, design.getTitle());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getNoData());\n\n for (JRGroup jrgroup : design.getGroupsList()) {\n DJGroup djGroup = (DJGroup) getReferencesMap().get(jrgroup.getName());\n JRDesignSection headerSection = (JRDesignSection) jrgroup.getGroupHeaderSection();\n JRDesignSection footerSection = (JRDesignSection) jrgroup.getGroupFooterSection();\n if (djGroup != null) {\n for (JRBand headerBand : headerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) headerBand, djGroup.getHeaderHeight(), djGroup.isFitHeaderHeightToContent());\n\n }\n for (JRBand footerBand : footerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) footerBand, djGroup.getFooterHeight(), djGroup.isFitFooterHeightToContent());\n\n }\n } else {\n bands.addAll(headerSection.getBandsList());\n bands.addAll(footerSection.getBandsList());\n }\n }\n\n for (JRBand jrDesignBand : bands) {\n setBandFinalHeight((JRDesignBand) jrDesignBand);\n }\n }", "public static void validateInterimFinalCluster(final Cluster interimCluster,\n final Cluster finalCluster) {\n validateClusterPartitionCounts(interimCluster, finalCluster);\n validateClusterZonesSame(interimCluster, finalCluster);\n validateClusterNodeCounts(interimCluster, finalCluster);\n validateClusterNodeState(interimCluster, finalCluster);\n return;\n }", "private long interpolateTimeFromUpdate(TrackPositionUpdate lastTrackUpdate, CdjStatus newDeviceUpdate,\n BeatGrid beatGrid) {\n final int beatNumber = newDeviceUpdate.getBeatNumber();\n final boolean noLongerPlaying = !newDeviceUpdate.isPlaying();\n\n // If we have just stopped, see if we are near a cue (assuming that information is available), and if so,\n // the best assumption is that the DJ jumped to that cue.\n if (lastTrackUpdate.playing && noLongerPlaying) {\n final CueList.Entry jumpedTo = findAdjacentCue(newDeviceUpdate, beatGrid);\n if (jumpedTo != null) return jumpedTo.cueTime;\n }\n\n // Handle the special case where we were not playing either in the previous or current update, but the DJ\n // might have jumped to a different place in the track.\n if (!lastTrackUpdate.playing) {\n if (lastTrackUpdate.beatNumber == beatNumber && noLongerPlaying) { // Haven't moved\n return lastTrackUpdate.milliseconds;\n } else {\n if (noLongerPlaying) { // Have jumped without playing.\n if (beatNumber < 0) {\n return -1; // We don't know the position any more; weird to get into this state and still have a grid?\n }\n // As a heuristic, assume we are right before the beat?\n return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);\n }\n }\n }\n\n // One way or another, we are now playing.\n long elapsedMillis = (newDeviceUpdate.getTimestamp() - lastTrackUpdate.timestamp) / 1000000;\n long moved = Math.round(lastTrackUpdate.pitch * elapsedMillis);\n long interpolated = (lastTrackUpdate.reverse)?\n (lastTrackUpdate.milliseconds - moved) : lastTrackUpdate.milliseconds + moved;\n if (Math.abs(beatGrid.findBeatAtTime(interpolated) - beatNumber) < 2) {\n return interpolated; // Our calculations still look plausible\n }\n // The player has jumped or drifted somewhere unexpected, correct.\n if (newDeviceUpdate.isPlayingForwards()) {\n return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);\n } else {\n return beatGrid.getTimeWithinTrack(Math.min(beatNumber + 1, beatGrid.beatCount));\n }\n }", "public static long count(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_bridgegroup_binding obj = new nstrafficdomain_bridgegroup_binding();\n\t\tobj.set_td(td);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tnstrafficdomain_bridgegroup_binding response[] = (nstrafficdomain_bridgegroup_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}", "private void writeCustomFields() throws IOException\n {\n m_writer.writeStartList(\"custom_fields\");\n for (CustomField field : m_projectFile.getCustomFields())\n {\n writeCustomField(field);\n }\n m_writer.writeEndList();\n }", "public 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 void populateExpandedExceptions()\n {\n if (!m_exceptions.isEmpty() && m_expandedExceptions.isEmpty())\n {\n for (ProjectCalendarException exception : m_exceptions)\n {\n RecurringData recurring = exception.getRecurring();\n if (recurring == null)\n {\n m_expandedExceptions.add(exception);\n }\n else\n {\n for (Date date : recurring.getDates())\n {\n Date startDate = DateHelper.getDayStartDate(date);\n Date endDate = DateHelper.getDayEndDate(date);\n ProjectCalendarException newException = new ProjectCalendarException(startDate, endDate);\n int rangeCount = exception.getRangeCount();\n for (int rangeIndex = 0; rangeIndex < rangeCount; rangeIndex++)\n {\n newException.addRange(exception.getRange(rangeIndex));\n }\n m_expandedExceptions.add(newException);\n }\n }\n }\n Collections.sort(m_expandedExceptions);\n }\n }", "public synchronized int get() {\n if (available == 0) {\n return -1;\n }\n byte value = buffer[idxGet];\n idxGet = (idxGet + 1) % capacity;\n available--;\n return value;\n }" ]
Find the length of the block starting from 'start'.
[ "private static int blockLength(int start, QrMode[] inputMode) {\n\n QrMode mode = inputMode[start];\n int count = 0;\n int i = start;\n\n do {\n count++;\n } while (((i + count) < inputMode.length) && (inputMode[i + count] == mode));\n\n return count;\n }" ]
[ "public final Jar setAttribute(String section, String name, String value) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Manifest cannot be modified after entries are added.\");\n Attributes attr = getManifest().getAttributes(section);\n if (attr == null) {\n attr = new Attributes();\n getManifest().getEntries().put(section, attr);\n }\n attr.putValue(name, value);\n return this;\n }", "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 putInWakeUpQueue(SerialMessage serialMessage) {\r\n\t\tif (this.wakeUpQueue.contains(serialMessage)) {\r\n\t\t\tlogger.debug(\"Message already on the wake-up queue for node {}. Discarding.\", this.getNode().getNodeId());\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\t\r\n\t\tlogger.debug(\"Putting message in wakeup queue for node {}.\", this.getNode().getNodeId());\r\n\t\tthis.wakeUpQueue.add(serialMessage);\r\n\t}", "public static String make512Safe(StringBuffer input, String newline) {\n\t\tStringBuilder result = new StringBuilder();\n\t\tString content = input.toString();\n\t\tString rest = content;\n\t\twhile (!rest.isEmpty()) {\n\t\t\tif (rest.contains(\"\\n\")) {\n\t\t\t\tString line = rest.substring(0, rest.indexOf(\"\\n\"));\n\t\t\t\trest = rest.substring(rest.indexOf(\"\\n\") + 1);\n\t\t\t\tif (line.length() > 1 && line.charAt(line.length() - 1) == '\\r')\n\t\t\t\t\tline = line.substring(0, line.length() - 1);\n\t\t\t\tappend512Safe(line, result, newline);\n\t\t\t} else {\n\t\t\t\tappend512Safe(rest, result, newline);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn result.toString();\n\t}", "@SuppressWarnings(\"SameParameterValue\")\n private void sendField(Field field) throws IOException {\n if (isConnected()) {\n try {\n field.write(channel);\n } catch (IOException e) {\n logger.warn(\"Problem trying to write field to dbserver, closing connection\", e);\n close();\n throw e;\n }\n return;\n }\n throw new IOException(\"sendField() called after dbserver connection was closed\");\n }", "public void editMeta(String photosetId, String title, String description) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_META);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n parameters.put(\"title\", title);\r\n if (description != null) {\r\n parameters.put(\"description\", description);\r\n }\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 }", "protected void appendStringType(StringBuilder sb, FieldType fieldType, int fieldWidth) {\n\t\tif (isVarcharFieldWidthSupported()) {\n\t\t\tsb.append(\"VARCHAR(\").append(fieldWidth).append(')');\n\t\t} else {\n\t\t\tsb.append(\"VARCHAR\");\n\t\t}\n\t}", "public static base_responses add(nitro_service client, authenticationradiusaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tauthenticationradiusaction addresources[] = new authenticationradiusaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new authenticationradiusaction();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].serverip = resources[i].serverip;\n\t\t\t\taddresources[i].serverport = resources[i].serverport;\n\t\t\t\taddresources[i].authtimeout = resources[i].authtimeout;\n\t\t\t\taddresources[i].radkey = resources[i].radkey;\n\t\t\t\taddresources[i].radnasip = resources[i].radnasip;\n\t\t\t\taddresources[i].radnasid = resources[i].radnasid;\n\t\t\t\taddresources[i].radvendorid = resources[i].radvendorid;\n\t\t\t\taddresources[i].radattributetype = resources[i].radattributetype;\n\t\t\t\taddresources[i].radgroupsprefix = resources[i].radgroupsprefix;\n\t\t\t\taddresources[i].radgroupseparator = resources[i].radgroupseparator;\n\t\t\t\taddresources[i].passencoding = resources[i].passencoding;\n\t\t\t\taddresources[i].ipvendorid = resources[i].ipvendorid;\n\t\t\t\taddresources[i].ipattributetype = resources[i].ipattributetype;\n\t\t\t\taddresources[i].accounting = resources[i].accounting;\n\t\t\t\taddresources[i].pwdvendorid = resources[i].pwdvendorid;\n\t\t\t\taddresources[i].pwdattributetype = resources[i].pwdattributetype;\n\t\t\t\taddresources[i].defaultauthenticationgroup = resources[i].defaultauthenticationgroup;\n\t\t\t\taddresources[i].callingstationid = resources[i].callingstationid;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "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 }" ]
Convert an object to another object given a parameterized type signature @param context @param destinationType the destination type @param source the source object @return the converted object @throws ConverterException if conversion failed
[ "public <T> T convert(ConversionContext context, Object source,\r\n\t\t\tTypeReference<T> destinationType) throws ConverterException {\r\n\t\ttry {\r\n\t\t\treturn (T) multiConverter.convert(context, source, destinationType);\r\n\t\t} catch (ConverterException e) {\r\n\t\t\tthrow e;\r\n\t\t} catch (Exception e) {\r\n\t\t\t// There is a problem with one converter. This should not happen.\r\n\t\t\t// Either there is a bug in this converter or it is not properly\r\n\t\t\t// configured\r\n\t\t\tthrow new ConverterException(\r\n\t\t\t\t\tMessageFormat\r\n\t\t\t\t\t\t\t.format(\r\n\t\t\t\t\t\t\t\t\t\"Could not convert given object with class ''{0}'' to object with type signature ''{1}''\",\r\n\t\t\t\t\t\t\t\t\tsource == null ? \"null\" : source.getClass()\r\n\t\t\t\t\t\t\t\t\t\t\t.getName(), destinationType), e);\r\n\t\t}\r\n\t}" ]
[ "private void handleGlobalArguments(Section section) {\n\t\tfor (String key : section.keySet()) {\n\t\t\tswitch (key) {\n\t\t\tcase OPTION_OFFLINE_MODE:\n\t\t\t\tif (section.get(key).toLowerCase().equals(\"true\")) {\n\t\t\t\t\tthis.offlineMode = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OPTION_QUIET:\n\t\t\t\tif (section.get(key).toLowerCase().equals(\"true\")) {\n\t\t\t\t\tthis.quiet = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OPTION_CREATE_REPORT:\n\t\t\t\tthis.reportFilename = section.get(key);\n\t\t\t\tbreak;\n\t\t\tcase OPTION_DUMP_LOCATION:\n\t\t\t\tthis.dumpDirectoryLocation = section.get(key);\n\t\t\t\tbreak;\n\t\t\tcase OPTION_FILTER_LANGUAGES:\n\t\t\t\tsetLanguageFilters(section.get(key));\n\t\t\t\tbreak;\n\t\t\tcase OPTION_FILTER_SITES:\n\t\t\t\tsetSiteFilters(section.get(key));\n\t\t\t\tbreak;\n\t\t\tcase OPTION_FILTER_PROPERTIES:\n\t\t\t\tsetPropertyFilters(section.get(key));\n\t\t\t\tbreak;\n\t\t\tcase OPTION_LOCAL_DUMPFILE:\n\t\t\t\tthis.inputDumpLocation = section.get(key);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogger.warn(\"Unrecognized option: \" + key);\n\t\t\t}\n\t\t}\n\t}", "private void processBlock(List<GenericCriteria> list, byte[] block)\n {\n if (block != null)\n {\n if (MPPUtility.getShort(block, 0) > 0x3E6)\n {\n addCriteria(list, block);\n }\n else\n {\n switch (block[0])\n {\n case (byte) 0x0B:\n {\n processBlock(list, getChildBlock(block));\n break;\n }\n\n case (byte) 0x06:\n {\n processBlock(list, getListNextBlock(block));\n break;\n }\n\n case (byte) 0xED: // EQUALS\n {\n addCriteria(list, block);\n break;\n }\n\n case (byte) 0x19: // AND\n case (byte) 0x1B:\n {\n addBlock(list, block, TestOperator.AND);\n break;\n }\n\n case (byte) 0x1A: // OR\n case (byte) 0x1C:\n {\n addBlock(list, block, TestOperator.OR);\n break;\n }\n }\n }\n }\n }", "public static base_response delete(nitro_service client, String network) throws Exception {\n\t\troute6 deleteresource = new route6();\n\t\tdeleteresource.network = network;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public boolean equivalent(Element otherElement, boolean logging) {\n\t\tif (eventable.getElement().equals(otherElement)) {\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element equal\");\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (eventable.getElement().equalAttributes(otherElement)) {\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element attributes equal\");\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (eventable.getElement().equalId(otherElement)) {\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element ID equal\");\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (!eventable.getElement().getText().equals(\"\")\n\t\t\t\t&& eventable.getElement().equalText(otherElement)) {\n\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element text equal\");\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}", "public static void validate(final ArtifactQuery artifactQuery) {\n final Pattern invalidChars = Pattern.compile(\"[^A-Fa-f0-9]\");\n if(artifactQuery.getUser() == null ||\n \t\tartifactQuery.getUser().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [user] missing\")\n .build());\n }\n if( artifactQuery.getStage() != 0 && artifactQuery.getStage() !=1 ){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid [stage] value (supported 0 | 1)\")\n .build());\n }\n if(artifactQuery.getName() == null ||\n \t\tartifactQuery.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [name] missing, it should be the file name\")\n .build());\n }\n if(artifactQuery.getSha256() == null ||\n artifactQuery.getSha256().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [sha256] missing\")\n .build());\n }\n if(artifactQuery.getSha256().length() < 64 || invalidChars.matcher(artifactQuery.getSha256()).find()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid file checksum value\")\n .build());\n }\n if(artifactQuery.getType() == null ||\n \t\tartifactQuery.getType().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [type] missing\")\n .build());\n }\n }", "@Deprecated\n public ClientConfig setThreadIdleTime(long threadIdleTime, TimeUnit unit) {\n this.threadIdleMs = unit.toMillis(threadIdleTime);\n return this;\n }", "@UiThread\n private int getFlatParentPosition(int parentPosition) {\n int parentCount = 0;\n int listItemCount = mFlatItemList.size();\n for (int i = 0; i < listItemCount; i++) {\n if (mFlatItemList.get(i).isParent()) {\n parentCount++;\n\n if (parentCount > parentPosition) {\n return i;\n }\n }\n }\n\n return INVALID_FLAT_POSITION;\n }", "public <T extends OutputStream> T write(T os) throws IOException {\n close();\n\n if (!(this.os instanceof ByteArrayOutputStream))\n throw new IllegalStateException(\"Cannot write to another target if setOutputStream has been called\");\n final byte[] content = ((ByteArrayOutputStream) this.os).toByteArray();\n\n if (packer != null)\n packer.pack(new JarInputStream(new ByteArrayInputStream(content)), os);\n else\n os.write(content);\n\n os.close();\n return os;\n }", "private void validateJUnit4() throws BuildException {\n try {\n Class<?> clazz = Class.forName(\"org.junit.runner.Description\");\n if (!Serializable.class.isAssignableFrom(clazz)) {\n throw new BuildException(\"At least JUnit version 4.10 is required on junit4's taskdef classpath.\");\n }\n } catch (ClassNotFoundException e) {\n throw new BuildException(\"JUnit JAR must be added to junit4 taskdef's classpath.\");\n }\n }" ]
Encode a long into a byte array at an offset @param ba Byte array @param offset Offset @param v Long value @return byte array given in input
[ "public static byte[] encode(byte[] ba, int offset, long v) {\n ba[offset + 0] = (byte) (v >>> 56);\n ba[offset + 1] = (byte) (v >>> 48);\n ba[offset + 2] = (byte) (v >>> 40);\n ba[offset + 3] = (byte) (v >>> 32);\n ba[offset + 4] = (byte) (v >>> 24);\n ba[offset + 5] = (byte) (v >>> 16);\n ba[offset + 6] = (byte) (v >>> 8);\n ba[offset + 7] = (byte) (v >>> 0);\n return ba;\n }" ]
[ "public static appflowpolicy_appflowglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappflowpolicy_appflowglobal_binding obj = new appflowpolicy_appflowglobal_binding();\n\t\tobj.set_name(name);\n\t\tappflowpolicy_appflowglobal_binding response[] = (appflowpolicy_appflowglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static base_responses add(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 addresources[] = new onlinkipv6prefix[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new onlinkipv6prefix();\n\t\t\t\taddresources[i].ipv6prefix = resources[i].ipv6prefix;\n\t\t\t\taddresources[i].onlinkprefix = resources[i].onlinkprefix;\n\t\t\t\taddresources[i].autonomusprefix = resources[i].autonomusprefix;\n\t\t\t\taddresources[i].depricateprefix = resources[i].depricateprefix;\n\t\t\t\taddresources[i].decrementprefixlifetimes = resources[i].decrementprefixlifetimes;\n\t\t\t\taddresources[i].prefixvalidelifetime = resources[i].prefixvalidelifetime;\n\t\t\t\taddresources[i].prefixpreferredlifetime = resources[i].prefixpreferredlifetime;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "private void countCoordinateStatement(Statement statement,\n\t\t\tItemDocument itemDocument) {\n\t\tValue value = statement.getValue();\n\t\tif (!(value instanceof GlobeCoordinatesValue)) {\n\t\t\treturn;\n\t\t}\n\n\t\tGlobeCoordinatesValue coordsValue = (GlobeCoordinatesValue) value;\n\t\tif (!this.globe.equals((coordsValue.getGlobe()))) {\n\t\t\treturn;\n\t\t}\n\n\t\tint xCoord = (int) (((coordsValue.getLongitude() + 180.0) / 360.0) * this.width)\n\t\t\t\t% this.width;\n\t\tint yCoord = (int) (((coordsValue.getLatitude() + 90.0) / 180.0) * this.height)\n\t\t\t\t% this.height;\n\n\t\tif (xCoord < 0 || yCoord < 0 || xCoord >= this.width\n\t\t\t\t|| yCoord >= this.height) {\n\t\t\tSystem.out.println(\"Dropping out-of-range coordinate: \"\n\t\t\t\t\t+ coordsValue);\n\t\t\treturn;\n\t\t}\n\n\t\tcountCoordinates(xCoord, yCoord, itemDocument);\n\t\tthis.count += 1;\n\n\t\tif (this.count % 100000 == 0) {\n\t\t\treportProgress();\n\t\t\twriteImages();\n\t\t}\n\t}", "private static int skipEndOfLine(String text, int offset)\n {\n char c;\n boolean finished = false;\n\n while (finished == false)\n {\n c = text.charAt(offset);\n switch (c)\n {\n case ' ': // found that OBJDATA could be followed by a space the EOL\n case '\\r':\n case '\\n':\n {\n ++offset;\n break;\n }\n\n case '}':\n {\n offset = -1;\n finished = true;\n break;\n }\n\n default:\n {\n finished = true;\n break;\n }\n }\n }\n\n return (offset);\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 }", "public boolean merge(AbstractTransition another) {\n if (!isCompatible(another)) {\n return false;\n }\n if (another.mId != null) {\n if (mId == null) {\n mId = another.mId;\n } else {\n StringBuilder sb = new StringBuilder(mId.length() + another.mId.length());\n sb.append(mId);\n sb.append(\"_MERGED_\");\n sb.append(another.mId);\n mId = sb.toString();\n }\n }\n mUpdateStateAfterUpdateProgress |= another.mUpdateStateAfterUpdateProgress;\n mSetupList.addAll(another.mSetupList);\n Collections.sort(mSetupList, new Comparator<S>() {\n @Override\n public int compare(S lhs, S rhs) {\n if (lhs instanceof AbstractTransitionBuilder && rhs instanceof AbstractTransitionBuilder) {\n AbstractTransitionBuilder left = (AbstractTransitionBuilder) lhs;\n AbstractTransitionBuilder right = (AbstractTransitionBuilder) rhs;\n float startLeft = left.mReverse ? left.mEnd : left.mStart;\n float startRight = right.mReverse ? right.mEnd : right.mStart;\n return (int) ((startRight - startLeft) * 1000);\n }\n return 0;\n }\n });\n\n return true;\n }", "private Variable createVariableInferred(TokenList.Token t0, Variable variableRight) {\n Variable result;\n\n if( t0.getType() == Type.WORD ) {\n switch( variableRight.getType()) {\n case MATRIX:\n alias(new DMatrixRMaj(1,1),t0.getWord());\n break;\n\n case SCALAR:\n if( variableRight instanceof VariableInteger) {\n alias(0,t0.getWord());\n } else {\n alias(1.0,t0.getWord());\n }\n break;\n\n case INTEGER_SEQUENCE:\n alias((IntegerSequence)null,t0.getWord());\n break;\n\n default:\n throw new RuntimeException(\"Type not supported for assignment: \"+variableRight.getType());\n }\n\n result = variables.get(t0.getWord());\n } else {\n result = t0.getVariable();\n }\n return result;\n }", "private LoginContext getClientLoginContext() throws LoginException {\n Configuration config = new Configuration() {\n @Override\n public AppConfigurationEntry[] getAppConfigurationEntry(String name) {\n Map<String, String> options = new HashMap<String, String>();\n options.put(\"multi-threaded\", \"true\");\n options.put(\"restore-login-identity\", \"true\");\n\n AppConfigurationEntry clmEntry = new AppConfigurationEntry(ClientLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, options);\n return new AppConfigurationEntry[] { clmEntry };\n }\n };\n return getLoginContext(config);\n }", "public static ScheduledExecutorService newScheduledDaemonThreadPool(int corePoolSize) {\n return Executors.newScheduledThreadPool(corePoolSize, r -> {\n Thread t = Executors.defaultThreadFactory().newThread(r);\n t.setDaemon(true);\n return t;\n });\n }" ]
Mbeans for UPDATE_ENTRIES
[ "@JmxGetter(name = \"avgUpdateEntriesNetworkTimeMs\", description = \"average time spent on network, for streaming operations\")\n public double getAvgUpdateEntriesNetworkTimeMs() {\n return networkTimeCounterMap.get(Operation.UPDATE_ENTRIES).getAvgEventValue()\n / Time.NS_PER_MS;\n }" ]
[ "private void readResources(Document cdp)\n {\n for (Document.Resources.Resource resource : cdp.getResources().getResource())\n {\n readResource(resource);\n }\n }", "public HashMap<String, IndexInput> getIndexInputList() {\n HashMap<String, IndexInput> clonedIndexInputList = new HashMap<String, IndexInput>();\n for (Entry<String, IndexInput> entry : indexInputList.entrySet()) {\n clonedIndexInputList.put(entry.getKey(), entry.getValue().clone());\n }\n return clonedIndexInputList;\n }", "public void register(Delta delta) {\n\t\tfinal IResourceDescription newDesc = delta.getNew();\n\t\tif (newDesc == null) {\n\t\t\tremoveDescription(delta.getUri());\n\t\t} else {\n\t\t\taddDescription(delta.getUri(), newDesc);\n\t\t}\n\t}", "@Deprecated\r\n public Location resolvePlaceURL(String flickrPlacesUrl) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_RESOLVE_PLACE_URL);\r\n\r\n parameters.put(\"url\", flickrPlacesUrl);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }", "private void processActivities(Storepoint phoenixProject)\n {\n final AlphanumComparator comparator = new AlphanumComparator();\n List<Activity> activities = phoenixProject.getActivities().getActivity();\n Collections.sort(activities, new Comparator<Activity>()\n {\n @Override public int compare(Activity o1, Activity o2)\n {\n Map<UUID, UUID> codes1 = getActivityCodes(o1);\n Map<UUID, UUID> codes2 = getActivityCodes(o2);\n for (UUID code : m_codeSequence)\n {\n UUID codeValue1 = codes1.get(code);\n UUID codeValue2 = codes2.get(code);\n\n if (codeValue1 == null || codeValue2 == null)\n {\n if (codeValue1 == null && codeValue2 == null)\n {\n continue;\n }\n\n if (codeValue1 == null)\n {\n return -1;\n }\n\n if (codeValue2 == null)\n {\n return 1;\n }\n }\n\n if (!codeValue1.equals(codeValue2))\n {\n Integer sequence1 = m_activityCodeSequence.get(codeValue1);\n Integer sequence2 = m_activityCodeSequence.get(codeValue2);\n\n return NumberHelper.compare(sequence1, sequence2);\n }\n }\n\n return comparator.compare(o1.getId(), o2.getId());\n }\n });\n\n for (Activity activity : activities)\n {\n processActivity(activity);\n }\n }", "public LuaPreparedScript endPreparedScript(LuaScriptConfig config) {\n if (!endsWithReturnStatement()) {\n add(new LuaAstReturnStatement());\n }\n String scriptText = buildScriptText();\n ArrayList<LuaKeyArgument> keyList = new ArrayList<>(keyArg2AstArg.keySet());\n ArrayList<LuaValueArgument> argvList = new ArrayList<>(valueArg2AstArg.keySet());\n if (config.isThreadSafe()) {\n return new ThreadSafeLuaPreparedScript(scriptText, keyList, argvList, config);\n } else {\n return new BasicLuaPreparedScript(scriptText, keyList, argvList, config);\n }\n }", "public void setAllowBlank(boolean allowBlank) {\n this.allowBlank = allowBlank;\n\n // Setup the allow blank validation\n if (!allowBlank) {\n if (blankValidator == null) {\n blankValidator = createBlankValidator();\n }\n setupBlurValidation();\n addValidator(blankValidator);\n } else {\n removeValidator(blankValidator);\n }\n }", "public static Iterable<BoxCollection.Info> getAllCollections(final BoxAPIConnection api) {\n return new Iterable<BoxCollection.Info>() {\n public Iterator<BoxCollection.Info> iterator() {\n URL url = GET_COLLECTIONS_URL_TEMPLATE.build(api.getBaseURL());\n return new BoxCollectionIterator(api, url);\n }\n };\n }", "public static void addToListIfNotExists(List<String> list, String value) {\n boolean found = false;\n for (String item : list) {\n if (item.equalsIgnoreCase(value)) {\n found = true;\n break;\n }\n }\n if (!found) {\n list.add(value);\n }\n }" ]
Run through the map and remove any references that have been null'd out by the GC.
[ "public <T> void cleanNullReferences(Class<T> clazz) {\n\t\tMap<Object, Reference<Object>> objectMap = getMapForClass(clazz);\n\t\tif (objectMap != null) {\n\t\t\tcleanMap(objectMap);\n\t\t}\n\t}" ]
[ "@Override\n\tpublic ProxyAuthenticationMethod getMethod() {\n\t\tswitch (authenticationMethod) {\n\t\tcase BASIC:\n\t\t\treturn ProxyAuthenticationMethod.BASIC;\n\t\tcase DIGEST:\n\t\t\treturn ProxyAuthenticationMethod.DIGEST;\n\t\tcase URL:\n\t\t\treturn ProxyAuthenticationMethod.URL;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}", "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 }", "public Launcher addEnvironmentVariable(final String key, final String value) {\n env.put(key, value);\n return this;\n }", "public Number getOvertimeCost()\n {\n Number cost = (Number) getCachedValue(AssignmentField.OVERTIME_COST);\n if (cost == null)\n {\n Number actual = getActualOvertimeCost();\n Number remaining = getRemainingOvertimeCost();\n if (actual != null && remaining != null)\n {\n cost = NumberHelper.getDouble(actual.doubleValue() + remaining.doubleValue());\n set(AssignmentField.OVERTIME_COST, cost);\n }\n }\n return (cost);\n }", "protected String getClasspath() throws IOException {\n List<String> classpath = new ArrayList<>();\n classpath.add(getBundleJarPath());\n classpath.addAll(getPluginsPath());\n return StringUtils.toString(classpath.toArray(new String[classpath.size()]), \" \");\n }", "private void deleteAsync(final File file) {\n new Thread(new Runnable() {\n\n @Override\n public void run() {\n try {\n try {\n logger.info(\"Waiting for \" + deleteBackupMs\n + \" milliseconds before deleting \" + file.getAbsolutePath());\n Thread.sleep(deleteBackupMs);\n } catch(InterruptedException e) {\n logger.warn(\"Did not sleep enough before deleting backups\");\n }\n logger.info(\"Deleting file \" + file.getAbsolutePath());\n Utils.rm(file);\n logger.info(\"Deleting of \" + file.getAbsolutePath()\n + \" completed successfully.\");\n storeVersionManager.syncInternalStateFromFileSystem(true);\n } catch(Exception e) {\n logger.error(\"Exception during deleteAsync for path: \" + file, e);\n }\n }\n }, \"background-file-delete\").start();\n }", "public static String plus(CharSequence left, Object value) {\n return left + DefaultGroovyMethods.toString(value);\n }", "public static String make512Safe(StringBuffer input, String newline) {\n\t\tStringBuilder result = new StringBuilder();\n\t\tString content = input.toString();\n\t\tString rest = content;\n\t\twhile (!rest.isEmpty()) {\n\t\t\tif (rest.contains(\"\\n\")) {\n\t\t\t\tString line = rest.substring(0, rest.indexOf(\"\\n\"));\n\t\t\t\trest = rest.substring(rest.indexOf(\"\\n\") + 1);\n\t\t\t\tif (line.length() > 1 && line.charAt(line.length() - 1) == '\\r')\n\t\t\t\t\tline = line.substring(0, line.length() - 1);\n\t\t\t\tappend512Safe(line, result, newline);\n\t\t\t} else {\n\t\t\t\tappend512Safe(rest, result, newline);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn result.toString();\n\t}", "private void readCalendar(Gantt gantt)\n {\n Gantt.Calendar ganttCalendar = gantt.getCalendar();\n m_projectFile.getProjectProperties().setWeekStartDay(ganttCalendar.getWeekStart());\n\n ProjectCalendar calendar = m_projectFile.addCalendar();\n calendar.setName(\"Standard\");\n m_projectFile.setDefaultCalendar(calendar);\n\n String workingDays = ganttCalendar.getWorkDays();\n calendar.setWorkingDay(Day.SUNDAY, workingDays.charAt(0) == '1');\n calendar.setWorkingDay(Day.MONDAY, workingDays.charAt(1) == '1');\n calendar.setWorkingDay(Day.TUESDAY, workingDays.charAt(2) == '1');\n calendar.setWorkingDay(Day.WEDNESDAY, workingDays.charAt(3) == '1');\n calendar.setWorkingDay(Day.THURSDAY, workingDays.charAt(4) == '1');\n calendar.setWorkingDay(Day.FRIDAY, workingDays.charAt(5) == '1');\n calendar.setWorkingDay(Day.SATURDAY, workingDays.charAt(6) == '1');\n\n for (int i = 1; i <= 7; i++)\n {\n Day day = Day.getInstance(i);\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n if (calendar.isWorkingDay(day))\n {\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n\n for (Gantt.Holidays.Holiday holiday : gantt.getHolidays().getHoliday())\n {\n ProjectCalendarException exception = calendar.addCalendarException(holiday.getDate(), holiday.getDate());\n exception.setName(holiday.getContent());\n }\n }" ]
Returns whether the division range includes the block of values for its prefix length
[ "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}" ]
[ "private int countCharsStart(final char ch, final boolean allowSpaces)\n {\n int count = 0;\n for (int i = 0; i < this.value.length(); i++)\n {\n final char c = this.value.charAt(i);\n if (c == ' ' && allowSpaces)\n {\n continue;\n }\n if (c == ch)\n {\n count++;\n }\n else\n {\n break;\n }\n }\n return count;\n }", "@Override\n public Symmetry454Date dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "public void add(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {\n BinderDescriptor binderDescriptor = new BinderDescriptor(declarationBinderRef);\n declarationBinders.put(declarationBinderRef, binderDescriptor);\n }", "public void writeFinalResults() {\n\t\tprintStatus();\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers\n\t\t\t\t\t\t.openExampleFileOuputStream(\"life-expectancies.csv\"))) {\n\n\t\t\tfor (int i = 0; i < lifeSpans.length; i++) {\n\t\t\t\tif (peopleCount[i] != 0) {\n\t\t\t\t\tout.println(i + \",\" + (double) lifeSpans[i]\n\t\t\t\t\t\t\t/ peopleCount[i] + \",\" + peopleCount[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "@SuppressWarnings(\"deprecation\")\n private final void operationTimeout() {\n\n /**\n * first kill async http worker; before suicide LESSON: MUST KILL AND\n * WAIT FOR CHILDREN to reply back before kill itself.\n */\n cancelCancellable();\n if (asyncWorker != null && !asyncWorker.isTerminated()) {\n asyncWorker\n .tell(RequestWorkerMsgType.PROCESS_ON_TIMEOUT, getSelf());\n\n } else {\n logger.info(\"asyncWorker has been killed or uninitialized (null). \"\n + \"Not send PROCESS ON TIMEOUT.\\nREQ: \"\n + request.toString());\n replyErrors(PcConstants.OPERATION_TIMEOUT,\n PcConstants.OPERATION_TIMEOUT, PcConstants.NA,\n PcConstants.NA_INT);\n }\n\n }", "public List<List<IN>> classifyRaw(String str,\r\n DocumentReaderAndWriter<IN> readerAndWriter) {\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromString(str, readerAndWriter);\r\n List<List<IN>> result = new ArrayList<List<IN>>();\r\n\r\n for (List<IN> document : documents) {\r\n classify(document);\r\n\r\n List<IN> sentence = new ArrayList<IN>();\r\n for (IN wi : document) {\r\n // TaggedWord word = new TaggedWord(wi.word(), wi.answer());\r\n // sentence.add(word);\r\n sentence.add(wi);\r\n }\r\n result.add(sentence);\r\n }\r\n return result;\r\n }", "public static int[] randomPermutation(int size) {\n Random r = new Random();\n int[] result = new int[size];\n\n for (int j = 0; j < size; j++) {\n result[j] = j;\n }\n \n for (int j = size - 1; j > 0; j--) {\n int k = r.nextInt(j);\n int temp = result[j];\n result[j] = result[k];\n result[k] = temp;\n }\n\n return result;\n }", "private CostRateTableEntry getCostRateTableEntry(Date date)\n {\n CostRateTableEntry result;\n\n CostRateTable table = getCostRateTable();\n if (table == null)\n {\n Resource resource = getResource();\n result = new CostRateTableEntry(resource.getStandardRate(), TimeUnit.HOURS, resource.getOvertimeRate(), TimeUnit.HOURS, resource.getCostPerUse(), null);\n }\n else\n {\n if (table.size() == 1)\n {\n result = table.get(0);\n }\n else\n {\n result = table.getEntryByDate(date);\n }\n }\n\n return result;\n }", "private void checkProcedures(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 ProcedureDef procDef;\r\n String type;\r\n String name;\r\n String fieldName;\r\n String argName;\r\n \r\n for (Iterator it = classDef.getProcedures(); it.hasNext();)\r\n {\r\n procDef = (ProcedureDef)it.next();\r\n type = procDef.getName();\r\n name = procDef.getProperty(PropertyHelper.OJB_PROPERTY_NAME);\r\n if ((name == null) || (name.length() == 0))\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-procedure in class \"+classDef.getName()+\" doesn't have a name\");\r\n }\r\n fieldName = procDef.getProperty(PropertyHelper.OJB_PROPERTY_RETURN_FIELD_REF);\r\n if ((fieldName != null) && (fieldName.length() > 0))\r\n {\r\n if (classDef.getField(fieldName) == null)\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-procedure \"+name+\" in class \"+classDef.getName()+\" references an unknown or non-persistent return field \"+fieldName);\r\n }\r\n }\r\n for (CommaListIterator argIt = new CommaListIterator(procDef.getProperty(PropertyHelper.OJB_PROPERTY_ARGUMENTS)); argIt.hasNext();)\r\n {\r\n argName = argIt.getNext();\r\n if (classDef.getProcedureArgument(argName) == null)\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-procedure \"+name+\" in class \"+classDef.getName()+\" references an unknown argument \"+argName);\r\n }\r\n }\r\n }\r\n\r\n ProcedureArgumentDef argDef;\r\n\r\n for (Iterator it = classDef.getProcedureArguments(); it.hasNext();)\r\n {\r\n argDef = (ProcedureArgumentDef)it.next();\r\n type = argDef.getProperty(PropertyHelper.OJB_PROPERTY_TYPE);\r\n if (\"runtime\".equals(type))\r\n {\r\n fieldName = argDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELD_REF);\r\n if ((fieldName != null) && (fieldName.length() > 0))\r\n {\r\n if (classDef.getField(fieldName) == null)\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-argument \"+argDef.getName()+\" in class \"+classDef.getName()+\" references an unknown or non-persistent return field \"+fieldName);\r\n }\r\n }\r\n }\r\n }\r\n }" ]
Given a storedefinition, constructs the xml string to be sent out in response to a "schemata" fetch request @param storeDefinition @return serialized store definition
[ "public static String constructSerializerInfoXml(StoreDefinition storeDefinition) {\n Element store = new Element(StoreDefinitionsMapper.STORE_ELMT);\n store.addContent(new Element(StoreDefinitionsMapper.STORE_NAME_ELMT).setText(storeDefinition.getName()));\n Element keySerializer = new Element(StoreDefinitionsMapper.STORE_KEY_SERIALIZER_ELMT);\n StoreDefinitionsMapper.addSerializer(keySerializer, storeDefinition.getKeySerializer());\n store.addContent(keySerializer);\n\n Element valueSerializer = new Element(StoreDefinitionsMapper.STORE_VALUE_SERIALIZER_ELMT);\n StoreDefinitionsMapper.addSerializer(valueSerializer, storeDefinition.getValueSerializer());\n store.addContent(valueSerializer);\n\n XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());\n return serializer.outputString(store);\n }" ]
[ "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 }", "private void processFileType(String token) throws MPXJException\n {\n String version = token.substring(2).split(\" \")[0];\n //System.out.println(version);\n Class<? extends AbstractFileFormat> fileFormatClass = FILE_VERSION_MAP.get(Integer.valueOf(version));\n if (fileFormatClass == null)\n {\n throw new MPXJException(\"Unsupported PP file format version \" + version);\n }\n\n try\n {\n AbstractFileFormat format = fileFormatClass.newInstance();\n m_tableDefinitions = format.tableDefinitions();\n m_epochDateFormat = format.epochDateFormat();\n }\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to configure file format\", ex);\n }\n }", "public void setDates(SortedSet<Date> dates) {\n\n if (!m_model.getIndividualDates().equals(dates)) {\n m_model.setIndividualDates(dates);\n onValueChange();\n }\n\n }", "private PlayState1 findPlayState1() {\n PlayState1 result = PLAY_STATE_1_MAP.get(packetBytes[123]);\n if (result == null) {\n return PlayState1.UNKNOWN;\n }\n return result;\n }", "public <T extends Widget & Checkable> List<Integer> getCheckedWidgetIndexes() {\n List<Integer> checked = new ArrayList<>();\n List<Widget> children = getChildren();\n\n final int size = children.size();\n for (int i = 0, j = -1; i < size; ++i) {\n Widget c = children.get(i);\n if (c instanceof Checkable) {\n ++j;\n if (((Checkable) c).isChecked()) {\n checked.add(j);\n }\n }\n }\n\n return checked;\n }", "List<MwDumpFile> mergeDumpLists(List<MwDumpFile> localDumps,\n\t\t\tList<MwDumpFile> onlineDumps) {\n\t\tList<MwDumpFile> result = new ArrayList<>(localDumps);\n\n\t\tHashSet<String> localDateStamps = new HashSet<>();\n\t\tfor (MwDumpFile dumpFile : localDumps) {\n\t\t\tlocalDateStamps.add(dumpFile.getDateStamp());\n\t\t}\n\t\tfor (MwDumpFile dumpFile : onlineDumps) {\n\t\t\tif (!localDateStamps.contains(dumpFile.getDateStamp())) {\n\t\t\t\tresult.add(dumpFile);\n\t\t\t}\n\t\t}\n\t\tresult.sort(Collections.reverseOrder(new MwDumpFile.DateComparator()));\n\t\treturn result;\n\t}", "@Override\n\tpublic ClosableIterator<Tuple> callStoredProcedure(String storedProcedureName, ProcedureQueryParameters params, TupleContext tupleContext) {\n\t\tvalidate( params );\n\t\tStringBuilder commandLine = createCallStoreProcedureCommand( storedProcedureName, params );\n\t\tDocument result = callStoredProcedure( commandLine );\n\t\tObject resultValue = result.get( \"retval\" );\n\t\tList<Tuple> resultTuples = extractTuples( storedProcedureName, resultValue );\n\t\treturn CollectionHelper.newClosableIterator( resultTuples );\n\t}", "public static String readTextFile(Context context, String asset) {\n try {\n InputStream inputStream = context.getAssets().open(asset);\n return org.gearvrf.utility.TextFile.readTextFile(inputStream);\n } catch (FileNotFoundException f) {\n Log.w(TAG, \"readTextFile(): asset file '%s' doesn't exist\", asset);\n } catch (IOException e) {\n e.printStackTrace();\n Log.e(TAG, e, \"readTextFile()\");\n }\n return null;\n }", "public ApnsServiceBuilder withAuthProxy(Proxy proxy, String proxyUsername, String proxyPassword) {\n this.proxy = proxy;\n this.proxyUsername = proxyUsername;\n this.proxyPassword = proxyPassword;\n return this;\n }" ]
Navigate to this address in the given model node. @param model the model node @param create {@code true} to create the last part of the node if it does not exist @return the submodel @throws NoSuchElementException if the model contains no such element @deprecated manipulating a deep DMR node tree via PathAddress is no longer how the management layer works internally, so this method has become legacy cruft. Management operation handlers should obtain a {@link org.jboss.as.controller.registry.Resource Resource} from the {@link org.jboss.as.controller.OperationContext#readResource(PathAddress) OperationContext} and use the {@code Resource} API to access child resources
[ "@Deprecated\n public ModelNode navigate(ModelNode model, boolean create) throws NoSuchElementException {\n final Iterator<PathElement> i = pathAddressList.iterator();\n while (i.hasNext()) {\n final PathElement element = i.next();\n if (create && !i.hasNext()) {\n if (element.isMultiTarget()) {\n throw new IllegalStateException();\n }\n model = model.require(element.getKey()).get(element.getValue());\n } else {\n model = model.require(element.getKey()).require(element.getValue());\n }\n }\n return model;\n }" ]
[ "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 byte[] toByteArray() {\n try {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n oos.writeObject(this);\n return baos.toByteArray();\n } catch (IOException e) {\n throw E.ioException(e);\n }\n }", "private void addIncludes(DBHandling handling, FileSet fileSet) throws BuildException\r\n {\r\n DirectoryScanner scanner = fileSet.getDirectoryScanner(getProject());\r\n String[] files = scanner.getIncludedFiles();\r\n StringBuffer includes = new StringBuffer();\r\n\r\n for (int idx = 0; idx < files.length; idx++)\r\n {\r\n if (idx > 0)\r\n {\r\n includes.append(\",\");\r\n }\r\n includes.append(files[idx]);\r\n }\r\n try\r\n {\r\n handling.addDBDefinitionFiles(fileSet.getDir(getProject()).getAbsolutePath(), includes.toString());\r\n }\r\n catch (IOException ex)\r\n {\r\n throw new BuildException(ex);\r\n }\r\n }", "public void addDataSource(int groupno, DataSource datasource) {\n // the loader takes care of validation\n if (groupno == 0)\n datasources.add(datasource);\n else if (groupno == 1)\n group1.add(datasource);\n else if (groupno == 2)\n group2.add(datasource);\n }", "@Deprecated\n public int getEntityTypeId(@NotNull final String entityType, final boolean allowCreate) {\n return getEntityTypeId(txnProvider, entityType, allowCreate);\n }", "public synchronized void resumeDeployment(final String deployment) {\n for (ControlPoint ep : entryPoints.values()) {\n if (ep.getDeployment().equals(deployment)) {\n ep.resume();\n }\n }\n }", "private void prepare() throws IOException, DocumentException, PrintingException {\n\t\tif (baos == null) {\n\t\t\tbaos = new ByteArrayOutputStream(); // let it grow as much as needed\n\t\t}\n\t\tbaos.reset();\n\t\tboolean resize = false;\n\t\tif (page.getConstraint().getWidth() == 0 || page.getConstraint().getHeight() == 0) {\n\t\t\tresize = true;\n\t\t}\n\t\t// Create a document in the requested ISO scale.\n\t\tDocument document = new Document(page.getBounds(), 0, 0, 0, 0);\n\t\tPdfWriter writer;\n\t\twriter = PdfWriter.getInstance(document, baos);\n\n\t\t// Render in correct colors for transparent rasters\n\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t// The mapView is not scaled to the document, we assume the mapView\n\t\t// has the right ratio.\n\n\t\t// Write document title and metadata\n\t\tdocument.open();\n\t\tPdfContext context = new PdfContext(writer);\n\t\tcontext.initSize(page.getBounds());\n\t\t// first pass of all children to calculate size\n\t\tpage.calculateSize(context);\n\t\tif (resize) {\n\t\t\t// we now know the bounds of the document\n\t\t\t// round 'm up and restart with a new document\n\t\t\tint width = (int) Math.ceil(page.getBounds().getWidth());\n\t\t\tint height = (int) Math.ceil(page.getBounds().getHeight());\n\t\t\tpage.getConstraint().setWidth(width);\n\t\t\tpage.getConstraint().setHeight(height);\n\n\t\t\tdocument = new Document(new Rectangle(width, height), 0, 0, 0, 0);\n\t\t\twriter = PdfWriter.getInstance(document, baos);\n\t\t\t// Render in correct colors for transparent rasters\n\t\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t\tdocument.open();\n\t\t\tbaos.reset();\n\t\t\tcontext = new PdfContext(writer);\n\t\t\tcontext.initSize(page.getBounds());\n\t\t}\n\t\t// int compressionLevel = writer.getCompressionLevel(); // For testing\n\t\t// writer.setCompressionLevel(0);\n\n\t\t// Actual drawing\n\t\tdocument.addTitle(\"Geomajas\");\n\t\t// second pass to layout\n\t\tpage.layout(context);\n\t\t// finally render (uses baos)\n\t\tpage.render(context);\n\n\t\tdocument.add(context.getImage());\n\t\t// Now close the document\n\t\tdocument.close();\n\t}", "public static Map<Integer, Integer> getMapOfContiguousPartitions(final Cluster cluster,\n int zoneId) {\n List<Integer> partitionIds = new ArrayList<Integer>(cluster.getPartitionIdsInZone(zoneId));\n Map<Integer, Integer> partitionIdToRunLength = Maps.newHashMap();\n\n if(partitionIds.isEmpty()) {\n return partitionIdToRunLength;\n }\n\n int lastPartitionId = partitionIds.get(0);\n int initPartitionId = lastPartitionId;\n\n for(int offset = 1; offset < partitionIds.size(); offset++) {\n int partitionId = partitionIds.get(offset);\n if(partitionId == lastPartitionId + 1) {\n lastPartitionId = partitionId;\n continue;\n }\n int runLength = lastPartitionId - initPartitionId + 1;\n\n partitionIdToRunLength.put(initPartitionId, runLength);\n\n initPartitionId = partitionId;\n lastPartitionId = initPartitionId;\n }\n\n int runLength = lastPartitionId - initPartitionId + 1;\n if(lastPartitionId == cluster.getNumberOfPartitions() - 1\n && partitionIdToRunLength.containsKey(0)) {\n // special case of contiguity that wraps around the ring.\n partitionIdToRunLength.put(initPartitionId, runLength + partitionIdToRunLength.get(0));\n partitionIdToRunLength.remove(0);\n } else {\n partitionIdToRunLength.put(initPartitionId, runLength);\n }\n\n return partitionIdToRunLength;\n }", "public Widget addControl(String name, int resId, Widget.OnTouchListener listener, int position) {\n Widget control = findChildByName(name);\n if (control == null) {\n control = createControlWidget(resId, name, null);\n }\n setupControl(name, control, listener, position);\n return control;\n }" ]
Select the specific vertex and fragment shader to use. The shader template is used to generate the sources for the vertex and fragment shader based on the vertex, material and light properties. This function may compile the shader if it does not already exist. @param context GVRContext @param rdata renderable entity with mesh and rendering options @param scene list of light sources
[ "public int bindShader(GVRContext context, IRenderable rdata, GVRScene scene, boolean isMultiview)\n {\n String signature = getClass().getSimpleName();\n GVRShaderManager shaderManager = context.getShaderManager();\n GVRMaterial mtl = rdata.getMaterial();\n synchronized (shaderManager)\n {\n int nativeShader = shaderManager.getShader(signature);\n\n if (nativeShader == 0)\n {\n nativeShader = addShader(shaderManager, signature, mtl);\n }\n if (nativeShader > 0)\n {\n rdata.setShader(nativeShader, isMultiview);\n }\n return nativeShader;\n }\n }" ]
[ "protected final StringBuilder getBaseUrl(final HttpServletRequest httpServletRequest) {\n StringBuilder baseURL = new StringBuilder();\n if (httpServletRequest.getContextPath() != null && !httpServletRequest.getContextPath().isEmpty()) {\n baseURL.append(httpServletRequest.getContextPath());\n }\n if (httpServletRequest.getServletPath() != null && !httpServletRequest.getServletPath().isEmpty()) {\n baseURL.append(httpServletRequest.getServletPath());\n }\n return baseURL;\n }", "public Optional<URL> getRoute(String routeName) {\n Route route = getClient().routes()\n .inNamespace(namespace).withName(routeName).get();\n\n return route != null ? Optional.ofNullable(createUrlFromRoute(route)) : Optional.empty();\n }", "@Override\n public AccountingDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "public static clusterinstance get(nitro_service service, Long clid) throws Exception{\n\t\tclusterinstance obj = new clusterinstance();\n\t\tobj.set_clid(clid);\n\t\tclusterinstance response = (clusterinstance) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void saveToBundleDescriptor() throws CmsException {\n\n if (null != m_descFile) {\n m_removeDescriptorOnCancel = false;\n updateBundleDescriptorContent();\n m_descFile.getFile().setContents(m_descContent.marshal());\n m_cms.writeFile(m_descFile.getFile());\n }\n }", "public static <T> T mode(Collection<T> values) {\r\n Set<T> modes = modes(values);\r\n return modes.iterator().next();\r\n }", "private static int getTrimmedXStart(BufferedImage img) {\n int height = img.getHeight();\n int width = img.getWidth();\n int xStart = width;\n\n for (int i = 0; i < height; i++) {\n for (int j = 0; j < width; j++) {\n if (img.getRGB(j, i) != Color.WHITE.getRGB() && j < xStart) {\n xStart = j;\n break;\n }\n }\n }\n\n return xStart;\n }", "public static Type[] getActualTypeArguments(Class<?> clazz) {\n Type type = Types.getCanonicalType(clazz);\n if (type instanceof ParameterizedType) {\n return ((ParameterizedType) type).getActualTypeArguments();\n } else {\n return EMPTY_TYPES;\n }\n }", "public static csvserver_copolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_copolicy_binding obj = new csvserver_copolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_copolicy_binding response[] = (csvserver_copolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Encrypt a string with HMAC-SHA1 using the specified key. @param message Input string. @param key Encryption key. @return Encrypted output.
[ "static byte[] hmacSha1(StringBuilder message, String key) {\n try {\n Mac mac = Mac.getInstance(\"HmacSHA1\");\n mac.init(new SecretKeySpec(key.getBytes(), \"HmacSHA1\"));\n return mac.doFinal(message.toString().getBytes());\n } catch (Exception e) {\n throw new RuntimeException(e);\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 }", "public static void parse(Reader src, StatementHandler handler)\n throws IOException {\n new NTriplesParser(src, handler).parse();\n }", "public static PJsonObject parseSpec(final String spec) {\n final JSONObject jsonSpec;\n try {\n jsonSpec = new JSONObject(spec);\n } catch (JSONException e) {\n throw new RuntimeException(\"Cannot parse the spec file: \" + spec, e);\n }\n return new PJsonObject(jsonSpec, \"spec\");\n }", "@Override\n public void process() {\n if (client.isDone() || executorService.isTerminated()) {\n throw new IllegalStateException(\"Client is already stopped\");\n }\n Runnable runner = new Runnable() {\n @Override\n public void run() {\n try {\n while (!client.isDone()) {\n String msg = messageQueue.take();\n try {\n parseMessage(msg);\n } catch (Exception e) {\n logger.warn(\"Exception thrown during parsing msg \" + msg, e);\n onException(e);\n }\n }\n } catch (Exception e) {\n onException(e);\n }\n }\n };\n\n executorService.execute(runner);\n }", "public void process() {\n // are we ready to process yet, or have we had an error, and are\n // waiting a bit longer in the hope that it will resolve itself?\n if (error_skips > 0) {\n error_skips--;\n return;\n }\n \n try {\n if (logger != null)\n logger.debug(\"Starting processing\");\n status = \"Processing\";\n lastCheck = System.currentTimeMillis();\n\n // FIXME: how to break off processing if we don't want to keep going?\n processor.deduplicate(batch_size);\n\n status = \"Sleeping\";\n if (logger != null)\n logger.debug(\"Finished processing\");\n } catch (Throwable e) {\n status = \"Thread blocked on error: \" + e;\n if (logger != null)\n logger.error(\"Error in processing; waiting\", e);\n error_skips = error_factor;\n }\n }", "public Range<App> listApps(String range) {\n return connection.execute(new AppList(range), apiKey);\n }", "private static Version getDockerVersion(String serverUrl) {\n try {\n DockerClient client = DockerClientBuilder.getInstance(serverUrl).build();\n return client.versionCmd().exec();\n } catch (Exception e) {\n return null;\n }\n }", "void publish() {\n assert publishedFullRegistry != null : \"Cannot write directly to main registry\";\n\n writeLock.lock();\n try {\n if (!modified) {\n return;\n }\n publishedFullRegistry.writeLock.lock();\n try {\n publishedFullRegistry.clear(true);\n copy(this, publishedFullRegistry);\n pendingRemoveCapabilities.clear();\n pendingRemoveRequirements.clear();\n modified = false;\n } finally {\n publishedFullRegistry.writeLock.unlock();\n }\n } finally {\n writeLock.unlock();\n }\n }", "public static base_response add(nitro_service client, authenticationradiusaction resource) throws Exception {\n\t\tauthenticationradiusaction addresource = new authenticationradiusaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.serverip = resource.serverip;\n\t\taddresource.serverport = resource.serverport;\n\t\taddresource.authtimeout = resource.authtimeout;\n\t\taddresource.radkey = resource.radkey;\n\t\taddresource.radnasip = resource.radnasip;\n\t\taddresource.radnasid = resource.radnasid;\n\t\taddresource.radvendorid = resource.radvendorid;\n\t\taddresource.radattributetype = resource.radattributetype;\n\t\taddresource.radgroupsprefix = resource.radgroupsprefix;\n\t\taddresource.radgroupseparator = resource.radgroupseparator;\n\t\taddresource.passencoding = resource.passencoding;\n\t\taddresource.ipvendorid = resource.ipvendorid;\n\t\taddresource.ipattributetype = resource.ipattributetype;\n\t\taddresource.accounting = resource.accounting;\n\t\taddresource.pwdvendorid = resource.pwdvendorid;\n\t\taddresource.pwdattributetype = resource.pwdattributetype;\n\t\taddresource.defaultauthenticationgroup = resource.defaultauthenticationgroup;\n\t\taddresource.callingstationid = resource.callingstationid;\n\t\treturn addresource.add_resource(client);\n\t}" ]
Creates dependency on management executor. @param builder the builder @param injector the injector @param <T> the parameter type @return service builder instance @deprecated Use {@link #requireServerExecutor(ServiceBuilder)} instead. This method will be removed in the future.
[ "@Deprecated\n public static <T> ServiceBuilder<T> addServerExecutorDependency(ServiceBuilder<T> builder, Injector<ExecutorService> injector) {\n return builder.addDependency(ServerService.MANAGEMENT_EXECUTOR, ExecutorService.class, injector);\n }" ]
[ "public Logger getLogger(String loggerName)\r\n {\r\n Logger logger;\r\n //lookup in the cache first\r\n logger = (Logger) cache.get(loggerName);\r\n\r\n if(logger == null)\r\n {\r\n try\r\n {\r\n // get the configuration (not from the configurator because this is independent)\r\n logger = createLoggerInstance(loggerName);\r\n if(getBootLogger().isDebugEnabled())\r\n {\r\n getBootLogger().debug(\"Using logger class '\"\r\n + (getConfiguration() != null ? getConfiguration().getLoggerClass() : null)\r\n + \"' for \" + loggerName);\r\n }\r\n // configure the logger\r\n getBootLogger().debug(\"Initializing logger instance \" + loggerName);\r\n logger.configure(conf);\r\n }\r\n catch(Throwable t)\r\n {\r\n // do reassign check and signal logger creation failure\r\n reassignBootLogger(true);\r\n logger = getBootLogger();\r\n getBootLogger().error(\"[\" + this.getClass().getName()\r\n + \"] Could not initialize logger \" + (conf != null ? conf.getLoggerClass() : null), t);\r\n }\r\n //cache it so we can get it faster the next time\r\n cache.put(loggerName, logger);\r\n // do reassign check\r\n reassignBootLogger(false);\r\n }\r\n return logger;\r\n }", "private void setSearchScopeFilter(CmsObject cms) {\n\n final List<String> searchRoots = CmsSearchUtil.computeScopeFolders(cms, this);\n\n // If the resource types contain the type \"function\" also\n // add \"/system/modules/\" to the search path\n\n if ((null != getResourceTypes()) && containsFunctionType(getResourceTypes())) {\n searchRoots.add(\"/system/modules/\");\n }\n\n addFoldersToSearchIn(searchRoots);\n }", "public static boolean isArray(Type type) {\n return (type instanceof GenericArrayType) || (type instanceof Class<?> && ((Class<?>) type).isArray());\n }", "public static final Duration getDuration(InputStream is) throws IOException\n {\n double durationInSeconds = getInt(is);\n durationInSeconds /= (60 * 60);\n return Duration.getInstance(durationInSeconds, TimeUnit.HOURS);\n }", "public void processSplitData(Task task, List<TimephasedWork> timephasedComplete, List<TimephasedWork> timephasedPlanned)\n {\n Date splitsComplete = null;\n TimephasedWork lastComplete = null;\n TimephasedWork firstPlanned = null;\n if (!timephasedComplete.isEmpty())\n {\n lastComplete = timephasedComplete.get(timephasedComplete.size() - 1);\n splitsComplete = lastComplete.getFinish();\n }\n\n if (!timephasedPlanned.isEmpty())\n {\n firstPlanned = timephasedPlanned.get(0);\n }\n\n LinkedList<DateRange> splits = new LinkedList<DateRange>();\n TimephasedWork lastAssignment = null;\n DateRange lastRange = null;\n for (TimephasedWork assignment : timephasedComplete)\n {\n if (lastAssignment != null && lastRange != null && lastAssignment.getTotalAmount().getDuration() != 0 && assignment.getTotalAmount().getDuration() != 0)\n {\n splits.removeLast();\n lastRange = new DateRange(lastRange.getStart(), assignment.getFinish());\n }\n else\n {\n lastRange = new DateRange(assignment.getStart(), assignment.getFinish());\n }\n splits.add(lastRange);\n lastAssignment = assignment;\n }\n\n //\n // We may not have a split, we may just have a partially\n // complete split.\n //\n Date splitStart = null;\n if (lastComplete != null && firstPlanned != null && lastComplete.getTotalAmount().getDuration() != 0 && firstPlanned.getTotalAmount().getDuration() != 0)\n {\n lastRange = splits.removeLast();\n splitStart = lastRange.getStart();\n }\n\n lastAssignment = null;\n lastRange = null;\n for (TimephasedWork assignment : timephasedPlanned)\n {\n if (splitStart == null)\n {\n if (lastAssignment != null && lastRange != null && lastAssignment.getTotalAmount().getDuration() != 0 && assignment.getTotalAmount().getDuration() != 0)\n {\n splits.removeLast();\n lastRange = new DateRange(lastRange.getStart(), assignment.getFinish());\n }\n else\n {\n lastRange = new DateRange(assignment.getStart(), assignment.getFinish());\n }\n }\n else\n {\n lastRange = new DateRange(splitStart, assignment.getFinish());\n }\n splits.add(lastRange);\n splitStart = null;\n lastAssignment = assignment;\n }\n\n //\n // We must have a minimum of 3 entries for this to be a valid split task\n //\n if (splits.size() > 2)\n {\n task.getSplits().addAll(splits);\n task.setSplitCompleteDuration(splitsComplete);\n }\n else\n {\n task.setSplits(null);\n task.setSplitCompleteDuration(null);\n }\n }", "public NodeInfo getNode(String name) {\n final URI uri = uriWithPath(\"./nodes/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, NodeInfo.class);\n }", "public String getString(String fieldName) {\n\t\treturn hasValue(fieldName) ? String.valueOf(resultMap.get(fieldName)) : null;\n\t}", "void registerAlias(FieldType type, String alias)\n {\n m_aliasMap.put(new Pair<FieldTypeClass, String>(type.getFieldTypeClass(), alias), type);\n }", "private Collection<TestClassResults> flattenResults(List<ISuite> suites)\n {\n Map<IClass, TestClassResults> flattenedResults = new HashMap<IClass, TestClassResults>();\n for (ISuite suite : suites)\n {\n for (ISuiteResult suiteResult : suite.getResults().values())\n {\n // Failed and skipped configuration methods are treated as test failures.\n organiseByClass(suiteResult.getTestContext().getFailedConfigurations().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getSkippedConfigurations().getAllResults(), flattenedResults);\n // Successful configuration methods are not included.\n \n organiseByClass(suiteResult.getTestContext().getFailedTests().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getSkippedTests().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getPassedTests().getAllResults(), flattenedResults);\n }\n }\n return flattenedResults.values();\n }" ]
Checks the day, month and year are equal.
[ "@SuppressWarnings(\"deprecation\")\n\tpublic static boolean dateEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getDate() == d2.getDate()\n && d1.getMonth() == d2.getMonth()\n && d1.getYear() == d2.getYear();\n }" ]
[ "public static ModelMBean createModelMBean(Object o) {\n try {\n ModelMBean mbean = new RequiredModelMBean();\n JmxManaged annotation = o.getClass().getAnnotation(JmxManaged.class);\n String description = annotation == null ? \"\" : annotation.description();\n ModelMBeanInfo info = new ModelMBeanInfoSupport(o.getClass().getName(),\n description,\n extractAttributeInfo(o),\n new ModelMBeanConstructorInfo[0],\n extractOperationInfo(o),\n new ModelMBeanNotificationInfo[0]);\n mbean.setModelMBeanInfo(info);\n mbean.setManagedResource(o, \"ObjectReference\");\n\n return mbean;\n } catch(MBeanException e) {\n throw new VoldemortException(e);\n } catch(InvalidTargetObjectTypeException e) {\n throw new VoldemortException(e);\n } catch(InstanceNotFoundException e) {\n throw new VoldemortException(e);\n }\n }", "public static inat[] get(nitro_service service) throws Exception{\n\t\tinat obj = new inat();\n\t\tinat[] response = (inat[])obj.get_resources(service);\n\t\treturn response;\n\t}", "@Override\n public void onLoadFinished(final Loader<SortedList<T>> loader,\n final SortedList<T> data) {\n isLoading = false;\n mCheckedItems.clear();\n mCheckedVisibleViewHolders.clear();\n mFiles = data;\n mAdapter.setList(data);\n if (mCurrentDirView != null) {\n mCurrentDirView.setText(getFullPath(mCurrentPath));\n }\n // Stop loading now to avoid a refresh clearing the user's selections\n getLoaderManager().destroyLoader( 0 );\n }", "void updateFromResponseOnDeletePost(Response<ResponseBody> response) throws IOException {\n this.withResponse(response);\n String responseContent = null;\n if (response.body() != null) {\n responseContent = response.body().string();\n response.body().close();\n }\n this.withResource(serializerAdapter.<T>deserialize(responseContent, resourceType));\n withStatus(AzureAsyncOperation.SUCCESS_STATUS, response.code());\n }", "private AlbumArt findArtInMemoryCaches(DataReference artReference) {\n // First see if we can find the new track in the hot cache as a hot cue\n for (AlbumArt cached : hotCache.values()) {\n if (cached.artReference.equals(artReference)) { // Found a hot cue hit, use it.\n return cached;\n }\n }\n\n // Not in the hot cache, see if it is in our LRU cache\n return artCache.get(artReference);\n }", "public ConfigOptionBuilder setDefaultWith( Object defaultValue ) {\n co.setHasDefault( true );\n co.setValue( defaultValue );\n return setOptional();\n }", "public Duration getWorkVariance()\n {\n Duration variance = (Duration) getCachedValue(ResourceField.WORK_VARIANCE);\n if (variance == null)\n {\n Duration work = getWork();\n Duration baselineWork = getBaselineWork();\n if (work != null && baselineWork != null)\n {\n variance = Duration.getInstance(work.getDuration() - baselineWork.convertUnits(work.getUnits(), getParentFile().getProjectProperties()).getDuration(), work.getUnits());\n set(ResourceField.WORK_VARIANCE, variance);\n }\n }\n return (variance);\n }", "public ResultSetAndStatement executeSQL(\r\n final String sql,\r\n ClassDescriptor cld,\r\n ValueContainer[] values,\r\n boolean scrollable)\r\n throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled()) logger.debug(\"executeSQL: \" + sql);\r\n final boolean isStoredprocedure = isStoredProcedure(sql);\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n try\r\n {\r\n stmt = sm.getPreparedStatement(cld, sql,\r\n scrollable, StatementManagerIF.FETCH_SIZE_NOT_EXPLICITLY_SET, isStoredprocedure);\r\n if (isStoredprocedure)\r\n {\r\n // Query implemented as a stored procedure, which must return a result set.\r\n // Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}\r\n getPlatform().registerOutResultSet((CallableStatement) stmt, 1);\r\n sm.bindValues(stmt, values, 2);\r\n stmt.execute();\r\n rs = (ResultSet) ((CallableStatement) stmt).getObject(1);\r\n }\r\n else\r\n {\r\n sm.bindValues(stmt, values, 1);\r\n rs = stmt.executeQuery();\r\n }\r\n\r\n // as we return the resultset for further operations, we cannot release the statement yet.\r\n // that has to be done by the JdbcAccess-clients (i.e. RsIterator, ProxyRsIterator and PkEnumeration.)\r\n return new ResultSetAndStatement(sm, stmt, rs, new SelectStatement()\r\n {\r\n public Query getQueryInstance()\r\n {\r\n return null;\r\n }\r\n\r\n public int getColumnIndex(FieldDescriptor fld)\r\n {\r\n return JdbcType.MIN_INT;\r\n }\r\n\r\n public String getStatement()\r\n {\r\n return sql;\r\n }\r\n });\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n logger.error(\"PersistenceBrokerException during the execution of the SQL query: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n throw ExceptionHelper.generateException(e, sql, cld, values, logger, null);\r\n }\r\n }", "Map<UUID, UUID> getActivityCodes(Activity activity)\n {\n Map<UUID, UUID> map = m_activityCodeCache.get(activity);\n if (map == null)\n {\n map = new HashMap<UUID, UUID>();\n m_activityCodeCache.put(activity, map);\n for (CodeAssignment ca : activity.getCodeAssignment())\n {\n UUID code = getUUID(ca.getCodeUuid(), ca.getCode());\n UUID value = getUUID(ca.getValueUuid(), ca.getValue());\n map.put(code, value);\n }\n }\n return map;\n }" ]
Gets the string describing the uniforms used by shaders of this type. @param ctx GVFContext shader is associated with @return uniform descriptor string @see #getTemplate(GVRContext) GVRShader#getUniformDescriptor()
[ "public String getUniformDescriptor(GVRContext ctx)\n {\n if (mShaderTemplate == null)\n {\n mShaderTemplate = makeTemplate(ID, ctx);\n ctx.getShaderManager().addShaderID(this);\n }\n return mShaderTemplate.getUniformDescriptor();\n }" ]
[ "@Override\n public void registerAttributes(ManagementResourceRegistration resourceRegistration) {\n for (AttributeAccess attr : attributes.values()) {\n resourceRegistration.registerReadOnlyAttribute(attr.getAttributeDefinition(), null);\n }\n }", "private void disableTalkBack() {\n GVRSceneObject[] sceneObjects = mGvrContext.getMainScene().getWholeSceneObjects();\n for (GVRSceneObject sceneObject : sceneObjects) {\n if (sceneObject instanceof GVRAccessiblityObject)\n if (((GVRAccessiblityObject) sceneObject).getTalkBack() != null)\n ((GVRAccessiblityObject) sceneObject).getTalkBack().setActive(false);\n\n }\n }", "public String getAuthorizationUrl(OAuth1RequestToken oAuthRequestToken, Permission permission) {\r\n\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .build(FlickrApi.instance());\r\n String authorizationUrl = service.getAuthorizationUrl(oAuthRequestToken);\r\n return String.format(\"%s&perms=%s\", authorizationUrl, permission.toString());\r\n }", "public int update(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\ttry {\n\t\t\t// there is always and id field as an argument so just return 0 lines updated\n\t\t\tif (argFieldTypes.length <= 1) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tObject[] args = getFieldObjects(data);\n\t\t\tObject newVersion = null;\n\t\t\tif (versionFieldType != null) {\n\t\t\t\tnewVersion = versionFieldType.extractJavaFieldValue(data);\n\t\t\t\tnewVersion = versionFieldType.moveToNextValue(newVersion);\n\t\t\t\targs[versionFieldTypeIndex] = versionFieldType.convertJavaFieldToSqlArgValue(newVersion);\n\t\t\t}\n\t\t\tint rowC = databaseConnection.update(statement, args, argFieldTypes);\n\t\t\tif (rowC > 0) {\n\t\t\t\tif (newVersion != null) {\n\t\t\t\t\t// if we have updated a row then update the version field in our object to the new value\n\t\t\t\t\tversionFieldType.assignField(connectionSource, data, newVersion, false, null);\n\t\t\t\t}\n\t\t\t\tif (objectCache != null) {\n\t\t\t\t\t// if we've changed something then see if we need to update our cache\n\t\t\t\t\tObject id = idField.extractJavaFieldValue(data);\n\t\t\t\t\tT cachedData = objectCache.get(clazz, id);\n\t\t\t\t\tif (cachedData != null && cachedData != data) {\n\t\t\t\t\t\t// copy each field from the updated data into the cached object\n\t\t\t\t\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\t\t\t\t\tif (fieldType != idField) {\n\t\t\t\t\t\t\t\tfieldType.assignField(connectionSource, cachedData,\n\t\t\t\t\t\t\t\t\t\tfieldType.extractJavaFieldValue(data), false, objectCache);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tlogger.debug(\"update data with statement '{}' and {} args, changed {} rows\", statement, args.length, rowC);\n\t\t\tif (args.length > 0) {\n\t\t\t\t// need to do the (Object) cast to force args to be a single object\n\t\t\t\tlogger.trace(\"update arguments: {}\", (Object) args);\n\t\t\t}\n\t\t\treturn rowC;\n\t\t} catch (SQLException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Unable to run update stmt on object \" + data + \": \" + statement, e);\n\t\t}\n\t}", "public static double elementSumSq( DMatrixD1 m ) {\n\n // minimize round off error\n double maxAbs = CommonOps_DDRM.elementMaxAbs(m);\n if( maxAbs == 0)\n return 0;\n\n double total = 0;\n \n int N = m.getNumElements();\n for( int i = 0; i < N; i++ ) {\n double d = m.data[i]/maxAbs;\n total += d*d;\n }\n\n return maxAbs*total*maxAbs;\n }", "public static String getStringOption(Map<String, String> configOptions, String optionKey, String defaultValue) {\n\n String result = configOptions.get(optionKey);\n return null != result ? result : defaultValue;\n }", "public static String getValue(Element element) {\r\n if (element != null) {\r\n Node dataNode = element.getFirstChild();\r\n if (dataNode != null) {\r\n return ((Text) dataNode).getData();\r\n }\r\n }\r\n return null;\r\n }", "private void sendMessage(Message message) throws IOException {\n logger.debug(\"Sending> {}\", message);\n int totalSize = 0;\n for (Field field : message.fields) {\n totalSize += field.getBytes().remaining();\n }\n ByteBuffer combined = ByteBuffer.allocate(totalSize);\n for (Field field : message.fields) {\n logger.debug(\"..sending> {}\", field);\n combined.put(field.getBytes());\n }\n combined.flip();\n Util.writeFully(combined, channel);\n }", "public BoxComment.Info reply(String message) {\n JsonObject itemJSON = new JsonObject();\n itemJSON.add(\"type\", \"comment\");\n itemJSON.add(\"id\", this.getID());\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"item\", itemJSON);\n if (BoxComment.messageContainsMention(message)) {\n requestJSON.add(\"tagged_message\", message);\n } else {\n requestJSON.add(\"message\", message);\n }\n\n URL url = ADD_COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxComment addedComment = new BoxComment(this.getAPI(), responseJSON.get(\"id\").asString());\n return addedComment.new Info(responseJSON);\n }" ]
Returns the user records for all users in the specified workspace or organization. @param workspace The workspace in which to get users. @return Request object
[ "public CollectionRequest<User> findByWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/users\", workspace);\n return new CollectionRequest<User>(this, User.class, path, \"GET\");\n }" ]
[ "public StateVertex crawlIndex() {\n\t\tLOG.debug(\"Setting up vertex of the index page\");\n\n\t\tif (basicAuthUrl != null) {\n\t\t\tbrowser.goToUrl(basicAuthUrl);\n\t\t}\n\n\t\tbrowser.goToUrl(url);\n\n\t\t// Run url first load plugin to clear the application state\n\t\tplugins.runOnUrlFirstLoadPlugins(context);\n\n\t\tplugins.runOnUrlLoadPlugins(context);\n\t\tStateVertex index = vertexFactory.createIndex(url.toString(), browser.getStrippedDom(),\n\t\t\t\tstateComparator.getStrippedDom(browser), browser);\n\t\tPreconditions.checkArgument(index.getId() == StateVertex.INDEX_ID,\n\t\t\t\t\"It seems some the index state is crawled more than once.\");\n\n\t\tLOG.debug(\"Parsing the index for candidate elements\");\n\t\tImmutableList<CandidateElement> extract = candidateExtractor.extract(index);\n\n\t\tplugins.runPreStateCrawlingPlugins(context, extract, index);\n\n\t\tcandidateActionCache.addActions(extract, index);\n\n\t\treturn index;\n\n\t}", "public static service_stats[] get(nitro_service service) throws Exception{\n\t\tservice_stats obj = new service_stats();\n\t\tservice_stats[] response = (service_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public void setClasspath(Path classpath)\r\n {\r\n if (_classpath == null)\r\n {\r\n _classpath = classpath;\r\n }\r\n else\r\n {\r\n _classpath.append(classpath);\r\n }\r\n log(\"Verification classpath is \"+ _classpath,\r\n Project.MSG_VERBOSE);\r\n }", "public static base_response delete(nitro_service client, route6 resource) throws Exception {\n\t\troute6 deleteresource = new route6();\n\t\tdeleteresource.network = resource.network;\n\t\tdeleteresource.gateway = resource.gateway;\n\t\tdeleteresource.vlan = resource.vlan;\n\t\tdeleteresource.td = resource.td;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public void load(List<E> result) {\n ++pageCount;\n if (this.result == null || this.result.isEmpty()) {\n this.result = result;\n } else {\n this.result.addAll(result);\n }\n }", "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 boolean checkConverged(DMatrixRMaj A) {\n double worst = 0;\n double worst2 = 0;\n for( int j = 0; j < A.numRows; j++ ) {\n double val = Math.abs(q2.data[j] - q0.data[j]);\n if( val > worst ) worst = val;\n val = Math.abs(q2.data[j] + q0.data[j]);\n if( val > worst2 ) worst2 = val;\n }\n\n // swap vectors\n DMatrixRMaj temp = q0;\n q0 = q2;\n q2 = temp;\n\n if( worst < tol )\n return true;\n else if( worst2 < tol )\n return true;\n else\n return false;\n }", "private ClassMatcher buildMatcher(String tagText) {\n\t// check there are at least @match <type> and a parameter\n\tString[] strings = StringUtil.tokenize(tagText);\n\tif (strings.length < 2) {\n\t System.err.println(\"Skipping uncomplete @match tag, type missing: \" + tagText + \" in view \" + viewDoc);\n\t return null;\n\t}\n\t\n\ttry {\n\t if (strings[0].equals(\"class\")) {\n\t\treturn new PatternMatcher(Pattern.compile(strings[1]));\n\t } else if (strings[0].equals(\"context\")) {\n\t\treturn new ContextMatcher(root, Pattern.compile(strings[1]), getGlobalOptions(), \n\t\t\tfalse);\n\t } else if (strings[0].equals(\"outgoingContext\")) {\n\t\treturn new ContextMatcher(root, Pattern.compile(strings[1]), getGlobalOptions(), \n\t\t\tfalse);\n\t } else if (strings[0].equals(\"interface\")) {\n\t\treturn new InterfaceMatcher(root, Pattern.compile(strings[1]));\n\t } else if (strings[0].equals(\"subclass\")) {\n\t\treturn new SubclassMatcher(root, Pattern.compile(strings[1]));\n\t } else {\n\t\tSystem.err.println(\"Skipping @match tag, unknown match type, in view \" + viewDoc);\n\t }\n\t} catch (PatternSyntaxException pse) {\n\t System.err.println(\"Skipping @match tag due to invalid regular expression '\" + tagText\n\t\t + \"'\" + \" in view \" + viewDoc);\n\t} catch (Exception e) {\n\t System.err.println(\"Skipping @match tag due to an internal error '\" + tagText\n\t\t + \"'\" + \" in view \" + viewDoc);\n\t e.printStackTrace();\n\t}\n\treturn null;\n }", "public static base_responses update(nitro_service client, systemuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsystemuser updateresources[] = new systemuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new systemuser();\n\t\t\t\tupdateresources[i].username = resources[i].username;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].externalauth = resources[i].externalauth;\n\t\t\t\tupdateresources[i].promptstring = resources[i].promptstring;\n\t\t\t\tupdateresources[i].timeout = resources[i].timeout;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Build a String representation of given arguments.
[ "protected String buildErrorSetMsg(Object obj, Object value, Field aField)\r\n {\r\n String eol = SystemUtils.LINE_SEPARATOR;\r\n StringBuffer buf = new StringBuffer();\r\n buf\r\n .append(eol + \"[try to set 'object value' in 'target object'\")\r\n .append(eol + \"target obj class: \" + (obj != null ? obj.getClass().getName() : null))\r\n .append(eol + \"target field name: \" + (aField != null ? aField.getName() : null))\r\n .append(eol + \"target field type: \" + (aField != null ? aField.getType() : null))\r\n .append(eol + \"target field declared in: \" + (aField != null ? aField.getDeclaringClass().getName() : null))\r\n .append(eol + \"object value class: \" + (value != null ? value.getClass().getName() : null))\r\n .append(eol + \"object value: \" + (value != null ? value : null))\r\n .append(eol + \"]\");\r\n return buf.toString();\r\n }" ]
[ "public boolean removeCustomResponse(String pathValue, String requestType) {\n try {\n JSONObject path = getPathFromEndpoint(pathValue, requestType);\n if (path == null) {\n return false;\n }\n String pathId = path.getString(\"pathId\");\n return resetResponseOverride(pathId);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "public static base_response add(nitro_service client, nsacl6 resource) throws Exception {\n\t\tnsacl6 addresource = new nsacl6();\n\t\taddresource.acl6name = resource.acl6name;\n\t\taddresource.acl6action = resource.acl6action;\n\t\taddresource.td = resource.td;\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.ttl = resource.ttl;\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.established = resource.established;\n\t\taddresource.icmptype = resource.icmptype;\n\t\taddresource.icmpcode = resource.icmpcode;\n\t\taddresource.priority = resource.priority;\n\t\taddresource.state = resource.state;\n\t\treturn addresource.add_resource(client);\n\t}", "private Duration getAssignmentWork(ProjectCalendar calendar, TimephasedWork assignment)\n {\n Date assignmentStart = assignment.getStart();\n\n Date splitStart = assignmentStart;\n Date splitFinishTime = calendar.getFinishTime(splitStart);\n Date splitFinish = DateHelper.setTime(splitStart, splitFinishTime);\n\n Duration calendarSplitWork = calendar.getWork(splitStart, splitFinish, TimeUnit.MINUTES);\n Duration assignmentWorkPerDay = assignment.getAmountPerDay();\n Duration splitWork;\n\n double splitMinutes = assignmentWorkPerDay.getDuration();\n splitMinutes *= calendarSplitWork.getDuration();\n splitMinutes /= (8 * 60); // this appears to be a fixed value\n splitWork = Duration.getInstance(splitMinutes, TimeUnit.MINUTES);\n return splitWork;\n }", "public static rnat6_nsip6_binding[] get(nitro_service service, String name) throws Exception{\n\t\trnat6_nsip6_binding obj = new rnat6_nsip6_binding();\n\t\tobj.set_name(name);\n\t\trnat6_nsip6_binding response[] = (rnat6_nsip6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public IPv6Address getIPv6Address(IPv6AddressSegment segs[]) {\n\t\tIPv6AddressCreator creator = getIPv6Network().getAddressCreator();\n\t\treturn creator.createAddress(IPv6AddressSection.createSection(creator, segs, this)); /* address creation */\n\t}", "static JDOClass getJDOClass(Class c)\r\n\t{\r\n\t\tJDOClass rc = null;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tJavaModelFactory javaModelFactory = RuntimeJavaModelFactory.getInstance();\r\n\t\t\tJavaModel javaModel = javaModelFactory.getJavaModel(c.getClassLoader());\r\n\t\t\tJDOModel m = JDOModelFactoryImpl.getInstance().getJDOModel(javaModel);\r\n\t\t\trc = m.getJDOClass(c.getName());\r\n\t\t}\r\n\t\tcatch (RuntimeException ex)\r\n\t\t{\r\n\t\t\tthrow new JDOFatalInternalException(\"Not a JDO class: \" + c.getName()); \r\n\t\t}\r\n\t\treturn rc;\r\n\t}", "public void stop() {\n if (accelerometer != null) {\n queue.clear();\n sensorManager.unregisterListener(this, accelerometer);\n sensorManager = null;\n accelerometer = null;\n }\n }", "public void adjustLinks(String sourceFolder, String targetFolder) throws CmsException {\n\n String rootSourceFolder = addSiteRoot(sourceFolder);\n String rootTargetFolder = addSiteRoot(targetFolder);\n String siteRoot = getRequestContext().getSiteRoot();\n getRequestContext().setSiteRoot(\"\");\n try {\n CmsLinkRewriter linkRewriter = new CmsLinkRewriter(this, rootSourceFolder, rootTargetFolder);\n linkRewriter.rewriteLinks();\n } finally {\n getRequestContext().setSiteRoot(siteRoot);\n }\n }", "public static List<BoxTermsOfService.Info> getAllTermsOfServices(final BoxAPIConnection api,\n BoxTermsOfService.TermsOfServiceType\n termsOfServiceType) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (termsOfServiceType != null) {\n builder.appendParam(\"tos_type\", termsOfServiceType.toString());\n }\n\n URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n List<BoxTermsOfService.Info> termsOfServices = new ArrayList<BoxTermsOfService.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject termsOfServiceJSON = value.asObject();\n BoxTermsOfService termsOfService = new BoxTermsOfService(api, termsOfServiceJSON.get(\"id\").asString());\n BoxTermsOfService.Info info = termsOfService.new Info(termsOfServiceJSON);\n termsOfServices.add(info);\n }\n\n return termsOfServices;\n }" ]
Not used.
[ "public void init(Configuration configuration) {\n if (devMode && reload && !listeningToDispatcher) {\n // this is the only way I found to be able to get added to to\n // ConfigurationProvider list\n // listening to events in Dispatcher\n listeningToDispatcher = true;\n Dispatcher.addDispatcherListener(this);\n }\n }" ]
[ "protected boolean isFiltered(AbstractElement canddiate, Param param) {\n\t\tif (canddiate instanceof Group) {\n\t\t\tGroup group = (Group) canddiate;\n\t\t\tif (group.getGuardCondition() != null) {\n\t\t\t\tSet<Parameter> context = param.getAssignedParametes();\n\t\t\t\tConditionEvaluator evaluator = new ConditionEvaluator(context);\n\t\t\t\tif (!evaluator.evaluate(group.getGuardCondition())) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "private void readSubProjects(byte[] data, int uniqueIDOffset, int filePathOffset, int fileNameOffset, int subprojectIndex)\n {\n while (uniqueIDOffset < filePathOffset)\n {\n readSubProject(data, uniqueIDOffset, filePathOffset, fileNameOffset, subprojectIndex++);\n uniqueIDOffset += 4;\n }\n }", "public static void writeFlowId(Message message, String flowId) {\n if (!(message instanceof SoapMessage)) {\n return;\n }\n SoapMessage soapMessage = (SoapMessage)message;\n Header hdFlowId = soapMessage.getHeader(FLOW_ID_QNAME);\n if (hdFlowId != null) {\n LOG.warning(\"FlowId already existing in soap header, need not to write FlowId header.\");\n return;\n }\n\n try {\n soapMessage.getHeaders().add(\n new Header(FLOW_ID_QNAME, flowId, new JAXBDataBinding(String.class)));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Stored flowId '\" + flowId + \"' in soap header: \" + FLOW_ID_QNAME);\n }\n } catch (JAXBException e) {\n LOG.log(Level.SEVERE, \"Couldn't create flowId header.\", e);\n }\n\n }", "private String getStringPredicate(String fieldName, List<String> filterValues, List<Object> prms)\n {\n if (filterValues != null && !filterValues.isEmpty())\n {\n String res = \"\";\n for (String filterValue : filterValues)\n {\n if (filterValue == null)\n {\n continue;\n }\n if (!filterValue.isEmpty())\n {\n prms.add(filterValue);\n if (filterValue.contains(\"%\"))\n {\n res += String.format(\"(%s LIKE ?) OR \", fieldName);\n }\n else\n {\n res += String.format(\"(%s = ?) OR \", fieldName);\n }\n }\n else\n {\n res += String.format(\"(%s IS NULL OR %s = '') OR \", fieldName, fieldName);\n }\n }\n if (!res.isEmpty())\n {\n res = \"AND (\" + res.substring(0, res.length() - 4) + \") \";\n return res;\n }\n }\n return \"\";\n }", "private double sumSquaredDiffs()\n { \n double mean = getArithmeticMean();\n double squaredDiffs = 0;\n for (int i = 0; i < getSize(); i++)\n {\n double diff = mean - dataSet[i];\n squaredDiffs += (diff * diff);\n }\n return squaredDiffs;\n }", "public static final void parseExtendedAttribute(ProjectFile file, FieldContainer mpx, String value, FieldType mpxFieldID, TimeUnit durationFormat)\n {\n if (mpxFieldID != null)\n {\n switch (mpxFieldID.getDataType())\n {\n case STRING:\n {\n mpx.set(mpxFieldID, value);\n break;\n }\n\n case DATE:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeDate(value));\n break;\n }\n\n case CURRENCY:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeCurrency(value));\n break;\n }\n\n case BOOLEAN:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeBoolean(value));\n break;\n }\n\n case NUMERIC:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeNumber(value));\n break;\n }\n\n case DURATION:\n {\n mpx.set(mpxFieldID, parseDuration(file, durationFormat, value));\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n }", "protected static void invalidateSwitchPoints() {\n if (LOG_ENABLED) {\n LOG.info(\"invalidating switch point\");\n }\n \tSwitchPoint old = switchPoint;\n switchPoint = new SwitchPoint();\n synchronized(IndyInterface.class) { SwitchPoint.invalidateAll(new SwitchPoint[]{old}); }\n }", "private Object instanceNotYetLoaded(\n\t\tfinal Tuple resultset,\n\t\tfinal int i,\n\t\tfinal Loadable persister,\n\t\tfinal String rowIdAlias,\n\t\tfinal org.hibernate.engine.spi.EntityKey key,\n\t\tfinal LockMode lockMode,\n\t\tfinal org.hibernate.engine.spi.EntityKey optionalObjectKey,\n\t\tfinal Object optionalObject,\n\t\tfinal List hydratedObjects,\n\t\tfinal SharedSessionContractImplementor session)\n\tthrows HibernateException {\n\t\tfinal String instanceClass = getInstanceClass(\n\t\t\t\tresultset,\n\t\t\t\ti,\n\t\t\t\tpersister,\n\t\t\t\tkey.getIdentifier(),\n\t\t\t\tsession\n\t\t\t);\n\n\t\tfinal Object object;\n\t\tif ( optionalObjectKey != null && key.equals( optionalObjectKey ) ) {\n\t\t\t//its the given optional object\n\t\t\tobject = optionalObject;\n\t\t}\n\t\telse {\n\t\t\t// instantiate a new instance\n\t\t\tobject = session.instantiate( instanceClass, key.getIdentifier() );\n\t\t}\n\n\t\t//need to hydrate it.\n\n\t\t// grab its state from the ResultSet and keep it in the Session\n\t\t// (but don't yet initialize the object itself)\n\t\t// note that we acquire LockMode.READ even if it was not requested\n\t\tLockMode acquiredLockMode = lockMode == LockMode.NONE ? LockMode.READ : lockMode;\n\t\tloadFromResultSet(\n\t\t\t\tresultset,\n\t\t\t\ti,\n\t\t\t\tobject,\n\t\t\t\tinstanceClass,\n\t\t\t\tkey,\n\t\t\t\trowIdAlias,\n\t\t\t\tacquiredLockMode,\n\t\t\t\tpersister,\n\t\t\t\tsession\n\t\t\t);\n\n\t\t//materialize associations (and initialize the object) later\n\t\thydratedObjects.add( object );\n\n\t\treturn object;\n\t}", "public Set<Processor<?, ?>> getAllProcessors() {\n IdentityHashMap<Processor<?, ?>, Void> all = new IdentityHashMap<>();\n for (ProcessorGraphNode<?, ?> root: this.roots) {\n for (Processor p: root.getAllProcessors()) {\n all.put(p, null);\n }\n }\n return all.keySet();\n }" ]
Build a URL with Query String and URL Parameters. @param base base URL @param queryString query string @param values URL Parameters @return URL
[ "public URL buildWithQuery(String base, String queryString, Object... values) {\n String urlString = String.format(base + this.template, values) + queryString;\n URL url = null;\n try {\n url = new URL(urlString);\n } catch (MalformedURLException e) {\n assert false : \"An invalid URL template indicates a bug in the SDK.\";\n }\n\n return url;\n }" ]
[ "public static ModelControllerClient createReceiving(final Channel channel, final ExecutorService executorService) {\n final ManagementClientChannelStrategy strategy = ManagementClientChannelStrategy.create(channel);\n final ManagementChannelHandler handler = new ManagementChannelHandler(strategy, executorService);\n final ExistingChannelModelControllerClient client = new ExistingChannelModelControllerClient(handler);\n handler.addHandlerFactory(client);\n channel.addCloseHandler(new CloseHandler<Channel>() {\n @Override\n public void handleClose(Channel closed, IOException exception) {\n handler.shutdown();\n try {\n handler.awaitCompletion(1, TimeUnit.SECONDS);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n } finally {\n handler.shutdownNow();\n }\n }\n });\n channel.receiveMessage(handler.getReceiver());\n return client;\n }", "public double[] getBasisVector( int which ) {\n if( which < 0 || which >= numComponents )\n throw new IllegalArgumentException(\"Invalid component\");\n\n DMatrixRMaj v = new DMatrixRMaj(1,A.numCols);\n CommonOps_DDRM.extract(V_t,which,which+1,0,A.numCols,v,0,0);\n\n return v.data;\n }", "@Override\n public List<Integer> getReplicatingPartitionList(int index) {\n List<Node> preferenceNodesList = new ArrayList<Node>(getNumReplicas());\n List<Integer> replicationPartitionsList = new ArrayList<Integer>(getNumReplicas());\n\n // Copy Zone based Replication Factor\n HashMap<Integer, Integer> requiredRepFactor = new HashMap<Integer, Integer>();\n requiredRepFactor.putAll(zoneReplicationFactor);\n\n // Cross-check if individual zone replication factor equals global\n int sum = 0;\n for(Integer zoneRepFactor: requiredRepFactor.values()) {\n sum += zoneRepFactor;\n }\n\n if(sum != getNumReplicas())\n throw new IllegalArgumentException(\"Number of zone replicas is not equal to the total replication factor\");\n\n if(getPartitionToNode().length == 0) {\n return new ArrayList<Integer>(0);\n }\n\n for(int i = 0; i < getPartitionToNode().length; i++) {\n // add this one if we haven't already, and it can satisfy some zone\n // replicationFactor\n Node currentNode = getNodeByPartition(index);\n if(!preferenceNodesList.contains(currentNode)) {\n preferenceNodesList.add(currentNode);\n if(checkZoneRequirement(requiredRepFactor, currentNode.getZoneId()))\n replicationPartitionsList.add(index);\n }\n\n // if we have enough, go home\n if(replicationPartitionsList.size() >= getNumReplicas())\n return replicationPartitionsList;\n // move to next clockwise slot on the ring\n index = (index + 1) % getPartitionToNode().length;\n }\n\n // we don't have enough, but that may be okay\n return replicationPartitionsList;\n }", "public BufferedImage toNewBufferedImage(int type) {\n BufferedImage target = new BufferedImage(width, height, type);\n Graphics2D g2 = (Graphics2D) target.getGraphics();\n g2.drawImage(awt, 0, 0, null);\n g2.dispose();\n return target;\n }", "public static void main(String[] args) {\n if (args.length < 2) { // NOSONAR\n LOGGER.error(\"There must be at least two arguments\");\n return;\n }\n int lastIndex = args.length - 1;\n AllureReportGenerator reportGenerator = new AllureReportGenerator(\n getFiles(Arrays.copyOf(args, lastIndex))\n );\n reportGenerator.generate(new File(args[lastIndex]));\n }", "public void setOutlineCode(int index, String value)\n {\n set(selectField(TaskFieldLists.CUSTOM_OUTLINE_CODE, index), value);\n }", "public static servicegroup_stats[] get(nitro_service service, options option) throws Exception{\n\t\tservicegroup_stats obj = new servicegroup_stats();\n\t\tservicegroup_stats[] response = (servicegroup_stats[])obj.stat_resources(service,option);\n\t\treturn response;\n\t}", "public SparqlResult runQuery(String endpoint, String query) {\n return SparqlClient.execute(endpoint, query, username, password);\n }", "public synchronized void unregisterJmxIfRequired() {\n referenceCount--;\n if (isRegistered == true && referenceCount <= 0) {\n JmxUtils.unregisterMbean(this.jmxObjectName);\n isRegistered = false;\n }\n }" ]
Exchanges the final messages which politely report our intention to disconnect from the dbserver.
[ "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 static Integer getDays(String days)\n {\n Integer result = null;\n if (days != null)\n {\n result = Integer.valueOf(Integer.parseInt(days, 2));\n }\n return (result);\n }", "public Double score(final String member) {\n return doWithJedis(new JedisCallable<Double>() {\n @Override\n public Double call(Jedis jedis) {\n return jedis.zscore(getKey(), member);\n }\n });\n }", "void endOfRunDb()\n {\n DbConn cnx = null;\n\n try\n {\n cnx = Helpers.getNewDbSession();\n\n // Done: put inside history & remove instance from queue.\n History.create(cnx, this.ji, this.resultStatus, endDate);\n jqmlogger.trace(\"An History was just created for job instance \" + this.ji.getId());\n cnx.runUpdate(\"ji_delete_by_id\", this.ji.getId());\n cnx.commit();\n }\n catch (RuntimeException e)\n {\n endBlockDbFailureAnalysis(e);\n }\n finally\n {\n Helpers.closeQuietly(cnx);\n }\n }", "public void logAttributeWarning(PathAddress address, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, null, message, attributes));\n }", "public void check(ModelDef modelDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureReferencedKeys(modelDef, checkLevel);\r\n checkReferenceForeignkeys(modelDef, checkLevel);\r\n checkCollectionForeignkeys(modelDef, checkLevel);\r\n checkKeyModifications(modelDef, checkLevel);\r\n }", "protected void recordContentLoader(final String patchID, final PatchContentLoader contentLoader) {\n if (contentLoaders.containsKey(patchID)) {\n throw new IllegalStateException(\"Content loader already registered for patch \" + patchID); // internal wrong usage, no i18n\n }\n contentLoaders.put(patchID, contentLoader);\n }", "private void processSubProjects()\n {\n int subprojectIndex = 1;\n for (Task task : m_project.getTasks())\n {\n String subProjectFileName = task.getSubprojectName();\n if (subProjectFileName != null)\n {\n String fileName = subProjectFileName;\n int offset = 0x01000000 + (subprojectIndex * 0x00400000);\n int index = subProjectFileName.lastIndexOf('\\\\');\n if (index != -1)\n {\n fileName = subProjectFileName.substring(index + 1);\n }\n\n SubProject sp = new SubProject();\n sp.setFileName(fileName);\n sp.setFullPath(subProjectFileName);\n sp.setUniqueIDOffset(Integer.valueOf(offset));\n sp.setTaskUniqueID(task.getUniqueID());\n task.setSubProject(sp);\n\n ++subprojectIndex;\n }\n }\n }", "public void setTimewarpInt(String timewarp) {\n\n try {\n m_userSettings.setTimeWarp(Long.valueOf(timewarp).longValue());\n } catch (Exception e) {\n m_userSettings.setTimeWarp(-1);\n }\n }", "public static base_response update(nitro_service client, cacheselector resource) throws Exception {\n\t\tcacheselector updateresource = new cacheselector();\n\t\tupdateresource.selectorname = resource.selectorname;\n\t\tupdateresource.rule = resource.rule;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Sets the text alignment for all cells in the table. @param textAlignment new text alignment @throws NullPointerException if the argument was null @return this to allow chaining @throws {@link NullPointerException} if the argument was null
[ "public AsciiTable setTextAlignment(TextAlignment textAlignment){\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setTextAlignment(textAlignment);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}" ]
[ "private OJBIterator getReportQueryIteratorFromQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\n {\n RsIteratorFactory factory = ReportRsIteratorFactoryImpl.getInstance();\n OJBIterator result = getRsIteratorFromQuery(query, cld, factory);\n\n if (query.usePaging())\n {\n result = new PagingIterator(result, query.getStartAtIndex(), query.getEndAtIndex());\n }\n\n return result;\n }", "public static long randomLongBetween(long min, long max) {\n Random rand = new Random();\n return min + (long) (rand.nextDouble() * (max - min));\n }", "public LuaPreparedScript endPreparedScriptReturn(LuaValue value, LuaScriptConfig config) {\n add(new LuaAstReturnStatement(argument(value)));\n return endPreparedScript(config);\n }", "protected Violation createViolation(Integer lineNumber, String sourceLine, String message) {\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine(sourceLine);\n violation.setLineNumber(lineNumber);\n violation.setMessage(message);\n return violation;\n }", "protected <T> Request doInvoke(ResponseReader responseReader,\n String methodName, RpcStatsContext statsContext, String requestData,\n AsyncCallback<T> callback) {\n\n RequestBuilder rb = doPrepareRequestBuilderImpl(responseReader, methodName,\n statsContext, requestData, callback);\n\n try {\n return rb.send();\n } catch (RequestException ex) {\n InvocationException iex = new InvocationException(\n \"Unable to initiate the asynchronous service invocation (\" +\n methodName + \") -- check the network connection\",\n ex);\n callback.onFailure(iex);\n } finally {\n if (statsContext.isStatsAvailable()) {\n statsContext.stats(statsContext.bytesStat(methodName,\n requestData.length(), \"requestSent\"));\n }\n }\n return null;\n }", "@Deprecated\n\tpublic static Schedule createScheduleFromConventions(\n\t\t\tLocalDate referenceDate,\n\t\t\tLocalDate startDate,\n\t\t\tString frequency,\n\t\t\tdouble maturity,\n\t\t\tString daycountConvention,\n\t\t\tString shortPeriodConvention,\n\t\t\tString dateRollConvention,\n\t\t\tBusinessdayCalendar businessdayCalendar,\n\t\t\tint\tfixingOffsetDays,\n\t\t\tint\tpaymentOffsetDays\n\t\t\t)\n\t{\n\t\tLocalDate maturityDate = createDateFromDateAndOffset(startDate, maturity);\n\n\t\treturn createScheduleFromConventions(\n\t\t\t\treferenceDate,\n\t\t\t\tstartDate,\n\t\t\t\tmaturityDate,\n\t\t\t\tFrequency.valueOf(frequency.toUpperCase()),\n\t\t\t\tDaycountConvention.getEnum(daycountConvention),\n\t\t\t\tShortPeriodConvention.valueOf(shortPeriodConvention.toUpperCase()),\n\t\t\t\tDateRollConvention.getEnum(dateRollConvention),\n\t\t\t\tbusinessdayCalendar,\n\t\t\t\tfixingOffsetDays,\n\t\t\t\tpaymentOffsetDays\n\t\t\t\t);\n\n\t}", "private void updateArt(TrackMetadataUpdate update, AlbumArt art) {\n hotCache.put(DeckReference.getDeckReference(update.player, 0), art); // Main deck\n if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well\n for (CueList.Entry entry : update.metadata.getCueList().entries) {\n if (entry.hotCueNumber != 0) {\n hotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), art);\n }\n }\n }\n deliverAlbumArtUpdate(update.player, art);\n }", "public Class<? extends MonetaryAmount> getAmountType() {\n Class<?> clazz = get(AMOUNT_TYPE, Class.class);\n return clazz.asSubclass(MonetaryAmount.class);\n }", "private <T> T readIntoBean(final T bean, final String[] nameMapping, final CellProcessor[] processors)\n\t\tthrows IOException {\n\t\t\n\t\tif( readRow() ) {\n\t\t\tif( nameMapping.length != length() ) {\n\t\t\t\tthrow new IllegalArgumentException(String.format(\n\t\t\t\t\t\"the nameMapping array and the number of columns read \"\n\t\t\t\t\t\t+ \"should be the same size (nameMapping length = %d, columns = %d)\", nameMapping.length,\n\t\t\t\t\tlength()));\n\t\t\t}\n\t\t\t\n\t\t\tif( processors == null ) {\n\t\t\t\tprocessedColumns.clear();\n\t\t\t\tprocessedColumns.addAll(getColumns());\n\t\t\t} else {\n\t\t\t\texecuteProcessors(processedColumns, processors);\n\t\t\t}\n\t\t\t\n\t\t\treturn populateBean(bean, nameMapping);\n\t\t}\n\t\t\n\t\treturn null; // EOF\n\t}" ]
If a and b are not null, returns a new duration of a + b. If a is null and b is not null, returns b. If a is not null and b is null, returns a. If a and b are null, returns null. If needed, b is converted to a's time unit using the project properties. @param a first duration @param b second duration @param defaults project properties containing default values @return a + b
[ "public static Duration add(Duration a, Duration b, ProjectProperties defaults)\n {\n if (a == null && b == null)\n {\n return null;\n }\n if (a == null)\n {\n return b;\n }\n if (b == null)\n {\n return a;\n }\n TimeUnit unit = a.getUnits();\n if (b.getUnits() != unit)\n {\n b = b.convertUnits(unit, defaults);\n }\n\n return Duration.getInstance(a.getDuration() + b.getDuration(), unit);\n }" ]
[ "public void editPhotos(String photosetId, String primaryPhotoId, String[] photoIds) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_PHOTOS);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n parameters.put(\"primary_photo_id\", primaryPhotoId);\r\n parameters.put(\"photo_ids\", StringUtilities.join(photoIds, \",\"));\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 }", "public Map<String,Object> getAttributeValues()\n throws AttributeNotFoundException, InstanceNotFoundException, ReflectionException {\n\n HashSet<String> attributeSet = new HashSet<String>();\n\n for (MBeanAttributeInfo attributeInfo : mBeanInfo.getAttributes()) {\n attributeSet.add(attributeInfo.getName());\n }\n\n AttributeList attributeList =\n mBeanServer.getAttributes(objectName, attributeSet.toArray(new String[attributeSet.size()]));\n\n Map<String, Object> attributeValueMap = new TreeMap<String, Object>();\n for (Attribute attribute : attributeList.asList()) {\n attributeValueMap.put(attribute.getName(), sanitizer.escapeValue(attribute.getValue()));\n }\n\n return attributeValueMap;\n }", "public static authenticationvserver_authenticationlocalpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_authenticationlocalpolicy_binding obj = new authenticationvserver_authenticationlocalpolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_authenticationlocalpolicy_binding response[] = (authenticationvserver_authenticationlocalpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static int getJSONColor(final JSONObject json, String elementName) throws JSONException {\n Object raw = json.get(elementName);\n return convertJSONColor(raw);\n }", "public static ExtensibleConfigurationPersister createDomainXmlConfigurationPersister(final ConfigurationFile file, ExecutorService executorService, ExtensionRegistry extensionRegistry, final HostControllerEnvironment environment) {\n DomainXml domainXml = new DomainXml(Module.getBootModuleLoader(), executorService, extensionRegistry);\n\n boolean suppressLoad = false;\n ConfigurationFile.InteractionPolicy policy = file.getInteractionPolicy();\n final boolean isReloaded = environment.getRunningModeControl().isReloaded();\n\n if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW && (file.getBootFile().exists() && file.getBootFile().length() != 0))) {\n throw HostControllerLogger.ROOT_LOGGER.cannotOverwriteDomainXmlWithEmpty(file.getBootFile().getName());\n }\n\n if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW || policy == ConfigurationFile.InteractionPolicy.DISCARD)) {\n suppressLoad = true;\n }\n\n BackupXmlConfigurationPersister persister = new BackupXmlConfigurationPersister(file, new QName(Namespace.CURRENT.getUriString(), \"domain\"), domainXml, domainXml, suppressLoad);\n for (Namespace namespace : Namespace.domainValues()) {\n if (!namespace.equals(Namespace.CURRENT)) {\n persister.registerAdditionalRootElement(new QName(namespace.getUriString(), \"domain\"), domainXml);\n }\n }\n extensionRegistry.setWriterRegistry(persister);\n return persister;\n }", "public void set(float val, Layout.Axis axis) {\n switch (axis) {\n case X:\n x = val;\n break;\n case Y:\n y = val;\n break;\n case Z:\n z = val;\n break;\n default:\n throw new RuntimeAssertion(\"Bad axis specified: %s\", axis);\n }\n }", "public static String termPrefix(String term) {\n int i = term.indexOf(MtasToken.DELIMITER);\n String prefix = term;\n if (i >= 0) {\n prefix = term.substring(0, i);\n }\n return prefix.replace(\"\\u0000\", \"\");\n }", "@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 final void cancelOld(\n final long starttimeThreshold, final long checkTimeThreshold, final String message) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaUpdate<PrintJobStatusExtImpl> update =\n builder.createCriteriaUpdate(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = update.from(PrintJobStatusExtImpl.class);\n update.where(builder.and(\n builder.equal(root.get(\"status\"), PrintJobStatus.Status.WAITING),\n builder.or(\n builder.lessThan(root.get(\"entry\").get(\"startTime\"), starttimeThreshold),\n builder.and(builder.isNotNull(root.get(\"lastCheckTime\")),\n builder.lessThan(root.get(\"lastCheckTime\"), checkTimeThreshold))\n )\n ));\n update.set(root.get(\"status\"), PrintJobStatus.Status.CANCELLED);\n update.set(root.get(\"error\"), message);\n getSession().createQuery(update).executeUpdate();\n }" ]
Use this API to unset the properties of onlinkipv6prefix resource. Properties that need to be unset are specified in args array.
[ "public static base_response unset(nitro_service client, onlinkipv6prefix resource, String[] args) throws Exception{\n\t\tonlinkipv6prefix unsetresource = new onlinkipv6prefix();\n\t\tunsetresource.ipv6prefix = resource.ipv6prefix;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
[ "public CollectionRequest<ProjectMembership> findByProject(String project) {\n \n String path = String.format(\"/projects/%s/project_memberships\", project);\n return new CollectionRequest<ProjectMembership>(this, ProjectMembership.class, path, \"GET\");\n }", "private void verifyApplicationName(String name) {\n if (name == null) {\n throw new IllegalArgumentException(\"Application name cannot be null\");\n }\n if (name.isEmpty()) {\n throw new IllegalArgumentException(\"Application name length must be > 0\");\n }\n String reason = null;\n char[] chars = name.toCharArray();\n char c;\n for (int i = 0; i < chars.length; i++) {\n c = chars[i];\n if (c == 0) {\n reason = \"null character not allowed @\" + i;\n break;\n } else if (c == '/' || c == '.' || c == ':') {\n reason = \"invalid character '\" + c + \"'\";\n break;\n } else if (c > '\\u0000' && c <= '\\u001f' || c >= '\\u007f' && c <= '\\u009F'\n || c >= '\\ud800' && c <= '\\uf8ff' || c >= '\\ufff0' && c <= '\\uffff') {\n reason = \"invalid character @\" + i;\n break;\n }\n }\n if (reason != null) {\n throw new IllegalArgumentException(\n \"Invalid application name \\\"\" + name + \"\\\" caused by \" + reason);\n }\n }", "private void readAssignmentBaselines(Project.Assignments.Assignment assignment, ResourceAssignment mpx)\n {\n for (Project.Assignments.Assignment.Baseline baseline : assignment.getBaseline())\n {\n int number = NumberHelper.getInt(baseline.getNumber());\n\n //baseline.getBCWP()\n //baseline.getBCWS()\n Number cost = DatatypeConverter.parseExtendedAttributeCurrency(baseline.getCost());\n Date finish = DatatypeConverter.parseExtendedAttributeDate(baseline.getFinish());\n //baseline.getNumber()\n Date start = DatatypeConverter.parseExtendedAttributeDate(baseline.getStart());\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork());\n\n if (number == 0)\n {\n mpx.setBaselineCost(cost);\n mpx.setBaselineFinish(finish);\n mpx.setBaselineStart(start);\n mpx.setBaselineWork(work);\n }\n else\n {\n mpx.setBaselineCost(number, cost);\n mpx.setBaselineWork(number, work);\n mpx.setBaselineStart(number, start);\n mpx.setBaselineFinish(number, finish);\n }\n }\n }", "public void setValue(Vector3f scale) {\n mX = scale.x;\n mY = scale.y;\n mZ = scale.z;\n }", "static void showWarning(final String caption, final String description) {\n\n Notification warning = new Notification(caption, description, Type.WARNING_MESSAGE, true);\n warning.setDelayMsec(-1);\n warning.show(UI.getCurrent().getPage());\n\n }", "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 }", "public boolean getBooleanProperty(String name, boolean defaultValue)\r\n {\r\n return PropertyHelper.toBoolean(_properties.getProperty(name), defaultValue);\r\n }", "public static void showBooks(final ListOfBooks booksList){\n \t\n \tif(booksList != null && booksList.getBook() != null && !booksList.getBook().isEmpty()){\n \t\tList<BookType> books = booksList.getBook();\n \t\tSystem.out.println(\"\\nNumber of books: \" + books.size());\n \t\tint cnt = 0;\n \t\tfor (BookType book : books) {\n \t\t\tSystem.out.println(\"\\nBookNum: \" + (cnt++ + 1));\n \t\t\tList<PersonType> authors = book.getAuthor();\n \t\t\tif(authors != null && !authors.isEmpty()){\n \t\t\t\tfor (PersonType author : authors) {\n \t\t\t\t\tSystem.out.println(\"Author: \" + author.getFirstName() + \n \t\t\t\t\t\t\t\t\t\t\" \" + author.getLastName());\n\t\t\t\t\t}\n \t\t\t}\n \t\t\tSystem.out.println(\"Title: \" + book.getTitle());\n \t\t\tSystem.out.println(\"Year: \" + book.getYearPublished());\n \t\t\tif(book.getISBN()!=null){\n \t\t\t\tSystem.out.println(\"ISBN: \" + book.getISBN());\n \t\t\t}\n\t\t\t\t\n\t\t\t}\n \t}else{\n \t\tSystem.out.println(\"List of books is empty\");\n \t}\n \tSystem.out.println(\"\");\n\t}", "public static PropertyResourceBundle getBundle(String baseName, Locale locale) throws UnsupportedEncodingException, IOException{\n\t\tInputStream is = UTF8PropertyResourceBundle.class.getResourceAsStream(\"/\"+baseName + \"_\"+locale.toString()+PROPERTIES_EXT);\n\t\tif(is != null){\n\t\t\treturn new PropertyResourceBundle(new InputStreamReader(is, \"UTF-8\"));\n\t\t}\n\t\treturn null;\n\t}" ]
Reverse how the transition is applied, such that the transition previously performed when progress=start of range is only performed when progress=end of range @return
[ "public T reverse() {\n String id = getId();\n String REVERSE = \"_REVERSE\";\n if (id.endsWith(REVERSE)) {\n setId(id.substring(0, id.length() - REVERSE.length()));\n }\n\n float start = mStart;\n float end = mEnd;\n mStart = end;\n mEnd = start;\n mReverse = !mReverse;\n return self();\n }" ]
[ "public Where<T, ID> raw(String rawStatement, ArgumentHolder... args) {\n\t\tfor (ArgumentHolder arg : args) {\n\t\t\tString columnName = arg.getColumnName();\n\t\t\tif (columnName == null) {\n\t\t\t\tif (arg.getSqlType() == null) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Either the column name or SqlType must be set on each argument\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\targ.setMetaInfo(findColumnFieldType(columnName));\n\t\t\t}\n\t\t}\n\t\taddClause(new Raw(rawStatement, args));\n\t\treturn this;\n\t}", "protected static JRDesignExpression getExpressionFromVariable(JRDesignVariable var){\n\t\tJRDesignExpression exp = new JRDesignExpression();\n\t\texp.setText(\"$V{\" + var.getName() + \"}\");\n\t\texp.setValueClass(var.getValueClass());\n\t\treturn exp;\n\t}", "static String toFormattedString(final String iban) {\n final StringBuilder ibanBuffer = new StringBuilder(iban);\n final int length = ibanBuffer.length();\n\n for (int i = 0; i < length / 4; i++) {\n ibanBuffer.insert((i + 1) * 4 + i, ' ');\n }\n\n return ibanBuffer.toString().trim();\n }", "@SuppressWarnings({\"WeakerAccess\"})\n protected void initDeviceID() {\n getDeviceCachedInfo(); // put this here to avoid running on main thread\n\n // generate a provisional while we do the rest async\n generateProvisionalGUID();\n // grab and cache the googleAdID in any event if available\n // if we already have a deviceID we won't user ad id as the guid\n cacheGoogleAdID();\n\n // if we already have a device ID use it and just notify\n // otherwise generate one, either from ad id if available or the provisional\n String deviceID = getDeviceID();\n if (deviceID == null || deviceID.trim().length() <= 2) {\n generateDeviceID();\n }\n\n }", "public void serializeTimingData(Path outputPath)\n {\n //merge subThreads instances into the main instance\n merge();\n\n try (FileWriter fw = new FileWriter(outputPath.toFile()))\n {\n fw.write(\"Number Of Executions, Total Milliseconds, Milliseconds per execution, Type\\n\");\n for (Map.Entry<String, TimingData> timing : executionInfo.entrySet())\n {\n TimingData data = timing.getValue();\n long totalMillis = (data.totalNanos / 1000000);\n double millisPerExecution = (double) totalMillis / (double) data.numberOfExecutions;\n fw.write(String.format(\"%6d, %6d, %8.2f, %s\\n\",\n data.numberOfExecutions, totalMillis, millisPerExecution,\n StringEscapeUtils.escapeCsv(timing.getKey())\n ));\n }\n }\n catch (Exception e)\n {\n e.printStackTrace();\n }\n }", "protected BoxWatermark getWatermark(URLTemplate itemUrl, String... fields) {\n URL watermarkUrl = itemUrl.build(this.getAPI().getBaseURL(), this.getID());\n QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n URL url = WATERMARK_URL_TEMPLATE.buildWithQuery(watermarkUrl.toString(), builder.toString());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new BoxWatermark(response.getJSON());\n }", "public void setBackgroundColor(int color) {\n setBackgroundColorR(Colors.byteToGl(Color.red(color)));\n setBackgroundColorG(Colors.byteToGl(Color.green(color)));\n setBackgroundColorB(Colors.byteToGl(Color.blue(color)));\n setBackgroundColorA(Colors.byteToGl(Color.alpha(color)));\n }", "public static String getHeaders(HttpMethod method) {\n String headerString = \"\";\n Header[] headers = method.getRequestHeaders();\n for (Header header : headers) {\n String name = header.getName();\n if (name.equals(Constants.ODO_PROXY_HEADER)) {\n // skip.. don't want to log this\n continue;\n }\n\n if (headerString.length() != 0) {\n headerString += \"\\n\";\n }\n\n headerString += header.getName() + \": \" + header.getValue();\n }\n\n return headerString;\n }", "public void showToast(final String message, float duration) {\n final float quadWidth = 1.2f;\n final GVRTextViewSceneObject toastSceneObject = new GVRTextViewSceneObject(this, quadWidth, quadWidth / 5,\n message);\n\n toastSceneObject.setTextSize(6);\n toastSceneObject.setTextColor(Color.WHITE);\n toastSceneObject.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.TOP);\n toastSceneObject.setBackgroundColor(Color.DKGRAY);\n toastSceneObject.setRefreshFrequency(GVRTextViewSceneObject.IntervalFrequency.REALTIME);\n\n final GVRTransform t = toastSceneObject.getTransform();\n t.setPositionZ(-1.5f);\n\n final GVRRenderData rd = toastSceneObject.getRenderData();\n final float finalOpacity = 0.7f;\n rd.getMaterial().setOpacity(0);\n rd.setRenderingOrder(2 * GVRRenderData.GVRRenderingOrder.OVERLAY);\n rd.setDepthTest(false);\n\n final GVRCameraRig rig = getMainScene().getMainCameraRig();\n rig.addChildObject(toastSceneObject);\n\n final GVRMaterialAnimation fadeOut = new GVRMaterialAnimation(rd.getMaterial(), duration / 4.0f) {\n @Override\n protected void animate(GVRHybridObject target, float ratio) {\n final GVRMaterial material = (GVRMaterial) target;\n material.setOpacity(finalOpacity - ratio * finalOpacity);\n }\n };\n fadeOut.setOnFinish(new GVROnFinish() {\n @Override\n public void finished(GVRAnimation animation) {\n rig.removeChildObject(toastSceneObject);\n }\n });\n\n final GVRMaterialAnimation fadeIn = new GVRMaterialAnimation(rd.getMaterial(), 3.0f * duration / 4.0f) {\n @Override\n protected void animate(GVRHybridObject target, float ratio) {\n final GVRMaterial material = (GVRMaterial) target;\n material.setOpacity(ratio * finalOpacity);\n }\n };\n fadeIn.setOnFinish(new GVROnFinish() {\n @Override\n public void finished(GVRAnimation animation) {\n getAnimationEngine().start(fadeOut);\n }\n });\n\n getAnimationEngine().start(fadeIn);\n }" ]
Create a style from a list of rules. @param styleRules the rules
[ "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 static void ensureChildElement(DomXmlElement parentElement, DomXmlElement childElement) {\n Node parent = childElement.unwrap().getParentNode();\n if (parent == null || !parentElement.unwrap().isEqualNode(parent)) {\n throw LOG.elementIsNotChildOfThisElement(childElement, parentElement);\n }\n }", "private void addUserDefinedField(FieldTypeClass fieldType, UserFieldDataType dataType, String name)\n {\n try\n {\n switch (fieldType)\n {\n case TASK:\n TaskField taskField;\n\n do\n {\n taskField = m_taskUdfCounters.nextField(TaskField.class, dataType);\n }\n while (m_taskFields.containsKey(taskField) || m_wbsFields.containsKey(taskField));\n\n m_project.getCustomFields().getCustomField(taskField).setAlias(name);\n\n break;\n case RESOURCE:\n ResourceField resourceField;\n\n do\n {\n resourceField = m_resourceUdfCounters.nextField(ResourceField.class, dataType);\n }\n while (m_resourceFields.containsKey(resourceField));\n\n m_project.getCustomFields().getCustomField(resourceField).setAlias(name);\n\n break;\n case ASSIGNMENT:\n AssignmentField assignmentField;\n\n do\n {\n assignmentField = m_assignmentUdfCounters.nextField(AssignmentField.class, dataType);\n }\n while (m_assignmentFields.containsKey(assignmentField));\n\n m_project.getCustomFields().getCustomField(assignmentField).setAlias(name);\n\n break;\n default:\n break;\n }\n }\n\n catch (Exception ex)\n {\n //\n // SF#227: If we get an exception thrown here... it's likely that\n // we've run out of user defined fields, for example\n // there are only 30 TEXT fields. We'll ignore this: the user\n // defined field won't be mapped to an alias, so we'll\n // ignore it when we read in the values.\n //\n }\n }", "public static boolean setCustomRequestForDefaultClient(String profileName, String pathName, String customData) {\n try {\n return setCustomForDefaultClient(profileName, pathName, false, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "public GVRAndroidResource openResource(String filePath) throws IOException {\n // Error tolerance: Remove initial '/' introduced by file::///filename\n // In this case, the path is interpreted as relative to defaultPath,\n // which is the root of the filesystem.\n if (filePath.startsWith(File.separator)) {\n filePath = filePath.substring(File.separator.length());\n }\n\n filePath = adaptFilePath(filePath);\n String path;\n int resourceId;\n\n GVRAndroidResource resourceKey;\n switch (volumeType) {\n case ANDROID_ASSETS:\n // Resolve '..' and '.'\n path = getFullPath(defaultPath, filePath);\n path = new File(path).getCanonicalPath();\n if (path.startsWith(File.separator)) {\n path = path.substring(1);\n }\n resourceKey = new GVRAndroidResource(gvrContext, path);\n break;\n\n case ANDROID_RESOURCE:\n path = FileNameUtils.getBaseName(filePath);\n resourceId = gvrContext.getContext().getResources().getIdentifier(path, \"raw\", gvrContext.getContext().getPackageName());\n if (resourceId == 0) {\n throw new FileNotFoundException(filePath + \" resource not found\");\n }\n resourceKey = new GVRAndroidResource(gvrContext, resourceId);\n break;\n\n case LINUX_FILESYSTEM:\n resourceKey = new GVRAndroidResource(\n getFullPath(defaultPath, filePath));\n break;\n\n case ANDROID_SDCARD:\n String linuxPath = Environment.getExternalStorageDirectory()\n .getAbsolutePath();\n resourceKey = new GVRAndroidResource(\n getFullPath(linuxPath, defaultPath, filePath));\n break;\n\n case INPUT_STREAM:\n resourceKey = new GVRAndroidResource(getFullPath(defaultPath, filePath), volumeInputStream);\n break;\n\n case NETWORK:\n resourceKey = new GVRAndroidResource(gvrContext,\n getFullURL(defaultPath, filePath), enableUrlLocalCache);\n break;\n\n default:\n throw new IOException(\n String.format(\"Unrecognized volumeType %s\", volumeType));\n }\n return addResource(resourceKey);\n }", "private ClassNode getGenericsResolvedTypeOfFieldOrProperty(AnnotatedNode an, ClassNode type) {\n if (!type.isUsingGenerics()) return type;\n Map<String, GenericsType> connections = new HashMap();\n //TODO: inner classes mean a different this-type. This is ignored here!\n extractGenericsConnections(connections, typeCheckingContext.getEnclosingClassNode(), an.getDeclaringClass());\n type= applyGenericsContext(connections, type);\n return type;\n }", "public boolean link(D declaration, ServiceReference<S> declarationBinderRef) {\n S declarationBinder = bindersManager.getDeclarationBinder(declarationBinderRef);\n LOG.debug(declaration + \" match the filter of \" + declarationBinder + \" : bind them together\");\n declaration.bind(declarationBinderRef);\n try {\n declarationBinder.addDeclaration(declaration);\n } catch (Exception e) {\n declaration.unbind(declarationBinderRef);\n LOG.debug(declarationBinder + \" throw an exception when giving to it the Declaration \"\n + declaration, e);\n return false;\n }\n return true;\n }", "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 }", "public static Artifact createArtifact(final String groupId, final String artifactId, final String version, final String classifier, final String type, final String extension, final String origin){\n\t\tfinal Artifact artifact = new Artifact();\n\n\t\tartifact.setGroupId(groupId);\n\t\tartifact.setArtifactId(artifactId);\n\t\tartifact.setVersion(version);\n\n\t\tif(classifier != null){\n\t\t\tartifact.setClassifier(classifier);\n\t\t}\n\n\t\tif(type != null){\n\t\t\tartifact.setType(type);\n\t\t}\n\n\t\tif(extension != null){\n\t\t\tartifact.setExtension(extension);\n\t\t}\n\n\t\tartifact.setOrigin(origin == null ? \"maven\" : origin);\n\n\t\treturn artifact;\n\t}", "public List<Client> findAllClients(int profileId) throws Exception {\n ArrayList<Client> clients = new ArrayList<Client>();\n\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\"\n );\n query.setInt(1, profileId);\n results = query.executeQuery();\n while (results.next()) {\n clients.add(this.getClientFromResultSet(results));\n }\n } catch (Exception e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n return clients;\n }" ]
Send JSON representation of given data object to all connections tagged with given label @param data the data object @param label the tag label
[ "public void sendJsonToTagged(Object data, String label) {\n sendToTagged(JSON.toJSONString(data), label);\n }" ]
[ "public static void copy(byte[] in, OutputStream out) throws IOException {\n\t\tAssert.notNull(in, \"No input byte array specified\");\n\t\tAssert.notNull(out, \"No OutputStream specified\");\n\t\tout.write(in);\n\t}", "public static base_response change(nitro_service client, appfwsignatures resource) throws Exception {\n\t\tappfwsignatures updateresource = new appfwsignatures();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.mergedefault = resource.mergedefault;\n\t\treturn updateresource.perform_operation(client,\"update\");\n\t}", "private static Iterable<String> splitAndOmitEmpty(final String str, final char splitChar) {\n return new Iterable<String>() {\n @Override\n public Iterator<String> iterator() {\n return new Iterator<String>() {\n\n int startIdx = 0;\n String next = null;\n\n @Override\n public boolean hasNext() {\n while (next == null && startIdx < str.length()) {\n int idx = str.indexOf(splitChar, startIdx);\n if (idx == startIdx) {\n // Omit empty string\n startIdx++;\n continue;\n }\n if (idx >= 0) {\n // Found the next part\n next = str.substring(startIdx, idx);\n startIdx = idx;\n } else {\n // The last part\n if (startIdx < str.length()) {\n next = str.substring(startIdx);\n startIdx = str.length();\n }\n break;\n }\n }\n return next != null;\n }\n\n @Override\n public String next() {\n if (hasNext()) {\n String next = this.next;\n this.next = null;\n return next;\n }\n throw new NoSuchElementException(\"No more element\");\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException(\"Remove not supported\");\n }\n };\n }\n };\n }", "private Object filterValue(Object value)\n {\n if (value instanceof Boolean && !((Boolean) value).booleanValue())\n {\n value = null;\n }\n if (value instanceof String && ((String) value).isEmpty())\n {\n value = null;\n }\n if (value instanceof Double && ((Double) value).doubleValue() == 0.0)\n {\n value = null;\n }\n if (value instanceof Integer && ((Integer) value).intValue() == 0)\n {\n value = null;\n }\n if (value instanceof Duration && ((Duration) value).getDuration() == 0.0)\n {\n value = null;\n }\n\n return value;\n }", "public final void notifyContentItemRangeRemoved(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for content items [0 - \"\n + (contentItemCount - 1) + \"].\");\n }\n notifyItemRangeRemoved(positionStart + headerItemCount, itemCount);\n }", "public FieldType getField()\n {\n FieldType result = null;\n if (m_index < m_fields.length)\n {\n result = m_fields[m_index++];\n }\n\n return result;\n }", "public static ManagementProtocolHeader parse(DataInput input) throws IOException {\n validateSignature(input);\n expectHeader(input, ManagementProtocol.VERSION_FIELD);\n int version = input.readInt();\n expectHeader(input, ManagementProtocol.TYPE);\n byte type = input.readByte();\n switch (type) {\n case ManagementProtocol.TYPE_REQUEST:\n return new ManagementRequestHeader(version, input);\n case ManagementProtocol.TYPE_RESPONSE:\n return new ManagementResponseHeader(version, input);\n case ManagementProtocol.TYPE_BYE_BYE:\n return new ManagementByeByeHeader(version);\n case ManagementProtocol.TYPE_PING:\n return new ManagementPingHeader(version);\n case ManagementProtocol.TYPE_PONG:\n return new ManagementPongHeader(version);\n default:\n throw ProtocolLogger.ROOT_LOGGER.invalidType(\"0x\" + Integer.toHexString(type));\n }\n }", "public void addIterator(OJBIterator iterator)\r\n {\r\n /**\r\n * only add iterators that are not null and non-empty.\r\n */\r\n if (iterator != null)\r\n {\r\n if (iterator.hasNext())\r\n {\r\n setNextIterator();\r\n m_rsIterators.add(iterator);\r\n }\r\n }\r\n }", "public static RelationType getInstance(Locale locale, String type)\n {\n int index = -1;\n\n String[] relationTypes = LocaleData.getStringArray(locale, LocaleData.RELATION_TYPES);\n for (int loop = 0; loop < relationTypes.length; loop++)\n {\n if (relationTypes[loop].equalsIgnoreCase(type) == true)\n {\n index = loop;\n break;\n }\n }\n\n RelationType result = null;\n if (index != -1)\n {\n result = RelationType.getInstance(index);\n }\n\n return (result);\n }" ]
Get unique values form the array. @param values Array of values. @return Unique values.
[ "public static int[] Unique(int[] values) {\r\n HashSet<Integer> lst = new HashSet<Integer>();\r\n for (int i = 0; i < values.length; i++) {\r\n lst.add(values[i]);\r\n }\r\n\r\n int[] v = new int[lst.size()];\r\n Iterator<Integer> it = lst.iterator();\r\n for (int i = 0; i < v.length; i++) {\r\n v[i] = it.next();\r\n }\r\n\r\n return v;\r\n }" ]
[ "public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo info)\r\n\t{\r\n\t\tUtil.log(\"In OTMJCAManagedConnectionFactory.createManagedConnection\");\r\n\t\ttry\r\n\t\t{\r\n\t\t\tKit kit = getKit();\r\n\t\t\tPBKey key = ((OTMConnectionRequestInfo) info).getPbKey();\r\n\t\t\tOTMConnection connection = kit.acquireConnection(key);\r\n\t\t\treturn new OTMJCAManagedConnection(this, connection, key);\r\n\t\t}\r\n\t\tcatch (ResourceException e)\r\n\t\t{\r\n\t\t\tthrow new OTMConnectionRuntimeException(e.getMessage());\r\n\t\t}\r\n\t}", "public static void checkCreateUpload(CmsObject cms, CmsUgcConfiguration config, String name, long size)\n throws CmsUgcException {\n\n if (!config.getUploadParentFolder().isPresent()) {\n String message = Messages.get().container(Messages.ERR_NO_UPLOADS_ALLOWED_0).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errNoUploadAllowed, message);\n }\n\n if (config.getMaxUploadSize().isPresent()) {\n if (config.getMaxUploadSize().get().longValue() < size) {\n String message = Messages.get().container(Messages.ERR_UPLOAD_TOO_BIG_1, name).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errMaxUploadSizeExceeded, message);\n }\n }\n\n if (config.getValidExtensions().isPresent()) {\n List<String> validExtensions = config.getValidExtensions().get();\n boolean foundExtension = false;\n for (String extension : validExtensions) {\n if (name.toLowerCase().endsWith(extension.toLowerCase())) {\n foundExtension = true;\n break;\n }\n }\n if (!foundExtension) {\n String message = Messages.get().container(Messages.ERR_UPLOAD_FILE_EXTENSION_NOT_ALLOWED_1, name).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errInvalidExtension, message);\n }\n }\n }", "public void sendMessageUntilStopCount(int stopCount) {\n\n // always send with valid data.\n for (int i = processedWorkerCount; i < workers.size(); ++i) {\n ActorRef worker = workers.get(i);\n try {\n\n /**\n * !!! This is a must; without this sleep; stuck occured at 5K.\n * AKKA seems cannot handle too much too fast message send out.\n */\n Thread.sleep(1L);\n\n } catch (InterruptedException e) {\n logger.error(\"sleep exception \" + e + \" details: \", e);\n }\n\n // send as if the sender is the origin manager; so reply back to\n // origin manager\n worker.tell(OperationWorkerMsgType.PROCESS_REQUEST, originalManager);\n\n processedWorkerCount++;\n\n if (processedWorkerCount > stopCount) {\n return;\n }\n\n logger.debug(\"REQ_SENT: {} / {} taskId {}\", \n processedWorkerCount, requestTotalCount, taskIdTrim);\n\n }// end for loop\n }", "protected FieldDescriptor resolvePayloadField(Message message) {\n for (FieldDescriptor field : message.getDescriptorForType().getFields()) {\n if (message.hasField(field)) {\n return field;\n }\n }\n\n throw new RuntimeException(\"No payload found in message \" + message);\n }", "private void processActivityCodes(Storepoint storepoint)\n {\n for (Code code : storepoint.getActivityCodes().getCode())\n {\n int sequence = 0;\n for (Value value : code.getValue())\n {\n UUID uuid = getUUID(value.getUuid(), value.getName());\n m_activityCodeValues.put(uuid, value.getName());\n m_activityCodeSequence.put(uuid, Integer.valueOf(++sequence));\n }\n }\n }", "public static int readInt(byte[] bytes, int offset) {\n return (((bytes[offset + 0] & 0xff) << 24) | ((bytes[offset + 1] & 0xff) << 16)\n | ((bytes[offset + 2] & 0xff) << 8) | (bytes[offset + 3] & 0xff));\n }", "private Expression correctClassClassChain(PropertyExpression pe) {\n LinkedList<Expression> stack = new LinkedList<Expression>();\n ClassExpression found = null;\n for (Expression it = pe; it != null; it = ((PropertyExpression) it).getObjectExpression()) {\n if (it instanceof ClassExpression) {\n found = (ClassExpression) it;\n break;\n } else if (!(it.getClass() == PropertyExpression.class)) {\n return pe;\n }\n stack.addFirst(it);\n }\n if (found == null) return pe;\n\n if (stack.isEmpty()) return pe;\n Object stackElement = stack.removeFirst();\n if (!(stackElement.getClass() == PropertyExpression.class)) return pe;\n PropertyExpression classPropertyExpression = (PropertyExpression) stackElement;\n String propertyNamePart = classPropertyExpression.getPropertyAsString();\n if (propertyNamePart == null || !propertyNamePart.equals(\"class\")) return pe;\n\n found.setSourcePosition(classPropertyExpression);\n if (stack.isEmpty()) return found;\n stackElement = stack.removeFirst();\n if (!(stackElement.getClass() == PropertyExpression.class)) return pe;\n PropertyExpression classPropertyExpressionContainer = (PropertyExpression) stackElement;\n\n classPropertyExpressionContainer.setObjectExpression(found);\n return pe;\n }", "public static lbvserver_appflowpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_appflowpolicy_binding obj = new lbvserver_appflowpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_appflowpolicy_binding response[] = (lbvserver_appflowpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@Override\n public final String getString(final int i) {\n String val = this.array.optString(i, null);\n if (val == null) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return val;\n }" ]
Randomize the gradient.
[ "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 static String movePath( final String file,\n final String target ) {\n final String name = new File(file).getName();\n return target.endsWith(\"/\") ? target + name : target + '/' + name;\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}", "public static int[] randomSubset(int k, int n) {\n assert(0 < k && k <= n);\n Random r = new Random();\n int t = 0, m = 0;\n int[] result = new int[k];\n\n while (m < k) {\n double u = r.nextDouble();\n if ( (n - t) * u < k - m ) {\n result[m] = t;\n m++;\n }\n t++;\n }\n return result;\n }", "public static base_response add(nitro_service client, cachepolicylabel resource) throws Exception {\n\t\tcachepolicylabel addresource = new cachepolicylabel();\n\t\taddresource.labelname = resource.labelname;\n\t\taddresource.evaluates = resource.evaluates;\n\t\treturn addresource.add_resource(client);\n\t}", "public Date getStartDate()\n {\n Date result = (Date) getCachedValue(ProjectField.START_DATE);\n if (result == null)\n {\n result = getParentFile().getStartDate();\n }\n return (result);\n }", "@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/{clientUUID}\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> updateClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @PathVariable(\"clientUUID\") String clientUUID,\n @RequestParam(required = false) Boolean active,\n @RequestParam(required = false) String friendlyName,\n @RequestParam(required = false) Boolean reset) throws Exception {\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n if (active != null) {\n logger.info(\"Active: {}\", active);\n clientService.updateActive(profileId, clientUUID, active);\n }\n\n if (friendlyName != null) {\n clientService.setFriendlyName(profileId, clientUUID, friendlyName);\n }\n\n if (reset != null && reset) {\n clientService.reset(profileId, clientUUID);\n }\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"client\", clientService.findClient(clientUUID, profileId));\n return valueHash;\n }", "public String getTextForExpression(DJGroup group, DJGroup childGroup, String type) {\n\t\treturn \"new Double( $V{\" + getReportName() + \"_\" + getGroupVariableName(childGroup) + \"}.doubleValue() / $V{\" + getReportName() + \"_\" + getGroupVariableName(type,group.getColumnToGroupBy().getColumnProperty().getProperty()) + \"}.doubleValue())\";\n\t}", "private void allClustersEqual(final List<String> clusterUrls) {\n Validate.notEmpty(clusterUrls, \"clusterUrls cannot be null\");\n // If only one clusterUrl return immediately\n if (clusterUrls.size() == 1)\n return;\n AdminClient adminClientLhs = adminClientPerCluster.get(clusterUrls.get(0));\n Cluster clusterLhs = adminClientLhs.getAdminClientCluster();\n for (int index = 1; index < clusterUrls.size(); index++) {\n AdminClient adminClientRhs = adminClientPerCluster.get(clusterUrls.get(index));\n Cluster clusterRhs = adminClientRhs.getAdminClientCluster();\n if (!areTwoClustersEqual(clusterLhs, clusterRhs))\n throw new VoldemortException(\"Cluster \" + clusterLhs.getName()\n + \" is not the same as \" + clusterRhs.getName());\n }\n }", "private void writeWBS(Task mpxj)\n {\n if (mpxj.getUniqueID().intValue() != 0)\n {\n WBSType xml = m_factory.createWBSType();\n m_project.getWBS().add(xml);\n String code = mpxj.getWBS();\n code = code == null || code.length() == 0 ? DEFAULT_WBS_CODE : code;\n\n Task parentTask = mpxj.getParentTask();\n Integer parentObjectID = parentTask == null ? null : parentTask.getUniqueID();\n\n xml.setCode(code);\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setName(mpxj.getName());\n\n xml.setObjectId(mpxj.getUniqueID());\n xml.setParentObjectId(parentObjectID);\n xml.setProjectObjectId(PROJECT_OBJECT_ID);\n xml.setSequenceNumber(Integer.valueOf(m_wbsSequence++));\n\n xml.setStatus(\"Active\");\n }\n\n writeChildTasks(mpxj);\n }" ]
Returns sql statement used in this prepared statement together with the parameters. @param sql base sql statement @param logParams parameters to print out @return returns printable statement
[ "public static String fillLogParams(String sql, Map<Object, Object> logParams) {\n\t\tStringBuilder result = new StringBuilder();\n\t\tMap<Object, Object> tmpLogParam = (logParams == null ? new HashMap<Object, Object>() : logParams);\n\n\t\tIterator<Object> it = tmpLogParam.values().iterator();\n\t\tboolean inQuote = false;\n\t\tboolean inQuote2 = false;\n\t\tchar[] sqlChar = sql != null ? sql.toCharArray() : new char[]{};\n\n\t\tfor (int i=0; i < sqlChar.length; i++){\n\t\t\tif (sqlChar[i] == '\\''){\n\t\t\t\tinQuote = !inQuote;\n\t\t\t}\n\t\t\tif (sqlChar[i] == '\"'){\n\t\t\t\tinQuote2 = !inQuote2;\n\t\t\t}\n\n\t\t\tif (sqlChar[i] == '?' && !(inQuote || inQuote2)){\n\t\t\t\tif (it.hasNext()){\n\t\t\t\t\tresult.append(prettyPrint(it.next()));\n\t\t\t\t} else {\n\t\t\t\t\tresult.append('?');\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresult.append(sqlChar[i]);\n\t\t\t}\n\t\t}\n\n\n\t\treturn result.toString();\n\t}" ]
[ "private String toResourceNameOnClasspath(String classPathRootOnDisk, File file) {\n String fileName = file.getAbsolutePath().replace(\"\\\\\", \"/\");\n return fileName.substring(classPathRootOnDisk.length());\n }", "private Map<String, String> parseAttributes(I_CmsXmlContentLocation formatterLoc) {\n\n Map<String, String> result = new LinkedHashMap<>();\n for (I_CmsXmlContentValueLocation mappingLoc : formatterLoc.getSubValues(N_ATTRIBUTE)) {\n String key = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_KEY));\n String value = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_VALUE));\n result.put(key, value);\n }\n return Collections.unmodifiableMap(result);\n }", "private static boolean containsGreekLetter(String s) {\r\n Matcher m = biogreek.matcher(s);\r\n return m.find();\r\n }", "public ReferrerList getPhotosetReferrers(Date date, String domain, String photosetId, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_PHOTOSET_REFERRERS, domain, \"photoset_id\", photosetId, date, perPage, page);\n }", "public static int scale(Double factor, int pixel) {\n return rgb(\n (int) Math.round(factor * red(pixel)),\n (int) Math.round(factor * green(pixel)),\n (int) Math.round(factor * blue(pixel))\n );\n }", "public static String getTypeValue(Class<? extends WindupFrame> clazz)\n {\n TypeValue typeValueAnnotation = clazz.getAnnotation(TypeValue.class);\n if (typeValueAnnotation == null)\n throw new IllegalArgumentException(\"Class \" + clazz.getCanonicalName() + \" lacks a @TypeValue annotation\");\n\n return typeValueAnnotation.value();\n }", "private static void deleteUserDirectories(final File root,\n final FileFilter filter) {\n final File[] dirs = root.listFiles(filter);\n LOGGER.info(\"Identified (\" + dirs.length + \") directories to delete\");\n for (final File dir : dirs) {\n LOGGER.info(\"Deleting \" + dir);\n if (!FileUtils.deleteQuietly(dir)) {\n LOGGER.info(\"Failed to delete directory \" + dir);\n }\n }\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 List<Artifact> getArtifacts(final Boolean hasLicense) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactsPath());\n final ClientResponse response = resource.queryParam(ServerAPI.HAS_LICENSE_PARAM, hasLicense.toString())\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to get artifacts\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(ArtifactList.class);\n }" ]
Prints a currency symbol position value. @param value CurrencySymbolPosition instance @return currency symbol position
[ "public static final String printCurrencySymbolPosition(CurrencySymbolPosition value)\n {\n String result;\n\n switch (value)\n {\n default:\n case BEFORE:\n {\n result = \"0\";\n break;\n }\n\n case AFTER:\n {\n result = \"1\";\n break;\n }\n\n case BEFORE_WITH_SPACE:\n {\n result = \"2\";\n break;\n }\n\n case AFTER_WITH_SPACE:\n {\n result = \"3\";\n break;\n }\n }\n\n return (result);\n }" ]
[ "public static List<List<RTFEmbeddedObject>> getEmbeddedObjects(String text)\n {\n List<List<RTFEmbeddedObject>> objects = null;\n List<RTFEmbeddedObject> objectData;\n\n int offset = text.indexOf(OBJDATA);\n if (offset != -1)\n {\n objects = new LinkedList<List<RTFEmbeddedObject>>();\n\n while (offset != -1)\n {\n objectData = new LinkedList<RTFEmbeddedObject>();\n objects.add(objectData);\n offset = readObjectData(offset, text, objectData);\n offset = text.indexOf(OBJDATA, offset);\n }\n }\n\n return (objects);\n }", "public Headers getAllHeaders() {\n Headers requestHeaders = getHeaders();\n requestHeaders = hasPayload() ? requestHeaders.withContentType(getPayload().get().getMimeType()) : requestHeaders;\n //We don't want to add headers more than once.\n return requestHeaders;\n }", "public static <T> ConflictHandler<T> localWins() {\n return new ConflictHandler<T>() {\n @Override\n public T resolveConflict(\n final BsonValue documentId,\n final ChangeEvent<T> localEvent,\n final ChangeEvent<T> remoteEvent\n ) {\n return localEvent.getFullDocument();\n }\n };\n }", "@JsonProperty(\"descriptions\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, TermImpl> getDescriptionUpdates() {\n \treturn getMonolingualUpdatedValues(newDescriptions);\n }", "public Configuration[] getConfigurations(String name) {\n ArrayList<Configuration> valuesList = new ArrayList<Configuration>();\n\n logger.info(\"Getting data for {}\", name);\n\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n\n String queryString = \"SELECT * FROM \" + Constants.DB_TABLE_CONFIGURATION;\n if (name != null) {\n queryString += \" WHERE \" + Constants.DB_TABLE_CONFIGURATION_NAME + \"=?\";\n }\n\n statement = sqlConnection.prepareStatement(queryString);\n if (name != null) {\n statement.setString(1, name);\n }\n\n results = statement.executeQuery();\n while (results.next()) {\n Configuration config = new Configuration();\n config.setValue(results.getString(Constants.DB_TABLE_CONFIGURATION_VALUE));\n config.setKey(results.getString(Constants.DB_TABLE_CONFIGURATION_NAME));\n config.setId(results.getInt(Constants.GENERIC_ID));\n logger.info(\"the configValue is = {}\", config.getValue());\n valuesList.add(config);\n }\n } catch (SQLException sqe) {\n logger.info(\"Exception in sql\");\n sqe.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n if (valuesList.size() == 0) {\n return null;\n }\n\n return valuesList.toArray(new Configuration[0]);\n }", "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 base_response clear(nitro_service client, nsconfig resource) throws Exception {\n\t\tnsconfig clearresource = new nsconfig();\n\t\tclearresource.force = resource.force;\n\t\tclearresource.level = resource.level;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}", "public static Shell createSubshell(String pathElement, Shell parent, String appName, Object mainHandler,\n MultiMap<String, Object> auxHandlers) {\n\n List<String> newPath = new ArrayList<String>(parent.getPath());\n newPath.add(pathElement);\n\n Shell subshell = new Shell(parent.getSettings().createWithAddedAuxHandlers(auxHandlers),\n new CommandTable(parent.getCommandTable().getNamer()), newPath);\n\n subshell.setAppName(appName);\n subshell.addMainHandler(subshell, \"!\");\n subshell.addMainHandler(new HelpCommandHandler(), \"?\");\n\n subshell.addMainHandler(mainHandler, \"\");\n return subshell;\n }", "public static String readContent(InputStream is) {\n String ret = \"\";\n try {\n String line;\n BufferedReader in = new BufferedReader(new InputStreamReader(is));\n StringBuffer out = new StringBuffer();\n\n while ((line = in.readLine()) != null) {\n out.append(line).append(CARRIAGE_RETURN);\n }\n ret = out.toString();\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return ret;\n }" ]
The method determines if the type can be resolved and if not, will try to guess the qualified name using the information from the imports.
[ "private ClassReference processType(Type type, TypeReferenceLocation typeReferenceLocation, int lineNumber, int columnNumber, int length,\n String line)\n {\n if (type == null)\n return null;\n\n ITypeBinding resolveBinding = type.resolveBinding();\n if (resolveBinding == null)\n {\n ResolveClassnameResult resolvedResult = resolveClassname(type.toString());\n ResolutionStatus status = resolvedResult.found ? ResolutionStatus.RECOVERED : ResolutionStatus.UNRESOLVED;\n PackageAndClassName packageAndClassName = PackageAndClassName.parseFromQualifiedName(resolvedResult.result);\n\n return processTypeAsString(resolvedResult.result, packageAndClassName.packageName, packageAndClassName.className, status,\n typeReferenceLocation, lineNumber,\n columnNumber, length, line);\n }\n else\n {\n return processTypeBinding(type.resolveBinding(), ResolutionStatus.RESOLVED, typeReferenceLocation, lineNumber,\n columnNumber, length, line);\n }\n\n }" ]
[ "public String invokeOperation(String operationName, Map<String, String[]> parameterMap)\n throws JMException, UnsupportedEncodingException {\n MBeanOperationInfo operationInfo = getOperationInfo(operationName);\n MBeanOperationInvoker invoker = createMBeanOperationInvoker(mBeanServer, objectName, operationInfo);\n return sanitizer.escapeValue(invoker.invokeOperation(parameterMap));\n }", "private void logUnexpectedStructure()\n {\n if (m_log != null)\n {\n m_log.println(\"ABORTED COLUMN - unexpected structure: \" + m_currentColumn.getClass().getSimpleName() + \" \" + m_currentColumn.getName());\n }\n }", "public History getHistoryForID(int id) {\n History history = null;\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.GENERIC_ID + \"=?\");\n query.setInt(1, id);\n\n logger.info(\"Query: {}\", query.toString());\n results = query.executeQuery();\n if (results.next()) {\n history = historyFromSQLResult(results, true, ScriptService.getInstance().getScripts(Constants.SCRIPT_TYPE_HISTORY));\n }\n query.close();\n } catch (Exception e) {\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n return history;\n }", "public void recordResourceRequestQueueLength(SocketDestination dest, int queueLength) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordResourceRequestQueueLength(null, queueLength);\n recordResourceRequestQueueLength(null, queueLength);\n } else {\n this.resourceRequestQueueLengthHistogram.insert(queueLength);\n checkMonitoringInterval();\n }\n }", "private void processCalendarData(List<ProjectCalendar> calendars) throws SQLException\n {\n for (ProjectCalendar calendar : calendars)\n {\n processCalendarData(calendar, getRows(\"SELECT * FROM MSP_CALENDAR_DATA WHERE PROJ_ID=? AND CAL_UID=?\", m_projectID, calendar.getUniqueID()));\n }\n }", "protected void setColumnsFinalWidth() {\n log.debug(\"Setting columns final width.\");\n float factor;\n int printableArea = report.getOptions().getColumnWidth();\n\n //Create a list with only the visible columns.\n List visibleColums = getVisibleColumns();\n\n\n if (report.getOptions().isUseFullPageWidth()) {\n int columnsWidth = 0;\n int notRezisableWidth = 0;\n\n //Store in a variable the total with of all visible columns\n for (Object visibleColum : visibleColums) {\n AbstractColumn col = (AbstractColumn) visibleColum;\n columnsWidth += col.getWidth();\n if (col.isFixedWidth())\n notRezisableWidth += col.getWidth();\n }\n\n\n factor = (float) (printableArea - notRezisableWidth) / (float) (columnsWidth - notRezisableWidth);\n\n log.debug(\"printableArea = \" + printableArea\n + \", columnsWidth = \" + columnsWidth\n + \", columnsWidth = \" + columnsWidth\n + \", notRezisableWidth = \" + notRezisableWidth\n + \", factor = \" + factor);\n\n int acumulated = 0;\n int colFinalWidth;\n\n //Select the non-resizable columns\n Collection resizableColumns = CollectionUtils.select(visibleColums, new Predicate() {\n public boolean evaluate(Object arg0) {\n return !((AbstractColumn) arg0).isFixedWidth();\n }\n\n });\n\n //Finally, set the new width to the resizable columns\n for (Iterator iter = resizableColumns.iterator(); iter.hasNext(); ) {\n AbstractColumn col = (AbstractColumn) iter.next();\n\n if (!iter.hasNext()) {\n col.setWidth(printableArea - notRezisableWidth - acumulated);\n } else {\n colFinalWidth = (new Float(col.getWidth() * factor)).intValue();\n acumulated += colFinalWidth;\n col.setWidth(colFinalWidth);\n }\n }\n }\n\n // If the columns width changed, the X position must be setted again.\n int posx = 0;\n for (Object visibleColum : visibleColums) {\n AbstractColumn col = (AbstractColumn) visibleColum;\n col.setPosX(posx);\n posx += col.getWidth();\n }\n }", "public void clearSources()\n {\n synchronized (mAudioSources)\n {\n for (GVRAudioSource source : mAudioSources)\n {\n source.setListener(null);\n }\n mAudioSources.clear();\n }\n }", "public void unlock() {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", \"lock\").toString();\n URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject lockObject = new JsonObject();\n lockObject.add(\"lock\", JsonObject.NULL);\n\n request.setBody(lockObject.toString());\n request.send();\n }", "public static BatchASTFuture analyze(final BatchASTListener listener, final WildcardImportResolver importResolver,\n final Set<String> libraryPaths,\n final Set<String> sourcePaths, Set<Path> sourceFiles)\n {\n\n final String[] encodings = null;\n final String[] bindingKeys = new String[0];\n final ExecutorService executor = WindupExecutors.newFixedThreadPool(WindupExecutors.getDefaultThreadCount());\n final FileASTRequestor requestor = new FileASTRequestor()\n {\n @Override\n public void acceptAST(String sourcePath, CompilationUnit ast)\n {\n try\n {\n /*\n * This super() call doesn't do anything, but we call it just to be nice, in case that ever changes.\n */\n super.acceptAST(sourcePath, ast);\n ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, ast, sourcePath);\n ast.accept(visitor);\n listener.processed(Paths.get(sourcePath), visitor.getJavaClassReferences());\n }\n catch (WindupStopException ex)\n {\n throw ex;\n }\n catch (Throwable t)\n {\n listener.failed(Paths.get(sourcePath), t);\n }\n }\n };\n\n List<List<String>> batches = createBatches(sourceFiles);\n\n for (final List<String> batch : batches)\n {\n executor.submit(new Callable<Void>()\n {\n @Override\n public Void call() throws Exception\n {\n ASTParser parser = ASTParser.newParser(AST.JLS8);\n parser.setBindingsRecovery(false);\n parser.setResolveBindings(true);\n Map<String, String> options = JavaCore.getOptions();\n JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);\n // these options seem to slightly reduce the number of times that JDT aborts on compilation errors\n options.put(JavaCore.CORE_INCOMPLETE_CLASSPATH, \"warning\");\n options.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, \"warning\");\n options.put(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, \"warning\");\n options.put(JavaCore.CORE_CIRCULAR_CLASSPATH, \"warning\");\n options.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, \"warning\");\n options.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION, \"warning\");\n options.put(JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, \"ignore\");\n options.put(JavaCore.COMPILER_PB_NULL_ANNOTATION_INFERENCE_CONFLICT, \"warning\");\n options.put(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, \"warning\");\n options.put(JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, \"warning\");\n\n parser.setCompilerOptions(options);\n parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]),\n sourcePaths.toArray(new String[sourcePaths.size()]),\n null,\n true);\n\n parser.createASTs(batch.toArray(new String[batch.size()]), encodings, bindingKeys, requestor, null);\n return null;\n }\n });\n }\n\n executor.shutdown();\n\n return new BatchASTFuture()\n {\n @Override\n public boolean isDone()\n {\n return executor.isTerminated();\n }\n };\n }" ]
Determines whether the given type is an array type. @param type the given type @return true if the given type is a subclass of java.lang.Class or implements GenericArrayType
[ "public static boolean isArray(Type type) {\n return (type instanceof GenericArrayType) || (type instanceof Class<?> && ((Class<?>) type).isArray());\n }" ]
[ "public static int e(ISubsystem subsystem, String tag, String msg) {\n return isEnabled(subsystem) ?\n currentLog.e(tag, getMsg(subsystem,msg)) : 0;\n }", "public void writeTo(IIMWriter writer) throws IOException {\r\n\t\tfinal boolean doLog = log != null;\r\n\t\tfor (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) {\r\n\t\t\tDataSet ds = i.next();\r\n\t\t\twriter.write(ds);\r\n\t\t\tif (doLog) {\r\n\t\t\t\tlog.debug(\"Wrote data set \" + ds);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "private long getTotalUploadSize() throws IOException {\n long size = 0;\n for (Map.Entry<String, File> entry : files.entrySet()) {\n size += entry.getValue().length();\n }\n\n for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {\n size += entry.getValue().available();\n }\n return size;\n }", "public Where<T, ID> isNull(String columnName) throws SQLException {\n\t\taddClause(new IsNull(columnName, findColumnFieldType(columnName)));\n\t\treturn this;\n\t}", "public static BoxConfig readFrom(Reader reader) throws IOException {\n JsonObject config = JsonObject.readFrom(reader);\n JsonObject settings = (JsonObject) config.get(\"boxAppSettings\");\n String clientId = settings.get(\"clientID\").asString();\n String clientSecret = settings.get(\"clientSecret\").asString();\n JsonObject appAuth = (JsonObject) settings.get(\"appAuth\");\n String publicKeyId = appAuth.get(\"publicKeyID\").asString();\n String privateKey = appAuth.get(\"privateKey\").asString();\n String passphrase = appAuth.get(\"passphrase\").asString();\n String enterpriseId = config.get(\"enterpriseID\").asString();\n return new BoxConfig(clientId, clientSecret, enterpriseId, publicKeyId, privateKey, passphrase);\n }", "public static String getFlowContext() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.flowContext;\n }", "public Set<? extends AbstractBean<?, ?>> resolveSpecializedBeans(Bean<?> specializingBean) {\n if (specializingBean instanceof AbstractClassBean<?>) {\n AbstractClassBean<?> abstractClassBean = (AbstractClassBean<?>) specializingBean;\n if (abstractClassBean.isSpecializing()) {\n return specializedBeans.getValue(specializingBean);\n }\n }\n if (specializingBean instanceof ProducerMethod<?, ?>) {\n ProducerMethod<?, ?> producerMethod = (ProducerMethod<?, ?>) specializingBean;\n if (producerMethod.isSpecializing()) {\n return specializedBeans.getValue(specializingBean);\n }\n }\n return Collections.emptySet();\n }", "public void fireCalendarWrittenEvent(ProjectCalendar calendar)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.calendarWritten(calendar);\n }\n }\n }", "public Object getProperty(String property) {\n if(ExpandoMetaClass.isValidExpandoProperty(property)) {\n if(property.equals(ExpandoMetaClass.STATIC_QUALIFIER) ||\n property.equals(ExpandoMetaClass.CONSTRUCTOR) ||\n myMetaClass.hasProperty(this, property) == null) {\n return replaceDelegate().getProperty(property);\n }\n }\n return myMetaClass.getProperty(this, property);\n }" ]
Alias accessor provided for JSON serialization only
[ "@JsonProperty(\"aliases\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, List<TermImpl>> getAliasUpdates() {\n \t\n \tMap<String, List<TermImpl>> updatedValues = new HashMap<>();\n \tfor(Map.Entry<String,AliasesWithUpdate> entry : newAliases.entrySet()) {\n \t\tAliasesWithUpdate update = entry.getValue();\n \t\tif (!update.write) {\n \t\t\tcontinue;\n \t\t}\n \t\tList<TermImpl> convertedAliases = new ArrayList<>();\n \t\tfor(MonolingualTextValue alias : update.aliases) {\n \t\t\tconvertedAliases.add(monolingualToJackson(alias));\n \t\t}\n \t\tupdatedValues.put(entry.getKey(), convertedAliases);\n \t}\n \treturn updatedValues;\n }" ]
[ "public void setIntVec(IntBuffer data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input buffer for indices cannot be null\");\n }\n if (getIndexSize() != 4)\n {\n throw new UnsupportedOperationException(\"Cannot update integer indices with short array\");\n }\n if (data.isDirect())\n {\n if (!NativeIndexBuffer.setIntVec(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input array is wrong size\");\n }\n }\n else if (data.hasArray())\n {\n if (!NativeIndexBuffer.setIntArray(getNative(), data.array()))\n {\n throw new IllegalArgumentException(\"Data array incompatible with index buffer\");\n }\n }\n else\n {\n throw new UnsupportedOperationException(\"IntBuffer type not supported. Must be direct or have backing array\");\n }\n }", "@PreDestroy\n public final void dispose() {\n getConnectionPool().ifPresent(PoolResources::dispose);\n getThreadPool().dispose();\n\n try {\n ObjectName name = getByteBufAllocatorObjectName();\n\n if (ManagementFactory.getPlatformMBeanServer().isRegistered(name)) {\n ManagementFactory.getPlatformMBeanServer().unregisterMBean(name);\n }\n } catch (JMException e) {\n this.logger.error(\"Unable to register ByteBufAllocator MBean\", e);\n }\n }", "public static <X> ServiceTypeLoader<X> load(Class<X> serviceType) {\n return load(serviceType, Thread.currentThread().getContextClassLoader());\n }", "public final ProcessorDependencyGraph getProcessorGraph() {\n if (this.processorGraph == null) {\n synchronized (this) {\n if (this.processorGraph == null) {\n final Map<String, Class<?>> attcls = new HashMap<>();\n for (Map.Entry<String, Attribute> attribute: this.attributes.entrySet()) {\n attcls.put(attribute.getKey(), attribute.getValue().getValueType());\n }\n this.processorGraph = this.processorGraphFactory.build(this.processors, attcls);\n }\n }\n }\n return this.processorGraph;\n }", "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 boolean runOnMainThreadNext(Runnable r) {\n assert handler != null;\n\n if (!sanityCheck(\"runOnMainThreadNext \" + r)) {\n return false;\n }\n return handler.post(r);\n }", "protected Object[] getFieldObjects(Object data) throws SQLException {\n\t\tObject[] objects = new Object[argFieldTypes.length];\n\t\tfor (int i = 0; i < argFieldTypes.length; i++) {\n\t\t\tFieldType fieldType = argFieldTypes[i];\n\t\t\tif (fieldType.isAllowGeneratedIdInsert()) {\n\t\t\t\tobjects[i] = fieldType.getFieldValueIfNotDefault(data);\n\t\t\t} else {\n\t\t\t\tobjects[i] = fieldType.extractJavaFieldToSqlArgValue(data);\n\t\t\t}\n\t\t\tif (objects[i] == null) {\n\t\t\t\t// NOTE: the default value could be null as well\n\t\t\t\tobjects[i] = fieldType.getDefaultValue();\n\t\t\t}\n\t\t}\n\t\treturn objects;\n\t}", "@Deprecated\n public FluoConfiguration clearObservers() {\n Iterator<String> iter1 = getKeys(OBSERVER_PREFIX.substring(0, OBSERVER_PREFIX.length() - 1));\n while (iter1.hasNext()) {\n String key = iter1.next();\n clearProperty(key);\n }\n\n return this;\n }", "public Collection<QName> getPortComponentQNames()\n {\n //TODO:Check if there is just one QName that drives all portcomponents\n //or each port component can have a distinct QName (namespace/prefix)\n //Maintain uniqueness of the QName\n Map<String, QName> map = new HashMap<String, QName>();\n for (PortComponentMetaData pcm : portComponents)\n {\n QName qname = pcm.getWsdlPort();\n map.put(qname.getPrefix(), qname);\n }\n return map.values();\n }" ]
close the AdminPool, if no long required. After closed, all public methods will throw IllegalStateException
[ "public void close() {\n boolean isPreviouslyClosed = isClosed.getAndSet(true);\n if (isPreviouslyClosed) {\n return;\n }\n\n AdminClient client;\n while ((client = clientCache.poll()) != null) {\n client.close();\n }\n }" ]
[ "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 }", "private void updateRoutingStrategies(Cluster cluster, List<StoreDefinition> storeDefs) {\n // acquire write lock\n writeLock.lock();\n try {\n VectorClock clock = new VectorClock();\n if(metadataCache.containsKey(ROUTING_STRATEGY_KEY))\n clock = (VectorClock) metadataCache.get(ROUTING_STRATEGY_KEY).getVersion();\n\n logger.info(\"Updating routing strategy for all stores\");\n HashMap<String, StoreDefinition> storeDefMap = makeStoreDefinitionMap(storeDefs);\n HashMap<String, RoutingStrategy> routingStrategyMap = createRoutingStrategyMap(cluster,\n storeDefMap);\n this.metadataCache.put(ROUTING_STRATEGY_KEY,\n new Versioned<Object>(routingStrategyMap,\n clock.incremented(getNodeId(),\n System.currentTimeMillis())));\n\n for(String storeName: storeNameTolisteners.keySet()) {\n RoutingStrategy updatedRoutingStrategy = routingStrategyMap.get(storeName);\n if(updatedRoutingStrategy != null) {\n try {\n for(MetadataStoreListener listener: storeNameTolisteners.get(storeName)) {\n listener.updateRoutingStrategy(updatedRoutingStrategy);\n listener.updateStoreDefinition(storeDefMap.get(storeName));\n }\n } catch(Exception e) {\n if(logger.isEnabledFor(Level.WARN))\n logger.warn(e, e);\n }\n }\n\n }\n } finally {\n writeLock.unlock();\n }\n }", "public Formation scale(String appName, String processType, int quantity) {\n return connection.execute(new FormationUpdate(appName, processType, quantity), apiKey);\n }", "public ModelNode buildRequest() throws OperationFormatException {\n\n ModelNode address = request.get(Util.ADDRESS);\n if(prefix.isEmpty()) {\n address.setEmptyList();\n } else {\n Iterator<Node> iterator = prefix.iterator();\n while (iterator.hasNext()) {\n OperationRequestAddress.Node node = iterator.next();\n if (node.getName() != null) {\n address.add(node.getType(), node.getName());\n } else if (iterator.hasNext()) {\n throw new OperationFormatException(\n \"The node name is not specified for type '\"\n + node.getType() + \"'\");\n }\n }\n }\n\n if(!request.hasDefined(Util.OPERATION)) {\n throw new OperationFormatException(\"The operation name is missing or the format of the operation request is wrong.\");\n }\n\n return request;\n }", "public static ipseccounters_stats get(nitro_service service) throws Exception{\n\t\tipseccounters_stats obj = new ipseccounters_stats();\n\t\tipseccounters_stats[] response = (ipseccounters_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}", "public void growMaxColumns( int desiredColumns , boolean preserveValue ) {\n if( col_idx.length < desiredColumns+1 ) {\n int[] c = new int[ desiredColumns+1 ];\n if( preserveValue )\n System.arraycopy(col_idx,0,c,0,col_idx.length);\n col_idx = c;\n }\n }", "private void resetStoreDefinitions(Set<String> storeNamesToDelete) {\n // Clear entries in the metadata cache\n for(String storeName: storeNamesToDelete) {\n this.metadataCache.remove(storeName);\n this.storeDefinitionsStorageEngine.delete(storeName, null);\n this.storeNames.remove(storeName);\n }\n }", "public static String fill(int color) {\n final String colorCode = Integer.toHexString(color & 0xFFFFFF); // Strip alpha\n return FILTER_FILL + \"(\" + colorCode + \")\";\n }", "public void setColorInterpolated(int index, int firstIndex, int lastIndex, int color) {\n\t\tint firstColor = map[firstIndex];\n\t\tint lastColor = map[lastIndex];\n\t\tfor (int i = firstIndex; i <= index; i++)\n\t\t\tmap[i] = ImageMath.mixColors((float)(i-firstIndex)/(index-firstIndex), firstColor, color);\n\t\tfor (int i = index; i < lastIndex; i++)\n\t\t\tmap[i] = ImageMath.mixColors((float)(i-index)/(lastIndex-index), color, lastColor);\n\t}" ]
Fetch the given image from the web. @param request The request @param transformer The transformer @return The image
[ "protected BufferedImage fetchImage(\n @Nonnull final ClientHttpRequest request, @Nonnull final MapfishMapContext transformer)\n throws IOException {\n final String baseMetricName = getClass().getName() + \".read.\" +\n StatsUtils.quotePart(request.getURI().getHost());\n final Timer.Context timerDownload = this.registry.timer(baseMetricName).time();\n try (ClientHttpResponse httpResponse = request.execute()) {\n if (httpResponse.getStatusCode() != HttpStatus.OK) {\n final String message = String.format(\n \"Invalid status code for %s (%d!=%d). The response was: '%s'\",\n request.getURI(), httpResponse.getStatusCode().value(),\n HttpStatus.OK.value(), httpResponse.getStatusText());\n this.registry.counter(baseMetricName + \".error\").inc();\n if (getFailOnError()) {\n throw new RuntimeException(message);\n } else {\n LOGGER.info(message);\n return createErrorImage(transformer.getPaintArea());\n }\n }\n\n final List<String> contentType = httpResponse.getHeaders().get(\"Content-Type\");\n if (contentType == null || contentType.size() != 1) {\n LOGGER.debug(\"The image {} didn't return a valid content type header.\",\n request.getURI());\n } else if (!contentType.get(0).startsWith(\"image/\")) {\n final byte[] data;\n try (InputStream body = httpResponse.getBody()) {\n data = IOUtils.toByteArray(body);\n }\n LOGGER.debug(\"We get a wrong image for {}, content type: {}\\nresult:\\n{}\",\n request.getURI(), contentType.get(0),\n new String(data, StandardCharsets.UTF_8));\n this.registry.counter(baseMetricName + \".error\").inc();\n return createErrorImage(transformer.getPaintArea());\n }\n\n final BufferedImage image = ImageIO.read(httpResponse.getBody());\n if (image == null) {\n LOGGER.warn(\"Cannot read image from %a\", request.getURI());\n this.registry.counter(baseMetricName + \".error\").inc();\n if (getFailOnError()) {\n throw new RuntimeException(\"Cannot read image from \" + request.getURI());\n } else {\n return createErrorImage(transformer.getPaintArea());\n }\n }\n timerDownload.stop();\n return image;\n } catch (Throwable e) {\n this.registry.counter(baseMetricName + \".error\").inc();\n throw e;\n }\n }" ]
[ "@SuppressWarnings({\"unchecked\", \"unused\"})\n public static <T> T[] object2Array(final Class<T> clazz, final Object obj) {\n return (T[]) obj;\n }", "public VALUE put(KEY key, VALUE object) {\n CacheEntry<VALUE> entry;\n if (referenceType == ReferenceType.WEAK) {\n entry = new CacheEntry<>(new WeakReference<>(object), null);\n } else if (referenceType == ReferenceType.SOFT) {\n entry = new CacheEntry<>(new SoftReference<>(object), null);\n } else {\n entry = new CacheEntry<>(null, object);\n }\n\n countPutCountSinceEviction++;\n countPut++;\n if (isExpiring && nextCleanUpTimestamp == 0) {\n nextCleanUpTimestamp = System.currentTimeMillis() + expirationMillis + 1;\n }\n\n CacheEntry<VALUE> oldEntry;\n synchronized (this) {\n if (values.size() >= maxSize) {\n evictToTargetSize(maxSize - 1);\n }\n oldEntry = values.put(key, entry);\n }\n return getValueForRemoved(oldEntry);\n }", "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 }", "@Deprecated\n public void validateOperation(final ModelNode operation) throws OperationFailedException {\n if (operation.hasDefined(ModelDescriptionConstants.OPERATION_NAME) && deprecationData != null && deprecationData.isNotificationUseful()) {\n ControllerLogger.DEPRECATED_LOGGER.operationDeprecated(getName(),\n PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)).toCLIStyleString());\n }\n for (AttributeDefinition ad : this.parameters) {\n ad.validateOperation(operation);\n }\n }", "public String getValueSchema() throws IOException {\n Schema schema = getInputPathAvroSchema();\n String valueSchema = schema.getField(valueFieldName).schema().toString();\n return valueSchema;\n }", "@SuppressWarnings(\"serial\")\n private Button createSaveExitButton() {\n\n Button saveExitBtn = CmsToolBar.createButton(\n FontOpenCms.SAVE_EXIT,\n m_messages.key(Messages.GUI_BUTTON_SAVE_AND_EXIT_0));\n saveExitBtn.addClickListener(new ClickListener() {\n\n public void buttonClick(ClickEvent event) {\n\n saveAction();\n closeAction();\n\n }\n });\n saveExitBtn.setEnabled(false);\n return saveExitBtn;\n }", "protected boolean determineFeatureState(final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, boolean defaultState) {\n final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(context.getConfiguration());\n final IStandardExpression expression = expressionParser.parseExpression(context, attributeValue);\n final Object value = expression.execute(context);\n if (value != null) {\n return isFeatureActive(value.toString());\n }\n else {\n return defaultState;\n }\n }", "public void drawGeometry(Geometry geometry, SymbolInfo symbol, Color fillColor, Color strokeColor, float lineWidth,\n\t\t\tfloat[] dashArray, Rectangle clipRect) {\n\t\ttemplate.saveState();\n\t\t// clipping code\n\t\tif (clipRect != null) {\n\t\t\ttemplate.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(), clipRect\n\t\t\t\t\t.getHeight());\n\t\t\ttemplate.clip();\n\t\t\ttemplate.newPath();\n\t\t}\n\t\tsetStroke(strokeColor, lineWidth, dashArray);\n\t\tsetFill(fillColor);\n\t\tdrawGeometry(geometry, symbol);\n\t\ttemplate.restoreState();\n\t}", "public void updateExceptions() {\n\n m_exceptionsList.setDates(m_model.getExceptions());\n if (m_model.getExceptions().size() > 0) {\n m_exceptionsPanel.setVisible(true);\n } else {\n m_exceptionsPanel.setVisible(false);\n }\n }" ]
Get a prefix for the log message to help identify which request is which and which responses belong to which requests.
[ "private String getLogRequestIdentifier() {\n if (logIdentifier == null) {\n logIdentifier = String.format(\"%s-%s %s %s\", Integer.toHexString(hashCode()),\n numberOfRetries, connection.getRequestMethod(), connection.getURL());\n }\n return logIdentifier;\n }" ]
[ "private void processFile(InputStream is) throws MPXJException\n {\n int line = 1;\n\n try\n {\n //\n // Test the header and extract the separator. If this is successful,\n // we reset the stream back as far as we can. The design of the\n // BufferedInputStream class means that we can't get back to character\n // zero, so the first record we will read will get \"RMHDR\" rather than\n // \"ERMHDR\" in the first field position.\n //\n BufferedInputStream bis = new BufferedInputStream(is);\n byte[] data = new byte[6];\n data[0] = (byte) bis.read();\n bis.mark(1024);\n bis.read(data, 1, 5);\n\n if (!new String(data).equals(\"ERMHDR\"))\n {\n throw new MPXJException(MPXJException.INVALID_FILE);\n }\n\n bis.reset();\n\n InputStreamReader reader = new InputStreamReader(bis, getCharset());\n Tokenizer tk = new ReaderTokenizer(reader);\n tk.setDelimiter('\\t');\n List<String> record = new ArrayList<String>();\n\n while (tk.getType() != Tokenizer.TT_EOF)\n {\n readRecord(tk, record);\n if (!record.isEmpty())\n {\n if (processRecord(record))\n {\n break;\n }\n }\n ++line;\n }\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(MPXJException.READ_ERROR + \" (failed at line \" + line + \")\", ex);\n }\n }", "private String formatDate(Date date) {\n\n if (null == m_dateFormat) {\n m_dateFormat = DateFormat.getDateInstance(\n 0,\n OpenCms.getWorkplaceManager().getWorkplaceLocale(getCmsObject()));\n }\n return m_dateFormat.format(date);\n }", "public int scrollToItem(int position) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToItem position = %d\", position);\n scrollToPosition(position);\n return mCurrentItemIndex;\n }", "public ItemRequest<ProjectStatus> createInProject(String project) {\n\n String path = String.format(\"/projects/%s/project_statuses\", project);\n return new ItemRequest<ProjectStatus>(this, ProjectStatus.class, path, \"POST\");\n }", "public static cmpparameter get(nitro_service service) throws Exception{\n\t\tcmpparameter obj = new cmpparameter();\n\t\tcmpparameter[] response = (cmpparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "private Expression correctClassClassChain(PropertyExpression pe) {\n LinkedList<Expression> stack = new LinkedList<Expression>();\n ClassExpression found = null;\n for (Expression it = pe; it != null; it = ((PropertyExpression) it).getObjectExpression()) {\n if (it instanceof ClassExpression) {\n found = (ClassExpression) it;\n break;\n } else if (!(it.getClass() == PropertyExpression.class)) {\n return pe;\n }\n stack.addFirst(it);\n }\n if (found == null) return pe;\n\n if (stack.isEmpty()) return pe;\n Object stackElement = stack.removeFirst();\n if (!(stackElement.getClass() == PropertyExpression.class)) return pe;\n PropertyExpression classPropertyExpression = (PropertyExpression) stackElement;\n String propertyNamePart = classPropertyExpression.getPropertyAsString();\n if (propertyNamePart == null || !propertyNamePart.equals(\"class\")) return pe;\n\n found.setSourcePosition(classPropertyExpression);\n if (stack.isEmpty()) return found;\n stackElement = stack.removeFirst();\n if (!(stackElement.getClass() == PropertyExpression.class)) return pe;\n PropertyExpression classPropertyExpressionContainer = (PropertyExpression) stackElement;\n\n classPropertyExpressionContainer.setObjectExpression(found);\n return pe;\n }", "public ItemRequest<Attachment> findById(String attachment) {\n \n String path = String.format(\"/attachments/%s\", attachment);\n return new ItemRequest<Attachment>(this, Attachment.class, path, \"GET\");\n }", "private void updateHostingEntityIfRequired() {\n\t\tif ( hostingEntity != null && hostingEntityRequiresReadAfterUpdate() ) {\n\t\t\tOgmEntityPersister entityPersister = getHostingEntityPersister();\n\n\t\t\tif ( GridDialects.hasFacet( gridDialect, GroupingByEntityDialect.class ) ) {\n\t\t\t\t( (GroupingByEntityDialect) gridDialect ).flushPendingOperations( getAssociationKey().getEntityKey(),\n\t\t\t\t\t\tentityPersister.getTupleContext( session ) );\n\t\t\t}\n\n\t\t\tentityPersister.processUpdateGeneratedProperties(\n\t\t\t\t\tentityPersister.getIdentifier( hostingEntity, session ),\n\t\t\t\t\thostingEntity,\n\t\t\t\t\tnew Object[entityPersister.getPropertyNames().length],\n\t\t\t\t\tsession\n\t\t\t);\n\t\t}\n\t}", "private boolean hasBidirectionalAssociation(Class clazz)\r\n {\r\n ClassDescriptor cdesc;\r\n Collection refs;\r\n boolean hasBidirAssc;\r\n\r\n if (_withoutBidirAssc.contains(clazz))\r\n {\r\n return false;\r\n }\r\n\r\n if (_withBidirAssc.contains(clazz))\r\n {\r\n return true;\r\n }\r\n\r\n // first time we meet this class, let's look at metadata\r\n cdesc = _pb.getClassDescriptor(clazz);\r\n refs = cdesc.getObjectReferenceDescriptors();\r\n hasBidirAssc = false;\r\n REFS_CYCLE:\r\n for (Iterator it = refs.iterator(); it.hasNext(); )\r\n {\r\n ObjectReferenceDescriptor ord;\r\n ClassDescriptor relCDesc;\r\n Collection relRefs;\r\n\r\n ord = (ObjectReferenceDescriptor) it.next();\r\n relCDesc = _pb.getClassDescriptor(ord.getItemClass());\r\n relRefs = relCDesc.getObjectReferenceDescriptors();\r\n for (Iterator relIt = relRefs.iterator(); relIt.hasNext(); )\r\n {\r\n ObjectReferenceDescriptor relOrd;\r\n\r\n relOrd = (ObjectReferenceDescriptor) relIt.next();\r\n if (relOrd.getItemClass().equals(clazz))\r\n {\r\n hasBidirAssc = true;\r\n break REFS_CYCLE;\r\n }\r\n }\r\n }\r\n if (hasBidirAssc)\r\n {\r\n _withBidirAssc.add(clazz);\r\n }\r\n else\r\n {\r\n _withoutBidirAssc.add(clazz);\r\n }\r\n\r\n return hasBidirAssc;\r\n }" ]
Return the BundleCapability of a bundle exporting the package packageName. @param context The BundleContext @param packageName The package name @return the BundleCapability of a bundle exporting the package packageName
[ "private static BundleCapability getExportedPackage(BundleContext context, String packageName) {\n List<BundleCapability> packages = new ArrayList<BundleCapability>();\n for (Bundle bundle : context.getBundles()) {\n BundleRevision bundleRevision = bundle.adapt(BundleRevision.class);\n for (BundleCapability packageCapability : bundleRevision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE)) {\n String pName = (String) packageCapability.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE);\n if (pName.equalsIgnoreCase(packageName)) {\n packages.add(packageCapability);\n }\n }\n }\n\n Version max = Version.emptyVersion;\n BundleCapability maxVersion = null;\n for (BundleCapability aPackage : packages) {\n Version version = (Version) aPackage.getAttributes().get(\"version\");\n if (max.compareTo(version) <= 0) {\n max = version;\n maxVersion = aPackage;\n }\n }\n\n return maxVersion;\n }" ]
[ "private void processRemarks(GanttDesignerRemark remark)\n {\n for (GanttDesignerRemark.Task remarkTask : remark.getTask())\n {\n Integer id = remarkTask.getRow();\n Task task = m_projectFile.getTaskByID(id);\n String notes = task.getNotes();\n if (notes.isEmpty())\n {\n notes = remarkTask.getContent();\n }\n else\n {\n notes = notes + '\\n' + remarkTask.getContent();\n }\n task.setNotes(notes);\n }\n }", "public static base_responses add(nitro_service client, cmppolicylabel resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcmppolicylabel addresources[] = new cmppolicylabel[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new cmppolicylabel();\n\t\t\t\taddresources[i].labelname = resources[i].labelname;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "protected static void invalidateSwitchPoints() {\n if (LOG_ENABLED) {\n LOG.info(\"invalidating switch point\");\n }\n \tSwitchPoint old = switchPoint;\n switchPoint = new SwitchPoint();\n synchronized(IndyInterface.class) { SwitchPoint.invalidateAll(new SwitchPoint[]{old}); }\n }", "private Object getConstantValue(FieldType type, byte[] block)\n {\n Object value;\n DataType dataType = type.getDataType();\n\n if (dataType == null)\n {\n value = null;\n }\n else\n {\n switch (dataType)\n {\n case DURATION:\n {\n value = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(block, getValueOffset()), MPPUtility.getDurationTimeUnits(MPPUtility.getShort(block, getTimeUnitsOffset())));\n break;\n }\n\n case NUMERIC:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()));\n break;\n }\n\n case PERCENTAGE:\n {\n value = Double.valueOf(MPPUtility.getShort(block, getValueOffset()));\n break;\n }\n\n case CURRENCY:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()) / 100);\n break;\n }\n\n case STRING:\n {\n int textOffset = getTextOffset(block);\n value = MPPUtility.getUnicodeString(m_criteriaData, m_dataOffset + m_criteriaTextStart + textOffset);\n break;\n }\n\n case BOOLEAN:\n {\n int intValue = MPPUtility.getShort(block, getValueOffset());\n value = (intValue == 1 ? Boolean.TRUE : Boolean.FALSE);\n break;\n }\n\n case DATE:\n {\n value = MPPUtility.getTimestamp(block, getValueOffset());\n break;\n }\n\n default:\n {\n value = null;\n break;\n }\n }\n }\n\n return value;\n }", "public static String asTime(long time) {\n if (time > HOUR) {\n return String.format(\"%.1f h\", (time / HOUR));\n } else if (time > MINUTE) {\n return String.format(\"%.1f m\", (time / MINUTE));\n } else if (time > SECOND) {\n return String.format(\"%.1f s\", (time / SECOND));\n } else {\n return String.format(\"%d ms\", time);\n }\n }", "public final static int readMdLink(final StringBuilder out, final String in, final int start)\n {\n int pos = start;\n int counter = 1;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (ch == '\\\\' && pos + 1 < in.length())\n {\n pos = escape(out, in.charAt(pos + 1), pos);\n }\n else\n {\n boolean endReached = false;\n switch (ch)\n {\n case '(':\n counter++;\n break;\n case ' ':\n if (counter == 1)\n {\n endReached = true;\n }\n break;\n case ')':\n counter--;\n if (counter == 0)\n {\n endReached = true;\n }\n break;\n }\n if (endReached)\n {\n break;\n }\n out.append(ch);\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }", "public static base_response add(nitro_service client, dnspolicylabel resource) throws Exception {\n\t\tdnspolicylabel addresource = new dnspolicylabel();\n\t\taddresource.labelname = resource.labelname;\n\t\taddresource.transform = resource.transform;\n\t\treturn addresource.add_resource(client);\n\t}", "private void populateRelation(TaskField field, Task sourceTask, String relationship) throws MPXJException\n {\n int index = 0;\n int length = relationship.length();\n\n //\n // Extract the identifier\n //\n while ((index < length) && (Character.isDigit(relationship.charAt(index)) == true))\n {\n ++index;\n }\n\n Integer taskID;\n try\n {\n taskID = Integer.valueOf(relationship.substring(0, index));\n }\n\n catch (NumberFormatException ex)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT + \" '\" + relationship + \"'\");\n }\n\n //\n // Now find the task, so we can extract the unique ID\n //\n Task targetTask;\n if (field == TaskField.PREDECESSORS)\n {\n targetTask = m_projectFile.getTaskByID(taskID);\n }\n else\n {\n targetTask = m_projectFile.getTaskByUniqueID(taskID);\n }\n\n //\n // If we haven't reached the end, we next expect to find\n // SF, SS, FS, FF\n //\n RelationType type = null;\n Duration lag = null;\n\n if (index == length)\n {\n type = RelationType.FINISH_START;\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n else\n {\n if ((index + 1) == length)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT + \" '\" + relationship + \"'\");\n }\n\n type = RelationTypeUtility.getInstance(m_locale, relationship.substring(index, index + 2));\n\n index += 2;\n\n if (index == length)\n {\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n else\n {\n if (relationship.charAt(index) == '+')\n {\n ++index;\n }\n\n lag = DurationUtility.getInstance(relationship.substring(index), m_formats.getDurationDecimalFormat(), m_locale);\n }\n }\n\n if (type == null)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT + \" '\" + relationship + \"'\");\n }\n\n // We have seen at least one example MPX file where an invalid task ID\n // is present. We'll ignore this as the schedule is otherwise valid.\n if (targetTask != null)\n {\n Relation relation = sourceTask.addPredecessor(targetTask, type, lag);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }", "public static File copyResourceToLocalFile(String sourceResource, String destFileName) throws Exception {\n try {\n Resource keystoreFile = new ClassPathResource(sourceResource);\n InputStream in = keystoreFile.getInputStream();\n\n File outKeyStoreFile = new File(destFileName);\n FileOutputStream fop = new FileOutputStream(outKeyStoreFile);\n byte[] buf = new byte[512];\n int num;\n while ((num = in.read(buf)) != -1) {\n fop.write(buf, 0, num);\n }\n fop.flush();\n fop.close();\n in.close();\n return outKeyStoreFile;\n } catch (IOException ioe) {\n throw new Exception(\"Could not copy keystore file: \" + ioe.getMessage());\n }\n }" ]
performs a SQL SELECT statement against RDBMS. @param sql the query string. @param cld ClassDescriptor providing meta-information.
[ "public ResultSetAndStatement executeSQL(\r\n final String sql,\r\n ClassDescriptor cld,\r\n ValueContainer[] values,\r\n boolean scrollable)\r\n throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled()) logger.debug(\"executeSQL: \" + sql);\r\n final boolean isStoredprocedure = isStoredProcedure(sql);\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n try\r\n {\r\n stmt = sm.getPreparedStatement(cld, sql,\r\n scrollable, StatementManagerIF.FETCH_SIZE_NOT_EXPLICITLY_SET, isStoredprocedure);\r\n if (isStoredprocedure)\r\n {\r\n // Query implemented as a stored procedure, which must return a result set.\r\n // Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}\r\n getPlatform().registerOutResultSet((CallableStatement) stmt, 1);\r\n sm.bindValues(stmt, values, 2);\r\n stmt.execute();\r\n rs = (ResultSet) ((CallableStatement) stmt).getObject(1);\r\n }\r\n else\r\n {\r\n sm.bindValues(stmt, values, 1);\r\n rs = stmt.executeQuery();\r\n }\r\n\r\n // as we return the resultset for further operations, we cannot release the statement yet.\r\n // that has to be done by the JdbcAccess-clients (i.e. RsIterator, ProxyRsIterator and PkEnumeration.)\r\n return new ResultSetAndStatement(sm, stmt, rs, new SelectStatement()\r\n {\r\n public Query getQueryInstance()\r\n {\r\n return null;\r\n }\r\n\r\n public int getColumnIndex(FieldDescriptor fld)\r\n {\r\n return JdbcType.MIN_INT;\r\n }\r\n\r\n public String getStatement()\r\n {\r\n return sql;\r\n }\r\n });\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n logger.error(\"PersistenceBrokerException during the execution of the SQL query: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n throw ExceptionHelper.generateException(e, sql, cld, values, logger, null);\r\n }\r\n }" ]
[ "public String getUniqueFilename(String baseFileName, String extension, boolean cleanBaseFileName, String... ancestorFolders)\n {\n if (cleanBaseFileName)\n {\n baseFileName = PathUtil.cleanFileName(baseFileName);\n }\n\n if (ancestorFolders != null)\n {\n Path pathToFile = Paths.get(\"\", Stream.of(ancestorFolders).map(ancestor -> PathUtil.cleanFileName(ancestor)).toArray(String[]::new)).resolve(baseFileName);\n baseFileName = pathToFile.toString();\n }\n String filename = baseFileName + \".\" + extension;\n\n // FIXME this looks nasty\n while (usedFilenames.contains(filename))\n {\n filename = baseFileName + \".\" + index.getAndIncrement() + \".\" + extension;\n }\n usedFilenames.add(filename);\n\n return filename;\n }", "public void init(ServletContext context) {\n if (profiles != null) {\n for (IDiagramProfile profile : profiles) {\n profile.init(context);\n _registry.put(profile.getName(),\n profile);\n }\n }\n }", "public List<TimephasedCost> getTimephasedCost()\n {\n if (m_timephasedCost == null)\n {\n Resource r = getResource();\n ResourceType type = r != null ? r.getType() : ResourceType.WORK;\n\n //for Work and Material resources, we will calculate in the normal way\n if (type != ResourceType.COST)\n {\n if (m_timephasedWork != null && m_timephasedWork.hasData())\n {\n if (hasMultipleCostRates())\n {\n m_timephasedCost = getTimephasedCostMultipleRates(getTimephasedWork(), getTimephasedOvertimeWork());\n }\n else\n {\n m_timephasedCost = getTimephasedCostSingleRate(getTimephasedWork(), getTimephasedOvertimeWork());\n }\n }\n }\n else\n {\n m_timephasedCost = getTimephasedCostFixedAmount();\n }\n\n }\n return m_timephasedCost;\n }", "public void setModificationState(ModificationState newModificationState)\r\n {\r\n if(newModificationState != modificationState)\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"object state transition for object \" + this.oid + \" (\"\r\n + modificationState + \" --> \" + newModificationState + \")\");\r\n// try{throw new Exception();}catch(Exception e)\r\n// {\r\n// e.printStackTrace();\r\n// }\r\n }\r\n modificationState = newModificationState;\r\n }\r\n }", "public SchedulerDocsResponse.Doc schedulerDoc(String docId) {\n assertNotEmpty(docId, \"docId\");\n return this.get(new DatabaseURIHelper(getBaseUri()).\n path(\"_scheduler\").path(\"docs\").path(\"_replicator\").path(docId).build(),\n SchedulerDocsResponse.Doc.class);\n }", "public void removeChildTask(Task child)\n {\n if (m_children.remove(child))\n {\n child.m_parent = null;\n }\n setSummary(!m_children.isEmpty());\n }", "private void unregisterAllServlets() {\n\n for (String endpoint : registeredServlets) {\n registeredServlets.remove(endpoint);\n web.unregister(endpoint);\n LOG.info(\"endpoint {} unregistered\", endpoint);\n }\n\n }", "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}", "public void setPatternScheme(final boolean isWeekDayBased) {\n\n if (isWeekDayBased ^ (null != m_model.getWeekDay())) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n if (isWeekDayBased) {\n m_model.setWeekDay(getPatternDefaultValues().getWeekDay());\n m_model.setWeekOfMonth(getPatternDefaultValues().getWeekOfMonth());\n } else {\n m_model.setWeekDay(null);\n m_model.setWeekOfMonth(null);\n }\n m_model.setMonth(getPatternDefaultValues().getMonth());\n m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth());\n m_model.setInterval(getPatternDefaultValues().getInterval());\n onValueChange();\n }\n });\n }\n }" ]
Verifies if the new value is different from the field's old value. It's useful, for example, in NoSQL databases that replicates data between servers. This verification prevents to mark a field as modified and to be replicated needlessly. @param field the field that we are checking before to be modified @param value the new value @return true if the new and the old values are different and the value was changed.
[ "protected boolean setFieldIfNecessary(String field, Object value) {\n\t\tif (!isOpen())\n\t\t\tthrow new ClosedObjectException(\"The Document object is closed.\");\n\n\t\tif (!compareFieldValue(field, value)) {\n\t\t\t_doc.setField(field, value);\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}" ]
[ "void parseWorkerThreadPool(final XMLExtendedStreamReader reader, final ModelNode subsystemAdd) throws XMLStreamException {\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n requireNoNamespaceAttribute(reader, i);\n final String value = reader.getAttributeValue(i);\n final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));\n switch (attribute) {\n case WORKER_READ_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_READ_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_READ_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_READ_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_CORE_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_CORE_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_CORE_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_TASK_CORE_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_KEEPALIVE:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_KEEPALIVE)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_KEEPALIVE);\n }\n RemotingSubsystemRootResource.WORKER_TASK_KEEPALIVE.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_LIMIT:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_LIMIT)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_LIMIT);\n }\n RemotingSubsystemRootResource.WORKER_TASK_LIMIT.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_MAX_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_MAX_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_MAX_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_TASK_MAX_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_WRITE_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_WRITE_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_WRITE_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_WRITE_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n default:\n throw unexpectedAttribute(reader, i);\n }\n }\n requireNoContent(reader);\n }", "public void setShadow(float radius, float dx, float dy, int color) {\n\t\tshadowRadius = radius;\n\t\tshadowDx = dx;\n\t\tshadowDy = dy;\n\t\tshadowColor = color;\n\t\tupdateShadow();\n\t}", "public static URL codeLocationFromPath(String filePath) {\n try {\n return new File(filePath).toURI().toURL();\n } catch (Exception e) {\n throw new InvalidCodeLocation(filePath);\n }\n }", "public void useNewRESTService(String address) throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n org.customer.service.CustomerService customerService = JAXRSClientFactory\n .createFromModel(address, \n org.customer.service.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n\n System.out.println(\"Using new RESTful CustomerService with new client\");\n\n customer.v2.Customer customer = createNewCustomer(\"Smith New REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith New REST\");\n printNewCustomerDetails(customer);\n }", "private void processHyperlinkData(Task task, byte[] data)\n {\n if (data != null)\n {\n int offset = 12;\n String hyperlink;\n String address;\n String subaddress;\n\n offset += 12;\n hyperlink = MPPUtility.getUnicodeString(data, offset);\n offset += ((hyperlink.length() + 1) * 2);\n\n offset += 12;\n address = MPPUtility.getUnicodeString(data, offset);\n offset += ((address.length() + 1) * 2);\n\n offset += 12;\n subaddress = MPPUtility.getUnicodeString(data, offset);\n\n task.setHyperlink(hyperlink);\n task.setHyperlinkAddress(address);\n task.setHyperlinkSubAddress(subaddress);\n }\n }", "public Document removeDocument(String key) throws PrintingException {\n\t\tif (documentMap.containsKey(key)) {\n\t\t\treturn documentMap.remove(key);\n\t\t} else {\n\t\t\tthrow new PrintingException(PrintingException.DOCUMENT_NOT_FOUND, key);\n\t\t}\n\t}", "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 float getQuaternionW(float x, float y, float z) {\n return (float) Math.cos(Math.asin(Math.sqrt(x * x + y * y + z * z)));\n }", "public ParallelTaskBuilder setTargetHostsFromLineByLineText(\n String sourcePath, HostsSourceType sourceType)\n throws TargetHostsLoadException {\n\n this.targetHosts = targetHostBuilder.setTargetHostsFromLineByLineText(sourcePath,\n sourceType);\n return this;\n }" ]
Use this API to fetch all the autoscaleaction resources that are configured on netscaler.
[ "public static autoscaleaction[] get(nitro_service service) throws Exception{\n\t\tautoscaleaction obj = new autoscaleaction();\n\t\tautoscaleaction[] response = (autoscaleaction[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public static void dumpMaterial(AiMaterial material) {\n for (AiMaterial.Property prop : material.getProperties()) {\n dumpMaterialProperty(prop);\n }\n }", "public boolean isServerAvailable(){\n final Client client = getClient();\n final ClientResponse response = client.resource(serverURL).get(ClientResponse.class);\n\n if(ClientResponse.Status.OK.getStatusCode() == response.getStatus()){\n return true;\n }\n\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, \"Failed to reach the targeted Grapes server\", response.getStatus()));\n }\n client.destroy();\n\n return false;\n }", "@Deprecated\n public static PersistentResourceXMLBuilder decorator(final String elementName) {\n return new PersistentResourceXMLBuilder(PathElement.pathElement(elementName), null).setDecoratorGroup(elementName);\n }", "private void process(String input, String output) throws MPXJException, IOException\n {\n //\n // Extract the project data\n //\n MPPReader reader = new MPPReader();\n m_project = reader.read(input);\n\n String varDataFileName;\n String projectDirName;\n int mppFileType = NumberHelper.getInt(m_project.getProjectProperties().getMppFileType());\n switch (mppFileType)\n {\n case 8:\n {\n projectDirName = \" 1\";\n varDataFileName = \"FixDeferFix 0\";\n break;\n }\n\n case 9:\n {\n projectDirName = \" 19\";\n varDataFileName = \"Var2Data\";\n break;\n }\n\n case 12:\n {\n projectDirName = \" 112\";\n varDataFileName = \"Var2Data\";\n break;\n }\n\n case 14:\n {\n projectDirName = \" 114\";\n varDataFileName = \"Var2Data\";\n break;\n }\n\n default:\n {\n throw new IllegalArgumentException(\"Unsupported file type \" + mppFileType);\n }\n }\n\n //\n // Load the raw file\n //\n FileInputStream is = new FileInputStream(input);\n POIFSFileSystem fs = new POIFSFileSystem(is);\n is.close();\n\n //\n // Locate the root of the project file system\n //\n DirectoryEntry root = fs.getRoot();\n m_projectDir = (DirectoryEntry) root.getEntry(projectDirName);\n\n //\n // Process Tasks\n //\n Map<String, String> replacements = new HashMap<String, String>();\n for (Task task : m_project.getTasks())\n {\n mapText(task.getName(), replacements);\n }\n processReplacements(((DirectoryEntry) m_projectDir.getEntry(\"TBkndTask\")), varDataFileName, replacements, true);\n\n //\n // Process Resources\n //\n replacements.clear();\n for (Resource resource : m_project.getResources())\n {\n mapText(resource.getName(), replacements);\n mapText(resource.getInitials(), replacements);\n }\n processReplacements((DirectoryEntry) m_projectDir.getEntry(\"TBkndRsc\"), varDataFileName, replacements, true);\n\n //\n // Process project properties\n //\n replacements.clear();\n ProjectProperties properties = m_project.getProjectProperties();\n mapText(properties.getProjectTitle(), replacements);\n processReplacements(m_projectDir, \"Props\", replacements, true);\n\n replacements.clear();\n mapText(properties.getProjectTitle(), replacements);\n mapText(properties.getSubject(), replacements);\n mapText(properties.getAuthor(), replacements);\n mapText(properties.getKeywords(), replacements);\n mapText(properties.getComments(), replacements);\n processReplacements(root, \"\\005SummaryInformation\", replacements, false);\n\n replacements.clear();\n mapText(properties.getManager(), replacements);\n mapText(properties.getCompany(), replacements);\n mapText(properties.getCategory(), replacements);\n processReplacements(root, \"\\005DocumentSummaryInformation\", replacements, false);\n\n //\n // Write the replacement raw file\n //\n FileOutputStream os = new FileOutputStream(output);\n fs.writeFilesystem(os);\n os.flush();\n os.close();\n fs.close();\n }", "public void useNewRESTService(String address) throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n org.customer.service.CustomerService customerService = JAXRSClientFactory\n .createFromModel(address, \n org.customer.service.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n\n System.out.println(\"Using new RESTful CustomerService with new client\");\n\n customer.v2.Customer customer = createNewCustomer(\"Smith New REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith New REST\");\n printNewCustomerDetails(customer);\n }", "public double distanceToPlane(Point3d p) {\n return normal.x * p.x + normal.y * p.y + normal.z * p.z - planeOffset;\n }", "public void fireEvent(Type eventType, Object event, Annotation... qualifiers) {\n final EventMetadata metadata = new EventMetadataImpl(eventType, null, qualifiers);\n notifier.fireEvent(eventType, event, metadata, qualifiers);\n }", "public static Logger getLogger(String className) {\n\t\tif (logType == null) {\n\t\t\tlogType = findLogType();\n\t\t}\n\t\treturn new Logger(logType.createLog(className));\n\t}", "@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 }" ]
Parse a list of String into a list of Integer. If one element can not be parsed, the behavior depends on the value of failOnException. @param strList can't be null @param failOnException if an element can not be parsed should we return null or add a null element to the list. @return list of all String parsed as Integer or null if failOnException
[ "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 ServerSetup createCopy(String bindAddress) {\r\n ServerSetup setup = new ServerSetup(getPort(), bindAddress, getProtocol());\r\n setup.setServerStartupTimeout(getServerStartupTimeout());\r\n setup.setConnectionTimeout(getConnectionTimeout());\r\n setup.setReadTimeout(getReadTimeout());\r\n setup.setWriteTimeout(getWriteTimeout());\r\n setup.setVerbose(isVerbose());\r\n\r\n return setup;\r\n }", "public CollectionRequest<Task> projects(String task) {\n \n String path = String.format(\"/tasks/%s/projects\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }", "private float[] generateParticleVelocities()\n {\n float [] particleVelocities = new float[mEmitRate * 3];\n Vector3f temp = new Vector3f(0,0,0);\n for ( int i = 0; i < mEmitRate * 3 ; i +=3 )\n {\n temp.x = mParticlePositions[i];\n temp.y = mParticlePositions[i+1];\n temp.z = mParticlePositions[i+2];\n\n\n float velx = mRandom.nextFloat() * (maxVelocity.x- minVelocity.x)\n + minVelocity.x;\n\n float vely = mRandom.nextFloat() * (maxVelocity.y - minVelocity.y)\n + minVelocity.y;\n float velz = mRandom.nextFloat() * (maxVelocity.z - minVelocity.z)\n + minVelocity.z;\n\n temp = temp.normalize();\n temp.mul(velx, vely, velz, temp);\n\n particleVelocities[i] = temp.x;\n particleVelocities[i+1] = temp.y;\n particleVelocities[i+2] = temp.z;\n }\n\n return particleVelocities;\n\n }", "public void visitMethodInsn(int opcode, String owner, String name,\n String desc, boolean itf) {\n if (mv != null) {\n mv.visitMethodInsn(opcode, owner, name, desc, itf);\n }\n }", "public static base_response add(nitro_service client, autoscaleaction resource) throws Exception {\n\t\tautoscaleaction addresource = new autoscaleaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.type = resource.type;\n\t\taddresource.profilename = resource.profilename;\n\t\taddresource.parameters = resource.parameters;\n\t\taddresource.vmdestroygraceperiod = resource.vmdestroygraceperiod;\n\t\taddresource.quiettime = resource.quiettime;\n\t\taddresource.vserver = resource.vserver;\n\t\treturn addresource.add_resource(client);\n\t}", "public void merge(GVRSkeleton newSkel)\n {\n int numBones = getNumBones();\n List<Integer> parentBoneIds = new ArrayList<Integer>(numBones + newSkel.getNumBones());\n List<String> newBoneNames = new ArrayList<String>(newSkel.getNumBones());\n List<Matrix4f> newMatrices = new ArrayList<Matrix4f>(newSkel.getNumBones());\n GVRPose oldBindPose = getBindPose();\n GVRPose curPose = getPose();\n\n for (int i = 0; i < numBones; ++i)\n {\n parentBoneIds.add(mParentBones[i]);\n }\n for (int j = 0; j < newSkel.getNumBones(); ++j)\n {\n String boneName = newSkel.getBoneName(j);\n int boneId = getBoneIndex(boneName);\n if (boneId < 0)\n {\n int parentId = newSkel.getParentBoneIndex(j);\n Matrix4f m = new Matrix4f();\n\n newSkel.getBindPose().getLocalMatrix(j, m);\n newMatrices.add(m);\n newBoneNames.add(boneName);\n if (parentId >= 0)\n {\n boneName = newSkel.getBoneName(parentId);\n parentId = getBoneIndex(boneName);\n }\n parentBoneIds.add(parentId);\n }\n }\n if (parentBoneIds.size() == numBones)\n {\n return;\n }\n int n = numBones + parentBoneIds.size();\n int[] parentIds = Arrays.copyOf(mParentBones, n);\n int[] boneOptions = Arrays.copyOf(mBoneOptions, n);\n String[] boneNames = Arrays.copyOf(mBoneNames, n);\n\n mBones = Arrays.copyOf(mBones, n);\n mPoseMatrices = new float[n * 16];\n for (int i = 0; i < parentBoneIds.size(); ++i)\n {\n n = numBones + i;\n parentIds[n] = parentBoneIds.get(i);\n boneNames[n] = newBoneNames.get(i);\n boneOptions[n] = BONE_ANIMATE;\n }\n mBoneOptions = boneOptions;\n mBoneNames = boneNames;\n mParentBones = parentIds;\n mPose = new GVRPose(this);\n mBindPose = new GVRPose(this);\n mBindPose.copy(oldBindPose);\n mPose.copy(curPose);\n mBindPose.sync();\n for (int j = 0; j < newSkel.getNumBones(); ++j)\n {\n mBindPose.setLocalMatrix(numBones + j, newMatrices.get(j));\n mPose.setLocalMatrix(numBones + j, newMatrices.get(j));\n }\n setBindPose(mBindPose);\n mPose.sync();\n updateBonePose();\n }", "String generateSynopsis() {\n synopsisOptions = buildSynopsisOptions(opts, arg, domain);\n StringBuilder synopsisBuilder = new StringBuilder();\n if (parentName != null) {\n synopsisBuilder.append(parentName).append(\" \");\n }\n synopsisBuilder.append(commandName);\n if (isOperation && !opts.isEmpty()) {\n synopsisBuilder.append(\"(\");\n } else {\n synopsisBuilder.append(\" \");\n }\n boolean hasOptions = arg != null || !opts.isEmpty();\n if (hasActions && hasOptions) {\n synopsisBuilder.append(\" [\");\n }\n if (hasActions) {\n synopsisBuilder.append(\" <action>\");\n }\n if (hasActions && hasOptions) {\n synopsisBuilder.append(\" ] || [\");\n }\n SynopsisOption opt;\n while ((opt = retrieveNextOption(synopsisOptions, false)) != null) {\n String content = addSynopsisOption(opt);\n if (content != null) {\n synopsisBuilder.append(content.trim());\n if (isOperation) {\n if (!synopsisOptions.isEmpty()) {\n synopsisBuilder.append(\",\");\n } else {\n synopsisBuilder.append(\")\");\n }\n }\n synopsisBuilder.append(\" \");\n }\n }\n if (hasActions && hasOptions) {\n synopsisBuilder.append(\" ]\");\n }\n return synopsisBuilder.toString();\n }", "private void decreaseIndent() throws IOException\n {\n if (m_pretty)\n {\n m_writer.write('\\n');\n m_indent = m_indent.substring(0, m_indent.length() - INDENT.length());\n m_writer.write(m_indent);\n }\n m_firstNameValuePair.pop();\n }", "public static base_response sync(nitro_service client, gslbconfig resource) throws Exception {\n\t\tgslbconfig syncresource = new gslbconfig();\n\t\tsyncresource.preview = resource.preview;\n\t\tsyncresource.debug = resource.debug;\n\t\tsyncresource.forcesync = resource.forcesync;\n\t\tsyncresource.nowarn = resource.nowarn;\n\t\tsyncresource.saveconfig = resource.saveconfig;\n\t\tsyncresource.command = resource.command;\n\t\treturn syncresource.perform_operation(client,\"sync\");\n\t}" ]
Reads any exceptions present in the file. This is only used in MSPDI file versions saved by Project 2007 and later. @param calendar XML calendar @param bc MPXJ calendar
[ "private void readExceptions(Project.Calendars.Calendar calendar, ProjectCalendar bc)\n {\n Project.Calendars.Calendar.Exceptions exceptions = calendar.getExceptions();\n if (exceptions != null)\n {\n for (Project.Calendars.Calendar.Exceptions.Exception exception : exceptions.getException())\n {\n readException(bc, exception);\n }\n }\n }" ]
[ "public static boolean compareAnnotatedParameters(AnnotatedParameter<?> p1, AnnotatedParameter<?> p2) {\n return compareAnnotatedCallable(p1.getDeclaringCallable(), p2.getDeclaringCallable()) && p1.getPosition() == p2.getPosition() && compareAnnotated(p1, p2);\n }", "public static long getGcTimestamp(String zookeepers) {\n ZooKeeper zk = null;\n try {\n zk = new ZooKeeper(zookeepers, 30000, null);\n\n // wait until zookeeper is connected\n long start = System.currentTimeMillis();\n while (!zk.getState().isConnected() && System.currentTimeMillis() - start < 30000) {\n Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS);\n }\n\n byte[] d = zk.getData(ZookeeperPath.ORACLE_GC_TIMESTAMP, false, null);\n return LongUtil.fromByteArray(d);\n } catch (KeeperException | InterruptedException | IOException e) {\n log.warn(\"Failed to get oldest timestamp of Oracle from Zookeeper\", e);\n return OLDEST_POSSIBLE;\n } finally {\n if (zk != null) {\n try {\n zk.close();\n } catch (InterruptedException e) {\n log.error(\"Failed to close zookeeper client\", e);\n }\n }\n }\n }", "public FloatBuffer getFloatVec(String attributeName)\n {\n int size = getAttributeSize(attributeName);\n if (size <= 0)\n {\n return null;\n }\n size *= 4 * getVertexCount();\n ByteBuffer buffer = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());\n FloatBuffer data = buffer.asFloatBuffer();\n if (!NativeVertexBuffer.getFloatVec(getNative(), attributeName, data, 0, 0))\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return data;\n }", "public static List<String> enableJMX(List<String> jvmArgs) {\n final String arg = \"-D\" + OPT_JMX_REMOTE;\n if (jvmArgs.contains(arg))\n return jvmArgs;\n final List<String> cmdLine2 = new ArrayList<>(jvmArgs);\n cmdLine2.add(arg);\n return cmdLine2;\n }", "private StitchUserT doLogin(final StitchCredential credential, final boolean asLinkRequest) {\n final Response response = doLoginRequest(credential, asLinkRequest);\n\n final StitchUserT previousUser = activeUser;\n final StitchUserT user = processLoginResponse(credential, response, asLinkRequest);\n\n if (asLinkRequest) {\n onUserLinked(user);\n } else {\n onUserLoggedIn(user);\n onActiveUserChanged(activeUser, previousUser);\n }\n\n return user;\n }", "public EventBus emit(Enum<?> event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }", "protected void markStatementsForInsertion(\n\t\t\tStatementDocument currentDocument, List<Statement> addStatements) {\n\t\tfor (Statement statement : addStatements) {\n\t\t\taddStatement(statement, true);\n\t\t}\n\n\t\tfor (StatementGroup sg : currentDocument.getStatementGroups()) {\n\t\t\tif (this.toKeep.containsKey(sg.getProperty())) {\n\t\t\t\tfor (Statement statement : sg) {\n\t\t\t\t\tif (!this.toDelete.contains(statement.getStatementId())) {\n\t\t\t\t\t\taddStatement(statement, false);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public ParallelTaskBuilder preparePing() {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.PING);\n return cb;\n }", "private void readFile(InputStream is) throws IOException\n {\n StreamHelper.skip(is, 64);\n int index = 64;\n\n ArrayList<Integer> offsetList = new ArrayList<Integer>();\n List<String> nameList = new ArrayList<String>();\n\n while (true)\n {\n byte[] table = new byte[32];\n is.read(table);\n index += 32;\n\n int offset = PEPUtility.getInt(table, 0);\n offsetList.add(Integer.valueOf(offset));\n if (offset == 0)\n {\n break;\n }\n\n nameList.add(PEPUtility.getString(table, 5).toUpperCase());\n }\n\n StreamHelper.skip(is, offsetList.get(0).intValue() - index);\n\n for (int offsetIndex = 1; offsetIndex < offsetList.size() - 1; offsetIndex++)\n {\n String name = nameList.get(offsetIndex - 1);\n Class<? extends Table> tableClass = TABLE_CLASSES.get(name);\n if (tableClass == null)\n {\n tableClass = Table.class;\n }\n\n Table table;\n try\n {\n table = tableClass.newInstance();\n }\n\n catch (Exception ex)\n {\n throw new RuntimeException(ex);\n }\n\n m_tables.put(name, table);\n table.read(is);\n }\n }" ]
Puts a new document in the service. The generate key is globally unique. @param document document @return key unique key to reference the document
[ "public String putDocument(Document document) {\n\t\tString key = UUID.randomUUID().toString();\n\t\tdocumentMap.put(key, document);\n\t\treturn key;\n\t}" ]
[ "public int nextToken() throws IOException\n {\n int c;\n int nextc = -1;\n boolean quoted = false;\n int result = m_next;\n if (m_next != 0)\n {\n m_next = 0;\n }\n\n m_buffer.setLength(0);\n\n while (result == 0)\n {\n if (nextc != -1)\n {\n c = nextc;\n nextc = -1;\n }\n else\n {\n c = read();\n }\n\n switch (c)\n {\n case TT_EOF:\n {\n if (m_buffer.length() != 0)\n {\n result = TT_WORD;\n m_next = TT_EOF;\n }\n else\n {\n result = TT_EOF;\n }\n break;\n }\n\n case TT_EOL:\n {\n int length = m_buffer.length();\n\n if (length != 0 && m_buffer.charAt(length - 1) == '\\r')\n {\n --length;\n m_buffer.setLength(length);\n }\n\n if (length == 0)\n {\n result = TT_EOL;\n }\n else\n {\n result = TT_WORD;\n m_next = TT_EOL;\n }\n\n break;\n }\n\n default:\n {\n if (c == m_quote)\n {\n if (quoted == false && startQuotedIsValid(m_buffer))\n {\n quoted = true;\n }\n else\n {\n if (quoted == false)\n {\n m_buffer.append((char) c);\n }\n else\n {\n nextc = read();\n if (nextc == m_quote)\n {\n m_buffer.append((char) c);\n nextc = -1;\n }\n else\n {\n quoted = false;\n }\n }\n }\n }\n else\n {\n if (c == m_delimiter && quoted == false)\n {\n result = TT_WORD;\n }\n else\n {\n m_buffer.append((char) c);\n }\n }\n }\n }\n }\n\n m_type = result;\n\n return (result);\n }", "private void ensureToolValidForCreation(ExternalTool tool) {\n //check for the unconditionally required fields\n if(StringUtils.isAnyBlank(tool.getName(), tool.getPrivacyLevel(), tool.getConsumerKey(), tool.getSharedSecret())) {\n throw new IllegalArgumentException(\"External tool requires all of the following for creation: name, privacy level, consumer key, shared secret\");\n }\n //check that there is either a URL or a domain. One or the other is required\n if(StringUtils.isBlank(tool.getUrl()) && StringUtils.isBlank(tool.getDomain())) {\n throw new IllegalArgumentException(\"External tool requires either a URL or domain for creation\");\n }\n }", "public static final String printBookingType(BookingType value)\n {\n return (Integer.toString(value == null ? BookingType.COMMITTED.getValue() : value.getValue()));\n }", "@Deprecated\r\n public Location resolvePlaceId(String placeId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_RESOLVE_PLACE_ID);\r\n\r\n parameters.put(\"place_id\", placeId);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }", "@Override\n public void addVariable(String varName, Object value) {\n synchronized (mGlobalVariables) {\n mGlobalVariables.put(varName, value);\n }\n refreshGlobalBindings();\n }", "@Override\n public Symmetry454Date date(int prolepticYear, int month, int dayOfMonth) {\n return Symmetry454Date.of(prolepticYear, month, dayOfMonth);\n }", "private void logState(final FileRollEvent fileRollEvent) {\n\n//\t\tif (ApplicationState.isApplicationStateEnabled()) {\n\t\t\t\n\t\t\tsynchronized (this) {\n\t\t\t\t\n\t\t\t\tfinal Collection<ApplicationState.ApplicationStateMessage> entries = ApplicationState.getAppStateEntries();\n\t\t\t\tfor (ApplicationState.ApplicationStateMessage entry : entries) {\n Level level = ApplicationState.getLog4jLevel(entry.getLevel());\n\t\t\t\t if(level.isGreaterOrEqual(ApplicationState.LOGGER.getEffectiveLevel())) {\n\t\t\t\t\t\tfinal org.apache.log4j.spi.LoggingEvent loggingEvent = new org.apache.log4j.spi.LoggingEvent(ApplicationState.FQCN, ApplicationState.LOGGER, level, entry.getMessage(), null);\n\n\t\t\t\t\t\t//Save the current layout before changing it to the original (relevant for marker cases when the layout was changed)\n\t\t\t\t\t\tLayout current=fileRollEvent.getSource().getLayout();\n\t\t\t\t\t\t//fileRollEvent.getSource().activeOriginalLayout();\n\t\t\t\t\t\tString flowContext = (String) MDC.get(\"flowCtxt\");\n\t\t\t\t\t\tMDC.remove(\"flowCtxt\");\n\t\t\t\t\t\t//Write applicationState:\n\t\t\t\t\t\tif(fileRollEvent.getSource().isAddApplicationState() && fileRollEvent.getSource().getFile().endsWith(\"log\")){\n\t\t\t\t\t\t\tfileRollEvent.dispatchToAppender(loggingEvent);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//Set current again.\n\t\t\t\t\t\tfileRollEvent.getSource().setLayout(current);\n\t\t\t\t\t\tif (flowContext != null) {\n\t\t\t\t\t\t\tMDC.put(\"flowCtxt\", flowContext);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\t\n//\t\t}\n\t}", "public static long getVisibilityCacheWeight(FluoConfiguration conf) {\n long size = conf.getLong(VISIBILITY_CACHE_WEIGHT, VISIBILITY_CACHE_WEIGHT_DEFAULT);\n if (size <= 0) {\n throw new IllegalArgumentException(\n \"Cache size must be positive for \" + VISIBILITY_CACHE_WEIGHT);\n }\n return size;\n }", "public void modified(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {\n declarationBinders.get(declarationBinderRef).update(declarationBinderRef);\n }" ]
Send a waveform preview update announcement to all registered listeners. @param player the player whose waveform preview has changed @param preview the new waveform preview, if any
[ "private void deliverWaveformPreviewUpdate(final int player, final WaveformPreview preview) {\n final Set<WaveformListener> listeners = getWaveformListeners();\n if (!listeners.isEmpty()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n final WaveformPreviewUpdate update = new WaveformPreviewUpdate(player, preview);\n for (final WaveformListener listener : listeners) {\n try {\n listener.previewChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering waveform preview update to listener\", t);\n }\n }\n }\n });\n }\n }" ]
[ "private static Set<String> imageOrientationsOf(ImageMetadata metadata) {\n\n String exifIFD0DirName = new ExifIFD0Directory().getName();\n\n Tag[] tags = Arrays.stream(metadata.getDirectories())\n .filter(dir -> dir.getName().equals(exifIFD0DirName))\n .findFirst()\n .map(Directory::getTags)\n .orElseGet(() -> new Tag[0]);\n\n return Arrays.stream(tags)\n .filter(tag -> tag.getType() == 274)\n .map(Tag::getRawValue)\n .collect(Collectors.toSet());\n }", "public ClassificationModel attachLink(ClassificationModel classificationModel, LinkModel linkModel)\n {\n for (LinkModel existing : classificationModel.getLinks())\n {\n if (StringUtils.equals(existing.getLink(), linkModel.getLink()))\n {\n return classificationModel;\n }\n }\n classificationModel.addLink(linkModel);\n return classificationModel;\n }", "void close() {\n try {\n performTeardownExchange();\n } catch (IOException e) {\n logger.warn(\"Problem reporting our intention to close the dbserver connection\", e);\n }\n try {\n channel.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client output channel\", e);\n }\n try {\n os.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client output stream\", e);\n }\n try {\n is.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client input stream\", e);\n }\n try {\n socket.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client socket\", e);\n }\n }", "public Collection<Argument> getArguments(final String key) {\n final Collection<Argument> args = map.get(key);\n if (args != null) {\n return new ArrayList<>(args);\n }\n return Collections.emptyList();\n }", "protected boolean computeOffset(CacheDataSet cache) {\n // offset computation: update offset for all items in the cache\n float startDataOffset = getStartingOffset((cache.getTotalSizeWithPadding()));\n float layoutOffset = getLayoutOffset();\n\n boolean inBounds = startDataOffset < -layoutOffset;\n\n for (int pos = 0; pos < cache.count(); ++pos) {\n int id = cache.getId(pos);\n if (id != -1) {\n float endDataOffset = cache.setDataAfter(id, startDataOffset);\n inBounds = inBounds &&\n endDataOffset > layoutOffset &&\n startDataOffset < -layoutOffset;\n startDataOffset = endDataOffset;\n Log.d(LAYOUT, TAG, \"computeOffset [%d] = %f\" , id, cache.getDataOffset(id));\n }\n }\n\n return inBounds;\n }", "public static String determineFieldName(@Nonnull final String methodName) {\n\t\tCheck.notEmpty(methodName, \"methodName\");\n\t\tfinal Matcher m = PATTERN.matcher(methodName);\n\t\tCheck.stateIsTrue(m.find(), \"passed method name '%s' is not applicable\", methodName);\n\t\treturn m.group(2).substring(0, 1).toLowerCase() + m.group(2).substring(1);\n\t}", "private static void updateJar(final File file, final byte[] searchPattern, final int[] badSkipBytes, final int newSig, final int endSig) throws IOException {\n final RandomAccessFile raf = new RandomAccessFile(file, \"rw\");\n try {\n final FileChannel channel = raf.getChannel();\n try {\n long pos = channel.size() - ENDLEN;\n final ScanContext context;\n if (newSig == CRIPPLED_ENDSIG) {\n context = new ScanContext(GOOD_ENDSIG_PATTERN, CRIPPLED_ENDSIG_PATTERN);\n } else if (newSig == GOOD_ENDSIG) {\n context = new ScanContext(CRIPPLED_ENDSIG_PATTERN, GOOD_ENDSIG_PATTERN);\n } else {\n context = null;\n }\n\n if (!validateEndRecord(file, channel, pos, endSig)) {\n pos = scanForEndSig(file, channel, context);\n }\n if (pos == -1) {\n if (context.state == State.NOT_FOUND) {\n // Don't fail patching if we cannot validate a valid zip\n PatchLogger.ROOT_LOGGER.cannotInvalidateZip(file.getAbsolutePath());\n }\n return;\n }\n // Update the central directory record\n channel.position(pos);\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(newSig);\n buffer.flip();\n while (buffer.hasRemaining()) {\n channel.write(buffer);\n }\n } finally {\n safeClose(channel);\n }\n } finally {\n safeClose(raf);\n }\n }", "private static void multBlockAdd( double []blockA, double []blockB, double []blockC,\n final int m, final int n, final int o,\n final int blockLength ) {\n// for( int i = 0; i < m; i++ ) {\n// for( int j = 0; j < o; j++ ) {\n// double val = 0;\n// for( int k = 0; k < n; k++ ) {\n// val += blockA[ i*blockLength + k]*blockB[ k*blockLength + j];\n// }\n//\n// blockC[ i*blockLength + j] += val;\n// }\n// }\n\n// int rowA = 0;\n// for( int i = 0; i < m; i++ , rowA += blockLength) {\n// for( int j = 0; j < o; j++ ) {\n// double val = 0;\n// int indexB = j;\n// int indexA = rowA;\n// int end = indexA + n;\n// for( ; indexA != end; indexA++ , indexB += blockLength ) {\n// val += blockA[ indexA ]*blockB[ indexB ];\n// }\n//\n// blockC[ rowA + j] += val;\n// }\n// }\n\n// for( int k = 0; k < n; k++ ) {\n// for( int i = 0; i < m; i++ ) {\n// for( int j = 0; j < o; j++ ) {\n// blockC[ i*blockLength + j] += blockA[ i*blockLength + k]*blockB[ k*blockLength + j];\n// }\n// }\n// }\n\n for( int k = 0; k < n; k++ ) {\n int rowB = k*blockLength;\n int endB = rowB+o;\n for( int i = 0; i < m; i++ ) {\n int indexC = i*blockLength;\n double valA = blockA[ indexC + k];\n int indexB = rowB;\n \n while( indexB != endB ) {\n blockC[ indexC++ ] += valA*blockB[ indexB++];\n }\n }\n }\n }", "protected Map<String, OperationTransformer> buildOperationTransformers(AttributeTransformationDescriptionBuilderImpl.AttributeTransformationDescriptionBuilderRegistry registry) {\n final Map<String, OperationTransformer> operations = new HashMap<String, OperationTransformer>();\n for(final Map.Entry<String, OperationTransformationEntry> entry: operationTransformers.entrySet()) {\n final OperationTransformer transformer = entry.getValue().getOperationTransformer(registry);\n operations.put(entry.getKey(), transformer);\n }\n return operations;\n }" ]
Called when a ParentViewHolder has triggered a collapse for it's parent @param flatParentPosition the position of the parent that is calling to be collapsed
[ "@UiThread\n protected void parentCollapsedFromViewHolder(int flatParentPosition) {\n ExpandableWrapper<P, C> parentWrapper = mFlatItemList.get(flatParentPosition);\n updateCollapsedParent(parentWrapper, flatParentPosition, true);\n }" ]
[ "private ProjectFile readTextFile(InputStream inputStream) throws MPXJException\n {\n ProjectReader reader = new AstaTextFileReader();\n addListeners(reader);\n return reader.read(inputStream);\n }", "public Float getFloat(String fieldName) {\n\t\ttry {\n\t\t\treturn hasValue(fieldName) ? Float.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a number.\", e);\n\t\t}\n\t}", "public static void validate(final Module module) {\n if (null == module) {\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module cannot be null!\")\n .build());\n }\n if(module.getName() == null ||\n module.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module name cannot be null or empty!\")\n .build());\n }\n if(module.getVersion()== null ||\n module.getVersion().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module version cannot be null or empty!\")\n .build());\n }\n\n // Check artifacts\n for(final Artifact artifact: DataUtils.getAllArtifacts(module)){\n validate(artifact);\n }\n\n // Check dependencies\n for(final Dependency dependency: DataUtils.getAllDependencies(module)){\n validate(dependency.getTarget());\n }\n }", "protected void parseSequencesWithColons(TokenList tokens , Sequence sequence ) {\n\n TokenList.Token t = tokens.getFirst();\n if( t == null )\n return;\n\n int state = 0;\n\n TokenList.Token start = null;\n TokenList.Token middle = null;\n TokenList.Token prev = t;\n\n boolean last = false;\n while( true ) {\n if( state == 0 ) {\n if( isVariableInteger(t) && (t.next != null && t.next.getSymbol() == Symbol.COLON) ) {\n start = t;\n state = 1;\n t = t.next;\n } else if( t != null && t.getSymbol() == Symbol.COLON ) {\n // If it starts with a colon then it must be 'all' or a type-o\n IntegerSequence range = new IntegerSequence.Range(null,null);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(range);\n TokenList.Token n = new TokenList.Token(varSequence);\n tokens.insert(t.previous, n);\n tokens.remove(t);\n t = n;\n }\n } else if( state == 1 ) {\n // var : ?\n if (isVariableInteger(t)) {\n state = 2;\n } else {\n // array range\n IntegerSequence range = new IntegerSequence.Range(start,null);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(range);\n replaceSequence(tokens, varSequence, start, prev);\n state = 0;\n }\n } else if ( state == 2 ) {\n // var:var ?\n if( t != null && t.getSymbol() == Symbol.COLON ) {\n middle = prev;\n state = 3;\n } else {\n // create for sequence with start and stop elements only\n IntegerSequence numbers = new IntegerSequence.For(start,null,prev);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n replaceSequence(tokens, varSequence, start, prev );\n if( t != null )\n t = t.previous;\n state = 0;\n }\n } else if ( state == 3 ) {\n // var:var: ?\n if( isVariableInteger(t) ) {\n // create 'for' sequence with three variables\n IntegerSequence numbers = new IntegerSequence.For(start,middle,t);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n t = replaceSequence(tokens, varSequence, start, t);\n } else {\n // array range with 2 elements\n IntegerSequence numbers = new IntegerSequence.Range(start,middle);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n replaceSequence(tokens, varSequence, start, prev);\n }\n state = 0;\n }\n\n if( last ) {\n break;\n } else if( t.next == null ) {\n // handle the case where it is the last token in the sequence\n last = true;\n }\n prev = t;\n t = t.next;\n }\n }", "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 }", "private void logError(LifecycleListener listener, Exception e) {\n LOGGER.error(\"Error for listener \" + listener.getClass(), e);\n }", "public ProjectCalendarWeek addWorkWeek()\n {\n ProjectCalendarWeek week = new ProjectCalendarWeek();\n week.setParent(this);\n m_workWeeks.add(week);\n m_weeksSorted = false;\n clearWorkingDateCache();\n return week;\n }", "public Operation.Info create( Symbol op , Variable left , Variable right ) {\n switch( op ) {\n case PLUS:\n return Operation.add(left, right, managerTemp);\n\n case MINUS:\n return Operation.subtract(left, right, managerTemp);\n\n case TIMES:\n return Operation.multiply(left, right, managerTemp);\n\n case RDIVIDE:\n return Operation.divide(left, right, managerTemp);\n\n case LDIVIDE:\n return Operation.divide(right, left, managerTemp);\n\n case POWER:\n return Operation.pow(left, right, managerTemp);\n\n case ELEMENT_DIVIDE:\n return Operation.elementDivision(left, right, managerTemp);\n\n case ELEMENT_TIMES:\n return Operation.elementMult(left, right, managerTemp);\n\n case ELEMENT_POWER:\n return Operation.elementPow(left, right, managerTemp);\n\n default:\n throw new RuntimeException(\"Unknown operation \" + op);\n }\n }", "protected void addEnumList(String key, List<? extends Enum> list) {\n optionsMap.put(key, list.stream().map(i -> i.toString()).collect(Collectors.toList()));\n }" ]
Gets an expiring URL for downloading a file directly from Box. This can be user, for example, for sending as a redirect to a browser to cause the browser to download the file directly from Box. @return the temporary download URL
[ "public URL getDownloadURL() {\n URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n request.setFollowRedirects(false);\n\n BoxRedirectResponse response = (BoxRedirectResponse) request.send();\n\n return response.getRedirectURL();\n }" ]
[ "@Override\n\tpublic double getDiscountFactor(AnalyticModelInterface model, double maturity)\n\t{\n\t\t// Change time scale\n\t\tmaturity *= timeScaling;\n\n\t\tdouble beta1\t= parameter[0];\n\t\tdouble beta2\t= parameter[1];\n\t\tdouble beta3\t= parameter[2];\n\t\tdouble beta4\t= parameter[3];\n\t\tdouble tau1\t\t= parameter[4];\n\t\tdouble tau2\t\t= parameter[5];\n\n\t\tdouble x1 = tau1 > 0 ? FastMath.exp(-maturity/tau1) : 0.0;\n\t\tdouble x2 = tau2 > 0 ? FastMath.exp(-maturity/tau2) : 0.0;\n\n\t\tdouble y1 = tau1 > 0 ? (maturity > 0.0 ? (1.0-x1)/maturity*tau1 : 1.0) : 0.0;\n\t\tdouble y2 = tau2 > 0 ? (maturity > 0.0 ? (1.0-x2)/maturity*tau2 : 1.0) : 0.0;\n\n\t\tdouble zeroRate = beta1 + beta2 * y1 + beta3 * (y1-x1) + beta4 * (y2-x2);\n\n\t\treturn Math.exp(- zeroRate * maturity);\n\t}", "public final static String process(final String input, final Configuration configuration)\n {\n try\n {\n return process(new StringReader(input), configuration);\n }\n catch (final IOException e)\n {\n // This _can never_ happen\n return null;\n }\n }", "protected String statusMsg(final String queue, final Job job) throws IOException {\n final WorkerStatus status = new WorkerStatus();\n status.setRunAt(new Date());\n status.setQueue(queue);\n status.setPayload(job);\n return ObjectMapperFactory.get().writeValueAsString(status);\n }", "public void useXopAttachmentServiceWithWebClient() throws Exception {\n\n final String serviceURI = \"http://localhost:\" + port + \"/services/attachments/xop\";\n \n JAXRSClientFactoryBean factoryBean = new JAXRSClientFactoryBean();\n factoryBean.setAddress(serviceURI);\n factoryBean.setProperties(Collections.singletonMap(org.apache.cxf.message.Message.MTOM_ENABLED, \n (Object)\"true\"));\n WebClient client = factoryBean.createWebClient();\n WebClient.getConfig(client).getRequestContext().put(\"support.type.as.multipart\", \n \"true\"); \n client.type(\"multipart/related\").accept(\"multipart/related\");\n \n XopBean xop = createXopBean();\n \n System.out.println();\n System.out.println(\"Posting a XOP attachment with a WebClient\");\n \n XopBean xopResponse = client.post(xop, XopBean.class);\n \n verifyXopResponse(xop, xopResponse);\n }", "@UiHandler(\"m_everyDay\")\r\n void onEveryDayChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setInterval(m_everyDay.getFormValueAsString());\r\n }\r\n\r\n }", "ValidationResult isRestrictedEventName(String name) {\n ValidationResult error = new ValidationResult();\n if (name == null) {\n error.setErrorCode(510);\n error.setErrorDesc(\"Event Name is null\");\n return error;\n }\n for (String x : restrictedNames)\n if (name.equalsIgnoreCase(x)) {\n // The event name is restricted\n\n error.setErrorCode(513);\n error.setErrorDesc(name + \" is a restricted event name. Last event aborted.\");\n Logger.v(name + \" is a restricted system event name. Last event aborted.\");\n return error;\n }\n return error;\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 PhotoList<Photo> getContactsPhotos(int count, boolean justFriends, boolean singlePhoto, boolean includeSelf) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTACTS_PHOTOS);\r\n\r\n if (count > 0) {\r\n parameters.put(\"count\", Integer.toString(count));\r\n }\r\n if (justFriends) {\r\n parameters.put(\"just_friends\", \"1\");\r\n }\r\n if (singlePhoto) {\r\n parameters.put(\"single_photo\", \"1\");\r\n }\r\n if (includeSelf) {\r\n parameters.put(\"include_self\", \"1\");\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n photos.setPage(\"1\");\r\n photos.setPages(\"1\");\r\n photos.setPerPage(\"\" + photoNodes.getLength());\r\n photos.setTotal(\"\" + photoNodes.getLength());\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }", "public static boolean isMethodNamed(MethodCallExpression methodCall, String methodNamePattern, Integer numArguments) {\r\n Expression method = methodCall.getMethod();\r\n\r\n // !important: performance enhancement\r\n boolean IS_NAME_MATCH = false;\r\n if (method instanceof ConstantExpression) {\r\n if (((ConstantExpression) method).getValue() instanceof String) {\r\n IS_NAME_MATCH = ((String)((ConstantExpression) method).getValue()).matches(methodNamePattern);\r\n }\r\n }\r\n\r\n if (IS_NAME_MATCH && numArguments != null) {\r\n return AstUtil.getMethodArguments(methodCall).size() == numArguments;\r\n }\r\n return IS_NAME_MATCH;\r\n }" ]
Wait until a scan of the table completes without seeing notifications AND without the Oracle issuing any timestamps during the scan.
[ "private static void waitUntilFinished(FluoConfiguration config) {\n try (Environment env = new Environment(config)) {\n List<TableRange> ranges = getRanges(env);\n\n outer: while (true) {\n long ts1 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp();\n for (TableRange range : ranges) {\n boolean sawNotifications = waitTillNoNotifications(env, range);\n if (sawNotifications) {\n ranges = getRanges(env);\n // This range had notifications. Processing those notifications may have created\n // notifications in previously scanned ranges, so start over.\n continue outer;\n }\n }\n long ts2 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp();\n\n // Check to ensure the Oracle issued no timestamps during the scan for notifications.\n if (ts2 - ts1 == 1) {\n break;\n }\n }\n } catch (Exception e) {\n log.error(\"An exception was thrown -\", e);\n System.exit(-1);\n }\n }" ]
[ "private boolean renameKeyForAllLanguages(String oldKey, String newKey) {\n\n try {\n loadAllRemainingLocalizations();\n lockAllLocalizations(oldKey);\n if (hasDescriptor()) {\n lockDescriptor();\n }\n } catch (CmsException | IOException e) {\n LOG.error(e.getLocalizedMessage(), e);\n return false;\n }\n for (Entry<Locale, SortedProperties> entry : m_localizations.entrySet()) {\n SortedProperties localization = entry.getValue();\n if (localization.containsKey(oldKey)) {\n String value = localization.getProperty(oldKey);\n localization.remove(oldKey);\n localization.put(newKey, value);\n m_changedTranslations.add(entry.getKey());\n }\n }\n if (hasDescriptor()) {\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 String key = m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).getStringValue(m_cms);\n if (key == oldKey) {\n m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).setStringValue(m_cms, newKey);\n break;\n }\n }\n m_descriptorHasChanges = true;\n }\n m_keyset.renameKey(oldKey, newKey);\n return true;\n }", "public Bundler put(String key, Serializable value) {\n delegate.putSerializable(key, value);\n return this;\n }", "public synchronized static <D extends Dao<T, ?>, T> D lookupDao(ConnectionSource connectionSource, Class<T> clazz) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\tClassConnectionSource key = new ClassConnectionSource(connectionSource, clazz);\n\t\tDao<?, ?> dao = lookupDao(key);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tD castDao = (D) dao;\n\t\treturn castDao;\n\t}", "private void merge(ExecutionStatistics otherStatistics) {\n for (String s : otherStatistics.executionInfo.keySet())\n {\n TimingData thisStats = this.executionInfo.get(s);\n TimingData otherStats = otherStatistics.executionInfo.get(s);\n if(thisStats == null) {\n this.executionInfo.put(s,otherStats);\n } else {\n thisStats.merge(otherStats);\n }\n\n }\n }", "public Set<Action.ActionEffect> getActionEffects() {\n switch(getImpact()) {\n case CLASSLOADING:\n case WRITE:\n return WRITES;\n case READ_ONLY:\n return READS;\n default:\n throw new IllegalStateException();\n }\n\n }", "void insertMacros(TokenList tokens ) {\n TokenList.Token t = tokens.getFirst();\n while( t != null ) {\n if( t.getType() == Type.WORD ) {\n Macro v = lookupMacro(t.word);\n if (v != null) {\n TokenList.Token before = t.previous;\n List<TokenList.Token> inputs = new ArrayList<TokenList.Token>();\n t = parseMacroInput(inputs,t.next);\n\n TokenList sniplet = v.execute(inputs);\n tokens.extractSubList(before.next,t);\n tokens.insertAfter(before,sniplet);\n t = sniplet.last;\n }\n }\n t = t.next;\n }\n }", "public Object getFieldByAlias(String alias)\n {\n return getCachedValue(getParentFile().getCustomFields().getFieldByAlias(FieldTypeClass.TASK, alias));\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 VerticalLayout getEmptyLayout() {\n\n m_emptyLayout = CmsVaadinUtils.getInfoLayout(CmsOuTreeType.USER.getEmptyMessageKey());\n setVisible(size() > 0);\n m_emptyLayout.setVisible(size() == 0);\n return m_emptyLayout;\n }" ]
Write a calendar. @param record calendar instance @throws IOException
[ "private void writeCalendar(ProjectCalendar record) throws IOException\n {\n //\n // Test used to ensure that we don't write the default calendar used for the \"Unassigned\" resource\n //\n if (record.getParent() == null || record.getResource() != null)\n {\n m_buffer.setLength(0);\n\n if (record.getParent() == null)\n {\n m_buffer.append(MPXConstants.BASE_CALENDAR_RECORD_NUMBER);\n m_buffer.append(m_delimiter);\n if (record.getName() != null)\n {\n m_buffer.append(record.getName());\n }\n }\n else\n {\n m_buffer.append(MPXConstants.RESOURCE_CALENDAR_RECORD_NUMBER);\n m_buffer.append(m_delimiter);\n m_buffer.append(record.getParent().getName());\n }\n\n for (DayType day : record.getDays())\n {\n if (day == null)\n {\n day = DayType.DEFAULT;\n }\n m_buffer.append(m_delimiter);\n m_buffer.append(day.getValue());\n }\n\n m_buffer.append(MPXConstants.EOL);\n m_writer.write(m_buffer.toString());\n\n ProjectCalendarHours[] hours = record.getHours();\n for (int loop = 0; loop < hours.length; loop++)\n {\n if (hours[loop] != null)\n {\n writeCalendarHours(record, hours[loop]);\n }\n }\n\n if (!record.getCalendarExceptions().isEmpty())\n {\n //\n // A quirk of MS Project is that these exceptions must be\n // in date order in the file, otherwise they are ignored.\n // The getCalendarExceptions method now guarantees that\n // the exceptions list is sorted when retrieved.\n //\n for (ProjectCalendarException ex : record.getCalendarExceptions())\n {\n writeCalendarException(record, ex);\n }\n }\n\n m_eventManager.fireCalendarWrittenEvent(record);\n }\n }" ]
[ "public static void findSomeStringProperties(ApiConnection connection)\n\t\t\tthrows MediaWikiApiErrorException, IOException {\n\t\tWikibaseDataFetcher wbdf = new WikibaseDataFetcher(connection, siteIri);\n\t\twbdf.getFilter().excludeAllProperties();\n\t\twbdf.getFilter().setLanguageFilter(Collections.singleton(\"en\"));\n\n\t\tArrayList<PropertyIdValue> stringProperties = new ArrayList<>();\n\n\t\tSystem.out\n\t\t\t\t.println(\"*** Trying to find string properties for the example ... \");\n\t\tint propertyNumber = 1;\n\t\twhile (stringProperties.size() < 5) {\n\t\t\tArrayList<String> fetchProperties = new ArrayList<>();\n\t\t\tfor (int i = propertyNumber; i < propertyNumber + 10; i++) {\n\t\t\t\tfetchProperties.add(\"P\" + i);\n\t\t\t}\n\t\t\tpropertyNumber += 10;\n\t\t\tMap<String, EntityDocument> results = wbdf\n\t\t\t\t\t.getEntityDocuments(fetchProperties);\n\t\t\tfor (EntityDocument ed : results.values()) {\n\t\t\t\tPropertyDocument pd = (PropertyDocument) ed;\n\t\t\t\tif (DatatypeIdValue.DT_STRING.equals(pd.getDatatype().getIri())\n\t\t\t\t\t\t&& pd.getLabels().containsKey(\"en\")) {\n\t\t\t\t\tstringProperties.add(pd.getEntityId());\n\t\t\t\t\tSystem.out.println(\"* Found string property \"\n\t\t\t\t\t\t\t+ pd.getEntityId().getId() + \" (\"\n\t\t\t\t\t\t\t+ pd.getLabels().get(\"en\") + \")\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstringProperty1 = stringProperties.get(0);\n\t\tstringProperty2 = stringProperties.get(1);\n\t\tstringProperty3 = stringProperties.get(2);\n\t\tstringProperty4 = stringProperties.get(3);\n\t\tstringProperty5 = stringProperties.get(4);\n\n\t\tSystem.out.println(\"*** Done.\");\n\t}", "public void modified(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {\n declarationBinders.get(declarationBinderRef).update(declarationBinderRef);\n }", "public static void main(String[] args) throws IOException {\n\t\tExampleHelpers.configureLogging();\n\t\tJsonSerializationProcessor.printDocumentation();\n\n\t\tJsonSerializationProcessor jsonSerializationProcessor = new JsonSerializationProcessor();\n\t\tExampleHelpers.processEntitiesFromWikidataDump(jsonSerializationProcessor);\n\t\tjsonSerializationProcessor.close();\n\t}", "public static String digestToFileName(String digest) {\n if (StringUtils.startsWith(digest, \"sha1\")) {\n return \"manifest.json\";\n }\n return getShaVersion(digest) + \"__\" + getShaValue(digest);\n }", "private Properties parseFile(File file) throws InvalidDeclarationFileException {\n Properties properties = new Properties();\n InputStream is = null;\n try {\n is = new FileInputStream(file);\n properties.load(is);\n } catch (Exception e) {\n throw new InvalidDeclarationFileException(String.format(\"Error reading declaration file %s\", file.getAbsoluteFile()), e);\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n LOG.error(\"IOException thrown while trying to close the declaration file.\", e);\n }\n }\n }\n\n if (!properties.containsKey(Constants.ID)) {\n throw new InvalidDeclarationFileException(String.format(\"File %s is not a correct declaration, needs to contains an id property\", file.getAbsoluteFile()));\n }\n return properties;\n }", "@SuppressWarnings({\"unchecked\", \"unused\"})\n public static <T> T[] object2Array(final Class<T> clazz, final Object obj) {\n return (T[]) obj;\n }", "protected Class<?> getPropertyClass(ClassMetadata meta, String propertyName) throws HibernateLayerException {\n\t\t// try to assure the correct separator is used\n\t\tpropertyName = propertyName.replace(XPATH_SEPARATOR, SEPARATOR);\n\n\t\tif (propertyName.contains(SEPARATOR)) {\n\t\t\tString directProperty = propertyName.substring(0, propertyName.indexOf(SEPARATOR));\n\t\t\ttry {\n\t\t\t\tType prop = meta.getPropertyType(directProperty);\n\t\t\t\tif (prop.isCollectionType()) {\n\t\t\t\t\tCollectionType coll = (CollectionType) prop;\n\t\t\t\t\tprop = coll.getElementType((SessionFactoryImplementor) sessionFactory);\n\t\t\t\t}\n\t\t\t\tClassMetadata propMeta = sessionFactory.getClassMetadata(prop.getReturnedClass());\n\t\t\t\treturn getPropertyClass(propMeta, propertyName.substring(propertyName.indexOf(SEPARATOR) + 1));\n\t\t\t} catch (HibernateException e) {\n\t\t\t\tthrow new HibernateLayerException(e, ExceptionCode.HIBERNATE_COULD_NOT_RESOLVE, propertyName,\n\t\t\t\t\t\tmeta.getEntityName());\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\treturn meta.getPropertyType(propertyName).getReturnedClass();\n\t\t\t} catch (HibernateException e) {\n\t\t\t\tthrow new HibernateLayerException(e, ExceptionCode.HIBERNATE_COULD_NOT_RESOLVE, propertyName,\n\t\t\t\t\t\tmeta.getEntityName());\n\t\t\t}\n\t\t}\n\t}", "public static base_response update(nitro_service client, nsdiameter resource) throws Exception {\n\t\tnsdiameter updateresource = new nsdiameter();\n\t\tupdateresource.identity = resource.identity;\n\t\tupdateresource.realm = resource.realm;\n\t\tupdateresource.serverclosepropagation = resource.serverclosepropagation;\n\t\treturn updateresource.update_resource(client);\n\t}", "public int getCostRateTableIndex()\n {\n Integer value = (Integer) getCachedValue(AssignmentField.COST_RATE_TABLE);\n return value == null ? 0 : value.intValue();\n }" ]
Exchanges the initial fully-formed messages which establishes the transaction context for queries to the dbserver. @throws IOException if there is a problem during the exchange
[ "private void performSetupExchange() throws IOException {\n Message setupRequest = new Message(0xfffffffeL, Message.KnownType.SETUP_REQ, new NumberField(posingAsPlayer, 4));\n sendMessage(setupRequest);\n Message response = Message.read(is);\n if (response.knownType != Message.KnownType.MENU_AVAILABLE) {\n throw new IOException(\"Did not receive message type 0x4000 in response to setup message, got: \" + response);\n }\n if (response.arguments.size() != 2) {\n throw new IOException(\"Did not receive two arguments in response to setup message, got: \" + response);\n }\n final Field player = response.arguments.get(1);\n if (!(player instanceof NumberField)) {\n throw new IOException(\"Second argument in response to setup message was not a number: \" + response);\n }\n if (((NumberField)player).getValue() != targetPlayer) {\n throw new IOException(\"Expected to connect to player \" + targetPlayer +\n \", but welcome response identified itself as player \" + ((NumberField)player).getValue());\n }\n }" ]
[ "@Inline(value = \"$1.remove($2.getKey(), $2.getValue())\", statementExpression = true)\n\tpublic static <K, V> boolean operator_remove(Map<K, V> map, Pair<? extends K, ? extends V> entry) {\n\t\t//TODO use the JRE 1.8 API: map.remove(entry.getKey(), entry.getValue());\n\t\tfinal K key = entry.getKey();\n\t\tfinal V storedValue = map.get(entry.getKey());\n\t if (!Objects.equal(storedValue, entry.getValue())\n\t\t\t|| (storedValue == null && !map.containsKey(key))) {\n\t return false;\n \t}\n \tmap.remove(key);\n\t return true;\n\t}", "public void initialize(FragmentManager fragmentManager) {\n AirMapInterface mapInterface = (AirMapInterface)\n fragmentManager.findFragmentById(R.id.map_frame);\n\n if (mapInterface != null) {\n initialize(fragmentManager, mapInterface);\n } else {\n initialize(fragmentManager, new DefaultAirMapViewBuilder(getContext()).builder().build());\n }\n }", "public ViewPort then(Functions.Func1<ViewPortChange> then, ViewPortFallback fallback) {\n assert then != null : \"'then' callback cannot be null\";\n this.then = then;\n this.fallback = fallback;\n return load();\n }", "private void populateRelationList(Task task, TaskField field, String data)\n {\n DeferredRelationship dr = new DeferredRelationship();\n dr.setTask(task);\n dr.setField(field);\n dr.setData(data);\n m_deferredRelationships.add(dr);\n }", "private void readPage(byte[] buffer, Table table)\n {\n int magicNumber = getShort(buffer, 0);\n if (magicNumber == 0x4400)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, 0, 6, true, 16, \"\"));\n int recordSize = m_definition.getRecordSize();\n RowValidator rowValidator = m_definition.getRowValidator();\n String primaryKeyColumnName = m_definition.getPrimaryKeyColumnName();\n\n int index = 6;\n while (index + recordSize <= buffer.length)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, index, recordSize, true, 16, \"\"));\n int btrieveValue = getShort(buffer, index);\n if (btrieveValue != 0)\n {\n Map<String, Object> row = new HashMap<String, Object>();\n row.put(\"ROW_VERSION\", Integer.valueOf(btrieveValue));\n for (ColumnDefinition column : m_definition.getColumns())\n {\n Object value = column.read(index, buffer);\n //System.out.println(column.getName() + \": \" + value);\n row.put(column.getName(), value);\n }\n\n if (rowValidator == null || rowValidator.validRow(row))\n {\n table.addRow(primaryKeyColumnName, row);\n }\n }\n index += recordSize;\n }\n }\n }", "public final static int readUntil(final StringBuilder out, final String in, final int start, final char end)\n {\n int pos = start;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (ch == '\\\\' && pos + 1 < in.length())\n {\n pos = escape(out, in.charAt(pos + 1), pos);\n }\n else\n {\n if (ch == end)\n {\n break;\n }\n out.append(ch);\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }", "public double multi8p(int x, int y, double masc) {\n int aR = getIntComponent0(x - 1, y - 1);\n int bR = getIntComponent0(x - 1, y);\n int cR = getIntComponent0(x - 1, y + 1);\n int aG = getIntComponent1(x - 1, y - 1);\n int bG = getIntComponent1(x - 1, y);\n int cG = getIntComponent1(x - 1, y + 1);\n int aB = getIntComponent1(x - 1, y - 1);\n int bB = getIntComponent1(x - 1, y);\n int cB = getIntComponent1(x - 1, y + 1);\n\n\n int dR = getIntComponent0(x, y - 1);\n int eR = getIntComponent0(x, y);\n int fR = getIntComponent0(x, y + 1);\n int dG = getIntComponent1(x, y - 1);\n int eG = getIntComponent1(x, y);\n int fG = getIntComponent1(x, y + 1);\n int dB = getIntComponent1(x, y - 1);\n int eB = getIntComponent1(x, y);\n int fB = getIntComponent1(x, y + 1);\n\n\n int gR = getIntComponent0(x + 1, y - 1);\n int hR = getIntComponent0(x + 1, y);\n int iR = getIntComponent0(x + 1, y + 1);\n int gG = getIntComponent1(x + 1, y - 1);\n int hG = getIntComponent1(x + 1, y);\n int iG = getIntComponent1(x + 1, y + 1);\n int gB = getIntComponent1(x + 1, y - 1);\n int hB = getIntComponent1(x + 1, y);\n int iB = getIntComponent1(x + 1, y + 1);\n\n double rgb = 0;\n\n rgb = ((aR * masc) + (bR * masc) + (cR * masc) +\n (dR * masc) + (eR * masc) + (fR * masc) +\n (gR * masc) + (hR * masc) + (iR * masc));\n\n return (rgb);\n\n }", "public static Bitmap decodeStream(InputStream stream, boolean closeStream) {\n return AsyncBitmapTexture.decodeStream(stream,\n AsyncBitmapTexture.glMaxTextureSize,\n AsyncBitmapTexture.glMaxTextureSize, true, null, closeStream);\n }", "protected String generateCacheKey(\n CmsObject cms,\n String targetSiteRoot,\n String detailPagePart,\n String absoluteLink) {\n\n return cms.getRequestContext().getSiteRoot() + \":\" + targetSiteRoot + \":\" + detailPagePart + absoluteLink;\n }" ]
Returns a copy of the given document. @param document the document to copy. @return a copy of the given document.
[ "public static BsonDocument copyOfDocument(final BsonDocument document) {\n final BsonDocument newDocument = new BsonDocument();\n for (final Map.Entry<String, BsonValue> kv : document.entrySet()) {\n newDocument.put(kv.getKey(), kv.getValue());\n }\n return newDocument;\n }" ]
[ "public LuaScript endScriptReturn(LuaValue value, LuaScriptConfig config) {\n add(new LuaAstReturnStatement(argument(value)));\n String scriptText = buildScriptText();\n return new BasicLuaScript(scriptText, config);\n }", "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 static appflowpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tappflowpolicy_binding obj = new appflowpolicy_binding();\n\t\tobj.set_name(name);\n\t\tappflowpolicy_binding response = (appflowpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "private String formatTime(Date value)\n {\n return (value == null ? null : m_formats.getTimeFormat().format(value));\n }", "public void onDrawFrame(float frameTime) {\n final GVRSceneObject owner = getOwnerObject();\n if (owner == null) {\n return;\n }\n\n final int size = mRanges.size();\n final GVRTransform t = getGVRContext().getMainScene().getMainCameraRig().getCenterCamera().getTransform();\n\n for (final Object[] range : mRanges) {\n ((GVRSceneObject)range[1]).setEnable(false);\n }\n\n for (int i = size - 1; i >= 0; --i) {\n final Object[] range = mRanges.get(i);\n final GVRSceneObject child = (GVRSceneObject) range[1];\n if (child.getParent() != owner) {\n Log.w(TAG, \"the scene object for distance greater than \" + range[0] + \" is not a child of the owner; skipping it\");\n continue;\n }\n\n final float[] values = child.getBoundingVolumeRawValues();\n mCenter.set(values[0], values[1], values[2], 1.0f);\n mVector.set(t.getPositionX(), t.getPositionY(), t.getPositionZ(), 1.0f);\n\n mVector.sub(mCenter);\n mVector.negate();\n\n float distance = mVector.dot(mVector);\n\n if (distance >= (Float) range[0]) {\n child.setEnable(true);\n break;\n }\n }\n }", "public static String encodeUserInfo(String userInfo, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(userInfo, encoding, HierarchicalUriComponents.Type.USER_INFO);\n\t}", "protected Boolean getIgnoreQuery() {\n\n Boolean isIgnoreQuery = parseOptionalBooleanValue(m_configObject, JSON_KEY_IGNORE_QUERY);\n return (null == isIgnoreQuery) && (m_baseConfig != null)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getIgnoreQueryParam())\n : isIgnoreQuery;\n }", "public static SQLException create(String message, Throwable cause) {\n\t\tSQLException sqlException;\n\t\tif (cause instanceof SQLException) {\n\t\t\t// if the cause is another SQLException, pass alot of the SQL state\n\t\t\tsqlException = new SQLException(message, ((SQLException) cause).getSQLState());\n\t\t} else {\n\t\t\tsqlException = new SQLException(message);\n\t\t}\n\t\tsqlException.initCause(cause);\n\t\treturn sqlException;\n\t}", "private static JSONObject parseProperties(HashMap<String, String> properties) throws JSONException {\n if (properties != null) {\n JSONObject propertiesObject = new JSONObject();\n\n for (String key : properties.keySet()) {\n String propertyValue = properties.get(key);\n\n /*\n * if(propertyValue.matches(\"true|false\")) {\n * \n * propertiesObject.put(key, propertyValue.equals(\"true\"));\n * \n * } else if(propertyValue.matches(\"[0-9]+\")) {\n * \n * Integer value = Integer.parseInt(propertyValue);\n * propertiesObject.put(key, value);\n * \n * } else\n */\n if (propertyValue.startsWith(\"{\") && propertyValue.endsWith(\"}\")) {\n propertiesObject.put(key,\n new JSONObject(propertyValue));\n } else {\n propertiesObject.put(key,\n propertyValue.toString());\n }\n }\n\n return propertiesObject;\n }\n\n return new JSONObject();\n }" ]
dataType in weight descriptors and input descriptors is used to describe storage
[ "public static int cudnnGetRNNWorkspaceSize(\n cudnnHandle handle, \n cudnnRNNDescriptor rnnDesc, \n int seqLength, \n cudnnTensorDescriptor[] xDesc, \n long[] sizeInBytes)\n {\n return checkResult(cudnnGetRNNWorkspaceSizeNative(handle, rnnDesc, seqLength, xDesc, sizeInBytes));\n }" ]
[ "void endOfRunDb()\n {\n DbConn cnx = null;\n\n try\n {\n cnx = Helpers.getNewDbSession();\n\n // Done: put inside history & remove instance from queue.\n History.create(cnx, this.ji, this.resultStatus, endDate);\n jqmlogger.trace(\"An History was just created for job instance \" + this.ji.getId());\n cnx.runUpdate(\"ji_delete_by_id\", this.ji.getId());\n cnx.commit();\n }\n catch (RuntimeException e)\n {\n endBlockDbFailureAnalysis(e);\n }\n finally\n {\n Helpers.closeQuietly(cnx);\n }\n }", "public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n String url = null;\n Boolean confirm = false;\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 AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_CONFIRM)) {\n confirm = true;\n }\n\n // print summary\n System.out.println(\"Synchronize metadata versions across all nodes\");\n System.out.println(\"Location:\");\n System.out.println(\" bootstrap url = \" + url);\n System.out.println(\" node = all nodes\");\n\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n AdminToolUtils.assertServerNotInRebalancingState(adminClient);\n\n Versioned<Properties> versionedProps = mergeAllVersions(adminClient);\n\n printVersions(versionedProps);\n\n // execute command\n if(!AdminToolUtils.askConfirm(confirm,\n \"do you want to synchronize metadata versions to all node\"))\n return;\n\n adminClient.metadataMgmtOps.setMetadataVersion(versionedProps);\n }", "public List<String> getMultiSelect(String path) {\n List<String> values = new ArrayList<String>();\n for (JsonValue val : this.getValue(path).asArray()) {\n values.add(val.asString());\n }\n\n return values;\n }", "public static void main(final String[] args) {\n if (System.getProperty(\"db.name\") == null) {\n System.out.println(\"Not running in multi-instance mode: no DB to connect to\");\n System.exit(1);\n }\n while (true) {\n try {\n Class.forName(\"org.postgresql.Driver\");\n DriverManager.getConnection(\"jdbc:postgresql://\" + System.getProperty(\"db.host\") + \":5432/\" +\n System.getProperty(\"db.name\"),\n System.getProperty(\"db.username\"),\n System.getProperty(\"db.password\"));\n System.out.println(\"Opened database successfully. Running in multi-instance mode\");\n System.exit(0);\n return;\n } catch (Exception e) {\n System.out.println(\"Failed to connect to the DB: \" + e.toString());\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e1) {\n //ignored\n }\n }\n }\n }", "private Double zeroIsNull(Double value)\n {\n if (value != null && value.doubleValue() == 0)\n {\n value = null;\n }\n return value;\n }", "protected NodeData createBlockStyle()\n {\n NodeData ret = CSSFactory.createNodeData();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"display\", tf.createIdent(\"block\")));\n return ret;\n }", "public static Chart getMSDLineWithPowerModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double a, double D) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tdouble[] modelData = new double[lagMax - lagMin + 1];\n\t\tMeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(\n\t\t\t\tt, lagMin);\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t\tmodelData[i - lagMin] = 4 * D * Math.pow(i * timelag, a);\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\t\tchart.addSeries(\"y=4*D*t^alpha\", xData, modelData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}", "public Profile[] getProfilesForServerName(String serverName) throws Exception {\n int profileId = -1;\n ArrayList<Profile> returnProfiles = new ArrayList<Profile>();\n\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.GENERIC_PROFILE_ID + \" FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.SERVER_REDIRECT_SRC_URL + \" = ? GROUP BY \" +\n Constants.GENERIC_PROFILE_ID\n );\n queryStatement.setString(1, serverName);\n results = queryStatement.executeQuery();\n\n while (results.next()) {\n profileId = results.getInt(Constants.GENERIC_PROFILE_ID);\n\n Profile profile = ProfileService.getInstance().findProfile(profileId);\n\n returnProfiles.add(profile);\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 (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n if (returnProfiles.size() == 0) {\n return null;\n }\n return returnProfiles.toArray(new Profile[0]);\n }", "String buildSelect(String htmlAttributes, SelectOptions options) {\n\n return buildSelect(htmlAttributes, options.getOptions(), options.getValues(), options.getSelectedIndex());\n }" ]
Set the value of a field using its alias. @param alias field alias @param value field value
[ "public void setFieldByAlias(String alias, Object value)\n {\n set(getParentFile().getCustomFields().getFieldByAlias(FieldTypeClass.TASK, alias), value);\n }" ]
[ "public Replication targetOauth(String consumerSecret, String consumerKey, String tokenSecret,\n String token) {\n targetOauth = new JsonObject();\n this.consumerSecret = consumerSecret;\n this.consumerKey = consumerKey;\n this.tokenSecret = tokenSecret;\n this.token = token;\n return this;\n }", "public void shutdown() {\n final Connection connection;\n synchronized (this) {\n if(shutdown) return;\n shutdown = true;\n connection = this.connection;\n if(connectTask != null) {\n connectTask.shutdown();\n }\n }\n if (connection != null) {\n connection.closeAsync();\n }\n }", "public static DMatrixRMaj stripReal(ZMatrixD1 input , DMatrixRMaj output ) {\n if( output == null ) {\n output = new DMatrixRMaj(input.numRows,input.numCols);\n } else if( input.numCols != output.numCols || input.numRows != output.numRows ) {\n throw new IllegalArgumentException(\"The matrices are not all the same dimension.\");\n }\n\n final int length = input.getDataLength();\n\n for( int i = 0; i < length; i += 2 ) {\n output.data[i/2] = input.data[i];\n }\n return output;\n }", "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 }", "public List<ProjectFile> readAll(InputStream is, boolean linkCrossProjectRelations) throws MPXJException\n {\n try\n {\n m_tables = new HashMap<String, List<Row>>();\n m_numberFormat = new DecimalFormat();\n\n processFile(is);\n\n List<Row> rows = getRows(\"project\", null, null);\n List<ProjectFile> result = new ArrayList<ProjectFile>(rows.size());\n List<ExternalPredecessorRelation> externalPredecessors = new ArrayList<ExternalPredecessorRelation>();\n for (Row row : rows)\n {\n setProjectID(row.getInt(\"proj_id\"));\n\n m_reader = new PrimaveraReader(m_taskUdfCounters, m_resourceUdfCounters, m_assignmentUdfCounters, m_resourceFields, m_wbsFields, m_taskFields, m_assignmentFields, m_aliases, m_matchPrimaveraWBS);\n ProjectFile project = m_reader.getProject();\n project.getEventManager().addProjectListeners(m_projectListeners);\n\n processProjectProperties();\n processUserDefinedFields();\n processCalendars();\n processResources();\n processResourceRates();\n processTasks();\n processPredecessors();\n processAssignments();\n\n externalPredecessors.addAll(m_reader.getExternalPredecessors());\n\n m_reader = null;\n project.updateStructure();\n\n result.add(project);\n }\n\n if (linkCrossProjectRelations)\n {\n for (ExternalPredecessorRelation externalRelation : externalPredecessors)\n {\n Task predecessorTask;\n // we could aggregate the project task id maps but that's likely more work\n // than just looping through the projects\n for (ProjectFile proj : result)\n {\n predecessorTask = proj.getTaskByUniqueID(externalRelation.getSourceUniqueID());\n if (predecessorTask != null)\n {\n Relation relation = externalRelation.getTargetTask().addPredecessor(predecessorTask, externalRelation.getType(), externalRelation.getLag());\n relation.setUniqueID(externalRelation.getUniqueID());\n break;\n }\n }\n // if predecessorTask not found the external task is outside of the file so ignore\n }\n }\n\n return result;\n }\n\n finally\n {\n m_reader = null;\n m_tables = null;\n m_currentTableName = null;\n m_currentTable = null;\n m_currentFieldNames = null;\n m_defaultCurrencyName = null;\n m_currencyMap.clear();\n m_numberFormat = null;\n m_defaultCurrencyData = null;\n }\n }", "@Override\n\tpublic void validate() throws AddressStringException {\n\t\tif(isValidated()) {\n\t\t\treturn;\n\t\t}\n\t\tsynchronized(this) {\n\t\t\tif(isValidated()) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t//we know nothing about this address. See what it is.\n\t\t\ttry {\n\t\t\t\tparsedAddress = getValidator().validateAddress(this);\n\t\t\t\tisValid = true;\n\t\t\t} catch(AddressStringException e) {\n\t\t\t\tcachedException = e;\n\t\t\t\tisValid = false;\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t}", "public AppMsg setLayoutGravity(int gravity) {\n mLayoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, gravity);\n return this;\n }", "@Override\n public void updateStoreDefinition(StoreDefinition storeDef) {\n this.storeDef = storeDef;\n if(storeDef.hasRetentionPeriod())\n this.retentionTimeMs = storeDef.getRetentionDays() * Time.MS_PER_DAY;\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}" ]
Writes a presentable version of the given PTB-tokenized text. PTB tokenization splits up punctuation and does various other things that makes simply joining the tokens with spaces look bad. So join the tokens with space and run it through this method to produce nice looking text. It's not perfect, but it works pretty well.
[ "public static int ptb2Text(Reader ptbText, Writer w) throws IOException {\r\n int numTokens = 0;\r\n PTB2TextLexer lexer = new PTB2TextLexer(ptbText);\r\n for (String token; (token = lexer.next()) != null; ) {\r\n numTokens++;\r\n w.write(token);\r\n }\r\n return numTokens;\r\n }" ]
[ "public InsertIntoTable addRowsFromDelimited(File file, String delimiter, Object nullValue) {\n builder.addRowsFromDelimited(file, delimiter, nullValue);\n return this;\n }", "public Metadata remove(String path) {\n this.values.remove(this.pathToProperty(path));\n this.addOp(\"remove\", path, (String) null);\n return this;\n }", "@Override\n public void close() throws IOException {\n // Notify encoder of EOF (-1).\n if (doEncode) {\n baseNCodec.encode(singleByte, 0, EOF, context);\n } else {\n baseNCodec.decode(singleByte, 0, EOF, context);\n }\n flush();\n out.close();\n }", "public synchronized Response<ByteArray, Object> responseQueuePoll(long timeout,\n TimeUnit timeUnit)\n throws InterruptedException {\n long timeoutMs = timeUnit.toMillis(timeout);\n long timeoutWallClockMs = System.currentTimeMillis() + timeoutMs;\n while(responseQueue.isEmpty() && System.currentTimeMillis() < timeoutWallClockMs) {\n long remainingMs = Math.max(0, timeoutWallClockMs - System.currentTimeMillis());\n if(logger.isDebugEnabled()) {\n logger.debug(\"Start waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n this.wait(remainingMs);\n if(logger.isDebugEnabled()) {\n logger.debug(\"End waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n }\n return responseQueue.poll();\n }", "public CentralDogmaBuilder port(InetSocketAddress localAddress, SessionProtocol protocol) {\n return port(new ServerPort(localAddress, protocol));\n }", "public PhotoAllContext getAllContexts(String photoId) throws FlickrException {\r\n PhotoSetList<PhotoSet> setList = new PhotoSetList<PhotoSet>();\r\n PoolList<Pool> poolList = new PoolList<Pool>();\r\n PhotoAllContext allContext = new PhotoAllContext();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_ALL_CONTEXTS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Collection<Element> photosElement = response.getPayloadCollection();\r\n\r\n for (Element setElement : photosElement) {\r\n if (setElement.getTagName().equals(\"set\")) {\r\n PhotoSet pset = new PhotoSet();\r\n pset.setTitle(setElement.getAttribute(\"title\"));\r\n pset.setSecret(setElement.getAttribute(\"secret\"));\r\n pset.setId(setElement.getAttribute(\"id\"));\r\n pset.setFarm(setElement.getAttribute(\"farm\"));\r\n pset.setPrimary(setElement.getAttribute(\"primary\"));\r\n pset.setServer(setElement.getAttribute(\"server\"));\r\n pset.setViewCount(Integer.parseInt(setElement.getAttribute(\"view_count\")));\r\n pset.setCommentCount(Integer.parseInt(setElement.getAttribute(\"comment_count\")));\r\n pset.setCountPhoto(Integer.parseInt(setElement.getAttribute(\"count_photo\")));\r\n pset.setCountVideo(Integer.parseInt(setElement.getAttribute(\"count_video\")));\r\n setList.add(pset);\r\n allContext.setPhotoSetList(setList);\r\n } else if (setElement.getTagName().equals(\"pool\")) {\r\n Pool pool = new Pool();\r\n pool.setTitle(setElement.getAttribute(\"title\"));\r\n pool.setId(setElement.getAttribute(\"id\"));\r\n pool.setUrl(setElement.getAttribute(\"url\"));\r\n pool.setIconServer(setElement.getAttribute(\"iconserver\"));\r\n pool.setIconFarm(setElement.getAttribute(\"iconfarm\"));\r\n pool.setMemberCount(Integer.parseInt(setElement.getAttribute(\"members\")));\r\n pool.setPoolCount(Integer.parseInt(setElement.getAttribute(\"pool_count\")));\r\n poolList.add(pool);\r\n allContext.setPoolList(poolList);\r\n }\r\n }\r\n\r\n return allContext;\r\n\r\n }", "public synchronized void removeControlPoint(ControlPoint controlPoint) {\n if (controlPoint.decreaseReferenceCount() == 0) {\n ControlPointIdentifier id = new ControlPointIdentifier(controlPoint.getDeployment(), controlPoint.getEntryPoint());\n entryPoints.remove(id);\n }\n }", "public static vpnvserver_auditnslogpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_auditnslogpolicy_binding obj = new vpnvserver_auditnslogpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_auditnslogpolicy_binding response[] = (vpnvserver_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static base_response update(nitro_service client, autoscaleaction resource) throws Exception {\n\t\tautoscaleaction updateresource = new autoscaleaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.profilename = resource.profilename;\n\t\tupdateresource.parameters = resource.parameters;\n\t\tupdateresource.vmdestroygraceperiod = resource.vmdestroygraceperiod;\n\t\tupdateresource.quiettime = resource.quiettime;\n\t\tupdateresource.vserver = resource.vserver;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Load the properties from the resource file if one is specified
[ "private void loadResourceFile(URL configurationResourceUrl, Properties hotRodConfiguration) {\n\t\tif ( configurationResourceUrl != null ) {\n\t\t\ttry ( InputStream openStream = configurationResourceUrl.openStream() ) {\n\t\t\t\thotRodConfiguration.load( openStream );\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\tthrow log.failedLoadingHotRodConfigurationProperties( e );\n\t\t\t}\n\t\t}\n\t}" ]
[ "@Override\n public T getById(Object id)\n {\n return context.getFramed().getFramedVertex(this.type, id);\n }", "@SuppressWarnings({\"unchecked\", \"WeakerAccess\"})\n public static <T> List<T> readListAttributeElement(final XMLExtendedStreamReader reader, final String attributeName,\n final Class<T> type) throws XMLStreamException {\n requireSingleAttribute(reader, attributeName);\n // todo: fix this when this method signature is corrected\n final List<T> value = (List<T>) reader.getListAttributeValue(0, type);\n requireNoContent(reader);\n return value;\n }", "public static String getDateTimeStr(Date d) {\n if (d == null)\n return \"\";\n\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss.SSSZ\");\n // 20140315 test will problem +0000\n return sdf.format(d);\n }", "static final TimeBasedRollStrategy findRollStrategy(\n final AppenderRollingProperties properties) {\n if (properties.getDatePattern() == null) {\n LogLog.error(\"null date pattern\");\n return ROLL_ERROR;\n }\n // Strip out quoted sections so that we may safely scan the undecorated\n // pattern for characters that are meaningful to SimpleDateFormat.\n final LocalizedDateFormatPatternHelper localizedDateFormatPatternHelper = new LocalizedDateFormatPatternHelper(\n properties.getDatePatternLocale());\n final String undecoratedDatePattern = localizedDateFormatPatternHelper\n .excludeQuoted(properties.getDatePattern());\n if (ROLL_EACH_MINUTE.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_MINUTE;\n }\n if (ROLL_EACH_HOUR.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_HOUR;\n }\n if (ROLL_EACH_HALF_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_HALF_DAY;\n }\n if (ROLL_EACH_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_DAY;\n }\n if (ROLL_EACH_WEEK.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_WEEK;\n }\n if (ROLL_EACH_MONTH.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_MONTH;\n }\n return ROLL_ERROR;\n }", "public Profile findProfile(int profileId) throws Exception {\n Profile profile = null;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_PROFILE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, profileId);\n results = statement.executeQuery();\n if (results.next()) {\n profile = this.getProfileFromResultSet(results);\n }\n } catch (Exception e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n return profile;\n }", "public boolean deleteExisting(final File file) {\n if (!file.exists()) {\n return true;\n }\n boolean deleted = false;\n if (file.canWrite()) {\n deleted = file.delete();\n } else {\n LogLog.debug(file + \" is not writeable for delete (retrying)\");\n }\n if (!deleted) {\n if (!file.exists()) {\n deleted = true;\n } else {\n file.delete();\n deleted = (!file.exists());\n }\n }\n return deleted;\n }", "public static boolean requiresReload(final Set<Flag> flags) {\n return flags.contains(Flag.RESTART_ALL_SERVICES) || flags.contains(Flag.RESTART_RESOURCE_SERVICES);\n }", "public static vpnvserver_responderpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_responderpolicy_binding obj = new vpnvserver_responderpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_responderpolicy_binding response[] = (vpnvserver_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private static void addTimePerComponent(HashMap<String, Long> mapComponentTimes,\tComponent component) {\n Long currentTimeOfComponent = 0L;\n String key = component.getComponentType();\n if (mapComponentTimes.containsKey(key)) {\n currentTimeOfComponent = mapComponentTimes.get(key);\n }\n //when transactions are run in parallel, we should log the longest transaction only to avoid that \n //for ex 'Total time' would be 100ms and transactions in parallel to hornetQ will be 2000ms \n Long maxTime = Math.max(component.getTime(), currentTimeOfComponent);\n mapComponentTimes.put(key, maxTime);\n }" ]
Sets the specified short attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
[ "public void setShortAttribute(String name, Short value) {\n\t\tensureValue();\n\t\tAttribute attribute = new ShortAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}" ]
[ "public List<TimephasedCost> getTimephasedActualCost()\n {\n if (m_timephasedActualCost == null)\n {\n Resource r = getResource();\n ResourceType type = r != null ? r.getType() : ResourceType.WORK;\n\n //for Work and Material resources, we will calculate in the normal way\n if (type != ResourceType.COST)\n {\n if (m_timephasedActualWork != null && m_timephasedActualWork.hasData())\n {\n if (hasMultipleCostRates())\n {\n m_timephasedActualCost = getTimephasedCostMultipleRates(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n else\n {\n m_timephasedActualCost = getTimephasedCostSingleRate(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n }\n }\n else\n {\n m_timephasedActualCost = getTimephasedActualCostFixedAmount();\n }\n\n }\n\n return m_timephasedActualCost;\n }", "public void addItem(T value, Direction dir, String text) {\n addItem(value, dir, text, true);\n }", "private void readCalendars(Project project, HashMap<BigInteger, ProjectCalendar> map)\n {\n Project.Calendars calendars = project.getCalendars();\n if (calendars != null)\n {\n LinkedList<Pair<ProjectCalendar, BigInteger>> baseCalendars = new LinkedList<Pair<ProjectCalendar, BigInteger>>();\n for (Project.Calendars.Calendar cal : calendars.getCalendar())\n {\n readCalendar(cal, map, baseCalendars);\n }\n updateBaseCalendarNames(baseCalendars, map);\n }\n\n try\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n BigInteger calendarID = new BigInteger(properties.getDefaultCalendarName());\n ProjectCalendar calendar = map.get(calendarID);\n m_projectFile.setDefaultCalendar(calendar);\n }\n\n catch (Exception ex)\n {\n // Ignore exceptions\n }\n }", "public Where<T, ID> reset() {\n\t\tfor (int i = 0; i < clauseStackLevel; i++) {\n\t\t\t// help with gc\n\t\t\tclauseStack[i] = null;\n\t\t}\n\t\tclauseStackLevel = 0;\n\t\treturn this;\n\t}", "public void removeJobType(final Class<?> jobType) {\n if (jobType == null) {\n throw new IllegalArgumentException(\"jobType must not be null\");\n }\n this.jobTypes.values().remove(jobType);\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}", "public FluoMutationGenerator put(Column col, CharSequence value) {\n return put(col, value.toString().getBytes(StandardCharsets.UTF_8));\n }", "@SuppressWarnings(\"unchecked\")\n public static <E> void serialize(E object, ParameterizedType<E> parameterizedType, OutputStream os) throws IOException {\n mapperFor(parameterizedType).serialize(object, os);\n }", "static ChangeEvent<BsonDocument> changeEventForLocalInsert(\n final MongoNamespace namespace,\n final BsonDocument document,\n final boolean writePending\n ) {\n final BsonValue docId = BsonUtils.getDocumentId(document);\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.INSERT,\n document,\n namespace,\n new BsonDocument(\"_id\", docId),\n null,\n writePending);\n }" ]
Returns the accrued interest of the bond for a given date. @param date The date of interest. @param model The model under which the product is valued. @return The accrued interest.
[ "public double getAccruedInterest(LocalDate date, AnalyticModel model) {\n\t\tint periodIndex=schedule.getPeriodIndex(date);\n\t\tPeriod period=schedule.getPeriod(periodIndex);\n\t\tDayCountConvention dcc= schedule.getDaycountconvention();\n\t\tdouble accruedInterest=getCouponPayment(periodIndex,model)*(dcc.getDaycountFraction(period.getPeriodStart(), date))/schedule.getPeriodLength(periodIndex);\n\t\treturn accruedInterest;\n\t}" ]
[ "@Api\n\tpublic void setUseCache(boolean useCache) {\n\t\tif (null == cacheManagerService && useCache) {\n\t\t\tlog.warn(\"The caching plugin needs to be available to cache WMS requests. Not setting useCache.\");\n\t\t} else {\n\t\t\tthis.useCache = useCache;\n\t\t}\n\t}", "public static void registerTinyTypes(Class<?> head, Class<?>... tail) {\n final Set<HeaderDelegateProvider> systemRegisteredHeaderProviders = stealAcquireRefToHeaderDelegateProviders();\n register(head, systemRegisteredHeaderProviders);\n for (Class<?> tt : tail) {\n register(tt, systemRegisteredHeaderProviders);\n }\n }", "public static void withInstance(String url, Closure c) throws SQLException {\n Sql sql = null;\n try {\n sql = newInstance(url);\n c.call(sql);\n } finally {\n if (sql != null) sql.close();\n }\n }", "public HashMap<K2, HashMap<K3, V>> get(final K1 firstKey) {\n\t\treturn map.get(firstKey);\n\t}", "@UiThread\n public void collapseParentRange(int startParentPosition, int parentCount) {\n int endParentPosition = startParentPosition + parentCount;\n for (int i = startParentPosition; i < endParentPosition; i++) {\n collapseParent(i);\n }\n }", "@Deprecated\r\n public Location resolvePlaceId(String placeId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_RESOLVE_PLACE_ID);\r\n\r\n parameters.put(\"place_id\", placeId);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }", "public static 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 void setFilePath(String filePath) throws IOException, GVRScriptException\n {\n GVRResourceVolume.VolumeType volumeType = GVRResourceVolume.VolumeType.ANDROID_ASSETS;\n String fname = filePath.toLowerCase();\n \n mLanguage = FileNameUtils.getExtension(fname); \n if (fname.startsWith(\"sd:\"))\n {\n volumeType = GVRResourceVolume.VolumeType.ANDROID_SDCARD;\n }\n else if (fname.startsWith(\"http:\") || fname.startsWith(\"https:\"))\n {\n volumeType = GVRResourceVolume.VolumeType.NETWORK; \n }\n GVRResourceVolume volume = new GVRResourceVolume(getGVRContext(), volumeType,\n FileNameUtils.getParentDirectory(filePath));\n GVRAndroidResource resource = volume.openResource(filePath);\n \n setScriptFile((GVRScriptFile)getGVRContext().getScriptManager().loadScript(resource, mLanguage));\n }", "public Photo getInfo(String photoId, String secret) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n if (secret != null) {\r\n parameters.put(\"secret\", secret);\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 photoElement = response.getPayload();\r\n\r\n return PhotoUtils.createPhoto(photoElement);\r\n }" ]
Returns the connection that has been saved or null if none.
[ "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}" ]
[ "@Override\n\tpublic synchronized boolean fireEventAndWait(Eventable eventable)\n\t\t\tthrows ElementNotVisibleException, NoSuchElementException, InterruptedException {\n\t\ttry {\n\n\t\t\tboolean handleChanged = false;\n\t\t\tboolean result = false;\n\n\t\t\tif (eventable.getRelatedFrame() != null && !eventable.getRelatedFrame().equals(\"\")) {\n\t\t\t\tLOGGER.debug(\"switching to frame: \" + eventable.getRelatedFrame());\n\t\t\t\ttry {\n\n\t\t\t\t\tswitchToFrame(eventable.getRelatedFrame());\n\t\t\t\t} catch (NoSuchFrameException e) {\n\t\t\t\t\tLOGGER.debug(\"Frame not found, possibly while back-tracking..\", e);\n\t\t\t\t\t// TODO Stefan, This exception is caught to prevent stopping\n\t\t\t\t\t// from working\n\t\t\t\t\t// This was the case on the Gmail case; find out if not switching\n\t\t\t\t\t// (catching)\n\t\t\t\t\t// Results in good performance...\n\t\t\t\t}\n\t\t\t\thandleChanged = true;\n\t\t\t}\n\n\t\t\tWebElement webElement =\n\t\t\t\t\tbrowser.findElement(eventable.getIdentification().getWebDriverBy());\n\n\t\t\tif (webElement != null) {\n\t\t\t\tresult = fireEventWait(webElement, eventable);\n\t\t\t}\n\n\t\t\tif (handleChanged) {\n\t\t\t\tbrowser.switchTo().defaultContent();\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (ElementNotVisibleException | NoSuchElementException e) {\n\t\t\tthrow e;\n\t\t} catch (WebDriverException e) {\n\t\t\tthrowIfConnectionException(e);\n\t\t\treturn false;\n\t\t}\n\t}", "public RemoteMongoCollection<Document> getCollection(final String collectionName) {\n return new RemoteMongoCollectionImpl<>(proxy.getCollection(collectionName), dispatcher);\n }", "public static int cudnnLRNCrossChannelBackward(\n cudnnHandle handle, \n cudnnLRNDescriptor normDesc, \n int lrnMode, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnLRNCrossChannelBackwardNative(handle, normDesc, lrnMode, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }", "public void renumberUniqueIDs()\n {\n int uid = firstUniqueID();\n for (T entity : this)\n {\n entity.setUniqueID(Integer.valueOf(uid++));\n }\n }", "public static linkset get(nitro_service service, String id) throws Exception{\n\t\tlinkset obj = new linkset();\n\t\tobj.set_id(id);\n\t\tlinkset response = (linkset) obj.get_resource(service);\n\t\treturn response;\n\t}", "public ModelNode toModelNode() {\n final ModelNode node = new ModelNode().setEmptyList();\n for (PathElement element : pathAddressList) {\n final String value;\n if (element.isMultiTarget() && !element.isWildcard()) {\n value = '[' + element.getValue() + ']';\n } else {\n value = element.getValue();\n }\n node.add(element.getKey(), value);\n }\n return node;\n }", "@JsonProperty(\"labels\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, TermImpl> getLabelUpdates() {\n \treturn getMonolingualUpdatedValues(newLabels);\n }", "public void fireResourceReadEvent(Resource resource)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.resourceRead(resource);\n }\n }\n }", "synchronized public String getPrettyProgressBar() {\n StringBuilder sb = new StringBuilder();\n\n double taskRate = numTasksCompleted / (double) totalTaskCount;\n double partitionStoreRate = numPartitionStoresMigrated / (double) totalPartitionStoreCount;\n\n long deltaTimeMs = System.currentTimeMillis() - startTimeMs;\n long taskTimeRemainingMs = Long.MAX_VALUE;\n if(taskRate > 0) {\n taskTimeRemainingMs = (long) (deltaTimeMs * ((1.0 / taskRate) - 1.0));\n }\n long partitionStoreTimeRemainingMs = Long.MAX_VALUE;\n if(partitionStoreRate > 0) {\n partitionStoreTimeRemainingMs = (long) (deltaTimeMs * ((1.0 / partitionStoreRate) - 1.0));\n }\n\n // Title line\n sb.append(\"Progress update on rebalancing batch \" + batchId).append(Utils.NEWLINE);\n // Tasks in flight update\n sb.append(\"There are currently \" + tasksInFlight.size() + \" rebalance tasks executing: \")\n .append(tasksInFlight)\n .append(\".\")\n .append(Utils.NEWLINE);\n // Tasks completed update\n sb.append(\"\\t\" + numTasksCompleted + \" out of \" + totalTaskCount\n + \" rebalance tasks complete.\")\n .append(Utils.NEWLINE)\n .append(\"\\t\")\n .append(decimalFormatter.format(taskRate * 100.0))\n .append(\"% done, estimate \")\n .append(taskTimeRemainingMs)\n .append(\" ms (\")\n .append(TimeUnit.MILLISECONDS.toMinutes(taskTimeRemainingMs))\n .append(\" minutes) remaining.\")\n .append(Utils.NEWLINE);\n // Partition-stores migrated update\n sb.append(\"\\t\" + numPartitionStoresMigrated + \" out of \" + totalPartitionStoreCount\n + \" partition-stores migrated.\")\n .append(Utils.NEWLINE)\n .append(\"\\t\")\n .append(decimalFormatter.format(partitionStoreRate * 100.0))\n .append(\"% done, estimate \")\n .append(partitionStoreTimeRemainingMs)\n .append(\" ms (\")\n .append(TimeUnit.MILLISECONDS.toMinutes(partitionStoreTimeRemainingMs))\n .append(\" minutes) remaining.\")\n .append(Utils.NEWLINE);\n return sb.toString();\n }" ]
Sets the permissions associated with this shared link. @param permissions the new permissions for this shared link.
[ "public void setPermissions(Permissions permissions) {\n if (this.permissions == permissions) {\n return;\n }\n\n this.removeChildObject(\"permissions\");\n this.permissions = permissions;\n this.addChildObject(\"permissions\", permissions);\n }" ]
[ "protected void update(float scale) {\n // Updates only when the plane is in the scene\n GVRSceneObject owner = getOwnerObject();\n\n if ((owner != null) && isEnabled() && owner.isEnabled())\n {\n convertFromARtoVRSpace(scale);\n }\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 }", "public void start() {\n if (this.started) {\n throw new IllegalStateException(\"Cannot start the EventStream because it isn't stopped.\");\n }\n\n final long initialPosition;\n\n if (this.startingPosition == STREAM_POSITION_NOW) {\n BoxAPIRequest request = new BoxAPIRequest(this.api, EVENT_URL.build(this.api.getBaseURL(), \"now\"), \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n initialPosition = jsonObject.get(\"next_stream_position\").asLong();\n } else {\n assert this.startingPosition >= 0 : \"Starting position must be non-negative\";\n initialPosition = this.startingPosition;\n }\n\n this.poller = new Poller(initialPosition);\n\n this.pollerThread = new Thread(this.poller);\n this.pollerThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {\n public void uncaughtException(Thread t, Throwable e) {\n EventStream.this.notifyException(e);\n }\n });\n this.pollerThread.start();\n\n this.started = true;\n }", "private static List<String> parseAndCompare(List<String> fileNames, int masterPartitionId) {\n List<String> sourceFileNames = new ArrayList<String>();\n for(String fileName: fileNames) {\n String[] partitionIdReplicaChunk = fileName.split(SPLIT_LITERAL);\n if(Integer.parseInt(partitionIdReplicaChunk[0]) == masterPartitionId) {\n sourceFileNames.add(fileName);\n }\n }\n return sourceFileNames;\n }", "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 }", "protected Object getMacroBeanValue(Object bean, String property) {\n\n Object result = null;\n if ((bean != null) && CmsStringUtil.isNotEmptyOrWhitespaceOnly(property)) {\n try {\n PropertyUtilsBean propBean = BeanUtilsBean.getInstance().getPropertyUtils();\n result = propBean.getProperty(bean, property);\n } catch (Exception e) {\n LOG.error(\"Unable to access property '\" + property + \"' of '\" + bean + \"'.\", e);\n }\n } else {\n LOG.info(\"Invalid parameters: property='\" + property + \"' bean='\" + bean + \"'.\");\n }\n return result;\n }", "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 }", "@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}", "private void updateSortedServices() {\n List<T> copiedList = new ArrayList<T>(serviceMap.values());\n sortedServices = Collections.unmodifiableList(copiedList);\n if (changeListener != null) {\n changeListener.changed();\n }\n }" ]
Returns the Class object of the Event implementation.
[ "public Class<E> getEventClass() {\n if (cachedClazz != null) {\n return cachedClazz;\n }\n Class<?> clazz = this.getClass();\n while (clazz != Object.class) {\n try {\n Type mySuperclass = clazz.getGenericSuperclass();\n Type tType = ((ParameterizedType) mySuperclass).getActualTypeArguments()[0];\n cachedClazz = (Class<E>) Class.forName(tType.getTypeName());\n return cachedClazz;\n } catch (Exception e) {\n }\n clazz = clazz.getSuperclass();\n }\n throw new IllegalStateException(\"Failed to load event class - \" + this.getClass().getCanonicalName());\n }" ]
[ "public static void main(String[] args) {\n\t\ttry {\n\t\t\tJarRunner runner = new JarRunner(args);\n\t\t\trunner.runIfConfigured();\n\t\t} catch (NumberFormatException e) {\n\t\t\tSystem.err.println(\"Could not parse number \" + e.getMessage());\n\t\t\tSystem.exit(1);\n\t\t} catch (RuntimeException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t\tSystem.exit(1);\n\t\t}\n\t}", "private void processFileType(String token) throws MPXJException\n {\n String version = token.substring(2).split(\" \")[0];\n //System.out.println(version);\n Class<? extends AbstractFileFormat> fileFormatClass = FILE_VERSION_MAP.get(Integer.valueOf(version));\n if (fileFormatClass == null)\n {\n throw new MPXJException(\"Unsupported PP file format version \" + version);\n }\n\n try\n {\n AbstractFileFormat format = fileFormatClass.newInstance();\n m_tableDefinitions = format.tableDefinitions();\n m_epochDateFormat = format.epochDateFormat();\n }\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to configure file format\", ex);\n }\n }", "public Bundler put(String key, String[] value) {\n delegate.putStringArray(key, value);\n return this;\n }", "public MembersList<Member> getList(String groupId, Set<String> memberTypes, int perPage, int page) throws FlickrException {\r\n MembersList<Member> members = new MembersList<Member>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n\r\n parameters.put(\"group_id\", groupId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n if (memberTypes != null) {\r\n parameters.put(\"membertypes\", StringUtilities.join(memberTypes, \",\"));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element mElement = response.getPayload();\r\n members.setPage(mElement.getAttribute(\"page\"));\r\n members.setPages(mElement.getAttribute(\"pages\"));\r\n members.setPerPage(mElement.getAttribute(\"perpage\"));\r\n members.setTotal(mElement.getAttribute(\"total\"));\r\n\r\n NodeList mNodes = mElement.getElementsByTagName(\"member\");\r\n for (int i = 0; i < mNodes.getLength(); i++) {\r\n Element element = (Element) mNodes.item(i);\r\n members.add(parseMember(element));\r\n }\r\n return members;\r\n }", "public BoxFile.Info restoreFile(String fileID) {\n URL url = RESTORE_FILE_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"\", \"\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFile restoredFile = new BoxFile(this.api, responseJSON.get(\"id\").asString());\n return restoredFile.new Info(responseJSON);\n }", "protected void mergeHardcodedResultsFrom(Configuration otherConfiguration) {\r\n Map<Dotted, AnalysisResult> resultsMap = hardcodedResults.build().stream()\r\n .collect(Collectors.toMap(r -> r.className, r -> r));\r\n resultsMap.putAll(otherConfiguration.hardcodedResults());\r\n hardcodedResults = ImmutableSet.<AnalysisResult>builder().addAll(resultsMap.values());\r\n }", "public double Function2D(double x, double y) {\n double frequency = initFrequency;\n double amplitude = initAmplitude;\n double sum = 0;\n\n // octaves\n for (int i = 0; i < octaves; i++) {\n sum += SmoothedNoise(x * frequency, y * frequency) * amplitude;\n\n frequency *= 2;\n amplitude *= persistence;\n }\n return sum;\n }", "protected ExpectState prepareClosure(int pairIndex, MatchResult result) {\n /* TODO: potentially remove this?\n {\n System.out.println( \"Begin: \" + result.beginOffset(0) );\n System.out.println( \"Length: \" + result.length() );\n System.out.println( \"Current: \" + input.getCurrentOffset() );\n System.out.println( \"Begin: \" + input.getMatchBeginOffset() );\n System.out.println( \"End: \" + input.getMatchEndOffset() );\n //System.out.println( \"Match: \" + input.match() );\n //System.out.println( \"Pre: >\" + input.preMatch() + \"<\");\n //System.out.println( \"Post: \" + input.postMatch() );\n }\n */\n\n // Prepare Closure environment\n ExpectState state;\n Map<String, Object> prevMap = null;\n if (g_state != null) {\n prevMap = g_state.getVars();\n }\n\n int matchedWhere = result.beginOffset(0);\n String matchedText = result.toString(); // expect_out(0,string)\n\n // Unmatched upto end of match\n // expect_out(buffer)\n char[] chBuffer = input.getBuffer();\n String copyBuffer = new String(chBuffer, 0, result.endOffset(0) );\n\n List<String> groups = new ArrayList<>();\n for (int j = 1; j <= result.groups(); j++) {\n String group = result.group(j);\n groups.add( group );\n }\n state = new ExpectState(copyBuffer.toString(), matchedWhere, matchedText, pairIndex, groups, prevMap);\n\n return state;\n }", "public static RgbaColor fromRgba(String rgba) {\n if (rgba.length() == 0) return getDefaultColor();\n\n String[] parts = getRgbaParts(rgba).split(\",\");\n if (parts.length == 4) {\n return new RgbaColor(parseInt(parts[0]),\n parseInt(parts[1]),\n parseInt(parts[2]),\n parseFloat(parts[3]));\n }\n else {\n return getDefaultColor();\n }\n }" ]
Retrieves basic meta data from the result set. @throws SQLException
[ "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 }" ]
[ "private void updateRemoveQ( int rowIndex ) {\n Qm.set(Q);\n Q.reshape(m_m,m_m, false);\n\n for( int i = 0; i < rowIndex; i++ ) {\n for( int j = 1; j < m; j++ ) {\n double sum = 0;\n for( int k = 0; k < m; k++ ) {\n sum += Qm.data[i*m+k]* U_tran.data[j*m+k];\n }\n Q.data[i*m_m+j-1] = sum;\n }\n }\n\n for( int i = rowIndex+1; i < m; i++ ) {\n for( int j = 1; j < m; j++ ) {\n double sum = 0;\n for( int k = 0; k < m; k++ ) {\n sum += Qm.data[i*m+k]* U_tran.data[j*m+k];\n }\n Q.data[(i-1)*m_m+j-1] = sum;\n }\n }\n }", "public static <K> Map<K, Integer> rankMapOnIntegerValue(Map<K, Integer> inputMap) {\n Map<K, Integer> newMap = new TreeMap<K, Integer>(new IntegerValueComparator(inputMap));\n newMap.putAll(inputMap);\n\n Map<K, Integer> linkedMap = new LinkedHashMap<K, Integer>(newMap);\n return linkedMap;\n }", "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 }", "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 }", "@Override\n\tpublic void Invoke(final String method, JSONArray args,\n\t\t\tHubInvokeCallback callback) {\n\n\t\tif (method == null)\n {\n throw new IllegalArgumentException(\"method\");\n }\n\n if (args == null)\n {\n throw new IllegalArgumentException(\"args\");\n }\n\n final String callbackId = mConnection.RegisterCallback(callback);\n\n HubInvocation hubData = new HubInvocation(mHubName, method, args, callbackId);\n\n String value = hubData.Serialize();\n\n mConnection.Send(value, new SendCallback() \n {\n\t\t\t@Override\n\t\t\tpublic void OnSent(CharSequence messageSent) {\n\t\t\t\tLog.v(TAG, \"Invoke of \" + method + \"sent to \" + mHubName);\n\t\t\t\t// callback.OnSent() ??!?!?\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void OnError(Exception ex) {\n\t\t\t\t// TODO Cancel the callback\n\t\t\t\tLog.e(TAG, \"Failed to invoke \" + method + \"on \" + mHubName);\n\t\t\t\tmConnection.RemoveCallback(callbackId);\n\t\t\t\t// callback.OnError() ?!?!?\n\t\t\t}\n });\n }", "public static Cluster\n balanceContiguousPartitionsPerZone(final Cluster nextCandidateCluster,\n final int maxContiguousPartitionsPerZone) {\n System.out.println(\"Balance number of contiguous partitions within a zone.\");\n System.out.println(\"numPartitionsPerZone\");\n for(int zoneId: nextCandidateCluster.getZoneIds()) {\n System.out.println(zoneId + \" : \"\n + nextCandidateCluster.getNumberOfPartitionsInZone(zoneId));\n }\n System.out.println(\"numNodesPerZone\");\n for(int zoneId: nextCandidateCluster.getZoneIds()) {\n System.out.println(zoneId + \" : \" + nextCandidateCluster.getNumberOfNodesInZone(zoneId));\n }\n\n // Break up contiguous partitions within each zone\n HashMap<Integer, List<Integer>> partitionsToRemoveFromZone = Maps.newHashMap();\n System.out.println(\"Contiguous partitions\");\n for(Integer zoneId: nextCandidateCluster.getZoneIds()) {\n System.out.println(\"\\tZone: \" + zoneId);\n Map<Integer, Integer> partitionToRunLength = PartitionBalanceUtils.getMapOfContiguousPartitions(nextCandidateCluster,\n zoneId);\n\n List<Integer> partitionsToRemoveFromThisZone = new ArrayList<Integer>();\n for(Map.Entry<Integer, Integer> entry: partitionToRunLength.entrySet()) {\n if(entry.getValue() > maxContiguousPartitionsPerZone) {\n List<Integer> contiguousPartitions = new ArrayList<Integer>(entry.getValue());\n for(int partitionId = entry.getKey(); partitionId < entry.getKey()\n + entry.getValue(); partitionId++) {\n contiguousPartitions.add(partitionId\n % nextCandidateCluster.getNumberOfPartitions());\n }\n System.out.println(\"Contiguous partitions: \" + contiguousPartitions);\n partitionsToRemoveFromThisZone.addAll(Utils.removeItemsToSplitListEvenly(contiguousPartitions,\n maxContiguousPartitionsPerZone));\n }\n }\n\n partitionsToRemoveFromZone.put(zoneId, partitionsToRemoveFromThisZone);\n System.out.println(\"\\t\\tPartitions to remove: \" + partitionsToRemoveFromThisZone);\n }\n\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n\n Random r = new Random();\n for(int zoneId: returnCluster.getZoneIds()) {\n for(int partitionId: partitionsToRemoveFromZone.get(zoneId)) {\n // Pick a random other zone Id\n List<Integer> otherZoneIds = new ArrayList<Integer>();\n for(int otherZoneId: returnCluster.getZoneIds()) {\n if(otherZoneId != zoneId) {\n otherZoneIds.add(otherZoneId);\n }\n }\n int whichOtherZoneId = otherZoneIds.get(r.nextInt(otherZoneIds.size()));\n\n // Pick a random node from other zone ID\n int whichNodeOffset = r.nextInt(returnCluster.getNumberOfNodesInZone(whichOtherZoneId));\n int whichNodeId = new ArrayList<Integer>(returnCluster.getNodeIdsInZone(whichOtherZoneId)).get(whichNodeOffset);\n\n // Steal partition from one zone to another!\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n whichNodeId,\n Lists.newArrayList(partitionId));\n }\n }\n\n return returnCluster;\n\n }", "@POST\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response addCorporateGroupIdPrefix(@Auth final DbCredential credential, @PathParam(\"name\") final String organizationId, final String corporateGroupId){\n LOG.info(\"Got an add a corporate groupId prefix request for organization \" + organizationId +\".\");\n if(!credential.getRoles().contains(DbCredential.AvailableRoles.DATA_UPDATER)){\n throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build());\n }\n\n if(corporateGroupId == null || corporateGroupId.isEmpty()){\n LOG.error(\"No corporate GroupId to add!\");\n throw new WebApplicationException(Response.serverError().status(HttpStatus.BAD_REQUEST_400)\n .entity(\"CorporateGroupId to add should be in the query content.\").build());\n }\n\n getOrganizationHandler().addCorporateGroupId(organizationId, corporateGroupId);\n return Response.ok().status(HttpStatus.CREATED_201).build();\n }", "protected boolean isNetworkSection(int networkPrefixLength, boolean withPrefixLength) {\n\t\tint segmentCount = getSegmentCount();\n\t\tif(segmentCount == 0) {\n\t\t\treturn true;\n\t\t}\n\t\tint bitsPerSegment = getBitsPerSegment();\n\t\tint prefixedSegmentIndex = getNetworkSegmentIndex(networkPrefixLength, getBytesPerSegment(), bitsPerSegment);\n\t\tif(prefixedSegmentIndex + 1 < segmentCount) {\n\t\t\treturn false; //not the right number of segments\n\t\t}\n\t\t//the segment count matches, now compare the prefixed segment\n\t\tint segPrefLength = getPrefixedSegmentPrefixLength(bitsPerSegment, networkPrefixLength, prefixedSegmentIndex);\n\t\treturn !getSegment(segmentCount - 1).isNetworkChangedByPrefix(segPrefLength, withPrefixLength);\n\t}", "public SqlStatement getPreparedUpdateStatement(ClassDescriptor cld)\r\n {\r\n SqlForClass sfc = getSqlForClass(cld);\r\n SqlStatement result = sfc.getUpdateSql();\r\n if(result == null)\r\n {\r\n ProcedureDescriptor pd = cld.getUpdateProcedure();\r\n\r\n if(pd == null)\r\n {\r\n result = new SqlUpdateStatement(cld, logger);\r\n }\r\n else\r\n {\r\n result = new SqlProcedureStatement(pd, logger);\r\n }\r\n // set the sql string\r\n sfc.setUpdateSql(result);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + result.getStatement());\r\n }\r\n }\r\n return result;\r\n }" ]
Reads a nested table. Uses the supplied reader class instance. @param readerClass reader class instance @return table rows
[ "public List<MapRow> readTable(Class<? extends TableReader> readerClass) throws IOException\n {\n TableReader reader;\n\n try\n {\n reader = readerClass.getConstructor(StreamReader.class).newInstance(this);\n }\n catch (Exception ex)\n {\n throw new RuntimeException(ex);\n }\n\n return readTable(reader);\n }" ]
[ "public static void installDomainConnectorServices(final OperationContext context,\n final ServiceTarget serviceTarget,\n final ServiceName endpointName,\n final ServiceName networkInterfaceBinding,\n final int port,\n final OptionMap options,\n final ServiceName securityRealm,\n final ServiceName saslAuthenticationFactory,\n final ServiceName sslContext) {\n String sbmCap = \"org.wildfly.management.socket-binding-manager\";\n ServiceName sbmName = context.hasOptionalCapability(sbmCap, NATIVE_MANAGEMENT_RUNTIME_CAPABILITY.getName(), null)\n ? context.getCapabilityServiceName(sbmCap, SocketBindingManager.class) : null;\n installConnectorServicesForNetworkInterfaceBinding(serviceTarget, endpointName, MANAGEMENT_CONNECTOR,\n networkInterfaceBinding, port, options, securityRealm, saslAuthenticationFactory, sslContext, sbmName);\n }", "public static LuaCondition isNull(LuaValue value) {\n LuaAstExpression expression;\n if (value instanceof LuaLocal) {\n expression = new LuaAstLocal(((LuaLocal) value).getName());\n } else {\n throw new IllegalArgumentException(\"Unexpected value type: \" + value.getClass().getName());\n }\n return new LuaCondition(new LuaAstNot(expression));\n }", "public Try<R,Throwable> execute(T input){\n\t\treturn Try.withCatch( ()->transactionTemplate.execute(status-> transaction.apply(input)));\n\t\t \n\t}", "private void handleUpdate(final CdjStatus update) {\n // First see if any metadata caches need evicting or mount sets need updating.\n if (update.isLocalUsbEmpty()) {\n final SlotReference slot = SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.USB_SLOT);\n detachMetadataCache(slot);\n flushHotCacheSlot(slot);\n removeMount(slot);\n } else if (update.isLocalUsbLoaded()) {\n recordMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.USB_SLOT));\n }\n\n if (update.isLocalSdEmpty()) {\n final SlotReference slot = SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.SD_SLOT);\n detachMetadataCache(slot);\n flushHotCacheSlot(slot);\n removeMount(slot);\n } else if (update.isLocalSdLoaded()){\n recordMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.SD_SLOT));\n }\n\n if (update.isDiscSlotEmpty()) {\n removeMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.CD_SLOT));\n } else {\n recordMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.CD_SLOT));\n }\n\n // Now see if a track has changed that needs new metadata.\n if (update.getTrackType() == CdjStatus.TrackType.UNKNOWN ||\n update.getTrackType() == CdjStatus.TrackType.NO_TRACK ||\n update.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.NO_TRACK ||\n update.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.UNKNOWN ||\n update.getRekordboxId() == 0) { // We no longer have metadata for this device.\n clearDeck(update);\n } else { // We can offer metadata for this device; check if we already looked up this track.\n final TrackMetadata lastMetadata = hotCache.get(DeckReference.getDeckReference(update.getDeviceNumber(), 0));\n final DataReference trackReference = new DataReference(update.getTrackSourcePlayer(),\n update.getTrackSourceSlot(), update.getRekordboxId());\n if (lastMetadata == null || !lastMetadata.trackReference.equals(trackReference)) { // We have something new!\n // First see if we can find the new track in the hot cache as a hot cue\n for (TrackMetadata cached : hotCache.values()) {\n if (cached.trackReference.equals(trackReference)) { // Found a hot cue hit, use it.\n updateMetadata(update, cached);\n return;\n }\n }\n\n // Not in the hot cache so try actually retrieving it.\n if (activeRequests.add(update.getTrackSourcePlayer())) {\n // We had to make sure we were not already asking for this track.\n clearDeck(update); // We won't know what it is until our request completes.\n new Thread(new Runnable() {\n @Override\n public void run() {\n try {\n TrackMetadata data = requestMetadataInternal(trackReference, update.getTrackType(), true);\n if (data != null) {\n updateMetadata(update, data);\n }\n } catch (Exception e) {\n logger.warn(\"Problem requesting track metadata from update\" + update, e);\n } finally {\n activeRequests.remove(update.getTrackSourcePlayer());\n }\n }\n }, \"MetadataFinder metadata request\").start();\n }\n }\n }\n }", "private void readResourceBaselines(Project.Resources.Resource xmlResource, Resource mpxjResource)\n {\n for (Project.Resources.Resource.Baseline baseline : xmlResource.getBaseline())\n {\n int number = NumberHelper.getInt(baseline.getNumber());\n\n Double cost = DatatypeConverter.parseCurrency(baseline.getCost());\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork());\n\n if (number == 0)\n {\n mpxjResource.setBaselineCost(cost);\n mpxjResource.setBaselineWork(work);\n }\n else\n {\n mpxjResource.setBaselineCost(number, cost);\n mpxjResource.setBaselineWork(number, work);\n }\n }\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 }", "public Logger getLogger(String loggerName)\r\n {\r\n Logger logger;\r\n //lookup in the cache first\r\n logger = (Logger) cache.get(loggerName);\r\n\r\n if(logger == null)\r\n {\r\n try\r\n {\r\n // get the configuration (not from the configurator because this is independent)\r\n logger = createLoggerInstance(loggerName);\r\n if(getBootLogger().isDebugEnabled())\r\n {\r\n getBootLogger().debug(\"Using logger class '\"\r\n + (getConfiguration() != null ? getConfiguration().getLoggerClass() : null)\r\n + \"' for \" + loggerName);\r\n }\r\n // configure the logger\r\n getBootLogger().debug(\"Initializing logger instance \" + loggerName);\r\n logger.configure(conf);\r\n }\r\n catch(Throwable t)\r\n {\r\n // do reassign check and signal logger creation failure\r\n reassignBootLogger(true);\r\n logger = getBootLogger();\r\n getBootLogger().error(\"[\" + this.getClass().getName()\r\n + \"] Could not initialize logger \" + (conf != null ? conf.getLoggerClass() : null), t);\r\n }\r\n //cache it so we can get it faster the next time\r\n cache.put(loggerName, logger);\r\n // do reassign check\r\n reassignBootLogger(false);\r\n }\r\n return logger;\r\n }", "private Query.Builder createScatterQuery(Query query, int numSplits) {\n // TODO(pcostello): We can potentially support better splits with equality filters in our query\n // if there exists a composite index on property, __scatter__, __key__. Until an API for\n // metadata exists, this isn't possible. Note that ancestor and inequality queries fall into\n // the same category.\n Query.Builder scatterPointQuery = Query.newBuilder();\n scatterPointQuery.addAllKind(query.getKindList());\n scatterPointQuery.addOrder(DatastoreHelper.makeOrder(\n DatastoreHelper.SCATTER_PROPERTY_NAME, Direction.ASCENDING));\n // There is a split containing entities before and after each scatter entity:\n // ||---*------*------*------*------*------*------*---|| = scatter entity\n // If we represent each split as a region before a scatter entity, there is an extra region\n // following the last scatter point. Thus, we do not need the scatter entities for the last\n // region.\n scatterPointQuery.getLimitBuilder().setValue((numSplits - 1) * KEYS_PER_SPLIT);\n scatterPointQuery.addProjection(Projection.newBuilder().setProperty(\n PropertyReference.newBuilder().setName(\"__key__\")));\n return scatterPointQuery;\n }", "private void processHyperlinkData(Resource resource, byte[] data)\n {\n if (data != null)\n {\n int offset = 12;\n String hyperlink;\n String address;\n String subaddress;\n\n offset += 12;\n hyperlink = MPPUtility.getUnicodeString(data, offset);\n offset += ((hyperlink.length() + 1) * 2);\n\n offset += 12;\n address = MPPUtility.getUnicodeString(data, offset);\n offset += ((address.length() + 1) * 2);\n\n offset += 12;\n subaddress = MPPUtility.getUnicodeString(data, offset);\n\n resource.setHyperlink(hyperlink);\n resource.setHyperlinkAddress(address);\n resource.setHyperlinkSubAddress(subaddress);\n }\n }" ]
Returns true if the given dump file type contains page revisions and false if it does not. Dumps that do not contain pages are for auxiliary information such as linked sites. @param dumpContentType the type of dump @return true if the dumpfile contains revisions @throws IllegalArgumentException if the given dump file type is not known
[ "public static boolean isRevisionDumpFile(DumpContentType dumpContentType) {\n\t\tif (WmfDumpFile.REVISION_DUMP.containsKey(dumpContentType)) {\n\t\t\treturn WmfDumpFile.REVISION_DUMP.get(dumpContentType);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Unsupported dump type \"\n\t\t\t\t\t+ dumpContentType);\n\t\t}\n\t}" ]
[ "public static Multimap<String, String> convertToMultiMap(final PObject objectParams) {\n Multimap<String, String> params = HashMultimap.create();\n if (objectParams != null) {\n Iterator<String> customParamsIter = objectParams.keys();\n while (customParamsIter.hasNext()) {\n String key = customParamsIter.next();\n if (objectParams.isArray(key)) {\n final PArray array = objectParams.optArray(key);\n for (int i = 0; i < array.size(); i++) {\n params.put(key, array.getString(i));\n }\n } else {\n params.put(key, objectParams.optString(key, \"\"));\n }\n }\n }\n\n return params;\n }", "public boolean isEmbeddedProperty(String targetTypeName, List<String> namesWithoutAlias) {\n\t\tOgmEntityPersister persister = getPersister( targetTypeName );\n\t\tType propertyType = persister.getPropertyType( namesWithoutAlias.get( 0 ) );\n\t\tif ( propertyType.isComponentType() ) {\n\t\t\t// Embedded\n\t\t\treturn true;\n\t\t}\n\t\telse if ( propertyType.isAssociationType() ) {\n\t\t\tJoinable associatedJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( persister.getFactory() );\n\t\t\tif ( associatedJoinable.isCollection() ) {\n\t\t\t\tOgmCollectionPersister collectionPersister = (OgmCollectionPersister) associatedJoinable;\n\t\t\t\treturn collectionPersister.getType().isComponentType();\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "@VisibleForTesting\n protected static int getBarSize(final ScaleBarRenderSettings settings) {\n if (settings.getParams().barSize != null) {\n return settings.getParams().barSize;\n } else {\n if (settings.getParams().getOrientation().isHorizontal()) {\n return settings.getMaxSize().height / 4;\n } else {\n return settings.getMaxSize().width / 4;\n }\n }\n }", "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 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}", "public void each(int offset, int maxRows, Closure closure) throws SQLException {\n eachRow(getSql(), getParameters(), offset, maxRows, closure);\n }", "public static boolean pullImage(Launcher launcher, final String imageTag, final String username, final String password, final String host)\n throws IOException, InterruptedException {\n\n return launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {\n public Boolean call() throws IOException {\n DockerUtils.pullImage(imageTag, username, password, host);\n return true;\n }\n });\n }", "private String trim(String line) {\n char[] chars = line.toCharArray();\n int len = chars.length;\n\n while (len > 0) {\n if (!Character.isWhitespace(chars[len - 1])) {\n break;\n }\n len--;\n }\n\n return line.substring(0, len);\n }", "public static base_response expire(nitro_service client, cacheobject resource) throws Exception {\n\t\tcacheobject expireresource = new cacheobject();\n\t\texpireresource.locator = resource.locator;\n\t\texpireresource.url = resource.url;\n\t\texpireresource.host = resource.host;\n\t\texpireresource.port = resource.port;\n\t\texpireresource.groupname = resource.groupname;\n\t\texpireresource.httpmethod = resource.httpmethod;\n\t\treturn expireresource.perform_operation(client,\"expire\");\n\t}" ]
Use this API to update bridgetable.
[ "public static base_response update(nitro_service client, bridgetable resource) throws Exception {\n\t\tbridgetable updateresource = new bridgetable();\n\t\tupdateresource.bridgeage = resource.bridgeage;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
[ "private static String wordShapeDan2Bio(String s, Collection<String> knownLCWords) {\r\n if (containsGreekLetter(s)) {\r\n return wordShapeDan2(s, knownLCWords) + \"-GREEK\";\r\n } else {\r\n return wordShapeDan2(s, knownLCWords);\r\n }\r\n }", "public static Date getTime(int hour, int minutes)\n {\n Calendar cal = popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, hour);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.SECOND, 0);\n Date result = cal.getTime();\n pushCalendar(cal);\n return result;\n }", "private boolean moreDates(Calendar calendar, List<Date> dates)\n {\n boolean result;\n if (m_finishDate == null)\n {\n int occurrences = NumberHelper.getInt(m_occurrences);\n if (occurrences < 1)\n {\n occurrences = 1;\n }\n result = dates.size() < occurrences;\n }\n else\n {\n result = calendar.getTimeInMillis() <= m_finishDate.getTime();\n }\n return result;\n }", "public void performImplicitDoubleStep(int x1, int x2 , double real , double img ) {\n double a11 = A.get(x1,x1);\n double a21 = A.get(x1+1,x1);\n double a12 = A.get(x1,x1+1);\n double a22 = A.get(x1+1,x1+1);\n double a32 = A.get(x1+2,x1+1);\n\n double p_plus_t = 2.0*real;\n double p_times_t = real*real + img*img;\n\n double b11,b21,b31;\n if( useStandardEq ) {\n b11 = (a11*a11 - p_plus_t*a11+p_times_t)/a21 + a12;\n b21 = a11+a22-p_plus_t;\n b31 = a32;\n } else {\n // this is different from the version in the book and seems in my testing to be more resilient to\n // over flow issues\n b11 = (a11*a11 - p_plus_t*a11+p_times_t) + a12*a21;\n b21 = (a11+a22-p_plus_t)*a21;\n b31 = a32*a21;\n }\n\n performImplicitDoubleStep(x1, x2, b11, b21, b31);\n }", "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 }", "public ModelNode registerDeploymentSubsystemResource(final String subsystemName, final Resource resource) {\n assert subsystemName != null : \"The subsystemName cannot be null\";\n assert resource != null : \"The resource cannot be null\";\n return registerDeploymentSubResource(subsystemName, PathAddress.EMPTY_ADDRESS, resource);\n }", "private boolean activityIsStartMilestone(Activity activity)\n {\n String type = activity.getType();\n return type != null && type.indexOf(\"StartMilestone\") != -1;\n }", "@Override\n\tpublic int getMinPrefixLengthForBlock() {\n\t\tint count = getDivisionCount();\n\t\tint totalPrefix = getBitCount();\n\t\tfor(int i = count - 1; i >= 0 ; i--) {\n\t\t\tAddressDivisionBase div = getDivision(i);\n\t\t\tint segBitCount = div.getBitCount();\n\t\t\tint segPrefix = div.getMinPrefixLengthForBlock();\n\t\t\tif(segPrefix == segBitCount) {\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\ttotalPrefix -= segBitCount;\n\t\t\t\tif(segPrefix != 0) {\n\t\t\t\t\ttotalPrefix += segPrefix;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn totalPrefix;\n\t}", "@JsonProperty(\"aliases\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, List<TermImpl>> getAliasUpdates() {\n \t\n \tMap<String, List<TermImpl>> updatedValues = new HashMap<>();\n \tfor(Map.Entry<String,AliasesWithUpdate> entry : newAliases.entrySet()) {\n \t\tAliasesWithUpdate update = entry.getValue();\n \t\tif (!update.write) {\n \t\t\tcontinue;\n \t\t}\n \t\tList<TermImpl> convertedAliases = new ArrayList<>();\n \t\tfor(MonolingualTextValue alias : update.aliases) {\n \t\t\tconvertedAliases.add(monolingualToJackson(alias));\n \t\t}\n \t\tupdatedValues.put(entry.getKey(), convertedAliases);\n \t}\n \treturn updatedValues;\n }" ]
Navigate to, and remove, this address in the given model node. @param model the model node @return the submodel @throws NoSuchElementException if the model contains no such element @deprecated manipulating a deep DMR node tree via PathAddress is no longer how the management layer works internally, so this method has become legacy cruft. Management operation handlers would use {@link org.jboss.as.controller.OperationContext#removeResource(PathAddress)} to remove resources.
[ "@Deprecated\n public ModelNode remove(ModelNode model) throws NoSuchElementException {\n final Iterator<PathElement> i = pathAddressList.iterator();\n while (i.hasNext()) {\n final PathElement element = i.next();\n if (i.hasNext()) {\n model = model.require(element.getKey()).require(element.getValue());\n } else {\n final ModelNode parent = model.require(element.getKey());\n model = parent.remove(element.getValue()).clone();\n }\n }\n return model;\n }" ]
[ "@Override\n public Iterator<BoxItem.Info> iterator() {\n URL url = GET_COLLECTION_ITEMS_URL.build(this.getAPI().getBaseURL(), BoxCollection.this.getID());\n return new BoxItemIterator(BoxCollection.this.getAPI(), url);\n }", "public Results analyze(RuleSet ruleSet) {\r\n long startTime = System.currentTimeMillis();\r\n DirectoryResults reportResults = new DirectoryResults();\r\n\r\n int numThreads = Runtime.getRuntime().availableProcessors() - 1;\r\n numThreads = numThreads > 0 ? numThreads : 1;\r\n\r\n ExecutorService pool = Executors.newFixedThreadPool(numThreads);\r\n\r\n for (FileSet fileSet : fileSets) {\r\n processFileSet(fileSet, ruleSet, pool);\r\n }\r\n\r\n pool.shutdown();\r\n\r\n try {\r\n boolean completed = pool.awaitTermination(POOL_TIMEOUT_SECONDS, TimeUnit.SECONDS);\r\n if (!completed) {\r\n throw new IllegalStateException(\"Thread Pool terminated before comp<FileResults>letion\");\r\n }\r\n } catch (InterruptedException e) {\r\n throw new IllegalStateException(\"Thread Pool interrupted before completion\");\r\n }\r\n\r\n addDirectoryResults(reportResults);\r\n LOG.info(\"Analysis time=\" + (System.currentTimeMillis() - startTime) + \"ms\");\r\n return reportResults;\r\n }", "public void info(Throwable throwable, String msg, Object[] argArray) {\n\t\tlogIfEnabled(Level.INFO, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);\n\t}", "public Swagger read(Class<?> cls) {\n SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);\n if (swaggerDefinition != null) {\n readSwaggerConfig(cls, swaggerDefinition);\n }\n\n return read(cls, \"\", null, false, new String[0], new String[0], new LinkedHashMap<>(), new ArrayList<>(), new HashSet<>());\n }", "private Integer getNullOnValue(Integer value, int nullValue)\n {\n return (NumberHelper.getInt(value) == nullValue ? null : value);\n }", "private static void defineField(Map<String, FieldType> container, String name, FieldType type)\n {\n defineField(container, name, type, null);\n }", "protected void prepareForwardedRequestHeaders(RequestData request, ForwardDestination destination) {\n HttpHeaders headers = request.getHeaders();\n headers.set(HOST, destination.getUri().getAuthority());\n headers.remove(TE);\n }", "public static final Date parseDate(String value)\n {\n Date result = null;\n\n try\n {\n if (value != null && !value.isEmpty())\n {\n result = DATE_FORMAT.get().parse(value);\n }\n }\n catch (ParseException ex)\n {\n // Ignore\n }\n\n return result;\n }", "public final Object getRealObject(Object objectOrProxy)\r\n {\r\n if(isNormalOjbProxy(objectOrProxy))\r\n {\r\n String msg;\r\n\r\n try\r\n {\r\n return getIndirectionHandler(objectOrProxy).getRealSubject();\r\n }\r\n catch(ClassCastException e)\r\n {\r\n // shouldn't happen but still ...\r\n msg = \"The InvocationHandler for the provided Proxy was not an instance of \" + IndirectionHandler.class.getName();\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(IllegalArgumentException e)\r\n {\r\n msg = \"Could not retrieve real object for given Proxy: \" + objectOrProxy;\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for given Proxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else if(isVirtualOjbProxy(objectOrProxy))\r\n {\r\n try\r\n {\r\n return ((VirtualProxy) objectOrProxy).getRealSubject();\r\n }\r\n catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for VirtualProxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else\r\n {\r\n return objectOrProxy;\r\n }\r\n }" ]
Convert a color to an angle. @param color The RGB value of the color to "find" on the color wheel. @return The angle (in rad) the "normalized" color is displayed on the color wheel.
[ "private float colorToAngle(int color) {\n\t\tfloat[] colors = new float[3];\n\t\tColor.colorToHSV(color, colors);\n\t\t\n\t\treturn (float) Math.toRadians(-colors[0]);\n\t}" ]
[ "public static final long getLong(byte[] data, int offset)\n {\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 64; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }", "private void removeMount(SlotReference slot) {\n mediaDetails.remove(slot);\n if (mediaMounts.remove(slot)) {\n deliverMountUpdate(slot, false);\n }\n }", "public static FormValidation validateEmails(String emails) {\n if (!Strings.isNullOrEmpty(emails)) {\n String[] recipients = StringUtils.split(emails, \" \");\n for (String email : recipients) {\n FormValidation validation = validateInternetAddress(email);\n if (validation != FormValidation.ok()) {\n return validation;\n }\n }\n }\n return FormValidation.ok();\n }", "private void makeSingularPositive() {\n numSingular = qralg.getNumberOfSingularValues();\n singularValues = qralg.getSingularValues();\n\n for( int i = 0; i < numSingular; i++ ) {\n double val = singularValues[i];\n\n if( val < 0 ) {\n singularValues[i] = -val;\n\n if( computeU ) {\n // compute the results of multiplying it by an element of -1 at this location in\n // a diagonal matrix.\n int start = i* Ut.numCols;\n int stop = start+ Ut.numCols;\n\n for( int j = start; j < stop; j++ ) {\n Ut.data[j] = -Ut.data[j];\n }\n }\n }\n }\n }", "private boolean hasAbstractPackagePrivateSuperClassWithImplementation(Class<?> clazz, BridgeMethod bridgeMethod) {\n Class<?> superClass = clazz.getSuperclass();\n while (superClass != null) {\n if (Modifier.isAbstract(superClass.getModifiers()) && Reflections.isPackagePrivate(superClass.getModifiers())) {\n // if superclass is abstract, we need to dig deeper\n for (Method method : superClass.getDeclaredMethods()) {\n if (bridgeMethod.signature.matches(method) && method.getGenericReturnType().equals(bridgeMethod.returnType)\n && !Reflections.isAbstract(method)) {\n // this is the case we are after -> methods have same signature and the one in super class has actual implementation\n return true;\n }\n }\n }\n superClass = superClass.getSuperclass();\n }\n return false;\n }", "private Integer getKeyPartitionId(byte[] key) {\n Integer keyPartitionId = storeInstance.getNodesPartitionIdForKey(nodeId, key);\n\n Utils.notNull(keyPartitionId);\n return keyPartitionId;\n }", "public double mean() {\n double total = 0;\n\n final int N = getNumElements();\n for( int i = 0; i < N; i++ ) {\n total += get(i);\n }\n\n return total/N;\n }", "public static String get(Properties props, String name, String defval) {\n String value = props.getProperty(name);\n if (value == null)\n value = defval;\n return value;\n }", "@Override\n public HandlerRegistration addChangeHandler(final ChangeHandler handler) {\n return getRangeInputElement().addDomHandler(handler, ChangeEvent.getType());\n }" ]
Configs created by this ConfigBuilder will use the given Redis sentinels. @param sentinels the Redis set of sentinels @return this ConfigBuilder
[ "public ConfigBuilder withSentinels(final Set<String> sentinels) {\n if (sentinels == null || sentinels.size() < 1) {\n throw new IllegalArgumentException(\"sentinels is null or empty: \" + sentinels);\n }\n this.sentinels = sentinels;\n return this;\n }" ]
[ "private long size(final Jedis jedis, final String queueName) {\n final String key = key(QUEUE, queueName);\n final long size;\n if (JedisUtils.isDelayedQueue(jedis, key)) { // If delayed queue, use ZCARD\n size = jedis.zcard(key);\n } else { // Else, use LLEN\n size = jedis.llen(key);\n }\n return size;\n }", "public void linkOneToMany(Object obj, CollectionDescriptor cod, boolean insert)\n {\n Object referencedObjects = cod.getPersistentField().get(obj);\n storeAndLinkOneToMany(true, obj, cod,referencedObjects, insert);\n }", "@VisibleForTesting\n protected static int getLabelDistance(final ScaleBarRenderSettings settings) {\n if (settings.getParams().labelDistance != null) {\n return settings.getParams().labelDistance;\n } else {\n if (settings.getParams().getOrientation().isHorizontal()) {\n return settings.getMaxSize().width / 40;\n } else {\n return settings.getMaxSize().height / 40;\n }\n }\n }", "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 static <T> int createTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig)\n\t\t\tthrows SQLException {\n\t\tDao<T, ?> dao = DaoManager.createDao(connectionSource, tableConfig);\n\t\treturn doCreateTable(dao, false);\n\t}", "public static <E extends Enum<E>> EnumStringConverter<E> create(Class<E> enumType) {\n return new EnumStringConverter<E>(enumType);\n }", "public Task add()\n {\n Task task = new Task(m_projectFile, (Task) null);\n add(task);\n m_projectFile.getChildTasks().add(task);\n return task;\n }", "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 }", "public double getValue(double x)\n\t{\n\t\tsynchronized(interpolatingRationalFunctionsLazyInitLock) {\n\t\t\tif(interpolatingRationalFunctions == null) {\n\t\t\t\tdoCreateRationalFunctions();\n\t\t\t}\n\t\t}\n\n\t\t// Get interpolating rational function for the given point x\n\t\tint pointIndex = java.util.Arrays.binarySearch(points, x);\n\t\tif(pointIndex >= 0) {\n\t\t\treturn values[pointIndex];\n\t\t}\n\n\t\tint intervallIndex = -pointIndex-2;\n\n\t\t// Check for extrapolation\n\t\tif(intervallIndex < 0) {\n\t\t\t// Extrapolation\n\t\t\tif(this.extrapolationMethod == ExtrapolationMethod.CONSTANT) {\n\t\t\t\treturn values[0];\n\t\t\t} else if(this.extrapolationMethod == ExtrapolationMethod.LINEAR) {\n\t\t\t\treturn values[0]+(values[1]-values[0])/(points[1]-points[0])*(x-points[0]);\n\t\t\t} else {\n\t\t\t\tintervallIndex = 0;\n\t\t\t}\n\t\t}\n\t\telse if(intervallIndex > points.length-2) {\n\t\t\t// Extrapolation\n\t\t\tif(this.extrapolationMethod == ExtrapolationMethod.CONSTANT) {\n\t\t\t\treturn values[points.length-1];\n\t\t\t} else if(this.extrapolationMethod == ExtrapolationMethod.LINEAR) {\n\t\t\t\treturn values[points.length-1]+(values[points.length-2]-values[points.length-1])/(points[points.length-2]-points[points.length-1])*(x-points[points.length-1]);\n\t\t\t} else {\n\t\t\t\tintervallIndex = points.length-2;\n\t\t\t}\n\t\t}\n\n\t\tRationalFunction rationalFunction = interpolatingRationalFunctions[intervallIndex];\n\n\t\t// Calculate interpolating value\n\t\treturn rationalFunction.getValue(x-points[intervallIndex]);\n\t}" ]
This method take a list of fileName of the type partitionId_Replica_Chunk and returns file names that match the regular expression masterPartitionId_
[ "private static List<String> parseAndCompare(List<String> fileNames, int masterPartitionId) {\n List<String> sourceFileNames = new ArrayList<String>();\n for(String fileName: fileNames) {\n String[] partitionIdReplicaChunk = fileName.split(SPLIT_LITERAL);\n if(Integer.parseInt(partitionIdReplicaChunk[0]) == masterPartitionId) {\n sourceFileNames.add(fileName);\n }\n }\n return sourceFileNames;\n }" ]
[ "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 }", "public static String getStringOption(Map<String, String> configOptions, String optionKey, String defaultValue) {\n\n String result = configOptions.get(optionKey);\n return null != result ? result : defaultValue;\n }", "public static void initialize(final Context context) {\n if (!initialized.compareAndSet(false, true)) {\n return;\n }\n\n applicationContext = context.getApplicationContext();\n\n final String packageName = applicationContext.getPackageName();\n localAppName = packageName;\n\n final PackageManager manager = applicationContext.getPackageManager();\n try {\n final PackageInfo pkgInfo = manager.getPackageInfo(packageName, 0);\n localAppVersion = pkgInfo.versionName;\n } catch (final NameNotFoundException e) {\n Log.d(TAG, \"Failed to get version of application, will not send in device info.\");\n }\n\n Log.d(TAG, \"Initialized android SDK\");\n }", "public 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 static void sendMimeMessage(MimeMessage mimeMessage) {\r\n try {\r\n Transport.send(mimeMessage);\r\n } catch (MessagingException e) {\r\n throw new IllegalStateException(\"Can not send message \" + mimeMessage, e);\r\n }\r\n }", "protected <H extends EventHandler> HandlerRegistration addHandler(final H handler, GwtEvent.Type<H> type) {\r\n\r\n return ensureHandlers().addHandlerToSource(type, this, handler);\r\n }", "public static Property getChildAddress(final ModelNode address) {\n if (address.getType() != ModelType.LIST) {\n throw new IllegalArgumentException(\"The address type must be a list.\");\n }\n final List<Property> addressParts = address.asPropertyList();\n if (addressParts.isEmpty()) {\n throw new IllegalArgumentException(\"The address is empty.\");\n }\n return addressParts.get(addressParts.size() - 1);\n }", "public final static void appendCode(final StringBuilder out, final String in, final int start, final int end)\n {\n for (int i = start; i < end; i++)\n {\n final char c;\n switch (c = in.charAt(i))\n {\n case '&':\n out.append(\"&amp;\");\n break;\n case '<':\n out.append(\"&lt;\");\n break;\n case '>':\n out.append(\"&gt;\");\n break;\n default:\n out.append(c);\n break;\n }\n }\n }", "public static sslparameter get(nitro_service service) throws Exception{\n\t\tsslparameter obj = new sslparameter();\n\t\tsslparameter[] response = (sslparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}" ]
Format a date that is parseable from JavaScript, according to ISO-8601. @param date the date to format to a JSON string @return a formatted date in the form of a string
[ "public static String toJson(Date date) {\n if (date == null) {\n return NULL_VALUE;\n }\n\n CharBuf buffer = CharBuf.create(26);\n writeDate(date, buffer);\n\n return buffer.toString();\n }" ]
[ "public void deploy(InputStream inputStream) throws IOException {\n final List<? extends HasMetadata> entities = deploy(\"application\", inputStream);\n\n if (this.applicationName == null) {\n\n Optional<String> deployment = entities.stream()\n .filter(hm -> hm instanceof Deployment)\n .map(hm -> (Deployment) hm)\n .map(rc -> rc.getMetadata().getName()).findFirst();\n\n deployment.ifPresent(name -> this.applicationName = name);\n }\n }", "public static void log(String label, Class<?> klass, Map<String, Object> map)\n {\n if (LOG != null)\n {\n LOG.write(label);\n LOG.write(\": \");\n LOG.println(klass.getSimpleName());\n\n for (Map.Entry<String, Object> entry : map.entrySet())\n {\n LOG.println(entry.getKey() + \": \" + entry.getValue());\n }\n LOG.println();\n LOG.flush();\n }\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 }", "boolean isUserPasswordReset(CmsUser user) {\n\n if (USER_PASSWORD_STATUS.containsKey(user.getId())) { //Check if user was checked before\n if (!USER_PASSWORD_STATUS.get(user.getId()).booleanValue()) { // was false before, false->true is never done without changing map\n return false;\n }\n if (m_checkedUserPasswordReset.contains(user.getId())) { //was true before, true->false happens when user resets password. Only check one time per table load.\n return true; //Set gets flushed on reloading table\n }\n }\n CmsUser currentUser = user;\n if (user.getAdditionalInfo().size() < 3) {\n\n try {\n currentUser = m_cms.readUser(user.getId());\n } catch (CmsException e) {\n LOG.error(\"Can not read user\", e);\n }\n }\n if (currentUser.getAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_PASSWORD_RESET) != null) {\n USER_PASSWORD_STATUS.put(currentUser.getId(), new Boolean(true));\n m_checkedUserPasswordReset.add(currentUser.getId());\n return true;\n }\n USER_PASSWORD_STATUS.put(currentUser.getId(), new Boolean(false));\n return false;\n }", "public int getPropertyId(@NotNull final PersistentStoreTransaction txn, @NotNull final String propertyName, final boolean allowCreate) {\n return allowCreate ? propertyIds.getOrAllocateId(txn, propertyName) : propertyIds.getId(txn, propertyName);\n }", "public void set(String name, Object value) {\n hashAttributes.put(name, value);\n\n if (plugin != null) {\n plugin.invalidate();\n }\n }", "public static dnsview get(nitro_service service, String viewname) throws Exception{\n\t\tdnsview obj = new dnsview();\n\t\tobj.set_viewname(viewname);\n\t\tdnsview response = (dnsview) obj.get_resource(service);\n\t\treturn response;\n\t}", "protected void processDurationField(Row row)\n {\n processField(row, \"DUR_FIELD_ID\", \"DUR_REF_UID\", MPDUtility.getAdjustedDuration(m_project, row.getInt(\"DUR_VALUE\"), MPDUtility.getDurationTimeUnits(row.getInt(\"DUR_FMT\"))));\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 }" ]
Answer the search class. This is the class of the example object or the class represented by Identity. @return Class
[ "public Class getSearchClass()\r\n\t{\r\n\t\tObject obj = getExampleObject();\r\n\r\n\t\tif (obj instanceof Identity)\r\n\t\t{\r\n\t\t\treturn ((Identity) obj).getObjectsTopLevelClass();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn obj.getClass();\r\n\t\t}\r\n\t}" ]
[ "@SuppressWarnings(\"serial\")\n private Component createAddDescriptorButton() {\n\n Button addDescriptorButton = CmsToolBar.createButton(\n FontOpenCms.COPY_LOCALE,\n m_messages.key(Messages.GUI_ADD_DESCRIPTOR_0));\n\n addDescriptorButton.setDisableOnClick(true);\n\n addDescriptorButton.addClickListener(new ClickListener() {\n\n @SuppressWarnings(\"synthetic-access\")\n public void buttonClick(ClickEvent event) {\n\n Map<Object, Object> filters = getFilters();\n m_table.clearFilters();\n if (!m_model.addDescriptor()) {\n CmsVaadinUtils.showAlert(\n m_messages.key(Messages.ERR_BUNDLE_DESCRIPTOR_CREATION_FAILED_0),\n m_messages.key(Messages.ERR_BUNDLE_DESCRIPTOR_CREATION_FAILED_DESCRIPTION_0),\n null);\n } else {\n IndexedContainer newContainer = null;\n try {\n newContainer = m_model.getContainerForCurrentLocale();\n m_table.setContainerDataSource(newContainer);\n initFieldFactories();\n initStyleGenerators();\n setEditMode(EditMode.MASTER);\n m_table.setColumnCollapsingAllowed(true);\n adjustVisibleColumns();\n m_options.updateShownOptions(m_model.hasMasterMode(), m_model.canAddKeys());\n m_options.setEditMode(m_model.getEditMode());\n } catch (IOException | CmsException e) {\n // Can never appear here, since container is created by addDescriptor already.\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n setFilters(filters);\n }\n });\n return addDescriptorButton;\n }", "public static Variable upcastToGeneratedBuilder(\n SourceBuilder code, Datatype datatype, String builder) {\n return code.scope().computeIfAbsent(Declaration.UPCAST, () -> {\n Variable base = new Variable(\"base\");\n code.addLine(UPCAST_COMMENT)\n .addLine(\"%s %s = %s;\", datatype.getGeneratedBuilder(), base, builder);\n return base;\n });\n }", "public HashMap<String, Object> getFirstResult(String query)\n throws Exception {\n HashMap<String, Object> result = null;\n\n Statement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = getConnection()) {\n queryStatement = sqlConnection.createStatement();\n results = queryStatement.executeQuery(query);\n if (results.next()) {\n result = new HashMap<>();\n String[] columns = getColumnNames(results.getMetaData());\n\n for (String column : columns) {\n result.put(column, results.getObject(column));\n }\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return result;\n }", "private static void createDirectory(Path path) throws IOException {\n\t\ttry {\n\t\t\tFiles.createDirectory(path);\n\t\t} catch (FileAlreadyExistsException e) {\n\t\t\tif (!Files.isDirectory(path)) {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t}", "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 String fileNameClean(String s) {\r\n char[] chars = s.toCharArray();\r\n StringBuilder sb = new StringBuilder();\r\n for (char c : chars) {\r\n if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '_')) {\r\n sb.append(c);\r\n } else {\r\n if (c == ' ' || c == '-') {\r\n sb.append('_');\r\n } else {\r\n sb.append('x').append((int) c).append('x');\r\n }\r\n }\r\n }\r\n return sb.toString();\r\n }", "public boolean isPublisherWrapped(AbstractProject<?, ?> project, Class<T> type) {\n return find(project, type) != null;\n }", "public Task<Long> count() {\n return dispatcher.dispatchTask(new Callable<Long>() {\n @Override\n public Long call() {\n return proxy.count();\n }\n });\n }", "private <T> void add(EjbDescriptor<T> ejbDescriptor) {\n InternalEjbDescriptor<T> internalEjbDescriptor = InternalEjbDescriptor.of(ejbDescriptor);\n ejbByName.put(ejbDescriptor.getEjbName(), internalEjbDescriptor);\n ejbByClass.put(ejbDescriptor.getBeanClass(), internalEjbDescriptor.getEjbName());\n }" ]
This method allows a resource assignment to be added to the current task. @param resource the resource to assign @return ResourceAssignment object
[ "public ResourceAssignment addResourceAssignment(Resource resource)\n {\n ResourceAssignment assignment = getExistingResourceAssignment(resource);\n\n if (assignment == null)\n {\n assignment = new ResourceAssignment(getParentFile(), this);\n m_assignments.add(assignment);\n getParentFile().getResourceAssignments().add(assignment);\n\n assignment.setTaskUniqueID(getUniqueID());\n assignment.setWork(getDuration());\n assignment.setUnits(ResourceAssignment.DEFAULT_UNITS);\n\n if (resource != null)\n {\n assignment.setResourceUniqueID(resource.getUniqueID());\n resource.addResourceAssignment(assignment);\n }\n }\n\n return (assignment);\n }" ]
[ "public Query customizeQuery(Object anObject, PersistenceBroker aBroker, CollectionDescriptor aCod, QueryByCriteria aQuery)\r\n {\r\n return aQuery;\r\n }", "private boolean checkAndSetManifestAndImagePathCandidates(String manifestPath, String candidateImagePath, ArtifactoryDependenciesClient dependenciesClient, TaskListener listener) throws IOException {\n String candidateManifest = getManifestFromArtifactory(dependenciesClient, manifestPath);\n if (candidateManifest == null) {\n return false;\n }\n\n String imageDigest = DockerUtils.getConfigDigest(candidateManifest);\n if (imageDigest.equals(imageId)) {\n manifest = candidateManifest;\n imagePath = candidateImagePath;\n return true;\n }\n\n listener.getLogger().println(String.format(\"Found incorrect manifest.json file in Artifactory in the following path: %s\\nExpecting: %s got: %s\", manifestPath, imageId, imageDigest));\n return false;\n }", "@Override\n\tpublic synchronized boolean fireEventAndWait(Eventable eventable)\n\t\t\tthrows ElementNotVisibleException, NoSuchElementException, InterruptedException {\n\t\ttry {\n\n\t\t\tboolean handleChanged = false;\n\t\t\tboolean result = false;\n\n\t\t\tif (eventable.getRelatedFrame() != null && !eventable.getRelatedFrame().equals(\"\")) {\n\t\t\t\tLOGGER.debug(\"switching to frame: \" + eventable.getRelatedFrame());\n\t\t\t\ttry {\n\n\t\t\t\t\tswitchToFrame(eventable.getRelatedFrame());\n\t\t\t\t} catch (NoSuchFrameException e) {\n\t\t\t\t\tLOGGER.debug(\"Frame not found, possibly while back-tracking..\", e);\n\t\t\t\t\t// TODO Stefan, This exception is caught to prevent stopping\n\t\t\t\t\t// from working\n\t\t\t\t\t// This was the case on the Gmail case; find out if not switching\n\t\t\t\t\t// (catching)\n\t\t\t\t\t// Results in good performance...\n\t\t\t\t}\n\t\t\t\thandleChanged = true;\n\t\t\t}\n\n\t\t\tWebElement webElement =\n\t\t\t\t\tbrowser.findElement(eventable.getIdentification().getWebDriverBy());\n\n\t\t\tif (webElement != null) {\n\t\t\t\tresult = fireEventWait(webElement, eventable);\n\t\t\t}\n\n\t\t\tif (handleChanged) {\n\t\t\t\tbrowser.switchTo().defaultContent();\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (ElementNotVisibleException | NoSuchElementException e) {\n\t\t\tthrow e;\n\t\t} catch (WebDriverException e) {\n\t\t\tthrowIfConnectionException(e);\n\t\t\treturn false;\n\t\t}\n\t}", "private void merge(Integer cid1, Integer cid2) {\n Collection<String> klass1 = classix.get(cid1);\n Collection<String> klass2 = classix.get(cid2);\n\n // if klass1 is the smaller, swap the two\n if (klass1.size() < klass2.size()) {\n Collection<String> tmp = klass2;\n klass2 = klass1;\n klass1 = tmp;\n\n Integer itmp = cid2;\n cid2 = cid1;\n cid1 = itmp;\n }\n\n // now perform the actual merge\n for (String id : klass2) {\n klass1.add(id);\n recordix.put(id, cid1);\n }\n\n // delete the smaller class, and we're done\n classix.remove(cid2);\n }", "@PostConstruct\n\tprotected void buildCopyrightMap() {\n\t\tif (null == declaredPlugins) {\n\t\t\treturn;\n\t\t}\n\t\t// go over all plug-ins, adding copyright info, avoiding duplicates (on object key)\n\t\tfor (PluginInfo plugin : declaredPlugins.values()) {\n\t\t\tfor (CopyrightInfo copyright : plugin.getCopyrightInfo()) {\n\t\t\t\tString key = copyright.getKey();\n\t\t\t\tString msg = copyright.getKey() + \": \" + copyright.getCopyright() + \" : licensed as \" +\n\t\t\t\t\t\tcopyright.getLicenseName() + \", see \" + copyright.getLicenseUrl();\n\t\t\t\tif (null != copyright.getSourceUrl()) {\n\t\t\t\t\tmsg += \" source \" + copyright.getSourceUrl();\n\t\t\t\t}\n\t\t\t\tif (!copyrightMap.containsKey(key)) {\n\t\t\t\t\tlog.info(msg);\n\t\t\t\t\tcopyrightMap.put(key, copyright);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public boolean setOverrideRepeatCount(String pathName, String methodName, Integer ordinal, Integer repeatCount) {\n try {\n String methodId = getOverrideIdForMethodName(methodName).toString();\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"profileIdentifier\", this._profileName),\n new BasicNameValuePair(\"ordinal\", ordinal.toString()),\n new BasicNameValuePair(\"repeatNumber\", repeatCount.toString())\n };\n\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName) + \"/\" + methodId, params));\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "public static String getTitleGalleryKey(String gallery) {\n\n StringBuffer sb = new StringBuffer(GUI_TITLE_PREFIX);\n sb.append(gallery.toUpperCase());\n sb.append(GUI_TITLE_POSTFIX);\n return sb.toString();\n }", "public void addItem(T value, String text, boolean reload) {\n values.add(value);\n listBox.addItem(text, keyFactory.generateKey(value));\n\n if (reload) {\n reload();\n }\n }", "public static String stringifyJavascriptObject(Object object) {\n StringBuilder bld = new StringBuilder();\n stringify(object, bld);\n return bld.toString();\n }" ]
Asta Powerproject assigns an explicit calendar for each task. This method is used to find the most common calendar and use this as the default project calendar. This allows the explicitly assigned task calendars to be removed.
[ "private void deriveProjectCalendar()\n {\n //\n // Count the number of times each calendar is used\n //\n Map<ProjectCalendar, Integer> map = new HashMap<ProjectCalendar, Integer>();\n for (Task task : m_project.getTasks())\n {\n ProjectCalendar calendar = task.getCalendar();\n Integer count = map.get(calendar);\n if (count == null)\n {\n count = Integer.valueOf(1);\n }\n else\n {\n count = Integer.valueOf(count.intValue() + 1);\n }\n map.put(calendar, count);\n }\n\n //\n // Find the most frequently used calendar\n //\n int maxCount = 0;\n ProjectCalendar defaultCalendar = null;\n\n for (Entry<ProjectCalendar, Integer> entry : map.entrySet())\n {\n if (entry.getValue().intValue() > maxCount)\n {\n maxCount = entry.getValue().intValue();\n defaultCalendar = entry.getKey();\n }\n }\n\n //\n // Set the default calendar for the project\n // and remove it's use as a task-specific calendar.\n //\n if (defaultCalendar != null)\n {\n m_project.setDefaultCalendar(defaultCalendar);\n for (Task task : m_project.getTasks())\n {\n if (task.getCalendar() == defaultCalendar)\n {\n task.setCalendar(null);\n }\n }\n }\n }" ]
[ "public Map<String, Object> getModuleFieldsFilters() {\n final Map<String, Object> params = new HashMap<String, Object>();\n\n for(final Filter filter: filters){\n params.putAll(filter.moduleFilterFields());\n }\n\n return params;\n }", "public Response getBill(int month, int year)\n throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new Response(request.get(\"/bill/\" + year + String.format(\"-%02d\", month)));\n }", "public void logAttributeWarning(PathAddress address, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, null, message, attributes));\n }", "public static final boolean valueIsNotDefault(FieldType type, Object value)\n {\n boolean result = true;\n\n if (value == null)\n {\n result = false;\n }\n else\n {\n DataType dataType = type.getDataType();\n switch (dataType)\n {\n case BOOLEAN:\n {\n result = ((Boolean) value).booleanValue();\n break;\n }\n\n case CURRENCY:\n case NUMERIC:\n {\n result = !NumberHelper.equals(((Number) value).doubleValue(), 0.0, 0.00001);\n break;\n }\n\n case DURATION:\n {\n result = (((Duration) value).getDuration() != 0);\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n return result;\n }", "private boolean checkZoneRequirement(HashMap<Integer, Integer> requiredRepFactor, int zoneId) {\n if(requiredRepFactor.containsKey(zoneId)) {\n if(requiredRepFactor.get(zoneId) == 0) {\n return false;\n } else {\n requiredRepFactor.put(zoneId, requiredRepFactor.get(zoneId) - 1);\n return true;\n }\n }\n return false;\n\n }", "public static <K,V> SortedMap<K,V> asImmutable(SortedMap<K, ? extends V> self) {\n return Collections.unmodifiableSortedMap(self);\n }", "public DbOrganization getMatchingOrganization(final DbModule dbModule) {\n if(dbModule.getOrganization() != null\n && !dbModule.getOrganization().isEmpty()){\n return getOrganization(dbModule.getOrganization());\n }\n\n for(final DbOrganization organization: repositoryHandler.getAllOrganizations()){\n final CorporateFilter corporateFilter = new CorporateFilter(organization);\n if(corporateFilter.matches(dbModule)){\n return organization;\n }\n }\n\n return null;\n }", "public void setOccurence(int min, int max) throws ParseException {\n if (!simplified) {\n if ((min < 0) || (min > max) || (max < 1)) {\n throw new ParseException(\"Illegal number {\" + min + \",\" + max + \"}\");\n }\n if (min == 0) {\n optional = true;\n }\n minimumOccurence = Math.max(1, min);\n maximumOccurence = max;\n } else {\n throw new ParseException(\"already simplified\");\n }\n }", "private double convertToConvention(double value, DataKey key, QuotingConvention toConvention, double toDisplacement,\r\n\t\t\tQuotingConvention fromConvention, double fromDisplacement, AnalyticModel model) {\r\n\r\n\t\tif(toConvention == fromConvention) {\r\n\t\t\tif(toConvention != QuotingConvention.PAYERVOLATILITYLOGNORMAL) {\r\n\t\t\t\treturn value;\r\n\t\t\t} else {\r\n\t\t\t\tif(toDisplacement == fromDisplacement) {\r\n\t\t\t\t\treturn value;\r\n\t\t\t\t} else {\r\n\t\t\t\t\treturn convertToConvention(convertToConvention(value, key, QuotingConvention.PAYERPRICE, 0, fromConvention, fromDisplacement, model),\r\n\t\t\t\t\t\t\tkey, toConvention, toDisplacement, QuotingConvention.PAYERPRICE, 0, model);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tSchedule floatSchedule\t= floatMetaSchedule.generateSchedule(getReferenceDate(), key.maturity, key.tenor);\r\n\t\tSchedule fixSchedule\t= fixMetaSchedule.generateSchedule(getReferenceDate(), key.maturity, key.tenor);\r\n\r\n\t\tdouble forward = Swap.getForwardSwapRate(fixSchedule, floatSchedule, model.getForwardCurve(forwardCurveName), model);\r\n\t\tdouble optionMaturity = floatSchedule.getFixing(0);\r\n\t\tdouble offset = key.moneyness /10000.0;\r\n\t\tdouble optionStrike = forward + (quotingConvention == QuotingConvention.RECEIVERPRICE ? -offset : offset);\r\n\t\tdouble payoffUnit = SwapAnnuity.getSwapAnnuity(fixSchedule.getFixing(0), fixSchedule, model.getDiscountCurve(discountCurveName), model);\r\n\r\n\t\tif(toConvention.equals(QuotingConvention.PAYERPRICE) && fromConvention.equals(QuotingConvention.PAYERVOLATILITYLOGNORMAL)) {\r\n\t\t\treturn AnalyticFormulas.blackScholesGeneralizedOptionValue(forward + fromDisplacement, value, optionMaturity, optionStrike + fromDisplacement, payoffUnit);\r\n\t\t}\r\n\t\telse if(toConvention.equals(QuotingConvention.PAYERPRICE) && fromConvention.equals(QuotingConvention.PAYERVOLATILITYNORMAL)) {\r\n\t\t\treturn AnalyticFormulas.bachelierOptionValue(forward, value, optionMaturity, optionStrike, payoffUnit);\r\n\t\t}\r\n\t\telse if(toConvention.equals(QuotingConvention.PAYERPRICE) && fromConvention.equals(QuotingConvention.RECEIVERPRICE)) {\r\n\t\t\treturn value + (forward - optionStrike) * payoffUnit;\r\n\t\t}\r\n\t\telse if(toConvention.equals(QuotingConvention.PAYERVOLATILITYLOGNORMAL) && fromConvention.equals(QuotingConvention.PAYERPRICE)) {\r\n\t\t\treturn AnalyticFormulas.blackScholesOptionImpliedVolatility(forward + toDisplacement, optionMaturity, optionStrike + toDisplacement, payoffUnit, value);\r\n\t\t}\r\n\t\telse if(toConvention.equals(QuotingConvention.PAYERVOLATILITYNORMAL) && fromConvention.equals(QuotingConvention.PAYERPRICE)) {\r\n\t\t\treturn AnalyticFormulas.bachelierOptionImpliedVolatility(forward, optionMaturity, optionStrike, payoffUnit, value);\r\n\t\t}\r\n\t\telse if(toConvention.equals(QuotingConvention.RECEIVERPRICE) && fromConvention.equals(QuotingConvention.PAYERPRICE)) {\r\n\t\t\treturn value - (forward - optionStrike) * payoffUnit;\r\n\t\t}\r\n\t\telse {\r\n\t\t\treturn convertToConvention(convertToConvention(value, key, QuotingConvention.PAYERPRICE, 0, fromConvention, fromDisplacement, model),\r\n\t\t\t\t\tkey, toConvention, toDisplacement, QuotingConvention.PAYERPRICE, 0, model);\r\n\t\t}\r\n\t}" ]
Find the latest task finish date. We treat this as the finish date for the project. @return finish date
[ "public Date getFinishDate()\n {\n Date finishDate = null;\n\n for (Task task : m_tasks)\n {\n //\n // If a hidden \"summary\" task is present we ignore it\n //\n if (NumberHelper.getInt(task.getUniqueID()) == 0)\n {\n continue;\n }\n\n //\n // Select the actual or forecast start date\n //\n Date taskFinishDate;\n taskFinishDate = task.getActualFinish();\n if (taskFinishDate == null)\n {\n taskFinishDate = task.getFinish();\n }\n\n if (taskFinishDate != null)\n {\n if (finishDate == null)\n {\n finishDate = taskFinishDate;\n }\n else\n {\n if (taskFinishDate.getTime() > finishDate.getTime())\n {\n finishDate = taskFinishDate;\n }\n }\n }\n }\n\n return (finishDate);\n }" ]
[ "public static String getGetterName(String propertyName, Class type) {\n String prefix = type == boolean.class || type == Boolean.class ? \"is\" : \"get\";\n return prefix + MetaClassHelper.capitalize(propertyName);\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 }", "private void readFile(InputStream is) throws IOException\n {\n StreamHelper.skip(is, 64);\n int index = 64;\n\n ArrayList<Integer> offsetList = new ArrayList<Integer>();\n List<String> nameList = new ArrayList<String>();\n\n while (true)\n {\n byte[] table = new byte[32];\n is.read(table);\n index += 32;\n\n int offset = PEPUtility.getInt(table, 0);\n offsetList.add(Integer.valueOf(offset));\n if (offset == 0)\n {\n break;\n }\n\n nameList.add(PEPUtility.getString(table, 5).toUpperCase());\n }\n\n StreamHelper.skip(is, offsetList.get(0).intValue() - index);\n\n for (int offsetIndex = 1; offsetIndex < offsetList.size() - 1; offsetIndex++)\n {\n String name = nameList.get(offsetIndex - 1);\n Class<? extends Table> tableClass = TABLE_CLASSES.get(name);\n if (tableClass == null)\n {\n tableClass = Table.class;\n }\n\n Table table;\n try\n {\n table = tableClass.newInstance();\n }\n\n catch (Exception ex)\n {\n throw new RuntimeException(ex);\n }\n\n m_tables.put(name, table);\n table.read(is);\n }\n }", "public static final int getInt(InputStream is) throws IOException\n {\n byte[] data = new byte[4];\n is.read(data);\n return getInt(data, 0);\n }", "private ProjectFile read() throws Exception\n {\n m_project = new ProjectFile();\n m_eventManager = m_project.getEventManager();\n\n ProjectConfig config = m_project.getProjectConfig();\n config.setAutoCalendarUniqueID(false);\n config.setAutoTaskID(false);\n config.setAutoTaskUniqueID(false);\n config.setAutoResourceUniqueID(false);\n config.setAutoWBS(false);\n config.setAutoOutlineNumber(false);\n\n m_project.getProjectProperties().setFileApplication(\"FastTrack\");\n m_project.getProjectProperties().setFileType(\"FTS\");\n\n m_eventManager.addProjectListeners(m_projectListeners);\n\n // processProject();\n // processCalendars();\n processResources();\n processTasks();\n processDependencies();\n processAssignments();\n\n return m_project;\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 static int getId(Context context, String id) {\n final String defType;\n if (id.startsWith(\"R.\")) {\n int dot = id.indexOf('.', 2);\n defType = id.substring(2, dot);\n } else {\n defType = \"drawable\";\n }\n\n Log.d(TAG, \"getId(): id: %s, extracted type: %s\", id, defType);\n return getId(context, id, defType);\n }", "public final void begin() {\n this.file = this.getAppender().getIoFile();\n if (this.file == null) {\n this.getAppender().getErrorHandler()\n .error(\"Scavenger not started: missing log file name\");\n return;\n }\n if (this.getProperties().getScavengeInterval() > -1) {\n final Thread thread = new Thread(this, \"Log4J File Scavenger\");\n thread.setDaemon(true);\n thread.start();\n this.threadRef = thread;\n }\n }", "public long removeAll(final String... members) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.srem(getKey(), members);\n }\n });\n }" ]
Adds the newState and the edge between the currentState and the newState on the SFG. @param newState the new state. @param eventable the clickable causing the new state. @return the clone state iff newState is a clone, else returns null
[ "private StateVertex addStateToCurrentState(StateVertex newState, Eventable eventable) {\n\t\tLOGGER.debug(\"addStateToCurrentState currentState: {} newState {}\",\n\t\t\t\tcurrentState.getName(), newState.getName());\n\n\t\t// Add the state to the stateFlowGraph. Store the result\n\t\tStateVertex cloneState = stateFlowGraph.putIfAbsent(newState);\n\n\t\t// Is there a clone detected?\n\t\tif (cloneState != null) {\n\t\t\tLOGGER.info(\"CLONE State detected: {} and {} are the same.\", newState.getName(),\n\t\t\t\t\tcloneState.getName());\n\t\t\tLOGGER.debug(\"CLONE CURRENT STATE: {}\", currentState.getName());\n\t\t\tLOGGER.debug(\"CLONE STATE: {}\", cloneState.getName());\n\t\t\tLOGGER.debug(\"CLONE CLICKABLE: {}\", eventable);\n\t\t\tboolean added = stateFlowGraph.addEdge(currentState, cloneState, eventable);\n\t\t\tif (!added) {\n\t\t\t\tLOGGER.debug(\"Clone edge !! Need to fix the crawlPath??\");\n\t\t\t}\n\t\t} else {\n\t\t\tstateFlowGraph.addEdge(currentState, newState, eventable);\n\t\t\tLOGGER.info(\"State {} added to the StateMachine.\", newState.getName());\n\t\t}\n\n\t\treturn cloneState;\n\t}" ]
[ "public static void permutationVector( DMatrixSparseCSC P , int[] vector) {\n if( P.numCols != P.numRows ) {\n throw new MatrixDimensionException(\"Expected a square matrix\");\n } else if( P.nz_length != P.numCols ) {\n throw new IllegalArgumentException(\"Expected N non-zero elements in permutation matrix\");\n } else if( vector.length < P.numCols ) {\n throw new IllegalArgumentException(\"vector is too short\");\n }\n\n int M = P.numCols;\n\n for (int i = 0; i < M; i++) {\n if( P.col_idx[i+1] != i+1 )\n throw new IllegalArgumentException(\"Unexpected number of elements in a column\");\n\n vector[P.nz_rows[i]] = i;\n }\n }", "private List<Entry> sortEntries(List<Entry> loadedEntries) {\n Collections.sort(loadedEntries, new Comparator<Entry>() {\n @Override\n public int compare(Entry entry1, Entry entry2) {\n int result = (int) (entry1.cuePosition - entry2.cuePosition);\n if (result == 0) {\n int h1 = (entry1.hotCueNumber != 0) ? 1 : 0;\n int h2 = (entry2.hotCueNumber != 0) ? 1 : 0;\n result = h1 - h2;\n }\n return result;\n }\n });\n return Collections.unmodifiableList(loadedEntries);\n }", "public static AppDescriptor of(String appName, Class<?> entryClass) {\n System.setProperty(\"osgl.version.suppress-var-found-warning\", \"true\");\n return of(appName, entryClass, Version.of(entryClass));\n }", "protected void appendList(StringBuilder sql, List<?> list, String init, String sep) {\n\n boolean first = true;\n\n for (Object s : list) {\n if (first) {\n sql.append(init);\n } else {\n sql.append(sep);\n }\n sql.append(s);\n first = false;\n }\n }", "public void createPath(String pathName, String pathValue, String requestType) {\n try {\n int type = getRequestTypeFromString(requestType);\n String url = BASE_PATH;\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"pathName\", pathName),\n new BasicNameValuePair(\"path\", pathValue),\n new BasicNameValuePair(\"requestType\", String.valueOf(type)),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n\n JSONObject response = new JSONObject(doPost(BASE_PATH, params));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }", "private void deliverCacheUpdate(SlotReference slot, MetadataCache cache) {\n for (final MetadataCacheListener listener : getCacheListeners()) {\n try {\n if (cache == null) {\n listener.cacheDetached(slot);\n } else {\n listener.cacheAttached(slot, cache);\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering metadata cache update to listener\", t);\n }\n }\n }", "public BoxFile.Info uploadFile(FileUploadParams uploadParams) {\n URL uploadURL = UPLOAD_FILE_URL.build(this.getAPI().getBaseUploadURL());\n BoxMultipartRequest request = new BoxMultipartRequest(getAPI(), uploadURL);\n\n JsonObject fieldJSON = new JsonObject();\n JsonObject parentIdJSON = new JsonObject();\n parentIdJSON.add(\"id\", getID());\n fieldJSON.add(\"name\", uploadParams.getName());\n fieldJSON.add(\"parent\", parentIdJSON);\n\n if (uploadParams.getCreated() != null) {\n fieldJSON.add(\"content_created_at\", BoxDateFormat.format(uploadParams.getCreated()));\n }\n\n if (uploadParams.getModified() != null) {\n fieldJSON.add(\"content_modified_at\", BoxDateFormat.format(uploadParams.getModified()));\n }\n\n if (uploadParams.getSHA1() != null && !uploadParams.getSHA1().isEmpty()) {\n request.setContentSHA1(uploadParams.getSHA1());\n }\n\n if (uploadParams.getDescription() != null) {\n fieldJSON.add(\"description\", uploadParams.getDescription());\n }\n\n request.putField(\"attributes\", fieldJSON.toString());\n\n if (uploadParams.getSize() > 0) {\n request.setFile(uploadParams.getContent(), uploadParams.getName(), uploadParams.getSize());\n } else if (uploadParams.getContent() != null) {\n request.setFile(uploadParams.getContent(), uploadParams.getName());\n } else {\n request.setUploadFileCallback(uploadParams.getUploadFileCallback(), uploadParams.getName());\n }\n\n BoxJSONResponse response;\n if (uploadParams.getProgressListener() == null) {\n response = (BoxJSONResponse) request.send();\n } else {\n response = (BoxJSONResponse) request.send(uploadParams.getProgressListener());\n }\n JsonObject collection = JsonObject.readFrom(response.getJSON());\n JsonArray entries = collection.get(\"entries\").asArray();\n JsonObject fileInfoJSON = entries.get(0).asObject();\n String uploadedFileID = fileInfoJSON.get(\"id\").asString();\n\n BoxFile uploadedFile = new BoxFile(getAPI(), uploadedFileID);\n return uploadedFile.new Info(fileInfoJSON);\n }", "public static <T, C extends Comparable<? super C>> List<T> sortInplaceBy(List<T> list,\n\t\t\tfinal Functions.Function1<? super T, C> key) {\n\t\tif (key == null)\n\t\t\tthrow new NullPointerException(\"key\");\n\t\tCollections.sort(list, new KeyComparator<T, C>(key));\n\t\treturn list;\n\t}", "public Tree determineHead(Tree t, Tree parent) {\r\n if (nonTerminalInfo == null) {\r\n throw new RuntimeException(\"Classes derived from AbstractCollinsHeadFinder must\" + \" create and fill HashMap nonTerminalInfo.\");\r\n }\r\n if (t == null || t.isLeaf()) {\r\n return null;\r\n }\r\n if (DEBUG) {\r\n System.err.println(\"determineHead for \" + t.value());\r\n }\r\n \r\n Tree[] kids = t.children();\r\n\r\n Tree theHead;\r\n // first check if subclass found explicitly marked head\r\n if ((theHead = findMarkedHead(t)) != null) {\r\n if (DEBUG) {\r\n System.err.println(\"Find marked head method returned \" +\r\n theHead.label() + \" as head of \" + t.label());\r\n }\r\n return theHead;\r\n }\r\n\r\n // if the node is a unary, then that kid must be the head\r\n // it used to special case preterminal and ROOT/TOP case\r\n // but that seemed bad (especially hardcoding string \"ROOT\")\r\n if (kids.length == 1) {\r\n if (DEBUG) {\r\n System.err.println(\"Only one child determines \" +\r\n kids[0].label() + \" as head of \" + t.label());\r\n }\r\n return kids[0];\r\n }\r\n\r\n return determineNonTrivialHead(t, parent);\r\n }" ]
Entry point for processing saved view state. @param file project file @param varData view state var data @param fixedData view state fixed data @throws IOException
[ "public void process(ProjectFile file, Var2Data varData, byte[] fixedData) throws IOException\n {\n Props props = getProps(varData);\n //System.out.println(props);\n if (props != null)\n {\n String viewName = MPPUtility.removeAmpersands(props.getUnicodeString(VIEW_NAME));\n byte[] listData = props.getByteArray(VIEW_CONTENTS);\n List<Integer> uniqueIdList = new LinkedList<Integer>();\n if (listData != null)\n {\n for (int index = 0; index < listData.length; index += 4)\n {\n Integer uniqueID = Integer.valueOf(MPPUtility.getInt(listData, index));\n\n //\n // Ensure that we have a valid task, and that if we have and\n // ID of zero, this is the first task shown.\n //\n if (file.getTaskByUniqueID(uniqueID) != null && (uniqueID.intValue() != 0 || index == 0))\n {\n uniqueIdList.add(uniqueID);\n }\n }\n }\n\n int filterID = MPPUtility.getShort(fixedData, 128);\n\n ViewState state = new ViewState(file, viewName, uniqueIdList, filterID);\n file.getViews().setViewState(state);\n }\n }" ]
[ "@Override\r\n public void onBrowserEvent(Event event) {\r\n\r\n super.onBrowserEvent(event);\r\n\r\n switch (DOM.eventGetType(event)) {\r\n case Event.ONMOUSEUP:\r\n Event.releaseCapture(m_slider.getElement());\r\n m_capturedMouse = false;\r\n break;\r\n case Event.ONMOUSEDOWN:\r\n Event.setCapture(m_slider.getElement());\r\n m_capturedMouse = true;\r\n //$FALL-THROUGH$\r\n case Event.ONMOUSEMOVE:\r\n if (m_capturedMouse) {\r\n event.preventDefault();\r\n float x = ((event.getClientX() - (m_colorUnderlay.getAbsoluteLeft())) + Window.getScrollLeft());\r\n float y = ((event.getClientY() - (m_colorUnderlay.getAbsoluteTop())) + Window.getScrollTop());\r\n\r\n if (m_parent != null) {\r\n m_parent.onMapSelected(x, y);\r\n }\r\n\r\n setSliderPosition(x, y);\r\n }\r\n //$FALL-THROUGH$\r\n default:\r\n\r\n }\r\n }", "private void populateUserDefinedFieldValues(String tableName, FieldTypeClass type, FieldContainer container, Integer uniqueID)\n {\n Map<Integer, List<Row>> tableData = m_udfValues.get(tableName);\n if (tableData != null)\n {\n List<Row> udf = tableData.get(uniqueID);\n if (udf != null)\n {\n for (Row r : udf)\n {\n addUDFValue(type, container, r);\n }\n }\n }\n }", "public Replication targetOauth(String consumerSecret, String consumerKey, String tokenSecret,\n String token) {\n targetOauth = new JsonObject();\n this.consumerSecret = consumerSecret;\n this.consumerKey = consumerKey;\n this.tokenSecret = tokenSecret;\n this.token = token;\n return this;\n }", "public void createEnablement() {\n GlobalEnablementBuilder builder = beanManager.getServices().get(GlobalEnablementBuilder.class);\n ModuleEnablement enablement = builder.createModuleEnablement(this);\n beanManager.setEnabled(enablement);\n\n if (BootstrapLogger.LOG.isDebugEnabled()) {\n BootstrapLogger.LOG.enabledAlternatives(this.beanManager, WeldCollections.toMultiRowString(enablement.getAllAlternatives()));\n BootstrapLogger.LOG.enabledDecorators(this.beanManager, WeldCollections.toMultiRowString(enablement.getDecorators()));\n BootstrapLogger.LOG.enabledInterceptors(this.beanManager, WeldCollections.toMultiRowString(enablement.getInterceptors()));\n }\n }", "public T withLabel(String text, String languageCode) {\n\t\twithLabel(factory.getMonolingualTextValue(text, languageCode));\n\t\treturn getThis();\n\t}", "private Map<String, Criteria> getCriterias(Map<String, String[]> params) {\n Map<String, Criteria> result = new HashMap<String, Criteria>();\n for (Map.Entry<String, String[]> param : params.entrySet()) {\n for (Criteria criteria : FILTER_CRITERIAS) {\n if (criteria.getName().equals(param.getKey())) {\n try {\n Criteria[] parsedCriterias = criteria.parseValue(param.getValue()[0]);\n for (Criteria parsedCriteria : parsedCriterias) {\n result.put(parsedCriteria.getName(), parsedCriteria);\n }\n } catch (Exception e) {\n // Exception happened during paring\n LOG.log(Level.SEVERE, \"Error parsing parameter \" + param.getKey(), e);\n }\n break;\n }\n }\n }\n return result;\n }", "public static void mergeHints(InputStream is, Map<String,List<Long>> hints) throws IOException {\n final BufferedReader reader = new BufferedReader(\n new InputStreamReader(is, Charsets.UTF_8));\n \n String line;\n while ((line = reader.readLine()) != null) {\n line = line.trim();\n if (line.isEmpty() || line.startsWith(\"#\"))\n continue;\n\n final int equals = line.indexOf('=');\n if (equals <= 0) {\n throw new IOException(\"No '=' character on a non-comment line?: \" + line);\n } else {\n String key = line.substring(0, equals);\n List<Long> values = hints.get(key);\n if (values == null) {\n hints.put(key, values = new ArrayList<>());\n }\n for (String v : line.substring(equals + 1).split(\"[\\\\,]\")) {\n if (!v.isEmpty()) values.add(Long.parseLong(v));\n }\n }\n }\n }", "public static void validateUserStoreNamesOnNode(AdminClient adminClient,\n Integer nodeId,\n List<String> storeNames) {\n List<StoreDefinition> storeDefList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId)\n .getValue();\n Map<String, Boolean> existingStoreNames = new HashMap<String, Boolean>();\n for(StoreDefinition storeDef: storeDefList) {\n existingStoreNames.put(storeDef.getName(), true);\n }\n for(String storeName: storeNames) {\n if(!Boolean.TRUE.equals(existingStoreNames.get(storeName))) {\n Utils.croak(\"Store \" + storeName + \" does not exist!\");\n }\n }\n }", "public synchronized int getPartitionStoreMoves() {\n int count = 0;\n for (List<Integer> entry : storeToPartitionIds.values())\n count += entry.size();\n return count;\n }" ]
Provide array of String results from inputOutput MFString field named url. @array saved in valueDestination
[ "public String[] getUrl() {\n String[] valueDestination = new String[ url.size() ];\n this.url.getValue(valueDestination);\n return valueDestination;\n }" ]
[ "@SuppressWarnings(\"unchecked\")\n public List<Field> getValueAsList() {\n return (List<Field>) type.convert(getValue(), Type.LIST);\n }", "public void leave(String groupId, Boolean deletePhotos) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LEAVE);\r\n parameters.put(\"group_id\", groupId);\r\n parameters.put(\"delete_photos\", deletePhotos);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "public static <T, U extends Closeable> T withCloseable(U self, @ClosureParams(value=FirstParam.class) Closure<T> action) throws IOException {\n try {\n T result = action.call(self);\n\n Closeable temp = self;\n self = null;\n temp.close();\n\n return result;\n } finally {\n DefaultGroovyMethodsSupport.closeWithWarning(self);\n }\n }", "public static void dumpClusterToFile(String outputDirName, String fileName, Cluster cluster) {\n\n if(outputDirName != null) {\n File outputDir = new File(outputDirName);\n if(!outputDir.exists()) {\n Utils.mkdirs(outputDir);\n }\n\n try {\n FileUtils.writeStringToFile(new File(outputDirName, fileName),\n new ClusterMapper().writeCluster(cluster));\n } catch(IOException e) {\n logger.error(\"IOException during dumpClusterToFile: \" + e);\n }\n }\n }", "public JavadocComment toComment(String indentation) {\n for (char c : indentation.toCharArray()) {\n if (!Character.isWhitespace(c)) {\n throw new IllegalArgumentException(\"The indentation string should be composed only by whitespace characters\");\n }\n }\n StringBuilder sb = new StringBuilder();\n sb.append(EOL);\n final String text = toText();\n if (!text.isEmpty()) {\n for (String line : text.split(EOL)) {\n sb.append(indentation);\n sb.append(\" * \");\n sb.append(line);\n sb.append(EOL);\n }\n }\n sb.append(indentation);\n sb.append(\" \");\n return new JavadocComment(sb.toString());\n }", "private void setTempoMaster(DeviceUpdate newMaster) {\n DeviceUpdate oldMaster = tempoMaster.getAndSet(newMaster);\n if ((newMaster == null && oldMaster != null) ||\n (newMaster != null && ((oldMaster == null) || !newMaster.getAddress().equals(oldMaster.getAddress())))) {\n // This is a change in master, so report it to any registered listeners\n deliverMasterChangedAnnouncement(newMaster);\n }\n }", "public static String transformXPath(String originalXPath)\n {\n // use a list to maintain the multiple joined xqueries (if there are multiple queries joined with the \"|\" operator)\n List<StringBuilder> compiledXPaths = new ArrayList<>(1);\n\n int frameIdx = -1;\n boolean inQuote = false;\n int conditionLevel = 0;\n char startQuoteChar = 0;\n StringBuilder currentXPath = new StringBuilder();\n compiledXPaths.add(currentXPath);\n for (int i = 0; i < originalXPath.length(); i++)\n {\n char curChar = originalXPath.charAt(i);\n if (!inQuote && curChar == '[')\n {\n frameIdx++;\n conditionLevel++;\n currentXPath.append(\"[windup:startFrame(\").append(frameIdx).append(\") and windup:evaluate(\").append(frameIdx).append(\", \");\n }\n else if (!inQuote && curChar == ']')\n {\n conditionLevel--;\n currentXPath.append(\")]\");\n }\n else if (!inQuote && conditionLevel == 0 && curChar == '|')\n {\n // joining multiple xqueries\n currentXPath = new StringBuilder();\n compiledXPaths.add(currentXPath);\n }\n else\n {\n if (inQuote && curChar == startQuoteChar)\n {\n inQuote = false;\n startQuoteChar = 0;\n }\n else if (curChar == '\"' || curChar == '\\'')\n {\n inQuote = true;\n startQuoteChar = curChar;\n }\n\n if (!inQuote && originalXPath.startsWith(WINDUP_MATCHES_FUNCTION_PREFIX, i))\n {\n i += (WINDUP_MATCHES_FUNCTION_PREFIX.length() - 1);\n currentXPath.append(\"windup:matches(\").append(frameIdx).append(\", \");\n }\n else\n {\n currentXPath.append(curChar);\n }\n }\n }\n\n Pattern leadingAndTrailingWhitespace = Pattern.compile(\"(\\\\s*)(.*?)(\\\\s*)\");\n StringBuilder finalResult = new StringBuilder();\n for (StringBuilder compiledXPath : compiledXPaths)\n {\n if (StringUtils.isNotBlank(compiledXPath))\n {\n Matcher whitespaceMatcher = leadingAndTrailingWhitespace.matcher(compiledXPath);\n if (!whitespaceMatcher.matches())\n continue;\n\n compiledXPath = new StringBuilder();\n compiledXPath.append(whitespaceMatcher.group(1));\n compiledXPath.append(whitespaceMatcher.group(2));\n compiledXPath.append(\"/self::node()[windup:persist(\").append(frameIdx).append(\", \").append(\".)]\");\n compiledXPath.append(whitespaceMatcher.group(3));\n\n if (StringUtils.isNotBlank(finalResult))\n finalResult.append(\"|\");\n finalResult.append(compiledXPath);\n }\n }\n return finalResult.toString();\n }", "public void setModel(Database databaseModel, DescriptorRepository objModel)\r\n {\r\n _dbModel = databaseModel;\r\n _preparedModel = new PreparedModel(objModel, databaseModel);\r\n }", "private void readExceptionDay(ProjectCalendar mpxjCalendar, ExceptedDay day)\n {\n ProjectCalendarException mpxjException = mpxjCalendar.addCalendarException(day.getDate(), day.getDate());\n if (day.isIsDayWorking())\n {\n for (Document.Calendars.Calendar.ExceptedDays.ExceptedDay.TimePeriods.TimePeriod period : day.getTimePeriods().getTimePeriod())\n {\n mpxjException.addRange(new DateRange(period.getFrom(), period.getTo()));\n }\n }\n }" ]
Process StepFinishedEvent. Change last added to stepStorage step and add it as child of previous step. @param event to process
[ "public void fire(StepFinishedEvent event) {\n Step step = stepStorage.adopt();\n event.process(step);\n\n notifier.fire(event);\n }" ]
[ "private String formatUnits(Number value)\n {\n return (value == null ? null : m_formats.getUnitsDecimalFormat().format(value.doubleValue() / 100));\n }", "public void actionPerformed(java.awt.event.ActionEvent actionEvent)\r\n {\r\n new Thread()\r\n {\r\n public void run()\r\n {\r\n final java.sql.Connection conn = new JDlgDBConnection(containingFrame, false).showAndReturnConnection();\r\n if (conn != null)\r\n {\r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n JIFrmDatabase frm = new JIFrmDatabase(conn);\r\n containingFrame.getContentPane().add(frm);\r\n frm.setVisible(true);\r\n }\r\n });\r\n }\r\n }\r\n }.start();\r\n }", "public static <E> void retainAll(Collection<E> elems, Filter<? super E> filter) {\r\n for (Iterator<E> iter = elems.iterator(); iter.hasNext();) {\r\n E elem = iter.next();\r\n if ( ! filter.accept(elem)) {\r\n iter.remove();\r\n }\r\n }\r\n }", "public AsciiTable setPaddingTopChar(Character paddingTopChar) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingTopChar(paddingTopChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "private void initManagementPart() {\n\n m_manageExceptionsButton.setText(Messages.get().key(Messages.GUI_SERIALDATE_BUTTON_MANAGE_EXCEPTIONS_0));\n m_manageExceptionsButton.getElement().getStyle().setFloat(Style.Float.RIGHT);\n }", "protected AbstractColumn buildExpressionColumn() {\n\t\tExpressionColumn column = new ExpressionColumn();\n\t\tpopulateCommonAttributes(column);\n\t\t\n\t\tpopulateExpressionAttributes(column);\n\t\t\n\t\tcolumn.setExpression(customExpression);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setExpressionForCalculation(customExpressionForCalculation);\n\t\t\n\t\treturn column;\n\t}", "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 GroovyFieldDoc[] enumConstants() {\n Collections.sort(enumConstants);\n return enumConstants.toArray(new GroovyFieldDoc[enumConstants.size()]);\n }", "public static ComplexNumber Tan(ComplexNumber z1) {\r\n ComplexNumber result = new ComplexNumber();\r\n\r\n if (z1.imaginary == 0.0) {\r\n result.real = Math.tan(z1.real);\r\n result.imaginary = 0.0;\r\n } else {\r\n double real2 = 2 * z1.real;\r\n double imag2 = 2 * z1.imaginary;\r\n double denom = Math.cos(real2) + Math.cosh(real2);\r\n\r\n result.real = Math.sin(real2) / denom;\r\n result.imaginary = Math.sinh(imag2) / denom;\r\n }\r\n\r\n return result;\r\n }" ]
Save a SVG graphic to the given path. @param graphics2d The SVG graphic to save. @param path The file.
[ "public static void saveSvgFile(final SVGGraphics2D graphics2d, final File path) throws IOException {\n try (FileOutputStream fs = new FileOutputStream(path);\n OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fs, StandardCharsets.UTF_8);\n Writer osw = new BufferedWriter(outputStreamWriter)\n ) {\n graphics2d.stream(osw, true);\n }\n }" ]
[ "public static String formatTimeISO8601(TimeValue value) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tDecimalFormat yearForm = new DecimalFormat(FORMAT_YEAR);\n\t\tDecimalFormat timeForm = new DecimalFormat(FORMAT_OTHER);\n\t\tif (value.getYear() > 0) {\n\t\t\tbuilder.append(\"+\");\n\t\t}\n\t\tbuilder.append(yearForm.format(value.getYear()));\n\t\tbuilder.append(\"-\");\n\t\tbuilder.append(timeForm.format(value.getMonth()));\n\t\tbuilder.append(\"-\");\n\t\tbuilder.append(timeForm.format(value.getDay()));\n\t\tbuilder.append(\"T\");\n\t\tbuilder.append(timeForm.format(value.getHour()));\n\t\tbuilder.append(\":\");\n\t\tbuilder.append(timeForm.format(value.getMinute()));\n\t\tbuilder.append(\":\");\n\t\tbuilder.append(timeForm.format(value.getSecond()));\n\t\tbuilder.append(\"Z\");\n\t\treturn builder.toString();\n\t}", "public Iterable<BoxRetentionPolicyAssignment.Info> getEnterpriseAssignments(int limit, String ... fields) {\r\n return this.getAssignments(BoxRetentionPolicyAssignment.TYPE_ENTERPRISE, limit, fields);\r\n }", "public Collection getReaders(Object obj)\r\n {\r\n \tcheckTimedOutLocks();\r\n Identity oid = new Identity(obj,getBroker());\r\n return getReaders(oid);\r\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 }", "private void writeProperties() throws IOException\n {\n writeAttributeTypes(\"property_types\", ProjectField.values());\n writeFields(\"property_values\", m_projectFile.getProjectProperties(), ProjectField.values());\n }", "public PhotoList<Photo> getContactsPublicPhotos(String userId, int count, boolean justFriends, boolean singlePhoto, boolean includeSelf)\r\n throws FlickrException {\r\n return getContactsPublicPhotos(userId, Extras.MIN_EXTRAS, count, justFriends, singlePhoto, includeSelf);\r\n }", "private void processQueue()\r\n {\r\n CacheEntry sv;\r\n while((sv = (CacheEntry) queue.poll()) != null)\r\n {\r\n sessionCache.remove(sv.oid);\r\n }\r\n }", "public static int randomIntBetween(int min, int max) {\n Random rand = new Random();\n return rand.nextInt((max - min) + 1) + min;\n }", "public void log(Level level, Throwable throwable, String msg, Object[] argArray) {\n\t\tlogIfEnabled(level, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);\n\t}" ]
Collects all the fields from columns and also the fields not bounds to columns @return List<ColumnProperty>
[ "public List<ColumnProperty> getAllFields(){\n\t\tArrayList<ColumnProperty> l = new ArrayList<ColumnProperty>();\n\t\tfor (AbstractColumn abstractColumn : this.getColumns()) {\n\t\t\tif (abstractColumn instanceof SimpleColumn && !(abstractColumn instanceof ExpressionColumn)) {\n\t\t\t\tl.add(((SimpleColumn)abstractColumn).getColumnProperty());\n\t\t\t}\n\t\t}\n\t\tl.addAll(this.getFields());\n\n\t\treturn l;\n\t\t\n\t}" ]
[ "public static Method findGetMethod(Field field, DatabaseType databaseType, boolean throwExceptions)\n\t\t\tthrows IllegalArgumentException {\n\t\tMethod fieldGetMethod = findMethodFromNames(field, true, throwExceptions,\n\t\t\t\tmethodFromField(field, \"get\", databaseType, true), methodFromField(field, \"get\", databaseType, false),\n\t\t\t\tmethodFromField(field, \"is\", databaseType, true), methodFromField(field, \"is\", databaseType, false));\n\t\tif (fieldGetMethod == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (fieldGetMethod.getReturnType() != field.getType()) {\n\t\t\tif (throwExceptions) {\n\t\t\t\tthrow new IllegalArgumentException(\"Return type of get method \" + fieldGetMethod.getName()\n\t\t\t\t\t\t+ \" does not return \" + field.getType());\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn fieldGetMethod;\n\t}", "void endIfStarted(CodeAttribute b, ClassMethod method) {\n b.aload(getLocalVariableIndex(0));\n b.dup();\n final BranchEnd ifnotnull = b.ifnull();\n b.checkcast(Stack.class);\n b.invokevirtual(Stack.class.getName(), END_INTERCEPTOR_CONTEXT_METHOD_NAME, EMPTY_PARENTHESES + VOID_CLASS_DESCRIPTOR);\n BranchEnd ifnull = b.gotoInstruction();\n b.branchEnd(ifnotnull);\n b.pop(); // remove null Stack\n b.branchEnd(ifnull);\n }", "@SuppressWarnings(\"unused\")\n public static void changeCredentials(String accountID, String token) {\n changeCredentials(accountID, token, null);\n }", "public void setBodyFilter(int pathId, String bodyFilter) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_BODY_FILTER + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, bodyFilter);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "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 }", "@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public List<HazeltaskTask<G>> shutdownNow() {\n\t return (List<HazeltaskTask<G>>) (List) localExecutorPool.shutdownNow();\n\t}", "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 }", "public MapBounds getRotatedBounds(final Rectangle2D.Double paintAreaPrecise, final Rectangle paintArea) {\n final MapBounds rotatedBounds = this.getRotatedBounds();\n\n if (rotatedBounds instanceof CenterScaleMapBounds) {\n return rotatedBounds;\n }\n\n final ReferencedEnvelope envelope = ((BBoxMapBounds) rotatedBounds).toReferencedEnvelope(null);\n // the paint area size and the map bounds are rotated independently. because\n // the paint area size is rounded to integers, the map bounds have to be adjusted\n // to these rounding changes.\n final double widthRatio = paintArea.getWidth() / paintAreaPrecise.getWidth();\n final double heightRatio = paintArea.getHeight() / paintAreaPrecise.getHeight();\n\n final double adaptedWidth = envelope.getWidth() * widthRatio;\n final double adaptedHeight = envelope.getHeight() * heightRatio;\n\n final double widthDiff = adaptedWidth - envelope.getWidth();\n final double heigthDiff = adaptedHeight - envelope.getHeight();\n envelope.expandBy(widthDiff / 2.0, heigthDiff / 2.0);\n\n return new BBoxMapBounds(envelope);\n }", "public static base_response update(nitro_service client, transformpolicy resource) throws Exception {\n\t\ttransformpolicy updateresource = new transformpolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.rule = resource.rule;\n\t\tupdateresource.profilename = resource.profilename;\n\t\tupdateresource.comment = resource.comment;\n\t\tupdateresource.logaction = resource.logaction;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Return the List of Arguments for the specified MethodCallExpression or a ConstructorCallExpression. The returned List contains either ConstantExpression or MapEntryExpression objects. @param methodCall - the AST MethodCallExpression or ConstructorCalLExpression @return the List of argument objects
[ "public static List<? extends Expression> getMethodArguments(ASTNode methodCall) {\r\n if (methodCall instanceof ConstructorCallExpression) {\r\n return extractExpressions(((ConstructorCallExpression) methodCall).getArguments());\r\n } else if (methodCall instanceof MethodCallExpression) {\r\n return extractExpressions(((MethodCallExpression) methodCall).getArguments());\r\n } else if (methodCall instanceof StaticMethodCallExpression) {\r\n return extractExpressions(((StaticMethodCallExpression) methodCall).getArguments());\r\n } else if (respondsTo(methodCall, \"getArguments\")) {\r\n throw new RuntimeException(); // TODO: remove, should never happen\r\n }\r\n return new ArrayList<Expression>();\r\n }" ]
[ "public static ConsistencyLevel determineConsistency(Map<Value, Set<ClusterNode>> versionNodeSetMap,\n int replicationFactor) {\n boolean fullyConsistent = true;\n Value latestVersion = null;\n for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : versionNodeSetMap.entrySet()) {\n Value value = versionNodeSetEntry.getKey();\n if (latestVersion == null) {\n latestVersion = value;\n } else if (value.isTimeStampLaterThan(latestVersion)) {\n latestVersion = value;\n }\n Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue();\n fullyConsistent = fullyConsistent && (nodeSet.size() == replicationFactor);\n }\n if (fullyConsistent) {\n return ConsistencyLevel.FULL;\n } else {\n // latest write consistent, effectively consistent\n if (latestVersion != null && versionNodeSetMap.get(latestVersion).size() == replicationFactor) {\n return ConsistencyLevel.LATEST_CONSISTENT;\n }\n // all other states inconsistent\n return ConsistencyLevel.INCONSISTENT;\n }\n }", "public byte[] getByteArray(Integer offset)\n {\n byte[] result = null;\n\n if (offset != null)\n {\n result = m_map.get(offset);\n }\n\n return (result);\n }", "public void print( String equation ) {\n // first assume it's just a variable\n Variable v = lookupVariable(equation);\n if( v == null ) {\n Sequence sequence = compile(equation,false,false);\n sequence.perform();\n v = sequence.output;\n }\n\n if( v instanceof VariableMatrix ) {\n ((VariableMatrix)v).matrix.print();\n } else if(v instanceof VariableScalar ) {\n System.out.println(\"Scalar = \"+((VariableScalar)v).getDouble() );\n } else {\n System.out.println(\"Add support for \"+v.getClass().getSimpleName());\n }\n }", "private static int getColumnWidth(final PropertyDescriptor _property) {\n final Class type = _property.getPropertyType();\n if (Float.class.isAssignableFrom(type) || Double.class.isAssignableFrom(type)) {\n return 70;\n } else if (type == Boolean.class) {\n return 10;\n } else if (Number.class.isAssignableFrom(type)) {\n return 60;\n } else if (type == String.class) {\n return 100;\n } else if (Date.class.isAssignableFrom(type)) {\n return 50;\n } else {\n return 50;\n }\n }", "public static double fastNormP2( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return fastNormF(A);\n } else {\n return inducedP2(A);\n }\n }", "public CollectionRequest<Story> findByTask(String task) {\n \n String path = String.format(\"/tasks/%s/stories\", task);\n return new CollectionRequest<Story>(this, Story.class, path, \"GET\");\n }", "public static nspbr6[] get(nitro_service service, nspbr6_args args) throws Exception{\n\t\tnspbr6 obj = new nspbr6();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tnspbr6[] response = (nspbr6[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "protected TableFontStyle getColumnFontStyle(byte[] data, int offset, Map<Integer, FontBase> fontBases)\n {\n int uniqueID = MPPUtility.getInt(data, offset);\n FieldType fieldType = MPPTaskField.getInstance(MPPUtility.getShort(data, offset + 4));\n Integer index = Integer.valueOf(MPPUtility.getByte(data, offset + 8));\n int style = MPPUtility.getByte(data, offset + 9);\n ColorType color = ColorType.getInstance(MPPUtility.getByte(data, offset + 10));\n int change = MPPUtility.getByte(data, offset + 12);\n\n FontBase fontBase = fontBases.get(index);\n\n boolean bold = ((style & 0x01) != 0);\n boolean italic = ((style & 0x02) != 0);\n boolean underline = ((style & 0x04) != 0);\n\n boolean boldChanged = ((change & 0x01) != 0);\n boolean underlineChanged = ((change & 0x02) != 0);\n boolean italicChanged = ((change & 0x04) != 0);\n boolean colorChanged = ((change & 0x08) != 0);\n boolean fontChanged = ((change & 0x10) != 0);\n boolean backgroundColorChanged = (uniqueID == -1);\n boolean backgroundPatternChanged = (uniqueID == -1);\n\n return (new TableFontStyle(uniqueID, fieldType, fontBase, italic, bold, underline, false, color.getColor(), Color.BLACK, BackgroundPattern.TRANSPARENT, italicChanged, boldChanged, underlineChanged, false, colorChanged, fontChanged, backgroundColorChanged, backgroundPatternChanged));\n }", "public synchronized GeoInterface getGeoInterface() {\r\n if (geoInterface == null) {\r\n geoInterface = new GeoInterface(apiKey, sharedSecret, transport);\r\n }\r\n return geoInterface;\r\n }" ]
End building the script @param config the configuration for the script to build @return the new {@link LuaScript} instance
[ "public LuaScript endScript(LuaScriptConfig config) {\n if (!endsWithReturnStatement()) {\n add(new LuaAstReturnStatement());\n }\n String scriptText = buildScriptText();\n return new BasicLuaScript(scriptText, config);\n }" ]
[ "protected final Event processEvent() throws IOException {\n while (true) {\n String line;\n try {\n line = readLine();\n } catch (final EOFException ex) {\n if (doneOnce) {\n throw ex;\n }\n doneOnce = true;\n line = \"\";\n }\n\n // If the line is empty (a blank line), Dispatch the event, as defined below.\n if (line.isEmpty()) {\n // If the data buffer is an empty string, set the data buffer and the event name buffer to\n // the empty string and abort these steps.\n if (dataBuffer.length() == 0) {\n eventName = \"\";\n continue;\n }\n\n // If the event name buffer is not the empty string but is also not a valid NCName,\n // set the data buffer and the event name buffer to the empty string and abort these steps.\n // NOT IMPLEMENTED\n\n final Event.Builder eventBuilder = new Event.Builder();\n eventBuilder.withEventName(eventName.isEmpty() ? Event.MESSAGE_EVENT : eventName);\n eventBuilder.withData(dataBuffer.toString());\n\n // Set the data buffer and the event name buffer to the empty string.\n dataBuffer = new StringBuilder();\n eventName = \"\";\n\n return eventBuilder.build();\n // If the line starts with a U+003A COLON character (':')\n } else if (line.startsWith(\":\")) {\n // ignore the line\n // If the line contains a U+003A COLON character (':') character\n } else if (line.contains(\":\")) {\n // Collect the characters on the line before the first U+003A COLON character (':'),\n // and let field be that string.\n final int colonIdx = line.indexOf(\":\");\n final String field = line.substring(0, colonIdx);\n\n // Collect the characters on the line after the first U+003A COLON character (':'),\n // and let value be that string.\n // If value starts with a single U+0020 SPACE character, remove it from value.\n String value = line.substring(colonIdx + 1);\n value = value.startsWith(\" \") ? value.substring(1) : value;\n\n processField(field, value);\n // Otherwise, the string is not empty but does not contain a U+003A COLON character (':')\n // character\n } else {\n processField(line, \"\");\n }\n }\n }", "public boolean isEmpty() {\n\t\tint snapshotSize = cleared ? 0 : snapshot.size();\n\t\t//nothing in both\n\t\tif ( snapshotSize == 0 && currentState.isEmpty() ) {\n\t\t\treturn true;\n\t\t}\n\t\t//snapshot bigger than changeset\n\t\tif ( snapshotSize > currentState.size() ) {\n\t\t\treturn false;\n\t\t}\n\t\treturn size() == 0;\n\t}", "public static final String printResourceType(ResourceType value)\n {\n return (Integer.toString(value == null ? ResourceType.WORK.getValue() : value.getValue()));\n }", "public static appflowglobal_binding get(nitro_service service) throws Exception{\n\t\tappflowglobal_binding obj = new appflowglobal_binding();\n\t\tappflowglobal_binding response = (appflowglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "private static double arcAngle(Point center, Point a, Point b, Rect area, int radius) {\n double angle = threePointsAngle(center, a, b);\n Point innerPoint = findMidnormalPoint(center, a, b, area, radius);\n Point midInsectPoint = new Point((a.x + b.x) / 2, (a.y + b.y) / 2);\n double distance = pointsDistance(midInsectPoint, innerPoint);\n if (distance > radius) {\n return 360 - angle;\n }\n return angle;\n }", "protected Element createPageElement()\n {\n String pstyle = \"\";\n PDRectangle layout = getCurrentMediaBox();\n if (layout != null)\n {\n /*System.out.println(\"x1 \" + layout.getLowerLeftX());\n System.out.println(\"y1 \" + layout.getLowerLeftY());\n System.out.println(\"x2 \" + layout.getUpperRightX());\n System.out.println(\"y2 \" + layout.getUpperRightY());\n System.out.println(\"rot \" + pdpage.findRotation());*/\n \n float w = layout.getWidth();\n float h = layout.getHeight();\n final int rot = pdpage.getRotation();\n if (rot == 90 || rot == 270)\n {\n float x = w; w = h; h = x;\n }\n \n pstyle = \"width:\" + w + UNIT + \";\" + \"height:\" + h + UNIT + \";\";\n pstyle += \"overflow:hidden;\";\n }\n else\n log.warn(\"No media box found\");\n \n Element el = doc.createElement(\"div\");\n el.setAttribute(\"id\", \"page_\" + (pagecnt++));\n el.setAttribute(\"class\", \"page\");\n el.setAttribute(\"style\", pstyle);\n return el;\n }", "public void reinitIfClosed() {\n if (isClosed.get()) {\n logger.info(\"External Resource was released. Now Re-initializing resources ...\");\n\n ActorConfig.createAndGetActorSystem();\n httpClientStore.reinit();\n tcpSshPingResourceStore.reinit();\n try {\n Thread.sleep(1000l);\n } catch (InterruptedException e) {\n logger.error(\"error reinit httpClientStore\", e);\n }\n isClosed.set(false);\n logger.info(\"Parallel Client Resources has been reinitialized.\");\n } else {\n logger.debug(\"NO OP. Resource was not released.\");\n }\n }", "public static String entityToString(HttpEntity entity) throws IOException {\n if (entity != null) {\n InputStream is = entity.getContent();\n return IOUtils.toString(is, \"UTF-8\");\n }\n return \"\";\n }", "public boolean addDescriptor() {\n\n saveLocalization();\n IndexedContainer oldContainer = m_container;\n try {\n createAndLockDescriptorFile();\n unmarshalDescriptor();\n updateBundleDescriptorContent();\n m_hasMasterMode = true;\n m_container = createContainer();\n m_editorState.put(EditMode.DEFAULT, getDefaultState());\n m_editorState.put(EditMode.MASTER, getMasterState());\n } catch (CmsException | IOException e) {\n LOG.error(e.getLocalizedMessage(), e);\n if (m_descContent != null) {\n m_descContent = null;\n }\n if (m_descFile != null) {\n m_descFile = null;\n }\n if (m_desc != null) {\n try {\n m_cms.deleteResource(m_desc, CmsResourceDeleteMode.valueOf(1));\n } catch (CmsException ex) {\n LOG.error(ex.getLocalizedMessage(), ex);\n }\n m_desc = null;\n }\n m_hasMasterMode = false;\n m_container = oldContainer;\n return false;\n }\n m_removeDescriptorOnCancel = true;\n return true;\n }" ]
replaces the old with the new item. The new item will not be added when the old one is not found. @param oldObject will be removed @param newObject is added only when hte old item is removed
[ "public void replaceItem(@NonNull final T oldObject, @NonNull final T newObject) {\n synchronized (mLock) {\n final int position = getPosition(oldObject);\n if (position == -1) {\n // not found, don't replace\n return;\n }\n\n mObjects.remove(position);\n mObjects.add(position, newObject);\n\n if (isItemTheSame(oldObject, newObject)) {\n if (isContentTheSame(oldObject, newObject)) {\n // visible content hasn't changed, don't notify\n return;\n }\n\n // item with same stable id has changed\n notifyItemChanged(position, newObject);\n } else {\n // item replaced with another one with a different id\n notifyItemRemoved(position);\n notifyItemInserted(position);\n }\n }\n }" ]
[ "public static Class<?> loadClass(String className, ClassLoader cl) {\n try {\n return Class.forName(className, false, cl);\n } catch(ClassNotFoundException e) {\n throw new IllegalArgumentException(e);\n }\n }", "protected void addRow(int uniqueID, Map<String, Object> map)\n {\n m_rows.put(Integer.valueOf(uniqueID), new MapRow(map));\n }", "public Duration getWorkVariance()\n {\n Duration variance = (Duration) getCachedValue(ResourceField.WORK_VARIANCE);\n if (variance == null)\n {\n Duration work = getWork();\n Duration baselineWork = getBaselineWork();\n if (work != null && baselineWork != null)\n {\n variance = Duration.getInstance(work.getDuration() - baselineWork.convertUnits(work.getUnits(), getParentFile().getProjectProperties()).getDuration(), work.getUnits());\n set(ResourceField.WORK_VARIANCE, variance);\n }\n }\n return (variance);\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 }", "private void readTask(ChildTaskContainer mpxjParent, net.sf.mpxj.ganttproject.schema.Task gpTask)\n {\n Task mpxjTask = mpxjParent.addTask();\n mpxjTask.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpTask.getId()) + 1));\n mpxjTask.setName(gpTask.getName());\n mpxjTask.setPercentageComplete(gpTask.getComplete());\n mpxjTask.setPriority(getPriority(gpTask.getPriority()));\n mpxjTask.setHyperlink(gpTask.getWebLink());\n\n Duration duration = Duration.getInstance(NumberHelper.getDouble(gpTask.getDuration()), TimeUnit.DAYS);\n mpxjTask.setDuration(duration);\n\n if (duration.getDuration() == 0)\n {\n mpxjTask.setMilestone(true);\n }\n else\n {\n mpxjTask.setStart(gpTask.getStart());\n mpxjTask.setFinish(m_mpxjCalendar.getDate(gpTask.getStart(), mpxjTask.getDuration(), false));\n }\n\n mpxjTask.setConstraintDate(gpTask.getThirdDate());\n if (mpxjTask.getConstraintDate() != null)\n {\n // TODO: you don't appear to be able to change this setting in GanttProject\n // task.getThirdDateConstraint()\n mpxjTask.setConstraintType(ConstraintType.START_NO_EARLIER_THAN);\n }\n\n readTaskCustomFields(gpTask, mpxjTask);\n\n m_eventManager.fireTaskReadEvent(mpxjTask);\n\n // TODO: read custom values\n\n //\n // Process child tasks\n //\n for (net.sf.mpxj.ganttproject.schema.Task childTask : gpTask.getTask())\n {\n readTask(mpxjTask, childTask);\n }\n }", "protected Object[] idsOf(final List<?> idsOrValues) {\n // convert list to array that we can mutate\n final Object[] ids = idsOrValues.toArray();\n\n // mutate array to contain only non-empty ids\n int length = 0;\n for (int i = 0; i < ids.length;) {\n final Object p = ids[i++];\n if (p instanceof HasId) {\n // only use values with ids that are non-empty\n final String id = ((HasId) p).getId();\n if (!StringUtils.isEmpty(id)) {\n ids[length++] = id;\n }\n } else if (p instanceof String) {\n // only use ids that are non-empty\n final String id = p.toString();\n if (!StringUtils.isEmpty(id)) {\n ids[length++] = id;\n }\n } else if (p != null) {\n throw new StoreException(\"Invalid id or value of type \" + p);\n }\n }\n\n // no ids in array\n if (length == 0) {\n return null;\n }\n\n // some ids in array\n if (length != ids.length) {\n final Object[] tmp = new Object[length];\n System.arraycopy(ids, 0, tmp, 0, length);\n return tmp;\n }\n\n // array was full\n return ids;\n }", "public static String paramMapToString(final Map<String, String[]> parameters) {\n\n final StringBuffer result = new StringBuffer();\n for (final String key : parameters.keySet()) {\n String[] values = parameters.get(key);\n if (null == values) {\n result.append(key).append('&');\n } else {\n for (final String value : parameters.get(key)) {\n result.append(key).append('=').append(CmsEncoder.encode(value)).append('&');\n }\n }\n }\n // remove last '&'\n if (result.length() > 0) {\n result.setLength(result.length() - 1);\n }\n return result.toString();\n }", "protected final StringBuilder getBaseUrl(final HttpServletRequest httpServletRequest) {\n StringBuilder baseURL = new StringBuilder();\n if (httpServletRequest.getContextPath() != null && !httpServletRequest.getContextPath().isEmpty()) {\n baseURL.append(httpServletRequest.getContextPath());\n }\n if (httpServletRequest.getServletPath() != null && !httpServletRequest.getServletPath().isEmpty()) {\n baseURL.append(httpServletRequest.getServletPath());\n }\n return baseURL;\n }", "public static void checkEigenvalues() {\n DoubleMatrix A = new DoubleMatrix(new double[][]{\n {3.0, 2.0, 0.0},\n {2.0, 3.0, 2.0},\n {0.0, 2.0, 3.0}\n });\n\n DoubleMatrix E = new DoubleMatrix(3, 1);\n\n NativeBlas.dsyev('N', 'U', 3, A.data, 0, 3, E.data, 0);\n check(\"checking existence of dsyev...\", true);\n }" ]
Creates an element that represents a rectangle drawn at the specified coordinates in the page. @param x the X coordinate of the rectangle @param y the Y coordinate of the rectangle @param width the width of the rectangle @param height the height of the rectangle @param stroke should there be a stroke around? @param fill should the rectangle be filled? @return the resulting DOM element
[ "protected Element createRectangleElement(float x, float y, float width, float height, boolean stroke, boolean fill)\n {\n float lineWidth = transformWidth(getGraphicsState().getLineWidth());\n \tfloat wcor = stroke ? lineWidth : 0.0f;\n float strokeOffset = wcor == 0 ? 0 : wcor / 2;\n width = width - wcor < 0 ? 1 : width - wcor;\n height = height - wcor < 0 ? 1 : height - wcor;\n\n StringBuilder pstyle = new StringBuilder(50);\n \tpstyle.append(\"left:\").append(style.formatLength(x - strokeOffset)).append(';');\n pstyle.append(\"top:\").append(style.formatLength(y - strokeOffset)).append(';');\n pstyle.append(\"width:\").append(style.formatLength(width)).append(';');\n pstyle.append(\"height:\").append(style.formatLength(height)).append(';');\n \t \n \tif (stroke)\n \t{\n String color = colorString(getGraphicsState().getStrokingColor());\n \tpstyle.append(\"border:\").append(style.formatLength(lineWidth)).append(\" solid \").append(color).append(';');\n \t}\n \t\n \tif (fill)\n \t{\n String fcolor = colorString(getGraphicsState().getNonStrokingColor());\n \t pstyle.append(\"background-color:\").append(fcolor).append(';');\n \t}\n \t\n Element el = doc.createElement(\"div\");\n el.setAttribute(\"class\", \"r\");\n el.setAttribute(\"style\", pstyle.toString());\n el.appendChild(doc.createEntityReference(\"nbsp\"));\n return el;\n }" ]
[ "public void setBackgroundColor(int colorRes) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }", "public static Field getField(Class clazz, String fieldName)\r\n {\r\n try\r\n {\r\n return clazz.getField(fieldName);\r\n }\r\n catch (Exception ignored)\r\n {}\r\n return null;\r\n }", "public static String get(MessageKey key) {\n return data.getProperty(key.toString(), key.toString());\n }", "protected long preConnection() throws SQLException{\r\n\t\tlong statsObtainTime = 0;\r\n\t\t\r\n\t\tif (this.pool.poolShuttingDown){\r\n\t\t\tthrow new SQLException(this.pool.shutdownStackTrace);\r\n\t\t}\r\n\r\n\r\n\t\tif (this.pool.statisticsEnabled){\r\n\t\t\tstatsObtainTime = System.nanoTime();\r\n\t\t\tthis.pool.statistics.incrementConnectionsRequested();\r\n\t\t}\r\n\t\t\r\n\t\treturn statsObtainTime;\r\n\t}", "private void showSettingsMenu(final Cursor cursor) {\n Log.d(TAG, \"showSettingsMenu\");\n enableSettingsCursor(cursor);\n context.runOnGlThread(new Runnable() {\n @Override\n public void run() {\n new SettingsView(context, scene, CursorManager.this,\n settingsCursor.getIoDevice().getCursorControllerId(), cursor, new\n SettingsChangeListener() {\n @Override\n public void onBack(boolean cascading) {\n disableSettingsCursor();\n }\n\n @Override\n public int onDeviceChanged(IoDevice device) {\n // we are changing the io device on the settings cursor\n removeCursorFromScene(settingsCursor);\n IoDevice clickedDevice = getAvailableIoDevice(device);\n settingsCursor.setIoDevice(clickedDevice);\n addCursorToScene(settingsCursor);\n return device.getCursorControllerId();\n }\n });\n }\n });\n }", "public static ModelNode addCurrentServerGroupsToHostInfoModel(boolean ignoreUnaffectedServerGroups, Resource hostModel, ModelNode model) {\n if (!ignoreUnaffectedServerGroups) {\n return model;\n }\n model.get(IGNORE_UNUSED_CONFIG).set(ignoreUnaffectedServerGroups);\n addServerGroupsToModel(hostModel, model);\n return model;\n }", "@SuppressWarnings(\"WeakerAccess\")\n public String formatCueCountdown() {\n int count = getCueCountdown();\n\n if (count == 511) {\n return \"--.-\";\n }\n\n if ((count >= 1) && (count <= 256)) {\n int bars = (count - 1) / 4;\n int beats = ((count - 1) % 4) + 1;\n return String.format(\"%02d.%d\", bars, beats);\n }\n\n if (count == 0) {\n return \"00.0\";\n }\n\n return \"??.?\";\n }", "private void setLockingValues(ClassDescriptor cld, Object obj, ValueContainer[] oldLockingValues)\r\n {\r\n FieldDescriptor fields[] = cld.getLockingFields();\r\n\r\n for (int i=0; i<fields.length; i++)\r\n {\r\n PersistentField field = fields[i].getPersistentField();\r\n Object lockVal = oldLockingValues[i].getValue();\r\n\r\n field.set(obj, lockVal);\r\n }\r\n }", "private void writeCostRateTables(Project.Resources.Resource xml, Resource mpx)\n {\n //Rates rates = m_factory.createProjectResourcesResourceRates();\n //xml.setRates(rates);\n //List<Project.Resources.Resource.Rates.Rate> ratesList = rates.getRate();\n\n List<Project.Resources.Resource.Rates.Rate> ratesList = null;\n\n for (int tableIndex = 0; tableIndex < 5; tableIndex++)\n {\n CostRateTable table = mpx.getCostRateTable(tableIndex);\n if (table != null)\n {\n Date from = DateHelper.FIRST_DATE;\n for (CostRateTableEntry entry : table)\n {\n if (costRateTableWriteRequired(entry, from))\n {\n if (ratesList == null)\n {\n Rates rates = m_factory.createProjectResourcesResourceRates();\n xml.setRates(rates);\n ratesList = rates.getRate();\n }\n\n Project.Resources.Resource.Rates.Rate rate = m_factory.createProjectResourcesResourceRatesRate();\n ratesList.add(rate);\n\n rate.setCostPerUse(DatatypeConverter.printCurrency(entry.getCostPerUse()));\n rate.setOvertimeRate(DatatypeConverter.printRate(entry.getOvertimeRate()));\n rate.setOvertimeRateFormat(DatatypeConverter.printTimeUnit(entry.getOvertimeRateFormat()));\n rate.setRatesFrom(from);\n from = entry.getEndDate();\n rate.setRatesTo(from);\n rate.setRateTable(BigInteger.valueOf(tableIndex));\n rate.setStandardRate(DatatypeConverter.printRate(entry.getStandardRate()));\n rate.setStandardRateFormat(DatatypeConverter.printTimeUnit(entry.getStandardRateFormat()));\n }\n }\n }\n }\n }" ]
Get a value as a string. @param key the key for looking up the value. @param type the type of the object @param <V> the type
[ "public <V> V getObject(final String key, final Class<V> type) {\n final Object obj = this.values.get(key);\n return type.cast(obj);\n }" ]
[ "public boolean hasForeignkey(String name)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n ForeignkeyDef def = null;\r\n\r\n for (Iterator it = getForeignkeys(); it.hasNext();)\r\n {\r\n def = (ForeignkeyDef)it.next();\r\n if (realName.equals(def.getName()))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "private HiveShellContainer createHiveServerContainer(final List<? extends Script> scripts, final Object testCase, TemporaryFolder baseDir) \n throws IOException {\n\n HiveServerContext context = new StandaloneHiveServerContext(baseDir, config);\n\n final HiveServerContainer hiveTestHarness = new HiveServerContainer(context);\n\n HiveShellBuilder hiveShellBuilder = new HiveShellBuilder();\n hiveShellBuilder.setCommandShellEmulation(config.getCommandShellEmulator());\n\n HiveShellField shellSetter = loadScriptUnderTest(testCase, hiveShellBuilder);\n if (scripts != null) {\n hiveShellBuilder.overrideScriptsUnderTest(scripts);\n }\n\n hiveShellBuilder.setHiveServerContainer(hiveTestHarness);\n\n loadAnnotatedResources(testCase, hiveShellBuilder);\n\n loadAnnotatedProperties(testCase, hiveShellBuilder);\n\n loadAnnotatedSetupScripts(testCase, hiveShellBuilder);\n\n // Build shell\n final HiveShellContainer shell = hiveShellBuilder.buildShell();\n\n // Set shell\n shellSetter.setShell(shell);\n\n if (shellSetter.isAutoStart()) {\n shell.start();\n }\n\n return shell;\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 }", "static void undoChanges(final PatchEntry entry, final PatchContentLoader loader) {\n final List<ContentModification> modifications = new ArrayList<ContentModification>(entry.rollbackActions);\n for (final ContentModification modification : modifications) {\n final ContentItem item = modification.getItem();\n if (item.getContentType() != ContentType.MISC) {\n // Skip modules and bundles they should be removed as part of the {@link FinalizeCallback}\n continue;\n }\n final PatchingTaskDescription description = new PatchingTaskDescription(entry.applyPatchId, modification, loader, false, false, false);\n try {\n final PatchingTask task = PatchingTask.Factory.create(description, entry);\n task.execute(entry);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.failedToUndoChange(item.toString());\n }\n }\n }", "public DynamicReportBuilder setQuery(String text, String language) {\n this.report.setQuery(new DJQuery(text, language));\n return this;\n }", "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 }", "private static BufferedImage scale(BufferedImage imageToScale, int dWidth, int dHeight, double fWidth, double fHeight) {\n BufferedImage dbi = null;\n // Needed to create a new BufferedImage object\n int imageType = imageToScale.getType();\n if (imageToScale != null) {\n dbi = new BufferedImage(dWidth, dHeight, imageType);\n Graphics2D g = dbi.createGraphics();\n AffineTransform at = AffineTransform.getScaleInstance(fWidth, fHeight);\n g.drawRenderedImage(imageToScale, at);\n }\n return dbi;\n }", "private static void invokeSetter(final Object bean, final Method setMethod, final Object fieldValue) {\n\t\ttry {\n\t\t\tsetMethod.setAccessible(true);\n\t\t\tsetMethod.invoke(bean, fieldValue);\n\t\t}\n\t\tcatch(final Exception e) {\n\t\t\tthrow new SuperCsvReflectionException(String.format(\"error invoking method %s()\", setMethod.getName()), e);\n\t\t}\n\t}", "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 }" ]
Searches for brackets which are only used to construct new matrices by concatenating 1 or more matrices together
[ "protected void parseBracketCreateMatrix(TokenList tokens, Sequence sequence) {\n List<TokenList.Token> left = new ArrayList<TokenList.Token>();\n\n TokenList.Token t = tokens.getFirst();\n\n while( t != null ) {\n TokenList.Token next = t.next;\n if( t.getSymbol() == Symbol.BRACKET_LEFT ) {\n left.add(t);\n } else if( t.getSymbol() == Symbol.BRACKET_RIGHT ) {\n if( left.isEmpty() )\n throw new RuntimeException(\"No matching left bracket for right\");\n\n TokenList.Token start = left.remove(left.size() - 1);\n\n // Compute everything inside the [ ], this will leave a\n // series of variables and semi-colons hopefully\n TokenList bracketLet = tokens.extractSubList(start.next,t.previous);\n parseBlockNoParentheses(bracketLet, sequence, true);\n MatrixConstructor constructor = constructMatrix(bracketLet);\n\n // define the matrix op and inject into token list\n Operation.Info info = Operation.matrixConstructor(constructor);\n sequence.addOperation(info.op);\n\n tokens.insert(start.previous, new TokenList.Token(info.output));\n\n // remove the brackets\n tokens.remove(start);\n tokens.remove(t);\n }\n\n t = next;\n }\n\n if( !left.isEmpty() )\n throw new RuntimeException(\"Dangling [\");\n }" ]
[ "public static void copyRecursively(final Path source, final Path target, boolean overwrite) throws IOException {\n final CopyOption[] options;\n if (overwrite) {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING};\n } else {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES};\n }\n Files.walkFileTree(source, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n Files.copy(dir, target.resolve(source.relativize(dir)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n Files.copy(file, target.resolve(source.relativize(file)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n DeploymentRepositoryLogger.ROOT_LOGGER.cannotCopyFile(exc, file);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n });\n }", "private static void setCmsOfflineProject(CmsObject cms) {\n\n if (null == cms) {\n return;\n }\n\n final CmsRequestContext cmsContext = cms.getRequestContext();\n final CmsProject cmsProject = cmsContext.getCurrentProject();\n\n if (cmsProject.isOnlineProject()) {\n CmsProject cmsOfflineProject;\n try {\n cmsOfflineProject = cms.readProject(\"Offline\");\n cmsContext.setCurrentProject(cmsOfflineProject);\n } catch (CmsException e) {\n LOG.warn(\"Could not set the current project to \\\"Offline\\\". \");\n }\n }\n }", "public static base_responses update(nitro_service client, dospolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdospolicy updateresources[] = new dospolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new dospolicy();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].qdepth = resources[i].qdepth;\n\t\t\t\tupdateresources[i].cltdetectrate = resources[i].cltdetectrate;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public void setWholeDay(Boolean isWholeDay) {\r\n\r\n if (m_model.isWholeDay() ^ ((null != isWholeDay) && isWholeDay.booleanValue())) {\r\n m_model.setWholeDay(isWholeDay);\r\n valueChanged();\r\n }\r\n }", "public void insertAfter(Token before, TokenList list ) {\n Token after = before.next;\n\n before.next = list.first;\n list.first.previous = before;\n if( after == null ) {\n last = list.last;\n } else {\n after.previous = list.last;\n list.last.next = after;\n }\n size += list.size;\n }", "public static <T> T splitEachLine(CharSequence self, Pattern pattern, @ClosureParams(value=FromString.class,options=\"List<String>\") Closure<T> closure) throws IOException {\n final List<String> list = readLines(self);\n T result = null;\n for (String line : list) {\n List vals = Arrays.asList(pattern.split(line));\n result = closure.call(vals);\n }\n return result;\n }", "public GroovyFieldDoc[] fields() {\n Collections.sort(fields);\n return fields.toArray(new GroovyFieldDoc[fields.size()]);\n }", "public ProjectCalendar getEffectiveCalendar()\n {\n ProjectCalendar result = getCalendar();\n if (result == null)\n {\n result = getParentFile().getDefaultCalendar();\n }\n return result;\n }", "public static Map<String, Object> introspect(Object obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {\n\t\tMap<String, Object> result = new HashMap<>();\n\t\tBeanInfo info = Introspector.getBeanInfo( obj.getClass() );\n\t\tfor ( PropertyDescriptor pd : info.getPropertyDescriptors() ) {\n\t\t\tMethod reader = pd.getReadMethod();\n\t\t\tString name = pd.getName();\n\t\t\tif ( reader != null && !\"class\".equals( name ) ) {\n\t\t\t\tresult.put( name, reader.invoke( obj ) );\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}" ]
Bessel function of the second kind, of order 0. @param x Value. @return Y0 value.
[ "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 }" ]
[ "public void setPadding(float padding, Layout.Axis axis) {\n OrientedLayout layout = null;\n switch(axis) {\n case X:\n layout = mShiftLayout;\n break;\n case Y:\n layout = mShiftLayout;\n break;\n case Z:\n layout = mStackLayout;\n break;\n }\n if (layout != null) {\n if (!equal(layout.getDividerPadding(axis), padding)) {\n layout.setDividerPadding(padding, axis);\n\n if (layout.getOrientationAxis() == axis) {\n requestLayout();\n }\n }\n }\n\n }", "private EventTypeEnum getEventType(Message message) {\n boolean isRequestor = MessageUtils.isRequestor(message);\n boolean isFault = MessageUtils.isFault(message);\n boolean isOutbound = MessageUtils.isOutbound(message);\n\n //Needed because if it is rest request and method does not exists had better to return Fault\n if(!isFault && isRestMessage(message)) {\n isFault = (message.getExchange().get(\"org.apache.cxf.resource.operation.name\") == null);\n if (!isFault) {\n Integer responseCode = (Integer) message.get(Message.RESPONSE_CODE);\n if (null != responseCode) {\n isFault = (responseCode >= 400);\n }\n }\n }\n if (isOutbound) {\n if (isFault) {\n return EventTypeEnum.FAULT_OUT;\n } else {\n return isRequestor ? EventTypeEnum.REQ_OUT : EventTypeEnum.RESP_OUT;\n }\n } else {\n if (isFault) {\n return EventTypeEnum.FAULT_IN;\n } else {\n return isRequestor ? EventTypeEnum.RESP_IN : EventTypeEnum.REQ_IN;\n }\n }\n }", "public void unbind(String name) throws ObjectNameNotFoundException\r\n {\r\n /**\r\n * Is DB open? ODMG 3.0 says it has to be to call unbind.\r\n */\r\n if (!this.isOpen())\r\n {\r\n throw new DatabaseClosedException(\"Database is not open. Must have an open DB to call unbind\");\r\n }\r\n TransactionImpl tx = getTransaction();\r\n if (tx == null || !tx.isOpen())\r\n {\r\n throw new TransactionNotInProgressException(\"Tx is not open. Must have an open TX to call lookup.\");\r\n }\r\n\r\n tx.getNamedRootsMap().unbind(name);\r\n }", "public PhotoList<Photo> getContactsPhotos(int count, boolean justFriends, boolean singlePhoto, boolean includeSelf) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTACTS_PHOTOS);\r\n\r\n if (count > 0) {\r\n parameters.put(\"count\", Integer.toString(count));\r\n }\r\n if (justFriends) {\r\n parameters.put(\"just_friends\", \"1\");\r\n }\r\n if (singlePhoto) {\r\n parameters.put(\"single_photo\", \"1\");\r\n }\r\n if (includeSelf) {\r\n parameters.put(\"include_self\", \"1\");\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n photos.setPage(\"1\");\r\n photos.setPages(\"1\");\r\n photos.setPerPage(\"\" + photoNodes.getLength());\r\n photos.setTotal(\"\" + photoNodes.getLength());\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }", "public static Integer parseInteger(String value) throws ParseException\n {\n Integer result = null;\n\n if (value.length() > 0 && value.indexOf(' ') == -1)\n {\n if (value.indexOf('.') == -1)\n {\n result = Integer.valueOf(value);\n }\n else\n {\n Number n = DatatypeConverter.parseDouble(value);\n result = Integer.valueOf(n.intValue());\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 }", "private void updateRoutingStrategies(Cluster cluster, List<StoreDefinition> storeDefs) {\n // acquire write lock\n writeLock.lock();\n try {\n VectorClock clock = new VectorClock();\n if(metadataCache.containsKey(ROUTING_STRATEGY_KEY))\n clock = (VectorClock) metadataCache.get(ROUTING_STRATEGY_KEY).getVersion();\n\n logger.info(\"Updating routing strategy for all stores\");\n HashMap<String, StoreDefinition> storeDefMap = makeStoreDefinitionMap(storeDefs);\n HashMap<String, RoutingStrategy> routingStrategyMap = createRoutingStrategyMap(cluster,\n storeDefMap);\n this.metadataCache.put(ROUTING_STRATEGY_KEY,\n new Versioned<Object>(routingStrategyMap,\n clock.incremented(getNodeId(),\n System.currentTimeMillis())));\n\n for(String storeName: storeNameTolisteners.keySet()) {\n RoutingStrategy updatedRoutingStrategy = routingStrategyMap.get(storeName);\n if(updatedRoutingStrategy != null) {\n try {\n for(MetadataStoreListener listener: storeNameTolisteners.get(storeName)) {\n listener.updateRoutingStrategy(updatedRoutingStrategy);\n listener.updateStoreDefinition(storeDefMap.get(storeName));\n }\n } catch(Exception e) {\n if(logger.isEnabledFor(Level.WARN))\n logger.warn(e, e);\n }\n }\n\n }\n } finally {\n writeLock.unlock();\n }\n }", "public ParallelTaskBuilder prepareHttpPost(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.POST);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }", "public Set<String> getSupportedUriSchemes() {\n Set<String> schemes = new HashSet<>();\n\n for (ConfigFileLoaderPlugin loaderPlugin: this.getLoaderPlugins()) {\n schemes.add(loaderPlugin.getUriScheme());\n }\n\n return schemes;\n }" ]
Create a patch representing what we actually processed. This may contain some fixed content hashes for removed modules. @param original the original @return the processed patch
[ "protected Patch createProcessedPatch(final Patch original) {\n\n // Process elements\n final List<PatchElement> elements = new ArrayList<PatchElement>();\n // Process layers\n for (final PatchEntry entry : getLayers()) {\n final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications);\n elements.add(element);\n }\n // Process add-ons\n for (final PatchEntry entry : getAddOns()) {\n final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications);\n elements.add(element);\n }\n\n // Swap the patch element modifications, keep the identity ones since we don't need to fix the misc modifications\n return new PatchImpl(original.getPatchId(), original.getDescription(), original.getLink(), original.getIdentity(), elements, identityEntry.modifications);\n }" ]
[ "public static int[] getTileScreenSize(double[] worldSize, double scale) {\n\t\tint screenWidth = (int) Math.round(scale * worldSize[0]);\n\t\tint screenHeight = (int) Math.round(scale * worldSize[1]);\n\t\treturn new int[] { screenWidth, screenHeight };\n\t}", "private void createSimpleCubeSixMeshes(GVRContext gvrContext,\n boolean facingOut, String vertexDesc, ArrayList<GVRTexture> textureList)\n {\n GVRSceneObject[] children = new GVRSceneObject[6];\n GVRMesh[] meshes = new GVRMesh[6];\n GVRVertexBuffer vbuf = new GVRVertexBuffer(gvrContext, vertexDesc, SIMPLE_VERTICES.length / 3);\n\n if (facingOut)\n {\n vbuf.setFloatArray(\"a_position\", SIMPLE_VERTICES, 3, 0);\n vbuf.setFloatArray(\"a_normal\", SIMPLE_OUTWARD_NORMALS, 3, 0);\n vbuf.setFloatArray(\"a_texcoord\", SIMPLE_OUTWARD_TEXCOORDS, 2, 0);\n meshes[0] = createMesh(vbuf, SIMPLE_OUTWARD_FRONT_INDICES);\n meshes[1] = createMesh(vbuf, SIMPLE_OUTWARD_RIGHT_INDICES);\n meshes[2] = createMesh(vbuf, SIMPLE_OUTWARD_BACK_INDICES);\n meshes[3] = createMesh(vbuf, SIMPLE_OUTWARD_LEFT_INDICES);\n meshes[4] = createMesh(vbuf, SIMPLE_OUTWARD_TOP_INDICES);\n meshes[5] = createMesh(vbuf, SIMPLE_OUTWARD_BOTTOM_INDICES);\n }\n else\n {\n vbuf.setFloatArray(\"a_position\", SIMPLE_VERTICES, 3, 0);\n vbuf.setFloatArray(\"a_normal\", SIMPLE_INWARD_NORMALS, 3, 0);\n vbuf.setFloatArray(\"a_texcoord\", SIMPLE_INWARD_TEXCOORDS, 2, 0);\n meshes[0] = createMesh(vbuf, SIMPLE_INWARD_FRONT_INDICES);\n meshes[1] = createMesh(vbuf, SIMPLE_INWARD_RIGHT_INDICES);\n meshes[2] = createMesh(vbuf, SIMPLE_INWARD_BACK_INDICES);\n meshes[3] = createMesh(vbuf, SIMPLE_INWARD_LEFT_INDICES);\n meshes[4] = createMesh(vbuf, SIMPLE_INWARD_TOP_INDICES);\n meshes[5] = createMesh(vbuf, SIMPLE_INWARD_BOTTOM_INDICES);\n }\n\n for (int i = 0; i < 6; i++)\n {\n children[i] = new GVRSceneObject(gvrContext, meshes[i], textureList.get(i));\n addChildObject(children[i]);\n }\n\n // attached an empty renderData for parent object, so that we can set some common properties\n GVRRenderData renderData = new GVRRenderData(gvrContext);\n attachRenderData(renderData);\n }", "private Number calculatePercentComplete(Row row)\n {\n Number result;\n switch (PercentCompleteType.getInstance(row.getString(\"complete_pct_type\")))\n {\n case UNITS:\n {\n result = calculateUnitsPercentComplete(row);\n break;\n }\n\n case DURATION:\n {\n result = calculateDurationPercentComplete(row);\n break;\n }\n\n default:\n {\n result = calculatePhysicalPercentComplete(row);\n break;\n }\n }\n\n return result;\n }", "public static authenticationvserver_stats get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_stats obj = new authenticationvserver_stats();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_stats response = (authenticationvserver_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "protected List<TokenList.Token> parseParameterCommaBlock( TokenList tokens, Sequence sequence ) {\n // find all the comma tokens\n List<TokenList.Token> commas = new ArrayList<TokenList.Token>();\n TokenList.Token token = tokens.first;\n\n int numBracket = 0;\n while( token != null ) {\n if( token.getType() == Type.SYMBOL ) {\n switch( token.getSymbol() ) {\n case COMMA:\n if( numBracket == 0)\n commas.add(token);\n break;\n\n case BRACKET_LEFT: numBracket++; break;\n case BRACKET_RIGHT: numBracket--; break;\n }\n }\n token = token.next;\n }\n\n List<TokenList.Token> output = new ArrayList<TokenList.Token>();\n if( commas.isEmpty() ) {\n output.add(parseBlockNoParentheses(tokens, sequence, false));\n } else {\n TokenList.Token before = tokens.first;\n for (int i = 0; i < commas.size(); i++) {\n TokenList.Token after = commas.get(i);\n if( before == after )\n throw new ParseError(\"No empty function inputs allowed!\");\n TokenList.Token tmp = after.next;\n TokenList sublist = tokens.extractSubList(before,after);\n sublist.remove(after);// remove the comma\n output.add(parseBlockNoParentheses(sublist, sequence, false));\n before = tmp;\n }\n\n // if the last character is a comma then after.next above will be null and thus before is null\n if( before == null )\n throw new ParseError(\"No empty function inputs allowed!\");\n\n TokenList.Token after = tokens.last;\n TokenList sublist = tokens.extractSubList(before, after);\n output.add(parseBlockNoParentheses(sublist, sequence, false));\n }\n\n return output;\n }", "protected void propagateOnNoPick(GVRPicker picker)\n {\n if (mEventOptions.contains(EventOptions.SEND_PICK_EVENTS))\n {\n if (mEventOptions.contains(EventOptions.SEND_TO_LISTENERS))\n {\n getGVRContext().getEventManager().sendEvent(this, IPickEvents.class, \"onNoPick\", picker);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_SCENE) && (mScene != null))\n {\n getGVRContext().getEventManager().sendEvent(mScene, IPickEvents.class, \"onNoPick\", picker);\n }\n }\n }", "public static boolean isEasterSunday(LocalDate date) {\n\t\tint y = date.getYear();\n\t\tint a = y % 19;\n\t\tint b = y / 100;\n\t\tint c = y % 100;\n\t\tint d = b / 4;\n\t\tint e = b % 4;\n\t\tint f = (b + 8) / 25;\n\t\tint g = (b - f + 1) / 3;\n\t\tint h = (19 * a + b - d - g + 15) % 30;\n\t\tint i = c / 4;\n\t\tint k = c % 4;\n\t\tint l = (32 + 2 * e + 2 * i - h - k) % 7;\n\t\tint m = (a + 11 * h + 22 * l) / 451;\n\t\tint easterSundayMonth\t= (h + l - 7 * m + 114) / 31;\n\t\tint easterSundayDay\t\t= ((h + l - 7 * m + 114) % 31) + 1;\n\n\t\tint month = date.getMonthValue();\n\t\tint day = date.getDayOfMonth();\n\n\t\treturn (easterSundayMonth == month) && (easterSundayDay == day);\n\t}", "public static String paramMapToString(final Map<String, String[]> parameters) {\n\n final StringBuffer result = new StringBuffer();\n for (final String key : parameters.keySet()) {\n String[] values = parameters.get(key);\n if (null == values) {\n result.append(key).append('&');\n } else {\n for (final String value : parameters.get(key)) {\n result.append(key).append('=').append(CmsEncoder.encode(value)).append('&');\n }\n }\n }\n // remove last '&'\n if (result.length() > 0) {\n result.setLength(result.length() - 1);\n }\n return result.toString();\n }", "public static double huntKennedyCMSOptionValue(\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 a = 1.0/swapMaturity;\n\t\tdouble b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;\n\t\tdouble convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);\n\n\t\tdouble valueUnadjusted\t= blackModelSwaptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);\n\t\tdouble valueAdjusted\t= blackModelSwaptionValue(forwardSwaprate * convexityAdjustment, volatility, optionMaturity, optionStrike, swapAnnuity);\n\n\t\treturn a * valueUnadjusted + b * forwardSwaprate * valueAdjusted;\n\t}" ]
Reads the integer representation of calendar hours for a given day and populates the calendar. @param calendar parent calendar @param day target day @param hours working hours
[ "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 }" ]
[ "public Duration getDuration(FastTrackField type)\n {\n Double value = (Double) getObject(type);\n return value == null ? null : Duration.getInstance(value.doubleValue(), m_table.getDurationTimeUnit());\n }", "private static void flushCurrentWord( StringBuilder currentWords, List<Word> formattedWords, boolean cutWhitespace ) {\n if( currentWords.length() > 0 ) {\n if( cutWhitespace && currentWords.charAt( currentWords.length() - 1 ) == ' ' ) {\n currentWords.setLength( currentWords.length() - 1 );\n }\n formattedWords.add( new Word( currentWords.toString() ) );\n currentWords.setLength( 0 );\n }\n }", "public long countByLex(final LexRange lexRange) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.zlexcount(getKey(), lexRange.from(), lexRange.to());\n }\n });\n }", "private synchronized HostServerGroupEffect getHostEffect(PathAddress address, String host, Resource root) {\n if (requiresMapping) {\n map(root);\n requiresMapping = false;\n }\n Set<String> mapped = hostsToGroups.get(host);\n if (mapped == null) {\n // Unassigned host. Treat like an unassigned profile or socket-binding-group;\n // i.e. available to all server group scoped roles.\n // Except -- WFLY-2085 -- the master HC is not open to all s-g-s-rs\n Resource hostResource = root.getChild(PathElement.pathElement(HOST, host));\n if (hostResource != null) {\n ModelNode dcModel = hostResource.getModel().get(DOMAIN_CONTROLLER);\n if (!dcModel.hasDefined(REMOTE)) {\n mapped = Collections.emptySet(); // prevents returning HostServerGroupEffect.forUnassignedHost(address, host)\n }\n }\n }\n return mapped == null ? HostServerGroupEffect.forUnassignedHost(address, host)\n : HostServerGroupEffect.forMappedHost(address, mapped, host);\n\n }", "private String getPathSelectString() {\n String queryString = \"SELECT \" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.GENERIC_CLIENT_UUID +\n \",\" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID +\n \",\" + Constants.PATH_PROFILE_PATHNAME +\n \",\" + Constants.PATH_PROFILE_ACTUAL_PATH +\n \",\" + Constants.PATH_PROFILE_BODY_FILTER +\n \",\" + Constants.PATH_PROFILE_GROUP_IDS +\n \",\" + Constants.DB_TABLE_PATH + \".\" + Constants.PATH_PROFILE_PROFILE_ID +\n \",\" + Constants.PATH_PROFILE_PATH_ORDER +\n \",\" + Constants.REQUEST_RESPONSE_REPEAT_NUMBER +\n \",\" + Constants.REQUEST_RESPONSE_REQUEST_ENABLED +\n \",\" + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED +\n \",\" + Constants.PATH_PROFILE_CONTENT_TYPE +\n \",\" + Constants.PATH_PROFILE_REQUEST_TYPE +\n \",\" + Constants.PATH_PROFILE_GLOBAL +\n \" FROM \" + Constants.DB_TABLE_PATH +\n \" JOIN \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \" ON \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID +\n \"=\" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.REQUEST_RESPONSE_PATH_ID +\n \" AND \" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.GENERIC_CLIENT_UUID + \" = ?\";\n\n return queryString;\n }", "public static autoscaleprofile[] get(nitro_service service) throws Exception{\n\t\tautoscaleprofile obj = new autoscaleprofile();\n\t\tautoscaleprofile[] response = (autoscaleprofile[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public void set( int row , int col , double value ) {\n ops.set(mat, row, col, value);\n }", "public <V> V attach(final AttachmentKey<V> key, final V value) {\n assert key != null;\n return key.cast(contextAttachments.put(key, value));\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 }" ]
this method is not intended to be called by clients @since 2.12
[ "@Inject(optional = true)\n protected Pattern setEndTag(@Named(AbstractMultiLineCommentProvider.END_TAG) final String endTag) {\n return this.endTagPattern = Pattern.compile((endTag + \"\\\\z\"));\n }" ]
[ "public void setKey(int keyIndex, float time, final float[] values)\n {\n int index = keyIndex * mFloatsPerKey;\n Integer valSize = mFloatsPerKey-1;\n\n if (values.length != valSize)\n {\n throw new IllegalArgumentException(\"This key needs \" + valSize.toString() + \" float per value\");\n }\n mKeys[index] = time;\n System.arraycopy(values, 0, mKeys, index + 1, values.length);\n }", "public static <T> Collection<T> diff(Collection<T> list1, Collection<T> list2) {\r\n Collection<T> diff = new ArrayList<T>();\r\n for (T t : list1) {\r\n if (!list2.contains(t)) {\r\n diff.add(t);\r\n }\r\n }\r\n return diff;\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 }", "public Authentication getAuthentication(String token) {\n\t\tif (null != token) {\n\t\t\tTokenContainer container = tokens.get(token);\n\t\t\tif (null != container) {\n\t\t\t\tif (container.isValid()) {\n\t\t\t\t\treturn container.getAuthentication();\n\t\t\t\t} else {\n\t\t\t\t\tlogout(token);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "private void writeResourceAssignmentWorkgroupFields(ResourceAssignmentWorkgroupFields record) throws IOException\n {\n m_buffer.setLength(0);\n\n m_buffer.append(MPXConstants.RESOURCE_ASSIGNMENT_WORKGROUP_FIELDS_RECORD_NUMBER);\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getMessageUniqueID()));\n m_buffer.append(m_delimiter);\n m_buffer.append(record.getConfirmed() ? \"1\" : \"0\");\n m_buffer.append(m_delimiter);\n m_buffer.append(record.getResponsePending() ? \"1\" : \"0\");\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTimeNull(record.getUpdateStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTimeNull(record.getUpdateFinish())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getScheduleID()));\n\n stripTrailingDelimiters(m_buffer);\n m_buffer.append(MPXConstants.EOL);\n\n m_writer.write(m_buffer.toString());\n }", "@Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {\n try {\n if (exceptionRaised.get()) {\n return;\n }\n\n if (!(msg instanceof HttpRequest)) {\n // If there is no methodInfo, it means the request was already rejected.\n // What we received here is just residue of the request, which can be ignored.\n if (methodInfo != null) {\n ReferenceCountUtil.retain(msg);\n ctx.fireChannelRead(msg);\n }\n return;\n }\n HttpRequest request = (HttpRequest) msg;\n BasicHttpResponder responder = new BasicHttpResponder(ctx.channel(), sslEnabled);\n\n // Reset the methodInfo for the incoming request error handling\n methodInfo = null;\n methodInfo = prepareHandleMethod(request, responder, ctx);\n\n if (methodInfo != null) {\n ReferenceCountUtil.retain(msg);\n ctx.fireChannelRead(msg);\n } else {\n if (!responder.isResponded()) {\n // If not yet responded, just respond with a not found and close the connection\n HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);\n HttpUtil.setContentLength(response, 0);\n HttpUtil.setKeepAlive(response, false);\n ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);\n } else {\n // If already responded, just close the connection\n ctx.channel().close();\n }\n }\n } finally {\n ReferenceCountUtil.release(msg);\n }\n }", "protected synchronized StealerBasedRebalanceTask scheduleNextTask(boolean executeService) {\n // Make sure there is work left to do.\n if(doneSignal.getCount() == 0) {\n logger.info(\"All tasks completion signaled... returning\");\n\n return null;\n }\n // Limit number of tasks outstanding.\n if(this.numTasksExecuting >= maxParallelRebalancing) {\n logger.info(\"Executing more tasks than [\" + this.numTasksExecuting\n + \"] the parallel allowed \" + maxParallelRebalancing);\n return null;\n }\n // Shuffle list of stealer IDs each time a new task to schedule needs to\n // be found. Randomizing the order should avoid prioritizing one\n // specific stealer's work ahead of all others.\n List<Integer> stealerIds = new ArrayList<Integer>(tasksByStealer.keySet());\n Collections.shuffle(stealerIds);\n for(int stealerId: stealerIds) {\n if(nodeIdsWithWork.contains(stealerId)) {\n logger.info(\"Stealer \" + stealerId + \" is already working... continuing\");\n continue;\n }\n\n for(StealerBasedRebalanceTask sbTask: tasksByStealer.get(stealerId)) {\n int donorId = sbTask.getStealInfos().get(0).getDonorId();\n if(nodeIdsWithWork.contains(donorId)) {\n logger.info(\"Stealer \" + stealerId + \" Donor \" + donorId\n + \" is already working... continuing\");\n continue;\n }\n // Book keeping\n addNodesToWorkerList(Arrays.asList(stealerId, donorId));\n numTasksExecuting++;\n // Remove this task from list thus destroying list being\n // iterated over. This is safe because returning directly out of\n // this branch.\n tasksByStealer.get(stealerId).remove(sbTask);\n try {\n if(executeService) {\n logger.info(\"Stealer \" + stealerId + \" Donor \" + donorId\n + \" going to schedule work\");\n service.execute(sbTask);\n }\n } catch(RejectedExecutionException ree) {\n logger.error(\"Stealer \" + stealerId\n + \"Rebalancing task rejected by executor service.\", ree);\n throw new VoldemortRebalancingException(\"Stealer \"\n + stealerId\n + \"Rebalancing task rejected by executor service.\");\n }\n return sbTask;\n }\n }\n printRemainingTasks(stealerIds);\n return null;\n }", "void commitTempFile(File temp) throws ConfigurationPersistenceException {\n if (!doneBootup.get()) {\n return;\n }\n if (!interactionPolicy.isReadOnly()) {\n FilePersistenceUtils.moveTempFileToMain(temp, mainFile);\n } else {\n FilePersistenceUtils.moveTempFileToMain(temp, lastFile);\n }\n }", "@Override\n public final boolean getBool(final String key) {\n Boolean result = optBool(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }" ]
Return a copy of the new fragment and set the variable above.
[ "@Override\n protected AbstractFilePickerFragment<File> getFragment(\n final String startPath, final int mode, final boolean allowMultiple,\n final boolean allowDirCreate, final boolean allowExistingFile,\n final boolean singleClick) {\n\n // startPath is allowed to be null.\n // In that case, default folder should be SD-card and not \"/\"\n String path = (startPath != null ? startPath\n : Environment.getExternalStorageDirectory().getPath());\n\n currentFragment = new BackHandlingFilePickerFragment();\n currentFragment.setArgs(path, mode, allowMultiple, allowDirCreate,\n allowExistingFile, singleClick);\n return currentFragment;\n }" ]
[ "protected void processDeletions(CmsObject cms, List<CmsResource> toDelete) throws CmsException {\n\n Collections.sort(toDelete, (a, b) -> b.getRootPath().compareTo(a.getRootPath()));\n for (CmsResource deleteRes : toDelete) {\n m_report.print(\n org.opencms.importexport.Messages.get().container(org.opencms.importexport.Messages.RPT_DELFOLDER_0),\n I_CmsReport.FORMAT_NOTE);\n m_report.print(\n org.opencms.report.Messages.get().container(\n org.opencms.report.Messages.RPT_ARGUMENT_1,\n deleteRes.getRootPath()));\n CmsLock lock = cms.getLock(deleteRes);\n if (lock.isUnlocked()) {\n lock(cms, deleteRes);\n }\n cms.deleteResource(deleteRes, CmsResource.DELETE_PRESERVE_SIBLINGS);\n m_report.println(\n org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),\n I_CmsReport.FORMAT_OK);\n\n }\n }", "public static boolean propertyExists(Class<?> clazz, String property, ElementType elementType) {\n\t\tif ( ElementType.FIELD.equals( elementType ) ) {\n\t\t\treturn getDeclaredField( clazz, property ) != null;\n\t\t}\n\t\telse {\n\t\t\tString capitalizedPropertyName = capitalize( property );\n\n\t\t\tMethod method = getMethod( clazz, PROPERTY_ACCESSOR_PREFIX_GET + capitalizedPropertyName );\n\t\t\tif ( method != null && method.getReturnType() != void.class ) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tmethod = getMethod( clazz, PROPERTY_ACCESSOR_PREFIX_IS + capitalizedPropertyName );\n\t\t\tif ( method != null && method.getReturnType() == boolean.class ) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}", "public static <T extends JsonRtn> T parseJsonRtn(String jsonRtn, Class<T> jsonRtnClazz) {\n T rtn = JSONObject.parseObject(jsonRtn, jsonRtnClazz);\n appendErrorHumanMsg(rtn);\n return rtn;\n }", "public static nd6ravariables[] get(nitro_service service, options option) throws Exception{\n\t\tnd6ravariables obj = new nd6ravariables();\n\t\tnd6ravariables[] response = (nd6ravariables[])obj.get_resources(service,option);\n\t\treturn response;\n\t}", "@Override\n public void setCursorDepth(float depth)\n {\n super.setCursorDepth(depth);\n if (mRayModel != null)\n {\n mRayModel.getTransform().setScaleZ(mCursorDepth);\n }\n }", "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 CollectionRequest<User> findByWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/users\", workspace);\n return new CollectionRequest<User>(this, User.class, path, \"GET\");\n }", "private void stream(InputStream is, File destFile) throws IOException {\n try {\n startProgress();\n OutputStream os = new FileOutputStream(destFile);\n \n boolean finished = false;\n try {\n byte[] buf = new byte[1024 * 10];\n int read;\n while ((read = is.read(buf)) >= 0) {\n os.write(buf, 0, read);\n processedBytes += read;\n logProgress();\n }\n \n os.flush();\n finished = true;\n } finally {\n os.close();\n if (!finished) {\n destFile.delete();\n }\n }\n } finally {\n is.close();\n completeProgress();\n }\n }", "public static ModelNode getOperationAddress(final ModelNode op) {\n return op.hasDefined(OP_ADDR) ? op.get(OP_ADDR) : new ModelNode();\n }" ]
Determines if the queue identified by the given key is a regular queue. @param jedis connection to Redis @param key the key that identifies a queue @return true if the key identifies a regular queue, false otherwise
[ "public static boolean isRegularQueue(final Jedis jedis, final String key) {\n return LIST.equalsIgnoreCase(jedis.type(key));\n }" ]
[ "public Double score(final String member) {\n return doWithJedis(new JedisCallable<Double>() {\n @Override\n public Double call(Jedis jedis) {\n return jedis.zscore(getKey(), member);\n }\n });\n }", "public void read(File file, Table table) throws IOException\n {\n //System.out.println(\"Reading \" + file.getName());\n InputStream is = null;\n try\n {\n is = new FileInputStream(file);\n read(is, table);\n }\n\n finally\n {\n StreamHelper.closeQuietly(is);\n }\n }", "private static final String correctNumberFormat(String value)\n {\n String result;\n int index = value.indexOf(',');\n if (index == -1)\n {\n result = value;\n }\n else\n {\n char[] chars = value.toCharArray();\n chars[index] = '.';\n result = new String(chars);\n }\n return result;\n }", "public ByteBuffer payload() {\n ByteBuffer payload = buffer.duplicate();\n payload.position(headerSize(magic()));\n payload = payload.slice();\n payload.limit(payloadSize());\n payload.rewind();\n return payload;\n }", "public <T extends Widget & Checkable> boolean check(int checkableIndex) {\n List<T> children = getCheckableChildren();\n T checkableWidget = children.get(checkableIndex);\n return checkInternal(checkableWidget, true);\n }", "protected static String getTimePrecisionString(byte precision) {\n\t\tswitch (precision) {\n\t\tcase TimeValue.PREC_SECOND:\n\t\t\treturn \"sec\";\n\t\tcase TimeValue.PREC_MINUTE:\n\t\t\treturn \"min\";\n\t\tcase TimeValue.PREC_HOUR:\n\t\t\treturn \"hour\";\n\t\tcase TimeValue.PREC_DAY:\n\t\t\treturn \"day\";\n\t\tcase TimeValue.PREC_MONTH:\n\t\t\treturn \"month\";\n\t\tcase TimeValue.PREC_YEAR:\n\t\t\treturn \"year\";\n\t\tcase TimeValue.PREC_DECADE:\n\t\t\treturn \"decade\";\n\t\tcase TimeValue.PREC_100Y:\n\t\t\treturn \"100 years\";\n\t\tcase TimeValue.PREC_1KY:\n\t\t\treturn \"1000 years\";\n\t\tcase TimeValue.PREC_10KY:\n\t\t\treturn \"10K years\";\n\t\tcase TimeValue.PREC_100KY:\n\t\t\treturn \"100K years\";\n\t\tcase TimeValue.PREC_1MY:\n\t\t\treturn \"1 million years\";\n\t\tcase TimeValue.PREC_10MY:\n\t\t\treturn \"10 million years\";\n\t\tcase TimeValue.PREC_100MY:\n\t\t\treturn \"100 million years\";\n\t\tcase TimeValue.PREC_1GY:\n\t\t\treturn \"1000 million years\";\n\t\tdefault:\n\t\t\treturn \"Unsupported precision \" + precision;\n\t\t}\n\t}", "public boolean removeKey(long key) {\r\n\tint i = indexOfKey(key);\r\n\tif (i<0) return false; // key not contained\r\n\r\n\tthis.state[i]=REMOVED;\r\n\tthis.values[i]=0; // delta\r\n\tthis.distinct--;\r\n\r\n\tif (this.distinct < this.lowWaterMark) {\r\n\t\tint newCapacity = chooseShrinkCapacity(this.distinct,this.minLoadFactor, this.maxLoadFactor);\r\n\t\trehash(newCapacity);\r\n\t}\r\n\t\r\n\treturn true;\t\r\n}", "public StandaloneCommandBuilder addSecurityProperty(final String key, final String value) {\n securityProperties.put(key, value);\n return this;\n }", "private <T> MongoCollection<T> getLocalCollection(\n final MongoNamespace namespace,\n final Class<T> resultClass,\n final CodecRegistry codecRegistry\n ) {\n return localClient\n .getDatabase(String.format(\"sync_user_%s\", namespace.getDatabaseName()))\n .getCollection(namespace.getCollectionName(), resultClass)\n .withCodecRegistry(codecRegistry);\n }" ]
Returns the list view of corporate groupIds of an organization @param organizationId String @return ListView
[ "public List<String> getCorporateGroupIds(final String organizationId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n return dbOrganization.getCorporateGroupIdPrefixes();\n }" ]
[ "static byte[] hmacSha1(StringBuilder message, String key) {\n try {\n Mac mac = Mac.getInstance(\"HmacSHA1\");\n mac.init(new SecretKeySpec(key.getBytes(), \"HmacSHA1\"));\n return mac.doFinal(message.toString().getBytes());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "public ModelNode getDeploymentSubsystemModel(final String subsystemName) {\n assert subsystemName != null : \"The subsystemName cannot be null\";\n return getDeploymentSubModel(subsystemName, PathAddress.EMPTY_ADDRESS, null, deploymentUnit);\n }", "public static URL getAuthorizationURL(String clientID, URI redirectUri, String state, List<String> scopes) {\n URLTemplate template = new URLTemplate(AUTHORIZATION_URL);\n QueryStringBuilder queryBuilder = new QueryStringBuilder().appendParam(\"client_id\", clientID)\n .appendParam(\"response_type\", \"code\")\n .appendParam(\"redirect_uri\", redirectUri.toString())\n .appendParam(\"state\", state);\n\n if (scopes != null && !scopes.isEmpty()) {\n StringBuilder builder = new StringBuilder();\n int size = scopes.size() - 1;\n int i = 0;\n while (i < size) {\n builder.append(scopes.get(i));\n builder.append(\" \");\n i++;\n }\n builder.append(scopes.get(i));\n\n queryBuilder.appendParam(\"scope\", builder.toString());\n }\n\n return template.buildWithQuery(\"\", queryBuilder.toString());\n }", "public static base_response disable(nitro_service client, nsacl6 resource) throws Exception {\n\t\tnsacl6 disableresource = new nsacl6();\n\t\tdisableresource.acl6name = resource.acl6name;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}", "private static QName getServiceName(Server server) {\n QName serviceName;\n String bindingId = getBindingId(server);\n EndpointInfo eInfo = server.getEndpoint().getEndpointInfo();\n \n if (JAXRS_BINDING_ID.equals(bindingId)) {\n serviceName = eInfo.getName();\n } else {\n ServiceInfo serviceInfo = eInfo.getService();\n serviceName = serviceInfo.getName();\n }\n return serviceName;\n }", "public static int optionLength(String option) {\n\tint result = Standard.optionLength(option);\n\tif (result != 0)\n\t return result;\n\telse\n\t return UmlGraph.optionLength(option);\n }", "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 }", "@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 static onlinkipv6prefix[] get(nitro_service service, String ipv6prefix[]) throws Exception{\n\t\tif (ipv6prefix !=null && ipv6prefix.length>0) {\n\t\t\tonlinkipv6prefix response[] = new onlinkipv6prefix[ipv6prefix.length];\n\t\t\tonlinkipv6prefix obj[] = new onlinkipv6prefix[ipv6prefix.length];\n\t\t\tfor (int i=0;i<ipv6prefix.length;i++) {\n\t\t\t\tobj[i] = new onlinkipv6prefix();\n\t\t\t\tobj[i].set_ipv6prefix(ipv6prefix[i]);\n\t\t\t\tresponse[i] = (onlinkipv6prefix) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}" ]