query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Converts a vector into a quaternion.
Used for the direction of spot and directional lights
Called upon initialization and updates to those vectors
@param d | [
"public Quaternionf ConvertDirectionalVectorToQuaternion(Vector3f d) {\n d.negate();\n Quaternionf q = new Quaternionf();\n // check for exception condition\n if ((d.x == 0) && (d.z == 0)) {\n // exception condition if direction is (0,y,0):\n // straight up, straight down or all zero's.\n if (d.y > 0) { // direction straight up\n AxisAngle4f angleAxis = new AxisAngle4f(-(float) Math.PI / 2, 1, 0,\n 0);\n q.set(angleAxis);\n } else if (d.y < 0) { // direction straight down\n AxisAngle4f angleAxis = new AxisAngle4f((float) Math.PI / 2, 1, 0, 0);\n q.set(angleAxis);\n } else { // All zero's. Just set to identity quaternion\n q.identity();\n }\n } else {\n d.normalize();\n Vector3f up = new Vector3f(0, 1, 0);\n Vector3f s = new Vector3f();\n d.cross(up, s);\n s.normalize();\n Vector3f u = new Vector3f();\n d.cross(s, u);\n u.normalize();\n Matrix4f matrix = new Matrix4f(s.x, s.y, s.z, 0, u.x, u.y, u.z, 0, d.x,\n d.y, d.z, 0, 0, 0, 0, 1);\n q.setFromNormalized(matrix);\n }\n return q;\n }"
] | [
"private void emitSuiteEnd(AggregatedSuiteResultEvent e, int suitesCompleted) throws IOException {\n assert showSuiteSummary;\n\n final StringBuilder b = new StringBuilder();\n final int totalErrors = this.totalErrors.addAndGet(e.isSuccessful() ? 0 : 1);\n b.append(String.format(Locale.ROOT, \"%sCompleted [%d/%d%s]%s in %.2fs, \",\n shortTimestamp(e.getStartTimestamp() + e.getExecutionTime()),\n suitesCompleted,\n totalSuites,\n totalErrors == 0 ? \"\" : \" (\" + totalErrors + \"!)\",\n e.getSlave().slaves > 1 ? \" on J\" + e.getSlave().id : \"\",\n e.getExecutionTime() / 1000.0d));\n b.append(e.getTests().size()).append(Pluralize.pluralize(e.getTests().size(), \" test\"));\n\n int failures = e.getFailureCount();\n if (failures > 0) {\n b.append(\", \").append(failures).append(Pluralize.pluralize(failures, \" failure\"));\n }\n\n int errors = e.getErrorCount();\n if (errors > 0) {\n b.append(\", \").append(errors).append(Pluralize.pluralize(errors, \" error\"));\n }\n\n int ignored = e.getIgnoredCount();\n if (ignored > 0) {\n b.append(\", \").append(ignored).append(\" skipped\");\n }\n\n if (!e.isSuccessful()) {\n b.append(FAILURE_STRING);\n }\n\n b.append(\"\\n\");\n logShort(b, false);\n }",
"public HalfEdge getEdge(int i) {\n HalfEdge he = he0;\n while (i > 0) {\n he = he.next;\n i--;\n }\n while (i < 0) {\n he = he.prev;\n i++;\n }\n return he;\n }",
"public ParallelTaskBuilder prepareHttpHead(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.HEAD);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }",
"@Beta\n public MSICredentials withIdentityId(String identityId) {\n this.identityId = identityId;\n this.clientId = null;\n this.objectId = null;\n return this;\n }",
"public static Integer convertPathIdentifier(String identifier, Integer profileId) throws Exception {\n Integer pathId = -1;\n try {\n pathId = Integer.parseInt(identifier);\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n if (profileId == null)\n throw new Exception(\"A profileId must be specified\");\n\n pathId = PathOverrideService.getInstance().getPathId(identifier, profileId);\n }\n\n return pathId;\n }",
"public List<CmsCategory> getTopItems() {\n\n List<CmsCategory> categories = new ArrayList<CmsCategory>();\n String matcher = Pattern.quote(m_mainCategoryPath) + \"[^/]*/\";\n for (CmsCategory category : m_categories) {\n if (category.getPath().matches(matcher)) {\n categories.add(category);\n }\n }\n return categories;\n }",
"protected NodeData createBodyStyle()\n {\n NodeData ret = createBlockStyle();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"background-color\", tf.createColor(255, 255, 255)));\n return ret;\n }",
"public double loglikelihood(List<IN> lineInfos) {\r\n double cll = 0.0;\r\n\r\n for (int i = 0; i < lineInfos.size(); i++) {\r\n Datum<String, String> d = makeDatum(lineInfos, i, featureFactory);\r\n Counter<String> c = classifier.logProbabilityOf(d);\r\n\r\n double total = Double.NEGATIVE_INFINITY;\r\n for (String s : c.keySet()) {\r\n total = SloppyMath.logAdd(total, c.getCount(s));\r\n }\r\n cll -= c.getCount(d.label()) - total;\r\n }\r\n // quadratic prior\r\n // HN: TODO: add other priors\r\n\r\n if (classifier instanceof LinearClassifier) {\r\n double sigmaSq = flags.sigma * flags.sigma;\r\n LinearClassifier<String, String> lc = (LinearClassifier<String, String>)classifier;\r\n for (String feature: lc.features()) {\r\n for (String classLabel: classIndex) {\r\n double w = lc.weight(feature, classLabel);\r\n cll += w * w / 2.0 / sigmaSq;\r\n }\r\n }\r\n }\r\n return cll;\r\n }",
"public ItemRequest<Story> update(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"PUT\");\n }"
] |
A convenience method for creating an immutable list.
@param self a Set
@return an immutable Set
@see java.util.Collections#unmodifiableSet(java.util.Set)
@since 1.0 | [
"public static <T> Set<T> asImmutable(Set<? extends T> self) {\n return Collections.unmodifiableSet(self);\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}",
"public static <T extends WindupVertexFrame> WindupVertexFrame removeTypeFromModel(GraphContext graphContext, WindupVertexFrame frame, Class<T> type)\n {\n Vertex vertex = frame.getElement();\n graphContext.getGraphTypeManager().removeTypeFromElement(type, vertex);\n return graphContext.getFramed().frameElement(vertex, WindupVertexFrame.class);\n }",
"protected ValueContainer[] getKeyValues(PersistenceBroker broker, ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getKeyValues(cld, obj);\r\n }",
"public static void addHeaders(BoundRequestBuilder builder,\n Map<String, String> headerMap) {\n for (Entry<String, String> entry : headerMap.entrySet()) {\n String name = entry.getKey();\n String value = entry.getValue();\n builder.addHeader(name, value);\n }\n\n }",
"private static boolean isBinary(InputStream in) {\n try {\n int size = in.available();\n if (size > 1024) size = 1024;\n byte[] data = new byte[size];\n in.read(data);\n in.close();\n\n int ascii = 0;\n int other = 0;\n\n for (int i = 0; i < data.length; i++) {\n byte b = data[i];\n if (b < 0x09) return true;\n\n if (b == 0x09 || b == 0x0A || b == 0x0C || b == 0x0D) ascii++;\n else if (b >= 0x20 && b <= 0x7E) ascii++;\n else other++;\n }\n\n return other != 0 && 100 * other / (ascii + other) > 95;\n\n } catch (IOException e) {\n throw E.ioException(e);\n }\n }",
"public static float[] getBoundingSize(GVRMesh mesh) {\n final float [] dim = new float[3];\n final float [] vertices = mesh.getVertices();\n final int vsize = vertices.length;\n float minx = Integer.MAX_VALUE;\n float miny = Integer.MAX_VALUE;\n float minz = Integer.MAX_VALUE;\n float maxx = Integer.MIN_VALUE;\n float maxy = Integer.MIN_VALUE;\n float maxz = Integer.MIN_VALUE;\n\n for (int i = 0; i < vsize; i += 3) {\n if (vertices[i] < minx) minx = vertices[i];\n if (vertices[i] > maxx) maxx = vertices[i];\n\n if (vertices[i + 1] < miny) miny = vertices[i + 1];\n if (vertices[i + 1] > maxy) maxy = vertices[i + 1];\n\n if (vertices[i + 2] < minz) minz = vertices[i + 2];\n if (vertices[i + 2] > maxz) maxz = vertices[i + 2];\n }\n\n dim[0] = maxx - minx;\n dim[1] = maxy - miny;\n dim[2] = maxz - minz;\n\n return dim;\n }",
"private ServerDetails createInitialResolveDetailsFromDeployDetails(ServerDetails deployerDetails) {\n RepositoryConf oldResolveRepositoryConfig = deployerDetails.getResolveReleaseRepository();\n RepositoryConf oldSnapshotResolveRepositoryConfig = deployerDetails.getResolveSnapshotRepository();\n RepositoryConf resolverReleaseRepos = oldResolveRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldResolveRepositoryConfig;\n RepositoryConf resolveSnapshotRepos = oldSnapshotResolveRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldSnapshotResolveRepositoryConfig;\n return new ServerDetails(deployerDetails.getArtifactoryName(), deployerDetails.getArtifactoryUrl(),\n null, null, resolverReleaseRepos, resolveSnapshotRepos, null, null);\n }",
"private void handleIncomingMessage(SerialMessage incomingMessage) {\n\t\t\n\t\tlogger.debug(\"Incoming message to process\");\n\t\tlogger.debug(incomingMessage.toString());\n\t\t\n\t\tswitch (incomingMessage.getMessageType()) {\n\t\t\tcase Request:\n\t\t\t\thandleIncomingRequestMessage(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tcase Response:\n\t\t\t\thandleIncomingResponseMessage(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogger.warn(\"Unsupported incomingMessageType: 0x%02X\", incomingMessage.getMessageType());\n\t\t}\n\t}",
"public boolean needMerge(@NotNull final BasePage left, @NotNull final BasePage right) {\n final int leftSize = left.getSize();\n final int rightSize = right.getSize();\n return leftSize == 0 || rightSize == 0 ||\n leftSize + rightSize <= (((isDupTree(left) ? getDupPageMaxSize() : getPageMaxSize()) * 7) >> 3);\n }"
] |
Use this API to fetch all the sslpolicylabel resources that are configured on netscaler. | [
"public static sslpolicylabel[] get(nitro_service service) throws Exception{\n\t\tsslpolicylabel obj = new sslpolicylabel();\n\t\tsslpolicylabel[] response = (sslpolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public final static void appendDecEntity(final StringBuilder out, final char value)\n {\n out.append(\"&#\");\n out.append((int)value);\n out.append(';');\n }",
"static DisplayMetrics getDisplayMetrics(final Context context) {\n final WindowManager\n windowManager =\n (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n final DisplayMetrics metrics = new DisplayMetrics();\n windowManager.getDefaultDisplay().getMetrics(metrics);\n return metrics;\n }",
"private FieldType addUserDefinedField(FieldTypeClass fieldType, UserFieldDataType dataType, String name)\n {\n FieldType field = null;\n \n try\n {\n switch (fieldType)\n {\n case TASK:\n {\n do\n {\n field = m_taskUdfCounters.nextField(TaskField.class, dataType);\n }\n while (RESERVED_TASK_FIELDS.contains(field));\n\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n\n break;\n }\n \n case RESOURCE:\n {\n field = m_resourceUdfCounters.nextField(ResourceField.class, dataType);\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n break;\n }\n \n case ASSIGNMENT:\n {\n field = m_assignmentUdfCounters.nextField(AssignmentField.class, dataType);\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n break;\n }\n \n default:\n {\n break;\n }\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 \n return field;\n }",
"public String clean(String value) {\n String orig = value;\n \n // check if there's a + before the first digit\n boolean initialplus = findPlus(value);\n \n // remove everything but digits\n value = sub.clean(value);\n if (value == null)\n return null;\n\n // check for initial '00'\n boolean zerozero = !initialplus && value.startsWith(\"00\");\n if (zerozero)\n value = value.substring(2); // strip off the zeros\n\n // look for country code\n CountryCode ccode = findCountryCode(value);\n if (ccode == null) {\n // no country code, let's do what little we can\n if (initialplus || zerozero)\n return orig; // this number is messed up. dare not touch\n return value;\n\n } else {\n value = value.substring(ccode.getPrefix().length()); // strip off ccode\n if (ccode.getStripZero() && value.startsWith(\"0\"))\n value = value.substring(1); // strip the zero\n\n if (ccode.isRightFormat(value))\n return \"+\" + ccode.getPrefix() + \" \" + value;\n else\n return orig; // don't dare touch this\n }\n }",
"private static void processTaskFilter(ProjectFile project, Filter filter)\n {\n for (Task task : project.getTasks())\n {\n if (filter.evaluate(task, null))\n {\n System.out.println(task.getID() + \",\" + task.getUniqueID() + \",\" + task.getName());\n }\n }\n }",
"private void handleTextWebSocketFrameInternal(TextWebSocketFrame frame, ChannelHandlerContext ctx) {\n\t\tif (logger.isTraceEnabled()) {\n\t\t\tlogger.trace(String.format(\"%s received %s\", ctx.channel(), frame.text()));\n\t\t}\n\n\t\taddTraceForFrame(frame, \"text\");\n\t\tctx.channel().write(new TextWebSocketFrame(\"Echo: \" + frame.text()));\n\t}",
"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 synchronized int put(byte[] src, int off, int len) {\n if (available == capacity) {\n return 0;\n }\n\n // limit is last index to put + 1\n int limit = idxPut < idxGet ? idxGet : capacity;\n int count = Math.min(limit - idxPut, len);\n System.arraycopy(src, off, buffer, idxPut, count);\n idxPut += count;\n\n if (idxPut == capacity) {\n // Array end reached, check if we have more\n int count2 = Math.min(len - count, idxGet);\n if (count2 > 0) {\n System.arraycopy(src, off + count, buffer, 0, count2);\n idxPut = count2;\n count += count2;\n } else {\n idxPut = 0;\n }\n }\n available += count;\n return count;\n }",
"@Nullable\n public T getItem(final int position) {\n if (position < 0 || position >= mObjects.size()) {\n return null;\n }\n return mObjects.get(position);\n }"
] |
Answer the counted size
@return int | [
"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 }"
] | [
"private void logTimeTakenByRuleProvider(GraphContext graphContext, Context context, int ruleIndex, int timeTaken)\n {\n AbstractRuleProvider ruleProvider = (AbstractRuleProvider) context.get(RuleMetadataType.RULE_PROVIDER);\n if (ruleProvider == null)\n return;\n\n if (!timeTakenByProvider.containsKey(ruleProvider))\n {\n RuleProviderExecutionStatisticsModel model = new RuleProviderExecutionStatisticsService(graphContext)\n .create();\n model.setRuleIndex(ruleIndex);\n model.setRuleProviderID(ruleProvider.getMetadata().getID());\n model.setTimeTaken(timeTaken);\n\n timeTakenByProvider.put(ruleProvider, model.getElement().id());\n }\n else\n {\n RuleProviderExecutionStatisticsService service = new RuleProviderExecutionStatisticsService(graphContext);\n RuleProviderExecutionStatisticsModel model = service.getById(timeTakenByProvider.get(ruleProvider));\n int prevTimeTaken = model.getTimeTaken();\n model.setTimeTaken(prevTimeTaken + timeTaken);\n }\n logTimeTakenByPhase(graphContext, ruleProvider.getMetadata().getPhase(), timeTaken);\n }",
"public static ServerSetup[] verbose(ServerSetup[] serverSetups) {\r\n ServerSetup[] copies = new ServerSetup[serverSetups.length];\r\n for (int i = 0; i < serverSetups.length; i++) {\r\n copies[i] = serverSetups[i].createCopy().setVerbose(true);\r\n }\r\n return copies;\r\n }",
"public ArrayList<Double> segmentBaselineCost(ProjectFile file, List<TimephasedCost> cost, TimescaleUnits rangeUnits, ArrayList<DateRange> dateList)\n {\n return segmentCost(file.getBaselineCalendar(), cost, rangeUnits, dateList);\n }",
"private void recordMount(SlotReference slot) {\n if (mediaMounts.add(slot)) {\n deliverMountUpdate(slot, true);\n }\n if (!mediaDetails.containsKey(slot)) {\n try {\n VirtualCdj.getInstance().sendMediaQuery(slot);\n } catch (Exception e) {\n logger.warn(\"Problem trying to request media details for \" + slot, e);\n }\n }\n }",
"public static dnspolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tdnspolicylabel obj = new dnspolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tdnspolicylabel response = (dnspolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public PayloadBuilder sound(final String sound) {\n if (sound != null) {\n aps.put(\"sound\", sound);\n } else {\n aps.remove(\"sound\");\n }\n return this;\n }",
"public UUID getUUID(FastTrackField type)\n {\n String value = getString(type);\n UUID result = null;\n if (value != null && !value.isEmpty() && value.length() >= 36)\n {\n if (value.startsWith(\"{\"))\n {\n value = value.substring(1, value.length() - 1);\n }\n if (value.length() > 16)\n {\n value = value.substring(0, 36);\n }\n result = UUID.fromString(value);\n }\n return result;\n }",
"private String swapStore(String storeName, String directory) throws VoldemortException {\n\n ReadOnlyStorageEngine store = getReadOnlyStorageEngine(metadataStore,\n storeRepository,\n storeName);\n\n if(!Utils.isReadableDir(directory))\n throw new VoldemortException(\"Store directory '\" + directory\n + \"' is not a readable directory.\");\n\n String currentDirPath = store.getCurrentDirPath();\n\n logger.info(\"Swapping RO store '\" + storeName + \"' to version directory '\" + directory\n + \"'\");\n store.swapFiles(directory);\n logger.info(\"Swapping swapped RO store '\" + storeName + \"' to version directory '\"\n + directory + \"'\");\n\n return currentDirPath;\n }",
"public static base_response unset(nitro_service client, sslcertkey resource, String[] args) throws Exception{\n\t\tsslcertkey unsetresource = new sslcertkey();\n\t\tunsetresource.certkey = resource.certkey;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}"
] |
Implement the persistence handler for storing the user properties. | [
"void persist(final String key, final String value, final boolean enableDisableMode, final boolean disable, final File file, final String realm) throws IOException, StartException {\n final PropertiesFileLoader propertiesHandler = realm == null ? new PropertiesFileLoader(file.getAbsolutePath(), null) :\n new UserPropertiesFileLoader(file.getAbsolutePath(), null);\n try {\n propertiesHandler.start(null);\n if (realm != null) {\n ((UserPropertiesFileLoader) propertiesHandler).setRealmName(realm);\n }\n Properties prob = propertiesHandler.getProperties();\n if (value != null) {\n prob.setProperty(key, value);\n }\n if (enableDisableMode) {\n prob.setProperty(key + \"!disable\", String.valueOf(disable));\n }\n propertiesHandler.persistProperties();\n } finally {\n propertiesHandler.stop(null);\n }\n }"
] | [
"protected synchronized void stealExistingAllocations(){\r\n\t\t\r\n\t\tfor (ConnectionHandle handle: this.threadFinalizableRefs.keySet()){\r\n\t\t\t// if they're not in use, pretend they are in use now and close them off.\r\n\t\t\t// this method assumes that the strategy has been flipped back to non-caching mode\r\n\t\t\t// prior to this method invocation.\r\n\t\t\tif (handle.logicallyClosed.compareAndSet(true, false)){ \r\n\t\t\t\ttry {\r\n\t\t\t\t\tthis.pool.releaseConnection(handle);\r\n\t\t\t\t} catch (SQLException e) {\r\n\t\t\t\t\tlogger.error(\"Error releasing connection\", e);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (this.warnApp.compareAndSet(false, true)){ // only issue warning once.\r\n\t\t\tlogger.warn(\"Cached strategy chosen, but more threads are requesting a connection than are configured. Switching permanently to default strategy.\");\r\n\t\t}\r\n\t\tthis.threadFinalizableRefs.clear();\r\n\t\t\r\n\t}",
"public void init(Map<String, String> testConfig, Map<String, String> hiveVars) {\n\n context.init();\n\n HiveConf hiveConf = context.getHiveConf();\n\n // merge test case properties with hive conf before HiveServer is started.\n for (Map.Entry<String, String> property : testConfig.entrySet()) {\n hiveConf.set(property.getKey(), property.getValue());\n }\n\n try {\n hiveServer2 = new HiveServer2();\n hiveServer2.init(hiveConf);\n\n // Locate the ClIService in the HiveServer2\n for (Service service : hiveServer2.getServices()) {\n if (service instanceof CLIService) {\n client = (CLIService) service;\n }\n }\n\n Preconditions.checkNotNull(client, \"ClIService was not initialized by HiveServer2\");\n\n sessionHandle = client.openSession(\"noUser\", \"noPassword\", null);\n\n SessionState sessionState = client.getSessionManager().getSession(sessionHandle).getSessionState();\n currentSessionState = sessionState;\n currentSessionState.setHiveVariables(hiveVars);\n } catch (Exception e) {\n throw new IllegalStateException(\"Failed to create HiveServer :\" + e.getMessage(), e);\n }\n\n // Ping hive server before we do anything more with it! If validation\n // is switched on, this will fail if metastorage is not set up properly\n pingHiveServer();\n }",
"@Override\n\tpublic boolean retainAll(Collection<?> collection) {\n\t\tif (dao == null) {\n\t\t\treturn false;\n\t\t}\n\t\tboolean changed = false;\n\t\tCloseableIterator<T> iterator = closeableIterator();\n\t\ttry {\n\t\t\twhile (iterator.hasNext()) {\n\t\t\t\tT data = iterator.next();\n\t\t\t\tif (!collection.contains(data)) {\n\t\t\t\t\titerator.remove();\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn changed;\n\t\t} finally {\n\t\t\tIOUtils.closeQuietly(iterator);\n\t\t}\n\t}",
"public static nsrollbackcmd get(nitro_service service) throws Exception{\n\t\tnsrollbackcmd obj = new nsrollbackcmd();\n\t\tnsrollbackcmd[] response = (nsrollbackcmd[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public void setExplicitTime(String hours, String minutes, String seconds, String amPm, String zoneString) {\n int hoursInt = Integer.parseInt(hours);\n int minutesInt = minutes != null ? Integer.parseInt(minutes) : 0;\n assert(amPm == null || amPm.equals(AM) || amPm.equals(PM));\n assert(hoursInt >= 0);\n assert(minutesInt >= 0 && minutesInt < 60); \n \n markTimeInvocation(amPm);\n \n // reset milliseconds to 0\n _calendar.set(Calendar.MILLISECOND, 0);\n \n // if no explicit zone is given, we use our own\n TimeZone zone = null;\n if(zoneString != null) {\n if(zoneString.startsWith(PLUS) || zoneString.startsWith(MINUS)) {\n zoneString = GMT + zoneString;\n }\n zone = TimeZone.getTimeZone(zoneString);\n }\n \n _calendar.setTimeZone(zone != null ? zone : _defaultTimeZone);\n \n _calendar.set(Calendar.HOUR_OF_DAY, hoursInt);\n // hours greater than 12 are in 24-hour time\n if(hoursInt <= 12) {\n int amPmInt = amPm == null ? \n (hoursInt >= 12 ? Calendar.PM : Calendar.AM) :\n amPm.equals(PM) ? Calendar.PM : Calendar.AM;\n _calendar.set(Calendar.AM_PM, amPmInt);\n \n // calendar is whacky at 12 o'clock (must use 0)\n if(hoursInt == 12) hoursInt = 0;\n _calendar.set(Calendar.HOUR, hoursInt);\n }\n \n if(seconds != null) {\n int secondsInt = Integer.parseInt(seconds);\n assert(secondsInt >= 0 && secondsInt < 60); \n _calendar.set(Calendar.SECOND, secondsInt);\n }\n else {\n _calendar.set(Calendar.SECOND, 0);\n }\n \n _calendar.set(Calendar.MINUTE, minutesInt);\n }",
"public static Provider getCurrentProvider(boolean useSwingEventQueue) {\n Provider provider;\n if (Platform.isX11()) {\n provider = new X11Provider();\n } else if (Platform.isWindows()) {\n provider = new WindowsProvider();\n } else if (Platform.isMac()) {\n provider = new CarbonProvider();\n } else {\n LOGGER.warn(\"No suitable provider for \" + System.getProperty(\"os.name\"));\n return null;\n }\n provider.setUseSwingEventQueue(useSwingEventQueue);\n provider.init();\n return provider;\n\n }",
"public static <T> T[] concat(T firstElement, T... array) {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT[] result = (T[]) Array.newInstance( firstElement.getClass(), 1 + array.length );\n\t\tresult[0] = firstElement;\n\t\tSystem.arraycopy( array, 0, result, 1, array.length );\n\n\t\treturn result;\n\t}",
"private void clearBeatGrids(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(hotCache.keySet())) {\n if (deck.player == player) {\n hotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverBeatGridUpdate(player, null); // Inform listeners the beat grid is gone.\n }\n }\n }\n }",
"public static final boolean isInside(int x, int y, Rect box) {\n return (box.x < x && x < box.x + box.w && box.y < y && y < box.y + box.h);\n }"
] |
Writes one or more String columns as a line to the CsvWriter.
@param columns
the columns to write
@throws IllegalArgumentException
if columns.length == 0
@throws IOException
If an I/O error occurs
@throws NullPointerException
if columns is null | [
"protected void writeRow(final String... columns) throws IOException {\n\t\t\n\t\tif( columns == null ) {\n\t\t\tthrow new NullPointerException(String.format(\"columns to write should not be null on line %d\", lineNumber));\n\t\t} else if( columns.length == 0 ) {\n\t\t\tthrow new IllegalArgumentException(String.format(\"columns to write should not be empty on line %d\",\n\t\t\t\tlineNumber));\n\t\t}\n\t\t\n\t\tStringBuilder builder = new StringBuilder();\n\t\tfor( int i = 0; i < columns.length; i++ ) {\n\t\t\t\n\t\t\tcolumnNumber = i + 1; // column no used by CsvEncoder\n\t\t\t\n\t\t\tif( i > 0 ) {\n\t\t\t\tbuilder.append((char) preference.getDelimiterChar()); // delimiter\n\t\t\t}\n\t\t\t\n\t\t\tfinal String csvElement = columns[i];\n\t\t\tif( csvElement != null ) {\n\t\t\t\tfinal CsvContext context = new CsvContext(lineNumber, rowNumber, columnNumber);\n\t\t\t\tfinal String escapedCsv = encoder.encode(csvElement, context, preference);\n\t\t\t\tbuilder.append(escapedCsv);\n\t\t\t\tlineNumber = context.getLineNumber(); // line number can increment when encoding multi-line columns\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tbuilder.append(preference.getEndOfLineSymbols()); // EOL\n\t\twriter.write(builder.toString());\n\t}"
] | [
"private boolean hasNullifiedFK(FieldDescriptor[] fkFieldDescriptors, Object[] fkValues)\r\n {\r\n boolean result = true;\r\n for (int i = 0; i < fkValues.length; i++)\r\n {\r\n if (!pb.serviceBrokerHelper().representsNull(fkFieldDescriptors[i], fkValues[i]))\r\n {\r\n result = false;\r\n break;\r\n }\r\n }\r\n return result;\r\n }",
"public void search(String query) {\n final Query newQuery = searcher.getQuery().setQuery(query);\n searcher.setQuery(newQuery).search();\n }",
"public static boolean compareAnnotatedTypes(AnnotatedType<?> t1, AnnotatedType<?> t2) {\n if (!t1.getJavaClass().equals(t2.getJavaClass())) {\n return false;\n }\n if (!compareAnnotated(t1, t2)) {\n return false;\n }\n\n if (t1.getFields().size() != t2.getFields().size()) {\n return false;\n }\n Map<Field, AnnotatedField<?>> fields = new HashMap<Field, AnnotatedField<?>>();\n for (AnnotatedField<?> f : t2.getFields()) {\n fields.put(f.getJavaMember(), f);\n }\n for (AnnotatedField<?> f : t1.getFields()) {\n if (fields.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedField(f, fields.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n\n if (t1.getMethods().size() != t2.getMethods().size()) {\n return false;\n }\n Map<Method, AnnotatedMethod<?>> methods = new HashMap<Method, AnnotatedMethod<?>>();\n for (AnnotatedMethod<?> f : t2.getMethods()) {\n methods.put(f.getJavaMember(), f);\n }\n for (AnnotatedMethod<?> f : t1.getMethods()) {\n if (methods.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, methods.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n if (t1.getConstructors().size() != t2.getConstructors().size()) {\n return false;\n }\n Map<Constructor<?>, AnnotatedConstructor<?>> constructors = new HashMap<Constructor<?>, AnnotatedConstructor<?>>();\n for (AnnotatedConstructor<?> f : t2.getConstructors()) {\n constructors.put(f.getJavaMember(), f);\n }\n for (AnnotatedConstructor<?> f : t1.getConstructors()) {\n if (constructors.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, constructors.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n return true;\n\n }",
"public BoxFile.Info getFileInfo(String fileID) {\n URL url = FILE_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFile file = new BoxFile(this.api, jsonObject.get(\"id\").asString());\n return file.new Info(response.getJSON());\n }",
"@Override\n\tpublic void format(final StringBuffer sbuf, final LoggingEvent event) {\n\t\tfor (int i = 0; i < patternConverters.length; i++) {\n\t\t\tfinal int startField = sbuf.length();\n\t\t\tpatternConverters[i].format(event, sbuf);\n\t\t\tpatternFields[i].format(startField, sbuf);\n\t\t}\n\t}",
"public static base_responses delete(nitro_service client, route6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\troute6 deleteresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new route6();\n\t\t\t\tdeleteresources[i].network = resources[i].network;\n\t\t\t\tdeleteresources[i].gateway = resources[i].gateway;\n\t\t\t\tdeleteresources[i].vlan = resources[i].vlan;\n\t\t\t\tdeleteresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"private void handleIncomingMessage(SerialMessage incomingMessage) {\n\t\t\n\t\tlogger.debug(\"Incoming message to process\");\n\t\tlogger.debug(incomingMessage.toString());\n\t\t\n\t\tswitch (incomingMessage.getMessageType()) {\n\t\t\tcase Request:\n\t\t\t\thandleIncomingRequestMessage(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tcase Response:\n\t\t\t\thandleIncomingResponseMessage(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogger.warn(\"Unsupported incomingMessageType: 0x%02X\", incomingMessage.getMessageType());\n\t\t}\n\t}",
"private List<String> parseParams(String param) {\n\t\tAssert.hasText(param, \"param must not be empty nor null\");\n\t\tList<String> paramsToUse = new ArrayList<>();\n\t\tMatcher regexMatcher = DEPLOYMENT_PARAMS_PATTERN.matcher(param);\n\t\tint start = 0;\n\t\twhile (regexMatcher.find()) {\n\t\t\tString p = removeQuoting(param.substring(start, regexMatcher.start()).trim());\n\t\t\tif (StringUtils.hasText(p)) {\n\t\t\t\tparamsToUse.add(p);\n\t\t\t}\n\t\t\tstart = regexMatcher.start();\n\t\t}\n\t\tif (param != null && param.length() > 0) {\n\t\t\tString p = removeQuoting(param.substring(start, param.length()).trim());\n\t\t\tif (StringUtils.hasText(p)) {\n\t\t\t\tparamsToUse.add(p);\n\t\t\t}\n\t\t}\n\t\treturn paramsToUse;\n\t}",
"public boolean runOnMainThreadNext(Runnable r) {\n assert handler != null;\n\n if (!sanityCheck(\"runOnMainThreadNext \" + r)) {\n return false;\n }\n return handler.post(r);\n }"
] |
Obtains a local date in Symmetry454 calendar system from the
proleptic-year, month-of-year and day-of-month fields.
@param prolepticYear the proleptic-year
@param month the month-of-year
@param dayOfMonth the day-of-month
@return the Symmetry454 local date, not null
@throws DateTimeException if unable to create the date | [
"@Override\n public Symmetry454Date date(int prolepticYear, int month, int dayOfMonth) {\n return Symmetry454Date.of(prolepticYear, month, dayOfMonth);\n }"
] | [
"public static <T> T createProxy(final Class<T> proxyInterface) {\n\t\tif( proxyInterface == null ) {\n\t\t\tthrow new NullPointerException(\"proxyInterface should not be null\");\n\t\t}\n\t\treturn proxyInterface.cast(Proxy.newProxyInstance(proxyInterface.getClassLoader(),\n\t\t\tnew Class[] { proxyInterface }, new BeanInterfaceProxy()));\n\t}",
"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 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 }",
"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 }",
"private void initKeySetForXmlBundle() {\n\n // consider only available locales\n for (Locale l : m_locales) {\n if (m_xmlBundle.hasLocale(l)) {\n Set<Object> keys = new HashSet<Object>();\n for (I_CmsXmlContentValue msg : m_xmlBundle.getValueSequence(\"Message\", l).getValues()) {\n String msgpath = msg.getPath();\n keys.add(m_xmlBundle.getStringValue(m_cms, msgpath + \"/Key\", l));\n }\n m_keyset.updateKeySet(null, keys);\n }\n }\n\n }",
"public static double findMax( double[] u, int startU , int length ) {\n double max = -1;\n\n int index = startU*2;\n int stopIndex = (startU + length)*2;\n for( ; index < stopIndex;) {\n double real = u[index++];\n double img = u[index++];\n\n double val = real*real + img*img;\n\n if( val > max ) {\n max = val;\n }\n }\n\n return Math.sqrt(max);\n }",
"public static boolean isDelayedQueue(final Jedis jedis, final String key) {\n return ZSET.equalsIgnoreCase(jedis.type(key));\n }",
"public static boolean containsAllQualifiers(Set<QualifierInstance> requiredQualifiers, Set<QualifierInstance> qualifiers) {\n return qualifiers.containsAll(requiredQualifiers);\n }",
"public static long count(nitro_service service, String zonename) throws Exception{\n\t\tdnszone_domain_binding obj = new dnszone_domain_binding();\n\t\tobj.set_zonename(zonename);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tdnszone_domain_binding response[] = (dnszone_domain_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}"
] |
digest message with MD5
@param source message
@return 32 bit MD5 value (lower case) | [
"public static String md5(byte[] source) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(source);\n byte tmp[] = md.digest();\n char str[] = new char[32];\n int k = 0;\n for (byte b : tmp) {\n str[k++] = hexDigits[b >>> 4 & 0xf];\n str[k++] = hexDigits[b & 0xf];\n }\n return new String(str);\n\n } catch (Exception e) {\n throw new IllegalArgumentException(e);\n }\n }"
] | [
"public void addExtraInfo(String key, Object value) {\n // Turn extraInfo into map\n Map<String, Object> infoMap = (HashMap<String, Object>)getMapFromJSON(extraInfo);\n // Add value\n infoMap.put(key, value);\n\n // Turn back into string\n extraInfo = getJSONFromMap(infoMap);\n }",
"private static CmsObject adjustSiteRootIfNecessary(final CmsObject cms, final CmsModule module)\n throws CmsException {\n\n CmsObject cmsClone;\n if ((null == module.getSite()) || cms.getRequestContext().getSiteRoot().equals(module.getSite())) {\n cmsClone = cms;\n } else {\n cmsClone = OpenCms.initCmsObject(cms);\n cmsClone.getRequestContext().setSiteRoot(module.getSite());\n }\n\n return cmsClone;\n }",
"public void logWarning(final String message) {\n messageQueue.add(new LogEntry() {\n @Override\n public String getMessage() {\n return message;\n }\n });\n }",
"public static vpnglobal_auditnslogpolicy_binding[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tvpnglobal_auditnslogpolicy_binding obj = new vpnglobal_auditnslogpolicy_binding();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tvpnglobal_auditnslogpolicy_binding[] response = (vpnglobal_auditnslogpolicy_binding[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"public String[] getAttributeNames()\r\n {\r\n Set keys = (attributeMap == null ? new HashSet() : attributeMap.keySet());\r\n String[] result = new String[keys.size()];\r\n\r\n keys.toArray(result);\r\n return result;\r\n }",
"public static HashMap<StoreDefinition, Integer> getUniqueStoreDefinitionsWithCounts(List<StoreDefinition> storeDefs) {\n\n HashMap<StoreDefinition, Integer> uniqueStoreDefs = Maps.newHashMap();\n for(StoreDefinition storeDef: storeDefs) {\n if(uniqueStoreDefs.isEmpty()) {\n uniqueStoreDefs.put(storeDef, 1);\n } else {\n StoreDefinition sameStore = null;\n\n // Go over all the other stores to find if this is unique\n for(StoreDefinition uniqueStoreDef: uniqueStoreDefs.keySet()) {\n if(uniqueStoreDef.getReplicationFactor() == storeDef.getReplicationFactor()\n && uniqueStoreDef.getRoutingStrategyType()\n .compareTo(storeDef.getRoutingStrategyType()) == 0) {\n\n // Further check for the zone routing case\n if(uniqueStoreDef.getRoutingStrategyType()\n .compareTo(RoutingStrategyType.ZONE_STRATEGY) == 0) {\n boolean zonesSame = true;\n for(int zoneId: uniqueStoreDef.getZoneReplicationFactor().keySet()) {\n if(storeDef.getZoneReplicationFactor().get(zoneId) == null\n || storeDef.getZoneReplicationFactor().get(zoneId) != uniqueStoreDef.getZoneReplicationFactor()\n .get(zoneId)) {\n zonesSame = false;\n break;\n }\n }\n if(zonesSame) {\n sameStore = uniqueStoreDef;\n }\n } else {\n sameStore = uniqueStoreDef;\n }\n\n if(sameStore != null) {\n // Bump up the count\n int currentCount = uniqueStoreDefs.get(sameStore);\n uniqueStoreDefs.put(sameStore, currentCount + 1);\n break;\n }\n }\n }\n\n if(sameStore == null) {\n // New store\n uniqueStoreDefs.put(storeDef, 1);\n }\n }\n }\n\n return uniqueStoreDefs;\n }",
"public void setBean(String name, Object object) {\n\t\tBean bean = beans.get(name);\n\t\tif (null == bean) {\n\t\t\tbean = new Bean();\n\t\t\tbeans.put(name, bean);\n\t\t}\n\t\tbean.object = object;\n\t}",
"public static void startTrack(final Object... args){\r\n if(isClosed){ return; }\r\n //--Create Record\r\n final int len = args.length == 0 ? 0 : args.length-1;\r\n final Object content = args.length == 0 ? \"\" : args[len];\r\n final Object[] tags = new Object[len];\r\n final StackTraceElement ste = getStackTrace();\r\n final long timestamp = System.currentTimeMillis();\r\n System.arraycopy(args,0,tags,0,len);\r\n //--Create Task\r\n final long threadID = Thread.currentThread().getId();\r\n final Runnable startTrack = new Runnable(){\r\n public void run(){\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n Record toPass = new Record(content,tags,depth,ste,timestamp);\r\n depth += 1;\r\n titleStack.push(args.length == 0 ? \"\" : args[len].toString());\r\n handlers.process(toPass, MessageType.START_TRACK, depth, toPass.timesstamp);\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n }\r\n };\r\n //--Run Task\r\n if(isThreaded){\r\n //(case: multithreaded)\r\n long threadId = Thread.currentThread().getId();\r\n attemptThreadControl( threadId, startTrack );\r\n } else {\r\n //(case: no threading)\r\n startTrack.run();\r\n }\r\n }",
"@Nullable\n public ByteIterable get(@NotNull final Transaction txn, @NotNull final ByteIterable first) {\n return this.first.get(txn, first);\n }"
] |
return a prepared Update Statement fitting to the given ClassDescriptor | [
"public PreparedStatement getUpdateStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getUpdateStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }"
] | [
"public static final Bytes of(String s, Charset c) {\n Objects.requireNonNull(s);\n Objects.requireNonNull(c);\n if (s.isEmpty()) {\n return EMPTY;\n }\n byte[] data = s.getBytes(c);\n return new Bytes(data);\n }",
"protected void addFreeConnection(ConnectionHandle connectionHandle) throws SQLException{\r\n\t\tconnectionHandle.setOriginatingPartition(this);\r\n\t\t// assume success to avoid racing where we insert an item in a queue and having that item immediately\r\n\t\t// taken and closed off thus decrementing the created connection count.\r\n\t\tupdateCreatedConnections(1);\r\n\t\tif (!this.disableTracking){\r\n\t\t\ttrackConnectionFinalizer(connectionHandle); \r\n\t\t}\r\n\t\t\r\n\t\t// the instant the following line is executed, consumers can start making use of this \r\n\t\t// connection.\r\n\t\tif (!this.freeConnections.offer(connectionHandle)){\r\n\t\t\t// we failed. rollback.\r\n\t\t\tupdateCreatedConnections(-1); // compensate our createdConnection count.\r\n\t\t\t\r\n\t\t\tif (!this.disableTracking){\r\n\t\t\t\tthis.pool.getFinalizableRefs().remove(connectionHandle.getInternalConnection());\r\n\t\t\t}\r\n\t\t\t// terminate the internal handle.\r\n\t\t\tconnectionHandle.internalClose();\r\n\t\t}\r\n\t}",
"private void registerPerformanceMonitor(String beanName,\n BeanDefinitionRegistry registry) {\n\n String perfMonitorName = beanName + \"PerformanceMonitor\";\n if (!registry.containsBeanDefinition(perfMonitorName)) {\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(PerformanceMonitorBean.class);\n registry.registerBeanDefinition(perfMonitorName, initializer.getBeanDefinition());\n }\n }",
"public synchronized void releaseRebalancingPermit(int nodeId) {\n boolean removed = rebalancePermits.remove(nodeId);\n logger.info(\"Releasing rebalancing permit for node id \" + nodeId + \", returned: \" + removed);\n if(!removed)\n throw new VoldemortException(new IllegalStateException(\"Invalid state, must hold a \"\n + \"permit to release\"));\n }",
"public Map<String, String> resolve(Map<String, String> config) {\n config = resolveSystemEnvironmentVariables(config);\n config = resolveSystemDefaultSetup(config);\n config = resolveDockerInsideDocker(config);\n config = resolveDownloadDockerMachine(config);\n config = resolveAutoStartDockerMachine(config);\n config = resolveDefaultDockerMachine(config);\n config = resolveServerUriByOperativeSystem(config);\n config = resolveServerIp(config);\n config = resolveTlsVerification(config);\n return config;\n }",
"public void setEveryWorkingDay(final boolean isEveryWorkingDay) {\n\n if (m_model.isEveryWorkingDay() != isEveryWorkingDay) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setEveryWorkingDay(Boolean.valueOf(isEveryWorkingDay));\n m_model.setInterval(getPatternDefaultValues().getInterval());\n onValueChange();\n }\n });\n }\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 public Scenario<GIVEN, WHEN, THEN> startScenario( String description ) {\n super.startScenario( description );\n return this;\n\n }",
"public byte[] getByteArray(Integer id, Integer type)\n {\n return (getByteArray(m_meta.getOffset(id, type)));\n }"
] |
Delete a record.
@param referenceId the reference ID. | [
"public void delete(final String referenceId) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaDelete<PrintJobStatusExtImpl> delete =\n builder.createCriteriaDelete(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = delete.from(PrintJobStatusExtImpl.class);\n delete.where(builder.equal(root.get(\"referenceId\"), referenceId));\n getSession().createQuery(delete).executeUpdate();\n }"
] | [
"public void addImportedPackages(String... importedPackages) {\n\t\tString oldBundles = mainAttributes.get(IMPORT_PACKAGE);\n\t\tif (oldBundles == null)\n\t\t\toldBundles = \"\";\n\t\tBundleList oldResultList = BundleList.fromInput(oldBundles, newline);\n\t\tBundleList resultList = BundleList.fromInput(oldBundles, newline);\n\t\tfor (String bundle : importedPackages)\n\t\t\tresultList.mergeInto(Bundle.fromInput(bundle));\n\t\tString result = resultList.toString();\n\t\tboolean changed = !oldResultList.toString().equals(result);\n\t\tmodified |= changed;\n\t\tif (changed)\n\t\t\tmainAttributes.put(IMPORT_PACKAGE, result);\n\t}",
"public static void pauseTimer(final String type) {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return;\n }\n\n instance.components.get(type).pauseTimer();\n }",
"public static boolean matches(Map<String, Object> nodeProperties, String[] keyColumnNames, Object[] keyColumnValues) {\n\t\tfor ( int i = 0; i < keyColumnNames.length; i++ ) {\n\t\t\tString property = keyColumnNames[i];\n\t\t\tObject expectedValue = keyColumnValues[i];\n\t\t\tboolean containsProperty = nodeProperties.containsKey( property );\n\t\t\tif ( containsProperty ) {\n\t\t\t\tObject actualValue = nodeProperties.get( property );\n\t\t\t\tif ( !sameValue( expectedValue, actualValue ) ) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ( expectedValue != null ) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}",
"public static String getVariablesMapExpression(Collection variables) {\n StringBuilder variablesMap = new StringBuilder(\"new \" + PropertiesMap.class.getName() + \"()\");\n for (Object variable : variables) {\n JRVariable jrvar = (JRVariable) variable;\n String varname = jrvar.getName();\n variablesMap.append(\".with(\\\"\").append(varname).append(\"\\\",$V{\").append(varname).append(\"})\");\n }\n return variablesMap.toString();\n }",
"protected InternalHttpResponse sendInternalRequest(HttpRequest request) {\n InternalHttpResponder responder = new InternalHttpResponder();\n httpResourceHandler.handle(request, responder);\n return responder.getResponse();\n }",
"private void populateRecurringException(ProjectCalendarException mpxjException, Exceptions.Exception xmlException)\n {\n RecurringData data = mpxjException.getRecurring();\n xmlException.setEnteredByOccurrences(Boolean.TRUE);\n xmlException.setOccurrences(NumberHelper.getBigInteger(data.getOccurrences()));\n\n switch (data.getRecurrenceType())\n {\n case DAILY:\n {\n xmlException.setType(BigInteger.valueOf(7));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n break;\n }\n\n case WEEKLY:\n {\n xmlException.setType(BigInteger.valueOf(6));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n xmlException.setDaysOfWeek(getDaysOfTheWeek(data));\n break;\n }\n\n case MONTHLY:\n {\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(5));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(4));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n break;\n }\n\n case YEARLY:\n {\n xmlException.setMonth(BigInteger.valueOf(NumberHelper.getInt(data.getMonthNumber()) - 1));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(3));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(2));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n }\n }\n }",
"public static String getURL(String sourceURI) {\n String retval = sourceURI;\n int qPos = sourceURI.indexOf(\"?\");\n if (qPos != -1) {\n retval = retval.substring(0, qPos);\n }\n\n return retval;\n }",
"private void cleanUpAction() {\n\n try {\n m_model.deleteDescriptorIfNecessary();\n } catch (CmsException e) {\n LOG.error(m_messages.key(Messages.ERR_DELETING_DESCRIPTOR_0), e);\n }\n // unlock resource\n m_model.unlock();\n }",
"public void scale(double v){\n\t\tfor(int i = 0; i < this.size(); i++){\n\t\t\tthis.get(i).scale(v);;\n\t\t}\n\t}"
] |
Gets the JsonObject representation of the Field Operation.
@param fieldOperation represents the template update operation
@return the json object | [
"private static JsonObject getFieldOperationJsonObject(FieldOperation fieldOperation) {\n JsonObject jsonObject = new JsonObject();\n jsonObject.add(\"op\", fieldOperation.getOp().toString());\n\n String fieldKey = fieldOperation.getFieldKey();\n if (fieldKey != null) {\n jsonObject.add(\"fieldKey\", fieldKey);\n }\n\n Field field = fieldOperation.getData();\n if (field != null) {\n JsonObject fieldObj = new JsonObject();\n\n String type = field.getType();\n if (type != null) {\n fieldObj.add(\"type\", type);\n }\n\n String key = field.getKey();\n if (key != null) {\n fieldObj.add(\"key\", key);\n }\n\n String displayName = field.getDisplayName();\n if (displayName != null) {\n fieldObj.add(\"displayName\", displayName);\n }\n\n String description = field.getDescription();\n if (description != null) {\n fieldObj.add(\"description\", description);\n }\n\n Boolean hidden = field.getIsHidden();\n if (hidden != null) {\n fieldObj.add(\"hidden\", hidden);\n }\n\n List<String> options = field.getOptions();\n if (options != null) {\n JsonArray array = new JsonArray();\n for (String option: options) {\n JsonObject optionObj = new JsonObject();\n optionObj.add(\"key\", option);\n\n array.add(optionObj);\n }\n\n fieldObj.add(\"options\", array);\n }\n\n jsonObject.add(\"data\", fieldObj);\n }\n\n List<String> fieldKeys = fieldOperation.getFieldKeys();\n if (fieldKeys != null) {\n jsonObject.add(\"fieldKeys\", getJsonArray(fieldKeys));\n }\n\n List<String> enumOptionKeys = fieldOperation.getEnumOptionKeys();\n if (enumOptionKeys != null) {\n jsonObject.add(\"enumOptionKeys\", getJsonArray(enumOptionKeys));\n }\n\n String enumOptionKey = fieldOperation.getEnumOptionKey();\n if (enumOptionKey != null) {\n jsonObject.add(\"enumOptionKey\", enumOptionKey);\n }\n\n String multiSelectOptionKey = fieldOperation.getMultiSelectOptionKey();\n if (multiSelectOptionKey != null) {\n jsonObject.add(\"multiSelectOptionKey\", multiSelectOptionKey);\n }\n\n List<String> multiSelectOptionKeys = fieldOperation.getMultiSelectOptionKeys();\n if (multiSelectOptionKeys != null) {\n jsonObject.add(\"multiSelectOptionKeys\", getJsonArray(multiSelectOptionKeys));\n }\n\n return jsonObject;\n }"
] | [
"public static String load(LoadConfiguration config, String prefix) {\n\t\tif (config.getMode() == Mode.INSERT) {\n\t\t\treturn loadInsert(config, prefix);\n\t\t}\n\t\telse if (config.getMode() == Mode.UPDATE) {\n\t\t\treturn loadUpdate(config, prefix);\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Unsupported mode \" + config.getMode());\n\t}",
"public static AliasFinder newInstance(final String variableName, final ControlFlowBlock controlFlowBlockToExamine) {\n checkArgument(!variableName.isEmpty());\n return new AliasFinder(variableName, checkNotNull(controlFlowBlockToExamine));\n }",
"public void setMatrix(int[] matrix) {\n\t\tthis.matrix = matrix;\n\t\tsum = 0;\n\t\tfor (int i = 0; i < matrix.length; i++)\n\t\t\tsum += matrix[i];\n\t}",
"public static String find(CharSequence self, CharSequence regex, @ClosureParams(value=SimpleType.class, options=\"java.lang.String[]\") Closure closure) {\n return find(self.toString(), Pattern.compile(regex.toString()), closure);\n }",
"public static<A, B, C, Z> Function3<A, B, C, Z> lift(Func3<A, B, C, Z> f) {\n\treturn bridge.lift(f);\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 Connection connectSync(final ProtocolConnectionConfiguration configuration) throws IOException {\n long timeoutMillis = configuration.getConnectionTimeout();\n CallbackHandler handler = configuration.getCallbackHandler();\n final CallbackHandler actualHandler;\n ProtocolTimeoutHandler timeoutHandler = configuration.getTimeoutHandler();\n // Note: If a client supplies a ProtocolTimeoutHandler it is taking on full responsibility for timeout management.\n if (timeoutHandler == null) {\n GeneralTimeoutHandler defaultTimeoutHandler = new GeneralTimeoutHandler();\n // No point wrapping our AnonymousCallbackHandler.\n actualHandler = handler != null ? new WrapperCallbackHandler(defaultTimeoutHandler, handler) : null;\n timeoutHandler = defaultTimeoutHandler;\n } else {\n actualHandler = handler;\n }\n\n final IoFuture<Connection> future = connect(actualHandler, configuration);\n\n IoFuture.Status status = timeoutHandler.await(future, timeoutMillis);\n\n if (status == IoFuture.Status.DONE) {\n return future.get();\n }\n if (status == IoFuture.Status.FAILED) {\n throw ProtocolLogger.ROOT_LOGGER.failedToConnect(configuration.getUri(), future.getException());\n }\n throw ProtocolLogger.ROOT_LOGGER.couldNotConnect(configuration.getUri());\n }",
"public static authenticationvserver_binding get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_binding obj = new authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_binding response = (authenticationvserver_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static JMXServiceURL getLocalConnectorAddress(Process p, boolean startAgent) {\n return getLocalConnectorAddress(Integer.toString(getPid(p)), startAgent);\n }"
] |
Updates the information about this weblink with any info fields that have been modified locally.
<p>The only fields that will be updated are the ones that have been modified locally. For example, the following
code won't update any information (or even send a network request) since none of the info's fields were
changed:</p>
<pre>BoxWebLink webLink = new BoxWebLink(api, id);
BoxWebLink.Info info = webLink.getInfo();
webLink.updateInfo(info);</pre>
@param info the updated info. | [
"public void updateInfo(BoxWebLink.Info info) {\n URL url = WEB_LINK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(info.getPendingChanges());\n String body = info.getPendingChanges();\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n info.update(jsonObject);\n }"
] | [
"public static BoxUser getCurrentUser(BoxAPIConnection api) {\n URL url = GET_ME_URL.build(api.getBaseURL());\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n return new BoxUser(api, jsonObject.get(\"id\").asString());\n }",
"@Override\n synchronized public V put(K key, V value) {\n V oldValue = this.get(key);\n try {\n super.put(key, value);\n writeBack(key, value);\n return oldValue;\n } catch(Exception e) {\n super.put(key, oldValue);\n writeBack(key, oldValue);\n throw new VoldemortException(\"Failed to put(\" + key + \", \" + value\n + \") in write through cache\", e);\n }\n }",
"public static StitchAppClient getAppClient(\n @Nonnull final String clientAppId\n ) {\n ensureInitialized();\n\n synchronized (Stitch.class) {\n if (!appClients.containsKey(clientAppId)) {\n throw new IllegalStateException(\n String.format(\"client for app '%s' has not yet been initialized\", clientAppId));\n }\n return appClients.get(clientAppId);\n }\n }",
"public FinishRequest toFinishRequest(boolean includeHeaders) {\n if (includeHeaders) {\n return new FinishRequest(body, copyHeaders(headers), statusCode);\n } else {\n String mime = null;\n if (body!=null) {\n mime = \"text/plain\";\n if (headers!=null && (headers.containsKey(\"Content-Type\") || headers.containsKey(\"content-type\"))) {\n mime = headers.get(\"Content-Type\");\n if (mime==null) {\n mime = headers.get(\"content-type\");\n }\n }\n }\n\n return new FinishRequest(body, mime, statusCode);\n }\n }",
"public static Boolean assertFalse(Boolean value, String message) {\n if (Boolean.valueOf(value))\n throw new IllegalStateException(message);\n return value;\n }",
"public ItemDocumentBuilder withSiteLink(String title, String siteKey,\n\t\t\tItemIdValue... badges) {\n\t\twithSiteLink(factory.getSiteLink(title, siteKey, Arrays.asList(badges)));\n\t\treturn this;\n\t}",
"private void deliverDatabaseUpdate(SlotReference slot, Database database, boolean available) {\n for (final DatabaseListener listener : getDatabaseListeners()) {\n try {\n if (available) {\n listener.databaseMounted(slot, database);\n } else {\n listener.databaseUnmounted(slot, database);\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering rekordbox database availability update to listener\", t);\n }\n }\n }",
"private void computeCosts() {\n cost = Long.MAX_VALUE;\n for (QueueItem item : queueSpans) {\n cost = Math.min(cost, item.sequenceSpans.spans.cost());\n }\n }",
"public static String getTemplateAsString(String fileName) throws IOException {\n // in .jar file\n String fNameJar = getFileNameInPath(fileName);\n InputStream inStream = DomUtils.class.getResourceAsStream(\"/\"\n + fNameJar);\n if (inStream == null) {\n // try to find file normally\n File f = new File(fileName);\n if (f.exists()) {\n inStream = new FileInputStream(f);\n } else {\n throw new IOException(\"Cannot find \" + fileName + \" or \"\n + fNameJar);\n }\n }\n\n BufferedReader bufferedReader = new BufferedReader(\n new InputStreamReader(inStream));\n String line;\n StringBuilder stringBuilder = new StringBuilder();\n\n while ((line = bufferedReader.readLine()) != null) {\n stringBuilder.append(line).append(\"\\n\");\n }\n\n bufferedReader.close();\n return stringBuilder.toString();\n }"
] |
Read the name of a table and prepare to populate it with column data.
@param startIndex start of the block
@param blockLength length of the block | [
"private void readTableBlock(int startIndex, int blockLength)\n {\n for (int index = startIndex; index < (startIndex + blockLength - 11); index++)\n {\n if (matchPattern(TABLE_BLOCK_PATTERNS, index))\n {\n int offset = index + 7;\n int nameLength = FastTrackUtility.getInt(m_buffer, offset);\n offset += 4;\n String name = new String(m_buffer, offset, nameLength, CharsetHelper.UTF16LE).toUpperCase();\n FastTrackTableType type = REQUIRED_TABLES.get(name);\n if (type != null)\n {\n m_currentTable = new FastTrackTable(type, this);\n m_tables.put(type, m_currentTable);\n }\n else\n {\n m_currentTable = null;\n }\n m_currentFields.clear();\n break;\n }\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 }",
"public static base_response update(nitro_service client, tmtrafficaction resource) throws Exception {\n\t\ttmtrafficaction updateresource = new tmtrafficaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.apptimeout = resource.apptimeout;\n\t\tupdateresource.sso = resource.sso;\n\t\tupdateresource.formssoaction = resource.formssoaction;\n\t\tupdateresource.persistentcookie = resource.persistentcookie;\n\t\tupdateresource.initiatelogout = resource.initiatelogout;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\tupdateresource.samlssoprofile = resource.samlssoprofile;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static JasperPrint generateJasperPrint(DynamicReport dr, LayoutManager layoutManager, Connection con, Map<String, Object> _parameters) throws JRException {\n log.info(\"generating JasperPrint\");\n JasperPrint jp;\n\n if (_parameters == null)\n _parameters = new HashMap<String, Object>();\n\n visitSubreports(dr, _parameters);\n compileOrLoadSubreports(dr, _parameters, \"r\");\n\n DynamicJasperDesign jd = generateJasperDesign(dr);\n Map<String, Object> params = new HashMap<String, Object>();\n if (!_parameters.isEmpty()) {\n registerParams(jd, _parameters);\n params.putAll(_parameters);\n }\n registerEntities(jd, dr, layoutManager);\n layoutManager.applyLayout(jd, dr);\n JRPropertiesUtil.getInstance(DefaultJasperReportsContext.getInstance()).setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());\n //JRProperties.setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());\n JasperReport jr = JasperCompileManager.compileReport(jd);\n params.putAll(jd.getParametersWithValues());\n jp = JasperFillManager.fillReport(jr, params, con);\n\n return jp;\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 String login(String token, Authentication authentication) {\n\t\tif (null == token) {\n\t\t\treturn login(authentication);\n\t\t}\n\t\ttokens.put(token, new TokenContainer(authentication));\n\t\treturn token;\n\t}",
"private Integer getNullOnValue(Integer value, int nullValue)\n {\n return (NumberHelper.getInt(value) == nullValue ? null : value);\n }",
"private void addMetadataProviderForMedia(String key, MetadataProvider provider) {\n if (!metadataProviders.containsKey(key)) {\n metadataProviders.put(key, Collections.newSetFromMap(new ConcurrentHashMap<MetadataProvider, Boolean>()));\n }\n Set<MetadataProvider> providers = metadataProviders.get(key);\n providers.add(provider);\n }",
"public static int serialize(OutputStream stream, Object obj) {\n ObjectMapper mapper = createMapperWithJaxbAnnotationInspector();\n\n try (DataOutputStream data = new DataOutputStream(stream);\n OutputStreamWriter writer = new OutputStreamWriter(data, StandardCharsets.UTF_8)) {\n mapper.writerWithDefaultPrettyPrinter().writeValue(writer, obj);\n return data.size();\n } catch (IOException e) {\n throw new ReportGenerationException(e);\n }\n }",
"public static Timespan create(Timespan... timespans) {\n if (timespans == null) {\n return null;\n }\n\n if (timespans.length == 0) {\n return ZERO_MILLISECONDS;\n }\n\n Timespan res = timespans[0];\n\n for (int i = 1; i < timespans.length; i++) {\n Timespan timespan = timespans[i];\n res = res.add(timespan);\n }\n\n return res;\n }"
] |
Convert a floating point date to a LocalDate.
Note: This method currently performs a rounding to the next day.
In a future extension intra-day time offsets may be considered.
If referenceDate is null, the method returns null.
@param referenceDate The reference date associated with \( t=0 \).
@param floatingPointDate The value to the time offset \( t \).
@return The date resulting from adding Math.round(fixingTime*365.0) days to referenceDate. | [
"public static LocalDate getDateFromFloatingPointDate(LocalDate referenceDate, double floatingPointDate) {\n\t\tif(referenceDate == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn referenceDate.plusDays((int)Math.round(floatingPointDate*365.0));\n\t}"
] | [
"public static base_response update(nitro_service client, vpnsessionaction resource) throws Exception {\n\t\tvpnsessionaction updateresource = new vpnsessionaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.httpport = resource.httpport;\n\t\tupdateresource.winsip = resource.winsip;\n\t\tupdateresource.dnsvservername = resource.dnsvservername;\n\t\tupdateresource.splitdns = resource.splitdns;\n\t\tupdateresource.sesstimeout = resource.sesstimeout;\n\t\tupdateresource.clientsecurity = resource.clientsecurity;\n\t\tupdateresource.clientsecuritygroup = resource.clientsecuritygroup;\n\t\tupdateresource.clientsecuritymessage = resource.clientsecuritymessage;\n\t\tupdateresource.clientsecuritylog = resource.clientsecuritylog;\n\t\tupdateresource.splittunnel = resource.splittunnel;\n\t\tupdateresource.locallanaccess = resource.locallanaccess;\n\t\tupdateresource.rfc1918 = resource.rfc1918;\n\t\tupdateresource.spoofiip = resource.spoofiip;\n\t\tupdateresource.killconnections = resource.killconnections;\n\t\tupdateresource.transparentinterception = resource.transparentinterception;\n\t\tupdateresource.windowsclienttype = resource.windowsclienttype;\n\t\tupdateresource.defaultauthorizationaction = resource.defaultauthorizationaction;\n\t\tupdateresource.authorizationgroup = resource.authorizationgroup;\n\t\tupdateresource.clientidletimeout = resource.clientidletimeout;\n\t\tupdateresource.proxy = resource.proxy;\n\t\tupdateresource.allprotocolproxy = resource.allprotocolproxy;\n\t\tupdateresource.httpproxy = resource.httpproxy;\n\t\tupdateresource.ftpproxy = resource.ftpproxy;\n\t\tupdateresource.socksproxy = resource.socksproxy;\n\t\tupdateresource.gopherproxy = resource.gopherproxy;\n\t\tupdateresource.sslproxy = resource.sslproxy;\n\t\tupdateresource.proxyexception = resource.proxyexception;\n\t\tupdateresource.proxylocalbypass = resource.proxylocalbypass;\n\t\tupdateresource.clientcleanupprompt = resource.clientcleanupprompt;\n\t\tupdateresource.forcecleanup = resource.forcecleanup;\n\t\tupdateresource.clientoptions = resource.clientoptions;\n\t\tupdateresource.clientconfiguration = resource.clientconfiguration;\n\t\tupdateresource.sso = resource.sso;\n\t\tupdateresource.ssocredential = resource.ssocredential;\n\t\tupdateresource.windowsautologon = resource.windowsautologon;\n\t\tupdateresource.usemip = resource.usemip;\n\t\tupdateresource.useiip = resource.useiip;\n\t\tupdateresource.clientdebug = resource.clientdebug;\n\t\tupdateresource.loginscript = resource.loginscript;\n\t\tupdateresource.logoutscript = resource.logoutscript;\n\t\tupdateresource.homepage = resource.homepage;\n\t\tupdateresource.icaproxy = resource.icaproxy;\n\t\tupdateresource.wihome = resource.wihome;\n\t\tupdateresource.citrixreceiverhome = resource.citrixreceiverhome;\n\t\tupdateresource.wiportalmode = resource.wiportalmode;\n\t\tupdateresource.clientchoices = resource.clientchoices;\n\t\tupdateresource.epaclienttype = resource.epaclienttype;\n\t\tupdateresource.iipdnssuffix = resource.iipdnssuffix;\n\t\tupdateresource.forcedtimeout = resource.forcedtimeout;\n\t\tupdateresource.forcedtimeoutwarning = resource.forcedtimeoutwarning;\n\t\tupdateresource.ntdomain = resource.ntdomain;\n\t\tupdateresource.clientlessvpnmode = resource.clientlessvpnmode;\n\t\tupdateresource.emailhome = resource.emailhome;\n\t\tupdateresource.clientlessmodeurlencoding = resource.clientlessmodeurlencoding;\n\t\tupdateresource.clientlesspersistentcookie = resource.clientlesspersistentcookie;\n\t\tupdateresource.allowedlogingroups = resource.allowedlogingroups;\n\t\tupdateresource.securebrowse = resource.securebrowse;\n\t\tupdateresource.storefronturl = resource.storefronturl;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private static void validatePseudoScopedBean(Bean<?> bean, BeanManagerImpl beanManager) {\n if (bean.getInjectionPoints().isEmpty()) {\n // Skip validation if there are no injection points (e.g. for classes which are not intended to be used as beans)\n return;\n }\n reallyValidatePseudoScopedBean(bean, beanManager, new LinkedHashSet<Object>(), new HashSet<Bean<?>>());\n }",
"public static vlan_interface_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tvlan_interface_binding obj = new vlan_interface_binding();\n\t\tobj.set_id(id);\n\t\tvlan_interface_binding response[] = (vlan_interface_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void setTaskNotes(Task task, byte[] data, ExtendedData taskExtData, FixDeferFix taskVarData)\n {\n String notes = taskExtData.getString(TASK_NOTES);\n if (notes == null && data.length == 366)\n {\n byte[] offsetData = taskVarData.getByteArray(getOffset(data, 362));\n if (offsetData != null && offsetData.length >= 12)\n {\n notes = taskVarData.getString(getOffset(offsetData, 8));\n \n // We do pick up some random stuff with this approach, and \n // we don't know enough about the file format to know when to ignore it\n // so we'll use a heuristic here to ignore anything that\n // doesn't look like RTF.\n if (notes != null && notes.indexOf('{') == -1)\n {\n notes = null;\n }\n }\n }\n \n if (notes != null)\n {\n if (m_reader.getPreserveNoteFormatting() == false)\n {\n notes = RtfHelper.strip(notes);\n }\n\n task.setNotes(notes);\n }\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 void initializeInternalProject(CommandExecutor executor) {\n final long creationTimeMillis = System.currentTimeMillis();\n try {\n executor.execute(createProject(creationTimeMillis, Author.SYSTEM, INTERNAL_PROJ))\n .get();\n } catch (Throwable cause) {\n cause = Exceptions.peel(cause);\n if (!(cause instanceof ProjectExistsException)) {\n throw new Error(\"failed to initialize an internal project\", cause);\n }\n }\n // These repositories might be created when creating an internal project, but we try to create them\n // again here in order to make sure them exist because sometimes their names are changed.\n for (final String repo : ImmutableList.of(Project.REPO_META, Project.REPO_DOGMA)) {\n try {\n executor.execute(createRepository(creationTimeMillis, Author.SYSTEM, INTERNAL_PROJ, repo))\n .get();\n } catch (Throwable cause) {\n cause = Exceptions.peel(cause);\n if (!(cause instanceof RepositoryExistsException)) {\n throw new Error(cause);\n }\n }\n }\n }",
"@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 }",
"protected void printCenterWithLead(String lead, String format, Object ... args) {\n String text = S.fmt(format, args);\n int len = 80 - lead.length();\n info(S.concat(lead, S.center(text, len)));\n }",
"private static JsonParser newJsonParserForNode(JsonNode jsonNode) throws IOException {\n JsonParser parser = new JsonFactory().createParser(jsonNode.toString());\n parser.nextToken();\n return parser;\n }"
] |
Creates a new Box Developer Edition connection with App User token.
@param userId the user ID to use for an App User.
@param clientId the client ID to use when exchanging the JWT assertion for an access token.
@param clientSecret the client secret to use when exchanging the JWT assertion for an access token.
@param encryptionPref the encryption preferences for signing the JWT.
@param accessTokenCache the cache for storing access token information (to minimize fetching new tokens)
@return a new instance of BoxAPIConnection. | [
"public static BoxDeveloperEditionAPIConnection getAppUserConnection(String userId, String clientId,\n String clientSecret, JWTEncryptionPreferences encryptionPref, IAccessTokenCache accessTokenCache) {\n\n BoxDeveloperEditionAPIConnection connection = new BoxDeveloperEditionAPIConnection(userId,\n DeveloperEditionEntityType.USER, clientId, clientSecret, encryptionPref, accessTokenCache);\n\n connection.tryRestoreUsingAccessTokenCache();\n\n return connection;\n }"
] | [
"public ExecutionChain setErrorCallback(ErrorCallback callback) {\n if (state.get() == State.RUNNING) {\n throw new IllegalStateException(\n \"Invalid while ExecutionChain is running\");\n }\n errorCallback = callback;\n return this;\n }",
"public static DMatrixRMaj convert(DMatrixRBlock src , DMatrixRMaj dst )\n {\n return ConvertDMatrixStruct.convert(src,dst);\n }",
"private boolean shouldWrapMethodCall(String methodName) {\n if (methodList == null) {\n return true; // Wrap all by default\n }\n\n if (methodList.contains(methodName)) {\n return true; //Wrap a specific method\n }\n\n // If I get to this point, I should not wrap the call.\n return false;\n }",
"private static void reallyValidatePseudoScopedBean(Bean<?> bean, BeanManagerImpl beanManager, Set<Object> dependencyPath, Set<Bean<?>> validatedBeans) {\n // see if we have already seen this bean in the dependency path\n if (dependencyPath.contains(bean)) {\n // create a list that shows the path to the bean\n List<Object> realDependencyPath = new ArrayList<Object>(dependencyPath);\n realDependencyPath.add(bean);\n throw ValidatorLogger.LOG.pseudoScopedBeanHasCircularReferences(WeldCollections.toMultiRowString(realDependencyPath));\n }\n if (validatedBeans.contains(bean)) {\n return;\n }\n dependencyPath.add(bean);\n for (InjectionPoint injectionPoint : bean.getInjectionPoints()) {\n if (!injectionPoint.isDelegate()) {\n dependencyPath.add(injectionPoint);\n validatePseudoScopedInjectionPoint(injectionPoint, beanManager, dependencyPath, validatedBeans);\n dependencyPath.remove(injectionPoint);\n }\n }\n if (bean instanceof DecorableBean<?>) {\n final List<Decorator<?>> decorators = Reflections.<DecorableBean<?>>cast(bean).getDecorators();\n if (!decorators.isEmpty()) {\n for (final Decorator<?> decorator : decorators) {\n reallyValidatePseudoScopedBean(decorator, beanManager, dependencyPath, validatedBeans);\n }\n }\n }\n if (bean instanceof AbstractProducerBean<?, ?, ?> && !(bean instanceof EEResourceProducerField<?, ?>)) {\n AbstractProducerBean<?, ?, ?> producer = (AbstractProducerBean<?, ?, ?>) bean;\n if (!beanManager.isNormalScope(producer.getDeclaringBean().getScope()) && !producer.getAnnotated().isStatic()) {\n reallyValidatePseudoScopedBean(producer.getDeclaringBean(), beanManager, dependencyPath, validatedBeans);\n }\n }\n validatedBeans.add(bean);\n dependencyPath.remove(bean);\n }",
"private int combineSubsetBlocks(Mode[] mode_type, int[] mode_length, int index_point) {\n /* bring together same type blocks */\n if (index_point > 1) {\n for (int i = 1; i < index_point; i++) {\n if (mode_type[i - 1] == mode_type[i]) {\n /* bring together */\n mode_length[i - 1] = mode_length[i - 1] + mode_length[i];\n /* decrease the list */\n for (int j = i + 1; j < index_point; j++) {\n mode_length[j - 1] = mode_length[j];\n mode_type[j - 1] = mode_type[j];\n }\n index_point--;\n i--;\n }\n }\n }\n return index_point;\n }",
"public static double calculateBoundedness(double D, int N, double timelag, double confRadius){\n\t\tdouble r = confRadius;\n\t\tdouble cov_area = a(N)*D*timelag;\n\t\tdouble res = cov_area/(4*r*r);\n\t\treturn res;\n\t}",
"public void revertWorkingCopy() throws IOException, InterruptedException {\n build.getWorkspace()\n .act(new RevertWorkingCopyCallable(getLocation(), getSvnAuthenticationProvider(build), buildListener));\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 RequiredConfigurationHolder populateHostResolutionContext(final HostInfo hostInfo, final Resource root, final ExtensionRegistry extensionRegistry) {\n final RequiredConfigurationHolder rc = new RequiredConfigurationHolder();\n for (IgnoredNonAffectedServerGroupsUtil.ServerConfigInfo info : hostInfo.getServerConfigInfos()) {\n processServerConfig(root, rc, info, extensionRegistry);\n }\n return rc;\n }"
] |
The click handler for the add button. | [
"private void onClickAdd() {\n\n if (m_currentLocation.isPresent()) {\n CmsFavoriteEntry entry = m_currentLocation.get();\n List<CmsFavoriteEntry> entries = getEntries();\n entries.add(entry);\n try {\n m_favDao.saveFavorites(entries);\n } catch (Exception e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n m_context.close();\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 }",
"private ClassDescriptor discoverDescriptor(Class clazz)\r\n {\r\n ClassDescriptor result = (ClassDescriptor) descriptorTable.get(clazz.getName());\r\n\r\n if (result == null)\r\n {\r\n Class superClass = clazz.getSuperclass();\r\n // only recurse if the superClass is not java.lang.Object\r\n if (superClass != null)\r\n {\r\n result = discoverDescriptor(superClass);\r\n }\r\n if (result == null)\r\n {\r\n // we're also checking the interfaces as there could be normal\r\n // mappings for them in the repository (using factory-class,\r\n // factory-method, and the property field accessor)\r\n Class[] interfaces = clazz.getInterfaces();\r\n\r\n if ((interfaces != null) && (interfaces.length > 0))\r\n {\r\n for (int idx = 0; (idx < interfaces.length) && (result == null); idx++)\r\n {\r\n result = discoverDescriptor(interfaces[idx]);\r\n }\r\n }\r\n }\r\n\r\n if (result != null)\r\n {\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \tsynchronized (descriptorTable) {\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n \t\tdescriptorTable.put(clazz.getName(), result);\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \t}\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n }\r\n }\r\n return result;\r\n }",
"public AwsServiceClient withCodecRegistry(@Nonnull final CodecRegistry codecRegistry) {\n return new AwsServiceClientImpl(proxy.withCodecRegistry(codecRegistry), dispatcher);\n }",
"public static void hideOnlyChannels(Object... channels){\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n visHandler.showAll();\r\n for (Object channel : channels) {\r\n visHandler.alsoHide(channel);\r\n }\r\n }\r\n }\r\n }",
"public SyntaxException getSyntaxError(int index) {\n SyntaxException exception = null;\n\n Message message = getError(index);\n if (message != null && message instanceof SyntaxErrorMessage) {\n exception = ((SyntaxErrorMessage) message).getCause();\n }\n return exception;\n }",
"final protected char next(final ByteBuffer buffer, boolean allow8859) throws BaseExceptions.BadMessage {\n\n if (!buffer.hasRemaining()) return HttpTokens.EMPTY_BUFF;\n\n if (_segmentByteLimit <= _segmentBytePosition) {\n shutdownParser();\n throw new BaseExceptions.BadMessage(\"Request length limit exceeded: \" + _segmentByteLimit);\n }\n\n final byte b = buffer.get();\n _segmentBytePosition++;\n\n // If we ended on a CR, make sure we are\n if (_cr) {\n if (b != HttpTokens.LF) {\n throw new BadCharacter(\"Invalid sequence: LF didn't follow CR: \" + b);\n }\n _cr = false;\n return (char)b; // must be LF\n }\n\n // Make sure its a valid character\n if (b < HttpTokens.SPACE) {\n if (b == HttpTokens.CR) { // Set the flag to check for _cr and just run again\n _cr = true;\n return next(buffer, allow8859);\n }\n else if (b == HttpTokens.TAB || allow8859 && b < 0) {\n return (char)(b & 0xff);\n }\n else if (b == HttpTokens.LF) {\n return (char)b; // A backend should accept a bare linefeed. http://tools.ietf.org/html/rfc2616#section-19.3\n }\n else if (isLenient()) {\n return HttpTokens.REPLACEMENT;\n }\n else {\n shutdownParser();\n throw new BadCharacter(\"Invalid char: '\" + (char)(b & 0xff) + \"', 0x\" + Integer.toHexString(b));\n }\n }\n\n // valid ascii char\n return (char)b;\n }",
"public static String dump(final int displayOffset, final byte[] data, final int offset, final int len)\n {\n StringBuilder sb = new StringBuilder();\n Formatter formatter = new Formatter(sb);\n StringBuilder ascii = new StringBuilder();\n\n int dataNdx = offset;\n final int maxDataNdx = offset + len;\n final int lines = (len + 16) / 16;\n for (int i = 0; i < lines; i++) {\n ascii.append(\" |\");\n formatter.format(\"%08x \", displayOffset + (i * 16));\n\n for (int j = 0; j < 16; j++) {\n if (dataNdx < maxDataNdx) {\n byte b = data[dataNdx++];\n formatter.format(\"%02x \", b);\n ascii.append((b > MIN_VISIBLE && b < MAX_VISIBLE) ? (char) b : ' ');\n }\n else {\n sb.append(\" \");\n }\n\n if (j == 7) {\n sb.append(' ');\n }\n }\n\n ascii.append('|');\n sb.append(ascii).append('\\n');\n ascii.setLength(0);\n }\n\n formatter.close();\n return sb.toString();\n }",
"@Deprecated\n public void parseAndSetParameter(String value, ModelNode operation, XMLStreamReader reader) throws XMLStreamException {\n //we use manual parsing here, and not #getParser().. to preserve backward compatibility.\n if (value != null) {\n for (String element : value.split(\",\")) {\n parseAndAddParameterElement(element.trim(), operation, reader);\n }\n }\n }",
"private void writeActivity(Task mpxj)\n {\n ActivityType xml = m_factory.createActivityType();\n m_project.getActivity().add(xml);\n\n Task parentTask = mpxj.getParentTask();\n Integer parentObjectID = parentTask == null ? null : parentTask.getUniqueID();\n\n xml.setActualStartDate(mpxj.getActualStart());\n xml.setActualFinishDate(mpxj.getActualFinish());\n xml.setAtCompletionDuration(getDuration(mpxj.getDuration()));\n xml.setCalendarObjectId(getCalendarUniqueID(mpxj.getCalendar()));\n xml.setDurationPercentComplete(getPercentage(mpxj.getPercentageComplete()));\n xml.setDurationType(DURATION_TYPE_MAP.get(mpxj.getType()));\n xml.setFinishDate(mpxj.getFinish());\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setId(getActivityID(mpxj));\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setPercentComplete(getPercentage(mpxj.getPercentageComplete()));\n xml.setPercentCompleteType(\"Duration\");\n xml.setPrimaryConstraintType(CONSTRAINT_TYPE_MAP.get(mpxj.getConstraintType()));\n xml.setPrimaryConstraintDate(mpxj.getConstraintDate());\n xml.setPlannedDuration(getDuration(mpxj.getDuration()));\n xml.setPlannedFinishDate(mpxj.getFinish());\n xml.setPlannedStartDate(mpxj.getStart());\n xml.setProjectObjectId(PROJECT_OBJECT_ID);\n xml.setRemainingDuration(getDuration(mpxj.getRemainingDuration()));\n xml.setRemainingEarlyFinishDate(mpxj.getEarlyFinish());\n xml.setRemainingEarlyStartDate(mpxj.getResume());\n xml.setRemainingLaborCost(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingLaborUnits(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingNonLaborCost(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingNonLaborUnits(NumberHelper.DOUBLE_ZERO);\n xml.setStartDate(mpxj.getStart());\n xml.setStatus(getActivityStatus(mpxj));\n xml.setType(extractAndConvertTaskType(mpxj));\n xml.setWBSObjectId(parentObjectID);\n xml.getUDF().addAll(writeUDFType(FieldTypeClass.TASK, mpxj));\n\n writePredecessors(mpxj);\n }"
] |
All tests completed. | [
"@Subscribe\n public void onQuit(AggregatedQuitEvent e) {\n if (jsonWriter == null)\n return;\n\n try {\n jsonWriter.endArray();\n\n jsonWriter.name(\"slaves\");\n jsonWriter.beginObject();\n for (Map.Entry<Integer, ForkedJvmInfo> entry : slaves.entrySet()) {\n jsonWriter.name(Integer.toString(entry.getKey()));\n entry.getValue().serialize(jsonWriter);\n }\n jsonWriter.endObject();\n\n jsonWriter.endObject();\n jsonWriter.flush();\n\n if (!Strings.isNullOrEmpty(jsonpMethod)) {\n writer.write(\");\");\n }\n\n jsonWriter.close();\n jsonWriter = null;\n writer = null;\n\n if (method == OutputMethod.HTML) {\n copyScaffolding(targetFile);\n }\n } catch (IOException x) {\n junit4.log(x, Project.MSG_ERR);\n }\n }"
] | [
"public Map<String, Attribute> getAttributes() {\n Map<String, Attribute> result = new HashMap<>();\n DataSourceAttribute datasourceAttribute = new DataSourceAttribute();\n Map<String, Attribute> dsResult = new HashMap<>();\n dsResult.put(MAP_KEY, this.mapAttribute);\n datasourceAttribute.setAttributes(dsResult);\n result.put(\"datasource\", datasourceAttribute);\n return result;\n }",
"private void readColumn(int startIndex, int length) throws Exception\n {\n if (m_currentTable != null)\n {\n int value = FastTrackUtility.getByte(m_buffer, startIndex);\n Class<?> klass = COLUMN_MAP[value];\n if (klass == null)\n {\n klass = UnknownColumn.class;\n }\n\n FastTrackColumn column = (FastTrackColumn) klass.newInstance();\n m_currentColumn = column;\n\n logColumnData(startIndex, length);\n\n column.read(m_currentTable.getType(), m_buffer, startIndex, length);\n FastTrackField type = column.getType();\n\n //\n // Don't try to add this data if:\n // 1. We don't know what type it is\n // 2. We have seen the type already\n //\n if (type != null && !m_currentFields.contains(type))\n {\n m_currentFields.add(type);\n m_currentTable.addColumn(column);\n updateDurationTimeUnit(column);\n updateWorkTimeUnit(column);\n\n logColumn(column);\n }\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 }",
"public static <T extends Spin<?>> T S(Object input, DataFormat<T> format) {\n return SpinFactory.INSTANCE.createSpin(input, format);\n }",
"public static base_response export(nitro_service client, sslfipskey resource) throws Exception {\n\t\tsslfipskey exportresource = new sslfipskey();\n\t\texportresource.fipskeyname = resource.fipskeyname;\n\t\texportresource.key = resource.key;\n\t\treturn exportresource.perform_operation(client,\"export\");\n\t}",
"private static String mapContent(DataHandler dh) {\n if (dh == null) {\n return \"\";\n }\n try {\n InputStream is = dh.getInputStream();\n String content = IOUtils.toString(is);\n is.close();\n return content;\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }",
"private void bumpScores(Map<Long, Score> candidates,\n List<Bucket> buckets,\n int ix) {\n for (; ix < buckets.size(); ix++) {\n Bucket b = buckets.get(ix);\n if (b.nextfree > CUTOFF_FACTOR_2 * candidates.size())\n return;\n double score = b.getScore();\n for (Score s : candidates.values())\n if (b.contains(s.id))\n s.score += score;\n }\n }",
"public static <T> T withObjectStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={\"java.io.ObjectInputStream\",\"java.io.ObjectOutputStream\"}) Closure<T> closure) throws IOException {\n InputStream input = socket.getInputStream();\n OutputStream output = socket.getOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(output);\n ObjectInputStream ois = new ObjectInputStream(input);\n try {\n T result = closure.call(new Object[]{ois, oos});\n\n InputStream temp1 = ois;\n ois = null;\n temp1.close();\n temp1 = input;\n input = null;\n temp1.close();\n OutputStream temp2 = oos;\n oos = null;\n temp2.close();\n temp2 = output;\n output = null;\n temp2.close();\n\n return result;\n } finally {\n closeWithWarning(ois);\n closeWithWarning(input);\n closeWithWarning(oos);\n closeWithWarning(output);\n }\n }",
"void throwCloudExceptionIfInFailedState() {\n if (this.isStatusFailed()) {\n if (this.errorBody() != null) {\n throw new CloudException(\"Async operation failed with provisioning state: \" + this.status(), this.response(), this.errorBody());\n } else {\n throw new CloudException(\"Async operation failed with provisioning state: \" + this.status(), this.response());\n }\n }\n }"
] |
Get the values of the fields for an obj
Autoincrement values are automatically set.
@param fields
@param obj
@throws PersistenceBrokerException | [
"public ValueContainer[] getValuesForObject(FieldDescriptor[] fields, Object obj, boolean convertToSql, boolean assignAutoincrement) throws PersistenceBrokerException\r\n {\r\n ValueContainer[] result = new ValueContainer[fields.length];\r\n\r\n for(int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fd = fields[i];\r\n Object cv = fd.getPersistentField().get(obj);\r\n\r\n /*\r\n handle autoincrement attributes if\r\n - is a autoincrement field\r\n - field represents a 'null' value, is nullified\r\n and generate a new value\r\n */\r\n if(assignAutoincrement && fd.isAutoIncrement() && representsNull(fd, cv))\r\n {\r\n /*\r\n setAutoIncrementValue returns a value that is\r\n properly typed for the java-world. This value\r\n needs to be converted to it's corresponding\r\n sql type so that the entire result array contains\r\n objects that are properly typed for sql.\r\n */\r\n cv = setAutoIncrementValue(fd, obj);\r\n }\r\n if(convertToSql)\r\n {\r\n // apply type and value conversion\r\n cv = fd.getFieldConversion().javaToSql(cv);\r\n }\r\n // create ValueContainer\r\n result[i] = new ValueContainer(cv, fd.getJdbcType());\r\n }\r\n return result;\r\n }"
] | [
"private void initPatternButtonGroup() {\n\n m_groupPattern = new CmsRadioButtonGroup();\n m_patternButtons = new HashMap<>();\n\n createAndAddButton(PatternType.DAILY, Messages.GUI_SERIALDATE_TYPE_DAILY_0);\n m_patternButtons.put(PatternType.NONE, m_patternButtons.get(PatternType.DAILY));\n createAndAddButton(PatternType.WEEKLY, Messages.GUI_SERIALDATE_TYPE_WEEKLY_0);\n createAndAddButton(PatternType.MONTHLY, Messages.GUI_SERIALDATE_TYPE_MONTHLY_0);\n createAndAddButton(PatternType.YEARLY, Messages.GUI_SERIALDATE_TYPE_YEARLY_0);\n // createAndAddButton(PatternType.INDIVIDUAL, Messages.GUI_SERIALDATE_TYPE_INDIVIDUAL_0);\n\n m_groupPattern.addValueChangeHandler(new ValueChangeHandler<String>() {\n\n public void onValueChange(ValueChangeEvent<String> event) {\n\n if (handleChange()) {\n String value = event.getValue();\n if (value != null) {\n m_controller.setPattern(value);\n }\n }\n }\n });\n\n }",
"public int addServerGroup(String groupName, int profileId) throws Exception {\n int groupId = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_SERVER_GROUPS\n + \"(\" + Constants.GENERIC_NAME + \",\" +\n Constants.GENERIC_PROFILE_ID + \")\"\n + \" VALUES (?, ?);\", PreparedStatement.RETURN_GENERATED_KEYS);\n statement.setString(1, groupName);\n statement.setInt(2, profileId);\n statement.executeUpdate();\n\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n groupId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add group\");\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return groupId;\n }",
"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}",
"public List<T> resolveConflicts(List<T> values) {\n if(values.size() > 1)\n return values;\n else\n return Collections.singletonList(values.get(0));\n }",
"protected void addLineContent(BufferedReader bufferedFileReader, List<String> content, String line) throws IOException {\n content.add(line);\n }",
"public static base_response delete(nitro_service client, String acl6name) throws Exception {\n\t\tnsacl6 deleteresource = new nsacl6();\n\t\tdeleteresource.acl6name = acl6name;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"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 List<Dependency> getCorporateDependencies(final Module module, final List<String> corporateFilters) {\n final List<Dependency> corporateDependencies = new ArrayList<Dependency>();\n final Pattern corporatePattern = generateCorporatePattern(corporateFilters);\n\n for(final Dependency dependency: getAllDependencies(module)){\n if(dependency.getTarget().getGavc().matches(corporatePattern.pattern())){\n corporateDependencies.add(dependency);\n }\n }\n\n return corporateDependencies;\n }",
"public static final UUID getUUID(InputStream is) throws IOException\n {\n byte[] data = new byte[16];\n is.read(data);\n\n long long1 = 0;\n long1 |= ((long) (data[3] & 0xFF)) << 56;\n long1 |= ((long) (data[2] & 0xFF)) << 48;\n long1 |= ((long) (data[1] & 0xFF)) << 40;\n long1 |= ((long) (data[0] & 0xFF)) << 32;\n long1 |= ((long) (data[5] & 0xFF)) << 24;\n long1 |= ((long) (data[4] & 0xFF)) << 16;\n long1 |= ((long) (data[7] & 0xFF)) << 8;\n long1 |= ((long) (data[6] & 0xFF)) << 0;\n\n long long2 = 0;\n long2 |= ((long) (data[8] & 0xFF)) << 56;\n long2 |= ((long) (data[9] & 0xFF)) << 48;\n long2 |= ((long) (data[10] & 0xFF)) << 40;\n long2 |= ((long) (data[11] & 0xFF)) << 32;\n long2 |= ((long) (data[12] & 0xFF)) << 24;\n long2 |= ((long) (data[13] & 0xFF)) << 16;\n long2 |= ((long) (data[14] & 0xFF)) << 8;\n long2 |= ((long) (data[15] & 0xFF)) << 0;\n\n return new UUID(long1, long2);\n }"
] |
Merge a subtree.
@param targetRegistry the target registry
@param subTree the subtree | [
"public void mergeSubtree(final OperationTransformerRegistry targetRegistry, final Map<PathAddress, ModelVersion> subTree) {\n for(Map.Entry<PathAddress, ModelVersion> entry: subTree.entrySet()) {\n mergeSubtree(targetRegistry, entry.getKey(), entry.getValue());\n }\n }"
] | [
"public void set(int index, T object) {\n synchronized (mLock) {\n if (mOriginalValues != null) {\n mOriginalValues.set(index, object);\n } else {\n mObjects.set(index, object);\n }\n }\n if (mNotifyOnChange) notifyDataSetChanged();\n }",
"private static String quoteSort(Sort[] sort) {\n LinkedList<String> sorts = new LinkedList<String>();\n for (Sort pair : sort) {\n sorts.add(String.format(\"{%s: %s}\", Helpers.quote(pair.getName()), Helpers.quote(pair.getOrder().toString())));\n }\n return sorts.toString();\n }",
"public String getValueForDisplayValue(final String key) {\n if (mapDisplayValuesToValues.containsKey(key)) {\n return mapDisplayValuesToValues.get(key);\n }\n return key;\n }",
"private void readTasks(Project gpProject)\n {\n Tasks tasks = gpProject.getTasks();\n readTaskCustomPropertyDefinitions(tasks);\n for (net.sf.mpxj.ganttproject.schema.Task task : tasks.getTask())\n {\n readTask(m_projectFile, task);\n }\n }",
"public void setStatusBarColor(int statusBarColor) {\n if (mBuilder.mScrimInsetsLayout != null) {\n mBuilder.mScrimInsetsLayout.setInsetForeground(statusBarColor);\n mBuilder.mScrimInsetsLayout.getView().invalidate();\n }\n }",
"private Class<?> beanType(String name) {\n\t\tClass<?> type = context.getType(name);\n\t\tif (ClassUtils.isCglibProxyClass(type)) {\n\t\t\treturn AopProxyUtils.ultimateTargetClass(context.getBean(name));\n\t\t}\n\t\treturn type;\n\t}",
"private Table getTable(String name)\n {\n Table table = m_tables.get(name);\n if (table == null)\n {\n table = EMPTY_TABLE;\n }\n return table;\n }",
"public static List<Integer> getAllPartitions(AdminClient adminClient) {\n List<Integer> partIds = Lists.newArrayList();\n partIds = Lists.newArrayList();\n for(Node node: adminClient.getAdminClientCluster().getNodes()) {\n partIds.addAll(node.getPartitionIds());\n }\n return partIds;\n }",
"public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection(BoxConfig boxConfig) {\n\n BoxDeveloperEditionAPIConnection connection = getAppEnterpriseConnection(boxConfig.getEnterpriseId(),\n boxConfig.getClientId(), boxConfig.getClientSecret(), boxConfig.getJWTEncryptionPreferences());\n\n return connection;\n }"
] |
Create a forward curve from given times and discount factors.
The forward curve will have times.length-1 fixing times from times[0] to times[times.length-2]
<code>
forward[timeIndex] = (givenDiscountFactors[timeIndex]/givenDiscountFactors[timeIndex+1]-1.0) / (times[timeIndex+1] - times[timeIndex]);
</code>
Note: If time[0] > 0, then the discount factor 1.0 will inserted at time 0.0
@param name The name of this curve.
@param times A vector of given time points.
@param givenDiscountFactors A vector of given discount factors (corresponding to the given time points).
@param paymentOffset The maturity of the underlying index modeled by this curve.
@return A new ForwardCurve object. | [
"public static ForwardCurveInterpolation createForwardCurveFromDiscountFactors(String name, double[] times, RandomVariable[] givenDiscountFactors, double paymentOffset) {\n\t\tForwardCurveInterpolation forwardCurveInterpolation = new ForwardCurveInterpolation(name, paymentOffset, InterpolationEntityForward.FORWARD, null);\n\n\t\tif(times.length == 0) {\n\t\t\tthrow new IllegalArgumentException(\"Vector of times must not be empty.\");\n\t\t}\n\n\t\tif(times[0] > 0) {\n\t\t\t// Add first forward\n\t\t\tRandomVariable forward = givenDiscountFactors[0].sub(1.0).pow(-1.0).div(times[0]);\n\t\t\tforwardCurveInterpolation.addForward(null, 0.0, forward, true);\n\t\t}\n\n\t\tfor(int timeIndex=0; timeIndex<times.length-1;timeIndex++) {\n\t\t\tRandomVariable \tforward\t\t= givenDiscountFactors[timeIndex].div(givenDiscountFactors[timeIndex+1].sub(1.0)).div(times[timeIndex+1] - times[timeIndex]);\n\t\t\tdouble\tfixingTime\t= times[timeIndex];\n\t\t\tboolean\tisParameter\t= (fixingTime > 0);\n\t\t\tforwardCurveInterpolation.addForward(null, fixingTime, forward, isParameter);\n\t\t}\n\n\t\treturn forwardCurveInterpolation;\n\t}"
] | [
"public void addColumn(String columnName, boolean searchable, boolean orderable,\n String searchValue) {\n this.columns.add(new Column(columnName, \"\", searchable, orderable,\n new Search(searchValue, false)));\n }",
"public boolean setUpCameraForVrMode(final int fpsMode) {\n\n cameraSetUpStatus = false;\n this.fpsMode = fpsMode;\n\n if (!isCameraOpen) {\n Log.e(TAG, \"Camera is not open\");\n return false;\n }\n if (fpsMode < 0 || fpsMode > 2) {\n Log.e(TAG,\n \"Invalid fpsMode: %d. It can only take values 0, 1, or 2.\", fpsMode);\n } else {\n Parameters params = camera.getParameters();\n\n // check if the device supports vr mode preview\n if (\"true\".equalsIgnoreCase(params.get(\"vrmode-supported\"))) {\n\n Log.v(TAG, \"VR Mode supported!\");\n\n // set vr mode\n params.set(\"vrmode\", 1);\n\n // true if the apps intend to record videos using\n // MediaRecorder\n params.setRecordingHint(true);\n\n // set preview size\n // params.setPreviewSize(640, 480);\n\n // set fast-fps-mode: 0 for 30fps, 1 for 60 fps,\n // 2 for 120 fps\n params.set(\"fast-fps-mode\", fpsMode);\n\n switch (fpsMode) {\n case 0: // 30 fps\n params.setPreviewFpsRange(30000, 30000);\n break;\n case 1: // 60 fps\n params.setPreviewFpsRange(60000, 60000);\n break;\n case 2: // 120 fps\n params.setPreviewFpsRange(120000, 120000);\n break;\n default:\n }\n\n // for auto focus\n params.set(\"focus-mode\", \"continuous-video\");\n\n params.setVideoStabilization(false);\n if (\"true\".equalsIgnoreCase(params.get(\"ois-supported\"))) {\n params.set(\"ois\", \"center\");\n }\n\n camera.setParameters(params);\n cameraSetUpStatus = true;\n }\n }\n\n return cameraSetUpStatus;\n }",
"private void updateBeatGrid(TrackMetadataUpdate update, BeatGrid beatGrid) {\n hotCache.put(DeckReference.getDeckReference(update.player, 0), beatGrid); // 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), beatGrid);\n }\n }\n }\n deliverBeatGridUpdate(update.player, beatGrid);\n }",
"public static void main(String[] args) throws IOException, ClassNotFoundException {\r\n CoNLLDocumentReaderAndWriter f = new CoNLLDocumentReaderAndWriter();\r\n f.init(new SeqClassifierFlags());\r\n int numDocs = 0;\r\n int numTokens = 0;\r\n int numEntities = 0;\r\n String lastAnsBase = \"\";\r\n for (Iterator<List<CoreLabel>> it = f.getIterator(new FileReader(args[0])); it.hasNext(); ) {\r\n List<CoreLabel> doc = it.next();\r\n numDocs++;\r\n for (CoreLabel fl : doc) {\r\n // System.out.println(\"FL \" + (++i) + \" was \" + fl);\r\n if (fl.word().equals(BOUNDARY)) {\r\n continue;\r\n }\r\n String ans = fl.get(AnswerAnnotation.class);\r\n String ansBase;\r\n String ansPrefix;\r\n String[] bits = ans.split(\"-\");\r\n if (bits.length == 1) {\r\n ansBase = bits[0];\r\n ansPrefix = \"\";\r\n } else {\r\n ansBase = bits[1];\r\n ansPrefix = bits[0];\r\n }\r\n numTokens++;\r\n if (ansBase.equals(\"O\")) {\r\n } else if (ansBase.equals(lastAnsBase)) {\r\n if (ansPrefix.equals(\"B\")) {\r\n numEntities++;\r\n }\r\n } else {\r\n numEntities++;\r\n }\r\n }\r\n }\r\n System.out.println(\"File \" + args[0] + \" has \" + numDocs + \" documents, \" +\r\n numTokens + \" (non-blank line) tokens and \" +\r\n numEntities + \" entities.\");\r\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 Diff compare(CtElement left, CtElement right) {\n\t\tfinal SpoonGumTreeBuilder scanner = new SpoonGumTreeBuilder();\n\t\treturn new DiffImpl(scanner.getTreeContext(), scanner.getTree(left), scanner.getTree(right));\n\t}",
"synchronized void removeEvents(Table table) {\n final String tName = table.getName();\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n db.delete(tName, null, null);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error removing all events from table \" + tName + \" Recreating DB\");\n deleteDB();\n } finally {\n dbHelper.close();\n }\n }",
"public boolean checkPrefixes(String uri, String[] patterns) {\n\t\tfor (String pattern : patterns) {\n\t\t\tif (pattern.length() > 0) {\n\t\t\t\tif (uri.startsWith(pattern)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public void generateMapFile(File jarFile, String mapFileName, boolean mapClassMethods) throws XMLStreamException, IOException, ClassNotFoundException, IntrospectionException\n {\n m_responseList = new LinkedList<String>();\n writeMapFile(mapFileName, jarFile, mapClassMethods);\n }"
] |
Read the domain controller's data from an input stream.
@param instream the input stream
@throws Exception | [
"public void readFrom(DataInput instream) throws Exception {\n host = S3Util.readString(instream);\n port = instream.readInt();\n protocol = S3Util.readString(instream);\n }"
] | [
"public void removeLinks(ServiceReference<S> declarationBinderRef) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n if (declaration.getStatus().getServiceReferencesBounded().contains(declarationBinderRef)) {\n linkerManagement.unlink(declaration, declarationBinderRef);\n }\n }\n }",
"public void addFieldDescriptor(FieldDescriptor fld)\r\n {\r\n fld.setClassDescriptor(this); // BRJ\r\n if (m_FieldDescriptions == null)\r\n {\r\n m_FieldDescriptions = new FieldDescriptor[1];\r\n m_FieldDescriptions[0] = fld;\r\n }\r\n else\r\n {\r\n int size = m_FieldDescriptions.length;\r\n FieldDescriptor[] tmpArray = new FieldDescriptor[size + 1];\r\n System.arraycopy(m_FieldDescriptions, 0, tmpArray, 0, size);\r\n tmpArray[size] = fld;\r\n m_FieldDescriptions = tmpArray;\r\n // 2. Sort fields according to their getOrder() Property\r\n Arrays.sort(m_FieldDescriptions, FieldDescriptor.getComparator());\r\n }\r\n\r\n m_fieldDescriptorNameMap = null;\r\n m_PkFieldDescriptors = null;\r\n m_nonPkFieldDescriptors = null;\r\n m_lockingFieldDescriptors = null;\r\n m_RwFieldDescriptors = null;\r\n m_RwNonPkFieldDescriptors = null;\r\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 boolean equal(Vector3f v1, Vector3f v2) {\n return equal(v1.x, v2.x) && equal(v1.y, v2.y) && equal(v1.z, v2.z);\n }",
"protected FieldDescriptor getFieldDescriptor(TableAlias aTableAlias, PathInfo aPathInfo)\r\n {\r\n FieldDescriptor fld = null;\r\n String colName = aPathInfo.column;\r\n\r\n if (aTableAlias != null)\r\n {\r\n fld = aTableAlias.cld.getFieldDescriptorByName(colName);\r\n if (fld == null)\r\n {\r\n ObjectReferenceDescriptor ord = aTableAlias.cld.getObjectReferenceDescriptorByName(colName);\r\n if (ord != null)\r\n {\r\n fld = getFldFromReference(aTableAlias, ord);\r\n }\r\n else\r\n {\r\n fld = getFldFromJoin(aTableAlias, colName);\r\n }\r\n }\r\n }\r\n\r\n return fld;\r\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 GroovyFieldDoc[] properties() {\n Collections.sort(properties);\n return properties.toArray(new GroovyFieldDoc[properties.size()]);\n }",
"public Map<String, String> getMapAttribute(String name, String defaultValue) {\n return mapSplit(getAttribute(name), defaultValue);\n }",
"public static boolean compareAnnotatedTypes(AnnotatedType<?> t1, AnnotatedType<?> t2) {\n if (!t1.getJavaClass().equals(t2.getJavaClass())) {\n return false;\n }\n if (!compareAnnotated(t1, t2)) {\n return false;\n }\n\n if (t1.getFields().size() != t2.getFields().size()) {\n return false;\n }\n Map<Field, AnnotatedField<?>> fields = new HashMap<Field, AnnotatedField<?>>();\n for (AnnotatedField<?> f : t2.getFields()) {\n fields.put(f.getJavaMember(), f);\n }\n for (AnnotatedField<?> f : t1.getFields()) {\n if (fields.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedField(f, fields.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n\n if (t1.getMethods().size() != t2.getMethods().size()) {\n return false;\n }\n Map<Method, AnnotatedMethod<?>> methods = new HashMap<Method, AnnotatedMethod<?>>();\n for (AnnotatedMethod<?> f : t2.getMethods()) {\n methods.put(f.getJavaMember(), f);\n }\n for (AnnotatedMethod<?> f : t1.getMethods()) {\n if (methods.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, methods.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n if (t1.getConstructors().size() != t2.getConstructors().size()) {\n return false;\n }\n Map<Constructor<?>, AnnotatedConstructor<?>> constructors = new HashMap<Constructor<?>, AnnotatedConstructor<?>>();\n for (AnnotatedConstructor<?> f : t2.getConstructors()) {\n constructors.put(f.getJavaMember(), f);\n }\n for (AnnotatedConstructor<?> f : t1.getConstructors()) {\n if (constructors.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, constructors.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n return true;\n\n }"
] |
Returns true if super class of the parameter exists and is abstract and package private. In such case we want to omit such method.
See WELD-2507 and Oracle issue - https://bugs.java.com/view_bug.do?bug_id=6342411
@return true if the super class exists and is abstract and package private | [
"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 }"
] | [
"synchronized void bulkRegisterSingleton() {\n for (Map.Entry<Class<? extends AppService>, AppService> entry : registry.entrySet()) {\n if (isSingletonService(entry.getKey())) {\n app.registerSingleton(entry.getKey(), entry.getValue());\n }\n }\n }",
"public static Integer convertOverrideIdentifier(String overrideIdentifier) throws Exception {\n Integer overrideId = -1;\n\n try {\n // there is an issue with parseInt where it does not parse negative values correctly\n boolean isNegative = false;\n if (overrideIdentifier.startsWith(\"-\")) {\n isNegative = true;\n overrideIdentifier = overrideIdentifier.substring(1);\n }\n overrideId = Integer.parseInt(overrideIdentifier);\n\n if (isNegative) {\n overrideId = 0 - overrideId;\n }\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n\n // split into two parts\n String className = null;\n String methodName = null;\n int lastDot = overrideIdentifier.lastIndexOf(\".\");\n className = overrideIdentifier.substring(0, lastDot);\n methodName = overrideIdentifier.substring(lastDot + 1);\n\n overrideId = OverrideService.getInstance().getOverrideIdForMethod(className, methodName);\n }\n\n return overrideId;\n }",
"private ProjectFile handleByteOrderMark(InputStream stream, int length, Charset charset) throws Exception\n {\n UniversalProjectReader reader = new UniversalProjectReader();\n reader.setSkipBytes(length);\n reader.setCharset(charset);\n return reader.read(stream);\n }",
"public static <K,V> Map<K,V> asImmutable(Map<? extends K, ? extends V> self) {\n return Collections.unmodifiableMap(self);\n }",
"public static <T> void notNull(final String name, final T value) {\n if (value == null) {\n throw new IllegalArgumentException(name + \" can not be null\");\n }\n }",
"@Override\n protected void registerRequest(RestRequestValidator requestValidator,\n ChannelHandlerContext ctx,\n MessageEvent messageEvent) {\n\n // At this point we know the request is valid and we have a\n // error handler. So we construct the composite Voldemort\n // request object.\n CompositeVoldemortRequest<ByteArray, byte[]> requestObject = requestValidator.constructCompositeVoldemortRequestObject();\n\n if(requestObject != null) {\n\n DynamicTimeoutStoreClient<ByteArray, byte[]> storeClient = null;\n\n if(!requestValidator.getStoreName().equalsIgnoreCase(RestMessageHeaders.SCHEMATA_STORE)) {\n\n storeClient = this.fatClientMap.get(requestValidator.getStoreName());\n if(storeClient == null) {\n logger.error(\"Error when getting store. Non Existing store client.\");\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Non Existing store client. Critical error.\");\n return;\n }\n } else {\n requestObject.setOperationType(VoldemortOpCode.GET_METADATA_OP_CODE);\n }\n\n CoordinatorStoreClientRequest coordinatorRequest = new CoordinatorStoreClientRequest(requestObject,\n storeClient);\n Channels.fireMessageReceived(ctx, coordinatorRequest);\n\n }\n }",
"public static Object newInstance(Class target, Class[] types, Object[] args) throws InstantiationException,\r\n IllegalAccessException,\r\n IllegalArgumentException,\r\n InvocationTargetException,\r\n NoSuchMethodException,\r\n SecurityException\r\n {\r\n return newInstance(target, types, args, false);\r\n }",
"public int compare(final Version other) throws IncomparableException{\n\t\t// Cannot compare branch versions and others \n\t\tif(!isBranch().equals(other.isBranch())){\n\t\t\tthrow new IncomparableException();\n\t\t}\n\t\t\n\t\t// Compare digits\n\t\tfinal int minDigitSize = getDigitsSize() < other.getDigitsSize()? getDigitsSize(): other.getDigitsSize();\n\t\t\n\t\tfor(int i = 0; i < minDigitSize ; i++){\n\t\t\tif(!getDigit(i).equals(other.getDigit(i))){\n\t\t\t\treturn getDigit(i).compareTo(other.getDigit(i));\n\t\t\t}\n\t\t}\n\t\t\n\t\t// If not the same number of digits and the first digits are equals, the longest is the newer\n\t\tif(!getDigitsSize().equals(other.getDigitsSize())){\n\t\t\treturn getDigitsSize() > other.getDigitsSize()? 1: -1;\n\t\t}\n\n if(isBranch() && !getBranchId().equals(other.getBranchId())){\n\t\t\treturn getBranchId().compareTo(other.getBranchId());\n\t\t}\n\t\t\n\t\t// if the digits are the same, a snapshot is newer than a release\n\t\tif(isSnapshot() && other.isRelease()){\n\t\t\treturn 1;\n\t\t}\n\t\t\n\t\tif(isRelease() && other.isSnapshot()){\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\t// if both versions are releases, compare the releaseID\n\t\tif(isRelease() && other.isRelease()){\n\t\t\treturn getReleaseId().compareTo(other.getReleaseId());\n\t\t}\n\t\t\n\t\treturn 0;\n\t}",
"public static void installManagementChannelServices(\n final ServiceTarget serviceTarget,\n final ServiceName endpointName,\n final AbstractModelControllerOperationHandlerFactoryService operationHandlerService,\n final ServiceName modelControllerName,\n final String channelName,\n final ServiceName executorServiceName,\n final ServiceName scheduledExecutorServiceName) {\n\n final OptionMap options = OptionMap.EMPTY;\n final ServiceName operationHandlerName = endpointName.append(channelName).append(ModelControllerClientOperationHandlerFactoryService.OPERATION_HANDLER_NAME_SUFFIX);\n\n serviceTarget.addService(operationHandlerName, operationHandlerService)\n .addDependency(modelControllerName, ModelController.class, operationHandlerService.getModelControllerInjector())\n .addDependency(executorServiceName, ExecutorService.class, operationHandlerService.getExecutorInjector())\n .addDependency(scheduledExecutorServiceName, ScheduledExecutorService.class, operationHandlerService.getScheduledExecutorInjector())\n .setInitialMode(ACTIVE)\n .install();\n\n installManagementChannelOpenListenerService(serviceTarget, endpointName, channelName, operationHandlerName, options, false);\n }"
] |
Use this API to disable vserver of given name. | [
"public static base_response disable(nitro_service client, String name) throws Exception {\n\t\tvserver disableresource = new vserver();\n\t\tdisableresource.name = name;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}"
] | [
"public synchronized void reset() {\n this.authorizerDescription = StandardRBACAuthorizer.AUTHORIZER_DESCRIPTION;\n this.useIdentityRoles = this.nonFacadeMBeansSensitive = false;\n this.roleMappings = new HashMap<String, RoleMappingImpl>();\n RoleMaps oldRoleMaps = this.roleMaps;\n this.roleMaps = new RoleMaps(authorizerDescription.getStandardRoles(), Collections.<String, ScopedRole>emptyMap());\n for (ScopedRole role : oldRoleMaps.scopedRoles.values()) {\n for (ScopedRoleListener listener : scopedRoleListeners) {\n try {\n listener.scopedRoleRemoved(role);\n } catch (Exception ignored) {\n // TODO log an ERROR\n }\n }\n }\n }",
"protected static void checkChannels(final Iterable<String> channels) {\n if (channels == null) {\n throw new IllegalArgumentException(\"channels must not be null\");\n }\n for (final String channel : channels) {\n if (channel == null || \"\".equals(channel)) {\n throw new IllegalArgumentException(\"channels' members must not be null: \" + channels);\n }\n }\n }",
"OTMConnection getConnection()\r\n {\r\n if (m_connection == null)\r\n {\r\n OTMConnectionRuntimeException ex = new OTMConnectionRuntimeException(\"Connection is null.\");\r\n sendEvents(ConnectionEvent.CONNECTION_ERROR_OCCURRED, ex, null);\r\n }\r\n return m_connection;\r\n }",
"public static sslvserver_sslciphersuite_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslciphersuite_binding obj = new sslvserver_sslciphersuite_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslciphersuite_binding response[] = (sslvserver_sslciphersuite_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void computeGradientAndHessian(DMatrixRMaj param )\n {\n // residuals = f(x) - y\n function.compute(param, residuals);\n\n computeNumericalJacobian(param,jacobian);\n\n CommonOps_DDRM.multTransA(jacobian, residuals, g);\n CommonOps_DDRM.multTransA(jacobian, jacobian, H);\n\n CommonOps_DDRM.extractDiag(H,Hdiag);\n }",
"public EventBus emit(Enum<?> event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }",
"@Override\n public ActivityInterface getActivityInterface() {\n if (activityInterface == null) {\n activityInterface = new ActivityInterface(apiKey, sharedSecret, transport);\n }\n return activityInterface;\n }",
"public static PasswordSpec parse(String spec) {\n char[] ca = spec.toCharArray();\n int len = ca.length;\n illegalIf(0 == len, spec);\n Builder builder = new Builder();\n StringBuilder minBuf = new StringBuilder();\n StringBuilder maxBuf = new StringBuilder();\n boolean lenSpecStart = false;\n boolean minPart = false;\n for (int i = 0; i < len; ++i) {\n char c = ca[i];\n switch (c) {\n case SPEC_LOWERCASE:\n illegalIf(lenSpecStart, spec);\n builder.requireLowercase();\n break;\n case SPEC_UPPERCASE:\n illegalIf(lenSpecStart, spec);\n builder.requireUppercase();\n break;\n case SPEC_SPECIAL_CHAR:\n illegalIf(lenSpecStart, spec);\n builder.requireSpecialChar();\n break;\n case SPEC_LENSPEC_START:\n lenSpecStart = true;\n minPart = true;\n break;\n case SPEC_LENSPEC_CLOSE:\n illegalIf(minPart, spec);\n lenSpecStart = false;\n break;\n case SPEC_LENSPEC_SEP:\n minPart = false;\n break;\n case SPEC_DIGIT:\n if (!lenSpecStart) {\n builder.requireDigit();\n } else {\n if (minPart) {\n minBuf.append(c);\n } else {\n maxBuf.append(c);\n }\n }\n break;\n default:\n illegalIf(!lenSpecStart || !isDigit(c), spec);\n if (minPart) {\n minBuf.append(c);\n } else {\n maxBuf.append(c);\n }\n }\n }\n illegalIf(lenSpecStart, spec);\n if (minBuf.length() != 0) {\n builder.minLength(Integer.parseInt(minBuf.toString()));\n }\n if (maxBuf.length() != 0) {\n builder.maxLength(Integer.parseInt(maxBuf.toString()));\n }\n return builder;\n }",
"private Map<String, Table> getIndex(Table table)\n {\n Map<String, Table> result;\n\n if (!table.getResourceFlag())\n {\n result = m_taskTablesByName;\n }\n else\n {\n result = m_resourceTablesByName;\n }\n return result;\n }"
] |
Gathers all parameters' annotations for the given method, starting from the third parameter. | [
"private List<Map<Class<? extends Annotation>, ParameterInfo<?>>> createParametersInfos(Method method) {\n if (method.getParameterTypes().length <= 2) {\n return Collections.emptyList();\n }\n\n List<Map<Class<? extends Annotation>, ParameterInfo<?>>> result = new ArrayList<>();\n Type[] parameterTypes = method.getGenericParameterTypes();\n Annotation[][] parameterAnnotations = method.getParameterAnnotations();\n\n for (int i = 2; i < parameterAnnotations.length; i++) {\n Annotation[] annotations = parameterAnnotations[i];\n Map<Class<? extends Annotation>, ParameterInfo<?>> paramAnnotations = new IdentityHashMap<>();\n\n for (Annotation annotation : annotations) {\n Class<? extends Annotation> annotationType = annotation.annotationType();\n ParameterInfo<?> parameterInfo;\n\n if (PathParam.class.isAssignableFrom(annotationType)) {\n parameterInfo = ParameterInfo.create(annotation,\n ParamConvertUtils.createPathParamConverter(parameterTypes[i]));\n } else if (QueryParam.class.isAssignableFrom(annotationType)) {\n parameterInfo = ParameterInfo.create(annotation,\n ParamConvertUtils.createQueryParamConverter(parameterTypes[i]));\n } else if (HeaderParam.class.isAssignableFrom(annotationType)) {\n parameterInfo = ParameterInfo.create(annotation,\n ParamConvertUtils.createHeaderParamConverter(parameterTypes[i]));\n } else {\n parameterInfo = ParameterInfo.create(annotation, null);\n }\n\n paramAnnotations.put(annotationType, parameterInfo);\n }\n\n // Must have either @PathParam, @QueryParam or @HeaderParam, but not two or more.\n int presence = 0;\n for (Class<? extends Annotation> annotationClass : paramAnnotations.keySet()) {\n if (SUPPORTED_PARAM_ANNOTATIONS.contains(annotationClass)) {\n presence++;\n }\n }\n if (presence != 1) {\n throw new IllegalArgumentException(\n String.format(\"Must have exactly one annotation from %s for parameter %d in method %s\",\n SUPPORTED_PARAM_ANNOTATIONS, i, method));\n }\n\n result.add(Collections.unmodifiableMap(paramAnnotations));\n }\n\n return Collections.unmodifiableList(result);\n }"
] | [
"private void ensureReferencedPKs(ModelDef modelDef, ReferenceDescriptorDef refDef) throws ConstraintException\r\n {\r\n String targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF);\r\n ClassDescriptorDef targetClassDef = modelDef.getClass(targetClassName);\r\n\r\n ensurePKsFromHierarchy(targetClassDef);\r\n }",
"@SafeVarargs\n public static <T> Set<T> create(final T... values) {\n Set<T> result = new HashSet<>(values.length);\n Collections.addAll(result, values);\n return result;\n }",
"public static String getDefaultJdbcTypeFor(String javaType)\r\n {\r\n return _jdbcMappings.containsKey(javaType) ? (String)_jdbcMappings.get(javaType) : JDBC_DEFAULT_TYPE;\r\n }",
"public void add(StatementRank rank, Resource subject) {\n\t\tif (this.bestRank == rank) {\n\t\t\tsubjects.add(subject);\n\t\t} else if(bestRank == StatementRank.NORMAL && rank == StatementRank.PREFERRED) {\n\t\t\t//We found a preferred statement\n\t\t\tsubjects.clear();\n\t\t\tbestRank = StatementRank.PREFERRED;\n\t\t\tsubjects.add(subject);\n\t\t}\n\t}",
"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 <A extends Collection<? super ResultT>> A into(final A target) {\n forEach(new Block<ResultT>() {\n @Override\n public void apply(@Nonnull final ResultT t) {\n target.add(t);\n }\n });\n return target;\n }",
"public OpenShiftAssistantTemplate parameter(String name, String value) {\n parameterValues.put(name, value);\n return this;\n }",
"public static void main(String[] args) {\r\n //Adding custom equivalence class generation transformer - NOTE this will get applied during graph traversal-->\r\n //MODEL USAGE EXAMPLE: <assign name=\"var_out_V1_2\" expr=\"%ssn\"/> <dg:transform name=\"EQ\"/>\r\n Map<String, DataTransformer> transformers = new HashMap<String, DataTransformer>();\r\n transformers.put(\"EQ\", new EquivalenceClassTransformer());\r\n Vector<CustomTagExtension> cte = new Vector<CustomTagExtension>();\r\n cte.add(new InLineTransformerExtension(transformers));\r\n Engine engine = new SCXMLEngine(cte);\n\r\n //will default to samplemachine, but you could specify a different file if you choose to\r\n InputStream is = CmdLine.class.getResourceAsStream(\"/\" + (args.length == 0 ? \"samplemachine\" : args[0]) + \".xml\");\n\r\n engine.setModelByInputFileStream(is);\n\r\n // Usually, this should be more than the number of threads you intend to run\r\n engine.setBootstrapMin(1);\n\r\n //Prepare the consumer with the proper writer and transformer\r\n DataConsumer consumer = new DataConsumer();\r\n consumer.addDataTransformer(new SampleMachineTransformer());\n\r\n //Adding custom equivalence class generation transformer - NOTE this will get applied post data generation.\r\n //MODEL USAGE EXAMPLE: <dg:assign name=\"var_out_V2\" set=\"%regex([0-9]{3}[A-Z0-9]{5})\"/>\r\n consumer.addDataTransformer(new EquivalenceClassTransformer());\n\r\n consumer.addDataWriter(new DefaultWriter(System.out,\r\n new String[]{\"var_1_1\", \"var_1_2\", \"var_1_3\", \"var_1_4\", \"var_1_5\", \"var_1_6\", \"var_1_7\",\r\n \"var_2_1\", \"var_2_2\", \"var_2_3\", \"var_2_4\", \"var_2_5\", \"var_2_6\", \"var_2_7\", \"var_2_8\"}));\n\r\n //Prepare the distributor\r\n DefaultDistributor defaultDistributor = new DefaultDistributor();\r\n defaultDistributor.setThreadCount(1);\r\n defaultDistributor.setDataConsumer(consumer);\r\n Logger.getLogger(\"org.apache\").setLevel(Level.WARN);\n\r\n engine.process(defaultDistributor);\r\n }",
"public Response save() throws RequestException, LocalOperationException {\n Map<String, Object> templateData = new HashMap<String, Object>();\n templateData.put(\"name\", name);\n\n options.put(\"steps\", steps.toMap());\n\n templateData.put(\"template\", options);\n Request request = new Request(transloadit);\n return new Response(request.post(\"/templates\", templateData));\n }"
] |
Sets the top padding for all cells in the row.
@param paddingTop new padding, ignored if smaller than 0
@return this to allow chaining | [
"public AT_Row setPaddingTop(int paddingTop) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingTop(paddingTop);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}"
] | [
"public DbOrganization getOrganization(final DbArtifact dbArtifact) {\n final DbModule module = getModule(dbArtifact);\n\n if(module == null || module.getOrganization() == null){\n return null;\n }\n\n return repositoryHandler.getOrganization(module.getOrganization());\n }",
"private void writeExceptions9(List<Project.Calendars.Calendar.WeekDays.WeekDay> dayList, List<ProjectCalendarException> exceptions)\n {\n for (ProjectCalendarException exception : exceptions)\n {\n boolean working = exception.getWorking();\n\n Project.Calendars.Calendar.WeekDays.WeekDay day = m_factory.createProjectCalendarsCalendarWeekDaysWeekDay();\n dayList.add(day);\n day.setDayType(BIGINTEGER_ZERO);\n day.setDayWorking(Boolean.valueOf(working));\n\n Project.Calendars.Calendar.WeekDays.WeekDay.TimePeriod period = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayTimePeriod();\n day.setTimePeriod(period);\n period.setFromDate(exception.getFromDate());\n period.setToDate(exception.getToDate());\n\n if (working)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimes();\n day.setWorkingTimes(times);\n List<Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime> timesList = times.getWorkingTime();\n\n for (DateRange range : exception)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime time = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimesWorkingTime();\n timesList.add(time);\n\n time.setFromTime(range.getStart());\n time.setToTime(range.getEnd());\n }\n }\n }\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void markReadInboxMessage(final CTInboxMessage message){\n postAsyncSafely(\"markReadInboxMessage\", new Runnable() {\n @Override\n public void run() {\n synchronized (inboxControllerLock) {\n if(ctInboxController != null){\n boolean read = ctInboxController.markReadForMessageWithId(message.getMessageId());\n if (read) {\n _notifyInboxMessagesDidUpdate();\n }\n } else {\n getConfigLogger().debug(getAccountId(),\"Notification Inbox not initialized\");\n }\n }\n }\n });\n }",
"public void postArtifact(final Artifact artifact, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.artifactResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, artifact);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST artifact\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }",
"public static int cudnnGetConvolutionNdDescriptor(\n cudnnConvolutionDescriptor convDesc, \n int arrayLengthRequested, \n int[] arrayLength, \n int[] padA, \n int[] strideA, \n int[] dilationA, \n int[] mode, \n int[] computeType)/** convolution data type */\n {\n return checkResult(cudnnGetConvolutionNdDescriptorNative(convDesc, arrayLengthRequested, arrayLength, padA, strideA, dilationA, mode, computeType));\n }",
"public void setDates(SortedSet<Date> dates, boolean checked) {\n\n m_checkBoxes.clear();\n for (Date date : dates) {\n CmsCheckBox cb = generateCheckBox(date, checked);\n m_checkBoxes.add(cb);\n }\n reInitLayoutElements();\n setDatesInternal(dates);\n }",
"@SuppressWarnings(\"unused\")\n public static void changeCredentials(String accountID, String token) {\n changeCredentials(accountID, token, null);\n }",
"public static Color cueColor(CueList.Entry entry) {\n if (entry.hotCueNumber > 0) {\n return Color.GREEN;\n }\n if (entry.isLoop) {\n return Color.ORANGE;\n }\n return Color.RED;\n }",
"public static Diagram parseJson(String json,\n Boolean keepGlossaryLink) throws JSONException {\n JSONObject modelJSON = new JSONObject(json);\n return parseJson(modelJSON,\n keepGlossaryLink);\n }"
] |
Returns the result of a stored procedure executed on the backend.
@param embeddedCacheManager embedded cache manager
@param storedProcedureName name of stored procedure
@param queryParameters parameters passed for this query
@param classLoaderService the class loader service
@return a {@link ClosableIterator} with the result of the query | [
"public ClosableIterator<Tuple> callStoredProcedure(EmbeddedCacheManager embeddedCacheManager, String storedProcedureName, ProcedureQueryParameters queryParameters, ClassLoaderService classLoaderService ) {\n\t\tvalidate( queryParameters );\n\t\tCache<String, String> cache = embeddedCacheManager.getCache( STORED_PROCEDURES_CACHE_NAME, true );\n\t\tString className = cache.getOrDefault( storedProcedureName, storedProcedureName );\n\t\tCallable<?> callable = instantiate( storedProcedureName, className, classLoaderService );\n\t\tsetParams( storedProcedureName, queryParameters, callable );\n\t\tObject res = execute( storedProcedureName, embeddedCacheManager, callable );\n\t\treturn extractResultSet( storedProcedureName, res );\n\t}"
] | [
"public void addFile(InputStream inputStream) {\n String name = \"file\";\n fileStreams.put(normalizeDuplicateName(name), inputStream);\n }",
"public static <T> T flattenOption(scala.Option<T> option) {\n if (option.isEmpty()) {\n return null;\n } else {\n return option.get();\n }\n }",
"private void clearDeckDetail(TrackMetadataUpdate update) {\n if (detailHotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) {\n deliverWaveformDetailUpdate(update.player, null);\n }\n }",
"public ServerSetup[] build(Properties properties) {\n List<ServerSetup> serverSetups = new ArrayList<>();\n\n String hostname = properties.getProperty(\"greenmail.hostname\", ServerSetup.getLocalHostAddress());\n long serverStartupTimeout =\n Long.parseLong(properties.getProperty(\"greenmail.startup.timeout\", \"-1\"));\n\n // Default setups\n addDefaultSetups(hostname, properties, serverSetups);\n\n // Default setups for test\n addTestSetups(hostname, properties, serverSetups);\n\n // Default setups\n for (String protocol : ServerSetup.PROTOCOLS) {\n addSetup(hostname, protocol, properties, serverSetups);\n }\n\n for (ServerSetup setup : serverSetups) {\n if (properties.containsKey(GREENMAIL_VERBOSE)) {\n setup.setVerbose(true);\n }\n if (serverStartupTimeout >= 0L) {\n setup.setServerStartupTimeout(serverStartupTimeout);\n }\n }\n\n return serverSetups.toArray(new ServerSetup[serverSetups.size()]);\n }",
"public void restartDyno(String appName, String dynoId) {\n connection.execute(new DynoRestart(appName, dynoId), apiKey);\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 }",
"private static void listHierarchy(ProjectFile file)\n {\n for (Task task : file.getChildTasks())\n {\n System.out.println(\"Task: \" + task.getName() + \"\\t\" + task.getStart() + \"\\t\" + task.getFinish());\n listHierarchy(task, \" \");\n }\n\n System.out.println();\n }",
"public static boolean hasValidContentAdditionParameterDefined(ModelNode operation) {\n for (String s : DeploymentAttributes.MANAGED_CONTENT_ATTRIBUTES.keySet()) {\n if (operation.hasDefined(s)) {\n return true;\n }\n }\n return false;\n }",
"@Override public void setID(Integer val)\n {\n ProjectFile parent = getParentFile();\n Integer previous = getID();\n\n if (previous != null)\n {\n parent.getTasks().unmapID(previous);\n }\n\n parent.getTasks().mapID(val, this);\n\n set(TaskField.ID, val);\n }"
] |
Write correlation id.
@param message the message
@param correlationId the correlation id | [
"public static void writeCorrelationId(Message message, String correlationId) {\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n headers.put(CORRELATIONID_HTTP_HEADER_NAME, Collections.singletonList(correlationId));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + CORRELATIONID_HTTP_HEADER_NAME + \"' set to: \" + correlationId);\n }\n }"
] | [
"public void removeExtension(Resource rootResource, String moduleName, ManagementResourceRegistration rootRegistration) throws IllegalStateException {\n final ManagementResourceRegistration profileReg;\n if (rootRegistration.getPathAddress().size() == 0) {\n //domain or server extension\n // Can't use processType.isServer() to determine where to look for profile reg because a lot of test infrastructure\n // doesn't add the profile mrr even in HC-based tests\n ManagementResourceRegistration reg = rootRegistration.getSubModel(PathAddress.pathAddress(PathElement.pathElement(PROFILE)));\n if (reg == null) {\n reg = rootRegistration;\n }\n profileReg = reg;\n } else {\n //host model extension\n profileReg = rootRegistration;\n }\n ManagementResourceRegistration deploymentsReg = processType.isServer() ? rootRegistration.getSubModel(PathAddress.pathAddress(PathElement.pathElement(DEPLOYMENT))) : null;\n\n ExtensionInfo extension = extensions.remove(moduleName);\n if (extension != null) {\n //noinspection SynchronizationOnLocalVariableOrMethodParameter\n synchronized (extension) {\n Set<String> subsystemNames = extension.subsystems.keySet();\n\n final boolean dcExtension = processType.isHostController() ?\n rootRegistration.getPathAddress().size() == 0 : false;\n\n for (String subsystem : subsystemNames) {\n if (hasSubsystemsRegistered(rootResource, subsystem, dcExtension)) {\n // Restore the data\n extensions.put(moduleName, extension);\n throw ControllerLogger.ROOT_LOGGER.removingExtensionWithRegisteredSubsystem(moduleName, subsystem);\n }\n }\n for (Map.Entry<String, SubsystemInformation> entry : extension.subsystems.entrySet()) {\n String subsystem = entry.getKey();\n profileReg.unregisterSubModel(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, subsystem));\n if (deploymentsReg != null) {\n deploymentsReg.unregisterSubModel(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, subsystem));\n deploymentsReg.unregisterSubModel(PathElement.pathElement(ModelDescriptionConstants.SUBDEPLOYMENT, subsystem));\n }\n\n if (extension.xmlMapper != null) {\n SubsystemInformationImpl subsystemInformation = SubsystemInformationImpl.class.cast(entry.getValue());\n for (String namespace : subsystemInformation.getXMLNamespaces()) {\n extension.xmlMapper.unregisterRootElement(new QName(namespace, SUBSYSTEM));\n }\n }\n }\n }\n }\n }",
"private void ensureNoTableInfoIfNoRepositoryInfo(ClassDescriptorDef classDef, String checkLevel)\r\n {\r\n if (!classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true))\r\n {\r\n classDef.setProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, \"false\");\r\n }\r\n }",
"public static void checkSvdMatrixSize(DMatrixRMaj U, boolean tranU, DMatrixRMaj W, DMatrixRMaj V, boolean tranV ) {\n int numSingular = Math.min(W.numRows,W.numCols);\n boolean compact = W.numRows == W.numCols;\n\n if( compact ) {\n if( U != null ) {\n if( tranU && U.numRows != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n else if( !tranU && U.numCols != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n }\n\n if( V != null ) {\n if( tranV && V.numRows != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n else if( !tranV && V.numCols != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n }\n } else {\n if( U != null && U.numRows != U.numCols )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n if( V != null && V.numRows != V.numCols )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n if( U != null && U.numRows != W.numRows )\n throw new IllegalArgumentException(\"Unexpected size of W\");\n if( V != null && V.numRows != W.numCols )\n throw new IllegalArgumentException(\"Unexpected size of W\");\n }\n }",
"public StatementBuilder withQualifierValue(PropertyIdValue propertyIdValue,\n\t\t\tValue value) {\n\t\twithQualifier(factory.getValueSnak(propertyIdValue, value));\n\t\treturn getThis();\n\t}",
"@PostConstruct\n\tprotected void postConstruct() {\n\t\tif (pixelPerUnitBased) {\n\t\t\t//\tCalculate numerator and denominator\n\t\t\tif (pixelPerUnit > PIXEL_PER_METER) {\n\t\t\t\tthis.numerator = pixelPerUnit / conversionFactor;\n\t\t\t\tthis.denominator = 1;\n\t\t\t} else {\n\t\t\t\tthis.numerator = 1;\n\t\t\t\tthis.denominator = PIXEL_PER_METER / pixelPerUnit;\n\t\t\t}\n\t\t\tsetPixelPerUnitBased(false);\n\t\t} else {\n\t\t\t// Calculate PPU\n\t\t\tthis.pixelPerUnit = numerator / denominator * conversionFactor;\n\t\t\tsetPixelPerUnitBased(true);\n\t\t}\n\t}",
"private void persistDisabledVersion(long version) throws PersistenceFailureException {\n File disabledMarker = getDisabledMarkerFile(version);\n try {\n disabledMarker.createNewFile();\n } catch (IOException e) {\n throw new PersistenceFailureException(\"Failed to create the disabled marker at path: \" +\n disabledMarker.getAbsolutePath() + \"\\nThe store/version \" +\n \"will remain disabled only until the next restart.\", e);\n }\n }",
"public int[] getVertexPointIndices() {\n int[] indices = new int[numVertices];\n for (int i = 0; i < numVertices; i++) {\n indices[i] = vertexPointIndices[i];\n }\n return indices;\n }",
"public List<Callouts.Callout> getCallout()\n {\n if (callout == null)\n {\n callout = new ArrayList<Callouts.Callout>();\n }\n return this.callout;\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 }"
] |
Returns the end time of the event.
@return the end time of the event. | [
"public Date getEnd() {\n\n if (null != m_explicitEnd) {\n return isWholeDay() ? adjustForWholeDay(m_explicitEnd, true) : m_explicitEnd;\n }\n if ((null == m_end) && (m_series.getInstanceDuration() != null)) {\n m_end = new Date(m_start.getTime() + m_series.getInstanceDuration().longValue());\n }\n return isWholeDay() && !m_series.isWholeDay() ? adjustForWholeDay(m_end, true) : m_end;\n }"
] | [
"public String generateInitScript(EnvVars env) throws IOException, InterruptedException {\n StringBuilder initScript = new StringBuilder();\n InputStream templateStream = getClass().getResourceAsStream(\"/initscripttemplate.gradle\");\n String templateAsString = IOUtils.toString(templateStream, Charsets.UTF_8.name());\n File extractorJar = PluginDependencyHelper.getExtractorJar(env);\n FilePath dependencyDir = PluginDependencyHelper.getActualDependencyDirectory(extractorJar, rootPath);\n String absoluteDependencyDirPath = dependencyDir.getRemote();\n absoluteDependencyDirPath = absoluteDependencyDirPath.replace(\"\\\\\", \"/\");\n String str = templateAsString.replace(\"${pluginLibDir}\", absoluteDependencyDirPath);\n initScript.append(str);\n return initScript.toString();\n }",
"public static responderpolicylabel_responderpolicy_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tresponderpolicylabel_responderpolicy_binding obj = new responderpolicylabel_responderpolicy_binding();\n\t\tobj.set_labelname(labelname);\n\t\tresponderpolicylabel_responderpolicy_binding response[] = (responderpolicylabel_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Duration getStartSlack()\n {\n Duration startSlack = (Duration) getCachedValue(TaskField.START_SLACK);\n if (startSlack == null)\n {\n Duration duration = getDuration();\n if (duration != null)\n {\n startSlack = DateHelper.getVariance(this, getEarlyStart(), getLateStart(), duration.getUnits());\n set(TaskField.START_SLACK, startSlack);\n }\n }\n return (startSlack);\n }",
"public Vector3Axis delta(Vector3f v) {\n Vector3Axis ret = new Vector3Axis(Float.NaN, Float.NaN, Float.NaN);\n if (x != Float.NaN && v.x != Float.NaN && !equal(x, v.x)) {\n ret.set(x - v.x, Layout.Axis.X);\n }\n if (y != Float.NaN && v.y != Float.NaN && !equal(y, v.y)) {\n ret.set(y - v.y, Layout.Axis.Y);\n }\n if (z != Float.NaN && v.z != Float.NaN && !equal(z, v.z)) {\n ret.set(z - v.z, Layout.Axis.Z);\n }\n return ret;\n }",
"private static void freeTempLOB(ClobWrapper clob, BlobWrapper blob)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tif (clob != null)\r\n\t\t\t{\r\n\t\t\t\t// If the CLOB is open, close it\r\n\t\t\t\tif (clob.isOpen())\r\n\t\t\t\t{\r\n\t\t\t\t\tclob.close();\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Free the memory used by this CLOB\r\n\t\t\t\tclob.freeTemporary();\r\n\t\t\t}\r\n\r\n\t\t\tif (blob != null)\r\n\t\t\t{\r\n\t\t\t\t// If the BLOB is open, close it\r\n\t\t\t\tif (blob.isOpen())\r\n\t\t\t\t{\r\n\t\t\t\t\tblob.close();\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Free the memory used by this BLOB\r\n\t\t\t\tblob.freeTemporary();\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n logger.error(\"Error during temporary LOB release\", e);\r\n\t\t}\r\n\t}",
"public FormAction setValuesInForm(Form form) {\r\n\t\tFormAction formAction = new FormAction();\r\n\t\tform.setFormAction(formAction);\r\n\t\tthis.forms.add(form);\r\n\t\treturn formAction;\r\n\t}",
"private void readResource(net.sf.mpxj.planner.schema.Resource plannerResource) throws MPXJException\n {\n Resource mpxjResource = m_projectFile.addResource();\n\n //mpxjResource.setResourceCalendar(m_projectFile.getBaseCalendarByUniqueID(getInteger(plannerResource.getCalendar())));\n mpxjResource.setEmailAddress(plannerResource.getEmail());\n mpxjResource.setUniqueID(getInteger(plannerResource.getId()));\n mpxjResource.setName(plannerResource.getName());\n mpxjResource.setNotes(plannerResource.getNote());\n mpxjResource.setInitials(plannerResource.getShortName());\n mpxjResource.setType(getInt(plannerResource.getType()) == 2 ? ResourceType.MATERIAL : ResourceType.WORK);\n //plannerResource.getStdRate();\n //plannerResource.getOvtRate();\n //plannerResource.getUnits();\n //plannerResource.getProperties();\n\n ProjectCalendar calendar = mpxjResource.addResourceCalendar();\n\n calendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n\n ProjectCalendar baseCalendar = m_projectFile.getCalendarByUniqueID(getInteger(plannerResource.getCalendar()));\n if (baseCalendar == null)\n {\n baseCalendar = m_defaultCalendar;\n }\n calendar.setParent(baseCalendar);\n\n m_eventManager.fireResourceReadEvent(mpxjResource);\n }",
"public static cachepolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tcachepolicylabel_binding obj = new cachepolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcachepolicylabel_binding response = (cachepolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void checkForCycles(DefaultDirectedWeightedGraph<RuleProvider, DefaultEdge> graph)\n {\n CycleDetector<RuleProvider, DefaultEdge> cycleDetector = new CycleDetector<>(graph);\n\n if (cycleDetector.detectCycles())\n {\n // if we have cycles, then try to throw an exception with some usable data\n Set<RuleProvider> cycles = cycleDetector.findCycles();\n StringBuilder errorSB = new StringBuilder();\n for (RuleProvider cycle : cycles)\n {\n errorSB.append(\"Found dependency cycle involving: \" + cycle.getMetadata().getID()).append(System.lineSeparator());\n Set<RuleProvider> subCycleSet = cycleDetector.findCyclesContainingVertex(cycle);\n for (RuleProvider subCycle : subCycleSet)\n {\n errorSB.append(\"\\tSubcycle: \" + subCycle.getMetadata().getID()).append(System.lineSeparator());\n }\n }\n throw new RuntimeException(\"Dependency cycles detected: \" + errorSB.toString());\n }\n }"
] |
The point that is the GOLDEN_SECTION along the way from a to b.
a may be less or greater than b, you find the point 60-odd percent
of the way from a to b.
@param a Interval minimum
@param b Interval maximum
@return The GOLDEN_SECTION along the way from a to b. | [
"private double goldenMean(double a, double b) {\r\n if (geometric) {\r\n return a * Math.pow(b / a, GOLDEN_SECTION);\r\n } else {\r\n return a + (b - a) * GOLDEN_SECTION;\r\n }\r\n }"
] | [
"public static String getAt(CharSequence self, Collection indices) {\n StringBuilder answer = new StringBuilder();\n for (Object value : indices) {\n if (value instanceof Range) {\n answer.append(getAt(self, (Range) value));\n } else if (value instanceof Collection) {\n answer.append(getAt(self, (Collection) value));\n } else {\n int idx = DefaultTypeTransformation.intUnbox(value);\n answer.append(getAt(self, idx));\n }\n }\n return answer.toString();\n }",
"public void evictCache(String key) {\n H.Session sess = session();\n if (null != sess) {\n sess.evict(key);\n } else {\n app().cache().evict(key);\n }\n }",
"private void deliverLostAnnouncement(final DeviceAnnouncement announcement) {\n for (final DeviceAnnouncementListener listener : getDeviceAnnouncementListeners()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n try {\n listener.deviceLost(announcement);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering device lost announcement to listener\", t);\n }\n }\n });\n }\n }",
"public static Class<?> resolveTypeArgument(Class<?> clazz, Class<?> genericIfc) {\n\t\tClass<?>[] typeArgs = resolveTypeArguments(clazz, genericIfc);\n\t\tif (typeArgs == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (typeArgs.length != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Expected 1 type argument on generic interface [\" +\n\t\t\t\t\tgenericIfc.getName() + \"] but found \" + typeArgs.length);\n\t\t}\n\t\treturn typeArgs[0];\n\t}",
"@Override\n public synchronized void start() {\n if (!started.getAndSet(true)) {\n finished.set(false);\n thread.start();\n }\n }",
"public Collection<DataSource> getDataSources(int groupno) {\n if (groupno == 1)\n return group1;\n else if (groupno == 2)\n return group2;\n else\n throw new DukeConfigException(\"Invalid group number: \" + groupno);\n }",
"public static URL classFileUrl(Class<?> clazz) throws IOException {\n ClassLoader cl = clazz.getClassLoader();\n if (cl == null) {\n cl = ClassLoader.getSystemClassLoader();\n }\n URL res = cl.getResource(clazz.getName().replace('.', '/') + \".class\");\n if (res == null) {\n throw new IllegalArgumentException(\"Unable to locate class file for \" + clazz);\n }\n return res;\n }",
"public void start(String name)\n {\n GVRAnimator anim = findAnimation(name);\n\n if (name.equals(anim.getName()))\n {\n start(anim);\n return;\n }\n }",
"protected void processAliases(List<MonolingualTextValue> addAliases, List<MonolingualTextValue> deleteAliases) {\n for(MonolingualTextValue val : addAliases) {\n addAlias(val);\n }\n for(MonolingualTextValue val : deleteAliases) {\n deleteAlias(val);\n }\n }"
] |
The nullity of the decomposed matrix.
@see SingularOps_DDRM#nullity(SingularValueDecomposition_F64, double)
@return The matrix's nullity | [
"public int nullity() {\n if( is64 ) {\n return SingularOps_DDRM.nullity((SingularValueDecomposition_F64)svd, 10.0 * UtilEjml.EPS);\n } else {\n return SingularOps_FDRM.nullity((SingularValueDecomposition_F32)svd, 5.0f * UtilEjml.F_EPS);\n }\n }"
] | [
"@Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n\n // If the API level is less than 11, we can't rely on the view animation system to\n // do the scrolling animation. Need to tick it here and call postInvalidate() until the scrolling is done.\n if (Build.VERSION.SDK_INT < 11) {\n tickScrollAnimation();\n if (!mScroller.isFinished()) {\n mGraph.postInvalidate();\n }\n }\n }",
"@Override\r\n public String upload(InputStream in, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(in);\r\n return sendUploadRequest(metaData, payload);\r\n }",
"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 }",
"public void addCommandClass(ZWaveCommandClass commandClass)\n\t{\n\t\tZWaveCommandClass.CommandClass key = commandClass.getCommandClass();\n\t\t\n\t\tif (!supportedCommandClasses.containsKey(key)) {\n\t\t\tsupportedCommandClasses.put(key, commandClass);\n\t\t\t\n\t\t\tif (commandClass instanceof ZWaveEventListener)\n\t\t\t\tthis.controller.addEventListener((ZWaveEventListener)commandClass);\n\t\t\t\n\t\t\tthis.lastUpdated = Calendar.getInstance().getTime();\n\t\t}\n\t}",
"@Override\n protected void stopInner() {\n /*\n * TODO REST-Server Need to handle inflight operations. What happens to\n * the existing async operations when a channel.close() is issued in\n * Netty?\n */\n if(this.nettyServerChannel != null) {\n this.nettyServerChannel.close();\n }\n\n if(allChannels != null) {\n allChannels.close().awaitUninterruptibly();\n }\n this.bootstrap.releaseExternalResources();\n }",
"public void writeNameValuePair(String name, Date value) throws IOException\n {\n internalWriteNameValuePair(name, m_format.format(value));\n }",
"static boolean isOnClasspath(String className) {\n boolean isOnClassPath = true;\n try {\n Class.forName(className);\n } catch (ClassNotFoundException exception) {\n isOnClassPath = false;\n }\n return isOnClassPath;\n }",
"private void prepareInitialState(boolean isNewObject)\r\n {\r\n // determine appropriate modification state\r\n ModificationState initialState;\r\n if(isNewObject)\r\n {\r\n // if object is not already persistent it must be marked as new\r\n // it must be marked as dirty because it must be stored even if it will not modified during tx\r\n initialState = StateNewDirty.getInstance();\r\n }\r\n else if(isDeleted(oid))\r\n {\r\n // if object is already persistent it will be marked as old.\r\n // it is marked as dirty as it has been deleted during tx and now it is inserted again,\r\n // possibly with new field values.\r\n initialState = StateOldDirty.getInstance();\r\n }\r\n else\r\n {\r\n // if object is already persistent it will be marked as old.\r\n // it is marked as clean as it has not been modified during tx already\r\n initialState = StateOldClean.getInstance();\r\n }\r\n // remember it:\r\n modificationState = initialState;\r\n }",
"private String decodeStr(String str) {\r\n try {\r\n return MimeUtility.decodeText(str);\r\n } catch (UnsupportedEncodingException e) {\r\n return str;\r\n }\r\n }"
] |
Use this API to fetch nslimitselector resource of given name . | [
"public static nslimitselector get(nitro_service service, String selectorname) throws Exception{\n\t\tnslimitselector obj = new nslimitselector();\n\t\tobj.set_selectorname(selectorname);\n\t\tnslimitselector response = (nslimitselector) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"@JsonInclude(Include.NON_EMPTY)\n\t@JsonProperty(\"id\")\n\tpublic String getJsonId() {\n\t\tif (!EntityIdValue.SITE_LOCAL.equals(this.siteIri)) {\n\t\t\treturn this.entityId;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}",
"private void populateBar(Row row, Task task)\n {\n Integer calendarID = row.getInteger(\"CALENDAU\");\n ProjectCalendar calendar = m_project.getCalendarByUniqueID(calendarID);\n\n //PROJID\n task.setUniqueID(row.getInteger(\"BARID\"));\n task.setStart(row.getDate(\"STARV\"));\n task.setFinish(row.getDate(\"ENF\"));\n //NATURAL_ORDER\n //SPARI_INTEGER\n task.setName(row.getString(\"NAMH\"));\n //EXPANDED_TASK\n //PRIORITY\n //UNSCHEDULABLE\n //MARK_FOR_HIDING\n //TASKS_MAY_OVERLAP\n //SUBPROJECT_ID\n //ALT_ID\n //LAST_EDITED_DATE\n //LAST_EDITED_BY\n //Proc_Approve\n //Proc_Design_info\n //Proc_Proc_Dur\n //Proc_Procurement\n //Proc_SC_design\n //Proc_Select_SC\n //Proc_Tender\n //QA Checked\n //Related_Documents\n task.setCalendar(calendar);\n }",
"public String getPendingChanges() {\n JsonObject jsonObject = this.getPendingJSONObject();\n if (jsonObject == null) {\n return null;\n }\n\n return jsonObject.toString();\n }",
"public static void pushImage(String imageTag, String username, String password, String host) throws IOException {\n final AuthConfig authConfig = new AuthConfig();\n authConfig.withUsername(username);\n authConfig.withPassword(password);\n\n DockerClient dockerClient = null;\n try {\n dockerClient = getDockerClient(host);\n dockerClient.pushImageCmd(imageTag).withAuthConfig(authConfig).exec(new PushImageResultCallback()).awaitSuccess();\n } finally {\n closeQuietly(dockerClient);\n }\n }",
"public static String getString(byte[] bytes, String encoding) {\n try {\n return new String(bytes, encoding);\n } catch(UnsupportedEncodingException e) {\n throw new IllegalArgumentException(encoding + \" is not a known encoding name.\", e);\n }\n }",
"public static List<String> getBuildNumbersNotToBeDeleted(Run build) {\n List<String> notToDelete = Lists.newArrayList();\n List<? extends Run<?, ?>> builds = build.getParent().getBuilds();\n for (Run<?, ?> run : builds) {\n if (run.isKeepLog()) {\n notToDelete.add(String.valueOf(run.getNumber()));\n }\n }\n return notToDelete;\n }",
"public List<CmsCategory> getTopItems() {\n\n List<CmsCategory> categories = new ArrayList<CmsCategory>();\n String matcher = Pattern.quote(m_mainCategoryPath) + \"[^/]*/\";\n for (CmsCategory category : m_categories) {\n if (category.getPath().matches(matcher)) {\n categories.add(category);\n }\n }\n return categories;\n }",
"private static File getUserDirectory(final String prefix, final String suffix, final File parent) {\n final String dirname = formatDirName(prefix, suffix);\n return new File(parent, dirname);\n }",
"void bootTimeScan(final DeploymentOperations deploymentOperations) {\n // WFCORE-1579: skip the scan if deployment dir is not available\n if (!checkDeploymentDir(this.deploymentDir)) {\n DeploymentScannerLogger.ROOT_LOGGER.bootTimeScanFailed(deploymentDir.getAbsolutePath());\n return;\n }\n\n this.establishDeployedContentList(this.deploymentDir, deploymentOperations);\n deployedContentEstablished = true;\n if (acquireScanLock()) {\n try {\n scan(true, deploymentOperations);\n } finally {\n releaseScanLock();\n }\n }\n }"
] |
Convert an Object to a Time, without an Exception | [
"public static java.sql.Time getTime(Object value) {\n try {\n return toTime(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }"
] | [
"public void recordPutTimeAndSize(long timeNS, long valueSize, long keySize) {\n recordTime(Tracked.PUT, timeNS, 0, valueSize, keySize, 0);\n }",
"private void throwOrWarnAboutDescriptorProblem(String message) {\n if (validateDescriptions) {\n throw new IllegalArgumentException(message);\n }\n ControllerLogger.ROOT_LOGGER.warn(message);\n }",
"public Object toInternal(Attribute<?> attribute) throws GeomajasException {\n\t\tif (attribute instanceof PrimitiveAttribute<?>) {\n\t\t\treturn toPrimitiveObject((PrimitiveAttribute<?>) attribute);\n\t\t} else if (attribute instanceof AssociationAttribute<?>) {\n\t\t\treturn toAssociationObject((AssociationAttribute<?>) attribute);\n\t\t} else {\n\t\t\tthrow new GeomajasException(ExceptionCode.CONVERSION_PROBLEM, attribute);\n\t\t}\n\t}",
"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 Shell createSubshell(String pathElement, Shell parent, String appName, Object mainHandler) {\n return createSubshell(pathElement, parent, appName, mainHandler, new EmptyMultiMap<String, Object>());\n }",
"public static BMatrixRMaj elementLessThan(DMatrixRMaj A , double value , BMatrixRMaj output )\n {\n if( output == null ) {\n output = new BMatrixRMaj(A.numRows,A.numCols);\n }\n\n output.reshape(A.numRows, A.numCols);\n\n int N = A.getNumElements();\n\n for (int i = 0; i < N; i++) {\n output.data[i] = A.data[i] < value;\n }\n\n return output;\n }",
"public 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}",
"public static ServiceActivator create(final ModelNode endpointConfig, final URI managementURI, final String serverName, final String serverProcessName,\n final String authKey, final boolean managementSubsystemEndpoint, final Supplier<SSLContext> sslContextSupplier) {\n\n return new DomainServerCommunicationServices(endpointConfig, managementURI, serverName, serverProcessName, authKey, managementSubsystemEndpoint, sslContextSupplier);\n }",
"public void set_protocol(String protocol) throws nitro_exception\n\t{\n\t\tif (protocol == null || !(protocol.equalsIgnoreCase(\"http\") ||protocol.equalsIgnoreCase(\"https\"))) {\n\t\t\tthrow new nitro_exception(\"error: protocol value \" + protocol + \" is not supported\");\n\t\t}\n\t\tthis.protocol = protocol;\n\t}"
] |
Encodes the given URI path segment with the given encoding.
@param segment the segment to be encoded
@param encoding the character encoding to encode to
@return the encoded segment
@throws UnsupportedEncodingException when the given encoding parameter is not supported | [
"public static String encodePathSegment(String segment, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(segment, encoding, HierarchicalUriComponents.Type.PATH_SEGMENT);\n\t}"
] | [
"public void process(DirectoryEntry projectDir, ProjectFile file, DocumentInputStreamFactory inputStreamFactory) throws IOException\n {\n DirectoryEntry consDir;\n try\n {\n consDir = (DirectoryEntry) projectDir.getEntry(\"TBkndCons\");\n }\n\n catch (FileNotFoundException ex)\n {\n consDir = null;\n }\n\n if (consDir != null)\n {\n FixedMeta consFixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) consDir.getEntry(\"FixedMeta\"))), 10);\n FixedData consFixedData = new FixedData(consFixedMeta, 20, inputStreamFactory.getInstance(consDir, \"FixedData\"));\n // FixedMeta consFixed2Meta = new FixedMeta(new DocumentInputStream(((DocumentEntry) consDir.getEntry(\"Fixed2Meta\"))), 9);\n // FixedData consFixed2Data = new FixedData(consFixed2Meta, 48, getEncryptableInputStream(consDir, \"Fixed2Data\"));\n\n int count = consFixedMeta.getAdjustedItemCount();\n int lastConstraintID = -1;\n\n ProjectProperties properties = file.getProjectProperties();\n EventManager eventManager = file.getEventManager();\n\n boolean project15 = NumberHelper.getInt(properties.getMppFileType()) == 14 && NumberHelper.getInt(properties.getApplicationVersion()) > ApplicationVersion.PROJECT_2010;\n int durationUnitsOffset = project15 ? 18 : 14;\n int durationOffset = project15 ? 14 : 16;\n\n for (int loop = 0; loop < count; loop++)\n {\n byte[] metaData = consFixedMeta.getByteArrayValue(loop);\n\n //\n // SourceForge bug 2209477: we were reading an int here, but\n // it looks like the deleted flag is just a short.\n //\n if (MPPUtility.getShort(metaData, 0) != 0)\n {\n continue;\n }\n\n int index = consFixedData.getIndexFromOffset(MPPUtility.getInt(metaData, 4));\n if (index == -1)\n {\n continue;\n }\n\n //\n // Do we have enough data?\n //\n byte[] data = consFixedData.getByteArrayValue(index);\n if (data.length < 14)\n {\n continue;\n }\n\n int constraintID = MPPUtility.getInt(data, 0);\n if (constraintID <= lastConstraintID)\n {\n continue;\n }\n\n lastConstraintID = constraintID;\n int taskID1 = MPPUtility.getInt(data, 4);\n int taskID2 = MPPUtility.getInt(data, 8);\n\n if (taskID1 == taskID2)\n {\n continue;\n }\n\n // byte[] metaData2 = consFixed2Meta.getByteArrayValue(loop);\n // int index2 = consFixed2Data.getIndexFromOffset(MPPUtility.getInt(metaData2, 4));\n // byte[] data2 = consFixed2Data.getByteArrayValue(index2);\n\n Task task1 = file.getTaskByUniqueID(Integer.valueOf(taskID1));\n Task task2 = file.getTaskByUniqueID(Integer.valueOf(taskID2));\n if (task1 != null && task2 != null)\n {\n RelationType type = RelationType.getInstance(MPPUtility.getShort(data, 12));\n TimeUnit durationUnits = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(data, durationUnitsOffset));\n Duration lag = MPPUtility.getAdjustedDuration(properties, MPPUtility.getInt(data, durationOffset), durationUnits);\n Relation relation = task2.addPredecessor(task1, type, lag);\n relation.setUniqueID(Integer.valueOf(constraintID));\n eventManager.fireRelationReadEvent(relation);\n }\n }\n }\n }",
"public void sendLoadTrackCommand(DeviceUpdate target, int rekordboxId,\n int sourcePlayer, CdjStatus.TrackSourceSlot sourceSlot, CdjStatus.TrackType sourceType)\n throws IOException {\n ensureRunning();\n byte[] payload = new byte[LOAD_TRACK_PAYLOAD.length];\n System.arraycopy(LOAD_TRACK_PAYLOAD, 0, payload, 0, LOAD_TRACK_PAYLOAD.length);\n payload[0x02] = getDeviceNumber();\n payload[0x05] = getDeviceNumber();\n payload[0x09] = (byte)sourcePlayer;\n payload[0x0a] = sourceSlot.protocolValue;\n payload[0x0b] = sourceType.protocolValue;\n Util.numberToBytes(rekordboxId, payload, 0x0d, 4);\n assembleAndSendPacket(Util.PacketType.LOAD_TRACK_COMMAND, payload, target.getAddress(), UPDATE_PORT);\n }",
"public static FilePath createAndGetTempDir(final FilePath ws) throws IOException, InterruptedException {\n // The token that combines the project name and unique number to create unique workspace directory.\n String workspaceList = System.getProperty(\"hudson.slaves.WorkspaceList\");\n return ws.act(new MasterToSlaveCallable<FilePath, IOException>() {\n @Override\n public FilePath call() {\n final FilePath tempDir = ws.sibling(ws.getName() + Objects.toString(workspaceList, \"@\") + \"tmp\").child(\"artifactory\");\n File tempDirFile = new File(tempDir.getRemote());\n tempDirFile.mkdirs();\n tempDirFile.deleteOnExit();\n return tempDir;\n }\n });\n }",
"public static String md5(byte[] source) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(source);\n byte tmp[] = md.digest();\n char str[] = new char[32];\n int k = 0;\n for (byte b : tmp) {\n str[k++] = hexDigits[b >>> 4 & 0xf];\n str[k++] = hexDigits[b & 0xf];\n }\n return new String(str);\n\n } catch (Exception e) {\n throw new IllegalArgumentException(e);\n }\n }",
"public static int getActionBarHeight(Context context) {\n int actionBarHeight = UIUtils.getThemeAttributeDimensionSize(context, R.attr.actionBarSize);\n if (actionBarHeight == 0) {\n actionBarHeight = context.getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height_material);\n }\n return actionBarHeight;\n }",
"public DockerContainerObjectBuilder<T> withEnrichers(Collection<TestEnricher> enrichers) {\n if (enrichers == null) {\n throw new IllegalArgumentException(\"enrichers cannot be null\");\n }\n this.enrichers = enrichers;\n return this;\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 void postModule(final Module module, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.moduleResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, module);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST module\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }",
"public File getTargetFile(final MiscContentItem item) {\n final State state = this.state;\n if (state == State.NEW || state == State.ROLLBACK_ONLY) {\n return getTargetFile(miscTargetRoot, item);\n } else {\n throw new IllegalStateException(); // internal wrong usage, no i18n\n }\n }"
] |
get the setter method corresponding to given property | [
"public static Method getSetterPropertyMethod(Class<?> type,\r\n\t\t\tString propertyName) {\r\n\t\tString sourceMethodName = \"set\"\r\n\t\t\t\t+ BeanUtils.capitalizePropertyName(propertyName);\r\n\r\n\t\tMethod sourceMethod = BeanUtils.getMethod(type, sourceMethodName);\r\n\r\n\t\treturn sourceMethod;\r\n\t}"
] | [
"public void add(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {\n BinderDescriptor binderDescriptor = new BinderDescriptor(declarationBinderRef);\n declarationBinders.put(declarationBinderRef, binderDescriptor);\n }",
"public <A extends Collection<? super ResultT>> A into(final A target) {\n forEach(new Block<ResultT>() {\n @Override\n public void apply(@Nonnull final ResultT t) {\n target.add(t);\n }\n });\n return target;\n }",
"public static appfwprofile_denyurl_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_denyurl_binding obj = new appfwprofile_denyurl_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_denyurl_binding response[] = (appfwprofile_denyurl_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static String format(Flags flags) {\r\n StringBuilder buf = new StringBuilder();\r\n buf.append('(');\r\n if (flags.contains(Flags.Flag.ANSWERED)) {\r\n buf.append(\"\\\\Answered \");\r\n }\r\n if (flags.contains(Flags.Flag.DELETED)) {\r\n buf.append(\"\\\\Deleted \");\r\n }\r\n if (flags.contains(Flags.Flag.DRAFT)) {\r\n buf.append(\"\\\\Draft \");\r\n }\r\n if (flags.contains(Flags.Flag.FLAGGED)) {\r\n buf.append(\"\\\\Flagged \");\r\n }\r\n if (flags.contains(Flags.Flag.RECENT)) {\r\n buf.append(\"\\\\Recent \");\r\n }\r\n if (flags.contains(Flags.Flag.SEEN)) {\r\n buf.append(\"\\\\Seen \");\r\n }\r\n String[] userFlags = flags.getUserFlags();\r\n if(null!=userFlags) {\r\n for(String uf: userFlags) {\r\n buf.append(uf).append(' ');\r\n }\r\n }\r\n // Remove the trailing space, if necessary.\r\n if (buf.length() > 1) {\r\n buf.setLength(buf.length() - 1);\r\n }\r\n buf.append(')');\r\n return buf.toString();\r\n }",
"private void deliverLostAnnouncement(final DeviceAnnouncement announcement) {\n for (final DeviceAnnouncementListener listener : getDeviceAnnouncementListeners()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n try {\n listener.deviceLost(announcement);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering device lost announcement to listener\", t);\n }\n }\n });\n }\n }",
"private void fireTreeStructureChanged()\n {\n // Guaranteed to return a non-null array\n Object[] listeners = m_listenerList.getListenerList();\n TreeModelEvent e = null;\n // Process the listeners last to first, notifying\n // those that are interested in this event\n for (int i = listeners.length - 2; i >= 0; i -= 2)\n {\n if (listeners[i] == TreeModelListener.class)\n {\n // Lazily create the event:\n if (e == null)\n {\n e = new TreeModelEvent(getRoot(), new Object[]\n {\n getRoot()\n }, null, null);\n }\n ((TreeModelListener) listeners[i + 1]).treeStructureChanged(e);\n }\n }\n }",
"public List<Cluster> cluster(final Collection<Point2D> points) {\n \tfinal List<Cluster> clusters = new ArrayList<Cluster>();\n final Map<Point2D, PointStatus> visited = new HashMap<Point2D, DBScan.PointStatus>();\n\n KDTree<Point2D> tree = new KDTree<Point2D>(2);\n \n // Populate the kdTree\n for (final Point2D point : points) {\n \tdouble[] key = {point.x, point.y};\n \ttree.insert(key, point);\n }\n \n for (final Point2D point : points) {\n if (visited.get(point) != null) {\n continue;\n }\n final List<Point2D> neighbors = getNeighbors(point, tree);\n if (neighbors.size() >= minPoints) {\n // DBSCAN does not care about center points\n final Cluster cluster = new Cluster(clusters.size());\n clusters.add(expandCluster(cluster, point, neighbors, tree, visited));\n } else {\n visited.put(point, PointStatus.NOISE);\n }\n }\n\n for (Cluster cluster : clusters) {\n \tcluster.calculateCentroid();\n }\n \n return clusters;\n }",
"public ManageableCollection createCollectionProxy(PBKey brokerKey, Query query, Class collectionClass)\r\n {\r\n Object args[] = {brokerKey, collectionClass, query};\r\n\r\n try\r\n {\r\n return (ManageableCollection) getCollectionProxyConstructor(collectionClass).newInstance(args);\r\n }\r\n catch(InstantiationException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new collection proxy instance\", ex);\r\n }\r\n catch(InvocationTargetException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new collection proxy instance\", ex);\r\n }\r\n catch(IllegalAccessException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new collection proxy instance\", ex);\r\n }\r\n }",
"public T transitInt(int propertyId, int... vals) {\n String property = getPropertyName(propertyId);\n mHolders.put(propertyId, PropertyValuesHolder.ofInt(property, vals));\n mShadowHolders.put(propertyId, ShadowValuesHolder.ofInt(property, vals));\n return self();\n }"
] |
Use this API to add vpnsessionaction. | [
"public static base_response add(nitro_service client, vpnsessionaction resource) throws Exception {\n\t\tvpnsessionaction addresource = new vpnsessionaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.httpport = resource.httpport;\n\t\taddresource.winsip = resource.winsip;\n\t\taddresource.dnsvservername = resource.dnsvservername;\n\t\taddresource.splitdns = resource.splitdns;\n\t\taddresource.sesstimeout = resource.sesstimeout;\n\t\taddresource.clientsecurity = resource.clientsecurity;\n\t\taddresource.clientsecuritygroup = resource.clientsecuritygroup;\n\t\taddresource.clientsecuritymessage = resource.clientsecuritymessage;\n\t\taddresource.clientsecuritylog = resource.clientsecuritylog;\n\t\taddresource.splittunnel = resource.splittunnel;\n\t\taddresource.locallanaccess = resource.locallanaccess;\n\t\taddresource.rfc1918 = resource.rfc1918;\n\t\taddresource.spoofiip = resource.spoofiip;\n\t\taddresource.killconnections = resource.killconnections;\n\t\taddresource.transparentinterception = resource.transparentinterception;\n\t\taddresource.windowsclienttype = resource.windowsclienttype;\n\t\taddresource.defaultauthorizationaction = resource.defaultauthorizationaction;\n\t\taddresource.authorizationgroup = resource.authorizationgroup;\n\t\taddresource.clientidletimeout = resource.clientidletimeout;\n\t\taddresource.proxy = resource.proxy;\n\t\taddresource.allprotocolproxy = resource.allprotocolproxy;\n\t\taddresource.httpproxy = resource.httpproxy;\n\t\taddresource.ftpproxy = resource.ftpproxy;\n\t\taddresource.socksproxy = resource.socksproxy;\n\t\taddresource.gopherproxy = resource.gopherproxy;\n\t\taddresource.sslproxy = resource.sslproxy;\n\t\taddresource.proxyexception = resource.proxyexception;\n\t\taddresource.proxylocalbypass = resource.proxylocalbypass;\n\t\taddresource.clientcleanupprompt = resource.clientcleanupprompt;\n\t\taddresource.forcecleanup = resource.forcecleanup;\n\t\taddresource.clientoptions = resource.clientoptions;\n\t\taddresource.clientconfiguration = resource.clientconfiguration;\n\t\taddresource.sso = resource.sso;\n\t\taddresource.ssocredential = resource.ssocredential;\n\t\taddresource.windowsautologon = resource.windowsautologon;\n\t\taddresource.usemip = resource.usemip;\n\t\taddresource.useiip = resource.useiip;\n\t\taddresource.clientdebug = resource.clientdebug;\n\t\taddresource.loginscript = resource.loginscript;\n\t\taddresource.logoutscript = resource.logoutscript;\n\t\taddresource.homepage = resource.homepage;\n\t\taddresource.icaproxy = resource.icaproxy;\n\t\taddresource.wihome = resource.wihome;\n\t\taddresource.citrixreceiverhome = resource.citrixreceiverhome;\n\t\taddresource.wiportalmode = resource.wiportalmode;\n\t\taddresource.clientchoices = resource.clientchoices;\n\t\taddresource.epaclienttype = resource.epaclienttype;\n\t\taddresource.iipdnssuffix = resource.iipdnssuffix;\n\t\taddresource.forcedtimeout = resource.forcedtimeout;\n\t\taddresource.forcedtimeoutwarning = resource.forcedtimeoutwarning;\n\t\taddresource.ntdomain = resource.ntdomain;\n\t\taddresource.clientlessvpnmode = resource.clientlessvpnmode;\n\t\taddresource.emailhome = resource.emailhome;\n\t\taddresource.clientlessmodeurlencoding = resource.clientlessmodeurlencoding;\n\t\taddresource.clientlesspersistentcookie = resource.clientlesspersistentcookie;\n\t\taddresource.allowedlogingroups = resource.allowedlogingroups;\n\t\taddresource.securebrowse = resource.securebrowse;\n\t\taddresource.storefronturl = resource.storefronturl;\n\t\taddresource.kcdaccount = resource.kcdaccount;\n\t\treturn addresource.add_resource(client);\n\t}"
] | [
"public List<TerminalString> getOptionLongNamesWithDash() {\n List<ProcessedOption> opts = getOptions();\n List<TerminalString> names = new ArrayList<>(opts.size());\n for (ProcessedOption o : opts) {\n if(o.getValues().size() == 0 &&\n o.activator().isActivated(new ParsedCommand(this)))\n names.add(o.getRenderedNameWithDashes());\n }\n\n return names;\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 AT_CellContext setPadding(int padding){\r\n\t\tif(padding>-1){\r\n\t\t\tthis.paddingTop = padding;\r\n\t\t\tthis.paddingBottom = padding;\r\n\t\t\tthis.paddingLeft = padding;\r\n\t\t\tthis.paddingRight = padding;\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public TimephasedWorkContainer getBaselineWork(ResourceAssignment assignment, ProjectCalendar calendar, TimephasedWorkNormaliser normaliser, byte[] data, boolean raw)\n {\n TimephasedWorkContainer result = null;\n\n if (data != null && data.length > 0)\n {\n LinkedList<TimephasedWork> list = null;\n\n //System.out.println(ByteArrayHelper.hexdump(data, false));\n int index = 8; // 8 byte header\n int blockSize = 40;\n double previousCumulativeWorkPerformedInMinutes = 0;\n\n Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 36);\n index += blockSize;\n TimephasedWork work = null;\n\n while (index + blockSize <= data.length)\n {\n double cumulativeWorkInMinutes = (double) ((long) MPPUtility.getDouble(data, index + 20)) / 1000;\n if (!Duration.durationValueEquals(cumulativeWorkInMinutes, previousCumulativeWorkPerformedInMinutes))\n {\n //double unknownWorkThisPeriodInMinutes = ((long) MPPUtility.getDouble(data, index + 0)) / 1000;\n double normalActualWorkThisPeriodInMinutes = ((double) MPPUtility.getInt(data, index + 8)) / 10;\n double normalRemainingWorkThisPeriodInMinutes = ((double) MPPUtility.getInt(data, index + 28)) / 10;\n double workThisPeriodInMinutes = cumulativeWorkInMinutes - previousCumulativeWorkPerformedInMinutes;\n double overtimeWorkThisPeriodInMinutes = workThisPeriodInMinutes - (normalActualWorkThisPeriodInMinutes + normalRemainingWorkThisPeriodInMinutes);\n double overtimeFactor = overtimeWorkThisPeriodInMinutes / (normalActualWorkThisPeriodInMinutes + normalRemainingWorkThisPeriodInMinutes);\n\n double normalWorkPerDayInMinutes = 480;\n double overtimeWorkPerDayInMinutes = normalWorkPerDayInMinutes * overtimeFactor;\n\n work = new TimephasedWork();\n work.setFinish(MPPUtility.getTimestampFromTenths(data, index + 16));\n work.setStart(blockStartDate);\n work.setTotalAmount(Duration.getInstance(workThisPeriodInMinutes, TimeUnit.MINUTES));\n work.setAmountPerDay(Duration.getInstance(normalWorkPerDayInMinutes + overtimeWorkPerDayInMinutes, TimeUnit.MINUTES));\n\n previousCumulativeWorkPerformedInMinutes = cumulativeWorkInMinutes;\n\n if (list == null)\n {\n list = new LinkedList<TimephasedWork>();\n }\n list.add(work);\n //System.out.println(work);\n }\n blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 36);\n index += blockSize;\n }\n\n if (list != null)\n {\n if (work != null)\n {\n work.setFinish(assignment.getFinish());\n }\n result = new DefaultTimephasedWorkContainer(calendar, normaliser, list, raw);\n }\n }\n\n return result;\n }",
"String checkVersion(String pluginName, String dependency, String requestedVersion, String availableVersion) {\n\t\tif (null == availableVersion) {\n\t\t\treturn \"Dependency \" + dependency + \" not found for \" + pluginName + \", version \" + requestedVersion +\n\t\t\t\t\t\" or higher needed.\\n\";\n\t\t}\n\t\tif (requestedVersion.startsWith(EXPR_START) || availableVersion.startsWith(EXPR_START)) {\n\t\t\treturn \"\";\n\t\t}\n\t\tVersion requested = new Version(requestedVersion);\n\t\tVersion available = new Version(availableVersion);\n\t\tif (requested.getMajor() != available.getMajor()) {\n\t\t\treturn \"Dependency \" + dependency + \" is provided in a incompatible API version for plug-in \" +\n\t\t\t\t\tpluginName + \", which requests version \" + requestedVersion +\n\t\t\t\t\t\", but version \" + availableVersion + \" supplied.\\n\";\n\t\t}\n\t\tif (requested.after(available)) {\n\t\t\treturn \"Dependency \" + dependency + \" too old for \" + pluginName + \", version \" + requestedVersion +\n\t\t\t\t\t\" or higher needed, but version \" + availableVersion + \" supplied.\\n\";\n\t\t}\n\t\treturn \"\";\n\t}",
"public static Map<FieldType, String> getDefaultAliases()\n {\n Map<FieldType, String> map = new HashMap<FieldType, String>();\n\n map.put(TaskField.DATE1, \"Suspend Date\");\n map.put(TaskField.DATE2, \"Resume Date\");\n map.put(TaskField.TEXT1, \"Code\");\n map.put(TaskField.TEXT2, \"Activity Type\");\n map.put(TaskField.TEXT3, \"Status\");\n map.put(TaskField.NUMBER1, \"Primary Resource Unique ID\");\n\n return map;\n }",
"public static AssociationKeyMetadata getInverseAssociationKeyMetadata(OgmEntityPersister mainSidePersister, int propertyIndex) {\n\t\tType propertyType = mainSidePersister.getPropertyTypes()[propertyIndex];\n\t\tSessionFactoryImplementor factory = mainSidePersister.getFactory();\n\n\t\t// property represents no association, so no inverse meta-data can exist\n\t\tif ( !propertyType.isAssociationType() ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tJoinable mainSideJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( factory );\n\t\tOgmEntityPersister inverseSidePersister = null;\n\n\t\t// to-many association\n\t\tif ( mainSideJoinable.isCollection() ) {\n\t\t\tinverseSidePersister = (OgmEntityPersister) ( (OgmCollectionPersister) mainSideJoinable ).getElementPersister();\n\t\t}\n\t\t// to-one\n\t\telse {\n\t\t\tinverseSidePersister = (OgmEntityPersister) mainSideJoinable;\n\t\t\tmainSideJoinable = mainSidePersister;\n\t\t}\n\n\t\tString mainSideProperty = mainSidePersister.getPropertyNames()[propertyIndex];\n\n\t\t// property is a one-to-one association (a many-to-one cannot be on the inverse side) -> get the meta-data\n\t\t// straight from the main-side persister\n\t\tAssociationKeyMetadata inverseOneToOneMetadata = mainSidePersister.getInverseOneToOneAssociationKeyMetadata( mainSideProperty );\n\t\tif ( inverseOneToOneMetadata != null ) {\n\t\t\treturn inverseOneToOneMetadata;\n\t\t}\n\n\t\t// process properties of inverse side and try to find association back to main side\n\t\tfor ( String candidateProperty : inverseSidePersister.getPropertyNames() ) {\n\t\t\tType type = inverseSidePersister.getPropertyType( candidateProperty );\n\n\t\t\t// candidate is a *-to-many association\n\t\t\tif ( type.isCollectionType() ) {\n\t\t\t\tOgmCollectionPersister inverseCollectionPersister = getPersister( factory, (CollectionType) type );\n\t\t\t\tString mappedByProperty = inverseCollectionPersister.getMappedByProperty();\n\t\t\t\tif ( mainSideProperty.equals( mappedByProperty ) ) {\n\t\t\t\t\tif ( isCollectionMatching( mainSideJoinable, inverseCollectionPersister ) ) {\n\t\t\t\t\t\treturn inverseCollectionPersister.getAssociationKeyMetadata();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"public void displayUseCases()\r\n {\r\n System.out.println();\r\n for (int i = 0; i < useCases.size(); i++)\r\n {\r\n System.out.println(\"[\" + i + \"] \" + ((UseCase) useCases.get(i)).getDescription());\r\n }\r\n }",
"public byte[] getThumbnail(ThumbnailFileType fileType, int minWidth, int minHeight, int maxWidth, int maxHeight) {\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(\"min_width\", minWidth);\n builder.appendParam(\"min_height\", minHeight);\n builder.appendParam(\"max_width\", maxWidth);\n builder.appendParam(\"max_height\", maxHeight);\n\n URLTemplate template;\n if (fileType == ThumbnailFileType.PNG) {\n template = GET_THUMBNAIL_PNG_TEMPLATE;\n } else if (fileType == ThumbnailFileType.JPG) {\n template = GET_THUMBNAIL_JPG_TEMPLATE;\n } else {\n throw new BoxAPIException(\"Unsupported thumbnail file type\");\n }\n URL url = template.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxAPIResponse response = request.send();\n\n ByteArrayOutputStream thumbOut = new ByteArrayOutputStream();\n InputStream body = response.getBody();\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = body.read(buffer);\n while (n != -1) {\n thumbOut.write(buffer, 0, n);\n n = body.read(buffer);\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Error reading thumbnail bytes from response body\", e);\n } finally {\n response.disconnect();\n }\n\n return thumbOut.toByteArray();\n }"
] |
This solution is based on an absolute path | [
"private String getSlashyPath(final String path) {\n String changedPath = path;\n if (File.separatorChar != '/')\n changedPath = changedPath.replace(File.separatorChar, '/');\n\n return changedPath;\n }"
] | [
"@Override\n\tpublic Set<String> getRoundingNames(String... providers) {\n Set<String> result = new HashSet<>();\n String[] providerNames = providers;\n if (providerNames.length == 0) {\n providerNames = Monetary.getDefaultRoundingProviderChain().toArray(new String[Monetary.getDefaultRoundingProviderChain().size()]);\n }\n for (String providerName : providerNames) {\n for (RoundingProviderSpi prov : Bootstrap.getServices(RoundingProviderSpi.class)) {\n try {\n if (prov.getProviderName().equals(providerName) || prov.getProviderName().matches(providerName)) {\n result.addAll(prov.getRoundingNames());\n }\n } catch (Exception e) {\n Logger.getLogger(DefaultMonetaryRoundingsSingletonSpi.class.getName())\n .log(Level.SEVERE, \"Error loading RoundingProviderSpi from provider: \" + prov, e);\n }\n }\n }\n return result;\n }",
"public Iterable<V> sorted(Iterator<V> input) {\n ExecutorService executor = new ThreadPoolExecutor(this.numThreads,\n this.numThreads,\n 1000L,\n TimeUnit.MILLISECONDS,\n new SynchronousQueue<Runnable>(),\n new CallerRunsPolicy());\n final AtomicInteger count = new AtomicInteger(0);\n final List<File> tempFiles = Collections.synchronizedList(new ArrayList<File>());\n while(input.hasNext()) {\n final int segmentId = count.getAndIncrement();\n final long segmentStartMs = System.currentTimeMillis();\n logger.info(\"Segment \" + segmentId + \": filling sort buffer for segment...\");\n @SuppressWarnings(\"unchecked\")\n final V[] buffer = (V[]) new Object[internalSortSize];\n int segmentSizeIter = 0;\n for(; segmentSizeIter < internalSortSize && input.hasNext(); segmentSizeIter++)\n buffer[segmentSizeIter] = input.next();\n final int segmentSize = segmentSizeIter;\n logger.info(\"Segment \" + segmentId + \": sort buffer filled...adding to sort queue.\");\n\n // sort and write out asynchronously\n executor.execute(new Runnable() {\n\n public void run() {\n logger.info(\"Segment \" + segmentId + \": sorting buffer.\");\n long start = System.currentTimeMillis();\n Arrays.sort(buffer, 0, segmentSize, comparator);\n long elapsed = System.currentTimeMillis() - start;\n logger.info(\"Segment \" + segmentId + \": sort completed in \" + elapsed\n + \" ms, writing to temp file.\");\n\n // write out values to a temp file\n try {\n File tempFile = File.createTempFile(\"segment-\", \".dat\", tempDir);\n tempFile.deleteOnExit();\n tempFiles.add(tempFile);\n OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile),\n bufferSize);\n if(gzip)\n os = new GZIPOutputStream(os);\n DataOutputStream output = new DataOutputStream(os);\n for(int i = 0; i < segmentSize; i++)\n writeValue(output, buffer[i]);\n output.close();\n } catch(IOException e) {\n throw new VoldemortException(e);\n }\n long segmentElapsed = System.currentTimeMillis() - segmentStartMs;\n logger.info(\"Segment \" + segmentId + \": completed processing of segment in \"\n + segmentElapsed + \" ms.\");\n }\n });\n }\n\n // wait for all sorting to complete\n executor.shutdown();\n try {\n executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);\n // create iterator over sorted values\n return new DefaultIterable<V>(new ExternalSorterIterator(tempFiles, bufferSize\n / tempFiles.size()));\n } catch(InterruptedException e) {\n throw new RuntimeException(e);\n }\n }",
"protected static Map<String, String> getHeadersAsMap(ResponseEntity response) {\n\n Map<String, List<String>> headers = new HashMap<>(response.getHeaders());\n Map<String, String> map = new HashMap<>();\n\n for ( Map.Entry<String, List<String>> header :headers.entrySet() ) {\n String headerValue = Joiner.on(\",\").join(header.getValue());\n map.put(header.getKey(), headerValue);\n }\n\n return map;\n }",
"@Deprecated public Duration getDuration(Date startDate, Date endDate) throws MPXJException\n {\n return (getDuration(\"Standard\", startDate, endDate));\n }",
"public static void showChannels(Object... channels){\r\n // TODO this could share more code with the other show/hide(Only)Channels methods\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n for (Object channel : channels) {\r\n visHandler.alsoShow(channel);\r\n }\r\n }\r\n }\r\n }",
"public static cmppolicylabel_stats get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel_stats obj = new cmppolicylabel_stats();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel_stats response = (cmppolicylabel_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public void copyStructure( DMatrixSparseCSC orig ) {\n reshape(orig.numRows, orig.numCols, orig.nz_length);\n this.nz_length = orig.nz_length;\n System.arraycopy(orig.col_idx,0,col_idx,0,orig.numCols+1);\n System.arraycopy(orig.nz_rows,0,nz_rows,0,orig.nz_length);\n }",
"private void updateScheduleSource(ProjectProperties properties)\n {\n // Rudimentary identification of schedule source\n if (properties.getCompany() != null && properties.getCompany().equals(\"Synchro Software Ltd\"))\n {\n properties.setFileApplication(\"Synchro\");\n }\n else\n {\n if (properties.getAuthor() != null && properties.getAuthor().equals(\"SG Project\"))\n {\n properties.setFileApplication(\"Simple Genius\");\n }\n else\n {\n properties.setFileApplication(\"Microsoft\");\n }\n }\n properties.setFileType(\"MSPDI\");\n }",
"public void setSeed(String randomSeed) {\n if (!Strings.isNullOrEmpty(getProject().getUserProperty(SYSPROP_RANDOM_SEED()))) {\n String userProperty = getProject().getUserProperty(SYSPROP_RANDOM_SEED());\n if (!userProperty.equals(randomSeed)) {\n log(\"Ignoring seed attribute because it is overridden by user properties.\", Project.MSG_WARN);\n }\n } else if (!Strings.isNullOrEmpty(randomSeed)) {\n this.random = randomSeed;\n }\n }"
] |
Use this API to add tmtrafficaction resources. | [
"public static base_responses add(nitro_service client, tmtrafficaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\ttmtrafficaction addresources[] = new tmtrafficaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new tmtrafficaction();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].apptimeout = resources[i].apptimeout;\n\t\t\t\taddresources[i].sso = resources[i].sso;\n\t\t\t\taddresources[i].formssoaction = resources[i].formssoaction;\n\t\t\t\taddresources[i].persistentcookie = resources[i].persistentcookie;\n\t\t\t\taddresources[i].initiatelogout = resources[i].initiatelogout;\n\t\t\t\taddresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\taddresources[i].samlssoprofile = resources[i].samlssoprofile;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"protected final boolean isGLThread() {\n final Thread glThread = sGLThread.get();\n return glThread != null && glThread.equals(Thread.currentThread());\n }",
"public Object getRealSubject() throws PersistenceBrokerException\r\n\t{\r\n\t\tif (_realSubject == null)\r\n\t\t{\r\n\t\t\tbeforeMaterialization();\r\n\t\t\t_realSubject = materializeSubject();\r\n\t\t\tafterMaterialization();\r\n\t\t}\r\n\t\treturn _realSubject;\r\n\t}",
"private void countPropertyMain(UsageStatistics usageStatistics,\n\t\t\tPropertyIdValue property, int count) {\n\t\taddPropertyCounters(usageStatistics, property);\n\t\tusageStatistics.propertyCountsMain.put(property,\n\t\t\t\tusageStatistics.propertyCountsMain.get(property) + count);\n\t}",
"protected DatabaseConnection getSavedConnection() {\n\t\tNestedConnection nested = specialConnection.get();\n\t\tif (nested == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn nested.connection;\n\t\t}\n\t}",
"private void 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 boolean compareBytes(byte[] lhs, byte[] rhs, int rhsOffset)\n {\n boolean result = true;\n for (int loop = 0; loop < lhs.length; loop++)\n {\n if (lhs[loop] != rhs[rhsOffset + loop])\n {\n result = false;\n break;\n }\n }\n return (result);\n }",
"static void populateFileCreationRecord(Record record, ProjectProperties properties)\n {\n properties.setMpxProgramName(record.getString(0));\n properties.setMpxFileVersion(FileVersion.getInstance(record.getString(1)));\n properties.setMpxCodePage(record.getCodePage(2));\n }",
"public static base_response update(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager updateresource = new snmpmanager();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.netmask = resource.netmask;\n\t\tupdateresource.domainresolveretry = resource.domainresolveretry;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static cachecontentgroup get(nitro_service service, String name) throws Exception{\n\t\tcachecontentgroup obj = new cachecontentgroup();\n\t\tobj.set_name(name);\n\t\tcachecontentgroup response = (cachecontentgroup) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
RReturns the entity type of the id like "item" or "property"
@param id
the identifier of the entity, such as "Q42"
@throws IllegalArgumentException
if the id is invalid | [
"static String guessEntityTypeFromId(String id) {\n\t\tif(id.isEmpty()) {\n\t\t\tthrow new IllegalArgumentException(\"Entity ids should not be empty.\");\n\t\t}\n\t\tswitch (id.charAt(0)) {\n\t\t\tcase 'L':\n\t\t\t\tif(id.contains(\"-F\")) {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_FORM;\n\t\t\t\t} else if(id.contains(\"-S\")) {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_SENSE;\n\t\t\t\t} else {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_LEXEME;\n\t\t\t\t}\n\t\t\tcase 'P':\n\t\t\t\treturn JSON_ENTITY_TYPE_PROPERTY;\n\t\t\tcase 'Q':\n\t\t\t\treturn JSON_ENTITY_TYPE_ITEM;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Entity id \\\"\" + id + \"\\\" is not supported.\");\n\t\t}\n\t}"
] | [
"private void ensureIndexIsUnlocked(String dataDir) {\n\n Collection<File> lockFiles = new ArrayList<File>(2);\n lockFiles.add(\n new File(\n CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + \"index\") + \"write.lock\"));\n lockFiles.add(\n new File(\n CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + \"spellcheck\")\n + \"write.lock\"));\n for (File lockFile : lockFiles) {\n if (lockFile.exists()) {\n lockFile.delete();\n LOG.warn(\n \"Forcely unlocking index with data dir \\\"\"\n + dataDir\n + \"\\\" by removing file \\\"\"\n + lockFile.getAbsolutePath()\n + \"\\\".\");\n }\n }\n }",
"@Override\n public Response toResponse(ErrorDto e)\n {\n // String type = headers.getContentType() == null ? MediaType.APPLICATION_JSON : headers.getContentType();\n return Response.status(e.httpStatus).entity(e).type(MediaType.APPLICATION_JSON).build();\n }",
"public static String getEncoding(CmsObject cms, CmsResource file) {\n\n CmsProperty encodingProperty = CmsProperty.getNullProperty();\n try {\n encodingProperty = cms.readPropertyObject(file, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true);\n } catch (CmsException e) {\n LOG.debug(e.getLocalizedMessage(), e);\n }\n return CmsEncoder.lookupEncoding(encodingProperty.getValue(\"\"), OpenCms.getSystemInfo().getDefaultEncoding());\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public static synchronized SlotReference getSlotReference(int player, CdjStatus.TrackSourceSlot slot) {\n Map<CdjStatus.TrackSourceSlot, SlotReference> playerMap = instances.get(player);\n if (playerMap == null) {\n playerMap = new HashMap<CdjStatus.TrackSourceSlot, SlotReference>();\n instances.put(player, playerMap);\n }\n SlotReference result = playerMap.get(slot);\n if (result == null) {\n result = new SlotReference(player, slot);\n playerMap.put(slot, result);\n }\n return result;\n }",
"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 static tmtrafficpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\ttmtrafficpolicy_lbvserver_binding obj = new tmtrafficpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\ttmtrafficpolicy_lbvserver_binding response[] = (tmtrafficpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"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}",
"public static final BigDecimal printDurationInDecimalThousandthsOfMinutes(Duration duration)\n {\n BigDecimal result = null;\n if (duration != null && duration.getDuration() != 0)\n {\n result = BigDecimal.valueOf(printDurationFractionsOfMinutes(duration, 1000));\n }\n return result;\n }",
"public String getInvalidMessage(String key) {\n return invalidMessageOverride == null ? messageMixin.lookup(key, messageValueArgs) : MessageFormat.format(\n invalidMessageOverride, messageValueArgs);\n }"
] |
Sets the request type for this ID. Defaults to GET
@param pathId ID of path
@param requestType type of request to service | [
"public void setRequestType(int pathId, Integer requestType) {\n if (requestType == null) {\n requestType = Constants.REQUEST_TYPE_GET;\n }\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_REQUEST_TYPE + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, requestType);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }"
] | [
"public static BufferedImage cloneImage( BufferedImage image ) {\n\t\tBufferedImage newImage = new BufferedImage( image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB );\n\t\tGraphics2D g = newImage.createGraphics();\n\t\tg.drawRenderedImage( image, null );\n\t\tg.dispose();\n\t\treturn newImage;\n\t}",
"@Inject(optional = true)\n protected Pattern setEndTag(@Named(AbstractMultiLineCommentProvider.END_TAG) final String endTag) {\n return this.endTagPattern = Pattern.compile((endTag + \"\\\\z\"));\n }",
"public static int findFirstNonAnnotationLine(ASTNode node, SourceCode sourceCode) {\r\n if (node instanceof AnnotatedNode && !((AnnotatedNode) node).getAnnotations().isEmpty()) {\r\n\r\n // HACK: Groovy line numbers are broken when annotations have a parameter :(\r\n // so we must look at the lineNumber, not the lastLineNumber\r\n AnnotationNode lastAnnotation = null;\r\n for (AnnotationNode annotation : ((AnnotatedNode) node).getAnnotations()) {\r\n if (lastAnnotation == null) lastAnnotation = annotation;\r\n else if (lastAnnotation.getLineNumber() < annotation.getLineNumber()) lastAnnotation = annotation;\r\n }\r\n\r\n String rawLine = getRawLine(sourceCode, lastAnnotation.getLastLineNumber()-1);\r\n\r\n if(rawLine == null) {\r\n return node.getLineNumber();\r\n }\r\n\r\n // is the annotation the last thing on the line?\r\n if (rawLine.length() > lastAnnotation.getLastColumnNumber()) {\r\n // no it is not\r\n return lastAnnotation.getLastLineNumber();\r\n }\r\n // yes it is the last thing, return the next thing\r\n return lastAnnotation.getLastLineNumber() + 1;\r\n }\r\n return node.getLineNumber();\r\n }",
"private void writeTaskPredecessors(Task record)\n {\n m_buffer.setLength(0);\n //\n // Write the task predecessor\n //\n if (!record.getSummary() && !record.getPredecessors().isEmpty())\n { // I don't use summary tasks for SDEF\n m_buffer.append(\"PRED \");\n List<Relation> predecessors = record.getPredecessors();\n\n for (Relation pred : predecessors)\n {\n m_buffer.append(SDEFmethods.rset(pred.getSourceTask().getUniqueID().toString(), 10) + \" \");\n m_buffer.append(SDEFmethods.rset(pred.getTargetTask().getUniqueID().toString(), 10) + \" \");\n String type = \"C\"; // default finish-to-start\n if (!pred.getType().toString().equals(\"FS\"))\n {\n type = pred.getType().toString().substring(0, 1);\n }\n m_buffer.append(type + \" \");\n\n Duration dd = pred.getLag();\n double duration = dd.getDuration();\n if (dd.getUnits() != TimeUnit.DAYS)\n {\n dd = Duration.convertUnits(duration, dd.getUnits(), TimeUnit.DAYS, m_minutesPerDay, m_minutesPerWeek, m_daysPerMonth);\n }\n Double days = Double.valueOf(dd.getDuration() + 0.5); // Add 0.5 so half day rounds up upon truncation\n Integer est = Integer.valueOf(days.intValue());\n m_buffer.append(SDEFmethods.rset(est.toString(), 4) + \" \"); // task duration in days required by USACE\n }\n m_writer.println(m_buffer.toString());\n }\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 }",
"public static base_response Force(nitro_service client, hafailover resource) throws Exception {\n\t\thafailover Forceresource = new hafailover();\n\t\tForceresource.force = resource.force;\n\t\treturn Forceresource.perform_operation(client,\"Force\");\n\t}",
"private org.apache.log4j.Logger getLogger()\r\n\t{\r\n /*\r\n Logger interface extends Serializable, thus Log field is\r\n declared 'transient' and we have to null-check\r\n\t\t*/\r\n\t\tif (logger == null)\r\n\t\t{\r\n\t\t\tlogger = org.apache.log4j.Logger.getLogger(name);\r\n\t\t}\r\n\t\treturn logger;\r\n\t}",
"public static gslbldnsentries[] get(nitro_service service) throws Exception{\n\t\tgslbldnsentries obj = new gslbldnsentries();\n\t\tgslbldnsentries[] response = (gslbldnsentries[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public NamedStyleInfo getNamedStyleInfo(String name) {\n\t\tfor (NamedStyleInfo info : namedStyleInfos) {\n\t\t\tif (info.getName().equals(name)) {\n\t\t\t\treturn info;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}"
] |
Remove a PropertyChangeListener for a specific property from this node.
This functionality has. Please note that the listener this does not remove
a listener that has been added without specifying the property it is
interested in. | [
"public void removePropertyChangeListener (String propertyName, java.beans.PropertyChangeListener listener)\r\n {\r\n this.propertyChangeDelegate.removePropertyChangeListener(propertyName, listener);\r\n }"
] | [
"public PartialCollection<BoxItem.Info> getChildrenRange(long offset, long limit, String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder()\n .appendParam(\"limit\", limit)\n .appendParam(\"offset\", offset);\n\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n\n URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), builder.toString(), getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n String totalCountString = responseJSON.get(\"total_count\").toString();\n long fullSize = Double.valueOf(totalCountString).longValue();\n PartialCollection<BoxItem.Info> children = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);\n JsonArray jsonArray = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : jsonArray) {\n JsonObject jsonObject = value.asObject();\n BoxItem.Info parsedItemInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), jsonObject);\n if (parsedItemInfo != null) {\n children.add(parsedItemInfo);\n }\n }\n return children;\n }",
"public void fillRect(int x, int y, int w, int h, Color c) {\n int color = c.getRGB();\n for (int i = x; i < x + w; i++) {\n for (int j = y; j < y + h; j++) {\n setIntColor(i, j, color);\n }\n }\n }",
"public Map<String, Object> getValues(double evaluationTime, MonteCarloSimulationInterface model) throws CalculationException\n\t{\n\t\tRandomVariableInterface values = getValue(evaluationTime, model);\n\n\t\tif(values == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Sum up values on path\n\t\tdouble value = values.getAverage();\n\t\tdouble error = values.getStandardError();\n\n\t\tMap<String, Object> results = new HashMap<String, Object>();\n\t\tresults.put(\"value\", value);\n\t\tresults.put(\"error\", error);\n\n\t\treturn results;\n\t}",
"public static vpnvserver_vpnsessionpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_vpnsessionpolicy_binding obj = new vpnvserver_vpnsessionpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_vpnsessionpolicy_binding response[] = (vpnvserver_vpnsessionpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static int minutesDiff(Date earlierDate, Date laterDate) {\n if (earlierDate == null || laterDate == null) {\n return 0;\n }\n\n return (int) ((laterDate.getTime() / MINUTE_MILLIS) - (earlierDate.getTime() / MINUTE_MILLIS));\n }",
"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 BoxCollaborationWhitelistExemptTarget.Info getInfo() {\n URL url = COLLABORATION_WHITELIST_EXEMPT_TARGET_ENTRY_URL_TEMPLATE.build(this.getAPI().getBaseURL(),\n this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n return new Info(JsonObject.readFrom(response.getJSON()));\n }",
"@Pure\n\tpublic static <K, V> Map<K, V> operator_minus(Map<K, V> left, final Map<? extends K, ? extends V> right) {\n\t\treturn Maps.filterEntries(left, new Predicate<Entry<K, V>>() {\n\t\t\t@Override\n\t\t\tpublic boolean apply(Entry<K, V> input) {\n\t\t\t\tfinal V value = right.get(input.getKey());\n\t\t\t\tif (value == null) {\n\t\t\t\t\treturn input.getValue() == null && right.containsKey(input.getKey());\n\t\t\t\t}\n\t\t\t\treturn !Objects.equal(input.getValue(), value);\n\t\t\t}\n\t\t});\n\t}",
"public List<DesignDocument> list() throws IOException {\r\n return db.getAllDocsRequestBuilder()\r\n .startKey(\"_design/\")\r\n .endKey(\"_design0\")\r\n .inclusiveEnd(false)\r\n .includeDocs(true)\r\n .build()\r\n .getResponse().getDocsAs(DesignDocument.class);\r\n }"
] |
Enables or disables sound.
When sound is disabled, nothing is played but the
audio sources remain intact.
@param flag true to enable sound, false to disable. | [
"public void setEnable(boolean flag)\n {\n if (mEnabled == flag)\n {\n return;\n }\n mEnabled = flag;\n if (flag)\n {\n mContext.registerDrawFrameListener(this);\n mContext.getApplication().getEventReceiver().addListener(this);\n mAudioEngine.resume();\n }\n else\n {\n mContext.unregisterDrawFrameListener(this);\n mContext.getApplication().getEventReceiver().removeListener(this);\n mAudioEngine.pause();\n }\n }"
] | [
"protected String getKey(final String ref, final String filename, final String extension) {\n return prefix + ref + \"/\" + filename + \".\" + extension;\n }",
"public void synchronizeTaskIDToHierarchy()\n {\n clear();\n\n int currentID = (getByID(Integer.valueOf(0)) == null ? 1 : 0);\n for (Task task : m_projectFile.getChildTasks())\n {\n task.setID(Integer.valueOf(currentID++));\n add(task);\n currentID = synchroizeTaskIDToHierarchy(task, currentID);\n }\n }",
"private void remove() {\n if (removing) {\n return;\n }\n if (deactiveNotifications.size() == 0) {\n return;\n }\n removing = true;\n final NotificationPopupView view = deactiveNotifications.get(0);\n final LinearFadeOutAnimation fadeOutAnimation = new LinearFadeOutAnimation(view) {\n\n @Override\n public void onUpdate(double progress) {\n super.onUpdate(progress);\n for (int i = 0; i < activeNotifications.size(); i++) {\n NotificationPopupView v = activeNotifications.get(i);\n final int left = v.getPopupLeft();\n final int top = (int) (((i + 1) * SPACING) - (progress * SPACING));\n v.setPopupPosition(left,\n top);\n }\n }\n\n @Override\n public void onComplete() {\n super.onComplete();\n view.hide();\n deactiveNotifications.remove(view);\n activeNotifications.remove(view);\n removing = false;\n remove();\n }\n };\n fadeOutAnimation.run(500);\n }",
"private void populateDefaultData(FieldItem[] defaultData)\n {\n for (FieldItem item : defaultData)\n {\n m_map.put(item.getType(), item);\n }\n }",
"@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 }",
"public void localCommit()\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"commit was called\");\r\n if (!this.isInLocalTransaction)\r\n {\r\n throw new TransactionNotInProgressException(\"Not in transaction, call begin() before commit()\");\r\n }\r\n try\r\n {\r\n if(!broker.isManaged())\r\n {\r\n if (batchCon != null)\r\n {\r\n batchCon.commit();\r\n }\r\n else if (con != null)\r\n {\r\n con.commit();\r\n }\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled()) log.debug(\r\n \"Found managed environment setting in PB, will skip Connection.commit() call\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n log.error(\"Commit on underlying connection failed, try to rollback connection\", e);\r\n this.localRollback();\r\n throw new TransactionAbortedException(\"Commit on connection failed\", e);\r\n }\r\n finally\r\n {\r\n this.isInLocalTransaction = false;\r\n restoreAutoCommitState();\r\n this.releaseConnection();\r\n }\r\n }",
"public final void debug(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.DEBUG, pObject, null);\r\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 }",
"protected byte[] getUpperBytesInternal() {\n\t\tbyte cached[];\n\t\tif(hasNoValueCache()) {\n\t\t\tValueCache cache = valueCache;\n\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\tif(!isMultiple()) {\n\t\t\t\tcache.lowerBytes = cached;\n\t\t\t}\n\t\t} else {\n\t\t\tValueCache cache = valueCache;\n\t\t\tif((cached = cache.upperBytes) == null) {\n\t\t\t\tif(!isMultiple()) {\n\t\t\t\t\tif((cached = cache.lowerBytes) != null) {\n\t\t\t\t\t\tcache.upperBytes = cached;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcache.lowerBytes = cache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn cached;\n\t}"
] |
Meant to execute assertions in tests only
@return a read-only view of the map containing the relations between entities | [
"public Map<AssociationKey, Map<RowKey, Map<String, Object>>> getAssociationsMap() {\n\t\treturn Collections.unmodifiableMap( associationsKeyValueStorage );\n\t}"
] | [
"@SuppressWarnings(\"rawtypes\")\n\tpublic void setReplicationClassLoader(Fqn regionFqn, ClassLoader classLoader) {\n\t\tif (!isLocalMode()) {\n\t\t\tfinal Region region = jBossCache.getRegion(regionFqn, true);\n\t\t\tregion.registerContextClassLoader(classLoader);\n\t\t\tif (!region.isActive() && jBossCache.getCacheStatus() == CacheStatus.STARTED) {\n\t\t\t\tregion.activate();\n\t\t\t}\t\t\t\n\t\t}\n\t}",
"public static authenticationvserver_auditnslogpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_auditnslogpolicy_binding obj = new authenticationvserver_auditnslogpolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_auditnslogpolicy_binding response[] = (authenticationvserver_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Collection<Method> getAllMethods(String name) {\n final Map<ParamList, Map<Class<?>, Method>> nameMap = methods.get(name);\n if (nameMap == null) {\n return Collections.emptySet();\n }\n final Collection<Method> methods = new ArrayList<Method>();\n for (Map<Class<?>, Method> map : nameMap.values()) {\n methods.addAll(map.values());\n }\n return methods;\n }",
"private void printClassRecord(PrintStream out, ClassRecord classRecord,\n\t\t\tEntityIdValue entityIdValue) {\n\t\tprintTerms(out, classRecord.itemDocument, entityIdValue, \"\\\"\"\n\t\t\t\t+ getClassLabel(entityIdValue) + \"\\\"\");\n\t\tprintImage(out, classRecord.itemDocument);\n\n\t\tout.print(\",\" + classRecord.itemCount + \",\" + classRecord.subclassCount);\n\n\t\tprintClassList(out, classRecord.superClasses);\n\n\t\tHashSet<EntityIdValue> superClasses = new HashSet<>();\n\t\tfor (EntityIdValue superClass : classRecord.superClasses) {\n\t\t\taddSuperClasses(superClass, superClasses);\n\t\t}\n\n\t\tprintClassList(out, superClasses);\n\n\t\tprintRelatedProperties(out, classRecord);\n\n\t\tout.println(\"\");\n\t}",
"public String getResourceFilename() {\n switch (resourceType) {\n case ANDROID_ASSETS:\n return assetPath\n .substring(assetPath.lastIndexOf(File.separator) + 1);\n\n case ANDROID_RESOURCE:\n return resourceFilePath.substring(\n resourceFilePath.lastIndexOf(File.separator) + 1);\n\n case LINUX_FILESYSTEM:\n return filePath.substring(filePath.lastIndexOf(File.separator) + 1);\n\n case NETWORK:\n return url.getPath().substring(url.getPath().lastIndexOf(\"/\") + 1);\n\n case INPUT_STREAM:\n return inputStreamName;\n\n default:\n return null;\n }\n }",
"public void printExtraClasses(RootDoc root) {\n\tSet<String> names = new HashSet<String>(classnames.keySet()); \n\tfor(String className: names) {\n\t ClassInfo info = getClassInfo(className, true);\n\t if (info.nodePrinted)\n\t\tcontinue;\n\t ClassDoc c = root.classNamed(className);\n\t if(c != null) {\n\t\tprintClass(c, false);\n\t\tcontinue;\n\t }\n\t // Handle missing classes:\n\t Options opt = optionProvider.getOptionsFor(className);\n\t if(opt.matchesHideExpression(className))\n\t\tcontinue;\n\t w.println(linePrefix + \"// \" + className);\n\t w.print(linePrefix + info.name + \"[label=\");\n\t externalTableStart(opt, className, classToUrl(className));\n\t innerTableStart();\n\t String qualifiedName = qualifiedName(opt, className);\n\t int startTemplate = qualifiedName.indexOf('<');\n\t int idx = qualifiedName.lastIndexOf('.', startTemplate < 0 ? qualifiedName.length() - 1 : startTemplate);\n\t if(opt.postfixPackage && idx > 0 && idx < (qualifiedName.length() - 1)) {\n\t\tString packageName = qualifiedName.substring(0, idx);\n\t\tString cn = qualifiedName.substring(idx + 1);\n\t\ttableLine(Align.CENTER, Font.CLASS.wrap(opt, escape(cn)));\n\t\ttableLine(Align.CENTER, Font.PACKAGE.wrap(opt, packageName));\n\t } else {\n\t\ttableLine(Align.CENTER, Font.CLASS.wrap(opt, escape(qualifiedName)));\n\t }\n\t innerTableEnd();\n\t externalTableEnd();\n\t if (className == null || className.length() == 0)\n\t\tw.print(\",URL=\\\"\" + classToUrl(className) + \"\\\"\");\n\t nodeProperties(opt);\n\t}\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 }",
"private static void listHierarchy(Task task, String indent)\n {\n for (Task child : task.getChildTasks())\n {\n System.out.println(indent + \"Task: \" + child.getName() + \"\\t\" + child.getStart() + \"\\t\" + child.getFinish());\n listHierarchy(child, indent + \" \");\n }\n }",
"public static ipset[] get(nitro_service service) throws Exception{\n\t\tipset obj = new ipset();\n\t\tipset[] response = (ipset[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Return total number of connections currently in use by an application
@return no of leased connections | [
"public int getTotalLeased(){\r\n\t\tint total=0;\r\n\t\tfor (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){\r\n\t\t\ttotal+=this.partitions[i].getCreatedConnections()-this.partitions[i].getAvailableConnections();\r\n\t\t}\r\n\t\treturn total;\r\n\t}"
] | [
"private static DataHandler getDataHandlerForString(Event event) {\n try {\n return new DataHandler(new ByteDataSource(event.getContent().getBytes(\"UTF-8\")));\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n }",
"public String addExtent(Properties attributes) throws XDocletException\r\n {\r\n String name = attributes.getProperty(ATTRIBUTE_NAME);\r\n\r\n if (!_model.hasClass(name))\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_FIND_TYPE,\r\n new String[]{name}));\r\n }\r\n _curClassDef.addExtentClass(_model.getClass(name));\r\n return \"\";\r\n }",
"@Override\n\tpublic boolean isSinglePrefixBlock() {\n\t\tInteger networkPrefixLength = getNetworkPrefixLength();\n\t\tif(networkPrefixLength == null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn containsSinglePrefixBlock(networkPrefixLength);\n\t}",
"@SuppressWarnings(\"unchecked\")\n\tpublic <T extends StatementDocument> T nullEdit(T currentDocument)\n\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tStatementUpdate statementUpdate = new StatementUpdate(currentDocument,\n\t\t\t\tCollections.<Statement>emptyList(), Collections.<Statement>emptyList());\n\t\tstatementUpdate.setGuidGenerator(guidGenerator);\n\t\t\n\t return (T) this.wbEditingAction.wbEditEntity(currentDocument\n\t\t\t\t.getEntityId().getId(), null, null, null, statementUpdate\n\t\t\t\t.getJsonUpdateString(), false, this.editAsBot, currentDocument\n\t\t\t\t.getRevisionId(), null);\n\t}",
"public float getChildSize(final int dataIndex, final Axis axis) {\n float size = 0;\n Widget child = mContainer.get(dataIndex);\n if (child != null) {\n switch (axis) {\n case X:\n size = child.getLayoutWidth();\n break;\n case Y:\n size = child.getLayoutHeight();\n break;\n case Z:\n size = child.getLayoutDepth();\n break;\n default:\n throw new RuntimeAssertion(\"Bad axis specified: %s\", axis);\n }\n }\n return size;\n }",
"public List<Dependency> getModuleDependencies(final String moduleId, final FiltersHolder filters){\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n return getModuleDependencies(module, filters, 1, new ArrayList<String>());\n }",
"public Map<Integer, List<Row>> createTimeEntryMap(List<Row> rows)\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer workPatternID = row.getInteger(\"TIME_ENTRYID\");\n List<Row> list = map.get(workPatternID);\n if (list == null)\n {\n list = new LinkedList<Row>();\n map.put(workPatternID, list);\n }\n list.add(row);\n }\n return map;\n }",
"private void addDownloadButton(final CmsLogFileView view) {\n\n Button button = CmsToolBar.createButton(\n FontOpenCms.DOWNLOAD,\n CmsVaadinUtils.getMessageText(Messages.GUI_LOGFILE_DOWNLOAD_0));\n button.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n Window window = CmsBasicDialog.prepareWindow(CmsBasicDialog.DialogWidth.wide);\n window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_LOGFILE_DOWNLOAD_0));\n window.setContent(new CmsLogDownloadDialog(window, view.getCurrentFile()));\n A_CmsUI.get().addWindow(window);\n }\n });\n m_uiContext.addToolbarButton(button);\n }",
"public int[] getCurrentValuesArray() {\n int[] currentValues = new int[5];\n\n currentValues[0] = getMinFilterType().getFilterValue(); // MIN FILTER\n currentValues[1] = getMagFilterType().getFilterValue(); // MAG FILTER\n currentValues[2] = getAnisotropicValue(); // ANISO FILTER\n currentValues[3] = getWrapSType().getWrapValue(); // WRAP S\n currentValues[4] = getWrapTType().getWrapValue(); // WRAP T\n\n return currentValues;\n }"
] |
Set the diffuse light intensity.
This designates the color of the diffuse reflection.
It is multiplied by the material diffuse color to derive
the hue of the diffuse reflection for that material.
The built-in phong shader {@link GVRPhongShader} uses a {@code vec4} uniform named
{@code diffuse_intensity} to control the intensity of diffuse light reflected.
@param r red component (0 to 1)
@param g green component (0 to 1)
@param b blue component (0 to 1)
@param a alpha component (0 to 1) | [
"public void setDiffuseIntensity(float r, float g, float b, float a) {\n setVec4(\"diffuse_intensity\", r, g, b, a);\n }"
] | [
"@SuppressWarnings(\"unused\")\n public String getDevicePushToken(final PushType type) {\n switch (type) {\n case GCM:\n return getCachedGCMToken();\n case FCM:\n return getCachedFCMToken();\n default:\n return null;\n }\n }",
"private static String formatDirName(final String prefix, final String suffix) {\n // Replace all invalid characters with '-'\n final CharMatcher invalidCharacters = VALID_SUFFIX_CHARS.negate();\n return String.format(\"%s-%s\", prefix, invalidCharacters.trimAndCollapseFrom(suffix.toLowerCase(), '-'));\n }",
"public Object selectElement(String predicate) throws org.odmg.QueryInvalidException\r\n {\r\n return ((DList) this.query(predicate)).get(0);\r\n }",
"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 Object convertStringToJavaField(String value, int columnPos) throws SQLException {\n\t\tif (value == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn fieldConverter.resultStringToJava(this, value, columnPos);\n\t\t}\n\t}",
"private void expireDevices() {\n long now = System.currentTimeMillis();\n // Make a copy so we don't have to worry about concurrent modification.\n Map<InetAddress, DeviceAnnouncement> copy = new HashMap<InetAddress, DeviceAnnouncement>(devices);\n for (Map.Entry<InetAddress, DeviceAnnouncement> entry : copy.entrySet()) {\n if (now - entry.getValue().getTimestamp() > MAXIMUM_AGE) {\n devices.remove(entry.getKey());\n deliverLostAnnouncement(entry.getValue());\n }\n }\n if (devices.isEmpty()) {\n firstDeviceTime.set(0); // We have lost contact with the Pro DJ Link network, so start over with next device.\n }\n }",
"public ItemRequest<Tag> delete(String tag) {\n \n String path = String.format(\"/tags/%s\", tag);\n return new ItemRequest<Tag>(this, Tag.class, path, \"DELETE\");\n }",
"private boolean detectWSAddressingFeature(InterceptorProvider provider, Bus bus) {\n //detect on the bus level\n if (bus.getFeatures() != null) {\n Iterator<Feature> busFeatures = bus.getFeatures().iterator();\n while (busFeatures.hasNext()) {\n Feature busFeature = busFeatures.next();\n if (busFeature instanceof WSAddressingFeature) {\n return true;\n }\n }\n }\n\n //detect on the endpoint/client level\n Iterator<Interceptor<? extends Message>> interceptors = provider.getInInterceptors().iterator();\n while (interceptors.hasNext()) {\n Interceptor<? extends Message> ic = interceptors.next();\n if (ic instanceof MAPAggregator) {\n return true;\n }\n }\n\n return false;\n }",
"public void setOnKeyboardDone(final IntlPhoneInputListener listener) {\n mPhoneEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_DONE) {\n listener.done(IntlPhoneInput.this, isValid());\n }\n return false;\n }\n });\n }"
] |
Mark objects no longer available in collection for delete and new objects for insert.
@param broker the PB to persist all objects | [
"private void checkAllEnvelopes(PersistenceBroker broker)\r\n {\r\n Iterator iter = ((List) mvOrderOfIds.clone()).iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n // only non transient objects should be performed\r\n if(!mod.getModificationState().isTransient())\r\n {\r\n mod.markReferenceElements(broker);\r\n }\r\n }\r\n }"
] | [
"public static final String printTime(Date value)\n {\n return (value == null ? null : TIME_FORMAT.get().format(value));\n }",
"private static JSONObject parseStencilSet(StencilSet stencilSet) throws JSONException {\n if (stencilSet != null) {\n JSONObject stencilSetObject = new JSONObject();\n\n stencilSetObject.put(\"url\",\n stencilSet.getUrl().toString());\n stencilSetObject.put(\"namespace\",\n stencilSet.getNamespace().toString());\n\n return stencilSetObject;\n }\n\n return new JSONObject();\n }",
"public <T> T invokeWithClientSession(int targetPlayer, ClientTask<T> task, String description)\n throws Exception {\n if (!isRunning()) {\n throw new IllegalStateException(\"ConnectionManager is not running, aborting \" + description);\n }\n\n final Client client = allocateClient(targetPlayer, description);\n try {\n return task.useClient(client);\n } finally {\n freeClient(client);\n }\n }",
"public void setFrustum(float[] frustum)\n {\n Matrix4f projMatrix = new Matrix4f();\n projMatrix.setFrustum(frustum[0], frustum[3], frustum[1], frustum[4], frustum[2], frustum[5]);\n setFrustum(projMatrix);\n }",
"protected CmsProject createAndSetModuleImportProject(CmsObject cms, CmsModule module) throws CmsException {\n\n CmsProject importProject = cms.createProject(\n org.opencms.module.Messages.get().getBundle(cms.getRequestContext().getLocale()).key(\n org.opencms.module.Messages.GUI_IMPORT_MODULE_PROJECT_NAME_1,\n new Object[] {module.getName()}),\n org.opencms.module.Messages.get().getBundle(cms.getRequestContext().getLocale()).key(\n org.opencms.module.Messages.GUI_IMPORT_MODULE_PROJECT_DESC_1,\n new Object[] {module.getName()}),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n CmsProject.PROJECT_TYPE_TEMPORARY);\n cms.getRequestContext().setCurrentProject(importProject);\n cms.copyResourceToProject(\"/\");\n return importProject;\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 static double HighAccuracyFunction(double x) {\n if (x < -8 || x > 8)\n return 0;\n\n double sum = x;\n double term = 0;\n\n double nextTerm = x;\n double pwr = x * x;\n double i = 1;\n\n // Iterate until adding next terms doesn't produce\n // any change within the current numerical accuracy.\n\n while (sum != term) {\n term = sum;\n\n // Next term\n nextTerm *= pwr / (i += 2);\n\n sum += nextTerm;\n }\n\n return 0.5 + sum * Math.exp(-0.5 * pwr - 0.5 * Constants.Log2PI);\n }",
"public boolean canLockBecauseOfInactivity(CmsObject cms, CmsUser user) {\n\n return !user.isManaged()\n && !user.isWebuser()\n && !OpenCms.getDefaultUsers().isDefaultUser(user.getName())\n && !OpenCms.getRoleManager().hasRole(cms, user.getName(), CmsRole.ROOT_ADMIN);\n }",
"private String checkinScriptCommand() {\n\n String exportModules = \"\";\n if ((m_modulesToExport != null) && !m_modulesToExport.isEmpty()) {\n StringBuffer exportModulesParam = new StringBuffer();\n for (String moduleName : m_modulesToExport) {\n exportModulesParam.append(\" \").append(moduleName);\n }\n exportModulesParam.replace(0, 1, \" \\\"\");\n exportModulesParam.append(\"\\\" \");\n exportModules = \" --modules \" + exportModulesParam.toString();\n\n }\n String commitMessage = \"\";\n if (m_commitMessage != null) {\n commitMessage = \" -msg \\\"\" + m_commitMessage.replace(\"\\\"\", \"\\\\\\\"\") + \"\\\"\";\n }\n String gitUserName = \"\";\n if (m_gitUserName != null) {\n if (m_gitUserName.trim().isEmpty()) {\n gitUserName = \" --ignore-default-git-user-name\";\n } else {\n gitUserName = \" --git-user-name \\\"\" + m_gitUserName + \"\\\"\";\n }\n }\n String gitUserEmail = \"\";\n if (m_gitUserEmail != null) {\n if (m_gitUserEmail.trim().isEmpty()) {\n gitUserEmail = \" --ignore-default-git-user-email\";\n } else {\n gitUserEmail = \" --git-user-email \\\"\" + m_gitUserEmail + \"\\\"\";\n }\n }\n String autoPullBefore = \"\";\n if (m_autoPullBefore != null) {\n autoPullBefore = m_autoPullBefore.booleanValue() ? \" --pull-before \" : \" --no-pull-before\";\n }\n String autoPullAfter = \"\";\n if (m_autoPullAfter != null) {\n autoPullAfter = m_autoPullAfter.booleanValue() ? \" --pull-after \" : \" --no-pull-after\";\n }\n String autoPush = \"\";\n if (m_autoPush != null) {\n autoPush = m_autoPush.booleanValue() ? \" --push \" : \" --no-push\";\n }\n String exportFolder = \" --export-folder \\\"\" + m_currentConfiguration.getModuleExportPath() + \"\\\"\";\n String exportMode = \" --export-mode \" + m_currentConfiguration.getExportMode();\n String excludeLibs = \"\";\n if (m_excludeLibs != null) {\n excludeLibs = m_excludeLibs.booleanValue() ? \" --exclude-libs\" : \" --no-exclude-libs\";\n }\n String commitMode = \"\";\n if (m_commitMode != null) {\n commitMode = m_commitMode.booleanValue() ? \" --commit\" : \" --no-commit\";\n }\n String ignoreUncleanMode = \"\";\n if (m_ignoreUnclean != null) {\n ignoreUncleanMode = m_ignoreUnclean.booleanValue() ? \" --ignore-unclean\" : \" --no-ignore-unclean\";\n }\n String copyAndUnzip = \"\";\n if (m_copyAndUnzip != null) {\n copyAndUnzip = m_copyAndUnzip.booleanValue() ? \" --copy-and-unzip\" : \" --no-copy-and-unzip\";\n }\n\n String configFilePath = m_currentConfiguration.getFilePath();\n\n return \"\\\"\"\n + DEFAULT_SCRIPT_FILE\n + \"\\\"\"\n + exportModules\n + commitMessage\n + gitUserName\n + gitUserEmail\n + autoPullBefore\n + autoPullAfter\n + autoPush\n + exportFolder\n + exportMode\n + excludeLibs\n + commitMode\n + ignoreUncleanMode\n + copyAndUnzip\n + \" \\\"\"\n + configFilePath\n + \"\\\"\";\n }"
] |
Checks if template mapper is configured in modules.
@return true if the template mapper is configured in modules | [
"public static boolean checkConfiguredInModules() {\n\n Boolean result = m_moduleCheckCache.get();\n if (result == null) {\n result = Boolean.valueOf(getConfiguredTemplateMapping() != null);\n m_moduleCheckCache.set(result);\n }\n return result.booleanValue();\n }"
] | [
"public List<Message> requestArtistMenuFrom(final SlotReference slotReference, final int sortOrder)\n throws Exception {\n\n ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {\n @Override\n public List<Message> useClient(Client client) throws Exception {\n if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {\n try {\n logger.debug(\"Requesting Artist menu.\");\n Message response = client.menuRequest(Message.KnownType.ARTIST_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,\n new NumberField(sortOrder));\n return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);\n } finally {\n client.unlockForMenuOperations();\n }\n } else {\n throw new TimeoutException(\"Unable to lock player for menu operations.\");\n }\n }\n };\n\n return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, \"requesting artist menu\");\n }",
"public F resolve(R resolvable, boolean cache) {\n R wrappedResolvable = wrap(resolvable);\n if (cache) {\n return resolved.getValue(wrappedResolvable);\n } else {\n return resolverFunction.apply(wrappedResolvable);\n }\n }",
"public static linkset_interface_binding[] get(nitro_service service, String id) throws Exception{\n\t\tlinkset_interface_binding obj = new linkset_interface_binding();\n\t\tobj.set_id(id);\n\t\tlinkset_interface_binding response[] = (linkset_interface_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void setNamespace(String prefix, String namespaceURI) {\n ensureNotNull(\"Prefix\", prefix);\n ensureNotNull(\"Namespace URI\", namespaceURI);\n\n namespaces.put(prefix, namespaceURI);\n }",
"public boolean setOverrideRepeatCount(String pathName, String methodName, Integer ordinal, Integer repeatCount) {\n try {\n String methodId = getOverrideIdForMethodName(methodName).toString();\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"profileIdentifier\", this._profileName),\n new BasicNameValuePair(\"ordinal\", ordinal.toString()),\n new BasicNameValuePair(\"repeatNumber\", repeatCount.toString())\n };\n\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName) + \"/\" + methodId, params));\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"public static void forceDelete(final Path path) throws IOException {\n\t\tif (!java.nio.file.Files.isDirectory(path)) {\n\t\t\tjava.nio.file.Files.delete(path);\n\t\t} else {\n\t\t\tjava.nio.file.Files.walkFileTree(path, DeleteDirVisitor.getInstance());\n\t\t}\n\t}",
"public void addChildTask(Task child, int childOutlineLevel)\n {\n int outlineLevel = NumberHelper.getInt(getOutlineLevel());\n\n if ((outlineLevel + 1) == childOutlineLevel)\n {\n m_children.add(child);\n setSummary(true);\n }\n else\n {\n if (m_children.isEmpty() == false)\n {\n (m_children.get(m_children.size() - 1)).addChildTask(child, childOutlineLevel);\n }\n }\n }",
"public boolean updateSelectedItemsList(int dataIndex, boolean select) {\n boolean done = false;\n boolean contains = isSelected(dataIndex);\n if (select) {\n if (!contains) {\n if (!mMultiSelectionSupported) {\n clearSelection(false);\n }\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"updateSelectedItemsList add index = %d\", dataIndex);\n mSelectedItemsList.add(dataIndex);\n done = true;\n }\n } else {\n if (contains) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"updateSelectedItemsList remove index = %d\", dataIndex);\n mSelectedItemsList.remove(dataIndex);\n done = true;\n }\n }\n return done;\n }",
"private void readAssignments(Resource mpxjResource, net.sf.mpxj.phoenix.schema.Project.Storepoints.Storepoint.Resources.Resource res)\n {\n for (Assignment assignment : res.getAssignment())\n {\n readAssignment(mpxjResource, assignment);\n }\n }"
] |
Use this API to change appfwsignatures. | [
"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}"
] | [
"@Override\n public Collection<EnhancedAnnotatedConstructor<T>> getEnhancedConstructors(Class<? extends Annotation> annotationType) {\n Set<EnhancedAnnotatedConstructor<T>> ret = new HashSet<EnhancedAnnotatedConstructor<T>>();\n for (EnhancedAnnotatedConstructor<T> constructor : constructors) {\n if (constructor.isAnnotationPresent(annotationType)) {\n ret.add(constructor);\n }\n }\n return ret;\n }",
"public static void showOnlyChannels(Object... channels){\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n visHandler.hideAll();\r\n for (Object channel : channels) {\r\n visHandler.alsoShow(channel);\r\n }\r\n }\r\n }\r\n }",
"public void replace( Token original , Token target ) {\n if( first == original )\n first = target;\n if( last == original )\n last = target;\n\n target.next = original.next;\n target.previous = original.previous;\n\n if( original.next != null )\n original.next.previous = target;\n if( original.previous != null )\n original.previous.next = target;\n\n original.next = original.previous = null;\n }",
"public void sort(ChildTaskContainer container)\n {\n // Do we have any tasks?\n List<Task> tasks = container.getChildTasks();\n if (!tasks.isEmpty())\n {\n for (Task task : tasks)\n {\n //\n // Sort child activities\n //\n sort(task);\n\n //\n // Sort Order:\n // 1. Activities come first\n // 2. WBS come last\n // 3. Activities ordered by activity ID\n // 4. WBS ordered by ID\n //\n Collections.sort(tasks, new Comparator<Task>()\n {\n @Override public int compare(Task t1, Task t2)\n {\n boolean t1IsWbs = m_wbsTasks.contains(t1);\n boolean t2IsWbs = m_wbsTasks.contains(t2);\n\n // Both are WBS\n if (t1IsWbs && t2IsWbs)\n {\n return t1.getID().compareTo(t2.getID());\n }\n\n // Both are activities\n if (!t1IsWbs && !t2IsWbs)\n {\n String activityID1 = (String) t1.getCurrentValue(m_activityIDField);\n String activityID2 = (String) t2.getCurrentValue(m_activityIDField);\n\n if (activityID1 == null || activityID2 == null)\n {\n return (activityID1 == null && activityID2 == null ? 0 : (activityID1 == null ? 1 : -1));\n }\n\n return activityID1.compareTo(activityID2);\n }\n\n // One activity one WBS\n return t1IsWbs ? 1 : -1;\n }\n });\n }\n }\n }",
"public Release getReleaseInfo(String appName, String releaseName) {\n return connection.execute(new ReleaseInfo(appName, releaseName), apiKey);\n }",
"public static void deleteSilentlyRecursively(final Path path) {\n if (path != null) {\n try {\n deleteRecursively(path);\n } catch (IOException ioex) {\n DeploymentRepositoryLogger.ROOT_LOGGER.cannotDeleteFile(ioex, path);\n }\n }\n }",
"public Diff compare(String left, String right) {\n\t\treturn compare(getCtType(left), getCtType(right));\n\t}",
"@SuppressWarnings(\"unchecked\")\n public static Map<String, Properties> readMultipleClientConfigAvro(String configAvro) {\n Map<String, Properties> mapStoreToProps = Maps.newHashMap();\n try {\n JsonDecoder decoder = new JsonDecoder(CLIENT_CONFIGS_AVRO_SCHEMA, configAvro);\n GenericDatumReader<Object> datumReader = new GenericDatumReader<Object>(CLIENT_CONFIGS_AVRO_SCHEMA);\n\n Map<Utf8, Map<Utf8, Utf8>> storeConfigs = (Map<Utf8, Map<Utf8, Utf8>>) datumReader.read(null,\n decoder);\n // Store config props to return back\n for(Utf8 storeName: storeConfigs.keySet()) {\n Properties props = new Properties();\n Map<Utf8, Utf8> singleConfig = storeConfigs.get(storeName);\n\n for(Utf8 key: singleConfig.keySet()) {\n props.put(key.toString(), singleConfig.get(key).toString());\n }\n\n if(storeName == null || storeName.length() == 0) {\n throw new Exception(\"Invalid store name found!\");\n }\n\n mapStoreToProps.put(storeName.toString(), props);\n }\n } catch(Exception e) {\n e.printStackTrace();\n }\n return mapStoreToProps;\n }",
"static TarArchiveEntry defaultFileEntryWithName( final String fileName ) {\n TarArchiveEntry entry = new TarArchiveEntry(fileName, true);\n entry.setUserId(ROOT_UID);\n entry.setUserName(ROOT_NAME);\n entry.setGroupId(ROOT_UID);\n entry.setGroupName(ROOT_NAME);\n entry.setMode(TarArchiveEntry.DEFAULT_FILE_MODE);\n return entry;\n }"
] |
Adds the file to the tar archive represented by output stream. It's caller's responsibility to close output stream
properly.
@param out target archive.
@param source file to be added.
@param fileSize size of the file (which is known in most cases).
@throws IOException in case of any issues with underlying store. | [
"public static void archiveFile(@NotNull final ArchiveOutputStream out,\n @NotNull final VirtualFileDescriptor source,\n final long fileSize) throws IOException {\n if (!source.hasContent()) {\n throw new IllegalArgumentException(\"Provided source is not a file: \" + source.getPath());\n }\n //noinspection ChainOfInstanceofChecks\n if (out instanceof TarArchiveOutputStream) {\n final TarArchiveEntry entry = new TarArchiveEntry(source.getPath() + source.getName());\n entry.setSize(fileSize);\n entry.setModTime(source.getTimeStamp());\n out.putArchiveEntry(entry);\n } else if (out instanceof ZipArchiveOutputStream) {\n final ZipArchiveEntry entry = new ZipArchiveEntry(source.getPath() + source.getName());\n entry.setSize(fileSize);\n entry.setTime(source.getTimeStamp());\n out.putArchiveEntry(entry);\n } else {\n throw new IOException(\"Unknown archive output stream\");\n }\n final InputStream input = source.getInputStream();\n try {\n IOUtil.copyStreams(input, fileSize, out, IOUtil.BUFFER_ALLOCATOR);\n } finally {\n if (source.shouldCloseStream()) {\n input.close();\n }\n }\n out.closeArchiveEntry();\n }"
] | [
"public static void checkRequired(OptionSet options, List<String> opts)\n throws VoldemortException {\n List<String> optCopy = Lists.newArrayList();\n for(String opt: opts) {\n if(options.has(opt)) {\n optCopy.add(opt);\n }\n }\n if(optCopy.size() < 1) {\n System.err.println(\"Please specify one of the following options:\");\n for(String opt: opts) {\n System.err.println(\"--\" + opt);\n }\n Utils.croak(\"Missing required option.\");\n }\n if(optCopy.size() > 1) {\n System.err.println(\"Conflicting options:\");\n for(String opt: optCopy) {\n System.err.println(\"--\" + opt);\n }\n Utils.croak(\"Conflicting options detected.\");\n }\n }",
"public static boolean isPrimitiveArray(Class<?> clazz) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\treturn (clazz.isArray() && clazz.getComponentType().isPrimitive());\n\t}",
"public static void acceptsJson(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_J, OPT_JSON),\n \"fetch key/entry by key value of json type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }",
"public static <T> T createObject(final Class<T> clazz, final Object... args) throws NoSuchConstructorException,\n AmbiguousConstructorException, ReflectiveOperationException {\n return findConstructor(clazz, args).newInstance(args);\n }",
"public String getRepoKey() {\n String repoKey;\n if (isDynamicMode()) {\n repoKey = keyFromText;\n } else {\n repoKey = keyFromSelect;\n }\n return repoKey;\n }",
"public static TaskField getMpxjField(int value)\n {\n TaskField result = null;\n\n if (value >= 0 && value < MPX_MPXJ_ARRAY.length)\n {\n result = MPX_MPXJ_ARRAY[value];\n }\n\n return (result);\n }",
"private void readHolidays()\n {\n for (MapRow row : m_tables.get(\"HOL\"))\n {\n ProjectCalendar calendar = m_calendarMap.get(row.getInteger(\"CALENDAR_ID\"));\n if (calendar != null)\n {\n Date date = row.getDate(\"DATE\");\n ProjectCalendarException exception = calendar.addCalendarException(date, date);\n if (row.getBoolean(\"ANNUAL\"))\n {\n RecurringData recurring = new RecurringData();\n recurring.setRecurrenceType(RecurrenceType.YEARLY);\n recurring.setYearlyAbsoluteFromDate(date);\n recurring.setStartDate(date);\n exception.setRecurring(recurring);\n // TODO set end date based on project end date\n }\n }\n }\n }",
"public ScopedToken getLowerScopedToken(List<String> scopes, String resource) {\n assert (scopes != null);\n assert (scopes.size() > 0);\n URL url = null;\n try {\n url = new URL(this.getTokenURL());\n } catch (MalformedURLException e) {\n assert false : \"An invalid refresh URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid refresh URL indicates a bug in the SDK.\", e);\n }\n\n StringBuilder spaceSeparatedScopes = new StringBuilder();\n for (int i = 0; i < scopes.size(); i++) {\n spaceSeparatedScopes.append(scopes.get(i));\n if (i < scopes.size() - 1) {\n spaceSeparatedScopes.append(\" \");\n }\n }\n\n String urlParameters = null;\n\n if (resource != null) {\n //this.getAccessToken() ensures we have a valid access token\n urlParameters = String.format(\"grant_type=urn:ietf:params:oauth:grant-type:token-exchange\"\n + \"&subject_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=%s\"\n + \"&scope=%s&resource=%s\",\n this.getAccessToken(), spaceSeparatedScopes, resource);\n } else {\n //this.getAccessToken() ensures we have a valid access token\n urlParameters = String.format(\"grant_type=urn:ietf:params:oauth:grant-type:token-exchange\"\n + \"&subject_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=%s\"\n + \"&scope=%s\",\n this.getAccessToken(), spaceSeparatedScopes);\n }\n\n BoxAPIRequest request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n String json;\n try {\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n json = response.getJSON();\n } catch (BoxAPIException e) {\n this.notifyError(e);\n throw e;\n }\n\n JsonObject jsonObject = JsonObject.readFrom(json);\n ScopedToken token = new ScopedToken(jsonObject);\n token.setObtainedAt(System.currentTimeMillis());\n token.setExpiresIn(jsonObject.get(\"expires_in\").asLong() * 1000);\n return token;\n }",
"protected boolean isSlopDead(Cluster cluster, Set<String> storeNames, Slop slop) {\n // destination node , no longer exists\n if(!cluster.getNodeIds().contains(slop.getNodeId())) {\n return true;\n }\n\n // destination store, no longer exists\n if(!storeNames.contains(slop.getStoreName())) {\n return true;\n }\n\n // else. slop is alive\n return false;\n }"
] |
Returns all the version directories present in the root directory
specified
@param rootDir The parent directory
@param maxId The
@return An array of version directories | [
"public static File[] getVersionDirs(File rootDir, final long minId, final long maxId) {\n return rootDir.listFiles(new FileFilter() {\n\n public boolean accept(File pathName) {\n if(checkVersionDirName(pathName)) {\n long versionId = getVersionId(pathName);\n if(versionId != -1 && versionId <= maxId && versionId >= minId) {\n return true;\n }\n }\n return false;\n }\n });\n }"
] | [
"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 List<LogSegment> trunc(int newStart) {\n if (newStart < 0) {\n throw new IllegalArgumentException(\"Starting index must be positive.\");\n }\n while (true) {\n List<LogSegment> curr = contents.get();\n int newLength = Math.max(curr.size() - newStart, 0);\n List<LogSegment> updatedList = new ArrayList<LogSegment>(curr.subList(Math.min(newStart, curr.size() - 1),\n curr.size()));\n if (contents.compareAndSet(curr, updatedList)) {\n return curr.subList(0, curr.size() - newLength);\n }\n }\n }",
"public static<T> Vendor<T> vendor(Callable<T> f) {\n\treturn j.vendor(f);\n }",
"public static <T> ManagedBean<T> of(BeanAttributes<T> attributes, EnhancedAnnotatedType<T> clazz, BeanManagerImpl beanManager) {\n return new ManagedBean<T>(attributes, clazz, createId(attributes, clazz), beanManager);\n }",
"public Point3d[] getVertices() {\n Point3d[] vtxs = new Point3d[numVertices];\n for (int i = 0; i < numVertices; i++) {\n vtxs[i] = pointBuffer[vertexPointIndices[i]].pnt;\n }\n return vtxs;\n }",
"public List<File> getAutoAttachCacheFiles() {\n ArrayList<File> currentFiles = new ArrayList<File>(autoAttachCacheFiles);\n Collections.sort(currentFiles, new Comparator<File>() {\n @Override\n public int compare(File o1, File o2) {\n return o1.getName().compareTo(o2.getName());\n }\n });\n return Collections.unmodifiableList(currentFiles);\n }",
"public void setSize(int size) {\n if (size != MaterialProgressDrawable.LARGE && size != MaterialProgressDrawable.DEFAULT) {\n return;\n }\n final DisplayMetrics metrics = getResources().getDisplayMetrics();\n if (size == MaterialProgressDrawable.LARGE) {\n mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER_LARGE * metrics.density);\n } else {\n mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);\n }\n // force the bounds of the progress circle inside the circle view to\n // update by setting it to null before updating its size and then\n // re-setting it\n mCircleView.setImageDrawable(null);\n mProgress.updateSizes(size);\n mCircleView.setImageDrawable(mProgress);\n }",
"@Override\n\tpublic void format(final StringBuffer sbuf, final LoggingEvent event) {\n\t\tfor (int i = 0; i < patternConverters.length; i++) {\n\t\t\tfinal int startField = sbuf.length();\n\t\t\tpatternConverters[i].format(event, sbuf);\n\t\t\tpatternFields[i].format(startField, sbuf);\n\t\t}\n\t}",
"@Deprecated\n\tpublic List<Double> getResolutions() {\n\t\tList<Double> resolutions = new ArrayList<Double>();\n\t\tfor (ScaleInfo scale : getZoomLevels()) {\n\t\t\tresolutions.add(1. / scale.getPixelPerUnit());\n\t\t}\n\t\treturn resolutions;\n\t}"
] |
Add a URL pattern to the routing table.
@param urlPattern A regular expression
@throws RouteAlreadyMappedException | [
"public void addRegexRoute(String urlPattern, Class<? extends Actor> actorClass) throws RouteAlreadyMappedException {\n addRoute(new Route(urlPattern, true), actorClass);\n }"
] | [
"private boolean isBundleProperty(Object property) {\n\n return (property.equals(TableProperty.KEY) || property.equals(TableProperty.TRANSLATION));\n }",
"protected void postProcessing()\n {\n //\n // Update the internal structure. We'll take this opportunity to\n // generate outline numbers for the tasks as they don't appear to\n // be present in the MPP file.\n //\n ProjectConfig config = m_project.getProjectConfig();\n config.setAutoWBS(m_autoWBS);\n config.setAutoOutlineNumber(true);\n m_project.updateStructure();\n config.setAutoOutlineNumber(false);\n\n //\n // Perform post-processing to set the summary flag\n //\n for (Task task : m_project.getTasks())\n {\n task.setSummary(task.hasChildTasks());\n }\n\n //\n // Ensure that the unique ID counters are correct\n //\n config.updateUniqueCounters();\n }",
"public Stats getPhotostreamStats(Date date) throws FlickrException {\n return getStats(METHOD_GET_PHOTOSTREAM_STATS, null, null, date);\n }",
"public float get(Layout.Axis axis) {\n switch (axis) {\n case X:\n return x;\n case Y:\n return y;\n case Z:\n return z;\n default:\n throw new RuntimeAssertion(\"Bad axis specified: %s\", axis);\n }\n }",
"public static String getRelativePathName(Path root, Path path) {\n Path relative = root.relativize(path);\n return Files.isDirectory(path) && !relative.toString().endsWith(\"/\") ? String.format(\"%s/\", relative.toString()) : relative.toString();\n }",
"public void deleteArtifact(final String gavc, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactPath(gavc));\n final ClientResponse response = resource.delete(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to DELETE artifact \" + gavc;\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 }",
"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 static <T> Method getMethod(Class<T> c, String name, Class<?>... argTypes) {\n try {\n return c.getMethod(name, argTypes);\n } catch(NoSuchMethodException e) {\n throw new IllegalArgumentException(e);\n }\n }",
"public static dnsview[] get(nitro_service service) throws Exception{\n\t\tdnsview obj = new dnsview();\n\t\tdnsview[] response = (dnsview[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Sets the specified many-to-one attribute to the specified value.
@param name name of the attribute
@param value value of the attribute
@since 1.9.0 | [
"public void setManyToOneAttribute(String name, AssociationValue value) {\n\t\tensureAttributes();\n\t\tAttribute attribute = new ManyToOneAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetAllAttributes().put(name, attribute);\n\n\t}"
] | [
"public Jar addClass(Class<?> clazz) throws IOException {\n final String resource = clazz.getName().replace('.', '/') + \".class\";\n return addEntry(resource, clazz.getClassLoader().getResourceAsStream(resource));\n }",
"private static Future<?> spawn(final int priority, final Runnable threadProc) {\n return threadPool.submit(new Runnable() {\n\n @Override\n public void run() {\n Thread current = Thread.currentThread();\n int defaultPriority = current.getPriority();\n\n try {\n current.setPriority(priority);\n\n /*\n * We yield to give the foreground process a chance to run.\n * This also means that the new priority takes effect RIGHT\n * AWAY, not after the next blocking call or quantum\n * timeout.\n */\n Thread.yield();\n\n try {\n threadProc.run();\n } catch (Exception e) {\n logException(TAG, e);\n }\n } finally {\n current.setPriority(defaultPriority);\n }\n\n }\n\n });\n }",
"public static Integer getDurationUnits(RecurringTask recurrence)\n {\n Duration duration = recurrence.getDuration();\n Integer result = null;\n\n if (duration != null)\n {\n result = UNITS_MAP.get(duration.getUnits());\n }\n\n return (result);\n }",
"private void processProperties(XMLStreamWriter writer, Set<Method> methodSet, Class<?> aClass) throws IntrospectionException, XMLStreamException\n {\n BeanInfo beanInfo = Introspector.getBeanInfo(aClass, aClass.getSuperclass());\n PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();\n\n for (int i = 0; i < propertyDescriptors.length; i++)\n {\n PropertyDescriptor propertyDescriptor = propertyDescriptors[i];\n if (propertyDescriptor.getPropertyType() != null)\n {\n String name = propertyDescriptor.getName();\n Method readMethod = propertyDescriptor.getReadMethod();\n Method writeMethod = propertyDescriptor.getWriteMethod();\n\n String readMethodName = readMethod == null ? null : readMethod.getName();\n String writeMethodName = writeMethod == null ? null : writeMethod.getName();\n addProperty(writer, name, propertyDescriptor.getPropertyType(), readMethodName, writeMethodName);\n\n if (readMethod != null)\n {\n methodSet.add(readMethod);\n }\n\n if (writeMethod != null)\n {\n methodSet.add(writeMethod);\n }\n }\n else\n {\n processAmbiguousProperty(writer, methodSet, aClass, propertyDescriptor);\n }\n }\n }",
"public Class<?> getType(String key) {\n Object val = this.data.get(key);\n return val == null ? null : val.getClass();\n }",
"public static void recursiveAddZip(File parent, ZipOutputStream zout, File fileSource)\n throws IOException {\n\n File[] files = fileSource.listFiles();\n\n for (int i = 0; i < files.length; i++) {\n if (files[i].isDirectory()) {\n recursiveAddZip(parent, zout, files[i]);\n continue;\n }\n\n byte[] buffer = new byte[1024];\n\n FileInputStream fin = new FileInputStream(files[i]);\n\n ZipEntry zipEntry =\n new ZipEntry(files[i].getAbsolutePath()\n .replace(parent.getAbsolutePath(), \"\").substring(1)); //$NON-NLS-1$\n zout.putNextEntry(zipEntry);\n\n int length;\n while ((length = fin.read(buffer)) > 0) {\n zout.write(buffer, 0, length);\n }\n\n zout.closeEntry();\n\n fin.close();\n\n }\n\n }",
"public 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 void delete(final String referenceId) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaDelete<PrintJobStatusExtImpl> delete =\n builder.createCriteriaDelete(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = delete.from(PrintJobStatusExtImpl.class);\n delete.where(builder.equal(root.get(\"referenceId\"), referenceId));\n getSession().createQuery(delete).executeUpdate();\n }",
"public void updateActive(int profileId, String clientUUID, Boolean active) throws Exception {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_CLIENT +\n \" SET \" + Constants.CLIENT_IS_ACTIVE + \"= ?\" +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= ? \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ?\"\n );\n statement.setBoolean(1, active);\n statement.setString(2, clientUUID);\n statement.setInt(3, profileId);\n statement.executeUpdate();\n } catch (Exception e) {\n // ok to swallow this.. just means there wasn't any\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }"
] |
Performs a null edit on an item. This has some effects on Wikibase,
such as refreshing the labels of the referred items in the UI.
@param itemId
the document to perform a null edit on
@throws MediaWikiApiErrorException
if the API returns errors
@throws IOException
if there are any IO errors, such as missing network connection | [
"public <T extends StatementDocument> void nullEdit(ItemIdValue itemId)\n\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tItemDocument currentDocument = (ItemDocument) this.wikibaseDataFetcher\n\t\t\t\t.getEntityDocument(itemId.getId());\n\t\t\n\t\tnullEdit(currentDocument);\n\t}"
] | [
"public CollectionRequest<Task> findByTag(String tag) {\n \n String path = String.format(\"/tags/%s/tasks\", tag);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"public boolean hasCachedValue(Key key) {\n\t\ttry {\n\t\t\treadLock.lock();\n\t\t\treturn content.containsKey(key);\n\t\t} finally {\n\t\t\treadLock.unlock();\n\t\t}\n\t}",
"private void addSubMatrixVariables(List<TokenList.Token> inputs, List<Variable> variables) {\n for (int i = 0; i < inputs.size(); i++) {\n TokenList.Token t = inputs.get(i);\n if( t.getType() != Type.VARIABLE )\n throw new ParseError(\"Expected variables only in sub-matrix input, not \"+t.getType());\n Variable v = t.getVariable();\n if( v.getType() == VariableType.INTEGER_SEQUENCE || isVariableInteger(t) ) {\n variables.add(v);\n } else {\n throw new ParseError(\"Expected an integer, integer sequence, or array range to define a submatrix\");\n }\n }\n }",
"public void forAllProcedures(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getProcedures(); it.hasNext(); )\r\n {\r\n _curProcedureDef = (ProcedureDef)it.next();\r\n generate(template);\r\n }\r\n _curProcedureDef = null;\r\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 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 }",
"public DbLicense getLicense(final String name) {\n final DbLicense license = repoHandler.getLicense(name);\n\n if (license == null) {\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"License \" + name + \" does not exist.\").build());\n }\n\n return license;\n }",
"public static void abortSystem(final Throwable error) {\n DaemonStarter.currentPhase.set(LifecyclePhase.ABORTING);\n try {\n DaemonStarter.getLifecycleListener().aborting();\n } catch (Exception e) {\n DaemonStarter.rlog.error(\"Custom abort failed\", e);\n }\n if (error != null) {\n DaemonStarter.rlog.error(\"Unrecoverable error encountered --> Exiting : {}\", error.getMessage());\n DaemonStarter.getLifecycleListener().exception(LifecyclePhase.ABORTING, error);\n } else {\n DaemonStarter.rlog.error(\"Unrecoverable error encountered --> Exiting\");\n }\n // Exit system with failure return code\n System.exit(1);\n }",
"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 }"
] |
Get the bounding box for a certain tile.
@param code
The unique tile code. Determines what tile we're talking about.
@param maxExtent
The maximum extent of the grid to which this tile belongs.
@param scale
The current client side scale.
@return Returns the bounding box for the tile, expressed in the layer's coordinate system. | [
"public static Envelope getTileBounds(TileCode code, Envelope maxExtent, double scale) {\n\t\tdouble[] layerSize = getTileLayerSize(code, maxExtent, scale);\n\t\tif (layerSize[0] == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tdouble cX = maxExtent.getMinX() + code.getX() * layerSize[0];\n\t\tdouble cY = maxExtent.getMinY() + code.getY() * layerSize[1];\n\t\treturn new Envelope(cX, cX + layerSize[0], cY, cY + layerSize[1]);\n\t}"
] | [
"private static final Duration parseDurationInFractionsOfMinutes(ProjectProperties properties, Number value, TimeUnit targetTimeUnit, int factor)\n {\n Duration result = null;\n\n if (value != null)\n {\n result = Duration.getInstance(value.intValue() / factor, TimeUnit.MINUTES);\n if (targetTimeUnit != result.getUnits())\n {\n result = result.convertUnits(targetTimeUnit, properties);\n }\n }\n\n return (result);\n }",
"protected void copyStream(File outputDirectory,\n InputStream stream,\n String targetFileName) throws IOException\n {\n File resourceFile = new File(outputDirectory, targetFileName);\n BufferedReader reader = null;\n Writer writer = null;\n try\n {\n reader = new BufferedReader(new InputStreamReader(stream, ENCODING));\n writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resourceFile), ENCODING));\n\n String line = reader.readLine();\n while (line != null)\n {\n writer.write(line);\n writer.write('\\n');\n line = reader.readLine();\n }\n writer.flush();\n }\n finally\n {\n if (reader != null)\n {\n reader.close();\n }\n if (writer != null)\n {\n writer.close();\n }\n }\n }",
"public boolean shouldCache(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkContains(uri, cacheIdentifiers) || checkSuffixes(uri, cacheSuffixes);\n\t}",
"public static <T> T callConstructor(Class<T> klass, Object[] args) {\n Class<?>[] klasses = new Class[args.length];\n for(int i = 0; i < args.length; i++)\n klasses[i] = args[i].getClass();\n return callConstructor(klass, klasses, args);\n }",
"@Override\r\n public String remove(Object key) {\r\n\r\n String result = m_configurationStrings.remove(key);\r\n m_configurationObjects.remove(key);\r\n return result;\r\n }",
"public Duration getStartVariance()\n {\n Duration variance = (Duration) getCachedValue(AssignmentField.START_VARIANCE);\n if (variance == null)\n {\n TimeUnit format = getParentFile().getProjectProperties().getDefaultDurationUnits();\n variance = DateHelper.getVariance(getTask(), getBaselineStart(), getStart(), format);\n set(AssignmentField.START_VARIANCE, variance);\n }\n return (variance);\n }",
"private Double zeroIsNull(Double value)\n {\n if (value != null && value.doubleValue() == 0)\n {\n value = null;\n }\n return value;\n }",
"public ClassDescriptor getDescriptorFor(String strClassName) throws ClassNotPersistenceCapableException\r\n {\r\n ClassDescriptor result = discoverDescriptor(strClassName);\r\n if (result == null)\r\n {\r\n throw new ClassNotPersistenceCapableException(strClassName + \" not found in OJB Repository\");\r\n }\r\n else\r\n {\r\n return result;\r\n }\r\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 }"
] |
Delete all enabled overrides for a client
@param profileId profile ID of teh client
@param client_uuid UUID of teh client | [
"public void disableAll(int profileId, String client_uuid) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.CLIENT_PROFILE_ID + \" = ?\" +\n \" AND \" + Constants.CLIENT_CLIENT_UUID + \" =? \"\n );\n statement.setInt(1, profileId);\n statement.setString(2, client_uuid);\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 }"
] | [
"public PhotoList<Photo> getUntagged(int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_UNTAGGED);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n PhotoList<Photo> photos = PhotoUtils.createPhotoList(photosElement);\r\n return photos;\r\n }",
"public static void addJarToClasspath(ClassLoader loader, URL url) throws IOException,\n IllegalAccessException, IllegalArgumentException, InvocationTargetException,\n NoSuchMethodException, SecurityException {\n URLClassLoader sysloader = (URLClassLoader) loader;\n Class<?> sysclass = URLClassLoader.class;\n\n Method method =\n sysclass.getDeclaredMethod(MyClasspathUtils.ADD_URL_METHOD, new Class[] {URL.class});\n method.setAccessible(true);\n method.invoke(sysloader, new Object[] {url});\n\n }",
"public boolean endsWith(Bytes suffix) {\n Objects.requireNonNull(suffix, \"endsWith(Bytes suffix) cannot have null parameter\");\n int startOffset = this.length - suffix.length;\n\n if (startOffset < 0) {\n return false;\n } else {\n int end = startOffset + this.offset + suffix.length;\n for (int i = startOffset + this.offset, j = suffix.offset; i < end; i++, j++) {\n if (this.data[i] != suffix.data[j]) {\n return false;\n }\n }\n }\n return true;\n }",
"public static int cudnnOpTensor(\n cudnnHandle handle, \n cudnnOpTensorDescriptor opTensorDesc, \n Pointer alpha1, \n cudnnTensorDescriptor aDesc, \n Pointer A, \n Pointer alpha2, \n cudnnTensorDescriptor bDesc, \n Pointer B, \n Pointer beta, \n cudnnTensorDescriptor cDesc, \n Pointer C)\n {\n return checkResult(cudnnOpTensorNative(handle, opTensorDesc, alpha1, aDesc, A, alpha2, bDesc, B, beta, cDesc, C));\n }",
"public <V> V detach(final AttachmentKey<V> key) {\n assert key != null;\n return key.cast(contextAttachments.remove(key));\n }",
"public static String makeHTMLTable(String[][] table, String[] rowLabels, String[] colLabels) {\r\n StringBuilder buff = new StringBuilder();\r\n buff.append(\"<table class=\\\"auto\\\" border=\\\"1\\\" cellspacing=\\\"0\\\">\\n\");\r\n // top row\r\n buff.append(\"<tr>\\n\");\r\n buff.append(\"<td></td>\\n\"); // the top left cell\r\n for (int j = 0; j < table[0].length; j++) { // assume table is a rectangular matrix\r\n buff.append(\"<td class=\\\"label\\\">\").append(colLabels[j]).append(\"</td>\\n\");\r\n }\r\n buff.append(\"</tr>\\n\");\r\n // all other rows\r\n for (int i = 0; i < table.length; i++) {\r\n // one row\r\n buff.append(\"<tr>\\n\");\r\n buff.append(\"<td class=\\\"label\\\">\").append(rowLabels[i]).append(\"</td>\\n\");\r\n for (int j = 0; j < table[i].length; j++) {\r\n buff.append(\"<td class=\\\"data\\\">\");\r\n buff.append(((table[i][j] != null) ? table[i][j] : \"\"));\r\n buff.append(\"</td>\\n\");\r\n }\r\n buff.append(\"</tr>\\n\");\r\n }\r\n buff.append(\"</table>\");\r\n return buff.toString();\r\n }",
"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 void acceptsUrl(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), \"bootstrap url\")\n .withRequiredArg()\n .describedAs(\"url\")\n .ofType(String.class);\n }",
"private Priority getPriority(Integer gpPriority)\n {\n int result;\n if (gpPriority == null)\n {\n result = Priority.MEDIUM;\n }\n else\n {\n int index = gpPriority.intValue();\n if (index < 0 || index >= PRIORITY.length)\n {\n result = Priority.MEDIUM;\n }\n else\n {\n result = PRIORITY[index];\n }\n }\n return Priority.getInstance(result);\n }"
] |
This method allows a predecessor relationship to be added to this
task instance.
@param targetTask the predecessor task
@param type relation type
@param lag relation lag
@return relationship | [
"@SuppressWarnings(\"unchecked\") public Relation addPredecessor(Task targetTask, RelationType type, Duration lag)\n {\n //\n // Ensure that we have a valid lag duration\n //\n if (lag == null)\n {\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n\n //\n // Retrieve the list of predecessors\n //\n List<Relation> predecessorList = (List<Relation>) getCachedValue(TaskField.PREDECESSORS);\n\n //\n // Ensure that there is only one predecessor relationship between\n // these two tasks.\n //\n Relation predecessorRelation = null;\n Iterator<Relation> iter = predecessorList.iterator();\n while (iter.hasNext() == true)\n {\n predecessorRelation = iter.next();\n if (predecessorRelation.getTargetTask() == targetTask)\n {\n if (predecessorRelation.getType() != type || predecessorRelation.getLag().compareTo(lag) != 0)\n {\n predecessorRelation = null;\n }\n break;\n }\n predecessorRelation = null;\n }\n\n //\n // If necessary, create a new predecessor relationship\n //\n if (predecessorRelation == null)\n {\n predecessorRelation = new Relation(this, targetTask, type, lag);\n predecessorList.add(predecessorRelation);\n }\n\n //\n // Retrieve the list of successors\n //\n List<Relation> successorList = (List<Relation>) targetTask.getCachedValue(TaskField.SUCCESSORS);\n\n //\n // Ensure that there is only one successor relationship between\n // these two tasks.\n //\n Relation successorRelation = null;\n iter = successorList.iterator();\n while (iter.hasNext() == true)\n {\n successorRelation = iter.next();\n if (successorRelation.getTargetTask() == this)\n {\n if (successorRelation.getType() != type || successorRelation.getLag().compareTo(lag) != 0)\n {\n successorRelation = null;\n }\n break;\n }\n successorRelation = null;\n }\n\n //\n // If necessary, create a new successor relationship\n //\n if (successorRelation == null)\n {\n successorRelation = new Relation(targetTask, this, type, lag);\n successorList.add(successorRelation);\n }\n\n return (predecessorRelation);\n }"
] | [
"int cancel(int downloadId) {\n\t\tsynchronized (mCurrentRequests) {\n\t\t\tfor (DownloadRequest request : mCurrentRequests) {\n\t\t\t\tif (request.getDownloadId() == downloadId) {\n\t\t\t\t\trequest.cancel();\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn 0;\n\t}",
"@RequestMapping(value = \"api/edit/disable\", method = RequestMethod.POST)\n public\n @ResponseBody\n String disableResponses(Model model, int path_id, @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n OverrideService.getInstance().disableAllOverrides(path_id, clientUUID);\n //TODO also need to disable custom override if there is one of those\n editService.removeCustomOverride(path_id, clientUUID);\n\n return null;\n }",
"public static pqbinding[] get(nitro_service service, pqbinding_args args) throws Exception{\n\t\tpqbinding obj = new pqbinding();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tpqbinding[] response = (pqbinding[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"private List<String> parseParams(String param) {\n\t\tAssert.hasText(param, \"param must not be empty nor null\");\n\t\tList<String> paramsToUse = new ArrayList<>();\n\t\tMatcher regexMatcher = DEPLOYMENT_PARAMS_PATTERN.matcher(param);\n\t\tint start = 0;\n\t\twhile (regexMatcher.find()) {\n\t\t\tString p = removeQuoting(param.substring(start, regexMatcher.start()).trim());\n\t\t\tif (StringUtils.hasText(p)) {\n\t\t\t\tparamsToUse.add(p);\n\t\t\t}\n\t\t\tstart = regexMatcher.start();\n\t\t}\n\t\tif (param != null && param.length() > 0) {\n\t\t\tString p = removeQuoting(param.substring(start, param.length()).trim());\n\t\t\tif (StringUtils.hasText(p)) {\n\t\t\t\tparamsToUse.add(p);\n\t\t\t}\n\t\t}\n\t\treturn paramsToUse;\n\t}",
"synchronized ArrayList<CTMessageDAO> getMessages(String userId){\n final String tName = Table.INBOX_MESSAGES.getName();\n Cursor cursor;\n ArrayList<CTMessageDAO> messageDAOArrayList = new ArrayList<>();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n cursor= db.rawQuery(\"SELECT * FROM \"+tName+\" WHERE \" + USER_ID + \" = ? ORDER BY \" + KEY_CREATED_AT+ \" DESC\", new String[]{userId});\n if(cursor != null) {\n while(cursor.moveToNext()){\n CTMessageDAO ctMessageDAO = new CTMessageDAO();\n ctMessageDAO.setId(cursor.getString(cursor.getColumnIndex(_ID)));\n ctMessageDAO.setJsonData(new JSONObject(cursor.getString(cursor.getColumnIndex(KEY_DATA))));\n ctMessageDAO.setWzrkParams(new JSONObject(cursor.getString(cursor.getColumnIndex(WZRKPARAMS))));\n ctMessageDAO.setDate(cursor.getLong(cursor.getColumnIndex(KEY_CREATED_AT)));\n ctMessageDAO.setExpires(cursor.getLong(cursor.getColumnIndex(EXPIRES)));\n ctMessageDAO.setRead(cursor.getInt(cursor.getColumnIndex(IS_READ)));\n ctMessageDAO.setUserId(cursor.getString(cursor.getColumnIndex(USER_ID)));\n ctMessageDAO.setTags(cursor.getString(cursor.getColumnIndex(TAGS)));\n ctMessageDAO.setCampaignId(cursor.getString(cursor.getColumnIndex(CAMPAIGN)));\n messageDAOArrayList.add(ctMessageDAO);\n }\n cursor.close();\n }\n return messageDAOArrayList;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e);\n return null;\n } catch (JSONException e) {\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e.getMessage());\n return null;\n } finally {\n dbHelper.close();\n }\n }",
"private static TransportType map2TransportType(String transportId) {\n TransportType type;\n if (CXF_HTTP_TRANSPORT_ID.equals(transportId) || SOAP_HTTP_TRANSPORT_ID.equals(transportId)) {\n type = TransportType.HTTP;\n } else {\n type = TransportType.OTHER;\n }\n return type;\n }",
"public ApnsServiceBuilder withSocksProxy(String host, int port) {\n Proxy proxy = new Proxy(Proxy.Type.SOCKS,\n new InetSocketAddress(host, port));\n return withProxy(proxy);\n }",
"public static int getDayAsReadableInt(Calendar calendar) {\n int day = calendar.get(Calendar.DAY_OF_MONTH);\n int month = calendar.get(Calendar.MONTH) + 1;\n int year = calendar.get(Calendar.YEAR);\n return year * 10000 + month * 100 + day;\n }",
"public static Collection<Component> getComponentsList() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.components.values();\n }"
] |
Resets the handler data to a basic state. | [
"@Override\r\n public void close() {\r\n // Use monitor to avoid race between external close and handler thread run()\r\n synchronized (closeMonitor) {\r\n // Close and clear streams, sockets etc.\r\n if (socket != null) {\r\n try {\r\n // Terminates thread blocking on socket read\r\n // and automatically closed depending streams\r\n socket.close();\r\n } catch (IOException e) {\r\n log.warn(\"Can not close socket\", e);\r\n } finally {\r\n socket = null;\r\n }\r\n }\r\n\r\n // Clear user data\r\n session = null;\r\n response = null;\r\n }\r\n }"
] | [
"public void rename(String newName) {\n URL url = FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject updateInfo = new JsonObject();\n updateInfo.add(\"name\", newName);\n\n request.setBody(updateInfo.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n response.getJSON();\n }",
"public static HazardCurve createHazardCurveFromSurvivalProbabilities(String name, double[] times, double[] givenSurvivalProbabilities){\n\t\tHazardCurve survivalProbabilities = new HazardCurve(name);\n\n\t\tfor(int timeIndex=0; timeIndex<times.length;timeIndex++) {\n\t\t\tsurvivalProbabilities.addSurvivalProbability(times[timeIndex], givenSurvivalProbabilities[timeIndex], times[timeIndex] > 0);\n\t\t}\n\n\t\treturn survivalProbabilities;\n\t}",
"static Shell createTerminalConsoleShell(String prompt, String appName,\n ShellCommandHandler mainHandler, InputStream input, OutputStream output) {\n try {\n PrintStream out = new PrintStream(output);\n\n // Build jline terminal\n jline.Terminal term = TerminalFactory.get();\n final ConsoleReader console = new ConsoleReader(input, output, term);\n console.setBellEnabled(true);\n console.setHistoryEnabled(true);\n\n // Build console\n BufferedReader in = new BufferedReader(new InputStreamReader(\n new ConsoleReaderInputStream(console)));\n\n ConsoleIO.PromptListener promptListener = new ConsoleIO.PromptListener() {\n @Override\n public boolean onPrompt(String prompt) {\n console.setPrompt(prompt);\n return true; // suppress normal prompt\n }\n };\n\n return createConsoleShell(prompt, appName, mainHandler, in, out, out, promptListener);\n } catch (Exception e) {\n // Failover: use default shell\n BufferedReader in = new BufferedReader(new InputStreamReader(input));\n PrintStream out = new PrintStream(output);\n\n return createConsoleShell(prompt, appName, mainHandler, in, out, out, null);\n }\n }",
"public InetSocketAddress getMulticastSocketAddress() {\n if (multicastAddress == null) {\n throw MESSAGES.noMulticastBinding(name);\n }\n return new InetSocketAddress(multicastAddress, multicastPort);\n }",
"public static Optimizer<DifferentiableFunction> getRegularizedOptimizer(final Optimizer<DifferentiableFunction> opt,\n final double l1Lambda, final double l2Lambda) {\n if (l1Lambda == 0 && l2Lambda == 0) {\n return opt;\n }\n return new Optimizer<DifferentiableFunction>() {\n \n @Override\n public boolean minimize(DifferentiableFunction objective, IntDoubleVector point) {\n DifferentiableFunction fn = getRegularizedFn(objective, false, l1Lambda, l2Lambda);\n return opt.minimize(fn, point);\n }\n \n };\n }",
"public double getValueWithGivenSpreadOverCurve(double evaluationTime,Curve referenceCurve, double spread, AnalyticModel model) {\n\t\tdouble value=0;\n\t\tfor(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods();periodIndex++) {\n\t\t\tdouble paymentDate\t= schedule.getPayment(periodIndex);\n\t\t\tvalue+= paymentDate>evaluationTime ? getCouponPayment(periodIndex,model)*Math.exp(-spread*paymentDate)*referenceCurve.getValue(paymentDate): 0.0;\n\t\t}\n\n\t\tdouble paymentDate\t= schedule.getPayment(schedule.getNumberOfPeriods()-1);\n\t\treturn paymentDate>evaluationTime ? value+Math.exp(-spread*paymentDate)*referenceCurve.getValue(paymentDate):0.0;\n\t}",
"private void processCalendarException(ProjectCalendar calendar, Row row)\n {\n Date fromDate = row.getDate(\"CD_FROM_DATE\");\n Date toDate = row.getDate(\"CD_TO_DATE\");\n boolean working = row.getInt(\"CD_WORKING\") != 0;\n ProjectCalendarException exception = calendar.addCalendarException(fromDate, toDate);\n if (working)\n {\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME1\"), row.getDate(\"CD_TO_TIME1\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME2\"), row.getDate(\"CD_TO_TIME2\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME3\"), row.getDate(\"CD_TO_TIME3\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME4\"), row.getDate(\"CD_TO_TIME4\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME5\"), row.getDate(\"CD_TO_TIME5\")));\n }\n }",
"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 void editCoords(String photoId, String userId, Rectangle bounds) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_COORDS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"user_id\", userId);\r\n parameters.put(\"person_x\", bounds.x);\r\n parameters.put(\"person_y\", bounds.y);\r\n parameters.put(\"person_w\", bounds.width);\r\n parameters.put(\"person_h\", bounds.height);\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 }"
] |
Return a product descriptor for a specific strike.
@param referenceDate The reference date (translating the maturity floating point date to dates.
@param index The index corresponding to the strike grid.
@return a product descriptor for a specific strike.
@throws ArrayIndexOutOfBoundsException Thrown if index is out of bound. | [
"public SingleAssetEuropeanOptionProductDescriptor getDescriptor(LocalDate referenceDate, int index) throws ArrayIndexOutOfBoundsException{\n\t\tLocalDate maturityDate = FloatingpointDate.getDateFromFloatingPointDate(referenceDate, maturity);\n\t\tif(index >= strikes.length) {\n\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Strike index out of bounds\");\n\t\t}else {\n\t\t\treturn new SingleAssetEuropeanOptionProductDescriptor(underlyingName, maturityDate, strikes[index]);\n\t\t}\n\t}"
] | [
"public static void configure(Job conf, SimpleConfiguration props) {\n try {\n\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n props.save(baos);\n\n conf.getConfiguration().set(PROPS_CONF_KEY,\n new String(baos.toByteArray(), StandardCharsets.UTF_8));\n\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"protected void processStop(Endpoint endpoint, EventTypeEnum eventType) {\n if (!sendLifecycleEvent) {\n return;\n }\n\n Event event = createEvent(endpoint, eventType);\n monitoringServiceClient.putEvents(Collections.singletonList(event));\n if (LOG.isLoggable(Level.INFO)) {\n LOG.info(\"Send \" + eventType + \" event to SAM Server successful!\");\n }\n }",
"public static int compare(Integer n1, Integer n2)\n {\n int result;\n if (n1 == null || n2 == null)\n {\n result = (n1 == null && n2 == null ? 0 : (n1 == null ? 1 : -1));\n }\n else\n {\n result = n1.compareTo(n2);\n }\n return (result);\n }",
"public boolean isActive(int profileId) {\n boolean active = false;\n PreparedStatement queryStatement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.CLIENT_IS_ACTIVE + \" FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= '-1' \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ? \"\n );\n queryStatement.setInt(1, profileId);\n logger.info(queryStatement.toString());\n ResultSet results = queryStatement.executeQuery();\n if (results.next()) {\n active = results.getBoolean(Constants.CLIENT_IS_ACTIVE);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return active;\n }",
"private void connect() throws IOException, GeneralSecurityException {\n synchronized (closedSync) {\n if (socket == null || socket.isClosed()) {\n SSLContext sc = SSLContext.getInstance(\"SSL\");\n sc.init(null, new TrustManager[] { new X509TrustAllManager() }, new SecureRandom());\n socket = sc.getSocketFactory().createSocket();\n socket.connect(address);\n }\n /**\n * Authenticate\n */\n CastChannel.DeviceAuthMessage authMessage = CastChannel.DeviceAuthMessage.newBuilder()\n .setChallenge(CastChannel.AuthChallenge.newBuilder().build())\n .build();\n\n CastChannel.CastMessage msg = CastChannel.CastMessage.newBuilder()\n .setDestinationId(DEFAULT_RECEIVER_ID)\n .setNamespace(\"urn:x-cast:com.google.cast.tp.deviceauth\")\n .setPayloadType(CastChannel.CastMessage.PayloadType.BINARY)\n .setProtocolVersion(CastChannel.CastMessage.ProtocolVersion.CASTV2_1_0)\n .setSourceId(name)\n .setPayloadBinary(authMessage.toByteString())\n .build();\n\n write(msg);\n CastChannel.CastMessage response = read();\n CastChannel.DeviceAuthMessage authResponse = CastChannel.DeviceAuthMessage.parseFrom(response.getPayloadBinary());\n if (authResponse.hasError()) {\n throw new ChromeCastException(\"Authentication failed: \" + authResponse.getError().getErrorType().toString());\n }\n\n /**\n * Send 'PING' message\n */\n PingThread pingThread = new PingThread();\n pingThread.run();\n\n /**\n * Send 'CONNECT' message to start session\n */\n write(\"urn:x-cast:com.google.cast.tp.connection\", StandardMessage.connect(), DEFAULT_RECEIVER_ID);\n\n /**\n * Start ping/pong and reader thread\n */\n pingTimer = new Timer(name + \" PING\");\n pingTimer.schedule(pingThread, 1000, PING_PERIOD);\n\n reader = new ReadThread();\n reader.start();\n\n if (closed) {\n closed = false;\n notifyListenerOfConnectionEvent(true);\n }\n }\n }",
"public DiscreteInterval minus(DiscreteInterval other) {\n return new DiscreteInterval(this.min - other.max, this.max - other.min);\n }",
"public static boolean isSymmetric( DMatrixSparseCSC A , double tol ) {\n if( A.numRows != A.numCols )\n return false;\n\n int N = A.numCols;\n\n for (int i = 0; i < N; i++) {\n int idx0 = A.col_idx[i];\n int idx1 = A.col_idx[i+1];\n\n for (int index = idx0; index < idx1; index++) {\n int j = A.nz_rows[index];\n double value_ji = A.nz_values[index];\n double value_ij = A.get(i,j);\n\n if( Math.abs(value_ij-value_ji) > tol )\n return false;\n }\n }\n\n return true;\n }",
"private YearWeek with(int newYear, int newWeek) {\n if (year == newYear && week == newWeek) {\n return this;\n }\n return of(newYear, newWeek);\n }",
"public static WebDriverBackedEmbeddedBrowser withDriver(WebDriver driver,\n\t\t\tImmutableSortedSet<String> filterAttributes, long crawlWaitEvent,\n\t\t\tlong crawlWaitReload) {\n\t\treturn new WebDriverBackedEmbeddedBrowser(driver, filterAttributes, crawlWaitEvent,\n\t\t\t\tcrawlWaitReload);\n\t}"
] |
don't run on main thread | [
"@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 static ServiceActivator create(final ModelNode endpointConfig, final URI managementURI, final String serverName, final String serverProcessName,\n final String authKey, final boolean managementSubsystemEndpoint, final Supplier<SSLContext> sslContextSupplier) {\n\n return new DomainServerCommunicationServices(endpointConfig, managementURI, serverName, serverProcessName, authKey, managementSubsystemEndpoint, sslContextSupplier);\n }",
"public void init(LblTree t1, LblTree t2) {\n\t\tLabelDictionary ld = new LabelDictionary();\n\t\tit1 = new InfoTree(t1, ld);\n\t\tit2 = new InfoTree(t2, ld);\n\t\tsize1 = it1.getSize();\n\t\tsize2 = it2.getSize();\n\t\tIJ = new int[Math.max(size1, size2)][Math.max(size1, size2)];\n\t\tdelta = new double[size1][size2];\n\t\tdeltaBit = new byte[size1][size2];\n\t\tcostV = new long[3][size1][size2];\n\t\tcostW = new long[3][size2];\n\n\t\t// Calculate delta between every leaf in G (empty tree) and all the nodes in F.\n\t\t// Calculate it both sides: leafs of F and nodes of G & leafs of G and nodes of\n\t\t// F.\n\t\tint[] labels1 = it1.getInfoArray(POST2_LABEL);\n\t\tint[] labels2 = it2.getInfoArray(POST2_LABEL);\n\t\tint[] sizes1 = it1.getInfoArray(POST2_SIZE);\n\t\tint[] sizes2 = it2.getInfoArray(POST2_SIZE);\n\t\tfor (int x = 0; x < sizes1.length; x++) { // for all nodes of initially left tree\n\t\t\tfor (int y = 0; y < sizes2.length; y++) { // for all nodes of initially right tree\n\n\t\t\t\t// This is an attempt for distances of single-node subtree and anything alse\n\t\t\t\t// The differences between pairs of labels are stored\n\t\t\t\tif (labels1[x] == labels2[y]) {\n\t\t\t\t\tdeltaBit[x][y] = 0;\n\t\t\t\t} else {\n\t\t\t\t\tdeltaBit[x][y] =\n\t\t\t\t\t\t\t1; // if this set, the labels differ, cost of relabeling is set\n\t\t\t\t\t// to costMatch\n\t\t\t\t}\n\n\t\t\t\tif (sizes1[x] == 1 && sizes2[y] == 1) { // both nodes are leafs\n\t\t\t\t\tdelta[x][y] = 0;\n\t\t\t\t} else {\n\t\t\t\t\tif (sizes1[x] == 1) {\n\t\t\t\t\t\tdelta[x][y] = sizes2[y] - 1;\n\t\t\t\t\t}\n\t\t\t\t\tif (sizes2[y] == 1) {\n\t\t\t\t\t\tdelta[x][y] = sizes1[x] - 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public static byte[] decodeBase64(String value) {\n int byteShift = 4;\n int tmp = 0;\n boolean done = false;\n final StringBuilder buffer = new StringBuilder();\n\n for (int i = 0; i != value.length(); i++) {\n final char c = value.charAt(i);\n final int sixBit = (c < 123) ? EncodingGroovyMethodsSupport.TRANSLATE_TABLE[c] : 66;\n\n if (sixBit < 64) {\n if (done)\n throw new RuntimeException(\"= character not at end of base64 value\"); // TODO: change this exception type\n\n tmp = (tmp << 6) | sixBit;\n\n if (byteShift-- != 4) {\n buffer.append((char) ((tmp >> (byteShift * 2)) & 0XFF));\n }\n\n } else if (sixBit == 64) {\n\n byteShift--;\n done = true;\n\n } else if (sixBit == 66) {\n // RFC 2045 says that I'm allowed to take the presence of\n // these characters as evidence of data corruption\n // So I will\n throw new RuntimeException(\"bad character in base64 value\"); // TODO: change this exception type\n }\n\n if (byteShift == 0) byteShift = 4;\n }\n\n try {\n return buffer.toString().getBytes(\"ISO-8859-1\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"Base 64 decode produced byte values > 255\"); // TODO: change this exception type\n }\n }",
"protected ValueContainer[] getNonKeyValues(PersistenceBroker broker, ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getNonKeyRwValues(cld, obj);\r\n }",
"private Query getQueryBySqlCount(QueryBySQL aQuery)\r\n {\r\n String countSql = aQuery.getSql();\r\n\r\n int fromPos = countSql.toUpperCase().indexOf(\" FROM \");\r\n if(fromPos >= 0)\r\n {\r\n countSql = \"select count(*)\" + countSql.substring(fromPos);\r\n }\r\n\r\n int orderPos = countSql.toUpperCase().indexOf(\" ORDER BY \");\r\n if(orderPos >= 0)\r\n {\r\n countSql = countSql.substring(0, orderPos);\r\n }\r\n\r\n return new QueryBySQL(aQuery.getSearchClass(), countSql);\r\n }",
"public double getValueAsPrice(double evaluationTime, AnalyticModel model) {\n\t\tForwardCurve\tforwardCurve\t= model.getForwardCurve(forwardCurveName);\n\t\tDiscountCurve\tdiscountCurve\t= model.getDiscountCurve(discountCurveName);\n\n\t\tDiscountCurve\tdiscountCurveForForward = null;\n\t\tif(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {\n\t\t\t// User might like to get forward from discount curve.\n\t\t\tdiscountCurveForForward\t= model.getDiscountCurve(forwardCurveName);\n\n\t\t\tif(discountCurveForForward == null) {\n\t\t\t\t// User specified a name for the forward curve, but no curve was found.\n\t\t\t\tthrow new IllegalArgumentException(\"No curve of the name \" + forwardCurveName + \" was found in the model.\");\n\t\t\t}\n\t\t}\n\n\t\tdouble value = 0.0;\n\t\tfor(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) {\n\t\t\tdouble fixingDate\t= schedule.getFixing(periodIndex);\n\t\t\tdouble paymentDate\t= schedule.getPayment(periodIndex);\n\t\t\tdouble periodLength\t= schedule.getPeriodLength(periodIndex);\n\n\t\t\t/*\n\t\t\t * We do not count empty periods.\n\t\t\t * Since empty periods are an indication for a ill-specified product,\n\t\t\t * it might be reasonable to throw an illegal argument exception instead.\n\t\t\t */\n\t\t\tif(periodLength == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tdouble forward = 0.0;\n\t\t\tif(forwardCurve != null) {\n\t\t\t\tforward\t\t\t+= forwardCurve.getForward(model, fixingDate, paymentDate-fixingDate);\n\t\t\t}\n\t\t\telse if(discountCurveForForward != null) {\n\t\t\t\t/*\n\t\t\t\t * Classical single curve case: using a discount curve as a forward curve.\n\t\t\t\t * This is only implemented for demonstration purposes (an exception would also be appropriate :-)\n\t\t\t\t */\n\t\t\t\tif(fixingDate != paymentDate) {\n\t\t\t\t\tforward\t\t\t+= (discountCurveForForward.getDiscountFactor(fixingDate) / discountCurveForForward.getDiscountFactor(paymentDate) - 1.0) / (paymentDate-fixingDate);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdouble discountFactor\t= paymentDate > evaluationTime ? discountCurve.getDiscountFactor(model, paymentDate) : 0.0;\n\t\t\tdouble payoffUnit = discountFactor * periodLength;\n\n\t\t\tdouble effektiveStrike = strike;\n\t\t\tif(isStrikeMoneyness) {\n\t\t\t\teffektiveStrike += getATMForward(model, true);\n\t\t\t}\n\n\t\t\tVolatilitySurface volatilitySurface\t= model.getVolatilitySurface(volatiltiySufaceName);\n\t\t\tif(volatilitySurface == null) {\n\t\t\t\tthrow new IllegalArgumentException(\"Volatility surface not found in model: \" + volatiltiySufaceName);\n\t\t\t}\n\t\t\tif(volatilitySurface.getQuotingConvention() == QuotingConvention.VOLATILITYLOGNORMAL) {\n\t\t\t\tdouble volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYLOGNORMAL);\n\t\t\t\tvalue += AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Default to normal volatility as quoting convention\n\t\t\t\tdouble volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYNORMAL);\n\t\t\t\tvalue += AnalyticFormulas.bachelierOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit);\n\t\t\t}\n\t\t}\n\n\t\treturn value / discountCurve.getDiscountFactor(model, evaluationTime);\n\t}",
"private void tryToSetParsedValue(String value) throws Exception {\n\n JSONObject json = JSONParser.parseStrict(value).isObject();\n JSONValue val = json.get(JsonKey.START);\n setStart(readOptionalDate(val));\n val = json.get(JsonKey.END);\n setEnd(readOptionalDate(val));\n setWholeDay(readOptionalBoolean(json.get(JsonKey.WHOLE_DAY)));\n JSONObject patternJson = json.get(JsonKey.PATTERN).isObject();\n readPattern(patternJson);\n setExceptions(readDates(json.get(JsonKey.EXCEPTIONS)));\n setSeriesEndDate(readOptionalDate(json.get(JsonKey.SERIES_ENDDATE)));\n setOccurrences(readOptionalInt(json.get(JsonKey.SERIES_OCCURRENCES)));\n setDerivedEndType();\n setCurrentTillEnd(readOptionalBoolean(json.get(JsonKey.CURRENT_TILL_END)));\n setParentSeriesId(readOptionalUUID(json.get(JsonKey.PARENT_SERIES)));\n\n }",
"public void modified(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {\n declarationBinders.get(declarationBinderRef).update(declarationBinderRef);\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 }"
] |
Computes the eigenvalue of the 2 by 2 matrix. | [
"protected void eigenvalue2by2( int x1 ) {\n double a = diag[x1];\n double b = off[x1];\n double c = diag[x1+1];\n\n // normalize to reduce overflow\n double absA = Math.abs(a);\n double absB = Math.abs(b);\n double absC = Math.abs(c);\n\n double scale = absA > absB ? absA : absB;\n if( absC > scale ) scale = absC;\n\n // see if it is a pathological case. the diagonal must already be zero\n // and the eigenvalues are all zero. so just return\n if( scale == 0 ) {\n off[x1] = 0;\n diag[x1] = 0;\n diag[x1+1] = 0;\n return;\n }\n\n a /= scale;\n b /= scale;\n c /= scale;\n\n eigenSmall.symm2x2_fast(a,b,c);\n\n off[x1] = 0;\n diag[x1] = scale*eigenSmall.value0.real;\n diag[x1+1] = scale*eigenSmall.value1.real;\n }"
] | [
"public static DMatrix2 extractColumn( DMatrix2x2 a , int column , DMatrix2 out ) {\n if( out == null) out = new DMatrix2();\n switch( column ) {\n case 0:\n out.a1 = a.a11;\n out.a2 = a.a21;\n break;\n case 1:\n out.a1 = a.a12;\n out.a2 = a.a22;\n break;\n default:\n throw new IllegalArgumentException(\"Out of bounds column. column = \"+column);\n }\n return out;\n }",
"public static String createLabel(final double value, final String unit, final GridLabelFormat format) {\n final double zero = 0.000000001;\n if (format != null) {\n return format.format(value, unit);\n } else {\n if (Math.abs(value - Math.round(value)) < zero) {\n return String.format(\"%d %s\", Math.round(value), unit);\n } else if (\"m\".equals(unit)) {\n // meter: no decimals\n return String.format(\"%1.0f %s\", value, unit);\n } else if (NonSI.DEGREE_ANGLE.toString().equals(unit)) {\n // degree: by default 6 decimals\n return String.format(\"%1.6f %s\", value, unit);\n } else {\n return String.format(\"%f %s\", value, unit);\n }\n }\n }",
"public CollectionRequest<Team> findByUser(String user) {\n \n String path = String.format(\"/users/%s/teams\", user);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }",
"public void ifMemberTagValueEquals(String template, Properties attributes) throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n if (isTagValueEqual(attributes, FOR_FIELD)) {\r\n generate(template);\r\n }\r\n }\r\n else if (getCurrentMethod() != null) {\r\n if (isTagValueEqual(attributes, FOR_METHOD)) {\r\n generate(template);\r\n }\r\n }\r\n }",
"private PersistenceBrokerException createException(final Exception ex, String message, final Object objectToIdentify, Class topLevelClass, Class realClass, Object[] pks)\r\n {\r\n final String eol = SystemUtils.LINE_SEPARATOR;\r\n StringBuffer msg = new StringBuffer();\r\n if(message == null)\r\n {\r\n msg.append(\"Unexpected error: \");\r\n }\r\n else\r\n {\r\n msg.append(message).append(\" :\");\r\n }\r\n if(topLevelClass != null) msg.append(eol).append(\"objectTopLevelClass=\").append(topLevelClass.getName());\r\n if(realClass != null) msg.append(eol).append(\"objectRealClass=\").append(realClass.getName());\r\n if(pks != null) msg.append(eol).append(\"pkValues=\").append(ArrayUtils.toString(pks));\r\n if(objectToIdentify != null) msg.append(eol).append(\"object to identify: \").append(objectToIdentify);\r\n if(ex != null)\r\n {\r\n // add causing stack trace\r\n Throwable rootCause = ExceptionUtils.getRootCause(ex);\r\n if(rootCause != null)\r\n {\r\n msg.append(eol).append(\"The root stack trace is --> \");\r\n String rootStack = ExceptionUtils.getStackTrace(rootCause);\r\n msg.append(eol).append(rootStack);\r\n }\r\n\r\n return new PersistenceBrokerException(msg.toString(), ex);\r\n }\r\n else\r\n {\r\n return new PersistenceBrokerException(msg.toString());\r\n }\r\n }",
"public void addColumnPair(String localColumn, String remoteColumn)\r\n {\r\n if (!_localColumns.contains(localColumn))\r\n { \r\n _localColumns.add(localColumn);\r\n }\r\n if (!_remoteColumns.contains(remoteColumn))\r\n { \r\n _remoteColumns.add(remoteColumn);\r\n }\r\n }",
"void setPatternDefaultValues(Date startDate) {\r\n\r\n if ((m_patternDefaultValues == null) || !Objects.equals(m_patternDefaultValues.getDate(), startDate)) {\r\n m_patternDefaultValues = new PatternDefaultValues(startDate);\r\n }\r\n }",
"public static MBeanParameterInfo[] extractParameterInfo(Method m) {\n Class<?>[] types = m.getParameterTypes();\n Annotation[][] annotations = m.getParameterAnnotations();\n MBeanParameterInfo[] params = new MBeanParameterInfo[types.length];\n for(int i = 0; i < params.length; i++) {\n boolean hasAnnotation = false;\n for(int j = 0; j < annotations[i].length; j++) {\n if(annotations[i][j] instanceof JmxParam) {\n JmxParam param = (JmxParam) annotations[i][j];\n params[i] = new MBeanParameterInfo(param.name(),\n types[i].getName(),\n param.description());\n hasAnnotation = true;\n break;\n }\n }\n if(!hasAnnotation) {\n params[i] = new MBeanParameterInfo(\"\", types[i].getName(), \"\");\n }\n }\n\n return params;\n }",
"@SuppressWarnings(\"UnusedDeclaration\")\n public void init() throws Exception {\n initBuilderSpecific();\n resetFields();\n if (!UserPluginInfo.NO_PLUGIN_KEY.equals(getSelectedStagingPluginName())) {\n PluginSettings selectedStagingPluginSettings = getSelectedStagingPlugin();\n try {\n stagingStrategy = getArtifactoryServer().getStagingStrategy(selectedStagingPluginSettings, Util.rawEncode(project.getName()), project);\n } catch (Exception e) {\n log.log(Level.WARNING, \"Failed to obtain staging strategy: \" + e.getMessage(), e);\n strategyRequestFailed = true;\n strategyRequestErrorMessage = \"Failed to obtain staging strategy '\" +\n selectedStagingPluginSettings.getPluginName() + \"': \" + e.getMessage() +\n \".\\nPlease review the log for further information.\";\n stagingStrategy = null;\n }\n strategyPluginExists = (stagingStrategy != null) && !stagingStrategy.isEmpty();\n }\n\n prepareDefaultVersioning();\n prepareDefaultGlobalModule();\n prepareDefaultModules();\n prepareDefaultVcsSettings();\n prepareDefaultPromotionConfig();\n }"
] |
Adds special accessors for private constants so that inner classes can retrieve them. | [
"@SuppressWarnings(\"unchecked\")\n private void addPrivateFieldsAccessors(ClassNode node) {\n Set<ASTNode> accessedFields = (Set<ASTNode>) node.getNodeMetaData(StaticTypesMarker.PV_FIELDS_ACCESS);\n if (accessedFields==null) return;\n Map<String, MethodNode> privateConstantAccessors = (Map<String, MethodNode>) node.getNodeMetaData(PRIVATE_FIELDS_ACCESSORS);\n if (privateConstantAccessors!=null) {\n // already added\n return;\n }\n int acc = -1;\n privateConstantAccessors = new HashMap<String, MethodNode>();\n final int access = Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC;\n for (FieldNode fieldNode : node.getFields()) {\n if (accessedFields.contains(fieldNode)) {\n\n acc++;\n Parameter param = new Parameter(node.getPlainNodeReference(), \"$that\");\n Expression receiver = fieldNode.isStatic()?new ClassExpression(node):new VariableExpression(param);\n Statement stmt = new ExpressionStatement(new PropertyExpression(\n receiver,\n fieldNode.getName()\n ));\n MethodNode accessor = node.addMethod(\"pfaccess$\"+acc, access, fieldNode.getOriginType(), new Parameter[]{param}, ClassNode.EMPTY_ARRAY, stmt);\n privateConstantAccessors.put(fieldNode.getName(), accessor);\n }\n }\n node.setNodeMetaData(PRIVATE_FIELDS_ACCESSORS, privateConstantAccessors);\n }"
] | [
"public void writeAnswers(List<IN> doc, PrintWriter printWriter,\r\n DocumentReaderAndWriter<IN> readerAndWriter)\r\n throws IOException {\r\n if (flags.lowerNewgeneThreshold) {\r\n return;\r\n }\r\n if (flags.numRuns <= 1) {\r\n readerAndWriter.printAnswers(doc, printWriter);\r\n // out.println();\r\n printWriter.flush();\r\n }\r\n }",
"public String addPostRunDependent(FunctionalTaskItem dependent) {\n Objects.requireNonNull(dependent);\n return this.taskGroup().addPostRunDependent(dependent);\n }",
"public Object getColumnValue(String columnName) {\n\t\tfor ( int j = 0; j < columnNames.length; j++ ) {\n\t\t\tif ( columnNames[j].equals( columnName ) ) {\n\t\t\t\treturn columnValues[j];\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public AwsServiceClient withCodecRegistry(@Nonnull final CodecRegistry codecRegistry) {\n return new AwsServiceClientImpl(proxy.withCodecRegistry(codecRegistry), dispatcher);\n }",
"public static ForwardCurveInterpolation createForwardCurveFromDiscountFactors(String name, double[] times, RandomVariable[] givenDiscountFactors, double paymentOffset) {\n\t\tForwardCurveInterpolation forwardCurveInterpolation = new ForwardCurveInterpolation(name, paymentOffset, InterpolationEntityForward.FORWARD, null);\n\n\t\tif(times.length == 0) {\n\t\t\tthrow new IllegalArgumentException(\"Vector of times must not be empty.\");\n\t\t}\n\n\t\tif(times[0] > 0) {\n\t\t\t// Add first forward\n\t\t\tRandomVariable forward = givenDiscountFactors[0].sub(1.0).pow(-1.0).div(times[0]);\n\t\t\tforwardCurveInterpolation.addForward(null, 0.0, forward, true);\n\t\t}\n\n\t\tfor(int timeIndex=0; timeIndex<times.length-1;timeIndex++) {\n\t\t\tRandomVariable \tforward\t\t= givenDiscountFactors[timeIndex].div(givenDiscountFactors[timeIndex+1].sub(1.0)).div(times[timeIndex+1] - times[timeIndex]);\n\t\t\tdouble\tfixingTime\t= times[timeIndex];\n\t\t\tboolean\tisParameter\t= (fixingTime > 0);\n\t\t\tforwardCurveInterpolation.addForward(null, fixingTime, forward, isParameter);\n\t\t}\n\n\t\treturn forwardCurveInterpolation;\n\t}",
"public long removeRangeByLex(final LexRange lexRange) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.zremrangeByLex(getKey(), lexRange.from(), lexRange.to());\n }\n });\n }",
"public Indexes listIndexes() {\n URI uri = new DatabaseURIHelper(db.getDBUri()).path(\"_index\").build();\n return client.couchDbClient.get(uri, Indexes.class);\n }",
"private Duration getAssignmentWork(ProjectCalendar calendar, TimephasedWork assignment)\n {\n Date assignmentStart = assignment.getStart();\n\n Date splitStart = assignmentStart;\n Date splitFinishTime = calendar.getFinishTime(splitStart);\n Date splitFinish = DateHelper.setTime(splitStart, splitFinishTime);\n\n Duration calendarSplitWork = calendar.getWork(splitStart, splitFinish, TimeUnit.MINUTES);\n Duration assignmentWorkPerDay = assignment.getAmountPerDay();\n Duration splitWork;\n\n double splitMinutes = assignmentWorkPerDay.getDuration();\n splitMinutes *= calendarSplitWork.getDuration();\n splitMinutes /= (8 * 60); // this appears to be a fixed value\n splitWork = Duration.getInstance(splitMinutes, TimeUnit.MINUTES);\n return splitWork;\n }",
"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 }"
] |
Attempts to locate the activity type value extracted from an existing P6 schedule.
If necessary converts to the form which can be used in the PMXML file.
Returns "Resource Dependent" as the default value.
@param task parent task
@return activity type | [
"private String extractAndConvertTaskType(Task task)\n {\n String activityType = (String) task.getCachedValue(m_activityTypeField);\n if (activityType == null)\n {\n activityType = \"Resource Dependent\";\n }\n else\n {\n if (ACTIVITY_TYPE_MAP.containsKey(activityType))\n {\n activityType = ACTIVITY_TYPE_MAP.get(activityType);\n }\n }\n return activityType;\n }"
] | [
"public String clean(String value) {\n String orig = value;\n \n // check if there's a + before the first digit\n boolean initialplus = findPlus(value);\n \n // remove everything but digits\n value = sub.clean(value);\n if (value == null)\n return null;\n\n // check for initial '00'\n boolean zerozero = !initialplus && value.startsWith(\"00\");\n if (zerozero)\n value = value.substring(2); // strip off the zeros\n\n // look for country code\n CountryCode ccode = findCountryCode(value);\n if (ccode == null) {\n // no country code, let's do what little we can\n if (initialplus || zerozero)\n return orig; // this number is messed up. dare not touch\n return value;\n\n } else {\n value = value.substring(ccode.getPrefix().length()); // strip off ccode\n if (ccode.getStripZero() && value.startsWith(\"0\"))\n value = value.substring(1); // strip the zero\n\n if (ccode.isRightFormat(value))\n return \"+\" + ccode.getPrefix() + \" \" + value;\n else\n return orig; // don't dare touch this\n }\n }",
"public static String defaultHtml(HttpServletRequest request) {\n\n CmsObject cms = CmsFlexController.getController(request).getCmsObject();\n\n // We only want the big red warning in Offline mode\n if (cms.getRequestContext().getCurrentProject().isOnlineProject()) {\n return \"<div><!--Dynamic function not configured--></div>\";\n } else {\n Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);\n String message = Messages.get().getBundle(locale).key(Messages.GUI_FUNCTION_DEFAULT_HTML_0);\n return \"<div style=\\\"border: 2px solid red; padding: 10px;\\\">\" + message + \"</div>\";\n }\n }",
"ArgumentsBuilder param(String param, Integer value) {\n if (value != null) {\n args.add(param);\n args.add(value.toString());\n }\n return this;\n }",
"public ChangesResult getChanges() {\n final URI uri = this.databaseHelper.changesUri(\"feed\", \"normal\");\n return client.get(uri, ChangesResult.class);\n }",
"public static <T> Observable<T> map(Observable<?> fromObservable, final T toValue) {\n if (fromObservable != null) {\n return fromObservable.subscribeOn(Schedulers.io())\n .map(new RXMapper<T>(toValue));\n } else {\n return Observable.empty();\n }\n }",
"public static String constructResourceId(\n final String subscriptionId,\n final String resourceGroupName,\n final String resourceProviderNamespace,\n final String resourceType,\n final String resourceName,\n final String parentResourcePath) {\n String prefixedParentPath = parentResourcePath;\n if (parentResourcePath != null && !parentResourcePath.isEmpty()) {\n prefixedParentPath = \"/\" + parentResourcePath;\n }\n return String.format(\n \"/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s\",\n subscriptionId,\n resourceGroupName,\n resourceProviderNamespace,\n prefixedParentPath,\n resourceType,\n resourceName);\n }",
"@Nullable\n private static Converter<List<String>, Object> createPrimitiveTypeConverter(final Class<?> resultClass) {\n Object defaultValue = defaultValue(resultClass);\n\n if (defaultValue == null) {\n // For primitive type, the default value shouldn't be null\n return null;\n }\n\n return new BasicConverter(defaultValue) {\n @Override\n protected Object convert(String value) throws Exception {\n return valueOf(value, resultClass);\n }\n };\n }",
"protected void writePropertiesToLog(Logger logger, Level level) {\n writeToLog(logger, level, getMapAsString(this.properties, separator), null);\n\n if (this.exception != null) {\n writeToLog(this.logger, Level.ERROR, \"Error:\", this.exception);\n }\n }",
"public static int getIbanLength(final CountryCode countryCode) {\n final BbanStructure structure = getBbanStructure(countryCode);\n return COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH + structure.getBbanLength();\n }"
] |
Find the number of Strings matched to the given Matcher.
@param matcher a Matcher
@return int the number of Strings matched to the given matcher.
@since 1.0 | [
"public static int getCount(Matcher matcher) {\n int counter = 0;\n matcher.reset();\n while (matcher.find()) {\n counter++;\n }\n return counter;\n }"
] | [
"@Override\n public final Job queueIn(final Job job, final long millis) {\n return pushAt(job, System.currentTimeMillis() + millis);\n }",
"public String createSessionForResource(String configPath, String fileName) throws CmsUgcException {\n\n CmsUgcSession formSession = CmsUgcSessionFactory.getInstance().createSessionForFile(\n getCmsObject(),\n getRequest(),\n configPath,\n fileName);\n return \"\" + formSession.getId();\n }",
"public static final String printExtendedAttributeCurrency(Number value)\n {\n return (value == null ? null : NUMBER_FORMAT.get().format(value.doubleValue() * 100));\n }",
"public void setRequestType(int pathId, Integer requestType) {\n if (requestType == null) {\n requestType = Constants.REQUEST_TYPE_GET;\n }\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_REQUEST_TYPE + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, requestType);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"protected synchronized void registerOpenDatabase(DatabaseImpl newDB)\r\n {\r\n DatabaseImpl old_db = getCurrentDatabase();\r\n if (old_db != null)\r\n {\r\n try\r\n {\r\n if (old_db.isOpen())\r\n {\r\n log.warn(\"## There is still an opened database, close old one ##\");\r\n old_db.close();\r\n }\r\n }\r\n catch (Throwable t)\r\n {\r\n //ignore\r\n }\r\n }\r\n if (log.isDebugEnabled()) log.debug(\"Set current database \" + newDB + \" PBKey was \" + newDB.getPBKey());\r\n setCurrentDatabase(newDB);\r\n// usedDatabases.add(newDB.getPBKey());\r\n }",
"public void init(Map<String, String> testConfig, Map<String, String> hiveVars) {\n\n context.init();\n\n HiveConf hiveConf = context.getHiveConf();\n\n // merge test case properties with hive conf before HiveServer is started.\n for (Map.Entry<String, String> property : testConfig.entrySet()) {\n hiveConf.set(property.getKey(), property.getValue());\n }\n\n try {\n hiveServer2 = new HiveServer2();\n hiveServer2.init(hiveConf);\n\n // Locate the ClIService in the HiveServer2\n for (Service service : hiveServer2.getServices()) {\n if (service instanceof CLIService) {\n client = (CLIService) service;\n }\n }\n\n Preconditions.checkNotNull(client, \"ClIService was not initialized by HiveServer2\");\n\n sessionHandle = client.openSession(\"noUser\", \"noPassword\", null);\n\n SessionState sessionState = client.getSessionManager().getSession(sessionHandle).getSessionState();\n currentSessionState = sessionState;\n currentSessionState.setHiveVariables(hiveVars);\n } catch (Exception e) {\n throw new IllegalStateException(\"Failed to create HiveServer :\" + e.getMessage(), e);\n }\n\n // Ping hive server before we do anything more with it! If validation\n // is switched on, this will fail if metastorage is not set up properly\n pingHiveServer();\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 static ServiceActivator create(final ModelNode endpointConfig, final URI managementURI, final String serverName, final String serverProcessName,\n final String authKey, final boolean managementSubsystemEndpoint, final Supplier<SSLContext> sslContextSupplier) {\n\n return new DomainServerCommunicationServices(endpointConfig, managementURI, serverName, serverProcessName, authKey, managementSubsystemEndpoint, sslContextSupplier);\n }",
"public static TagModel getSingleParent(TagModel tag)\n {\n final Iterator<TagModel> parents = tag.getDesignatedByTags().iterator();\n if (!parents.hasNext())\n throw new WindupException(\"Tag is not designated by any tags: \" + tag);\n\n final TagModel maybeOnlyParent = parents.next();\n\n if (parents.hasNext()) {\n StringBuilder sb = new StringBuilder();\n tag.getDesignatedByTags().iterator().forEachRemaining(x -> sb.append(x).append(\", \"));\n throw new WindupException(String.format(\"Tag %s is designated by multiple tags: %s\", tag, sb.toString()));\n }\n\n return maybeOnlyParent;\n }"
] |
Returns the header with the specified name from the supplied map. The
header lookup is case-insensitive.
@param headers A <code>Map</code> containing the HTTP request headers.
@param name The name of the header to return.
@return The value of specified header, or a comma-separated list if there
were multiple headers of that name. | [
"private final String getHeader(Map /* String, String */ headers, String name) {\n return (String) headers.get(name.toLowerCase());\n }"
] | [
"public void updateAnimation()\n {\n Date time = new Date();\n long currentTime = time.getTime() - this.beginAnimation;\n if (currentTime > animationTime)\n {\n this.currentQuaternion.set(endQuaternion);\n for (int i = 0; i < 3; i++)\n {\n\n this.currentPos[i] = this.endPos[i];\n }\n this.animate = false;\n }\n\n else\n {\n float t = (float) currentTime / animationTime;\n this.currentQuaternion = this.beginQuaternion.slerp(this.endQuaternion,\n t);\n for (int i = 0; i < 3; i++)\n {\n this.currentPos[i] = this.beginPos[i] + totalTranslation[i] * t;\n }\n\n }\n }",
"public static base_response unset(nitro_service client, systemcollectionparam resource, String[] args) throws Exception{\n\t\tsystemcollectionparam unsetresource = new systemcollectionparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"protected boolean isSlopDead(Cluster cluster, Set<String> storeNames, Slop slop) {\n // destination node , no longer exists\n if(!cluster.getNodeIds().contains(slop.getNodeId())) {\n return true;\n }\n\n // destination store, no longer exists\n if(!storeNames.contains(slop.getStoreName())) {\n return true;\n }\n\n // else. slop is alive\n return false;\n }",
"public String getPromotionDetailsJsonModel() throws IOException {\n final PromotionEvaluationReport sampleReport = new PromotionEvaluationReport();\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNPROMOTED_MSG, \"com.acme.secure-smh:core-relay:1.2.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.DO_NOT_USE_MSG, \"com.google.guava:guava:20.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.MISSING_LICENSE_MSG, \"org.apache.maven.wagon:wagon-webdav-jackrabbit:2.12\"), MINOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNACCEPTABLE_LICENSE_MSG,\n \"aopaliance:aopaliance:1.0 licensed as Attribution-ShareAlike 2.5 Generic, \" +\n \"org.polyjdbc:polyjdbc0.7.1 licensed as Creative Commons Attribution-ShareAlike 3.0 Unported License\"),\n MINOR);\n\n sampleReport.addMessage(PromotionReportTranslator.SNAPSHOT_VERSION_MSG, Tag.CRITICAL);\n return JsonUtils.serialize(sampleReport);\n }",
"public static base_response update(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup updateresource = new cachecontentgroup();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.weakposrelexpiry = resource.weakposrelexpiry;\n\t\tupdateresource.heurexpiryparam = resource.heurexpiryparam;\n\t\tupdateresource.relexpiry = resource.relexpiry;\n\t\tupdateresource.relexpirymillisec = resource.relexpirymillisec;\n\t\tupdateresource.absexpiry = resource.absexpiry;\n\t\tupdateresource.absexpirygmt = resource.absexpirygmt;\n\t\tupdateresource.weaknegrelexpiry = resource.weaknegrelexpiry;\n\t\tupdateresource.hitparams = resource.hitparams;\n\t\tupdateresource.invalparams = resource.invalparams;\n\t\tupdateresource.ignoreparamvaluecase = resource.ignoreparamvaluecase;\n\t\tupdateresource.matchcookies = resource.matchcookies;\n\t\tupdateresource.invalrestrictedtohost = resource.invalrestrictedtohost;\n\t\tupdateresource.polleverytime = resource.polleverytime;\n\t\tupdateresource.ignorereloadreq = resource.ignorereloadreq;\n\t\tupdateresource.removecookies = resource.removecookies;\n\t\tupdateresource.prefetch = resource.prefetch;\n\t\tupdateresource.prefetchperiod = resource.prefetchperiod;\n\t\tupdateresource.prefetchperiodmillisec = resource.prefetchperiodmillisec;\n\t\tupdateresource.prefetchmaxpending = resource.prefetchmaxpending;\n\t\tupdateresource.flashcache = resource.flashcache;\n\t\tupdateresource.expireatlastbyte = resource.expireatlastbyte;\n\t\tupdateresource.insertvia = resource.insertvia;\n\t\tupdateresource.insertage = resource.insertage;\n\t\tupdateresource.insertetag = resource.insertetag;\n\t\tupdateresource.cachecontrol = resource.cachecontrol;\n\t\tupdateresource.quickabortsize = resource.quickabortsize;\n\t\tupdateresource.minressize = resource.minressize;\n\t\tupdateresource.maxressize = resource.maxressize;\n\t\tupdateresource.memlimit = resource.memlimit;\n\t\tupdateresource.ignorereqcachinghdrs = resource.ignorereqcachinghdrs;\n\t\tupdateresource.minhits = resource.minhits;\n\t\tupdateresource.alwaysevalpolicies = resource.alwaysevalpolicies;\n\t\tupdateresource.persist = resource.persist;\n\t\tupdateresource.pinned = resource.pinned;\n\t\tupdateresource.lazydnsresolve = resource.lazydnsresolve;\n\t\tupdateresource.hitselector = resource.hitselector;\n\t\tupdateresource.invalselector = resource.invalselector;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public void collectVariables(EnvVars env, Run build, TaskListener listener) {\n EnvVars buildParameters = Utils.extractBuildParameters(build, listener);\n if (buildParameters != null) {\n env.putAll(buildParameters);\n }\n addAllWithFilter(envVars, env, filter.getPatternFilter());\n Map<String, String> sysEnv = new HashMap<>();\n Properties systemProperties = System.getProperties();\n Enumeration<?> enumeration = systemProperties.propertyNames();\n while (enumeration.hasMoreElements()) {\n String propertyKey = (String) enumeration.nextElement();\n sysEnv.put(propertyKey, systemProperties.getProperty(propertyKey));\n }\n addAllWithFilter(sysVars, sysEnv, filter.getPatternFilter());\n }",
"public void checkConstraints(String checkLevel) throws ConstraintException\r\n {\r\n // now checking constraints\r\n FieldDescriptorConstraints fieldConstraints = new FieldDescriptorConstraints();\r\n ReferenceDescriptorConstraints refConstraints = new ReferenceDescriptorConstraints();\r\n CollectionDescriptorConstraints collConstraints = new CollectionDescriptorConstraints();\r\n\r\n for (Iterator it = getFields(); it.hasNext();)\r\n {\r\n fieldConstraints.check((FieldDescriptorDef)it.next(), checkLevel);\r\n }\r\n for (Iterator it = getReferences(); it.hasNext();)\r\n {\r\n refConstraints.check((ReferenceDescriptorDef)it.next(), checkLevel);\r\n }\r\n for (Iterator it = getCollections(); it.hasNext();)\r\n {\r\n collConstraints.check((CollectionDescriptorDef)it.next(), checkLevel);\r\n }\r\n new ClassDescriptorConstraints().check(this, checkLevel);\r\n }",
"private Level getLogLevel() {\n return isQuiet() ? Level.OFF : isVerbose() ? Level.DEBUG : Level.INFO;\n }",
"public static base_response clear(nitro_service client) throws Exception {\n\t\tnssimpleacl clearresource = new nssimpleacl();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}"
] |
Resolve the targeted license thanks to the license ID
Return null if no license is matching the licenseId
@param licenseId
@return DbLicense | [
"public DbLicense resolve(final String licenseId) {\n\n for (final Entry<String, DbLicense> regexp : licensesRegexp.entrySet()) {\n try {\n if (licenseId.matches(regexp.getKey())) {\n return regexp.getValue();\n }\n } catch (PatternSyntaxException e) {\n LOG.error(\"Wrong pattern for the following license \" + regexp.getValue().getName(), e);\n continue;\n }\n }\n\n if(LOG.isWarnEnabled()) {\n LOG.warn(String.format(\"No matching pattern for license %s\", licenseId));\n }\n return null;\n }"
] | [
"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 CustomHeadersInterceptor addHeaderMap(Map<String, String> headers) {\n for (Map.Entry<String, String> header : headers.entrySet()) {\n this.headers.put(header.getKey(), Collections.singletonList(header.getValue()));\n }\n return this;\n }",
"public static final String getString(byte[] data, int offset)\n {\n StringBuilder buffer = new StringBuilder();\n char c;\n\n for (int loop = 0; offset + loop < data.length; loop++)\n {\n c = (char) data[offset + loop];\n\n if (c == 0)\n {\n break;\n }\n\n buffer.append(c);\n }\n\n return (buffer.toString());\n }",
"public static final String printDateTime(Date value)\n {\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }",
"protected boolean isSavedConnection(DatabaseConnection connection) {\n\t\tNestedConnection currentSaved = specialConnection.get();\n\t\tif (currentSaved == null) {\n\t\t\treturn false;\n\t\t} else if (currentSaved.connection == connection) {\n\t\t\t// ignore the release when we have a saved connection\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}",
"public int delete(DatabaseConnection databaseConnection, PreparedDelete<T> preparedDelete) throws SQLException {\n\t\tCompiledStatement compiledStatement = preparedDelete.compile(databaseConnection, StatementType.DELETE);\n\t\ttry {\n\t\t\tint result = compiledStatement.runUpdate();\n\t\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\t\tdao.notifyChanges();\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tIOUtils.closeThrowSqlException(compiledStatement, \"compiled statement\");\n\t\t}\n\t}",
"public static appfwpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tappfwpolicy_stats obj = new appfwpolicy_stats();\n\t\tobj.set_name(name);\n\t\tappfwpolicy_stats response = (appfwpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public static int Mode( int[] values ){\n int mode = 0, curMax = 0;\n\n for ( int i = 0, length = values.length; i < length; i++ )\n {\n if ( values[i] > curMax )\n {\n curMax = values[i];\n mode = i;\n }\n }\n return mode;\n }",
"private void processProperties() {\n state = true;\n try {\n importerServiceFilter = getFilter(importerServiceFilterProperty);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.debug(\"The value of the Property \" + FILTER_IMPORTERSERVICE_PROPERTY + \" is invalid,\"\n + \" the recuperation of the Filter has failed. The instance gonna stop.\", invalidFilterException);\n state = false;\n return;\n }\n\n try {\n importDeclarationFilter = getFilter(importDeclarationFilterProperty);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.debug(\"The value of the Property \" + FILTER_IMPORTDECLARATION_PROPERTY + \" is invalid,\"\n + \" the recuperation of the Filter has failed. The instance gonna stop.\", invalidFilterException);\n state = false;\n return;\n }\n }"
] |
Get viewport size along the axis
@param axis {@link Axis}
@return size | [
"protected float getViewPortSize(final Axis axis) {\n float size = mViewPort == null ? 0 : mViewPort.get(axis);\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"getViewPortSize for %s %f mViewPort = %s\", axis, size, mViewPort);\n return size;\n }"
] | [
"private Query getFKQuery(Object obj, ClassDescriptor cld, CollectionDescriptor cds)\r\n {\r\n Query fkQuery;\r\n QueryByCriteria fkQueryCrit;\r\n\r\n if (cds.isMtoNRelation())\r\n {\r\n fkQueryCrit = getFKQueryMtoN(obj, cld, cds);\r\n }\r\n else\r\n {\r\n fkQueryCrit = getFKQuery1toN(obj, cld, cds);\r\n }\r\n\r\n // check if collection must be ordered\r\n if (!cds.getOrderBy().isEmpty())\r\n {\r\n Iterator iter = cds.getOrderBy().iterator();\r\n while (iter.hasNext())\r\n {\r\n fkQueryCrit.addOrderBy((FieldHelper)iter.next());\r\n }\r\n }\r\n\r\n // BRJ: customize the query\r\n if (cds.getQueryCustomizer() != null)\r\n {\r\n fkQuery = cds.getQueryCustomizer().customizeQuery(obj, pb, cds, fkQueryCrit);\r\n }\r\n else\r\n {\r\n fkQuery = fkQueryCrit;\r\n }\r\n\r\n return fkQuery;\r\n }",
"public List<List<String>> getAllScopes() {\n this.checkInitialized();\n final ImmutableList.Builder<List<String>> builder = ImmutableList.<List<String>>builder();\n final Consumer<Integer> _function = (Integer it) -> {\n List<String> _get = this.scopes.get(it);\n StringConcatenation _builder = new StringConcatenation();\n _builder.append(\"No scopes are available for index: \");\n _builder.append(it);\n builder.add(Preconditions.<List<String>>checkNotNull(_get, _builder));\n };\n this.scopes.keySet().forEach(_function);\n return builder.build();\n }",
"public void delete(Object obj, boolean ignoreReferences) throws PersistenceBrokerException\n {\n if(isTxCheck() && !isInTransaction())\n {\n if(logger.isEnabledFor(Logger.ERROR))\n {\n String msg = \"No running PB-tx found. Please, only delete objects in context of a PB-transaction\" +\n \" to avoid side-effects - e.g. when rollback of complex objects.\";\n try\n {\n throw new Exception(\"** Delete object without active PersistenceBroker transaction **\");\n }\n catch(Exception e)\n {\n logger.error(msg, e);\n }\n }\n }\n try\n {\n doDelete(obj, ignoreReferences);\n }\n finally\n {\n markedForDelete.clear();\n }\n }",
"private List<CmsGitConfiguration> readConfigFiles() {\n\n List<CmsGitConfiguration> configurations = new LinkedList<CmsGitConfiguration>();\n\n // Default configuration file for backwards compatibility\n addConfigurationIfValid(configurations, new File(DEFAULT_CONFIG_FILE));\n\n // All files in the config folder\n File configFolder = new File(DEFAULT_CONFIG_FOLDER);\n if (configFolder.isDirectory()) {\n for (File configFile : configFolder.listFiles()) {\n addConfigurationIfValid(configurations, configFile);\n }\n }\n return configurations;\n }",
"public int getJdbcType(String ojbType) throws SQLException\r\n {\r\n int result;\r\n if(ojbType == null) ojbType = \"\";\r\n\t\tojbType = ojbType.toLowerCase();\r\n if (ojbType.equals(\"bit\"))\r\n result = Types.BIT;\r\n else if (ojbType.equals(\"tinyint\"))\r\n result = Types.TINYINT;\r\n else if (ojbType.equals(\"smallint\"))\r\n result = Types.SMALLINT;\r\n else if (ojbType.equals(\"integer\"))\r\n result = Types.INTEGER;\r\n else if (ojbType.equals(\"bigint\"))\r\n result = Types.BIGINT;\r\n\r\n else if (ojbType.equals(\"float\"))\r\n result = Types.FLOAT;\r\n else if (ojbType.equals(\"real\"))\r\n result = Types.REAL;\r\n else if (ojbType.equals(\"double\"))\r\n result = Types.DOUBLE;\r\n\r\n else if (ojbType.equals(\"numeric\"))\r\n result = Types.NUMERIC;\r\n else if (ojbType.equals(\"decimal\"))\r\n result = Types.DECIMAL;\r\n\r\n else if (ojbType.equals(\"char\"))\r\n result = Types.CHAR;\r\n else if (ojbType.equals(\"varchar\"))\r\n result = Types.VARCHAR;\r\n else if (ojbType.equals(\"longvarchar\"))\r\n result = Types.LONGVARCHAR;\r\n\r\n else if (ojbType.equals(\"date\"))\r\n result = Types.DATE;\r\n else if (ojbType.equals(\"time\"))\r\n result = Types.TIME;\r\n else if (ojbType.equals(\"timestamp\"))\r\n result = Types.TIMESTAMP;\r\n\r\n else if (ojbType.equals(\"binary\"))\r\n result = Types.BINARY;\r\n else if (ojbType.equals(\"varbinary\"))\r\n result = Types.VARBINARY;\r\n else if (ojbType.equals(\"longvarbinary\"))\r\n result = Types.LONGVARBINARY;\r\n\r\n\t\telse if (ojbType.equals(\"clob\"))\r\n \t\tresult = Types.CLOB;\r\n\t\telse if (ojbType.equals(\"blob\"))\r\n\t\t\tresult = Types.BLOB;\r\n else\r\n throw new SQLException(\r\n \"The type '\"+ ojbType + \"' is not a valid jdbc type.\");\r\n return result;\r\n }",
"private CmsVfsEntryBean buildVfsEntryBeanForQuickSearch(\n CmsResource resource,\n Multimap<CmsResource, CmsResource> childMap,\n Set<CmsResource> filterMatches,\n Set<String> parentPaths,\n boolean isRoot)\n throws CmsException {\n\n CmsObject cms = getCmsObject();\n String title = cms.readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();\n boolean isMatch = filterMatches.contains(resource);\n List<CmsVfsEntryBean> childBeans = Lists.newArrayList();\n\n Collection<CmsResource> children = childMap.get(resource);\n if (!children.isEmpty()) {\n for (CmsResource child : children) {\n CmsVfsEntryBean childBean = buildVfsEntryBeanForQuickSearch(\n child,\n childMap,\n filterMatches,\n parentPaths,\n false);\n childBeans.add(childBean);\n }\n } else if (filterMatches.contains(resource)) {\n if (parentPaths.contains(resource.getRootPath())) {\n childBeans = null;\n }\n // otherwise childBeans remains an empty list\n }\n\n String rootPath = resource.getRootPath();\n CmsVfsEntryBean result = new CmsVfsEntryBean(\n rootPath,\n resource.getStructureId(),\n title,\n CmsIconUtil.getIconClasses(CmsIconUtil.getDisplayType(cms, resource), resource.getName(), true),\n isRoot,\n isEditable(cms, resource),\n childBeans,\n isMatch);\n String siteRoot = null;\n if (OpenCms.getSiteManager().startsWithShared(rootPath)) {\n siteRoot = OpenCms.getSiteManager().getSharedFolder();\n } else {\n String tempSiteRoot = OpenCms.getSiteManager().getSiteRoot(rootPath);\n if (tempSiteRoot != null) {\n siteRoot = tempSiteRoot;\n } else {\n siteRoot = \"\";\n }\n }\n result.setSiteRoot(siteRoot);\n return result;\n }",
"protected BufferedImage createErrorImage(final Rectangle area) {\n final BufferedImage bufferedImage = new BufferedImage(area.width, area.height, TYPE_INT_ARGB_PRE);\n final Graphics2D graphics = bufferedImage.createGraphics();\n try {\n graphics.setBackground(ColorParser.toColor(this.configuration.getTransparentTileErrorColor()));\n graphics.clearRect(0, 0, area.width, area.height);\n return bufferedImage;\n } finally {\n graphics.dispose();\n }\n }",
"private Date seasonalDateFromIcs(String icsFileName, String eventSummary, int year) {\n Map<Integer, Date> dates = getDatesFromIcs(icsFileName, eventSummary, year, year);\n return dates.get(year - (eventSummary.equals(Holiday.NEW_YEARS_EVE.getSummary()) ? 1 : 0));\n }",
"public void setCloseConnectionWatchTimeout(long closeConnectionWatchTimeout, TimeUnit timeUnit) {\n\t\tthis.closeConnectionWatchTimeoutInMs = TimeUnit.MILLISECONDS.convert(closeConnectionWatchTimeout, timeUnit);\n\t}"
] |
Read the given number of bytes into a long
@param bytes The byte array to read from
@param offset The offset at which to begin reading
@param numBytes The number of bytes to read
@return The long value read | [
"public static long readBytes(byte[] bytes, int offset, int numBytes) {\n int shift = 0;\n long value = 0;\n for(int i = offset + numBytes - 1; i >= offset; i--) {\n value |= (bytes[i] & 0xFFL) << shift;\n shift += 8;\n }\n return value;\n }"
] | [
"public void updateStructure()\n {\n if (size() > 1)\n {\n Collections.sort(this);\n m_projectFile.getChildTasks().clear();\n\n Task lastTask = null;\n int lastLevel = -1;\n boolean autoWbs = m_projectFile.getProjectConfig().getAutoWBS();\n boolean autoOutlineNumber = m_projectFile.getProjectConfig().getAutoOutlineNumber();\n\n for (Task task : this)\n {\n task.clearChildTasks();\n Task parent = null;\n if (!task.getNull())\n {\n int level = NumberHelper.getInt(task.getOutlineLevel());\n\n if (lastTask != null)\n {\n if (level == lastLevel || task.getNull())\n {\n parent = lastTask.getParentTask();\n level = lastLevel;\n }\n else\n {\n if (level > lastLevel)\n {\n parent = lastTask;\n }\n else\n {\n while (level <= lastLevel)\n {\n parent = lastTask.getParentTask();\n\n if (parent == null)\n {\n break;\n }\n\n lastLevel = NumberHelper.getInt(parent.getOutlineLevel());\n lastTask = parent;\n }\n }\n }\n }\n\n lastTask = task;\n lastLevel = level;\n\n if (autoWbs || task.getWBS() == null)\n {\n task.generateWBS(parent);\n }\n\n if (autoOutlineNumber)\n {\n task.generateOutlineNumber(parent);\n }\n }\n\n if (parent == null)\n {\n m_projectFile.getChildTasks().add(task);\n }\n else\n {\n parent.addChildTask(task);\n }\n }\n }\n }",
"public String getPrototypeName() {\n\t\tString name = getClass().getName();\n\t\tif (name.startsWith(ORG_GEOMAJAS)) {\n\t\t\tname = name.substring(ORG_GEOMAJAS.length());\n\t\t}\n\t\tname = name.replace(\".dto.\", \".impl.\");\n\t\treturn name.substring(0, name.length() - 4) + \"Impl\";\n\t}",
"private float[] generateParticleVelocities()\n {\n float velocities[] = new float[mEmitRate * 3];\n for ( int i = 0; i < mEmitRate * 3; i +=3 )\n {\n Vector3f nexVel = getNextVelocity();\n velocities[i] = nexVel.x;\n velocities[i+1] = nexVel.y;\n velocities[i+2] = nexVel.z;\n }\n return velocities;\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 static Object getFieldValue(Object object, String fieldName) {\n try {\n return getDeclaredFieldInHierarchy(object.getClass(), fieldName).get(object);\n } catch (IllegalArgumentException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n }",
"public static void dumpClusters(Cluster currentCluster,\n Cluster finalCluster,\n String outputDirName) {\n dumpClusters(currentCluster, finalCluster, outputDirName, \"\");\n }",
"private synchronized void initializeFatClient(String storeName, Properties storeClientProps) {\n // updates the coordinator metadata with recent stores and cluster xml\n updateCoordinatorMetadataWithLatestState();\n\n logger.info(\"Creating a Fat client for store: \" + storeName);\n SocketStoreClientFactory fatClientFactory = getFatClientFactory(this.coordinatorConfig.getBootstrapURLs(),\n storeClientProps);\n\n if(this.fatClientMap == null) {\n this.fatClientMap = new HashMap<String, DynamicTimeoutStoreClient<ByteArray, byte[]>>();\n }\n DynamicTimeoutStoreClient<ByteArray, byte[]> fatClient = new DynamicTimeoutStoreClient<ByteArray, byte[]>(storeName,\n fatClientFactory,\n 1,\n this.coordinatorMetadata.getStoreDefs(),\n this.coordinatorMetadata.getClusterXmlStr());\n this.fatClientMap.put(storeName, fatClient);\n\n }",
"public static boolean isTypeManagedBeanOrDecoratorOrInterceptor(AnnotatedType<?> annotatedType) {\n Class<?> javaClass = annotatedType.getJavaClass();\n return !javaClass.isEnum() && !Extension.class.isAssignableFrom(javaClass)\n && Reflections.isTopLevelOrStaticNestedClass(javaClass) && !Reflections.isParameterizedTypeWithWildcard(javaClass)\n && hasSimpleCdiConstructor(annotatedType);\n }",
"private void readLeafTasks(Task parent, Integer id)\n {\n Integer currentID = id;\n Table table = getTable(\"A1TAB\");\n while (currentID.intValue() != 0)\n {\n if (m_projectFile.getTaskByUniqueID(currentID) == null)\n {\n readTask(parent, currentID);\n }\n currentID = table.find(currentID).getInteger(\"NEXT_TASK_ID\");\n }\n }"
] |
Use this API to update tmtrafficaction resources. | [
"public static base_responses update(nitro_service client, tmtrafficaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\ttmtrafficaction updateresources[] = new tmtrafficaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new tmtrafficaction();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].apptimeout = resources[i].apptimeout;\n\t\t\t\tupdateresources[i].sso = resources[i].sso;\n\t\t\t\tupdateresources[i].formssoaction = resources[i].formssoaction;\n\t\t\t\tupdateresources[i].persistentcookie = resources[i].persistentcookie;\n\t\t\t\tupdateresources[i].initiatelogout = resources[i].initiatelogout;\n\t\t\t\tupdateresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\tupdateresources[i].samlssoprofile = resources[i].samlssoprofile;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public Map<BsonValue, ChangeEvent<BsonDocument>> getEventsForNamespace(\n final MongoNamespace namespace\n ) {\n this.instanceLock.readLock().lock();\n final NamespaceChangeStreamListener streamer;\n try {\n streamer = nsStreamers.get(namespace);\n } finally {\n this.instanceLock.readLock().unlock();\n }\n if (streamer == null) {\n return new HashMap<>();\n }\n return streamer.getEvents();\n }",
"public static base_responses update(nitro_service client, gslbservice resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbservice updateresources[] = new gslbservice[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new gslbservice();\n\t\t\t\tupdateresources[i].servicename = resources[i].servicename;\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].publicip = resources[i].publicip;\n\t\t\t\tupdateresources[i].publicport = resources[i].publicport;\n\t\t\t\tupdateresources[i].cip = resources[i].cip;\n\t\t\t\tupdateresources[i].cipheader = resources[i].cipheader;\n\t\t\t\tupdateresources[i].sitepersistence = resources[i].sitepersistence;\n\t\t\t\tupdateresources[i].siteprefix = resources[i].siteprefix;\n\t\t\t\tupdateresources[i].maxclient = resources[i].maxclient;\n\t\t\t\tupdateresources[i].healthmonitor = resources[i].healthmonitor;\n\t\t\t\tupdateresources[i].maxbandwidth = resources[i].maxbandwidth;\n\t\t\t\tupdateresources[i].downstateflush = resources[i].downstateflush;\n\t\t\t\tupdateresources[i].maxaaausers = resources[i].maxaaausers;\n\t\t\t\tupdateresources[i].viewname = resources[i].viewname;\n\t\t\t\tupdateresources[i].viewip = resources[i].viewip;\n\t\t\t\tupdateresources[i].monthreshold = resources[i].monthreshold;\n\t\t\t\tupdateresources[i].weight = resources[i].weight;\n\t\t\t\tupdateresources[i].monitor_name_svc = resources[i].monitor_name_svc;\n\t\t\t\tupdateresources[i].hashid = resources[i].hashid;\n\t\t\t\tupdateresources[i].comment = resources[i].comment;\n\t\t\t\tupdateresources[i].appflowlog = resources[i].appflowlog;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static responderhtmlpage get(nitro_service service, String name) throws Exception{\n\t\tresponderhtmlpage obj = new responderhtmlpage();\n\t\tobj.set_name(name);\n\t\tresponderhtmlpage response = (responderhtmlpage) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static String readStringFromUrlGeneric(String url)\n throws IOException {\n InputStream is = null;\n URL urlObj = null;\n String responseString = PcConstants.NA;\n try {\n urlObj = new URL(url);\n URLConnection con = urlObj.openConnection();\n\n con.setConnectTimeout(ParallecGlobalConfig.urlConnectionConnectTimeoutMillis);\n con.setReadTimeout(ParallecGlobalConfig.urlConnectionReadTimeoutMillis);\n is = con.getInputStream();\n\n BufferedReader rd = new BufferedReader(new InputStreamReader(is,\n Charset.forName(\"UTF-8\")));\n responseString = PcFileNetworkIoUtils.readAll(rd);\n\n } finally {\n\n if (is != null) {\n is.close();\n }\n\n }\n\n return responseString;\n }",
"private void performScriptedStep() {\n double scale = computeBulgeScale();\n if( steps > giveUpOnKnown ) {\n // give up on the script\n followScript = false;\n } else {\n // use previous singular value to step\n double s = values[x2]/scale;\n performImplicitSingleStep(scale,s*s,false);\n }\n }",
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public void registerFilters(List<AlgoliaFilter> filters) {\n for (final AlgoliaFilter filter : filters) {\n searcher.addFacet(filter.getAttribute());\n }\n }",
"public WindupConfiguration setOptionValue(String name, Object value)\n {\n configurationOptions.put(name, value);\n return this;\n }",
"public static CurrencySymbolPosition getSymbolPosition(int value)\n {\n CurrencySymbolPosition result;\n\n switch (value)\n {\n case 1:\n {\n result = CurrencySymbolPosition.AFTER;\n break;\n }\n\n case 2:\n {\n result = CurrencySymbolPosition.BEFORE_WITH_SPACE;\n break;\n }\n\n case 3:\n {\n result = CurrencySymbolPosition.AFTER_WITH_SPACE;\n break;\n }\n\n case 0:\n default:\n {\n result = CurrencySymbolPosition.BEFORE;\n break;\n }\n }\n\n return (result);\n }",
"private void addCalendars(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (ProjectCalendar calendar : file.getCalendars())\n {\n addCalendar(parentNode, calendar);\n }\n }"
] |
Use this API to fetch a responderglobal_responderpolicy_binding resources. | [
"public static responderglobal_responderpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tresponderglobal_responderpolicy_binding obj = new responderglobal_responderpolicy_binding();\n\t\tresponderglobal_responderpolicy_binding response[] = (responderglobal_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public static pqbinding[] get(nitro_service service, pqbinding_args args) throws Exception{\n\t\tpqbinding obj = new pqbinding();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tpqbinding[] response = (pqbinding[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"public void syncInternalStateFromFileSystem(boolean alsoSyncRemoteState) {\n // Make sure versions missing from the file-system are cleaned up from the internal state\n for (Long version: versionToEnabledMap.keySet()) {\n File[] existingVersionDirs = ReadOnlyUtils.getVersionDirs(rootDir, version, version);\n if (existingVersionDirs.length == 0) {\n removeVersion(version, alsoSyncRemoteState);\n }\n }\n\n // Make sure we have all versions on the file-system in the internal state\n File[] versionDirs = ReadOnlyUtils.getVersionDirs(rootDir);\n if (versionDirs != null) {\n for (File versionDir: versionDirs) {\n long versionNumber = ReadOnlyUtils.getVersionId(versionDir);\n boolean versionEnabled = isVersionEnabled(versionDir);\n versionToEnabledMap.put(versionNumber, versionEnabled);\n }\n }\n\n // Identify the current version (based on a symlink in the file-system)\n File currentVersionDir = ReadOnlyUtils.getCurrentVersion(rootDir);\n if (currentVersionDir != null) {\n currentVersion = ReadOnlyUtils.getVersionId(currentVersionDir);\n } else {\n currentVersion = -1; // Should we throw instead?\n }\n\n logger.info(\"Successfully synced internal state from local file-system: \" + this.toString());\n }",
"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}",
"ProtectionDomain getProtectionDomainForProxy(ProtectionDomain domain) {\n if (domain.getCodeSource() == null) {\n // no codesource to cache on\n return create(domain);\n }\n ProtectionDomain proxyProtectionDomain = proxyProtectionDomains.get(domain.getCodeSource());\n if (proxyProtectionDomain == null) {\n // as this is not atomic create() may be called multiple times for the same domain\n // we ignore that\n proxyProtectionDomain = create(domain);\n ProtectionDomain existing = proxyProtectionDomains.putIfAbsent(domain.getCodeSource(), proxyProtectionDomain);\n if (existing != null) {\n proxyProtectionDomain = existing;\n }\n }\n return proxyProtectionDomain;\n }",
"public DescriptorRepository readDescriptorRepository(InputStream inst)\r\n {\r\n try\r\n {\r\n RepositoryPersistor persistor = new RepositoryPersistor();\r\n return persistor.readDescriptorRepository(inst);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\"Can not read repository \" + inst, e);\r\n }\r\n }",
"public void sendSyncModeCommand(int deviceNumber, boolean synced) throws IOException {\n final DeviceUpdate update = getLatestStatusFor(deviceNumber);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + deviceNumber + \" not found on network.\");\n }\n sendSyncModeCommand(update, synced);\n }",
"public Where<T, ID> isNotNull(String columnName) throws SQLException {\n\t\taddClause(new IsNotNull(columnName, findColumnFieldType(columnName)));\n\t\treturn this;\n\t}",
"public static void rebuild(final MODE newMode) {\n if (mode != newMode) {\n mode = newMode;\n TYPE type;\n switch (mode) {\n case DEBUG:\n type = TYPE.ANDROID;\n Log.startFullLog();\n break;\n case DEVELOPER:\n type = TYPE.PERSISTENT;\n Log.stopFullLog();\n break;\n case USER:\n type = TYPE.ANDROID;\n break;\n default:\n type = DEFAULT_TYPE;\n Log.stopFullLog();\n break;\n }\n currentLog = getLog(type);\n }\n }",
"private boolean hasToBuilderMethod(\n DeclaredType builder,\n boolean isExtensible,\n Iterable<ExecutableElement> methods) {\n for (ExecutableElement method : methods) {\n if (isToBuilderMethod(builder, method)) {\n if (!isExtensible) {\n messager.printMessage(ERROR,\n \"No accessible no-args Builder constructor available to implement toBuilder\",\n method);\n }\n return true;\n }\n }\n return false;\n }"
] |
Sets the Base Calendar field indicates which calendar is the base calendar
for a resource calendar. The list includes the three built-in calendars,
as well as any new base calendars you have created in the Change Working
Time dialog box.
@param val calendar name | [
"public void setBaseCalendar(String val)\n {\n set(ResourceField.BASE_CALENDAR, val == null || val.length() == 0 ? \"Standard\" : val);\n }"
] | [
"private String formatTime(Date value)\n {\n return (value == null ? null : m_formats.getTimeFormat().format(value));\n }",
"public ServerSetup createCopy(String bindAddress) {\r\n ServerSetup setup = new ServerSetup(getPort(), bindAddress, getProtocol());\r\n setup.setServerStartupTimeout(getServerStartupTimeout());\r\n setup.setConnectionTimeout(getConnectionTimeout());\r\n setup.setReadTimeout(getReadTimeout());\r\n setup.setWriteTimeout(getWriteTimeout());\r\n setup.setVerbose(isVerbose());\r\n\r\n return setup;\r\n }",
"public static GVRTexture loadFutureCubemapTexture(\n GVRContext gvrContext, ResourceCache<GVRImage> textureCache,\n GVRAndroidResource resource, int priority,\n Map<String, Integer> faceIndexMap) {\n GVRTexture tex = new GVRTexture(gvrContext);\n GVRImage cached = textureCache.get(resource);\n if (cached != null)\n {\n Log.v(\"ASSET\", \"Future Texture: %s loaded from cache\", cached.getFileName());\n tex.setImage(cached);\n }\n else\n {\n AsyncCubemapTexture.get().loadTexture(gvrContext,\n CancelableCallbackWrapper.wrap(GVRCubemapImage.class, tex),\n resource, priority, faceIndexMap);\n\n }\n return tex;\n }",
"public static String format(String pattern, Object... arguments) {\n String msg = pattern;\n if (arguments != null) {\n for (int index = 0; index < arguments.length; index++) {\n msg = msg.replaceAll(\"\\\\{\" + (index + 1) + \"\\\\}\", String.valueOf(arguments[index]));\n }\n }\n return msg;\n }",
"@Override\n\tpublic Set<String> getRoundingNames(String... providers) {\n Set<String> result = new HashSet<>();\n String[] providerNames = providers;\n if (providerNames.length == 0) {\n providerNames = Monetary.getDefaultRoundingProviderChain().toArray(new String[Monetary.getDefaultRoundingProviderChain().size()]);\n }\n for (String providerName : providerNames) {\n for (RoundingProviderSpi prov : Bootstrap.getServices(RoundingProviderSpi.class)) {\n try {\n if (prov.getProviderName().equals(providerName) || prov.getProviderName().matches(providerName)) {\n result.addAll(prov.getRoundingNames());\n }\n } catch (Exception e) {\n Logger.getLogger(DefaultMonetaryRoundingsSingletonSpi.class.getName())\n .log(Level.SEVERE, \"Error loading RoundingProviderSpi from provider: \" + prov, e);\n }\n }\n }\n return result;\n }",
"@SuppressWarnings({\"deprecation\", \"WeakerAccess\"})\n protected void removeShutdownHook(ClassLoaderLeakPreventor preventor, Thread shutdownHook) {\n final String displayString = \"'\" + shutdownHook + \"' of type \" + shutdownHook.getClass().getName();\n preventor.error(\"Removing shutdown hook: \" + displayString);\n Runtime.getRuntime().removeShutdownHook(shutdownHook);\n\n if(executeShutdownHooks) { // Shutdown hooks should be executed\n \n preventor.info(\"Executing shutdown hook now: \" + displayString);\n // Make sure it's from protected ClassLoader\n shutdownHook.start(); // Run cleanup immediately\n \n if(shutdownHookWaitMs > 0) { // Wait for shutdown hook to finish\n try {\n shutdownHook.join(shutdownHookWaitMs); // Wait for thread to run\n }\n catch (InterruptedException e) {\n // Do nothing\n }\n if(shutdownHook.isAlive()) {\n preventor.warn(shutdownHook + \"still running after \" + shutdownHookWaitMs + \" ms - Stopping!\");\n shutdownHook.stop();\n }\n }\n }\n }",
"public static<A, B, C, Z> Function3<A, B, C, Z> lift(Func3<A, B, C, Z> f) {\n\treturn bridge.lift(f);\n }",
"@UiThread\n public int getParentAdapterPosition() {\n int flatPosition = getAdapterPosition();\n if (mExpandableAdapter == null || flatPosition == RecyclerView.NO_POSITION) {\n return RecyclerView.NO_POSITION;\n }\n\n return mExpandableAdapter.getNearestParentPosition(flatPosition);\n }",
"private static void addCauseToBacktrace(final Throwable cause, final List<String> bTrace) {\n if (cause.getMessage() == null) {\n bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName());\n } else {\n bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName() + \": \" + cause.getMessage());\n }\n for (final StackTraceElement ste : cause.getStackTrace()) {\n bTrace.add(BT_PREFIX + ste.toString());\n }\n if (cause.getCause() != null) {\n addCauseToBacktrace(cause.getCause(), bTrace);\n }\n }"
] |
Convert MPX day index to Day instance.
@param day day index
@return Day instance | [
"public static Day getDay(Integer day)\n {\n Day result = null;\n if (day != null)\n {\n result = DAY_ARRAY[day.intValue()];\n }\n return (result);\n }"
] | [
"private static String buildErrorMsg(List<String> dependencies, String message) {\n final StringBuilder buffer = new StringBuilder();\n boolean isFirstElement = true;\n for (String dependency : dependencies) {\n if (!isFirstElement) {\n buffer.append(\", \");\n }\n // check if it is an instance of Artifact - add the gavc else append the object\n buffer.append(dependency);\n\n isFirstElement = false;\n }\n return String.format(message, buffer.toString());\n }",
"void endIfStarted(CodeAttribute b, ClassMethod method) {\n b.aload(getLocalVariableIndex(0));\n b.dup();\n final BranchEnd ifnotnull = b.ifnull();\n b.checkcast(Stack.class);\n b.invokevirtual(Stack.class.getName(), END_INTERCEPTOR_CONTEXT_METHOD_NAME, EMPTY_PARENTHESES + VOID_CLASS_DESCRIPTOR);\n BranchEnd ifnull = b.gotoInstruction();\n b.branchEnd(ifnotnull);\n b.pop(); // remove null Stack\n b.branchEnd(ifnull);\n }",
"private org.apache.log4j.Logger getLogger()\r\n\t{\r\n /*\r\n Logger interface extends Serializable, thus Log field is\r\n declared 'transient' and we have to null-check\r\n\t\t*/\r\n\t\tif (logger == null)\r\n\t\t{\r\n\t\t\tlogger = org.apache.log4j.Logger.getLogger(name);\r\n\t\t}\r\n\t\treturn logger;\r\n\t}",
"private void writeTasks(List<Task> tasks) throws IOException\n {\n for (Task task : tasks)\n {\n writeTask(task);\n writeTasks(task.getChildTasks());\n }\n }",
"protected void sendPageBreakToBottom(JRDesignBand band) {\n\t\tJRElement[] elems = band.getElements();\n\t\tJRElement aux = null;\n\t\tfor (JRElement elem : elems) {\n\t\t\tif ((\"\" + elem.getKey()).startsWith(PAGE_BREAK_FOR_)) {\n\t\t\t\taux = elem;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (aux != null)\n\t\t\t((JRDesignElement)aux).setY(band.getHeight());\n\t}",
"public BoxGroupMembership.Info addMembership(BoxUser user, Role role) {\n BoxAPIConnection api = this.getAPI();\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"user\", new JsonObject().add(\"id\", user.getID()));\n requestJSON.add(\"group\", new JsonObject().add(\"id\", this.getID()));\n if (role != null) {\n requestJSON.add(\"role\", role.toJSONString());\n }\n\n URL url = ADD_MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxGroupMembership membership = new BoxGroupMembership(api, responseJSON.get(\"id\").asString());\n return membership.new Info(responseJSON);\n }",
"public static void dumpClusters(Cluster currentCluster,\n Cluster finalCluster,\n String outputDirName) {\n dumpClusters(currentCluster, finalCluster, outputDirName, \"\");\n }",
"private void writeNewLineIndent() throws IOException\n {\n if (m_pretty)\n {\n if (!m_indent.isEmpty())\n {\n m_writer.write('\\n');\n m_writer.write(m_indent);\n }\n }\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 }"
] |
Return true if the two connections seem to one one connection under the covers. | [
"protected boolean isSingleConnection(DatabaseConnection conn1, DatabaseConnection conn2) throws SQLException {\n\t\t// initialize the connections auto-commit flags\n\t\tconn1.setAutoCommit(true);\n\t\tconn2.setAutoCommit(true);\n\t\ttry {\n\t\t\t// change conn1's auto-commit to be false\n\t\t\tconn1.setAutoCommit(false);\n\t\t\tif (conn2.isAutoCommit()) {\n\t\t\t\t// if the 2nd connection's auto-commit is still true then we have multiple connections\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\t// if the 2nd connection's auto-commit is also false then we have a single connection\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} finally {\n\t\t\t// restore its auto-commit\n\t\t\tconn1.setAutoCommit(true);\n\t\t}\n\t}"
] | [
"public synchronized Response doCommandFullResponse(String command) throws CommandFormatException, IOException {\n ModelNode request = cmdCtx.buildRequest(command);\n boolean replacedBytes = replaceFilePathsWithBytes(request);\n OperationResponse response = execute(request, isSlowCommand(command) || replacedBytes);\n return new Response(command, request, response);\n }",
"public final void setWeeksOfMonth(SortedSet<WeekOfMonth> weeksOfMonth) {\n\n m_weeksOfMonth.clear();\n if (null != weeksOfMonth) {\n m_weeksOfMonth.addAll(weeksOfMonth);\n }\n\n }",
"private ServerDetails createInitialResolveDetailsFromDeployDetails(ServerDetails deployerDetails) {\n RepositoryConf oldResolveRepositoryConfig = deployerDetails.getResolveReleaseRepository();\n RepositoryConf oldSnapshotResolveRepositoryConfig = deployerDetails.getResolveSnapshotRepository();\n RepositoryConf resolverReleaseRepos = oldResolveRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldResolveRepositoryConfig;\n RepositoryConf resolveSnapshotRepos = oldSnapshotResolveRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldSnapshotResolveRepositoryConfig;\n return new ServerDetails(deployerDetails.getArtifactoryName(), deployerDetails.getArtifactoryUrl(),\n null, null, resolverReleaseRepos, resolveSnapshotRepos, null, null);\n }",
"public ServerRedirect getRedirect(int id) throws Exception {\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, id);\n results = queryStatement.executeQuery();\n if (results.next()) {\n ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.SERVER_REDIRECT_REGION),\n results.getString(Constants.SERVER_REDIRECT_SRC_URL),\n results.getString(Constants.SERVER_REDIRECT_DEST_URL),\n results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));\n curServer.setProfileId(results.getInt(Constants.GENERIC_PROFILE_ID));\n\n return curServer;\n }\n logger.info(\"Did not find the ID: {}\", id);\n } catch (SQLException e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return null;\n }",
"public static void setSourceLevelUrisWithoutCopy(final ResourceSet resourceSet, final Set<URI> uris) {\n final SourceLevelURIsAdapter adapter = SourceLevelURIsAdapter.findOrCreateAdapter(resourceSet);\n adapter.sourceLevelURIs = uris;\n }",
"public void notifyEventListeners(ZWaveEvent event) {\n\t\tlogger.debug(\"Notifying event listeners\");\n\t\tfor (ZWaveEventListener listener : this.zwaveEventListeners) {\n\t\t\tlogger.trace(\"Notifying {}\", listener.toString());\n\t\t\tlistener.ZWaveIncomingEvent(event);\n\t\t}\n\t}",
"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 }",
"public void logWarning(final String message) {\n messageQueue.add(new LogEntry() {\n @Override\n public String getMessage() {\n return message;\n }\n });\n }",
"public static DMatrixSparseCSC triangle( boolean upper , int N , double minFill , double maxFill , Random rand ) {\n int nz = (int)(((N-1)*(N-1)/2)*(rand.nextDouble()*(maxFill-minFill)+minFill))+N;\n\n if( upper ) {\n return triangleUpper(N,0,nz,-1,1,rand);\n } else {\n return triangleLower(N,0,nz,-1,1,rand);\n }\n }"
] |
Returns the site path for the edited bundle file.
@return the site path for the edited bundle file. | [
"public String getEditedFilePath() {\n\n switch (getBundleType()) {\n case DESCRIPTOR:\n return m_cms.getSitePath(m_desc);\n case PROPERTY:\n return null != m_lockedBundleFiles.get(getLocale())\n ? m_cms.getSitePath(m_lockedBundleFiles.get(getLocale()).getFile())\n : m_cms.getSitePath(m_resource);\n case XML:\n return m_cms.getSitePath(m_resource);\n default:\n throw new IllegalArgumentException();\n }\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 List<String> processAllListeners(View rootView) {\n List<String> refinementAttributes = new ArrayList<>();\n\n // Register any AlgoliaResultsListener (unless it has a different variant than searcher)\n final List<AlgoliaResultsListener> resultListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaResultsListener.class);\n if (resultListeners.isEmpty()) {\n throw new IllegalStateException(Errors.LAYOUT_MISSING_RESULT_LISTENER);\n }\n for (AlgoliaResultsListener listener : resultListeners) {\n if (!this.resultListeners.contains(listener)) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n this.resultListeners.add(listener);\n searcher.registerResultListener(listener);\n prepareWidget(listener, refinementAttributes);\n }\n }\n }\n\n // Register any AlgoliaErrorListener (unless it has a different variant than searcher)\n final List<AlgoliaErrorListener> errorListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaErrorListener.class);\n for (AlgoliaErrorListener listener : errorListeners) {\n if (!this.errorListeners.contains(listener)) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n this.errorListeners.add(listener);\n }\n }\n searcher.registerErrorListener(listener);\n prepareWidget(listener, refinementAttributes);\n }\n\n // Register any AlgoliaSearcherListener (unless it has a different variant than searcher)\n final List<AlgoliaSearcherListener> searcherListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaSearcherListener.class);\n for (AlgoliaSearcherListener listener : searcherListeners) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n listener.initWithSearcher(searcher);\n prepareWidget(listener, refinementAttributes);\n }\n }\n\n return refinementAttributes;\n }",
"public BoxFile.Info getFileInfo(String fileID, String... fields) {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", fields).toString();\n URL url = FILE_INFO_URL_TEMPLATE.buildWithQuery(this.api.getBaseURL(), queryString, fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFile file = new BoxFile(this.api, jsonObject.get(\"id\").asString());\n return file.new Info(response.getJSON());\n }",
"public static base_responses disable(nitro_service client, String trapname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (trapname != null && trapname.length > 0) {\n\t\t\tsnmpalarm disableresources[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++){\n\t\t\t\tdisableresources[i] = new snmpalarm();\n\t\t\t\tdisableresources[i].trapname = trapname[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 cmppolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tcmppolicy_stats obj = new cmppolicy_stats();\n\t\tobj.set_name(name);\n\t\tcmppolicy_stats response = (cmppolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public RelatedTagsList getRelated(String tag) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_RELATED);\n\n parameters.put(\"tag\", tag);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element tagsElement = response.getPayload();\n\n RelatedTagsList tags = new RelatedTagsList();\n tags.setSource(tagsElement.getAttribute(\"source\"));\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag t = new Tag();\n t.setValue(XMLUtilities.getValue(tagElement));\n tags.add(t);\n }\n return tags;\n }",
"private FieldConversion[] getPkFieldConversion(ClassDescriptor cld)\r\n {\r\n FieldDescriptor[] pks = cld.getPkFields();\r\n FieldConversion[] fc = new FieldConversion[pks.length]; \r\n \r\n for (int i= 0; i < pks.length; i++)\r\n {\r\n fc[i] = pks[i].getFieldConversion();\r\n }\r\n \r\n return fc;\r\n }",
"public void setRefreshFrequency(IntervalFrequency frequency) {\n if (NONE_REFRESH_INTERVAL == mRefreshInterval && IntervalFrequency.NONE != frequency) {\n // Install draw-frame listener if frequency is no longer NONE\n getGVRContext().unregisterDrawFrameListener(mFrameListener);\n getGVRContext().registerDrawFrameListener(mFrameListener);\n }\n switch (frequency) {\n case REALTIME:\n mRefreshInterval = REALTIME_REFRESH_INTERVAL;\n break;\n case HIGH:\n mRefreshInterval = HIGH_REFRESH_INTERVAL;\n break;\n case MEDIUM:\n mRefreshInterval = MEDIUM_REFRESH_INTERVAL;\n break;\n case LOW:\n mRefreshInterval = LOW_REFRESH_INTERVAL;\n break;\n case NONE:\n mRefreshInterval = NONE_REFRESH_INTERVAL;\n break;\n default:\n break;\n }\n }",
"public 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 }"
] |
Helper function that drops all local databases for every client. | [
"public static void clearallLocalDBs() {\n for (final Map.Entry<MongoClient, Boolean> entry : localInstances.entrySet()) {\n for (final String dbName : entry.getKey().listDatabaseNames()) {\n entry.getKey().getDatabase(dbName).drop();\n }\n }\n }"
] | [
"protected AllowableActions collectAllowableActions(CmsObject cms, CmsResource file) {\r\n\r\n try {\r\n\r\n if (file == null) {\r\n throw new IllegalArgumentException(\"File must not be null!\");\r\n }\r\n CmsLock lock = cms.getLock(file);\r\n CmsUser user = cms.getRequestContext().getCurrentUser();\r\n boolean canWrite = !cms.getRequestContext().getCurrentProject().isOnlineProject()\r\n && (lock.isOwnedBy(user) || lock.isLockableBy(user))\r\n && cms.hasPermissions(file, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.DEFAULT);\r\n boolean isReadOnly = !canWrite;\r\n boolean isFolder = file.isFolder();\r\n boolean isRoot = file.getRootPath().length() <= 1;\r\n\r\n Set<Action> aas = new LinkedHashSet<Action>();\r\n addAction(aas, Action.CAN_GET_OBJECT_PARENTS, !isRoot);\r\n addAction(aas, Action.CAN_GET_PROPERTIES, true);\r\n addAction(aas, Action.CAN_UPDATE_PROPERTIES, !isReadOnly);\r\n addAction(aas, Action.CAN_MOVE_OBJECT, !isReadOnly && !isRoot);\r\n addAction(aas, Action.CAN_DELETE_OBJECT, !isReadOnly && !isRoot);\r\n if (isFolder) {\r\n addAction(aas, Action.CAN_GET_DESCENDANTS, true);\r\n addAction(aas, Action.CAN_GET_CHILDREN, true);\r\n addAction(aas, Action.CAN_GET_FOLDER_PARENT, !isRoot);\r\n addAction(aas, Action.CAN_GET_FOLDER_TREE, true);\r\n addAction(aas, Action.CAN_CREATE_DOCUMENT, !isReadOnly);\r\n addAction(aas, Action.CAN_CREATE_FOLDER, !isReadOnly);\r\n addAction(aas, Action.CAN_DELETE_TREE, !isReadOnly);\r\n } else {\r\n addAction(aas, Action.CAN_GET_CONTENT_STREAM, true);\r\n addAction(aas, Action.CAN_SET_CONTENT_STREAM, !isReadOnly);\r\n addAction(aas, Action.CAN_GET_ALL_VERSIONS, true);\r\n }\r\n AllowableActionsImpl result = new AllowableActionsImpl();\r\n result.setAllowableActions(aas);\r\n return result;\r\n } catch (CmsException e) {\r\n handleCmsException(e);\r\n return null;\r\n }\r\n }",
"public static List<String> readLines(CharSequence self) throws IOException {\n return IOGroovyMethods.readLines(new StringReader(self.toString()));\n }",
"public static void redeployLinksAndTransformOperation(OperationContext context, ModelNode removeOperation, PathAddress deploymentsRootAddress, Set<String> runtimeNames) throws OperationFailedException {\n Set<String> deploymentNames = listDeployments(context.readResourceFromRoot(deploymentsRootAddress), runtimeNames);\n Operations.CompositeOperationBuilder opBuilder = Operations.CompositeOperationBuilder.create();\n if (deploymentNames.isEmpty()) {\n for (String s : runtimeNames) {\n ServerLogger.ROOT_LOGGER.debugf(\"We haven't found any deployment for %s in server-group %s\", s, deploymentsRootAddress.getLastElement().getValue());\n }\n }\n if(removeOperation != null) {\n opBuilder.addStep(removeOperation);\n }\n for (String deploymentName : deploymentNames) {\n opBuilder.addStep(addRedeployStep(deploymentsRootAddress.append(DEPLOYMENT, deploymentName)));\n }\n List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);\n if (transformers == null) {\n context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());\n }\n final ModelNode slave = opBuilder.build().getOperation();\n transformers.add(new OverlayOperationTransmuter(slave, context.getCurrentAddress()));\n }",
"public static void cache(XmlFileModel key, Document document)\n {\n String cacheKey = getKey(key);\n map.put(cacheKey, new CacheDocument(false, document));\n }",
"private static void generateContextDiagrams(RootDoc root, Options opt, String outputFolder)\n\t throws IOException {\n Set<ClassDoc> classDocs = new TreeSet<ClassDoc>(new Comparator<ClassDoc>() {\n public int compare(ClassDoc cd1, ClassDoc cd2) {\n return cd1.name().compareTo(cd2.name());\n }\n });\n for (ClassDoc classDoc : root.classes())\n classDocs.add(classDoc);\n\n\tContextView view = null;\n\tfor (ClassDoc classDoc : classDocs) {\n\t try {\n\t\tif(view == null)\n\t\t view = new ContextView(outputFolder, classDoc, root, opt);\n\t\telse\n\t\t view.setContextCenter(classDoc);\n\t\tUmlGraph.buildGraph(root, view, classDoc);\n\t\trunGraphviz(opt.dotExecutable, outputFolder, classDoc.containingPackage().name(), classDoc.name(), root);\n\t\talterHtmlDocs(opt, outputFolder, classDoc.containingPackage().name(), classDoc.name(),\n\t\t\tclassDoc.name() + \".html\", Pattern.compile(\".*(Class|Interface|Enum) \" + classDoc.name() + \".*\") , root);\n\t } catch (Exception e) {\n\t\tthrow new RuntimeException(\"Error generating \" + classDoc.name(), e);\n\t }\n\t}\n }",
"private static boolean equalAsInts(Vec2d a, Vec2d b) {\n return ((int) a.x) == ((int) b.x) && ((int) a.y) == ((int) b.y);\n }",
"public static TransactionalProtocolClient createClient(final ManagementChannelHandler channelAssociation) {\n final TransactionalProtocolClientImpl client = new TransactionalProtocolClientImpl(channelAssociation);\n channelAssociation.addHandlerFactory(client);\n return client;\n }",
"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 }",
"private static Document objectForInsert(Tuple tuple, Document dbObject) {\n\t\tMongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot();\n\t\tfor ( TupleOperation operation : tuple.getOperations() ) {\n\t\t\tString column = operation.getColumn();\n\t\t\tif ( notInIdField( snapshot, column ) ) {\n\t\t\t\tswitch ( operation.getType() ) {\n\t\t\t\t\tcase PUT:\n\t\t\t\t\t\tMongoHelpers.setValue( dbObject, column, operation.getValue() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase PUT_NULL:\n\t\t\t\t\tcase REMOVE:\n\t\t\t\t\t\tMongoHelpers.resetValue( dbObject, column );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn dbObject;\n\t}"
] |
Use this API to clear Interface resources. | [
"public static base_responses clear(nitro_service client, Interface resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tInterface clearresources[] = new Interface[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tclearresources[i] = new Interface();\n\t\t\t\tclearresources[i].id = resources[i].id;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, clearresources,\"clear\");\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public Stamp allocateTimestamp() {\n\n synchronized (this) {\n Preconditions.checkState(!closed, \"tracker closed \");\n\n if (node == null) {\n Preconditions.checkState(allocationsInProgress == 0,\n \"expected allocationsInProgress == 0 when node == null\");\n Preconditions.checkState(!updatingZk, \"unexpected concurrent ZK update\");\n\n createZkNode(getTimestamp().getTxTimestamp());\n }\n\n allocationsInProgress++;\n }\n\n try {\n Stamp ts = getTimestamp();\n\n synchronized (this) {\n timestamps.add(ts.getTxTimestamp());\n }\n\n return ts;\n } catch (RuntimeException re) {\n synchronized (this) {\n allocationsInProgress--;\n }\n throw re;\n }\n }",
"public void reverse() {\n for (int i = 0, size = mTransitionControls.size(); i < size; i++) {\n mTransitionControls.get(i).reverse();\n }\n }",
"protected final boolean isGLThread() {\n final Thread glThread = sGLThread.get();\n return glThread != null && glThread.equals(Thread.currentThread());\n }",
"public void setWorkConnection(CmsSetupDb db) {\n\n db.setConnection(\n m_setupBean.getDbDriver(),\n m_setupBean.getDbWorkConStr(),\n m_setupBean.getDbConStrParams(),\n m_setupBean.getDbWorkUser(),\n m_setupBean.getDbWorkPwd());\n }",
"private Class<?> beanType(String name) {\n\t\tClass<?> type = context.getType(name);\n\t\tif (ClassUtils.isCglibProxyClass(type)) {\n\t\t\treturn AopProxyUtils.ultimateTargetClass(context.getBean(name));\n\t\t}\n\t\treturn type;\n\t}",
"@Override\n public AuthInterface getAuthInterface() {\n if (authInterface == null) {\n authInterface = new AuthInterface(apiKey, sharedSecret, transport);\n }\n return authInterface;\n }",
"public void addPathToRequestResponseTable(int profileId, String clientUUID, int pathId) throws Exception {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection\n .prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \"(\" + Constants.REQUEST_RESPONSE_PATH_ID + \",\"\n + Constants.GENERIC_PROFILE_ID + \",\"\n + Constants.GENERIC_CLIENT_UUID + \",\"\n + Constants.REQUEST_RESPONSE_REPEAT_NUMBER + \",\"\n + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED + \",\"\n + Constants.REQUEST_RESPONSE_REQUEST_ENABLED + \",\"\n + Constants.REQUEST_RESPONSE_CUSTOM_RESPONSE + \",\"\n + Constants.REQUEST_RESPONSE_CUSTOM_REQUEST + \")\"\n + \" VALUES (?, ?, ?, ?, ?, ?, ?, ?);\");\n statement.setInt(1, pathId);\n statement.setInt(2, profileId);\n statement.setString(3, clientUUID);\n statement.setInt(4, -1);\n statement.setInt(5, 0);\n statement.setInt(6, 0);\n statement.setString(7, \"\");\n statement.setString(8, \"\");\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"public static boolean isSafe(Expression expression) {\r\n if (expression instanceof MethodCallExpression) {\r\n return ((MethodCallExpression) expression).isSafe();\r\n }\r\n if (expression instanceof PropertyExpression) {\r\n return ((PropertyExpression) expression).isSafe();\r\n }\r\n return false;\r\n }",
"public Collection<Group> getGroups() throws FlickrException {\r\n GroupList<Group> groups = new GroupList<Group>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_GROUPS);\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 groupsElement = response.getPayload();\r\n groups.setPage(groupsElement.getAttribute(\"page\"));\r\n groups.setPages(groupsElement.getAttribute(\"pages\"));\r\n groups.setPerPage(groupsElement.getAttribute(\"perpage\"));\r\n groups.setTotal(groupsElement.getAttribute(\"total\"));\r\n NodeList groupNodes = groupsElement.getElementsByTagName(\"group\");\r\n for (int i = 0; i < groupNodes.getLength(); i++) {\r\n Element groupElement = (Element) groupNodes.item(i);\r\n Group group = new Group();\r\n group.setId(groupElement.getAttribute(\"id\"));\r\n group.setName(groupElement.getAttribute(\"name\"));\r\n group.setAdmin(\"1\".equals(groupElement.getAttribute(\"admin\")));\r\n group.setPrivacy(groupElement.getAttribute(\"privacy\"));\r\n group.setIconServer(groupElement.getAttribute(\"iconserver\"));\r\n group.setIconFarm(groupElement.getAttribute(\"iconfarm\"));\r\n group.setPhotoCount(groupElement.getAttribute(\"photos\"));\r\n groups.add(group);\r\n }\r\n return groups;\r\n }"
] |
Returns the body of the request. This method is used to read posted JSON data.
@param request The request.
@return String representation of the request's body.
@throws IOException in case reading the request fails | [
"private String getRequestBody(ServletRequest request) throws IOException {\n\n final StringBuilder sb = new StringBuilder();\n\n String line = request.getReader().readLine();\n while (null != line) {\n sb.append(line);\n line = request.getReader().readLine();\n }\n\n return sb.toString();\n }"
] | [
"public boolean perform(Run<?, ?> build, Launcher launcher, TaskListener listener, EnvVars env, FilePath workDir, FilePath tempDir)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.getLogger().println(\"Couldn't find Maven home at \" + mavenHome.getRemote() + \" on agent \" + Utils.getAgentName(workDir) +\n \". This could be because this build is running inside a Docker container.\");\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, workDir, tempDir);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }",
"public void setCycleInterval(float newCycleInterval) {\n if ( (this.cycleInterval != newCycleInterval) && (newCycleInterval > 0) ) {\n for (GVRNodeAnimation gvrKeyFrameAnimation : gvrKeyFrameAnimations) {\n //TODO Cannot easily change the GVRAnimation's GVRChannel once set.\n }\n this.cycleInterval = newCycleInterval;\n }\n }",
"private void removeGroupIdFromTablePaths(int groupIdToRemove) {\n PreparedStatement queryStatement = null;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_PATH);\n results = queryStatement.executeQuery();\n // this is a hashamp from a pathId to the string of groups\n HashMap<Integer, String> idToGroups = new HashMap<Integer, String>();\n while (results.next()) {\n int pathId = results.getInt(Constants.GENERIC_ID);\n String stringGroupIds = results.getString(Constants.PATH_PROFILE_GROUP_IDS);\n int[] groupIds = Utils.arrayFromStringOfIntegers(stringGroupIds);\n String newGroupIds = \"\";\n for (int i = 0; i < groupIds.length; i++) {\n if (groupIds[i] != groupIdToRemove) {\n newGroupIds += (groupIds[i] + \",\");\n }\n }\n idToGroups.put(pathId, newGroupIds);\n }\n\n // now i want to go though the hashmap and for each pathId, add\n // update the newGroupIds\n for (Map.Entry<Integer, String> entry : idToGroups.entrySet()) {\n Integer pathId = entry.getKey();\n String newGroupIds = entry.getValue();\n\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH\n + \" SET \" + Constants.PATH_PROFILE_GROUP_IDS + \" = ? \"\n + \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, newGroupIds);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"protected String colorString(PDColor pdcolor)\n {\n String color = null;\n try\n {\n float[] rgb = pdcolor.getColorSpace().toRGB(pdcolor.getComponents());\n color = colorString(rgb[0], rgb[1], rgb[2]);\n } catch (IOException e) {\n log.error(\"colorString: IOException: {}\", e.getMessage());\n } catch (UnsupportedOperationException e) {\n log.error(\"colorString: UnsupportedOperationException: {}\", e.getMessage());\n }\n return color;\n }",
"private void processProperties(XMLStreamWriter writer, Set<Method> methodSet, Class<?> aClass) throws IntrospectionException, XMLStreamException\n {\n BeanInfo beanInfo = Introspector.getBeanInfo(aClass, aClass.getSuperclass());\n PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();\n\n for (int i = 0; i < propertyDescriptors.length; i++)\n {\n PropertyDescriptor propertyDescriptor = propertyDescriptors[i];\n if (propertyDescriptor.getPropertyType() != null)\n {\n String name = propertyDescriptor.getName();\n Method readMethod = propertyDescriptor.getReadMethod();\n Method writeMethod = propertyDescriptor.getWriteMethod();\n\n String readMethodName = readMethod == null ? null : readMethod.getName();\n String writeMethodName = writeMethod == null ? null : writeMethod.getName();\n addProperty(writer, name, propertyDescriptor.getPropertyType(), readMethodName, writeMethodName);\n\n if (readMethod != null)\n {\n methodSet.add(readMethod);\n }\n\n if (writeMethod != null)\n {\n methodSet.add(writeMethod);\n }\n }\n else\n {\n processAmbiguousProperty(writer, methodSet, aClass, propertyDescriptor);\n }\n }\n }",
"private void updateMaxMin(IntervalRBTreeNode<T> n, IntervalRBTreeNode<T> c) {\n if (c != null) {\n if (n.max < c.max) {\n n.max = c.max;\n }\n if (n.min > c.min) {\n n.min = c.min;\n }\n }\n }",
"public <T extends CanvasReader> T getReader(Class<T> type, OauthToken oauthToken, Integer paginationPageSize) {\n LOG.debug(\"Factory call to instantiate class: \" + type.getName());\n RestClient restClient = new RefreshingRestClient();\n\n @SuppressWarnings(\"unchecked\")\n Class<T> concreteClass = (Class<T>)readerMap.get(type);\n\n if (concreteClass == null) {\n throw new UnsupportedOperationException(\"No implementation for requested interface found: \" + type.getName());\n }\n\n LOG.debug(\"got class: \" + concreteClass);\n try {\n Constructor<T> constructor = concreteClass.getConstructor(String.class, Integer.class,\n OauthToken.class, RestClient.class, Integer.TYPE, Integer.TYPE, Integer.class, Boolean.class);\n return constructor.newInstance(canvasBaseUrl, CANVAS_API_VERSION, oauthToken, restClient,\n connectTimeout, readTimeout, paginationPageSize, false);\n } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {\n throw new UnsupportedOperationException(\"Unknown error instantiating the concrete API class: \" + type.getName(), e);\n }\n }",
"public void addProjectListeners(List<ProjectListener> listeners)\n {\n if (listeners != null)\n {\n for (ProjectListener listener : listeners)\n {\n addProjectListener(listener);\n }\n }\n }",
"protected void checkActiveState(Widget child) {\n // Check if this widget has a valid href\n String href = child.getElement().getAttribute(\"href\");\n String url = Window.Location.getHref();\n int pos = url.indexOf(\"#\");\n String location = pos >= 0 ? url.substring(pos, url.length()) : \"\";\n\n if (!href.isEmpty() && location.startsWith(href)) {\n ListItem li = findListItemParent(child);\n if (li != null) {\n makeActive(li);\n }\n } else if (child instanceof HasWidgets) {\n // Recursive check\n for (Widget w : (HasWidgets) child) {\n checkActiveState(w);\n }\n }\n }"
] |
Convert the holiday format from EquivalenceClassTransformer into a date format
@param holiday the date
@return a date String in the format yyyy-MM-dd | [
"public String convertToReadableDate(Holiday holiday) {\n DateTimeFormatter parser = ISODateTimeFormat.date();\n\n if (holiday.isInDateForm()) {\n String month = Integer.toString(holiday.getMonth()).length() < 2\n ? \"0\" + holiday.getMonth() : Integer.toString(holiday.getMonth());\n String day = Integer.toString(holiday.getDayOfMonth()).length() < 2\n ? \"0\" + holiday.getDayOfMonth() : Integer.toString(holiday.getDayOfMonth());\n return holiday.getYear() + \"-\" + month + \"-\" + day;\n } else {\n /*\n * 5 denotes the final occurrence of the day in the month. Need to find actual\n * number of occurrences\n */\n if (holiday.getOccurrence() == 5) {\n holiday.setOccurrence(numOccurrences(holiday.getYear(), holiday.getMonth(),\n holiday.getDayOfWeek()));\n }\n\n DateTime date = parser.parseDateTime(holiday.getYear() + \"-\"\n + holiday.getMonth() + \"-\" + \"01\");\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date.toDate());\n int count = 0;\n\n while (count < holiday.getOccurrence()) {\n if (calendar.get(Calendar.DAY_OF_WEEK) == holiday.getDayOfWeek()) {\n count++;\n if (count == holiday.getOccurrence()) {\n break;\n }\n }\n date = date.plusDays(1);\n calendar.setTime(date.toDate());\n }\n return date.toString().substring(0, 10);\n }\n }"
] | [
"private boolean computeUWV() {\n bidiag.getDiagonal(diag,off);\n qralg.setMatrix(numRowsT,numColsT,diag,off);\n\n// long pointA = System.currentTimeMillis();\n // compute U and V matrices\n if( computeU )\n Ut = bidiag.getU(Ut,true,compact);\n if( computeV )\n Vt = bidiag.getV(Vt,true,compact);\n\n qralg.setFastValues(false);\n if( computeU )\n qralg.setUt(Ut);\n else\n qralg.setUt(null);\n if( computeV )\n qralg.setVt(Vt);\n else\n qralg.setVt(null);\n\n// long pointB = System.currentTimeMillis();\n\n boolean ret = !qralg.process();\n\n// long pointC = System.currentTimeMillis();\n// System.out.println(\" compute UV \"+(pointB-pointA)+\" QR = \"+(pointC-pointB));\n\n return ret;\n }",
"@Override\n public void finish() {\n if (started.get() && !finished.getAndSet(true)) {\n waitUntilFinished();\n super.finish();\n // recreate thread (don't start) for processor reuse\n createProcessorThread();\n clearQueues();\n started.set(false);\n }\n }",
"public static <T> String listToString(List<T> list, final boolean justValue) {\r\n return listToString(list, justValue, null);\r\n }",
"public void loadAnimation(GVRAndroidResource animResource, String boneMap)\n {\n String filePath = animResource.getResourcePath();\n GVRContext ctx = mAvatarRoot.getGVRContext();\n GVRResourceVolume volume = new GVRResourceVolume(ctx, animResource);\n\n if (filePath.endsWith(\".bvh\"))\n {\n GVRAnimator animator = new GVRAnimator(ctx);\n animator.setName(filePath);\n try\n {\n BVHImporter importer = new BVHImporter(ctx);\n GVRSkeletonAnimation skelAnim;\n\n if (boneMap != null)\n {\n GVRSkeleton skel = importer.importSkeleton(animResource);\n skelAnim = importer.readMotion(skel);\n animator.addAnimation(skelAnim);\n\n GVRPoseMapper retargeter = new GVRPoseMapper(mSkeleton, skel, skelAnim.getDuration());\n retargeter.setBoneMap(boneMap);\n animator.addAnimation(retargeter);\n }\n else\n {\n skelAnim = importer.importAnimation(animResource, mSkeleton);\n animator.addAnimation(skelAnim);\n }\n addAnimation(animator);\n ctx.getEventManager().sendEvent(this,\n IAvatarEvents.class,\n \"onAnimationLoaded\",\n GVRAvatar.this,\n animator,\n filePath,\n null);\n }\n catch (IOException ex)\n {\n ctx.getEventManager().sendEvent(this,\n IAvatarEvents.class,\n \"onAnimationLoaded\",\n GVRAvatar.this,\n null,\n filePath,\n ex.getMessage());\n }\n }\n else\n {\n EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_TEXTURING));\n\n GVRSceneObject animRoot = new GVRSceneObject(ctx);\n ctx.getAssetLoader().loadModel(volume, animRoot, settings, false, mLoadAnimHandler);\n }\n }",
"public void addImportedPackages(String... importedPackages) {\n\t\tString oldBundles = mainAttributes.get(IMPORT_PACKAGE);\n\t\tif (oldBundles == null)\n\t\t\toldBundles = \"\";\n\t\tBundleList oldResultList = BundleList.fromInput(oldBundles, newline);\n\t\tBundleList resultList = BundleList.fromInput(oldBundles, newline);\n\t\tfor (String bundle : importedPackages)\n\t\t\tresultList.mergeInto(Bundle.fromInput(bundle));\n\t\tString result = resultList.toString();\n\t\tboolean changed = !oldResultList.toString().equals(result);\n\t\tmodified |= changed;\n\t\tif (changed)\n\t\t\tmainAttributes.put(IMPORT_PACKAGE, result);\n\t}",
"public IOrientationState getOrientationStateFromParam(int orientation) {\n switch (orientation) {\n case Orientation.ORIENTATION_HORIZONTAL_BOTTOM:\n return new OrientationStateHorizontalBottom();\n case Orientation.ORIENTATION_HORIZONTAL_TOP:\n return new OrientationStateHorizontalTop();\n case Orientation.ORIENTATION_VERTICAL_LEFT:\n return new OrientationStateVerticalLeft();\n case Orientation.ORIENTATION_VERTICAL_RIGHT:\n return new OrientationStateVerticalRight();\n default:\n return new OrientationStateHorizontalBottom();\n }\n }",
"private boolean isReadRequired(ValueGeneration valueGeneration, GenerationTiming matchTiming) {\n\t\treturn valueGeneration != null && valueGeneration.getValueGenerator() == null &&\n\t\t\t\ttimingsMatch( valueGeneration.getGenerationTiming(), matchTiming );\n\t}",
"public boolean uploadConfigurationAndProfile(String fileName, String odoImport) {\n File file = new File(fileName);\n MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();\n FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA);\n multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);\n multipartEntityBuilder.addPart(\"fileData\", fileBody);\n multipartEntityBuilder.addTextBody(\"odoImport\", odoImport);\n try {\n JSONObject response = new JSONObject(doMultipartPost(BASE_BACKUP_PROFILE + \"/\" + uriEncode(this._profileName) + \"/\" + this._clientId, multipartEntityBuilder));\n if (response.length() == 0) {\n return true;\n } else {\n return false;\n }\n } catch (Exception e) {\n return false;\n }\n }",
"public boolean detectTierIphone() {\r\n\r\n if (detectIphoneOrIpod()\r\n || detectAndroidPhone()\r\n || detectWindowsPhone()\r\n || detectBlackBerry10Phone()\r\n || (detectBlackBerryWebKit() && detectBlackBerryTouch())\r\n || detectPalmWebOS()\r\n || detectBada()\r\n || detectTizen()\r\n || detectFirefoxOSPhone()\r\n || detectSailfishPhone()\r\n || detectUbuntuPhone()\r\n || detectGamingHandheld()) {\r\n return true;\r\n }\r\n return false;\r\n }"
] |
Formats a double value.
@param number numeric value
@return Double instance | [
"private Double getDouble(Number number)\n {\n Double result = null;\n\n if (number != null)\n {\n result = Double.valueOf(number.doubleValue());\n }\n\n return result;\n }"
] | [
"public TimephasedWorkContainer getBaselineWork(ResourceAssignment assignment, ProjectCalendar calendar, TimephasedWorkNormaliser normaliser, byte[] data, boolean raw)\n {\n TimephasedWorkContainer result = null;\n\n if (data != null && data.length > 0)\n {\n LinkedList<TimephasedWork> list = null;\n\n //System.out.println(ByteArrayHelper.hexdump(data, false));\n int index = 8; // 8 byte header\n int blockSize = 40;\n double previousCumulativeWorkPerformedInMinutes = 0;\n\n Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 36);\n index += blockSize;\n TimephasedWork work = null;\n\n while (index + blockSize <= data.length)\n {\n double cumulativeWorkInMinutes = (double) ((long) MPPUtility.getDouble(data, index + 20)) / 1000;\n if (!Duration.durationValueEquals(cumulativeWorkInMinutes, previousCumulativeWorkPerformedInMinutes))\n {\n //double unknownWorkThisPeriodInMinutes = ((long) MPPUtility.getDouble(data, index + 0)) / 1000;\n double normalActualWorkThisPeriodInMinutes = ((double) MPPUtility.getInt(data, index + 8)) / 10;\n double normalRemainingWorkThisPeriodInMinutes = ((double) MPPUtility.getInt(data, index + 28)) / 10;\n double workThisPeriodInMinutes = cumulativeWorkInMinutes - previousCumulativeWorkPerformedInMinutes;\n double overtimeWorkThisPeriodInMinutes = workThisPeriodInMinutes - (normalActualWorkThisPeriodInMinutes + normalRemainingWorkThisPeriodInMinutes);\n double overtimeFactor = overtimeWorkThisPeriodInMinutes / (normalActualWorkThisPeriodInMinutes + normalRemainingWorkThisPeriodInMinutes);\n\n double normalWorkPerDayInMinutes = 480;\n double overtimeWorkPerDayInMinutes = normalWorkPerDayInMinutes * overtimeFactor;\n\n work = new TimephasedWork();\n work.setFinish(MPPUtility.getTimestampFromTenths(data, index + 16));\n work.setStart(blockStartDate);\n work.setTotalAmount(Duration.getInstance(workThisPeriodInMinutes, TimeUnit.MINUTES));\n work.setAmountPerDay(Duration.getInstance(normalWorkPerDayInMinutes + overtimeWorkPerDayInMinutes, TimeUnit.MINUTES));\n\n previousCumulativeWorkPerformedInMinutes = cumulativeWorkInMinutes;\n\n if (list == null)\n {\n list = new LinkedList<TimephasedWork>();\n }\n list.add(work);\n //System.out.println(work);\n }\n blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 36);\n index += blockSize;\n }\n\n if (list != null)\n {\n if (work != null)\n {\n work.setFinish(assignment.getFinish());\n }\n result = new DefaultTimephasedWorkContainer(calendar, normaliser, list, raw);\n }\n }\n\n return result;\n }",
"public static MarvinImage rgbToBinary(MarvinImage img, int threshold) {\n MarvinImage resultImage = new MarvinImage(img.getWidth(), img.getHeight(), MarvinImage.COLOR_MODEL_BINARY);\n\n for (int y = 0; y < img.getHeight(); y++) {\n for (int x = 0; x < img.getWidth(); x++) {\n int gray = (int) ((img.getIntComponent0(x, y) * 0.3) + (img.getIntComponent1(x, y) * 0.59) + (img.getIntComponent2(x, y) * 0.11));\n\n if (gray <= threshold) {\n resultImage.setBinaryColor(x, y, true);\n } else {\n resultImage.setBinaryColor(x, y, false);\n }\n }\n }\n return resultImage;\n }",
"private synchronized void closeIdleClients() {\n List<Client> candidates = new LinkedList<Client>(openClients.values());\n logger.debug(\"Scanning for idle clients; \" + candidates.size() + \" candidates.\");\n for (Client client : candidates) {\n if ((useCounts.get(client) < 1) &&\n ((timestamps.get(client) + idleLimit.get() * 1000) <= System.currentTimeMillis())) {\n logger.debug(\"Idle time reached for unused client {}\", client);\n closeClient(client);\n }\n }\n }",
"private CmsTemplateMapperConfiguration getConfiguration(final CmsObject cms) {\n\n if (!m_enabled) {\n return CmsTemplateMapperConfiguration.EMPTY_CONFIG;\n }\n\n if (m_configPath == null) {\n m_configPath = OpenCms.getSystemInfo().getConfigFilePath(cms, \"template-mapping.xml\");\n }\n\n return (CmsTemplateMapperConfiguration)(CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().loadVfsObject(\n cms,\n m_configPath,\n new Transformer() {\n\n @Override\n public Object transform(Object input) {\n\n try {\n CmsFile file = cms.readFile(m_configPath, CmsResourceFilter.IGNORE_EXPIRATION);\n SAXReader saxBuilder = new SAXReader();\n try (ByteArrayInputStream stream = new ByteArrayInputStream(file.getContents())) {\n Document document = saxBuilder.read(stream);\n CmsTemplateMapperConfiguration config = new CmsTemplateMapperConfiguration(cms, document);\n return config;\n }\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return new CmsTemplateMapperConfiguration(); // empty configuration, does not do anything\n }\n\n }\n }));\n }",
"static Map<String, Set<String>> getChildAddresses(final OperationContext context, final PathAddress addr, final ImmutableManagementResourceRegistration registry, Resource resource, final String validChildType) {\n\n Map<String, Set<String>> result = new HashMap<>();\n Predicate<String> validChildTypeFilter = childType -> (validChildType == null) || validChildType.equals(childType);\n\n if (resource != null) {\n for (String childType : registry.getChildNames(PathAddress.EMPTY_ADDRESS)) {\n if (validChildTypeFilter.test(childType)) {\n List<String> list = new ArrayList<>();\n for (String child : resource.getChildrenNames(childType)) {\n if (registry.getSubModel(PathAddress.pathAddress(PathElement.pathElement(childType, child))) != null) {\n list.add(child);\n }\n }\n result.put(childType, new LinkedHashSet<>(list));\n }\n }\n }\n\n Set<PathElement> paths = registry.getChildAddresses(PathAddress.EMPTY_ADDRESS);\n for (PathElement path : paths) {\n String childType = path.getKey();\n if (validChildTypeFilter.test(childType)) {\n Set<String> children = result.get(childType);\n if (children == null) {\n // WFLY-3306 Ensure we have an entry for any valid child type\n children = new LinkedHashSet<>();\n result.put(childType, children);\n }\n ImmutableManagementResourceRegistration childRegistration = registry.getSubModel(PathAddress.pathAddress(path));\n if (childRegistration != null) {\n AliasEntry aliasEntry = childRegistration.getAliasEntry();\n if (aliasEntry != null) {\n PathAddress childAddr = addr.append(path);\n PathAddress target = aliasEntry.convertToTargetAddress(childAddr, AliasContext.create(childAddr, context));\n assert !childAddr.equals(target) : \"Alias was not translated\";\n PathAddress targetParent = target.getParent();\n Resource parentResource = context.readResourceFromRoot(targetParent, false);\n if (parentResource != null) {\n PathElement targetElement = target.getLastElement();\n if (targetElement.isWildcard()) {\n children.addAll(parentResource.getChildrenNames(targetElement.getKey()));\n } else if (parentResource.hasChild(targetElement)) {\n children.add(path.getValue());\n }\n }\n }\n if (!path.isWildcard() && childRegistration.isRemote()) {\n children.add(path.getValue());\n }\n }\n }\n }\n\n return result;\n }",
"private float newRandomIndividualParticleRadius(@NonNull final SceneConfiguration scene) {\n return scene.getParticleRadiusMin() == scene.getParticleRadiusMax() ?\n scene.getParticleRadiusMin() : scene.getParticleRadiusMin() + (random.nextInt(\n (int) ((scene.getParticleRadiusMax() - scene.getParticleRadiusMin()) * 100f)))\n / 100f;\n }",
"private static void bodyWithBuilderAndSeparator(\n SourceBuilder code,\n Datatype datatype,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n String typename) {\n Variable result = new Variable(\"result\");\n Variable separator = new Variable(\"separator\");\n\n code.addLine(\" %1$s %2$s = new %1$s(\\\"%3$s{\\\");\", StringBuilder.class, result, typename);\n if (generatorsByProperty.size() > 1) {\n // If there's a single property, we don't actually use the separator variable\n code.addLine(\" %s %s = \\\"\\\";\", String.class, separator);\n }\n\n Property first = generatorsByProperty.keySet().iterator().next();\n Property last = getLast(generatorsByProperty.keySet());\n for (Property property : generatorsByProperty.keySet()) {\n PropertyCodeGenerator generator = generatorsByProperty.get(property);\n switch (generator.initialState()) {\n case HAS_DEFAULT:\n throw new RuntimeException(\"Internal error: unexpected default field\");\n\n case OPTIONAL:\n code.addLine(\" if (%s) {\", (Excerpt) generator::addToStringCondition);\n break;\n\n case REQUIRED:\n code.addLine(\" if (!%s.contains(%s.%s)) {\",\n UNSET_PROPERTIES, datatype.getPropertyEnum(), property.getAllCapsName());\n break;\n }\n code.add(\" \").add(result);\n if (property != first) {\n code.add(\".append(%s)\", separator);\n }\n code.add(\".append(\\\"%s=\\\").append(%s)\",\n property.getName(), (Excerpt) generator::addToStringValue);\n if (property != last) {\n code.add(\";%n %s = \\\", \\\"\", separator);\n }\n code.add(\";%n }%n\");\n }\n code.addLine(\" return %s.append(\\\"}\\\").toString();\", result);\n }",
"public Set<ConstraintViolation> validate(int record) {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\tfor (int ds = 0; ds < 250; ++ds) {\r\n\t\t\ttry {\r\n\t\t\t\tDataSetInfo dataSetInfo = dsiFactory.create(IIM.DS(record, ds));\r\n\t\t\t\terrors.addAll(validate(dataSetInfo));\r\n\t\t\t} catch (InvalidDataSetException ignored) {\r\n\t\t\t\t// DataSetFactory doesn't know about this ds, so will skip it\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn errors;\r\n\t}",
"protected static boolean numericEquals(Field vector1, Field vector2) {\n\t\tif (vector1.size() != vector2.size())\n\t\t\treturn false;\n\t\tif (vector1.isEmpty())\n\t\t\treturn true;\n\n\t\tIterator<Object> it1 = vector1.iterator();\n\t\tIterator<Object> it2 = vector2.iterator();\n\n\t\twhile (it1.hasNext()) {\n\t\t\tObject obj1 = it1.next();\n\t\t\tObject obj2 = it2.next();\n\n\t\t\tif (!(obj1 instanceof Number && obj2 instanceof Number))\n\t\t\t\treturn false;\n\n\t\t\tif (((Number) obj1).doubleValue() != ((Number) obj2).doubleValue())\n\t\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}"
] |
Obtains a Coptic local date-time from another date-time object.
@param temporal the date-time object to convert, not null
@return the Coptic local date-time, not null
@throws DateTimeException if unable to create the date-time | [
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<CopticDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<CopticDate>) super.localDateTime(temporal);\n }"
] | [
"public void addTags(String photoId, String[] tags) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD_TAGS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"tags\", StringUtilities.join(tags, \" \", true));\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"private void renameReadOnlyV2Files(int masterPartitionId, int correctReplicaType) {\n for (int replica = 0; replica < routingStrategy.getNumReplicas(); replica++) {\n if (replica != correctReplicaType) {\n int chunkId = 0;\n while (true) {\n String fileName = Integer.toString(masterPartitionId) + \"_\"\n + Integer.toString(replica) + \"_\"\n + Integer.toString(chunkId);\n File index = getIndexFile(fileName);\n File data = getDataFile(fileName);\n\n if(index.exists() && data.exists()) {\n // We found files with the \"wrong\" replica type, so let's rename them\n\n String correctFileName = Integer.toString(masterPartitionId) + \"_\"\n + Integer.toString(correctReplicaType) + \"_\"\n + Integer.toString(chunkId);\n File indexWithCorrectReplicaType = getIndexFile(correctFileName);\n File dataWithCorrectReplicaType = getDataFile(correctFileName);\n\n Utils.move(index, indexWithCorrectReplicaType);\n Utils.move(data, dataWithCorrectReplicaType);\n\n // Maybe change this to DEBUG?\n logger.info(\"Renamed files with wrong replica type: \"\n + index.getAbsolutePath() + \"|data -> \"\n + indexWithCorrectReplicaType.getName() + \"|data\");\n } else if(index.exists() ^ data.exists()) {\n throw new VoldemortException(\"One of the following does not exist: \"\n + index.toString()\n + \" or \"\n + data.toString() + \".\");\n } else {\n // The files don't exist, or we've gone over all available chunks,\n // so let's move on.\n break;\n }\n chunkId++;\n }\n }\n }\n }",
"public static final TimeUnit parseWorkUnits(BigInteger value)\n {\n TimeUnit result = TimeUnit.HOURS;\n\n if (value != null)\n {\n switch (value.intValue())\n {\n case 1:\n {\n result = TimeUnit.MINUTES;\n break;\n }\n\n case 3:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 4:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 5:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 7:\n {\n result = TimeUnit.YEARS;\n break;\n }\n\n default:\n case 2:\n {\n result = TimeUnit.HOURS;\n break;\n }\n }\n }\n\n return (result);\n }",
"public Object getColumnValue(String columnName) {\n\t\tfor ( int j = 0; j < columnNames.length; j++ ) {\n\t\t\tif ( columnNames[j].equals( columnName ) ) {\n\t\t\t\treturn columnValues[j];\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"private List<ParameterConverter> methodReturningConverters(final Class<?> type) {\n final List<ParameterConverter> converters = new ArrayList<>();\n for (final Method method : type.getMethods()) {\n if (method.isAnnotationPresent(AsParameterConverter.class)) {\n converters.add(new MethodReturningConverter(method, type, this));\n }\n }\n return converters;\n }",
"public static void createDotStoryFile(String scenarioName,\n String srcTestRootFolder, String packagePath,\n String givenDescription, String whenDescription,\n String thenDescription) throws BeastException {\n String[] folders = packagePath.split(\".\");\n for (String folder : folders) {\n srcTestRootFolder += \"/\" + folder;\n }\n\n FileWriter writer = createFileWriter(createDotStoryName(scenarioName),\n packagePath, srcTestRootFolder);\n try {\n writer.write(\"Scenario: \" + scenarioName + \"\\n\");\n writer.write(\"Given \" + givenDescription + \"\\n\");\n writer.write(\"When \" + whenDescription + \"\\n\");\n writer.write(\"Then \" + thenDescription + \"\\n\");\n writer.close();\n } catch (Exception e) {\n String message = \"Unable to write the .story file for the scenario \"\n + scenarioName;\n logger.severe(message);\n logger.severe(e.getMessage());\n throw new BeastException(message, e);\n }\n }",
"public void insert( Token where , Token token ) {\n if( where == null ) {\n // put at the front of the list\n if( size == 0 )\n push(token);\n else {\n first.previous = token;\n token.previous = null;\n token.next = first;\n first = token;\n size++;\n }\n } else if( where == last || null == last ) {\n push(token);\n } else {\n token.next = where.next;\n token.previous = where;\n where.next.previous = token;\n where.next = token;\n size++;\n }\n }",
"private void skip() {\n try {\n int blockSize;\n do {\n blockSize = read();\n rawData.position(rawData.position() + blockSize);\n } while (blockSize > 0);\n } catch (IllegalArgumentException ex) {\n }\n }",
"public Map<String, Integer> getAggregateResultCountSummary() {\n\n Map<String, Integer> summaryMap = new LinkedHashMap<String, Integer>();\n\n for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap\n .entrySet()) {\n summaryMap.put(entry.getKey(), entry.getValue().size());\n }\n\n return summaryMap;\n }"
] |
Convenience method dispatches the specified event to the source appender,
which will result in the custom event data being appended to the new file.
@param customLoggingEvent
The custom Log4J event to be appended. | [
"final void dispatchToAppender(final LoggingEvent customLoggingEvent) {\n // wrap the LoggingEvent in a FileRollEvent to prevent recursion bug\n final FoundationFileRollingAppender appender = this.getSource();\n if (appender != null) {\n appender.append(new FileRollEvent(customLoggingEvent, this));\n }\n }"
] | [
"@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 }",
"private void writeAssignmentExtendedAttributes(Project.Assignments.Assignment xml, ResourceAssignment mpx)\n {\n Project.Assignments.Assignment.ExtendedAttribute attrib;\n List<Project.Assignments.Assignment.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute();\n\n for (AssignmentField mpxFieldID : getAllAssignmentExtendedAttributes())\n {\n Object value = mpx.getCachedValue(mpxFieldID);\n\n if (FieldTypeHelper.valueIsNotDefault(mpxFieldID, value))\n {\n m_extendedAttributesInUse.add(mpxFieldID);\n\n Integer xmlFieldID = Integer.valueOf(MPPAssignmentField.getID(mpxFieldID) | MPPAssignmentField.ASSIGNMENT_FIELD_BASE);\n\n attrib = m_factory.createProjectAssignmentsAssignmentExtendedAttribute();\n extendedAttributes.add(attrib);\n attrib.setFieldID(xmlFieldID.toString());\n attrib.setValue(DatatypeConverter.printExtendedAttribute(this, value, mpxFieldID.getDataType()));\n attrib.setDurationFormat(printExtendedAttributeDurationFormat(value));\n }\n }\n }",
"private String formatConstraintType(ConstraintType type)\n {\n return (type == null ? null : LocaleData.getStringArray(m_locale, LocaleData.CONSTRAINT_TYPES)[type.getValue()]);\n }",
"private String[] getDatePatterns(ProjectProperties properties)\n {\n String pattern = \"\";\n\n char datesep = properties.getDateSeparator();\n DateOrder dateOrder = properties.getDateOrder();\n\n switch (dateOrder)\n {\n case DMY:\n {\n pattern = \"dd\" + datesep + \"MM\" + datesep + \"yy\";\n break;\n }\n\n case MDY:\n {\n pattern = \"MM\" + datesep + \"dd\" + datesep + \"yy\";\n break;\n }\n\n case YMD:\n {\n pattern = \"yy\" + datesep + \"MM\" + datesep + \"dd\";\n break;\n }\n }\n\n return new String[]\n {\n pattern\n };\n }",
"public TransformersSubRegistration getServerRegistration(final ModelVersionRange range) {\n final PathAddress address = PathAddress.EMPTY_ADDRESS.append(HOST, SERVER);\n return new TransformersSubRegistrationImpl(range, domain, address);\n }",
"public static boolean checkDuplicateElements(DMatrixSparseCSC A ) {\n A = A.copy(); // create a copy so that it doesn't modify A\n A.sortIndices(null);\n return !checkSortedFlag(A);\n }",
"public void setShowOutput(String mode) {\n try {\n this.outputMode = OutputMode.valueOf(mode.toUpperCase(Locale.ROOT));\n } catch (IllegalArgumentException e) {\n throw new IllegalArgumentException(\"showOutput accepts any of: \"\n + Arrays.toString(OutputMode.values()) + \", value is not valid: \" + mode);\n }\n }",
"public static void configure(Job conf, SimpleConfiguration props) {\n try {\n\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n props.save(baos);\n\n conf.getConfiguration().set(PROPS_CONF_KEY,\n new String(baos.toByteArray(), StandardCharsets.UTF_8));\n\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"public boolean hasUppercaseVariations(int base, boolean lowerOnly) {\n\t\tif(base > 10) {\n\t\t\tint count = getSegmentCount();\n\t\t\tfor(int i = 0; i < count; i++) {\n\t\t\t\tIPv6AddressSegment seg = getSegment(i);\n\t\t\t\tif(seg.hasUppercaseVariations(base, lowerOnly)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}"
] |
Set the individual dates.
@param dates the dates to set. | [
"public void setDates(SortedSet<Date> dates) {\n\n if (!m_model.getIndividualDates().equals(dates)) {\n m_model.setIndividualDates(dates);\n onValueChange();\n }\n\n }"
] | [
"public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {\n final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();\n final ServicesAttachment servicesAttachment = deploymentUnit.getAttachment(Attachments.SERVICES);\n if (servicesAttachment == null || servicesAttachment.getServiceImplementations(ServiceActivator.class.getName()).isEmpty()) {\n return; // Skip it if it has not been marked\n }\n final Module module = deploymentUnit.getAttachment(Attachments.MODULE);\n if (module == null) {\n return; // Skip deployments with no module\n }\n\n AttachmentList<DeploymentUnit> duList = deploymentUnit.getAttachment(Attachments.SUB_DEPLOYMENTS);\n List<String> serviceAcitvatorList = new ArrayList<String>();\n if (duList!=null && !duList.isEmpty()) {\n for (DeploymentUnit du : duList) {\n ServicesAttachment duServicesAttachment = du.getAttachment(Attachments.SERVICES);\n for (String serv : duServicesAttachment.getServiceImplementations(ServiceActivator.class.getName())) {\n serviceAcitvatorList.add(serv);\n }\n }\n }\n\n ServiceRegistry serviceRegistry = phaseContext.getServiceRegistry();\n if (WildFlySecurityManager.isChecking()) {\n //service registry allows you to modify internal server state across all deployments\n //if a security manager is present we use a version that has permission checks\n serviceRegistry = new SecuredServiceRegistry(serviceRegistry);\n }\n final ServiceActivatorContext serviceActivatorContext = new ServiceActivatorContextImpl(phaseContext.getServiceTarget(), serviceRegistry);\n\n final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();\n\n try {\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(module.getClassLoader());\n for (ServiceActivator serviceActivator : module.loadService(ServiceActivator.class)) {\n try {\n for (String serv : servicesAttachment.getServiceImplementations(ServiceActivator.class.getName())) {\n if (serv.compareTo(serviceActivator.getClass().getName()) == 0 && !serviceAcitvatorList.contains(serv)) {\n serviceActivator.activate(serviceActivatorContext);\n break;\n }\n }\n } catch (ServiceRegistryException e) {\n throw new DeploymentUnitProcessingException(e);\n }\n }\n } finally {\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current);\n }\n }",
"public static double[] getTileLayerSize(TileCode code, Envelope maxExtent, double scale) {\n\t\tdouble div = Math.pow(2, code.getTileLevel());\n\t\tdouble tileWidth = Math.ceil((scale * maxExtent.getWidth()) / div) / scale;\n\t\tdouble tileHeight = Math.ceil((scale * maxExtent.getHeight()) / div) / scale;\n\t\treturn new double[] { tileWidth, tileHeight };\n\t}",
"protected FluentModelTImpl prepareForFutureCommitOrPostRun(FluentModelTImpl childResource) {\n if (this.isPostRunMode) {\n if (!childResource.taskGroup().dependsOn(this.parentTaskGroup)) {\n this.parentTaskGroup.addPostRunDependentTaskGroup(childResource.taskGroup());\n }\n return childResource;\n } else {\n return childResource;\n }\n }",
"protected void convertSearchResults(final Collection<CmsSearchResource> searchResults) {\n\n m_foundResources = new ArrayList<I_CmsSearchResourceBean>();\n for (final CmsSearchResource searchResult : searchResults) {\n m_foundResources.add(new CmsSearchResourceBean(searchResult, m_cmsObject));\n }\n }",
"public ItemRequest<Section> insertInProject(String project) {\n \n String path = String.format(\"/projects/%s/sections/insert\", project);\n return new ItemRequest<Section>(this, Section.class, path, \"POST\");\n }",
"private void readChunkIfNeeded() {\n if (workBufferSize > workBufferPosition) {\n return;\n }\n if (workBuffer == null) {\n workBuffer = bitmapProvider.obtainByteArray(WORK_BUFFER_SIZE);\n }\n workBufferPosition = 0;\n workBufferSize = Math.min(rawData.remaining(), WORK_BUFFER_SIZE);\n rawData.get(workBuffer, 0, workBufferSize);\n }",
"public Date getStart()\n {\n Date result = (Date) getCachedValue(AssignmentField.START);\n if (result == null)\n {\n result = getTask().getStart();\n }\n return result;\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 static base_response add(nitro_service client, policydataset resource) throws Exception {\n\t\tpolicydataset addresource = new policydataset();\n\t\taddresource.name = resource.name;\n\t\taddresource.type = resource.type;\n\t\taddresource.indextype = resource.indextype;\n\t\treturn addresource.add_resource(client);\n\t}"
] |
Runs the currently entered query and displays the results. | [
"protected void runQuery() {\n\n String pool = m_pool.getValue();\n String stmt = m_script.getValue();\n if (stmt.trim().isEmpty()) {\n return;\n }\n CmsStringBufferReport report = new CmsStringBufferReport(Locale.ENGLISH);\n List<Throwable> errors = new ArrayList<>();\n CmsSqlConsoleResults result = m_console.execute(stmt, pool, report, errors);\n if (errors.size() > 0) {\n CmsErrorDialog.showErrorDialog(report.toString() + errors.get(0).getMessage(), errors.get(0));\n } else {\n Window window = CmsBasicDialog.prepareWindow(DialogWidth.max);\n window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_SQLCONSOLE_QUERY_RESULTS_0));\n window.setContent(new CmsSqlConsoleResultsForm(result, report.toString()));\n A_CmsUI.get().addWindow(window);\n window.center();\n }\n\n }"
] | [
"private void readTasks()\n {\n Integer rootID = Integer.valueOf(1);\n readWBS(m_projectFile, rootID);\n readTasks(rootID);\n m_projectFile.getTasks().synchronizeTaskIDToHierarchy();\n }",
"public static base_responses update(nitro_service client, gslbservice resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbservice updateresources[] = new gslbservice[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new gslbservice();\n\t\t\t\tupdateresources[i].servicename = resources[i].servicename;\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].publicip = resources[i].publicip;\n\t\t\t\tupdateresources[i].publicport = resources[i].publicport;\n\t\t\t\tupdateresources[i].cip = resources[i].cip;\n\t\t\t\tupdateresources[i].cipheader = resources[i].cipheader;\n\t\t\t\tupdateresources[i].sitepersistence = resources[i].sitepersistence;\n\t\t\t\tupdateresources[i].siteprefix = resources[i].siteprefix;\n\t\t\t\tupdateresources[i].maxclient = resources[i].maxclient;\n\t\t\t\tupdateresources[i].healthmonitor = resources[i].healthmonitor;\n\t\t\t\tupdateresources[i].maxbandwidth = resources[i].maxbandwidth;\n\t\t\t\tupdateresources[i].downstateflush = resources[i].downstateflush;\n\t\t\t\tupdateresources[i].maxaaausers = resources[i].maxaaausers;\n\t\t\t\tupdateresources[i].viewname = resources[i].viewname;\n\t\t\t\tupdateresources[i].viewip = resources[i].viewip;\n\t\t\t\tupdateresources[i].monthreshold = resources[i].monthreshold;\n\t\t\t\tupdateresources[i].weight = resources[i].weight;\n\t\t\t\tupdateresources[i].monitor_name_svc = resources[i].monitor_name_svc;\n\t\t\t\tupdateresources[i].hashid = resources[i].hashid;\n\t\t\t\tupdateresources[i].comment = resources[i].comment;\n\t\t\t\tupdateresources[i].appflowlog = resources[i].appflowlog;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"private void addMembersInclSupertypes(Collection memberNames, HashMap members, XClass type, String tagName, String paramName, String paramValue) throws XDocletException\r\n {\r\n addMembers(memberNames, members, type, tagName, paramName, paramValue);\r\n if (type.getInterfaces() != null) {\r\n for (Iterator it = type.getInterfaces().iterator(); it.hasNext(); ) {\r\n addMembersInclSupertypes(memberNames, members, (XClass)it.next(), tagName, paramName, paramValue);\r\n }\r\n }\r\n if (!type.isInterface() && (type.getSuperclass() != null)) {\r\n addMembersInclSupertypes(memberNames, members, type.getSuperclass(), tagName, paramName, paramValue);\r\n }\r\n }",
"private boolean absoluteBasic(int row)\r\n {\r\n boolean retval = false;\r\n \r\n if (row > m_current_row)\r\n {\r\n try\r\n {\r\n while (m_current_row < row && getRsAndStmt().m_rs.next())\r\n {\r\n m_current_row++;\r\n }\r\n if (m_current_row == row)\r\n {\r\n retval = true;\r\n }\r\n else\r\n {\r\n setHasCalledCheck(true);\r\n setHasNext(false);\r\n retval = false;\r\n autoReleaseDbResources();\r\n }\r\n }\r\n catch (Exception ex)\r\n {\r\n setHasCalledCheck(true);\r\n setHasNext(false);\r\n retval = false;\r\n }\r\n }\r\n else\r\n {\r\n logger.info(\"Your driver does not support advanced JDBC Functionality, \" +\r\n \"you cannot call absolute() with a position < current\");\r\n }\r\n return retval;\r\n }",
"public List<BindingInfo> getQueueBindings(String vhost, String queue) {\n final URI uri = uriWithPath(\"./queues/\" + encodePathSegment(vhost) +\n \"/\" + encodePathSegment(queue) + \"/bindings\");\n final BindingInfo[] result = this.rt.getForObject(uri, BindingInfo[].class);\n return asListOrNull(result);\n }",
"public Request option(String key, Object value) {\n this.options.put(key, value);\n return this;\n }",
"public Integer getNodesPartitionIdForKey(int nodeId, final byte[] key) {\n // this is all the partitions the key replicates to.\n List<Integer> partitionIds = getReplicatingPartitionList(key);\n for(Integer partitionId: partitionIds) {\n // check which of the replicating partitions belongs to the node in\n // question\n if(getNodeIdForPartitionId(partitionId) == nodeId) {\n return partitionId;\n }\n }\n return null;\n }",
"public void execute()\n {\n Runnable task = new Runnable()\n {\n public void run()\n {\n final V result = performTask();\n SwingUtilities.invokeLater(new Runnable()\n {\n public void run()\n {\n postProcessing(result);\n latch.countDown();\n }\n });\n }\n };\n new Thread(task, \"SwingBackgroundTask-\" + id).start();\n }",
"public static CharSequence getAt(CharSequence text, IntRange range) {\n return getAt(text, (Range) range);\n }"
] |
Returns the compact project status update records for all updates on the project.
@param project The project to find status updates for.
@return Request object | [
"public CollectionRequest<ProjectStatus> findByProject(String project) {\n\n String path = String.format(\"/projects/%s/project_statuses\", project);\n return new CollectionRequest<ProjectStatus>(this, ProjectStatus.class, path, \"GET\");\n }"
] | [
"public static double[][] pseudoInverse(double[][] matrix){\n\t\tif(isSolverUseApacheCommonsMath) {\n\t\t\t// Use LU from common math\n\t\t\tSingularValueDecomposition svd = new SingularValueDecomposition(new Array2DRowRealMatrix(matrix));\n\t\t\tdouble[][] matrixInverse = svd.getSolver().getInverse().getData();\n\n\t\t\treturn matrixInverse;\n\t\t}\n\t\telse {\n\t\t\treturn org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2();\n\t\t}\n\t}",
"public static base_response update(nitro_service client, gslbsite resource) throws Exception {\n\t\tgslbsite updateresource = new gslbsite();\n\t\tupdateresource.sitename = resource.sitename;\n\t\tupdateresource.metricexchange = resource.metricexchange;\n\t\tupdateresource.nwmetricexchange = resource.nwmetricexchange;\n\t\tupdateresource.sessionexchange = resource.sessionexchange;\n\t\tupdateresource.triggermonitor = resource.triggermonitor;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static GVRMesh createQuad(GVRContext gvrContext, float width, float height) {\n GVRMesh mesh = new GVRMesh(gvrContext);\n\n float[] vertices = { width * -0.5f, height * 0.5f, 0.0f, width * -0.5f,\n height * -0.5f, 0.0f, width * 0.5f, height * 0.5f, 0.0f,\n width * 0.5f, height * -0.5f, 0.0f };\n mesh.setVertices(vertices);\n\n final float[] normals = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f, 1.0f };\n mesh.setNormals(normals);\n\n final float[] texCoords = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,\n 1.0f };\n mesh.setTexCoords(texCoords);\n\n char[] triangles = { 0, 1, 2, 1, 3, 2 };\n mesh.setIndices(triangles);\n\n return mesh;\n }",
"public static final Path resolveSecurely(Path rootPath, String path) {\n Path resolvedPath;\n if(path == null || path.isEmpty()) {\n resolvedPath = rootPath.normalize();\n } else {\n String relativePath = removeSuperflousSlashes(path);\n resolvedPath = rootPath.resolve(relativePath).normalize();\n }\n if(!resolvedPath.startsWith(rootPath)) {\n throw DeploymentRepositoryLogger.ROOT_LOGGER.forbiddenPath(path);\n }\n return resolvedPath;\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 void finished() throws Throwable {\n if( state == FINISHED ) {\n return;\n }\n\n State previousState = state;\n\n state = FINISHED;\n methodInterceptor.enableMethodInterception( false );\n\n try {\n if( previousState == STARTED ) {\n callFinishLifeCycleMethods();\n }\n } finally {\n listener.scenarioFinished();\n }\n }",
"public void addFile(File file) {\n String name = \"file\";\n files.put(normalizeDuplicateName(name), file);\n }",
"static String md5(String input) {\n if (input == null || input.length() == 0) {\n throw new IllegalArgumentException(\"Input string must not be blank.\");\n }\n try {\n MessageDigest algorithm = MessageDigest.getInstance(\"MD5\");\n algorithm.reset();\n algorithm.update(input.getBytes());\n byte[] messageDigest = algorithm.digest();\n\n StringBuilder hexString = new StringBuilder();\n for (byte messageByte : messageDigest) {\n hexString.append(Integer.toHexString((messageByte & 0xFF) | 0x100).substring(1, 3));\n }\n return hexString.toString();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"public static LocalDate getDateFromFloatingPointDate(LocalDate referenceDate, double floatingPointDate) {\n\t\tif(referenceDate == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn referenceDate.plusDays((int)Math.round(floatingPointDate*365.0));\n\t}"
] |
Sets the proxy class to be used.
@param newProxyClass java.lang.Class | [
"public void setProxyClass(Class newProxyClass)\r\n {\r\n proxyClass = newProxyClass;\r\n if (proxyClass == null)\r\n {\r\n setProxyClassName(null);\r\n }\r\n else\r\n {\r\n proxyClassName = proxyClass.getName();\r\n }\r\n }"
] | [
"private static List<Class<?>> getClassHierarchy(Class<?> clazz) {\n\t\tList<Class<?>> hierarchy = new ArrayList<Class<?>>( 4 );\n\n\t\tfor ( Class<?> current = clazz; current != null; current = current.getSuperclass() ) {\n\t\t\thierarchy.add( current );\n\t\t}\n\n\t\treturn hierarchy;\n\t}",
"protected String ensureTextColorFormat(String textColor) {\n String formatted = \"\";\n boolean mainColor = true;\n for (String style : textColor.split(\" \")) {\n if (mainColor) {\n // the main color\n if (!style.endsWith(\"-text\")) {\n style += \"-text\";\n }\n mainColor = false;\n } else {\n // the shading type\n if (!style.startsWith(\"text-\")) {\n style = \" text-\" + style;\n }\n }\n formatted += style;\n }\n return formatted;\n }",
"private boolean shouldWrapMethodCall(String methodName) {\n if (methodList == null) {\n return true; // Wrap all by default\n }\n\n if (methodList.contains(methodName)) {\n return true; //Wrap a specific method\n }\n\n // If I get to this point, I should not wrap the call.\n return false;\n }",
"public CliCommandBuilder setController(final String protocol, final String hostname, final int port) {\n setController(formatAddress(protocol, hostname, port));\n return this;\n }",
"public PayloadBuilder customField(final String key, final Object value) {\n root.put(key, value);\n return this;\n }",
"static boolean isEmptyWhitespace(@Nullable final String s) {\n if (s == null) {\n return true;\n }\n return CharMatcher.WHITESPACE.matchesAllOf(s);\n }",
"public Collection<String> getMethods() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_METHODS);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element methodsElement = response.getPayload();\r\n\r\n List<String> methods = new ArrayList<String>();\r\n NodeList methodElements = methodsElement.getElementsByTagName(\"method\");\r\n for (int i = 0; i < methodElements.getLength(); i++) {\r\n Element methodElement = (Element) methodElements.item(i);\r\n methods.add(XMLUtilities.getValue(methodElement));\r\n }\r\n return methods;\r\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 }",
"public boolean isResourceExcluded(final PathAddress address) {\n if (!localHostControllerInfo.isMasterDomainController() && address.size() > 0) {\n IgnoredDomainResourceRoot root = this.rootResource;\n PathElement firstElement = address.getElement(0);\n IgnoreDomainResourceTypeResource typeResource = root == null ? null : root.getChildInternal(firstElement.getKey());\n if (typeResource != null) {\n if (typeResource.hasName(firstElement.getValue())) {\n return true;\n }\n }\n }\n return false;\n }"
] |
Get the object responsible for printing to the correct output format.
@param specJson the request json from the client | [
"public final OutputFormat getOutputFormat(final PJsonObject specJson) {\n final String format = specJson.getString(MapPrinterServlet.JSON_OUTPUT_FORMAT);\n final boolean mapExport =\n this.configuration.getTemplate(specJson.getString(Constants.JSON_LAYOUT_KEY)).isMapExport();\n final String beanName =\n format + (mapExport ? MAP_OUTPUT_FORMAT_BEAN_NAME_ENDING : OUTPUT_FORMAT_BEAN_NAME_ENDING);\n\n if (!this.outputFormat.containsKey(beanName)) {\n throw new RuntimeException(\"Format '\" + format + \"' with mapExport '\" + mapExport\n + \"' is not supported.\");\n }\n\n return this.outputFormat.get(beanName);\n }"
] | [
"public void revisitThrowEvents(Definitions def) {\n List<RootElement> rootElements = def.getRootElements();\n List<Signal> toAddSignals = new ArrayList<Signal>();\n Set<Error> toAddErrors = new HashSet<Error>();\n Set<Escalation> toAddEscalations = new HashSet<Escalation>();\n Set<Message> toAddMessages = new HashSet<Message>();\n Set<ItemDefinition> toAddItemDefinitions = new HashSet<ItemDefinition>();\n for (RootElement root : rootElements) {\n if (root instanceof Process) {\n setThrowEventsInfo((Process) root,\n def,\n rootElements,\n toAddSignals,\n toAddErrors,\n toAddEscalations,\n toAddMessages,\n toAddItemDefinitions);\n }\n }\n for (Lane lane : _lanes) {\n setThrowEventsInfoForLanes(lane,\n def,\n rootElements,\n toAddSignals,\n toAddErrors,\n toAddEscalations,\n toAddMessages,\n toAddItemDefinitions);\n }\n for (Signal s : toAddSignals) {\n def.getRootElements().add(s);\n }\n for (Error er : toAddErrors) {\n def.getRootElements().add(er);\n }\n for (Escalation es : toAddEscalations) {\n def.getRootElements().add(es);\n }\n for (ItemDefinition idef : toAddItemDefinitions) {\n def.getRootElements().add(idef);\n }\n for (Message msg : toAddMessages) {\n def.getRootElements().add(msg);\n }\n }",
"public static void unregisterContextualInstance(EjbDescriptor<?> descriptor) {\n Set<Class<?>> classes = CONTEXTUAL_SESSION_BEANS.get();\n classes.remove(descriptor.getBeanClass());\n if (classes.isEmpty()) {\n CONTEXTUAL_SESSION_BEANS.remove();\n }\n }",
"private void initXmlBundle() throws CmsException {\n\n CmsFile file = m_cms.readFile(m_resource);\n m_bundleFiles.put(null, m_resource);\n m_xmlBundle = CmsXmlContentFactory.unmarshal(m_cms, file);\n initKeySetForXmlBundle();\n\n }",
"private Class getDynamicProxyClass(Class baseClass) {\r\n Class[] m_dynamicProxyClassInterfaces;\r\n if (foundInterfaces.containsKey(baseClass)) {\r\n m_dynamicProxyClassInterfaces = (Class[])foundInterfaces.get(baseClass);\r\n } else {\r\n m_dynamicProxyClassInterfaces = getInterfaces(baseClass);\r\n foundInterfaces.put(baseClass, m_dynamicProxyClassInterfaces);\r\n }\r\n\r\n // return dynymic Proxy Class implementing all interfaces\r\n Class proxyClazz = Proxy.getProxyClass(baseClass.getClassLoader(), m_dynamicProxyClassInterfaces);\r\n return proxyClazz;\r\n }",
"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 }",
"public App named(String name) {\n App newApp = copy();\n newApp.name = name;\n return newApp;\n }",
"public static responderglobal_responderpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tresponderglobal_responderpolicy_binding obj = new responderglobal_responderpolicy_binding();\n\t\tresponderglobal_responderpolicy_binding response[] = (responderglobal_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static ForwardCurveInterpolation createForwardCurveFromMonteCarloLiborModel(String name, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{\n\n\t\tint timeIndex\t= model.getTimeIndex(startTime);\n\t\t// Get all Libors at timeIndex which are not yet fixed (others null) and times for the timeDiscretizationFromArray of the curves\n\t\tArrayList<RandomVariable> liborsAtTimeIndex = new ArrayList<>();\n\t\tint firstLiborIndex = model.getLiborPeriodDiscretization().getTimeIndexNearestGreaterOrEqual(startTime);\n\t\tdouble firstLiborTime = model.getLiborPeriodDiscretization().getTime(firstLiborIndex);\n\t\tif(firstLiborTime>startTime) {\n\t\t\tliborsAtTimeIndex.add(model.getLIBOR(startTime, startTime, firstLiborTime));\n\t\t}\n\t\t// Vector of times for the forward curve\n\t\tdouble[] times = new double[firstLiborTime==startTime ? (model.getNumberOfLibors()-firstLiborIndex) : (model.getNumberOfLibors()-firstLiborIndex+1)];\n\t\ttimes[0]=0;\n\t\tint indexOffset = firstLiborTime==startTime ? 0 : 1;\n\t\tfor(int i=firstLiborIndex;i<model.getNumberOfLibors();i++) {\n\t\t\tliborsAtTimeIndex.add(model.getLIBOR(timeIndex,i));\n\t\t\ttimes[i-firstLiborIndex+indexOffset]=model.getLiborPeriodDiscretization().getTime(i)-startTime;\n\t\t}\n\n\t\tRandomVariable[] libors = liborsAtTimeIndex.toArray(new RandomVariable[liborsAtTimeIndex.size()]);\n\t\treturn ForwardCurveInterpolation.createForwardCurveFromForwards(name, times, libors, model.getLiborPeriodDiscretization().getTimeStep(firstLiborIndex));\n\n\t}",
"private void deliverAlbumArtUpdate(int player, AlbumArt art) {\n if (!getAlbumArtListeners().isEmpty()) {\n final AlbumArtUpdate update = new AlbumArtUpdate(player, art);\n for (final AlbumArtListener listener : getAlbumArtListeners()) {\n try {\n listener.albumArtChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering album art update to listener\", t);\n }\n }\n }\n }"
] |
This method extracts assignment data from an MSPDI file.
@param project Root node of the MSPDI file | [
"private void readAssignments(Project project)\n {\n Project.Assignments assignments = project.getAssignments();\n if (assignments != null)\n {\n SplitTaskFactory splitFactory = new SplitTaskFactory();\n TimephasedWorkNormaliser normaliser = new MSPDITimephasedWorkNormaliser();\n for (Project.Assignments.Assignment assignment : assignments.getAssignment())\n {\n readAssignment(assignment, splitFactory, normaliser);\n }\n }\n }"
] | [
"public CustomField getCustomField(FieldType field)\n {\n CustomField result = m_configMap.get(field);\n if (result == null)\n {\n result = new CustomField(field, this);\n m_configMap.put(field, result);\n }\n return result;\n }",
"public static void addTTLIndex(DBCollection collection, String field, int ttl) {\n if (ttl <= 0) {\n throw new IllegalArgumentException(\"TTL must be positive\");\n }\n collection.createIndex(new BasicDBObject(field, 1), new BasicDBObject(\"expireAfterSeconds\", ttl));\n }",
"public void abortExternalTx(TransactionImpl odmgTrans)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"abortExternTransaction was called\");\r\n if (odmgTrans == null) return;\r\n TxBuffer buf = (TxBuffer) txRepository.get();\r\n Transaction extTx = buf != null ? buf.getExternTx() : null;\r\n try\r\n {\r\n if (extTx != null && extTx.getStatus() == Status.STATUS_ACTIVE)\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Set extern transaction to rollback\");\r\n }\r\n extTx.setRollbackOnly();\r\n }\r\n }\r\n catch (Exception ignore)\r\n {\r\n }\r\n txRepository.set(null);\r\n }",
"String fetchToken(String tokenType) throws IOException, MediaWikiApiErrorException {\n\t\tMap<String, String> params = new HashMap<>();\n\t\tparams.put(ApiConnection.PARAM_ACTION, \"query\");\n\t\tparams.put(\"meta\", \"tokens\");\n\t\tparams.put(\"type\", tokenType);\n\n\t\ttry {\n\t\t\tJsonNode root = this.sendJsonRequest(\"POST\", params);\n\t\t\treturn root.path(\"query\").path(\"tokens\").path(tokenType + \"token\").textValue();\n\t\t} catch (IOException | MediaWikiApiErrorException e) {\n\t\t\tlogger.error(\"Error when trying to fetch token: \" + e.toString());\n\t\t}\n\t\treturn null;\n\t}",
"public static Date setTime(Date date, Date canonicalTime)\n {\n Date result;\n if (canonicalTime == null)\n {\n result = date;\n }\n else\n {\n //\n // The original naive implementation of this method generated\n // the \"start of day\" date (midnight) for the required day\n // then added the milliseconds from the canonical time\n // to move the time forward to the required point. Unfortunately\n // if the date we'e trying to do this for is the entry or\n // exit from DST, the result is wrong, hence I've switched to\n // the approach below.\n //\n Calendar cal = popCalendar(canonicalTime);\n int dayOffset = cal.get(Calendar.DAY_OF_YEAR) - 1;\n int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);\n int minute = cal.get(Calendar.MINUTE);\n int second = cal.get(Calendar.SECOND);\n int millisecond = cal.get(Calendar.MILLISECOND);\n\n cal.setTime(date);\n\n if (dayOffset != 0)\n {\n // The canonical time can be +1 day.\n // It's to do with the way we've historically\n // managed time ranges and midnight.\n cal.add(Calendar.DAY_OF_YEAR, dayOffset);\n }\n\n cal.set(Calendar.MILLISECOND, millisecond);\n cal.set(Calendar.SECOND, second);\n cal.set(Calendar.MINUTE, minute);\n cal.set(Calendar.HOUR_OF_DAY, hourOfDay);\n\n result = cal.getTime();\n pushCalendar(cal);\n }\n return result;\n }",
"protected void generateMopCalls(LinkedList<MethodNode> mopCalls, boolean useThis) {\n for (MethodNode method : mopCalls) {\n String name = getMopMethodName(method, useThis);\n Parameter[] parameters = method.getParameters();\n String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameters());\n MethodVisitor mv = controller.getClassVisitor().visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, name, methodDescriptor, null, null);\n controller.setMethodVisitor(mv);\n mv.visitVarInsn(ALOAD, 0);\n int newRegister = 1;\n OperandStack operandStack = controller.getOperandStack();\n for (Parameter parameter : parameters) {\n ClassNode type = parameter.getType();\n operandStack.load(parameter.getType(), newRegister);\n // increment to next register, double/long are using two places\n newRegister++;\n if (type == ClassHelper.double_TYPE || type == ClassHelper.long_TYPE) newRegister++;\n }\n operandStack.remove(parameters.length);\n ClassNode declaringClass = method.getDeclaringClass();\n // JDK 8 support for default methods in interfaces\n // this should probably be strenghtened when we support the A.super.foo() syntax\n int opcode = declaringClass.isInterface()?INVOKEINTERFACE:INVOKESPECIAL;\n mv.visitMethodInsn(opcode, BytecodeHelper.getClassInternalName(declaringClass), method.getName(), methodDescriptor, opcode == INVOKEINTERFACE);\n BytecodeHelper.doReturn(mv, method.getReturnType());\n mv.visitMaxs(0, 0);\n mv.visitEnd();\n controller.getClassNode().addMethod(name, ACC_PUBLIC | ACC_SYNTHETIC, method.getReturnType(), parameters, null, null);\n }\n }",
"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 static Calendar parseDividendDate(String date) {\n if (!Utils.isParseable(date)) {\n return null;\n }\n date = date.trim();\n SimpleDateFormat format = new SimpleDateFormat(Utils.getDividendDateFormat(date), Locale.US);\n format.setTimeZone(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n try {\n Calendar today = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n Calendar parsedDate = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n parsedDate.setTime(format.parse(date));\n\n if (parsedDate.get(Calendar.YEAR) == 1970) {\n // Not really clear which year the dividend date is... making a reasonable guess.\n int monthDiff = parsedDate.get(Calendar.MONTH) - today.get(Calendar.MONTH);\n int year = today.get(Calendar.YEAR);\n if (monthDiff > 6) {\n year -= 1;\n } else if (monthDiff < -6) {\n year += 1;\n }\n parsedDate.set(Calendar.YEAR, year);\n }\n\n return parsedDate;\n } catch (ParseException ex) {\n log.warn(\"Failed to parse dividend date: \" + date);\n log.debug(\"Failed to parse dividend date: \" + date, ex);\n return null;\n }\n }",
"public static void pushImage(String imageTag, String username, String password, String host) throws IOException {\n final AuthConfig authConfig = new AuthConfig();\n authConfig.withUsername(username);\n authConfig.withPassword(password);\n\n DockerClient dockerClient = null;\n try {\n dockerClient = getDockerClient(host);\n dockerClient.pushImageCmd(imageTag).withAuthConfig(authConfig).exec(new PushImageResultCallback()).awaitSuccess();\n } finally {\n closeQuietly(dockerClient);\n }\n }"
] |
Constructs a reference of the given type to the given
referent. The reference is registered with the queue
for later purging.
@param type HARD, SOFT or WEAK
@param referent the object to refer to
@param hash the hash code of the <I>key</I> of the mapping;
this number might be different from referent.hashCode() if
the referent represents a value and not a key | [
"private Object toReference(int type, Object referent, int hash)\r\n {\r\n switch (type)\r\n {\r\n case HARD:\r\n return referent;\r\n case SOFT:\r\n return new SoftRef(hash, referent, queue);\r\n case WEAK:\r\n return new WeakRef(hash, referent, queue);\r\n default:\r\n throw new Error();\r\n }\r\n }"
] | [
"public ItemRequest<Task> dependents(String task) {\n \n String path = String.format(\"/tasks/%s/dependents\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }",
"protected synchronized int loadSize() throws PersistenceBrokerException\r\n {\r\n PersistenceBroker broker = getBroker();\r\n try\r\n {\r\n return broker.getCount(getQuery());\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(ex);\r\n }\r\n finally\r\n {\r\n releaseBroker(broker);\r\n }\r\n }",
"public String renameApp(String appName, String newName) {\n return connection.execute(new AppRename(appName, newName), apiKey).getName();\n }",
"public static String getPrettyMapOfContiguousPartitionRunLengths(final Cluster cluster,\n int zoneId) {\n Map<Integer, Integer> runLengthToCount = getMapOfContiguousPartitionRunLengths(cluster,\n zoneId);\n String prettyHistogram = \"[\";\n boolean first = true;\n Set<Integer> runLengths = new TreeSet<Integer>(runLengthToCount.keySet());\n for(int runLength: runLengths) {\n if(first) {\n first = false;\n } else {\n prettyHistogram += \", \";\n }\n prettyHistogram += \"{\" + runLength + \" : \" + runLengthToCount.get(runLength) + \"}\";\n }\n prettyHistogram += \"]\";\n return prettyHistogram;\n }",
"public static<T> SessionVar<T> vendSessionVar(T defValue) {\n\treturn (new VarsJBridge()).vendSessionVar(defValue, new Exception());\n }",
"public ParallelTaskBuilder prepareHttpGet(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n \n cb.getHttpMeta().setHttpMethod(HttpMethod.GET);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n \n return cb;\n }",
"public Set<URI> collectOutgoingReferences(IResourceDescription description) {\n\t\tURI resourceURI = description.getURI();\n\t\tSet<URI> result = null;\n\t\tfor(IReferenceDescription reference: description.getReferenceDescriptions()) {\n\t\t\tURI targetResource = reference.getTargetEObjectUri().trimFragment();\n\t\t\tif (!resourceURI.equals(targetResource)) {\n\t\t\t\tif (result == null)\n\t\t\t\t\tresult = Sets.newHashSet(targetResource);\n\t\t\t\telse\n\t\t\t\t\tresult.add(targetResource);\n\t\t\t}\n\t\t}\n\t\tif (result != null)\n\t\t\treturn result;\n\t\treturn Collections.emptySet();\n\t}",
"protected void writeBody(HttpURLConnection connection, ProgressListener listener) {\n if (this.body == null) {\n return;\n }\n\n connection.setDoOutput(true);\n try {\n OutputStream output = connection.getOutputStream();\n if (listener != null) {\n output = new ProgressOutputStream(output, listener, this.bodyLength);\n }\n int b = this.body.read();\n while (b != -1) {\n output.write(b);\n b = this.body.read();\n }\n output.close();\n } catch (IOException e) {\n throw new BoxAPIException(\"Couldn't connect to the Box API due to a network error.\", e);\n }\n }",
"public void merge(final ResourceRoot additionalResourceRoot) {\n if(!additionalResourceRoot.getRoot().equals(root)) {\n throw ServerLogger.ROOT_LOGGER.cannotMergeResourceRoot(root, additionalResourceRoot.getRoot());\n }\n usePhysicalCodeSource = additionalResourceRoot.usePhysicalCodeSource;\n if(additionalResourceRoot.getExportFilters().isEmpty()) {\n //new root has no filters, so we don't want our existing filters to break anything\n //see WFLY-1527\n this.exportFilters.clear();\n } else {\n this.exportFilters.addAll(additionalResourceRoot.getExportFilters());\n }\n }"
] |
Returns the associated SQL WHERE statement. | [
"public String getStatement() throws SQLException {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tappendSql(null, sb, new ArrayList<ArgumentHolder>());\n\t\treturn sb.toString();\n\t}"
] | [
"public static base_responses save(nitro_service client, cacheobject resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheobject saveresources[] = new cacheobject[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tsaveresources[i] = new cacheobject();\n\t\t\t\tsaveresources[i].locator = resources[i].locator;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, saveresources,\"save\");\n\t\t}\n\t\treturn result;\n\t}",
"Renderer copy() {\n Renderer copy = null;\n try {\n copy = (Renderer) this.clone();\n } catch (CloneNotSupportedException e) {\n Log.e(\"Renderer\", \"All your renderers should be clonables.\");\n }\n return copy;\n }",
"public static vpnvserver_aaapreauthenticationpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_aaapreauthenticationpolicy_binding obj = new vpnvserver_aaapreauthenticationpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_aaapreauthenticationpolicy_binding response[] = (vpnvserver_aaapreauthenticationpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void processDays(ProjectCalendar calendar) throws Exception\n {\n // Default all days to non-working\n for (Day day : Day.values())\n {\n calendar.setWorkingDay(day, false);\n }\n\n List<Row> rows = getRows(\"select * from zcalendarrule where zcalendar1=? and z_ent=?\", calendar.getUniqueID(), m_entityMap.get(\"CalendarWeekDayRule\"));\n for (Row row : rows)\n {\n Day day = row.getDay(\"ZWEEKDAY\");\n String timeIntervals = row.getString(\"ZTIMEINTERVALS\");\n if (timeIntervals == null)\n {\n calendar.setWorkingDay(day, false);\n }\n else\n {\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n NodeList nodes = getNodeList(timeIntervals, m_dayTimeIntervals);\n calendar.setWorkingDay(day, nodes.getLength() > 0);\n\n for (int loop = 0; loop < nodes.getLength(); loop++)\n {\n NamedNodeMap attributes = nodes.item(loop).getAttributes();\n Date startTime = m_calendarTimeFormat.parse(attributes.getNamedItem(\"startTime\").getTextContent());\n Date endTime = m_calendarTimeFormat.parse(attributes.getNamedItem(\"endTime\").getTextContent());\n\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n hours.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }",
"public static WidgetLib init(GVRContext gvrContext, String customPropertiesAsset)\n throws InterruptedException, JSONException, NoSuchMethodException {\n if (mInstance == null) {\n // Constructor sets mInstance to ensure the initialization order\n new WidgetLib(gvrContext, customPropertiesAsset);\n }\n return mInstance.get();\n }",
"public static double[] singularValues( DMatrixRMaj A ) {\n SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(A.numRows,A.numCols,false,true,true);\n\n if( svd.inputModified() ) {\n A = A.copy();\n }\n if( !svd.decompose(A)) {\n throw new RuntimeException(\"SVD Failed!\");\n }\n\n double sv[] = svd.getSingularValues();\n Arrays.sort(sv,0,svd.numberOfSingularValues());\n\n // change the ordering to ascending\n for (int i = 0; i < sv.length/2; i++) {\n double tmp = sv[i];\n sv[i] = sv[sv.length-i-1];\n sv[sv.length-i-1] = tmp;\n }\n\n return sv;\n }",
"public static clusternodegroup_nslimitidentifier_binding[] get(nitro_service service, String name) throws Exception{\n\t\tclusternodegroup_nslimitidentifier_binding obj = new clusternodegroup_nslimitidentifier_binding();\n\t\tobj.set_name(name);\n\t\tclusternodegroup_nslimitidentifier_binding response[] = (clusternodegroup_nslimitidentifier_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private static void readAndAddDocumentsFromStream(\n final SolrClient client,\n final String lang,\n final InputStream is,\n final List<SolrInputDocument> documents,\n final boolean closeStream) {\n\n final BufferedReader br = new BufferedReader(new InputStreamReader(is));\n\n try {\n String line = br.readLine();\n while (null != line) {\n\n final SolrInputDocument document = new SolrInputDocument();\n // Each field is named after the schema \"entry_xx\" where xx denotes\n // the two digit language code. See the file spellcheck/conf/schema.xml.\n document.addField(\"entry_\" + lang, line);\n documents.add(document);\n\n // Prevent OutOfMemoryExceptions ...\n if (documents.size() >= MAX_LIST_SIZE) {\n addDocuments(client, documents, false);\n documents.clear();\n }\n\n line = br.readLine();\n }\n } catch (IOException e) {\n LOG.error(\"Could not read spellcheck dictionary from input stream.\");\n } catch (SolrServerException e) {\n LOG.error(\"Error while adding documents to Solr server. \");\n } finally {\n try {\n if (closeStream) {\n br.close();\n }\n } catch (Exception e) {\n // Nothing to do here anymore ....\n }\n }\n }",
"public static Object newInstance(Class target, Class type, Object arg) throws InstantiationException,\r\n IllegalAccessException,\r\n IllegalArgumentException,\r\n InvocationTargetException,\r\n NoSuchMethodException,\r\n SecurityException\r\n {\r\n return newInstance(target, new Class[]{ type }, new Object[]{ arg });\r\n }"
] |
Use this API to fetch the statistics of all audit_stats resources that are configured on netscaler. | [
"public static audit_stats get(nitro_service service, options option) throws Exception{\n\t\taudit_stats obj = new audit_stats();\n\t\taudit_stats[] response = (audit_stats[])obj.stat_resources(service,option);\n\t\treturn response[0];\n\t}"
] | [
"private static void writeToLog(Logger logger, Level level, String pattern, Exception exception) {\n if (level == Level.ERROR) {\n logger.error(pattern, exception);\n } else if (level == Level.INFO) {\n logger.info(pattern);\n } else if (level == Level.DEBUG) {\n logger.debug(pattern);\n }\n }",
"private void writeCalendar(ProjectCalendar mpxjCalendar, net.sf.mpxj.planner.schema.Calendar plannerCalendar) throws JAXBException\n {\n //\n // Populate basic details\n //\n plannerCalendar.setId(getIntegerString(mpxjCalendar.getUniqueID()));\n plannerCalendar.setName(getString(mpxjCalendar.getName()));\n\n //\n // Set working and non working days\n //\n DefaultWeek dw = m_factory.createDefaultWeek();\n plannerCalendar.setDefaultWeek(dw);\n dw.setMon(getWorkingDayString(mpxjCalendar, Day.MONDAY));\n dw.setTue(getWorkingDayString(mpxjCalendar, Day.TUESDAY));\n dw.setWed(getWorkingDayString(mpxjCalendar, Day.WEDNESDAY));\n dw.setThu(getWorkingDayString(mpxjCalendar, Day.THURSDAY));\n dw.setFri(getWorkingDayString(mpxjCalendar, Day.FRIDAY));\n dw.setSat(getWorkingDayString(mpxjCalendar, Day.SATURDAY));\n dw.setSun(getWorkingDayString(mpxjCalendar, Day.SUNDAY));\n\n //\n // Set working hours\n //\n OverriddenDayTypes odt = m_factory.createOverriddenDayTypes();\n plannerCalendar.setOverriddenDayTypes(odt);\n List<OverriddenDayType> typeList = odt.getOverriddenDayType();\n Sequence uniqueID = new Sequence(0);\n\n //\n // This is a bit arbitrary, so not ideal, however...\n // The idea here is that MS Project allows us to specify working hours\n // for each day of the week individually. Planner doesn't do this,\n // but instead allows us to specify working hours for each day type.\n // What we are doing here is stepping through the days of the week to\n // find the first working day, then using the hours for that day\n // as the hours for the working day type in Planner.\n //\n for (int dayLoop = 1; dayLoop < 8; dayLoop++)\n {\n Day day = Day.getInstance(dayLoop);\n if (mpxjCalendar.isWorkingDay(day))\n {\n processWorkingHours(mpxjCalendar, uniqueID, day, typeList);\n break;\n }\n }\n\n //\n // Process exception days\n //\n Days plannerDays = m_factory.createDays();\n plannerCalendar.setDays(plannerDays);\n List<net.sf.mpxj.planner.schema.Day> dayList = plannerDays.getDay();\n processExceptionDays(mpxjCalendar, dayList);\n\n m_eventManager.fireCalendarWrittenEvent(mpxjCalendar);\n\n //\n // Process any derived calendars\n //\n List<net.sf.mpxj.planner.schema.Calendar> calendarList = plannerCalendar.getCalendar();\n\n for (ProjectCalendar mpxjDerivedCalendar : mpxjCalendar.getDerivedCalendars())\n {\n net.sf.mpxj.planner.schema.Calendar plannerDerivedCalendar = m_factory.createCalendar();\n calendarList.add(plannerDerivedCalendar);\n writeCalendar(mpxjDerivedCalendar, plannerDerivedCalendar);\n }\n }",
"public void setWidth(int width) {\n this.width = width;\n getElement().getStyle().setWidth(width, Style.Unit.PX);\n }",
"public void setLocale(String locale) {\n\n try {\n m_locale = LocaleUtils.toLocale(locale);\n } catch (IllegalArgumentException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_TAG_INVALID_LOCALE_1, \"cms:navigation\"), e);\n m_locale = null;\n }\n }",
"public static byte[] explodeContentAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws OperationFailedException, ExplodedContentException {\n final Resource deploymentResource = context.readResource(PathAddress.EMPTY_ADDRESS);\n ModelNode contentItem = getContentItem(deploymentResource);\n ModelNode explodedPath = DEPLOYMENT_CONTENT_PATH.resolveModelAttribute(context, operation);\n byte[] oldHash = CONTENT_HASH.resolveModelAttribute(context, contentItem).asBytes();\n final byte[] hash;\n if (explodedPath.isDefined()) {\n hash = contentRepository.explodeSubContent(oldHash, explodedPath.asString());\n } else {\n hash = contentRepository.explodeContent(oldHash);\n }\n\n // Clear the contents and update with the hash\n final ModelNode slave = operation.clone();\n ModelNode addedContent = new ModelNode().setEmptyObject();\n addedContent.get(HASH).set(hash);\n addedContent.get(TARGET_PATH.getName()).set(\"./\");\n slave.get(CONTENT).setEmptyList().add(addedContent);\n // Add the domain op transformer\n List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);\n if (transformers == null) {\n context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());\n }\n transformers.add(new CompositeOperationAwareTransmuter(slave));\n return hash;\n }",
"public void animate(float timeInSec)\n {\n GVRSkeleton skel = getSkeleton();\n GVRPose pose = skel.getPose();\n computePose(timeInSec,pose);\n skel.poseToBones();\n skel.updateBonePose();\n skel.updateSkinPose();\n }",
"public static <T> boolean addAll(Collection<T> target, Iterator<? extends T> iterator) {\n Preconditions.checkArgumentNotNull(target, \"target\");\n boolean modified = false;\n while (iterator.hasNext()) {\n modified |= target.add(iterator.next());\n }\n return modified;\n }",
"public String clean(String value) {\n String orig = value;\n \n // check if there's a + before the first digit\n boolean initialplus = findPlus(value);\n \n // remove everything but digits\n value = sub.clean(value);\n if (value == null)\n return null;\n\n // check for initial '00'\n boolean zerozero = !initialplus && value.startsWith(\"00\");\n if (zerozero)\n value = value.substring(2); // strip off the zeros\n\n // look for country code\n CountryCode ccode = findCountryCode(value);\n if (ccode == null) {\n // no country code, let's do what little we can\n if (initialplus || zerozero)\n return orig; // this number is messed up. dare not touch\n return value;\n\n } else {\n value = value.substring(ccode.getPrefix().length()); // strip off ccode\n if (ccode.getStripZero() && value.startsWith(\"0\"))\n value = value.substring(1); // strip the zero\n\n if (ccode.isRightFormat(value))\n return \"+\" + ccode.getPrefix() + \" \" + value;\n else\n return orig; // don't dare touch this\n }\n }",
"synchronized void setServerProcessStopping() {\n this.requiredState = InternalState.STOPPED;\n internalSetState(null, InternalState.STOPPED, InternalState.PROCESS_STOPPING);\n }"
] |
Returns a compact representation of all of the projects the task is in.
@param task The task to get projects on.
@return Request object | [
"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 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 }",
"@Override\n public void run() {\n try {\n threadContext.activate();\n // run the original thread\n runnable.run();\n } finally {\n threadContext.invalidate();\n threadContext.deactivate();\n }\n\n }",
"public static Thumbor create(String host, String key) {\n if (key == null || key.length() == 0) {\n throw new IllegalArgumentException(\"Key must not be blank.\");\n }\n return new Thumbor(host, key);\n }",
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher cancelPendingRequests() {\n if (pendingRequests.size() != 0) {\n for (int i = 0; i < pendingRequests.size(); i++) {\n int reqId = pendingRequests.keyAt(i);\n Request r = pendingRequests.valueAt(i);\n if (!r.isFinished() && !r.isCancelled()) {\n cancelRequest(r, reqId);\n }\n }\n }\n return this;\n }",
"public void processCollection(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n CollectionDescriptorDef collDef = _curClassDef.getCollection(name);\r\n String attrName;\r\n\r\n if (collDef == null)\r\n {\r\n collDef = new CollectionDescriptorDef(name);\r\n _curClassDef.addCollection(collDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processCollection\", \" Processing collection \"+collDef.getName());\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n collDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n if (OjbMemberTagsHandler.getMemberDimension() > 0)\r\n {\r\n // we store the array-element type for later use\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_ARRAY_ELEMENT_CLASS_REF,\r\n OjbMemberTagsHandler.getMemberType().getQualifiedName());\r\n }\r\n else\r\n { \r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_VARIABLE_TYPE,\r\n OjbMemberTagsHandler.getMemberType().getQualifiedName());\r\n }\r\n\r\n _curCollectionDef = collDef;\r\n generate(template);\r\n _curCollectionDef = null;\r\n }",
"public static gslbvserver_spilloverpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tgslbvserver_spilloverpolicy_binding obj = new gslbvserver_spilloverpolicy_binding();\n\t\tobj.set_name(name);\n\t\tgslbvserver_spilloverpolicy_binding response[] = (gslbvserver_spilloverpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private static boolean getSystemConnectivity(Context context) {\n try {\n ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n if (cm == null) {\n return false;\n }\n\n NetworkInfo activeNetwork = cm.getActiveNetworkInfo();\n return activeNetwork.isConnectedOrConnecting();\n } catch (Exception exception) {\n return false;\n }\n }",
"protected void markStatementsForDeletion(StatementDocument currentDocument,\n\t\t\tList<Statement> deleteStatements) {\n\t\tfor (Statement statement : deleteStatements) {\n\t\t\tboolean found = false;\n\t\t\tfor (StatementGroup sg : currentDocument.getStatementGroups()) {\n\t\t\t\tif (!sg.getProperty().equals(statement.getMainSnak().getPropertyId())) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tStatement changedStatement = null;\n\t\t\t\tfor (Statement existingStatement : sg) {\n\t\t\t\t\tif (existingStatement.equals(statement)) {\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\ttoDelete.add(statement.getStatementId());\n\t\t\t\t\t} else if (existingStatement.getStatementId().equals(\n\t\t\t\t\t\t\tstatement.getStatementId())) {\n\t\t\t\t\t\t// (we assume all existing statement ids to be nonempty\n\t\t\t\t\t\t// here)\n\t\t\t\t\t\tchangedStatement = existingStatement;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!found) {\n\t\t\t\t\tStringBuilder warning = new StringBuilder();\n\t\t\t\t\twarning.append(\"Cannot delete statement (id \")\n\t\t\t\t\t\t\t.append(statement.getStatementId())\n\t\t\t\t\t\t\t.append(\") since it is not present in data. Statement was:\\n\")\n\t\t\t\t\t\t\t.append(statement);\n\n\t\t\t\t\tif (changedStatement != null) {\n\t\t\t\t\t\twarning.append(\n\t\t\t\t\t\t\t\t\"\\nThe data contains another statement with the same id: maybe it has been edited? Other statement was:\\n\")\n\t\t\t\t\t\t\t\t.append(changedStatement);\n\t\t\t\t\t}\n\t\t\t\t\tlogger.warn(warning.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"private List<TimephasedCost> getTimephasedCostFixedAmount()\n {\n List<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n ProjectCalendar cal = getCalendar();\n\n double remainingCost = getRemainingCost().doubleValue();\n\n if (remainingCost > 0)\n {\n AccrueType accrueAt = getResource().getAccrueAt();\n\n if (accrueAt == AccrueType.START)\n {\n result.add(splitCostStart(cal, remainingCost, getStart()));\n }\n else\n if (accrueAt == AccrueType.END)\n {\n result.add(splitCostEnd(cal, remainingCost, getFinish()));\n }\n else\n {\n //for prorated, we have to deal with it differently depending on whether or not\n //any actual has been entered, since we want to mimic the other timephased data\n //where planned and actual values do not overlap\n double numWorkingDays = cal.getWork(getStart(), getFinish(), TimeUnit.DAYS).getDuration();\n double standardAmountPerDay = getCost().doubleValue() / numWorkingDays;\n\n if (getActualCost().intValue() > 0)\n {\n //need to get three possible blocks of data: one for the possible partial amount\n //overlap with timephased actual cost; one with all the standard amount days\n //that happen after the actual cost stops; and one with any remaining\n //partial day cost amount\n\n int numActualDaysUsed = (int) Math.ceil(getActualCost().doubleValue() / standardAmountPerDay);\n Date actualWorkFinish = cal.getDate(getStart(), Duration.getInstance(numActualDaysUsed, TimeUnit.DAYS), false);\n\n double partialDayActualAmount = getActualCost().doubleValue() % standardAmountPerDay;\n\n if (partialDayActualAmount > 0)\n {\n double dayAmount = standardAmountPerDay < remainingCost ? standardAmountPerDay - partialDayActualAmount : remainingCost;\n\n result.add(splitCostEnd(cal, dayAmount, actualWorkFinish));\n\n remainingCost -= dayAmount;\n }\n\n //see if there's anything left to work with\n if (remainingCost > 0)\n {\n //have to split up the amount into standard prorated amount days and whatever is left\n result.addAll(splitCostProrated(cal, remainingCost, standardAmountPerDay, cal.getNextWorkStart(actualWorkFinish)));\n }\n\n }\n else\n {\n //no actual cost to worry about, so just a standard split from the beginning of the assignment\n result.addAll(splitCostProrated(cal, remainingCost, standardAmountPerDay, getStart()));\n }\n }\n }\n\n return result;\n }"
] |
Create a clone of the Renderer. This method is the base of the prototype mechanism implemented
to avoid create new objects from RendererBuilder. Pay an special attention implementing clone
method in Renderer subtypes.
@return a copy of the current renderer. | [
"Renderer copy() {\n Renderer copy = null;\n try {\n copy = (Renderer) this.clone();\n } catch (CloneNotSupportedException e) {\n Log.e(\"Renderer\", \"All your renderers should be clonables.\");\n }\n return copy;\n }"
] | [
"public void getKey(int keyIndex, float[] values)\n {\n int index = keyIndex * mFloatsPerKey;\n System.arraycopy(mKeys, index + 1, values, 0, values.length);\n }",
"public static List<String> readLines(CharSequence self) throws IOException {\n return IOGroovyMethods.readLines(new StringReader(self.toString()));\n }",
"protected Query buildMtoNImplementorQuery(Collection ids)\r\n {\r\n String[] indFkCols = getFksToThisClass();\r\n String[] indItemFkCols = getFksToItemClass();\r\n FieldDescriptor[] pkFields = getOwnerClassDescriptor().getPkFields();\r\n FieldDescriptor[] itemPkFields = getItemClassDescriptor().getPkFields();\r\n String[] cols = new String[indFkCols.length + indItemFkCols.length];\r\n int[] jdbcTypes = new int[indFkCols.length + indItemFkCols.length];\r\n\r\n // concatenate the columns[]\r\n System.arraycopy(indFkCols, 0, cols, 0, indFkCols.length);\r\n System.arraycopy(indItemFkCols, 0, cols, indFkCols.length, indItemFkCols.length);\r\n\r\n Criteria crit = buildPrefetchCriteria(ids, indFkCols, indItemFkCols, itemPkFields);\r\n\r\n // determine the jdbcTypes of the pks\r\n for (int i = 0; i < pkFields.length; i++)\r\n {\r\n jdbcTypes[i] = pkFields[i].getJdbcType().getType();\r\n }\r\n for (int i = 0; i < itemPkFields.length; i++)\r\n {\r\n jdbcTypes[pkFields.length + i] = itemPkFields[i].getJdbcType().getType();\r\n }\r\n\r\n ReportQueryByMtoNCriteria q = new ReportQueryByMtoNCriteria(getItemClassDescriptor().getClassOfObject(), cols,\r\n crit, false);\r\n q.setIndirectionTable(getCollectionDescriptor().getIndirectionTable());\r\n q.setJdbcTypes(jdbcTypes);\r\n\r\n CollectionDescriptor cds = getCollectionDescriptor();\r\n //check if collection must be ordered\r\n if (!cds.getOrderBy().isEmpty())\r\n {\r\n Iterator iter = cds.getOrderBy().iterator();\r\n while (iter.hasNext())\r\n {\r\n q.addOrderBy((FieldHelper) iter.next());\r\n }\r\n }\r\n \r\n return q;\r\n }",
"public static void main(String[] args) {\r\n\r\n String[] s = {\"there once was a man\", \"this one is a manic\", \"hey there\", \"there once was a mane\", \"once in a manger.\", \"where is one match?\", \"Jo3seph Smarr!\", \"Joseph R Smarr\"};\r\n for (int i = 0; i < 8; i++) {\r\n for (int j = 0; j < 8; j++) {\r\n System.out.println(\"s1: \" + s[i]);\r\n System.out.println(\"s2: \" + s[j]);\r\n System.out.println(\"edit distance: \" + editDistance(s[i], s[j]));\r\n System.out.println(\"LCS: \" + longestCommonSubstring(s[i], s[j]));\r\n System.out.println(\"LCCS: \" + longestCommonContiguousSubstring(s[i], s[j]));\r\n System.out.println();\r\n }\r\n }\r\n }",
"private Table getTable(String name)\n {\n Table table = m_tables.get(name);\n if (table == null)\n {\n table = EMPTY_TABLE;\n }\n return table;\n }",
"public void check(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureNoTableInfoIfNoRepositoryInfo(classDef, checkLevel);\r\n checkModifications(classDef, checkLevel);\r\n checkExtents(classDef, checkLevel);\r\n ensureTableIfNecessary(classDef, checkLevel);\r\n checkFactoryClassAndMethod(classDef, checkLevel);\r\n checkInitializationMethod(classDef, checkLevel);\r\n checkPrimaryKey(classDef, checkLevel);\r\n checkProxyPrefetchingLimit(classDef, checkLevel);\r\n checkRowReader(classDef, checkLevel);\r\n checkObjectCache(classDef, checkLevel);\r\n checkProcedures(classDef, checkLevel);\r\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<CopticDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<CopticDate>) super.zonedDateTime(temporal);\n }",
"public static final Date utc2date(Long time) {\n\n // don't accept negative values\n if (time == null || time < 0) return null;\n \n // add the timezone offset\n time += timezoneOffsetMillis(new Date(time));\n\n return new Date(time);\n }",
"public static Double getDistanceWithinThresholdOfCoordinates(\r\n Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) {\r\n throw new NotImplementedError();\r\n }"
] |
Converts a vector from sample space into eigen space.
@param sampleData Sample space data.
@return Eigen space projection. | [
"public double[] sampleToEigenSpace( double[] sampleData ) {\n if( sampleData.length != A.getNumCols() )\n throw new IllegalArgumentException(\"Unexpected sample length\");\n DMatrixRMaj mean = DMatrixRMaj.wrap(A.getNumCols(),1,this.mean);\n\n DMatrixRMaj s = new DMatrixRMaj(A.getNumCols(),1,true,sampleData);\n DMatrixRMaj r = new DMatrixRMaj(numComponents,1);\n\n CommonOps_DDRM.subtract(s, mean, s);\n\n CommonOps_DDRM.mult(V_t,s,r);\n\n return r.data;\n }"
] | [
"public Map getPathClasses()\r\n\t{\r\n\t\tif (m_pathClasses.isEmpty())\r\n\t\t{\r\n\t\t\tif (m_parentCriteria == null)\r\n\t\t\t{\r\n\t\t\t\tif (m_query == null)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_pathClasses;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_query.getPathClasses();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\treturn m_parentCriteria.getPathClasses();\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn m_pathClasses;\r\n\t\t}\r\n\t}",
"private void addArrayMethods(List<MethodNode> methods, ClassNode receiver, String name, ClassNode[] args) {\n if (args.length!=1) return;\n if (!receiver.isArray()) return;\n if (!isIntCategory(getUnwrapper(args[0]))) return;\n if (\"getAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, receiver.getComponentType(), new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n } else if (\"setAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, VOID_TYPE, new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n }\n }",
"public ConfigOptionBuilder setStringConverter( StringConverter converter ) {\n co.setConverter( converter );\n co.setHasArgument( true );\n return this;\n }",
"@NonNull\n private List<String> mapObsoleteElements(List<String> names) {\n List<String> elementsToRemove = new ArrayList<>(names.size());\n for (String name : names) {\n if (name.startsWith(\"android\")) continue;\n elementsToRemove.add(name);\n }\n return elementsToRemove;\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<BritishCutoverDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<BritishCutoverDate>) super.localDateTime(temporal);\n }",
"@Override\n protected String getToken() {\n GetAccessTokenResult token = accessToken.get();\n if (token == null || isExpired(token)\n || (isAboutToExpire(token) && refreshInProgress.compareAndSet(false, true))) {\n lock.lock();\n try {\n token = accessToken.get();\n if (token == null || isAboutToExpire(token)) {\n token = accessTokenProvider.getNewAccessToken(oauthScopes);\n accessToken.set(token);\n cacheExpirationHeadroom.set(getNextCacheExpirationHeadroom());\n }\n } finally {\n refreshInProgress.set(false);\n lock.unlock();\n }\n }\n return token.getAccessToken();\n }",
"private int decode(Huffman h) throws IOException\n {\n int len; /* current number of bits in code */\n int code; /* len bits being decoded */\n int first; /* first code of length len */\n int count; /* number of codes of length len */\n int index; /* index of first code of length len in symbol table */\n int bitbuf; /* bits from stream */\n int left; /* bits left in next or left to process */\n //short *next; /* next number of codes */\n\n bitbuf = m_bitbuf;\n left = m_bitcnt;\n code = first = index = 0;\n len = 1;\n int nextIndex = 1; // next = h->count + 1;\n while (true)\n {\n while (left-- != 0)\n {\n code |= (bitbuf & 1) ^ 1; /* invert code */\n bitbuf >>= 1;\n //count = *next++;\n count = h.m_count[nextIndex++];\n if (code < first + count)\n { /* if length len, return symbol */\n m_bitbuf = bitbuf;\n m_bitcnt = (m_bitcnt - len) & 7;\n return h.m_symbol[index + (code - first)];\n }\n index += count; /* else update for next length */\n first += count;\n first <<= 1;\n code <<= 1;\n len++;\n }\n left = (MAXBITS + 1) - len;\n if (left == 0)\n {\n break;\n }\n if (m_left == 0)\n {\n m_in = m_input.read();\n m_left = m_in == -1 ? 0 : 1;\n if (m_left == 0)\n {\n throw new IOException(\"out of input\"); /* out of input */\n }\n }\n bitbuf = m_in;\n m_left--;\n if (left > 8)\n {\n left = 8;\n }\n }\n return -9; /* ran out of codes */\n }",
"public void validateOperations(final List<ModelNode> operations) {\n if (operations == null) {\n return;\n }\n\n for (ModelNode operation : operations) {\n try {\n validateOperation(operation);\n } catch (RuntimeException e) {\n if (exitOnError) {\n throw e;\n } else {\n System.out.println(\"---- Operation validation error:\");\n System.out.println(e.getMessage());\n }\n\n }\n }\n }",
"public static String encodePathSegment(String segment, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(segment, encoding, HierarchicalUriComponents.Type.PATH_SEGMENT);\n\t}"
] |
Retrieves the baseline duration text value.
@param baselineNumber baseline number
@return baseline duration text value | [
"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 }"
] | [
"protected float computeUniformPadding(final CacheDataSet cache) {\n float axisSize = getViewPortSize(getOrientationAxis());\n float totalPadding = axisSize - cache.getTotalSize();\n float uniformPadding = totalPadding > 0 && cache.count() > 1 ?\n totalPadding / (cache.count() - 1) : 0;\n return uniformPadding;\n }",
"public static double SymmetricKullbackLeibler(double[] p, double[] q) {\n double dist = 0;\n for (int i = 0; i < p.length; i++) {\n dist += (p[i] - q[i]) * (Math.log(p[i]) - Math.log(q[i]));\n }\n\n return dist;\n }",
"public static void checkDirectory(File directory) {\n if (!(directory.exists() || directory.mkdirs())) {\n throw new ReportGenerationException(\n String.format(\"Can't create data directory <%s>\", directory.getAbsolutePath())\n );\n }\n }",
"public static void writeProcessorOutputToValues(\n final Object output,\n final Processor<?, ?> processor,\n final Values values) {\n Map<String, String> mapper = processor.getOutputMapperBiMap();\n if (mapper == null) {\n mapper = Collections.emptyMap();\n }\n\n final Collection<Field> fields = getAllAttributes(output.getClass());\n for (Field field: fields) {\n String name = getOutputValueName(processor.getOutputPrefix(), mapper, field);\n try {\n final Object value = field.get(output);\n if (value != null) {\n values.put(name, value);\n } else {\n values.remove(name);\n }\n } catch (IllegalAccessException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }\n }",
"public static boolean isFloat(CharSequence self) {\n try {\n Float.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }",
"private boolean isRedeployAfterRemoval(ModelNode operation) {\n return operation.hasDefined(DEPLOYMENT_OVERLAY_LINK_REMOVAL) &&\n operation.get(DEPLOYMENT_OVERLAY_LINK_REMOVAL).asBoolean();\n }",
"public boolean matches(String resourcePath) {\n if (!valid) {\n return false;\n }\n if (resourcePath == null) {\n return acceptsContextPathEmpty;\n }\n if (contextPathRegex != null && !contextPathRegex.matcher(resourcePath).matches()) {\n return false;\n }\n if (contextPathBlacklistRegex != null && contextPathBlacklistRegex.matcher(resourcePath).matches()) {\n return false;\n }\n return true;\n }",
"private boolean containsCollectionAndMapsToDifferentTable(CollectionDescriptorDef origCollDef, TableDef origTableDef, ClassDescriptorDef classDef)\r\n {\r\n if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) &&\r\n !origTableDef.getName().equals(classDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE)))\r\n {\r\n CollectionDescriptorDef curCollDef = classDef.getCollection(origCollDef.getName());\r\n\r\n if ((curCollDef != null) &&\r\n !curCollDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"public <T> T getSPI(Class<T> spiType)\n {\n return getSPI(spiType, SecurityActions.getContextClassLoader());\n }"
] |
Get a signature for a list of parameters using the given shared secret.
@param sharedSecret
The shared secret
@param params
The parameters
@return The signature String | [
"private String getSignature(String sharedSecret, Map<String, String> params) {\r\n StringBuffer buffer = new StringBuffer();\r\n buffer.append(sharedSecret);\r\n for (Map.Entry<String, String> entry : params.entrySet()) {\r\n buffer.append(entry.getKey());\r\n buffer.append(entry.getValue());\r\n }\r\n\r\n try {\r\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\r\n return ByteUtilities.toHexString(md.digest(buffer.toString().getBytes(\"UTF-8\")));\r\n } catch (NoSuchAlgorithmException e) {\r\n throw new RuntimeException(e);\r\n } catch (UnsupportedEncodingException u) {\r\n throw new RuntimeException(u);\r\n }\r\n }"
] | [
"public void seekToMonth(String direction, String seekAmount, String month) {\n int seekAmountInt = Integer.parseInt(seekAmount);\n int monthInt = Integer.parseInt(month);\n assert(direction.equals(DIR_LEFT) || direction.equals(DIR_RIGHT));\n assert(monthInt >= 1 && monthInt <= 12);\n \n markDateInvocation();\n \n // set the day to the first of month. This step is necessary because if we seek to the \n // current day of a month whose number of days is less than the current day, we will \n // pushed into the next month.\n _calendar.set(Calendar.DAY_OF_MONTH, 1);\n \n // seek to the appropriate year\n if(seekAmountInt > 0) {\n int currentMonth = _calendar.get(Calendar.MONTH) + 1;\n int sign = direction.equals(DIR_RIGHT) ? 1 : -1;\n int numYearsToShift = seekAmountInt +\n (currentMonth == monthInt ? 0 : (currentMonth < monthInt ? sign > 0 ? -1 : 0 : sign > 0 ? 0 : -1));\n\n _calendar.add(Calendar.YEAR, (numYearsToShift * sign));\n }\n \n // now set the month\n _calendar.set(Calendar.MONTH, monthInt - 1);\n }",
"public void setStatusBarColor(int statusBarColor) {\n if (mBuilder.mScrimInsetsLayout != null) {\n mBuilder.mScrimInsetsLayout.setInsetForeground(statusBarColor);\n mBuilder.mScrimInsetsLayout.getView().invalidate();\n }\n }",
"public void handle(HttpRequest request, HttpResponder responder) {\n if (urlRewriter != null) {\n try {\n request.setUri(URI.create(request.uri()).normalize().toString());\n if (!urlRewriter.rewrite(request, responder)) {\n return;\n }\n } catch (Throwable t) {\n responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Caught exception processing request. Reason: %s\",\n t.getMessage()));\n LOG.error(\"Exception thrown during rewriting of uri {}\", request.uri(), t);\n return;\n }\n }\n\n try {\n String path = URI.create(request.uri()).normalize().getPath();\n\n List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> routableDestinations\n = patternRouter.getDestinations(path);\n\n PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> matchedDestination =\n getMatchedDestination(routableDestinations, request.method(), path);\n\n if (matchedDestination != null) {\n //Found a httpresource route to it.\n HttpResourceModel httpResourceModel = matchedDestination.getDestination();\n\n // Call preCall method of handler hooks.\n boolean terminated = false;\n HandlerInfo info = new HandlerInfo(httpResourceModel.getMethod().getDeclaringClass().getName(),\n httpResourceModel.getMethod().getName());\n for (HandlerHook hook : handlerHooks) {\n if (!hook.preCall(request, responder, info)) {\n // Terminate further request processing if preCall returns false.\n terminated = true;\n break;\n }\n }\n\n // Call httpresource method\n if (!terminated) {\n // Wrap responder to make post hook calls.\n responder = new WrappedHttpResponder(responder, handlerHooks, request, info);\n if (httpResourceModel.handle(request, responder, matchedDestination.getGroupNameValues()).isStreaming()) {\n responder.sendString(HttpResponseStatus.METHOD_NOT_ALLOWED,\n String.format(\"Body Consumer not supported for internalHttpResponder: %s\",\n request.uri()));\n }\n }\n } else if (routableDestinations.size() > 0) {\n //Found a matching resource but could not find the right HttpMethod so return 405\n responder.sendString(HttpResponseStatus.METHOD_NOT_ALLOWED,\n String.format(\"Problem accessing: %s. Reason: Method Not Allowed\", request.uri()));\n } else {\n responder.sendString(HttpResponseStatus.NOT_FOUND, String.format(\"Problem accessing: %s. Reason: Not Found\",\n request.uri()));\n }\n } catch (Throwable t) {\n responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Caught exception processing request. Reason: %s\", t.getMessage()));\n LOG.error(\"Exception thrown during request processing for uri {}\", request.uri(), t);\n }\n }",
"private void serializeEPR(EndpointReferenceType wsAddr, Node parent) throws ServiceLocatorException {\n try {\n JAXBElement<EndpointReferenceType> ep =\n WSA_OBJECT_FACTORY.createEndpointReference(wsAddr);\n createMarshaller().marshal(ep, parent);\n } catch (JAXBException e) {\n if (LOG.isLoggable(Level.SEVERE)) {\n LOG.log(Level.SEVERE,\n \"Failed to serialize endpoint data\", e);\n }\n throw new ServiceLocatorException(\"Failed to serialize endpoint data\", e);\n }\n }",
"public static String convertToSQL92(char escape, char multi, char single, String pattern)\n\t\t\tthrows IllegalArgumentException {\n\t\tif ((escape == '\\'') || (multi == '\\'') || (single == '\\'')) {\n\t\t\tthrow new IllegalArgumentException(\"do not use single quote (') as special char!\");\n\t\t}\n\t\t\n\t\tStringBuilder result = new StringBuilder(pattern.length() + 5);\n\t\tint i = 0;\n\t\twhile (i < pattern.length()) {\n\t\t\tchar chr = pattern.charAt(i);\n\t\t\tif (chr == escape) {\n\t\t\t\t// emit the next char and skip it\n\t\t\t\tif (i != (pattern.length() - 1)) {\n\t\t\t\t\tresult.append(pattern.charAt(i + 1));\n\t\t\t\t}\n\t\t\t\ti++; // skip next char\n\t\t\t} else if (chr == single) {\n\t\t\t\tresult.append('_');\n\t\t\t} else if (chr == multi) {\n\t\t\t\tresult.append('%');\n\t\t\t} else if (chr == '\\'') {\n\t\t\t\tresult.append('\\'');\n\t\t\t\tresult.append('\\'');\n\t\t\t} else {\n\t\t\t\tresult.append(chr);\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\n\t\treturn result.toString();\n\t}",
"public int getTotalCreatedConnections(){\r\n\t\tint total=0;\r\n\t\tfor (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){\r\n\t\t\ttotal+=this.partitions[i].getCreatedConnections();\r\n\t\t}\r\n\t\treturn total;\r\n\t}",
"private InterfaceAddress findMatchingAddress(DeviceAnnouncement aDevice, NetworkInterface networkInterface) {\n for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {\n if ((address.getBroadcast() != null) &&\n Util.sameNetwork(address.getNetworkPrefixLength(), aDevice.getAddress(), address.getAddress())) {\n return address;\n }\n }\n return null;\n }",
"private void\n executeSubBatch(final int batchId,\n RebalanceBatchPlanProgressBar progressBar,\n final Cluster batchRollbackCluster,\n final List<StoreDefinition> batchRollbackStoreDefs,\n final List<RebalanceTaskInfo> rebalanceTaskPlanList,\n boolean hasReadOnlyStores,\n boolean hasReadWriteStores,\n boolean finishedReadOnlyStores) {\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"Submitting rebalance tasks \");\n\n // Get an ExecutorService in place used for submitting our tasks\n ExecutorService service = RebalanceUtils.createExecutors(maxParallelRebalancing);\n\n // Sub-list of the above list\n final List<RebalanceTask> failedTasks = Lists.newArrayList();\n final List<RebalanceTask> incompleteTasks = Lists.newArrayList();\n\n // Semaphores for donor nodes - To avoid multiple disk sweeps\n Map<Integer, Semaphore> donorPermits = new HashMap<Integer, Semaphore>();\n for(Node node: batchRollbackCluster.getNodes()) {\n donorPermits.put(node.getId(), new Semaphore(1));\n }\n\n try {\n // List of tasks which will run asynchronously\n List<RebalanceTask> allTasks = executeTasks(batchId,\n progressBar,\n service,\n rebalanceTaskPlanList,\n donorPermits);\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"All rebalance tasks submitted\");\n\n // Wait and shutdown after (infinite) timeout\n RebalanceUtils.executorShutDown(service, Long.MAX_VALUE);\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"Finished waiting for executors\");\n\n // Collects all failures + incomplete tasks from the rebalance\n // tasks.\n List<Exception> failures = Lists.newArrayList();\n for(RebalanceTask task: allTasks) {\n if(task.hasException()) {\n failedTasks.add(task);\n failures.add(task.getError());\n } else if(!task.isComplete()) {\n incompleteTasks.add(task);\n }\n }\n\n if(failedTasks.size() > 0) {\n throw new VoldemortRebalancingException(\"Rebalance task terminated unsuccessfully on tasks \"\n + failedTasks,\n failures);\n }\n\n // If there were no failures, then we could have had a genuine\n // timeout ( Rebalancing took longer than the operator expected ).\n // We should throw a VoldemortException and not a\n // VoldemortRebalancingException ( which will start reverting\n // metadata ). The operator may want to manually then resume the\n // process.\n if(incompleteTasks.size() > 0) {\n throw new VoldemortException(\"Rebalance tasks are still incomplete / running \"\n + incompleteTasks);\n }\n\n } catch(VoldemortRebalancingException e) {\n\n logger.error(\"Failure while migrating partitions for rebalance task \"\n + batchId);\n\n if(hasReadOnlyStores && hasReadWriteStores\n && finishedReadOnlyStores) {\n // Case 0\n adminClient.rebalanceOps.rebalanceStateChange(null,\n batchRollbackCluster,\n null,\n batchRollbackStoreDefs,\n null,\n true,\n true,\n false,\n false,\n false);\n } else if(hasReadWriteStores && finishedReadOnlyStores) {\n // Case 4\n adminClient.rebalanceOps.rebalanceStateChange(null,\n batchRollbackCluster,\n null,\n batchRollbackStoreDefs,\n null,\n false,\n true,\n false,\n false,\n false);\n }\n\n throw e;\n\n } finally {\n if(!service.isShutdown()) {\n RebalanceUtils.printErrorLog(batchId,\n logger,\n \"Could not shutdown service cleanly for rebalance task \"\n + batchId,\n null);\n service.shutdownNow();\n }\n }\n }",
"private void readTask(String projectIdentifier, Map<String, Task> map, Document.Projects.Project.Task task)\n {\n Task parentTask = map.get(getParentOutlineNumber(task.getOutlineNumber()));\n Task mpxjTask = parentTask.addTask();\n\n TimeUnit units = task.getBaseDurationTimeUnit();\n\n mpxjTask.setCost(task.getActualCost());\n mpxjTask.setDuration(getDuration(units, task.getActualDuration()));\n mpxjTask.setFinish(task.getActualFinishDate());\n mpxjTask.setStart(task.getActualStartDate());\n mpxjTask.setBaselineDuration(getDuration(units, task.getBaseDuration()));\n mpxjTask.setBaselineFinish(task.getBaseFinishDate());\n mpxjTask.setBaselineCost(task.getBaselineCost());\n // task.getBaselineFinishDate()\n // task.getBaselineFinishTemplateOffset()\n // task.getBaselineStartDate()\n // task.getBaselineStartTemplateOffset()\n mpxjTask.setBaselineStart(task.getBaseStartDate());\n // task.getCallouts()\n mpxjTask.setPercentageComplete(task.getComplete());\n mpxjTask.setDeadline(task.getDeadlineDate());\n // task.getDeadlineTemplateOffset()\n // task.getHyperlinks()\n // task.getMarkerID()\n mpxjTask.setName(task.getName());\n mpxjTask.setNotes(task.getNote());\n mpxjTask.setPriority(task.getPriority());\n // task.getRecalcBase1()\n // task.getRecalcBase2()\n mpxjTask.setType(task.getSchedulingType());\n // task.getStyleProject()\n // task.getTemplateOffset()\n // task.getValidatedByProject()\n\n if (task.isIsMilestone())\n {\n mpxjTask.setMilestone(true);\n mpxjTask.setDuration(Duration.getInstance(0, TimeUnit.HOURS));\n mpxjTask.setBaselineDuration(Duration.getInstance(0, TimeUnit.HOURS));\n }\n\n String taskIdentifier = projectIdentifier + \".\" + task.getID();\n m_taskIdMap.put(task.getID(), mpxjTask);\n mpxjTask.setGUID(UUID.nameUUIDFromBytes(taskIdentifier.getBytes()));\n\n map.put(task.getOutlineNumber(), mpxjTask);\n\n for (Document.Projects.Project.Task.ResourceAssignments.ResourceAssignment assignment : task.getResourceAssignments().getResourceAssignment())\n {\n readResourceAssignment(mpxjTask, assignment);\n }\n }"
] |
delete of files more than 1 day old | [
"private static void deleteOldAndEmptyFiles() {\n File dir = LOG_FILE_DIR;\n if (dir.exists()) {\n File[] files = dir.listFiles();\n\n for (File f : files) {\n if (f.length() == 0 ||\n f.lastModified() + MAXFILEAGE < System.currentTimeMillis()) {\n f.delete();\n }\n }\n }\n }"
] | [
"private List<Versioned<byte[]>> filterExpiredEntries(ByteArray key, List<Versioned<byte[]>> vals) {\n Iterator<Versioned<byte[]>> valsIterator = vals.iterator();\n while(valsIterator.hasNext()) {\n Versioned<byte[]> val = valsIterator.next();\n VectorClock clock = (VectorClock) val.getVersion();\n // omit if expired\n if(clock.getTimestamp() < (time.getMilliseconds() - this.retentionTimeMs)) {\n valsIterator.remove();\n // delete stale value if configured\n if(deleteExpiredEntries) {\n getInnerStore().delete(key, clock);\n }\n }\n }\n return vals;\n }",
"protected void processStart(Endpoint endpoint, EventTypeEnum eventType) {\n if (!sendLifecycleEvent) {\n return;\n }\n\n Event event = createEvent(endpoint, eventType);\n queue.add(event);\n }",
"void backup() throws ConfigurationPersistenceException {\n if (!doneBootup.get()) {\n return;\n }\n try {\n if (!interactionPolicy.isReadOnly()) {\n //Move the main file to the versioned history\n moveFile(mainFile, getVersionedFile(mainFile));\n } else {\n //Copy the Last file to the versioned history\n moveFile(lastFile, getVersionedFile(mainFile));\n }\n int seq = sequence.get();\n // delete unwanted backup files\n int currentHistoryLength = getInteger(CURRENT_HISTORY_LENGTH_PROPERTY, CURRENT_HISTORY_LENGTH, 0);\n if (seq > currentHistoryLength) {\n for (int k = seq - currentHistoryLength; k > 0; k--) {\n File delete = getVersionedFile(mainFile, k);\n if (! delete.exists()) {\n break;\n }\n delete.delete();\n }\n }\n } catch (IOException e) {\n throw ControllerLogger.ROOT_LOGGER.failedToBackup(e, mainFile);\n }\n }",
"private void processUpdate(DeviceUpdate update) {\n updates.put(update.getAddress(), update);\n\n // Keep track of the largest sync number we see.\n if (update instanceof CdjStatus) {\n int syncNumber = ((CdjStatus)update).getSyncNumber();\n if (syncNumber > this.largestSyncCounter.get()) {\n this.largestSyncCounter.set(syncNumber);\n }\n }\n\n // Deal with the tempo master complexities, including handoff to/from us.\n if (update.isTempoMaster()) {\n final Integer packetYieldingTo = update.getDeviceMasterIsBeingYieldedTo();\n if (packetYieldingTo == null) {\n // This is a normal, non-yielding master packet. Update our notion of the current master, and,\n // if we were yielding, finish that process, updating our sync number appropriately.\n if (master.get()) {\n if (nextMaster.get() == update.deviceNumber) {\n syncCounter.set(largestSyncCounter.get() + 1);\n } else {\n if (nextMaster.get() == 0xff) {\n logger.warn(\"Saw master asserted by player \" + update.deviceNumber +\n \" when we were not yielding it.\");\n } else {\n logger.warn(\"Expected to yield master role to player \" + nextMaster.get() +\n \" but saw master asserted by player \" + update.deviceNumber);\n }\n }\n }\n master.set(false);\n nextMaster.set(0xff);\n setTempoMaster(update);\n setMasterTempo(update.getEffectiveTempo());\n } else {\n // This is a yielding master packet. If it is us that is being yielded to, take over master.\n // Log a message if it was unsolicited, and a warning if it's coming from a different player than\n // we asked.\n if (packetYieldingTo == getDeviceNumber()) {\n if (update.deviceNumber != masterYieldedFrom.get()) {\n if (masterYieldedFrom.get() == 0) {\n logger.info(\"Accepting unsolicited Master yield; we must be the only synced device playing.\");\n } else {\n logger.warn(\"Expected player \" + masterYieldedFrom.get() + \" to yield master to us, but player \" +\n update.deviceNumber + \" did.\");\n }\n }\n master.set(true);\n masterYieldedFrom.set(0);\n setTempoMaster(null);\n setMasterTempo(getTempo());\n }\n }\n } else {\n // This update was not acting as a tempo master; if we thought it should be, update our records.\n DeviceUpdate oldMaster = getTempoMaster();\n if (oldMaster != null && oldMaster.getAddress().equals(update.getAddress())) {\n // This device has resigned master status, and nobody else has claimed it so far\n setTempoMaster(null);\n }\n }\n deliverDeviceUpdate(update);\n }",
"public void linkOneToOne(Object obj, ClassDescriptor cld, ObjectReferenceDescriptor rds, boolean insert)\n {\n storeAndLinkOneToOne(true, obj, cld, rds, true);\n }",
"private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList) {\n List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>();\n\n int parentCount = parentList.size();\n for (int i = 0; i < parentCount; i++) {\n P parent = parentList.get(i);\n generateParentWrapper(flatItemList, parent, parent.isInitiallyExpanded());\n }\n\n return flatItemList;\n }",
"public static Shell createConsoleShell(String prompt, String appName, Object mainHandler) {\n return createConsoleShell(prompt, appName, mainHandler, new EmptyMultiMap<String, Object>());\n }",
"public static List<File> extract(File zipFile, File outputFolder) throws IOException {\n List<File> extracted = new ArrayList<File>();\n\n byte[] buffer = new byte[2048];\n\n if (!outputFolder.exists()) {\n outputFolder.mkdir();\n }\n\n ZipInputStream zipInput = new ZipInputStream(new FileInputStream(zipFile));\n\n ZipEntry zipEntry = zipInput.getNextEntry();\n\n while (zipEntry != null) {\n\n String neFileNameName = zipEntry.getName();\n File newFile = new File(outputFolder + File.separator + neFileNameName);\n\n newFile.getParentFile().mkdirs();\n\n if (!zipEntry.isDirectory()) {\n FileOutputStream fos = new FileOutputStream(newFile);\n\n int size;\n while ((size = zipInput.read(buffer)) > 0) {\n fos.write(buffer, 0, size);\n }\n\n fos.close();\n extracted.add(newFile);\n }\n\n zipEntry = zipInput.getNextEntry();\n }\n\n zipInput.closeEntry();\n zipInput.close();\n\n return extracted;\n\n }",
"public Iterable<BoxRetentionPolicyAssignment.Info> getAllAssignments(int limit, String ... fields) {\r\n return this.getAssignments(null, limit, fields);\r\n }"
] |
This method will return a list of installed identities for which
the corresponding .conf file exists under .installation directory.
The list will also include the default identity even if the .conf
file has not been created for it. | [
"@Override\n public List<InstalledIdentity> getInstalledIdentities() throws PatchingException {\n\n List<InstalledIdentity> installedIdentities;\n\n final File metadataDir = installedImage.getInstallationMetadata();\n if(!metadataDir.exists()) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n final String defaultConf = defaultIdentity.getIdentity().getName() + Constants.DOT_CONF;\n final File[] identityConfs = metadataDir.listFiles(new FileFilter() {\n @Override\n public boolean accept(File pathname) {\n return pathname.isFile() &&\n pathname.getName().endsWith(Constants.DOT_CONF) &&\n !pathname.getName().equals(defaultConf);\n }\n });\n if(identityConfs == null || identityConfs.length == 0) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n installedIdentities = new ArrayList<InstalledIdentity>(identityConfs.length + 1);\n installedIdentities.add(defaultIdentity);\n for(File conf : identityConfs) {\n final Properties props = loadProductConf(conf);\n String productName = conf.getName();\n productName = productName.substring(0, productName.length() - Constants.DOT_CONF.length());\n final String productVersion = props.getProperty(Constants.CURRENT_VERSION);\n\n InstalledIdentity identity;\n try {\n identity = LayersFactory.load(installedImage, new ProductConfig(productName, productVersion, null), moduleRoots, bundleRoots);\n } catch (IOException e) {\n throw new PatchingException(PatchLogger.ROOT_LOGGER.failedToLoadInfo(productName), e);\n }\n installedIdentities.add(identity);\n }\n }\n }\n return installedIdentities;\n }"
] | [
"public static String getDumpFilePostfix(DumpContentType dumpContentType) {\n\t\tif (WmfDumpFile.POSTFIXES.containsKey(dumpContentType)) {\n\t\t\treturn WmfDumpFile.POSTFIXES.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 boolean hasDeploymentSubsystemModel(final String subsystemName) {\n final Resource root = deploymentUnit.getAttachment(DEPLOYMENT_RESOURCE);\n final PathElement subsystem = PathElement.pathElement(SUBSYSTEM, subsystemName);\n return root.hasChild(subsystem);\n }",
"@Override\n public void run() {\n try {\n threadContext.activate();\n // run the original thread\n runnable.run();\n } finally {\n threadContext.invalidate();\n threadContext.deactivate();\n }\n\n }",
"private static List<Segment> parseSegments(String origPathStr) {\n String pathStr = origPathStr;\n if (!pathStr.startsWith(\"/\")) {\n pathStr = pathStr + \"/\";\n }\n\n List<Segment> result = new ArrayList<>();\n for (String segmentStr : PATH_SPLITTER.split(pathStr)) {\n Matcher m = SEGMENT_PATTERN.matcher(segmentStr);\n if (!m.matches()) {\n throw new IllegalArgumentException(\"Bad aql path: \" + origPathStr);\n }\n Segment segment = new Segment();\n segment.attribute = m.group(1);\n segment.nodeId = m.groupCount() >= 3 ? m.group(3) : null;\n result.add(segment);\n }\n return result;\n }",
"private void readCalendars(Project ganttProject)\n {\n m_mpxjCalendar = m_projectFile.addCalendar();\n m_mpxjCalendar.setName(ProjectCalendar.DEFAULT_BASE_CALENDAR_NAME);\n\n Calendars gpCalendar = ganttProject.getCalendars();\n setWorkingDays(m_mpxjCalendar, gpCalendar);\n setExceptions(m_mpxjCalendar, gpCalendar);\n m_eventManager.fireCalendarReadEvent(m_mpxjCalendar);\n }",
"public static base_response save(nitro_service client, cacheobject resource) throws Exception {\n\t\tcacheobject saveresource = new cacheobject();\n\t\tsaveresource.locator = resource.locator;\n\t\treturn saveresource.perform_operation(client,\"save\");\n\t}",
"protected void updateTables()\n {\n byte[] data = m_model.getData();\n int columns = m_model.getColumns();\n int rows = (data.length / columns) + 1;\n int offset = m_model.getOffset();\n\n String[][] hexData = new String[rows][columns];\n String[][] asciiData = new String[rows][columns];\n\n int row = 0;\n int column = 0;\n StringBuilder hexValue = new StringBuilder();\n for (int index = offset; index < data.length; index++)\n {\n int value = data[index];\n hexValue.setLength(0);\n hexValue.append(HEX_DIGITS[(value & 0xF0) >> 4]);\n hexValue.append(HEX_DIGITS[value & 0x0F]);\n\n char c = (char) value;\n if ((c > 200) || (c < 27))\n {\n c = ' ';\n }\n\n hexData[row][column] = hexValue.toString();\n asciiData[row][column] = Character.toString(c);\n\n ++column;\n if (column == columns)\n {\n column = 0;\n ++row;\n }\n }\n\n String[] columnHeadings = new String[columns];\n TableModel hexTableModel = new DefaultTableModel(hexData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n TableModel asciiTableModel = new DefaultTableModel(asciiData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n m_model.setSizeValueLabel(Integer.toString(data.length));\n m_model.setHexTableModel(hexTableModel);\n m_model.setAsciiTableModel(asciiTableModel);\n m_model.setCurrentSelectionIndex(0);\n m_model.setPreviousSelectionIndex(0);\n }",
"public static void installManagementChannelServices(\n final ServiceTarget serviceTarget,\n final ServiceName endpointName,\n final AbstractModelControllerOperationHandlerFactoryService operationHandlerService,\n final ServiceName modelControllerName,\n final String channelName,\n final ServiceName executorServiceName,\n final ServiceName scheduledExecutorServiceName) {\n\n final OptionMap options = OptionMap.EMPTY;\n final ServiceName operationHandlerName = endpointName.append(channelName).append(ModelControllerClientOperationHandlerFactoryService.OPERATION_HANDLER_NAME_SUFFIX);\n\n serviceTarget.addService(operationHandlerName, operationHandlerService)\n .addDependency(modelControllerName, ModelController.class, operationHandlerService.getModelControllerInjector())\n .addDependency(executorServiceName, ExecutorService.class, operationHandlerService.getExecutorInjector())\n .addDependency(scheduledExecutorServiceName, ScheduledExecutorService.class, operationHandlerService.getScheduledExecutorInjector())\n .setInitialMode(ACTIVE)\n .install();\n\n installManagementChannelOpenListenerService(serviceTarget, endpointName, channelName, operationHandlerName, options, false);\n }",
"private void validateSegments(List<LogSegment> segments) {\n synchronized (lock) {\n for (int i = 0; i < segments.size() - 1; i++) {\n LogSegment curr = segments.get(i);\n LogSegment next = segments.get(i + 1);\n if (curr.start() + curr.size() != next.start()) {\n throw new IllegalStateException(\"The following segments don't validate: \" + curr.getFile()\n .getAbsolutePath() + \", \" + next.getFile().getAbsolutePath());\n }\n }\n }\n }"
] |
Verify that all OGM custom externalizers are present.
N.B. even if some Externalizer is only needed in specific configuration,
it is not safe to start a CacheManager without one as the same CacheManager
might be used, or have been used in the past, to store data using a different
configuration.
@see ExternalizerIds
@see AdvancedExternalizer
@param externalCacheManager the provided CacheManager to validate | [
"public static void validateExternalizersPresent(EmbeddedCacheManager externalCacheManager) {\n\t\tMap<Integer, AdvancedExternalizer<?>> externalizerMap = externalCacheManager\n\t\t\t\t.getCacheManagerConfiguration()\n\t\t\t\t.serialization()\n\t\t\t\t.advancedExternalizers();\n\t\tfor ( AdvancedExternalizer<?> ogmExternalizer : ogmExternalizers.values() ) {\n\t\t\tfinal Integer externalizerId = ogmExternalizer.getId();\n\t\t\tAdvancedExternalizer<?> registeredExternalizer = externalizerMap.get( externalizerId );\n\t\t\tif ( registeredExternalizer == null ) {\n\t\t\t\tthrow log.externalizersNotRegistered( externalizerId, ogmExternalizer.getClass() );\n\t\t\t}\n\t\t\telse if ( !registeredExternalizer.getClass().equals( ogmExternalizer ) ) {\n\t\t\t\tif ( registeredExternalizer.getClass().toString().equals( ogmExternalizer.getClass().toString() ) ) {\n\t\t\t\t\t// same class name, yet different Class definition!\n\t\t\t\t\tthrow log.registeredExternalizerNotLoadedFromOGMClassloader( registeredExternalizer.getClass() );\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow log.externalizerIdNotMatchingType( externalizerId, registeredExternalizer, ogmExternalizer );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}"
] | [
"@PostConstruct\n public final void init() {\n this.cleanUpTimer = Executors.newScheduledThreadPool(1, timerTask -> {\n final Thread thread = new Thread(timerTask, \"Clean up old job records\");\n thread.setDaemon(true);\n return thread;\n });\n this.cleanUpTimer.scheduleAtFixedRate(this::cleanup, this.cleanupInterval, this.cleanupInterval,\n TimeUnit.SECONDS);\n }",
"private static void listTasks(ProjectFile file)\n {\n SimpleDateFormat df = new SimpleDateFormat(\"dd/MM/yyyy HH:mm z\");\n\n for (Task task : file.getTasks())\n {\n Date date = task.getStart();\n String text = task.getStartText();\n String startDate = text != null ? text : (date != null ? df.format(date) : \"(no start date supplied)\");\n\n date = task.getFinish();\n text = task.getFinishText();\n String finishDate = text != null ? text : (date != null ? df.format(date) : \"(no finish date supplied)\");\n\n Duration dur = task.getDuration();\n text = task.getDurationText();\n String duration = text != null ? text : (dur != null ? dur.toString() : \"(no duration supplied)\");\n\n dur = task.getActualDuration();\n String actualDuration = dur != null ? dur.toString() : \"(no actual duration supplied)\";\n\n String baselineDuration = task.getBaselineDurationText();\n if (baselineDuration == null)\n {\n dur = task.getBaselineDuration();\n if (dur != null)\n {\n baselineDuration = dur.toString();\n }\n else\n {\n baselineDuration = \"(no duration supplied)\";\n }\n }\n\n System.out.println(\"Task: \" + task.getName() + \" ID=\" + task.getID() + \" Unique ID=\" + task.getUniqueID() + \" (Start Date=\" + startDate + \" Finish Date=\" + finishDate + \" Duration=\" + duration + \" Actual Duration\" + actualDuration + \" Baseline Duration=\" + baselineDuration + \" Outline Level=\" + task.getOutlineLevel() + \" Outline Number=\" + task.getOutlineNumber() + \" Recurring=\" + task.getRecurring() + \")\");\n }\n System.out.println();\n }",
"private String getApiKey(CmsObject cms, String sitePath) throws CmsException {\n\n String res = cms.readPropertyObject(\n sitePath,\n CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY_WORKPLACE,\n true).getValue();\n\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(res)) {\n res = cms.readPropertyObject(sitePath, CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY, true).getValue();\n }\n return res;\n\n }",
"protected void updateFontTable()\n {\n PDResources resources = pdpage.getResources();\n if (resources != null)\n {\n try\n {\n processFontResources(resources, fontTable);\n } catch (IOException e) {\n log.error(\"Error processing font resources: \"\n + \"Exception: {} {}\", e.getMessage(), e.getClass());\n }\n }\n }",
"protected void prepareRequest(List<BoxAPIRequest> requests) {\n JsonObject body = new JsonObject();\n JsonArray requestsJSONArray = new JsonArray();\n for (BoxAPIRequest request: requests) {\n JsonObject batchRequest = new JsonObject();\n batchRequest.add(\"method\", request.getMethod());\n batchRequest.add(\"relative_url\", request.getUrl().toString().substring(this.api.getBaseURL().length() - 1));\n //If the actual request has a JSON body then add it to vatch request\n if (request instanceof BoxJSONRequest) {\n BoxJSONRequest jsonRequest = (BoxJSONRequest) request;\n batchRequest.add(\"body\", jsonRequest.getBodyAsJsonValue());\n }\n //Add any headers that are in the request, except Authorization\n if (request.getHeaders() != null) {\n JsonObject batchRequestHeaders = new JsonObject();\n for (RequestHeader header: request.getHeaders()) {\n if (header.getKey() != null && !header.getKey().isEmpty()\n && !HttpHeaders.AUTHORIZATION.equals(header.getKey())) {\n batchRequestHeaders.add(header.getKey(), header.getValue());\n }\n }\n batchRequest.add(\"headers\", batchRequestHeaders);\n }\n\n //Add the request to array\n requestsJSONArray.add(batchRequest);\n }\n //Add the requests array to body\n body.add(\"requests\", requestsJSONArray);\n super.setBody(body);\n }",
"private void populateSortedCustomFieldsList ()\n {\n m_sortedCustomFieldsList = new ArrayList<CustomField>();\n for (CustomField field : m_projectFile.getCustomFields())\n {\n FieldType fieldType = field.getFieldType();\n if (fieldType != null)\n {\n m_sortedCustomFieldsList.add(field);\n }\n }\n\n // Sort to ensure consistent order in file\n Collections.sort(m_sortedCustomFieldsList, new Comparator<CustomField>()\n {\n @Override public int compare(CustomField customField1, CustomField customField2)\n {\n FieldType o1 = customField1.getFieldType();\n FieldType o2 = customField2.getFieldType();\n String name1 = o1.getClass().getSimpleName() + \".\" + o1.getName() + \" \" + customField1.getAlias();\n String name2 = o2.getClass().getSimpleName() + \".\" + o2.getName() + \" \" + customField2.getAlias();\n return name1.compareTo(name2);\n }\n });\n }",
"List<LogSegment> markDeletedWhile(LogSegmentFilter filter) throws IOException {\n synchronized (lock) {\n List<LogSegment> view = segments.getView();\n List<LogSegment> deletable = new ArrayList<LogSegment>();\n for (LogSegment seg : view) {\n if (filter.filter(seg)) {\n deletable.add(seg);\n }\n }\n for (LogSegment seg : deletable) {\n seg.setDeleted(true);\n }\n int numToDelete = deletable.size();\n //\n // if we are deleting everything, create a new empty segment\n if (numToDelete == view.size()) {\n if (view.get(numToDelete - 1).size() > 0) {\n roll();\n } else {\n // If the last segment to be deleted is empty and we roll the log, the new segment will have the same\n // file name. So simply reuse the last segment and reset the modified time.\n view.get(numToDelete - 1).getFile().setLastModified(System.currentTimeMillis());\n numToDelete -= 1;\n }\n }\n return segments.trunc(numToDelete);\n }\n }",
"protected void addPropertiesStart(String type) {\n putProperty(PropertyKey.Host.name(), IpUtils.getHostName());\n putProperty(PropertyKey.Type.name(), type);\n putProperty(PropertyKey.Status.name(), Status.Start.name());\n }",
"public static Map<String, StoreDefinition> getSystemStoreDefMap() {\n Map<String, StoreDefinition> sysStoreDefMap = Maps.newHashMap();\n List<StoreDefinition> storesDefs = SystemStoreConstants.getAllSystemStoreDefs();\n for(StoreDefinition def: storesDefs) {\n sysStoreDefMap.put(def.getName(), def);\n }\n return sysStoreDefMap;\n }"
] |
Multiplies all positions with a factor v
@param v Multiplication factor | [
"public void scale(double v){\n\t\tfor(int i = 0; i < this.size(); i++){\n\t\t\tthis.get(i).scale(v);;\n\t\t}\n\t}"
] | [
"public static String readFileContentToString(String filePath)\n throws IOException {\n String content = \"\";\n content = Files.toString(new File(filePath), Charsets.UTF_8);\n return content;\n }",
"private void readRelationships(Storepoint phoenixProject)\n {\n for (Relationship relation : phoenixProject.getRelationships().getRelationship())\n {\n readRelation(relation);\n }\n }",
"public static CrashReport fromJson(String json) throws IllegalArgumentException {\n try {\n return new CrashReport(json);\n } catch (JSONException je) {\n throw new IllegalArgumentException(je.toString());\n }\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 }",
"protected DataSource wrapAsDataSource(JdbcConnectionDescriptor jcd,\r\n ObjectPool connectionPool)\r\n {\r\n final boolean allowConnectionUnwrap;\r\n if (jcd == null)\r\n {\r\n allowConnectionUnwrap = false;\r\n }\r\n else\r\n {\r\n final Properties properties = jcd.getConnectionPoolDescriptor().getDbcpProperties();\r\n final String allowConnectionUnwrapParam;\r\n allowConnectionUnwrapParam = properties.getProperty(PARAM_NAME_UNWRAP_ALLOWED);\r\n allowConnectionUnwrap = allowConnectionUnwrapParam != null &&\r\n Boolean.valueOf(allowConnectionUnwrapParam).booleanValue();\r\n }\r\n final PoolingDataSource dataSource;\r\n dataSource = new PoolingDataSource(connectionPool);\r\n dataSource.setAccessToUnderlyingConnectionAllowed(allowConnectionUnwrap);\r\n\r\n if(jcd != null)\r\n {\r\n final AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig();\r\n if (ac.getRemoveAbandoned() && ac.getLogAbandoned()) {\r\n final LoggerWrapperPrintWriter loggerPiggyBack;\r\n loggerPiggyBack = new LoggerWrapperPrintWriter(log, Logger.ERROR);\r\n dataSource.setLogWriter(loggerPiggyBack);\r\n }\r\n }\r\n return dataSource;\r\n }",
"public JsonNode apply(final JsonNode node) {\n requireNonNull(node, \"node\");\n JsonNode ret = node.deepCopy();\n for (final JsonPatchOperation operation : operations) {\n ret = operation.apply(ret);\n }\n\n return ret;\n }",
"public static <T extends InterconnectObject> T fromJson(String data, Class<T> clazz) throws IOException {\n return InterconnectMapper.mapper.readValue(data, clazz);\n }",
"public ProjectCalendarHours addCalendarHours(Day day)\n {\n ProjectCalendarHours bch = new ProjectCalendarHours(this);\n bch.setDay(day);\n m_hours[day.getValue() - 1] = bch;\n return (bch);\n }",
"public static ClassNode getWrapper(ClassNode cn) {\n cn = cn.redirect();\n if (!isPrimitiveType(cn)) return cn;\n if (cn==boolean_TYPE) {\n return Boolean_TYPE;\n } else if (cn==byte_TYPE) {\n return Byte_TYPE;\n } else if (cn==char_TYPE) {\n return Character_TYPE;\n } else if (cn==short_TYPE) {\n return Short_TYPE;\n } else if (cn==int_TYPE) {\n return Integer_TYPE;\n } else if (cn==long_TYPE) {\n return Long_TYPE;\n } else if (cn==float_TYPE) {\n return Float_TYPE;\n } else if (cn==double_TYPE) {\n return Double_TYPE;\n } else if (cn==VOID_TYPE) {\n return void_WRAPPER_TYPE;\n }\n else {\n return cn;\n }\n }"
] |
Helper method to add cue list entries from a parsed ANLZ cue tag
@param entries the list of entries being accumulated
@param tag the tag whose entries are to be added | [
"private void addEntriesFromTag(List<Entry> entries, RekordboxAnlz.CueTag tag) {\n for (RekordboxAnlz.CueEntry cueEntry : tag.cues()) { // TODO: Need to figure out how to identify deleted entries to ignore.\n if (cueEntry.type() == RekordboxAnlz.CueEntryType.LOOP) {\n entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time()),\n Util.timeToHalfFrame(cueEntry.loopTime())));\n } else {\n entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time())));\n }\n }\n }"
] | [
"public static URL classFileUrl(Class<?> clazz) throws IOException {\n ClassLoader cl = clazz.getClassLoader();\n if (cl == null) {\n cl = ClassLoader.getSystemClassLoader();\n }\n URL res = cl.getResource(clazz.getName().replace('.', '/') + \".class\");\n if (res == null) {\n throw new IllegalArgumentException(\"Unable to locate class file for \" + clazz);\n }\n return res;\n }",
"private List<Long> collectLongMetric(String metricGetterName) {\n List<Long> vals = new ArrayList<Long>();\n for(BdbEnvironmentStats envStats: environmentStatsTracked) {\n vals.add((Long) ReflectUtils.callMethod(envStats,\n BdbEnvironmentStats.class,\n metricGetterName,\n new Class<?>[0],\n new Object[0]));\n }\n return vals;\n }",
"public IndexDef getIndex(String name)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n IndexDef def = null;\r\n\r\n for (Iterator it = getIndices(); it.hasNext();)\r\n {\r\n def = (IndexDef)it.next();\r\n if (def.getName().equals(realName))\r\n {\r\n return def;\r\n }\r\n }\r\n return null;\r\n }",
"public static double getFloatingPointDateFromDate(LocalDateTime referenceDate, LocalDateTime date) {\n\t\tDuration duration = Duration.between(referenceDate, date);\n\t\treturn ((double)duration.getSeconds()) / SECONDS_PER_DAY;\n\t}",
"public static<T> Vendor<T> vendor(Func0<T> f) {\n\treturn j.vendor(f);\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void setOffline(boolean value){\n offline = value;\n if (offline) {\n getConfigLogger().debug(getAccountId(), \"CleverTap Instance has been set to offline, won't send events queue\");\n } else {\n getConfigLogger().debug(getAccountId(), \"CleverTap Instance has been set to online, sending events queue\");\n flush();\n }\n }",
"public static final BigInteger printPriority(Priority priority)\n {\n int result = Priority.MEDIUM;\n\n if (priority != null)\n {\n result = priority.getValue();\n }\n\n return (BigInteger.valueOf(result));\n }",
"public static <T, ID> int dropTable(ConnectionSource connectionSource, Class<T> dataClass, boolean ignoreErrors)\n\t\t\tthrows SQLException {\n\t\tDao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);\n\t\treturn dropTable(dao, ignoreErrors);\n\t}",
"public final Jar setAttribute(String name, String value) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Manifest cannot be modified after entries are added.\");\n getManifest().getMainAttributes().putValue(name, value);\n return this;\n }"
] |
Main method for testing fetching | [
"public static void main(String[] args) throws Exception {\n if(args.length < 1)\n Utils.croak(\"USAGE: java \" + HdfsFetcher.class.getName()\n + \" url [keytab-location kerberos-username hadoop-config-path [destDir]]\");\n String url = args[0];\n\n VoldemortConfig config = new VoldemortConfig(-1, \"\");\n\n HdfsFetcher fetcher = new HdfsFetcher(config);\n\n String destDir = null;\n Long diskQuotaSizeInKB;\n if(args.length >= 4) {\n fetcher.voldemortConfig.setReadOnlyKeytabPath(args[1]);\n fetcher.voldemortConfig.setReadOnlyKerberosUser(args[2]);\n fetcher.voldemortConfig.setHadoopConfigPath(args[3]);\n }\n if(args.length >= 5)\n destDir = args[4];\n\n if(args.length >= 6)\n diskQuotaSizeInKB = Long.parseLong(args[5]);\n else\n diskQuotaSizeInKB = null;\n\n // for testing we want to be able to download a single file\n allowFetchingOfSingleFile = true;\n\n FileSystem fs = HadoopUtils.getHadoopFileSystem(fetcher.voldemortConfig, url);\n Path p = new Path(url);\n\n FileStatus status = fs.listStatus(p)[0];\n long size = status.getLen();\n long start = System.currentTimeMillis();\n if(destDir == null)\n destDir = System.getProperty(\"java.io.tmpdir\") + File.separator + start;\n\n File location = fetcher.fetch(url, destDir, null, null, -1, null, diskQuotaSizeInKB);\n\n double rate = size * Time.MS_PER_SECOND / (double) (System.currentTimeMillis() - start);\n NumberFormat nf = NumberFormat.getInstance();\n nf.setMaximumFractionDigits(2);\n System.out.println(\"Fetch to \" + location + \" completed: \"\n + nf.format(rate / (1024.0 * 1024.0)) + \" MB/sec.\");\n fs.close();\n }"
] | [
"public static String resolveOrOriginal(String input) {\n try {\n return resolve(input, true);\n } catch (UnresolvedExpressionException e) {\n return input;\n }\n }",
"public static long randomLongBetween(long min, long max) {\n Random rand = new Random();\n return min + (long) (rand.nextDouble() * (max - min));\n }",
"public final SimpleFeatureCollection treatStringAsURL(final Template template, final String geoJsonUrl)\n throws IOException {\n URL url;\n try {\n url = FileUtils.testForLegalFileUrl(template.getConfiguration(), new URL(geoJsonUrl));\n } catch (MalformedURLException e) {\n return null;\n }\n\n final String geojsonString;\n if (url.getProtocol().equalsIgnoreCase(\"file\")) {\n geojsonString = IOUtils.toString(url, Constants.DEFAULT_CHARSET.name());\n } else {\n geojsonString = URIUtils.toString(this.httpRequestFactory, url);\n }\n\n return treatStringAsGeoJson(geojsonString);\n }",
"@Pure\n\tpublic static <P1, P2, P3, RESULT> Function2<P2, P3, RESULT> curry(final Function3<? super P1, ? super P2, ? super P3, ? extends RESULT> function,\n\t\t\tfinal P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function2<P2, P3, RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply(P2 p2, P3 p3) {\n\t\t\t\treturn function.apply(argument, p2, p3);\n\t\t\t}\n\t\t};\n\t}",
"public static <T extends Spin<?>> T S(Object input, DataFormat<T> format) {\n return SpinFactory.INSTANCE.createSpin(input, format);\n }",
"public static base_response Shutdown(nitro_service client, shutdown resource) throws Exception {\n\t\tshutdown Shutdownresource = new shutdown();\n\t\treturn Shutdownresource.perform_operation(client);\n\t}",
"public static cmppolicylabel_stats[] get(nitro_service service) throws Exception{\n\t\tcmppolicylabel_stats obj = new cmppolicylabel_stats();\n\t\tcmppolicylabel_stats[] response = (cmppolicylabel_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"public static pqbinding[] get(nitro_service service, pqbinding_args args) throws Exception{\n\t\tpqbinding obj = new pqbinding();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tpqbinding[] response = (pqbinding[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"private ModelNode addLocalHost(final ModelNode address, final List<ModelNode> operationList, final String hostName) {\n\n String resolvedHost = hostName != null ? hostName : defaultHostControllerName;\n\n // All further operations should modify the newly added host so the address passed in is updated.\n address.add(HOST, resolvedHost);\n\n // Add a step to setup the ManagementResourceRegistrations for the root host resource\n final ModelNode hostAddOp = new ModelNode();\n hostAddOp.get(OP).set(HostAddHandler.OPERATION_NAME);\n hostAddOp.get(OP_ADDR).set(address);\n\n operationList.add(hostAddOp);\n\n // Add a step to store the HC name\n ModelNode nameValue = hostName == null ? new ModelNode() : new ModelNode(hostName);\n final ModelNode writeName = Util.getWriteAttributeOperation(address, NAME, nameValue);\n operationList.add(writeName);\n return hostAddOp;\n }"
] |
Gets the last element in the address.
@return the element, or {@code null} if {@link #size()} is zero. | [
"public PathElement getLastElement() {\n final List<PathElement> list = pathAddressList;\n return list.size() == 0 ? null : list.get(list.size() - 1);\n }"
] | [
"public JsonNode wbRemoveClaims(List<String> statementIds,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(statementIds,\n\t\t\t\t\"statementIds parameter cannot be null when deleting statements\");\n\t\tValidate.notEmpty(statementIds,\n\t\t\t\t\"statement ids to delete must be non-empty when deleting statements\");\n\t\tValidate.isTrue(statementIds.size() <= 50,\n\t\t\t\t\"At most 50 statements can be deleted at once\");\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"claim\", String.join(\"|\", statementIds));\n\t\t\n\t\treturn performAPIAction(\"wbremoveclaims\", null, null, null, null, parameters, summary, baserevid, bot);\n\t}",
"private char getCachedCharValue(FieldType field, char defaultValue)\n {\n Character c = (Character) getCachedValue(field);\n return c == null ? defaultValue : c.charValue();\n }",
"private void updateDefaultTimeAndSizeRollingAppender(final FoundationFileRollingAppender appender) {\n\n\t\tif (appender.getDatePattern().trim().length() == 0) {\n\t\t\tappender.setDatePattern(FoundationLoggerConstants.DEFAULT_DATE_PATTERN.toString());\n\t\t}\n\t\t\n\t\tString maxFileSizeKey = \"log4j.appender.\"+appender.getName()+\".MaxFileSize\";\n\t\tappender.setMaxFileSize(FoundationLogger.log4jConfigProps.getProperty(maxFileSizeKey, FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString()));\n\n//\t\tif (appender.getMaxFileSize() == null || appender.getMaxFileSize().equals(FoundationLoggerConstants.DEFAULT_FILE_SIZE.toString())) {\n//\t\t\tappender.setMaxFileSize(FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString());\n//\t\t}\n\n\t\tString maxRollCountKey = \"log4j.appender.\"+appender.getName()+\".MaxRollFileCount\";\n\t\tappender.setMaxRollFileCount(Integer.parseInt(FoundationLogger.log4jConfigProps.getProperty(maxRollCountKey,\"100\")));\n\t}",
"public static final boolean valueIsNotDefault(FieldType type, Object value)\n {\n boolean result = true;\n\n if (value == null)\n {\n result = false;\n }\n else\n {\n DataType dataType = type.getDataType();\n switch (dataType)\n {\n case BOOLEAN:\n {\n result = ((Boolean) value).booleanValue();\n break;\n }\n\n case CURRENCY:\n case NUMERIC:\n {\n result = !NumberHelper.equals(((Number) value).doubleValue(), 0.0, 0.00001);\n break;\n }\n\n case DURATION:\n {\n result = (((Duration) value).getDuration() != 0);\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n return result;\n }",
"public static cmppolicylabel_cmppolicy_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel_cmppolicy_binding obj = new cmppolicylabel_cmppolicy_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel_cmppolicy_binding response[] = (cmppolicylabel_cmppolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"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 setAppender(final Appender appender) {\n if (this.appender != null) {\n close();\n }\n checkAccess(this);\n if (applyLayout && appender != null) {\n final Formatter formatter = getFormatter();\n appender.setLayout(formatter == null ? null : new FormatterLayout(formatter));\n }\n appenderUpdater.set(this, appender);\n }",
"@Programmatic\n public <T> List<T> fromExcel(\n final Blob excelBlob,\n final Class<T> cls,\n final String sheetName) throws ExcelService.Exception {\n return fromExcel(excelBlob, new WorksheetSpec(cls, sheetName));\n }",
"public void addFile(File file) {\n String name = \"file\";\n files.put(normalizeDuplicateName(name), file);\n }"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.