query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Convert a date to the String representation we use in the JSON. @param d the date to convert @return the String representation we use in the JSON.
[ "private JSONValue dateToJson(Date d) {\n\n return null != d ? new JSONString(Long.toString(d.getTime())) : null;\n }" ]
[ "@Override\n public void run() {\n for (Map.Entry<String, TestSuiteResult> entry : testSuites) {\n for (TestCaseResult testCase : entry.getValue().getTestCases()) {\n markTestcaseAsInterruptedIfNotFinishedYet(testCase);\n }\n entry.getValue().getTestCases().add(createFakeTestcaseWithWarning(entry.getValue()));\n\n Allure.LIFECYCLE.fire(new TestSuiteFinishedEvent(entry.getKey()));\n }\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<InternationalFixedDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<InternationalFixedDate>) super.localDateTime(temporal);\n }", "private ProjectCalendar getResourceCalendar(Integer calendarID)\n {\n ProjectCalendar result = null;\n if (calendarID != null)\n {\n ProjectCalendar calendar = m_calMap.get(calendarID);\n if (calendar != null)\n {\n //\n // If the resource is linked to a base calendar, derive\n // a default calendar from the base calendar.\n //\n if (!calendar.isDerived())\n {\n ProjectCalendar resourceCalendar = m_project.addCalendar();\n resourceCalendar.setParent(calendar);\n resourceCalendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n result = resourceCalendar;\n }\n else\n {\n //\n // Primavera seems to allow a calendar to be shared between resources\n // whereas in the MS Project model there is a one-to-one\n // relationship. If we find a shared calendar, take a copy of it\n //\n if (calendar.getResource() == null)\n {\n result = calendar;\n }\n else\n {\n ProjectCalendar copy = m_project.addCalendar();\n copy.copy(calendar);\n result = copy;\n }\n }\n }\n }\n\n return result;\n }", "public static int getStatusBarHeight(Context context, boolean force) {\n int result = 0;\n int resourceId = context.getResources().getIdentifier(\"status_bar_height\", \"dimen\", \"android\");\n if (resourceId > 0) {\n result = context.getResources().getDimensionPixelSize(resourceId);\n }\n\n int dimenResult = context.getResources().getDimensionPixelSize(R.dimen.tool_bar_top_padding);\n //if our dimension is 0 return 0 because on those devices we don't need the height\n if (dimenResult == 0 && !force) {\n return 0;\n } else {\n //if our dimens is > 0 && the result == 0 use the dimenResult else the result;\n return result == 0 ? dimenResult : result;\n }\n }", "public static boolean isSameStructure(DMatrixSparseCSC a , DMatrixSparseCSC b) {\n if( a.numRows == b.numRows && a.numCols == b.numCols && a.nz_length == b.nz_length) {\n for (int i = 0; i <= a.numCols; i++) {\n if( a.col_idx[i] != b.col_idx[i] )\n return false;\n }\n for (int i = 0; i < a.nz_length; i++) {\n if( a.nz_rows[i] != b.nz_rows[i] )\n return false;\n }\n return true;\n }\n return false;\n }", "public void setLongAttribute(String name, Long value) {\n\t\tensureValue();\n\t\tAttribute attribute = new LongAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}", "public static AppDescriptor of(String appName, String packageName) {\n String[] packages = packageName.split(S.COMMON_SEP);\n return of(appName, packageName, Version.ofPackage(packages[0]));\n }", "public void delete(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_DELETE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // This method has no specific response - It returns an empty\r\n // sucess response if it completes without error.\r\n }", "public T reverse() {\n String id = getId();\n String REVERSE = \"_REVERSE\";\n if (id.endsWith(REVERSE)) {\n setId(id.substring(0, id.length() - REVERSE.length()));\n }\n\n float start = mStart;\n float end = mEnd;\n mStart = end;\n mEnd = start;\n mReverse = !mReverse;\n return self();\n }" ]
Prepare a batch api request using list of individual reuests. @param requests list of api requests that has to be executed in batch.
[ "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 int getBeliefCount() {\n Integer count = (Integer)introspector.getBeliefBase(ListenerMockAgent.this).get(Definitions.RECEIVED_MESSAGE_COUNT);\n if (count == null) count = 0; // Just in case, not really sure if this is necessary.\n return count;\n }", "@Override\n public void setActive(boolean active) {\n this.active = active;\n\n if (parent != null) {\n fireCollapsibleHandler();\n removeStyleName(CssName.ACTIVE);\n if (header != null) {\n header.removeStyleName(CssName.ACTIVE);\n }\n if (active) {\n if (parent != null && parent.isAccordion()) {\n parent.clearActive();\n }\n addStyleName(CssName.ACTIVE);\n\n if (header != null) {\n header.addStyleName(CssName.ACTIVE);\n }\n }\n\n if (body != null) {\n body.setDisplay(active ? Display.BLOCK : Display.NONE);\n }\n } else {\n GWT.log(\"Please make sure that the Collapsible parent is attached or existed.\", new IllegalStateException());\n }\n }", "@Beta\n public MSICredentials withObjectId(String objectId) {\n this.objectId = objectId;\n this.clientId = null;\n this.identityId = null;\n return this;\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 static BMatrixRMaj elementLessThan(DMatrixRMaj A , double value , BMatrixRMaj output )\n {\n if( output == null ) {\n output = new BMatrixRMaj(A.numRows,A.numCols);\n }\n\n output.reshape(A.numRows, A.numCols);\n\n int N = A.getNumElements();\n\n for (int i = 0; i < N; i++) {\n output.data[i] = A.data[i] < value;\n }\n\n return output;\n }", "public boolean hasRequiredMiniFluoProps() {\n boolean valid = true;\n if (getMiniStartAccumulo()) {\n // ensure that client properties are not set since we are using MiniAccumulo\n valid &= verifyStringPropNotSet(ACCUMULO_USER_PROP, CLIENT_ACCUMULO_USER_PROP);\n valid &= verifyStringPropNotSet(ACCUMULO_PASSWORD_PROP, CLIENT_ACCUMULO_PASSWORD_PROP);\n valid &= verifyStringPropNotSet(ACCUMULO_INSTANCE_PROP, CLIENT_ACCUMULO_INSTANCE_PROP);\n valid &= verifyStringPropNotSet(ACCUMULO_ZOOKEEPERS_PROP, CLIENT_ACCUMULO_ZOOKEEPERS_PROP);\n valid &= verifyStringPropNotSet(CONNECTION_ZOOKEEPERS_PROP, CLIENT_ZOOKEEPER_CONNECT_PROP);\n if (valid == false) {\n log.error(\"Client properties should not be set in your configuration if MiniFluo is \"\n + \"configured to start its own accumulo (indicated by fluo.mini.start.accumulo being \"\n + \"set to true)\");\n }\n } else {\n valid &= hasRequiredClientProps();\n valid &= hasRequiredAdminProps();\n valid &= hasRequiredOracleProps();\n valid &= hasRequiredWorkerProps();\n }\n return valid;\n }", "@Pure\n\tpublic static <P1, RESULT> Function0<RESULT> curry(final Function1<? super P1, ? extends RESULT> function, final P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function0<RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply() {\n\t\t\t\treturn function.apply(argument);\n\t\t\t}\n\t\t};\n\t}", "public static String fileNameClean(String s) {\r\n char[] chars = s.toCharArray();\r\n StringBuilder sb = new StringBuilder();\r\n for (char c : chars) {\r\n if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '_')) {\r\n sb.append(c);\r\n } else {\r\n if (c == ' ' || c == '-') {\r\n sb.append('_');\r\n } else {\r\n sb.append('x').append((int) c).append('x');\r\n }\r\n }\r\n }\r\n return sb.toString();\r\n }", "public ResponseOnSingeRequest genErrorResponse(Exception t) {\n ResponseOnSingeRequest sshResponse = new ResponseOnSingeRequest();\n String displayError = PcErrorMsgUtils.replaceErrorMsg(t.toString());\n\n sshResponse.setStackTrace(PcStringUtils.printStackTrace(t));\n sshResponse.setErrorMessage(displayError);\n sshResponse.setFailObtainResponse(true);\n\n logger.error(\"error in exec SSH. \\nIf exection is JSchException: \"\n + \"Auth cancel and using public key. \"\n + \"\\nMake sure 1. private key full path is right (try sshMeta.getPrivKeyAbsPath()). \"\n + \"\\n2. the user name and key matches \" + t);\n\n return sshResponse;\n }" ]
Parse the given projection. @param projection The projection string. @param longitudeFirst longitudeFirst
[ "public static CoordinateReferenceSystem parseProjection(\n final String projection, final Boolean longitudeFirst) {\n try {\n if (longitudeFirst == null) {\n return CRS.decode(projection);\n } else {\n return CRS.decode(projection, longitudeFirst);\n }\n } catch (NoSuchAuthorityCodeException e) {\n throw new RuntimeException(projection + \" was not recognized as a crs code\", e);\n } catch (FactoryException e) {\n throw new RuntimeException(\"Error occurred while parsing: \" + projection, e);\n }\n }" ]
[ "public void dumpKnownFieldMaps(Props props)\n {\n //for (int key=131092; key < 131098; key++)\n for (int key = 50331668; key < 50331674; key++)\n {\n byte[] fieldMapData = props.getByteArray(Integer.valueOf(key));\n if (fieldMapData != null)\n {\n System.out.println(\"KEY: \" + key);\n createFieldMap(fieldMapData);\n System.out.println(toString());\n clear();\n }\n }\n }", "public static boolean isExclusivelyKnownArchive(GraphRewrite event, String filePath)\n {\n String extension = StringUtils.substringAfterLast(filePath, \".\");\n\n if (!StringUtils.equalsIgnoreCase(extension, \"jar\"))\n return false;\n\n ZipFile archive;\n try\n {\n archive = new ZipFile(filePath);\n } catch (IOException e)\n {\n return false;\n }\n\n WindupJavaConfigurationService javaConfigurationService = new WindupJavaConfigurationService(event.getGraphContext());\n WindupJavaConfigurationModel javaConfigurationModel = WindupJavaConfigurationService.getJavaConfigurationModel(event.getGraphContext());\n\n // indicates that the user did specify some packages to scan explicitly (as opposed to scanning everything)\n boolean customerPackagesSpecified = javaConfigurationModel.getScanJavaPackages().iterator().hasNext();\n\n // this should only be true if:\n // 1) the package does not contain *any* customer packages.\n // 2) the package contains \"known\" vendor packages.\n boolean exclusivelyKnown = false;\n\n String organization = null;\n Enumeration<?> e = archive.entries();\n\n // go through all entries...\n ZipEntry entry;\n while (e.hasMoreElements())\n {\n entry = (ZipEntry) e.nextElement();\n String entryName = entry.getName();\n\n if (entry.isDirectory() || !StringUtils.endsWith(entryName, \".class\"))\n continue;\n\n String classname = PathUtil.classFilePathToClassname(entryName);\n // if the package isn't current \"known\", try to match against known packages for this entry.\n if (!exclusivelyKnown)\n {\n organization = getOrganizationForPackage(event, classname);\n if (organization != null)\n {\n exclusivelyKnown = true;\n } else\n {\n // we couldn't find a package definitively, so ignore the archive\n exclusivelyKnown = false;\n break;\n }\n }\n\n // If the user specified package names and this is in those package names, then scan it anyway\n if (customerPackagesSpecified && javaConfigurationService.shouldScanPackage(classname))\n {\n return false;\n }\n }\n\n if (exclusivelyKnown)\n LOG.info(\"Known Package: \" + archive.getName() + \"; Organization: \" + organization);\n\n // Return the evaluated exclusively known value.\n return exclusivelyKnown;\n }", "private String getJSONFromMap(Map<String, Object> propMap) {\n try {\n return new JSONObject(propMap).toString();\n } catch (Exception e) {\n return \"{}\";\n }\n }", "static Resource getOrCreateSubDeployment(final String deploymentName, final DeploymentUnit parent) {\n final Resource root = parent.getAttachment(DEPLOYMENT_RESOURCE);\n return getOrCreate(root, PathElement.pathElement(SUBDEPLOYMENT, deploymentName));\n }", "void notifyMwRevisionProcessors(MwRevision mwRevision, boolean isCurrent) {\n\t\tif (mwRevision == null || mwRevision.getPageId() <= 0) {\n\t\t\treturn;\n\t\t}\n\t\tfor (MwRevisionProcessorBroker.RevisionSubscription rs : this.revisionSubscriptions) {\n\t\t\tif (rs.onlyCurrentRevisions == isCurrent\n\t\t\t\t\t&& (rs.model == null || mwRevision.getModel().equals(\n\t\t\t\t\t\t\trs.model))) {\n\t\t\t\trs.mwRevisionProcessor.processRevision(mwRevision);\n\t\t\t}\n\t\t}\n\t}", "public Set<URI> collectOutgoingReferences(IResourceDescription description) {\n\t\tURI resourceURI = description.getURI();\n\t\tSet<URI> result = null;\n\t\tfor(IReferenceDescription reference: description.getReferenceDescriptions()) {\n\t\t\tURI targetResource = reference.getTargetEObjectUri().trimFragment();\n\t\t\tif (!resourceURI.equals(targetResource)) {\n\t\t\t\tif (result == null)\n\t\t\t\t\tresult = Sets.newHashSet(targetResource);\n\t\t\t\telse\n\t\t\t\t\tresult.add(targetResource);\n\t\t\t}\n\t\t}\n\t\tif (result != null)\n\t\t\treturn result;\n\t\treturn Collections.emptySet();\n\t}", "private void processRemarks(GanttDesignerRemark remark)\n {\n for (GanttDesignerRemark.Task remarkTask : remark.getTask())\n {\n Integer id = remarkTask.getRow();\n Task task = m_projectFile.getTaskByID(id);\n String notes = task.getNotes();\n if (notes.isEmpty())\n {\n notes = remarkTask.getContent();\n }\n else\n {\n notes = notes + '\\n' + remarkTask.getContent();\n }\n task.setNotes(notes);\n }\n }", "private CompiledStatement assignStatementArguments(CompiledStatement stmt) throws SQLException {\n\t\tboolean ok = false;\n\t\ttry {\n\t\t\tif (limit != null) {\n\t\t\t\t// we use this if SQL statement LIMITs are not supported by this database type\n\t\t\t\tstmt.setMaxRows(limit.intValue());\n\t\t\t}\n\t\t\t// set any arguments if we are logging our object\n\t\t\tObject[] argValues = null;\n\t\t\tif (logger.isLevelEnabled(Level.TRACE) && argHolders.length > 0) {\n\t\t\t\targValues = new Object[argHolders.length];\n\t\t\t}\n\t\t\tfor (int i = 0; i < argHolders.length; i++) {\n\t\t\t\tObject argValue = argHolders[i].getSqlArgValue();\n\t\t\t\tFieldType fieldType = argFieldTypes[i];\n\t\t\t\tSqlType sqlType;\n\t\t\t\tif (fieldType == null) {\n\t\t\t\t\tsqlType = argHolders[i].getSqlType();\n\t\t\t\t} else {\n\t\t\t\t\tsqlType = fieldType.getSqlType();\n\t\t\t\t}\n\t\t\t\tstmt.setObject(i, argValue, sqlType);\n\t\t\t\tif (argValues != null) {\n\t\t\t\t\targValues[i] = argValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlogger.debug(\"prepared statement '{}' with {} args\", statement, argHolders.length);\n\t\t\tif (argValues != null) {\n\t\t\t\t// need to do the (Object) cast to force args to be a single object\n\t\t\t\tlogger.trace(\"prepared statement arguments: {}\", (Object) argValues);\n\t\t\t}\n\t\t\tok = true;\n\t\t\treturn stmt;\n\t\t} finally {\n\t\t\tif (!ok) {\n\t\t\t\tIOUtils.closeThrowSqlException(stmt, \"statement\");\n\t\t\t}\n\t\t}\n\t}", "public Integer getInteger(String fieldName) {\n\t\ttry {\n\t\t\treturn hasValue(fieldName) ? Integer.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a number.\", e);\n\t\t}\n\t}" ]
set ViewPager scroller to change animation duration when sliding
[ "private void setViewPagerScroller() {\n try {\n Field scrollerField = ViewPager.class.getDeclaredField(\"mScroller\");\n scrollerField.setAccessible(true);\n Field interpolatorField = ViewPager.class.getDeclaredField(\"sInterpolator\");\n interpolatorField.setAccessible(true);\n\n scroller = new CustomDurationScroller(getContext(), (Interpolator)interpolatorField.get(null));\n scrollerField.set(this, scroller);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }" ]
[ "public void registerComponent(java.awt.Component c)\r\n {\r\n unregisterComponent(c);\r\n if (recognizerAbstractClass == null)\r\n {\r\n hmDragGestureRecognizers.put(c, \r\n dragSource.createDefaultDragGestureRecognizer(c, \r\n dragWorker.getAcceptableActions(c), dgListener)\r\n );\r\n }\r\n else\r\n {\r\n hmDragGestureRecognizers.put(c, \r\n dragSource.createDragGestureRecognizer (recognizerAbstractClass,\r\n c, dragWorker.getAcceptableActions(c), dgListener)\r\n );\r\n }\r\n }", "public final PJsonObject getJSONObject(final int i) {\n JSONObject val = this.array.optJSONObject(i);\n final String context = \"[\" + i + \"]\";\n if (val == null) {\n throw new ObjectMissingException(this, context);\n }\n return new PJsonObject(this, val, context);\n }", "public void initialize(BinaryPackageControlFile packageControlFile) {\n set(\"Binary\", packageControlFile.get(\"Package\"));\n set(\"Source\", Utils.defaultString(packageControlFile.get(\"Source\"), packageControlFile.get(\"Package\")));\n set(\"Architecture\", packageControlFile.get(\"Architecture\"));\n set(\"Version\", packageControlFile.get(\"Version\"));\n set(\"Maintainer\", packageControlFile.get(\"Maintainer\"));\n set(\"Changed-By\", packageControlFile.get(\"Maintainer\"));\n set(\"Distribution\", packageControlFile.get(\"Distribution\"));\n\n for (Entry<String, String> entry : packageControlFile.getUserDefinedFields().entrySet()) {\n set(entry.getKey(), entry.getValue());\n }\n\n StringBuilder description = new StringBuilder();\n description.append(packageControlFile.get(\"Package\"));\n if (packageControlFile.get(\"Description\") != null) {\n description.append(\" - \");\n description.append(packageControlFile.getShortDescription());\n }\n set(\"Description\", description.toString());\n }", "@Override public Object instantiateItem(ViewGroup parent, int position) {\n T content = getItem(position);\n rendererBuilder.withContent(content);\n rendererBuilder.withParent(parent);\n rendererBuilder.withLayoutInflater(LayoutInflater.from(parent.getContext()));\n Renderer<T> renderer = rendererBuilder.build();\n if (renderer == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null Renderer\");\n }\n updateRendererExtraValues(content, renderer, position);\n renderer.render();\n View view = renderer.getRootView();\n parent.addView(view);\n return view;\n }", "public static boolean isLong(CharSequence self) {\n try {\n Long.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "public static List<Representation> parseRepresentations(JsonObject jsonObject) {\n List<Representation> representations = new ArrayList<Representation>();\n for (JsonValue representationJson : jsonObject.get(\"entries\").asArray()) {\n Representation representation = new Representation(representationJson.asObject());\n representations.add(representation);\n }\n return representations;\n }", "public static AccessorPrefix determineAccessorPrefix(@Nonnull final String methodName) {\n\t\tCheck.notEmpty(methodName, \"methodName\");\n\t\tfinal Matcher m = PATTERN.matcher(methodName);\n\t\tCheck.stateIsTrue(m.find(), \"passed method name '%s' is not applicable\", methodName);\n\t\treturn new AccessorPrefix(m.group(1));\n\t}", "public static final Number parseExtendedAttributeCurrency(String value)\n {\n Number result;\n\n if (value == null)\n {\n result = null;\n }\n else\n {\n result = NumberHelper.getDouble(Double.parseDouble(correctNumberFormat(value)) / 100);\n }\n return result;\n }", "public List<String> getCorporateGroupIds(final String organizationId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n return dbOrganization.getCorporateGroupIdPrefixes();\n }" ]
flush all messages to disk @param force flush anyway(ignore flush interval)
[ "public void flushAllLogs(final boolean force) {\n Iterator<Log> iter = getLogIterator();\n while (iter.hasNext()) {\n Log log = iter.next();\n try {\n boolean needFlush = force;\n if (!needFlush) {\n long timeSinceLastFlush = System.currentTimeMillis() - log.getLastFlushedTime();\n Integer logFlushInterval = logFlushIntervalMap.get(log.getTopicName());\n if (logFlushInterval == null) {\n logFlushInterval = config.getDefaultFlushIntervalMs();\n }\n final String flushLogFormat = \"[%s] flush interval %d, last flushed %d, need flush? %s\";\n needFlush = timeSinceLastFlush >= logFlushInterval.intValue();\n logger.trace(String.format(flushLogFormat, log.getTopicName(), logFlushInterval,\n log.getLastFlushedTime(), needFlush));\n }\n if (needFlush) {\n log.flush();\n }\n } catch (IOException ioe) {\n logger.error(\"Error flushing topic \" + log.getTopicName(), ioe);\n logger.error(\"Halting due to unrecoverable I/O error while flushing logs: \" + ioe.getMessage(), ioe);\n Runtime.getRuntime().halt(1);\n } catch (Exception e) {\n logger.error(\"Error flushing topic \" + log.getTopicName(), e);\n }\n }\n }" ]
[ "public static base_response delete(nitro_service client, ntpserver resource) throws Exception {\n\t\tntpserver deleteresource = new ntpserver();\n\t\tdeleteresource.serverip = resource.serverip;\n\t\tdeleteresource.servername = resource.servername;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "private void copyToStrBuffer(byte[] buffer, int offset, int length) {\n Preconditions.checkArgument(length >= 0);\n if (strBuffer.length - strBufferIndex < length) {\n // cannot fit, expanding buffer\n expandStrBuffer(length);\n }\n System.arraycopy(\n buffer, offset, strBuffer, strBufferIndex, Math.min(length, MAX_ALLOWABLE_BUFFER_SIZE - strBufferIndex));\n strBufferIndex += length;\n }", "public void logAttributeWarning(PathAddress address, ModelNode operation, String message, String attribute) {\n messageQueue.add(new AttributeLogEntry(address, operation, message, attribute));\n }", "public void updateInfo(Info info) {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"PUT\");\n request.setBody(info.getPendingChanges());\n BoxAPIResponse boxAPIResponse = request.send();\n\n if (boxAPIResponse instanceof BoxJSONResponse) {\n BoxJSONResponse response = (BoxJSONResponse) boxAPIResponse;\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n info.update(jsonObject);\n }\n }", "@Override\n protected void runUnsafe() throws Exception {\n Path reportDirectory = getReportDirectoryPath();\n Files.walkFileTree(reportDirectory, new DeleteVisitor());\n LOGGER.info(\"Report directory <{}> was successfully cleaned.\", reportDirectory);\n }", "private List<Integer> getNodeIdListForPartitionIdList(List<Integer> partitionIds)\n throws VoldemortException {\n List<Integer> nodeIds = new ArrayList<Integer>(partitionIds.size());\n for(Integer partitionId: partitionIds) {\n int nodeId = getNodeIdForPartitionId(partitionId);\n if(nodeIds.contains(nodeId)) {\n throw new VoldemortException(\"Node ID \" + nodeId + \" already in list of Node IDs.\");\n } else {\n nodeIds.add(nodeId);\n }\n }\n return nodeIds;\n }", "private String parseAddress(String address) {\r\n try {\r\n StringBuilder buf = new StringBuilder();\r\n InternetAddress[] netAddrs = InternetAddress.parseHeader(address, false);\r\n for (InternetAddress netAddr : netAddrs) {\r\n if (buf.length() > 0) {\r\n buf.append(SP);\r\n }\r\n\r\n buf.append(LB);\r\n\r\n String personal = netAddr.getPersonal();\r\n if (personal != null && (personal.length() != 0)) {\r\n buf.append(Q).append(personal).append(Q);\r\n } else {\r\n buf.append(NIL);\r\n }\r\n buf.append(SP);\r\n buf.append(NIL); // should add route-addr\r\n buf.append(SP);\r\n try {\r\n // Remove quotes to avoid double quoting\r\n MailAddress mailAddr = new MailAddress(netAddr.getAddress().replaceAll(\"\\\"\", \"\\\\\\\\\\\"\"));\r\n buf.append(Q).append(mailAddr.getUser()).append(Q);\r\n buf.append(SP);\r\n buf.append(Q).append(mailAddr.getHost()).append(Q);\r\n } catch (Exception pe) {\r\n buf.append(NIL + SP + NIL);\r\n }\r\n buf.append(RB);\r\n }\r\n\r\n return buf.toString();\r\n } catch (AddressException e) {\r\n throw new RuntimeException(\"Failed to parse address: \" + address, e);\r\n }\r\n }", "ModelNode toModelNode() {\n ModelNode result = null;\n if (map != null) {\n result = new ModelNode();\n for (Map.Entry<PathAddress, ResourceData> entry : map.entrySet()) {\n ModelNode item = new ModelNode();\n PathAddress pa = entry.getKey();\n item.get(ABSOLUTE_ADDRESS).set(pa.toModelNode());\n ResourceData rd = entry.getValue();\n item.get(RELATIVE_ADDRESS).set(pa.subAddress(baseAddressLength).toModelNode());\n ModelNode attrs = new ModelNode().setEmptyList();\n if (rd.attributes != null) {\n for (String attr : rd.attributes) {\n attrs.add(attr);\n }\n }\n if (attrs.asInt() > 0) {\n item.get(FILTERED_ATTRIBUTES).set(attrs);\n }\n ModelNode children = new ModelNode().setEmptyList();\n if (rd.children != null) {\n for (PathElement pe : rd.children) {\n children.add(new Property(pe.getKey(), new ModelNode(pe.getValue())));\n }\n }\n if (children.asInt() > 0) {\n item.get(UNREADABLE_CHILDREN).set(children);\n }\n ModelNode childTypes = new ModelNode().setEmptyList();\n if (rd.childTypes != null) {\n Set<String> added = new HashSet<String>();\n for (PathElement pe : rd.childTypes) {\n if (added.add(pe.getKey())) {\n childTypes.add(pe.getKey());\n }\n }\n }\n if (childTypes.asInt() > 0) {\n item.get(FILTERED_CHILDREN_TYPES).set(childTypes);\n }\n result.add(item);\n }\n }\n return result;\n }", "@JmxGetter(name = \"avgFetchEntriesNetworkTimeMs\", description = \"average time spent on network, for streaming operations\")\n public double getAvgFetchEntriesNetworkTimeMs() {\n return networkTimeCounterMap.get(Operation.FETCH_ENTRIES).getAvgEventValue()\n / Time.NS_PER_MS;\n }" ]
Visits a method instruction. A method instruction is an instruction that invokes a method. @param opcode the opcode of the type instruction to be visited. This opcode is either INVOKEVIRTUAL, INVOKESPECIAL, INVOKESTATIC or INVOKEINTERFACE. @param owner the internal name of the method's owner class (see {@link Type#getInternalName() getInternalName}). @param name the method's name. @param desc the method's descriptor (see {@link Type Type}). @param itf if the method's owner class is an interface.
[ "public void visitMethodInsn(int opcode, String owner, String name,\n String desc, boolean itf) {\n if (mv != null) {\n mv.visitMethodInsn(opcode, owner, name, desc, itf);\n }\n }" ]
[ "public static Set<String> listAllLinks(OperationContext context, String overlay) {\n Set<String> serverGoupNames = listServerGroupsReferencingOverlay(context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS), overlay);\n Set<String> links = new HashSet<>();\n for (String serverGoupName : serverGoupNames) {\n links.addAll(listLinks(context, PathAddress.pathAddress(\n PathElement.pathElement(SERVER_GROUP, serverGoupName),\n PathElement.pathElement(DEPLOYMENT_OVERLAY, overlay))));\n }\n return links;\n }", "public AT_Row setPaddingRightChar(Character paddingRightChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingRightChar(paddingRightChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public static base_response restart(nitro_service client) throws Exception {\n\t\tdbsmonitors restartresource = new dbsmonitors();\n\t\treturn restartresource.perform_operation(client,\"restart\");\n\t}", "private static CmsUUID toUuid(String uuid) {\n\n if (\"null\".equals(uuid) || CmsStringUtil.isEmpty(uuid)) {\n return null;\n }\n return new CmsUUID(uuid);\n\n }", "public static boolean isLogDownloadAvailable(CliGuiContext cliGuiCtx) {\n ModelNode readOps = null;\n try {\n readOps = cliGuiCtx.getExecutor().doCommand(\"/subsystem=logging:read-children-types\");\n } catch (CommandFormatException | IOException e) {\n return false;\n }\n if (!readOps.get(\"result\").isDefined()) return false;\n for (ModelNode op: readOps.get(\"result\").asList()) {\n if (\"log-file\".equals(op.asString())) return true;\n }\n return false;\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<Symmetry010Date> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<Symmetry010Date>) super.zonedDateTime(temporal);\n }", "private double getExpectedProbability(double x)\n {\n double y = 1 / (standardDeviation * Math.sqrt(Math.PI * 2));\n double z = -(Math.pow(x - mean, 2) / (2 * Math.pow(standardDeviation, 2)));\n return y * Math.exp(z);\n }", "public static boolean isSinglePositionPrefix(FieldInfo fieldInfo,\n String prefix) throws IOException {\n if (fieldInfo == null) {\n throw new IOException(\"no fieldInfo\");\n } else {\n String info = fieldInfo.getAttribute(\n MtasCodecPostingsFormat.MTAS_FIELDINFO_ATTRIBUTE_PREFIX_SINGLE_POSITION);\n if (info == null) {\n throw new IOException(\"no \"\n + MtasCodecPostingsFormat.MTAS_FIELDINFO_ATTRIBUTE_PREFIX_SINGLE_POSITION);\n } else {\n return Arrays.asList(info.split(Pattern.quote(MtasToken.DELIMITER)))\n .contains(prefix);\n }\n }\n }", "public void resume() {\n this.paused = false;\n ServerActivityCallback listener = listenerUpdater.get(this);\n if (listener != null) {\n listenerUpdater.compareAndSet(this, listener, null);\n }\n }" ]
Helper to format term updates as expected by the Wikibase API @param updates planned updates for the type of term @return map ready to be serialized as JSON by Jackson
[ "protected Map<String, TermImpl> getMonolingualUpdatedValues(Map<String, NameWithUpdate> updates) {\n \tMap<String, TermImpl> updatedValues = new HashMap<>();\n \tfor(NameWithUpdate update : updates.values()) {\n if (!update.write) {\n continue;\n }\n updatedValues.put(update.value.getLanguageCode(), monolingualToJackson(update.value));\n \t}\n \treturn updatedValues;\n }" ]
[ "public NamespacesList<Pair> getPairs(String namespace, String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Pair> nsList = new NamespacesList<Pair>();\r\n parameters.put(\"method\", METHOD_GET_PAIRS);\r\n\r\n if (namespace != null) {\r\n parameters.put(\"namespace\", namespace);\r\n }\r\n if (predicate != null) {\r\n parameters.put(\"predicate\", predicate);\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element nsElement = response.getPayload();\r\n NodeList nsNodes = nsElement.getElementsByTagName(\"pair\");\r\n nsList.setPage(nsElement.getAttribute(\"page\"));\r\n nsList.setPages(nsElement.getAttribute(\"pages\"));\r\n nsList.setPerPage(nsElement.getAttribute(\"perPage\"));\r\n nsList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n nsList.add(parsePair(element));\r\n }\r\n return nsList;\r\n }", "public List<Action> getRootActions() {\n\t\tfinal List<Action> rootActions = srcUpdTrees.stream().map(t -> originalActionsSrc.get(t))\n\t\t\t\t.collect(Collectors.toList());\n\n\t\trootActions.addAll(srcDelTrees.stream() //\n\t\t\t\t.filter(t -> !srcDelTrees.contains(t.getParent()) && !srcUpdTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsSrc.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.addAll(dstAddTrees.stream() //\n\t\t\t\t.filter(t -> !dstAddTrees.contains(t.getParent()) && !dstUpdTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsDst.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.addAll(dstMvTrees.stream() //\n\t\t\t\t.filter(t -> !dstMvTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsDst.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.removeAll(Collections.singleton(null));\n\t\treturn rootActions;\n\t}", "private ProjectFile read() throws Exception\n {\n m_project = new ProjectFile();\n m_eventManager = m_project.getEventManager();\n\n ProjectConfig config = m_project.getProjectConfig();\n config.setAutoCalendarUniqueID(false);\n config.setAutoTaskID(false);\n config.setAutoTaskUniqueID(false);\n config.setAutoResourceUniqueID(false);\n config.setAutoWBS(false);\n config.setAutoOutlineNumber(false);\n\n m_project.getProjectProperties().setFileApplication(\"FastTrack\");\n m_project.getProjectProperties().setFileType(\"FTS\");\n\n m_eventManager.addProjectListeners(m_projectListeners);\n\n // processProject();\n // processCalendars();\n processResources();\n processTasks();\n processDependencies();\n processAssignments();\n\n return m_project;\n }", "void logAuditRecord() {\n trackConfigurationChange();\n if (!auditLogged) {\n try {\n AccessAuditContext accessContext = SecurityActions.currentAccessAuditContext();\n Caller caller = getCaller();\n auditLogger.log(\n isReadOnly(),\n resultAction,\n caller == null ? null : caller.getName(),\n accessContext == null ? null : accessContext.getDomainUuid(),\n accessContext == null ? null : accessContext.getAccessMechanism(),\n accessContext == null ? null : accessContext.getRemoteAddress(),\n getModel(),\n controllerOperations);\n auditLogged = true;\n } catch (Exception e) {\n ControllerLogger.MGMT_OP_LOGGER.failedToUpdateAuditLog(e);\n }\n }\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 Sites getSitesInformation() throws IOException {\n\t\tMwDumpFile sitesTableDump = getMostRecentDump(DumpContentType.SITES);\n\t\tif (sitesTableDump == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Create a suitable processor for such dumps and process the file:\n\t\tMwSitesDumpFileProcessor sitesDumpFileProcessor = new MwSitesDumpFileProcessor();\n\t\tsitesDumpFileProcessor.processDumpFileContents(\n\t\t\t\tsitesTableDump.getDumpFileStream(), sitesTableDump);\n\n\t\treturn sitesDumpFileProcessor.getSites();\n\t}", "@Override\n public final Job queueIn(final Job job, final long millis) {\n return pushAt(job, System.currentTimeMillis() + millis);\n }", "public static Cluster getCluster(ZkClient zkClient) {\n Cluster cluster = new Cluster();\n List<String> nodes = getChildrenParentMayNotExist(zkClient, BrokerIdsPath);\n for (String node : nodes) {\n final String brokerInfoString = readData(zkClient, BrokerIdsPath + \"/\" + node);\n cluster.add(Broker.createBroker(Integer.valueOf(node), brokerInfoString));\n }\n return cluster;\n }", "public ThreadUsage getThreadUsage() {\n ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();\n\n ThreadUsage threadUsage = new ThreadUsage();\n long[] threadIds = threadMxBean.getAllThreadIds();\n threadUsage.liveThreadCount = threadIds.length;\n\n for (long tId : threadIds) {\n ThreadInfo threadInfo = threadMxBean.getThreadInfo(tId);\n threadUsage.threadData.put(Long.toString(tId), new ThreadData(\n threadInfo.getThreadName(), threadInfo.getThreadState()\n .name(), threadMxBean.getThreadCpuTime(tId)));\n\n }\n return threadUsage;\n }" ]
Generates an artifact regarding the parameters. <P> <b>WARNING:</b> The parameters grId/arId/version should be filled!!! Only classifier and type are not mandatory. @param groupId String @param artifactId String @param version String @param classifier String @param type String @param extension String @return Artifact
[ "public static Artifact createArtifact(final String groupId, final String artifactId, final String version, final String classifier, final String type, final String extension, final String origin){\n\t\tfinal Artifact artifact = new Artifact();\n\n\t\tartifact.setGroupId(groupId);\n\t\tartifact.setArtifactId(artifactId);\n\t\tartifact.setVersion(version);\n\n\t\tif(classifier != null){\n\t\t\tartifact.setClassifier(classifier);\n\t\t}\n\n\t\tif(type != null){\n\t\t\tartifact.setType(type);\n\t\t}\n\n\t\tif(extension != null){\n\t\t\tartifact.setExtension(extension);\n\t\t}\n\n\t\tartifact.setOrigin(origin == null ? \"maven\" : origin);\n\n\t\treturn artifact;\n\t}" ]
[ "public static systementitydata[] get(nitro_service service, systementitydata_args args) throws Exception{\n\t\tsystementitydata obj = new systementitydata();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tsystementitydata[] response = (systementitydata[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public CollectionRequest<Team> findByOrganization(String organization) {\n \n String path = String.format(\"/organizations/%s/teams\", organization);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }", "protected String getUserDefinedFieldName(String field) {\n int index = field.indexOf('-');\n char letter = getUserDefinedFieldLetter();\n\n for (int i = 0; i < index; ++i) {\n if (field.charAt(i) == letter) {\n return field.substring(index + 1);\n }\n }\n\n return null;\n }", "private Charset getCharset()\n {\n Charset result = m_charset;\n if (result == null)\n {\n // We default to CP1252 as this seems to be the most common encoding\n result = m_encoding == null ? CharsetHelper.CP1252 : Charset.forName(m_encoding);\n }\n return result;\n }", "@Override\n public boolean decompose( ZMatrixRMaj A )\n {\n if( A.numRows != A.numCols )\n throw new IllegalArgumentException(\"A must be square.\");\n if( A.numRows <= 0 )\n return false;\n\n QH = A;\n\n N = A.numCols;\n\n if( b.length < N*2 ) {\n b = new double[ N*2 ];\n gammas = new double[ N ];\n u = new double[ N*2 ];\n }\n return _decompose();\n }", "public Map<String, CmsCategory> getReadCategory() {\n\n if (null == m_categories) {\n m_categories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object categoryPath) {\n\n try {\n CmsCategoryService catService = CmsCategoryService.getInstance();\n return catService.localizeCategory(\n m_cms,\n catService.readCategory(m_cms, (String)categoryPath, getRequestContext().getUri()),\n m_cms.getRequestContext().getLocale());\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n\n });\n }\n return m_categories;\n }", "public static DMatrixRMaj diagonal(int numRows , int numCols , double min , double max , Random rand ) {\n if( max < min )\n throw new IllegalArgumentException(\"The max must be >= the min\");\n\n DMatrixRMaj ret = new DMatrixRMaj(numRows,numCols);\n\n int N = Math.min(numRows,numCols);\n\n double r = max-min;\n\n for( int i = 0; i < N; i++ ) {\n ret.set(i,i, rand.nextDouble()*r+min);\n }\n\n return ret;\n }", "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 }", "public static base_responses update(nitro_service client, systemuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsystemuser updateresources[] = new systemuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new systemuser();\n\t\t\t\tupdateresources[i].username = resources[i].username;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].externalauth = resources[i].externalauth;\n\t\t\t\tupdateresources[i].promptstring = resources[i].promptstring;\n\t\t\t\tupdateresources[i].timeout = resources[i].timeout;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Reverse Engineers an XPath Expression of a given Node in the DOM. @param node the given node. @return string xpath expression (e.g., "/html[1]/body[1]/div[3]").
[ "public static String getXPathExpression(Node node) {\n\t\tObject xpathCache = node.getUserData(FULL_XPATH_CACHE);\n\t\tif (xpathCache != null) {\n\t\t\treturn xpathCache.toString();\n\t\t}\n\t\tNode parent = node.getParentNode();\n\n\t\tif ((parent == null) || parent.getNodeName().contains(\"#document\")) {\n\t\t\tString xPath = \"/\" + node.getNodeName() + \"[1]\";\n\t\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\t\treturn xPath;\n\t\t}\n\n\t\tif (node.hasAttributes() && node.getAttributes().getNamedItem(\"id\") != null) {\n\t\t\tString xPath = \"//\" + node.getNodeName() + \"[@id = '\"\n\t\t\t\t\t+ node.getAttributes().getNamedItem(\"id\").getNodeValue() + \"']\";\n\t\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\t\treturn xPath;\n\t\t}\n\n\t\tStringBuffer buffer = new StringBuffer();\n\n\t\tif (parent != node) {\n\t\t\tbuffer.append(getXPathExpression(parent));\n\t\t\tbuffer.append(\"/\");\n\t\t}\n\n\t\tbuffer.append(node.getNodeName());\n\n\t\tList<Node> mySiblings = getSiblings(parent, node);\n\n\t\tfor (int i = 0; i < mySiblings.size(); i++) {\n\t\t\tNode el = mySiblings.get(i);\n\n\t\t\tif (el.equals(node)) {\n\t\t\t\tbuffer.append('[').append(Integer.toString(i + 1)).append(']');\n\t\t\t\t// Found so break;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tString xPath = buffer.toString();\n\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\treturn xPath;\n\t}" ]
[ "public static void validateRollbackState(final String patchID, final InstalledIdentity identity) throws PatchingException {\n final Set<String> validHistory = processRollbackState(patchID, identity);\n if (patchID != null && !validHistory.contains(patchID)) {\n throw PatchLogger.ROOT_LOGGER.patchNotFoundInHistory(patchID);\n }\n }", "final protected String getTrimmedString() throws BadMessage {\n if (_bufferPosition == 0) return \"\";\n\n int start = 0;\n boolean quoted = false;\n // Look for start\n while (start < _bufferPosition) {\n final char ch = _internalBuffer[start];\n if (ch == '\"') {\n quoted = true;\n break;\n }\n else if (ch != HttpTokens.SPACE && ch != HttpTokens.TAB) {\n break;\n }\n start++;\n }\n\n int end = _bufferPosition; // Position is of next write\n\n // Look for end\n while(end > start) {\n final char ch = _internalBuffer[end - 1];\n\n if (quoted) {\n if (ch == '\"') break;\n else if (ch != HttpTokens.SPACE && ch != HttpTokens.TAB) {\n throw new BadMessage(\"String might not quoted correctly: '\" + getString() + \"'\");\n }\n }\n else if (ch != HttpTokens.SPACE && ch != HttpTokens.TAB) break;\n end--;\n }\n\n String str = new String(_internalBuffer, start, end - start);\n\n return str;\n }", "public void set1Value(int index, String newValue) {\n try {\n value.set( index, newValue );\n }\n catch (IndexOutOfBoundsException e) {\n Log.e(TAG, \"X3D MFString set1Value(int index, ...) out of bounds.\" + e);\n }\n catch (Exception e) {\n Log.e(TAG, \"X3D MFString set1Value(int index, ...) exception \" + e);\n }\n }", "public static base_response change(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey updateresource = new sslcertkey();\n\t\tupdateresource.certkey = resource.certkey;\n\t\tupdateresource.cert = resource.cert;\n\t\tupdateresource.key = resource.key;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.fipskey = resource.fipskey;\n\t\tupdateresource.inform = resource.inform;\n\t\tupdateresource.passplain = resource.passplain;\n\t\tupdateresource.nodomaincheck = resource.nodomaincheck;\n\t\treturn updateresource.perform_operation(client,\"update\");\n\t}", "public void abort() {\n URL abortURL = this.sessionInfo.getSessionEndpoints().getAbortEndpoint();\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), abortURL, HttpMethod.DELETE);\n request.send();\n }", "public Weld addPackages(boolean scanRecursively, Class<?>... packageClasses) {\n for (Class<?> packageClass : packageClasses) {\n addPackage(scanRecursively, packageClass);\n }\n return this;\n }", "public List<MapRow> readUnknownTable(int rowSize, int rowMagicNumber) throws IOException\n {\n TableReader reader = new UnknownTableReader(this, rowSize, rowMagicNumber);\n reader.read();\n return reader.getRows();\n }", "public void unlock() {\n\n for (Locale l : m_lockedBundleFiles.keySet()) {\n LockedFile f = m_lockedBundleFiles.get(l);\n f.tryUnlock();\n }\n if (null != m_descFile) {\n m_descFile.tryUnlock();\n }\n }", "private void deliverCacheUpdate(SlotReference slot, MetadataCache cache) {\n for (final MetadataCacheListener listener : getCacheListeners()) {\n try {\n if (cache == null) {\n listener.cacheDetached(slot);\n } else {\n listener.cacheAttached(slot, cache);\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering metadata cache update to listener\", t);\n }\n }\n }" ]
Notifies that multiple content items are changed. @param positionStart the position. @param itemCount the item count.
[ "public final void notifyContentItemRangeChanged(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for content items [0 - \"\n + (contentItemCount - 1) + \"].\");\n }\n notifyItemRangeChanged(positionStart + headerItemCount, itemCount);\n }" ]
[ "private static int tribus(int version, int a, int b, int c) {\n if (version < 10) {\n return a;\n } else if (version >= 10 && version <= 26) {\n return b;\n } else {\n return c;\n }\n }", "public String isChecked(String value1, String value2) {\n\n if ((value1 == null) || (value2 == null)) {\n return \"\";\n }\n\n if (value1.trim().equalsIgnoreCase(value2.trim())) {\n return \"checked\";\n }\n\n return \"\";\n }", "public static String getAt(GString text, int index) {\n return (String) getAt(text.toString(), index);\n }", "protected Map getAllVariables(){\n try{\n Iterator names = FreeMarkerTL.getEnvironment().getKnownVariableNames().iterator();\n Map vars = new HashMap();\n while (names.hasNext()) {\n Object name =names.next();\n vars.put(name, get(name.toString()));\n }\n return vars;\n }catch(Exception e){\n throw new ViewException(e);\n }\n }", "public static sslcipher[] get(nitro_service service, String ciphergroupname[]) throws Exception{\n\t\tif (ciphergroupname !=null && ciphergroupname.length>0) {\n\t\t\tsslcipher response[] = new sslcipher[ciphergroupname.length];\n\t\t\tsslcipher obj[] = new sslcipher[ciphergroupname.length];\n\t\t\tfor (int i=0;i<ciphergroupname.length;i++) {\n\t\t\t\tobj[i] = new sslcipher();\n\t\t\t\tobj[i].set_ciphergroupname(ciphergroupname[i]);\n\t\t\t\tresponse[i] = (sslcipher) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public void afterLoading(CollectionProxyDefaultImpl colProxy)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"loading a proxied collection a collection: \" + colProxy);\r\n Collection data = colProxy.getData();\r\n for (Iterator iterator = data.iterator(); iterator.hasNext();)\r\n {\r\n Object o = iterator.next();\r\n if(!isOpen())\r\n {\r\n log.error(\"Collection proxy materialization outside of a running tx, obj=\" + o);\r\n try{throw new Exception(\"Collection proxy materialization outside of a running tx, obj=\" + o);}\r\n catch(Exception e)\r\n {e.printStackTrace();}\r\n }\r\n else\r\n {\r\n Identity oid = getBroker().serviceIdentity().buildIdentity(o);\r\n ClassDescriptor cld = getBroker().getClassDescriptor(ProxyHelper.getRealClass(o));\r\n RuntimeObject rt = new RuntimeObject(o, oid, cld, false, ProxyHelper.isProxy(o));\r\n lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList());\r\n }\r\n }\r\n unregisterFromCollectionProxy(colProxy);\r\n }", "public static boolean isFinalVariable(DeclarationExpression declarationExpression, SourceCode sourceCode) {\r\n if (isFromGeneratedSourceCode(declarationExpression)) {\r\n return false;\r\n }\r\n List<Expression> variableExpressions = getVariableExpressions(declarationExpression);\r\n if (!variableExpressions.isEmpty()) {\r\n Expression variableExpression = variableExpressions.get(0);\r\n int startOfDeclaration = declarationExpression.getColumnNumber();\r\n int startOfVariableName = variableExpression.getColumnNumber();\r\n int sourceLineNumber = findFirstNonAnnotationLine(declarationExpression, sourceCode);\r\n String sourceLine = sourceCode.getLines().get(sourceLineNumber-1);\r\n\r\n String modifiers = (startOfDeclaration >= 0 && startOfVariableName >= 0 && sourceLine.length() >= startOfVariableName) ?\r\n sourceLine.substring(startOfDeclaration - 1, startOfVariableName - 1) : \"\";\r\n return modifiers.contains(\"final\");\r\n }\r\n return false;\r\n }", "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 }", "private static void addRedeployOperationStep(final CompositeOperationBuilder builder, final DeploymentDescription deployment) {\n final String deploymentName = deployment.getName();\n final Set<String> serverGroups = deployment.getServerGroups();\n if (serverGroups.isEmpty()) {\n builder.addStep(createOperation(DEPLOYMENT_REDEPLOY_OPERATION, createAddress(DEPLOYMENT, deploymentName)));\n } else {\n for (String serverGroup : serverGroups) {\n builder.addStep(createOperation(DEPLOYMENT_REDEPLOY_OPERATION, createAddress(SERVER_GROUP, serverGroup, DEPLOYMENT, deploymentName)));\n }\n }\n }" ]
Return configuration tweaks in a format appropriate for ness-jdbc DatabaseModule.
[ "public ImmutableMap<String, String> getConfigurationTweak(String dbModuleName)\n {\n final DbInfo db = cluster.getNextDb();\n return ImmutableMap.of(\"ness.db.\" + dbModuleName + \".uri\", getJdbcUri(db),\n \"ness.db.\" + dbModuleName + \".ds.user\", db.user);\n }" ]
[ "public void run() {\r\n\t\tConnectionHandle connection = null;\r\n\t\tlong tmp;\r\n\t\tlong nextCheckInMs = this.maxAgeInMs;\r\n\r\n\t\tint partitionSize= this.partition.getAvailableConnections();\r\n\t\tlong currentTime = System.currentTimeMillis();\r\n\t\tfor (int i=0; i < partitionSize; i++){\r\n\t\t\ttry {\r\n\t\t\t\tconnection = this.partition.getFreeConnections().poll();\r\n\r\n\t\t\t\tif (connection != null){\r\n\t\t\t\t\tconnection.setOriginatingPartition(this.partition);\r\n\r\n\t\t\t\t\ttmp = this.maxAgeInMs - (currentTime - connection.getConnectionCreationTimeInMs()); \r\n\r\n\t\t\t\t\tif (tmp < nextCheckInMs){\r\n\t\t\t\t\t\tnextCheckInMs = tmp; \r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (connection.isExpired(currentTime)){\r\n\t\t\t\t\t\t// kill off this connection\r\n\t\t\t\t\t\tcloseConnection(connection);\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (this.lifoMode){\r\n\t\t\t\t\t\t// we can't put it back normally or it will end up in front again.\r\n\t\t\t\t\t\tif (!(connection.getOriginatingPartition().getFreeConnections().offer(connection))){\r\n\t\t\t\t\t\t\tconnection.internalClose();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tthis.pool.putConnectionBackInPartition(connection);\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\tThread.sleep(20L); // test slowly, this is not an operation that we're in a hurry to deal with (avoid CPU spikes)...\r\n\t\t\t\t}\r\n\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\tlogger.error(\"Connection max age thread exception.\", e);\r\n\t\t\t}\r\n\r\n\t\t} // throw it back on the queue\r\n\r\n\t}", "protected int getDonorId(StoreRoutingPlan currentSRP,\n StoreRoutingPlan finalSRP,\n int stealerZoneId,\n int stealerNodeId,\n int stealerPartitionId) {\n int stealerZoneNAry = finalSRP.getZoneNaryForNodesPartition(stealerZoneId,\n stealerNodeId,\n stealerPartitionId);\n\n int donorZoneId;\n if(currentSRP.zoneNAryExists(stealerZoneId, stealerZoneNAry, stealerPartitionId)) {\n // Steal from local n-ary (since one exists).\n donorZoneId = stealerZoneId;\n } else {\n // Steal from zone that hosts primary partition Id.\n int currentMasterNodeId = currentSRP.getNodeIdForPartitionId(stealerPartitionId);\n donorZoneId = currentCluster.getNodeById(currentMasterNodeId).getZoneId();\n }\n\n return currentSRP.getNodeIdForZoneNary(donorZoneId, stealerZoneNAry, stealerPartitionId);\n\n }", "public void safeRevertWorkingCopy() {\n try {\n revertWorkingCopy();\n } catch (Exception e) {\n debuggingLogger.log(Level.FINE, \"Failed to revert working copy\", e);\n log(\"Failed to revert working copy: \" + e.getLocalizedMessage());\n Throwable cause = e.getCause();\n if (!(cause instanceof SVNException)) {\n return;\n }\n SVNException svnException = (SVNException) cause;\n if (svnException.getErrorMessage().getErrorCode() == SVNErrorCode.WC_LOCKED) {\n // work space locked attempt cleanup and try to revert again\n try {\n cleanupWorkingCopy();\n } catch (Exception unlockException) {\n debuggingLogger.log(Level.FINE, \"Failed to cleanup working copy\", e);\n log(\"Failed to cleanup working copy: \" + e.getLocalizedMessage());\n return;\n }\n\n try {\n revertWorkingCopy();\n } catch (Exception revertException) {\n log(\"Failed to revert working copy on the 2nd attempt: \" + e.getLocalizedMessage());\n }\n }\n }\n }", "private void processColumns()\n {\n int fieldID = MPPUtility.getInt(m_data, m_headerOffset);\n m_headerOffset += 4;\n\n m_dataOffset = MPPUtility.getInt(m_data, m_headerOffset);\n m_headerOffset += 4;\n\n FieldType type = FieldTypeHelper.getInstance(fieldID);\n if (type.getDataType() != null)\n {\n processKnownType(type);\n }\n }", "public static KnowledgeBuilderConfiguration newKnowledgeBuilderConfiguration(Properties properties,\n ClassLoader... classLoaders) {\n return FactoryServiceHolder.factoryService.newKnowledgeBuilderConfiguration( properties, classLoaders );\n }", "public void applyToPrimaryClassNodes(PrimaryClassNodeOperation body) throws CompilationFailedException {\n Iterator classNodes = getPrimaryClassNodes(body.needSortedInput()).iterator();\n while (classNodes.hasNext()) {\n SourceUnit context = null;\n try {\n ClassNode classNode = (ClassNode) classNodes.next();\n context = classNode.getModule().getContext();\n if (context == null || context.phase < phase || (context.phase == phase && !context.phaseComplete)) {\n int offset = 1;\n Iterator<InnerClassNode> iterator = classNode.getInnerClasses();\n while (iterator.hasNext()) {\n iterator.next();\n offset++;\n }\n body.call(context, new GeneratorContext(this.ast, offset), classNode);\n }\n } catch (CompilationFailedException e) {\n // fall through, getErrorReporter().failIfErrors() will trigger\n } catch (NullPointerException npe) {\n GroovyBugError gbe = new GroovyBugError(\"unexpected NullpointerException\", npe);\n changeBugText(gbe, context);\n throw gbe;\n } catch (GroovyBugError e) {\n changeBugText(e, context);\n throw e;\n } catch (NoClassDefFoundError e) {\n // effort to get more logging in case a dependency of a class is loaded\n // although it shouldn't have\n convertUncaughtExceptionToCompilationError(e);\n } catch (Exception e) {\n convertUncaughtExceptionToCompilationError(e);\n }\n }\n\n getErrorCollector().failIfErrors();\n }", "public void beforeBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final Method methodSetExecuteBatch;\r\n final Method methodSendBatch;\r\n methodSetExecuteBatch = ClassHelper.getMethod(stmt, \"setExecuteBatch\", PARAM_TYPE_INTEGER);\r\n methodSendBatch = ClassHelper.getMethod(stmt, \"sendBatch\", null);\r\n\r\n final boolean statementBatchingSupported = methodSetExecuteBatch != null && methodSendBatch != null;\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n // Set number of statements per batch\r\n methodSetExecuteBatch.invoke(stmt, PARAM_STATEMENT_BATCH_SIZE);\r\n m_batchStatementsInProgress.put(stmt, methodSendBatch);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new PlatformException(e.getLocalizedMessage(), e);\r\n }\r\n }\r\n else\r\n {\r\n super.beforeBatch(stmt);\r\n }\r\n }", "public void delete() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_WHITELIST_ENTRY_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, HttpMethod.DELETE);\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "public <T> T convert(ConversionContext context, Object source,\r\n\t\t\tTypeReference<T> destinationType) throws ConverterException {\r\n\t\ttry {\r\n\t\t\treturn (T) multiConverter.convert(context, source, destinationType);\r\n\t\t} catch (ConverterException e) {\r\n\t\t\tthrow e;\r\n\t\t} catch (Exception e) {\r\n\t\t\t// There is a problem with one converter. This should not happen.\r\n\t\t\t// Either there is a bug in this converter or it is not properly\r\n\t\t\t// configured\r\n\t\t\tthrow new ConverterException(\r\n\t\t\t\t\tMessageFormat\r\n\t\t\t\t\t\t\t.format(\r\n\t\t\t\t\t\t\t\t\t\"Could not convert given object with class ''{0}'' to object with type signature ''{1}''\",\r\n\t\t\t\t\t\t\t\t\tsource == null ? \"null\" : source.getClass()\r\n\t\t\t\t\t\t\t\t\t\t\t.getName(), destinationType), e);\r\n\t\t}\r\n\t}" ]
Call the appropriate handler for handling the httprequest. 404 if path is not found. 405 if path is found but httpMethod does not match what's configured. @param request instance of {@code HttpRequest} @param responder instance of {@code HttpResponder} to handle the request.
[ "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 static List<Path> expandMultiAppInputDirs(List<Path> input)\n {\n List<Path> expanded = new LinkedList<>();\n for (Path path : input)\n {\n if (Files.isRegularFile(path))\n {\n expanded.add(path);\n continue;\n }\n if (!Files.isDirectory(path))\n {\n String pathString = (path == null) ? \"\" : path.toString(); \n log.warning(\"Neither a file or directory found in input: \" + pathString);\n continue;\n }\n\n try\n {\n try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path))\n {\n for (Path subpath : directoryStream)\n {\n\n if (isJavaArchive(subpath))\n {\n expanded.add(subpath);\n }\n }\n }\n }\n catch (IOException e)\n {\n throw new WindupException(\"Failed to read directory contents of: \" + path);\n }\n }\n return expanded;\n }", "private String getResourceField(int key)\n {\n String result = null;\n\n if (key > 0 && key < m_resourceNames.length)\n {\n result = m_resourceNames[key];\n }\n\n return (result);\n }", "public synchronized boolean tryDelegateResponseHandling(Response<ByteArray, Object> response) {\n if(responseHandlingCutoff) {\n return false;\n } else {\n responseQueue.offer(response);\n this.notifyAll();\n return true;\n }\n }", "private void setFileNotWorldReadablePermissions(File file) {\n file.setReadable(false, false);\n file.setWritable(false, false);\n file.setExecutable(false, false);\n file.setReadable(true, true);\n file.setWritable(true, true);\n }", "public void start() {\n nsLock.writeLock().lock();\n try {\n if (runnerThread != null) {\n return;\n }\n runnerThread =\n new Thread(new NamespaceChangeStreamRunner(\n new WeakReference<>(this), networkMonitor, logger));\n runnerThread.start();\n } finally {\n nsLock.writeLock().unlock();\n }\n }", "private void process(String input, String output) throws MPXJException, IOException\n {\n //\n // Extract the project data\n //\n MPPReader reader = new MPPReader();\n m_project = reader.read(input);\n\n String varDataFileName;\n String projectDirName;\n int mppFileType = NumberHelper.getInt(m_project.getProjectProperties().getMppFileType());\n switch (mppFileType)\n {\n case 8:\n {\n projectDirName = \" 1\";\n varDataFileName = \"FixDeferFix 0\";\n break;\n }\n\n case 9:\n {\n projectDirName = \" 19\";\n varDataFileName = \"Var2Data\";\n break;\n }\n\n case 12:\n {\n projectDirName = \" 112\";\n varDataFileName = \"Var2Data\";\n break;\n }\n\n case 14:\n {\n projectDirName = \" 114\";\n varDataFileName = \"Var2Data\";\n break;\n }\n\n default:\n {\n throw new IllegalArgumentException(\"Unsupported file type \" + mppFileType);\n }\n }\n\n //\n // Load the raw file\n //\n FileInputStream is = new FileInputStream(input);\n POIFSFileSystem fs = new POIFSFileSystem(is);\n is.close();\n\n //\n // Locate the root of the project file system\n //\n DirectoryEntry root = fs.getRoot();\n m_projectDir = (DirectoryEntry) root.getEntry(projectDirName);\n\n //\n // Process Tasks\n //\n Map<String, String> replacements = new HashMap<String, String>();\n for (Task task : m_project.getTasks())\n {\n mapText(task.getName(), replacements);\n }\n processReplacements(((DirectoryEntry) m_projectDir.getEntry(\"TBkndTask\")), varDataFileName, replacements, true);\n\n //\n // Process Resources\n //\n replacements.clear();\n for (Resource resource : m_project.getResources())\n {\n mapText(resource.getName(), replacements);\n mapText(resource.getInitials(), replacements);\n }\n processReplacements((DirectoryEntry) m_projectDir.getEntry(\"TBkndRsc\"), varDataFileName, replacements, true);\n\n //\n // Process project properties\n //\n replacements.clear();\n ProjectProperties properties = m_project.getProjectProperties();\n mapText(properties.getProjectTitle(), replacements);\n processReplacements(m_projectDir, \"Props\", replacements, true);\n\n replacements.clear();\n mapText(properties.getProjectTitle(), replacements);\n mapText(properties.getSubject(), replacements);\n mapText(properties.getAuthor(), replacements);\n mapText(properties.getKeywords(), replacements);\n mapText(properties.getComments(), replacements);\n processReplacements(root, \"\\005SummaryInformation\", replacements, false);\n\n replacements.clear();\n mapText(properties.getManager(), replacements);\n mapText(properties.getCompany(), replacements);\n mapText(properties.getCategory(), replacements);\n processReplacements(root, \"\\005DocumentSummaryInformation\", replacements, false);\n\n //\n // Write the replacement raw file\n //\n FileOutputStream os = new FileOutputStream(output);\n fs.writeFilesystem(os);\n os.flush();\n os.close();\n fs.close();\n }", "public BsonDocument toBsonDocument() {\n final BsonDocument updateDescDoc = new BsonDocument();\n updateDescDoc.put(\n Fields.UPDATED_FIELDS_FIELD,\n this.getUpdatedFields());\n\n final BsonArray removedFields = new BsonArray();\n for (final String field : this.getRemovedFields()) {\n removedFields.add(new BsonString(field));\n }\n updateDescDoc.put(\n Fields.REMOVED_FIELDS_FIELD,\n removedFields);\n\n return updateDescDoc;\n }", "private void addServer(CmsSiteMatcher matcher, CmsSite site) {\n\n Map<CmsSiteMatcher, CmsSite> siteMatcherSites = new HashMap<CmsSiteMatcher, CmsSite>(m_siteMatcherSites);\n siteMatcherSites.put(matcher, site);\n setSiteMatcherSites(siteMatcherSites);\n }", "private static void setFields(final Object from, final Object to,\r\n\t final Field[] fields, final boolean accessible,\r\n\t final Map objMap, final Map metadataMap)\r\n\t{\r\n\t\tfor (int f = 0, fieldsLength = fields.length; f < fieldsLength; ++f)\r\n\t\t{\r\n\t\t\tfinal Field field = fields[f];\r\n\t\t\tfinal int modifiers = field.getModifiers();\r\n\t\t\tif ((Modifier.STATIC & modifiers) != 0) continue;\r\n\t\t\tif ((Modifier.FINAL & modifiers) != 0)\r\n\t\t\t\tthrow new ObjectCopyException(\"cannot set final field [\" + field.getName() + \"] of class [\" + from.getClass().getName() + \"]\");\r\n\t\t\tif (!accessible && ((Modifier.PUBLIC & modifiers) == 0))\r\n\t\t\t{\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\tfield.setAccessible(true);\r\n\t\t\t\t}\r\n\t\t\t\tcatch (SecurityException e)\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow new ObjectCopyException(\"cannot access field [\" + field.getName() + \"] of class [\" + from.getClass().getName() + \"]: \" + e.toString(), e);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tcloneAndSetFieldValue(field, from, to, objMap, metadataMap);\r\n\t\t\t}\r\n\t\t\tcatch (Exception e)\r\n\t\t\t{\r\n\t\t\t\tthrow new ObjectCopyException(\"cannot set field [\" + field.getName() + \"] of class [\" + from.getClass().getName() + \"]: \" + e.toString(), e);\r\n\t\t\t}\r\n\t\t}\r\n\t}" ]
Creates a Bytes object by copying the value of the given String with a given charset
[ "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 }" ]
[ "public void add(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD);\r\n parameters.put(\"photo_id\", photoId);\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 }", "@NotThreadsafe\n private void initFileStreams(int chunkId) {\n /**\n * {@link Set#add(Object)} returns false if the element already existed in the set.\n * This ensures we initialize the resources for each chunk only once.\n */\n if (chunksHandled.add(chunkId)) {\n try {\n this.indexFileSizeInBytes[chunkId] = 0L;\n this.valueFileSizeInBytes[chunkId] = 0L;\n this.checkSumDigestIndex[chunkId] = CheckSum.getInstance(checkSumType);\n this.checkSumDigestValue[chunkId] = CheckSum.getInstance(checkSumType);\n this.position[chunkId] = 0;\n this.taskIndexFileName[chunkId] = new Path(FileOutputFormat.getOutputPath(conf),\n getStoreName() + \".\"\n + Integer.toString(chunkId) + \"_\"\n + this.taskId + INDEX_FILE_EXTENSION\n + fileExtension);\n this.taskValueFileName[chunkId] = new Path(FileOutputFormat.getOutputPath(conf),\n getStoreName() + \".\"\n + Integer.toString(chunkId) + \"_\"\n + this.taskId + DATA_FILE_EXTENSION\n + fileExtension);\n if(this.fs == null)\n this.fs = this.taskIndexFileName[chunkId].getFileSystem(conf);\n if(isValidCompressionEnabled) {\n this.indexFileStream[chunkId] = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(fs.create(this.taskIndexFileName[chunkId]),\n DEFAULT_BUFFER_SIZE)));\n this.valueFileStream[chunkId] = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(fs.create(this.taskValueFileName[chunkId]),\n DEFAULT_BUFFER_SIZE)));\n\n } else {\n this.indexFileStream[chunkId] = fs.create(this.taskIndexFileName[chunkId]);\n this.valueFileStream[chunkId] = fs.create(this.taskValueFileName[chunkId]);\n\n }\n fs.setPermission(this.taskIndexFileName[chunkId],\n new FsPermission(HadoopStoreBuilder.HADOOP_FILE_PERMISSION));\n logger.info(\"Setting permission to 755 for \" + this.taskIndexFileName[chunkId]);\n fs.setPermission(this.taskValueFileName[chunkId],\n new FsPermission(HadoopStoreBuilder.HADOOP_FILE_PERMISSION));\n logger.info(\"Setting permission to 755 for \" + this.taskValueFileName[chunkId]);\n\n logger.info(\"Opening \" + this.taskIndexFileName[chunkId] + \" and \"\n + this.taskValueFileName[chunkId] + \" for writing.\");\n } catch(IOException e) {\n throw new RuntimeException(\"Failed to open Input/OutputStream\", e);\n }\n }\n }", "Document convertSelectorToDocument(Document selector) {\n Document document = new Document();\n for (String key : selector.keySet()) {\n if (key.startsWith(\"$\")) {\n continue;\n }\n\n Object value = selector.get(key);\n if (!Utils.containsQueryExpression(value)) {\n Utils.changeSubdocumentValue(document, key, value, (AtomicReference<Integer>) null);\n }\n }\n return document;\n }", "public void copyTo(int srcOffset, byte[] destArray, int destOffset, int size) {\n int cursor = destOffset;\n for (ByteBuffer bb : toDirectByteBuffers(srcOffset, size)) {\n int bbSize = bb.remaining();\n if ((cursor + bbSize) > destArray.length)\n throw new ArrayIndexOutOfBoundsException(String.format(\"cursor + bbSize = %,d\", cursor + bbSize));\n bb.get(destArray, cursor, bbSize);\n cursor += bbSize;\n }\n }", "private void setProperties(Properties properties) {\n Props props = new Props(properties);\n if(props.containsKey(ClientConfig.ENABLE_JMX_PROPERTY)) {\n this.setEnableJmx(props.getBoolean(ClientConfig.ENABLE_JMX_PROPERTY));\n }\n\n if(props.containsKey(ClientConfig.BOOTSTRAP_URLS_PROPERTY)) {\n List<String> urls = props.getList(ClientConfig.BOOTSTRAP_URLS_PROPERTY);\n if(urls.size() > 0) {\n setHttpBootstrapURL(urls.get(0));\n }\n }\n\n if(props.containsKey(ClientConfig.MAX_TOTAL_CONNECTIONS_PROPERTY)) {\n setMaxR2ConnectionPoolSize(props.getInt(ClientConfig.MAX_TOTAL_CONNECTIONS_PROPERTY,\n maxR2ConnectionPoolSize));\n }\n\n if(props.containsKey(ClientConfig.ROUTING_TIMEOUT_MS_PROPERTY))\n this.setTimeoutMs(props.getLong(ClientConfig.ROUTING_TIMEOUT_MS_PROPERTY, timeoutMs),\n TimeUnit.MILLISECONDS);\n\n // By default, make all the timeouts equal to routing timeout\n timeoutConfig = new TimeoutConfig(timeoutMs, false);\n\n if(props.containsKey(ClientConfig.GETALL_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_ALL_OP_CODE,\n props.getInt(ClientConfig.GETALL_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.GET_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_OP_CODE,\n props.getInt(ClientConfig.GET_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.PUT_ROUTING_TIMEOUT_MS_PROPERTY)) {\n long putTimeoutMs = props.getInt(ClientConfig.PUT_ROUTING_TIMEOUT_MS_PROPERTY);\n timeoutConfig.setOperationTimeout(VoldemortOpCode.PUT_OP_CODE, putTimeoutMs);\n // By default, use the same thing for getVersions() also\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE, putTimeoutMs);\n }\n\n // of course, if someone overrides it, we will respect that\n if(props.containsKey(ClientConfig.GET_VERSIONS_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE,\n props.getInt(ClientConfig.GET_VERSIONS_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.DELETE_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.DELETE_OP_CODE,\n props.getInt(ClientConfig.DELETE_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.ALLOW_PARTIAL_GETALLS_PROPERTY))\n timeoutConfig.setPartialGetAllAllowed(props.getBoolean(ClientConfig.ALLOW_PARTIAL_GETALLS_PROPERTY));\n\n }", "@SuppressWarnings(\"unchecked\") private Object formatType(DataType type, Object value)\n {\n switch (type)\n {\n case DATE:\n {\n value = formatDateTime(value);\n break;\n }\n\n case CURRENCY:\n {\n value = formatCurrency((Number) value);\n break;\n }\n\n case UNITS:\n {\n value = formatUnits((Number) value);\n break;\n }\n\n case PERCENTAGE:\n {\n value = formatPercentage((Number) value);\n break;\n }\n\n case ACCRUE:\n {\n value = formatAccrueType((AccrueType) value);\n break;\n }\n\n case CONSTRAINT:\n {\n value = formatConstraintType((ConstraintType) value);\n break;\n }\n\n case WORK:\n case DURATION:\n {\n value = formatDuration(value);\n break;\n }\n\n case RATE:\n {\n value = formatRate((Rate) value);\n break;\n }\n\n case PRIORITY:\n {\n value = formatPriority((Priority) value);\n break;\n }\n\n case RELATION_LIST:\n {\n value = formatRelationList((List<Relation>) value);\n break;\n }\n\n case TASK_TYPE:\n {\n value = formatTaskType((TaskType) value);\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return (value);\n }", "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 }", "protected TextBox createTextBox(BlockBox contblock, Text n)\n {\n TextBox text = new TextBox(n, (Graphics2D) contblock.getGraphics().create(), contblock.getVisualContext().create());\n text.setOrder(next_order++);\n text.setContainingBlockBox(contblock);\n text.setClipBlock(contblock);\n text.setViewport(viewport);\n text.setBase(baseurl);\n return text;\n }", "public static URI setQueryParams(final URI initialUri, final Multimap<String, String> queryParams) {\n StringBuilder queryString = new StringBuilder();\n for (Map.Entry<String, String> entry: queryParams.entries()) {\n if (queryString.length() > 0) {\n queryString.append(\"&\");\n }\n queryString.append(entry.getKey()).append(\"=\").append(entry.getValue());\n }\n try {\n if (initialUri.getHost() == null && initialUri.getAuthority() != null) {\n return new URI(initialUri.getScheme(), initialUri.getAuthority(), initialUri.getPath(),\n queryString.toString(),\n initialUri.getFragment());\n } else {\n return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),\n initialUri.getPort(),\n initialUri.getPath(),\n queryString.toString(), initialUri.getFragment());\n }\n } catch (URISyntaxException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }" ]
Split a module Id to get the module name @param moduleId @return String
[ "public static String getModuleName(final String moduleId) {\n final int splitter = moduleId.indexOf(':');\n if(splitter == -1){\n return moduleId;\n }\n return moduleId.substring(0, splitter);\n }" ]
[ "public float conditionalLogProb(int[] given, int of) {\r\n if (given.length != windowSize - 1) {\r\n System.err.println(\"error computing conditional log prob\");\r\n System.exit(0);\r\n }\r\n int[] label = indicesFront(given);\r\n float[] masses = new float[label.length];\r\n for (int i = 0; i < masses.length; i++) {\r\n masses[i] = table[label[i]];\r\n }\r\n float z = ArrayMath.logSum(masses);\r\n\r\n return table[indexOf(given, of)] - z;\r\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 }", "@Override\n\tprotected void clearReference(EObject obj, EReference ref) {\n\t\tsuper.clearReference(obj, ref);\n\t\tif (obj.eIsSet(ref) && ref.getEType().equals(XtextPackage.Literals.TYPE_REF)) {\n\t\t\tINode node = NodeModelUtils.getNode((EObject) obj.eGet(ref));\n\t\t\tif (node == null)\n\t\t\t\tobj.eUnset(ref);\n\t\t}\n\t\tif (obj.eIsSet(ref) && ref == XtextPackage.Literals.CROSS_REFERENCE__TERMINAL) {\n\t\t\tINode node = NodeModelUtils.getNode((EObject) obj.eGet(ref));\n\t\t\tif (node == null)\n\t\t\t\tobj.eUnset(ref);\n\t\t}\n\t\tif (ref == XtextPackage.Literals.RULE_CALL__RULE) {\n\t\t\tobj.eUnset(XtextPackage.Literals.RULE_CALL__EXPLICITLY_CALLED);\n\t\t}\n\t}", "public void removeNodeMetaData(Object key) {\n if (key==null) throw new GroovyBugError(\"Tried to remove meta data with null key \"+this+\".\");\n if (metaDataMap == null) {\n return;\n }\n metaDataMap.remove(key);\n }", "private void readWeekDay(ProjectCalendar mpxjCalendar, WeekDay day)\n {\n if (day.isIsDayWorking())\n {\n ProjectCalendarHours hours = mpxjCalendar.addCalendarHours(day.getDay());\n for (Document.Calendars.Calendar.WeekDays.WeekDay.TimePeriods.TimePeriod period : day.getTimePeriods().getTimePeriod())\n {\n hours.addRange(new DateRange(period.getFrom(), period.getTo()));\n }\n }\n }", "private BigInteger getDaysOfTheWeek(RecurringData data)\n {\n int value = 0;\n for (Day day : Day.values())\n {\n if (data.getWeeklyDay(day))\n {\n value = value | DAY_MASKS[day.getValue()];\n }\n }\n return BigInteger.valueOf(value);\n }", "public static void load(File file)\n {\n try(FileInputStream inputStream = new FileInputStream(file))\n {\n LineIterator it = IOUtils.lineIterator(inputStream, \"UTF-8\");\n while (it.hasNext())\n {\n String line = it.next();\n if (!line.startsWith(\"#\") && !line.trim().isEmpty())\n {\n add(line);\n }\n }\n }\n catch (Exception e)\n {\n throw new WindupException(\"Failed loading archive ignore patterns from [\" + file.toString() + \"]\", e);\n }\n }", "public static PersistenceStrategy<?, ?, ?> getInstance(\n\t\t\tCacheMappingType cacheMapping,\n\t\t\tEmbeddedCacheManager externalCacheManager,\n\t\t\tURL configurationUrl,\n\t\t\tJtaPlatform jtaPlatform,\n\t\t\tSet<EntityKeyMetadata> entityTypes,\n\t\t\tSet<AssociationKeyMetadata> associationTypes,\n\t\t\tSet<IdSourceKeyMetadata> idSourceTypes ) {\n\n\t\tif ( cacheMapping == CacheMappingType.CACHE_PER_KIND ) {\n\t\t\treturn getPerKindStrategy(\n\t\t\t\t\texternalCacheManager,\n\t\t\t\t\tconfigurationUrl,\n\t\t\t\t\tjtaPlatform\n\t\t\t);\n\t\t}\n\t\telse {\n\t\t\treturn getPerTableStrategy(\n\t\t\t\t\texternalCacheManager,\n\t\t\t\t\tconfigurationUrl,\n\t\t\t\t\tjtaPlatform,\n\t\t\t\t\tentityTypes,\n\t\t\t\t\tassociationTypes,\n\t\t\t\t\tidSourceTypes\n\t\t\t);\n\t\t}\n\t}", "protected void ensureDJStyles() {\n //first of all, register all parent styles if any\n for (Style style : getReport().getStyles().values()) {\n addStyleToDesign(style);\n }\n\n Style defaultDetailStyle = getReport().getOptions().getDefaultDetailStyle();\n\n Style defaultHeaderStyle = getReport().getOptions().getDefaultHeaderStyle();\n for (AbstractColumn column : report.getColumns()) {\n if (column.getStyle() == null)\n column.setStyle(defaultDetailStyle);\n if (column.getHeaderStyle() == null)\n column.setHeaderStyle(defaultHeaderStyle);\n }\n }" ]
Returns the y-coordinate of a vertex tangent. @param vertex the vertex index @return the y coordinate
[ "public float getBitangentY(int vertex) {\n if (!hasTangentsAndBitangents()) {\n throw new IllegalStateException(\"mesh has no bitangents\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_bitangents.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\n }" ]
[ "public static int getNavigationBarHeight(Context context) {\n Resources resources = context.getResources();\n int id = resources.getIdentifier(context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ? \"navigation_bar_height\" : \"navigation_bar_height_landscape\", \"dimen\", \"android\");\n if (id > 0) {\n return resources.getDimensionPixelSize(id);\n }\n return 0;\n }", "private boolean initRequestHandler(SelectionKey selectionKey) {\n ByteBuffer inputBuffer = inputStream.getBuffer();\n int remaining = inputBuffer.remaining();\n\n // Don't have enough bytes to determine the protocol yet...\n if(remaining < 3)\n return true;\n\n byte[] protoBytes = { inputBuffer.get(0), inputBuffer.get(1), inputBuffer.get(2) };\n\n try {\n String proto = ByteUtils.getString(protoBytes, \"UTF-8\");\n inputBuffer.clear();\n RequestFormatType requestFormatType = RequestFormatType.fromCode(proto);\n requestHandler = requestHandlerFactory.getRequestHandler(requestFormatType);\n\n if(logger.isInfoEnabled())\n logger.info(\"Protocol negotiated for \" + socketChannel.socket() + \": \"\n + requestFormatType.getDisplayName());\n\n // The protocol negotiation is the first request, so respond by\n // sticking the bytes in the output buffer, signaling the Selector,\n // and returning false to denote no further processing is needed.\n outputStream.getBuffer().put(ByteUtils.getBytes(\"ok\", \"UTF-8\"));\n prepForWrite(selectionKey);\n\n return false;\n } catch(IllegalArgumentException e) {\n // okay we got some nonsense. For backwards compatibility,\n // assume this is an old client who does not know how to negotiate\n RequestFormatType requestFormatType = RequestFormatType.VOLDEMORT_V0;\n requestHandler = requestHandlerFactory.getRequestHandler(requestFormatType);\n\n if(logger.isInfoEnabled())\n logger.info(\"No protocol proposal given for \" + socketChannel.socket()\n + \", assuming \" + requestFormatType.getDisplayName());\n\n return true;\n }\n }", "public static base_response update(nitro_service client, clusterinstance resource) throws Exception {\n\t\tclusterinstance updateresource = new clusterinstance();\n\t\tupdateresource.clid = resource.clid;\n\t\tupdateresource.deadinterval = resource.deadinterval;\n\t\tupdateresource.hellointerval = resource.hellointerval;\n\t\tupdateresource.preemption = resource.preemption;\n\t\treturn updateresource.update_resource(client);\n\t}", "public final void visitChildren(final Visitor visitor)\n\t{\n\t\tfor (final DiffNode child : children.values())\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tchild.visit(visitor);\n\t\t\t}\n\t\t\tcatch (final StopVisitationException e)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}", "private static String toColumnName(String fieldName) {\n int lastDot = fieldName.indexOf('.');\n if (lastDot > -1) {\n return fieldName.substring(lastDot + 1);\n } else {\n return fieldName;\n }\n }", "public static cachepolicylabel[] get(nitro_service service) throws Exception{\n\t\tcachepolicylabel obj = new cachepolicylabel();\n\t\tcachepolicylabel[] response = (cachepolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private void writeAssignments() throws IOException\n {\n writeAttributeTypes(\"assignment_types\", AssignmentField.values());\n\n m_writer.writeStartList(\"assignments\");\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n writeFields(null, assignment, AssignmentField.values());\n }\n m_writer.writeEndList();\n\n }", "public static final BigDecimal printUnits(Number value)\n {\n return (value == null ? BIGDECIMAL_ONE : new BigDecimal(value.doubleValue() / 100));\n }", "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}" ]
convolution data type
[ "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 ClassicCounter<K2> setCounter(K1 o, Counter<K2> c) {\r\n ClassicCounter<K2> old = getCounter(o);\r\n total -= old.totalCount();\r\n if (c instanceof ClassicCounter) {\r\n map.put(o, (ClassicCounter<K2>) c);\r\n } else {\r\n map.put(o, new ClassicCounter<K2>(c));\r\n }\r\n total += c.totalCount();\r\n return old;\r\n }", "@Override\n public <X> X getScreenshotAs(OutputType<X> target) {\n // Get the screenshot as base64 and convert it to the requested type (i.e. OutputType<T>)\n String base64 = (String) execute(DriverCommand.SCREENSHOT).getValue();\n return target.convertFromBase64Png(base64);\n }", "private void ensureConversion(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n // we issue a warning if we encounter a field with a java.util.Date java type without a conversion\r\n if (\"java.util.Date\".equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JAVA_TYPE)) &&\r\n !fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_CONVERSION))\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureConversion\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\r\n \" of type java.util.Date is directly mapped to jdbc-type \"+\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE)+\r\n \". However, most JDBC drivers can't handle java.util.Date directly so you might want to \"+\r\n \" use a conversion for converting it to a JDBC datatype like TIMESTAMP.\");\r\n }\r\n\r\n String conversionClass = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_CONVERSION);\r\n\r\n if (((conversionClass == null) || (conversionClass.length() == 0)) &&\r\n fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION) &&\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_JDBC_TYPE).equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE)))\r\n {\r\n conversionClass = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_CONVERSION, conversionClass);\r\n }\r\n // now checking\r\n if (CHECKLEVEL_STRICT.equals(checkLevel) && (conversionClass != null) && (conversionClass.length() > 0))\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n try\r\n {\r\n if (!helper.isSameOrSubTypeOf(conversionClass, CONVERSION_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The conversion class specified for field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" does not implement the necessary interface \"+CONVERSION_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"The class \"+ex.getMessage()+\" hasn't been found on the classpath while checking the conversion class specified for field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName());\r\n }\r\n }\r\n}", "public String getDbProperty(String key) {\n\n // extract the database key out of the entire key\n String databaseKey = key.substring(0, key.indexOf('.'));\n Properties databaseProperties = getDatabaseProperties().get(databaseKey);\n\n return databaseProperties.getProperty(key, \"\");\n }", "public ArrayList<IntPoint> process(ImageSource fastBitmap) {\r\n //FastBitmap l = new FastBitmap(fastBitmap);\r\n if (points == null) {\r\n apply(fastBitmap);\r\n }\r\n\r\n int width = fastBitmap.getWidth();\r\n int height = fastBitmap.getHeight();\r\n points = new ArrayList<IntPoint>();\r\n\r\n if (fastBitmap.isGrayscale()) {\r\n for (int x = 0; x < height; x++) {\r\n for (int y = 0; y < width; y++) {\r\n if (fastBitmap.getRGB(y, x) == 255) points.add(new IntPoint(y, x));\r\n }\r\n }\r\n } else {\r\n for (int x = 0; x < height; x++) {\r\n for (int y = 0; y < width; y++) {\r\n // TODO Check for green and blue?\r\n if (fastBitmap.getR(y, x) == 255) points.add(new IntPoint(y, x));\r\n }\r\n }\r\n }\r\n\r\n return points;\r\n }", "@Override\n public String getPartialFilterSelector() {\n return (def.selector != null) ? def.selector.toString() : null;\n }", "private void processSubProjects()\n {\n int subprojectIndex = 1;\n for (Task task : m_project.getTasks())\n {\n String subProjectFileName = task.getSubprojectName();\n if (subProjectFileName != null)\n {\n String fileName = subProjectFileName;\n int offset = 0x01000000 + (subprojectIndex * 0x00400000);\n int index = subProjectFileName.lastIndexOf('\\\\');\n if (index != -1)\n {\n fileName = subProjectFileName.substring(index + 1);\n }\n\n SubProject sp = new SubProject();\n sp.setFileName(fileName);\n sp.setFullPath(subProjectFileName);\n sp.setUniqueIDOffset(Integer.valueOf(offset));\n sp.setTaskUniqueID(task.getUniqueID());\n task.setSubProject(sp);\n\n ++subprojectIndex;\n }\n }\n }", "public boolean accept(String str) {\r\n int k = str.length() - 1;\r\n char c = str.charAt(k);\r\n while (k >= 0 && !Character.isDigit(c)) {\r\n k--;\r\n if (k >= 0) {\r\n c = str.charAt(k);\r\n }\r\n }\r\n if (k < 0) {\r\n return false;\r\n }\r\n int j = k;\r\n c = str.charAt(j);\r\n while (j >= 0 && Character.isDigit(c)) {\r\n j--;\r\n if (j >= 0) {\r\n c = str.charAt(j);\r\n }\r\n }\r\n j++;\r\n k++;\r\n String theNumber = str.substring(j, k);\r\n int number = Integer.parseInt(theNumber);\r\n for (Pair<Integer,Integer> p : ranges) {\r\n int low = p.first().intValue();\r\n int high = p.second().intValue();\r\n if (number >= low && number <= high) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "public static dnsnsecrec get(nitro_service service, String hostname) throws Exception{\n\t\tdnsnsecrec obj = new dnsnsecrec();\n\t\tobj.set_hostname(hostname);\n\t\tdnsnsecrec response = (dnsnsecrec) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Creates a setter method with the given body. @param declaringClass the class to which we will add the setter @param propertyNode the field to back the setter @param setterName the name of the setter @param setterBlock the statement representing the setter block
[ "protected void createSetterMethod(ClassNode declaringClass, PropertyNode propertyNode, String setterName, Statement setterBlock) {\r\n MethodNode setter = new MethodNode(\r\n setterName,\r\n propertyNode.getModifiers(),\r\n ClassHelper.VOID_TYPE,\r\n params(param(propertyNode.getType(), \"value\")),\r\n ClassNode.EMPTY_ARRAY,\r\n setterBlock);\r\n setter.setSynthetic(true);\r\n // add it to the class\r\n declaringClass.addMethod(setter);\r\n }" ]
[ "private static Set<ProjectModel> getAllApplications(GraphContext graphContext)\n {\n Set<ProjectModel> apps = new HashSet<>();\n Iterable<ProjectModel> appProjects = graphContext.findAll(ProjectModel.class);\n for (ProjectModel appProject : appProjects)\n apps.add(appProject);\n return apps;\n }", "public boolean hasUser(String userId) {\r\n String normalized = normalizerUserName(userId);\r\n return loginToUser.containsKey(normalized) || emailToUser.containsKey(normalized);\r\n }", "public void growMaxColumns( int desiredColumns , boolean preserveValue ) {\n if( col_idx.length < desiredColumns+1 ) {\n int[] c = new int[ desiredColumns+1 ];\n if( preserveValue )\n System.arraycopy(col_idx,0,c,0,col_idx.length);\n col_idx = c;\n }\n }", "public double nextDouble(double lo, double hi) {\n if (lo < 0) {\n if (nextInt(2) == 0)\n return -nextDouble(0, -lo);\n else\n return nextDouble(0, hi);\n } else {\n return (lo + (hi - lo) * nextDouble());\n }\n }", "protected ServiceName serviceName(final String name) {\n return baseServiceName != null ? baseServiceName.append(name) : null;\n }", "protected void addNeighbor(Queue<ColorPoint> queue, int px, int py, int color, Feature component) {\n if (!inBoundary(px, py, component)) {\n return;\n }\n\n if (!mask.isTouched(px, py)) {\n queue.add(new ColorPoint(px, py, color));\n }\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 }", "private void performSetupExchange() throws IOException {\n Message setupRequest = new Message(0xfffffffeL, Message.KnownType.SETUP_REQ, new NumberField(posingAsPlayer, 4));\n sendMessage(setupRequest);\n Message response = Message.read(is);\n if (response.knownType != Message.KnownType.MENU_AVAILABLE) {\n throw new IOException(\"Did not receive message type 0x4000 in response to setup message, got: \" + response);\n }\n if (response.arguments.size() != 2) {\n throw new IOException(\"Did not receive two arguments in response to setup message, got: \" + response);\n }\n final Field player = response.arguments.get(1);\n if (!(player instanceof NumberField)) {\n throw new IOException(\"Second argument in response to setup message was not a number: \" + response);\n }\n if (((NumberField)player).getValue() != targetPlayer) {\n throw new IOException(\"Expected to connect to player \" + targetPlayer +\n \", but welcome response identified itself as player \" + ((NumberField)player).getValue());\n }\n }", "@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 }" ]
Validates for non-conflicting roles
[ "protected void checkConflictingRoles() {\n if (getType().isAnnotationPresent(Interceptor.class)) {\n throw BeanLogger.LOG.ejbCannotBeInterceptor(getType());\n }\n if (getType().isAnnotationPresent(Decorator.class)) {\n throw BeanLogger.LOG.ejbCannotBeDecorator(getType());\n }\n }" ]
[ "protected void merge(Set<Annotation> stereotypeAnnotations) {\n final MetaAnnotationStore store = manager.getServices().get(MetaAnnotationStore.class);\n for (Annotation stereotypeAnnotation : stereotypeAnnotations) {\n // Retrieve and merge all metadata from stereotypes\n StereotypeModel<?> stereotype = store.getStereotype(stereotypeAnnotation.annotationType());\n if (stereotype == null) {\n throw MetadataLogger.LOG.stereotypeNotRegistered(stereotypeAnnotation);\n }\n if (stereotype.isAlternative()) {\n alternative = true;\n }\n if (stereotype.getDefaultScopeType() != null) {\n possibleScopeTypes.add(stereotype.getDefaultScopeType());\n }\n if (stereotype.isBeanNameDefaulted()) {\n beanNameDefaulted = true;\n }\n this.stereotypes.add(stereotypeAnnotation.annotationType());\n // Merge in inherited stereotypes\n merge(stereotype.getInheritedStereotypes());\n }\n }", "public static Class<?> getRawType(Type type) {\n\t\tif (type instanceof Class) {\n\t\t\treturn (Class<?>) type;\n\t\t} else if (type instanceof ParameterizedType) {\n\t\t\tParameterizedType actualType = (ParameterizedType) type;\n\t\t\treturn getRawType(actualType.getRawType());\n\t\t} else if (type instanceof GenericArrayType) {\n\t\t\tGenericArrayType genericArrayType = (GenericArrayType) type;\n\t\t\tObject rawArrayType = Array.newInstance(getRawType(genericArrayType\n\t\t\t\t\t.getGenericComponentType()), 0);\n\t\t\treturn rawArrayType.getClass();\n\t\t} else if (type instanceof WildcardType) {\n\t\t\tWildcardType castedType = (WildcardType) type;\n\t\t\treturn getRawType(castedType.getUpperBounds()[0]);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Type \\'\"\n\t\t\t\t\t\t\t+ type\n\t\t\t\t\t\t\t+ \"\\' is not a Class, \"\n\t\t\t\t\t\t\t+ \"ParameterizedType, or GenericArrayType. Can't extract class.\");\n\t\t}\n\t}", "@SuppressWarnings(\"unchecked\")\n private static synchronized Map<String, Boolean> getCache(GraphRewrite event)\n {\n Map<String, Boolean> result = (Map<String, Boolean>)event.getRewriteContext().get(ClassificationServiceCache.class);\n if (result == null)\n {\n result = Collections.synchronizedMap(new LRUMap(30000));\n event.getRewriteContext().put(ClassificationServiceCache.class, result);\n }\n return result;\n }", "private ClassNode getGenericsResolvedTypeOfFieldOrProperty(AnnotatedNode an, ClassNode type) {\n if (!type.isUsingGenerics()) return type;\n Map<String, GenericsType> connections = new HashMap();\n //TODO: inner classes mean a different this-type. This is ignored here!\n extractGenericsConnections(connections, typeCheckingContext.getEnclosingClassNode(), an.getDeclaringClass());\n type= applyGenericsContext(connections, type);\n return type;\n }", "public static Node removePartitionFromNode(final Node node, Integer donatedPartition) {\n return UpdateClusterUtils.removePartitionsFromNode(node, Sets.newHashSet(donatedPartition));\n }", "public static Command newSetGlobal(String identifier,\n Object object) {\n return getCommandFactoryProvider().newSetGlobal( identifier,\n object );\n }", "public static boolean setCustomRequestForDefaultProfile(String pathName, String customData) {\n try {\n return setCustomForDefaultProfile(pathName, false, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "public static String[] copyArrayAddFirst(String[] arr, String add) {\n String[] arrCopy = new String[arr.length + 1];\n arrCopy[0] = add;\n System.arraycopy(arr, 0, arrCopy, 1, arr.length);\n return arrCopy;\n }", "public BoxFile.Info restoreFile(String fileID, String newName, String newParentID) {\n JsonObject requestJSON = new JsonObject();\n\n if (newName != null) {\n requestJSON.add(\"name\", newName);\n }\n\n if (newParentID != null) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", newParentID);\n requestJSON.add(\"parent\", parent);\n }\n\n URL url = RESTORE_FILE_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxJSONRequest request = new BoxJSONRequest(this.api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFile restoredFile = new BoxFile(this.api, responseJSON.get(\"id\").asString());\n return restoredFile.new Info(responseJSON);\n }" ]
Determines the address for the host being used. @param client the client used to communicate with the server @return the address of the host @throws IOException if an error occurs communicating with the server @throws OperationExecutionException if the operation used to determine the host name fails
[ "public static ModelNode determineHostAddress(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadAttributeOperation(EMPTY_ADDRESS, \"local-host-name\");\n ModelNode response = client.execute(op);\n if (Operations.isSuccessfulOutcome(response)) {\n return DeploymentOperations.createAddress(\"host\", Operations.readResult(response).asString());\n }\n throw new OperationExecutionException(op, response);\n }" ]
[ "private void setBelief(String bName, Object value) {\n introspector.setBeliefValue(this.getLocalName(), bName, value, null);\n }", "public Set<Method> findAnnotatedMethods(String scanBase, Class<? extends Annotation> annotationClass) {\n Set<BeanDefinition> filteredComponents = findCandidateBeans(scanBase, annotationClass);\n return extractAnnotatedMethods(filteredComponents, annotationClass);\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 }", "protected AssemblyResponse watchStatus() throws LocalOperationException, RequestException {\n AssemblyResponse response;\n do {\n response = getClient().getAssemblyByUrl(url);\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n throw new LocalOperationException(e);\n }\n } while (!response.isFinished());\n\n setState(State.FINISHED);\n return response;\n }", "public RasterLayerInfo asLayerInfo(TileMap tileMap) {\n\t\tRasterLayerInfo layerInfo = new RasterLayerInfo();\n\n\t\tlayerInfo.setCrs(tileMap.getSrs());\n\t\tlayerInfo.setDataSourceName(tileMap.getTitle());\n\t\tlayerInfo.setLayerType(LayerType.RASTER);\n\t\tlayerInfo.setMaxExtent(asBbox(tileMap.getBoundingBox()));\n\t\tlayerInfo.setTileHeight(tileMap.getTileFormat().getHeight());\n\t\tlayerInfo.setTileWidth(tileMap.getTileFormat().getWidth());\n\n\t\tList<ScaleInfo> zoomLevels = new ArrayList<ScaleInfo>(tileMap.getTileSets().getTileSets().size());\n\t\tfor (TileSet tileSet : tileMap.getTileSets().getTileSets()) {\n\t\t\tzoomLevels.add(asScaleInfo(tileSet));\n\t\t}\n\t\tlayerInfo.setZoomLevels(zoomLevels);\n\n\t\treturn layerInfo;\n\t}", "public static final String printTaskType(TaskType value)\n {\n return (Integer.toString(value == null ? TaskType.FIXED_UNITS.getValue() : value.getValue()));\n }", "public DomainList getCollectionDomains(Date date, String collectionId, int perPage, int page) throws FlickrException {\n return getDomains(METHOD_GET_COLLECTION_DOMAINS, \"collection_id\", collectionId, date, perPage, page);\n }", "public static final void deleteQuietly(File file)\n {\n if (file != null)\n {\n if (file.isDirectory())\n {\n File[] children = file.listFiles();\n if (children != null)\n {\n for (File child : children)\n {\n deleteQuietly(child);\n }\n }\n }\n file.delete();\n }\n }", "public static boolean isPackageOrClassName(String s) {\n if (S.blank(s)) {\n return false;\n }\n S.List parts = S.fastSplit(s, \".\");\n if (parts.size() < 2) {\n return false;\n }\n for (String part: parts) {\n if (!Character.isJavaIdentifierStart(part.charAt(0))) {\n return false;\n }\n for (int i = 1, len = part.length(); i < len; ++i) {\n if (!Character.isJavaIdentifierPart(part.charAt(i))) {\n return false;\n }\n }\n }\n return true;\n }" ]
Compute pose of skeleton at the given time from the animation channels. @param timeInSec animation time in seconds.
[ "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 String makeAsciiTable(Object[][] table, Object[] rowLabels, Object[] colLabels, int padLeft, int padRight, boolean tsv) {\r\n StringBuilder buff = new StringBuilder();\r\n // top row\r\n buff.append(makeAsciiTableCell(\"\", padLeft, padRight, tsv)); // 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(makeAsciiTableCell(colLabels[j], padLeft, padRight, (j != table[0].length - 1) && tsv));\r\n }\r\n buff.append('\\n');\r\n // all other rows\r\n for (int i = 0; i < table.length; i++) {\r\n // one row\r\n buff.append(makeAsciiTableCell(rowLabels[i], padLeft, padRight, tsv));\r\n for (int j = 0; j < table[i].length; j++) {\r\n buff.append(makeAsciiTableCell(table[i][j], padLeft, padRight, (j != table[0].length - 1) && tsv));\r\n }\r\n buff.append('\\n');\r\n }\r\n return buff.toString();\r\n }", "@Override\n public <K, V> StoreClient<K, V> getStoreClient(final String storeName,\n final InconsistencyResolver<Versioned<V>> resolver) {\n // wrap it in LazyStoreClient here so any direct calls to this method\n // returns a lazy client\n return new LazyStoreClient<K, V>(new Callable<StoreClient<K, V>>() {\n\n @Override\n public StoreClient<K, V> call() throws Exception {\n Store<K, V, Object> clientStore = getRawStore(storeName, resolver);\n return new RESTClient<K, V>(storeName, clientStore);\n }\n }, true);\n }", "public final void end() {\n final Thread thread = threadRef;\n if (thread != null) {\n thread.interrupt();\n try {\n thread.join();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n this.threadRef = null;\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 }", "void apply() {\n final FlushLog log = new FlushLog();\n store.logOperations(txn, log);\n final BlobVault blobVault = store.getBlobVault();\n if (blobVault.requiresTxn()) {\n try {\n blobVault.flushBlobs(blobStreams, blobFiles, deferredBlobsToDelete, txn);\n } catch (Exception e) {\n // out of disk space not expected there\n throw ExodusException.toEntityStoreException(e);\n }\n }\n txn.setCommitHook(new Runnable() {\n @Override\n public void run() {\n log.flushed();\n final EntityIterableCacheAdapterMutable cache = PersistentStoreTransaction.this.mutableCache;\n if (cache != null) { // mutableCache can be null if only blobs are modified\n applyAtomicCaches(cache);\n }\n }\n });\n }", "private void visitImplicitFirstFrame() {\n // There can be at most descriptor.length() + 1 locals\n int frameIndex = startFrame(0, descriptor.length() + 1, 0);\n if ((access & Opcodes.ACC_STATIC) == 0) {\n if ((access & ACC_CONSTRUCTOR) == 0) {\n frame[frameIndex++] = Frame.OBJECT | cw.addType(cw.thisName);\n } else {\n frame[frameIndex++] = Frame.UNINITIALIZED_THIS;\n }\n }\n int i = 1;\n loop: while (true) {\n int j = i;\n switch (descriptor.charAt(i++)) {\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n frame[frameIndex++] = Frame.INTEGER;\n break;\n case 'F':\n frame[frameIndex++] = Frame.FLOAT;\n break;\n case 'J':\n frame[frameIndex++] = Frame.LONG;\n break;\n case 'D':\n frame[frameIndex++] = Frame.DOUBLE;\n break;\n case '[':\n while (descriptor.charAt(i) == '[') {\n ++i;\n }\n if (descriptor.charAt(i) == 'L') {\n ++i;\n while (descriptor.charAt(i) != ';') {\n ++i;\n }\n }\n frame[frameIndex++] = Frame.type(cw, descriptor.substring(j, ++i));\n break;\n case 'L':\n while (descriptor.charAt(i) != ';') {\n ++i;\n }\n frame[frameIndex++] = Frame.OBJECT\n | cw.addType(descriptor.substring(j + 1, i++));\n break;\n default:\n break loop;\n }\n }\n frame[1] = frameIndex - 3;\n endFrame();\n }", "public Collection<Integer> getNumericCodes() {\n Collection<Integer> result = get(KEY_QUERY_NUMERIC_CODES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "public ThumborUrlBuilder align(VerticalAlign valign, HorizontalAlign halign) {\n return align(valign).align(halign);\n }", "protected void ensureDJStyles() {\n //first of all, register all parent styles if any\n for (Style style : getReport().getStyles().values()) {\n addStyleToDesign(style);\n }\n\n Style defaultDetailStyle = getReport().getOptions().getDefaultDetailStyle();\n\n Style defaultHeaderStyle = getReport().getOptions().getDefaultHeaderStyle();\n for (AbstractColumn column : report.getColumns()) {\n if (column.getStyle() == null)\n column.setStyle(defaultDetailStyle);\n if (column.getHeaderStyle() == null)\n column.setHeaderStyle(defaultHeaderStyle);\n }\n }" ]
the applications main loop.
[ "public void run()\r\n { \t\r\n \tSystem.out.println(AsciiSplash.getSplashArt());\r\n System.out.println(\"Welcome to the OJB PB tutorial application\");\r\n System.out.println();\r\n // never stop (there is a special use case to quit the application)\r\n while (true)\r\n {\r\n try\r\n {\r\n // select a use case and perform it\r\n UseCase uc = selectUseCase();\r\n uc.apply();\r\n }\r\n catch (Throwable t)\r\n {\r\n broker.close();\r\n System.out.println(t.getMessage());\r\n }\r\n }\r\n }" ]
[ "static void writePatch(final Patch rollbackPatch, final File file) throws IOException {\n final File parent = file.getParentFile();\n if (!parent.isDirectory()) {\n if (!parent.mkdirs() && !parent.exists()) {\n throw PatchLogger.ROOT_LOGGER.cannotCreateDirectory(file.getAbsolutePath());\n }\n }\n try {\n try (final OutputStream os = new FileOutputStream(file)){\n PatchXml.marshal(os, rollbackPatch);\n }\n } catch (XMLStreamException e) {\n throw new IOException(e);\n }\n }", "private String[] getColumnNames(ResultSetMetaData rsmd) throws Exception {\n ArrayList<String> names = new ArrayList<String>();\n\n // Get result set meta data\n int numColumns = rsmd.getColumnCount();\n\n // Get the column names; column indices start from 1\n for (int i = 1; i < numColumns + 1; i++) {\n String columnName = rsmd.getColumnName(i);\n\n names.add(columnName);\n }\n\n return names.toArray(new String[0]);\n }", "public static Shell createSubshell(String pathElement, Shell parent, String appName, Object mainHandler,\n MultiMap<String, Object> auxHandlers) {\n\n List<String> newPath = new ArrayList<String>(parent.getPath());\n newPath.add(pathElement);\n\n Shell subshell = new Shell(parent.getSettings().createWithAddedAuxHandlers(auxHandlers),\n new CommandTable(parent.getCommandTable().getNamer()), newPath);\n\n subshell.setAppName(appName);\n subshell.addMainHandler(subshell, \"!\");\n subshell.addMainHandler(new HelpCommandHandler(), \"?\");\n\n subshell.addMainHandler(mainHandler, \"\");\n return subshell;\n }", "protected I_CmsSearchDocument appendFieldMappingsFromElementsOnThePage(\n I_CmsSearchDocument document,\n CmsObject cms,\n CmsResource resource,\n List<String> systemFields) {\n\n try {\n CmsFile file = cms.readFile(resource);\n CmsXmlContainerPage containerPage = CmsXmlContainerPageFactory.unmarshal(cms, file);\n CmsContainerPageBean containerBean = containerPage.getContainerPage(cms);\n if (containerBean != null) {\n for (CmsContainerElementBean element : containerBean.getElements()) {\n element.initResource(cms);\n CmsResource elemResource = element.getResource();\n Set<CmsSearchField> mappedFields = getXSDMappingsForPage(cms, elemResource);\n if (mappedFields != null) {\n\n for (CmsSearchField field : mappedFields) {\n if (!systemFields.contains(field.getName())) {\n document = appendFieldMapping(\n document,\n field,\n cms,\n elemResource,\n CmsSolrDocumentXmlContent.extractXmlContent(cms, elemResource, getIndex()),\n cms.readPropertyObjects(resource, false),\n cms.readPropertyObjects(resource, true));\n } else {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.LOG_SOLR_ERR_MAPPING_TO_INTERNALLY_USED_FIELD_3,\n elemResource.getRootPath(),\n field.getName(),\n resource.getRootPath()));\n }\n }\n }\n }\n }\n } catch (CmsException e) {\n // Should be thrown if element on the page does not exist anymore - this is possible, but not necessarily an error.\n // Hence, just notice it in the debug log.\n if (LOG.isDebugEnabled()) {\n LOG.debug(e.getLocalizedMessage(), e);\n }\n }\n return document;\n }", "protected String sp_createSequenceQuery(String sequenceName, long maxKey)\r\n {\r\n return \"insert into \" + SEQ_TABLE_NAME + \" (\"\r\n + SEQ_NAME_STRING + \",\" + SEQ_ID_STRING +\r\n \") values ('\" + sequenceName + \"',\" + maxKey + \")\";\r\n }", "public static Configuration getDefaultFreemarkerConfiguration()\n {\n freemarker.template.Configuration configuration = new freemarker.template.Configuration(Configuration.VERSION_2_3_26);\n DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_26);\n objectWrapperBuilder.setUseAdaptersForContainers(true);\n objectWrapperBuilder.setIterableSupport(true);\n configuration.setObjectWrapper(objectWrapperBuilder.build());\n configuration.setAPIBuiltinEnabled(true);\n\n configuration.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader());\n configuration.setTemplateUpdateDelayMilliseconds(3600);\n return configuration;\n }", "private GraphicalIndicatorCriteria processCriteria(FieldType type)\n {\n GraphicalIndicatorCriteria criteria = new GraphicalIndicatorCriteria(m_properties);\n criteria.setLeftValue(type);\n\n int indicatorType = MPPUtility.getInt(m_data, m_dataOffset);\n m_dataOffset += 4;\n criteria.setIndicator(indicatorType);\n\n if (m_dataOffset + 4 < m_data.length)\n {\n int operatorValue = MPPUtility.getInt(m_data, m_dataOffset);\n m_dataOffset += 4;\n TestOperator operator = (operatorValue == 0 ? TestOperator.IS_ANY_VALUE : TestOperator.getInstance(operatorValue - 0x3E7));\n criteria.setOperator(operator);\n\n if (operator != TestOperator.IS_ANY_VALUE)\n {\n processOperandValue(0, type, criteria);\n\n if (operator == TestOperator.IS_WITHIN || operator == TestOperator.IS_NOT_WITHIN)\n {\n processOperandValue(1, type, criteria);\n }\n }\n }\n\n return (criteria);\n }", "public static nsrollbackcmd get(nitro_service service) throws Exception{\n\t\tnsrollbackcmd obj = new nsrollbackcmd();\n\t\tnsrollbackcmd[] response = (nsrollbackcmd[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "void checkRmModelConformance() {\n final AmVisitor<AmObject, AmConstraintContext> visitor = AmVisitors.preorder(new ConformanceVisitor());\n ArchetypeWalker.walkConstraints(visitor, archetype, new AmConstraintContext());\n }" ]
Returns formatted version of Iban. @return A string representing formatted Iban for printing.
[ "static String toFormattedString(final String iban) {\n final StringBuilder ibanBuffer = new StringBuilder(iban);\n final int length = ibanBuffer.length();\n\n for (int i = 0; i < length / 4; i++) {\n ibanBuffer.insert((i + 1) * 4 + i, ' ');\n }\n\n return ibanBuffer.toString().trim();\n }" ]
[ "@Override\n public void run()\n {\n try {\n startBarrier.await();\n\n int idleCount = 0;\n while (!isRunning.compareAndSet(idleCount > lingerIterations && pidToProcessMap.isEmpty(), false)) {\n idleCount = (!shutdown && process()) ? 0 : (idleCount + 1);\n }\n }\n catch (Exception e) {\n // TODO: how to handle this error?\n isRunning.set(false);\n }\n }", "@Override public void render() {\n Video video = getContent();\n renderThumbnail(video);\n renderTitle(video);\n renderMarker(video);\n renderLabel();\n }", "public String getValueSchema() throws IOException {\n Schema schema = getInputPathAvroSchema();\n String valueSchema = schema.getField(valueFieldName).schema().toString();\n return valueSchema;\n }", "public String setClassification(String classificationType) {\n Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType);\n Metadata classification = null;\n\n try {\n classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, \"enterprise\", metadata);\n } catch (BoxAPIException e) {\n if (e.getResponseCode() == 409) {\n metadata = new Metadata(\"enterprise\", Metadata.CLASSIFICATION_TEMPLATE_KEY);\n metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType);\n classification = this.updateMetadata(metadata);\n } else {\n throw e;\n }\n }\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }", "private Map<Integer, Integer> getNodeIdToNaryCount(Cluster cluster,\n StoreRoutingPlan storeRoutingPlan) {\n Map<Integer, Integer> nodeIdToNaryCount = Maps.newHashMap();\n\n for(int nodeId: cluster.getNodeIds()) {\n nodeIdToNaryCount.put(nodeId, storeRoutingPlan.getZoneNAryPartitionIds(nodeId).size());\n }\n\n return nodeIdToNaryCount;\n }", "public static String escapeDoubleQuotesForJson(String text) {\n\t\tif ( text == null ) {\n\t\t\treturn null;\n\t\t}\n\t\tStringBuilder builder = new StringBuilder( text.length() );\n\t\tfor ( int i = 0; i < text.length(); i++ ) {\n\t\t\tchar c = text.charAt( i );\n\t\t\tswitch ( c ) {\n\t\t\t\tcase '\"':\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tbuilder.append( \"\\\\\" );\n\t\t\t\tdefault:\n\t\t\t\t\tbuilder.append( c );\n\t\t\t}\n\t\t}\n\t\treturn builder.toString();\n\t}", "public CollectionRequest<ProjectMembership> findByProject(String project) {\n \n String path = String.format(\"/projects/%s/project_memberships\", project);\n return new CollectionRequest<ProjectMembership>(this, ProjectMembership.class, path, \"GET\");\n }", "public static base_response update(nitro_service client, filterhtmlinjectionparameter resource) throws Exception {\n\t\tfilterhtmlinjectionparameter updateresource = new filterhtmlinjectionparameter();\n\t\tupdateresource.rate = resource.rate;\n\t\tupdateresource.frequency = resource.frequency;\n\t\tupdateresource.strict = resource.strict;\n\t\tupdateresource.htmlsearchlen = resource.htmlsearchlen;\n\t\treturn updateresource.update_resource(client);\n\t}", "public void copyTo(long srcOffset, LBufferAPI dest, long destOffset, long size) {\n unsafe.copyMemory(address() + srcOffset, dest.address() + destOffset, size);\n }" ]
Creates an appropriate HSGE for resources in the host tree, excluding the server and server-config subtrees
[ "private synchronized HostServerGroupEffect getHostEffect(PathAddress address, String host, Resource root) {\n if (requiresMapping) {\n map(root);\n requiresMapping = false;\n }\n Set<String> mapped = hostsToGroups.get(host);\n if (mapped == null) {\n // Unassigned host. Treat like an unassigned profile or socket-binding-group;\n // i.e. available to all server group scoped roles.\n // Except -- WFLY-2085 -- the master HC is not open to all s-g-s-rs\n Resource hostResource = root.getChild(PathElement.pathElement(HOST, host));\n if (hostResource != null) {\n ModelNode dcModel = hostResource.getModel().get(DOMAIN_CONTROLLER);\n if (!dcModel.hasDefined(REMOTE)) {\n mapped = Collections.emptySet(); // prevents returning HostServerGroupEffect.forUnassignedHost(address, host)\n }\n }\n }\n return mapped == null ? HostServerGroupEffect.forUnassignedHost(address, host)\n : HostServerGroupEffect.forMappedHost(address, mapped, host);\n\n }" ]
[ "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 }", "private void logColumnData(int startIndex, int length)\n {\n if (m_log != null)\n {\n m_log.println();\n m_log.println(FastTrackUtility.hexdump(m_buffer, startIndex, length, true, 16, \"\"));\n m_log.println();\n m_log.flush();\n }\n }", "private int beatOffset(int beatNumber) {\n if (beatCount == 0) {\n throw new IllegalStateException(\"There are no beats in this beat grid.\");\n }\n if (beatNumber < 1 || beatNumber > beatCount) {\n throw new IndexOutOfBoundsException(\"beatNumber (\" + beatNumber + \") must be between 1 and \" + beatCount);\n }\n return beatNumber - 1;\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 final static String process(final File file, final boolean safeMode) throws IOException\n {\n return process(file, Configuration.builder().setSafeMode(safeMode).build());\n }", "@Override\n\tpublic void visit(Rule rule) {\n\t\tRule copy = null;\n\t\tFilter filterCopy = null;\n\n\t\tif (rule.getFilter() != null) {\n\t\t\tFilter filter = rule.getFilter();\n\t\t\tfilterCopy = copy(filter);\n\t\t}\n\n\t\tList<Symbolizer> symsCopy = new ArrayList<Symbolizer>();\n\t\tfor (Symbolizer sym : rule.symbolizers()) {\n\t\t\tif (!skipSymbolizer(sym)) {\n\t\t\t\tSymbolizer symCopy = copy(sym);\n\t\t\t\tsymsCopy.add(symCopy);\n\t\t\t}\n\t\t}\n\n\t\tGraphic[] legendCopy = rule.getLegendGraphic();\n\t\tfor (int i = 0; i < legendCopy.length; i++) {\n\t\t\tlegendCopy[i] = copy(legendCopy[i]);\n\t\t}\n\n\t\tDescription descCopy = rule.getDescription();\n\t\tdescCopy = copy(descCopy);\n\n\t\tcopy = sf.createRule();\n\t\tcopy.symbolizers().addAll(symsCopy);\n\t\tcopy.setDescription(descCopy);\n\t\tcopy.setLegendGraphic(legendCopy);\n\t\tcopy.setName(rule.getName());\n\t\tcopy.setFilter(filterCopy);\n\t\tcopy.setElseFilter(rule.isElseFilter());\n\t\tcopy.setMaxScaleDenominator(rule.getMaxScaleDenominator());\n\t\tcopy.setMinScaleDenominator(rule.getMinScaleDenominator());\n\n\t\tif (STRICT && !copy.equals(rule)) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"Was unable to duplicate provided Rule:\" + rule);\n\t\t}\n\t\tpages.push(copy);\n\t}", "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 }", "public Integer getIdFromName(String profileName) {\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_PROFILE +\n \" WHERE \" + Constants.PROFILE_PROFILE_NAME + \" = ?\");\n query.setString(1, profileName);\n results = query.executeQuery();\n if (results.next()) {\n Object toReturn = results.getObject(Constants.GENERIC_ID);\n query.close();\n return (Integer) toReturn;\n }\n query.close();\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 (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n return null;\n }", "public static String fillLogParams(String sql, Map<Object, Object> logParams) {\n\t\tStringBuilder result = new StringBuilder();\n\t\tMap<Object, Object> tmpLogParam = (logParams == null ? new HashMap<Object, Object>() : logParams);\n\n\t\tIterator<Object> it = tmpLogParam.values().iterator();\n\t\tboolean inQuote = false;\n\t\tboolean inQuote2 = false;\n\t\tchar[] sqlChar = sql != null ? sql.toCharArray() : new char[]{};\n\n\t\tfor (int i=0; i < sqlChar.length; i++){\n\t\t\tif (sqlChar[i] == '\\''){\n\t\t\t\tinQuote = !inQuote;\n\t\t\t}\n\t\t\tif (sqlChar[i] == '\"'){\n\t\t\t\tinQuote2 = !inQuote2;\n\t\t\t}\n\n\t\t\tif (sqlChar[i] == '?' && !(inQuote || inQuote2)){\n\t\t\t\tif (it.hasNext()){\n\t\t\t\t\tresult.append(prettyPrint(it.next()));\n\t\t\t\t} else {\n\t\t\t\t\tresult.append('?');\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresult.append(sqlChar[i]);\n\t\t\t}\n\t\t}\n\n\n\t\treturn result.toString();\n\t}" ]
Gets all Checkable widgets in the group @return list of Checkable widgets
[ "public <T extends Widget & Checkable> List<T> getCheckableChildren() {\n List<Widget> children = getChildren();\n ArrayList<T> result = new ArrayList<>();\n for (Widget c : children) {\n if (c instanceof Checkable) {\n result.add((T) c);\n }\n }\n return result;\n }" ]
[ "protected static boolean isMaskCompatibleWithRange(long value, long upperValue, long maskValue, long maxValue) {\n\t\tif(value == upperValue || maskValue == maxValue || maskValue == 0) {\n\t\t\treturn true;\n\t\t}\n\n\t\t//algorithm:\n\t\t//here we find the highest bit that is part of the range, highestDifferingBitInRange (ie changes from lower to upper)\n\t\t//then we find the highest bit in the mask that is 1 that is the same or below highestDifferingBitInRange (if such a bit exists)\n\t\t\n\t\t//this gives us the highest bit that is part of the masked range (ie changes from lower to upper after applying the mask)\n\t\t//if this latter bit exists, then any bit below it in the mask must be 1 to include the entire range.\n\t\t\n\t\tlong differing = value ^ upperValue;\n\t\tboolean foundDiffering = (differing != 0);\n\t\tboolean differingIsLowestBit = (differing == 1);\n\t\tif(foundDiffering && !differingIsLowestBit) {\n\t\t\tint highestDifferingBitInRange = Long.numberOfLeadingZeros(differing);\n\t\t\tlong maskMask = ~0L >>> highestDifferingBitInRange;\n\t\t\tlong differingMasked = maskValue & maskMask;\n\t\t\tfoundDiffering = (differingMasked != 0);\n\t\t\tdifferingIsLowestBit = (differingMasked == 1);\n\t\t\tif(foundDiffering && !differingIsLowestBit) {\n\t\t\t\t//anything below highestDifferingBitMasked in the mask must be ones\n\t\t\t\t//Also, if we have masked out any 1 bit in the original, then anything that we do not mask out that follows must be all 1s\n\t\t\t\tint highestDifferingBitMasked = Long.numberOfLeadingZeros(differingMasked);\n\t\t\t\tlong hostMask = ~0L >>> (highestDifferingBitMasked + 1);//for the first mask bit that is 1, all bits that follow must also be 1\n\t\t\t\tif((maskValue & hostMask) != hostMask) { //check if all ones below\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif(highestDifferingBitMasked > highestDifferingBitInRange) {\n\t\t\t\t\t//We have masked out a 1 bit, so we need to check that all bits in upper value that we do not mask out are also 1 bits, otherwise we end up missing values in the masked range\n\t\t\t\t\t//This check is unnecessary for prefix-length subnets, only non-standard ranges might fail this check.\n\t\t\t\t\t//For instance, if we have range 0000 to 1010\n\t\t\t\t\t//and we mask upper and lower with 0111\n\t\t\t\t\t//we get 0000 to 0010, but 0111 was in original range, and the mask of that value retains that value\n\t\t\t\t\t//so that value needs to be in final range, and it's not.\n\t\t\t\t\t//What went wrong is that we masked out the top bit, and any other bit that is not masked out must be 1.\n\t\t\t\t\t//To work, our original range needed to be 0000 to 1111, with the three 1s following the first masked-out 1\n\t\t\t\t\tlong hostMaskUpper = ~0L >>> highestDifferingBitMasked;\n\t\t\t\t\tif((upperValue & hostMaskUpper) != hostMaskUpper) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "private static long createLongSeed(byte[] seed)\n {\n if (seed == null || seed.length != SEED_SIZE_BYTES)\n {\n throw new IllegalArgumentException(\"Java RNG requires a 64-bit (8-byte) seed.\");\n }\n return BinaryUtils.convertBytesToLong(seed, 0);\n }", "public static boolean isMessageContentToBeLogged(final Message message, final boolean logMessageContent,\n boolean logMessageContentOverride) {\n\n /*\n * If controlling of logging behavior is not allowed externally\n * then log according to global property value\n */\n if (!logMessageContentOverride) {\n return logMessageContent;\n }\n\n Object logMessageContentExtObj = message.getContextualProperty(EXTERNAL_PROPERTY_NAME);\n\n if (null == logMessageContentExtObj) {\n\n return logMessageContent;\n\n } else if (logMessageContentExtObj instanceof Boolean) {\n\n return ((Boolean) logMessageContentExtObj).booleanValue();\n\n } else if (logMessageContentExtObj instanceof String) {\n\n String logMessageContentExtVal = (String) logMessageContentExtObj;\n\n if (logMessageContentExtVal.equalsIgnoreCase(\"true\")) {\n\n return true;\n\n } else if (logMessageContentExtVal.equalsIgnoreCase(\"false\")) {\n\n return false;\n\n } else {\n\n return logMessageContent;\n }\n } else {\n\n return logMessageContent;\n }\n }", "static void addOperationAddress(final ModelNode operation, final PathAddress base, final String key, final String value) {\n operation.get(OP_ADDR).set(base.append(key, value).toModelNode());\n }", "public static String readFileContents(FileSystem fs, Path path, int bufferSize)\n throws IOException {\n if(bufferSize <= 0)\n return new String();\n\n FSDataInputStream input = fs.open(path);\n byte[] buffer = new byte[bufferSize];\n\n ByteArrayOutputStream stream = new ByteArrayOutputStream();\n\n while(true) {\n int read = input.read(buffer);\n if(read < 0) {\n break;\n } else {\n buffer = ByteUtils.copy(buffer, 0, read);\n }\n stream.write(buffer);\n }\n\n return new String(stream.toByteArray());\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 }", "private boolean removeKeyForAllLanguages(String key) {\n\n try {\n if (hasDescriptor()) {\n lockDescriptor();\n }\n loadAllRemainingLocalizations();\n lockAllLocalizations(key);\n } catch (CmsException | IOException e) {\n LOG.warn(\"Not able lock all localications for bundle.\", e);\n return false;\n }\n if (!hasDescriptor()) {\n\n for (Entry<Locale, SortedProperties> entry : m_localizations.entrySet()) {\n SortedProperties localization = entry.getValue();\n if (localization.containsKey(key)) {\n localization.remove(key);\n m_changedTranslations.add(entry.getKey());\n }\n }\n }\n return true;\n }", "public DomainList getPhotoDomains(Date date, String photoId, int perPage, int page) throws FlickrException {\n return getDomains(METHOD_GET_PHOTO_DOMAINS, \"photo_id\", photoId, date, perPage, page);\n }", "public static String formatConnectionTerminationMessage(final String connectionName, final String host, final String connectionReason, final String terminationReason) {\n\t\treturn CON_TERMINATION_FORMAT.format(new Object[] { connectionName, host, connectionReason, terminationReason });\n\t}" ]
Get the target file for misc items. @param item the misc item @return the target location
[ "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 }" ]
[ "public void setClassOfObject(Class c)\r\n {\r\n m_Class = c;\r\n isAbstract = Modifier.isAbstract(m_Class.getModifiers());\r\n // TODO : Shouldn't the HashMap in DescriptorRepository be updated as well?\r\n }", "public <Result, Param extends Resource> Result execWithTemporaryCaching(Param resource, IUnitOfWork<Result, Param> transaction) throws WrappedException {\n\t\tCacheAdapter cacheAdapter = getOrCreate(resource);\n\t\tIgnoreValuesMemento memento = cacheAdapter.ignoreNewValues();\n\t\ttry {\n\t\t\treturn transaction.exec(resource);\n\t\t} catch (Exception e) {\n\t\t\tthrow new WrappedException(e);\n\t\t} finally {\n\t\t\tmemento.done();\n\t\t}\n\t}", "public void poseFromBones()\n {\n for (int i = 0; i < getNumBones(); ++i)\n {\n GVRSceneObject bone = mBones[i];\n if (bone == null)\n {\n continue;\n }\n if ((mBoneOptions[i] & BONE_LOCK_ROTATION) != 0)\n {\n continue;\n }\n GVRTransform trans = bone.getTransform();\n mPose.setLocalMatrix(i, trans.getLocalModelMatrix4f());\n }\n mPose.sync();\n updateBonePose();\n }", "private void fillToolBar(final I_CmsAppUIContext context) {\n\n context.setAppTitle(m_messages.key(Messages.GUI_APP_TITLE_0));\n\n // create components\n Component publishBtn = createPublishButton();\n m_saveBtn = createSaveButton();\n m_saveExitBtn = createSaveExitButton();\n Component closeBtn = createCloseButton();\n\n context.enableDefaultToolbarButtons(false);\n context.addToolbarButtonRight(closeBtn);\n context.addToolbarButton(publishBtn);\n context.addToolbarButton(m_saveExitBtn);\n context.addToolbarButton(m_saveBtn);\n\n Component addDescriptorBtn = createAddDescriptorButton();\n if (m_model.hasDescriptor() || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {\n addDescriptorBtn.setEnabled(false);\n }\n context.addToolbarButton(addDescriptorBtn);\n if (m_model.getBundleType().equals(BundleType.XML)) {\n Component convertToPropertyBundleBtn = createConvertToPropertyBundleButton();\n context.addToolbarButton(convertToPropertyBundleBtn);\n }\n }", "public static base_response update(nitro_service client, csparameter resource) throws Exception {\n\t\tcsparameter updateresource = new csparameter();\n\t\tupdateresource.stateupdate = resource.stateupdate;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static ResourceField getInstance(int value)\n {\n ResourceField result = null;\n\n if (value >= 0 && value < FIELD_ARRAY.length)\n {\n result = FIELD_ARRAY[value];\n }\n else\n {\n if ((value & 0x8000) != 0)\n {\n int baseValue = ResourceField.ENTERPRISE_CUSTOM_FIELD1.getValue();\n int id = baseValue + (value & 0xFFF);\n result = ResourceField.getInstance(id);\n }\n }\n\n return (result);\n }", "protected boolean isValidLayout(Gravity gravity, Orientation orientation) {\n boolean isValid = true;\n\n switch (gravity) {\n case TOP:\n case BOTTOM:\n isValid = (!isUnlimitedSize() && orientation == Orientation.VERTICAL);\n break;\n case LEFT:\n case RIGHT:\n isValid = (!isUnlimitedSize() && orientation == Orientation.HORIZONTAL);\n break;\n case FRONT:\n case BACK:\n isValid = (!isUnlimitedSize() && orientation == Orientation.STACK);\n break;\n case FILL:\n isValid = !isUnlimitedSize();\n break;\n case CENTER:\n break;\n default:\n isValid = false;\n break;\n }\n if (!isValid) {\n Log.w(TAG, \"Cannot set the gravity %s and orientation %s - \" +\n \"due to unlimited bounds or incompatibility\", gravity, orientation);\n }\n return isValid;\n }", "@Override\r\n\tpublic boolean check(EmbeddedBrowser browser) {\r\n\t\tString js =\r\n\t\t\t\t\"try{ if(\" + expression + \"){return '1';}else{\" + \"return '0';}}catch(e){\"\r\n\t\t\t\t\t\t+ \" return '0';}\";\r\n\t\ttry {\r\n\t\t\tObject object = browser.executeJavaScript(js);\r\n\t\t\tif (object == null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\treturn object.toString().equals(\"1\");\r\n\t\t} catch (CrawljaxException e) {\r\n\t\t\t// Exception is caught, check failed so return false;\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}", "@Deprecated\n public <T> List<T> findByIndex(String selectorJson, Class<T> classOfT) {\n return findByIndex(selectorJson, classOfT, new FindByIndexOptions());\n }" ]
Adds a handler for a mouse type event on the map. @param obj The object that the event should be registered on. @param type Type of the event to register against. @param h Handler that will be called when the event occurs.
[ "public void addUIEventHandler(JavascriptObject obj, UIEventType type, UIEventHandler h) {\n String key = registerEventHandler(h);\n String mcall = \"google.maps.event.addListener(\" + obj.getVariableName() + \", '\" + type.name() + \"', \"\n + \"function(event) {document.jsHandlers.handleUIEvent('\" + key + \"', event);});\";//.latLng\n //System.out.println(\"addUIEventHandler mcall: \" + mcall);\n runtime.execute(mcall);\n }" ]
[ "public static XMLStreamException unexpectedEndElement(final XMLExtendedStreamReader reader) {\n return ControllerLogger.ROOT_LOGGER.unexpectedEndElement(reader.getName(), reader.getLocation());\n }", "public Map<String, String> getMapAttribute(String name, String defaultValue) {\n return mapSplit(getAttribute(name), defaultValue);\n }", "private static int findTrackIdAtOffset(SlotReference slot, Client client, int offset) throws IOException {\n Message entry = client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot.slot, CdjStatus.TrackType.REKORDBOX, offset, 1).get(0);\n if (entry.getMenuItemType() == Message.MenuItemType.UNKNOWN) {\n logger.warn(\"Encountered unrecognized track list entry item type: {}\", entry);\n }\n return (int)((NumberField)entry.arguments.get(1)).getValue();\n }", "protected List<Object> executeProcessors(final List<Object> processedColumns, final CellProcessor[] processors) {\n\t\tUtil.executeCellProcessors(processedColumns, getColumns(), processors, getLineNumber(), getRowNumber());\n\t\treturn processedColumns;\n\t}", "private static QName convertString(String str) {\n if (str != null) {\n return QName.valueOf(str);\n } else {\n return null;\n }\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 <ResultT> PollingState<ResultT> createFromJSONString(String serializedPollingState) {\n ObjectMapper mapper = initMapper(new ObjectMapper());\n PollingState<ResultT> pollingState;\n try {\n pollingState = mapper.readValue(serializedPollingState, PollingState.class);\n } catch (IOException exception) {\n throw new RuntimeException(exception);\n }\n return pollingState;\n }", "public static hanode_routemonitor_binding[] get(nitro_service service, Long id) throws Exception{\n\t\thanode_routemonitor_binding obj = new hanode_routemonitor_binding();\n\t\tobj.set_id(id);\n\t\thanode_routemonitor_binding response[] = (hanode_routemonitor_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static 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}" ]
Parse a string representation of a Boolean value. @param value string representation @return Boolean value
[ "public static Boolean parseBoolean(String value) throws ParseException\n {\n Boolean result = null;\n Integer number = parseInteger(value);\n if (number != null)\n {\n result = number.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE;\n }\n\n return result;\n }" ]
[ "public List<ServerRedirect> deleteServerMapping(int serverMappingId) {\n ArrayList<ServerRedirect> servers = new ArrayList<ServerRedirect>();\n try {\n JSONArray serverArray = new JSONArray(doDelete(BASE_SERVER + \"/\" + serverMappingId, null));\n for (int i = 0; i < serverArray.length(); i++) {\n JSONObject jsonServer = serverArray.getJSONObject(i);\n ServerRedirect server = getServerRedirectFromJSON(jsonServer);\n if (server != null) {\n servers.add(server);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n\n return servers;\n }", "public static base_responses unset(nitro_service client, String acl6name[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 unsetresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tunsetresources[i] = new nsacl6();\n\t\t\t\tunsetresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "private void countEntity() {\n\t\tif (!this.timer.isRunning()) {\n\t\t\tstartTimer();\n\t\t}\n\n\t\tthis.entityCount++;\n\t\tif (this.entityCount % 100 == 0) {\n\t\t\ttimer.stop();\n\t\t\tint seconds = (int) (timer.getTotalWallTime() / 1000000000);\n\t\t\tif (seconds >= this.lastSeconds + this.reportInterval) {\n\t\t\t\tthis.lastSeconds = seconds;\n\t\t\t\tprintStatus();\n\t\t\t\tif (this.timeout > 0 && seconds > this.timeout) {\n\t\t\t\t\tlogger.info(\"Timeout. Aborting processing.\");\n\t\t\t\t\tthrow new TimeoutException();\n\t\t\t\t}\n\t\t\t}\n\t\t\ttimer.start();\n\t\t}\n\t}", "protected synchronized void quit() {\n log.debug(\"Stopping {}\", getName());\n closeServerSocket();\n\n // Close all handlers. Handler threads terminate if run loop exits\n synchronized (handlers) {\n for (ProtocolHandler handler : handlers) {\n handler.close();\n }\n handlers.clear();\n }\n log.debug(\"Stopped {}\", getName());\n }", "public void actionPerformed(java.awt.event.ActionEvent actionEvent)\r\n {\r\n new Thread()\r\n {\r\n public void run()\r\n {\r\n final java.sql.Connection conn = new JDlgDBConnection(containingFrame, false).showAndReturnConnection();\r\n if (conn != null)\r\n {\r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n JIFrmDatabase frm = new JIFrmDatabase(conn);\r\n containingFrame.getContentPane().add(frm);\r\n frm.setVisible(true);\r\n }\r\n });\r\n }\r\n }\r\n }.start();\r\n }", "private void appendJoinSQL92NoParen(Join join, StringBuffer where, StringBuffer buf)\r\n {\r\n if (join.isOuter)\r\n {\r\n buf.append(\" LEFT OUTER JOIN \");\r\n }\r\n else\r\n {\r\n buf.append(\" INNER JOIN \");\r\n }\r\n\r\n buf.append(join.right.getTableAndAlias());\r\n buf.append(\" ON \");\r\n join.appendJoinEqualities(buf);\r\n\r\n appendTableWithJoins(join.right, where, buf);\r\n }", "private JsonObject getPendingJSONObject() {\n for (Map.Entry<String, BoxJSONObject> entry : this.children.entrySet()) {\n BoxJSONObject child = entry.getValue();\n JsonObject jsonObject = child.getPendingJSONObject();\n if (jsonObject != null) {\n if (this.pendingChanges == null) {\n this.pendingChanges = new JsonObject();\n }\n\n this.pendingChanges.set(entry.getKey(), jsonObject);\n }\n }\n return this.pendingChanges;\n }", "private String getDurationString(Duration value)\n {\n String result = null;\n\n if (value != null)\n {\n double seconds = 0;\n\n switch (value.getUnits())\n {\n case MINUTES:\n case ELAPSED_MINUTES:\n {\n seconds = value.getDuration() * 60;\n break;\n }\n\n case HOURS:\n case ELAPSED_HOURS:\n {\n seconds = value.getDuration() * (60 * 60);\n break;\n }\n\n case DAYS:\n {\n double minutesPerDay = m_projectFile.getProjectProperties().getMinutesPerDay().doubleValue();\n seconds = value.getDuration() * (minutesPerDay * 60);\n break;\n }\n\n case ELAPSED_DAYS:\n {\n seconds = value.getDuration() * (24 * 60 * 60);\n break;\n }\n\n case WEEKS:\n {\n double minutesPerWeek = m_projectFile.getProjectProperties().getMinutesPerWeek().doubleValue();\n seconds = value.getDuration() * (minutesPerWeek * 60);\n break;\n }\n\n case ELAPSED_WEEKS:\n {\n seconds = value.getDuration() * (7 * 24 * 60 * 60);\n break;\n }\n\n case MONTHS:\n {\n double minutesPerDay = m_projectFile.getProjectProperties().getMinutesPerDay().doubleValue();\n double daysPerMonth = m_projectFile.getProjectProperties().getDaysPerMonth().doubleValue();\n seconds = value.getDuration() * (daysPerMonth * minutesPerDay * 60);\n break;\n }\n\n case ELAPSED_MONTHS:\n {\n seconds = value.getDuration() * (30 * 24 * 60 * 60);\n break;\n }\n\n case YEARS:\n {\n double minutesPerDay = m_projectFile.getProjectProperties().getMinutesPerDay().doubleValue();\n double daysPerMonth = m_projectFile.getProjectProperties().getDaysPerMonth().doubleValue();\n seconds = value.getDuration() * (12 * daysPerMonth * minutesPerDay * 60);\n break;\n }\n\n case ELAPSED_YEARS:\n {\n seconds = value.getDuration() * (365 * 24 * 60 * 60);\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n result = Long.toString((long) seconds);\n }\n\n return (result);\n }", "void logAuditRecord() {\n trackConfigurationChange();\n if (!auditLogged) {\n try {\n AccessAuditContext accessContext = SecurityActions.currentAccessAuditContext();\n Caller caller = getCaller();\n auditLogger.log(\n isReadOnly(),\n resultAction,\n caller == null ? null : caller.getName(),\n accessContext == null ? null : accessContext.getDomainUuid(),\n accessContext == null ? null : accessContext.getAccessMechanism(),\n accessContext == null ? null : accessContext.getRemoteAddress(),\n getModel(),\n controllerOperations);\n auditLogged = true;\n } catch (Exception e) {\n ControllerLogger.MGMT_OP_LOGGER.failedToUpdateAuditLog(e);\n }\n }\n }" ]
Adds an individual alias. It will be merged with the current list of aliases, or added as a label if there is no label for this item in this language yet. @param alias the alias to add
[ "protected void addAlias(MonolingualTextValue alias) {\n String lang = alias.getLanguageCode();\n AliasesWithUpdate currentAliasesUpdate = newAliases.get(lang);\n \n NameWithUpdate currentLabel = newLabels.get(lang);\n // If there isn't any label for that language, put the alias there\n if (currentLabel == null) {\n newLabels.put(lang, new NameWithUpdate(alias, true));\n // If the new alias is equal to the current label, skip it\n } else if (!currentLabel.value.equals(alias)) {\n \tif (currentAliasesUpdate == null) {\n \t\tcurrentAliasesUpdate = new AliasesWithUpdate(new ArrayList<MonolingualTextValue>(), true);\n \t}\n \tList<MonolingualTextValue> currentAliases = currentAliasesUpdate.aliases;\n \tif(!currentAliases.contains(alias)) {\n \t\tcurrentAliases.add(alias);\n \t\tcurrentAliasesUpdate.added.add(alias);\n \t\tcurrentAliasesUpdate.write = true;\n \t}\n \tnewAliases.put(lang, currentAliasesUpdate);\n }\n }" ]
[ "private void checkLocking(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String jdbcType = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE);\r\n\r\n if (!\"TIMESTAMP\".equals(jdbcType) && !\"INTEGER\".equals(jdbcType))\r\n {\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_LOCKING, false))\r\n {\r\n throw new ConstraintException(\"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has locking set to true though it is not of TIMESTAMP or INTEGER type\");\r\n }\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_UPDATE_LOCK, false))\r\n {\r\n throw new ConstraintException(\"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has update-lock set to true though it is not of TIMESTAMP or INTEGER type\");\r\n }\r\n }\r\n }", "private void destroyRequestQueue(Queue<AsyncResourceRequest<V>> requestQueue) {\n if(requestQueue != null) {\n AsyncResourceRequest<V> resourceRequest = requestQueue.poll();\n while(resourceRequest != null) {\n destroyRequest(resourceRequest);\n resourceRequest = requestQueue.poll();\n }\n }\n }", "void killAll()\n {\n for (RjiRegistration reg : this.instancesById.values().toArray(new RjiRegistration[] {}))\n {\n reg.rji.handleInstruction(Instruction.KILL);\n }\n }", "@Override\n public void stopTransition() {\n //call listeners so they can perform their actions first, like modifying this adapter's transitions\n for (int i = 0, size = mListenerList.size(); i < size; i++) {\n mListenerList.get(i).onTransitionEnd(this);\n }\n\n for (int i = 0, size = mTransitionList.size(); i < size; i++) {\n mTransitionList.get(i).stopTransition();\n }\n }", "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 void copy(ProjectCalendar cal)\n {\n setName(cal.getName());\n setParent(cal.getParent());\n System.arraycopy(cal.getDays(), 0, getDays(), 0, getDays().length);\n for (ProjectCalendarException ex : cal.m_exceptions)\n {\n addCalendarException(ex.getFromDate(), ex.getToDate());\n for (DateRange range : ex)\n {\n ex.addRange(new DateRange(range.getStart(), range.getEnd()));\n }\n }\n\n for (ProjectCalendarHours hours : getHours())\n {\n if (hours != null)\n {\n ProjectCalendarHours copyHours = cal.addCalendarHours(hours.getDay());\n for (DateRange range : hours)\n {\n copyHours.addRange(new DateRange(range.getStart(), range.getEnd()));\n }\n }\n }\n }", "private Set<Annotation> getFieldAnnotations(final Class<?> clazz)\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn new LinkedHashSet<Annotation>(asList(clazz.getDeclaredField(propertyName).getAnnotations()));\n\t\t}\n\t\tcatch (final NoSuchFieldException e)\n\t\t{\n\t\t\tif (clazz.getSuperclass() != null)\n\t\t\t{\n\t\t\t\treturn getFieldAnnotations(clazz.getSuperclass());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlogger.debug(\"Cannot find propertyName: {}, declaring class: {}\", propertyName, clazz);\n\t\t\t\treturn new LinkedHashSet<Annotation>(0);\n\t\t\t}\n\t\t}\n\t}", "@SuppressWarnings(\"deprecation\")\n\tprivate static WriteConcern mergeWriteConcern(WriteConcern original, WriteConcern writeConcern) {\n\t\tif ( original == null ) {\n\t\t\treturn writeConcern;\n\t\t}\n\t\telse if ( writeConcern == null ) {\n\t\t\treturn original;\n\t\t}\n\t\telse if ( original.equals( writeConcern ) ) {\n\t\t\treturn original;\n\t\t}\n\n\t\tObject wObject;\n\t\tint wTimeoutMS;\n\t\tboolean fsync;\n\t\tBoolean journal;\n\n\t\tif ( original.getWObject() instanceof String ) {\n\t\t\twObject = original.getWString();\n\t\t}\n\t\telse if ( writeConcern.getWObject() instanceof String ) {\n\t\t\twObject = writeConcern.getWString();\n\t\t}\n\t\telse {\n\t\t\twObject = Math.max( original.getW(), writeConcern.getW() );\n\t\t}\n\n\t\twTimeoutMS = Math.min( original.getWtimeout(), writeConcern.getWtimeout() );\n\n\t\tfsync = original.getFsync() || writeConcern.getFsync();\n\n\t\tif ( original.getJournal() == null ) {\n\t\t\tjournal = writeConcern.getJournal();\n\t\t}\n\t\telse if ( writeConcern.getJournal() == null ) {\n\t\t\tjournal = original.getJournal();\n\t\t}\n\t\telse {\n\t\t\tjournal = original.getJournal() || writeConcern.getJournal();\n\t\t}\n\n\t\tif ( wObject instanceof String ) {\n\t\t\treturn new WriteConcern( (String) wObject, wTimeoutMS, fsync, journal );\n\t\t}\n\t\telse {\n\t\t\treturn new WriteConcern( (int) wObject, wTimeoutMS, fsync, journal );\n\t\t}\n\t}", "private ClassLoaderInterface getClassLoader() {\n\t\tMap<String, Object> application = ActionContext.getContext().getApplication();\n\t\tif (application != null) {\n\t\t\treturn (ClassLoaderInterface) application.get(ClassLoaderInterface.CLASS_LOADER_INTERFACE);\n\t\t}\n\t\treturn null;\n\t}" ]
Processes text as a FreeMarker template. Usually used to process an inner body of a tag. @param text text of a template. @param params map with parameters for processing. @param writer writer to write output to.
[ "protected void process(String text, Map params, Writer writer){\n\n try{\n Template t = new Template(\"temp\", new StringReader(text), FreeMarkerTL.getEnvironment().getConfiguration());\n t.process(params, writer);\n }catch(Exception e){ \n throw new ViewException(e);\n }\n }" ]
[ "private static void computeBadByteSkipArray(byte[] pattern, int[] badByteArray) {\n for (int a = 0; a < ALPHABET_SIZE; a++) {\n badByteArray[a] = pattern.length;\n }\n\n for (int j = 0; j < pattern.length - 1; j++) {\n badByteArray[pattern[j] - Byte.MIN_VALUE] = pattern.length - j - 1;\n }\n }", "private void readResource(net.sf.mpxj.ganttproject.schema.Resource gpResource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n mpxjResource.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpResource.getId()) + 1));\n mpxjResource.setName(gpResource.getName());\n mpxjResource.setEmailAddress(gpResource.getContacts());\n mpxjResource.setText(1, gpResource.getPhone());\n mpxjResource.setGroup(m_roleDefinitions.get(gpResource.getFunction()));\n\n net.sf.mpxj.ganttproject.schema.Rate gpRate = gpResource.getRate();\n if (gpRate != null)\n {\n mpxjResource.setStandardRate(new Rate(gpRate.getValueAttribute(), TimeUnit.DAYS));\n }\n readResourceCustomFields(gpResource, mpxjResource);\n m_eventManager.fireResourceReadEvent(mpxjResource);\n }", "public static int cudnnPoolingBackward(\n cudnnHandle handle, \n cudnnPoolingDescriptor poolingDesc, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnPoolingBackwardNative(handle, poolingDesc, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }", "public void setAmbientIntensity(float r, float g, float b, float a) {\n setVec4(\"ambient_intensity\", r, g, b, a);\n }", "private void rotatorPushRight2( int m , int offset)\n {\n double b11 = bulge;\n double b12 = diag[m+offset];\n\n computeRotator(b12,-b11);\n\n diag[m+offset] = b12*c-b11*s;\n\n if( m+offset<N-1) {\n double b22 = off[m+offset];\n off[m+offset] = b22*c;\n bulge = b22*s;\n }\n\n// SimpleMatrix Q = createQ(m,m+offset, c, s, true);\n// B=Q.mult(B);\n//\n// B.print();\n// printMatrix();\n// System.out.println(\" bulge = \"+bulge);\n// System.out.println();\n\n if( Ut != null ) {\n updateRotator(Ut,m,m+offset,c,s);\n\n// SimpleMatrix.wrap(Ut).mult(B).mult(SimpleMatrix.wrap(Vt).transpose()).print();\n// printMatrix();\n// System.out.println(\"bulge = \"+bulge);\n// System.out.println();\n }\n }", "public void delete() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "private boolean isAllNumeric(TokenStream stream) {\n List<Token> tokens = ((NattyTokenSource) stream.getTokenSource()).getTokens();\n for(Token token:tokens) {\n try {\n Integer.parseInt(token.getText());\n } catch(NumberFormatException e) {\n return false;\n }\n }\n return true;\n }", "public static base_response add(nitro_service client, clusternodegroup resource) throws Exception {\n\t\tclusternodegroup addresource = new clusternodegroup();\n\t\taddresource.name = resource.name;\n\t\taddresource.strict = resource.strict;\n\t\treturn addresource.add_resource(client);\n\t}", "public void writeNameValuePair(String name, int value) throws IOException\n {\n internalWriteNameValuePair(name, Integer.toString(value));\n }" ]
Creates a non-binary media type with the given type, subtype, and UTF-8 encoding @throws com.tngtech.jgiven.exception.JGivenWrongUsageException if any of the given arguments is {@code null}
[ "public static MediaType nonBinaryUtf8( MediaType.Type type, String subType ) {\n return new MediaType( type, subType, UTF_8 );\n }" ]
[ "public void strokeRectangle(Rectangle rect, Color color, float linewidth) {\n\t\tstrokeRectangle(rect, color, linewidth, null);\n\t}", "public void setAccordion(boolean accordion) {\n getElement().setAttribute(\"data-collapsible\", accordion ? CssName.ACCORDION : CssName.EXPANDABLE);\n reload();\n }", "static void restoreFromHistory(final InstallationManager.MutablePatchingTarget target, final String rollbackPatchId,\n final Patch.PatchType patchType, final PatchableTarget.TargetInfo history) throws PatchingException {\n if (patchType == Patch.PatchType.CUMULATIVE) {\n assert history.getCumulativePatchID().equals(rollbackPatchId);\n target.apply(rollbackPatchId, patchType);\n // Restore one off state\n final List<String> oneOffs = new ArrayList<String>(history.getPatchIDs());\n Collections.reverse(oneOffs);\n for (final String oneOff : oneOffs) {\n target.apply(oneOff, Patch.PatchType.ONE_OFF);\n }\n }\n checkState(history, history); // Just check for tests, that rollback should restore the old state\n }", "private void cleanupDestination(DownloadRequest request, boolean forceClean) {\n if (!request.isResumable() || forceClean) {\n Log.d(\"cleanupDestination() deleting \" + request.getDestinationURI().getPath());\n File destinationFile = new File(request.getDestinationURI().getPath());\n if (destinationFile.exists()) {\n destinationFile.delete();\n }\n }\n }", "public static TestSpecification generateSpecification(@Nonnull final TestDefinition testDefinition) {\n final TestSpecification testSpecification = new TestSpecification();\n // Sort buckets by value ascending\n final Map<String,Integer> buckets = Maps.newLinkedHashMap();\n final List<TestBucket> testDefinitionBuckets = Ordering.from(new Comparator<TestBucket>() {\n @Override\n public int compare(final TestBucket lhs, final TestBucket rhs) {\n return Ints.compare(lhs.getValue(), rhs.getValue());\n }\n }).immutableSortedCopy(testDefinition.getBuckets());\n int fallbackValue = -1;\n if(testDefinitionBuckets.size() > 0) {\n final TestBucket firstBucket = testDefinitionBuckets.get(0);\n fallbackValue = firstBucket.getValue(); // buckets are sorted, choose smallest value as the fallback value\n\n final PayloadSpecification payloadSpecification = new PayloadSpecification();\n if(firstBucket.getPayload() != null && !firstBucket.getPayload().equals(Payload.EMPTY_PAYLOAD)) {\n final PayloadType payloadType = PayloadType.payloadTypeForName(firstBucket.getPayload().fetchType());\n payloadSpecification.setType(payloadType.payloadTypeName);\n if (payloadType == PayloadType.MAP) {\n final Map<String, String> payloadSpecificationSchema = new HashMap<String, String>();\n for (Map.Entry<String, Object> entry : firstBucket.getPayload().getMap().entrySet()) {\n payloadSpecificationSchema.put(entry.getKey(), PayloadType.payloadTypeForValue(entry.getValue()).payloadTypeName);\n }\n payloadSpecification.setSchema(payloadSpecificationSchema);\n }\n testSpecification.setPayload(payloadSpecification);\n }\n\n for (int i = 0; i < testDefinitionBuckets.size(); i++) {\n final TestBucket bucket = testDefinitionBuckets.get(i);\n buckets.put(bucket.getName(), bucket.getValue());\n }\n }\n testSpecification.setBuckets(buckets);\n testSpecification.setDescription(testDefinition.getDescription());\n testSpecification.setFallbackValue(fallbackValue);\n return testSpecification;\n }", "public static boolean isBeanProxyable(Bean<?> bean, BeanManagerImpl manager) {\n if (bean instanceof RIBean<?>) {\n return ((RIBean<?>) bean).isProxyable();\n } else {\n return Proxies.isTypesProxyable(bean.getTypes(), manager.getServices());\n }\n }", "public static <T> T withStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={\"java.io.InputStream\",\"java.io.OutputStream\"}) Closure<T> closure) throws IOException {\n InputStream input = socket.getInputStream();\n OutputStream output = socket.getOutputStream();\n try {\n T result = closure.call(new Object[]{input, output});\n\n InputStream temp1 = input;\n input = null;\n temp1.close();\n OutputStream temp2 = output;\n output = null;\n temp2.close();\n\n return result;\n } finally {\n closeWithWarning(input);\n closeWithWarning(output);\n }\n }", "public ManagementModelNode getSelectedNode() {\n if (tree.getSelectionPath() == null) return null;\n return (ManagementModelNode)tree.getSelectionPath().getLastPathComponent();\n }", "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 }" ]
Iterates over the elements of an iterable collection of items, starting from a specified startIndex, and returns the index values of the items that match the condition specified in the closure. @param self the iteration object over which to iterate @param startIndex start matching from this index @param closure the filter to perform a match on the collection @return a list of numbers corresponding to the index values of all matched objects @since 1.5.2
[ "public static List<Number> findIndexValues(Object self, Number startIndex, Closure closure) {\n List<Number> result = new ArrayList<Number>();\n long count = 0;\n long startCount = startIndex.longValue();\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); count++) {\n Object value = iter.next();\n if (count < startCount) {\n continue;\n }\n if (bcw.call(value)) {\n result.add(count);\n }\n }\n return result;\n }" ]
[ "private void setPlaying(boolean playing) {\n PlaybackState oldState = currentSimpleState();\n if (oldState != null && oldState.playing != playing) {\n setPlaybackState(oldState.player, oldState.position, playing);\n }\n }", "public static boolean isAssignableFrom(TypeReference<?> from, TypeReference<?> to) {\n\t\tif (from == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (to.equals(from)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (to.getType() instanceof Class) {\n\t\t\treturn to.getRawType().isAssignableFrom(from.getRawType());\n\t\t} else if (to.getType() instanceof ParameterizedType) {\n\t\t\treturn isAssignableFrom(from.getType(), (ParameterizedType) to\n\t\t\t\t\t.getType(), new HashMap<String, Type>());\n\t\t} else if (to.getType() instanceof GenericArrayType) {\n\t\t\treturn to.getRawType().isAssignableFrom(from.getRawType())\n\t\t\t\t\t&& isAssignableFrom(from.getType(), (GenericArrayType) to\n\t\t\t\t\t\t\t.getType());\n\t\t} else {\n\t\t\tthrow new AssertionError(\"Unexpected Type : \" + to);\n\t\t}\n\t}", "public void copyTo(int start, int end, byte[] dest, int destPos) {\n // this.subSequence(start, end).copyTo(dest, destPos) would allocate another Bytes object\n arraycopy(start, dest, destPos, end - start);\n }", "public static base_response add(nitro_service client, ipset resource) throws Exception {\n\t\tipset addresource = new ipset();\n\t\taddresource.name = resource.name;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}", "public int scrollToItem(int position) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToItem position = %d\", position);\n scrollToPosition(position);\n return mCurrentItemIndex;\n }", "protected void parseCombineIntegerLists(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n if( t == null || t.next == null )\n return;\n\n int numFound = 0;\n\n TokenList.Token start = null;\n TokenList.Token end = null;\n\n while( t != null ) {\n if( t.getType() == Type.VARIABLE && (isVariableInteger(t) ||\n t.getVariable().getType() == VariableType.INTEGER_SEQUENCE )) {\n if( numFound == 0 ) {\n numFound = 1;\n start = end = t;\n } else {\n numFound++;\n end = t;\n }\n } else if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n numFound = 0;\n } else {\n numFound = 0;\n }\n t = t.next;\n }\n\n if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n }\n }", "public static String getChildValue(Element element, String name) {\r\n return getValue(getChild(element, name));\r\n }", "@NonNull\n @Override\n public Loader<SortedList<FtpFile>> getLoader() {\n return new AsyncTaskLoader<SortedList<FtpFile>>(getContext()) {\n @Override\n public SortedList<FtpFile> loadInBackground() {\n SortedList<FtpFile> sortedList = new SortedList<>(FtpFile.class, new SortedListAdapterCallback<FtpFile>(getDummyAdapter()) {\n @Override\n public int compare(FtpFile lhs, FtpFile rhs) {\n if (lhs.isDirectory() && !rhs.isDirectory()) {\n return -1;\n } else if (rhs.isDirectory() && !lhs.isDirectory()) {\n return 1;\n } else {\n return lhs.getName().compareToIgnoreCase(rhs.getName());\n }\n }\n\n @Override\n public boolean areContentsTheSame(FtpFile oldItem, FtpFile newItem) {\n return oldItem.getName().equals(newItem.getName());\n }\n\n @Override\n public boolean areItemsTheSame(FtpFile item1, FtpFile item2) {\n return item1.getName().equals(item2.getName());\n }\n });\n\n\n if (!ftp.isConnected()) {\n // Connect\n try {\n ftp.connect(server, port);\n\n ftp.setFileType(FTP.ASCII_FILE_TYPE);\n ftp.enterLocalPassiveMode();\n ftp.setUseEPSVwithIPv4(false);\n\n if (!(loggedIn = ftp.login(username, password))) {\n ftp.logout();\n Log.e(TAG, \"Login failed\");\n }\n } catch (IOException e) {\n if (ftp.isConnected()) {\n try {\n ftp.disconnect();\n } catch (IOException ignored) {\n }\n }\n Log.e(TAG, \"Could not connect to server.\");\n }\n }\n\n if (loggedIn) {\n try {\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n sortedList.beginBatchedUpdates();\n for (FTPFile f : ftp.listFiles(mCurrentPath.getPath())) {\n FtpFile file;\n if (f.isDirectory()) {\n file = new FtpDir(mCurrentPath, f.getName());\n } else {\n file = new FtpFile(mCurrentPath, f.getName());\n }\n if (isItemVisible(file)) {\n sortedList.add(file);\n }\n }\n sortedList.endBatchedUpdates();\n } catch (IOException e) {\n Log.e(TAG, \"IOException: \" + e.getMessage());\n }\n }\n\n return sortedList;\n }\n\n /**\n * Handles a request to start the Loader.\n */\n @Override\n protected void onStartLoading() {\n super.onStartLoading();\n\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n forceLoad();\n }\n };\n }", "@SuppressWarnings(\"unchecked\")\n protected String addPostRunDependent(Creatable<? extends Indexable> creatable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) creatable;\n return this.addPostRunDependent(dependency);\n }" ]
Processes the template for all class definitions. @param template The template @param attributes The attributes of the tag @exception XDocletException if an error occurs @doc.tag type="block"
[ "public void forAllClassDefinitions(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _model.getClasses(); it.hasNext(); )\r\n {\r\n _curClassDef = (ClassDescriptorDef)it.next();\r\n generate(template);\r\n }\r\n _curClassDef = null;\r\n\r\n LogHelper.debug(true, OjbTagsHandler.class, \"forAllClassDefinitions\", \"Processed \"+_model.getNumClasses()+\" types\");\r\n }" ]
[ "public int compareTo(WordLemmaTag wordLemmaTag) {\r\n int first = word().compareTo(wordLemmaTag.word());\r\n if (first != 0)\r\n return first;\r\n int second = lemma().compareTo(wordLemmaTag.lemma());\r\n if (second != 0)\r\n return second;\r\n else\r\n return tag().compareTo(wordLemmaTag.tag());\r\n }", "public static String join(Iterable<?> iterable, String separator) {\n if (iterable != null) {\n StringBuilder buf = new StringBuilder();\n Iterator<?> it = iterable.iterator();\n char singleChar = separator.length() == 1 ? separator.charAt(0) : 0;\n while (it.hasNext()) {\n buf.append(it.next());\n if (it.hasNext()) {\n if (singleChar != 0) {\n // More efficient\n buf.append(singleChar);\n } else {\n buf.append(separator);\n }\n }\n }\n return buf.toString();\n } else {\n return \"\";\n }\n }", "@Override\n protected void runUnsafe() throws Exception {\n Path reportDirectory = getReportDirectoryPath();\n Files.walkFileTree(reportDirectory, new DeleteVisitor());\n LOGGER.info(\"Report directory <{}> was successfully cleaned.\", reportDirectory);\n }", "private int runCommitScript() {\n\n if (m_checkout && !m_fetchAndResetBeforeImport) {\n m_logStream.println(\"Skipping script....\");\n return 0;\n }\n try {\n m_logStream.flush();\n String commandParam;\n if (m_resetRemoteHead) {\n commandParam = resetRemoteHeadScriptCommand();\n } else if (m_resetHead) {\n commandParam = resetHeadScriptCommand();\n } else if (m_checkout) {\n commandParam = checkoutScriptCommand();\n } else {\n commandParam = checkinScriptCommand();\n }\n String[] cmd = {\"bash\", \"-c\", commandParam};\n m_logStream.println(\"Calling the script as follows:\");\n m_logStream.println();\n m_logStream.println(cmd[0] + \" \" + cmd[1] + \" \" + cmd[2]);\n ProcessBuilder builder = new ProcessBuilder(cmd);\n m_logStream.close();\n m_logStream = null;\n Redirect redirect = Redirect.appendTo(new File(DEFAULT_LOGFILE_PATH));\n builder.redirectOutput(redirect);\n builder.redirectError(redirect);\n Process scriptProcess = builder.start();\n int exitCode = scriptProcess.waitFor();\n scriptProcess.getOutputStream().close();\n m_logStream = new PrintStream(new FileOutputStream(DEFAULT_LOGFILE_PATH, true));\n return exitCode;\n } catch (InterruptedException | IOException e) {\n e.printStackTrace(m_logStream);\n return -1;\n }\n\n }", "public void copyCategories(CmsObject cms, CmsResource fromResource, String toResourceSitePath) throws CmsException {\n\n List<CmsCategory> categories = readResourceCategories(cms, fromResource);\n for (CmsCategory category : categories) {\n addResourceToCategory(cms, toResourceSitePath, category);\n }\n }", "public static <T> OptionalValue<T> ofNullable(ResourceKey key, T value) {\n return new GenericOptionalValue<T>(RUNTIME_SOURCE, key, value);\n }", "private void cascadeMarkedForInsert()\r\n {\r\n // This list was used to avoid endless recursion on circular references\r\n List alreadyPrepared = new ArrayList();\r\n for(int i = 0; i < markedForInsertList.size(); i++)\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) markedForInsertList.get(i);\r\n // only if a new object was found we cascade to register the dependent objects\r\n if(mod.needsInsert())\r\n {\r\n cascadeInsertFor(mod, alreadyPrepared);\r\n alreadyPrepared.clear();\r\n }\r\n }\r\n markedForInsertList.clear();\r\n }", "public final void visit(final Visitor visitor)\n\t{\n\t\tfinal Visit visit = new Visit();\n\t\ttry\n\t\t{\n\t\t\tvisit(visitor, visit);\n\t\t}\n\t\tcatch (final StopVisitationException ignored)\n\t\t{\n\t\t}\n\t}", "public static boolean queryHasResult(Statement stmt, String sql) {\n try {\n ResultSet rs = stmt.executeQuery(sql);\n try {\n return rs.next();\n } finally {\n rs.close();\n }\n } catch (SQLException e) {\n throw new DukeException(e);\n }\n }" ]
Get a property as a object or throw exception. @param key the property name
[ "@Override\n public final PObject getObject(final String key) {\n PObject result = optObject(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }" ]
[ "public static base_response expire(nitro_service client, cacheobject resource) throws Exception {\n\t\tcacheobject expireresource = new cacheobject();\n\t\texpireresource.locator = resource.locator;\n\t\texpireresource.url = resource.url;\n\t\texpireresource.host = resource.host;\n\t\texpireresource.port = resource.port;\n\t\texpireresource.groupname = resource.groupname;\n\t\texpireresource.httpmethod = resource.httpmethod;\n\t\treturn expireresource.perform_operation(client,\"expire\");\n\t}", "public static final Rate parseRate(BigDecimal value)\n {\n Rate result = null;\n\n if (value != null)\n {\n result = new Rate(value, TimeUnit.HOURS);\n }\n\n return (result);\n }", "protected boolean executeOperation(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, TransactionalProtocolClient client, final ServerIdentity identity, final ModelNode operation, final OperationResultTransformer transformer) {\n if(client == null) {\n return false;\n }\n final OperationMessageHandler messageHandler = new DelegatingMessageHandler(context);\n final OperationAttachments operationAttachments = new DelegatingOperationAttachments(context);\n final ServerOperation serverOperation = new ServerOperation(identity, operation, messageHandler, operationAttachments, transformer);\n try {\n DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef(\"Sending %s to %s\", operation, identity);\n final Future<OperationResponse> result = client.execute(listener, serverOperation);\n recordExecutedRequest(new ExecutedServerRequest(identity, result, transformer));\n } catch (IOException e) {\n final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e);\n listener.operationPrepared(result);\n recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), transformer));\n }\n return true;\n }", "public static appfwprofile_stats[] get(nitro_service service) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tappfwprofile_stats[] response = (appfwprofile_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "private boolean applyRemoteDomainModel(final List<ModelNode> bootOperations, final HostInfo hostInfo) {\n try {\n HostControllerLogger.ROOT_LOGGER.debug(\"Applying domain level boot operations provided by master\");\n SyncModelParameters parameters =\n new SyncModelParameters(domainController, ignoredDomainResourceRegistry,\n hostControllerEnvironment, extensionRegistry, operationExecutor, true, serverProxies, remoteFileRepository, contentRepository);\n final SyncDomainModelOperationHandler handler =\n new SyncDomainModelOperationHandler(hostInfo, parameters);\n final ModelNode operation = APPLY_DOMAIN_MODEL.clone();\n operation.get(DOMAIN_MODEL).set(bootOperations);\n\n final ModelNode result = operationExecutor.execute(OperationBuilder.create(operation).build(), OperationMessageHandler.DISCARD, ModelController.OperationTransactionControl.COMMIT, handler);\n\n final String outcome = result.get(OUTCOME).asString();\n final boolean success = SUCCESS.equals(outcome);\n\n // check if anything we synced triggered reload-required or restart-required.\n // if they did we log a warning on the synced slave.\n if (result.has(RESPONSE_HEADERS)) {\n final ModelNode headers = result.get(RESPONSE_HEADERS);\n if (headers.hasDefined(OPERATION_REQUIRES_RELOAD) && headers.get(OPERATION_REQUIRES_RELOAD).asBoolean()) {\n HostControllerLogger.ROOT_LOGGER.domainModelAppliedButReloadIsRequired();\n }\n if (headers.hasDefined(OPERATION_REQUIRES_RESTART) && headers.get(OPERATION_REQUIRES_RESTART).asBoolean()) {\n HostControllerLogger.ROOT_LOGGER.domainModelAppliedButRestartIsRequired();\n }\n }\n if (!success) {\n ModelNode failureDesc = result.hasDefined(FAILURE_DESCRIPTION) ? result.get(FAILURE_DESCRIPTION) : new ModelNode();\n HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(outcome, failureDesc);\n return false;\n } else {\n return true;\n }\n } catch (Exception e) {\n HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(e);\n return false;\n }\n }", "protected void registerValueFormatter(DJGroupVariable djVariable, String variableName) {\n\t\tif ( djVariable.getValueFormatter() == null){\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tJRDesignParameter dparam = new JRDesignParameter();\n\t\tdparam.setName(variableName + \"_vf\"); //value formater suffix\n\t\tdparam.setValueClassName(DJValueFormatter.class.getName());\n\t\tlog.debug(\"Registering value formatter parameter for property \" + dparam.getName() );\n\t\ttry {\n\t\t\tgetDjd().addParameter(dparam);\n\t\t} catch (JRException e) {\n\t\t\tthrow new EntitiesRegistrationException(e.getMessage(),e);\n\t\t}\n\t\tgetDjd().getParametersWithValues().put(dparam.getName(), djVariable.getValueFormatter());\t\t\n\t\t\n\t}", "public static String getCacheDir(Context ctx) {\n return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || (!Environment.isExternalStorageRemovable() && ctx.getExternalCacheDir() != null) ?\n ctx.getExternalCacheDir().getPath() : ctx.getCacheDir().getPath();\n }", "public final void cancelOld(\n final long starttimeThreshold, final long checkTimeThreshold, final String message) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaUpdate<PrintJobStatusExtImpl> update =\n builder.createCriteriaUpdate(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = update.from(PrintJobStatusExtImpl.class);\n update.where(builder.and(\n builder.equal(root.get(\"status\"), PrintJobStatus.Status.WAITING),\n builder.or(\n builder.lessThan(root.get(\"entry\").get(\"startTime\"), starttimeThreshold),\n builder.and(builder.isNotNull(root.get(\"lastCheckTime\")),\n builder.lessThan(root.get(\"lastCheckTime\"), checkTimeThreshold))\n )\n ));\n update.set(root.get(\"status\"), PrintJobStatus.Status.CANCELLED);\n update.set(root.get(\"error\"), message);\n getSession().createQuery(update).executeUpdate();\n }", "public boolean changeState(StateVertex nextState) {\n\t\tif (nextState == null) {\n\t\t\tLOGGER.info(\"nextState given is null\");\n\t\t\treturn false;\n\t\t}\n\t\tLOGGER.debug(\"Trying to change to state: '{}' from: '{}'\", nextState.getName(),\n\t\t\t\tcurrentState.getName());\n\n\t\tif (stateFlowGraph.canGoTo(currentState, nextState)) {\n\n\t\t\tLOGGER.debug(\"Changed to state: '{}' from: '{}'\", nextState.getName(),\n\t\t\t\t\tcurrentState.getName());\n\n\t\t\tsetCurrentState(nextState);\n\n\t\t\treturn true;\n\t\t} else {\n\t\t\tLOGGER.info(\"Cannot go to state: '{}' from: '{}'\", nextState.getName(),\n\t\t\t\t\tcurrentState.getName());\n\t\t\treturn false;\n\t\t}\n\t}" ]
We have received an update that invalidates the beat grid for a player, so clear it and alert any listeners if this represents a change. This does not affect the hot cues; they will stick around until the player loads a new track that overwrites one or more of them. @param update the update which means we have no beat grid for the associated player
[ "private void clearDeck(TrackMetadataUpdate update) {\n if (hotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) {\n deliverBeatGridUpdate(update.player, null);\n }\n }" ]
[ "protected void setOffsetAndLength(long offset, int length) throws IOException {\r\n\t\tthis.offset = offset;\r\n\t\tthis.length = length;\r\n\t\tthis.position = 0;\r\n\r\n\t\tif (subStream.position() != offset) {\r\n\t\t\tsubStream.seek(offset);\r\n\t\t}\r\n\t}", "public ProducerPoolData<V> getProducerPoolData(String topic, Partition bidPid, List<V> data) {\n return new ProducerPoolData<V>(topic, bidPid, data);\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}", "private void writeTask(Task task) throws IOException\n {\n writeFields(null, task, TaskField.values());\n for (Task child : task.getChildTasks())\n {\n writeTask(child);\n }\n }", "public static EventLog getEnterpriseEvents(BoxAPIConnection api, Date after, Date before, BoxEvent.Type... types) {\n return getEnterpriseEvents(api, null, after, before, ENTERPRISE_LIMIT, types);\n }", "public static dnszone_domain_binding[] get(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\tdnszone_domain_binding response[] = (dnszone_domain_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void prepareForEnumeration() {\n if (isPreparer()) {\n for (NodeT node : nodeTable.values()) {\n // Prepare each node for traversal\n node.initialize();\n if (!this.isRootNode(node)) {\n // Mark other sub-DAGs as non-preparer\n node.setPreparer(false);\n }\n }\n initializeDependentKeys();\n initializeQueue();\n }\n }", "private String pathToProperty(String path) {\n if (path == null || !path.startsWith(\"/\")) {\n throw new IllegalArgumentException(\"Path must be prefixed with a \\\"/\\\".\");\n }\n return path.substring(1);\n }", "public static void acceptsFormat(OptionParser parser) {\n parser.accepts(OPT_FORMAT, \"format of key or entry, could be hex, json or binary\")\n .withRequiredArg()\n .describedAs(\"hex | json | binary\")\n .ofType(String.class);\n }" ]
Use this API to fetch the statistics of all ipseccounters_stats resources that are configured on netscaler.
[ "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 static void Forward(double[][] data) {\n double[][] result = new double[data.length][data[0].length];\n\n for (int m = 0; m < data.length; m++) {\n for (int n = 0; n < data[0].length; n++) {\n double sum = 0;\n for (int i = 0; i < result.length; i++) {\n for (int k = 0; k < data.length; k++) {\n sum += data[i][k] * cas(((2.0 * Math.PI) / data.length) * (i * m + k * n));\n }\n result[m][n] = (1.0 / data.length) * sum;\n }\n }\n }\n\n for (int i = 0; i < data.length; i++) {\n for (int j = 0; j < data[0].length; j++) {\n data[i][j] = result[i][j];\n }\n }\n }", "private static Date getSentDate(MimeMessage msg, Date defaultVal) {\r\n if (msg == null) {\r\n return defaultVal;\r\n }\r\n try {\r\n Date sentDate = msg.getSentDate();\r\n if (sentDate == null) {\r\n return defaultVal;\r\n } else {\r\n return sentDate;\r\n }\r\n } catch (MessagingException me) {\r\n return new Date();\r\n }\r\n }", "public static final String printDate(Date value)\n {\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }", "public Character getCharacter(int field)\n {\n Character result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = Character.valueOf(m_fields[field].charAt(0));\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "public static void acceptsZone(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_Z, OPT_ZONE), \"zone id\")\n .withRequiredArg()\n .describedAs(\"zone-id\")\n .ofType(Integer.class);\n }", "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 }", "public AsciiTable setPaddingBottomChar(Character paddingBottomChar) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingBottomChar(paddingBottomChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "@Override\n public final Optional<Boolean> tryOverrideValidation(final MatchInfo matchInfo) throws SocketException,\n UnknownHostException, MalformedURLException {\n for (AddressHostMatcher addressHostMatcher: this.matchersForHost) {\n if (addressHostMatcher.matches(matchInfo)) {\n return Optional.empty();\n }\n }\n\n return Optional.of(false);\n }", "public GVRAnimation setDuration(float start, float end)\n {\n if(start>end || start<0 || end>mDuration){\n throw new IllegalArgumentException(\"start and end values are wrong\");\n }\n animationOffset = start;\n mDuration = end-start;\n return this;\n }" ]
Send Identify Node message to the controller. @param nodeId the nodeId of the node to identify @throws SerialInterfaceException when timing out or getting an invalid response.
[ "public void identifyNode(int nodeId) throws SerialInterfaceException {\n\t\tSerialMessage newMessage = new SerialMessage(nodeId, SerialMessage.SerialMessageClass.IdentifyNode, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.IdentifyNode, SerialMessage.SerialMessagePriority.High);\n \tbyte[] newPayload = { (byte) nodeId };\n \tnewMessage.setMessagePayload(newPayload);\n \tthis.enqueue(newMessage);\n\t}" ]
[ "public String createTorqueSchema(Properties attributes) throws XDocletException\r\n {\r\n String dbName = (String)getDocletContext().getConfigParam(CONFIG_PARAM_DATABASENAME);\r\n\r\n _torqueModel = new TorqueModelDef(dbName, _model);\r\n return \"\";\r\n }", "public InetSocketAddress getMulticastSocketAddress() {\n if (multicastAddress == null) {\n throw MESSAGES.noMulticastBinding(name);\n }\n return new InetSocketAddress(multicastAddress, multicastPort);\n }", "public IPv6Address getIPv6Address(IPv6AddressSegment segs[]) {\n\t\tIPv6AddressCreator creator = getIPv6Network().getAddressCreator();\n\t\treturn creator.createAddress(IPv6AddressSection.createSection(creator, segs, this)); /* address creation */\n\t}", "private void renderThumbnail(Video video) {\n Picasso.with(getContext()).cancelRequest(thumbnail);\n Picasso.with(getContext())\n .load(video.getThumbnail())\n .placeholder(R.drawable.placeholder)\n .into(thumbnail);\n }", "public static DMatrixRMaj symmetric(int length, double min, double max, Random rand) {\n DMatrixRMaj A = new DMatrixRMaj(length,length);\n\n symmetric(A,min,max,rand);\n\n return A;\n }", "private Collection parseTreeCollection(Element collectionElement) {\n\n Collection collection = new Collection();\n parseCommonFields(collectionElement, collection);\n collection.setTitle(collectionElement.getAttribute(\"title\"));\n collection.setDescription(collectionElement.getAttribute(\"description\"));\n\n // Collections can contain either sets or collections (but not both)\n NodeList childCollectionElements = collectionElement.getElementsByTagName(\"collection\");\n for (int i = 0; i < childCollectionElements.getLength(); i++) {\n Element childCollectionElement = (Element) childCollectionElements.item(i);\n collection.addCollection(parseTreeCollection(childCollectionElement));\n }\n\n NodeList childPhotosetElements = collectionElement.getElementsByTagName(\"set\");\n for (int i = 0; i < childPhotosetElements.getLength(); i++) {\n Element childPhotosetElement = (Element) childPhotosetElements.item(i);\n collection.addPhotoset(createPhotoset(childPhotosetElement));\n }\n\n return collection;\n }", "private CmsSpellcheckingRequest parseHttpRequest(final ServletRequest req, final CmsObject cms) {\n\n if ((null != cms) && OpenCms.getRoleManager().hasRole(cms, CmsRole.ROOT_ADMIN)) {\n try {\n if (null != req.getParameter(HTTP_PARAMETER_CHECKREBUILD)) {\n if (CmsSpellcheckDictionaryIndexer.updatingIndexNecessesary(cms)) {\n\n parseAndAddDictionaries(cms);\n\n }\n }\n\n if (null != req.getParameter(HTTP_PARAMTER_REBUILD)) {\n parseAndAddDictionaries(cms);\n }\n } catch (CmsRoleViolationException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n\n final String q = req.getParameter(HTTP_PARAMETER_WORDS);\n\n if (null == q) {\n LOG.debug(\"Invalid HTTP request: No parameter \\\"\" + HTTP_PARAMETER_WORDS + \"\\\" defined. \");\n return null;\n }\n\n final StringTokenizer st = new StringTokenizer(q);\n final List<String> wordsToCheck = new ArrayList<String>();\n while (st.hasMoreTokens()) {\n final String word = st.nextToken();\n wordsToCheck.add(word);\n\n if (Character.isUpperCase(word.codePointAt(0))) {\n wordsToCheck.add(word.toLowerCase());\n }\n }\n\n final String[] w = wordsToCheck.toArray(new String[wordsToCheck.size()]);\n final String dict = req.getParameter(HTTP_PARAMETER_LANG) == null\n ? LANG_DEFAULT\n : req.getParameter(HTTP_PARAMETER_LANG);\n\n return new CmsSpellcheckingRequest(w, dict);\n }", "@Override\n public double get( int row , int col ) {\n if( col < 0 || col >= numCols || row < 0 || row >= numRows ) {\n throw new IllegalArgumentException(\"Specified element is out of bounds: \"+row+\" \"+col);\n }\n\n return data[ row * numCols + col ];\n }", "@Override public ProjectFile read(String accessDatabaseFileName) throws MPXJException\n {\n try\n {\n Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\");\n String url = \"jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb);DBQ=\" + accessDatabaseFileName;\n m_connection = DriverManager.getConnection(url);\n m_projectID = Integer.valueOf(1);\n return (read());\n }\n\n catch (ClassNotFoundException ex)\n {\n throw new MPXJException(\"Failed to load JDBC driver\", ex);\n }\n\n catch (SQLException ex)\n {\n throw new MPXJException(\"Failed to create connection\", ex);\n }\n\n finally\n {\n if (m_connection != null)\n {\n try\n {\n m_connection.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore exceptions when closing connection\n }\n }\n }\n }" ]
Add the deployment scanner service to a batch. @param context context for the operation that is adding this service @param resourceAddress the address of the resource that manages the service @param relativeTo the relative to @param path the path @param scanInterval the scan interval @param unit the unit of {@code scanInterval} @param autoDeployZip whether zipped content should be auto-deployed @param autoDeployExploded whether exploded content should be auto-deployed @param autoDeployXml whether xml content should be auto-deployed @param scanEnabled scan enabled @param deploymentTimeout the deployment timeout @param rollbackOnRuntimeFailure rollback on runtime failures @param bootTimeService the deployment scanner used in the boot time scan @param scheduledExecutorService executor to use for asynchronous tasks @return the controller for the deployment scanner service
[ "public static ServiceController<DeploymentScanner> addService(final OperationContext context, final PathAddress resourceAddress, final String relativeTo, final String path,\n final int scanInterval, TimeUnit unit, final boolean autoDeployZip,\n final boolean autoDeployExploded, final boolean autoDeployXml, final boolean scanEnabled, final long deploymentTimeout, boolean rollbackOnRuntimeFailure,\n final FileSystemDeploymentService bootTimeService, final ScheduledExecutorService scheduledExecutorService) {\n final DeploymentScannerService service = new DeploymentScannerService(resourceAddress, relativeTo, path, scanInterval, unit, autoDeployZip,\n autoDeployExploded, autoDeployXml, scanEnabled, deploymentTimeout, rollbackOnRuntimeFailure, bootTimeService);\n final ServiceName serviceName = getServiceName(resourceAddress.getLastElement().getValue());\n service.scheduledExecutorValue.inject(scheduledExecutorService);\n final ServiceBuilder<DeploymentScanner> sb = context.getServiceTarget().addService(serviceName, service);\n sb.addDependency(context.getCapabilityServiceName(PATH_MANAGER_CAPABILITY, PathManager.class), PathManager.class, service.pathManagerValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.notification-handler-registry\", null),\n NotificationHandlerRegistry.class, service.notificationRegistryValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.model-controller-client-factory\", null),\n ModelControllerClientFactory.class, service.clientFactoryValue);\n sb.requires(org.jboss.as.server.deployment.Services.JBOSS_DEPLOYMENT_CHAINS);\n sb.addDependency(ControlledProcessStateService.SERVICE_NAME, ControlledProcessStateService.class, service.controlledProcessStateServiceValue);\n return sb.install();\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 RgbaColor fromHsl(float H, float S, float L) {\n\n // convert to [0-1]\n H /= 360f;\n S /= 100f;\n L /= 100f;\n\n float R, G, B;\n\n if (S == 0) {\n // grey\n R = G = B = L;\n }\n else {\n float m2 = L <= 0.5 ? L * (S + 1f) : L + S - L * S;\n float m1 = 2f * L - m2;\n R = hue2rgb(m1, m2, H + 1 / 3f);\n G = hue2rgb(m1, m2, H);\n B = hue2rgb(m1, m2, H - 1 / 3f);\n }\n\n // convert [0-1] to [0-255]\n int r = Math.round(R * 255f);\n int g = Math.round(G * 255f);\n int b = Math.round(B * 255f);\n\n return new RgbaColor(r, g, b, 1);\n }", "public static int[] randomSubset(int k, int n) {\n assert(0 < k && k <= n);\n Random r = new Random();\n int t = 0, m = 0;\n int[] result = new int[k];\n\n while (m < k) {\n double u = r.nextDouble();\n if ( (n - t) * u < k - m ) {\n result[m] = t;\n m++;\n }\n t++;\n }\n return result;\n }", "public void forObjectCache(String template, Properties attributes) throws XDocletException\r\n {\r\n _curObjectCacheDef = _curClassDef.getObjectCache();\r\n if (_curObjectCacheDef != null)\r\n {\r\n generate(template);\r\n _curObjectCacheDef = null;\r\n }\r\n }", "public static <ResultT> PollingState<ResultT> createFromPollingState(PollingState<?> other, ResultT result) {\n PollingState<ResultT> pollingState = new PollingState<>();\n pollingState.resource = result;\n pollingState.initialHttpMethod = other.initialHttpMethod();\n pollingState.status = other.status();\n pollingState.statusCode = other.statusCode();\n pollingState.azureAsyncOperationHeaderLink = other.azureAsyncOperationHeaderLink();\n pollingState.locationHeaderLink = other.locationHeaderLink();\n pollingState.putOrPatchResourceUri = other.putOrPatchResourceUri();\n pollingState.defaultRetryTimeout = other.defaultRetryTimeout;\n pollingState.retryTimeout = other.retryTimeout;\n pollingState.loggingContext = other.loggingContext;\n pollingState.finalStateVia = other.finalStateVia;\n return pollingState;\n }", "public void startDockerMachine(String cliPathExec, String machineName) {\n commandLineExecutor.execCommand(createDockerMachineCommand(cliPathExec), \"start\", machineName);\n this.manuallyStarted = true;\n }", "private List<String> getCommandLines(File file) {\n List<String> lines = new ArrayList<>();\n try (BufferedReader reader = new BufferedReader(new FileReader(file))) {\n String line = reader.readLine();\n while (line != null) {\n lines.add(line);\n line = reader.readLine();\n }\n } catch (Throwable e) {\n throw new IllegalStateException(\"Failed to process file \" + file.getAbsolutePath(), e);\n }\n return lines;\n }", "public static appfwprofile_cookieconsistency_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_cookieconsistency_binding obj = new appfwprofile_cookieconsistency_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_cookieconsistency_binding response[] = (appfwprofile_cookieconsistency_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "protected void validate(final boolean isDomain) throws MojoDeploymentException {\n final boolean hasServerGroups = hasServerGroups();\n if (isDomain) {\n if (!hasServerGroups) {\n throw new MojoDeploymentException(\n \"Server is running in domain mode, but no server groups have been defined.\");\n }\n } else if (hasServerGroups) {\n throw new MojoDeploymentException(\"Server is running in standalone mode, but server groups have been defined.\");\n }\n }" ]
2-D Forward Discrete Hartley Transform. @param data Data.
[ "public static void Forward(double[][] data) {\n double[][] result = new double[data.length][data[0].length];\n\n for (int m = 0; m < data.length; m++) {\n for (int n = 0; n < data[0].length; n++) {\n double sum = 0;\n for (int i = 0; i < result.length; i++) {\n for (int k = 0; k < data.length; k++) {\n sum += data[i][k] * cas(((2.0 * Math.PI) / data.length) * (i * m + k * n));\n }\n result[m][n] = (1.0 / data.length) * sum;\n }\n }\n }\n\n for (int i = 0; i < data.length; i++) {\n for (int j = 0; j < data[0].length; j++) {\n data[i][j] = result[i][j];\n }\n }\n }" ]
[ "public static base_response update(nitro_service client, csparameter resource) throws Exception {\n\t\tcsparameter updateresource = new csparameter();\n\t\tupdateresource.stateupdate = resource.stateupdate;\n\t\treturn updateresource.update_resource(client);\n\t}", "public void seekToHolidayYear(String holidayString, String yearString) {\n Holiday holiday = Holiday.valueOf(holidayString);\n assert(holiday != null);\n \n seekToIcsEventYear(HOLIDAY_ICS_FILE, yearString, holiday.getSummary());\n }", "public Collection<Integer> getNumericCodes() {\n Collection<Integer> result = get(KEY_QUERY_NUMERIC_CODES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "public static boolean decomposeQR_block_col( final int blockLength ,\n final DSubmatrixD1 Y ,\n final double gamma[] )\n {\n int width = Y.col1-Y.col0;\n int height = Y.row1-Y.row0;\n int min = Math.min(width,height);\n for( int i = 0; i < min; i++ ) {\n // compute the householder vector\n if (!computeHouseHolderCol(blockLength, Y, gamma, i))\n return false;\n\n // apply to rest of the columns in the block\n rank1UpdateMultR_Col(blockLength,Y,i,gamma[Y.col0+i]);\n }\n\n return true;\n }", "protected void setColumnsFinalWidth() {\n log.debug(\"Setting columns final width.\");\n float factor;\n int printableArea = report.getOptions().getColumnWidth();\n\n //Create a list with only the visible columns.\n List visibleColums = getVisibleColumns();\n\n\n if (report.getOptions().isUseFullPageWidth()) {\n int columnsWidth = 0;\n int notRezisableWidth = 0;\n\n //Store in a variable the total with of all visible columns\n for (Object visibleColum : visibleColums) {\n AbstractColumn col = (AbstractColumn) visibleColum;\n columnsWidth += col.getWidth();\n if (col.isFixedWidth())\n notRezisableWidth += col.getWidth();\n }\n\n\n factor = (float) (printableArea - notRezisableWidth) / (float) (columnsWidth - notRezisableWidth);\n\n log.debug(\"printableArea = \" + printableArea\n + \", columnsWidth = \" + columnsWidth\n + \", columnsWidth = \" + columnsWidth\n + \", notRezisableWidth = \" + notRezisableWidth\n + \", factor = \" + factor);\n\n int acumulated = 0;\n int colFinalWidth;\n\n //Select the non-resizable columns\n Collection resizableColumns = CollectionUtils.select(visibleColums, new Predicate() {\n public boolean evaluate(Object arg0) {\n return !((AbstractColumn) arg0).isFixedWidth();\n }\n\n });\n\n //Finally, set the new width to the resizable columns\n for (Iterator iter = resizableColumns.iterator(); iter.hasNext(); ) {\n AbstractColumn col = (AbstractColumn) iter.next();\n\n if (!iter.hasNext()) {\n col.setWidth(printableArea - notRezisableWidth - acumulated);\n } else {\n colFinalWidth = (new Float(col.getWidth() * factor)).intValue();\n acumulated += colFinalWidth;\n col.setWidth(colFinalWidth);\n }\n }\n }\n\n // If the columns width changed, the X position must be setted again.\n int posx = 0;\n for (Object visibleColum : visibleColums) {\n AbstractColumn col = (AbstractColumn) visibleColum;\n col.setPosX(posx);\n posx += col.getWidth();\n }\n }", "public static List<Representation> parseRepresentations(JsonObject jsonObject) {\n List<Representation> representations = new ArrayList<Representation>();\n for (JsonValue representationJson : jsonObject.get(\"entries\").asArray()) {\n Representation representation = new Representation(representationJson.asObject());\n representations.add(representation);\n }\n return representations;\n }", "@SuppressWarnings(\"rawtypes\")\n\tprivate MailInboundChannelAdapterSpec getImapFlowBuilder(URLName urlName) {\n\t\treturn Mail.imapInboundAdapter(urlName.toString())\n\t\t\t\t.shouldMarkMessagesAsRead(this.properties.isMarkAsRead());\n\t}", "private FieldType getActivityIDField(Map<FieldType, String> map)\n {\n FieldType result = null;\n for (Map.Entry<FieldType, String> entry : map.entrySet())\n {\n if (entry.getValue().equals(\"task_code\"))\n {\n result = entry.getKey();\n break;\n }\n }\n return result;\n }", "public void process(String driverClass, String connectionString, String projectID, String outputFile) throws Exception\n {\n System.out.println(\"Reading Primavera database started.\");\n\n Class.forName(driverClass);\n Properties props = new Properties();\n\n //\n // This is not a very robust way to detect that we're working with SQLlite...\n // If you are trying to grab data from\n // a standalone P6 using SQLite, the SQLite JDBC driver needs this property\n // in order to correctly parse timestamps.\n //\n if (driverClass.equals(\"org.sqlite.JDBC\"))\n {\n props.setProperty(\"date_string_format\", \"yyyy-MM-dd HH:mm:ss\");\n }\n\n Connection c = DriverManager.getConnection(connectionString, props);\n PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader();\n reader.setConnection(c);\n\n processProject(reader, Integer.parseInt(projectID), outputFile);\n }" ]
Should the URI be cached? @param requestUri request URI @return true when caching is needed
[ "public boolean shouldCache(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkContains(uri, cacheIdentifiers) || checkSuffixes(uri, cacheSuffixes);\n\t}" ]
[ "@SuppressWarnings( { \"unchecked\" })\r\n public static <K1, K2> TwoDimensionalCounter<K2, K1> reverseIndexOrder(TwoDimensionalCounter<K1, K2> cc) {\r\n // they typing on the outerMF is violated a bit, but it'll work....\r\n TwoDimensionalCounter<K2, K1> result = new TwoDimensionalCounter<K2, K1>((MapFactory) cc.outerMF,\r\n (MapFactory) cc.innerMF);\r\n\r\n for (K1 key1 : cc.firstKeySet()) {\r\n ClassicCounter<K2> c = cc.getCounter(key1);\r\n for (K2 key2 : c.keySet()) {\r\n double count = c.getCount(key2);\r\n result.setCount(key2, key1, count);\r\n }\r\n }\r\n return result;\r\n }", "private void addCalendarDay(MpxjTreeNode parentNode, ProjectCalendar calendar, final Day day)\n {\n MpxjTreeNode dayNode = new MpxjTreeNode(day)\n {\n @Override public String toString()\n {\n return day.name();\n }\n };\n parentNode.add(dayNode);\n addHours(dayNode, calendar.getHours(day));\n }", "public static appfwprofile_stats[] get(nitro_service service) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tappfwprofile_stats[] response = (appfwprofile_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public static void logBeforeExit(ExitLogger logger) {\n try {\n if (logged.compareAndSet(false, true)) {\n logger.logExit();\n }\n } catch (Throwable ignored){\n // ignored\n }\n }", "@RequestMapping(value = \"/profiles\", method = RequestMethod.GET)\n public String list(Model model) {\n Profile profiles = new Profile();\n model.addAttribute(\"addNewProfile\", profiles);\n model.addAttribute(\"version\", Constants.VERSION);\n logger.info(\"Loading initial page\");\n\n return \"profiles\";\n }", "private void init(final List<DbLicense> licenses) {\n licensesRegexp.clear();\n\n for (final DbLicense license : licenses) {\n if (license.getRegexp() == null ||\n license.getRegexp().isEmpty()) {\n licensesRegexp.put(license.getName(), license);\n } else {\n licensesRegexp.put(license.getRegexp(), license);\n }\n }\n }", "private int tryAcquireExclusiveTransaction(@NotNull final Thread thread, final int timeout) {\n long nanos = TimeUnit.MILLISECONDS.toNanos(timeout);\n try (CriticalSection ignored = criticalSection.enter()) {\n if (getThreadPermits(thread) > 0) {\n throw new ExodusException(\"Exclusive transaction can't be nested\");\n }\n final Condition condition = criticalSection.newCondition();\n final long currentOrder = acquireOrder++;\n regularQueue.put(currentOrder, condition);\n while (acquiredPermits > 0 || regularQueue.firstKey() != currentOrder) {\n try {\n nanos = condition.awaitNanos(nanos);\n if (nanos < 0) {\n break;\n }\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n break;\n }\n }\n if (acquiredPermits == 0 && regularQueue.firstKey() == currentOrder) {\n regularQueue.pollFirstEntry();\n acquiredPermits = availablePermits;\n threadPermits.put(thread, availablePermits);\n return availablePermits;\n }\n regularQueue.remove(currentOrder);\n notifyNextWaiters();\n }\n return 0;\n }", "public void warn(Throwable throwable, String msg, Object[] argArray) {\n\t\tlogIfEnabled(Level.WARNING, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);\n\t}", "public static List<String> splitAsList(String text, String delimiter) {\n List<String> answer = new ArrayList<String>();\n if (text != null && text.length() > 0) {\n answer.addAll(Arrays.asList(text.split(delimiter)));\n }\n return answer;\n }" ]
generate a prepared SELECT-Statement for the Class described by cld @param cld the ClassDescriptor
[ "public SelectStatement getPreparedSelectByPkStatement(ClassDescriptor cld)\r\n {\r\n SelectStatement sql;\r\n SqlForClass sfc = getSqlForClass(cld);\r\n sql = sfc.getSelectByPKSql();\r\n if(sql == null)\r\n {\r\n sql = new SqlSelectByPkStatement(m_platform, cld, logger);\r\n\r\n // set the sql string\r\n sfc.setSelectByPKSql(sql);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n }\r\n return sql;\r\n }" ]
[ "public List<Throwable> getCauses(Throwable t)\n {\n List<Throwable> causes = new LinkedList<Throwable>();\n Throwable next = t;\n while (next.getCause() != null)\n {\n next = next.getCause();\n causes.add(next);\n }\n return causes;\n }", "@Override\n\tpublic boolean isSinglePrefixBlock() {\n\t\tInteger networkPrefixLength = getNetworkPrefixLength();\n\t\tif(networkPrefixLength == null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn containsSinglePrefixBlock(networkPrefixLength);\n\t}", "public static <T extends Range> T findRange(List<T> ranges, long value, int arraySize) {\n if (ranges.size() < 1) return null;\n T first = ranges.get(0);\n T last = ranges.get(arraySize - 1);\n // check out of bounds\n if (value < first.start() || value > last.start() + last.size()) {\n throw new OffsetOutOfRangeException(format(\"offset %s is out of range (%s, %s)\",//\n value,first.start(),last.start()+last.size()));\n }\n\n // check at the end\n if (value == last.start() + last.size()) return null;\n\n int low = 0;\n int high = arraySize - 1;\n while (low <= high) {\n int mid = (high + low) / 2;\n T found = ranges.get(mid);\n if (found.contains(value)) {\n return found;\n } else if (value < found.start()) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n }\n return null;\n }", "public Collection<Contact> getList() throws FlickrException {\r\n \t ContactList<Contact> contacts = new ContactList<Contact>();\r\n \r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element contactsElement = response.getPayload();\r\n contacts.setPage(contactsElement.getAttribute(\"page\"));\r\n contacts.setPages(contactsElement.getAttribute(\"pages\"));\r\n contacts.setPerPage(contactsElement.getAttribute(\"perpage\"));\r\n contacts.setTotal(contactsElement.getAttribute(\"total\"));\r\n NodeList contactNodes = contactsElement.getElementsByTagName(\"contact\");\r\n for (int i = 0; i < contactNodes.getLength(); i++) {\r\n Element contactElement = (Element) contactNodes.item(i);\r\n Contact contact = new Contact();\r\n contact.setId(contactElement.getAttribute(\"nsid\"));\r\n contact.setUsername(contactElement.getAttribute(\"username\"));\r\n contact.setRealName(contactElement.getAttribute(\"realname\"));\r\n contact.setFriend(\"1\".equals(contactElement.getAttribute(\"friend\")));\r\n contact.setFamily(\"1\".equals(contactElement.getAttribute(\"family\")));\r\n contact.setIgnored(\"1\".equals(contactElement.getAttribute(\"ignored\")));\r\n String lPathAlias = contactElement.getAttribute(\"path_alias\");\r\n contact.setPathAlias(lPathAlias == null || \"\".equals(lPathAlias) ? null : lPathAlias);\r\n contact.setOnline(OnlineStatus.fromType(contactElement.getAttribute(\"online\")));\r\n contact.setIconFarm(contactElement.getAttribute(\"iconfarm\"));\r\n contact.setIconServer(contactElement.getAttribute(\"iconserver\"));\r\n if (contact.getOnline() == OnlineStatus.AWAY) {\r\n contactElement.normalize();\r\n contact.setAwayMessage(XMLUtilities.getValue(contactElement));\r\n }\r\n contacts.add(contact);\r\n }\r\n return contacts;\r\n }", "public Object getBean(String name) {\n\t\tBean bean = beans.get(name);\n\t\tif (null == bean) {\n\t\t\treturn null;\n\t\t}\n\t\treturn bean.object;\n\t}", "public void putAll(Map<KEY, VALUE> mapDataToPut) {\n int targetSize = maxSize - mapDataToPut.size();\n if (maxSize > 0 && values.size() > targetSize) {\n evictToTargetSize(targetSize);\n }\n Set<Entry<KEY, VALUE>> entries = mapDataToPut.entrySet();\n for (Entry<KEY, VALUE> entry : entries) {\n put(entry.getKey(), entry.getValue());\n }\n }", "public void process(String name) throws Exception\n {\n ProjectFile file = new UniversalProjectReader().read(name);\n for (Task task : file.getTasks())\n {\n if (!task.getSummary())\n {\n System.out.print(task.getWBS());\n System.out.print(\"\\t\");\n System.out.print(task.getName());\n System.out.print(\"\\t\");\n System.out.print(format(task.getStart()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getActualStart()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getFinish()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getActualFinish()));\n System.out.println();\n }\n }\n }", "private static void processResourceFilter(ProjectFile project, Filter filter)\n {\n for (Resource resource : project.getResources())\n {\n if (filter.evaluate(resource, null))\n {\n System.out.println(resource.getID() + \",\" + resource.getUniqueID() + \",\" + resource.getName());\n }\n }\n }", "public void setBackgroundColor(int color) {\n setBackgroundColorR(Colors.byteToGl(Color.red(color)));\n setBackgroundColorG(Colors.byteToGl(Color.green(color)));\n setBackgroundColorB(Colors.byteToGl(Color.blue(color)));\n setBackgroundColorA(Colors.byteToGl(Color.alpha(color)));\n }" ]
Gets the first group of a regex @param pattern Pattern @param str String to find @return the matching group
[ "public static String regexFindFirst(String pattern, String str) {\n return regexFindFirst(Pattern.compile(pattern), str, 1);\n }" ]
[ "private void setBandFinalHeight(JRDesignBand band, int currHeigth, boolean fitToContent) {\n if (band != null) {\n int finalHeight = LayoutUtils.findVerticalOffset(band);\n //noinspection StatementWithEmptyBody\n if (finalHeight < currHeigth && !fitToContent) {\n //nothing\n } else {\n band.setHeight(finalHeight);\n }\n }\n\n }", "private void checkTexRange(AiTextureType type, int index) {\n if (index < 0 || index > m_numTextures.get(type)) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Size: \" +\n m_numTextures.get(type));\n }\n }", "public static java.sql.Time toTime(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.sql.Time) {\n return (java.sql.Time) value;\n }\n if (value instanceof String) {\n if (\"\".equals((String) value)) {\n return null;\n }\n return new java.sql.Time(IN_TIME_FORMAT.parse((String) value).getTime());\n }\n\n return new java.sql.Time(IN_TIME_FORMAT.parse(value.toString()).getTime());\n }", "public void writeTo(IIMWriter writer) throws IOException {\r\n\t\tfinal boolean doLog = log != null;\r\n\t\tfor (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) {\r\n\t\t\tDataSet ds = i.next();\r\n\t\t\twriter.write(ds);\r\n\t\t\tif (doLog) {\r\n\t\t\t\tlog.debug(\"Wrote data set \" + ds);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "private void showGlobalContextActionBar() {\n ActionBar actionBar = getActionBar();\n actionBar.setDisplayShowTitleEnabled(true);\n actionBar.setTitle(R.string.app_name);\n }", "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 }", "@Override protected View inflate(LayoutInflater inflater, ViewGroup parent) {\n View inflatedView = inflater.inflate(R.layout.video_renderer, parent, false);\n /*\n * You don't have to use ButterKnife library to implement the mapping between your layout\n * and your widgets you can implement setUpView and hookListener methods declared in\n * Renderer<T> class.\n */\n ButterKnife.bind(this, inflatedView);\n return inflatedView;\n }", "public void trace(String msg) {\n\t\tlogIfEnabled(Level.TRACE, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);\n\t}", "public Object remove(Object key)\r\n {\r\n if (key == null) return null;\r\n purge();\r\n int hash = hashCode(key);\r\n int index = indexFor(hash);\r\n Entry previous = null;\r\n Entry entry = table[index];\r\n while (entry != null)\r\n {\r\n if ((hash == entry.hash) && equals(key, entry.getKey()))\r\n {\r\n if (previous == null)\r\n table[index] = entry.next;\r\n else\r\n previous.next = entry.next;\r\n this.size--;\r\n modCount++;\r\n return entry.getValue();\r\n }\r\n previous = entry;\r\n entry = entry.next;\r\n }\r\n return null;\r\n }" ]
Determine the common ancestor of the given classes, if any. @param clazz1 the class to introspect @param clazz2 the other class to introspect @return the common ancestor (i.e. common superclass, one interface extending the other), or {@code null} if none found. If any of the given classes is {@code null}, the other class will be returned. @since 2.0
[ "public static Class<?> determineCommonAncestor(Class<?> clazz1, Class<?> clazz2) {\n\t\tif (clazz1 == null) {\n\t\t\treturn clazz2;\n\t\t}\n\t\tif (clazz2 == null) {\n\t\t\treturn clazz1;\n\t\t}\n\t\tif (clazz1.isAssignableFrom(clazz2)) {\n\t\t\treturn clazz1;\n\t\t}\n\t\tif (clazz2.isAssignableFrom(clazz1)) {\n\t\t\treturn clazz2;\n\t\t}\n\t\tClass<?> ancestor = clazz1;\n\t\tdo {\n\t\t\tancestor = ancestor.getSuperclass();\n\t\t\tif (ancestor == null || Object.class.equals(ancestor)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\twhile (!ancestor.isAssignableFrom(clazz2));\n\t\treturn ancestor;\n\t}" ]
[ "private void setFileNotWorldReadablePermissions(File file) {\n file.setReadable(false, false);\n file.setWritable(false, false);\n file.setExecutable(false, false);\n file.setReadable(true, true);\n file.setWritable(true, true);\n }", "public JsonObject getJsonObject() {\n\n JsonObject obj = new JsonObject();\n obj.add(\"field\", this.field);\n\n obj.add(\"value\", this.value);\n\n return obj;\n }", "public MethodKey createCopy() {\n int size = getParameterCount();\n Class[] paramTypes = new Class[size];\n for (int i = 0; i < size; i++) {\n paramTypes[i] = getParameterType(i);\n }\n return new DefaultMethodKey(sender, name, paramTypes, isCallToSuper);\n }", "protected String format(String key, String defaultPattern, Object... args) {\n String escape = escape(defaultPattern);\n String s = lookupPattern(key, escape);\n Object[] objects = escapeAll(args);\n return MessageFormat.format(s, objects);\n }", "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 }", "private String formatDateTimeNull(Date value)\n {\n return (value == null ? m_formats.getNullText() : m_formats.getDateTimeFormat().format(value));\n }", "private static Object checkComponentType(Object array, Class<?> expectedComponentType) {\n\t\tClass<?> actualComponentType = array.getClass().getComponentType();\n\t\tif (!expectedComponentType.isAssignableFrom(actualComponentType)) {\n\t\t\tthrow new ArrayStoreException(\n\t\t\t\t\tString.format(\"The expected component type %s is not assignable from the actual type %s\",\n\t\t\t\t\t\t\texpectedComponentType.getCanonicalName(), actualComponentType.getCanonicalName()));\n\t\t}\n\t\treturn array;\n\t}", "public static JqmEngineOperations startEngine(String name, JqmEngineHandler handler)\n {\n JqmEngine e = new JqmEngine();\n e.start(name, handler);\n return e;\n }", "private Charset getCharset()\n {\n Charset result = m_charset;\n if (result == null)\n {\n // We default to CP1252 as this seems to be the most common encoding\n result = m_encoding == null ? CharsetHelper.CP1252 : Charset.forName(m_encoding);\n }\n return result;\n }" ]
Prepares Artifactory server either from serverID or from ArtifactoryServer. @param artifactoryServerID @param pipelineServer @return
[ "public static org.jfrog.hudson.ArtifactoryServer prepareArtifactoryServer(String artifactoryServerID,\n ArtifactoryServer pipelineServer) {\n\n if (artifactoryServerID == null && pipelineServer == null) {\n return null;\n }\n if (artifactoryServerID != null && pipelineServer != null) {\n return null;\n }\n if (pipelineServer != null) {\n CredentialsConfig credentials = pipelineServer.createCredentialsConfig();\n\n return new org.jfrog.hudson.ArtifactoryServer(null, pipelineServer.getUrl(), credentials,\n credentials, pipelineServer.getConnection().getTimeout(), pipelineServer.isBypassProxy(), pipelineServer.getConnection().getRetry(), pipelineServer.getDeploymentThreads());\n }\n org.jfrog.hudson.ArtifactoryServer server = RepositoriesUtils.getArtifactoryServer(artifactoryServerID, RepositoriesUtils.getArtifactoryServers());\n if (server == null) {\n return null;\n }\n return server;\n }" ]
[ "private int getTaskCode(String field) throws MPXJException\n {\n Integer result = m_taskNumbers.get(field.trim());\n\n if (result == null)\n {\n throw new MPXJException(MPXJException.INVALID_TASK_FIELD_NAME + \" \" + field);\n }\n\n return (result.intValue());\n }", "public static Face createTriangle(Vertex v0, Vertex v1, Vertex v2, double minArea) {\n Face face = new Face();\n HalfEdge he0 = new HalfEdge(v0, face);\n HalfEdge he1 = new HalfEdge(v1, face);\n HalfEdge he2 = new HalfEdge(v2, face);\n\n he0.prev = he2;\n he0.next = he1;\n he1.prev = he0;\n he1.next = he2;\n he2.prev = he1;\n he2.next = he0;\n\n face.he0 = he0;\n\n // compute the normal and offset\n face.computeNormalAndCentroid(minArea);\n return face;\n }", "public static auditsyslogpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_lbvserver_binding obj = new auditsyslogpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_lbvserver_binding response[] = (auditsyslogpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static List<StoreDefinition> validateRebalanceStore(List<StoreDefinition> storeDefList) {\n List<StoreDefinition> returnList = new ArrayList<StoreDefinition>(storeDefList.size());\n\n for(StoreDefinition def: storeDefList) {\n if(!def.isView() && !canRebalanceList.contains(def.getType())) {\n throw new VoldemortException(\"Rebalance does not support rebalancing of stores of type \"\n + def.getType() + \" - \" + def.getName());\n } else if(!def.isView()) {\n returnList.add(def);\n } else {\n logger.debug(\"Ignoring view \" + def.getName() + \" for rebalancing\");\n }\n }\n return returnList;\n }", "public boolean isHomeKeyPresent() {\n final GVRApplication application = mApplication.get();\n if (null != application) {\n final String model = getHmtModel();\n if (null != model && model.contains(\"R323\")) {\n return true;\n }\n }\n return false;\n }", "public LogStreamResponse getLogs(String appName, Boolean tail) {\n return connection.execute(new Log(appName, tail), apiKey);\n }", "public final int toCodePoints(char[] src, int srcOff, int srcLen, int[] dest, int destOff) {\n if (srcLen < 0) {\n throw new IllegalArgumentException(\"srcLen must be >= 0\");\n }\n int codePointCount = 0;\n for (int i = 0; i < srcLen; ) {\n final int cp = codePointAt(src, srcOff + i, srcOff + srcLen);\n final int charCount = Character.charCount(cp);\n dest[destOff + codePointCount++] = cp;\n i += charCount;\n }\n return codePointCount;\n }", "public static AnalysisResult fakeSuccess() {\n return new AnalysisResult(null, new Extensions(Collections.emptyMap(), Collections.emptyMap(),\n Collections.emptyMap(), Collections.emptyMap()));\n }", "public ProjectCalendar getDefaultCalendar()\n {\n String calendarName = m_properties.getDefaultCalendarName();\n ProjectCalendar calendar = getCalendarByName(calendarName);\n if (calendar == null)\n {\n if (m_calendars.isEmpty())\n {\n calendar = addDefaultBaseCalendar();\n }\n else\n {\n calendar = m_calendars.get(0);\n }\n }\n return calendar;\n }" ]
Rename a key for all languages. @param oldKey the key to rename @param newKey the new key name @return <code>true</code> if renaming was successful, <code>false</code> otherwise.
[ "private boolean renameKeyForAllLanguages(String oldKey, String newKey) {\n\n try {\n loadAllRemainingLocalizations();\n lockAllLocalizations(oldKey);\n if (hasDescriptor()) {\n lockDescriptor();\n }\n } catch (CmsException | IOException e) {\n LOG.error(e.getLocalizedMessage(), e);\n return false;\n }\n for (Entry<Locale, SortedProperties> entry : m_localizations.entrySet()) {\n SortedProperties localization = entry.getValue();\n if (localization.containsKey(oldKey)) {\n String value = localization.getProperty(oldKey);\n localization.remove(oldKey);\n localization.put(newKey, value);\n m_changedTranslations.add(entry.getKey());\n }\n }\n if (hasDescriptor()) {\n CmsXmlContentValueSequence messages = m_descContent.getValueSequence(\n Descriptor.N_MESSAGE,\n Descriptor.LOCALE);\n for (int i = 0; i < messages.getElementCount(); i++) {\n\n String prefix = messages.getValue(i).getPath() + \"/\";\n String key = m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).getStringValue(m_cms);\n if (key == oldKey) {\n m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).setStringValue(m_cms, newKey);\n break;\n }\n }\n m_descriptorHasChanges = true;\n }\n m_keyset.renameKey(oldKey, newKey);\n return true;\n }" ]
[ "public List<DbModule> getAncestors(final String gavc, final FiltersHolder filters) {\n final DbArtifact dbArtifact = getArtifact(gavc);\n return repositoryHandler.getAncestors(dbArtifact, filters);\n }", "public void setWeeklyDaysFromBitmap(Integer days, int[] masks)\n {\n if (days != null)\n {\n int value = days.intValue();\n for (Day day : Day.values())\n {\n setWeeklyDay(day, ((value & masks[day.getValue()]) != 0));\n }\n }\n }", "private static void dumpTree(PrintWriter pw, DirectoryEntry dir, String prefix, boolean showData, boolean hex, String indent) throws Exception\n {\n long byteCount;\n\n for (Iterator<Entry> iter = dir.getEntries(); iter.hasNext();)\n {\n Entry entry = iter.next();\n if (entry instanceof DirectoryEntry)\n {\n String childIndent = indent;\n if (childIndent != null)\n {\n childIndent += \" \";\n }\n\n String childPrefix = prefix + \"[\" + entry.getName() + \"].\";\n pw.println(\"start dir: \" + prefix + entry.getName());\n dumpTree(pw, (DirectoryEntry) entry, childPrefix, showData, hex, childIndent);\n pw.println(\"end dir: \" + prefix + entry.getName());\n }\n else\n if (entry instanceof DocumentEntry)\n {\n if (showData)\n {\n pw.println(\"start doc: \" + prefix + entry.getName());\n if (hex == true)\n {\n byteCount = hexdump(new DocumentInputStream((DocumentEntry) entry), pw);\n }\n else\n {\n byteCount = asciidump(new DocumentInputStream((DocumentEntry) entry), pw);\n }\n pw.println(\"end doc: \" + prefix + entry.getName() + \" (\" + byteCount + \" bytes read)\");\n }\n else\n {\n if (indent != null)\n {\n pw.print(indent);\n }\n pw.println(\"doc: \" + prefix + entry.getName());\n }\n }\n else\n {\n pw.println(\"found unknown: \" + prefix + entry.getName());\n }\n }\n }", "private CmsXmlContent unmarshalXmlContent(CmsFile file) throws CmsXmlException {\n\n CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, file);\n content.setAutoCorrectionEnabled(true);\n content.correctXmlStructure(m_cms);\n\n return content;\n }", "public void createResourceFieldMap(Props props)\n {\n byte[] fieldMapData = null;\n for (Integer key : RESOURCE_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData == null)\n {\n populateDefaultData(getDefaultResourceData());\n }\n else\n {\n createFieldMap(fieldMapData);\n }\n }", "public static String toPrettyJson(Object o) {\n\t\ttry {\n\t\t\treturn MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(o);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tLoggerFactory\n\t\t\t .getLogger(Serializer.class)\n\t\t\t .error(\"Could not serialize the object. This will be ignored and the error will be written instead. Object was {}\",\n\t\t\t o, e);\n\t\t\treturn \"\\\"\" + e.getMessage() + \"\\\"\";\n\t\t}\n\t}", "public static final Color getColor(byte[] data, int offset)\n {\n Color result = null;\n\n if (getByte(data, offset + 3) == 0)\n {\n int r = getByte(data, offset);\n int g = getByte(data, offset + 1);\n int b = getByte(data, offset + 2);\n result = new Color(r, g, b);\n }\n\n return result;\n }", "protected String getUniqueString(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n ResultSetAndStatement rsStmt = null;\r\n String returnValue = null;\r\n try\r\n {\r\n rsStmt = getBrokerForClass().serviceJdbcAccess().executeSQL(\r\n \"select newid()\", field.getClassDescriptor(), Query.NOT_SCROLLABLE);\r\n if (rsStmt.m_rs.next())\r\n {\r\n returnValue = rsStmt.m_rs.getString(1);\r\n }\r\n else\r\n {\r\n LoggerFactory.getDefaultLogger().error(this.getClass()\r\n + \": Can't lookup new oid for field \" + field);\r\n }\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n throw new SequenceManagerException(e);\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new SequenceManagerException(e);\r\n }\r\n\r\n finally\r\n {\r\n // close the used resources\r\n if (rsStmt != null) rsStmt.close();\r\n }\r\n return returnValue;\r\n }", "private float getQuaternionW(float x, float y, float z) {\n return (float) Math.cos(Math.asin(Math.sqrt(x * x + y * y + z * z)));\n }" ]
Use this API to unlink sslcertkey.
[ "public static base_response unlink(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey unlinkresource = new sslcertkey();\n\t\tunlinkresource.certkey = resource.certkey;\n\t\treturn unlinkresource.perform_operation(client,\"unlink\");\n\t}" ]
[ "public void removeScript(int id) throws Exception {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, id);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public AT_Row setPaddingBottom(int paddingBottom) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingBottom(paddingBottom);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public synchronized int get() {\n if (available == 0) {\n return -1;\n }\n byte value = buffer[idxGet];\n idxGet = (idxGet + 1) % capacity;\n available--;\n return value;\n }", "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 }", "static <T> boolean syncInstantiation(T objectType) {\n List<Template> templates = new ArrayList<>();\n Templates tr = TEMP_FINDER.findAnnotations(templates, objectType);\n if (tr == null) {\n /* Default to synchronous instantiation */\n return true;\n } else {\n return tr.syncInstantiation();\n }\n }", "public boolean setCurrentPage(final int page) {\n Log.d(TAG, \"setPageId pageId = %d\", page);\n return (page >= 0 && page < getCheckableCount()) && check(page);\n }", "public static void serialize(final File folder, final String content, final String fileName) throws IOException {\n if (!folder.exists()) {\n folder.mkdirs();\n }\n\n final File output = new File(folder, fileName);\n\n try (\n final FileWriter writer = new FileWriter(output);\n ) {\n writer.write(content);\n writer.flush();\n } catch (Exception e) {\n throw new IOException(\"Failed to serialize the notification in folder \" + folder.getPath(), e);\n }\n }", "public List<String> uuids(long count) {\n final URI uri = new URIBase(clientUri).path(\"_uuids\").query(\"count\", count).build();\n final JsonObject json = get(uri, JsonObject.class);\n return getGson().fromJson(json.get(\"uuids\").toString(), DeserializationTypes.STRINGS);\n }", "public void sendJsonToUrl(Object data, String url) {\n sendToUrl(JSON.toJSONString(data), url);\n }" ]
1-D Integer array to double array. @param array Integer array. @return Double array.
[ "public static double[] toDouble(int[] array) {\n double[] n = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n n[i] = (double) array[i];\n }\n return n;\n }" ]
[ "private void populateTask(Row row, Task task)\n {\n //\"PROJID\"\n task.setUniqueID(row.getInteger(\"TASKID\"));\n //GIVEN_DURATIONTYPF\n //GIVEN_DURATIONELA_MONTHS\n task.setDuration(row.getDuration(\"GIVEN_DURATIONHOURS\"));\n task.setResume(row.getDate(\"RESUME\"));\n //task.setStart(row.getDate(\"GIVEN_START\"));\n //LATEST_PROGRESS_PERIOD\n //TASK_WORK_RATE_TIME_UNIT\n //TASK_WORK_RATE\n //PLACEMENT\n //BEEN_SPLIT\n //INTERRUPTIBLE\n //HOLDING_PIN\n ///ACTUAL_DURATIONTYPF\n //ACTUAL_DURATIONELA_MONTHS\n task.setActualDuration(row.getDuration(\"ACTUAL_DURATIONHOURS\"));\n task.setEarlyStart(row.getDate(\"EARLY_START_DATE\"));\n task.setLateStart(row.getDate(\"LATE_START_DATE\"));\n //FREE_START_DATE\n //START_CONSTRAINT_DATE\n //END_CONSTRAINT_DATE\n //task.setBaselineWork(row.getDuration(\"EFFORT_BUDGET\"));\n //NATURAO_ORDER\n //LOGICAL_PRECEDENCE\n //SPAVE_INTEGER\n //SWIM_LANE\n //USER_PERCENT_COMPLETE\n task.setPercentageComplete(row.getDouble(\"OVERALL_PERCENV_COMPLETE\"));\n //OVERALL_PERCENT_COMPL_WEIGHT\n task.setName(row.getString(\"NARE\"));\n task.setNotes(getNotes(row));\n task.setText(1, row.getString(\"UNIQUE_TASK_ID\"));\n task.setCalendar(m_project.getCalendarByUniqueID(row.getInteger(\"CALENDAU\")));\n //EFFORT_TIMI_UNIT\n //WORL_UNIT\n //LATEST_ALLOC_PROGRESS_PERIOD\n //WORN\n //BAR\n //CONSTRAINU\n //PRIORITB\n //CRITICAM\n //USE_PARENU_CALENDAR\n //BUFFER_TASK\n //MARK_FOS_HIDING\n //OWNED_BY_TIMESHEEV_X\n //START_ON_NEX_DAY\n //LONGEST_PATH\n //DURATIOTTYPF\n //DURATIOTELA_MONTHS\n //DURATIOTHOURS\n task.setStart(row.getDate(\"STARZ\"));\n task.setFinish(row.getDate(\"ENJ\"));\n //DURATION_TIMJ_UNIT\n //UNSCHEDULABLG\n //SUBPROJECT_ID\n //ALT_ID\n //LAST_EDITED_DATE\n //LAST_EDITED_BY\n\n processConstraints(row, task);\n\n if (NumberHelper.getInt(task.getPercentageComplete()) != 0)\n {\n task.setActualStart(task.getStart());\n if (task.getPercentageComplete().intValue() == 100)\n {\n task.setActualFinish(task.getFinish());\n task.setDuration(task.getActualDuration());\n }\n }\n }", "private static void checkPreconditions(final Set<Object> possibleValues) {\n\t\tif( possibleValues == null ) {\n\t\t\tthrow new NullPointerException(\"possibleValues Set should not be null\");\n\t\t} else if( possibleValues.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"possibleValues Set should not be empty\");\n\t\t}\n\t}", "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}", "private Integer getIntegerPropertyOverrideValue(String name, String key) {\n if (properties != null) {\n String propertyName = getPropertyName(name, key);\n\n String propertyOverrideValue = properties.getProperty(propertyName);\n\n if (propertyOverrideValue != null) {\n try {\n return Integer.parseInt(propertyOverrideValue);\n }\n catch (NumberFormatException e) {\n logger.error(\"Could not parse property override key={}, value={}\",\n key, propertyOverrideValue);\n }\n }\n }\n return null;\n }", "private void readDefinitions()\n {\n for (MapRow row : m_tables.get(\"TTL\"))\n {\n Integer id = row.getInteger(\"DEFINITION_ID\");\n List<MapRow> list = m_definitions.get(id);\n if (list == null)\n {\n list = new ArrayList<MapRow>();\n m_definitions.put(id, list);\n }\n list.add(row);\n }\n\n List<MapRow> rows = m_definitions.get(WBS_FORMAT_ID);\n if (rows != null)\n {\n m_wbsFormat = new SureTrakWbsFormat(rows.get(0));\n }\n }", "public CollectionRequest<Project> findByWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/projects\", workspace);\n return new CollectionRequest<Project>(this, Project.class, path, \"GET\");\n }", "public static base_response unset(nitro_service client, nsrpcnode resource, String[] args) throws Exception{\n\t\tnsrpcnode unsetresource = new nsrpcnode();\n\t\tunsetresource.ipaddress = resource.ipaddress;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public StringBuilder getSQLCondition(StringBuilder builder, String columnName) {\n\t\tString string = networkString.getString();\n\t\tif(isEntireAddress) {\n\t\t\tmatchString(builder, columnName, string);\n\t\t} else {\n\t\t\tmatchSubString(\n\t\t\t\t\tbuilder,\n\t\t\t\t\tcolumnName,\n\t\t\t\t\tnetworkString.getTrailingSegmentSeparator(),\n\t\t\t\t\tnetworkString.getTrailingSeparatorCount() + 1,\n\t\t\t\t\tstring);\n\t\t}\n\t\treturn builder;\n\t}", "public static base_responses update(nitro_service client, appfwlearningsettings resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwlearningsettings updateresources[] = new appfwlearningsettings[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new appfwlearningsettings();\n\t\t\t\tupdateresources[i].profilename = resources[i].profilename;\n\t\t\t\tupdateresources[i].starturlminthreshold = resources[i].starturlminthreshold;\n\t\t\t\tupdateresources[i].starturlpercentthreshold = resources[i].starturlpercentthreshold;\n\t\t\t\tupdateresources[i].cookieconsistencyminthreshold = resources[i].cookieconsistencyminthreshold;\n\t\t\t\tupdateresources[i].cookieconsistencypercentthreshold = resources[i].cookieconsistencypercentthreshold;\n\t\t\t\tupdateresources[i].csrftagminthreshold = resources[i].csrftagminthreshold;\n\t\t\t\tupdateresources[i].csrftagpercentthreshold = resources[i].csrftagpercentthreshold;\n\t\t\t\tupdateresources[i].fieldconsistencyminthreshold = resources[i].fieldconsistencyminthreshold;\n\t\t\t\tupdateresources[i].fieldconsistencypercentthreshold = resources[i].fieldconsistencypercentthreshold;\n\t\t\t\tupdateresources[i].crosssitescriptingminthreshold = resources[i].crosssitescriptingminthreshold;\n\t\t\t\tupdateresources[i].crosssitescriptingpercentthreshold = resources[i].crosssitescriptingpercentthreshold;\n\t\t\t\tupdateresources[i].sqlinjectionminthreshold = resources[i].sqlinjectionminthreshold;\n\t\t\t\tupdateresources[i].sqlinjectionpercentthreshold = resources[i].sqlinjectionpercentthreshold;\n\t\t\t\tupdateresources[i].fieldformatminthreshold = resources[i].fieldformatminthreshold;\n\t\t\t\tupdateresources[i].fieldformatpercentthreshold = resources[i].fieldformatpercentthreshold;\n\t\t\t\tupdateresources[i].xmlwsiminthreshold = resources[i].xmlwsiminthreshold;\n\t\t\t\tupdateresources[i].xmlwsipercentthreshold = resources[i].xmlwsipercentthreshold;\n\t\t\t\tupdateresources[i].xmlattachmentminthreshold = resources[i].xmlattachmentminthreshold;\n\t\t\t\tupdateresources[i].xmlattachmentpercentthreshold = resources[i].xmlattachmentpercentthreshold;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Use this API to update gslbservice.
[ "public static base_response update(nitro_service client, gslbservice resource) throws Exception {\n\t\tgslbservice updateresource = new gslbservice();\n\t\tupdateresource.servicename = resource.servicename;\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.publicip = resource.publicip;\n\t\tupdateresource.publicport = resource.publicport;\n\t\tupdateresource.cip = resource.cip;\n\t\tupdateresource.cipheader = resource.cipheader;\n\t\tupdateresource.sitepersistence = resource.sitepersistence;\n\t\tupdateresource.siteprefix = resource.siteprefix;\n\t\tupdateresource.maxclient = resource.maxclient;\n\t\tupdateresource.healthmonitor = resource.healthmonitor;\n\t\tupdateresource.maxbandwidth = resource.maxbandwidth;\n\t\tupdateresource.downstateflush = resource.downstateflush;\n\t\tupdateresource.maxaaausers = resource.maxaaausers;\n\t\tupdateresource.viewname = resource.viewname;\n\t\tupdateresource.viewip = resource.viewip;\n\t\tupdateresource.monthreshold = resource.monthreshold;\n\t\tupdateresource.weight = resource.weight;\n\t\tupdateresource.monitor_name_svc = resource.monitor_name_svc;\n\t\tupdateresource.hashid = resource.hashid;\n\t\tupdateresource.comment = resource.comment;\n\t\tupdateresource.appflowlog = resource.appflowlog;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
[ "public static ProjectReader getProjectReader(String name) throws MPXJException\n {\n int index = name.lastIndexOf('.');\n if (index == -1)\n {\n throw new IllegalArgumentException(\"Filename has no extension: \" + name);\n }\n\n String extension = name.substring(index + 1).toUpperCase();\n\n Class<? extends ProjectReader> fileClass = READER_MAP.get(extension);\n if (fileClass == null)\n {\n throw new IllegalArgumentException(\"Cannot read files of type: \" + extension);\n }\n\n try\n {\n ProjectReader file = fileClass.newInstance();\n return (file);\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to load project reader\", ex);\n }\n }", "@Deprecated public Duration getDuration(Date startDate, Date endDate) throws MPXJException\n {\n return (getDuration(\"Standard\", startDate, endDate));\n }", "public ItemRequest<Task> delete(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"DELETE\");\n }", "public static Map<Integer, Integer> getMapOfContiguousPartitions(final Cluster cluster,\n int zoneId) {\n List<Integer> partitionIds = new ArrayList<Integer>(cluster.getPartitionIdsInZone(zoneId));\n Map<Integer, Integer> partitionIdToRunLength = Maps.newHashMap();\n\n if(partitionIds.isEmpty()) {\n return partitionIdToRunLength;\n }\n\n int lastPartitionId = partitionIds.get(0);\n int initPartitionId = lastPartitionId;\n\n for(int offset = 1; offset < partitionIds.size(); offset++) {\n int partitionId = partitionIds.get(offset);\n if(partitionId == lastPartitionId + 1) {\n lastPartitionId = partitionId;\n continue;\n }\n int runLength = lastPartitionId - initPartitionId + 1;\n\n partitionIdToRunLength.put(initPartitionId, runLength);\n\n initPartitionId = partitionId;\n lastPartitionId = initPartitionId;\n }\n\n int runLength = lastPartitionId - initPartitionId + 1;\n if(lastPartitionId == cluster.getNumberOfPartitions() - 1\n && partitionIdToRunLength.containsKey(0)) {\n // special case of contiguity that wraps around the ring.\n partitionIdToRunLength.put(initPartitionId, runLength + partitionIdToRunLength.get(0));\n partitionIdToRunLength.remove(0);\n } else {\n partitionIdToRunLength.put(initPartitionId, runLength);\n }\n\n return partitionIdToRunLength;\n }", "private SortedProperties getLocalization(Locale locale) throws IOException, CmsException {\n\n if (null == m_localizations.get(locale)) {\n switch (m_bundleType) {\n case PROPERTY:\n loadLocalizationFromPropertyBundle(locale);\n break;\n case XML:\n loadLocalizationFromXmlBundle(locale);\n break;\n case DESCRIPTOR:\n return null;\n default:\n break;\n }\n }\n return m_localizations.get(locale);\n }", "private boolean processQueue(K key) {\n Queue<AsyncResourceRequest<V>> requestQueue = getRequestQueueForKey(key);\n if(requestQueue.isEmpty()) {\n return false;\n }\n\n // Attempt to get a resource.\n Pool<V> resourcePool = getResourcePoolForKey(key);\n V resource = null;\n Exception ex = null;\n try {\n // Must attempt non-blocking checkout to ensure resources are\n // created for the pool.\n resource = attemptNonBlockingCheckout(key, resourcePool);\n } catch(Exception e) {\n destroyResource(key, resourcePool, resource);\n ex = e;\n resource = null;\n }\n // Neither we got a resource, nor an exception. So no requests can be\n // processed return\n if(resource == null && ex == null) {\n return false;\n }\n\n // With resource in hand, process the resource requests\n AsyncResourceRequest<V> resourceRequest = getNextUnexpiredResourceRequest(requestQueue);\n if(resourceRequest == null) {\n if(resource != null) {\n // Did not use the resource! Directly check in via super to\n // avoid\n // circular call to processQueue().\n try {\n super.checkin(key, resource);\n } catch(Exception e) {\n logger.error(\"Exception checking in resource: \", e);\n }\n } else {\n // Poor exception, no request to tag this exception onto\n // drop it on the floor and continue as usual.\n }\n return false;\n } else {\n // We have a request here.\n if(resource != null) {\n resourceRequest.useResource(resource);\n } else {\n resourceRequest.handleException(ex);\n }\n return true;\n }\n }", "public Metadata getMetadata(String templateName) {\n String scope = Metadata.scopeBasedOnType(templateName);\n return this.getMetadata(templateName, scope);\n }", "private void writeProperties() throws IOException\n {\n writeAttributeTypes(\"property_types\", ProjectField.values());\n writeFields(\"property_values\", m_projectFile.getProjectProperties(), ProjectField.values());\n }", "public static void acceptsNodeMultiple(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_N, OPT_NODE), \"node id list\")\n .withRequiredArg()\n .describedAs(\"node-id-list\")\n .withValuesSeparatedBy(',')\n .ofType(Integer.class);\n }" ]
Use this API to fetch aaauser_binding resource of given name .
[ "public static aaauser_binding get(nitro_service service, String username) throws Exception{\n\t\taaauser_binding obj = new aaauser_binding();\n\t\tobj.set_username(username);\n\t\taaauser_binding response = (aaauser_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "@Override\n\tpublic void writeValue(TimeValue value, Resource resource)\n\t\t\tthrows RDFHandlerException {\n\t\tthis.rdfWriter.writeTripleValueObject(resource, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.WB_TIME_VALUE);\n\n\t\tthis.rdfWriter.writeTripleValueObject(resource, RdfWriter.WB_TIME,\n\t\t\t\tTimeValueConverter.getTimeLiteral(value, this.rdfWriter));\n\n\t\tthis.rdfWriter.writeTripleIntegerObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_PRECISION, value.getPrecision());\n\t\tthis.rdfWriter.writeTripleIntegerObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_TIMEZONE,\n\t\t\t\tvalue.getTimezoneOffset());\n\t\tthis.rdfWriter.writeTripleUriObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_CALENDAR_MODEL,\n\t\t\t\tvalue.getPreferredCalendarModel());\n\t}", "public static PredicateExpression nin(Object... rhs) {\n PredicateExpression ex = new PredicateExpression(\"$nin\", rhs);\n if (rhs.length == 1) {\n ex.single = true;\n }\n return ex;\n }", "private void createTimephasedData(ProjectFile file, ResourceAssignment assignment, List<TimephasedWork> timephasedPlanned, List<TimephasedWork> timephasedComplete)\n {\n if (timephasedPlanned.isEmpty() && timephasedComplete.isEmpty())\n {\n Duration totalMinutes = assignment.getWork().convertUnits(TimeUnit.MINUTES, file.getProjectProperties());\n\n Duration workPerDay;\n\n if (assignment.getResource() == null || assignment.getResource().getType() == ResourceType.WORK)\n {\n workPerDay = totalMinutes.getDuration() == 0 ? totalMinutes : ResourceAssignmentFactory.DEFAULT_NORMALIZER_WORK_PER_DAY;\n int units = NumberHelper.getInt(assignment.getUnits());\n if (units != 100)\n {\n workPerDay = Duration.getInstance((workPerDay.getDuration() * units) / 100.0, workPerDay.getUnits());\n }\n }\n else\n {\n if (assignment.getVariableRateUnits() == null)\n {\n Duration workingDays = assignment.getCalendar().getWork(assignment.getStart(), assignment.getFinish(), TimeUnit.DAYS);\n double units = NumberHelper.getDouble(assignment.getUnits());\n double unitsPerDayAsMinutes = (units * 60) / (workingDays.getDuration() * 100);\n workPerDay = Duration.getInstance(unitsPerDayAsMinutes, TimeUnit.MINUTES);\n }\n else\n {\n double unitsPerHour = NumberHelper.getDouble(assignment.getUnits());\n workPerDay = ResourceAssignmentFactory.DEFAULT_NORMALIZER_WORK_PER_DAY;\n Duration hoursPerDay = workPerDay.convertUnits(TimeUnit.HOURS, file.getProjectProperties());\n double unitsPerDayAsHours = (unitsPerHour * hoursPerDay.getDuration()) / 100;\n double unitsPerDayAsMinutes = unitsPerDayAsHours * 60;\n workPerDay = Duration.getInstance(unitsPerDayAsMinutes, TimeUnit.MINUTES);\n }\n }\n\n Duration overtimeWork = assignment.getOvertimeWork();\n if (overtimeWork != null && overtimeWork.getDuration() != 0)\n {\n Duration totalOvertimeMinutes = overtimeWork.convertUnits(TimeUnit.MINUTES, file.getProjectProperties());\n totalMinutes = Duration.getInstance(totalMinutes.getDuration() - totalOvertimeMinutes.getDuration(), TimeUnit.MINUTES);\n }\n\n TimephasedWork tra = new TimephasedWork();\n tra.setStart(assignment.getStart());\n tra.setAmountPerDay(workPerDay);\n tra.setModified(false);\n tra.setFinish(assignment.getFinish());\n tra.setTotalAmount(totalMinutes);\n timephasedPlanned.add(tra);\n }\n }", "public static dnsview[] get(nitro_service service, String viewname[]) throws Exception{\n\t\tif (viewname !=null && viewname.length>0) {\n\t\t\tdnsview response[] = new dnsview[viewname.length];\n\t\t\tdnsview obj[] = new dnsview[viewname.length];\n\t\t\tfor (int i=0;i<viewname.length;i++) {\n\t\t\t\tobj[i] = new dnsview();\n\t\t\t\tobj[i].set_viewname(viewname[i]);\n\t\t\t\tresponse[i] = (dnsview) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public void setConvergence( int maxIterations , double ftol , double gtol ) {\n this.maxIterations = maxIterations;\n this.ftol = ftol;\n this.gtol = gtol;\n }", "protected boolean check(String value, String regex) {\n\t\tPattern pattern = Pattern.compile(regex);\n\t\treturn pattern.matcher(value).matches();\n\t}", "public void forAllMemberTags(String template, Properties attributes) throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n forAllMemberTags(template, attributes, FOR_FIELD, XDocletTagshandlerMessages.ONLY_CALL_FIELD_NOT_NULL, new String[]{\"forAllMemberTags\"});\r\n }\r\n else if (getCurrentMethod() != null) {\r\n forAllMemberTags(template, attributes, FOR_METHOD, XDocletTagshandlerMessages.ONLY_CALL_METHOD_NOT_NULL, new String[]{\"forAllMemberTags\"});\r\n }\r\n }", "public static java.util.Date rollDateTime(java.util.Date startDate, int period, int amount) {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(startDate);\n gc.add(period, amount);\n return new java.util.Date(gc.getTime().getTime());\n }", "public SqlStatement getPreparedUpdateStatement(ClassDescriptor cld)\r\n {\r\n SqlForClass sfc = getSqlForClass(cld);\r\n SqlStatement result = sfc.getUpdateSql();\r\n if(result == null)\r\n {\r\n ProcedureDescriptor pd = cld.getUpdateProcedure();\r\n\r\n if(pd == null)\r\n {\r\n result = new SqlUpdateStatement(cld, logger);\r\n }\r\n else\r\n {\r\n result = new SqlProcedureStatement(pd, logger);\r\n }\r\n // set the sql string\r\n sfc.setUpdateSql(result);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + result.getStatement());\r\n }\r\n }\r\n return result;\r\n }" ]
Create the environment as specified by @Template or arq.extension.ce-cube.openshift.template.* properties. <p> In the future, this might be handled by starting application Cube objects, e.g. CreateCube(application), StartCube(application) <p> Needs to fire before the containers are started.
[ "public void createEnvironment(@Observes(precedence = 10) BeforeClass event, OpenShiftAdapter client,\n CubeOpenShiftConfiguration cubeOpenShiftConfiguration) {\n final TestClass testClass = event.getTestClass();\n log.info(String.format(\"Creating environment for %s\", testClass.getName()));\n OpenShiftResourceFactory.createResources(testClass.getName(), client, testClass.getJavaClass(),\n cubeOpenShiftConfiguration.getProperties());\n classTemplateProcessor = new ClassTemplateProcessor(client, cubeOpenShiftConfiguration, testClass);\n final List<? extends OpenShiftResource> templateResources = classTemplateProcessor.processTemplateResources();\n templateDetailsProducer.set(() -> templateResources);\n }" ]
[ "public static ConstraintField getInstance(int value)\n {\n ConstraintField result = null;\n\n if (value >= 0 && value < FIELD_ARRAY.length)\n {\n result = FIELD_ARRAY[value];\n }\n\n return (result);\n }", "public String getDefaultTableName()\r\n {\r\n String name = getName();\r\n int lastDotPos = name.lastIndexOf('.');\r\n int lastDollarPos = name.lastIndexOf('$');\r\n\r\n return lastDollarPos > lastDotPos ? name.substring(lastDollarPos + 1) : name.substring(lastDotPos + 1);\r\n }", "public static Chart getTrajectoryChart(String title, Trajectory t){\n\t\tif(t.getDimension()==2){\n\t\t \tdouble[] xData = new double[t.size()];\n\t\t double[] yData = new double[t.size()];\n\t\t for(int i = 0; i < t.size(); i++){\n\t\t \txData[i] = t.get(i).x;\n\t\t \tyData[i] = t.get(i).y;\n\t\t \t\n\t\t }\n\t\t // Create Chart\n\t\t Chart chart = QuickChart.getChart(title, \"X\", \"Y\", \"y(x)\", xData, yData);\n\t\n\t\t return chart;\n\t\t //Show it\n\t\t // SwingWrapper swr = new SwingWrapper(chart);\n\t\t // swr.displayChart();\n\t\t} \n\t\treturn null;\n\t}", "public String getNextDay(String dateString, boolean onlyBusinessDays) {\n DateTimeFormatter parser = ISODateTimeFormat.date();\n DateTime date = parser.parseDateTime(dateString).plusDays(1);\n Calendar cal = Calendar.getInstance();\n cal.setTime(date.toDate());\n\n if (onlyBusinessDays) {\n if (cal.get(Calendar.DAY_OF_WEEK) == 1 || cal.get(Calendar.DAY_OF_WEEK) == 7\n || isHoliday(date.toString().substring(0, 10))) {\n return getNextDay(date.toString().substring(0, 10), true);\n } else {\n return parser.print(date);\n }\n } else {\n return parser.print(date);\n }\n }", "public void addDateTimeHelper(int ds, Date date) throws SerializationException, InvalidDataSetException {\r\n\t\tif (date == null) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tDataSetInfo dsi = dsiFactory.create(ds);\r\n\r\n\t\tSimpleDateFormat df = new SimpleDateFormat(dsi.getSerializer().toString());\r\n\t\tString value = df.format(date);\r\n\t\tbyte[] data = dsi.getSerializer().serialize(value, activeSerializationContext);\r\n\t\tDataSet dataSet = new DefaultDataSet(dsi, data);\r\n\t\tadd(dataSet);\r\n\t}", "private void writeExceptions12(Project.Calendars.Calendar calendar, List<ProjectCalendarException> exceptions)\n {\n Exceptions ce = m_factory.createProjectCalendarsCalendarExceptions();\n calendar.setExceptions(ce);\n List<Exceptions.Exception> el = ce.getException();\n\n for (ProjectCalendarException exception : exceptions)\n {\n Exceptions.Exception ex = m_factory.createProjectCalendarsCalendarExceptionsException();\n el.add(ex);\n\n ex.setName(exception.getName());\n boolean working = exception.getWorking();\n ex.setDayWorking(Boolean.valueOf(working));\n\n if (exception.getRecurring() == null)\n {\n ex.setEnteredByOccurrences(Boolean.FALSE);\n ex.setOccurrences(BigInteger.ONE);\n ex.setType(BigInteger.ONE);\n }\n else\n {\n populateRecurringException(exception, ex);\n }\n\n Project.Calendars.Calendar.Exceptions.Exception.TimePeriod period = m_factory.createProjectCalendarsCalendarExceptionsExceptionTimePeriod();\n ex.setTimePeriod(period);\n period.setFromDate(exception.getFromDate());\n period.setToDate(exception.getToDate());\n\n if (working)\n {\n Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes times = m_factory.createProjectCalendarsCalendarExceptionsExceptionWorkingTimes();\n ex.setWorkingTimes(times);\n List<Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime> timesList = times.getWorkingTime();\n\n for (DateRange range : exception)\n {\n Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime time = m_factory.createProjectCalendarsCalendarExceptionsExceptionWorkingTimesWorkingTime();\n timesList.add(time);\n\n time.setFromTime(range.getStart());\n time.setToTime(range.getEnd());\n }\n }\n }\n }", "public void setTileUrls(List<String> tileUrls) {\n\t\tthis.tileUrls = tileUrls;\n\t\tif (null != urlStrategy) {\n\t\t\turlStrategy.setUrls(tileUrls);\n\t\t}\n\t}", "@SuppressWarnings(\"unchecked\")\n @Nonnull\n public final java.util.Optional<Style> getStyle(final String styleName) {\n final String styleRef = this.styles.get(styleName);\n Optional<Style> style;\n if (styleRef != null) {\n style = (Optional<Style>) this.styleParser\n .loadStyle(getConfiguration(), this.httpRequestFactory, styleRef);\n } else {\n style = Optional.empty();\n }\n return or(style, this.configuration.getStyle(styleName));\n }", "public ViewGroup getContentContainer() {\n if (mDragMode == MENU_DRAG_CONTENT) {\n return mContentContainer;\n } else {\n return (ViewGroup) findViewById(android.R.id.content);\n }\n }" ]
Creates the "Add key" button. @return the "Add key" button.
[ "private Component createAddKeyButton() {\n\n // the \"+\" button\n Button addKeyButton = new Button();\n addKeyButton.addStyleName(\"icon-only\");\n addKeyButton.addStyleName(\"borderless-colored\");\n addKeyButton.setDescription(m_messages.key(Messages.GUI_ADD_KEY_0));\n addKeyButton.setIcon(FontOpenCms.CIRCLE_PLUS, m_messages.key(Messages.GUI_ADD_KEY_0));\n addKeyButton.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n handleAddKey();\n\n }\n });\n return addKeyButton;\n }" ]
[ "public <T> T fetchObject(String objectId, Class<T> type) {\n\t\tURI uri = URIBuilder.fromUri(getBaseGraphApiUrl() + objectId).build();\n\t\treturn getRestTemplate().getForObject(uri, type);\n\t}", "private void logError(LifecycleListener listener, Exception e) {\n LOGGER.error(\"Error for listener \" + listener.getClass(), e);\n }", "protected ValueContainer[] getKeyValues(PersistenceBroker broker, ClassDescriptor cld, Identity oid) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getKeyValues(cld, oid);\r\n }", "public static sslciphersuite[] get(nitro_service service, options option) throws Exception{\n\t\tsslciphersuite obj = new sslciphersuite();\n\t\tsslciphersuite[] response = (sslciphersuite[])obj.get_resources(service,option);\n\t\treturn response;\n\t}", "public void doLocalClear()\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"Clear materialization cache\");\r\n invokeCounter = 0;\r\n enabledReadCache = false;\r\n objectBuffer.clear();\r\n }", "private void readRelationship(Link link)\n {\n Task sourceTask = m_taskIdMap.get(link.getSourceTaskID());\n Task destinationTask = m_taskIdMap.get(link.getDestinationTaskID());\n if (sourceTask != null && destinationTask != null)\n {\n Duration lag = getDuration(link.getLagUnit(), link.getLag());\n RelationType type = link.getType();\n Relation relation = destinationTask.addPredecessor(sourceTask, type, lag);\n relation.setUniqueID(link.getID());\n }\n }", "protected void animateOffsetTo(int position, int velocity, boolean animate) {\n endDrag();\n endPeek();\n\n final int startX = (int) mOffsetPixels;\n final int dx = position - startX;\n if (dx == 0 || !animate) {\n setOffsetPixels(position);\n setDrawerState(position == 0 ? STATE_CLOSED : STATE_OPEN);\n stopLayerTranslation();\n return;\n }\n\n int duration;\n\n velocity = Math.abs(velocity);\n if (velocity > 0) {\n duration = 4 * Math.round(1000.f * Math.abs((float) dx / velocity));\n } else {\n duration = (int) (600.f * Math.abs((float) dx / mMenuSize));\n }\n\n duration = Math.min(duration, mMaxAnimationDuration);\n animateOffsetTo(position, duration);\n }", "@Override\n public Optional<SoyMapData> toSoyMap(@Nullable final Object model) throws Exception {\n if (model instanceof SoyMapData) {\n return Optional.of((SoyMapData) model);\n }\n if (model instanceof Map) {\n return Optional.of(new SoyMapData(model));\n }\n\n return Optional.of(new SoyMapData());\n }", "public static Map<FieldType, String> getDefaultTaskFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(TaskField.UNIQUE_ID, \"task_id\");\n map.put(TaskField.GUID, \"guid\");\n map.put(TaskField.NAME, \"task_name\");\n map.put(TaskField.ACTUAL_DURATION, \"act_drtn_hr_cnt\");\n map.put(TaskField.REMAINING_DURATION, \"remain_drtn_hr_cnt\");\n map.put(TaskField.ACTUAL_WORK, \"act_work_qty\");\n map.put(TaskField.REMAINING_WORK, \"remain_work_qty\");\n map.put(TaskField.BASELINE_WORK, \"target_work_qty\");\n map.put(TaskField.BASELINE_DURATION, \"target_drtn_hr_cnt\");\n map.put(TaskField.DURATION, \"target_drtn_hr_cnt\");\n map.put(TaskField.CONSTRAINT_DATE, \"cstr_date\");\n map.put(TaskField.ACTUAL_START, \"act_start_date\");\n map.put(TaskField.ACTUAL_FINISH, \"act_end_date\");\n map.put(TaskField.LATE_START, \"late_start_date\");\n map.put(TaskField.LATE_FINISH, \"late_end_date\");\n map.put(TaskField.EARLY_START, \"early_start_date\");\n map.put(TaskField.EARLY_FINISH, \"early_end_date\");\n map.put(TaskField.REMAINING_EARLY_START, \"restart_date\");\n map.put(TaskField.REMAINING_EARLY_FINISH, \"reend_date\");\n map.put(TaskField.BASELINE_START, \"target_start_date\");\n map.put(TaskField.BASELINE_FINISH, \"target_end_date\");\n map.put(TaskField.CONSTRAINT_TYPE, \"cstr_type\");\n map.put(TaskField.PRIORITY, \"priority_type\");\n map.put(TaskField.CREATED, \"create_date\");\n map.put(TaskField.TYPE, \"duration_type\");\n map.put(TaskField.FREE_SLACK, \"free_float_hr_cnt\");\n map.put(TaskField.TOTAL_SLACK, \"total_float_hr_cnt\");\n map.put(TaskField.TEXT1, \"task_code\");\n map.put(TaskField.TEXT2, \"task_type\");\n map.put(TaskField.TEXT3, \"status_code\");\n map.put(TaskField.NUMBER1, \"rsrc_id\");\n\n return map;\n }" ]
Queries a Search Index and returns ungrouped results. In case the query used grouping, an empty list is returned @param <T> Object type T @param query the Lucene query to be passed to the Search index @param classOfT The class of type T @return The result of the search query as a {@code List<T> }
[ "public <T> List<T> query(String query, Class<T> classOfT) {\r\n InputStream instream = null;\r\n List<T> result = new ArrayList<T>();\r\n try {\r\n Reader reader = new InputStreamReader(instream = queryForStream(query), \"UTF-8\");\r\n JsonObject json = new JsonParser().parse(reader).getAsJsonObject();\r\n if (json.has(\"rows\")) {\r\n if (!includeDocs) {\r\n log.warning(\"includeDocs set to false and attempting to retrieve doc. \" +\r\n \"null object will be returned\");\r\n }\r\n for (JsonElement e : json.getAsJsonArray(\"rows\")) {\r\n result.add(jsonToObject(client.getGson(), e, \"doc\", classOfT));\r\n }\r\n } else {\r\n log.warning(\"No ungrouped result available. Use queryGroups() if grouping set\");\r\n }\r\n return result;\r\n } catch (UnsupportedEncodingException e1) {\r\n // This should never happen as every implementation of the java platform is required\r\n // to support UTF-8.\r\n throw new RuntimeException(e1);\r\n } finally {\r\n close(instream);\r\n }\r\n }" ]
[ "private TaskField getTaskField(int field)\n {\n TaskField result = MPPTaskField14.getInstance(field);\n\n if (result != null)\n {\n switch (result)\n {\n case START_TEXT:\n {\n result = TaskField.START;\n break;\n }\n\n case FINISH_TEXT:\n {\n result = TaskField.FINISH;\n break;\n }\n\n case DURATION_TEXT:\n {\n result = TaskField.DURATION;\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n return result;\n }", "@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 Collection<Locale> initLocales() {\n\n Collection<Locale> locales = null;\n switch (m_bundleType) {\n case DESCRIPTOR:\n locales = new ArrayList<Locale>(1);\n locales.add(Descriptor.LOCALE);\n break;\n case XML:\n case PROPERTY:\n locales = OpenCms.getLocaleManager().getAvailableLocales(m_cms, m_resource);\n break;\n default:\n throw new IllegalArgumentException();\n }\n return locales;\n\n }", "private static void parseChildShapes(ArrayList<Shape> shapes,\n JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"childShapes\")) {\n ArrayList<Shape> childShapes = new ArrayList<Shape>();\n\n JSONArray childShapeObject = modelJSON.getJSONArray(\"childShapes\");\n for (int i = 0; i < childShapeObject.length(); i++) {\n childShapes.add(getShapeWithId(childShapeObject.getJSONObject(i).getString(\"resourceId\"),\n shapes));\n }\n if (childShapes.size() > 0) {\n for (Shape each : childShapes) {\n each.setParent(current);\n }\n current.setChildShapes(childShapes);\n }\n ;\n }\n }", "private static long asciidump(InputStream is, PrintWriter pw) throws Exception\n {\n byte[] buffer = new byte[BUFFER_SIZE];\n long byteCount = 0;\n\n char c;\n int loop;\n int count;\n StringBuilder sb = new StringBuilder();\n\n while (true)\n {\n count = is.read(buffer);\n if (count == -1)\n {\n break;\n }\n\n byteCount += count;\n\n sb.setLength(0);\n for (loop = 0; loop < count; loop++)\n {\n c = (char) buffer[loop];\n if (c > 200 || c < 27)\n {\n c = ' ';\n }\n\n sb.append(c);\n }\n\n pw.print(sb.toString());\n }\n\n return (byteCount);\n }", "@UiThread\n protected void collapseView() {\n setExpanded(false);\n onExpansionToggled(true);\n\n if (mParentViewHolderExpandCollapseListener != null) {\n mParentViewHolderExpandCollapseListener.onParentCollapsed(getAdapterPosition());\n }\n }", "public static base_response update(nitro_service client, Interface resource) throws Exception {\n\t\tInterface updateresource = new Interface();\n\t\tupdateresource.id = resource.id;\n\t\tupdateresource.speed = resource.speed;\n\t\tupdateresource.duplex = resource.duplex;\n\t\tupdateresource.flowctl = resource.flowctl;\n\t\tupdateresource.autoneg = resource.autoneg;\n\t\tupdateresource.hamonitor = resource.hamonitor;\n\t\tupdateresource.tagall = resource.tagall;\n\t\tupdateresource.trunk = resource.trunk;\n\t\tupdateresource.lacpmode = resource.lacpmode;\n\t\tupdateresource.lacpkey = resource.lacpkey;\n\t\tupdateresource.lagtype = resource.lagtype;\n\t\tupdateresource.lacppriority = resource.lacppriority;\n\t\tupdateresource.lacptimeout = resource.lacptimeout;\n\t\tupdateresource.ifalias = resource.ifalias;\n\t\tupdateresource.throughput = resource.throughput;\n\t\tupdateresource.bandwidthhigh = resource.bandwidthhigh;\n\t\tupdateresource.bandwidthnormal = resource.bandwidthnormal;\n\t\treturn updateresource.update_resource(client);\n\t}", "public Date getFinish()\n {\n Date result = (Date) getCachedValue(AssignmentField.FINISH);\n if (result == null)\n {\n result = getTask().getFinish();\n }\n return result;\n }", "public static void start(final GVRContext context, final String appId, final ResultListener listener) {\n if (null == listener) {\n throw new IllegalArgumentException(\"listener cannot be null\");\n }\n\n final Activity activity = context.getActivity();\n final long result = create(activity, appId);\n if (0 != result) {\n throw new IllegalStateException(\"Could not initialize the platform sdk; error code: \" + result);\n }\n\n context.registerDrawFrameListener(new GVRDrawFrameListener() {\n @Override\n public void onDrawFrame(float frameTime) {\n final int result = processEntitlementCheckResponse();\n if (0 != result) {\n context.unregisterDrawFrameListener(this);\n\n final Runnable runnable;\n if (-1 == result) {\n runnable = new Runnable() {\n @Override\n public void run() {\n listener.onFailure();\n }\n };\n } else {\n runnable = new Runnable() {\n @Override\n public void run() {\n listener.onSuccess();\n }\n };\n }\n activity.runOnUiThread(runnable);\n }\n }\n });\n }" ]
Performs backward pass of Batch Normalization layer. Returns x gradient, bnScale gradient and bnBias gradient
[ "public static int cudnnBatchNormalizationBackward(\n cudnnHandle handle, \n int mode, \n Pointer alphaDataDiff, \n Pointer betaDataDiff, \n Pointer alphaParamDiff, \n Pointer betaParamDiff, \n cudnnTensorDescriptor xDesc, /** same desc for x, dx, dy */\n Pointer x, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor dxDesc, \n Pointer dx, \n /** Shared tensor desc for the 4 tensors below */\n cudnnTensorDescriptor dBnScaleBiasDesc, \n Pointer bnScale, /** bnBias doesn't affect backpropagation */\n /** scale and bias diff are not backpropagated below this layer */\n Pointer dBnScaleResult, \n Pointer dBnBiasResult, \n /** Same epsilon as forward pass */\n double epsilon, \n /** Optionally cached intermediate results from\n forward pass */\n Pointer savedMean, \n Pointer savedInvVariance)\n {\n return checkResult(cudnnBatchNormalizationBackwardNative(handle, mode, alphaDataDiff, betaDataDiff, alphaParamDiff, betaParamDiff, xDesc, x, dyDesc, dy, dxDesc, dx, dBnScaleBiasDesc, bnScale, dBnScaleResult, dBnBiasResult, epsilon, savedMean, savedInvVariance));\n }" ]
[ "public static base_response unset(nitro_service client, ipv6 resource, String[] args) throws Exception{\n\t\tipv6 unsetresource = new ipv6();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public void setPatternScheme(final boolean isByWeekDay, final boolean fireChange) {\n\n if (isByWeekDay ^ (null != m_model.getWeekDay())) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n if (isByWeekDay) {\n m_model.setWeekOfMonth(getPatternDefaultValues().getWeekOfMonth());\n m_model.setWeekDay(getPatternDefaultValues().getWeekDay());\n } else {\n m_model.clearWeekDays();\n m_model.clearWeeksOfMonth();\n m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth());\n }\n m_model.setInterval(getPatternDefaultValues().getInterval());\n if (fireChange) {\n onValueChange();\n }\n }\n });\n }\n\n }", "public void animate(GVRHybridObject object, float animationTime)\n {\n GVRMeshMorph morph = (GVRMeshMorph) mTarget;\n\n mKeyInterpolator.animate(animationTime * mDuration, mCurrentValues);\n morph.setWeights(mCurrentValues);\n\n }", "private static MessageInfoType mapMessageInfo(MessageInfo messageInfo) {\n if (messageInfo == null) {\n return null;\n }\n MessageInfoType miType = new MessageInfoType();\n miType.setMessageId(messageInfo.getMessageId());\n miType.setFlowId(messageInfo.getFlowId());\n miType.setPorttype(convertString(messageInfo.getPortType()));\n miType.setOperationName(messageInfo.getOperationName());\n miType.setTransport(messageInfo.getTransportType());\n return miType;\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 static Map<Integer, Integer> getMapOfContiguousPartitions(final Cluster cluster,\n int zoneId) {\n List<Integer> partitionIds = new ArrayList<Integer>(cluster.getPartitionIdsInZone(zoneId));\n Map<Integer, Integer> partitionIdToRunLength = Maps.newHashMap();\n\n if(partitionIds.isEmpty()) {\n return partitionIdToRunLength;\n }\n\n int lastPartitionId = partitionIds.get(0);\n int initPartitionId = lastPartitionId;\n\n for(int offset = 1; offset < partitionIds.size(); offset++) {\n int partitionId = partitionIds.get(offset);\n if(partitionId == lastPartitionId + 1) {\n lastPartitionId = partitionId;\n continue;\n }\n int runLength = lastPartitionId - initPartitionId + 1;\n\n partitionIdToRunLength.put(initPartitionId, runLength);\n\n initPartitionId = partitionId;\n lastPartitionId = initPartitionId;\n }\n\n int runLength = lastPartitionId - initPartitionId + 1;\n if(lastPartitionId == cluster.getNumberOfPartitions() - 1\n && partitionIdToRunLength.containsKey(0)) {\n // special case of contiguity that wraps around the ring.\n partitionIdToRunLength.put(initPartitionId, runLength + partitionIdToRunLength.get(0));\n partitionIdToRunLength.remove(0);\n } else {\n partitionIdToRunLength.put(initPartitionId, runLength);\n }\n\n return partitionIdToRunLength;\n }", "public int length() {\n int length = 1 + 2 + deviceToken.length + 2 + payload.length;\n final int marshalledLength = marshall().length;\n assert marshalledLength == length;\n return length;\n }", "protected byte[] getBytesInternal() {\n\t\tbyte cached[];\n\t\tif(hasNoValueCache() || (cached = valueCache.lowerBytes) == null) {\n\t\t\tvalueCache.lowerBytes = cached = getBytesImpl(true);\n\t\t}\n\t\treturn cached;\n\t}", "@UiHandler(\"m_endTime\")\n void onEndTimeChange(CmsDateBoxEvent event) {\n\n if (handleChange() && !event.isUserTyping()) {\n m_controller.setEndTime(event.getDate());\n }\n }" ]
Compares two columns given by their names. @param objA The name of the first column @param objB The name of the second column @return @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
[ "public int compare(Object objA, Object objB)\r\n {\r\n String idAStr = _table.getColumn((String)objA).getProperty(\"id\");\r\n String idBStr = _table.getColumn((String)objB).getProperty(\"id\");\r\n int idA;\r\n int idB;\r\n\r\n try {\r\n idA = Integer.parseInt(idAStr);\r\n }\r\n catch (Exception ex) {\r\n return 1;\r\n }\r\n try {\r\n idB = Integer.parseInt(idBStr);\r\n }\r\n catch (Exception ex) {\r\n return -1;\r\n }\r\n return idA < idB ? -1 : (idA > idB ? 1 : 0);\r\n }" ]
[ "public static appfwpolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_binding obj = new appfwpolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_binding response = (appfwpolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void createTasks(ChildTaskContainer parent, String parentName, List<Row> rows)\n {\n for (Row row : rows)\n {\n boolean rowIsBar = (row.getInteger(\"BARID\") != null);\n\n //\n // Don't export hammock tasks.\n //\n if (rowIsBar && row.getChildRows().isEmpty())\n {\n continue;\n }\n\n Task task = parent.addTask();\n\n //\n // Do we have a bar, task, or milestone?\n //\n if (rowIsBar)\n {\n //\n // If the bar only has one child task, we skip it and add the task directly\n //\n if (skipBar(row))\n {\n populateLeaf(row.getString(\"NAMH\"), row.getChildRows().get(0), task);\n }\n else\n {\n populateBar(row, task);\n createTasks(task, task.getName(), row.getChildRows());\n }\n }\n else\n {\n populateLeaf(parentName, row, task);\n }\n\n m_eventManager.fireTaskReadEvent(task);\n }\n }", "private void addHours(ProjectCalendarDateRanges ranges, Record hoursRecord)\n {\n if (hoursRecord.getValue() != null)\n {\n String[] wh = hoursRecord.getValue().split(\"\\\\|\");\n try\n {\n String startText;\n String endText;\n\n if (wh[0].equals(\"s\"))\n {\n startText = wh[1];\n endText = wh[3];\n }\n else\n {\n startText = wh[3];\n endText = wh[1];\n }\n\n // for end time treat midnight as midnight next day\n if (endText.equals(\"00:00\"))\n {\n endText = \"24:00\";\n }\n Date start = m_calendarTimeFormat.parse(startText);\n Date end = m_calendarTimeFormat.parse(endText);\n\n ranges.addRange(new DateRange(start, end));\n }\n catch (ParseException e)\n {\n // silently ignore date parse exceptions\n }\n }\n }", "public static int cudnnLRNCrossChannelBackward(\n cudnnHandle handle, \n cudnnLRNDescriptor normDesc, \n int lrnMode, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnLRNCrossChannelBackwardNative(handle, normDesc, lrnMode, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }", "public Channel sessionConnectGenerateChannel(Session session)\n throws JSchException {\n \t// set timeout\n session.connect(sshMeta.getSshConnectionTimeoutMillis());\n \n ChannelExec channel = (ChannelExec) session.openChannel(\"exec\");\n channel.setCommand(sshMeta.getCommandLine());\n\n // if run as super user, assuming the input stream expecting a password\n if (sshMeta.isRunAsSuperUser()) {\n \ttry {\n channel.setInputStream(null, true);\n\n OutputStream out = channel.getOutputStream();\n channel.setOutputStream(System.out, true);\n channel.setExtOutputStream(System.err, true);\n channel.setPty(true);\n channel.connect();\n \n\t out.write((sshMeta.getPassword()+\"\\n\").getBytes());\n\t out.flush();\n\t\t\t} catch (IOException e) {\n\t\t\t\tlogger.error(\"error in sessionConnectGenerateChannel for super user\", e);\n\t\t\t}\n } else {\n \tchannel.setInputStream(null);\n \tchannel.connect();\n }\n\n return channel;\n\n }", "public RedwoodConfiguration stderr(){\r\n LogRecordHandler visibility = new VisibilityHandler();\r\n LogRecordHandler console = Redwood.ConsoleHandler.err();\r\n return this\r\n .rootHandler(visibility)\r\n .handler(visibility, console);\r\n }", "public static dnstxtrec[] get(nitro_service service, String domain[]) throws Exception{\n\t\tif (domain !=null && domain.length>0) {\n\t\t\tdnstxtrec response[] = new dnstxtrec[domain.length];\n\t\t\tdnstxtrec obj[] = new dnstxtrec[domain.length];\n\t\t\tfor (int i=0;i<domain.length;i++) {\n\t\t\t\tobj[i] = new dnstxtrec();\n\t\t\t\tobj[i].set_domain(domain[i]);\n\t\t\t\tresponse[i] = (dnstxtrec) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "protected void updateLabelActiveStyle() {\n if (this.valueBoxBase.getText() != null && !this.valueBoxBase.getText().isEmpty()) {\n label.addStyleName(CssName.ACTIVE);\n } else {\n label.removeStyleName(CssName.ACTIVE);\n }\n }", "public static boolean isArrayOfUnboundedTypeVariablesOrObjects(Type[] types) {\n for (Type type : types) {\n if (Object.class.equals(type)) {\n continue;\n }\n if (type instanceof TypeVariable<?>) {\n Type[] bounds = ((TypeVariable<?>) type).getBounds();\n if (bounds == null || bounds.length == 0 || (bounds.length == 1 && Object.class.equals(bounds[0]))) {\n continue;\n }\n }\n return false;\n }\n return true;\n }" ]
Use this API to add route6.
[ "public static base_response add(nitro_service client, route6 resource) throws Exception {\n\t\troute6 addresource = new route6();\n\t\taddresource.network = resource.network;\n\t\taddresource.gateway = resource.gateway;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.weight = resource.weight;\n\t\taddresource.distance = resource.distance;\n\t\taddresource.cost = resource.cost;\n\t\taddresource.advertise = resource.advertise;\n\t\taddresource.msr = resource.msr;\n\t\taddresource.monitor = resource.monitor;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}" ]
[ "public List<BuildpackInstallation> listBuildpackInstallations(String appName) {\n return connection.execute(new BuildpackInstallationList(appName), apiKey);\n }", "public void setPerms(String photoId, GeoPermissions perms) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_PERMS);\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"is_public\", perms.isPublic() ? \"1\" : \"0\");\r\n parameters.put(\"is_contact\", perms.isContact() ? \"1\" : \"0\");\r\n parameters.put(\"is_friend\", perms.isFriend() ? \"1\" : \"0\");\r\n parameters.put(\"is_family\", perms.isFamily() ? \"1\" : \"0\");\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n // This method has no specific response - It returns an empty sucess response\r\n // if it completes without error.\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "public void setControllerModel(GVRSceneObject controllerModel)\n {\n if (mControllerModel != null)\n {\n mControllerGroup.removeChildObject(mControllerModel);\n }\n mControllerModel = controllerModel;\n mControllerGroup.addChildObject(mControllerModel);\n mControllerModel.setEnable(mShowControllerModel);\n }", "@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 setAttribute(final String name, final Attribute attribute) {\n if (name.equals(\"datasource\")) {\n this.allAttributes.putAll(((DataSourceAttribute) attribute).getAttributes());\n } else if (this.copyAttributes.contains(name)) {\n this.allAttributes.put(name, attribute);\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 }", "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}", "public StackTraceElement[] asStackTrace() {\n\t\tint i = 1;\n\t\tStackTraceElement[] list = new StackTraceElement[this.size()];\n\t\tfor (Eventable e : this) {\n\t\t\tlist[this.size() - i] =\n\t\t\t\t\tnew StackTraceElement(e.getEventType().toString(), e.getIdentification()\n\t\t\t\t\t\t\t.toString(), e.getElement().toString(), i);\n\t\t\ti++;\n\t\t}\n\t\treturn list;\n\t}", "public final void reset()\n {\n for (int i = 0; i < combinationIndices.length; i++)\n {\n combinationIndices[i] = i;\n }\n remainingCombinations = totalCombinations;\n }" ]
Export modules and check them in. Assumes the log stream already open. @return exit code of the commit-script.
[ "private int checkInInternal() {\n\n m_logStream.println(\"[\" + new Date() + \"] STARTING Git task\");\n m_logStream.println(\"=========================\");\n m_logStream.println();\n\n if (m_checkout) {\n m_logStream.println(\"Running checkout script\");\n\n } else if (!(m_resetHead || m_resetRemoteHead)) {\n m_logStream.println(\"Exporting relevant modules\");\n m_logStream.println(\"--------------------------\");\n m_logStream.println();\n\n exportModules();\n\n m_logStream.println();\n m_logStream.println(\"Calling script to check in the exports\");\n m_logStream.println(\"--------------------------------------\");\n m_logStream.println();\n\n } else {\n\n m_logStream.println();\n m_logStream.println(\"Calling script to reset the repository\");\n m_logStream.println(\"--------------------------------------\");\n m_logStream.println();\n\n }\n\n int exitCode = runCommitScript();\n if (exitCode != 0) {\n m_logStream.println();\n m_logStream.println(\"ERROR: Something went wrong. The script got exitcode \" + exitCode + \".\");\n m_logStream.println();\n }\n if ((exitCode == 0) && m_checkout) {\n boolean importOk = importModules();\n if (!importOk) {\n return -1;\n }\n }\n m_logStream.println(\"[\" + new Date() + \"] FINISHED Git task\");\n m_logStream.println();\n m_logStream.close();\n\n return exitCode;\n }" ]
[ "public static Iterable<BoxFileVersionRetention.Info> getAll(BoxAPIConnection api, String ... fields) {\n return getRetentions(api, new QueryFilter(), fields);\n }", "public Optional<Project> findProject(String name) throws IllegalArgumentException {\n if (name == null || name.isEmpty()) {\n throw new IllegalArgumentException(\"Project name cannot be empty\");\n }\n return getProject(name);\n }", "static String findNonProgressingOp(Resource resource, boolean forServer, long timeout) throws OperationFailedException {\n\n Resource.ResourceEntry nonProgressing = null;\n for (Resource.ResourceEntry child : resource.getChildren(ACTIVE_OPERATION)) {\n ModelNode model = child.getModel();\n if (model.get(EXCLUSIVE_RUNNING_TIME).asLong() > timeout) {\n nonProgressing = child;\n ControllerLogger.MGMT_OP_LOGGER.tracef(\"non-progressing op: %s\", nonProgressing.getModel());\n break;\n }\n }\n if (nonProgressing != null && !forServer) {\n // WFCORE-263\n // See if the op is non-progressing because it's the HC op waiting for commit\n // from the DC while other ops (i.e. ops proxied to our servers) associated\n // with the same domain-uuid are not completing\n ModelNode model = nonProgressing.getModel();\n if (model.get(DOMAIN_ROLLOUT).asBoolean()\n && OperationContext.ExecutionStatus.COMPLETING.toString().equals(model.get(EXECUTION_STATUS).asString())\n && model.hasDefined(DOMAIN_UUID)) {\n ControllerLogger.MGMT_OP_LOGGER.trace(\"Potential domain rollout issue\");\n String domainUUID = model.get(DOMAIN_UUID).asString();\n\n Set<String> relatedIds = null;\n List<Resource.ResourceEntry> relatedExecutingOps = null;\n for (Resource.ResourceEntry activeOp : resource.getChildren(ACTIVE_OPERATION)) {\n if (nonProgressing.getName().equals(activeOp.getName())) {\n continue; // ignore self\n }\n ModelNode opModel = activeOp.getModel();\n if (opModel.hasDefined(DOMAIN_UUID) && domainUUID.equals(opModel.get(DOMAIN_UUID).asString())\n && opModel.get(RUNNING_TIME).asLong() > timeout) {\n if (relatedIds == null) {\n relatedIds = new TreeSet<String>(); // order these as an aid to unit testing\n }\n relatedIds.add(activeOp.getName());\n\n // If the op is ExecutionStatus.EXECUTING that means it's still EXECUTING on the\n // server or a prepare message got lost. It would be COMPLETING if the server\n // had sent a prepare message, as that would result in ProxyStepHandler calling completeStep\n if (OperationContext.ExecutionStatus.EXECUTING.toString().equals(opModel.get(EXECUTION_STATUS).asString())) {\n if (relatedExecutingOps == null) {\n relatedExecutingOps = new ArrayList<Resource.ResourceEntry>();\n }\n relatedExecutingOps.add(activeOp);\n ControllerLogger.MGMT_OP_LOGGER.tracef(\"Related executing: %s\", opModel);\n } else ControllerLogger.MGMT_OP_LOGGER.tracef(\"Related non-executing: %s\", opModel);\n } else ControllerLogger.MGMT_OP_LOGGER.tracef(\"unrelated: %s\", opModel);\n }\n\n if (relatedIds != null) {\n // There are other ops associated with this domain-uuid that are also not completing\n // in the desired time, so we can't treat the one holding the lock as the problem.\n if (relatedExecutingOps != null && relatedExecutingOps.size() == 1) {\n // There's a single related op that's executing for too long. So we can report that one.\n // Note that it's possible that the same problem exists on other hosts as well\n // and that this cancellation will not resolve the overall problem. But, we only\n // get here on a slave HC and if the user is invoking this on a slave and not the\n // master, we'll assume they have a reason for doing that and want us to treat this\n // as a problem on this particular host.\n nonProgressing = relatedExecutingOps.get(0);\n } else {\n // Fail and provide a useful failure message.\n throw DomainManagementLogger.ROOT_LOGGER.domainRolloutNotProgressing(nonProgressing.getName(),\n timeout, domainUUID, relatedIds);\n }\n }\n }\n }\n\n return nonProgressing == null ? null : nonProgressing.getName();\n }", "protected Class<?> classForName(String name) {\n try {\n return resourceLoader.classForName(name);\n } catch (ResourceLoadingException cnfe) {\n return DUMMY_CLASS;\n }\n }", "public void addDateTimeHelper(int ds, Date date) throws SerializationException, InvalidDataSetException {\r\n\t\tif (date == null) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tDataSetInfo dsi = dsiFactory.create(ds);\r\n\r\n\t\tSimpleDateFormat df = new SimpleDateFormat(dsi.getSerializer().toString());\r\n\t\tString value = df.format(date);\r\n\t\tbyte[] data = dsi.getSerializer().serialize(value, activeSerializationContext);\r\n\t\tDataSet dataSet = new DefaultDataSet(dsi, data);\r\n\t\tadd(dataSet);\r\n\t}", "@SuppressWarnings(\"unchecked\")\n public Map<BsonValue, ChangeEvent<BsonDocument>> getEvents() {\n nsLock.readLock().lock();\n final Map<BsonValue, ChangeEvent<BsonDocument>> events;\n try {\n events = new HashMap<>(this.events);\n } finally {\n nsLock.readLock().unlock();\n }\n\n nsLock.writeLock().lock();\n try {\n this.events.clear();\n return events;\n } finally {\n nsLock.writeLock().unlock();\n }\n }", "public static base_responses delete(nitro_service client, nsip6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsip6 deleteresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new nsip6();\n\t\t\t\tdeleteresources[i].ipv6address = resources[i].ipv6address;\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}", "public static lbvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_cachepolicy_binding obj = new lbvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_cachepolicy_binding response[] = (lbvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public Object getJavaDefaultValueDefault() {\n\t\tif (field.getType() == boolean.class) {\n\t\t\treturn DEFAULT_VALUE_BOOLEAN;\n\t\t} else if (field.getType() == byte.class || field.getType() == Byte.class) {\n\t\t\treturn DEFAULT_VALUE_BYTE;\n\t\t} else if (field.getType() == char.class || field.getType() == Character.class) {\n\t\t\treturn DEFAULT_VALUE_CHAR;\n\t\t} else if (field.getType() == short.class || field.getType() == Short.class) {\n\t\t\treturn DEFAULT_VALUE_SHORT;\n\t\t} else if (field.getType() == int.class || field.getType() == Integer.class) {\n\t\t\treturn DEFAULT_VALUE_INT;\n\t\t} else if (field.getType() == long.class || field.getType() == Long.class) {\n\t\t\treturn DEFAULT_VALUE_LONG;\n\t\t} else if (field.getType() == float.class || field.getType() == Float.class) {\n\t\t\treturn DEFAULT_VALUE_FLOAT;\n\t\t} else if (field.getType() == double.class || field.getType() == Double.class) {\n\t\t\treturn DEFAULT_VALUE_DOUBLE;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}" ]
Byte run automaton map. @param automatonMap the automaton map @return the map
[ "public static Map<String, ByteRunAutomaton> byteRunAutomatonMap(\n Map<String, Automaton> automatonMap) {\n HashMap<String, ByteRunAutomaton> byteRunAutomatonMap = new HashMap<>();\n if (automatonMap != null) {\n for (Entry<String, Automaton> entry : automatonMap.entrySet()) {\n byteRunAutomatonMap.put(entry.getKey(),\n new ByteRunAutomaton(entry.getValue()));\n }\n }\n return byteRunAutomatonMap;\n }" ]
[ "protected void runScript(File script) {\n if (!script.exists()) {\n JOptionPane.showMessageDialog(cliGuiCtx.getMainPanel(), script.getAbsolutePath() + \" does not exist.\",\n \"Unable to run script.\", JOptionPane.ERROR_MESSAGE);\n return;\n }\n\n int choice = JOptionPane.showConfirmDialog(cliGuiCtx.getMainPanel(), \"Run CLI script \" + script.getName() + \"?\",\n \"Confirm run script\", JOptionPane.YES_NO_OPTION);\n if (choice != JOptionPane.YES_OPTION) return;\n\n menu.addScript(script);\n\n cliGuiCtx.getTabs().setSelectedIndex(1); // set to Output tab to view the output\n output.post(\"\\n\");\n\n SwingWorker scriptRunner = new ScriptRunner(script);\n scriptRunner.execute();\n }", "private 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 }", "protected synchronized void releaseBroker(PersistenceBroker broker)\r\n {\r\n /*\r\n arminw:\r\n only close the broker instance if we get\r\n it from the PBF, do nothing if we obtain it from\r\n PBThreadMapping\r\n */\r\n if (broker != null && _needsClose)\r\n {\r\n _needsClose = false;\r\n broker.close();\r\n }\r\n }", "private void updateBundleDescriptorContent() throws CmsXmlException {\n\n if (m_descContent.hasLocale(Descriptor.LOCALE)) {\n m_descContent.removeLocale(Descriptor.LOCALE);\n }\n m_descContent.addLocale(m_cms, Descriptor.LOCALE);\n\n int i = 0;\n Property<Object> descProp;\n String desc;\n Property<Object> defaultValueProp;\n String defaultValue;\n Map<String, Item> keyItemMap = getKeyItemMap();\n List<String> keys = new ArrayList<String>(keyItemMap.keySet());\n Collections.sort(keys, CmsCaseInsensitiveStringComparator.getInstance());\n for (Object key : keys) {\n if ((null != key) && !key.toString().isEmpty()) {\n\n m_descContent.addValue(m_cms, Descriptor.N_MESSAGE, Descriptor.LOCALE, i);\n i++;\n String messagePrefix = Descriptor.N_MESSAGE + \"[\" + i + \"]/\";\n\n m_descContent.getValue(messagePrefix + Descriptor.N_KEY, Descriptor.LOCALE).setStringValue(\n m_cms,\n (String)key);\n descProp = keyItemMap.get(key).getItemProperty(TableProperty.DESCRIPTION);\n if ((null != descProp) && (null != descProp.getValue())) {\n desc = descProp.getValue().toString();\n m_descContent.getValue(messagePrefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).setStringValue(\n m_cms,\n desc);\n }\n\n defaultValueProp = keyItemMap.get(key).getItemProperty(TableProperty.DEFAULT);\n if ((null != defaultValueProp) && (null != defaultValueProp.getValue())) {\n defaultValue = defaultValueProp.getValue().toString();\n m_descContent.getValue(messagePrefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).setStringValue(\n m_cms,\n defaultValue);\n }\n\n }\n }\n\n }", "private void sortFileList() {\n if (this.size() > 1) {\n Collections.sort(this.fileList, new Comparator() {\n\n public final int compare(final Object o1, final Object o2) {\n final File f1 = (File) o1;\n final File f2 = (File) o2;\n final Object[] f1TimeAndCount = backupSuffixHelper\n .backupTimeAndCount(f1.getName(), baseFile);\n final Object[] f2TimeAndCount = backupSuffixHelper\n .backupTimeAndCount(f2.getName(), baseFile);\n final long f1TimeSuffix = ((Long) f1TimeAndCount[0]).longValue();\n final long f2TimeSuffix = ((Long) f2TimeAndCount[0]).longValue();\n if ((0L == f1TimeSuffix) && (0L == f2TimeSuffix)) {\n final long f1Time = f1.lastModified();\n final long f2Time = f2.lastModified();\n if (f1Time < f2Time) {\n return -1;\n }\n if (f1Time > f2Time) {\n return 1;\n }\n return 0;\n }\n if (f1TimeSuffix < f2TimeSuffix) {\n return -1;\n }\n if (f1TimeSuffix > f2TimeSuffix) {\n return 1;\n }\n final int f1Count = ((Integer) f1TimeAndCount[1]).intValue();\n final int f2Count = ((Integer) f2TimeAndCount[1]).intValue();\n if (f1Count < f2Count) {\n return -1;\n }\n if (f1Count > f2Count) {\n return 1;\n }\n if (f1Count == f2Count) {\n if (fileHelper.isCompressed(f1)) {\n return -1;\n }\n if (fileHelper.isCompressed(f2)) {\n return 1;\n }\n }\n return 0;\n }\n });\n }\n }", "public static void registerMbean(MBeanServer server, ModelMBean mbean, ObjectName name) {\n try {\n synchronized(LOCK) {\n if(server.isRegistered(name))\n JmxUtils.unregisterMbean(server, name);\n server.registerMBean(mbean, name);\n }\n } catch(Exception e) {\n logger.error(\"Error registering mbean:\", e);\n }\n }", "public static auditsyslogpolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_vpnglobal_binding obj = new auditsyslogpolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_vpnglobal_binding response[] = (auditsyslogpolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static base_response add(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup addresource = new cachecontentgroup();\n\t\taddresource.name = resource.name;\n\t\taddresource.weakposrelexpiry = resource.weakposrelexpiry;\n\t\taddresource.heurexpiryparam = resource.heurexpiryparam;\n\t\taddresource.relexpiry = resource.relexpiry;\n\t\taddresource.relexpirymillisec = resource.relexpirymillisec;\n\t\taddresource.absexpiry = resource.absexpiry;\n\t\taddresource.absexpirygmt = resource.absexpirygmt;\n\t\taddresource.weaknegrelexpiry = resource.weaknegrelexpiry;\n\t\taddresource.hitparams = resource.hitparams;\n\t\taddresource.invalparams = resource.invalparams;\n\t\taddresource.ignoreparamvaluecase = resource.ignoreparamvaluecase;\n\t\taddresource.matchcookies = resource.matchcookies;\n\t\taddresource.invalrestrictedtohost = resource.invalrestrictedtohost;\n\t\taddresource.polleverytime = resource.polleverytime;\n\t\taddresource.ignorereloadreq = resource.ignorereloadreq;\n\t\taddresource.removecookies = resource.removecookies;\n\t\taddresource.prefetch = resource.prefetch;\n\t\taddresource.prefetchperiod = resource.prefetchperiod;\n\t\taddresource.prefetchperiodmillisec = resource.prefetchperiodmillisec;\n\t\taddresource.prefetchmaxpending = resource.prefetchmaxpending;\n\t\taddresource.flashcache = resource.flashcache;\n\t\taddresource.expireatlastbyte = resource.expireatlastbyte;\n\t\taddresource.insertvia = resource.insertvia;\n\t\taddresource.insertage = resource.insertage;\n\t\taddresource.insertetag = resource.insertetag;\n\t\taddresource.cachecontrol = resource.cachecontrol;\n\t\taddresource.quickabortsize = resource.quickabortsize;\n\t\taddresource.minressize = resource.minressize;\n\t\taddresource.maxressize = resource.maxressize;\n\t\taddresource.memlimit = resource.memlimit;\n\t\taddresource.ignorereqcachinghdrs = resource.ignorereqcachinghdrs;\n\t\taddresource.minhits = resource.minhits;\n\t\taddresource.alwaysevalpolicies = resource.alwaysevalpolicies;\n\t\taddresource.persist = resource.persist;\n\t\taddresource.pinned = resource.pinned;\n\t\taddresource.lazydnsresolve = resource.lazydnsresolve;\n\t\taddresource.hitselector = resource.hitselector;\n\t\taddresource.invalselector = resource.invalselector;\n\t\taddresource.type = resource.type;\n\t\treturn addresource.add_resource(client);\n\t}", "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 }" ]
We have received an update that invalidates any previous metadata for that player, so clear it out, and alert any listeners if this represents a change. This does not affect the hot cues; they will stick around until the player loads a new track that overwrites one or more of them. @param update the update which means we can have no metadata for the associated player
[ "private void clearDeck(CdjStatus update) {\n if (hotCache.remove(DeckReference.getDeckReference(update.getDeviceNumber(), 0)) != null) {\n deliverTrackMetadataUpdate(update.getDeviceNumber(), null);\n }\n }" ]
[ "private void readProjectHeader()\n {\n Table table = m_tables.get(\"DIR\");\n MapRow row = table.find(\"\");\n if (row != null)\n {\n setFields(PROJECT_FIELDS, row, m_projectFile.getProjectProperties());\n m_wbsFormat = new P3WbsFormat(row);\n }\n }", "public String validationErrors() {\n\n List<String> errors = new ArrayList<>();\n for (File config : getConfigFiles()) {\n String filename = config.getName();\n try (FileInputStream stream = new FileInputStream(config)) {\n CmsXmlUtils.unmarshalHelper(CmsFileUtil.readFully(stream, false), new CmsXmlEntityResolver(null), true);\n } catch (CmsXmlException e) {\n errors.add(filename + \":\" + e.getCause().getMessage());\n } catch (Exception e) {\n errors.add(filename + \":\" + e.getMessage());\n }\n }\n if (errors.size() == 0) {\n return null;\n }\n String errString = CmsStringUtil.listAsString(errors, \"\\n\");\n JSONObject obj = new JSONObject();\n try {\n obj.put(\"err\", errString);\n } catch (JSONException e) {\n\n }\n return obj.toString();\n }", "public boolean load()\r\n {\r\n \t_load();\r\n \tjava.util.Iterator it = this.alChildren.iterator();\r\n \twhile (it.hasNext())\r\n \t{\r\n \t\tObject o = it.next();\r\n \t\tif (o instanceof OjbMetaTreeNode) ((OjbMetaTreeNode)o).load();\r\n \t}\r\n \treturn true;\r\n }", "public void init( DMatrixRMaj A ) {\n if( A.numRows != A.numCols)\n throw new IllegalArgumentException(\"Must be square\");\n\n if( A.numCols != N ) {\n N = A.numCols;\n QT.reshape(N,N, false);\n\n if( w.length < N ) {\n w = new double[ N ];\n gammas = new double[N];\n b = new double[N];\n }\n }\n\n // just copy the top right triangle\n QT.set(A);\n }", "public void setAppender(final Appender appender) {\n if (this.appender != null) {\n close();\n }\n checkAccess(this);\n if (applyLayout && appender != null) {\n final Formatter formatter = getFormatter();\n appender.setLayout(formatter == null ? null : new FormatterLayout(formatter));\n }\n appenderUpdater.set(this, appender);\n }", "public static String changeFileNameSuffixTo(String filename, String suffix) {\n\n int dotPos = filename.lastIndexOf('.');\n if (dotPos != -1) {\n return filename.substring(0, dotPos + 1) + suffix;\n } else {\n // the string has no suffix\n return filename;\n }\n }", "public boolean clearSelection(boolean requestLayout) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"clearSelection [%d]\", mSelectedItemsList.size());\n\n boolean updateLayout = false;\n List<ListItemHostWidget> views = getAllHosts();\n for (ListItemHostWidget host: views) {\n if (host.isSelected()) {\n host.setSelected(false);\n updateLayout = true;\n if (requestLayout) {\n host.requestLayout();\n }\n }\n }\n clearSelectedItemsList();\n return updateLayout;\n }", "private License getLicense(final String licenseId) {\n License result = null;\n final Set<DbLicense> matchingLicenses = licenseMatcher.getMatchingLicenses(licenseId);\n\n if (matchingLicenses.isEmpty()) {\n result = DataModelFactory.createLicense(\"#\" + licenseId + \"# (to be identified)\", NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET);\n result.setUnknown(true);\n } else {\n if (matchingLicenses.size() > 1 && LOG.isWarnEnabled()) {\n LOG.warn(String.format(\"%s matches multiple licenses %s. \" +\n \"Please run the report showing multiple matching on licenses\",\n licenseId, matchingLicenses.toString()));\n }\n result = mapper.getLicense(matchingLicenses.iterator().next());\n\n }\n\n return result;\n }", "public String getOriginalValue(ParsedCommandLine parsedLine, boolean required) throws CommandFormatException {\n String value = null;\n if(parsedLine.hasProperties()) {\n if(index >= 0) {\n List<String> others = parsedLine.getOtherProperties();\n if(others.size() > index) {\n return others.get(index);\n }\n }\n\n value = parsedLine.getPropertyValue(fullName);\n if(value == null && shortName != null) {\n value = parsedLine.getPropertyValue(shortName);\n }\n }\n\n if(required && value == null && !isPresent(parsedLine)) {\n StringBuilder buf = new StringBuilder();\n buf.append(\"Required argument \");\n buf.append('\\'').append(fullName).append('\\'');\n buf.append(\" is missing.\");\n throw new CommandFormatException(buf.toString());\n }\n return value;\n }" ]
Add exceptions to the calendar. @param mpxjCalendar MPXJ calendar @param gpCalendar GanttProject calendar
[ "private void setExceptions(ProjectCalendar mpxjCalendar, Calendars gpCalendar)\n {\n List<net.sf.mpxj.ganttproject.schema.Date> dates = gpCalendar.getDate();\n for (net.sf.mpxj.ganttproject.schema.Date date : dates)\n {\n addException(mpxjCalendar, date);\n }\n }" ]
[ "public static String replaceFirst(final CharSequence self, final CharSequence regex, final CharSequence replacement) {\n return self.toString().replaceFirst(regex.toString(), replacement.toString());\n }", "public void setSlideDrawable(Drawable drawable) {\n mSlideDrawable = new SlideDrawable(drawable);\n mSlideDrawable.setIsRtl(ViewHelper.getLayoutDirection(this) == LAYOUT_DIRECTION_RTL);\n\n if (mActionBarHelper != null) {\n mActionBarHelper.setDisplayShowHomeAsUpEnabled(true);\n\n if (mDrawerIndicatorEnabled) {\n mActionBarHelper.setActionBarUpIndicator(mSlideDrawable,\n isMenuVisible() ? mDrawerOpenContentDesc : mDrawerClosedContentDesc);\n }\n }\n }", "public float getBoundsDepth() {\n if (mSceneObject != null) {\n GVRSceneObject.BoundingVolume v = mSceneObject.getBoundingVolume();\n return v.maxCorner.z - v.minCorner.z;\n }\n return 0f;\n }", "public static String get(String url, Map<String, String> customHeaders, Map<String, String> params) throws URISyntaxException, IOException, HTTPException {\n LOGGER.log(Level.INFO, \"Sending GET request to the url {0}\", url);\n\n URIBuilder uriBuilder = new URIBuilder(url);\n\n if (params != null && params.size() > 0) {\n for (Map.Entry<String, String> param : params.entrySet()) {\n uriBuilder.setParameter(param.getKey(), param.getValue());\n }\n }\n\n HttpGet httpGet = new HttpGet(uriBuilder.build());\n\n populateHeaders(httpGet, customHeaders);\n\n HttpClient httpClient = HttpClientBuilder.create().build();\n\n HttpResponse httpResponse = httpClient.execute(httpGet);\n\n int statusCode = httpResponse.getStatusLine().getStatusCode();\n if (isErrorStatus(statusCode)) {\n String jsonErrorResponse = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);\n throw new HTTPException(statusCode, httpResponse.getStatusLine().getReasonPhrase(), jsonErrorResponse);\n }\n\n return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);\n }", "@Override\n public void process() {\n if (client.isDone() || executorService.isTerminated()) {\n throw new IllegalStateException(\"Client is already stopped\");\n }\n Runnable runner = new Runnable() {\n @Override\n public void run() {\n try {\n while (!client.isDone()) {\n String msg = messageQueue.take();\n try {\n parseMessage(msg);\n } catch (Exception e) {\n logger.warn(\"Exception thrown during parsing msg \" + msg, e);\n onException(e);\n }\n }\n } catch (Exception e) {\n onException(e);\n }\n }\n };\n\n executorService.execute(runner);\n }", "private void readZookeeperConfig() {\n\n try (CuratorFramework curator = CuratorUtil.newAppCurator(config)) {\n curator.start();\n\n accumuloInstance =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_NAME),\n StandardCharsets.UTF_8);\n accumuloInstanceID =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_ID),\n StandardCharsets.UTF_8);\n fluoApplicationID =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID),\n StandardCharsets.UTF_8);\n\n table = new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_TABLE),\n StandardCharsets.UTF_8);\n\n observers = ObserverUtil.load(curator);\n\n config = FluoAdminImpl.mergeZookeeperConfig(config);\n\n // make sure not to include config passed to env, only want config from zookeeper\n appConfig = config.getAppConfiguration();\n } catch (Exception e) {\n throw new IllegalStateException(e);\n }\n }", "public static ReportGenerator.Format getFormat( String... args ) {\n ConfigOptionParser configParser = new ConfigOptionParser();\n List<ConfigOption> configOptions = Arrays.asList( format, help );\n\n for( ConfigOption co : configOptions ) {\n if( co.hasDefault() ) {\n configParser.parsedOptions.put( co.getLongName(), co.getValue() );\n }\n }\n\n for( String arg : args ) {\n configParser.commandLineLookup( arg, format, configOptions );\n }\n\n // TODO properties\n // TODO environment\n\n if( !configParser.hasValue( format ) ) {\n configParser.printUsageAndExit( configOptions );\n }\n return (ReportGenerator.Format) configParser.getValue( format );\n }", "public CentralDogmaBuilder port(InetSocketAddress localAddress, SessionProtocol protocol) {\n return port(new ServerPort(localAddress, protocol));\n }", "public static String md5sum(InputStream input) throws IOException {\r\n InputStream in = new BufferedInputStream(input);\r\n try {\r\n MessageDigest digest = java.security.MessageDigest.getInstance(\"MD5\");\r\n DigestInputStream digestInputStream = new DigestInputStream(in, digest);\r\n while(digestInputStream.read() >= 0) {\r\n }\r\n OutputStream md5out = new ByteArrayOutputStream();\r\n md5out.write(digest.digest());\r\n return md5out.toString();\r\n }\r\n catch(NoSuchAlgorithmException e) {\r\n throw new IllegalStateException(\"MD5 algorithm is not available: \" + e.getMessage());\r\n }\r\n finally {\r\n in.close();\r\n }\r\n }" ]
waits for all async mutations that were added before this was called to be flushed. Does not wait for async mutations added after call.
[ "public void waitForAsyncFlush() {\n long numAdded = asyncBatchesAdded.get();\n\n synchronized (this) {\n while (numAdded > asyncBatchesProcessed) {\n try {\n wait();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n }\n }" ]
[ "public static lbvserver[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tlbvserver obj = new lbvserver();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tlbvserver[] response = (lbvserver[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "private void createResults(List<ISuite> suites,\n File outputDirectory,\n boolean onlyShowFailures) throws Exception\n {\n int index = 1;\n for (ISuite suite : suites)\n {\n int index2 = 1;\n for (ISuiteResult result : suite.getResults().values())\n {\n boolean failuresExist = result.getTestContext().getFailedTests().size() > 0\n || result.getTestContext().getFailedConfigurations().size() > 0;\n if (!onlyShowFailures || failuresExist)\n {\n VelocityContext context = createContext();\n context.put(RESULT_KEY, result);\n context.put(FAILED_CONFIG_KEY, sortByTestClass(result.getTestContext().getFailedConfigurations()));\n context.put(SKIPPED_CONFIG_KEY, sortByTestClass(result.getTestContext().getSkippedConfigurations()));\n context.put(FAILED_TESTS_KEY, sortByTestClass(result.getTestContext().getFailedTests()));\n context.put(SKIPPED_TESTS_KEY, sortByTestClass(result.getTestContext().getSkippedTests()));\n context.put(PASSED_TESTS_KEY, sortByTestClass(result.getTestContext().getPassedTests()));\n String fileName = String.format(\"suite%d_test%d_%s\", index, index2, RESULTS_FILE);\n generateFile(new File(outputDirectory, fileName),\n RESULTS_FILE + TEMPLATE_EXTENSION,\n context);\n }\n ++index2;\n }\n ++index;\n }\n }", "public Configuration[] getConfigurations(String name) {\n ArrayList<Configuration> valuesList = new ArrayList<Configuration>();\n\n logger.info(\"Getting data for {}\", name);\n\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n\n String queryString = \"SELECT * FROM \" + Constants.DB_TABLE_CONFIGURATION;\n if (name != null) {\n queryString += \" WHERE \" + Constants.DB_TABLE_CONFIGURATION_NAME + \"=?\";\n }\n\n statement = sqlConnection.prepareStatement(queryString);\n if (name != null) {\n statement.setString(1, name);\n }\n\n results = statement.executeQuery();\n while (results.next()) {\n Configuration config = new Configuration();\n config.setValue(results.getString(Constants.DB_TABLE_CONFIGURATION_VALUE));\n config.setKey(results.getString(Constants.DB_TABLE_CONFIGURATION_NAME));\n config.setId(results.getInt(Constants.GENERIC_ID));\n logger.info(\"the configValue is = {}\", config.getValue());\n valuesList.add(config);\n }\n } catch (SQLException sqe) {\n logger.info(\"Exception in sql\");\n sqe.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n if (valuesList.size() == 0) {\n return null;\n }\n\n return valuesList.toArray(new Configuration[0]);\n }", "public static int restrictRange(int value, int min, int max)\n {\n return Math.min((Math.max(value, min)), max);\n }", "public String processObjectCache(Properties attributes) throws XDocletException\r\n {\r\n ObjectCacheDef objCacheDef = _curClassDef.setObjectCache(attributes.getProperty(ATTRIBUTE_CLASS));\r\n String attrName;\r\n\r\n attributes.remove(ATTRIBUTE_CLASS);\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n objCacheDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }", "private void unmarshalDescriptor() throws CmsXmlException, CmsException {\n\n if (null != m_desc) {\n\n // unmarshal descriptor\n m_descContent = CmsXmlContentFactory.unmarshal(m_cms, m_cms.readFile(m_desc));\n\n // configure messages if wanted\n CmsProperty bundleProp = m_cms.readPropertyObject(m_desc, PROPERTY_BUNDLE_DESCRIPTOR_LOCALIZATION, true);\n if (!(bundleProp.isNullProperty() || bundleProp.getValue().trim().isEmpty())) {\n m_configuredBundle = bundleProp.getValue();\n }\n }\n\n }", "private void setWorkingDays(ProjectCalendar mpxjCalendar, Calendars gpCalendar)\n {\n DayTypes dayTypes = gpCalendar.getDayTypes();\n DefaultWeek defaultWeek = dayTypes.getDefaultWeek();\n if (defaultWeek == null)\n {\n mpxjCalendar.setWorkingDay(Day.SUNDAY, false);\n mpxjCalendar.setWorkingDay(Day.MONDAY, true);\n mpxjCalendar.setWorkingDay(Day.TUESDAY, true);\n mpxjCalendar.setWorkingDay(Day.WEDNESDAY, true);\n mpxjCalendar.setWorkingDay(Day.THURSDAY, true);\n mpxjCalendar.setWorkingDay(Day.FRIDAY, true);\n mpxjCalendar.setWorkingDay(Day.SATURDAY, false);\n }\n else\n {\n mpxjCalendar.setWorkingDay(Day.MONDAY, isWorkingDay(defaultWeek.getMon()));\n mpxjCalendar.setWorkingDay(Day.TUESDAY, isWorkingDay(defaultWeek.getTue()));\n mpxjCalendar.setWorkingDay(Day.WEDNESDAY, isWorkingDay(defaultWeek.getWed()));\n mpxjCalendar.setWorkingDay(Day.THURSDAY, isWorkingDay(defaultWeek.getThu()));\n mpxjCalendar.setWorkingDay(Day.FRIDAY, isWorkingDay(defaultWeek.getFri()));\n mpxjCalendar.setWorkingDay(Day.SATURDAY, isWorkingDay(defaultWeek.getSat()));\n mpxjCalendar.setWorkingDay(Day.SUNDAY, isWorkingDay(defaultWeek.getSun()));\n }\n\n for (Day day : Day.values())\n {\n if (mpxjCalendar.isWorkingDay(day))\n {\n ProjectCalendarHours hours = mpxjCalendar.addCalendarHours(day);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\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 }", "public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo info)\r\n\t{\r\n\t\tUtil.log(\"In OTMJCAManagedConnectionFactory.createManagedConnection\");\r\n\t\ttry\r\n\t\t{\r\n\t\t\tKit kit = getKit();\r\n\t\t\tPBKey key = ((OTMConnectionRequestInfo) info).getPbKey();\r\n\t\t\tOTMConnection connection = kit.acquireConnection(key);\r\n\t\t\treturn new OTMJCAManagedConnection(this, connection, key);\r\n\t\t}\r\n\t\tcatch (ResourceException e)\r\n\t\t{\r\n\t\t\tthrow new OTMConnectionRuntimeException(e.getMessage());\r\n\t\t}\r\n\t}" ]
Build a Dataset from some data. @param oldData This {@link Dataset} represents data for which we which to some features, specifically those features not in the {@link edu.stanford.nlp.util.Index} goodFeatures. @param goodFeatures An {@link edu.stanford.nlp.util.Index} of features we wish to retain. @return A new {@link Dataset} wheres each datapoint contains only features which were in goodFeatures.
[ "public Dataset<String, String> getDataset(Dataset<String, String> oldData, Index<String> goodFeatures) {\r\n //public Dataset getDataset(List data, Collection goodFeatures) {\r\n //makeAnswerArraysAndTagIndex(data);\r\n\r\n int[][] oldDataArray = oldData.getDataArray();\r\n int[] oldLabelArray = oldData.getLabelsArray();\r\n Index<String> oldFeatureIndex = oldData.featureIndex;\r\n\r\n int[] oldToNewFeatureMap = new int[oldFeatureIndex.size()];\r\n\r\n int[][] newDataArray = new int[oldDataArray.length][];\r\n\r\n System.err.print(\"Building reduced dataset...\");\r\n\r\n int size = oldFeatureIndex.size();\r\n int max = 0;\r\n for (int i = 0; i < size; i++) {\r\n oldToNewFeatureMap[i] = goodFeatures.indexOf(oldFeatureIndex.get(i));\r\n if (oldToNewFeatureMap[i] > max) {\r\n max = oldToNewFeatureMap[i];\r\n }\r\n }\r\n\r\n for (int i = 0; i < oldDataArray.length; i++) {\r\n int[] data = oldDataArray[i];\r\n size = 0;\r\n for (int j = 0; j < data.length; j++) {\r\n if (oldToNewFeatureMap[data[j]] > 0) {\r\n size++;\r\n }\r\n }\r\n int[] newData = new int[size];\r\n int index = 0;\r\n for (int j = 0; j < data.length; j++) {\r\n int f = oldToNewFeatureMap[data[j]];\r\n if (f > 0) {\r\n newData[index++] = f;\r\n }\r\n }\r\n newDataArray[i] = newData;\r\n }\r\n\r\n Dataset<String, String> train = new Dataset<String, String>(oldData.labelIndex, oldLabelArray, goodFeatures, newDataArray, newDataArray.length);\r\n\r\n System.err.println(\"done.\");\r\n if (flags.featThreshFile != null) {\r\n System.err.println(\"applying thresholds...\");\r\n List<Pair<Pattern,Integer>> thresh = getThresholds(flags.featThreshFile);\r\n train.applyFeatureCountThreshold(thresh);\r\n } else if (flags.featureThreshold > 1) {\r\n System.err.println(\"Removing Features with counts < \" + flags.featureThreshold);\r\n train.applyFeatureCountThreshold(flags.featureThreshold);\r\n }\r\n train.summaryStatistics();\r\n return train;\r\n }" ]
[ "public static base_response update(nitro_service client, nsacl6 resource) throws Exception {\n\t\tnsacl6 updateresource = new nsacl6();\n\t\tupdateresource.acl6name = resource.acl6name;\n\t\tupdateresource.aclaction = resource.aclaction;\n\t\tupdateresource.srcipv6 = resource.srcipv6;\n\t\tupdateresource.srcipop = resource.srcipop;\n\t\tupdateresource.srcipv6val = resource.srcipv6val;\n\t\tupdateresource.srcport = resource.srcport;\n\t\tupdateresource.srcportop = resource.srcportop;\n\t\tupdateresource.srcportval = resource.srcportval;\n\t\tupdateresource.destipv6 = resource.destipv6;\n\t\tupdateresource.destipop = resource.destipop;\n\t\tupdateresource.destipv6val = resource.destipv6val;\n\t\tupdateresource.destport = resource.destport;\n\t\tupdateresource.destportop = resource.destportop;\n\t\tupdateresource.destportval = resource.destportval;\n\t\tupdateresource.srcmac = resource.srcmac;\n\t\tupdateresource.protocol = resource.protocol;\n\t\tupdateresource.protocolnumber = resource.protocolnumber;\n\t\tupdateresource.icmptype = resource.icmptype;\n\t\tupdateresource.icmpcode = resource.icmpcode;\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.Interface = resource.Interface;\n\t\tupdateresource.priority = resource.priority;\n\t\tupdateresource.established = resource.established;\n\t\treturn updateresource.update_resource(client);\n\t}", "public void delete(Object obj, boolean ignoreReferences) throws PersistenceBrokerException\n {\n if(isTxCheck() && !isInTransaction())\n {\n if(logger.isEnabledFor(Logger.ERROR))\n {\n String msg = \"No running PB-tx found. Please, only delete objects in context of a PB-transaction\" +\n \" to avoid side-effects - e.g. when rollback of complex objects.\";\n try\n {\n throw new Exception(\"** Delete object without active PersistenceBroker transaction **\");\n }\n catch(Exception e)\n {\n logger.error(msg, e);\n }\n }\n }\n try\n {\n doDelete(obj, ignoreReferences);\n }\n finally\n {\n markedForDelete.clear();\n }\n }", "public CollectionRequest<CustomField> findByWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/custom_fields\", workspace);\n return new CollectionRequest<CustomField>(this, CustomField.class, path, \"GET\");\n }", "public static String chomp(String s) {\r\n if(s.length() == 0)\r\n return s;\r\n int l_1 = s.length() - 1;\r\n if (s.charAt(l_1) == '\\n') {\r\n return s.substring(0, l_1);\r\n }\r\n return s;\r\n }", "void merge(Archetype flatParent, Archetype specialized) {\n expandAttributeNodes(specialized.getDefinition());\n\n flattenCObject(RmPath.ROOT, null, flatParent.getDefinition(), specialized.getDefinition());\n\n\n mergeOntologies(flatParent.getTerminology(), specialized.getTerminology());\n if (flatParent.getAnnotations() != null) {\n if (specialized.getAnnotations() == null) {\n specialized.setAnnotations(new ResourceAnnotations());\n }\n annotationsMerger.merge(flatParent.getAnnotations().getItems(), specialized.getAnnotations().getItems());\n }\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<Symmetry010Date> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<Symmetry010Date>) super.localDateTime(temporal);\n }", "synchronized void transitionFailed(final InternalState state) {\n final InternalState current = this.internalState;\n if(state == current) {\n // Revert transition and mark as failed\n switch (current) {\n case PROCESS_ADDING:\n this.internalState = InternalState.PROCESS_STOPPED;\n break;\n case PROCESS_STARTED:\n internalSetState(getTransitionTask(InternalState.PROCESS_STOPPING), InternalState.PROCESS_STARTED, InternalState.PROCESS_ADDED);\n break;\n case PROCESS_STARTING:\n this.internalState = InternalState.PROCESS_ADDED;\n break;\n case SEND_STDIN:\n case SERVER_STARTING:\n this.internalState = InternalState.PROCESS_STARTED;\n break;\n }\n this.requiredState = InternalState.FAILED;\n notifyAll();\n }\n }", "@SuppressWarnings(\"deprecation\")\n public BUILDER addAccessConstraint(final AccessConstraintDefinition accessConstraint) {\n if (accessConstraints == null) {\n accessConstraints = new AccessConstraintDefinition[] {accessConstraint};\n } else {\n accessConstraints = Arrays.copyOf(accessConstraints, accessConstraints.length + 1);\n accessConstraints[accessConstraints.length - 1] = accessConstraint;\n }\n return (BUILDER) this;\n }", "protected synchronized PersistenceBroker getBroker() throws PBFactoryException\r\n {\r\n /*\r\n mkalen:\r\n NB! The loadProfileIfNeeded must be called _before_ acquiring a broker below,\r\n since some methods in PersistenceBrokerImpl will keep a local reference to\r\n the descriptor repository that was active during broker construction/refresh\r\n (not checking the repository beeing used on method invocation).\r\n\r\n PersistenceBrokerImpl#getClassDescriptor(Class clazz) is such a method,\r\n that will throw ClassNotPersistenceCapableException on the following scenario:\r\n\r\n (All happens in one thread only):\r\n t0: activate per-thread metadata changes\r\n t1: load, register and activate profile A\r\n t2: load object O1 witch collection proxy C to objects {O2} (C stores profile key K(A))\r\n t3: close broker from t2\r\n t4: load, register and activate profile B\r\n t5: reference O1.getO2Collection, causing C loadData() to be invoked\r\n t6: C calls getBroker\r\n broker B is created and descriptorRepository is set to descriptors from profile B\r\n t7: C calls loadProfileIfNeeded, re-activating profile A\r\n t8: C calls B.getCollectionByQuery\r\n t9: B gets callback (via QueryReferenceBroker) to getClassDescriptor\r\n the local descriptorRepository from t6 is used!\r\n => We will now try to query for {O2} with profile B\r\n (even though we re-activated profile A in t7)\r\n => ClassNotPersistenceCapableException\r\n\r\n Keeping loadProfileIfNeeded() at the start of this method changes everything from t6:\r\n t6: C calls loadProfileIfNeeded, re-activating profile A\r\n t7: C calls getBroker,\r\n broker B is created and descriptorRepository is set to descriptors from profile A\r\n t8: C calls B.getCollectionByQuery\r\n t9: B gets callback to getClassDescriptor,\r\n the local descriptorRepository from t6 is used\r\n => We query for {O2} with profile A\r\n => All good :-)\r\n */\r\n if (_perThreadDescriptorsEnabled)\r\n {\r\n loadProfileIfNeeded();\r\n }\r\n\r\n PersistenceBroker broker;\r\n if (getBrokerKey() == null)\r\n {\r\n /*\r\n arminw:\r\n if no PBKey is set we throw an exception, because we don't\r\n know which PB (connection) should be used.\r\n */\r\n throw new OJBRuntimeException(\"Can't find associated PBKey. Need PBKey to obtain a valid\" +\r\n \"PersistenceBroker instance from intern resources.\");\r\n }\r\n // first try to use the current threaded broker to avoid blocking\r\n broker = PersistenceBrokerThreadMapping.currentPersistenceBroker(getBrokerKey());\r\n // current broker not found or was closed, create a intern new one\r\n if (broker == null || broker.isClosed())\r\n {\r\n broker = PersistenceBrokerFactory.createPersistenceBroker(getBrokerKey());\r\n // signal that we use a new internal obtained PB instance to read the\r\n // data and that this instance have to be closed after use\r\n _needsClose = true;\r\n }\r\n return broker;\r\n }" ]
Used to add working hours to the calendar. Note that the MPX file definition allows a maximum of 7 calendar hours records to be added to a single calendar. @param day day number @return new ProjectCalendarHours instance
[ "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 void setShortVec(char[] data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input data for indices cannot be null\");\n }\n if (getIndexSize() != 2)\n {\n throw new UnsupportedOperationException(\"Cannot update integer indices with char array\");\n }\n if (!NativeIndexBuffer.setShortArray(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input array is wrong size\");\n }\n }", "public static boolean isSuccess(JsonRtn jsonRtn) {\n if (jsonRtn == null) {\n return false;\n }\n\n String errCode = jsonRtn.getErrCode();\n if (StringUtils.isEmpty(errCode) || StringUtils.equals(WECHAT_JSON_RTN_SUCCESS_CODE, errCode)) {\n return true;\n }\n\n return false;\n }", "public void setJobTypes(final Map<String, ? extends Class<?>> jobTypes) {\n checkJobTypes(jobTypes);\n this.jobTypes.clear();\n this.jobTypes.putAll(jobTypes);\n }", "public List<DbMigration> getMigrationsSinceVersion(int version) {\n List<DbMigration> dbMigrations = new ArrayList<>();\n migrationScripts.stream().filter(script -> script.getVersion() > version).forEach(script -> {\n String content = loadScriptContent(script);\n dbMigrations.add(new DbMigration(script.getScriptName(), script.getVersion(), content));\n });\n return dbMigrations;\n }", "private Duration getDuration(String value)\n {\n Duration result = null;\n\n if (value != null && value.length() != 0)\n {\n double seconds = getLong(value);\n double hours = seconds / (60 * 60);\n double days = hours / 8;\n\n if (days < 1)\n {\n result = Duration.getInstance(hours, TimeUnit.HOURS);\n }\n else\n {\n double durationDays = hours / 8;\n result = Duration.getInstance(durationDays, TimeUnit.DAYS);\n }\n }\n\n return (result);\n }", "synchronized void stop(Integer timeout) {\n final InternalState required = this.requiredState;\n if(required != InternalState.STOPPED) {\n this.requiredState = InternalState.STOPPED;\n ROOT_LOGGER.stoppingServer(serverName);\n // Only send the stop operation if the server is started\n if (internalState == InternalState.SERVER_STARTED) {\n internalSetState(new ServerStopTask(timeout), internalState, InternalState.PROCESS_STOPPING);\n } else {\n transition(false);\n }\n }\n }", "public static <T> T get(String key, Class<T> clz) {\n return (T)m().get(key);\n }", "public BoxFileUploadSessionPart uploadPart(byte[] data, long offset, int partSize,\n long totalSizeOfFile) {\n URL uploadPartURL = this.sessionInfo.getSessionEndpoints().getUploadPartEndpoint();\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), uploadPartURL, HttpMethod.PUT);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM);\n\n MessageDigest digestInstance = null;\n try {\n digestInstance = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1);\n } catch (NoSuchAlgorithmException ae) {\n throw new BoxAPIException(\"Digest algorithm not found\", ae);\n }\n\n //Creates the digest using SHA1 algorithm. Then encodes the bytes using Base64.\n byte[] digestBytes = digestInstance.digest(data);\n String digest = Base64.encode(digestBytes);\n request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest);\n //Content-Range: bytes offset-part/totalSize\n request.addHeader(HttpHeaders.CONTENT_RANGE,\n \"bytes \" + offset + \"-\" + (offset + partSize - 1) + \"/\" + totalSizeOfFile);\n\n //Creates the body\n request.setBody(new ByteArrayInputStream(data));\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n BoxFileUploadSessionPart part = new BoxFileUploadSessionPart((JsonObject) jsonObject.get(\"part\"));\n return part;\n }", "protected Object[] getFieldObjects(Object data) throws SQLException {\n\t\tObject[] objects = new Object[argFieldTypes.length];\n\t\tfor (int i = 0; i < argFieldTypes.length; i++) {\n\t\t\tFieldType fieldType = argFieldTypes[i];\n\t\t\tif (fieldType.isAllowGeneratedIdInsert()) {\n\t\t\t\tobjects[i] = fieldType.getFieldValueIfNotDefault(data);\n\t\t\t} else {\n\t\t\t\tobjects[i] = fieldType.extractJavaFieldToSqlArgValue(data);\n\t\t\t}\n\t\t\tif (objects[i] == null) {\n\t\t\t\t// NOTE: the default value could be null as well\n\t\t\t\tobjects[i] = fieldType.getDefaultValue();\n\t\t\t}\n\t\t}\n\t\treturn objects;\n\t}" ]
Click handler for bottom drawer items.
[ "@Override\n public void onClick(View v) {\n String tag = (String) v.getTag();\n mContentTextView.setText(String.format(\"%s clicked.\", tag));\n mMenuDrawer.setActiveView(v);\n }" ]
[ "private void setViewPagerScroller() {\n try {\n Field scrollerField = ViewPager.class.getDeclaredField(\"mScroller\");\n scrollerField.setAccessible(true);\n Field interpolatorField = ViewPager.class.getDeclaredField(\"sInterpolator\");\n interpolatorField.setAccessible(true);\n\n scroller = new CustomDurationScroller(getContext(), (Interpolator)interpolatorField.get(null));\n scrollerField.set(this, scroller);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }", "@Override\n\tpublic Object executeJavaScript(String code) throws CrawljaxException {\n\t\ttry {\n\t\t\tJavascriptExecutor js = (JavascriptExecutor) browser;\n\t\t\treturn js.executeScript(code);\n\t\t} catch (WebDriverException e) {\n\t\t\tthrowIfConnectionException(e);\n\t\t\tthrow new CrawljaxException(e);\n\t\t}\n\t}", "private GenericCriteriaPrompt getPromptValue(FieldType field, byte[] block)\n {\n int textOffset = getPromptOffset(block);\n String value = MPPUtility.getUnicodeString(m_criteriaData, m_criteriaTextStart + textOffset);\n GenericCriteriaPrompt prompt = new GenericCriteriaPrompt(field.getDataType(), value);\n if (m_prompts != null)\n {\n m_prompts.add(prompt);\n }\n return prompt;\n }", "private void initComponents(List<CmsSetupComponent> components) {\n\n for (CmsSetupComponent component : components) {\n CheckBox checkbox = new CheckBox();\n checkbox.setValue(component.isChecked());\n checkbox.setCaption(component.getName() + \" - \" + component.getDescription());\n checkbox.setDescription(component.getDescription());\n checkbox.setData(component);\n checkbox.setWidth(\"100%\");\n m_components.addComponent(checkbox);\n m_componentCheckboxes.add(checkbox);\n m_componentMap.put(component.getId(), component);\n\n }\n }", "private String mountPath(CdjStatus.TrackSourceSlot slot) {\n switch (slot) {\n case SD_SLOT: return \"/B/\";\n case USB_SLOT: return \"/C/\";\n }\n throw new IllegalArgumentException(\"Don't know how to NFS mount filesystem for slot \" + slot);\n }", "public final Jar setAttribute(String section, String name, String value) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Manifest cannot be modified after entries are added.\");\n Attributes attr = getManifest().getAttributes(section);\n if (attr == null) {\n attr = new Attributes();\n getManifest().getEntries().put(section, attr);\n }\n attr.putValue(name, value);\n return this;\n }", "public ByteArray readBytes(int size) throws IOException\n {\n byte[] data = new byte[size];\n m_stream.read(data);\n return new ByteArray(data);\n }", "public static base_responses create(nitro_service client, sslfipskey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslfipskey createresources[] = new sslfipskey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tcreateresources[i] = new sslfipskey();\n\t\t\t\tcreateresources[i].fipskeyname = resources[i].fipskeyname;\n\t\t\t\tcreateresources[i].modulus = resources[i].modulus;\n\t\t\t\tcreateresources[i].exponent = resources[i].exponent;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, createresources,\"create\");\n\t\t}\n\t\treturn result;\n\t}", "public static<T> SessionVar<T> vendSessionVar(T defValue) {\n\treturn (new VarsJBridge()).vendSessionVar(defValue, new Exception());\n }" ]
Called when the end type is changed.
[ "void onEndTypeChange() {\n\n EndType endType = m_model.getEndType();\n m_groupDuration.selectButton(getDurationButtonForType(endType));\n switch (endType) {\n case DATE:\n case TIMES:\n m_durationPanel.setVisible(true);\n m_seriesEndDate.setValue(m_model.getSeriesEndDate());\n int occurrences = m_model.getOccurrences();\n if (!m_occurrences.isFocused()) {\n m_occurrences.setFormValueAsString(occurrences > 0 ? \"\" + occurrences : \"\");\n }\n break;\n default:\n m_durationPanel.setVisible(false);\n break;\n }\n updateExceptions();\n }" ]
[ "public static base_responses update(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey updateresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new sslcertkey();\n\t\t\t\tupdateresources[i].certkey = resources[i].certkey;\n\t\t\t\tupdateresources[i].expirymonitor = resources[i].expirymonitor;\n\t\t\t\tupdateresources[i].notificationperiod = resources[i].notificationperiod;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private void handleSerialAPIGetCapabilitiesResponse(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Serial API Get Capabilities\");\n\n\t\tthis.serialAPIVersion = String.format(\"%d.%d\", incomingMessage.getMessagePayloadByte(0), incomingMessage.getMessagePayloadByte(1));\n\t\tthis.manufactureId = ((incomingMessage.getMessagePayloadByte(2)) << 8) | (incomingMessage.getMessagePayloadByte(3));\n\t\tthis.deviceType = ((incomingMessage.getMessagePayloadByte(4)) << 8) | (incomingMessage.getMessagePayloadByte(5));\n\t\tthis.deviceId = (((incomingMessage.getMessagePayloadByte(6)) << 8) | (incomingMessage.getMessagePayloadByte(7)));\n\t\t\n\t\tlogger.debug(String.format(\"API Version = %s\", this.getSerialAPIVersion()));\n\t\tlogger.debug(String.format(\"Manufacture ID = 0x%x\", this.getManufactureId()));\n\t\tlogger.debug(String.format(\"Device Type = 0x%x\", this.getDeviceType()));\n\t\tlogger.debug(String.format(\"Device ID = 0x%x\", this.getDeviceId()));\n\t\t\n\t\t// Ready to get information on Serial API\t\t\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.SerialApiGetInitData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.SerialApiGetInitData, SerialMessage.SerialMessagePriority.High));\n\t}", "private SiteRecord getSiteRecord(String siteKey) {\n\t\tSiteRecord siteRecord = this.siteRecords.get(siteKey);\n\t\tif (siteRecord == null) {\n\t\t\tsiteRecord = new SiteRecord(siteKey);\n\t\t\tthis.siteRecords.put(siteKey, siteRecord);\n\t\t}\n\t\treturn siteRecord;\n\t}", "public <FV> FV getFieldValueIfNotDefault(Object object) throws SQLException {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tFV fieldValue = (FV) extractJavaFieldValue(object);\n\t\tif (isFieldValueDefault(fieldValue)) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn fieldValue;\n\t\t}\n\t}", "private static void listProjectProperties(ProjectFile file)\n {\n SimpleDateFormat df = new SimpleDateFormat(\"dd/MM/yyyy HH:mm z\");\n ProjectProperties properties = file.getProjectProperties();\n Date startDate = properties.getStartDate();\n Date finishDate = properties.getFinishDate();\n String formattedStartDate = startDate == null ? \"(none)\" : df.format(startDate);\n String formattedFinishDate = finishDate == null ? \"(none)\" : df.format(finishDate);\n\n System.out.println(\"MPP file type: \" + properties.getMppFileType());\n System.out.println(\"Project Properties: StartDate=\" + formattedStartDate + \" FinishDate=\" + formattedFinishDate);\n System.out.println();\n }", "public static dnsnsecrec[] get(nitro_service service, dnsnsecrec_args args) throws Exception{\n\t\tdnsnsecrec obj = new dnsnsecrec();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tdnsnsecrec[] response = (dnsnsecrec[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public FieldDescriptor getAutoIncrementField()\r\n {\r\n if (m_autoIncrementField == null)\r\n {\r\n FieldDescriptor[] fds = getPkFields();\r\n\r\n for (int i = 0; i < fds.length; i++)\r\n {\r\n FieldDescriptor fd = fds[i];\r\n if (fd.isAutoIncrement())\r\n {\r\n m_autoIncrementField = fd;\r\n break;\r\n }\r\n }\r\n }\r\n if (m_autoIncrementField == null)\r\n {\r\n LoggerFactory.getDefaultLogger().warn(\r\n this.getClass().getName()\r\n + \": \"\r\n + \"Could not find autoincrement attribute for class: \"\r\n + this.getClassNameOfObject());\r\n }\r\n return m_autoIncrementField;\r\n }", "public static ServiceController<DeploymentScanner> addService(final OperationContext context, final PathAddress resourceAddress, final String relativeTo, final String path,\n final int scanInterval, TimeUnit unit, final boolean autoDeployZip,\n final boolean autoDeployExploded, final boolean autoDeployXml, final boolean scanEnabled, final long deploymentTimeout, boolean rollbackOnRuntimeFailure,\n final FileSystemDeploymentService bootTimeService, final ScheduledExecutorService scheduledExecutorService) {\n final DeploymentScannerService service = new DeploymentScannerService(resourceAddress, relativeTo, path, scanInterval, unit, autoDeployZip,\n autoDeployExploded, autoDeployXml, scanEnabled, deploymentTimeout, rollbackOnRuntimeFailure, bootTimeService);\n final ServiceName serviceName = getServiceName(resourceAddress.getLastElement().getValue());\n service.scheduledExecutorValue.inject(scheduledExecutorService);\n final ServiceBuilder<DeploymentScanner> sb = context.getServiceTarget().addService(serviceName, service);\n sb.addDependency(context.getCapabilityServiceName(PATH_MANAGER_CAPABILITY, PathManager.class), PathManager.class, service.pathManagerValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.notification-handler-registry\", null),\n NotificationHandlerRegistry.class, service.notificationRegistryValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.model-controller-client-factory\", null),\n ModelControllerClientFactory.class, service.clientFactoryValue);\n sb.requires(org.jboss.as.server.deployment.Services.JBOSS_DEPLOYMENT_CHAINS);\n sb.addDependency(ControlledProcessStateService.SERVICE_NAME, ControlledProcessStateService.class, service.controlledProcessStateServiceValue);\n return sb.install();\n }", "public static int compactDistance(String s1, String s2) {\n if (s1.length() == 0)\n return s2.length();\n if (s2.length() == 0)\n return s1.length();\n\n // the maximum edit distance there is any point in reporting.\n int maxdist = Math.min(s1.length(), s2.length()) / 2;\n \n // we allocate just one column instead of the entire matrix, in\n // order to save space. this also enables us to implement the\n // algorithm somewhat faster. the first cell is always the\n // virtual first row.\n int s1len = s1.length();\n int[] column = new int[s1len + 1];\n\n // first we need to fill in the initial column. we use a separate\n // loop for this, because in this case our basis for comparison is\n // not the previous column, but a virtual first column.\n int ix2 = 0;\n char ch2 = s2.charAt(ix2);\n column[0] = 1; // virtual first row\n for (int ix1 = 1; ix1 <= s1len; ix1++) {\n int cost = s1.charAt(ix1 - 1) == ch2 ? 0 : 1;\n\n // Lowest of three: above (column[ix1 - 1]), aboveleft: ix1 - 1,\n // left: ix1. Latter cannot possibly be lowest, so is\n // ignored.\n column[ix1] = Math.min(column[ix1 - 1], ix1 - 1) + cost;\n }\n\n // okay, now we have an initialized first column, and we can\n // compute the rest of the matrix.\n int above = 0;\n for (ix2 = 1; ix2 < s2.length(); ix2++) {\n ch2 = s2.charAt(ix2);\n above = ix2 + 1; // virtual first row\n\n int smallest = s1len * 2; // used to implement cutoff\n for (int ix1 = 1; ix1 <= s1len; ix1++) {\n int cost = s1.charAt(ix1 - 1) == ch2 ? 0 : 1;\n\n // above: above\n // aboveleft: column[ix1 - 1]\n // left: column[ix1]\n int value = Math.min(Math.min(above, column[ix1 - 1]), column[ix1]) +\n cost;\n column[ix1 - 1] = above; // write previous\n above = value; // keep current\n smallest = Math.min(smallest, value);\n }\n column[s1len] = above;\n\n // check if we can stop because we'll be going over the max distance\n if (smallest > maxdist)\n return smallest;\n }\n\n // ok, we're done\n return above;\n }" ]
Replaces sequences of whitespaces with tabs within a line. @param self A line to unexpand @param tabStop The number of spaces a tab represents @return an unexpanded String @since 1.8.2
[ "public static String unexpandLine(CharSequence self, int tabStop) {\n StringBuilder builder = new StringBuilder(self.toString());\n int index = 0;\n while (index + tabStop < builder.length()) {\n // cut original string in tabstop-length pieces\n String piece = builder.substring(index, index + tabStop);\n // count trailing whitespace characters\n int count = 0;\n while ((count < tabStop) && (Character.isWhitespace(piece.charAt(tabStop - (count + 1)))))\n count++;\n // replace if whitespace was found\n if (count > 0) {\n piece = piece.substring(0, tabStop - count) + '\\t';\n builder.replace(index, index + tabStop, piece);\n index = index + tabStop - (count - 1);\n } else\n index = index + tabStop;\n }\n return builder.toString();\n }" ]
[ "protected AssemblyResponse watchStatus() throws LocalOperationException, RequestException {\n AssemblyResponse response;\n do {\n response = getClient().getAssemblyByUrl(url);\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n throw new LocalOperationException(e);\n }\n } while (!response.isFinished());\n\n setState(State.FINISHED);\n return response;\n }", "public static int getCount(Matcher matcher) {\n int counter = 0;\n matcher.reset();\n while (matcher.find()) {\n counter++;\n }\n return counter;\n }", "private void verifyOrAddStore(String clusterURL,\n String keySchema,\n String valueSchema) {\n String newStoreDefXml = VoldemortUtils.getStoreDefXml(\n storeName,\n props.getInt(BUILD_REPLICATION_FACTOR, 2),\n props.getInt(BUILD_REQUIRED_READS, 1),\n props.getInt(BUILD_REQUIRED_WRITES, 1),\n props.getNullableInt(BUILD_PREFERRED_READS),\n props.getNullableInt(BUILD_PREFERRED_WRITES),\n props.getString(PUSH_FORCE_SCHEMA_KEY, keySchema),\n props.getString(PUSH_FORCE_SCHEMA_VALUE, valueSchema),\n description,\n owners);\n\n log.info(\"Verifying store against cluster URL: \" + clusterURL + \"\\n\" + newStoreDefXml.toString());\n StoreDefinition newStoreDef = VoldemortUtils.getStoreDef(newStoreDefXml);\n\n try {\n adminClientPerCluster.get(clusterURL).storeMgmtOps.verifyOrAddStore(newStoreDef, \"BnP config/data\",\n enableStoreCreation, this.storeVerificationExecutorService);\n } catch (UnreachableStoreException e) {\n log.info(\"verifyOrAddStore() failed on some nodes for clusterURL: \" + clusterURL + \" (this is harmless).\", e);\n // When we can't reach some node, we just skip it and won't create the store on it.\n // Next time BnP is run while the node is up, it will get the store created.\n } // Other exceptions need to bubble up!\n\n storeDef = newStoreDef;\n }", "public static Class<?> loadClass(String className) {\n try {\n return Class.forName(className);\n } catch(ClassNotFoundException e) {\n throw new IllegalArgumentException(e);\n }\n }", "public static appfwpolicy_csvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwpolicy_csvserver_binding obj = new appfwpolicy_csvserver_binding();\n\t\tobj.set_name(name);\n\t\tappfwpolicy_csvserver_binding response[] = (appfwpolicy_csvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static base_response delete(nitro_service client) throws Exception {\n\t\tlocationfile deleteresource = new locationfile();\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static File createFolder(String path, String dest_dir)\n throws BeastException {\n File f = new File(dest_dir);\n if (!f.isDirectory()) {\n try {\n f.mkdirs();\n } catch (Exception e) {\n logger.severe(\"Problem creating directory: \" + path\n + File.separator + dest_dir);\n }\n }\n\n String folderPath = createFolderPath(path);\n\n f = new File(f, folderPath);\n if (!f.isDirectory()) {\n try {\n f.mkdirs();\n } catch (Exception e) {\n String message = \"Problem creating directory: \" + path\n + File.separator + dest_dir;\n logger.severe(message);\n throw new BeastException(message, e);\n }\n }\n\n return f;\n }", "public HashSet<String> getDataById(String id) throws IOException {\n if (idToVersion.containsKey(id)) {\n return get(id);\n } else {\n return null;\n }\n }", "public static void processEntitiesFromWikidataDump(\n\t\t\tEntityDocumentProcessor entityDocumentProcessor) {\n\n\t\t// Controller object for processing dumps:\n\t\tDumpProcessingController dumpProcessingController = new DumpProcessingController(\n\t\t\t\t\"wikidatawiki\");\n\t\tdumpProcessingController.setOfflineMode(OFFLINE_MODE);\n\n\t\t// // Optional: Use another download directory:\n\t\t// dumpProcessingController.setDownloadDirectory(System.getProperty(\"user.dir\"));\n\n\t\t// Should we process historic revisions or only current ones?\n\t\tboolean onlyCurrentRevisions;\n\t\tswitch (DUMP_FILE_MODE) {\n\t\tcase ALL_REVS:\n\t\tcase ALL_REVS_WITH_DAILIES:\n\t\t\tonlyCurrentRevisions = false;\n\t\t\tbreak;\n\t\tcase CURRENT_REVS:\n\t\tcase CURRENT_REVS_WITH_DAILIES:\n\t\tcase JSON:\n\t\tcase JUST_ONE_DAILY_FOR_TEST:\n\t\tdefault:\n\t\t\tonlyCurrentRevisions = true;\n\t\t}\n\n\t\t// Subscribe to the most recent entity documents of type wikibase item:\n\t\tdumpProcessingController.registerEntityDocumentProcessor(\n\t\t\t\tentityDocumentProcessor, null, onlyCurrentRevisions);\n\n\t\t// Also add a timer that reports some basic progress information:\n\t\tEntityTimerProcessor entityTimerProcessor = new EntityTimerProcessor(\n\t\t\t\tTIMEOUT_SEC);\n\t\tdumpProcessingController.registerEntityDocumentProcessor(\n\t\t\t\tentityTimerProcessor, null, onlyCurrentRevisions);\n\n\t\tMwDumpFile dumpFile = null;\n\t\ttry {\n\t\t\t// Start processing (may trigger downloads where needed):\n\t\t\tswitch (DUMP_FILE_MODE) {\n\t\t\tcase ALL_REVS:\n\t\t\tcase CURRENT_REVS:\n\t\t\t\tdumpFile = dumpProcessingController\n\t\t\t\t\t\t.getMostRecentDump(DumpContentType.FULL);\n\t\t\t\tbreak;\n\t\t\tcase ALL_REVS_WITH_DAILIES:\n\t\t\tcase CURRENT_REVS_WITH_DAILIES:\n\t\t\t\tMwDumpFile fullDumpFile = dumpProcessingController\n\t\t\t\t\t\t.getMostRecentDump(DumpContentType.FULL);\n\t\t\t\tMwDumpFile incrDumpFile = dumpProcessingController\n\t\t\t\t\t\t.getMostRecentDump(DumpContentType.DAILY);\n\t\t\t\tlastDumpFileName = fullDumpFile.getProjectName() + \"-\"\n\t\t\t\t\t\t+ incrDumpFile.getDateStamp() + \".\"\n\t\t\t\t\t\t+ fullDumpFile.getDateStamp();\n\t\t\t\tdumpProcessingController.processAllRecentRevisionDumps();\n\t\t\t\tbreak;\n\t\t\tcase JSON:\n\t\t\t\tdumpFile = dumpProcessingController\n\t\t\t\t\t\t.getMostRecentDump(DumpContentType.JSON);\n\t\t\t\tbreak;\n\t\t\tcase JUST_ONE_DAILY_FOR_TEST:\n\t\t\t\tdumpFile = dumpProcessingController\n\t\t\t\t\t\t.getMostRecentDump(DumpContentType.DAILY);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new RuntimeException(\"Unsupported dump processing type \"\n\t\t\t\t\t\t+ DUMP_FILE_MODE);\n\t\t\t}\n\n\t\t\tif (dumpFile != null) {\n\t\t\t\tlastDumpFileName = dumpFile.getProjectName() + \"-\"\n\t\t\t\t\t\t+ dumpFile.getDateStamp();\n\t\t\t\tdumpProcessingController.processDump(dumpFile);\n\t\t\t}\n\t\t} catch (TimeoutException e) {\n\t\t\t// The timer caused a time out. Continue and finish normally.\n\t\t}\n\n\t\t// Print final timer results:\n\t\tentityTimerProcessor.close();\n\t}" ]
Performs the filtering of the expired entries based on retention time. Optionally, deletes them also @param key the key whose value is to be deleted if needed @param vals set of values to be filtered out @return filtered list of values which are currently valid
[ "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 }" ]
[ "public String addressPath() {\n if (isLeaf) {\n ManagementModelNode parent = (ManagementModelNode)getParent();\n return parent.addressPath();\n }\n\n StringBuilder builder = new StringBuilder();\n for (Object pathElement : getUserObjectPath()) {\n UserObject userObj = (UserObject)pathElement;\n if (userObj.isRoot()) { // don't want to escape root\n builder.append(userObj.getName());\n continue;\n }\n\n builder.append(userObj.getName());\n builder.append(\"=\");\n builder.append(userObj.getEscapedValue());\n builder.append(\"/\");\n }\n\n return builder.toString();\n }", "public ThumborUrlBuilder resize(int width, int height) {\n if (width < 0 && width != ORIGINAL_SIZE) {\n throw new IllegalArgumentException(\"Width must be a positive number.\");\n }\n if (height < 0 && height != ORIGINAL_SIZE) {\n throw new IllegalArgumentException(\"Height must be a positive number.\");\n }\n if (width == 0 && height == 0) {\n throw new IllegalArgumentException(\"Both width and height must not be zero.\");\n }\n hasResize = true;\n resizeWidth = width;\n resizeHeight = height;\n return this;\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 static HashMap<Integer, List<Integer>>\n getBalancedNumberOfPrimaryPartitionsPerNode(final Cluster nextCandidateCluster,\n Map<Integer, Integer> targetPartitionsPerZone) {\n HashMap<Integer, List<Integer>> numPartitionsPerNode = Maps.newHashMap();\n for(Integer zoneId: nextCandidateCluster.getZoneIds()) {\n List<Integer> partitionsOnNode = Utils.distributeEvenlyIntoList(nextCandidateCluster.getNumberOfNodesInZone(zoneId),\n targetPartitionsPerZone.get(zoneId));\n numPartitionsPerNode.put(zoneId, partitionsOnNode);\n }\n return numPartitionsPerNode;\n }", "protected synchronized void streamingSlopPut(ByteArray key,\n Versioned<byte[]> value,\n String storeName,\n int failedNodeId) throws IOException {\n\n Slop slop = new Slop(storeName,\n Slop.Operation.PUT,\n key,\n value.getValue(),\n null,\n failedNodeId,\n new Date());\n\n ByteArray slopKey = slop.makeKey();\n Versioned<byte[]> slopValue = new Versioned<byte[]>(slopSerializer.toBytes(slop),\n value.getVersion());\n\n Node failedNode = adminClient.getAdminClientCluster().getNodeById(failedNodeId);\n HandoffToAnyStrategy slopRoutingStrategy = new HandoffToAnyStrategy(adminClient.getAdminClientCluster(),\n true,\n failedNode.getZoneId());\n // node Id which will receive the slop\n int slopDestination = slopRoutingStrategy.routeHint(failedNode).get(0).getId();\n\n VAdminProto.PartitionEntry partitionEntry = VAdminProto.PartitionEntry.newBuilder()\n .setKey(ProtoUtils.encodeBytes(slopKey))\n .setVersioned(ProtoUtils.encodeVersioned(slopValue))\n .build();\n\n VAdminProto.UpdatePartitionEntriesRequest.Builder updateRequest = VAdminProto.UpdatePartitionEntriesRequest.newBuilder()\n .setStore(SLOP_STORE)\n .setPartitionEntry(partitionEntry);\n\n DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair<String, Integer>(SLOP_STORE,\n slopDestination));\n\n if(nodeIdStoreInitialized.get(new Pair<String, Integer>(SLOP_STORE, slopDestination))) {\n ProtoUtils.writeMessage(outputStream, updateRequest.build());\n } else {\n ProtoUtils.writeMessage(outputStream,\n VAdminProto.VoldemortAdminRequest.newBuilder()\n .setType(VAdminProto.AdminRequestType.UPDATE_PARTITION_ENTRIES)\n .setUpdatePartitionEntries(updateRequest)\n .build());\n outputStream.flush();\n nodeIdStoreInitialized.put(new Pair<String, Integer>(SLOP_STORE, slopDestination), true);\n\n }\n\n throttler.maybeThrottle(1);\n\n }", "protected String findPath(String start, String end) {\n if (start.equals(end)) {\n return start;\n } else {\n return findPath(start, parent.get(end)) + \" -> \" + end;\n }\n }", "private Pair<Double, String>\n summarizeBalance(final Map<Integer, Integer> nodeIdToPartitionCount, String title) {\n StringBuilder builder = new StringBuilder();\n builder.append(\"\\n\" + title + \"\\n\");\n\n Map<Integer, ZoneBalanceStats> zoneToBalanceStats = new HashMap<Integer, ZoneBalanceStats>();\n for(Integer zoneId: cluster.getZoneIds()) {\n zoneToBalanceStats.put(zoneId, new ZoneBalanceStats());\n }\n\n for(Node node: cluster.getNodes()) {\n int curCount = nodeIdToPartitionCount.get(node.getId());\n builder.append(\"\\tNode ID: \" + node.getId() + \" : \" + curCount + \" (\" + node.getHost()\n + \")\\n\");\n zoneToBalanceStats.get(node.getZoneId()).addPartitions(curCount);\n }\n\n // double utilityToBeMinimized = Double.MIN_VALUE;\n double utilityToBeMinimized = 0;\n for(Integer zoneId: cluster.getZoneIds()) {\n builder.append(\"Zone \" + zoneId + \"\\n\");\n builder.append(zoneToBalanceStats.get(zoneId).dumpStats());\n utilityToBeMinimized += zoneToBalanceStats.get(zoneId).getUtility();\n /*- \n * Another utility function to consider \n if(zoneToBalanceStats.get(zoneId).getMaxMinRatio() > utilityToBeMinimized) {\n utilityToBeMinimized = zoneToBalanceStats.get(zoneId).getUtility();\n }\n */\n }\n\n return Pair.create(utilityToBeMinimized, builder.toString());\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 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 }" ]
Sets the search scope. @param cms The current CmsObject object.
[ "private void setSearchScopeFilter(CmsObject cms) {\n\n final List<String> searchRoots = CmsSearchUtil.computeScopeFolders(cms, this);\n\n // If the resource types contain the type \"function\" also\n // add \"/system/modules/\" to the search path\n\n if ((null != getResourceTypes()) && containsFunctionType(getResourceTypes())) {\n searchRoots.add(\"/system/modules/\");\n }\n\n addFoldersToSearchIn(searchRoots);\n }" ]
[ "public void rotateWithPivot(float quatW, float quatX, float quatY,\n float quatZ, float pivotX, float pivotY, float pivotZ) {\n NativeTransform.rotateWithPivot(getNative(), quatW, quatX, quatY,\n quatZ, pivotX, pivotY, pivotZ);\n }", "public String computeTrackSignature(final String title, final SearchableItem artist, final int duration,\n final WaveformDetail waveformDetail, final BeatGrid beatGrid) {\n final String safeTitle = (title == null)? \"\" : title;\n final String artistName = (artist == null)? \"[no artist]\" : artist.label;\n try {\n // Compute the SHA-1 hash of our fields\n MessageDigest digest = MessageDigest.getInstance(\"SHA1\");\n digest.update(safeTitle.getBytes(\"UTF-8\"));\n digest.update((byte) 0);\n digest.update(artistName.getBytes(\"UTF-8\"));\n digest.update((byte) 0);\n digestInteger(digest, duration);\n digest.update(waveformDetail.getData());\n for (int i = 1; i <= beatGrid.beatCount; i++) {\n digestInteger(digest, beatGrid.getBeatWithinBar(i));\n digestInteger(digest, (int)beatGrid.getTimeWithinTrack(i));\n }\n byte[] result = digest.digest();\n\n // Create a hex string representation of the hash\n StringBuilder hex = new StringBuilder(result.length * 2);\n for (byte aResult : result) {\n hex.append(Integer.toString((aResult & 0xff) + 0x100, 16).substring(1));\n }\n\n return hex.toString();\n\n } catch (NullPointerException e) {\n logger.info(\"Returning null track signature because an input element was null.\", e);\n } catch (NoSuchAlgorithmException e) {\n logger.error(\"Unable to obtain SHA-1 MessageDigest instance for computing track signatures.\", e);\n } catch (UnsupportedEncodingException e) {\n logger.error(\"Unable to work with UTF-8 string encoding for computing track signatures.\", e);\n }\n return null; // We were unable to compute a signature\n }", "boolean openStream() throws InterruptedException, IOException {\n logger.info(\"stream START\");\n final boolean isOpen;\n final Set<BsonValue> idsToWatch = nsConfig.getSynchronizedDocumentIds();\n\n if (!networkMonitor.isConnected()) {\n logger.info(\"stream END - Network disconnected\");\n return false;\n }\n\n if (idsToWatch.isEmpty()) {\n logger.info(\"stream END - No synchronized documents\");\n return false;\n }\n\n nsLock.writeLock().lockInterruptibly();\n try {\n if (!authMonitor.isLoggedIn()) {\n logger.info(\"stream END - Logged out\");\n return false;\n }\n\n final Document args = new Document();\n args.put(\"database\", namespace.getDatabaseName());\n args.put(\"collection\", namespace.getCollectionName());\n args.put(\"ids\", idsToWatch);\n\n currentStream =\n service.streamFunction(\n \"watch\",\n Collections.singletonList(args),\n ResultDecoders.changeEventDecoder(BSON_DOCUMENT_CODEC));\n\n if (currentStream != null && currentStream.isOpen()) {\n this.nsConfig.setStale(true);\n isOpen = true;\n } else {\n isOpen = false;\n }\n } finally {\n nsLock.writeLock().unlock();\n }\n return isOpen;\n }", "public void endRecord_() {\n // this is where we actually update the link database. basically,\n // all we need to do is to retract those links which weren't seen\n // this time around, and that can be done via assertLink, since it\n // can override existing links.\n\n // get all the existing links\n Collection<Link> oldlinks = linkdb.getAllLinksFor(getIdentity(current));\n\n // build a hashmap so we can look up corresponding old links from\n // new links\n if (oldlinks != null) {\n Map<String, Link> oldmap = new HashMap(oldlinks.size());\n for (Link l : oldlinks)\n oldmap.put(makeKey(l), l);\n\n // removing all the links we found this time around from the set of\n // old links. any links remaining after this will be stale, and need\n // to be retracted\n for (Link newl : new ArrayList<Link>(curlinks)) {\n String key = makeKey(newl);\n Link oldl = oldmap.get(key);\n if (oldl == null)\n continue;\n\n if (oldl.overrides(newl))\n // previous information overrides this link, so ignore\n curlinks.remove(newl);\n else if (sameAs(oldl, newl)) {\n // there's no new information here, so just ignore this\n curlinks.remove(newl);\n oldmap.remove(key); // we don't want to retract the old one\n } else\n // the link is out of date, but will be overwritten, so remove\n oldmap.remove(key);\n }\n\n // all the inferred links left in oldmap are now old links we\n // didn't find on this pass. there is no longer any evidence\n // supporting them, and so we can retract them.\n for (Link oldl : oldmap.values())\n if (oldl.getStatus() == LinkStatus.INFERRED) {\n oldl.retract(); // changes to retracted, updates timestamp\n curlinks.add(oldl);\n }\n }\n\n // okay, now we write it all to the database\n for (Link l : curlinks)\n linkdb.assertLink(l);\n }", "private String createMethodSignature(Method method)\n {\n StringBuilder sb = new StringBuilder();\n sb.append(\"(\");\n for (Class<?> type : method.getParameterTypes())\n {\n sb.append(getTypeString(type));\n }\n sb.append(\")\");\n Class<?> type = method.getReturnType();\n if (type.getName().equals(\"void\"))\n {\n sb.append(\"V\");\n }\n else\n {\n sb.append(getTypeString(type));\n }\n return sb.toString();\n }", "public String getRelativePath() {\n final StringBuilder builder = new StringBuilder();\n for(final String p : path) {\n builder.append(p).append(\"/\");\n }\n builder.append(getName());\n return builder.toString();\n }", "protected void removeInvalidChildren() {\n\n if (getLoadState() == LoadState.LOADED) {\n List<CmsSitemapTreeItem> toDelete = new ArrayList<CmsSitemapTreeItem>();\n for (int i = 0; i < getChildCount(); i++) {\n CmsSitemapTreeItem item = (CmsSitemapTreeItem)getChild(i);\n CmsUUID id = item.getEntryId();\n if ((id != null) && (CmsSitemapView.getInstance().getController().getEntryById(id) == null)) {\n toDelete.add(item);\n }\n }\n for (CmsSitemapTreeItem deleteItem : toDelete) {\n m_children.removeItem(deleteItem);\n }\n }\n }", "public static float noise1(float x) {\n int bx0, bx1;\n float rx0, rx1, sx, t, u, v;\n\n if (start) {\n start = false;\n init();\n }\n\n t = x + N;\n bx0 = ((int)t) & BM;\n bx1 = (bx0+1) & BM;\n rx0 = t - (int)t;\n rx1 = rx0 - 1.0f;\n\n sx = sCurve(rx0);\n\n u = rx0 * g1[p[bx0]];\n v = rx1 * g1[p[bx1]];\n return 2.3f*lerp(sx, u, v);\n }", "public void addResourceAssignment(ResourceAssignment assignment)\n {\n if (getExistingResourceAssignment(assignment.getResource()) == null)\n {\n m_assignments.add(assignment);\n getParentFile().getResourceAssignments().add(assignment);\n\n Resource resource = assignment.getResource();\n if (resource != null)\n {\n resource.addResourceAssignment(assignment);\n }\n }\n }" ]
Append the given item to the end of the list @param segment segment to append
[ "public void append(LogSegment segment) {\n while (true) {\n List<LogSegment> curr = contents.get();\n List<LogSegment> updated = new ArrayList<LogSegment>(curr);\n updated.add(segment);\n if (contents.compareAndSet(curr, updated)) {\n return;\n }\n }\n }" ]
[ "public Bitmap drawableToBitmap(Drawable drawable) {\n\t\tif (drawable == null) // Don't do anything without a proper drawable\n\t\t\treturn null;\n\t\telse if (drawable instanceof BitmapDrawable) { // Use the getBitmap() method instead if BitmapDrawable\n\t\t\tLog.i(TAG, \"Bitmap drawable!\");\n\t\t\treturn ((BitmapDrawable) drawable).getBitmap();\n\t\t}\n\n\t\tint intrinsicWidth = drawable.getIntrinsicWidth();\n\t\tint intrinsicHeight = drawable.getIntrinsicHeight();\n\n\t\tif (!(intrinsicWidth > 0 && intrinsicHeight > 0))\n\t\t\treturn null;\n\n\t\ttry {\n\t\t\t// Create Bitmap object out of the drawable\n\t\t\tBitmap bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888);\n\t\t\tCanvas canvas = new Canvas(bitmap);\n\t\t\tdrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());\n\t\t\tdrawable.draw(canvas);\n\t\t\treturn bitmap;\n\t\t} catch (OutOfMemoryError e) {\n\t\t\t// Simply return null of failed bitmap creations\n\t\t\tLog.e(TAG, \"Encountered OutOfMemoryError while generating bitmap!\");\n\t\t\treturn null;\n\t\t}\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}", "public static void setTranslucentNavigationFlag(Activity activity, boolean on) {\n if (Build.VERSION.SDK_INT >= 19) {\n setFlag(activity, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, on);\n }\n }", "public static Integer getDays(String days)\n {\n Integer result = null;\n if (days != null)\n {\n result = Integer.valueOf(Integer.parseInt(days, 2));\n }\n return (result);\n }", "private void appendSubQuery(Query subQuery, StringBuffer buf)\r\n {\r\n buf.append(\" (\");\r\n buf.append(getSubQuerySQL(subQuery));\r\n buf.append(\") \");\r\n }", "protected String createName() {\n final StringBuilder buf = new StringBuilder(128);\n try {\n buf.append(InetAddress.getLocalHost().getHostName()).append(COLON)\n .append(ManagementFactory.getRuntimeMXBean().getName().split(\"@\")[0]) // PID\n .append('-').append(this.workerId).append(COLON).append(JAVA_DYNAMIC_QUEUES);\n for (final String queueName : this.queueNames) {\n buf.append(',').append(queueName);\n }\n } catch (UnknownHostException uhe) {\n throw new RuntimeException(uhe);\n }\n return buf.toString();\n }", "protected void putResponse(JSONObject json,\n String param,\n Object value) {\n try {\n json.put(param,\n value);\n } catch (JSONException e) {\n logger.error(\"json write error\",\n e);\n }\n }", "public String getOriginalUrl() throws FlickrException {\r\n if (originalSize == null) {\r\n if (originalFormat != null) {\r\n return getOriginalBaseImageUrl() + \"_o.\" + originalFormat;\r\n }\r\n return getOriginalBaseImageUrl() + DEFAULT_ORIGINAL_IMAGE_SUFFIX;\r\n } else {\r\n return originalSize.getSource();\r\n }\r\n }", "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}" ]
Merge the given maps. <p> The replied map is a view on the given two maps. If a key exists in the two maps, the replied value is the value of the right operand. </p> <p> Even if the key of the right operand exists in the left operand, the value in the right operand is preferred. </p> <p> The replied map is unmodifiable. </p> @param <K> type of the map keys. @param <V> type of the map values. @param left the left map. @param right the right map. @return a map with the merged contents from the two maps. @since 2.15
[ "@Pure\n\t@Inline(value = \"(new $3<$5, $6>($1, $2))\", imported = UnmodifiableMergingMapView.class, constantExpression = true)\n\tpublic static <K, V> Map<K, V> union(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) {\n\t\treturn new UnmodifiableMergingMapView<K, V>(left, right);\n\t}" ]
[ "public <T> Map<String, List<T>> queryGroups(String query, Class<T> classOfT) {\r\n InputStream instream = null;\r\n try {\r\n Reader reader = new InputStreamReader(instream = queryForStream(query), \"UTF-8\");\r\n JsonObject json = new JsonParser().parse(reader).getAsJsonObject();\r\n Map<String, List<T>> result = new LinkedHashMap<String, List<T>>();\r\n if (json.has(\"groups\")) {\r\n for (JsonElement e : json.getAsJsonArray(\"groups\")) {\r\n String groupName = e.getAsJsonObject().get(\"by\").getAsString();\r\n List<T> orows = new ArrayList<T>();\r\n if (!includeDocs) {\r\n log.warning(\"includeDocs set to false and attempting to retrieve doc. \" +\r\n \"null object will be returned\");\r\n }\r\n for (JsonElement rows : e.getAsJsonObject().getAsJsonArray(\"rows\")) {\r\n orows.add(jsonToObject(client.getGson(), rows, \"doc\", classOfT));\r\n }\r\n result.put(groupName, orows);\r\n }// end for(groups)\r\n }// end hasgroups\r\n else {\r\n log.warning(\"No grouped results available. Use query() if non grouped query\");\r\n }\r\n return result;\r\n } catch (UnsupportedEncodingException e1) {\r\n // This should never happen as every implementation of the java platform is required\r\n // to support UTF-8.\r\n throw new RuntimeException(e1);\r\n } finally {\r\n close(instream);\r\n }\r\n }", "public String generateTaskId() {\n final String uuid = UUID.randomUUID().toString().substring(0, 12);\n int size = this.targetHostMeta == null ? 0 : this.targetHostMeta\n .getHosts().size();\n return \"PT_\" + size + \"_\"\n + PcDateUtils.getNowDateTimeStrConciseNoZone() + \"_\" + uuid;\n }", "public static ManagerFunctions.InputN createMultTransA() {\n return (inputs, manager) -> {\n if( inputs.size() != 2 )\n throw new RuntimeException(\"Two inputs required\");\n\n final Variable varA = inputs.get(0);\n final Variable varB = inputs.get(1);\n\n Operation.Info ret = new Operation.Info();\n\n if( varA instanceof VariableMatrix && varB instanceof VariableMatrix ) {\n\n // The output matrix or scalar variable must be created with the provided manager\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n ret.op = new Operation(\"multTransA-mm\") {\n @Override\n public void process() {\n DMatrixRMaj mA = ((VariableMatrix)varA).matrix;\n DMatrixRMaj mB = ((VariableMatrix)varB).matrix;\n\n CommonOps_DDRM.multTransA(mA,mB,output.matrix);\n }\n };\n } else {\n throw new IllegalArgumentException(\"Expected both inputs to be a matrix\");\n }\n\n return ret;\n };\n }", "public void deleteObject(Object object)\r\n {\r\n PersistenceBroker broker = null;\r\n try\r\n {\r\n broker = getBroker();\r\n broker.delete(object);\r\n }\r\n finally\r\n {\r\n if (broker != null) broker.close();\r\n }\r\n }", "public static <T> T buildInstanceForMap(Class<T> clazz, Map<String, Object> values, MyReflectionDifferenceHandler differenceHandler)\n throws InstantiationException, IllegalAccessException, IntrospectionException,\n IllegalArgumentException, InvocationTargetException {\n\n log.debug(\"Building new instance of Class \" + clazz.getName());\n\n T instance = clazz.newInstance();\n\n for (String key : values.keySet()) {\n Object value = values.get(key);\n\n if (value == null) {\n log.debug(\"Value for field \" + key + \" is null, so ignoring it...\");\n continue;\n }\n \n log.debug(\n \"Invoke setter for \" + key + \" (\" + value.getClass() + \" / \" + value.toString() + \")\");\n Method setter = null;\n try {\n setter = new PropertyDescriptor(key.replace('.', '_'), clazz).getWriteMethod();\n } catch (Exception e) {\n throw new IllegalArgumentException(\"Setter for field \" + key + \" was not found\", e);\n }\n\n Class<?> argumentType = setter.getParameterTypes()[0];\n\n if (argumentType.isAssignableFrom(value.getClass())) {\n setter.invoke(instance, value);\n } else {\n\n Object newValue = differenceHandler.handleDifference(value, setter.getParameterTypes()[0]);\n setter.invoke(instance, newValue);\n\n }\n }\n\n return instance;\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 }", "protected int readShort(InputStream is) throws IOException\n {\n byte[] data = new byte[2];\n if (is.read(data) != data.length)\n {\n throw new EOFException();\n }\n\n return (MPPUtility.getShort(data, 0));\n }", "public void addMarker(Marker marker) {\n if (markers == null) {\n markers = new HashSet<>();\n }\n markers.add(marker);\n marker.setMap(this);\n }", "public float conditionalLogProb(int[] given, int of) {\r\n if (given.length != windowSize - 1) {\r\n System.err.println(\"error computing conditional log prob\");\r\n System.exit(0);\r\n }\r\n int[] label = indicesFront(given);\r\n float[] masses = new float[label.length];\r\n for (int i = 0; i < masses.length; i++) {\r\n masses[i] = table[label[i]];\r\n }\r\n float z = ArrayMath.logSum(masses);\r\n\r\n return table[indexOf(given, of)] - z;\r\n }" ]
Make all elements of a String array upper case. @param strings string array, may contain null item but can't be null @return array containing all provided elements upper case
[ "public static String[] allUpperCase(String... strings){\n\t\tString[] tmp = new String[strings.length];\n\t\tfor(int idx=0;idx<strings.length;idx++){\n\t\t\tif(strings[idx] != null){\n\t\t\t\ttmp[idx] = strings[idx].toUpperCase();\n\t\t\t}\n\t\t}\n\t\treturn tmp;\n\t}" ]
[ "static final TimeBasedRollStrategy findRollStrategy(\n final AppenderRollingProperties properties) {\n if (properties.getDatePattern() == null) {\n LogLog.error(\"null date pattern\");\n return ROLL_ERROR;\n }\n // Strip out quoted sections so that we may safely scan the undecorated\n // pattern for characters that are meaningful to SimpleDateFormat.\n final LocalizedDateFormatPatternHelper localizedDateFormatPatternHelper = new LocalizedDateFormatPatternHelper(\n properties.getDatePatternLocale());\n final String undecoratedDatePattern = localizedDateFormatPatternHelper\n .excludeQuoted(properties.getDatePattern());\n if (ROLL_EACH_MINUTE.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_MINUTE;\n }\n if (ROLL_EACH_HOUR.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_HOUR;\n }\n if (ROLL_EACH_HALF_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_HALF_DAY;\n }\n if (ROLL_EACH_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_DAY;\n }\n if (ROLL_EACH_WEEK.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_WEEK;\n }\n if (ROLL_EACH_MONTH.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_MONTH;\n }\n return ROLL_ERROR;\n }", "protected boolean setChannel(final Channel newChannel) {\n if(newChannel == null) {\n return false;\n }\n synchronized (lock) {\n if(state != State.OPEN || channel != null) {\n return false;\n }\n this.channel = newChannel;\n this.channel.addCloseHandler(new CloseHandler<Channel>() {\n @Override\n public void handleClose(final Channel closed, final IOException exception) {\n synchronized (lock) {\n if(FutureManagementChannel.this.channel == closed) {\n FutureManagementChannel.this.channel = null;\n }\n lock.notifyAll();\n }\n }\n });\n lock.notifyAll();\n return true;\n }\n }", "public RendererBuilder<T> withPrototype(Renderer<? extends T> renderer) {\n if (renderer == null) {\n throw new NeedsPrototypesException(\n \"RendererBuilder can't use a null Renderer<T> instance as prototype\");\n }\n this.prototypes.add(renderer);\n return this;\n }", "@SuppressWarnings(\"unchecked\")\n public Multimap<String, Processor> getAllRequiredAttributes() {\n Multimap<String, Processor> requiredInputs = HashMultimap.create();\n for (ProcessorGraphNode root: this.roots) {\n final BiMap<String, String> inputMapper = root.getInputMapper();\n for (String attr: inputMapper.keySet()) {\n requiredInputs.put(attr, root.getProcessor());\n }\n final Object inputParameter = root.getProcessor().createInputParameter();\n if (inputParameter instanceof Values) {\n continue;\n } else if (inputParameter != null) {\n final Class<?> inputParameterClass = inputParameter.getClass();\n final Set<String> requiredAttributesDefinedInInputParameter =\n getAttributeNames(inputParameterClass,\n FILTER_ONLY_REQUIRED_ATTRIBUTES);\n for (String attName: requiredAttributesDefinedInInputParameter) {\n try {\n if (inputParameterClass.getField(attName).getType() == Values.class) {\n continue;\n }\n } catch (NoSuchFieldException e) {\n throw new RuntimeException(e);\n }\n String mappedName = ProcessorUtils.getInputValueName(\n root.getProcessor().getInputPrefix(),\n inputMapper, attName);\n requiredInputs.put(mappedName, root.getProcessor());\n }\n }\n }\n\n return requiredInputs;\n }", "public static final TimeUnit getTimeUnit(int value)\n {\n TimeUnit result = null;\n\n switch (value)\n {\n case 1:\n {\n // Appears to mean \"use the document format\"\n result = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 2:\n {\n result = TimeUnit.HOURS;\n break;\n }\n\n case 4:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 6:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 8:\n case 10:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n {\n result = TimeUnit.YEARS;\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return result;\n }", "synchronized void openConnection(final ModelController controller, final ActiveOperation.CompletedCallback<ModelNode> callback) throws Exception {\n boolean ok = false;\n final Connection connection = connectionManager.connect();\n try {\n channelHandler.executeRequest(new ServerRegisterRequest(), null, callback);\n // HC is the same version, so it will support sending the subject\n channelHandler.getAttachments().attach(TransactionalProtocolClient.SEND_IDENTITY, Boolean.TRUE);\n channelHandler.getAttachments().attach(TransactionalProtocolClient.SEND_IN_VM, Boolean.TRUE);\n channelHandler.addHandlerFactory(new TransactionalProtocolOperationHandler(controller, channelHandler, responseAttachmentSupport));\n ok = true;\n } finally {\n if(!ok) {\n connection.close();\n }\n }\n }", "private void maybeUpdateScrollbarPositions() {\r\n\r\n if (!isAttached()) {\r\n return;\r\n }\r\n\r\n if (m_scrollbar != null) {\r\n int vPos = getVerticalScrollPosition();\r\n if (m_scrollbar.getVerticalScrollPosition() != vPos) {\r\n m_scrollbar.setVerticalScrollPosition(vPos);\r\n }\r\n }\r\n }", "protected Path createTempDirectory(String prefix) {\n try {\n return Files.createTempDirectory(tempDirectory, prefix);\n } catch (IOException e) {\n throw new AllureCommandException(e);\n }\n }", "public static void main(String[] args) {\r\n Treebank treebank = new DiskTreebank();\r\n treebank.loadPath(args[0]);\r\n WordStemmer ls = new WordStemmer();\r\n for (Tree tree : treebank) {\r\n ls.visitTree(tree);\r\n System.out.println(tree);\r\n }\r\n }" ]
Read an optional boolean value form a JSON Object. @param json the JSON object to read from. @param key the key for the boolean value in the provided JSON object. @return the boolean or null if reading the boolean fails.
[ "private Boolean readOptionalBoolean(JSONObject json, String key) {\n\n try {\n return Boolean.valueOf(json.getBoolean(key));\n } catch (JSONException e) {\n LOG.debug(\"Reading optional JSON boolean failed. Default to provided default value.\", e);\n }\n return null;\n }" ]
[ "public Map<AssociationKey, Map<RowKey, Map<String, Object>>> getAssociationsMap() {\n\t\treturn Collections.unmodifiableMap( associationsKeyValueStorage );\n\t}", "public static ProtocolConnectionManager create(final Connection connection, final ConnectionOpenHandler openHandler) {\n return create(new EstablishedConnection(connection, openHandler));\n }", "private String validatePattern() {\n\n String error = null;\n switch (getPatternType()) {\n case DAILY:\n error = isEveryWorkingDay() ? null : validateInterval();\n break;\n case WEEKLY:\n error = validateInterval();\n if (null == error) {\n error = validateWeekDaySet();\n }\n break;\n case MONTHLY:\n error = validateInterval();\n if (null == error) {\n error = validateMonthSet();\n if (null == error) {\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n }\n }\n break;\n case YEARLY:\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n break;\n case INDIVIDUAL:\n case NONE:\n default:\n }\n return error;\n }", "public CredentialsConfig getResolvingCredentialsConfig() {\n if (resolverCredentialsConfig != null && resolverCredentialsConfig.isCredentialsProvided()) {\n return getResolverCredentialsConfig();\n }\n if (deployerCredentialsConfig != null) {\n return getDeployerCredentialsConfig();\n }\n\n return CredentialsConfig.EMPTY_CREDENTIALS_CONFIG;\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 }", "public Envelope getMaxExtent() {\n final int minX = 0;\n final int maxX = 1;\n final int minY = 2;\n final int maxY = 3;\n return new Envelope(this.maxExtent[minX], this.maxExtent[minY], this.maxExtent[maxX],\n this.maxExtent[maxY]);\n }", "public long[] append(MessageSet messages) throws IOException {\n checkMutable();\n long written = 0L;\n while (written < messages.getSizeInBytes())\n written += messages.writeTo(channel, 0, messages.getSizeInBytes());\n long beforeOffset = setSize.getAndAdd(written);\n return new long[]{written, beforeOffset};\n }", "private org.apache.tools.ant.types.Path addSlaveClasspath() {\n org.apache.tools.ant.types.Path path = new org.apache.tools.ant.types.Path(getProject());\n\n String [] REQUIRED_SLAVE_CLASSES = {\n SlaveMain.class.getName(),\n Strings.class.getName(),\n MethodGlobFilter.class.getName(),\n TeeOutputStream.class.getName()\n };\n\n for (String clazz : Arrays.asList(REQUIRED_SLAVE_CLASSES)) {\n String resource = clazz.replace(\".\", \"/\") + \".class\";\n File f = LoaderUtils.getResourceSource(getClass().getClassLoader(), resource);\n if (f != null) {\n path.createPath().setLocation(f);\n } else {\n throw new BuildException(\"Could not locate classpath for resource: \" + resource);\n }\n }\n return path;\n }", "@Beta\n public MSICredentials withIdentityId(String identityId) {\n this.identityId = identityId;\n this.clientId = null;\n this.objectId = null;\n return this;\n }" ]
Find the earliest start time of the specified methods. @param methods A list of test methods. @return The earliest start time.
[ "public long getStartTime(List<IInvokedMethod> methods)\n {\n long startTime = System.currentTimeMillis();\n for (IInvokedMethod method : methods)\n {\n startTime = Math.min(startTime, method.getDate());\n }\n return startTime;\n }" ]
[ "public static LayersConfig getLayersConfig(final File repoRoot) throws IOException {\n final File layersList = new File(repoRoot, LAYERS_CONF);\n if (!layersList.exists()) {\n return new LayersConfig();\n }\n final Properties properties = PatchUtils.loadProperties(layersList);\n return new LayersConfig(properties);\n }", "public static final BigInteger getBigInteger(Number value)\n {\n BigInteger result = null;\n if (value != null)\n {\n if (value instanceof BigInteger)\n {\n result = (BigInteger) value;\n }\n else\n {\n result = BigInteger.valueOf(Math.round(value.doubleValue()));\n }\n }\n return (result);\n }", "public void transform(String name, String transform) throws Exception {\n\n File configFile = new File(m_configDir, name);\n File transformFile = new File(m_xsltDir, transform);\n try (InputStream stream = new FileInputStream(transformFile)) {\n StreamSource source = new StreamSource(stream);\n transform(configFile, source);\n }\n }", "@Override\n protected void _acceptTimestampVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint)\n throws JsonMappingException\n {\n SerializerProvider prov = visitor.getProvider();\n if ((prov != null) && useNanoseconds(prov)) {\n JsonNumberFormatVisitor v2 = visitor.expectNumberFormat(typeHint);\n if (v2 != null) {\n v2.numberType(NumberType.BIG_DECIMAL);\n }\n } else {\n JsonIntegerFormatVisitor v2 = visitor.expectIntegerFormat(typeHint);\n if (v2 != null) {\n v2.numberType(NumberType.LONG);\n }\n }\n }", "public static base_responses add(nitro_service client, appfwjsoncontenttype resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwjsoncontenttype addresources[] = new appfwjsoncontenttype[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new appfwjsoncontenttype();\n\t\t\t\taddresources[i].jsoncontenttypevalue = resources[i].jsoncontenttypevalue;\n\t\t\t\taddresources[i].isregex = resources[i].isregex;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public void removeVariable(String name)\n {\n Map<String, Iterable<? extends WindupVertexFrame>> frame = peek();\n frame.remove(name);\n }", "private void map(Resource root) {\n\n for (Resource.ResourceEntry serverGroup : root.getChildren(SERVER_GROUP)) {\n String serverGroupName = serverGroup.getName();\n ModelNode serverGroupModel = serverGroup.getModel();\n String profile = serverGroupModel.require(PROFILE).asString();\n store(serverGroupName, profile, profilesToGroups);\n String socketBindingGroup = serverGroupModel.require(SOCKET_BINDING_GROUP).asString();\n store(serverGroupName, socketBindingGroup, socketsToGroups);\n\n for (Resource.ResourceEntry deployment : serverGroup.getChildren(DEPLOYMENT)) {\n store(serverGroupName, deployment.getName(), deploymentsToGroups);\n }\n\n for (Resource.ResourceEntry overlay : serverGroup.getChildren(DEPLOYMENT_OVERLAY)) {\n store(serverGroupName, overlay.getName(), overlaysToGroups);\n }\n\n }\n\n for (Resource.ResourceEntry host : root.getChildren(HOST)) {\n String hostName = host.getPathElement().getValue();\n for (Resource.ResourceEntry serverConfig : host.getChildren(SERVER_CONFIG)) {\n ModelNode serverConfigModel = serverConfig.getModel();\n String serverGroupName = serverConfigModel.require(GROUP).asString();\n store(serverGroupName, hostName, hostsToGroups);\n }\n }\n }", "public void remove( Token token ) {\n if( token == first ) {\n first = first.next;\n }\n if( token == last ) {\n last = last.previous;\n }\n if( token.next != null ) {\n token.next.previous = token.previous;\n }\n if( token.previous != null ) {\n token.previous.next = token.next;\n }\n\n token.next = token.previous = null;\n size--;\n }", "@SuppressWarnings(\"WeakerAccess\")\n public int findBeatAtTime(long milliseconds) {\n int found = Arrays.binarySearch(timeWithinTrackValues, milliseconds);\n if (found >= 0) { // An exact match, just change 0-based array index to 1-based beat number\n return found + 1;\n } else if (found == -1) { // We are before the first beat\n return found;\n } else { // We are after some beat, report its beat number\n return -(found + 1);\n }\n }" ]
A specific, existing task can be deleted by making a DELETE request on the URL for that task. Deleted tasks go into the "trash" of the user making the delete request. Tasks can be recovered from the trash within a period of 30 days; afterward they are completely removed from the system. Returns an empty data record. @param task The task to delete. @return Request object
[ "public ItemRequest<Task> delete(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"DELETE\");\n }" ]
[ "public static boolean isConstructorCall(Expression expression, String classNamePattern) {\r\n return expression instanceof ConstructorCallExpression && expression.getType().getName().matches(classNamePattern);\r\n }", "public float getBoundsWidth() {\n if (mSceneObject != null) {\n GVRSceneObject.BoundingVolume v = mSceneObject.getBoundingVolume();\n return v.maxCorner.x - v.minCorner.x;\n }\n return 0f;\n }", "private String escapeQuotes(String value)\n {\n StringBuilder sb = new StringBuilder();\n int length = value.length();\n char c;\n\n sb.append('\"');\n for (int index = 0; index < length; index++)\n {\n c = value.charAt(index);\n sb.append(c);\n\n if (c == '\"')\n {\n sb.append('\"');\n }\n }\n sb.append('\"');\n\n return (sb.toString());\n }", "private ColorItem buildColorItem(Message menuItem) {\n final int colorId = (int) ((NumberField) menuItem.arguments.get(1)).getValue();\n final String label = ((StringField) menuItem.arguments.get(3)).getValue();\n return buildColorItem(colorId, label);\n }", "public static Bounds getSymmetricBounds(int dim, double l, double u) {\n double [] L = new double[dim];\n double [] U = new double[dim];\n for(int i=0; i<dim; i++) {\n L[i] = l;\n U[i] = u;\n }\n return new Bounds(L, U);\n }", "public Column getColumn(String columnName) {\n if (columnName == null) {\n return null;\n }\n for (Column column : columns) {\n if (columnName.equals(column.getData())) {\n return column;\n }\n }\n return null;\n }", "public ParallelTaskBuilder setHttpPollerProcessor(\n HttpPollerProcessor httpPollerProcessor) {\n this.httpMeta.setHttpPollerProcessor(httpPollerProcessor);\n this.httpMeta.setPollable(true);\n return this;\n }", "public void setWorkingDay(Day day, DayType working)\n {\n DayType value;\n\n if (working == null)\n {\n if (isDerived())\n {\n value = DayType.DEFAULT;\n }\n else\n {\n value = DayType.WORKING;\n }\n }\n else\n {\n value = working;\n }\n\n m_days[day.getValue() - 1] = value;\n }", "public 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}" ]
Retrieve a specific row by index number, creating a blank row if this row does not exist. @param index index number @return MapRow instance
[ "private MapRow getRow(int index)\n {\n MapRow result;\n\n if (index == m_rows.size())\n {\n result = new MapRow(this, new HashMap<FastTrackField, Object>());\n m_rows.add(result);\n }\n else\n {\n result = m_rows.get(index);\n }\n\n return result;\n }" ]
[ "private void stream(InputStream is, File destFile) throws IOException {\n try {\n startProgress();\n OutputStream os = new FileOutputStream(destFile);\n \n boolean finished = false;\n try {\n byte[] buf = new byte[1024 * 10];\n int read;\n while ((read = is.read(buf)) >= 0) {\n os.write(buf, 0, read);\n processedBytes += read;\n logProgress();\n }\n \n os.flush();\n finished = true;\n } finally {\n os.close();\n if (!finished) {\n destFile.delete();\n }\n }\n } finally {\n is.close();\n completeProgress();\n }\n }", "private SubProject readSubProject(byte[] data, int uniqueIDOffset, int filePathOffset, int fileNameOffset, int subprojectIndex)\n {\n try\n {\n SubProject sp = new SubProject();\n int type = SUBPROJECT_TASKUNIQUEID0;\n\n if (uniqueIDOffset != -1)\n {\n int value = MPPUtility.getInt(data, uniqueIDOffset);\n type = MPPUtility.getInt(data, uniqueIDOffset + 4);\n switch (type)\n {\n case SUBPROJECT_TASKUNIQUEID0:\n case SUBPROJECT_TASKUNIQUEID1:\n case SUBPROJECT_TASKUNIQUEID2:\n case SUBPROJECT_TASKUNIQUEID3:\n case SUBPROJECT_TASKUNIQUEID4:\n case SUBPROJECT_TASKUNIQUEID5:\n case SUBPROJECT_TASKUNIQUEID6:\n {\n sp.setTaskUniqueID(Integer.valueOf(value));\n m_taskSubProjects.put(sp.getTaskUniqueID(), sp);\n break;\n }\n\n default:\n {\n if (value != 0)\n {\n sp.addExternalTaskUniqueID(Integer.valueOf(value));\n m_taskSubProjects.put(Integer.valueOf(value), sp);\n }\n break;\n }\n }\n\n // Now get the unique id offset for this subproject\n value = 0x00800000 + ((subprojectIndex - 1) * 0x00400000);\n sp.setUniqueIDOffset(Integer.valueOf(value));\n }\n\n if (type == SUBPROJECT_TASKUNIQUEID4)\n {\n sp.setFullPath(MPPUtility.getUnicodeString(data, filePathOffset));\n }\n else\n {\n //\n // First block header\n //\n filePathOffset += 18;\n\n //\n // String size as a 4 byte int\n //\n filePathOffset += 4;\n\n //\n // Full DOS path\n //\n sp.setDosFullPath(MPPUtility.getString(data, filePathOffset));\n filePathOffset += (sp.getDosFullPath().length() + 1);\n\n //\n // 24 byte block\n //\n filePathOffset += 24;\n\n //\n // 4 byte block size\n //\n int size = MPPUtility.getInt(data, filePathOffset);\n filePathOffset += 4;\n if (size == 0)\n {\n sp.setFullPath(sp.getDosFullPath());\n }\n else\n {\n //\n // 4 byte unicode string size in bytes\n //\n size = MPPUtility.getInt(data, filePathOffset);\n filePathOffset += 4;\n\n //\n // 2 byte data\n //\n filePathOffset += 2;\n\n //\n // Unicode string\n //\n sp.setFullPath(MPPUtility.getUnicodeString(data, filePathOffset, size));\n //filePathOffset += size;\n }\n\n //\n // Second block header\n //\n fileNameOffset += 18;\n\n //\n // String size as a 4 byte int\n //\n fileNameOffset += 4;\n\n //\n // DOS file name\n //\n sp.setDosFileName(MPPUtility.getString(data, fileNameOffset));\n fileNameOffset += (sp.getDosFileName().length() + 1);\n\n //\n // 24 byte block\n //\n fileNameOffset += 24;\n\n //\n // 4 byte block size\n //\n size = MPPUtility.getInt(data, fileNameOffset);\n fileNameOffset += 4;\n\n if (size == 0)\n {\n sp.setFileName(sp.getDosFileName());\n }\n else\n {\n //\n // 4 byte unicode string size in bytes\n //\n size = MPPUtility.getInt(data, fileNameOffset);\n fileNameOffset += 4;\n\n //\n // 2 byte data\n //\n fileNameOffset += 2;\n\n //\n // Unicode string\n //\n sp.setFileName(MPPUtility.getUnicodeString(data, fileNameOffset, size));\n //fileNameOffset += size;\n }\n }\n\n //System.out.println(sp.toString());\n\n // Add to the list of subprojects\n m_file.getSubProjects().add(sp);\n\n return (sp);\n }\n\n //\n // Admit defeat at this point - we have probably stumbled\n // upon a data format we don't understand, so we'll fail\n // gracefully here. This will now be reported as a missing\n // sub project error by end users of the library, rather\n // than as an exception being thrown.\n //\n catch (ArrayIndexOutOfBoundsException ex)\n {\n return (null);\n }\n }", "public static boolean classNodeImplementsType(ClassNode node, Class target) {\r\n ClassNode targetNode = ClassHelper.make(target);\r\n if (node.implementsInterface(targetNode)) {\r\n return true;\r\n }\r\n if (node.isDerivedFrom(targetNode)) {\r\n return true;\r\n }\r\n if (node.getName().equals(target.getName())) {\r\n return true;\r\n }\r\n if (node.getName().equals(target.getSimpleName())) {\r\n return true;\r\n }\r\n if (node.getSuperClass() != null && node.getSuperClass().getName().equals(target.getName())) {\r\n return true;\r\n }\r\n if (node.getSuperClass() != null && node.getSuperClass().getName().equals(target.getSimpleName())) {\r\n return true;\r\n }\r\n if (node.getInterfaces() != null) {\r\n for (ClassNode declaredInterface : node.getInterfaces()) {\r\n if (classNodeImplementsType(declaredInterface, target)) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }", "public Metadata add(String path, List<String> values) {\n JsonArray arr = new JsonArray();\n for (String value : values) {\n arr.add(value);\n }\n this.values.add(this.pathToProperty(path), arr);\n this.addOp(\"add\", path, arr);\n return this;\n }", "public void process(CompilationUnitDeclaration unit, int i) {\n this.lookupEnvironment.unitBeingCompleted = unit;\n long parseStart = System.currentTimeMillis();\n\n this.parser.getMethodBodies(unit);\n\n long resolveStart = System.currentTimeMillis();\n this.stats.parseTime += resolveStart - parseStart;\n\n // fault in fields & methods\n if (unit.scope != null)\n unit.scope.faultInTypes();\n\n // verify inherited methods\n if (unit.scope != null)\n unit.scope.verifyMethods(this.lookupEnvironment.methodVerifier());\n\n // type checking\n unit.resolve();\n\n long analyzeStart = System.currentTimeMillis();\n this.stats.resolveTime += analyzeStart - resolveStart;\n\n //No need of analysis or generation of code if statements are not required\n if (!this.options.ignoreMethodBodies) unit.analyseCode(); // flow analysis\n\n long generateStart = System.currentTimeMillis();\n this.stats.analyzeTime += generateStart - analyzeStart;\n\n if (!this.options.ignoreMethodBodies) unit.generateCode(); // code generation\n\n // reference info\n if (this.options.produceReferenceInfo && unit.scope != null)\n unit.scope.storeDependencyInfo();\n\n // finalize problems (suppressWarnings)\n unit.finalizeProblems();\n\n this.stats.generateTime += System.currentTimeMillis() - generateStart;\n\n // refresh the total number of units known at this stage\n unit.compilationResult.totalUnitsKnown = this.totalUnits;\n\n this.lookupEnvironment.unitBeingCompleted = null;\n }", "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 }", "public void signIn(String key, WebSocketConnection connection) {\n ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key);\n bag.put(connection, connection);\n }", "@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher addBooleanFilter(String attribute, Boolean value) {\n booleanFilterMap.put(attribute, value);\n rebuildQueryFacetFilters();\n return this;\n }", "protected void _format(EObject obj, IFormattableDocument document) {\n\t\tfor (EObject child : obj.eContents())\n\t\t\tdocument.format(child);\n\t}" ]
Returns the compact records for all users that are members of the team. @param team Globally unique identifier for the team. @return Request object
[ "public CollectionRequest<Team> users(String team) {\n \n String path = String.format(\"/teams/%s/users\", team);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }" ]
[ "public void setLargePayloadSupportEnabled(AmazonS3 s3, String s3BucketName) {\n\t\tif (s3 == null || s3BucketName == null) {\n\t\t\tString errorMessage = \"S3 client and/or S3 bucket name cannot be null.\";\n\t\t\tLOG.error(errorMessage);\n\t\t\tthrow new AmazonClientException(errorMessage);\n\t\t}\n\t\tif (isLargePayloadSupportEnabled()) {\n\t\t\tLOG.warn(\"Large-payload support is already enabled. Overwriting AmazonS3Client and S3BucketName.\");\n\t\t}\n\t\tthis.s3 = s3;\n\t\tthis.s3BucketName = s3BucketName;\n\t\tlargePayloadSupport = true;\n\t\tLOG.info(\"Large-payload support enabled.\");\n\t}", "public static I_CmsSearchConfigurationPagination create(\n String pageParam,\n List<Integer> pageSizes,\n Integer pageNavLength) {\n\n return (pageParam != null) || (pageSizes != null) || (pageNavLength != null)\n ? new CmsSearchConfigurationPagination(pageParam, pageSizes, pageNavLength)\n : null;\n\n }", "protected InputStream getCompressorInputStream(InputStream inputStream,\n\t\t\tCompressionType compressionType) throws IOException {\n\t\tswitch (compressionType) {\n\t\tcase NONE:\n\t\t\treturn inputStream;\n\t\tcase GZIP:\n\t\t\treturn new GZIPInputStream(inputStream);\n\t\tcase BZ2:\n\t\t\treturn new BZip2CompressorInputStream(new BufferedInputStream(\n\t\t\t\t\tinputStream));\n\t\tdefault:\n\t\t\tthrow new IllegalArgumentException(\"Unsupported compression type: \"\n\t\t\t\t\t+ compressionType);\n\t\t}\n\t}", "public void writeFinalResults() {\n\t\tprintStatus();\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"gender-ratios.csv\"))) {\n\n\t\t\tout.print(\"Site key,pages total,pages on humans,pages on humans with gender\");\n\t\t\tfor (EntityIdValue gender : this.genderNamesList) {\n\t\t\t\tout.print(\",\" + this.genderNames.get(gender) + \" (\"\n\t\t\t\t\t\t+ gender.getId() + \")\");\n\t\t\t}\n\t\t\tout.println();\n\n\t\t\tList<SiteRecord> siteRecords = new ArrayList<>(\n\t\t\t\t\tthis.siteRecords.values());\n\t\t\tCollections.sort(siteRecords, new SiteRecordComparator());\n\t\t\tfor (SiteRecord siteRecord : siteRecords) {\n\t\t\t\tout.print(siteRecord.siteKey + \",\" + siteRecord.pageCount + \",\"\n\t\t\t\t\t\t+ siteRecord.humanPageCount + \",\"\n\t\t\t\t\t\t+ siteRecord.humanGenderPageCount);\n\n\t\t\t\tfor (EntityIdValue gender : this.genderNamesList) {\n\t\t\t\t\tif (siteRecord.genderCounts.containsKey(gender)) {\n\t\t\t\t\t\tout.print(\",\" + siteRecord.genderCounts.get(gender));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tout.print(\",0\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tout.println();\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "public Widget addControl(String name, int resId, String label, Widget.OnTouchListener listener) {\n return addControl(name, resId, label, listener, -1);\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 }", "private void primeCache() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) {\n if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck\n handleUpdate(new TrackMetadataUpdate(entry.getKey().player, entry.getValue()));\n }\n }\n }\n });\n }", "public PlacesList<Place> placesForUser(int placeType, String woeId, String placeId, String threshold, Date minUploadDate, Date maxUploadDate,\r\n Date minTakenDate, Date maxTakenDate) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n PlacesList<Place> placesList = new PlacesList<Place>();\r\n parameters.put(\"method\", METHOD_PLACES_FOR_USER);\r\n\r\n parameters.put(\"place_type\", intPlaceTypeToString(placeType));\r\n if (placeId != null) {\r\n parameters.put(\"place_id\", placeId);\r\n }\r\n if (woeId != null) {\r\n parameters.put(\"woe_id\", woeId);\r\n }\r\n if (threshold != null) {\r\n parameters.put(\"threshold\", threshold);\r\n }\r\n if (minUploadDate != null) {\r\n parameters.put(\"min_upload_date\", Long.toString(minUploadDate.getTime() / 1000L));\r\n }\r\n if (maxUploadDate != null) {\r\n parameters.put(\"max_upload_date\", Long.toString(maxUploadDate.getTime() / 1000L));\r\n }\r\n if (minTakenDate != null) {\r\n parameters.put(\"min_taken_date\", ((DateFormat) SearchParameters.MYSQL_DATE_FORMATS.get()).format(minTakenDate));\r\n }\r\n if (maxTakenDate != null) {\r\n parameters.put(\"max_taken_date\", ((DateFormat) SearchParameters.MYSQL_DATE_FORMATS.get()).format(maxTakenDate));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element placesElement = response.getPayload();\r\n NodeList placesNodes = placesElement.getElementsByTagName(\"place\");\r\n placesList.setPage(\"1\");\r\n placesList.setPages(\"1\");\r\n placesList.setPerPage(\"\" + placesNodes.getLength());\r\n placesList.setTotal(\"\" + placesNodes.getLength());\r\n for (int i = 0; i < placesNodes.getLength(); i++) {\r\n Element placeElement = (Element) placesNodes.item(i);\r\n placesList.add(parsePlace(placeElement));\r\n }\r\n return placesList;\r\n }", "public static double diagProd( DMatrix1Row T )\n {\n double prod = 1.0;\n int N = Math.min(T.numRows,T.numCols);\n for( int i = 0; i < N; i++ ) {\n prod *= T.unsafe_get(i,i);\n }\n\n return prod;\n }" ]
Check if the given class represents an array of primitives, i.e. boolean, byte, char, short, int, long, float, or double. @param clazz the class to check @return whether the given class is a primitive array class
[ "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 void fireResourceWrittenEvent(Resource resource)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.resourceWritten(resource);\n }\n }\n }", "public static URL getAuthorizationURL(String clientID, URI redirectUri, String state, List<String> scopes) {\n URLTemplate template = new URLTemplate(AUTHORIZATION_URL);\n QueryStringBuilder queryBuilder = new QueryStringBuilder().appendParam(\"client_id\", clientID)\n .appendParam(\"response_type\", \"code\")\n .appendParam(\"redirect_uri\", redirectUri.toString())\n .appendParam(\"state\", state);\n\n if (scopes != null && !scopes.isEmpty()) {\n StringBuilder builder = new StringBuilder();\n int size = scopes.size() - 1;\n int i = 0;\n while (i < size) {\n builder.append(scopes.get(i));\n builder.append(\" \");\n i++;\n }\n builder.append(scopes.get(i));\n\n queryBuilder.appendParam(\"scope\", builder.toString());\n }\n\n return template.buildWithQuery(\"\", queryBuilder.toString());\n }", "@Pure\n\tpublic static <P1, P2, P3, P4, RESULT> Function3<P2, P3, P4, RESULT> curry(\n\t\t\tfinal Function4<? super P1, ? super P2, ? super P3, ? super P4, ? extends RESULT> function, final P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function3<P2, P3, P4, RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply(P2 p2, P3 p3, P4 p4) {\n\t\t\t\treturn function.apply(argument, p2, p3, p4);\n\t\t\t}\n\t\t};\n\t}", "public static void applyMultiIconTo(Drawable icon, int iconColor, Drawable selectedIcon, int selectedIconColor, boolean tinted, ImageView imageView) {\n //if we have an icon then we want to set it\n if (icon != null) {\n //if we got a different color for the selectedIcon we need a StateList\n if (selectedIcon != null) {\n if (tinted) {\n imageView.setImageDrawable(new PressedEffectStateListDrawable(icon, selectedIcon, iconColor, selectedIconColor));\n } else {\n imageView.setImageDrawable(UIUtils.getIconStateList(icon, selectedIcon));\n }\n } else if (tinted) {\n imageView.setImageDrawable(new PressedEffectStateListDrawable(icon, iconColor, selectedIconColor));\n } else {\n imageView.setImageDrawable(icon);\n }\n //make sure we display the icon\n imageView.setVisibility(View.VISIBLE);\n } else {\n //hide the icon\n imageView.setVisibility(View.GONE);\n }\n }", "public String getURN() throws InvalidRegistrationContentException {\n if (parsedConfig==null || parsedConfig.urn==null || parsedConfig.urn.trim().isEmpty()) {\n throw new InvalidRegistrationContentException(\"Invalid registration config - failed to read mediator URN\");\n }\n return parsedConfig.urn;\n }", "public AssemblyResponse save(boolean isResumable)\n throws RequestException, LocalOperationException {\n Request request = new Request(getClient());\n options.put(\"steps\", steps.toMap());\n\n // only do tus uploads if files will be uploaded\n if (isResumable && getFilesCount() > 0) {\n Map<String, String> tusOptions = new HashMap<String, String>();\n tusOptions.put(\"tus_num_expected_upload_files\", Integer.toString(getFilesCount()));\n\n AssemblyResponse response = new AssemblyResponse(\n request.post(\"/assemblies\", options, tusOptions, null, null), true);\n\n // check if the assembly returned an error\n if (response.hasError()) {\n throw new RequestException(\"Request to Assembly failed: \" + response.json().getString(\"error\"));\n }\n\n try {\n handleTusUpload(response);\n } catch (IOException e) {\n throw new LocalOperationException(e);\n } catch (ProtocolException e) {\n throw new RequestException(e);\n }\n return response;\n } else {\n return new AssemblyResponse(request.post(\"/assemblies\", options, null, files, fileStreams));\n }\n }", "private void handleArchiveByFile(Predicate<String> filter, File archive, List<String> discoveredFiles)\n {\n try\n {\n try (ZipFile zip = new ZipFile(archive))\n {\n Enumeration<? extends ZipEntry> entries = zip.entries();\n \n while (entries.hasMoreElements())\n {\n ZipEntry entry = entries.nextElement();\n String name = entry.getName();\n if (filter.accept(name))\n discoveredFiles.add(name);\n }\n }\n }\n catch (IOException e)\n {\n throw new RuntimeException(\"Error handling file \" + archive, e);\n }\n }", "public 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 }", "public static ClassLoader overrideThreadContextClassLoader(ClassLoader classLoaderToUse) {\n\t\tThread currentThread = Thread.currentThread();\n\t\tClassLoader threadContextClassLoader = currentThread.getContextClassLoader();\n\t\tif (classLoaderToUse != null && !classLoaderToUse.equals(threadContextClassLoader)) {\n\t\t\tcurrentThread.setContextClassLoader(classLoaderToUse);\n\t\t\treturn threadContextClassLoader;\n\t\t}\n\t\telse {\n\t\t\treturn null;\n\t\t}\n\t}" ]
Here we specify the configuration, starting from default MostUsefulConfiguration, and changing only what is needed
[ "@Override\n public Configuration configuration() {\n return new MostUsefulConfiguration()\n // where to find the stories\n .useStoryLoader(new LoadFromClasspath(this.getClass())) \n // CONSOLE and TXT reporting\n .useStoryReporterBuilder(new StoryReporterBuilder().withDefaultFormats().withFormats(Format.CONSOLE, Format.TXT)); \n }" ]
[ "private void calculateMenuItemPosition() {\n\n float itemRadius = (expandedRadius + collapsedRadius) / 2, f;\n RectF area = new RectF(\n center.x - itemRadius,\n center.y - itemRadius,\n center.x + itemRadius,\n center.y + itemRadius);\n Path path = new Path();\n path.addArc(area, (float) fromAngle, (float) (toAngle - fromAngle));\n PathMeasure measure = new PathMeasure(path, false);\n float len = measure.getLength();\n int divisor = getChildCount();\n float divider = len / divisor;\n\n for (int i = 0; i < getChildCount(); i++) {\n float[] coords = new float[2];\n measure.getPosTan(i * divider + divider * .5f, coords, null);\n FilterMenu.Item item = (FilterMenu.Item) getChildAt(i).getTag();\n item.setX((int) coords[0] - item.getView().getMeasuredWidth() / 2);\n item.setY((int) coords[1] - item.getView().getMeasuredHeight() / 2);\n }\n }", "private static void tryWritePreferenceOnDisk(Preferences preference) throws BackingStoreException {\n final String DUMMY_PROP=\"dummywrite\";\n instance.put(DUMMY_PROP,\"test\");\n instance.flush();\n instance.remove(DUMMY_PROP);\n instance.flush();\n }", "private PlayState3 findPlayState3() {\n PlayState3 result = PLAY_STATE_3_MAP.get(packetBytes[157]);\n if (result == null) {\n return PlayState3.UNKNOWN;\n }\n return result;\n }", "private static Constraint loadConstraint(Annotation context) {\n Constraint constraint = null;\n final ServiceLoader<Constraint> constraints = ServiceLoader.load(Constraint.class);\n\n for (Constraint aConstraint : constraints) {\n try {\n aConstraint.getClass().getDeclaredMethod(\"check\", context.annotationType());\n constraint = aConstraint;\n break;\n } catch (NoSuchMethodException e) {\n // Look for next implementation if method not found with required signature.\n }\n }\n\n if (constraint == null) {\n throw new IllegalStateException(\"Couldn't found any implementation of \" + Constraint.class.getName());\n }\n return constraint;\n }", "@Override\n public boolean isCompleteRequest(final ByteBuffer buffer) throws VoldemortException {\n DataInputStream inputStream = new DataInputStream(new ByteBufferBackedInputStream(buffer));\n\n try {\n\n byte opCode = inputStream.readByte();\n // Store Name\n inputStream.readUTF();\n // Store routing type\n getRoutingType(inputStream);\n\n switch(opCode) {\n case VoldemortOpCode.GET_VERSION_OP_CODE:\n if(!GetVersionRequestHandler.isCompleteRequest(inputStream, buffer))\n return false;\n break;\n case VoldemortOpCode.GET_OP_CODE:\n if(!GetRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))\n return false;\n break;\n case VoldemortOpCode.GET_ALL_OP_CODE:\n if(!GetAllRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))\n return false;\n break;\n case VoldemortOpCode.PUT_OP_CODE: {\n if(!PutRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))\n return false;\n break;\n }\n case VoldemortOpCode.DELETE_OP_CODE: {\n if(!DeleteRequestHandler.isCompleteRequest(inputStream, buffer))\n return false;\n break;\n }\n default:\n throw new VoldemortException(\" Unrecognized Voldemort OpCode \" + opCode);\n }\n // This should not happen, if we reach here and if buffer has more\n // data, there is something wrong.\n if(buffer.hasRemaining()) {\n logger.info(\"Probably a client bug, Discarding additional bytes in isCompleteRequest. Opcode: \"\n + opCode + \", remaining bytes: \" + buffer.remaining());\n }\n return true;\n } catch(IOException e) {\n // This could also occur if the various methods we call into\n // re-throw a corrupted value error as some other type of exception.\n // For example, updating the position on a buffer past its limit\n // throws an InvalidArgumentException.\n if(logger.isDebugEnabled())\n logger.debug(\"Probable partial read occurred causing exception\", e);\n\n return false;\n }\n }", "public PeriodicEvent runEvery(Runnable task, float delay, float period,\n int repetitions) {\n if (repetitions < 1) {\n return null;\n } else if (repetitions == 1) {\n // Better to burn a handful of CPU cycles than to churn memory by\n // creating a new callback\n return runAfter(task, delay);\n } else {\n return runEvery(task, delay, period, new RunFor(repetitions));\n }\n }", "public void setPerms(String photoId, Permissions permissions) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_PERMS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"is_public\", permissions.isPublicFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_friend\", permissions.isFriendFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_family\", permissions.isFamilyFlag() ? \"1\" : \"0\");\r\n parameters.put(\"perm_comment\", Integer.toString(permissions.getComment()));\r\n parameters.put(\"perm_addmeta\", Integer.toString(permissions.getAddmeta()));\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "private SortedSet<Date> filterExceptions(SortedSet<Date> dates) {\n\n SortedSet<Date> result = new TreeSet<Date>();\n for (Date d : dates) {\n if (!m_exceptions.contains(d)) {\n result.add(d);\n }\n }\n return result;\n }", "public int getTrailingBitCount(boolean network) {\n\t\tint count = getDivisionCount();\n\t\tif(count == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tlong back = network ? 0 : getDivision(0).getMaxValue();\n\t\tint bitLen = 0;\n\t\tfor(int i = count - 1; i >= 0; i--) {\n\t\t\tIPAddressDivision seg = getDivision(i);\n\t\t\tlong value = seg.getDivisionValue();\n\t\t\tif(value != back) {\n\t\t\t\treturn bitLen + seg.getTrailingBitCount(network);\n\t\t\t}\n\t\t\tbitLen += seg.getBitCount();\n\t\t}\n\t\treturn bitLen;\n\t}" ]
Returns an iterable containing the items in this folder and specifies which child fields to retrieve from the API. @param fields the fields to retrieve. @return an iterable containing the items in this folder.
[ "public Iterable<BoxItem.Info> getChildren(final String... fields) {\n return new Iterable<BoxItem.Info>() {\n @Override\n public Iterator<BoxItem.Info> iterator() {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", fields).toString();\n URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), queryString, getID());\n return new BoxItemIterator(getAPI(), url);\n }\n };\n }" ]
[ "public void addClass(ClassDescriptorDef classDef)\r\n {\r\n classDef.setOwner(this);\r\n // Regardless of the format of the class name, we're using the fully qualified format\r\n // This is safe because of the package & class naming constraints of the Java language\r\n _classDefs.put(classDef.getQualifiedName(), classDef);\r\n }", "private 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 }", "public static int numberAwareCompareTo(Comparable self, Comparable other) {\n NumberAwareComparator<Comparable> numberAwareComparator = new NumberAwareComparator<Comparable>();\n return numberAwareComparator.compare(self, other);\n }", "public IndexDescriptorDef getIndexDescriptor(String name)\r\n {\r\n IndexDescriptorDef indexDef = null;\r\n\r\n for (Iterator it = _indexDescriptors.iterator(); it.hasNext(); )\r\n {\r\n indexDef = (IndexDescriptorDef)it.next();\r\n if (indexDef.getName().equals(name))\r\n {\r\n return indexDef;\r\n }\r\n }\r\n return null;\r\n }", "private void handleMemoryGetId(SerialMessage incomingMessage) {\n\t\tthis.homeId = ((incomingMessage.getMessagePayloadByte(0)) << 24) | \n\t\t\t\t((incomingMessage.getMessagePayloadByte(1)) << 16) | \n\t\t\t\t((incomingMessage.getMessagePayloadByte(2)) << 8) | \n\t\t\t\t(incomingMessage.getMessagePayloadByte(3));\n\t\tthis.ownNodeId = incomingMessage.getMessagePayloadByte(4);\n\t\tlogger.debug(String.format(\"Got MessageMemoryGetId response. Home id = 0x%08X, Controller Node id = %d\", this.homeId, this.ownNodeId));\n\t}", "public void setStatusBarMessage(final String message)\r\n {\r\n // Guaranteed to return a non-null array\r\n Object[] listeners = listenerList.getListenerList();\r\n // Process the listeners last to first, notifying\r\n // those that are interested in this event\r\n for (int i = listeners.length-2; i>=0; i-=2) {\r\n if (listeners[i]==StatusMessageListener.class) \r\n {\r\n ((StatusMessageListener)listeners[i+1]).statusMessageReceived(message);\r\n } \r\n } \r\n }", "public static String wordShape(String inStr, int wordShaper, Collection<String> knownLCWords) {\r\n // this first bit is for backwards compatibility with how things were first\r\n // implemented, where the word shaper name encodes whether to useLC.\r\n // If the shaper is in the old compatibility list, then a specified\r\n // list of knownLCwords is ignored\r\n if (knownLCWords != null && dontUseLC(wordShaper)) {\r\n knownLCWords = null;\r\n }\r\n switch (wordShaper) {\r\n case NOWORDSHAPE:\r\n return inStr;\r\n case WORDSHAPEDAN1:\r\n return wordShapeDan1(inStr);\r\n case WORDSHAPECHRIS1:\r\n return wordShapeChris1(inStr);\r\n case WORDSHAPEDAN2:\r\n return wordShapeDan2(inStr, knownLCWords);\r\n case WORDSHAPEDAN2USELC:\r\n return wordShapeDan2(inStr, knownLCWords);\r\n case WORDSHAPEDAN2BIO:\r\n return wordShapeDan2Bio(inStr, knownLCWords);\r\n case WORDSHAPEDAN2BIOUSELC:\r\n return wordShapeDan2Bio(inStr, knownLCWords);\r\n case WORDSHAPEJENNY1:\r\n return wordShapeJenny1(inStr, knownLCWords);\r\n case WORDSHAPEJENNY1USELC:\r\n return wordShapeJenny1(inStr, knownLCWords);\r\n case WORDSHAPECHRIS2:\r\n return wordShapeChris2(inStr, false, knownLCWords);\r\n case WORDSHAPECHRIS2USELC:\r\n return wordShapeChris2(inStr, false, knownLCWords);\r\n case WORDSHAPECHRIS3:\r\n return wordShapeChris2(inStr, true, knownLCWords);\r\n case WORDSHAPECHRIS3USELC:\r\n return wordShapeChris2(inStr, true, knownLCWords);\r\n case WORDSHAPECHRIS4:\r\n return wordShapeChris4(inStr, false, knownLCWords);\r\n case WORDSHAPEDIGITS:\r\n return wordShapeDigits(inStr);\r\n default:\r\n throw new IllegalStateException(\"Bad WordShapeClassifier\");\r\n }\r\n }", "public static long count(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_bridgegroup_binding obj = new nstrafficdomain_bridgegroup_binding();\n\t\tobj.set_td(td);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tnstrafficdomain_bridgegroup_binding response[] = (nstrafficdomain_bridgegroup_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}", "private void addCalendar(MpxjTreeNode parentNode, final ProjectCalendar calendar)\n {\n MpxjTreeNode calendarNode = new MpxjTreeNode(calendar, CALENDAR_EXCLUDED_METHODS)\n {\n @Override public String toString()\n {\n return calendar.getName();\n }\n };\n parentNode.add(calendarNode);\n\n MpxjTreeNode daysFolder = new MpxjTreeNode(\"Days\");\n calendarNode.add(daysFolder);\n\n for (Day day : Day.values())\n {\n addCalendarDay(daysFolder, calendar, day);\n }\n\n MpxjTreeNode exceptionsFolder = new MpxjTreeNode(\"Exceptions\");\n calendarNode.add(exceptionsFolder);\n\n for (ProjectCalendarException exception : calendar.getCalendarExceptions())\n {\n addCalendarException(exceptionsFolder, exception);\n }\n }" ]
Use this API to fetch csvserver_cachepolicy_binding resources of given name .
[ "public static csvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cachepolicy_binding obj = new csvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cachepolicy_binding response[] = (csvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "@SuppressWarnings(\"unchecked\")\n public <T> Map<String, T> find(final Class<T> valueTypeToFind) {\n return (Map<String, T>) this.values.entrySet().stream()\n .filter(input -> valueTypeToFind.isInstance(input.getValue()))\n .collect(\n Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\n }", "public void recordAsyncOpTimeNs(SocketDestination dest, long opTimeNs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordAsyncOpTimeNs(null, opTimeNs);\n recordAsyncOpTimeNs(null, opTimeNs);\n } else {\n this.asynOpTimeRequestCounter.addRequest(opTimeNs);\n }\n }", "public void setRegExp(final String pattern,\n final String invalidCharactersInNameErrorMessage,\n final String invalidCharacterTypedMessage) {\n regExp = RegExp.compile(pattern);\n this.invalidCharactersInNameErrorMessage = invalidCharactersInNameErrorMessage;\n this.invalidCharacterTypedMessage = invalidCharacterTypedMessage;\n }", "public static base_responses update(nitro_service client, onlinkipv6prefix resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tonlinkipv6prefix updateresources[] = new onlinkipv6prefix[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new onlinkipv6prefix();\n\t\t\t\tupdateresources[i].ipv6prefix = resources[i].ipv6prefix;\n\t\t\t\tupdateresources[i].onlinkprefix = resources[i].onlinkprefix;\n\t\t\t\tupdateresources[i].autonomusprefix = resources[i].autonomusprefix;\n\t\t\t\tupdateresources[i].depricateprefix = resources[i].depricateprefix;\n\t\t\t\tupdateresources[i].decrementprefixlifetimes = resources[i].decrementprefixlifetimes;\n\t\t\t\tupdateresources[i].prefixvalidelifetime = resources[i].prefixvalidelifetime;\n\t\t\t\tupdateresources[i].prefixpreferredlifetime = resources[i].prefixpreferredlifetime;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public Collection<Method> getAllMethods(String name, int paramCount) {\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 for (Method method : map.values()) {\n if (method.getParameterTypes().length == paramCount) {\n methods.add(method);\n }\n }\n }\n return methods;\n }", "public void setPattern(String patternType) {\r\n\r\n final PatternType type = PatternType.valueOf(patternType);\r\n if (type != m_model.getPatternType()) {\r\n removeExceptionsOnChange(new Command() {\r\n\r\n public void execute() {\r\n\r\n EndType oldEndType = m_model.getEndType();\r\n m_model.setPatternType(type);\r\n m_model.setIndividualDates(null);\r\n m_model.setInterval(getPatternDefaultValues().getInterval());\r\n m_model.setEveryWorkingDay(Boolean.FALSE);\r\n m_model.clearWeekDays();\r\n m_model.clearIndividualDates();\r\n m_model.clearWeeksOfMonth();\r\n m_model.clearExceptions();\r\n if (type.equals(PatternType.NONE) || type.equals(PatternType.INDIVIDUAL)) {\r\n m_model.setEndType(EndType.SINGLE);\r\n } else if (oldEndType.equals(EndType.SINGLE)) {\r\n m_model.setEndType(EndType.TIMES);\r\n m_model.setOccurrences(10);\r\n m_model.setSeriesEndDate(null);\r\n }\r\n m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth());\r\n m_model.setMonth(getPatternDefaultValues().getMonth());\r\n if (type.equals(PatternType.WEEKLY)) {\r\n m_model.setWeekDay(getPatternDefaultValues().getWeekDay());\r\n }\r\n valueChanged();\r\n }\r\n });\r\n }\r\n\r\n }", "public static appfwlearningsettings[] get(nitro_service service) throws Exception{\n\t\tappfwlearningsettings obj = new appfwlearningsettings();\n\t\tappfwlearningsettings[] response = (appfwlearningsettings[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static void main(final String[] args) throws IOException\n {\n // This is just a _hack_ ...\n BufferedReader reader = null;\n if (args.length == 0)\n {\n System.err.println(\"No input file specified.\");\n System.exit(-1);\n }\n if (args.length > 1)\n {\n reader = new BufferedReader(new InputStreamReader(new FileInputStream(args[1]), \"UTF-8\"));\n String line = reader.readLine();\n while (line != null && !line.startsWith(\"<!-- ###\"))\n {\n System.out.println(line);\n line = reader.readLine();\n }\n }\n System.out.println(Processor.process(new File(args[0])));\n if (args.length > 1 && reader != null)\n {\n String line = reader.readLine();\n while (line != null)\n {\n System.out.println(line);\n line = reader.readLine();\n }\n reader.close();\n }\n }", "public static PackageType resolve(final MavenProject project) {\n final String packaging = project.getPackaging().toLowerCase(Locale.ROOT);\n if (DEFAULT_TYPES.containsKey(packaging)) {\n return DEFAULT_TYPES.get(packaging);\n }\n return new PackageType(packaging);\n }" ]
Write a new line and indent.
[ "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 }" ]
[ "public static void writeUTF(@NotNull final OutputStream stream, @NotNull final String str) throws IOException {\n try (DataOutputStream dataStream = new DataOutputStream(stream)) {\n int len = str.length();\n if (len < SINGLE_UTF_CHUNK_SIZE) {\n dataStream.writeUTF(str);\n } else {\n int startIndex = 0;\n int endIndex;\n do {\n endIndex = startIndex + SINGLE_UTF_CHUNK_SIZE;\n if (endIndex > len) {\n endIndex = len;\n }\n dataStream.writeUTF(str.substring(startIndex, endIndex));\n startIndex += SINGLE_UTF_CHUNK_SIZE;\n } while (endIndex < len);\n }\n }\n }", "synchronized void storeUninstallTimestamp() {\n\n if (!this.belowMemThreshold()) {\n getConfigLogger().verbose(\"There is not enough space left on the device to store data, data discarded\");\n return ;\n }\n final String tableName = Table.UNINSTALL_TS.getName();\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n final ContentValues cv = new ContentValues();\n cv.put(KEY_CREATED_AT, System.currentTimeMillis());\n db.insert(tableName, null, cv);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error adding data to table \" + tableName + \" Recreating DB\");\n dbHelper.deleteDatabase();\n } finally {\n dbHelper.close();\n }\n\n }", "static void showWarning(final String caption, final String description) {\n\n Notification warning = new Notification(caption, description, Type.WARNING_MESSAGE, true);\n warning.setDelayMsec(-1);\n warning.show(UI.getCurrent().getPage());\n\n }", "public void clearMarkers() {\n if (markers != null && !markers.isEmpty()) {\n markers.forEach((m) -> {\n m.setMap(null);\n });\n markers.clear();\n }", "private T getWrappedPublisher(Publisher flexiblePublisher, Class<T> type) {\n if (!(flexiblePublisher instanceof FlexiblePublisher)) {\n throw new IllegalArgumentException(String.format(\"Publisher should be of type: '%s'. Found type: '%s'\",\n FlexiblePublisher.class, flexiblePublisher.getClass()));\n }\n\n List<ConditionalPublisher> conditions = ((FlexiblePublisher) flexiblePublisher).getPublishers();\n for (ConditionalPublisher condition : conditions) {\n if (type.isInstance(condition.getPublisher())) {\n return type.cast(condition.getPublisher());\n }\n }\n\n return null;\n }", "public static final String vertexAsString(Vertex vertex, int depth, String withEdgesOfLabel)\n {\n StringBuilder sb = new StringBuilder();\n vertexAsString(vertex, depth, withEdgesOfLabel, sb, 0, new HashSet<>());\n return sb.toString();\n }", "private JSONArray datesToJson(Collection<Date> individualDates) {\n\n if (null != individualDates) {\n JSONArray result = new JSONArray();\n for (Date d : individualDates) {\n result.put(dateToJson(d));\n }\n return result;\n }\n return null;\n }", "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 ProviderContextBuilder setRateTypes(Collection<RateType> rateTypes) {\n Objects.requireNonNull(rateTypes);\n if (rateTypes.isEmpty()) {\n throw new IllegalArgumentException(\"At least one RateType is required.\");\n }\n Set<RateType> rtSet = new HashSet<>(rateTypes);\n set(ProviderContext.KEY_RATE_TYPES, rtSet);\n return this;\n }" ]
lookup a ClassDescriptor in the internal Hashtable @param strClassName a fully qualified class name as it is returned by Class.getName().
[ "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 addAllWithFilter(Map<String, String> toMap, Map<String, String> fromMap, IncludeExcludePatterns pattern) {\n for (Object o : fromMap.entrySet()) {\n Map.Entry entry = (Map.Entry) o;\n String key = (String) entry.getKey();\n if (PatternMatcher.pathConflicts(key, pattern)) {\n continue;\n }\n toMap.put(key, (String) entry.getValue());\n }\n }", "@SuppressWarnings({\"UnusedDeclaration\"})\n public void doIndex(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException {\n req.getView(this, chooseAction()).forward(req, resp);\n }", "public Profile[] getProfilesForServerName(String serverName) throws Exception {\n int profileId = -1;\n ArrayList<Profile> returnProfiles = new ArrayList<Profile>();\n\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.GENERIC_PROFILE_ID + \" FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.SERVER_REDIRECT_SRC_URL + \" = ? GROUP BY \" +\n Constants.GENERIC_PROFILE_ID\n );\n queryStatement.setString(1, serverName);\n results = queryStatement.executeQuery();\n\n while (results.next()) {\n profileId = results.getInt(Constants.GENERIC_PROFILE_ID);\n\n Profile profile = ProfileService.getInstance().findProfile(profileId);\n\n returnProfiles.add(profile);\n }\n } catch (SQLException e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n if (returnProfiles.size() == 0) {\n return null;\n }\n return returnProfiles.toArray(new Profile[0]);\n }", "private ImmutableList<Element> getNodeListForTagElement(Document dom,\n\t\t\tCrawlElement crawlElement,\n\t\t\tEventableConditionChecker eventableConditionChecker) {\n\n\t\tBuilder<Element> result = ImmutableList.builder();\n\n\t\tif (crawlElement.getTagName() == null) {\n\t\t\treturn result.build();\n\t\t}\n\n\t\tEventableCondition eventableCondition =\n\t\t\t\teventableConditionChecker.getEventableCondition(crawlElement.getId());\n\t\t// TODO Stefan; this part of the code should be re-factored, Hack-ed it this way to prevent\n\t\t// performance problems.\n\t\tImmutableList<String> expressions = getFullXpathForGivenXpath(dom, eventableCondition);\n\n\t\tNodeList nodeList = dom.getElementsByTagName(crawlElement.getTagName());\n\n\t\tfor (int k = 0; k < nodeList.getLength(); k++) {\n\n\t\t\tElement element = (Element) nodeList.item(k);\n\t\t\tboolean matchesXpath =\n\t\t\t\t\telementMatchesXpath(eventableConditionChecker, eventableCondition,\n\t\t\t\t\t\t\texpressions, element);\n\t\t\tLOG.debug(\"Element {} matches Xpath={}\", DomUtils.getElementString(element),\n\t\t\t\t\tmatchesXpath);\n\t\t\t/*\n\t\t\t * TODO Stefan This is a possible Thread-Interleaving problem, as / isChecked can return\n\t\t\t * false and when needed to add it can return true. / check if element is a candidate\n\t\t\t */\n\t\t\tString id = element.getNodeName() + \": \" + DomUtils.getAllElementAttributes(element);\n\t\t\tif (matchesXpath && !checkedElements.isChecked(id)\n\t\t\t\t\t&& !isExcluded(dom, element, eventableConditionChecker)) {\n\t\t\t\taddElement(element, result, crawlElement);\n\t\t\t} else {\n\t\t\t\tLOG.debug(\"Element {} was not added\", element);\n\t\t\t}\n\t\t}\n\t\treturn result.build();\n\t}", "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 }", "public FieldLocation getFieldLocation(FieldType type)\n {\n FieldLocation result = null;\n\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getFieldLocation();\n }\n return result;\n }", "public void delete() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "private SpellCheckResponse performSpellcheckQuery(CmsSpellcheckingRequest request) {\n\n if ((null == request) || !request.isInitialized()) {\n return null;\n }\n\n final String[] wordsToCheck = request.m_wordsToCheck;\n\n final ModifiableSolrParams params = new ModifiableSolrParams();\n params.set(\"spellcheck\", \"true\");\n params.set(\"spellcheck.dictionary\", request.m_dictionaryToUse);\n params.set(\"spellcheck.extendedResults\", \"true\");\n\n // Build one string from array of words and use it as query.\n final StringBuilder builder = new StringBuilder();\n for (int i = 0; i < wordsToCheck.length; i++) {\n builder.append(wordsToCheck[i] + \" \");\n }\n\n params.set(\"spellcheck.q\", builder.toString());\n\n final SolrQuery query = new SolrQuery();\n query.setRequestHandler(\"/spell\");\n query.add(params);\n\n try {\n QueryResponse qres = m_solrClient.query(query);\n return qres.getSpellCheckResponse();\n } catch (Exception e) {\n LOG.debug(\"Exception while performing spellcheck query...\", e);\n }\n\n return null;\n }", "public void addControllerType(GVRControllerType controllerType)\n {\n if (cursorControllerTypes == null)\n {\n cursorControllerTypes = new ArrayList<GVRControllerType>();\n }\n else if (cursorControllerTypes.contains(controllerType))\n {\n return;\n }\n cursorControllerTypes.add(controllerType);\n }" ]
Deletes a vertex from this list.
[ "public void delete(Vertex vtx) {\n if (vtx.prev == null) {\n head = vtx.next;\n } else {\n vtx.prev.next = vtx.next;\n }\n if (vtx.next == null) {\n tail = vtx.prev;\n } else {\n vtx.next.prev = vtx.prev;\n }\n }" ]
[ "protected boolean isNetworkSection(int networkPrefixLength, boolean withPrefixLength) {\n\t\tint segmentCount = getSegmentCount();\n\t\tif(segmentCount == 0) {\n\t\t\treturn true;\n\t\t}\n\t\tint bitsPerSegment = getBitsPerSegment();\n\t\tint prefixedSegmentIndex = getNetworkSegmentIndex(networkPrefixLength, getBytesPerSegment(), bitsPerSegment);\n\t\tif(prefixedSegmentIndex + 1 < segmentCount) {\n\t\t\treturn false; //not the right number of segments\n\t\t}\n\t\t//the segment count matches, now compare the prefixed segment\n\t\tint segPrefLength = getPrefixedSegmentPrefixLength(bitsPerSegment, networkPrefixLength, prefixedSegmentIndex);\n\t\treturn !getSegment(segmentCount - 1).isNetworkChangedByPrefix(segPrefLength, withPrefixLength);\n\t}", "public static <T> T mode(Collection<T> values) {\r\n Set<T> modes = modes(values);\r\n return modes.iterator().next();\r\n }", "public static Cluster dropZone(Cluster intermediateCluster, int dropZoneId) {\n // Filter out nodes that don't belong to the zone being dropped\n Set<Node> survivingNodes = new HashSet<Node>();\n for(int nodeId: intermediateCluster.getNodeIds()) {\n if(intermediateCluster.getNodeById(nodeId).getZoneId() != dropZoneId) {\n survivingNodes.add(intermediateCluster.getNodeById(nodeId));\n }\n }\n\n // Filter out dropZoneId from all zones\n Set<Zone> zones = new HashSet<Zone>();\n for(int zoneId: intermediateCluster.getZoneIds()) {\n if(zoneId == dropZoneId) {\n continue;\n }\n List<Integer> proximityList = intermediateCluster.getZoneById(zoneId)\n .getProximityList();\n proximityList.remove(new Integer(dropZoneId));\n zones.add(new Zone(zoneId, proximityList));\n }\n\n return new Cluster(intermediateCluster.getName(),\n Utils.asSortedList(survivingNodes),\n Utils.asSortedList(zones));\n }", "public static base_responses add(nitro_service client, snmpuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpuser addresources[] = new snmpuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new snmpuser();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].group = resources[i].group;\n\t\t\t\taddresources[i].authtype = resources[i].authtype;\n\t\t\t\taddresources[i].authpasswd = resources[i].authpasswd;\n\t\t\t\taddresources[i].privtype = resources[i].privtype;\n\t\t\t\taddresources[i].privpasswd = resources[i].privpasswd;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public void destroy() throws Exception {\n if (_clientId == null) {\n return;\n }\n\n // delete the clientId here\n String uri = BASE_PROFILE + uriEncode(_profileName) + \"/\" + BASE_CLIENTS + \"/\" + _clientId;\n try {\n doDelete(uri, null);\n } catch (Exception e) {\n // some sort of error\n throw new Exception(\"Could not delete a proxy client\");\n }\n }", "public static String createFolderPath(String path) {\n\n String[] pathParts = path.split(\"\\\\.\");\n String path2 = \"\";\n for (String part : pathParts) {\n if (path2.equals(\"\")) {\n path2 = part;\n } else {\n path2 = path2 + File.separator\n + changeFirstLetterToLowerCase(createClassName(part));\n }\n }\n\n return path2;\n }", "public ParallelTaskBuilder setReplaceVarMapToSingleTargetSingleVar(\n String variable, List<String> replaceList, String uniformTargetHost) {\n\n if (Strings.isNullOrEmpty(uniformTargetHost)) {\n logger.error(\"uniform target host is empty or null. skil setting.\");\n return this;\n }\n this.replacementVarMapNodeSpecific.clear();\n this.targetHosts.clear();\n int i = 0;\n for (String replace : replaceList) {\n if (replace == null){\n logger.error(\"null replacement.. skip\");\n continue;\n }\n String hostName = PcConstants.API_PREFIX + i;\n\n replacementVarMapNodeSpecific.put(\n hostName,\n new StrStrMap().addPair(variable, replace).addPair(\n PcConstants.UNIFORM_TARGET_HOST_VAR,\n uniformTargetHost));\n targetHosts.add(hostName);\n ++i;\n }\n this.requestReplacementType = RequestReplacementType.TARGET_HOST_SPECIFIC_VAR_REPLACEMENT;\n logger.info(\n \"Set requestReplacementType as {} for single target. Will disable the set target hosts.\"\n + \"Also Simulated \"\n + \"Now Already set targetHost list with size {}. \\nPLEASE NOT TO SET TARGET HOSTS AGAIN WITH THIS API.\",\n requestReplacementType.toString(), targetHosts.size());\n\n return this;\n }", "private int[] changeColor() {\n int[] changedPixels = new int[pixels.length];\n double frequenz = 2 * Math.PI / 1020;\n\n for (int i = 0; i < pixels.length; i++) {\n int argb = pixels[i];\n int a = (argb >> 24) & 0xff;\n int r = (argb >> 16) & 0xff;\n int g = (argb >> 8) & 0xff;\n int b = argb & 0xff;\n\n r = (int) (255 * Math.sin(frequenz * r));\n b = (int) (-255 * Math.cos(frequenz * b) + 255);\n\n changedPixels[i] = (a << 24) | (r << 16) | (g << 8) | b;\n }\n\n return changedPixels;\n }", "public static void dumpRow(Map<String, Object> row)\n {\n for (Entry<String, Object> entry : row.entrySet())\n {\n Object value = entry.getValue();\n System.out.println(entry.getKey() + \" = \" + value + \" ( \" + (value == null ? \"\" : value.getClass().getName()) + \")\");\n }\n }" ]
Helper to read an optional String value list. @param path The XML path of the element to read. @return The String list stored in the XML, or <code>null</code> if the value could not be read.
[ "protected List<String> parseOptionalStringValues(final String path) {\n\n final List<I_CmsXmlContentValue> values = m_xml.getValues(path, m_locale);\n if (values == null) {\n return null;\n } else {\n List<String> stringValues = new ArrayList<String>(values.size());\n for (I_CmsXmlContentValue value : values) {\n stringValues.add(value.getStringValue(null));\n }\n return stringValues;\n }\n }" ]
[ "public Map<DeckReference, TrackMetadata> getLoadedTracks() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, TrackMetadata>(hotCache));\n }", "private boolean isSatisfied() {\n if(pipelineData.getZonesRequired() != null) {\n return ((pipelineData.getSuccesses() >= required) && (pipelineData.getZoneResponses()\n .size() >= (pipelineData.getZonesRequired() + 1)));\n } else {\n return pipelineData.getSuccesses() >= required;\n }\n }", "public static DMatrixRMaj elements(DMatrixRMaj A , BMatrixRMaj marked , DMatrixRMaj output ) {\n if( A.numRows != marked.numRows || A.numCols != marked.numCols )\n throw new MatrixDimensionException(\"Input matrices must have the same shape\");\n if( output == null )\n output = new DMatrixRMaj(1,1);\n\n output.reshape(countTrue(marked),1);\n\n int N = A.getNumElements();\n\n int index = 0;\n for (int i = 0; i < N; i++) {\n if( marked.data[i] ) {\n output.data[index++] = A.data[i];\n }\n }\n\n return output;\n }", "@Override protected View inflate(LayoutInflater inflater, ViewGroup parent) {\n View inflatedView = inflater.inflate(R.layout.video_renderer, parent, false);\n /*\n * You don't have to use ButterKnife library to implement the mapping between your layout\n * and your widgets you can implement setUpView and hookListener methods declared in\n * Renderer<T> class.\n */\n ButterKnife.bind(this, inflatedView);\n return inflatedView;\n }", "public static void block(DMatrix1Row A , DMatrix1Row A_tran ,\n final int blockLength )\n {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int blockHeight = Math.min( blockLength , A.numRows - i);\n\n int indexSrc = i*A.numCols;\n int indexDst = i;\n\n for( int j = 0; j < A.numCols; j += blockLength ) {\n int blockWidth = Math.min( blockLength , A.numCols - j);\n\n// int indexSrc = i*A.numCols + j;\n// int indexDst = j*A_tran.numCols + i;\n\n int indexSrcEnd = indexSrc + blockWidth;\n// for( int l = 0; l < blockWidth; l++ , indexSrc++ ) {\n for( ; indexSrc < indexSrcEnd; indexSrc++ ) {\n int rowSrc = indexSrc;\n int rowDst = indexDst;\n int end = rowDst + blockHeight;\n// for( int k = 0; k < blockHeight; k++ , rowSrc += A.numCols ) {\n for( ; rowDst < end; rowSrc += A.numCols ) {\n // faster to write in sequence than to read in sequence\n A_tran.data[ rowDst++ ] = A.data[ rowSrc ];\n }\n indexDst += A_tran.numCols;\n }\n }\n }\n }", "public void addResourceAssignment(ResourceAssignment assignment)\n {\n if (getExistingResourceAssignment(assignment.getResource()) == null)\n {\n m_assignments.add(assignment);\n getParentFile().getResourceAssignments().add(assignment);\n\n Resource resource = assignment.getResource();\n if (resource != null)\n {\n resource.addResourceAssignment(assignment);\n }\n }\n }", "protected AbstractColumn buildSimpleColumn() {\n\t\tSimpleColumn column = new SimpleColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tcolumnProperty.getFieldProperties().putAll(fieldProperties);\n\t\tcolumn.setColumnProperty(columnProperty);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setFieldDescription(fieldDescription);\n\t\treturn column;\n\t}", "public Map<Integer, TableDefinition> tableDefinitions()\n {\n Map<Integer, TableDefinition> result = new HashMap<Integer, TableDefinition>();\n\n result.put(Integer.valueOf(2), new TableDefinition(\"PROJECT_SUMMARY\", columnDefinitions(PROJECT_SUMMARY_COLUMNS, projectSummaryColumnsOrder())));\n result.put(Integer.valueOf(7), new TableDefinition(\"BAR\", columnDefinitions(BAR_COLUMNS, barColumnsOrder())));\n result.put(Integer.valueOf(11), new TableDefinition(\"CALENDAR\", columnDefinitions(CALENDAR_COLUMNS, calendarColumnsOrder())));\n result.put(Integer.valueOf(12), new TableDefinition(\"EXCEPTIONN\", columnDefinitions(EXCEPTIONN_COLUMNS, exceptionColumnsOrder())));\n result.put(Integer.valueOf(14), new TableDefinition(\"EXCEPTION_ASSIGNMENT\", columnDefinitions(EXCEPTION_ASSIGNMENT_COLUMNS, exceptionAssignmentColumnsOrder())));\n result.put(Integer.valueOf(15), new TableDefinition(\"TIME_ENTRY\", columnDefinitions(TIME_ENTRY_COLUMNS, timeEntryColumnsOrder())));\n result.put(Integer.valueOf(17), new TableDefinition(\"WORK_PATTERN\", columnDefinitions(WORK_PATTERN_COLUMNS, workPatternColumnsOrder()))); \n result.put(Integer.valueOf(18), new TableDefinition(\"TASK_COMPLETED_SECTION\", columnDefinitions(TASK_COMPLETED_SECTION_COLUMNS, taskCompletedSectionColumnsOrder()))); \n result.put(Integer.valueOf(21), new TableDefinition(\"TASK\", columnDefinitions(TASK_COLUMNS, taskColumnsOrder())));\n result.put(Integer.valueOf(22), new TableDefinition(\"MILESTONE\", columnDefinitions(MILESTONE_COLUMNS, milestoneColumnsOrder())));\n result.put(Integer.valueOf(23), new TableDefinition(\"EXPANDED_TASK\", columnDefinitions(EXPANDED_TASK_COLUMNS, expandedTaskColumnsOrder())));\n result.put(Integer.valueOf(25), new TableDefinition(\"LINK\", columnDefinitions(LINK_COLUMNS, linkColumnsOrder())));\n result.put(Integer.valueOf(61), new TableDefinition(\"CONSUMABLE_RESOURCE\", columnDefinitions(CONSUMABLE_RESOURCE_COLUMNS, consumableResourceColumnsOrder())));\n result.put(Integer.valueOf(62), new TableDefinition(\"PERMANENT_RESOURCE\", columnDefinitions(PERMANENT_RESOURCE_COLUMNS, permanentResourceColumnsOrder())));\n result.put(Integer.valueOf(63), new TableDefinition(\"PERM_RESOURCE_SKILL\", columnDefinitions(PERMANENT_RESOURCE_SKILL_COLUMNS, permanentResourceSkillColumnsOrder())));\n result.put(Integer.valueOf(67), new TableDefinition(\"PERMANENT_SCHEDUL_ALLOCATION\", columnDefinitions(PERMANENT_SCHEDULE_ALLOCATION_COLUMNS, permanentScheduleAllocationColumnsOrder())));\n result.put(Integer.valueOf(190), new TableDefinition(\"WBS_ENTRY\", columnDefinitions(WBS_ENTRY_COLUMNS, wbsEntryColumnsOrder())));\n\n return result;\n }", "public String convertFromJavaString(String string, boolean useUnicode) {\n\t\tint firstEscapeSequence = string.indexOf('\\\\');\n\t\tif (firstEscapeSequence == -1) {\n\t\t\treturn string;\n\t\t}\n\t\tint length = string.length();\n\t\tStringBuilder result = new StringBuilder(length);\n\t\tappendRegion(string, 0, firstEscapeSequence, result);\n\t\treturn convertFromJavaString(string, useUnicode, firstEscapeSequence, result);\n\t}" ]
Determines total number of partition-stores moved across zones. @return number of cross zone partition-store moves
[ "public int getCrossZonePartitionStoreMoves() {\n int xzonePartitionStoreMoves = 0;\n for (RebalanceTaskInfo info : batchPlan) {\n Node donorNode = finalCluster.getNodeById(info.getDonorId());\n Node stealerNode = finalCluster.getNodeById(info.getStealerId());\n\n if(donorNode.getZoneId() != stealerNode.getZoneId()) {\n xzonePartitionStoreMoves += info.getPartitionStoreMoves();\n }\n }\n\n return xzonePartitionStoreMoves;\n }" ]
[ "private void addFilters(MpxjTreeNode parentNode, List<Filter> filters)\n {\n for (Filter field : filters)\n {\n final Filter f = field;\n MpxjTreeNode childNode = new MpxjTreeNode(field)\n {\n @Override public String toString()\n {\n return f.getName();\n }\n };\n parentNode.add(childNode);\n }\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}", "public static base_response Import(nitro_service client, application resource) throws Exception {\n\t\tapplication Importresource = new application();\n\t\tImportresource.apptemplatefilename = resource.apptemplatefilename;\n\t\tImportresource.appname = resource.appname;\n\t\tImportresource.deploymentfilename = resource.deploymentfilename;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}", "public ObjectReferenceDescriptor getObjectReferenceDescriptorByName(String name)\r\n {\r\n ObjectReferenceDescriptor ord = (ObjectReferenceDescriptor)\r\n getObjectReferenceDescriptorsNameMap().get(name);\r\n\r\n //\r\n // BRJ: if the ReferenceDescriptor is not found\r\n // look in the ClassDescriptor referenced by 'super' for it\r\n //\r\n if (ord == null)\r\n {\r\n ClassDescriptor superCld = getSuperClassDescriptor();\r\n if (superCld != null)\r\n {\r\n ord = superCld.getObjectReferenceDescriptorByName(name);\r\n }\r\n }\r\n return ord;\r\n }", "public static base_responses restore(nitro_service client, appfwprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwprofile restoreresources[] = new appfwprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\trestoreresources[i] = new appfwprofile();\n\t\t\t\trestoreresources[i].archivename = resources[i].archivename;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, restoreresources,\"restore\");\n\t\t}\n\t\treturn result;\n\t}", "private void deliverMasterChangedAnnouncement(final DeviceUpdate update) {\n for (final MasterListener listener : getMasterListeners()) {\n try {\n listener.masterChanged(update);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master changed announcement to listener\", t);\n }\n }\n }", "public ConfigOptionBuilder setCommandLineOptionWithoutArgument( CommandLineOption commandLineOption, Object value ) {\n co.setCommandLineOption( commandLineOption );\n co.setValue( value );\n return this;\n }", "public static String getAt(String text, IntRange range) {\n return getAt(text, (Range) range);\n }", "@Deprecated\n @SuppressWarnings(\"deprecation\")\n protected void registerAddOperation(final ManagementResourceRegistration registration, final OperationStepHandler handler, OperationEntry.Flag... flags) {\n if (handler instanceof DescriptionProvider) {\n registration.registerOperationHandler(getOperationDefinition(ModelDescriptionConstants.ADD,\n (DescriptionProvider) handler, OperationEntry.EntryType.PUBLIC,flags)\n , handler);\n\n } else {\n registration.registerOperationHandler(getOperationDefinition(ModelDescriptionConstants.ADD,\n new DefaultResourceAddDescriptionProvider(registration, descriptionResolver, orderedChild),\n OperationEntry.EntryType.PUBLIC,\n flags)\n , handler);\n }\n }" ]
adds a value to the list @param value the value
[ "public void add(T value) {\n Element<T> element = new Element<T>(bundle, value);\n element.previous = tail;\n if (tail != null) tail.next = element;\n tail = element;\n if (head == null) head = element;\n }" ]
[ "public AsciiTable setPaddingLeftRight(int padding){\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingLeftRight(padding);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public BoxFileUploadSessionPart uploadPart(InputStream stream, long offset, int partSize,\n long totalSizeOfFile) {\n\n URL uploadPartURL = this.sessionInfo.getSessionEndpoints().getUploadPartEndpoint();\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), uploadPartURL, HttpMethod.PUT);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM);\n\n //Read the partSize bytes from the stream\n byte[] bytes = new byte[partSize];\n try {\n stream.read(bytes);\n } catch (IOException ioe) {\n throw new BoxAPIException(\"Reading data from stream failed.\", ioe);\n }\n\n return this.uploadPart(bytes, offset, partSize, totalSizeOfFile);\n }", "protected synchronized void doClose()\r\n {\r\n try\r\n {\r\n LockManager lm = getImplementation().getLockManager();\r\n Enumeration en = objectEnvelopeTable.elements();\r\n while (en.hasMoreElements())\r\n {\r\n ObjectEnvelope oe = (ObjectEnvelope) en.nextElement();\r\n lm.releaseLock(this, oe.getIdentity(), oe.getObject());\r\n }\r\n\r\n //remove locks for objects which haven't been materialized yet\r\n for (Iterator it = unmaterializedLocks.iterator(); it.hasNext();)\r\n {\r\n lm.releaseLock(this, it.next());\r\n }\r\n\r\n // this tx is no longer interested in materialization callbacks\r\n unRegisterFromAllIndirectionHandlers();\r\n unRegisterFromAllCollectionProxies();\r\n }\r\n finally\r\n {\r\n /**\r\n * MBAIRD: Be nice and close the table to release all refs\r\n */\r\n if (log.isDebugEnabled())\r\n log.debug(\"Close Transaction and release current PB \" + broker + \" on tx \" + this);\r\n // remove current thread from LocalTxManager\r\n // to avoid problems for succeeding calls of the same thread\r\n implementation.getTxManager().deregisterTx(this);\r\n // now cleanup and prepare for reuse\r\n refresh();\r\n }\r\n }", "void close() {\n try {\n performTeardownExchange();\n } catch (IOException e) {\n logger.warn(\"Problem reporting our intention to close the dbserver connection\", e);\n }\n try {\n channel.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client output channel\", e);\n }\n try {\n os.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client output stream\", e);\n }\n try {\n is.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client input stream\", e);\n }\n try {\n socket.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client socket\", e);\n }\n }", "public Module getModule(final String name, final String version) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getModulePath(name, version));\n final ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"get module details\", name, version);\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(Module.class);\n }", "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 }", "private boolean activityIsMilestone(Activity activity)\n {\n String type = activity.getType();\n return type != null && type.indexOf(\"Milestone\") != -1;\n }", "public static boolean decomposeSafe(DecompositionInterface<ZMatrixRMaj> decomposition, ZMatrixRMaj a) {\n\n if( decomposition.inputModified() ) {\n a = a.copy();\n }\n return decomposition.decompose(a);\n }", "@RequestMapping(value = \"api/edit/repeatNumber\", method = RequestMethod.POST)\n public\n @ResponseBody\n String updateRepeatNumber(Model model, int newNum, int path_id,\n @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n logger.info(\"want to update repeat number of path_id={}, to newNum={}\", path_id, newNum);\n editService.updateRepeatNumber(newNum, path_id, clientUUID);\n return null;\n }" ]
Flushes all changes to disk.
[ "public void commit() {\n if (directory == null)\n return;\n\n try {\n if (reader != null)\n reader.close();\n\n // it turns out that IndexWriter.optimize actually slows\n // searches down, because it invalidates the cache. therefore\n // not calling it any more.\n // http://www.searchworkings.org/blog/-/blogs/uwe-says%3A-is-your-reader-atomic\n // iwriter.optimize();\n\n iwriter.commit();\n openSearchers();\n } catch (IOException e) {\n throw new DukeException(e);\n }\n }" ]
[ "protected void putResponse(JSONObject json,\n String param,\n Object value) {\n try {\n json.put(param,\n value);\n } catch (JSONException e) {\n logger.error(\"json write error\",\n e);\n }\n }", "public SqlStatement getPreparedDeleteStatement(Query query, ClassDescriptor cld)\r\n {\r\n return new SqlDeleteByQuery(m_platform, cld, query, logger);\r\n }", "void setDayOfMonth(String day) {\n\n final int i = CmsSerialDateUtil.toIntWithDefault(day, -1);\n if (m_model.getDayOfMonth() != i) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setDayOfMonth(i);\n onValueChange();\n }\n });\n }\n }", "private void refreshInstance(Object cachedInstance, Identity oid, ClassDescriptor cld)\n {\n // read in fresh copy from the db, but do not cache it\n Object freshInstance = getPlainDBObject(cld, oid);\n\n // update all primitive typed attributes\n FieldDescriptor[] fields = cld.getFieldDescriptions();\n FieldDescriptor fmd;\n PersistentField fld;\n for (int i = 0; i < fields.length; i++)\n {\n fmd = fields[i];\n fld = fmd.getPersistentField();\n fld.set(cachedInstance, fld.get(freshInstance));\n }\n }", "public static String getImageIdFromAgent(Launcher launcher, final String imageTag, final String host) throws IOException, InterruptedException {\n return launcher.getChannel().call(new MasterToSlaveCallable<String, IOException>() {\n public String call() throws IOException {\n return DockerUtils.getImageIdFromTag(imageTag, host);\n }\n });\n }", "public static MfClientHttpRequestFactory createFactoryWrapper(\n final MfClientHttpRequestFactory requestFactory,\n final UriMatchers matchers, final Map<String, List<String>> headers) {\n return new AbstractMfClientHttpRequestFactoryWrapper(requestFactory, matchers, false) {\n @Override\n protected ClientHttpRequest createRequest(\n final URI uri,\n final HttpMethod httpMethod,\n final MfClientHttpRequestFactory requestFactory) throws IOException {\n final ClientHttpRequest request = requestFactory.createRequest(uri, httpMethod);\n request.getHeaders().putAll(headers);\n return request;\n }\n };\n }", "public GroovyFieldDoc[] properties() {\n Collections.sort(properties);\n return properties.toArray(new GroovyFieldDoc[properties.size()]);\n }", "public static appfwpolicylabel_stats[] get(nitro_service service) throws Exception{\n\t\tappfwpolicylabel_stats obj = new appfwpolicylabel_stats();\n\t\tappfwpolicylabel_stats[] response = (appfwpolicylabel_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "@Api\n\tpublic void setNamedRoles(Map<String, List<NamedRoleInfo>> namedRoles) {\n\t\tthis.namedRoles = namedRoles;\n\t\tldapRoleMapping = new HashMap<String, Set<String>>();\n\t\tfor (String roleName : namedRoles.keySet()) {\n\t\t\tif (!ldapRoleMapping.containsKey(roleName)) {\n\t\t\t\tldapRoleMapping.put(roleName, new HashSet<String>());\n\t\t\t}\n\t\t\tfor (NamedRoleInfo role : namedRoles.get(roleName)) {\n\t\t\t\tldapRoleMapping.get(roleName).add(role.getName());\n\t\t\t}\n\t\t}\n\t}" ]
Throws an exception if the current thread is not a GL thread. @since 1.6.5
[ "public void assertGLThread() {\n if (Thread.currentThread().getId() != mGLThreadID) {\n RuntimeException e = new RuntimeException(\n \"Should not run GL functions from a non-GL thread!\");\n e.printStackTrace();\n throw e;\n }\n }" ]
[ "public static <T> void injectEEFields(Iterable<Set<ResourceInjection<?>>> resourceInjectionsHierarchy,\n T beanInstance, CreationalContext<T> ctx) {\n for (Set<ResourceInjection<?>> resourceInjections : resourceInjectionsHierarchy) {\n for (ResourceInjection<?> resourceInjection : resourceInjections) {\n resourceInjection.injectResourceReference(beanInstance, ctx);\n }\n }\n }", "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 static CoordinateReferenceSystem parseProjection(\n final String projection, final Boolean longitudeFirst) {\n try {\n if (longitudeFirst == null) {\n return CRS.decode(projection);\n } else {\n return CRS.decode(projection, longitudeFirst);\n }\n } catch (NoSuchAuthorityCodeException e) {\n throw new RuntimeException(projection + \" was not recognized as a crs code\", e);\n } catch (FactoryException e) {\n throw new RuntimeException(\"Error occurred while parsing: \" + projection, e);\n }\n }", "public Where<T, ID> or() {\n\t\tManyClause clause = new ManyClause(pop(\"OR\"), ManyClause.OR_OPERATION);\n\t\tpush(clause);\n\t\taddNeedsFuture(clause);\n\t\treturn this;\n\t}", "public static String getParameter(DbConn cnx, String key, String defaultValue)\n {\n try\n {\n return cnx.runSelectSingle(\"globalprm_select_by_key\", 3, String.class, key);\n }\n catch (NoResultException e)\n {\n return defaultValue;\n }\n }", "public boolean isWorkingDay(Day day)\n {\n DayType value = getWorkingDay(day);\n boolean result;\n\n if (value == DayType.DEFAULT)\n {\n ProjectCalendar cal = getParent();\n if (cal != null)\n {\n result = cal.isWorkingDay(day);\n }\n else\n {\n result = (day != Day.SATURDAY && day != Day.SUNDAY);\n }\n }\n else\n {\n result = (value == DayType.WORKING);\n }\n\n return (result);\n }", "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}", "private static Iterable<BoxUser.Info> getUsersInfoForType(final BoxAPIConnection api,\n final String filterTerm, final String userType, final String externalAppUserId, final String... fields) {\n return new Iterable<BoxUser.Info>() {\n public Iterator<BoxUser.Info> iterator() {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (filterTerm != null) {\n builder.appendParam(\"filter_term\", filterTerm);\n }\n if (userType != null) {\n builder.appendParam(\"user_type\", userType);\n }\n if (externalAppUserId != null) {\n builder.appendParam(\"external_app_user_id\", externalAppUserId);\n }\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n URL url = USERS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n return new BoxUserIterator(api, url);\n }\n };\n }", "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 }" ]
Add a '&gt;' clause so the column must be greater-than the value.
[ "public Where<T, ID> gt(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.GREATER_THAN_OPERATION));\n\t\treturn this;\n\t}" ]
[ "public static int read(ReadableByteChannel channel, ByteBuffer buffer) throws IOException {\n int count = channel.read(buffer);\n if (count == -1) throw new EOFException(\"Received -1 when reading from channel, socket has likely been closed.\");\n return count;\n }", "private void printSuggestion( String arg, List<ConfigOption> co ) {\n List<ConfigOption> sortedList = new ArrayList<ConfigOption>( co );\n Collections.sort( sortedList, new ConfigOptionLevenshteinDistance( arg ) );\n System.err.println( \"Parse error for argument \\\"\" + arg + \"\\\", did you mean \" + sortedList.get( 0 ).getCommandLineOption()\n .showFlagInfo() + \"? Ignoring for now.\" );\n\n }", "public Response remove(String id, String rev) {\r\n assertNotEmpty(id, \"id\");\r\n assertNotEmpty(id, \"rev\");\r\n return db.remove(ensureDesignPrefix(id), rev);\r\n\r\n }", "public static <T> void addAll(Collection<T> collection, Iterable<? extends T> items) {\r\n for (T item : items) {\r\n collection.add(item);\r\n }\r\n }", "public ItemRequest<ProjectMembership> findById(String projectMembership) {\n \n String path = String.format(\"/project_memberships/%s\", projectMembership);\n return new ItemRequest<ProjectMembership>(this, ProjectMembership.class, path, \"GET\");\n }", "public Metadata createMetadata(String templateName, String scope, Metadata metadata) {\n URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, templateName);\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"POST\");\n request.addHeader(\"Content-Type\", \"application/json\");\n request.setBody(metadata.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new Metadata(JsonObject.readFrom(response.getJSON()));\n }", "public static <GIVEN, WHEN, THEN> Scenario<GIVEN, WHEN, THEN> create( Class<GIVEN> givenClass, Class<WHEN> whenClass,\n Class<THEN> thenClass ) {\n return new Scenario<GIVEN, WHEN, THEN>( givenClass, whenClass, thenClass );\n }", "public static base_responses add(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 addresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new route6();\n\t\t\t\taddresources[i].network = resources[i].network;\n\t\t\t\taddresources[i].gateway = resources[i].gateway;\n\t\t\t\taddresources[i].vlan = resources[i].vlan;\n\t\t\t\taddresources[i].weight = resources[i].weight;\n\t\t\t\taddresources[i].distance = resources[i].distance;\n\t\t\t\taddresources[i].cost = resources[i].cost;\n\t\t\t\taddresources[i].advertise = resources[i].advertise;\n\t\t\t\taddresources[i].msr = resources[i].msr;\n\t\t\t\taddresources[i].monitor = resources[i].monitor;\n\t\t\t\taddresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public void add(Map<String, Object> map) throws SQLException {\n if (withinDataSetBatch) {\n if (batchData.size() == 0) {\n batchKeys = map.keySet();\n } else {\n if (!map.keySet().equals(batchKeys)) {\n throw new IllegalArgumentException(\"Inconsistent keys found for batch add!\");\n }\n }\n batchData.add(map);\n return;\n }\n int answer = executeUpdate(buildListQuery(map), new ArrayList<Object>(map.values()));\n if (answer != 1) {\n LOG.warning(\"Should have updated 1 row not \" + answer + \" when trying to add: \" + map);\n }\n }" ]
Sets the left padding for all cells in the row. @param paddingLeft new padding, ignored if smaller than 0 @return this to allow chaining
[ "public AT_Row setPaddingLeft(int paddingLeft) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingLeft(paddingLeft);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}" ]
[ "public StreamReader getTableData(String name) throws IOException\n {\n InputStream stream = new ByteArrayInputStream(m_tableData.get(name));\n if (m_majorVersion > 5)\n { \n byte[] header = new byte[24];\n stream.read(header);\n SynchroLogger.log(\"TABLE HEADER\", header);\n }\n return new StreamReader(m_majorVersion, stream);\n }", "public float getSphereBound(float[] sphere)\n {\n if ((sphere == null) || (sphere.length != 4) ||\n ((NativeVertexBuffer.getBoundingVolume(getNative(), sphere)) < 0))\n {\n throw new IllegalArgumentException(\"Cannot copy sphere bound into array provided\");\n }\n return sphere[0];\n }", "public void addGroupBy(String[] fieldNames)\r\n {\r\n for (int i = 0; i < fieldNames.length; i++)\r\n {\r\n addGroupBy(fieldNames[i]);\r\n }\r\n }", "public ItemRequest<Project> createInWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/projects\", workspace);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }", "public ItemRequest<Task> addTag(String task) {\n \n String path = String.format(\"/tasks/%s/addTag\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "public static base_response kill(nitro_service client, systemsession resource) throws Exception {\n\t\tsystemsession killresource = new systemsession();\n\t\tkillresource.sid = resource.sid;\n\t\tkillresource.all = resource.all;\n\t\treturn killresource.perform_operation(client,\"kill\");\n\t}", "protected void store(Object obj, Identity oid, ClassDescriptor cld, boolean insert)\n {\n store(obj, oid, cld, insert, false);\n }", "public ParallelTaskBuilder prepareSsh() {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.SSH);\n return cb;\n }", "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 }" ]
Submits the configured template to Transloadit. @return {@link Response} @throws RequestException if request to transloadit server fails. @throws LocalOperationException if something goes wrong while running non-http operations.
[ "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 }" ]
[ "public AsciiTable setPaddingTopChar(Character paddingTopChar) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingTopChar(paddingTopChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public void updateInfo(BoxTermsOfServiceUserStatus.Info info) {\n URL url = TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(info.getPendingChanges());\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n info.update(responseJSON);\n }", "private void deliverDeviceUpdate(final DeviceUpdate update) {\n for (DeviceUpdateListener listener : getUpdateListeners()) {\n try {\n listener.received(update);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering device update to listener\", t);\n }\n }\n }", "public static spilloverpolicy_stats[] get(nitro_service service) throws Exception{\n\t\tspilloverpolicy_stats obj = new spilloverpolicy_stats();\n\t\tspilloverpolicy_stats[] response = (spilloverpolicy_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public final void reset()\n {\n for (int i = 0; i < combinationIndices.length; i++)\n {\n combinationIndices[i] = i;\n }\n remainingCombinations = totalCombinations;\n }", "private static Data loadLeapSeconds() {\n Data bestData = null;\n URL url = null;\n try {\n // this is the new location of the file, working on Java 8, Java 9 class path and Java 9 module path\n Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources(\"META-INF/\" + LEAP_SECONDS_TXT);\n while (en.hasMoreElements()) {\n url = en.nextElement();\n Data candidate = loadLeapSeconds(url);\n if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {\n bestData = candidate;\n }\n }\n // this location does not work on Java 9 module path because the resource is encapsulated\n en = Thread.currentThread().getContextClassLoader().getResources(LEAP_SECONDS_TXT);\n while (en.hasMoreElements()) {\n url = en.nextElement();\n Data candidate = loadLeapSeconds(url);\n if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {\n bestData = candidate;\n }\n }\n // this location is the canonical one, and class-based loading works on Java 9 module path\n url = SystemUtcRules.class.getResource(\"/\" + LEAP_SECONDS_TXT);\n if (url != null) {\n Data candidate = loadLeapSeconds(url);\n if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {\n bestData = candidate;\n }\n }\n } catch (Exception ex) {\n throw new RuntimeException(\"Unable to load time-zone rule data: \" + url, ex);\n }\n if (bestData == null) {\n // no data on classpath, but we allow manual registration of leap seconds\n // setup basic known data - MJD 1972-01-01 is 41317L, where offset was 10\n bestData = new Data(new long[] {41317L}, new int[] {10}, new long[] {tai(41317L, 10)});\n }\n return bestData;\n }", "public static List<String> createBacktrace(final Throwable t) {\n final List<String> bTrace = new LinkedList<String>();\n for (final StackTraceElement ste : t.getStackTrace()) {\n bTrace.add(BT_PREFIX + ste.toString());\n }\n if (t.getCause() != null) {\n addCauseToBacktrace(t.getCause(), bTrace);\n }\n return bTrace;\n }", "public void start() {\n instanceLock.writeLock().lock();\n try {\n for (final Map.Entry<MongoNamespace, NamespaceChangeStreamListener> streamerEntry :\n nsStreamers.entrySet()) {\n streamerEntry.getValue().start();\n }\n } finally {\n instanceLock.writeLock().unlock();\n }\n }", "public static TimeZone getStockTimeZone(String symbol) {\n // First check if it's a known stock index\n if(INDEX_TIMEZONES.containsKey(symbol)) {\n return INDEX_TIMEZONES.get(symbol);\n }\n \n if(!symbol.contains(\".\")) {\n return ExchangeTimeZone.get(\"\");\n }\n String[] split = symbol.split(\"\\\\.\");\n return ExchangeTimeZone.get(split[split.length - 1]);\n }" ]
Remove the corresponding object from session AND application cache.
[ "public void remove(Identity oid)\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"Remove object \" + oid);\r\n sessionCache.remove(oid);\r\n getApplicationCache().remove(oid);\r\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 void addProcedureArgument(ProcedureArgumentDef argDef)\r\n {\r\n argDef.setOwner(this);\r\n _procedureArguments.put(argDef.getName(), argDef);\r\n }", "public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize)\n throws InterruptedException, IOException {\n URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL());\n return new LargeFileUpload().\n upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize);\n }", "private void gobble(Iterator iter)\n {\n if (eatTheRest)\n {\n while (iter.hasNext())\n {\n tokens.add(iter.next());\n }\n }\n }", "private void logTimeTakenByPhase(GraphContext graphContext, Class<? extends RulePhase> phase, int timeTaken)\n {\n if (!timeTakenByPhase.containsKey(phase))\n {\n RulePhaseExecutionStatisticsModel model = new GraphService<>(graphContext,\n RulePhaseExecutionStatisticsModel.class).create();\n model.setRulePhase(phase.toString());\n model.setTimeTaken(timeTaken);\n model.setOrderExecuted(timeTakenByPhase.size());\n timeTakenByPhase.put(phase, model.getElement().id());\n }\n else\n {\n GraphService<RulePhaseExecutionStatisticsModel> service = new GraphService<>(graphContext,\n RulePhaseExecutionStatisticsModel.class);\n RulePhaseExecutionStatisticsModel model = service.getById(timeTakenByPhase.get(phase));\n int prevTimeTaken = model.getTimeTaken();\n model.setTimeTaken(prevTimeTaken + timeTaken);\n }\n }", "public String getScopes() {\n final StringBuilder sb = new StringBuilder();\n for (final Scope scope : Scope.values()) {\n sb.append(scope);\n sb.append(\", \");\n }\n final String scopes = sb.toString().trim();\n return scopes.substring(0, scopes.length() - 1);\n }", "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}", "protected void markStatementsForInsertion(\n\t\t\tStatementDocument currentDocument, List<Statement> addStatements) {\n\t\tfor (Statement statement : addStatements) {\n\t\t\taddStatement(statement, true);\n\t\t}\n\n\t\tfor (StatementGroup sg : currentDocument.getStatementGroups()) {\n\t\t\tif (this.toKeep.containsKey(sg.getProperty())) {\n\t\t\t\tfor (Statement statement : sg) {\n\t\t\t\t\tif (!this.toDelete.contains(statement.getStatementId())) {\n\t\t\t\t\t\taddStatement(statement, false);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public void uploadFields(\n final Set<String> fields,\n final Function<Map<String, String>, Void> filenameCallback,\n final I_CmsErrorCallback errorCallback) {\n\n disableAllFileFieldsExcept(fields);\n final String id = CmsJsUtils.generateRandomId();\n updateFormAction(id);\n // Using an array here because we can only store the handler registration after it has been created , but\n final HandlerRegistration[] registration = {null};\n registration[0] = addSubmitCompleteHandler(new SubmitCompleteHandler() {\n\n @SuppressWarnings(\"synthetic-access\")\n public void onSubmitComplete(SubmitCompleteEvent event) {\n\n enableAllFileFields();\n registration[0].removeHandler();\n CmsUUID sessionId = m_formSession.internalGetSessionId();\n RequestBuilder requestBuilder = CmsXmlContentUgcApi.SERVICE.uploadFiles(\n sessionId,\n fields,\n id,\n new AsyncCallback<Map<String, String>>() {\n\n public void onFailure(Throwable caught) {\n\n m_formSession.getContentFormApi().handleError(caught, errorCallback);\n\n }\n\n public void onSuccess(Map<String, String> fileNames) {\n\n filenameCallback.apply(fileNames);\n\n }\n });\n m_formSession.getContentFormApi().getRpcHelper().executeRpc(requestBuilder);\n m_formSession.getContentFormApi().getRequestCounter().decrement();\n }\n });\n m_formSession.getContentFormApi().getRequestCounter().increment();\n submit();\n }" ]
Parses command line arguments. @param args Array of arguments, like the ones provided by {@code void main(String[] args)} @param objs One or more objects with annotated public fields. @return A {@code List} containing all unparsed arguments (i.e. arguments that are no switches) @throws IOException if a parsing error occurred. @see CmdArgument
[ "public static List<String> parse(final String[] args, final Object... objs) throws IOException\n {\n final List<String> ret = Colls.list();\n\n final List<Arg> allArgs = Colls.list();\n final HashMap<String, Arg> shortArgs = new HashMap<String, Arg>();\n final HashMap<String, Arg> longArgs = new HashMap<String, Arg>();\n\n parseArgs(objs, allArgs, shortArgs, longArgs);\n\n for (int i = 0; i < args.length; i++)\n {\n final String s = args[i];\n\n final Arg a;\n\n if (s.startsWith(\"--\"))\n {\n a = longArgs.get(s.substring(2));\n if (a == null)\n {\n throw new IOException(\"Unknown switch: \" + s);\n }\n }\n else if (s.startsWith(\"-\"))\n {\n a = shortArgs.get(s.substring(1));\n if (a == null)\n {\n throw new IOException(\"Unknown switch: \" + s);\n }\n }\n else\n {\n a = null;\n ret.add(s);\n }\n\n if (a != null)\n {\n if (a.isSwitch)\n {\n a.setField(\"true\");\n }\n else\n {\n if (i + 1 >= args.length)\n {\n System.out.println(\"Missing parameter for: \" + s);\n }\n if (a.isCatchAll())\n {\n final List<String> ca = Colls.list();\n for (++i; i < args.length; ++i)\n {\n ca.add(args[i]);\n }\n a.setCatchAll(ca);\n }\n else\n {\n ++i;\n a.setField(args[i]);\n }\n }\n a.setPresent();\n }\n }\n\n for (final Arg a : allArgs)\n {\n if (!a.isOk())\n {\n throw new IOException(\"Missing mandatory argument: \" + a);\n }\n }\n\n return ret;\n }" ]
[ "public DockerContainerObjectBuilder<T> withContainerObjectClass(Class<T> containerObjectClass) {\n if (containerObjectClass == null) {\n throw new IllegalArgumentException(\"container object class cannot be null\");\n }\n this.containerObjectClass = containerObjectClass;\n\n //First we check if this ContainerObject is defining a @CubeDockerFile in static method\n final List<Method> methodsWithCubeDockerFile =\n ReflectionUtil.getMethodsWithAnnotation(containerObjectClass, CubeDockerFile.class);\n\n if (methodsWithCubeDockerFile.size() > 1) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Methods where annotation was found are: %s\",\n CubeDockerFile.class.getSimpleName(), methodsWithCubeDockerFile));\n }\n\n classHasMethodWithCubeDockerFile = !methodsWithCubeDockerFile.isEmpty();\n classDefinesCubeDockerFile = containerObjectClass.isAnnotationPresent(CubeDockerFile.class);\n classDefinesImage = containerObjectClass.isAnnotationPresent(Image.class);\n\n if (classHasMethodWithCubeDockerFile) {\n methodWithCubeDockerFile = methodsWithCubeDockerFile.get(0);\n boolean isMethodStatic = Modifier.isStatic(methodWithCubeDockerFile.getModifiers());\n boolean methodHasNoArguments = methodWithCubeDockerFile.getParameterCount() == 0;\n boolean methodReturnsAnArchive = Archive.class.isAssignableFrom(methodWithCubeDockerFile.getReturnType());\n if (!isMethodStatic || !methodHasNoArguments || !methodReturnsAnArchive) {\n throw new IllegalArgumentException(\n String.format(\"Method %s annotated with %s is expected to be static, no args and return %s.\",\n methodWithCubeDockerFile, CubeDockerFile.class.getSimpleName(), Archive.class.getSimpleName()));\n }\n }\n\n // User has defined @CubeDockerfile on the class and a method\n if (classHasMethodWithCubeDockerFile && classDefinesCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Both class and method %s has the annotation.\",\n CubeDockerFile.class.getSimpleName(), methodWithCubeDockerFile));\n }\n\n // User has defined @CubeDockerfile and @Image\n if ((classHasMethodWithCubeDockerFile || classDefinesCubeDockerFile) && classDefinesImage) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s has defined %s annotation and %s annotation together.\",\n containerObjectClass.getSimpleName(), Image.class.getSimpleName(),\n CubeDockerFile.class.getSimpleName()));\n }\n\n // User has not defined either @CubeDockerfile or @Image\n if (!classDefinesCubeDockerFile && !classDefinesImage && !classHasMethodWithCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s is not annotated with either %s or %s annotations.\",\n containerObjectClass.getName(), CubeDockerFile.class.getSimpleName(), Image.class.getSimpleName()));\n }\n\n return this;\n }", "public void addRequiredBundles(Set<String> bundles) {\n\t\t// TODO manage transitive dependencies\n\t\t// don't require self\n\t\tSet<String> bundlesToMerge;\n\t\tString bundleName = (String) getMainAttributes().get(BUNDLE_SYMBOLIC_NAME);\n\t\tif (bundleName != null) {\n\t\t\tint idx = bundleName.indexOf(';');\n\t\t\tif (idx >= 0) {\n\t\t\t\tbundleName = bundleName.substring(0, idx);\n\t\t\t}\n\t\t}\n\t\tif (bundleName != null && bundles.contains(bundleName)\n\t\t\t\t|| projectName != null && bundles.contains(projectName)) {\n\t\t\tbundlesToMerge = new LinkedHashSet<String>(bundles);\n\t\t\tbundlesToMerge.remove(bundleName);\n\t\t\tbundlesToMerge.remove(projectName);\n\t\t} else {\n\t\t\tbundlesToMerge = bundles;\n\t\t}\n\t\tString s = (String) getMainAttributes().get(REQUIRE_BUNDLE);\n\t\tWrapper<Boolean> modified = Wrapper.wrap(this.modified);\n\t\tString result = mergeIntoCommaSeparatedList(s, bundlesToMerge, modified, lineDelimiter);\n\t\tthis.modified = modified.get();\n\t\tgetMainAttributes().put(REQUIRE_BUNDLE, result);\n\t}", "public double getCouponPayment(int periodIndex, AnalyticModel model) {\n\n\t\tForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName);\n\t\tif(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {\n\t\t\tthrow new IllegalArgumentException(\"No forward curve with name '\" + forwardCurveName + \"' was found in the model:\\n\" + model.toString());\n\t\t}\n\n\t\tdouble periodLength\t= schedule.getPeriodLength(periodIndex);\n\t\tdouble couponPayment=fixedCoupon ;\n\t\tif(forwardCurve != null ) {\n\t\t\tcouponPayment = floatingSpread+forwardCurve.getForward(model, schedule.getFixing(periodIndex));\n\t\t}\n\t\treturn couponPayment*periodLength;\n\t}", "public JsonTypeDefinition projectionType(String... properties) {\n if(this.getType() instanceof Map<?, ?>) {\n Map<?, ?> type = (Map<?, ?>) getType();\n Arrays.sort(properties);\n Map<String, Object> newType = new LinkedHashMap<String, Object>();\n for(String prop: properties)\n newType.put(prop, type.get(prop));\n return new JsonTypeDefinition(newType);\n } else {\n throw new IllegalArgumentException(\"Cannot take the projection of a type that is not a Map.\");\n }\n }", "public static Comment createComment(final String entityId,\n\t\t\t\t\t\t\t\t\t\tfinal String entityType,\n\t\t\t\t\t\t\t\t\t\tfinal String action,\n\t\t\t\t\t\t\t\t\t\tfinal String commentedText,\n\t\t\t\t\t\t\t\t\t\tfinal String user,\n\t\t\t\t\t\t\t\t\t\tfinal Date date) {\n\n\t\tfinal Comment comment = new Comment();\n\t\tcomment.setEntityId(entityId);\n\t\tcomment.setEntityType(entityType);\n\t\tcomment.setAction(action);\n\t\tcomment.setCommentText(commentedText);\n\t\tcomment.setCommentedBy(user);\n\t\tcomment.setCreatedDateTime(date);\n\t\treturn comment;\n\t}", "public static wisite_farmname_binding[] get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_farmname_binding obj = new wisite_farmname_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_farmname_binding response[] = (wisite_farmname_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "protected int _countPeriods(String str)\n {\n int commas = 0;\n for (int i = 0, end = str.length(); i < end; ++i) {\n int ch = str.charAt(i);\n if (ch < '0' || ch > '9') {\n if (ch == '.') {\n ++commas;\n } else {\n return -1;\n }\n }\n }\n return commas;\n }", "public void addRow(String primaryKeyColumnName, Map<String, Object> map)\n {\n Integer rowNumber = Integer.valueOf(m_rowNumber++);\n map.put(\"ROW_NUMBER\", rowNumber);\n Object primaryKey = null;\n if (primaryKeyColumnName != null)\n {\n primaryKey = map.get(primaryKeyColumnName);\n }\n\n if (primaryKey == null)\n {\n primaryKey = rowNumber;\n }\n\n MapRow newRow = new MapRow(map);\n MapRow oldRow = m_rows.get(primaryKey);\n if (oldRow == null)\n {\n m_rows.put(primaryKey, newRow);\n }\n else\n {\n int oldVersion = oldRow.getInteger(\"ROW_VERSION\").intValue();\n int newVersion = newRow.getInteger(\"ROW_VERSION\").intValue();\n if (newVersion > oldVersion)\n {\n m_rows.put(primaryKey, newRow);\n }\n }\n }", "public static String getHeaders(HttpServletRequest request) {\n String headerString = \"\";\n Enumeration<String> headerNames = request.getHeaderNames();\n\n while (headerNames.hasMoreElements()) {\n String name = headerNames.nextElement();\n if (name.equals(Constants.ODO_PROXY_HEADER)) {\n // skip.. don't want to log this\n continue;\n }\n\n if (headerString.length() != 0) {\n headerString += \"\\n\";\n }\n\n headerString += name + \": \" + request.getHeader(name);\n }\n\n return headerString;\n }" ]
Method handle a change on the cluster members set @param event
[ "@ViewChanged\n\tpublic synchronized void onViewChangeEvent(ViewChangedEvent event) {\n\t\t\n\t\tif (logger.isDebugEnabled()) {\n\t\t\tlogger.debug(\"onViewChangeEvent : pre[\" + event.isPre() + \"] : event local address[\" + event.getCache().getLocalAddress() + \"]\");\n\t\t}\n\t\t\n\t\tfinal List<Address> oldView = currentView;\n\t\tcurrentView = new ArrayList<Address>(event.getNewView().getMembers());\n\t\tfinal Address localAddress = getLocalAddress();\n\t\t\n\t\t//just a precaution, it can be null!\n\t\tif (oldView != null) {\n\t\t\tfinal Cache jbossCache = mobicentsCache.getJBossCache();\n\t\t\tfinal Configuration config = jbossCache.getConfiguration();\t\t\n\n\t\t\tfinal boolean isBuddyReplicationEnabled = config.getBuddyReplicationConfig() != null && config.getBuddyReplicationConfig().isEnabled();\n\t\t\t// recover stuff from lost members\n\t\t\tRunnable runnable = new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tfor (Address oldMember : oldView) {\n\t\t\t\t\t\tif (!currentView.contains(oldMember)) {\n\t\t\t\t\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\t\t\t\t\tlogger.debug(\"onViewChangeEvent : processing lost member \" + oldMember);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfor (FailOverListener localListener : failOverListeners) {\n\t\t\t\t\t\t\t\tClientLocalListenerElector localListenerElector = localListener.getElector();\n\t\t\t\t\t\t\t\tif (localListenerElector != null && !isBuddyReplicationEnabled) {\n\t\t\t\t\t\t\t\t\t// going to use the local listener elector instead, which gives results based on data\n\t\t\t\t\t\t\t\t\tperformTakeOver(localListener,oldMember,localAddress, true, isBuddyReplicationEnabled);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tList<Address> electionView = getElectionView(oldMember);\n\t\t\t\t\t\t\t\t\tif(electionView!=null && elector.elect(electionView).equals(localAddress))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tperformTakeOver(localListener, oldMember, localAddress, false, isBuddyReplicationEnabled);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tcleanAfterTakeOver(localListener, oldMember);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tThread t = new Thread(runnable);\n\t\t\tt.start();\n\t\t}\n\t\t\n\t}" ]
[ "public static void main(String[] args) throws Exception {\r\n StringUtils.printErrInvocationString(\"CMMClassifier\", args);\r\n\r\n Properties props = StringUtils.argsToProperties(args);\r\n CMMClassifier cmm = new CMMClassifier<CoreLabel>(props);\r\n String testFile = cmm.flags.testFile;\r\n String textFile = cmm.flags.textFile;\r\n String loadPath = cmm.flags.loadClassifier;\r\n String serializeTo = cmm.flags.serializeTo;\r\n\r\n // cmm.crossValidateTrainAndTest(trainFile);\r\n if (loadPath != null) {\r\n cmm.loadClassifierNoExceptions(loadPath, props);\r\n } else if (cmm.flags.loadJarClassifier != null) {\r\n cmm.loadJarClassifier(cmm.flags.loadJarClassifier, props);\r\n } else if (cmm.flags.trainFile != null) {\r\n if (cmm.flags.biasedTrainFile != null) {\r\n cmm.trainSemiSup();\r\n } else {\r\n cmm.train();\r\n }\r\n } else {\r\n cmm.loadDefaultClassifier();\r\n }\r\n\r\n if (serializeTo != null) {\r\n cmm.serializeClassifier(serializeTo);\r\n }\r\n\r\n if (testFile != null) {\r\n cmm.classifyAndWriteAnswers(testFile, cmm.makeReaderAndWriter());\r\n } else if (cmm.flags.testFiles != null) {\r\n cmm.classifyAndWriteAnswers(cmm.flags.baseTestDir, cmm.flags.testFiles,\r\n cmm.makeReaderAndWriter());\r\n }\r\n\r\n if (textFile != null) {\r\n DocumentReaderAndWriter readerAndWriter =\r\n new PlainTextDocumentReaderAndWriter();\r\n cmm.classifyAndWriteAnswers(textFile, readerAndWriter);\r\n }\r\n }", "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 }", "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 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 }", "@SuppressWarnings(\"unused\")\n public static void changeCredentials(String accountID, String token) {\n changeCredentials(accountID, token, null);\n }", "public Try<R,Throwable> execute(T input){\n\t\treturn Try.withCatch( ()->transactionTemplate.execute(status-> transaction.apply(input)));\n\t\t \n\t}", "public static boolean isPackageOrClassName(String s) {\n if (S.blank(s)) {\n return false;\n }\n S.List parts = S.fastSplit(s, \".\");\n if (parts.size() < 2) {\n return false;\n }\n for (String part: parts) {\n if (!Character.isJavaIdentifierStart(part.charAt(0))) {\n return false;\n }\n for (int i = 1, len = part.length(); i < len; ++i) {\n if (!Character.isJavaIdentifierPart(part.charAt(i))) {\n return false;\n }\n }\n }\n return true;\n }", "public static byte[] removeContentFromExplodedAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws OperationFailedException, ExplodedContentException {\n final Resource deploymentResource = context.readResource(PathAddress.EMPTY_ADDRESS);\n ModelNode contentItemNode = getContentItem(deploymentResource);\n final byte[] oldHash = CONTENT_HASH.resolveModelAttribute(context, contentItemNode).asBytes();\n final List<String> paths = REMOVED_PATHS.unwrap(context, operation);\n final byte[] hash = contentRepository.removeContentFromExploded(oldHash, paths);\n\n // Clear the contents and update with the hash\n final ModelNode slave = operation.clone();\n slave.get(CONTENT).setEmptyList().add().get(HASH).set(hash);\n slave.get(CONTENT).add().get(ARCHIVE).set(false);\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 static long count(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_crldistribution_binding obj = new sslcertkey_crldistribution_binding();\n\t\tobj.set_certkey(certkey);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tsslcertkey_crldistribution_binding response[] = (sslcertkey_crldistribution_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}" ]
Publish finish events for each of the specified query labels <pre> {@code LabelledEvents.start("get", 1l, bus, "typeA", "custom"); try { return "ok"; } finally { RequestEvents.finish("get", 1l, bus, "typeA", "custom"); } } </pre> @param query Completed query @param correlationId Identifier @param bus EventBus to post events to @param labels Query types to post to event bus
[ "public static <T> void finish(T query, long correlationId, EventBus bus, String... labels) {\n for (String type : labels) {\n RemoveLabelledQuery<T> next = finish(query, correlationId, type);\n bus.post(next);\n }\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 Class<? extends com.vividsolutions.jts.geom.Geometry> toInternal(LayerType layerType) {\n\t\tswitch (layerType) {\n\t\t\tcase GEOMETRY:\n\t\t\t\treturn com.vividsolutions.jts.geom.Geometry.class;\n\t\t\tcase LINESTRING:\n\t\t\t\treturn LineString.class;\n\t\t\tcase MULTILINESTRING:\n\t\t\t\treturn MultiLineString.class;\n\t\t\tcase POINT:\n\t\t\t\treturn Point.class;\n\t\t\tcase MULTIPOINT:\n\t\t\t\treturn MultiPoint.class;\n\t\t\tcase POLYGON:\n\t\t\t\treturn Polygon.class;\n\t\t\tcase MULTIPOLYGON:\n\t\t\t\treturn MultiPolygon.class;\n\t\t\tcase RASTER:\n\t\t\t\treturn null;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalStateException(\"Don't know how to handle layer type \" + layerType);\n\t\t}\n\t}", "protected static void error(\n final HttpServletResponse httpServletResponse, final String message, final HttpStatus code) {\n try {\n httpServletResponse.setContentType(\"text/plain\");\n httpServletResponse.setStatus(code.value());\n setNoCache(httpServletResponse);\n try (PrintWriter out = httpServletResponse.getWriter()) {\n out.println(\"Error while processing request:\");\n out.println(message);\n }\n\n LOGGER.error(\"Error while processing request: {}\", message);\n } catch (IOException ex) {\n throw ExceptionUtils.getRuntimeException(ex);\n }\n }", "private TrackSourceSlot findTrackSourceSlot() {\n TrackSourceSlot result = TRACK_SOURCE_SLOT_MAP.get(packetBytes[41]);\n if (result == null) {\n return TrackSourceSlot.UNKNOWN;\n }\n return result;\n }", "public static List<DockerImage> getImagesByBuildId(int buildInfoId) {\n List<DockerImage> list = new ArrayList<DockerImage>();\n Iterator<DockerImage> it = images.iterator();\n while (it.hasNext()) {\n DockerImage image = it.next();\n if (image.getBuildInfoId() == buildInfoId && image.hasManifest()) {\n list.add(image);\n }\n }\n return list;\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<DiscordianDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<DiscordianDate>) super.zonedDateTime(temporal);\n }", "public void createTag(final String tagUrl, final String commitMessage)\n throws IOException, InterruptedException {\n build.getWorkspace()\n .act(new SVNCreateTagCallable(tagUrl, commitMessage, getLocation(), getSvnAuthenticationProvider(build),\n buildListener));\n }", "protected NodeData createBlockStyle()\n {\n NodeData ret = CSSFactory.createNodeData();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"display\", tf.createIdent(\"block\")));\n return ret;\n }", "@Override\n\tpublic EmbeddedBrowser get() {\n\t\tLOGGER.debug(\"Setting up a Browser\");\n\t\t// Retrieve the config values used\n\t\tImmutableSortedSet<String> filterAttributes =\n\t\t\t\tconfiguration.getCrawlRules().getPreCrawlConfig().getFilterAttributeNames();\n\t\tlong crawlWaitReload = configuration.getCrawlRules().getWaitAfterReloadUrl();\n\t\tlong crawlWaitEvent = configuration.getCrawlRules().getWaitAfterEvent();\n\n\t\t// Determine the requested browser type\n\t\tEmbeddedBrowser browser = null;\n\t\tEmbeddedBrowser.BrowserType browserType =\n\t\t\t\tconfiguration.getBrowserConfig().getBrowserType();\n\t\ttry {\n\t\t\tswitch (browserType) {\n\t\t\t\tcase CHROME:\n\t\t\t\t\tbrowser = newChromeBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\tfalse);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CHROME_HEADLESS:\n\t\t\t\t\tbrowser = newChromeBrowser(filterAttributes, crawlWaitReload,\n\t\t\t\t\t\t\tcrawlWaitEvent, true);\n\t\t\t\t\tbreak;\n\t\t\t\tcase FIREFOX:\n\t\t\t\t\tbrowser = newFirefoxBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\tfalse);\n\t\t\t\t\tbreak;\n\t\t\t\tcase FIREFOX_HEADLESS:\n\t\t\t\t\tbrowser = newFirefoxBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\ttrue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase REMOTE:\n\t\t\t\t\tbrowser = WebDriverBackedEmbeddedBrowser.withRemoteDriver(\n\t\t\t\t\t\t\tconfiguration.getBrowserConfig().getRemoteHubUrl(), filterAttributes,\n\t\t\t\t\t\t\tcrawlWaitEvent, crawlWaitReload);\n\t\t\t\t\tbreak;\n\t\t\t\tcase PHANTOMJS:\n\t\t\t\t\tbrowser =\n\t\t\t\t\t\t\tnewPhantomJSDriver(filterAttributes, crawlWaitReload, crawlWaitEvent);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalStateException(\"Unrecognized browser type \"\n\t\t\t\t\t\t\t+ configuration.getBrowserConfig().getBrowserType());\n\t\t\t}\n\t\t} catch (IllegalStateException e) {\n\t\t\tLOGGER.error(\"Crawling with {} failed: \" + e.getMessage(), browserType.toString());\n\t\t\tthrow e;\n\t\t}\n\n\t\t/* for Retina display. */\n\t\tif (browser instanceof WebDriverBackedEmbeddedBrowser) {\n\t\t\tint pixelDensity =\n\t\t\t\t\tthis.configuration.getBrowserConfig().getBrowserOptions().getPixelDensity();\n\t\t\tif (pixelDensity != -1)\n\t\t\t\t((WebDriverBackedEmbeddedBrowser) browser).setPixelDensity(pixelDensity);\n\t\t}\n\n\t\tplugins.runOnBrowserCreatedPlugins(browser);\n\t\treturn browser;\n\t}" ]
Remove contents from the deployment and attach a "transformed" slave operation to the operation context. @param context the operation context @param operation the original operation @param contentRepository the content repository @return the hash of the uploaded deployment content @throws IOException @throws OperationFailedException
[ "public static byte[] removeContentFromExplodedAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws OperationFailedException, ExplodedContentException {\n final Resource deploymentResource = context.readResource(PathAddress.EMPTY_ADDRESS);\n ModelNode contentItemNode = getContentItem(deploymentResource);\n final byte[] oldHash = CONTENT_HASH.resolveModelAttribute(context, contentItemNode).asBytes();\n final List<String> paths = REMOVED_PATHS.unwrap(context, operation);\n final byte[] hash = contentRepository.removeContentFromExploded(oldHash, paths);\n\n // Clear the contents and update with the hash\n final ModelNode slave = operation.clone();\n slave.get(CONTENT).setEmptyList().add().get(HASH).set(hash);\n slave.get(CONTENT).add().get(ARCHIVE).set(false);\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 }" ]
[ "@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 }", "protected void closeServerSocket() {\n // Close server socket, we do not accept new requests anymore.\n // This also terminates the server thread if blocking on socket.accept.\n if (null != serverSocket) {\n try {\n if (!serverSocket.isClosed()) {\n serverSocket.close();\n if (log.isTraceEnabled()) {\n log.trace(\"Closed server socket \" + serverSocket + \"/ref=\"\n + Integer.toHexString(System.identityHashCode(serverSocket))\n + \" for \" + getName());\n }\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Failed to successfully quit server \" + getName(), e);\n }\n }\n }", "public static <E> Collection<E> collectify(ObjectMapper mapper, Object source, Class<? extends Collection> targetCollectionType, Class<E> targetElementType) {\n CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(targetCollectionType, targetElementType);\n return objectify(mapper, convertToCollection(source), collectionType);\n }", "public boolean isInBounds(int row, int col) {\n return row >= 0 && col >= 0 && row < mat.getNumRows() && col < mat.getNumCols();\n }", "public void unlink(Object obj, ObjectReferenceDescriptor ord, boolean insert)\r\n {\r\n linkOrUnlink(false, obj, ord, insert);\r\n }", "public static base_response add(nitro_service client, clusternodegroup resource) throws Exception {\n\t\tclusternodegroup addresource = new clusternodegroup();\n\t\taddresource.name = resource.name;\n\t\taddresource.strict = resource.strict;\n\t\treturn addresource.add_resource(client);\n\t}", "public boolean containsEntryFor(int maturityInMonths, int tenorInMonths, int moneynessBP) {\r\n\t\treturn entryMap.containsKey(new DataKey(maturityInMonths, tenorInMonths, moneynessBP));\r\n\t}", "public void deleteStoreDefinition(String storeName) {\n // acquire write lock\n writeLock.lock();\n\n try {\n // Check if store exists\n if(!this.storeNames.contains(storeName)) {\n throw new VoldemortException(\"Requested store to be deleted does not exist !\");\n }\n\n // Otherwise remove from the STORES directory. Note: The version\n // argument is not required here since the\n // ConfigurationStorageEngine simply ignores this.\n this.storeDefinitionsStorageEngine.delete(storeName, null);\n\n // Update the metadata cache\n this.metadataCache.remove(storeName);\n\n // Re-initialize the store definitions. This is primarily required\n // to re-create the value for key: 'stores.xml'. This is necessary\n // for backwards compatibility.\n initStoreDefinitions(null);\n } finally {\n writeLock.unlock();\n }\n }", "public synchronized ModelNode doCommand(String command) throws CommandFormatException, IOException {\n ModelNode request = cmdCtx.buildRequest(command);\n return execute(request, isSlowCommand(command)).getResponseNode();\n }" ]
Starts the animation with the given index. @param animIndex 0-based index of {@link GVRAnimator} to start; @see GVRAvatar#stop() @see #start(String)
[ "public GVRAnimator start(int animIndex)\n {\n if ((animIndex < 0) || (animIndex >= mAnimations.size()))\n {\n throw new IndexOutOfBoundsException(\"Animation index out of bounds\");\n }\n GVRAnimator anim = mAnimations.get(animIndex);\n start(anim);\n return anim;\n }" ]
[ "public static base_response clear(nitro_service client, nsconfig resource) throws Exception {\n\t\tnsconfig clearresource = new nsconfig();\n\t\tclearresource.force = resource.force;\n\t\tclearresource.level = resource.level;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}", "private void sortFileList() {\n if (this.size() > 1) {\n Collections.sort(this.fileList, new Comparator() {\n\n public final int compare(final Object o1, final Object o2) {\n final File f1 = (File) o1;\n final File f2 = (File) o2;\n final Object[] f1TimeAndCount = backupSuffixHelper\n .backupTimeAndCount(f1.getName(), baseFile);\n final Object[] f2TimeAndCount = backupSuffixHelper\n .backupTimeAndCount(f2.getName(), baseFile);\n final long f1TimeSuffix = ((Long) f1TimeAndCount[0]).longValue();\n final long f2TimeSuffix = ((Long) f2TimeAndCount[0]).longValue();\n if ((0L == f1TimeSuffix) && (0L == f2TimeSuffix)) {\n final long f1Time = f1.lastModified();\n final long f2Time = f2.lastModified();\n if (f1Time < f2Time) {\n return -1;\n }\n if (f1Time > f2Time) {\n return 1;\n }\n return 0;\n }\n if (f1TimeSuffix < f2TimeSuffix) {\n return -1;\n }\n if (f1TimeSuffix > f2TimeSuffix) {\n return 1;\n }\n final int f1Count = ((Integer) f1TimeAndCount[1]).intValue();\n final int f2Count = ((Integer) f2TimeAndCount[1]).intValue();\n if (f1Count < f2Count) {\n return -1;\n }\n if (f1Count > f2Count) {\n return 1;\n }\n if (f1Count == f2Count) {\n if (fileHelper.isCompressed(f1)) {\n return -1;\n }\n if (fileHelper.isCompressed(f2)) {\n return 1;\n }\n }\n return 0;\n }\n });\n }\n }", "private Revision uncachedHeadRevision() {\n try (RevWalk revWalk = new RevWalk(jGitRepository)) {\n final ObjectId headRevisionId = jGitRepository.resolve(R_HEADS_MASTER);\n if (headRevisionId != null) {\n final RevCommit revCommit = revWalk.parseCommit(headRevisionId);\n return CommitUtil.extractRevision(revCommit.getFullMessage());\n }\n } catch (CentralDogmaException e) {\n throw e;\n } catch (Exception e) {\n throw new StorageException(\"failed to get the current revision\", e);\n }\n\n throw new StorageException(\"failed to determine the HEAD: \" + jGitRepository.getDirectory());\n }", "public double[] getTenors(double moneyness, double maturity) {\r\n\t\tint maturityInMonths\t= (int) Math.round(maturity * 12);\r\n\t\tint[] tenorsInMonths\t= getTenors(convertMoneyness(moneyness), maturityInMonths);\r\n\t\tdouble[] tenors\t\t\t= new double[tenorsInMonths.length];\r\n\r\n\t\tfor(int index = 0; index < tenors.length; index++) {\r\n\t\t\ttenors[index] = convertTenor(maturityInMonths, tenorsInMonths[index]);\r\n\t\t}\r\n\t\treturn tenors;\r\n\t}", "@Override\n public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n EnvVars env = build.getEnvironment(listener);\n FilePath workDir = build.getModuleRoot();\n FilePath ws = build.getWorkspace();\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.error(\"Couldn't find Maven home: \" + mavenHome.getRemote());\n throw new Run.RunnerAbortedException();\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, ws, ws);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }", "protected long buildNextSequence(PersistenceBroker broker, ClassDescriptor cld, String sequenceName)\r\n throws LookupException, SQLException, PlatformException\r\n {\r\n CallableStatement cs = null;\r\n try\r\n {\r\n Connection con = broker.serviceConnectionManager().getConnection();\r\n cs = getPlatform().prepareNextValProcedureStatement(con, PROCEDURE_NAME, sequenceName);\r\n cs.executeUpdate();\r\n return cs.getLong(1);\r\n }\r\n finally\r\n {\r\n try\r\n {\r\n if (cs != null)\r\n cs.close();\r\n }\r\n catch (SQLException ignore)\r\n {\r\n // ignore it\r\n }\r\n }\r\n }", "public static int[] arrayFromStringOfIntegers(String str) throws IllegalArgumentException {\n StringTokenizer tokenizer = new StringTokenizer(str, \",\");\n int n = tokenizer.countTokens();\n int[] list = new int[n];\n for (int i = 0; i < n; i++) {\n String token = tokenizer.nextToken();\n list[i] = Integer.parseInt(token);\n }\n return list;\n }", "private void tagvalue(Options opt, Doc c) {\n\tTag tags[] = c.tags(\"tagvalue\");\n\tif (tags.length == 0)\n\t return;\n\t\n\tfor (Tag tag : tags) {\n\t String t[] = tokenize(tag.text());\n\t if (t.length != 2) {\n\t\tSystem.err.println(\"@tagvalue expects two fields: \" + tag.text());\n\t\tcontinue;\n\t }\n\t tableLine(Align.RIGHT, Font.TAG.wrap(opt, \"{\" + t[0] + \" = \" + t[1] + \"}\"));\n\t}\n }", "public Request option(String key, Object value) {\n this.options.put(key, value);\n return this;\n }" ]
Gets the currency codes, or the regular expression to select codes. @return the query for chaining.
[ "public Collection<String> getCurrencyCodes() {\n Collection<String> result = get(KEY_QUERY_CURRENCY_CODES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }" ]
[ "GVRSceneObject makeParticleMesh(float[] vertices, float[] velocities,\n float[] particleTimeStamps )\n {\n mParticleMesh = new GVRMesh(mGVRContext);\n\n //pass the particle positions as vertices, velocities as normals, and\n //spawning times as texture coordinates.\n mParticleMesh.setVertices(vertices);\n mParticleMesh.setNormals(velocities);\n mParticleMesh.setTexCoords(particleTimeStamps);\n\n particleID = new GVRShaderId(ParticleShader.class);\n material = new GVRMaterial(mGVRContext, particleID);\n\n material.setVec4(\"u_color\", mColorMultiplier.x, mColorMultiplier.y,\n mColorMultiplier.z, mColorMultiplier.w);\n material.setFloat(\"u_particle_age\", mAge);\n material.setVec3(\"u_acceleration\", mAcceleration.x, mAcceleration.y, mAcceleration.z);\n material.setFloat(\"u_particle_size\", mSize);\n material.setFloat(\"u_size_change_rate\", mParticleSizeRate);\n material.setFloat(\"u_fade\", mFadeWithAge);\n material.setFloat(\"u_noise_factor\", mNoiseFactor);\n\n GVRRenderData renderData = new GVRRenderData(mGVRContext);\n renderData.setMaterial(material);\n renderData.setMesh(mParticleMesh);\n material.setMainTexture(mTexture);\n\n GVRSceneObject meshObject = new GVRSceneObject(mGVRContext);\n meshObject.attachRenderData(renderData);\n meshObject.getRenderData().setMaterial(material);\n\n // Set the draw mode to GL_POINTS, disable writing to depth buffer, enable depth testing\n // and set the rendering order to transparent.\n // Disabling writing to depth buffer ensure that the particles blend correctly\n // and keeping the depth test on along with rendering them\n // after the geometry queue makes sure they occlude, and are occluded, correctly.\n\n meshObject.getRenderData().setDrawMode(GL_POINTS);\n meshObject.getRenderData().setDepthTest(true);\n meshObject.getRenderData().setDepthMask(false);\n meshObject.getRenderData().setRenderingOrder(GVRRenderData.GVRRenderingOrder.TRANSPARENT);\n\n return meshObject;\n }", "public static audit_stats get(nitro_service service, options option) throws Exception{\n\t\taudit_stats obj = new audit_stats();\n\t\taudit_stats[] response = (audit_stats[])obj.stat_resources(service,option);\n\t\treturn response[0];\n\t}", "@SuppressWarnings(\"unused\")\n private void setTextureNumber(int type, int number) {\n m_numTextures.put(AiTextureType.fromRawValue(type), number);\n }", "private CmsSpellcheckingRequest parseJsonRequest(JSONObject jsonRequest) {\n\n final String id = jsonRequest.optString(JSON_ID);\n\n final JSONObject params = jsonRequest.optJSONObject(JSON_PARAMS);\n\n if (null == params) {\n LOG.debug(\"Invalid JSON request: No field \\\"params\\\" defined. \");\n return null;\n }\n final JSONArray words = params.optJSONArray(JSON_WORDS);\n final String lang = params.optString(JSON_LANG, LANG_DEFAULT);\n if (null == words) {\n LOG.debug(\"Invalid JSON request: No field \\\"words\\\" defined. \");\n return null;\n }\n\n // Convert JSON array to array of type String\n final List<String> wordsToCheck = new LinkedList<String>();\n for (int i = 0; i < words.length(); i++) {\n final String word = words.opt(i).toString();\n wordsToCheck.add(word);\n\n if (Character.isUpperCase(word.codePointAt(0))) {\n wordsToCheck.add(word.toLowerCase());\n }\n }\n\n return new CmsSpellcheckingRequest(wordsToCheck.toArray(new String[wordsToCheck.size()]), lang, id);\n }", "private int cleanupSegmentsToMaintainSize(final Log log) throws IOException {\n if (logRetentionSize < 0 || log.size() < logRetentionSize) return 0;\n\n List<LogSegment> toBeDeleted = log.markDeletedWhile(new LogSegmentFilter() {\n\n long diff = log.size() - logRetentionSize;\n\n public boolean filter(LogSegment segment) {\n diff -= segment.size();\n return diff >= 0;\n }\n });\n return deleteSegments(log, toBeDeleted);\n }", "public static boolean validate(Statement stmt) {\n try {\n Connection conn = stmt.getConnection();\n if (conn == null)\n return false;\n\n if (!conn.isClosed() && conn.isValid(10))\n return true;\n\n stmt.close();\n conn.close();\n } catch (SQLException e) {\n // this may well fail. that doesn't matter. we're just making an\n // attempt to clean up, and if we can't, that's just too bad.\n }\n return false;\n }", "private Date getTime(String value) throws MPXJException\n {\n try\n {\n Number hours = m_twoDigitFormat.parse(value.substring(0, 2));\n Number minutes = m_twoDigitFormat.parse(value.substring(2, 4));\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, hours.intValue());\n cal.set(Calendar.MINUTE, minutes.intValue());\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n Date result = cal.getTime();\n DateHelper.pushCalendar(cal);\n \n return result;\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse time \" + value, ex);\n }\n }", "private PersistentResourceXMLDescription getSimpleMapperParser() {\n if (version.equals(Version.VERSION_1_0)) {\n return simpleMapperParser_1_0;\n } else if (version.equals(Version.VERSION_1_1)) {\n return simpleMapperParser_1_1;\n }\n return simpleMapperParser;\n }", "public void recordSyncOpTimeNs(SocketDestination dest, long opTimeNs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordSyncOpTimeNs(null, opTimeNs);\n recordSyncOpTimeNs(null, opTimeNs);\n } else {\n this.syncOpTimeRequestCounter.addRequest(opTimeNs);\n }\n }" ]
Throws an IllegalArgumentException when the given value is not true. @param value the value to assert if true @param message the message to display if the value is false @return the value
[ "public static Boolean assertTrue(Boolean value, String message) {\n if (!Boolean.valueOf(value))\n throw new IllegalArgumentException(message);\n return value;\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 deEndify(List<CoreLabel> tokens) {\r\n if (flags.retainEntitySubclassification) {\r\n return;\r\n }\r\n tokens = new PaddedList<CoreLabel>(tokens, new CoreLabel());\r\n int k = tokens.size();\r\n String[] newAnswers = new String[k];\r\n for (int i = 0; i < k; i++) {\r\n CoreLabel c = tokens.get(i);\r\n CoreLabel p = tokens.get(i - 1);\r\n if (c.get(AnswerAnnotation.class).length() > 1 && c.get(AnswerAnnotation.class).charAt(1) == '-') {\r\n String base = c.get(AnswerAnnotation.class).substring(2);\r\n String pBase = (p.get(AnswerAnnotation.class).length() <= 2 ? p.get(AnswerAnnotation.class) : p.get(AnswerAnnotation.class).substring(2));\r\n boolean isSecond = (base.equals(pBase));\r\n boolean isStart = (c.get(AnswerAnnotation.class).charAt(0) == 'B' || c.get(AnswerAnnotation.class).charAt(0) == 'S');\r\n if (isSecond && isStart) {\r\n newAnswers[i] = intern(\"B-\" + base);\r\n } else {\r\n newAnswers[i] = intern(\"I-\" + base);\r\n }\r\n } else {\r\n newAnswers[i] = c.get(AnswerAnnotation.class);\r\n }\r\n }\r\n for (int i = 0; i < k; i++) {\r\n CoreLabel c = tokens.get(i);\r\n c.set(AnswerAnnotation.class, newAnswers[i]);\r\n }\r\n }", "public void addSerie(AbstractColumn column, StringExpression labelExpression) {\r\n\t\tseries.add(column);\r\n\t\tseriesLabels.put(column, labelExpression);\r\n\t}", "@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/{clientUUID}\", method = RequestMethod.DELETE)\n public\n @ResponseBody\n HashMap<String, Object> deleteClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @PathVariable(\"clientUUID\") String clientUUID) throws Exception {\n logger.info(\"Attempting to remove the following client: {}\", clientUUID);\n if (clientUUID.compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) == 0)\n throw new Exception(\"Default client cannot be deleted\");\n\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n clientService.remove(profileId, clientUUID);\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"clients\", clientService.findAllClients(profileId));\n return valueHash;\n }", "@Override\n public InstalledIdentity getInstalledIdentity(String productName, String productVersion) throws PatchingException {\n final String defaultIdentityName = defaultIdentity.getIdentity().getName();\n if(productName == null) {\n productName = defaultIdentityName;\n }\n\n final File productConf = new File(installedImage.getInstallationMetadata(), productName + Constants.DOT_CONF);\n final String recordedProductVersion;\n if(!productConf.exists()) {\n recordedProductVersion = null;\n } else {\n final Properties props = loadProductConf(productConf);\n recordedProductVersion = props.getProperty(Constants.CURRENT_VERSION);\n }\n\n if(defaultIdentityName.equals(productName)) {\n if(recordedProductVersion != null && !recordedProductVersion.equals(defaultIdentity.getIdentity().getVersion())) {\n // this means the patching history indicates that the current version is different from the one specified in the server's version module,\n // which could happen in case:\n // - the last applied CP didn't include the new version module or\n // - the version module version included in the last CP didn't match the version specified in the CP's metadata, or\n // - the version module was updated from a one-off, or\n // - the patching history was edited somehow\n // In any case, here I decided to rely on the patching history.\n defaultIdentity = loadIdentity(productName, recordedProductVersion);\n }\n if(productVersion != null && !defaultIdentity.getIdentity().getVersion().equals(productVersion)) {\n throw new PatchingException(PatchLogger.ROOT_LOGGER.productVersionDidNotMatchInstalled(\n productName, productVersion, defaultIdentity.getIdentity().getVersion()));\n }\n return defaultIdentity;\n }\n\n if(recordedProductVersion != null && !Constants.UNKNOWN.equals(recordedProductVersion)) {\n if(productVersion != null) {\n if (!productVersion.equals(recordedProductVersion)) {\n throw new PatchingException(PatchLogger.ROOT_LOGGER.productVersionDidNotMatchInstalled(productName, productVersion, recordedProductVersion));\n }\n } else {\n productVersion = recordedProductVersion;\n }\n }\n\n return loadIdentity(productName, productVersion);\n }", "public static boolean isArrayOfUnboundedTypeVariablesOrObjects(Type[] types) {\n for (Type type : types) {\n if (Object.class.equals(type)) {\n continue;\n }\n if (type instanceof TypeVariable<?>) {\n Type[] bounds = ((TypeVariable<?>) type).getBounds();\n if (bounds == null || bounds.length == 0 || (bounds.length == 1 && Object.class.equals(bounds[0]))) {\n continue;\n }\n }\n return false;\n }\n return true;\n }", "private void copyResources(File outputDirectory) throws IOException\n {\n copyClasspathResource(outputDirectory, \"reportng.css\", \"reportng.css\");\n copyClasspathResource(outputDirectory, \"reportng.js\", \"reportng.js\");\n // If there is a custom stylesheet, copy that.\n File customStylesheet = META.getStylesheetPath();\n\n if (customStylesheet != null)\n {\n if (customStylesheet.exists())\n {\n copyFile(outputDirectory, customStylesheet, CUSTOM_STYLE_FILE);\n }\n else\n {\n // If not found, try to read the file as a resource on the classpath\n // useful when reportng is called by a jarred up library\n InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream(customStylesheet.getPath());\n if (stream != null)\n {\n copyStream(outputDirectory, stream, CUSTOM_STYLE_FILE);\n }\n }\n }\n }", "@Override\n public PaxDate date(int prolepticYear, int month, int dayOfMonth) {\n return PaxDate.of(prolepticYear, month, dayOfMonth);\n }", "@Nullable\n public ByteIterable get2(@NotNull final Transaction txn, @NotNull final ByteIterable second) {\n return this.second.get(txn, second);\n }" ]
Use this API to update systemuser resources.
[ "public static base_responses update(nitro_service client, systemuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsystemuser updateresources[] = new systemuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new systemuser();\n\t\t\t\tupdateresources[i].username = resources[i].username;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].externalauth = resources[i].externalauth;\n\t\t\t\tupdateresources[i].promptstring = resources[i].promptstring;\n\t\t\t\tupdateresources[i].timeout = resources[i].timeout;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}" ]
[ "private void logShort(CharSequence message, boolean trim) throws IOException {\n int length = message.length();\n if (trim) {\n while (length > 0 && Character.isWhitespace(message.charAt(length - 1))) {\n length--;\n }\n }\n\n char [] chars = new char [length + 1];\n for (int i = 0; i < length; i++) {\n chars[i] = message.charAt(i);\n }\n chars[length] = '\\n';\n\n output.write(chars);\n }", "@RequestMapping(value = \"group\", method = RequestMethod.GET)\n public String newGroupGet(Model model) {\n model.addAttribute(\"groups\",\n pathOverrideService.findAllGroups());\n return \"groups\";\n }", "public 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 }", "public static final String getString(InputStream is) throws IOException\n {\n int type = is.read();\n if (type != 1)\n {\n throw new IllegalArgumentException(\"Unexpected string format\");\n }\n\n Charset charset = CharsetHelper.UTF8;\n \n int length = is.read();\n if (length == 0xFF)\n {\n length = getShort(is);\n if (length == 0xFFFE)\n {\n charset = CharsetHelper.UTF16LE;\n length = (is.read() * 2);\n }\n }\n\n String result;\n if (length == 0)\n {\n result = null;\n }\n else\n {\n byte[] stringData = new byte[length]; \n is.read(stringData);\n result = new String(stringData, charset);\n }\n return result;\n }", "public static String buildDynamicCapabilityName(String baseName, String ... dynamicNameElement) {\n assert baseName != null;\n assert dynamicNameElement != null;\n assert dynamicNameElement.length > 0;\n StringBuilder sb = new StringBuilder(baseName);\n for (String part:dynamicNameElement){\n sb.append(\".\").append(part);\n }\n return sb.toString();\n }", "public ItemRequest<Task> removeFollowers(String task) {\n \n String path = String.format(\"/tasks/%s/removeFollowers\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "public void appointTempoMaster(int deviceNumber) throws IOException {\n final DeviceUpdate update = getLatestStatusFor(deviceNumber);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + deviceNumber + \" not found on network.\");\n }\n appointTempoMaster(update);\n }", "public ThumborUrlBuilder resize(int width, int height) {\n if (width < 0 && width != ORIGINAL_SIZE) {\n throw new IllegalArgumentException(\"Width must be a positive number.\");\n }\n if (height < 0 && height != ORIGINAL_SIZE) {\n throw new IllegalArgumentException(\"Height must be a positive number.\");\n }\n if (width == 0 && height == 0) {\n throw new IllegalArgumentException(\"Both width and height must not be zero.\");\n }\n hasResize = true;\n resizeWidth = width;\n resizeHeight = height;\n return this;\n }", "public synchronized void addNodesToWorkerList(List<Integer> nodeIds) {\n // Bookkeeping for nodes that will be involved in the next task\n nodeIdsWithWork.addAll(nodeIds);\n logger.info(\"Node IDs with work: \" + nodeIdsWithWork + \" Newly added nodes \" + nodeIds);\n }" ]
Lookup a PortComponentMetaData by wsdl-port local part @param name - the wsdl-port local part @return PortComponentMetaData if found, null otherwise
[ "public PortComponentMetaData getPortComponentByWsdlPort(String name)\n {\n ArrayList<String> pcNames = new ArrayList<String>();\n for (PortComponentMetaData pc : portComponents)\n {\n String wsdlPortName = pc.getWsdlPort().getLocalPart();\n if (wsdlPortName.equals(name))\n return pc;\n\n pcNames.add(wsdlPortName);\n }\n\n Loggers.METADATA_LOGGER.cannotGetPortComponentName(name, pcNames);\n return null;\n }" ]
[ "public static Command newInsert(Object object,\n String outIdentifier) {\n return getCommandFactoryProvider().newInsert( object,\n outIdentifier );\n }", "public static <T> T[] concat(T[] first, T... second) {\n\t\tint firstLength = first.length;\n\t\tint secondLength = second.length;\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT[] result = (T[]) Array.newInstance( first.getClass().getComponentType(), firstLength + secondLength );\n\t\tSystem.arraycopy( first, 0, result, 0, firstLength );\n\t\tSystem.arraycopy( second, 0, result, firstLength, secondLength );\n\n\t\treturn result;\n\t}", "public void fireEvent(Type eventType, Object event, Annotation... qualifiers) {\n final EventMetadata metadata = new EventMetadataImpl(eventType, null, qualifiers);\n notifier.fireEvent(eventType, event, metadata, qualifiers);\n }", "String deriveGroupIdFromPackages(ProjectModel projectModel)\n {\n Map<Object, Long> pkgsMap = new HashMap<>();\n Set<String> pkgs = new HashSet<>(1000);\n GraphTraversal<Vertex, Vertex> pipeline = new GraphTraversalSource(graphContext.getGraph()).V(projectModel);\n\n\n pkgsMap = pipeline.out(ProjectModel.PROJECT_MODEL_TO_FILE)\n .has(WindupVertexFrame.TYPE_PROP, new P(new BiPredicate<String, String>() {\n @Override\n public boolean test(String o, String o2) {\n return o.contains(o2);\n }\n },\n GraphTypeManager.getTypeValue(JavaClassFileModel.class)))\n .hasKey(JavaClassFileModel.PROPERTY_PACKAGE_NAME)\n .groupCount()\n .by(v -> upToThirdDot(graphContext, (Vertex)v)).toList().get(0);\n\n Map.Entry<Object, Long> biggest = null;\n for (Map.Entry<Object, Long> entry : pkgsMap.entrySet())\n {\n if (biggest == null || biggest.getValue() < entry.getValue())\n biggest = entry;\n }\n // More than a half is of this package.\n if (biggest != null && biggest.getValue() > pkgsMap.size() / 2)\n return biggest.getKey().toString();\n\n return null;\n }", "public boolean removeHandlerFor(final GVRSceneObject sceneObject) {\n sceneObject.detachComponent(GVRCollider.getComponentType());\n return null != touchHandlers.remove(sceneObject);\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 }", "public void set(Object receiver, String fieldName, /* @Nullable */ Object value) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {\n\t\tPreconditions.checkNotNull(receiver,\"receiver\");\n\t\tPreconditions.checkNotNull(fieldName,\"fieldName\");\n\t\tClass<? extends Object> clazz = receiver.getClass();\n\t\tField f = getDeclaredField(clazz, fieldName);\n\t\tif (!f.isAccessible())\n\t\t\tf.setAccessible(true);\n\t\tf.set(receiver, value);\n\t}", "public void login(Object userIdentifier) {\n session().put(config().sessionKeyUsername(), userIdentifier);\n app().eventBus().trigger(new LoginEvent(userIdentifier.toString()));\n }", "public static int getProfileIdFromPathID(int path_id) throws Exception {\n return (Integer) SQLService.getInstance().getFromTable(Constants.GENERIC_PROFILE_ID, Constants.GENERIC_ID, path_id, Constants.DB_TABLE_PATH);\n }" ]
The Cost Variance field shows the difference between the baseline cost and total cost for a task. The total cost is the current estimate of costs based on actual costs and remaining costs. @return amount
[ "public Number getCostVariance()\n {\n Number variance = (Number) getCachedValue(TaskField.COST_VARIANCE);\n if (variance == null)\n {\n Number cost = getCost();\n Number baselineCost = getBaselineCost();\n if (cost != null && baselineCost != null)\n {\n variance = NumberHelper.getDouble(cost.doubleValue() - baselineCost.doubleValue());\n set(TaskField.COST_VARIANCE, variance);\n }\n }\n return (variance);\n }" ]
[ "private static String wordShapeChris2Long(String s, boolean omitIfInBoundary, int len, Collection<String> knownLCWords) {\r\n final char[] beginChars = new char[BOUNDARY_SIZE];\r\n final char[] endChars = new char[BOUNDARY_SIZE];\r\n int beginUpto = 0;\r\n int endUpto = 0;\r\n final Set<Character> seenSet = new TreeSet<Character>(); // TreeSet guarantees stable ordering; has no size parameter\r\n\r\n boolean nonLetters = false;\r\n\r\n for (int i = 0; i < len; i++) {\r\n int iIncr = 0;\r\n char c = s.charAt(i);\r\n char m = c;\r\n if (Character.isDigit(c)) {\r\n m = 'd';\r\n } else if (Character.isLowerCase(c)) {\r\n m = 'x';\r\n } else if (Character.isUpperCase(c) || Character.isTitleCase(c)) {\r\n m = 'X';\r\n }\r\n for (String gr : greek) {\r\n if (s.startsWith(gr, i)) {\r\n m = 'g';\r\n //System.out.println(s + \" :: \" + s.substring(i+1));\r\n iIncr = gr.length() - 1;\r\n break;\r\n }\r\n }\r\n if (m != 'x' && m != 'X') {\r\n nonLetters = true;\r\n }\r\n\r\n if (i < BOUNDARY_SIZE) {\r\n beginChars[beginUpto++] = m;\r\n } else if (i < len - BOUNDARY_SIZE) {\r\n seenSet.add(Character.valueOf(m));\r\n } else {\r\n endChars[endUpto++] = m;\r\n }\r\n i += iIncr;\r\n // System.out.println(\"Position skips to \" + i);\r\n }\r\n\r\n // Calculate size. This may be an upperbound, but is often correct\r\n int sbSize = beginUpto + endUpto + seenSet.size();\r\n if (knownLCWords != null) { sbSize++; }\r\n final StringBuilder sb = new StringBuilder(sbSize);\r\n // put in the beginning chars\r\n sb.append(beginChars, 0, beginUpto);\r\n // put in the stored ones sorted\r\n if (omitIfInBoundary) {\r\n for (Character chr : seenSet) {\r\n char ch = chr.charValue();\r\n boolean insert = true;\r\n for (int i = 0; i < beginUpto; i++) {\r\n if (beginChars[i] == ch) {\r\n insert = false;\r\n break;\r\n }\r\n }\r\n for (int i = 0; i < endUpto; i++) {\r\n if (endChars[i] == ch) {\r\n insert = false;\r\n break;\r\n }\r\n }\r\n if (insert) {\r\n sb.append(ch);\r\n }\r\n }\r\n } else {\r\n for (Character chr : seenSet) {\r\n sb.append(chr.charValue());\r\n }\r\n }\r\n // and add end ones\r\n sb.append(endChars, 0, endUpto);\r\n\r\n if (knownLCWords != null) {\r\n if (!nonLetters && knownLCWords.contains(s.toLowerCase())) {\r\n sb.append('k');\r\n }\r\n }\r\n // System.out.println(s + \" became \" + sb);\r\n return sb.toString();\r\n }", "private static ModelNode createOperation(final ModelNode operationToValidate) {\n PathAddress pa = PathAddress.pathAddress(operationToValidate.require(OP_ADDR));\n PathAddress validationAddress = pa.subAddress(0, pa.size() - 1);\n\n return Util.getEmptyOperation(\"validate-cache\", validationAddress.toModelNode());\n }", "public int scrollToNextPage() {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToNextPage getCurrentPage() = %d currentIndex = %d\",\n getCurrentPage(), mCurrentItemIndex);\n\n if (mSupportScrollByPage) {\n scrollToPage(getCurrentPage() + 1);\n } else {\n Log.w(TAG, \"Pagination is not enabled!\");\n }\n\n return mCurrentItemIndex;\n\t}", "public static DMatrixRMaj triangularUpper(int dimen , int hessenberg , double min , double max , Random rand )\n {\n if( hessenberg < 0 )\n throw new RuntimeException(\"hessenberg must be more than or equal to 0\");\n\n double range = max-min;\n\n DMatrixRMaj A = new DMatrixRMaj(dimen,dimen);\n\n for( int i = 0; i < dimen; i++ ) {\n int start = i <= hessenberg ? 0 : i-hessenberg;\n\n for( int j = start; j < dimen; j++ ) {\n A.set(i,j, rand.nextDouble()*range+min);\n }\n\n }\n\n return A;\n }", "public static double JensenShannonDivergence(double[] p, double[] q) {\n double[] m = new double[p.length];\n for (int i = 0; i < m.length; i++) {\n m[i] = (p[i] + q[i]) / 2;\n }\n\n return (KullbackLeiblerDivergence(p, m) + KullbackLeiblerDivergence(q, m)) / 2;\n }", "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 }", "private void updateCursorsInScene(GVRScene scene, boolean add) {\n synchronized (mCursors) {\n for (Cursor cursor : mCursors) {\n if (cursor.isActive()) {\n if (add) {\n addCursorToScene(cursor);\n } else {\n removeCursorFromScene(cursor);\n }\n }\n }\n }\n }", "public static base_responses delete(nitro_service client, String certkey[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (certkey != null && certkey.length > 0) {\n\t\t\tsslcertkey deleteresources[] = new sslcertkey[certkey.length];\n\t\t\tfor (int i=0;i<certkey.length;i++){\n\t\t\t\tdeleteresources[i] = new sslcertkey();\n\t\t\t\tdeleteresources[i].certkey = certkey[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "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 }" ]